language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
pytorch__pytorch
torch/nn/modules/upsampling.py
{ "start": 9878, "end": 11675 }
class ____(Upsample): r"""Applies a 2D bilinear upsampling to an input signal composed of several input channels. To specify the scale, it takes either the :attr:`size` or the :attr:`scale_factor` as it's constructor argument. When :attr:`size` is given, it is the output size of the image `(h, w)`. Args: size (int or Tuple[int, int], optional): output spatial sizes scale_factor (float or Tuple[float, float], optional): multiplier for spatial size. .. warning:: This class is deprecated in favor of :func:`~nn.functional.interpolate`. It is equivalent to ``nn.functional.interpolate(..., mode='bilinear', align_corners=True)``. Shape: - Input: :math:`(N, C, H_{in}, W_{in})` - Output: :math:`(N, C, H_{out}, W_{out})` where .. math:: H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor .. math:: W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor Examples:: >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2) >>> input tensor([[[[1., 2.], [3., 4.]]]]) >>> # xdoctest: +IGNORE_WANT("do other tests modify the global state?") >>> m = nn.UpsamplingBilinear2d(scale_factor=2) >>> m(input) tensor([[[[1.0000, 1.3333, 1.6667, 2.0000], [1.6667, 2.0000, 2.3333, 2.6667], [2.3333, 2.6667, 3.0000, 3.3333], [3.0000, 3.3333, 3.6667, 4.0000]]]]) """ def __init__( self, size: Optional[_size_2_t] = None, scale_factor: Optional[_ratio_2_t] = None, ) -> None: super().__init__(size, scale_factor, mode="bilinear", align_corners=True)
UpsamplingBilinear2d
python
getsentry__sentry
src/sentry/unmerge.py
{ "start": 7669, "end": 8297 }
class ____(UnmergeArgsBase): last_event: Any | None locked_primary_hashes: Collection[str] # unmerge may only start mutating data on a successive page, once it # actually has found an event that needs to be migrated. # (unmerge_key) -> (group_id, eventstream_state) destinations: Destinations # likewise unmerge may only find "source" events (events that should not be # migrated) on the second page, only then (and only once) it can reset # group attributes such as last_seen. source_fields_reset: bool UnmergeArgs = Union[InitialUnmergeArgs, SuccessiveUnmergeArgs]
SuccessiveUnmergeArgs
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-valid-strings-to-form-target-i.py
{ "start": 5174, "end": 6715 }
class ____(object): def minValidStrings(self, words, target): """ :type words: List[str] :type target: str :rtype: int """ class Trie(object): def __init__(self): self.__nodes = [] self.__new_node() def __new_node(self): self.__nodes.append([-1]*26) return len(self.__nodes)-1 def add(self, w): curr = 0 for c in w: x = ord(c)-ord('a') if self.__nodes[curr][x] == -1: self.__nodes[curr][x] = self.__new_node() curr = self.__nodes[curr][x] def query(self, target, i): curr = 0 for l in xrange(len(target)-i): x = ord(target[i+l])-ord('a') if self.__nodes[curr][x] == -1: return l curr = self.__nodes[curr][x] return len(target)-i trie = Trie() for w in words: trie.add(w) lookup = [0]*len(target) for i in xrange(len(target)): l = trie.query(target, i) for nl in xrange(1, l+1): lookup[i+nl-1] = max(lookup[i+nl-1], nl) dp = [0]*(len(target)+1) for i in xrange(len(target)): if not lookup[i]: return -1 dp[i+1] = dp[(i-lookup[i])+1]+1 return dp[-1]
Solution4
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/distlib/util.py
{ "start": 16613, "end": 24131 }
class ____(object): def __init__(self, dry_run=False): self.dry_run = dry_run self.ensured = set() self._init_record() def _init_record(self): self.record = False self.files_written = set() self.dirs_created = set() def record_as_written(self, path): if self.record: self.files_written.add(path) def newer(self, source, target): """Tell if the target is newer than the source. Returns true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Returns false if both exist and 'target' is the same age or younger than 'source'. Raise PackagingFileError if 'source' does not exist. Note that this test is not very accurate: files created in the same second will have the same "age". """ if not os.path.exists(source): raise DistlibException("file '%r' does not exist" % os.path.abspath(source)) if not os.path.exists(target): return True return os.stat(source).st_mtime > os.stat(target).st_mtime def copy_file(self, infile, outfile, check=True): """Copy a file respecting dry-run and force flags. """ self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying %s to %s', infile, outfile) if not self.dry_run: msg = None if check: if os.path.islink(outfile): msg = '%s is a symlink' % outfile elif os.path.exists(outfile) and not os.path.isfile(outfile): msg = '%s is a non-regular file' % outfile if msg: raise ValueError(msg + ' which would be overwritten') shutil.copyfile(infile, outfile) self.record_as_written(outfile) def copy_stream(self, instream, outfile, encoding=None): assert not os.path.isdir(outfile) self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying stream %s to %s', instream, outfile) if not self.dry_run: if encoding is None: outstream = open(outfile, 'wb') else: outstream = codecs.open(outfile, 'w', encoding=encoding) try: shutil.copyfileobj(instream, outstream) finally: outstream.close() self.record_as_written(outfile) def write_binary_file(self, path, data): self.ensure_dir(os.path.dirname(path)) if not self.dry_run: if os.path.exists(path): os.remove(path) with open(path, 'wb') as f: f.write(data) self.record_as_written(path) def write_text_file(self, path, data, encoding): self.write_binary_file(path, data.encode(encoding)) def set_mode(self, bits, mask, files): if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'): # Set the executable bits (owner, group, and world) on # all the files specified. for f in files: if self.dry_run: logger.info("changing mode of %s", f) else: mode = (os.stat(f).st_mode | bits) & mask logger.info("changing mode of %s to %o", f, mode) os.chmod(f, mode) set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f) def ensure_dir(self, path): path = os.path.abspath(path) if path not in self.ensured and not os.path.exists(path): self.ensured.add(path) d, f = os.path.split(path) self.ensure_dir(d) logger.info('Creating %s' % path) if not self.dry_run: os.mkdir(path) if self.record: self.dirs_created.add(path) def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False): dpath = cache_from_source(path, not optimize) logger.info('Byte-compiling %s to %s', path, dpath) if not self.dry_run: if force or self.newer(path, dpath): if not prefix: diagpath = None else: assert path.startswith(prefix) diagpath = path[len(prefix):] compile_kwargs = {} if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'): compile_kwargs[ 'invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH py_compile.compile(path, dpath, diagpath, True, **compile_kwargs) # raise error self.record_as_written(dpath) return dpath def ensure_removed(self, path): if os.path.exists(path): if os.path.isdir(path) and not os.path.islink(path): logger.debug('Removing directory tree at %s', path) if not self.dry_run: shutil.rmtree(path) if self.record: if path in self.dirs_created: self.dirs_created.remove(path) else: if os.path.islink(path): s = 'link' else: s = 'file' logger.debug('Removing %s %s', s, path) if not self.dry_run: os.remove(path) if self.record: if path in self.files_written: self.files_written.remove(path) def is_writable(self, path): result = False while not result: if os.path.exists(path): result = os.access(path, os.W_OK) break parent = os.path.dirname(path) if parent == path: break path = parent return result def commit(self): """ Commit recorded changes, turn off recording, return changes. """ assert self.record result = self.files_written, self.dirs_created self._init_record() return result def rollback(self): if not self.dry_run: for f in list(self.files_written): if os.path.exists(f): os.remove(f) # dirs should all be empty now, except perhaps for # __pycache__ subdirs # reverse so that subdirs appear before their parents dirs = sorted(self.dirs_created, reverse=True) for d in dirs: flist = os.listdir(d) if flist: assert flist == ['__pycache__'] sd = os.path.join(d, flist[0]) os.rmdir(sd) os.rmdir(d) # should fail if non-empty self._init_record() def resolve(module_name, dotted_path): if module_name in sys.modules: mod = sys.modules[module_name] else: mod = __import__(module_name) if dotted_path is None: result = mod else: parts = dotted_path.split('.') result = getattr(mod, parts.pop(0)) for p in parts: result = getattr(result, p) return result
FileOperator
python
numba__numba
numba/cuda/cudadrv/nvrtc.py
{ "start": 970, "end": 1485 }
class ____: """ A class for managing the lifetime of nvrtcProgram instances. Instances of the class own an nvrtcProgram; when an instance is deleted, the underlying nvrtcProgram is destroyed using the appropriate NVRTC API. """ def __init__(self, nvrtc, handle): self._nvrtc = nvrtc self._handle = handle @property def handle(self): return self._handle def __del__(self): if self._handle: self._nvrtc.destroy_program(self)
NvrtcProgram
python
django__django
tests/postgres_tests/models.py
{ "start": 863, "end": 984 }
class ____(models.Model): class Meta: abstract = True required_db_vendor = "postgresql"
PostgreSQLModel
python
PrefectHQ__prefect
tests/utilities/test_collections.py
{ "start": 2225, "end": 2291 }
class ____(pydantic.BaseModel): x: int y: int
SimplePydantic
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 64651, "end": 65040 }
class ____(_PrintableStructure): _fields_ = [ ('timeStamp', c_ulonglong), ('vgpuInstance', _nvmlVgpuInstance_t), ('smUtil', c_nvmlValue_t), ('memUtil', c_nvmlValue_t), ('encUtil', c_nvmlValue_t), ('decUtil', c_nvmlValue_t), ('jpgUtil', c_nvmlValue_t), ('ofaUtil', c_nvmlValue_t), ]
c_nvmlVgpuInstanceUtilizationInfo_v1_t
python
getsentry__sentry
src/sentry/incidents/endpoints/organization_incident_details.py
{ "start": 1301, "end": 2807 }
class ____(IncidentEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } permission_classes = (IncidentPermission,) @track_alert_endpoint_execution("GET", "sentry-api-0-organization-incident-details") def get(self, request: Request, organization, incident) -> Response: """ Fetch an Incident. `````````````````` :auth: required """ data = serialize(incident, request.user, DetailedIncidentSerializer()) return Response(data) @track_alert_endpoint_execution("PUT", "sentry-api-0-organization-incident-details") def put(self, request: Request, organization: Organization, incident) -> Response: serializer = IncidentSerializer(data=request.data) if serializer.is_valid(): result = serializer.validated_data if result["status"] == IncidentStatus.CLOSED: incident = update_incident_status( incident=incident, status=result["status"], status_method=IncidentStatusMethod.MANUAL, ) return Response( serialize(incident, request.user, DetailedIncidentSerializer()), status=200 ) else: return Response("Status cannot be changed.", status=400) return Response(serializer.errors, status=400)
OrganizationIncidentDetailsEndpoint
python
PrefectHQ__prefect
src/prefect/utilities/asyncutils.py
{ "start": 15939, "end": 19024 }
class ____(anyio.abc.TaskGroup): """ A task group that gathers results. AnyIO does not include `gather` support. This class extends the `TaskGroup` interface to allow simple gathering. See https://github.com/agronholm/anyio/issues/100 This class should be instantiated with `create_gather_task_group`. """ def __init__(self, task_group: anyio.abc.TaskGroup): self._results: dict[UUID, Any] = {} # The concrete task group implementation to use self._task_group: anyio.abc.TaskGroup = task_group async def _run_and_store( self, key: UUID, fn: Callable[[Unpack[PosArgsT]], Awaitable[Any]], *args: Unpack[PosArgsT], ) -> None: self._results[key] = await fn(*args) def start_soon( # pyright: ignore[reportIncompatibleMethodOverride] self, func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], *args: Unpack[PosArgsT], name: object = None, ) -> UUID: key = uuid4() # Put a placeholder in-case the result is retrieved earlier self._results[key] = GatherIncomplete self._task_group.start_soon(self._run_and_store, key, func, *args, name=name) return key async def start(self, func: object, *args: object, name: object = None) -> NoReturn: """ Since `start` returns the result of `task_status.started()` but here we must return the key instead, we just won't support this method for now. """ raise RuntimeError("`GatherTaskGroup` does not support `start`.") def get_result(self, key: UUID) -> Any: result = self._results[key] if result is GatherIncomplete: raise GatherIncomplete( "Task is not complete. " "Results should not be retrieved until the task group exits." ) return result async def __aenter__(self) -> Self: await self._task_group.__aenter__() return self async def __aexit__(self, *tb: Any) -> Optional[bool]: # pyright: ignore[reportIncompatibleMethodOverride] try: retval = await self._task_group.__aexit__(*tb) return retval finally: del self._task_group def create_gather_task_group() -> GatherTaskGroup: """Create a new task group that gathers results""" # This function matches the AnyIO API which uses callables since the concrete # task group class depends on the async library being used and cannot be # determined until runtime return GatherTaskGroup(anyio.create_task_group()) async def gather(*calls: Callable[[], Coroutine[Any, Any, T]]) -> list[T]: """ Run calls concurrently and gather their results. Unlike `asyncio.gather` this expects to receive _callables_ not _coroutines_. This matches `anyio` semantics. """ keys: list[UUID] = [] async with create_gather_task_group() as tg: for call in calls: keys.append(tg.start_soon(call)) return [tg.get_result(key) for key in keys]
GatherTaskGroup
python
bokeh__bokeh
tests/unit/bokeh/models/test_plots.py
{ "start": 2091, "end": 2713 }
class ____: def test_basic(self) -> None: plot = figure(tools='') x = plot.legend assert isinstance(x, bmp._list_attr_splat) assert len(x) == 0 plot.scatter([1,2], [3,4], legend_label="foo") x = plot.legend assert isinstance(x, bmp._list_attr_splat) assert len(x) == 1 def test_warning(self) -> None: plot = figure(tools='') with pytest.warns(UserWarning) as warns: plot.legend.location = "above" assert len(warns) == 1 assert warns[0].message.args[0] == _LEGEND_EMPTY_WARNING
TestPlotLegendProperty
python
html5lib__html5lib-python
html5lib/tests/sanitizer.py
{ "start": 439, "end": 1869 }
class ____(pytest.Item): def __init__(self, name, parent, test): super(SanitizerTest, self).__init__(name, parent) self.obj = lambda: 1 # this is to hack around skipif needing a function! self.test = test def runtest(self): input = self.test["input"] expected = self.test["output"] parsed = parseFragment(input) with pytest.deprecated_call(): serialized = serialize(parsed, sanitize=True, omit_optional_tags=False, use_trailing_solidus=True, space_before_trailing_solidus=False, quote_attr_values="always", quote_char="'", alphabetical_attributes=True) errorMsg = "\n".join(["\n\nInput:", input, "\nExpected:", expected, "\nReceived:", serialized]) assert expected == serialized, errorMsg def repr_failure(self, excinfo): traceback = excinfo.traceback ntraceback = traceback.cut(path=__file__) excinfo.traceback = ntraceback.filter() return excinfo.getrepr(funcargs=True, showlocals=False, style="short", tbfilter=False)
SanitizerTest
python
huggingface__transformers
src/transformers/models/hubert/modular_hubert.py
{ "start": 4387, "end": 4482 }
class ____(Wav2Vec2EncoderStableLayerNorm): pass @auto_docstring
HubertEncoderStableLayerNorm
python
django__django
tests/defer_regress/models.py
{ "start": 591, "end": 697 }
class ____(models.Model): name = models.CharField(max_length=10) value = models.IntegerField()
Child
python
readthedocs__readthedocs.org
readthedocs/oauth/admin.py
{ "start": 2437, "end": 3092 }
class ____(admin.ModelAdmin): """Admin configuration for the RemoteOrganizationRelation model.""" raw_id_fields = ( "account", "remote_organization", "user", ) list_select_related = ( "remote_organization", "user", "account", ) list_display = ( "id", "remote_organization", "user", "account", "vcs_provider", ) list_filter = ("remote_organization__vcs_provider",) def vcs_provider(self, obj): """Get the display name for the VCS provider.""" return obj.remote_organization.vcs_provider
RemoteOrganizationRelationAdmin
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 33727, "end": 33843 }
class ____(Structure): _fields_ = (("data_owner", p_str16), ("offset", p_uint64), ("size", p_uint64))
note_command
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constructors.py
{ "start": 257, "end": 762 }
class ____: HOST = "api.some.com/1.1" AUTHENTICATE_URL = f"https://{HOST}/some.json" def __init__(self, oauth_token: str, oauth_token_secret: str) -> None: self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret @classmethod def from_default_keys(cls, oauth_token: str, oauth_token_secret: str) -> "SomeAPI": return cls(oauth_token, oauth_token_secret) def async_get_authenticated_user(self): eval(self.AUTHENTICATE_URL)
SomeAPI
python
scipy__scipy
scipy/optimize/tests/test_minpack.py
{ "start": 8929, "end": 9829 }
class ____: def setup_method(self): self.nfev = threading.local() def zero_f(self, y): if not hasattr(self.nfev, 'c'): self.nfev.c = 0 self.nfev.c += 1 return y**2-3 @pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov', 'df-sane']) def test_root_nfev(self, method): self.nfev.c = 0 solution = optimize.root(self.zero_f, 100, method=method) assert solution.nfev == self.nfev.c def test_fsolve_nfev(self): self.nfev.c = 0 x, info, ier, mesg = optimize.fsolve(self.zero_f, 100, full_output=True) assert info['nfev'] == self.nfev.c
TestNfev
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-make-array-continuous.py
{ "start": 749, "end": 1171 }
class ____(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) nums = sorted(set(nums)) result = right = 0 for left in xrange(len(nums)): while right < len(nums) and nums[right] <= nums[left]+n-1: right += 1 result = max(result, right-left) return n-result
Solution2
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 184589, "end": 185584 }
class ____(PyObjectType, PythonTypeConstructorMixin): """ For things like ClassVar, Optional, etc, which are not types and disappear during type analysis. """ def __init__(self, name): super().__init__() self.set_python_type_constructor_name(name) self.modifier_name = name def __repr__(self): return self.name def resolve(self): return self def specialize_here(self, pos, env, template_values=None): if len(template_values) != 1: if self.modifier_name == "typing.Union": return None error(pos, "'%s' takes exactly one template argument." % self.name) return error_type if template_values[0] is None: # FIXME: allowing unknown types for now since we don't recognise all Python types. return None # Replace this type with the actual 'template' argument. return template_values[0].resolve()
SpecialPythonTypeConstructor
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/ColorMapButton.py
{ "start": 3070, "end": 3878 }
class ____(ColorMapDisplayMixin, QtWidgets.QWidget): sigColorMapChanged = QtCore.Signal(object) def __init__(self): QtWidgets.QWidget.__init__(self) ColorMapDisplayMixin.__init__(self, orientation='horizontal') def colorMapChanged(self): cmap = self.colorMap() self.sigColorMapChanged.emit(cmap) self.update() def paintEvent(self, evt): painter = QtGui.QPainter(self) self.paintColorMap(painter, self.contentsRect()) painter.end() def mouseReleaseEvent(self, evt): if evt.button() != QtCore.Qt.MouseButton.LeftButton: return # position the menu below the widget pos = self.mapToGlobal(self.pos()) pos.setY(pos.y() + self.height()) self.getMenu().popup(pos)
ColorMapButton
python
falconry__falcon
falcon/errors.py
{ "start": 103370, "end": 105818 }
class ____(HTTPBadRequest): """400 Bad Request. Request media is invalid. This exception is raised by a media validator (such as :func:`jsonschema.validate <falcon.media.validators.jsonschema.validate>`) when ``req.media`` is successfully deserialized, but fails to validate against the configured schema. The cause of this exception, if any, is stored in the ``__cause__`` attribute using the "raise ... from" form when raising. Note: All the arguments must be passed as keyword only. Keyword Args: title (str): Error title (default '400 Bad Request'). description (str): Human-friendly description of the error, along with a helpful suggestion or two. headers (dict or list): A ``dict`` of header names and values to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and *value* must be of type ``str`` or ``StringType``, and only character values 0x00 through 0xFF may be used on platforms that use wide characters. Note: The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client Note: Falcon can process a list of ``tuple`` slightly faster than a ``dict``. href (str): A URL someone can visit to find out more information (default ``None``). Unicode characters are percent-encoded. href_text (str): If href is given, use this as the friendly title/description for the link (default 'API documentation for this error'). code (int): An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default ``None``). """ def __init__( self, *, title: str | None = None, description: str | None = None, headers: HeaderArg | None = None, **kwargs: HTTPErrorKeywordArguments, ) -> None: super().__init__( title=title, description=description, headers=headers, **kwargs, )
MediaValidationError
python
gevent__gevent
src/gevent/testing/util.py
{ "start": 17572, "end": 18963 }
class ____(ExampleMixin, unittest.TestCase): popen = None def running_server(self): from contextlib import contextmanager @contextmanager def running_server(): with self.start_example() as popen: self.popen = popen self.before() yield self.after() return running_server() def test(self): with self.running_server(): self._run_all_tests() def before(self): if self.before_delay is not None: sleep(self.before_delay) self.assertIsNone(self.popen.poll(), '%s died with code %s' % ( self.example, self.popen.poll(), )) def after(self): if self.after_delay is not None: sleep(self.after_delay) self.assertIsNone(self.popen.poll(), '%s died with code %s' % ( self.example, self.popen.poll(), )) def _run_all_tests(self): ran = False for method in sorted(dir(self)): if method.startswith('_test'): function = getattr(self, method) if callable(function): function() ran = True assert ran
TestServer
python
getsentry__sentry
src/sentry/quotas/redis.py
{ "start": 640, "end": 10647 }
class ____(Quota): #: The ``grace`` period allows accommodating for clock drift in TTL #: calculation since the clock on the Redis instance used to store quota #: metrics may not be in sync with the computer running this code. grace = 60 def __init__(self, **options: object): self.is_redis_cluster, self.cluster, options = get_dynamic_cluster_from_options( "SENTRY_QUOTA_OPTIONS", options ) # Based on the `is_redis_cluster` flag, self.cluster is set two one of # the following two objects: # - false: `cluster` is a `RBCluster`. Call `get_local_client_for_key` # on the cluster to resolve a client to run a script or query a key. # - true: `cluster` is a `RedisCluster`. It automatically dispatches to # the correct node and can be used as a client directly. super().__init__(**options) self.namespace = "quota" def validate(self) -> None: validate_dynamic_cluster(self.is_redis_cluster, self.cluster) def __get_redis_client(self, routing_key: str) -> RedisCluster | rb.RoutingClient: if is_instance_redis_cluster(self.cluster, self.is_redis_cluster): return self.cluster elif is_instance_rb_cluster(self.cluster, self.is_redis_cluster): return self.cluster.get_local_client_for_key(routing_key) else: raise AssertionError("unreachable") def __get_redis_key( self, quota: QuotaConfig, timestamp: float, shift: int, organization_id: int ) -> str: scope_id = quota.scope_id or "" if quota.scope != QuotaScope.ORGANIZATION else "" local_key = f"{quota.id}{{{organization_id}}}{scope_id}" interval = quota.window return f"{self.namespace}:{local_key}:{int((timestamp - shift) // interval)}" def get_quotas( self, project: Project, key: ProjectKey | None = None, keys: Iterable[ProjectKey] | None = None, ) -> list[QuotaConfig]: if key: key.project = project results = [*self.get_abuse_quotas(project.organization)] with sentry_sdk.start_span(op="redis.get_quotas.get_monitor_quota") as span: span.set_tag("project.id", project.id) mrlquota = self.get_monitor_quota(project) if mrlquota[0] is not None: results.append( QuotaConfig( id="mrl", limit=mrlquota[0], window=mrlquota[1], scope=QuotaScope.PROJECT, scope_id=project.id, categories=[DataCategory.MONITOR], reason_code="monitor_rate_limit", ) ) if key and not keys: keys = [key] elif not keys: keys = [] for key in keys: with sentry_sdk.start_span(op="redis.get_quotas.get_key_quota") as span: span.set_tag("key.id", key.id) kquota = self.get_key_quota(key) if kquota[0] is not None: results.append( QuotaConfig( id="k", scope=QuotaScope.KEY, scope_id=key.id, categories=DataCategory.error_categories(), limit=kquota[0], window=kquota[1], reason_code="key_quota", ) ) return results def get_usage( self, organization_id: int, quotas: list[QuotaConfig], timestamp: float | None = None ) -> list[int | None]: if timestamp is None: timestamp = time() def get_usage_for_quota( client: RedisCluster, quota: QuotaConfig ) -> tuple[str | None, str | None]: if not quota.should_track: return None, None key = self.__get_redis_key( quota, timestamp, organization_id % quota.window, organization_id ) refund_key = self.get_refunded_quota_key(key) return client.get(key), client.get(refund_key) def get_value_for_result(result, refund_result) -> int | None: if result is None: return None return int(result.value or 0) - int(refund_result.value or 0) if is_instance_redis_cluster(self.cluster, self.is_redis_cluster): results = [get_usage_for_quota(self.cluster, quota) for quota in quotas] elif is_instance_rb_cluster(self.cluster, self.is_redis_cluster): with self.cluster.fanout() as client: target = client.target_key(str(organization_id)) results = [get_usage_for_quota(target, quota) for quota in quotas] else: AssertionError("unreachable") return [get_value_for_result(*r) for r in results] def get_refunded_quota_key(self, key: str) -> str: return f"r:{key}" @sentry_sdk.tracing.trace def refund( self, project: Project, key: ProjectKey | None = None, timestamp: float | None = None, category: DataCategory | None = None, quantity: int | None = None, ) -> None: if timestamp is None: timestamp = time() if category is None: category = DataCategory.ERROR if quantity is None: quantity = 1 # only refund quotas that can be tracked and that specify the given # category. an empty categories list usually refers to all categories, # but such quotas are invalid with counters. quotas = [ quota for quota in self.get_quotas(project, key=key) if quota.should_track and category in quota.categories ] if not quotas: return client = self.__get_redis_client(str(project.organization_id)) pipe = client.pipeline() for quota in quotas: shift = project.organization_id % quota.window # kind of arbitrary, but seems like we don't want this to expire til we're # sure the window is over? expiry = self.get_next_period_start(quota.window, shift, timestamp) + self.grace return_key = self.get_refunded_quota_key( self.__get_redis_key(quota, timestamp, shift, project.organization_id) ) pipe.incr(return_key, quantity) pipe.expireat(return_key, int(expiry)) pipe.execute() def get_next_period_start(self, interval: int, shift: int, timestamp: float) -> float: """Return the timestamp when the next rate limit period begins for an interval.""" return (((timestamp - shift) // interval) + 1) * interval + shift def is_rate_limited( self, project: Project, key: ProjectKey | None = None, timestamp: float | None = None ) -> RateLimited | NotRateLimited: # XXX: This is effectively deprecated and scheduled for removal. Event # ingestion quotas are now enforced in Relay. This function will be # deleted once the Python store endpoints are removed. if timestamp is None: timestamp = time() # Relay supports separate rate limiting per data category and and can # handle scopes explicitly. This function implements a simplified logic # that treats all events the same and ignores transaction rate limits. # Thus, we filter for (1) no categories, which implies this quota # affects all data, and (2) quotas that specify `error` events. quotas = [ q for q in self.get_quotas(project, key=key) if not q.categories or DataCategory.ERROR in q.categories ] # If there are no quotas to actually check, skip the trip to the database. if not quotas: return NotRateLimited() keys: list[str] = [] args: list[int] = [] for quota in quotas: if quota.limit == 0: # A zero-sized quota is the absolute worst-case. Do not call # into Redis at all, and do not increment any keys, as one # quota has reached capacity (this is how regular quotas behave # as well). assert quota.window is None assert not quota.should_track return RateLimited(retry_after=None, reason_code=quota.reason_code) assert quota.should_track shift: int = project.organization_id % quota.window quota_key = self.__get_redis_key(quota, timestamp, shift, project.organization_id) return_key = self.get_refunded_quota_key(quota_key) keys.extend((quota_key, return_key)) expiry = self.get_next_period_start(quota.window, shift, timestamp) + self.grace # limit=None is represented as limit=-1 in lua lua_quota = quota.limit if quota.limit is not None else -1 args.extend((lua_quota, int(expiry))) if not keys or not args: return NotRateLimited() client = self.__get_redis_client(str(project.organization_id)) rejections = is_rate_limited(keys, args, client) if not any(rejections): return NotRateLimited() worst_case: tuple[float, int | None] = (0, None) for quota, rejected in zip(quotas, rejections): if not rejected: continue shift = project.organization_id % quota.window delay = self.get_next_period_start(quota.window, shift, timestamp) - timestamp if delay > worst_case[0]: worst_case = (delay, quota.reason_code) return RateLimited(retry_after=worst_case[0], reason_code=worst_case[1])
RedisQuota
python
huggingface__transformers
tests/models/blip/test_image_processing_blip.py
{ "start": 4083, "end": 5193 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = BlipImageProcessor if is_vision_available() else None fast_image_processing_class = BlipImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = BlipImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processor, "do_resize")) self.assertTrue(hasattr(image_processor, "size")) self.assertTrue(hasattr(image_processor, "do_normalize")) self.assertTrue(hasattr(image_processor, "image_mean")) self.assertTrue(hasattr(image_processor, "image_std")) self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
BlipImageProcessingTestFourChannels
python
pydantic__pydantic
pydantic/errors.py
{ "start": 4816, "end": 5142 }
class ____(PydanticUserError): """An error raised during failures to generate a JSON schema for some `CoreSchema`. Attributes: message: Description of the error. """ def __init__(self, message: str) -> None: super().__init__(message, code='invalid-for-json-schema')
PydanticInvalidForJsonSchema
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/operators/search_ads.py
{ "start": 5122, "end": 6257 }
class ____(_GoogleSearchAdsBaseOperator): """ Retrieve metadata for a resource or a field. .. seealso: For API documentation check: https://developers.google.com/search-ads/reporting/api/reference/rest/v0/searchAds360Fields/get .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GoogleSearchAdsGetFieldOperator` :param field_name: The name of the field. :param gcp_conn_id: The connection ID to use when fetching connection info. :param api_version: The version of the API that will be requested for example 'v0'. """ def __init__( self, *, field_name: str, **kwargs, ): super().__init__(**kwargs) self.field_name = field_name def execute(self, context: Context) -> Any: self.log.info("Retrieving the metadata for the field '%s'", self.field_name) response = self.hook.get_field(field_name=self.field_name) self.log.info("Retrieved field: %s", response["resourceName"]) return response
GoogleSearchAdsGetFieldOperator
python
PyCQA__pylint
tests/functional/g/generic_class_syntax_py312.py
{ "start": 59, "end": 189 }
class ____[_T: float]: last_update: int | None = None def __init__(self, data: _T) -> None: self.data = data
Entity
python
django__django
tests/filtered_relation/models.py
{ "start": 2601, "end": 2679 }
class ____(models.Model): currency = models.CharField(max_length=3)
Currency
python
pypa__hatch
tests/config/test_model.py
{ "start": 20384, "end": 22066 }
class ____: def test_default(self): config = RootConfig({}) assert config.publish == config.publish == {"index": {"repo": "main"}} assert config.raw_data == {"publish": {"index": {"repo": "main"}}} def test_defined(self): config = RootConfig({"publish": {"foo": {"username": "", "password": ""}}}) assert config.publish == {"foo": {"username": "", "password": ""}} assert config.raw_data == {"publish": {"foo": {"username": "", "password": ""}}} def test_not_table(self, helpers): config = RootConfig({"publish": 9000}) with pytest.raises( ConfigurationError, match=helpers.dedent( """ Error parsing config: publish must be a table""" ), ): _ = config.publish def test_data_not_table(self, helpers): config = RootConfig({"publish": {"foo": 9000}}) with pytest.raises( ConfigurationError, match=helpers.dedent( """ Error parsing config: publish -> foo must be a table""" ), ): _ = config.publish def test_set_lazy_error(self, helpers): config = RootConfig({}) config.publish = 9000 assert config.raw_data == {"publish": 9000} with pytest.raises( ConfigurationError, match=helpers.dedent( """ Error parsing config: publish must be a table""" ), ): _ = config.publish
TestPublish
python
jazzband__django-model-utils
tests/models.py
{ "start": 3386, "end": 3484 }
class ____(TimeStampedModel): test_field = models.PositiveSmallIntegerField(default=0)
TimeStamp
python
tensorflow__tensorflow
tensorflow/python/distribute/values_v2_test.py
{ "start": 12954, "end": 13759 }
class ____(_VariableInterfaceTestBase): def create_variable(self, initial_value=1., **kwargs): variables = [] for device in self.devices: with ops.device(device): variables.append( variables_lib.Variable(initial_value, **kwargs)) return values_v2.DistributedVariable(variables) # Prevent the base class from running. del _VariableInterfaceTestBase @combinations.generate( combinations.combine( strategy=[ strategy_combinations.tpu_strategy, strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_two_gpus, ], enable_packed_handle=[True, False], tf_function=[combinations.tf_function, combinations.no_tf_function]))
DistributedVariableInterfaceTest
python
huggingface__transformers
tests/models/musicgen_melody/test_modeling_musicgen_melody.py
{ "start": 5953, "end": 18970 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = (MusicgenMelodyModel, MusicgenMelodyForCausalLM) if is_torch_available() else () # Doesn't run generation tests. See `greedy_sample_model_classes` below all_generative_model_classes = () greedy_sample_model_classes = ( (MusicgenMelodyForCausalLM,) if is_torch_available() else () ) # the model uses a custom generation method so we only run a specific subset of the generation tests test_resize_embeddings = False def setUp(self): self.model_tester = MusicgenMelodyDecoderTester(self) self.config_tester = ConfigTester(self, config_class=MusicgenMelodyDecoderConfig, hidden_size=16) def test_config(self): self.config_tester.run_common_tests() # special case for labels # Copied from tests.models.musicgen.test_modeling_musicgen.MusicgenDecoderTest._prepare_for_class def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: inputs_dict["labels"] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length, self.model_tester.num_codebooks), dtype=torch.long, device=torch_device, ) return inputs_dict # Copied from tests.models.musicgen.test_modeling_musicgen.MusicgenDecoderTest.check_training_gradient_checkpointing with Musicgen->MusicgenMelody def check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=None): if not self.model_tester.is_training: self.skipTest(reason="model_tester.is_training is set to False") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.use_cache = False config.return_dict = True model = MusicgenMelodyForCausalLM(config) model.to(torch_device) model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs) model.train() # Contrarily to the initial method, we don't unfreeze freezed parameters. # Indeed, sinusoidal position embeddings have frozen weights that should stay frozen. optimizer = torch.optim.SGD(model.parameters(), lr=0.01) inputs = self._prepare_for_class(inputs_dict, MusicgenMelodyForCausalLM, return_labels=True) loss = model(**inputs).loss loss.backward() optimizer.step() for k, v in model.named_parameters(): if v.requires_grad: self.assertTrue(v.grad is not None, f"{k} in {MusicgenMelodyForCausalLM.__name__} has no gradient!") # override since we have to compute the input embeddings over codebooks def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) input_ids = inputs["input_ids"] del inputs["input_ids"] embed_tokens = model.get_input_embeddings() input_ids = input_ids.reshape(-1, config.num_codebooks, input_ids.shape[-1]) inputs["inputs_embeds"] = sum( embed_tokens[codebook](input_ids[:, codebook]) for codebook in range(config.num_codebooks) ) with torch.no_grad(): model(**inputs)[0] # override since we have embeddings / LM heads over multiple codebooks def test_model_get_set_embeddings(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) first_embed = model.get_input_embeddings()[0] self.assertIsInstance(first_embed, torch.nn.Embedding) lm_heads = model.get_output_embeddings() self.assertTrue(lm_heads is None or isinstance(lm_heads[0], torch.nn.Linear)) @unittest.skip(reason="MusicGen melody does not use inputs_embeds") def test_inputs_embeds_matches_input_ids(self): pass @unittest.skip(reason="this model doesn't support all arguments tested") def test_model_outputs_equivalence(self): pass @unittest.skip(reason="this model has multiple inputs embeds and lm heads that should not be tied") def test_tied_weights_keys(self): pass def _get_logits_processor_kwargs(self, do_sample=False, config=None): logits_processor_kwargs = {} return logits_processor_kwargs def test_greedy_generate_stereo_outputs(self): original_audio_channels = self.model_tester.audio_channels self.model_tester.audio_channels = 2 super().test_greedy_generate_dict_outputs() self.model_tester.audio_channels = original_audio_channels @require_flash_attn @require_torch_gpu @mark.flash_attn_test @slow # Copied from tests.models.musicgen.test_modeling_musicgen.MusicgenDecoderTest.test_flash_attn_2_inference_equivalence def test_flash_attn_2_inference_equivalence(self): for model_class in self.all_model_classes: if not model_class._supports_flash_attn: self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model_fa = model_class.from_pretrained( tmpdirname, dtype=torch.bfloat16, attn_implementation="flash_attention_2", ) model_fa.to(torch_device) model = model_class.from_pretrained(tmpdirname, dtype=torch.bfloat16) model.to(torch_device) # Ignore copy dummy_input = inputs_dict[model.main_input_name] if dummy_input.dtype in [torch.float32, torch.float16]: dummy_input = dummy_input.to(torch.bfloat16) dummy_attention_mask = inputs_dict.get("attention_mask", None) if dummy_attention_mask is not None: # Ignore copy dummy_attention_mask[:, 1:] = 1 dummy_attention_mask[:, :1] = 0 # Ignore copy outputs = model(dummy_input, output_hidden_states=True) # Ignore copy outputs_fa = model_fa(dummy_input, output_hidden_states=True) logits = ( outputs.hidden_states[-1] if not model.config.is_encoder_decoder else outputs.decoder_hidden_states[-1] ) logits_fa = ( outputs_fa.hidden_states[-1] if not model.config.is_encoder_decoder else outputs_fa.decoder_hidden_states[-1] ) assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2) # Ignore copy other_inputs = { "output_hidden_states": True, } if dummy_attention_mask is not None: other_inputs["attention_mask"] = dummy_attention_mask outputs = model(dummy_input, **other_inputs) outputs_fa = model_fa(dummy_input, **other_inputs) logits = ( outputs.hidden_states[-1] if not model.config.is_encoder_decoder else outputs.decoder_hidden_states[-1] ) logits_fa = ( outputs_fa.hidden_states[-1] if not model.config.is_encoder_decoder else outputs_fa.decoder_hidden_states[-1] ) assert torch.allclose(logits_fa[1:], logits[1:], atol=4e-2, rtol=4e-2) # check with inference + dropout model.train() _ = model_fa(dummy_input, **other_inputs) @require_flash_attn @require_torch_gpu @mark.flash_attn_test @slow # Copied from tests.models.musicgen.test_modeling_musicgen.MusicgenDecoderTest.test_flash_attn_2_inference_equivalence_right_padding def test_flash_attn_2_inference_equivalence_right_padding(self): for model_class in self.all_model_classes: if not model_class._supports_flash_attn: self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model_fa = model_class.from_pretrained( tmpdirname, dtype=torch.bfloat16, attn_implementation="flash_attention_2", ) model_fa.to(torch_device) model = model_class.from_pretrained(tmpdirname, dtype=torch.bfloat16) model.to(torch_device) # Ignore copy dummy_input = inputs_dict[model.main_input_name] if dummy_input.dtype in [torch.float32, torch.float16]: dummy_input = dummy_input.to(torch.bfloat16) dummy_attention_mask = inputs_dict.get("attention_mask", None) if dummy_attention_mask is not None: # Ignore copy dummy_attention_mask[:, :-1] = 1 dummy_attention_mask[:, -1:] = 0 if model.config.is_encoder_decoder: decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input) outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) outputs_fa = model_fa(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) else: outputs = model(dummy_input, output_hidden_states=True) outputs_fa = model_fa(dummy_input, output_hidden_states=True) logits = ( outputs.hidden_states[-1] if not model.config.is_encoder_decoder else outputs.decoder_hidden_states[-1] ) logits_fa = ( outputs_fa.hidden_states[-1] if not model.config.is_encoder_decoder else outputs_fa.decoder_hidden_states[-1] ) assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2) # Ignore copy other_inputs = { "output_hidden_states": True, } if dummy_attention_mask is not None: other_inputs["attention_mask"] = dummy_attention_mask outputs = model(dummy_input, **other_inputs) outputs_fa = model_fa(dummy_input, **other_inputs) logits = ( outputs.hidden_states[-1] if not model.config.is_encoder_decoder else outputs.decoder_hidden_states[-1] ) logits_fa = ( outputs_fa.hidden_states[-1] if not model.config.is_encoder_decoder else outputs_fa.decoder_hidden_states[-1] ) assert torch.allclose(logits_fa[:-1], logits[:-1], atol=4e-2, rtol=4e-2) @unittest.skip( reason=( "MusicGen has a custom set of generation tests that rely on `GenerationTesterMixin`, controlled by " "`greedy_sample_model_classes`" ) ) def test_generation_tester_mixin_inheritance(self): pass def prepare_musicgen_melody_inputs_dict( config, input_ids, decoder_input_ids, attention_mask=None, decoder_attention_mask=None, labels=None, ): if decoder_attention_mask is None: decoder_attention_mask = decoder_input_ids.reshape( -1, config.decoder.num_codebooks, decoder_input_ids.shape[-1] )[:, 0, :] decoder_attention_mask = decoder_attention_mask.ne(config.decoder.pad_token_id) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "labels": labels, }
MusicgenMelodyDecoderTest
python
google__jax
docs/autodidax.py
{ "start": 32121, "end": 32311 }
class ____: val: Any aval: ShapedArray def __init__(self, val): self.aval = aval = raise_to_shaped(get_aval(val)) self.val = np.array(val, aval.dtype) Atom = Union[Var, Lit]
Lit
python
huggingface__transformers
src/transformers/models/gemma3n/modular_gemma3n.py
{ "start": 92288, "end": 92989 }
class ____(Gemma2PreTrainedModel): config: Gemma3nConfig input_modalities = ("image", "text", "audio") _no_split_modules = ["Gemma3nTextDecoderLayer"] @torch.no_grad() def _init_weights(self, module): PreTrainedModel._init_weights(self, module) if isinstance(module, Gemma3nAudioCumulativeGroupNorm): init.ones_(module.weight) elif isinstance(module, Gemma3nAudioAttention): init.zeros_(module.per_dim_scale) elif isinstance(module, Gemma3nTextAltUp): init.zeros_(module.correct_output_scale) @auto_docstring(custom_intro="The base Gemma 3n language model without a language modeling head.")
Gemma3nPreTrainedModel
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_data_versions.py
{ "start": 1590, "end": 17003 }
class ____(ExecutingGraphQLContextTestMatrix): # Storage dir is shared between tests in the same class, so we need to clean it out. @pytest.fixture(autouse=True) def clean_storage_directory(self, graphql_context): """Clean IO manager storage directory before each test to prevent pollution.""" # Clean before test runs storage_dir = Path(graphql_context.instance.storage_directory()) if storage_dir.exists(): shutil.rmtree(storage_dir) storage_dir.mkdir(parents=True) yield # Clean after test runs if storage_dir.exists(): shutil.rmtree(storage_dir) storage_dir.mkdir(parents=True) def test_dependencies_changed(self, graphql_context): repo_v2 = get_repo_v2() instance = graphql_context.instance with define_out_of_process_context(__file__, "get_repo_v1", instance) as context_v1: assert materialize_assets(context_v1, [AssetKey(["foo"]), AssetKey(["bar"])]) wait_for_runs_to_finish(context_v1.instance) with define_out_of_process_context(__file__, "get_repo_v2", instance) as context_v2: assert _fetch_data_versions(context_v2, repo_v2) def test_stale_status(self, graphql_context): repo = get_repo_v1() instance = graphql_context.instance with define_out_of_process_context(__file__, "get_repo_v1", instance) as context: result = _fetch_data_versions(context, repo) foo = _get_asset_node(result, "foo") assert foo["dataVersion"] is None assert foo["staleStatus"] == "MISSING" assert foo["staleCauses"] == [] assert materialize_assets(context, [AssetKey(["foo"]), AssetKey(["bar"])]) wait_for_runs_to_finish(context.instance) with define_out_of_process_context(__file__, "get_repo_v1", instance) as context: result = _fetch_data_versions(context, repo) foo = _get_asset_node(result, "foo") assert foo["dataVersion"] is not None assert foo["staleStatus"] == "FRESH" assert foo["staleCauses"] == [] assert materialize_assets(context, asset_selection=[AssetKey(["foo"])]) wait_for_runs_to_finish(context.instance) with define_out_of_process_context(__file__, "get_repo_v1", instance) as context: result = _fetch_data_versions(context, repo) bar = _get_asset_node(result, "bar") assert bar["dataVersion"] is not None assert bar["staleStatus"] == "STALE" assert bar["staleCauses"] == [ { "key": {"path": ["foo"]}, "category": "DATA", "reason": "has a new materialization", "dependency": None, } ] def test_stale_status_partitioned(self, graphql_context): instance = graphql_context.instance instance.add_dynamic_partitions("dynamic", ["alpha", "beta"]) with define_out_of_process_context(__file__, "get_repo_partitioned", instance) as context: for key in ["foo", "bar", "dynamic_asset"]: result = _fetch_partition_data_versions(context, AssetKey([key])) node = _get_asset_node(result) assert node["dataVersion"] is None assert node["dataVersionByPartition"] == [None, None] assert ( node["staleStatus"] == "FRESH" ) # always returns fresh for this undefined field assert node["staleStatusByPartition"] == ["MISSING", "MISSING"] assert node["staleCauses"] == [] # always returns empty for this undefined field assert node["staleCausesByPartition"] == [[], []] assert materialize_assets( context, [AssetKey(["foo"]), AssetKey(["bar"]), AssetKey("dynamic_asset")], ["alpha", "beta"], ) wait_for_runs_to_finish(context.instance) with define_out_of_process_context(__file__, "get_repo_partitioned", instance) as context: for key in ["foo", "bar", "dynamic_asset"]: result = _fetch_partition_data_versions(context, AssetKey([key]), "alpha") node = _get_asset_node(result) assert node["dataVersion"] == f"ok_{key}_alpha" assert node["dataVersionByPartition"] == [f"ok_{key}_alpha", f"ok_{key}_beta"] assert node["staleStatus"] == "FRESH" assert node["staleStatusByPartition"] == ["FRESH", "FRESH"] assert node["staleCauses"] == [] assert node["staleCausesByPartition"] == [[], []] assert materialize_assets( context, [AssetKey(["foo"])], ["alpha", "beta"], run_config_data={"ops": {"foo": {"config": {"prefix": "from_config"}}}}, ) wait_for_runs_to_finish(context.instance) with define_out_of_process_context(__file__, "get_repo_partitioned", instance) as context: result = _fetch_partition_data_versions(context, AssetKey(["foo"]), "alpha") foo = _get_asset_node(result, "foo") assert foo["dataVersion"] == "from_config_foo_alpha" assert foo["dataVersionByPartition"] == [ "from_config_foo_alpha", "from_config_foo_beta", ] assert foo["staleStatus"] == "FRESH" assert foo["staleStatusByPartition"] == ["FRESH", "FRESH"] result = _fetch_partition_data_versions( context, AssetKey(["bar"]), "alpha", ["beta", "alpha"] ) bar = _get_asset_node(result, "bar") assert bar["dataVersion"] == "ok_bar_alpha" assert bar["dataVersionByPartition"] == ["ok_bar_beta", "ok_bar_alpha"] assert bar["staleStatus"] == "STALE" assert bar["staleStatusByPartition"] == ["STALE", "STALE"] assert bar["staleCauses"] == [ { "key": {"path": ["foo"]}, "partitionKey": "alpha", "category": "DATA", "reason": "has a new data version", "dependency": None, "dependencyPartitionKey": None, } ] assert bar["staleCausesByPartition"] == [ [ { "key": {"path": ["foo"]}, "partitionKey": key, "category": "DATA", "reason": "has a new data version", "dependency": None, "dependencyPartitionKey": None, } ] for key in ["beta", "alpha"] ] def test_cross_repo_dependency(self, graphql_context): instance = graphql_context.instance with ( temp_workspace_file( [ ("repo1", __file__, "get_cross_repo_test_repo1"), ("repo2", __file__, "get_cross_repo_test_repo2"), ] ) as workspace_file, define_out_of_process_context(workspace_file, None, instance) as context, ): # Materialize the downstream asset. Provenance will store the version of foo as INITIAL. assert materialize_assets(context, [AssetKey(["bar"])], location_name="repo2") wait_for_runs_to_finish(context.instance) repo2 = get_cross_repo_test_repo2() result = _fetch_data_versions(context, repo2, location_name="repo2") bar = _get_asset_node(result, "bar") assert bar["staleStatus"] == "FRESH" def test_data_version_from_tags(self, graphql_context): repo_v1 = get_repo_v1() instance = graphql_context.instance with define_out_of_process_context(__file__, "get_repo_v1", instance) as context_v1: assert materialize_assets(context_v1, [AssetKey(["foo"]), AssetKey(["bar"])]) wait_for_runs_to_finish(context_v1.instance) result = _fetch_data_versions(context_v1, repo_v1) tags = result.data["assetNodes"][0]["assetMaterializations"][0]["tags"] dv_tag = next(tag for tag in tags if tag["key"] == DATA_VERSION_TAG) assert dv_tag["value"] == result.data["assetNodes"][0]["dataVersion"] def test_partitioned_self_dep(self, graphql_context): repo = get_repo_with_partitioned_self_dep_asset() instance = graphql_context.instance with define_out_of_process_context( __file__, "get_repo_with_partitioned_self_dep_asset", instance ) as context: result = _fetch_partition_data_versions( context, AssetKey(["a"]), partitions=["2020-01-01", "2020-01-02"] ) assert result assert result.data node = _get_asset_node(result, "a") assert node["staleStatusByPartition"] == ["MISSING", "MISSING"] result = _fetch_data_versions(context, repo) node = _get_asset_node(result, "b") assert node["staleStatus"] == "MISSING" def test_source_asset_job_name(self, graphql_context): get_observable_source_asset_repo() instance = graphql_context.instance with define_out_of_process_context( __file__, "get_observable_source_asset_repo", instance ) as context: selector = infer_repository_selector(context) result = execute_dagster_graphql( context, GET_ASSET_JOB_NAMES, variables={ "selector": selector, }, ) assert result and result.data foo_jobs = _get_asset_node(result.data["repositoryOrError"], "foo")["jobNames"] bar_jobs = _get_asset_node(result.data["repositoryOrError"], "bar")["jobNames"] baz_jobs = _get_asset_node(result.data["repositoryOrError"], "baz")["jobNames"] # All nodes should have separate job sets since there are two different partitions defs # and a non-partitioned observable. assert foo_jobs and foo_jobs != bar_jobs and foo_jobs != baz_jobs assert bar_jobs and bar_jobs != foo_jobs and bar_jobs != baz_jobs assert baz_jobs and baz_jobs != foo_jobs and baz_jobs != bar_jobs # Make sure none of our assets included in non-asset job assert "bop_job" not in foo_jobs assert "bop_job" not in bar_jobs assert "bop_job" not in baz_jobs # Make sure observable source asset does not appear in non-explicit observation job assert "foo_job" not in bar_jobs # Make sure observable source asset appears in explicit observation job assert "bar_job" in bar_jobs # ######################## # ##### REPOSITORY DEFS # ######################## # These are used to define definition state in the test functions above def get_repo_v1(): @asset def foo(): return True @asset def bar(foo): return True @repository def repo(): return [foo, bar] return repo def get_repo_v2(): @asset def bar(): return True @repository def repo(): return [bar] return repo def get_repo_partitioned(): partitions_def = StaticPartitionsDefinition(["alpha", "beta"]) dynamic_partitions_def = DynamicPartitionsDefinition(name="dynamic") class FooConfig(Config): prefix: str = "ok" @asset(partitions_def=partitions_def) def foo(context: OpExecutionContext, config: FooConfig) -> Output[bool]: return Output( True, data_version=DataVersion(f"{config.prefix}_foo_{context.partition_key}") ) @asset(partitions_def=partitions_def) def bar(context: OpExecutionContext, foo) -> Output[bool]: return Output(True, data_version=DataVersion(f"ok_bar_{context.partition_key}")) @asset(partitions_def=dynamic_partitions_def) def dynamic_asset(context: OpExecutionContext): return Output(True, data_version=DataVersion(f"ok_dynamic_asset_{context.partition_key}")) @repository def repo(): return [foo, bar, dynamic_asset] return repo def get_cross_repo_test_repo1(): @asset def foo(): pass @repository def repo1(): return [foo] return repo1 def get_cross_repo_test_repo2(): @asset(deps=["foo"]) def bar(): pass @repository def repo2(): return [bar] return repo2 def get_repo_with_partitioned_self_dep_asset(): @asset( partitions_def=DailyPartitionsDefinition(start_date="2020-01-01"), ins={ "a": AssetIn( partition_mapping=TimeWindowPartitionMapping(start_offset=-1, end_offset=-1) ) }, ) def a(a): del a @asset def b(a): return a @repository def repo(): return [a, b] return repo def get_observable_source_asset_repo(): @asset(partitions_def=StaticPartitionsDefinition(["1"])) def foo(): return 1 @observable_source_asset def bar(): return DataVersion("1") @asset(partitions_def=StaticPartitionsDefinition(["2"])) def baz(): return 1 @op def bop(): pass @job def bop_job(): bop() foo_job = define_asset_job("foo_job", [foo]) bar_job = define_asset_job("bar_job", [bar]) defs = Definitions( assets=[foo, bar, baz], jobs=[foo_job, bar_job, bop_job], ) return defs.get_repository_def() # ######################## # ##### HELPERS # ######################## def _fetch_data_versions( context: WorkspaceRequestContext, repo: RepositoryDefinition, location_name: Optional[str] = None, ): selector = infer_job_selector( context, repo.get_implicit_asset_job_names()[0], location_name=location_name ) return execute_dagster_graphql( context, GET_ASSET_DATA_VERSIONS, variables={ "pipelineSelector": selector, }, ) def _fetch_partition_data_versions( context: WorkspaceRequestContext, asset_key: AssetKey, partition: Optional[str] = None, partitions: Optional[Sequence[str]] = None, ): return execute_dagster_graphql( context, GET_ASSET_DATA_VERSIONS_BY_PARTITION, variables={ "assetKey": asset_key.to_graphql_input(), "partition": partition, "partitions": partitions, }, ) def _get_asset_node(result: Any, key: Optional[str] = None) -> Mapping[str, Any]: to_check = result if isinstance(result, dict) else result.data # GqlResult if key is None: # assume we are dealing with a single-node query return to_check["assetNodeOrError"] else: return ( to_check["assetNodeOrError"] if "assetNodeOrError" in to_check else next(node for node in to_check["assetNodes"] if node["assetKey"]["path"] == [key]) )
TestDataVersions
python
facelessuser__pymdown-extensions
pymdownx/tabbed.py
{ "start": 1403, "end": 11414 }
class ____(BlockProcessor): """Tabbed block processor.""" START = re.compile( r'(?:^|\n)={3}(\+|\+!|!\+|!)? +"(.*?)" *(?:\n|$)' ) COMPRESS_SPACES = re.compile(r' {2,}') def __init__(self, parser, config): """Initialize.""" super().__init__(parser) self.tab_group_count = 0 self.current_sibling = None self.content_indention = 0 self.alternate_style = config['alternate_style'] self.slugify = callable(config['slugify']) def detab_by_length(self, text, length): """Remove a tab from the front of each line of the given text.""" newtext = [] lines = text.split('\n') for line in lines: if line.startswith(' ' * length): newtext.append(line[length:]) elif not line.strip(): newtext.append('') # pragma: no cover else: break return '\n'.join(newtext), '\n'.join(lines[len(newtext):]) def parse_content(self, parent, block): """ Get sibling tab. Retrieve the appropriate sibling element. This can get tricky when dealing with lists. """ old_block = block non_tabs = '' tabbed_set = 'tabbed-set' if not self.alternate_style else 'tabbed-set tabbed-alternate' # We already acquired the block via test if self.current_sibling is not None: sibling = self.current_sibling block, non_tabs = self.detab_by_length(block, self.content_indent) self.current_sibling = None self.content_indent = 0 return sibling, block, non_tabs sibling = self.lastChild(parent) if sibling is None or sibling.tag.lower() != 'div' or sibling.attrib.get('class', '') != tabbed_set: sibling = None else: # If the last child is a list and the content is indented sufficient # to be under it, then the content's is sibling is in the list. if self.alternate_style: last_child = self.lastChild(self.lastChild(sibling)) tabbed_content = 'tabbed-block' else: last_child = self.lastChild(sibling) tabbed_content = 'tabbed-content' child_class = last_child.attrib.get('class', '') if last_child is not None else '' indent = 0 while last_child is not None: if ( sibling is not None and block.startswith(' ' * self.tab_length * 2) and last_child is not None and ( last_child.tag in ('ul', 'ol', 'dl') or ( last_child.tag == 'div' and child_class == tabbed_content ) ) ): # Handle nested tabbed content if last_child.tag == 'div' and child_class == tabbed_content: temp_child = self.lastChild(last_child) if temp_child is None or temp_child.tag not in ('ul', 'ol', 'dl'): break last_child = temp_child child_class = last_child.attrib.get('class', '') if last_child is not None else '' # The expectation is that we'll find an `<li>`. # We should get it's last child as well. sibling = self.lastChild(last_child) last_child = self.lastChild(sibling) if sibling is not None else None child_class = last_child.attrib.get('class', '') if last_child is not None else '' # Context has been lost at this point, so we must adjust the # text's indentation level so it will be evaluated correctly # under the list. block = block[self.tab_length:] indent += self.tab_length else: last_child = None if not block.startswith(' ' * self.tab_length): sibling = None if sibling is not None: indent += self.tab_length block, non_tabs = self.detab_by_length(old_block, indent) self.current_sibling = sibling self.content_indent = indent return sibling, block, non_tabs def test(self, parent, block): """Test block.""" if self.START.search(block): return True else: return self.parse_content(parent, block)[0] is not None def run(self, parent, blocks): """Convert to tabbed block.""" block = blocks.pop(0) m = self.START.search(block) tabbed_set = 'tabbed-set' if not self.alternate_style else 'tabbed-set tabbed-alternate' if m: # removes the first line if m.start() > 0: self.parser.parseBlocks(parent, [block[:m.start()]]) block = block[m.end():] sibling = self.lastChild(parent) block, non_tabs = self.detab(block) else: sibling, block, non_tabs = self.parse_content(parent, block) if m: special = m.group(1) if m.group(1) else '' title = m.group(2) if m.group(2) else m.group(3) index = 0 labels = None content = None if ( sibling is not None and sibling.tag.lower() == 'div' and sibling.attrib.get('class', '') == tabbed_set and '!' not in special ): first = False tab_group = sibling if self.alternate_style: index = [index for index, _ in enumerate(tab_group.findall('input'), 1)][-1] for d in tab_group.findall('div'): if d.attrib['class'] == 'tabbed-labels': labels = d elif d.attrib['class'] == 'tabbed-content': content = d if labels is not None and content is not None: break else: first = True self.tab_group_count += 1 tab_group = etree.SubElement( parent, 'div', {'class': tabbed_set, 'data-tabs': '%d:0' % self.tab_group_count} ) if self.alternate_style: labels = etree.SubElement( tab_group, 'div', {'class': 'tabbed-labels'} ) content = etree.SubElement( tab_group, 'div', {'class': 'tabbed-content'} ) data = tab_group.attrib['data-tabs'].split(':') tab_set = int(data[0]) tab_count = int(data[1]) + 1 attributes = { "name": "__tabbed_%d" % tab_set, "type": "radio" } if not self.slugify: attributes['id'] = "__tabbed_%d_%d" % (tab_set, tab_count) if first or '+' in special: attributes['checked'] = 'checked' # Remove any previously assigned "checked states" to siblings for i in tab_group.findall('input'): if i.attrib.get('name', '') == f'__tabbed_{tab_set}': if 'checked' in i.attrib: del i.attrib['checked'] attributes2 = {"for": "__tabbed_%d_%d" % (tab_set, tab_count)} if not self.slugify else {} if self.alternate_style: input_el = etree.Element( 'input', attributes ) tab_group.insert(index, input_el) lab = etree.SubElement( labels, "label", attributes2 ) lab.text = title div = etree.SubElement( content, "div", {'class': 'tabbed-block'} ) else: etree.SubElement( tab_group, 'input', attributes ) lab = etree.SubElement( tab_group, "label", attributes2 ) lab.text = title div = etree.SubElement( tab_group, "div", { "class": "tabbed-content" } ) tab_group.attrib['data-tabs'] = '%d:%d' % (tab_set, tab_count) else: if sibling.tag in ('li', 'dd') and sibling.text: # Sibling is a list item, but we need to wrap it's content should be wrapped in <p> text = sibling.text sibling.text = '' p = etree.SubElement(sibling, 'p') p.text = text div = sibling elif sibling.tag == 'div' and sibling.attrib.get('class', '') == tabbed_set: # Get `tabbed-content` under `tabbed-set` if self.alternate_style: div = self.lastChild(self.lastChild(sibling)) else: div = self.lastChild(sibling) else: # Pass anything else as the parent div = sibling self.parser.parseChunk(div, block) if non_tabs: # Insert the tabbed content back into blocks blocks.insert(0, non_tabs)
TabbedProcessor
python
tensorflow__tensorflow
tensorflow/python/distribute/input_lib.py
{ "start": 42008, "end": 54358 }
class ____(_IterableInput, composite_tensor.CompositeTensor): """Inputs created from dataset function.""" def __init__( self, input_workers, strategy, input_contexts=None, dataset_fn=None, options=None, components=None, element_spec=None, build=True, replica_order=None, ): """Makes an iterable from datasets created by the given function. Args: input_workers: an `InputWorkers` object. strategy: a `tf.distribute.Strategy` object, used to run all-reduce to handle last partial batch. input_contexts: A list of `InputContext` instances to be passed to call(s) to `dataset_fn`. Length and order should match worker order in `worker_device_pairs`. dataset_fn: A function that returns a `Dataset` given an `InputContext`. Either dataset_fn or components should be passed to construct DistributedDatasetsFromFunction. Use this when constructing DistributedDataset using a function. Use components when constructing using DistributedDatasetsFromFunctionSpec. options: `tf.distribute.InputOptions` used to control options on how this dataset is distributed. components: datasets when DistributedDatasetsFromFunction is constructed from DistributedDatasetsFromFunctionSpec. Only one of dataset or components should be passed. element_spec: element spec for DistributedDataset when constructing from DistributedDatasetSpec. This will be used to set the element_spec for DistributedDatasetsFromFunctionSpec and verified against element_spec from components. build: whether to build underlying datasets when this object is created. This is only useful for `ParameterServerStrategy` now. replica_order: the order of the replicas, which will be used to reorder the iterators to match the device order. """ super(DistributedDatasetsFromFunction, self).__init__( input_workers=input_workers) self._input_workers = input_workers self._strategy = strategy self._options = options self._replica_order = replica_order if dataset_fn is not None and components is not None: raise ValueError("Only one of dataset_fn or components should be set") if dataset_fn is None and components is None: raise ValueError("At least one of dataset_fn or components should be set") if dataset_fn is not None: if input_workers.num_workers != len(input_contexts): raise ValueError( "Number of input workers (%d) is not same as number of " "input_contexts (%d)" % (input_workers.num_workers, len(input_contexts))) self._input_contexts = input_contexts self._num_replicas_in_sync = self._input_contexts[0].num_replicas_in_sync self._dataset_fn = dataset_fn self._built = False if build: self.build() else: if element_spec is None: raise ValueError( "element_spec should also be passed when passing components") if not build: raise ValueError( "When constructing DistributedDatasetFromFunction with components, " "build should not be False. This is an internal error. Please file " "a bug.") self._element_spec = element_spec self._datasets = components self._num_replicas_in_sync = None self._built = True self._cardinality = _cardinality(self._datasets[0]) self._enable_get_next_as_optional = _enable_get_next_as_optional( self._strategy, self._datasets[0], self._cardinality) def build(self): assert not self._built distribute_start_time_ns = time.time_ns() self._datasets, element_spec = ( _create_datasets_from_function_with_input_context( self._input_contexts, self._input_workers, self._dataset_fn)) if context.executing_eagerly(): # Records the time to initialize the distributed dataset. context.async_wait() distribute_duration_ms = (time.time_ns() - distribute_start_time_ns) // 1_000_000 _distributed_dataset_from_function_initialization_time_milliseconds.get_cell( self._strategy.__class__.__name__, str(self._input_workers.num_workers)).add(distribute_duration_ms) self._element_spec = _create_distributed_tensor_spec( self._strategy, element_spec) self._cardinality = _cardinality(self._datasets[0]) self._enable_get_next_as_optional = _enable_get_next_as_optional( self._strategy, self._datasets[0], self._cardinality) self._built = True def auto_shard(self, num_shards, shard_ix): assert ( len(self._datasets) == len(self._input_workers.worker_devices) ), ( f"datasets: {len(self._datasets)}, " f"input workers: {len(self._input_workers.worker_devices)}" ) sharded_datasets = [] for i in range(len(self._input_workers.worker_devices)): with ops.colocate_with(self._datasets[i]._variant_tensor): # pylint: disable=protected-access sharded_datasets.append( input_ops.auto_shard_dataset( self._datasets[i], num_shards, shard_ix, self._num_replicas_in_sync ) ) return DistributedDatasetsFromFunction(self._input_workers, self._strategy, components=sharded_datasets, element_spec=self._element_spec, options=self._options) @property def cardinality(self): if not self._built: raise ValueError( "Cannot get the cardinality of a dataset that is not built") return self._cardinality def __iter__(self): if not (ops.executing_eagerly_outside_functions() or ops.get_default_graph().building_function): raise RuntimeError("__iter__() is only supported inside of tf.function " "or when eager execution is enabled.") if not self._built: raise ValueError("You need to use this dataset in " "ClusterCoordinator.create_per_worker_dataset.") canonicalize_devices = getattr(self._strategy, "_canonicalize_devices", True) iterators = _create_iterators_per_worker( self._datasets, self._input_workers, options=self._options, canonicalize_devices=canonicalize_devices) iterator = DistributedIterator( input_workers=self._input_workers, iterators=iterators, strategy=self._strategy, cardinality=self._cardinality, enable_get_next_as_optional=self._enable_get_next_as_optional, options=self._options, replica_order=self._replica_order, ) iterator._element_spec = self._element_spec # pylint: disable=protected-access # When async eager is enabled, sometimes the iterator may not finish # initialization before passing to a multi device function, add a sync # point here to make sure all underlying iterators are initialized. if context.executing_eagerly(): context.async_wait() return iterator @property def element_spec(self): """The type specification of an element of this dataset.""" # When partial batch handling is enabled, always set the batch dimension to # None, otherwise we just follow element_spec of the underlying dataset # (whose batch dimension may also be None). This is because with partial # batching handling we could always produce empty batches. if (self._enable_get_next_as_optional and self._strategy.extended._in_multi_worker_mode()): # pylint: disable=protected-access return nest.map_structure( _rebatch_as_dynamic, self._element_spec, expand_composites=False) return self._element_spec @property def _type_spec(self): return DistributedDatasetsFromFunctionSpec(self._input_workers, self._element_spec, self._strategy, self._options) def _dummy_tensor_fn(value_structure): """A function to create dummy tensors from `value_structure`.""" def create_dummy_tensor(spec): """Create a dummy tensor with possible batch dimensions set to 0.""" if hasattr(spec, "_create_empty_value"): # Type spec may overwrite default dummy values behavior by declaring the # `_create_empty_value(self)` method. This method must return a value # compatible with the type spec with batch dimensions set to 0 or fail if # such a value does not exist. This allows a composite tensor to customize # dummy values creation as, in general, its dummy value is not composed # from dummy components (e.g. `row_splits` tensor of a RaggedTensor is # never allowed to be empty). See b/183969859 for more discussions. # TODO(b/186079336): reconsider CompositeTensor support. return spec._create_empty_value() # pylint: disable=protected-access if isinstance(spec, ragged_tensor.RaggedTensorSpec): # Splice out the ragged dimensions. # pylint: disable=protected-access feature_shape = spec._shape[:1].concatenate( spec._shape[(1 + spec._ragged_rank):]) feature_type = spec._dtype # pylint: enable=protected-access else: feature_shape = spec.shape feature_type = spec.dtype # Ideally we should set the batch dimension to 0, however as in # DistributionStrategy we don't know the batch dimension, we try to # guess it as much as possible. If the feature has unknown dimensions, we # will set them to 0. If the feature shape is already static, we guess the # first dimension as batch dimension and set it to 0. dims = ([dim if dim is not None else 0 for dim in feature_shape.as_list()] if feature_shape else []) if dims and (isinstance(spec, ragged_tensor.RaggedTensorSpec) or feature_shape.is_fully_defined()): dims[0] = tensor_shape.Dimension(0) if isinstance(spec, sparse_tensor.SparseTensorSpec): return sparse_tensor.SparseTensor( values=array_ops.zeros(0, feature_type), indices=array_ops.zeros((0, len(dims)), dtypes.int64), dense_shape=dims) # Create the dummy tensor. dummy_tensor = array_ops.zeros(tensor_shape.TensorShape(dims), feature_type) if isinstance(spec, ragged_tensor.RaggedTensorSpec): # Reinsert the ragged dimensions with size 0. # pylint: disable=protected-access row_splits = array_ops.zeros(1, spec._row_splits_dtype) dummy_tensor = ragged_tensor.RaggedTensor.from_nested_row_splits( dummy_tensor, (row_splits,) * spec._ragged_rank, validate=False) # pylint: enable=protected-access return dummy_tensor return nest.map_structure(create_dummy_tensor, value_structure) def _get_value_or_dummy(input_workers, optional_list, produce_dummy): """Returns the value of the optionals or dummy values. Args: input_workers: the `InputWorkers`. optional_list: a list of lists `tf.experimental.Optional`. The values from each compute device grouped by the input device. produce_dummy: a bool. Whether to produce dummy tensors when the optional doesn't have a value. Returns: A flatten list of Tensors. """ value_list = [] for i, worker in enumerate(input_workers.worker_devices): with ops.device(worker): devices = input_workers.compute_devices_for_worker(i) for j, device in enumerate(devices): with ops.device(device): if produce_dummy: # pylint: disable=cell-var-from-loop value_list.append( tf_cond.cond( optional_list[i][j].has_value(), lambda: optional_list[i][j].get_value(), # pylint: disable=unnecessary-lambda lambda: _dummy_tensor_fn(optional_list[i][j].element_spec), strict=True, )) # pylint: enable=cell-var-from-loop else: value_list.append(optional_list[i][j].get_value()) return value_list
DistributedDatasetsFromFunction
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/sparse_batch_test.py
{ "start": 4314, "end": 5050 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def _build_dataset(self, components): return dataset_ops.Dataset.from_tensor_slices(components).map( lambda x: array_ops.fill([x], x)).sparse_batch(4, [12]) @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations())) def test(self, verify_fn): components = np.random.randint(5, size=(40,)).astype(np.int32) num_outputs = len(components) // 4 verify_fn(self, lambda: self._build_dataset(components), num_outputs) if __name__ == "__main__": test.main()
DenseToSparseBatchCheckpointTest
python
astropy__astropy
astropy/utils/decorators.py
{ "start": 32311, "end": 35117 }
class ____(property): """ Works similarly to property(), but computes the value only once. This essentially memorizes the value of the property by storing the result of its computation in the ``__dict__`` of the object instance. This is useful for computing the value of some property that should otherwise be invariant. For example:: >>> class LazyTest: ... @lazyproperty ... def complicated_property(self): ... print('Computing the value for complicated_property...') ... return 42 ... >>> lt = LazyTest() >>> lt.complicated_property Computing the value for complicated_property... 42 >>> lt.complicated_property 42 As the example shows, the second time ``complicated_property`` is accessed, the ``print`` statement is not executed. Only the return value from the first access off ``complicated_property`` is returned. By default, a setter and deleter are used which simply overwrite and delete, respectively, the value stored in ``__dict__``. Any user-specified setter or deleter is executed before executing these default actions. The one exception is that the default setter is not run if the user setter already sets the new value in ``__dict__`` and returns that value and the returned value is not ``None``. """ def __init__(self, fget, fset=None, fdel=None, doc=None): super().__init__(fget, fset, fdel, doc) self._key = self.fget.__name__ self._lock = threading.RLock() def __get__(self, obj, owner=None): try: obj_dict = obj.__dict__ val = obj_dict.get(self._key, _NotFound) if val is _NotFound: with self._lock: # Check if another thread beat us to it. val = obj_dict.get(self._key, _NotFound) if val is _NotFound: val = self.fget(obj) obj_dict[self._key] = val return val except AttributeError: if obj is None: return self raise def __set__(self, obj, val): obj_dict = obj.__dict__ if self.fset: ret = self.fset(obj, val) if ret is not None and obj_dict.get(self._key) is ret: # By returning the value set the setter signals that it # took over setting the value in obj.__dict__; this # mechanism allows it to override the input value return obj_dict[self._key] = val def __delete__(self, obj): if self.fdel: self.fdel(obj) obj.__dict__.pop(self._key, None) # Delete if present
lazyproperty
python
spack__spack
lib/spack/spack/modules/tcl.py
{ "start": 1829, "end": 2100 }
class ____(BaseFileLayout): """File layout for tcl module files.""" @property def modulerc(self): """Returns the modulerc file associated with current module file""" return os.path.join(os.path.dirname(self.filename), ".modulerc")
TclFileLayout
python
explosion__spaCy
spacy/schemas.py
{ "start": 19978, "end": 20055 }
class ____(BaseModel): name: str size_factor: int
RecommendationTrfItem
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_comment07.py
{ "start": 315, "end": 1115 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("comment07.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with comments.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.write_comment("A1", "Some text") worksheet.write_comment("A2", "Some text") worksheet.write_comment("A3", "Some text") worksheet.write_comment("A4", "Some text") worksheet.write_comment("A5", "Some text") worksheet.show_comments() worksheet.set_comments_author("John") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
coleifer__peewee
tests/model_sql.py
{ "start": 40210, "end": 40270 }
class ____(CompoundTestModel): alpha = IntegerField()
Alpha
python
google__jax
jax/_src/stages.py
{ "start": 11683, "end": 11934 }
class ____: _aval: core.AbstractValue donated: bool @property def shape(self): return self._aval.shape # pytype: disable=attribute-error @property def dtype(self): return self._aval.dtype # pytype: disable=attribute-error
ArgInfo
python
nedbat__coveragepy
tests/test_arcs.py
{ "start": 63300, "end": 63733 }
class ____(CoverageTest): """Tests using type annotations.""" def test_annotations(self) -> None: self.check_coverage( """\ def f(x:str, y:int) -> str: a:int = 2 return f"{x}, {y}, {a}, 3" print(f("x", 4)) """, branchz="", branchz_missing="", ) assert self.stdout() == "x, 4, 2, 3\n"
AnnotationTest
python
getsentry__sentry
src/sentry/migrations/0966_groupopenperiod_data_pending_inc_detector_id_index.py
{ "start": 155, "end": 1534 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = True dependencies = [ ("sentry", "0965_gzippeddict_big_tables"), ] operations = [ migrations.AddIndex( model_name="groupopenperiod", index=models.Index( models.F("data__pending_incident_detector_id"), name="data__pend_inc_detector_id_idx", ), ), ]
Migration
python
fastai__fastai
fastai/callback/core.py
{ "start": 2378, "end": 4083 }
class ____(Stateful,GetAttr): "Basic class handling tweaks of the training loop by changing a `Learner` in various events" order,_default,learn,run,run_train,run_valid = 0,'learn',None,True,True,True _methods = _events def __init__(self, **kwargs): assert not kwargs, f'Passed unknown events: {kwargs}' def __repr__(self): return type(self).__name__ def __call__(self, event_name): "Call `self.{event_name}` if it's defined" _run = (event_name not in _inner_loop or (self.run_train and getattr(self, 'training', True)) or (self.run_valid and not getattr(self, 'training', False))) res = None if self.run and _run: try: res = getcallable(self, event_name)() except (CancelBatchException, CancelBackwardException, CancelEpochException, CancelFitException, CancelStepException, CancelTrainException, CancelValidException): raise except Exception as e: raise modify_exception(e, f'Exception occured in `{self.__class__.__name__}` when calling event `{event_name}`:\n\t{e.args[0]}', replace=True) if event_name=='after_fit': self.run=True #Reset self.run to True at each end of fit return res def __setattr__(self, name, value): "Set an attribute for a `Callback`" if hasattr(self.learn,name): warn(f"You are shadowing an attribute ({name}) that exists in the learner. Use `self.learn.{name}` to avoid this") super().__setattr__(name, value) @property def name(self): "Name of the `Callback`, camel-cased and with '*Callback*' removed" return class2attr(self, 'Callback') # %% ../../nbs/13_callback.core.ipynb 34
Callback
python
huggingface__transformers
src/transformers/models/glm4v/modular_glm4v.py
{ "start": 71013, "end": 80108 }
class ____(Qwen2VLProcessor): r""" Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor. [`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information. Args: image_processor ([`Glm4vProcessor`], *optional*): The image processor is a required input. tokenizer ([`PreTrainedTokenizerFast`], *optional*): The tokenizer is a required input. video_processor ([`Glm4vVideoProcessor`], *optional*): The video processor is a required input. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string. """ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs): super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template) self.image_token = "<|image|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token self.video_token = "<|video|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token def __call__( self, images: Optional[ImageInput] = None, text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None, videos: Optional[VideoInput] = None, **kwargs: Unpack[Glm4vProcessorKwargs], ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode the text. Args: images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`. - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`. - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`. """ output_kwargs = self._merge_kwargs( Glm4vProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) if images is not None: image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"]) image_grid_thw = image_inputs["image_grid_thw"] else: image_inputs = {} image_grid_thw = None if videos is not None: videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"]) # If user has not requested video metadata, pop it if not kwargs.get("return_metadata"): video_metadata = videos_inputs.pop("video_metadata") else: video_metadata = videos_inputs["video_metadata"] video_grid_thw = videos_inputs["video_grid_thw"] else: videos_inputs = {} video_grid_thw = None if not isinstance(text, list): text = [text] text = text.copy() # below lines change text in-place if image_grid_thw is not None: merge_length = self.image_processor.merge_size**2 index = 0 for i in range(len(text)): while self.image_token in text[i]: num_image_tokens = image_grid_thw[index].prod() // merge_length text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1) index += 1 text[i] = text[i].replace("<|placeholder|>", self.image_token) if video_grid_thw is not None: merge_length = self.video_processor.merge_size**2 video_index = 0 for i in range(len(text)): while self.video_token in text[i]: num_frames = video_grid_thw[video_index][0] video_structure = "" metadata = video_metadata[video_index] if metadata.fps is None: logger.warning_once( "SmolVLM requires frame timestamps to construct prompts, but the `fps` of the input video could not be inferred. " "Probably `video_metadata` was missing from inputs and you passed pre-sampled frames. " "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results." ) metadata.fps = 24 if metadata.fps is None else metadata.fps timestamps = metadata.timestamps[::2] # mrope unique_timestamps = [] for idx in range(0, len(timestamps)): unique_timestamps.append(timestamps[idx]) selected_timestamps = unique_timestamps[:num_frames] while len(selected_timestamps) < num_frames: selected_timestamps.append(selected_timestamps[-1] if selected_timestamps else 0) for frame_idx in range(num_frames): timestamp_sec = selected_timestamps[frame_idx] frame_structure = self.replace_frame_token_id(timestamp_sec) video_structure += frame_structure text[i] = text[i].replace(self.video_token, video_structure, 1) num_image_tokens = ( video_grid_thw[video_index].prod() // merge_length // video_grid_thw[video_index][0] ) for frame_idx in range(num_frames): if self.image_token in text[i]: text[i] = text[i].replace(self.image_token, "<|placeholder|>" * num_image_tokens, 1) video_index += 1 text[i] = text[i].replace("<|placeholder|>", self.image_token) return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None) return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", False) text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"]) self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"]) if return_mm_token_type_ids: array_ids = np.array(text_inputs["input_ids"]) mm_token_type_ids = np.zeros_like(text_inputs["input_ids"]) mm_token_type_ids[array_ids == self.image_token_id] = 1 text_inputs["mm_token_type_ids"] = mm_token_type_ids.tolist() return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors) def replace_frame_token_id(self, timestamp_sec): return f"<|begin_of_image|>{self.image_token}<|end_of_image|>{int(timestamp_sec)}" __all__ = [ "Glm4vConfig", "Glm4vTextConfig", "Glm4vVisionConfig", "Glm4vForConditionalGeneration", "Glm4vModel", "Glm4vPreTrainedModel", "Glm4vProcessor", "Glm4vTextModel", "Glm4vVisionModel", ]
Glm4vProcessor
python
pytorch__pytorch
torch/fx/experimental/migrate_gradual_types/constraint.py
{ "start": 4150, "end": 4979 }
class ____(Constraint): """ Greatest Upper bound for dimensions """ def __init__(self, res, rhs1, rhs2): """ :param res: Dimension variable to store the result :param rhs1: dimension variable 1 :param rhs2: dimension variable 2 """ assert is_dim(res) assert is_dim(rhs1) assert is_dim(rhs2) self.res = res self.rhs1 = rhs1 self.rhs2 = rhs2 def __repr__(self): return f"{self.res} = {self.rhs1}\u2294{self.rhs2}" def __eq__(self, other): if isinstance(other, DGreatestUpperBound): return ( self.res == other.res and self.rhs1 == other.rhs1 and self.rhs2 == other.rhs2 ) else: return False
DGreatestUpperBound
python
getsentry__sentry
tests/sentry/releases/endpoints/test_organization_release_file_details.py
{ "start": 4346, "end": 5580 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) releasefile = ReleaseFile.objects.create( organization_id=project.organization_id, release_id=release.id, file=File.objects.create(name="application.js", type="release.file"), name="http://example.com/application.js", ) url = reverse( "sentry-api-0-organization-release-file-details", kwargs={ "organization_id_or_slug": project.organization.slug, "version": release.version, "file_id": releasefile.id, }, ) response = self.client.put(url, {"name": "foobar"}) assert response.status_code == 200, response.content assert response.data["id"] == str(releasefile.id) releasefile = ReleaseFile.objects.get(id=releasefile.id) assert releasefile.name == "foobar" assert releasefile.ident == ReleaseFile.get_ident("foobar")
ReleaseFileUpdateTest
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 4567, "end": 4652 }
class ____(PydanticTypeError): msg_template = 'value is not a valid dict'
DictError
python
pytorch__pytorch
test/distributed/_composable/test_composability/test_2d_composability.py
{ "start": 3067, "end": 16111 }
class ____(FSDPTest): global c10d_ops global funcol c10d_ops = torch.ops.c10d funcol = torch.ops.c10d_functional @property def world_size(self) -> int: return min(4, torch.accelerator.device_count()) def init_global_mesh(self) -> DeviceMesh: # Prefer to test with >=4 GPUs, but for 2 GPUs, use 2-way TP dp_size = 2 if self.world_size > 2 else 1 return init_device_mesh( device_type, (dp_size, self.world_size // dp_size), mesh_dim_names=("dp", "tp"), ) @skip_if_rocm_arch_multiprocess(MI200_ARCH) @skip_if_lt_x_gpu(2) def test_train_parity_2d_mlp(self): global_mesh = self.init_global_mesh() self.run_subtests( { "reshard_after_forward": [False, True], "use_activation_checkpointing": [False, True], "mlp_dim": [3, 16, 17], }, functools.partial(self._test_train_parity_2d_mlp, global_mesh), ) def _test_train_parity_2d_mlp( self, global_mesh: DeviceMesh, reshard_after_forward: bool, use_activation_checkpointing: bool, mlp_dim: int, ): dp_mesh, tp_mesh = global_mesh["dp"], global_mesh["tp"] dp_pg = dp_mesh.get_group() # used for `replicate()` torch.manual_seed(42) model = MLPStack(mlp_dim) ref_model = copy.deepcopy(model).to(device_type) replicate(ref_model, device_ids=[self.rank], process_group=dp_pg) ref_optim = torch.optim.Adam(ref_model.parameters(), lr=1e-2, foreach=False) model.parallelize( tp_mesh, dp_mesh, use_activation_checkpointing, reshard_after_forward=reshard_after_forward, ) optim = torch.optim.Adam(model.parameters(), lr=1e-2, foreach=False) torch.manual_seed(42 + dp_pg.rank() + 1) for iter_idx in range(10): inp = torch.randn((8, mlp_dim), device=device_type) losses: list[torch.Tensor] = [] for _model, _optim in ((ref_model, ref_optim), (model, optim)): _optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) losses.append(_model(inp).sum()) losses[-1].backward() _optim.step() self.assertEqual(losses[0], losses[1]) @skip_if_lt_x_gpu(2) @xfailIf(TEST_XPU) # https://github.com/intel/torch-xpu-ops/issues/1881 def test_train_parity_2d_transformer(self): self.run_subtests( {"use_shard_placement_fn": [False, True]}, self._test_train_parity_2d_transformer, ) def _test_train_parity_2d_transformer(self, use_shard_placement_fn: bool): torch.manual_seed(42) model_args = ModelArgs(n_layers=3, dropout_p=0.0) model = Transformer(model_args) ref_model = copy.deepcopy(model).to(device_type) ref_optim = torch.optim.AdamW(ref_model.parameters(), lr=1e-2) dp_size, tp_size = self.world_size // 2, 2 global_mesh = init_device_mesh( device_type, (dp_size, tp_size), mesh_dim_names=("dp", "tp") ) model = Transformer.parallelize(model, global_mesh["tp"], use_seq_parallel=True) def _shard_placement_fn(param: nn.Parameter) -> Optional[Shard]: if isinstance(param, DTensor): for placement in param.placements: if isinstance(placement, Shard): shard_dim = param.ndim - 1 - placement.dim assert shard_dim >= 0, f"{param.shape}" return Shard(shard_dim) return Shard(0) shard_placement_fn = _shard_placement_fn if use_shard_placement_fn else None for layer in model.layers: fully_shard( layer, mesh=global_mesh["dp"], shard_placement_fn=shard_placement_fn ) fully_shard( model, mesh=global_mesh["dp"], shard_placement_fn=shard_placement_fn ) optim = torch.optim.AdamW(model.parameters(), lr=1e-2) for param, ref_param in zip(model.parameters(), ref_model.parameters()): full_param = param.full_tensor() self.assertEqual(full_param, ref_param) torch.manual_seed(42 + global_mesh.get_local_rank("dp")) inp = torch.randint(0, model_args.vocab_size, (2, 16), device=device_type) for _ in range(5): ref_loss = ref_model(inp).sum() loss = model(inp).sum() self.assertEqual(ref_loss, loss) ref_loss.backward() loss.backward() for param in ref_model.parameters(): if param.grad is not None: dist.all_reduce( param.grad, group=global_mesh.get_group("dp"), op=dist.ReduceOp.AVG, ) # Specially check the TP placement for `pos_embeddings.weight` and # its which since the grad naturally has replicate placement, # requiring FSDP to redistribute it to shard placement before FSDP # runs its reduce-scatter self.assertIsInstance(model.pos_embeddings.weight.placements[1], Shard) self.assertIsInstance(model.pos_embeddings.weight.grad.placements[1], Shard) for ref_param, param in zip(ref_model.parameters(), model.parameters()): full_grad = param.grad.full_tensor() self.assertEqual(ref_param.grad, full_grad) ref_optim.step() optim.step() ref_optim.zero_grad() optim.zero_grad() for param, ref_param in zip(model.parameters(), ref_model.parameters()): full_param = param.full_tensor() self.assertEqual(full_param, ref_param) @skip_if_lt_x_gpu(2) @xfailIf(TEST_XPU) # https://github.com/pytorch/pytorch/issues/156782 def test_tp_with_fsdp_offloading(self): global_mesh = init_device_mesh( device_type, (1, self.world_size), mesh_dim_names=("dp", "tp") ) dp_mesh, tp_mesh = global_mesh["dp"], global_mesh["tp"] torch.manual_seed(42) mlp_dim = 16 model = MLPStack(mlp_dim) ref_model = copy.deepcopy(model).to(device_type) ref_optim = torch.optim.Adam(ref_model.parameters(), lr=1e-2, foreach=False) # Parallelize with N-way TP and 1-way FSDP model.parallelize( tp_mesh, dp_mesh, use_activation_checkpointing=False, reshard_after_forward=True, offload_policy=CPUOffloadPolicy(), ) for param in model.parameters(): self.assertEqual(param.device.type, "cpu") num_mlps = sum(isinstance(module, MLP) for module in model.modules()) optim = torch.optim.Adam(model.parameters(), lr=1e-2, foreach=False) # NOTE: We still see the FSDP all-gather/reduce-scatter c10d ops # called, but they will just be no-ops without issuing any kernels. # We prefer to keep the no-op check at the c10d level, not in FSDP. inp = torch.randn((4, mlp_dim), device=device_type) # same on all ranks for _ in range(10): ref_optim.zero_grad() optim.zero_grad() with CommDebugMode() as fwd_comm_mode: loss = model(inp).sum() fwd_comm_counts = fwd_comm_mode.get_comm_counts() self.assertEqual(len(fwd_comm_counts), 1) self.assertEqual(fwd_comm_counts[funcol.all_reduce], num_mlps) self.assertEqual(fwd_comm_counts[c10d_ops._allgather_base_], 0) ref_loss = ref_model(inp).sum() self.assertEqual(loss, ref_loss) with CommDebugMode() as bwd_comm_mode: loss.backward() bwd_comm_counts = bwd_comm_mode.get_comm_counts() self.assertEqual(len(bwd_comm_counts), 1) # First MLP's input gradient does not need to be all-reduced self.assertEqual(bwd_comm_counts[funcol.all_reduce], num_mlps - 1) self.assertEqual(bwd_comm_counts[c10d_ops._allgather_base_], 0) self.assertEqual(bwd_comm_counts[c10d_ops._reduce_scatter_base_], 0) ref_loss.backward() optim.step() ref_optim.step() @skip_if_lt_x_gpu(2) @xfailIf(TEST_XPU) # https://github.com/intel/torch-xpu-ops/issues/1881 @with_temp_dir def test_train_parity_2d_transformer_checkpoint_resume(self): """ Tests train parity of a 2D transformer without checkpointing against a 2D transformer with a checkpoint save/load. """ self.run_subtests( { "use_seq_parallel": [False, True], # If reusing, then load into the same model/optimizer instance # else construct new ones (requiring eager optim state init) "reuse_model_optim": [False, True], "optimizer_class": [torch.optim.Adam, torch.optim.AdamW], # TODO: need to update `parallelize` before including foreach=True for testing "foreach": [False], }, self._test_train_parity_2d_transformer_checkpoint_resume, ) def _test_train_parity_2d_transformer_checkpoint_resume( self, use_seq_parallel: bool, reuse_model_optim: bool, optimizer_class: type[torch.optim.Optimizer], foreach: bool, ): def train_step( _model: nn.Module, _optim: torch.optim.Optimizer, _inp: torch.Tensor ) -> torch.Tensor: loss = _model(_inp).sum() loss.backward() _optim.step() _optim.zero_grad() return loss def parallelize(_model: Transformer, mesh: DeviceMesh, use_seq_parallel: bool): _model = Transformer.parallelize(_model, mesh["tp"], use_seq_parallel) for layer in _model.layers: fully_shard(layer, mesh=mesh["dp"]) fully_shard(_model, mesh=mesh["dp"]) return _model global_mesh = self.init_global_mesh() # Baseline: run two iterations without checkpointing seed = 42 torch.manual_seed(seed) model_args = ModelArgs(dropout_p=0.0) model_no_cp = parallelize( Transformer(model_args), global_mesh, use_seq_parallel ) optim_no_cp = optimizer_class( model_no_cp.parameters(), lr=1e-2, foreach=foreach ) torch.manual_seed(42 + global_mesh["dp"].get_local_rank() + 1) inp = torch.randint(0, model_args.vocab_size, (3, 16), device=device_type) loss_no_cp1 = train_step(model_no_cp, optim_no_cp, inp) loss_no_cp2 = train_step(model_no_cp, optim_no_cp, inp) # Test: run one iteration, save checkpoint, zero states or init new # model/optimizer, load checkpoint, and run another iteration torch.manual_seed(seed) model_cp = parallelize(Transformer(model_args), global_mesh, use_seq_parallel) optim_cp = optimizer_class(model_cp.parameters(), lr=1e-2, foreach=foreach) loss_cp1 = train_step(model_cp, optim_cp, inp) self.assertEqual(loss_no_cp1, loss_cp1) sharded_sd = { "model": get_model_state_dict(model_cp), # Use `get_optimizer_state_dict` to handle eager optim state init # when constructing a new optimizer instance "optim": get_optimizer_state_dict(model_cp, optim_cp), } dcp.save( state_dict=sharded_sd, storage_writer=dcp.FileSystemWriter(self.temp_dir), ) if reuse_model_optim: with torch.no_grad(): for param in model_cp.parameters(): param.zero_() optim_sd = optim_cp.state_dict() for param_states in optim_sd["state"].values(): for state_value in param_states.values(): if torch.is_tensor(state_value): state_value.zero_() else: torch.manual_seed(seed + 1) # different seed model_cp = parallelize( Transformer(model_args), global_mesh, use_seq_parallel ) optim_cp = optimizer_class(model_cp.parameters(), lr=1e-2, foreach=foreach) self.assertNotEqual(loss_no_cp2, train_step(model_cp, optim_cp, inp)) sharded_sd = { "model": get_model_state_dict(model_cp), "optim": get_optimizer_state_dict(model_cp, optim_cp), } dcp.load( state_dict=sharded_sd, storage_reader=dcp.FileSystemReader(self.temp_dir), ) self.assertGreater(len(optim_cp.state_dict()["state"]), 0) loss_cp2 = train_step(model_cp, optim_cp, inp) self.assertEqual(loss_no_cp2, loss_cp2)
TestFullyShard2DTraining
python
joke2k__faker
tests/providers/test_isbn.py
{ "start": 1259, "end": 2488 }
class ____: prov = ISBNProvider(None) def test_reg_pub_separation(self): r1 = ("0000000", "0000001", 1) r2 = ("0000002", "0000003", 2) assert self.prov._registrant_publication("00000000", [r1, r2]) == ( "0", "0000000", ) assert self.prov._registrant_publication("00000010", [r1, r2]) == ( "0", "0000010", ) assert self.prov._registrant_publication("00000019", [r1, r2]) == ( "0", "0000019", ) assert self.prov._registrant_publication("00000020", [r1, r2]) == ( "00", "000020", ) assert self.prov._registrant_publication("00000030", [r1, r2]) == ( "00", "000030", ) assert self.prov._registrant_publication("00000031", [r1, r2]) == ( "00", "000031", ) assert self.prov._registrant_publication("00000039", [r1, r2]) == ( "00", "000039", ) def test_rule_not_found(self): with pytest.raises(Exception): r = ("0000000", "0000001", 1) self.prov._registrant_publication("0000002", [r])
TestProvider
python
django-extensions__django-extensions
tests/management/commands/test_sync_s3.py
{ "start": 333, "end": 759 }
class ____: def setUp(self): self.m_boto = Mock() self.boto_patch = patch( "django_extensions.management.commands.sync_s3.boto", create=True, boto=self.m_boto, ) self.boto_patch.start() def tearDown(self): super().tearDown() self.boto_patch.stop() @patch("django_extensions.management.commands.sync_s3.HAS_BOTO", True)
SyncS3TestsMixin
python
celery__celery
celery/app/control.py
{ "start": 15646, "end": 29699 }
class ____: """Worker remote control client.""" Mailbox = Mailbox def __init__(self, app=None): self.app = app if (app.conf.control_queue_durable and app.conf.control_queue_exclusive): raise ImproperlyConfigured( "control_queue_durable and control_queue_exclusive cannot both be True " "(exclusive queues are automatically deleted and cannot be durable).", ) self.mailbox = self.Mailbox( app.conf.control_exchange, type='fanout', accept=app.conf.accept_content, serializer=app.conf.task_serializer, producer_pool=lazy(lambda: self.app.amqp.producer_pool), queue_ttl=app.conf.control_queue_ttl, reply_queue_ttl=app.conf.control_queue_ttl, queue_expires=app.conf.control_queue_expires, queue_exclusive=app.conf.control_queue_exclusive, queue_durable=app.conf.control_queue_durable, reply_queue_expires=app.conf.control_queue_expires, ) register_after_fork(self, _after_fork_cleanup_control) def _after_fork(self): del self.mailbox.producer_pool @cached_property def inspect(self): """Create new :class:`Inspect` instance.""" return self.app.subclass_with_self(Inspect, reverse='control.inspect') def purge(self, connection=None): """Discard all waiting tasks. This will ignore all tasks waiting for execution, and they will be deleted from the messaging server. Arguments: connection (kombu.Connection): Optional specific connection instance to use. If not provided a connection will be acquired from the connection pool. Returns: int: the number of tasks discarded. """ with self.app.connection_or_acquire(connection) as conn: return self.app.amqp.TaskConsumer(conn).purge() discard_all = purge def election(self, id, topic, action=None, connection=None): self.broadcast( 'election', connection=connection, destination=None, arguments={ 'id': id, 'topic': topic, 'action': action, }, ) def revoke(self, task_id, destination=None, terminate=False, signal=TERM_SIGNAME, **kwargs): """Tell all (or specific) workers to revoke a task by id (or list of ids). If a task is revoked, the workers will ignore the task and not execute it after all. Arguments: task_id (Union(str, list)): Id of the task to revoke (or list of ids). terminate (bool): Also terminate the process currently working on the task (if any). signal (str): Name of signal to send to process if terminate. Default is TERM. See Also: :meth:`broadcast` for supported keyword arguments. """ return self.broadcast('revoke', destination=destination, arguments={ 'task_id': task_id, 'terminate': terminate, 'signal': signal, }, **kwargs) def revoke_by_stamped_headers(self, headers, destination=None, terminate=False, signal=TERM_SIGNAME, **kwargs): """ Tell all (or specific) workers to revoke a task by headers. If a task is revoked, the workers will ignore the task and not execute it after all. Arguments: headers (dict[str, Union(str, list)]): Headers to match when revoking tasks. terminate (bool): Also terminate the process currently working on the task (if any). signal (str): Name of signal to send to process if terminate. Default is TERM. See Also: :meth:`broadcast` for supported keyword arguments. """ result = self.broadcast('revoke_by_stamped_headers', destination=destination, arguments={ 'headers': headers, 'terminate': terminate, 'signal': signal, }, **kwargs) task_ids = set() if result: for host in result: for response in host.values(): if isinstance(response['ok'], set): task_ids.update(response['ok']) if task_ids: return self.revoke(list(task_ids), destination=destination, terminate=terminate, signal=signal, **kwargs) else: return result def terminate(self, task_id, destination=None, signal=TERM_SIGNAME, **kwargs): """Tell all (or specific) workers to terminate a task by id (or list of ids). See Also: This is just a shortcut to :meth:`revoke` with the terminate argument enabled. """ return self.revoke( task_id, destination=destination, terminate=True, signal=signal, **kwargs) def ping(self, destination=None, timeout=1.0, **kwargs): """Ping all (or specific) workers. >>> app.control.ping() [{'celery@node1': {'ok': 'pong'}}, {'celery@node2': {'ok': 'pong'}}] >>> app.control.ping(destination=['celery@node2']) [{'celery@node2': {'ok': 'pong'}}] Returns: List[Dict]: List of ``{HOSTNAME: {'ok': 'pong'}}`` dictionaries. See Also: :meth:`broadcast` for supported keyword arguments. """ return self.broadcast( 'ping', reply=True, arguments={}, destination=destination, timeout=timeout, **kwargs) def rate_limit(self, task_name, rate_limit, destination=None, **kwargs): """Tell workers to set a new rate limit for task by type. Arguments: task_name (str): Name of task to change rate limit for. rate_limit (int, str): The rate limit as tasks per second, or a rate limit string (`'100/m'`, etc. see :attr:`celery.app.task.Task.rate_limit` for more information). See Also: :meth:`broadcast` for supported keyword arguments. """ return self.broadcast( 'rate_limit', destination=destination, arguments={ 'task_name': task_name, 'rate_limit': rate_limit, }, **kwargs) def add_consumer(self, queue, exchange=None, exchange_type='direct', routing_key=None, options=None, destination=None, **kwargs): """Tell all (or specific) workers to start consuming from a new queue. Only the queue name is required as if only the queue is specified then the exchange/routing key will be set to the same name ( like automatic queues do). Note: This command does not respect the default queue/exchange options in the configuration. Arguments: queue (str): Name of queue to start consuming from. exchange (str): Optional name of exchange. exchange_type (str): Type of exchange (defaults to 'direct') command to, when empty broadcast to all workers. routing_key (str): Optional routing key. options (Dict): Additional options as supported by :meth:`kombu.entity.Queue.from_dict`. See Also: :meth:`broadcast` for supported keyword arguments. """ return self.broadcast( 'add_consumer', destination=destination, arguments=dict({ 'queue': queue, 'exchange': exchange, 'exchange_type': exchange_type, 'routing_key': routing_key, }, **options or {}), **kwargs ) def cancel_consumer(self, queue, destination=None, **kwargs): """Tell all (or specific) workers to stop consuming from ``queue``. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'cancel_consumer', destination=destination, arguments={'queue': queue}, **kwargs) def time_limit(self, task_name, soft=None, hard=None, destination=None, **kwargs): """Tell workers to set time limits for a task by type. Arguments: task_name (str): Name of task to change time limits for. soft (float): New soft time limit (in seconds). hard (float): New hard time limit (in seconds). **kwargs (Any): arguments passed on to :meth:`broadcast`. """ return self.broadcast( 'time_limit', arguments={ 'task_name': task_name, 'hard': hard, 'soft': soft, }, destination=destination, **kwargs) def enable_events(self, destination=None, **kwargs): """Tell all (or specific) workers to enable events. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'enable_events', arguments={}, destination=destination, **kwargs) def disable_events(self, destination=None, **kwargs): """Tell all (or specific) workers to disable events. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'disable_events', arguments={}, destination=destination, **kwargs) def pool_grow(self, n=1, destination=None, **kwargs): """Tell all (or specific) workers to grow the pool by ``n``. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'pool_grow', arguments={'n': n}, destination=destination, **kwargs) def pool_shrink(self, n=1, destination=None, **kwargs): """Tell all (or specific) workers to shrink the pool by ``n``. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'pool_shrink', arguments={'n': n}, destination=destination, **kwargs) def autoscale(self, max, min, destination=None, **kwargs): """Change worker(s) autoscale setting. See Also: Supports the same arguments as :meth:`broadcast`. """ return self.broadcast( 'autoscale', arguments={'max': max, 'min': min}, destination=destination, **kwargs) def shutdown(self, destination=None, **kwargs): """Shutdown worker(s). See Also: Supports the same arguments as :meth:`broadcast` """ return self.broadcast( 'shutdown', arguments={}, destination=destination, **kwargs) def pool_restart(self, modules=None, reload=False, reloader=None, destination=None, **kwargs): """Restart the execution pools of all or specific workers. Keyword Arguments: modules (Sequence[str]): List of modules to reload. reload (bool): Flag to enable module reloading. Default is False. reloader (Any): Function to reload a module. destination (Sequence[str]): List of worker names to send this command to. See Also: Supports the same arguments as :meth:`broadcast` """ return self.broadcast( 'pool_restart', arguments={ 'modules': modules, 'reload': reload, 'reloader': reloader, }, destination=destination, **kwargs) def heartbeat(self, destination=None, **kwargs): """Tell worker(s) to send a heartbeat immediately. See Also: Supports the same arguments as :meth:`broadcast` """ return self.broadcast( 'heartbeat', arguments={}, destination=destination, **kwargs) def broadcast(self, command, arguments=None, destination=None, connection=None, reply=False, timeout=1.0, limit=None, callback=None, channel=None, pattern=None, matcher=None, **extra_kwargs): """Broadcast a control command to the celery workers. Arguments: command (str): Name of command to send. arguments (Dict): Keyword arguments for the command. destination (List): If set, a list of the hosts to send the command to, when empty broadcast to all workers. connection (kombu.Connection): Custom broker connection to use, if not set, a connection will be acquired from the pool. reply (bool): Wait for and return the reply. timeout (float): Timeout in seconds to wait for the reply. limit (int): Limit number of replies. callback (Callable): Callback called immediately for each reply received. pattern (str): Custom pattern string to match matcher (Callable): Custom matcher to run the pattern to match """ with self.app.connection_or_acquire(connection) as conn: arguments = dict(arguments or {}, **extra_kwargs) if pattern and matcher: # tests pass easier without requiring pattern/matcher to # always be sent in return self.mailbox(conn)._broadcast( command, arguments, destination, reply, timeout, limit, callback, channel=channel, pattern=pattern, matcher=matcher, ) else: return self.mailbox(conn)._broadcast( command, arguments, destination, reply, timeout, limit, callback, channel=channel, )
Control
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 89110, "end": 89241 }
class ____(CIntType): to_py_function = "__Pyx_PyLong_FromSize_t" def sign_and_name(self): return "size_t"
CSizeTType
python
google__jax
jax/_src/interpreters/partial_eval.py
{ "start": 79058, "end": 79398 }
class ____(NamedTuple): # A pair of a canonicalized constant and its original form. # It is important that we keep the original value alive because we use id(c) # as a key in various dictionaries. If the original value were deleted we # may confuse constants if the same object ID is reused. canonical: Any original: Any
Constants
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/cache_key.py
{ "start": 14710, "end": 14936 }
class ____(HasCacheKey, HasMemoized): __slots__ = () @HasMemoized.memoized_instancemethod def _generate_cache_key(self) -> Optional[CacheKey]: return HasCacheKey._generate_cache_key(self)
MemoizedHasCacheKey
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 62616, "end": 63413 }
class ____(BiffRecord): """ This record contains information about the layout of outline symbols. Record GUTS, BIFF3-BIFF8: Offset Size Contents 0 2 Width of the area to display row outlines (left of the sheet), in pixel 2 2 Height of the area to display column outlines (above the sheet), in pixel 4 2 Number of visible row outline levels (used row levels + 1; or 0, if not used) 6 2 Number of visible column outline levels (used column levels + 1; or 0, if not used) """ _REC_ID = 0x0080 def __init__(self, row_gut_width, col_gut_height, row_visible_levels, col_visible_levels): self._rec_data = pack('<4H', row_gut_width, col_gut_height, row_visible_levels, col_visible_levels)
GutsRecord
python
openai__openai-python
src/openai/types/shared_params/custom_tool_input_format.py
{ "start": 402, "end": 769 }
class ____(TypedDict, total=False): definition: Required[str] """The grammar definition.""" syntax: Required[Literal["lark", "regex"]] """The syntax of the grammar definition. One of `lark` or `regex`.""" type: Required[Literal["grammar"]] """Grammar format. Always `grammar`.""" CustomToolInputFormat: TypeAlias = Union[Text, Grammar]
Grammar
python
huggingface__transformers
src/transformers/models/falcon_mamba/modular_falcon_mamba.py
{ "start": 1686, "end": 8727 }
class ____(MambaConfig): """ This is the configuration class to store the configuration of a [`FalconMambaModel`]. It is used to instantiate a FALCON_MAMBA model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the FALCON_MAMBA [tiiuae/falcon-mamba-7b](https://huggingface.co/tiiuae/falcon-mamba-7b) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50280): Vocabulary size of the FALCON_MAMBA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`FalconMambaModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the embeddings and hidden states. state_size (`int`, *optional*, defaults to 16): shape of the state space latents. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the model. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05): The epsilon to use in the layer normalization layers. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. bos_token_id (`int`, *optional*, defaults to 0): The id of the beginning of sentence token in the vocabulary. eos_token_id (`int`, *optional*, defaults to 0): The id of the end of sentence token in the vocabulary. expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size. conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel. use_bias (`bool`, *optional*, defaults to `False`): Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block use_conv_bias (`bool`, *optional*, defaults to `True`): Whether or not to use bias in the convolution layer of the mixer block. hidden_act (`str`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. initializer_range (`float`, *optional*, defaults to 0.1): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. residual_in_fp32 (`bool`, *optional*, defaults to `True`): Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`): Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)` time_step_scale (`float`, *optional*, defaults to 1.0): Scale used used to scale `dt_proj.bias`. time_step_min (`float`, *optional*, defaults to 0.001): Minimum `time_step` used to bound `dt_proj.bias`. time_step_max (`float`, *optional*, defaults to 0.1): Maximum `time_step` used to bound `dt_proj.bias`. time_step_init_scheme (`float`, *optional*, defaults to `"random"`): Init scheme used for `dt_proj.weight`. Should be one of `["random","uniform"]` time_step_floor (`float`, *optional*, defaults to 0.0001): Minimum clamping value of the `dt_proj.bias` layer initialization. rescale_prenorm_residual (`bool`, *optional*, defaults to `False`): Whether or not to rescale `out_proj` weights when initializing. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the cache should be used. use_falcon_mambapy (`bool`, *optional*, defaults to `False`): This argument corresponds to `use_mambapy` in MambaConfig. Determines the fallback strategy during training if the CUDA-based official implementation of Mamba is not available. If `True`, the mamba.py implementation is used. If `False`, the naive and slower implementation is used. Consider switching to the naive version if memory is limited. mixer_rms_eps (`float`, *optional*, defaults to 1e-06): The RMS norm epsilon value that is used in the Mixer RMS norm for B, C and dt states. Example: ```python >>> from transformers import FalconMambaConfig, FalconMambaModel >>> # Initializing a FalconMamba configuration >>> configuration = FalconMambaConfig() >>> # Initializing a model (with random weights) from the configuration >>> model = FalconMambaModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" def __init__( self, vocab_size=50280, hidden_size=768, state_size=16, num_hidden_layers=32, layer_norm_epsilon=1e-5, pad_token_id=0, bos_token_id=0, eos_token_id=0, expand=2, conv_kernel=4, use_bias=False, use_conv_bias=True, hidden_act="silu", initializer_range=0.1, residual_in_fp32=True, time_step_rank="auto", time_step_scale=1.0, time_step_min=0.001, time_step_max=0.1, time_step_init_scheme="random", time_step_floor=1e-4, rescale_prenorm_residual=False, use_cache=True, use_falcon_mambapy=False, mixer_rms_eps=1e-6, **kwargs, ): super().__init__( vocab_size=vocab_size, hidden_size=hidden_size, state_size=state_size, num_hidden_layers=num_hidden_layers, layer_norm_epsilon=layer_norm_epsilon, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, expand=expand, conv_kernel=conv_kernel, use_bias=use_bias, use_conv_bias=use_conv_bias, hidden_act=hidden_act, initializer_range=initializer_range, residual_in_fp32=residual_in_fp32, time_step_rank=time_step_rank, time_step_scale=time_step_scale, time_step_min=time_step_min, time_step_max=time_step_max, time_step_init_scheme=time_step_init_scheme, time_step_floor=time_step_floor, rescale_prenorm_residual=rescale_prenorm_residual, use_cache=use_cache, use_falcon_mambapy=use_falcon_mambapy, **kwargs, ) self.mixer_rms_eps = mixer_rms_eps # This is needed since mamba overrides the intermediate_size attribute self.intermediate_size = ( int(expand * self.hidden_size) if kwargs.get("intermediate_size") is None else kwargs.get("intermediate_size") )
FalconMambaConfig
python
allegroai__clearml
clearml/backend_api/services/v2_13/workers.py
{ "start": 23847, "end": 25100 }
class ____(NonStrictDataModel): """ :param id: ID :type id: str :param name: Name :type name: str """ _schema = { "properties": { "id": {"description": "ID", "type": ["string", "null"]}, "name": {"description": "Name", "type": ["string", "null"]}, }, "type": "object", } def __init__(self, id: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) -> None: super(IdNameEntry, self).__init__(**kwargs) self.id = id self.name = name @schema_property("id") def id(self) -> Optional[str]: return self._property_id @id.setter def id(self, value: Optional[str]) -> None: if value is None: self._property_id = None return self.assert_isinstance(value, "id", six.string_types) self._property_id = value @schema_property("name") def name(self) -> Optional[str]: return self._property_name @name.setter def name(self, value: Optional[str]) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value
IdNameEntry
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 3684, "end": 3889 }
class ____(InvalidTransition): def to_event(self) -> tuple[str, dict[str, Any]]: topic, msg = super().to_event() return "transition-counter-max-exceeded", msg
TransitionCounterMaxExceeded
python
cython__cython
Cython/Compiler/UtilNodes.py
{ "start": 3354, "end": 6767 }
class ____(AtomicExprNode): # A reference to the result of an expression. The result_code # must be set externally (usually a temp name). subexprs = [] lhs_of_first_assignment = False def __init__(self, expression=None, pos=None, type=None, may_hold_none=True, is_temp=False): self.expression = expression self.pos = None self.may_hold_none = may_hold_none if expression is not None: self.pos = expression.pos self.type = getattr(expression, "type", None) if pos is not None: self.pos = pos if type is not None: self.type = type if is_temp: self.is_temp = True assert self.pos is not None def clone_node(self): # nothing to do here return self def type_dependencies(self, env): if self.expression: return self.expression.type_dependencies(env) else: return () def update_expression(self, expression): self.expression = expression type = getattr(expression, "type", None) if type: self.type = type def analyse_target_declaration(self, env): pass # OK - we can assign to this def analyse_types(self, env): if self.expression is not None: if not self.expression.type: self.expression = self.expression.analyse_types(env) self.type = self.expression.type return self def infer_type(self, env): if self.type is not None: return self.type if self.expression is not None: if self.expression.type is not None: return self.expression.type return self.expression.infer_type(env) assert False, "cannot infer type of ResultRefNode" def may_be_none(self): if not self.type.is_pyobject: return False return self.may_hold_none def _DISABLED_may_be_none(self): # not sure if this is safe - the expression may not be the # only value that gets assigned if self.expression is not None: return self.expression.may_be_none() if self.type is not None: return self.type.is_pyobject return True # play it safe def is_simple(self): return True def result(self): try: return self.result_code except AttributeError: if self.expression is not None: self.result_code = self.expression.result() return self.result_code def generate_evaluation_code(self, code): pass def generate_result_code(self, code): pass def generate_disposal_code(self, code): pass def generate_assignment_code(self, rhs, code, overloaded_assignment=False): if self.type.is_pyobject: rhs.make_owned_reference(code) if not self.lhs_of_first_assignment: code.put_decref(self.result(), self.ctype()) code.putln('%s = %s;' % ( self.result(), rhs.result() if overloaded_assignment else rhs.result_as(self.ctype()), )) rhs.generate_post_assignment_code(code) rhs.free_temps(code) def allocate_temps(self, env): pass def release_temp(self, env): pass def free_temps(self, code): pass
ResultRefNode
python
django__django
tests/forms_tests/tests/test_i18n.py
{ "start": 289, "end": 4738 }
class ____(SimpleTestCase): def test_lazy_labels(self): class SomeForm(Form): username = CharField(max_length=10, label=gettext_lazy("username")) f = SomeForm() self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>", ) # Translations are done at rendering time, so multi-lingual apps can # define forms. with translation.override("de"): self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">Benutzername:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>", ) with translation.override("pl"): self.assertHTMLEqual( f.as_p(), '<p><label for="id_username">nazwa u\u017cytkownika:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>", ) def test_non_ascii_label(self): class SomeForm(Form): field_1 = CharField(max_length=10, label=gettext_lazy("field_1")) field_2 = CharField( max_length=10, label=gettext_lazy("field_2"), widget=TextInput(attrs={"id": "field_2_id"}), ) f = SomeForm() self.assertHTMLEqual( f["field_1"].label_tag(), '<label for="id_field_1">field_1:</label>' ) self.assertHTMLEqual( f["field_1"].legend_tag(), "<legend>field_1:</legend>", ) self.assertHTMLEqual( f["field_2"].label_tag(), '<label for="field_2_id">field_2:</label>' ) self.assertHTMLEqual( f["field_2"].legend_tag(), "<legend>field_2:</legend>", ) def test_non_ascii_choices(self): class SomeForm(Form): somechoice = ChoiceField( choices=(("\xc5", "En tied\xe4"), ("\xf8", "Mies"), ("\xdf", "Nainen")), widget=RadioSelect(), label="\xc5\xf8\xdf", ) f = SomeForm() self.assertHTMLEqual( f.as_p(), "<p><label>\xc5\xf8\xdf:</label>" '<div id="id_somechoice">\n' '<div><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" ' "required> En tied\xe4</label></div>\n" '<div><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" ' 'required> Mies</label></div>\n<div><label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" ' "required> Nainen</label></div>\n</div></p>", ) # Translated error messages with translation.override("ru"): f = SomeForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist" id="id_somechoice_error"><li>' "\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c" "\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n" "<p><label>\xc5\xf8\xdf:</label>" ' <div id="id_somechoice">\n<div><label for="id_somechoice_0">' '<input type="radio" id="id_somechoice_0" value="\xc5" ' 'name="somechoice" aria-invalid="true" required>' "En tied\xe4</label></div>\n" '<div><label for="id_somechoice_1">' '<input type="radio" id="id_somechoice_1" value="\xf8" ' 'name="somechoice" aria-invalid="true" required>' "Mies</label></div>\n<div>" '<label for="id_somechoice_2">' '<input type="radio" id="id_somechoice_2" value="\xdf" ' 'name="somechoice" aria-invalid="true" required>' "Nainen</label></div>\n</div></p>", ) def test_select_translated_text(self): # Deep copying translated text shouldn't raise an error. class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy("test")),))) CopyForm() @jinja2_tests
FormsI18nTests
python
pytorch__pytorch
test/test_numba_integration.py
{ "start": 360, "end": 15769 }
class ____(common.TestCase): @unittest.skipIf(not TEST_NUMPY, "No numpy") @unittest.skipIf(not TEST_CUDA, "No cuda") def test_cuda_array_interface(self): """torch.Tensor exposes __cuda_array_interface__ for cuda tensors. An object t is considered a cuda-tensor if: hasattr(t, '__cuda_array_interface__') A cuda-tensor provides a tensor description dict: shape: (integer, ...) Tensor shape. strides: (integer, ...) Tensor strides, in bytes. typestr: (str) A numpy-style typestr. data: (int, boolean) A (data_ptr, read-only) tuple. version: (int) Version 0 See: https://numba.pydata.org/numba-doc/dev/cuda/cuda_array_interface.html """ types = [ torch.DoubleTensor, torch.FloatTensor, torch.HalfTensor, torch.LongTensor, torch.IntTensor, torch.ShortTensor, torch.CharTensor, torch.ByteTensor, ] dtypes = [ numpy.float64, numpy.float32, numpy.float16, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, ] for tp, npt in zip(types, dtypes): # CPU tensors do not implement the interface. cput = tp(10) self.assertFalse(hasattr(cput, "__cuda_array_interface__")) self.assertRaises(AttributeError, lambda: cput.__cuda_array_interface__) # Sparse CPU/CUDA tensors do not implement the interface if tp not in (torch.HalfTensor,): indices_t = torch.empty(1, cput.size(0), dtype=torch.long).clamp_(min=0) sparse_t = torch.sparse_coo_tensor(indices_t, cput) self.assertFalse(hasattr(sparse_t, "__cuda_array_interface__")) self.assertRaises( AttributeError, lambda: sparse_t.__cuda_array_interface__ ) sparse_cuda_t = torch.sparse_coo_tensor(indices_t, cput).cuda() self.assertFalse(hasattr(sparse_cuda_t, "__cuda_array_interface__")) self.assertRaises( AttributeError, lambda: sparse_cuda_t.__cuda_array_interface__ ) # CUDA tensors have the attribute and v2 interface cudat = tp(10).cuda() self.assertTrue(hasattr(cudat, "__cuda_array_interface__")) ar_dict = cudat.__cuda_array_interface__ self.assertEqual( set(ar_dict.keys()), {"shape", "strides", "typestr", "data", "version"} ) self.assertEqual(ar_dict["shape"], (10,)) self.assertIs(ar_dict["strides"], None) # typestr from numpy, cuda-native little-endian self.assertEqual(ar_dict["typestr"], numpy.dtype(npt).newbyteorder("<").str) self.assertEqual(ar_dict["data"], (cudat.data_ptr(), False)) self.assertEqual(ar_dict["version"], 2) @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") def test_array_adaptor(self): """Torch __cuda_array_adaptor__ exposes tensor data to numba.cuda.""" torch_dtypes = [ torch.complex64, torch.complex128, torch.float16, torch.float32, torch.float64, torch.uint8, torch.int8, torch.uint16, torch.int16, torch.uint32, torch.int32, torch.uint64, torch.int64, torch.bool, ] for dt in torch_dtypes: # CPU tensors of all types do not register as cuda arrays, # attempts to convert raise a type error. cput = torch.arange(10).to(dt) npt = cput.numpy() self.assertTrue(not numba.cuda.is_cuda_array(cput)) with self.assertRaises(TypeError): numba.cuda.as_cuda_array(cput) # Any cuda tensor is a cuda array. cudat = cput.to(device="cuda") self.assertTrue(numba.cuda.is_cuda_array(cudat)) numba_view = numba.cuda.as_cuda_array(cudat) self.assertIsInstance(numba_view, numba.cuda.devicearray.DeviceNDArray) # The reported type of the cuda array matches the numpy type of the cpu tensor. self.assertEqual(numba_view.dtype, npt.dtype) self.assertEqual(numba_view.strides, npt.strides) self.assertEqual(numba_view.shape, cudat.shape) # Pass back to cuda from host for all equality checks below, needed for # float16 comparisons, which aren't supported cpu-side. # The data is identical in the view. self.assertEqual(cudat, torch.tensor(numba_view.copy_to_host()).to("cuda")) # Writes to the torch.Tensor are reflected in the numba array. cudat[:5] = 11 self.assertEqual(cudat, torch.tensor(numba_view.copy_to_host()).to("cuda")) # Strided tensors are supported. strided_cudat = cudat[::2] strided_npt = cput[::2].numpy() strided_numba_view = numba.cuda.as_cuda_array(strided_cudat) self.assertEqual(strided_numba_view.dtype, strided_npt.dtype) self.assertEqual(strided_numba_view.strides, strided_npt.strides) self.assertEqual(strided_numba_view.shape, strided_cudat.shape) # As of numba 0.40.0 support for strided views is ...limited... # Cannot verify correctness of strided view operations. @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") def test_conversion_errors(self): """Numba properly detects array interface for tensor.Tensor variants.""" # CPU tensors are not cuda arrays. cput = torch.arange(100) self.assertFalse(numba.cuda.is_cuda_array(cput)) with self.assertRaises(TypeError): numba.cuda.as_cuda_array(cput) # Sparse tensors are not cuda arrays, regardless of device. sparset = torch.sparse_coo_tensor(cput[None, :], cput) self.assertFalse(numba.cuda.is_cuda_array(sparset)) with self.assertRaises(TypeError): numba.cuda.as_cuda_array(sparset) sparset.cuda() self.assertFalse(numba.cuda.is_cuda_array(sparset)) with self.assertRaises(TypeError): numba.cuda.as_cuda_array(sparset) # Device-status overrides gradient status. # CPU+gradient isn't a cuda array. cpu_gradt = torch.zeros(100).requires_grad_(True) self.assertFalse(numba.cuda.is_cuda_array(cpu_gradt)) with self.assertRaises(TypeError): numba.cuda.as_cuda_array(cpu_gradt) # CUDA+gradient raises a RuntimeError on check or conversion. # # Use of hasattr for interface detection causes interface change in # python2; it swallows all exceptions not just AttributeError. cuda_gradt = torch.zeros(100).requires_grad_(True).cuda() # conversion raises RuntimeError with self.assertRaises(RuntimeError): numba.cuda.is_cuda_array(cuda_gradt) with self.assertRaises(RuntimeError): numba.cuda.as_cuda_array(cuda_gradt) @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") @unittest.skipIf(not TEST_MULTIGPU, "No multigpu") def test_active_device(self): """'as_cuda_array' tensor device must match active numba context.""" # Both torch/numba default to device 0 and can interop freely cudat = torch.arange(10, device="cuda") self.assertEqual(cudat.device.index, 0) self.assertIsInstance( numba.cuda.as_cuda_array(cudat), numba.cuda.devicearray.DeviceNDArray ) # Tensors on non-default device raise api error if converted cudat = torch.arange(10, device=torch.device("cuda", 1)) with self.assertRaises(numba.cuda.driver.CudaAPIError): numba.cuda.as_cuda_array(cudat) # but can be converted when switching to the device's context with numba.cuda.devices.gpus[cudat.device.index]: self.assertIsInstance( numba.cuda.as_cuda_array(cudat), numba.cuda.devicearray.DeviceNDArray ) @unittest.skip( "Test is temporary disabled, see https://github.com/pytorch/pytorch/issues/54418" ) @unittest.skipIf(not TEST_NUMPY, "No numpy") @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") def test_from_cuda_array_interface(self): """torch.as_tensor() and torch.tensor() supports the __cuda_array_interface__ protocol. If an object exposes the __cuda_array_interface__, .as_tensor() and .tensor() will use the exposed device memory. See: https://numba.pydata.org/numba-doc/dev/cuda/cuda_array_interface.html """ dtypes = [ numpy.complex64, numpy.complex128, numpy.float64, numpy.float32, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, ] for dtype in dtypes: numpy_arys = [ numpy.ones((), dtype=dtype), numpy.arange(6).reshape(2, 3).astype(dtype), numpy.arange(6) .reshape(2, 3) .astype(dtype)[1:], # View offset should be ignored numpy.arange(6) .reshape(2, 3) .astype(dtype)[:, None], # change the strides but still contiguous ] # Zero-copy when using `torch.as_tensor()` for numpy_ary in numpy_arys: numba_ary = numba.cuda.to_device(numpy_ary) torch_ary = torch.as_tensor(numba_ary, device="cuda") self.assertEqual( numba_ary.__cuda_array_interface__, torch_ary.__cuda_array_interface__, ) self.assertEqual( torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary, dtype=dtype) ) # Check that `torch_ary` and `numba_ary` points to the same device memory torch_ary += 42 self.assertEqual( torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary, dtype=dtype) ) # Implicit-copy because `torch_ary` is a CPU array for numpy_ary in numpy_arys: numba_ary = numba.cuda.to_device(numpy_ary) torch_ary = torch.as_tensor(numba_ary, device="cpu") self.assertEqual( torch_ary.data.numpy(), numpy.asarray(numba_ary, dtype=dtype) ) # Check that `torch_ary` and `numba_ary` points to different memory torch_ary += 42 self.assertEqual( torch_ary.data.numpy(), numpy.asarray(numba_ary, dtype=dtype) + 42 ) # Explicit-copy when using `torch.tensor()` for numpy_ary in numpy_arys: numba_ary = numba.cuda.to_device(numpy_ary) torch_ary = torch.tensor(numba_ary, device="cuda") self.assertEqual( torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary, dtype=dtype) ) # Check that `torch_ary` and `numba_ary` points to different memory torch_ary += 42 self.assertEqual( torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary, dtype=dtype) + 42, ) @unittest.skipIf(not TEST_NUMPY, "No numpy") @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") def test_from_cuda_array_interface_inferred_strides(self): """torch.as_tensor(numba_ary) should have correct inferred (contiguous) strides""" # This could, in theory, be combined with test_from_cuda_array_interface but that test # is overly strict: it checks that the exported protocols are exactly the same, which # cannot handle differing exported protocol versions. dtypes = [ numpy.float64, numpy.float32, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, ] for dtype in dtypes: numpy_ary = numpy.arange(6).reshape(2, 3).astype(dtype) numba_ary = numba.cuda.to_device(numpy_ary) self.assertTrue(numba_ary.is_c_contiguous()) torch_ary = torch.as_tensor(numba_ary, device="cuda") self.assertTrue(torch_ary.is_contiguous()) @unittest.skip( "Test is temporary disabled, see https://github.com/pytorch/pytorch/issues/54418" ) @unittest.skipIf(not TEST_NUMPY, "No numpy") @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") def test_from_cuda_array_interface_lifetime(self): """torch.as_tensor(obj) tensor grabs a reference to obj so that the lifetime of obj exceeds the tensor""" numba_ary = numba.cuda.to_device(numpy.arange(6)) torch_ary = torch.as_tensor(numba_ary, device="cuda") self.assertEqual( torch_ary.__cuda_array_interface__, numba_ary.__cuda_array_interface__ ) # No copy del numba_ary self.assertEqual( torch_ary.cpu().data.numpy(), numpy.arange(6) ) # `torch_ary` is still alive @unittest.skip( "Test is temporary disabled, see https://github.com/pytorch/pytorch/issues/54418" ) @unittest.skipIf(not TEST_NUMPY, "No numpy") @unittest.skipIf(not TEST_CUDA, "No cuda") @unittest.skipIf(not TEST_NUMBA_CUDA, "No numba.cuda") @unittest.skipIf(not TEST_MULTIGPU, "No multigpu") def test_from_cuda_array_interface_active_device(self): """torch.as_tensor() tensor device must match active numba context.""" # Zero-copy: both torch/numba default to device 0 and can interop freely numba_ary = numba.cuda.to_device(numpy.arange(6)) torch_ary = torch.as_tensor(numba_ary, device="cuda") self.assertEqual(torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary)) self.assertEqual( torch_ary.__cuda_array_interface__, numba_ary.__cuda_array_interface__ ) # Implicit-copy: when the Numba and Torch device differ numba_ary = numba.cuda.to_device(numpy.arange(6)) torch_ary = torch.as_tensor(numba_ary, device=torch.device("cuda", 1)) self.assertEqual(torch_ary.get_device(), 1) self.assertEqual(torch_ary.cpu().data.numpy(), numpy.asarray(numba_ary)) if1 = torch_ary.__cuda_array_interface__ if2 = numba_ary.__cuda_array_interface__ self.assertNotEqual(if1["data"], if2["data"]) del if1["data"] del if2["data"] self.assertEqual(if1, if2) if __name__ == "__main__": common.run_tests()
TestNumbaIntegration
python
pytorch__pytorch
torch/fx/experimental/proxy_tensor.py
{ "start": 5821, "end": 30236 }
class ____(threading.local): value: bool = False _disable_update_tensor_tracker_tls = _DisableUpdateTensorTracker() _FAKE_TENSOR_ID_TO_PROXY_MAP_FOR_EXPORT: dict[int, torch.fx.Node] = {} def _is_proxy_tensor_update_tensor_tracker_disabled() -> bool: """ Returns current state of disabling update tensor tracker. """ return _disable_update_tensor_tracker_tls.value @contextmanager def _proxy_tensor_disable_update_tensor_tracker() -> Generator[None, None, None]: """ NOTE "Do not clobber inplace ops" By default tensor_tracker is updated every time. This leads to chaining every operation by the FakeTensor. For example for mutable ops if we have several consecutive mutable operations: def f(x, y, z): x.copy_(y) x.copy_(z) return x Default graph result: def f_graph(x, y, z) x_1 = x.copy_(y) x_2 = x_1.copy_(z) return x_2 This chaining simplifies the fx passes and helps to prevent the reordering. But in some cases, we want those nodes to be disconnected. E.g. in case of splitting joint graph into forward and backward. If first inplace op happened in forward, second in backward, we want them after split to be properly placed. Enabling this context manager for copy_ will result in: def f_graph_2(x, y, z): x_1 = x.copy_(y) x_2 = x.copy_(z) return x Results of copy_ x1 and x2 will have empty users in the graph. The reason why this behavior is not enabled for all inplace ops is that some fx passes (e.g. fx quantization) rely on chaining inplace ops like add_ in their fusions passes. We could revisit enabling this logic for all inplace ops in future. """ orig_value = _disable_update_tensor_tracker_tls.value _disable_update_tensor_tracker_tls.value = True try: yield finally: _disable_update_tensor_tracker_tls.value = orig_value def set_proxy_slot( # type: ignore[no-redef] obj: Union[PySymType, _AnyScriptObjectType, Tensor], tracer: _ProxyTracer, proxy: object, ) -> None: log.debug("set_proxy_slot %s (%s) %s", obj, id(obj), proxy) if isinstance(obj, Tensor): # We DO want to clobber proxies whenever we run an inplace operation # on a tensor, and it affects the metadata on the proxy. assert isinstance(proxy, _ProxyTensor) # see NOTE [Do not clobber inplace ops] if not _is_proxy_tensor_update_tensor_tracker_disabled(): tracer.tensor_tracker[obj] = proxy elif isinstance(obj, (_AnyScriptObject)): # We DO want to clobber proxies, with a similar rationale as for tensors. assert isinstance(proxy, Proxy) tracer.script_object_tracker[obj] = proxy else: # NB: Never clobber pre-existing proxy. Although the proxies # are in principle equivalent, when we do graph partitioning # we need there not to be spurious dependencies on tangent inputs. # This works because primals get their SymInts set first, and # THEN later we allocate tangent inputs. Make sure if a SymInt # is derivable from a primal that we use that. assert isinstance(obj, py_sym_types), type(obj) if obj not in tracer.symnode_tracker: proxy = typing.cast(_PySymProxyType, proxy) tracer.symnode_tracker[obj] = proxy # WAR: python test/dynamo/test_subclasses.py # TestNestedTensor.test_basic_autograd # # AOTAutograd doesn't pass the "outer sizes" as an actual argument # to make_fx, but it is made use of internally in AOTAutograd's # call to tensor unflatten. Because the outer sizes isn't passed # as an argument, it is therefore untracked. However, it turns # out you luck out, because *Dynamo* will manually add the outer # sizes as an argument so you can fix up the proxy'ness. # # This is probably fixed in # https://github.com/pytorch/pytorch/pull/125941/ import sympy if isinstance(obj.node.expr, sympy.Symbol): tracer.sympy_expr_tracker[obj.node.expr] = _SympyExprTrackerValue( proxy, obj ) def has_proxy_slot(obj: Tensor, tracer: _ProxyTracer) -> bool: assert isinstance(obj, (Tensor, SymNode)), type(obj) # pyrefly: ignore [no-matching-overload] return bool(get_proxy_slot(obj, tracer, False, lambda _: True)) _PySymProxyType = Thunk[Proxy] @overload def get_proxy_slot( obj: Tensor, tracer: _ProxyTracer, ) -> _ProxyTensor: ... @overload def get_proxy_slot( obj: Tensor, tracer: _ProxyTracer, default: U, ) -> Union[_ProxyTensor, U]: ... @overload def get_proxy_slot( obj: Tensor, tracer: _ProxyTracer, default: U, transform: Callable[[_ProxyTensor], R], ) -> Union[R, U]: ... @overload def get_proxy_slot( obj: _AnyScriptObjectType, tracer: _ProxyTracer, ) -> Proxy: ... @overload def get_proxy_slot( obj: _AnyScriptObjectType, tracer: _ProxyTracer, default: U, ) -> Union[Proxy, U]: ... @overload def get_proxy_slot( obj: _AnyScriptObjectType, tracer: _ProxyTracer, default: U, transform: Callable[[Proxy], R], ) -> Union[R, U]: ... @overload def get_proxy_slot( obj: PySymType, tracer: _ProxyTracer, ) -> _PySymProxyType: ... @overload def get_proxy_slot( obj: PySymType, tracer: _ProxyTracer, default: T, ) -> Union[T, _PySymProxyType]: ... @overload def get_proxy_slot( obj: PySymType, tracer: _ProxyTracer, default: U, transform: Callable[[_PySymProxyType], R], ) -> Union[R, U]: ... # the default argument is what to return if the slot is not set. # the transform argument is handy if you need to extract a subfield from # the successfully looked up result (but NOT the default.) def get_proxy_slot( obj: Union[Tensor, _AnyScriptObjectType, PySymType], tracer: _ProxyTracer, default: object = no_default, transform: Callable = lambda x: x, ) -> object: tracker: Any if isinstance(obj, Tensor): tracker = tracer.tensor_tracker elif isinstance(obj, _AnyScriptObject): tracker = tracer.script_object_tracker else: assert isinstance(obj, py_sym_types), type(obj) tracker = tracer.symnode_tracker # pyrefly: ignore [index-error] # pyrefly: ignore [no-matching-overload, bad-argument-type] value = tracker.get(obj) if value is None and isinstance(obj, py_sym_types): if obj.node.is_symbolic(): # Last ditch - we found a SymInt (SymBool, etc) we don't know # about. if (tmp := tracer.sympy_expr_tracker.get(obj.node.expr)) is not None: value = tmp.proxy else: # Attempt to build it from first principles. _build_proxy_for_sym_expr(tracer, obj.node.expr, obj) # pyrefly: ignore [no-matching-overload] value = tracker.get(obj) if value is None: # We don't know this value - return the default. if isinstance(default, _NoDefault): raise RuntimeError( f"{obj} ({type(obj)}, {id(obj)})is not tracked with proxy for {tracer}" ) return default res = transform(value) return res @functools.cache def _sympy_handlers() -> dict[type[sympy.Expr], Callable[..., Any]]: """ Returns a dict converting sympy functions to python operators (i.e. `sympy.Mul` -> `operator.mul`) """ import torch.utils._sympy.interp handlers = {} for k, v in torch.utils._sympy.interp.handlers().items(): op = getattr(operator, v, None) if op is not None: handlers[k] = op return handlers def _build_proxy_for_sym_expr( tracer: _ProxyTracer, expr: sympy.Expr, out: PySymType | None = None ) -> IntLikeType | FloatLikeType | BoolLikeType | None: """ Decompose `expr` and look for the pieces as inputs. If `out` is provided then that will be the resulting SymNode (and `out.expr` must be the same as `expr`). This function is used when the ProxyTorchDispatchMode sees a SymNode that it hasn't seen before to try to associate it with traced inputs. How can this happen? First thing to remember is that although sympy.Exprs are interned (so `sympy.Expr("s3*s4")` will always have the same `id` and will always compare equal) SymNode does not (so doing `SymNode("s3")*SymNode("s4")` twice in a row will give two unique SymNodes). - On way for this to happen is if we turn off tracing to compute an intermediate value and then USE that value with tracing turned on - for example if we turn off tracing to do some FakeTensor propagation to compute a size (dtensor does this) but then turn tracing back on and use that computed size. - Another way is if we compute a size in one graph and stash it somewhere hidden (such as in some meta-data) and later use it in a different graph (dtensor does this too). Since the size was computed in the first graph and it's not an official input to the second graph it's not tracked properly. This is often going to show up as it usually works in fullgraph but a graph break causes a failure. To handle this we decompose the sympy.Expr and look for the pieces as inputs. But there are problems with this approach: - We lose operation provanance: We end up figuring out where to get the inputs - but those may not actually be correct. If we have "s1" coming in from both tensor1 and tensor2 and we pick the wrong one we could end up keeping a tensor alive longer than intended. - There's no guarantee that those values are inputs to the graph: If we have "s1*s2" computed in a graph #1 and used in graph #2 there's no guarantee that the input that holds "s1" is actually an input on graph #2. - The decomposition isn't guaranteed to be the same: Sympy can "simplify" expressions so it's possible that our inputs are "s1*s2" and "s3" but we decompose it into "s1" and "s2*s3" - which wouldn't be found. Other ways we could handle this: - Don't: Just require that all inputs are tracked properly. This is the "correct" solution but harder because you need to track down each potential problem one by one and fix them. And when it fails it's a lot of work to figure out both why it's failing and the right way to fix it. This is complicated by the fact that a stashed value could be incorrect but work fine until we happen to get an graph break in the wrong place - so it may be a while before the bug is found. (Maybe we need a "dynamo abuse mode" where we run tests with as many graph breaks inserted as possible?) - Track SymNode ops separately from proxy tracing: Right now SymNode operations are tracked as part of the proxy tracing - so when we disable proxy tracing we also disable SymNode tracing. But we don't have to do that - we could instead always have SymNodes track where they came from and just use that when needed. This solves the problem of tracing being temporarily turned off but doesn't help if an input isn't present after a graph break. - Better decomposition: Right now the decomposition is pretty simple. We do have a sat-solver available to us so we could theoretically do a better job figuring out a "correct" decomposition. But that still relies on having the inputs available at all - which isn't a guarantee. """ if (value := tracer.sympy_expr_tracker.get(expr)) is not None: assert not out return value.value if isinstance(expr, (int, float, bool)): return expr if expr.is_Integer: return int(expr) if expr.is_Float: return float(expr) args = [] for arg in expr.args: if (arg_value := _build_proxy_for_sym_expr(tracer, arg)) is None: return None args.append(arg_value) args = tuple(args) func: OpOverload | None = _sympy_handlers().get(expr.func) # type: ignore[assignment] if not func: # Handler not found return None if out is None: out = func(*args) else: _sym_register(tracer, func, args, out) return out def snapshot_fake(val: Tensor, include_real: bool = False) -> Optional[Tensor]: # val.detach() will also eventually call fast_detach(), # but this saves us a full trip into __torch_dispatch__ # (snapshot_fake is called a lot) if isinstance(val, FakeTensor): return fast_detach(val.fake_mode, val, include_real) else: return val.detach() _ExtractValType = Optional[ Union[ PySymType, _AnyScriptObjectType, BackwardState, list["_ExtractValType"], tuple["_ExtractValType", ...], dict[str, "_ExtractValType"], Tensor, int, float, bool, ] ] def extract_val(val: _ExtractValType, include_real: bool = False) -> _ExtractValType: if is_fake(val): return snapshot_fake(val, include_real=include_real) elif isinstance(val, py_sym_types): return val elif isinstance(val, _AnyScriptObject): return val elif isinstance(val, BackwardState): return val elif isinstance(val, (list, tuple)): return val.__class__([extract_val(x) for x in val]) elif isinstance(val, dict): return {k: extract_val(v) for k, v in val.items()} elif isinstance(val, Tensor): if not val.is_sparse: # NB: Kinda hacky, but we should try to get val as the metadata # everywhere # TODO: This doesn't properly track storages. A more robust # approach would be to maintain a per-trace FakeTensorMode and # from_real_tensor to create fake values (don't forget to # snapshot_fake) from torch._guards import detect_fake_mode fake_tensor_mode = detect_fake_mode(val) if not fake_tensor_mode: fake_tensor_mode = FakeTensorMode(allow_fallback_kernels=True) with fake_tensor_mode: return torch.empty_strided( val.shape, val.stride(), device=val.device, dtype=val.dtype ) else: return None elif isinstance(val, (int, float, bool)): return val elif val is None: return None typing_extensions.assert_never(val) @contextmanager def _enable_thunkify( tracer: _ProxyTracer, *, enable: bool = True ) -> Generator[None, None, None]: """ Enable thunkification inside the context manager. Thunkification prevents SymNode computation from directly being traced into an FX graph; instead, the compute is only added to the graph if it is actually used. This helps us track SymNode compute when it is computed (since we need /something/ to put in the tracker) even if it is unlikely to be used. """ old = tracer.enable_thunkify tracer.enable_thunkify = enable try: yield finally: tracer.enable_thunkify = old @contextmanager def maybe_disable_thunkify() -> Generator[None, None, None]: """Within a context, disable thunkification. See :func:`maybe_enable_thunkify` for more details. This is helpful if you have a wrapper function which you want to enable thunkification on, but in some segment on the inside (say, the original user function), you want to disable thunkification as you know it is not needed there. """ proxy_mode = get_proxy_mode() if proxy_mode is not None: with _enable_thunkify(proxy_mode.tracer, enable=False): yield else: yield @contextmanager def maybe_enable_thunkify() -> Generator[None, None, None]: """Within this context manager, if you are doing make_fx tracing, we will thunkify all SymNode compute and avoid tracing it into the graph unless it is actually needed. You should prefer to avoid using this as much as possible, as lazy evaluation of SymNode tracing can lead to long chains of thunks which will stack overflow if you evaluate them. However, this is currently sometimes necessary as there are buggy parts of PT2 which will fail with "s0 is not tracked with proxy" error due to insufficient tracing of SymNode computation. """ proxy_mode = get_proxy_mode() if proxy_mode is not None: with _enable_thunkify(proxy_mode.tracer): yield else: yield # Note [invariants for node meta 'val'] # What invariants do we have for the 'val' set on the FX node? It has accurate # metadata... but only for metadata that exists "below" all other subsystems # (most notably autograd, but also vmap, functorch transforms, etc). This means # you can get the dtype, shape, stride, storage, but you CANNOT get requires_grad, # grad_fn, _base (_base actually may be set due to recursive call to # ADInplaceOrView, but you shouldn't rely on it.) def set_meta(proxy: Proxy, val: _ExtractValType) -> Proxy: proxy.node.meta["val"] = extract_val( val, include_real=(proxy.node.op == "placeholder") ) with _enable_thunkify(proxy.tracer): # type: ignore[arg-type] # Best effort tensor_meta setting; prefer using val! if is_fake(val): proxy.node.meta["tensor_meta"] = _extract_tensor_metadata(val) elif isinstance(val, Tensor) and not val.is_sparse: proxy.node.meta["tensor_meta"] = _extract_tensor_metadata(val) return proxy def thunkify( tracer: _ProxyTracer, f: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs ) -> Thunk[R]: """ Delays computation of f until it's called again Also caches the result """ if tracer.enable_thunkify: return Thunk(functools.partial(f, *args, **kwargs)) else: r = f(*args, **kwargs) return Thunk(lambda: r) def track_tensor( tensor: Tensor, proxy: Proxy, *, constant: Optional[Tensor], tracer: _ProxyTracer ) -> None: def try_set_proxy_slot( outer_s: IntLikeType, proxy_callable: Callable[Concatenate[PySymType, _P], Proxy], *args: _P.args, **kwargs: _P.kwargs, ) -> None: assert callable(proxy_callable) if isinstance(outer_s, SymInt): with _enable_thunkify(tracer): set_proxy_slot( outer_s, tracer, thunkify(tracer, proxy_callable, outer_s, *args, **kwargs), ) # The basic idea is that we need to associate each tensor/SymInt # with a Proxy. How do we setup this association? We just store # the proxy on the proxy slot of the object, keyed on the tracer # (so that if we have multiple tracers at the same time, they # don't clobber each other.) for i, s in enumerate(tensor.shape): try_set_proxy_slot( s, lambda x, i: set_meta( tracer.create_proxy( "call_function", torch.ops.aten.sym_size.int, (proxy, i), {} ), x, ), i, ) if not is_sparse_any(tensor): for i, s in enumerate(tensor.stride()): try_set_proxy_slot( s, lambda x, i: set_meta( tracer.create_proxy( "call_function", torch.ops.aten.sym_stride.int, (proxy, i), {} ), x, ), i, ) try_set_proxy_slot( tensor.numel(), lambda x: set_meta( tracer.create_proxy( "call_function", torch.ops.aten.sym_numel.default, (proxy,), {} ), x, ), ) if not is_sparse_any(tensor): try_set_proxy_slot( tensor.storage_offset(), lambda x: set_meta( tracer.create_proxy( "call_function", torch.ops.aten.sym_storage_offset.default, (proxy,), {}, ), x, ), ) set_proxy_slot(tensor, tracer, _ProxyTensor(proxy, constant)) _NestedProxys = Union[ Proxy, Sequence["_NestedProxys"], Mapping[object, "_NestedProxys"] ] _NestedTensors = Union[ Tensor, Sequence["_NestedTensors"], Mapping[object, "_NestedTensors"] ] def track_tensor_tree( inner_res: T, proxy_res: _NestedProxys, *, constant: Optional[_NestedTensors], tracer: _ProxyTracer, ) -> T: # NB: We call set_unbacked_bindings only on the *topmost* call to # track_tensor_tree, not recursive calls. This is because there must # be only ONE unbacked_binding proxy call, and it should be the one # where all of the unbacked SymInts actually first come into existence. # If you call this again on the inner proxies for the tuple projections, # you will have multiple unbacked_bindings for the same symbol, but # they're not going to show up anywhere. # # I was briefly deceived into setting unbacked bindings recursively when # working on https://github.com/pytorch/pytorch/pull/133585 because I # observed that some extra unbacked bindings were needed to handle some # higher order operator code. But actually it looks like this was # just an unrelated bug that needed to be fixed separately. _set_unbacked_bindings(inner_res, proxy_res) def wrap_with_proxy( e: object, proxy: _NestedProxys, constant: Optional[_NestedTensors] ) -> None: if isinstance(e, Tensor): assert isinstance(proxy, Proxy) assert constant is None or isinstance(constant, Tensor) track_tensor(e, proxy, tracer=tracer, constant=constant) set_meta(proxy, e) elif isinstance(e, py_sym_types): assert isinstance(proxy, Proxy) # NB: eagerly set meta here, so that the numbering is in order set_meta(proxy, e) set_proxy_slot(e, tracer, thunkify(tracer, lambda: proxy)) elif isinstance(e, _AnyScriptObject): assert isinstance(proxy, Proxy) set_proxy_slot(e, tracer, proxy) set_meta(proxy, e) elif isinstance(e, (tuple, list)): # example use case: allreduce_ returns ([tensor], work) if isinstance(proxy, fx.Proxy): set_meta(proxy, e) def get_constant( c: Optional[_NestedTensors], idx: int ) -> Optional[_NestedTensors]: if c is None: return None else: assert isinstance(c, (list, tuple)) return c[idx] for idx, ee in enumerate(e): # Use an indexer here - if proxy is a List then it will unwrap # it. If it's a Proxy then it will proxy the getelem. wrap_with_proxy(ee, proxy[idx], get_constant(constant, idx)) # type: ignore[index] elif isinstance(e, dict): # example use case: triton_kernel_wrapper takes arguments as kwargs # In theory we could support const-prop when proxy-tensor-tracing # operators that returns dicts of tensors, but we have no use case # for it today (since the only op we currently trace that can # return a dict is triton_kernel_wrapper_functional/mutation, # which does not participate in const-prop) assert constant is None if isinstance(proxy, fx.Proxy): set_meta(proxy, e) for key, val in e.items(): wrap_with_proxy(val, proxy[key], None) # type: ignore[index] elif isinstance(e, BackwardState): assert isinstance(proxy, Proxy) set_meta(proxy, e) e.proxy = proxy else: # intentionally pass on primitives pass wrap_with_proxy(inner_res, proxy_res, constant) return inner_res @dataclass
_DisableUpdateTensorTracker
python
facebookresearch__faiss
tests/test_residual_quantizer.py
{ "start": 38886, "end": 40015 }
class ____(unittest.TestCase): def test_codec(self): """check that the error is in the same ballpark as PQ.""" ds = datasets.SyntheticDataset(64, 3000, 3000, 0) xt = ds.get_train() xb = ds.get_database() nsplits = 2 Msub = 2 nbits = 4 prq = faiss.ProductResidualQuantizer(ds.d, nsplits, Msub, nbits) prq.train(xt) err_prq = eval_codec(prq, xb) pq = faiss.ProductQuantizer(ds.d, nsplits * Msub, nbits) pq.train(xt) err_pq = eval_codec(pq, xb) self.assertLess(err_prq, err_pq) def test_with_rq(self): """compare with RQ when nsplits = 1""" ds = datasets.SyntheticDataset(32, 3000, 3000, 0) xt = ds.get_train() xb = ds.get_database() M = 4 nbits = 4 prq = faiss.ProductResidualQuantizer(ds.d, 1, M, nbits) prq.train(xt) err_prq = eval_codec(prq, xb) rq = faiss.ResidualQuantizer(ds.d, M, nbits) rq.train(xt) err_rq = eval_codec(rq, xb) self.assertEqual(err_prq, err_rq)
TestProductResidualQuantizer
python
pennersr__django-allauth
tests/apps/socialaccount/providers/evernote/tests.py
{ "start": 243, "end": 989 }
class ____(OAuthTestsMixin, TestCase): provider_id = EvernoteProvider.id def get_mocked_response(self): return [] def get_expected_to_str(self): return "Evernote" def get_access_token_response(self): return MockedResponse( HTTPStatus.OK, "oauth_token=S%3Ds1%3AU%3D9876%3AE%3D999999b0c50%3AC%3D14c1f89dd18%3AP%3D81%3AA%3Dpennersr%3AV%3D2%3AH%3Ddeadf00dd2d6aba7b519923987b4bf77&oauth_token_secret=&edam_shard=s1&edam_userId=591969&edam_expires=1457994271824&edam_noteStoreUrl=https%3A%2F%2Fsandbox.evernote.com%2Fshard%2Fs1%2Fnotestore&edam_webApiUrlPrefix=https%3A%2F%2Fsandbox.evernote.com%2Fshard%2Fs1%2F", # noqa {"content-type": "text/plain"}, )
EvernoteTests
python
django__django
tests/admin_widgets/models.py
{ "start": 5350, "end": 5630 }
class ____(models.Model): name = models.CharField(max_length=255) students = models.ManyToManyField(Student, related_name="current_schools") alumni = models.ManyToManyField(Student, related_name="previous_schools") def __str__(self): return self.name
School
python
numba__numba
numba/tests/test_unsafe_intrinsics.py
{ "start": 2088, "end": 4123 }
class ____(TestCase): """Tests for numba.unsafe.ndarray """ def test_to_fixed_tuple(self): const = 3 @njit def foo(array): a = to_fixed_tuple(array, length=1) b = to_fixed_tuple(array, 2) c = to_fixed_tuple(array, const) d = to_fixed_tuple(array, 0) return a, b, c, d np.random.seed(123) for _ in range(10): # Random data arr = np.random.random(3) # Run a, b, c, d = foo(arr) # Check self.assertEqual(a, tuple(arr[:1])) self.assertEqual(b, tuple(arr[:2])) self.assertEqual(c, tuple(arr[:3])) self.assertEqual(d, ()) # Check error with ndim!=1 with self.assertRaises(TypingError) as raises: foo(np.random.random((1, 2))) self.assertIn("Not supported on array.ndim=2", str(raises.exception)) # Check error with non-constant length @njit def tuple_with_length(array, length): return to_fixed_tuple(array, length) with self.assertRaises(TypingError) as raises: tuple_with_length(np.random.random(3), 1) expectmsg = "*length* argument must be a constant" self.assertIn(expectmsg, str(raises.exception)) def test_issue_3586_variant1(self): @njit def func(): S = empty_inferred((10,)) a = 1.1 for i in range(len(S)): S[i] = a + 2 return S got = func() expect = np.asarray([3.1] * 10) np.testing.assert_array_equal(got, expect) def test_issue_3586_variant2(self): @njit def func(): S = empty_inferred((10,)) a = 1.1 for i in range(S.size): S[i] = a + 2 return S got = func() expect = np.asarray([3.1] * 10) np.testing.assert_array_equal(got, expect)
TestNdarrayIntrinsic
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1068829, "end": 1069586 }
class ____(sgqlc.types.Type, GitObject, Node): """Represents a Git blob.""" __schema__ = github_schema __field_names__ = ("byte_size", "is_binary", "is_truncated", "text") byte_size = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="byteSize") """Byte size of Blob object""" is_binary = sgqlc.types.Field(Boolean, graphql_name="isBinary") """Indicates whether the Blob is binary or text. Returns null if unable to determine the encoding. """ is_truncated = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isTruncated") """Indicates whether the contents is truncated""" text = sgqlc.types.Field(String, graphql_name="text") """UTF8 text data or null if the Blob is binary"""
Blob
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_filter_rewriting.py
{ "start": 11426, "end": 24765 }
class ____: def __call__(self, bar): return True lambda_without_source = eval("lambda x: x > 2", {}, {}) assert get_pretty_function_description(lambda_without_source) == "lambda x: <unknown>" @pytest.mark.parametrize( "start, end, predicate", [ (1, 4, lambda x: 0 < x < 5 and x % 7), (0, 9, lambda x: 0 <= x < 10 and x % 3), (1, None, lambda x: 0 < x <= Y), (None, None, lambda x: x == x), (None, None, lambda x: 1 == 1), (None, None, lambda x: 1 <= 2), (None, None, lambda x: x != 0), (None, None, NotAFunction()), (None, None, lambda_without_source), (None, None, lambda x, y=2: x >= 0), ], ) @given(data=st.data()) def test_rewriting_partially_understood_filters(data, start, end, predicate): s = st.integers().filter(predicate).wrapped_strategy assert isinstance(s, FilteredStrategy) assert isinstance(s.filtered_strategy, IntegersStrategy) assert s.filtered_strategy.start == start assert s.filtered_strategy.end == end assert s.flat_conditions == (predicate,) value = data.draw(s) assert predicate(value) @pytest.mark.parametrize( "strategy", [ st.text(), st.text(min_size=2), st.lists(st.none()), st.lists(st.none(), min_size=2), ], ) @pytest.mark.parametrize( "predicate", [bool, len, tuple, list, lambda x: x], ids=get_pretty_function_description, ) def test_sequence_filter_rewriting(strategy, predicate): s = unwrap_strategies(strategy) fs = s.filter(predicate) assert not isinstance(fs, FilteredStrategy) if s.min_size > 0: assert fs is s else: assert fs.min_size == 1 @pytest.mark.parametrize("method", [str.lower, str.title, str.upper]) def test_warns_on_suspicious_string_methods(method): s = unwrap_strategies(st.text()) with pytest.warns( HypothesisWarning, match="this allows all nonempty strings! Did you mean" ): fs = s.filter(method) assert fs.min_size == 1 @pytest.mark.parametrize("method", [str.isalnum]) def test_bumps_min_size_and_filters_for_content_str_methods(method): s = unwrap_strategies(st.text()) fs = s.filter(method) assert fs.filtered_strategy.min_size == 1 assert fs.flat_conditions == (method,) # Should we deterministically check whether ascii or not or st.characters fine? @pytest.mark.parametrize("al", [None, "cdef123", "cd12¥¦§©"]) @given(data()) def test_isidentifier_filter_properly_rewritten(al, data): if al is None: example = data.draw(st.text().filter(str.isidentifier)) else: example = data.draw(st.text(alphabet=al).filter(str.isidentifier)) assert set(example).issubset(al) assert example.isidentifier() def test_isidentifer_filter_unsatisfiable(): alphabet = "¥¦§©" assert not any(f"_{c}".isidentifier() for c in alphabet) fs = st.text(alphabet=alphabet).filter(str.isidentifier) with pytest.raises(Unsatisfiable): check_can_generate_examples(fs) @pytest.mark.parametrize( "op, attr, value, expected", [ (operator.lt, "min_value", -float_info.min / 2, 0), (operator.lt, "min_value", float_info.min / 2, float_info.min), (operator.gt, "max_value", float_info.min / 2, 0), (operator.gt, "max_value", -float_info.min / 2, -float_info.min), ], ) def test_filter_floats_can_skip_subnormals(op, attr, value, expected): base = st.floats(allow_subnormal=False).filter(partial(op, value)) assert getattr(base.wrapped_strategy, attr) == expected @pytest.mark.parametrize( "strategy, predicate, start, end", [ # text with integer bounds (st.text(min_size=1, max_size=5), partial(min_len, 3), 3, 5), (st.text(min_size=1, max_size=5), partial(max_len, 3), 1, 3), # text with only one bound (st.text(min_size=1), partial(min_len, 3), 3, math.inf), (st.text(min_size=1), partial(max_len, 3), 1, 3), (st.text(max_size=5), partial(min_len, 3), 3, 5), (st.text(max_size=5), partial(max_len, 3), 0, 3), # Unbounded text (st.text(), partial(min_len, 3), 3, math.inf), (st.text(), partial(max_len, 3), 0, 3), ], ids=get_pretty_function_description, ) @settings(max_examples=A_FEW) @given(data=st.data()) def test_filter_rewriting_text_partial_len(data, strategy, predicate, start, end): s = strategy.filter(predicate) assert isinstance(s, LazyStrategy) inner = unwrap_strategies(s) assert isinstance(inner, TextStrategy) assert inner.min_size == start assert inner.max_size == end value = data.draw(s) assert predicate(value) @given(data=st.data()) def test_can_rewrite_multiple_length_filters_if_not_lambdas(data): # This is a key capability for efficient rewriting using the `annotated-types` # package, although unfortunately we can't do it for lambdas. s = ( st.text(min_size=1, max_size=5) .filter(partial(min_len, 2)) .filter(partial(max_len, 4)) ) assert isinstance(s, LazyStrategy) inner = unwrap_strategies(s) assert isinstance(inner, TextStrategy) assert inner.min_size == 2 assert inner.max_size == 4 value = data.draw(s) assert 2 <= len(value) <= 4 @pytest.mark.parametrize( "predicate, start, end", [ # Simple lambdas (lambda x: len(x) < 3, 0, 2), (lambda x: len(x) <= 3, 0, 3), (lambda x: len(x) == 3, 3, 3), (lambda x: len(x) >= 3, 3, math.inf), (lambda x: len(x) > 3, 4, math.inf), # Simple lambdas, reverse comparison (lambda x: 3 > len(x), 0, 2), (lambda x: 3 >= len(x), 0, 3), (lambda x: 3 == len(x), 3, 3), (lambda x: 3 <= len(x), 3, math.inf), (lambda x: 3 < len(x), 4, math.inf), # More complicated lambdas (lambda x: 0 < len(x) < 5, 1, 4), (lambda x: 0 < len(x) >= 1, 1, math.inf), (lambda x: 1 > len(x) <= 0, 0, 0), (lambda x: len(x) > 0 and len(x) > 0, 1, math.inf), (lambda x: len(x) < 1 and len(x) < 1, 0, 0), (lambda x: len(x) > 1 and len(x) > 0, 2, math.inf), (lambda x: len(x) < 1 and len(x) < 2, 0, 0), ], ids=get_pretty_function_description, ) @pytest.mark.parametrize( "strategy", [ st.text(), st.lists(st.integers()), st.lists(st.integers(), unique=True), st.lists(st.sampled_from([1, 2, 3])), st.binary(), st.sets(st.integers()), st.frozensets(st.integers()), st.dictionaries(st.integers(), st.none()), st.lists(st.integers(), unique_by=lambda x: x % 17).map(tuple), ], ids=get_pretty_function_description, ) @settings(max_examples=A_FEW) @given(data=st.data()) def test_filter_rewriting_text_lambda_len(data, strategy, predicate, start, end): s = strategy.filter(predicate) unwrapped_nofilter = unwrap_strategies(strategy) unwrapped = unwrap_strategies(s) if was_mapped := isinstance(unwrapped, MappedStrategy): unwrapped = unwrapped.mapped_strategy assert isinstance(unwrapped, FilteredStrategy), f"{unwrapped=} {type(unwrapped)=}" assert isinstance( unwrapped.filtered_strategy, type(unwrapped_nofilter.mapped_strategy if was_mapped else unwrapped_nofilter), ) for pred in unwrapped.flat_conditions: assert pred.__name__ == "<lambda>" if isinstance(unwrapped.filtered_strategy, MappedStrategy): unwrapped = unwrapped.filtered_strategy.mapped_strategy # binary() has a finite-but-effectively-infinite cap instead. if isinstance(unwrapped_nofilter, BytesStrategy) and end == math.inf: end = COLLECTION_DEFAULT_MAX_SIZE assert unwrapped.filtered_strategy.min_size == start assert unwrapped.filtered_strategy.max_size == end value = data.draw(s) assert predicate(value) two = 2 @pytest.mark.parametrize( "predicate, start, end", [ # Simple lambdas (lambda x: len(x) < 3, 0, 2), (lambda x: len(x) <= 3, 0, 3), (lambda x: len(x) == 3, 3, 3), (lambda x: len(x) >= 3, 3, 3), # input max element_count=3 # Simple lambdas, reverse comparison (lambda x: 3 > len(x), 0, 2), (lambda x: 3 >= len(x), 0, 3), (lambda x: 3 == len(x), 3, 3), (lambda x: 3 <= len(x), 3, 3), # input max element_count=3 # More complicated lambdas (lambda x: 0 < len(x) < 5, 1, 3), # input max element_count=3 (lambda x: 0 < len(x) >= 1, 1, 3), # input max element_count=3 (lambda x: 1 > len(x) <= 0, 0, 0), (lambda x: len(x) > 0 and len(x) > 0, 1, 3), # input max element_count=3 (lambda x: len(x) < 1 and len(x) < 1, 0, 0), (lambda x: len(x) > 1 and len(x) > 0, 2, 3), # input max element_count=3 (lambda x: len(x) < 1 and len(x) < 2, 0, 0), # Comparisons involving one literal and one variable (lambda x: 1 <= len(x) <= two, 1, 3), (lambda x: two <= len(x) <= 4, 0, 3), ], ids=get_pretty_function_description, ) @pytest.mark.parametrize( "strategy", [ st.lists(st.sampled_from([1, 2, 3]), unique=True), ], ids=get_pretty_function_description, ) @settings(max_examples=A_FEW) @given(data=st.data()) def test_filter_rewriting_lambda_len_unique_elements( data, strategy, predicate, start, end ): s = strategy.filter(predicate) unwrapped = unwrap_strategies(s) assert isinstance(unwrapped, FilteredStrategy) assert isinstance(unwrapped.filtered_strategy, type(unwrap_strategies(strategy))) for pred in unwrapped.flat_conditions: assert pred.__name__ == "<lambda>" assert unwrapped.filtered_strategy.min_size == start assert unwrapped.filtered_strategy.max_size == end value = data.draw(s) assert predicate(value) @pytest.mark.parametrize( "predicate", [ (lambda x: len(x) < 3), (lambda x: len(x) > 5), ], ids=get_pretty_function_description, ) def test_does_not_rewrite_unsatisfiable_len_filter(predicate): strategy = st.lists(st.none(), min_size=4, max_size=4).filter(predicate) with pytest.raises(Unsatisfiable): check_can_generate_examples(strategy) # Rewriting to nothing() would correctly express the constraint. However # we don't want _only rewritable strategies_ to work in e.g. one_of, so: assert not strategy.is_empty @pytest.mark.parametrize( "method", ["match", "search", "findall", "fullmatch", "finditer", "split"] ) @pytest.mark.parametrize( "strategy, pattern", [ (st.text(), "ab+c"), (st.text(), "a|b"), (st.text(alphabet="abcdef"), "ab+c"), (st.text(min_size=5, max_size=10), "ab+c"), (st.binary(), b"ab+c"), (st.binary(), b"a|b"), (st.binary(min_size=5, max_size=10), b"ab+c"), ], ids=repr, ) @settings(max_examples=A_FEW) @given(data=st.data()) def test_regex_filter_rewriting(data, strategy, pattern, method): # This would raise a HealthCheck without rewriting, so checking that # we can draw a valid value is sufficient. predicate = getattr(re.compile(pattern), method) s = strategy.filter(predicate) if method in ("finditer", "split"): msg = r"You applied re.compile\(.+?\).\w+ as a filter, but this allows" with pytest.warns(HypothesisWarning, match=msg): value = data.draw(s) else: value = data.draw(s) assert predicate(value) @fails_with(TypeError) @given(st.text().filter(re.compile("abc").sub)) def test_error_on_method_which_requires_multiple_args(_): pass def test_dates_filter_rewriting(): today = dt.date.today() assert st.dates().filter(partial(operator.lt, dt.date.max)).is_empty assert st.dates().filter(partial(operator.gt, dt.date.min)).is_empty assert st.dates(min_value=today).filter(partial(operator.gt, today)).is_empty assert st.dates(max_value=today).filter(partial(operator.lt, today)).is_empty bare = unwrap_strategies(st.dates()) assert bare.filter(partial(operator.ge, dt.date.max)) is bare assert bare.filter(partial(operator.le, dt.date.min)) is bare new = bare.filter(partial(operator.le, today)) assert not new.is_empty assert new is not bare @pytest.mark.skipif( sys.version_info[:2] < (3, 14), reason="functools.Placeholder is new in 3.14" ) def test_partial_placeholder(): from functools import Placeholder assert st.integers(0, 5).filter(partial(operator.gt, Placeholder, 5)).is_empty s = unwrap_strategies( st.integers(-5, 5).filter(partial(operator.lt, Placeholder, 3)) ) assert (s.start, s.end) == (-5, 2) s = unwrap_strategies( st.integers(-5, 5).filter(partial(operator.le, Placeholder, 3)) ) assert (s.start, s.end) == (-5, 3) s = unwrap_strategies( st.integers(-5, 5).filter(partial(operator.gt, Placeholder, 3)) ) assert (s.start, s.end) == (4, 5) s = unwrap_strategies( st.integers(-5, 5).filter(partial(operator.ge, Placeholder, 3)) ) assert (s.start, s.end) == (3, 5) s = unwrap_strategies( st.integers(-5, 5).filter(partial(operator.eq, Placeholder, 3)) ) assert (s.start, s.end) == (3, 3)
NotAFunction
python
wandb__wandb
tests/system_tests/test_core/test_torch_full.py
{ "start": 773, "end": 1108 }
class ____(nn.Module): def __init__(self, x=16, y=32): super().__init__() self.emb1 = nn.Embedding(x, y) self.emb2 = nn.Embedding(x, y) def forward(self, x): return { "key": { "emb1": self.emb1(x), "emb2": self.emb2(x), } }
EmbModel
python
falconry__falcon
examples/ws_tutorial/ws_tutorial/app.py
{ "start": 2159, "end": 2537 }
class ____: async def on_websocket(self, req: Request, ws: WebSocket): while True: try: message = await ws.receive_text() await ws.send_media( {'message': message, 'date': datetime.now().isoformat()} ) except WebSocketDisconnected: return
EchoWebSocketResource
python
python-excel__xlwt
tests/test_by_name_functions.py
{ "start": 31, "end": 868 }
class ____(unittest.TestCase): def setUp(self): self.wb = xlwt.Workbook() self.wb.add_sheet('Plan1') self.wb.add_sheet('Plan2') self.wb.add_sheet('Plan3') self.wb.add_sheet('Plan4') def test_sheet_index(self): 'Return sheet index by sheet name' idx = self.wb.sheet_index('Plan3') self.assertEqual(2, idx) def test_get_by_name(self): 'Get sheet by name' ws = self.wb.get_sheet('Plan2') self.assertEqual('Plan2', ws.name) def test_get_by_index(self): 'Get sheet by index' ws = self.wb.get_sheet(1) self.assertEqual('Plan2', ws.name) def test_invalid_sheet_parameter(self): 'Raises exception when sheet is not string or integer' self.assertRaises(Exception, self.wb.get_sheet, 1.1)
TestByName
python
sphinx-doc__sphinx
utils/bump_version.py
{ "start": 5106, "end": 6574 }
class ____(Exception): pass @contextmanager def processing(message: str) -> Iterator[None]: try: print(message + ' ... ', end='') yield except Skip as exc: print(f'skip: {exc}') except Exception: print('error') raise else: print('done') def parse_options(argv: Sequence[str]) -> tuple[VersionInfo, bool]: parser = argparse.ArgumentParser() parser.add_argument('version', help='A version number (cf. 1.6.0b0)') parser.add_argument('--in-develop', action='store_true') options = parser.parse_args(argv) return parse_version(options.version), options.in_develop def main() -> None: version, in_develop = parse_options(sys.argv[1:]) with processing('Rewriting sphinx/__init__.py'): bump_version(package_dir / 'sphinx' / '__init__.py', version, in_develop) with processing('Rewriting CHANGES'): changes = Changes(package_dir / 'CHANGES.rst') if changes.version_tuple == version.version_tuple: if changes.in_development and version.is_final and not in_develop: changes.finalise_release_date() else: reason = 'version not changed' raise Skip(reason) else: if changes.in_development: print(f'WARNING: last version is not released yet: {changes.version}') changes.add_release(version) if __name__ == '__main__': main()
Skip
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 735255, "end": 737665 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "commit", "commit_oid", "created_at", "creator", "database_id", "description", "environment", "latest_environment", "latest_status", "original_environment", "payload", "ref", "repository", "state", "statuses", "task", "updated_at", ) commit = sgqlc.types.Field(Commit, graphql_name="commit") commit_oid = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="commitOid" ) created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) creator = sgqlc.types.Field(sgqlc.types.non_null(Actor), graphql_name="creator") database_id = sgqlc.types.Field(Int, graphql_name="databaseId") description = sgqlc.types.Field(String, graphql_name="description") environment = sgqlc.types.Field(String, graphql_name="environment") latest_environment = sgqlc.types.Field(String, graphql_name="latestEnvironment") latest_status = sgqlc.types.Field("DeploymentStatus", graphql_name="latestStatus") original_environment = sgqlc.types.Field(String, graphql_name="originalEnvironment") payload = sgqlc.types.Field(String, graphql_name="payload") ref = sgqlc.types.Field("Ref", graphql_name="ref") repository = sgqlc.types.Field( sgqlc.types.non_null("Repository"), graphql_name="repository" ) state = sgqlc.types.Field(DeploymentState, graphql_name="state") statuses = sgqlc.types.Field( DeploymentStatusConnection, graphql_name="statuses", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) task = sgqlc.types.Field(String, graphql_name="task") updated_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="updatedAt" )
Deployment
python
google__pytype
pytype/tests/test_flow1.py
{ "start": 111, "end": 9320 }
class ____(test_base.BaseTest): """Tests for control flow. These tests primarily test instruction ordering and CFG traversal of the bytecode interpreter, i.e., their primary focus isn't the inferred types. Even though they check the validity of the latter, they're mostly smoke tests. """ def test_if(self): ty = self.Infer(""" if __random__: x = 3 else: x = 3.1 """) self.assertTypesMatchPytd( ty, """ from typing import Union x = ... # type: Union[int, float] """, ) def test_exception(self): ty = self.Infer( """ def f(): try: x = UndefinedName() except Exception: return 3 f() """, report_errors=False, ) self.assertTypesMatchPytd(ty, "def f() -> int | None: ...") def test_two_except_handlers(self): ty = self.Infer( """ def f(): try: x = UndefinedName() except Exception: return 3 except: return 3.5 f() """, report_errors=False, ) self.assertTypesMatchPytd(ty, "def f() -> int | float | None: ...") def test_nested_exceptions(self): ty = self.Infer( """ def f(): try: try: UndefinedName() except: return 3 except: return 3.5 f() """, report_errors=False, ) self.assertTypesMatchPytd(ty, "def f() -> int | float | None: ...") def test_raise(self): ty = self.Infer(""" def f(): try: try: raise # raises TypeError (exception not derived from BaseException) except: return 3 except: return 3.5 f() """) self.assertTypesMatchPytd(ty, "def f() -> int | float: ...") def test_finally(self): ty = self.Infer( """ def f(): try: x = RaiseANameError() finally: return 3 f() """, report_errors=False, ) self.assertTypesMatchPytd(ty, "def f() -> int: ...") def test_finally_suffix(self): ty = self.Infer( """ def f(): try: x = RaiseANameError() finally: x = 3 return x f() """, report_errors=False, ) self.assertTypesMatchPytd(ty, "def f() -> int: ...") def test_try_and_loop(self): ty = self.Infer(""" def f(): for s in (1, 2): try: try: pass except: continue finally: return 3 f() """) self.assertTypesMatchPytd(ty, "def f() -> int | None: ...") def test_simple_with(self): self.Check(""" def f(x): y = 1 with __any_object__: y = 2 return x assert_type(f(1), int) """) def test_nested_with(self): self.Check(""" def f(x): y = 1 with __any_object__: y = 2 with __any_object__: pass return x assert_type(f(1), int) """) def test_null_flow(self): ty = self.Infer(""" def f(x): if x is None: return 0 return len(x) f(__any_object__) """) self.assertTypesMatchPytd( ty, """ def f(x) -> int: ... """, ) def test_continue_in_with(self): ty = self.Infer(""" def f(): l = [] for i in range(3): with __any_object__: l.append(i) if i % 2: continue l.append(i) l.append(i) return l f() """) self.assertTypesMatchPytd(ty, "def f() -> list[int]: ...") def test_break_in_with(self): ty = self.Infer(""" def f(): l = [] for i in range(3): with __any_object__: l.append('w') if i % 2: break l.append('z') l.append('e') l.append('r') s = ''.join(l) return s f() """) self.assertTypesMatchPytd(ty, "def f() -> str: ...") def test_raise_in_with(self): ty = self.Infer(""" def f(): l = [] try: with __any_object__: l.append('w') raise ValueError("oops") l.append('z') l.append('e') except ValueError as e: assert str(e) == "oops" l.append('x') l.append('r') s = ''.join(l) return s f() """) self.assertTypesMatchPytd(ty, "def f() -> str: ...") def test_return_in_with(self): ty = self.Infer(""" def f(): with __any_object__: return "foo" f() """) self.assertTypesMatchPytd(ty, "def f() -> str: ...") def test_dead_if(self): self.Check(""" x = None if x is not None: x.foo() """) self.Check(""" x = 1 if x is not 1: x.foo() """) def test_return_after_loop(self): ty = self.Infer(""" def f(): x = g() return x def g(): while True: pass return 42 """) self.assertTypesMatchPytd( ty, """ from typing import Any def f() -> Any: ... def g() -> Any: ... """, ) def test_change_boolean(self): ty = self.Infer(""" def f(): b = True while b: b = False """) if self.python_version >= (3, 10): expected_return_type = "None" else: expected_return_type = "Any" self.assertTypesMatchPytd( ty, f""" from typing import Any def f() -> {expected_return_type}: ... """, ) def test_independent_calls(self): ty = self.Infer(""" class _Item: def __init__(self, stack): self.name = "foo" self.name_list = [s.name for s in stack] def foo(): stack = [] if __random__: stack.append(_Item(stack)) else: stack.append(_Item(stack)) """) self.assertTypesMatchPytd( ty, """ class _Item: name = ... # type: str name_list = ... # type: list def __init__(self, stack) -> None: ... def foo() -> None: ... """, ) def test_duplicate_getproperty(self): ty = self.Infer(""" class Foo: def __init__(self): self._node = __any_object__ def bar(self): if __random__: raise Exception( 'No node with type %s could be extracted.' % self._node) Foo().bar() """) self.assertTypesMatchPytd( ty, """ from typing import Any class Foo: _node = ... # type: Any def __init__(self) -> None: ... def bar(self) -> NoneType: ... """, ) def test_break(self): ty = self.Infer(""" def _foo(): while True: if __random__: break return 3j """) self.assertTypesMatchPytd( ty, """ def _foo() -> complex: ... """, ) def test_continue(self): ty = self.Infer(""" def bar(): while True: if __random__: return 3j continue return 3 # dead code """) self.assertTypesMatchPytd( ty, """ def bar() -> complex: ... """, ) def test_loop_over_list_of_lists(self): ty = self.Infer(""" for seq in [[1, 2, 3]]: seq.append("foo") """) self.assertTypesMatchPytd( ty, """ from typing import List, Union seq = ... # type: List[Union[int, str]] """, ) def test_call_undefined(self): errors = self.CheckWithErrors(""" def f(): try: func = None except: func() # name-error[e] """) self.assertErrorRegexes(errors, {"e": r"func"}) def test_nested_break(self): self.assertNoCrash( self.Infer, """ while True: try: pass except: break while True: try: pass except: break """, ) def test_nested_break2(self): self.assertNoCrash( self.Infer, """ while True: for x in []: pass break """, ) def test_loop_after_break(self): self.assertNoCrash( self.Infer, """ for _ in (): break else: raise for _ in (): break else: raise """, ) def test_recursion(self): ty = self.Infer(""" b = True def f(): if b: g() def g(): global b b = False f() """) self.assertTypesMatchPytd( ty, """ b = ... # type: bool def f() -> None: ... def g() -> None: ... """, ) def test_deleted(self): self.CheckWithErrors(""" def bar(y): return y*y def foo(x): del x y = x.y() # name-error return bar(y) """) if __name__ == "__main__": test_base.main()
FlowTest
python
django-haystack__django-haystack
test_haystack/test_query.py
{ "start": 35627, "end": 36829 }
class ____(TestCase): def setUp(self): super().setUp() self.esqs = EmptySearchQuerySet() def test_get_count(self): self.assertEqual(self.esqs.count(), 0) self.assertEqual(len(self.esqs.all()), 0) def test_filter(self): sqs = self.esqs.filter(content="foo") self.assertTrue(isinstance(sqs, EmptySearchQuerySet)) self.assertEqual(len(sqs), 0) def test_exclude(self): sqs = self.esqs.exclude(content="foo") self.assertTrue(isinstance(sqs, EmptySearchQuerySet)) self.assertEqual(len(sqs), 0) def test_slice(self): sqs = self.esqs.filter(content="foo") self.assertTrue(isinstance(sqs, EmptySearchQuerySet)) self.assertEqual(len(sqs), 0) self.assertEqual(sqs[:10], []) try: sqs[4] self.fail() except IndexError: pass def test_dictionary_lookup(self): """ Ensure doing a dictionary lookup raises a TypeError so EmptySearchQuerySets can be used in templates. """ self.assertRaises(TypeError, lambda: self.esqs["count"]) @override_settings(DEBUG=True)
EmptySearchQuerySetTestCase
python
h5py__h5py
h5py/tests/test_attrs_data.py
{ "start": 736, "end": 3693 }
class ____(BaseAttrs): """ Feature: Scalar types map correctly to array scalars """ def test_int(self): """ Integers are read as correct NumPy type """ name = make_name() self.f.attrs[name] = np.array(1, dtype=np.int8) out = self.f.attrs[name] self.assertIsInstance(out, np.int8) def test_compound(self): """ Compound scalars are read as numpy.void """ name = make_name() dt = np.dtype([('a', 'i'), ('b', 'f')]) data = np.array((1, 4.2), dtype=dt) self.f.attrs[name] = data out = self.f.attrs[name] self.assertIsInstance(out, np.void) self.assertEqual(out, data) self.assertEqual(out['b'], data['b']) def test_compound_with_vlen_fields(self): """ Compound scalars with vlen fields can be written and read """ name = make_name() dt = np.dtype([('a', h5py.vlen_dtype(np.int32)), ('b', h5py.vlen_dtype(np.int32))]) data = np.array((np.array(list(range(1, 5)), dtype=np.int32), np.array(list(range(8, 10)), dtype=np.int32)), dtype=dt)[()] self.f.attrs[name] = data out = self.f.attrs[name] # Specifying check_alignment=False because vlen fields have 8 bytes of padding # because the vlen datatype in hdf5 occupies 16 bytes self.assertArrayEqual(out, data, check_alignment=False) def test_nesting_compound_with_vlen_fields(self): """ Compound scalars with nested compound vlen fields can be written and read """ dt_inner = np.dtype([('a', h5py.vlen_dtype(np.int32)), ('b', h5py.vlen_dtype(np.int32))]) dt = np.dtype([('f1', h5py.vlen_dtype(dt_inner)), ('f2', np.int64)]) inner1 = (np.array(range(1, 3), dtype=np.int32), np.array(range(6, 9), dtype=np.int32)) inner2 = (np.array(range(10, 14), dtype=np.int32), np.array(range(16, 20), dtype=np.int32)) data = np.array((np.array([inner1, inner2], dtype=dt_inner), 2), dtype=dt)[()] name = make_name() self.f.attrs[name] = data out = self.f.attrs[name] self.assertArrayEqual(out, data, check_alignment=False) def test_vlen_compound_with_vlen_string(self): """ Compound scalars with vlen compounds containing vlen strings can be written and read """ dt_inner = np.dtype([('a', h5py.string_dtype()), ('b', h5py.string_dtype())]) dt = np.dtype([('f', h5py.vlen_dtype(dt_inner))]) name = make_name() data = np.array((np.array([(b"apples", b"bananas"), (b"peaches", b"oranges")], dtype=dt_inner),),dtype=dt)[()] self.f.attrs[name] = data out = self.f.attrs[name] self.assertArrayEqual(out, data, check_alignment=False)
TestScalar
python
catalyst-team__catalyst
tests/catalyst/callbacks/test_profiler.py
{ "start": 1475, "end": 4871 }
class ____(dl.IRunner): def __init__(self, logdir, device, tb_logs=None, chrome_logs=None, stack_logs=None): super().__init__() self._logdir = logdir self._device = device self.profiler_tb_logs = tb_logs self.chrome_trace_logs = chrome_logs self.stacks_logs = stack_logs self._export_stacks_kwargs = ( dict(path=self.stacks_logs) if self.stacks_logs is not None else None ) def get_engine(self): return dl.GPUEngine() def get_callbacks(self): return { "criterion": dl.CriterionCallback( metric_key="loss", input_key="logits", target_key="targets" ), "backward": dl.BackwardCallback(metric_key="loss"), "optimizer": dl.OptimizerCallback(metric_key="loss"), "profiler": ProfilerCallback( loader_key="train", epoch=1, profiler_kwargs=dict( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], with_stack=True, with_flops=True, ), tensorboard_path=self.profiler_tb_logs, export_chrome_trace_path=self.chrome_trace_logs, export_stacks_kwargs=self._export_stacks_kwargs, ), } @property def num_epochs(self) -> int: return 10 def get_loaders(self) -> "OrderedDict[str, DataLoader]": dataset = DummyDataset(6) loader = DataLoader(dataset, batch_size=4) return {"train": loader, "valid": loader} def get_model(self): return DummyModel(4, 2) def get_criterion(self): return torch.nn.MSELoss() def get_optimizer(self, model): return torch.optim.Adam(model.parameters()) def get_scheduler(self, optimizer): return None def get_loggers(self): loggers = { "console": dl.ConsoleLogger(), "csv": dl.CSVLogger(logdir=self._logdir), "tensorboard": dl.TensorboardLogger(logdir=self._logdir), } return loggers def handle_batch(self, batch): x, y = batch logits = self.model(x) self.batch = {"features": x, "targets": y, "logits": logits} def _run_custom_runner(device): with TemporaryDirectory() as tmp_dir: tb_logs = os.path.join(tmp_dir, "profiler_tb_logs") runner = CustomRunner(tmp_dir, device, tb_logs=tb_logs) runner.run() assert os.path.isdir(tb_logs) with TemporaryDirectory() as tmp_dir: chrome_logs = os.path.join(tmp_dir, "chrome_trace.json") runner = CustomRunner(tmp_dir, device, chrome_logs=chrome_logs) runner.run() assert os.path.isfile(chrome_logs) with TemporaryDirectory() as tmp_dir: stack_logs = os.path.join(tmp_dir, "flamegraph.txt") runner = CustomRunner(tmp_dir, device, stack_logs=stack_logs) runner.run() assert os.path.isfile(stack_logs) @pytest.mark.skipif( not HAS_REQUIRED_TORCH_VERSION, reason="Need PyTorch version higher than 1.8.1!" ) @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is not available!") def test_profiler_on_cuda(): _run_custom_runner("cuda:0")
CustomRunner
python
ipython__ipython
IPython/core/builtin_trap.py
{ "start": 442, "end": 3006 }
class ____(Configurable): shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) def __init__(self, shell=None): super(BuiltinTrap, self).__init__(shell=shell, config=None) self._orig_builtins = {} # We define this to track if a single BuiltinTrap is nested. # Only turn off the trap when the outermost call to __exit__ is made. self._nested_level = 0 self.shell = shell # builtins we always add - if set to HideBuiltin, they will just # be removed instead of being replaced by something else self.auto_builtins = {'exit': HideBuiltin, 'quit': HideBuiltin, 'get_ipython': self.shell.get_ipython, } def __enter__(self): if self._nested_level == 0: self.activate() self._nested_level += 1 # I return self, so callers can use add_builtin in a with clause. return self def __exit__(self, type, value, traceback): if self._nested_level == 1: self.deactivate() self._nested_level -= 1 # Returning False will cause exceptions to propagate return False def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = builtin_mod.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig del bdict[key] else: self._orig_builtins[key] = orig bdict[key] = value def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del builtin_mod.__dict__[key] else: builtin_mod.__dict__[key] = orig def activate(self): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin for name, func in self.auto_builtins.items(): add_builtin(name, func) def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.items(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
BuiltinTrap
python
google__pytype
pytype/tests/test_special_builtins2.py
{ "start": 93, "end": 1392 }
class ____(test_base.BaseTest): """Tests for special_builtins.py.""" def test_property_with_type_parameter(self): ty = self.Infer(""" from typing import Union class Foo: @property def foo(self) -> Union[str, int]: return __any_object__ """) self.assertTypesMatchPytd( ty, """ from typing import Annotated, Union class Foo: foo = ... # type: Annotated[Union[int, str], 'property'] """, ) def test_property_with_contained_type_parameter(self): ty = self.Infer(""" from typing import List, Union class Foo: @property def foo(self) -> List[Union[str, int]]: return __any_object__ """) self.assertTypesMatchPytd( ty, """ from typing import Annotated, List, Union class Foo: foo = ... # type: Annotated[List[Union[int, str]], 'property'] """, ) def test_callable_matching(self): self.Check(""" from typing import Any, Callable def f(x: Callable[[Any], bool]): pass f(callable) """) def test_filter_starargs(self): self.Check(""" def f(*args, **kwargs): filter(*args, **kwargs) """) if __name__ == "__main__": test_base.main()
SpecialBuiltinsTest
python
google__flatbuffers
python/flatbuffers/flexbuffers.py
{ "start": 11867, "end": 12596 }
class ____(Sized): """Data accessor for the encoded vector bytes.""" __slots__ = () def __getitem__(self, index): if index < 0 or index >= len(self): raise IndexError( 'vector index %s is out of [0, %d) range' % (index, len(self)) ) packed_type = self._buf[len(self) * self._byte_width + index] buf = self._buf.Slice(index * self._byte_width) return Ref.PackedType(buf, self._byte_width, packed_type) @property def Value(self): """Returns the underlying encoded data as a list object.""" return [e.Value for e in self] def __repr__(self): return 'Vector(%s, byte_width=%d, size=%d)' % ( self._buf, self._byte_width, self._size, )
Vector
python
getsentry__sentry
src/sentry/utils/marketo_client.py
{ "start": 220, "end": 540 }
class ____(Exception): def __init__(self, data: MarketoErrorResponse): # just use the first error error = data["errors"][0] self.code = error["code"] self.message = error["message"] def __str__(self) -> str: return f"MarketoError: {self.code} - {self.message}"
MarketoError
python
kamyu104__LeetCode-Solutions
Python/divide-an-array-into-subarrays-with-minimum-cost-ii.py
{ "start": 3851, "end": 4813 }
class ____(object): def minimumCost(self, nums, k, dist): """ :type nums: List[int] :type k: int :type dist: int :rtype: int """ sl1, sl2 = SortedList(), SortedList() mn, curr = float("inf"), 0 for i in xrange(1, len(nums)): sl1.add(nums[i]) curr += nums[i] if len(sl1) > k-1: curr -= sl1[-1] sl2.add(sl1.pop()) if len(sl1)+len(sl2) > 1+dist: if sl2[0] <= nums[i-(1+dist)]: sl2.remove(nums[i-(1+dist)]) else: sl1.remove(nums[i-(1+dist)]) curr -= nums[i-(1+dist)]-sl2[0] sl1.add(sl2.pop(0)) if len(sl1) == k-1: mn = min(mn, curr) return nums[0]+mn # Time: O(nlogd) # Space: O(d) from sortedcontainers import SortedList # sliding window, sorted list
Solution3
python
agronholm__apscheduler
src/apscheduler/triggers/cron/fields.py
{ "start": 3192, "end": 3432 }
class ____( BaseField, extra_compilers=(WeekdayPositionExpression, LastDayOfMonthExpression) ): __slots__ = () def get_max(self, dateval: datetime) -> int: return monthrange(dateval.year, dateval.month)[1]
DayOfMonthField
python
walkccc__LeetCode
solutions/2932. Maximum Strong Pair XOR I/2932.py
{ "start": 141, "end": 1516 }
class ____: def __init__(self, maxBit: int): self.maxBit = maxBit self.root = TrieNode() def insert(self, num: int) -> None: node = self.root for i in range(self.maxBit, -1, -1): bit = num >> i & 1 if not node.children[bit]: node.children[bit] = TrieNode() node = node.children[bit] node.mn = min(node.mn, num) node.mx = max(node.mx, num) def getMaxXor(self, x: int) -> int: """Returns max(x ^ y) where |x - y| <= min(x, y). If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. So, y <= 2 * x. """ maxXor = 0 node = self.root for i in range(self.maxBit, -1, -1): bit = x >> i & 1 toggleBit = bit ^ 1 # If `node.children[toggleBit].mx > x`, it means there's a number in the # node that satisfies the condition to ensure that x <= y among x and y. # If `node.children[toggleBit].mn <= 2 * x`, it means there's a number in # the node that satisfies the condition for a valid y. if (node.children[toggleBit] and node.children[toggleBit].mx > x and node.children[toggleBit].mn <= 2 * x): maxXor = maxXor | 1 << i node = node.children[toggleBit] elif node.children[bit]: node = node.children[bit] else: # There's nothing in the Bit Trie. return 0 return maxXor
BitTrie
python
rapidsai__cudf
python/cudf_polars/cudf_polars/containers/dataframe.py
{ "start": 2175, "end": 2218 }
class ____(Column): name: str
NamedColumn
python
google__jax
jax/_src/pallas/mosaic_gpu/core.py
{ "start": 18067, "end": 19450 }
class ____(state.AbstractRef): refs: Sequence[_GPUMemoryRefTree] def __init__( self, aval, refs: Sequence[_GPUMemoryRefTree], memory_space, ): self.refs = refs super().__init__(aval, memory_space=memory_space) def _iter(self, tracer): return iter(flatten_ref_union(tracer)) def _getitem(self, tracer, index): return list(iter(tracer))[index] def _setitem(self, tracer, index, value): del tracer, index, value # Unused. raise ValueError("Ref unions can't be assigned to.") def update(self, inner_aval=None, memory_space=None, kind=None): ref = super().update(inner_aval, memory_space, kind) return AbstractRefUnion(ref.inner_aval, self.refs, self.memory_space) @functools.cached_property def layout(self) -> tcgen05.TMEMLayout: if self.memory_space != TMEM: raise ValueError("layout attribute is only defined for TMEM refs") return tcgen05.tmem_default_layout(packing=1) @functools.cached_property def collective(self) -> bool: if self.memory_space != TMEM: raise ValueError("collective attribute is only defined for TMEM refs") ref_leaves = jax.tree.leaves(self.refs) first_ref = ref_leaves[0] assert all(ref.collective == first_ref.collective for ref in ref_leaves) return first_ref.collective @dataclasses.dataclass(init=False, frozen=True)
AbstractRefUnion
python
explosion__spaCy
spacy/lang/af/__init__.py
{ "start": 84, "end": 153 }
class ____(BaseDefaults): stop_words = STOP_WORDS
AfrikaansDefaults
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 163334, "end": 164899 }
class ____(TestCase): """Tests for ``windowed_complete()``""" def test_basic(self): actual = list(mi.windowed_complete([1, 2, 3, 4, 5], 3)) expected = [ ((), (1, 2, 3), (4, 5)), ((1,), (2, 3, 4), (5,)), ((1, 2), (3, 4, 5), ()), ] self.assertEqual(actual, expected) def test_zero_length(self): actual = list(mi.windowed_complete([1, 2, 3], 0)) expected = [ ((), (), (1, 2, 3)), ((1,), (), (2, 3)), ((1, 2), (), (3,)), ((1, 2, 3), (), ()), ] self.assertEqual(actual, expected) def test_wrong_length(self): seq = [1, 2, 3, 4, 5] for n in (-10, -1, len(seq) + 1, len(seq) + 10): with self.subTest(n=n): with self.assertRaises(ValueError): list(mi.windowed_complete(seq, n)) def test_every_partition(self): every_partition = lambda seq: chain( *map(partial(mi.windowed_complete, seq), range(len(seq))) ) seq = 'ABC' actual = list(every_partition(seq)) expected = [ ((), (), ('A', 'B', 'C')), (('A',), (), ('B', 'C')), (('A', 'B'), (), ('C',)), (('A', 'B', 'C'), (), ()), ((), ('A',), ('B', 'C')), (('A',), ('B',), ('C',)), (('A', 'B'), ('C',), ()), ((), ('A', 'B'), ('C',)), (('A',), ('B', 'C'), ()), ] self.assertEqual(actual, expected)
WindowedCompleteTests
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 7394, "end": 7494 }
class ____(SQLAlchemyError): """Raised when an error occurs during SQL compilation"""
CompileError
python
jina-ai__jina
tests/integration/hub_usage/dummyhub/__init__.py
{ "start": 53, "end": 185 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) foo()
DummyHubExecutor
python
fastai__fastai
fastai/torch_core.py
{ "start": 20417, "end": 20572 }
class ____(TensorBase): pass TensorBase.register_func(Tensor.__getitem__, TensorImageBase, TensorCategory) # %% ../nbs/00_torch_core.ipynb 121
TensorCategory
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 56417, "end": 62405 }
class ____(nn.Module): """ Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a [`OneFormerPixelDecoderEncoderLayer`]. The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers. Args: config: OneFormerConfig """ def __init__(self, config: OneFormerConfig): super().__init__() self.config = config self.dropout = config.dropout self.layers = nn.ModuleList([OneFormerPixelDecoderEncoderLayer(config) for _ in range(config.encoder_layers)]) @staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): """ Get reference points for each feature map. Used in decoder. Args: spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`): Spatial shapes of each feature map. valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`): Valid ratios of each feature map. device (`torch.device`): Device on which to create the tensors. Returns: `torch.FloatTensor` of shape `(batch_size, num_queries, num_feature_levels, 2)` """ reference_points_list = [] for lvl, (height, width) in enumerate(spatial_shapes): ref_y, ref_x = torch.meshgrid( torch.linspace(0.5, height - 0.5, height, dtype=valid_ratios.dtype, device=device), torch.linspace(0.5, width - 0.5, width, dtype=valid_ratios.dtype, device=device), ) ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * height) ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * width) ref = torch.stack((ref_x, ref_y), -1) reference_points_list.append(ref) reference_points = torch.cat(reference_points_list, 1) reference_points = reference_points[:, :, None] * valid_ratios[:, None] return reference_points def forward( self, inputs_embeds=None, attention_mask=None, position_embeddings=None, spatial_shapes=None, level_start_index=None, valid_ratios=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Flattened feature map (output of the backbone + projection layer) that is passed to the encoder. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`: - 1 for pixel features that are real (i.e. **not masked**), - 0 for pixel features that are padding (i.e. **masked**). [What are attention masks?](../glossary#attention-mask) position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Position embeddings that are added to the queries and keys in each self-attention layer. spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`): Spatial shapes of each feature map. level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`): Starting index of each feature map. valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`): Ratio of valid area in each feature level. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict hidden_states = inputs_embeds reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=inputs_embeds.device) encoder_states = () if output_hidden_states else None all_attentions = () if output_attentions else None for i, encoder_layer in enumerate(self.layers): if output_hidden_states: encoder_states = encoder_states + (hidden_states,) layer_outputs = encoder_layer( hidden_states, attention_mask, position_embeddings=position_embeddings, reference_points=reference_points, spatial_shapes=spatial_shapes, level_start_index=level_start_index, output_attentions=output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if output_hidden_states: encoder_states = encoder_states + (hidden_states,) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions ) # Modified from from transformers.models.mask2former.modeling_mask2former.Mask2FormerPixelDecoder with Mask2->One
OneFormerPixelDecoderEncoderOnly
python
scipy__scipy
scipy/optimize/_shgo.py
{ "start": 61586, "end": 63593 }
class ____: def __init__(self): self.cache = {} # Lists for search queries self.v_maps = [] self.xl_maps = [] self.xl_maps_set = set() self.f_maps = [] self.lbound_maps = [] self.size = 0 def __getitem__(self, v): try: v = np.ndarray.tolist(v) except TypeError: pass v = tuple(v) try: return self.cache[v] except KeyError: xval = LMap(v) self.cache[v] = xval return self.cache[v] def add_res(self, v, lres, bounds=None): v = np.ndarray.tolist(v) v = tuple(v) self.cache[v].x_l = lres.x self.cache[v].lres = lres self.cache[v].f_min = lres.fun self.cache[v].lbounds = bounds # Update cache size self.size += 1 # Cache lists for search queries self.v_maps.append(v) self.xl_maps.append(lres.x) self.xl_maps_set.add(tuple(lres.x)) self.f_maps.append(lres.fun) self.lbound_maps.append(bounds) def sort_cache_result(self): """ Sort results and build the global return object """ results = {} # Sort results and save self.xl_maps = np.array(self.xl_maps) self.f_maps = np.array(self.f_maps) # Sorted indexes in Func_min ind_sorted = np.argsort(self.f_maps) # Save ordered list of minima results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals self.f_maps = np.array(self.f_maps) results['funl'] = self.f_maps[ind_sorted] results['funl'] = results['funl'].T # Find global of all minimizers results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value self.xl_maps = np.ndarray.tolist(self.xl_maps) self.f_maps = np.ndarray.tolist(self.f_maps) return results
LMapCache
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 13648, "end": 17233 }
class ____(MimetypeRenderer): """ Renderer to display interactive figures using an IFrame. HTML representations of Figures are saved to an `iframe_figures/` directory and iframe HTML elements that reference these files are inserted into the notebook. With this approach, neither plotly.js nor the figure data are embedded in the notebook, so this is a good choice for notebooks that contain so many large figures that basic operations (like saving and opening) become very slow. Notebooks using this renderer will display properly when exported to HTML as long as the `iframe_figures/` directory is placed in the same directory as the exported html file. Note that the HTML files in `iframe_figures/` are numbered according to the IPython cell execution count and so they will start being overwritten each time the kernel is restarted. This directory may be deleted whenever the kernel is restarted and it will be automatically recreated. mime type: 'text/html' """ def __init__( self, config=None, auto_play=False, post_script=None, animation_opts=None, include_plotlyjs=True, html_directory="iframe_figures", ): self.config = config self.auto_play = auto_play self.post_script = post_script self.animation_opts = animation_opts self.include_plotlyjs = include_plotlyjs self.html_directory = html_directory def to_mimebundle(self, fig_dict): from plotly.io import write_html # Make iframe size slightly larger than figure size to avoid # having iframe have its own scroll bar. iframe_buffer = 20 layout = fig_dict.get("layout", {}) if layout.get("width", False): iframe_width = str(layout["width"] + iframe_buffer) + "px" else: iframe_width = "100%" if layout.get("height", False): iframe_height = layout["height"] + iframe_buffer else: iframe_height = str(525 + iframe_buffer) + "px" # Build filename using ipython cell number filename = self.build_filename() # Make directory for try: os.makedirs(self.html_directory) except OSError: if not isdir(self.html_directory): raise write_html( fig_dict, filename, config=self.config, auto_play=self.auto_play, include_plotlyjs=self.include_plotlyjs, include_mathjax="cdn", auto_open=False, post_script=self.post_script, animation_opts=self.animation_opts, default_width="100%", default_height=525, validate=False, ) # Build IFrame iframe_html = """\ <iframe scrolling="no" width="{width}" height="{height}" src="{src}" frameborder="0" allowfullscreen ></iframe> """.format(width=iframe_width, height=iframe_height, src=self.build_url(filename)) return {"text/html": iframe_html} def build_filename(self): ip = IPython.get_ipython() if IPython else None try: cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1 if ip else 0 except Exception: cell_number = 0 return "{dirname}/figure_{cell_number}.html".format( dirname=self.html_directory, cell_number=cell_number ) def build_url(self, filename): return filename
IFrameRenderer