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 | apache__airflow | task-sdk/src/airflow/sdk/bases/operator.py | {
"start": 6984,
"end": 14205
} | class ____:
"""A descriptor that guards against ``.partial`` being called on Task objects."""
class_method: ClassMethodDescriptorType | None = None
def __get__(
self, obj: BaseOperator, cls: type[BaseOperator] | None = None
) -> Callable[..., OperatorPartial]:
# Call this "partial" so it looks nicer in stack traces.
def partial(**kwargs):
raise TypeError("partial can only be called on Operator classes, not Tasks themselves")
if obj is not None:
return partial
return self.class_method.__get__(cls, cls)
OPERATOR_DEFAULTS: dict[str, Any] = {
"allow_nested_operators": True,
"depends_on_past": False,
"email_on_failure": True,
"email_on_retry": True,
"execution_timeout": DEFAULT_TASK_EXECUTION_TIMEOUT,
# "executor": DEFAULT_EXECUTOR,
"executor_config": {},
"ignore_first_depends_on_past": DEFAULT_IGNORE_FIRST_DEPENDS_ON_PAST,
"inlets": [],
"map_index_template": None,
"on_execute_callback": [],
"on_failure_callback": [],
"on_retry_callback": [],
"on_skipped_callback": [],
"on_success_callback": [],
"outlets": [],
"owner": DEFAULT_OWNER,
"pool_slots": DEFAULT_POOL_SLOTS,
"priority_weight": DEFAULT_PRIORITY_WEIGHT,
"queue": DEFAULT_QUEUE,
"retries": DEFAULT_RETRIES,
"retry_delay": DEFAULT_RETRY_DELAY,
"retry_exponential_backoff": 0,
"trigger_rule": DEFAULT_TRIGGER_RULE,
"wait_for_past_depends_before_skipping": DEFAULT_WAIT_FOR_PAST_DEPENDS_BEFORE_SKIPPING,
"wait_for_downstream": False,
"weight_rule": DEFAULT_WEIGHT_RULE,
}
# This is what handles the actual mapping.
if TYPE_CHECKING:
def partial(
operator_class: type[BaseOperator],
*,
task_id: str,
dag: DAG | None = None,
task_group: TaskGroup | None = None,
start_date: datetime = ...,
end_date: datetime = ...,
owner: str = ...,
email: None | str | Iterable[str] = ...,
params: collections.abc.MutableMapping | None = None,
resources: dict[str, Any] | None = ...,
trigger_rule: str = ...,
depends_on_past: bool = ...,
ignore_first_depends_on_past: bool = ...,
wait_for_past_depends_before_skipping: bool = ...,
wait_for_downstream: bool = ...,
retries: int | None = ...,
queue: str = ...,
pool: str = ...,
pool_slots: int = ...,
execution_timeout: timedelta | None = ...,
max_retry_delay: None | timedelta | float = ...,
retry_delay: timedelta | float = ...,
retry_exponential_backoff: float = ...,
priority_weight: int = ...,
weight_rule: str | PriorityWeightStrategy = ...,
sla: timedelta | None = ...,
map_index_template: str | None = ...,
max_active_tis_per_dag: int | None = ...,
max_active_tis_per_dagrun: int | None = ...,
on_execute_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = ...,
on_failure_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = ...,
on_success_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = ...,
on_retry_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = ...,
on_skipped_callback: None | TaskStateChangeCallback | list[TaskStateChangeCallback] = ...,
run_as_user: str | None = ...,
executor: str | None = ...,
executor_config: dict | None = ...,
inlets: Any | None = ...,
outlets: Any | None = ...,
doc: str | None = ...,
doc_md: str | None = ...,
doc_json: str | None = ...,
doc_yaml: str | None = ...,
doc_rst: str | None = ...,
task_display_name: str | None = ...,
logger_name: str | None = ...,
allow_nested_operators: bool = True,
**kwargs,
) -> OperatorPartial: ...
else:
def partial(
operator_class: type[BaseOperator],
*,
task_id: str,
dag: DAG | None = None,
task_group: TaskGroup | None = None,
params: collections.abc.MutableMapping | None = None,
**kwargs,
):
from airflow.sdk.definitions._internal.contextmanager import DagContext, TaskGroupContext
validate_mapping_kwargs(operator_class, "partial", kwargs)
dag = dag or DagContext.get_current()
if dag:
task_group = task_group or TaskGroupContext.get_current(dag)
if task_group:
task_id = task_group.child_id(task_id)
# Merge Dag and task group level defaults into user-supplied values.
dag_default_args, partial_params = get_merged_defaults(
dag=dag,
task_group=task_group,
task_params=params,
task_default_args=kwargs.pop("default_args", None),
)
# Create partial_kwargs from args and kwargs
partial_kwargs: dict[str, Any] = {
"task_id": task_id,
"dag": dag,
"task_group": task_group,
**kwargs,
}
# Inject Dag-level default args into args provided to this function.
# Most of the default args will be retrieved during unmapping; here we
# only ensure base properties are correctly set for the scheduler.
partial_kwargs.update(
(k, v)
for k, v in dag_default_args.items()
if k not in partial_kwargs and k in BaseOperator.__init__._BaseOperatorMeta__param_names
)
# Fill fields not provided by the user with default values.
partial_kwargs.update((k, v) for k, v in OPERATOR_DEFAULTS.items() if k not in partial_kwargs)
# Post-process arguments. Should be kept in sync with _TaskDecorator.expand().
if "task_concurrency" in kwargs: # Reject deprecated option.
raise TypeError("unexpected argument: task_concurrency")
if start_date := partial_kwargs.get("start_date", None):
partial_kwargs["start_date"] = timezone.convert_to_utc(start_date)
if end_date := partial_kwargs.get("end_date", None):
partial_kwargs["end_date"] = timezone.convert_to_utc(end_date)
if partial_kwargs["pool_slots"] < 1:
dag_str = ""
if dag:
dag_str = f" in dag {dag.dag_id}"
raise ValueError(f"pool slots for {task_id}{dag_str} cannot be less than 1")
if retries := partial_kwargs.get("retries"):
partial_kwargs["retries"] = BaseOperator._convert_retries(retries)
partial_kwargs["retry_delay"] = BaseOperator._convert_retry_delay(partial_kwargs["retry_delay"])
partial_kwargs["max_retry_delay"] = BaseOperator._convert_max_retry_delay(
partial_kwargs.get("max_retry_delay", None)
)
for k in ("execute", "failure", "success", "retry", "skipped"):
partial_kwargs[attr] = _collect_from_input(partial_kwargs.get(attr := f"on_{k}_callback"))
return OperatorPartial(
operator_class=operator_class,
kwargs=partial_kwargs,
params=partial_params,
)
| _PartialDescriptor |
python | fsspec__filesystem_spec | fsspec/spec.py | {
"start": 64732,
"end": 77678
} | class ____(io.IOBase):
"""Convenient class to derive from to provide buffering
In the case that the backend does not provide a pythonic file-like object
already, this class contains much of the logic to build one. The only
methods that need to be overridden are ``_upload_chunk``,
``_initiate_upload`` and ``_fetch_range``.
"""
DEFAULT_BLOCK_SIZE = 5 * 2**20
_details = None
def __init__(
self,
fs,
path,
mode="rb",
block_size="default",
autocommit=True,
cache_type="readahead",
cache_options=None,
size=None,
**kwargs,
):
"""
Template for files with buffered reading and writing
Parameters
----------
fs: instance of FileSystem
path: str
location in file-system
mode: str
Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file
systems may be read-only, and some may not support append.
block_size: int
Buffer size for reading or writing, 'default' for class default
autocommit: bool
Whether to write to final destination; may only impact what
happens when file is being closed.
cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead"
Caching policy in read mode. See the definitions in ``core``.
cache_options : dict
Additional options passed to the constructor for the cache specified
by `cache_type`.
size: int
If given and in read mode, suppressed having to look up the file size
kwargs:
Gets stored as self.kwargs
"""
from .core import caches
self.path = path
self.fs = fs
self.mode = mode
self.blocksize = (
self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size
)
self.loc = 0
self.autocommit = autocommit
self.end = None
self.start = None
self.closed = False
if cache_options is None:
cache_options = {}
if "trim" in kwargs:
warnings.warn(
"Passing 'trim' to control the cache behavior has been deprecated. "
"Specify it within the 'cache_options' argument instead.",
FutureWarning,
)
cache_options["trim"] = kwargs.pop("trim")
self.kwargs = kwargs
if mode not in {"ab", "rb", "wb", "xb"}:
raise NotImplementedError("File mode not supported")
if mode == "rb":
if size is not None:
self.size = size
else:
self.size = self.details["size"]
self.cache = caches[cache_type](
self.blocksize, self._fetch_range, self.size, **cache_options
)
else:
self.buffer = io.BytesIO()
self.offset = None
self.forced = False
self.location = None
@property
def details(self):
if self._details is None:
self._details = self.fs.info(self.path)
return self._details
@details.setter
def details(self, value):
self._details = value
self.size = value["size"]
@property
def full_name(self):
return _unstrip_protocol(self.path, self.fs)
@property
def closed(self):
# get around this attr being read-only in IOBase
# use getattr here, since this can be called during del
return getattr(self, "_closed", True)
@closed.setter
def closed(self, c):
self._closed = c
def __hash__(self):
if "w" in self.mode:
return id(self)
else:
return int(tokenize(self.details), 16)
def __eq__(self, other):
"""Files are equal if they have the same checksum, only in read mode"""
if self is other:
return True
return (
isinstance(other, type(self))
and self.mode == "rb"
and other.mode == "rb"
and hash(self) == hash(other)
)
def commit(self):
"""Move from temp to final destination"""
def discard(self):
"""Throw away temporary file"""
def info(self):
"""File information about this path"""
if self.readable():
return self.details
else:
raise ValueError("Info not available while writing")
def tell(self):
"""Current file location"""
return self.loc
def seek(self, loc, whence=0):
"""Set current file location
Parameters
----------
loc: int
byte location
whence: {0, 1, 2}
from start of file, current location or end of file, resp.
"""
loc = int(loc)
if not self.mode == "rb":
raise OSError(ESPIPE, "Seek only available in read mode")
if whence == 0:
nloc = loc
elif whence == 1:
nloc = self.loc + loc
elif whence == 2:
nloc = self.size + loc
else:
raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
if nloc < 0:
raise ValueError("Seek before start of file")
self.loc = nloc
return self.loc
def write(self, data):
"""
Write data to buffer.
Buffer only sent on flush() or if buffer is greater than
or equal to blocksize.
Parameters
----------
data: bytes
Set of bytes to be written.
"""
if not self.writable():
raise ValueError("File not in write mode")
if self.closed:
raise ValueError("I/O operation on closed file.")
if self.forced:
raise ValueError("This file has been force-flushed, can only close")
out = self.buffer.write(data)
self.loc += out
if self.buffer.tell() >= self.blocksize:
self.flush()
return out
def flush(self, force=False):
"""
Write buffered data to backend store.
Writes the current buffer, if it is larger than the block-size, or if
the file is being closed.
Parameters
----------
force: bool
When closing, write the last block even if it is smaller than
blocks are allowed to be. Disallows further writing to this file.
"""
if self.closed:
raise ValueError("Flush on closed file")
if force and self.forced:
raise ValueError("Force flush cannot be called more than once")
if force:
self.forced = True
if self.readable():
# no-op to flush on read-mode
return
if not force and self.buffer.tell() < self.blocksize:
# Defer write on small block
return
if self.offset is None:
# Initialize a multipart upload
self.offset = 0
try:
self._initiate_upload()
except:
self.closed = True
raise
if self._upload_chunk(final=force) is not False:
self.offset += self.buffer.seek(0, 2)
self.buffer = io.BytesIO()
def _upload_chunk(self, final=False):
"""Write one part of a multi-block file upload
Parameters
==========
final: bool
This is the last block, so should complete file, if
self.autocommit is True.
"""
# may not yet have been initialized, may need to call _initialize_upload
def _initiate_upload(self):
"""Create remote file/upload"""
pass
def _fetch_range(self, start, end):
"""Get the specified set of bytes from remote"""
return self.fs.cat_file(self.path, start=start, end=end)
def read(self, length=-1):
"""
Return data from cache, or fetch pieces as necessary
Parameters
----------
length: int (-1)
Number of bytes to read; if <0, all remaining bytes.
"""
length = -1 if length is None else int(length)
if self.mode != "rb":
raise ValueError("File not in read mode")
if length < 0:
length = self.size - self.loc
if self.closed:
raise ValueError("I/O operation on closed file.")
if length == 0:
# don't even bother calling fetch
return b""
out = self.cache._fetch(self.loc, self.loc + length)
logger.debug(
"%s read: %i - %i %s",
self,
self.loc,
self.loc + length,
self.cache._log_stats(),
)
self.loc += len(out)
return out
def readinto(self, b):
"""mirrors builtin file's readinto method
https://docs.python.org/3/library/io.html#io.RawIOBase.readinto
"""
out = memoryview(b).cast("B")
data = self.read(out.nbytes)
out[: len(data)] = data
return len(data)
def readuntil(self, char=b"\n", blocks=None):
"""Return data between current position and first occurrence of char
char is included in the output, except if the end of the tile is
encountered first.
Parameters
----------
char: bytes
Thing to find
blocks: None or int
How much to read in each go. Defaults to file blocksize - which may
mean a new read on every call.
"""
out = []
while True:
start = self.tell()
part = self.read(blocks or self.blocksize)
if len(part) == 0:
break
found = part.find(char)
if found > -1:
out.append(part[: found + len(char)])
self.seek(start + found + len(char))
break
out.append(part)
return b"".join(out)
def readline(self):
"""Read until and including the first occurrence of newline character
Note that, because of character encoding, this is not necessarily a
true line ending.
"""
return self.readuntil(b"\n")
def __next__(self):
out = self.readline()
if out:
return out
raise StopIteration
def __iter__(self):
return self
def readlines(self):
"""Return all data, split by the newline character, including the newline character"""
data = self.read()
lines = data.split(b"\n")
out = [l + b"\n" for l in lines[:-1]]
if data.endswith(b"\n"):
return out
else:
return out + [lines[-1]]
# return list(self) ???
def readinto1(self, b):
return self.readinto(b)
def close(self):
"""Close file
Finalizes writes, discards cache
"""
if getattr(self, "_unclosable", False):
return
if self.closed:
return
try:
if self.mode == "rb":
self.cache = None
else:
if not self.forced:
self.flush(force=True)
if self.fs is not None:
self.fs.invalidate_cache(self.path)
self.fs.invalidate_cache(self.fs._parent(self.path))
finally:
self.closed = True
def readable(self):
"""Whether opened for reading"""
return "r" in self.mode and not self.closed
def seekable(self):
"""Whether is seekable (only in read mode)"""
return self.readable()
def writable(self):
"""Whether opened for writing"""
return self.mode in {"wb", "ab", "xb"} and not self.closed
def __reduce__(self):
if self.mode != "rb":
raise RuntimeError("Pickling a writeable file is not supported")
return reopen, (
self.fs,
self.path,
self.mode,
self.blocksize,
self.loc,
self.size,
self.autocommit,
self.cache.name if self.cache else "none",
self.kwargs,
)
def __del__(self):
if not self.closed:
self.close()
def __str__(self):
return f"<File-like object {type(self.fs).__name__}, {self.path}>"
__repr__ = __str__
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs):
file = fs.open(
path,
mode=mode,
block_size=blocksize,
autocommit=autocommit,
cache_type=cache_type,
size=size,
**kwargs,
)
if loc > 0:
file.seek(loc)
return file
| AbstractBufferedFile |
python | kamyu104__LeetCode-Solutions | Python/find-the-town-judge.py | {
"start": 33,
"end": 423
} | class ____(object):
def findJudge(self, N, trust):
"""
:type N: int
:type trust: List[List[int]]
:rtype: int
"""
degrees = [0]*N
for i, j in trust:
degrees[i-1] -= 1
degrees[j-1] += 1
for i in xrange(len(degrees)):
if degrees[i] == N-1:
return i+1
return -1
| Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/parsing_config.py | {
"start": 17523,
"end": 45485
} | class ____:
"""Raw parameters used by `gen_parsing_ops`.
Attributes:
sparse_keys: A list of string keys in the examples' features. The results
for these keys will be returned as `SparseTensor` objects.
sparse_types: A list of `DTypes` of the same length as `sparse_keys`. Only
`tf.float32` (`FloatList`), `tf.int64` (`Int64List`), and `tf.string`
(`BytesList`) are supported.
dense_keys: A list of string keys in the examples' features. The results for
these keys will be returned as `Tensor`s
dense_types: A list of DTypes of the same length as `dense_keys`. Only
`tf.float32` (`FloatList`), `tf.int64` (`Int64List`), and `tf.string`
(`BytesList`) are supported.
dense_defaults: A dict mapping string keys to `Tensor`s. The keys of the
dict must match the dense_keys of the feature.
dense_shapes: A list of tuples with the same length as `dense_keys`. The
shape of the data for each dense feature referenced by `dense_keys`.
Required for any input tensors identified by `dense_keys`. Must be either
fully defined, or may contain an unknown first dimension. An unknown first
dimension means the feature is treated as having a variable number of
blocks, and the output shape along this dimension is considered unknown at
graph build time. Padding is applied for minibatch elements smaller than
the maximum number of blocks for the given feature along this dimension.
ragged_keys: A list of string keys in the examples' features. The
results for these keys will be returned as `RaggedTensor` objects.
ragged_value_types: A list of `DTypes` of the same length as `ragged_keys`,
specifying the value type for each ragged feature. Must be one of:
`tf.float32`, `tf.int64`, `tf.string`.
ragged_split_types: A list of `DTypes` of the same length as `ragged_keys`,
specifying the row_splits type for each ragged feature. Must be one of:
`tf.int32`, `tf.int64`.
dense_shapes_as_proto: dense_shapes converted to TensorShapeProto.
dense_defaults_vec: A vector of `Tensor`s containing the default values,
corresponding 1:1 with `dense_keys`.
num_features: The total number of feature keys.
"""
def __init__(self,
sparse_keys=None,
sparse_types=None,
dense_keys=None,
dense_types=None,
dense_defaults=None,
dense_shapes=None,
ragged_keys=None,
ragged_value_types=None,
ragged_split_types=None):
# Note: we use an OrderedDict for dense_defaults, to ensure consistent
# graph construction order for _e2e_test.
dense_defaults = (
collections.OrderedDict() if dense_defaults is None else dense_defaults)
sparse_keys = [] if sparse_keys is None else sparse_keys
sparse_types = [] if sparse_types is None else sparse_types
dense_keys = [] if dense_keys is None else dense_keys
dense_types = [] if dense_types is None else dense_types
dense_shapes = ([[]] *
len(dense_keys) if dense_shapes is None else dense_shapes)
ragged_keys = [] if ragged_keys is None else ragged_keys
ragged_value_types = ([]
if ragged_value_types is None else ragged_value_types)
ragged_split_types = ([]
if ragged_split_types is None else ragged_split_types)
self.sparse_keys = sparse_keys
self.sparse_types = [dtypes.as_dtype(t) for t in sparse_types]
self.dense_keys = dense_keys
self.dense_types = [dtypes.as_dtype(t) for t in dense_types]
self.dense_shapes = [tensor_shape.as_shape(s) for s in dense_shapes]
self.dense_defaults = dense_defaults
self.ragged_keys = ragged_keys
self.ragged_value_types = [dtypes.as_dtype(t) for t in ragged_value_types]
self.ragged_split_types = [dtypes.as_dtype(t) for t in ragged_split_types]
self._validate()
@classmethod
def from_features(cls, features, types):
"""Builds _ParseOpParams for a given set of features and allowed types.
Args:
features: A `dict` mapping feature keys to objects of a type in `types`.
types: Type of features to allow, among `FixedLenFeature`,
`VarLenFeature`, `SparseFeature`, and `FixedLenSequenceFeature`.
Returns:
A `_ParseOpParams` containing the raw parameters for `gen_parsing_ops`.
Raises:
ValueError: if `features` contains an item not in `types`, or an invalid
feature.
ValueError: if sparse and dense key sets intersect.
ValueError: if input lengths do not match up.
"""
params = cls()
if features:
# NOTE: We iterate over sorted keys to keep things deterministic.
for key in sorted(features.keys()):
feature = features[key]
if not isinstance(feature, tuple(types)):
raise ValueError(
f"Unsupported {type(feature).__name__} {feature} for key '{key}'")
params._add_feature(key, feature) # pylint: disable=protected-access
params._validate() # pylint: disable=protected-access
return params
@property
def dense_shapes_as_proto(self):
return [shape.as_proto() for shape in self.dense_shapes]
@property
def num_features(self):
return len(self.dense_keys) + len(self.sparse_keys) + len(self.ragged_keys)
@property
def dense_defaults_vec(self):
return [
self._make_dense_default(k, s, t)
for k, s, t in zip(self.dense_keys, self.dense_shapes, self.dense_types)
]
def _make_dense_default(self, key, shape, dtype):
"""Construct the default value tensor for a specified dense feature.
Args:
key: The key string identifying the dense feature.
shape: The dense feature's shape.
dtype: The dense feature's dtype.
Returns:
A Tensor.
"""
default_value = self.dense_defaults.get(key)
if (shape.ndims is not None and shape.ndims > 0 and
shape.dims[0].value is None):
# Variable stride dense shape, the default value should be a
# scalar padding value.
if default_value is None:
default_value = ops.convert_to_tensor(
"" if dtype == dtypes.string else 0, dtype=dtype)
else:
# Reshape to a scalar to ensure user gets an error if they
# provide a tensor that's not intended to be a padding value
# (0 or 2+ elements).
key_name = "padding_" + re.sub("[^A-Za-z0-9_.\\-/]", "_", key)
default_value = ops.convert_to_tensor(
default_value, dtype=dtype, name=key_name)
default_value = array_ops.reshape(default_value, [])
else:
if default_value is None:
default_value = constant_op.constant([], dtype=dtype)
elif not isinstance(default_value, tensor.Tensor):
key_name = "key_" + re.sub("[^A-Za-z0-9_.\\-/]", "_", key)
default_value = ops.convert_to_tensor(
default_value, dtype=dtype, name=key_name)
default_value = array_ops.reshape(default_value, shape)
return default_value
def _add_feature(self, key, feature):
"""Adds the specified feature to this ParseOpParams."""
if isinstance(feature, VarLenFeature):
self._add_varlen_feature(key, feature)
elif isinstance(feature, SparseFeature):
self._add_sparse_feature(key, feature)
elif isinstance(feature, FixedLenFeature):
self._add_fixed_len_feature(key, feature)
elif isinstance(feature, FixedLenSequenceFeature):
self._add_fixed_len_sequence_feature(key, feature)
elif isinstance(feature, RaggedFeature):
self._add_ragged_feature(key, feature)
else:
raise ValueError(f"Invalid feature {key}:{feature}.")
def _add_varlen_feature(self, key, feature):
"""Adds a VarLenFeature."""
if not feature.dtype:
raise ValueError(
f"Missing type for feature {key}. Received feature={feature}")
self._add_sparse_key(key, feature.dtype)
def _add_sparse_key(self, key, dtype):
"""Adds a sparse key & dtype, checking for duplicates."""
if key in self.sparse_keys:
original_dtype = self.sparse_types[self.sparse_keys.index(key)]
if original_dtype != dtype:
raise ValueError(
f"Conflicting type {original_dtype} vs {dtype} for feature {key}.")
else:
self.sparse_keys.append(key)
self.sparse_types.append(dtype)
def _add_sparse_feature(self, key, feature):
"""Adds a SparseFeature."""
if not feature.index_key:
raise ValueError(f"Missing index_key for SparseFeature {feature}.")
if not feature.value_key:
raise ValueError(f"Missing value_key for SparseFeature {feature}.")
if not feature.dtype:
raise ValueError(f"Missing type for feature {key}. Received feature="
f"{feature}.")
index_keys = feature.index_key
if isinstance(index_keys, str):
index_keys = [index_keys]
elif len(index_keys) > 1:
tf_logging.warning("SparseFeature is a complicated feature config "
"and should only be used after careful "
"consideration of VarLenFeature.")
for index_key in sorted(index_keys):
self._add_sparse_key(index_key, dtypes.int64)
self._add_sparse_key(feature.value_key, feature.dtype)
def _add_fixed_len_feature(self, key, feature):
"""Adds a FixedLenFeature.
Args:
key: The key for the feature.
feature: The FixedLenFeature to add.
Raises:
ValueError: If `feature.dtype` is missing, if `feature.shape` is missing,
if the first dimension of `feature.shape` is unknown, or if not all
"""
if not feature.dtype:
raise ValueError(f"Missing type for feature {key}. Received feature="
f"{feature}.")
if feature.shape is None:
raise ValueError(f"Missing shape for feature {key}. Received feature="
f"{feature}.")
feature_tensor_shape = tensor_shape.as_shape(feature.shape)
if (feature.shape and feature_tensor_shape.ndims and
feature_tensor_shape.dims[0].value is None):
raise ValueError(f"First dimension of shape for feature {key} unknown. "
"Consider using FixedLenSequenceFeature. Received "
f"feature={feature}.")
if (feature.shape is not None and
not feature_tensor_shape.is_fully_defined()):
raise ValueError(f"All dimensions of shape for feature {key} need to be "
f"known but received {feature.shape!s}.")
self.dense_keys.append(key)
self.dense_shapes.append(tensor_shape.as_shape(feature.shape))
self.dense_types.append(feature.dtype)
if feature.default_value is not None:
self.dense_defaults[key] = feature.default_value
def _add_fixed_len_sequence_feature(self, key, feature):
"""Adds a FixedLenSequenceFeature.
Args:
key: The key for the feature.
feature: The FixedLenSequenceFeature to add.
Raises:
ValueError: If `feature.dtype` is missing or if `feature.shape` is
missing.
"""
if not feature.dtype:
raise ValueError(f"Missing type for feature {key}. Received feature="
f"{feature}.")
if feature.shape is None:
raise ValueError(f"Missing shape for feature {key}. Received feature="
f"{feature}.")
self.dense_keys.append(key)
self.dense_shapes.append(tensor_shape.as_shape(feature.shape))
self.dense_types.append(feature.dtype)
if feature.allow_missing:
self.dense_defaults[key] = None
if feature.default_value is not None:
self.dense_defaults[key] = feature.default_value
def _add_ragged_key(self, key, value_type, split_type):
"""Adds a ragged key & dtype, checking for duplicates.
Args:
key: The key for the ragged feature.
value_type: The dtype of the ragged feature's values.
split_type: The dtype of the ragged feature's row splits.
Raises:
ValueError: If a key is already present with a different `value_type` or
`split_type`.
"""
if key in self.ragged_keys:
original_value_type = self.ragged_value_types[self.ragged_keys.index(key)]
original_split_type = self.ragged_split_types[self.ragged_keys.index(key)]
if original_value_type != value_type:
raise ValueError(f"Conflicting type {original_value_type} vs "
f"{value_type} for feature {key}.")
if original_split_type != split_type:
raise ValueError(f"Conflicting partition type {original_split_type} vs "
f"{split_type} for feature {key}.")
else:
self.ragged_keys.append(key)
self.ragged_value_types.append(value_type)
self.ragged_split_types.append(split_type)
def _add_ragged_feature(self, key, feature):
"""Adds a RaggedFeature.
Args:
key: The key for the feature.
feature: The RaggedFeature to add.
Raises:
ValueError: If a value or partition key is already present with a
different value or split type.
"""
value_key = key if feature.value_key is None else feature.value_key
self._add_ragged_key(value_key, feature.dtype, feature.row_splits_dtype)
for partition in feature.partitions:
if not isinstance(partition, RaggedFeature.UniformRowLength):
self._add_ragged_key(partition.key, dtypes.int64,
feature.row_splits_dtype)
def _validate(self):
"""Validates the features in this ParseOpParams.
Raises:
ValueError: If the lengths of `dense_shapes`, `dense_keys`,
`dense_types`, `sparse_types`, `sparse_keys`, `ragged_value_types` or
`ragged_split_types` do not match their corresponding keys, or if
dense and sparse keys, dense and ragged keys, or ragged and sparse keys
intersect.
"""
if len(self.dense_shapes) != len(self.dense_keys):
raise ValueError("len(self.dense_shapes) != len(self.dense_keys): "
f"{len(self.dense_shapes)} vs {len(self.dense_keys)}.")
if len(self.dense_types) != len(self.dense_keys):
raise ValueError("len(self.dense_types) != len(self.dense_keys): "
f"{len(self.dense_types)} vs {len(self.dense_keys)}.")
if len(self.sparse_types) != len(self.sparse_keys):
raise ValueError("len(self.sparse_types) != len(self.sparse_keys): "
f"{len(self.sparse_types)} vs {len(self.sparse_keys)}.")
if len(self.ragged_value_types) != len(self.ragged_keys):
raise ValueError(
"len(self.ragged_value_types) != len(self.ragged_keys): "
f"{len(self.ragged_value_types)} vs {len(self.ragged_keys)}.")
if len(self.ragged_split_types) != len(self.ragged_keys):
raise ValueError(
"len(self.ragged_split_types) != len(self.ragged_keys): "
f"{len(self.ragged_split_types)} vs {len(self.ragged_keys)}.")
dense_key_set = set(self.dense_keys)
sparse_key_set = set(self.sparse_keys)
ragged_key_set = set(self.ragged_keys)
if not dense_key_set.isdisjoint(sparse_key_set):
raise ValueError(
"Dense and sparse keys must not intersect; dense_keys: "
f"{self.dense_keys}, sparse_keys: {self.sparse_keys}, intersection: "
f"{dense_key_set.intersection(sparse_key_set)}")
if not dense_key_set.isdisjoint(ragged_key_set):
raise ValueError(
"Dense and ragged keys must not intersect; dense_keys: ",
f"{self.dense_keys}, ragged_keys: {self.ragged_keys}, intersection: "
f"{dense_key_set.intersection(ragged_key_set)}")
if not ragged_key_set.isdisjoint(sparse_key_set):
raise ValueError(
"Ragged and sparse keys must not intersect; ragged_keys: "
f"{self.ragged_keys}, sparse_keys: {self.sparse_keys}, intersection: "
f"{ragged_key_set.intersection(sparse_key_set)}")
def _construct_tensors_for_composite_features(features, tensor_dict):
"""Creates tensors for SparseFeatures and RaggedFeatures.
Constructs new dict based on `tensor_dict`.
For each key in `features` whose value is a `SparseFeature`:
* Looks up that SparseFeature's value_key and index_keys in tensor_dict.
* Uses those tensors to construct a single SparseTensor.
* Stores that SparseTensor in the output dict under the same key.
For each key in `features` whose value is a `RaggedFeature`:
* Looks up that RaggedFeature's value_key and partition keys in tensor_dict.
* Uses those tensors to construct a single RaggedTensor.
* Stores that RaggedTensor in the output dict under the same key.
For any other key in `features`:
* Copies that key and its value from tensor_dict to the output dictionary.
Args:
features: A `dict` mapping feature keys to `SparseFeature` or
`RaggedFeature` values. Values of other types will be ignored.
tensor_dict: A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and
`RaggedTensor` values. Expected to contain keys of the `SparseFeature`s'
`index_key`s and `value_key`s and mapping them to `SparseTensor`s.
Returns:
A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and
`RaggedTensor` values. Similar to `tensor_dict` except each `SparseFeature`
in `features` results in a single `SparseTensor`; and each `RaggedFeature`
in `features` results in a single `RaggedTensor`.
"""
tensor_dict = dict(tensor_dict) # Do not modify argument passed in.
updates = {}
for key in sorted(features.keys()):
feature = features[key]
if isinstance(feature, SparseFeature):
# Construct SparseTensors for SparseFeatures
if isinstance(feature.index_key, str):
sp_ids = tensor_dict[feature.index_key]
else:
sp_ids = [tensor_dict[index_key] for index_key in feature.index_key]
sp_values = tensor_dict[feature.value_key]
updates[key] = sparse_ops.sparse_merge(
sp_ids,
sp_values,
vocab_size=feature.size,
already_sorted=feature.already_sorted)
elif isinstance(feature, RaggedFeature):
# Construct RaggedTensors for RaggedFeatures.
value_key = key if feature.value_key is None else feature.value_key
rt = tensor_dict[value_key]
if isinstance(rt, ragged_tensor.RaggedTensor):
# We processed a batch of tf.Example or tf.SequenceExample, or single
# tf.SequenceExample.
if rt.ragged_rank > 1:
# We're processing a batch of SequenceExample, and we effectively have
# two batch dimensions. Cllapse those batch dimensions here, and
# restore them below (using outer_splits).
outer_splits = rt.row_splits
rt = rt.values
else:
outer_splits = None
for partition in reversed(feature.partitions):
rt = _add_batched_ragged_partition(rt, partition, tensor_dict,
key, feature.validate,
outer_splits)
if outer_splits is not None:
rt = ragged_tensor.RaggedTensor.from_row_splits(
rt, outer_splits, validate=feature.validate)
else:
# We processed a single tf.Example.
for partition in reversed(feature.partitions):
rt = _add_ragged_partition(rt, partition, tensor_dict,
feature.row_splits_dtype, feature.validate)
updates[key] = rt
# Process updates after all composite tensors have been constructed (in case
# multiple features use the same value_key, and one uses that key as its
# feature key).
tensor_dict.update(updates)
# Remove tensors from dictionary that were only used to construct
# tensors for SparseFeature or RaggedTensor.
for key in set(tensor_dict) - set(features):
del tensor_dict[key]
return tensor_dict
def _add_ragged_partition(values, partition, tensor_dict, row_splits_dtype,
validate):
"""Creates a RaggedTensor from a values tensor and a partition tensor.
Args:
values: The values tensor for the new RaggedTensor.
partition: The partition configuration object. Specifies the key that
should be used to look up the partition tensor (unless partition is a
RaggedFeature.UniformRowLength, in which case there is no partition
tensor).
tensor_dict: The dictionary mapping keys to tensors.
row_splits_dtype: The dtype for the partition tensor.
validate: Whether to validate that the values form a valid RaggedTensor.
Returns:
A new RaggedTensor formed from the values and partition tensors.
"""
if isinstance(partition, RaggedFeature.UniformRowLength):
if isinstance(values, ragged_tensor.RaggedTensor):
length = ops.convert_to_tensor(partition.length, dtype=row_splits_dtype)
return ragged_tensor.RaggedTensor.from_uniform_row_length(
values, length, validate=validate)
else:
return array_ops.reshape(values, array_ops.concat(
[[-1, partition.length], array_ops.shape(values)[1:]], axis=0))
else:
partition_t = math_ops.cast(tensor_dict[partition.key], row_splits_dtype)
if isinstance(partition, RaggedFeature.RowSplits):
return ragged_tensor.RaggedTensor.from_row_splits(
values, partition_t, validate=validate)
elif isinstance(partition, RaggedFeature.RowLengths):
return ragged_tensor.RaggedTensor.from_row_lengths(
values, partition_t, validate=validate)
elif isinstance(partition, RaggedFeature.RowStarts):
return ragged_tensor.RaggedTensor.from_row_starts(
values, partition_t, validate=validate)
elif isinstance(partition, RaggedFeature.RowLimits):
return ragged_tensor.RaggedTensor.from_row_limits(
values, partition_t, validate=validate)
elif isinstance(partition, RaggedFeature.ValueRowIds):
return ragged_tensor.RaggedTensor.from_value_rowids(
values, partition_t, validate=validate)
raise ValueError(f"Unhandled partition type {partition!r}")
def _add_batched_ragged_partition(rt, partition, tensor_dict, feature_key,
validate, outer_splits=None):
"""Adds a batched ragged partition tensor to a batched ragged tensor.
Args:
rt: A RaggedTensor with shape [batch_size, ...].
partition: The partition configuration object. Specifies the key that
should be used to look up the partition tensor (unless partition is a
RaggedFeature.UniformRowLength, in which case there is no partition
tensor). The specified tensor must have shape [batch_size, ...].
tensor_dict: The dictionary mapping keys to tensors.
feature_key: The name of the feature being parsed (for error messages).
validate: Whether to validate that the values form a valid RaggedTensor.
outer_splits: If not None, then we have two batch dimensions, and this
is the row-splits for the collapsed batch dimension. Every partition
tensor must have an outer row_splits that matches this value.
Returns:
A new RaggedTensor where each batch item `rt[i]` has been partitioned
using the `partition_t[i]`.
"""
if isinstance(partition, RaggedFeature.UniformRowLength):
if rt.ragged_rank > 1:
length = ops.convert_to_tensor(partition.length, rt.row_splits.dtype)
return ragged_tensor.RaggedTensor.from_row_splits(
ragged_tensor.RaggedTensor.from_uniform_row_length(
rt.values, length, validate=validate),
rt.row_splits // length,
validate=validate)
else:
reshaped_vals = array_ops.reshape(rt.values, array_ops.concat(
[[-1, partition.length], array_ops.shape(rt.values)[1:]], axis=0))
return ragged_tensor.RaggedTensor.from_row_splits(
reshaped_vals, rt.row_splits // partition.length, validate=validate)
partition_t = tensor_dict[partition.key]
if partition_t.values.dtype != rt.row_splits.dtype:
partition_t = math_ops.cast(partition_t, rt.row_splits.dtype)
checks = []
if outer_splits is not None:
if validate:
checks.append(check_ops.assert_equal(
outer_splits, partition_t.row_splits,
message="Feature %s: values and partitions are not aligned"
% feature_key))
partition_t = partition_t.values
with ops.control_dependencies(checks):
if isinstance(partition, (RaggedFeature.RowSplits,
RaggedFeature.RowLimits)):
if isinstance(partition, RaggedFeature.RowSplits):
partition_t = partition_t[:, 1:]
adjusted_limits = partition_t.values + array_ops.repeat(
rt.row_starts(), partition_t.row_lengths())
return partition_t.with_values(
ragged_tensor.RaggedTensor.from_row_limits(
rt.values, adjusted_limits, validate=validate))
elif isinstance(partition, RaggedFeature.RowStarts):
adjusted_starts = partition_t.values + array_ops.repeat(
rt.row_starts(), partition_t.row_lengths())
return partition_t.with_values(
ragged_tensor.RaggedTensor.from_row_starts(
rt.values, adjusted_starts, validate=validate))
elif isinstance(partition, RaggedFeature.RowLengths):
return partition_t.with_values(
ragged_tensor.RaggedTensor.from_row_lengths(
rt.values, partition_t.values, validate=validate))
elif isinstance(partition, RaggedFeature.ValueRowIds):
nrows = math_ops.maximum( # number of rows in each batch item
ragged_math_ops.reduce_max(partition_t + 1, axis=1), 0)
adjusted_rowids = partition_t.values + array_ops.repeat(
math_ops.cumsum(nrows, exclusive=True), partition_t.row_lengths())
return ragged_tensor.RaggedTensor.from_row_lengths(
ragged_tensor.RaggedTensor.from_value_rowids(
rt.values, adjusted_rowids, validate=validate),
nrows,
validate=validate)
raise ValueError(f"Unhandled partition type {partition!r}")
def _build_ragged_tensors(serialized_shape,
ragged_values,
ragged_row_splits,
ragged_inner_splits=None):
"""Builds RaggedTensors from the outputs of a parse op.
This function takes the results of parsing a serialized batch of
examples, and constructs `RaggedTensor`s from the parsed values and
row-partitioning tensors.
Args:
serialized_shape: The shape of the input tensor that was parsed. This
is used to determine whether the input was a single example or a
batch of examples.
ragged_values: A list of `Tensor`s containing the values for the
`RaggedTensor`s to be constructed.
ragged_row_splits: A list of `Tensor`s containing the row-splits for
the outer dimension of the `RaggedTensor`s to be constructed.
ragged_inner_splits: Optional list of `Tensor`s containing the row-splits
for an inner dimension of the `RaggedTensor`s to be constructed.
This is used when parsing `SequenceExample`s.
Returns:
A list of `RaggedTensor`s. The number of `RaggedTensor`s in the
returned list is equal to the number of elements in `ragged_values`.
If `serialized_shape` corresponds to a single example, then the
returned `RaggedTensor`s will have one less dimension than if
`serialized_shape` corresponds to a batch of examples.
"""
if ragged_inner_splits is not None:
ragged_values = [
ragged_tensor.RaggedTensor.from_row_splits(val, split, validate=False)
for (val, split) in zip(ragged_values, ragged_inner_splits)
]
if serialized_shape.ndims == 0:
return ragged_values
else:
return [
ragged_tensor.RaggedTensor.from_row_splits(val, split, validate=False)
for (val, split) in zip(ragged_values, ragged_row_splits)
]
| _ParseOpParams |
python | google__jax | tests/pallas/mosaic_gpu_test.py | {
"start": 203124,
"end": 203419
} | class ____(PallasTest):
def test_export_succeeds(self):
out_shape = jax.ShapeDtypeStruct([128], jnp.float32)
@functools.partial(self.pallas_call, out_shape=out_shape)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...] + 1.0
_ = export.export(kernel)(out_shape)
| ExportTest |
python | bokeh__bokeh | tests/unit/bokeh/io/test_output.py | {
"start": 2114,
"end": 3796
} | class ____:
@patch('bokeh.io.output.run_notebook_hook')
def test_no_args(self, mock_run_notebook_hook: MagicMock) -> None:
default_load_jupyter_args = (None, False, False, 5000)
bio.output_notebook()
assert mock_run_notebook_hook.call_count == 1
assert mock_run_notebook_hook.call_args[0] == ('jupyter', 'load', *default_load_jupyter_args)
assert mock_run_notebook_hook.call_args[1] == {}
@patch('bokeh.io.output.run_notebook_hook')
def test_with_args(self, mock_run_notebook_hook: MagicMock) -> None:
load_jupyter_args = (Resources(), True, True, 1000)
bio.output_notebook(*load_jupyter_args)
assert mock_run_notebook_hook.call_count == 1
assert mock_run_notebook_hook.call_args[0] == ('jupyter', 'load', *load_jupyter_args)
assert mock_run_notebook_hook.call_args[1] == {}
@patch('bokeh.io.state.State.reset')
def test_reset_output(mock_reset: MagicMock) -> None:
# might create a new one, which also calls reset
original_call_count = curstate().reset.call_count
bio.reset_output()
assert curstate().reset.call_count == original_call_count+1
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Test_output_notebook |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_rows.py | {
"start": 689,
"end": 1553
} | class ____:
def new_version(self, session):
# make us transient (removes persistent
# identity).
make_transient(self)
# set 'id' to None.
# a new PK will be generated on INSERT.
self.id = None
@event.listens_for(Session, "before_flush")
def before_flush(session, flush_context, instances):
for instance in session.dirty:
if not isinstance(instance, Versioned):
continue
if not session.is_modified(instance):
continue
if not attributes.instance_state(instance).has_identity:
continue
# make it transient
instance.new_version(session)
# re-add
session.add(instance)
Base = declarative_base()
engine = create_engine("sqlite://", echo=True)
Session = sessionmaker(engine)
# example 1, simple versioning
| Versioned |
python | eventlet__eventlet | eventlet/zipkin/api.py | {
"start": 3993,
"end": 5467
} | class ____:
@staticmethod
def build_span(name, trace_id, span_id, parent_id,
annotations, bannotations):
return ttypes.Span(
name=name,
trace_id=trace_id,
id=span_id,
parent_id=parent_id,
annotations=annotations,
binary_annotations=bannotations
)
@staticmethod
def build_annotation(value, endpoint=None):
if isinstance(value, str):
value = value.encode('utf-8')
assert isinstance(value, bytes)
return ttypes.Annotation(time.time() * 1000 * 1000,
value, endpoint)
@staticmethod
def build_binary_annotation(key, value, endpoint=None):
annotation_type = ttypes.AnnotationType.STRING
return ttypes.BinaryAnnotation(key, value, annotation_type, endpoint)
@staticmethod
def build_endpoint(ipv4=None, port=None, service_name=None):
if ipv4 is not None:
ipv4 = ZipkinDataBuilder._ipv4_to_int(ipv4)
if service_name is None:
service_name = ZipkinDataBuilder._get_script_name()
return ttypes.Endpoint(
ipv4=ipv4,
port=port,
service_name=service_name
)
@staticmethod
def _ipv4_to_int(ipv4):
return struct.unpack('!i', socket.inet_aton(ipv4))[0]
@staticmethod
def _get_script_name():
return os.path.basename(sys.argv[0])
| ZipkinDataBuilder |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 42306,
"end": 48029
} | class ____:
def test_theilslopes(self):
# Test for basic slope and intercept.
slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1])
assert_almost_equal(slope, 0.5)
assert_almost_equal(intercept, 0.5)
slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1],
method='joint')
assert_almost_equal(slope, 0.5)
assert_almost_equal(intercept, 0.0)
# Test for correct masking.
y = np.ma.array([0, 1, 100, 1], mask=[False, False, True, False])
slope, intercept, lower, upper = mstats.theilslopes(y)
assert_almost_equal(slope, 1./3)
assert_almost_equal(intercept, 2./3)
slope, intercept, lower, upper = mstats.theilslopes(y,
method='joint')
assert_almost_equal(slope, 1./3)
assert_almost_equal(intercept, 0.0)
# Test of confidence intervals from example in Sen (1968).
x = [1, 2, 3, 4, 10, 12, 18]
y = [9, 15, 19, 20, 45, 55, 78]
slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07)
assert_almost_equal(slope, 4)
assert_almost_equal(intercept, 4.0)
assert_almost_equal(upper, 4.38, decimal=2)
assert_almost_equal(lower, 3.71, decimal=2)
slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07,
method='joint')
assert_almost_equal(slope, 4)
assert_almost_equal(intercept, 6.0)
assert_almost_equal(upper, 4.38, decimal=2)
assert_almost_equal(lower, 3.71, decimal=2)
def test_theilslopes_warnings(self):
# Test `theilslopes` with degenerate input; see gh-15943
msg = "All `x` coordinates.*|Mean of empty slice|invalid value encountered.*"
with pytest.warns(RuntimeWarning, match=msg):
res = mstats.theilslopes([0, 1], [0, 0])
assert np.all(np.isnan(res))
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", "invalid value encountered...", RuntimeWarning)
res = mstats.theilslopes([0, 0, 0], [0, 1, 0])
assert_allclose(res, (0, 0, np.nan, np.nan))
def test_theilslopes_namedtuple_consistency(self):
"""
Simple test to ensure tuple backwards-compatibility of the returned
TheilslopesResult object
"""
y = [1, 2, 4]
x = [4, 6, 8]
slope, intercept, low_slope, high_slope = mstats.theilslopes(y, x)
result = mstats.theilslopes(y, x)
# note all four returned values are distinct here
assert_equal(slope, result.slope)
assert_equal(intercept, result.intercept)
assert_equal(low_slope, result.low_slope)
assert_equal(high_slope, result.high_slope)
def test_gh19678_uint8(self):
# `theilslopes` returned unexpected results when `y` was an unsigned type.
# Check that this is resolved.
rng = np.random.default_rng(2549824598234528)
y = rng.integers(0, 255, size=10, dtype=np.uint8)
res = stats.theilslopes(y, y)
np.testing.assert_allclose(res.slope, 1)
def test_siegelslopes():
# method should be exact for straight line
y = 2 * np.arange(10) + 0.5
assert_equal(mstats.siegelslopes(y), (2.0, 0.5))
assert_equal(mstats.siegelslopes(y, method='separate'), (2.0, 0.5))
x = 2 * np.arange(10)
y = 5 * x - 3.0
assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0))
assert_equal(mstats.siegelslopes(y, x, method='separate'), (5.0, -3.0))
# method is robust to outliers: brekdown point of 50%
y[:4] = 1000
assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0))
# if there are no outliers, results should be comparable to linregress
x = np.arange(10)
y = -2.3 + 0.3*x + stats.norm.rvs(size=10, random_state=231)
slope_ols, intercept_ols, _, _, _ = stats.linregress(x, y)
slope, intercept = mstats.siegelslopes(y, x)
assert_allclose(slope, slope_ols, rtol=0.1)
assert_allclose(intercept, intercept_ols, rtol=0.1)
slope, intercept = mstats.siegelslopes(y, x, method='separate')
assert_allclose(slope, slope_ols, rtol=0.1)
assert_allclose(intercept, intercept_ols, rtol=0.1)
def test_siegelslopes_namedtuple_consistency():
"""
Simple test to ensure tuple backwards-compatibility of the returned
SiegelslopesResult object.
"""
y = [1, 2, 4]
x = [4, 6, 8]
slope, intercept = mstats.siegelslopes(y, x)
result = mstats.siegelslopes(y, x)
# note both returned values are distinct here
assert_equal(slope, result.slope)
assert_equal(intercept, result.intercept)
def test_sen_seasonal_slopes():
rng = np.random.default_rng(5765986256978575148)
x = rng.random(size=(100, 4))
intra_slope, inter_slope = mstats.sen_seasonal_slopes(x)
# reference implementation from the `sen_seasonal_slopes` documentation
def dijk(yi):
n = len(yi)
x = np.arange(n)
dy = yi - yi[:, np.newaxis]
dx = x - x[:, np.newaxis]
mask = np.triu(np.ones((n, n), dtype=bool), k=1)
return dy[mask]/dx[mask]
for i in range(4):
assert_allclose(np.median(dijk(x[:, i])), intra_slope[i])
all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])])
assert_allclose(np.median(all_slopes), inter_slope)
def test_plotting_positions():
# Regression test for #1256
pos = mstats.plotting_positions(np.arange(3), 0, 0)
assert_array_almost_equal(pos.data, np.array([0.25, 0.5, 0.75]))
@skip_xp_invalid_arg
| TestTheilslopes |
python | geekcomputers__Python | JustDialScrapperGUI/Justdial Scrapper GUI.py | {
"start": 6531,
"end": 8694
} | class ____:
def __init__(self, master):
self.master = master
self.label_query = Label
self.entry_query = Entry
self.label_location = Label
self.entry_location = Entry
self.label_file_name = Label
self.entry_file_name = Entry
self.label_progress = Label
self.button_start = Button
# Progress bar widget
self.progress = Progressbar
def start_scrapping(self):
query = self.entry_query.get()
location = self.entry_location.get()
file_name = self.entry_file_name.get()
scrapper = ScrapperLogic(
query, location, file_name, self.progress, self.label_progress
)
t1 = threading.Thread(target=scrapper.start_scrapping_logic, args=[])
t1.start()
def start(self):
self.label_query = Label(self.master, text="Query")
self.label_query.grid(row=0, column=0)
self.entry_query = Entry(self.master, width=23)
self.entry_query.grid(row=0, column=1)
self.label_location = Label(self.master, text="Location")
self.label_location.grid(row=1, column=0)
self.entry_location = Entry(self.master, width=23)
self.entry_location.grid(row=1, column=1)
self.label_file_name = Label(self.master, text="File Name")
self.label_file_name.grid(row=2, column=0)
self.entry_file_name = Entry(self.master, width=23)
self.entry_file_name.grid(row=2, column=1)
self.label_progress = Label(self.master, text="0%")
self.label_progress.grid(row=3, column=0)
self.button_start = Button(
self.master, text="Start", command=self.start_scrapping
)
self.button_start.grid(row=3, column=1)
self.progress = Progressbar(
self.master, orient=HORIZONTAL, length=350, mode="determinate"
)
self.progress.grid(row=4, columnspan=2)
# Above is the progress bar
if __name__ == "__main__":
root = Tk()
root.geometry("350x130+600+100")
root.title("Just Dial Scrapper - Cool")
JDScrapperGUI(root).start()
root.mainloop()
| JDScrapperGUI |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_shared_strings03.py | {
"start": 315,
"end": 912
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("shared_strings03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
non_char1 = "\ufffe"
non_char2 = "\uffff"
worksheet.write(0, 0, non_char1)
worksheet.write(1, 0, non_char2)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | python-openxml__python-docx | tests/parts/test_styles.py | {
"start": 332,
"end": 1695
} | class ____:
def it_provides_access_to_its_styles(self, styles_fixture):
styles_part, Styles_, styles_ = styles_fixture
styles = styles_part.styles
Styles_.assert_called_once_with(styles_part.element)
assert styles is styles_
def it_can_construct_a_default_styles_part_to_help(self):
package = OpcPackage()
styles_part = StylesPart.default(package)
assert isinstance(styles_part, StylesPart)
assert styles_part.partname == "/word/styles.xml"
assert styles_part.content_type == CT.WML_STYLES
assert styles_part.package is package
assert len(styles_part.element) == 6
# fixtures -------------------------------------------------------
@pytest.fixture
def styles_fixture(self, Styles_, styles_elm_, styles_):
styles_part = StylesPart(None, None, styles_elm_, None)
return styles_part, Styles_, styles_
# fixture components ---------------------------------------------
@pytest.fixture
def Styles_(self, request, styles_):
return class_mock(request, "docx.parts.styles.Styles", return_value=styles_)
@pytest.fixture
def styles_(self, request):
return instance_mock(request, Styles)
@pytest.fixture
def styles_elm_(self, request):
return instance_mock(request, CT_Styles)
| DescribeStylesPart |
python | apache__airflow | providers/google/tests/unit/google/cloud/openlineage/test_mixins.py | {
"start": 3769,
"end": 43929
} | class ____:
def setup_method(self):
self.copy_job_details = read_common_json_file("copy_job_details.json")
self.extract_job_details = read_common_json_file("extract_job_details.json")
self.load_job_details = read_common_json_file("load_job_details.json")
self.query_job_details = read_common_json_file("query_job_details.json")
self.script_job_details = read_common_json_file("script_job_details.json")
hook = MagicMock()
self.client = MagicMock()
class BQOperator(_BigQueryInsertJobOperatorOpenLineageMixin):
sql = ""
job_id = "job_id"
project_id = "project_id"
location = None
log = logging.getLogger("BQOperator")
@property
def hook(self):
return hook
hook.get_client.return_value = self.client
self.operator = BQOperator()
self.operator._client = self.client
def test_get_openlineage_facets_on_complete_query_job(self):
self.client.get_job.return_value._properties = self.query_job_details
self.client.get_table.side_effect = [
Table.from_api_repr(read_common_json_file("table_details.json")),
Table.from_api_repr(read_common_json_file("out_table_details.json")),
]
lineage = self.operator.get_openlineage_facets_on_complete(None)
self.query_job_details["configuration"]["query"].pop("query")
assert lineage.run_facets == {
"bigQueryJob": BigQueryJobRunFacet(
cached=False, billedBytes=111149056, properties=json.dumps(self.query_job_details)
),
"externalQuery": ExternalQueryRunFacet(externalQueryId="job_id", source="bigquery"),
}
assert lineage.inputs == [
InputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.test_table",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("state", "STRING", "2-digit state code"),
SchemaDatasetFacetFields("gender", "STRING", "Sex (M=male or F=female)"),
SchemaDatasetFacetFields("year", "INTEGER", "4-digit year of birth"),
SchemaDatasetFacetFields("name", "STRING", "Given name of a person at birth"),
SchemaDatasetFacetFields(
"number", "INTEGER", "Number of occurrences of the name"
),
]
),
"documentation": DocumentationDatasetFacet(
"The table contains the number of applicants for a Social Security card by year of birth and sex."
),
},
)
]
assert lineage.outputs == [
OutputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.output_table",
outputFacets={
"outputStatistics": OutputStatisticsOutputDatasetFacet(
rowCount=20, size=321, fileCount=None
)
},
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
),
},
),
]
def test_get_openlineage_facets_on_complete_copy_job(self):
self.client.get_job.return_value._properties = self.copy_job_details
self.client.get_table.return_value = Table.from_api_repr(read_common_json_file("table_details.json"))
expected_facets = {
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("state", "STRING", "2-digit state code"),
SchemaDatasetFacetFields("gender", "STRING", "Sex (M=male or F=female)"),
SchemaDatasetFacetFields("year", "INTEGER", "4-digit year of birth"),
SchemaDatasetFacetFields("name", "STRING", "Given name of a person at birth"),
SchemaDatasetFacetFields("number", "INTEGER", "Number of occurrences of the name"),
]
),
"documentation": DocumentationDatasetFacet(
"The table contains the number of applicants for a Social Security card by year of birth and sex."
),
}
lineage = self.operator.get_openlineage_facets_on_complete(None)
assert lineage.run_facets == {
"bigQueryJob": BigQueryJobRunFacet(
cached=False, billedBytes=None, properties=json.dumps(self.copy_job_details)
),
"externalQuery": ExternalQueryRunFacet(externalQueryId="job_id", source="bigquery"),
}
assert lineage.inputs == [
InputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.copy_job_source",
facets=expected_facets,
),
InputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.copy_job_source2",
facets=expected_facets,
),
]
assert lineage.outputs == [
OutputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.copy_job_result",
outputFacets={
"outputStatistics": OutputStatisticsOutputDatasetFacet(
rowCount=20, size=3800, fileCount=None
)
},
facets={
**expected_facets,
"columnLineage": ColumnLineageDatasetFacet(
fields={
col: Fields(
inputFields=[
InputField(
"bigquery", "airflow-openlineage.new_dataset.copy_job_source", col
),
InputField(
"bigquery", "airflow-openlineage.new_dataset.copy_job_source2", col
),
],
transformationType="IDENTITY",
transformationDescription="identical",
)
for col in ["state", "gender", "year", "name", "number"]
}
),
},
),
]
def test_get_openlineage_facets_on_complete_load_job(self):
self.client.get_job.return_value._properties = self.load_job_details
self.client.get_table.return_value = Table.from_api_repr(
read_common_json_file("out_table_details.json")
)
lineage = self.operator.get_openlineage_facets_on_complete(None)
assert lineage.run_facets == {
"bigQueryJob": BigQueryJobRunFacet(
cached=False, billedBytes=None, properties=json.dumps(self.load_job_details)
),
"externalQuery": ExternalQueryRunFacet(externalQueryId="job_id", source="bigquery"),
}
assert lineage.inputs == [
InputDataset(
namespace="gs://airflow-openlineage",
name="/",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
)
},
),
]
assert lineage.outputs == [
OutputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.job_load",
outputFacets={
"outputStatistics": OutputStatisticsOutputDatasetFacet(
rowCount=10, size=546, fileCount=None
)
},
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
),
"columnLineage": ColumnLineageDatasetFacet(
fields={
"name": Fields(
inputFields=[InputField("gs://airflow-openlineage", "/", "name")],
transformationType="IDENTITY",
transformationDescription="identical",
),
"total_people": Fields(
inputFields=[InputField("gs://airflow-openlineage", "/", "total_people")],
transformationType="IDENTITY",
transformationDescription="identical",
),
}
),
},
),
]
def test_get_openlineage_facets_on_complete_extract_job(self):
self.client.get_job.return_value._properties = self.extract_job_details
self.client.get_table.return_value = Table.from_api_repr(
read_common_json_file("out_table_details.json")
)
lineage = self.operator.get_openlineage_facets_on_complete(None)
assert lineage.run_facets == {
"bigQueryJob": BigQueryJobRunFacet(
cached=False, billedBytes=None, properties=json.dumps(self.extract_job_details)
),
"externalQuery": ExternalQueryRunFacet(externalQueryId="job_id", source="bigquery"),
}
assert lineage.inputs == [
InputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.extract_job_source",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
)
},
),
]
assert lineage.outputs == [
OutputDataset(
namespace="gs://airflow-openlineage",
name="extract_job_source",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
),
"columnLineage": ColumnLineageDatasetFacet(
fields={
"name": Fields(
inputFields=[
InputField(
"bigquery",
"airflow-openlineage.new_dataset.extract_job_source",
"name",
)
],
transformationType="IDENTITY",
transformationDescription="identical",
),
"total_people": Fields(
inputFields=[
InputField(
"bigquery",
"airflow-openlineage.new_dataset.extract_job_source",
"total_people",
)
],
transformationType="IDENTITY",
transformationDescription="identical",
),
}
),
},
),
]
def test_get_openlineage_facets_on_complete_script_job(self):
self.client.get_job.side_effect = [
MagicMock(_properties=self.script_job_details),
MagicMock(_properties=self.query_job_details),
]
self.client.get_table.side_effect = [
Table.from_api_repr(read_common_json_file("table_details.json")),
Table.from_api_repr(read_common_json_file("out_table_details.json")),
]
self.client.list_jobs.return_value = ["child_job_id"]
lineage = self.operator.get_openlineage_facets_on_complete(None)
self.script_job_details["configuration"]["query"].pop("query")
assert lineage.run_facets == {
"bigQueryJob": BigQueryJobRunFacet(
cached=False, billedBytes=120586240, properties=json.dumps(self.script_job_details)
),
"externalQuery": ExternalQueryRunFacet(externalQueryId="job_id", source="bigquery"),
}
assert lineage.inputs == [
InputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.test_table",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("state", "STRING", "2-digit state code"),
SchemaDatasetFacetFields("gender", "STRING", "Sex (M=male or F=female)"),
SchemaDatasetFacetFields("year", "INTEGER", "4-digit year of birth"),
SchemaDatasetFacetFields("name", "STRING", "Given name of a person at birth"),
SchemaDatasetFacetFields(
"number", "INTEGER", "Number of occurrences of the name"
),
]
),
"documentation": DocumentationDatasetFacet(
"The table contains the number of applicants for a Social Security card by year of birth and sex."
),
},
)
]
assert lineage.outputs == [
OutputDataset(
namespace="bigquery",
name="airflow-openlineage.new_dataset.output_table",
outputFacets={
"outputStatistics": OutputStatisticsOutputDatasetFacet(
rowCount=20, size=321, fileCount=None
)
},
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("name", "STRING"),
SchemaDatasetFacetFields("total_people", "INTEGER"),
]
),
},
),
]
def test_deduplicate_outputs(self):
outputs = [
None,
OutputDataset(
name="d1",
namespace="",
outputFacets={"outputStatistics": OutputStatisticsOutputDatasetFacet(3, 4)},
),
OutputDataset(
name="d1",
namespace="",
outputFacets={"outputStatistics": OutputStatisticsOutputDatasetFacet(3, 4)},
facets={"t1": "t1"},
),
OutputDataset(
name="d2",
namespace="",
outputFacets={"outputStatistics": OutputStatisticsOutputDatasetFacet(6, 7)},
facets={"t2": "t2"},
),
OutputDataset(
name="d2",
namespace="",
outputFacets={"outputStatistics": OutputStatisticsOutputDatasetFacet(60, 70)},
facets={"t20": "t20"},
),
]
result = self.operator._deduplicate_outputs(outputs)
assert len(result) == 2
first_result = result[0]
assert first_result.name == "d1"
assert first_result.facets == {"t1": "t1"}
second_result = result[1]
assert second_result.name == "d2"
assert second_result.facets == {"t20": "t20"}
def test_deduplicate_outputs_with_cll(self):
outputs = [
None,
OutputDataset(
name="a.b.c",
namespace="bigquery",
facets={
"columnLineage": ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "a.b.1", "c")],
transformationType="",
transformationDescription="",
),
"d": Fields(
inputFields=[InputField("bigquery", "a.b.2", "d")],
transformationType="",
transformationDescription="",
),
}
)
},
),
OutputDataset(
name="a.b.c",
namespace="bigquery",
facets={
"columnLineage": ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "a.b.3", "x")],
transformationType="",
transformationDescription="",
),
"e": Fields(
inputFields=[InputField("bigquery", "a.b.1", "e")],
transformationType="",
transformationDescription="",
),
}
)
},
),
OutputDataset(
name="x.y.z",
namespace="bigquery",
facets={
"columnLineage": ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "a.b.3", "x")],
transformationType="",
transformationDescription="",
)
}
)
},
),
]
result = self.operator._deduplicate_outputs(outputs)
assert len(result) == 2
first_result = result[0]
assert first_result.name == "a.b.c"
assert first_result.facets["columnLineage"] == ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "a.b.1", "c"), InputField("bigquery", "a.b.3", "x")],
transformationType="",
transformationDescription="",
),
"d": Fields(
inputFields=[InputField("bigquery", "a.b.2", "d")],
transformationType="",
transformationDescription="",
),
"e": Fields(
inputFields=[InputField("bigquery", "a.b.1", "e")],
transformationType="",
transformationDescription="",
),
}
)
second_result = result[1]
assert second_result.name == "x.y.z"
assert second_result.facets["columnLineage"] == ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "a.b.3", "x")],
transformationType="",
transformationDescription="",
)
}
)
@patch("airflow.providers.google.cloud.openlineage.mixins.get_facets_from_bq_table")
def test_get_table_facets_safely(self, mock_get_facets):
mock_get_facets.return_value = {"some": "facets"}
result = self.operator._get_table_facets_safely("some_table")
assert result == {"some": "facets"}
@patch("airflow.providers.google.cloud.openlineage.mixins.get_facets_from_bq_table")
def test_get_table_facets_safely_empty_when_error(self, mock_get_facets):
mock_get_facets.side_effect = ValueError("Some error")
result = self.operator._get_table_facets_safely("some_table")
assert result == {}
@patch("airflow.providers.google.cloud.openlineage.mixins.get_facets_from_bq_table")
def test_get_dataset(self, mock_get_facets):
mock_get_facets.return_value = {"some": "facets"}
table_ref = {"projectId": "p", "datasetId": "d", "tableId": "t"}
input_result = self.operator._get_dataset(table_ref, "input")
assert input_result == InputDataset("bigquery", "p.d.t", facets={"some": "facets"})
output_result = self.operator._get_dataset(table_ref, "output")
assert output_result == OutputDataset("bigquery", "p.d.t", facets={"some": "facets"})
with pytest.raises(ValueError, match="Invalid dataset_type. Must be 'input' or 'output'"):
self.operator._get_dataset(table_ref, "wrong")
@patch("airflow.providers.google.cloud.openlineage.mixins.get_facets_from_bq_table")
def test_get_input_dataset(self, mock_get_facets):
mock_get_facets.return_value = {"some": "facets"}
table_ref = {"projectId": "p", "datasetId": "d", "tableId": "t"}
expected_result = self.operator._get_dataset(table_ref, "input")
result = self.operator._get_input_dataset(table_ref)
assert result == expected_result
@patch("airflow.providers.google.cloud.openlineage.mixins.get_facets_from_bq_table")
def test_get_output_dataset(self, mock_get_facets):
mock_get_facets.return_value = {"some": "facets"}
table_ref = {"projectId": "p", "datasetId": "d", "tableId": "t"}
expected_result = self.operator._get_dataset(table_ref, "output")
result = self.operator._get_output_dataset(table_ref)
assert result == expected_result
@pytest.mark.parametrize("job_type", ("LOAD", "COPY", "EXTRACT"))
def test_get_bigquery_job_run_facet_non_query_jobs(self, job_type):
properties = {
"statistics": {"some": "stats"},
"configuration": {"jobType": job_type},
}
result = self.operator._get_bigquery_job_run_facet(properties)
assert result.cached is False
assert result.billedBytes is None
assert result.properties == json.dumps(properties)
@pytest.mark.parametrize("cache", (None, "false", False, 0))
def test_get_bigquery_job_run_facet_query_no_cache_and_with_bytes(self, cache):
properties = {
"statistics": {"query": {"cacheHit": cache, "totalBytesBilled": 10}},
"configuration": {"query": {"query": "SELECT ..."}, "jobType": "QUERY"},
}
result = self.operator._get_bigquery_job_run_facet(properties)
assert result.cached is False
assert result.billedBytes == 10
properties["configuration"]["query"].pop("query")
assert result.properties == json.dumps(properties)
@pytest.mark.parametrize("cache", ("true", True))
def test_get_bigquery_job_run_facet_query_with_cache_and_no_bytes(self, cache):
properties = {
"statistics": {
"query": {
"cacheHit": cache,
}
},
"configuration": {"query": {"query": "SELECT ..."}, "jobType": "QUERY"},
}
result = self.operator._get_bigquery_job_run_facet(properties)
assert result.cached is True
assert result.billedBytes is None
properties["configuration"]["query"].pop("query")
assert result.properties == json.dumps(properties)
def test_get_output_statistics_dataset_facet_query_no_query_plan(self):
properties = {
"statistics": {"query": {"totalBytesBilled": 10}},
"configuration": {"query": {"query": "SELECT ..."}, "jobType": "QUERY"},
}
result = self.operator._get_output_statistics_dataset_facet(properties)
assert result is None
def test_get_output_statistics_dataset_facet_query_no_stats(self):
properties = {
"statistics": {"query": {"totalBytesBilled": 10, "queryPlan": [{"test": "test"}]}},
"configuration": {"query": {"query": "SELECT ..."}, "jobType": "QUERY"},
}
result = self.operator._get_output_statistics_dataset_facet(properties)
assert result is None
def test_get_output_statistics_dataset_facet_query(self):
properties = {
"statistics": {
"query": {
"totalBytesBilled": 10,
"queryPlan": [{"recordsWritten": 123, "shuffleOutputBytes": "321"}],
}
},
"configuration": {"query": {"query": "SELECT ..."}, "jobType": "QUERY"},
}
result = self.operator._get_output_statistics_dataset_facet(properties)
assert result.rowCount == 123
assert result.size == 321
def test_get_output_statistics_dataset_facet_copy(self):
properties = {
"statistics": {
"copy": {
"copiedRows": 123,
"copiedLogicalBytes": 321,
}
},
"configuration": {"jobType": "COPY"},
}
result = self.operator._get_output_statistics_dataset_facet(properties)
assert result.rowCount == 123
assert result.size == 321
def test_get_output_statistics_dataset_facet_load(self):
properties = {
"statistics": {
"load": {
"outputRows": 123,
"outputBytes": 321,
}
},
"configuration": {"jobType": "LOAD"},
}
result = self.operator._get_output_statistics_dataset_facet(properties)
assert result.rowCount == 123
assert result.size == 321
def test_get_column_level_lineage_facet(self):
result = self.operator._get_column_level_lineage_facet_for_query_job(
QUERY_JOB_PROPERTIES, OUTPUT_DATASET, INPUT_DATASETS
)
assert result == ColumnLineageDatasetFacet(
fields={
col: Fields(
inputFields=[
InputField("bigquery", "default_project.default_dataset.source_table2", col),
InputField("bigquery", "source_project.source_dataset.source_table", col),
],
transformationType="",
transformationDescription="",
)
for col in ("a", "b", "c")
}
)
def test_get_column_level_lineage_facet_early_exit_empty_cll_from_parser(self):
properties = {"configuration": {"query": {"query": "SELECT 1"}}}
assert (
self.operator._get_column_level_lineage_facet_for_query_job(
properties, OUTPUT_DATASET, INPUT_DATASETS
)
is None
)
assert (
self.operator._get_column_level_lineage_facet_for_query_job({}, OUTPUT_DATASET, INPUT_DATASETS)
is None
)
def test_get_column_level_lineage_facet_early_exit_output_table_id_mismatch(self):
output = copy.deepcopy(OUTPUT_DATASET)
output.name = "different.name.table"
assert (
self.operator._get_column_level_lineage_facet_for_query_job(
QUERY_JOB_PROPERTIES, output, INPUT_DATASETS
)
is None
)
def test_get_column_level_lineage_facet_early_exit_output_columns_mismatch(self):
output = copy.deepcopy(OUTPUT_DATASET)
output.facets["schema"].fields = [
SchemaDatasetFacetFields("different_col", "STRING"),
]
assert (
self.operator._get_column_level_lineage_facet_for_query_job(
QUERY_JOB_PROPERTIES, output, INPUT_DATASETS
)
is None
)
def test_get_column_level_lineage_facet_early_exit_wrong_parsed_input_tables(self):
properties = {
"configuration": {
"query": {
"query": """
INSERT INTO dest_project.dest_dataset.dest_table
SELECT a, b, c FROM some.wrong.source_table
""",
}
}
}
assert (
self.operator._get_column_level_lineage_facet_for_query_job(
properties, OUTPUT_DATASET, INPUT_DATASETS
)
is None
)
def test_get_column_level_lineage_facet_early_exit_wrong_parsed_input_columns(self):
properties = {
"configuration": {
"query": {
"query": """
INSERT INTO dest_project.dest_dataset.dest_table
SELECT wrong_col, wrong2, wrong3 FROM source_project.source_dataset.source_table
""",
}
}
}
assert (
self.operator._get_column_level_lineage_facet_for_query_job(
properties, OUTPUT_DATASET, INPUT_DATASETS
)
is None
)
def test_get_qualified_name_from_parse_result(self):
class _Table: # Replacement for SQL parser TableMeta
database = "project"
schema = "dataset"
name = "table"
class _TableNoSchema: # Replacement for SQL parser TableMeta
database = None
schema = "dataset"
name = "table"
class _TableNoSchemaNoDb: # Replacement for SQL parser TableMeta
database = None
schema = None
name = "table"
result = self.operator._get_qualified_name_from_parse_result(
table=_Table(),
default_project="default_project",
default_dataset="default_dataset",
)
assert result == "project.dataset.table"
result = self.operator._get_qualified_name_from_parse_result(
table=_TableNoSchema(),
default_project="default_project",
default_dataset="default_dataset",
)
assert result == "default_project.dataset.table"
result = self.operator._get_qualified_name_from_parse_result(
table=_TableNoSchemaNoDb(),
default_project="default_project",
default_dataset="default_dataset",
)
assert result == "default_project.default_dataset.table"
def test_extract_default_dataset_and_project(self):
properties = {"configuration": {"query": {"defaultDataset": {"datasetId": "default_dataset"}}}}
result = self.operator._extract_default_dataset_and_project(properties, "default_project")
assert result == ("default_dataset", "default_project")
properties = {
"configuration": {
"query": {"defaultDataset": {"datasetId": "default_dataset", "projectId": "default_project"}}
}
}
result = self.operator._extract_default_dataset_and_project(properties, "another_project")
assert result == ("default_dataset", "default_project")
result = self.operator._extract_default_dataset_and_project({}, "default_project")
assert result == ("", "default_project")
def test_validate_output_table_id_no_table(self):
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("SELECT 1"))
assert parse_result.out_tables == []
assert self.operator._validate_output_table_id(parse_result, None, None, None) is False
def test_validate_output_table_id_multiple_tables(self):
query = "INSERT INTO a.b.c VALUES (1); INSERT INTO d.e.f VALUES (2);"
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string(query))
assert len(parse_result.out_tables) == 2
assert self.operator._validate_output_table_id(parse_result, None, None, None) is False
def test_validate_output_table_id_mismatch(self):
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("INSERT INTO a.b.c VALUES (1)"))
assert len(parse_result.out_tables) == 1
assert parse_result.out_tables[0].qualified_name == "a.b.c"
assert (
self.operator._validate_output_table_id(parse_result, OutputDataset("", "d.e.f"), None, None)
is False
)
def test_validate_output_table_id(self):
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("INSERT INTO a.b.c VALUES (1)"))
assert len(parse_result.out_tables) == 1
assert parse_result.out_tables[0].qualified_name == "a.b.c"
assert (
self.operator._validate_output_table_id(parse_result, OutputDataset("", "a.b.c"), None, None)
is True
)
def test_validate_output_table_id_query_with_table_name_only(self):
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("INSERT INTO c VALUES (1)"))
assert len(parse_result.out_tables) == 1
assert parse_result.out_tables[0].qualified_name == "c"
assert (
self.operator._validate_output_table_id(parse_result, OutputDataset("", "a.b.c"), "a", "b")
is True
)
def test_extract_column_names_dataset_without_schema(self):
assert self.operator._extract_column_names(Dataset("a", "b")) == []
def test_extract_column_names_dataset_(self):
ds = Dataset(
"a",
"b",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("col1", "STRING"),
SchemaDatasetFacetFields("col2", "STRING"),
]
)
},
)
assert self.operator._extract_column_names(ds) == ["col1", "col2"]
def test_validate_output_columns_mismatch(self):
ds = OutputDataset(
"a",
"b",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("col1", "STRING"),
SchemaDatasetFacetFields("col2", "STRING"),
]
)
},
)
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("SELECT a , b FROM c"))
assert self.operator._validate_output_columns(parse_result, ds) is False
def test_validate_output_columns(self):
ds = OutputDataset(
"a",
"b",
facets={
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields("a", "STRING"),
SchemaDatasetFacetFields("b", "STRING"),
]
)
},
)
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("SELECT a , b FROM c"))
assert self.operator._validate_output_columns(parse_result, ds) is True
def test_extract_parsed_input_tables(self):
query = "INSERT INTO x SELECT a, b from project1.ds1.tb1; INSERT INTO y SELECT c, d from tb2;"
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string(query))
assert self.operator._extract_parsed_input_tables(parse_result, "default_project", "default_ds") == {
"project1.ds1.tb1": ["a", "b"],
"default_project.default_ds.tb2": ["c", "d"],
}
def test_extract_parsed_input_tables_no_cll(self):
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string("SELECT 1"))
assert self.operator._extract_parsed_input_tables(parse_result, "p", "d") == {}
def test_validate_input_tables_mismatch(self):
result = self.operator._validate_input_tables({"a": None, "b": None}, {"a": None, "c": None})
assert result is False
def test_validate_input_tables_bq_has_more_tables(self):
result = self.operator._validate_input_tables({"a": None}, {"a": None, "c": None})
assert result is True
def test_validate_input_tables_empty(self):
result = self.operator._validate_input_tables({}, {"a": None, "c": None})
assert result is False
def test_validate_input_columns_mismatch(self):
result = self.operator._validate_input_columns(
{"a": ["1", "2"], "b": ["3", "4"]}, {"a": ["1", "2", "3"], "c": ["4", "5"]}
)
assert result is False
def test_validate_input_columns_bq_has_more_cols(self):
result = self.operator._validate_input_columns(
{"a": ["1", "2"]}, {"a": ["1", "2", "3"], "c": ["4", "5"]}
)
assert result is True
def test_validate_input_columns_empty(self):
result = self.operator._validate_input_columns({}, {"a": ["1", "2", "3"], "c": ["4", "5"]})
assert result is False
def test_generate_column_lineage_facet(self):
query = "INSERT INTO b.c SELECT c, d from tb2;"
parse_result = SQLParser("bigquery").parse(SQLParser.split_sql_string(query))
result = self.operator._generate_column_lineage_facet(parse_result, "default_project", "default_ds")
assert result == ColumnLineageDatasetFacet(
fields={
"c": Fields(
inputFields=[InputField("bigquery", "default_project.default_ds.tb2", "c")],
transformationType="",
transformationDescription="",
),
"d": Fields(
inputFields=[InputField("bigquery", "default_project.default_ds.tb2", "d")],
transformationType="",
transformationDescription="",
),
}
)
def test_project_id_selection(self):
"""
Check if project_id set via an argument to the operator takes prevalence over project_id set in a
connection.
"""
from airflow.providers.google.cloud.operators.cloud_base import GoogleCloudBaseOperator
class TestOperator(GoogleCloudBaseOperator, _BigQueryInsertJobOperatorOpenLineageMixin):
def __init__(self, project_id: str | None = None, **_):
self.project_id = project_id
self.job_id = "foobar"
self.location = "foobar"
self.sql = "foobar"
# First test task where project_id is set explicitly
test = TestOperator(project_id="project_a")
test.hook = MagicMock()
test.hook.project_id = "project_b"
test._client = MagicMock()
test.get_openlineage_facets_on_complete(None)
_, kwargs = test.hook.get_client.call_args
assert kwargs["project_id"] == "project_a"
# Then test task where project_id is inherited from the hook
test = TestOperator()
test.hook = MagicMock()
test.hook.project_id = "project_b"
test._client = MagicMock()
test.get_openlineage_facets_on_complete(None)
_, kwargs = test.hook.get_client.call_args
assert kwargs["project_id"] == "project_b"
| TestBigQueryOpenLineageMixin |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet.py | {
"start": 1513,
"end": 1781
} | class ____:
def __init__(self, ksize):
self.ksize = ksize
def forward(self, X):
return tf.nn.avg_pool(
X,
ksize=[1, self.ksize, self.ksize, 1],
strides=[1, 1, 1, 1],
padding='VALID'
)
def get_params(self):
return []
| AvgPool |
python | PrefectHQ__prefect | tests/utilities/test_filesystem.py | {
"start": 4908,
"end": 8215
} | class ____:
@pytest.mark.skipif(sys.platform == "win32", reason="This is a unix-specific test")
@pytest.mark.parametrize(
"path_str,expected",
[
("mypath.py:my_flow", "mypath.py:my_flow"),
(r"my\test\path.py:my_flow", "my/test/path.py:my_flow"),
("my\\test\\path.py:my_flow", "my/test/path.py:my_flow"),
("my/test/path.py:my_flow", "my/test/path.py:my_flow"),
],
)
def test_paths_on_unix(self, path_str, expected):
new_path = relative_path_to_current_platform(path_str)
assert isinstance(new_path, PosixPath)
assert str(new_path) == expected
@pytest.mark.skipif(
sys.platform != "win32", reason="This is a windows-specific test"
)
@pytest.mark.parametrize(
"path_str,expected",
[
("mypath.py:my_flow", "mypath.py:my_flow"),
(r"my\test\path.py:my_flow", "my\\test\\path.py:my_flow"),
("my\\test\\path.py:my_flow", "my\\test\\path.py:my_flow"),
("my/test/path.py:my_flow", "my\\test\\path.py:my_flow"),
],
)
def test_paths_on_windows(self, path_str, expected):
new_path = relative_path_to_current_platform(path_str)
assert isinstance(new_path, WindowsPath)
assert str(new_path) == expected
def test_get_open_file_limit():
"""
Test that we can get the open file limit. Although this is a simple test, it
ensures that the function works as expected on both Windows and Unix.
"""
limit = get_open_file_limit()
# The functions that check the open file limit on either Windows or Unix
# have an 'Any' return type, so this assertion ensures any changes to the
# function don't break its contract.
assert isinstance(limit, int)
# It shouldn't be possible to have a negative open file limit.
assert limit >= 0
# The open file limit should not equal the default value of 200
# returned if an error occurs.
assert limit != 200
@pytest.mark.skipif(os.name == "nt", reason="This is a Unix-specific test")
def test_get_open_file_limit_exception_unix(monkeypatch):
import resource
def mock_getrlimit(*args, **kwargs):
raise OSError
monkeypatch.setattr(resource, "getrlimit", mock_getrlimit)
assert get_open_file_limit() == 200
@pytest.mark.skipif(os.name != "nt", reason="This is a Windows-specific test")
def test_get_open_file_limit_exception_windows(monkeypatch):
import ctypes
# General error when calling _getmaxstdio
def mock_getmaxstdio_error(*args, **kwargs):
raise OSError
# Either ucrtbase or _getmaxstdio is missing
def mock_getmaxstdio_missing(*args, **kwargs):
raise AttributeError
# Invalid argument(s) passed to _getmaxstdio
def mock_getmaxstdio_invalid_args(*args, **kwargs):
raise ValueError
monkeypatch.setattr(ctypes.cdll.ucrtbase, "_getmaxstdio", mock_getmaxstdio_error)
assert get_open_file_limit() == 200
monkeypatch.setattr(ctypes.cdll.ucrtbase, "_getmaxstdio", mock_getmaxstdio_missing)
assert get_open_file_limit() == 200
monkeypatch.setattr(
ctypes.cdll.ucrtbase, "_getmaxstdio", mock_getmaxstdio_invalid_args
)
assert get_open_file_limit() == 200
| TestPlatformSpecificRelpath |
python | doocs__leetcode | solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/Solution.py | {
"start": 0,
"end": 289
} | class ____:
def findMinFibonacciNumbers(self, k: int) -> int:
a = b = 1
while b <= k:
a, b = b, a + b
ans = 0
while k:
if k >= b:
k -= b
ans += 1
a, b = b - a, a
return ans
| Solution |
python | getsentry__sentry | tests/sentry/api/endpoints/test_api_authorizations.py | {
"start": 571,
"end": 1661
} | class ____(ApiAuthorizationsTest):
def test_simple(self) -> None:
app = ApiApplication.objects.create(name="test", owner=self.user)
auth = ApiAuthorization.objects.create(application=app, user=self.user)
ApiAuthorization.objects.create(
application=app, user=self.create_user("example@example.com")
)
response = self.get_success_response()
assert len(response.data) == 1
assert response.data[0]["id"] == str(auth.id)
assert response.data[0]["organization"] is None
def test_org_level_auth(self) -> None:
org = self.create_organization(owner=self.user, slug="test-org-slug")
app = ApiApplication.objects.create(
name="test", owner=self.user, requires_org_level_access=True
)
ApiAuthorization.objects.create(application=app, user=self.user, organization_id=org.id)
response = self.get_success_response()
assert len(response.data) == 1
assert response.data[0]["organization"]["slug"] == org.slug
@control_silo_test
| ApiAuthorizationsListTest |
python | gevent__gevent | src/gevent/threadpool.py | {
"start": 22453,
"end": 22706
} | class ____(object):
def send(self):
pass
close = stop = send
def __call__(self, result):
"fake out for 'receiver'"
def __bool__(self):
return False
__nonzero__ = __bool__
_FakeAsync = _FakeAsync()
| _FakeAsync |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py | {
"start": 1378,
"end": 1515
} | class ____:
@check_permission("fake_permission")
def mutate(self, graphene_info: ResolveInfo, **_kwargs):
pass
| FakeMutation |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 4263,
"end": 4349
} | class ____(HashAlgorithm):
name = "md5"
digest_size = 16
block_size = 64
| MD5 |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_team_members.py | {
"start": 355,
"end": 561
} | class ____(GQLResult):
team_members: List[TeamRegistryMemberFragment] = Field(alias="teamMembers")
RegistryTeamMembers.model_rebuild()
RegistryTeamMembersProject.model_rebuild()
| RegistryTeamMembersProject |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 13142,
"end": 15930
} | class ____:
def test_default_project(self, temp_dir, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(temp_dir, config=config)
environment = MockEnvironment(
temp_dir,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
(temp_dir / "pyproject.toml").touch()
with temp_dir.as_cwd():
assert environment.skip_install is environment.skip_install is False
def test_default_no_project(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
assert environment.skip_install is environment.skip_install is True
def test_not_boolean(self, isolation, isolated_data_dir, platform, global_application):
config = {
"project": {"name": "my_app", "version": "0.0.1"},
"tool": {"hatch": {"envs": {"default": {"skip-install": 9000}}}},
}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
with pytest.raises(TypeError, match="Field `tool.hatch.envs.default.skip-install` must be a boolean"):
_ = environment.skip_install
def test_enable(self, isolation, isolated_data_dir, platform, global_application):
config = {
"project": {"name": "my_app", "version": "0.0.1"},
"tool": {"hatch": {"envs": {"default": {"skip-install": True}}}},
}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
assert environment.skip_install is True
| TestSkipInstall |
python | streamlit__streamlit | lib/streamlit/runtime/session_manager.py | {
"start": 1150,
"end": 1265
} | class ____(Exception):
"""Raised by operations on a disconnected SessionClient."""
| SessionClientDisconnectedError |
python | sqlalchemy__sqlalchemy | examples/graphs/directed_graph.py | {
"start": 331,
"end": 606
} | class ____(Base):
__tablename__ = "node"
node_id = Column(Integer, primary_key=True)
def higher_neighbors(self):
return [x.higher_node for x in self.lower_edges]
def lower_neighbors(self):
return [x.lower_node for x in self.higher_edges]
| Node |
python | django__django | django/contrib/gis/db/backends/postgis/models.py | {
"start": 1431,
"end": 2002
} | class ____(models.Model, SpatialRefSysMixin):
"""
The 'spatial_ref_sys' table from PostGIS. See the PostGIS
documentation at Ch. 4.2.1.
"""
srid = models.IntegerField(primary_key=True)
auth_name = models.CharField(max_length=256)
auth_srid = models.IntegerField()
srtext = models.CharField(max_length=2048)
proj4text = models.CharField(max_length=2048)
class Meta:
app_label = "gis"
db_table = "spatial_ref_sys"
managed = False
@property
def wkt(self):
return self.srtext
| PostGISSpatialRefSys |
python | automl__auto-sklearn | autosklearn/pipeline/components/data_preprocessing/minority_coalescense/no_coalescense.py | {
"start": 430,
"end": 1861
} | class ____(AutoSklearnPreprocessingAlgorithm):
def __init__(
self,
feat_type: Optional[FEAT_TYPE_TYPE] = None,
random_state: Optional[Union[int, np.random.RandomState]] = None,
) -> None:
pass
def fit(
self, X: np.array, y: Optional[PIPELINE_DATA_DTYPE] = None
) -> PIPELINE_DATA_DTYPE:
self.preprocessor = "passthrough"
return self
def transform(self, X: PIPELINE_DATA_DTYPE) -> PIPELINE_DATA_DTYPE:
return X
@staticmethod
def get_properties(
dataset_properties: Optional[DATASET_PROPERTIES_TYPE] = None,
) -> Dict[str, Optional[Union[str, int, bool, Tuple]]]:
return {
"shortname": "no coalescence",
"name": "No categorical variable coalescence",
"handles_regression": True,
"handles_classification": True,
"handles_multiclass": True,
"handles_multilabel": True,
"handles_multioutput": True,
"handles_sparse": True,
"handles_dense": True,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (INPUT,),
}
@staticmethod
def get_hyperparameter_search_space(
feat_type: Optional[FEAT_TYPE_TYPE] = None,
dataset_properties: Optional[DATASET_PROPERTIES_TYPE] = None,
) -> ConfigurationSpace:
cs = ConfigurationSpace()
return cs
| NoCoalescence |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 62067,
"end": 62230
} | class ____(Qwen3MoeSparseMoeBlock):
def __init__(self, config: Qwen3OmniMoeThinkerConfig):
super().__init__(config)
| Qwen3OmniMoeThinkerTextSparseMoeBlock |
python | ray-project__ray | python/ray/llm/_internal/common/callbacks/cloud_downloader.py | {
"start": 893,
"end": 3066
} | class ____(CallbackBase):
"""Callback that downloads files from cloud storage before model files are downloaded.
This callback expects self.kwargs to contain a 'paths' field which should be
a list of tuples, where each tuple contains (cloud_uri, local_path) strings.
Supported cloud storage URIs: s3://, gs://, abfss://, azure://
Example:
```
from ray.llm._internal.common.callbacks.cloud_downloader import CloudDownloader
from ray.llm._internal.serve.core.configs.llm_config import LLMConfig
config = LLMConfig(
...
callback_config={
"callback_class": CloudDownloader,
"callback_kwargs": {
"paths": [
("s3://bucket/path/to/file.txt", "/local/path/to/file.txt"),
("gs://bucket/path/to/file.txt", "/local/path/to/file.txt"),
]
}
}
...
)
```
"""
def __init__(self, **kwargs: Any) -> None:
"""Initialize the CloudDownloader callback.
Args:
**kwargs: Keyword arguments passed to the callback as a dictionary.
Must contain a 'paths' field with a list of (cloud_uri, local_path) tuples.
"""
super().__init__(**kwargs)
# Validate configuration using Pydantic
if "paths" not in self.kwargs:
raise ValueError("CloudDownloader requires 'paths' field in kwargs")
CloudDownloaderConfig.model_validate(self.kwargs)
def on_before_download_model_files_distributed(self) -> None:
"""Download files from cloud storage to local paths before model files are downloaded."""
from ray.llm._internal.common.utils.cloud_utils import CloudFileSystem
paths = self.kwargs["paths"]
start_time = time.monotonic()
for cloud_uri, local_path in paths:
CloudFileSystem.download_files(path=local_path, bucket_uri=cloud_uri)
end_time = time.monotonic()
logger.info(
f"CloudDownloader: Files downloaded in {end_time - start_time} seconds"
)
| CloudDownloader |
python | aio-libs__aiohttp | aiohttp/compression_utils.py | {
"start": 9108,
"end": 9912
} | class ____:
# Supports both 'brotlipy' and 'Brotli' packages
# since they share an import name. The top branches
# are for 'brotlipy' and bottom branches for 'Brotli'
def __init__(self) -> None:
if not HAS_BROTLI:
raise RuntimeError(
"The brotli decompression is not available. "
"Please install `Brotli` module"
)
self._obj = brotli.Decompressor()
def decompress_sync(self, data: Buffer) -> bytes:
if hasattr(self._obj, "decompress"):
return cast(bytes, self._obj.decompress(data))
return cast(bytes, self._obj.process(data))
def flush(self) -> bytes:
if hasattr(self._obj, "flush"):
return cast(bytes, self._obj.flush())
return b""
| BrotliDecompressor |
python | pypa__warehouse | tests/unit/oidc/forms/test_activestate.py | {
"start": 671,
"end": 3347
} | class ____:
def test_validate(self, monkeypatch, project_service):
route_url = pretend.stub()
data = MultiDict(
{
"organization": "some-org",
"project": "some-project",
"actor": "someuser",
"project_name": "some-project",
}
)
form = activestate.PendingActiveStatePublisherForm(
MultiDict(data),
route_url=route_url,
check_project_name=project_service.check_project_name,
user=pretend.stub(),
)
# Test built-in validations
monkeypatch.setattr(form, "_lookup_actor", lambda *o: {"user_id": "some-id"})
monkeypatch.setattr(form, "_lookup_organization", lambda *o: None)
assert form._check_project_name == project_service.check_project_name
assert form._route_url == route_url
assert form.validate()
def test_validate_project_name_already_in_use_owner(
self, pyramid_config, project_service
):
route_url = pretend.call_recorder(lambda *args, **kwargs: "")
user = UserFactory.create()
project = ProjectFactory.create(name="some-project")
RoleFactory.create(user=user, project=project)
form = activestate.PendingActiveStatePublisherForm(
route_url=route_url,
check_project_name=project_service.check_project_name,
user=user,
)
field = pretend.stub(data="some-project")
with pytest.raises(wtforms.validators.ValidationError):
form.validate_project_name(field)
# The project settings URL is only shown in the error message if
# the user is the owner of the project
assert route_url.calls == [
pretend.call(
"manage.project.settings.publishing",
project_name="some-project",
_query={"provider": {"activestate"}},
)
]
def test_validate_project_name_already_in_use_not_owner(
self, pyramid_config, project_service
):
route_url = pretend.call_recorder(lambda *args, **kwargs: "")
user = UserFactory.create()
ProjectFactory.create(name="some-project")
form = activestate.PendingActiveStatePublisherForm(
route_url=route_url,
check_project_name=project_service.check_project_name,
user=user,
)
field = pretend.stub(data="some-project")
with pytest.raises(wtforms.validators.ValidationError):
form.validate_project_name(field)
assert route_url.calls == []
| TestPendingActiveStatePublisherForm |
python | astropy__astropy | astropy/visualization/basic_rgb.py | {
"start": 441,
"end": 7277
} | class ____:
"""
Class to map red, blue, green images into either a normalized float or
an 8-bit image, by performing optional clipping and applying
a scaling function to each band independently.
Parameters
----------
interval : `~astropy.visualization.BaseInterval` subclass instance or array-like, optional
The interval object to apply to the data (either a single instance or
an array for R, G, B). Default is
`~astropy.visualization.ManualInterval`.
stretch : `~astropy.visualization.BaseStretch` subclass instance, optional
The stretch object to apply to the data. Default is
`~astropy.visualization.LinearStretch`.
"""
def __init__(
self, interval=ManualInterval(vmin=0, vmax=None), stretch=LinearStretch()
):
try:
len(interval)
except TypeError:
interval = 3 * [interval]
if len(interval) != 3:
raise ValueError("please provide 1 or 3 instances for interval.")
self.intervals = interval
self.stretch = stretch
def make_rgb_image(self, image_r, image_g, image_b, output_dtype=np.uint8):
"""
Convert 3 arrays, image_r, image_g, and image_b into a RGB image,
either as an 8-bit per-channel or normalized image.
The input images can be int or float, and in any range or bit-depth,
but must have the same shape (NxM).
Parameters
----------
image_r : ndarray
Image to map to red.
image_g : ndarray
Image to map to green.
image_b : ndarray
Image to map to blue.
output_dtype : numpy scalar type, optional
Image output format. Default is np.uint8.
Returns
-------
RGBimage : ndarray
RGB color image with the specified format as an NxMx3 numpy array.
"""
if output_dtype not in _OUTPUT_IMAGE_FORMATS:
raise ValueError(f"'output_dtype' must be one of {_OUTPUT_IMAGE_FORMATS}!")
image_r = np.asarray(image_r)
image_g = np.asarray(image_g)
image_b = np.asarray(image_b)
if (image_r.shape != image_g.shape) or (image_g.shape != image_b.shape):
msg = "The image shapes must match. r: {}, g: {} b: {}"
raise ValueError(msg.format(image_r.shape, image_g.shape, image_b.shape))
image_rgb = self.apply_mappings(image_r, image_g, image_b)
if np.issubdtype(output_dtype, float):
conv_images = self._convert_images_to_float(image_rgb, output_dtype)
elif np.issubdtype(output_dtype, np.unsignedinteger):
conv_images = self._convert_images_to_uint(image_rgb, output_dtype)
return np.dstack(conv_images)
def apply_mappings(self, image_r, image_g, image_b):
"""
Apply mapping stretch and intervals to convert images image_r, image_g,
and image_b to a triplet of normalized images.
Parameters
----------
image_r : ndarray
Intensity of image to be mapped to red
image_g : ndarray
Intensity of image to be mapped to green.
image_b : ndarray
Intensity of image to be mapped to blue.
Returns
-------
image_rgb : ndarray
Triplet of mapped images based on the specified (per-band)
intervals and the stretch function
"""
image_rgb = [image_r, image_g, image_b]
for i, img in enumerate(image_rgb):
# Using syntax from mpl_normalize.ImageNormalize,
# but NOT using that class to avoid dependency on matplotlib.
# Define vmin and vmax
vmin, vmax = self.intervals[i].get_limits(img)
# copy because of in-place operations after
img = np.array(img, copy=True, dtype=float)
# Normalize based on vmin and vmax
np.subtract(img, vmin, out=img)
np.true_divide(img, vmax - vmin, out=img)
# Clip to the 0 to 1 range
img = np.clip(img, 0.0, 1.0, out=img)
# Stretch values
img = self.stretch(img, out=img, clip=False)
image_rgb[i] = img
return np.asarray(image_rgb)
def _convert_images_to_float(self, image_rgb, output_dtype):
"""
Convert a triplet of normalized images to float.
"""
return image_rgb.astype(output_dtype)
def _convert_images_to_uint(self, image_rgb, output_dtype):
"""
Convert a triplet of normalized images to unsigned integer images
"""
pixmax = float(np.iinfo(output_dtype).max)
image_rgb *= pixmax
return image_rgb.astype(output_dtype)
def make_rgb(
image_r,
image_g,
image_b,
interval=ManualInterval(vmin=0, vmax=None),
stretch=LinearStretch(),
filename=None,
output_dtype=np.uint8,
):
"""
Base class to return a Red/Green/Blue color image from 3 images using
a specified stretch and interval, for each band *independently*.
The input images can be int or float, and in any range or bit-depth,
but must have the same shape (NxM).
For a more detailed look at the use of this method, see the document
:ref:`astropy:astropy-visualization-rgb`.
Parameters
----------
image_r : ndarray
Image to map to red.
image_g : ndarray
Image to map to green.
image_b : ndarray
Image to map to blue.
interval : `~astropy.visualization.BaseInterval` subclass instance or array-like, optional
The interval object to apply to the data (either a single instance or
an array for R, G, B). Default is
`~astropy.visualization.ManualInterval` with vmin=0.
stretch : `~astropy.visualization.BaseStretch` subclass instance, optional
The stretch object to apply to the data. Default is
`~astropy.visualization.LinearStretch`.
filename : str, optional
Write the resulting RGB image to a file (file type determined
from extension).
output_dtype : numpy scalar type, optional
Image output data type. Default is np.uint8.
Returns
-------
rgb : ndarray
RGB (either float or integer with 8-bits per channel) color image
as an NxMx3 numpy array.
Notes
-----
This procedure of clipping and then scaling is similar to the DS9
image algorithm (see the DS9 reference guide:
http://ds9.si.edu/doc/ref/how.html).
"""
map_ = RGBImageMapping(interval=interval, stretch=stretch)
rgb = map_.make_rgb_image(image_r, image_g, image_b, output_dtype=output_dtype)
if filename:
import matplotlib.image
matplotlib.image.imsave(filename, rgb, origin="lower")
return rgb
| RGBImageMapping |
python | kamyu104__LeetCode-Solutions | Python/check-divisibility-by-digit-sum-and-product.py | {
"start": 39,
"end": 357
} | class ____(object):
def checkDivisibility(self, n):
"""
:type n: int
:rtype: bool
"""
curr = n
total, product = 0, 1
while curr:
curr, r = divmod(curr, 10)
total += r
product *= r
return n%(total+product) == 0
| Solution |
python | walkccc__LeetCode | solutions/2814. Minimum Time Takes to Reach Destination Without Drowning/2814.py | {
"start": 0,
"end": 1727
} | class ____:
def minimumSeconds(self, land: list[list[str]]) -> int:
self.DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(land)
n = len(land[0])
floodDist = self._getFloodDist(land)
startPos = self._getStartPos(land, 'S')
q = collections.deque([startPos])
seen = {startPos}
step = 1
while q:
for _ in range(len(q)):
i, j = q.popleft()
for dx, dy in self.DIRS:
x = i + dx
y = j + dy
if x < 0 or x == m or y < 0 or y == n:
continue
if land[x][y] == 'D':
return step
if floodDist[x][y] <= step or land[x][y] == 'X' or (x, y) in seen:
continue
q.append((x, y))
seen.add((x, y))
step += 1
return -1
def _getFloodDist(self, land: list[list[str]]) -> list[list[int]]:
m = len(land)
n = len(land[0])
dist = [[math.inf] * n for _ in range(m)]
q = collections.deque()
seen = set()
for i, row in enumerate(land):
for j, cell in enumerate(row):
if cell == '*':
q.append((i, j))
seen.add((i, j))
d = 0
while q:
for _ in range(len(q)):
i, j = q.popleft()
dist[i][j] = d
for dx, dy in self.DIRS:
x = i + dx
y = j + dy
if x < 0 or x == m or y < 0 or y == n:
continue
if land[x][y] in 'XD' or (x, y) in seen:
continue
q.append((x, y))
seen.add((x, y))
d += 1
return dist
def _getStartPos(self, land: list[list[str]], c: str) -> tuple[int, int]:
for i, row in enumerate(land):
for j, cell in enumerate(row):
if cell == c:
return i, j
| Solution |
python | django__django | tests/migrations/test_migrations_plan/0001_initial.py | {
"start": 175,
"end": 598
} | class ____(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
"Salamander",
[
("id", models.AutoField(primary_key=True)),
("tail", models.IntegerField(default=0)),
("silly_field", models.BooleanField(default=False)),
],
),
migrations.RunPython(grow_tail, shrink_tail),
]
| Migration |
python | ray-project__ray | release/release_logs/fetch_release_logs.py | {
"start": 2067,
"end": 6042
} | class ____:
job: Job
id: str
def get_buildkite_api() -> Buildkite:
bk = Buildkite()
buildkite_token = fetch_buildkite_token()
bk.set_access_token(buildkite_token)
return bk
def fetch_buildkite_token() -> str:
buildkite_token = boto3.client(
"secretsmanager", region_name="us-west-2"
).get_secret_value(
SecretId="arn:aws:secretsmanager:us-west-2:029272617770:secret:"
"buildkite/ro-token"
)[
"SecretString"
]
os.environ["BUILDKITE_TOKEN"] = buildkite_token
return buildkite_token
def get_results_from_build_collection(
bk: Buildkite, build_dict_list: List[Dict]
) -> Dict[str, Dict]:
results_to_fetch = RESULTS_TO_FETCH.copy()
fetched_results = {}
for build_dict in sorted(build_dict_list, key=lambda bd: -bd["number"]):
if not results_to_fetch:
break
build = Build(
id=build_dict["id"],
number=build_dict["number"],
commit=build_dict["commit"],
job_dict_list=build_dict["jobs"],
)
build_results = get_results_from_build(bk, build, results_to_fetch)
fetched_results.update(build_results)
return fetched_results
def get_results_from_build(bk: Buildkite, build: Build, results_to_fetch: Dict) -> Dict:
fetched_results = {}
for job_dict in build.job_dict_list:
if not results_to_fetch:
break
job = Job(build=build, id=job_dict["id"], name=job_dict.get("name", None))
if not job.name:
continue
for job_regex, filename in list(results_to_fetch.items()):
if re.match(job_regex, job.name):
result = get_results_artifact_for_job(bk, job=job)
if not result:
continue
fetched_results[filename] = result
results_to_fetch.pop(job_regex)
print(f"Fetched {filename} for commit {job.build.commit}")
return fetched_results
def get_results_artifact_for_job(bk: Buildkite, job: Job) -> Optional[Dict]:
artifacts = bk.artifacts().list_artifacts_for_job(
organization=job.build.organization,
pipeline=job.build.pipeline,
build=job.build.number,
job=job.id,
)
for artifact in artifacts:
if "result.json" in artifact["filename"]:
artifact = Artifact(job=job, id=artifact["id"])
return download_results_artifact(bk=bk, artifact=artifact)
return None
def download_results_artifact(bk: Buildkite, artifact: Artifact) -> Dict:
blob = bk.artifacts().download_artifact(
organization=artifact.job.build.organization,
pipeline=artifact.job.build.pipeline,
build=artifact.job.build.number,
job=artifact.job.id,
artifact=artifact.id,
)
data_dict = json.loads(blob)
return data_dict.get("results", {})
def write_results(log_dir: Path, fetched_results: Dict[str, Any]) -> None:
log_dir.mkdir(parents=True, exist_ok=True)
for filepath, content in fetched_results.items():
path = log_dir.joinpath(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
print(f"Writing {path}")
with open(path, "w") as fp:
json.dump(content, fp, sort_keys=True, indent=4)
fp.write("\n")
@click.command()
@click.argument("version", required=True)
@click.argument("commit", required=True)
@click.argument("branch", required=True)
def main(version: str, commit: str, branch: str):
log_dir = Path(__file__).parent.joinpath(version)
bk = get_buildkite_api()
build_dict_list = bk.builds().list_all_for_pipeline(
organization=BUILDKITE_ORGANIZATION,
pipeline=BUILDKITE_PIPELINE,
branch=branch,
commit=commit,
)
fetched_results = get_results_from_build_collection(bk, build_dict_list)
write_results(log_dir, fetched_results)
if __name__ == "__main__":
main()
| Artifact |
python | ijl__orjson | test/test_append_newline.py | {
"start": 112,
"end": 1395
} | class ____:
def test_dumps_newline(self):
"""
dumps() OPT_APPEND_NEWLINE
"""
assert orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE) == b"[]\n"
@needs_data
def test_twitter_newline(self):
"""
loads(),dumps() twitter.json OPT_APPEND_NEWLINE
"""
val = read_fixture_obj("twitter.json.xz")
assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val
@needs_data
def test_canada(self):
"""
loads(), dumps() canada.json OPT_APPEND_NEWLINE
"""
val = read_fixture_obj("canada.json.xz")
assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val
@needs_data
def test_citm_catalog_newline(self):
"""
loads(), dumps() citm_catalog.json OPT_APPEND_NEWLINE
"""
val = read_fixture_obj("citm_catalog.json.xz")
assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val
@needs_data
def test_github_newline(self):
"""
loads(), dumps() github.json OPT_APPEND_NEWLINE
"""
val = read_fixture_obj("github.json.xz")
assert orjson.loads(orjson.dumps(val, option=orjson.OPT_APPEND_NEWLINE)) == val
| TestAppendNewline |
python | cython__cython | Tools/dataclass_test_data/test_dataclasses.py | {
"start": 106562,
"end": 112786
} | class ____(unittest.TestCase):
def test_classvar(self):
# Some expressions recognized as ClassVar really aren't. But
# if you're using string annotations, it's not an exact
# science.
# These tests assume that both "import typing" and "from
# typing import *" have been run in this file.
for typestr in ('ClassVar[int]',
'ClassVar [int]',
' ClassVar [int]',
'ClassVar',
' ClassVar ',
'typing.ClassVar[int]',
'typing.ClassVar[str]',
' typing.ClassVar[str]',
'typing .ClassVar[str]',
'typing. ClassVar[str]',
'typing.ClassVar [str]',
'typing.ClassVar [ str]',
# Not syntactically valid, but these will
# be treated as ClassVars.
'typing.ClassVar.[int]',
'typing.ClassVar+',
):
with self.subTest(typestr=typestr):
@dataclass
class C:
x: typestr
# x is a ClassVar, so C() takes no args.
C()
# And it won't appear in the class's dict because it doesn't
# have a default.
self.assertNotIn('x', C.__dict__)
def test_isnt_classvar(self):
for typestr in ('CV',
't.ClassVar',
't.ClassVar[int]',
'typing..ClassVar[int]',
'Classvar',
'Classvar[int]',
'typing.ClassVarx[int]',
'typong.ClassVar[int]',
'dataclasses.ClassVar[int]',
'typingxClassVar[str]',
):
with self.subTest(typestr=typestr):
@dataclass
class C:
x: typestr
# x is not a ClassVar, so C() takes one arg.
self.assertEqual(C(10).x, 10)
def test_initvar(self):
# These tests assume that both "import dataclasses" and "from
# dataclasses import *" have been run in this file.
for typestr in ('InitVar[int]',
'InitVar [int]'
' InitVar [int]',
'InitVar',
' InitVar ',
'dataclasses.InitVar[int]',
'dataclasses.InitVar[str]',
' dataclasses.InitVar[str]',
'dataclasses .InitVar[str]',
'dataclasses. InitVar[str]',
'dataclasses.InitVar [str]',
'dataclasses.InitVar [ str]',
# Not syntactically valid, but these will
# be treated as InitVars.
'dataclasses.InitVar.[int]',
'dataclasses.InitVar+',
):
with self.subTest(typestr=typestr):
@dataclass
class C:
x: typestr
# x is an InitVar, so doesn't create a member.
with self.assertRaisesRegex(AttributeError,
"object has no attribute 'x'"):
C(1).x
def test_isnt_initvar(self):
for typestr in ('IV',
'dc.InitVar',
'xdataclasses.xInitVar',
'typing.xInitVar[int]',
):
with self.subTest(typestr=typestr):
@dataclass
class C:
x: typestr
# x is not an InitVar, so there will be a member x.
self.assertEqual(C(10).x, 10)
def test_classvar_module_level_import(self):
from test import dataclass_module_1
from test import dataclass_module_1_str
from test import dataclass_module_2
from test import dataclass_module_2_str
for m in (dataclass_module_1, dataclass_module_1_str,
dataclass_module_2, dataclass_module_2_str,
):
with self.subTest(m=m):
# There's a difference in how the ClassVars are
# interpreted when using string annotations or
# not. See the imported modules for details.
if m.USING_STRINGS:
c = m.CV(10)
else:
c = m.CV()
self.assertEqual(c.cv0, 20)
# There's a difference in how the InitVars are
# interpreted when using string annotations or
# not. See the imported modules for details.
c = m.IV(0, 1, 2, 3, 4)
for field_name in ('iv0', 'iv1', 'iv2', 'iv3'):
with self.subTest(field_name=field_name):
with self.assertRaisesRegex(AttributeError, f"object has no attribute '{field_name}'"):
# Since field_name is an InitVar, it's
# not an instance field.
getattr(c, field_name)
if m.USING_STRINGS:
# iv4 is interpreted as a normal field.
self.assertIn('not_iv4', c.__dict__)
self.assertEqual(c.not_iv4, 4)
else:
# iv4 is interpreted as an InitVar, so it
# won't exist on the instance.
self.assertNotIn('not_iv4', c.__dict__)
def test_text_annotations(self):
from test import dataclass_textanno
self.assertEqual(
get_type_hints(dataclass_textanno.Bar),
{'foo': dataclass_textanno.Foo})
self.assertEqual(
get_type_hints(dataclass_textanno.Bar.__init__),
{'foo': dataclass_textanno.Foo,
'return': type(None)})
| TestStringAnnotations |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/environment.py | {
"start": 637,
"end": 847
} | class ____(serializers.Serializer):
isHidden = serializers.BooleanField(
help_text="Specify `true` to make the environment visible or `false` to make the environment hidden."
)
| EnvironmentSerializer |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 29933,
"end": 39755
} | class ____:
def test_key_agreement_false_encipher_decipher_true(self):
with pytest.raises(ValueError):
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=True,
decipher_only=False,
)
with pytest.raises(ValueError):
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=True,
decipher_only=True,
)
with pytest.raises(ValueError):
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
def test_properties_key_agreement_true(self):
ku = x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert ku.digital_signature is True
assert ku.content_commitment is True
assert ku.key_encipherment is False
assert ku.data_encipherment is False
assert ku.key_agreement is False
assert ku.key_cert_sign is True
assert ku.crl_sign is False
def test_key_agreement_true_properties(self):
ku = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
assert ku.key_agreement is True
assert ku.encipher_only is False
assert ku.decipher_only is True
def test_key_agreement_false_properties(self):
ku = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert ku.key_agreement is False
with pytest.raises(ValueError):
ku.encipher_only
with pytest.raises(ValueError):
ku.decipher_only
def test_repr_key_agreement_false(self):
ku = x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert repr(ku) == (
"<KeyUsage(digital_signature=True, content_commitment=True, key_en"
"cipherment=False, data_encipherment=False, key_agreement=False, k"
"ey_cert_sign=True, crl_sign=False, encipher_only=False, decipher_"
"only=False)>"
)
def test_repr_key_agreement_true(self):
ku = x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert repr(ku) == (
"<KeyUsage(digital_signature=True, content_commitment=True, key_en"
"cipherment=False, data_encipherment=False, key_agreement=True, k"
"ey_cert_sign=True, crl_sign=False, encipher_only=False, decipher_"
"only=False)>"
)
def test_eq(self):
ku = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
ku2 = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
assert ku == ku2
def test_ne(self):
ku = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
ku2 = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert ku != ku2
assert ku != object()
def test_hash(self):
ku = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
ku2 = x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
)
ku3 = x509.KeyUsage(
digital_signature=False,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
assert hash(ku) == hash(ku2)
assert hash(ku) != hash(ku3)
@pytest.mark.parametrize(
("ext", "serialized"),
[
(
x509.KeyUsage(
digital_signature=False,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
b"\x03\x02\x06@",
),
(
x509.KeyUsage(
digital_signature=False,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=True,
),
b"\x03\x03\x07H\x80",
),
(
x509.KeyUsage(
digital_signature=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=True,
key_cert_sign=False,
crl_sign=False,
encipher_only=True,
decipher_only=False,
),
b"\x03\x02\x00\x89",
),
(
x509.KeyUsage(
digital_signature=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=True,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
b"\x03\x02\x02\x94",
),
(
x509.KeyUsage(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
b"\x03\x01\x00",
),
],
)
def test_public_bytes(self, ext, serialized):
assert ext.public_bytes() == serialized
| TestKeyUsage |
python | scipy__scipy | benchmarks/benchmarks/test_functions.py | {
"start": 3283,
"end": 4366
} | class ____:
target_E = 0.
solution = np.array([3., 0.5])
xmin = np.array([-4.5, -4.5])
xmax = np.array([4.5, 4.5])
def fun(self, coords):
x, y = coords
p1 = (1.5 - x + x * y)**2
p2 = (2.25 - x + x * y**2)**2
p3 = (2.625 - x + x * y**3)**2
return p1 + p2 + p3
def der(self, coords):
x, y = coords
dfdx = (2. * (1.5 - x + x * y) * (-1. + y) +
2. * (2.25 - x + x * y**2) * (-1. + y**2) +
2. * (2.625 - x + x * y**3) * (-1. + y**3))
dfdy = (2. * (1.5 - x + x * y) * (x) +
2. * (2.25 - x + x * y**2) * (2. * y * x) +
2. * (2.625 - x + x * y**3) * (3. * x * y**2))
return np.array([dfdx, dfdy])
"""
Global Test functions for minimizers.
HolderTable, Ackey and Levi have many competing local minima and are suited
for global minimizers such as basinhopping or differential_evolution.
(https://en.wikipedia.org/wiki/Test_functions_for_optimization)
See also https://mpra.ub.uni-muenchen.de/2718/1/MPRA_paper_2718.pdf
"""
| Beale |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 232579,
"end": 233279
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("is_restricted", "occurred_at", "resource_path", "url", "user")
is_restricted = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="isRestricted"
)
occurred_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="occurredAt"
)
resource_path = sgqlc.types.Field(
sgqlc.types.non_null(URI), graphql_name="resourcePath"
)
url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="url")
user = sgqlc.types.Field(sgqlc.types.non_null("User"), graphql_name="user")
| Contribution |
python | huggingface__transformers | tests/trainer/test_trainer.py | {
"start": 10177,
"end": 10469
} | class ____:
def __init__(self, thresh=0.25):
self.thresh = thresh
def __call__(self, eval_pred):
predictions, labels = eval_pred
true = np.abs(predictions - labels) <= self.thresh
return {"accuracy": true.astype(np.float32).mean().item()}
| AlmostAccuracy |
python | django__django | tests/serializers/tests.py | {
"start": 3358,
"end": 18577
} | class ____:
serializer_name = None # Set by subclasses to the serialization format name
@classmethod
def setUpTestData(cls):
sports = Category.objects.create(name="Sports")
music = Category.objects.create(name="Music")
op_ed = Category.objects.create(name="Op-Ed")
cls.joe = Author.objects.create(name="Joe")
cls.jane = Author.objects.create(name="Jane")
cls.a1 = Article(
author=cls.jane,
headline="Poker has no place on ESPN",
pub_date=datetime(2006, 6, 16, 11, 00),
)
cls.a1.save()
cls.a1.categories.set([sports, op_ed])
cls.a2 = Article(
author=cls.joe,
headline="Time to reform copyright",
pub_date=datetime(2006, 6, 16, 13, 00, 11, 345),
)
cls.a2.save()
cls.a2.categories.set([music, op_ed])
def test_serialize(self):
"""Basic serialization works."""
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
self.assertTrue(self._validate_output(serial_str))
def test_serializer_roundtrip(self):
"""Serialized content can be deserialized."""
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
models = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(len(models), 2)
def test_serialize_to_stream(self):
obj = ComplexModel(field1="first", field2="second", field3="third")
obj.save_base(raw=True)
# Serialize the test database to a stream
for stream in (StringIO(), HttpResponse()):
serializers.serialize(self.serializer_name, [obj], indent=2, stream=stream)
# Serialize normally for a comparison
string_data = serializers.serialize(self.serializer_name, [obj], indent=2)
# The two are the same
if isinstance(stream, StringIO):
self.assertEqual(string_data, stream.getvalue())
else:
self.assertEqual(string_data, stream.text)
def test_serialize_specific_fields(self):
obj = ComplexModel(field1="first", field2="second", field3="third")
obj.save_base(raw=True)
# Serialize then deserialize the test database
serialized_data = serializers.serialize(
self.serializer_name, [obj], indent=2, fields=("field1", "field3")
)
result = next(serializers.deserialize(self.serializer_name, serialized_data))
# The deserialized object contains data in only the serialized fields.
self.assertEqual(result.object.field1, "first")
self.assertEqual(result.object.field2, "")
self.assertEqual(result.object.field3, "third")
def test_altering_serialized_output(self):
"""
The ability to create new objects by modifying serialized content.
"""
old_headline = "Poker has no place on ESPN"
new_headline = "Poker has no place on television"
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
serial_str = serial_str.replace(old_headline, new_headline)
models = list(serializers.deserialize(self.serializer_name, serial_str))
# Prior to saving, old headline is in place
self.assertTrue(Article.objects.filter(headline=old_headline))
self.assertFalse(Article.objects.filter(headline=new_headline))
for model in models:
model.save()
# After saving, new headline is in place
self.assertTrue(Article.objects.filter(headline=new_headline))
self.assertFalse(Article.objects.filter(headline=old_headline))
def test_one_to_one_as_pk(self):
"""
If you use your own primary key field (such as a OneToOneField), it
doesn't appear in the serialized field list - it replaces the pk
identifier.
"""
AuthorProfile.objects.create(
author=self.joe, date_of_birth=datetime(1970, 1, 1)
)
serial_str = serializers.serialize(
self.serializer_name, AuthorProfile.objects.all()
)
self.assertFalse(self._get_field_values(serial_str, "author"))
for obj in serializers.deserialize(self.serializer_name, serial_str):
self.assertEqual(obj.object.pk, self.joe.pk)
def test_serialize_field_subset(self):
"""Output can be restricted to a subset of fields"""
valid_fields = ("headline", "pub_date")
invalid_fields = ("author", "categories")
serial_str = serializers.serialize(
self.serializer_name, Article.objects.all(), fields=valid_fields
)
for field_name in invalid_fields:
self.assertFalse(self._get_field_values(serial_str, field_name))
for field_name in valid_fields:
self.assertTrue(self._get_field_values(serial_str, field_name))
def test_serialize_unicode_roundtrip(self):
"""Unicode makes the roundtrip intact"""
actor_name = "Za\u017c\u00f3\u0142\u0107"
movie_title = "G\u0119\u015bl\u0105 ja\u017a\u0144"
ac = Actor(name=actor_name)
mv = Movie(title=movie_title, actor=ac)
ac.save()
mv.save()
serial_str = serializers.serialize(self.serializer_name, [mv])
self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title)
self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name)
obj_list = list(serializers.deserialize(self.serializer_name, serial_str))
mv_obj = obj_list[0].object
self.assertEqual(mv_obj.title, movie_title)
def test_unicode_serialization(self):
unicode_name = "יוניקוד"
data = serializers.serialize(self.serializer_name, [Author(name=unicode_name)])
self.assertIn(unicode_name, data)
objs = list(serializers.deserialize(self.serializer_name, data))
self.assertEqual(objs[0].object.name, unicode_name)
def test_serialize_progressbar(self):
fake_stdout = StringIO()
serializers.serialize(
self.serializer_name,
Article.objects.all(),
progress_output=fake_stdout,
object_count=Article.objects.count(),
)
self.assertTrue(
fake_stdout.getvalue().endswith(
"[" + "." * ProgressBar.progress_width + "]\n"
)
)
def test_serialize_superfluous_queries(self):
"""Ensure no superfluous queries are made when serializing ForeignKeys
#17602
"""
ac = Actor(name="Actor name")
ac.save()
mv = Movie(title="Movie title", actor_id=ac.pk)
mv.save()
with self.assertNumQueries(0):
serializers.serialize(self.serializer_name, [mv])
def test_serialize_prefetch_related_m2m(self):
# One query for the Article table, one for each prefetched m2m
# field, and one extra one for the nested prefetch for the Topics
# that have a relationship to the Category.
with self.assertNumQueries(5):
serializers.serialize(
self.serializer_name,
Article.objects.prefetch_related(
"meta_data",
"topics",
Prefetch(
"categories",
queryset=Category.objects.prefetch_related("topic_set"),
),
),
)
# One query for the Article table, and three m2m queries for each
# article.
with self.assertNumQueries(7):
serializers.serialize(self.serializer_name, Article.objects.all())
def test_serialize_prefetch_related_m2m_with_natural_keys(self):
# One query for the Article table, one for each prefetched m2m
# field, and a query to get the categories for each Article (two in
# total).
with self.assertNumQueries(5):
serializers.serialize(
self.serializer_name,
Article.objects.prefetch_related(
Prefetch(
"meta_data",
queryset=CategoryMetaData.objects.prefetch_related(
"category_set"
),
),
"topics",
),
use_natural_foreign_keys=True,
)
def test_serialize_with_null_pk(self):
"""
Serialized data with no primary key results
in a model instance with no id
"""
category = Category(name="Reference")
serial_str = serializers.serialize(self.serializer_name, [category])
pk_value = self._get_pk_values(serial_str)[0]
self.assertFalse(pk_value)
cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[
0
].object
self.assertIsNone(cat_obj.id)
def test_float_serialization(self):
"""Float values serialize and deserialize intact"""
sc = Score(score=3.4)
sc.save()
serial_str = serializers.serialize(self.serializer_name, [sc])
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1))
def test_deferred_field_serialization(self):
author = Author.objects.create(name="Victor Hugo")
author = Author.objects.defer("name").get(pk=author.pk)
serial_str = serializers.serialize(self.serializer_name, [author])
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertIsInstance(deserial_objs[0].object, Author)
def test_custom_field_serialization(self):
"""Custom fields serialize and deserialize intact"""
team_str = "Spartak Moskva"
player = Player()
player.name = "Soslan Djanaev"
player.rank = 1
player.team = Team(team_str)
player.save()
serial_str = serializers.serialize(self.serializer_name, Player.objects.all())
team = self._get_field_values(serial_str, "team")
self.assertTrue(team)
self.assertEqual(team[0], team_str)
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(
deserial_objs[0].object.team.to_string(), player.team.to_string()
)
def test_pre_1000ad_date(self):
"""Year values before 1000AD are properly formatted"""
# Regression for #12524 -- dates before 1000AD get prefixed
# 0's on the year
a = Article.objects.create(
author=self.jane,
headline="Nobody remembers the early years",
pub_date=datetime(1, 2, 3, 4, 5, 6),
)
serial_str = serializers.serialize(self.serializer_name, [a])
date_values = self._get_field_values(serial_str, "pub_date")
self.assertEqual(date_values[0].replace("T", " "), "0001-02-03 04:05:06")
def test_pkless_serialized_strings(self):
"""
Serialized strings without PKs can be turned into models
"""
deserial_objs = list(
serializers.deserialize(self.serializer_name, self.pkless_str)
)
for obj in deserial_objs:
self.assertFalse(obj.object.id)
obj.save()
self.assertEqual(Category.objects.count(), 5)
def test_deterministic_mapping_ordering(self):
"""
Mapping such as fields should be deterministically ordered. (#24558)
"""
output = serializers.serialize(self.serializer_name, [self.a1], indent=2)
categories = self.a1.categories.values_list("pk", flat=True)
self.assertEqual(
output,
self.mapping_ordering_str
% {
"article_pk": self.a1.pk,
"author_pk": self.a1.author_id,
"first_category_pk": categories[0],
"second_category_pk": categories[1],
},
)
def test_deserialize_force_insert(self):
"""
Deserialized content can be saved with force_insert as a parameter.
"""
serial_str = serializers.serialize(self.serializer_name, [self.a1])
deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[
0
]
with mock.patch("django.db.models.Model") as mock_model:
deserial_obj.save(force_insert=False)
mock_model.save_base.assert_called_with(
deserial_obj.object, raw=True, using=None, force_insert=False
)
@skipUnlessDBFeature("can_defer_constraint_checks")
def test_serialize_proxy_model(self):
BaseModel.objects.create(parent_data=1)
base_objects = BaseModel.objects.all()
proxy_objects = ProxyBaseModel.objects.all()
proxy_proxy_objects = ProxyProxyBaseModel.objects.all()
base_data = serializers.serialize("json", base_objects)
proxy_data = serializers.serialize("json", proxy_objects)
proxy_proxy_data = serializers.serialize("json", proxy_proxy_objects)
self.assertEqual(base_data, proxy_data.replace("proxy", ""))
self.assertEqual(base_data, proxy_proxy_data.replace("proxy", ""))
def test_serialize_inherited_fields(self):
child_1 = Child.objects.create(parent_data="a", child_data="b")
child_2 = Child.objects.create(parent_data="c", child_data="d")
child_1.parent_m2m.add(child_2)
child_data = serializers.serialize(self.serializer_name, [child_1, child_2])
self.assertEqual(self._get_field_values(child_data, "parent_m2m"), [])
self.assertEqual(self._get_field_values(child_data, "parent_data"), [])
def test_serialize_only_pk(self):
with self.assertNumQueries(7) as ctx:
serializers.serialize(
self.serializer_name,
Article.objects.all(),
use_natural_foreign_keys=False,
)
categories_sql = ctx[1]["sql"]
self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql)
meta_data_sql = ctx[2]["sql"]
self.assertNotIn(connection.ops.quote_name("kind"), meta_data_sql)
topics_data_sql = ctx[3]["sql"]
self.assertNotIn(connection.ops.quote_name("category_id"), topics_data_sql)
def test_serialize_no_only_pk_with_natural_keys(self):
with self.assertNumQueries(7) as ctx:
serializers.serialize(
self.serializer_name,
Article.objects.all(),
use_natural_foreign_keys=True,
)
categories_sql = ctx[1]["sql"]
self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql)
# CategoryMetaData has natural_key().
meta_data_sql = ctx[2]["sql"]
self.assertIn(connection.ops.quote_name("kind"), meta_data_sql)
topics_data_sql = ctx[3]["sql"]
self.assertNotIn(connection.ops.quote_name("category_id"), topics_data_sql)
| SerializersTestBase |
python | cython__cython | Cython/Compiler/FlowControl.py | {
"start": 15168,
"end": 16343
} | class ____:
"""Graphviz DOT renderer."""
def __init__(self, name, flow):
self.name = name
self.flow = flow
def render(self, fp, ctx, annotate_defs=False):
fp.write(' subgraph %s {\n' % self.name)
for block in self.flow.blocks:
label = ctx.extract_sources(block)
if annotate_defs:
for stat in block.stats:
if isinstance(stat, NameAssignment):
label += '\n %s [%s %s]' % (
stat.entry.name, 'deletion' if stat.is_deletion else 'definition', stat.pos[1])
elif isinstance(stat, NameReference):
if stat.entry:
label += '\n %s [reference %s]' % (stat.entry.name, stat.pos[1])
if not label:
label = 'empty'
pid = ctx.nodeid(block)
fp.write(' %s [label="%s"];\n' % (pid, ctx.escape(label)))
for block in self.flow.blocks:
pid = ctx.nodeid(block)
for child in block.children:
fp.write(' %s -> %s;\n' % (pid, ctx.nodeid(child)))
fp.write(' }\n')
| GV |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/gql.py | {
"start": 3672,
"end": 29387
} | class ____(Enum):
SERVERLESS = "SERVERLESS"
HYBRID = "HYBRID"
def fetch_agent_status(client: DagsterCloudGraphQLClient) -> list[Any]:
return client.execute(AGENT_STATUS_QUERY)["data"]["agents"]
AGENT_TYPE_QUERY = """
query DeploymentInfoQuery {
currentDeployment {
agentType
}
}
"""
def fetch_agent_type(client: DagsterCloudGraphQLClient) -> DagsterPlusDeploymentAgentType:
return DagsterPlusDeploymentAgentType(
client.execute(AGENT_TYPE_QUERY)["data"]["currentDeployment"]["agentType"]
)
WORKSPACE_ENTRIES_QUERY = """
query CliWorkspaceEntries {
workspace {
workspaceEntries {
locationName
serializedDeploymentMetadata
}
}
}
"""
def fetch_workspace_entries(client: DagsterCloudGraphQLClient) -> list[Any]:
return client.execute(WORKSPACE_ENTRIES_QUERY)["data"]["workspace"]["workspaceEntries"]
REPOSITORY_LOCATIONS_QUERY = """
query CliLocationsQuery {
workspaceOrError {
__typename
... on Workspace {
locationEntries {
__typename
name
loadStatus
locationOrLoadError {
__typename
... on RepositoryLocation {
name
}
... on PythonError {
message
stack
errorChain {
isExplicitLink
error {
message
stack
}
}
}
}
}
}
... on PythonError {
message
stack
}
}
}
"""
def fetch_code_locations(client: DagsterCloudGraphQLClient) -> list[Any]:
result = client.execute(REPOSITORY_LOCATIONS_QUERY)["data"]["workspaceOrError"]
if result["__typename"] != "Workspace":
raise Exception("Unable to query code locations: ", result["message"])
return result["locationEntries"]
ADD_OR_UPDATE_LOCATION_FROM_DOCUMENT_MUTATION = """
mutation CliAddOrUpdateLocation($document: GenericScalar!) {
addOrUpdateLocationFromDocument(document: $document) {
__typename
... on WorkspaceEntry {
locationName
}
... on PythonError {
message
stack
}
... on InvalidLocationError {
errors
}
... on UnauthorizedError {
message
}
}
}
"""
def add_or_update_code_location(
client: DagsterCloudGraphQLClient, location_document: dict[str, Any]
) -> None:
result = client.execute(
ADD_OR_UPDATE_LOCATION_FROM_DOCUMENT_MUTATION,
variable_values={"document": location_document},
)["data"]["addOrUpdateLocationFromDocument"]
if result["__typename"] == "InvalidLocationError":
raise Exception("Error in location config:\n" + "\n".join(result["errors"]))
elif result["__typename"] != "WorkspaceEntry":
raise Exception("Unable to add/update code location: ", result["message"])
DELETE_LOCATION_MUTATION = """
mutation CliDeleteLocation($locationName: String!) {
deleteLocation(locationName: $locationName) {
__typename
... on DeleteLocationSuccess {
locationName
}
... on PythonError {
message
stack
}
}
}
"""
def delete_code_location(client: DagsterCloudGraphQLClient, location_name: str) -> None:
result = client.execute(
DELETE_LOCATION_MUTATION, variable_values={"locationName": location_name}
)
if result["data"]["deleteLocation"]["__typename"] != "DeleteLocationSuccess":
raise Exception(f"Unable to delete location: {result['data']['deleteLocation']}")
RECONCILE_LOCATIONS_FROM_DOCUMENT_MUTATION = """
mutation CliReconcileLocationsFromDoc($document: GenericScalar!) {
reconcileLocationsFromDocument(document: $document) {
__typename
... on ReconcileLocationsSuccess {
locations {
locationName
}
}
... on PythonError {
message
stack
}
... on InvalidLocationError {
errors
}
}
}
"""
def reconcile_code_locations(
client: DagsterCloudGraphQLClient, locations_document: dict[str, Any]
) -> list[str]:
result = client.execute(
RECONCILE_LOCATIONS_FROM_DOCUMENT_MUTATION,
variable_values={"document": locations_document},
)
if (
result["data"]["reconcileLocationsFromDocument"]["__typename"]
== "ReconcileLocationsSuccess"
):
return sorted(
[
location["locationName"]
for location in result["data"]["reconcileLocationsFromDocument"]["locations"]
]
)
elif result["data"]["reconcileLocationsFromDocument"] == "InvalidLocationError":
raise Exception("Error in workspace config:\n" + "\n".join(result["errors"]))
else:
raise Exception(f"Unable to sync locations: {result}")
DEPLOY_LOCATIONS_FROM_DOCUMENT_MUTATION = """
mutation CliDeployLocations($document: GenericScalar!) {
deployLocations(document: $document) {
__typename
... on DeployLocationsSuccess {
locations {
locationName
}
}
... on PythonError {
message
stack
}
... on InvalidLocationError {
errors
}
}
}
"""
def deploy_code_locations(
client: DagsterCloudGraphQLClient,
locations_document: dict[str, Any],
) -> list[str]:
result = client.execute(
DEPLOY_LOCATIONS_FROM_DOCUMENT_MUTATION,
variable_values={
"document": locations_document,
},
)
if result["data"]["deployLocations"]["__typename"] == "DeployLocationsSuccess":
return sorted(
[
location["locationName"]
for location in result["data"]["deployLocations"]["locations"]
]
)
elif result["data"]["deployLocations"] == "InvalidLocationError":
raise Exception("Error in workspace config:\n" + "\n".join(result["errors"]))
else:
raise Exception(f"Unable to deploy locations: {result}")
GET_LOCATIONS_AS_DOCUMENT_QUERY = """
query CliLocationsAsDocument {
locationsAsDocument {
__typename
document
}
}
"""
def fetch_locations_as_document(client: DagsterCloudGraphQLClient) -> dict[str, Any]:
result = client.execute(GET_LOCATIONS_AS_DOCUMENT_QUERY)
return result["data"]["locationsAsDocument"]["document"]
SET_DEPLOYMENT_SETTINGS_MUTATION = """
mutation CliSetDeploymentSettings($deploymentSettings: DeploymentSettingsInput!) {
setDeploymentSettings(deploymentSettings: $deploymentSettings) {
__typename
... on DeploymentSettings {
settings
}
...on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
"""
def set_deployment_settings(
client: DagsterCloudGraphQLClient, deployment_settings: dict[str, Any]
) -> None:
result = client.execute(
SET_DEPLOYMENT_SETTINGS_MUTATION,
variable_values={"deploymentSettings": deployment_settings},
)
if result["data"]["setDeploymentSettings"]["__typename"] != "DeploymentSettings":
raise Exception(f"Unable to set deployment settings: {result}")
DEPLOYMENT_SETTINGS_QUERY = """
query CliDeploymentSettings {
deploymentSettings {
settings
}
}
"""
def get_deployment_settings(client: DagsterCloudGraphQLClient) -> dict[str, Any]:
result = client.execute(DEPLOYMENT_SETTINGS_QUERY)
if result.get("data", {}).get("deploymentSettings", {}).get("settings") is None:
raise Exception(f"Unable to get deployment settings: {result}")
return result["data"]["deploymentSettings"]["settings"]
ALERT_POLICIES_QUERY = """
query CliAlertPoliciesDocument {
alertPoliciesAsDocumentOrError {
__typename
... on AlertPoliciesAsDocument {
document
}
... on PythonError {
message
stack
}
... on UnauthorizedError {
message
}
}
}
"""
def get_alert_policies(client: DagsterCloudGraphQLClient) -> dict[str, Any]:
result = client.execute(ALERT_POLICIES_QUERY)
if (
not result.get("data", {}).get("alertPoliciesAsDocumentOrError", {})
or result.get("data", {}).get("alertPoliciesAsDocumentOrError", {}).get("__typename")
!= "AlertPoliciesAsDocument"
):
raise Exception(f"Unable to get alert policies: {result}")
return result["data"]["alertPoliciesAsDocumentOrError"]["document"]
RECONCILE_ALERT_POLICIES_FROM_DOCUMENT_MUTATION = """
mutation CliReconcileAlertPoliciesFromDocumentMutation($document: GenericScalar!) {
reconcileAlertPoliciesFromDocument(document: $document) {
__typename
... on ReconcileAlertPoliciesSuccess {
alertPolicies {
name
}
}
... on UnauthorizedError {
message
}
... on InvalidAlertPolicyError {
message
}
... on PythonError {
message
stack
}
}
}
"""
def reconcile_alert_policies(
client: DagsterCloudGraphQLClient, alert_policy_inputs: Sequence[dict]
) -> Sequence[str]:
result = client.execute(
RECONCILE_ALERT_POLICIES_FROM_DOCUMENT_MUTATION,
variable_values={"document": alert_policy_inputs},
)
if (
result["data"]["reconcileAlertPoliciesFromDocument"]["__typename"]
!= "ReconcileAlertPoliciesSuccess"
):
raise Exception(f"Unable to reconcile alert policies: {result}")
return sorted(
alert_policy["name"]
for alert_policy in result["data"]["reconcileAlertPoliciesFromDocument"]["alertPolicies"]
)
SET_ORGANIZATION_SETTINGS_MUTATION = """
mutation CliSetOrganizationSettings($organizationSettings: OrganizationSettingsInput!) {
setOrganizationSettings(organizationSettings: $organizationSettings) {
__typename
... on OrganizationSettings {
settings
}
...on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
"""
def set_organization_settings(
client: DagsterCloudGraphQLClient, organization_settings: dict[str, Any]
) -> None:
result = client.execute(
SET_ORGANIZATION_SETTINGS_MUTATION,
variable_values={"organizationSettings": organization_settings},
)
if result["data"]["setOrganizationSettings"]["__typename"] != "OrganizationSettings":
raise Exception(f"Unable to set organization settings: {result}")
ORGANIZATION_SETTINGS_QUERY = """
query CliOrganizationSettings {
organizationSettings {
settings
}
}
"""
def get_organization_settings(client: DagsterCloudGraphQLClient) -> dict[str, Any]:
result = client.execute(ORGANIZATION_SETTINGS_QUERY)
if result.get("data", {}).get("organizationSettings", {}).get("settings") is None:
raise Exception(f"Unable to get organization settings: {result}")
return result["data"]["organizationSettings"]["settings"]
CREATE_OR_UPDATE_BRANCH_DEPLOYMENT = """
mutation CliCreateOrUpdateBranchDeployment(
$branchData: CreateOrUpdateBranchDeploymentInput!
$commit: DeploymentCommitInput!
$baseDeploymentName: String
$snapshotBaseCondition: SnapshotBaseDeploymentCondition
) {
createOrUpdateBranchDeployment(
branchData: $branchData,
commit: $commit,
baseDeploymentName: $baseDeploymentName,
snapshotBaseCondition: $snapshotBaseCondition,
) {
__typename
... on DagsterCloudDeployment {
deploymentId
deploymentName
}
... on PythonError {
message
}
}
}
"""
def create_or_update_branch_deployment(
client: DagsterCloudGraphQLClient,
repo_name: str,
branch_name: str,
commit_hash: str,
timestamp: float,
branch_url: Optional[str] = None,
pull_request_url: Optional[str] = None,
pull_request_status: Optional[str] = None,
pull_request_number: Optional[str] = None,
commit_message: Optional[str] = None,
commit_url: Optional[str] = None,
author_name: Optional[str] = None,
author_email: Optional[str] = None,
author_avatar_url: Optional[str] = None,
base_deployment_name: Optional[str] = None,
snapshot_base_condition: Optional[SnapshotBaseDeploymentCondition] = None,
) -> str:
result = client.execute(
CREATE_OR_UPDATE_BRANCH_DEPLOYMENT,
variable_values={
"branchData": {
"repoName": repo_name,
"branchName": branch_name,
"branchUrl": branch_url,
"pullRequestUrl": pull_request_url,
"pullRequestStatus": pull_request_status,
"pullRequestNumber": pull_request_number,
},
"commit": {
"commitHash": commit_hash,
"timestamp": timestamp,
"commitMessage": commit_message,
"commitUrl": commit_url,
"authorName": author_name,
"authorEmail": author_email,
"authorAvatarUrl": author_avatar_url,
},
"baseDeploymentName": base_deployment_name,
"snapshotBaseCondition": snapshot_base_condition.name
if snapshot_base_condition
else None,
},
)
name = result.get("data", {}).get("createOrUpdateBranchDeployment", {}).get("deploymentName")
if name is None:
raise Exception(f"Unable to create or update branch deployment: {result}")
return cast("str", name)
GET_BRANCH_DEPLOYMENT_NAME = """
query CliGetBranchDeploymentName($repoName: String!, $branchName: String!) {
getBranchDeploymentName(repoName: $repoName, branchName: $branchName)
}
"""
def get_branch_deployment_name(
client: DagsterCloudGraphQLClient,
repo_name: str,
branch_name: str,
) -> str:
result = client.execute(
GET_BRANCH_DEPLOYMENT_NAME,
variable_values={
"repoName": repo_name,
"branchName": branch_name,
},
)
name = result.get("data", {}).get("getBranchDeploymentName")
if name is None:
raise Exception(f"Unable to get branch deployment name: {result}")
return cast("str", name)
LAUNCH_RUN_MUTATION = """
mutation CliLaunchRun($executionParams: ExecutionParams!) {
launchRun(executionParams: $executionParams) {
__typename
... on LaunchRunSuccess {
run {
runId
tags {
key
value
}
status
runConfigYaml
}
}
... on PythonError {
message
stack
}
}
}
"""
def launch_run(
client: DagsterCloudGraphQLClient,
location_name: str,
repo_name: str,
job_name: str,
tags: dict[str, Any],
config: dict[str, Any],
asset_keys: Optional[list[str]],
) -> str:
formatted_tags = [{"key": cast("str", k), "value": cast("str", v)} for k, v in tags.items()]
params: dict[str, Any] = {
"selector": {
"repositoryLocationName": location_name,
"repositoryName": repo_name,
"jobName": job_name,
**(
{"assetSelection": [{"path": path.split("/")} for path in asset_keys]}
if asset_keys
else {}
),
},
"runConfigData": config,
"executionMetadata": {"tags": formatted_tags},
}
result = client.execute(
LAUNCH_RUN_MUTATION,
variable_values={"executionParams": params},
)
if result["data"]["launchRun"]["__typename"] != "LaunchRunSuccess":
raise Exception(f"Unable to launch run: {result}")
return result["data"]["launchRun"]["run"]["runId"]
GET_ECR_CREDS_QUERY = """
query CliGetEcrInfo {
serverless {
awsRegion
awsAuthToken
registryAllowCustomBase
registryUrl
}
}
"""
def get_ecr_info(client: DagsterCloudGraphQLClient) -> Any:
data = client.execute(GET_ECR_CREDS_QUERY)["data"]
return {
"registry_url": data["serverless"]["registryUrl"],
"aws_region": data["serverless"]["awsRegion"],
"aws_auth_token": data["serverless"]["awsAuthToken"],
"allow_custom_base": data["serverless"]["registryAllowCustomBase"],
}
GET_RUN_STATUS_QUERY = """
query CliGetRunStatus($runId: ID!) {
runOrError(runId: $runId) {
__typename
... on Run {
id
status
}
}
}
"""
def run_status(client: DagsterCloudGraphQLClient, run_id: str) -> Any:
result = client.execute(
GET_RUN_STATUS_QUERY,
variable_values={"runId": run_id},
)["data"]
if result["runOrError"]["__typename"] != "Run" or result["runOrError"]["status"] is None:
raise Exception(f"Unable to fetch run status: {result}")
return result["runOrError"]["status"]
MARK_CLI_EVENT_MUTATION = """
mutation MarkCliEventMutation(
$eventType: CliEventType!
$durationSeconds: Float!
$success: Boolean
$tags: [String]
$message: String
) {
markCliEvent(eventType: $eventType, durationSeconds: $durationSeconds, success: $success, tags: $tags, message: $message)
}
"""
def mark_cli_event(
client: DagsterCloudGraphQLClient,
event_type: CliEventType,
duration_seconds: float,
success: bool = True,
tags: Optional[list[str]] = None,
message: Optional[str] = None,
) -> Any:
with suppress(Exception):
result = client.execute(
MARK_CLI_EVENT_MUTATION,
variable_values={
"eventType": event_type.name,
"durationSeconds": duration_seconds,
"success": success,
"tags": tags,
"message": message,
},
)
return result["data"]["markCliEvent"] == "ok"
GET_DEPLOYMENT_BY_NAME_QUERY = """
query DeploymentByNameQuery($deploymentName: String!) {
deploymentByName(name: $deploymentName) {
__typename
... on DagsterCloudDeployment {
deploymentName
deploymentId
deploymentType
}
}
}
"""
DELETE_DEPLOYMENT_MUTATION = """
mutation CliDeleteDeployment($deploymentId: Int!) {
deleteDeployment(deploymentId: $deploymentId) {
__typename
... on DagsterCloudDeployment {
deploymentId
}
... on PythonError {
message
stack
}
}
}
"""
def get_deployment_by_name(client: DagsterCloudGraphQLClient, deployment: str) -> dict[str, Any]:
result = client.execute(
GET_DEPLOYMENT_BY_NAME_QUERY, variable_values={"deploymentName": deployment}
)["data"]["deploymentByName"]
if not result["__typename"] == "DagsterCloudDeployment":
raise Exception(f"Unable to find deployment {deployment}")
return result
raise Exception(f"Unable to find deployment {deployment}")
def delete_branch_deployment(client: DagsterCloudGraphQLClient, deployment: str) -> Any:
deployment_info = get_deployment_by_name(client, deployment)
if not deployment_info["deploymentType"] == "BRANCH":
raise Exception(f"Deployment {deployment} is not a branch deployment")
result = client.execute(
DELETE_DEPLOYMENT_MUTATION,
variable_values={"deploymentId": deployment_info["deploymentId"]},
)
if result["data"]["deleteDeployment"]["__typename"] != "DagsterCloudDeployment":
raise Exception(f"Unable to delete deployment: {result}")
return result["data"]["deleteDeployment"]["deploymentId"]
SET_ATLAN_INTEGRATION_SETTINGS_MUTATION = """
mutation CliSetAtlanIntegrationSettings($atlanIntegrationSettings: AtlanIntegrationSettingsInput!) {
setAtlanIntegrationSettings(atlanIntegrationSettings: $atlanIntegrationSettings) {
__typename
... on SetAtlanIntegrationSettingsSuccess {
organization
success
}
...on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
"""
DELETE_ATLAN_INTEGRATION_SETTINGS_MUTATION = """
mutation CliDeleteAtlanIntegrationSettings {
deleteAtlanIntegrationSettings {
__typename
...on DeleteAtlanIntegrationSuccess {
organization
success
}
...on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
"""
GET_ATLAN_INTEGRATION_SETTINGS_QUERY = """
query CliGetAtlanIntegrationSettings {
atlanIntegration {
atlanIntegrationSettingsOrError {
__typename
... on AtlanIntegrationSettings {
token
domain
}
... on AtlanIntegrationSettingsUnset {
__typename
}
... on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
}
"""
ATLAN_INTEGRATION_PREFLIGHT_CHECK_QUERY = """
query CliAtlanIntegrationPreflightCheck {
atlanIntegration {
atlanIntegrationPreflightCheckOrError {
__typename
... on AtlanIntegrationPreflightCheckSuccess {
__typename
success
}
... on AtlanIntegrationPreflightCheckFailure {
errorCode
errorMessage
}
... on AtlanIntegrationSettingsUnset {
__typename
}
... on UnauthorizedError {
message
}
... on PythonError {
message
stack
}
}
}
}
"""
def set_atlan_integration_settings(
client: DagsterCloudGraphQLClient,
token: str,
domain: str,
) -> tuple[str, bool]:
result = client.execute(
SET_ATLAN_INTEGRATION_SETTINGS_MUTATION,
variable_values={"atlanIntegrationSettings": {"token": token, "domain": domain}},
)
if (
result["data"]["setAtlanIntegrationSettings"]["__typename"]
!= "SetAtlanIntegrationSettingsSuccess"
):
raise Exception(f"Unable to set Atlan integration settings: {result}")
return result["data"]["setAtlanIntegrationSettings"]["organization"], result["data"][
"setAtlanIntegrationSettings"
]["success"]
def delete_atlan_integration_settings(
client: DagsterCloudGraphQLClient,
) -> tuple[str, bool]:
result = client.execute(
DELETE_ATLAN_INTEGRATION_SETTINGS_MUTATION,
)
if (
result["data"]["deleteAtlanIntegrationSettings"]["__typename"]
!= "DeleteAtlanIntegrationSuccess"
):
raise Exception(f"Unable to delete Atlan integration settings: {result}")
return result["data"]["deleteAtlanIntegrationSettings"]["organization"], result["data"][
"deleteAtlanIntegrationSettings"
]["success"]
def get_atlan_integration_settings(
client: DagsterCloudGraphQLClient,
) -> dict:
result = client.execute(
GET_ATLAN_INTEGRATION_SETTINGS_QUERY,
)
settings_data = result["data"]["atlanIntegration"]["atlanIntegrationSettingsOrError"]
typename = settings_data["__typename"]
if typename == "AtlanIntegrationSettingsUnset":
raise Exception("No Atlan integration settings configured")
elif typename in ("UnauthorizedError", "PythonError"):
raise Exception(f"Unable to get Atlan integration settings: {result}")
return {
"token": settings_data["token"],
"domain": settings_data["domain"],
}
def atlan_integration_preflight_check(
client: DagsterCloudGraphQLClient,
) -> dict:
result = client.execute(
ATLAN_INTEGRATION_PREFLIGHT_CHECK_QUERY,
)
check_data = result["data"]["atlanIntegration"]["atlanIntegrationPreflightCheckOrError"]
typename = check_data["__typename"]
if typename == "AtlanIntegrationPreflightCheckSuccess":
return {"success": True}
elif typename == "AtlanIntegrationPreflightCheckFailure":
return {
"success": False,
"error_code": check_data["errorCode"],
"error_message": check_data["errorMessage"],
}
elif typename == "AtlanIntegrationSettingsUnset":
raise Exception("No Atlan integration settings configured")
else:
raise Exception(f"Unable to perform Atlan integration preflight check: {result}")
| DagsterPlusDeploymentAgentType |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_project_alert_rule_details.py | {
"start": 4177,
"end": 5119
} | class ____(AlertRuleDetailsBase):
method = "delete"
def test_simple(self) -> None:
with self.feature("organizations:incidents"), outbox_runner():
self.get_success_response(
self.organization.slug, self.project.slug, self.alert_rule.id, status_code=204
)
with self.tasks():
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=self.alert_rule.id).exists()
assert not AlertRule.objects_with_snapshots.filter(name=self.alert_rule.id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=self.alert_rule.id).exists()
with assume_test_silo_mode(SiloMode.CONTROL):
audit_log_entry = AuditLogEntry.objects.filter(
event=audit_log.get_event_id("ALERT_RULE_REMOVE"), target_object=self.alert_rule.id
)
assert len(audit_log_entry) == 1
| AlertRuleDetailsDeleteEndpointTest |
python | keras-team__keras | keras/src/ops/math.py | {
"start": 20578,
"end": 23942
} | class ____(Operation):
def __init__(self, fft_length=None, *, name=None):
super().__init__(name=name)
self.fft_length = fft_length
def compute_output_spec(self, x):
if not isinstance(x, (tuple, list)) or len(x) != 2:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and "
f"imaginary. Received: x={x}"
)
real, imag = x
# Both real and imaginary parts should have the same shape.
if real.shape != imag.shape:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and "
"imaginary. Both the real and imaginary parts should have the "
f"same shape. Received: x[0].shape = {real.shape}, "
f"x[1].shape = {imag.shape}"
)
# We are calculating 1D IRFFT. Hence, rank >= 1.
if len(real.shape) < 1:
raise ValueError(
f"Input should have rank >= 1. "
f"Received: input.shape = {real.shape}"
)
if self.fft_length is not None:
new_last_dimension = self.fft_length
else:
if real.shape[-1] is not None:
new_last_dimension = 2 * (real.shape[-1] - 1)
else:
new_last_dimension = None
new_shape = real.shape[:-1] + (new_last_dimension,)
return KerasTensor(shape=new_shape, dtype=real.dtype)
def call(self, x):
return backend.math.irfft(x, fft_length=self.fft_length)
@keras_export("keras.ops.irfft")
def irfft(x, fft_length=None):
"""Inverse real-valued Fast Fourier transform along the last axis.
Computes the inverse 1D Discrete Fourier Transform of a real-valued signal
over the inner-most dimension of input.
The inner-most dimension of the input is assumed to be the result of RFFT:
the `fft_length / 2 + 1` unique components of the DFT of a real-valued
signal. If `fft_length` is not provided, it is computed from the size of the
inner-most dimension of the input `(fft_length = 2 * (inner - 1))`. If the
FFT length used to compute is odd, it should be provided since it cannot
be inferred properly.
Along the axis IRFFT is computed on, if `fft_length / 2 + 1` is smaller than
the corresponding dimension of the input, the dimension is cropped. If it is
larger, the dimension is padded with zeros.
Args:
x: Tuple of the real and imaginary parts of the input tensor. Both
tensors in the tuple should be of floating type.
fft_length: An integer representing the number of the fft length. If not
specified, it is inferred from the length of the last axis of `x`.
Defaults to `None`.
Returns:
A tensor containing the inverse real-valued Fast Fourier Transform
along the last axis of `x`.
Examples:
>>> real = keras.ops.convert_to_tensor([0.0, 1.0, 2.0, 3.0, 4.0])
>>> imag = keras.ops.convert_to_tensor([0.0, 1.0, 2.0, 3.0, 4.0])
>>> irfft((real, imag))
array([0.66666667, -0.9106836, 0.24401694])
>>> irfft(rfft(real, 5), 5)
array([0.0, 1.0, 2.0, 3.0, 4.0])
"""
if any_symbolic_tensors(x):
return IRFFT(fft_length).symbolic_call(x)
return backend.math.irfft(x, fft_length)
| IRFFT |
python | streamlit__streamlit | lib/streamlit/elements/plotly_chart.py | {
"start": 5497,
"end": 6805
} | class ____(TypedDict, total=False):
"""
The schema for the Plotly chart event state.
The event state is stored in a dictionary-like object that supports both
key and attribute notation. Event states cannot be programmatically
changed or set through Session State.
Only selection events are supported at this time.
Attributes
----------
selection : dict
The state of the ``on_select`` event. This attribute returns a
dictionary-like object that supports both key and attribute notation.
The attributes are described by the ``PlotlySelectionState`` dictionary
schema.
Example
-------
Try selecting points by any of the three available methods (direct click,
box, or lasso). The current selection state is available through Session
State or as the output of the chart function.
>>> import plotly.express as px
>>> import streamlit as st
>>>
>>> df = px.data.iris()
>>> fig = px.scatter(df, x="sepal_width", y="sepal_length")
>>>
>>> event = st.plotly_chart(fig, key="iris", on_select="rerun")
>>>
>>> event
.. output::
https://doc-chart-events-plotly-state.streamlit.app
height: 600px
"""
selection: Required[PlotlySelectionState]
@dataclass
| PlotlyState |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/xaxis/_autorangeoptions.py | {
"start": 235,
"end": 5894
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.xaxis"
_path_str = "layout.scene.xaxis.autorangeoptions"
_valid_props = {
"clipmax",
"clipmin",
"include",
"includesrc",
"maxallowed",
"minallowed",
}
@property
def clipmax(self):
"""
Clip autorange maximum if it goes beyond this value. Has no
effect when `autorangeoptions.maxallowed` is provided.
The 'clipmax' property accepts values of any type
Returns
-------
Any
"""
return self["clipmax"]
@clipmax.setter
def clipmax(self, val):
self["clipmax"] = val
@property
def clipmin(self):
"""
Clip autorange minimum if it goes beyond this value. Has no
effect when `autorangeoptions.minallowed` is provided.
The 'clipmin' property accepts values of any type
Returns
-------
Any
"""
return self["clipmin"]
@clipmin.setter
def clipmin(self, val):
self["clipmin"] = val
@property
def include(self):
"""
Ensure this value is included in autorange.
The 'include' property accepts values of any type
Returns
-------
Any|numpy.ndarray
"""
return self["include"]
@include.setter
def include(self, val):
self["include"] = val
@property
def includesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `include`.
The 'includesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["includesrc"]
@includesrc.setter
def includesrc(self, val):
self["includesrc"] = val
@property
def maxallowed(self):
"""
Use this value exactly as autorange maximum.
The 'maxallowed' property accepts values of any type
Returns
-------
Any
"""
return self["maxallowed"]
@maxallowed.setter
def maxallowed(self, val):
self["maxallowed"] = val
@property
def minallowed(self):
"""
Use this value exactly as autorange minimum.
The 'minallowed' property accepts values of any type
Returns
-------
Any
"""
return self["minallowed"]
@minallowed.setter
def minallowed(self, val):
self["minallowed"] = val
@property
def _prop_descriptions(self):
return """\
clipmax
Clip autorange maximum if it goes beyond this value.
Has no effect when `autorangeoptions.maxallowed` is
provided.
clipmin
Clip autorange minimum if it goes beyond this value.
Has no effect when `autorangeoptions.minallowed` is
provided.
include
Ensure this value is included in autorange.
includesrc
Sets the source reference on Chart Studio Cloud for
`include`.
maxallowed
Use this value exactly as autorange maximum.
minallowed
Use this value exactly as autorange minimum.
"""
def __init__(
self,
arg=None,
clipmax=None,
clipmin=None,
include=None,
includesrc=None,
maxallowed=None,
minallowed=None,
**kwargs,
):
"""
Construct a new Autorangeoptions object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.scene.x
axis.Autorangeoptions`
clipmax
Clip autorange maximum if it goes beyond this value.
Has no effect when `autorangeoptions.maxallowed` is
provided.
clipmin
Clip autorange minimum if it goes beyond this value.
Has no effect when `autorangeoptions.minallowed` is
provided.
include
Ensure this value is included in autorange.
includesrc
Sets the source reference on Chart Studio Cloud for
`include`.
maxallowed
Use this value exactly as autorange maximum.
minallowed
Use this value exactly as autorange minimum.
Returns
-------
Autorangeoptions
"""
super().__init__("autorangeoptions")
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.layout.scene.xaxis.Autorangeoptions
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.scene.xaxis.Autorangeoptions`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("clipmax", arg, clipmax)
self._set_property("clipmin", arg, clipmin)
self._set_property("include", arg, include)
self._set_property("includesrc", arg, includesrc)
self._set_property("maxallowed", arg, maxallowed)
self._set_property("minallowed", arg, minallowed)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Autorangeoptions |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with1.py | {
"start": 345,
"end": 592
} | class ____(object):
def __enter__(self):
return 1
def __exit__(
self,
t: Optional[type] = None,
exc: Optional[BaseException] = None,
tb: Optional[Any] = None,
) -> bool:
return True
| Class2 |
python | kamyu104__LeetCode-Solutions | Python/apply-substitutions.py | {
"start": 81,
"end": 1945
} | class ____(object):
def applySubstitutions(self, replacements, text):
"""
:type replacements: List[List[str]]
:type text: str
:rtype: str
"""
def find_adj(s):
result = set()
i = 0
while i < len(s):
if s[i] != '%':
i += 1
continue
j = next(j for j in xrange(i+1, len(s)) if s[j] == '%')
result.add(s[i+1:j])
i = j+1
return result
def replace(s):
result = []
i = 0
while i < len(s):
if s[i] != '%':
result.append(s[i])
i += 1
continue
j = next(j for j in xrange(i+1, len(s)) if s[j] == '%')
result.append(lookup[s[i+1:j]])
i = j+1
return "".join(result)
def topological_sort():
adj = collections.defaultdict(set)
in_degree = collections.defaultdict(int)
for u, s in replacements:
for v in find_adj(s):
adj[v].add(u)
in_degree[u] += 1
result = []
q = [u for u, _ in replacements if not in_degree[u]]
while q:
new_q = []
for u in q:
lookup[u] = replace(lookup[u])
for v in adj[u]:
in_degree[v] -= 1
if in_degree[v]:
continue
new_q.append(v)
q = new_q
return result
lookup = {k:v for k, v in replacements}
topological_sort()
return replace(text)
# Time: O(r * 2^r)
# Space: O(r * 2^r)
# memoization
| Solution |
python | wandb__wandb | wandb/apis/public/projects.py | {
"start": 4596,
"end": 8059
} | class ____(Attrs):
"""A project is a namespace for runs.
Args:
client: W&B API client instance.
name (str): The name of the project.
entity (str): The entity name that owns the project.
"""
QUERY = gql(f"""#graphql
query Project($project: String!, $entity: String!) {{
project(name: $project, entityName: $entity) {{
...ProjectFragment
}}
}}
{PROJECT_FRAGMENT}
""")
def __init__(
self,
client: RetryingClient,
entity: str,
project: str,
attrs: dict,
) -> Project:
"""A single project associated with an entity.
Args:
client: The API client used to query W&B.
entity: The entity which owns the project.
project: The name of the project to query.
attrs: The attributes of the project.
"""
super().__init__(dict(attrs))
self._is_loaded = bool(attrs)
self.client = client
self.name = project
self.entity = entity
def _load(self):
from requests import HTTPError
variable_values = {"project": self.name, "entity": self.entity}
try:
response = self.client.execute(self.QUERY, variable_values)
except HTTPError as e:
raise ValueError(f"Unable to fetch project ID: {variable_values!r}") from e
self._attrs = response["project"]
self._is_loaded = True
@property
def path(self):
"""Returns the path of the project. The path is a list containing the
entity and project name."""
return [self.entity, self.name]
@property
def url(self):
"""Returns the URL of the project."""
return self.client.app_url + "/".join(self.path + ["workspace"])
def to_html(self, height=420, hidden=False):
"""Generate HTML containing an iframe displaying this project.
<!-- lazydoc-ignore: internal -->
"""
url = self.url + "?jupyter=true"
style = f"border:none;width:100%;height:{height}px;"
prefix = ""
if hidden:
style += "display:none;"
prefix = ipython.toggle_button("project")
return prefix + f"<iframe src={url!r} style={style!r}></iframe>"
def _repr_html_(self) -> str:
return self.to_html()
def __repr__(self):
return "<Project {}>".format("/".join(self.path))
@normalize_exceptions
def artifacts_types(self, per_page=50):
"""Returns all artifact types associated with this project."""
return public.ArtifactTypes(self.client, self.entity, self.name)
@normalize_exceptions
def sweeps(self, per_page=50):
"""Return a paginated collection of sweeps in this project.
Args:
per_page: The number of sweeps to fetch per request to the API.
Returns:
A `Sweeps` object, which is an iterable collection of `Sweep` objects.
"""
return Sweeps(self.client, self.entity, self.name, per_page=per_page)
@property
def id(self) -> str:
if not self._is_loaded:
self._load()
if "id" not in self._attrs:
raise ValueError(f"Project {self.name} not found")
return self._attrs["id"]
def __getattr__(self, name: str):
if not self._is_loaded:
self._load()
return super().__getattr__(name)
| Project |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 11748,
"end": 15497
} | class ____(_MagiclinkShorthandPattern):
"""Convert #1, repo#1, user/repo#1, !1, repo!1, user/repo!1, hash, repo@hash, or user/repo@hash to links."""
def process_issues(self, el, provider, user, repo, issue):
"""Process issues."""
issue_type = issue[:1]
issue_value = issue[1:]
if issue_type == '#':
issue_link = self.provider_info[provider]['issue']
issue_label = self.labels.get('issue', 'Issue')
class_name = 'magiclink-issue'
icon = issue_type
elif issue_type == '!':
issue_link = self.provider_info[provider]['pull']
issue_label = self.labels.get('pull', 'Pull Request')
class_name = 'magiclink-pull'
icon = '#' if self.normalize else issue_type
elif self.provider_info[provider]['type'] == "github" and issue_type == '?':
issue_link = self.provider_info[provider]['discuss']
issue_label = self.labels.get('discuss', 'Discussion')
class_name = 'magiclink-discussion'
icon = '#' if self.normalize else issue_type
else:
return False
if self.my_repo:
el.text = md_util.AtomicString(f'{icon}{issue_value}')
elif self.my_user:
el.text = md_util.AtomicString(f'{repo}{icon}{issue_value}')
else:
el.text = md_util.AtomicString(f'{user}/{repo}{icon}{issue_value}')
el.set('href', issue_link.format(user, repo, issue_value))
el.set('class', f'magiclink magiclink-{provider} {class_name}')
el.set(
'title',
'{} {}: {}/{} #{}'.format(
self.provider_info[provider]['provider'],
issue_label,
user,
repo,
issue_value
)
)
return True
def process_commit(self, el, provider, user, repo, commit):
"""Process commit."""
hash_ref = commit[0:self.provider_info[provider]['hash_size']]
if self.my_repo:
text = hash_ref
elif self.my_user:
text = f'{repo}@{hash_ref}'
else:
text = f'{user}/{repo}@{hash_ref}'
el.set('href', self.provider_info[provider]['commit'].format(user, repo, commit))
el.text = md_util.AtomicString(text)
el.set('class', f'magiclink magiclink-{provider} magiclink-commit')
el.set(
'title',
'{} {}: {}/{}@{}'.format(
self.provider_info[provider]['provider'],
self.labels.get('commit', 'Commit'),
user,
repo,
hash_ref
)
)
def process_compare(self, el, provider, user, repo, commit1, commit2):
"""Process commit."""
hash_ref1 = commit1[0:self.provider_info[provider]['hash_size']]
hash_ref2 = commit2[0:self.provider_info[provider]['hash_size']]
if self.my_repo:
text = f'{hash_ref1}...{hash_ref2}'
elif self.my_user:
text = f'{repo}@{hash_ref1}...{hash_ref2}'
else:
text = f'{user}/{repo}@{hash_ref1}...{hash_ref2}'
el.set('href', self.provider_info[provider]['compare'].format(user, repo, commit1, commit2))
el.text = md_util.AtomicString(text)
el.set('class', f'magiclink magiclink-{provider} magiclink-compare')
el.set(
'title',
'{} {}: {}/{}@{}...{}'.format(
self.provider_info[provider]['provider'],
self.labels.get('compare', 'Compare'),
user,
repo,
hash_ref1,
hash_ref2
)
)
| _MagiclinkReferencePattern |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 219416,
"end": 221105
} | class ____(rv_continuous):
r"""A Maxwell continuous random variable.
%(before_notes)s
Notes
-----
A special case of a `chi` distribution, with ``df=3``, ``loc=0.0``,
and given ``scale = a``, where ``a`` is the parameter used in the
Mathworld description [1]_.
The probability density function for `maxwell` is:
.. math::
f(x) = \sqrt{2/\pi}x^2 \exp(-x^2/2)
for :math:`x >= 0`.
%(after_notes)s
References
----------
.. [1] http://mathworld.wolfram.com/MaxwellDistribution.html
%(example)s
"""
def _shape_info(self):
return []
def _rvs(self, size=None, random_state=None):
return chi.rvs(3.0, size=size, random_state=random_state)
def _pdf(self, x):
# maxwell.pdf(x) = sqrt(2/pi)x**2 * exp(-x**2/2)
return _SQRT_2_OVER_PI*x*x*np.exp(-x*x/2.0)
def _logpdf(self, x):
# Allow x=0 without 'divide by zero' warnings
with np.errstate(divide='ignore'):
return _LOG_SQRT_2_OVER_PI + 2*np.log(x) - 0.5*x*x
def _cdf(self, x):
return sc.gammainc(1.5, x*x/2.0)
def _ppf(self, q):
return np.sqrt(2*sc.gammaincinv(1.5, q))
def _sf(self, x):
return sc.gammaincc(1.5, x*x/2.0)
def _isf(self, q):
return np.sqrt(2*sc.gammainccinv(1.5, q))
def _stats(self):
val = 3*np.pi-8
return (2*np.sqrt(2.0/np.pi),
3-8/np.pi,
np.sqrt(2)*(32-10*np.pi)/val**1.5,
(-12*np.pi*np.pi + 160*np.pi - 384) / val**2.0)
def _entropy(self):
return _EULER + 0.5*np.log(2*np.pi)-0.5
maxwell = maxwell_gen(a=0.0, name='maxwell')
| maxwell_gen |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor25.py | {
"start": 765,
"end": 956
} | class ____(Generic[T]):
def method1(self) -> "C[T]":
return C[T]()
c1 = C[int]()
reveal_type(c1, expected_text="C[int]")
c2 = c1.method1()
reveal_type(c2, expected_text="C[int]")
| C |
python | huggingface__transformers | src/transformers/models/swiftformer/modeling_swiftformer.py | {
"start": 16560,
"end": 19203
} | class ____(SwiftFormerPreTrainedModel):
def __init__(self, config: SwiftFormerConfig) -> None:
super().__init__(config)
embed_dims = config.embed_dims
self.num_labels = config.num_labels
self.swiftformer = SwiftFormerModel(config)
# Classifier head
self.norm = nn.BatchNorm2d(embed_dims[-1], eps=config.batch_norm_eps)
self.head = nn.Linear(embed_dims[-1], self.num_labels) if self.num_labels > 0 else nn.Identity()
self.dist_head = nn.Linear(embed_dims[-1], self.num_labels) if self.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# run base model
outputs = self.swiftformer(
pixel_values,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs.last_hidden_state if return_dict else outputs[0]
# run classification head
sequence_output = self.norm(sequence_output)
sequence_output = sequence_output.flatten(2).mean(-1)
cls_out = self.head(sequence_output)
distillation_out = self.dist_head(sequence_output)
logits = (cls_out + distillation_out) / 2
# calculate loss
loss = None
if labels is not None:
loss = self.loss_function(labels, logits, self.config)
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
)
__all__ = ["SwiftFormerForImageClassification", "SwiftFormerModel", "SwiftFormerPreTrainedModel"]
| SwiftFormerForImageClassification |
python | python-pillow__Pillow | src/PIL/IcoImagePlugin.py | {
"start": 4849,
"end": 10477
} | class ____:
def __init__(self, buf: IO[bytes]) -> None:
"""
Parse image from file-like object containing ico file data
"""
# check magic
s = buf.read(6)
if not _accept(s):
msg = "not an ICO file"
raise SyntaxError(msg)
self.buf = buf
self.entry = []
# Number of items in file
self.nb_items = i16(s, 4)
# Get headers for each item
for i in range(self.nb_items):
s = buf.read(16)
# See Wikipedia
width = s[0] or 256
height = s[1] or 256
# No. of colors in image (0 if >=8bpp)
nb_color = s[2]
bpp = i16(s, 6)
icon_header = IconHeader(
width=width,
height=height,
nb_color=nb_color,
reserved=s[3],
planes=i16(s, 4),
bpp=i16(s, 6),
size=i32(s, 8),
offset=i32(s, 12),
dim=(width, height),
square=width * height,
# See Wikipedia notes about color depth.
# We need this just to differ images with equal sizes
color_depth=bpp or (nb_color != 0 and ceil(log(nb_color, 2))) or 256,
)
self.entry.append(icon_header)
self.entry = sorted(self.entry, key=lambda x: x.color_depth)
# ICO images are usually squares
self.entry = sorted(self.entry, key=lambda x: x.square, reverse=True)
def sizes(self) -> set[tuple[int, int]]:
"""
Get a set of all available icon sizes and color depths.
"""
return {(h.width, h.height) for h in self.entry}
def getentryindex(self, size: tuple[int, int], bpp: int | bool = False) -> int:
for i, h in enumerate(self.entry):
if size == h.dim and (bpp is False or bpp == h.color_depth):
return i
return 0
def getimage(self, size: tuple[int, int], bpp: int | bool = False) -> Image.Image:
"""
Get an image from the icon
"""
return self.frame(self.getentryindex(size, bpp))
def frame(self, idx: int) -> Image.Image:
"""
Get an image from frame idx
"""
header = self.entry[idx]
self.buf.seek(header.offset)
data = self.buf.read(8)
self.buf.seek(header.offset)
im: Image.Image
if data[:8] == PngImagePlugin._MAGIC:
# png frame
im = PngImagePlugin.PngImageFile(self.buf)
Image._decompression_bomb_check(im.size)
else:
# XOR + AND mask bmp frame
im = BmpImagePlugin.DibImageFile(self.buf)
Image._decompression_bomb_check(im.size)
# change tile dimension to only encompass XOR image
im._size = (im.size[0], int(im.size[1] / 2))
d, e, o, a = im.tile[0]
im.tile[0] = ImageFile._Tile(d, (0, 0) + im.size, o, a)
# figure out where AND mask image starts
if header.bpp == 32:
# 32-bit color depth icon image allows semitransparent areas
# PIL's DIB format ignores transparency bits, recover them.
# The DIB is packed in BGRX byte order where X is the alpha
# channel.
# Back up to start of bmp data
self.buf.seek(o)
# extract every 4th byte (eg. 3,7,11,15,...)
alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]
# convert to an 8bpp grayscale image
try:
mask = Image.frombuffer(
"L", # 8bpp
im.size, # (w, h)
alpha_bytes, # source chars
"raw", # raw decoder
("L", 0, -1), # 8bpp inverted, unpadded, reversed
)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
mask = None
else:
raise
else:
# get AND image from end of bitmap
w = im.size[0]
if (w % 32) > 0:
# bitmap row data is aligned to word boundaries
w += 32 - (im.size[0] % 32)
# the total mask data is
# padded row size * height / bits per char
total_bytes = int((w * im.size[1]) / 8)
and_mask_offset = header.offset + header.size - total_bytes
self.buf.seek(and_mask_offset)
mask_data = self.buf.read(total_bytes)
# convert raw data to image
try:
mask = Image.frombuffer(
"1", # 1 bpp
im.size, # (w, h)
mask_data, # source chars
"raw", # raw decoder
("1;I", int(w / 8), -1), # 1bpp inverted, padded, reversed
)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
mask = None
else:
raise
# now we have two images, im is XOR image and mask is AND image
# apply mask image as alpha channel
if mask:
im = im.convert("RGBA")
im.putalpha(mask)
return im
##
# Image plugin for Windows Icon files.
| IcoFile |
python | ray-project__ray | python/ray/serve/tests/test_standalone.py | {
"start": 20254,
"end": 24093
} | class ____:
pass
serve.run(A.bind())"""
run_string_as_driver(
driver_template.format(address=address, namespace="test_namespace1", port=8000)
)
run_string_as_driver(
driver_template.format(address=address, namespace="test_namespace2", port=8001)
)
def test_serve_start_different_http_checkpoint_options_warning(
ray_shutdown, propagate_logs, caplog
):
logger = logging.getLogger("ray.serve")
caplog.set_level(logging.WARNING, logger="ray.serve")
warning_msg = []
class WarningHandler(logging.Handler):
def emit(self, record):
warning_msg.append(self.format(record))
logger.addHandler(WarningHandler())
ray.init(namespace="serve-test")
serve.start()
# create a different config
test_http = dict(host="127.1.1.8", port=_get_random_port())
serve.start(http_options=test_http)
for test_config, msg in zip([["host", "port"]], warning_msg):
for test_msg in test_config:
if "Autoscaling metrics pusher thread" in msg:
continue
assert test_msg in msg
def test_recovering_controller_no_redeploy():
"""Ensure controller doesn't redeploy running deployments when recovering."""
ray_context = ray.init(namespace="x")
address = ray_context.address_info["address"]
serve.start()
client = _get_global_client()
@serve.deployment
def f():
pass
serve.run(f.bind())
num_actors = len(list_actors(address, filters=[("state", "=", "ALIVE")]))
assert num_actors > 0
pid = ray.get(client._controller.get_pid.remote())
ray.kill(client._controller, no_restart=False)
wait_for_condition(lambda: ray.get(client._controller.get_pid.remote()) != pid)
# Confirm that no new deployment is deployed over the next 5 seconds
with pytest.raises(RuntimeError):
wait_for_condition(
lambda: len(list_actors(address, filters=[("state", "=", "ALIVE")]))
> num_actors,
timeout=5,
)
serve.shutdown()
ray.shutdown()
def test_updating_status_message(lower_slow_startup_threshold_and_reset):
"""Check if status message says if a serve deployment has taken a long time"""
@serve.deployment(
num_replicas=5,
ray_actor_options={"num_cpus": 1},
)
def f(*args):
pass
serve._run(f.bind(), _blocking=False)
def updating_message():
deployment_status = (
serve.status().applications[SERVE_DEFAULT_APP_NAME].deployments["f"]
)
message_substring = "more than 1s to be scheduled."
return (deployment_status.status == "UPDATING") and (
message_substring in deployment_status.message
)
wait_for_condition(updating_message, timeout=20)
def test_unhealthy_override_updating_status(lower_slow_startup_threshold_and_reset):
"""
Check that if status is UNHEALTHY and there is a resource availability
issue, the status should not change. The issue that caused the deployment to
be unhealthy should be prioritized over this resource availability issue.
"""
@serve.deployment
class f:
def __init__(self):
self.num = 1 / 0
def __call__(self, request):
pass
serve._run(f.bind(), _blocking=False)
wait_for_condition(
lambda: serve.status()
.applications[SERVE_DEFAULT_APP_NAME]
.deployments["f"]
.status
== "DEPLOY_FAILED",
timeout=20,
)
with pytest.raises(RuntimeError):
wait_for_condition(
lambda: serve.status()
.applications[SERVE_DEFAULT_APP_NAME]
.deployments["f"]
.status
== "UPDATING",
timeout=10,
)
@serve.deployment(ray_actor_options={"num_cpus": 0})
| A |
python | plotly__plotly.py | plotly/graph_objs/bar/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9929
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar.marker.colorbar.title"
_path_str = "bar.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
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 family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this color bar's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.bar.marker.col
orbar.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
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.bar.marker.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.bar.marker.colorbar.title.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | wandb__wandb | wandb/apis/public/teams.py | {
"start": 409,
"end": 1508
} | class ____(Attrs):
"""A member of a team.
Args:
client (`wandb.apis.internal.Api`): The client instance to use
team (str): The name of the team this member belongs to
attrs (dict): The member attributes
"""
DELETE_MEMBER_MUTATION = gql(
"""
mutation DeleteInvite($id: String, $entityName: String) {
deleteInvite(input: {id: $id, entityName: $entityName}) {
success
}
}
"""
)
def __init__(self, client, team, attrs):
super().__init__(attrs)
self._client = client
self.team = team
def delete(self):
"""Remove a member from a team.
Returns:
Boolean indicating success
"""
import requests
try:
return self._client.execute(
self.DELETE_MEMBER_MUTATION, {"id": self.id, "entityName": self.team}
)["deleteInvite"]["success"]
except requests.exceptions.HTTPError:
return False
def __repr__(self):
return f"<Member {self.name} ({self.account_type})>"
| Member |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/sac/optimizer_torch.py | {
"start": 1662,
"end": 26502
} | class ____(TorchOptimizer):
class PolicyValueNetwork(nn.Module):
def __init__(
self,
stream_names: List[str],
observation_specs: List[ObservationSpec],
network_settings: NetworkSettings,
action_spec: ActionSpec,
):
super().__init__()
num_value_outs = max(sum(action_spec.discrete_branches), 1)
num_action_ins = int(action_spec.continuous_size)
self.q1_network = ValueNetwork(
stream_names,
observation_specs,
network_settings,
num_action_ins,
num_value_outs,
)
self.q2_network = ValueNetwork(
stream_names,
observation_specs,
network_settings,
num_action_ins,
num_value_outs,
)
def forward(
self,
inputs: List[torch.Tensor],
actions: Optional[torch.Tensor] = None,
memories: Optional[torch.Tensor] = None,
sequence_length: int = 1,
q1_grad: bool = True,
q2_grad: bool = True,
) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
"""
Performs a forward pass on the value network, which consists of a Q1 and Q2
network. Optionally does not evaluate gradients for either the Q1, Q2, or both.
:param inputs: List of observation tensors.
:param actions: For a continuous Q function (has actions), tensor of actions.
Otherwise, None.
:param memories: Initial memories if using memory. Otherwise, None.
:param sequence_length: Sequence length if using memory.
:param q1_grad: Whether or not to compute gradients for the Q1 network.
:param q2_grad: Whether or not to compute gradients for the Q2 network.
:return: Tuple of two dictionaries, which both map {reward_signal: Q} for Q1 and Q2,
respectively.
"""
# ExitStack allows us to enter the torch.no_grad() context conditionally
with ExitStack() as stack:
if not q1_grad:
stack.enter_context(torch.no_grad())
q1_out, _ = self.q1_network(
inputs,
actions=actions,
memories=memories,
sequence_length=sequence_length,
)
with ExitStack() as stack:
if not q2_grad:
stack.enter_context(torch.no_grad())
q2_out, _ = self.q2_network(
inputs,
actions=actions,
memories=memories,
sequence_length=sequence_length,
)
return q1_out, q2_out
class TargetEntropy(NamedTuple):
discrete: List[float] = [] # One per branch
continuous: float = 0.0
class LogEntCoef(nn.Module):
def __init__(self, discrete, continuous):
super().__init__()
self.discrete = discrete
self.continuous = continuous
def __init__(self, policy: TorchPolicy, trainer_settings: TrainerSettings):
super().__init__(policy, trainer_settings)
reward_signal_configs = trainer_settings.reward_signals
reward_signal_names = [key.value for key, _ in reward_signal_configs.items()]
if isinstance(policy.actor, SharedActorCritic):
raise UnityTrainerException("SAC does not support SharedActorCritic")
self._critic = ValueNetwork(
reward_signal_names,
policy.behavior_spec.observation_specs,
policy.network_settings,
)
hyperparameters: SACSettings = cast(
SACSettings, trainer_settings.hyperparameters
)
self.tau = hyperparameters.tau
self.init_entcoef = hyperparameters.init_entcoef
self.policy = policy
policy_network_settings = policy.network_settings
self.tau = hyperparameters.tau
self.burn_in_ratio = 0.0
# Non-exposed SAC parameters
self.discrete_target_entropy_scale = 0.2 # Roughly equal to e-greedy 0.05
self.continuous_target_entropy_scale = 1.0
self.stream_names = list(self.reward_signals.keys())
# Use to reduce "survivor bonus" when using Curiosity or GAIL.
self.gammas = [_val.gamma for _val in trainer_settings.reward_signals.values()]
self.use_dones_in_backup = {
name: int(not self.reward_signals[name].ignore_done)
for name in self.stream_names
}
self._action_spec = self.policy.behavior_spec.action_spec
self.q_network = TorchSACOptimizer.PolicyValueNetwork(
self.stream_names,
self.policy.behavior_spec.observation_specs,
policy_network_settings,
self._action_spec,
)
self.target_network = ValueNetwork(
self.stream_names,
self.policy.behavior_spec.observation_specs,
policy_network_settings,
)
ModelUtils.soft_update(self._critic, self.target_network, 1.0)
# We create one entropy coefficient per action, whether discrete or continuous.
_disc_log_ent_coef = torch.nn.Parameter(
torch.log(
torch.as_tensor(
[self.init_entcoef] * len(self._action_spec.discrete_branches)
)
),
requires_grad=True,
)
_cont_log_ent_coef = torch.nn.Parameter(
torch.log(torch.as_tensor([self.init_entcoef])), requires_grad=True
)
self._log_ent_coef = TorchSACOptimizer.LogEntCoef(
discrete=_disc_log_ent_coef, continuous=_cont_log_ent_coef
)
_cont_target = (
-1
* self.continuous_target_entropy_scale
* np.prod(self._action_spec.continuous_size).astype(np.float32)
)
_disc_target = [
self.discrete_target_entropy_scale * np.log(i).astype(np.float32)
for i in self._action_spec.discrete_branches
]
self.target_entropy = TorchSACOptimizer.TargetEntropy(
continuous=_cont_target, discrete=_disc_target
)
policy_params = list(self.policy.actor.parameters())
value_params = list(self.q_network.parameters()) + list(
self._critic.parameters()
)
logger.debug("value_vars")
for param in value_params:
logger.debug(param.shape)
logger.debug("policy_vars")
for param in policy_params:
logger.debug(param.shape)
self.decay_learning_rate = ModelUtils.DecayedValue(
hyperparameters.learning_rate_schedule,
hyperparameters.learning_rate,
1e-10,
self.trainer_settings.max_steps,
)
self.policy_optimizer = torch.optim.Adam(
policy_params, lr=hyperparameters.learning_rate
)
self.value_optimizer = torch.optim.Adam(
value_params, lr=hyperparameters.learning_rate
)
self.entropy_optimizer = torch.optim.Adam(
self._log_ent_coef.parameters(), lr=hyperparameters.learning_rate
)
self._move_to_device(default_device())
@property
def critic(self):
return self._critic
def _move_to_device(self, device: torch.device) -> None:
self._log_ent_coef.to(device)
self.target_network.to(device)
self._critic.to(device)
self.q_network.to(device)
def sac_q_loss(
self,
q1_out: Dict[str, torch.Tensor],
q2_out: Dict[str, torch.Tensor],
target_values: Dict[str, torch.Tensor],
dones: torch.Tensor,
rewards: Dict[str, torch.Tensor],
loss_masks: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
q1_losses = []
q2_losses = []
# Multiple q losses per stream
for i, name in enumerate(q1_out.keys()):
q1_stream = q1_out[name].squeeze()
q2_stream = q2_out[name].squeeze()
with torch.no_grad():
q_backup = rewards[name] + (
(1.0 - self.use_dones_in_backup[name] * dones)
* self.gammas[i]
* target_values[name]
)
_q1_loss = 0.5 * ModelUtils.masked_mean(
torch.nn.functional.mse_loss(q_backup, q1_stream), loss_masks
)
_q2_loss = 0.5 * ModelUtils.masked_mean(
torch.nn.functional.mse_loss(q_backup, q2_stream), loss_masks
)
q1_losses.append(_q1_loss)
q2_losses.append(_q2_loss)
q1_loss = torch.mean(torch.stack(q1_losses))
q2_loss = torch.mean(torch.stack(q2_losses))
return q1_loss, q2_loss
def sac_value_loss(
self,
log_probs: ActionLogProbs,
values: Dict[str, torch.Tensor],
q1p_out: Dict[str, torch.Tensor],
q2p_out: Dict[str, torch.Tensor],
loss_masks: torch.Tensor,
) -> torch.Tensor:
min_policy_qs = {}
with torch.no_grad():
_cont_ent_coef = self._log_ent_coef.continuous.exp()
_disc_ent_coef = self._log_ent_coef.discrete.exp()
for name in values.keys():
if self._action_spec.discrete_size <= 0:
min_policy_qs[name] = torch.min(q1p_out[name], q2p_out[name])
else:
disc_action_probs = log_probs.all_discrete_tensor.exp()
_branched_q1p = ModelUtils.break_into_branches(
q1p_out[name] * disc_action_probs,
self._action_spec.discrete_branches,
)
_branched_q2p = ModelUtils.break_into_branches(
q2p_out[name] * disc_action_probs,
self._action_spec.discrete_branches,
)
_q1p_mean = torch.mean(
torch.stack(
[
torch.sum(_br, dim=1, keepdim=True)
for _br in _branched_q1p
]
),
dim=0,
)
_q2p_mean = torch.mean(
torch.stack(
[
torch.sum(_br, dim=1, keepdim=True)
for _br in _branched_q2p
]
),
dim=0,
)
min_policy_qs[name] = torch.min(_q1p_mean, _q2p_mean)
value_losses = []
if self._action_spec.discrete_size <= 0:
for name in values.keys():
with torch.no_grad():
v_backup = min_policy_qs[name] - torch.sum(
_cont_ent_coef * log_probs.continuous_tensor, dim=1
)
value_loss = 0.5 * ModelUtils.masked_mean(
torch.nn.functional.mse_loss(values[name], v_backup), loss_masks
)
value_losses.append(value_loss)
else:
disc_log_probs = log_probs.all_discrete_tensor
branched_per_action_ent = ModelUtils.break_into_branches(
disc_log_probs * disc_log_probs.exp(),
self._action_spec.discrete_branches,
)
# We have to do entropy bonus per action branch
branched_ent_bonus = torch.stack(
[
torch.sum(_disc_ent_coef[i] * _lp, dim=1, keepdim=True)
for i, _lp in enumerate(branched_per_action_ent)
]
)
for name in values.keys():
with torch.no_grad():
v_backup = min_policy_qs[name] - torch.mean(
branched_ent_bonus, axis=0
)
# Add continuous entropy bonus to minimum Q
if self._action_spec.continuous_size > 0:
v_backup += torch.sum(
_cont_ent_coef * log_probs.continuous_tensor,
dim=1,
keepdim=True,
)
value_loss = 0.5 * ModelUtils.masked_mean(
torch.nn.functional.mse_loss(values[name], v_backup.squeeze()),
loss_masks,
)
value_losses.append(value_loss)
value_loss = torch.mean(torch.stack(value_losses))
if torch.isinf(value_loss).any() or torch.isnan(value_loss).any():
raise UnityTrainerException("Inf found")
return value_loss
def sac_policy_loss(
self,
log_probs: ActionLogProbs,
q1p_outs: Dict[str, torch.Tensor],
loss_masks: torch.Tensor,
) -> torch.Tensor:
_cont_ent_coef, _disc_ent_coef = (
self._log_ent_coef.continuous,
self._log_ent_coef.discrete,
)
_cont_ent_coef = _cont_ent_coef.exp()
_disc_ent_coef = _disc_ent_coef.exp()
mean_q1 = torch.mean(torch.stack(list(q1p_outs.values())), axis=0)
batch_policy_loss = 0
if self._action_spec.discrete_size > 0:
disc_log_probs = log_probs.all_discrete_tensor
disc_action_probs = disc_log_probs.exp()
branched_per_action_ent = ModelUtils.break_into_branches(
disc_log_probs * disc_action_probs, self._action_spec.discrete_branches
)
branched_q_term = ModelUtils.break_into_branches(
mean_q1 * disc_action_probs, self._action_spec.discrete_branches
)
branched_policy_loss = torch.stack(
[
torch.sum(_disc_ent_coef[i] * _lp - _qt, dim=1, keepdim=False)
for i, (_lp, _qt) in enumerate(
zip(branched_per_action_ent, branched_q_term)
)
],
dim=1,
)
batch_policy_loss += torch.sum(branched_policy_loss, dim=1)
all_mean_q1 = torch.sum(disc_action_probs * mean_q1, dim=1)
else:
all_mean_q1 = mean_q1
if self._action_spec.continuous_size > 0:
cont_log_probs = log_probs.continuous_tensor
batch_policy_loss += (
_cont_ent_coef * torch.sum(cont_log_probs, dim=1) - all_mean_q1
)
policy_loss = ModelUtils.masked_mean(batch_policy_loss, loss_masks)
return policy_loss
def sac_entropy_loss(
self, log_probs: ActionLogProbs, loss_masks: torch.Tensor
) -> torch.Tensor:
_cont_ent_coef, _disc_ent_coef = (
self._log_ent_coef.continuous,
self._log_ent_coef.discrete,
)
entropy_loss = 0
if self._action_spec.discrete_size > 0:
with torch.no_grad():
# Break continuous into separate branch
disc_log_probs = log_probs.all_discrete_tensor
branched_per_action_ent = ModelUtils.break_into_branches(
disc_log_probs * disc_log_probs.exp(),
self._action_spec.discrete_branches,
)
target_current_diff_branched = torch.stack(
[
torch.sum(_lp, axis=1, keepdim=True) + _te
for _lp, _te in zip(
branched_per_action_ent, self.target_entropy.discrete
)
],
axis=1,
)
target_current_diff = torch.squeeze(
target_current_diff_branched, axis=2
)
entropy_loss += -1 * ModelUtils.masked_mean(
torch.mean(_disc_ent_coef * target_current_diff, axis=1), loss_masks
)
if self._action_spec.continuous_size > 0:
with torch.no_grad():
cont_log_probs = log_probs.continuous_tensor
target_current_diff = (
torch.sum(cont_log_probs, dim=1) + self.target_entropy.continuous
)
# We update all the _cont_ent_coef as one block
entropy_loss += -1 * ModelUtils.masked_mean(
_cont_ent_coef * target_current_diff, loss_masks
)
return entropy_loss
def _condense_q_streams(
self, q_output: Dict[str, torch.Tensor], discrete_actions: torch.Tensor
) -> Dict[str, torch.Tensor]:
condensed_q_output = {}
onehot_actions = ModelUtils.actions_to_onehot(
discrete_actions, self._action_spec.discrete_branches
)
for key, item in q_output.items():
branched_q = ModelUtils.break_into_branches(
item, self._action_spec.discrete_branches
)
only_action_qs = torch.stack(
[
torch.sum(_act * _q, dim=1, keepdim=True)
for _act, _q in zip(onehot_actions, branched_q)
]
)
condensed_q_output[key] = torch.mean(only_action_qs, dim=0)
return condensed_q_output
@timed
def update(self, batch: AgentBuffer, num_sequences: int) -> Dict[str, float]:
"""
Updates model using buffer.
:param num_sequences: Number of trajectories in batch.
:param batch: Experience mini-batch.
:param update_target: Whether or not to update target value network
:param reward_signal_batches: Minibatches to use for updating the reward signals,
indexed by name. If none, don't update the reward signals.
:return: Output from update process.
"""
rewards = {}
for name in self.reward_signals:
rewards[name] = ModelUtils.list_to_tensor(
batch[RewardSignalUtil.rewards_key(name)]
)
n_obs = len(self.policy.behavior_spec.observation_specs)
current_obs = ObsUtil.from_buffer(batch, n_obs)
# Convert to tensors
current_obs = [ModelUtils.list_to_tensor(obs) for obs in current_obs]
next_obs = ObsUtil.from_buffer_next(batch, n_obs)
# Convert to tensors
next_obs = [ModelUtils.list_to_tensor(obs) for obs in next_obs]
act_masks = ModelUtils.list_to_tensor(batch[BufferKey.ACTION_MASK])
actions = AgentAction.from_buffer(batch)
memories_list = [
ModelUtils.list_to_tensor(batch[BufferKey.MEMORY][i])
for i in range(0, len(batch[BufferKey.MEMORY]), self.policy.sequence_length)
]
# LSTM shouldn't have sequence length <1, but stop it from going out of the index if true.
value_memories_list = [
ModelUtils.list_to_tensor(batch[BufferKey.CRITIC_MEMORY][i])
for i in range(
0, len(batch[BufferKey.CRITIC_MEMORY]), self.policy.sequence_length
)
]
if len(memories_list) > 0:
memories = torch.stack(memories_list).unsqueeze(0)
value_memories = torch.stack(value_memories_list).unsqueeze(0)
else:
memories = None
value_memories = None
# Q and V network memories are 0'ed out, since we don't have them during inference.
q_memories = (
torch.zeros_like(value_memories) if value_memories is not None else None
)
# Copy normalizers from policy
self.q_network.q1_network.network_body.copy_normalization(
self.policy.actor.network_body
)
self.q_network.q2_network.network_body.copy_normalization(
self.policy.actor.network_body
)
self.target_network.network_body.copy_normalization(
self.policy.actor.network_body
)
self._critic.network_body.copy_normalization(self.policy.actor.network_body)
sampled_actions, run_out, _, = self.policy.actor.get_action_and_stats(
current_obs,
masks=act_masks,
memories=memories,
sequence_length=self.policy.sequence_length,
)
log_probs = run_out["log_probs"]
value_estimates, _ = self._critic.critic_pass(
current_obs, value_memories, sequence_length=self.policy.sequence_length
)
cont_sampled_actions = sampled_actions.continuous_tensor
cont_actions = actions.continuous_tensor
q1p_out, q2p_out = self.q_network(
current_obs,
cont_sampled_actions,
memories=q_memories,
sequence_length=self.policy.sequence_length,
q2_grad=False,
)
q1_out, q2_out = self.q_network(
current_obs,
cont_actions,
memories=q_memories,
sequence_length=self.policy.sequence_length,
)
if self._action_spec.discrete_size > 0:
disc_actions = actions.discrete_tensor
q1_stream = self._condense_q_streams(q1_out, disc_actions)
q2_stream = self._condense_q_streams(q2_out, disc_actions)
else:
q1_stream, q2_stream = q1_out, q2_out
with torch.no_grad():
# Since we didn't record the next value memories, evaluate one step in the critic to
# get them.
if value_memories is not None:
# Get the first observation in each sequence
just_first_obs = [
_obs[:: self.policy.sequence_length] for _obs in current_obs
]
_, next_value_memories = self._critic.critic_pass(
just_first_obs, value_memories, sequence_length=1
)
else:
next_value_memories = None
target_values, _ = self.target_network(
next_obs,
memories=next_value_memories,
sequence_length=self.policy.sequence_length,
)
masks = ModelUtils.list_to_tensor(batch[BufferKey.MASKS], dtype=torch.bool)
dones = ModelUtils.list_to_tensor(batch[BufferKey.DONE])
q1_loss, q2_loss = self.sac_q_loss(
q1_stream, q2_stream, target_values, dones, rewards, masks
)
value_loss = self.sac_value_loss(
log_probs, value_estimates, q1p_out, q2p_out, masks
)
policy_loss = self.sac_policy_loss(log_probs, q1p_out, masks)
entropy_loss = self.sac_entropy_loss(log_probs, masks)
total_value_loss = q1_loss + q2_loss + value_loss
decay_lr = self.decay_learning_rate.get_value(self.policy.get_current_step())
ModelUtils.update_learning_rate(self.policy_optimizer, decay_lr)
self.policy_optimizer.zero_grad()
policy_loss.backward()
self.policy_optimizer.step()
ModelUtils.update_learning_rate(self.value_optimizer, decay_lr)
self.value_optimizer.zero_grad()
total_value_loss.backward()
self.value_optimizer.step()
ModelUtils.update_learning_rate(self.entropy_optimizer, decay_lr)
self.entropy_optimizer.zero_grad()
entropy_loss.backward()
self.entropy_optimizer.step()
# Update target network
ModelUtils.soft_update(self._critic, self.target_network, self.tau)
update_stats = {
"Losses/Policy Loss": policy_loss.item(),
"Losses/Value Loss": value_loss.item(),
"Losses/Q1 Loss": q1_loss.item(),
"Losses/Q2 Loss": q2_loss.item(),
"Policy/Discrete Entropy Coeff": torch.mean(
torch.exp(self._log_ent_coef.discrete)
).item(),
"Policy/Continuous Entropy Coeff": torch.mean(
torch.exp(self._log_ent_coef.continuous)
).item(),
"Policy/Learning Rate": decay_lr,
}
return update_stats
def get_modules(self):
modules = {
"Optimizer:q_network": self.q_network,
"Optimizer:value_network": self._critic,
"Optimizer:target_network": self.target_network,
"Optimizer:policy_optimizer": self.policy_optimizer,
"Optimizer:value_optimizer": self.value_optimizer,
"Optimizer:entropy_optimizer": self.entropy_optimizer,
}
for reward_provider in self.reward_signals.values():
modules.update(reward_provider.get_modules())
return modules
| TorchSACOptimizer |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp-pandas/dagster_gcp_pandas/bigquery/bigquery_pandas_type_handler.py | {
"start": 7446,
"end": 11323
} | class ____(BigQueryIOManager):
"""An I/O manager definition that reads inputs from and writes pandas DataFrames to BigQuery.
Returns:
IOManagerDefinition
Examples:
.. code-block:: python
from dagster_gcp_pandas import BigQueryPandasIOManager
from dagster import Definitions, EnvVar
@asset(
key_prefix=["my_dataset"] # will be used as the dataset in BigQuery
)
def my_table() -> pd.DataFrame: # the name of the asset will be the table name
...
Definitions(
assets=[my_table],
resources={
"io_manager": BigQueryPandasIOManager(project=EnvVar("GCP_PROJECT"))
}
)
You can set a default dataset to store the assets using the ``dataset`` configuration value of the BigQuery I/O
Manager. This dataset will be used if no other dataset is specified directly on an asset or op.
.. code-block:: python
Definitions(
assets=[my_table],
resources={
"io_manager": BigQueryPandasIOManager(project=EnvVar("GCP_PROJECT"), dataset="my_dataset")
}
)
On individual assets, you an also specify the dataset where they should be stored using metadata or
by adding a ``key_prefix`` to the asset key. If both ``key_prefix`` and metadata are defined, the metadata will
take precedence.
.. code-block:: python
@asset(
key_prefix=["my_dataset"] # will be used as the dataset in BigQuery
)
def my_table() -> pd.DataFrame:
...
@asset(
# note that the key needs to be "schema"
metadata={"schema": "my_dataset"} # will be used as the dataset in BigQuery
)
def my_other_table() -> pd.DataFrame:
...
For ops, the dataset can be specified by including a "schema" entry in output metadata.
.. code-block:: python
@op(
out={"my_table": Out(metadata={"schema": "my_schema"})}
)
def make_my_table() -> pd.DataFrame:
...
If none of these is provided, the dataset will default to "public".
To only use specific columns of a table as input to a downstream op or asset, add the metadata "columns" to the
In or AssetIn.
.. code-block:: python
@asset(
ins={"my_table": AssetIn("my_table", metadata={"columns": ["a"]})}
)
def my_table_a(my_table: pd.DataFrame) -> pd.DataFrame:
# my_table will just contain the data from column "a"
...
If you cannot upload a file to your Dagster deployment, or otherwise cannot
`authenticate with GCP <https://cloud.google.com/docs/authentication/provide-credentials-adc>`_
via a standard method, you can provide a service account key as the "gcp_credentials" configuration.
Dagster will store this key in a temporary file and set GOOGLE_APPLICATION_CREDENTIALS to point to the file.
After the run completes, the file will be deleted, and GOOGLE_APPLICATION_CREDENTIALS will be
unset. The key must be base64 encoded to avoid issues with newlines in the keys. You can retrieve
the base64 encoded key with this shell command: cat $GOOGLE_APPLICATION_CREDENTIALS | base64
"""
@classmethod
def _is_dagster_maintained(cls) -> bool:
return True
@staticmethod
def type_handlers() -> Sequence[DbTypeHandler]:
return [BigQueryPandasTypeHandler()]
@staticmethod
def default_load_type() -> Optional[type]:
return pd.DataFrame
| BigQueryPandasIOManager |
python | dask__dask | dask/dataframe/dask_expr/_util.py | {
"start": 3096,
"end": 3700
} | class ____(UserDict[K, V]):
"""Limited size mapping, evicting the least recently looked-up key when full"""
def __init__(self, maxsize: float) -> None:
super().__init__()
self.data = OrderedDict()
self.maxsize = maxsize
def __getitem__(self, key: K) -> V:
value = super().__getitem__(key)
cast(OrderedDict, self.data).move_to_end(key)
return value
def __setitem__(self, key: K, value: V) -> None:
if len(self) >= self.maxsize:
cast(OrderedDict, self.data).popitem(last=False)
super().__setitem__(key, value)
| LRU |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 13652,
"end": 15068
} | class ____(Widget):
"""A representation of ``st.color_picker``."""
_value: str | None
label: str
help: str
form_id: str
proto: ColorPickerProto = field(repr=False)
def __init__(self, proto: ColorPickerProto, root: ElementTree) -> None:
super().__init__(proto, root)
self.type = "color_picker"
@property
def value(self) -> str:
"""The currently selected value as a hex string. (str)""" # noqa: D400
if self._value is not None:
return self._value
state = self.root.session_state
assert state
return cast("str", state[self.id])
@property
def _widget_state(self) -> WidgetState:
"""Protobuf message representing the state of the widget, including
any interactions that have happened.
Should be the same as the frontend would produce for those interactions.
"""
ws = WidgetState()
ws.id = self.id
ws.string_value = self.value
return ws
def set_value(self, v: str) -> ColorPicker:
"""Set the value of the widget as a hex string."""
self._value = v
return self
def pick(self, v: str) -> ColorPicker:
"""Set the value of the widget as a hex string. May omit the "#" prefix."""
if not v.startswith("#"):
v = f"#{v}"
return self.set_value(v)
@dataclass(repr=False)
| ColorPicker |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 110,
"end": 761
} | class ____(ValueError, TOMLKitError):
"""
This error occurs when the parser encounters a syntax error
in the TOML being parsed. The error references the line and
location within the line where the error was encountered.
"""
def __init__(self, line: int, col: int, message: str | None = None) -> None:
self._line = line
self._col = col
if message is None:
message = "TOML parse error"
super().__init__(f"{message} at line {self._line} col {self._col}")
@property
def line(self):
return self._line
@property
def col(self):
return self._col
| ParseError |
python | getsentry__sentry | src/sentry/backup/dependencies.py | {
"start": 3769,
"end": 3965
} | class ____(NamedTuple):
"""A field that creates a dependency on another Sentry model."""
model: type[models.base.Model]
kind: ForeignFieldKind
nullable: bool
@dataclass
| ForeignField |
python | sympy__sympy | bin/coverage_doctest.py | {
"start": 8598,
"end": 23278
} | class ____(HTMLParser):
is_imported = []
def handle_starttag(self, tag, attr):
a = dict(attr)
if tag == "div" and a.get('class', None) == "viewcode-block":
self.is_imported.append(a['id'])
def find_sphinx(name, mod_path, found={}):
if mod_path in found: # Cache results
return name in found[mod_path]
doc_path = mod_path.split('.')
doc_path[-1] += '.html'
sphinx_path = os.path.join(sympy_top, 'doc', '_build', 'html', '_modules', *doc_path)
if not os.path.exists(sphinx_path):
return False
html_txt = Path(sphinx_path).read_text()
p = FindInSphinx()
p.feed(html_txt)
found[mod_path] = p.is_imported
return name in p.is_imported
def process_function(name, c_name, b_obj, mod_path, f_skip, f_missing_doc, f_missing_doctest, f_indirect_doctest,
f_has_doctest, skip_list, sph, sphinx=True):
"""
Processes a function to get information regarding documentation.
It is assume that the function calling this subrouting has already
verified that it is a valid module function.
"""
if name in skip_list:
return False, False
# We add in the end, as inspect.getsourcelines is slow
add_missing_doc = False
add_missing_doctest = False
add_indirect_doctest = False
in_sphinx = True
f_doctest = False
function = False
if inspect.isclass(b_obj):
obj = getattr(b_obj, name)
obj_name = c_name + '.' + name
else:
obj = b_obj
obj_name = name
full_name = _get_arg_list(name, obj)
if name.startswith('_'):
f_skip.append(full_name)
else:
doc = obj.__doc__
if isinstance(doc, str):
if not doc:
add_missing_doc = True
elif not '>>>' in doc:
add_missing_doctest = True
elif _is_indirect(name, doc):
add_indirect_doctest = True
else:
f_doctest = True
elif doc is None:
# this was a function defined in the docstring
f_doctest = True
else:
raise TypeError('Current doc type for ', print(obj), ' is ', type(doc), '. Docstring must be a string, property, or none')
function = True
if sphinx:
in_sphinx = find_sphinx(obj_name, mod_path)
if add_missing_doc or add_missing_doctest or add_indirect_doctest or not in_sphinx:
try:
line_no = inspect.getsourcelines(obj)[1]
except IOError:
# Raised when source does not exist
# which means the function is not there.
return False, False
full_name = "LINE %d: %s" % (line_no, full_name)
if add_missing_doc:
f_missing_doc.append(full_name)
elif add_missing_doctest:
f_missing_doctest.append(full_name)
elif add_indirect_doctest:
f_indirect_doctest.append(full_name)
if not in_sphinx:
sph.append(full_name)
return f_doctest, function
def process_class(c_name, obj, c_skip, c_missing_doc, c_missing_doctest, c_indirect_doctest, c_has_doctest,
mod_path, sph, sphinx=True):
"""
Extracts information about the class regarding documentation.
It is assumed that the function calling this subroutine has already
checked that the class is valid.
"""
# Skip class case
if c_name.startswith('_'):
c_skip.append(c_name)
return False, False, None
c = False
c_dt = False
# Get the line number of class
try:
source, line_no = inspect.getsourcelines(obj)
except IOError:
# Raised when source does not exist
# which means the class is not there.
return False, False, None
c = True
full_name = "LINE %d: %s" % (line_no, c_name)
doc = obj.__doc__
if isinstance(doc, str):
if not doc:
c_missing_doc.append(full_name)
elif not '>>>' in doc:
c_missing_doctest.append(full_name)
elif _is_indirect(c_name, doc):
c_indirect_doctest.append(full_name)
else:
c_dt = True
c_has_doctest.append(full_name)
elif doc is None:
# this was a class defined in the docstring
c_dt = True
c_has_doctest.append(full_name)
elif isinstance(doc, property):
# skip class with dynamic doc
c_skip.append(c_name)
return False, False, None
else:
raise TypeError('Current doc type of ', print(obj), ' is ', type(doc), '. Docstring must be a string, property , or none')
in_sphinx = False
if sphinx:
in_sphinx = find_sphinx(c_name, mod_path)
if not in_sphinx:
sph.append(full_name)
return c_dt, c, source
def coverage(module_path, verbose=False, no_color=False, sphinx=True):
""" Given a module path, builds an index of all classes and functions
contained. It then goes through each of the classes/functions to get
the docstring and doctest coverage of the module. """
# Import the package and find members
m = None
try:
__import__(module_path)
m = sys.modules[module_path]
except Exception as a:
# Most likely cause, absence of __init__
print("%s could not be loaded due to %s." % (module_path, repr(a)))
return 0, 0, 0
c_skipped = []
c_missing_doc = []
c_missing_doctest = []
c_has_doctest = []
c_indirect_doctest = []
classes = 0
c_doctests = 0
c_sph = []
f_skipped = []
f_missing_doc = []
f_missing_doctest = []
f_has_doctest = []
f_indirect_doctest = []
functions = 0
f_doctests = 0
f_sph = []
skip_members = ['__abstractmethods__']
# Get the list of members
m_members = dir(m)
for member in m_members:
# Check for skipped functions first, they throw nasty errors
# when combined with getattr
if member in skip_members:
continue
# Identify if the member (class/def) is a part of this module
obj = getattr(m, member)
obj_mod = inspect.getmodule(obj)
# Function not a part of this module
if not obj_mod or not obj_mod.__name__ == module_path:
continue
# If it's a function
if inspect.isfunction(obj) or inspect.ismethod(obj):
f_dt, f = process_function(member, '', obj, module_path,
f_skipped, f_missing_doc, f_missing_doctest, f_indirect_doctest, f_has_doctest, skip_members,
f_sph, sphinx=sphinx)
if f:
functions += 1
if f_dt:
f_doctests += 1
# If it's a class, look at it's methods too
elif inspect.isclass(obj):
# Process the class first
c_dt, c, source = process_class(member, obj, c_skipped, c_missing_doc,
c_missing_doctest, c_indirect_doctest, c_has_doctest, module_path, c_sph, sphinx=sphinx)
if not c:
continue
else:
classes += 1
if c_dt:
c_doctests += 1
# Iterate through it's members
for f_name in obj.__dict__:
if f_name in skip_members or f_name.startswith('_'):
continue
# Check if def funcname appears in source
if not ("def " + f_name) in ' '.join(source):
continue
# Identify the module of the current class member
f_obj = getattr(obj, f_name)
obj_mod = inspect.getmodule(f_obj)
# Function not a part of this module
if not obj_mod or not obj_mod.__name__ == module_path:
continue
# If it's a function
if inspect.isfunction(f_obj) or inspect.ismethod(f_obj):
f_dt, f = process_function(f_name, member, obj,
module_path, f_skipped, f_missing_doc, f_missing_doctest, f_indirect_doctest, f_has_doctest,
skip_members, f_sph, sphinx=sphinx)
if f:
functions += 1
if f_dt:
f_doctests += 1
# Evaluate the percent coverage
total_doctests = c_doctests + f_doctests
total_members = classes + functions
if total_members:
score = 100 * float(total_doctests) / (total_members)
else:
score = 100
score = int(score)
if sphinx:
total_sphinx = len(c_sph) + len(f_sph)
if total_members:
sphinx_score = 100 - 100 * float(total_sphinx) / total_members
else:
sphinx_score = 100
sphinx_score = int(sphinx_score)
else:
total_sphinx = 0
sphinx_score = 0
# Sort functions/classes by line number
c_missing_doc = sorted(c_missing_doc, key=lambda x: int(x.split()[1][:-1]))
c_missing_doctest = sorted(c_missing_doctest, key=lambda x: int(x.split()[1][:-1]))
c_indirect_doctest = sorted(c_indirect_doctest, key=lambda x: int(x.split()[1][:-1]))
f_missing_doc = sorted(f_missing_doc, key=lambda x: int(x.split()[1][:-1]))
f_missing_doctest = sorted(f_missing_doctest, key=lambda x: int(x.split()[1][:-1]))
f_indirect_doctest = sorted(f_indirect_doctest, key=lambda x: int(x.split()[1][:-1]))
print_coverage(module_path, classes, c_missing_doc, c_missing_doctest, c_indirect_doctest, c_sph, functions, f_missing_doc,
f_missing_doctest, f_indirect_doctest, f_sph, score, total_doctests, total_members,
sphinx_score, total_sphinx, verbose=verbose,
no_color=no_color, sphinx=sphinx)
return total_doctests, total_sphinx, total_members
def go(sympy_top, file, verbose=False, no_color=False, exact=True, sphinx=True):
# file names containing any string in skip_paths will be skipped,
skip_paths = []
if os.path.isdir(file):
doctests, total_sphinx, num_functions = 0, 0, 0
for F in os.listdir(file):
_doctests, _total_sphinx, _num_functions = go(sympy_top, '%s/%s' % (file, F),
verbose=verbose, no_color=no_color, exact=False, sphinx=sphinx)
doctests += _doctests
total_sphinx += _total_sphinx
num_functions += _num_functions
return doctests, total_sphinx, num_functions
if (not (file.endswith((".py", ".pyx"))) or
file.endswith('__init__.py') or
not exact and ('test_' in file or 'bench_' in file or
any(name in file for name in skip_paths))):
return 0, 0, 0
if not os.path.exists(file):
print("File(%s does not exist." % file)
sys.exit(1)
# Relpath for constructing the module name
return coverage(get_mod_name(file, sympy_top), verbose=verbose,
no_color=no_color, sphinx=sphinx)
if __name__ == "__main__":
bintest_dir = os.path.abspath(os.path.dirname(__file__)) # bin/cover...
sympy_top = os.path.split(bintest_dir)[0] # ../
sympy_dir = os.path.join(sympy_top, 'sympy') # ../sympy/
if os.path.isdir(sympy_dir):
sys.path.insert(0, sympy_top)
usage = "usage: ./bin/doctest_coverage.py PATHS"
parser = ArgumentParser(
description=__doc__,
usage=usage,
formatter_class=RawDescriptionHelpFormatter,
)
parser.add_argument("path", nargs='*', default=[os.path.join(sympy_top, 'sympy')])
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose",
default=False)
parser.add_argument("--no-colors", action="store_true", dest="no_color",
help="use no colors", default=False)
parser.add_argument("--no-sphinx", action="store_false", dest="sphinx",
help="don't report Sphinx coverage", default=True)
args = parser.parse_args()
if args.sphinx and not os.path.exists(os.path.join(sympy_top, 'doc', '_build', 'html')):
print(filldedent("""
Cannot check Sphinx coverage without a documentation build.
To build the docs, run "cd doc; make html". To skip
checking Sphinx coverage, pass --no-sphinx.
"""))
sys.exit(1)
full_coverage = True
for file in args.path:
file = os.path.normpath(file)
print('DOCTEST COVERAGE for %s' % (file))
print('='*70)
print()
doctests, total_sphinx, num_functions = go(sympy_top, file, verbose=args.verbose,
no_color=args.no_color, sphinx=args.sphinx)
if num_functions == 0:
score = 100
sphinx_score = 100
else:
score = 100 * float(doctests) / num_functions
score = int(score)
if doctests < num_functions:
full_coverage = False
if args.sphinx:
sphinx_score = 100 - 100 * float(total_sphinx) / num_functions
sphinx_score = int(sphinx_score)
if total_sphinx > 0:
full_coverage = False
print()
print('='*70)
if args.no_color:
print("TOTAL DOCTEST SCORE for %s: %s%% (%s of %s)" % \
(get_mod_name(file, sympy_top), score, doctests, num_functions))
elif score < 100:
print("TOTAL DOCTEST SCORE for %s: %s%s%% (%s of %s)%s" % \
(get_mod_name(file, sympy_top), c_color % (colors["Red"]),
score, doctests, num_functions, c_normal))
else:
print("TOTAL DOCTEST SCORE for %s: %s%s%% (%s of %s)%s" % \
(get_mod_name(file, sympy_top), c_color % (colors["Green"]),
score, doctests, num_functions, c_normal))
if args.sphinx:
if args.no_color:
print("TOTAL SPHINX SCORE for %s: %s%% (%s of %s)" % \
(get_mod_name(file, sympy_top), sphinx_score,
num_functions - total_sphinx, num_functions))
elif sphinx_score < 100:
print("TOTAL SPHINX SCORE for %s: %s%s%% (%s of %s)%s" % \
(get_mod_name(file, sympy_top), c_color % (colors["Red"]),
sphinx_score, num_functions - total_sphinx, num_functions, c_normal))
else:
print("TOTAL SPHINX SCORE for %s: %s%s%% (%s of %s)%s" % \
(get_mod_name(file, sympy_top), c_color % (colors["Green"]),
sphinx_score, num_functions - total_sphinx, num_functions, c_normal))
print()
sys.exit(not full_coverage)
| FindInSphinx |
python | scikit-image__scikit-image | tests/skimage/feature/test_texture.py | {
"start": 12925,
"end": 13596
} | class ____:
def test_single_mblbp(self):
# Create dummy matrix where first and fifth rectangles have greater
# value than the central one. Therefore, the following bits
# should be 1.
test_img = np.zeros((9, 9), dtype='uint8')
test_img[3:6, 3:6] = 1
test_img[:3, :3] = 255
test_img[6:, 6:] = 255
# MB-LBP is filled in reverse order. So the first and fifth bits from
# the end should be filled.
correct_answer = 0b10001000
int_img = integral_image(test_img)
lbp_code = multiblock_lbp(int_img, 0, 0, 3, 3)
np.testing.assert_equal(lbp_code, correct_answer)
| TestMBLBP |
python | encode__django-rest-framework | tests/test_relations_hyperlink.py | {
"start": 2441,
"end": 11088
} | class ____(TestCase):
def setUp(self):
for idx in range(1, 4):
target = ManyToManyTarget(name='target-%d' % idx)
target.save()
source = ManyToManySource(name='source-%d' % idx)
source.save()
for target in ManyToManyTarget.objects.all():
source.targets.add(target)
def test_relative_hyperlinks(self):
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': None})
expected = [
{'url': '/manytomanysource/1/', 'name': 'source-1', 'targets': ['/manytomanytarget/1/']},
{'url': '/manytomanysource/2/', 'name': 'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': 'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}
]
with self.assertNumQueries(4):
assert serializer.data == expected
def test_many_to_many_retrieve(self):
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
{'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
]
with self.assertNumQueries(4):
assert serializer.data == expected
def test_many_to_many_retrieve_prefetch_related(self):
queryset = ManyToManySource.objects.all().prefetch_related('targets')
serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
with self.assertNumQueries(2):
serializer.data
def test_reverse_many_to_many_retrieve(self):
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
]
with self.assertNumQueries(4):
assert serializer.data == expected
def test_many_to_many_update(self):
data = {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
instance = ManyToManySource.objects.get(pk=1)
serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request})
assert serializer.is_valid()
serializer.save()
assert serializer.data == data
# Ensure source 1 is updated, and everything else is as expected
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
{'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
]
assert serializer.data == expected
def test_reverse_many_to_many_update(self):
data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}
instance = ManyToManyTarget.objects.get(pk=1)
serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request})
assert serializer.is_valid()
serializer.save()
assert serializer.data == data
# Ensure target 1 is updated, and everything else is as expected
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']},
{'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
]
assert serializer.data == expected
def test_many_to_many_create(self):
data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
serializer = ManyToManySourceSerializer(data=data, context={'request': request})
assert serializer.is_valid()
obj = serializer.save()
assert serializer.data == data
assert obj.name == 'source-4'
# Ensure source 4 is added, and everything else is as expected
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
{'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
{'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
]
assert serializer.data == expected
def test_reverse_many_to_many_create(self):
data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
serializer = ManyToManyTargetSerializer(data=data, context={'request': request})
assert serializer.is_valid()
obj = serializer.save()
assert serializer.data == data
assert obj.name == 'target-4'
# Ensure target 4 is added, and everything else is as expected
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [
{'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']},
{'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
]
assert serializer.data == expected
@override_settings(ROOT_URLCONF='tests.test_relations_hyperlink')
| HyperlinkedManyToManyTests |
python | ijl__orjson | test/test_datetime.py | {
"start": 807,
"end": 21133
} | class ____:
def test_datetime_naive(self):
"""
datetime.datetime naive prints without offset
"""
assert (
orjson.dumps([datetime.datetime(2000, 1, 1, 2, 3, 4, 123)])
== b'["2000-01-01T02:03:04.000123"]'
)
def test_datetime_naive_utc(self):
"""
datetime.datetime naive with opt assumes UTC
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_NAIVE_UTC,
)
== b'["2000-01-01T02:03:04.000123+00:00"]'
)
def test_datetime_min(self):
"""
datetime.datetime min range
"""
assert (
orjson.dumps(
[datetime.datetime(datetime.MINYEAR, 1, 1, 0, 0, 0, 0)],
option=orjson.OPT_NAIVE_UTC,
)
== b'["0001-01-01T00:00:00+00:00"]'
)
def test_datetime_max(self):
"""
datetime.datetime max range
"""
assert (
orjson.dumps(
[datetime.datetime(datetime.MAXYEAR, 12, 31, 23, 59, 50, 999999)],
option=orjson.OPT_NAIVE_UTC,
)
== b'["9999-12-31T23:59:50.999999+00:00"]'
)
def test_datetime_three_digits(self):
"""
datetime.datetime three digit year
"""
assert (
orjson.dumps(
[datetime.datetime(312, 1, 1)],
option=orjson.OPT_NAIVE_UTC,
)
== b'["0312-01-01T00:00:00+00:00"]'
)
def test_datetime_two_digits(self):
"""
datetime.datetime two digit year
"""
assert (
orjson.dumps(
[datetime.datetime(46, 1, 1)],
option=orjson.OPT_NAIVE_UTC,
)
== b'["0046-01-01T00:00:00+00:00"]'
)
@pytest.mark.skipif(tz is None, reason="dateutil optional")
def test_datetime_tz_assume(self):
"""
datetime.datetime tz with assume UTC uses tz
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
1,
1,
2,
3,
4,
0,
tzinfo=tz.gettz("Asia/Shanghai"),
),
],
option=orjson.OPT_NAIVE_UTC,
)
== b'["2018-01-01T02:03:04+08:00"]'
)
def test_datetime_timezone_utc(self):
"""
datetime.datetime.utc
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
6,
1,
2,
3,
4,
0,
tzinfo=datetime.timezone.utc,
),
],
)
== b'["2018-06-01T02:03:04+00:00"]'
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_pytz_utc(self):
"""
pytz.UTC
"""
assert (
orjson.dumps([datetime.datetime(2018, 6, 1, 2, 3, 4, 0, tzinfo=pytz.UTC)])
== b'["2018-06-01T02:03:04+00:00"]'
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_zoneinfo_utc(self):
"""
zoneinfo.ZoneInfo("UTC")
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
6,
1,
2,
3,
4,
0,
tzinfo=zoneinfo.ZoneInfo("UTC"),
),
],
)
== b'["2018-06-01T02:03:04+00:00"]'
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_zoneinfo_positive(self):
assert (
orjson.dumps(
[
datetime.datetime(
2018,
1,
1,
2,
3,
4,
0,
tzinfo=zoneinfo.ZoneInfo("Asia/Shanghai"),
),
],
)
== b'["2018-01-01T02:03:04+08:00"]'
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_zoneinfo_negative(self):
assert (
orjson.dumps(
[
datetime.datetime(
2018,
6,
1,
2,
3,
4,
0,
tzinfo=zoneinfo.ZoneInfo("America/New_York"),
),
],
)
== b'["2018-06-01T02:03:04-04:00"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_pendulum_utc(self):
"""
datetime.datetime UTC
"""
assert (
orjson.dumps(
[datetime.datetime(2018, 6, 1, 2, 3, 4, 0, tzinfo=pendulum.UTC)],
)
== b'["2018-06-01T02:03:04+00:00"]'
)
@pytest.mark.skipif(tz is None, reason="dateutil optional")
def test_datetime_arrow_positive(self):
"""
datetime.datetime positive UTC
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
1,
1,
2,
3,
4,
0,
tzinfo=tz.gettz("Asia/Shanghai"),
),
],
)
== b'["2018-01-01T02:03:04+08:00"]'
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_pytz_positive(self):
"""
datetime.datetime positive UTC
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
1,
1,
2,
3,
4,
0,
tzinfo=pytz.timezone("Asia/Shanghai"),
),
],
)
== b'["2018-01-01T02:03:04+08:00"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_pendulum_positive(self):
"""
datetime.datetime positive UTC
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
1,
1,
2,
3,
4,
0,
tzinfo=pendulum.timezone("Asia/Shanghai"), # type: ignore
),
],
)
== b'["2018-01-01T02:03:04+08:00"]'
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_pytz_negative_dst(self):
"""
datetime.datetime negative UTC DST
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
6,
1,
2,
3,
4,
0,
tzinfo=pytz.timezone("America/New_York"),
),
],
)
== b'["2018-06-01T02:03:04-04:00"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_pendulum_negative_dst(self):
"""
datetime.datetime negative UTC DST
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
6,
1,
2,
3,
4,
0,
tzinfo=pendulum.timezone("America/New_York"), # type: ignore
),
],
)
== b'["2018-06-01T02:03:04-04:00"]'
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_zoneinfo_negative_non_dst(self):
"""
datetime.datetime negative UTC non-DST
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=zoneinfo.ZoneInfo("America/New_York"),
),
],
)
== b'["2018-12-01T02:03:04-05:00"]'
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_pytz_negative_non_dst(self):
"""
datetime.datetime negative UTC non-DST
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=pytz.timezone("America/New_York"),
),
],
)
== b'["2018-12-01T02:03:04-05:00"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_pendulum_negative_non_dst(self):
"""
datetime.datetime negative UTC non-DST
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=pendulum.timezone("America/New_York"), # type: ignore
),
],
)
== b'["2018-12-01T02:03:04-05:00"]'
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_zoneinfo_partial_hour(self):
"""
datetime.datetime UTC offset partial hour
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide"),
),
],
)
== b'["2018-12-01T02:03:04+10:30"]'
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_pytz_partial_hour(self):
"""
datetime.datetime UTC offset partial hour
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=pytz.timezone("Australia/Adelaide"),
),
],
)
== b'["2018-12-01T02:03:04+10:30"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_pendulum_partial_hour(self):
"""
datetime.datetime UTC offset partial hour
"""
assert (
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
4,
0,
tzinfo=pendulum.timezone("Australia/Adelaide"), # type: ignore
),
],
)
== b'["2018-12-01T02:03:04+10:30"]'
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_partial_second_pendulum_supported(self):
"""
datetime.datetime UTC offset round seconds
https://tools.ietf.org/html/rfc3339#section-5.8
"""
assert (
orjson.dumps(
[
datetime.datetime(
1937,
1,
1,
12,
0,
27,
87,
tzinfo=pendulum.timezone("Europe/Amsterdam"), # type: ignore
),
],
)
in AMSTERDAM_1937_DATETIMES
)
@pytest.mark.skipif(zoneinfo is None, reason="zoneinfo not available")
def test_datetime_partial_second_zoneinfo(self):
"""
datetime.datetime UTC offset round seconds
https://tools.ietf.org/html/rfc3339#section-5.8
"""
assert (
orjson.dumps(
[
datetime.datetime(
1937,
1,
1,
12,
0,
27,
87,
tzinfo=zoneinfo.ZoneInfo("Europe/Amsterdam"),
),
],
)
in AMSTERDAM_1937_DATETIMES
)
@pytest.mark.skipif(pytz is None, reason="pytz optional")
def test_datetime_partial_second_pytz(self):
"""
datetime.datetime UTC offset round seconds
https://tools.ietf.org/html/rfc3339#section-5.8
"""
assert (
orjson.dumps(
[
datetime.datetime(
1937,
1,
1,
12,
0,
27,
87,
tzinfo=pytz.timezone("Europe/Amsterdam"),
),
],
)
in AMSTERDAM_1937_DATETIMES
)
@pytest.mark.skipif(tz is None, reason="dateutil optional")
def test_datetime_partial_second_dateutil(self):
"""
datetime.datetime UTC offset round seconds
https://tools.ietf.org/html/rfc3339#section-5.8
"""
assert (
orjson.dumps(
[
datetime.datetime(
1937,
1,
1,
12,
0,
27,
87,
tzinfo=tz.gettz("Europe/Amsterdam"),
),
],
)
in AMSTERDAM_1937_DATETIMES
)
def test_datetime_microsecond_max(self):
"""
datetime.datetime microsecond max
"""
assert (
orjson.dumps(datetime.datetime(2000, 1, 1, 0, 0, 0, 999999))
== b'"2000-01-01T00:00:00.999999"'
)
def test_datetime_microsecond_min(self):
"""
datetime.datetime microsecond min
"""
assert (
orjson.dumps(datetime.datetime(2000, 1, 1, 0, 0, 0, 1))
== b'"2000-01-01T00:00:00.000001"'
)
def test_datetime_omit_microseconds(self):
"""
datetime.datetime OPT_OMIT_MICROSECONDS
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_OMIT_MICROSECONDS,
)
== b'["2000-01-01T02:03:04"]'
)
def test_datetime_omit_microseconds_naive(self):
"""
datetime.datetime naive OPT_OMIT_MICROSECONDS
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_NAIVE_UTC | orjson.OPT_OMIT_MICROSECONDS,
)
== b'["2000-01-01T02:03:04+00:00"]'
)
def test_time_omit_microseconds(self):
"""
datetime.time OPT_OMIT_MICROSECONDS
"""
assert (
orjson.dumps(
[datetime.time(2, 3, 4, 123)],
option=orjson.OPT_OMIT_MICROSECONDS,
)
== b'["02:03:04"]'
)
def test_datetime_utc_z_naive_omit(self):
"""
datetime.datetime naive OPT_UTC_Z
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_NAIVE_UTC
| orjson.OPT_UTC_Z
| orjson.OPT_OMIT_MICROSECONDS,
)
== b'["2000-01-01T02:03:04Z"]'
)
def test_datetime_utc_z_naive(self):
"""
datetime.datetime naive OPT_UTC_Z
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z,
)
== b'["2000-01-01T02:03:04.000123Z"]'
)
def test_datetime_utc_z_without_tz(self):
"""
datetime.datetime naive OPT_UTC_Z
"""
assert (
orjson.dumps(
[datetime.datetime(2000, 1, 1, 2, 3, 4, 123)],
option=orjson.OPT_UTC_Z,
)
== b'["2000-01-01T02:03:04.000123"]'
)
@pytest.mark.skipif(tz is None, reason="dateutil optional")
def test_datetime_utc_z_with_tz(self):
"""
datetime.datetime naive OPT_UTC_Z
"""
assert (
orjson.dumps(
[
datetime.datetime(
2000,
1,
1,
0,
0,
0,
1,
tzinfo=datetime.timezone.utc,
),
],
option=orjson.OPT_UTC_Z,
)
== b'["2000-01-01T00:00:00.000001Z"]'
)
assert (
orjson.dumps(
[
datetime.datetime(
1937,
1,
1,
12,
0,
27,
87,
tzinfo=tz.gettz("Europe/Amsterdam"),
),
],
option=orjson.OPT_UTC_Z,
)
in AMSTERDAM_1937_DATETIMES_WITH_Z
)
@pytest.mark.skipif(pendulum is None, reason="pendulum not installed")
def test_datetime_roundtrip(self):
"""
datetime.datetime parsed by pendulum
"""
obj = datetime.datetime(2000, 1, 1, 0, 0, 0, 1, tzinfo=datetime.timezone.utc)
serialized = orjson.dumps(obj).decode("utf-8").replace('"', "")
parsed = pendulum.parse(serialized)
for attr in ("year", "month", "day", "hour", "minute", "second", "microsecond"):
assert getattr(obj, attr) == getattr(parsed, attr)
| TestDatetime |
python | streamlit__streamlit | scripts/generate_agent_rules.py | {
"start": 1413,
"end": 6544
} | class ____(TypedDict):
cursor_mdc: str
agents_md: str
globs: str
github_copilot: str
always_apply: bool
AGENT_RULE_FILES: Final[list[AgentRuleFile]] = [
{
"cursor_mdc": ".cursor/rules/e2e_playwright.mdc",
"github_copilot": ".github/instructions/e2e_playwright.instructions.md",
"agents_md": "e2e_playwright/AGENTS.md",
"globs": "e2e_playwright/**/*.py",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/python.mdc",
"github_copilot": ".github/instructions/python.instructions.md",
"agents_md": "lib/AGENTS.md",
"globs": "**/*.py",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/python_lib.mdc",
"github_copilot": ".github/instructions/python_lib.instructions.md",
"agents_md": "lib/streamlit/AGENTS.md",
"globs": "lib/streamlit/**/*.py",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/python_tests.mdc",
"github_copilot": ".github/instructions/python_tests.instructions.md",
"agents_md": "lib/tests/AGENTS.md",
"globs": "lib/tests/**/*.py",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/protobuf.mdc",
"github_copilot": ".github/instructions/protobuf.instructions.md",
"agents_md": "proto/streamlit/proto/AGENTS.md",
"globs": "**/*.proto",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/typescript.mdc",
"github_copilot": ".github/instructions/typescript.instructions.md",
"agents_md": "frontend/AGENTS.md",
"globs": "**/*.ts, **/*.tsx",
"always_apply": False,
},
{
"cursor_mdc": ".cursor/rules/overview.mdc",
# Use repository-wide instructions file:
"github_copilot": ".github/copilot-instructions.md",
"agents_md": "AGENTS.md",
"globs": "**",
"always_apply": True,
},
]
def generate_make_commands_rule() -> None:
"""Generate the make commands cursor rule file."""
# Determine workspace root and run `make help` without directory trace noise
workspace_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
result = subprocess.run(
["make", "--no-print-directory", "help"],
capture_output=True,
text=True,
check=True,
cwd=workspace_root,
)
make_commands = result.stdout.strip()
# Format the template with the make commands
formatted_content = MAKE_COMMANDS_CURSOR_RULE_TEMPLATE.format(
make_commands=make_commands
)
# Define the output path
output_dir = os.path.join(workspace_root, ".cursor", "rules")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "make_commands.mdc")
# Write the formatted content to the file
with open(output_path, "w") as f:
f.write(formatted_content)
print(f"Generated rule file: {output_path}")
def resolve_rule_path(rule_path: str) -> str:
workspace_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
output_path = os.path.join(workspace_root, rule_path)
output_dir = os.path.dirname(output_path)
os.makedirs(output_dir, exist_ok=True)
return output_path
def generate_agent_rules() -> None:
"""Generate Cursor and Github Copilot agent rule files based on AGENT_RULE_FILES."""
for rule in AGENT_RULE_FILES:
cursor_mdc_path = resolve_rule_path(rule["cursor_mdc"])
github_copilot_path = resolve_rule_path(rule["github_copilot"])
agents_md_path = resolve_rule_path(rule["agents_md"])
globs = rule["globs"]
always_apply = rule["always_apply"]
if not os.path.isfile(agents_md_path):
raise FileNotFoundError(f"Missing AGENTS.md file at '{agents_md_path}'.")
# Read the full content of the AGENTS.md file
with open(agents_md_path) as f:
agents_md_content = f.read()
# Write cursor rule file:
if always_apply:
content = CURSOR_RULE_TEMPLATE_GLOBAL.format(
agents_md_content=agents_md_content.strip(),
)
else:
content = CURSOR_RULE_TEMPLATE_GLOBS.format(
globs=globs, agents_md_content=agents_md_content.strip()
)
with open(cursor_mdc_path, "w") as f:
f.write(content)
print(f"Generated Cursor rule file: {cursor_mdc_path}")
# Write github copilot rule file:
if always_apply:
content = GITHUB_COPILOT_RULE_TEMPLATE_GLOBAL.format(
agents_md_content=agents_md_content.strip(),
)
else:
content = GITHUB_COPILOT_RULE_TEMPLATE_GLOBS.format(
globs=globs, agents_md_content=agents_md_content.strip()
)
with open(github_copilot_path, "w") as f:
f.write(content)
print(f"Generated GitHub Copilot rule file: {github_copilot_path}")
if __name__ == "__main__":
generate_make_commands_rule()
generate_agent_rules()
| AgentRuleFile |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 62774,
"end": 64254
} | class ____(torch.nn.Module):
def forward(self, primals_1: "f32[8, 8]", primals_2: "f32[8, 8]"):
partitioned_fw_subgraph_0_0 = self.partitioned_fw_subgraph_0_0
invoke_subgraph_2 = torch.ops.higher_order.invoke_subgraph(partitioned_fw_subgraph_0_0, 'partitioned_fw_subgraph_0_0', primals_1, primals_2); partitioned_fw_subgraph_0_0 = primals_1 = primals_2 = None
getitem_6: "f32[8, 8]" = invoke_subgraph_2[3]
getitem_5: "f32[8, 8]" = invoke_subgraph_2[2]
getitem_4: "f32[8, 8]" = invoke_subgraph_2[1]
getitem: "f32[8, 8]" = invoke_subgraph_2[0]; invoke_subgraph_2 = None
sin: "f32[8, 8]" = torch.ops.aten.sin.default(getitem)
cos: "f32[8, 8]" = torch.ops.aten.cos.default(getitem); getitem = None
return (sin, getitem_6, getitem_5, getitem_4, cos)
class partitioned_fw_subgraph_0_0(torch.nn.Module):
def forward(self, primals_0: "f32[8, 8]", primals_1: "f32[8, 8]"):
mm: "f32[8, 8]" = torch.ops.aten.mm.default(primals_0, primals_1)
sin: "f32[8, 8]" = torch.ops.aten.sin.default(mm)
t: "f32[8, 8]" = torch.ops.aten.t.default(primals_0); primals_0 = None
t_1: "f32[8, 8]" = torch.ops.aten.t.default(primals_1); primals_1 = None
return (sin, mm, t, t_1)
""",
)
self.assertExpectedInline(
normalize_gm(backend.bw_graphs[0].print_readable(print_output=False)),
"""\
| GraphModule |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 8866,
"end": 9050
} | class ____(ExternalSignal):
"""
Raised when a flow run receives a termination signal.
"""
def __init__(self, signal: int):
self.signal = signal
| TerminationSignal |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/PlotSpeedTest.py | {
"start": 1662,
"end": 5236
} | class ____(pg.PlotCurveItem):
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self.monkey_mode = ''
def setMethod(self, value):
self.monkey_mode = value
def paint(self, painter, opt, widget):
if self.monkey_mode not in ['drawPolyline']:
return super().paint(painter, opt, widget)
painter.setRenderHint(painter.RenderHint.Antialiasing, self.opts['antialias'])
painter.setPen(pg.mkPen(self.opts['pen']))
if self.monkey_mode == 'drawPolyline':
painter.drawPolyline(fn.arrayToQPolygonF(self.xData, self.yData))
app = pg.mkQApp("Plot Speed Test")
default_pen = pg.mkPen()
params = ptree.Parameter.create(name='Parameters', type='group')
pt = ptree.ParameterTree(showHeader=False)
pt.setParameters(params)
pw = pg.PlotWidget()
splitter = QtWidgets.QSplitter()
splitter.addWidget(pt)
splitter.addWidget(pw)
splitter.show()
interactor = ptree.Interactor(
parent=params, nest=False, runOptions=ptree.RunOptions.ON_CHANGED
)
pw.setWindowTitle('pyqtgraph example: PlotSpeedTest')
pw.setLabel('bottom', 'Index', units='B')
curve = MonkeyCurveItem(pen=default_pen, brush='b')
pw.addItem(curve)
iterations_counter = itertools.count()
@interactor.decorate(
nest=True,
nsamples={'limits': [0, None]},
frames={'limits': [1, None]},
fsample={'units': 'Hz'},
frequency={'units': 'Hz'}
)
def makeData(
noise=args.noise,
nsamples=args.nsamples,
frames=args.frames,
fsample=args.fsample,
frequency=args.frequency,
amplitude=args.amplitude,
):
global data, connect_array, ptr
ttt = np.arange(frames * nsamples, dtype=np.float64) / fsample
data = amplitude*np.sin(2*np.pi*frequency*ttt).reshape((frames, nsamples))
if noise:
data += np.random.normal(size=data.shape)
connect_array = np.ones(data.shape[-1], dtype=bool)
ptr = 0
pw.setRange(QtCore.QRectF(0, -10, nsamples, 20))
params.child('makeData').setOpts(title='Plot Options')
@interactor.decorate(
connect={'type': 'list', 'limits': ['all', 'pairs', 'finite', 'array']}
)
def update(
antialias=pg.getConfigOption('antialias'),
connect='all',
skipFiniteCheck=False
):
global ptr
if next(iterations_counter) > args.iterations:
# cleanly close down benchmark
timer.stop()
app.quit()
return None
if connect == 'array':
connect = connect_array
curve.setData(
data[ptr],
antialias=antialias,
connect=connect,
skipFiniteCheck=skipFiniteCheck
)
ptr = (ptr + 1) % data.shape[0]
framecnt.update()
@interactor.decorate(
useOpenGL={'readonly': not args.allow_opengl_toggle},
plotMethod={'limits': ['pyqtgraph', 'drawPolyline'], 'type': 'list'},
curvePen={'type': 'pen'}
)
def updateOptions(
curvePen=pg.mkPen(),
plotMethod='pyqtgraph',
fillLevel=False,
enableExperimental=False,
useOpenGL=use_opengl,
):
pg.setConfigOption('enableExperimental', enableExperimental)
pw.useOpenGL(useOpenGL)
curve.setPen(curvePen)
curve.setFillLevel(0.0 if fillLevel else None)
curve.setMethod(plotMethod)
makeData()
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
framecnt = FrameCounter()
framecnt.sigFpsUpdate.connect(lambda fps: pw.setTitle(f'{fps:.1f} fps'))
if __name__ == '__main__':
# Splitter by default gives too small of a width to the parameter tree,
# so fix that right before the event loop
pt.setMinimumSize(225,0)
pg.exec()
| MonkeyCurveItem |
python | kamyu104__LeetCode-Solutions | Python/dot-product-of-two-sparse-vectors.py | {
"start": 70,
"end": 517
} | class ____:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.lookup = {i:v for i, v in enumerate(nums) if v}
def dotProduct(self, vec):
"""
:type vec: 'SparseVector'
:rtype: int
"""
if len(self.lookup) > len(vec.lookup):
self, vec = vec, self
return sum(v*vec.lookup[i] for i, v in self.lookup.iteritems() if i in vec.lookup)
| SparseVector |
python | numpy__numpy | numpy/lib/tests/test_io.py | {
"start": 5527,
"end": 5851
} | class ____(RoundtripTest):
def roundtrip(self, *args, **kwargs):
arr, arr_reloaded = RoundtripTest.roundtrip(self, np.save, *args, **kwargs)
assert_equal(arr[0], arr_reloaded)
assert_equal(arr[0].dtype, arr_reloaded.dtype)
assert_equal(arr[0].flags.fnc, arr_reloaded.flags.fnc)
| TestSaveLoad |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 1642,
"end": 2118
} | class ____[**P1, **P2 = P1, **P3 = P2]: ...
pa1 = ClassPA()
reveal_type(pa1, expected_text="ClassPA[..., ..., ...]")
pa2 = ClassPA[[str]]()
reveal_type(pa2, expected_text="ClassPA[(str), (str), (str)]")
pa3 = ClassPA[..., [float]]()
reveal_type(pa3, expected_text="ClassPA[..., (float), (float)]")
pa4 = ClassPA[..., [int, int], [float]]()
reveal_type(pa4, expected_text="ClassPA[..., (int, int), (float)]")
# This should generate an error because P1 depends on P2.
| ClassPA |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 413586,
"end": 416309
} | class ____:
"""
Test arr.device attribute and arr.to_device() method.
"""
@pytest.mark.parametrize("func, arg", [
(np.arange, 5),
(np.empty_like, []),
(np.zeros, 5),
(np.empty, (5, 5)),
(np.asarray, []),
(np.asanyarray, []),
])
def test_device(self, func, arg):
arr = func(arg)
assert arr.device == "cpu"
arr = func(arg, device=None)
assert arr.device == "cpu"
arr = func(arg, device="cpu")
assert arr.device == "cpu"
with assert_raises_regex(
ValueError,
r"Device not understood. Only \"cpu\" is allowed, "
r"but received: nonsense"
):
func(arg, device="nonsense")
with assert_raises_regex(
AttributeError,
r"attribute 'device' of '(numpy.|)ndarray' objects is "
r"not writable"
):
arr.device = "other"
def test_to_device(self):
arr = np.arange(5)
assert arr.to_device("cpu") is arr
with assert_raises_regex(
ValueError,
r"The stream argument in to_device\(\) is not supported"
):
arr.to_device("cpu", stream=1)
def test_array_interface_excess_dimensions_raises():
"""Regression test for gh-27949: ensure too many dims raises ValueError instead of segfault."""
# Dummy object to hold a custom __array_interface__
class DummyArray:
def __init__(self, interface):
# Attach the array interface dict to mimic an array
self.__array_interface__ = interface
# Create a base array (scalar) and copy its interface
base = np.array(42) # base can be any scalar or array
interface = dict(base.__array_interface__)
# Modify the shape to exceed NumPy's dimension limit (NPY_MAXDIMS, typically 64)
interface['shape'] = tuple([1] * 136) # match the original bug report
dummy = DummyArray(interface)
# Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
with pytest.raises(ValueError, match="dimensions must be within"):
np.asanyarray(dummy)
@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.uint32, np.complex128])
def test_array_dunder_array_preserves_dtype_on_none(dtype):
"""
Regression test for: https://github.com/numpy/numpy/issues/27407
Ensure that __array__(None) returns an array of the same dtype.
"""
a = np.array([1], dtype=dtype)
b = a.__array__(None)
assert_array_equal(a, b, strict=True)
@pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
@pytest.mark.skipif(IS_PYPY, reason="PyPy does not modify tp_doc")
| TestDevice |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_instigation.py | {
"start": 1527,
"end": 6485
} | class ____(NonLaunchableGraphQLContextTestMatrix):
def test_schedule_next_tick(self, graphql_context) -> None:
repository_selector = infer_repository_selector(graphql_context)
remote_repository = graphql_context.get_code_location(
repository_selector["repositoryLocationName"]
).get_repository(repository_selector["repositoryName"])
schedule_name = "no_config_job_hourly_schedule"
schedule = remote_repository.get_schedule(schedule_name)
selector = infer_instigation_selector(graphql_context, schedule_name)
# need to be running in order to generate a future tick
graphql_context.instance.start_schedule(schedule)
result = execute_dagster_graphql(
graphql_context,
INSTIGATION_QUERY,
variables={
"id": schedule.get_compound_id().to_string(),
"instigationSelector": selector,
},
)
assert result.data
assert result.data["instigationStateOrError"]["__typename"] == "InstigationState"
next_tick = result.data["instigationStateOrError"]["nextTick"]
assert next_tick
# ensure legacy selector based impl works until removal
selector = infer_instigation_selector(graphql_context, schedule_name)
result = execute_dagster_graphql(
graphql_context, INSTIGATION_QUERY, variables={"instigationSelector": selector}
)
assert result.data
assert result.data["instigationStateOrError"]["__typename"] == "InstigationState"
next_tick = result.data["instigationStateOrError"]["nextTick"]
assert next_tick
def test_sensor_next_tick(self, graphql_context):
repository_selector = infer_repository_selector(graphql_context)
remote_repository = graphql_context.get_code_location(
repository_selector["repositoryLocationName"]
).get_repository(repository_selector["repositoryName"])
sensor_name = "always_no_config_sensor_with_tags_and_metadata"
sensor = remote_repository.get_sensor(sensor_name)
selector = infer_instigation_selector(graphql_context, sensor_name)
result = execute_dagster_graphql(
graphql_context,
INSTIGATION_QUERY,
variables={
"id": sensor.get_compound_id().to_string(),
"instigationSelector": selector,
},
)
assert result.data
assert result.data["instigationStateOrError"]["__typename"] == "InstigationState", (
result.data["instigationStateOrError"]
)
# need to be running and create a sensor tick in the last 30 seconds in order to generate a
# future tick
graphql_context.instance.start_sensor(sensor)
_create_sensor_tick(graphql_context)
result = execute_dagster_graphql(
graphql_context,
INSTIGATION_QUERY,
variables={
"id": sensor.get_compound_id().to_string(),
"instigationSelector": selector,
},
)
assert result.data
assert result.data["instigationStateOrError"]["__typename"] == "InstigationState", (
result.data["instigationStateOrError"]
)
next_tick = result.data["instigationStateOrError"]["nextTick"]
assert next_tick
# ensure legacy selector based lookup continues to work until removed
result = execute_dagster_graphql(
graphql_context, INSTIGATION_QUERY, variables={"instigationSelector": selector}
)
assert result.data
assert result.data["instigationStateOrError"]["__typename"] == "InstigationState", (
result.data["instigationStateOrError"]
)
next_tick = result.data["instigationStateOrError"]["nextTick"]
assert next_tick
def test_instigation_states(self, graphql_context) -> None:
repository_selector = infer_repository_selector(graphql_context)
remote_repository = graphql_context.get_code_location(
repository_selector["repositoryLocationName"]
).get_repository(repository_selector["repositoryName"])
schedule_name = "no_config_job_hourly_schedule"
schedule = remote_repository.get_schedule(schedule_name)
graphql_context.instance.start_schedule(schedule)
result = execute_dagster_graphql(
graphql_context,
INSTIGATION_STATES_QUERY,
variables={"id": remote_repository.get_compound_id().to_string()},
)
assert result.data
assert result.data["instigationStatesOrError"]["__typename"] == "InstigationStates", (
result.data["instigationStatesOrError"]
)
results = result.data["instigationStatesOrError"]["results"]
assert results == [{"name": schedule_name, "instigationType": "SCHEDULE"}]
| TestNextTickRepository |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/comments.py | {
"start": 8870,
"end": 15906
} | class ____:
@property
def ca(self):
# type: () -> Any
if not hasattr(self, Comment.attrib):
setattr(self, Comment.attrib, Comment())
return getattr(self, Comment.attrib)
def yaml_end_comment_extend(self, comment, clear=False):
# type: (Any, bool) -> None
if comment is None:
return
if clear or self.ca.end is None:
self.ca.end = []
self.ca.end.extend(comment)
def yaml_key_comment_extend(self, key, comment, clear=False):
# type: (Any, Any, bool) -> None
r = self.ca._items.setdefault(key, [None, None, None, None])
if clear or r[1] is None:
if comment[1] is not None:
assert isinstance(comment[1], list)
r[1] = comment[1]
else:
r[1].extend(comment[0])
r[0] = comment[0]
def yaml_value_comment_extend(self, key, comment, clear=False):
# type: (Any, Any, bool) -> None
r = self.ca._items.setdefault(key, [None, None, None, None])
if clear or r[3] is None:
if comment[1] is not None:
assert isinstance(comment[1], list)
r[3] = comment[1]
else:
r[3].extend(comment[0])
r[2] = comment[0]
def yaml_set_start_comment(self, comment, indent=0):
# type: (Any, Any) -> None
"""overwrites any preceding comment lines on an object
expects comment to be without `#` and possible have multiple lines
"""
from .error import CommentMark
from .tokens import CommentToken
pre_comments = self._yaml_clear_pre_comment() # type: ignore
if comment[-1] == '\n':
comment = comment[:-1] # strip final newline if there
start_mark = CommentMark(indent)
for com in comment.split('\n'):
c = com.strip()
if len(c) > 0 and c[0] != '#':
com = '# ' + com
pre_comments.append(CommentToken(com + '\n', start_mark))
def yaml_set_comment_before_after_key(
self, key, before=None, indent=0, after=None, after_indent=None
):
# type: (Any, Any, Any, Any, Any) -> None
"""
expects comment (before/after) to be without `#` and possible have multiple lines
"""
from spack.vendor.ruamel.yaml.error import CommentMark
from spack.vendor.ruamel.yaml.tokens import CommentToken
def comment_token(s, mark):
# type: (Any, Any) -> Any
# handle empty lines as having no comment
return CommentToken(('# ' if s else "") + s + '\n', mark)
if after_indent is None:
after_indent = indent + 2
if before and (len(before) > 1) and before[-1] == '\n':
before = before[:-1] # strip final newline if there
if after and after[-1] == '\n':
after = after[:-1] # strip final newline if there
start_mark = CommentMark(indent)
c = self.ca.items.setdefault(key, [None, [], None, None])
if before is not None:
if c[1] is None:
c[1] = []
if before == '\n':
c[1].append(comment_token("", start_mark)) # type: ignore
else:
for com in before.split('\n'):
c[1].append(comment_token(com, start_mark)) # type: ignore
if after:
start_mark = CommentMark(after_indent)
if c[3] is None:
c[3] = []
for com in after.split('\n'):
c[3].append(comment_token(com, start_mark)) # type: ignore
@property
def fa(self):
# type: () -> Any
"""format attribute
set_flow_style()/set_block_style()"""
if not hasattr(self, Format.attrib):
setattr(self, Format.attrib, Format())
return getattr(self, Format.attrib)
def yaml_add_eol_comment(self, comment, key=NoComment, column=None):
# type: (Any, Optional[Any], Optional[Any]) -> None
"""
there is a problem as eol comments should start with ' #'
(but at the beginning of the line the space doesn't have to be before
the #. The column index is for the # mark
"""
from .tokens import CommentToken
from .error import CommentMark
if column is None:
try:
column = self._yaml_get_column(key)
except AttributeError:
column = 0
if comment[0] != '#':
comment = '# ' + comment
if column is None:
if comment[0] == '#':
comment = ' ' + comment
column = 0
start_mark = CommentMark(column)
ct = [CommentToken(comment, start_mark), None]
self._yaml_add_eol_comment(ct, key=key)
@property
def lc(self):
# type: () -> Any
if not hasattr(self, LineCol.attrib):
setattr(self, LineCol.attrib, LineCol())
return getattr(self, LineCol.attrib)
def _yaml_set_line_col(self, line, col):
# type: (Any, Any) -> None
self.lc.line = line
self.lc.col = col
def _yaml_set_kv_line_col(self, key, data):
# type: (Any, Any) -> None
self.lc.add_kv_line_col(key, data)
def _yaml_set_idx_line_col(self, key, data):
# type: (Any, Any) -> None
self.lc.add_idx_line_col(key, data)
@property
def anchor(self):
# type: () -> Any
if not hasattr(self, Anchor.attrib):
setattr(self, Anchor.attrib, Anchor())
return getattr(self, Anchor.attrib)
def yaml_anchor(self):
# type: () -> Any
if not hasattr(self, Anchor.attrib):
return None
return self.anchor
def yaml_set_anchor(self, value, always_dump=False):
# type: (Any, bool) -> None
self.anchor.value = value
self.anchor.always_dump = always_dump
@property
def tag(self):
# type: () -> Any
if not hasattr(self, Tag.attrib):
setattr(self, Tag.attrib, Tag())
return getattr(self, Tag.attrib)
def yaml_set_tag(self, value):
# type: (Any) -> None
self.tag.value = value
def copy_attributes(self, t, memo=None):
# type: (Any, Any) -> None
# fmt: off
for a in [Comment.attrib, Format.attrib, LineCol.attrib, Anchor.attrib,
Tag.attrib, merge_attrib]:
if hasattr(self, a):
if memo is not None:
setattr(t, a, copy.deepcopy(getattr(self, a), memo))
else:
setattr(t, a, getattr(self, a))
# fmt: on
def _yaml_add_eol_comment(self, comment, key):
# type: (Any, Any) -> None
raise NotImplementedError
def _yaml_get_pre_comment(self):
# type: () -> Any
raise NotImplementedError
def _yaml_get_column(self, key):
# type: (Any) -> Any
raise NotImplementedError
| CommentedBase |
python | kamyu104__LeetCode-Solutions | Python/apply-substitutions.py | {
"start": 1945,
"end": 2748
} | class ____(object):
def applySubstitutions(self, replacements, text):
"""
:type replacements: List[List[str]]
:type text: str
:rtype: str
"""
lookup = {k:v for k, v in replacements}
memo = {}
def replace(s):
if s not in memo:
result = []
i = 0
while i < len(s):
if s[i] != '%':
result.append(s[i])
i += 1
continue
j = next(j for j in xrange(i+1, len(s)) if s[j] == '%')
result.append(replace(lookup[s[i+1:j]]))
i = j+1
memo[s] = "".join(result)
return memo[s]
return replace(text)
| Solution2 |
python | realpython__materials | dwitter-part-4/source_code_final/dwitter/forms.py | {
"start": 54,
"end": 425
} | class ____(forms.ModelForm):
body = forms.CharField(
required=True,
widget=forms.widgets.Textarea(
attrs={
"placeholder": "Dweet something...",
"class": "textarea is-success is-medium",
}
),
label="",
)
class Meta:
model = Dweet
exclude = ("user",)
| DweetForm |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 28247,
"end": 28693
} | class ____(nn.Module):
def __init__(self, config, num_labels):
super().__init__()
hid_dim = config.hidden_size
self.logit_fc = nn.Sequential(
nn.Linear(hid_dim, hid_dim * 2),
GeLU(),
nn.LayerNorm(hid_dim * 2, eps=1e-12),
nn.Linear(hid_dim * 2, num_labels),
)
def forward(self, hidden_states):
return self.logit_fc(hidden_states)
| LxmertVisualAnswerHead |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Robot_arm/A3C.py | {
"start": 1228,
"end": 5340
} | class ____(object):
def __init__(self, scope, globalAC=None):
if scope == GLOBAL_NET_SCOPE: # get global network
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self._build_net()
self.a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')
self.c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')
else: # local net, calculate losses
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self.a_his = tf.placeholder(tf.float32, [None, N_A], 'A')
self.v_target = tf.placeholder(tf.float32, [None, 1], 'Vtarget')
mu, sigma, self.v = self._build_net()
td = tf.subtract(self.v_target, self.v, name='TD_error')
with tf.name_scope('c_loss'):
self.c_loss = tf.reduce_mean(tf.square(td))
with tf.name_scope('wrap_a_out'):
self.test = sigma[0]
mu, sigma = mu * A_BOUND[1], sigma + 1e-5
normal_dist = tf.contrib.distributions.Normal(mu, sigma)
with tf.name_scope('a_loss'):
log_prob = normal_dist.log_prob(self.a_his)
exp_v = log_prob * td
entropy = normal_dist.entropy() # encourage exploration
self.exp_v = ENTROPY_BETA * entropy + exp_v
self.a_loss = tf.reduce_mean(-self.exp_v)
with tf.name_scope('choose_a'): # use local params to choose action
self.A = tf.clip_by_value(tf.squeeze(normal_dist.sample(1), axis=0), *A_BOUND)
with tf.name_scope('local_grad'):
self.a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor')
self.c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic')
self.a_grads = tf.gradients(self.a_loss, self.a_params)
self.c_grads = tf.gradients(self.c_loss, self.c_params)
with tf.name_scope('sync'):
with tf.name_scope('pull'):
self.pull_a_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.a_params, globalAC.a_params)]
self.pull_c_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.c_params, globalAC.c_params)]
with tf.name_scope('push'):
self.update_a_op = OPT_A.apply_gradients(zip(self.a_grads, globalAC.a_params))
self.update_c_op = OPT_C.apply_gradients(zip(self.c_grads, globalAC.c_params))
def _build_net(self):
w_init = tf.contrib.layers.xavier_initializer()
with tf.variable_scope('actor'):
l_a = tf.layers.dense(self.s, 400, tf.nn.relu6, kernel_initializer=w_init, name='la')
l_a = tf.layers.dense(l_a, 300, tf.nn.relu6, kernel_initializer=w_init, name='la2')
mu = tf.layers.dense(l_a, N_A, tf.nn.tanh, kernel_initializer=w_init, name='mu')
sigma = tf.layers.dense(l_a, N_A, tf.nn.softplus, kernel_initializer=w_init, name='sigma')
with tf.variable_scope('critic'):
l_c = tf.layers.dense(self.s, 400, tf.nn.relu6, kernel_initializer=w_init, name='lc')
l_c = tf.layers.dense(l_c, 200, tf.nn.relu6, kernel_initializer=w_init, name='lc2')
v = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # state value
return mu, sigma, v
def update_global(self, feed_dict): # run by a local
_, _, t = SESS.run([self.update_a_op, self.update_c_op, self.test], feed_dict) # local grads applies to global net
return t
def pull_global(self): # run by a local
SESS.run([self.pull_a_params_op, self.pull_c_params_op])
def choose_action(self, s): # run by a local
s = s[np.newaxis, :]
return SESS.run(self.A, {self.s: s})[0]
| ACNet |
python | django__django | tests/queries/models.py | {
"start": 5467,
"end": 5648
} | class ____(models.Model):
name = models.CharField(max_length=10)
details = models.OneToOneField(Detail, models.CASCADE, primary_key=True)
objects = MemberManager()
| Member |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias18.py | {
"start": 614,
"end": 716
} | class ____(A_Alias_2[T2]): ...
# This should generate an error because the variance is incompatible.
| A_2 |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 27563,
"end": 28680
} | class ____(TestCase):
def test_basic(self):
iterable = (x for x in range(4))
actual = list(mi.substrings(iterable))
expected = [
(0,),
(1,),
(2,),
(3,),
(0, 1),
(1, 2),
(2, 3),
(0, 1, 2),
(1, 2, 3),
(0, 1, 2, 3),
]
self.assertEqual(actual, expected)
def test_strings(self):
iterable = 'abc'
actual = list(mi.substrings(iterable))
expected = [
('a',),
('b',),
('c',),
('a', 'b'),
('b', 'c'),
('a', 'b', 'c'),
]
self.assertEqual(actual, expected)
def test_empty(self):
iterable = iter([])
actual = list(mi.substrings(iterable))
expected = []
self.assertEqual(actual, expected)
def test_order(self):
iterable = [2, 0, 1]
actual = list(mi.substrings(iterable))
expected = [(2,), (0,), (1,), (2, 0), (0, 1), (2, 0, 1)]
self.assertEqual(actual, expected)
| SubstringsTests |
python | getsentry__sentry | src/sentry/api/endpoints/project_repo_path_parsing.py | {
"start": 3673,
"end": 3949
} | class ____(ProjectPermission):
"""
Similar to the code_mappings endpoint, loosen permissions to all users
"""
scope_map = {
"POST": ["org:read", "project:write", "project:admin"],
}
@region_silo_endpoint
| ProjectRepoPathParsingEndpointLoosePermission |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 2017,
"end": 6030
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
self.register_buffer(
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
past_key_values_length: int = 0,
) -> torch.Tensor:
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
batch_size, seq_length = input_shape
if position_ids is None:
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
# issue #5664
if token_type_ids is None:
if hasattr(self, "token_type_ids"):
# NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + token_type_embeddings
position_embeddings = self.position_embeddings(position_ids)
embeddings = embeddings + position_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: Optional[float] = None,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
if scaling is None:
scaling = query.size(-1) ** -0.5
# Take the dot product between "query" and "key" to get the raw attention scores.
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
if attention_mask is not None:
attention_mask = attention_mask[:, :, :, : key.shape[-2]]
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| BertEmbeddings |
python | ray-project__ray | rllib/connectors/agent/mean_std_filter.py | {
"start": 714,
"end": 5659
} | class ____(SyncedFilterAgentConnector):
"""A connector used to mean-std-filter observations.
Incoming observations are filtered such that the output of this filter is on
average zero and has a standard deviation of 1. This filtering is applied
separately per element of the observation space.
"""
def __init__(
self,
ctx: ConnectorContext,
demean: bool = True,
destd: bool = True,
clip: float = 10.0,
):
SyncedFilterAgentConnector.__init__(self, ctx)
# We simply use the old MeanStdFilter until non-connector env_runner is fully
# deprecated to avoid duplicate code
filter_shape = tree.map_structure(
lambda s: (
None
if isinstance(s, (Discrete, MultiDiscrete)) # noqa
else np.array(s.shape)
),
get_base_struct_from_space(ctx.observation_space),
)
self.filter = MeanStdFilter(filter_shape, demean=demean, destd=destd, clip=clip)
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
d = ac_data.data
assert (
type(d) is dict
), "Single agent data must be of type Dict[str, TensorStructType]"
if SampleBatch.OBS in d:
d[SampleBatch.OBS] = self.filter(
d[SampleBatch.OBS], update=self._is_training
)
if SampleBatch.NEXT_OBS in d:
d[SampleBatch.NEXT_OBS] = self.filter(
d[SampleBatch.NEXT_OBS], update=self._is_training
)
return ac_data
def to_state(self):
# Flattening is deterministic
flattened_rs = tree.flatten(self.filter.running_stats)
flattened_buffer = tree.flatten(self.filter.buffer)
return MeanStdObservationFilterAgentConnector.__name__, {
"shape": self.filter.shape,
"no_preprocessor": self.filter.no_preprocessor,
"demean": self.filter.demean,
"destd": self.filter.destd,
"clip": self.filter.clip,
"running_stats": [s.to_state() for s in flattened_rs],
"buffer": [s.to_state() for s in flattened_buffer],
}
# demean, destd, clip, and a state dict
@staticmethod
def from_state(
ctx: ConnectorContext,
params: List[Any] = None,
demean: bool = True,
destd: bool = True,
clip: float = 10.0,
):
connector = MeanStdObservationFilterAgentConnector(ctx, demean, destd, clip)
if params:
connector.filter.shape = params["shape"]
connector.filter.no_preprocessor = params["no_preprocessor"]
connector.filter.demean = params["demean"]
connector.filter.destd = params["destd"]
connector.filter.clip = params["clip"]
# Unflattening is deterministic
running_stats = [RunningStat.from_state(s) for s in params["running_stats"]]
connector.filter.running_stats = tree.unflatten_as(
connector.filter.shape, running_stats
)
# Unflattening is deterministic
buffer = [RunningStat.from_state(s) for s in params["buffer"]]
connector.filter.buffer = tree.unflatten_as(connector.filter.shape, buffer)
return connector
def reset_state(self) -> None:
"""Creates copy of current state and resets accumulated state"""
if not self._is_training:
raise ValueError(
"State of {} can only be changed when trainin.".format(self.__name__)
)
self.filter.reset_buffer()
def apply_changes(self, other: "Filter", *args, **kwargs) -> None:
"""Updates self with state from other filter."""
# inline this as soon as we deprecate ordinary filter with non-connector
# env_runner
if not self._is_training:
raise ValueError(
"Changes can only be applied to {} when trainin.".format(self.__name__)
)
return self.filter.apply_changes(other, *args, **kwargs)
def copy(self) -> "Filter":
"""Creates a new object with same state as self.
This is a legacy Filter method that we need to keep around for now
Returns:
A copy of self.
"""
# inline this as soon as we deprecate ordinary filter with non-connector
# env_runner
return self.filter.copy()
def sync(self, other: "AgentConnector") -> None:
"""Copies all state from other filter to self."""
# inline this as soon as we deprecate ordinary filter with non-connector
# env_runner
if not self._is_training:
raise ValueError(
"{} can only be synced when trainin.".format(self.__name__)
)
return self.filter.sync(other.filter)
@OldAPIStack
| MeanStdObservationFilterAgentConnector |
python | falconry__falcon | tests/test_httperror.py | {
"start": 36103,
"end": 36288
} | class ____(BaseHandler):
async def serialize_async(self, media, content_type=None):
assert media == {'title': '410 Gone'}
return b'this is async'
| AsyncOnlyMediaHandler |
python | keon__algorithms | tests/test_array.py | {
"start": 12419,
"end": 12707
} | class ____(unittest.TestCase):
def test_two_sum(self):
self.assertTupleEqual((0, 2), two_sum([2, 11, 7, 9], target=9))
self.assertTupleEqual((0, 3), two_sum([-3, 5, 2, 3, 8, -9], target=0))
self.assertIsNone(two_sum([-3, 5, 2, 3, 8, -9], target=6))
| TestTwoSum |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/source.py | {
"start": 2084,
"end": 14783
} | class ____(ConcurrentSourceAdapter):
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
START_DATE_OFFSET_IN_YEARS = 2
stop_sync_on_stream_failure = True
message_repository = InMemoryMessageRepository(Level(AirbyteLogFormatter.level_mapping[logger.level]))
def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: Optional[TState], **kwargs):
if config:
concurrency_level = min(config.get("num_workers", _DEFAULT_CONCURRENCY), _MAX_CONCURRENCY)
else:
concurrency_level = _DEFAULT_CONCURRENCY
logger.info(f"Using concurrent cdk with concurrency level {concurrency_level}")
concurrent_source = ConcurrentSource.create(
concurrency_level, concurrency_level // 2, logger, self._slice_logger, self.message_repository
)
super().__init__(concurrent_source)
self.catalog = catalog
self.state = state
self._job_tracker = JobTracker(limit=100)
@staticmethod
def _get_sf_object(config: Mapping[str, Any]) -> Salesforce:
sf = Salesforce(**config)
sf.login()
return sf
@staticmethod
def _validate_stream_slice_step(stream_slice_step: str):
if stream_slice_step:
try:
duration = pendulum.parse(stream_slice_step)
if not isinstance(duration, pendulum.Duration):
message = "Stream slice step Interval should be provided in ISO 8601 format."
elif duration < pendulum.Duration(seconds=1):
message = "Stream slice step Interval is too small. It should be no less than 1 second. Please set higher value and try again."
else:
return
raise ParserError(message)
except ParserError as e:
internal_message = "Incorrect stream slice step"
raise AirbyteTracedException(failure_type=FailureType.config_error, internal_message=internal_message, message=e.args[0])
def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Optional[str]]:
self._validate_stream_slice_step(config.get("stream_slice_step"))
salesforce = self._get_sf_object(config)
salesforce.describe()
return True, None
@classmethod
def _get_api_type(cls, stream_name: str, json_schema: Mapping[str, Any], force_use_bulk_api: bool) -> str:
"""Get proper API type: rest or bulk"""
# Salesforce BULK API currently does not support loading fields with data type base64 and compound data
properties = json_schema.get("properties", {})
properties_not_supported_by_bulk = {
key: value for key, value in properties.items() if value.get("format") == "base64" or "object" in value["type"]
}
rest_only = stream_name in UNSUPPORTED_BULK_API_SALESFORCE_OBJECTS
if rest_only:
logger.warning(f"BULK API is not supported for stream: {stream_name}")
return "rest"
if force_use_bulk_api and properties_not_supported_by_bulk:
logger.warning(
f"Following properties will be excluded from stream: {stream_name} due to BULK API limitations: {list(properties_not_supported_by_bulk)}"
)
return "bulk"
if properties_not_supported_by_bulk:
return "rest"
return "bulk"
@classmethod
def _get_stream_type(cls, stream_name: str, api_type: str):
"""Get proper stream class: full_refresh, incremental or substream
SubStreams (like ContentDocumentLink) do not support incremental sync because of query restrictions, look here:
https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_contentdocumentlink.htm
"""
parent_name = PARENT_SALESFORCE_OBJECTS.get(stream_name, {}).get("parent_name")
if api_type == "rest":
full_refresh = RestSalesforceSubStream if parent_name else RestSalesforceStream
incremental = IncrementalRestSalesforceStream
elif api_type == "bulk":
full_refresh = BulkSalesforceSubStream if parent_name else BulkSalesforceStream
incremental = BulkIncrementalSalesforceStream
else:
raise Exception(f"Stream {stream_name} cannot be processed by REST or BULK API.")
return full_refresh, incremental
def prepare_stream(self, stream_name: str, json_schema, sobject_options, sf_object, authenticator, config):
"""Choose proper stream class: syncMode(full_refresh/incremental), API type(Rest/Bulk), SubStream"""
pk, replication_key = sf_object.get_pk_and_replication_key(json_schema)
stream_kwargs = {
"stream_name": stream_name,
"schema": json_schema,
"pk": pk,
"sobject_options": sobject_options,
"sf_api": sf_object,
"authenticator": authenticator,
"start_date": config.get("start_date"),
"job_tracker": self._job_tracker,
"message_repository": self.message_repository,
}
api_type = self._get_api_type(stream_name, json_schema, config.get("force_use_bulk_api", False))
full_refresh, incremental = self._get_stream_type(stream_name, api_type)
if replication_key and stream_name not in UNSUPPORTED_FILTERING_STREAMS:
stream_class = incremental
stream_kwargs["replication_key"] = replication_key
stream_kwargs["stream_slice_step"] = config.get("stream_slice_step", "P30D")
else:
stream_class = full_refresh
return stream_class, stream_kwargs
def generate_streams(
self,
config: Mapping[str, Any],
stream_objects: Mapping[str, Any],
sf_object: Salesforce,
) -> List[Stream]:
"""Generates a list of stream by their names. It can be used for different tests too"""
authenticator = TokenAuthenticator(sf_object.access_token)
schemas = sf_object.generate_schemas(stream_objects)
default_args = [sf_object, authenticator, config]
streams = []
state_manager = ConnectorStateManager(state=self.state)
for stream_name, sobject_options in stream_objects.items():
json_schema = schemas.get(stream_name, {})
stream_class, kwargs = self.prepare_stream(stream_name, json_schema, sobject_options, *default_args)
parent_name = PARENT_SALESFORCE_OBJECTS.get(stream_name, {}).get("parent_name")
if parent_name:
# get minimal schema required for getting proper class name full_refresh/incremental, rest/bulk
parent_schema = PARENT_SALESFORCE_OBJECTS.get(stream_name, {}).get("schema_minimal")
parent_class, parent_kwargs = self.prepare_stream(parent_name, parent_schema, sobject_options, *default_args)
kwargs["parent"] = parent_class(**parent_kwargs)
stream = stream_class(**kwargs)
api_type = self._get_api_type(stream_name, json_schema, config.get("force_use_bulk_api", False))
if api_type == "rest" and not stream.primary_key and stream.too_many_properties:
logger.warning(
f"Can not instantiate stream {stream_name}. It is not supported by the BULK API and can not be "
"implemented via REST because the number of its properties exceeds the limit and it lacks a primary key."
)
continue
streams.append(self._wrap_for_concurrency(config, stream, state_manager))
streams.append(self._wrap_for_concurrency(config, Describe(sf_api=sf_object, catalog=self.catalog), state_manager))
return streams
def _wrap_for_concurrency(self, config, stream, state_manager):
stream_slicer_cursor = None
if stream.cursor_field:
stream_slicer_cursor = self._create_stream_slicer_cursor(config, state_manager, stream)
if hasattr(stream, "set_cursor"):
stream.set_cursor(stream_slicer_cursor)
if hasattr(stream, "parent") and hasattr(stream.parent, "set_cursor"):
stream_slicer_cursor = self._create_stream_slicer_cursor(config, state_manager, stream)
stream.parent.set_cursor(stream_slicer_cursor)
if not stream_slicer_cursor or self._get_sync_mode_from_catalog(stream) == SyncMode.full_refresh:
cursor = FinalStateCursor(
stream_name=stream.name, stream_namespace=stream.namespace, message_repository=self.message_repository
)
state = None
else:
cursor = stream_slicer_cursor
state = cursor.state
return StreamFacade.create_from_stream(stream, self, logger, state, cursor)
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
if not config.get("start_date"):
config["start_date"] = (datetime.now() - relativedelta(years=self.START_DATE_OFFSET_IN_YEARS)).strftime(self.DATETIME_FORMAT)
sf = self._get_sf_object(config)
stream_objects = sf.get_validated_streams(config=config, catalog=self.catalog)
streams = self.generate_streams(config, stream_objects, sf)
return streams
def _create_stream_slicer_cursor(
self, config: Mapping[str, Any], state_manager: ConnectorStateManager, stream: Stream
) -> ConcurrentCursor:
"""
We have moved the generation of stream slices to the concurrent CDK cursor
"""
cursor_field_key = stream.cursor_field or ""
if not isinstance(cursor_field_key, str):
raise AssertionError(f"Nested cursor field are not supported hence type str is expected but got {cursor_field_key}.")
cursor_field = CursorField(cursor_field_key)
stream_state = state_manager.get_stream_state(stream.name, stream.namespace)
return ConcurrentCursor(
stream.name,
stream.namespace,
stream_state,
self.message_repository,
state_manager,
stream.state_converter,
cursor_field,
self._get_slice_boundary_fields(stream, state_manager),
datetime.fromtimestamp(pendulum.parse(config["start_date"]).timestamp(), timezone.utc),
stream.state_converter.get_end_provider(),
timedelta(seconds=LOOKBACK_SECONDS),
isodate.parse_duration(config["stream_slice_step"]) if "stream_slice_step" in config else timedelta(days=30),
)
def _get_slice_boundary_fields(self, stream: Stream, state_manager: ConnectorStateManager) -> Optional[Tuple[str, str]]:
return ("start_date", "end_date")
def _get_sync_mode_from_catalog(self, stream: Stream) -> Optional[SyncMode]:
if self.catalog:
for catalog_stream in self.catalog.streams:
if stream.name == catalog_stream.stream.name:
return catalog_stream.sync_mode
return None
def read(
self,
logger: logging.Logger,
config: Mapping[str, Any],
catalog: ConfiguredAirbyteCatalog,
state: Union[List[AirbyteStateMessage], MutableMapping[str, Any]] = None,
) -> Iterator[AirbyteMessage]:
# save for use inside streams method
self.catalog = catalog
try:
yield from super().read(logger, config, catalog, state)
except AirbyteStopSync:
logger.info(f"Finished syncing {self.name}")
def _read_stream(
self,
logger: logging.Logger,
stream_instance: Stream,
configured_stream: ConfiguredAirbyteStream,
state_manager: ConnectorStateManager,
internal_config: InternalConfig,
) -> Iterator[AirbyteMessage]:
try:
yield from super()._read_stream(logger, stream_instance, configured_stream, state_manager, internal_config)
except exceptions.HTTPError as error:
try:
error_data = error.response.json()[0]
except JSONDecodeError as json_error:
raise error from json_error
error_code = error_data.get("errorCode")
url = error.response.url
if error.response.status_code == codes.FORBIDDEN and error_code == "REQUEST_LIMIT_EXCEEDED":
logger.warning(f"API Call {url} limit is exceeded. Error message: '{error_data.get('message')}'")
raise AirbyteStopSync() # if got 403 rate limit response, finish the sync with success.
raise error
| SourceSalesforce |
python | pypa__hatch | backend/src/hatchling/utils/context.py | {
"start": 356,
"end": 1568
} | class ____(ABC):
@abstractmethod
def get_formatters(self) -> MutableMapping:
"""
This returns a mapping of supported field names to their respective formatting functions. Each function
accepts 2 arguments:
- the `value` that was passed to the format call, defaulting to `None`
- the modifier `data`, defaulting to an empty string
"""
@classmethod
def format_path(cls, path: str, modifier: str) -> str:
if not modifier:
return os.path.normpath(path)
modifiers = modifier.split(":")[::-1]
while modifiers and modifiers[-1] == "parent":
path = os.path.dirname(path)
modifiers.pop()
if not modifiers:
return path
if len(modifiers) > 1:
message = f"Expected a single path modifier and instead got: {', '.join(reversed(modifiers))}"
raise ValueError(message)
modifier = modifiers[0]
if modifier == "uri":
return path_to_uri(path)
if modifier == "real":
return os.path.realpath(path)
message = f"Unknown path modifier: {modifier}"
raise ValueError(message)
| ContextFormatter |
python | pytorch__pytorch | torch/_inductor/analyze_preserves_zero_mask.py | {
"start": 2551,
"end": 2626
} | class ____:
dtype: torch.dtype
is_scalar: bool = False
| DTypeContainer |
python | walkccc__LeetCode | solutions/323. Number of Connected Components in an Undirected Graph/323-2.py | {
"start": 0,
"end": 493
} | class ____:
def countComponents(self, n: int, edges: list[list[int]]) -> int:
ans = 0
graph = [[] for _ in range(n)]
seen = set()
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def dfs(u: int, seen: set[int]) -> None:
for v in graph[u]:
if v not in seen:
seen.add(v)
dfs(v, seen)
for i in range(n):
if i not in seen:
seen.add(i)
dfs(graph, i, seen)
ans += 1
return ans
| Solution |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_single.py | {
"start": 68289,
"end": 71372
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global persons_table, employees_table
persons_table = Table(
"persons",
metadata,
Column(
"person_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
Column("type", String(20), nullable=False),
)
employees_table = Table(
"employees",
metadata,
Column(
"person_id",
Integer,
ForeignKey("persons.person_id"),
primary_key=True,
),
Column("employee_data", String(50)),
Column("manager_data", String(50)),
)
def test_single_on_joined(self):
class Person(ComparableEntity):
pass
class Employee(Person):
pass
class Manager(Employee):
pass
self.mapper_registry.map_imperatively(
Person,
persons_table,
polymorphic_on=persons_table.c.type,
polymorphic_identity="person",
)
self.mapper_registry.map_imperatively(
Employee,
employees_table,
inherits=Person,
polymorphic_identity="engineer",
)
self.mapper_registry.map_imperatively(
Manager, inherits=Employee, polymorphic_identity="manager"
)
sess = fixture_session()
sess.add(Person(name="p1"))
sess.add(Employee(name="e1", employee_data="ed1"))
sess.add(Manager(name="m1", employee_data="ed2", manager_data="md1"))
sess.flush()
sess.expunge_all()
eq_(
sess.query(Person).order_by(Person.person_id).all(),
[
Person(name="p1"),
Employee(name="e1", employee_data="ed1"),
Manager(name="m1", employee_data="ed2", manager_data="md1"),
],
)
sess.expunge_all()
eq_(
sess.query(Employee).order_by(Person.person_id).all(),
[
Employee(name="e1", employee_data="ed1"),
Manager(name="m1", employee_data="ed2", manager_data="md1"),
],
)
sess.expunge_all()
eq_(
sess.query(Manager).order_by(Person.person_id).all(),
[Manager(name="m1", employee_data="ed2", manager_data="md1")],
)
sess.expunge_all()
def go():
wp = with_polymorphic(Person, "*")
eq_(
sess.query(wp).order_by(wp.person_id).all(),
[
Person(name="p1"),
Employee(name="e1", employee_data="ed1"),
Manager(
name="m1", employee_data="ed2", manager_data="md1"
),
],
)
self.assert_sql_count(testing.db, go, 1)
| SingleOnJoinedTest |
python | pytest-dev__pytest | src/_pytest/_py/path.py | {
"start": 4736,
"end": 5661
} | class ____:
def __init__(self, pattern):
self.pattern = pattern
def __call__(self, path):
pattern = self.pattern
if (
pattern.find(path.sep) == -1
and iswin32
and pattern.find(posixpath.sep) != -1
):
# Running on Windows, the pattern has no Windows path separators,
# and the pattern has one or more Posix path separators. Replace
# the Posix path separators with the Windows path separator.
pattern = pattern.replace(posixpath.sep, path.sep)
if pattern.find(path.sep) == -1:
name = path.basename
else:
name = str(path) # path.strpath # XXX svn?
if not os.path.isabs(pattern):
pattern = "*" + path.sep + pattern
return fnmatch.fnmatch(name, pattern)
def map_as_list(func, iter):
return list(map(func, iter))
| FNMatcher |
python | viewflow__viewflow | tests/fsm/test_fsm__permissions.py | {
"start": 604,
"end": 1177
} | class ____(TestCase):
def setUp(self):
self.privileged_user = User.objects.create(
username='privileged',
is_staff=True
)
self.unprivileged_user = User.objects.create(
username='unprivileged',
is_staff=False
)
def test_callable_permission(self):
publication = _Publication()
self.assertTrue(
publication.remove.has_perm(self.privileged_user)
)
self.assertFalse(
publication.remove.has_perm(self.unprivileged_user)
)
| _Test |
python | getsentry__sentry | src/sentry/integrations/aws_lambda/integration.py | {
"start": 9648,
"end": 10748
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
# if we have the projectId, go to the next step
if "projectId" in request.GET:
pipeline.bind_state("project_id", request.GET["projectId"])
return pipeline.next_step()
assert pipeline.organization is not None
organization = pipeline.organization
projects = organization.projects
# if only one project, automatically use that
if len(projects) == 1:
pipeline.bind_state("skipped_project_select", True)
pipeline.bind_state("project_id", projects[0].id)
return pipeline.next_step()
projects = sorted(projects, key=lambda p: p.slug)
serialized_projects = project_service.serialize_many(
organization_id=organization.id,
filter=dict(project_ids=[p.id for p in projects]),
)
return render_react_view(
request, "awsLambdaProjectSelect", {"projects": serialized_projects}
)
| AwsLambdaProjectSelectPipelineView |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.