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 | pytorch__pytorch | torch/fx/experimental/unification/multipledispatch/variadic.py | {
"start": 146,
"end": 1477
} | class ____(type):
# checking if subclass is a subclass of self
def __subclasscheck__(cls, subclass):
other_type = subclass.variadic_type if isvariadic(subclass) else (subclass,)
return subclass is cls or all(
issubclass(other, cls.variadic_type) # type: ignore[attr-defined]
for other in other_type
)
def __eq__(cls, other):
"""
Return True if other has the same variadic type
Parameters
----------
other : object (type)
The object (type) to check
Returns
-------
bool
Whether or not `other` is equal to `self`
"""
return isvariadic(other) and set(cls.variadic_type) == set(other.variadic_type) # type: ignore[attr-defined]
def __hash__(cls):
return hash((type(cls), frozenset(cls.variadic_type))) # type: ignore[attr-defined]
def isvariadic(obj):
"""Check whether the type `obj` is variadic.
Parameters
----------
obj : type
The type to check
Returns
-------
bool
Whether or not `obj` is variadic
Examples
--------
>>> # xdoctest: +SKIP
>>> isvariadic(int)
False
>>> isvariadic(Variadic[int])
True
"""
return isinstance(obj, VariadicSignatureType)
| VariadicSignatureType |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_rich_string06.py | {
"start": 315,
"end": 971
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("rich_string06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
red = workbook.add_format({"font_color": "red"})
worksheet.write("A1", "Foo", red)
worksheet.write("A2", "Bar")
worksheet.write_rich_string("A3", "ab", red, "cde", "fg")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/metrics_utils.py | {
"start": 2045,
"end": 9373
} | class ____(Enum):
"""Types of metrics reduction.
Contains the following values:
* `SUM`: Scalar sum of weighted values.
* `SUM_OVER_BATCH_SIZE`: Scalar sum of weighted values divided by
number of elements.
* `WEIGHTED_MEAN`: Scalar sum of weighted values divided by sum of weights.
"""
SUM = 'sum'
SUM_OVER_BATCH_SIZE = 'sum_over_batch_size'
WEIGHTED_MEAN = 'weighted_mean'
def update_state_wrapper(update_state_fn):
"""Decorator to wrap metric `update_state()` with `add_update()`.
Args:
update_state_fn: function that accumulates metric statistics.
Returns:
Decorated function that wraps `update_state_fn()` with `add_update()`.
"""
def decorated(metric_obj, *args, **kwargs):
"""Decorated function with `add_update()`."""
strategy = distribute_lib.get_strategy()
for weight in metric_obj.weights:
if (backend.is_tpu_strategy(strategy) and
not strategy.extended.variable_created_in_scope(weight)
and not distribute_lib.in_cross_replica_context()):
raise ValueError(
'Trying to run metric.update_state in replica context when '
'the metric was not created in TPUStrategy scope. '
'Make sure the keras Metric is created in TPUstrategy scope. ')
with tf_utils.graph_context_for_symbolic_tensors(*args, **kwargs):
update_op = update_state_fn(*args, **kwargs)
if update_op is not None: # update_op will be None in eager execution.
metric_obj.add_update(update_op)
return update_op
return tf_decorator.make_decorator(update_state_fn, decorated)
def result_wrapper(result_fn):
"""Decorator to wrap metric `result()` function in `merge_call()`.
Result computation is an idempotent operation that simply calculates the
metric value using the state variables.
If metric state variables are distributed across replicas/devices and
`result()` is requested from the context of one device - This function wraps
`result()` in a distribution strategy `merge_call()`. With this,
the metric state variables will be aggregated across devices.
Args:
result_fn: function that computes the metric result.
Returns:
Decorated function that wraps `result_fn()` in distribution strategy
`merge_call()`.
"""
def decorated(metric_obj, *args):
"""Decorated function with merge_call."""
has_strategy = distribute_lib.has_strategy()
replica_context = distribute_lib.get_replica_context()
# The purpose of using `merge_call` to call `result()` is to trigger cross
# replica aggregation of metric state variables (SyncOnReadVariable). After
# we introduced `variable_sync_on_read_context`, in principle there is no
# need to use `merge_call` here. However the branch still exists because:
#
# 1. Keras V1 training code sometimes assumes `result_t` is the same tensor
# across replicas (achieved by `merge_call`). With
# `variable_sync_on_read_context` each replica gets their own tensors
# residing on replica's device, thus breaking the assumption.
# 2. Keras c/fit creates a tf.function (a.k.a, train_function) that returns
# the metric values of the first replica. With
# `variable_sync_on_read_context` since each replica gets their own
# tensors, the metric result tensors on the non-first replicas are not in
# the return value of train_function, making TF graph optimizer prune the
# branch that computes and aggregates those metric results. As a result,
# if NCCL is used to do the aggregation, the program will hang because
# NCCL ops are only launched on the non-pruned first replica.
#
# We condition on strategy.extended._use_merge_call() since we know if it is
# false, the program uses `jit_compile` to compile replica fn, meaning it is
# not V1 training (hence #1 is okay), and no pruning will happen as
# compiled functions are not inlined (hence #2 is okay).
if (not has_strategy or replica_context is None or
not distribute_lib.get_strategy(
).extended._use_merge_call()):
with distribute_lib.variable_sync_on_read_context():
raw_result = result_fn(*args)
# Results need to be wrapped in a `tf.identity` op to ensure
# correct execution order.
if isinstance(raw_result,
(tensor.Tensor, variables_module.Variable, float, int)):
result_t = array_ops.identity(raw_result)
elif isinstance(raw_result, dict):
result_t = {
key: array_ops.identity(value)
for key, value in raw_result.items()
}
else:
try:
result_t = array_ops.identity(raw_result)
except (ValueError, TypeError):
raise RuntimeError(
'The output of `metric.result()` can only be a single '
'Tensor/Variable, or a dict of Tensors/Variables. '
'For metric %s, got result %s.' % (metric_obj.name, raw_result))
else:
# TODO(psv): Test distribution of metrics using different distribution
# strategies.
# Creating a wrapper for merge_fn. merge_call invokes the given merge_fn
# with distribution object as the first parameter. We create a wrapper
# here so that the result function need not have that parameter.
def merge_fn_wrapper(distribution, merge_fn, *args):
# We will get `PerReplica` merge function. Taking the first one as all
# are identical copies of the function that we had passed below.
result = distribution.experimental_local_results(merge_fn)[0](*args)
# Wrapping result in identity so that control dependency between
# update_op from `update_state` and result works in case result returns
# a tensor.
return array_ops.identity(result)
# Wrapping result in merge_call. merge_call is used when we want to leave
# replica mode and compute a value in cross replica mode.
result_t = replica_context.merge_call(
merge_fn_wrapper, args=(result_fn,) + args)
# We are saving the result op here to be used in train/test execution
# functions. This basically gives the result op that was generated with a
# control dep to the updates for these workflows.
metric_obj._call_result = result_t
return result_t
return tf_decorator.make_decorator(result_fn, decorated)
def weakmethod(method):
"""Creates a weak reference to the bound method."""
cls = method.im_class
func = method.im_func
instance_ref = weakref.ref(method.im_self)
@functools.wraps(method)
def inner(*args, **kwargs):
return func.__get__(instance_ref(), cls)(*args, **kwargs)
del method
return inner
def assert_thresholds_range(thresholds):
if thresholds is not None:
invalid_thresholds = [t for t in thresholds if t is None or t < 0 or t > 1]
if invalid_thresholds:
raise ValueError(
'Threshold values must be in [0, 1]. Invalid values: {}'.format(
invalid_thresholds))
def parse_init_thresholds(thresholds, default_threshold=0.5):
if thresholds is not None:
assert_thresholds_range(to_list(thresholds))
thresholds = to_list(default_threshold if thresholds is None else thresholds)
return thresholds
| Reduction |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/unit_tests/integration/test_issues.py | {
"start": 1911,
"end": 3438
} | class ____(TestCase):
@HttpMocker()
def test_given_timezone_in_state_when_read_consider_timezone(self, http_mocker: HttpMocker) -> None:
config = _create_config().build()
datetime_with_timezone = "2023-11-01T00:00:00.000-0800"
timestamp_with_timezone = 1698825600000
state = (
StateBuilder()
.with_stream_state(
"issues",
{
"use_global_cursor": False,
"state": {"updated": datetime_with_timezone},
"lookback_window": 2,
"states": [{"partition": {}, "cursor": {"updated": datetime_with_timezone}}],
},
)
.build()
)
http_mocker.get(
HttpRequest(
f"https://{_DOMAIN}/rest/api/3/search/jql",
{
"fields": "*all",
"jql": f"updated >= {timestamp_with_timezone} ORDER BY updated asc",
"expand": "renderedFields,transitions,changelog",
"maxResults": "50",
},
),
_create_response().with_record(_create_record()).with_record(_create_record()).build(),
)
source = YamlDeclarativeSource(config=config, catalog=_create_catalog(), state=state, path_to_yaml=str(_YAML_FILE_PATH))
actual_messages = read(source, config=config, catalog=_create_catalog(), state=state)
assert len(actual_messages.records) == 2
| IssuesTest |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 45893,
"end": 46452
} | class ____(MixinSequenceOfValues):
"""
Horizontal facet label background
Parameters
----------
theme_element : element_rect
"""
def apply_figure(self, figure: Figure, targets: ThemeTargets):
super().apply_figure(figure, targets)
if bboxes := targets.strip_background_x:
self.set(bboxes)
def blank_figure(self, figure: Figure, targets: ThemeTargets):
super().blank_figure(figure, targets)
for rect in targets.strip_background_x:
rect.set_visible(False)
| strip_background_x |
python | doocs__leetcode | solution/1900-1999/1970.Last Day Where You Can Still Cross/Solution2.py | {
"start": 563,
"end": 1332
} | class ____:
def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
mn = len(cells)
uf = UnionFind(mn + 2)
s, t = mn, mn + 1
dirs = (-1, 0, 1, 0, -1)
g = [[1] * col for _ in range(row)]
for i in range(mn - 1, -1, -1):
x, y = cells[i][0] - 1, cells[i][1] - 1
g[x][y] = 0
for a, b in pairwise(dirs):
nx, ny = x + a, y + b
if 0 <= nx < row and 0 <= ny < col and g[nx][ny] == 0:
uf.union(x * col + y, nx * col + ny)
if x == 0:
uf.union(y, s)
if x == row - 1:
uf.union(x * col + y, t)
if uf.find(s) == uf.find(t):
return i
| Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 21319,
"end": 22449
} | class ____(graphene.ObjectType):
keyStateInfo = non_null_list(GrapheneDefsKeyStateInfoEntry)
class Meta:
name = "DefsStateInfo"
def __init__(self, defs_state_info: DefsStateInfo):
super().__init__(
keyStateInfo=[
GrapheneDefsKeyStateInfoEntry(
key,
GrapheneDefsKeyStateInfo(
info.version, info.create_timestamp, info.management_type
)
if info
else None,
)
for key, info in defs_state_info.info_mapping.items()
]
)
types = [
GrapheneLocationStateChangeEvent,
GrapheneLocationStateChangeEventType,
GrapheneLocationStateChangeSubscription,
GrapheneRepositoriesOrError,
GrapheneRepository,
GrapheneRepositoryConnection,
GrapheneRepositoryLocation,
GrapheneRepositoryOrError,
GrapheneWorkspaceLocationEntryOrError,
GrapheneDefsStateInfo,
GrapheneDefsKeyStateInfo,
GrapheneDefsKeyStateInfoEntry,
GrapheneDefsStateManagementType,
]
| GrapheneDefsStateInfo |
python | huggingface__transformers | src/transformers/models/gpt_oss/modular_gpt_oss.py | {
"start": 15570,
"end": 16695
} | class ____(LlamaPreTrainedModel):
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
_supports_sdpa = False
_supports_flash_attention = False
_supports_flex_attention = False
_can_record_outputs = {
"router_logits": OutputRecorder(GptOssTopKRouter, index=0),
"hidden_states": GptOssDecoderLayer,
"attentions": GptOssAttention,
}
@torch.no_grad()
def _init_weights(self, module):
PreTrainedModel._init_weights(self, module)
std = self.config.initializer_range
if isinstance(module, GptOssExperts):
init.normal_(module.gate_up_proj, mean=0.0, std=std)
init.zeros_(module.gate_up_proj_bias)
init.normal_(module.down_proj, mean=0.0, std=std)
init.zeros_(module.down_proj_bias)
elif isinstance(module, GptOssAttention):
init.normal_(module.sinks, mean=0.0, std=std)
elif isinstance(module, GptOssTopKRouter):
init.normal_(module.weight, mean=0.0, std=std)
init.normal_(module.bias, mean=0.0, std=std)
| GptOssPreTrainedModel |
python | Textualize__textual | docs/examples/guide/widgets/checker03.py | {
"start": 224,
"end": 1758
} | class ____(ScrollView):
COMPONENT_CLASSES = {
"checkerboard--white-square",
"checkerboard--black-square",
}
DEFAULT_CSS = """
CheckerBoard .checkerboard--white-square {
background: #A5BAC9;
}
CheckerBoard .checkerboard--black-square {
background: #004578;
}
"""
def __init__(self, board_size: int) -> None:
super().__init__()
self.board_size = board_size
# Each square is 4 rows and 8 columns
self.virtual_size = Size(board_size * 8, board_size * 4)
def render_line(self, y: int) -> Strip:
"""Render a line of the widget. y is relative to the top of the widget."""
scroll_x, scroll_y = self.scroll_offset # The current scroll position
y += scroll_y # The line at the top of the widget is now `scroll_y`, not zero!
row_index = y // 4 # four lines per row
white = self.get_component_rich_style("checkerboard--white-square")
black = self.get_component_rich_style("checkerboard--black-square")
if row_index >= self.board_size:
return Strip.blank(self.size.width)
is_odd = row_index % 2
segments = [
Segment(" " * 8, black if (column + is_odd) % 2 else white)
for column in range(self.board_size)
]
strip = Strip(segments, self.board_size * 8)
# Crop the strip so that it covers the visible area
strip = strip.crop(scroll_x, scroll_x + self.size.width)
return strip
| CheckerBoard |
python | redis__redis-py | tests/test_multidb/test_healthcheck.py | {
"start": 9297,
"end": 14453
} | class ____:
def test_database_is_healthy_when_bdb_matches_by_dns_name(
self, mock_client, mock_cb
):
"""
Ensures health check succeeds when /v1/bdbs contains an endpoint whose dns_name
matches database host, and availability endpoint returns success.
"""
host = "db1.example.com"
mock_client.get_connection_kwargs.return_value = {"host": host}
# Mock HttpClient used inside LagAwareHealthCheck
mock_http = MagicMock()
mock_http.get.side_effect = [
# First call: list of bdbs
[
{
"uid": "bdb-1",
"endpoints": [
{"dns_name": host, "addr": ["10.0.0.1", "10.0.0.2"]},
],
}
],
# Second call: availability check (no JSON expected)
None,
]
hc = LagAwareHealthCheck(rest_api_port=1234, lag_aware_tolerance=150)
# Inject our mocked http client
hc._http_client = mock_http
db = Database(mock_client, mock_cb, 1.0, "https://healthcheck.example.com")
assert hc.check_health(db) is True
# Base URL must be set correctly
assert hc._http_client.base_url == "https://healthcheck.example.com:1234"
# Calls: first to list bdbs, then to availability
assert mock_http.get.call_count == 2
first_call = mock_http.get.call_args_list[0]
second_call = mock_http.get.call_args_list[1]
assert first_call.args[0] == "/v1/bdbs"
assert (
second_call.args[0]
== "/v1/bdbs/bdb-1/availability?extend_check=lag&availability_lag_tolerance_ms=150"
)
assert second_call.kwargs.get("expect_json") is False
def test_database_is_healthy_when_bdb_matches_by_addr(self, mock_client, mock_cb):
"""
Ensures health check succeeds when endpoint addr list contains the database host.
"""
host_ip = "203.0.113.5"
mock_client.get_connection_kwargs.return_value = {"host": host_ip}
mock_http = MagicMock()
mock_http.get.side_effect = [
[
{
"uid": "bdb-42",
"endpoints": [
{"dns_name": "not-matching.example.com", "addr": [host_ip]},
],
}
],
None,
]
hc = LagAwareHealthCheck()
hc._http_client = mock_http
db = Database(mock_client, mock_cb, 1.0, "https://healthcheck.example.com")
assert hc.check_health(db) is True
assert mock_http.get.call_count == 2
assert (
mock_http.get.call_args_list[1].args[0]
== "/v1/bdbs/bdb-42/availability?extend_check=lag&availability_lag_tolerance_ms=5000"
)
def test_raises_value_error_when_no_matching_bdb(self, mock_client, mock_cb):
"""
Ensures health check raises ValueError when there's no bdb matching the database host.
"""
host = "db2.example.com"
mock_client.get_connection_kwargs.return_value = {"host": host}
mock_http = MagicMock()
# Return bdbs that do not match host by dns_name nor addr
mock_http.get.return_value = [
{
"uid": "a",
"endpoints": [{"dns_name": "other.example.com", "addr": ["10.0.0.9"]}],
},
{
"uid": "b",
"endpoints": [
{"dns_name": "another.example.com", "addr": ["10.0.0.10"]}
],
},
]
hc = LagAwareHealthCheck()
hc._http_client = mock_http
db = Database(mock_client, mock_cb, 1.0, "https://healthcheck.example.com")
with pytest.raises(ValueError, match="Could not find a matching bdb"):
hc.check_health(db)
# Only the listing call should have happened
mock_http.get.assert_called_once_with("/v1/bdbs")
def test_propagates_http_error_from_availability(self, mock_client, mock_cb):
"""
Ensures that any HTTP error raised by the availability endpoint is propagated.
"""
host = "db3.example.com"
mock_client.get_connection_kwargs.return_value = {"host": host}
mock_http = MagicMock()
# First: list bdbs -> match by dns_name
mock_http.get.side_effect = [
[{"uid": "bdb-err", "endpoints": [{"dns_name": host, "addr": []}]}],
# Second: availability -> raise HttpError
HttpError(
url=f"https://{host}:9443/v1/bdbs/bdb-err/availability",
status=503,
message="busy",
),
]
hc = LagAwareHealthCheck()
hc._http_client = mock_http
db = Database(mock_client, mock_cb, 1.0, "https://healthcheck.example.com")
with pytest.raises(HttpError, match="busy") as e:
hc.check_health(db)
assert e.status == 503
# Ensure both calls were attempted
assert mock_http.get.call_count == 2
| TestLagAwareHealthCheck |
python | wandb__wandb | wandb/sdk/artifacts/artifact_file_cache.py | {
"start": 1169,
"end": 9966
} | class ____:
def __init__(self, cache_dir: StrPath) -> None:
self._cache_dir = Path(cache_dir)
self._obj_dir = self._cache_dir / "obj"
self._temp_dir = self._cache_dir / "tmp"
self._ensure_write_permissions()
# NamedTemporaryFile sets the file mode to 600 [1], we reset to the default.
# [1] https://stackoverflow.com/questions/10541760/can-i-set-the-umask-for-tempfile-namedtemporaryfile-in-python
self._sys_umask = _get_sys_umask_threadsafe()
self._override_cache_path: StrPath | None = None
def check_md5_obj_path(
self, b64_md5: B64MD5, size: int
) -> tuple[FilePathStr, bool, Opener]:
# Check if we're using vs skipping the cache
if self._override_cache_path is not None:
skip_cache = True
path = Path(self._override_cache_path)
else:
skip_cache = False
hex_md5 = b64_to_hex_id(b64_md5)
path = self._obj_dir / "md5" / hex_md5[:2] / hex_md5[2:]
return self._check_or_create(path, size, skip_cache=skip_cache)
# TODO(spencerpearson): this method at least needs its signature changed.
# An ETag is not (necessarily) a checksum.
def check_etag_obj_path(
self,
url: URIStr,
etag: ETag,
size: int,
) -> tuple[FilePathStr, bool, Opener]:
# Check if we're using vs skipping the cache
if self._override_cache_path is not None:
skip_cache = True
path = Path(self._override_cache_path)
else:
skip_cache = False
hexhash = hashlib.sha256(
hashlib.sha256(url.encode("utf-8")).digest()
+ hashlib.sha256(etag.encode("utf-8")).digest()
).hexdigest()
path = self._obj_dir / "etag" / hexhash[:2] / hexhash[2:]
return self._check_or_create(path, size, skip_cache=skip_cache)
def _check_or_create(
self, path: Path, size: int, skip_cache: bool = False
) -> tuple[FilePathStr, bool, Opener]:
opener = self._opener(path, size, skip_cache=skip_cache)
hit = path.is_file() and path.stat().st_size == size
return FilePathStr(path), hit, opener
def cleanup(
self,
target_size: int | None = None,
remove_temp: bool = False,
target_fraction: float | None = None,
) -> int:
"""Clean up the cache, removing the least recently used files first.
Args:
target_size: The target size of the cache in bytes. If the cache is larger
than this, we will remove the least recently used files until the cache
is smaller than this size.
remove_temp: Whether to remove temporary files. Temporary files are files
that are currently being written to the cache. If remove_temp is True,
all temp files will be removed, regardless of the target_size or
target_fraction.
target_fraction: The target fraction of the cache to reclaim. If the cache
is larger than this, we will remove the least recently used files until
the cache is smaller than this fraction of its current size. It is an
error to specify both target_size and target_fraction.
Returns:
The number of bytes reclaimed.
"""
if target_size is None and target_fraction is None:
# Default to clearing the entire cache.
target_size = 0
if target_size is not None and target_fraction is not None:
raise ValueError("Cannot specify both target_size and target_fraction")
if target_size is not None and target_size < 0:
raise ValueError("target_size must be non-negative")
if target_fraction is not None and (target_fraction < 0 or target_fraction > 1):
raise ValueError("target_fraction must be between 0 and 1")
bytes_reclaimed = 0
total_size = 0
temp_size = 0
# Remove all temporary files if requested. Otherwise sum their size.
for entry in files_in(self._temp_dir):
size = entry.stat().st_size
total_size += size
if remove_temp:
try:
os.remove(entry.path)
bytes_reclaimed += size
except OSError:
pass
else:
temp_size += size
if temp_size:
wandb.termwarn(
f"Cache contains {util.to_human_size(temp_size)} of temporary files. "
"Run `wandb artifact cache cleanup --remove-temp` to remove them."
)
entries = []
for file_entry in files_in(self._obj_dir):
total_size += file_entry.stat().st_size
entries.append(file_entry)
if target_fraction is not None:
target_size = int(total_size * target_fraction)
assert target_size is not None
for entry in sorted(entries, key=lambda x: x.stat().st_atime):
if total_size <= target_size:
return bytes_reclaimed
try:
os.remove(entry.path)
except OSError:
pass
total_size -= entry.stat().st_size
bytes_reclaimed += entry.stat().st_size
if total_size > target_size:
wandb.termerror(
f"Failed to reclaim enough space in {self._cache_dir}. Try running"
" `wandb artifact cache cleanup --remove-temp` to remove temporary files."
)
return bytes_reclaimed
def _free_space(self) -> int:
"""Return the number of bytes of free space in the cache directory."""
return shutil.disk_usage(self._cache_dir)[2]
def _reserve_space(self, size: int) -> None:
"""If a `size` write would exceed disk space, remove cached items to make space.
Raises:
OSError: If there is not enough space to write `size` bytes, even after
removing cached items.
"""
if size <= self._free_space():
return
wandb.termwarn("Cache size exceeded. Attempting to reclaim space...")
self.cleanup(target_fraction=0.5)
if size <= self._free_space():
return
self.cleanup(target_size=0)
if size > self._free_space():
raise OSError(errno.ENOSPC, f"Insufficient free space in {self._cache_dir}")
def _opener(self, path: Path, size: int, skip_cache: bool = False) -> Opener:
@contextlib.contextmanager
def atomic_open(mode: str = "w") -> Iterator[IO]:
if "a" in mode:
raise ValueError("Appending to cache files is not supported")
if skip_cache:
# Skip the cache but still use an intermediate temporary file to
# ensure atomicity. Place the temp file in the same root as the
# destination file to avoid cross-filesystem move/copy operations.
temp_dir = path.parent
else:
self._reserve_space(size)
temp_dir = self._temp_dir
temp_dir.mkdir(parents=True, exist_ok=True)
temp_file = NamedTemporaryFile(dir=temp_dir, mode=mode, delete=False)
try:
yield temp_file
temp_file.close()
os.chmod(temp_file.name, 0o666 & ~self._sys_umask)
path.parent.mkdir(parents=True, exist_ok=True)
os.replace(temp_file.name, path)
except Exception:
os.remove(temp_file.name)
raise
return atomic_open
def _ensure_write_permissions(self) -> None:
"""Raise an error if we cannot write to the cache directory."""
try:
self._temp_dir.mkdir(parents=True, exist_ok=True)
with NamedTemporaryFile(dir=self._temp_dir) as f:
f.write(b"wandb")
except PermissionError as e:
raise PermissionError(
f"Unable to write to {self._cache_dir}. "
"Ensure that the current user has write permissions."
) from e
# Memo `ArtifactFileCache` instances while avoiding reliance on global
# variable(s). Notes:
# - @lru_cache should be thread-safe.
# - We don't memoize `get_artifact_file_cache` directly, as the cache_dir
# may change at runtime. This is likely rare in practice, though.
@lru_cache(maxsize=1)
def _build_artifact_file_cache(cache_dir: StrPath) -> ArtifactFileCache:
return ArtifactFileCache(cache_dir)
def get_artifact_file_cache() -> ArtifactFileCache:
return _build_artifact_file_cache(artifacts_cache_dir())
| ArtifactFileCache |
python | h5py__h5py | h5py/tests/test_attrs.py | {
"start": 693,
"end": 856
} | class ____(TestCase):
def setUp(self):
self.f = File(self.mktemp(), 'w')
def tearDown(self):
if self.f:
self.f.close()
| BaseAttrs |
python | tensorflow__tensorflow | tensorflow/python/autograph/impl/api.py | {
"start": 5939,
"end": 7328
} | class ____(tf_stack.StackTraceMapper):
"""Remaps generated code to code it originated from."""
def __init__(self, converted_fn):
super().__init__()
self._source_map = converted_fn.ag_source_map
# This may be called repeatedly: once on entry, by the superclass, then by
# each child context manager.
self._cached_map = None
def get_effective_source_map(self):
if self._cached_map is not None:
return self._cached_map
parent_map = self.parent.get_effective_source_map()
effective_source_map = {}
for loc, origin in self._source_map.items():
effective_source_map[(loc.filename, loc.lineno)] = (origin.loc.filename,
origin.loc.lineno,
origin.function_name)
for key, value in parent_map.items():
filename, lineno, _ = value
value_loc = origin_info.LineLocation(filename=filename, lineno=lineno)
if value_loc in self._source_map:
origin = self._source_map[value_loc]
effective_source_map[key] = (origin.loc.filename, origin.loc.lineno,
origin.function_name)
else:
effective_source_map[key] = value
self._cached_map = effective_source_map
return effective_source_map
#
# Actual source code transformation
#
| StackTraceMapper |
python | huggingface__transformers | src/transformers/models/siglip2/image_processing_siglip2_fast.py | {
"start": 2573,
"end": 5700
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = [0.5, 0.5, 0.5]
image_std = [0.5, 0.5, 0.5]
do_resize = True
do_rescale = True
do_normalize = True
patch_size = 16
max_num_patches = 256
valid_kwargs = Siglip2ImageProcessorKwargs
unused_kwargs = ["size", "do_center_crop", "crop_size"]
def __init__(self, **kwargs: Unpack[Siglip2ImageProcessorKwargs]):
super().__init__(**kwargs)
def _validate_preprocess_kwargs(self, **kwargs) -> tuple:
# Remove do_resize from kwargs to not raise an error as size is None
kwargs.pop("do_resize", None)
return super()._validate_preprocess_kwargs(**kwargs)
@auto_docstring
def preprocess(self, images: ImageInput, **kwargs: Unpack[Siglip2ImageProcessorKwargs]) -> BatchFeature:
return super().preprocess(images, **kwargs)
def _preprocess(
self,
images: list["torch.Tensor"],
do_resize: bool,
patch_size: int,
max_num_patches: int,
interpolation: Optional["F.InterpolationMode"],
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
image_mean: Optional[Union[float, list[float]]],
image_std: Optional[Union[float, list[float]]],
return_tensors: Optional[Union[str, TensorType]],
**kwargs,
) -> BatchFeature:
pixel_masks = []
pixel_values = []
spatial_shapes = []
for image in images:
if do_resize:
height, width = get_image_size_for_max_num_patches(
image_height=image.shape[1],
image_width=image.shape[2],
patch_size=patch_size,
max_num_patches=max_num_patches,
)
size_dict = SizeDict(height=height, width=width)
image = self.resize(image=image, size=size_dict, interpolation=interpolation)
image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
# (num_channels, height, width) -> (num_patches, patch_size * patch_size * num_channels)
patches = convert_image_to_patches(image, patch_size)
patches, mask = pad_along_first_dim(patches, max_num_patches)
num_patches_height = image.shape[1] // patch_size
num_patches_width = image.shape[2] // patch_size
spatial_shapes.append((num_patches_height, num_patches_width))
pixel_values.append(patches)
pixel_masks.append(mask)
pixel_values = torch.stack(pixel_values)
pixel_masks = torch.stack(pixel_masks)
spatial_shapes = torch.tensor(spatial_shapes)
batch_feature = BatchFeature(
data={
"pixel_values": pixel_values,
"pixel_attention_mask": pixel_masks,
"spatial_shapes": spatial_shapes,
},
tensor_type=return_tensors,
)
return batch_feature
__all__ = ["Siglip2ImageProcessorFast"]
| Siglip2ImageProcessorFast |
python | huggingface__transformers | tests/models/roformer/test_modeling_roformer.py | {
"start": 21265,
"end": 23845
} | class ____(unittest.TestCase):
tolerance = 1e-4
def test_apply_rotary_position_embeddings(self):
# 2,12,16,64
query_layer = (
torch.arange(2 * 12 * 16 * 64, dtype=torch.float, device=torch_device).reshape(2, 12, 16, 64) / 100
).to(torch_device)
key_layer = (
-torch.arange(2 * 12 * 16 * 64, dtype=torch.float, device=torch_device).reshape(2, 12, 16, 64) / 100
).to(torch_device)
embed_positions = RoFormerSinusoidalPositionalEmbedding(num_positions=32, embedding_dim=64)
embed_positions.weight.copy_(embed_positions.create_weight())
embed_positions = embed_positions.to(torch_device)
sinusoidal_pos = embed_positions([2, 16, 768])[None, None, :, :]
query_layer, key_layer = RoFormerSelfAttention.apply_rotary_position_embeddings(
sinusoidal_pos, query_layer, key_layer
)
desired_query_layer = torch.tensor(
[
[0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700],
[-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343],
[-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985],
[-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871],
[0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980],
[3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253],
]
).to(torch_device)
desired_key_layer = torch.tensor(
[
[0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700],
[0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343],
[1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985],
[2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871],
[-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980],
[-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253],
]
).to(torch_device)
self.assertTrue(
torch.allclose(query_layer[0, 0, :6, :8], desired_query_layer, atol=self.tolerance),
msg=f"\nexp:\n{desired_query_layer}\ngot:\n{query_layer}\n",
)
self.assertTrue(
torch.allclose(key_layer[0, 0, :6, :8], desired_key_layer, atol=self.tolerance),
msg=f"\nexp:\n{desired_key_layer}\ngot:\n{key_layer}\n",
)
| RoFormerSelfAttentionRotaryPositionEmbeddingTest |
python | getsentry__sentry | src/sentry/exceptions.py | {
"start": 190,
"end": 373
} | class ____(InvalidRequest):
def __init__(self, origin):
self.origin = origin
def __str__(self) -> str:
return "Invalid origin: '%s'" % self.origin
| InvalidOrigin |
python | PrefectHQ__prefect | src/prefect/infrastructure/provisioners/ecs.py | {
"start": 12141,
"end": 17771
} | class ____:
def __init__(
self,
work_pool_name: str,
user_name: str = "prefect-ecs-user",
policy_name: str = "prefect-ecs-policy",
credentials_block_name: Optional[str] = None,
):
self._user_name = user_name
self._credentials_block_name = (
credentials_block_name or f"{work_pool_name}-aws-credentials"
)
self._policy_name = policy_name
self._policy_document: dict[str, Any] = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PrefectEcsPolicy",
"Effect": "Allow",
"Action": [
"ec2:AuthorizeSecurityGroupIngress",
"ec2:CreateSecurityGroup",
"ec2:CreateTags",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs",
"ecs:CreateCluster",
"ecs:DeregisterTaskDefinition",
"ecs:DescribeClusters",
"ecs:DescribeTaskDefinition",
"ecs:DescribeTasks",
"ecs:ListAccountSettings",
"ecs:ListClusters",
"ecs:ListTaskDefinitions",
"ecs:RegisterTaskDefinition",
"ecs:RunTask",
"ecs:StopTask",
"ecs:TagResource",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups",
"logs:GetLogEvents",
],
"Resource": "*",
}
],
}
self._iam_user_resource = IamUserResource(user_name=user_name)
self._iam_policy_resource = IamPolicyResource(policy_name=policy_name)
self._credentials_block_resource = CredentialsBlockResource(
user_name=user_name, block_document_name=self._credentials_block_name
)
self._execution_role_resource = ExecutionRoleResource()
@property
def resources(
self,
) -> list[
"ExecutionRoleResource | IamUserResource | IamPolicyResource | CredentialsBlockResource"
]:
return [
self._execution_role_resource,
self._iam_user_resource,
self._iam_policy_resource,
self._credentials_block_resource,
]
async def get_task_count(self) -> int:
"""
Returns the number of tasks that will be executed to provision this resource.
Returns:
int: The number of tasks to be provisioned.
"""
return sum([await resource.get_task_count() for resource in self.resources])
async def requires_provisioning(self) -> bool:
"""
Check if this resource requires provisioning.
Returns:
bool: True if provisioning is required, False otherwise.
"""
return any(
[await resource.requires_provisioning() for resource in self.resources]
)
async def get_planned_actions(self) -> List[str]:
"""
Returns a description of the planned actions for provisioning this resource.
Returns:
Optional[str]: A description of the planned actions for provisioning the resource,
or None if provisioning is not required.
"""
return [
action
for resource in self.resources
for action in await resource.get_planned_actions()
]
async def provision(
self,
base_job_template: dict[str, Any],
advance: Callable[[], None],
) -> None:
"""
Provisions the authentication resources.
Args:
base_job_template: The base job template of the work pool to provision
infrastructure for.
advance: A callback function to indicate progress.
"""
# Provision task execution role
role_arn = await self._execution_role_resource.provision(
base_job_template=base_job_template, advance=advance
)
# Update policy document with the role ARN
self._policy_document["Statement"].append(
{
"Sid": "AllowPassRoleForEcs",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": role_arn,
}
)
# Provision the IAM user
await self._iam_user_resource.provision(advance=advance)
# Provision the IAM policy
policy_arn = await self._iam_policy_resource.provision(
policy_document=self._policy_document, advance=advance
)
# Attach the policy to the user
if policy_arn:
iam_client = boto3.client("iam")
await anyio.to_thread.run_sync(
partial(
iam_client.attach_user_policy,
UserName=self._user_name,
PolicyArn=policy_arn,
)
)
await self._credentials_block_resource.provision(
base_job_template=base_job_template,
advance=advance,
)
@property
def next_steps(self) -> list[str]:
return [
next_step
for resource in self.resources
for next_step in resource.next_steps
]
| AuthenticationResource |
python | pandas-dev__pandas | pandas/tests/generic/test_frame.py | {
"start": 5215,
"end": 6966
} | class ____:
@pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0])
def test_validate_bool_args(self, value):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
msg = 'For argument "inplace" expected type bool, received type'
with pytest.raises(ValueError, match=msg):
df.copy().rename_axis(mapper={"a": "x", "b": "y"}, axis=1, inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy().drop("a", axis=1, inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy().fillna(value=0, inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy().replace(to_replace=1, value=7, inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy().interpolate(inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy()._where(cond=df.a > 2, inplace=value)
with pytest.raises(ValueError, match=msg):
df.copy().mask(cond=df.a > 2, inplace=value)
def test_unexpected_keyword(self):
# GH8597
df = DataFrame(
np.random.default_rng(2).standard_normal((5, 2)), columns=["jim", "joe"]
)
ca = pd.Categorical([0, 0, 2, 2, 3, np.nan])
ts = df["joe"].copy()
ts[2] = np.nan
msg = "unexpected keyword"
with pytest.raises(TypeError, match=msg):
df.drop("joe", axis=1, in_place=True)
with pytest.raises(TypeError, match=msg):
df.reindex([1, 0], inplace=True)
with pytest.raises(TypeError, match=msg):
ca.fillna(0, inplace=True)
with pytest.raises(TypeError, match=msg):
ts.fillna(0, in_place=True)
| TestDataFrame2 |
python | django__django | django/core/serializers/json.py | {
"start": 1794,
"end": 2647
} | class ____(PythonDeserializer):
"""Deserialize a stream or string of JSON data."""
def __init__(self, stream_or_string, **options):
if not isinstance(stream_or_string, (bytes, str)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode()
try:
objects = json.loads(stream_or_string)
except Exception as exc:
raise DeserializationError() from exc
super().__init__(objects, **options)
def _handle_object(self, obj):
try:
yield from super()._handle_object(obj)
except (GeneratorExit, DeserializationError):
raise
except Exception as exc:
raise DeserializationError(f"Error deserializing object: {exc}") from exc
| Deserializer |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_context_management_response.py | {
"start": 657,
"end": 804
} | class ____(BaseModel):
applied_edits: List[AppliedEdit]
"""List of context management edits that were applied."""
| BetaContextManagementResponse |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 99699,
"end": 102475
} | class ____:
def test_manage_projects(self, db_request):
older_release = ReleaseFactory(created=datetime.datetime(2015, 1, 1))
project_with_older_release = ProjectFactory(releases=[older_release])
newer_release = ReleaseFactory(created=datetime.datetime(2017, 1, 1))
project_with_newer_release = ProjectFactory(releases=[newer_release])
older_project_with_no_releases = ProjectFactory(
releases=[], created=datetime.datetime(2016, 1, 1)
)
newer_project_with_no_releases = ProjectFactory(
releases=[], created=datetime.datetime(2018, 1, 1)
)
team_project = ProjectFactory(
name="team-proj", releases=[], created=datetime.datetime(2022, 3, 3)
)
db_request.user = UserFactory()
RoleFactory.create(
user=db_request.user,
project=project_with_older_release,
role_name="Maintainer",
)
RoleFactory.create(
user=db_request.user, project=project_with_newer_release, role_name="Owner"
)
RoleFactory.create(
user=db_request.user,
project=newer_project_with_no_releases,
role_name="Owner",
)
RoleFactory.create(
user=db_request.user,
project=older_project_with_no_releases,
role_name="Maintainer",
)
user_second_owner = UserFactory()
RoleFactory.create(
user=user_second_owner,
project=project_with_older_release,
role_name="Owner",
)
RoleFactory.create(
user=user_second_owner,
project=older_project_with_no_releases,
role_name="Owner",
)
RoleFactory.create(
user=user_second_owner,
project=project_with_newer_release,
role_name="Owner",
)
team = TeamFactory()
TeamRoleFactory.create(team=team, user=db_request.user)
TeamProjectRoleFactory(
team=team,
project=team_project,
role_name=TeamProjectRoleType.Maintainer,
)
assert views.manage_projects(db_request) == {
"projects": [
team_project,
newer_project_with_no_releases,
project_with_newer_release,
older_project_with_no_releases,
project_with_older_release,
],
"projects_owned": {
project_with_newer_release.name,
newer_project_with_no_releases.name,
},
"projects_sole_owned": {
newer_project_with_no_releases.name,
},
"project_invites": [],
}
| TestManageProjects |
python | huggingface__transformers | src/transformers/models/smolvlm/modular_smolvlm.py | {
"start": 15789,
"end": 19107
} | class ____(Idefics3ForConditionalGeneration):
_tied_weights_keys = {"lm_head.weight": "model.text_model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = SmolVLMModel(config)
self.model.text_model.generation_config = GenerationConfig.from_model_config(config)
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
self.post_init()
def forward(self, **super_kwargs):
r"""
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*):
Mask to avoid performing attention on padding pixel indices.
image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
The hidden states of the image encoder after modality projection.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or `model.image_token_id`. Tokens with indices set to `model.image_token_id` are
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> from transformers.image_utils import load_image
>>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible
>>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg")
>>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg")
>>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg")
>>> processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct")
>>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM2-2.2B-Instruct", dtype=torch.bfloat16, device_map="auto")
>>> # Create inputs
>>> messages = [
... {
... "role": "user",
... "content": [
... {"type": "video", "path": path/to/video},
... {"type": "text", "text": "What is happening in this video?"},
... ]
... }
... ]
>>> inputs = processor.apply_chat_template([messages], add_generation_prompt=True)
>>> # Generate
>>> generated_ids = model.generate(**inputs, max_new_tokens=256)
>>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
>>> print(generated_texts)
```"""
super().forward(**super_kwargs)
__all__ = [
"SmolVLMVisionConfig",
"SmolVLMConfig",
"SmolVLMImageProcessor",
"SmolVLMImageProcessorFast",
"SmolVLMForConditionalGeneration",
"SmolVLMPreTrainedModel",
"SmolVLMModel",
"SmolVLMVisionTransformer",
]
| SmolVLMForConditionalGeneration |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 450,
"end": 480
} | class ____(object, A):
...
| B |
python | huggingface__transformers | src/transformers/models/granite/modeling_granite.py | {
"start": 10070,
"end": 13845
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: GraniteConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GraniteAttention(config=config, layer_idx=layer_idx)
self.mlp = GraniteMLP(config)
self.input_layernorm = GraniteRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = GraniteRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.residual_multiplier = config.residual_multiplier
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs,
) -> 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`, *optional*):
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
query_sequence_length, key_sequence_length)` if default attention is used.
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`).
past_key_values (`Cache`, *optional*): cached past key and value projection states
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
with `head_dim` being the embedding dimension of each attention head.
kwargs (`dict`, *optional*):
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
into the model
"""
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states * self.residual_multiplier
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states * self.residual_multiplier # main diff with Llama
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
@auto_docstring
| GraniteDecoderLayer |
python | squidfunk__mkdocs-material | material/plugins/social/layout.py | {
"start": 2060,
"end": 2161
} | class ____(Config):
width = Type(int, default = 0)
height = Type(int, default = 0)
# Offset
| Size |
python | jina-ai__jina | jina/orchestrate/deployments/config/k8s.py | {
"start": 745,
"end": 14313
} | class ____:
"""
Class that implements the output of configuration files for Kubernetes for a given Deployment.
"""
class _K8sDeployment:
def __init__(
self,
name: str,
version: str,
pod_type: PodRoleType,
jina_deployment_name: str,
shard_id: Optional[int],
common_args: Union['Namespace', Dict],
deployment_args: Union['Namespace', Dict],
k8s_namespace: str,
):
self.name = name
self.dns_name = to_compatible_name(name)
self.version = version
self.pod_type = pod_type
self.jina_deployment_name = jina_deployment_name
self.shard_id = shard_id
self.common_args = common_args
self.deployment_args = deployment_args
self.num_replicas = getattr(self.deployment_args, 'replicas', 1)
self.k8s_namespace = k8s_namespace
def get_gateway_yamls(
self,
) -> List[Dict]:
cargs = copy.copy(self.deployment_args)
from jina.helper import ArgNamespace
from jina.parsers import set_gateway_parser
taboo = {
'uses_metas',
'volumes',
'uses_before',
'uses_after',
'workspace',
'workspace_id',
'noblock_on_start',
'env_from_secret',
'image_pull_secrets',
'env',
}
image_name = resolve_image_name(cargs.uses)
if cargs.uses not in [
__default_http_gateway__,
__default_websocket_gateway__,
__default_grpc_gateway__,
__default_composite_gateway__,
]:
cargs.uses = 'config.yml'
non_defaults = ArgNamespace.get_non_defaults_args(
cargs, set_gateway_parser(), taboo=taboo
)
_args = ArgNamespace.kwargs2list(non_defaults)
container_args = ['gateway'] + _args
return kubernetes_deployment.get_template_yamls(
self.dns_name,
namespace=self.k8s_namespace,
image_name=image_name,
container_cmd='["jina"]',
container_args=f'{container_args}',
replicas=self.num_replicas,
pull_policy='IfNotPresent',
jina_deployment_name='gateway',
pod_type=self.pod_type,
env=cargs.env,
env_from_secret=cargs.env_from_secret,
image_pull_secrets=cargs.image_pull_secrets,
monitoring=self.common_args.monitoring,
protocol=self.common_args.protocol,
timeout_ready=self.common_args.timeout_ready,
)
def _get_container_args(self, cargs, pod_type):
uses_metas = cargs.uses_metas or {}
uses_with = self.deployment_args.uses_with
if cargs.uses != __default_executor__:
cargs.uses = 'config.yml'
return construct_runtime_container_args(
cargs, uses_metas, uses_with, pod_type
)
def get_runtime_yamls(self) -> List[Dict]:
cargs = copy.copy(self.deployment_args)
image_name = resolve_image_name(cargs.uses)
image_name_uses_before = (
resolve_image_name(cargs.uses_before)
if hasattr(cargs, 'uses_before') and cargs.uses_before
else None
)
image_name_uses_after = (
resolve_image_name(cargs.uses_after)
if hasattr(cargs, 'uses_after') and cargs.uses_after
else None
)
container_args = self._get_container_args(cargs, pod_type=self.pod_type)
container_args_uses_before = None
if getattr(cargs, 'uses_before', False):
uses_before_cargs = copy.copy(cargs)
uses_before_cargs.uses = cargs.uses_before
uses_before_cargs.name = f'{self.common_args.name}/uses-before'
uses_before_cargs.port = GrpcConnectionPool.K8S_PORT_USES_BEFORE
uses_before_cargs.uses_before_address = None
uses_before_cargs.uses_after_address = None
uses_before_cargs.uses_before = None
uses_before_cargs.uses_after = None
uses_before_cargs.uses_with = None
uses_before_cargs.uses_metas = None
uses_before_cargs.connection_list = None
uses_before_cargs.runtime_cls = 'WorkerRuntime'
uses_before_cargs.pod_role = PodRoleType.WORKER
uses_before_cargs.polling = None
uses_before_cargs.env = None
container_args_uses_before = self._get_container_args(
uses_before_cargs, PodRoleType.WORKER
)
container_args_uses_after = None
if getattr(cargs, 'uses_after', False):
uses_after_cargs = copy.copy(cargs)
uses_after_cargs.uses = cargs.uses_after
uses_after_cargs.name = f'{self.common_args.name}/uses-after'
uses_after_cargs.port = GrpcConnectionPool.K8S_PORT_USES_AFTER
uses_after_cargs.uses_before_address = None
uses_after_cargs.uses_after_address = None
uses_after_cargs.uses_before = None
uses_after_cargs.uses_after = None
uses_after_cargs.uses_with = None
uses_after_cargs.uses_metas = None
uses_after_cargs.connection_list = None
uses_after_cargs.runtime_cls = 'WorkerRuntime'
uses_after_cargs.pod_role = PodRoleType.WORKER
uses_after_cargs.polling = None
uses_after_cargs.env = None
container_args_uses_after = self._get_container_args(
uses_after_cargs, PodRoleType.WORKER
)
return kubernetes_deployment.get_template_yamls(
self.dns_name,
namespace=self.k8s_namespace,
image_name=image_name,
image_name_uses_after=image_name_uses_after,
image_name_uses_before=image_name_uses_before,
container_cmd='["jina"]',
container_cmd_uses_before='["jina"]',
container_cmd_uses_after='["jina"]',
container_args=f'{container_args}',
container_args_uses_before=container_args_uses_before,
container_args_uses_after=container_args_uses_after,
replicas=self.num_replicas,
pull_policy='IfNotPresent',
jina_deployment_name=self.jina_deployment_name,
pod_type=self.pod_type,
protocol=self.common_args.protocol,
shard_id=self.shard_id,
env=cargs.env,
env_from_secret=cargs.env_from_secret,
image_pull_secrets=cargs.image_pull_secrets,
gpus=cargs.gpus if hasattr(cargs, 'gpus') else None,
monitoring=cargs.monitoring,
volumes=getattr(cargs, 'volumes', None),
timeout_ready=cargs.timeout_ready,
)
def __init__(
self,
args: Union['Namespace', Dict],
k8s_namespace: Optional[str] = None,
):
# External Deployments should be ignored in a K8s based Flow
assert not (hasattr(args, 'external') and args.external)
if not validate_uses(args.uses):
raise NoContainerizedError(
f'Executor "{args.uses}" is not valid to be used in K8s. '
'You need to use a containerized Executor. You may check `jina hub --help` to see how Jina Hub can help you building containerized Executors.'
)
self.k8s_namespace = k8s_namespace
self.head_deployment = None
self.args = copy.copy(args)
if k8s_namespace is not None:
# otherwise it will remain with the one from the original Deployment
self.args.k8s_namespace = k8s_namespace
self.name = self.args.name
self.deployment_args = self._get_deployment_args(self.args)
if self.deployment_args['head_deployment'] is not None:
self.head_deployment = self._K8sDeployment(
name=self.deployment_args['head_deployment'].name,
version=get_base_executor_version(),
shard_id=None,
jina_deployment_name=self.name,
common_args=self.args,
deployment_args=self.deployment_args['head_deployment'],
pod_type=PodRoleType.HEAD,
k8s_namespace=self.k8s_namespace,
)
self.worker_deployments = []
deployment_args = self.deployment_args['deployments']
for i, args in enumerate(deployment_args):
name = f'{self.name}-{i}' if len(deployment_args) > 1 else f'{self.name}'
self.worker_deployments.append(
self._K8sDeployment(
name=name,
version=get_base_executor_version(),
shard_id=i,
common_args=self.args,
deployment_args=args,
pod_type=(
PodRoleType.WORKER if name != 'gateway' else PodRoleType.GATEWAY
),
jina_deployment_name=self.name,
k8s_namespace=self.k8s_namespace,
)
)
def _get_deployment_args(self, args):
parsed_args = {
'head_deployment': None,
'deployments': [],
}
shards = getattr(args, 'shards', 1)
uses_before = getattr(args, 'uses_before', None)
uses_after = getattr(args, 'uses_after', None)
if args.name != 'gateway':
# head deployment only exists for sharded deployments
if shards > 1:
parsed_args['head_deployment'] = Deployment._copy_to_head_args(
self.args
)
parsed_args['head_deployment'].gpus = None
parsed_args['head_deployment'].port = GrpcConnectionPool.K8S_PORT
parsed_args['head_deployment'].port_monitoring = (
GrpcConnectionPool.K8S_PORT_MONITORING
)
parsed_args['head_deployment'].uses = None
parsed_args['head_deployment'].uses_metas = None
parsed_args['head_deployment'].uses_with = None
import json
connection_list = {}
for i in range(shards):
name = (
f'{to_compatible_name(self.name)}-{i}'
if shards > 1
else f'{to_compatible_name(self.name)}'
)
connection_list[str(i)] = (
f'{name}.{self.k8s_namespace}.svc:{GrpcConnectionPool.K8S_PORT}'
)
parsed_args['head_deployment'].connection_list = json.dumps(
connection_list
)
if uses_before:
parsed_args['head_deployment'].uses_before_address = (
f'127.0.0.1:{GrpcConnectionPool.K8S_PORT_USES_BEFORE}'
)
if uses_after:
parsed_args['head_deployment'].uses_after_address = (
f'127.0.0.1:{GrpcConnectionPool.K8S_PORT_USES_AFTER}'
)
for i in range(shards):
cargs = copy.deepcopy(args)
cargs.host = args.host[0] if isinstance(args.host, list) else args.host
cargs.shard_id = i
cargs.uses_before = None
cargs.uses_after = None
cargs.port = [
GrpcConnectionPool.K8S_PORT + i for i in range(len(cargs.protocol))
]
cargs.port_monitoring = GrpcConnectionPool.K8S_PORT_MONITORING
cargs.uses_before_address = None
cargs.uses_after_address = None
if shards > 1:
cargs.name = f'{cargs.name}-{i}'
if args.name == 'gateway':
cargs.pod_role = PodRoleType.GATEWAY
parsed_args['deployments'].append(cargs)
return parsed_args
def to_kubernetes_yaml(
self,
) -> List[Tuple[str, List[Dict]]]:
"""
Return a list of dictionary configurations. One for each deployment in this Deployment
.. # noqa: DAR201
.. # noqa: DAR101
"""
if self.name == 'gateway':
return [
(
'gateway',
self.worker_deployments[0].get_gateway_yamls(),
)
]
else:
deployments = []
if self.head_deployment:
deployments.append(self.head_deployment)
deployments.extend(self.worker_deployments)
return [
(
deployment.dns_name,
deployment.get_runtime_yamls(),
)
for deployment in deployments
]
to_k8s_yaml = to_kubernetes_yaml
| K8sDeploymentConfig |
python | sympy__sympy | sympy/sandbox/indexed_integrals.py | {
"start": 197,
"end": 2141
} | class ____(Integral):
"""
Experimental class to test integration by indexed variables.
Usage is analogue to ``Integral``, it simply adds awareness of
integration over indices.
Contraction of non-identical index symbols referring to the same
``IndexedBase`` is not yet supported.
Examples
========
>>> from sympy.sandbox.indexed_integrals import IndexedIntegral
>>> from sympy import IndexedBase, symbols
>>> A = IndexedBase('A')
>>> i, j = symbols('i j', integer=True)
>>> ii = IndexedIntegral(A[i], A[i])
>>> ii
Integral(_A[i], _A[i])
>>> ii.doit()
A[i]**2/2
If the indices are different, indexed objects are considered to be
different variables:
>>> i2 = IndexedIntegral(A[j], A[i])
>>> i2
Integral(A[j], _A[i])
>>> i2.doit()
A[i]*A[j]
"""
def __new__(cls, function, *limits, **assumptions):
repl, limits = IndexedIntegral._indexed_process_limits(limits)
function = sympify(function)
function = function.xreplace(repl)
obj = Integral.__new__(cls, function, *limits, **assumptions)
obj._indexed_repl = repl
obj._indexed_reverse_repl = {val: key for key, val in repl.items()}
return obj
def doit(self):
res = super().doit()
return res.xreplace(self._indexed_reverse_repl)
@staticmethod
def _indexed_process_limits(limits):
repl = {}
newlimits = []
for i in limits:
if isinstance(i, (tuple, list, Tuple)):
v = i[0]
vrest = i[1:]
else:
v = i
vrest = ()
if isinstance(v, Indexed):
if v not in repl:
r = Dummy(str(v))
repl[v] = r
newlimits.append((r,)+vrest)
else:
newlimits.append(i)
return repl, newlimits
| IndexedIntegral |
python | huggingface__transformers | src/transformers/models/cohere/modeling_cohere.py | {
"start": 20923,
"end": 25189
} | class ____(CoherePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = CohereModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.logit_scale = config.logit_scale
self.tie_word_embeddings = config.tie_word_embeddings
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>> from transformers import AutoTokenizer, CohereForCausalLM
>> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01")
>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
>> prompt = "Hey, are you conscious? Can you talk to me?"
>> inputs = tokenizer(prompt, return_tensors="pt")
>> # Generate
>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
logits = logits * self.logit_scale # main diff from Llama
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
__all__ = ["CohereForCausalLM", "CohereModel", "CoherePreTrainedModel"]
| CohereForCausalLM |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 5897,
"end": 7394
} | class ____(SQLAlchemyError):
"""Raised by topological sorts when a circular dependency is detected.
There are two scenarios where this error occurs:
* In a Session flush operation, if two objects are mutually dependent
on each other, they can not be inserted or deleted via INSERT or
DELETE statements alone; an UPDATE will be needed to post-associate
or pre-deassociate one of the foreign key constrained values.
The ``post_update`` flag described at :ref:`post_update` can resolve
this cycle.
* In a :attr:`_schema.MetaData.sorted_tables` operation, two
:class:`_schema.ForeignKey`
or :class:`_schema.ForeignKeyConstraint` objects mutually refer to each
other. Apply the ``use_alter=True`` flag to one or both,
see :ref:`use_alter`.
"""
def __init__(
self,
message: str,
cycles: Any,
edges: Any,
msg: Optional[str] = None,
code: Optional[str] = None,
):
if msg is None:
message += " (%s)" % ", ".join(repr(s) for s in cycles)
else:
message = msg
SQLAlchemyError.__init__(self, message, code=code)
self.cycles = cycles
self.edges = edges
def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
return (
self.__class__,
(None, self.cycles, self.edges, self.args[0]),
{"code": self.code} if self.code is not None else {},
)
| CircularDependencyError |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 24446,
"end": 25219
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
# Ignore copy
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
# Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer
| MllamaTextMLP |
python | facebook__pyre-check | tools/typeshed_patcher/buck.py | {
"start": 346,
"end": 466
} | class ____:
def to_string(self) -> str:
return 'glob(["**/*"])'
@dataclasses.dataclass(frozen=True)
| GlobSource |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 113355,
"end": 114448
} | class ____(Response):
"""
Response of projects.move endpoint.
:param moved: The number of projects moved
:type moved: int
"""
_service = "projects"
_action = "move"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"moved": {
"description": "The number of projects moved",
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, moved: Optional[int] = None, **kwargs: Any) -> None:
super(MoveResponse, self).__init__(**kwargs)
self.moved = moved
@schema_property("moved")
def moved(self) -> Optional[int]:
return self._property_moved
@moved.setter
def moved(self, value: Optional[int]) -> None:
if value is None:
self._property_moved = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "moved", six.integer_types)
self._property_moved = value
| MoveResponse |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_rules.py | {
"start": 4979,
"end": 5464
} | class ____(ProjectRuleBaseTestCase):
method = "get"
def test_simple(self) -> None:
# attaches lastTriggered by default
response = self.get_success_response(
self.organization.slug,
self.project.slug,
status_code=status.HTTP_200_OK,
)
assert len(response.data) == Rule.objects.filter(project=self.project).count()
for rule in response.data:
assert "lastTriggered" in rule
| GetProjectRulesTest |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_event_details.py | {
"start": 3598,
"end": 6273
} | class ____(OrganizationEventsEndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def convert_args(
self,
request: Request,
organization_id_or_slug: int | str | None = None,
*args: Any,
**kwargs: Any,
) -> tuple[tuple[Any, ...], dict[str, Any]]:
args, kwargs = super().convert_args(request, organization_id_or_slug, *args, **kwargs)
organization = kwargs["organization"]
project_id_or_slug = kwargs.pop("project_id_or_slug")
try:
project = Project.objects.get(
slug__id_or_slug=project_id_or_slug,
organization_id=organization.id,
status=ObjectStatus.ACTIVE,
)
kwargs["project"] = project
except Project.DoesNotExist:
raise ResourceDoesNotExist
return args, kwargs
def get(self, request: Request, organization, project: Project, event_id) -> Response:
"""event_id is validated by a regex in the URL"""
if not self.has_feature(organization, request):
return Response(status=404)
# Check access to the project as this endpoint doesn't use membership checks done
# get_filter_params().
if not request.access.has_project_access(project):
return Response(status=404)
referrer = request.GET.get("referrer")
if referrer is not None:
sentry_sdk.set_tag("referrer", referrer)
# We return the requested event if we find a match regardless of whether
# it occurred within the range specified
with handle_query_errors():
event = eventstore.backend.get_event_by_id(project.id, event_id)
if event is None:
return Response({"detail": "Event not found"}, status=404)
average_columns = request.GET.getlist("averageColumn", [])
if (
all(col in VALID_AVERAGE_COLUMNS for col in average_columns)
and len(average_columns) > 0
and features.has("organizations:insight-modules", organization, actor=request.user)
):
add_comparison_to_event(event=event, average_columns=average_columns, request=request)
# TODO: Remove `for_group` check once performance issues are moved to the issue platform
if hasattr(event, "for_group") and event.group:
event = event.for_group(event.group)
data = serialize(
event, request.user, SqlFormatEventSerializer(), include_full_release_data=False
)
data["projectSlug"] = project.slug
return Response(data)
| OrganizationEventDetailsEndpoint |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-yelp/llama_index/tools/yelp/base.py | {
"start": 1656,
"end": 3072
} | class ____(BaseToolSpec):
"""Yelp tool spec."""
# TODO add disclaimer
spec_functions = ["business_search", "business_reviews"]
def __init__(self, api_key: str, client_id: str) -> Document:
"""Initialize with parameters."""
from yelpapi import YelpAPI
self.client = YelpAPI(api_key)
def business_search(self, location: str, term: str, radius: Optional[int] = None):
"""
Make a query to Yelp to find businesses given a location to search.
Args:
Businesses returned in the response may not be strictly within the specified location.
term (str): Search term, e.g. "food" or "restaurants", The term may also be the business's name, such as "Starbucks"
radius (int): A suggested search radius in meters. This field is used as a suggestion to the search. The actual search radius may be lower than the suggested radius in dense urban areas, and higher in regions of less business density.
"""
response = self.client.search_query(location=location, term=term)
return [Document(text=str(response))]
def business_reviews(self, id: str):
"""
Make a query to Yelp to find a business using an id from business_search.
Args:
# The id
"""
response = self.client.reviews_query(id=id)
return [Document(text=str(response))]
| YelpToolSpec |
python | pytorch__pytorch | torch/testing/_internal/distributed/distributed_test.py | {
"start": 3357,
"end": 4992
} | class ____:
def __init__(self, x):
# Can be tensor or int
self.x = x
def __eq__(self, other):
def eq(value, other):
if isinstance(value, torch.Tensor):
return torch.equal(value, other)
return value == other
for attr, value in self.__dict__.items():
other_value = other.__dict__[attr]
if not eq(value, other_value):
return False
return True
f = Foo(10)
f.bar = 1
# Defer instantiation until the seed is set so that randn() returns the same
# values in all processes.
def create_collectives_object_test_list():
return [
{"key1": 3, "key2": 4, "key3": {"nested": True}},
f,
Foo(torch.randn(3, 3)),
"foo",
[1, 2, True, "string", [4, 5, "nested"]],
]
# Allowlist of distributed backends where profiling collectives is supported.
PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.NCCL,
dist.Backend.GLOO,
dist.Backend.MPI,
dist.Backend.UCC,
]
# Allowlist of distributed backends where profiling is supported with use_cuda=True
CUDA_PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.GLOO,
dist.Backend.MPI,
dist.Backend.NCCL,
dist.Backend.UCC,
]
# Allowlist of distributed backends where profiling is supported for p2p ops
SEND_RECV_PROFILING_SUPPORTED_BACKENDS = [
dist.Backend.MPI,
dist.Backend.GLOO,
dist.Backend.NCCL,
dist.Backend.UCC,
]
# Dummy NamedTuple data structures to test DDP support for NamedTuple types.
EXPECTED_FIELDS = ("a", "b")
TestNamedTupleInput_0 = namedtuple("NamedTuple", EXPECTED_FIELDS)
| Foo |
python | pandas-dev__pandas | pandas/tests/test_algos.py | {
"start": 69625,
"end": 76184
} | class ____:
def test_no_mode(self):
exp = Series([], dtype=np.float64, index=Index([], dtype=int))
result, _ = algos.mode(np.array([]))
tm.assert_numpy_array_equal(result, exp.values)
def test_mode_single(self, any_real_numpy_dtype):
# GH 15714
exp_single = [1]
data_single = [1]
exp_multi = [1]
data_multi = [1, 1]
ser = Series(data_single, dtype=any_real_numpy_dtype)
exp = Series(exp_single, dtype=any_real_numpy_dtype)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
ser = Series(data_multi, dtype=any_real_numpy_dtype)
exp = Series(exp_multi, dtype=any_real_numpy_dtype)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
def test_mode_obj_int(self):
exp = Series([1], dtype=int)
result, _ = algos.mode(exp.values)
tm.assert_numpy_array_equal(result, exp.values)
exp = Series(["a", "b", "c"], dtype=object)
result, _ = algos.mode(exp.values)
tm.assert_numpy_array_equal(result, exp.values)
def test_number_mode(self, any_real_numpy_dtype):
exp_single = [1]
data_single = [1] * 5 + [2] * 3
exp_multi = [1, 3]
data_multi = [1] * 5 + [2] * 3 + [3] * 5
ser = Series(data_single, dtype=any_real_numpy_dtype)
exp = Series(exp_single, dtype=any_real_numpy_dtype)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
ser = Series(data_multi, dtype=any_real_numpy_dtype)
exp = Series(exp_multi, dtype=any_real_numpy_dtype)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
def test_strobj_mode(self):
exp = ["b"]
data = ["a"] * 2 + ["b"] * 3
ser = Series(data, dtype="c")
exp = Series(exp, dtype="c")
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
@pytest.mark.parametrize("dt", [str, object])
def test_strobj_multi_char(self, dt, using_infer_string):
exp = ["bar"]
data = ["foo"] * 2 + ["bar"] * 3
ser = Series(data, dtype=dt)
exp = Series(exp, dtype=dt)
result, _ = algos.mode(ser.values)
if using_infer_string and dt is str:
tm.assert_extension_array_equal(result, exp.values)
else:
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
def test_datelike_mode(self):
exp = Series(["1900-05-03", "2011-01-03", "2013-01-02"], dtype="M8[ns]")
ser = Series(["2011-01-03", "2013-01-02", "1900-05-03"], dtype="M8[ns]")
tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2011-01-03", "2013-01-02"], dtype="M8[ns]")
ser = Series(
["2011-01-03", "2013-01-02", "1900-05-03", "2011-01-03", "2013-01-02"],
dtype="M8[ns]",
)
tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
tm.assert_series_equal(ser.mode(), exp)
def test_timedelta_mode(self):
exp = Series(["-1 days", "0 days", "1 days"], dtype="timedelta64[ns]")
ser = Series(["1 days", "-1 days", "0 days"], dtype="timedelta64[ns]")
tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
tm.assert_series_equal(ser.mode(), exp)
exp = Series(["2 min", "1 day"], dtype="timedelta64[ns]")
ser = Series(
["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
dtype="timedelta64[ns]",
)
tm.assert_extension_array_equal(algos.mode(ser.values), exp._values)
tm.assert_series_equal(ser.mode(), exp)
def test_mixed_dtype(self):
exp = Series(["foo"], dtype=object)
ser = Series([1, "foo", "foo"])
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
def test_uint64_overflow(self):
exp = Series([2**63], dtype=np.uint64)
ser = Series([1, 2**63, 2**63], dtype=np.uint64)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
exp = Series([1, 2**63], dtype=np.uint64)
ser = Series([1, 2**63], dtype=np.uint64)
result, _ = algos.mode(ser.values)
tm.assert_numpy_array_equal(result, exp.values)
tm.assert_series_equal(ser.mode(), exp)
def test_categorical(self):
c = Categorical([1, 2])
exp = c
res = Series(c).mode()._values
tm.assert_categorical_equal(res, exp)
c = Categorical([1, "a", "a"])
exp = Categorical(["a"], categories=[1, "a"])
res = Series(c).mode()._values
tm.assert_categorical_equal(res, exp)
c = Categorical([1, 1, 2, 3, 3])
exp = Categorical([1, 3], categories=[1, 2, 3])
res = Series(c).mode()._values
tm.assert_categorical_equal(res, exp)
def test_index(self):
idx = Index([1, 2, 3])
exp = Series([1, 2, 3], dtype=np.int64)
result, _ = algos.mode(idx)
tm.assert_numpy_array_equal(result, exp.values)
idx = Index([1, "a", "a"])
exp = Series(["a"], dtype=object)
result, _ = algos.mode(idx)
tm.assert_numpy_array_equal(result, exp.values)
idx = Index([1, 1, 2, 3, 3])
exp = Series([1, 3], dtype=np.int64)
result, _ = algos.mode(idx)
tm.assert_numpy_array_equal(result, exp.values)
idx = Index(
["1 day", "1 day", "-1 day", "-1 day 2 min", "2 min", "2 min"],
dtype="timedelta64[ns]",
)
with pytest.raises(AttributeError, match="TimedeltaIndex"):
# algos.mode expects Arraylike, does *not* unwrap TimedeltaIndex
algos.mode(idx)
def test_ser_mode_with_name(self):
# GH 46737
ser = Series([1, 1, 3], name="foo")
result = ser.mode()
expected = Series([1], name="foo")
tm.assert_series_equal(result, expected)
| TestMode |
python | kamyu104__LeetCode-Solutions | Python/count-vowels-permutation.py | {
"start": 955,
"end": 1295
} | class ____(object):
def countVowelPermutation(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9 + 7
a, e, i, o, u = 1, 1, 1, 1, 1
for _ in xrange(1, n):
a, e, i, o, u = (e+i+u) % MOD, (a+i) % MOD, (e+o) % MOD, i, (i+o) % MOD
return (a+e+i+o+u) % MOD
| Solution2 |
python | rapidsai__cudf | python/cudf/cudf/core/udf/api.py | {
"start": 111,
"end": 972
} | class ____:
"""
Most of the time, MaskedType as defined in typing.py
combined with the ops defined to operate on them are
enough to fulfill the obligations of DataFrame.apply
However sometimes we need to refer to an instance of
a masked scalar outside the context of a UDF like as
a global variable. To get numba to identify that var
a of type MaskedType and treat it as such we need to
have an actual python class we can tie to MaskedType
This is that class
"""
def __init__(self, value, valid):
self.value = value
self.valid = valid
def pack_return(masked_or_scalar):
# Blank function to give us something for the typing and
# lowering to grab onto. Just a dummy function for us to
# call within kernels that will get replaced later by the
# lowered implementation
pass
| Masked |
python | Textualize__textual | src/textual/screen.py | {
"start": 72301,
"end": 72973
} | class ____(Screen[ScreenResultType]):
"""A screen with bindings that take precedence over the App's key bindings.
The default styling of a modal screen will dim the screen underneath.
"""
DEFAULT_CSS = """
ModalScreen {
layout: vertical;
overflow-y: auto;
background: $background 60%;
&:ansi {
background: transparent;
}
}
"""
def __init__(
self,
name: str | None = None,
id: str | None = None,
classes: str | None = None,
) -> None:
super().__init__(name=name, id=id, classes=classes)
self._modal = True
| ModalScreen |
python | Textualize__textual | src/textual/_animator.py | {
"start": 2544,
"end": 5296
} | class ____(Animation):
obj: object
attribute: str
start_time: float
duration: float
start_value: float | Animatable
end_value: float | Animatable
final_value: object
easing: EasingFunction
on_complete: CallbackType | None = None
level: AnimationLevel = "full"
"""Minimum level required for the animation to take place (inclusive)."""
def __call__(
self, time: float, app_animation_level: AnimationLevel = "full"
) -> bool:
if (
self.duration == 0
or app_animation_level == "none"
or app_animation_level == "basic"
and self.level == "full"
):
setattr(self.obj, self.attribute, self.final_value)
return True
factor = min(1.0, (time - self.start_time) / self.duration)
eased_factor = self.easing(factor)
if factor == 1.0:
value = self.final_value
elif isinstance(self.start_value, Animatable):
assert isinstance(
self.end_value, Animatable
), "end_value must be animatable"
value = self.start_value.blend(self.end_value, eased_factor)
else:
assert isinstance(
self.start_value, (int, float)
), f"`start_value` must be float, not {self.start_value!r}"
assert isinstance(
self.end_value, (int, float)
), f"`end_value` must be float, not {self.end_value!r}"
if self.end_value > self.start_value:
eased_factor = self.easing(factor)
value = (
self.start_value
+ (self.end_value - self.start_value) * eased_factor
)
else:
eased_factor = 1 - self.easing(factor)
value = (
self.end_value + (self.start_value - self.end_value) * eased_factor
)
setattr(self.obj, self.attribute, value)
return factor >= 1
async def stop(self, complete: bool = True) -> None:
"""Stop the animation.
Args:
complete: Flag to say if the animation should be taken to completion.
Note:
[`on_complete`][Animation.on_complete] will be called regardless
of the value provided for `complete`.
"""
if complete:
setattr(self.obj, self.attribute, self.end_value)
await self.invoke_callback()
def __eq__(self, other: object) -> bool:
if isinstance(other, SimpleAnimation):
return (
self.final_value == other.final_value
and self.duration == other.duration
)
return False
| SimpleAnimation |
python | plotly__plotly.py | plotly/graph_objs/barpolar/unselected/_marker.py | {
"start": 233,
"end": 3330
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.unselected"
_path_str = "barpolar.unselected.marker"
_valid_props = {"color", "opacity"}
@property
def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exists.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def opacity(self):
"""
Sets the marker opacity of unselected points, applied only when
a selection exists.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the marker color of unselected points, applied
only when a selection exists.
opacity
Sets the marker opacity of unselected points, applied
only when a selection exists.
"""
def __init__(self, arg=None, color=None, opacity=None, **kwargs):
"""
Construct a new Marker object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.barpolar.unselected.Marker`
color
Sets the marker color of unselected points, applied
only when a selection exists.
opacity
Sets the marker opacity of unselected points, applied
only when a selection exists.
Returns
-------
Marker
"""
super().__init__("marker")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.barpolar.unselected.Marker
constructor must be a dict or
an instance of :class:`plotly.graph_objs.barpolar.unselected.Marker`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("opacity", arg, opacity)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Marker |
python | ray-project__ray | python/ray/tests/test_runtime_env_plugin.py | {
"start": 5175,
"end": 5328
} | class ____(RuntimeEnvPlugin):
name = DUMMY_PLUGIN_NAME
@staticmethod
def validate(runtime_env_dict: dict) -> str:
return 1
| DummyPlugin |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 8569,
"end": 8726
} | class ____(AssignValues):
"""Check the assignment of valued arrays (size 2, UCS4 values)"""
ulen = 2
ucs_value = ucs4_value
| TestAssignValues_2_UCS4 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_dialect.py | {
"start": 2767,
"end": 4532
} | class ____(fixtures.TablesTest):
"""Test basic exception wrapping.
DBAPIs vary a lot in exception behavior so to actually anticipate
specific exceptions from real round trips, we need to be conservative.
"""
run_deletes = "each"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"manual_pk",
metadata,
Column("id", Integer, primary_key=True, autoincrement=False),
Column("data", String(50)),
)
@requirements.duplicate_key_raises_integrity_error
def test_integrity_error(self):
with config.db.connect() as conn:
trans = conn.begin()
conn.execute(
self.tables.manual_pk.insert(), {"id": 1, "data": "d1"}
)
assert_raises(
exc.IntegrityError,
conn.execute,
self.tables.manual_pk.insert(),
{"id": 1, "data": "d1"},
)
trans.rollback()
def test_exception_with_non_ascii(self):
with config.db.connect() as conn:
try:
# try to create an error message that likely has non-ascii
# characters in the DBAPI's message string. unfortunately
# there's no way to make this happen with some drivers like
# mysqlclient, pymysql. this at least does produce a non-
# ascii error message for cx_oracle, psycopg2
conn.execute(select(literal_column("méil")))
assert False
except exc.DBAPIError as err:
err_str = str(err)
assert str(err.orig) in str(err)
assert isinstance(err_str, str)
| ExceptionTest |
python | fastapi__sqlmodel | docs_src/tutorial/one/tutorial009.py | {
"start": 92,
"end": 1541
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
hero = session.get(Hero, 9001)
print("Hero:", hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | ApeWorX__ape | src/ape/managers/converters.py | {
"start": 1549,
"end": 2061
} | class ____(ConverterAPI):
"""
Convert hex values to integers.
**NOTE** If value is a ``str``, it must begin with "0x".
"""
def is_convertible(self, value: Any) -> bool:
# NOTE: Hex int conversion requires 0x prefix to know if it is base 16 or base 10.
return (isinstance(value, str) and is_hex(value) and value.startswith("0x")) or isinstance(
value, bytes
)
def convert(self, value: Any) -> int:
return to_int(HexBytes(value))
| HexIntConverter |
python | ray-project__ray | rllib/algorithms/dreamerv3/torch/models/components/representation_layer.py | {
"start": 644,
"end": 5821
} | class ____(nn.Module):
"""A representation (z-state) generating layer.
The value for z is the result of sampling from a categorical distribution with
shape B x `num_classes`. So a computed z-state consists of `num_categoricals`
one-hot vectors, each of size `num_classes_per_categorical`.
"""
def __init__(
self,
*,
input_size: int,
model_size: str = "XS",
num_categoricals: Optional[int] = None,
num_classes_per_categorical: Optional[int] = None,
):
"""Initializes a RepresentationLayer instance.
Args:
input_size: The input size of the representation layer.
model_size: The "Model Size" used according to [1] Appendinx B.
Use None for manually setting the different parameters.
num_categoricals: Overrides the number of categoricals used in the z-states.
In [1], 32 is used for any model size.
num_classes_per_categorical: Overrides the number of classes within each
categorical used for the z-states. In [1], 32 is used for any model
dimension.
"""
self.num_categoricals = get_num_z_categoricals(
model_size, override=num_categoricals
)
self.num_classes_per_categorical = get_num_z_classes(
model_size, override=num_classes_per_categorical
)
super().__init__()
self.z_generating_layer = nn.Linear(
input_size,
self.num_categoricals * self.num_classes_per_categorical,
bias=True,
)
# Use same initializers as the Author in their JAX repo.
dreamerv3_normal_initializer(self.z_generating_layer.weight)
def forward(self, inputs, return_z_probs=False):
"""Produces a discrete, differentiable z-sample from some 1D input tensor.
Pushes the input_ tensor through our dense layer, which outputs
32(B=num categoricals)*32(c=num classes) logits. Logits are used to:
1) sample stochastically
2) compute probs (via softmax)
3) make sure the sampling step is differentiable (see [2] Algorithm 1):
sample=one_hot(draw(logits))
probs=softmax(logits)
sample=sample + probs - stop_grad(probs)
-> Now sample has the gradients of the probs.
Args:
inputs: The input to our z-generating layer. This might be a) the combined
(concatenated) outputs of the (image?) encoder + the last hidden
deterministic state, or b) the output of the dynamics predictor MLP
network.
return_z_probs: Whether to return the probabilities for the categorical
distribution (in the shape of [B, num_categoricals, num_classes])
as a second return value.
"""
# Compute the logits (no activation) for our `num_categoricals` Categorical
# distributions (with `num_classes_per_categorical` classes each).
logits = self.z_generating_layer(inputs)
# Reshape the logits to [B, num_categoricals, num_classes]
logits = logits.reshape(
-1, self.num_categoricals, self.num_classes_per_categorical
)
# Compute the probs (based on logits) via softmax.
probs = F.softmax(logits, dim=-1)
# Add the unimix weighting (1% uniform) to the probs.
# See [1]: "Unimix categoricals: We parameterize the categorical distributions
# for the world model representations and dynamics, as well as for the actor
# network, as mixtures of 1% uniform and 99% neural network output to ensure
# a minimal amount of probability mass on every class and thus keep log
# probabilities and KL divergences well behaved."
probs = 0.99 * probs + 0.01 * (1.0 / self.num_classes_per_categorical)
# Danijar's code does: distr = [Distr class](logits=torch.log(probs)).
# Not sure why we don't directly use the already available probs instead.
logits = torch.log(probs)
# Create the distribution object using the unimix'd logits.
distribution = torch.distributions.Independent(
torch.distributions.OneHotCategorical(logits=logits),
reinterpreted_batch_ndims=1,
)
# Draw a one-hot sample (B, num_categoricals, num_classes).
sample = distribution.sample()
# Make sure we can take gradients "straight-through" the sampling step
# by adding the probs and subtracting the sg(probs). Note that `sample`
# does not have any gradients as it's the result of a Categorical sample step,
# which is non-differentiable (other than say a Gaussian sample step).
# [1] "The representations are sampled from a vector of softmax distributions
# and we take straight-through gradients through the sampling step."
# [2] Algorithm 1.
differentiable_sample = sample.detach() + probs - probs.detach()
if return_z_probs:
return differentiable_sample, probs
return differentiable_sample
| RepresentationLayer |
python | ray-project__ray | python/ray/serve/tests/common/test_modules.py | {
"start": 1588,
"end": 2173
} | class ____:
def __init__(self, val):
self.val = val
def get(self):
return self.val
def inc(self, inc):
self.val += inc
@serve.deployment
def fn_hello():
return "hello"
@serve.deployment
def fn(val, incr=0):
return val + incr
@serve.deployment
def combine(m1_output, m2_output, kwargs_output=0):
return m1_output + m2_output + kwargs_output
def class_factory():
class MyInlineClass:
def __init__(self, val):
self.val = val
def get(self):
return self.val
return MyInlineClass
| Counter |
python | cython__cython | Cython/Build/Cache.py | {
"start": 1727,
"end": 1945
} | class ____:
language: str = "c"
py_limited_api: bool = False
np_pythran: bool = False
def get_fingerprint(self):
return str((self.language, self.py_limited_api, self.np_pythran))
| FingerprintFlags |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-kibela/llama_index/readers/kibela/base.py | {
"start": 494,
"end": 692
} | class ____(BaseModel, Generic[NodeType]):
nodes: Optional[List[NodeType]] = None
edges: Optional[List[Edge[NodeType]]]
pageInfo: Optional[PageInfo]
totalCount: Optional[int]
| Connection |
python | huggingface__transformers | src/transformers/models/superglue/modeling_superglue.py | {
"start": 19217,
"end": 19587
} | class ____(nn.Module):
def __init__(self, config: SuperGlueConfig) -> None:
super().__init__()
hidden_size = config.hidden_size
self.final_proj = nn.Linear(hidden_size, hidden_size, bias=True)
def forward(self, descriptors: torch.Tensor) -> torch.Tensor:
return self.final_proj(descriptors)
@auto_docstring
| SuperGlueFinalProjection |
python | huggingface__transformers | src/transformers/models/regnet/convert_regnet_to_pytorch.py | {
"start": 4968,
"end": 18420
} | class ____(dict):
"""
A Dictionary with some additional logic to return the correct hugging face RegNet class reference.
"""
def __getitem__(self, x: str) -> Callable[[], nn.Module]:
if "seer" in x and "in1k" not in x:
val = RegNetModel
else:
val = RegNetForImageClassification
return val
def manually_copy_vissl_head(from_state_dict, to_state_dict, keys: list[tuple[str, str]]):
for from_key, to_key in keys:
to_state_dict[to_key] = from_state_dict[from_key].clone()
print(f"Copied key={from_key} to={to_key}")
return to_state_dict
def convert_weight_and_push(
name: str,
from_model_func: Callable[[], nn.Module],
our_model_func: Callable[[], nn.Module],
config: RegNetConfig,
save_directory: Path,
push_to_hub: bool = True,
):
print(f"Converting {name}...")
with torch.no_grad():
from_model, from_state_dict = from_model_func()
our_model = our_model_func(config).eval()
module_transfer = ModuleTransfer(src=from_model, dest=our_model, raise_if_mismatch=False)
x = torch.randn((1, 3, 224, 224))
module_transfer(x)
if from_state_dict is not None:
keys = []
# for seer - in1k finetuned we have to manually copy the head
if "seer" in name and "in1k" in name:
keys = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")]
to_state_dict = manually_copy_vissl_head(from_state_dict, our_model.state_dict(), keys)
our_model.load_state_dict(to_state_dict)
our_outputs = our_model(x, output_hidden_states=True)
our_output = (
our_outputs.logits if isinstance(our_model, RegNetForImageClassification) else our_outputs.last_hidden_state
)
from_output = from_model(x)
from_output = from_output[-1] if isinstance(from_output, list) else from_output
# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
if "seer" in name and "in1k" in name:
our_output = our_outputs.hidden_states[-1]
assert torch.allclose(from_output, our_output), "The model logits don't match the original one."
if push_to_hub:
our_model.push_to_hub(repo_id=name)
size = 224 if "seer" not in name else 384
# we can use the convnext one
image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k", size=size)
image_processor.push_to_hub(repo_id=name)
print(f"Pushed {name}")
def convert_weights_and_push(save_directory: Path, model_name: Optional[str] = None, push_to_hub: bool = True):
filename = "imagenet-1k-id2label.json"
num_labels = 1000
expected_shape = (1, num_labels)
repo_id = "huggingface/label-files"
id2label = json.loads(Path(hf_hub_download(repo_id, filename, repo_type="dataset")).read_text())
id2label = {int(k): v for k, v in id2label.items()}
label2id = {v: k for k, v in id2label.items()}
ImageNetPreTrainedConfig = partial(RegNetConfig, num_labels=num_labels, id2label=id2label, label2id=label2id)
names_to_config = {
"regnet-x-002": ImageNetPreTrainedConfig(
depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type="x"
),
"regnet-x-004": ImageNetPreTrainedConfig(
depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type="x"
),
"regnet-x-006": ImageNetPreTrainedConfig(
depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type="x"
),
"regnet-x-008": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type="x"
),
"regnet-x-016": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type="x"
),
"regnet-x-032": ImageNetPreTrainedConfig(
depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type="x"
),
"regnet-x-040": ImageNetPreTrainedConfig(
depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type="x"
),
"regnet-x-064": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type="x"
),
"regnet-x-080": ImageNetPreTrainedConfig(
depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type="x"
),
"regnet-x-120": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type="x"
),
"regnet-x-160": ImageNetPreTrainedConfig(
depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type="x"
),
"regnet-x-320": ImageNetPreTrainedConfig(
depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type="x"
),
# y variant
"regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8),
"regnet-y-004": ImageNetPreTrainedConfig(
depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8
),
"regnet-y-006": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16
),
"regnet-y-008": ImageNetPreTrainedConfig(
depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16
),
"regnet-y-016": ImageNetPreTrainedConfig(
depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24
),
"regnet-y-032": ImageNetPreTrainedConfig(
depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24
),
"regnet-y-040": ImageNetPreTrainedConfig(
depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64
),
"regnet-y-064": ImageNetPreTrainedConfig(
depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72
),
"regnet-y-080": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56
),
"regnet-y-120": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112
),
"regnet-y-160": ImageNetPreTrainedConfig(
depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112
),
"regnet-y-320": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232
),
# models created by SEER -> https://huggingface.co/papers/2202.08360
"regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232),
"regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328),
"regnet-y-1280-seer": RegNetConfig(
depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264
),
"regnet-y-2560-seer": RegNetConfig(
depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640
),
"regnet-y-10b-seer": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010
),
# finetuned on imagenet
"regnet-y-320-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232
),
"regnet-y-640-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328
),
"regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264
),
"regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig(
depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640
),
"regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010
),
}
names_to_ours_model_map = NameToOurModelFuncMap()
names_to_from_model_map = NameToFromModelFuncMap()
# add seer weights logic
def load_using_classy_vision(checkpoint_url: str, model_func: Callable[[], nn.Module]) -> tuple[nn.Module, dict]:
files = torch.hub.load_state_dict_from_url(checkpoint_url, model_dir=str(save_directory), map_location="cpu")
model = model_func()
# check if we have a head, if yes add it
model_state_dict = files["classy_state_dict"]["base_model"]["model"]
state_dict = model_state_dict["trunk"]
model.load_state_dict(state_dict)
return model.eval(), model_state_dict["heads"]
# pretrained
names_to_from_model_map["regnet-y-320-seer"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch",
lambda: FakeRegNetVisslWrapper(RegNetY32gf()),
)
names_to_from_model_map["regnet-y-640-seer"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch",
lambda: FakeRegNetVisslWrapper(RegNetY64gf()),
)
names_to_from_model_map["regnet-y-1280-seer"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch",
lambda: FakeRegNetVisslWrapper(RegNetY128gf()),
)
names_to_from_model_map["regnet-y-10b-seer"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch",
lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27, group_width=1010, w_0=1744, w_a=620.83, w_m=2.52))
),
)
# IN1K finetuned
names_to_from_model_map["regnet-y-320-seer-in1k"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch",
lambda: FakeRegNetVisslWrapper(RegNetY32gf()),
)
names_to_from_model_map["regnet-y-640-seer-in1k"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch",
lambda: FakeRegNetVisslWrapper(RegNetY64gf()),
)
names_to_from_model_map["regnet-y-1280-seer-in1k"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch",
lambda: FakeRegNetVisslWrapper(RegNetY128gf()),
)
names_to_from_model_map["regnet-y-10b-seer-in1k"] = partial(
load_using_classy_vision,
"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch",
lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27, group_width=1010, w_0=1744, w_a=620.83, w_m=2.52))
),
)
if model_name:
convert_weight_and_push(
model_name,
names_to_from_model_map[model_name],
names_to_ours_model_map[model_name],
names_to_config[model_name],
save_directory,
push_to_hub,
)
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(
model_name,
names_to_from_model_map[model_name],
names_to_ours_model_map[model_name],
config,
save_directory,
push_to_hub,
)
return config, expected_shape
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default=None,
type=str,
help=(
"The name of the model you wish to convert, it must be one of the supported regnet* architecture,"
" currently: regnetx-*, regnety-*. If `None`, all of them will the converted."
),
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=Path,
required=True,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub",
default=True,
type=bool,
required=False,
help="If True, push model and image processor to the hub.",
)
args = parser.parse_args()
pytorch_dump_folder_path: Path = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| NameToOurModelFuncMap |
python | jina-ai__jina | tests/k8s_otel/kind_wrapper.py | {
"start": 306,
"end": 8940
} | class ____:
def __init__(self, kind_cluster: KindCluster, logger: JinaLogger) -> None:
self._log: JinaLogger = logger
self._cluster: KindCluster = kind_cluster
self._cluster.ensure_kubectl()
self._cluster.ensure_kind()
os.environ['KUBECONFIG'] = str(self._cluster.kubeconfig_path)
self._docker_client: DockerClient = docker.from_env()
def create_namespace(self, namespace: str) -> bool:
"""Create a namespace in the kind cluster.
Returns:
bool: True if the namespace was created, False if it already exists.
"""
self._log.info(f'Creating namespace {namespace}')
try:
self._cluster.kubectl('create', 'namespace', namespace)
self._log.info(f'Namespace {namespace} created')
return True
except CalledProcessError as e:
# TODO: How do you get the error message from CalledProcessError?
self._log.info(f'Namespace {namespace} already exists')
return False
def delete_namespace(self, namespace: str) -> bool:
"""Delete a namespace in the kind cluster.
Returns:
bool: True if the namespace was deleted, False if it doesn't exist.
"""
self._log.info(f'Deleting namespace {namespace}')
try:
self._cluster.kubectl('delete', 'namespace', namespace)
self._log.info(f'Namespace {namespace} deleted')
return True
except CalledProcessError as e:
# TODO: How do you get the error message from CalledProcessError?
self._log.info(f"Namespace {namespace} doesn't exists")
return False
def deploy_from_dir(
self, dir: str, namespace: str, timeout_seconds: int = 300
) -> None:
"""
Deploy artifacts from a directory containing the k8s yaml files
Args:
dir: directory containing the k8s yaml files
namespace: namespace to deploy to
timeout_seconds: timeout in seconds. Default is 300 seconds.
"""
self.create_namespace(namespace)
artifacts: str = self._cluster.kubectl("apply", "-Rf", dir, '-n', namespace)
# Wait for deployments to be available
for artifact in artifacts.splitlines():
if artifact.startswith('deployment'):
deployment_name = artifact.split()[0]
self._log.info(f'Awaiting deployment {deployment_name}')
try:
self._cluster.kubectl(
'wait',
'--for=condition=available',
deployment_name,
f"--timeout={timeout_seconds}s",
'-n',
namespace,
)
except CalledProcessError as e:
self._log.error(
f'Error while waiting for deployment {deployment_name}: {e}'
)
self.log_node_summaries(namespace)
self.log_pod_summaries(namespace)
self.log_failing_pods(namespace)
raise e
self._log.info(f'Deployment {deployment_name} ready')
def log_node_summaries(self, namespace: str) -> None:
"""Logs node summaries in a namespace."""
self._log.info(self._cluster.kubectl('get', 'nodes', '-n', namespace))
self._log.info(self._cluster.kubectl('describe', 'nodes', '-n', namespace))
def log_pod_summaries(self, namespace: str) -> None:
"""Logs pod summaries in a namespace."""
self._log.error(self._cluster.kubectl('get', 'pods', '-n', namespace))
self._log.error(self._cluster.kubectl('describe', 'pods', '-n', namespace))
def log_failing_pods(self, namespace: str) -> None:
"""Logs all pods that are not in a running state in a namespace."""
self._log.info(f'Logging failing pods in {namespace}')
pods = self._cluster.kubectl(
'get', 'pods', '-n', namespace, '-o', 'jsonpath={.items[*].metadata.name}'
)
for pod in pods.split():
if (
self._cluster.kubectl(
'get',
'pods',
pod,
'-n',
namespace,
'-o',
'jsonpath={.status.phase}',
)
!= 'Running'
):
self._log.error(self._cluster.kubectl('logs', pod, '-n', namespace))
async def async_deploy_from_dir(
self, dir: str, namespace: str, timeout_seconds: int = 900
) -> None:
"""
Deploy artifacts from a directory containing the k8s yaml files
But wait for the deployments to be ready asynchronously
Args:
dir: directory containing the k8s yaml files
namespace: namespace to deploy to
timeout_seconds: timeout in seconds. Default is 900 seconds.
"""
# TODO: Timeout should be shorter and should async sleep if failed
raise NotImplementedError('Not implemented yet')
def build_and_load_docker_image(self, dir: str, image_name: str, tag: str) -> str:
"""Build and load docker image.
Args:
dir: path to build directory
image_name: name of the image
tag: tag of the image
Returns:
str: image name with tag
"""
self._log.info(f'Building docker image {image_name}:{tag}')
self._docker_client.images.build(path=dir, tag=f'{image_name}:{tag}')
self._log.info(f'Docker image {image_name}:{tag} built')
self.load_docker_image(image_name, tag)
return f'{image_name}:{tag}'
def load_docker_image(self, image_name: str, tag: str) -> str:
"""Load docker image.
Args:
image_name: name of the image
tag: tag of the image
Returns:
str: image name with tag
"""
self._log.info(f'Loading docker image {image_name}:{tag}')
self._cluster.load_docker_image(f'{image_name}:{tag}')
self._log.info(f'Docker image {image_name}:{tag} loaded')
return f'{image_name}:{tag}'
def remove_docker_image(self, image_name: str, tag: str) -> None:
"""Remove docker image.
Args:
image_name: name of the image
tag: tag of the image
"""
self._log.info(f'Removing docker image {image_name}:{tag}')
self._docker_client.images.remove(f'{image_name}:{tag}')
self._log.info(f'Docker image {image_name}:{tag} removed')
@contextmanager
def port_forward(
self,
service_or_pod_name: str,
namespace: str,
svc_port: int,
host_port: int = None,
retries: int = 10,
) -> Generator[int, None, None]:
"""
Run "kubectl port-forward" for the given service/pod.
Args:
service_or_pod_name: name of the service or pod
namespace: namespace of the service or pod
svc_port: service port to forward to
host_port: host port to forward to. If None, a random port will be used.
retries: number of retries to find a free port. Default is 10.
"""
if host_port is None:
host_port = random.randint(5000, 30000)
proc = None
for i in range(retries):
if proc:
proc.kill()
proc = subprocess.Popen(
[
str(self._cluster.kubectl_path),
"port-forward",
service_or_pod_name,
f"{host_port}:{svc_port}",
"-n",
namespace,
],
env={"KUBECONFIG": str(self._cluster.kubeconfig_path)},
)
time.sleep(1)
returncode = proc.poll()
if returncode is not None:
if i >= retries - 1:
raise Exception(
f"kubectl port-forward returned exit code {returncode}"
)
else:
continue
s = socket.socket()
try:
s.connect(("127.0.0.1", host_port))
except:
if i >= retries - 1:
raise
finally:
s.close()
try:
yield host_port
finally:
if proc:
proc.kill()
| KindClusterWrapperV2 |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 58233,
"end": 58448
} | class ____(_TestCopying, __TestCase):
def setUp(self):
self.set = set(["hello"])
super().setUp()
#------------------------------------------------------------------------------
| TestCopyingSingleton |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 349709,
"end": 356170
} | class ____(rv_continuous):
r"""A uniform continuous random variable.
In the standard form, the distribution is uniform on ``[0, 1]``. Using
the parameters ``loc`` and ``scale``, one obtains the uniform distribution
on ``[loc, loc + scale]``.
%(before_notes)s
%(example)s
"""
def _shape_info(self):
return []
def _rvs(self, size=None, random_state=None):
return random_state.uniform(0.0, 1.0, size)
def _pdf(self, x):
return 1.0*(x == x)
def _cdf(self, x):
return x
def _ppf(self, q):
return q
def _stats(self):
return 0.5, 1.0/12, 0, -1.2
def _entropy(self):
return 0.0
@_call_super_mom
def fit(self, data, *args, **kwds):
"""
Maximum likelihood estimate for the location and scale parameters.
`uniform.fit` uses only the following parameters. Because exact
formulas are used, the parameters related to optimization that are
available in the `fit` method of other distributions are ignored
here. The only positional argument accepted is `data`.
Parameters
----------
data : array_like
Data to use in calculating the maximum likelihood estimate.
floc : float, optional
Hold the location parameter fixed to the specified value.
fscale : float, optional
Hold the scale parameter fixed to the specified value.
Returns
-------
loc, scale : float
Maximum likelihood estimates for the location and scale.
Notes
-----
An error is raised if `floc` is given and any values in `data` are
less than `floc`, or if `fscale` is given and `fscale` is less
than ``data.max() - data.min()``. An error is also raised if both
`floc` and `fscale` are given.
Examples
--------
>>> import numpy as np
>>> from scipy.stats import uniform
We'll fit the uniform distribution to `x`:
>>> x = np.array([2, 2.5, 3.1, 9.5, 13.0])
For a uniform distribution MLE, the location is the minimum of the
data, and the scale is the maximum minus the minimum.
>>> loc, scale = uniform.fit(x)
>>> loc
2.0
>>> scale
11.0
If we know the data comes from a uniform distribution where the support
starts at 0, we can use ``floc=0``:
>>> loc, scale = uniform.fit(x, floc=0)
>>> loc
0.0
>>> scale
13.0
Alternatively, if we know the length of the support is 12, we can use
``fscale=12``:
>>> loc, scale = uniform.fit(x, fscale=12)
>>> loc
1.5
>>> scale
12.0
In that last example, the support interval is [1.5, 13.5]. This
solution is not unique. For example, the distribution with ``loc=2``
and ``scale=12`` has the same likelihood as the one above. When
`fscale` is given and it is larger than ``data.max() - data.min()``,
the parameters returned by the `fit` method center the support over
the interval ``[data.min(), data.max()]``.
"""
if len(args) > 0:
raise TypeError("Too many arguments.")
floc = kwds.pop('floc', None)
fscale = kwds.pop('fscale', None)
_remove_optimizer_parameters(kwds)
if floc is not None and fscale is not None:
# This check is for consistency with `rv_continuous.fit`.
raise ValueError("All parameters fixed. There is nothing to "
"optimize.")
data = np.asarray(data)
if not np.isfinite(data).all():
raise ValueError("The data contains non-finite values.")
# MLE for the uniform distribution
# --------------------------------
# The PDF is
#
# f(x, loc, scale) = {1/scale for loc <= x <= loc + scale
# {0 otherwise}
#
# The likelihood function is
# L(x, loc, scale) = (1/scale)**n
# where n is len(x), assuming loc <= x <= loc + scale for all x.
# The log-likelihood is
# l(x, loc, scale) = -n*log(scale)
# The log-likelihood is maximized by making scale as small as possible,
# while keeping loc <= x <= loc + scale. So if neither loc nor scale
# are fixed, the log-likelihood is maximized by choosing
# loc = x.min()
# scale = np.ptp(x)
# If loc is fixed, it must be less than or equal to x.min(), and then
# the scale is
# scale = x.max() - loc
# If scale is fixed, it must not be less than np.ptp(x). If scale is
# greater than np.ptp(x), the solution is not unique. Note that the
# likelihood does not depend on loc, except for the requirement that
# loc <= x <= loc + scale. All choices of loc for which
# x.max() - scale <= loc <= x.min()
# have the same log-likelihood. In this case, we choose loc such that
# the support is centered over the interval [data.min(), data.max()]:
# loc = x.min() = 0.5*(scale - np.ptp(x))
if fscale is None:
# scale is not fixed.
if floc is None:
# loc is not fixed, scale is not fixed.
loc = data.min()
scale = np.ptp(data)
else:
# loc is fixed, scale is not fixed.
loc = floc
scale = data.max() - loc
if data.min() < loc:
raise FitDataError("uniform", lower=loc, upper=loc + scale)
else:
# loc is not fixed, scale is fixed.
ptp = np.ptp(data)
if ptp > fscale:
raise FitUniformFixedScaleDataError(ptp=ptp, fscale=fscale)
# If ptp < fscale, the ML estimate is not unique; see the comments
# above. We choose the distribution for which the support is
# centered over the interval [data.min(), data.max()].
loc = data.min() - 0.5*(fscale - ptp)
scale = fscale
# We expect the return values to be floating point, so ensure it
# by explicitly converting to float.
return float(loc), float(scale)
uniform = uniform_gen(a=0.0, b=1.0, name='uniform')
| uniform_gen |
python | kamyu104__LeetCode-Solutions | Python/keep-multiplying-found-values-by-two.py | {
"start": 42,
"end": 325
} | class ____(object):
def findFinalValue(self, nums, original):
"""
:type nums: List[int]
:type original: int
:rtype: int
"""
lookup = set(nums)
while original in lookup:
original *= 2
return original
| Solution |
python | apache__airflow | providers/discord/src/airflow/providers/discord/operators/discord_webhook.py | {
"start": 1165,
"end": 3824
} | class ____(HttpOperator):
"""
This operator allows you to post messages to Discord using incoming webhooks.
Takes a Discord connection ID with a default relative webhook endpoint. The
default endpoint can be overridden using the webhook_endpoint parameter
(https://discordapp.com/developers/docs/resources/webhook).
Each Discord webhook can be pre-configured to use a specific username and
avatar_url. You can override these defaults in this operator.
:param http_conn_id: Http connection ID with host as "https://discord.com/api/" and
default webhook endpoint in the extra field in the form of
{"webhook_endpoint": "webhooks/{webhook.id}/{webhook.token}"}
:param webhook_endpoint: Discord webhook endpoint in the form of
"webhooks/{webhook.id}/{webhook.token}" (templated)
:param message: The message you want to send to your Discord channel
(max 2000 characters). (templated)
:param username: Override the default username of the webhook. (templated)
:param avatar_url: Override the default avatar of the webhook
:param tts: Is a text-to-speech message
:param proxy: Proxy to use to make the Discord webhook call
"""
template_fields: Sequence[str] = ("username", "message", "webhook_endpoint")
def __init__(
self,
*,
http_conn_id: str | None = None,
webhook_endpoint: str | None = None,
message: str = "",
username: str | None = None,
avatar_url: str | None = None,
tts: bool = False,
proxy: str | None = None,
**kwargs,
) -> None:
super().__init__(endpoint=webhook_endpoint, **kwargs)
if not http_conn_id:
raise AirflowException("No valid Discord http_conn_id supplied.")
self.http_conn_id = http_conn_id
self.webhook_endpoint = webhook_endpoint
self.message = message
self.username = username
self.avatar_url = avatar_url
self.tts = tts
self.proxy = proxy
@property
def hook(self) -> DiscordWebhookHook:
hook = DiscordWebhookHook(
self.http_conn_id,
self.webhook_endpoint,
self.message,
self.username,
self.avatar_url,
self.tts,
self.proxy,
)
return hook
def execute(self, context: Context) -> None:
"""
Call the DiscordWebhookHook to post a message.
:param context: the context object
:return: None
"""
self.hook.execute()
| DiscordWebhookOperator |
python | crytic__slither | slither/core/declarations/function.py | {
"start": 1809,
"end": 2561
} | class ____:
def __init__(
self,
modifier: Union["Contract", "Function"],
entry_point: "Node",
nodes: List["Node"],
) -> None:
self._modifier = modifier
self._entry_point = entry_point
self._nodes = nodes
@property
def modifier(self) -> Union["Contract", "Function"]:
return self._modifier
@property
def entry_point(self) -> "Node":
return self._entry_point
@entry_point.setter
def entry_point(self, entry_point: "Node"):
self._entry_point = entry_point
@property
def nodes(self) -> List["Node"]:
return self._nodes
@nodes.setter
def nodes(self, nodes: List["Node"]):
self._nodes = nodes
| ModifierStatements |
python | getsentry__sentry | src/sentry/relay/config/experimental.py | {
"start": 244,
"end": 464
} | class ____(Exception):
def __init__(self, elapsed: timedelta, timeout: timedelta, *args: object) -> None:
super().__init__(*args)
self._elapsed = elapsed
self._timeout = timeout
| TimeoutException |
python | keras-team__keras | keras/src/layers/rnn/dropout_rnn_cell_test.py | {
"start": 197,
"end": 1465
} | class ____(layers.Layer, DropoutRNNCell):
def __init__(
self, units, dropout=0.5, recurrent_dropout=0.5, seed=None, **kwargs
):
super().__init__(**kwargs)
self.seed = seed
self.seed_generator = backend.random.SeedGenerator(seed)
self.units = units
self.state_size = units
self.dropout = dropout
self.recurrent_dropout = recurrent_dropout
def build(self, input_shape):
self.kernel = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="ones",
name="kernel",
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units),
initializer="ones",
name="recurrent_kernel",
)
def call(self, inputs, states, training=False):
if training:
dp_mask = self.get_dropout_mask(inputs)
inputs = inputs * dp_mask
prev_output = states[0]
h = ops.matmul(inputs, self.kernel)
if training:
rdp_mask = self.get_recurrent_dropout_mask(prev_output)
prev_output = prev_output * rdp_mask
output = h + ops.matmul(prev_output, self.recurrent_kernel)
return output, [output]
| RNNCellWithDropout |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/data_utils.py | {
"start": 20527,
"end": 24503
} | class ____(SequenceEnqueuer):
"""Builds a Enqueuer from a Sequence.
Args:
sequence: A `tf.keras.utils.data_utils.Sequence` object.
use_multiprocessing: use multiprocessing if True, otherwise threading
shuffle: whether to shuffle the data at the beginning of each epoch
"""
def __init__(self, sequence, use_multiprocessing=False, shuffle=False):
super(OrderedEnqueuer, self).__init__(sequence, use_multiprocessing)
self.shuffle = shuffle
def _get_executor_init(self, workers):
"""Gets the Pool initializer for multiprocessing.
Args:
workers: Number of workers.
Returns:
Function, a Function to initialize the pool
"""
def pool_fn(seqs):
pool = get_pool_class(True)(
workers, initializer=init_pool_generator,
initargs=(seqs, None, get_worker_id_queue()))
_DATA_POOLS.add(pool)
return pool
return pool_fn
def _wait_queue(self):
"""Wait for the queue to be empty."""
while True:
time.sleep(0.1)
if self.queue.unfinished_tasks == 0 or self.stop_signal.is_set():
return
def _run(self):
"""Submits request to the executor and queue the `Future` objects."""
sequence = list(range(len(self.sequence)))
self._send_sequence() # Share the initial sequence
while True:
if self.shuffle:
random.shuffle(sequence)
with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor:
for i in sequence:
if self.stop_signal.is_set():
return
self.queue.put(
executor.apply_async(get_index, (self.uid, i)), block=True)
# Done with the current epoch, waiting for the final batches
self._wait_queue()
if self.stop_signal.is_set():
# We're done
return
# Call the internal on epoch end.
self.sequence.on_epoch_end()
self._send_sequence() # Update the pool
def get(self):
"""Creates a generator to extract data from the queue.
Skip the data if it is `None`.
Yields:
The next element in the queue, i.e. a tuple
`(inputs, targets)` or
`(inputs, targets, sample_weights)`.
"""
while self.is_running():
try:
inputs = self.queue.get(block=True, timeout=5).get()
if self.is_running():
self.queue.task_done()
if inputs is not None:
yield inputs
except queue.Empty:
pass
except Exception as e: # pylint: disable=broad-except
self.stop()
raise e
def init_pool_generator(gens, random_seed=None, id_queue=None):
"""Initializer function for pool workers.
Args:
gens: State which should be made available to worker processes.
random_seed: An optional value with which to seed child processes.
id_queue: A multiprocessing Queue of worker ids. This is used to indicate
that a worker process was created by Keras and can be terminated using
the cleanup_all_keras_forkpools utility.
"""
global _SHARED_SEQUENCES
_SHARED_SEQUENCES = gens
worker_proc = multiprocessing.current_process()
# name isn't used for anything, but setting a more descriptive name is helpful
# when diagnosing orphaned processes.
worker_proc.name = 'Keras_worker_{}'.format(worker_proc.name)
if random_seed is not None:
np.random.seed(random_seed + worker_proc.ident)
if id_queue is not None:
# If a worker dies during init, the pool will just create a replacement.
id_queue.put(worker_proc.ident, block=True, timeout=0.1)
def next_sample(uid):
"""Gets the next value from the generator `uid`.
To allow multiple generators to be used at the same time, we use `uid` to
get a specific one. A single generator would cause the validation to
overwrite the training generator.
Args:
uid: int, generator identifier
Returns:
The next value of generator `uid`.
"""
return next(_SHARED_SEQUENCES[uid])
| OrderedEnqueuer |
python | gevent__gevent | src/greentest/3.11/test_selectors.py | {
"start": 1396,
"end": 15137
} | class ____:
def make_socketpair(self):
rd, wr = socketpair()
self.addCleanup(rd.close)
self.addCleanup(wr.close)
return rd, wr
def test_register(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertIsInstance(key, selectors.SelectorKey)
self.assertEqual(key.fileobj, rd)
self.assertEqual(key.fd, rd.fileno())
self.assertEqual(key.events, selectors.EVENT_READ)
self.assertEqual(key.data, "data")
# register an unknown event
self.assertRaises(ValueError, s.register, 0, 999999)
# register an invalid FD
self.assertRaises(ValueError, s.register, -10, selectors.EVENT_READ)
# register twice
self.assertRaises(KeyError, s.register, rd, selectors.EVENT_READ)
# register the same FD, but with a different object
self.assertRaises(KeyError, s.register, rd.fileno(),
selectors.EVENT_READ)
def test_unregister(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
s.unregister(rd)
# unregister an unknown file obj
self.assertRaises(KeyError, s.unregister, 999999)
# unregister twice
self.assertRaises(KeyError, s.unregister, rd)
def test_unregister_after_fd_close(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
r, w = rd.fileno(), wr.fileno()
s.register(r, selectors.EVENT_READ)
s.register(w, selectors.EVENT_WRITE)
rd.close()
wr.close()
s.unregister(r)
s.unregister(w)
@unittest.skipUnless(os.name == 'posix', "requires posix")
def test_unregister_after_fd_close_and_reuse(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
r, w = rd.fileno(), wr.fileno()
s.register(r, selectors.EVENT_READ)
s.register(w, selectors.EVENT_WRITE)
rd2, wr2 = self.make_socketpair()
rd.close()
wr.close()
os.dup2(rd2.fileno(), r)
os.dup2(wr2.fileno(), w)
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
s.unregister(r)
s.unregister(w)
def test_unregister_after_socket_close(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
s.register(wr, selectors.EVENT_WRITE)
rd.close()
wr.close()
s.unregister(rd)
s.unregister(wr)
def test_modify(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
key = s.register(rd, selectors.EVENT_READ)
# modify events
key2 = s.modify(rd, selectors.EVENT_WRITE)
self.assertNotEqual(key.events, key2.events)
self.assertEqual(key2, s.get_key(rd))
s.unregister(rd)
# modify data
d1 = object()
d2 = object()
key = s.register(rd, selectors.EVENT_READ, d1)
key2 = s.modify(rd, selectors.EVENT_READ, d2)
self.assertEqual(key.events, key2.events)
self.assertNotEqual(key.data, key2.data)
self.assertEqual(key2, s.get_key(rd))
self.assertEqual(key2.data, d2)
# modify unknown file obj
self.assertRaises(KeyError, s.modify, 999999, selectors.EVENT_READ)
# modify use a shortcut
d3 = object()
s.register = unittest.mock.Mock()
s.unregister = unittest.mock.Mock()
s.modify(rd, selectors.EVENT_READ, d3)
self.assertFalse(s.register.called)
self.assertFalse(s.unregister.called)
def test_modify_unregister(self):
# Make sure the fd is unregister()ed in case of error on
# modify(): http://bugs.python.org/issue30014
if self.SELECTOR.__name__ == 'EpollSelector':
patch = unittest.mock.patch(
'selectors.EpollSelector._selector_cls')
elif self.SELECTOR.__name__ == 'PollSelector':
patch = unittest.mock.patch(
'selectors.PollSelector._selector_cls')
elif self.SELECTOR.__name__ == 'DevpollSelector':
patch = unittest.mock.patch(
'selectors.DevpollSelector._selector_cls')
else:
raise self.skipTest("")
with patch as m:
m.return_value.modify = unittest.mock.Mock(
side_effect=ZeroDivisionError)
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
self.assertEqual(len(s._map), 1)
with self.assertRaises(ZeroDivisionError):
s.modify(rd, selectors.EVENT_WRITE)
self.assertEqual(len(s._map), 0)
def test_close(self):
s = self.SELECTOR()
self.addCleanup(s.close)
mapping = s.get_map()
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
s.register(wr, selectors.EVENT_WRITE)
s.close()
self.assertRaises(RuntimeError, s.get_key, rd)
self.assertRaises(RuntimeError, s.get_key, wr)
self.assertRaises(KeyError, mapping.__getitem__, rd)
self.assertRaises(KeyError, mapping.__getitem__, wr)
def test_get_key(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertEqual(key, s.get_key(rd))
# unknown file obj
self.assertRaises(KeyError, s.get_key, 999999)
def test_get_map(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
keys = s.get_map()
self.assertFalse(keys)
self.assertEqual(len(keys), 0)
self.assertEqual(list(keys), [])
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertIn(rd, keys)
self.assertEqual(key, keys[rd])
self.assertEqual(len(keys), 1)
self.assertEqual(list(keys), [rd.fileno()])
self.assertEqual(list(keys.values()), [key])
# unknown file obj
with self.assertRaises(KeyError):
keys[999999]
# Read-only mapping
with self.assertRaises(TypeError):
del keys[rd]
def test_select(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
wr_key = s.register(wr, selectors.EVENT_WRITE)
result = s.select()
for key, events in result:
self.assertTrue(isinstance(key, selectors.SelectorKey))
self.assertTrue(events)
self.assertFalse(events & ~(selectors.EVENT_READ |
selectors.EVENT_WRITE))
self.assertEqual([(wr_key, selectors.EVENT_WRITE)], result)
def test_select_read_write(self):
# gh-110038: when a file descriptor is registered for both read and
# write, the two events must be seen on a single call to select().
s = self.SELECTOR()
self.addCleanup(s.close)
sock1, sock2 = self.make_socketpair()
sock2.send(b"foo")
my_key = s.register(sock1, selectors.EVENT_READ | selectors.EVENT_WRITE)
seen_read, seen_write = False, False
result = s.select()
# We get the read and write either in the same result entry or in two
# distinct entries with the same key.
self.assertLessEqual(len(result), 2)
for key, events in result:
self.assertTrue(isinstance(key, selectors.SelectorKey))
self.assertEqual(key, my_key)
self.assertFalse(events & ~(selectors.EVENT_READ |
selectors.EVENT_WRITE))
if events & selectors.EVENT_READ:
self.assertFalse(seen_read)
seen_read = True
if events & selectors.EVENT_WRITE:
self.assertFalse(seen_write)
seen_write = True
self.assertTrue(seen_read)
self.assertTrue(seen_write)
def test_context_manager(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
with s as sel:
sel.register(rd, selectors.EVENT_READ)
sel.register(wr, selectors.EVENT_WRITE)
self.assertRaises(RuntimeError, s.get_key, rd)
self.assertRaises(RuntimeError, s.get_key, wr)
def test_fileno(self):
s = self.SELECTOR()
self.addCleanup(s.close)
if hasattr(s, 'fileno'):
fd = s.fileno()
self.assertTrue(isinstance(fd, int))
self.assertGreaterEqual(fd, 0)
def test_selector(self):
s = self.SELECTOR()
self.addCleanup(s.close)
NUM_SOCKETS = 12
MSG = b" This is a test."
MSG_LEN = len(MSG)
readers = []
writers = []
r2w = {}
w2r = {}
for i in range(NUM_SOCKETS):
rd, wr = self.make_socketpair()
s.register(rd, selectors.EVENT_READ)
s.register(wr, selectors.EVENT_WRITE)
readers.append(rd)
writers.append(wr)
r2w[rd] = wr
w2r[wr] = rd
bufs = []
while writers:
ready = s.select()
ready_writers = find_ready_matching(ready, selectors.EVENT_WRITE)
if not ready_writers:
self.fail("no sockets ready for writing")
wr = random.choice(ready_writers)
wr.send(MSG)
for i in range(10):
ready = s.select()
ready_readers = find_ready_matching(ready,
selectors.EVENT_READ)
if ready_readers:
break
# there might be a delay between the write to the write end and
# the read end is reported ready
sleep(0.1)
else:
self.fail("no sockets ready for reading")
self.assertEqual([w2r[wr]], ready_readers)
rd = ready_readers[0]
buf = rd.recv(MSG_LEN)
self.assertEqual(len(buf), MSG_LEN)
bufs.append(buf)
s.unregister(r2w[rd])
s.unregister(rd)
writers.remove(r2w[rd])
self.assertEqual(bufs, [MSG] * NUM_SOCKETS)
@unittest.skipIf(sys.platform == 'win32',
'select.select() cannot be used with empty fd sets')
def test_empty_select(self):
# Issue #23009: Make sure EpollSelector.select() works when no FD is
# registered.
s = self.SELECTOR()
self.addCleanup(s.close)
self.assertEqual(s.select(timeout=0), [])
def test_timeout(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
s.register(wr, selectors.EVENT_WRITE)
t = time()
self.assertEqual(1, len(s.select(0)))
self.assertEqual(1, len(s.select(-1)))
self.assertLess(time() - t, 0.5)
s.unregister(wr)
s.register(rd, selectors.EVENT_READ)
t = time()
self.assertFalse(s.select(0))
self.assertFalse(s.select(-1))
self.assertLess(time() - t, 0.5)
t0 = time()
self.assertFalse(s.select(1))
t1 = time()
dt = t1 - t0
# Tolerate 2.0 seconds for very slow buildbots
self.assertTrue(0.8 <= dt <= 2.0, dt)
@unittest.skipUnless(hasattr(signal, "alarm"),
"signal.alarm() required for this test")
def test_select_interrupt_exc(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
class InterruptSelect(Exception):
pass
def handler(*args):
raise InterruptSelect
orig_alrm_handler = signal.signal(signal.SIGALRM, handler)
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
try:
signal.alarm(1)
s.register(rd, selectors.EVENT_READ)
t = time()
# select() is interrupted by a signal which raises an exception
with self.assertRaises(InterruptSelect):
s.select(30)
# select() was interrupted before the timeout of 30 seconds
self.assertLess(time() - t, 5.0)
finally:
signal.alarm(0)
@unittest.skipUnless(hasattr(signal, "alarm"),
"signal.alarm() required for this test")
def test_select_interrupt_noraise(self):
s = self.SELECTOR()
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
orig_alrm_handler = signal.signal(signal.SIGALRM, lambda *args: None)
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
try:
signal.alarm(1)
s.register(rd, selectors.EVENT_READ)
t = time()
# select() is interrupted by a signal, but the signal handler doesn't
# raise an exception, so select() should by retries with a recomputed
# timeout
self.assertFalse(s.select(1.5))
self.assertGreaterEqual(time() - t, 1.0)
finally:
signal.alarm(0)
| BaseSelectorTestCase |
python | dagster-io__dagster | python_modules/libraries/dagster-celery/dagster_celery/executor.py | {
"start": 5017,
"end": 6548
} | class ____(Executor):
def __init__(
self,
retries,
broker=None,
backend=None,
include=None,
config_source=None,
):
self.broker = check.opt_str_param(broker, "broker", default=broker_url)
self.backend = check.opt_str_param(backend, "backend", default=result_backend)
self.include = check.opt_list_param(include, "include", of_type=str)
self.config_source = dict_wrapper(
dict(DEFAULT_CONFIG, **check.opt_dict_param(config_source, "config_source"))
)
self._retries = check.inst_param(retries, "retries", RetryMode)
@property
def retries(self):
return self._retries
def execute(self, plan_context, execution_plan):
from dagster_celery.core_execution_loop import core_celery_execution_loop
return core_celery_execution_loop(
plan_context, execution_plan, step_execution_fn=_submit_task
)
@staticmethod
def for_cli(broker=None, backend=None, include=None, config_source=None):
return CeleryExecutor(
retries=RetryMode(RetryMode.DISABLED),
broker=broker,
backend=backend,
include=include,
config_source=config_source,
)
def app_args(self):
return {
"broker": self.broker,
"backend": self.backend,
"include": self.include,
"config_source": self.config_source,
"retries": self.retries,
}
| CeleryExecutor |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 4537,
"end": 5115
} | class ____(schedule):
def now_func():
return datetime.now(timezone.utc)
def __init__(self, is_due, next_run_at, nowfun=now_func):
self._is_due = is_due
self._next_run_at = next_run_at
self.run_every = timedelta(seconds=1)
self.nowfun = nowfun
self.default_now = self.nowfun
def is_due(self, last_run_at):
return self._is_due, self._next_run_at
always_due = mocked_schedule(True, 1)
always_pending = mocked_schedule(False, 1)
always_pending_left_10_milliseconds = mocked_schedule(False, 0.01)
| mocked_schedule |
python | django__django | tests/generic_views/views.py | {
"start": 4299,
"end": 4469
} | class ____(generic.UpdateView):
success_url = "/list/authors/"
fields = "__all__"
def get_object(self):
return Author.objects.get(pk=1)
| OneAuthorUpdate |
python | huggingface__transformers | tests/utils/test_configuration_utils.py | {
"start": 5452,
"end": 15575
} | class ____(unittest.TestCase):
def test_config_from_string(self):
c = GPT2Config()
# attempt to modify each of int/float/bool/str config records and verify they were updated
n_embd = c.n_embd + 1 # int
resid_pdrop = c.resid_pdrop + 1.0 # float
scale_attn_weights = not c.scale_attn_weights # bool
summary_type = c.summary_type + "foo" # str
c.update_from_string(
f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}"
)
self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd")
self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop")
self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights")
self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type")
def test_config_common_kwargs_is_complete(self):
base_config = PreTrainedConfig()
missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to add in config_common_kwargs above.
self.assertListEqual(
missing_keys,
[
"_output_attentions",
"is_encoder_decoder",
"_name_or_path",
"_commit_hash",
"_attn_implementation_internal",
"transformers_version",
],
)
keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)]
if len(keys_with_defaults) > 0:
raise ValueError(
"The following keys are set with the default values in"
" `test_configuration_common.config_common_kwargs` pick another value for them:"
f" {', '.join(keys_with_defaults)}."
)
def test_nested_config_load_from_dict(self):
config = AutoConfig.from_pretrained(
"hf-internal-testing/tiny-random-CLIPModel", text_config={"num_hidden_layers": 2}
)
self.assertNotIsInstance(config.text_config, dict)
self.assertEqual(config.text_config.__class__.__name__, "CLIPTextConfig")
def test_from_pretrained_subfolder(self):
config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder")
self.assertIsNotNone(config)
config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder", subfolder="bert")
self.assertIsNotNone(config)
def test_cached_files_are_used_when_internet_is_down(self):
# A mock response for an HTTP head request to emulate server down
response_mock = mock.Mock()
response_mock.status_code = 500
response_mock.headers = {}
response_mock.raise_for_status.side_effect = httpx.HTTPStatusError(
"failed", request=mock.Mock(), response=mock.Mock()
)
response_mock.json.return_value = {}
# Download this model to make sure it's in the cache.
_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch("httpx.Client.request", return_value=response_mock) as mock_head:
_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
# This check we did call the fake head request
mock_head.assert_called()
def test_local_versioning(self):
configuration = AutoConfig.from_pretrained("google-bert/bert-base-cased")
configuration.configuration_files = ["config.4.0.0.json"]
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(tmp_dir)
configuration.hidden_size = 2
json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w"))
# This should pick the new configuration file as the version of Transformers is > 4.0.0
new_configuration = AutoConfig.from_pretrained(tmp_dir)
self.assertEqual(new_configuration.hidden_size, 2)
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
configuration.configuration_files = ["config.42.0.0.json"]
configuration.hidden_size = 768
configuration.save_pretrained(tmp_dir)
shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json"))
new_configuration = AutoConfig.from_pretrained(tmp_dir)
self.assertEqual(new_configuration.hidden_size, 768)
def test_repo_versioning_before(self):
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
repo = "hf-internal-testing/test-two-configs"
import transformers as new_transformers
new_transformers.configuration_utils.__version__ = "v4.0.0"
new_configuration, kwargs = new_transformers.models.auto.AutoConfig.from_pretrained(
repo, return_unused_kwargs=True
)
self.assertEqual(new_configuration.hidden_size, 2)
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(kwargs, {})
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
old_transformers.configuration_utils.__version__ = "v3.0.0"
old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo)
self.assertEqual(old_configuration.hidden_size, 768)
def test_saving_config_with_custom_generation_kwargs_raises_error(self):
config = BertConfig()
config.min_length = 3 # `min_length = 3` is a non-default generation kwarg
with tempfile.TemporaryDirectory() as tmp_dir:
with self.assertRaises(ValueError):
config.save_pretrained(tmp_dir)
def test_get_non_default_generation_parameters(self):
config = BertConfig()
self.assertFalse(len(config._get_non_default_generation_parameters()) > 0)
config.min_length = 3
self.assertTrue(len(config._get_non_default_generation_parameters()) > 0)
config.min_length = 0 # `min_length = 0` is a default generation kwarg
self.assertFalse(len(config._get_non_default_generation_parameters()) > 0)
def test_loading_config_do_not_raise_future_warnings(self):
"""Regression test for https://github.com/huggingface/transformers/issues/31002."""
# Loading config should not raise a FutureWarning. It was the case before.
with warnings.catch_warnings():
warnings.simplefilter("error")
PreTrainedConfig.from_pretrained("bert-base-uncased")
def test_get_text_config(self):
"""Tests the `get_text_config` method."""
# 1. model with only text input -> returns the original config instance
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
self.assertEqual(config.get_text_config(), config)
self.assertEqual(config.get_text_config(decoder=True), config)
# 2. composite model (VLM) -> returns the text component
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-LlavaForConditionalGeneration")
self.assertEqual(config.get_text_config(), config.text_config)
self.assertEqual(config.get_text_config(decoder=True), config.text_config)
# 3. ! corner case! : composite model whose sub-config is an old composite model (should behave as above)
config = Florence2Config()
self.assertEqual(config.get_text_config(), config.text_config)
self.assertEqual(config.get_text_config(decoder=True), config.text_config)
# 4. old composite model -> may remove components based on the `decoder` or `encoder` argument
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-bart")
self.assertEqual(config.get_text_config(), config)
# both encoder_layers and decoder_layers exist
self.assertTrue(getattr(config, "encoder_layers", None) is not None)
self.assertTrue(getattr(config, "decoder_layers", None) is not None)
decoder_config = config.get_text_config(decoder=True)
self.assertNotEqual(decoder_config, config)
self.assertEqual(decoder_config.num_hidden_layers, config.decoder_layers)
self.assertTrue(getattr(decoder_config, "encoder_layers", None) is None) # encoder_layers is removed
encoder_config = config.get_text_config(encoder=True)
self.assertNotEqual(encoder_config, config)
self.assertEqual(encoder_config.num_hidden_layers, config.encoder_layers)
self.assertTrue(getattr(encoder_config, "decoder_layers", None) is None) # decoder_layers is removed
@require_torch
def test_bc_torch_dtype(self):
import torch
config = PreTrainedConfig(dtype="bfloat16")
self.assertEqual(config.dtype, torch.bfloat16)
config = PreTrainedConfig(torch_dtype="bfloat16")
self.assertEqual(config.dtype, torch.bfloat16)
# Check that if we pass both, `dtype` is used
config = PreTrainedConfig(dtype="bfloat16", torch_dtype="float32")
self.assertEqual(config.dtype, torch.bfloat16)
with tempfile.TemporaryDirectory() as tmpdirname:
config.save_pretrained(tmpdirname)
config = PreTrainedConfig.from_pretrained(tmpdirname)
self.assertEqual(config.dtype, torch.bfloat16)
config = PreTrainedConfig.from_pretrained(tmpdirname, dtype="float32")
self.assertEqual(config.dtype, "float32")
config = PreTrainedConfig.from_pretrained(tmpdirname, torch_dtype="float32")
self.assertEqual(config.dtype, "float32")
| ConfigTestUtils |
python | eventlet__eventlet | eventlet/green/http/client.py | {
"start": 57772,
"end": 58275
} | class ____(HTTPException):
def __init__(self, partial, expected=None):
self.args = partial,
self.partial = partial
self.expected = expected
def __repr__(self):
if self.expected is not None:
e = ', %i more expected' % self.expected
else:
e = ''
return '%s(%i bytes read%s)' % (self.__class__.__name__,
len(self.partial), e)
def __str__(self):
return repr(self)
| IncompleteRead |
python | marshmallow-code__marshmallow | src/marshmallow/validate.py | {
"start": 7429,
"end": 9311
} | class ____(Validator):
"""Validate an email address.
:param error: Error message to raise in case of a validation error. Can be
interpolated with `{input}`.
"""
USER_REGEX = re.compile(
r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*\Z" # dot-atom
# quoted-string
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
r'|\\[\001-\011\013\014\016-\177])*"\Z)',
re.IGNORECASE | re.UNICODE,
)
DOMAIN_REGEX = re.compile(
# domain
r"(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+"
r"(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\Z"
# literal form, ipv4 address (SMTP 4.1.3)
r"|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)"
r"(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]\Z",
re.IGNORECASE | re.UNICODE,
)
DOMAIN_WHITELIST = ("localhost",)
default_message = "Not a valid email address."
def __init__(self, *, error: str | None = None):
self.error: str = error or self.default_message
def _format_error(self, value: str) -> str:
return self.error.format(input=value)
def __call__(self, value: str) -> str:
message = self._format_error(value)
if not value or "@" not in value:
raise ValidationError(message)
user_part, domain_part = value.rsplit("@", 1)
if not self.USER_REGEX.match(user_part):
raise ValidationError(message)
if domain_part not in self.DOMAIN_WHITELIST:
if not self.DOMAIN_REGEX.match(domain_part):
try:
domain_part = domain_part.encode("idna").decode("ascii")
except UnicodeError:
pass
else:
if self.DOMAIN_REGEX.match(domain_part):
return value
raise ValidationError(message)
return value
| Email |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 9380,
"end": 9565
} | class ____(Web3RPCError):
"""
Raised when a transaction receipt is not yet available due to transaction indexing
still being in progress.
"""
| TransactionIndexingInProgress |
python | ray-project__ray | python/ray/data/_internal/execution/operators/hash_shuffle.py | {
"start": 59707,
"end": 63130
} | class ____:
"""Actor handling of the assigned partitions during hash-shuffle operation
NOTE: This actor might have ``max_concurrency`` > 1 (depending on the number of
assigned partitions, and has to be thread-safe!
"""
def __init__(
self,
aggregator_id: int,
target_partition_ids: List[int],
agg_factory: StatefulShuffleAggregationFactory,
data_context: DataContext,
):
self._lock = threading.Lock()
self._agg: StatefulShuffleAggregation = agg_factory(
aggregator_id, target_partition_ids
)
self._data_context = data_context
def submit(self, input_seq_id: int, partition_id: int, partition_shard: Block):
with self._lock:
self._agg.accept(input_seq_id, partition_id, partition_shard)
def finalize(
self, partition_id: int
) -> Generator[Union[Block, "BlockMetadataWithSchema"], None, None]:
with self._lock:
exec_stats_builder = BlockExecStats.builder()
# Finalize given partition id
block = self._agg.finalize(partition_id)
exec_stats = exec_stats_builder.build()
# Clear any remaining state (to release resources)
self._agg.clear(partition_id)
target_max_block_size = self._data_context.target_max_block_size
# None means the user wants to preserve the block distribution,
# so we do not break the block down further.
if target_max_block_size is not None:
# Creating a block output buffer per partition finalize task because
# retrying finalize tasks cause stateful output_bufer to be
# fragmented (ie, adding duplicated blocks, calling finalize 2x)
output_buffer = BlockOutputBuffer(
output_block_size_option=OutputBlockSizeOption(
target_max_block_size=target_max_block_size
)
)
output_buffer.add_block(block)
output_buffer.finalize()
while output_buffer.has_next():
block = output_buffer.next()
yield block
yield BlockMetadataWithSchema.from_block(block, stats=exec_stats)
else:
yield block
yield BlockMetadataWithSchema.from_block(block, stats=exec_stats)
def _get_total_cluster_resources() -> ExecutionResources:
"""Retrieves total available cluster resources:
1. If AutoscalerV2 is used, then corresponding max configured resources of
the corresponding `ClusterConfig` is returned.
2. In case `ClusterConfig` is not set then falls back to currently available
cluster resources (retrieved by `ray.cluster_resources()`)
"""
return ExecutionResources.from_resource_dict(
ray._private.state.state.get_max_resources_from_cluster_config()
or ray.cluster_resources()
)
# TODO rebase on generic operator output estimation
def _try_estimate_output_bytes(
input_logical_ops: List[LogicalOperator],
) -> Optional[int]:
inferred_op_output_bytes = [
op.infer_metadata().size_bytes for op in input_logical_ops
]
# Return sum of input ops estimated output byte sizes,
# if all are well defined
if all(nbs is not None for nbs in inferred_op_output_bytes):
return sum(inferred_op_output_bytes)
return None
| HashShuffleAggregator |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 206405,
"end": 206969
} | class ____(TestCase):
def test_basic(self) -> None:
result = list(islice(mi.iterate(lambda x: 2 * x, start=1), 10))
expected = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
self.assertEqual(result, expected)
def test_func_controls_iteration_stop(self) -> None:
def func(num):
if num > 100:
raise StopIteration
return num * 2
result = list(islice(mi.iterate(func, start=1), 10))
expected = [1, 2, 4, 8, 16, 32, 64, 128]
self.assertEqual(result, expected)
| IterateTests |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 86724,
"end": 89670
} | class ____(SingleContinuousDistribution):
_argnames = ('mean', 'shape')
@property
def set(self):
return Interval(0, oo)
@staticmethod
def check(mean, shape):
_value_check(shape > 0, "Shape parameter must be positive")
_value_check(mean > 0, "Mean must be positive")
def pdf(self, x):
mu, s = self.mean, self.shape
return exp(-s*(x - mu)**2 / (2*x*mu**2)) * sqrt(s/(2*pi*x**3))
def _cdf(self, x):
from sympy.stats import cdf
mu, s = self.mean, self.shape
stdNormalcdf = cdf(Normal('x', 0, 1))
first_term = stdNormalcdf(sqrt(s/x) * ((x/mu) - S.One))
second_term = exp(2*s/mu) * stdNormalcdf(-sqrt(s/x)*(x/mu + S.One))
return first_term + second_term
def _characteristic_function(self, t):
mu, s = self.mean, self.shape
return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*I*t)/s)))
def _moment_generating_function(self, t):
mu, s = self.mean, self.shape
return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*t)/s)))
def GaussianInverse(name, mean, shape):
r"""
Create a continuous random variable with an Inverse Gaussian distribution.
Inverse Gaussian distribution is also known as Wald distribution.
Explanation
===========
The density of the Inverse Gaussian distribution is given by
.. math::
f(x) := \sqrt{\frac{\lambda}{2\pi x^3}} e^{-\frac{\lambda(x-\mu)^2}{2x\mu^2}}
Parameters
==========
mu :
Positive number representing the mean.
lambda :
Positive number representing the shape parameter.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import GaussianInverse, density, E, std, skewness
>>> from sympy import Symbol, pprint
>>> mu = Symbol("mu", positive=True)
>>> lamda = Symbol("lambda", positive=True)
>>> z = Symbol("z", positive=True)
>>> X = GaussianInverse("x", mu, lamda)
>>> D = density(X)(z)
>>> pprint(D, use_unicode=False)
2
-lambda*(-mu + z)
-------------------
2
___ ________ 2*mu *z
\/ 2 *\/ lambda *e
-------------------------------------
____ 3/2
2*\/ pi *z
>>> E(X)
mu
>>> std(X).expand()
mu**(3/2)/sqrt(lambda)
>>> skewness(X).expand()
3*sqrt(mu)/sqrt(lambda)
References
==========
.. [1] https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
.. [2] https://mathworld.wolfram.com/InverseGaussianDistribution.html
"""
return rv(name, GaussianInverseDistribution, (mean, shape))
Wald = GaussianInverse
#-------------------------------------------------------------------------------
# Pareto distribution ----------------------------------------------------------
| GaussianInverseDistribution |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_aggregate_metrics/column_min.py | {
"start": 499,
"end": 999
} | class ____(ColumnAggregateMetricProvider):
metric_name = "column.min"
value_keys = ()
@column_aggregate_value(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.min()
@column_aggregate_partial(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(cls, column, **kwargs):
return sa.func.min(column)
@column_aggregate_partial(engine=SparkDFExecutionEngine)
def _spark(cls, column, **kwargs):
return F.min(column)
| ColumnMin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_logging_format/G004.py | {
"start": 1050,
"end": 1350
} | class ____:
def __init__(self, name: str):
self.name = name
logging.info(f"No changes made to {file_path.name}.")
user = "tron"
balance = 123.45
logging.error(f"Error {404}: User {user} has insufficient balance ${balance:.2f}")
import logging
x = 1
logging.error(f"{x} -> %s", x)
| FilePath |
python | google__jax | jax/_src/debugging.py | {
"start": 1907,
"end": 2005
} | class ____(effects.Effect):
__str__ = lambda self: "Debug"
debug_effect = DebugEffect()
| DebugEffect |
python | coleifer__peewee | playhouse/apsw_ext.py | {
"start": 1044,
"end": 4642
} | class ____(SqliteExtDatabase):
server_version = tuple(int(i) for i in apsw.sqlitelibversion().split('.'))
def __init__(self, database, **kwargs):
self._modules = {}
super(APSWDatabase, self).__init__(database, **kwargs)
def register_module(self, mod_name, mod_inst):
self._modules[mod_name] = mod_inst
if not self.is_closed():
self.connection().createmodule(mod_name, mod_inst)
def unregister_module(self, mod_name):
del(self._modules[mod_name])
def _connect(self):
conn = apsw.Connection(self.database, **self.connect_params)
if self._timeout is not None:
conn.setbusytimeout(self._timeout * 1000)
try:
self._add_conn_hooks(conn)
except:
conn.close()
raise
return conn
def _add_conn_hooks(self, conn):
super(APSWDatabase, self)._add_conn_hooks(conn)
self._load_modules(conn) # APSW-only.
def _load_modules(self, conn):
for mod_name, mod_inst in self._modules.items():
conn.createmodule(mod_name, mod_inst)
return conn
def _load_aggregates(self, conn):
for name, (klass, num_params) in self._aggregates.items():
def make_aggregate():
return (klass(), klass.step, klass.finalize)
conn.createaggregatefunction(name, make_aggregate)
def _load_collations(self, conn):
for name, fn in self._collations.items():
conn.createcollation(name, fn)
def _load_functions(self, conn):
for name, (fn, num_params, deterministic) in self._functions.items():
args = (deterministic,) if deterministic else ()
conn.createscalarfunction(name, fn, num_params, *args)
def _load_extensions(self, conn):
conn.enableloadextension(True)
for extension in self._extensions:
conn.loadextension(extension)
def load_extension(self, extension):
self._extensions.add(extension)
if not self.is_closed():
conn = self.connection()
conn.enableloadextension(True)
conn.loadextension(extension)
def last_insert_id(self, cursor, query_type=None):
if not self.returning_clause:
return cursor.getconnection().last_insert_rowid()
elif query_type == Insert.SIMPLE:
try:
return cursor[0][0]
except (AttributeError, IndexError, TypeError):
pass
return cursor
def rows_affected(self, cursor):
try:
return cursor.getconnection().changes()
except AttributeError:
return cursor.cursor.getconnection().changes() # RETURNING query.
def begin(self, lock_type='deferred'):
self.cursor().execute('begin %s;' % lock_type)
def commit(self):
with __exception_wrapper__:
curs = self.cursor()
if curs.getconnection().getautocommit():
return False
curs.execute('commit;')
return True
def rollback(self):
with __exception_wrapper__:
curs = self.cursor()
if curs.getconnection().getautocommit():
return False
curs.execute('rollback;')
return True
def execute_sql(self, sql, params=None):
logger.debug((sql, params))
with __exception_wrapper__:
cursor = self.cursor()
cursor.execute(sql, params or ())
return cursor
def nh(s, v):
if v is not None:
return str(v)
| APSWDatabase |
python | doocs__leetcode | solution/2400-2499/2425.Bitwise XOR of All Pairings/Solution.py | {
"start": 0,
"end": 280
} | class ____:
def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int:
ans = 0
if len(nums2) & 1:
for v in nums1:
ans ^= v
if len(nums1) & 1:
for v in nums2:
ans ^= v
return ans
| Solution |
python | bokeh__bokeh | src/bokeh/core/has_props.py | {
"start": 6019,
"end": 8914
} | class ____(type):
''' Specialize the construction of |HasProps| classes.
This class is a `metaclass`_ for |HasProps| that is responsible for
creating and adding the ``PropertyDescriptor`` instances that delegate
validation and serialization to |Property| attributes.
.. _metaclass: https://docs.python.org/3/reference/datamodel.html#metaclasses
'''
__properties__: dict[str, Property[Any]]
__overridden_defaults__: dict[str, Any]
__themed_values__: dict[str, Any]
def __new__(cls, class_name: str, bases: tuple[type, ...], class_dict: dict[str, Any]):
'''
'''
overridden_defaults = _overridden_defaults(class_dict)
generators = _generators(class_dict)
properties = {}
for name, generator in generators.items():
descriptors = generator.make_descriptors(name)
for descriptor in descriptors:
name = descriptor.name
if name in class_dict:
raise RuntimeError(f"Two property generators both created {class_name}.{name}")
class_dict[name] = descriptor
properties[name] = descriptor.property
class_dict["__properties__"] = properties
class_dict["__overridden_defaults__"] = overridden_defaults
return super().__new__(cls, class_name, bases, class_dict)
def __init__(cls, class_name: str, bases: tuple[type, ...], _) -> None:
# HasProps itself may not have any properties defined
if class_name == "HasProps":
return
# Check for improperly redeclared a Property attribute.
base_properties: dict[str, Any] = {}
for base in (x for x in bases if issubclass(x, HasProps)):
base_properties.update(base.properties(_with_props=True))
own_properties = {k: v for k, v in cls.__dict__.items() if isinstance(v, PropertyDescriptor)}
redeclared = own_properties.keys() & base_properties.keys()
if redeclared:
from ..util.warnings import warn
warn(f"Properties {redeclared!r} in class {cls.__name__} were previously declared on a parent "
"class. It never makes sense to do this. Redundant properties should be deleted here, or on "
"the parent class. Override() can be used to change a default value of a base class property.",
RuntimeWarning)
# Check for no-op Overrides
unused_overrides = cls.__overridden_defaults__.keys() - cls.properties(_with_props=True).keys()
if unused_overrides:
from ..util.warnings import warn
warn(f"Overrides of {unused_overrides} in class {cls.__name__} does not override anything.", RuntimeWarning)
@property
def model_class_reverse_map(cls) -> dict[str, type[HasProps]]:
return _default_resolver.known_models
| MetaHasProps |
python | sympy__sympy | sympy/polys/polyoptions.py | {
"start": 1728,
"end": 6861
} | class ____(dict):
"""
Options manager for polynomial manipulation module.
Examples
========
>>> from sympy.polys.polyoptions import Options
>>> from sympy.polys.polyoptions import build_options
>>> from sympy.abc import x, y, z
>>> Options((x, y, z), {'domain': 'ZZ'})
{'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
>>> build_options((x, y, z), {'domain': 'ZZ'})
{'auto': False, 'domain': ZZ, 'gens': (x, y, z)}
**Options**
* Expand --- boolean option
* Gens --- option
* Wrt --- option
* Sort --- option
* Order --- option
* Field --- boolean option
* Greedy --- boolean option
* Domain --- option
* Split --- boolean option
* Gaussian --- boolean option
* Extension --- option
* Modulus --- option
* Symmetric --- boolean option
* Strict --- boolean option
**Flags**
* Auto --- boolean flag
* Frac --- boolean flag
* Formal --- boolean flag
* Polys --- boolean flag
* Include --- boolean flag
* All --- boolean flag
* Gen --- flag
* Series --- boolean flag
"""
__order__ = None
__options__: dict[str, type[Option]] = {}
gens: tuple[Expr, ...]
domain: sympy.polys.domains.Domain
def __init__(self, gens, args, flags=None, strict=False):
dict.__init__(self)
if gens and args.get('gens', ()):
raise OptionError(
"both '*gens' and keyword argument 'gens' supplied")
elif gens:
args = dict(args)
args['gens'] = gens
defaults = args.pop('defaults', {})
def preprocess_options(args):
for option, value in args.items():
try:
cls = self.__options__[option]
except KeyError:
raise OptionError("'%s' is not a valid option" % option)
if issubclass(cls, Flag):
if flags is None or option not in flags:
if strict:
raise OptionError("'%s' flag is not allowed in this context" % option)
if value is not None:
self[option] = cls.preprocess(value)
preprocess_options(args)
for key in dict(defaults):
if key in self:
del defaults[key]
else:
for option in self.keys():
cls = self.__options__[option]
if key in cls.excludes:
del defaults[key]
break
preprocess_options(defaults)
for option in self.keys():
cls = self.__options__[option]
for require_option in cls.requires:
if self.get(require_option) is None:
raise OptionError("'%s' option is only allowed together with '%s'" % (option, require_option))
for exclude_option in cls.excludes:
if self.get(exclude_option) is not None:
raise OptionError("'%s' option is not allowed together with '%s'" % (option, exclude_option))
for option in self.__order__:
self.__options__[option].postprocess(self)
@classmethod
def _init_dependencies_order(cls):
"""Resolve the order of options' processing. """
if cls.__order__ is None:
vertices, edges = [], set()
for name, option in cls.__options__.items():
vertices.append(name)
edges.update((_name, name) for _name in option.after)
edges.update((name, _name) for _name in option.before)
try:
cls.__order__ = topological_sort((vertices, list(edges)))
except ValueError:
raise RuntimeError(
"cycle detected in sympy.polys options framework")
def clone(self, updates={}):
"""Clone ``self`` and update specified options. """
obj = dict.__new__(self.__class__)
for option, value in self.items():
obj[option] = value
for option, value in updates.items():
obj[option] = value
return obj
def __setattr__(self, attr, value):
if attr in self.__options__:
self[attr] = value
else:
super().__setattr__(attr, value)
@property
def args(self):
args = {}
for option, value in self.items():
if value is not None and option != 'gens':
cls = self.__options__[option]
if not issubclass(cls, Flag):
args[option] = value
return args
@property
def options(self):
options = {}
for option, cls in self.__options__.items():
if not issubclass(cls, Flag):
options[option] = getattr(self, option)
return options
@property
def flags(self):
flags = {}
for option, cls in self.__options__.items():
if issubclass(cls, Flag):
flags[option] = getattr(self, option)
return flags
| Options |
python | walkccc__LeetCode | solutions/1472. Design Browser History/1472-3.py | {
"start": 107,
"end": 642
} | class ____:
def __init__(self, homepage: str):
self.curr = Node(homepage)
def visit(self, url: str) -> None:
self.curr.next = Node(url)
self.curr.next.prev = self.curr
self.curr = self.curr.next
def back(self, steps: int) -> str:
while self.curr.prev and steps > 0:
self.curr = self.curr.prev
steps -= 1
return self.curr.url
def forward(self, steps: int) -> str:
while self.curr.next and steps > 0:
self.curr = self.curr.next
steps -= 1
return self.curr.url
| BrowserHistory |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-octoai/llama_index/llms/octoai/base.py | {
"start": 1129,
"end": 7201
} | class ____(LLM):
model: str = Field(
default=DEFAULT_OCTOAI_MODEL, description="The model to use with OctoAI"
)
temperature: float = Field(
default=DEFAULT_TEMPERATURE,
description="The temperature to use during generation.",
ge=0.0,
le=1.0,
)
max_tokens: Optional[int] = Field(
description="The maximum number of tokens to generate.",
gt=0,
)
additional_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Additional kwargs for the OctoAI SDK."
)
def __init__(
self,
model: str = DEFAULT_OCTOAI_MODEL,
temperature: float = DEFAULT_TEMPERATURE,
max_tokens: Optional[int] = None,
timeout: int = 120,
token: Optional[str] = None,
additional_kwargs: Optional[Dict[str, Any]] = None,
callback_manager: Optional[CallbackManager] = None,
# base class
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[MessagesToPromptCallable] = None,
completion_to_prompt: Optional[CompletionToPromptCallable] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
output_parser: Optional[BaseOutputParser] = None,
) -> None:
additional_kwargs = additional_kwargs or {}
callback_manager = callback_manager or CallbackManager([])
super().__init__(
callback_manager=callback_manager,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
output_parser=output_parser,
model=model,
temperature=temperature,
max_tokens=max_tokens,
additional_kwargs=additional_kwargs,
)
token = get_from_param_or_env("token", token, "OCTOAI_TOKEN", "")
if not token:
raise ValueError(
"You must provide an API token to use OctoAI. "
"You can either pass it in as an argument or set it `OCTOAI_TOKEN`."
"To generate a token in your OctoAI account settings: https://octoai.cloud/settings`."
)
try:
self._client = Client(api_key=token, timeout=timeout)
except ImportError as err:
raise ImportError(
"Could not import OctoAI python package. "
"Please install it with `pip install octoai-sdk`."
) from err
@property
def metadata(self) -> LLMMetadata:
"""Get LLM metadata."""
return LLMMetadata(
context_window=octoai_modelname_to_contextsize(self.model),
num_output=self.max_tokens or -1,
is_chat_model=True,
model_name=self.model,
)
@property
def _model_kwargs(self) -> Dict[str, Any]:
base_kwargs = {
"model": self.model,
"temperature": self.temperature,
}
if self.max_tokens:
base_kwargs["max_tokens"] = self.max_tokens
return {
**base_kwargs,
**self.additional_kwargs,
}
def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
return {
**self._model_kwargs,
**kwargs,
}
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
response = self._client.text_gen.create_chat_completion(
messages=to_octoai_messages(messages), **self._get_all_kwargs(**kwargs)
)
return ChatResponse(
message=ChatMessage(
role=MessageRole.ASSISTANT, content=response.choices[0].message.content
),
raw=dict(response),
)
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
streaming_response = self._client.text_gen.create_chat_completion_stream(
messages=to_octoai_messages(messages),
**self._get_all_kwargs(**kwargs),
)
def gen() -> ChatResponseGen:
content = ""
role = MessageRole.ASSISTANT
for completion in streaming_response:
content_delta = completion.choices[0].delta.content
if content_delta is None:
continue
content += content_delta
yield ChatResponse(
message=ChatMessage(role=role, content=content),
delta=content_delta,
raw=completion,
)
return gen()
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
complete_fn = chat_to_completion_decorator(self.chat)
return complete_fn(prompt, **kwargs)
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
stream_complete_fn = stream_chat_to_completion_decorator(self.stream_chat)
return stream_complete_fn(prompt, **kwargs)
# ===== Async Endpoints =====
@llm_chat_callback()
async def achat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponse:
raise NotImplementedError
@llm_chat_callback()
async def astream_chat(
self,
messages: Sequence[ChatMessage],
**kwargs: Any,
) -> ChatResponseAsyncGen:
raise NotImplementedError
@llm_completion_callback()
async def acomplete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
raise NotImplementedError
@llm_completion_callback()
async def astream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseAsyncGen:
raise NotImplementedError
| OctoAI |
python | doocs__leetcode | solution/1400-1499/1447.Simplified Fractions/Solution.py | {
"start": 0,
"end": 226
} | class ____:
def simplifiedFractions(self, n: int) -> List[str]:
return [
f'{i}/{j}'
for i in range(1, n)
for j in range(i + 1, n + 1)
if gcd(i, j) == 1
]
| Solution |
python | walkccc__LeetCode | solutions/3070. Count Submatrices with Top-Left Element and Sum Less Than k/3070.py | {
"start": 0,
"end": 489
} | class ____:
def countSubmatrices(self, grid: list[list[int]], k: int) -> int:
m = len(grid)
n = len(grid[0])
ans = 0
# prefix[i][j] := the sum of matrix[0..i)[0..j)
prefix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
prefix[i + 1][j + 1] = (grid[i][j] + prefix[i][j + 1] +
prefix[i + 1][j] - prefix[i][j])
if prefix[i + 1][j + 1] <= k:
ans += 1
return ans
| Solution |
python | getsentry__sentry | tests/sentry/flags/test_audit_log_presenter.py | {
"start": 988,
"end": 2363
} | class ____(APITestCase):
endpoint = "sentry-api-0-flag-hooks"
def test_audit_log_presenter_flush(self) -> None:
with self.options(
{
"flags:options-audit-log-is-enabled": True,
"flags:options-audit-log-organization-id": self.organization.id,
}
):
presenter = AuditLogPresenter("", dry_run=False)
presenter.set("a", True)
presenter.flush()
assert FlagAuditLogModel.objects.count() == 1
flag = FlagAuditLogModel.objects.first()
assert flag is not None
assert flag.action == ACTION_MAP["created"]
assert flag.flag == "a"
assert flag.created_by == "internal"
assert flag.created_by_type == CREATED_BY_TYPE_MAP["name"]
assert flag.organization_id == self.organization.id
assert flag.tags == {"value": True}
def test_audit_log_presenter_flush_dry_run(self) -> None:
with self.options(
{
"flags:options-audit-log-is-enabled": True,
"flags:options-audit-log-organization-id": self.organization.id,
}
):
presenter = AuditLogPresenter("", dry_run=True)
presenter.set("a", True)
presenter.flush()
assert FlagAuditLogModel.objects.count() == 0
| AuditLogPresenterFunctionalTestCase |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 610351,
"end": 611988
} | class ____(CoercionNode):
def __init__(self, arg, dst_type, env):
if arg.type.is_complex:
arg = arg.coerce_to_simple(env)
self.type = dst_type
CoercionNode.__init__(self, arg)
dst_type.create_declaration_utility_code(env)
def calculate_result_code(self):
if self.arg.type.is_complex:
real_part = self.arg.type.real_code(self.arg.result())
imag_part = self.arg.type.imag_code(self.arg.result())
else:
real_part = self.arg.result()
imag_part = "0"
return "%s(%s, %s)" % (
self.type.from_parts,
real_part,
imag_part)
def generate_result_code(self, code):
pass
def analyse_types(self, env):
return self
def coerce_from_soft_complex(arg, dst_type, env):
from .UtilNodes import HasNoGilNode
cfunc_type = PyrexTypes.CFuncType(
PyrexTypes.c_double_type,
[ PyrexTypes.CFuncTypeArg("value", PyrexTypes.soft_complex_type, None),
PyrexTypes.CFuncTypeArg("have_gil", PyrexTypes.c_bint_type, None) ],
exception_value=-1,
exception_check=True,
nogil=True # We can acquire the GIL internally on failure
)
call = PythonCapiCallNode(
arg.pos,
"__Pyx_SoftComplexToDouble",
cfunc_type,
utility_code = UtilityCode.load_cached("SoftComplexToDouble", "Complex.c"),
args = [arg, HasNoGilNode(arg.pos)],
)
call = call.analyse_types(env)
if call.type != dst_type:
call = call.coerce_to(dst_type, env)
return call
| CoerceToComplexNode |
python | gevent__gevent | src/greentest/3.9/test_signal.py | {
"start": 47197,
"end": 48098
} | class ____(unittest.TestCase):
def test_sigint(self):
with self.assertRaises(KeyboardInterrupt):
signal.raise_signal(signal.SIGINT)
@unittest.skipIf(sys.platform != "win32", "Windows specific test")
def test_invalid_argument(self):
try:
SIGHUP = 1 # not supported on win32
signal.raise_signal(SIGHUP)
self.fail("OSError (Invalid argument) expected")
except OSError as e:
if e.errno == errno.EINVAL:
pass
else:
raise
def test_handler(self):
is_ok = False
def handler(a, b):
nonlocal is_ok
is_ok = True
old_signal = signal.signal(signal.SIGINT, handler)
self.addCleanup(signal.signal, signal.SIGINT, old_signal)
signal.raise_signal(signal.SIGINT)
self.assertTrue(is_ok)
| RaiseSignalTest |
python | huggingface__transformers | tests/models/ministral/test_modeling_ministral.py | {
"start": 1416,
"end": 2240
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = MinistralModelTester
# TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146
def is_pipeline_test_to_skip(
self,
pipeline_test_case_name,
config_class,
model_architecture,
tokenizer_name,
image_processor_name,
feature_extractor_name,
processor_name,
):
return True
@require_flash_attn
@require_torch_accelerator
@pytest.mark.flash_attn_test
@slow
def test_flash_attn_2_inference_equivalence_right_padding(self):
self.skipTest(reason="Ministral flash attention does not support right padding")
@require_torch
| MinistralModelTest |
python | keras-team__keras | keras/src/layers/preprocessing/pipeline.py | {
"start": 202,
"end": 2533
} | class ____(Layer):
"""Applies a series of layers to an input.
This class is useful to build a preprocessing pipeline,
in particular an image data augmentation pipeline.
Compared to a `Sequential` model, `Pipeline` features
a few important differences:
- It's not a `Model`, just a plain layer.
- When the layers in the pipeline are compatible
with `tf.data`, the pipeline will also
remain `tf.data` compatible. That is to say,
the pipeline will not attempt to convert
its inputs to backend-native tensors
when in a tf.data context (unlike a `Sequential`
model).
Example:
```python
from keras import layers
preprocessing_pipeline = layers.Pipeline([
layers.AutoContrast(),
layers.RandomZoom(0.2),
layers.RandomRotation(0.2),
])
# `ds` is a tf.data.Dataset
preprocessed_ds = ds.map(
preprocessing_pipeline,
num_parallel_calls=4,
)
```
"""
def __init__(self, layers, name=None):
super().__init__(name=name)
self._pipeline_layers = layers
self._convert_input_args = False
self._allow_non_tensor_positional_args = True
@property
def layers(self):
return self._pipeline_layers
def call(self, inputs, training=True, mask=None):
for layer in self._pipeline_layers:
kwargs = {}
if layer._call_has_mask_arg:
kwargs["mask"] = mask
if layer._call_has_training_arg and training is not None:
kwargs["training"] = training
outputs = layer(inputs, **kwargs)
inputs = outputs
def _get_mask_from_keras_tensor(kt):
return getattr(kt, "_keras_mask", None)
mask = tree.map_structure(_get_mask_from_keras_tensor, outputs)
return outputs
@classmethod
def from_config(cls, config):
config["layers"] = [
serialization_lib.deserialize_keras_object(x)
for x in config["layers"]
]
return cls(**config)
def get_config(self):
config = {
"layers": serialization_lib.serialize_keras_object(
self._pipeline_layers
),
"name": self.name,
}
return config
| Pipeline |
python | scipy__scipy | scipy/signal/_ltisys.py | {
"start": 22729,
"end": 25312
} | class ____(TransferFunction, lti):
r"""
Continuous-time Linear Time Invariant system in transfer function form.
Represents the system as the transfer function
:math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j`, where
:math:`b` are elements of the numerator `num`, :math:`a` are elements of
the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
Continuous-time `TransferFunction` systems inherit additional
functionality from the `lti` class.
Parameters
----------
*system: arguments
The `TransferFunction` class can be instantiated with 1 or 2
arguments. The following gives the number of input arguments and their
interpretation:
* 1: `lti` system: (`StateSpace`, `TransferFunction` or
`ZerosPolesGain`)
* 2: array_like: (numerator, denominator)
See Also
--------
ZerosPolesGain, StateSpace, lti
tf2ss, tf2zpk, tf2sos
Notes
-----
Changing the value of properties that are not part of the
`TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
state-space matrices) is very inefficient and may lead to numerical
inaccuracies. It is better to convert to the specific system
representation first. For example, call ``sys = sys.to_ss()`` before
accessing/changing the A, B, C, D system matrices.
If (numerator, denominator) is passed in for ``*system``, coefficients
for both the numerator and denominator should be specified in descending
exponent order (e.g. ``s^2 + 3s + 5`` would be represented as
``[1, 3, 5]``)
Examples
--------
Construct the transfer function
:math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`:
>>> from scipy import signal
>>> num = [1, 3, 3]
>>> den = [1, 2, 1]
>>> signal.TransferFunction(num, den)
TransferFunctionContinuous(
array([ 1., 3., 3.]),
array([ 1., 2., 1.]),
dt: None
)
"""
def to_discrete(self, dt, method='zoh', alpha=None):
"""
Returns the discretized `TransferFunction` system.
Parameters: See `cont2discrete` for details.
Returns
-------
sys: instance of `dlti` and `StateSpace`
"""
return TransferFunction(*cont2discrete((self.num, self.den),
dt,
method=method,
alpha=alpha)[:-1],
dt=dt)
| TransferFunctionContinuous |
python | wandb__wandb | wandb/vendor/pygments/lexers/esoteric.py | {
"start": 4885,
"end": 7096
} | class ____(RegexLexer):
"""
Basic lexer for
`CapDL <https://ssrg.nicta.com.au/publications/nictaabstracts/Kuz_KLW_10.abstract.pml>`_.
The source of the primary tool that reads such specifications is available
at https://github.com/seL4/capdl/tree/master/capDL-tool. Note that this
lexer only supports a subset of the grammar. For example, identifiers can
shadow type names, but these instances are currently incorrectly
highlighted as types. Supporting this would need a stateful lexer that is
considered unnecessarily complex for now.
.. versionadded:: 2.2
"""
name = 'CapDL'
aliases = ['capdl']
filenames = ['*.cdl']
tokens = {
'root': [
# C pre-processor directive
(r'^\s*#.*\n', Comment.Preproc),
# Whitespace, comments
(r'\s+', Text),
(r'/\*(.|\n)*?\*/', Comment),
(r'(//|--).*\n', Comment),
(r'[<>\[(){},:;=\]]', Punctuation),
(r'\.\.', Punctuation),
(words(('arch', 'arm11', 'caps', 'child_of', 'ia32', 'irq', 'maps',
'objects'), suffix=r'\b'), Keyword),
(words(('aep', 'asid_pool', 'cnode', 'ep', 'frame', 'io_device',
'io_ports', 'io_pt', 'notification', 'pd', 'pt', 'tcb',
'ut', 'vcpu'), suffix=r'\b'), Keyword.Type),
# Properties
(words(('asid', 'addr', 'badge', 'cached', 'dom', 'domainID', 'elf',
'fault_ep', 'G', 'guard', 'guard_size', 'init', 'ip',
'prio', 'sp', 'R', 'RG', 'RX', 'RW', 'RWG', 'RWX', 'W',
'WG', 'WX', 'level', 'masked', 'master_reply', 'paddr',
'ports', 'reply', 'uncached'), suffix=r'\b'),
Keyword.Reserved),
# Literals
(r'0[xX][\da-fA-F]+', Number.Hex),
(r'\d+(\.\d+)?(k|M)?', Number),
(words(('bits',), suffix=r'\b'), Number),
(words(('cspace', 'vspace', 'reply_slot', 'caller_slot',
'ipc_buffer_slot'), suffix=r'\b'), Number),
# Identifiers
(r'[a-zA-Z_][-@\.\w]*', Name),
],
}
| CapDLLexer |
python | wandb__wandb | wandb/sdk/internal/context.py | {
"start": 188,
"end": 893
} | class ____:
_cancel_event: threading.Event
# TODO(debug_context) add debug setting to enable this
# _debug_record: Optional[Record]
def __init__(self) -> None:
self._cancel_event = threading.Event()
# TODO(debug_context) see above
# self._debug_record = None
def cancel(self) -> None:
self._cancel_event.set()
@property
def cancel_event(self) -> threading.Event:
return self._cancel_event
def context_id_from_record(record: Record) -> str:
context_id = record.control.mailbox_slot
return context_id
def context_id_from_result(result: Result) -> str:
context_id = result.control.mailbox_slot
return context_id
| Context |
python | getsentry__sentry | tests/sentry/dynamic_sampling/tasks/helpers/test_sample_rate.py | {
"start": 301,
"end": 1582
} | class ____(BaseMetricsLayerTestCase, TestCase, SnubaTestCase):
@with_feature(["organizations:dynamic-sampling", "organizations:dynamic-sampling-custom"])
def test_get_org_sample_rate_from_target_sample_rate(self) -> None:
org1 = self.create_organization("test-org")
OrganizationOption.objects.create(
organization=org1, key="sentry:target_sample_rate", value=0.5
)
sample_rate, success = get_org_sample_rate(org1.id, None)
assert success
assert sample_rate == 0.5
@with_feature(["organizations:dynamic-sampling", "organizations:dynamic-sampling-custom"])
def test_get_org_sample_rate_from_target_sample_rate_missing(self) -> None:
org1 = self.create_organization("test-org")
sample_rate, success = get_org_sample_rate(org1.id, None)
assert not success
assert sample_rate == 1.0
@with_feature(["organizations:dynamic-sampling", "organizations:dynamic-sampling-custom"])
def test_get_org_sample_rate_from_target_sample_rate_missing_default(self) -> None:
org1 = self.create_organization("test-org")
sample_rate, success = get_org_sample_rate(org1.id, 0.7)
assert not success
assert sample_rate == 0.7
| PrioritiseProjectsSnubaQueryTest |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_process_runner.py | {
"start": 45167,
"end": 45834
} | class ____(RuntimeError):
"""An error that indicates there is at least one subprocess timing out.
When this is raised, a namedtuple object representing the multi-process run
result can be retrieved by
`tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s
`mpr_result` attribute. See
`tf.__internal__.distribute.multi_process_runner.run` for more information.
"""
def __init__(self, msg, mpr_result):
super(SubprocessTimeoutError, self).__init__(msg)
self.mpr_result = mpr_result
@tf_export('__internal__.distribute.multi_process_runner'
'.UnexpectedSubprocessExitError',
v1=[])
| SubprocessTimeoutError |
python | getsentry__sentry | src/sentry/integrations/gitlab/integration.py | {
"start": 11825,
"end": 13489
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
if "goback" in request.GET:
pipeline.state.step_index = 0
return pipeline.current_step()
if request.method == "POST":
form = InstallationForm(request.POST)
if form.is_valid():
form_data = form.cleaned_data
pipeline.bind_state("installation_data", form_data)
pipeline.bind_state(
"oauth_config_information",
{
"access_token_url": "{}/oauth/token".format(form_data.get("url")),
"authorize_url": "{}/oauth/authorize".format(form_data.get("url")),
"client_id": form_data.get("client_id"),
"client_secret": form_data.get("client_secret"),
"verify_ssl": form_data.get("verify_ssl"),
},
)
pipeline.get_logger().info(
"gitlab.setup.installation-config-view.success",
extra={
"base_url": form_data.get("url"),
"client_id": form_data.get("client_id"),
"verify_ssl": form_data.get("verify_ssl"),
},
)
return pipeline.next_step()
else:
form = InstallationForm()
return render_to_response(
template="sentry/integrations/gitlab-config.html",
context={"form": form},
request=request,
)
| InstallationConfigView |
python | scrapy__scrapy | tests/test_downloader_handler_twisted_http2.py | {
"start": 7050,
"end": 7158
} | class ____(
H2DownloadHandlerMixin, TestHttpsInvalidDNSPatternBase
):
pass
| TestHttps2InvalidDNSPattern |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 20543,
"end": 23925
} | class ____(Initializer):
"""Initializer that generates a truncated normal distribution.
These values are similar to values from a `random_normal_initializer`
except that values more than two standard deviations from the mean
are discarded and re-drawn. This is the recommended initializer for
neural network weights and filters.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values to
generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the random
values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer. Only floating point types are supported.
@compatibility(TF2)
Although it is a legacy `compat.v1` API, this symbol is compatible with eager
execution and `tf.function`.
To switch to TF2, switch to using either
`tf.initializers.truncated_normal` or `tf.keras.initializers.TruncatedNormal`
(neither from `compat.v1`) and
pass the dtype when calling the initializer. Keep in mind that
the default stddev and the behavior of fixed seeds have changed.
#### Structural Mapping to TF2
Before:
```python
initializer = tf.compat.v1.truncated_normal_initializer(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```python
initializer = tf.initializers.truncated_normal(
mean=mean,
seed=seed,
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| :-------------------- | :-------------- | :------------------------- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | Default changes from 1.0 to 0.05 |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 native api only takes it |
: : : as a `__call__` arg, not a constructor arg. :
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
@end_compatibility
"""
@deprecated_args(None,
"Call initializer instance with the dtype argument instead "
"of passing it to the constructor", "dtype")
def __init__(self, mean=0.0, stddev=1.0, seed=None, dtype=dtypes.float32):
self.mean = mean
self.stddev = stddev
self.seed = seed
self.dtype = _assert_float_dtype(dtypes.as_dtype(dtype))
def __call__(self, shape, dtype=None, partition_info=None):
if dtype is None:
dtype = self.dtype
return random_ops.truncated_normal(
shape, self.mean, self.stddev, dtype, seed=self.seed)
def get_config(self):
return {
"mean": self.mean,
"stddev": self.stddev,
"seed": self.seed,
"dtype": self.dtype.name
}
@tf_export(v1=[
"initializers.uniform_unit_scaling", "uniform_unit_scaling_initializer"
])
@deprecation.deprecated_endpoints("uniform_unit_scaling_initializer",
"initializers.uniform_unit_scaling")
| TruncatedNormal |
python | scrapy__scrapy | scrapy/http/cookies.py | {
"start": 712,
"end": 4370
} | class ____:
def __init__(
self,
policy: CookiePolicy | None = None,
check_expired_frequency: int = 10000,
):
self.policy: CookiePolicy = policy or DefaultCookiePolicy()
self.jar: _CookieJar = _CookieJar(self.policy)
self.jar._cookies_lock = _DummyLock() # type: ignore[attr-defined]
self.check_expired_frequency: int = check_expired_frequency
self.processed: int = 0
def extract_cookies(self, response: Response, request: Request) -> None:
wreq = WrappedRequest(request)
wrsp = WrappedResponse(response)
self.jar.extract_cookies(wrsp, wreq) # type: ignore[arg-type]
def add_cookie_header(self, request: Request) -> None:
wreq = WrappedRequest(request)
self.policy._now = self.jar._now = int(time.time()) # type: ignore[attr-defined]
# the cookiejar implementation iterates through all domains
# instead we restrict to potential matches on the domain
req_host = urlparse_cached(request).hostname
if not req_host:
return
if not IPV4_RE.search(req_host):
hosts = potential_domain_matches(req_host)
if "." not in req_host:
hosts += [req_host + ".local"]
else:
hosts = [req_host]
cookies = []
for host in hosts:
if host in self.jar._cookies: # type: ignore[attr-defined]
cookies += self.jar._cookies_for_domain(host, wreq) # type: ignore[attr-defined]
attrs = self.jar._cookie_attrs(cookies) # type: ignore[attr-defined]
if attrs and not wreq.has_header("Cookie"):
wreq.add_unredirected_header("Cookie", "; ".join(attrs))
self.processed += 1
if self.processed % self.check_expired_frequency == 0:
# This is still quite inefficient for large number of cookies
self.jar.clear_expired_cookies()
@property
def _cookies(self) -> dict[str, dict[str, dict[str, Cookie]]]:
return self.jar._cookies # type: ignore[attr-defined,no-any-return]
def clear_session_cookies(self) -> None:
return self.jar.clear_session_cookies()
def clear(
self,
domain: str | None = None,
path: str | None = None,
name: str | None = None,
) -> None:
self.jar.clear(domain, path, name)
def __iter__(self) -> Iterator[Cookie]:
return iter(self.jar)
def __len__(self) -> int:
return len(self.jar)
def set_policy(self, pol: CookiePolicy) -> None:
self.jar.set_policy(pol)
def make_cookies(self, response: Response, request: Request) -> Sequence[Cookie]:
wreq = WrappedRequest(request)
wrsp = WrappedResponse(response)
return self.jar.make_cookies(wrsp, wreq) # type: ignore[arg-type]
def set_cookie(self, cookie: Cookie) -> None:
self.jar.set_cookie(cookie)
def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None:
self.jar.set_cookie_if_ok(cookie, WrappedRequest(request)) # type: ignore[arg-type]
def potential_domain_matches(domain: str) -> list[str]:
"""Potential domain matches for a cookie
>>> potential_domain_matches('www.example.com')
['www.example.com', 'example.com', '.www.example.com', '.example.com']
"""
matches = [domain]
try:
start = domain.index(".") + 1
end = domain.rindex(".")
while start < end:
matches.append(domain[start:])
start = domain.index(".", start) + 1
except ValueError:
pass
return matches + ["." + d for d in matches]
| CookieJar |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 11018,
"end": 11597
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
| MobileBertIntermediate |
python | walkccc__LeetCode | solutions/2361. Minimum Costs Using the Train Line/2361.py | {
"start": 0,
"end": 615
} | class ____:
def minimumCosts(
self,
regular: list[int],
express: list[int],
expressCost: int,
) -> list[int]:
n = len(regular)
ans = [0] * n
# the minimum cost to reach the current stop in a regular route
dpReg = 0
# the minimum cost to reach the current stop in an express route
dpExp = expressCost
for i in range(n):
prevReg = dpReg
prevExp = dpExp
dpReg = min(prevReg + regular[i], prevExp + 0 + regular[i])
dpExp = min(prevReg + expressCost + express[i], prevExp + express[i])
ans[i] = min(dpReg, dpExp)
return ans
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.