language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_types10.py | {
"start": 471,
"end": 1066
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("types10.xlsx")
def test_write_user_type(self):
"""Test writing numbers as text."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.add_write_handler(uuid.UUID, write_uuid)
my_uuid = uuid.uuid3(uuid.NAMESPACE_DNS, "python.org")
worksheet.write("A1", my_uuid)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | weaviate__weaviate-python-client | integration/test_collection_batch.py | {
"start": 809,
"end": 1283
} | class ____:
array: list
def numpy(self) -> "MockNumpyTorch":
return MockNumpyTorch(self.array)
UUID1 = uuid.UUID("806827e0-2b31-43ca-9269-24fa95a221f9")
UUID2 = uuid.UUID("8ad0d33c-8db1-4437-87f3-72161ca2a51a")
UUID3 = uuid.UUID("83d99755-9deb-4b16-8431-d1dff4ab0a75")
UUID4 = uuid.UUID("385c992b-452a-4f71-a5d9-b161f51b540d")
UUID5 = uuid.UUID("0a4d16b3-c418-40d3-a6b7-51f87c7a603b")
UUID6 = uuid.UUID("c8a201b6-fdd2-48d1-a8ee-289a540b1b4b")
| MockTensorFlow |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 4650,
"end": 5901
} | class ____(DjangoResetTestCase):
def setUp(self):
super().setUp()
StandardFactory.reset_sequence()
def test_pk_first(self):
std = StandardFactory.build()
self.assertEqual('foo0', std.foo)
def test_pk_many(self):
std1 = StandardFactory.build()
std2 = StandardFactory.build()
self.assertEqual('foo0', std1.foo)
self.assertEqual('foo1', std2.foo)
def test_pk_creation(self):
self.reset_database_sequences(StandardFactory._meta.model)
std1 = StandardFactory.create()
self.assertEqual('foo0', std1.foo)
self.assertEqual(1, std1.pk)
StandardFactory.reset_sequence()
std2 = StandardFactory.create()
self.assertEqual('foo0', std2.foo)
self.assertEqual(2, std2.pk)
def test_pk_force_value(self):
std1 = StandardFactory.create(pk=10)
self.assertEqual('foo0', std1.foo) # sequence is unrelated to pk
self.assertEqual(10, std1.pk)
self.reset_database_sequences(StandardFactory._meta.model)
StandardFactory.reset_sequence()
std2 = StandardFactory.create()
self.assertEqual('foo0', std2.foo)
self.assertEqual(11, std2.pk)
| DjangoPkSequenceTestCase |
python | facebook__pyre-check | tools/generate_taint_models/get_undecorated_sources.py | {
"start": 623,
"end": 2909
} | class ____(ModelGenerator[CallableModel]):
"""
This generator allows you to filter the results of `source_generator` by callables
that do not implement the specified decorator annotations.
For instance, if you're interested in getting all REST endpoints that don't
implement a @sanitized_data decorator, you could use this generator via the
following pattern:
...
generators["get_unsanitized_REST_endpoints"] = UndecoratedSourceGenerator(
source_generator = RESTApiSourceGenerator(django_urls),
decorators_to_filter = [
DecoratorAnnotationSpecification(decorator="sanitized_data"),
],
)
"""
def __init__(
self,
source_generator: ModelGenerator[CallableModel],
root: str,
decorators_to_filter: List[DecoratorAnnotationSpecification],
) -> None:
self.source_generator = source_generator
self.root = root
self.decorators_to_filter = decorators_to_filter
def gather_functions_to_model(self) -> Iterable[Callable[..., object]]:
return []
def compute_models(
self, functions_to_model: Iterable[Callable[..., object]]
) -> Set[CallableModel]:
unfiltered_models = self.source_generator.generate_models()
modules_to_filter = set()
for callable_model in unfiltered_models:
if inspect.ismethod(callable_model.callable_object):
continue
module_name = getattr(callable_model.callable_object, "__module__", None)
if module_name is not None:
modules_to_filter.add(module_name)
paths = [
import_module(module_name).__file__ for module_name in modules_to_filter
]
models_to_filter = AnnotatedFreeFunctionWithDecoratorGenerator(
root=self.root,
annotation_specifications=self.decorators_to_filter,
# pyre-fixme[6]: For 3rd param expected `Optional[List[str]]` but got
# `List[Optional[str]]`.
paths=paths,
).generate_models()
# pyre-fixme[58]: `-` is not supported for operand types
# `Set[CallableModel]` and `Set[FunctionDefinitionModel]`.
return set(unfiltered_models) - set(models_to_filter)
| UndecoratedSourceGenerator |
python | PyCQA__pylint | tests/functional/u/unspecified_encoding_py38.py | {
"start": 3215,
"end": 3925
} | class ____:
"""Class that returns mode strings"""
mode = "wb"
def __init__(self):
self.my_mode = "wb"
@staticmethod
def my_mode_method():
"""Returns a pre-defined mode"""
return "wb"
@staticmethod
def my_mode_method_returner(mode: str) -> str:
"""Returns the supplied mode"""
return mode
open(FILENAME, mode=IOData.mode)
open(FILENAME, mode=IOData().my_mode)
open(FILENAME, mode=IOData().my_mode_method())
open(FILENAME, mode=IOData().my_mode_method_returner("wb"))
# Invalid value but shouldn't crash, reported in https://github.com/pylint-dev/pylint/issues/5321
open(FILENAME, mode=IOData)
# -- Dataclasses
@dataclasses.dataclass
| IOData |
python | jina-ai__jina | jina/serve/runtimes/monitoring.py | {
"start": 1057,
"end": 9266
} | class ____:
"""
Mixin for the request handling monitoring
:param metrics_registry: optional metrics registry for prometheus used if we need to expose metrics from the executor or from the data request handler
:param runtime_name: optional runtime_name that will be registered during monitoring
"""
def __init__(
self,
metrics_registry: Optional['CollectorRegistry'] = None,
meter: Optional['Meter'] = None,
runtime_name: Optional[str] = None,
):
self._request_init_time = {} if metrics_registry else None
self._meter_request_init_time = {} if meter else None
if metrics_registry:
with ImportExtensions(
required=True,
help_text='You need to install the `prometheus_client` to use the montitoring functionality of jina',
):
from prometheus_client import Counter, Gauge, Summary
from jina.serve.monitoring import _SummaryDeprecated
self._receiving_request_metrics = Summary(
'receiving_request_seconds',
'Time spent processing successful request',
registry=metrics_registry,
namespace='jina',
labelnames=('runtime_name',),
).labels(runtime_name)
self._pending_requests_metrics = Gauge(
'number_of_pending_requests',
'Number of pending requests',
registry=metrics_registry,
namespace='jina',
labelnames=('runtime_name',),
).labels(runtime_name)
self._failed_requests_metrics = Counter(
'failed_requests',
'Number of failed requests',
registry=metrics_registry,
namespace='jina',
labelnames=('runtime_name',),
).labels(runtime_name)
self._successful_requests_metrics = Counter(
'successful_requests',
'Number of successful requests',
registry=metrics_registry,
namespace='jina',
labelnames=('runtime_name',),
).labels(runtime_name)
self._request_size_metrics = _SummaryDeprecated(
old_name='request_size_bytes',
name='received_request_bytes',
documentation='The size in bytes of the request returned to the client',
namespace='jina',
labelnames=('runtime_name',),
registry=metrics_registry,
).labels(runtime_name)
self._sent_response_bytes = Summary(
'sent_response_bytes',
'The size in bytes of the request returned to the client',
namespace='jina',
labelnames=('runtime_name',),
registry=metrics_registry,
).labels(runtime_name)
else:
self._receiving_request_metrics = None
self._pending_requests_metrics = None
self._failed_requests_metrics = None
self._successful_requests_metrics = None
self._request_size_metrics = None
self._sent_response_bytes = None
if meter:
self._receiving_request_histogram = meter.create_histogram(
name='jina_receiving_request_seconds',
description='Time spent processing successful request',
)
self._pending_requests_up_down_counter = meter.create_up_down_counter(
name='jina_number_of_pending_requests',
description='Number of pending requests',
)
self._failed_requests_counter = meter.create_counter(
name='jina_failed_requests',
description='Number of failed requests',
)
self._successful_requests_counter = meter.create_counter(
name='jina_successful_requests',
description='Number of successful requests',
)
self._request_size_histogram = meter.create_histogram(
name='jina_received_request_bytes',
description='The size in bytes of the request returned to the client',
)
self._sent_response_bytes_histogram = meter.create_histogram(
name='jina_sent_response_bytes',
description='The size in bytes of the request returned to the client',
)
else:
self._receiving_request_histogram = None
self._pending_requests_up_down_counter = None
self._failed_requests_counter = None
self._successful_requests_counter = None
self._request_size_histogram = None
self._sent_response_bytes_histogram = None
self._metric_labels = {'runtime_name': runtime_name}
def _update_start_request_metrics(self, request: 'Request'):
if self._request_size_metrics:
self._request_size_metrics.observe(request.nbytes)
if self._request_size_histogram:
self._request_size_histogram.record(
request.nbytes, attributes=self._metric_labels
)
if self._receiving_request_metrics:
self._request_init_time[request.request_id] = time.time()
if self._receiving_request_histogram:
self._meter_request_init_time[request.request_id] = time.time()
if self._pending_requests_metrics:
self._pending_requests_metrics.inc()
if self._pending_requests_up_down_counter:
self._pending_requests_up_down_counter.add(
1, attributes=self._metric_labels
)
def _update_end_successful_requests_metrics(self, result: 'Request'):
if (
self._receiving_request_metrics
): # this one should only be observed when the metrics is succesful
init_time = self._request_init_time.pop(
result.request_id
) # need to pop otherwise it stays in memory forever
self._receiving_request_metrics.observe(time.time() - init_time)
if (
self._receiving_request_histogram
): # this one should only be observed when the metrics is succesful
init_time = self._meter_request_init_time.pop(
result.request_id
) # need to pop otherwise it stays in memory forever
self._receiving_request_histogram.record(
time.time() - init_time, attributes=self._metric_labels
)
if self._pending_requests_metrics:
self._pending_requests_metrics.dec()
if self._pending_requests_up_down_counter:
self._pending_requests_up_down_counter.add(
-1, attributes=self._metric_labels
)
if self._successful_requests_metrics:
self._successful_requests_metrics.inc()
if self._successful_requests_counter:
self._successful_requests_counter.add(1, attributes=self._metric_labels)
if self._sent_response_bytes:
self._sent_response_bytes.observe(result.nbytes)
if self._sent_response_bytes_histogram:
self._sent_response_bytes_histogram.record(
result.nbytes, attributes=self._metric_labels
)
def _update_end_failed_requests_metrics(self):
if self._pending_requests_metrics:
self._pending_requests_metrics.dec()
if self._pending_requests_up_down_counter:
self._pending_requests_up_down_counter.add(
-1, attributes=self._metric_labels
)
if self._failed_requests_metrics:
self._failed_requests_metrics.inc()
if self._failed_requests_counter:
self._failed_requests_counter.add(1, attributes=self._metric_labels)
def _update_end_request_metrics(self, result: 'Request'):
if result.status.code != jina_pb2.StatusProto.ERROR:
self._update_end_successful_requests_metrics(result)
else:
self._update_end_failed_requests_metrics()
| MonitoringRequestMixin |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py | {
"start": 579,
"end": 1580
} | class ____(CPythonPosix, CPython3):
@classmethod
def can_describe(cls, interpreter):
return (
is_mac_os_framework(interpreter) is False
and is_macos_brew(interpreter) is False
and super().can_describe(interpreter)
)
def env_patch_text(self):
text = super().env_patch_text()
if self.pyvenv_launch_patch_active(self.interpreter):
text += dedent(
"""
# for https://github.com/python/cpython/pull/9516, see https://github.com/pypa/virtualenv/issues/1704
import os
if "__PYVENV_LAUNCHER__" in os.environ:
del os.environ["__PYVENV_LAUNCHER__"]
""",
)
return text
@classmethod
def pyvenv_launch_patch_active(cls, interpreter):
ver = interpreter.version_info
return interpreter.platform == "darwin" and ((3, 7, 8) > ver >= (3, 7) or (3, 8, 3) > ver >= (3, 8))
| CPython3Posix |
python | numpy__numpy | numpy/_core/tests/test_dtype.py | {
"start": 48209,
"end": 48953
} | class ____:
def test_descr_has_trailing_void(self):
# see gh-6359
dtype = np.dtype({
'names': ['A', 'B'],
'formats': ['f4', 'f4'],
'offsets': [0, 8],
'itemsize': 16})
new_dtype = np.dtype(dtype.descr)
assert_equal(new_dtype.itemsize, 16)
def test_name_dtype_subclass(self):
# Ticket #4357
class user_def_subcls(np.void):
pass
assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls')
def test_zero_stride(self):
arr = np.ones(1, dtype="i8")
arr = np.broadcast_to(arr, 10)
assert arr.strides == (0,)
with pytest.raises(ValueError):
arr.dtype = "i1"
| TestDtypeAttributes |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_pprint.py | {
"start": 5865,
"end": 27630
} | class ____(BaseEstimator):
def __init__(
self,
missing_values=np.nan,
strategy="mean",
fill_value=None,
verbose=0,
copy=True,
):
self.missing_values = missing_values
self.strategy = strategy
self.fill_value = fill_value
self.verbose = verbose
self.copy = copy
@config_context(print_changed_only=False)
def test_basic():
# Basic pprint test
lr = LogisticRegression()
expected = """
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=0, max_iter=100,
multi_class='warn', n_jobs=None, random_state=None,
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__() == expected
def test_changed_only():
# Make sure the changed_only param is correctly used when True (default)
lr = LogisticRegression(C=99)
expected = """LogisticRegression(C=99)"""
assert lr.__repr__() == expected
# Check with a repr that doesn't fit on a single line
lr = LogisticRegression(
C=99, class_weight=0.4, fit_intercept=False, tol=1234, verbose=True
)
expected = """
LogisticRegression(C=99, class_weight=0.4, fit_intercept=False, tol=1234,
verbose=True)"""
expected = expected[1:] # remove first \n
assert lr.__repr__() == expected
imputer = SimpleImputer(missing_values=0)
expected = """SimpleImputer(missing_values=0)"""
assert imputer.__repr__() == expected
# Defaults to np.nan, trying with float('NaN')
imputer = SimpleImputer(missing_values=float("NaN"))
expected = """SimpleImputer()"""
assert imputer.__repr__() == expected
# make sure array parameters don't throw error (see #13583)
repr(LogisticRegressionCV(Cs=np.array([0.1, 1]), use_legacy_attributes=False))
@config_context(print_changed_only=False)
def test_pipeline():
# Render a pipeline object
pipeline = make_pipeline(StandardScaler(), LogisticRegression(C=999))
expected = """
Pipeline(memory=None,
steps=[('standardscaler',
StandardScaler(copy=True, with_mean=True, with_std=True)),
('logisticregression',
LogisticRegression(C=999, class_weight=None, dual=False,
fit_intercept=True, intercept_scaling=1,
l1_ratio=0, max_iter=100,
multi_class='warn', n_jobs=None,
random_state=None, solver='warn',
tol=0.0001, verbose=0, warm_start=False))],
transform_input=None, verbose=False)"""
expected = expected[1:] # remove first \n
assert pipeline.__repr__() == expected
@config_context(print_changed_only=False)
def test_deeply_nested():
# Render a deeply nested estimator
rfe = RFE(RFE(RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))))
expected = """
RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=LogisticRegression(C=1.0,
class_weight=None,
dual=False,
fit_intercept=True,
intercept_scaling=1,
l1_ratio=0,
max_iter=100,
multi_class='warn',
n_jobs=None,
random_state=None,
solver='warn',
tol=0.0001,
verbose=0,
warm_start=False),
n_features_to_select=None,
step=1,
verbose=0),
n_features_to_select=None,
step=1,
verbose=0),
n_features_to_select=None,
step=1, verbose=0),
n_features_to_select=None, step=1,
verbose=0),
n_features_to_select=None, step=1, verbose=0),
n_features_to_select=None, step=1, verbose=0),
n_features_to_select=None, step=1, verbose=0)"""
expected = expected[1:] # remove first \n
assert rfe.__repr__() == expected
@pytest.mark.parametrize(
("print_changed_only", "expected"),
[
(True, "RFE(estimator=RFE(...))"),
(
False,
"RFE(estimator=RFE(...), n_features_to_select=None, step=1, verbose=0)",
),
],
)
def test_print_estimator_max_depth(print_changed_only, expected):
with config_context(print_changed_only=print_changed_only):
pp = _EstimatorPrettyPrinter(depth=1)
rfe = RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))
assert pp.pformat(rfe) == expected
@config_context(print_changed_only=False)
def test_gridsearch():
# render a gridsearch
param_grid = [
{"kernel": ["rbf"], "gamma": [1e-3, 1e-4], "C": [1, 10, 100, 1000]},
{"kernel": ["linear"], "C": [1, 10, 100, 1000]},
]
gs = GridSearchCV(SVC(), param_grid, cv=5)
expected = """
GridSearchCV(cv=5, error_score='raise-deprecating',
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3,
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False),
iid='warn', n_jobs=None,
param_grid=[{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001],
'kernel': ['rbf']},
{'C': [1, 10, 100, 1000], 'kernel': ['linear']}],
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
scoring=None, verbose=0)"""
expected = expected[1:] # remove first \n
assert gs.__repr__() == expected
@config_context(print_changed_only=False)
def test_gridsearch_pipeline():
# render a pipeline inside a gridsearch
pp = _EstimatorPrettyPrinter(compact=True, indent=1, indent_at_name=True)
pipeline = Pipeline([("reduce_dim", PCA()), ("classify", SVC())])
N_FEATURES_OPTIONS = [2, 4, 8]
C_OPTIONS = [1, 10, 100, 1000]
param_grid = [
{
"reduce_dim": [PCA(iterated_power=7), NMF()],
"reduce_dim__n_components": N_FEATURES_OPTIONS,
"classify__C": C_OPTIONS,
},
{
"reduce_dim": [SelectKBest(chi2)],
"reduce_dim__k": N_FEATURES_OPTIONS,
"classify__C": C_OPTIONS,
},
]
gspipeline = GridSearchCV(pipeline, cv=3, n_jobs=1, param_grid=param_grid)
expected = """
GridSearchCV(cv=3, error_score='raise-deprecating',
estimator=Pipeline(memory=None,
steps=[('reduce_dim',
PCA(copy=True, iterated_power='auto',
n_components=None,
random_state=None,
svd_solver='auto', tol=0.0,
whiten=False)),
('classify',
SVC(C=1.0, cache_size=200,
class_weight=None, coef0=0.0,
decision_function_shape='ovr',
degree=3, gamma='auto_deprecated',
kernel='rbf', max_iter=-1,
probability=False,
random_state=None, shrinking=True,
tol=0.001, verbose=False))]),
iid='warn', n_jobs=1,
param_grid=[{'classify__C': [1, 10, 100, 1000],
'reduce_dim': [PCA(copy=True, iterated_power=7,
n_components=None,
random_state=None,
svd_solver='auto', tol=0.0,
whiten=False),
NMF(alpha=0.0, beta_loss='frobenius',
init=None, l1_ratio=0.0,
max_iter=200, n_components=None,
random_state=None, shuffle=False,
solver='cd', tol=0.0001,
verbose=0)],
'reduce_dim__n_components': [2, 4, 8]},
{'classify__C': [1, 10, 100, 1000],
'reduce_dim': [SelectKBest(k=10,
score_func=<function chi2 at some_address>)],
'reduce_dim__k': [2, 4, 8]}],
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
scoring=None, verbose=0)""" # noqa: E501
expected = expected[1:] # remove first \n
repr_ = pp.pformat(gspipeline)
# Remove address of '<function chi2 at 0x.....>' for reproducibility
repr_ = re.sub("function chi2 at 0x.*>", "function chi2 at some_address>", repr_)
assert repr_ == expected
@config_context(print_changed_only=False)
def test_n_max_elements_to_show():
n_max_elements_to_show = 30
pp = _EstimatorPrettyPrinter(
compact=True,
indent=1,
indent_at_name=True,
n_max_elements_to_show=n_max_elements_to_show,
)
# No ellipsis
vocabulary = {i: i for i in range(n_max_elements_to_show)}
vectorizer = CountVectorizer(vocabulary=vocabulary)
expected = r"""
CountVectorizer(analyzer='word', binary=False, decode_error='strict',
dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
lowercase=True, max_df=1.0, max_features=None, min_df=1,
ngram_range=(1, 1), preprocessor=None, stop_words=None,
strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
tokenizer=None,
vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
27: 27, 28: 28, 29: 29})"""
expected = expected[1:] # remove first \n
assert pp.pformat(vectorizer) == expected
# Now with ellipsis
vocabulary = {i: i for i in range(n_max_elements_to_show + 1)}
vectorizer = CountVectorizer(vocabulary=vocabulary)
expected = r"""
CountVectorizer(analyzer='word', binary=False, decode_error='strict',
dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
lowercase=True, max_df=1.0, max_features=None, min_df=1,
ngram_range=(1, 1), preprocessor=None, stop_words=None,
strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
tokenizer=None,
vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
27: 27, 28: 28, 29: 29, ...})"""
expected = expected[1:] # remove first \n
assert pp.pformat(vectorizer) == expected
# Also test with lists
param_grid = {"C": list(range(n_max_elements_to_show))}
gs = GridSearchCV(SVC(), param_grid)
expected = """
GridSearchCV(cv='warn', error_score='raise-deprecating',
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3,
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False),
iid='warn', n_jobs=None,
param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29]},
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
scoring=None, verbose=0)"""
expected = expected[1:] # remove first \n
assert pp.pformat(gs) == expected
# Now with ellipsis
param_grid = {"C": list(range(n_max_elements_to_show + 1))}
gs = GridSearchCV(SVC(), param_grid)
expected = """
GridSearchCV(cv='warn', error_score='raise-deprecating',
estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3,
gamma='auto_deprecated', kernel='rbf', max_iter=-1,
probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False),
iid='warn', n_jobs=None,
param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, ...]},
pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
scoring=None, verbose=0)"""
expected = expected[1:] # remove first \n
assert pp.pformat(gs) == expected
@config_context(print_changed_only=False)
def test_bruteforce_ellipsis():
# Check that the bruteforce ellipsis (used when the number of non-blank
# characters exceeds N_CHAR_MAX) renders correctly.
lr = LogisticRegression()
# test when the left and right side of the ellipsis aren't on the same
# line.
expected = """
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
in...
multi_class='warn', n_jobs=None, random_state=None,
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__(N_CHAR_MAX=150) == expected
# test with very small N_CHAR_MAX
# Note that N_CHAR_MAX is not strictly enforced, but it's normal: to avoid
# weird reprs we still keep the whole line of the right part (after the
# ellipsis).
expected = """
Lo...
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__(N_CHAR_MAX=4) == expected
# test with N_CHAR_MAX == number of non-blank characters: In this case we
# don't want ellipsis
full_repr = lr.__repr__(N_CHAR_MAX=float("inf"))
n_nonblank = len("".join(full_repr.split()))
assert lr.__repr__(N_CHAR_MAX=n_nonblank) == full_repr
assert "..." not in full_repr
# test with N_CHAR_MAX == number of non-blank characters - 10: the left and
# right side of the ellispsis are on different lines. In this case we
# want to expend the whole line of the right side
expected = """
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=0,...00,
multi_class='warn', n_jobs=None, random_state=None,
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 10) == expected
# test with N_CHAR_MAX == number of non-blank characters - 10: the left and
# right side of the ellispsis are on the same line. In this case we don't
# want to expend the whole line of the right side, just add the ellispsis
# between the 2 sides.
expected = """
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=0, max...r=100,
multi_class='warn', n_jobs=None, random_state=None,
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 4) == expected
# test with N_CHAR_MAX == number of non-blank characters - 2: the left and
# right side of the ellispsis are on the same line, but adding the ellipsis
# would actually make the repr longer. So we don't add the ellipsis.
expected = """
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=0, max_iter=100,
multi_class='warn', n_jobs=None, random_state=None,
solver='warn', tol=0.0001, verbose=0, warm_start=False)"""
expected = expected[1:] # remove first \n
assert lr.__repr__(N_CHAR_MAX=n_nonblank - 2) == expected
def test_builtin_prettyprinter():
# non regression test than ensures we can still use the builtin
# PrettyPrinter class for estimators (as done e.g. by joblib).
# Used to be a bug
PrettyPrinter().pprint(LogisticRegression())
def test_kwargs_in_init():
# Make sure the changed_only=True mode is OK when an argument is passed as
# kwargs.
# Non-regression test for
# https://github.com/scikit-learn/scikit-learn/issues/17206
class WithKWargs(BaseEstimator):
# Estimator with a kwargs argument. These need to hack around
# set_params and get_params. Here we mimic what LightGBM does.
def __init__(self, a="willchange", b="unchanged", **kwargs):
self.a = a
self.b = b
self._other_params = {}
self.set_params(**kwargs)
def get_params(self, deep=True):
params = super().get_params(deep=deep)
params.update(self._other_params)
return params
def set_params(self, **params):
for key, value in params.items():
setattr(self, key, value)
self._other_params[key] = value
return self
est = WithKWargs(a="something", c="abcd", d=None)
expected = "WithKWargs(a='something', c='abcd', d=None)"
assert est.__repr__() == expected
with config_context(print_changed_only=False):
expected = "WithKWargs(a='something', b='unchanged', c='abcd', d=None)"
assert est.__repr__() == expected
def test_complexity_print_changed_only():
# Make sure `__repr__` is called the same amount of times
# whether `print_changed_only` is True or False
# Non-regression test for
# https://github.com/scikit-learn/scikit-learn/issues/18490
class DummyEstimator(TransformerMixin, BaseEstimator):
nb_times_repr_called = 0
def __init__(self, estimator=None):
self.estimator = estimator
def __repr__(self):
DummyEstimator.nb_times_repr_called += 1
return super().__repr__()
def transform(self, X, copy=None): # pragma: no cover
return X
estimator = DummyEstimator(
make_pipeline(DummyEstimator(DummyEstimator()), DummyEstimator(), "passthrough")
)
with config_context(print_changed_only=False):
repr(estimator)
nb_repr_print_changed_only_false = DummyEstimator.nb_times_repr_called
DummyEstimator.nb_times_repr_called = 0
with config_context(print_changed_only=True):
repr(estimator)
nb_repr_print_changed_only_true = DummyEstimator.nb_times_repr_called
assert nb_repr_print_changed_only_false == nb_repr_print_changed_only_true
| SimpleImputer |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 91218,
"end": 91296
} | class ____(BinOpSeries):
operation = M.ge
_operator_repr = ">="
| GESeries |
python | mitmproxy__pdoc | pdoc/doc.py | {
"start": 13742,
"end": 20992
} | class ____(Namespace[types.ModuleType]):
"""
Representation of a module's documentation.
"""
def __init__(
self,
module: types.ModuleType,
):
"""
Creates a documentation object given the actual
Python module object.
"""
super().__init__(module.__name__, "", module, (module.__name__, ""))
kind = "module"
@classmethod
@cache
def from_name(cls, name: str) -> Module:
"""Create a `Module` object by supplying the module's (full) name."""
return cls(extract.load_module(name))
@cache
@_include_fullname_in_traceback
def __repr__(self):
return f"<module {self.fullname}{_docstr(self)}{_children(self)}>"
@cached_property
def is_package(self) -> bool:
"""
`True` if the module is a package, `False` otherwise.
Packages are a special kind of module that may have submodules.
Typically, this means that this file is in a directory named like the
module with the name `__init__.py`.
"""
return _safe_getattr(self.obj, "__path__", None) is not None
@cached_property
def _var_docstrings(self) -> dict[str, str]:
return doc_ast.walk_tree(self.obj).var_docstrings
@cached_property
def _func_docstrings(self) -> dict[str, str]:
return doc_ast.walk_tree(self.obj).func_docstrings
@cached_property
def _var_annotations(self) -> dict[str, Any]:
annotations = doc_ast.walk_tree(self.obj).annotations.copy()
for k, v in _safe_getattr(self.obj, "__annotations__", {}).items():
annotations[k] = v
return resolve_annotations(annotations, self.obj, None, self.fullname)
def _taken_from(self, member_name: str, obj: Any) -> tuple[str, str]:
if obj is empty:
return self.modulename, f"{self.qualname}.{member_name}".lstrip(".")
if isinstance(obj, types.ModuleType):
return obj.__name__, ""
mod = _safe_getattr(obj, "__module__", None)
qual = _safe_getattr(obj, "__qualname__", None)
if mod and isinstance(qual, str) and "<locals>" not in qual:
return mod, qual
else:
# This might be wrong, but it's the best guess we have.
return (mod or self.modulename), f"{self.qualname}.{member_name}".lstrip(
"."
)
@cached_property
def own_members(self) -> list[Doc]:
return list(self.members.values())
@cached_property
def submodules(self) -> list[Module]:
"""A list of all (direct) submodules."""
include: Callable[[str], bool]
mod_all = _safe_getattr(self.obj, "__all__", False)
if mod_all is not False:
mod_all_pos = {name: i for i, name in enumerate(mod_all)}
include = mod_all_pos.__contains__
else:
def include(name: str) -> bool:
# optimization: we don't even try to load modules starting with an underscore as they would not be
# visible by default. The downside of this is that someone who overrides `is_public` will miss those
# entries, the upsides are 1) better performance and 2) less warnings because of import failures
# (think of OS-specific modules, e.g. _linux.py failing to import on Windows).
return not name.startswith("_")
submodules: list[Module] = []
for mod_name, mod in extract.iter_modules2(self.obj).items():
if not include(mod_name):
continue
try:
module = Module.from_name(mod.name)
except RuntimeError:
warnings.warn(f"Couldn't import {mod.name}:\n{traceback.format_exc()}")
continue
submodules.append(module)
if mod_all:
submodules = sorted(submodules, key=lambda m: mod_all_pos[m.name])
return submodules
@cached_property
def _ast_keys(self) -> set[str]:
return (
self._var_docstrings.keys()
| self._func_docstrings.keys()
| self._var_annotations.keys()
)
@cached_property
def _member_objects(self) -> dict[str, Any]:
members = {}
all_: list[str] | None = _safe_getattr(self.obj, "__all__", None)
if all_ is not None:
for name in all_:
if not isinstance(name, str):
# Gracefully handle the case where objects are directly specified in __all__.
name = _safe_getattr(name, "__name__", str(name))
if name in self.obj.__dict__:
val = self.obj.__dict__[name]
elif name in self._var_annotations:
val = empty
else:
# this may be an unimported submodule, try importing.
# (https://docs.python.org/3/tutorial/modules.html#importing-from-a-package)
try:
val = extract.load_module(f"{self.modulename}.{name}")
except RuntimeError as e:
warnings.warn(
f"Found {name!r} in {self.modulename}.__all__, but it does not resolve: {e}"
)
val = empty
members[name] = val
else:
# Starting with Python 3.10, __annotations__ is created on demand,
# so we make a copy here as obj.__dict__ is changed while we iterate over it.
# Additionally, accessing self._ast_keys may lead to the execution of TYPE_CHECKING blocks,
# which may also modify obj.__dict__. (https://github.com/mitmproxy/pdoc/issues/351)
for name, obj in list(self.obj.__dict__.items()):
# We already exclude everything here that is imported.
obj_module = inspect.getmodule(obj)
declared_in_this_module = self.obj.__name__ == _safe_getattr(
obj_module, "__name__", None
)
include_in_docs = declared_in_this_module or name in self._ast_keys
if include_in_docs:
members[name] = obj
for name in self._var_docstrings:
members.setdefault(name, empty)
for name in self._var_annotations:
members.setdefault(name, empty)
members, notfound = doc_ast.sort_by_source(self.obj, {}, members)
members.update(notfound)
return members
@cached_property
def variables(self) -> list[Variable]:
"""
A list of all documented module level variables.
"""
return [x for x in self.members.values() if isinstance(x, Variable)]
@cached_property
def classes(self) -> list[Class]:
"""
A list of all documented module level classes.
"""
return [x for x in self.members.values() if isinstance(x, Class)]
@cached_property
def functions(self) -> list[Function]:
"""
A list of all documented module level functions.
"""
return [x for x in self.members.values() if isinstance(x, Function)]
| Module |
python | tensorflow__tensorflow | tensorflow/python/framework/tensor_util_test.py | {
"start": 34548,
"end": 35739
} | class ____(test.TestCase):
def testConstantTensor(self):
np_val = np.random.rand(3).astype(np.int32)
tf_val = constant_op.constant(np_val)
self.assertFalse(tensor_util.is_tf_type(np_val))
self.assertTrue(tensor_util.is_tf_type(tf_val))
def testRaggedTensor(self):
rt = ragged_factory_ops.constant([[1, 2], [3]])
rt_value = self.evaluate(rt)
self.assertTrue(tensor_util.is_tf_type(rt))
self.assertFalse(tensor_util.is_tf_type(rt_value))
def testSparseTensor(self):
st = sparse_tensor.SparseTensor([[1, 2]], [3], [10, 10])
st_value = self.evaluate(st)
self.assertTrue(tensor_util.is_tf_type(st))
self.assertFalse(tensor_util.is_tf_type(st_value))
def testIndexedSlices(self):
x = indexed_slices.IndexedSlices(
constant_op.constant([1, 2, 3]), constant_op.constant([10, 20, 30]))
x_value = indexed_slices.IndexedSlicesValue(
np.array([1, 2, 3]), np.array([10, 20, 30]), np.array([100]))
self.assertTrue(tensor_util.is_tf_type(x))
self.assertFalse(tensor_util.is_tf_type(x_value))
def testVariable(self):
v = variables.Variable([1, 2, 3])
self.assertTrue(tensor_util.is_tf_type(v))
| IsTensorTest |
python | pydantic__pydantic | pydantic/_internal/_config.py | {
"start": 779,
"end": 10239
} | class ____:
"""Internal wrapper for Config which exposes ConfigDict items as attributes."""
__slots__ = ('config_dict',)
config_dict: ConfigDict
# all annotations are copied directly from ConfigDict, and should be kept up to date, a test will fail if they
# stop matching
title: str | None
str_to_lower: bool
str_to_upper: bool
str_strip_whitespace: bool
str_min_length: int
str_max_length: int | None
extra: ExtraValues | None
frozen: bool
populate_by_name: bool
use_enum_values: bool
validate_assignment: bool
arbitrary_types_allowed: bool
from_attributes: bool
# whether to use the actual key provided in the data (e.g. alias or first alias for "field required" errors) instead of field_names
# to construct error `loc`s, default `True`
loc_by_alias: bool
alias_generator: Callable[[str], str] | AliasGenerator | None
model_title_generator: Callable[[type], str] | None
field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None
ignored_types: tuple[type, ...]
allow_inf_nan: bool
json_schema_extra: JsonDict | JsonSchemaExtraCallable | None
json_encoders: dict[type[object], JsonEncoder] | None
# new in V2
strict: bool
# whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
revalidate_instances: Literal['always', 'never', 'subclass-instances']
ser_json_timedelta: Literal['iso8601', 'float']
ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']
val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']
ser_json_bytes: Literal['utf8', 'base64', 'hex']
val_json_bytes: Literal['utf8', 'base64', 'hex']
ser_json_inf_nan: Literal['null', 'constants', 'strings']
# whether to validate default values during validation, default False
validate_default: bool
validate_return: bool
protected_namespaces: tuple[str | Pattern[str], ...]
hide_input_in_errors: bool
defer_build: bool
plugin_settings: dict[str, object] | None
schema_generator: type[GenerateSchema] | None
json_schema_serialization_defaults_required: bool
json_schema_mode_override: Literal['validation', 'serialization', None]
coerce_numbers_to_str: bool
regex_engine: Literal['rust-regex', 'python-re']
validation_error_cause: bool
use_attribute_docstrings: bool
cache_strings: bool | Literal['all', 'keys', 'none']
validate_by_alias: bool
validate_by_name: bool
serialize_by_alias: bool
url_preserve_empty_path: bool
def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True):
if check:
self.config_dict = prepare_config(config)
else:
self.config_dict = cast(ConfigDict, config)
@classmethod
def for_model(
cls,
bases: tuple[type[Any], ...],
namespace: dict[str, Any],
raw_annotations: dict[str, Any],
kwargs: dict[str, Any],
) -> Self:
"""Build a new `ConfigWrapper` instance for a `BaseModel`.
The config wrapper built based on (in descending order of priority):
- options from `kwargs`
- options from the `namespace`
- options from the base classes (`bases`)
Args:
bases: A tuple of base classes.
namespace: The namespace of the class being created.
raw_annotations: The (non-evaluated) annotations of the model.
kwargs: The kwargs passed to the class being created.
Returns:
A `ConfigWrapper` instance for `BaseModel`.
"""
config_new = ConfigDict()
for base in bases:
config = getattr(base, 'model_config', None)
if config:
config_new.update(config.copy())
config_class_from_namespace = namespace.get('Config')
config_dict_from_namespace = namespace.get('model_config')
if raw_annotations.get('model_config') and config_dict_from_namespace is None:
raise PydanticUserError(
'`model_config` cannot be used as a model field name. Use `model_config` for model configuration.',
code='model-config-invalid-field-name',
)
if config_class_from_namespace and config_dict_from_namespace:
raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both')
config_from_namespace = config_dict_from_namespace or prepare_config(config_class_from_namespace)
config_new.update(config_from_namespace)
for k in list(kwargs.keys()):
if k in config_keys:
config_new[k] = kwargs.pop(k)
return cls(config_new)
# we don't show `__getattr__` to type checkers so missing attributes cause errors
if not TYPE_CHECKING: # pragma: no branch
def __getattr__(self, name: str) -> Any:
try:
return self.config_dict[name]
except KeyError:
try:
return config_defaults[name]
except KeyError:
raise AttributeError(f'Config has no attribute {name!r}') from None
def core_config(self, title: str | None) -> core_schema.CoreConfig:
"""Create a pydantic-core config.
We don't use getattr here since we don't want to populate with defaults.
Args:
title: The title to use if not set in config.
Returns:
A `CoreConfig` object created from config.
"""
config = self.config_dict
if config.get('schema_generator') is not None:
warnings.warn(
'The `schema_generator` setting has been deprecated since v2.10. This setting no longer has any effect.',
PydanticDeprecatedSince210,
stacklevel=2,
)
if (populate_by_name := config.get('populate_by_name')) is not None:
# We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.
# Thus, the above warning and this patch can be removed then as well.
if config.get('validate_by_name') is None:
config['validate_by_alias'] = True
config['validate_by_name'] = populate_by_name
# We dynamically patch validate_by_name to be True if validate_by_alias is set to False
# and validate_by_name is not explicitly set.
if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:
config['validate_by_name'] = True
if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):
raise PydanticUserError(
'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',
code='validate-by-alias-and-name-false',
)
return core_schema.CoreConfig(
**{ # pyright: ignore[reportArgumentType]
k: v
for k, v in (
('title', config.get('title') or title or None),
('extra_fields_behavior', config.get('extra')),
('allow_inf_nan', config.get('allow_inf_nan')),
('str_strip_whitespace', config.get('str_strip_whitespace')),
('str_to_lower', config.get('str_to_lower')),
('str_to_upper', config.get('str_to_upper')),
('strict', config.get('strict')),
('ser_json_timedelta', config.get('ser_json_timedelta')),
('ser_json_temporal', config.get('ser_json_temporal')),
('val_temporal_unit', config.get('val_temporal_unit')),
('ser_json_bytes', config.get('ser_json_bytes')),
('val_json_bytes', config.get('val_json_bytes')),
('ser_json_inf_nan', config.get('ser_json_inf_nan')),
('from_attributes', config.get('from_attributes')),
('loc_by_alias', config.get('loc_by_alias')),
('revalidate_instances', config.get('revalidate_instances')),
('validate_default', config.get('validate_default')),
('str_max_length', config.get('str_max_length')),
('str_min_length', config.get('str_min_length')),
('hide_input_in_errors', config.get('hide_input_in_errors')),
('coerce_numbers_to_str', config.get('coerce_numbers_to_str')),
('regex_engine', config.get('regex_engine')),
('validation_error_cause', config.get('validation_error_cause')),
('cache_strings', config.get('cache_strings')),
('validate_by_alias', config.get('validate_by_alias')),
('validate_by_name', config.get('validate_by_name')),
('serialize_by_alias', config.get('serialize_by_alias')),
('url_preserve_empty_path', config.get('url_preserve_empty_path')),
)
if v is not None
}
)
def __repr__(self):
c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items())
return f'ConfigWrapper({c})'
| ConfigWrapper |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 33337,
"end": 42354
} | class ____(MultiOutputMixin, RegressorMixin, _BaseRidge):
"""Linear least squares with l2 regularization.
Minimizes the objective function::
||y - Xw||^2_2 + alpha * ||w||^2_2
This model solves a regression model where the loss function is
the linear least squares function and regularization is given by
the l2-norm. Also known as Ridge Regression or Tikhonov regularization.
This estimator has built-in support for multi-variate regression
(i.e., when y is a 2d-array of shape (n_samples, n_targets)).
Read more in the :ref:`User Guide <ridge_regression>`.
Parameters
----------
alpha : {float, ndarray of shape (n_targets,)}, default=1.0
Constant that multiplies the L2 term, controlling regularization
strength. `alpha` must be a non-negative float i.e. in `[0, inf)`.
When `alpha = 0`, the objective is equivalent to ordinary least
squares, solved by the :class:`LinearRegression` object. For numerical
reasons, using `alpha = 0` with the `Ridge` object is not advised.
Instead, you should use the :class:`LinearRegression` object.
If an array is passed, penalties are assumed to be specific to the
targets. Hence they must correspond in number.
fit_intercept : bool, default=True
Whether to fit the intercept for this model. If set
to false, no intercept will be used in calculations
(i.e. ``X`` and ``y`` are expected to be centered).
copy_X : bool, default=True
If True, X will be copied; else, it may be overwritten.
max_iter : int, default=None
Maximum number of iterations for conjugate gradient solver.
For 'sparse_cg' and 'lsqr' solvers, the default value is determined
by scipy.sparse.linalg. For 'sag' solver, the default value is 1000.
For 'lbfgs' solver, the default value is 15000.
tol : float, default=1e-4
The precision of the solution (`coef_`) is determined by `tol` which
specifies a different convergence criterion for each solver:
- 'svd': `tol` has no impact.
- 'cholesky': `tol` has no impact.
- 'sparse_cg': norm of residuals smaller than `tol`.
- 'lsqr': `tol` is set as atol and btol of scipy.sparse.linalg.lsqr,
which control the norm of the residual vector in terms of the norms of
matrix and coefficients.
- 'sag' and 'saga': relative change of coef smaller than `tol`.
- 'lbfgs': maximum of the absolute (projected) gradient=max|residuals|
smaller than `tol`.
.. versionchanged:: 1.2
Default value changed from 1e-3 to 1e-4 for consistency with other linear
models.
solver : {'auto', 'svd', 'cholesky', 'lsqr', 'sparse_cg', \
'sag', 'saga', 'lbfgs'}, default='auto'
Solver to use in the computational routines:
- 'auto' chooses the solver automatically based on the type of data.
- 'svd' uses a Singular Value Decomposition of X to compute the Ridge
coefficients. It is the most stable solver, in particular more stable
for singular matrices than 'cholesky' at the cost of being slower.
- 'cholesky' uses the standard :func:`scipy.linalg.solve` function to
obtain a closed-form solution.
- 'sparse_cg' uses the conjugate gradient solver as found in
:func:`scipy.sparse.linalg.cg`. As an iterative algorithm, this solver is
more appropriate than 'cholesky' for large-scale data
(possibility to set `tol` and `max_iter`).
- 'lsqr' uses the dedicated regularized least-squares routine
:func:`scipy.sparse.linalg.lsqr`. It is the fastest and uses an iterative
procedure.
- 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses
its improved, unbiased version named SAGA. Both methods also use an
iterative procedure, and are often faster than other solvers when
both n_samples and n_features are large. Note that 'sag' and
'saga' fast convergence is only guaranteed on features with
approximately the same scale. You can preprocess the data with a
scaler from :mod:`sklearn.preprocessing`.
- 'lbfgs' uses L-BFGS-B algorithm implemented in
:func:`scipy.optimize.minimize`. It can be used only when `positive`
is True.
All solvers except 'svd' support both dense and sparse data. However, only
'lsqr', 'sag', 'sparse_cg', and 'lbfgs' support sparse input when
`fit_intercept` is True.
.. versionadded:: 0.17
Stochastic Average Gradient descent solver.
.. versionadded:: 0.19
SAGA solver.
positive : bool, default=False
When set to ``True``, forces the coefficients to be positive.
Only 'lbfgs' solver is supported in this case.
random_state : int, RandomState instance, default=None
Used when ``solver`` == 'sag' or 'saga' to shuffle the data.
See :term:`Glossary <random_state>` for details.
.. versionadded:: 0.17
`random_state` to support Stochastic Average Gradient.
Attributes
----------
coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
Weight vector(s).
intercept_ : float or ndarray of shape (n_targets,)
Independent term in decision function. Set to 0.0 if
``fit_intercept = False``.
n_iter_ : None or ndarray of shape (n_targets,)
Actual number of iterations for each target. Available only for
'sag' and 'lsqr' solvers. Other solvers will return None.
.. versionadded:: 0.17
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
solver_ : str
The solver that was used at fit time by the computational
routines.
.. versionadded:: 1.5
See Also
--------
RidgeClassifier : Ridge classifier.
RidgeCV : Ridge regression with built-in cross validation.
:class:`~sklearn.kernel_ridge.KernelRidge` : Kernel ridge regression
combines ridge regression with the kernel trick.
Notes
-----
Regularization improves the conditioning of the problem and
reduces the variance of the estimates. Larger values specify stronger
regularization. Alpha corresponds to ``1 / (2C)`` in other linear
models such as :class:`~sklearn.linear_model.LogisticRegression` or
:class:`~sklearn.svm.LinearSVC`.
Examples
--------
>>> from sklearn.linear_model import Ridge
>>> import numpy as np
>>> n_samples, n_features = 10, 5
>>> rng = np.random.RandomState(0)
>>> y = rng.randn(n_samples)
>>> X = rng.randn(n_samples, n_features)
>>> clf = Ridge(alpha=1.0)
>>> clf.fit(X, y)
Ridge()
"""
def __init__(
self,
alpha=1.0,
*,
fit_intercept=True,
copy_X=True,
max_iter=None,
tol=1e-4,
solver="auto",
positive=False,
random_state=None,
):
super().__init__(
alpha=alpha,
fit_intercept=fit_intercept,
copy_X=copy_X,
max_iter=max_iter,
tol=tol,
solver=solver,
positive=positive,
random_state=random_state,
)
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y, sample_weight=None):
"""Fit Ridge regression model.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
Target values.
sample_weight : float or ndarray of shape (n_samples,), default=None
Individual weights for each sample. If given a float, every sample
will have the same weight.
Returns
-------
self : object
Fitted estimator.
"""
_accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver)
xp, _ = get_namespace(X, y, sample_weight)
X, y = validate_data(
self,
X,
y,
accept_sparse=_accept_sparse,
dtype=[xp.float64, xp.float32],
force_writeable=True,
multi_output=True,
y_numeric=True,
)
return super().fit(X, y, sample_weight=sample_weight)
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.array_api_support = True
tags.input_tags.sparse = (self.solver != "svd") and (
self.solver != "cholesky" or not self.fit_intercept
)
return tags
| Ridge |
python | django-mptt__django-mptt | mptt/forms.py | {
"start": 582,
"end": 1715
} | class ____:
def __init__(self, queryset, *args, **kwargs):
self.level_indicator = kwargs.pop("level_indicator", DEFAULT_LEVEL_INDICATOR)
self.start_level = kwargs.pop("start_level", 0)
# if a queryset is supplied, enforce ordering
if hasattr(queryset, "model"):
mptt_opts = queryset.model._mptt_meta
queryset = queryset.order_by(mptt_opts.tree_id_attr, mptt_opts.left_attr)
super().__init__(queryset, *args, **kwargs)
def _get_relative_level(self, obj):
level = getattr(obj, obj._mptt_meta.level_attr)
return level - self.start_level
def _get_level_indicator(self, obj):
level = self._get_relative_level(obj)
return mark_safe(conditional_escape(self.level_indicator) * min(100, level))
def label_from_instance(self, obj):
"""
Creates labels which represent the tree level of each node when
generating option labels.
"""
level_indicator = self._get_level_indicator(obj)
return mark_safe(level_indicator + " " + conditional_escape(smart_str(obj)))
| TreeNodeChoiceFieldMixin |
python | celery__celery | t/unit/utils/test_functional.py | {
"start": 12585,
"end": 13575
} | class ____:
@pytest.mark.parametrize('fun', [
lambda a, b, **kwargs: 1,
lambda *args, **kwargs: 1,
lambda foo=1, **kwargs: 1,
StarKwargsCallable(),
StarArgsStarKwargsCallable(),
ArgsStarKwargsCallable(),
])
def test_accepts(self, fun):
assert fun_accepts_kwargs(fun)
@pytest.mark.parametrize('fun', [
lambda a: 1,
lambda a, b: 1,
lambda *args: 1,
lambda a, kw1=1, kw2=2: 1,
StarArgsCallable(),
ArgsCallable(),
])
def test_rejects(self, fun):
assert not fun_accepts_kwargs(fun)
@pytest.mark.parametrize('value,expected', [
(5, True),
(5.0, True),
(0, True),
(0.0, True),
(True, False),
('value', False),
('5', False),
('5.0', False),
(None, False),
])
def test_is_numeric_value(value, expected):
res = is_numeric_value(value)
assert type(res) is type(expected)
assert res == expected
| test_fun_accepts_kwargs |
python | networkx__networkx | networkx/algorithms/tests/test_summarization.py | {
"start": 19030,
"end": 21312
} | class ____(AbstractSNAP):
def build_original_graph(self):
nodes = {
"A": {"color": "Red"},
"B": {"color": "Red"},
"C": {"color": "Green"},
"D": {"color": "Green"},
"E": {"color": "Blue"},
"F": {"color": "Blue"},
"G": {"color": "Yellow"},
"H": {"color": "Yellow"},
}
edges = [
("A", "C", ["Weak", "Strong"]),
("A", "E", ["Strong"]),
("A", "F", ["Weak"]),
("B", "D", ["Weak", "Strong"]),
("B", "E", ["Weak"]),
("B", "F", ["Strong"]),
("C", "G", ["Weak", "Strong"]),
("C", "F", ["Strong"]),
("D", "E", ["Strong"]),
("D", "H", ["Weak", "Strong"]),
("G", "E", ["Strong"]),
("H", "F", ["Strong"]),
]
G = nx.MultiDiGraph()
for node in nodes:
attributes = nodes[node]
G.add_node(node, **attributes)
for source, target, types in edges:
for type in types:
G.add_edge(source, target, type=type)
return G
def build_summary_graph(self):
nodes = {
"Supernode-0": {"color": "Red"},
"Supernode-1": {"color": "Blue"},
"Supernode-2": {"color": "Yellow"},
"Supernode-3": {"color": "Blue"},
}
edges = [
("Supernode-0", "Supernode-1", ["Weak", "Strong"]),
("Supernode-0", "Supernode-2", ["Weak", "Strong"]),
("Supernode-1", "Supernode-2", ["Strong"]),
("Supernode-1", "Supernode-3", ["Weak", "Strong"]),
("Supernode-3", "Supernode-2", ["Strong"]),
]
G = nx.MultiDiGraph()
for node in nodes:
attributes = nodes[node]
G.add_node(node, **attributes)
for source, target, types in edges:
for type in types:
G.add_edge(source, target, type=type)
supernodes = {
"Supernode-0": {"A", "B"},
"Supernode-1": {"C", "D"},
"Supernode-2": {"E", "F"},
"Supernode-3": {"G", "H"},
}
nx.set_node_attributes(G, supernodes, "group")
return G
| TestSNAPDirectedMulti |
python | psf__black | tests/data/cases/trailing_comma_optional_parens1.py | {
"start": 1127,
"end": 1420
} | class ____:
def get_help_text(self):
return ngettext(
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
self.min_length,
) % {"min_length": self.min_length}
| X |
python | pytorch__pytorch | torch/backends/xnnpack/__init__.py | {
"start": 67,
"end": 264
} | class ____:
def __get__(self, obj, objtype):
return torch._C._is_xnnpack_enabled()
def __set__(self, obj, val):
raise RuntimeError("Assignment not supported")
| _XNNPACKEnabled |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-amazon-product-extraction/llama_index/packs/amazon_product_extraction/base.py | {
"start": 1582,
"end": 3459
} | class ____(BaseLlamaPack):
"""
Product extraction pack.
Given a website url of a product (e.g. Amazon page), screenshot it,
and use GPT-4V to extract structured outputs.
"""
def __init__(
self,
website_url: str,
tmp_file_path: str = "./tmp.png",
screenshot_width: int = 1200,
screenshot_height: int = 800,
prompt_template_str: str = DEFAULT_PROMPT_TEMPLATE_STR,
**kwargs: Any,
) -> None:
"""Init params."""
self.website_url = website_url
# download image to temporary file
asyncio.get_event_loop().run_until_complete(
_screenshot_page(
website_url,
tmp_file_path,
width=screenshot_width,
height=screenshot_height,
)
)
# put your local directory here
self.image_documents = SimpleDirectoryReader(
input_files=[tmp_file_path]
).load_data()
# initialize openai pydantic program
self.openai_mm_llm = OpenAIMultiModal(
model="gpt-4-vision-preview", max_new_tokens=1000
)
self.openai_program = MultiModalLLMCompletionProgram.from_defaults(
output_parser=PydanticOutputParser(Product),
image_documents=self.image_documents,
prompt_template_str=prompt_template_str,
llm=self.openai_mm_llm,
verbose=True,
)
def get_modules(self) -> Dict[str, Any]:
"""Get modules."""
return {
"openai_program": self.openai_program,
"openai_mm_llm": self.openai_mm_llm,
"image_documents": self.image_documents,
}
def run(self, *args: Any, **kwargs: Any) -> Any:
"""Run the pipeline."""
return self.openai_program(*args, **kwargs)
| AmazonProductExtractionPack |
python | huggingface__transformers | src/transformers/models/biogpt/modular_biogpt.py | {
"start": 2087,
"end": 5883
} | class ____(BartDecoderLayer):
def __init__(self, config: BioGptConfig, layer_idx: Optional[int] = None):
super().__init__(config)
self.embed_dim = config.hidden_size
self.self_attn = BioGptAttention(
embed_dim=self.embed_dim,
num_heads=config.num_attention_heads,
dropout=config.attention_probs_dropout_prob,
is_decoder=True,
is_causal=True,
config=config,
layer_idx=layer_idx,
)
self.dropout = config.hidden_dropout_prob
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(self.embed_dim, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, self.embed_dim)
del self.encoder_attn
del self.encoder_attn_layer_norm
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = True,
position_ids: Optional[torch.LongTensor] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
past_key_values (`Cache`): cached past key and value projection states
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
(see `past_key_values`).
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
cache in the correct position and to infer the complete sequence length.
"""
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
# Self Attention
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
past_key_values=past_key_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
position_ids=position_ids,
cache_position=cache_position,
**kwargs,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
@auto_docstring
| BioGptDecoderLayer |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 1047,
"end": 1143
} | class ____(Package):
version("4.1")
version("4.0")
""",
)
_pkgy1 = (
"y1",
"""\
| X4 |
python | django__django | django/db/models/functions/math.py | {
"start": 5040,
"end": 5785
} | class ____(FixDecimalInputMixin, Transform):
function = "ROUND"
lookup_name = "round"
arity = None # Override Transform's arity=1 to enable passing precision.
def __init__(self, expression, precision=0, **extra):
super().__init__(expression, precision, **extra)
def as_sqlite(self, compiler, connection, **extra_context):
precision = self.get_source_expressions()[1]
if isinstance(precision, Value) and precision.value < 0:
raise ValueError("SQLite does not support negative precision.")
return super().as_sqlite(compiler, connection, **extra_context)
def _resolve_output_field(self):
source = self.get_source_expressions()[0]
return source.output_field
| Round |
python | readthedocs__readthedocs.org | readthedocs/organizations/forms.py | {
"start": 5768,
"end": 7183
} | class ____(forms.Form):
"""Form to manage owners of the organization."""
username_or_email = forms.CharField(label=_("Email address or username"))
def __init__(self, *args, **kwargs):
self.organization = kwargs.pop("organization", None)
self.request = kwargs.pop("request", None)
super().__init__(*args, **kwargs)
def clean_username_or_email(self):
"""Lookup owner by username or email, detect collisions with existing owners."""
username = self.cleaned_data["username_or_email"]
user = User.objects.filter(
Q(username=username) | Q(emailaddress__verified=True, emailaddress__email=username)
).first()
if user is None:
raise forms.ValidationError(
_("User %(username)s does not exist"),
params={"username": username},
)
if self.organization.owners.filter(pk=user.pk).exists():
raise forms.ValidationError(
_("User %(username)s is already an owner"),
params={"username": username},
)
return user
def save(self):
invitation, _ = Invitation.objects.invite(
from_user=self.request.user,
to_user=self.cleaned_data["username_or_email"],
obj=self.organization,
request=self.request,
)
return invitation
| OrganizationOwnerForm |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-convert-string-ii.py | {
"start": 14426,
"end": 17832
} | class ____(object):
def minimumCost(self, source, target, original, changed, cost):
"""
:type source: str
:type target: str
:type original: List[str]
:type changed: List[str]
:type cost: List[int]
:rtype: int
"""
INF = float("inf")
class Trie(object):
def __init__(self):
self.__nodes = []
self.__idxs = []
self.k = 0
self.__new_node()
def __new_node(self):
self.__nodes.append([-1]*26)
self.__idxs.append(-1)
return len(self.__nodes)-1
def add(self, s):
curr = 0
for c in s:
x = ord(c)-ord('a')
if self.__nodes[curr][x] == -1:
self.__nodes[curr][x] = self.__new_node()
curr = self.__nodes[curr][x]
if self.__idxs[curr] == -1:
self.__idxs[curr] = self.k
self.k += 1
return True, self.__idxs[curr]
return False, self.__idxs[curr]
def query(self, s):
curr = 0
for c in s:
curr = self.__nodes[curr][ord(c)-ord('a')]
return self.__idxs[curr]
def next(self, curr, c):
return self.__nodes[curr][ord(c)-ord('a')]
def id(self, curr):
return self.__idxs[curr]
def floydWarshall(dist):
for k in dist.iterkeys():
for i in dist.iterkeys():
if dist[i][k] == INF:
continue
for j in dist.iterkeys():
if dist[k][j] == INF:
continue
dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j])
trie = Trie()
buckets = collections.defaultdict(list)
for x in itertools.chain(original, changed):
not_duplicated, i = trie.add(x)
if not_duplicated:
buckets[len(x)].append(i)
dists = {l:{u:{v:0 if u == v else INF for v in lookup} for u in lookup} for l, lookup in buckets.iteritems()}
for i in xrange(len(original)):
l = len(original[i])
dist = dists[l]
u, v = trie.query(original[i]), trie.query(changed[i])
dist[u][v] = min(dist[u][v], cost[i])
for dist in dists.itervalues():
floydWarshall(dist)
dp = [INF]*(max(len(x) for x in original)+1)
dp[0] = 0
for i in xrange(len(source)):
if dp[i%len(dp)] == INF:
continue
if source[i] == target[i]:
dp[(i+1)%len(dp)] = min(dp[(i+1)%len(dp)], dp[i%len(dp)])
u = v = 0
for j in xrange(i, len(source)):
u = trie.next(u, source[j])
v = trie.next(v, target[j])
if u == -1 or v == -1:
break
if trie.id(u) != -1 and trie.id(v) != -1:
dp[(j+1)%len(dp)] = min(dp[(j+1)%len(dp)], dp[i%len(dp)]+dists[j-i+1][trie.id(u)][trie.id(v)])
dp[i%len(dp)] = INF
return dp[len(source)%len(dp)] if dp[len(source)%len(dp)] != INF else -1
| Solution6 |
python | doocs__leetcode | solution/0200-0299/0273.Integer to English Words/Solution.py | {
"start": 0,
"end": 1486
} | class ____:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
lt20 = [
'',
'One',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Eleven',
'Twelve',
'Thirteen',
'Fourteen',
'Fifteen',
'Sixteen',
'Seventeen',
'Eighteen',
'Nineteen',
]
tens = [
'',
'Ten',
'Twenty',
'Thirty',
'Forty',
'Fifty',
'Sixty',
'Seventy',
'Eighty',
'Ninety',
]
thousands = ['Billion', 'Million', 'Thousand', '']
def transfer(num):
if num == 0:
return ''
if num < 20:
return lt20[num] + ' '
if num < 100:
return tens[num // 10] + ' ' + transfer(num % 10)
return lt20[num // 100] + ' Hundred ' + transfer(num % 100)
res = []
i, j = 1000000000, 0
while i > 0:
if num // i != 0:
res.append(transfer(num // i))
res.append(thousands[j])
res.append(' ')
num %= i
j += 1
i //= 1000
return ''.join(res).strip()
| Solution |
python | pytorch__pytorch | tools/test/test_codegen.py | {
"start": 14291,
"end": 17699
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.native_functions: list[NativeFunction] = []
self.backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]] = (
defaultdict(dict)
)
yaml_entry = """
- func: op(Tensor self) -> Tensor
dispatch:
CompositeExplicitAutograd: op
autogen: op.out
"""
es = yaml.load(yaml_entry, Loader=LineLoader)
self.one_return_func, m = NativeFunction.from_yaml(
es[0], loc=Location(__file__, 1), valid_tags=set()
)
BackendIndex.grow_index(self.backend_indices, m)
self.two_returns_func, two_returns_backend_index = NativeFunction.from_yaml(
{
"func": "op_2() -> (Tensor, Tensor)",
"dispatch": {"CPU": "kernel_1"},
"autogen": "op_2.out",
},
loc=Location(__file__, 1),
valid_tags=set(),
)
BackendIndex.grow_index(self.backend_indices, two_returns_backend_index)
self.core_func, core_func_index = NativeFunction.from_yaml(
{
"func": "op_3.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor",
"autogen": "op_3.vec_out",
"tags": ["core"],
},
loc=Location(__file__, 1),
valid_tags={"core"},
)
BackendIndex.grow_index(self.backend_indices, core_func_index)
def test_functional_variant_autogen_out_variant(self) -> None:
native_functions = [self.one_return_func]
add_generated_native_functions(native_functions, self.backend_indices)
self.assertEqual(len(native_functions), 2)
self.assertEqual(
str(native_functions[1].func),
"op.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)",
)
op_name = native_functions[1].func.name
backend_metadata = self.backend_indices[DispatchKey.CompositeExplicitAutograd][
op_name
]
self.assertEqual(backend_metadata.kernel, "op_out")
def test_functional_variant_autogen_out_variant_two_returns(self) -> None:
native_functions = [self.two_returns_func]
add_generated_native_functions(native_functions, self.backend_indices)
self.assertEqual(len(native_functions), 2)
self.assertEqual(
str(native_functions[1].func),
"op_2.out(*, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))",
)
op_name = native_functions[1].func.name
backend_metadata = self.backend_indices[DispatchKey.CompositeExplicitAutograd][
op_name
]
self.assertEqual(backend_metadata.kernel, "op_2_out")
def test_functional_variant_autogen_out_variant_core(self) -> None:
"""
Tests autogen of out variants for core-tageed ops that are CompositeImplicitAutograd.
"""
native_functions = [self.core_func]
add_generated_native_functions(native_functions, self.backend_indices)
print(native_functions)
self.assertEqual(len(native_functions), 2)
self.assertEqual(
str(native_functions[1].func),
"op_3.vec_out(Tensor input, SymInt[]? output_size, float[]? scale_factors, *, Tensor(a!) out) -> Tensor(a!)",
)
# Test for static_dispatch
| TestNativeFunctionGeneratrion |
python | automl__auto-sklearn | autosklearn/pipeline/components/feature_preprocessing/pca.py | {
"start": 470,
"end": 2404
} | class ____(AutoSklearnPreprocessingAlgorithm):
def __init__(self, keep_variance, whiten, random_state=None):
self.keep_variance = keep_variance
self.whiten = whiten
self.random_state = random_state
def fit(self, X, Y=None):
import sklearn.decomposition
n_components = float(self.keep_variance)
self.whiten = check_for_bool(self.whiten)
self.preprocessor = sklearn.decomposition.PCA(
n_components=n_components, whiten=self.whiten, copy=True
)
self.preprocessor.fit(X)
if not np.isfinite(self.preprocessor.components_).all():
raise ValueError("PCA found non-finite components.")
return self
def transform(self, X):
if self.preprocessor is None:
raise NotImplementedError()
return self.preprocessor.transform(X)
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "PCA",
"name": "Principle Component Analysis",
"handles_regression": True,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": True,
# TODO document that we have to be very careful
"is_deterministic": False,
"input": (DENSE, UNSIGNED_DATA),
"output": (DENSE, UNSIGNED_DATA),
}
@staticmethod
def get_hyperparameter_search_space(
feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None
):
keep_variance = UniformFloatHyperparameter(
"keep_variance", 0.5, 0.9999, default_value=0.9999
)
whiten = CategoricalHyperparameter(
"whiten", ["False", "True"], default_value="False"
)
cs = ConfigurationSpace()
cs.add_hyperparameters([keep_variance, whiten])
return cs
| PCA |
python | huggingface__transformers | tests/pipelines/test_pipelines_common.py | {
"start": 2176,
"end": 2446
} | class ____:
def __init__(self, *_types):
self._types = _types
def __eq__(self, other):
return isinstance(other, self._types)
def __repr__(self):
return f"ANY({', '.join(_type.__name__ for _type in self._types)})"
@is_pipeline_test
| ANY |
python | langchain-ai__langchain | libs/core/tests/unit_tests/output_parsers/test_pydantic_parser.py | {
"start": 597,
"end": 2883
} | class ____(pydantic.BaseModel):
temperature: int
f_or_c: Literal["F", "C"]
forecast: str
if sys.version_info < (3, 14):
class ForecastV1(V1BaseModel):
temperature: int
f_or_c: Literal["F", "C"]
forecast: str
_FORECAST_MODELS_TYPES = type[ForecastV2] | type[ForecastV1]
_FORECAST_MODELS = [ForecastV2, ForecastV1]
else:
_FORECAST_MODELS_TYPES = type[ForecastV2]
_FORECAST_MODELS = [ForecastV2]
@pytest.mark.parametrize("pydantic_object", _FORECAST_MODELS)
def test_pydantic_parser_chaining(
pydantic_object: _FORECAST_MODELS_TYPES,
) -> None:
prompt = PromptTemplate(
template="""{{
"temperature": 20,
"f_or_c": "C",
"forecast": "Sunny"
}}""",
input_variables=[],
)
model = ParrotFakeChatModel()
parser = PydanticOutputParser[PydanticBaseModel](pydantic_object=pydantic_object)
chain = prompt | model | parser
res = chain.invoke({})
assert isinstance(res, pydantic_object)
assert res.f_or_c == "C"
assert res.temperature == 20
assert res.forecast == "Sunny"
@pytest.mark.parametrize("pydantic_object", _FORECAST_MODELS)
def test_pydantic_parser_validation(pydantic_object: TypeBaseModel) -> None:
bad_prompt = PromptTemplate(
template="""{{
"temperature": "oof",
"f_or_c": 1,
"forecast": "Sunny"
}}""",
input_variables=[],
)
model = ParrotFakeChatModel()
parser = PydanticOutputParser[PydanticBaseModel](pydantic_object=pydantic_object)
chain = bad_prompt | model | parser
with pytest.raises(OutputParserException):
chain.invoke({})
# JSON output parser tests
@pytest.mark.parametrize("pydantic_object", _FORECAST_MODELS)
def test_json_parser_chaining(
pydantic_object: TypeBaseModel,
) -> None:
prompt = PromptTemplate(
template="""{{
"temperature": 20,
"f_or_c": "C",
"forecast": "Sunny"
}}""",
input_variables=[],
)
model = ParrotFakeChatModel()
parser = JsonOutputParser(pydantic_object=pydantic_object)
chain = prompt | model | parser
res = chain.invoke({})
assert res["f_or_c"] == "C"
assert res["temperature"] == 20
assert res["forecast"] == "Sunny"
| ForecastV2 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_check_sheetname.py | {
"start": 354,
"end": 2338
} | class ____(unittest.TestCase):
"""
Test the Workbook _check_sheetname() method.
"""
def setUp(self):
self.workbook = Workbook()
def test_check_sheetname(self):
"""Test the _check_sheetname() method"""
got = self.workbook._check_sheetname("name")
exp = "name"
self.assertEqual(exp, got)
got = self.workbook._check_sheetname("Sheet1")
exp = "Sheet1"
self.assertEqual(exp, got)
got = self.workbook._check_sheetname(None)
exp = "Sheet3"
self.assertEqual(exp, got)
got = self.workbook._check_sheetname("")
exp = "Sheet4"
self.assertEqual(exp, got)
def test_check_sheetname_with_long_name(self):
"""Test the _check_sheetname() method with exception"""
name = "name_that_is_longer_than_thirty_one_characters"
self.assertRaises(InvalidWorksheetName, self.workbook._check_sheetname, name)
def test_check_sheetname_with_invalid_name(self):
"""Test the _check_sheetname() method with exception"""
name = "name_with_special_character_?"
self.assertRaises(InvalidWorksheetName, self.workbook._check_sheetname, name)
name = "'start with apostrophe"
self.assertRaises(InvalidWorksheetName, self.workbook._check_sheetname, name)
name = "end with apostrophe'"
self.assertRaises(InvalidWorksheetName, self.workbook._check_sheetname, name)
name = "'start and end with apostrophe'"
self.assertRaises(InvalidWorksheetName, self.workbook._check_sheetname, name)
def test_check_sheetname_with_duplicate_name(self):
"""Test the _check_sheetname() method with exception"""
name1 = "Duplicate_name"
name2 = name1.lower()
self.workbook.add_worksheet(name1)
self.assertRaises(DuplicateWorksheetName, self.workbook.add_worksheet, name2)
def tearDown(self):
self.workbook.fileclosed = True
| TestCheckSheetname |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 46924,
"end": 53338
} | class ____(Response):
"""
Response of projects.get_all endpoint.
:param projects: Projects list
:type projects: Sequence[ProjectsGetAllResponseSingle]
"""
_service = "projects"
_action = "get_all"
_version = "2.9"
_schema = {
"definitions": {
"projects_get_all_response_single": {
"properties": {
"company": {
"description": "Company id",
"type": ["string", "null"],
},
"created": {
"description": "Creation time",
"format": "date-time",
"type": ["string", "null"],
},
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": ["string", "null"],
},
"description": {
"description": "Project description",
"type": ["string", "null"],
},
"id": {"description": "Project id", "type": ["string", "null"]},
"name": {"description": "Project name", "type": ["string", "null"]},
"stats": {
"description": "Additional project stats",
"oneOf": [{"$ref": "#/definitions/stats"}, {"type": "null"}],
},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"user": {
"description": "Associated user id",
"type": ["string", "null"],
},
},
"type": "object",
},
"stats": {
"properties": {
"active": {
"description": "Stats for active tasks",
"oneOf": [
{"$ref": "#/definitions/stats_status_count"},
{"type": "null"},
],
},
"archived": {
"description": "Stats for archived tasks",
"oneOf": [
{"$ref": "#/definitions/stats_status_count"},
{"type": "null"},
],
},
},
"type": "object",
},
"stats_status_count": {
"properties": {
"status_count": {
"description": "Status counts",
"properties": {
"closed": {
"description": "Number of 'closed' tasks in project",
"type": "integer",
},
"created": {
"description": "Number of 'created' tasks in project",
"type": "integer",
},
"failed": {
"description": "Number of 'failed' tasks in project",
"type": "integer",
},
"in_progress": {
"description": "Number of 'in_progress' tasks in project",
"type": "integer",
},
"published": {
"description": "Number of 'published' tasks in project",
"type": "integer",
},
"queued": {
"description": "Number of 'queued' tasks in project",
"type": "integer",
},
"stopped": {
"description": "Number of 'stopped' tasks in project",
"type": "integer",
},
"unknown": {
"description": "Number of 'unknown' tasks in project",
"type": "integer",
},
},
"type": ["object", "null"],
},
"total_runtime": {
"description": "Total run time of all tasks in project (in seconds)",
"type": ["integer", "null"],
},
},
"type": "object",
},
},
"properties": {
"projects": {
"description": "Projects list",
"items": {"$ref": "#/definitions/projects_get_all_response_single"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, projects: Optional[List[Any]] = None, **kwargs: Any) -> None:
super(GetAllResponse, self).__init__(**kwargs)
self.projects = projects
@schema_property("projects")
def projects(self) -> Optional[List[Any]]:
return self._property_projects
@projects.setter
def projects(self, value: Optional[List[Any]]) -> None:
if value is None:
self._property_projects = None
return
self.assert_isinstance(value, "projects", (list, tuple))
if any((isinstance(v, dict) for v in value)):
value = [ProjectsGetAllResponseSingle.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "projects", ProjectsGetAllResponseSingle, is_array=True)
self._property_projects = value
| GetAllResponse |
python | tensorflow__tensorflow | tensorflow/tools/docs/generate2_test.py | {
"start": 981,
"end": 1948
} | class ____(types.ModuleType):
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError()
mod = AutoModule(name)
setattr(self, name, mod)
return mod
# Make a mock tensorflow package that won't take too long to test.
fake_tf = AutoModule('FakeTensorFlow')
fake_tf.Module = tf.Module # pylint: disable=invalid-name
fake_tf.feature_column.nummeric_column = tf.feature_column.numeric_column
fake_tf.keras.Model = tf.keras.Model
fake_tf.keras.preprocessing = tf.keras.preprocessing
fake_tf.keras.layers.Layer = tf.keras.layers.Layer
fake_tf.keras.optimizers.Optimizer = tf.keras.optimizers.Optimizer
fake_tf.nn.sigmoid_cross_entropy_with_logits = (
tf.nn.sigmoid_cross_entropy_with_logits
)
fake_tf.raw_ops.Add = tf.raw_ops.Add
fake_tf.raw_ops.Print = tf.raw_ops.Print # op with no XLA support
fake_tf.summary.audio = tf.summary.audio
fake_tf.summary.audio2 = tf.summary.audio
fake_tf.__version__ = tf.__version__
| AutoModule |
python | ray-project__ray | rllib/examples/envs/classes/six_room_env.py | {
"start": 3279,
"end": 11253
} | class ____(MultiAgentEnv):
def __init__(self, config=None):
super().__init__()
# User can provide a custom map or a recognized map name (small, medium, large).
self.map = config.get("custom_map", MAPS.get(config.get("map"), MAPS["small"]))
self.max_steps_low_level = config.get("max_steps_low_level", 15)
self.time_limit = config.get("time_limit", 50)
self.num_low_level_agents = config.get("num_low_level_agents", 3)
self.agents = self.possible_agents = ["high_level_agent"] + [
f"low_level_agent_{i}" for i in range(self.num_low_level_agents)
]
# Define basic observation space: Discrete, index fields.
observation_space = gym.spaces.Discrete(len(self.map) * len(self.map[0]))
# Low level agents always see where they are right now and what the target
# state should be.
low_level_observation_space = gym.spaces.Tuple(
(observation_space, observation_space)
)
# Primitive actions: up, down, left, right.
low_level_action_space = gym.spaces.Discrete(4)
self.observation_spaces = {"high_level_agent": observation_space}
self.observation_spaces.update(
{
f"low_level_agent_{i}": low_level_observation_space
for i in range(self.num_low_level_agents)
}
)
self.action_spaces = {
"high_level_agent": gym.spaces.Tuple(
(
# The new target observation.
observation_space,
# Low-level policy that should get us to the new target observation.
gym.spaces.Discrete(self.num_low_level_agents),
)
)
}
self.action_spaces.update(
{
f"low_level_agent_{i}": low_level_action_space
for i in range(self.num_low_level_agents)
}
)
# Initialize environment state.
self.reset()
def reset(self, *, seed=None, options=None):
self._agent_pos = (1, 1)
self._low_level_steps = 0
self._high_level_action = None
# Number of times the low-level agent reached the given target (by the high
# level agent).
self._num_targets_reached = 0
self._ts = 0
# Return high-level observation.
return {
"high_level_agent": self._agent_discrete_pos,
}, {}
def step(self, action_dict):
self._ts += 1
terminateds = {"__all__": self._ts >= self.time_limit}
truncateds = {"__all__": False}
# High-level agent acted: Set next goal and next low-level policy to use.
# Note that the agent does not move in this case and stays at its current
# location.
if "high_level_agent" in action_dict:
self._high_level_action = action_dict["high_level_agent"]
low_level_agent = f"low_level_agent_{self._high_level_action[1]}"
self._low_level_steps = 0
# Return next low-level observation for the now-active agent.
# We want this agent to act next.
return (
{
low_level_agent: (
self._agent_discrete_pos, # current
self._high_level_action[0], # target
)
},
# Penalty for a target state that's close to the current state.
{
"high_level_agent": (
self.eucl_dist(
self._agent_discrete_pos,
self._high_level_action[0],
self.map,
)
/ (len(self.map) ** 2 + len(self.map[0]) ** 2) ** 0.5
)
- 1.0,
},
terminateds,
truncateds,
{},
)
# Low-level agent made a move (primitive action).
else:
assert len(action_dict) == 1
# Increment low-level step counter.
self._low_level_steps += 1
target_discrete_pos, low_level_agent = self._high_level_action
low_level_agent = f"low_level_agent_{low_level_agent}"
next_pos = _get_next_pos(action_dict[low_level_agent], self._agent_pos)
# Check if the move ends up in a wall. If so -> Ignore the move and stay
# where we are right now.
if self.map[next_pos[0]][next_pos[1]] != "W":
self._agent_pos = next_pos
# Check if the agent has reached the global goal state.
if self.map[self._agent_pos[0]][self._agent_pos[1]] == "G":
rewards = {
"high_level_agent": 10.0,
# +1.0 if the goal position was also the target position for the
# low level agent.
low_level_agent: float(
self._agent_discrete_pos == target_discrete_pos
),
}
terminateds["__all__"] = True
return (
{"high_level_agent": self._agent_discrete_pos},
rewards,
terminateds,
truncateds,
{},
)
# Low-level agent has reached its target location (given by the high-level):
# - Hand back control to high-level agent.
# - Reward low level agent and high-level agent with small rewards.
elif self._agent_discrete_pos == target_discrete_pos:
self._num_targets_reached += 1
rewards = {
"high_level_agent": 1.0,
low_level_agent: 1.0,
}
return (
{"high_level_agent": self._agent_discrete_pos},
rewards,
terminateds,
truncateds,
{},
)
# Low-level agent has not reached anything.
else:
# Small step penalty for low-level agent.
rewards = {low_level_agent: -0.01}
# Reached time budget -> Hand back control to high level agent.
if self._low_level_steps >= self.max_steps_low_level:
rewards["high_level_agent"] = -0.01
return (
{"high_level_agent": self._agent_discrete_pos},
rewards,
terminateds,
truncateds,
{},
)
else:
return (
{
low_level_agent: (
self._agent_discrete_pos, # current
target_discrete_pos, # target
),
},
rewards,
terminateds,
truncateds,
{},
)
@property
def _agent_discrete_pos(self):
x = self._agent_pos[0]
y = self._agent_pos[1]
# discrete position = row idx * columns + col idx
return x * len(self.map[0]) + y
@staticmethod
def eucl_dist(pos1, pos2, map):
x1, y1 = pos1 % len(map[0]), pos1 // len(map)
x2, y2 = pos2 % len(map[0]), pos2 // len(map)
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
def _get_next_pos(action, pos):
x, y = pos
# Up.
if action == 0:
return x - 1, y
# Down.
elif action == 1:
return x + 1, y
# Left.
elif action == 2:
return x, y - 1
# Right.
else:
return x, y + 1
| HierarchicalSixRoomEnv |
python | apache__thrift | lib/py/src/transport/TSocket.py | {
"start": 988,
"end": 1641
} | class ____(TTransportBase):
def _resolveAddr(self):
if self._unix_socket is not None:
return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None,
self._unix_socket)]
else:
return socket.getaddrinfo(self.host,
self.port,
self._socket_family,
socket.SOCK_STREAM,
0,
socket.AI_PASSIVE)
def close(self):
if self.handle:
self.handle.close()
self.handle = None
| TSocketBase |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 31894,
"end": 32257
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a Variable."""
name: Optional[VariableName] = Field(default=None)
value: StrictVariableValue = Field(
default=None,
description="The value of the variable",
examples=["my-value"],
)
tags: Optional[list[str]] = Field(default=None)
| VariableUpdate |
python | gevent__gevent | src/greentest/3.11/test_ssl.py | {
"start": 10580,
"end": 45751
} | class ____(unittest.TestCase):
def test_constants(self):
ssl.CERT_NONE
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
ssl.OP_CIPHER_SERVER_PREFERENCE
ssl.OP_SINGLE_DH_USE
ssl.OP_SINGLE_ECDH_USE
ssl.OP_NO_COMPRESSION
self.assertEqual(ssl.HAS_SNI, True)
self.assertEqual(ssl.HAS_ECDH, True)
self.assertEqual(ssl.HAS_TLSv1_2, True)
self.assertEqual(ssl.HAS_TLSv1_3, True)
ssl.OP_NO_SSLv2
ssl.OP_NO_SSLv3
ssl.OP_NO_TLSv1
ssl.OP_NO_TLSv1_3
ssl.OP_NO_TLSv1_1
ssl.OP_NO_TLSv1_2
self.assertEqual(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv23)
def test_options(self):
# gh-106687: SSL options values are unsigned integer (uint64_t)
for name in dir(ssl):
if not name.startswith('OP_'):
continue
with self.subTest(option=name):
value = getattr(ssl, name)
self.assertGreaterEqual(value, 0, f"ssl.{name}")
def test_ssl_types(self):
ssl_types = [
_ssl._SSLContext,
_ssl._SSLSocket,
_ssl.MemoryBIO,
_ssl.Certificate,
_ssl.SSLSession,
_ssl.SSLError,
]
for ssl_type in ssl_types:
with self.subTest(ssl_type=ssl_type):
with self.assertRaisesRegex(TypeError, "immutable type"):
ssl_type.value = None
support.check_disallow_instantiation(self, _ssl.Certificate)
def test_private_init(self):
with self.assertRaisesRegex(TypeError, "public constructor"):
with socket.socket() as s:
ssl.SSLSocket(s)
def test_str_for_enums(self):
# Make sure that the PROTOCOL_* constants have enum-like string
# reprs.
proto = ssl.PROTOCOL_TLS_CLIENT
self.assertEqual(repr(proto), '<_SSLMethod.PROTOCOL_TLS_CLIENT: %r>' % proto.value)
self.assertEqual(str(proto), str(proto.value))
ctx = ssl.SSLContext(proto)
self.assertIs(ctx.protocol, proto)
def test_random(self):
v = ssl.RAND_status()
if support.verbose:
sys.stdout.write("\n RAND_status is %d (%s)\n"
% (v, (v and "sufficient randomness") or
"insufficient randomness"))
with warnings_helper.check_warnings():
data, is_cryptographic = ssl.RAND_pseudo_bytes(16)
self.assertEqual(len(data), 16)
self.assertEqual(is_cryptographic, v == 1)
if v:
data = ssl.RAND_bytes(16)
self.assertEqual(len(data), 16)
else:
self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16)
# negative num is invalid
self.assertRaises(ValueError, ssl.RAND_bytes, -5)
with warnings_helper.check_warnings():
self.assertRaises(ValueError, ssl.RAND_pseudo_bytes, -5)
ssl.RAND_add("this is a random string", 75.0)
ssl.RAND_add(b"this is a random bytes object", 75.0)
ssl.RAND_add(bytearray(b"this is a random bytearray object"), 75.0)
def test_parse_cert(self):
# note that this uses an 'unofficial' function in _ssl.c,
# provided solely for this test, to exercise the certificate
# parsing code
self.assertEqual(
ssl._ssl._test_decode_cert(CERTFILE),
CERTFILE_INFO
)
self.assertEqual(
ssl._ssl._test_decode_cert(SIGNED_CERTFILE),
SIGNED_CERTFILE_INFO
)
# Issue #13034: the subjectAltName in some certificates
# (notably projects.developer.nokia.com:443) wasn't parsed
p = ssl._ssl._test_decode_cert(NOKIACERT)
if support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
self.assertEqual(p['subjectAltName'],
(('DNS', 'projects.developer.nokia.com'),
('DNS', 'projects.forum.nokia.com'))
)
# extra OCSP and AIA fields
self.assertEqual(p['OCSP'], ('http://ocsp.verisign.com',))
self.assertEqual(p['caIssuers'],
('http://SVRIntl-G3-aia.verisign.com/SVRIntlG3.cer',))
self.assertEqual(p['crlDistributionPoints'],
('http://SVRIntl-G3-crl.verisign.com/SVRIntlG3.crl',))
def test_parse_cert_CVE_2019_5010(self):
p = ssl._ssl._test_decode_cert(TALOS_INVALID_CRLDP)
if support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
self.assertEqual(
p,
{
'issuer': (
(('countryName', 'UK'),), (('commonName', 'cody-ca'),)),
'notAfter': 'Jun 14 18:00:58 2028 GMT',
'notBefore': 'Jun 18 18:00:58 2018 GMT',
'serialNumber': '02',
'subject': ((('countryName', 'UK'),),
(('commonName',
'codenomicon-vm-2.test.lal.cisco.com'),)),
'subjectAltName': (
('DNS', 'codenomicon-vm-2.test.lal.cisco.com'),),
'version': 3
}
)
def test_parse_cert_CVE_2013_4238(self):
p = ssl._ssl._test_decode_cert(NULLBYTECERT)
if support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
subject = ((('countryName', 'US'),),
(('stateOrProvinceName', 'Oregon'),),
(('localityName', 'Beaverton'),),
(('organizationName', 'Python Software Foundation'),),
(('organizationalUnitName', 'Python Core Development'),),
(('commonName', 'null.python.org\x00example.org'),),
(('emailAddress', 'python-dev@python.org'),))
self.assertEqual(p['subject'], subject)
self.assertEqual(p['issuer'], subject)
if ssl._OPENSSL_API_VERSION >= (0, 9, 8):
san = (('DNS', 'altnull.python.org\x00example.com'),
('email', 'null@python.org\x00user@example.org'),
('URI', 'http://null.python.org\x00http://example.org'),
('IP Address', '192.0.2.1'),
('IP Address', '2001:DB8:0:0:0:0:0:1'))
else:
# OpenSSL 0.9.7 doesn't support IPv6 addresses in subjectAltName
san = (('DNS', 'altnull.python.org\x00example.com'),
('email', 'null@python.org\x00user@example.org'),
('URI', 'http://null.python.org\x00http://example.org'),
('IP Address', '192.0.2.1'),
('IP Address', '<invalid>'))
self.assertEqual(p['subjectAltName'], san)
def test_parse_all_sans(self):
p = ssl._ssl._test_decode_cert(ALLSANFILE)
self.assertEqual(p['subjectAltName'],
(
('DNS', 'allsans'),
('othername', '<unsupported>'),
('othername', '<unsupported>'),
('email', 'user@example.org'),
('DNS', 'www.example.org'),
('DirName',
((('countryName', 'XY'),),
(('localityName', 'Castle Anthrax'),),
(('organizationName', 'Python Software Foundation'),),
(('commonName', 'dirname example'),))),
('URI', 'https://www.python.org/'),
('IP Address', '127.0.0.1'),
('IP Address', '0:0:0:0:0:0:0:1'),
('Registered ID', '1.2.3.4.5')
)
)
def test_DER_to_PEM(self):
with open(CAFILE_CACERT, 'r') as f:
pem = f.read()
d1 = ssl.PEM_cert_to_DER_cert(pem)
p2 = ssl.DER_cert_to_PEM_cert(d1)
d2 = ssl.PEM_cert_to_DER_cert(p2)
self.assertEqual(d1, d2)
if not p2.startswith(ssl.PEM_HEADER + '\n'):
self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2)
if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'):
self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2)
def test_openssl_version(self):
n = ssl.OPENSSL_VERSION_NUMBER
t = ssl.OPENSSL_VERSION_INFO
s = ssl.OPENSSL_VERSION
self.assertIsInstance(n, int)
self.assertIsInstance(t, tuple)
self.assertIsInstance(s, str)
# Some sanity checks follow
# >= 1.1.1
self.assertGreaterEqual(n, 0x10101000)
# < 4.0
self.assertLess(n, 0x40000000)
major, minor, fix, patch, status = t
self.assertGreaterEqual(major, 1)
self.assertLess(major, 4)
self.assertGreaterEqual(minor, 0)
self.assertLess(minor, 256)
self.assertGreaterEqual(fix, 0)
self.assertLess(fix, 256)
self.assertGreaterEqual(patch, 0)
self.assertLessEqual(patch, 63)
self.assertGreaterEqual(status, 0)
self.assertLessEqual(status, 15)
libressl_ver = f"LibreSSL {major:d}"
if major >= 3:
# 3.x uses 0xMNN00PP0L
openssl_ver = f"OpenSSL {major:d}.{minor:d}.{patch:d}"
else:
openssl_ver = f"OpenSSL {major:d}.{minor:d}.{fix:d}"
self.assertTrue(
s.startswith((openssl_ver, libressl_ver)),
(s, t, hex(n))
)
@support.cpython_only
def test_refcycle(self):
# Issue #7943: an SSL object doesn't create reference cycles with
# itself.
s = socket.socket(socket.AF_INET)
ss = test_wrap_socket(s)
wr = weakref.ref(ss)
with warnings_helper.check_warnings(("", ResourceWarning)):
del ss
self.assertEqual(wr(), None)
def test_wrapped_unconnected(self):
# Methods on an unconnected SSLSocket propagate the original
# OSError raise by the underlying socket object.
s = socket.socket(socket.AF_INET)
with test_wrap_socket(s) as ss:
self.assertRaises(OSError, ss.recv, 1)
self.assertRaises(OSError, ss.recv_into, bytearray(b'x'))
self.assertRaises(OSError, ss.recvfrom, 1)
self.assertRaises(OSError, ss.recvfrom_into, bytearray(b'x'), 1)
self.assertRaises(OSError, ss.send, b'x')
self.assertRaises(OSError, ss.sendto, b'x', ('0.0.0.0', 0))
self.assertRaises(NotImplementedError, ss.dup)
self.assertRaises(NotImplementedError, ss.sendmsg,
[b'x'], (), 0, ('0.0.0.0', 0))
self.assertRaises(NotImplementedError, ss.recvmsg, 100)
self.assertRaises(NotImplementedError, ss.recvmsg_into,
[bytearray(100)])
def test_timeout(self):
# Issue #8524: when creating an SSL socket, the timeout of the
# original socket should be retained.
for timeout in (None, 0.0, 5.0):
s = socket.socket(socket.AF_INET)
s.settimeout(timeout)
with test_wrap_socket(s) as ss:
self.assertEqual(timeout, ss.gettimeout())
def test_openssl111_deprecations(self):
options = [
ssl.OP_NO_TLSv1,
ssl.OP_NO_TLSv1_1,
ssl.OP_NO_TLSv1_2,
ssl.OP_NO_TLSv1_3
]
protocols = [
ssl.PROTOCOL_TLSv1,
ssl.PROTOCOL_TLSv1_1,
ssl.PROTOCOL_TLSv1_2,
ssl.PROTOCOL_TLS
]
versions = [
ssl.TLSVersion.SSLv3,
ssl.TLSVersion.TLSv1,
ssl.TLSVersion.TLSv1_1,
]
for option in options:
with self.subTest(option=option):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with self.assertWarns(DeprecationWarning) as cm:
ctx.options |= option
self.assertEqual(
'ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are deprecated',
str(cm.warning)
)
for protocol in protocols:
if not has_tls_protocol(protocol):
continue
with self.subTest(protocol=protocol):
with self.assertWarns(DeprecationWarning) as cm:
ssl.SSLContext(protocol)
self.assertEqual(
f'ssl.{protocol.name} is deprecated',
str(cm.warning)
)
for version in versions:
if not has_tls_version(version):
continue
with self.subTest(version=version):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with self.assertWarns(DeprecationWarning) as cm:
ctx.minimum_version = version
version_text = '%s.%s' % (version.__class__.__name__, version.name)
self.assertEqual(
f'ssl.{version_text} is deprecated',
str(cm.warning)
)
@ignore_deprecation
def test_errors_sslwrap(self):
sock = socket.socket()
self.assertRaisesRegex(ValueError,
"certfile must be specified",
ssl.wrap_socket, sock, keyfile=CERTFILE)
self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True)
self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True, certfile="")
with ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE) as s:
self.assertRaisesRegex(ValueError, "can't connect in server-side mode",
s.connect, (HOST, 8080))
with self.assertRaises(OSError) as cm:
with socket.socket() as sock:
ssl.wrap_socket(sock, certfile=NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaises(OSError) as cm:
with socket.socket() as sock:
ssl.wrap_socket(sock,
certfile=CERTFILE, keyfile=NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaises(OSError) as cm:
with socket.socket() as sock:
ssl.wrap_socket(sock,
certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
def bad_cert_test(self, certfile):
"""Check that trying to use the given client certificate fails"""
certfile = os.path.join(os.path.dirname(__file__) or os.curdir,
"certdata", certfile)
sock = socket.socket()
self.addCleanup(sock.close)
with self.assertRaises(ssl.SSLError):
test_wrap_socket(sock,
certfile=certfile)
def test_empty_cert(self):
"""Wrapping with an empty cert file"""
self.bad_cert_test("nullcert.pem")
def test_malformed_cert(self):
"""Wrapping with a badly formatted certificate (syntax error)"""
self.bad_cert_test("badcert.pem")
def test_malformed_key(self):
"""Wrapping with a badly formatted key (syntax error)"""
self.bad_cert_test("badkey.pem")
@ignore_deprecation
def test_match_hostname(self):
def ok(cert, hostname):
ssl.match_hostname(cert, hostname)
def fail(cert, hostname):
self.assertRaises(ssl.CertificateError,
ssl.match_hostname, cert, hostname)
# -- Hostname matching --
cert = {'subject': ((('commonName', 'example.com'),),)}
ok(cert, 'example.com')
ok(cert, 'ExAmple.cOm')
fail(cert, 'www.example.com')
fail(cert, '.example.com')
fail(cert, 'example.org')
fail(cert, 'exampleXcom')
cert = {'subject': ((('commonName', '*.a.com'),),)}
ok(cert, 'foo.a.com')
fail(cert, 'bar.foo.a.com')
fail(cert, 'a.com')
fail(cert, 'Xa.com')
fail(cert, '.a.com')
# only match wildcards when they are the only thing
# in left-most segment
cert = {'subject': ((('commonName', 'f*.com'),),)}
fail(cert, 'foo.com')
fail(cert, 'f.com')
fail(cert, 'bar.com')
fail(cert, 'foo.a.com')
fail(cert, 'bar.foo.com')
# NULL bytes are bad, CVE-2013-4073
cert = {'subject': ((('commonName',
'null.python.org\x00example.org'),),)}
ok(cert, 'null.python.org\x00example.org') # or raise an error?
fail(cert, 'example.org')
fail(cert, 'null.python.org')
# error cases with wildcards
cert = {'subject': ((('commonName', '*.*.a.com'),),)}
fail(cert, 'bar.foo.a.com')
fail(cert, 'a.com')
fail(cert, 'Xa.com')
fail(cert, '.a.com')
cert = {'subject': ((('commonName', 'a.*.com'),),)}
fail(cert, 'a.foo.com')
fail(cert, 'a..com')
fail(cert, 'a.com')
# wildcard doesn't match IDNA prefix 'xn--'
idna = 'püthon.python.org'.encode("idna").decode("ascii")
cert = {'subject': ((('commonName', idna),),)}
ok(cert, idna)
cert = {'subject': ((('commonName', 'x*.python.org'),),)}
fail(cert, idna)
cert = {'subject': ((('commonName', 'xn--p*.python.org'),),)}
fail(cert, idna)
# wildcard in first fragment and IDNA A-labels in sequent fragments
# are supported.
idna = 'www*.pythön.org'.encode("idna").decode("ascii")
cert = {'subject': ((('commonName', idna),),)}
fail(cert, 'www.pythön.org'.encode("idna").decode("ascii"))
fail(cert, 'www1.pythön.org'.encode("idna").decode("ascii"))
fail(cert, 'ftp.pythön.org'.encode("idna").decode("ascii"))
fail(cert, 'pythön.org'.encode("idna").decode("ascii"))
# Slightly fake real-world example
cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT',
'subject': ((('commonName', 'linuxfrz.org'),),),
'subjectAltName': (('DNS', 'linuxfr.org'),
('DNS', 'linuxfr.com'),
('othername', '<unsupported>'))}
ok(cert, 'linuxfr.org')
ok(cert, 'linuxfr.com')
# Not a "DNS" entry
fail(cert, '<unsupported>')
# When there is a subjectAltName, commonName isn't used
fail(cert, 'linuxfrz.org')
# A pristine real-world example
cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
'subject': ((('countryName', 'US'),),
(('stateOrProvinceName', 'California'),),
(('localityName', 'Mountain View'),),
(('organizationName', 'Google Inc'),),
(('commonName', 'mail.google.com'),))}
ok(cert, 'mail.google.com')
fail(cert, 'gmail.com')
# Only commonName is considered
fail(cert, 'California')
# -- IPv4 matching --
cert = {'subject': ((('commonName', 'example.com'),),),
'subjectAltName': (('DNS', 'example.com'),
('IP Address', '10.11.12.13'),
('IP Address', '14.15.16.17'),
('IP Address', '127.0.0.1'))}
ok(cert, '10.11.12.13')
ok(cert, '14.15.16.17')
# socket.inet_ntoa(socket.inet_aton('127.1')) == '127.0.0.1'
fail(cert, '127.1')
fail(cert, '14.15.16.17 ')
fail(cert, '14.15.16.17 extra data')
fail(cert, '14.15.16.18')
fail(cert, 'example.net')
# -- IPv6 matching --
if socket_helper.IPV6_ENABLED:
cert = {'subject': ((('commonName', 'example.com'),),),
'subjectAltName': (
('DNS', 'example.com'),
('IP Address', '2001:0:0:0:0:0:0:CAFE\n'),
('IP Address', '2003:0:0:0:0:0:0:BABA\n'))}
ok(cert, '2001::cafe')
ok(cert, '2003::baba')
fail(cert, '2003::baba ')
fail(cert, '2003::baba extra data')
fail(cert, '2003::bebe')
fail(cert, 'example.net')
# -- Miscellaneous --
# Neither commonName nor subjectAltName
cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
'subject': ((('countryName', 'US'),),
(('stateOrProvinceName', 'California'),),
(('localityName', 'Mountain View'),),
(('organizationName', 'Google Inc'),))}
fail(cert, 'mail.google.com')
# No DNS entry in subjectAltName but a commonName
cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT',
'subject': ((('countryName', 'US'),),
(('stateOrProvinceName', 'California'),),
(('localityName', 'Mountain View'),),
(('commonName', 'mail.google.com'),)),
'subjectAltName': (('othername', 'blabla'), )}
ok(cert, 'mail.google.com')
# No DNS entry subjectAltName and no commonName
cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT',
'subject': ((('countryName', 'US'),),
(('stateOrProvinceName', 'California'),),
(('localityName', 'Mountain View'),),
(('organizationName', 'Google Inc'),)),
'subjectAltName': (('othername', 'blabla'),)}
fail(cert, 'google.com')
# Empty cert / no cert
self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com')
self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com')
# Issue #17980: avoid denials of service by refusing more than one
# wildcard per fragment.
cert = {'subject': ((('commonName', 'a*b.example.com'),),)}
with self.assertRaisesRegex(
ssl.CertificateError,
"partial wildcards in leftmost label are not supported"):
ssl.match_hostname(cert, 'axxb.example.com')
cert = {'subject': ((('commonName', 'www.*.example.com'),),)}
with self.assertRaisesRegex(
ssl.CertificateError,
"wildcard can only be present in the leftmost label"):
ssl.match_hostname(cert, 'www.sub.example.com')
cert = {'subject': ((('commonName', 'a*b*.example.com'),),)}
with self.assertRaisesRegex(
ssl.CertificateError,
"too many wildcards"):
ssl.match_hostname(cert, 'axxbxxc.example.com')
cert = {'subject': ((('commonName', '*'),),)}
with self.assertRaisesRegex(
ssl.CertificateError,
"sole wildcard without additional labels are not support"):
ssl.match_hostname(cert, 'host')
cert = {'subject': ((('commonName', '*.com'),),)}
with self.assertRaisesRegex(
ssl.CertificateError,
r"hostname 'com' doesn't match '\*.com'"):
ssl.match_hostname(cert, 'com')
# extra checks for _inet_paton()
for invalid in ['1', '', '1.2.3', '256.0.0.1', '127.0.0.1/24']:
with self.assertRaises(ValueError):
ssl._inet_paton(invalid)
for ipaddr in ['127.0.0.1', '192.168.0.1']:
self.assertTrue(ssl._inet_paton(ipaddr))
if socket_helper.IPV6_ENABLED:
for ipaddr in ['::1', '2001:db8:85a3::8a2e:370:7334']:
self.assertTrue(ssl._inet_paton(ipaddr))
def test_server_side(self):
# server_hostname doesn't work for server sockets
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
with socket.socket() as sock:
self.assertRaises(ValueError, ctx.wrap_socket, sock, True,
server_hostname="some.hostname")
def test_unknown_channel_binding(self):
# should raise ValueError for unknown type
s = socket.create_server(('127.0.0.1', 0))
c = socket.socket(socket.AF_INET)
c.connect(s.getsockname())
with test_wrap_socket(c, do_handshake_on_connect=False) as ss:
with self.assertRaises(ValueError):
ss.get_channel_binding("unknown-type")
s.close()
@unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES,
"'tls-unique' channel binding not available")
def test_tls_unique_channel_binding(self):
# unconnected should return None for known type
s = socket.socket(socket.AF_INET)
with test_wrap_socket(s) as ss:
self.assertIsNone(ss.get_channel_binding("tls-unique"))
# the same for server-side
s = socket.socket(socket.AF_INET)
with test_wrap_socket(s, server_side=True, certfile=CERTFILE) as ss:
self.assertIsNone(ss.get_channel_binding("tls-unique"))
def test_dealloc_warn(self):
ss = test_wrap_socket(socket.socket(socket.AF_INET))
r = repr(ss)
with self.assertWarns(ResourceWarning) as cm:
ss = None
support.gc_collect()
self.assertIn(r, str(cm.warning.args[0]))
def test_get_default_verify_paths(self):
paths = ssl.get_default_verify_paths()
self.assertEqual(len(paths), 6)
self.assertIsInstance(paths, ssl.DefaultVerifyPaths)
with os_helper.EnvironmentVarGuard() as env:
env["SSL_CERT_DIR"] = CAPATH
env["SSL_CERT_FILE"] = CERTFILE
paths = ssl.get_default_verify_paths()
self.assertEqual(paths.cafile, CERTFILE)
self.assertEqual(paths.capath, CAPATH)
@unittest.skipUnless(sys.platform == "win32", "Windows specific")
def test_enum_certificates(self):
self.assertTrue(ssl.enum_certificates("CA"))
self.assertTrue(ssl.enum_certificates("ROOT"))
self.assertRaises(TypeError, ssl.enum_certificates)
self.assertRaises(WindowsError, ssl.enum_certificates, "")
trust_oids = set()
for storename in ("CA", "ROOT"):
store = ssl.enum_certificates(storename)
self.assertIsInstance(store, list)
for element in store:
self.assertIsInstance(element, tuple)
self.assertEqual(len(element), 3)
cert, enc, trust = element
self.assertIsInstance(cert, bytes)
self.assertIn(enc, {"x509_asn", "pkcs_7_asn"})
self.assertIsInstance(trust, (frozenset, set, bool))
if isinstance(trust, (frozenset, set)):
trust_oids.update(trust)
serverAuth = "1.3.6.1.5.5.7.3.1"
self.assertIn(serverAuth, trust_oids)
@unittest.skipUnless(sys.platform == "win32", "Windows specific")
def test_enum_crls(self):
self.assertTrue(ssl.enum_crls("CA"))
self.assertRaises(TypeError, ssl.enum_crls)
self.assertRaises(WindowsError, ssl.enum_crls, "")
crls = ssl.enum_crls("CA")
self.assertIsInstance(crls, list)
for element in crls:
self.assertIsInstance(element, tuple)
self.assertEqual(len(element), 2)
self.assertIsInstance(element[0], bytes)
self.assertIn(element[1], {"x509_asn", "pkcs_7_asn"})
def test_asn1object(self):
expected = (129, 'serverAuth', 'TLS Web Server Authentication',
'1.3.6.1.5.5.7.3.1')
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1')
self.assertEqual(val, expected)
self.assertEqual(val.nid, 129)
self.assertEqual(val.shortname, 'serverAuth')
self.assertEqual(val.longname, 'TLS Web Server Authentication')
self.assertEqual(val.oid, '1.3.6.1.5.5.7.3.1')
self.assertIsInstance(val, ssl._ASN1Object)
self.assertRaises(ValueError, ssl._ASN1Object, 'serverAuth')
val = ssl._ASN1Object.fromnid(129)
self.assertEqual(val, expected)
self.assertIsInstance(val, ssl._ASN1Object)
self.assertRaises(ValueError, ssl._ASN1Object.fromnid, -1)
with self.assertRaisesRegex(ValueError, "unknown NID 100000"):
ssl._ASN1Object.fromnid(100000)
for i in range(1000):
try:
obj = ssl._ASN1Object.fromnid(i)
except ValueError:
pass
else:
self.assertIsInstance(obj.nid, int)
self.assertIsInstance(obj.shortname, str)
self.assertIsInstance(obj.longname, str)
self.assertIsInstance(obj.oid, (str, type(None)))
val = ssl._ASN1Object.fromname('TLS Web Server Authentication')
self.assertEqual(val, expected)
self.assertIsInstance(val, ssl._ASN1Object)
self.assertEqual(ssl._ASN1Object.fromname('serverAuth'), expected)
self.assertEqual(ssl._ASN1Object.fromname('1.3.6.1.5.5.7.3.1'),
expected)
with self.assertRaisesRegex(ValueError, "unknown object 'serverauth'"):
ssl._ASN1Object.fromname('serverauth')
def test_purpose_enum(self):
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1')
self.assertIsInstance(ssl.Purpose.SERVER_AUTH, ssl._ASN1Object)
self.assertEqual(ssl.Purpose.SERVER_AUTH, val)
self.assertEqual(ssl.Purpose.SERVER_AUTH.nid, 129)
self.assertEqual(ssl.Purpose.SERVER_AUTH.shortname, 'serverAuth')
self.assertEqual(ssl.Purpose.SERVER_AUTH.oid,
'1.3.6.1.5.5.7.3.1')
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.2')
self.assertIsInstance(ssl.Purpose.CLIENT_AUTH, ssl._ASN1Object)
self.assertEqual(ssl.Purpose.CLIENT_AUTH, val)
self.assertEqual(ssl.Purpose.CLIENT_AUTH.nid, 130)
self.assertEqual(ssl.Purpose.CLIENT_AUTH.shortname, 'clientAuth')
self.assertEqual(ssl.Purpose.CLIENT_AUTH.oid,
'1.3.6.1.5.5.7.3.2')
def test_unsupported_dtls(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addCleanup(s.close)
with self.assertRaises(NotImplementedError) as cx:
test_wrap_socket(s, cert_reqs=ssl.CERT_NONE)
self.assertEqual(str(cx.exception), "only stream sockets are supported")
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with self.assertRaises(NotImplementedError) as cx:
ctx.wrap_socket(s)
self.assertEqual(str(cx.exception), "only stream sockets are supported")
def cert_time_ok(self, timestring, timestamp):
self.assertEqual(ssl.cert_time_to_seconds(timestring), timestamp)
def cert_time_fail(self, timestring):
with self.assertRaises(ValueError):
ssl.cert_time_to_seconds(timestring)
@unittest.skipUnless(utc_offset(),
'local time needs to be different from UTC')
def test_cert_time_to_seconds_timezone(self):
# Issue #19940: ssl.cert_time_to_seconds() returns wrong
# results if local timezone is not UTC
self.cert_time_ok("May 9 00:00:00 2007 GMT", 1178668800.0)
self.cert_time_ok("Jan 5 09:34:43 2018 GMT", 1515144883.0)
def test_cert_time_to_seconds(self):
timestring = "Jan 5 09:34:43 2018 GMT"
ts = 1515144883.0
self.cert_time_ok(timestring, ts)
# accept keyword parameter, assert its name
self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts)
# accept both %e and %d (space or zero generated by strftime)
self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts)
# case-insensitive
self.cert_time_ok("JaN 5 09:34:43 2018 GmT", ts)
self.cert_time_fail("Jan 5 09:34 2018 GMT") # no seconds
self.cert_time_fail("Jan 5 09:34:43 2018") # no GMT
self.cert_time_fail("Jan 5 09:34:43 2018 UTC") # not GMT timezone
self.cert_time_fail("Jan 35 09:34:43 2018 GMT") # invalid day
self.cert_time_fail("Jon 5 09:34:43 2018 GMT") # invalid month
self.cert_time_fail("Jan 5 24:00:00 2018 GMT") # invalid hour
self.cert_time_fail("Jan 5 09:60:43 2018 GMT") # invalid minute
newyear_ts = 1230768000.0
# leap seconds
self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts)
# same timestamp
self.cert_time_ok("Jan 1 00:00:00 2009 GMT", newyear_ts)
self.cert_time_ok("Jan 5 09:34:59 2018 GMT", 1515144899)
# allow 60th second (even if it is not a leap second)
self.cert_time_ok("Jan 5 09:34:60 2018 GMT", 1515144900)
# allow 2nd leap second for compatibility with time.strptime()
self.cert_time_ok("Jan 5 09:34:61 2018 GMT", 1515144901)
self.cert_time_fail("Jan 5 09:34:62 2018 GMT") # invalid seconds
# no special treatment for the special value:
# 99991231235959Z (rfc 5280)
self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0)
@support.run_with_locale('LC_ALL', '')
def test_cert_time_to_seconds_locale(self):
# `cert_time_to_seconds()` should be locale independent
def local_february_name():
return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0))
if local_february_name().lower() == 'feb':
self.skipTest("locale-specific month name needs to be "
"different from C locale")
# locale-independent
self.cert_time_ok("Feb 9 00:00:00 2007 GMT", 1170979200.0)
self.cert_time_fail(local_february_name() + " 9 00:00:00 2007 GMT")
def test_connect_ex_error(self):
server = socket.socket(socket.AF_INET)
self.addCleanup(server.close)
port = socket_helper.bind_port(server) # Reserve port but don't listen
s = test_wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED)
self.addCleanup(s.close)
rc = s.connect_ex((HOST, port))
# Issue #19919: Windows machines or VMs hosted on Windows
# machines sometimes return EWOULDBLOCK.
errors = (
errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
errno.EWOULDBLOCK,
)
self.assertIn(rc, errors)
def test_read_write_zero(self):
# empty reads and writes now work, bpo-42854, bpo-31711
client_context, server_context, hostname = testing_context()
server = ThreadedEchoServer(context=server_context)
with server:
with client_context.wrap_socket(socket.socket(),
server_hostname=hostname) as s:
s.connect((HOST, server.port))
self.assertEqual(s.recv(0), b"")
self.assertEqual(s.send(b""), 0)
| BasicSocketTests |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/tfr_gen.py | {
"start": 53978,
"end": 57148
} | class ____(transpiler.GenericTranspiler):
"""Transforms Python objects into TFR MLIR source code."""
def __init__(self, op_defs):
self._op_defs = op_defs
def transform_ast(self, node, ctx):
node = _apply_py_to_tf_passes(node, ctx)
# TODO(mdan): Enable this.
# node = anf.transform(node, ctx)
graphs = cfg.build(node)
node = qual_names.resolve(node)
node = activity.resolve(node, ctx)
node = reaching_definitions.resolve(node, ctx, graphs)
node = reaching_fndefs.resolve(node, ctx, graphs)
node = type_inference.resolve(node, ctx, graphs,
TFRTypeResolver(self._op_defs))
mlir_generator = TFRGen(ctx, self._op_defs)
mlir_generator.visit(node)
return mlir_generator.code_buffer
def tfr_gen(func, op_defs):
"""Parse a function and emit the TFR functions."""
mlir_code, _ = TfrGen(op_defs).transform(func, None)
assert tfr.verify(mlir_code), 'mlir code not verified: {}'.format(mlir_code)
return mlir_code
def tfr_funcs_gen_from_module(source, op_defs, method_prefix=None,
op_libraries=None):
"""Parse the input source module and emit the TFR functions."""
# Load the op library so the op is added to the op registry. This is
# required when the op cc_library couldn't be statically linked in open
# source.
# This is a no op if the op shared library couldn't be found in the same
# directory of the op Python API.
# TODO(fengliuai): make the .so file path configurable.
if op_libraries:
prefix_len = len('gen_')
for m in op_libraries:
lib_dir = os.path.dirname(m.__file__)
lib_name = os.path.basename(m.__file__)[prefix_len:].replace('.py', '.so')
lib_path = os.path.join(lib_dir, lib_name)
if os.path.exists(lib_path):
logging.info('load file: ' + lib_path)
load_library.load_op_library(lib_path)
else:
# The op library is generated from the source module, then we load all the
# .so file in the directory
lib_dir = os.path.dirname(source.__file__)
for lib_name in os.listdir(lib_dir):
if lib_name.endswith('.so'):
lib_path = os.path.join(lib_dir, lib_name)
logging.info('load file: ' + lib_path)
load_library.load_op_library(lib_path)
py_funcs = [
func
for name, func in tf_inspect.getmembers(source, tf_inspect.isfunction)
if not method_prefix or name.startswith(method_prefix)
]
# Sort the methods by the line number, to make sure the definitions are
# processed before the usages.
# TODO(fengliuai): Use type inference resolver to recursively process any
# functions called.
py_funcs = sorted(py_funcs, key=lambda x: x.__code__.co_firstlineno)
mlir_funcs = [tfr_gen(func, op_defs) for func in py_funcs]
return mlir_funcs
def tfr_gen_from_module(source, method_prefix=None, op_libraries=None,
op_defs=OpDefCache()):
"""Parse the input source module and emit the TFR and external functions."""
mlir_funcs = tfr_funcs_gen_from_module(
source, op_defs, method_prefix, op_libraries)
return '\n'.join(mlir_funcs + op_defs.mlir_external_funcs())
| TfrGen |
python | PyCQA__pylint | tests/functional/m/member/member_checks.py | {
"start": 589,
"end": 1995
} | class ____:
"""use provider class"""
def __init__(self):
self._prov = Provider()
self._prov_attr = Provider.cattr
self._prov_attr2 = Provider.cattribute # [no-member]
self.set_later = 0
def set_set_later(self, value):
"""set set_later attribute (introduce an inference ambiguity)"""
self.set_later = value
def use_method(self):
"""use provider's method"""
self._prov.hophop()
self._prov.hophophop() # [no-member]
def use_attr(self):
"""use provider's attr"""
print(self._prov.attr)
print(self._prov.attribute) # [no-member]
def debug(self):
"""print debug information"""
print(self.__class__.__name__)
print(self.__doc__)
print(self.__dict__)
print(self.__module__)
def test_bt_types(self):
"""test access to unexistant member of builtin types"""
lis = []
lis.apppend(self) # [no-member]
dic = {}
dic.set(self) # [no-member]
tup = ()
tup.append(self) # [no-member]
string = 'toto'
print(string.loower()) # [no-member]
integer = 1
print(integer.whatever) # [no-member]
def test_no_false_positives(self):
none = None
print(none.whatever)
# No misssing in the parents.
super().misssing() # [no-member]
| Client |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 1903,
"end": 2259
} | class ____(hp.HasProps):
int1 = Int(default=10)
ds1 = NumberSpec(default=field("x"))
lst1 = List(String)
@property
def foo_prop(self) -> int:
return 110
def foo_func(self) -> int:
return 111
@property
def _foo_prop(self) -> int:
return 1100
def _foo_func(self) -> int:
return 1110
| Parent |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/automations.py | {
"start": 22139,
"end": 22294
} | class ____(ActionBaseModel, extra="forbid"):
enabled: bool = Field(True, description="Whether this automation will be evaluated")
| AutomationPartialUpdate |
python | conda__conda | conda/core/package_cache_data.py | {
"start": 3116,
"end": 21496
} | class ____(metaclass=PackageCacheType):
_cache_: dict[str, PackageCacheData] = {}
def __init__(self, pkgs_dir):
self.pkgs_dir = pkgs_dir
self.__package_cache_records = None
self.__is_writable = NULL
self._urls_data = UrlsData(pkgs_dir)
def insert(self, package_cache_record):
meta = join(
package_cache_record.extracted_package_dir, "info", "repodata_record.json"
)
write_as_json_to_file(meta, PackageRecord.from_objects(package_cache_record))
self._package_cache_records[package_cache_record] = package_cache_record
def load(self):
self.__package_cache_records = _package_cache_records = {}
self._check_writable() # called here to create the cache if it doesn't exist
if not isdir(self.pkgs_dir):
# no directory exists, and we didn't have permissions to create it
return
_CONDA_TARBALL_EXTENSIONS = CONDA_PACKAGE_EXTENSIONS
pkgs_dir_contents = tuple(entry.name for entry in scandir(self.pkgs_dir))
for base_name in self._dedupe_pkgs_dir_contents(pkgs_dir_contents):
full_path = join(self.pkgs_dir, base_name)
if islink(full_path):
continue
elif (
isdir(full_path)
and isfile(join(full_path, "info", "index.json"))
or isfile(full_path)
and full_path.endswith(_CONDA_TARBALL_EXTENSIONS)
):
try:
package_cache_record = self._make_single_record(base_name)
except ValidationError as err:
# ValidationError: package fields are invalid
log.warning(
f"Failed to create package cache record for '{base_name}'. {err}"
)
package_cache_record = None
# if package_cache_record is None, it means we couldn't create a record, ignore
if package_cache_record:
_package_cache_records[package_cache_record] = package_cache_record
def reload(self):
self.load()
return self
def get(self, package_ref: PackageRecord, default=NULL):
if not isinstance(package_ref, PackageRecord):
raise TypeError("`package_ref` must be a PackageRecord instance.")
try:
return self._package_cache_records[package_ref]
except KeyError:
if default is not NULL:
return default
else:
raise
def remove(self, package_ref, default=NULL):
if default is NULL:
return self._package_cache_records.pop(package_ref)
else:
return self._package_cache_records.pop(package_ref, default)
def query(self, package_ref_or_match_spec):
# returns a generator
param = package_ref_or_match_spec
if isinstance(param, str):
param = MatchSpec(param)
if isinstance(param, MatchSpec):
return (
pcrec
for pcrec in self._package_cache_records.values()
if param.match(pcrec)
)
else:
if not isinstance(param, PackageRecord):
raise TypeError("`package_ref` must be a PackageRecord instance.")
return (
pcrec
for pcrec in self._package_cache_records.values()
if pcrec == param
)
def iter_records(self):
return iter(self._package_cache_records)
@classmethod
def query_all(cls, package_ref_or_match_spec, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
return chain.from_iterable(
pcache.query(package_ref_or_match_spec)
for pcache in cls.all_caches_writable_first(pkgs_dirs)
)
# ##########################################################################################
# these class methods reach across all package cache directories (usually context.pkgs_dirs)
# ##########################################################################################
@classmethod
def first_writable(cls, pkgs_dirs=None):
# Calling this method will *create* a package cache directory if one does not already
# exist. Any caller should intend to *use* that directory for *writing*, not just reading.
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
for pkgs_dir in pkgs_dirs:
package_cache = cls(pkgs_dir)
i_wri = package_cache.is_writable
if i_wri is True:
return package_cache
elif i_wri is None:
# means package cache directory doesn't exist, need to try to create it
try:
created = create_package_cache_directory(package_cache.pkgs_dir)
except NotWritableError:
continue
if created:
package_cache.__is_writable = True
return package_cache
raise NoWritablePkgsDirError(pkgs_dirs)
@classmethod
def writable_caches(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
writable_caches = tuple(
filter(lambda c: c.is_writable, (cls(pd) for pd in pkgs_dirs))
)
return writable_caches
@classmethod
def read_only_caches(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
read_only_caches = tuple(
filter(lambda c: not c.is_writable, (cls(pd) for pd in pkgs_dirs))
)
return read_only_caches
@classmethod
def all_caches_writable_first(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
pc_groups = groupby(lambda pc: pc.is_writable, (cls(pd) for pd in pkgs_dirs))
return (*pc_groups.get(True, ()), *pc_groups.get(False, ()))
@classmethod
def get_all_extracted_entries(cls):
package_caches = (cls(pd) for pd in context.pkgs_dirs)
return tuple(
pc_entry
for pc_entry in chain.from_iterable(
package_cache.values() for package_cache in package_caches
)
if pc_entry.is_extracted
)
@classmethod
def get_entry_to_link(cls, package_ref):
pc_entry = next(
(pcrec for pcrec in cls.query_all(package_ref) if pcrec.is_extracted), None
)
if pc_entry is not None:
return pc_entry
# this can happen with `conda install path/to/package.tar.bz2`
# because dist has channel '<unknown>'
# if ProgressiveFetchExtract did its job correctly, what we're looking for
# should be the matching dist_name in the first writable package cache
# we'll search all caches for a match, but search writable caches first
dist_str = package_ref.dist_str().rsplit(":", 1)[-1]
pc_entry = next(
(
cache._scan_for_dist_no_channel(dist_str)
for cache in cls.all_caches_writable_first()
if cache
),
None,
)
if pc_entry is not None:
return pc_entry
raise CondaError(
f"No package '{package_ref.dist_str()}' found in cache directories."
)
@classmethod
def tarball_file_in_cache(cls, tarball_path, md5sum=None, exclude_caches=()):
tarball_full_path, md5sum = cls._clean_tarball_path_and_get_md5sum(
tarball_path, md5sum
)
pc_entry = first(
cls(pkgs_dir).tarball_file_in_this_cache(tarball_full_path, md5sum)
for pkgs_dir in context.pkgs_dirs
if pkgs_dir not in exclude_caches
)
return pc_entry
@classmethod
def clear(cls):
cls._cache_.clear()
def tarball_file_in_this_cache(self, tarball_path, md5sum=None):
tarball_full_path, md5sum = self._clean_tarball_path_and_get_md5sum(
tarball_path, md5sum
)
tarball_basename = basename(tarball_full_path)
pc_entry = first(
(pc_entry for pc_entry in self.values()),
key=lambda pce: pce.tarball_basename == tarball_basename
and pce.md5 == md5sum,
)
return pc_entry
@property
def _package_cache_records(self):
# don't actually populate _package_cache_records until we need it
if self.__package_cache_records is None:
self.load()
return self.__package_cache_records
@property
def is_writable(self):
# returns None if package cache directory does not exist / has not been created
if self.__is_writable is NULL:
return self._check_writable()
return self.__is_writable
def _check_writable(self):
magic_file = join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE)
if isfile(magic_file):
i_wri = file_path_is_writable(join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE))
self.__is_writable = i_wri
log.debug("package cache directory '%s' writable: %s", self.pkgs_dir, i_wri)
else:
log.log(TRACE, "package cache directory '%s' does not exist", self.pkgs_dir)
self.__is_writable = i_wri = None
return i_wri
@staticmethod
def _clean_tarball_path_and_get_md5sum(tarball_path, md5sum=None):
if tarball_path.startswith("file:/"):
tarball_path = url_to_path(tarball_path)
tarball_full_path = expand(tarball_path)
if isfile(tarball_full_path) and md5sum is None:
md5sum = compute_sum(tarball_full_path, "md5")
return tarball_full_path, md5sum
def _scan_for_dist_no_channel(self, dist_str):
return next(
(
pcrec
for pcrec in self._package_cache_records
if pcrec.dist_str().rsplit(":", 1)[-1] == dist_str
),
None,
)
def itervalues(self):
return iter(self.values())
def values(self):
return self._package_cache_records.values()
def __repr__(self):
args = (f"{key}={getattr(self, key)!r}" for key in ("pkgs_dir",))
return "{}({})".format(self.__class__.__name__, ", ".join(args))
def _make_single_record(self, package_filename):
# delay-load this to help make sure libarchive can be found
from conda_package_handling.api import InvalidArchiveError
package_tarball_full_path = join(self.pkgs_dir, package_filename)
log.log(TRACE, "adding to package cache %s", package_tarball_full_path)
extracted_package_dir, pkg_ext = strip_pkg_extension(package_tarball_full_path)
# try reading info/repodata_record.json
try:
repodata_record = read_repodata_json(extracted_package_dir)
package_cache_record = PackageCacheRecord.from_objects(
repodata_record,
package_tarball_full_path=package_tarball_full_path,
extracted_package_dir=extracted_package_dir,
)
return package_cache_record
except (OSError, json.JSONDecodeError, ValueError, FileNotFoundError) as e:
# EnvironmentError: info/repodata_record.json doesn't exists
# json.JSONDecodeError: info/repodata_record.json is partially extracted or corrupted
# python 2.7 raises ValueError instead of json.JSONDecodeError
# ValueError("No JSON object could be decoded")
log.debug(
"unable to read %s\n because %r",
join(extracted_package_dir, "info", "repodata_record.json"),
e,
)
# try reading info/index.json
try:
raw_json_record = read_index_json(extracted_package_dir)
except (OSError, json.JSONDecodeError, ValueError, FileNotFoundError) as e:
# EnvironmentError: info/index.json doesn't exist
# json.JSONDecodeError: info/index.json is partially extracted or corrupted
# python 2.7 raises ValueError instead of json.JSONDecodeError
# ValueError("No JSON object could be decoded")
log.debug(
"unable to read %s\n because %r",
join(extracted_package_dir, "info", "index.json"),
e,
)
if isdir(extracted_package_dir) and not isfile(
package_tarball_full_path
):
# We have a directory that looks like a conda package, but without
# (1) info/repodata_record.json or info/index.json, and (2) a conda package
# tarball, there's not much we can do. We'll just ignore it.
return None
try:
if self.is_writable:
if isdir(extracted_package_dir):
# We have a partially unpacked conda package directory. Best thing
# to do is remove it and try extracting.
rm_rf(extracted_package_dir)
try:
extract_tarball(
package_tarball_full_path, extracted_package_dir
)
except (OSError, InvalidArchiveError) as e:
if e.errno == ENOENT:
# FileNotFoundError(2, 'No such file or directory')
# At this point, we can assume the package tarball is bad.
# Remove everything and move on.
# see https://github.com/conda/conda/issues/6707
rm_rf(package_tarball_full_path)
rm_rf(extracted_package_dir)
return None
try:
raw_json_record = read_index_json(extracted_package_dir)
except (OSError, json.JSONDecodeError, FileNotFoundError):
# At this point, we can assume the package tarball is bad.
# Remove everything and move on.
rm_rf(package_tarball_full_path)
rm_rf(extracted_package_dir)
return None
else:
raw_json_record = read_index_json_from_tarball(
package_tarball_full_path
)
except (
EOFError,
ReadError,
FileNotFoundError,
InvalidArchiveError,
) as e:
# EOFError: Compressed file ended before the end-of-stream marker was reached
# tarfile.ReadError: file could not be opened successfully
# We have a corrupted tarball. Remove the tarball so it doesn't affect
# anything, and move on.
log.debug(
"unable to extract info/index.json from %s\n because %r",
package_tarball_full_path,
e,
)
rm_rf(package_tarball_full_path)
return None
# we were able to read info/index.json, so let's continue
if isfile(package_tarball_full_path):
md5 = compute_sum(package_tarball_full_path, "md5")
else:
md5 = None
url = self._urls_data.get_url(package_filename)
package_cache_record = PackageCacheRecord.from_objects(
raw_json_record,
url=url,
fn=basename(package_tarball_full_path),
md5=md5,
size=getsize(package_tarball_full_path),
package_tarball_full_path=package_tarball_full_path,
extracted_package_dir=extracted_package_dir,
)
# write the info/repodata_record.json file so we can short-circuit this next time
if self.is_writable:
repodata_record = PackageRecord.from_objects(package_cache_record)
repodata_record_path = join(
extracted_package_dir, "info", "repodata_record.json"
)
try:
write_as_json_to_file(repodata_record_path, repodata_record)
except OSError as e:
if e.errno in (EACCES, EPERM, EROFS) and isdir(
dirname(repodata_record_path)
):
raise NotWritableError(
repodata_record_path, e.errno, caused_by=e
)
else:
raise
return package_cache_record
@staticmethod
def _dedupe_pkgs_dir_contents(pkgs_dir_contents):
# if both 'six-1.10.0-py35_0/' and 'six-1.10.0-py35_0.tar.bz2' are in pkgs_dir,
# only 'six-1.10.0-py35_0.tar.bz2' will be in the return contents
if not pkgs_dir_contents:
return []
_CONDA_TARBALL_EXTENSION_V1 = CONDA_PACKAGE_EXTENSION_V1
_CONDA_TARBALL_EXTENSION_V2 = CONDA_PACKAGE_EXTENSION_V2
_strip_pkg_extension = strip_pkg_extension
groups = defaultdict(set)
any(
groups[ext].add(fn_root)
for fn_root, ext in (_strip_pkg_extension(fn) for fn in pkgs_dir_contents)
)
conda_extensions = groups[_CONDA_TARBALL_EXTENSION_V2]
tar_bz2_extensions = groups[_CONDA_TARBALL_EXTENSION_V1] - conda_extensions
others = groups[None] - conda_extensions - tar_bz2_extensions
return sorted(
(
*(path + _CONDA_TARBALL_EXTENSION_V2 for path in conda_extensions),
*(path + _CONDA_TARBALL_EXTENSION_V1 for path in tar_bz2_extensions),
*others,
)
)
| PackageCacheData |
python | wntrblm__nox | nox/virtualenv.py | {
"start": 11698,
"end": 12342
} | class ____(ProcessEnv):
"""Represents the environment used to run Nox itself
For now, this class is empty but it might contain tools to grasp some
hints about the actual env.
"""
conda_cmd = "conda"
@staticmethod
def is_offline() -> bool:
"""As of now this is only used in conda_install"""
return CondaEnv.is_offline() # pragma: no cover
def create(self) -> bool:
"""Does nothing, since this is an existing environment. Always returns
False since it's always reused."""
return False
@property
def venv_backend(self) -> str:
return "none"
| PassthroughEnv |
python | spack__spack | lib/spack/spack/stage.py | {
"start": 33914,
"end": 48244
} | class ____(AbstractStage):
requires_patch_success = False
def __init__(self, name, dev_path, reference_link):
super().__init__(name=name, path=None, keep=False, lock=True)
self.dev_path = dev_path
self._source_path = dev_path
# The path of a link that will point to this stage
if os.path.isabs(reference_link):
link_path = reference_link
else:
link_path = os.path.join(self._source_path, reference_link)
if not os.path.isdir(os.path.dirname(link_path)):
raise StageError(f"The directory containing {link_path} must exist")
self.reference_link = link_path
@property
def source_path(self):
"""Returns the development source path."""
return self._source_path
@property
def archive_file(self):
return None
def fetch(self, mirror_only: bool = False, err_msg: Optional[str] = None) -> None:
tty.debug("No fetching needed for develop stage.")
def check(self):
tty.debug("No checksum needed for develop stage.")
def expand_archive(self):
tty.debug("No expansion needed for develop stage.")
@property
def expanded(self):
"""Returns True since the source_path must exist."""
return True
def create(self):
super().create()
try:
symlink(self.path, self.reference_link)
except (AlreadyExistsError, FileExistsError):
pass
def destroy(self):
# Destroy all files, but do not follow symlinks
try:
shutil.rmtree(self.path)
except FileNotFoundError:
pass
try:
os.remove(self.reference_link)
except FileNotFoundError:
pass
self.created = False
def restage(self):
self.destroy()
self.create()
def cache_local(self):
tty.debug("Sources for Develop stages are not cached")
def ensure_access(file):
"""Ensure we can access a directory and die with an error if we can't."""
if not can_access(file):
tty.die("Insufficient permissions for %s" % file)
def purge():
"""Remove all build directories in the top-level stage path."""
root = get_stage_root()
if os.path.isdir(root):
for stage_dir in os.listdir(root):
if stage_dir.startswith(stage_prefix) or stage_dir == ".lock":
stage_path = os.path.join(root, stage_dir)
if os.path.isdir(stage_path):
remove_linked_tree(stage_path)
else:
os.remove(stage_path)
def interactive_version_filter(
url_dict: Dict[StandardVersion, str],
known_versions: Iterable[StandardVersion] = (),
*,
initial_verion_filter: Optional[VersionList] = None,
url_changes: Set[StandardVersion] = set(),
input: Callable[..., str] = input,
) -> Optional[Dict[StandardVersion, str]]:
"""Interactively filter the list of spidered versions.
Args:
url_dict: Dictionary of versions to URLs
known_versions: Versions that can be skipped because they are already known
Returns:
Filtered dictionary of versions to URLs or None if the user wants to quit
"""
# Find length of longest string in the list for padding
version_filter = initial_verion_filter or VersionList([":"])
max_len = max(len(str(v)) for v in url_dict) if url_dict else 0
sorted_and_filtered = [v for v in url_dict if v.satisfies(version_filter)]
sorted_and_filtered.sort(reverse=True)
orig_url_dict = url_dict # only copy when using editor to modify
print_header = True
VERSION_COLOR = spack.spec.VERSION_COLOR
while True:
if print_header:
has_filter = version_filter != VersionList([":"])
header = []
if len(orig_url_dict) > 0 and len(sorted_and_filtered) == len(orig_url_dict):
header.append(
f"Selected {spack.llnl.string.plural(len(sorted_and_filtered), 'version')}"
)
else:
header.append(
f"Selected {len(sorted_and_filtered)} of "
f"{spack.llnl.string.plural(len(orig_url_dict), 'version')}"
)
if sorted_and_filtered and known_versions:
num_new = sum(1 for v in sorted_and_filtered if v not in known_versions)
header.append(f"{spack.llnl.string.plural(num_new, 'new version')}")
if has_filter:
header.append(colorize(f"Filtered by {VERSION_COLOR}@@{version_filter}@."))
version_with_url = [
colorize(
f"{VERSION_COLOR}{str(v):{max_len}}@. {url_dict[v]}"
f"{' @K{# NOTE: change of URL}' if v in url_changes else ''}"
)
for v in sorted_and_filtered
]
tty.msg(". ".join(header), *spack.llnl.util.lang.elide_list(version_with_url))
print()
print_header = True
tty.info(colorize("Enter @*{number} of versions to take, or use a @*{command}:"))
commands = (
"@*b{[c]}hecksum",
"@*b{[e]}dit",
"@*b{[f]}ilter",
"@*b{[a]}sk each",
"@*b{[n]}ew only",
"@*b{[r]}estart",
"@*b{[q]}uit",
)
colify(list(map(colorize, commands)), indent=4)
try:
command = input(colorize("@*g{action>} ")).strip().lower()
except EOFError:
print()
command = "q"
if command == "c":
break
elif command == "e":
# Create a temporary file in the stage dir with lines of the form
# <version> <url>
# which the user can modify. Once the editor is closed, the file is
# read back in and the versions to url dict is updated.
# Create a temporary file by hashing its contents.
buffer = io.StringIO()
buffer.write("# Edit this file to change the versions and urls to fetch\n")
for v in sorted_and_filtered:
buffer.write(f"{str(v):{max_len}} {url_dict[v]}\n")
data = buffer.getvalue().encode("utf-8")
short_hash = hashlib.sha1(data).hexdigest()[:7]
filename = f"{stage_prefix}versions-{short_hash}.txt"
filepath = os.path.join(get_stage_root(), filename)
# Write contents
with open(filepath, "wb") as f:
f.write(data)
# Open editor
editor(filepath, exec_fn=executable)
# Read back in
with open(filepath, "r", encoding="utf-8") as f:
orig_url_dict, url_dict = url_dict, {}
for line in f:
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith("#"):
continue
try:
version, url = line.split(None, 1)
except ValueError:
tty.warn(f"Couldn't parse: {line}")
continue
try:
url_dict[StandardVersion.from_string(version)] = url
except ValueError:
tty.warn(f"Invalid version: {version}")
continue
sorted_and_filtered = sorted(url_dict.keys(), reverse=True)
os.unlink(filepath)
elif command == "f":
tty.msg(
colorize(
f"Examples filters: {VERSION_COLOR}1.2@. "
f"or {VERSION_COLOR}1.1:1.3@. "
f"or {VERSION_COLOR}=1.2, 1.2.2:@."
)
)
try:
# Allow a leading @ version specifier
filter_spec = input(colorize("@*g{filter>} ")).strip().lstrip("@")
except EOFError:
print()
continue
try:
version_filter.intersect(VersionList([filter_spec]))
except ValueError:
tty.warn(f"Invalid version specifier: {filter_spec}")
continue
# Apply filter
sorted_and_filtered = [v for v in sorted_and_filtered if v.satisfies(version_filter)]
elif command == "a":
i = 0
while i < len(sorted_and_filtered):
v = sorted_and_filtered[i]
try:
answer = input(f" {str(v):{max_len}} {url_dict[v]} [Y/n]? ").strip().lower()
except EOFError:
# If ^D, don't fully exit, but go back to the command prompt, now with possibly
# fewer versions
print()
break
if answer in ("n", "no"):
del sorted_and_filtered[i]
elif answer in ("y", "yes", ""):
i += 1
else:
# Went over each version, so go to checksumming
break
elif command == "n":
sorted_and_filtered = [v for v in sorted_and_filtered if v not in known_versions]
elif command == "r":
url_dict = orig_url_dict
sorted_and_filtered = sorted(url_dict.keys(), reverse=True)
version_filter = VersionList([":"])
elif command == "q":
try:
if input("Really quit [y/N]? ").strip().lower() in ("y", "yes"):
return None
except EOFError:
print()
return None
else:
# Last restort: filter the top N versions
try:
n = int(command)
invalid_command = n < 1
except ValueError:
invalid_command = True
if invalid_command:
tty.warn(f"Ignoring invalid command: {command}")
print_header = False
continue
sorted_and_filtered = sorted_and_filtered[:n]
return {v: url_dict[v] for v in sorted_and_filtered}
def get_checksums_for_versions(
url_by_version: Dict[StandardVersion, str],
package_name: str,
*,
first_stage_function: Optional[Callable[[str, str], None]] = None,
keep_stage: bool = False,
concurrency: Optional[int] = None,
fetch_options: Optional[Dict[str, str]] = None,
) -> Dict[StandardVersion, str]:
"""Computes the checksums for each version passed in input, and returns the results.
Archives are fetched according to the usl dictionary passed as input.
The ``first_stage_function`` argument allows the caller to inspect the first downloaded
archive, e.g., to determine the build system.
Args:
url_by_version: URL keyed by version
package_name: name of the package
first_stage_function: function that takes an archive file and a URL; this is run on the
stage of the first URL downloaded
keep_stage: whether to keep staging area when command completes
batch: whether to ask user how many versions to fetch (false) or fetch all versions (true)
fetch_options: options used for the fetcher (such as timeout or cookies)
concurrency: maximum number of workers to use for retrieving archives
Returns:
A dictionary mapping each version to the corresponding checksum
"""
versions = sorted(url_by_version.keys(), reverse=True)
search_arguments = [(url_by_version[v], v) for v in versions]
version_hashes: Dict[StandardVersion, str] = {}
errors: List[str] = []
# Don't spawn 16 processes when we need to fetch 2 urls
if concurrency is not None:
concurrency = min(concurrency, len(search_arguments))
else:
concurrency = min(os.cpu_count() or 1, len(search_arguments))
# The function might have side effects in memory, that would not be reflected in the
# parent process, if run in a child process. If this pattern happens frequently, we
# can move this function call *after* having distributed the work to executors.
if first_stage_function is not None:
(url, version), search_arguments = search_arguments[0], search_arguments[1:]
result = _fetch_and_checksum(url, fetch_options, keep_stage, first_stage_function)
if isinstance(result, Exception):
errors.append(str(result))
else:
version_hashes[version] = result
with spack.util.parallel.make_concurrent_executor(concurrency, require_fork=False) as executor:
results = [
(version, executor.submit(_fetch_and_checksum, url, fetch_options, keep_stage))
for url, version in search_arguments
]
for version, future in results:
result = future.result()
if isinstance(result, Exception):
errors.append(str(result))
else:
version_hashes[version] = result
for msg in errors:
tty.debug(msg)
if not version_hashes:
tty.die(f"Could not fetch any versions for {package_name}")
num_hash = len(version_hashes)
tty.debug(f"Checksummed {num_hash} version{'' if num_hash == 1 else 's'} of {package_name}:")
return version_hashes
def _fetch_and_checksum(
url: str,
options: Optional[dict],
keep_stage: bool,
action_fn: Optional[Callable[[str, str], None]] = None,
) -> Union[str, Exception]:
try:
with Stage(fs.URLFetchStrategy(url=url, fetch_options=options), keep=keep_stage) as stage:
# Fetch the archive
stage.fetch()
archive = stage.archive_file
assert archive is not None, f"Archive not found for {url}"
if action_fn is not None and archive:
# Only run first_stage_function the first time,
# no need to run it every time
action_fn(archive, url)
# Checksum the archive and add it to the list
checksum = spack.util.crypto.checksum(hashlib.sha256, archive)
return checksum
except Exception as e:
return Exception(f"[WORKER] Failed to fetch {url}: {e}")
| DevelopStage |
python | ray-project__ray | rllib/examples/envs/classes/look_and_push.py | {
"start": 45,
"end": 1466
} | class ____(gym.Env):
"""Memory-requiring Env: Best sequence of actions depends on prev. states.
Optimal behavior:
0) a=0 -> observe next state (s'), which is the "hidden" state.
If a=1 here, the hidden state is not observed.
1) a=1 to always jump to s=2 (not matter what the prev. state was).
2) a=1 to move to s=3.
3) a=1 to move to s=4.
4) a=0 OR 1 depending on s' observed after 0): +10 reward and done.
otherwise: -10 reward and done.
"""
def __init__(self):
self.action_space = gym.spaces.Discrete(2)
self.observation_space = gym.spaces.Discrete(5)
self._state = None
self._case = None
def reset(self, *, seed=None, options=None):
self._state = 2
self._case = np.random.choice(2)
return self._state, {}
def step(self, action):
assert self.action_space.contains(action)
if self._state == 4:
if action and self._case:
return self._state, 10.0, True, {}
else:
return self._state, -10, True, {}
else:
if action:
if self._state == 0:
self._state = 2
else:
self._state += 1
elif self._state == 2:
self._state = self._case
return self._state, -1, False, False, {}
| LookAndPush |
python | walkccc__LeetCode | solutions/852. Peak Index in a Mountain Array/852.py | {
"start": 0,
"end": 238
} | class ____:
def peakIndexInMountainArray(self, arr: list[int]) -> int:
l = 0
r = len(arr) - 1
while l < r:
m = (l + r) // 2
if arr[m] >= arr[m + 1]:
r = m
else:
l = m + 1
return l
| Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 4530,
"end": 5412
} | class ____:
params = [[True, False], ["default", 1]]
param_names = ["use_numexpr", "threads"]
def setup(self, use_numexpr, threads):
self.df = DataFrame(np.random.randn(20000, 100))
self.df2 = DataFrame(np.random.randn(20000, 100))
if threads != "default":
expr.set_numexpr_threads(threads)
if not use_numexpr:
expr.set_use_numexpr(False)
def time_frame_add(self, use_numexpr, threads):
self.df + self.df2
def time_frame_mult(self, use_numexpr, threads):
self.df * self.df2
def time_frame_multi_and(self, use_numexpr, threads):
self.df[(self.df > 0) & (self.df2 > 0)]
def time_frame_comparison(self, use_numexpr, threads):
self.df > self.df2
def teardown(self, use_numexpr, threads):
expr.set_use_numexpr(True)
expr.set_numexpr_threads()
| Ops |
python | Textualize__textual | src/textual/drivers/_byte_stream.py | {
"start": 3286,
"end": 3382
} | class ____(NamedTuple):
"""A type and payload."""
type: str
payload: bytes
| BytePacket |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/parallel.py | {
"start": 13673,
"end": 22841
} | class ____(Enum):
NO_SUMMARY = 0
FAILURE = 1
SUCCESS = 2
BOTH = 3
def check_async_run_results(
results: list[ApplyResult],
success_message: str,
outputs: list[Output],
include_success_outputs: bool,
poll_time_seconds: float = 0.2,
skip_cleanup: bool = False,
summarize_on_ci: SummarizeAfter = SummarizeAfter.NO_SUMMARY,
summary_start_regexp: str | None = None,
terminated_on_timeout: bool = False,
):
"""
Check if all async results were success.
Exits with error if:
* exit code 1: some tasks failed
* exit code 2: some tasks were terminated on timeout
:param results: results of parallel runs (expected in the form of Tuple: (return_code, info)
:param outputs: outputs where results are written to
:param success_message: Success string printed when everything is OK
:param include_success_outputs: include outputs of successful parallel runs
:param poll_time_seconds: what's the poll time between checks
:param skip_cleanup: whether to skip cleanup of temporary files.
:param summarize_on_ci: determines when to summarize the parallel jobs when they are completed in CI,
outside the folded CI output
:param summary_start_regexp: the regexp that determines line after which
outputs should be printed as summary, so that you do not have to look at the folded details of
the run in CI
:param terminated_on_timeout: whether the run was terminated on timeout
"""
if terminated_on_timeout:
print_outputs_on_timeout(outputs, results, include_success_outputs)
sys.exit(2)
completed_list = wait_for_all_tasks_completed(poll_time_seconds, results)
print_async_result_status(completed_list)
print_logs_on_completion(include_success_outputs, outputs, results)
summarize_results_outside_of_folded_logs(outputs, results, summarize_on_ci, summary_start_regexp)
if finalize_async_tasks(outputs, results, skip_cleanup, success_message):
sys.exit(1)
def print_logs_on_completion(
include_success_outputs: bool, outputs: list[Output], results: list[ApplyResult]
):
for i, result in enumerate(results):
if result.get()[0] != 0:
message_type = MessageType.ERROR
else:
message_type = MessageType.SUCCESS
if message_type == MessageType.ERROR or include_success_outputs:
from airflow_breeze.utils.ci_group import ci_group
with ci_group(f"{outputs[i].escaped_title}", message_type):
os.write(1, Path(outputs[i].file_name).read_bytes())
else:
get_console().print(f"[success]{outputs[i].escaped_title} OK[/]")
def wait_for_all_tasks_completed(poll_time_seconds: float, results: list[ApplyResult]) -> list[ApplyResult]:
completed_number = 0
total_number_of_results = len(results)
completed_list = get_completed_result_list(results)
while not len(completed_list) == total_number_of_results:
current_completed_number = len(completed_list)
if current_completed_number != completed_number:
completed_number = current_completed_number
get_console().print(
f"\n[info]Completed {completed_number} out of {total_number_of_results} "
f"({completed_number / total_number_of_results:.0%}).[/]\n"
)
print_async_result_status(completed_list)
time.sleep(poll_time_seconds)
completed_list = get_completed_result_list(results)
completed_number = len(completed_list)
get_console().print(
f"\n[info]Completed {completed_number} out of {total_number_of_results} "
f"({completed_number / total_number_of_results:.0%}).[/]\n"
)
return completed_list
def finalize_async_tasks(
outputs: list[Output], results: list[ApplyResult], skip_cleanup: bool, success_message: str
) -> bool:
"""
Finalize async tasks by checking results and cleaning up temporary files.
:param outputs: List of Output objects containing file names and titles.
:param results: List of ApplyResult objects containing the results of the tasks.
:param skip_cleanup: Whether to skip cleanup of temporary files.
:param success_message: Message to print if all tasks were successful.
:return: True if there were errors, False otherwise.
"""
errors = False
for result in results:
if result.get()[0] != 0:
errors = True
if errors:
get_console().print("\n[error]There were errors when running some tasks. Quitting.[/]\n")
else:
get_console().print(f"\n[success]{success_message}[/]\n")
if not skip_cleanup:
for output in outputs:
Path(output.file_name).unlink(missing_ok=True)
from airflow_breeze.utils.docker_command_utils import fix_ownership_using_docker
fix_ownership_using_docker()
return errors
def summarize_results_outside_of_folded_logs(
outputs: list[Output],
results: list[ApplyResult],
summarize_on_ci: SummarizeAfter,
summary_start_regexp: str | None = None,
):
"""
Print summary of the results outside the folded logs in CI.
:param outputs: List of Output objects containing file names and titles.
:param results: List of ApplyResult objects containing the results of the tasks.
:param summarize_on_ci: Determines when to summarize the parallel jobs when they are completed in
CI, outside the folded CI output.
:param summary_start_regexp: The regexp that determines line after which
outputs should be printed as summary, so that you do not have to look at the folded details of
the run in CI.
"""
if summarize_on_ci == SummarizeAfter.NO_SUMMARY:
return
regex = re.compile(summary_start_regexp) if summary_start_regexp is not None else None
for i, result in enumerate(results):
failure = result.get()[0] != 0
if summarize_on_ci in [
SummarizeAfter.BOTH,
SummarizeAfter.FAILURE if failure else SummarizeAfter.SUCCESS,
]:
print_lines = False
for line in Path(outputs[i].file_name).read_bytes().decode(errors="ignore").splitlines():
if not print_lines and (regex is None or regex.match(remove_ansi_colours(line))):
print_lines = True
get_console().print(f"\n[info]Summary: {outputs[i].escaped_title:<30}:\n")
if print_lines:
print(line)
def print_outputs_on_timeout(
outputs: list[Output], results: list[ApplyResult], include_success_outputs: bool
):
"""
Print outputs of the tasks that were terminated on timeout.
This function is called when some tasks were terminated on timeout.
It prints the outputs of the tasks that were terminated on timeout,
and the outputs of the tasks that were successful if `include_success_outputs` is True.
:param outputs: list of Output objects containing file names and titles
:param results: list of ApplyResult objects containing the results of the tasks
:param include_success_outputs: whether to include outputs of successful tasks
"""
get_console().print(
"\n[warning]Some tasks were terminated on timeout. "
"Please check the logs of the tasks (below) for more details.[/]\n"
)
for i, result in enumerate(results):
try:
exit_code = result.get(timeout=0)[0]
except Exception:
exit_code = -1
if exit_code != 0:
message_type = MessageType.ERROR
else:
message_type = MessageType.SUCCESS
output = outputs[i]
if message_type == MessageType.ERROR or include_success_outputs:
from airflow_breeze.utils.ci_group import ci_group
with ci_group(f"{output.escaped_title}", message_type):
os.write(1, Path(output.file_name).read_bytes())
else:
get_console().print(f"[success]{outputs[i].escaped_title} OK[/]")
get_console().print(
"\n[warning]Some tasks were terminated on timeout. "
"Please check the logs of the tasks (above) for more details.[/]\n"
)
from airflow_breeze.utils.docker_command_utils import fix_ownership_using_docker
fix_ownership_using_docker()
@contextmanager
def run_with_pool(
parallelism: int,
all_params: list[str],
initial_time_in_seconds: int = 2,
time_in_seconds: int = int(os.environ.get("AIRFLOW_MONITOR_DELAY_TIME_IN_SECONDS", "20")),
debug_resources: bool = False,
progress_matcher: AbstractProgressInfoMatcher | None = None,
) -> Generator[tuple[Pool, list[Output]], None, None]:
get_console().print(f"Running with parallelism: {parallelism}")
pool = create_pool(parallelism)
outputs = get_output_files(all_params)
m = ParallelMonitor(
outputs=outputs,
initial_time_in_seconds=initial_time_in_seconds,
time_in_seconds=time_in_seconds,
debug_resources=debug_resources,
progress_matcher=progress_matcher,
)
m.start()
yield pool, outputs
pool.close()
pool.join()
| SummarizeAfter |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 39253,
"end": 39535
} | class ____(FieldValues):
valid_inputs = {
None: None,
'': None,
' ': None,
}
invalid_inputs = {}
outputs = {
None: '',
}
field = serializers.DecimalField(max_digits=3, decimal_places=1, allow_null=True)
| TestAllowNullDecimalField |
python | keras-team__keras | keras/src/ops/numpy_test.py | {
"start": 2852,
"end": 18309
} | class ____(testing.TestCase):
def test_add(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.add(x, y).shape, (2, 3))
def test_heaviside(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.heaviside(x, y).shape, (None, 3))
def test_hypot(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.hypot(x, y).shape, (None, 3))
def test_subtract(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.subtract(x, y).shape, (2, 3))
def test_multiply(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.multiply(x, y).shape, (2, 3))
def test_matmul(self):
x = KerasTensor((None, 3, 4))
y = KerasTensor((3, None, 4, 5))
self.assertEqual(knp.matmul(x, y).shape, (3, None, 3, 5))
def test_power(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.power(x, y).shape, (2, 3))
def test_divide(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.divide(x, y).shape, (2, 3))
def test_divide_no_nan(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.divide_no_nan(x, y).shape, (2, 3))
def test_true_divide(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.true_divide(x, y).shape, (2, 3))
def test_append(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.append(x, y).shape, (None,))
def test_arctan2(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.arctan2(x, y).shape, (2, 3))
def test_bitwise_and(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.bitwise_and(x, y).shape, (None, 3))
def test_bitwise_or(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.bitwise_or(x, y).shape, (None, 3))
def test_bitwise_xor(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.bitwise_xor(x, y).shape, (None, 3))
def test_bitwise_left_shift(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.bitwise_left_shift(x, y).shape, (None, 3))
# left_shift is same as bitwise_left_shift
def test_bitwise_right_shift(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.bitwise_right_shift(x, y).shape, (None, 3))
# right_shift is same as bitwise_right_shift
def test_cross(self):
x1 = KerasTensor((2, 3, 3))
x2 = KerasTensor((1, 3, 2))
y = KerasTensor((None, 1, 2))
self.assertEqual(knp.cross(x1, y).shape, (2, 3, 3))
self.assertEqual(knp.cross(x2, y).shape, (None, 3))
def test_einsum(self):
x = KerasTensor((None, 3))
y = KerasTensor((3, 4))
self.assertEqual(knp.einsum("ij,jk->ik", x, y).shape, (None, 4))
self.assertEqual(knp.einsum("ij,jk->ikj", x, y).shape, (None, 4, 3))
self.assertEqual(knp.einsum("ii", x).shape, ())
self.assertEqual(knp.einsum(",ij", 5, x).shape, (None, 3))
x = KerasTensor((None, 3, 4))
y = KerasTensor((None, 4, 5))
z = KerasTensor((1, 1, 1, 9))
self.assertEqual(knp.einsum("ijk,jkl->li", x, y).shape, (5, None))
self.assertEqual(knp.einsum("ijk,jkl->lij", x, y).shape, (5, None, 3))
self.assertEqual(
knp.einsum("...,...j->...j", x, y).shape, (None, 3, 4, 5)
)
self.assertEqual(
knp.einsum("i...,...j->i...j", x, y).shape, (None, 3, 4, 5)
)
self.assertEqual(knp.einsum("i...,...j", x, y).shape, (3, 4, None, 5))
self.assertEqual(
knp.einsum("i...,...j,...k", x, y, z).shape, (1, 3, 4, None, 5, 9)
)
self.assertEqual(
knp.einsum("mij,ijk,...", x, y, z).shape, (1, 1, 1, 9, 5, None)
)
with self.assertRaises(ValueError):
x = KerasTensor((None, 3))
y = KerasTensor((3, 4))
knp.einsum("ijk,jk->ik", x, y)
def test_full_like(self):
x = KerasTensor((None, 3))
self.assertEqual(knp.full_like(x, KerasTensor((1, 3))).shape, (None, 3))
x = KerasTensor((None, 3, 3))
self.assertEqual(knp.full_like(x, 2).shape, (None, 3, 3))
def test_gcd(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.gcd(x, y).shape, (2, 3))
def test_greater(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.greater(x, y).shape, (2, 3))
def test_greater_equal(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.greater_equal(x, y).shape, (2, 3))
def test_isclose(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.isclose(x, y).shape, (2, 3))
def test_isin(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.isin(x, y).shape, (None, 3))
def test_kron(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.kron(x, y).shape, (None, None))
def test_lcm(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.lcm(x, y).shape, (2, 3))
def test_less(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.less(x, y).shape, (2, 3))
def test_less_equal(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.less_equal(x, y).shape, (2, 3))
def test_linspace(self):
start = KerasTensor((None, 3, 4))
stop = KerasTensor((2, 3, 4))
self.assertEqual(
knp.linspace(start, stop, 10, axis=1).shape, (2, 10, 3, 4)
)
start = KerasTensor((None, 3))
stop = 2
self.assertEqual(
knp.linspace(start, stop, 10, axis=1).shape, (None, 10, 3)
)
def test_logical_and(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.logical_and(x, y).shape, (2, 3))
def test_logical_or(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.logical_or(x, y).shape, (2, 3))
def test_logspace(self):
start = KerasTensor((None, 3, 4))
stop = KerasTensor((2, 3, 4))
self.assertEqual(
knp.logspace(start, stop, 10, axis=1).shape, (2, 10, 3, 4)
)
start = KerasTensor((None, 3))
stop = 2
self.assertEqual(
knp.logspace(start, stop, 10, axis=1).shape, (None, 10, 3)
)
def test_maximum(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.maximum(x, y).shape, (2, 3))
def test_minimum(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.minimum(x, y).shape, (2, 3))
def test_mod(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.mod(x, y).shape, (2, 3))
def test_not_equal(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.not_equal(x, y).shape, (2, 3))
def test_outer(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.outer(x, y).shape, (None, None))
def test_quantile(self):
x = KerasTensor((None, 3))
# q as scalar
q = KerasTensor(())
self.assertEqual(knp.quantile(x, q).shape, ())
# q as 1D tensor
q = KerasTensor((2,))
self.assertEqual(knp.quantile(x, q).shape, (2,))
self.assertEqual(knp.quantile(x, q, axis=1).shape, (2, None))
self.assertEqual(
knp.quantile(x, q, axis=1, keepdims=True).shape,
(2, None, 1),
)
def test_searchsorted(self):
a = KerasTensor((None,))
v = KerasTensor((2, 3))
output = knp.searchsorted(a, v)
self.assertEqual(output.shape, v.shape)
self.assertEqual(output.dtype, "int64")
def test_take(self):
x = KerasTensor((None, 3))
self.assertEqual(knp.take(x, 1).shape, ())
self.assertEqual(knp.take(x, [1, 2]).shape, (2,))
self.assertEqual(
knp.take(x, [[1, 2], [1, 2]], axis=1).shape, (None, 2, 2)
)
x = KerasTensor((None, 3, 3))
self.assertEqual(knp.take(x, 1, axis=1).shape, (None, 3))
self.assertEqual(knp.take(x, [1, 2]).shape, (2,))
self.assertEqual(
knp.take(x, [[1, 2], [1, 2]], axis=1).shape, (None, 2, 2, 3)
)
# test with negative axis
self.assertEqual(knp.take(x, 1, axis=-2).shape, (None, 3))
# test with multi-dimensional indices
x = KerasTensor((None, 3, None, 5))
indices = KerasTensor((6, 7))
self.assertEqual(knp.take(x, indices, axis=2).shape, (None, 3, 6, 7, 5))
def test_take_along_axis(self):
x = KerasTensor((None, 3))
indices = KerasTensor((1, 3))
self.assertEqual(knp.take_along_axis(x, indices, axis=0).shape, (1, 3))
self.assertEqual(
knp.take_along_axis(x, indices, axis=1).shape, (None, 3)
)
x = KerasTensor((None, 3, 3))
indices = KerasTensor((1, 3, None))
self.assertEqual(
knp.take_along_axis(x, indices, axis=1).shape, (None, 3, 3)
)
def test_tensordot(self):
x = KerasTensor((None, 3, 4))
y = KerasTensor((3, 4))
self.assertEqual(knp.tensordot(x, y, axes=1).shape, (None, 3, 4))
self.assertEqual(knp.tensordot(x, y, axes=[[0, 1], [1, 0]]).shape, (4,))
def test_vdot(self):
x = KerasTensor((None, 3))
y = KerasTensor((None, 3))
self.assertEqual(knp.vdot(x, y).shape, ())
x = KerasTensor((None, 3, 3))
y = KerasTensor((None, 3, 3))
self.assertEqual(knp.vdot(x, y).shape, ())
def test_inner(self):
x = KerasTensor((None,))
y = KerasTensor((3,))
self.assertEqual(knp.inner(x, y).shape, ())
def test_where(self):
condition = KerasTensor((2, None, 1))
x = KerasTensor((None, 1))
y = KerasTensor((None, 3))
self.assertEqual(knp.where(condition, x, y).shape, (2, None, 3))
self.assertEqual(knp.where(condition).shape, (2, None, 1))
def test_floor_divide(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.floor_divide(x, y).shape, (2, 3))
def test_xor(self):
x = KerasTensor((None, 3))
y = KerasTensor((2, None))
self.assertEqual(knp.logical_xor(x, y).shape, (2, 3))
def test_shape_equal_basic_equality(self):
x = KerasTensor((3, 4)).shape
y = KerasTensor((3, 4)).shape
self.assertTrue(knp.shape_equal(x, y))
y = KerasTensor((3, 5)).shape
self.assertFalse(knp.shape_equal(x, y))
def test_shape_equal_allow_none(self):
x = KerasTensor((3, 4, None)).shape
y = KerasTensor((3, 4, 5)).shape
self.assertTrue(knp.shape_equal(x, y, allow_none=True))
self.assertFalse(knp.shape_equal(x, y, allow_none=False))
def test_shape_equal_different_shape_lengths(self):
x = KerasTensor((3, 4)).shape
y = KerasTensor((3, 4, 5)).shape
self.assertFalse(knp.shape_equal(x, y))
def test_shape_equal_ignore_axes(self):
x = KerasTensor((3, 4, 5)).shape
y = KerasTensor((3, 6, 5)).shape
self.assertTrue(knp.shape_equal(x, y, axis=1))
y = KerasTensor((3, 6, 7)).shape
self.assertTrue(knp.shape_equal(x, y, axis=(1, 2)))
self.assertFalse(knp.shape_equal(x, y, axis=1))
def test_shape_equal_only_none(self):
x = KerasTensor((None, None)).shape
y = KerasTensor((5, 6)).shape
self.assertTrue(knp.shape_equal(x, y, allow_none=True))
def test_shape_equal_axis_as_list(self):
x = KerasTensor((3, 4, 5)).shape
y = KerasTensor((3, 6, 5)).shape
self.assertTrue(knp.shape_equal(x, y, axis=[1]))
def test_shape_non_equal_with_negative_axis(self):
x = KerasTensor((3, 4, 5)).shape
y = KerasTensor((3, 4, 6)).shape
self.assertFalse(knp.shape_equal(x, y, axis=-2))
def test_shape_equal_with_negative_axis(self):
x = KerasTensor((3, 4, 5)).shape
y = KerasTensor((3, 4, 5)).shape
self.assertTrue(knp.shape_equal(x, y, axis=-1))
def test_shape_equal_zeros(self):
x = KerasTensor((0, 4)).shape
y = KerasTensor((0, 4)).shape
self.assertTrue(knp.shape_equal(x, y))
y = KerasTensor((0, 5)).shape
self.assertFalse(knp.shape_equal(x, y))
def test_broadcast_shapes_conversion_to_list(self):
shape1 = KerasTensor((1, 2)).shape
shape2 = KerasTensor((3, 1)).shape
expected_output = [3, 2]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
def test_broadcast_shapes_shape1_longer_than_shape2(self):
shape1 = KerasTensor((5, 3, 2)).shape
shape2 = KerasTensor((1, 3)).shape
with self.assertRaisesRegex(ValueError, "Cannot broadcast shape"):
knp.broadcast_shapes(shape1, shape2)
def test_broadcast_shapes_shape2_longer_than_shape1(self):
shape1 = KerasTensor((5, 3)).shape
shape2 = KerasTensor((2, 5, 3)).shape
expected_output = [2, 5, 3]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
def test_broadcast_shapes_broadcasting_shape1_is_1(self):
shape1 = KerasTensor((1, 3)).shape
shape2 = KerasTensor((5, 1)).shape
expected_output = [5, 3]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
def test_broadcast_shapes_broadcasting_shape1_is_none(self):
shape1 = KerasTensor((None, 3)).shape
shape2 = KerasTensor((5, 1)).shape
expected_output = [5, 3]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
shape1 = KerasTensor((None, 3)).shape
shape2 = KerasTensor((5, 3)).shape
expected_output = [5, 3]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
def test_broadcast_shapes_broadcasting_shape2_conditions(self):
shape1 = KerasTensor((5, 3, 2)).shape
shape2 = KerasTensor((1, 3, 2)).shape
expected_output = [5, 3, 2]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
shape1 = KerasTensor((5, 3, 2)).shape
shape2 = KerasTensor((1, None, 2)).shape
expected_output = [5, 3, 2]
self.assertEqual(knp.broadcast_shapes(shape1, shape2), expected_output)
| NumpyTwoInputOpsDynamicShapeTest |
python | walkccc__LeetCode | solutions/2371. Minimize Maximum Value in a Grid/2371.py | {
"start": 0,
"end": 623
} | class ____:
def minScore(self, grid: list[list[int]]) -> list[list[int]]:
m = len(grid)
n = len(grid[0])
ans = [[0] * n for _ in range(m)]
valAndIndices = []
rows = [0] * m # rows[i] := the maximum used number so far
cols = [0] * n # cols[j] := the maximum used number so far
for i in range(m):
for j in range(n):
valAndIndices.append((grid[i][j], i, j))
valAndIndices.sort()
for _, i, j in valAndIndices:
nextAvailable = max(rows[i], cols[j]) + 1
ans[i][j] = nextAvailable
rows[i] = nextAvailable
cols[j] = nextAvailable
return ans
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/migrations/0003_extra_data_default_dict.py | {
"start": 43,
"end": 413
} | class ____(migrations.Migration):
dependencies = [
("socialaccount", "0002_token_max_lengths"),
]
operations = [
migrations.AlterField(
model_name="socialaccount",
name="extra_data",
field=models.TextField(default="{}", verbose_name="extra data"),
preserve_default=True,
),
]
| Migration |
python | pytorch__pytorch | test/distributed/test_store.py | {
"start": 27137,
"end": 30570
} | class ____(TestCase):
def create_tcp_url(self):
addr = DEFAULT_HOSTNAME
port = common.find_free_port()
url = f"tcp://{addr}:{port:d}?world_size=1"
return url
def test_common_errors(self):
with self.assertRaisesRegex(ValueError, "port number missing"):
gen = dist.rendezvous("tcp://127.0.0.1?rank=0&world_size=1")
next(gen)
with self.assertRaisesRegex(ValueError, "rank parameter missing"):
gen = dist.rendezvous("tcp://127.0.0.1:23456?world_size=1")
next(gen)
with self.assertRaisesRegex(ValueError, "size parameter missing"):
gen = dist.rendezvous("tcp://127.0.0.1:23456?rank=0")
next(gen)
def test_dns_timeout(self):
with self.assertRaisesRegex(
DistNetworkError, "client socket has timed out after.*dnsnotexist"
) as manager:
gen = dist.rendezvous(
"tcp://dnsnotexist:23456?world_size=2&rank=0",
timeout=timedelta(seconds=1),
)
next(gen)
self.assertTrue(isinstance(manager.exception, DistError))
@retry_on_connect_failures
def test_nominal(self):
url = self.create_tcp_url()
gen0 = dist.rendezvous(url + "&rank=0")
store0, rank0, size0 = next(gen0)
self.assertEqual(0, rank0)
self.assertEqual(1, size0)
# Set value on the single store
store0.set("key0", "value0")
# check with get
self.assertEqual(b"value0", store0.get("key0"))
@retry_on_connect_failures(connect_errors=(CONNECT_TIMEOUT, ADDRESS_IN_USE))
def test_tcp_store_timeout_set(self):
url = self.create_tcp_url()
test_store_timeout = timedelta(seconds=0.1)
gen0 = dist.rendezvous(url + "&rank=0", timeout=timedelta(seconds=10))
store0, _, _ = next(gen0)
store0.set_timeout(test_store_timeout)
# this should time out in 0.1s. If the timeout passed into rendezvous was
# not respected, it will take much longer to timeout.
start = time.time()
with self.assertRaisesRegex(
DistStoreError, "wait timeout after 100ms, keys: /nonexistent key"
):
store0.get("nonexistent key")
end = time.time()
time_diff = end - start
self.assertGreater(10, time_diff)
def test_tcp_store_timeout_doest_break_client(self):
url = self.create_tcp_url()
test_store_timeout = timedelta(seconds=0.1)
gen0 = dist.rendezvous(url + "&rank=0", timeout=timedelta(seconds=10))
store0, _, _ = next(gen0)
store0.set_timeout(test_store_timeout)
# this should time out in 10s. If the timeout passed into rendezvous was
# not respected, it will take much longer to timeout.
start = time.time()
with self.assertRaisesRegex(
DistStoreError, "wait timeout after 100ms, keys: /the_key"
):
store0.get("the_key")
store0.set("the_key", "x")
self.assertEqual(b"x", store0.get("the_key"))
end = time.time()
time_diff = end - start
self.assertGreater(10, time_diff)
def test_tcp_store_url_with_libuv(self):
url = self.create_tcp_url()
gen0 = dist.rendezvous(url + "&rank=0&use_libuv=1")
store0, _, _ = next(gen0)
self.assertTrue(store0.libuvBackend)
| RendezvousTCPTest |
python | walkccc__LeetCode | solutions/1984. Minimum Difference Between Highest and Lowest of K Scores/1984.py | {
"start": 0,
"end": 226
} | class ____:
def minimumDifference(self, nums: list[int], k: int) -> int:
nums.sort()
ans = nums[k - 1] - nums[0]
for i in range(k, len(nums)):
ans = min(ans, nums[i] - nums[i - k + 1])
return ans
| Solution |
python | palantir__python-language-server | pyls/lsp.py | {
"start": 951,
"end": 1272
} | class ____(object):
File = 1
Module = 2
Namespace = 3
Package = 4
Class = 5
Method = 6
Property = 7
Field = 8
Constructor = 9
Enum = 10
Interface = 11
Function = 12
Variable = 13
Constant = 14
String = 15
Number = 16
Boolean = 17
Array = 18
| SymbolKind |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/snippets/expect_column_max_to_be_between_custom.py | {
"start": 3696,
"end": 14466
} | class ____(ColumnAggregateExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py docstring">
"""Expect column max to be between a given range."""
# </snippet>
# Defining test cases
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py examples">
examples = [
{
"data": {"x": [1, 2, 3, 4, 5], "y": [0, -1, -2, 4, None]},
"only_for": ["pandas", "spark", "sqlite", "postgresql"],
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"column": "x",
"min_value": 4,
"strict_min": True,
"max_value": 5,
"strict_max": False,
},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"column": "y",
"min_value": -2,
"strict_min": False,
"max_value": 3,
"strict_max": True,
},
"out": {"success": False},
},
],
}
]
# </snippet>
min_value: Union[float, EvaluationParameterDict, datetime, None] = None
max_value: Union[float, EvaluationParameterDict, datetime, None] = None
strict_min: bool = False
strict_max: bool = False
# Setting necessary computation metric dependencies and defining kwargs, as well as assigning kwargs default values
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py metric_dependencies">
metric_dependencies = ("column.custom_max",)
# </snippet>
success_keys = ("min_value", "strict_min", "max_value", "strict_max")
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config">
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration] = None
) -> None:
"""
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
necessary configuration arguments have been provided for the validation of the expectation.
Args:
configuration (OPTIONAL[ExpectationConfiguration]): \
An optional Expectation Configuration entry that will be used to configure the expectation
Returns:
None. Raises InvalidExpectationConfigurationError if the config is not validated successfully
"""
# Setting up a configuration
super().validate_configuration(configuration)
configuration = configuration or self.configuration
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_params">
min_value = configuration.kwargs["min_value"]
max_value = configuration.kwargs["max_value"]
strict_min = configuration.kwargs["strict_min"]
strict_max = configuration.kwargs["strict_max"]
# </snippet>
# Validating that min_val, max_val, strict_min, and strict_max are of the proper format and type
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_values">
try:
assert (
min_value is not None or max_value is not None
), "min_value and max_value cannot both be none"
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_types">
assert min_value is None or isinstance(
min_value, (float, int)
), "Provided min threshold must be a number"
assert max_value is None or isinstance(
max_value, (float, int)
), "Provided max threshold must be a number"
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_comparison">
if min_value and max_value:
assert (
min_value <= max_value
), "Provided min threshold must be less than or equal to max threshold"
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_none">
assert strict_min is None or isinstance(
strict_min, bool
), "strict_min must be a boolean value"
assert strict_max is None or isinstance(
strict_max, bool
), "strict_max must be a boolean value"
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py validate_config_except">
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e))
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py _validate">
def _validate(
self,
metrics: Dict,
runtime_configuration: Optional[dict] = None,
execution_engine: ExecutionEngine = None,
):
"""Validates the given data against the set minimum and maximum value thresholds for the column max"""
column_max = metrics["column.custom_max"]
# Obtaining components needed for validation
success_kwargs = self._get_success_kwargs()
min_value = success_kwargs.get("min_value")
max_value = success_kwargs.get("max_value")
strict_min = success_kwargs.get("strict_min")
strict_max = success_kwargs.get("strict_max")
# Checking if mean lies between thresholds
if min_value is not None:
if strict_min:
above_min = column_max > min_value
else:
above_min = column_max >= min_value
else:
above_min = True
if max_value is not None:
if strict_max:
below_max = column_max < max_value
else:
below_max = column_max <= max_value
else:
below_max = True
success = above_min and below_max
return {"success": success, "result": {"observed_value": column_max}}
# </snippet>
@renderer(renderer_type="render.prescriptive")
@render_evaluation_parameter_string
def _prescriptive_renderer(
cls,
configuration: ExpectationConfiguration = None,
result: ExpectationValidationResult = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
):
assert (
configuration or result
), "Must provide renderers either a configuration or result."
runtime_configuration = runtime_configuration or {}
include_column_name = (
False if runtime_configuration.get("include_column_name") is False else True
)
styling = runtime_configuration.get("styling")
# get params dict with all expected kwargs
params = substitute_none_for_missing(
configuration.kwargs,
[
"column",
"min_value",
"max_value",
"mostly",
"row_condition",
"condition_parser",
"strict_min",
"strict_max",
],
)
# build the string, parameter by parameter
if (params["min_value"] is None) and (params["max_value"] is None):
template_str = "maximum value may have any numerical value."
else:
at_least_str, at_most_str = handle_strict_min_max(params)
if params["min_value"] is not None and params["max_value"] is not None:
template_str = f"maximum value must be {at_least_str} $min_value and {at_most_str} $max_value."
elif params["min_value"] is None:
template_str = f"maximum value must be {at_most_str} $max_value."
elif params["max_value"] is None:
template_str = f"maximum value must be {at_least_str} $min_value."
else:
template_str = ""
if include_column_name:
template_str = "$column " + template_str
if params["row_condition"] is not None:
(
conditional_template_str,
conditional_params,
) = parse_row_condition_string_pandas_engine(params["row_condition"])
template_str = conditional_template_str + ", then " + template_str
params.update(conditional_params)
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": params,
"styling": styling,
},
}
)
]
# This dictionary contains metadata for display in the public gallery
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py library_metadata">
library_metadata = {
"tags": ["flexible max comparisons"],
"contributors": ["@joegargery"],
}
# </snippet>
if __name__ == "__main__":
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py diagnostics">
ExpectColumnMaxToBeBetweenCustom(
column="x",
min_value=0,
max_value=10,
strict_min=True,
strict_max=False,
).print_diagnostic_checklist()
# </snippet>
# Note to users: code below this line is only for integration testing -- ignore!
diagnostics = ExpectColumnMaxToBeBetweenCustom(
column="x",
min_value=0,
max_value=10,
strict_min=True,
strict_max=False,
).run_diagnostics()
for check in diagnostics["tests"]:
assert check["test_passed"] is True
assert check["error_diagnostics"] is None
for check in diagnostics["errors"]:
assert check is None
for check in diagnostics["maturity_checklist"]["experimental"]:
if check["message"] == "Passes all linting checks":
continue
assert check["passed"] is True
| ExpectColumnMaxToBeBetweenCustom |
python | Textualize__textual | tests/notifications/test_app_notifications.py | {
"start": 46,
"end": 1917
} | class ____(App[None]):
pass
async def test_app_no_notifications() -> None:
"""An app with no notifications should have an empty notification list."""
async with NotificationApp().run_test() as pilot:
assert len(pilot.app._notifications) == 0
async def test_app_with_notifications() -> None:
"""An app with notifications should have notifications in the list."""
async with NotificationApp().run_test() as pilot:
pilot.app.notify("test")
await pilot.pause()
assert len(pilot.app._notifications) == 1
async def test_app_with_removing_notifications() -> None:
"""An app with notifications should have notifications in the list, which can be removed."""
async with NotificationApp().run_test() as pilot:
pilot.app.notify("test")
await pilot.pause()
assert len(pilot.app._notifications) == 1
pilot.app._unnotify(list(pilot.app._notifications)[0])
assert len(pilot.app._notifications) == 0
async def test_app_with_notifications_that_expire() -> None:
"""Notifications should expire from an app."""
async with NotificationApp().run_test() as pilot:
for n in range(10):
pilot.app.notify("test", timeout=(0.01 if bool(n % 2) else 60))
# Wait until the 0.01 timeout expires on all notifications (plus some leeway)
await asyncio.sleep(0.25)
assert len(pilot.app._notifications) == 5
async def test_app_clearing_notifications() -> None:
"""The application should be able to clear all notifications."""
async with NotificationApp().run_test() as pilot:
for _ in range(100):
pilot.app.notify("test", timeout=120)
await pilot.pause()
assert len(pilot.app._notifications) == 100
pilot.app.clear_notifications()
assert len(pilot.app._notifications) == 0
| NotificationApp |
python | pytorch__pytorch | test/export/random_dag.py | {
"start": 1162,
"end": 2054
} | class ____:
"""
Abstract base class for generating test code.
Users should subclass this class and implement the test_name() and
test_body() methods. The test_name() method should return a string
that uniquely identifies the test. The test_body() method should
yield blocks of code.
"""
def __init__(self):
self._count = 0
def _generate_test_name(self):
self._count += 1
return f"{self.test_name()}_{self._count}"
def generate_test(self):
test_name = self._generate_test_name()
code = Block()
code.new_line(f"def {test_name}():")
for block in self.test_body():
code.new_block(block)
code.new_line(f"{test_name}()")
return str(code)
def test_name(self):
raise NotImplementedError
def test_body(self):
raise NotImplementedError
| TestGenerator |
python | facebookresearch__faiss | tests/test_rabitq.py | {
"start": 18789,
"end": 30995
} | class ____(unittest.TestCase):
def do_comparison_vs_rabitq_test(
self, metric_type=faiss.METRIC_L2, bbs=32
):
"""Test IndexRaBitQFastScan produces similar results to IndexRaBitQ"""
ds = datasets.SyntheticDataset(128, 4096, 4096, 100)
k = 10
# IndexRaBitQ baseline
index_rbq = faiss.IndexRaBitQ(ds.d, metric_type)
index_rbq.train(ds.get_train())
index_rbq.add(ds.get_database())
_, I_rbq = index_rbq.search(ds.get_queries(), k)
# IndexRaBitQFastScan
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, metric_type, bbs)
index_rbq_fs.train(ds.get_train())
index_rbq_fs.add(ds.get_database())
_, I_rbq_fs = index_rbq_fs.search(ds.get_queries(), k)
index_flat = faiss.IndexFlat(ds.d, metric_type)
index_flat.train(ds.get_train())
index_flat.add(ds.get_database())
_, I_f = index_flat.search(ds.get_queries(), k)
# Evaluate against ground truth
eval_rbq = faiss.eval_intersection(I_rbq[:, :k], I_f[:, :k])
eval_rbq /= ds.nq * k
eval_rbq_fs = faiss.eval_intersection(I_rbq_fs[:, :k], I_f[:, :k])
eval_rbq_fs /= ds.nq * k
print(
f"RaBitQ baseline is {eval_rbq}, "
f"RaBitQFastScan is {eval_rbq_fs}"
)
# FastScan should be similar to baseline
np.testing.assert_(abs(eval_rbq - eval_rbq_fs) < 0.05)
def test_comparison_vs_rabitq_L2(self):
self.do_comparison_vs_rabitq_test(faiss.METRIC_L2)
def test_comparison_vs_rabitq_IP(self):
self.do_comparison_vs_rabitq_test(faiss.METRIC_INNER_PRODUCT)
def test_encode_decode_consistency(self):
"""Test that encoding and decoding operations are consistent"""
ds = datasets.SyntheticDataset(128, 1000, 0, 0) # No queries/db needed
# Test with IndexRaBitQFastScan
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
# Test encode/decode on a subset of training data
test_vectors = ds.get_train()[:100]
# Test compute_codes and sa_decode
# This tests that factors are properly embedded in codes
codes = np.empty(
(len(test_vectors), index_rbq_fs.code_size), dtype=np.uint8
)
index_rbq_fs.compute_codes(
faiss.swig_ptr(codes),
len(test_vectors),
faiss.swig_ptr(test_vectors)
)
# sa_decode should work directly with embedded codes
decoded_fs = index_rbq_fs.sa_decode(codes)
# Check reconstruction error for FastScan
distances_fs = np.sum((test_vectors - decoded_fs) ** 2, axis=1)
avg_distance_fs = np.mean(distances_fs)
print(f"Average FastScan reconstruction error: {avg_distance_fs}")
# Compare with original IndexRaBitQ on the SAME dataset
index_rbq = faiss.IndexRaBitQ(ds.d, faiss.METRIC_L2)
index_rbq.train(ds.get_train())
# Encode with original RaBitQ (correct API - returns encoded array)
codes_orig = index_rbq.sa_encode(test_vectors)
# Decode with original RaBitQ
decoded_orig = index_rbq.sa_decode(codes_orig)
# Check reconstruction error for original
distances_orig = np.sum((test_vectors - decoded_orig) ** 2, axis=1)
avg_distance_orig = np.mean(distances_orig)
print(
f"Average original RaBitQ reconstruction error: "
f"{avg_distance_orig}"
)
# Print comparison
print(
f"Error difference (FastScan - Original): "
f"{avg_distance_fs - avg_distance_orig}"
)
# FastScan should have similar reconstruction error to original RaBitQ
np.testing.assert_(
abs(avg_distance_fs - avg_distance_orig) < 0.01
) # Should be nearly identical
def test_query_quantization_bits(self):
"""Test different query quantization bit settings"""
ds = datasets.SyntheticDataset(64, 2000, 2000, 50)
k = 10
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
index_rbq_fs.add(ds.get_database())
# Test different qb values
results = {}
for qb in [4, 6, 8]:
index_rbq_fs.qb = qb
_, I = index_rbq_fs.search(ds.get_queries(), k)
results[qb] = I
# All should produce reasonable results
index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2)
index_flat.train(ds.get_train())
index_flat.add(ds.get_database())
_, I_f = index_flat.search(ds.get_queries(), k)
for qb in [4, 6, 8]:
eval_qb = faiss.eval_intersection(results[qb][:, :k], I_f[:, :k])
eval_qb /= ds.nq * k
print(f"Query quantization qb={qb} recall: {eval_qb}")
np.testing.assert_(eval_qb > 0.4) # Should be reasonable
def test_small_dataset(self):
"""Test on a small dataset to ensure basic functionality"""
d = 32
n = 100
nq = 10
rs = np.random.RandomState(123)
xb = rs.rand(n, d).astype(np.float32)
xq = rs.rand(nq, d).astype(np.float32)
index_rbq_fs = faiss.IndexRaBitQFastScan(d, faiss.METRIC_L2)
index_rbq_fs.train(xb)
index_rbq_fs.add(xb)
k = 5
distances, labels = index_rbq_fs.search(xq, k)
# Check output shapes and validity
np.testing.assert_equal(distances.shape, (nq, k))
np.testing.assert_equal(labels.shape, (nq, k))
# Check that labels are valid indices
np.testing.assert_(np.all(labels >= 0))
np.testing.assert_(np.all(labels < n))
# Check that distances are non-negative (for L2)
np.testing.assert_(np.all(distances >= 0))
# Quick recall check against exact search
index_flat = faiss.IndexFlat(d, faiss.METRIC_L2)
index_flat.train(xb)
index_flat.add(xb)
_, I_f = index_flat.search(xq, k)
# Evaluate recall
recall = faiss.eval_intersection(labels[:, :k], I_f[:, :k])
recall /= (nq * k)
print(f"Small dataset recall: {recall:.3f}")
np.testing.assert_(
recall > 0.4
) # Should be reasonable for small dataset
def test_comparison_vs_pq_fastscan(self):
"""Compare RaBitQFastScan to PQFastScan as a performance baseline"""
ds = datasets.SyntheticDataset(128, 4096, 4096, 100)
k = 10
# PQFastScan baseline
index_pq_fs = faiss.IndexPQFastScan(ds.d, 16, 4, faiss.METRIC_L2)
index_pq_fs.train(ds.get_train())
index_pq_fs.add(ds.get_database())
_, I_pq_fs = index_pq_fs.search(ds.get_queries(), k)
# RaBitQFastScan
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
index_rbq_fs.add(ds.get_database())
_, I_rbq_fs = index_rbq_fs.search(ds.get_queries(), k)
index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2)
index_flat.train(ds.get_train())
index_flat.add(ds.get_database())
_, I_f = index_flat.search(ds.get_queries(), k)
# Evaluate both against ground truth
eval_pq_fs = faiss.eval_intersection(I_pq_fs[:, :k], I_f[:, :k])
eval_pq_fs /= ds.nq * k
eval_rbq_fs = faiss.eval_intersection(I_rbq_fs[:, :k], I_f[:, :k])
eval_rbq_fs /= ds.nq * k
print(
f"PQFastScan is {eval_pq_fs}, "
f"RaBitQFastScan is {eval_rbq_fs}"
)
# RaBitQFastScan should have reasonable performance similar to regular
# RaBitQ
np.testing.assert_(eval_rbq_fs > 0.55)
def test_serialization(self):
"""Test serialization and deserialization of RaBitQFastScan"""
ds = datasets.SyntheticDataset(64, 1000, 100, 20)
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
index_rbq_fs.add(ds.get_database())
Dref, Iref = index_rbq_fs.search(ds.get_queries(), 10)
# Serialize and deserialize
b = faiss.serialize_index(index_rbq_fs)
index2 = faiss.deserialize_index(b)
Dnew, Inew = index2.search(ds.get_queries(), 10)
# Results should be identical
np.testing.assert_array_equal(Dref, Dnew)
np.testing.assert_array_equal(Iref, Inew)
def test_memory_management(self):
"""Test that memory is managed correctly during operations"""
ds = datasets.SyntheticDataset(128, 2000, 2000, 50)
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
# Add data in chunks to test memory management
chunk_size = 500
for i in range(0, ds.nb, chunk_size):
end_idx = min(i + chunk_size, ds.nb)
chunk_data = ds.get_database()[i:end_idx]
index_rbq_fs.add(chunk_data)
# Verify total count
np.testing.assert_equal(index_rbq_fs.ntotal, ds.nb)
# Test search still works and produces reasonable recall
_, I = index_rbq_fs.search(ds.get_queries(), 5)
np.testing.assert_equal(I.shape, (ds.nq, 5))
# Compare against ground truth to verify recall
index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2)
index_flat.train(ds.get_train())
index_flat.add(ds.get_database())
_, I_f = index_flat.search(ds.get_queries(), 5)
# Calculate recall - should be reasonable despite multiple add() calls
recall = faiss.eval_intersection(I[:, :5], I_f[:, :5])
recall /= (ds.nq * 5)
# If embedded factors are corrupted by multiple add() calls,
# recall will be very low
np.testing.assert_(
recall > 0.1,
f"Recall too low: {recall:.3f} - suggests multiple "
f"add() calls corrupted embedded factors"
)
def test_invalid_parameters(self):
"""Test proper error handling for invalid parameters"""
# Invalid dimension
with np.testing.assert_raises(Exception):
faiss.IndexRaBitQFastScan(0, faiss.METRIC_L2)
# Invalid metric (should only support L2 and IP)
try:
faiss.IndexRaBitQFastScan(64, faiss.METRIC_Lp)
np.testing.assert_(
False, "Should have raised exception for invalid metric"
)
except RuntimeError:
pass # Expected
def test_thread_safety(self):
"""Test that parallel operations work correctly"""
ds = datasets.SyntheticDataset(64, 2000, 2000, 500)
index_rbq_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2)
index_rbq_fs.train(ds.get_train())
index_rbq_fs.add(ds.get_database())
# Search with multiple threads (implicitly tested through OpenMP)
k = 10
distances, labels = index_rbq_fs.search(ds.get_queries(), k)
# Basic sanity checks
np.testing.assert_equal(distances.shape, (ds.nq, k))
np.testing.assert_equal(labels.shape, (ds.nq, k))
np.testing.assert_(np.all(distances >= 0))
np.testing.assert_(np.all(labels >= 0))
np.testing.assert_(np.all(labels < ds.nb))
def test_factory_construction(self):
"""Test that RaBitQFastScan can be constructed via factory method"""
ds = datasets.SyntheticDataset(64, 500, 500, 20)
# Test RaBitQFastScan (non-IVF) factory construction
index_flat = faiss.index_factory(ds.d, "RaBitQfs")
np.testing.assert_(isinstance(index_flat, faiss.IndexRaBitQFastScan))
index_flat.train(ds.get_train())
index_flat.add(ds.get_database())
# Test basic search
_, I_flat = index_flat.search(ds.get_queries(), 5)
np.testing.assert_equal(I_flat.shape, (ds.nq, 5))
# Test with custom batch size
index_custom = faiss.index_factory(ds.d, "RaBitQfs_64")
np.testing.assert_(isinstance(index_custom, faiss.IndexRaBitQFastScan))
np.testing.assert_equal(index_custom.bbs, 64)
| TestRaBitQFastScan |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_composer.py | {
"start": 8860,
"end": 9947
} | class ____:
@mock.patch(COMPOSER_STRING.format("Environment.to_dict"))
@mock.patch(COMPOSER_STRING.format("CloudComposerHook"))
def test_execute(self, mock_hook, to_dict_mode) -> None:
op = CloudComposerGetEnvironmentOperator(
task_id=TASK_ID,
project_id=TEST_GCP_PROJECT,
region=TEST_GCP_REGION,
environment_id=TEST_ENVIRONMENT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
)
op.execute(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.get_environment.assert_called_once_with(
project_id=TEST_GCP_PROJECT,
region=TEST_GCP_REGION,
environment_id=TEST_ENVIRONMENT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestCloudComposerGetEnvironmentOperator |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_adx.py | {
"start": 1387,
"end": 12280
} | class ____:
@pytest.mark.parametrize(
("mocked_connection", "error_pattern"),
[
(
Connection(
conn_id="missing_method",
conn_type="azure_data_explorer",
login="client_id",
password="client secret",
host="https://help.kusto.windows.net",
extra={},
),
"is missing: `auth_method`",
),
(
Connection(
conn_id="unknown_method",
conn_type="azure_data_explorer",
login="client_id",
password="client secret",
host="https://help.kusto.windows.net",
extra={"auth_method": "AAD_OTHER"},
),
"Unknown authentication method: AAD_OTHER",
),
(
Connection(
conn_id="missing_cluster",
conn_type="azure_data_explorer",
login="client_id",
password="client secret",
extra={},
),
"Host connection option is required",
),
],
indirect=["mocked_connection"],
ids=["missing_method", "unknown_method", "missing_cluster"],
)
def test_conn_errors(self, mocked_connection, error_pattern):
hook = AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id)
with pytest.raises(AirflowException, match=error_pattern):
assert hook.get_conn()
with pytest.raises(AirflowException, match=error_pattern):
assert hook.connection
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="method_aad_creds",
conn_type="azure_data_explorer",
login="client_id",
password="client secret",
host="https://help.kusto.windows.net",
extra={"tenant": "tenant", "auth_method": "AAD_CREDS"},
)
],
indirect=True,
)
@mock.patch.object(KustoClient, "__init__")
def test_conn_method_aad_creds(self, mock_init, mocked_connection):
mock_init.return_value = None
AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id).get_conn()
mock_init.assert_called()
args = mock_init.call_args
assert args[0][0].data_source == "https://help.kusto.windows.net"
assert args[0][0].aad_user_id == "client_id"
assert args[0][0].password == "client secret"
assert args[0][0].authority_id == "tenant"
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="method_token_creds",
conn_type="azure_data_explorer",
host="https://help.kusto.windows.net",
extra={
"auth_method": "AZURE_TOKEN_CRED",
},
),
],
indirect=True,
)
@mock.patch("azure.identity._credentials.environment.ClientSecretCredential")
def test_conn_method_token_creds(self, mock1, mocked_connection, monkeypatch):
hook = AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id)
monkeypatch.setenv("AZURE_TENANT_ID", "tenant")
monkeypatch.setenv("AZURE_CLIENT_ID", "client")
monkeypatch.setenv("AZURE_CLIENT_SECRET", "secret")
assert hook.connection._kcsb.data_source == "https://help.kusto.windows.net"
import azure.identity
azure_identity_version = Version(azure.identity.__version__)
if azure_identity_version >= Version("1.15.0"):
mock1.assert_called_once_with(
tenant_id="tenant",
client_id="client",
client_secret="secret",
authority="https://login.microsoftonline.com",
_within_dac=True,
)
else:
mock1.assert_called_once_with(
tenant_id="tenant",
client_id="client",
client_secret="secret",
authority="https://login.microsoftonline.com",
)
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="method_aad_app",
conn_type="azure_data_explorer",
login="app_id",
password="app key",
host="https://help.kusto.windows.net",
extra={
"tenant": "tenant",
"auth_method": "AAD_APP",
},
)
],
indirect=["mocked_connection"],
)
@mock.patch.object(KustoClient, "__init__")
def test_conn_method_aad_app(self, mock_init, mocked_connection):
mock_init.return_value = None
AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id).get_conn()
mock_init.assert_called()
arg = mock_init.call_args
assert arg[0][0].data_source == "https://help.kusto.windows.net"
assert arg[0][0].application_client_id == "app_id"
assert arg[0][0].application_key == "app key"
assert arg[0][0].authority_id == "tenant"
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id="method_aad_app",
conn_type="azure_data_explorer",
login="app_id",
password="app key",
host="https://help.kusto.windows.net",
extra={
"tenant": "tenant",
"auth_method": "AAD_APP",
},
)
],
indirect=True,
)
@mock.patch.object(KustoClient, "__init__")
def test_conn_method_aad_app_cert(self, mock_init, mocked_connection):
mock_init.return_value = None
AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id).get_conn()
mock_init.assert_called()
arg = mock_init.call_args
assert arg[0][0].data_source == "https://help.kusto.windows.net"
assert arg[0][0].application_client_id == "app_id"
assert arg[0][0].application_key == "app key"
assert arg[0][0].aad_federated_security
assert arg[0][0].authority_id == "tenant"
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id=ADX_TEST_CONN_ID,
conn_type="azure_data_explorer",
host="https://help.kusto.windows.net",
extra={"auth_method": "AAD_DEVICE"},
)
],
indirect=True,
)
@mock.patch.object(KustoClient, "__init__")
def test_conn_method_aad_device(self, mock_init, mocked_connection):
mock_init.return_value = None
AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id).get_conn()
mock_init.assert_called()
arg = mock_init.call_args
assert arg[0][0].data_source == "https://help.kusto.windows.net"
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id=ADX_TEST_CONN_ID,
conn_type="azure_data_explorer",
host="https://help.kusto.windows.net",
extra={
"auth_method": "AZURE_TOKEN_CRED",
"managed_identity_client_id": "test_id",
"workload_identity_tenant_id": "test_tenant_id",
},
)
],
indirect=True,
)
@mock.patch("airflow.providers.microsoft.azure.hooks.adx.get_sync_default_azure_credential")
@mock.patch.object(KustoClient, "__init__")
def test_conn_method_azure_token_cred(self, mock_init, mock_default_azure_credential, mocked_connection):
mock_init.return_value = None
AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id).get_conn()
mock_init.assert_called()
args = mock_init.call_args
assert args[0][0].data_source == "https://help.kusto.windows.net"
mock_default_azure_credential.assert_called()
args = mock_default_azure_credential.call_args
assert args[1]["managed_identity_client_id"] == "test_id"
assert args[1]["workload_identity_tenant_id"] == "test_tenant_id"
@pytest.mark.parametrize(
"mocked_connection",
[
Connection(
conn_id=ADX_TEST_CONN_ID,
conn_type="azure_data_explorer",
host="https://help.kusto.windows.net",
extra={"auth_method": "AAD_DEVICE"},
)
],
indirect=True,
)
@mock.patch.object(KustoClient, "execute")
def test_run_query(self, mock_execute, mocked_connection):
mock_execute.return_value = None
hook = AzureDataExplorerHook(azure_data_explorer_conn_id=ADX_TEST_CONN_ID)
hook.run_query("Database", "Logs | schema", options={"option1": "option_value"})
properties = ClientRequestProperties()
properties.set_option("option1", "option_value")
mock_execute.assert_called()
args = mock_execute.call_args
assert args[0][0] == "Logs | schema"
assert args[0][1] == "Database"
assert args[1]["properties"]._options["option1"] == "option_value"
@pytest.mark.parametrize(
"mocked_connection",
[
pytest.param("a://usr:pw@host?tenant=my-tenant&auth_method=AAD_APP", id="no-prefix"),
],
indirect=["mocked_connection"],
)
def test_prefix_works(self, mocked_connection):
hook = AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id)
assert hook.connection._kcsb.data_source == "host"
assert hook.connection._kcsb.application_client_id == "usr"
assert hook.connection._kcsb.application_key == "pw"
assert hook.connection._kcsb.authority_id == "my-tenant"
@pytest.mark.parametrize(
"mocked_connection",
[
(
"a://usr:pw@host?tenant=my-tenant&auth_method=AAD_APP"
"&extra__azure_data_explorer__auth_method=AAD_APP"
)
],
indirect=True,
)
def test_prefix_both_causes_warning(self, mocked_connection):
hook = AzureDataExplorerHook(azure_data_explorer_conn_id=mocked_connection.conn_id)
assert hook.connection._kcsb.data_source == "host"
assert hook.connection._kcsb.application_client_id == "usr"
assert hook.connection._kcsb.application_key == "pw"
assert hook.connection._kcsb.authority_id == "my-tenant"
| TestAzureDataExplorerHook |
python | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 108253,
"end": 108962
} | class ____(MaxNLocator):
"""
Place evenly spaced ticks, with the step size and maximum number of ticks chosen
automatically.
This is a subclass of `~matplotlib.ticker.MaxNLocator`, with parameters
*nbins = 'auto'* and *steps = [1, 2, 2.5, 5, 10]*.
"""
def __init__(self):
"""
To know the values of the non-public parameters, please have a
look to the defaults of `~matplotlib.ticker.MaxNLocator`.
"""
if mpl.rcParams['_internal.classic_mode']:
nbins = 9
steps = [1, 2, 5, 10]
else:
nbins = 'auto'
steps = [1, 2, 2.5, 5, 10]
super().__init__(nbins=nbins, steps=steps)
| AutoLocator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_format18.py | {
"start": 315,
"end": 913
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("format18.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with a quote prefix."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
quote_prefix = workbook.add_format({"quote_prefix": True})
worksheet.write_string(0, 0, "= Hello", quote_prefix)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/255. Verify Preorder Sequence in Binary Search Tree/255-3.py | {
"start": 0,
"end": 300
} | class ____:
def verifyPreorder(self, preorder: list[int]) -> bool:
low = -math.inf
i = -1
for p in preorder:
if p < low:
return False
while i >= 0 and preorder[i] < p:
low = preorder[i]
i -= 1
i += 1
preorder[i] = p
return True
| Solution |
python | pytorch__pytorch | torch/distributed/checkpoint/state_dict_saver.py | {
"start": 1566,
"end": 7343
} | class ____(Enum):
"""Enum for async checkpointer type."""
THREAD = "thread"
PROCESS = "process"
@deprecated(
"`save_state_dict` is deprecated and will be removed in future versions."
"Please use `save` instead.",
category=FutureWarning,
)
def save_state_dict(
state_dict: STATE_DICT_TYPE,
storage_writer: StorageWriter,
process_group: Optional[dist.ProcessGroup] = None,
coordinator_rank: int = 0,
no_dist: bool = False,
planner: Optional[SavePlanner] = None,
) -> Metadata:
"""This method is deprecated. Please switch to 'save'."""
storage_writer.reset()
# TODO: test returning `save` here instead.
with _profile():
return _save_state_dict(
state_dict,
storage_writer,
process_group,
coordinator_rank,
no_dist,
planner,
)
@_dcp_method_logger(log_exceptions=True) # type: ignore[arg-type]
@_api_bc_check
def save(
state_dict: STATE_DICT_TYPE,
*,
checkpoint_id: Union[str, os.PathLike, None] = None,
storage_writer: Optional[StorageWriter] = None,
planner: Optional[SavePlanner] = None,
process_group: Optional[dist.ProcessGroup] = None,
no_dist: bool = False,
use_collectives: bool = True,
) -> Metadata:
"""
Save a distributed model in SPMD style.
This function is different from ``torch.save()`` as it handles
``ShardedTensor`` , and ``DTensor`` by having each rank only save their local shards.
For each ``Stateful`` object (having both a ``state_dict`` and a ``load_state_dict``),
save will call ``state_dict`` before serialization.
.. warning::
There is no guarantees of Backwards Compatibility across PyTorch versions
for saved state_dicts.
.. warning::
If using the `process_group` argument, make sure that only its ranks
call `save_state_dict` and that all data in state_dict belong to it.
.. note::
When saving checkpoint for FSDP's `ShardingStrategy.HYBRID_SHARD`, only one of
the shard_group should be calling `save_state_dict` and the corresponding process
group needs to be passed in.
.. note::
If no process group is available, this function assumes the intention is to save the
state_dict in the local process.
.. note:
Rank 0 is assumed to be the coordinator rank.
Args:
state_dict (Dict[str, Any]): The state_dict to save.
checkpoint_id (Union[str, os.PathLike, None]):
The ID of this checkpoint instance. The meaning of the checkpoint_id
depends on the storage. It can be a path to a folder or to a file.
It can also be a key if the storage is a key-value store.
(Default: ``None``)
storage_writer (Optional[StorageWriter]):
Instance of StorageWriter used to perform writes. If this is not
specified, DCP will automatically infer the writer based on the
checkpoint_id. If checkpoint_id is also None, an exception will
be raised. (Default: ``None``)
planner (Optional[SavePlanner]):
Instance of SavePlanner. If this is not specified, the default
planner will be used. (Default: ``None``)
process_group (Optional[ProcessGroup]):
ProcessGroup to be used for cross-rank synchronization.
(Default: ``None``)
no_dist (bool):
If ``True``, this function will assume the intent is to load
a checkpoint on a single rank/process.
(Default: ``False``)
use_collectives (bool): If ``False``, this function will assume the intent is to save
a checkpoint without using cross-rank synchronization.
(Default: ``True``)
This configuration is experimental and should be used with caution.
It will change the format of the saved checkpoint and may not be backward compatible.
Returns:
Metadata: Metadata object for the saved checkpoint.
Example:
>>> # xdoctest: +SKIP
>>> my_model = MyModule()
>>> state_dict = {"model": my_model}
>>> fs_storage_writer = torch.distributed.checkpoint.FileSystemWriter(
... "/checkpoint/1"
... )
>>> torch.distributed.checkpoint.save(
>>> state_dict=state_dict,
>>> storage_writer=fs_storage_writer,
>>> )
.. note::
save_state_dict uses collectives to coordinate writes across ranks.
For NCCL-based process groups, internal tensor representations of
objects must be moved to the GPU device before communication takes place.
In this case, the device used is given by ``torch.cuda.current_device()``
and it is the user's responsibility to ensure that this is set so that
each rank has an individual GPU, via ``torch.cuda.set_device()``.
"""
torch._C._log_api_usage_once("torch.distributed.checkpoint.save")
no_dist = no_dist or (not dist.is_available()) or (not dist.is_initialized())
if no_dist:
warnings.warn(
"torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to save in a single process.",
stacklevel=2,
)
with _profile():
storage_writer = cast(
StorageWriter, _storage_setup(storage_writer, checkpoint_id, reader=False)
)
return _save_state_dict(
state_dict=_stateful_to_state_dict(state_dict),
storage_writer=storage_writer,
process_group=process_group,
no_dist=no_dist,
planner=planner,
use_collectives=use_collectives,
)
@dataclass
| AsyncCheckpointerType |
python | paramiko__paramiko | tests/test_channelfile.py | {
"start": 125,
"end": 929
} | class ____:
@patch("paramiko.channel.ChannelFile._set_mode")
def test_defaults_to_unbuffered_reading(self, setmode):
self.klass(Channel(None))
setmode.assert_called_once_with("r", -1)
@patch("paramiko.channel.ChannelFile._set_mode")
def test_can_override_mode_and_bufsize(self, setmode):
self.klass(Channel(None), mode="w", bufsize=25)
setmode.assert_called_once_with("w", 25)
def test_read_recvs_from_channel(self):
chan = MagicMock()
cf = self.klass(chan)
cf.read(100)
chan.recv.assert_called_once_with(100)
def test_write_calls_channel_sendall(self):
chan = MagicMock()
cf = self.klass(chan, mode="w")
cf.write("ohai")
chan.sendall.assert_called_once_with(b"ohai")
| ChannelFileBase |
python | kamyu104__LeetCode-Solutions | Python/minimum-unique-word-abbreviation.py | {
"start": 68,
"end": 1751
} | class ____(object):
def minAbbreviation(self, target, dictionary):
"""
:type target: str
:type dictionary: List[str]
:rtype: str
"""
def bits_to_abbr_len(targets, bits):
total = 0
pre = 0
for i in xrange(len(target)):
if bits & 1:
if i - pre > 0:
total += len(str(i - pre))
pre = i + 1
total += 1
elif i == len(target) - 1:
total += len(str(i - pre + 1))
bits >>= 1
return total
def bits_to_abbr(targets, bits):
abbr = []
pre = 0
for i in xrange(len(target)):
if bits & 1:
if i - pre > 0:
abbr.append(str(i - pre))
pre = i + 1
abbr.append(target[i])
elif i == len(target) - 1:
abbr.append(str(i - pre + 1))
bits >>= 1
return "".join(abbr)
diffs = []
for word in dictionary:
if len(word) != len(target):
continue
diffs.append(sum(2**i for i, c in enumerate(word) if target[i] != c))
if not diffs:
return str(len(target))
result = 2**len(target)-1
for mask in xrange(2**len(target)):
if all(d & mask for d in diffs) and bits_to_abbr_len(target, mask) < bits_to_abbr_len(target, result):
result = mask
return bits_to_abbr(target, result)
# Time: O((d + n) * 2^n)
# Space: O(d + n)
| Solution |
python | astropy__astropy | astropy/timeseries/tests/test_common.py | {
"start": 2355,
"end": 2726
} | class ____(CommonTimeSeriesTests):
_row = {"time": "2016-03-23T12:30:40", "a": 1.0, "b": 2, "c": "a"}
def setup_method(self, method):
self.series = TimeSeries(time=INPUT_TIME, data=PLAIN_TABLE)
self.time_attr = "time"
def test_column_slicing(self):
ts = self.series["time", "a"]
assert isinstance(ts, TimeSeries)
| TestTimeSeries |
python | pytest-dev__pytest | testing/test_skipping.py | {
"start": 27263,
"end": 36509
} | class ____:
def test_skipif_conditional(self, pytester: Pytester) -> None:
item = pytester.getitem(
"""
import pytest
@pytest.mark.skipif("hasattr(os, 'sep')")
def test_func():
pass
"""
)
x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))
assert x.value.msg == "condition: hasattr(os, 'sep')"
@pytest.mark.parametrize(
"params", ["\"hasattr(sys, 'platform')\"", 'True, reason="invalid platform"']
)
def test_skipif_reporting(self, pytester: Pytester, params) -> None:
p = pytester.makepyfile(
test_foo=f"""
import pytest
@pytest.mark.skipif({params})
def test_that():
assert 0
"""
)
result = pytester.runpytest(p, "-s", "-rs")
result.stdout.fnmatch_lines(["*SKIP*1*test_foo.py*platform*", "*1 skipped*"])
assert result.ret == 0
def test_skipif_using_platform(self, pytester: Pytester) -> None:
item = pytester.getitem(
"""
import pytest
@pytest.mark.skipif("platform.platform() == platform.platform()")
def test_func():
pass
"""
)
pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))
@pytest.mark.parametrize(
"marker, msg1, msg2",
[("skipif", "SKIP", "skipped"), ("xfail", "XPASS", "xpassed")],
)
def test_skipif_reporting_multiple(
self, pytester: Pytester, marker, msg1, msg2
) -> None:
pytester.makepyfile(
test_foo=f"""
import pytest
@pytest.mark.{marker}(False, reason='first_condition')
@pytest.mark.{marker}(True, reason='second_condition')
def test_foobar():
assert 1
"""
)
result = pytester.runpytest("-s", "-rsxX")
result.stdout.fnmatch_lines(
[f"*{msg1}*test_foo.py*second_condition*", f"*1 {msg2}*"]
)
assert result.ret == 0
def test_skip_not_report_default(pytester: Pytester) -> None:
p = pytester.makepyfile(
test_one="""
import pytest
def test_this():
pytest.skip("hello")
"""
)
result = pytester.runpytest(p, "-v")
result.stdout.fnmatch_lines(
[
# "*HINT*use*-r*",
"*1 skipped*"
]
)
def test_skipif_class(pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
class TestClass(object):
pytestmark = pytest.mark.skipif("True")
def test_that(self):
assert 0
def test_though(self):
assert 0
"""
)
result = pytester.runpytest(p)
result.stdout.fnmatch_lines(["*2 skipped*"])
def test_skipped_reasons_functional(pytester: Pytester) -> None:
pytester.makepyfile(
test_one="""
import pytest
from helpers import doskip
def setup_function(func): # LINE 4
doskip("setup function")
def test_func():
pass
class TestClass:
def test_method(self):
doskip("test method")
@pytest.mark.skip("via_decorator") # LINE 14
def test_deco(self):
assert 0
""",
helpers="""
import pytest, sys
def doskip(reason):
assert sys._getframe().f_lineno == 3
pytest.skip(reason) # LINE 4
""",
)
result = pytester.runpytest("-rs")
result.stdout.fnmatch_lines_random(
[
"SKIPPED [[]1[]] test_one.py:7: setup function",
"SKIPPED [[]1[]] helpers.py:4: test method",
"SKIPPED [[]1[]] test_one.py:14: via_decorator",
]
)
assert result.ret == 0
def test_skipped_folding(pytester: Pytester) -> None:
pytester.makepyfile(
test_one="""
import pytest
pytestmark = pytest.mark.skip("Folding")
def setup_function(func):
pass
def test_func():
pass
class TestClass(object):
def test_method(self):
pass
"""
)
result = pytester.runpytest("-rs")
result.stdout.fnmatch_lines(["*SKIP*2*test_one.py: Folding"])
assert result.ret == 0
def test_reportchars(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def test_1():
assert 0
@pytest.mark.xfail
def test_2():
assert 0
@pytest.mark.xfail
def test_3():
pass
def test_4():
pytest.skip("four")
"""
)
result = pytester.runpytest("-rfxXs")
result.stdout.fnmatch_lines(
["FAIL*test_1*", "XFAIL*test_2*", "XPASS*test_3*", "SKIP*four*"]
)
def test_reportchars_error(pytester: Pytester) -> None:
pytester.makepyfile(
conftest="""
def pytest_runtest_teardown():
assert 0
""",
test_simple="""
def test_foo():
pass
""",
)
result = pytester.runpytest("-rE")
result.stdout.fnmatch_lines(["ERROR*test_foo*"])
def test_reportchars_all(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def test_1():
assert 0
@pytest.mark.xfail
def test_2():
assert 0
@pytest.mark.xfail
def test_3():
pass
def test_4():
pytest.skip("four")
@pytest.fixture
def fail():
assert 0
def test_5(fail):
pass
"""
)
result = pytester.runpytest("-ra")
result.stdout.fnmatch_lines(
[
"SKIP*four*",
"XFAIL*test_2*",
"XPASS*test_3*",
"ERROR*test_5*",
"FAIL*test_1*",
]
)
def test_reportchars_all_error(pytester: Pytester) -> None:
pytester.makepyfile(
conftest="""
def pytest_runtest_teardown():
assert 0
""",
test_simple="""
def test_foo():
pass
""",
)
result = pytester.runpytest("-ra")
result.stdout.fnmatch_lines(["ERROR*test_foo*"])
def test_errors_in_xfail_skip_expressions(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.skipif("asd")
def test_nameerror():
pass
@pytest.mark.xfail("syntax error")
def test_syntax():
pass
def test_func():
pass
"""
)
result = pytester.runpytest()
expected = [
"*ERROR*test_nameerror*",
"*asd*",
"",
"During handling of the above exception, another exception occurred:",
]
expected += [
"*evaluating*skipif*condition*",
"*asd*",
"*ERROR*test_syntax*",
"*evaluating*xfail*condition*",
" syntax error",
" ^",
"SyntaxError: invalid syntax",
"*1 pass*2 errors*",
]
result.stdout.fnmatch_lines(expected)
def test_xfail_skipif_with_globals(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
x = 3
@pytest.mark.skipif("x == 3")
def test_skip1():
pass
@pytest.mark.xfail("x == 3")
def test_boolean():
assert 0
"""
)
result = pytester.runpytest("-rsx")
result.stdout.fnmatch_lines(["*SKIP*x == 3*", "*XFAIL*test_boolean*x == 3*"])
def test_default_markers(pytester: Pytester) -> None:
result = pytester.runpytest("--markers")
result.stdout.fnmatch_lines(
[
"*skipif(condition, ..., [*], reason=...)*skip*",
"*xfail(condition, ..., [*], reason=..., run=True, raises=None, strict=strict_xfail)*expected failure*",
]
)
def test_xfail_test_setup_exception(pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_runtest_setup():
0 / 0
"""
)
p = pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail
def test_func():
assert 0
"""
)
result = pytester.runpytest(p)
assert result.ret == 0
assert "xfailed" in result.stdout.str()
result.stdout.no_fnmatch_line("*xpassed*")
def test_imperativeskip_on_xfail_test(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail
def test_that_fails():
assert 0
@pytest.mark.skipif("True")
def test_hello():
pass
"""
)
pytester.makeconftest(
"""
import pytest
def pytest_runtest_setup(item):
pytest.skip("abc")
"""
)
result = pytester.runpytest("-rsxX")
result.stdout.fnmatch_lines_random(
"""
*SKIP*abc*
*SKIP*condition: True*
*2 skipped*
"""
)
| TestSkipif |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/dataframes.py | {
"start": 10395,
"end": 10705
} | class ____(Capture):
def __init__(self, left, right, ctx) -> None:
self.ctx = ctx
self.left = left
self.right = right
def __str__(self) -> str:
return f"{self.left} * {self.right}"
def execute(self):
return get_val(self.left) * get_val(self.right)
| CaptureMul |
python | getsentry__sentry | src/sentry/integrations/vercel/webhook.py | {
"start": 1601,
"end": 4784
} | class ____(TypedDict):
version: str
projects: list[str]
refs: list[dict[str, str]]
def verify_signature(request):
signature = request.META.get("HTTP_X_VERCEL_SIGNATURE")
secret = options.get("vercel.client-secret")
expected = hmac.new(
key=secret.encode("utf-8"), msg=bytes(request.body), digestmod=hashlib.sha1
).hexdigest()
return constant_time_compare(expected, signature)
def safe_json_parse(resp):
if resp.headers.get("content-type") == "application/json":
return resp.json()
return None
def get_commit_sha(meta: Mapping[str, str]) -> str:
"""Find the commit SHA so we can use it as as the release."""
commit_sha = (
meta.get("githubCommitSha") or meta.get("gitlabCommitSha") or meta.get("bitbucketCommitSha")
)
if not commit_sha:
# This can happen with manual builds.
raise NoCommitFoundError("No commit found")
return commit_sha
def get_repository(meta: Mapping[str, str]) -> str:
"""Construct the repository string depending what provider we use."""
try:
if meta.get("githubCommitSha"):
# We use these instead of githubOrg and githubRepo since it's the repo the user has access to.
return f'{meta["githubCommitOrg"]}/{meta["githubCommitRepo"]}'
if meta.get("gitlabCommitSha"):
# GitLab repos are formatted with a space for some reason.
return f'{meta["gitlabProjectNamespace"]} / {meta["gitlabProjectName"]}'
if meta.get("bitbucketCommitSha"):
return f'{meta["bitbucketRepoOwner"]}/{meta["bitbucketRepoName"]}'
except KeyError:
pass
raise MissingRepositoryError("Could not determine repository")
def get_payload_and_token(
payload: Mapping[str, Any], organization_id: int, sentry_project_id: int
) -> tuple[_ReleasePayload, str]:
meta = payload["deployment"]["meta"]
# look up the project so we can get the slug
project = project_service.get_by_id(organization_id=organization_id, id=sentry_project_id)
if project is None:
raise Project.DoesNotExist
# find the connected sentry app installation
installation_for_provider = SentryAppInstallationForProvider.objects.select_related(
"sentry_app_installation"
).get(organization_id=organization_id, provider="vercel")
sentry_app_installation = installation_for_provider.sentry_app_installation
# find a token associated with the installation so we can use it for authentication
sentry_app_installation_token = (
SentryAppInstallationToken.objects.select_related("api_token")
.filter(sentry_app_installation=sentry_app_installation)
.first()
)
if not sentry_app_installation_token:
raise SentryAppInstallationToken.DoesNotExist()
commit_sha = get_commit_sha(meta)
repository = get_repository(meta)
release_payload: _ReleasePayload = {
"version": commit_sha,
"projects": [project.slug],
"refs": [{"repository": repository, "commit": commit_sha}],
}
return release_payload, sentry_app_installation_token.api_token.token
@control_silo_endpoint
| _ReleasePayload |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 55871,
"end": 58535
} | class ____:
def test_ca_true_pathlen_6(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs", "pathLenConstraint6CACert.crt"
),
x509.load_der_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.critical is True
assert ext.value.ca is True
assert ext.value.path_length == 6
def test_path_length_zero(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "bc_path_length_zero.pem"),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.critical is True
assert ext.value.ca is True
assert ext.value.path_length == 0
def test_ca_true_no_pathlen(self, backend):
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.critical is True
assert ext.value.ca is True
assert ext.value.path_length is None
def test_ca_false(self, backend):
cert = _load_cert(
os.path.join("x509", "cryptography.io.pem"),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.critical is True
assert ext.value.ca is False
assert ext.value.path_length is None
def test_no_basic_constraints(self, backend):
cert = _load_cert(
os.path.join(
"x509",
"PKITS_data",
"certs",
"ValidCertificatePathTest1EE.crt",
),
x509.load_der_x509_certificate,
)
with pytest.raises(x509.ExtensionNotFound):
cert.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
def test_basic_constraint_not_critical(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom", "basic_constraints_not_critical.pem"
),
x509.load_pem_x509_certificate,
)
ext = cert.extensions.get_extension_for_class(x509.BasicConstraints)
assert ext is not None
assert ext.critical is False
assert ext.value.ca is False
| TestBasicConstraintsExtension |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 4252,
"end": 4860
} | class ____(ReprForm):
_choice = forms.ChoiceField(
choices=(("cola", "Cola"), ("tea", "Tea"), ("water", "Water"))
)
_multiple = forms.MultipleChoiceField(
choices=(("cola", "Cola"), ("tea", "Tea"), ("water", "Water"))
)
_typed = forms.TypedChoiceField(
choices=(("1", "one"), ("2", "two"), ("3", "three"), ("4", "four")),
coerce=int,
empty_value=0,
)
_typed_multiple = forms.TypedMultipleChoiceField(
choices=(("1", "one"), ("2", "two"), ("3", "three"), ("4", "four")),
coerce=int,
empty_value=0,
)
| ChoiceFieldForm |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numerictypes.py | {
"start": 726,
"end": 1416
} | class ____(TestCase):
def test_scalar_loses1(self):
res = np.find_common_type(["f4", "f4", "i2"], ["f8"])
assert_(res == "f4")
def test_scalar_loses2(self):
res = np.find_common_type(["f4", "f4"], ["i8"])
assert_(res == "f4")
def test_scalar_wins(self):
res = np.find_common_type(["f4", "f4", "i2"], ["c8"])
assert_(res == "c8")
def test_scalar_wins2(self):
res = np.find_common_type(["u4", "i4", "i4"], ["f4"])
assert_(res == "f8")
def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose
res = np.find_common_type(["u8", "i8", "i8"], ["f8"])
assert_(res == "f8")
| TestCommonType |
python | sphinx-doc__sphinx | sphinx/environment/adapters/indexentries.py | {
"start": 1392,
"end": 9753
} | class ____:
def __init__(self, env: BuildEnvironment) -> None:
self.env = env
def create_index(
self,
builder: Builder,
group_entries: bool = True,
_fixre: re.Pattern[str] = re.compile(r'(.*) ([(][^()]*[)])'),
) -> _Index:
"""Create the real index from the collected index entries."""
new: _IndexEntryMap = {}
rel_uri: str | Literal[False]
index_domain = self.env.domains.index_domain
for docname, entries in index_domain.entries.items():
try:
rel_uri = builder.get_relative_uri('genindex', docname)
except NoUri:
rel_uri = False
# new entry types must be listed in directives/other.py!
for entry_type, value, target_id, main, category_key in entries:
uri = rel_uri is not False and f'{rel_uri}#{target_id}'
try:
if entry_type == 'single':
try:
entry, sub_entry = _split_into(2, 'single', value)
except ValueError:
(entry,) = _split_into(1, 'single', value)
sub_entry = ''
_add_entry(
entry, sub_entry, main, dic=new, link=uri, key=category_key
)
elif entry_type == 'pair':
first, second = _split_into(2, 'pair', value)
_add_entry(
first, second, main, dic=new, link=uri, key=category_key
)
_add_entry(
second, first, main, dic=new, link=uri, key=category_key
)
elif entry_type == 'triple':
first, second, third = _split_into(3, 'triple', value)
_add_entry(
first,
second + ' ' + third,
main,
dic=new,
link=uri,
key=category_key,
)
_add_entry(
second,
third + ', ' + first,
main,
dic=new,
link=uri,
key=category_key,
)
_add_entry(
third,
first + ' ' + second,
main,
dic=new,
link=uri,
key=category_key,
)
elif entry_type == 'see':
first, second = _split_into(2, 'see', value)
_add_entry(
first,
_('see %s') % second,
None,
dic=new,
link=False,
key=category_key,
)
elif entry_type == 'seealso':
first, second = _split_into(2, 'see', value)
_add_entry(
first,
_('see also %s') % second,
None,
dic=new,
link=False,
key=category_key,
)
else:
logger.warning(
__('unknown index entry type %r'),
entry_type,
location=docname,
type='index',
)
except ValueError as err:
logger.warning(str(err), location=docname, type='index')
for targets, sub_items, _category_key in new.values():
targets.sort(key=_key_func_0)
for sub_targets, _sub_category_key in sub_items.values():
sub_targets.sort(key=_key_func_0)
new_list: list[tuple[str, _IndexEntry]] = sorted(new.items(), key=_key_func_1)
if group_entries:
# fixup entries: transform
# func() (in module foo)
# func() (in module bar)
# into
# func()
# (in module foo)
# (in module bar)
old_key = ''
old_sub_items: _IndexEntrySubItems = {}
i = 0
while i < len(new_list):
key, (targets, sub_items, category_key) = new_list[i]
# cannot move if it has sub_items; structure gets too complex
if not sub_items:
m = _fixre.match(key)
if m:
if old_key == m.group(1):
# prefixes match: add entry as subitem of the
# previous entry
prev = old_sub_items.setdefault(m[2], ([], category_key))
prev[0].extend(targets)
del new_list[i]
continue
old_key = m.group(1)
else:
old_key = key
old_sub_items = sub_items
i += 1
grouped = []
for group_key, group in groupby(new_list, _group_by_func):
group_list = []
for group_entry in group:
entry_key, (targets, sub_items, category_key) = group_entry
pairs = [
(sub_key, sub_targets)
for (sub_key, (sub_targets, _sub_category_key)) in sub_items.items()
]
pairs.sort(key=_key_func_2)
group_list.append((entry_key, (targets, pairs, category_key)))
grouped.append((group_key, group_list))
return grouped
def _add_entry(
word: str,
subword: str,
main: str | None,
*,
dic: _IndexEntryMap,
link: str | Literal[False],
key: _IndexEntryCategoryKey,
) -> None:
entry = dic.setdefault(word, ([], {}, key))
if subword:
targets = entry[1].setdefault(subword, ([], key))[0]
else:
targets = entry[0]
if link:
targets.append((main, link))
def _key_func_0(entry: _IndexEntryTarget) -> tuple[bool, str | Literal[False]]:
"""Sort the index entries for same keyword."""
main, uri = entry
return not main, uri # show main entries at first
def _key_func_1(entry: tuple[str, _IndexEntry]) -> tuple[tuple[int, str], str]:
"""Sort the index entries"""
key, (_targets, _sub_items, category_key) = entry
if category_key:
# using the specified category key to sort
key = category_key
lc_key = unicodedata.normalize('NFD', key.lower())
lc_key = lc_key.removeprefix('\N{RIGHT-TO-LEFT MARK}')
if not lc_key[0:1].isalpha() and not lc_key.startswith('_'):
# put symbols at the front of the index (0)
group = 0
else:
# put non-symbol characters at the following group (1)
group = 1
# ensure a deterministic order *within* letters by also sorting on
# the entry itself
return (group, lc_key), entry[0]
def _key_func_2(entry: tuple[str, _IndexEntryTargets]) -> str:
"""Sort the sub-index entries"""
key = unicodedata.normalize('NFD', entry[0].lower())
key = key.removeprefix('\N{RIGHT-TO-LEFT MARK}')
if key[0:1].isalpha() or key.startswith('_'):
key = chr(127) + key
return key
def _group_by_func(entry: tuple[str, _IndexEntry]) -> str:
"""Group the entries by letter or category key."""
key, (_targets, _sub_items, category_key) = entry
if category_key is not None:
return category_key
# now calculate the key
key = key.removeprefix('\N{RIGHT-TO-LEFT MARK}')
letter = unicodedata.normalize('NFD', key[0])[0].upper()
if letter.isalpha() or letter == '_':
return letter
# get all other symbols under one heading
return _('Symbols')
| IndexEntries |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 9908,
"end": 10638
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, stock_ticker: str, api_key: str):
"""Airbyte Source for Stock Ticker Api Tutorial.
Documentation can be found at https://polygon.io/docs/stocks/get_v2_aggs_grouped_locale_us_market_stocks__date
Args:
name (str): The name of the destination.
stock_ticker (str): The stock ticker to track
api_key (str): The Polygon.io Stocks API key to use to hit the API.
"""
self.stock_ticker = check.str_param(stock_ticker, "stock_ticker")
self.api_key = check.str_param(api_key, "api_key")
super().__init__("Stock Ticker Api Tutorial", name)
| StockTickerApiTutorialSource |
python | getsentry__sentry | src/sentry/search/snuba/executors.py | {
"start": 5309,
"end": 27661
} | class ____(metaclass=ABCMeta):
"""This class serves as a template for Query Executors.
We subclass it in order to implement query methods (we use it to implement two classes: joined
Postgres+Snuba queries, and Snuba only queries)
It's used to keep the query logic out of the actual search backend,
which can now just build query parameters and use the appropriate query executor to run the query
"""
@property
@abstractmethod
def aggregation_defs(self) -> Sequence[str] | Expression:
"""This method should return a dict of key:value
where key is a field name for your aggregation
and value is the aggregation function"""
raise NotImplementedError
@property
@abstractmethod
def dependency_aggregations(self) -> Mapping[str, list[str]]:
"""This method should return a dict of key:value
where key is an aggregation_def field name
and value is a list of aggregation field names that the 'key' aggregation requires."""
raise NotImplementedError
@property
def empty_result(self) -> CursorResult[Group]:
# TODO: Add types to paginators and remove this
return cast(CursorResult[Group], Paginator(Group.objects.none()).get_result())
@property
@abstractmethod
def dataset(self) -> Dataset:
"""This function should return an enum from snuba.Dataset (like snuba.Dataset.Events)"""
raise NotImplementedError
@property
@abstractmethod
def sort_strategies(self) -> Mapping[str, str]:
raise NotImplementedError
@property
@abstractmethod
def postgres_only_fields(self) -> set[str]:
raise NotImplementedError
@abstractmethod
def query(
self,
projects: Sequence[Project],
retention_window_start: datetime | None,
group_queryset: BaseQuerySet,
environments: Sequence[Environment] | None,
sort_by: str,
limit: int,
cursor: Cursor | None,
count_hits: bool,
paginator_options: Mapping[str, Any] | None,
search_filters: Sequence[SearchFilter] | None,
date_from: datetime | None,
date_to: datetime | None,
max_hits: int | None = None,
actor: Any | None = None,
aggregate_kwargs: TrendsSortWeights | None = None,
*,
referrer: str,
) -> CursorResult[Group]:
"""This function runs your actual query and returns the results
We usually return a paginator object, which contains the results and the number of hits"""
raise NotImplementedError
def _convert_search_filters(
self,
organization_id: int,
project_ids: Sequence[int],
environments: Sequence[str] | None,
search_filters: Sequence[SearchFilter],
) -> list[Any | None]:
"""Converts the SearchFilter format into snuba-compatible clauses"""
converted_filters: list[Sequence[Any] | None] = []
for search_filter in search_filters or ():
conditions, projects_to_filter, group_ids = format_search_filter(
search_filter,
params={
"organization_id": organization_id,
"project_id": project_ids,
"environment": environments,
},
)
# if no re-formatted conditions, use fallback method for selected groups
new_condition = None
if conditions:
new_condition = conditions[0]
elif group_ids:
new_condition = convert_search_filter_to_snuba_query(
search_filter,
params={
"organization_id": organization_id,
"project_id": project_ids,
"environment": environments,
},
)
if new_condition:
converted_filters.append(new_condition)
return converted_filters
def _prepare_aggregations(
self,
sort_field: str,
start: datetime,
end: datetime,
having: Sequence[Sequence[Any]],
aggregate_kwargs: TrendsSortWeights | None = None,
replace_trends_aggregation: bool | None = False,
) -> list[Any]:
extra_aggregations = self.dependency_aggregations.get(sort_field, [])
required_aggregations = set([sort_field, "total"] + extra_aggregations)
for h in having:
alias = h[0]
required_aggregations.add(alias)
aggregations = []
for alias in required_aggregations:
aggregation = self.aggregation_defs[alias]
if replace_trends_aggregation and alias == "trends":
aggregation = self.aggregation_defs["trends_issue_platform"]
if callable(aggregation):
if aggregate_kwargs:
aggregation = aggregation(start, end, aggregate_kwargs.get(alias, {}))
else:
aggregation = aggregation(start, end, DEFAULT_TRENDS_WEIGHTS)
aggregations.append(aggregation + [alias])
return aggregations
def _prepare_params_for_category(
self,
group_category: int,
query_partial: IntermediateSearchQueryPartial,
organization: Organization,
project_ids: Sequence[int],
environments: Sequence[str] | None,
group_ids: Sequence[int] | None,
filters: Mapping[str, Sequence[int]],
search_filters: Sequence[SearchFilter],
sort_field: str,
start: datetime,
end: datetime,
cursor: Cursor | None,
get_sample: bool,
actor: Any | None = None,
aggregate_kwargs: TrendsSortWeights | None = None,
) -> SnubaQueryParams | None:
"""
:raises UnsupportedSearchQuery: when search_filters includes conditions on a dataset that doesn't support it
"""
if group_category in SEARCH_FILTER_UPDATERS:
# remove filters not relevant to the group_category
search_filters = SEARCH_FILTER_UPDATERS[group_category](search_filters)
# convert search_filters to snuba format
converted_filters = self._convert_search_filters(
organization.id, project_ids, environments, search_filters
)
# categorize the clauses into having or condition clauses
having = []
conditions = []
for search_filter, converted_filter in zip(search_filters, converted_filters):
if converted_filter is not None:
# Ensure that no user-generated tags that clashes with aggregation_defs is added to having
if search_filter.key.name in self.aggregation_defs and not search_filter.key.is_tag:
having.append(converted_filter)
else:
conditions.append(converted_filter)
if sort_field == "trends" and group_category is not GroupCategory.ERROR.value:
aggregations = self._prepare_aggregations(
sort_field, start, end, having, aggregate_kwargs, True
)
else:
aggregations = self._prepare_aggregations(
sort_field, start, end, having, aggregate_kwargs
)
if cursor is not None:
having.append((sort_field, ">=" if cursor.is_prev else "<=", cursor.value))
selected_columns = []
if get_sample:
query_hash = md5(json.dumps(conditions).encode("utf-8")).hexdigest()[:8]
selected_columns.append(["cityHash64", [f"'{query_hash}'", "group_id"], "sample"])
orderby = ["sample"]
else:
# Get the top matching groups by score, i.e. the actual search results
# in the order that we want them.
orderby = [f"-{sort_field}", "group_id"] # ensure stable sort within the same score
pinned_query_partial: SearchQueryPartial = cast(
SearchQueryPartial,
functools.partial(
query_partial,
groupby=["group_id"],
having=having,
orderby=orderby,
),
)
strategy = get_search_strategies()[group_category]
snuba_query_params = strategy(
pinned_query_partial,
selected_columns,
aggregations,
organization.id,
project_ids,
environments,
group_ids,
filters,
conditions,
actor,
)
if snuba_query_params is not None:
snuba_query_params.kwargs["tenant_ids"] = {"organization_id": organization.id}
return snuba_query_params
def snuba_search(
self,
start: datetime,
end: datetime,
project_ids: Sequence[int],
environment_ids: Sequence[int] | None,
sort_field: str,
organization: Organization,
cursor: Cursor | None = None,
group_ids: Sequence[int] | None = None,
limit: int | None = None,
offset: int = 0,
get_sample: bool = False,
search_filters: Sequence[SearchFilter] | None = None,
actor: Any | None = None,
aggregate_kwargs: TrendsSortWeights | None = None,
*,
referrer: str,
) -> tuple[list[tuple[int, Any]], int]:
"""Queries Snuba for events with associated Groups based on the input criteria.
Returns a tuple of:
* a sorted list of (group_id, group_score) tuples sorted descending by score,
* the count of total results (rows) available for this query.
"""
filters = {"project_id": project_ids}
environments = None
if environment_ids is not None:
filters["environment"] = environment_ids
environments = list(
Environment.objects.filter(
organization_id=organization.id, id__in=environment_ids
).values_list("name", flat=True)
)
referrer = referrer or "search"
referrer = f"{referrer}_sample" if get_sample else referrer
snuba_search_filters = [
sf
for sf in search_filters or ()
# remove any search_filters that are only available in postgres, we special case date
if not (sf.key.name in self.postgres_only_fields.union(["date", "timestamp"]))
]
# common pinned parameters that won't change based off datasource
query_partial: IntermediateSearchQueryPartial = cast(
IntermediateSearchQueryPartial,
functools.partial(
aliased_query_params,
start=start,
end=end,
limit=limit,
offset=offset,
referrer=referrer,
totals=True, # Needs to have totals_mode=after_having_exclusive so we get groups matching HAVING only
turbo=get_sample, # Turn off FINAL when in sampling mode
sample=1, # Don't use clickhouse sampling, even when in turbo mode.
),
)
group_categories = group_categories_from_search_filters(search_filters, organization, actor)
query_params_for_categories = {}
for gc in group_categories:
try:
query_params = self._prepare_params_for_category(
gc,
query_partial,
organization,
project_ids,
environments,
group_ids,
filters,
snuba_search_filters,
sort_field,
start,
end,
cursor,
get_sample,
actor,
aggregate_kwargs,
)
except UnsupportedSearchQuery:
pass
else:
if query_params is not None:
query_params_for_categories[gc] = query_params
try:
bulk_query_results = bulk_raw_query(
list(query_params_for_categories.values()), referrer=referrer
)
except Exception:
metrics.incr(
"snuba.search.group_category_bulk",
tags={
GroupCategory(gc_val).name.lower(): True
for gc_val, _ in query_params_for_categories.items()
},
)
# one of the parallel bulk raw queries failed (maybe the issue platform dataset),
# we'll fallback to querying for errors only
if GroupCategory.ERROR.value in query_params_for_categories.keys():
bulk_query_results = bulk_raw_query(
[query_params_for_categories[GroupCategory.ERROR.value]], referrer=referrer
)
else:
raise
rows: list[MergeableRow] = []
total = 0
row_length = 0
for bulk_result in bulk_query_results:
if bulk_result:
if bulk_result["data"]:
rows.extend(bulk_result["data"])
if bulk_result["totals"]["total"]:
total += bulk_result["totals"]["total"]
row_length += len(bulk_result)
rows.sort(key=lambda row: row["group_id"])
if not get_sample:
metrics.distribution("snuba.search.num_result_groups", row_length)
if get_sample:
sort_field = "sample"
return [(row["group_id"], row[sort_field]) for row in rows], total # type: ignore[literal-required]
def has_sort_strategy(self, sort_by: str) -> bool:
return sort_by in self.sort_strategies.keys()
def trends_aggregation(
start: datetime,
end: datetime,
aggregate_kwargs: TrendsSortWeights,
) -> Sequence[str]:
return trends_aggregation_impl(
TrendsParams(
max_pow=16,
min_score=0.01,
event_age_weight=1,
log_level_weight=aggregate_kwargs["log_level"],
stacktrace_weight=aggregate_kwargs["has_stacktrace"],
event_halflife_hours=aggregate_kwargs["event_halflife_hours"],
issue_age_weight=1,
issue_halflife_hours=aggregate_kwargs["issue_halflife_hours"],
relative_volume_weight=aggregate_kwargs["relative_volume"],
v2=aggregate_kwargs["v2"],
normalize=aggregate_kwargs["norm"],
),
"timestamp",
True,
start,
end,
)
def trends_issue_platform_aggregation(
start: datetime,
end: datetime,
aggregate_kwargs: TrendsSortWeights,
) -> Sequence[str]:
return trends_aggregation_impl(
TrendsParams(
max_pow=16,
min_score=0.01,
event_age_weight=1,
log_level_weight=aggregate_kwargs["log_level"],
stacktrace_weight=0, # issue-platform occurrences won't have stacktrace
event_halflife_hours=aggregate_kwargs["event_halflife_hours"],
issue_age_weight=1,
issue_halflife_hours=aggregate_kwargs["issue_halflife_hours"],
relative_volume_weight=aggregate_kwargs["relative_volume"],
v2=aggregate_kwargs["v2"],
normalize=aggregate_kwargs["norm"],
),
"client_timestamp",
False,
start,
end,
)
def trends_aggregation_impl(
params: TrendsParams,
timestamp_column: str,
use_stacktrace: bool,
start: datetime,
end: datetime,
) -> Sequence[str]:
min_score = params.min_score
max_pow = params.max_pow
event_age_weight = params.event_age_weight
event_halflife_hours = params.event_halflife_hours
log_level_weight = params.log_level_weight
stacktrace_weight = params.stacktrace_weight
relative_volume_weight = params.relative_volume_weight
issue_age_weight = params.issue_age_weight
issue_halflife_hours = params.issue_halflife_hours
event_age_hours = f"divide(now() - {timestamp_column}, 3600)"
issue_age_hours = f"divide(now() - min({timestamp_column}), 3600)"
log_level_score = "multiIf(equals(level, 'fatal'), 1.0, equals(level, 'error'), 0.66, equals(level, 'warning'), 0.33, 0.0)"
stacktrace_score = "if(notEmpty(exception_stacks.type), 1.0, 0.0)"
# event_agg_rank:
# ls = log_level_score {1.0, 0.66, 0.33, 0}
# lw = log_level_weight [0, 10]
# ss = stacktrace_score {1.0, 0.0}
# sw = stacktrace_weight [0, 3]
# as = event_age_score [1, 0]
# aw = event_age_weight [1, 5]
#
# (ls * lw) + (ss * sw) + (as * aw) min(f(x) = 0, when individual scores are all 0
# f(x) = --------------------------------- , max(f(x)) = 1, when individual scores are all 1
# lw + sw + aw
#
if use_stacktrace:
event_agg_numerator = f"plus(plus(multiply({log_level_score}, {log_level_weight}), multiply({stacktrace_score}, {stacktrace_weight})), {event_age_weight})"
else:
event_agg_numerator = (
f"plus(multiply({log_level_score}, {log_level_weight}), {event_age_weight})"
)
event_agg_denominator = (
f"plus(plus({log_level_weight}, {stacktrace_weight}), {event_age_weight})"
)
event_agg_rank = f"divide({event_agg_numerator}, {event_agg_denominator})" # values from [0, 1]
aggregate_issue_score = f"greatest({min_score}, divide({issue_age_weight}, pow(2, least({max_pow}, divide({issue_age_hours}, {issue_halflife_hours})))))"
if not params.v2:
aggregate_event_score = f"greatest({min_score}, sum(divide({event_agg_rank}, pow(2, least({max_pow}, divide({event_age_hours}, {event_halflife_hours}))))))"
return [f"multiply({aggregate_event_score}, {aggregate_issue_score})", ""]
else:
# * apply log to event score summation to clamp the contribution of event scores to a reasonable maximum
# * add an extra 'relative volume score' (# of events in past 60 mins / # of events in the past 7 days)
# to factor in the volume of events that recently were fired versus the past. This will up-rank issues
# that are more recently active as a function of the overall amount of events grouped to that issue
# * add a configurable weight to 'relative volume score'
# * conditionally normalize all the scores so the range of values sweeps from 0.0 to 1.0
# aggregate_event_score:
#
# ------------------------------------------------------------------------------
# part 1 (summation over all events in group)
# x = event_age_hours
# k = event_halflife_hours (fixed to a constant)
# 1
# Σ ------- = Σ ([1, 0), [1, 0), [1, 0), ...) ~= [0, +inf] = g(x)
# 2^(x/k)
#
# ------------------------------------------------------------------------------
# part 2a (offset by 1 to remove possibility of ln(0))
# g(x) + 1 = [1, +inf] = h(x)
#
# ------------------------------------------------------------------------------
# part 2b (apply ln to clamp exponential growth and apply a 'fixed' maximum)
# x = 1, e, 10, 1000, 1000000, 1000000000, ...
# ln(h(x)) = [ln(1), ln(+inf)] = 0, 1, ~2.30, ~6.09, ~13.81, ~20.72, +inf
aggregate_event_score = f"log(plus(1, sum(divide({event_agg_rank}, pow(2, divide({event_age_hours}, {event_halflife_hours}))))))"
date_period = end - start
if date_period.days >= 7:
overall_event_count_seconds = 3600 * 24 * 7
recent_event_count_seconds = 3600
else:
overall_event_count_seconds = int(date_period.total_seconds())
recent_event_count_seconds = floor(overall_event_count_seconds * 0.01)
recent_event_count = (
f"countIf(lessOrEquals(minus(now(), {timestamp_column}), {recent_event_count_seconds}))"
)
overall_event_count = f"countIf(lessOrEquals(minus(now(), {timestamp_column}), {overall_event_count_seconds}))"
max_relative_volume_weight = 10
if relative_volume_weight > max_relative_volume_weight:
relative_volume_weight = max_relative_volume_weight
relative_volume_score = f"divide({recent_event_count}, plus({overall_event_count}, 1))"
scaled_relative_volume_score = f"divide(multiply({relative_volume_weight}, {relative_volume_score}), {max_relative_volume_weight})"
if not params.normalize:
return [
f"multiply(multiply({aggregate_issue_score}, greatest({min_score}, {aggregate_event_score})), greatest({min_score}, {scaled_relative_volume_score}))",
"",
]
else:
# aggregate_issue_score:
# x = issue_age_hours
# k = issue_halflife_hours (fixed to a constant)
# k = 4
# lim 1 x = 0, 1, 10, 100000000
# x -> inf ------- f(x) = 1, ~0.84, ~0.16, ~0
# 2^(x/k)
normalized_aggregate_issue_score = aggregate_issue_score # already ranges from 1 to 0
normalized_relative_volume_score = (
scaled_relative_volume_score # already normalized since it's a percentage
)
# aggregate_event_score ranges from [0, +inf], as the amount of events grouped to this issue
# increases. we apply an upper bound of 21 to the log of the summation of the event scores
# and then divide by 21 so the normalized score sweeps from [0, 1]
# In practice, itll take a degenerate issue with an absurd amount of events for the
# aggregate_event_score to reach to upper limit of ~21 (and normalized score of 1)
normalized_aggregate_event_score = f"divide(least({aggregate_event_score}, 21), 21)"
return [
f"plus(plus({normalized_aggregate_issue_score}, {normalized_aggregate_event_score}), {normalized_relative_volume_score})",
"",
]
| AbstractQueryExecutor |
python | getsentry__sentry | src/sentry/replays/usecases/ingest/event_parser.py | {
"start": 654,
"end": 970
} | class ____:
alt: str
aria_label: str
classes: list[str]
component_name: str
id: str
is_dead: int
is_rage: int
node_id: int
role: str
selector: str
tag: str
testid: str
text: str
timestamp: int
title: str
url: str | None
@dataclass(frozen=True)
| ClickEvent |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run_event.py | {
"start": 297,
"end": 743
} | class ____(BaseModel):
"""Error information model."""
message: str
className: Optional[str] = None
stack: Optional[list[str]] = None
cause: Optional["DgApiErrorInfo"] = None
class Config:
from_attributes = True
def get_stack_trace_string(self) -> str:
"""Get the stack trace as a formatted string."""
if not self.stack:
return ""
return "\n".join(self.stack)
| DgApiErrorInfo |
python | gevent__gevent | src/greentest/3.10/test_context.py | {
"start": 12534,
"end": 31362
} | class ____(unittest.TestCase):
def test_hashkey_helper_1(self):
k1 = HashKey(10, 'aaa')
k2 = HashKey(10, 'bbb')
self.assertNotEqual(k1, k2)
self.assertEqual(hash(k1), hash(k2))
d = dict()
d[k1] = 'a'
d[k2] = 'b'
self.assertEqual(d[k1], 'a')
self.assertEqual(d[k2], 'b')
def test_hamt_basics_1(self):
h = hamt()
h = None # NoQA
def test_hamt_basics_2(self):
h = hamt()
self.assertEqual(len(h), 0)
h2 = h.set('a', 'b')
self.assertIsNot(h, h2)
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertIsNone(h.get('a'))
self.assertEqual(h.get('a', 42), 42)
self.assertEqual(h2.get('a'), 'b')
h3 = h2.set('b', 10)
self.assertIsNot(h2, h3)
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertEqual(len(h3), 2)
self.assertEqual(h3.get('a'), 'b')
self.assertEqual(h3.get('b'), 10)
self.assertIsNone(h.get('b'))
self.assertIsNone(h2.get('b'))
self.assertIsNone(h.get('a'))
self.assertEqual(h2.get('a'), 'b')
h = h2 = h3 = None
def test_hamt_basics_3(self):
h = hamt()
o = object()
h1 = h.set('1', o)
h2 = h1.set('1', o)
self.assertIs(h1, h2)
def test_hamt_basics_4(self):
h = hamt()
h1 = h.set('key', [])
h2 = h1.set('key', [])
self.assertIsNot(h1, h2)
self.assertEqual(len(h1), 1)
self.assertEqual(len(h2), 1)
self.assertIsNot(h1.get('key'), h2.get('key'))
def test_hamt_collision_1(self):
k1 = HashKey(10, 'aaa')
k2 = HashKey(10, 'bbb')
k3 = HashKey(10, 'ccc')
h = hamt()
h2 = h.set(k1, 'a')
h3 = h2.set(k2, 'b')
self.assertEqual(h.get(k1), None)
self.assertEqual(h.get(k2), None)
self.assertEqual(h2.get(k1), 'a')
self.assertEqual(h2.get(k2), None)
self.assertEqual(h3.get(k1), 'a')
self.assertEqual(h3.get(k2), 'b')
h4 = h3.set(k2, 'cc')
h5 = h4.set(k3, 'aa')
self.assertEqual(h3.get(k1), 'a')
self.assertEqual(h3.get(k2), 'b')
self.assertEqual(h4.get(k1), 'a')
self.assertEqual(h4.get(k2), 'cc')
self.assertEqual(h4.get(k3), None)
self.assertEqual(h5.get(k1), 'a')
self.assertEqual(h5.get(k2), 'cc')
self.assertEqual(h5.get(k2), 'cc')
self.assertEqual(h5.get(k3), 'aa')
self.assertEqual(len(h), 0)
self.assertEqual(len(h2), 1)
self.assertEqual(len(h3), 2)
self.assertEqual(len(h4), 2)
self.assertEqual(len(h5), 3)
def test_hamt_collision_3(self):
# Test that iteration works with the deepest tree possible.
# https://github.com/python/cpython/issues/93065
C = HashKey(0b10000000_00000000_00000000_00000000, 'C')
D = HashKey(0b10000000_00000000_00000000_00000000, 'D')
E = HashKey(0b00000000_00000000_00000000_00000000, 'E')
h = hamt()
h = h.set(C, 'C')
h = h.set(D, 'D')
h = h.set(E, 'E')
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# BitmapNode(size=4 count=2 bitmap=0b101):
# <Key name:E hash:0>: 'E'
# NULL:
# CollisionNode(size=4 id=0x107a24520):
# <Key name:C hash:2147483648>: 'C'
# <Key name:D hash:2147483648>: 'D'
self.assertEqual({k.name for k in h.keys()}, {'C', 'D', 'E'})
def test_hamt_stress(self):
COLLECTION_SIZE = 7000
TEST_ITERS_EVERY = 647
CRASH_HASH_EVERY = 97
CRASH_EQ_EVERY = 11
RUN_XTIMES = 3
for _ in range(RUN_XTIMES):
h = hamt()
d = dict()
for i in range(COLLECTION_SIZE):
key = KeyStr(i)
if not (i % CRASH_HASH_EVERY):
with HaskKeyCrasher(error_on_hash=True):
with self.assertRaises(HashingError):
h.set(key, i)
h = h.set(key, i)
if not (i % CRASH_EQ_EVERY):
with HaskKeyCrasher(error_on_eq=True):
with self.assertRaises(EqError):
h.get(KeyStr(i)) # really trigger __eq__
d[key] = i
self.assertEqual(len(d), len(h))
if not (i % TEST_ITERS_EVERY):
self.assertEqual(set(h.items()), set(d.items()))
self.assertEqual(len(h.items()), len(d.items()))
self.assertEqual(len(h), COLLECTION_SIZE)
for key in range(COLLECTION_SIZE):
self.assertEqual(h.get(KeyStr(key), 'not found'), key)
keys_to_delete = list(range(COLLECTION_SIZE))
random.shuffle(keys_to_delete)
for iter_i, i in enumerate(keys_to_delete):
key = KeyStr(i)
if not (iter_i % CRASH_HASH_EVERY):
with HaskKeyCrasher(error_on_hash=True):
with self.assertRaises(HashingError):
h.delete(key)
if not (iter_i % CRASH_EQ_EVERY):
with HaskKeyCrasher(error_on_eq=True):
with self.assertRaises(EqError):
h.delete(KeyStr(i))
h = h.delete(key)
self.assertEqual(h.get(key, 'not found'), 'not found')
del d[key]
self.assertEqual(len(d), len(h))
if iter_i == COLLECTION_SIZE // 2:
hm = h
dm = d.copy()
if not (iter_i % TEST_ITERS_EVERY):
self.assertEqual(set(h.keys()), set(d.keys()))
self.assertEqual(len(h.keys()), len(d.keys()))
self.assertEqual(len(d), 0)
self.assertEqual(len(h), 0)
# ============
for key in dm:
self.assertEqual(hm.get(str(key)), dm[key])
self.assertEqual(len(dm), len(hm))
for i, key in enumerate(keys_to_delete):
hm = hm.delete(str(key))
self.assertEqual(hm.get(str(key), 'not found'), 'not found')
dm.pop(str(key), None)
self.assertEqual(len(d), len(h))
if not (i % TEST_ITERS_EVERY):
self.assertEqual(set(h.values()), set(d.values()))
self.assertEqual(len(h.values()), len(d.values()))
self.assertEqual(len(d), 0)
self.assertEqual(len(h), 0)
self.assertEqual(list(h.items()), [])
def test_hamt_delete_1(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(102, 'C')
D = HashKey(103, 'D')
E = HashKey(104, 'E')
Z = HashKey(-100, 'Z')
Er = HashKey(103, 'Er', error_on_eq_to=D)
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
orig_len = len(h)
# BitmapNode(size=10 bitmap=0b111110000 id=0x10eadc618):
# <Key name:A hash:100>: 'a'
# <Key name:B hash:101>: 'b'
# <Key name:C hash:102>: 'c'
# <Key name:D hash:103>: 'd'
# <Key name:E hash:104>: 'e'
h = h.delete(C)
self.assertEqual(len(h), orig_len - 1)
with self.assertRaisesRegex(ValueError, 'cannot compare'):
h.delete(Er)
h = h.delete(D)
self.assertEqual(len(h), orig_len - 2)
h2 = h.delete(Z)
self.assertIs(h2, h)
h = h.delete(A)
self.assertEqual(len(h), orig_len - 3)
self.assertEqual(h.get(A, 42), 42)
self.assertEqual(h.get(B), 'b')
self.assertEqual(h.get(E), 'e')
def test_hamt_delete_2(self):
A = HashKey(100, 'A')
B = HashKey(201001, 'B')
C = HashKey(101001, 'C')
D = HashKey(103, 'D')
E = HashKey(104, 'E')
Z = HashKey(-100, 'Z')
Er = HashKey(201001, 'Er', error_on_eq_to=B)
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
orig_len = len(h)
# BitmapNode(size=8 bitmap=0b1110010000):
# <Key name:A hash:100>: 'a'
# <Key name:D hash:103>: 'd'
# <Key name:E hash:104>: 'e'
# NULL:
# BitmapNode(size=4 bitmap=0b100000000001000000000):
# <Key name:B hash:201001>: 'b'
# <Key name:C hash:101001>: 'c'
with self.assertRaisesRegex(ValueError, 'cannot compare'):
h.delete(Er)
h = h.delete(Z)
self.assertEqual(len(h), orig_len)
h = h.delete(C)
self.assertEqual(len(h), orig_len - 1)
h = h.delete(B)
self.assertEqual(len(h), orig_len - 2)
h = h.delete(A)
self.assertEqual(len(h), orig_len - 3)
self.assertEqual(h.get(D), 'd')
self.assertEqual(h.get(E), 'e')
h = h.delete(A)
h = h.delete(B)
h = h.delete(D)
h = h.delete(E)
self.assertEqual(len(h), 0)
def test_hamt_delete_3(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(100100, 'C')
D = HashKey(100100, 'D')
E = HashKey(104, 'E')
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
orig_len = len(h)
# BitmapNode(size=6 bitmap=0b100110000):
# NULL:
# BitmapNode(size=4 bitmap=0b1000000000000000000001000):
# <Key name:A hash:100>: 'a'
# NULL:
# CollisionNode(size=4 id=0x108572410):
# <Key name:C hash:100100>: 'c'
# <Key name:D hash:100100>: 'd'
# <Key name:B hash:101>: 'b'
# <Key name:E hash:104>: 'e'
h = h.delete(A)
self.assertEqual(len(h), orig_len - 1)
h = h.delete(E)
self.assertEqual(len(h), orig_len - 2)
self.assertEqual(h.get(C), 'c')
self.assertEqual(h.get(B), 'b')
def test_hamt_delete_4(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(100100, 'C')
D = HashKey(100100, 'D')
E = HashKey(100100, 'E')
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
orig_len = len(h)
# BitmapNode(size=4 bitmap=0b110000):
# NULL:
# BitmapNode(size=4 bitmap=0b1000000000000000000001000):
# <Key name:A hash:100>: 'a'
# NULL:
# CollisionNode(size=6 id=0x10515ef30):
# <Key name:C hash:100100>: 'c'
# <Key name:D hash:100100>: 'd'
# <Key name:E hash:100100>: 'e'
# <Key name:B hash:101>: 'b'
h = h.delete(D)
self.assertEqual(len(h), orig_len - 1)
h = h.delete(E)
self.assertEqual(len(h), orig_len - 2)
h = h.delete(C)
self.assertEqual(len(h), orig_len - 3)
h = h.delete(A)
self.assertEqual(len(h), orig_len - 4)
h = h.delete(B)
self.assertEqual(len(h), 0)
def test_hamt_delete_5(self):
h = hamt()
keys = []
for i in range(17):
key = HashKey(i, str(i))
keys.append(key)
h = h.set(key, f'val-{i}')
collision_key16 = HashKey(16, '18')
h = h.set(collision_key16, 'collision')
# ArrayNode(id=0x10f8b9318):
# 0::
# BitmapNode(size=2 count=1 bitmap=0b1):
# <Key name:0 hash:0>: 'val-0'
#
# ... 14 more BitmapNodes ...
#
# 15::
# BitmapNode(size=2 count=1 bitmap=0b1):
# <Key name:15 hash:15>: 'val-15'
#
# 16::
# BitmapNode(size=2 count=1 bitmap=0b1):
# NULL:
# CollisionNode(size=4 id=0x10f2f5af8):
# <Key name:16 hash:16>: 'val-16'
# <Key name:18 hash:16>: 'collision'
self.assertEqual(len(h), 18)
h = h.delete(keys[2])
self.assertEqual(len(h), 17)
h = h.delete(collision_key16)
self.assertEqual(len(h), 16)
h = h.delete(keys[16])
self.assertEqual(len(h), 15)
h = h.delete(keys[1])
self.assertEqual(len(h), 14)
h = h.delete(keys[1])
self.assertEqual(len(h), 14)
for key in keys:
h = h.delete(key)
self.assertEqual(len(h), 0)
def test_hamt_items_1(self):
A = HashKey(100, 'A')
B = HashKey(201001, 'B')
C = HashKey(101001, 'C')
D = HashKey(103, 'D')
E = HashKey(104, 'E')
F = HashKey(110, 'F')
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
h = h.set(F, 'f')
it = h.items()
self.assertEqual(
set(list(it)),
{(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')})
def test_hamt_items_2(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(100100, 'C')
D = HashKey(100100, 'D')
E = HashKey(100100, 'E')
F = HashKey(110, 'F')
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
h = h.set(F, 'f')
it = h.items()
self.assertEqual(
set(list(it)),
{(A, 'a'), (B, 'b'), (C, 'c'), (D, 'd'), (E, 'e'), (F, 'f')})
def test_hamt_keys_1(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(100100, 'C')
D = HashKey(100100, 'D')
E = HashKey(100100, 'E')
F = HashKey(110, 'F')
h = hamt()
h = h.set(A, 'a')
h = h.set(B, 'b')
h = h.set(C, 'c')
h = h.set(D, 'd')
h = h.set(E, 'e')
h = h.set(F, 'f')
self.assertEqual(set(list(h.keys())), {A, B, C, D, E, F})
self.assertEqual(set(list(h)), {A, B, C, D, E, F})
def test_hamt_items_3(self):
h = hamt()
self.assertEqual(len(h.items()), 0)
self.assertEqual(list(h.items()), [])
def test_hamt_eq_1(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
C = HashKey(100100, 'C')
D = HashKey(100100, 'D')
E = HashKey(120, 'E')
h1 = hamt()
h1 = h1.set(A, 'a')
h1 = h1.set(B, 'b')
h1 = h1.set(C, 'c')
h1 = h1.set(D, 'd')
h2 = hamt()
h2 = h2.set(A, 'a')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.set(B, 'b')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.set(C, 'c')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.set(D, 'd2')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.set(D, 'd')
self.assertTrue(h1 == h2)
self.assertFalse(h1 != h2)
h2 = h2.set(E, 'e')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.delete(D)
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h2 = h2.set(E, 'd')
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
def test_hamt_eq_2(self):
A = HashKey(100, 'A')
Er = HashKey(100, 'Er', error_on_eq_to=A)
h1 = hamt()
h1 = h1.set(A, 'a')
h2 = hamt()
h2 = h2.set(Er, 'a')
with self.assertRaisesRegex(ValueError, 'cannot compare'):
h1 == h2
with self.assertRaisesRegex(ValueError, 'cannot compare'):
h1 != h2
def test_hamt_gc_1(self):
A = HashKey(100, 'A')
h = hamt()
h = h.set(0, 0) # empty HAMT node is memoized in hamt.c
ref = weakref.ref(h)
a = []
a.append(a)
a.append(h)
b = []
a.append(b)
b.append(a)
h = h.set(A, b)
del h, a, b
gc.collect()
gc.collect()
gc.collect()
self.assertIsNone(ref())
def test_hamt_gc_2(self):
A = HashKey(100, 'A')
B = HashKey(101, 'B')
h = hamt()
h = h.set(A, 'a')
h = h.set(A, h)
ref = weakref.ref(h)
hi = h.items()
next(hi)
del h, hi
gc.collect()
gc.collect()
gc.collect()
self.assertIsNone(ref())
def test_hamt_in_1(self):
A = HashKey(100, 'A')
AA = HashKey(100, 'A')
B = HashKey(101, 'B')
h = hamt()
h = h.set(A, 1)
self.assertTrue(A in h)
self.assertFalse(B in h)
with self.assertRaises(EqError):
with HaskKeyCrasher(error_on_eq=True):
AA in h
with self.assertRaises(HashingError):
with HaskKeyCrasher(error_on_hash=True):
AA in h
def test_hamt_getitem_1(self):
A = HashKey(100, 'A')
AA = HashKey(100, 'A')
B = HashKey(101, 'B')
h = hamt()
h = h.set(A, 1)
self.assertEqual(h[A], 1)
self.assertEqual(h[AA], 1)
with self.assertRaises(KeyError):
h[B]
with self.assertRaises(EqError):
with HaskKeyCrasher(error_on_eq=True):
h[AA]
with self.assertRaises(HashingError):
with HaskKeyCrasher(error_on_hash=True):
h[AA]
if __name__ == "__main__":
unittest.main()
| HamtTest |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 2044,
"end": 4545
} | class ____(CookieMixin, Exception):
# You should set in subclasses:
# status = 200
status_code = -1
empty_body = False
default_reason = "" # Initialized at the end of the module
def __init__(
self,
*,
headers: LooseHeaders | None = None,
reason: str | None = None,
text: str | None = None,
content_type: str | None = None,
) -> None:
if reason is None:
reason = self.default_reason
elif "\n" in reason:
raise ValueError("Reason cannot contain \\n")
if text is None:
if not self.empty_body:
text = f"{self.status_code}: {reason}"
else:
if self.empty_body:
warnings.warn(
f"text argument is deprecated for HTTP status {self.status_code} "
"since 4.0 and scheduled for removal in 5.0 (#3462),"
"the response should be provided without a body",
DeprecationWarning,
stacklevel=2,
)
if headers is not None:
real_headers = CIMultiDict(headers)
else:
real_headers = CIMultiDict()
if content_type is not None:
if not text:
warnings.warn(
"content_type without text is deprecated "
"since 4.0 and scheduled for removal in 5.0 "
"(#3462)",
DeprecationWarning,
stacklevel=2,
)
real_headers[hdrs.CONTENT_TYPE] = content_type
elif hdrs.CONTENT_TYPE not in real_headers and text:
real_headers[hdrs.CONTENT_TYPE] = "text/plain"
self._reason = reason
self._text = text
self._headers = real_headers
self.args = ()
def __bool__(self) -> bool:
return True
@property
def status(self) -> int:
return self.status_code
@property
def reason(self) -> str:
return self._reason
@property
def text(self) -> str | None:
return self._text
@property
def headers(self) -> "CIMultiDict[str]":
return self._headers
def __str__(self) -> str:
return self.reason
def __repr__(self) -> str:
return f"<{self.__class__.__name__}: {self.reason}>"
__reduce__ = object.__reduce__
def __getnewargs__(self) -> tuple[Any, ...]:
return self.args
| HTTPException |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 237822,
"end": 239317
} | class ____(GeneratedAirbyteSource):
class OAuth20:
@public
def __init__(self, client_id: str, client_secret: str, access_token: str):
self.auth_type = "OAuth2.0"
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client_secret, "client_secret")
self.access_token = check.str_param(access_token, "access_token")
class AccessToken:
@public
def __init__(self, token: str):
self.auth_type = "token"
self.token = check.str_param(token, "token")
@public
def __init__(
self,
name: str,
start_date: str,
credentials: Union["NotionSource.OAuth20", "NotionSource.AccessToken"],
):
"""Airbyte Source for Notion.
Documentation can be found at https://docs.airbyte.com/integrations/sources/notion
Args:
name (str): The name of the destination.
start_date (str): UTC date and time in the format 2017-01-25T00:00:00.000Z. Any data before this date will not be replicated.
credentials (Union[NotionSource.OAuth20, NotionSource.AccessToken]): Pick an authentication method.
"""
self.start_date = check.str_param(start_date, "start_date")
self.credentials = check.inst_param(
credentials, "credentials", (NotionSource.OAuth20, NotionSource.AccessToken)
)
super().__init__("Notion", name)
| NotionSource |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 157411,
"end": 159017
} | class ____(SchemaEventTarget):
"""A marker for a transparent database-side default.
Use :class:`.FetchedValue` when the database is configured
to provide some automatic default for a column.
E.g.::
Column("foo", Integer, FetchedValue())
Would indicate that some trigger or default generator
will create a new value for the ``foo`` column during an
INSERT.
.. seealso::
:ref:`triggered_columns`
"""
is_server_default = True
reflected = False
has_argument = False
is_clause_element = False
is_identity = False
column: Optional[Column[Any]]
def __init__(self, for_update: bool = False) -> None:
self.for_update = for_update
def _as_for_update(self, for_update: bool) -> FetchedValue:
if for_update == self.for_update:
return self
else:
return self._clone(for_update)
def _copy(self) -> FetchedValue:
return FetchedValue(self.for_update)
def _clone(self, for_update: bool) -> Self:
n = self.__class__.__new__(self.__class__)
n.__dict__.update(self.__dict__)
n.__dict__.pop("column", None)
n.for_update = for_update
return n
def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
column = parent
assert isinstance(column, Column)
self.column = column
if self.for_update:
self.column.server_onupdate = self
else:
self.column.server_default = self
def __repr__(self) -> str:
return util.generic_repr(self)
| FetchedValue |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 119165,
"end": 124320
} | class ____(Layer):
"""Zero-padding layer for 3D data (spatial or spatio-temporal).
Examples:
>>> input_shape = (1, 1, 2, 2, 3)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x)
>>> print(y.shape)
(1, 5, 6, 6, 3)
Args:
padding: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.
- If int: the same symmetric padding
is applied to height and width.
- If tuple of 3 ints:
interpreted as two different
symmetric padding values for height and width:
`(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`.
- If tuple of 3 tuples of 2 ints:
interpreted as
`((left_dim1_pad, right_dim1_pad), (left_dim2_pad,
right_dim2_pad), (left_dim3_pad, right_dim3_pad))`
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
while `channels_first` corresponds to inputs with shape
`(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.
It defaults to the `image_data_format` value found in your
Keras config file at `~/.keras/keras.json`.
If you never set it, then it will be "channels_last".
Input shape:
5D tensor with shape:
- If `data_format` is `"channels_last"`:
`(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad,
depth)`
- If `data_format` is `"channels_first"`:
`(batch_size, depth, first_axis_to_pad, second_axis_to_pad,
third_axis_to_pad)`
Output shape:
5D tensor with shape:
- If `data_format` is `"channels_last"`:
`(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad,
depth)`
- If `data_format` is `"channels_first"`:
`(batch_size, depth, first_padded_axis, second_padded_axis,
third_axis_to_pad)`
"""
def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs):
super(ZeroPadding3D, self).__init__(**kwargs)
self.data_format = conv_utils.normalize_data_format(data_format)
if isinstance(padding, int):
self.padding = ((padding, padding), (padding, padding), (padding,
padding))
elif hasattr(padding, '__len__'):
if len(padding) != 3:
raise ValueError('`padding` should have 3 elements. '
'Found: ' + str(padding))
dim1_padding = conv_utils.normalize_tuple(padding[0], 2,
'1st entry of padding')
dim2_padding = conv_utils.normalize_tuple(padding[1], 2,
'2nd entry of padding')
dim3_padding = conv_utils.normalize_tuple(padding[2], 2,
'3rd entry of padding')
self.padding = (dim1_padding, dim2_padding, dim3_padding)
else:
raise ValueError(
'`padding` should be either an int, '
'a tuple of 3 ints '
'(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), '
'or a tuple of 3 tuples of 2 ints '
'((left_dim1_pad, right_dim1_pad),'
' (left_dim2_pad, right_dim2_pad),'
' (left_dim3_pad, right_dim2_pad)). '
'Found: ' + str(padding))
self.input_spec = InputSpec(ndim=5)
def compute_output_shape(self, input_shape):
input_shape = tensor_shape.TensorShape(input_shape).as_list()
if self.data_format == 'channels_first':
if input_shape[2] is not None:
dim1 = input_shape[2] + self.padding[0][0] + self.padding[0][1]
else:
dim1 = None
if input_shape[3] is not None:
dim2 = input_shape[3] + self.padding[1][0] + self.padding[1][1]
else:
dim2 = None
if input_shape[4] is not None:
dim3 = input_shape[4] + self.padding[2][0] + self.padding[2][1]
else:
dim3 = None
return tensor_shape.TensorShape(
[input_shape[0], input_shape[1], dim1, dim2, dim3])
elif self.data_format == 'channels_last':
if input_shape[1] is not None:
dim1 = input_shape[1] + self.padding[0][0] + self.padding[0][1]
else:
dim1 = None
if input_shape[2] is not None:
dim2 = input_shape[2] + self.padding[1][0] + self.padding[1][1]
else:
dim2 = None
if input_shape[3] is not None:
dim3 = input_shape[3] + self.padding[2][0] + self.padding[2][1]
else:
dim3 = None
return tensor_shape.TensorShape(
[input_shape[0], dim1, dim2, dim3, input_shape[4]])
def call(self, inputs):
return backend.spatial_3d_padding(
inputs, padding=self.padding, data_format=self.data_format)
def get_config(self):
config = {'padding': self.padding, 'data_format': self.data_format}
base_config = super(ZeroPadding3D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
| ZeroPadding3D |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 10700,
"end": 11361
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.self = NystromformerSelfAttention(config)
self.output = NystromformerSelfOutput(config)
def forward(self, hidden_states, attention_mask=None, output_attentions=False):
self_outputs = self.self(hidden_states, attention_mask, output_attentions)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Nystromformer
| NystromformerAttention |
python | walkccc__LeetCode | solutions/2120. Execution of All Suffix Instructions Staying in a Grid/2120.py | {
"start": 0,
"end": 842
} | class ____:
def executeInstructions(
self,
n: int,
startPos: list[int],
s: str,
) -> list[int]:
moves = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}
m = len(s)
uMost = startPos[0] + 1
dMost = n - startPos[0]
lMost = startPos[1] + 1
rMost = n - startPos[1]
ans = [0] * m
reach = {(0, None): m, (None, 0): m}
x = 0
y = 0
for i in reversed(range(m)):
dx, dy = moves[s[i]]
x -= dx
y -= dy
reach[(x, None)] = i
reach[(None, y)] = i
out = min(reach.get((x - uMost, None), math.inf),
reach.get((x + dMost, None), math.inf),
reach.get((None, y - lMost), math.inf),
reach.get((None, y + rMost), math.inf))
ans[i] = m - i if out == math.inf else out - i - 1
return ans
| Solution |
python | python-visualization__folium | folium/map.py | {
"start": 4113,
"end": 5708
} | class ____(Layer):
"""
Create a FeatureGroup layer ; you can put things in it and handle them
as a single layer. For example, you can add a LayerControl to
tick/untick the whole group.
Parameters
----------
name : str, default None
The name of the featureGroup layer.
It will be displayed in the LayerControl.
If None get_name() will be called to get the technical (ugly) name.
overlay : bool, default True
Whether your layer will be an overlay (ticked with a check box in
LayerControls) or a base layer (ticked with a radio button).
control: bool, default True
Whether the layer will be included in LayerControls.
show: bool, default True
Whether the layer will be shown on opening.
**kwargs
Additional (possibly inherited) options. See
https://leafletjs.com/reference.html#featuregroup
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.featureGroup(
{{ this.options|tojavascript }}
);
{% endmacro %}
"""
)
def __init__(
self,
name: Optional[str] = None,
overlay: bool = True,
control: bool = True,
show: bool = True,
**kwargs: TypeJsonValue,
):
super().__init__(name=name, overlay=overlay, control=control, show=show)
self._name = "FeatureGroup"
self.tile_name = name if name is not None else self.get_name()
self.options = remove_empty(**kwargs)
| FeatureGroup |
python | getsentry__sentry | tests/apidocs/endpoints/events/test_group_events.py | {
"start": 1309,
"end": 1727
} | class ____(ProjectGroupEventBase):
def setUp(self) -> None:
super().setUp()
self.url = (
f"/api/0/organizations/{self.organization.slug}/issues/{self.group_id}/events/latest/"
)
def test_get(self) -> None:
response = self.client.get(self.url)
request = RequestFactory().get(self.url)
self.validate_schema(request, response)
| ProjectGroupEventDetailsDocs |
python | ray-project__ray | python/ray/data/datasource/file_based_datasource.py | {
"start": 18370,
"end": 19836
} | class ____:
"""pyarrow.fs.S3FileSystem wrapper that can be deserialized safely.
Importing pyarrow.fs during reconstruction triggers the pyarrow
S3 subsystem initialization.
NOTE: This is only needed for pyarrow<14.0.0 and should be removed
once the minimum supported pyarrow version exceeds that.
See https://github.com/apache/arrow/pull/38375 for context.
"""
def __init__(self, fs: "pyarrow.fs.FileSystem"):
self._fs = fs
def unwrap(self):
return self._fs
@classmethod
def _reconstruct(cls, fs_reconstruct, fs_args):
# Implicitly trigger S3 subsystem initialization by importing
# pyarrow.fs.
import pyarrow.fs # noqa: F401
return cls(fs_reconstruct(*fs_args))
def __reduce__(self):
return _S3FileSystemWrapper._reconstruct, self._fs.__reduce__()
def _resolve_kwargs(
kwargs_fn: Callable[[], Dict[str, Any]], **kwargs
) -> Dict[str, Any]:
if kwargs_fn:
kwarg_overrides = kwargs_fn()
kwargs.update(kwarg_overrides)
return kwargs
def _validate_shuffle_arg(
shuffle: Union[Literal["files"], FileShuffleConfig, None],
) -> None:
if not (
shuffle is None or shuffle == "files" or isinstance(shuffle, FileShuffleConfig)
):
raise ValueError(
f"Invalid value for 'shuffle': {shuffle}. "
"Valid values are None, 'files', `FileShuffleConfig`."
)
| _S3FileSystemWrapper |
python | pypa__pip | tests/unit/test_models.py | {
"start": 218,
"end": 1589
} | class ____:
"""Tests for pip._internal.models.index.PackageIndex"""
def test_gives_right_urls(self) -> None:
url = "https://mypypi.internal/path/"
file_storage_domain = "files.mypypi.internal"
pack_index = index.PackageIndex(url, file_storage_domain)
assert pack_index.url == url
assert pack_index.file_storage_domain == file_storage_domain
assert pack_index.netloc == "mypypi.internal"
assert pack_index.simple_url == url + "simple"
assert pack_index.pypi_url == url + "pypi"
def test_PyPI_urls_are_correct(self) -> None:
pack_index = index.PyPI
assert pack_index.netloc == "pypi.org"
assert pack_index.url == "https://pypi.org/"
assert pack_index.simple_url == "https://pypi.org/simple"
assert pack_index.pypi_url == "https://pypi.org/pypi"
assert pack_index.file_storage_domain == "files.pythonhosted.org"
def test_TestPyPI_urls_are_correct(self) -> None:
pack_index = index.TestPyPI
assert pack_index.netloc == "test.pypi.org"
assert pack_index.url == "https://test.pypi.org/"
assert pack_index.simple_url == "https://test.pypi.org/simple"
assert pack_index.pypi_url == "https://test.pypi.org/pypi"
assert pack_index.file_storage_domain == "test-files.pythonhosted.org"
| TestPackageIndex |
python | ray-project__ray | python/ray/tune/execution/class_cache.py | {
"start": 905,
"end": 2375
} | class ____:
"""Caches actor classes.
ray.remote is a registration call. It sends the serialized object to the
key value store (redis), and will be fetched at an arbitrary worker
later. Registration does not use any Ray scheduling resources.
Later, class.remote() actually creates the remote actor. The
actor will be instantiated on some arbitrary machine,
according to the underlying Ray scheduler.
Without this cache, you would register the same serialized object
over and over again. Naturally, since redis doesn’t spill to disk,
this can easily nuke the redis instance (and basically blow up Ray).
This cache instead allows us to register once and only once.
Note that we assume there can be multiple trainables in the
system at once.
"""
def __init__(self):
self._cache = {}
def get(self, trainable_cls):
"""Gets the wrapped trainable_cls, otherwise calls ray.remote."""
env_vars = DEFAULT_ENV_VARS.copy()
for env_var_to_propagate in ENV_VARS_TO_PROPAGATE:
if env_var_to_propagate in os.environ:
env_vars[env_var_to_propagate] = os.environ[env_var_to_propagate]
runtime_env = {"env_vars": env_vars}
if trainable_cls not in self._cache:
remote_cls = ray.remote(runtime_env=runtime_env)(trainable_cls)
self._cache[trainable_cls] = remote_cls
return self._cache[trainable_cls]
| _ActorClassCache |
python | django__django | tests/admin_views/admin.py | {
"start": 12943,
"end": 13140
} | class ____(admin.ModelAdmin):
show_full_result_count = False
search_fields = (
"=titletranslation__text",
"=the_recommender__titletranslation__text",
)
| RecommendationAdmin |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 37392,
"end": 44706
} | class ____(MoonshinePreTrainedModel):
def __init__(self, config: MoonshineConfig):
super().__init__(config)
self.encoder = MoonshineEncoder(config)
self.decoder = MoonshineDecoder(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.decoder.embed_tokens
def set_input_embeddings(self, value):
self.decoder.embed_tokens = value
def freeze_encoder(self):
"""
Calling this function will disable the gradient computation for the Moonshine encoder so that its parameters will
not be updated during training.
"""
self.encoder._freeze_parameters()
def _mask_input_features(
self,
input_features: torch.FloatTensor,
attention_mask: Optional[torch.LongTensor] = None,
):
"""
Masks extracted features along time axis and/or along feature axis according to
[SpecAugment](https://huggingface.co/papers/1904.08779).
"""
# `config.apply_spec_augment` can set masking to False
if not getattr(self.config, "apply_spec_augment", True):
return input_features
# generate indices & apply SpecAugment along time axis
batch_size, hidden_size, sequence_length = input_features.size()
if self.config.mask_time_prob > 0 and self.training:
# generate indices & apply SpecAugment along time axis
mask_time_indices = _compute_mask_indices(
(batch_size, sequence_length),
mask_prob=self.config.mask_time_prob,
mask_length=self.config.mask_time_length,
attention_mask=attention_mask,
min_masks=self.config.mask_time_min_masks,
)
mask_time_indices = torch.tensor(mask_time_indices, device=input_features.device, dtype=torch.bool)
mask_time_indices = mask_time_indices[:, None].expand(-1, hidden_size, -1)
input_features[mask_time_indices] = 0
if self.config.mask_feature_prob > 0 and self.training:
# generate indices & apply SpecAugment along feature axis
mask_feature_indices = _compute_mask_indices(
(batch_size, hidden_size),
mask_prob=self.config.mask_feature_prob,
mask_length=self.config.mask_feature_length,
min_masks=self.config.mask_feature_min_masks,
)
mask_feature_indices = torch.tensor(mask_feature_indices, device=input_features.device, dtype=torch.bool)
input_features[mask_feature_indices] = 0
return input_features
@can_return_tuple
@auto_docstring
def forward(
self,
input_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
past_key_values: Optional[EncoderDecoderCache] = None,
decoder_inputs_embeds: Optional[tuple[torch.FloatTensor]] = None,
decoder_position_ids: Optional[tuple[torch.LongTensor]] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Seq2SeqModelOutput:
r"""
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
Float values of the raw speech waveform. Raw speech waveform can be
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
the soundfile library (`pip install soundfile`). To prepare the array into
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
and conversion into a tensor of type `torch.FloatTensor`.
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
Indices of positions of each input sequence tokens in the position embeddings.
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
Example:
```python
>>> import torch
>>> from transformers import AutoFeatureExtractor, MoonshineModel
>>> from datasets import load_dataset
>>> model = MoonshineModel.from_pretrained("UsefulSensors/moonshine-tiny")
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine-tiny")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_values = inputs.input_values
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 2, 288]
```
"""
if encoder_outputs is None:
encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_attention_mask=attention_mask,
encoder_hidden_states=encoder_outputs.last_hidden_state,
past_key_values=past_key_values,
inputs_embeds=decoder_inputs_embeds,
position_ids=decoder_position_ids,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
return Seq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
"""
Shift input ids one token to the right.
"""
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
shifted_input_ids[:, 0] = decoder_start_token_id
if pad_token_id is None:
raise ValueError("self.model.config.pad_token_id has to be defined.")
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
return shifted_input_ids
@auto_docstring(
custom_intro="""
The Moonshine Model with a language modeling head. Can be used for automatic speech recognition.
"""
)
| MoonshineModel |
python | sphinx-doc__sphinx | sphinx/ext/intersphinx/_resolve.py | {
"start": 12144,
"end": 12746
} | class ____(CustomReSTDispatcher):
"""Custom dispatcher for external role.
This enables :external:***:/:external+***: roles on parsing reST document.
"""
def role(
self,
role_name: str,
language_module: ModuleType,
lineno: int,
reporter: Reporter,
) -> tuple[RoleFunction, list[system_message]]:
if len(role_name) > 9 and role_name.startswith(('external:', 'external+')):
return IntersphinxRole(role_name), []
else:
return super().role(role_name, language_module, lineno, reporter)
| IntersphinxDispatcher |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/file_asset.py | {
"start": 2518,
"end": 13133
} | class ____(PathDataAsset[DatasourceT, FileNamePartitioner], ABC, Generic[DatasourceT]):
"""Base class for PathDataAssets which batch by applying a regex to file names."""
_unnamed_regex_param_prefix: str = pydantic.PrivateAttr(default="batch_request_param_")
@public_api
def add_batch_definition_path(self, name: str, path: PathStr) -> BatchDefinition:
"""Add a BatchDefinition which matches a single Path.
Args:
name: BatchDefinition name
path: File path relative to the Asset
Raises:
PathNotFoundError: path cannot be resolved
AmbiguousPathError: path matches more than one file
"""
regex = re.compile(f"{path}$")
matched_data_references = len(self._data_connector.get_matched_data_references(regex=regex))
# we require path to match exactly 1 file
if matched_data_references < 1:
raise PathNotFoundError(path=path)
elif matched_data_references > 1:
raise AmbiguousPathError(path=path)
return self.add_batch_definition(
name=name,
partitioner=FileNamePartitionerPath(
regex=regex,
param_names=(),
),
)
@public_api
def add_batch_definition_yearly(
self, name: str, regex: Union[re.Pattern, str], sort_ascending: bool = True
) -> BatchDefinition:
"""Add a BatchDefinition which defines yearly batches by file name.
Args:
name: BatchDefinition name
regex: Regular Expression used to define batches by file name.
Must contain a single group `year`
sort_ascending: determine order in which batches are returned
Raises:
RegexMissingRequiredGroupsError: regex is missing the group `year`
RegexUnknownGroupsError: regex has groups other than `year`
"""
regex = re.compile(regex)
REQUIRED_GROUP_NAME = {"year"}
self._assert_group_names_in_regex(regex=regex, required_group_names=REQUIRED_GROUP_NAME)
return self.add_batch_definition(
name=name,
partitioner=FileNamePartitionerYearly(
regex=regex, param_names=("year",), sort_ascending=sort_ascending
),
)
@public_api
def add_batch_definition_monthly(
self, name: str, regex: Union[re.Pattern, str], sort_ascending: bool = True
) -> BatchDefinition:
"""Add a BatchDefinition which defines monthly batches by file name.
Args:
name: BatchDefinition name
regex: Regular Expression used to define batches by file name.
Must contain the groups `year` and `month`.
sort_ascending: determine order in which batches are returned
Raises:
RegexMissingRequiredGroupsError: regex is missing the groups `year` and/or `month`.
RegexUnknownGroupsError: regex has groups other than `year` and/or `month`.
"""
regex = re.compile(regex)
REQUIRED_GROUP_NAMES = {"year", "month"}
self._assert_group_names_in_regex(regex=regex, required_group_names=REQUIRED_GROUP_NAMES)
return self.add_batch_definition(
name=name,
partitioner=FileNamePartitionerMonthly(
regex=regex, param_names=("year", "month"), sort_ascending=sort_ascending
),
)
@public_api
def add_batch_definition_daily(
self, name: str, regex: Union[re.Pattern, str], sort_ascending: bool = True
) -> BatchDefinition:
"""Add a BatchDefinition which defines daily batches by file name.
Args:
name: BatchDefinition name
regex: Regular Expression used to define batches by file name.
Must contain the groups `year`, `month`, and `day`.
sort_ascending: determine order in which batches are returned
Raises:
RegexMissingRequiredGroupsError: regex is missing the
groups `year`, `month`, and/or `day`.
RegexUnknownGroupsError: regex has groups other than `year`, `month`, and/or `day`.
"""
regex = re.compile(regex)
REQUIRED_GROUP_NAMES = {"year", "month", "day"}
self._assert_group_names_in_regex(regex=regex, required_group_names=REQUIRED_GROUP_NAMES)
return self.add_batch_definition(
name=name,
partitioner=FileNamePartitionerDaily(
regex=regex, param_names=("year", "month", "day"), sort_ascending=sort_ascending
),
)
@classmethod
def _assert_group_names_in_regex(
cls, regex: re.Pattern, required_group_names: set[str]
) -> None:
regex_parser = RegExParser(
regex_pattern=regex,
)
actual_group_names = set(regex_parser.group_names())
if not required_group_names.issubset(actual_group_names):
missing_groups = required_group_names - actual_group_names
raise RegexMissingRequiredGroupsError(missing_groups)
if not actual_group_names.issubset(required_group_names):
unknown_groups = actual_group_names - required_group_names
raise RegexUnknownGroupsError(unknown_groups)
@override
def _get_batch_definition_list(
self, batch_request: BatchRequest
) -> list[LegacyBatchDefinition]:
batch_definition_list = self._data_connector.get_batch_definition_list(
batch_request=batch_request
)
return batch_definition_list
def _get_group_names(self, partitioner: Optional[FileNamePartitioner]) -> list[str]:
if not partitioner:
return []
regex_parser = RegExParser(
regex_pattern=partitioner.regex,
unnamed_regex_group_prefix=self._unnamed_regex_param_prefix,
)
return regex_parser.group_names()
@override
def get_batch_parameters_keys(
self,
partitioner: Optional[FileNamePartitioner] = None,
) -> tuple[str, ...]:
option_keys: tuple[str, ...] = (FILE_PATH_BATCH_SPEC_KEY,)
if partitioner:
option_keys += tuple(partitioner.param_names)
return option_keys
@override
def get_whole_directory_path_override(
self,
) -> None:
return None
@override
def build_batch_request(
self,
options: Optional[BatchParameters] = None,
batch_slice: Optional[BatchSlice] = None,
partitioner: Optional[FileNamePartitioner] = None,
) -> BatchRequest:
"""A batch request that can be used to obtain batches for this DataAsset.
Args:
options: A dict that can be used to filter the batch groups returned from the asset.
The dict structure depends on the asset type. The available keys for dict can be obtained by
calling get_batch_parameters_keys(...).
batch_slice: A python slice that can be used to limit the sorted batches by index.
e.g. `batch_slice = "[-5:]"` will request only the last 5 batches after the options filter is applied.
partitioner: A Partitioner used to narrow the data returned from the asset.
Returns:
A BatchRequest object that can be used to obtain a batch from an Asset by calling the
get_batch method.
Note:
Option "batch_slice" is supported for all "DataAsset" extensions of this class identically. This mechanism
applies to every "Datasource" type and any "ExecutionEngine" that is capable of loading data from files on
local and/or cloud/networked filesystems (currently, Pandas and Spark backends work with files).
""" # noqa: E501 # FIXME CoP
if options:
for option, value in options.items():
if (
option in self._get_group_names(partitioner=partitioner)
and value
and not isinstance(value, str)
):
raise gx_exceptions.InvalidBatchRequestError( # noqa: TRY003 # FIXME CoP
f"All batching_regex matching options must be strings. The value of '{option}' is " # noqa: E501 # FIXME CoP
f"not a string: {value}"
)
if options is not None and not self._batch_parameters_are_valid(
options=options,
partitioner=partitioner,
):
allowed_keys = set(self.get_batch_parameters_keys(partitioner=partitioner))
actual_keys = set(options.keys())
raise gx_exceptions.InvalidBatchRequestError( # noqa: TRY003 # FIXME CoP
"Batch parameters should only contain keys from the following set:\n"
f"{allowed_keys}\nbut your specified keys contain\n"
f"{actual_keys.difference(allowed_keys)}\nwhich is not valid.\n"
)
return BatchRequest(
datasource_name=self.datasource.name,
data_asset_name=self.name,
options=options or {},
batch_slice=batch_slice,
partitioner=partitioner,
)
@override
def _batch_spec_options_from_batch_request(self, batch_request: BatchRequest) -> dict:
"""Build a set of options for use in a batch spec from a batch request.
Args:
batch_request: Batch request to use to generate options.
Returns:
Dictionary containing batch spec options.
"""
get_reader_options_include: set[str] | None = self._get_reader_options_include()
if not get_reader_options_include:
# Set to None if empty set to include any additional `extra_kwargs` passed to `add_*_asset` # noqa: E501 # FIXME CoP
get_reader_options_include = None
batch_spec_options = {
"reader_method": self._get_reader_method(),
"reader_options": self.dict(
include=get_reader_options_include,
exclude=self._EXCLUDE_FROM_READER_OPTIONS,
exclude_unset=True,
by_alias=True,
config_provider=self._datasource._config_provider,
),
}
return batch_spec_options
@override
def _get_sortable_partitioner(
self, partitioner: Optional[FileNamePartitioner]
) -> Optional[PartitionerSortingProtocol]:
# FileNamePartitioner already implements PartitionerSortingProtocol
return partitioner
| FileDataAsset |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 274482,
"end": 274797
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("Deployment", graphql_name="node")
| DeploymentEdge |
python | doocs__leetcode | lcci/16.15.Master Mind/Solution.py | {
"start": 0,
"end": 228
} | class ____:
def masterMind(self, solution: str, guess: str) -> List[int]:
x = sum(a == b for a, b in zip(solution, guess))
y = sum((Counter(solution) & Counter(guess)).values())
return [x, y - x]
| Solution |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 10742,
"end": 14201
} | class ____:
scenarii: list[tuple[str, str, bytes | None]] = [
# Same origin (protocol, host, port): send referrer
(
"https://example.com/page.html",
"https://example.com/not-page.html",
b"https://example.com/page.html",
),
(
"http://example.com/page.html",
"http://example.com/not-page.html",
b"http://example.com/page.html",
),
(
"https://example.com:443/page.html",
"https://example.com/not-page.html",
b"https://example.com/page.html",
),
(
"http://example.com:80/page.html",
"http://example.com/not-page.html",
b"http://example.com/page.html",
),
(
"http://example.com/page.html",
"http://example.com:80/not-page.html",
b"http://example.com/page.html",
),
(
"http://example.com:8888/page.html",
"http://example.com:8888/not-page.html",
b"http://example.com:8888/page.html",
),
# Different host: send origin as referrer
(
"https://example2.com/page.html",
"https://scrapy.org/otherpage.html",
b"https://example2.com/",
),
(
"https://example2.com/page.html",
"https://not.example2.com/otherpage.html",
b"https://example2.com/",
),
(
"http://example2.com/page.html",
"http://not.example2.com/otherpage.html",
b"http://example2.com/",
),
# exact match required
(
"http://example2.com/page.html",
"http://www.example2.com/otherpage.html",
b"http://example2.com/",
),
# Different port: send origin as referrer
(
"https://example3.com:444/page.html",
"https://example3.com/not-page.html",
b"https://example3.com:444/",
),
(
"http://example3.com:81/page.html",
"http://example3.com/not-page.html",
b"http://example3.com:81/",
),
# Different protocols: send origin as referrer
(
"https://example4.com/page.html",
"http://example4.com/not-page.html",
b"https://example4.com/",
),
(
"https://example4.com/page.html",
"http://not.example4.com/",
b"https://example4.com/",
),
(
"ftps://example4.com/urls.zip",
"https://example4.com/not-page.html",
b"ftps://example4.com/",
),
(
"ftp://example4.com/urls.zip",
"http://example4.com/not-page.html",
b"ftp://example4.com/",
),
(
"ftps://example4.com/urls.zip",
"https://example4.com/not-page.html",
b"ftps://example4.com/",
),
# test for user/password stripping
(
"https://user:password@example5.com/page.html",
"https://example5.com/not-page.html",
b"https://example5.com/page.html",
),
# TLS to non-TLS downgrade: send origin
(
"https://user:password@example5.com/page.html",
"http://example5.com/not-page.html",
b"https://example5.com/",
),
]
| MixinOriginWhenCrossOrigin |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_base_aws.py | {
"start": 1472,
"end": 2266
} | class ____(AwsBaseOperator):
aws_hook_class = FakeS3Hook
def __init__(self, *, value: Any = None, **kwargs):
super().__init__(**kwargs)
self.value = value
def execute(self, context):
"""For test purpose"""
from botocore.config import Config
hook = self.hook
assert self.aws_conn_id == hook.aws_conn_id
assert self.region_name == hook._region_name
assert self.verify == hook._verify
botocore_config = hook._config
if botocore_config:
assert isinstance(botocore_config, Config)
else:
assert botocore_config is None
@pytest.fixture(autouse=True)
def fake_conn(monkeypatch):
monkeypatch.setenv(f"AWS_CONN_{TEST_CONN.upper()}", '{"conn_type": "aws"}')
| FakeS3Operator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.