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
mahmoud__boltons
boltons/tableutils.py
{ "start": 6314, "end": 6740 }
class ____(InputType): def check_type(self, obj): return hasattr(obj, '_fields') and isinstance(obj, tuple) def guess_headers(self, obj): return list(obj._fields) def get_entry(self, obj, headers): return [getattr(obj, h, None) for h in headers] def get_entry_seq(self, obj_seq, headers): return [[getattr(obj, h, None) for h in headers] for obj in obj_seq]
NamedTupleInputType
python
milvus-io__pymilvus
pymilvus/orm/iterator.py
{ "start": 17074, "end": 31202 }
class ____: def __init__( self, connection: Connections, collection_name: str, data: Union[List, utils.SparseMatrixInputType], ann_field: str, param: Dict, batch_size: Optional[int] = 1000, limit: Optional[int] = UNLIMITED, expr: Optional[str] = None, partition_names: Optional[List[str]] = None, output_fields: Optional[List[str]] = None, timeout: Optional[float] = None, round_decimal: int = -1, schema: Optional[CollectionSchema] = None, **kwargs, ) -> SearchIterator: rows = entity_helper.get_input_num_rows(data) if rows > 1: raise ParamError( message="Not support search iteration over multiple vectors at present" ) if rows == 0: raise ParamError(message="vector_data for search cannot be empty") self._conn = connection self._iterator_params = { "collection_name": collection_name, "data": data, "ann_field": ann_field, BATCH_SIZE: batch_size, "output_fields": output_fields, "partition_names": partition_names, "timeout": timeout, "round_decimal": round_decimal, } self._collection_name = collection_name self._expr = expr self.__check_set_params(param) self.__check_for_special_index_param() self._kwargs = kwargs self._kwargs[ITERATOR_FIELD] = "True" self.__set_up_collection_id() self._kwargs[COLLECTION_ID] = self._collection_id self._filtered_ids = [] self._filtered_distance = None self._schema = schema self._limit = limit self._returned_count = 0 self.__check_metrics() self.__check_offset() self.__check_rm_range_search_parameters() self.__setup__pk_prop() self.__init_search_iterator() def __set_up_collection_id(self): res = self._conn.describe_collection(self._collection_name) self._collection_id = res[COLLECTION_ID] def __init_search_iterator(self): init_page = self.__execute_next_search(self._param, self._expr, False) self._session_ts = init_page.get_session_ts() if self._session_ts <= 0: log.warning("failed to set up mvccTs from milvus server, use client-side ts instead") self._session_ts = fall_back_to_latest_session_ts() self._kwargs[GUARANTEE_TIMESTAMP] = self._session_ts if len(init_page) == 0: message = ( "Cannot init search iterator because init page contains no matched rows, " "please check the radius and range_filter set up by searchParams" ) log.error(message) self._cache_id = NO_CACHE_ID self._init_success = False return self._cache_id = iterator_cache.cache(init_page, NO_CACHE_ID) self.__set_up_range_parameters(init_page) self.__update_filtered_ids(init_page) self._init_success = True def __update_width(self, page: SearchPage): first_hit, last_hit = page[0], page[-1] if metrics_positive_related(self._param[METRIC_TYPE]): self._width = last_hit.distance - first_hit.distance else: self._width = first_hit.distance - last_hit.distance if self._width == 0.0: self._width = 0.05 # enable a minimum value for width to avoid radius and range_filter equal error def __set_up_range_parameters(self, page: SearchPage): self.__update_width(page) self._tail_band = page[-1].distance log.debug( f"set up init parameter for searchIterator width:{self._width} tail_band:{self._tail_band}" ) def __check_reached_limit(self) -> bool: if self._limit == UNLIMITED or self._returned_count < self._limit: return False log.debug( f"reached search limit:{self._limit}, returned_count:{self._returned_count}, directly return" ) return True def __check_set_params(self, param: Dict): if param is None: self._param = {} else: self._param = deepcopy(param) if PARAMS not in self._param: self._param[PARAMS] = {} def __check_for_special_index_param(self): if ( EF in self._param[PARAMS] and self._param[PARAMS][EF] < self._iterator_params[BATCH_SIZE] ): raise MilvusException( message="When using hnsw index, provided ef must be larger than or equal to batch size" ) def __setup__pk_prop(self): fields = self._schema[FIELDS] for field in fields: if field.get(IS_PRIMARY): if field["type"] == DataType.VARCHAR: self._pk_str = True else: self._pk_str = False self._pk_field_name = field["name"] break if self._pk_field_name is None or self._pk_field_name == "": raise ParamError(message="schema must contain pk field, broke") def __check_metrics(self): if self._param[METRIC_TYPE] is None or self._param[METRIC_TYPE] == "": raise ParamError(message="must specify metrics type for search iterator") """we use search && range search to implement search iterator, so range search parameters are disabled to clients""" def __check_rm_range_search_parameters(self): if ( (PARAMS in self._param) and (RADIUS in self._param[PARAMS]) and (RANGE_FILTER in self._param[PARAMS]) ): radius = self._param[PARAMS][RADIUS] range_filter = self._param[PARAMS][RANGE_FILTER] if metrics_positive_related(self._param[METRIC_TYPE]) and radius <= range_filter: raise MilvusException( message=f"for metrics:{self._param[METRIC_TYPE]}, radius must be " f"larger than range_filter, please adjust your parameter" ) if not metrics_positive_related(self._param[METRIC_TYPE]) and radius >= range_filter: raise MilvusException( message=f"for metrics:{self._param[METRIC_TYPE]}, radius must be " f"smaller than range_filter, please adjust your parameter" ) def __check_offset(self): if self._kwargs.get(OFFSET, 0) != 0: raise ParamError(message="Not support offset when searching iteration") def __update_filtered_ids(self, res: SearchPage): if len(res) == 0: return last_hit = res[-1] if last_hit is None: return if last_hit.distance != self._filtered_distance: self._filtered_ids = [] # distance has changed, clear filter_ids array self._filtered_distance = last_hit.distance # renew the distance for filtering for hit in res: if hit.distance == last_hit.distance: self._filtered_ids.append(hit.id) if len(self._filtered_ids) > MAX_FILTERED_IDS_COUNT_ITERATION: raise MilvusException( message=f"filtered ids length has accumulated to more than " f"{MAX_FILTERED_IDS_COUNT_ITERATION!s}, " f"there is a danger of overly memory consumption" ) def __is_cache_enough(self, count: int) -> bool: cached_page = iterator_cache.fetch_cache(self._cache_id) return cached_page is not None and len(cached_page) >= count def __extract_page_from_cache(self, count: int) -> SearchPage: cached_page = iterator_cache.fetch_cache(self._cache_id) if cached_page is None or len(cached_page) < count: raise ParamError( message=f"Wrong, try to extract {count} result from cache, " f"more than {len(cached_page)} there must be sth wrong with code" ) ret_page_res = cached_page[0:count] ret_page = SearchPage(ret_page_res) left_cache_page = SearchPage(cached_page[count:]) iterator_cache.cache(left_cache_page, self._cache_id) return ret_page def __push_new_page_to_cache(self, page: SearchPage) -> int: if page is None: raise ParamError(message="Cannot push None page into cache") cached_page: SearchPage = iterator_cache.fetch_cache(self._cache_id) if cached_page is None: iterator_cache.cache(page, self._cache_id) cached_page = page else: cached_page.merge(page.get_res()) return len(cached_page) def next(self): # 0. check reached limit if not self._init_success or self.__check_reached_limit(): return SearchPage(None) ret_len = self._iterator_params[BATCH_SIZE] if self._limit is not UNLIMITED: left_len = self._limit - self._returned_count ret_len = min(left_len, ret_len) # 1. if cached page is sufficient, directly return if self.__is_cache_enough(ret_len): ret_page = self.__extract_page_from_cache(ret_len) self._returned_count += len(ret_page) return ret_page # 2. if cached page not enough, try to fill the result by probing with constant width # until finish filling or exceeding max trial time: 10 new_page = self.__try_search_fill() cached_page_len = self.__push_new_page_to_cache(new_page) ret_len = min(cached_page_len, ret_len) ret_page = self.__extract_page_from_cache(ret_len) if len(ret_page) == self._iterator_params[BATCH_SIZE]: self.__update_width(ret_page) # 3. update filter ids to avoid returning result repeatedly self._returned_count += ret_len return ret_page def __try_search_fill(self) -> SearchPage: final_page = SearchPage(None) try_time = 0 coefficient = 1 while True: next_params = self.__next_params(coefficient) next_expr = self.__filtered_duplicated_result_expr(self._expr) new_page = self.__execute_next_search(next_params, next_expr, True) self.__update_filtered_ids(new_page) try_time += 1 if len(new_page) > 0: final_page.merge(new_page.get_res()) self._tail_band = new_page[-1].distance if len(final_page) >= self._iterator_params[BATCH_SIZE]: break if try_time > MAX_TRY_TIME: log.warning(f"Search probe exceed max try times:{MAX_TRY_TIME} directly break") break # if there's a ring containing no vectors matched, then we need to extend # the ring continually to avoid empty ring problem coefficient += 1 return final_page def __execute_next_search( self, next_params: dict, next_expr: str, to_extend_batch: bool ) -> SearchPage: log.debug(f"search_iterator_next_expr:{next_expr}, next_params:{next_params}") res = self._conn.search( self._iterator_params["collection_name"], self._iterator_params["data"], self._iterator_params["ann_field"], next_params, extend_batch_size(self._iterator_params[BATCH_SIZE], next_params, to_extend_batch), next_expr, self._iterator_params["partition_names"], self._iterator_params["output_fields"], self._iterator_params["round_decimal"], timeout=self._iterator_params["timeout"], schema=self._schema, **self._kwargs, ) return SearchPage(res[0], res.get_session_ts()) # at present, the range_filter parameter means 'larger/less and equal', # so there would be vectors with same distances returned multiple times in different pages # we need to refine and remove these results before returning def __filtered_duplicated_result_expr(self, expr: str): if len(self._filtered_ids) == 0: return expr filtered_ids_str = "" for filtered_id in self._filtered_ids: if self._pk_str: filtered_ids_str += f'"{filtered_id}",' else: filtered_ids_str += f"{filtered_id}," filtered_ids_str = filtered_ids_str[0:-1] if len(filtered_ids_str) > 0: if expr is not None and len(expr) > 0: filter_expr = f" and {self._pk_field_name} not in [{filtered_ids_str}]" return "(" + expr + ")" + filter_expr return f"{self._pk_field_name} not in [{filtered_ids_str}]" return expr def __next_params(self, coefficient: int): coefficient = max(1, coefficient) next_params = deepcopy(self._param) if metrics_positive_related(self._param[METRIC_TYPE]): next_radius = self._tail_band + self._width * coefficient if RADIUS in self._param[PARAMS] and next_radius > self._param[PARAMS][RADIUS]: next_params[PARAMS][RADIUS] = self._param[PARAMS][RADIUS] else: next_params[PARAMS][RADIUS] = next_radius else: next_radius = self._tail_band - self._width * coefficient if RADIUS in self._param[PARAMS] and next_radius < self._param[PARAMS][RADIUS]: next_params[PARAMS][RADIUS] = self._param[PARAMS][RADIUS] else: next_params[PARAMS][RADIUS] = next_radius next_params[PARAMS][RANGE_FILTER] = self._tail_band log.debug( f"next round search iteration radius:{next_params[PARAMS][RADIUS]}," f"range_filter:{next_params[PARAMS][RANGE_FILTER]}," f"coefficient:{coefficient}" ) return next_params def close(self): iterator_cache.release_cache(self._cache_id)
SearchIterator
python
protocolbuffers__protobuf
python/google/protobuf/internal/field_mask.py
{ "start": 362, "end": 5322 }
class ____(object): """Class for FieldMask message type.""" __slots__ = () def ToJsonString(self): """Converts FieldMask to string according to ProtoJSON spec.""" camelcase_paths = [] for path in self.paths: camelcase_paths.append(_SnakeCaseToCamelCase(path)) return ','.join(camelcase_paths) def FromJsonString(self, value): """Converts string to FieldMask according to ProtoJSON spec.""" if not isinstance(value, str): raise ValueError('FieldMask JSON value not a string: {!r}'.format(value)) self.Clear() if value: for path in value.split(','): self.paths.append(_CamelCaseToSnakeCase(path)) def IsValidForDescriptor(self, message_descriptor): """Checks whether the FieldMask is valid for Message Descriptor.""" for path in self.paths: if not _IsValidPath(message_descriptor, path): return False return True def AllFieldsFromDescriptor(self, message_descriptor): """Gets all direct fields of Message Descriptor to FieldMask.""" self.Clear() for field in message_descriptor.fields: self.paths.append(field.name) def CanonicalFormFromMask(self, mask): """Converts a FieldMask to the canonical form. Removes paths that are covered by another path. For example, "foo.bar" is covered by "foo" and will be removed if "foo" is also in the FieldMask. Then sorts all paths in alphabetical order. Args: mask: The original FieldMask to be converted. """ tree = _FieldMaskTree(mask) tree.ToFieldMask(self) def Union(self, mask1, mask2): """Merges mask1 and mask2 into this FieldMask.""" _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) tree.MergeFromFieldMask(mask2) tree.ToFieldMask(self) def Intersect(self, mask1, mask2): """Intersects mask1 and mask2 into this FieldMask.""" _CheckFieldMaskMessage(mask1) _CheckFieldMaskMessage(mask2) tree = _FieldMaskTree(mask1) intersection = _FieldMaskTree() for path in mask2.paths: tree.IntersectPath(path, intersection) intersection.ToFieldMask(self) def MergeMessage( self, source, destination, replace_message_field=False, replace_repeated_field=False): """Merges fields specified in FieldMask from source to destination. Args: source: Source message. destination: The destination message to be merged into. replace_message_field: Replace message field if True. Merge message field if False. replace_repeated_field: Replace repeated field if True. Append elements of repeated field if False. """ tree = _FieldMaskTree(self) tree.MergeMessage( source, destination, replace_message_field, replace_repeated_field) def _IsValidPath(message_descriptor, path): """Checks whether the path is valid for Message Descriptor.""" parts = path.split('.') last = parts.pop() for name in parts: field = message_descriptor.fields_by_name.get(name) if (field is None or field.is_repeated or field.type != FieldDescriptor.TYPE_MESSAGE): return False message_descriptor = field.message_type return last in message_descriptor.fields_by_name def _CheckFieldMaskMessage(message): """Raises ValueError if message is not a FieldMask.""" message_descriptor = message.DESCRIPTOR if (message_descriptor.name != 'FieldMask' or message_descriptor.file.name != 'google/protobuf/field_mask.proto'): raise ValueError('Message {0} is not a FieldMask.'.format( message_descriptor.full_name)) def _SnakeCaseToCamelCase(path_name): """Converts a path name from snake_case to camelCase.""" result = [] after_underscore = False for c in path_name: if c.isupper(): raise ValueError( 'Fail to print FieldMask to Json string: Path name ' '{0} must not contain uppercase letters.'.format(path_name)) if after_underscore: if c.islower(): result.append(c.upper()) after_underscore = False else: raise ValueError( 'Fail to print FieldMask to Json string: The ' 'character after a "_" must be a lowercase letter ' 'in path name {0}.'.format(path_name)) elif c == '_': after_underscore = True else: result += c if after_underscore: raise ValueError('Fail to print FieldMask to Json string: Trailing "_" ' 'in path name {0}.'.format(path_name)) return ''.join(result) def _CamelCaseToSnakeCase(path_name): """Converts a field name from camelCase to snake_case.""" result = [] for c in path_name: if c == '_': raise ValueError('Fail to parse FieldMask: Path name ' '{0} must not contain "_"s.'.format(path_name)) if c.isupper(): result += '_' result += c.lower() else: result += c return ''.join(result)
FieldMask
python
numba__numba
numba/core/datamodel/packer.py
{ "start": 1915, "end": 4973 }
class ____(object): """ Compute the position for each high-level typed argument. It flattens every composite argument into primitive types. It maintains a position map for unflattening the arguments. Since struct (esp. nested struct) have specific ABI requirements (e.g. alignment, pointer address-space, ...) in different architecture (e.g. OpenCL, CUDA), flattening composite argument types simplifes the call setup from the Python side. Functions are receiving simple primitive types and there are only a handful of these. """ def __init__(self, dmm, fe_args): self._dmm = dmm self._fe_args = fe_args self._nargs = len(fe_args) self._dm_args = [] argtys = [] for ty in fe_args: dm = self._dmm.lookup(ty) self._dm_args.append(dm) argtys.append(dm.get_argument_type()) self._unflattener = _Unflattener(argtys) self._be_args = list(_flatten(argtys)) def as_arguments(self, builder, values): """Flatten all argument values """ if len(values) != self._nargs: raise TypeError("invalid number of args: expected %d, got %d" % (self._nargs, len(values))) if not values: return () args = [dm.as_argument(builder, val) for dm, val in zip(self._dm_args, values) ] args = tuple(_flatten(args)) return args def from_arguments(self, builder, args): """Unflatten all argument values """ valtree = self._unflattener.unflatten(args) values = [dm.from_argument(builder, val) for dm, val in zip(self._dm_args, valtree) ] return values def assign_names(self, args, names): """Assign names for each flattened argument values. """ valtree = self._unflattener.unflatten(args) for aval, aname in zip(valtree, names): self._assign_names(aval, aname) def _assign_names(self, val_or_nested, name, depth=()): if isinstance(val_or_nested, (tuple, list)): for pos, aval in enumerate(val_or_nested): self._assign_names(aval, name, depth=depth + (pos,)) else: postfix = '.'.join(map(str, depth)) parts = [name, postfix] val_or_nested.name = '.'.join(filter(bool, parts)) @property def argument_types(self): """Return a list of LLVM types that are results of flattening composite types. """ return tuple(ty for ty in self._be_args if ty != ()) def _flatten(iterable): """ Flatten nested iterable of (tuple, list). """ def rec(iterable): for i in iterable: if isinstance(i, (tuple, list)): for j in rec(i): yield j else: yield i return rec(iterable) _PUSH_LIST = 1 _APPEND_NEXT_VALUE = 2 _APPEND_EMPTY_TUPLE = 3 _POP = 4
ArgPacker
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 362534, "end": 363121 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("LabelEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.types.list_of("Label"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
LabelConnection
python
scikit-learn__scikit-learn
sklearn/externals/array_api_extra/_lib/_at.py
{ "start": 1243, "end": 15327 }
class ____: # pylint: disable=invalid-name # numpydoc ignore=PR02 """ Update operations for read-only arrays. This implements ``jax.numpy.ndarray.at`` for all writeable backends (those that support ``__setitem__``) and routes to the ``.at[]`` method for JAX arrays. Parameters ---------- x : array Input array. idx : index, optional Only `array API standard compliant indices <https://data-apis.org/array-api/latest/API_specification/indexing.html>`_ are supported. You may use two alternate syntaxes:: >>> import array_api_extra as xpx >>> xpx.at(x, idx).set(value) # or add(value), etc. >>> xpx.at(x)[idx].set(value) copy : bool, optional None (default) The array parameter *may* be modified in place if it is possible and beneficial for performance. You should not reuse it after calling this function. True Ensure that the inputs are not modified. False Ensure that the update operation writes back to the input. Raise ``ValueError`` if a copy cannot be avoided. xp : array_namespace, optional The standard-compatible namespace for `x`. Default: infer. Returns ------- Updated input array. Warnings -------- (a) When you omit the ``copy`` parameter, you should never reuse the parameter array later on; ideally, you should reassign it immediately:: >>> import array_api_extra as xpx >>> x = xpx.at(x, 0).set(2) The above best practice pattern ensures that the behaviour won't change depending on whether ``x`` is writeable or not, as the original ``x`` object is dereferenced as soon as ``xpx.at`` returns; this way there is no risk to accidentally update it twice. On the reverse, the anti-pattern below must be avoided, as it will result in different behaviour on read-only versus writeable arrays:: >>> x = xp.asarray([0, 0, 0]) >>> y = xpx.at(x, 0).set(2) >>> z = xpx.at(x, 1).set(3) In the above example, both calls to ``xpx.at`` update ``x`` in place *if possible*. This causes the behaviour to diverge depending on whether ``x`` is writeable or not: - If ``x`` is writeable, then after the snippet above you'll have ``x == y == z == [2, 3, 0]`` - If ``x`` is read-only, then you'll end up with ``x == [0, 0, 0]``, ``y == [2, 0, 0]`` and ``z == [0, 3, 0]``. The correct pattern to use if you want diverging outputs from the same input is to enforce copies:: >>> x = xp.asarray([0, 0, 0]) >>> y = xpx.at(x, 0).set(2, copy=True) # Never updates x >>> z = xpx.at(x, 1).set(3) # May or may not update x in place >>> del x # avoid accidental reuse of x as we don't know its state anymore (b) The array API standard does not support integer array indices. The behaviour of update methods when the index is an array of integers is undefined and will vary between backends; this is particularly true when the index contains multiple occurrences of the same index, e.g.:: >>> import numpy as np >>> import jax.numpy as jnp >>> import array_api_extra as xpx >>> xpx.at(np.asarray([123]), np.asarray([0, 0])).add(1) array([124]) >>> xpx.at(jnp.asarray([123]), jnp.asarray([0, 0])).add(1) Array([125], dtype=int32) See Also -------- jax.numpy.ndarray.at : Equivalent array method in JAX. Notes ----- `sparse <https://sparse.pydata.org/>`_, as well as read-only arrays from libraries not explicitly covered by ``array-api-compat``, are not supported by update methods. Boolean masks are supported on Dask and jitted JAX arrays exclusively when `idx` has the same shape as `x` and `y` is 0-dimensional. Note that this support is not available in JAX's native ``x.at[mask].set(y)``. This pattern:: >>> mask = m(x) >>> x[mask] = f(x[mask]) Can't be replaced by `at`, as it won't work on Dask and JAX inside jax.jit:: >>> mask = m(x) >>> x = xpx.at(x, mask).set(f(x[mask]) # Crash on Dask and jax.jit You should instead use:: >>> x = xp.where(m(x), f(x), x) Examples -------- Given either of these equivalent expressions:: >>> import array_api_extra as xpx >>> x = xpx.at(x)[1].add(2) >>> x = xpx.at(x, 1).add(2) If x is a JAX array, they are the same as:: >>> x = x.at[1].add(2) If x is a read-only NumPy array, they are the same as:: >>> x = x.copy() >>> x[1] += 2 For other known backends, they are the same as:: >>> x[1] += 2 """ _x: Array _idx: SetIndex | Undef __slots__: ClassVar[tuple[str, ...]] = ("_idx", "_x") def __init__( self, x: Array, idx: SetIndex | Undef = _undef, / ) -> None: # numpydoc ignore=GL08 self._x = x self._idx = idx def __getitem__(self, idx: SetIndex, /) -> Self: # numpydoc ignore=PR01,RT01 """ Allow for the alternate syntax ``at(x)[start:stop:step]``. It looks prettier than ``at(x, slice(start, stop, step))`` and feels more intuitive coming from the JAX documentation. """ if self._idx is not _undef: msg = "Index has already been set" raise ValueError(msg) return type(self)(self._x, idx) def _op( self, at_op: _AtOp, in_place_op: Callable[[Array, Array | complex], Array] | None, out_of_place_op: Callable[[Array, Array], Array] | None, y: Array | complex, /, copy: bool | None, xp: ModuleType | None, ) -> Array: """ Implement all update operations. Parameters ---------- at_op : _AtOp Method of JAX's Array.at[]. in_place_op : Callable[[Array, Array | complex], Array] | None In-place operation to apply on mutable backends:: x[idx] = in_place_op(x[idx], y) If None:: x[idx] = y out_of_place_op : Callable[[Array, Array], Array] | None Out-of-place operation to apply when idx is a boolean mask and the backend doesn't support in-place updates:: x = xp.where(idx, out_of_place_op(x, y), x) If None:: x = xp.where(idx, y, x) y : array or complex Right-hand side of the operation. copy : bool or None Whether to copy the input array. See the class docstring for details. xp : array_namespace, optional The array namespace for the input array. Default: infer. Returns ------- Array Updated `x`. """ from ._funcs import apply_where # pylint: disable=cyclic-import x, idx = self._x, self._idx xp = array_namespace(x, y) if xp is None else xp if isinstance(idx, Undef): msg = ( "Index has not been set.\n" "Usage: either\n" " at(x, idx).set(value)\n" "or\n" " at(x)[idx].set(value)\n" "(same for all other methods)." ) raise ValueError(msg) if copy not in (True, False, None): msg = f"copy must be True, False, or None; got {copy!r}" raise ValueError(msg) writeable = None if copy else is_writeable_array(x) # JAX inside jax.jit doesn't support in-place updates with boolean # masks; Dask exclusively supports __setitem__ but not iops. # We can handle the common special case of 0-dimensional y # with where(idx, y, x) instead. if ( (is_dask_array(idx) or is_jax_array(idx)) and idx.dtype == xp.bool and idx.shape == x.shape ): y_xp = xp.asarray(y, dtype=x.dtype, device=_compat.device(x)) if y_xp.ndim == 0: if out_of_place_op: # add(), subtract(), ... # suppress inf warnings on Dask out = apply_where( idx, (x, y_xp), out_of_place_op, fill_value=x, xp=xp ) # Undo int->float promotion on JAX after _AtOp.DIVIDE out = xp.astype(out, x.dtype, copy=False) else: # set() out = xp.where(idx, y_xp, x) if copy is False: x[()] = out return x return out # else: this will work on eager JAX and crash on jax.jit and Dask if copy or (copy is None and not writeable): if is_jax_array(x): # Use JAX's at[] func = cast( Callable[[Array | complex], Array], getattr(x.at[idx], at_op.value), # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue,reportUnknownArgumentType] ) out = func(y) # Undo int->float promotion on JAX after _AtOp.DIVIDE return xp.astype(out, x.dtype, copy=False) # Emulate at[] behaviour for non-JAX arrays # with a copy followed by an update x = xp.asarray(x, copy=True) # A copy of a read-only numpy array is writeable # Note: this assumes that a copy of a writeable array is writeable assert not writeable writeable = None if writeable is None: writeable = is_writeable_array(x) if not writeable: # sparse crashes here msg = f"Can't update read-only array {x}" raise ValueError(msg) # Work around bug in PyTorch where __setitem__ doesn't # always support mismatched dtypes # https://github.com/pytorch/pytorch/issues/150017 if is_torch_array(y): y = xp.astype(y, x.dtype, copy=False) # Backends without boolean indexing (other than JAX) crash here if in_place_op: # add(), subtract(), ... x[idx] = in_place_op(x[idx], y) else: # set() x[idx] = y return x def set( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] = y`` and return the update array.""" return self._op(_AtOp.SET, None, None, y, copy=copy, xp=xp) def add( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] += y`` and return the updated array.""" # Note for this and all other methods based on _iop: # operator.iadd and operator.add subtly differ in behaviour, as # only iadd will trigger exceptions when y has an incompatible dtype. return self._op(_AtOp.ADD, operator.iadd, operator.add, y, copy=copy, xp=xp) def subtract( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] -= y`` and return the updated array.""" return self._op( _AtOp.SUBTRACT, operator.isub, operator.sub, y, copy=copy, xp=xp ) def multiply( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] *= y`` and return the updated array.""" return self._op( _AtOp.MULTIPLY, operator.imul, operator.mul, y, copy=copy, xp=xp ) def divide( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] /= y`` and return the updated array.""" return self._op( _AtOp.DIVIDE, operator.itruediv, operator.truediv, y, copy=copy, xp=xp ) def power( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] **= y`` and return the updated array.""" return self._op(_AtOp.POWER, operator.ipow, operator.pow, y, copy=copy, xp=xp) def min( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] = minimum(x[idx], y)`` and return the updated array.""" # On Dask, this function runs on the chunks, so we need to determine the # namespace that Dask is wrapping. # Note that da.minimum _incidentally_ works on NumPy, CuPy, and sparse # thanks to all these meta-namespaces implementing the __array_ufunc__ # interface, but there's no guarantee that it will work for other # wrapped libraries in the future. xp = array_namespace(self._x) if xp is None else xp mxp = meta_namespace(self._x, xp=xp) y = xp.asarray(y) return self._op(_AtOp.MIN, mxp.minimum, mxp.minimum, y, copy=copy, xp=xp) def max( self, y: Array | complex, /, copy: bool | None = None, xp: ModuleType | None = None, ) -> Array: # numpydoc ignore=PR01,RT01 """Apply ``x[idx] = maximum(x[idx], y)`` and return the updated array.""" # See note on min() xp = array_namespace(self._x) if xp is None else xp mxp = meta_namespace(self._x, xp=xp) y = xp.asarray(y) return self._op(_AtOp.MAX, mxp.maximum, mxp.maximum, y, copy=copy, xp=xp)
at
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 43562, "end": 43611 }
class ____(str, Enum): GEO = "geo"
GeoIndexType
python
Textualize__textual
src/textual/_log.py
{ "start": 24, "end": 298 }
class ____(Enum): """A log group is a classification of the log message (*not* a level).""" UNDEFINED = 0 # Mainly for testing EVENT = 1 DEBUG = 2 INFO = 3 WARNING = 4 ERROR = 5 PRINT = 6 SYSTEM = 7 LOGGING = 8 WORKER = 9
LogGroup
python
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 13788, "end": 14432 }
class ____(SnubaError): """ Exception raised when a query cannot be executed due to rate limits. """ def __init__( self, message: str | None = None, policy: str | None = None, quota_unit: str | None = None, storage_key: str | None = None, quota_used: int | None = None, rejection_threshold: int | None = None, ) -> None: super().__init__(message) self.policy = policy self.quota_unit = quota_unit self.storage_key = storage_key self.quota_used = quota_used self.rejection_threshold = rejection_threshold
RateLimitExceeded
python
sympy__sympy
sympy/testing/runtests.py
{ "start": 3263, "end": 40429 }
class ____(Exception): pass def _indent(s, indent=4): """ Add the given number of space characters to the beginning of every non-blank line in ``s``, and return the result. If the string ``s`` is Unicode, it is encoded using the stdout encoding and the ``backslashreplace`` error handler. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) pdoctest._indent = _indent # type: ignore # override reporter to maintain windows and python3 def _report_failure(self, out, test, example, got): """ Report that the given example failed. """ s = self._checker.output_difference(example, got, self.optionflags) s = s.encode('raw_unicode_escape').decode('utf8', 'ignore') out(self._failure_header(test, example) + s) if IS_WINDOWS: DocTestRunner.report_failure = _report_failure # type: ignore def convert_to_native_paths(lst): """ Converts a list of '/' separated paths into a list of native (os.sep separated) paths and converts to lowercase if the system is case insensitive. """ newlst = [] for rv in lst: rv = os.path.join(*rv.split("/")) # on windows the slash after the colon is dropped if sys.platform == "win32": pos = rv.find(':') if pos != -1: if rv[pos + 1] != '\\': rv = rv[:pos + 1] + '\\' + rv[pos + 1:] newlst.append(os.path.normcase(rv)) return newlst def get_sympy_dir(): """ Returns the root SymPy directory and set the global value indicating whether the system is case sensitive or not. """ this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) return os.path.normcase(sympy_dir) def setup_pprint(disable_line_wrap=True): from sympy.interactive.printing import init_printing from sympy.printing.pretty.pretty import pprint_use_unicode import sympy.interactive.printing as interactive_printing from sympy.printing.pretty import stringpict # Prevent init_printing() in doctests from affecting other doctests interactive_printing.NO_GLOBAL = True # force pprint to be in ascii mode in doctests use_unicode_prev = pprint_use_unicode(False) # disable line wrapping for pprint() outputs wrap_line_prev = stringpict._GLOBAL_WRAP_LINE if disable_line_wrap: stringpict._GLOBAL_WRAP_LINE = False # hook our nice, hash-stable strprinter init_printing(pretty_print=False) return use_unicode_prev, wrap_line_prev @contextmanager def raise_on_deprecated(): """Context manager to make DeprecationWarning raise an error This is to catch SymPyDeprecationWarning from library code while running tests and doctests. It is important to use this context manager around each individual test/doctest in case some tests modify the warning filters. """ with warnings.catch_warnings(): warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*') yield def run_in_subprocess_with_hash_randomization( function, function_args=(), function_kwargs=None, command=sys.executable, module='sympy.testing.runtests', force=False): """ Run a function in a Python subprocess with hash randomization enabled. If hash randomization is not supported by the version of Python given, it returns False. Otherwise, it returns the exit value of the command. The function is passed to sys.exit(), so the return value of the function will be the return value. The environment variable PYTHONHASHSEED is used to seed Python's hash randomization. If it is set, this function will return False, because starting a new subprocess is unnecessary in that case. If it is not set, one is set at random, and the tests are run. Note that if this environment variable is set when Python starts, hash randomization is automatically enabled. To force a subprocess to be created even if PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a subprocess in Python versions that do not support hash randomization (see below), because those versions of Python do not support the ``-R`` flag. ``function`` should be a string name of a function that is importable from the module ``module``, like "_test". The default for ``module`` is "sympy.testing.runtests". ``function_args`` and ``function_kwargs`` should be a repr-able tuple and dict, respectively. The default Python command is sys.executable, which is the currently running Python command. This function is necessary because the seed for hash randomization must be set by the environment variable before Python starts. Hence, in order to use a predetermined seed for tests, we must start Python in a separate subprocess. Examples ======== >>> from sympy.testing.runtests import ( ... run_in_subprocess_with_hash_randomization) >>> # run the core tests in verbose mode >>> run_in_subprocess_with_hash_randomization("_test", ... function_args=("core",), ... function_kwargs={'verbose': True}) # doctest: +SKIP # Will return 0 if sys.executable supports hash randomization and tests # pass, 1 if they fail, and False if it does not support hash # randomization. """ cwd = get_sympy_dir() # Note, we must return False everywhere, not None, as subprocess.call will # sometimes return None. hash_seed = os.getenv("PYTHONHASHSEED") if not hash_seed: os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32)) else: if not force: return False function_kwargs = function_kwargs or {} # Now run the command commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" % (module, function, function, repr(function_args), repr(function_kwargs))) p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd) try: p.communicate() except KeyboardInterrupt: p.wait() finally: # Put the environment variable back, so that it reads correctly for # the current Python process. if hash_seed is None: del os.environ["PYTHONHASHSEED"] else: os.environ["PYTHONHASHSEED"] = hash_seed return p.returncode def run_all_tests(test_args=(), test_kwargs=None, doctest_args=(), doctest_kwargs=None, examples_args=(), examples_kwargs=None): """ Run all tests. Right now, this runs the regular tests (bin/test), the doctests (bin/doctest), and the examples (examples/all.py). This is what ``setup.py test`` uses. You can pass arguments and keyword arguments to the test functions that support them (for now, test, doctest, and the examples). See the docstrings of those functions for a description of the available options. For example, to run the solvers tests with colors turned off: >>> from sympy.testing.runtests import run_all_tests >>> run_all_tests(test_args=("solvers",), ... test_kwargs={"colors:False"}) # doctest: +SKIP """ tests_successful = True test_kwargs = test_kwargs or {} doctest_kwargs = doctest_kwargs or {} examples_kwargs = examples_kwargs or {'quiet': True} try: # Regular tests if not test(*test_args, **test_kwargs): # some regular test fails, so set the tests_successful # flag to false and continue running the doctests tests_successful = False # Doctests print() if not doctest(*doctest_args, **doctest_kwargs): tests_successful = False # Examples print() sys.path.append("examples") # examples/all.py from all import run_examples # type: ignore if not run_examples(*examples_args, **examples_kwargs): tests_successful = False if tests_successful: return else: # Return nonzero exit code sys.exit(1) except KeyboardInterrupt: print() print("DO *NOT* COMMIT!") sys.exit(1) def test(*paths, subprocess=True, rerun=0, **kwargs): """ Run tests in the specified test_*.py files. Tests in a particular test_*.py file are run if any of the given strings in ``paths`` matches a part of the test file's path. If ``paths=[]``, tests in all test_*.py files are run. Notes: - If sort=False, tests are run in random order (not default). - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. **Explanation of test results** ====== =============================================================== Output Meaning ====== =============================================================== . passed F failed X XPassed (expected to fail but passed) f XFAILed (expected to fail and indeed failed) s skipped w slow T timeout (e.g., when ``--timeout`` is used) K KeyboardInterrupt (when running the slow tests with ``--slow``, you can interrupt one of them without killing the test runner) ====== =============================================================== Colors have no additional meaning and are used just to facilitate interpreting the output. Examples ======== >>> import sympy Run all tests: >>> sympy.test() # doctest: +SKIP Run one file: >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP >>> sympy.test("_basic") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.test("sympy/core/tests/test_basic.py", ... "sympy/functions") # doctest: +SKIP Run all tests in sympy/core and sympy/utilities: >>> sympy.test("/core", "/util") # doctest: +SKIP Run specific test from a file: >>> sympy.test("sympy/core/tests/test_basic.py", ... kw="test_equality") # doctest: +SKIP Run specific test from any file: >>> sympy.test(kw="subs") # doctest: +SKIP Run the tests with verbose mode on: >>> sympy.test(verbose=True) # doctest: +SKIP Do not sort the test output: >>> sympy.test(sort=False) # doctest: +SKIP Turn on post-mortem pdb: >>> sympy.test(pdb=True) # doctest: +SKIP Turn off colors: >>> sympy.test(colors=False) # doctest: +SKIP Force colors, even when the output is not to a terminal (this is useful, e.g., if you are piping to ``less -r`` and you still want colors) >>> sympy.test(force_colors=False) # doctest: +SKIP The traceback verboseness can be set to "short" or "no" (default is "short") >>> sympy.test(tb='no') # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. For instance, to run the first half of the test suite: >>> sympy.test(split='1/2') # doctest: +SKIP The ``time_balance`` option can be passed in conjunction with ``split``. If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt to split the tests such that each split takes equal time. This heuristic for balancing is based on pre-recorded test data. >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP You can disable running the tests in a separate subprocess using ``subprocess=False``. This is done to support seeding hash randomization, which is enabled by default in the Python versions where it is supported. If subprocess=False, hash randomization is enabled/disabled according to whether it has been enabled or not in the calling Python process. However, even if it is enabled, the seed cannot be printed unless it is called from a new Python process. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. If hash randomization is not supported ``subprocess=False`` is used automatically. >>> sympy.test(subprocess=False) # doctest: +SKIP To set the hash randomization seed, set the environment variable ``PYTHONHASHSEED`` before running the tests. This can be done from within Python using >>> import os >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP Or from the command line using $ PYTHONHASHSEED=42 ./bin/test If the seed is not set, a random seed will be chosen. Note that to reproduce the same hash values, you must use both the same seed as well as the same architecture (32-bit vs. 64-bit). """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_test", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_test(*paths, **kwargs)) if not val or i == 0: return val def _test(*paths, verbose=False, tb="short", kw=None, pdb=False, colors=True, force_colors=False, sort=True, seed=None, timeout=False, fail_on_timeout=False, slow=False, enhance_asserts=False, split=None, time_balance=True, blacklist=(), fast_threshold=None, slow_threshold=None): """ Internal function that actually runs the tests. All keyword arguments from ``test()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstring of ``test()`` for more information. """ kw = kw or () # ensure that kw is a tuple if isinstance(kw, str): kw = (kw,) post_mortem = pdb if seed is None: seed = random.randrange(100000000) if ON_CI and timeout is False: timeout = 595 fail_on_timeout = True if ON_CI: blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests'] blacklist = convert_to_native_paths(blacklist) r = PyTestReporter(verbose=verbose, tb=tb, colors=colors, force_colors=force_colors, split=split) # This won't strictly run the test for the corresponding file, but it is # good enough for copying and pasting the failing test. _paths = [] for path in paths: if '::' in path: path, _kw = path.split('::', 1) kw += (_kw,) _paths.append(path) paths = _paths t = SymPyTests(r, kw, post_mortem, seed, fast_threshold=fast_threshold, slow_threshold=slow_threshold) test_files = t.get_test_files('sympy') not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break density = None if time_balance: if slow: density = SPLIT_DENSITY_SLOW else: density = SPLIT_DENSITY if split: matched = split_list(matched, split, density=density) t._testfiles.extend(matched) return int(not t.test(sort=sort, timeout=timeout, slow=slow, enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout)) def doctest(*paths, subprocess=True, rerun=0, **kwargs): r""" Runs doctests in all \*.py files in the SymPy directory which match any of the given strings in ``paths`` or all tests if paths=[]. Notes: - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. Examples ======== >>> import sympy Run all tests: >>> sympy.doctest() # doctest: +SKIP Run one file: >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP >>> sympy.doctest("polynomial.rst") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP Run any file having polynomial in its name, doc/src/modules/polynomial.rst, sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py: >>> sympy.doctest("polynomial") # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. Note that the regular doctests and the Sphinx doctests are split independently. For instance, to run the first half of the test suite: >>> sympy.doctest(split='1/2') # doctest: +SKIP The ``subprocess`` and ``verbose`` options are the same as with the function ``test()`` (see the docstring of that function for more information) except that ``verbose`` may also be set equal to ``2`` in order to print individual doctest lines, as they are being tested. """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_doctest", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_doctest(*paths, **kwargs)) if not val or i == 0: return val def _get_doctest_blacklist(): '''Get the default blacklist for the doctests''' blacklist = [] blacklist.extend([ "doc/src/modules/plotting.rst", # generates live plots "doc/src/modules/physics/mechanics/autolev_parser.rst", "sympy/codegen/array_utils.py", # raises deprecation warning "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/galgebra.py", # no longer part of SymPy "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code "sympy/parsing/latex/_antlr/latexlexer.py", # generated code "sympy/parsing/latex/_antlr/latexparser.py", # generated code "sympy/plotting/pygletplot/__init__.py", # crashes on some systems "sympy/plotting/pygletplot/plot.py", # crashes on some systems "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning "sympy/this.py", # prints text ]) # autolev parser tests num = 12 for i in range (1, num+1): blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py") blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"]) if import_module('numpy') is None: blacklist.extend([ "sympy/plotting/experimental_lambdify.py", "sympy/plotting/plot_implicit.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py", "examples/intermediate/sample.py", "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py", "doc/src/modules/numeric-computation.rst", "doc/src/explanation/best-practices.md", "doc/src/tutorials/physics/biomechanics/biomechanical-model-example.rst", "doc/src/tutorials/physics/biomechanics/biomechanics.rst", ]) else: if import_module('matplotlib') is None: blacklist.extend([ "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py" ]) else: # Use a non-windowed backend, so that the tests work on CI import matplotlib matplotlib.use('Agg') if ON_CI or import_module('pyglet') is None: blacklist.extend(["sympy/plotting/pygletplot"]) if import_module('aesara') is None: blacklist.extend([ "sympy/printing/aesaracode.py", "doc/src/modules/numeric-computation.rst", ]) if import_module('cupy') is None: blacklist.extend([ "doc/src/modules/numeric-computation.rst", ]) if import_module('jax') is None: blacklist.extend([ "doc/src/modules/numeric-computation.rst", ]) if import_module('antlr4') is None: blacklist.extend([ "sympy/parsing/autolev/__init__.py", "sympy/parsing/latex/_parse_latex_antlr.py", ]) if import_module('lfortran') is None: #throws ImportError when lfortran not installed blacklist.extend([ "sympy/parsing/sym_expr.py", ]) if import_module("scipy") is None: # throws ModuleNotFoundError when scipy not installed blacklist.extend([ "doc/src/guides/solving/solve-numerically.md", "doc/src/guides/solving/solve-ode.md", ]) if import_module("numpy") is None: # throws ModuleNotFoundError when numpy not installed blacklist.extend([ "doc/src/guides/solving/solve-ode.md", "doc/src/guides/solving/solve-numerically.md", ]) # disabled because of doctest failures in asmeurer's bot blacklist.extend([ "sympy/utilities/autowrap.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py" ]) blacklist.extend([ "sympy/conftest.py", # Depends on pytest ]) # These are deprecated stubs to be removed: blacklist.extend([ "sympy/utilities/tmpfiles.py", "sympy/utilities/pytest.py", "sympy/utilities/runtests.py", "sympy/utilities/quality_unicode.py", "sympy/utilities/randtest.py", ]) blacklist = convert_to_native_paths(blacklist) return blacklist def _doctest(*paths, **kwargs): """ Internal function that actually runs the doctests. All keyword arguments from ``doctest()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstrings of ``doctest()`` and ``test()`` for more information. """ from sympy.printing.pretty.pretty import pprint_use_unicode from sympy.printing.pretty import stringpict normal = kwargs.get("normal", False) verbose = kwargs.get("verbose", False) colors = kwargs.get("colors", True) force_colors = kwargs.get("force_colors", False) blacklist = kwargs.get("blacklist", []) split = kwargs.get('split', None) blacklist.extend(_get_doctest_blacklist()) # Use a non-windowed backend, so that the tests work on CI if import_module('matplotlib') is not None: import matplotlib matplotlib.use('Agg') # Disable warnings for external modules import sympy.external sympy.external.importtools.WARN_OLD_VERSION = False sympy.external.importtools.WARN_NOT_INSTALLED = False # Disable showing up of plots from sympy.plotting.plot import unset_show unset_show() r = PyTestReporter(verbose, split=split, colors=colors,\ force_colors=force_colors) t = SymPyDocTests(r, normal) test_files = t.get_test_files('sympy') test_files.extend(t.get_test_files('examples', init_only=False)) not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # take only what was requested...but not blacklisted items # and allow for partial match anywhere or fnmatch of name paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break matched.sort() if split: matched = split_list(matched, split) t._testfiles.extend(matched) # run the tests and record the result for this *py portion of the tests if t._testfiles: failed = not t.test() else: failed = False # N.B. # -------------------------------------------------------------------- # Here we test *.rst and *.md files at or below doc/src. Code from these # must be self supporting in terms of imports since there is no importing # of necessary modules by doctest.testfile. If you try to pass *.py files # through this they might fail because they will lack the needed imports # and smarter parsing that can be done with source code. # test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False) test_files_md = t.get_test_files('doc/src', '*.md', init_only=False) test_files = test_files_rst + test_files_md test_files.sort() not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # Take only what was requested as long as it's not on the blacklist. # Paths were already made native in *py tests so don't repeat here. # There's no chance of having a *py file slip through since we # only have *rst files in test_files. matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break if split: matched = split_list(matched, split) first_report = True for rst_file in matched: if not os.path.isfile(rst_file): continue old_displayhook = sys.displayhook try: use_unicode_prev, wrap_line_prev = setup_pprint() out = sympytestfile( rst_file, module_relative=False, encoding='utf-8', optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) finally: # make sure we return to the original displayhook in case some # doctest has changed that sys.displayhook = old_displayhook # The NO_GLOBAL flag overrides the no_global flag to init_printing # if True import sympy.interactive.printing as interactive_printing interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) stringpict._GLOBAL_WRAP_LINE = wrap_line_prev rstfailed, tested = out if tested: failed = rstfailed or failed if first_report: first_report = False msg = 'rst/md doctests start' if not t._testfiles: r.start(msg=msg) else: r.write_center(msg) print() # use as the id, everything past the first 'sympy' file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:] print(file_id, end=" ") # get at least the name out so it is know who is being tested wid = r.terminal_width - len(file_id) - 1 # update width test_file = '[%s]' % (tested) report = '[%s]' % (rstfailed or 'OK') print(''.join( [test_file, ' '*(wid - len(test_file) - len(report)), report]) ) # the doctests for *py will have printed this message already if there was # a failure, so now only print it if there was intervening reporting by # testing the *rst as evidenced by first_report no longer being True. if not first_report and failed: print() print("DO *NOT* COMMIT!") return int(failed) sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` may be specified as a list. If specified, tests will be balanced so that each split has as equal-as-possible amount of mass according to `density`. >>> from sympy.testing.runtests import split_list >>> a = list(range(10)) >>> split_list(a, '1/3') [0, 1, 2] >>> split_list(a, '2/3') [3, 4, 5] >>> split_list(a, '3/3') [6, 7, 8, 9] """ m = sp.match(split) if not m: raise ValueError("split must be a string of the form a/b where a and b are ints") i, t = map(int, m.groups()) if not density: return l[(i - 1)*len(l)//t : i*len(l)//t] # normalize density tot = sum(density) density = [x / tot for x in density] def density_inv(x): """Interpolate the inverse to the cumulative distribution function given by density""" if x <= 0: return 0 if x >= sum(density): return 1 # find the first time the cumulative sum surpasses x # and linearly interpolate cumm = 0 for i, d in enumerate(density): cumm += d if cumm >= x: break frac = (d - (cumm - x)) / d return (i + frac) / len(density) lower_frac = density_inv((i - 1) / t) higher_frac = density_inv(i / t) return l[int(lower_frac*len(l)) : int(higher_frac*len(l))] from collections import namedtuple SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted') def sympytestfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=pdoctest.DocTestParser(), encoding=None): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg ``module_relative`` specifies how filenames should be interpreted: - If ``module_relative`` is True (the default), then ``filename`` specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the ``package`` argument is specified, then it is relative to that package. To ensure os-independence, ``filename`` should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If ``module_relative`` is False, then ``filename`` specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg ``name`` gives the name of the test; by default use the file's basename. Optional keyword argument ``package`` is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify ``package`` if ``module_relative`` is False. Optional keyword arg ``globs`` gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg ``extraglobs`` gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg ``verbose`` prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg ``report`` prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg ``optionflags`` or's together module constants, and defaults to 0. Possible values (see the docs for details): - DONT_ACCEPT_TRUE_FOR_1 - DONT_ACCEPT_BLANKLINE - NORMALIZE_WHITESPACE - ELLIPSIS - SKIP - IGNORE_EXCEPTION_DETAIL - REPORT_UDIFF - REPORT_CDIFF - REPORT_NDIFF - REPORT_ONLY_FIRST_FAILURE Optional keyword arg ``raise_on_error`` raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg ``parser`` specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg ``encoding`` specifies an encoding that should be used to convert the file to unicode. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path text, filename = pdoctest._load_testfile( filename, package, module_relative, encoding) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' if raise_on_error: runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags) runner._checker = SymPyOutputChecker() # Read the file, convert it to a test, and run it. test = parser.get_doctest(text, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if pdoctest.master is None: pdoctest.master = runner else: pdoctest.master.merge(runner) return SymPyTestResults(runner.failures, runner.tries)
DependencyError
python
celery__celery
t/unit/tasks/test_result.py
{ "start": 31306, "end": 32044 }
class ____: def setup_method(self): self.size = 11 self.app.conf.result_serializer = 'pickle' results = make_mock_group(self.app, 10) failed = mock_task('ts11', states.FAILURE, KeyError('Baz')) save_result(self.app, failed) failed_res = self.app.AsyncResult(failed['id']) self.ts = self.app.GroupResult(uuid(), results + [failed_res]) def test_completed_count(self): assert self.ts.completed_count() == len(self.ts) - 1 def test_join(self): with pytest.raises(KeyError): self.ts.join() def test_successful(self): assert not self.ts.successful() def test_failed(self): assert self.ts.failed()
test_failed_AsyncResult
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py
{ "start": 3150, "end": 3248 }
class ____: c: C = C() # https://github.com/astral-sh/ruff/issues/20266 @dataclass(frozen=True)
E
python
sympy__sympy
sympy/physics/control/lti.py
{ "start": 61768, "end": 78651 }
class ____(TransferFunctionBase): r""" A class for representing LTI (Linear, time-invariant) systems that can be strictly described by ratio of polynomials in the z-transform complex variable. The arguments are ``num``, ``den``, ``var``, and ``sampling_time``, where ``num`` and ``den`` are numerator and denominator polynomials of the ``DiscreteTransferFunction`` respectively, the third argument is a complex variable of the z-transform used by these polynomials of the transfer function, and the fourth represents the time interval between two consecutive sampling instants. If not specified, it defaults to 1 and, if it's set to 0, an instance of :class:`TransferFunction` is returned. ``num`` and ``den`` can be either polynomials or numbers, ``var`` has to be a :py:class:`~.Symbol` and ``sampling_time`` can be both :py:class:`~.Symbol` or numbers. See :class:`TransferFunctionBase` for more information. Parameters ========== num : Expr, Number The numerator polynomial of the transfer function. den : Expr, Number The denominator polynomial of the transfer function. var : Symbol Complex variable of the z-transform used by the polynomials of the transfer function. sampling_time : Symbol, Number Time interval between two consecutive sampling instants Defaults to 1. If sampling_time == 0, an instance of :class:`TransferFunction` is returned. Raises ====== TypeError When ``var`` is not a Symbol or when ``num`` or ``den`` is not a number or a polynomial. ValueError When ``den`` is zero. Examples ======== >>> from sympy.abc import z, p, a, k >>> from sympy.physics.control.lti import DiscreteTransferFunction >>> dtf1 = DiscreteTransferFunction(z**2 + a*z, z**2 + z + 1, z, 0.1) >>> dtf1 DiscreteTransferFunction(a*z + z**2, z**2 + z + 1, z, 0.1) >>> dtf1.num a*z + z**2 >>> dtf1.den z**2 + z + 1 >>> dtf1.var z >>> dtf1.sampling_time 0.1 >>> dtf1.args (a*z + z**2, z**2 + z + 1, z, 0.1) Any complex variable can be used for ``var``. >>> dtf2 = DiscreteTransferFunction(a*p**3 - a*p**2 + z*p, p + a**2, p, k) >>> dtf2 DiscreteTransferFunction(a*p**3 - a*p**2 + p*z, a**2 + p, p, k) >>> dtf3 = DiscreteTransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p, k) >>> dtf3 DiscreteTransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p, k) To negate a transfer function the ``-`` operator can be prepended: >>> dtf4 = DiscreteTransferFunction(-a + z, p**2 + z, p, 0.2) >>> -dtf4 DiscreteTransferFunction(a - z, p**2 + z, p, 0.2) >>> dtf5 = DiscreteTransferFunction(z**4 - 2*z**3 + 5*z + 4, z + 4, z, 12) >>> -dtf5 DiscreteTransferFunction(-z**4 + 2*z**3 - 5*z - 4, z + 4, z, 12) You can use a float or an integer (or other constants) as numerator and denominator: >>> dtf6 = DiscreteTransferFunction(1/2, 4, z, k) >>> dtf6.num 0.500000000000000 >>> dtf6.den 4 >>> dtf6.var z >>> dtf6.sampling_time k >>> dtf6.args (0.5, 4, z, k) You can take the integer power of a transfer function using the ``**`` operator: >>> dtf7 = DiscreteTransferFunction(z + a, z - a, z, 0.3) >>> dtf7**3 DiscreteTransferFunction((a + z)**3, (-a + z)**3, z, 0.3) >>> dtf7**0 DiscreteTransferFunction(1, 1, z, 0.3) >>> dtf8 = DiscreteTransferFunction(p + 4, p - 3, p, k) >>> dtf8**-1 DiscreteTransferFunction(p - 3, p + 4, p, k) Addition, subtraction, and multiplication of transfer functions can form unevaluated ``Series`` or ``Parallel`` objects. >>> dtf9 = DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k) >>> dtf10 = DiscreteTransferFunction(z - p, z + 3, z, k) >>> dtf11 = DiscreteTransferFunction(4*z**2 + 2*z - 4, z - 1, z, k) >>> dtf12 = DiscreteTransferFunction(1 - z, z**2 + 4, z, k) >>> dtf9 + dtf10 Parallel(DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k), DiscreteTransferFunction(-p + z, z + 3, z, k)) >>> dtf10 - dtf11 Parallel(DiscreteTransferFunction(-p + z, z + 3, z, k), DiscreteTransferFunction(-4*z**2 - 2*z + 4, z - 1, z, k)) >>> dtf9 * dtf10 Series(DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k), DiscreteTransferFunction(-p + z, z + 3, z, k)) >>> dtf10 - (dtf9 + dtf12) Parallel(DiscreteTransferFunction(-p + z, z + 3, z, k), DiscreteTransferFunction(-z - 1, z**2 + z + 1, z, k), DiscreteTransferFunction(z - 1, z**2 + 4, z, k)) >>> dtf10 - (dtf9 * dtf12) Parallel(DiscreteTransferFunction(-p + z, z + 3, z, k), Series(DiscreteTransferFunction(-1, 1, z, k), DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k), DiscreteTransferFunction(1 - z, z**2 + 4, z, k))) >>> dtf11 * dtf10 * dtf9 Series(DiscreteTransferFunction(4*z**2 + 2*z - 4, z - 1, z, k), DiscreteTransferFunction(-p + z, z + 3, z, k), DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k)) >>> dtf9 * dtf11 + dtf10 * dtf12 Parallel(Series(DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k), DiscreteTransferFunction(4*z**2 + 2*z - 4, z - 1, z, k)), Series(DiscreteTransferFunction(-p + z, z + 3, z, k), DiscreteTransferFunction(1 - z, z**2 + 4, z, k))) >>> (dtf9 + dtf12) * (dtf10 + dtf11) Series(Parallel(DiscreteTransferFunction(z + 1, z**2 + z + 1, z, k), DiscreteTransferFunction(1 - z, z**2 + 4, z, k)), Parallel(DiscreteTransferFunction(-p + z, z + 3, z, k), DiscreteTransferFunction(4*z**2 + 2*z - 4, z - 1, z, k))) These unevaluated ``Series`` or ``Parallel`` objects can convert into the resultant transfer function using ``.doit()`` method or by ``.rewrite(DiscreteTransferFunction)``. >>> ((dtf9 + dtf10) * dtf12).doit() DiscreteTransferFunction((1 - z)*((-p + z)*(z**2 + z + 1) + (z + 1)*(z + 3)), (z + 3)*(z**2 + 4)*(z**2 + z + 1), z, k) >>> (dtf9 * dtf10 - dtf11 * dtf12).rewrite(DiscreteTransferFunction) DiscreteTransferFunction(-(1 - z)*(z + 3)*(z**2 + z + 1)*(4*z**2 + 2*z - 4) + (-p + z)*(z - 1)*(z + 1)*(z**2 + 4), (z - 1)*(z + 3)*(z**2 + 4)*(z**2 + z + 1), z, k) See Also ======== TransferFunctionBase, TransferFunction, Feedback, Series, Parallel """ def __new__(cls, num, den, var, sampling_time=1): if sampling_time == 0: raise ValueError(filldedent(""" The sampling time cannot be zero. If you want to create a continuous transfer function, use the TransferFunction class instead.""")) sampling_time = sympify(sampling_time) obj = super(DiscreteTransferFunction, cls).__new__(cls, num, den, var, sampling_time) obj._sampling_time = sampling_time return obj @classmethod def from_rational_expression(cls, expr, var=None, sampling_time=1): r""" See :func:`TransferFunctionBase.from_rational_expression`. """ return super().from_rational_expression(expr, var, sampling_time=sampling_time) @classmethod def from_coeff_lists(cls, num_list, den_list, var, sampling_time=1): r""" See :func:`TransferFunctionBase.from_coeff_lists`. """ return super().from_coeff_lists(num_list, den_list, var, sampling_time=sampling_time) @classmethod def from_zpk(cls, zeros, poles, gain, var, sampling_time=1): r""" See :func:`TransferFunctionBase.from_zpk`. """ return super().from_zpk(zeros, poles, gain, var, sampling_time = sampling_time) @classmethod def from_gbt(cls, cont_tf, sampling_time, alpha, var): r""" Returns the discretized transfer function H(z) from a continuous transfer function H(s). Parameters ========== cont_tf : TransferFunction The continuous transfer function H(s) to be discretized. sampling_time : Symbol, Number Time interval between two consecutive sampling instants. alpha: Symbol, Number The parameter for the generalised bilinear transformation method. var: Symbol The complex variable of the z-transform used by the polynomials of the transfer function. Explanation =========== Where H(z) is the corresponding discretized transfer function, discretized with the generalised bilinear transformation method. H(z) is obtained from the continuous transfer function H(s) by substituting $s(z) = \frac{z-1}{T(\alpha z + (1-\alpha))}$ into H(s), where T is the sample time. Examples ======== >>> from sympy.physics.control.lti import TransferFunction, DiscreteTransferFunction >>> from sympy.abc import s, z, L, R, T >>> tf = TransferFunction(1, s*L + R, s) >>> dttf1 = DiscreteTransferFunction.from_gbt(tf, T, 0.5, z) >>> dttf1.num T*z/(2*(L + R*T/2)) + T/(2*(L + R*T/2)) >>> dttf1.den z + (-L + R*T/2)/(L + R*T/2) >>> dttf1.sampling_time T >>> dttf2 = DiscreteTransferFunction.from_gbt(tf, T, 0, z) >>> dttf2.num T/L >>> dttf2.den z + (-L + R*T)/L >>> dttf2.sampling_time T >>> dttf3 = DiscreteTransferFunction.from_gbt(tf, T, 1, z) >>> dttf3.num T*z/(L + R*T) >>> dttf3.den -L/(L + R*T) + z >>> dttf3.sampling_time T >>> dttf4 = DiscreteTransferFunction.from_gbt(tf, T, 0.3, z) >>> dttf4.num 3*T*z/(10*(L + 3*R*T/10)) + 7*T/(10*(L + 3*R*T/10)) >>> dttf4.den z + (-L + 7*R*T/10)/(L + 3*R*T/10) >>> dttf4.sampling_time T References ========== .. [1] https://www.polyu.edu.hk/ama/profile/gfzhang/Research/ZCC09_IJC.pdf """ num, den = gbt(cont_tf, sampling_time, alpha) return cls.from_coeff_lists(num, den, var, sampling_time) @classmethod def from_bilinear(cls, cont_tf, sampling_time, var): r""" Returns the discretized transfer function H(z) from a continuous transfer function H(s). Parameters ========== cont_tf : TransferFunction The continuous transfer function H(s) to be discretized. sampling_time : Symbol, Number Time interval between two consecutive sampling instants. var: Symbol The complex variable of the z-transform used by the polynomials of the transfer function. Explanation =========== Where H(z) is the corresponding discretized transfer function, discretized with the bilinear transform method. H(z) is obtained from the continuous transfer function H(s) by substituting $s(z) = \frac{2}{T}\frac{z-1}{z+1}$ into H(s), where T is the sample time. Examples ======== >>> from sympy.physics.control.lti import TransferFunction, DiscreteTransferFunction >>> from sympy.abc import s, z, L, R, T >>> tf = TransferFunction(1, s*L + R, s) >>> dttf = DiscreteTransferFunction.from_bilinear(tf, T, z) >>> dttf.num T*z/(2*(L + R*T/2)) + T/(2*(L + R*T/2)) >>> dttf.den z + (-L + R*T/2)/(L + R*T/2) >>> dttf.sampling_time T """ num, den = bilinear(cont_tf, sampling_time) return cls.from_coeff_lists(num, den, var, sampling_time) @classmethod def from_forward_diff(cls, cont_tf, sampling_time, var): r""" Returns the discretized transfer function H(z) from a continuous transfer function H(s). Parameters ========== cont_tf : TransferFunction The continuous transfer function H(s) to be discretized. sampling_time : Symbol, Number Time interval between two consecutive sampling instants. var: Symbol The complex variable of the z-transform used by the polynomials of the transfer function. Explanation =========== Where H(z) is the corresponding discretized transfer function, discretized with the forward difference transform method. H(z) is obtained from the continuous transfer function H(s) by substituting $s(z) = \frac{z-1}{T}$ into H(s), where T is the sample time. Examples ======== >>> from sympy.physics.control.lti import TransferFunction, DiscreteTransferFunction >>> from sympy.abc import s, z, L, R, T >>> tf = TransferFunction(1, s*L + R, s) >>> dttf = DiscreteTransferFunction.from_forward_diff(tf, T, z) >>> dttf.num T/L >>> dttf.den z + (-L + R*T)/L >>> dttf.sampling_time T """ num, den = forward_diff(cont_tf, sampling_time) return cls.from_coeff_lists(num, den, var, sampling_time) @classmethod def from_backward_diff(cls, cont_tf, sampling_time, var): r""" Returns the discretized transfer function H(z) from a continuous transfer function H(s). Parameters ========== cont_tf : TransferFunction The continuous transfer function H(s) to be discretized. sampling_time : Symbol, Number Time interval between two consecutive sampling instants. var: Symbol The complex variable of the z-transform used by the polynomials of the transfer function. Explanation =========== Where H(z) is the corresponding discretized transfer function, discretized with the backward difference transform method. H(z) is obtained from the continuous transfer function H(s) by substituting $s(z) = \frac{z-1}{Tz}$ into H(s), where T is the sample time. Examples ======== >>> from sympy.physics.control.lti import TransferFunction, DiscreteTransferFunction >>> from sympy.abc import s, z, L, R, T >>> tf = TransferFunction(1, s*L + R, s) >>> dttf = DiscreteTransferFunction.from_backward_diff(tf, T, z) >>> dttf.num T*z/(L + R*T) >>> dttf.den -L/(L + R*T) + z >>> dttf.sampling_time T """ num, den = backward_diff(cont_tf, sampling_time) return cls.from_coeff_lists(num, den, var, sampling_time) def dc_gain(self): r""" See :func:`TransferFunctionBase.dc_gain`. """ m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False) return limit(m, self.var, 1) def get_asymptotic_stability_conditions( self, cancel_poles_zeros=False, fast=False ) -> list[Boolean]: r""" See :func:`TransferFunctionBase.get_asymptotic_stability_conditions`. """ standard_form = self.to_standard_form(cancel_poles_zeros) domain = EXRAW if fast else None p = Poly(standard_form.den, self.var, domain = domain) return [c > 0 for c in p.schur_conditions()] def _eval_rewrite_as_DiscreteStateSpace(self, *args): """ Returns the equivalent space model of the transfer function model. The state space model will be returned in the controllable canonical form. Unlike the space state to transfer function model conversion, the transfer function to state space model conversion is not unique. There can be multiple state space representations of a given transfer function model. Examples ======== >>> from sympy.abc import z >>> from sympy.physics.control import DiscreteTransferFunction, DiscreteStateSpace >>> dtf = DiscreteTransferFunction(z**2 + 1, z**3 + z*2 + 10, z, 0.1) >>> dtf.rewrite(DiscreteStateSpace) DiscreteStateSpace(Matrix([ [ 0, 1, 0], [ 0, 0, 1], [-10, -2, 0]]), Matrix([ [0], [0], [1]]), Matrix([[1, 0, 1]]), Matrix([[0]]), 0.1) """ A, B, C, D = self._StateSpace_matrices_equivalent() return DiscreteStateSpace(A, B, C, D, self.sampling_time) def _eval_rewrite_as_StateSpace(self, *args): raise TypeError(""" The discrete transfer function model cannot be rewritten as a continuous-time state space model. """) @property def sampling_time(self): """Returns the sampling time of the DiscreteTransferFunction.""" return self._sampling_time _is_continuous = False
DiscreteTransferFunction
python
sanic-org__sanic
sanic/cli/arguments.py
{ "start": 5121, "end": 6146 }
class ____(Group): name = "TLS certificate" def attach(self): self.container.add_argument( "--cert", dest="cert", type=str, help="Location of fullchain.pem, bundle.crt or equivalent", ) self.container.add_argument( "--key", dest="key", type=str, help="Location of privkey.pem or equivalent .key file", ) self.container.add_argument( "--tls", metavar="DIR", type=str, action="append", help=( "TLS certificate folder with fullchain.pem and privkey.pem\n" "May be specified multiple times to choose multiple " "certificates" ), ) self.container.add_argument( "--tls-strict-host", dest="tlshost", action="store_true", help="Only allow clients that send an SNI matching server certs", )
TLSGroup
python
jazzband__django-oauth-toolkit
tests/test_application_views.py
{ "start": 700, "end": 2822 }
class ____(BaseTest): @pytest.mark.oauth2_settings({"APPLICATION_MODEL": "tests.SampleApplication"}) def test_get_form_class(self): """ Tests that the form class returned by the "get_form_class" method is bound to custom application model defined in the "OAUTH2_PROVIDER_APPLICATION_MODEL" setting. """ # Create a registration view and tests that the model form is bound # to the custom Application model application_form_class = ApplicationRegistration().get_form_class() self.assertEqual(SampleApplication, application_form_class._meta.model) def test_application_registration_user(self): self.client.login(username="foo_user", password="123456") form_data = { "name": "Foo app", "client_id": "client_id", "client_secret": "client_secret", "client_type": Application.CLIENT_CONFIDENTIAL, "redirect_uris": "http://example.com", "post_logout_redirect_uris": "http://other_example.com", "authorization_grant_type": Application.GRANT_AUTHORIZATION_CODE, "algorithm": "", } response = self.client.post(reverse("oauth2_provider:register"), form_data) self.assertEqual(response.status_code, 302) app = get_application_model().objects.get(name="Foo app") self.assertEqual(app.user.username, "foo_user") app = Application.objects.get() self.assertEqual(app.name, form_data["name"]) self.assertEqual(app.client_id, form_data["client_id"]) self.assertEqual(app.redirect_uris, form_data["redirect_uris"]) self.assertEqual(app.post_logout_redirect_uris, form_data["post_logout_redirect_uris"]) self.assertEqual(app.client_type, form_data["client_type"]) self.assertEqual(app.authorization_grant_type, form_data["authorization_grant_type"]) self.assertEqual(app.algorithm, form_data["algorithm"]) @pytest.mark.usefixtures("oauth2_settings") @pytest.mark.oauth2_settings({"ALLOW_URI_WILDCARDS": True})
TestApplicationRegistrationView
python
getsentry__sentry
src/sentry/rules/match.py
{ "start": 87, "end": 3132 }
class ____(StrEnum): CONTAINS = "co" ENDS_WITH = "ew" EQUAL = "eq" GREATER_OR_EQUAL = "gte" GREATER = "gt" IS_SET = "is" IS_IN = "in" LESS_OR_EQUAL = "lte" LESS = "lt" NOT_CONTAINS = "nc" NOT_ENDS_WITH = "new" NOT_EQUAL = "ne" NOT_SET = "ns" NOT_STARTS_WITH = "nsw" NOT_IN = "nin" STARTS_WITH = "sw" LEVEL_MATCH_CHOICES = { MatchType.EQUAL: "equal to", MatchType.GREATER_OR_EQUAL: "greater than or equal to", MatchType.LESS_OR_EQUAL: "less than or equal to", } RELEASE_MATCH_CHOICES = { MatchType.EQUAL: "equal to", MatchType.GREATER: "greater than", MatchType.LESS: "less than", } MATCH_CHOICES = { MatchType.CONTAINS: "contains", MatchType.ENDS_WITH: "ends with", MatchType.EQUAL: "equals", MatchType.IS_SET: "is set", MatchType.IS_IN: "is in (comma separated)", MatchType.NOT_CONTAINS: "does not contain", MatchType.NOT_ENDS_WITH: "does not end with", MatchType.NOT_EQUAL: "does not equal", MatchType.NOT_SET: "is not set", MatchType.NOT_STARTS_WITH: "does not start with", MatchType.NOT_IN: "not in (comma separated)", MatchType.STARTS_WITH: "starts with", } def match_values(group_values: Iterable[Any], match_value: str, match_type: str) -> bool: if match_type == MatchType.EQUAL: group_values_set = set(group_values) return match_value in group_values_set elif match_type == MatchType.NOT_EQUAL: group_values_set = set(group_values) return match_value not in group_values_set elif match_type == MatchType.STARTS_WITH: for g_value in group_values: if g_value.startswith(match_value): return True return False elif match_type == MatchType.NOT_STARTS_WITH: for g_value in group_values: if g_value.startswith(match_value): return False return True elif match_type == MatchType.ENDS_WITH: for g_value in group_values: if g_value.endswith(match_value): return True return False elif match_type == MatchType.NOT_ENDS_WITH: for g_value in group_values: if g_value.endswith(match_value): return False return True elif match_type == MatchType.CONTAINS: group_values_set = set(group_values) return any(match_value in g_value for g_value in group_values_set) elif match_type == MatchType.NOT_CONTAINS: group_values_set = set(group_values) return not any(match_value in g_value for g_value in group_values_set) elif match_type == MatchType.IS_IN: values_set = {value.strip() for value in match_value.split(",")} return any(g_value in values_set for g_value in group_values) elif match_type == MatchType.NOT_IN: values_set = {value.strip() for value in match_value.split(",")} return not any(g_value in values_set for g_value in group_values) raise RuntimeError("Invalid Match")
MatchType
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_permutation_test.py
{ "start": 1465, "end": 4107 }
class ____( linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def tearDown(self): config.enable_tensor_float_32_execution(self.tf32_keep_) def setUp(self): self.tf32_keep_ = config.tensor_float_32_execution_enabled() config.enable_tensor_float_32_execution(False) @staticmethod def operator_shapes_infos(): shape_info = linear_operator_test_util.OperatorShapesInfo return [ shape_info((1, 1)), shape_info((1, 3, 3)), shape_info((3, 4, 4)), shape_info((2, 1, 4, 4))] @staticmethod def skip_these_tests(): # This linear operator is almost never positive definite. return ["cholesky", "eigvalsh"] def operator_and_matrix( self, build_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False): shape = list(build_info.shape) perm = math_ops.range(0, shape[-1]) perm = array_ops.broadcast_to(perm, shape[:-1]) perm = random_ops.random_shuffle(perm) if use_placeholder: perm = array_ops.placeholder_with_default( perm, shape=None) operator = permutation.LinearOperatorPermutation( perm, dtype=dtype) matrix = math_ops.cast( math_ops.equal( math_ops.range(0, shape[-1]), perm[..., array_ops.newaxis]), dtype) return operator, matrix def test_permutation_raises(self): perm = constant_op.constant(0, dtype=dtypes.int32) with self.assertRaisesRegex(ValueError, "must have at least 1 dimension"): permutation.LinearOperatorPermutation(perm) perm = [0., 1., 2.] with self.assertRaisesRegex(TypeError, "must be integer dtype"): permutation.LinearOperatorPermutation(perm) perm = [-1, 2, 3] with self.assertRaisesRegex(ValueError, "must be a vector of unique integers"): permutation.LinearOperatorPermutation(perm) def test_to_dense_4x4(self): perm = [0, 1, 2, 3] self.assertAllClose( permutation.LinearOperatorPermutation(perm).to_dense(), linalg_ops.eye(4)) perm = [1, 0, 3, 2] self.assertAllClose( permutation.LinearOperatorPermutation(perm).to_dense(), [[0., 1, 0, 0], [1., 0, 0, 0], [0., 0, 0, 1], [0., 0, 1, 0]]) perm = [3, 2, 0, 1] self.assertAllClose( permutation.LinearOperatorPermutation(perm).to_dense(), [[0., 0, 0, 1], [0., 0, 1, 0], [1., 0, 0, 0], [0., 1, 0, 0]]) if __name__ == "__main__": linear_operator_test_util.add_tests(LinearOperatorPermutationTest) test.main()
LinearOperatorPermutationTest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/clipboard/base.py
{ "start": 304, "end": 622 }
class ____: """ Text on the clipboard. :param text: string :param type: :class:`~prompt_toolkit.selection.SelectionType` """ def __init__( self, text: str = "", type: SelectionType = SelectionType.CHARACTERS ) -> None: self.text = text self.type = type
ClipboardData
python
tensorflow__tensorflow
tensorflow/python/ops/custom_gradient.py
{ "start": 11930, "end": 30651 }
class ____: """When called evaluates `d(f, args, kwargs)` but supports binding `f`. >>> @Bind.decorator ... def my_decorator(f, args, kwargs): ... print("my_decorator called with", args, kwargs) ... return f(*args, **kwargs) >>> class Foo: ... @my_decorator ... def bar(self, a, b, c): ... return a * b * c >>> Foo.bar(None, 1, 2, c=3) my_decorator called with (None, 1, 2) {'c': 3} 6 >>> foo = Foo() >>> foo.bar(1, 2, c=3) my_decorator called with (1, 2) {'c': 3} 6 """ @classmethod def decorator(cls, d): return lambda f: Bind(f, d) def __init__(self, f, d): self._f = f self._d = d def __get__(self, instance, owner): if instance is not None: f = self._f.__get__(instance, owner) return tf_decorator.make_decorator(f, Bind(f, self._d)) else: return self def __call__(self, *a, **k): return self._d(self._f, a, k) def get_variable_by_name(var_name): """Given a variable name, retrieves a handle on the tensorflow Variable.""" global_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) def _filter_fn(item): try: return var_name == item.op.name except AttributeError: # Collection items without operation are ignored. return False candidate_vars = list(filter(_filter_fn, global_vars)) if len(candidate_vars) >= 1: # Filter out non-trainable variables. candidate_vars = [v for v in candidate_vars if v.trainable] else: raise ValueError("Unsuccessful at finding variable {}.".format(var_name)) if len(candidate_vars) == 1: return candidate_vars[0] elif len(candidate_vars) > 1: raise ValueError( "Unsuccessful at finding trainable variable {}. " "Number of candidates: {}. " "Candidates: {}".format(var_name, len(candidate_vars), candidate_vars)) else: # The variable is not trainable. return None def _get_dependent_variables(input_ops, output_ops): """Finds variables involved in the subgraph between input_ops and output_ops. Args: input_ops: Flattened list of input ops output_ops: Flattened list of output ops Returns: A list of variables """ # avoids the edge-case when input_ops == output_ops. output_ops = nest.map_structure(gen_array_ops.identity, output_ops) inbetween_ops = op_selector.get_backward_walk_ops( seed_ops=output_ops, stop_at_ts=input_ops, inclusive=False, only_differentiable=True) var_ops = (op for op in inbetween_ops if op.type in VAR_OP_TYPES) var_names = (op.name for op in var_ops) tf_vars = (get_variable_by_name(var_name) for var_name in var_names) tf_vars = [v for v in tf_vars if v is not None] return tf_vars def generate_name(): return "CustomGradient-%s" % ops.uid() def _graph_mode_decorator(f, args, kwargs): """Implement custom gradient decorator for graph mode.""" # TODO(rsepassi): Add support for kwargs if kwargs: raise ValueError( "The custom_gradient decorator currently supports keywords " "arguments only when eager execution is enabled.") name = generate_name() args = variable_utils.convert_variables_to_tensors(args) args = nest.map_structure(ops.convert_to_tensor, args, expand_composites=True) # Checking global and local variables attempts to ensure that no non-resource # Variables are added to the graph. current_var_scope = variable_scope.get_variable_scope() before_vars = set([ v.ref() for v in current_var_scope.global_variables() + current_var_scope.local_variables() ]) with record.VariableWatcher() as variable_watcher: result, grad_fn = f(*args) flat_args = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(args)) flat_result = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(result)) flat_result_len = len(flat_result) after_vars = set([ v.ref() for v in current_var_scope.global_variables() + current_var_scope.local_variables() ]) new_vars = after_vars - before_vars new_vars_list = [v.deref() for v in new_vars] for v in new_vars_list: if not resource_variable_ops.is_resource_variable(v): raise TypeError( "All variables used by a function wrapped with @custom_gradient must " "be `ResourceVariable`s. Ensure that no `variable_scope` is created " "with `use_resource=False`.") # The variables that grad_fn needs to return gradients for are the set of # variables used that are *not* part of the inputs. variables_in_tape = frozenset([ v.ref() for v in variable_watcher.watched_variables() ]) graphs = {getattr(o, "graph", None) for o in flat_result} # Not all results may be tensors. However, we want to ensure all tensor # outputs are from the same graph and get a list of captured inputs for # variable search graphs.discard(None) # Discard non-graph outputs if graphs: if len(graphs) > 1: raise ValueError( "All custom_gradient outputs should be from the same graph") output_graph = graphs.pop() filtered_input_tensors = [] for i in flat_args: if i.graph == output_graph: filtered_input_tensors.append(i) else: filtered_input_tensors = flat_args variables_in_subgraph = frozenset([ v.ref() for v in _get_dependent_variables( input_ops=filtered_input_tensors, output_ops=flat_result) ]) variables = sorted( [v.deref() for v in variables_in_subgraph.union(variables_in_tape)], key=lambda v: v.name) grad_argspec = tf_inspect.getfullargspec(grad_fn) variables_in_signature = ("variables" in grad_argspec.args or "variables" in grad_argspec.kwonlyargs or grad_argspec.varkw) if variables and not variables_in_signature: raise TypeError( "@tf.custom_gradient grad_fn must accept keyword argument 'variables', " "since function uses variables: {}".format(variables)) if variables_in_signature and not variables: # User seems to intend to use variables but none were captured. logging.vlog( 1, "@custom_gradient grad_fn has 'variables' in signature, " "but no ResourceVariables were used on the forward pass.") all_tensors = flat_result + flat_args + variables def tape_grad_fn(*result_grad_components): """Custom grad fn wrapper.""" result_grads = composite_tensor_gradient.replace_flat_tensors_for_gradients( nest.flatten(result), result_grad_components[:flat_result_len]) if not isinstance(result_grads, (list, tuple)): result_grads = [result_grads] if variables: input_grads, variable_grads = grad_fn(*result_grads, variables=variables) if len(variable_grads) != len(variables): raise ValueError("Must return gradient for each variable from " "@custom_gradient grad_fn.") else: input_grads = grad_fn(*result_grads) variable_grads = [] # Need to return one value per input to the IdentityN, so pad the # gradients of the inputs of the custom_gradient function with the # gradients of the outputs as well. input_grads = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(input_grads)) return ([None] * flat_result_len) + input_grads + variable_grads @ops.RegisterGradient(name) def internal_grad_fn(unused_op, *result_grads): # pylint: disable=unused-variable """Custom grad fn wrapper.""" return tape_grad_fn(*result_grads) original_tensors = all_tensors with ops.get_default_graph().gradient_override_map({"IdentityN": name}): all_tensors = array_ops.identity_n(all_tensors) original_tensors = [ops.convert_to_tensor(x) for x in original_tensors] # Propagate handle data for happier shape inference for resource variables. for i, t in enumerate(original_tensors): if t.dtype == dtypes.resource and hasattr(t, "_handle_data"): all_tensors[i]._handle_data = t._handle_data # pylint: disable=protected-access record.record_operation( f.__name__, all_tensors, original_tensors, tape_grad_fn) for ot, t in zip(original_tensors, all_tensors): handle_data_util.copy_handle_data(ot, t) flat_result = composite_tensor_gradient.replace_flat_tensors_for_gradients( nest.flatten(result), all_tensors[:flat_result_len]) return nest.pack_sequence_as(result, flat_result) def _eager_mode_decorator(f, args, kwargs): """Implement custom gradient decorator for eager mode.""" with record.VariableWatcher() as variable_watcher: result, grad_fn = f(*args, **kwargs) flat_args = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(args)) flat_kwargs = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(kwargs)) all_inputs = flat_args + flat_kwargs # The variables that grad_fn needs to return gradients for are the set of # variables used that are *not* part of the inputs. variables = [ v.deref() # pylint: disable=g-complex-comprehension for v in set(v.ref() for v in variable_watcher.watched_variables()) if all(v.deref() is not i for i in all_inputs) ] grad_argspec = tf_inspect.getfullargspec(grad_fn) if (variables and ("variables" not in grad_argspec.args) and ("variables" not in grad_argspec.kwonlyargs) and not grad_argspec.varkw): raise TypeError( "@tf.custom_gradient grad_fn must accept keyword argument 'variables', " "since function uses variables: {}".format(variables)) flat_result = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(result)) # TODO(apassos) consider removing the identity below. flat_result = [gen_array_ops.identity(x) for x in flat_result] input_tensors = [ ops.convert_to_tensor(x) for x in flat_args + list(variables)] recorded_inputs = input_tensors arg_count = len(flat_args) def actual_grad_fn(*result_grad_components): """Custom grad fn wrapper.""" result_grads = composite_tensor_gradient.replace_flat_tensors_for_gradients( nest.flatten(result), result_grad_components) if not isinstance(result_grads, (list, tuple)): result_grads = [result_grads] if variables: input_grads, variable_grads = grad_fn(*result_grads, variables=variables) if len(variable_grads) != len(variables): raise ValueError("Must return gradient for each variable from " "@custom_gradient grad_fn.") else: input_grads = grad_fn(*result_grads) variable_grads = [] flat_grads = composite_tensor_gradient.get_flat_tensors_for_gradients( nest.flatten(input_grads)) if len(flat_grads) != arg_count: raise ValueError( f"custom_gradient function expected to return {arg_count} " f"gradients, but returned {len(flat_grads)} instead.") return flat_grads + variable_grads record.record_operation(f.__name__, flat_result, recorded_inputs, actual_grad_fn) flat_result = composite_tensor_gradient.replace_flat_tensors_for_gradients( nest.flatten(result), flat_result) return nest.pack_sequence_as(result, flat_result) @tf_export("recompute_grad") def recompute_grad(f): """Defines a function as a recompute-checkpoint for the tape auto-diff. Tape checkpointing is a technique to reduce the memory consumption of the auto-diff tape: - Without tape checkpointing operations and intermediate values are recorded to the tape for use in the backward pass. - With tape checkpointing, only the function call and its inputs are recorded. During back-propagation the `recompute_grad` custom gradient (`tf.custom_gradient`) recomputes the function under a localized Tape object. This recomputation of the function during backpropagation performs redundant calculation, but reduces the overall memory usage of the Tape. >>> y = tf.Variable(1.0) >>> def my_function(x): ... tf.print('running') ... z = x*y ... return z >>> my_function_recompute = tf.recompute_grad(my_function) >>> with tf.GradientTape() as tape: ... r = tf.constant(1.0) ... for i in range(4): ... r = my_function_recompute(r) running running running running >>> grad = tape.gradient(r, [y]) running running running running Without `recompute_grad`, the tape contains all intermitate steps, and no recomputation is performed. >>> with tf.GradientTape() as tape: ... r = tf.constant(1.0) ... for i in range(4): ... r = my_function(r) running running running running >>> grad = tape.gradient(r, [y]) If `f` was a `tf.keras` `Model` or `Layer` object, methods and attributes such as `f.variables` are not available on the returned function `g`. Either keep a reference of `f` , or use `g.__wrapped__` for accessing these variables and methods. >>> def print_running_and_return(x): ... tf.print("running") ... return x >>> model = tf.keras.Sequential([ ... tf.keras.layers.Lambda(print_running_and_return), ... tf.keras.layers.Dense(2) ... ]) >>> model_recompute = tf.recompute_grad(model) >>> with tf.GradientTape(persistent=True) as tape: ... r = tf.constant([[1,2]]) ... for i in range(4): ... r = model_recompute(r) running running running running >>> grad = tape.gradient(r, model.variables) running running running running Alternatively, use the `__wrapped__` attribute to access the original model object. >>> grad = tape.gradient(r, model_recompute.__wrapped__.variables) running running running running Args: f: function `f(*x)` that returns a `Tensor` or sequence of `Tensor` outputs. Returns: A function `g` wrapping `f` that defines a custom gradient, which recomputes `f` on the backwards pass of a gradient call. """ # TODO(cdfreeman) Add is_recomputing functionality from graph mode version @custom_gradient def inner(*args, **kwargs): """Inner function closure for calculating gradients.""" current_var_scope = variable_scope.get_variable_scope() with record.stop_recording(): result = f(*args, **kwargs) def grad_wrapper(*wrapper_args, variables=None): """Wrapper function to accomodate lack of kwargs in graph mode custom_gradient.""" @custom_gradient def inner_recompute_grad(*dresult): """Nested custom gradient function for computing grads in reverse and forward mode autodiff.""" # Gradient calculation for reverse mode autodiff. with backprop.GradientTape() as t: id_args = nest.map_structure(gen_array_ops.identity, args) # Tuple `dresult` should contain at least one tensor. assert len(dresult) >= 1 if not context.executing_eagerly(): # XLA doesn't respect `tf.control_dependencies`. The code block # below manually adds a data dependency to `dresult` to ensure # recomputation of `f(*args, **kwargs)` happens after `dresult`. # This works even if `dresult[0]` is a size 0 tensor as reduce_max # of a size 0 tensor returns -inf. Use reshape here to avoid reading # the entire `dresult[0]`. elem = math_ops.reduce_max(array_ops.reshape(dresult[0], [-1])[:1]) # Cast elem to bool in case elem is NaN. elem_bool = math_ops.cast(elem, dtypes.bool) dresult_dep = array_ops.where_v2( elem_bool == elem_bool, 0., float("nan")) # pylint: disable=comparison-with-itself id_args = nest.map_structure( lambda x: x + math_ops.cast(dresult_dep, x.dtype), id_args) t.watch(id_args) if variables is not None: t.watch(variables) with variable_scope.variable_scope(current_var_scope): recomputed_result = f(*id_args, **kwargs) kw_vars = [] if variables is not None: kw_vars = list(variables) grads = t.gradient( recomputed_result, list(id_args) + kw_vars, output_gradients=dresult, unconnected_gradients=UnconnectedGradients.ZERO) def transpose(*t_args, **t_kwargs): """Gradient function calculation for forward mode autodiff.""" # Just throw an error since gradients / activations are not stored on # tape for recompute. raise NotImplementedError( "recompute_grad tried to transpose grad of {}. " "Consider not using recompute_grad in forward mode" "autodiff".format(f.__name__)) return (grads[:len(id_args)], grads[len(id_args):]), transpose return inner_recompute_grad(*wrapper_args) return result, grad_wrapper return tf_decorator.make_decorator(f, inner) @tf_export("grad_pass_through") def grad_pass_through(f): """Creates a grad-pass-through op with the forward behavior provided in f. Use this function to wrap any op, maintaining its behavior in the forward pass, but replacing the original op in the backward graph with an identity. For example: ```python x = tf.Variable(1.0, name="x") z = tf.Variable(3.0, name="z") with tf.GradientTape() as tape: # y will evaluate to 9.0 y = tf.grad_pass_through(x.assign)(z**2) # grads will evaluate to 6.0 grads = tape.gradient(y, z) ``` Another example is a 'differentiable' moving average approximation, where gradients are allowed to flow into the last value fed to the moving average, but the moving average is still used for the forward pass: ```python x = ... # Some scalar value # A moving average object, we don't need to know how this is implemented moving_average = MovingAverage() with backprop.GradientTape() as tape: # mavg_x will evaluate to the current running average value mavg_x = tf.grad_pass_through(moving_average)(x) grads = tape.gradient(mavg_x, x) # grads will evaluate to 1.0 ``` Args: f: function `f(*x)` that returns a `Tensor` or nested structure of `Tensor` outputs. Returns: A function `h(x)` which returns the same values as `f(x)` and whose gradients are the same as those of an identity function. """ @custom_gradient def _grad_pass_through_op(*args, **kwargs): def grad(*args, **kwargs): variables = kwargs.get("variables") if variables is not None: # Variables involved in the wrapped op will not receive gradients. return args, [None] * len(variables) return args return f(*args, **kwargs), grad return tf_decorator.make_decorator(f, _grad_pass_through_op)
Bind
python
ray-project__ray
rllib/connectors/agent/state_buffer.py
{ "start": 694, "end": 4361 }
class ____(AgentConnector): def __init__(self, ctx: ConnectorContext, states: Any = None): super().__init__(ctx) self._initial_states = ctx.initial_states self._action_space_struct = get_base_struct_from_space(ctx.action_space) self._states = defaultdict(lambda: defaultdict(lambda: (None, None, None))) self._enable_new_api_stack = False # TODO(jungong) : we would not need this if policies are never stashed # during the rollout of a single episode. if states: try: self._states = cloudpickle.loads(states) except pickle.UnpicklingError: # StateBufferConnector states are only needed for rare cases # like stashing then restoring a policy during the rollout of # a single episode. # It is ok to ignore the error for most of the cases here. logger.info( "Can not restore StateBufferConnector states. This warning can " "usually be ignore, unless it is from restoring a stashed policy." ) @override(Connector) def in_eval(self): super().in_eval() def reset(self, env_id: str): # States should not be carried over between episodes. if env_id in self._states: del self._states[env_id] def on_policy_output(self, ac_data: ActionConnectorDataType): # Buffer latest output states for next input __call__. self._states[ac_data.env_id][ac_data.agent_id] = ac_data.output 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]" env_id = ac_data.env_id agent_id = ac_data.agent_id assert ( env_id is not None and agent_id is not None ), f"StateBufferConnector requires env_id(f{env_id}) and agent_id(f{agent_id})" action, states, fetches = self._states[env_id][agent_id] if action is not None: d[SampleBatch.ACTIONS] = action # Last action else: # Default zero action. d[SampleBatch.ACTIONS] = tree.map_structure( lambda s: np.zeros_like(s.sample(), s.dtype) if hasattr(s, "dtype") else np.zeros_like(s.sample()), self._action_space_struct, ) if states is None: states = self._initial_states if self._enable_new_api_stack: if states: d[Columns.STATE_OUT] = states else: for i, v in enumerate(states): d["state_out_{}".format(i)] = v # Also add extra fetches if available. if fetches: d.update(fetches) return ac_data def to_state(self): # Note(jungong) : it is ok to use cloudpickle here for stats because: # 1. self._states may contain arbitary data objects, and will be hard # to serialize otherwise. # 2. seriazlized states are only useful if a policy is stashed and # restored during the rollout of a single episode. So it is ok to # use cloudpickle for such non-persistent data bits. states = cloudpickle.dumps(self._states) return StateBufferConnector.__name__, states @staticmethod def from_state(ctx: ConnectorContext, params: Any): return StateBufferConnector(ctx, params) register_connector(StateBufferConnector.__name__, StateBufferConnector)
StateBufferConnector
python
kamyu104__LeetCode-Solutions
Python/path-with-minimum-effort.py
{ "start": 2130, "end": 3199 }
class ____(object): def minimumEffortPath(self, heights): """ :type heights: List[List[int]] :rtype: int """ def index(n, i, j): return i*n + j diffs = [] for i in xrange(len(heights)): for j in xrange(len(heights[0])): if i > 0: diffs.append((abs(heights[i][j]-heights[i-1][j]), index(len(heights[0]), i-1, j), index(len(heights[0]), i, j))) if j > 0: diffs.append((abs(heights[i][j]-heights[i][j-1]), index(len(heights[0]), i, j-1), index(len(heights[0]), i, j))) diffs.sort() union_find = UnionFind(len(heights)*len(heights[0])) for d, i, j in diffs: if union_find.union_set(i, j): if union_find.find_set(index(len(heights[0]), 0, 0)) == \ union_find.find_set(index(len(heights[0]), len(heights)-1, len(heights[0])-1)): return d return 0 # Time: O(m * n * logh) # Space: O(m * n) # bi-bfs solution
Solution2
python
openai__openai-python
src/openai/types/beta/threads/file_citation_delta_annotation.py
{ "start": 451, "end": 873 }
class ____(BaseModel): index: int """The index of the annotation in the text content part.""" type: Literal["file_citation"] """Always `file_citation`.""" end_index: Optional[int] = None file_citation: Optional[FileCitation] = None start_index: Optional[int] = None text: Optional[str] = None """The text in the message content that needs to be replaced."""
FileCitationDeltaAnnotation
python
sympy__sympy
sympy/utilities/codegen.py
{ "start": 39217, "end": 39267 }
class ____(CCodeGen): standard = 'C89'
C89CodeGen
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 52963, "end": 57171 }
class ____(GoogleCloudBaseOperator): """ Gets an entry group. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataCatalogGetEntryGroupOperator` :param location: Required. The location of the entry group to get. :param entry_group: The ID of the entry group to get. :param read_mask: The fields to return. If not set or empty, all fields are returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.protobuf.field_mask_pb2.FieldMask` :param project_id: The ID of the Google Cloud project that owns the entry group. If set to ``None`` or missing, the default project_id from the Google Cloud connection is used. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: Optional, The connection ID used to connect to Google Cloud. Defaults to 'google_cloud_default'. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "location", "entry_group", "read_mask", "project_id", "retry", "timeout", "metadata", "gcp_conn_id", "impersonation_chain", ) operator_extra_links = (DataCatalogEntryGroupLink(),) def __init__( self, *, location: str, entry_group: str, read_mask: FieldMask, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.location = location self.entry_group = entry_group self.read_mask = read_mask self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context) -> dict: hook = CloudDataCatalogHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain ) result = hook.get_entry_group( location=self.location, entry_group=self.entry_group, read_mask=self.read_mask, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) DataCatalogEntryGroupLink.persist( context=context, entry_group_id=self.entry_group, location_id=self.location, project_id=self.project_id or hook.project_id, ) return EntryGroup.to_dict(result) @deprecated( planned_removal_date="January 30, 2026", use_instead="airflow.providers.google.cloud.operators.dataplex.DataplexCatalogGetAspectTypeOperator", reason="The Data Catalog will be discontinued on January 30, 2026 " "in favor of Dataplex Universal Catalog.", category=AirflowProviderDeprecationWarning, )
CloudDataCatalogGetEntryGroupOperator
python
openai__openai-python
src/openai/_types.py
{ "start": 3132, "end": 3404 }
class ____(TypedDict, total=False): headers: Headers max_retries: int timeout: float | Timeout | None params: Query extra_json: AnyMapping idempotency_key: str follow_redirects: bool # Sentinel class used until PEP 0661 is accepted
RequestOptions
python
doocs__leetcode
solution/2200-2299/2285.Maximum Total Importance of Roads/Solution.py
{ "start": 0, "end": 260 }
class ____: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: deg = [0] * n for a, b in roads: deg[a] += 1 deg[b] += 1 deg.sort() return sum(i * v for i, v in enumerate(deg, 1))
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_kubernetes_engine.py
{ "start": 3744, "end": 6275 }
class ____: @pytest.mark.parametrize( ( "use_dns_endpoint", "use_internal_ip", "endpoint", "private_endpoint", "dns_endpoint", "expected_cluster_url", ), [ ( False, False, GKE_CLUSTER_ENDPOINT, GKE_CLUSTER_PRIVATE_ENDPOINT, GKE_CLUSTER_DNS_ENDPOINT, GKE_CLUSTER_URL, ), ( False, True, GKE_CLUSTER_ENDPOINT, GKE_CLUSTER_PRIVATE_ENDPOINT, GKE_CLUSTER_DNS_ENDPOINT, GKE_CLUSTER_PRIVATE_URL, ), ( True, False, GKE_CLUSTER_ENDPOINT, GKE_CLUSTER_PRIVATE_ENDPOINT, GKE_CLUSTER_DNS_ENDPOINT, GKE_CLUSTER_DNS_URL, ), ( True, True, GKE_CLUSTER_ENDPOINT, GKE_CLUSTER_PRIVATE_ENDPOINT, GKE_CLUSTER_DNS_ENDPOINT, GKE_CLUSTER_DNS_URL, ), ], ) def test_fetch_cluster_info( self, use_dns_endpoint, use_internal_ip, endpoint, private_endpoint, dns_endpoint, expected_cluster_url, ): mock_cluster = mock.MagicMock( endpoint=endpoint, private_cluster_config=mock.MagicMock(private_endpoint=private_endpoint), control_plane_endpoints_config=mock.MagicMock( dns_endpoint_config=mock.MagicMock(endpoint=dns_endpoint) ), master_auth=mock.MagicMock(cluster_ca_certificate=GKE_SSL_CA_CERT), ) mock_cluster_hook = mock.MagicMock(get_cluster=mock.MagicMock(return_value=mock_cluster)) cluster_auth_details = GKEClusterAuthDetails( cluster_name=GKE_CLUSTER_NAME, project_id=TEST_PROJECT_ID, use_internal_ip=use_internal_ip, use_dns_endpoint=use_dns_endpoint, cluster_hook=mock_cluster_hook, ) cluster_url, ssl_ca_cert = cluster_auth_details.fetch_cluster_info() assert expected_cluster_url == cluster_url assert ssl_ca_cert == GKE_SSL_CA_CERT mock_cluster_hook.get_cluster.assert_called_once_with( name=GKE_CLUSTER_NAME, project_id=TEST_PROJECT_ID )
TestGKEClusterAuthDetails
python
pypa__setuptools
setuptools/warnings.py
{ "start": 3084, "end": 3420 }
class ____(SetuptoolsWarning): """Currently there is no clear way of displaying messages to the users that use the setuptools backend directly via ``pip``. The only thing that might work is a warning, although it is not the most appropriate tool for the job... See pypa/packaging-problems#558. """
InformationOnly
python
pytorch__pytorch
torch/_guards.py
{ "start": 40308, "end": 43828 }
class ____(Source): base: Source def is_dict_key(self) -> bool: # Recurse until you either hit a ConstDictKey or a Source return self.base.is_dict_key() def is_ephemeral(self) -> bool: return self.base.is_ephemeral() def get_base(self) -> Source: current: Source = self while isinstance(current, ChainedSource): current = current.base return current def detect_fake_mode(inputs: Any = None) -> Optional[FakeTensorMode]: """ Attempts to "detect" what the current fake mode is. If there is one ambiently available from TracingContext, we preferentially use that. Otherwise, we heuristically detect the fake mode via the following sources, in order of priority: - Currently active fake mode on stack - Fake mode associated with passed in tensors (inputs does not have to be flattened) """ from torch._subclasses.fake_tensor import ( FakeTensor, FakeTensorMode, get_plain_tensors, ) fake_modes = [] if context := TracingContext.try_get(): fake_mode = context.fake_mode if fake_mode is not None: fake_modes.append((fake_mode, "tracing context", 0)) from torch.utils._python_dispatch import _get_current_dispatch_mode_stack for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())): if isinstance(m, FakeTensorMode): # pyrefly: ignore [bad-argument-type] fake_modes.append((m, "active fake mode", i)) flat_inputs = pytree.tree_leaves(inputs) for i, flat_input in enumerate(flat_inputs): if isinstance(flat_input, FakeTensor): # pyrefly: ignore [bad-argument-type] fake_modes.append((flat_input.fake_mode, "fake tensor input", i)) if is_traceable_wrapper_subclass(flat_input): out: list[Union[torch.Tensor, int, torch.SymInt]] = [] get_plain_tensors(flat_input, out=out) # type: ignore[arg-type] fake_tensors: list[FakeTensor] = [ x for x in out if isinstance(x, FakeTensor) ] fake_modes.extend( # pyrefly: ignore [bad-argument-type] [ (tensor.fake_mode, f"subclass input {i}", ix) for ix, tensor in enumerate(fake_tensors) ] ) if fake_modes: fake_mode, desc1, i1 = fake_modes[0] for m, desc2, i2 in fake_modes[1:]: assert fake_mode is m, ( f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n" # pyrefly: ignore [missing-attribute] f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n" # pyrefly: ignore [missing-attribute] f"fake mode from {desc2} {i2} allocated at:\n{m.stack}" ) # pyrefly: ignore [bad-return] return fake_mode else: return None def active_fake_mode() -> Optional[FakeTensorMode]: """ Inspects the dispatch mode stack for an active fake mode and returns it. Returns None if no fake mode is active. """ from torch._subclasses.fake_tensor import FakeTensorMode from torch.utils._python_dispatch import _get_current_dispatch_mode_stack for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())): if isinstance(m, FakeTensorMode): return m return None
ChainedSource
python
qdrant__qdrant-client
qdrant_client/http/api_client.py
{ "start": 1284, "end": 2016 }
class ____(Generic[AsyncClientT]): def __init__(self, host: str, **kwargs: Any): self.client = AsyncApiClient(host, **kwargs) self.aliases_api = AsyncAliasesApi(self.client) self.beta_api = AsyncBetaApi(self.client) self.collections_api = AsyncCollectionsApi(self.client) self.distributed_api = AsyncDistributedApi(self.client) self.indexes_api = AsyncIndexesApi(self.client) self.points_api = AsyncPointsApi(self.client) self.search_api = AsyncSearchApi(self.client) self.service_api = AsyncServiceApi(self.client) self.snapshots_api = AsyncSnapshotsApi(self.client) async def aclose(self) -> None: await self.client.aclose()
AsyncApis
python
langchain-ai__langchain
libs/core/tests/unit_tests/output_parsers/test_openai_tools.py
{ "start": 22610, "end": 22683 }
class ____(BaseModel): age: int hair_color: str job: str
Person
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 140262, "end": 141897 }
class ____(test.TestCase): def _tf_reduce(self, x, reduction_axes, keepdims): raise NotImplementedError() def _np_reduce(self, x, reduction_axes, keepdims): raise NotImplementedError() def _makeIncremental(self, shape, dtype): data = np.arange(np.prod(shape)).reshape(shape).astype(dtype.as_numpy_dtype) if dtype.is_complex: data -= 2j * data return data def _makeRandom(self, shape, dtype): data = np.random.rand(*shape).astype(dtype.as_numpy_dtype) if dtype.is_complex: data -= 2j * data return data def _compareGradient(self, x, reduction_axes, rtol=1e-8, atol=1e-8): if reduction_axes is not None and np.shape(reduction_axes) == (1,): # Test scalar reduction_axes argument self._compareGradient(x, reduction_axes[0], rtol=rtol, atol=atol) with self.cached_session(use_gpu=True): t = ops.convert_to_tensor(x) su = self._tf_reduce(t, reduction_axes, False) jacob_t, jacob_n = gradient_checker.compute_gradient( t, x.shape, su, su.get_shape().as_list(), x_init_value=x, delta=1 ) self.assertAllClose(jacob_t, jacob_n, rtol=rtol, atol=atol) def _compareGradientAxes(self, x, rtol=1e-8, atol=1e-8): self._compareGradient(x, None, rtol=rtol, atol=atol) self._compareGradient(x, [], rtol=rtol, atol=atol) self._compareGradient(x, 0, rtol=rtol, atol=atol) self._compareGradient(x, [1], rtol=rtol, atol=atol) self._compareGradient(x, [2], rtol=rtol, atol=atol) self._compareGradient(x, [1, 2], rtol=rtol, atol=atol) self._compareGradient(x, [0, 1, 2, 3], rtol=rtol, atol=atol)
BaseReductionTest
python
pytorch__pytorch
torch/_dynamo/debug_utils.py
{ "start": 4534, "end": 11074 }
class ____: safe_reprs = [ torch.nn.Linear, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d, torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.LayerNorm, torch.nn.Dropout, torch.nn.Softmax, torch.nn.ReLU, torch.nn.GELU, torch.nn.Identity, torch.nn.MaxPool2d, torch.nn.Embedding, torch.nn.Tanh, torch.nn.ConvTranspose1d, torch.nn.GLU, torch.nn.LSTM, torch.nn.Flatten, torch.nn.AdaptiveAvgPool2d, ] @staticmethod def can_convert_to_string(gm: torch.fx.GraphModule) -> bool: cant_convert = set() for _, module in gm.named_children(): if type(module) not in NNModuleToString.safe_reprs: cant_convert.add(module) if len(cant_convert) > 0: log.warning("We have not tested reprs of some modules - %s", cant_convert) # TODO - Assuming that all modules can be safely repr'd. Check if that assumption is correct. return True @staticmethod def convert(gm: torch.fx.GraphModule) -> str: from torch.nn.modules.module import _addindent tab = " " * 4 model_str = textwrap.dedent( """ from torch.nn import * class Repro(torch.nn.Module): def __init__(self) -> None: super().__init__() """ ) for module_name, module in gm.named_children(): module_str = f"{module.__repr__()}" # module should be a core torch.nn.Module, so all parameters # should be on the same device. example_param = next(module.parameters(), None) if example_param is not None and example_param.is_cuda: module_str = f"{module_str}.cuda()" model_str += f"{tab * 2}self.{module_name} = {module_str}\n" for buffer_name, buffer in gm._buffers.items(): if buffer is None: continue # Serialize full data for small buffers if buffer.numel() <= MAX_CONSTANT_NUMEL_INLINE: from torch._tensor_str import PRINT_OPTS assert PRINT_OPTS.threshold >= MAX_CONSTANT_NUMEL_INLINE tensor_str = repr(buffer) elif torch.is_floating_point(buffer): tensor_str = f"torch.randn({list(buffer.shape)}, dtype={buffer.dtype})" else: tensor_str = ( f"torch.randint(1, size={list(buffer.shape)}, dtype={buffer.dtype})" ) if buffer.is_cuda: tensor_str = f"{tensor_str}.cuda()" model_str += ( f"{tab * 2}self.register_buffer('{buffer_name}', {tensor_str})\n" ) for param_name, param in gm._parameters.items(): if param is None: continue maybe_device = "" if param.is_cuda: maybe_device = ', device="cuda"' tensor_str = f"torch.nn.Parameter(torch.randn({list(param.shape)}, dtype={param.dtype}{maybe_device}))" model_str += f"{tab * 2}self.{param_name} = {tensor_str}\n" # TODO - Keep this code for now. But, I don't think we will need this. # attrs = dir(gm) # for attr in attrs: # if "_tensor_constant" in attr: # val = getattr(gm, attr) # model_str += f" {attr} = {val!r}\n" model_str += f"{_addindent(gm.code, 4)}\n" return model_str @functools.cache # subprocess is expensive def _cuda_system_info_comment() -> str: if not torch.cuda.is_available(): return "# torch.cuda.is_available()==False, no GPU info collected\n" model_str = "# CUDA Info: \n" try: cuda_version_out = subprocess.check_output(["nvcc", "--version"]) cuda_version_lines = cuda_version_out.decode().split("\n") comment = "".join([f"# {s} \n" for s in cuda_version_lines if s != ""]) model_str += f"{comment}\n" except (FileNotFoundError, subprocess.CalledProcessError): model_str += "# nvcc not found\n" gpu_names = Counter( torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) ) model_str += "# GPU Hardware Info: \n" for name, count in gpu_names.items(): model_str += f"# {name} : {count} \n" model_str += "\n" return model_str def generate_env_vars_string(*, stable_output: bool = False) -> str: """ Generate a string configuration for environment variables related to Dynamo, Inductor, and Triton. """ if stable_output: return "# env var omitted due to stable_output=True" allow_list = ["TORCH", "DYNAMO", "INDUCTOR", "TRITON"] skip_list = ["TRITON_LIBDEVICE_PATH", "TRITON_PTXAS_PATH", "TRITON_LIBCUDA_PATH"] def filter(key: str) -> bool: return any(string in key for string in allow_list) and key not in skip_list config_lines = [ f"os.environ['{key}'] = '{value}'" for key, value in os.environ.items() if filter(key) ] config_string = "\n".join(config_lines) return normalize_path_separator(f"""\ import os {config_string} """) def generate_config_string(*, stable_output: bool = False) -> str: import torch._functorch.config import torch._inductor.config if stable_output: return "# config omitted due to stable_output=True" experimental_config = torch.fx.experimental._config.codegen_config() # type: ignore[attr-defined] return f"""\ import torch._dynamo.config import torch._inductor.config import torch._functorch.config import torch.fx.experimental._config {torch._dynamo.config.codegen_config()} {torch._inductor.config.codegen_config()} {torch._functorch.config.codegen_config()} {experimental_config} """ def get_minifier_repro_path() -> str: return os.path.join(minifier_dir(), "minifier_launcher.py") def helper_for_dump_minify(contents: str) -> None: minified_repro_path = get_minifier_repro_path() log.warning("Writing minified repro to:\n%s", minified_repro_path) if use_buck: BuckTargetWriter(minified_repro_path).write() try: with open(minified_repro_path, "w") as fd: fd.write(contents) except OSError as e: log.exception("") raise NotImplementedError(f"Could not write to {minified_repro_path}") from e
NNModuleToString
python
getsentry__sentry
src/sentry/api/serializers/models/project_template.py
{ "start": 832, "end": 2496 }
class ____(Serializer): def __init__(self, expand: Iterable[ProjectTemplateAttributes] | None = None) -> None: self.expand = expand def _expand(self, key: ProjectTemplateAttributes) -> bool: return self.expand is not None and key in self.expand def get_attrs( self, item_list: Sequence[ProjectTemplate], user: User | RpcUser | AnonymousUser, **kwargs: Any, ): attrs = super().get_attrs(item_list, user, **kwargs) all_attrs: dict[ProjectTemplate, dict[ProjectTemplateAttributes, Any]] = defaultdict(dict) for template in item_list: all_attrs[template] = attrs.get(template, {}) if self._expand(ProjectTemplateAttributes.OPTIONS): for template in item_list: options = template.options.all() serialized_options: TProjectOptions = { option.key: option.value for option in options } all_attrs[template][ProjectTemplateAttributes.OPTIONS] = serialized_options return all_attrs def serialize( self, obj: ProjectTemplate, attrs: Mapping[str, Any], user: User | RpcUser | AnonymousUser, **kwargs: Any, ) -> SerializedProjectTemplate: response: SerializedProjectTemplate = { "id": obj.id, "name": obj.name, "createdAt": obj.date_added, "updatedAt": obj.date_updated, } if (options := attrs.get(ProjectTemplateAttributes.OPTIONS)) is not None: response["options"] = options return response
ProjectTemplateSerializer
python
django__django
django/contrib/gis/gdal/driver.py
{ "start": 309, "end": 3154 }
class ____(GDALBase): """ Wrap a GDAL/OGR Data Source Driver. For more information, see the C API documentation: https://gdal.org/api/vector_c_api.html https://gdal.org/api/raster_c_api.html """ # Case-insensitive aliases for some GDAL/OGR Drivers. # For a complete list of original driver names see # https://gdal.org/drivers/vector/ # https://gdal.org/drivers/raster/ _alias = { # vector "esri": "ESRI Shapefile", "shp": "ESRI Shapefile", "shape": "ESRI Shapefile", # raster "tiff": "GTiff", "tif": "GTiff", "jpeg": "JPEG", "jpg": "JPEG", } if GDAL_VERSION[:2] <= (3, 10): _alias.update( { "tiger": "TIGER", "tiger/line": "TIGER", } ) def __init__(self, dr_input): """ Initialize an GDAL/OGR driver on either a string or integer input. """ if isinstance(dr_input, str): # If a string name of the driver was passed in self.ensure_registered() # Checking the alias dictionary (case-insensitive) to see if an # alias exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the GDAL/OGR driver by the string name. driver = c_void_p(capi.get_driver_by_name(force_bytes(name))) elif isinstance(dr_input, int): self.ensure_registered() driver = capi.get_driver(dr_input) elif isinstance(dr_input, c_void_p): driver = dr_input else: raise GDALException( "Unrecognized input type for GDAL/OGR Driver: %s" % type(dr_input) ) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException( "Could not initialize GDAL/OGR Driver on input: %s" % dr_input ) self.ptr = driver def __str__(self): return self.name @classmethod def ensure_registered(cls): """ Attempt to register all the data source drivers. """ # Only register all if the driver count is 0 (or else all drivers will # be registered over and over again). if not capi.get_driver_count(): capi.register_all() @classmethod def driver_count(cls): """ Return the number of GDAL/OGR data source drivers registered. """ return capi.get_driver_count() @property def name(self): """ Return description/name string for this driver. """ return force_str(capi.get_driver_description(self.ptr))
Driver
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 3230, "end": 5334 }
class ____(BaseModelOutputWithCrossAttentions): r""" hidden_states (`tuple(torch.FloatTensor)`, *optional*): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. Returned when `output_hidden_states=True`. attentions (`tuple(torch.FloatTensor)`, *optional*): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Returned when `output_attentions=True`. masks_queries_logits (`tuple(torch.FloatTensor)` of shape `(batch_size, num_queries, height, width)`): Tuple of mask predictions from all layers of the transformer decoder. intermediate_hidden_states (`tuple(torch.FloatTensor)` of shape `(num_queries, 1, hidden_size)`): Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a layernorm. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor]] = None attentions: Optional[torch.FloatTensor] = None masks_queries_logits: Optional[tuple[torch.FloatTensor]] = None intermediate_hidden_states: Optional[tuple[torch.FloatTensor]] = None @dataclass @auto_docstring( custom_intro=""" Mask2Former's pixel level module output. It returns the output of the encoder (optional) and all hidden states (multi-scale features) from the `decoder`. By default, the `encoder` is a Swin Backbone and the `decoder` is a Multi-Scale Deformable Attention based decoder. The `decoder_last_hidden_state` are the **per-pixel embeddings** while `decoder_hidden_states` refer to multi-scale feature maps produced using **multi-scaling strategy** defined in the paper. """ )
Mask2FormerMaskedAttentionDecoderOutput
python
google__pytype
pytype/pattern_matching.py
{ "start": 7888, "end": 9137 }
class ____: """Tracks branches of match statements.""" def __init__(self, ast_matches): self.start_to_end = {} # match_line : match_end_line self.end_to_starts = collections.defaultdict(list) self.match_cases = {} # opcode_line : match_line self.defaults = set() # lines with defaults self.as_names = {} # case_end_line : case_as_name self.unseen_cases = {} # match_line : {unseen_cases} for m in ast_matches.matches: self._add_match(m.start, m.end, m.cases) def _add_match(self, start, end, cases): self.start_to_end[start] = end self.end_to_starts[end].append(start) self.unseen_cases[start] = {c.start for c in cases} for c in cases: for i in range(c.start, c.end + 1): self.match_cases[i] = start if c.is_underscore: self.defaults.add(c.start) if c.as_name: self.as_names[c.end] = c.as_name def register_case(self, match_line, case_line): assert self.match_cases[case_line] == match_line self.unseen_cases[match_line].discard(case_line) def __repr__(self): return f""" Matches: {sorted(self.start_to_end.items())} Cases: {self.match_cases} Defaults: {self.defaults} """ @dataclasses.dataclass
_Matches
python
cython__cython
Cython/Tests/TestCythonUtils.py
{ "start": 383, "end": 471 }
class ____: @cached_method def cached_next(self, x): return next(x)
Cached
python
ray-project__ray
python/ray/serve/_private/application_state.py
{ "start": 7679, "end": 44357 }
class ____: """Manage single application states with all operations""" def __init__( self, name: str, deployment_state_manager: DeploymentStateManager, autoscaling_state_manager: AutoscalingStateManager, endpoint_state: EndpointState, logging_config: LoggingConfig, external_scaler_enabled: bool, ): """ Initialize an ApplicationState instance. Args: name: Application name. deployment_state_manager: Manages the state of all deployments in the cluster. autoscaling_state_manager: Manages autoscaling decisions in the cluster. endpoint_state: Manages endpoints in the system. logging_config: Logging configuration schema. external_scaler_enabled: Whether external autoscaling is enabled for this application. """ self._name = name self._status_msg = "" self._deployment_state_manager = deployment_state_manager self._autoscaling_state_manager = autoscaling_state_manager self._endpoint_state = endpoint_state self._route_prefix: Optional[str] = None self._ingress_deployment_name: Optional[str] = None self._status: ApplicationStatus = ApplicationStatus.DEPLOYING self._deployment_timestamp = time.time() self._build_app_task_info: Optional[BuildAppTaskInfo] = None # Before a deploy app task finishes, we don't know what the # target deployments are, so set deployment_infos=None self._target_state: ApplicationTargetState = ApplicationTargetState( deployment_infos=None, code_version=None, config=None, target_capacity=None, target_capacity_direction=None, deleting=False, api_type=APIType.UNKNOWN, external_scaler_enabled=external_scaler_enabled, serialized_application_autoscaling_policy_def=None, ) self._logging_config = logging_config @property def route_prefix(self) -> Optional[str]: return self._route_prefix @property def external_scaler_enabled(self) -> bool: return self._target_state.external_scaler_enabled @property def docs_path(self) -> Optional[str]: # get the docs path from the running deployments # we are making an assumption that the docs path can only be set # on ingress deployments with fastapi. ingress_deployment = DeploymentID(self._ingress_deployment_name, self._name) return self._deployment_state_manager.get_deployment_docs_path( ingress_deployment ) @property def status(self) -> ApplicationStatus: """Status of the application. DEPLOYING: The build task is still running, or the deployments have started deploying but aren't healthy yet. RUNNING: All deployments are healthy. DEPLOY_FAILED: The build task failed or one or more deployments became unhealthy in the process of deploying UNHEALTHY: While the application was running, one or more deployments transition from healthy to unhealthy. DELETING: Application and its deployments are being deleted. """ return self._status @property def deployment_timestamp(self) -> float: return self._deployment_timestamp @property def target_deployments(self) -> List[str]: """List of target deployment names in application.""" if self._target_state.deployment_infos is None: return [] return list(self._target_state.deployment_infos.keys()) @property def ingress_deployment(self) -> Optional[str]: return self._ingress_deployment_name @property def api_type(self) -> APIType: return self._target_state.api_type def recover_target_state_from_checkpoint( self, checkpoint_data: ApplicationTargetState ): logger.info( f"Recovering target state for application '{self._name}' from checkpoint." ) self._set_target_state( checkpoint_data.deployment_infos, api_type=checkpoint_data.api_type, code_version=checkpoint_data.code_version, target_config=checkpoint_data.config, target_capacity=checkpoint_data.target_capacity, target_capacity_direction=checkpoint_data.target_capacity_direction, deleting=checkpoint_data.deleting, external_scaler_enabled=checkpoint_data.external_scaler_enabled, ) # Restore route prefix and docs path from checkpointed deployments when # the imperatively started application is restarting with controller. if checkpoint_data.deployment_infos is not None: self._route_prefix = self._check_routes(checkpoint_data.deployment_infos) # Restore app-level autoscaling policy from checkpoint if ( checkpoint_data.config and checkpoint_data.config.autoscaling_policy is not None ): self._autoscaling_state_manager.register_application( self._name, AutoscalingPolicy( _serialized_policy_def=checkpoint_data.serialized_application_autoscaling_policy_def, **checkpoint_data.config.autoscaling_policy, ), ) def _set_target_state( self, deployment_infos: Optional[Dict[str, DeploymentInfo]], *, api_type: APIType, code_version: Optional[str], target_config: Optional[ServeApplicationSchema], target_capacity: Optional[float] = None, target_capacity_direction: Optional[TargetCapacityDirection] = None, deleting: bool = False, external_scaler_enabled: bool = False, serialized_application_autoscaling_policy_def: Optional[bytes] = None, ): """Set application target state. While waiting for build task to finish, this should be (None, False) When build task has finished and during normal operation, this should be (target_deployments, False) When a request to delete the application has been received, this should be ({}, True) """ if deleting: self._update_status(ApplicationStatus.DELETING) else: self._update_status(ApplicationStatus.DEPLOYING) if deployment_infos is None: self._ingress_deployment_name = None else: for name, info in deployment_infos.items(): if info.ingress: self._ingress_deployment_name = name target_state = ApplicationTargetState( deployment_infos, code_version, target_config, target_capacity, target_capacity_direction, deleting, api_type=api_type, external_scaler_enabled=external_scaler_enabled, serialized_application_autoscaling_policy_def=serialized_application_autoscaling_policy_def, ) self._target_state = target_state def _set_target_state_deleting(self): """Set target state to deleting. Wipes the target deployment infos, code version, and config. """ self._set_target_state( deployment_infos={}, api_type=self._target_state.api_type, code_version=None, target_config=None, deleting=True, external_scaler_enabled=self.external_scaler_enabled, ) def _clear_target_state_and_store_config( self, target_config: Optional[ServeApplicationSchema], ): """Clears the target state and stores the config. NOTE: this currently assumes that this method is *only* called when managing apps deployed with the declarative API. """ self._set_target_state( deployment_infos=None, api_type=APIType.DECLARATIVE, code_version=None, target_config=target_config, deleting=False, external_scaler_enabled=target_config.external_scaler_enabled if target_config else False, ) def _delete_deployment(self, name: str) -> bool: """Delete a deployment in the application. Args: name: The name of the deployment to delete. Returns: Whether the target state has changed. """ id = DeploymentID(name=name, app_name=self._name) self._endpoint_state.delete_endpoint(id) return self._deployment_state_manager.delete_deployment(id) def delete(self): """Delete the application""" if self._status != ApplicationStatus.DELETING: logger.info( f"Deleting app '{self._name}'.", extra={"log_to_stderr": False}, ) self._set_target_state_deleting() def is_deleted(self) -> bool: """Check whether the application is already deleted. For an application to be considered deleted, the target state has to be set to deleting and all deployments have to be deleted. """ return self._target_state.deleting and len(self._get_live_deployments()) == 0 def should_autoscale(self) -> bool: """Determine if autoscaling is enabled for the application. Returns: Autoscaling is enabled for the application if any of the deployments have autoscaling enabled. """ return self._autoscaling_state_manager.should_autoscale_application(self._name) def autoscale(self) -> bool: """ Apply the autoscaling decisions for the application. If the application has deployment-level autoscaling, it will apply the autoscaling decisions for each deployment. Returns: True if there is a change to number of replicas for any deployment. False otherwise. """ target_deployments = self.target_deployments if len(target_deployments) == 0: return False deployment_to_target_num_replicas: Dict[DeploymentID, int] = {} for deployment_name in target_deployments: deployment_id = DeploymentID(name=deployment_name, app_name=self._name) target_num_replicas = ( self._deployment_state_manager.get_deployment_target_num_replicas( deployment_id ) ) if target_num_replicas is None: continue deployment_to_target_num_replicas[deployment_id] = target_num_replicas if len(deployment_to_target_num_replicas) == 0: return False decisions: Dict[ DeploymentID, int ] = self._autoscaling_state_manager.get_decision_num_replicas( self._name, deployment_to_target_num_replicas ) target_state_changed = False for deployment_id, decision_num_replicas in decisions.items(): target_state_changed = ( self._deployment_state_manager.autoscale( deployment_id, decision_num_replicas ) or target_state_changed ) return target_state_changed def apply_deployment_info( self, deployment_name: str, deployment_info: DeploymentInfo, ) -> bool: """Deploys a deployment in the application. Args: deployment_name: The name of the deployment to apply. deployment_info: The deployment info to apply. Returns: Whether the target state has changed. """ route_prefix = deployment_info.route_prefix if route_prefix is not None and not route_prefix.startswith("/"): raise RayServeException( f'Invalid route prefix "{route_prefix}", it must start with "/"' ) deployment_id = DeploymentID(name=deployment_name, app_name=self._name) target_state_changed = self._deployment_state_manager.deploy( deployment_id, deployment_info ) if deployment_info.route_prefix is not None: config = deployment_info.deployment_config # Try to get route_patterns from deployment state first (most up-to-date), # otherwise fall back to existing endpoint patterns route_patterns = ( self._deployment_state_manager.get_deployment_route_patterns( deployment_id ) ) self._endpoint_state.update_endpoint( deployment_id, # The current meaning of the "is_cross_language" field is ambiguous. # We will work on optimizing and removing this field in the future. # Instead of using the "is_cross_language" field, we will directly # compare if the replica is Python, which will assist the Python # router in determining if the replica invocation is a cross-language # operation. EndpointInfo( route=deployment_info.route_prefix, app_is_cross_language=config.deployment_language != DeploymentLanguage.PYTHON, route_patterns=route_patterns, ), ) else: self._endpoint_state.delete_endpoint(deployment_id) return target_state_changed def deploy_app( self, deployment_infos: Dict[str, DeploymentInfo], external_scaler_enabled: bool, ): """(Re-)deploy the application from list of deployment infos. This function should only be called to deploy an app from an imperative API (i.e., `serve.run` or Java API). Raises: RayServeException if there is more than one route prefix or docs path. """ # Check routes are unique in deployment infos self._route_prefix = self._check_routes(deployment_infos) self._set_target_state( deployment_infos=deployment_infos, api_type=APIType.IMPERATIVE, code_version=None, target_config=None, target_capacity=None, target_capacity_direction=None, external_scaler_enabled=external_scaler_enabled, ) def apply_app_config( self, config: ServeApplicationSchema, target_capacity: Optional[float], target_capacity_direction: Optional[TargetCapacityDirection], deployment_time: float, ) -> None: """Apply the config to the application. If the code version matches that of the current live deployments then it only applies the updated config to the deployment state manager. If the code version doesn't match, this will re-build the application. This function should only be called to (re-)deploy an app from the declarative API (i.e., through the REST API). """ self._deployment_timestamp = deployment_time config_version = get_app_code_version(config) if config_version == self._target_state.code_version: try: overrided_infos = override_deployment_info( self._target_state.deployment_infos, config, ) self._route_prefix = self._check_routes(overrided_infos) self._set_target_state( # Code version doesn't change. code_version=self._target_state.code_version, api_type=APIType.DECLARATIVE, # Everything else must reflect the new config. deployment_infos=overrided_infos, target_config=config, target_capacity=target_capacity, target_capacity_direction=target_capacity_direction, external_scaler_enabled=config.external_scaler_enabled, ) except (TypeError, ValueError, RayServeException): self._clear_target_state_and_store_config(config) self._update_status( ApplicationStatus.DEPLOY_FAILED, traceback.format_exc() ) except Exception: self._clear_target_state_and_store_config(config) self._update_status( ApplicationStatus.DEPLOY_FAILED, ( f"Unexpected error occurred while applying config for " f"application '{self._name}': \n{traceback.format_exc()}" ), ) else: # If there is an in progress build task, cancel it. if self._build_app_task_info and not self._build_app_task_info.finished: logger.info( f"Received new config for application '{self._name}'. " "Cancelling previous request." ) ray.cancel(self._build_app_task_info.obj_ref) # Halt reconciliation of target deployments. A new target state # will be set once the new app has finished building. self._clear_target_state_and_store_config(config) # Record telemetry for container runtime env feature if self._target_state.config.runtime_env.get( "container" ) or self._target_state.config.runtime_env.get("image_uri"): ServeUsageTag.APP_CONTAINER_RUNTIME_ENV_USED.record("1") if isinstance(config.autoscaling_policy, dict): application_autoscaling_policy_function = config.autoscaling_policy.get( "policy_function" ) else: application_autoscaling_policy_function = None deployment_to_autoscaling_policy_function = { deployment.name: deployment.autoscaling_config.get("policy", {}).get( "policy_function", DEFAULT_AUTOSCALING_POLICY_NAME ) for deployment in config.deployments if isinstance(deployment.autoscaling_config, dict) } deployment_to_request_router_cls = { deployment.name: deployment.request_router_config.get( "request_router_class", DEFAULT_REQUEST_ROUTER_PATH ) for deployment in config.deployments if isinstance(deployment.request_router_config, dict) } # Kick off new build app task logger.info(f"Importing and building app '{self._name}'.") build_app_obj_ref = build_serve_application.options( runtime_env=config.runtime_env, enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, ).remote( config.import_path, config_version, config.name, config.args, self._logging_config, application_autoscaling_policy_function, deployment_to_autoscaling_policy_function, deployment_to_request_router_cls, ) self._build_app_task_info = BuildAppTaskInfo( obj_ref=build_app_obj_ref, code_version=config_version, config=config, target_capacity=target_capacity, target_capacity_direction=target_capacity_direction, finished=False, ) def _get_live_deployments(self) -> List[str]: return self._deployment_state_manager.get_deployments_in_application(self._name) def _determine_app_status(self) -> Tuple[ApplicationStatus, str]: """Check deployment statuses and target state, and determine the corresponding application status. Returns: Status (ApplicationStatus): RUNNING: all deployments are healthy or autoscaling. DEPLOYING: there is one or more updating deployments, and there are no unhealthy deployments. DEPLOY_FAILED: one or more deployments became unhealthy while the application was deploying. UNHEALTHY: one or more deployments became unhealthy while the application was running. DELETING: the application is being deleted. Error message (str): Non-empty string if status is DEPLOY_FAILED or UNHEALTHY """ if self._target_state.deleting: return ApplicationStatus.DELETING, "" # Get the lowest rank, i.e. highest priority, deployment status info object # The deployment status info with highest priority determines the corresponding # application status to set. deployment_statuses = self.get_deployments_statuses() lowest_rank_status = min(deployment_statuses, key=lambda info: info.rank) if lowest_rank_status.status == DeploymentStatus.DEPLOY_FAILED: failed_deployments = [ s.name for s in deployment_statuses if s.status == DeploymentStatus.DEPLOY_FAILED ] return ( ApplicationStatus.DEPLOY_FAILED, f"Failed to update the deployments {failed_deployments}.", ) elif lowest_rank_status.status == DeploymentStatus.UNHEALTHY: unhealthy_deployment_names = [ s.name for s in deployment_statuses if s.status == DeploymentStatus.UNHEALTHY ] return ( ApplicationStatus.UNHEALTHY, f"The deployments {unhealthy_deployment_names} are UNHEALTHY.", ) elif lowest_rank_status.status == DeploymentStatus.UPDATING: return ApplicationStatus.DEPLOYING, "" elif ( lowest_rank_status.status in [DeploymentStatus.UPSCALING, DeploymentStatus.DOWNSCALING] and lowest_rank_status.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED ): return ApplicationStatus.DEPLOYING, "" else: return ApplicationStatus.RUNNING, "" def _reconcile_build_app_task( self, ) -> Tuple[Optional[bytes], Optional[Dict], BuildAppStatus, str]: """If necessary, reconcile the in-progress build task. Returns: Serialized application autoscaling policy def (bytes): The serialized application autoscaling policy def returned from the build app task if it was built successfully, otherwise None. Deploy arguments (Dict[str, DeploymentInfo]): The deploy arguments returned from the build app task and their code version. Status (BuildAppStatus): NO_TASK_IN_PROGRESS: There is no build task to reconcile. SUCCEEDED: Task finished successfully. FAILED: An error occurred during execution of build app task IN_PROGRESS: Task hasn't finished yet. Error message (str): Non-empty string if status is DEPLOY_FAILED or UNHEALTHY """ if self._build_app_task_info is None or self._build_app_task_info.finished: return None, None, BuildAppStatus.NO_TASK_IN_PROGRESS, "" if not check_obj_ref_ready_nowait(self._build_app_task_info.obj_ref): return None, None, BuildAppStatus.IN_PROGRESS, "" # Retrieve build app task result self._build_app_task_info.finished = True try: serialized_application_autoscaling_policy_def, args, err = ray.get( self._build_app_task_info.obj_ref ) if err is None: logger.info(f"Imported and built app '{self._name}' successfully.") else: return ( None, None, BuildAppStatus.FAILED, f"Deploying app '{self._name}' failed with exception:\n{err}", ) except RuntimeEnvSetupError: error_msg = ( f"Runtime env setup for app '{self._name}' failed:\n" + traceback.format_exc() ) return None, None, BuildAppStatus.FAILED, error_msg except Exception: error_msg = ( f"Unexpected error occurred while deploying application " f"'{self._name}': \n{traceback.format_exc()}" ) return None, None, BuildAppStatus.FAILED, error_msg # Convert serialized deployment args (returned by build app task) # to deployment infos and apply option overrides from config try: deployment_infos = { params["deployment_name"]: deploy_args_to_deployment_info( **params, app_name=self._name ) for params in args } deployment_to_serialized_autoscaling_policy_def = { params["deployment_name"]: params["serialized_autoscaling_policy_def"] for params in args if params["serialized_autoscaling_policy_def"] is not None } deployment_to_serialized_request_router_cls = { params["deployment_name"]: params["serialized_request_router_cls"] for params in args if params["serialized_request_router_cls"] is not None } overrided_infos = override_deployment_info( deployment_infos, self._build_app_task_info.config, deployment_to_serialized_autoscaling_policy_def, deployment_to_serialized_request_router_cls, ) self._route_prefix = self._check_routes(overrided_infos) return ( serialized_application_autoscaling_policy_def, overrided_infos, BuildAppStatus.SUCCEEDED, "", ) except (TypeError, ValueError, RayServeException): return None, None, BuildAppStatus.FAILED, traceback.format_exc() except Exception: error_msg = ( f"Unexpected error occurred while applying config for application " f"'{self._name}': \n{traceback.format_exc()}" ) return None, None, BuildAppStatus.FAILED, error_msg def _check_routes( self, deployment_infos: Dict[str, DeploymentInfo] ) -> Tuple[str, str]: """Check route prefixes of deployments in app. There should only be one non-null route prefix. If there is one, set it as the application route prefix. This function must be run every control loop iteration because the target config could be updated without kicking off a new task. Returns: route prefix. Raises: RayServeException if more than one route prefix is found among deployments. """ num_route_prefixes = 0 route_prefix = None for info in deployment_infos.values(): # Update route prefix of application, which may be updated # through a redeployed config. if info.route_prefix is not None: route_prefix = info.route_prefix num_route_prefixes += 1 if num_route_prefixes > 1: raise RayServeException( f'Found multiple route prefixes from application "{self._name}",' " Please specify only one route prefix for the application " "to avoid this issue." ) return route_prefix def _reconcile_target_deployments(self) -> None: """Reconcile target deployments in application target state. Ensure each deployment is running on up-to-date info, and remove outdated deployments from the application. """ target_state_changed = False # Set target state for each deployment for deployment_name, info in self._target_state.deployment_infos.items(): deploy_info = deepcopy(info) # Apply the target capacity information to the deployment info. deploy_info.set_target_capacity( new_target_capacity=self._target_state.target_capacity, new_target_capacity_direction=( self._target_state.target_capacity_direction ), ) # Apply the application logging config to the deployment logging config # if it is not set. if ( self._target_state.config and self._target_state.config.logging_config and deploy_info.deployment_config.logging_config is None ): deploy_info.deployment_config.logging_config = ( self._target_state.config.logging_config ) target_state_changed = ( self.apply_deployment_info(deployment_name, deploy_info) or target_state_changed ) # Delete outdated deployments for deployment_name in self._get_live_deployments(): if deployment_name not in self.target_deployments: target_state_changed = ( self._delete_deployment(deployment_name) or target_state_changed ) return target_state_changed def get_deployment_topology(self) -> Optional[DeploymentTopology]: """Get the deployment topology for this application. Returns: The deployment topology, or None if not yet built. """ if not self.target_deployments: return None nodes = {} # Using target deployments because we wish to build best effort topology based on current state. for deployment_name in self.target_deployments: deployment_id = DeploymentID(name=deployment_name, app_name=self._name) # Get outbound deployment names from deployment state outbound_deployment = ( self._deployment_state_manager.get_deployment_outbound_deployments( deployment_id ) ) or [] # Create node for this deployment node = DeploymentNode( name=deployment_name, app_name=self._name, outbound_deployments=[ {"name": dep.name, "app_name": dep.app_name} for dep in outbound_deployment ], is_ingress=(deployment_name == self._ingress_deployment_name), ) nodes[deployment_name] = node return DeploymentTopology( app_name=self._name, ingress_deployment=self._ingress_deployment_name, nodes=nodes, ) def update(self) -> Tuple[bool, bool]: """Attempts to reconcile this application to match its target state. Updates the application status and status message based on the current state of the system. Returns: Whether the target state has changed. """ target_state_changed = False # If the application is being deleted, ignore any build task results to # avoid flipping the state back to DEPLOYING/RUNNING. if not self._target_state.deleting: ( serialized_application_autoscaling_policy_def, infos, task_status, msg, ) = self._reconcile_build_app_task() if task_status == BuildAppStatus.SUCCEEDED: target_state_changed = True self._set_target_state( deployment_infos=infos, code_version=self._build_app_task_info.code_version, api_type=self._target_state.api_type, target_config=self._build_app_task_info.config, target_capacity=self._build_app_task_info.target_capacity, target_capacity_direction=( self._build_app_task_info.target_capacity_direction ), external_scaler_enabled=self._target_state.external_scaler_enabled, serialized_application_autoscaling_policy_def=serialized_application_autoscaling_policy_def, ) # Handling the case where the user turns off/turns on app-level autoscaling policy, # between app deployment. if ( self._target_state.config is not None and self._target_state.config.autoscaling_policy is not None ): self._autoscaling_state_manager.register_application( self._name, AutoscalingPolicy( _serialized_policy_def=serialized_application_autoscaling_policy_def, **self._target_state.config.autoscaling_policy, ), ) else: self._autoscaling_state_manager.deregister_application(self._name) elif task_status == BuildAppStatus.FAILED: self._update_status(ApplicationStatus.DEPLOY_FAILED, msg) # Only reconcile deployments when the build app task is finished. If # it's not finished, we don't know what the target list of deployments # is, so we don't perform any reconciliation. if self._target_state.deployment_infos is not None: target_state_changed = ( self._reconcile_target_deployments() or target_state_changed ) status, status_msg = self._determine_app_status() self._update_status(status, status_msg) # Check if app is ready to be deleted if self._target_state.deleting: return self.is_deleted(), target_state_changed return False, target_state_changed def get_checkpoint_data(self) -> ApplicationTargetState: return self._target_state def get_deployments_statuses(self) -> List[DeploymentStatusInfo]: """Return all deployment status information""" deployments = [ DeploymentID(name=deployment, app_name=self._name) for deployment in self.target_deployments ] return self._deployment_state_manager.get_deployment_statuses(deployments) def get_application_status_info(self) -> ApplicationStatusInfo: """Return the application status information""" return ApplicationStatusInfo( self._status, message=self._status_msg, deployment_timestamp=self._deployment_timestamp, ) def list_deployment_details(self) -> Dict[str, DeploymentDetails]: """Gets detailed info on all live deployments in this application. (Does not include deleted deployments.) Returns: A dictionary of deployment infos. The set of deployment info returned may not be the full list of deployments that are part of the application. This can happen when the application is still deploying and bringing up deployments, or when the application is deleting and some deployments have been deleted. """ details = { deployment_name: self._deployment_state_manager.get_deployment_details( DeploymentID(name=deployment_name, app_name=self._name) ) for deployment_name in self.target_deployments } return {k: v for k, v in details.items() if v is not None} def _update_status(self, status: ApplicationStatus, status_msg: str = "") -> None: if ( status_msg and status in [ ApplicationStatus.DEPLOY_FAILED, ApplicationStatus.UNHEALTHY, ] and status_msg != self._status_msg ): logger.error(status_msg) self._status = status self._status_msg = status_msg
ApplicationState
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/combine_documents/reduce.py
{ "start": 433, "end": 643 }
class ____(Protocol): """Interface for the combine_docs method.""" def __call__(self, docs: list[Document], **kwargs: Any) -> str: """Interface for the combine_docs method."""
CombineDocsProtocol
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/dagrun.py
{ "start": 1245, "end": 1352 }
class ____(BaseModel): """Schema for DAG Run State response.""" state: DagRunState
DagRunStateResponse
python
gevent__gevent
src/gevent/ssl.py
{ "start": 7469, "end": 34772 }
class ____(socket): """ gevent `ssl.SSLSocket <https://docs.python.org/3/library/ssl.html#ssl-sockets>`_ for Python 3. """ # pylint:disable=too-many-instance-attributes,too-many-public-methods def __init__(self, sock=None, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, suppress_ragged_eofs=True, npn_protocols=None, ciphers=None, server_hostname=None, _session=None, # 3.6 _context=None): # When a *sock* argument is passed, it is used only for its fileno() # and is immediately detach()'d *unless* we raise an error. # pylint:disable=too-many-locals,too-many-statements,too-many-branches if _context: self._context = _context else: if server_side and not certfile: raise ValueError("certfile must be specified for server-side " "operations") if keyfile and not certfile: raise ValueError("certfile must be specified") if certfile and not keyfile: keyfile = certfile self._context = SSLContext(ssl_version) self._context.verify_mode = cert_reqs if ca_certs: self._context.load_verify_locations(ca_certs) if certfile: self._context.load_cert_chain(certfile, keyfile) if npn_protocols: self._context.set_npn_protocols(npn_protocols) if ciphers: self._context.set_ciphers(ciphers) self.keyfile = keyfile self.certfile = certfile self.cert_reqs = cert_reqs self.ssl_version = ssl_version self.ca_certs = ca_certs self.ciphers = ciphers # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get # mixed in. if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: raise NotImplementedError("only stream sockets are supported") if server_side: if server_hostname: raise ValueError("server_hostname can only be specified " "in client mode") if _session is not None: raise ValueError("session can only be specified " "in client mode") if self._context.check_hostname and not server_hostname: raise ValueError("check_hostname requires server_hostname") self._session = _session self.server_side = server_side self.server_hostname = server_hostname self.do_handshake_on_connect = do_handshake_on_connect self.suppress_ragged_eofs = suppress_ragged_eofs connected = False sock_timeout = None if sock is not None: # We're going non-blocking below, can't set timeout yet. sock_timeout = sock.gettimeout() socket.__init__(self, family=sock.family, type=sock.type, proto=sock.proto, fileno=sock.fileno()) # When Python 3 sockets are __del__, they close() themselves, # including their underlying fd, unless they have been detached. # Only detach if we succeed in taking ownership; if we raise an exception, # then the user might have no way to close us and release the resources. sock.detach() elif fileno is not None: socket.__init__(self, fileno=fileno) else: socket.__init__(self, family=family, type=type, proto=proto) self._closed = False self._sslobj = None # see if we're connected try: self._sock.getpeername() except OSError as e: if e.errno != errno.ENOTCONN: # This file descriptor is hosed, shared or not. # Clean up. self.close() raise # Next block is originally from # https://github.com/python/cpython/commit/75a875e0df0530b75b1470d797942f90f4a718d3, # intended to fix https://github.com/python/cpython/issues/108310 blocking = self.getblocking() self.setblocking(False) try: # We are not connected so this is not supposed to block, but # testing revealed otherwise on macOS and Windows so we do # the non-blocking dance regardless. Our raise when any data # is found means consuming the data is harmless. notconn_pre_handshake_data = self.recv(1) except OSError as e: # pylint:disable=redefined-outer-name # EINVAL occurs for recv(1) on non-connected on unix sockets. if e.errno not in (errno.ENOTCONN, errno.EINVAL): raise notconn_pre_handshake_data = b'' self.setblocking(blocking) if notconn_pre_handshake_data: # This prevents pending data sent to the socket before it was # closed from escaping to the caller who could otherwise # presume it came through a successful TLS connection. reason = "Closed before TLS handshake with data in recv buffer." notconn_pre_handshake_data_error = SSLError(e.errno, reason) # Add the SSLError attributes that _ssl.c always adds. notconn_pre_handshake_data_error.reason = reason notconn_pre_handshake_data_error.library = None try: self.close() except OSError: pass raise notconn_pre_handshake_data_error else: connected = True self.settimeout(sock_timeout) self._connected = connected if connected: # create the SSL object try: self._sslobj = self.__create_sslobj(server_side, _session) if do_handshake_on_connect: timeout = self.gettimeout() if timeout == 0.0: # non-blocking raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") self.do_handshake() except OSError: self.close() raise def _gevent_sock_class(self, family, type, proto, fileno): return _contextawaresock(family, type, proto, fileno, _wref(self)) def _extra_repr(self): return ' server=%s, cipher=%r' % ( self.server_side, self._sslobj.cipher() if self._sslobj is not None else '' ) @property def context(self): return self._context @context.setter def context(self, ctx): self._context = ctx self._sslobj.context = ctx @property def session(self): """The SSLSession for client socket.""" if self._sslobj is not None: return self._sslobj.session @session.setter def session(self, session): self._session = session if self._sslobj is not None: self._sslobj.session = session @property def session_reused(self): """Was the client session reused during handshake""" if self._sslobj is not None: return self._sslobj.session_reused def dup(self): raise NotImplementedError("Can't dup() %s instances" % self.__class__.__name__) def _checkClosed(self, msg=None): # raise an exception here if you wish to check for spurious closes pass def _check_connected(self): if not self._connected: # getpeername() will raise ENOTCONN if the socket is really # not connected; note that we can be connected even without # _connected being set, e.g. if connect() first returned # EAGAIN. self.getpeername() def read(self, nbytes=2014, buffer=None): """Read up to LEN bytes and return them. Return zero-length string on EOF. .. versionchanged:: 24.2.1 No longer requires a non-None *buffer* to implement ``len()``. This is a backport from 3.11.8. """ # pylint:disable=too-many-branches self._checkClosed() # The stdlib signature is (len=1024, buffer=None) # but that shadows the len builtin, and its hard/annoying to # get it back. # # Also, the return values are weird. If *buffer* is given, # we return the count of bytes added to buffer. Otherwise, # we return the string we read. bytes_read = 0 while True: if not self._sslobj: raise ValueError("Read on closed or unwrapped SSL socket.") if nbytes == 0: return b'' if buffer is None else 0 # Negative lengths are handled natively when the buffer is None # to raise a ValueError try: if buffer is not None: bytes_read += self._sslobj.read(nbytes, buffer) return bytes_read return self._sslobj.read(nbytes or 1024) except SSLWantReadError: if self.timeout == 0.0: raise self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout) except SSLWantWriteError: if self.timeout == 0.0: raise # note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout) except SSLZeroReturnError: # This one is only seen in PyPy 7.3.17 if self.suppress_ragged_eofs: return b'' if buffer is None else bytes_read raise except SSLError as ex: # All the other SSLxxxxxError classes extend SSLError, # so catch it last. if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: return b'' if buffer is None else bytes_read raise # Certain versions of Python, built against certain # versions of OpenSSL operating in certain modes, can # produce ``ConnectionResetError`` instead of # ``SSLError``. Notably, it looks like anything built # against 1.1.1c does that? gevent briefly (from support of TLS 1.3 # in Sept 2019 to issue #1637 it June 2020) caught that error and treaded # it just like SSL_ERROR_EOF. But that's not what the standard library does. # So presumably errors that result from unexpected ``ConnectionResetError`` # are issues in gevent tests. def write(self, data): """Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.""" self._checkClosed() while True: if not self._sslobj: raise ValueError("Write on closed or unwrapped SSL socket.") try: return self._sslobj.write(data) except SSLError as ex: if ex.args[0] == SSL_ERROR_WANT_READ: if self.timeout == 0.0: raise self._wait(self._read_event, timeout_exc=_SSLErrorWriteTimeout) elif ex.args[0] == SSL_ERROR_WANT_WRITE: if self.timeout == 0.0: raise self._wait(self._write_event, timeout_exc=_SSLErrorWriteTimeout) else: raise def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" self._checkClosed() self._check_connected() try: c = self._sslobj.peer_certificate except AttributeError: # 3.6 c = self._sslobj.getpeercert return c(binary_form) def selected_npn_protocol(self): self._checkClosed() if not self._sslobj or not _ssl.HAS_NPN: return None return self._sslobj.selected_npn_protocol() if hasattr(_ssl, 'HAS_ALPN'): # 3.5+ def selected_alpn_protocol(self): self._checkClosed() if not self._sslobj or not _ssl.HAS_ALPN: # pylint:disable=no-member return None return self._sslobj.selected_alpn_protocol() def shared_ciphers(self): """Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. """ return self._sslobj.shared_ciphers() def version(self): """Return a string identifying the protocol version used by the current SSL channel. """ if not self._sslobj: return None return self._sslobj.version() # We inherit sendfile from super(); it always uses `send` def cipher(self): self._checkClosed() if not self._sslobj: return None return self._sslobj.cipher() def compression(self): self._checkClosed() if not self._sslobj: return None return self._sslobj.compression() def send(self, data, flags=0, timeout=timeout_default): self._checkClosed() if timeout is timeout_default: timeout = self.timeout if self._sslobj: if flags != 0: raise ValueError( "non-zero flags not allowed in calls to send() on %s" % self.__class__) while True: try: return self._sslobj.write(data) except SSLWantReadError: if self.timeout == 0.0: return 0 self._wait(self._read_event) except SSLWantWriteError: if self.timeout == 0.0: return 0 self._wait(self._write_event) else: return socket.send(self, data, flags, timeout) def sendto(self, data, flags_or_addr, addr=None): self._checkClosed() if self._sslobj: raise ValueError("sendto not allowed on instances of %s" % self.__class__) if addr is None: return socket.sendto(self, data, flags_or_addr) return socket.sendto(self, data, flags_or_addr, addr) def sendmsg(self, *args, **kwargs): # Ensure programs don't send data unencrypted if they try to # use this method. raise NotImplementedError("sendmsg not allowed on instances of %s" % self.__class__) def sendall(self, data, flags=0): self._checkClosed() if self._sslobj: if flags != 0: raise ValueError( "non-zero flags not allowed in calls to sendall() on %s" % self.__class__) try: return socket.sendall(self, data, flags) except _socket_timeout: if self.timeout == 0.0: # Raised by the stdlib on non-blocking sockets raise SSLWantWriteError("The operation did not complete (write)") raise def recv(self, buflen=1024, flags=0): self._checkClosed() if self._sslobj: if flags != 0: raise ValueError( "non-zero flags not allowed in calls to recv() on %s" % self.__class__) if buflen == 0: # https://github.com/python/cpython/commit/00915577dd84ba75016400793bf547666e6b29b5 # Python #23804 return b'' return self.read(buflen) return socket.recv(self, buflen, flags) def recv_into(self, buffer, nbytes=None, flags=0): """ .. versionchanged:: 24.2.1 No longer requires a non-None *buffer* to implement ``len()``. This is a backport from 3.11.8. """ self._checkClosed() if nbytes is None: if buffer is not None: with memoryview(buffer) as view: nbytes = view.nbytes if not nbytes: nbytes = 1024 if self._sslobj: if flags != 0: raise ValueError("non-zero flags not allowed in calls to recv_into() on %s" % self.__class__) return self.read(nbytes, buffer) return socket.recv_into(self, buffer, nbytes, flags) def recvfrom(self, buflen=1024, flags=0): self._checkClosed() if self._sslobj: raise ValueError("recvfrom not allowed on instances of %s" % self.__class__) return socket.recvfrom(self, buflen, flags) def recvfrom_into(self, buffer, nbytes=None, flags=0): self._checkClosed() if self._sslobj: raise ValueError("recvfrom_into not allowed on instances of %s" % self.__class__) return socket.recvfrom_into(self, buffer, nbytes, flags) def recvmsg(self, *args, **kwargs): raise NotImplementedError("recvmsg not allowed on instances of %s" % self.__class__) def recvmsg_into(self, *args, **kwargs): raise NotImplementedError("recvmsg_into not allowed on instances of " "%s" % self.__class__) def pending(self): self._checkClosed() if self._sslobj: return self._sslobj.pending() return 0 def shutdown(self, how): self._checkClosed() self._sslobj = None socket.shutdown(self, how) def unwrap(self): if not self._sslobj: raise ValueError("No SSL wrapper around " + str(self)) try: # 3.7 and newer, that use the SSLSocket object # call its shutdown. shutdown = self._sslobj.shutdown except AttributeError: # Earlier versions use SSLObject, which covers # that with a layer. shutdown = self._sslobj.unwrap s = self._sock while True: try: s = shutdown() break except SSLWantReadError: # Callers of this method expect to get a socket # back, so we can't simply return 0, we have # to let these be raised if self.timeout == 0.0: raise self._wait(self._read_event) except SSLWantWriteError: if self.timeout == 0.0: raise self._wait(self._write_event) except SSLEOFError: break except SSLZeroReturnError: # Between PyPy 7.3.12 and PyPy 7.3.17, it started raising # this. This is equivalent to SSLEOFError for our purposes: # both indicate the connection has been closed, # the former uncleanly, the latter cleanly. break except OSError as e: if e.errno == 0: # The equivalent of SSLEOFError on unpatched versions of Python. # https://bugs.python.org/issue31122 break raise self._sslobj = None # The return value of shutting down the SSLObject is the # original wrapped socket passed to _wrap_socket, i.e., # _contextawaresock. But that object doesn't have the # gevent wrapper around it so it can't be used. We have to # wrap it back up with a gevent wrapper. assert s is self._sock # In the stdlib, SSLSocket subclasses socket.socket and passes itself # to _wrap_socket, so it gets itself back. We can't do that, we have to # pass our subclass of _socket.socket, _contextawaresock. # So ultimately we should return ourself. # See test_ftplib.py:TestTLS_FTPClass.test_ccc return self def _real_close(self): self._sslobj = None socket._real_close(self) def do_handshake(self): """Perform a TLS/SSL handshake.""" self._check_connected() while True: try: self._sslobj.do_handshake() break except SSLWantReadError: if self.timeout == 0.0: raise self._wait(self._read_event, timeout_exc=_SSLErrorHandshakeTimeout) except SSLWantWriteError: if self.timeout == 0.0: raise self._wait(self._write_event, timeout_exc=_SSLErrorHandshakeTimeout) # 3.7+, making it difficult to create these objects. # There's a new type, _ssl.SSLSocket, that takes the # place of SSLObject for self._sslobj. This one does it all. def __create_sslobj(self, server_side=False, session=None): return self.context._wrap_socket( self._sock, server_side, self.server_hostname, owner=self._sock, session=session ) def _real_connect(self, addr, connect_ex): if self.server_side: raise ValueError("can't connect in server-side mode") # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._connected: raise ValueError("attempt to connect already-connected SSLSocket!") self._sslobj = self.__create_sslobj(False, self._session) try: if connect_ex: rc = socket.connect_ex(self, addr) else: rc = None socket.connect(self, addr) if not rc: if self.do_handshake_on_connect: self.do_handshake() self._connected = True return rc except socket_error: self._sslobj = None raise def connect(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" self._real_connect(addr, False) def connect_ex(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" return self._real_connect(addr, True) def accept(self): """ Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client. """ newsock, addr = super().accept() try: newsock = self._context.wrap_socket( newsock, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs, server_side=True ) return newsock, addr except: newsock.close() raise def get_channel_binding(self, cb_type="tls-unique"): """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ if hasattr(self._sslobj, 'get_channel_binding'): # 3.7+, and sslobj is not None return self._sslobj.get_channel_binding(cb_type) if cb_type not in CHANNEL_BINDING_TYPES: raise ValueError("Unsupported channel binding type") if cb_type != "tls-unique": raise NotImplementedError("{0} channel binding type not implemented".format(cb_type)) if self._sslobj is None: return None return self._sslobj.tls_unique_cb() def verify_client_post_handshake(self): # Only present in 3.7.1+; an attributeerror is alright if self._sslobj: return self._sslobj.verify_client_post_handshake() raise ValueError("No SSL wrapper around " + str(self)) if hasattr(__ssl__.SSLSocket, 'get_verified_chain'): # Added in 3.13 def get_verified_chain(self): chain = self._sslobj.get_verified_chain() if chain is None: return [] return [cert.public_bytes(_ssl.ENCODING_DER) for cert in chain] def get_unverified_chain(self): chain = self._sslobj.get_unverified_chain() if chain is None: return [] return [cert.public_bytes(_ssl.ENCODING_DER) for cert in chain] # Python does not support forward declaration of types SSLContext.sslsocket_class = SSLSocket # Python 3.2 onwards raise normal timeout errors, not SSLError. # See https://bugs.python.org/issue10272 _SSLErrorReadTimeout = _socket_timeout('The read operation timed out') _SSLErrorWriteTimeout = _socket_timeout('The write operation timed out') _SSLErrorHandshakeTimeout = _socket_timeout('The handshake operation timed out') def wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None): return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, server_side=server_side, cert_reqs=cert_reqs, ssl_version=ssl_version, ca_certs=ca_certs, do_handshake_on_connect=do_handshake_on_connect, suppress_ragged_eofs=suppress_ragged_eofs, ciphers=ciphers) def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" _, _ = addr if ca_certs is not None: cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE with create_connection(addr) as sock: with wrap_socket(sock, ssl_version=ssl_version, cert_reqs=cert_reqs, ca_certs=ca_certs) as sslsock: dercert = sslsock.getpeercert(True) sslsock = sock = None return DER_cert_to_PEM_cert(dercert)
SSLSocket
python
streamlit__streamlit
lib/tests/streamlit/elements/progress_test.py
{ "start": 888, "end": 4003 }
class ____(DeltaGeneratorTestCase): """Test DeltaGenerator Progress.""" def test_progress_int(self): """Test Progress with int values.""" values = [0, 42, 100] for value in values: st.progress(value) element = self.get_delta_from_queue().new_element assert value == element.progress.value def test_progress_float(self): """Test Progress with float values.""" values = [0.0, 0.42, 1.0] for value in values: st.progress(value) element = self.get_delta_from_queue().new_element assert int(value * 100) == element.progress.value def test_progress_bad_values(self): """Test Progress with bad values.""" values = [-1, 101, -0.01, 1.01] for value in values: with pytest.raises(StreamlitAPIException): st.progress(value) with pytest.raises(StreamlitAPIException): st.progress("some string") def test_progress_text(self): """Test Progress with text.""" text = "TEST_TEXT" st.progress(42, text=text) element = self.get_delta_from_queue().new_element assert text == element.progress.text def test_progress_with_text(self): """Test Progress with invalid type in text parameter.""" text = object() with pytest.raises(StreamlitAPIException): st.progress(42, text=text) def test_progress_with_close_float(self): """Test Progress with float values close to 0.0 and 1.0""" values = [-0.0000000000021, 1.0000000000000013] for value in values: st.progress(value) element = self.get_delta_from_queue().new_element assert int(value * 100) == element.progress.value def test_progress_width(self): """Test Progress with width parameter.""" st.progress(50, width="stretch") c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert c.width_config.use_stretch st.progress(50, width=500) c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert c.width_config.pixel_width == 500 st.progress(50) c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert c.width_config.use_stretch @parameterized.expand( [ "invalid", -100, 0, 100.5, None, ] ) def test_progress_invalid_width(self, invalid_width): """Test Progress with invalid width values.""" with pytest.raises(StreamlitAPIException) as ctx: st.progress(50, width=invalid_width) assert "Invalid width" in str(ctx.value)
DeltaGeneratorProgressTest
python
pypa__setuptools
setuptools/_distutils/errors.py
{ "start": 1297, "end": 1458 }
class ____(DistutilsError): """Raised by fancy_getopt in response to getopt.error -- ie. an error in the command line usage.""" pass
DistutilsArgError
python
sympy__sympy
sympy/stats/stochastic_process_types.py
{ "start": 65766, "end": 73026 }
class ____: """ Internal class to handle the queries of expectation and probability by substitution. """ @staticmethod def _rvindexed_subs(expr, condition=None): """ Substitutes the RandomIndexedSymbol with the RandomSymbol with same name, distribution and probability as RandomIndexedSymbol. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. """ rvs_expr = random_symbols(expr) if len(rvs_expr) != 0: swapdict_expr = {} for rv in rvs_expr: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv swapdict_expr[rv] = newrv expr = expr.subs(swapdict_expr) rvs_cond = random_symbols(condition) if len(rvs_cond)!=0: swapdict_cond = {} for rv in rvs_cond: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) swapdict_cond[rv] = newrv condition = condition.subs(swapdict_cond) return expr, condition @classmethod def _expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Internal method for computing expectation of indexed RV. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ new_expr, new_condition = self._rvindexed_subs(expr, condition) if not is_random(new_expr): return new_expr new_pspace = pspace(new_expr) if new_condition is not None: new_expr = given(new_expr, new_condition) if new_expr.is_Add: # As E is Linear return Add(*[new_pspace.compute_expectation( expr=arg, evaluate=evaluate, **kwargs) for arg in new_expr.args]) return new_pspace.compute_expectation( new_expr, evaluate=evaluate, **kwargs) @classmethod def _probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Internal method for computing probability of indexed RV Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition) if isinstance(new_givencondition, RandomSymbol): condrv = random_symbols(new_condition) if len(condrv) == 1 and condrv[0] == new_givencondition: return BernoulliDistribution(self._probability(new_condition), 0, 1) if any(dependent(rv, new_givencondition) for rv in condrv): return Probability(new_condition, new_givencondition) else: return self._probability(new_condition) if new_givencondition is not None and \ not isinstance(new_givencondition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_givencondition)) if new_givencondition == False or new_condition == False: return S.Zero if new_condition == True: return S.One if not isinstance(new_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_condition)) if new_givencondition is not None: # If there is a condition # Recompute on new conditional expr return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs) result = pspace(new_condition).probability(new_condition, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def get_timerv_swaps(expr, condition): """ Finds the appropriate interval for each time stamp in expr by parsing the given condition and returns intervals for each timestamp and dictionary that maps variable time-stamped Random Indexed Symbol to its corresponding Random Indexed variable with fixed time stamp. Parameters ========== expr: SymPy Expression Expression containing Random Indexed Symbols with variable time stamps condition: Relational/Boolean Expression Expression containing time bounds of variable time stamps in expr Examples ======== >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess >>> from sympy import symbols, Contains, Interval >>> x, t, d = symbols('x t d', positive=True) >>> X = PoissonProcess("X", 3) >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1))) ([Interval.Lopen(0, 1)], {X(t): X(1)}) >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)}) Returns ======= intervals: list List of Intervals/FiniteSet on which each time stamp is defined rv_swap: dict Dictionary mapping variable time Random Indexed Symbol to constant time Random Indexed Variable """ if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) expr_syms = list(expr.atoms(RandomIndexedSymbol)) if isinstance(condition, (And, Or)): given_cond_args = condition.args else: # single condition given_cond_args = (condition, ) rv_swap = {} intervals = [] for expr_sym in expr_syms: for arg in given_cond_args: if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol): intv = _set_converter(arg.args[1]) diff_key = intv._sup - intv._inf if diff_key == oo: raise ValueError("%s should have finite bounds" % str(expr_sym.name)) elif diff_key == S.Zero: # has singleton set diff_key = intv._sup rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key}) intervals.append(intv) return intervals, rv_swap
_SubstituteRV
python
pyca__cryptography
tests/test_cryptography_utils.py
{ "start": 256, "end": 1667 }
class ____: def test_simple(self): class T: @utils.cached_property def t(self): accesses.append(None) return 14 accesses: typing.List[typing.Optional[T]] = [] assert T.t t = T() assert t.t == 14 assert len(accesses) == 1 assert t.t == 14 assert len(accesses) == 1 t = T() assert t.t == 14 assert len(accesses) == 2 assert t.t == 14 assert len(accesses) == 2 def test_set(self): class T: @utils.cached_property def t(self): accesses.append(None) return 14 accesses: typing.List[typing.Optional[T]] = [] t = T() with pytest.raises(AttributeError): t.t = None assert len(accesses) == 0 assert t.t == 14 assert len(accesses) == 1 with pytest.raises(AttributeError): t.t = None assert len(accesses) == 1 assert t.t == 14 assert len(accesses) == 1 def test_enum(): class TestEnum(utils.Enum): something = "something" assert issubclass(TestEnum, enum.Enum) assert isinstance(TestEnum.something, enum.Enum) assert repr(TestEnum.something) == "<TestEnum.something: 'something'>" assert str(TestEnum.something) == "TestEnum.something"
TestCachedProperty
python
huggingface__transformers
src/transformers/models/siglip/modeling_siglip.py
{ "start": 28166, "end": 36291 }
class ____(SiglipPreTrainedModel): config: SiglipConfig def __init__(self, config: SiglipConfig): super().__init__(config) if not isinstance(config.text_config, SiglipTextConfig): raise TypeError( "config.text_config is expected to be of type SiglipTextConfig but is of type" f" {type(config.text_config)}." ) if not isinstance(config.vision_config, SiglipVisionConfig): raise TypeError( "config.vision_config is expected to be of type SiglipVisionConfig but is of type" f" {type(config.vision_config)}." ) text_config = config.text_config vision_config = config.vision_config # First, initialize the text and vision models with proper attention implementation text_model = SiglipTextModel._from_config(text_config) vision_model = SiglipVisionModel._from_config(vision_config) # Second, get the text and vision submodules (for backward compatibility) self.text_model = text_model.text_model self.vision_model = vision_model.vision_model self.logit_scale = nn.Parameter(torch.randn(1)) self.logit_bias = nn.Parameter(torch.randn(1)) # Initialize weights and apply final processing self.post_init() @filter_out_non_signature_kwargs() @auto_docstring def get_text_features( self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, ) -> torch.FloatTensor: r""" Returns: text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`]. Examples: ```python >>> from transformers import AutoTokenizer, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224") >>> # important: make sure to set padding="max_length" as that's how the model was trained >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt") >>> with torch.no_grad(): ... text_features = model.get_text_features(**inputs) ```""" text_outputs: BaseModelOutputWithPooling = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, ) pooled_output = text_outputs.pooler_output return pooled_output @filter_out_non_signature_kwargs() @auto_docstring def get_image_features( self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ) -> torch.FloatTensor: r""" Returns: image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`]. Examples: ```python >>> import torch >>> from transformers import AutoProcessor, AutoModel >>> from transformers.image_utils import load_image >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = load_image(url) >>> inputs = processor(images=image, return_tensors="pt") >>> with torch.no_grad(): ... image_features = model.get_image_features(**inputs) ```""" vision_outputs: BaseModelOutputWithPooling = self.vision_model( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) pooled_output = vision_outputs.pooler_output return pooled_output # NOTE: SiglipModel uses Pretrained backbones, so we don't need to add `check_model_inputs` here @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, return_loss: Optional[bool] = None, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ) -> SiglipOutput: r""" return_loss (`bool`, *optional*): Whether or not to return the contrastive loss. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, AutoModel >>> import torch >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"] >>> # important: we pass `padding=max_length` since the model was trained with this >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt") >>> with torch.no_grad(): ... outputs = model(**inputs) >>> logits_per_image = outputs.logits_per_image >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'") 31.9% that image 0 is 'a photo of 2 cats' ```""" vision_outputs: BaseModelOutputWithPooling = self.vision_model( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, ) text_outputs: BaseModelOutputWithPooling = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, **kwargs, ) image_embeds = vision_outputs.pooler_output text_embeds = text_outputs.pooler_output # normalized features image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True) text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True) # cosine similarity as logits logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device)) logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device) logits_per_text = logits_per_text * logit_scale.exp() + logit_bias logits_per_image = logits_per_text.t() loss = None if return_loss: # Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip.py#L287 eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device) m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text) nll = -torch.sum(loglik, dim=-1) loss = nll.mean() return SiglipOutput( loss=loss, logits_per_image=logits_per_image, logits_per_text=logits_per_text, text_embeds=text_embeds, image_embeds=image_embeds, text_model_output=text_outputs, vision_model_output=vision_outputs, ) @auto_docstring( custom_intro=""" SigLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of the patch tokens) e.g. for ImageNet. """ )
SiglipModel
python
pypa__warehouse
warehouse/events/tags.py
{ "start": 1262, "end": 9074 }
class ____: class Account(EventTagEnum): """Tags for User events.""" # Name = "source_type:subject_type:action" APITokenAdded = "account:api_token:added" APITokenRemoved = "account:api_token:removed" APITokenRemovedLeak = "account:api_token:removed_leak" AccountCreate = "account:create" EmailAdd = "account:email:add" EmailPrimaryChange = "account:email:primary:change" EmailRemove = "account:email:remove" EmailReverify = "account:email:reverify" EmailVerified = "account:email:verified" LoginFailure = "account:login:failure" LoginSuccess = "account:login:success" OrganizationRoleAdd = "account:organization_role:add" OrganizationRoleChange = "account:organization_role:change" OrganizationRoleDeclineInvite = "account:organization_role:decline_invite" OrganizationRoleExpireInvite = "account:organization_role:expire_invite" OrganizationRoleInvite = "account:organization_role:invite" OrganizationRoleRemove = "account:organization_role:remove" OrganizationRoleRevokeInvite = "account:organization_role:revoke_invite" PasswordChange = "account:password:change" PasswordDisabled = "account:password:disabled" PasswordReset = "account:password:reset" PasswordResetAttempt = "account:password:reset:attempt" PasswordResetRequest = "account:password:reset:request" PendingOIDCPublisherAdded = "account:oidc:pending-publisher-added" PendingOIDCPublisherRemoved = "account:oidc:pending-publisher-removed" RecoveryCodesGenerated = "account:recovery_codes:generated" RecoveryCodesRegenerated = "account:recovery_codes:regenerated" RecoveryCodesUsed = "account:recovery_codes:used" RoleAdd = "account:role:add" RoleChange = "account:role:change" RoleDeclineInvite = "account:role:decline_invite" RoleInvite = "account:role:invite" RoleRemove = "account:role:remove" RoleRevokeInvite = "account:role:revoke_invite" TeamRoleAdd = "account:team_role:add" TeamRoleRemove = "account:team_role:remove" TwoFactorDeviceRemembered = "account:two_factor:device_remembered" TwoFactorMethodAdded = "account:two_factor:method_added" TwoFactorMethodRemoved = "account:two_factor:method_removed" EmailSent = "account:email:sent" AlternateRepositoryAdd = "account:alternate_repository:add" AlternateRepositoryDelete = "account:alternate_repository:delete" # The following tags are no longer used when recording events. # ReauthenticateFailure = "account:reauthenticate:failure" # RoleAccepted = "account:role:accepted" class Project(EventTagEnum): """Tags for Project events. Keep in sync with: warehouse/templates/manage/project/history.html """ # Name = "source_type:subject_type:action" ShortLivedAPITokenAdded = "account:short_lived_api_token:added" APITokenAdded = "project:api_token:added" APITokenRemoved = "project:api_token:removed" OIDCPublisherAdded = "project:oidc:publisher-added" OIDCPublisherRemoved = "project:oidc:publisher-removed" OrganizationProjectAdd = "project:organization_project:add" OrganizationProjectRemove = "project:organization_project:remove" OwnersRequire2FADisabled = "project:owners_require_2fa:disabled" OwnersRequire2FAEnabled = "project:owners_require_2fa:enabled" ProjectArchiveEnter = "project:archive:enter" ProjectArchiveExit = "project:archive:exit" ProjectCreate = "project:create" ProjectQuarantineEnter = "project:quarantine:enter" ProjectQuarantineExit = "project:quarantine:exit" ReleaseAdd = "project:release:add" ReleaseRemove = "project:release:remove" ReleaseUnyank = "project:release:unyank" ReleaseYank = "project:release:yank" RoleAdd = "project:role:add" RoleChange = "project:role:change" RoleDeclineInvite = "project:role:decline_invite" RoleInvite = "project:role:invite" RoleRemove = "project:role:remove" RoleRevokeInvite = "project:role:revoke_invite" TeamProjectRoleAdd = "project:team_project_role:add" TeamProjectRoleChange = "project:team_project_role:change" TeamProjectRoleRemove = "project:team_project_role:remove" AlternateRepositoryAdd = "project:alternate_repository:add" AlternateRepositoryDelete = "project:alternate_repository:delete" # The following tags are no longer used when recording events. # RoleAccepted = "project:role:accepted" # RoleDelete = "project:role:delete" # ReleaseFileAdd = "project:release:file:add" # ReleaseFileRemove = "project:release:file:remove" class File(EventTagEnum): """Tags for File events. Keep in sync with: warehouse/templates/manage/project/history.html """ FileAdd = "file:add" FileRemove = "file:remove" class Organization(EventTagEnum): """Tags for Organization events. Keep in sync with: warehouse/templates/manage/organization/history.html """ # Name = "source_type:subject_type:action" CatalogEntryAdd = "organization:catalog_entry:add" OrganizationApprove = "organization:approve" OrganizationApplicationSubmit = "organization:application_submit" OrganizationCreate = "organization:create" OrganizationDecline = "organization:decline" OrganizationDelete = "organization:delete" OrganizationRename = "organization:rename" OrganizationProjectAdd = "organization:organization_project:add" OrganizationProjectRemove = "organization:organization_project:remove" OrganizationRoleAdd = "organization:organization_role:add" OrganizationRoleChange = "organization:organization_role:change" OrganizationRoleDeclineInvite = "organization:organization_role:decline_invite" OrganizationRoleExpireInvite = "organization:organization_role:expire_invite" OrganizationRoleInvite = "organization:organization_role:invite" OrganizationRoleRemove = "organization:organization_role:remove" OrganizationRoleRevokeInvite = "organization:organization_role:revoke_invite" TeamCreate = "organization:team:create" TeamDelete = "organization:team:delete" TeamRename = "organization:team:rename" TeamProjectRoleAdd = "organization:team_project_role:add" TeamProjectRoleChange = "organization:team_project_role:change" TeamProjectRoleRemove = "organization:team_project_role:remove" TeamRoleAdd = "organization:team_role:add" TeamRoleRemove = "organization:team_role:remove" OIDCPublisherAdded = "organization:oidc:publisher-added" OIDCPublisherRemoved = "organization:oidc:publisher-removed" PendingOIDCPublisherAdded = "organization:oidc:pending-publisher-added" PendingOIDCPublisherRemoved = "organization:oidc:pending-publisher-removed" class Team(EventTagEnum): """Tags for Organization events. Keep in sync with: warehouse/templates/manage/team/history.html """ # Name = "source_type:subject_type:action" TeamCreate = "team:create" TeamDelete = "team:delete" TeamRename = "team:rename" TeamProjectRoleAdd = "team:team_project_role:add" TeamProjectRoleChange = "team:team_project_role:change" TeamProjectRoleRemove = "team:team_project_role:remove" TeamRoleAdd = "team:team_role:add" TeamRoleRemove = "team:team_role:remove"
EventTag
python
getsentry__sentry
src/sentry/notifications/platform/types.py
{ "start": 6576, "end": 6753 }
class ____(NotificationBodyFormattingBlock): type: Literal[NotificationBodyFormattingBlockType.PARAGRAPH] blocks: list[NotificationBodyTextBlock] @dataclass
ParagraphBlock
python
kamyu104__LeetCode-Solutions
Python/maximum-of-absolute-value-expression.py
{ "start": 29, "end": 1254 }
class ____(object): def maxAbsValExpr(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ # 1. max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i > j) # = max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for j > i) # 2. for i > j: # (|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j|) # >= c1*(arr1[i]-arr1[j]) + c2*(arr2[i]-arr2[j]) + i-j for c1 in (1, -1), c2 in (1, -1) # = (c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j) for c1 in (1, -1), c2 in (1, -1) # 1 + 2 => max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i != j) # = max((c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j) # for c1 in (1, -1), c2 in (1, -1) for i > j) result = 0 for c1 in [1, -1]: for c2 in [1, -1]: min_prev = float("inf") for i in xrange(len(arr1)): curr = c1*arr1[i] + c2*arr2[i] + i result = max(result, curr-min_prev) min_prev = min(min_prev, curr) return result # Time: O(n) # Space: O(1)
Solution
python
doocs__leetcode
lcof/面试题33. 二叉搜索树的后序遍历序列/Solution2.py
{ "start": 0, "end": 313 }
class ____: def verifyPostorder(self, postorder: List[int]) -> bool: mx = inf stk = [] for x in postorder[::-1]: if x > mx: return False while stk and stk[-1] > x: mx = stk.pop() stk.append(x) return True
Solution
python
python__mypy
mypy/checker.py
{ "start": 375034, "end": 377844 }
class ____(SemanticAnalyzerCoreInterface): """ Adapts TypeChecker to the SemanticAnalyzerCoreInterface, allowing most type expressions to be parsed during the TypeChecker pass. See ExpressionChecker.try_parse_as_type_expression() to understand how this class is used. """ _chk: TypeChecker _names: dict[str, SymbolTableNode] did_fail: bool def __init__(self, chk: TypeChecker, names: dict[str, SymbolTableNode]) -> None: self._chk = chk self._names = names self.did_fail = False def lookup_qualified( self, name: str, ctx: Context, suppress_errors: bool = False ) -> SymbolTableNode | None: sym = self._names.get(name) # All names being looked up should have been previously gathered, # even if the related SymbolTableNode does not refer to a valid SymbolNode assert sym is not None, name return sym def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: ret = self.lookup_fully_qualified_or_none(fullname) assert ret is not None, fullname return ret def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: try: return self._chk.lookup_qualified(fullname) except KeyError: return None def fail( self, msg: str, ctx: Context, serious: bool = False, *, blocker: bool = False, code: ErrorCode | None = None, ) -> None: self.did_fail = True def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: pass def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: if feature not in self._chk.options.enable_incomplete_feature: self.fail("__ignored__", ctx) return False return True def record_incomplete_ref(self) -> None: pass def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: pass def is_incomplete_namespace(self, fullname: str) -> bool: return False @property def final_iteration(self) -> bool: return True def is_future_flag_set(self, flag: str) -> bool: return self._chk.tree.is_future_flag_set(flag) @property def is_stub_file(self) -> bool: return self._chk.tree.is_stub def is_func_scope(self) -> bool: # Return arbitrary value. # # This method is currently only used to decide whether to pair # a fail() message with a note() message or not. Both of those # message types are ignored. return False @property def type(self) -> TypeInfo | None: return self._chk.type
TypeCheckerAsSemanticAnalyzer
python
django__django
tests/sitemaps_tests/test_https.py
{ "start": 1479, "end": 2929 }
class ____(SitemapTestsBase): extra = {"wsgi.url_scheme": "https"} def test_sitemap_index_with_https_request(self): "A sitemap index requested in HTTPS is rendered with HTTPS links" response = self.client.get("/simple/index.xml", **self.extra) expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc><lastmod>%s</lastmod></sitemap> </sitemapindex> """ % ( self.base_url.replace("http://", "https://"), date.today(), ) self.assertXMLEqual(response.text, expected_content) def test_sitemap_section_with_https_request(self): "A sitemap section requested in HTTPS is rendered with HTTPS links" response = self.client.get("/simple/sitemap-simple.xml", **self.extra) expected_content = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ' 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n' "<url><loc>%s/location/</loc><lastmod>%s</lastmod>" "<changefreq>never</changefreq><priority>0.5</priority></url>\n" "</urlset>" ) % ( self.base_url.replace("http://", "https://"), date.today(), ) self.assertXMLEqual(response.text, expected_content)
HTTPSDetectionSitemapTests
python
huggingface__transformers
tests/models/mbart/test_modeling_mbart.py
{ "start": 7965, "end": 15261 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( (MBartModel, MBartForConditionalGeneration, MBartForSequenceClassification, MBartForQuestionAnswering) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": MBartModel, "fill-mask": MBartForConditionalGeneration, "question-answering": MBartForQuestionAnswering, "summarization": MBartForConditionalGeneration, "text-classification": MBartForSequenceClassification, "text-generation": MBartForCausalLM, "text2text-generation": MBartForConditionalGeneration, "translation": MBartForConditionalGeneration, "zero-shot": MBartForSequenceClassification, } if is_torch_available() else {} ) is_encoder_decoder = True test_missing_keys = False # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): return True return False def setUp(self): self.model_tester = MBartModelTester(self) self.config_tester = ConfigTester(self, config_class=MBartConfig) def test_config(self): self.config_tester.run_common_tests() def test_save_load_strict(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) self.assertEqual(info["missing_keys"], set()) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_encoder_decoder_model_standalone(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs) # MBartForSequenceClassification does not support inputs_embeds def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MBartModel, MBartForConditionalGeneration, MBartForQuestionAnswering): model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) if not self.is_encoder_decoder: input_ids = inputs["input_ids"] del inputs["input_ids"] else: encoder_input_ids = inputs["input_ids"] decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) del inputs["input_ids"] inputs.pop("decoder_input_ids", None) wte = model.get_input_embeddings() if not self.is_encoder_decoder: inputs["inputs_embeds"] = wte(input_ids) else: inputs["inputs_embeds"] = wte(encoder_input_ids) inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) with torch.no_grad(): model(**inputs)[0] @require_torch_fp16 def test_generate_fp16(self): config, input_dict = self.model_tester.prepare_config_and_inputs() input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(1).to(torch_device) model = MBartForConditionalGeneration(config).eval().to(torch_device) model.half() model.generate(input_ids, attention_mask=attention_mask) model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) def test_ensure_weights_are_shared(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs() config.tie_word_embeddings = True model = MBartForConditionalGeneration(config) # MBart shares four weights. # Not an issue to not have these correctly tied for torch.load, but it is an issue for safetensors. self.assertEqual( len( { model.get_output_embeddings().weight.data_ptr(), model.get_input_embeddings().weight.data_ptr(), model.base_model.decoder.embed_tokens.weight.data_ptr(), model.base_model.encoder.embed_tokens.weight.data_ptr(), } ), 1, ) config.tie_word_embeddings = False model = MBartForConditionalGeneration(config) # MBart shares four weights. # Not an issue to not have these correctly tied for torch.load, but it is an issue for safetensors. self.assertEqual( len( { model.get_output_embeddings().weight.data_ptr(), model.get_input_embeddings().weight.data_ptr(), model.base_model.decoder.embed_tokens.weight.data_ptr(), model.base_model.encoder.embed_tokens.weight.data_ptr(), } ), 4, ) @unittest.skip( reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245" ) def test_load_save_without_tied_weights(self): pass def test_resize_embeddings_persists_embeddings_type(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs() config.scale_embedding = True model = MBartForConditionalGeneration(config) old_type = type(model.model.decoder.embed_tokens) model.resize_token_embeddings(new_num_tokens=config.vocab_size) new_type = type(model.model.decoder.embed_tokens) self.assertIs(old_type, new_type) def assert_tensors_close(a, b, atol=1e-12, prefix=""): """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error.""" if a is None and b is None: return True try: if torch.allclose(a, b, atol=atol): return True raise Exception except Exception: pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item() if a.numel() > 100: msg = f"tensor values are {pct_different:.1%} percent different." else: msg = f"{a} != {b}" if prefix: msg = prefix + ": " + msg raise AssertionError(msg) def _long_tensor(tok_lst): return torch.tensor(tok_lst, dtype=torch.long, device=torch_device) @require_torch @require_sentencepiece @require_tokenizers
MBartModelTest
python
matplotlib__matplotlib
galleries/examples/user_interfaces/embedding_webagg_sgskip.py
{ "start": 3505, "end": 8988 }
class ____(tornado.web.Application): class MainPage(tornado.web.RequestHandler): """ Serves the main HTML page. """ def get(self): manager = self.application.manager ws_uri = f"ws://{self.request.host}/" content = html_content % { "ws_uri": ws_uri, "fig_id": manager.num} self.write(content) class MplJs(tornado.web.RequestHandler): """ Serves the generated matplotlib javascript file. The content is dynamically generated based on which toolbar functions the user has defined. Call `FigureManagerWebAgg` to get its content. """ def get(self): self.set_header('Content-Type', 'application/javascript') js_content = FigureManagerWebAgg.get_javascript() self.write(js_content) class Download(tornado.web.RequestHandler): """ Handles downloading of the figure in various file formats. """ def get(self, fmt): manager = self.application.manager self.set_header( 'Content-Type', mimetypes.types_map.get(fmt, 'binary')) buff = io.BytesIO() manager.canvas.figure.savefig(buff, format=fmt) self.write(buff.getvalue()) class WebSocket(tornado.websocket.WebSocketHandler): """ A websocket for interactive communication between the plot in the browser and the server. In addition to the methods required by tornado, it is required to have two callback methods: - ``send_json(json_content)`` is called by matplotlib when it needs to send json to the browser. `json_content` is a JSON tree (Python dictionary), and it is the responsibility of this implementation to encode it as a string to send over the socket. - ``send_binary(blob)`` is called to send binary image data to the browser. """ supports_binary = True def open(self): # Register the websocket with the FigureManager. manager = self.application.manager manager.add_web_socket(self) if hasattr(self, 'set_nodelay'): self.set_nodelay(True) def on_close(self): # When the socket is closed, deregister the websocket with # the FigureManager. manager = self.application.manager manager.remove_web_socket(self) def on_message(self, message): # The 'supports_binary' message is relevant to the # websocket itself. The other messages get passed along # to matplotlib as-is. # Every message has a "type" and a "figure_id". message = json.loads(message) if message['type'] == 'supports_binary': self.supports_binary = message['value'] else: manager = self.application.manager manager.handle_json(message) def send_json(self, content): self.write_message(json.dumps(content)) def send_binary(self, blob): if self.supports_binary: self.write_message(blob, binary=True) else: data_uri = ("data:image/png;base64," + blob.encode('base64').replace('\n', '')) self.write_message(data_uri) def __init__(self, figure): self.figure = figure self.manager = new_figure_manager_given_figure(id(figure), figure) super().__init__([ # Static files for the CSS and JS (r'/_static/(.*)', tornado.web.StaticFileHandler, {'path': FigureManagerWebAgg.get_static_file_path()}), # Static images for the toolbar (r'/_images/(.*)', tornado.web.StaticFileHandler, {'path': Path(mpl.get_data_path(), 'images')}), # The page that contains all of the pieces ('/', self.MainPage), ('/mpl.js', self.MplJs), # Sends images and events to the browser, and receives # events from the browser ('/ws', self.WebSocket), # Handles the downloading (i.e., saving) of static images (r'/download.([a-z0-9.]+)', self.Download), ]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', type=int, default=8080, help='Port to listen on (0 for a random port).') args = parser.parse_args() figure = create_figure() application = MyApplication(figure) http_server = tornado.httpserver.HTTPServer(application) sockets = tornado.netutil.bind_sockets(args.port, '') http_server.add_sockets(sockets) for s in sockets: addr, port = s.getsockname()[:2] if s.family is socket.AF_INET6: addr = f'[{addr}]' print(f"Listening on http://{addr}:{port}/") print("Press Ctrl+C to quit") ioloop = tornado.ioloop.IOLoop.instance() def shutdown(): ioloop.stop() print("Server stopped") old_handler = signal.signal( signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(shutdown)) try: ioloop.start() finally: signal.signal(signal.SIGINT, old_handler)
MyApplication
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/snap/snap.py
{ "start": 7731, "end": 7993 }
class ____: name: str partitions: PartitionsSnap @whitelist_for_serdes( storage_name="ExternalMultiPartitionsDefinitionData", storage_field_names={"partition_dimensions": "external_partition_dimension_definitions"}, ) @record
PartitionDimensionSnap
python
huggingface__transformers
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
{ "start": 50356, "end": 53961 }
class ____(XLMRobertaPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) self.roberta = XLMRobertaModel(config, add_pooling_layer=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]: r""" token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value >= 2. All the value in this tensor should be always < type_vocab_size. [What are token type IDs?](../glossary#token-type-ids) """ outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, return_dict=True, **kwargs, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "XLMRobertaForCausalLM", "XLMRobertaForMaskedLM", "XLMRobertaForMultipleChoice", "XLMRobertaForQuestionAnswering", "XLMRobertaForSequenceClassification", "XLMRobertaForTokenClassification", "XLMRobertaModel", "XLMRobertaPreTrainedModel", ]
XLMRobertaForQuestionAnswering
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 47952, "end": 55526 }
class ____(ScalarFormatter): """ Format axis values using engineering prefixes to represent powers of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7. """ # The SI engineering prefixes ENG_PREFIXES = { -30: "q", -27: "r", -24: "y", -21: "z", -18: "a", -15: "f", -12: "p", -9: "n", -6: "\N{MICRO SIGN}", -3: "m", 0: "", 3: "k", 6: "M", 9: "G", 12: "T", 15: "P", 18: "E", 21: "Z", 24: "Y", 27: "R", 30: "Q" } def __init__(self, unit="", places=None, sep=" ", *, usetex=None, useMathText=None, useOffset=False): r""" Parameters ---------- unit : str, default: "" Unit symbol to use, suitable for use with single-letter representations of powers of 1000. For example, 'Hz' or 'm'. places : int, default: None Precision with which to display the number, specified in digits after the decimal point (there will be between one and three digits before the decimal point). If it is None, the formatting falls back to the floating point format '%g', which displays up to 6 *significant* digits, i.e. the equivalent value for *places* varies between 0 and 5 (inclusive). sep : str, default: " " Separator used between the value and the prefix/unit. For example, one get '3.14 mV' if ``sep`` is " " (default) and '3.14mV' if ``sep`` is "". Besides the default behavior, some other useful options may be: * ``sep=""`` to append directly the prefix/unit to the value; * ``sep="\N{THIN SPACE}"`` (``U+2009``); * ``sep="\N{NARROW NO-BREAK SPACE}"`` (``U+202F``); * ``sep="\N{NO-BREAK SPACE}"`` (``U+00A0``). usetex : bool, default: :rc:`text.usetex` To enable/disable the use of TeX's math mode for rendering the numbers in the formatter. useMathText : bool, default: :rc:`axes.formatter.use_mathtext` To enable/disable the use mathtext for rendering the numbers in the formatter. useOffset : bool or float, default: False Whether to use offset notation with :math:`10^{3*N}` based prefixes. This features allows showing an offset with standard SI order of magnitude prefix near the axis. Offset is computed similarly to how `ScalarFormatter` computes it internally, but here you are guaranteed to get an offset which will make the tick labels exceed 3 digits. See also `.set_useOffset`. .. versionadded:: 3.10 """ self.unit = unit self.places = places self.sep = sep super().__init__( useOffset=useOffset, useMathText=useMathText, useLocale=False, usetex=usetex, ) def __call__(self, x, pos=None): """ Return the format for tick value *x* at position *pos*. If there is no currently offset in the data, it returns the best engineering formatting that fits the given argument, independently. """ if len(self.locs) == 0 or self.offset == 0: return self.fix_minus(self.format_data(x)) else: xp = (x - self.offset) / (10. ** self.orderOfMagnitude) if abs(xp) < 1e-8: xp = 0 return self._format_maybe_minus_and_locale(self.format, xp) def set_locs(self, locs): # docstring inherited self.locs = locs if len(self.locs) > 0: vmin, vmax = sorted(self.axis.get_view_interval()) if self._useOffset: self._compute_offset() if self.offset != 0: # We don't want to use the offset computed by # self._compute_offset because it rounds the offset unaware # of our engineering prefixes preference, and this can # cause ticks with 4+ digits to appear. These ticks are # slightly less readable, so if offset is justified # (decided by self._compute_offset) we set it to better # value: self.offset = round((vmin + vmax)/2, 3) # Use log1000 to use engineers' oom standards self.orderOfMagnitude = math.floor(math.log(vmax - vmin, 1000))*3 self._set_format() # Simplify a bit ScalarFormatter.get_offset: We always want to use # self.format_data. Also we want to return a non-empty string only if there # is an offset, no matter what is self.orderOfMagnitude. If there _is_ an # offset, self.orderOfMagnitude is consulted. This behavior is verified # in `test_ticker.py`. def get_offset(self): # docstring inherited if len(self.locs) == 0: return '' if self.offset: offsetStr = '' if self.offset: offsetStr = self.format_data(self.offset) if self.offset > 0: offsetStr = '+' + offsetStr sciNotStr = self.format_data(10 ** self.orderOfMagnitude) if self._useMathText or self._usetex: if sciNotStr != '': sciNotStr = r'\times%s' % sciNotStr s = f'${sciNotStr}{offsetStr}$' else: s = sciNotStr + offsetStr return self.fix_minus(s) return '' def format_eng(self, num): """Alias to EngFormatter.format_data""" return self.format_data(num) def format_data(self, value): """ Format a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples: >>> format_data(0) # for self.places = 0 '0' >>> format_data(1000000) # for self.places = 1 '1.0 M' >>> format_data(-1e-6) # for self.places = 2 '-1.00 \N{MICRO SIGN}' """ sign = 1 fmt = "g" if self.places is None else f".{self.places:d}f" if value < 0: sign = -1 value = -value if value != 0: pow10 = int(math.floor(math.log10(value) / 3) * 3) else: pow10 = 0 # Force value to zero, to avoid inconsistencies like # format_eng(-0) = "0" and format_eng(0.0) = "0" # but format_eng(-0.0) = "-0.0" value = 0.0 pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) mant = sign * value / (10.0 ** pow10) # Taking care of the cases like 999.9..., which may be rounded to 1000 # instead of 1 k. Beware of the corner case of values that are beyond # the range of SI prefixes (i.e. > 'Y'). if (abs(float(format(mant, fmt))) >= 1000 and pow10 < max(self.ENG_PREFIXES)): mant /= 1000 pow10 += 3 unit_prefix = self.ENG_PREFIXES[int(pow10)] if self.unit or unit_prefix: suffix = f"{self.sep}{unit_prefix}{self.unit}" else: suffix = "" if self._usetex or self._useMathText: return f"${mant:{fmt}}${suffix}" else: return f"{mant:{fmt}}{suffix}"
EngFormatter
python
django__django
tests/builtin_server/tests.py
{ "start": 5667, "end": 6198 }
class ____(TestCase): """ The ServerHandler chunks data properly. Tests for #18972: The logic that performs the math to break data into 32MB (MAX_SOCKET_CHUNK_SIZE) chunks was flawed, BUT it didn't actually cause any problems. """ def test_chunked_data(self): env = {"SERVER_PROTOCOL": "HTTP/1.0"} handler = WriteChunkCounterHandler(None, BytesIO(), BytesIO(), env) handler.run(send_big_data_app) self.assertEqual(handler.write_chunk_counter, 2)
ServerHandlerChunksProperly
python
wandb__wandb
wandb/sdk/artifacts/_generated/fragments.py
{ "start": 3861, "end": 3945 }
class ____(GQLResult): file: DeferredManifestFragmentFile
DeferredManifestFragment
python
plotly__plotly.py
plotly/graph_objs/bar/_error_y.py
{ "start": 233, "end": 14355 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "bar" _path_str = "bar.error_y" _valid_props = { "array", "arrayminus", "arrayminussrc", "arraysrc", "color", "symmetric", "thickness", "traceref", "tracerefminus", "type", "value", "valueminus", "visible", "width", } @property def array(self): """ Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. The 'array' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["array"] @array.setter def array(self, val): self["array"] = val @property def arrayminus(self): """ Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. The 'arrayminus' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["arrayminus"] @arrayminus.setter def arrayminus(self, val): self["arrayminus"] = val @property def arrayminussrc(self): """ Sets the source reference on Chart Studio Cloud for `arrayminus`. The 'arrayminussrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["arrayminussrc"] @arrayminussrc.setter def arrayminussrc(self, val): self["arrayminussrc"] = val @property def arraysrc(self): """ Sets the source reference on Chart Studio Cloud for `array`. The 'arraysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["arraysrc"] @arraysrc.setter def arraysrc(self, val): self["arraysrc"] = val @property def color(self): """ Sets the stroke color of the error bars. 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 symmetric(self): """ Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. The 'symmetric' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["symmetric"] @symmetric.setter def symmetric(self, val): self["symmetric"] = val @property def thickness(self): """ Sets the thickness (in px) of the error bars. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val @property def traceref(self): """ The 'traceref' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["traceref"] @traceref.setter def traceref(self, val): self["traceref"] = val @property def tracerefminus(self): """ The 'tracerefminus' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["tracerefminus"] @tracerefminus.setter def tracerefminus(self, val): self["tracerefminus"] = val @property def type(self): """ Determines the rule used to generate the error bars. If "constant", the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the square of the underlying data. If "data", the bar lengths are set with data set `array`. The 'type' property is an enumeration that may be specified as: - One of the following enumeration values: ['percent', 'constant', 'sqrt', 'data'] Returns ------- Any """ return self["type"] @type.setter def type(self, val): self["type"] = val @property def value(self): """ Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars. The 'value' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["value"] @value.setter def value(self, val): self["value"] = val @property def valueminus(self): """ Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars The 'valueminus' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["valueminus"] @valueminus.setter def valueminus(self, val): self["valueminus"] = val @property def visible(self): """ Determines whether or not this set of error bars is visible. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val @property def width(self): """ Sets the width (in px) of the cross-bar at both ends of the error bars. The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["width"] @width.setter def width(self, val): self["width"] = val @property def _prop_descriptions(self): return """\ array Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. arrayminus Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. arrayminussrc Sets the source reference on Chart Studio Cloud for `arrayminus`. arraysrc Sets the source reference on Chart Studio Cloud for `array`. color Sets the stroke color of the error bars. symmetric Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. thickness Sets the thickness (in px) of the error bars. traceref tracerefminus type Determines the rule used to generate the error bars. If "constant", the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the square of the underlying data. If "data", the bar lengths are set with data set `array`. value Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars. valueminus Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars visible Determines whether or not this set of error bars is visible. width Sets the width (in px) of the cross-bar at both ends of the error bars. """ def __init__( self, arg=None, array=None, arrayminus=None, arrayminussrc=None, arraysrc=None, color=None, symmetric=None, thickness=None, traceref=None, tracerefminus=None, type=None, value=None, valueminus=None, visible=None, width=None, **kwargs, ): """ Construct a new ErrorY object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bar.ErrorY` array Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. arrayminus Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. arrayminussrc Sets the source reference on Chart Studio Cloud for `arrayminus`. arraysrc Sets the source reference on Chart Studio Cloud for `array`. color Sets the stroke color of the error bars. symmetric Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. thickness Sets the thickness (in px) of the error bars. traceref tracerefminus type Determines the rule used to generate the error bars. If "constant", the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the square of the underlying data. If "data", the bar lengths are set with data set `array`. value Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars. valueminus Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars visible Determines whether or not this set of error bars is visible. width Sets the width (in px) of the cross-bar at both ends of the error bars. Returns ------- ErrorY """ super().__init__("error_y") 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.ErrorY constructor must be a dict or an instance of :class:`plotly.graph_objs.bar.ErrorY`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("array", arg, array) self._set_property("arrayminus", arg, arrayminus) self._set_property("arrayminussrc", arg, arrayminussrc) self._set_property("arraysrc", arg, arraysrc) self._set_property("color", arg, color) self._set_property("symmetric", arg, symmetric) self._set_property("thickness", arg, thickness) self._set_property("traceref", arg, traceref) self._set_property("tracerefminus", arg, tracerefminus) self._set_property("type", arg, type) self._set_property("value", arg, value) self._set_property("valueminus", arg, valueminus) self._set_property("visible", arg, visible) self._set_property("width", arg, width) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
ErrorY
python
pytorch__pytorch
test/ao/sparsity/test_structured_sparsifier.py
{ "start": 2142, "end": 4963 }
class ____(TestCase): def test_saliency_pruner_update_mask(self): """Test that we prune out the row with the lowest saliency (first row)""" model = SimpleLinear() with torch.no_grad(): model.linear1.weight = nn.Parameter( torch.Tensor([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]) ) pruning_config = [{"tensor_fqn": "linear1.weight", "sparsity_level": 0.5}] pruner = SaliencyPruner({}) pruner.prepare(model, pruning_config) pruner.enable_mask_update = True pruner.step() pruned_model = pruner.prune() expected = torch.Tensor([[3, 3, 3, 3], [4, 4, 4, 4]]) pruned = pruned_model.linear1.weight assert expected.shape == pruned.shape assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all() def test_lstm_saliency_pruner_update_mask(self): model = LSTMLinearModel( input_dim=2, hidden_dim=2, output_dim=2, num_layers=1, ) manual_weights = torch.Tensor( [[1, 1], [2, 2], [2, 2], [1, 1], [-1, -1], [-2, -2], [-2, -2], [-1, -1]] ) with torch.no_grad(): model.lstm.weight_ih_l0 = nn.Parameter(manual_weights) model.lstm.weight_hh_l0 = nn.Parameter(torch.Tensor(manual_weights)) model.lstm.bias_ih_l0 = nn.Parameter(manual_weights[:, 0]) model.lstm.bias_hh_l0 = nn.Parameter(manual_weights[:, 0]) config = [ {"tensor_fqn": "lstm.weight_ih_l0"}, {"tensor_fqn": "lstm.weight_hh_l0"}, ] lstm_input = torch.ones((1, 2)) fx_pruner = LSTMSaliencyPruner({"sparsity_level": 0.5}) fx_pruner.prepare(model, config) fx_pruner.enable_mask_update = True fx_pruner.step() model.eval() pruned_model = fx_pruner.prune() pruned_model.eval() # make sure both models run model(lstm_input) pruned_model(lstm_input) # make sure lowest saliency rows are pruned expected = torch.Tensor([[2, 2], [2, 2], [-2, -2], [-2, -2]]) pruned = model.lstm.weight_ih_l0 assert expected.shape == pruned.shape assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all() expected = torch.Tensor([[2], [2], [-2], [-2]]) pruned = model.lstm.weight_hh_l0 assert expected.shape == pruned.shape assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all() expected = torch.Tensor([2, 2, -2, -2]) for pruned in [model.lstm.bias_ih_l0, model.lstm.bias_hh_l0]: assert expected.shape == pruned.shape assert torch.isclose(expected, pruned, rtol=1e-05, atol=1e-07).all()
TestSaliencyPruner
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 36780, "end": 37728 }
class ____(TestCase): def test_choices_named_group(self): class Model(models.Model): field = models.UUIDField( choices=[ [ "knights", [ [ uuid.UUID("5c859437-d061-4847-b3f7-e6b78852f8c8"), "Lancelot", ], [ uuid.UUID("c7853ec1-2ea3-4359-b02d-b54e8f1bcee2"), "Galahad", ], ], ], [uuid.UUID("25d405be-4895-4d50-9b2e-d6695359ce47"), "Other"], ], ) self.assertEqual(Model._meta.get_field("field").check(), []) @isolate_apps("invalid_models_tests") @skipUnlessDBFeature("supports_json_field")
UUIDFieldTests
python
getsentry__sentry
fixtures/sudo_testutils.py
{ "start": 426, "end": 496 }
class ____(StubPasswordBackend): password = "foo"
FooPasswordBackend
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/psycopg.py
{ "start": 11196, "end": 20203 }
class ____(_PGDialect_common_psycopg): driver = "psycopg" supports_statement_cache = True supports_server_side_cursors = True default_paramstyle = "pyformat" supports_sane_multi_rowcount = True execution_ctx_cls = PGExecutionContext_psycopg statement_compiler = PGCompiler_psycopg preparer = PGIdentifierPreparer_psycopg psycopg_version = (0, 0) _has_native_hstore = True _psycopg_adapters_map = None colspecs = util.update_copy( _PGDialect_common_psycopg.colspecs, { sqltypes.String: _PGString, REGCONFIG: _PGREGCONFIG, JSON: _PGJSON, CITEXT: CITEXT, sqltypes.JSON: _PGJSON, JSONB: _PGJSONB, sqltypes.JSON.JSONPathType: _PGJSONPathType, sqltypes.JSON.JSONIntIndexType: _PGJSONIntIndexType, sqltypes.JSON.JSONStrIndexType: _PGJSONStrIndexType, sqltypes.Interval: _PGInterval, INTERVAL: _PGInterval, sqltypes.Date: _PGDate, sqltypes.DateTime: _PGTimeStamp, sqltypes.Time: _PGTime, sqltypes.Integer: _PGInteger, sqltypes.SmallInteger: _PGSmallInteger, sqltypes.BigInteger: _PGBigInteger, ranges.AbstractSingleRange: _PsycopgRange, ranges.AbstractMultiRange: _PsycopgMultiRange, }, ) def __init__(self, **kwargs): super().__init__(**kwargs) if self.dbapi: m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", self.dbapi.__version__) if m: self.psycopg_version = tuple( int(x) for x in m.group(1, 2, 3) if x is not None ) if self.psycopg_version < (3, 0, 2): raise ImportError( "psycopg version 3.0.2 or higher is required." ) from psycopg.adapt import AdaptersMap self._psycopg_adapters_map = adapters_map = AdaptersMap( self.dbapi.adapters ) if self._native_inet_types is False: import psycopg.types.string adapters_map.register_loader( "inet", psycopg.types.string.TextLoader ) adapters_map.register_loader( "cidr", psycopg.types.string.TextLoader ) if self._json_deserializer: from psycopg.types.json import set_json_loads set_json_loads(self._json_deserializer, adapters_map) if self._json_serializer: from psycopg.types.json import set_json_dumps set_json_dumps(self._json_serializer, adapters_map) def create_connect_args(self, url): # see https://github.com/psycopg/psycopg/issues/83 cargs, cparams = super().create_connect_args(url) if self._psycopg_adapters_map: cparams["context"] = self._psycopg_adapters_map if self.client_encoding is not None: cparams["client_encoding"] = self.client_encoding return cargs, cparams def _type_info_fetch(self, connection, name): from psycopg.types import TypeInfo return TypeInfo.fetch(connection.connection.driver_connection, name) def initialize(self, connection): super().initialize(connection) # PGDialect.initialize() checks server version for <= 8.2 and sets # this flag to False if so if not self.insert_returning: self.insert_executemany_returning = False # HSTORE can't be registered until we have a connection so that # we can look up its OID, so we set up this adapter in # initialize() if self.use_native_hstore: info = self._type_info_fetch(connection, "hstore") self._has_native_hstore = info is not None if self._has_native_hstore: from psycopg.types.hstore import register_hstore # register the adapter for connections made subsequent to # this one assert self._psycopg_adapters_map register_hstore(info, self._psycopg_adapters_map) # register the adapter for this connection assert connection.connection register_hstore(info, connection.connection.driver_connection) @classmethod def import_dbapi(cls): import psycopg return psycopg @classmethod def get_async_dialect_cls(cls, url): return PGDialectAsync_psycopg @util.memoized_property def _isolation_lookup(self): return { "READ COMMITTED": self.dbapi.IsolationLevel.READ_COMMITTED, "READ UNCOMMITTED": self.dbapi.IsolationLevel.READ_UNCOMMITTED, "REPEATABLE READ": self.dbapi.IsolationLevel.REPEATABLE_READ, "SERIALIZABLE": self.dbapi.IsolationLevel.SERIALIZABLE, } @util.memoized_property def _psycopg_Json(self): from psycopg.types import json return json.Json @util.memoized_property def _psycopg_Jsonb(self): from psycopg.types import json return json.Jsonb @util.memoized_property def _psycopg_TransactionStatus(self): from psycopg.pq import TransactionStatus return TransactionStatus @util.memoized_property def _psycopg_Range(self): from psycopg.types.range import Range return Range @util.memoized_property def _psycopg_Multirange(self): from psycopg.types.multirange import Multirange return Multirange def _do_isolation_level(self, connection, autocommit, isolation_level): connection.autocommit = autocommit connection.isolation_level = isolation_level def get_isolation_level(self, dbapi_connection): status_before = dbapi_connection.info.transaction_status value = super().get_isolation_level(dbapi_connection) # don't rely on psycopg providing enum symbols, compare with # eq/ne if status_before == self._psycopg_TransactionStatus.IDLE: dbapi_connection.rollback() return value def set_isolation_level(self, dbapi_connection, level): if level == "AUTOCOMMIT": self._do_isolation_level( dbapi_connection, autocommit=True, isolation_level=None ) else: self._do_isolation_level( dbapi_connection, autocommit=False, isolation_level=self._isolation_lookup[level], ) def set_readonly(self, connection, value): connection.read_only = value def get_readonly(self, connection): return connection.read_only def on_connect(self): def notices(conn): conn.add_notice_handler(_log_notices) fns = [notices] if self.isolation_level is not None: def on_connect(conn): self.set_isolation_level(conn, self.isolation_level) fns.append(on_connect) # fns always has the notices function def on_connect(conn): for fn in fns: fn(conn) return on_connect def is_disconnect(self, e, connection, cursor): if isinstance(e, self.dbapi.Error) and connection is not None: if connection.closed or connection.broken: return True return False def _do_prepared_twophase(self, connection, command, recover=False): dbapi_conn = connection.connection.dbapi_connection if ( recover # don't rely on psycopg providing enum symbols, compare with # eq/ne or dbapi_conn.info.transaction_status != self._psycopg_TransactionStatus.IDLE ): dbapi_conn.rollback() before_autocommit = dbapi_conn.autocommit try: if not before_autocommit: self._do_autocommit(dbapi_conn, True) with dbapi_conn.cursor() as cursor: cursor.execute(command) finally: if not before_autocommit: self._do_autocommit(dbapi_conn, before_autocommit) def do_rollback_twophase( self, connection, xid, is_prepared=True, recover=False ): if is_prepared: self._do_prepared_twophase( connection, f"ROLLBACK PREPARED '{xid}'", recover=recover ) else: self.do_rollback(connection.connection) def do_commit_twophase( self, connection, xid, is_prepared=True, recover=False ): if is_prepared: self._do_prepared_twophase( connection, f"COMMIT PREPARED '{xid}'", recover=recover ) else: self.do_commit(connection.connection) @util.memoized_property def _dialect_specific_select_one(self): return ";"
PGDialect_psycopg
python
tensorflow__tensorflow
tensorflow/python/distribute/input_lib_test.py
{ "start": 66581, "end": 76630 }
class ____(DistributedIteratorTestBase, parameterized.TestCase): """Tests for PER_WORKER and PER_REPLICA's InputOptions variants.""" @combinations.generate( combinations.combine( input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=True, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_WORKER), distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=True, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_REPLICA), ], mode=["eager"], distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ])) def testDevicePlacementForPerWorkerValuesWithPrefetch(self, distribution, input_options): def dataset_fn(input_context): # pylint: disable=[unused-argument] return dataset_ops.Dataset.from_tensor_slices([1, 2, 3, 4]) ds = distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) for x in ds: assert x.values[0].device == distribution.extended.worker_devices[0] assert x.values[0].backing_device == distribution.extended.worker_devices[ 0] assert x.values[1].device == distribution.extended.worker_devices[1] assert x.values[1].backing_device == distribution.extended.worker_devices[ 1] @combinations.generate( combinations.combine( distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ], input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=False, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_WORKER) ], mode=["eager"], )) def testDevicePlacementForPerWorkerValuesWithoutPrefetch( self, distribution, input_options): def dataset_fn(input_context): return dataset_ops.Dataset.from_tensor_slices( np.full(4, input_context.input_pipeline_id)) ds = distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) for x in ds: x = distribution.run(lambda inputs: inputs, args=(x,)) assert x.values[ 0].device == "/job:localhost/replica:0/task:0/device:CPU:0" assert x.values[ 0].backing_device == "/job:localhost/replica:0/task:0/device:CPU:0" assert x.values[ 1].device == "/job:localhost/replica:0/task:0/device:CPU:0" assert x.values[ 1].backing_device == "/job:localhost/replica:0/task:0/device:CPU:0" @combinations.generate( combinations.combine( input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=True, experimental_fetch_to_device=False, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_WORKER), distribute_lib.InputOptions( experimental_place_dataset_on_device=True, experimental_fetch_to_device=True, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_REPLICA) ], mode=["eager"], distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ])) def testDevicePlacementForInvalidCombinations(self, distribution, input_options): def dataset_fn(input_context): return dataset_ops.Dataset.from_tensor_slices( np.full(4, input_context.input_pipeline_id)) with self.assertRaises(ValueError): distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) @combinations.generate( combinations.combine( input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=False, experimental_per_replica_buffer_size=2), distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=True, experimental_per_replica_buffer_size=2), ], mode=["eager"], distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ])) def testPrefetchBufferSizeInputOptions(self, distribution, input_options): def dataset_fn(input_context): return dataset_ops.Dataset.from_tensor_slices( np.arange(1, 11).reshape( (2, 5)) * (input_context.input_pipeline_id + 1)) ds = distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) # validating the values x = next(iter(ds)) assert np.array_equal(x.values[0].numpy(), np.array([1, 2, 3, 4, 5])) assert np.array_equal(x.values[1].numpy(), np.array([6, 7, 8, 9, 10])) @combinations.generate( combinations.combine( input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=False, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_WORKER), distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=True, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_WORKER), ], mode=["eager"], distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ])) def testOutputValuesForPerWorkerInputOptions(self, distribution, input_options): def dataset_fn(input_context): return dataset_ops.Dataset.from_tensor_slices( np.arange(1, 11).reshape( (2, 5)) * (input_context.input_pipeline_id + 1)) ds = distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) # validating the values x = next(iter(ds)) assert np.array_equal(x.values[0].numpy(), np.array([1, 2, 3, 4, 5])) assert np.array_equal(x.values[1].numpy(), np.array([6, 7, 8, 9, 10])) @combinations.generate( combinations.combine( input_options=[ distribute_lib.InputOptions( experimental_place_dataset_on_device=True, experimental_fetch_to_device=False, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_REPLICA), distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=False, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_REPLICA), distribute_lib.InputOptions( experimental_place_dataset_on_device=False, experimental_fetch_to_device=True, experimental_replication_mode=distribute_lib .InputReplicationMode.PER_REPLICA), ], mode=["eager"], distribution=[ strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations .mirrored_strategy_with_two_gpus_no_merge_call, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, ])) def testOutputValuesForPerReplicaInputOptions(self, distribution, input_options): def dataset_fn(input_context): return dataset_ops.Dataset.from_tensor_slices( np.arange(1, 10) * (input_context.input_pipeline_id + 1)) ds = distribution.experimental_distribute_datasets_from_function( dataset_fn, input_options) expected = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) for i, x in enumerate(ds): # validating the values assert x.values[0].numpy() == expected[i] assert x.values[1].numpy() == expected[i] * 2 loop_num = i assert loop_num == len(expected) - 1
DistributedIteratorPerDeviceTest
python
python-attrs__attrs
src/attr/_make.py
{ "start": 94233, "end": 101670 }
class ____: """ Stores a converter callable. Allows for the wrapped converter to take additional arguments. The arguments are passed in the order they are documented. Args: converter (Callable): A callable that converts the passed value. takes_self (bool): Pass the partially initialized instance that is being initialized as a positional argument. (default: `False`) takes_field (bool): Pass the field definition (an :class:`Attribute`) into the converter as a positional argument. (default: `False`) .. versionadded:: 24.1.0 """ __slots__ = ( "__call__", "_first_param_type", "_global_name", "converter", "takes_field", "takes_self", ) def __init__(self, converter, *, takes_self=False, takes_field=False): self.converter = converter self.takes_self = takes_self self.takes_field = takes_field ex = _AnnotationExtractor(converter) self._first_param_type = ex.get_first_param_type() if not (self.takes_self or self.takes_field): self.__call__ = lambda value, _, __: self.converter(value) elif self.takes_self and not self.takes_field: self.__call__ = lambda value, instance, __: self.converter( value, instance ) elif not self.takes_self and self.takes_field: self.__call__ = lambda value, __, field: self.converter( value, field ) else: self.__call__ = lambda value, instance, field: self.converter( value, instance, field ) rt = ex.get_return_type() if rt is not None: self.__call__.__annotations__["return"] = rt @staticmethod def _get_global_name(attr_name: str) -> str: """ Return the name that a converter for an attribute name *attr_name* would have. """ return f"__attr_converter_{attr_name}" def _fmt_converter_call(self, attr_name: str, value_var: str) -> str: """ Return a string that calls the converter for an attribute name *attr_name* and the value in variable named *value_var* according to `self.takes_self` and `self.takes_field`. """ if not (self.takes_self or self.takes_field): return f"{self._get_global_name(attr_name)}({value_var})" if self.takes_self and self.takes_field: return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])" if self.takes_self: return f"{self._get_global_name(attr_name)}({value_var}, self)" return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])" def __getstate__(self): """ Return a dict containing only converter and takes_self -- the rest gets computed when loading. """ return { "converter": self.converter, "takes_self": self.takes_self, "takes_field": self.takes_field, } def __setstate__(self, state): """ Load instance from state. """ self.__init__(**state) _f = [ Attribute( name=name, default=NOTHING, validator=None, repr=True, cmp=None, eq=True, order=False, hash=True, init=True, inherited=False, ) for name in ("converter", "takes_self", "takes_field") ] Converter = _add_hash( _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f ) def make_class( name, attrs, bases=(object,), class_body=None, **attributes_arguments ): r""" A quick way to create a new class called *name* with *attrs*. .. note:: ``make_class()`` is a thin wrapper around `attr.s`, not `attrs.define` which means that it doesn't come with some of the improved defaults. For example, if you want the same ``on_setattr`` behavior as in `attrs.define`, you have to pass the hooks yourself: ``make_class(..., on_setattr=setters.pipe(setters.convert, setters.validate)`` .. warning:: It is *your* duty to ensure that the class name and the attribute names are valid identifiers. ``make_class()`` will *not* validate them for you. Args: name (str): The name for the new class. attrs (list | dict): A list of names or a dictionary of mappings of names to `attr.ib`\ s / `attrs.field`\ s. The order is deduced from the order of the names or attributes inside *attrs*. Otherwise the order of the definition of the attributes is used. bases (tuple[type, ...]): Classes that the new class will subclass. class_body (dict): An optional dictionary of class attributes for the new class. attributes_arguments: Passed unmodified to `attr.s`. Returns: type: A new class with *attrs*. .. versionadded:: 17.1.0 *bases* .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. .. versionchanged:: 23.2.0 *class_body* .. versionchanged:: 25.2.0 Class names can now be unicode. """ # Class identifiers are converted into the normal form NFKC while parsing name = unicodedata.normalize("NFKC", name) if isinstance(attrs, dict): cls_dict = attrs elif isinstance(attrs, (list, tuple)): cls_dict = {a: attrib() for a in attrs} else: msg = "attrs argument must be a dict or a list." raise TypeError(msg) pre_init = cls_dict.pop("__attrs_pre_init__", None) post_init = cls_dict.pop("__attrs_post_init__", None) user_init = cls_dict.pop("__init__", None) body = {} if class_body is not None: body.update(class_body) if pre_init is not None: body["__attrs_pre_init__"] = pre_init if post_init is not None: body["__attrs_post_init__"] = post_init if user_init is not None: body["__init__"] = user_init type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body)) # For pickling to work, the __module__ variable needs to be set to the # frame where the class is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython). with contextlib.suppress(AttributeError, ValueError): type_.__module__ = sys._getframe(1).f_globals.get( "__name__", "__main__" ) # We do it here for proper warnings with meaningful stacklevel. cmp = attributes_arguments.pop("cmp", None) ( attributes_arguments["eq"], attributes_arguments["order"], ) = _determine_attrs_eq_order( cmp, attributes_arguments.get("eq"), attributes_arguments.get("order"), True, ) cls = _attrs(these=cls_dict, **attributes_arguments)(type_) # Only add type annotations now or "_attrs()" will complain: cls.__annotations__ = { k: v.type for k, v in cls_dict.items() if v.type is not None } return cls # These are required by within this module so we define them here and merely # import into .validators / .converters. @attrs(slots=True, unsafe_hash=True)
Converter
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/global_.py
{ "start": 33, "end": 203 }
class ____(BaseModel): postgresqlSecretName: str dagsterHome: str serviceAccountName: str celeryConfigSecretName: str dagsterInstanceConfigMap: str
Global
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 8368, "end": 8428 }
class ____(GISLookup): lookup_name = "within"
WithinLookup
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-make-the-array-increasing.py
{ "start": 29, "end": 387 }
class ____(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ result = prev = 0 for curr in nums: if prev < curr: prev = curr continue prev += 1 result += prev-curr return result
Solution
python
plotly__plotly.py
plotly/graph_objs/histogram2dcontour/legendgrouptitle/_font.py
{ "start": 233, "end": 9982 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram2dcontour.legendgrouptitle" _path_str = "histogram2dcontour.legendgrouptitle.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 legend group's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram2dcon tour.legendgrouptitle.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.histogram2dcontour.legendgrouptitle.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.histogram2dcontour.legendgrouptitle.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
django-haystack__django-haystack
haystack/exceptions.py
{ "start": 916, "end": 1028 }
class ____(HaystackError): "Raised when incorrect arguments have been provided for stats" pass
StatsError
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1180789, "end": 1180988 }
class ____(VegaLiteSchema): """ShapeDef schema wrapper.""" _schema = {"$ref": "#/definitions/ShapeDef"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ShapeDef
python
lazyprogrammer__machine_learning_examples
nlp_class2/recursive_theano.py
{ "start": 1016, "end": 9927 }
class ____: def __init__(self, V, D, K): self.V = V self.D = D self.K = K def fit(self, trees, learning_rate=3*1e-3, mu=0.99, reg=1e-4, epochs=15, activation=T.nnet.relu, train_inner_nodes=False): D = self.D V = self.V K = self.K self.f = activation N = len(trees) We = init_weight(V, D) Wh = np.random.randn(2, D, D) / np.sqrt(2 + D + D) bh = np.zeros(D) Wo = init_weight(D, K) bo = np.zeros(K) self.We = theano.shared(We) self.Wh = theano.shared(Wh) self.bh = theano.shared(bh) self.Wo = theano.shared(Wo) self.bo = theano.shared(bo) self.params = [self.We, self.Wh, self.bh, self.Wo, self.bo] words = T.ivector('words') parents = T.ivector('parents') relations = T.ivector('relations') labels = T.ivector('labels') def recurrence(n, hiddens, words, parents, relations): w = words[n] # any non-word will have index -1 # if T.ge(w, 0): # hiddens = T.set_subtensor(hiddens[n], self.We[w]) # else: # hiddens = T.set_subtensor(hiddens[n], self.f(hiddens[n] + self.bh)) hiddens = T.switch( T.ge(w, 0), T.set_subtensor(hiddens[n], self.We[w]), T.set_subtensor(hiddens[n], self.f(hiddens[n] + self.bh)) ) r = relations[n] # 0 = is_left, 1 = is_right p = parents[n] # parent idx # if T.ge(p, 0): # # root will have parent -1 # hiddens = T.set_subtensor(hiddens[p], hiddens[p] + hiddens[n].dot(self.Wh[r])) hiddens = T.switch( T.ge(p, 0), T.set_subtensor(hiddens[p], hiddens[p] + hiddens[n].dot(self.Wh[r])), hiddens ) return hiddens hiddens = T.zeros((words.shape[0], D)) h, _ = theano.scan( fn=recurrence, outputs_info=[hiddens], n_steps=words.shape[0], sequences=T.arange(words.shape[0]), non_sequences=[words, parents, relations], ) # shape of h that is returned by scan is TxTxD # because hiddens is TxD, and it does the recurrence T times # technically this stores T times too much data py_x = T.nnet.softmax(h[-1].dot(self.Wo) + self.bo) prediction = T.argmax(py_x, axis=1) rcost = reg*T.mean([(p*p).sum() for p in self.params]) if train_inner_nodes: # won't work for binary classification cost = -T.mean(T.log(py_x[T.arange(labels.shape[0]), labels])) + rcost else: # print "K is:", K # premean = T.log(py_x[-1]) # target = T.zeros(K) # target = T.set_subtensor(target[labels[-1]], 1) # cost = -T.mean(target * premean) cost = -T.mean(T.log(py_x[-1, labels[-1]])) + rcost # grads = T.grad(cost, self.params) # dparams = [theano.shared(p.get_value()*0) for p in self.params] # updates = [ # (p, p + mu*dp - learning_rate*g) for p, dp, g in zip(self.params, dparams, grads) # ] + [ # (dp, mu*dp - learning_rate*g) for dp, g in zip(dparams, grads) # ] updates = adagrad(cost, self.params, lr=8e-3) self.cost_predict_op = theano.function( inputs=[words, parents, relations, labels], outputs=[cost, prediction], allow_input_downcast=True, ) self.train_op = theano.function( inputs=[words, parents, relations, labels], outputs=[h, cost, prediction], updates=updates ) costs = [] sequence_indexes = range(N) if train_inner_nodes: n_total = sum(len(words) for words, _, _, _ in trees) else: n_total = N for i in range(epochs): t0 = datetime.now() sequence_indexes = shuffle(sequence_indexes) n_correct = 0 cost = 0 it = 0 for j in sequence_indexes: words, par, rel, lab = trees[j] _, c, p = self.train_op(words, par, rel, lab) if np.isnan(c): print("Cost is nan! Let's stop here. \ Why don't you try decreasing the learning rate?") exit() cost += c if train_inner_nodes: n_correct += np.sum(p == lab) else: n_correct += (p[-1] == lab[-1]) it += 1 if it % 1 == 0: sys.stdout.write("j/N: %d/%d correct rate so far: %f, cost so far: %f\r" % (it, N, float(n_correct)/n_total, cost)) sys.stdout.flush() print( "i:", i, "cost:", cost, "correct rate:", (float(n_correct)/n_total), "time for epoch:", (datetime.now() - t0) ) costs.append(cost) plt.plot(costs) plt.draw() # don't block later code def score(self, trees, idx2word=None): n_total = len(trees) n_correct = 0 for words, par, rel, lab in trees: _, p = self.cost_predict_op(words, par, rel, lab) n_correct += (p[-1] == lab[-1]) # if idx2word: # print_sentence(words, idx2word) # print("label:", lab[-1], "pred:", p[-1]) print("n_correct:", n_correct, "n_total:", n_total, end=" ") return float(n_correct) / n_total def add_idx_to_tree(tree, current_idx): # post-order labeling of tree nodes if tree is None: return current_idx current_idx = add_idx_to_tree(tree.left, current_idx) current_idx = add_idx_to_tree(tree.right, current_idx) tree.idx = current_idx current_idx += 1 return current_idx def tree2list(tree, parent_idx, is_binary=False, is_left=False, is_right=False): if tree is None: return [], [], [], [] w = tree.word if tree.word is not None else -1 if is_left: r = 0 elif is_right: r = 1 else: r = -1 words_left, parents_left, relations_left, labels_left = tree2list(tree.left, tree.idx, is_binary, is_left=True) words_right, parents_right, relations_right, labels_right = tree2list(tree.right, tree.idx, is_binary, is_right=True) words = words_left + words_right + [w] parents = parents_left + parents_right + [parent_idx] relations = relations_left + relations_right + [r] if is_binary: if tree.label > 2: label = 1 elif tree.label < 2: label = 0 else: label = -1 # we will eventually filter these out else: label = tree.label labels = labels_left + labels_right + [label] return words, parents, relations, labels # def get_sentence(tree): # if tree is None: # return [] # w = [tree.word] if tree.word is not None else [] # return get_sentence(tree.left) + get_sentence(tree.right) + w def print_sentence(words, idx2word): # sentence = ' '.join(get_sentence(tree)) # print(sentence, "label:", tree.label) for w in words: if w >= 0: print(idx2word[w], end=" ") def main(is_binary=True): train, test, word2idx = get_ptb_data() for t in train: add_idx_to_tree(t, 0) train = [tree2list(t, -1, is_binary) for t in train] if is_binary: train = [t for t in train if t[3][-1] >= 0] # for filtering binary labels # sanity check # check that last node has no parent # for t in train: # assert(t[1][-1] == -1 and t[2][-1] == -1) for t in test: add_idx_to_tree(t, 0) test = [tree2list(t, -1, is_binary) for t in test] if is_binary: test = [t for t in test if t[3][-1] >= 0] # for filtering binary labels train = shuffle(train) # train = train[:2000] n_pos = sum(t[3][-1] for t in train) # print("num pos train:", n_pos) # idx2word = {v:k for k, v in word2idx.items()} # for i in range(4): # words, _, _, labels = train[i] # print_sentence(words, idx2word) # print("label:", labels[-1]) test = shuffle(test) test = test[:1000] V = len(word2idx) print("vocab size:", V) D = 10 K = 2 if is_binary else 5 model = RecursiveNN(V, D, K) model.fit(train, learning_rate=1e-2, reg=1e-2, mu=0, epochs=20, activation=T.tanh, train_inner_nodes=False) print("train accuracy:", model.score(train)) print("test accuracy:", model.score(test)) # make sure program doesn't end until we close the plot plt.show() if __name__ == '__main__': main()
RecursiveNN
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar24.py
{ "start": 315, "end": 1316 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar24.xlsx") self.ignore_elements = {"xl/workbook.xml": ["<fileVersion", "<calcPr"]} def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "bar"}) chart.axis_ids = [63591168, 63592704] chart.axis2_ids = [65934464, 72628864] data = [[27, 33, 44, 12, 1], [6, 8, 6, 4, 2]] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) chart.add_series({"values": "=Sheet1!$A$1:$A$5"}) chart.add_series({"values": "=Sheet1!$B$1:$B$5", "y2_axis": 1}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_reflection.py
{ "start": 4733, "end": 7303 }
class ____(fixtures.TablesTest, AssertsExecutionResults): # partitioned table reflection, issue #4237 __only_on__ = "postgresql >= 10" __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): # the actual function isn't reflected yet dv = Table( "data_values", metadata, Column("modulus", Integer, nullable=False), Column("data", String(30)), Column("q", Integer), postgresql_partition_by="range(modulus)", ) # looks like this is reflected prior to #4237 sa.event.listen( dv, "after_create", sa.DDL( "CREATE TABLE data_values_4_10 PARTITION OF data_values " "FOR VALUES FROM (4) TO (10)" ), ) if testing.against("postgresql >= 11"): Index("my_index", dv.c.q) def test_get_tablenames(self, connection): assert {"data_values", "data_values_4_10"}.issubset( inspect(connection).get_table_names() ) def test_reflect_cols(self, connection): cols = inspect(connection).get_columns("data_values") eq_([c["name"] for c in cols], ["modulus", "data", "q"]) def test_reflect_cols_from_partition(self, connection): cols = inspect(connection).get_columns("data_values_4_10") eq_([c["name"] for c in cols], ["modulus", "data", "q"]) @testing.only_on("postgresql >= 11") def test_reflect_index(self, connection): idx = inspect(connection).get_indexes("data_values") eq_( idx, [ { "name": "my_index", "unique": False, "column_names": ["q"], "include_columns": [], "dialect_options": {"postgresql_include": []}, } ], ) @testing.only_on("postgresql >= 11") def test_reflect_index_from_partition(self, connection): idx = inspect(connection).get_indexes("data_values_4_10") # note the name appears to be generated by PG, currently # 'data_values_4_10_q_idx' eq_( idx, [ { "column_names": ["q"], "include_columns": [], "dialect_options": {"postgresql_include": []}, "name": mock.ANY, "unique": False, } ], )
PartitionedReflectionTest
python
huggingface__transformers
tests/utils/test_modeling_utils.py
{ "start": 132425, "end": 135370 }
class ____(TestCasePlus): """ This test checks that a model can be saved and loaded that uses the torch extra state API. https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.get_extra_state. Currently, only tensor-valued extra_states are supported. """ def test_save_and_load_model_with_tensor_extra_state(self): class MyConfig(PreTrainedConfig): def __init__(self, **kwargs): super().__init__(**kwargs) class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.some_counter = 0 self.linear = torch.nn.Linear(320, 320) def get_extra_state(self): return torch.tensor(self.some_counter) def set_extra_state(self, state): self.some_counter = state.item() class MyModel(PreTrainedModel): config_class = MyConfig def __init__(self, config: MyConfig): super().__init__(config) self.my_layer = MyModule() def forward(self, hidden_states, attention_mask): return self.my_layer(hidden_states, attention_mask) config = MyConfig() model = MyModel(config) model.my_layer.some_counter = 42 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model = MyModel.from_pretrained(tmpdirname) self.assertEqual(model.my_layer.some_counter, 42) @mark.xfail(reason="save and from_pretrained currently only supports tensor extra_state") def test_save_and_load_model_with_dict_extra_state(self): class MyConfig(PreTrainedConfig): def __init__(self, **kwargs): super().__init__(**kwargs) class MyModule(torch.nn.Module): def __init__(self): super().__init__() self.some_counter = 0 self.linear = torch.nn.Linear(320, 320) def get_extra_state(self): return {"some_counter": self.some_counter} def set_extra_state(self, state): self.some_counter = state["some_counter"] class MyModel(PreTrainedModel): config_class = MyConfig def __init__(self, config: MyConfig): super().__init__(config) self.my_layer = MyModule() def forward(self, hidden_states, attention_mask): return self.my_layer(hidden_states, attention_mask) config = MyConfig() model = MyModel(config) model.my_layer.some_counter = 42 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model = MyModel.from_pretrained(tmpdirname) self.assertEqual(model.my_layer.some_counter, 42)
TestSaveAndLoadModelWithExtraState
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/conditioning.py
{ "start": 2777, "end": 5134 }
class ____(torch.nn.Module): def __init__( self, input_size, output_size, hyper_input_size, layer_size, num_layers ): """ Hyper Network module. This module will use the hyper_input tensor to generate the weights of the main network. The main network is a single fully connected layer. :param input_size: The size of the input of the main network :param output_size: The size of the output of the main network :param hyper_input_size: The size of the input of the hypernetwork that will generate the main network. :param layer_size: The number of hidden units in the layers of the hypernetwork :param num_layers: The number of layers of the hypernetwork """ super().__init__() self.input_size = input_size self.output_size = output_size layer_in_size = hyper_input_size layers = [] for _ in range(num_layers): layers.append( linear_layer( layer_in_size, layer_size, kernel_init=Initialization.KaimingHeNormal, kernel_gain=1.0, bias_init=Initialization.Zero, ) ) layers.append(Swish()) layer_in_size = layer_size flat_output = linear_layer( layer_size, input_size * output_size, kernel_init=Initialization.KaimingHeNormal, kernel_gain=0.1, bias_init=Initialization.Zero, ) # Re-initializing the weights of the last layer of the hypernetwork bound = math.sqrt(1 / (layer_size * self.input_size)) flat_output.weight.data.uniform_(-bound, bound) self.hypernet = torch.nn.Sequential(*layers, LayerNorm(), flat_output) # The hypernetwork will not generate the bias of the main network layer self.bias = torch.nn.Parameter(torch.zeros(output_size)) def forward(self, input_activation, hyper_input): output_weights = self.hypernet(hyper_input) output_weights = output_weights.view(-1, self.input_size, self.output_size) result = ( torch.bmm(input_activation.unsqueeze(1), output_weights).squeeze(1) + self.bias ) return result
HyperNetwork
python
django-guardian__django-guardian
guardian/testapp/models.py
{ "start": 647, "end": 786 }
class ____(UserObjectPermissionBase): content_object = models.ForeignKey("Project", on_delete=models.CASCADE)
ProjectUserObjectPermission
python
scipy__scipy
benchmarks/benchmarks/signal.py
{ "start": 5259, "end": 5864 }
class ____(Benchmark): param_names = ['up', 'down'] params = [ [1, 4], [1, 4] ] def setup(self, up, down): rng = np.random.default_rng(1234) # sample a bunch of pairs of 2d arrays pairs = [] for nfilt in [8, ]: for n in [32, 128, 512, 2048]: h = rng.standard_normal(nfilt) x = rng.standard_normal(n) pairs.append((h, x)) self.pairs = pairs def time_upfirdn1d(self, up, down): for h, x in self.pairs: signal.upfirdn(h, x, up=up, down=down)
Upfirdn1D
python
PyCQA__pylint
tests/functional/i/invalid/invalid_repr_returned.py
{ "start": 851, "end": 1029 }
class ____: """ __repr__ returns node which does not have 'value' in AST """ def __repr__(self): # [invalid-repr-returned] return lambda: "some repr"
ThirdBadRepr
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_property_types.py
{ "start": 5661, "end": 6281 }
class ____(_ItemProperties): obj_type: Literal['attribute', 'data'] value: object annotation: str class_var: bool instance_var: bool _obj_is_generic_alias: bool _obj_is_attribute_descriptor: bool _obj_is_mock: bool _obj_is_sentinel: ( RUNTIME_INSTANCE_ATTRIBUTE_T | SLOTS_ATTR_T | UNINITIALIZED_ATTR_T | None ) _obj_repr_rst: str _obj_type_annotation: str | None @property def _groupwise_order_key(self) -> int: return 40 if self.obj_type == 'data' else 60 @dataclasses.dataclass(frozen=False, kw_only=True, slots=True)
_AssignStatementProperties
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1512451, "end": 1514857 }
class ____(Transform): """ FilterTransform schema wrapper. Parameters ---------- filter : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :class:`LogicalOrPredicate`, :class:`ParameterPredicate`, :class:`FieldEqualPredicate`, :class:`FieldOneOfPredicate`, :class:`FieldRangePredicate`, :class:`FieldValidPredicate`, :class:`LogicalAndPredicate`, :class:`LogicalNotPredicate`, :class:`PredicateComposition` The ``filter`` property must be a predication definition, which can take one of the following forms: 1) an `expression <https://vega.github.io/vega-lite/docs/types.html#expression>`__ string, where ``datum`` can be used to refer to the current data object. For example, ``{filter: "datum.b2 > 60"}`` would make the output data includes only items that have values in the field ``b2`` over 60. 2) one of the `field predicates <https://vega.github.io/vega-lite/docs/predicate.html#field-predicate>`__: `equal <https://vega.github.io/vega-lite/docs/predicate.html#field-equal-predicate>`__, `lt <https://vega.github.io/vega-lite/docs/predicate.html#lt-predicate>`__, `lte <https://vega.github.io/vega-lite/docs/predicate.html#lte-predicate>`__, `gt <https://vega.github.io/vega-lite/docs/predicate.html#gt-predicate>`__, `gte <https://vega.github.io/vega-lite/docs/predicate.html#gte-predicate>`__, `range <https://vega.github.io/vega-lite/docs/predicate.html#range-predicate>`__, `oneOf <https://vega.github.io/vega-lite/docs/predicate.html#one-of-predicate>`__, or `valid <https://vega.github.io/vega-lite/docs/predicate.html#valid-predicate>`__, 3) a `selection predicate <https://vega.github.io/vega-lite/docs/predicate.html#selection-predicate>`__, which define the names of a selection that the data point should belong to (or a logical composition of selections). 4) a `logical composition <https://vega.github.io/vega-lite/docs/predicate.html#composition>`__ of (1), (2), or (3). """ _schema = {"$ref": "#/definitions/FilterTransform"} def __init__(self, filter: Optional[str | SchemaBase | Map] = Undefined, **kwds): super().__init__(filter=filter, **kwds)
FilterTransform
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-make-word-k-periodic.py
{ "start": 63, "end": 362 }
class ____(object): def minimumOperationsToMakeKPeriodic(self, word, k): """ :type word: str :type k: int :rtype: int """ cnt = collections.Counter(word[i:i+k]for i in xrange(0, len(word), k)) return len(word)//k-max(cnt.itervalues())
Solution
python
doocs__leetcode
solution/0800-0899/0879.Profitable Schemes/Solution2.py
{ "start": 0, "end": 661 }
class ____: def profitableSchemes( self, n: int, minProfit: int, group: List[int], profit: List[int] ) -> int: mod = 10**9 + 7 m = len(group) f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] for j in range(n + 1): f[0][j][0] = 1 for i, (x, p) in enumerate(zip(group, profit), 1): for j in range(n + 1): for k in range(minProfit + 1): f[i][j][k] = f[i - 1][j][k] if j >= x: f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod return f[m][n][minProfit]
Solution
python
run-llama__llama_index
llama-index-core/tests/test_utils.py
{ "start": 996, "end": 9664 }
class ____(Exception): """Exception that contains retry attribute.""" def __init__(self, should_retry: bool) -> None: """Initialize with parameters.""" self.should_retry = should_retry def test_retry_on_exceptions_with_backoff() -> None: """Make sure retry function has accurate number of attempts.""" global call_count assert fn_with_exception(None) call_count = 0 with pytest.raises(ValueError): fn_with_exception(ValueError) assert call_count == 1 call_count = 0 with pytest.raises(ValueError): retry_on_exceptions_with_backoff( lambda: fn_with_exception(ValueError), [ErrorToRetry(ValueError)], max_tries=3, min_backoff_secs=0.0, ) assert call_count == 3 # different exception will not get retried call_count = 0 with pytest.raises(TypeError): retry_on_exceptions_with_backoff( lambda: fn_with_exception(TypeError), [ErrorToRetry(ValueError)], max_tries=3, ) assert call_count == 1 @pytest.mark.asyncio async def test_retry_on_exceptions_with_backoff_decorator() -> None: """Make sure retry decorator works for both sync and async functions.""" global call_count call_count = 0 retry_on_value_error = get_retry_on_exceptions_with_backoff_decorator( [ErrorToRetry(ValueError)], max_tries=3, min_backoff_secs=0.0, ) SUCCESS_MESSAGE = "done" @retry_on_value_error def fn_with_exception(exception, n=2) -> None: global call_count call_count += 1 if call_count >= n: return SUCCESS_MESSAGE raise exception @retry_on_value_error async def async_fn_with_exception(exception, n=2) -> None: global call_count call_count += 1 if call_count >= n: return SUCCESS_MESSAGE raise exception # sync function # should retry 3 times call_count = 0 with pytest.raises(ValueError): result = fn_with_exception(ValueError, 5) assert call_count == 3 # should not raise exception call_count = 0 result = fn_with_exception(ValueError, 2) assert result == SUCCESS_MESSAGE assert call_count == 2 # different exception will not get retried call_count = 0 with pytest.raises(TypeError): result = fn_with_exception(TypeError, 2) assert call_count == 1 # Async function # should retry 3 times call_count = 0 with pytest.raises(ValueError): result = await async_fn_with_exception(ValueError, 5) assert call_count == 3 # should not raise exception call_count = 0 result = await async_fn_with_exception(ValueError, 2) assert result == SUCCESS_MESSAGE assert call_count == 2 # different exception will not get retried call_count = 0 with pytest.raises(TypeError): result = await async_fn_with_exception(TypeError, 2) assert call_count == 1 def test_retry_on_conditional_exceptions() -> None: """Make sure retry function works on conditional exceptions.""" global call_count call_count = 0 with pytest.raises(ConditionalException): retry_on_exceptions_with_backoff( lambda: fn_with_exception(ConditionalException(True)), [ErrorToRetry(ConditionalException, lambda e: e.should_retry)], max_tries=3, min_backoff_secs=0.0, ) assert call_count == 3 call_count = 0 with pytest.raises(ConditionalException): retry_on_exceptions_with_backoff( lambda: fn_with_exception(ConditionalException(False)), [ErrorToRetry(ConditionalException, lambda e: e.should_retry)], max_tries=3, min_backoff_secs=0.0, ) assert call_count == 1 def test_iter_batch() -> None: """Check iter_batch works as expected on regular, lazy and empty sequences.""" lst = list(range(6)) assert list(iter_batch(lst, 3)) == [[0, 1, 2], [3, 4, 5]] gen = (i for i in range(5)) assert list(iter_batch(gen, 3)) == [[0, 1, 2], [3, 4]] assert list(iter_batch([], 3)) == [] def test_get_color_mapping() -> None: """Test get_color_mapping function.""" items = ["item1", "item2", "item3", "item4"] color_mapping = get_color_mapping(items) assert len(color_mapping) == len(items) assert set(color_mapping.keys()) == set(items) assert all(color in _LLAMA_INDEX_COLORS for color in color_mapping.values()) color_mapping_ansi = get_color_mapping(items, use_llama_index_colors=False) assert len(color_mapping_ansi) == len(items) assert set(color_mapping_ansi.keys()) == set(items) assert all(color in _ANSI_COLORS for color in color_mapping_ansi.values()) def test_get_colored_text() -> None: """Test _get_colored_text function.""" text = "Hello, world!" for color in _LLAMA_INDEX_COLORS: colored_text = _get_colored_text(text, color) assert colored_text.startswith("\033[1;3;") assert colored_text.endswith("m" + text + "\033[0m") for color in _ANSI_COLORS: colored_text = _get_colored_text(text, color) assert colored_text.startswith("\033[1;3;") assert colored_text.endswith("m" + text + "\033[0m") # Test with an unsupported color colored_text = _get_colored_text(text, "unsupported_color") assert colored_text == f"\033[1;3m{text}\033[0m" # just bolded and italicized def test_print_text(capsys: CaptureFixture) -> None: """Test print_text function.""" text = "Hello, world!" for color in _LLAMA_INDEX_COLORS: print_text(text, color) captured = capsys.readouterr() assert captured.out == f"\033[1;3;{_LLAMA_INDEX_COLORS[color]}m{text}\033[0m" for color in _ANSI_COLORS: print_text(text, color) captured = capsys.readouterr() assert captured.out == f"\033[1;3;{_ANSI_COLORS[color]}m{text}\033[0m" # Test with an unsupported color print_text(text, "unsupported_color") captured = capsys.readouterr() assert captured.out == f"\033[1;3m{text}\033[0m" # Test without color print_text(text) captured = capsys.readouterr() assert captured.out == f"{text}" # Test with end print_text(text, end=" ") captured = capsys.readouterr() assert captured.out == f"{text} " def test_get_cache_dir_with_env_override(tmp_path, monkeypatch) -> None: custom_cache_dir = str(tmp_path / "custom_cache") # Test with environment variable set monkeypatch.setenv("LLAMA_INDEX_CACHE_DIR", custom_cache_dir) result = get_cache_dir() assert result == custom_cache_dir assert isinstance(result, str) assert Path(custom_cache_dir).exists() assert Path(custom_cache_dir).is_dir() def test_get_cache_dir_default_behavior(monkeypatch) -> None: # Ensure environment variable is not set monkeypatch.delenv("LLAMA_INDEX_CACHE_DIR", raising=False) with mock.patch("platformdirs.user_cache_dir") as mock_user_cache_dir: mock_cache_path = "/mock/cache/llama_index" mock_user_cache_dir.return_value = mock_cache_path with mock.patch("pathlib.Path.mkdir") as mock_mkdir: result = get_cache_dir() mock_user_cache_dir.assert_called_once_with("llama_index") mock_mkdir.assert_called_once_with(parents=True, exist_ok=True) assert result == mock_cache_path def test_get_cache_dir_creates_directory(tmp_path, monkeypatch) -> None: cache_dir = str(tmp_path / "test_cache" / "nested" / "llama_index") # Ensure directory doesn't exist initially assert not Path(cache_dir).exists() monkeypatch.setenv("LLAMA_INDEX_CACHE_DIR", cache_dir) result = get_cache_dir() assert Path(cache_dir).exists() assert Path(cache_dir).is_dir() assert result == cache_dir def test_get_cache_dir_no_toctou_issue(tmp_path, monkeypatch) -> None: cache_dir = str(tmp_path / "toctou_test") monkeypatch.setenv("LLAMA_INDEX_CACHE_DIR", cache_dir) with mock.patch("pathlib.Path.mkdir") as mock_mkdir: get_cache_dir() mock_mkdir.assert_called_once_with(parents=True, exist_ok=True) def test_get_cache_dir_env_var_precedence(tmp_path, monkeypatch) -> None: env_cache_dir = str(tmp_path / "env_cache") monkeypatch.setenv("LLAMA_INDEX_CACHE_DIR", env_cache_dir) with mock.patch("platformdirs.user_cache_dir") as mock_user_cache_dir: mock_user_cache_dir.return_value = "/should/not/be/used" get_cache_dir() mock_user_cache_dir.assert_not_called()
ConditionalException
python
getsentry__sentry
src/sentry/notifications/notifications/digest.py
{ "start": 1727, "end": 11871 }
class ____(ProjectNotification): message_builder = "DigestNotificationMessageBuilder" metrics_key = "digest" template_path = "sentry/emails/digests/body" def __init__( self, project: Project, digest: DigestInfo, target_type: ActionTargetType, target_identifier: int | None = None, fallthrough_choice: FallthroughChoiceType | None = None, notification_uuid: str | None = None, ) -> None: super().__init__(project, notification_uuid) self.digest = digest self.target_type = target_type self.target_identifier = target_identifier self.fallthrough_choice = fallthrough_choice def get_unsubscribe_key(self) -> UnsubscribeContext | None: return UnsubscribeContext( organization=self.project.organization, key="project", resource_id=self.project.id, referrer="alert_digest", ) def get_subject(self, context: Mapping[str, Any] | None = None) -> str: if not context: # This shouldn't be possible but adding a message just in case. return "Digest Report" # Use timezone from context if available (added by get_recipient_context) timezone = context.get("timezone") return get_digest_subject(context["group"], context["counts"], context["start"], timezone) def get_notification_title( self, provider: ExternalProviders, context: Mapping[str, Any] | None = None ) -> str: if not context: return "Digest Report" project = context["group"].project organization = project.organization return "<!date^{:.0f}^{count} {noun} detected {date} in| Digest Report for> <{project_link}|{project_name}>".format( context["start"].timestamp(), count=len(context["counts"]), noun="issue" if len(context["counts"]) == 1 else "issues", project_link=organization.absolute_url( f"/organizations/{organization.slug}/projects/{project.slug}/" ), project_name=project.name, date="{date_pretty}", ) def get_title_link(self, recipient: Actor, provider: ExternalProviders) -> str | None: return None def build_attachment_title(self, recipient: Actor) -> str: return "" @property def reference(self) -> Model | None: return self.project def get_recipient_context( self, recipient: Actor, extra_context: Mapping[str, Any] ) -> MutableMapping[str, Any]: tz: tzinfo = UTC if recipient.is_user: user_options = user_option_service.get_many( filter={"user_ids": [recipient.id], "keys": ["timezone"]} ) user_tz = get_option_from_list(user_options, key="timezone", default="UTC") try: tz = zoneinfo.ZoneInfo(user_tz) except (ValueError, zoneinfo.ZoneInfoNotFoundError): pass return { **super().get_recipient_context(recipient, extra_context), "timezone": tz, } def get_context(self) -> MutableMapping[str, Any]: rule_details = get_rules( list(self.digest.digest), self.project.organization, self.project, ) context = DigestNotification.build_context( self.digest, self.project, self.project.organization, rule_details, notification_uuid=self.notification_uuid, ) sentry_query_params = self.get_sentry_query_params(ExternalProviders.EMAIL) if not features.has("organizations:workflow-engine-ui-links", self.project.organization): # TODO(iamrajjoshi): This actually mutes a rule for a user, something we have not ported over in the new system # By not including this context, the template will not show the mute button snooze_alert = len(rule_details) > 0 snooze_alert_urls = { rule.id: f"{rule.status_url}{sentry_query_params}&{urlencode({'mute': '1'})}" for rule in rule_details } context["snooze_alert"] = snooze_alert context["snooze_alert_urls"] = snooze_alert_urls else: context["snooze_alert"] = False context["snooze_alert_urls"] = None return context @staticmethod def build_context( digest: DigestInfo, project: Project, organization: Organization, rule_details: Sequence[NotificationRuleDetails], alert_timestamp: int | None = None, notification_uuid: str | None = None, ) -> MutableMapping[str, Any]: has_session_replay = features.has("organizations:session-replay", organization) show_replay_link = features.has("organizations:session-replay-issue-emails", organization) return { **get_digest_as_context(digest.digest), "event_counts": digest.event_counts, "user_counts": digest.user_counts, "has_alert_integration": has_alert_integration(project), "project": project, "slack_link": get_integration_link(organization, IntegrationProviderSlug.SLACK.value), "rules_details": {rule.id: rule for rule in rule_details}, "link_params_for_rule": get_email_link_extra_params( "digest_email", None, rule_details, alert_timestamp, notification_uuid=notification_uuid, ), "show_replay_links": has_session_replay and show_replay_link, } def get_extra_context( self, participants_by_provider_by_event: Mapping[ Event | GroupEvent, Mapping[ExternalProviders, set[Actor]] ], ) -> Mapping[Actor, Mapping[str, Any]]: personalized_digests = get_personalized_digests( self.digest.digest, participants_by_provider_by_event ) return { actor: get_digest_as_context(digest) for actor, digest in personalized_digests.items() } def send(self) -> None: # Only calculate shared context once. shared_context = self.get_context() if should_send_as_alert_notification(shared_context): return send_as_alert_notification( shared_context, self.target_type, self.target_identifier, self.fallthrough_choice ) participants_by_provider_by_event = get_participants_by_event( self.digest.digest, self.project, self.target_type, self.target_identifier, self.fallthrough_choice, ) # Get every actor ID for every provider as a set. team_ids = set() user_ids = set() combined_participants_by_provider = defaultdict(set) for participants_by_provider in participants_by_provider_by_event.values(): for provider, participants in participants_by_provider.items(): for participant in participants: if participant.is_team: team_ids.add(participant.id) elif participant.is_user: user_ids.add(participant.id) combined_participants_by_provider[provider].add(participant) if not (team_ids or user_ids): return logger.info( "mail.adapter.notify_digest", extra={ "project_id": self.project.id, "target_type": self.target_type.value, "target_identifier": self.target_identifier, "team_ids": team_ids, "user_ids": user_ids, "notification_uuid": self.notification_uuid, "number_of_rules": len(shared_context.get("rules_details", [])), "group_count": len(shared_context.get("counts", [])), }, ) # Calculate the per-participant context. extra_context: Mapping[Actor, Mapping[str, Any]] = {} personalized_digests = should_get_personalized_digests(self.target_type, self.project.id) if personalized_digests: extra_context = self.get_extra_context(participants_by_provider_by_event) for provider, participants in combined_participants_by_provider.items(): if personalized_digests: # remove participants if the digest is empty participants_to_remove = set() for participant in participants: if participant not in extra_context: participants_to_remove.add(participant) participants -= participants_to_remove notify(provider, self, participants, shared_context, extra_context) def get_log_params(self, recipient: Actor) -> Mapping[str, Any]: try: alert_id = list(self.digest.digest)[0].id except Exception: alert_id = None return { "target_type": self.target_type.value, "target_identifier": self.target_identifier, "alert_id": alert_id, **super().get_log_params(recipient), } def record_notification_sent(self, recipient: Actor, provider: ExternalProviders) -> None: super().record_notification_sent(recipient, provider) log_params = self.get_log_params(recipient) try: analytics.record( AlertSentEvent( organization_id=self.organization.id, project_id=self.project.id, provider=provider.name, alert_id=log_params["alert_id"] if log_params["alert_id"] else "", alert_type="issue_alert", external_id=str(recipient.id), notification_uuid=self.notification_uuid, ) ) except Exception as e: sentry_sdk.capture_exception(e)
DigestNotification
python
getsentry__sentry
src/sentry/search/events/builder/profile_functions.py
{ "start": 846, "end": 1079 }
class ____(Protocol): @property def config(self) -> ProfileFunctionsDatasetConfig: ... @property def params(self) -> SnubaParams: ... def column(self, name: str) -> Column: ...
ProfileFunctionsQueryBuilderProtocol
python
huggingface__transformers
tests/models/mobilenet_v2/test_modeling_mobilenet_v2.py
{ "start": 6698, "end": 10190 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as MobileNetV2 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = ( (MobileNetV2Model, MobileNetV2ForImageClassification, MobileNetV2ForSemanticSegmentation) if is_torch_available() else () ) pipeline_model_mapping = ( { "image-feature-extraction": MobileNetV2Model, "image-classification": MobileNetV2ForImageClassification, "image-segmentation": MobileNetV2ForSemanticSegmentation, } if is_torch_available() else {} ) test_resize_embeddings = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = MobileNetV2ModelTester(self) self.config_tester = MobileNetV2ConfigTester(self, config_class=MobileNetV2Config, has_text_modality=False) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="MobileNetV2 does not output attentions") def test_attention_outputs(self): pass def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_stages = 16 self.assertEqual(len(hidden_states), expected_num_stages) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_for_image_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*config_and_inputs) def test_for_semantic_segmentation(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "google/mobilenet_v2_1.4_224" model = MobileNetV2Model.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision
MobileNetV2ModelTest
python
pallets__jinja
src/jinja2/lexer.py
{ "start": 7666, "end": 8503 }
class ____(t.NamedTuple): lineno: int type: str value: str def __str__(self) -> str: return describe_token(self) def test(self, expr: str) -> bool: """Test a token against a token expression. This can either be a token type or ``'token_type:token_value'``. This can only test against string values and types. """ # here we do a regular string equality check as test_any is usually # passed an iterable of not interned strings. if self.type == expr: return True if ":" in expr: return expr.split(":", 1) == [self.type, self.value] return False def test_any(self, *iterable: str) -> bool: """Test against multiple token expressions.""" return any(self.test(expr) for expr in iterable)
Token
python
huggingface__transformers
src/transformers/modelcard.py
{ "start": 3067, "end": 13621 }
class ____: r""" Structured Model Card class. Store model card as well as methods for loading/downloading/saving model cards. Please read the following paper for details and explanation on the sections: "Model Cards for Model Reporting" by Margaret Mitchell, Simone Wu, Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer, Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards. Link: https://huggingface.co/papers/1810.03993 Note: A model card can be loaded and saved to disk. """ def __init__(self, **kwargs): warnings.warn( "The class `ModelCard` is deprecated and will be removed in version 5 of Transformers", FutureWarning ) # Recommended attributes from https://huggingface.co/papers/1810.03993 (see papers) self.model_details = kwargs.pop("model_details", {}) self.intended_use = kwargs.pop("intended_use", {}) self.factors = kwargs.pop("factors", {}) self.metrics = kwargs.pop("metrics", {}) self.evaluation_data = kwargs.pop("evaluation_data", {}) self.training_data = kwargs.pop("training_data", {}) self.quantitative_analyses = kwargs.pop("quantitative_analyses", {}) self.ethical_considerations = kwargs.pop("ethical_considerations", {}) self.caveats_and_recommendations = kwargs.pop("caveats_and_recommendations", {}) # Open additional attributes for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def save_pretrained(self, save_directory_or_file): """Save a model card object to the directory or file `save_directory_or_file`.""" if os.path.isdir(save_directory_or_file): # If we save using the predefined names, we can load using `from_pretrained` output_model_card_file = os.path.join(save_directory_or_file, MODEL_CARD_NAME) else: output_model_card_file = save_directory_or_file self.to_json_file(output_model_card_file) logger.info(f"Model card saved in {output_model_card_file}") @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co. - a path to a *directory* containing a model card file saved using the [`~ModelCard.save_pretrained`] method, e.g.: `./my_model_directory/`. - a path or url to a saved model card JSON *file*, e.g.: `./my_model_directory/modelcard.json`. cache_dir: (*optional*) string: Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache should not be used. kwargs: (*optional*) dict: key/value pairs with which to update the ModelCard object after loading. - The values in kwargs of any keys which are model card attributes will be used to override the loaded values. - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the *return_unused_kwargs* keyword parameter. proxies: (*optional*) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. return_unused_kwargs: (*optional*) bool: - If False, then this function returns just the final model card object. - If True, then this functions returns a tuple *(model card, unused_kwargs)* where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of kwargs which has not been used to update *ModelCard* and is otherwise ignored. Examples: ```python # Download model card from huggingface.co and cache. modelcard = ModelCard.from_pretrained("google-bert/bert-base-uncased") # Model card was saved using *save_pretrained('./test/saved_model/')* modelcard = ModelCard.from_pretrained("./test/saved_model/") modelcard = ModelCard.from_pretrained("./test/saved_model/modelcard.json") modelcard = ModelCard.from_pretrained("google-bert/bert-base-uncased", output_attentions=True, foo=False) ```""" cache_dir = kwargs.pop("cache_dir", None) proxies = kwargs.pop("proxies", None) return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) from_pipeline = kwargs.pop("_from_pipeline", None) user_agent = {"file_type": "model_card"} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(pretrained_model_name_or_path): resolved_model_card_file = pretrained_model_name_or_path is_local = True else: try: # Load from URL or cache if already cached resolved_model_card_file = cached_file( pretrained_model_name_or_path, filename=MODEL_CARD_NAME, cache_dir=cache_dir, proxies=proxies, user_agent=user_agent, ) if is_local: logger.info(f"loading model card file {resolved_model_card_file}") else: logger.info(f"loading model card file {MODEL_CARD_NAME} from cache at {resolved_model_card_file}") # Load model card modelcard = cls.from_json_file(resolved_model_card_file) except (OSError, json.JSONDecodeError): # We fall back on creating an empty model card modelcard = cls() # Update model card with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(modelcard, key): setattr(modelcard, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f"Model card: {modelcard}") if return_unused_kwargs: return modelcard, kwargs else: return modelcard @classmethod def from_dict(cls, json_object): """Constructs a `ModelCard` from a Python dictionary of parameters.""" return cls(**json_object) @classmethod def from_json_file(cls, json_file): """Constructs a `ModelCard` from a json file of parameters.""" with open(json_file, encoding="utf-8") as reader: text = reader.read() dict_obj = json.loads(text) return cls(**dict_obj) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path): """Save this instance to a json file.""" with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) AUTOGENERATED_TRAINER_COMMENT = """ <!-- This model card has been generated automatically according to the information the Trainer had access to. You should probably proofread and complete it, then remove this comment. --> """ TASK_TAG_TO_NAME_MAPPING = { "fill-mask": "Masked Language Modeling", "image-classification": "Image Classification", "image-segmentation": "Image Segmentation", "multiple-choice": "Multiple Choice", "object-detection": "Object Detection", "question-answering": "Question Answering", "summarization": "Summarization", "table-question-answering": "Table Question Answering", "text-classification": "Text Classification", "text-generation": "Causal Language Modeling", "text2text-generation": "Sequence-to-sequence Language Modeling", "token-classification": "Token Classification", "translation": "Translation", "zero-shot-classification": "Zero Shot Classification", "automatic-speech-recognition": "Automatic Speech Recognition", "audio-classification": "Audio Classification", } METRIC_TAGS = [ "accuracy", "bleu", "f1", "matthews_correlation", "pearsonr", "precision", "recall", "rouge", "sacrebleu", "spearmanr", "wer", ] def _listify(obj): if obj is None: return [] elif isinstance(obj, str): return [obj] else: return obj def _insert_values_as_list(metadata, name, values): if values is None: return metadata if isinstance(values, str): values = [values] values = [v for v in values if v is not None] if len(values) == 0: return metadata metadata[name] = values return metadata def infer_metric_tags_from_eval_results(eval_results): if eval_results is None: return {} result = {} for key in eval_results: if key.lower().replace(" ", "_") in METRIC_TAGS: result[key.lower().replace(" ", "_")] = key elif key.lower() == "rouge1": result["rouge"] = key return result def _insert_value(metadata, name, value): if value is None: return metadata metadata[name] = value return metadata def is_hf_dataset(dataset): if not is_datasets_available(): return False from datasets import Dataset, IterableDataset return isinstance(dataset, (Dataset, IterableDataset)) def _get_mapping_values(mapping): result = [] for v in mapping.values(): if isinstance(v, (tuple, list)): result += list(v) else: result.append(v) return result @dataclass
ModelCard
python
pytorch__pytorch
test/onnx/test_pytorch_onnx_shape_inference.py
{ "start": 16471, "end": 23083 }
class ____(pytorch_test_common.ExportTestCase): def setUp(self): super().setUp() self.opset_version = _constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET def test_setType_maintains_output_shape_for_single_custom_op(self): self.addCleanup(torch.onnx.unregister_custom_op_symbolic, "::linalg_inv", 9) class CustomInverse(torch.nn.Module): def forward(self, x): return torch.inverse(x) + x def linalg_inv_settype(g, self): return g.op("com.microsoft::Inverse", self).setType(self.type()) torch.onnx.register_custom_op_symbolic("::linalg_inv", linalg_inv_settype, 9) model = CustomInverse() x = torch.randn(2, 3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, dynamo=False, ) model_proto = onnx.load(io.BytesIO(f.getvalue())) model_value_info = model_proto.graph.value_info self.assertIsNotNone(model_value_info) assert model_value_info dims = model_value_info[0].type.tensor_type.shape.dim for i in range(len(dims)): # If node output has shape info, it should have dim_value # Otherwise, it has dim_params with dynamic shape self.assertTrue(dims[i].HasField("dim_value")) for dim, rank in zip(dims, x.size()): self.assertEqual(dim.dim_value, rank) def test_no_setType_for_single_custom_op(self): self.addCleanup(torch.onnx.unregister_custom_op_symbolic, "::linalg_inv", 9) class CustomInverse(torch.nn.Module): def forward(self, x): return torch.inverse(x) + x def linalg_inv_no_settype(g, self): return g.op("com.microsoft::Inverse", self) torch.onnx.register_custom_op_symbolic("::linalg_inv", linalg_inv_no_settype, 9) model = CustomInverse() x = torch.randn(2, 3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, dynamo=False, ) model_proto = onnx.load(io.BytesIO(f.getvalue())) model_value_info = model_proto.graph.value_info self.assertIsNotNone(model_value_info) assert model_value_info dims = model_value_info[0].type.tensor_type.shape.dim for i in range(len(dims)): # If node output has shape info, it should have dim_value # Otherwise, it has dim_params with dynamic shape self.assertTrue(dims[i].HasField("dim_param")) def test_setType_maintains_output_shape_for_single_custom_op_with_dynamic_axes( self, ): self.addCleanup(torch.onnx.unregister_custom_op_symbolic, "::linalg_inv", 9) class CustomInverse(torch.nn.Module): def forward(self, x): return torch.inverse(x) + x def linalg_inv_settype(g, self): return g.op("com.microsoft::Inverse", self).setType( self.type().with_dtype(torch.float).with_sizes([None, 3, 3]) ) torch.onnx.register_custom_op_symbolic("::linalg_inv", linalg_inv_settype, 9) model = CustomInverse() x = torch.randn(2, 3, 3) f = io.BytesIO() torch.onnx.export( model, (x,), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, input_names=["x"], dynamic_axes={"x": {0: "batch"}}, dynamo=False, ) model_proto = onnx.load(io.BytesIO(f.getvalue())) model_value_info = model_proto.graph.value_info self.assertIsNotNone(model_value_info) assert model_value_info dims = model_value_info[0].type.tensor_type.shape.dim # The first axe should be dynamic as we defined when exporting self.assertTrue(dims[0].HasField("dim_param")) for i in range(1, len(dims)): # If node output has shape info, it should have dim_value # Otherwise, it has dim_params with dynamic shape self.assertTrue(dims[i].HasField("dim_value")) self.assertEqual(dims[i].dim_value, x.size()[i]) def test_setType_maintains_output_shape_for_single_custom_op_with_onnx_ops(self): self.addCleanup(torch.onnx.unregister_custom_op_symbolic, "::linalg_inv", 9) class CustomInverse(torch.nn.Module): def forward(self, x, y, z): x = torch.inverse(x) return x + y + z def linalg_inv_settype(g, self): return g.op("com.microsoft::Inverse", self).setType( self.type().with_dtype(torch.float).with_sizes([2, 3, 10, 10]) ) torch.onnx.register_custom_op_symbolic("::linalg_inv", linalg_inv_settype, 9) model = CustomInverse() x = torch.randn(2, 3, 10, 10) y = torch.randn(2, 3, 10, 10) z = torch.randn(2, 3, 10, 10) f = io.BytesIO() torch.onnx.export( model, (x, y, z), f, opset_version=self.opset_version, custom_opsets={"com.microsoft": 1}, dynamo=False, ) model_proto = onnx.load(io.BytesIO(f.getvalue())) # To validate the shape of inverse Op, we need to find inverse output name, # and then use it to identify its value_info for the shape. output_name = "" for node in model_proto.graph.node: if node.op_type == "Inverse": output_name = node.output[0] break assert output_name model_value_info = model_proto.graph.value_info self.assertIsNotNone(model_value_info) assert model_value_info for value_info in model_value_info: assert value_info.name if value_info.name == output_name: dims = value_info.type.tensor_type.shape.dim for i in range(len(dims)): # If node output has shape info, it should have dim_value # Otherwise, it has dim_params with dynamic shape self.assertTrue(dims[i].HasField("dim_value")) for dim, rank in zip(dims, x.size()): self.assertEqual(dim.dim_value, rank) if __name__ == "__main__": common_utils.run_tests()
TestONNXCustomOpShapeInference
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/regex.py
{ "start": 3399, "end": 6726 }
class ____: """Helper object that allows to configure `characters` strategy with various unicode categories and characters. Also allows negation of configured set. :param negate: If True, configure :func:`hypothesis.strategies.characters` to match anything other than configured character set :param flags: Regex flags. They affect how and which characters are matched """ def __init__(self, *, negate=False, flags=0, alphabet): self._categories = set() self._whitelist_chars = set() self._blacklist_chars = set() self._negate = negate self._ignorecase = flags & re.IGNORECASE self.code_to_char = chr self._alphabet = unwrap_strategies(alphabet) if flags & re.ASCII: self._alphabet = OneCharStringStrategy( self._alphabet.intervals & charmap.query(max_codepoint=127) ) @property def strategy(self): """Returns resulting strategy that generates configured char set.""" # Start by getting the set of all characters allowed by the pattern white_chars = self._whitelist_chars - self._blacklist_chars multi_chars = {c for c in white_chars if len(c) > 1} intervals = charmap.query( categories=self._categories, exclude_characters=self._blacklist_chars, include_characters=white_chars - multi_chars, ) # Then take the complement if this is from a negated character class if self._negate: intervals = charmap.query() - intervals multi_chars.clear() # and finally return the intersection with our alphabet return OneCharStringStrategy(intervals & self._alphabet.intervals) | ( st.sampled_from(sorted(multi_chars)) if multi_chars else st.nothing() ) def add_category(self, category): """Update unicode state to match sre_parse object ``category``.""" if category == sre.CATEGORY_DIGIT: self._categories |= UNICODE_DIGIT_CATEGORIES elif category == sre.CATEGORY_NOT_DIGIT: self._categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES elif category == sre.CATEGORY_SPACE: self._categories |= UNICODE_SPACE_CATEGORIES self._whitelist_chars |= UNICODE_SPACE_CHARS elif category == sre.CATEGORY_NOT_SPACE: self._categories |= UNICODE_CATEGORIES - UNICODE_SPACE_CATEGORIES self._blacklist_chars |= UNICODE_SPACE_CHARS elif category == sre.CATEGORY_WORD: self._categories |= UNICODE_WORD_CATEGORIES self._whitelist_chars.add("_") elif category == sre.CATEGORY_NOT_WORD: self._categories |= UNICODE_CATEGORIES - UNICODE_WORD_CATEGORIES self._blacklist_chars.add("_") else: raise NotImplementedError(f"Unknown character category: {category}") def add_char(self, c): """Add given char to the whitelist.""" self._whitelist_chars.add(c) if ( self._ignorecase and re.match(re.escape(c), c.swapcase(), flags=re.IGNORECASE) is not None ): # Note that it is possible that `len(c.swapcase()) > 1` self._whitelist_chars.add(c.swapcase())
CharactersBuilder
python
streamlit__streamlit
lib/tests/streamlit/runtime/secrets_test.py
{ "start": 2423, "end": 11460 }
class ____(unittest.TestCase): """Tests for st.secrets with a single secrets.toml file""" def setUp(self) -> None: # st.secrets modifies os.environ, so we save it here and # restore in tearDown. self._prev_environ = dict(os.environ) # Run tests on our own Secrets instance to reduce global state # mutations. self.secrets = Secrets() def tearDown(self) -> None: os.environ.clear() os.environ.update(self._prev_environ) @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_access_secrets(self, *mocks): assert self.secrets["db_username"] == "Jane" assert self.secrets["subsection"]["email"] == "eng@streamlit.io" assert self.secrets["subsection"].email == "eng@streamlit.io" @parameterized.expand( [ [ False, "Secrets", ], [ True, ( "{'db_username': 'Jane', 'db_password': '12345qwerty', " "'subsection': {'email': 'eng@streamlit.io'}}" ), ], ] ) @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_repr_secrets(self, runtime_exists, secrets_repr, *mocks): with patch("streamlit.runtime.exists", return_value=runtime_exists): assert repr(self.secrets) == secrets_repr @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_access_secrets_via_attribute(self, *mocks): assert self.secrets.db_username == "Jane" assert self.secrets.subsection["email"] == "eng@streamlit.io" assert self.secrets.subsection.email == "eng@streamlit.io" @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_os_environ(self, _): """os.environ gets patched when we load our secrets.toml""" # We haven't loaded secrets yet assert os.environ.get("db_username") is None self.secrets.load_if_toml_exists() assert os.environ["db_username"] == "Jane" assert os.environ["db_password"] == "12345qwerty" # Subsections do not get loaded into os.environ assert os.environ.get("subsection") is None @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_load_if_toml_exists_returns_true_if_parse_succeeds(self, _): assert self.secrets.load_if_toml_exists() def test_load_if_toml_exists_returns_false_if_parse_fails(self): assert not self.secrets.load_if_toml_exists() @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_missing_toml_error(self, _): """Secrets access raises an error if secrets.toml is missing.""" with patch("builtins.open", mock_open()) as mock_file: mock_file.side_effect = FileNotFoundError() with pytest.raises(StreamlitSecretNotFoundError): self.secrets.get("no_such_secret", None) @patch("builtins.open", new_callable=mock_open, read_data="invalid_toml") @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_malformed_toml_error(self, mock_get_option, _): """Secrets access raises an error if secrets.toml is malformed.""" with pytest.raises(StreamlitSecretNotFoundError): self.secrets.get("no_such_secret", None) @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_getattr_nonexistent(self, *mocks): """Verify that access to missing attribute raises AttributeError.""" with pytest.raises(AttributeError): self.secrets.nonexistent_secret # noqa: B018 with pytest.raises(AttributeError): self.secrets.subsection.nonexistent_secret # noqa: B018 @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_getattr_raises_exception_on_attr_dict(self, *mocks): """Verify that assignment to nested secrets raises TypeError.""" with pytest.raises(TypeError): self.secrets.subsection["new_secret"] = "123" with pytest.raises(TypeError): self.secrets.subsection.new_secret = "123" @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_getitem_nonexistent(self, *mocks): """Verify that access to missing key via dict notation raises KeyError.""" with pytest.raises(KeyError): self.secrets["nonexistent_secret"] with pytest.raises(KeyError): self.secrets["subsection"]["nonexistent_secret"] @patch("streamlit.watcher.path_watcher.watch_file") @patch("streamlit.config.get_option", return_value=[MOCK_SECRETS_FILE_LOC]) def test_reload_secrets_when_file_changes(self, mock_get_option, mock_watch_file): """When secrets.toml is loaded, the secrets file gets watched.""" with patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML): assert self.secrets["db_username"] == "Jane" assert self.secrets["db_password"] == "12345qwerty" assert os.environ["db_username"] == "Jane" assert os.environ["db_password"] == "12345qwerty" # watch_file should have been called on the "secrets.toml" file with # the "poll" watcher_type. ("poll" is used here - rather than whatever # is set in config - because Streamlit Cloud loads secrets.toml from # a virtual filesystem that watchdog is unable to fire events for.) mock_watch_file.assert_called_once_with( MOCK_SECRETS_FILE_LOC, self.secrets._on_secrets_changed, watcher_type="poll", ) # Mock the `send` method to later verify that it has been called. self.secrets.file_change_listener.send = MagicMock() # Change the text that will be loaded on the next call to `open` new_mock_toml = "db_username='Joan'" with patch("builtins.open", new_callable=mock_open, read_data=new_mock_toml): # Trigger a secrets file reload, ensure the secrets dict # gets repopulated as expected, and ensure that os.environ is # also updated properly. self.secrets._on_secrets_changed(MOCK_SECRETS_FILE_LOC) # A change in `secrets.toml` should emit a signal. self.secrets.file_change_listener.send.assert_called_once() assert self.secrets["db_username"] == "Joan" assert self.secrets.get("db_password") is None assert os.environ["db_username"] == "Joan" assert os.environ.get("db_password") is None @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_internal_attribute_assignment_allowed(self, *mocks): """Verify that internal attribute assignment is allowed.""" # Test setting each allowed internal attribute self.secrets._secrets = {} assert self.secrets._secrets == {} # Create and test RLock lock = threading.RLock() self.secrets._lock = lock assert self.secrets._lock == lock # Verify it's actually a lock by trying to acquire it assert self.secrets._lock.acquire(blocking=False) self.secrets._lock.release() self.secrets._file_watchers_installed = True assert self.secrets._file_watchers_installed self.secrets._suppress_print_error_on_exception = True assert self.secrets._suppress_print_error_on_exception self.secrets.file_change_listener = Signal() assert isinstance(self.secrets.file_change_listener, Signal) # Test that load_if_toml_exists can be assigned original_method = self.secrets.load_if_toml_exists self.secrets.load_if_toml_exists = lambda: True assert self.secrets.load_if_toml_exists != original_method @patch("streamlit.watcher.path_watcher.watch_file") @patch("builtins.open", new_callable=mock_open, read_data=MOCK_TOML) def test_attribute_assignment_raises_type_error(self, *mocks): """Verify that attribute assignment raises TypeError.""" with pytest.raises(TypeError) as cm: self.secrets.new_secret = "123" assert str(cm.value) == "Secrets does not support attribute assignment."
SecretsTest
python
facelessuser__pymdown-extensions
pymdownx/tilde.py
{ "start": 5677, "end": 7333 }
class ____(Extension): """Add delete and/or subscript extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'smart_delete': [True, "Treat ~~connected~~words~~ intelligently - Default: True"], 'delete': [True, "Enable delete - Default: True"], 'subscript': [True, "Enable subscript - Default: True"] } super().__init__(*args, **kwargs) def extendMarkdown(self, md): """Insert `<del>test</del>` tags as `~~test~~` and `<sub>test</sub>` tags as `~test~`.""" config = self.getConfigs() delete = bool(config.get('delete', True)) subscript = bool(config.get('subscript', True)) smart = bool(config.get('smart_delete', True)) md.registerExtension(self) escape_chars = [] if delete or subscript: escape_chars.append('~') if subscript: escape_chars.append(' ') util.escape_chars(md, escape_chars) tilde = None md.inlinePatterns.register(SimpleTextInlineProcessor(NOT_TILDE), 'not_tilde', 70) if delete and subscript: tilde = TildeSmartProcessor(r'~') if smart else TildeProcessor(r'~') elif delete: tilde = TildeSmartDeleteProcessor(r'~') if smart else TildeDeleteProcessor(r'~') elif subscript: tilde = TildeSubProcessor(r'~') if tilde is not None: md.inlinePatterns.register(tilde, "sub_del", 65) def makeExtension(*args, **kwargs): """Return extension.""" return DeleteSubExtension(*args, **kwargs)
DeleteSubExtension
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass8.py
{ "start": 231, "end": 276 }
class ____(ParentA): pass @dataclass
ChildA
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_optim_state.py
{ "start": 1687, "end": 1926 }
class ____(Enum): """Method for communicating the optimizer state dict for internal tests.""" BROADCAST_OBJECT_LIST = auto() SCATTER_FULL_OSD = auto() FLATTEN_SHARDED_OSD = auto() OPTIM_STATE_DICT = auto()
_OSDCommMethod
python
getsentry__sentry
src/sentry/replays/endpoints/organization_replay_count.py
{ "start": 1273, "end": 1658 }
class ____(serializers.Serializer): query = serializers.CharField(required=True) data_source = serializers.ChoiceField( choices=(Dataset.Discover.value, Dataset.IssuePlatform.value), default=Dataset.Discover.value, ) returnIds = serializers.BooleanField(default=False) @region_silo_endpoint @extend_schema(tags=["Replays"])
ReplayCountQueryParamsValidator
python
pandas-dev__pandas
pandas/tests/indexes/multi/test_lexsort.py
{ "start": 626, "end": 1358 }
class ____: def test_lexsort_depth(self): # Test that lexsort_depth return the correct sortorder # when it was given to the MultiIndex const. # GH#28518 levels = [[0, 1], [0, 1, 2]] index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], sortorder=2 ) assert index._lexsort_depth == 2 index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=1 ) assert index._lexsort_depth == 1 index = MultiIndex( levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=0 ) assert index._lexsort_depth == 0
TestLexsortDepth
python
apache__thrift
lib/py/src/protocol/TProtocol.py
{ "start": 946, "end": 1317 }
class ____(TException): """Custom Protocol Exception class""" UNKNOWN = 0 INVALID_DATA = 1 NEGATIVE_SIZE = 2 SIZE_LIMIT = 3 BAD_VERSION = 4 NOT_IMPLEMENTED = 5 DEPTH_LIMIT = 6 INVALID_PROTOCOL = 7 def __init__(self, type=UNKNOWN, message=None): TException.__init__(self, message) self.type = type
TProtocolException