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
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 25210, "end": 29118 }
class ____(ContinuousBase): """ A scale for date/time data. """ # TODO date: bool? # For when we only care about the time component, would affect # default formatter and norm conversion. Should also happen in # Property.default_scale. The alternative was having distinct # Calendric / Temporal scales, but that feels a bit fussy, and it # would get in the way of using first-letter shorthands because # Calendric and Continuous would collide. Still, we haven't implemented # those yet, and having a clear distinction betewen date(time) / time # may be more useful. trans = None _priority: ClassVar[int] = 2 def tick( self, locator: Locator | None = None, *, upto: int | None = None, ) -> Temporal: """ Configure the selection of ticks for the scale's axis or legend. .. note:: This API is under construction and will be enhanced over time. Parameters ---------- locator : :class:`matplotlib.ticker.Locator` subclass Pre-configured matplotlib locator; other parameters will not be used. upto : int Choose "nice" locations for ticks, but do not exceed this number. Returns ------- scale Copy of self with new tick configuration. """ if locator is not None and not isinstance(locator, Locator): err = ( f"Tick locator must be an instance of {Locator!r}, " f"not {type(locator)!r}." ) raise TypeError(err) new = copy(self) new._tick_params = {"locator": locator, "upto": upto} return new def label( self, formatter: Formatter | None = None, *, concise: bool = False, ) -> Temporal: """ Configure the appearance of tick labels for the scale's axis or legend. .. note:: This API is under construction and will be enhanced over time. Parameters ---------- formatter : :class:`matplotlib.ticker.Formatter` subclass Pre-configured formatter to use; other parameters will be ignored. concise : bool If True, use :class:`matplotlib.dates.ConciseDateFormatter` to make the tick labels as compact as possible. Returns ------- scale Copy of self with new label configuration. """ new = copy(self) new._label_params = {"formatter": formatter, "concise": concise} return new def _get_locators(self, locator, upto): if locator is not None: major_locator = locator elif upto is not None: major_locator = AutoDateLocator(minticks=2, maxticks=upto) else: major_locator = AutoDateLocator(minticks=2, maxticks=6) minor_locator = None return major_locator, minor_locator def _get_formatter(self, locator, formatter, concise): if formatter is not None: return formatter if concise: # TODO ideally we would have concise coordinate ticks, # but full semantic ticks. Is that possible? formatter = ConciseDateFormatter(locator) else: formatter = AutoDateFormatter(locator) return formatter # ----------------------------------------------------------------------------------- # # TODO Have this separate from Temporal or have Temporal(date=True) or similar? # class Calendric(Scale): # TODO Needed? Or handle this at layer (in stat or as param, eg binning=) # class Binned(Scale): # TODO any need for color-specific scales? # class Sequential(Continuous): # class Diverging(Continuous): # class Qualitative(Nominal): # ----------------------------------------------------------------------------------- #
Temporal
python
walkccc__LeetCode
solutions/2499. Minimum Total Cost to Make Arrays Unequal/2499.py
{ "start": 0, "end": 1357 }
class ____: def minimumTotalCost(self, nums1: list[int], nums2: list[int]) -> int: n = len(nums1) ans = 0 maxFreq = 0 maxFreqNum = 0 shouldBeSwapped = 0 conflictedNumCount = [0] * (n + 1) # Collect the indices i s.t. num1 == num2 and record their `maxFreq` # and `maxFreqNum`. for i, (num1, num2) in enumerate(zip(nums1, nums2)): if num1 == num2: conflictedNum = num1 conflictedNumCount[conflictedNum] += 1 if conflictedNumCount[conflictedNum] > maxFreq: maxFreq = conflictedNumCount[conflictedNum] maxFreqNum = conflictedNum shouldBeSwapped += 1 ans += i # Collect the indices with num1 != num2 that contribute less cost. # This can be greedily achieved by iterating from 0 to n - 1. for i, (num1, num2) in enumerate(zip(nums1, nums2)): # Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be # successfully distributed, so no need to collectextra spaces. if maxFreq * 2 <= shouldBeSwapped: break if num1 == num2: continue # The numbers == `maxFreqNum` worsen the result since they increase the # `maxFreq`. if num1 == maxFreqNum or num2 == maxFreqNum: continue shouldBeSwapped += 1 ans += i return -1 if maxFreq * 2 > shouldBeSwapped else ans
Solution
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/key_binding/key_bindings.py
{ "start": 20128, "end": 20933 }
class ____(_Proxy): """ Wrapper around a :class:`.KeyBindings` object that only exposes the global key bindings. """ def __init__(self, key_bindings: KeyBindingsBase) -> None: _Proxy.__init__(self) self.key_bindings = key_bindings def _update_cache(self) -> None: """ If one of the original registries was changed. Update our merged version. """ expected_version = self.key_bindings._version if self._last_version != expected_version: bindings2 = KeyBindings() for b in self.key_bindings.bindings: if b.is_global(): bindings2.bindings.append(b) self._bindings2 = bindings2 self._last_version = expected_version
GlobalOnlyKeyBindings
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/sort_by_all.py
{ "start": 56, "end": 122 }
class ____: pass def baz(): pass def qux(): pass
Bar
python
django__django
tests/prefetch_related/models.py
{ "start": 1261, "end": 1486 }
class ____(models.Model): author = models.ForeignKey( Author, models.CASCADE, to_field="name", related_name="addresses" ) address = models.TextField() class Meta: ordering = ["id"]
AuthorAddress
python
huggingface__transformers
src/transformers/models/gpt_neox/modular_gpt_neox.py
{ "start": 1521, "end": 5913 }
class ____(LlamaRotaryEmbedding): @staticmethod def compute_default_rope_parameters( config: Optional[GPTNeoXConfig] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0) head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads dim = int(head_dim * partial_rotary_factor) attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) # Keep half or full tensor for later concatenation rotary_dim = cos.shape[-1] q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:] k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:] # Apply rotary embeddings on the first half or full tensor q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin) k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin) # Concatenate back to full shape q_embed = torch.cat([q_embed, q_pass], dim=-1) k_embed = torch.cat([k_embed, k_pass], dim=-1) return q_embed, k_embed def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor, scaling: float, dropout: float = 0.0, **kwargs, ): attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) # Reshape outputs attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights
GPTNeoXRotaryEmbedding
python
realpython__materials
python-with-statement/redirect.py
{ "start": 13, "end": 482 }
class ____: def __init__(self, new_output): self.new_output = new_output def __enter__(self): self.std_output = sys.stdout sys.stdout = self.new_output def __exit__(self, *_): sys.stdout = self.std_output if __name__ == "__main__": with open("hello.txt", "w") as file: with StandardOutputRedirector(file): print("Hello, World!") print("Back to the standard output...")
StandardOutputRedirector
python
celery__celery
t/unit/utils/test_functional.py
{ "start": 977, "end": 2253 }
class ____: def test_AttributeError(self): assert firstmethod('foo')([object()]) is None def test_handles_lazy(self): class A: def __init__(self, value=None): self.value = value def m(self): return self.value assert 'four' == firstmethod('m')([ A(), A(), A(), A('four'), A('five')]) assert 'four' == firstmethod('m')([ A(), A(), A(), lazy(lambda: A('four')), A('five')]) def test_first(): iterations = [0] def predicate(value): iterations[0] += 1 if value == 5: return True return False assert first(predicate, range(10)) == 5 assert iterations[0] == 6 iterations[0] = 0 assert first(predicate, range(10, 20)) is None assert iterations[0] == 10 def test_lookahead(): assert list(lookahead(x for x in range(6))) == [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, None)] def test_maybe_list(): assert maybe_list(1) == [1] assert maybe_list([1]) == [1] assert maybe_list(None) is None def test_mlazy(): it = iter(range(20, 30)) p = mlazy(it.__next__) assert p() == 20 assert p.evaluated assert p() == 20 assert repr(p) == '20'
test_firstmethod
python
dask__dask
dask/dataframe/dask_expr/_indexing.py
{ "start": 1876, "end": 6483 }
class ____(Indexer): def __getitem__(self, key): if isinstance(key, tuple): if len(key) > self.obj.ndim: raise IndexingError("Too many indexers") iindexer = key[0] cindexer = key[1] pd_loc = self.obj._meta.loc[:, cindexer] if isinstance(pd_loc, pd.DataFrame): cindexer = list(pd_loc.columns) else: iindexer = key cindexer = None if isinstance(cindexer, np.generic): cindexer = cindexer.item() return self._loc(iindexer, cindexer) def _loc(self, iindexer, cindexer): if iindexer is None or isinstance(iindexer, slice) and iindexer == slice(None): if not isinstance(cindexer, Callable): return new_collection(Projection(self.obj, cindexer)) if isinstance(iindexer, Series): return self._loc_series(iindexer, cindexer) elif isinstance(iindexer, Array): return self._loc_array(iindexer, cindexer) elif callable(iindexer): return self._loc(iindexer(self.obj), cindexer) if self.obj.known_divisions: idx = self.obj.index._meta unit = idx.unit if hasattr(idx, "unit") else None iindexer = self._maybe_partial_time_string(iindexer, unit=unit) if isinstance(iindexer, slice): return self._loc_slice(iindexer, cindexer) elif is_series_like(iindexer) and not is_bool_dtype(iindexer.dtype): return new_collection(LocList(self.obj, iindexer.values, cindexer)) elif isinstance(iindexer, list) or is_arraylike(iindexer): if len(iindexer) == 0: return new_collection(LocEmpty(self.obj._meta, cindexer)) return new_collection(LocList(self.obj, iindexer, cindexer)) else: # element should raise KeyError return self._loc_element(iindexer, cindexer) else: if isinstance(iindexer, (list, np.ndarray)) or ( is_series_like(iindexer) and not is_bool_dtype(iindexer.dtype) ): # applying map_partitions to each partition # results in duplicated NaN rows msg = ( "Cannot index with list against unknown division. " "Try setting divisions using ``ddf.set_index``" ) raise KeyError(msg) elif not isinstance(iindexer, slice): iindexer = slice(iindexer, iindexer) return new_collection(LocUnknown(self.obj, iindexer, cindexer)) def _loc_series(self, iindexer, cindexer, check_alignment=True): if not is_bool_dtype(iindexer.dtype): raise KeyError( "Cannot index with non-boolean dask Series. Try passing computed " "values instead (e.g. ``ddf.loc[iindexer.compute()]``)" ) frame = self.obj.expr if cindexer is not None: frame = Projection(frame, cindexer) if check_alignment and not are_co_aligned(frame, iindexer.expr): return new_collection(LocAlign(frame, iindexer)) return new_collection(Loc(frame, iindexer)) def _loc_array(self, iindexer, cindexer): iindexer_series = from_dask_array(iindexer, columns="_", index=self.obj.index) return self._loc_series(iindexer_series, cindexer, check_alignment=False) def _maybe_partial_time_string(self, iindexer, unit): """ Convert index-indexer for partial time string slicing if obj.index is DatetimeIndex / PeriodIndex """ idx = meta_nonempty(self.obj._meta.index) iindexer = _maybe_partial_time_string(idx, iindexer, unit) return iindexer def _loc_slice(self, iindexer, cindexer): assert isinstance(iindexer, slice) if iindexer.step is not None and iindexer.step < 0: obj = ReverseDataFrame(self.obj) iindexer = slice(iindexer.start, iindexer.stop, -iindexer.step) else: obj = self.obj assert iindexer.step in (None, 1) return new_collection(LocSlice(obj, iindexer, cindexer)) def _loc_element(self, iindexer, cindexer): if iindexer < self.obj.divisions[0] or iindexer > self.obj.divisions[-1]: raise KeyError(f"the label [{iindexer}] is not in the index") return new_collection(LocElement(self.obj, iindexer, cindexer)) def _reverse_partition(df): return df.loc[::-1]
LocIndexer
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 490, "end": 811 }
class ____(ValueError): def __init__(self, errors: list[GreatExpectationsError]) -> None: self._errors = errors super().__init__("\n\t" + "\n\t".join(str(e) for e in errors)) @property def errors(self) -> list[GreatExpectationsError]: return self._errors
GreatExpectationsAggregateError
python
pytest-dev__pytest
doc/en/example/fixtures/test_fixtures_order_autouse_multiple_scopes.py
{ "start": 343, "end": 453 }
class ____: def test_order(self, order, c1, c3): assert order == ["c1", "c3"]
TestClassWithC1Request
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/sitemap/base.py
{ "start": 254, "end": 1890 }
class ____(BaseReader): """ Asynchronous sitemap reader for web. Reads pages from the web based on their sitemap.xml. Args: sitemap_url (string): Path to the sitemap.xml. e.g. https://gpt-index.readthedocs.io/sitemap.xml html_to_text (bool): Whether to convert HTML to text. Requires `html2text` package. limit (int): Maximum number of concurrent requests. """ xml_schema_sitemap = "http://www.sitemaps.org/schemas/sitemap/0.9" def __init__(self, html_to_text: bool = False, limit: int = 10) -> None: """Initialize with parameters.""" self._async_loader = AsyncWebPageReader(html_to_text=html_to_text, limit=limit) self._html_to_text = html_to_text self._limit = limit def _load_sitemap(self, sitemap_url: str) -> str: sitemap_url_request = httpx.get(sitemap_url) return sitemap_url_request.content def _parse_sitemap(self, raw_sitemap: str, filter_locs: str = None) -> list: sitemap = fromstring(raw_sitemap) sitemap_urls = [] for url in sitemap.findall(f"{{{self.xml_schema_sitemap}}}url"): location = url.find(f"{{{self.xml_schema_sitemap}}}loc").text if filter_locs is None or filter_locs in location: sitemap_urls.append(location) return sitemap_urls def load_data(self, sitemap_url: str, filter: str = None) -> List[Document]: sitemap = self._load_sitemap(sitemap_url=sitemap_url) sitemap_urls = self._parse_sitemap(sitemap, filter) return self._async_loader.load_data(urls=sitemap_urls)
SitemapReader
python
scipy__scipy
scipy/cluster/tests/test_hierarchy.py
{ "start": 32985, "end": 33963 }
class ____: def test_maxdists_empty_linkage(self, xp): # Tests maxdists(Z) on empty linkage. Expecting exception. Z = xp.zeros((0, 4), dtype=xp.float64) assert_raises(ValueError, maxdists, Z) def test_maxdists_one_cluster_linkage(self, xp): # Tests maxdists(Z) on linkage with one cluster. Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64) MD = maxdists(Z) expectedMD = calculate_maximum_distances(Z, xp) xp_assert_close(MD, expectedMD, atol=1e-15) @pytest.mark.parametrize( "method", ['single', 'complete', 'ward', 'centroid', 'median']) def test_maxdists_Q_linkage(self, method, xp): # Tests maxdists(Z) on the Q data set X = hierarchy_test_data.Q_X Z = xp.asarray(linkage(X, method)) MD = maxdists(Z) expectedMD = calculate_maximum_distances(Z, xp) xp_assert_close(MD, expectedMD, atol=1e-15) @make_xp_test_case(maxinconsts)
TestMaxDists
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_getlimits.py
{ "start": 4106, "end": 4919 }
class ____(TestCase): def test_iinfo_repr(self): expected = "iinfo(min=-32768, max=32767, dtype=int16)" assert_equal(repr(np.iinfo(np.int16)), expected) @skipIf(TEST_WITH_TORCHDYNAMO, reason="repr differs") def test_finfo_repr(self): repr_f32 = repr(np.finfo(np.float32)) assert "finfo(resolution=1e-06, min=-3.40282e+38," in repr_f32 assert "dtype=float32" in repr_f32 def assert_ma_equal(discovered, ma_like): # Check MachAr-like objects same as calculated MachAr instances for key, value in discovered.__dict__.items(): assert_equal(value, getattr(ma_like, key)) if hasattr(value, "shape"): assert_equal(value.shape, getattr(ma_like, key).shape) assert_equal(value.dtype, getattr(ma_like, key).dtype)
TestRepr
python
arrow-py__arrow
arrow/locales.py
{ "start": 138896, "end": 143130 }
class ____(Locale): names = ["am", "am-et"] past = "{0} α‰ αŠα‰΅" future = "{0} α‹αˆ΅αŒ₯" and_word = "αŠ₯αŠ“" timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[Mapping[str, str], str]]] = { "now": "αŠ αˆαŠ•", "second": { "past": "αŠ¨αŠ αŠ•α‹΅ αˆ°αŠ¨αŠ•α‹΅", "future": "α‰ αŠ αŠ•α‹΅ αˆ°αŠ¨αŠ•α‹΅", }, "seconds": { "past": "ከ {0} αˆ°αŠ¨αŠ•α‹΅", "future": "α‰  {0} αˆ°αŠ¨αŠ•α‹΅", }, "minute": { "past": "αŠ¨αŠ αŠ•α‹΅ ደቂቃ", "future": "α‰ αŠ αŠ•α‹΅ ደቂቃ", }, "minutes": { "past": "ከ {0} α‹°α‰‚α‰ƒα‹Žα‰½", "future": "α‰  {0} α‹°α‰‚α‰ƒα‹Žα‰½", }, "hour": { "past": "αŠ¨αŠ αŠ•α‹΅ αˆ°α‹“α‰΅", "future": "α‰ αŠ αŠ•α‹΅ αˆ°α‹“α‰΅", }, "hours": { "past": "ከ {0} αˆ°α‹“α‰³α‰΅", "future": "α‰  {0} αˆ°αŠ¨αŠ•α‹΅", }, "day": { "past": "αŠ¨αŠ αŠ•α‹΅ α‰€αŠ•", "future": "α‰ αŠ αŠ•α‹΅ α‰€αŠ•", }, "days": { "past": "ከ {0} α‰€αŠ“α‰΅", "future": "α‰  {0} α‰€αŠ“α‰΅", }, "week": { "past": "αŠ¨αŠ αŠ•α‹΅ αˆ³αˆαŠ•α‰΅", "future": "α‰ αŠ αŠ•α‹΅ αˆ³αˆαŠ•α‰΅", }, "weeks": { "past": "ከ {0} αˆ³αˆαŠ•α‰³α‰΅", "future": "α‰  {0} αˆ³αˆαŠ•α‰³α‰΅", }, "month": { "past": "αŠ¨αŠ αŠ•α‹΅ α‹ˆαˆ­", "future": "α‰ αŠ αŠ•α‹΅ α‹ˆαˆ­", }, "months": { "past": "ከ {0} α‹ˆαˆ­", "future": "α‰  {0} α‹ˆαˆ«α‰΅", }, "year": { "past": "αŠ¨αŠ αŠ•α‹΅ αŠ αˆ˜α‰΅", "future": "α‰ αŠ αŠ•α‹΅ αŠ αˆ˜α‰΅", }, "years": { "past": "ከ {0} α‹“αˆ˜α‰³α‰΅", "future": "α‰  {0} α‹“αˆ˜α‰³α‰΅", }, } # Amharic: the general format to describe timeframe is different from past and future, # so we do not copy the original timeframes dictionary timeframes_only_distance = { "second": "αŠ αŠ•α‹΅ αˆ°αŠ¨αŠ•α‹΅", "seconds": "{0} αˆ°αŠ¨αŠ•α‹΅", "minute": "αŠ αŠ•α‹΅ ደቂቃ", "minutes": "{0} α‹°α‰‚α‰ƒα‹Žα‰½", "hour": "αŠ αŠ•α‹΅ αˆ°α‹“α‰΅", "hours": "{0} αˆ°α‹“α‰΅", "day": "αŠ αŠ•α‹΅ α‰€αŠ•", "days": "{0} α‰€αŠ“α‰΅", "week": "αŠ αŠ•α‹΅ αˆ³αˆαŠ•α‰΅", "weeks": "{0} αˆ³αˆαŠ•α‰΅", "month": "αŠ αŠ•α‹΅ α‹ˆαˆ­", "months": "{0} α‹ˆαˆ«α‰΅", "year": "αŠ αŠ•α‹΅ αŠ αˆ˜α‰΅", "years": "{0} α‹“αˆ˜α‰³α‰΅", } month_names = [ "", "αŒƒαŠ•α‹©α‹ˆαˆͺ", "ፌα‰₯αˆ©α‹ˆαˆͺ", "αˆ›αˆ­α‰½", "αŠ€α•αˆͺል", "αˆœα‹­", "αŒαŠ•", "αŒαˆ‹α‹­", "αŠ¦αŒˆαˆ΅α‰΅", "αˆ΄α•α‰΄αˆα‰ αˆ­", "αŠ¦αŠ­α‰Άα‰ αˆ­", "αŠ–α‰¬αˆα‰ αˆ­", "α‹²αˆ΄αˆα‰ αˆ­", ] month_abbreviations = [ "", "αŒƒαŠ•α‹©", "ፌα‰₯ሩ", "αˆ›αˆ­α‰½", "αŠ€α•αˆͺ", "αˆœα‹­", "αŒαŠ•", "αŒαˆ‹α‹­", "ኦገሡ", "αˆ΄α•α‰΄", "αŠ¦αŠ­α‰Ά", "αŠ–α‰¬αˆ", "α‹²αˆ΄αˆ", ] day_names = [ "", "ሰኞ", "αˆ›αŠ­αˆ°αŠž", "αˆ¨α‰‘α‹•", "αˆαˆ™αˆ΅", "α‹“αˆ­α‰₯", "α‰…α‹³αˆœ", "αŠ₯αˆ‘α‹΅", ] day_abbreviations = ["", "αŠ₯", "ሰ", "αˆ›", "ረ", "ሐ", "α‹“", "α‰…"] def _ordinal_number(self, n: int) -> str: return f"{n}αŠ›" def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: """ Amharic awares time frame format function, takes into account the differences between general, past, and future forms (three different suffixes). """ abs_delta = abs(delta) form = self.timeframes[timeframe] if isinstance(form, str): return form.format(abs_delta) if delta > 0: key = "future" else: key = "past" form = form[key] return form.format(abs_delta) def describe( self, timeframe: TimeFrameLiteral, delta: Union[float, int] = 1, # key is always future when only_distance=False only_distance: bool = False, ) -> str: """Describes a delta within a timeframe in plain language. :param timeframe: a string representing a timeframe. :param delta: a quantity representing a delta in a timeframe. :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords """ if not only_distance: return super().describe(timeframe, delta, only_distance) humanized = self.timeframes_only_distance[timeframe].format(trunc(abs(delta))) return humanized
AmharicLocale
python
pytorch__pytorch
test/test_weak.py
{ "start": 489, "end": 7946 }
class ____(TestCase): COUNT = 10 def test_make_weak_keyed_dict_from_dict(self): o = torch.randn(2) dict = WeakIdKeyDictionary({o: 364}) self.assertEqual(dict[o], 364) def test_make_weak_keyed_dict_from_weak_keyed_dict(self): o = torch.randn(3) dict = WeakIdKeyDictionary({o: 364}) self.assertEqual(dict[o], 364) dict2 = WeakIdKeyDictionary(dict) self.assertEqual(dict2[o], 364) def check_popitem(self, klass, key1, value1, key2, value2): weakdict = klass() weakdict[key1] = value1 weakdict[key2] = value2 self.assertEqual(len(weakdict), 2) k, v = weakdict.popitem() self.assertEqual(len(weakdict), 1) if k is key1: self.assertIs(v, value1) else: self.assertIs(v, value2) k, v = weakdict.popitem() self.assertEqual(len(weakdict), 0) if k is key1: self.assertIs(v, value1) else: self.assertIs(v, value2) def test_weak_keyed_dict_popitem(self): self.check_popitem(WeakIdKeyDictionary, C(), "value 1", C(), "value 2") def check_setdefault(self, klass, key, value1, value2): self.assertIsNot( value1, value2, "invalid test -- value parameters must be distinct objects", ) weakdict = klass() o = weakdict.setdefault(key, value1) self.assertIs(o, value1) self.assertIn(key, weakdict) self.assertIs(weakdict.get(key), value1) self.assertIs(weakdict[key], value1) o = weakdict.setdefault(key, value2) self.assertIs(o, value1) self.assertIn(key, weakdict) self.assertIs(weakdict.get(key), value1) self.assertIs(weakdict[key], value1) def test_weak_keyed_dict_setdefault(self): self.check_setdefault(WeakIdKeyDictionary, C(), "value 1", "value 2") def check_update(self, klass, dict): # # This exercises d.update(), len(d), d.keys(), k in d, # d.get(), d[]. # weakdict = klass() weakdict.update(dict) self.assertEqual(len(weakdict), len(dict)) for k in weakdict: self.assertIn(k, dict, "mysterious new key appeared in weak dict") v = dict.get(k) self.assertIs(v, weakdict[k]) self.assertIs(v, weakdict.get(k)) for k in dict: self.assertIn(k, weakdict, "original key disappeared in weak dict") v = dict[k] self.assertIs(v, weakdict[k]) self.assertIs(v, weakdict.get(k)) def test_weak_keyed_dict_update(self): self.check_update(WeakIdKeyDictionary, {C(): 1, C(): 2, C(): 3}) def test_weak_keyed_delitem(self): d = WeakIdKeyDictionary() o1 = torch.randn(1) o2 = torch.randn(2) d[o1] = "something" d[o2] = "something" self.assertEqual(len(d), 2) del d[o1] self.assertEqual(len(d), 1) self.assertEqual(list(d.keys()), [o2]) def test_weak_keyed_union_operators(self): try: {} | {} except TypeError: self.skipTest("dict union not supported in this Python") o1 = C() o2 = C() o3 = C() wkd1 = WeakIdKeyDictionary({o1: 1, o2: 2}) wkd2 = WeakIdKeyDictionary({o3: 3, o1: 4}) wkd3 = wkd1.copy() d1 = {o2: "5", o3: "6"} pairs = [(o2, 7), (o3, 8)] tmp1 = wkd1 | wkd2 # Between two WeakKeyDictionaries self.assertEqual(dict(tmp1), dict(wkd1) | dict(wkd2)) self.assertIs(type(tmp1), WeakIdKeyDictionary) wkd1 |= wkd2 self.assertEqual(wkd1, tmp1) tmp2 = wkd2 | d1 # Between WeakKeyDictionary and mapping self.assertEqual(dict(tmp2), dict(wkd2) | d1) self.assertIs(type(tmp2), WeakIdKeyDictionary) wkd2 |= d1 self.assertEqual(wkd2, tmp2) tmp3 = wkd3.copy() # Between WeakKeyDictionary and iterable key, value tmp3 |= pairs self.assertEqual(dict(tmp3), dict(wkd3) | dict(pairs)) self.assertIs(type(tmp3), WeakIdKeyDictionary) tmp4 = d1 | wkd3 # Testing .__ror__ self.assertEqual(dict(tmp4), d1 | dict(wkd3)) self.assertIs(type(tmp4), WeakIdKeyDictionary) del o1 self.assertNotIn(4, tmp1.values()) self.assertNotIn(4, tmp2.values()) self.assertNotIn(1, tmp3.values()) self.assertNotIn(1, tmp4.values()) def test_weak_keyed_bad_delitem(self): d = WeakIdKeyDictionary() o = torch.randn(1) # An attempt to delete an object that isn't there should raise # KeyError. It didn't before 2.3. self.assertRaises(KeyError, d.__delitem__, o) self.assertRaises(KeyError, d.__getitem__, o) # If a key isn't of a weakly referenceable type, __getitem__ and # __setitem__ raise TypeError. __delitem__ should too. self.assertRaises(TypeError, d.__delitem__, 13) self.assertRaises(TypeError, d.__getitem__, 13) self.assertRaises(TypeError, d.__setitem__, 13, 13) def test_make_weak_keyed_dict_repr(self): dict = WeakIdKeyDictionary() self.assertRegex(repr(dict), "<WeakIdKeyDictionary at 0x.*>") def check_threaded_weak_dict_copy(self, type_, deepcopy): # `deepcopy` should be either True or False. exc = [] # Cannot give these slots as weakrefs weren't supported # on these objects until later versions of Python class DummyKey: # noqa: B903 def __init__(self, ctr): self.ctr = ctr class DummyValue: # noqa: B903 def __init__(self, ctr): self.ctr = ctr def dict_copy(d, exc): try: if deepcopy is True: _ = copy.deepcopy(d) else: _ = d.copy() except Exception as ex: exc.append(ex) def pop_and_collect(lst): gc_ctr = 0 while lst: i = random.randint(0, len(lst) - 1) gc_ctr += 1 lst.pop(i) if gc_ctr % 10000 == 0: gc.collect() # just in case d = type_() keys = [] values = [] # Initialize d with many entries for i in range(70000): k, v = DummyKey(i), DummyValue(i) keys.append(k) values.append(v) d[k] = v del k del v t_copy = threading.Thread(target=dict_copy, args=(d, exc)) t_collect = threading.Thread(target=pop_and_collect, args=(keys,)) t_copy.start() t_collect.start() t_copy.join() t_collect.join() # Test exceptions if exc: raise exc[0] def test_threaded_weak_key_dict_copy(self): # Issue #35615: Weakref keys or values getting GC'ed during dict # copying should not result in a crash. self.check_threaded_weak_dict_copy(WeakIdKeyDictionary, False) def test_threaded_weak_key_dict_deepcopy(self): # Issue #35615: Weakref keys or values getting GC'ed during dict # copying should not result in a crash. self.check_threaded_weak_dict_copy(WeakIdKeyDictionary, True) # Adapted from cpython/Lib/test/mapping_tests.py
WeakTest
python
django__django
tests/template_tests/filter_tests/test_date.py
{ "start": 245, "end": 2869 }
class ____(TimezoneTestCase): @setup({"date01": '{{ d|date:"m" }}'}) def test_date01(self): output = self.engine.render_to_string("date01", {"d": datetime(2008, 1, 1)}) self.assertEqual(output, "01") @setup({"date02": "{{ d|date }}"}) def test_date02(self): output = self.engine.render_to_string("date02", {"d": datetime(2008, 1, 1)}) self.assertEqual(output, "Jan. 1, 2008") @setup({"date02_l10n": "{{ d|date }}"}) def test_date02_l10n(self): """Without arg, the active language's DATE_FORMAT is used.""" with translation.override("fr"): output = self.engine.render_to_string( "date02_l10n", {"d": datetime(2008, 1, 1)} ) self.assertEqual(output, "1 janvier 2008") @setup({"date03": '{{ d|date:"m" }}'}) def test_date03(self): """ #9520: Make sure |date doesn't blow up on non-dates """ output = self.engine.render_to_string("date03", {"d": "fail_string"}) self.assertEqual(output, "") # ISO date formats @setup({"date04": '{{ d|date:"o" }}'}) def test_date04(self): output = self.engine.render_to_string("date04", {"d": datetime(2008, 12, 29)}) self.assertEqual(output, "2009") @setup({"date05": '{{ d|date:"o" }}'}) def test_date05(self): output = self.engine.render_to_string("date05", {"d": datetime(2010, 1, 3)}) self.assertEqual(output, "2009") # Timezone name @setup({"date06": '{{ d|date:"e" }}'}) def test_date06(self): output = self.engine.render_to_string( "date06", {"d": datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))}, ) self.assertEqual(output, "+0030") @setup({"date07": '{{ d|date:"e" }}'}) def test_date07(self): output = self.engine.render_to_string("date07", {"d": datetime(2009, 3, 12)}) self.assertEqual(output, "") # #19370: Make sure |date doesn't blow up on a midnight time object @setup({"date08": '{{ t|date:"H:i" }}'}) def test_date08(self): output = self.engine.render_to_string("date08", {"t": time(0, 1)}) self.assertEqual(output, "00:01") @setup({"date09": '{{ t|date:"H:i" }}'}) def test_date09(self): output = self.engine.render_to_string("date09", {"t": time(0, 0)}) self.assertEqual(output, "00:00") @setup({"datelazy": '{{ t|date:_("H:i") }}'}) def test_date_lazy(self): output = self.engine.render_to_string("datelazy", {"t": time(0, 0)}) self.assertEqual(output, "00:00")
DateTests
python
wandb__wandb
wandb/vendor/pygments/lexers/basic.py
{ "start": 8034, "end": 12933 }
class ____(RegexLexer): """ For `Monkey <https://en.wikipedia.org/wiki/Monkey_(programming_language)>`_ source code. .. versionadded:: 1.6 """ name = 'Monkey' aliases = ['monkey'] filenames = ['*.monkey'] mimetypes = ['text/x-monkey'] name_variable = r'[a-z_]\w*' name_function = r'[A-Z]\w*' name_constant = r'[A-Z_][A-Z0-9_]*' name_class = r'[A-Z]\w*' name_module = r'[a-z0-9_]*' keyword_type = r'(?:Int|Float|String|Bool|Object|Array|Void)' # ? == Bool // % == Int // # == Float // $ == String keyword_type_special = r'[?%#$]' flags = re.MULTILINE tokens = { 'root': [ # Text (r'\s+', Text), # Comments (r"'.*", Comment), (r'(?i)^#rem\b', Comment.Multiline, 'comment'), # preprocessor directives (r'(?i)^(?:#If|#ElseIf|#Else|#EndIf|#End|#Print|#Error)\b', Comment.Preproc), # preprocessor variable (any line starting with '#' that is not a directive) (r'^#', Comment.Preproc, 'variables'), # String ('"', String.Double, 'string'), # Numbers (r'[0-9]+\.[0-9]*(?!\.)', Number.Float), (r'\.[0-9]+(?!\.)', Number.Float), (r'[0-9]+', Number.Integer), (r'\$[0-9a-fA-Z]+', Number.Hex), (r'\%[10]+', Number.Bin), # Native data types (r'\b%s\b' % keyword_type, Keyword.Type), # Exception handling (r'(?i)\b(?:Try|Catch|Throw)\b', Keyword.Reserved), (r'Throwable', Name.Exception), # Builtins (r'(?i)\b(?:Null|True|False)\b', Name.Builtin), (r'(?i)\b(?:Self|Super)\b', Name.Builtin.Pseudo), (r'\b(?:HOST|LANG|TARGET|CONFIG)\b', Name.Constant), # Keywords (r'(?i)^(Import)(\s+)(.*)(\n)', bygroups(Keyword.Namespace, Text, Name.Namespace, Text)), (r'(?i)^Strict\b.*\n', Keyword.Reserved), (r'(?i)(Const|Local|Global|Field)(\s+)', bygroups(Keyword.Declaration, Text), 'variables'), (r'(?i)(New|Class|Interface|Extends|Implements)(\s+)', bygroups(Keyword.Reserved, Text), 'classname'), (r'(?i)(Function|Method)(\s+)', bygroups(Keyword.Reserved, Text), 'funcname'), (r'(?i)(?:End|Return|Public|Private|Extern|Property|' r'Final|Abstract)\b', Keyword.Reserved), # Flow Control stuff (r'(?i)(?:If|Then|Else|ElseIf|EndIf|' r'Select|Case|Default|' r'While|Wend|' r'Repeat|Until|Forever|' r'For|To|Until|Step|EachIn|Next|' r'Exit|Continue)\s+', Keyword.Reserved), # not used yet (r'(?i)\b(?:Module|Inline)\b', Keyword.Reserved), # Array (r'[\[\]]', Punctuation), # Other (r'<=|>=|<>|\*=|/=|\+=|-=|&=|~=|\|=|[-&*/^+=<>|~]', Operator), (r'(?i)(?:Not|Mod|Shl|Shr|And|Or)', Operator.Word), (r'[(){}!#,.:]', Punctuation), # catch the rest (r'%s\b' % name_constant, Name.Constant), (r'%s\b' % name_function, Name.Function), (r'%s\b' % name_variable, Name.Variable), ], 'funcname': [ (r'(?i)%s\b' % name_function, Name.Function), (r':', Punctuation, 'classname'), (r'\s+', Text), (r'\(', Punctuation, 'variables'), (r'\)', Punctuation, '#pop') ], 'classname': [ (r'%s\.' % name_module, Name.Namespace), (r'%s\b' % keyword_type, Keyword.Type), (r'%s\b' % name_class, Name.Class), # array (of given size) (r'(\[)(\s*)(\d*)(\s*)(\])', bygroups(Punctuation, Text, Number.Integer, Text, Punctuation)), # generics (r'\s+(?!<)', Text, '#pop'), (r'<', Punctuation, '#push'), (r'>', Punctuation, '#pop'), (r'\n', Text, '#pop'), default('#pop') ], 'variables': [ (r'%s\b' % name_constant, Name.Constant), (r'%s\b' % name_variable, Name.Variable), (r'%s' % keyword_type_special, Keyword.Type), (r'\s+', Text), (r':', Punctuation, 'classname'), (r',', Punctuation, '#push'), default('#pop') ], 'string': [ (r'[^"~]+', String.Double), (r'~q|~n|~r|~t|~z|~~', String.Escape), (r'"', String.Double, '#pop'), ], 'comment': [ (r'(?i)^#rem.*?', Comment.Multiline, "#push"), (r'(?i)^#end.*?', Comment.Multiline, "#pop"), (r'\n', Comment.Multiline), (r'.+', Comment.Multiline), ], }
MonkeyLexer
python
pola-rs__polars
py-polars/src/polars/io/iceberg/dataset.py
{ "start": 782, "end": 17813 }
class ____: """Dataset interface for PyIceberg.""" def __init__( self, source: str | Table, *, snapshot_id: int | None = None, iceberg_storage_properties: dict[str, Any] | None = None, reader_override: Literal["native", "pyiceberg"] | None = None, use_metadata_statistics: bool = True, fast_deletion_count: bool = True, use_pyiceberg_filter: bool = True, ) -> None: self._metadata_path = None self._table = None self._snapshot_id = snapshot_id self._iceberg_storage_properties = iceberg_storage_properties self._reader_override: Literal["native", "pyiceberg"] | None = reader_override self._use_metadata_statistics = use_metadata_statistics self._fast_deletion_count = fast_deletion_count self._use_pyiceberg_filter = use_pyiceberg_filter # Accept either a path or a table object. The one we don't have is # lazily initialized when needed. if isinstance(source, str): self._metadata_path = source else: self._table = source # # PythonDatasetProvider interface functions # def schema(self) -> pa.schema: """Fetch the schema of the table.""" return self.arrow_schema() def arrow_schema(self) -> pa.schema: """Fetch the arrow schema of the table.""" from pyiceberg.io.pyarrow import schema_to_pyarrow return schema_to_pyarrow(self.table().schema()) def to_dataset_scan( self, *, existing_resolved_version_key: str | None = None, limit: int | None = None, projection: list[str] | None = None, filter_columns: list[str] | None = None, pyarrow_predicate: str | None = None, ) -> tuple[LazyFrame, str] | None: """Construct a LazyFrame scan.""" if ( scan_data := self._to_dataset_scan_impl( existing_resolved_version_key=existing_resolved_version_key, limit=limit, projection=projection, filter_columns=filter_columns, pyarrow_predicate=pyarrow_predicate, ) ) is None: return None return scan_data.to_lazyframe(), scan_data.snapshot_id_key def _to_dataset_scan_impl( self, *, existing_resolved_version_key: str | None = None, limit: int | None = None, projection: list[str] | None = None, filter_columns: list[str] | None = None, pyarrow_predicate: str | None = None, ) -> _NativeIcebergScanData | _PyIcebergScanData | None: from pyiceberg.io.pyarrow import schema_to_pyarrow import polars._utils.logging verbose = polars._utils.logging.verbose() iceberg_table_filter = None if ( pyarrow_predicate is not None and self._use_metadata_statistics and self._use_pyiceberg_filter ): iceberg_table_filter = try_convert_pyarrow_predicate(pyarrow_predicate) if verbose: pyarrow_predicate_display = ( "Some(<redacted>)" if pyarrow_predicate is not None else "None" ) iceberg_table_filter_display = ( "Some(<redacted>)" if iceberg_table_filter is not None else "None" ) eprint( "IcebergDataset: to_dataset_scan(): " f"snapshot ID: {self._snapshot_id}, " f"limit: {limit}, " f"projection: {projection}, " f"filter_columns: {filter_columns}, " f"pyarrow_predicate: {pyarrow_predicate_display}, " f"iceberg_table_filter: {iceberg_table_filter_display}, " f"self._use_metadata_statistics: {self._use_metadata_statistics}" ) verbose_print_sensitive( lambda: f"IcebergDataset: to_dataset_scan(): {pyarrow_predicate = }, {iceberg_table_filter = }" ) tbl = self.table() if verbose: eprint( "IcebergDataset: to_dataset_scan(): " f"tbl.metadata.current_snapshot_id: {tbl.metadata.current_snapshot_id}" ) snapshot_id = self._snapshot_id schema_id = None if snapshot_id is not None: snapshot = tbl.snapshot_by_id(snapshot_id) if snapshot is None: msg = f"iceberg snapshot ID not found: {snapshot_id}" raise ValueError(msg) schema_id = snapshot.schema_id if schema_id is None: msg = ( f"IcebergDataset: requested snapshot {snapshot_id} " "did not contain a schema ID" ) raise ValueError(msg) iceberg_schema = tbl.schemas()[schema_id] snapshot_id_key = f"{snapshot.snapshot_id}" else: iceberg_schema = tbl.schema() schema_id = tbl.metadata.current_schema_id snapshot_id_key = ( f"{v.snapshot_id}" if (v := tbl.current_snapshot()) is not None else "" ) if ( existing_resolved_version_key is not None and existing_resolved_version_key == snapshot_id_key ): if verbose: eprint( "IcebergDataset: to_dataset_scan(): early return " f"({snapshot_id_key = })" ) return None # Take from parameter first then envvar reader_override = self._reader_override or os.getenv( "POLARS_ICEBERG_READER_OVERRIDE" ) if reader_override and reader_override not in ["native", "pyiceberg"]: msg = ( "iceberg: unknown value for reader_override: " f"'{reader_override}', expected one of ('native', 'pyiceberg')" ) raise ValueError(msg) fallback_reason = ( "forced reader_override='pyiceberg'" if reader_override == "pyiceberg" else f"unsupported table format version: {tbl.format_version}" if not tbl.format_version <= 2 else None ) selected_fields = ("*",) if projection is None else tuple(projection) projected_iceberg_schema = ( iceberg_schema if selected_fields == ("*",) else iceberg_schema.select(*selected_fields) ) sources = [] missing_field_defaults = IdentityTransformedPartitionValuesBuilder( tbl, projected_iceberg_schema, ) statistics_loader: IcebergStatisticsLoader | None = ( IcebergStatisticsLoader(tbl, iceberg_schema.select(*filter_columns)) if self._use_metadata_statistics and filter_columns is not None else None ) deletion_files: dict[int, list[str]] = {} total_physical_rows: int = 0 total_deleted_rows: int = 0 if reader_override != "pyiceberg" and not fallback_reason: from pyiceberg.manifest import DataFileContent, FileFormat if verbose: eprint("IcebergDataset: to_dataset_scan(): begin path expansion") start_time = perf_counter() scan = tbl.scan( snapshot_id=snapshot_id, limit=limit, selected_fields=selected_fields, ) if iceberg_table_filter is not None: scan = scan.filter(iceberg_table_filter) total_deletion_files = 0 for i, file_info in enumerate(scan.plan_files()): if file_info.file.file_format != FileFormat.PARQUET: fallback_reason = ( f"non-parquet format: {file_info.file.file_format}" ) break if file_info.delete_files: deletion_files[i] = [] for deletion_file in file_info.delete_files: if deletion_file.content != DataFileContent.POSITION_DELETES: fallback_reason = ( "unsupported deletion file type: " f"{deletion_file.content}" ) break if deletion_file.file_format != FileFormat.PARQUET: fallback_reason = ( "unsupported deletion file format: " f"{deletion_file.file_format}" ) break deletion_files[i].append(deletion_file.file_path) total_deletion_files += 1 total_deleted_rows += deletion_file.record_count if fallback_reason: break missing_field_defaults.push_partition_values( current_index=i, partition_spec_id=file_info.file.spec_id, partition_values=file_info.file.partition, ) if statistics_loader is not None: statistics_loader.push_file_statistics(file_info.file) total_physical_rows += file_info.file.record_count sources.append(file_info.file.file_path) if verbose: elapsed = perf_counter() - start_time eprint( "IcebergDataset: to_dataset_scan(): " f"finish path expansion ({elapsed:.3f}s)" ) if not fallback_reason: if verbose: s = "" if len(sources) == 1 else "s" s2 = "" if total_deletion_files == 1 else "s" eprint( "IcebergDataset: to_dataset_scan(): " f"native scan_parquet(): " f"{len(sources)} source{s}, " f"snapshot ID: {snapshot_id}, " f"schema ID: {schema_id}, " f"{total_deletion_files} deletion file{s2}" ) # The arrow schema returned by `schema_to_pyarrow` will contain # 'PARQUET:field_id' column_mapping = schema_to_pyarrow(iceberg_schema) identity_transformed_values = missing_field_defaults.finish() min_max_statistics = ( statistics_loader.finish(len(sources), identity_transformed_values) if statistics_loader is not None else None ) storage_options = ( _convert_iceberg_to_object_store_storage_options( self._iceberg_storage_properties ) if self._iceberg_storage_properties is not None else None ) return _NativeIcebergScanData( sources=sources, projected_iceberg_schema=projected_iceberg_schema, column_mapping=column_mapping, default_values=identity_transformed_values, deletion_files=deletion_files, min_max_statistics=min_max_statistics, statistics_loader=statistics_loader, storage_options=storage_options, row_count=( (total_physical_rows, total_deleted_rows) if ( self._use_metadata_statistics and (self._fast_deletion_count or total_deleted_rows == 0) ) else None ), _snapshot_id_key=snapshot_id_key, ) elif reader_override == "native": msg = f"iceberg reader_override='native' failed: {fallback_reason}" raise ComputeError(msg) if verbose: eprint( "IcebergDataset: to_dataset_scan(): " f"fallback to python[pyiceberg] scan: {fallback_reason}" ) func = partial( _scan_pyarrow_dataset_impl, tbl, snapshot_id=snapshot_id, n_rows=limit, with_columns=projection, iceberg_table_filter=iceberg_table_filter, ) arrow_schema = schema_to_pyarrow(tbl.schema()) lf = pl.LazyFrame._scan_python_function( arrow_schema, func, pyarrow=True, is_pure=True, ) return _PyIcebergScanData(lf=lf, _snapshot_id_key=snapshot_id_key) # # Accessors # def metadata_path(self) -> str: """Fetch the metadata path.""" if self._metadata_path is None: if self._table is None: msg = "impl error: both metadata_path and table are None" raise ValueError(msg) self._metadata_path = self.table().metadata_location return self._metadata_path def table(self) -> Table: """Fetch the PyIceberg Table object.""" if self._table is None: if self._metadata_path is None: msg = "impl error: both metadata_path and table are None" raise ValueError(msg) if verbose(): eprint(f"IcebergDataset: construct table from {self._metadata_path = }") from pyiceberg.table import StaticTable self._table = StaticTable.from_metadata( metadata_location=self._metadata_path, properties=self._iceberg_storage_properties or {}, ) return self._table # # Serialization functions # # We don't serialize the iceberg table object - the remote machine should # use their own permissions to reconstruct the table object from the path. # def __getstate__(self) -> dict[str, Any]: state = { "metadata_path": self.metadata_path(), "snapshot_id": self._snapshot_id, "iceberg_storage_properties": self._iceberg_storage_properties, "reader_override": self._reader_override, "use_metadata_statistics": self._use_metadata_statistics, "fast_deletion_count": self._fast_deletion_count, "use_pyiceberg_filter": self._use_pyiceberg_filter, } if verbose(): path_repr = state["metadata_path"] snapshot_id = f"'{v}'" if (v := state["snapshot_id"]) is not None else None keys_repr = _redact_dict_values(state["iceberg_storage_properties"]) reader_override = state["reader_override"] use_metadata_statistics = state["use_metadata_statistics"] fast_deletion_count = state["fast_deletion_count"] use_pyiceberg_filter = state["use_pyiceberg_filter"] eprint( "IcebergDataset: getstate(): " f"path: '{path_repr}', " f"snapshot_id: {snapshot_id}, " f"iceberg_storage_properties: {keys_repr}, " f"reader_override: {reader_override}, " f"use_metadata_statistics: {use_metadata_statistics}, " f"fast_deletion_count: {fast_deletion_count}, " f"use_pyiceberg_filter: {use_pyiceberg_filter}" ) return state def __setstate__(self, state: dict[str, Any]) -> None: if verbose(): path_repr = state["metadata_path"] snapshot_id = f"'{v}'" if (v := state["snapshot_id"]) is not None else None keys_repr = _redact_dict_values(state["iceberg_storage_properties"]) reader_override = state["reader_override"] use_metadata_statistics = state["use_metadata_statistics"] fast_deletion_count = state["fast_deletion_count"] use_pyiceberg_filter = state["use_pyiceberg_filter"] eprint( "IcebergDataset: getstate(): " f"path: '{path_repr}', " f"snapshot_id: '{snapshot_id}', " f"iceberg_storage_properties: {keys_repr}, " f"reader_override: {reader_override}, " f"use_metadata_statistics: {use_metadata_statistics}, " f"fast_deletion_count: {fast_deletion_count}, " f"use_pyiceberg_filter: {use_pyiceberg_filter}" ) IcebergDataset.__init__( self, state["metadata_path"], snapshot_id=state["snapshot_id"], iceberg_storage_properties=state["iceberg_storage_properties"], reader_override=state["reader_override"], use_metadata_statistics=state["use_metadata_statistics"], fast_deletion_count=state["fast_deletion_count"], use_pyiceberg_filter=state["use_pyiceberg_filter"], )
IcebergDataset
python
PrefectHQ__prefect
src/prefect/cli/cloud/__init__.py
{ "start": 2207, "end": 2257 }
class ____(BaseModel): api_key: str
LoginSuccess
python
doocs__leetcode
solution/2900-2999/2955.Number of Same-End Substrings/Solution.py
{ "start": 0, "end": 541 }
class ____: def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: n = len(s) cs = set(s) cnt = {c: [0] * (n + 1) for c in cs} for i, a in enumerate(s, 1): for c in cs: cnt[c][i] = cnt[c][i - 1] cnt[a][i] += 1 ans = [] for l, r in queries: t = r - l + 1 for c in cs: x = cnt[c][r + 1] - cnt[c][l] t += x * (x - 1) // 2 ans.append(t) return ans
Solution
python
prabhupant__python-ds
data_structures/linked_list/remove.py
{ "start": 0, "end": 388 }
class ____(): def __init__(self, val): self.val = val self.next = None def remove(head, val): while head and head.val == val: head = head.next if not head: return None curr = head while curr.next: if curr.next.val == val: curr.next = curr.next.next else: curr = curr.next return head
Node
python
getsentry__sentry
src/sentry/eventtypes/feedback.py
{ "start": 86, "end": 554 }
class ____(BaseEvent): key = "feedback" def extract_metadata(self, data): contact_email = get_path(data, "contexts", "feedback", "contact_email") message = get_path(data, "contexts", "feedback", "message") name = get_path(data, "contexts", "feedback", "name") source = get_path(data, "contexts", "feedback", "source") return {"contact_email": contact_email, "message": message, "name": name, "source": source}
FeedbackEvent
python
huggingface__transformers
src/transformers/models/depth_pro/modeling_depth_pro.py
{ "start": 27060, "end": 29067 }
class ____(nn.Module): """ ResidualConvUnit, pre-activate residual unit. Args: config (`[DepthProConfig]`): Model configuration class defining the model architecture. """ def __init__(self, config: DepthProConfig): super().__init__() self.use_batch_norm = config.use_batch_norm_in_fusion_residual use_bias_in_fusion_residual = ( config.use_bias_in_fusion_residual if config.use_bias_in_fusion_residual is not None else not self.use_batch_norm ) self.activation1 = nn.ReLU() self.convolution1 = nn.Conv2d( config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=3, stride=1, padding=1, bias=use_bias_in_fusion_residual, ) self.activation2 = nn.ReLU() self.convolution2 = nn.Conv2d( config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=3, stride=1, padding=1, bias=use_bias_in_fusion_residual, ) if self.use_batch_norm: self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size) self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size) def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: residual = hidden_state hidden_state = self.activation1(hidden_state) hidden_state = self.convolution1(hidden_state) if self.use_batch_norm: hidden_state = self.batch_norm1(hidden_state) hidden_state = self.activation2(hidden_state) hidden_state = self.convolution2(hidden_state) if self.use_batch_norm: hidden_state = self.batch_norm2(hidden_state) return hidden_state + residual # Modified from transformers.models.dpt.modeling_dpt.DPTFeatureFusionLayer # except it uses deconv and skip_add and needs no interpolation
DepthProPreActResidualLayer
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/adls.py
{ "start": 3328, "end": 4675 }
class ____(BaseOperator): """ Delete files in the specified path. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ADLSDeleteOperator` :param path: A directory or file to remove :param recursive: Whether to loop into directories in the location and remove the files :param ignore_not_found: Whether to raise error if file to delete is not found :param azure_data_lake_conn_id: Reference to the :ref:`Azure Data Lake connection<howto/connection:adl>`. """ template_fields: Sequence[str] = ("path",) ui_color = "#901dd2" def __init__( self, *, path: str, recursive: bool = False, ignore_not_found: bool = True, azure_data_lake_conn_id: str = DEFAULT_AZURE_DATA_LAKE_CONN_ID, **kwargs, ) -> None: super().__init__(**kwargs) self.path = path self.recursive = recursive self.ignore_not_found = ignore_not_found self.azure_data_lake_conn_id = azure_data_lake_conn_id def execute(self, context: Context) -> Any: hook = AzureDataLakeHook(azure_data_lake_conn_id=self.azure_data_lake_conn_id) return hook.remove(path=self.path, recursive=self.recursive, ignore_not_found=self.ignore_not_found)
ADLSDeleteOperator
python
ray-project__ray
python/ray/dag/compiled_dag_node.py
{ "start": 16138, "end": 29511 }
class ____: """A task that can be executed in a compiled DAG, and it corresponds to an actor method. """ def __init__( self, task: "CompiledTask", resolved_args: List[Any], resolved_kwargs: Dict[str, Any], ): """ Args: task: The CompiledTask that this ExecutableTask corresponds to. resolved_args: The arguments to the method. Arguments that are not Channels will get passed through to the actor method. If the argument is a channel, it will be replaced by the value read from the channel before the method executes. resolved_kwargs: The keyword arguments to the method. Currently, we do not support binding kwargs to other DAG nodes, so the values of the dictionary cannot be Channels. """ from ray.dag import CollectiveOutputNode self.method_name = task.dag_node.get_method_name() self.bind_index = task.dag_node._get_bind_index() self.output_channels = task.output_channels self.output_idxs = task.output_idxs self.input_type_hints: List[ChannelOutputType] = task.arg_type_hints self.output_type_hint: ChannelOutputType = task.dag_node.type_hint # The accelerator collective operation. self.collective_op: Optional["ray.dag.CollectiveOperation"] = None if isinstance(task.dag_node, CollectiveOutputNode): self.collective_op = task.dag_node.collective_op self.input_channels: List[ChannelInterface] = [] self.task_inputs: List[_ExecutableTaskInput] = [] self.resolved_kwargs: Dict[str, Any] = resolved_kwargs # A unique index which can be used to index into `idx_to_task` to get # the corresponding task. self.task_idx = task.idx # Reverse map for input_channels: maps an input channel to # its index in input_channels. input_channel_to_idx: dict[ChannelInterface, int] = {} for arg in resolved_args: if isinstance(arg, ChannelInterface): channel = arg if channel in input_channel_to_idx: # The same channel was added before, so reuse the index. channel_idx = input_channel_to_idx[channel] else: # Add a new channel to the list of input channels. self.input_channels.append(channel) channel_idx = len(self.input_channels) - 1 input_channel_to_idx[channel] = channel_idx task_input = _ExecutableTaskInput(arg, channel_idx) else: task_input = _ExecutableTaskInput(arg, None) self.task_inputs.append(task_input) # Currently DAGs do not support binding kwargs to other DAG nodes. for val in self.resolved_kwargs.values(): assert not isinstance(val, ChannelInterface) # Input reader to read input data from upstream DAG nodes. self.input_reader: ReaderInterface = SynchronousReader(self.input_channels) # Output writer to write output data to downstream DAG nodes. self.output_writer: WriterInterface = SynchronousWriter( self.output_channels, self.output_idxs ) # The intermediate future for a READ or COMPUTE operation, # and `wait()` must be called to get the actual result of the operation. # The result of a READ operation will be used by a COMPUTE operation, # and the result of a COMPUTE operation will be used by a WRITE operation. self._intermediate_future: Optional[DAGOperationFuture] = None def cancel(self): """ Close all the input channels and the output channel. The exact behavior depends on the type of channel. Typically, it will release the resources used by the channels. """ self.input_reader.close() self.output_writer.close() def destroy_cuda_event(self): """ If this executable task has created a GPU future that is not yet waited on, that future is in the channel context cache. Remove the future from the cache and destroy its CUDA event. """ GPUFuture.remove_gpu_future(self.task_idx) def prepare(self, overlap_gpu_communication: bool = False): """ Prepare the task for execution. The `exec_operation` function can only be called after `prepare` has been called. Args: overlap_gpu_communication: Whether to overlap GPU communication with computation during DAG execution to improve performance """ for typ_hint in self.input_type_hints: typ_hint.register_custom_serializer() self.output_type_hint.register_custom_serializer() self.input_reader.start() self.output_writer.start() # Stream context type are different between different accelerators. # Type hint is not applicable here. self._send_stream = nullcontext() self._recv_stream = nullcontext() if not overlap_gpu_communication: return # Set up send_stream and recv_stream when overlap_gpu_communication # is configured if self.output_type_hint.requires_accelerator(): comm_group_id = _get_comm_group_id(self.output_type_hint) comm_group = ChannelContext.get_current().communicators.get(comm_group_id) assert comm_group is not None self._send_stream = comm_group.send_stream if self.input_type_hints: for type_hint in self.input_type_hints: if type_hint.requires_accelerator(): comm_group_id = _get_comm_group_id(type_hint) comm_group = ChannelContext.get_current().communicators.get( comm_group_id ) assert comm_group is not None if not isinstance(self._recv_stream, nullcontext): assert self._recv_stream == comm_group.recv_stream, ( "Currently all torch tensor input channels of a " "Compiled Graph task should use the same recv cuda stream." ) self._recv_stream = comm_group.recv_stream def wrap_and_set_intermediate_future( self, val: Any, wrap_in_gpu_future: bool ) -> None: """ Wrap the value in a `DAGOperationFuture` and store to the intermediate future. The value corresponds to result of a READ or COMPUTE operation. If wrap_in_gpu_future is True, the value will be wrapped in a GPUFuture, Otherwise, the future will be a ResolvedFuture. Args: val: The value to wrap in a future. wrap_in_gpu_future: Whether to wrap the value in a GPUFuture. """ assert self._intermediate_future is None if wrap_in_gpu_future: future = GPUFuture(val, self.task_idx) else: future = ResolvedFuture(val) self._intermediate_future = future def reset_and_wait_intermediate_future(self) -> Any: """ Reset the intermediate future and wait for the result. The wait does not block the CPU because: - If the future is a ResolvedFuture, the result is immediately returned. - If the future is a GPUFuture, the result is only waited by the current CUDA stream, and the CPU is not blocked. Returns: The result of a READ or COMPUTE operation from the intermediate future. """ future = self._intermediate_future self._intermediate_future = None return future.wait() def _read(self, overlap_gpu_communication: bool) -> bool: """ Read input data from upstream DAG nodes and cache the intermediate result. Args: overlap_gpu_communication: Whether to overlap GPU communication with computation during DAG execution to improve performance. Returns: True if system error occurs and exit the loop; otherwise, False. """ assert self._intermediate_future is None exit = False try: input_data = self.input_reader.read() # When overlap_gpu_communication is enabled, wrap the result in # a GPUFuture so that this read operation (communication) can # be overlapped with computation. self.wrap_and_set_intermediate_future( input_data, wrap_in_gpu_future=overlap_gpu_communication, ) except RayChannelError: # Channel closed. Exit the loop. exit = True return exit def _compute( self, overlap_gpu_communication: bool, class_handle, ) -> bool: """ Retrieve the intermediate result from the READ operation and perform the computation. Then, cache the new intermediate result. The caller must ensure that the last operation executed is READ so that the function retrieves the correct intermediate result. Args: overlap_gpu_communication: Whether to overlap GPU communication with computation during DAG execution to improve performance. class_handle: An instance of the class to which the actor belongs. For example, the type of `class_handle` is <class 'xxxx.Worker'> if the actor belongs to the `class Worker` class. Returns: True if system error occurs and exit the loop; otherwise, False. """ input_data = self.reset_and_wait_intermediate_future() try: _process_return_vals(input_data, return_single_output=False) except Exception as exc: # Previous task raised an application-level exception. # Propagate it and skip the actual task. We don't need to wrap the # exception in a RayTaskError here because it has already been wrapped # by the previous task. self.wrap_and_set_intermediate_future( exc, wrap_in_gpu_future=overlap_gpu_communication ) return False resolved_inputs = [] for task_input in self.task_inputs: resolved_inputs.append(task_input.resolve(input_data)) if self.collective_op is not None: # Run an accelerator collective operation. method = self.collective_op.execute else: # Run an actor method. method = getattr(class_handle, self.method_name) try: output_val = method(*resolved_inputs, **self.resolved_kwargs) except Exception as exc: output_val = _wrap_exception(exc) # When overlap_gpu_communication is enabled, wrap the result in a GPUFuture # so that this compute operation can be overlapped with communication. self.wrap_and_set_intermediate_future( output_val, wrap_in_gpu_future=overlap_gpu_communication ) return False def _write(self) -> bool: """ Retrieve the intermediate result from the COMPUTE operation and write to its downstream DAG nodes. The caller must ensure that the last operation executed is COMPUTE so that the function retrieves the correct intermediate result. Returns: True if system error occurs and exit the loop; otherwise, False. """ output_val = self.reset_and_wait_intermediate_future() exit = False try: self.output_writer.write(output_val) except RayChannelError: # Channel closed. Exit the loop. exit = True return exit def exec_operation( self, class_handle, op_type: _DAGNodeOperationType, overlap_gpu_communication: bool = False, ) -> bool: """ An ExecutableTask corresponds to a DAGNode. It consists of three operations: READ, COMPUTE, and WRITE, which should be executed in order to ensure that each operation can read the correct intermediate result. Args: class_handle: The handle of the class to which the actor belongs. op_type: The type of the operation. Possible types are READ, COMPUTE, and WRITE. overlap_gpu_communication: Whether to overlap GPU communication with computation during DAG execution to improve performance. Returns: True if the next operation should not be executed; otherwise, False. """ if op_type == _DAGNodeOperationType.READ: with _device_context_manager(): with self._recv_stream: return self._read(overlap_gpu_communication) elif op_type == _DAGNodeOperationType.COMPUTE: return self._compute(overlap_gpu_communication, class_handle) elif op_type == _DAGNodeOperationType.WRITE: with _device_context_manager(): with self._send_stream: return self._write() @dataclass
ExecutableTask
python
pandas-dev__pandas
pandas/tests/arrays/sparse/test_array.py
{ "start": 767, "end": 7914 }
class ____: @pytest.mark.parametrize("fill_value", [0, None, np.nan]) def test_shift_fill_value(self, fill_value): # GH #24128 sparse = SparseArray(np.array([1, 0, 0, 3, 0]), fill_value=8.0) res = sparse.shift(1, fill_value=fill_value) if isna(fill_value): fill_value = res.dtype.na_value exp = SparseArray(np.array([fill_value, 1, 0, 0, 3]), fill_value=8.0) tm.assert_sp_array_equal(res, exp) def test_set_fill_value(self): arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan) arr.fill_value = 2 assert arr.fill_value == 2 arr = SparseArray([1, 0, 2], fill_value=0, dtype=np.int64) arr.fill_value = 2 assert arr.fill_value == 2 msg = "fill_value must be a valid value for the SparseDtype.subtype" with pytest.raises(ValueError, match=msg): # GH#53043 arr.fill_value = 3.1 assert arr.fill_value == 2 arr.fill_value = np.nan assert np.isnan(arr.fill_value) arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_) arr.fill_value = True assert arr.fill_value is True with pytest.raises(ValueError, match=msg): arr.fill_value = 0 assert arr.fill_value is True arr.fill_value = np.nan assert np.isnan(arr.fill_value) @pytest.mark.parametrize("val", [[1, 2, 3], np.array([1, 2]), (1, 2, 3)]) def test_set_fill_invalid_non_scalar(self, val): arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool_) msg = "fill_value must be a scalar" with pytest.raises(ValueError, match=msg): arr.fill_value = val def test_copy(self, arr): arr2 = arr.copy() assert arr2.sp_values is not arr.sp_values assert arr2.sp_index is arr.sp_index def test_values_asarray(self, arr_data, arr): tm.assert_almost_equal(arr.to_dense(), arr_data) @pytest.mark.parametrize( "data,shape,dtype", [ ([0, 0, 0, 0, 0], (5,), None), ([], (0,), None), ([0], (1,), None), (["A", "A", np.nan, "B"], (4,), object), ], ) def test_shape(self, data, shape, dtype): # GH 21126 out = SparseArray(data, dtype=dtype) assert out.shape == shape @pytest.mark.parametrize( "vals", [ [np.nan, np.nan, np.nan, np.nan, np.nan], [1, np.nan, np.nan, 3, np.nan], [1, np.nan, 0, 3, 0], ], ) @pytest.mark.parametrize("fill_value", [None, 0]) def test_dense_repr(self, vals, fill_value): vals = np.array(vals) arr = SparseArray(vals, fill_value=fill_value) res = arr.to_dense() tm.assert_numpy_array_equal(res, vals) @pytest.mark.parametrize("fix", ["arr", "zarr"]) def test_pickle(self, fix, request): obj = request.getfixturevalue(fix) unpickled = tm.round_trip_pickle(obj) tm.assert_sp_array_equal(unpickled, obj) def test_generator_warnings(self): sp_arr = SparseArray([1, 2, 3]) with tm.assert_produces_warning(None): for _ in sp_arr: pass def test_where_retain_fill_value(self): # GH#45691 don't lose fill_value on _where arr = SparseArray([np.nan, 1.0], fill_value=0) mask = np.array([True, False]) res = arr._where(~mask, 1) exp = SparseArray([1, 1.0], fill_value=0) tm.assert_sp_array_equal(res, exp) ser = pd.Series(arr) res = ser.where(~mask, 1) tm.assert_series_equal(res, pd.Series(exp)) def test_fillna(self): s = SparseArray([1, np.nan, np.nan, 3, np.nan]) res = s.fillna(-1) exp = SparseArray([1, -1, -1, 3, -1], fill_value=-1, dtype=np.float64) tm.assert_sp_array_equal(res, exp) s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0) res = s.fillna(-1) exp = SparseArray([1, -1, -1, 3, -1], fill_value=0, dtype=np.float64) tm.assert_sp_array_equal(res, exp) s = SparseArray([1, np.nan, 0, 3, 0]) res = s.fillna(-1) exp = SparseArray([1, -1, 0, 3, 0], fill_value=-1, dtype=np.float64) tm.assert_sp_array_equal(res, exp) s = SparseArray([1, np.nan, 0, 3, 0], fill_value=0) res = s.fillna(-1) exp = SparseArray([1, -1, 0, 3, 0], fill_value=0, dtype=np.float64) tm.assert_sp_array_equal(res, exp) s = SparseArray([np.nan, np.nan, np.nan, np.nan]) res = s.fillna(-1) exp = SparseArray([-1, -1, -1, -1], fill_value=-1, dtype=np.float64) tm.assert_sp_array_equal(res, exp) s = SparseArray([np.nan, np.nan, np.nan, np.nan], fill_value=0) res = s.fillna(-1) exp = SparseArray([-1, -1, -1, -1], fill_value=0, dtype=np.float64) tm.assert_sp_array_equal(res, exp) # float dtype's fill_value is np.nan, replaced by -1 s = SparseArray([0.0, 0.0, 0.0, 0.0]) res = s.fillna(-1) exp = SparseArray([0.0, 0.0, 0.0, 0.0], fill_value=-1) tm.assert_sp_array_equal(res, exp) # int dtype shouldn't have missing. No changes. s = SparseArray([0, 0, 0, 0]) assert s.dtype == SparseDtype(np.int64) assert s.fill_value == 0 res = s.fillna(-1) tm.assert_sp_array_equal(res, s) s = SparseArray([0, 0, 0, 0], fill_value=0) assert s.dtype == SparseDtype(np.int64) assert s.fill_value == 0 res = s.fillna(-1) exp = SparseArray([0, 0, 0, 0], fill_value=0) tm.assert_sp_array_equal(res, exp) # fill_value can be nan if there is no missing hole. # only fill_value will be changed s = SparseArray([0, 0, 0, 0], fill_value=np.nan) assert s.dtype == SparseDtype(np.int64, fill_value=np.nan) assert np.isnan(s.fill_value) res = s.fillna(-1) exp = SparseArray([0, 0, 0, 0], fill_value=-1) tm.assert_sp_array_equal(res, exp) def test_fillna_overlap(self): s = SparseArray([1, np.nan, np.nan, 3, np.nan]) # filling with existing value doesn't replace existing value with # fill_value, i.e. existing 3 remains in sp_values res = s.fillna(3) exp = np.array([1, 3, 3, 3, 3], dtype=np.float64) tm.assert_numpy_array_equal(res.to_dense(), exp) s = SparseArray([1, np.nan, np.nan, 3, np.nan], fill_value=0) res = s.fillna(3) exp = SparseArray([1, 3, 3, 3, 3], fill_value=0, dtype=np.float64) tm.assert_sp_array_equal(res, exp) def test_nonzero(self): # Tests regression #21172. sa = SparseArray([float("nan"), float("nan"), 1, 0, 0, 2, 0, 0, 0, 3, 0, 0]) expected = np.array([2, 5, 9], dtype=np.int32) (result,) = sa.nonzero() tm.assert_numpy_array_equal(expected, result) sa = SparseArray([0, 0, 1, 0, 0, 2, 0, 0, 0, 3, 0, 0]) (result,) = sa.nonzero() tm.assert_numpy_array_equal(expected, result)
TestSparseArray
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0118_addons_flyout_sorting.py
{ "start": 150, "end": 3135 }
class ____(migrations.Migration): safe = Safe.before_deploy() dependencies = [ ("projects", "0117_remove_old_fields"), ] operations = [ migrations.AddField( model_name="addonsconfig", name="flyout_sorting", field=models.CharField( choices=[ ("alphabetically", "Alphabetically"), ("semver-readthedocs-compatible", "SemVer (Read the Docs)"), ("python-packaging", "Python Packaging (PEP 440 and PEP 425)"), ("calver", "CalVer (YYYY.0M.0M)"), ("custom-pattern", "Define your own pattern"), ], default="alphabetically", max_length=64, ), ), migrations.AddField( model_name="addonsconfig", name="flyout_sorting_custom_pattern", field=models.CharField( blank=True, default=None, help_text='Sorting pattern supported by BumpVer (<a href="https://github.com/mbarkhau/bumpver#pattern-examples">See examples</a>', max_length=32, null=True, ), ), migrations.AddField( model_name="addonsconfig", name="flyout_sorting_latest_stable_at_beginning", field=models.BooleanField( default=True, help_text="Show <code>latest</code> and <code>stable</code> at the beginning", ), ), migrations.AddField( model_name="historicaladdonsconfig", name="flyout_sorting", field=models.CharField( choices=[ ("alphabetically", "Alphabetically"), ("semver-readthedocs-compatible", "SemVer (Read the Docs)"), ("python-packaging", "Python Packaging (PEP 440 and PEP 425)"), ("calver", "CalVer (YYYY.0M.0M)"), ("custom-pattern", "Define your own pattern"), ], default="alphabetically", max_length=64, ), ), migrations.AddField( model_name="historicaladdonsconfig", name="flyout_sorting_custom_pattern", field=models.CharField( blank=True, default=None, help_text='Sorting pattern supported by BumpVer (<a href="https://github.com/mbarkhau/bumpver#pattern-examples">See examples</a>', max_length=32, null=True, ), ), migrations.AddField( model_name="historicaladdonsconfig", name="flyout_sorting_latest_stable_at_beginning", field=models.BooleanField( default=True, help_text="Show <code>latest</code> and <code>stable</code> at the beginning", ), ), ]
Migration
python
spack__spack
lib/spack/spack/util/elf.py
{ "start": 954, "end": 1128 }
class ____(NamedTuple): p_type: int p_flags: int p_offset: int p_vaddr: int p_paddr: int p_filesz: int p_memsz: int p_align: int
ProgramHeader64
python
numba__numba
numba/tests/test_random.py
{ "start": 58051, "end": 61223 }
class ____(BaseTest): def _check_sample(self, size, sample): # Check output structure if size is not None: self.assertIsInstance(sample, np.ndarray) self.assertEqual(sample.dtype, np.float64) if isinstance(size, int): self.assertEqual(sample.shape, (size,)) else: self.assertEqual(sample.shape, size) else: self.assertIsInstance(sample, float) # Check statistical properties for val in np.nditer(sample): self.assertGreaterEqual(val, 0) def test_noncentral_chisquare_default(self): """ Test noncentral_chisquare(df, nonc, size=None) """ cfunc = jit(nopython=True)(numpy_noncentral_chisquare_default) inputs = ( (0.5, 1), # test branch when df < 1 (1, 5), (5, 1), (100000, 1), (1, 10000), ) for df, nonc in inputs: res = cfunc(df, nonc) self._check_sample(None, res) res = cfunc(df, np.nan) # test branch when nonc is nan self.assertTrue(np.isnan(res)) def test_noncentral_chisquare(self): """ Test noncentral_chisquare(df, nonc, size) """ cfunc = jit(nopython=True)(numpy_noncentral_chisquare) sizes = (None, 10, (10,), (10, 10)) inputs = ( (0.5, 1), (1, 5), (5, 1), (100000, 1), (1, 10000), ) for (df, nonc), size in itertools.product(inputs, sizes): res = cfunc(df, nonc, size) self._check_sample(size, res) res = cfunc(df, np.nan, size) # test branch when nonc is nan self.assertTrue(np.isnan(res).all()) def test_noncentral_chisquare_exceptions(self): cfunc = jit(nopython=True)(numpy_noncentral_chisquare) df, nonc = 0, 1 with self.assertRaises(ValueError) as raises: cfunc(df, nonc, 1) self.assertIn("df <= 0", str(raises.exception)) df, nonc = 1, -1 with self.assertRaises(ValueError) as raises: cfunc(df, nonc, 1) self.assertIn("nonc < 0", str(raises.exception)) df, nonc = 1, 1 sizes = (True, 3j, 1.5, (1.5, 1), (3j, 1), (3j, 3j), (np.int8(3), np.int64(7))) for size in sizes: with self.assertRaises(TypingError) as raises: cfunc(df, nonc, size) self.assertIn( "np.random.noncentral_chisquare(): size should be int or " "tuple of ints or None, got", str(raises.exception), ) @jit(nopython=True, nogil=True) def py_extract_randomness(seed, out): if seed != 0: random.seed(seed) for i in range(out.size): out[i] = random.getrandbits(32) _randint_limit = 1 << 32 @jit(nopython=True, nogil=True) def np_extract_randomness(seed, out): if seed != 0: np.random.seed(seed) s = 0 for i in range(out.size): out[i] = np.random.randint(_randint_limit)
TestRandomNoncentralChiSquare
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constructors.py
{ "start": 4221, "end": 4546 }
class ____(NoConstructor): def __init__(self, a, b): super().__init__(a, b) def test_parent_with_no_constructor(): _test_sink(ParentWithNoConstructor(_test_source(), "")) # Issue. _test_sink(ParentWithNoConstructor("", _test_source())) # Issue. # Test sanitizers on constructors
ParentWithNoConstructor
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchExhaustion1.py
{ "start": 1383, "end": 2277 }
class ____(Enum): red = 0 def func8(subj: SingleColor) -> int: match subj: case SingleColor.red: return 1 def func9(subj: int | None): match subj: case NoneType(): return 1 case int(): return 2 def func10(subj: Color | None = None) -> list[str]: results = [""] for x in [""]: match subj: case None: results.append(x) case Color.red: pass case Color.green: pass case Color.blue: pass return results def func11(subj: int | float | None): match subj: case float(): reveal_type(subj, expected_text="float") case int(): reveal_type(subj, expected_text="int") case NoneType(): reveal_type(subj, expected_text="None")
SingleColor
python
numpy__numpy
numpy/linalg/tests/test_linalg.py
{ "start": 41813, "end": 42652 }
class ____(HermitianTestCase, HermitianGeneralizedTestCase): def do(self, a, b, tags): # note that eigenvalue arrays returned by eig must be sorted since # their order isn't guaranteed. res = linalg.eigh(a) ev, evc = res.eigenvalues, res.eigenvectors evalues, evectors = linalg.eig(a) evalues.sort(axis=-1) assert_almost_equal(ev, evalues) assert_allclose(matmul(a, evc), np.asarray(ev)[..., None, :] * np.asarray(evc), rtol=get_rtol(ev.dtype)) ev2, evc2 = linalg.eigh(a, 'U') assert_almost_equal(ev2, evalues) assert_allclose(matmul(a, evc2), np.asarray(ev2)[..., None, :] * np.asarray(evc2), rtol=get_rtol(ev.dtype), err_msg=repr(a))
TestEighCases
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/messages/beta_message_batch_errored_result.py
{ "start": 260, "end": 367 }
class ____(BaseModel): error: BetaErrorResponse type: Literal["errored"]
BetaMessageBatchErroredResult
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 46881, "end": 48898 }
class ____(BaseModel): """ Config of HNSW index """ m: int = Field( ..., description="Number of edges per node in the index graph. Larger the value - more accurate the search, more space required.", ) ef_construct: int = Field( ..., description="Number of neighbours to consider during the index building. Larger the value - more accurate the search, more time required to build index.", ) full_scan_threshold: int = Field( ..., description="Minimal size threshold (in KiloBytes) below which full-scan is preferred over HNSW search. This measures the total size of vectors being queried against. When the maximum estimated amount of points that a condition satisfies is smaller than `full_scan_threshold_kb`, the query planner will use full-scan search instead of HNSW index traversal for better performance. Note: 1Kb = 1 vector of size 256", ) max_indexing_threads: Optional[int] = Field( default=0, description="Number of parallel threads used for background index building. If 0 - automatically select from 8 to 16. Best to keep between 8 and 16 to prevent likelihood of slow building or broken/inefficient HNSW graphs. On small CPUs, less threads are used.", ) on_disk: Optional[bool] = Field( default=None, description="Store HNSW index on disk. If set to false, index will be stored in RAM. Default: false", ) payload_m: Optional[int] = Field( default=None, description="Custom M param for hnsw graph built for payload index. If not set, default M will be used.", ) inline_storage: Optional[bool] = Field( default=None, description="Store copies of original and quantized vectors within the HNSW index file. Default: false. Enabling this option will trade the search speed for disk usage by reducing amount of random seeks during the search. Requires quantized vectors to be enabled. Multi-vectors are not supported.", )
HnswConfig
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 2508, "end": 2974 }
class ____: """Test cs_CZ bank provider""" def test_bban(self, faker, num_samples): for _ in range(num_samples): assert re.fullmatch(r"\d{20}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() assert is_valid_iban(iban) assert iban[:2] == CsCZBankProvider.country_code assert re.fullmatch(r"\d{2}\d{20}", iban[2:])
TestCsCz
python
ray-project__ray
python/ray/serve/tests/test_config_files/test_dag/conditional_dag.py
{ "start": 1175, "end": 1810 }
class ____: def __init__(self, factor: int): self.factor = factor def reconfigure(self, config: Dict): self.factor = config.get("factor", -1) def multiply(self, input_factor: int) -> int: if os.getenv("override_factor") is not None: return input_factor * int(os.getenv("override_factor")) return input_factor * self.factor @serve.deployment( user_config={ "increment": 2, }, ray_actor_options={ "num_cpus": 0.1, "runtime_env": { "env_vars": { "override_increment": "-2", } }, }, )
Multiplier
python
getsentry__sentry
tests/sentry/seer/explorer/test_tools.py
{ "start": 21096, "end": 28058 }
class ____(APITransactionTestCase, SpanTestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.ten_mins_ago = before_now(minutes=10) def _test_get_trace_waterfall(self, use_short_id: bool) -> None: transaction_name = "api/users/profile" trace_id = uuid.uuid4().hex spans: list[dict] = [] for i in range(5): # Create a span tree for this trace span = self.create_span( { **({"description": f"span-{i}"} if i != 4 else {}), "sentry_tags": {"transaction": transaction_name}, "trace_id": trace_id, "parent_span_id": (None if i == 0 else spans[i // 2]["span_id"]), "is_segment": i == 0, # First span is the root }, start_ts=self.ten_mins_ago + timedelta(minutes=i), ) spans.append(span) self.store_spans(spans, is_eap=True) result = get_trace_waterfall( trace_id[:8] if use_short_id else trace_id, self.organization.id ) assert isinstance(result, EAPTrace) assert result.trace_id == trace_id assert result.org_id == self.organization.id seen_span_ids = [] root_span_ids = [] def check_span(s): if "parent_span_id" not in s: # Not a span. return # Basic assertions and ID collection for returned spans. assert "op" in s assert "description" in s assert "children" in s assert s["transaction"] == transaction_name assert s["project_id"] == self.project.id desc = s["description"] assert isinstance(desc, str) if desc: assert desc.startswith("span-") seen_span_ids.append(s["event_id"]) # Is root if s["parent_span_id"] is None: assert s["is_transaction"] root_span_ids.append(s["event_id"]) # Recurse for child in s["children"]: check_span(child) for event in result.trace: check_span(event) assert set(seen_span_ids) == {s["span_id"] for s in spans} assert len(root_span_ids) == 1 def test_get_trace_waterfall_short_id(self) -> None: self._test_get_trace_waterfall(use_short_id=True) def test_get_trace_waterfall_full_id(self) -> None: self._test_get_trace_waterfall(use_short_id=False) def test_get_trace_waterfall_wrong_project(self) -> None: transaction_name = "api/users/profile" trace_id = uuid.uuid4().hex other_org = self.create_organization() other_project = self.create_project(organization=other_org) spans: list[dict] = [] for i in range(2): span = self.create_span( { "project_id": other_project.id, "description": f"span-{i}", "sentry_tags": {"transaction": transaction_name}, "trace_id": trace_id, "parent_span_id": None if i == 0 else spans[0]["span_id"], "is_segment": i == 0, }, start_ts=self.ten_mins_ago + timedelta(minutes=i), ) spans.append(span) self.store_spans(spans, is_eap=True) # Call with short ID and wrong org result = get_trace_waterfall(trace_id[:8], self.organization.id) assert result is None def test_get_trace_waterfall_sliding_window_second_period(self) -> None: """Test that sliding window finds traces in the second 14-day period (14-28 days ago)""" transaction_name = "api/users/profile" trace_id = uuid.uuid4().hex twenty_days_ago = before_now(days=20) spans: list[dict] = [] for i in range(3): span = self.create_span( { "description": f"span-{i}", "sentry_tags": {"transaction": transaction_name}, "trace_id": trace_id, "parent_span_id": None if i == 0 else spans[0]["span_id"], "is_segment": i == 0, }, start_ts=twenty_days_ago + timedelta(minutes=i), ) spans.append(span) self.store_spans(spans, is_eap=True) # Should find the trace using short ID by sliding back to the second window result = get_trace_waterfall(trace_id[:8], self.organization.id) assert isinstance(result, EAPTrace) assert result.trace_id == trace_id assert result.org_id == self.organization.id def test_get_trace_waterfall_sliding_window_old_trace(self) -> None: """Test that sliding window finds traces near the 90-day limit""" transaction_name = "api/users/profile" trace_id = uuid.uuid4().hex eighty_days_ago = before_now(days=80) spans: list[dict] = [] for i in range(3): span = self.create_span( { "description": f"span-{i}", "sentry_tags": {"transaction": transaction_name}, "trace_id": trace_id, "parent_span_id": None if i == 0 else spans[0]["span_id"], "is_segment": i == 0, }, start_ts=eighty_days_ago + timedelta(minutes=i), ) spans.append(span) self.store_spans(spans, is_eap=True) # Should find the trace by sliding back through multiple windows result = get_trace_waterfall(trace_id[:8], self.organization.id) assert isinstance(result, EAPTrace) assert result.trace_id == trace_id assert result.org_id == self.organization.id def test_get_trace_waterfall_sliding_window_beyond_limit(self) -> None: """Test that traces beyond 90 days are not found""" transaction_name = "api/users/profile" trace_id = uuid.uuid4().hex one_hundred_days_ago = before_now(days=100) spans: list[dict] = [] for i in range(3): span = self.create_span( { "description": f"span-{i}", "sentry_tags": {"transaction": transaction_name}, "trace_id": trace_id, "parent_span_id": None if i == 0 else spans[0]["span_id"], "is_segment": i == 0, }, start_ts=one_hundred_days_ago + timedelta(minutes=i), ) spans.append(span) self.store_spans(spans, is_eap=True) # Should not find the trace since it's beyond the 90-day limit result = get_trace_waterfall(trace_id[:8], self.organization.id) assert result is None
TestGetTraceWaterfall
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/random_test.py
{ "start": 5730, "end": 6914 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def _build_random_dataset( self, num_elements=10, seed=None, rerandomize_each_iteration=None): dataset = dataset_ops.Dataset.random( seed=seed, rerandomize_each_iteration=rerandomize_each_iteration) # Checkpoint tests need the test dataset to be finite whereas `random` is # infinite. Use `take` to limit the number of elements. return dataset.take(num_elements) @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( rerandomize_each_iteration=[True, False]))) def test(self, verify_fn, rerandomize_each_iteration): seed = 55 num_elements = 10 # pylint: disable=g-long-lambda verify_fn( self, lambda: self._build_random_dataset( seed=seed, num_elements=num_elements, rerandomize_each_iteration=rerandomize_each_iteration), num_elements) if __name__ == "__main__": test.main()
RandomCheckpointTest
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 57412, "end": 59219 }
class ____(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "a must be positive") _value_check(b > 0, "b must be positive") def pdf(self, x): a, b = self.a, self.b return a * b * x**(a-1) * (1-x**a)**(b-1) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < S.Zero), (1 - (1 - x**a)**b, x <= S.One), (S.One, True)) def Kumaraswamy(name, a, b): r""" Create a Continuous Random Variable with a Kumaraswamy distribution. Explanation =========== The density of the Kumaraswamy distribution is given by .. math:: f(x) := a b x^{a-1} (1-x^a)^{b-1} with :math:`x \in [0,1]`. Parameters ========== a : Real number, `a > 0`, a shape b : Real number, `b > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Kumaraswamy, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Kumaraswamy("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) b - 1 a - 1 / a\ a*b*z *\1 - z / >>> cdf(X)(z) Piecewise((0, z < 0), (1 - (1 - z**a)**b, z <= 1), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Kumaraswamy_distribution """ return rv(name, KumaraswamyDistribution, (a, b)) #------------------------------------------------------------------------------- # Laplace distribution ---------------------------------------------------------
KumaraswamyDistribution
python
eventlet__eventlet
tests/api_test.py
{ "start": 427, "end": 5578 }
class ____(tests.LimitedTestCase): def test_tcp_listener(self): socket = eventlet.listen(('0.0.0.0', 0)) assert socket.getsockname()[0] == '0.0.0.0' socket.close() check_hub() def test_connect_tcp(self): def accept_once(listenfd): try: conn, addr = listenfd.accept() fd = conn.makefile(mode='wb') conn.close() fd.write(b'hello\n') fd.close() finally: listenfd.close() server = eventlet.listen(('0.0.0.0', 0)) eventlet.spawn_n(accept_once, server) client = eventlet.connect(('127.0.0.1', server.getsockname()[1])) fd = client.makefile('rb') client.close() assert fd.readline() == b'hello\n' assert fd.read() == b'' fd.close() check_hub() @tests.skip_if_no_ssl def test_connect_ssl(self): def accept_once(listenfd): try: conn, addr = listenfd.accept() conn.write(b'hello\r\n') greenio.shutdown_safe(conn) conn.close() finally: greenio.shutdown_safe(listenfd) listenfd.close() server = eventlet.wrap_ssl( eventlet.listen(('0.0.0.0', 0)), tests.private_key_file, tests.certificate_file, server_side=True ) eventlet.spawn_n(accept_once, server) raw_client = eventlet.connect(('127.0.0.1', server.getsockname()[1])) client = ssl.wrap_socket(raw_client) fd = client.makefile('rb', 8192) assert fd.readline() == b'hello\r\n' try: self.assertEqual(b'', fd.read(10)) except greenio.SSL.ZeroReturnError: # if it's a GreenSSL object it'll do this pass greenio.shutdown_safe(client) client.close() check_hub() def test_001_trampoline_timeout(self): server_sock = eventlet.listen(('127.0.0.1', 0)) bound_port = server_sock.getsockname()[1] def server(sock): client, addr = sock.accept() eventlet.sleep(0.1) server_evt = eventlet.spawn(server, server_sock) eventlet.sleep(0) try: desc = eventlet.connect(('127.0.0.1', bound_port)) hubs.trampoline(desc, read=True, write=False, timeout=0.001) except eventlet.Timeout: pass # test passed else: assert False, "Didn't timeout" server_evt.wait() check_hub() def test_timeout_cancel(self): server = eventlet.listen(('0.0.0.0', 0)) bound_port = server.getsockname()[1] done = [False] def client_closer(sock): while True: (conn, addr) = sock.accept() conn.close() def go(): desc = eventlet.connect(('127.0.0.1', bound_port)) try: hubs.trampoline(desc, read=True, timeout=0.1) except eventlet.Timeout: assert False, "Timed out" server.close() desc.close() done[0] = True greenthread.spawn_after_local(0, go) server_coro = eventlet.spawn(client_closer, server) while not done[0]: eventlet.sleep(0) eventlet.kill(server_coro) check_hub() def test_killing_dormant(self): DELAY = 0.1 state = [] def test(): try: state.append('start') eventlet.sleep(DELAY) except: state.append('except') # catching GreenletExit pass # when switching to hub, hub makes itself the parent of this greenlet, # thus after the function's done, the control will go to the parent eventlet.sleep(0) state.append('finished') g = eventlet.spawn(test) eventlet.sleep(DELAY / 2) self.assertEqual(state, ['start']) eventlet.kill(g) # will not get there, unless switching is explicitly scheduled by kill self.assertEqual(state, ['start', 'except']) eventlet.sleep(DELAY) self.assertEqual(state, ['start', 'except', 'finished']) def test_nested_with_timeout(self): def func(): return eventlet.with_timeout(0.2, eventlet.sleep, 2, timeout_value=1) try: eventlet.with_timeout(0.1, func) self.fail('Expected Timeout') except eventlet.Timeout: pass def test_wrap_is_timeout(): class A: pass obj = eventlet.wrap_is_timeout(A)() tests.check_is_timeout(obj) def test_timeouterror_deprecated(): # https://github.com/eventlet/eventlet/issues/378 code = '''import eventlet; eventlet.Timeout(1).cancel(); print('pass')''' args = ['-Werror:eventlet.Timeout:DeprecationWarning', '-c', code] tests.run_python(path=None, args=args, expect_pass=True) def test_zero_second_sleep(): tests.run_isolated("zero_second_sleep.py")
TestApi
python
pypa__hatch
tests/backend/metadata/test_core.py
{ "start": 60911, "end": 62804 }
class ____: def test_correct(self, temp_dir, helpers): metadata = ProjectMetadata( str(temp_dir), PluginManager(), { "project": {"name": "foo", "dynamic": ["version"]}, "tool": {"hatch": {"build": {"reproducible": False}}}, }, ) file_path = temp_dir / "a" / "b" file_path.ensure_parent_dir_exists() file_path.write_text('__version__ = "0.0.1"') (temp_dir / "pyproject.toml").touch() file_path = temp_dir / "hatch.toml" file_path.write_text( helpers.dedent( """ [version] path = 'a/b' """ ) ) assert metadata.version == "0.0.1" assert metadata.hatch.build_config["reproducible"] is False def test_precedence(self, temp_dir, helpers): metadata = ProjectMetadata( str(temp_dir), PluginManager(), { "project": {"name": "foo", "dynamic": ["version"]}, "tool": {"hatch": {"version": {"path": "a/b"}, "build": {"reproducible": False}}}, }, ) file_path = temp_dir / "a" / "b" file_path.ensure_parent_dir_exists() file_path.write_text('__version__ = "0.0.1"') file_path = temp_dir / "c" / "d" file_path.ensure_parent_dir_exists() file_path.write_text('__version__ = "0.0.2"') (temp_dir / "pyproject.toml").touch() file_path = temp_dir / "hatch.toml" file_path.write_text( helpers.dedent( """ [version] path = 'c/d' """ ) ) assert metadata.version == "0.0.2" assert metadata.hatch.build_config["reproducible"] is False
TestHatchPersonalProjectConfigFile
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_tools_scrapegraph.py
{ "start": 8537, "end": 11707 }
class ____: """Test basic scrape functionality.""" def test_scrape_basic(self, tool_spec_with_api_key): """Test basic scrape functionality.""" tool_spec, mock_client = tool_spec_with_api_key url = "https://example.com" expected_response = { "html": "<html><body>Test content</body></html>", "request_id": "test-123", } mock_client.scrape.return_value = expected_response response = tool_spec.scrapegraph_scrape(url=url) mock_client.scrape.assert_called_once_with( website_url=url, render_heavy_js=False ) assert response == expected_response def test_scrape_with_js_rendering(self, tool_spec_from_env): """Test scrape with JavaScript rendering.""" tool_spec, mock_client = tool_spec_from_env url = "https://example.com" expected_response = {"html": "<html>Dynamic content</html>"} mock_client.scrape.return_value = expected_response response = tool_spec.scrapegraph_scrape(url=url, render_heavy_js=True) mock_client.scrape.assert_called_once_with( website_url=url, render_heavy_js=True ) assert response == expected_response def test_scrape_with_headers(self, tool_spec_with_api_key): """Test scrape with custom headers.""" tool_spec, mock_client = tool_spec_with_api_key url = "https://example.com" headers = {"User-Agent": "Test Agent", "Accept": "text/html"} expected_response = {"html": "<html>Test</html>", "status": "success"} mock_client.scrape.return_value = expected_response response = tool_spec.scrapegraph_scrape(url=url, headers=headers) mock_client.scrape.assert_called_once_with( website_url=url, render_heavy_js=False, headers=headers ) assert response == expected_response def test_scrape_with_all_options(self, tool_spec_from_env): """Test scrape with all options.""" tool_spec, mock_client = tool_spec_from_env url = "https://example.com" headers = {"User-Agent": "Full Test"} expected_response = {"html": "Full test content"} mock_client.scrape.return_value = expected_response response = tool_spec.scrapegraph_scrape( url=url, render_heavy_js=True, headers=headers, timeout=30, custom_option="value", ) mock_client.scrape.assert_called_once_with( website_url=url, render_heavy_js=True, headers=headers, timeout=30, custom_option="value", ) assert response == expected_response def test_scrape_exception_handling(self, tool_spec_with_api_key): """Test scrape exception handling.""" tool_spec, mock_client = tool_spec_with_api_key mock_client.scrape.side_effect = Exception("Scrape Error") response = tool_spec.scrapegraph_scrape(url="https://example.com") assert "error" in response assert "Scrape failed: Scrape Error" in response["error"]
TestBasicScrape
python
spyder-ide__spyder
spyder/plugins/editor/utils/editor.py
{ "start": 2367, "end": 3965 }
class ____(QTextBlockUserData): def __init__(self, editor, color=None, selection_start=None, selection_end=None): QTextBlockUserData.__init__(self) self.editor = editor self.breakpoint = False self.breakpoint_condition = None self.bookmarks = [] self.code_analysis = [] self.todo = '' self.color = color self.oedata = None self.import_statement = None self.selection_start = selection_start self.selection_end = selection_end def _selection(self): """ Function to compute the selection. This is slow to call so it is only called when needed. """ if self.selection_start is None or self.selection_end is None: return None document = self.editor.document() cursor = self.editor.textCursor() block = document.findBlockByNumber(self.selection_start['line']) cursor.setPosition(block.position()) cursor.movePosition(QTextCursor.StartOfBlock) cursor.movePosition( QTextCursor.NextCharacter, n=self.selection_start['character']) block2 = document.findBlockByNumber( self.selection_end['line']) cursor.setPosition(block2.position(), QTextCursor.KeepAnchor) cursor.movePosition( QTextCursor.StartOfBlock, mode=QTextCursor.KeepAnchor) cursor.movePosition( QTextCursor.NextCharacter, n=self.selection_end['character'], mode=QTextCursor.KeepAnchor) return QTextCursor(cursor)
BlockUserData
python
walkccc__LeetCode
solutions/1230. Toss Strange Coins/1230.py
{ "start": 0, "end": 476 }
class ____: def probabilityOfHeads(self, prob: list[float], target: int) -> float: # dp[i][j] := the probability of tossing the first i coins with j heads dp = [[0] * (target + 1) for _ in range(len(prob) + 1)] dp[0][0] = 1.0 for i in range(1, len(prob) + 1): for j in range(target + 1): dp[i][j] = ((dp[i - 1][j - 1] * prob[i - 1] if j > 0 else 0) + dp[i - 1][j] * (1 - prob[i - 1])) return dp[len(prob)][target]
Solution
python
pytorch__pytorch
test/test_cpp_api_parity.py
{ "start": 804, "end": 3026 }
class ____(common.TestCase): module_test_params_map = {} functional_test_params_map = {} expected_test_params_dicts = [] for test_params_dicts, test_instance_class in [ (sample_module.module_tests, common_nn.NewModuleTest), (sample_functional.functional_tests, common_nn.NewModuleTest), (common_nn.module_tests, common_nn.NewModuleTest), (common_nn.get_new_module_tests(), common_nn.NewModuleTest), (common_nn.criterion_tests, common_nn.CriterionTest), ]: for test_params_dict in test_params_dicts: if test_params_dict.get("test_cpp_api_parity", True): if is_torch_nn_functional_test(test_params_dict): functional_impl_check.write_test_to_test_class( TestCppApiParity, test_params_dict, test_instance_class, parity_table, devices, ) else: module_impl_check.write_test_to_test_class( TestCppApiParity, test_params_dict, test_instance_class, parity_table, devices, ) expected_test_params_dicts.append(test_params_dict) # Assert that all NN module/functional test dicts appear in the parity test assert len( [name for name in TestCppApiParity.__dict__ if "test_torch_nn_" in name] ) == len(expected_test_params_dicts) * len(devices) # Assert that there exists auto-generated tests for `SampleModule` and `sample_functional`. # 4 == 2 (number of test dicts that are not skipped) * 2 (number of devices) assert len([name for name in TestCppApiParity.__dict__ if "SampleModule" in name]) == 4 # 4 == 2 (number of test dicts that are not skipped) * 2 (number of devices) assert ( len([name for name in TestCppApiParity.__dict__ if "sample_functional" in name]) == 4 ) module_impl_check.build_cpp_tests(TestCppApiParity, print_cpp_source=PRINT_CPP_SOURCE) functional_impl_check.build_cpp_tests( TestCppApiParity, print_cpp_source=PRINT_CPP_SOURCE ) if __name__ == "__main__": common.TestCase._default_dtype_check_enabled = True common.run_tests()
TestCppApiParity
python
PrefectHQ__prefect
src/prefect/exceptions.py
{ "start": 3966, "end": 4498 }
class ____(PrefectException): """ Raised when a parameter does not pass Pydantic type validation. """ def __init__(self, msg: str): super().__init__(msg) @classmethod def from_validation_error(cls, exc: ValidationError) -> Self: bad_params = [ f"{'.'.join(str(item) for item in err['loc'])}: {err['msg']}" for err in exc.errors() ] msg = "Flow run received invalid parameters:\n - " + "\n - ".join(bad_params) return cls(msg)
ParameterTypeError
python
lepture__mistune
src/mistune/directives/_fenced.py
{ "start": 883, "end": 4826 }
class ____(BaseDirective): """A **fenced** style of directive looks like a fenced code block, it is inspired by markdown-it-docutils. The syntax looks like: .. code-block:: text ```{directive-type} title :option-key: option value :option-key: option value content text here ``` To use ``FencedDirective``, developers can add it into plugin list in the :class:`Markdown` instance: .. code-block:: python import mistune from mistune.directives import FencedDirective, Admonition md = mistune.create_markdown(plugins=[ # ... FencedDirective([Admonition()]), ]) FencedDirective is using >= 3 backticks or curly-brackets for the fenced syntax. Developers can change it to other characters, e.g. colon: .. code-block:: python directive = FencedDirective([Admonition()], ':') And then the directive syntax would look like: .. code-block:: text ::::{note} Nesting directives You can nest directives by ensuring the start and end fence matching the length. For instance, in this example, the admonition is started with 4 colons, then it should end with 4 colons. You can nest another admonition with other length of colons except 4. :::{tip} Longer outermost fence It would be better that you put longer markers for the outer fence, and shorter markers for the inner fence. In this example, we put 4 colons outsie, and 3 colons inside. ::: :::: :param plugins: list of directive plugins :param markers: characters to determine the fence, default is backtick and curly-bracket """ parser = FencedParser def __init__(self, plugins: List[DirectivePlugin], markers: str = "`~") -> None: super(FencedDirective, self).__init__(plugins) self.markers = markers _marker_pattern = "|".join(re.escape(c) for c in markers) self.directive_pattern = ( r"^(?P<fenced_directive_mark>(?:" + _marker_pattern + r"){3,})" r"\{[a-zA-Z0-9_-]+\}" ) def _process_directive(self, block: "BlockParser", marker: str, start: int, state: "BlockState") -> Optional[int]: mlen = len(marker) cursor_start = start + len(marker) _end_pattern = ( r"^ {0,3}" + marker[0] + "{" + str(mlen) + r",}" r"[ \t]*(?:\n|$)" ) _end_re = re.compile(_end_pattern, re.M) _end_m = _end_re.search(state.src, cursor_start) if _end_m: text = state.src[cursor_start : _end_m.start()] end_pos = _end_m.end() else: text = state.src[cursor_start:] end_pos = state.cursor_max m = _directive_re.match(text) if not m: return None self.parse_method(block, m, state) return end_pos def parse_directive(self, block: "BlockParser", m: Match[str], state: "BlockState") -> Optional[int]: marker = m.group("fenced_directive_mark") return self._process_directive(block, marker, m.start(), state) def parse_fenced_code(self, block: "BlockParser", m: Match[str], state: "BlockState") -> Optional[int]: info = m.group("fenced_3") if not info or not _type_re.match(info): return block.parse_fenced_code(m, state) if state.depth() >= block.max_nested_level: return block.parse_fenced_code(m, state) marker = m.group("fenced_2") return self._process_directive(block, marker, m.start(), state) def __call__(self, md: "Markdown") -> None: super(FencedDirective, self).__call__(md) if self.markers == "`~": md.block.register("fenced_code", None, self.parse_fenced_code) else: self.register_block_parser(md, "fenced_code")
FencedDirective
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 2880, "end": 3373 }
class ____(_TestSchema): _schema = { "$schema": _JSON_SCHEMA_DRAFT_URL, "definitions": { "Foo": {"type": "object", "properties": {"d": {"type": "string"}}}, "Bar": {"type": "string", "enum": ["A", "B"]}, }, "type": "object", "additionalProperties": False, "properties": { "a": {"type": "integer"}, "b": {"type": "string"}, "c": {"$ref": "#/definitions/Foo"}, }, }
Derived
python
wepe__MachineLearning
DecisionTree/id3_c45.py
{ "start": 7719, "end": 7846 }
class ____(Exception): """ Exception class to raise if estimator is used before fitting """ pass
NotFittedError
python
huggingface__transformers
src/transformers/models/visual_bert/modeling_visual_bert.py
{ "start": 17625, "end": 18343 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.transform = VisualBertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->VisualBert
VisualBertLMPredictionHead
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/packaging.py
{ "start": 9585, "end": 11116 }
class ____(PackagingCheck): name = "Connector version must follow Semantic Versioning" description = f"Connector version must follow the Semantic Versioning scheme. This is to ensure that all connectors follow a consistent versioning scheme. Refer to our [Semantic Versioning for Connectors]({consts.SEMVER_FOR_CONNECTORS_DOC_URL}) for more details." def _run(self, connector: Connector) -> CheckResult: if "dockerImageTag" not in connector.metadata: return self.create_check_result( connector=connector, passed=False, message=f"dockerImageTag is missing in {consts.METADATA_FILE_NAME}", ) try: semver.Version.parse(str(connector.metadata["dockerImageTag"])) except ValueError: return self.create_check_result( connector=connector, passed=False, message=f"Connector version {connector.metadata['dockerImageTag']} does not follow semantic versioning", ) return self.create_check_result( connector=connector, passed=True, message="Connector version follows semantic versioning", ) ENABLED_CHECKS = [ CheckConnectorUsesPoetry(), CheckConnectorLicense(), CheckConnectorLicenseMatchInPyproject(), CheckVersionFollowsSemver(), CheckConnectorVersionMatchInPyproject(), CheckPublishToPyPiIsDeclared(), CheckManifestOnlyConnectorBaseImage(), ]
CheckVersionFollowsSemver
python
run-llama__llama_index
llama-index-core/tests/response_synthesizers/test_refine.py
{ "start": 355, "end": 3667 }
class ____(BasePydanticProgram): """ Runs the query on the LLM as normal and always returns the answer with query_satisfied=True. In effect, doesn't do any answer filtering. """ def __init__(self, input_to_query_satisfied: Dict[str, bool]): self._input_to_query_satisfied = input_to_query_satisfied @property def output_cls(self) -> Type[BaseModel]: return StructuredRefineResponse def __call__( self, *args: Any, context_str: Optional[str] = None, context_msg: Optional[str] = None, **kwargs: Any, ) -> StructuredRefineResponse: input_str = context_str or context_msg input_str = cast(str, input_str) query_satisfied = self._input_to_query_satisfied[input_str] return StructuredRefineResponse( answer=input_str, query_satisfied=query_satisfied ) async def acall( self, *args: Any, context_str: Optional[str] = None, context_msg: Optional[str] = None, **kwargs: Any, ) -> StructuredRefineResponse: input_str = context_str or context_msg input_str = cast(str, input_str) query_satisfied = self._input_to_query_satisfied[input_str] return StructuredRefineResponse( answer=input_str, query_satisfied=query_satisfied ) @pytest.fixture() def refine_instance() -> Refine: return Refine( streaming=False, verbose=True, structured_answer_filtering=True, ) def test_constructor_args() -> None: with pytest.raises(ValueError): # can't construct refine with both streaming and answer filtering Refine( streaming=True, structured_answer_filtering=True, ) with pytest.raises(ValueError): # can't construct refine with a program factory but not answer filtering Refine( program_factory=lambda _: MockRefineProgram({}), structured_answer_filtering=False, ) @pytest.mark.asyncio async def test_answer_filtering_one_answer() -> None: input_to_query_satisfied = OrderedDict( [ ("input1", False), ("input2", True), ("input3", False), ] ) def program_factory(*args: Any, **kwargs: Any) -> MockRefineProgram: return MockRefineProgram(input_to_query_satisfied) refine_instance = Refine( structured_answer_filtering=True, program_factory=program_factory, ) res = await refine_instance.aget_response( "question", list(input_to_query_satisfied.keys()) ) assert res == "input2" @pytest.mark.asyncio async def test_answer_filtering_no_answers() -> None: input_to_query_satisfied = OrderedDict( [ ("input1", False), ("input2", False), ("input3", False), ] ) def program_factory(*args: Any, **kwargs: Any) -> MockRefineProgram: return MockRefineProgram(input_to_query_satisfied) refine_instance = Refine( structured_answer_filtering=True, program_factory=program_factory, ) res = await refine_instance.aget_response( "question", list(input_to_query_satisfied.keys()) ) assert res == "Empty Response"
MockRefineProgram
python
realpython__materials
python-constants/strict_constants.py
{ "start": 214, "end": 513 }
class ____: @property def PI(self): return 3.141592653589793 @property def EULER_NUMBER(self): return 2.718281828459045 ConstantsNamespace_namedtuple = namedtuple( "ConstantsNamespace", ["PI", "EULER_NUMBER"] ) @dataclass(frozen=True)
ConstantsNamespace_property
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/pysqlite.py
{ "start": 16224, "end": 16828 }
class ____(DATETIME): def bind_processor( # type: ignore[override] self, dialect: SQLiteDialect ) -> Optional[_BindProcessorType[Any]]: if dialect.native_datetime: return None else: return DATETIME.bind_processor(self, dialect) def result_processor( # type: ignore[override] self, dialect: SQLiteDialect, coltype: object ) -> Optional[_ResultProcessorType[Any]]: if dialect.native_datetime: return None else: return DATETIME.result_processor(self, dialect, coltype)
_SQLite_pysqliteTimeStamp
python
pallets__jinja
src/jinja2/compiler.py
{ "start": 8950, "end": 9182 }
class ____(Exception): """Raised if the compiler encountered a situation where it just doesn't make sense to further process the code. Any block that raises such an exception is not further processed. """
CompilerExit
python
numba__numba
numba/core/codegen.py
{ "start": 51581, "end": 52506 }
class ____(CPUCodegen): """ A codegen implementation suitable for Ahead-Of-Time compilation (e.g. generation of object files). """ _library_class = AOTCodeLibrary def __init__(self, module_name, cpu_name=None): # By default, use generic cpu model for the arch self._cpu_name = cpu_name or '' CPUCodegen.__init__(self, module_name) def _customize_tm_options(self, options): cpu_name = self._cpu_name if cpu_name == 'host': cpu_name = self._get_host_cpu_name() options['cpu'] = cpu_name options['reloc'] = 'pic' options['codemodel'] = 'default' options['features'] = self._tm_features def _customize_tm_features(self): # ISA features are selected according to the requested CPU model # in _customize_tm_options() return '' def _add_module(self, module): pass
AOTCPUCodegen
python
PrefectHQ__prefect
src/prefect/server/utilities/user_templates.py
{ "start": 694, "end": 1618 }
class ____(ImmutableSandboxedEnvironment): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) # Override the range function to limit its size self.globals["range"] = _check_template_range # type: ignore _template_environment = UserTemplateEnvironment( undefined=ChainableUndefined, enable_async=True, extensions=[ # Supports human-friendly rendering of dates and times # https://pypi.org/project/jinja2-humanize-extension/ "jinja2_humanize_extension.HumanizeExtension", ], ) _sync_template_environment = UserTemplateEnvironment( undefined=ChainableUndefined, enable_async=False, extensions=[ # Supports human-friendly rendering of dates and times # https://pypi.org/project/jinja2-humanize-extension/ "jinja2_humanize_extension.HumanizeExtension", ], )
UserTemplateEnvironment
python
getsentry__sentry
tests/sentry/uptime/subscriptions/test_tasks.py
{ "start": 11949, "end": 15327 }
class ____(UptimeTestCase): def test_basic(self) -> None: sub = self.create_uptime_subscription(region_slugs=["default"]) subscription_id = uuid4().hex assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.ACTIVE ) == { "subscription_id": subscription_id, "url": sub.url, "interval_seconds": sub.interval_seconds, "timeout_ms": sub.timeout_ms, "request_method": "GET", "request_headers": [], "trace_sampling": False, "active_regions": ["default"], "region_schedule_mode": "round_robin", } def test_request_fields(self) -> None: headers = [["hi", "bye"]] body = "some request body" method = "POST" sub = self.create_uptime_subscription( method=method, headers=headers, body=body, trace_sampling=True, region_slugs=["default"], ) sub.refresh_from_db() subscription_id = uuid4().hex assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.ACTIVE ) == { "subscription_id": subscription_id, "url": sub.url, "interval_seconds": sub.interval_seconds, "timeout_ms": sub.timeout_ms, "request_method": method, "request_headers": headers, "request_body": body, "trace_sampling": True, "active_regions": ["default"], "region_schedule_mode": "round_robin", } def test_no_regions(self) -> None: sub = self.create_uptime_subscription() subscription_id = uuid4().hex assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.ACTIVE ) == { "subscription_id": subscription_id, "url": sub.url, "interval_seconds": sub.interval_seconds, "timeout_ms": sub.timeout_ms, "request_method": "GET", "request_headers": [], "trace_sampling": False, "active_regions": [], "region_schedule_mode": "round_robin", } def test_region_mode(self) -> None: sub = self.create_uptime_subscription(region_slugs=["default"]) subscription_id = uuid4().hex assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.ACTIVE )["active_regions"] == ["default"] assert ( uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.SHADOW )["active_regions"] == [] ) self.create_uptime_subscription_region( sub, "shadow_slug", UptimeSubscriptionRegion.RegionMode.SHADOW ) assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.ACTIVE )["active_regions"] == ["default"] assert uptime_subscription_to_check_config( sub, subscription_id, UptimeSubscriptionRegion.RegionMode.SHADOW )["active_regions"] == ["shadow_slug"]
UptimeSubscriptionToCheckConfigTest
python
apache__airflow
airflow-core/tests/unit/executors/test_executor_loader.py
{ "start": 1186, "end": 1455 }
class ____: pass celery_executor = pytest.importorskip("airflow.providers.celery.executors.celery_executor") ecs_executor = pytest.importorskip("airflow.providers.amazon.aws.executors.ecs.ecs_executor") @pytest.mark.usefixtures("clean_executor_loader")
FakeExecutor
python
celery__celery
t/smoke/tests/stamping/test_visitor.py
{ "start": 199, "end": 1457 }
class ____: def test_callback(self, dev_worker: CeleryTestWorker): on_signature_stamp = {"on_signature_stamp": 4} no_visitor_stamp = {"no_visitor_stamp": "Stamp without visitor"} on_callback_stamp = {"on_callback_stamp": 2} link_stamp = { **on_signature_stamp, **no_visitor_stamp, **on_callback_stamp, } class CustomStampingVisitor(StampingVisitor): def on_signature(self, sig, **headers) -> dict: return on_signature_stamp.copy() def on_callback(self, callback, **header) -> dict: return on_callback_stamp.copy() stamped_task = identity.si(123).set(queue=dev_worker.worker_queue) stamped_task.link( add.s(0) .stamp(no_visitor_stamp=no_visitor_stamp["no_visitor_stamp"]) .set(queue=dev_worker.worker_queue) ) stamped_task.stamp(visitor=CustomStampingVisitor()) stamped_task.delay().get(timeout=RESULT_TIMEOUT) assert dev_worker.logs().count( json.dumps(on_signature_stamp, indent=4, sort_keys=True) ) assert dev_worker.logs().count(json.dumps(link_stamp, indent=4, sort_keys=True))
test_stamping_visitor
python
apache__airflow
dev/breeze/src/airflow_breeze/prepare_providers/provider_documentation.py
{ "start": 5633, "end": 5736 }
class ____(Exception): """Raised when user skipped package."""
PrepareReleaseDocsUserSkippedException
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/package_entry.py
{ "start": 2133, "end": 2419 }
class ____(EnvRegistryObjectFeatureData): schema: Optional[dict[str, Any]] @property def feature(self) -> EnvRegistryObjectFeature: return "scaffold-target" ############### # ENV REGISTRY MANIFEST ############### @whitelist_for_serdes @record
ScaffoldTargetTypeData
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1177371, "end": 1178783 }
class ____(sgqlc.types.Type, Node): """An environment.""" __schema__ = github_schema __field_names__ = ("database_id", "name", "protection_rules") database_id = sgqlc.types.Field(Int, graphql_name="databaseId") """Identifies the primary key from the database.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of the environment""" protection_rules = sgqlc.types.Field( sgqlc.types.non_null(DeploymentProtectionRuleConnection), graphql_name="protectionRules", 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)), ) ), ) """The protection rules defined for this environment Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """
Environment
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 12939, "end": 13098 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("CLOSED", "OPEN")
IssueState
python
walkccc__LeetCode
solutions/2954. Count the Number of Infection Sequences/2954.py
{ "start": 0, "end": 1059 }
class ____: def numberOfSequence(self, n: int, sick: list[int]) -> int: MOD = 1_000_000_007 @functools.lru_cache(None) def fact(i: int) -> int: return 1 if i <= 1 else i * fact(i - 1) % MOD @functools.lru_cache(None) def inv(i: int) -> int: return pow(i, MOD - 2, MOD) ans = fact(n - len(sick)) # the number of infected children prevSick = -1 for i, s in enumerate(sick): # The segment [prevSick + 1, sick - 1] are the current non-infected # children. nonInfected = sick[i] - prevSick - 1 prevSick = sick[i] if nonInfected == 0: continue ans *= inv(fact(nonInfected)) ans %= MOD if i > 0: # There're two choices per second since the children at the two # endpoints can both be the infect candidates. So, there are # 2^[nonInfected - 1] ways to infect all children in the current # segment. ans *= pow(2, nonInfected - 1, MOD) nonInfected = n - sick[-1] - 1 return ans * inv(fact(nonInfected)) % MOD
Solution
python
faif__python-patterns
patterns/structural/3-tier.py
{ "start": 485, "end": 833 }
class ____: """Business logic holding data store instances""" data = Data() def product_list(self) -> KeysView[str]: return self.data["products"].keys() def product_information( self, product: str ) -> Optional[Dict[str, Union[int, float]]]: return self.data["products"].get(product, None)
BusinessLogic
python
joke2k__faker
faker/providers/lorem/en_PH/__init__.py
{ "start": 115, "end": 2956 }
class ____(LoremProvider): """Implement lorem provider for ``en_PH`` locale. This localized provider generates pseudo-Latin text when using the standard lorem provider methods, and the ``english_*`` methods are also provided for generating text in American English. Both languages are used in this locale for this purpose. All the ``english_*`` methods use their corresponding standard lorem provider method under the hood with ``ext_word_list`` set to the |EnUsLoremProvider|'s word list. .. |EnUsLoremProvider| replace:: :meth:`EnUsLoremProvider <faker.providers.lorem.en_US.Provider>` """ english_word_list = EnUsProvider.word_list def english_word(self) -> str: """Generate an English word.""" return self.word(ext_word_list=self.english_word_list) def english_words(self, nb: int = 3, unique: bool = False) -> List[str]: """Generate a list of English words. :sample: nb=5 :sample: nb=5, unique=True """ word_list = self.generator.get_words_list(ext_word_list=self.english_word_list) return self.words(nb=nb, ext_word_list=word_list, unique=unique) def english_sentence(self, nb_words: int = 6, variable_nb_words: bool = True) -> str: """Generate a sentence in English. :sample: nb_words=10 :sample: nb_words=10, variable_nb_words=False """ return self.sentence(nb_words, variable_nb_words, self.english_word_list) def english_sentences(self, nb: int = 3) -> List[str]: """Generate a list of sentences in English. :sample: nb=5 """ return self.sentences(nb, self.english_word_list) def english_paragraph(self, nb_sentences: int = 3, variable_nb_sentences: bool = True) -> str: """Generate a paragraph in English. :sample: nb_sentences=5 :sample: nb_sentences=5, variable_nb_sentences=False """ return self.paragraph(nb_sentences, variable_nb_sentences, self.english_word_list) def english_paragraphs(self, nb: int = 3) -> List[str]: """Generate a list of paragraphs in English. :sample: nb=5 """ return self.paragraphs(nb, self.english_word_list) def english_text(self, max_nb_chars: int = 200) -> str: """Generate a text string in English. :sample: max_nb_chars=20 :sample: max_nb_chars=80 :sample: max_nb_chars=160 """ return self.text(max_nb_chars, self.english_word_list) def english_texts(self, nb_texts: int = 3, max_nb_chars: int = 200) -> List[str]: """Generate a list of text strings in English. :sample: nb_texts=5 :sample: nb_texts=5, max_nb_chars=50 """ return self.texts(nb_texts, max_nb_chars, self.english_word_list)
Provider
python
jazzband__django-model-utils
tests/models.py
{ "start": 2874, "end": 3386 }
class ____(InheritanceManagerTestParent): other_onetoone = models.OneToOneField( InheritanceManagerTestParent, related_name='non_inheritance_relation', parent_link=False, on_delete=models.CASCADE) # The following is needed because of that Django bug: # https://code.djangoproject.com/ticket/29998 parent_ptr = models.OneToOneField( InheritanceManagerTestParent, related_name='child4_onetoone', parent_link=True, on_delete=models.CASCADE)
InheritanceManagerTestChild4
python
pytorch__pytorch
test/nn/test_lazy_modules.py
{ "start": 479, "end": 33269 }
class ____(TestCase): @suppress_warnings def test_lazy_module_parameter(self): module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) self.assertTrue(module.has_uninitialized_params()) state_dict = module.state_dict() self.assertIsInstance(state_dict["test_param"], UninitializedParameter) new_module = LazyModule() # An error is raised when there is an attempt to replace an existing parameter # with an uninitialized one new_module.register_parameter("test_param", nn.Parameter(torch.ones(5, 5))) with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): new_module.load_state_dict(state_dict) # Uninitialized parameters are overridden when the state dict to be loaded contains a valid one new_module = LazyModule() new_module.register_parameter("test_param", nn.Parameter(torch.ones(5, 5))) module.load_state_dict(new_module.state_dict()) self.assertEqual(module.test_param, torch.ones((5, 5))) # Uninitialized parameters are left unchanged module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) self.assertTrue(module.has_uninitialized_params()) new_module = LazyModule() new_module.register_parameter("test_param", UninitializedParameter()) module.load_state_dict(new_module.state_dict()) self.assertTrue(module.has_uninitialized_params()) @suppress_warnings def test_lazy_module_buffer(self): module = LazyModule() module.test_buffer = UninitializedBuffer() self.assertTrue(module.has_uninitialized_params()) state_dict = module.state_dict() self.assertIsInstance(state_dict["test_buffer"], UninitializedBuffer) new_module = LazyModule() # An error is raised when there is an attempt to replace an existing parameter # with an uninitialized one new_module.test_buffer = Buffer(torch.ones(5, 5)) with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): new_module.load_state_dict(state_dict) # Uninitialized parameters are overridden when the state dict to be loaded contains a valid one new_module = LazyModule() new_module.test_buffer = Buffer(torch.ones(5, 5)) module.load_state_dict(new_module.state_dict()) self.assertEqual(module.test_buffer, torch.ones((5, 5))) # Uninitialized parameters are left unchanged module = LazyModule() module.test_buffer = UninitializedBuffer() self.assertTrue(module.has_uninitialized_params()) new_module = LazyModule() new_module.test_buffer = UninitializedBuffer() module.load_state_dict(new_module.state_dict()) module.load_state_dict(new_module.state_dict()) self.assertTrue(module.has_uninitialized_params()) @suppress_warnings def test_lazy_module_jit_param(self): module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) self.assertTrue(module.has_uninitialized_params()) with self.assertRaisesRegex(RuntimeError, "run a forward pass"): torch.jit.script(module) @suppress_warnings def test_lazy_module_jit_buffer(self): module = LazyModule() module.test_buffer = UninitializedBuffer() self.assertTrue(module.has_uninitialized_params()) with self.assertRaisesRegex(RuntimeError, "run a forward pass"): torch.jit.script(module) @suppress_warnings def test_lazy_share_memory_param(self): module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) self.assertTrue(module.has_uninitialized_params()) with self.assertRaisesRegex(RuntimeError, "share memory on an uninitialized"): module.share_memory() @suppress_warnings def test_lazy_share_memory_buffer(self): module = LazyModule() module.test_buffer = UninitializedBuffer() self.assertTrue(module.has_uninitialized_params()) with self.assertRaisesRegex(RuntimeError, "share memory on an uninitialized"): module.share_memory() @suppress_warnings def test_linear(self): module = nn.LazyLinear(10) self.assertIsInstance(module.weight, UninitializedParameter) self.assertIsInstance(module.bias, UninitializedParameter) input = torch.ones(5, 5) output = module(input) self.assertIsInstance(module, nn.Linear) self.assertNotIsInstance(module, nn.LazyLinear) self.assertTrue(module.weight.shape == (10, 5)) self.assertTrue(module.bias.shape == (10,)) self.assertTrue((module.weight != 0).any()) self.assertTrue((module.bias != 0).any()) self.assertTrue((output != 0).any()) y = module(input) self.assertTrue( torch.equal( torch.nn.functional.linear(input, module.weight, module.bias), y ) ) @suppress_warnings def test_lazy_linear_pickle(self): module = nn.LazyLinear(10) self.assertIsInstance(module.weight, UninitializedParameter) self.assertIsInstance(module.bias, UninitializedParameter) module = pickle.loads(pickle.dumps(module)) self.assertIsInstance(module, nn.LazyLinear) self.assertIsInstance(module.weight, UninitializedParameter) self.assertIsInstance(module.bias, UninitializedParameter) input = torch.ones(5, 5) module(input) # fully materialized new_module = pickle.loads(pickle.dumps(module)) self.assertIsInstance(new_module, nn.Linear) self.assertNotIsInstance(new_module, nn.LazyLinear) self.assertTrue(new_module.weight.shape == (10, 5)) self.assertNotIsInstance(new_module.weight, UninitializedParameter) self.assertTrue(new_module.bias.shape == (10,)) self.assertNotIsInstance(new_module.bias, UninitializedParameter) @suppress_warnings def test_linear_state(self): module = nn.Linear(5, 10) lazy_module = nn.LazyLinear(10) lazy_module.load_state_dict(module.state_dict()) # Parameters have been initialized but the module won't become a full # Linear one until the first iteration. This is due to # limitations on the state_dict loading logic self.assertFalse(lazy_module.has_uninitialized_params()) self.assertTrue(lazy_module.weight.shape == (10, 5)) self.assertTrue(lazy_module.bias.shape == (10,)) module = nn.Linear(5, 10) lazy_module = nn.LazyLinear(10) with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): module.load_state_dict(lazy_module.state_dict()) @suppress_warnings def test_lazy_linear_state_and_forward(self): module = nn.Linear(5, 10) lazy_module = nn.LazyLinear(10) lazy_module.load_state_dict(module.state_dict()) # Parameters have been initialized but the module won't become a full # Linear one until the first iteration. This is due to # limitations on the state_dict loading logic self.assertFalse(lazy_module.has_uninitialized_params()) self.assertTrue(isinstance(lazy_module, nn.LazyLinear)) input = torch.randn(5, 5) lazy_module(input) self.assertFalse(isinstance(lazy_module, nn.LazyLinear)) self.assertTrue(lazy_module.in_features == 5) def _check_lazy_conv( self, cls, lazy_cls, func, init_args, input_shape, expected_weight_shape, expected_bias_shape, *forward_args, **forward_kwargs, ): module = lazy_cls(*init_args) self.assertIsInstance(module.weight, UninitializedParameter) if module.bias is not None: self.assertIsInstance(module.bias, UninitializedParameter) input = torch.ones(*input_shape) module(input, *forward_args, **forward_kwargs) self.assertIsInstance(module, cls) self.assertNotIsInstance(module, lazy_cls) self.assertEqual(module.weight.shape, expected_weight_shape) if module.bias is not None: self.assertEqual(module.bias.shape, expected_bias_shape) y = module(input) self.assertTrue(torch.equal(func(input, module.weight, module.bias), y)) def _check_lazy_conv_pickle( self, cls, lazy_cls, init_args, input_shape, expected_weight_shape, expected_bias_shape, ): module = lazy_cls(*init_args) self.assertIsInstance(module.weight, UninitializedParameter) if module.bias is not None: self.assertIsInstance(module.bias, UninitializedParameter) module = pickle.loads(pickle.dumps(module)) self.assertIsInstance(module, lazy_cls) self.assertIsInstance(module.weight, UninitializedParameter) if module.bias is not None: self.assertIsInstance(module.bias, UninitializedParameter) input = torch.ones(*input_shape) module(input) # fully materialized new_module = pickle.loads(pickle.dumps(module)) self.assertIsInstance(new_module, cls) self.assertNotIsInstance(new_module, lazy_cls) self.assertEqual(new_module.weight.shape, expected_weight_shape) self.assertNotIsInstance(new_module.weight, UninitializedParameter) if new_module.bias is not None: self.assertEqual(new_module.bias.shape, expected_bias_shape) self.assertNotIsInstance(new_module.bias, UninitializedParameter) def _check_lazy_conv_state( self, gen_module, gen_lazy_module, expected_weight_shape, expected_bias_shape ): module = gen_module() lazy_module = gen_lazy_module() lazy_module.load_state_dict(module.state_dict()) # Parameters have been initialized but the module won't become a full # Conv one until the first iteration. This is due to # limitations on the state_dict loading logic self.assertFalse(lazy_module.has_uninitialized_params()) self.assertEqual(lazy_module.weight.shape, expected_weight_shape) if lazy_module.bias is not None: self.assertEqual(lazy_module.bias.shape, expected_bias_shape) module = gen_module() lazy_module = gen_lazy_module() with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): module.load_state_dict(lazy_module.state_dict()) def test_lazy_pre_forward_hook(self): """ This test is to test whether lazymodule can register other pre-forward hook functions successfully. """ class TestModule(torch.nn.modules.lazy.LazyModuleMixin, torch.nn.Module): def initialize_parameters(self, input): return None def forward(self, input): return input def hook_function(module, input): return input[0] + 1 module = TestModule() module.register_forward_pre_hook(hook_function) output = module(torch.zeros(2, 2)) self.assertEqual(output, torch.ones(2, 2)) def test_lazy_forward_hook(self): """ This test is to test whether lazymodule can register other forward hook functions successfully. """ class TestModule(torch.nn.modules.lazy.LazyModuleMixin, torch.nn.Module): def initialize_parameters(self, input): return None def forward(self, input): return input def hook_function(module, input, output): return input[0] + 1 module = TestModule() module.register_forward_hook(hook_function) output = module(torch.zeros(2, 2)) self.assertEqual(output, torch.ones(2, 2)) @suppress_warnings def test_lazy_conv1d(self): self._check_lazy_conv( nn.Conv1d, nn.LazyConv1d, torch.nn.functional.conv1d, (32, 2), (192, 16, 50), (32, 16, 2), (32,), ) @suppress_warnings def test_lazy_conv1d_pickle(self): self._check_lazy_conv_pickle( nn.Conv1d, nn.LazyConv1d, (32, 2), (192, 16, 50), (32, 16, 2), (32,) ) @suppress_warnings def test_lazy_conv1d_state(self): self._check_lazy_conv_state( lambda: nn.Conv1d(16, 32, 2), lambda: nn.LazyConv1d(32, 2), (32, 16, 2), (32,), ) @suppress_warnings def test_lazy_conv2d(self): self._check_lazy_conv( nn.Conv2d, nn.LazyConv2d, torch.nn.functional.conv2d, (32, 2), (192, 16, 8, 6), (32, 16, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv2d_pickle(self): self._check_lazy_conv_pickle( nn.Conv2d, nn.LazyConv2d, (32, 2), (192, 16, 8, 6), (32, 16, 2, 2), (32,) ) @suppress_warnings def test_lazy_conv2d_state(self): self._check_lazy_conv_state( lambda: nn.Conv2d(16, 32, 2), lambda: nn.LazyConv2d(32, 2), (32, 16, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv3d(self): self._check_lazy_conv( nn.Conv3d, nn.LazyConv3d, torch.nn.functional.conv3d, (32, 2), (192, 16, 8, 7, 6), (32, 16, 2, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv3d_pickle(self): self._check_lazy_conv_pickle( nn.Conv3d, nn.LazyConv3d, (32, 2), (192, 16, 8, 7, 6), (32, 16, 2, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv3d_state(self): self._check_lazy_conv_state( lambda: nn.Conv3d(16, 32, 2), lambda: nn.LazyConv3d(32, 2), (32, 16, 2, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transposed1d(self): self._check_lazy_conv( nn.ConvTranspose1d, nn.LazyConvTranspose1d, torch.nn.functional.conv_transpose1d, (32, 2), (192, 16, 50), (16, 32, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose1d_kwargs(self): self._check_lazy_conv( nn.ConvTranspose1d, nn.LazyConvTranspose1d, torch.nn.functional.conv_transpose1d, (32, 2), (192, 16, 50), (16, 32, 2), (32,), output_size=(51,), ) @suppress_warnings def test_lazy_conv_transpose1d_pickle(self): self._check_lazy_conv_pickle( nn.ConvTranspose1d, nn.LazyConvTranspose1d, (32, 2), (192, 16, 50), (16, 32, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose1d_state(self): self._check_lazy_conv_state( lambda: nn.ConvTranspose1d(16, 32, 2), lambda: nn.LazyConvTranspose1d(32, 2), (16, 32, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose2d(self): self._check_lazy_conv( nn.ConvTranspose2d, nn.LazyConvTranspose2d, torch.nn.functional.conv_transpose2d, (32, 2), (192, 16, 8, 6), (16, 32, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose2d_kwargs(self): self._check_lazy_conv( nn.ConvTranspose2d, nn.LazyConvTranspose2d, torch.nn.functional.conv_transpose2d, (32, 2), (192, 16, 8, 6), (16, 32, 2, 2), (32,), output_size=(9, 7), ) @suppress_warnings def test_lazy_conv_transpose2d_pickle(self): self._check_lazy_conv_pickle( nn.ConvTranspose2d, nn.LazyConvTranspose2d, (32, 2), (192, 16, 8, 6), (16, 32, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose2d_state(self): self._check_lazy_conv_state( lambda: nn.ConvTranspose2d(16, 32, 2), lambda: nn.LazyConvTranspose2d(32, 2), (16, 32, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose3d(self): self._check_lazy_conv( nn.ConvTranspose3d, nn.LazyConvTranspose3d, torch.nn.functional.conv_transpose3d, (32, 2), (192, 16, 8, 7, 6), (16, 32, 2, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose3d_kwargs(self): self._check_lazy_conv( nn.ConvTranspose3d, nn.LazyConvTranspose3d, torch.nn.functional.conv_transpose3d, (32, 2), (192, 16, 8, 7, 6), (16, 32, 2, 2, 2), (32,), output_size=(9, 8, 7), ) @suppress_warnings def test_lazy_conv_transpose3d_pickle(self): self._check_lazy_conv_pickle( nn.ConvTranspose3d, nn.LazyConvTranspose3d, (32, 2), (192, 16, 8, 7, 6), (16, 32, 2, 2, 2), (32,), ) @suppress_warnings def test_lazy_conv_transpose3d_state(self): self._check_lazy_conv_state( lambda: nn.ConvTranspose3d(16, 32, 2), lambda: nn.LazyConvTranspose3d(32, 2), (16, 32, 2, 2, 2), (32,), ) def _check_lazy_norm(self, cls, lazy_cls, input_shape): for affine in [False, True]: for track_running_stats in [False, True]: lazy_module = lazy_cls( affine=affine, track_running_stats=track_running_stats ) if affine: self.assertIsInstance(lazy_module.weight, UninitializedParameter) self.assertIsInstance(lazy_module.bias, UninitializedParameter) if track_running_stats: self.assertIsInstance(lazy_module.running_mean, UninitializedBuffer) self.assertIsInstance(lazy_module.running_var, UninitializedBuffer) input = torch.ones(*input_shape) lazy_output = lazy_module(input) self.assertIsInstance(lazy_module, cls) self.assertNotIsInstance(lazy_module, lazy_cls) num_features = input_shape[1] module = cls( num_features, affine=affine, track_running_stats=track_running_stats ) expected_output = module(input) self.assertEqual(lazy_output, expected_output) if module.weight is not None: self.assertEqual(lazy_module.weight.shape, module.weight.shape) self.assertEqual(lazy_module.weight, module.weight) if module.bias is not None: self.assertEqual(lazy_module.bias.shape, module.bias.shape) self.assertEqual(lazy_module.bias, module.bias) if module.running_mean is not None: self.assertEqual( lazy_module.running_mean.shape, module.running_mean.shape ) self.assertEqual(lazy_module.running_mean, module.running_mean) if module.running_var is not None: self.assertEqual( lazy_module.running_var.shape, module.running_var.shape ) self.assertEqual(lazy_module.running_var, module.running_var) if module.num_batches_tracked is not None: self.assertEqual( lazy_module.num_batches_tracked.shape, module.num_batches_tracked.shape, ) self.assertEqual( lazy_module.num_batches_tracked, module.num_batches_tracked ) def _check_lazy_norm_pickle(self, cls, lazy_cls, input_shape): for affine in [False, True]: for track_running_stats in [False, True]: module = lazy_cls( affine=affine, track_running_stats=track_running_stats ) module = pickle.loads(pickle.dumps(module)) self.assertIsInstance(module, lazy_cls) if affine: self.assertIsInstance(module.weight, UninitializedParameter) self.assertIsInstance(module.bias, UninitializedParameter) if track_running_stats: self.assertIsInstance(module.running_mean, UninitializedBuffer) self.assertIsInstance(module.running_var, UninitializedBuffer) input = torch.ones(*input_shape) module(input) # fully materialized module = pickle.loads(pickle.dumps(module)) self.assertNotIsInstance(module, lazy_cls) self.assertIsInstance(module, cls) if affine: self.assertNotIsInstance(module.weight, UninitializedParameter) self.assertNotIsInstance(module.bias, UninitializedParameter) if track_running_stats: self.assertNotIsInstance(module.running_mean, UninitializedBuffer) self.assertNotIsInstance(module.running_var, UninitializedBuffer) def _check_lazy_batchnorm_state(self, cls, lazy_cls): module = cls(10) lazy_module = lazy_cls(affine=True, track_running_stats=True) lazy_module.load_state_dict(module.state_dict()) # Parameters have been initialized but the module won't become a full # Conv one until the first iteration. This is due to # limitations on the state_dict loading logic self.assertFalse(lazy_module.has_uninitialized_params()) self.assertEqual(lazy_module.weight.shape, (10,)) self.assertEqual(lazy_module.bias.shape, (10,)) self.assertEqual(lazy_module.running_mean.shape, (10,)) self.assertEqual(lazy_module.running_var.shape, (10,)) module = cls(10) lazy_module = lazy_cls() with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): module.load_state_dict(lazy_module.state_dict()) def _check_lazy_instancenorm_state(self, cls, lazy_cls): for affine in [False, True]: for track_running_stats in [False, True]: module = cls(10, affine=affine, track_running_stats=track_running_stats) lazy_module = lazy_cls( affine=affine, track_running_stats=track_running_stats ) lazy_module.load_state_dict(module.state_dict()) # Parameters have been initialized but the module won't become a full # InstanceNorm one until the first iteration. This is due to # limitations on the state_dict loading logic self.assertFalse(lazy_module.has_uninitialized_params()) if affine: self.assertEqual(lazy_module.weight.shape, (10,)) self.assertEqual(lazy_module.bias.shape, (10,)) if track_running_stats: self.assertEqual(lazy_module.running_mean.shape, (10,)) self.assertEqual(lazy_module.running_var.shape, (10,)) module = cls(10, affine=True, track_running_stats=True) lazy_module = lazy_cls(affine=True, track_running_stats=True) with self.assertRaisesRegex(RuntimeError, "shape of an uninitialized"): module.load_state_dict(lazy_module.state_dict()) def _check_lazy_norm_with_dict_input(self, cls, lazy_cls, input_shape): input = {"input": torch.ones(*input_shape)} lazy_module = lazy_cls() lazy_output = lazy_module(**input) num_features = input_shape[1] module = cls(num_features) expected_output = module(**input) self.assertEqual(lazy_output, expected_output) def test_lazy_batchnorm1d(self): self._check_lazy_norm(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 3, 6)) self._check_lazy_norm(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 6)) def test_lazy_batchnorm1d_pickle(self): self._check_lazy_norm_pickle(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 3, 6)) self._check_lazy_norm_pickle(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 6)) def test_lazy_batchnorm1d_state(self): self._check_lazy_batchnorm_state(nn.BatchNorm1d, nn.LazyBatchNorm1d) self._check_lazy_batchnorm_state(nn.BatchNorm1d, nn.LazyBatchNorm1d) def test_lazy_batchnorm2d(self): self._check_lazy_norm(nn.BatchNorm2d, nn.LazyBatchNorm2d, (16, 3, 6, 7)) def test_lazy_batchnorm2d_pickle(self): self._check_lazy_norm_pickle(nn.BatchNorm2d, nn.LazyBatchNorm2d, (16, 3, 6, 7)) def test_lazy_batchnorm2d_state(self): self._check_lazy_batchnorm_state(nn.BatchNorm2d, nn.LazyBatchNorm2d) self._check_lazy_batchnorm_state(nn.BatchNorm2d, nn.LazyBatchNorm2d) def test_lazy_batchnorm3d(self): self._check_lazy_norm(nn.BatchNorm3d, nn.LazyBatchNorm3d, (16, 3, 6, 7, 8)) def test_lazy_batchnorm3d_pickle(self): self._check_lazy_norm_pickle( nn.BatchNorm3d, nn.LazyBatchNorm3d, (16, 3, 6, 7, 8) ) def test_lazy_batchnorm3d_state(self): self._check_lazy_batchnorm_state(nn.BatchNorm3d, nn.LazyBatchNorm3d) self._check_lazy_batchnorm_state(nn.BatchNorm3d, nn.LazyBatchNorm3d) def test_lazy_instancenorm1d(self): self._check_lazy_norm(nn.InstanceNorm1d, nn.LazyInstanceNorm1d, (16, 3, 6)) def test_lazy_instancenorm1d_pickle(self): self._check_lazy_norm_pickle( nn.InstanceNorm1d, nn.LazyInstanceNorm1d, (16, 3, 6) ) def test_lazy_instancenorm1d_state(self): self._check_lazy_instancenorm_state(nn.InstanceNorm1d, nn.LazyInstanceNorm1d) self._check_lazy_instancenorm_state(nn.InstanceNorm1d, nn.LazyInstanceNorm1d) def test_lazy_instancenorm2d(self): self._check_lazy_norm(nn.InstanceNorm2d, nn.LazyInstanceNorm2d, (16, 3, 6, 7)) def test_lazy_instancenorm2d_pickle(self): self._check_lazy_norm_pickle( nn.InstanceNorm2d, nn.LazyInstanceNorm2d, (16, 3, 6, 7) ) def test_lazy_instancenorm2d_state(self): self._check_lazy_instancenorm_state(nn.InstanceNorm2d, nn.LazyInstanceNorm2d) self._check_lazy_instancenorm_state(nn.InstanceNorm2d, nn.LazyInstanceNorm2d) def test_lazy_instancenorm3d(self): self._check_lazy_norm( nn.InstanceNorm3d, nn.LazyInstanceNorm3d, (16, 3, 6, 7, 8) ) def test_lazy_instancenorm3d_pickle(self): self._check_lazy_norm_pickle( nn.InstanceNorm3d, nn.LazyInstanceNorm3d, (16, 3, 6, 7, 8) ) def test_lazy_instancenorm3d_state(self): self._check_lazy_instancenorm_state(nn.InstanceNorm3d, nn.LazyInstanceNorm3d) self._check_lazy_instancenorm_state(nn.InstanceNorm3d, nn.LazyInstanceNorm3d) def test_lazy_batchnorm_with_dict_input(self): self._check_lazy_norm_with_dict_input( nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 3, 6) ) self._check_lazy_norm_with_dict_input( nn.BatchNorm2d, nn.LazyBatchNorm2d, (16, 3, 6, 7) ) self._check_lazy_norm_with_dict_input( nn.BatchNorm3d, nn.LazyBatchNorm3d, (16, 3, 6, 7, 8) ) @suppress_warnings def test_materialize_dtype(self): module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) module.test_param.materialize(10) self.assertTrue(module.test_param.dtype == torch.get_default_dtype()) module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) module.half() module.test_param.materialize(10) self.assertTrue(module.test_param.dtype == torch.float16) @unittest.skipIf( not (TEST_CUDA or TEST_PRIVATEUSE1), "CUDA and PRIVATEUSE1 not available" ) @suppress_warnings def test_materialize_device(self): module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) module.test_param.materialize(10) self.assertTrue(module.test_param.device.type == "cpu") if TEST_CUDA: device = "cuda" elif TEST_PRIVATEUSE1: device = torch._C._get_privateuse1_backend_name() module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) module.to(device) module.test_param.materialize(10) self.assertTrue(module.test_param.device.type == device) @suppress_warnings def test_chained_initialization(self): class MyNetwork(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear_1 = torch.nn.LazyLinear(15) self.linear_2 = torch.nn.LazyLinear(10) def forward(self, x): y = self.linear_1(x) return self.linear_2(y) net = MyNetwork() net(torch.ones(5, 10)) self.assertTrue(net.linear_1.weight.shape == (15, 10)) self.assertTrue(net.linear_1.bias.shape == (15,)) self.assertTrue(net.linear_2.weight.shape == (10, 15)) self.assertTrue(net.linear_2.bias.shape == (10,)) @suppress_warnings def test_optimizer_pass(self): optimizers = [ torch.optim.Adadelta, torch.optim.Adagrad, torch.optim.Adamax, torch.optim.Adam, torch.optim.AdamW, torch.optim.ASGD, torch.optim.SGD, torch.optim.Rprop, torch.optim.RMSprop, torch.optim.LBFGS, torch.optim.NAdam, torch.optim.RAdam, ] def run_step(module, optim): self.assertIsInstance( optim.param_groups[0]["params"][0], UninitializedParameter ) module.test_param.materialize(10) self.assertIsInstance(optim.param_groups[0]["params"][0], Parameter) self.assertNotIsInstance( optim.param_groups[0]["params"][0], UninitializedParameter ) for p in module.parameters(): p.grad = torch.rand_like(p) if isinstance(optim, torch.optim.LBFGS): optim.step(lambda: 1.0) else: optim.step() for optim_cls in optimizers: module = LazyModule() module.register_parameter("test_param", UninitializedParameter()) if optim_cls is torch.optim.SGD: optim = optim_cls(module.parameters(), lr=0.0) elif optim_cls is torch.optim.Adagrad: with self.assertRaisesRegex(ValueError, "uninitialized parameter"): optim = optim_cls(module.parameters()) continue else: optim = optim_cls(module.parameters()) run_step(module, optim) @suppress_warnings def test_weight_norm(self): m = nn.LazyLinear(7) with self.assertRaisesRegex(ValueError, "have uninitialized parameters."): m = torch.nn.utils.weight_norm(m) @suppress_warnings def test_spectral_norm(self): m = nn.LazyLinear(7) with self.assertRaisesRegex(ValueError, "have uninitialized parameters."): m = torch.nn.utils.spectral_norm(m) @suppress_warnings def test_invalid_functions(self): param = torch.nn.parameter.UninitializedParameter() with self.assertRaisesRegex(ValueError, "uninitialized parameter"): torch.empty_like(param) with self.assertRaisesRegex(ValueError, "uninitialized parameter"): torch.add(param, param) with self.assertRaisesRegex(ValueError, "uninitialized parameter"): param + param if __name__ == "__main__": run_tests()
TestLazyModules
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/session.py
{ "start": 7191, "end": 7495 }
class ____(_StateChangeState): ACTIVE = 1 PREPARED = 2 COMMITTED = 3 DEACTIVE = 4 CLOSED = 5 PROVISIONING_CONNECTION = 6 # backwards compatibility ACTIVE, PREPARED, COMMITTED, DEACTIVE, CLOSED, PROVISIONING_CONNECTION = tuple( SessionTransactionState )
SessionTransactionState
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_check_commands.py
{ "start": 14582, "end": 17153 }
class ____: """Test suite for other check commands that are not yet implemented.""" def setup_method(self): """Set up test fixtures.""" self.runner = CliRunner() def test_check_rst_symbols_runs(self): """Test that check rst-symbols runs without NotImplementedError.""" result = self.runner.invoke(check, ["rst-symbols", "--all"]) # Should not raise NotImplementedError and should exit cleanly assert result.exit_code in [0, 1] # Can succeed or fail validation but shouldn't crash assert "RST symbol checking functionality not yet implemented" not in result.output def test_check_rst_symbols_no_options_fails(self): """Test that check rst-symbols without options fails.""" result = self.runner.invoke(check, ["rst-symbols"]) # Should fail with exit code 1 assert result.exit_code == 1 assert "Error: One of --all or --package must be provided" in result.output def test_check_public_symbols_runs(self): """Test that check public-symbols runs without NotImplementedError.""" result = self.runner.invoke(check, ["public-symbols", "--all"]) # Should not raise NotImplementedError and should exit cleanly assert result.exit_code in [0, 1] # Can succeed or fail validation but shouldn't crash assert "Public symbol checking functionality not yet implemented" not in result.output def test_check_public_symbols_no_options_fails(self): """Test that check public-symbols without options fails.""" result = self.runner.invoke(check, ["public-symbols"]) # Should fail with exit code 1 assert result.exit_code == 1 assert "Error: One of --all or --package must be provided" in result.output def test_check_exports_runs(self): """Test that check exports runs without NotImplementedError.""" result = self.runner.invoke(check, ["exports", "--all"]) # Should not raise NotImplementedError and should exit cleanly assert result.exit_code in [0, 1] # Can succeed or fail validation but shouldn't crash assert "Export checking functionality not yet implemented" not in result.output def test_check_exports_no_options_fails(self): """Test that check exports without options fails.""" result = self.runner.invoke(check, ["exports"]) # Should fail with exit code 1 assert result.exit_code == 1 assert "Error: One of --all or --package must be provided" in result.output
TestCheckOtherCommands
python
cloudpipe__cloudpickle
tests/cloudpickle_file_test.py
{ "start": 118, "end": 3068 }
class ____(unittest.TestCase): """In Cloudpickle, expected behaviour when pickling an opened file is to send its contents over the wire and seek to the same position.""" def setUp(self): self.tmpdir = tempfile.mkdtemp() self.tmpfilepath = os.path.join(self.tmpdir, "testfile") self.teststring = "Hello world!" def tearDown(self): shutil.rmtree(self.tmpdir) def test_empty_file(self): # Empty file open(self.tmpfilepath, "w").close() with open(self.tmpfilepath) as f: self.assertEqual("", pickle.loads(cloudpickle.dumps(f)).read()) os.remove(self.tmpfilepath) def test_closed_file(self): # Write & close with open(self.tmpfilepath, "w") as f: f.write(self.teststring) with pytest.raises(pickle.PicklingError) as excinfo: cloudpickle.dumps(f) assert "Cannot pickle closed files" in str(excinfo.value) os.remove(self.tmpfilepath) def test_r_mode(self): # Write & close with open(self.tmpfilepath, "w") as f: f.write(self.teststring) # Open for reading with open(self.tmpfilepath) as f: new_f = pickle.loads(cloudpickle.dumps(f)) self.assertEqual(self.teststring, new_f.read()) os.remove(self.tmpfilepath) def test_w_mode(self): with open(self.tmpfilepath, "w") as f: f.write(self.teststring) f.seek(0) self.assertRaises(pickle.PicklingError, lambda: cloudpickle.dumps(f)) os.remove(self.tmpfilepath) def test_plus_mode(self): # Write, then seek to 0 with open(self.tmpfilepath, "w+") as f: f.write(self.teststring) f.seek(0) new_f = pickle.loads(cloudpickle.dumps(f)) self.assertEqual(self.teststring, new_f.read()) os.remove(self.tmpfilepath) def test_seek(self): # Write, then seek to arbitrary position with open(self.tmpfilepath, "w+") as f: f.write(self.teststring) f.seek(4) unpickled = pickle.loads(cloudpickle.dumps(f)) # unpickled StringIO is at position 4 self.assertEqual(4, unpickled.tell()) self.assertEqual(self.teststring[4:], unpickled.read()) # but unpickled StringIO also contained the start unpickled.seek(0) self.assertEqual(self.teststring, unpickled.read()) os.remove(self.tmpfilepath) def test_pickling_special_file_handles(self): # Warning: if you want to run your tests with nose, add -s option for out in sys.stdout, sys.stderr: # Regression test for SPARK-3415 self.assertEqual(out, pickle.loads(cloudpickle.dumps(out))) self.assertRaises(pickle.PicklingError, lambda: cloudpickle.dumps(sys.stdin)) if __name__ == "__main__": unittest.main()
CloudPickleFileTests
python
walkccc__LeetCode
solutions/1719. Number Of Ways To Reconstruct A Tree/1719.py
{ "start": 0, "end": 1426 }
class ____: def checkWays(self, pairs: list[list[int]]) -> int: MAX = 501 graph = collections.defaultdict(list) degrees = [0] * MAX connected = [[False] * MAX for _ in range(MAX)] for u, v in pairs: graph[u].append(v) graph[v].append(u) degrees[u] += 1 degrees[v] += 1 connected[u][v] = True connected[v][u] = True # For each node, sort its children by degrees in descending order. for _, children in graph.items(): children.sort(key=lambda x: -degrees[x]) # Find the root with a degree that equals to n - 1. root = next((i for i, d in enumerate(degrees) if d == len(graph) - 1), -1) if root == -1: return 0 hasMoreThanOneWay = False def dfs(u: int, ancestors: list[int], seen: list[bool]) -> bool: """ Returns True if each node rooted at u is connected to all of its ancestors. """ nonlocal hasMoreThanOneWay seen[u] = True for ancestor in ancestors: if not connected[u][ancestor]: return False ancestors.append(u) for v in graph[u]: if seen[v]: continue if degrees[v] == degrees[u]: hasMoreThanOneWay = True if not dfs(v, ancestors, seen): return False ancestors.pop() return True if not dfs(root, [], [False] * MAX): return 0 return 2 if hasMoreThanOneWay else 1
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py
{ "start": 1408, "end": 1462 }
class ____[T: (_Z := TypeVar('_Z'))](Generic[_Z]): ...
C
python
getsentry__sentry
src/sentry/api/analytics.py
{ "start": 90, "end": 263 }
class ____(analytics.Event): org_id: int search_type: str query: str @analytics.eventclass("organization_saved_search.deleted")
OrganizationSavedSearchCreatedEvent
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-papers/llama_index/readers/papers/arxiv/base.py
{ "start": 267, "end": 6533 }
class ____(BaseReader): """ Arxiv Reader. Gets a search query, return a list of Documents of the top corresponding scientific papers on Arxiv. """ def __init__( self, ) -> None: """Initialize with parameters.""" super().__init__() def _hacky_hash(self, some_string): return hashlib.md5(some_string.encode("utf-8")).hexdigest() def load_data( self, search_query: str, papers_dir: Optional[str] = ".papers", max_results: Optional[int] = 10, ) -> List[Document]: """ Search for a topic on Arxiv, download the PDFs of the top results locally, then read them. Args: search_query (str): A topic to search for (e.g. "Artificial Intelligence"). papers_dir (Optional[str]): Locally directory to store the papers max_results (Optional[int]): Maximum number of papers to fetch. Returns: List[Document]: A list of Document objects. """ import arxiv arxiv_search = arxiv.Search( query=search_query, id_list=[], max_results=max_results, sort_by=arxiv.SortCriterion.Relevance, ) search_results = list(arxiv_search.results()) logging.debug(f"> Successfully fetched {len(search_results)} paperes") if not os.path.exists(papers_dir): os.makedirs(papers_dir) paper_lookup = {} for paper in search_results: # Hash filename to avoid bad characters in file path hashed_name = self._hacky_hash(f"{paper.title}{paper.entry_id}") filename = f"{hashed_name}.pdf" paper_lookup[filename] = { "Title of this paper": paper.title, "Authors": (", ").join([a.name for a in paper.authors]), "Date published": paper.published.strftime("%m/%d/%Y"), "URL": paper.entry_id, # "summary": paper.summary } paper.download_pdf(dirpath=papers_dir, filename=filename) logging.debug(f"> Downloading {filename}...") def get_paper_metadata(filename): return paper_lookup[os.path.basename(filename)] arxiv_documents = SimpleDirectoryReader( papers_dir, file_metadata=get_paper_metadata, exclude_hidden=False, # default directory is hidden ".papers" ).load_data() # Include extra documents containing the abstracts abstract_documents = [] for paper in search_results: d = ( f"The following is a summary of the paper: {paper.title}\n\nSummary:" f" {paper.summary}" ) abstract_documents.append(Document(text=d)) # Delete downloaded papers try: for f in os.listdir(papers_dir): os.remove(os.path.join(papers_dir, f)) logging.debug(f"> Deleted file: {f}") os.rmdir(papers_dir) logging.debug(f"> Deleted directory: {papers_dir}") except OSError: print("Unable to delete files or directory") return arxiv_documents + abstract_documents def load_papers_and_abstracts( self, search_query: str, papers_dir: Optional[str] = ".papers", max_results: Optional[int] = 10, ) -> Tuple[List[Document], List[Document]]: """ Search for a topic on Arxiv, download the PDFs of the top results locally, then read them. Args: search_query (str): A topic to search for (e.g. "Artificial Intelligence"). papers_dir (Optional[str]): Locally directory to store the papers max_results (Optional[int]): Maximum number of papers to fetch. Returns: List[Document]: A list of Document objects representing the papers themselves List[Document]: A list of Document objects representing abstracts only """ import arxiv arxiv_search = arxiv.Search( query=search_query, id_list=[], max_results=max_results, sort_by=arxiv.SortCriterion.Relevance, ) search_results = list(arxiv_search.results()) logging.debug(f"> Successfully fetched {len(search_results)} paperes") if not os.path.exists(papers_dir): os.makedirs(papers_dir) paper_lookup = {} for paper in search_results: # Hash filename to avoid bad characters in file path hashed_name = self._hacky_hash(f"{paper.title}{paper.entry_id}") filename = f"{hashed_name}.pdf" paper_lookup[filename] = { "Title of this paper": paper.title, "Authors": (", ").join([a.name for a in paper.authors]), "Date published": paper.published.strftime("%m/%d/%Y"), "URL": paper.entry_id, # "summary": paper.summary } paper.download_pdf(dirpath=papers_dir, filename=filename) logging.debug(f"> Downloading {filename}...") def get_paper_metadata(filename): return paper_lookup[os.path.basename(filename)] arxiv_documents = SimpleDirectoryReader( papers_dir, file_metadata=get_paper_metadata, exclude_hidden=False, # default directory is hidden ".papers" ).load_data() # Include extra documents containing the abstracts abstract_documents = [] for paper in search_results: d = ( f"The following is a summary of the paper: {paper.title}\n\nSummary:" f" {paper.summary}" ) abstract_documents.append(Document(text=d)) # Delete downloaded papers try: for f in os.listdir(papers_dir): os.remove(os.path.join(papers_dir, f)) logging.debug(f"> Deleted file: {f}") os.rmdir(papers_dir) logging.debug(f"> Deleted directory: {papers_dir}") except OSError: print("Unable to delete files or directory") return arxiv_documents, abstract_documents
ArxivReader
python
tensorflow__tensorflow
tensorflow/python/framework/sparse_tensor.py
{ "start": 2062, "end": 14188 }
class ____(internal.NativeObject, composite_tensor.CompositeTensor): """Represents a sparse tensor. TensorFlow represents a sparse tensor as three separate dense tensors: `indices`, `values`, and `dense_shape`. In Python, the three tensors are collected into a `SparseTensor` class for ease of use. If you have separate `indices`, `values`, and `dense_shape` tensors, wrap them in a `SparseTensor` object before passing to the ops below. Concretely, the sparse tensor `SparseTensor(indices, values, dense_shape)` comprises the following components, where `N` and `ndims` are the number of values and number of dimensions in the `SparseTensor`, respectively: * `indices`: A 2-D int64 tensor of shape `[N, ndims]`, which specifies the indices of the elements in the sparse tensor that contain nonzero values (elements are zero-indexed). For example, `indices=[[1,3], [2,4]]` specifies that the elements with indexes of [1,3] and [2,4] have nonzero values. * `values`: A 1-D tensor of any type and shape `[N]`, which supplies the values for each element in `indices`. For example, given `indices=[[1,3], [2,4]]`, the parameter `values=[18, 3.6]` specifies that element [1,3] of the sparse tensor has a value of 18, and element [2,4] of the tensor has a value of 3.6. * `dense_shape`: A 1-D int64 tensor of shape `[ndims]`, which specifies the dense_shape of the sparse tensor. Takes a list indicating the number of elements in each dimension. For example, `dense_shape=[3,6]` specifies a two-dimensional 3x6 tensor, `dense_shape=[2,3,4]` specifies a three-dimensional 2x3x4 tensor, and `dense_shape=[9]` specifies a one-dimensional tensor with 9 elements. The corresponding dense tensor satisfies: ```python dense.shape = dense_shape dense[tuple(indices[i])] = values[i] ``` By convention, `indices` should be sorted in row-major order (or equivalently lexicographic order on the tuples `indices[i]`). This is not enforced when `SparseTensor` objects are constructed, but most ops assume correct ordering. If the ordering of sparse tensor `st` is wrong, a fixed version can be obtained by calling `tf.sparse.reorder(st)`. Example: The sparse tensor ```python SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]) ``` represents the dense tensor ```python [[1, 0, 0, 0] [0, 0, 2, 0] [0, 0, 0, 0]] ``` """ @classmethod def from_value(cls, sparse_tensor_value): if not is_sparse(sparse_tensor_value): raise TypeError(f"Argument sparse_tensor_value={sparse_tensor_value} " "is neither a SparseTensor nor SparseTensorValue.") return SparseTensor( indices=sparse_tensor_value.indices, values=sparse_tensor_value.values, dense_shape=sparse_tensor_value.dense_shape) def __init__(self, indices, values, dense_shape): """Creates a `SparseTensor`. Args: indices: A 2-D int64 tensor of shape `[N, ndims]`. values: A 1-D tensor of any type and shape `[N]`. dense_shape: A 1-D int64 tensor of shape `[ndims]`. Raises: ValueError: When building an eager SparseTensor if `dense_shape` is unknown or contains unknown elements (None or -1). """ with ops.name_scope(None, "SparseTensor", [indices, values, dense_shape]): indices = ops.convert_to_tensor( indices, name="indices", dtype=dtypes.int64) # TODO(touts): Consider adding mutable_values() when 'values' # is a VariableOp and updating users of SparseTensor. values = ops.convert_to_tensor(values, name="values") dense_shape = ops.convert_to_tensor( dense_shape, name="dense_shape", dtype=dtypes.int64) dense_shape_default = tensor_util.constant_value_as_shape(dense_shape) self._indices = indices self._values = values self._dense_shape = dense_shape self._dense_shape_default = dense_shape_default indices_shape = indices.shape.with_rank(2) values_shape = values.shape.with_rank(1) dense_shape_shape = dense_shape.shape.with_rank(1) # Assert number of rows in indices match the number of elements in values. indices_shape.dims[0].assert_is_compatible_with(values_shape.dims[0]) # Assert number of columns in indices matches the number of elements in # dense_shape. indices_shape.dims[1].assert_is_compatible_with(dense_shape_shape.dims[0]) def get_shape(self) -> tensor_shape.TensorShape: """Get the `TensorShape` representing the shape of the dense tensor. Returns: A `TensorShape` object. """ return self._dense_shape_default @property def indices(self): """The indices of non-zero values in the represented dense tensor. Returns: A 2-D Tensor of int64 with dense_shape `[N, ndims]`, where `N` is the number of non-zero values in the tensor, and `ndims` is the rank. """ return self._indices @property def values(self): """The non-zero values in the represented dense tensor. Returns: A 1-D Tensor of any data type. """ return self._values def with_values(self, new_values): """Returns a copy of `self` with `values` replaced by `new_values`. This method produces a new `SparseTensor` that has the same nonzero `indices` and same `dense_shape`, but updated values. Args: new_values: The values of the new `SparseTensor`. Needs to have the same shape as the current `.values` `Tensor`. May have a different type than the current `values`. Returns: A `SparseTensor` with identical indices and shape but updated values. Example usage: >>> st = tf.sparse.from_dense([[1, 0, 2, 0], [3, 0, 0, 4]]) >>> tf.sparse.to_dense(st.with_values([10, 20, 30, 40])) # 4 nonzero values <tf.Tensor: shape=(2, 4), dtype=int32, numpy= array([[10, 0, 20, 0], [30, 0, 0, 40]], dtype=int32)> """ return SparseTensor(self._indices, new_values, self._dense_shape) @property def op(self) -> ops.Operation: """The `Operation` that produces `values` as an output.""" return self._values.op @property def dtype(self): """The `DType` of elements in this tensor.""" return self._values.dtype @property def dense_shape(self): """A 1-D Tensor of int64 representing the shape of the dense tensor.""" return self._dense_shape @property def shape(self): """Get the `TensorShape` representing the shape of the dense tensor. Returns: A `TensorShape` object. """ return self._dense_shape_default def set_shape(self, shape): """Updates the `TensorShape` representing the shape of the dense tensor. With eager execution this operates as a shape assertion. Here the shapes match: >>> st = tf.SparseTensor( ... indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]) >>> st.set_shape([3, 4]) Passing a `None` in the new shape allows any value for that axis: >>> st.set_shape([3, None]) An error is raised if an incompatible shape is passed. >>> st.set_shape([1, 4]) Traceback (most recent call last): ... ValueError: Tensor's shape (3, 4) is not compatible with supplied shape [1, 4] When executing in a `tf.function`, or building a model using `tf.keras.Input`, `SparseTensor.set_shape` will *merge* the given `shape` with the current shape of this tensor, and set the tensor's shape to the merged value (see `tf.TensorShape.merge_with` for details): >>> st = tf.keras.Input(shape=[None, None, 3], sparse=True) >>> print(st.shape) (None, None, None, 3) Dimensions set to `None` are not updated: >>> st.set_shape([None, 224, 224, None]) >>> print(st.shape) (None, 224, 224, 3) The main use case for this is to provide additional shape information that cannot be inferred from the graph alone. Caution: `set_shape` ensures that the applied shape is compatible with the existing shape, but it does not check at runtime. Setting incorrect shapes can result in inconsistencies between the statically-known graph and the runtime value of tensors. Args: shape: A `TensorShape` representing the shape of this tensor, a `TensorShapeProto`, a list, a tuple, or None. Raises: ValueError: If `shape` is not compatible with the current shape of this tensor. """ if not isinstance(shape, tensor_shape.TensorShape): shape = tensor_shape.TensorShape(shape) self._dense_shape_default = self._dense_shape_default.merge_with(shape) @property def graph(self): """The `Graph` that contains the index, value, and dense_shape tensors.""" return self._indices.graph def __repr__(self): return "SparseTensor(indices=%s, values=%s, dense_shape=%s)" % ( self._indices, self._values, self._dense_shape) def eval(self, feed_dict=None, session=None): """Evaluates this sparse tensor in a `Session`. Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor. *N.B.* Before invoking `SparseTensor.eval()`, its graph must have been launched in a session, and either a default session must be available, or `session` must be specified explicitly. Args: feed_dict: A dictionary that maps `Tensor` objects to feed values. See `tf.Session.run` for a description of the valid feed values. session: (Optional.) The `Session` to be used to evaluate this sparse tensor. If none, the default session will be used. Returns: A `SparseTensorValue` object. """ indices, values, dense_shape = _eval_using_default_session( [self.indices, self.values, self.dense_shape], feed_dict, self.graph, session) return SparseTensorValue(indices, values, dense_shape) @staticmethod def _override_operator(operator, func): _override_helper(SparseTensor, operator, func) @property def _type_spec(self): return SparseTensorSpec(self.shape, self.dtype) def _shape_invariant_to_type_spec(self, shape): # From the tf.while_loop docs: "If a loop variable is a SparseTensor, the # shape invariant must be TensorShape([r]) where r is the rank of the dense # tensor represented by the sparse tensor. It means the shapes of the three # tensors of the SparseTensor are ([None], [None, r], [r]). NOTE: The shape # invariant here is the shape of the SparseTensor.dense_shape property. It # must be the shape of a vector. if shape.ndims is not None and shape.ndims != 1: raise ValueError(f"Expected a shape with 1 dimension. Obtained: {shape} " f"which has {shape.ndims} dimensions.") rank = tensor_shape.dimension_value(shape[0]) return SparseTensorSpec(tensor_shape.unknown_shape(rank), self.dtype) def consumers(self): return self._consumers() def _numpy(self): """Returns a numpy `array` with the values for this `SparseTensor`. Requires that this `SparseTensor` was constructed in eager execution mode. """ if not self._is_eager(): raise ValueError("SparseTensor.numpy() is only supported in eager mode.") arr = np.zeros(self.dense_shape, dtype=self.dtype.as_numpy_dtype()) for i, v in zip(self.indices, self.values): arr[tuple(i)] = v return arr def _is_eager(self): """Returns True if this `SparseTensor` was constructed in eager execution. Requires that each individual component of `SparseTensor` (`indices`, `values` and `dense_shape`) is an instance of `EagerTensor`. """ return all( isinstance(t, ops.EagerTensor) for t in (self.indices, self.values, self.dense_shape)) SparseTensorValue = collections.namedtuple("SparseTensorValue", ["indices", "values", "dense_shape"]) tf_export(v1=["SparseTensorValue"])(SparseTensorValue) @tf_export("SparseTensorSpec") @type_spec_registry.register("tf.SparseTensorSpec")
SparseTensor
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial006_py39.py
{ "start": 170, "end": 519 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: set[str] = set() images: Union[list[Image], None] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
Item
python
google__pytype
pytype/tests/test_dict1.py
{ "start": 139, "end": 3635 }
class ____(test_base.BaseTest): """Tests for dictionaries.""" def test_pop(self): ty = self.Infer(""" d = {"a": 42} v1 = d.pop("a") v2 = d.pop("b", None) """) self.assertTypesMatchPytd( ty, """ from typing import Dict d = ... # type: Dict[str, int] v1 = ... # type: int v2 = ... # type: None """, ) def test_bad_pop(self): ty = self.Infer(""" d = {"a": 42} v = d.pop("b") """) self.assertTypesMatchPytd( ty, """ from typing import Any, Dict d = ... # type: Dict[str, int] v = ... # type: Any """, ) def test_ambiguous_pop(self): ty = self.Infer(""" d = {"a": 42} k = None # type: str v1 = d.pop(k) v2 = d.pop(k, None) """) self.assertTypesMatchPytd( ty, """ from typing import Dict, Optional d = ... # type: Dict[str, int] k = ... # type: str v1 = ... # type: int v2 = ... # type: Optional[int] """, ) def test_pop_from_ambiguous_dict(self): ty = self.Infer(""" d = {} k = None # type: str v = None # type: int d[k] = v v1 = d.pop("a") v2 = d.pop("a", None) """) self.assertTypesMatchPytd( ty, """ from typing import Dict, Optional d = ... # type: Dict[str, int] k = ... # type: str v = ... # type: int v1 = ... # type: int v2 = ... # type: Optional[int] """, ) def test_update_empty(self): ty = self.Infer(""" from typing import Dict d1 = {} d2 = None # type: Dict[str, int] d1.update(d2) """) self.assertTypesMatchPytd( ty, """ from typing import Dict d1 = ... # type: Dict[str, int] d2 = ... # type: Dict[str, int] """, ) def test_update_any_subclass(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ from typing import TypeVar T = TypeVar("T") def f(x: T, y: T = ...) -> T: ... """, ) self.Check( """ from typing import Any import foo class Foo(Any): def f(self): kwargs = {} kwargs.update(foo.f(self)) """, pythonpath=[d.path], ) def test_update_noargs(self): self.Check(""" from typing import Dict d = {} # type: Dict d.update() """) def test_determinism(self): # Regression test for code on which pytype used to be non-deterministic. canonical = None for _ in range(10): # increase the chance of finding non-determinism ty = self.Infer(""" class Foo: def __init__(self, filenames): self._dict = {} for filename in filenames: d = self._dict if __random__: d[__any_object__] = {} d = d[__any_object__] if __random__: d[__any_object__] = None """) out = pytd_utils.Print(ty) if canonical is None: canonical = out else: self.assertMultiLineEqual(canonical, out) def test_unpack_ordered_dict_value(self): self.Check(""" import collections def f(): d = collections.OrderedDict() for k, (v1, v2) in d.items(): pass f() """) if __name__ == "__main__": test_base.main()
DictTest
python
matplotlib__matplotlib
lib/matplotlib/mathtext.py
{ "start": 1013, "end": 5104 }
class ____: _parser = None _font_type_mapping = { 'cm': _mathtext.BakomaFonts, 'dejavuserif': _mathtext.DejaVuSerifFonts, 'dejavusans': _mathtext.DejaVuSansFonts, 'stix': _mathtext.StixFonts, 'stixsans': _mathtext.StixSansFonts, 'custom': _mathtext.UnicodeFonts, } def __init__(self, output): """ Create a MathTextParser for the given backend *output*. Parameters ---------- output : {"path", "agg"} Whether to return a `VectorParse` ("path") or a `RasterParse` ("agg", or its synonym "macosx"). """ self._output_type = _api.check_getitem( {"path": "vector", "agg": "raster", "macosx": "raster"}, output=output.lower()) def parse(self, s, dpi=72, prop=None, *, antialiased=None): """ Parse the given math expression *s* at the given *dpi*. If *prop* is provided, it is a `.FontProperties` object specifying the "default" font to use in the math expression, used for all non-math text. The results are cached, so multiple calls to `parse` with the same expression should be fast. Depending on the *output* type, this returns either a `VectorParse` or a `RasterParse`. """ # lru_cache can't decorate parse() directly because prop is # mutable, so we key the cache using an internal copy (see # Text._get_text_metrics_with_cache for a similar case); likewise, # we need to check the mutable state of the text.antialiased and # text.hinting rcParams. prop = prop.copy() if prop is not None else None antialiased = mpl._val_or_rc(antialiased, 'text.antialiased') from matplotlib.backends import backend_agg load_glyph_flags = { "vector": LoadFlags.NO_HINTING, "raster": backend_agg.get_hinting_flag(), }[self._output_type] return self._parse_cached(s, dpi, prop, antialiased, load_glyph_flags) @functools.lru_cache(50) def _parse_cached(self, s, dpi, prop, antialiased, load_glyph_flags): if prop is None: prop = FontProperties() fontset_class = _api.check_getitem( self._font_type_mapping, fontset=prop.get_math_fontfamily()) fontset = fontset_class(prop, load_glyph_flags) fontsize = prop.get_size_in_points() if self._parser is None: # Cache the parser globally. self.__class__._parser = _mathtext.Parser() box = self._parser.parse(s, fontset, fontsize, dpi) output = _mathtext.ship(box) if self._output_type == "vector": return output.to_vector() elif self._output_type == "raster": return output.to_raster(antialiased=antialiased) def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None, *, color=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. Parameters ---------- s : str A math expression. The math portion must be enclosed in dollar signs. filename_or_obj : str or path-like or file-like Where to write the image data. prop : `.FontProperties`, optional The size and style of the text. dpi : float, optional The output dpi. If not set, the dpi is determined as for `.Figure.savefig`. format : str, optional The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the format is determined as for `.Figure.savefig`. color : str, optional Foreground color, defaults to :rc:`text.color`. """ from matplotlib import figure parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop, color=color) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
MathTextParser
python
TheAlgorithms__Python
cellular_automata/langtons_ant.py
{ "start": 291, "end": 3430 }
class ____: """ Represents the main LangonsAnt algorithm. >>> la = LangtonsAnt(2, 2) >>> la.board [[True, True], [True, True]] >>> la.ant_position (1, 1) """ def __init__(self, width: int, height: int) -> None: # Each square is either True or False where True is white and False is black self.board = [[True] * width for _ in range(height)] self.ant_position: tuple[int, int] = (width // 2, height // 2) # Initially pointing left (similar to the wikipedia image) # (0 = 0Β° | 1 = 90Β° | 2 = 180 Β° | 3 = 270Β°) self.ant_direction: int = 3 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None: """ Performs three tasks: 1. The ant turns either clockwise or anti-clockwise according to the colour of the square that it is currently on. If the square is white, the ant turns clockwise, and if the square is black the ant turns anti-clockwise 2. The ant moves one square in the direction that it is currently facing 3. The square the ant was previously on is inverted (White -> Black and Black -> White) If display is True, the board will also be displayed on the axes >>> la = LangtonsAnt(2, 2) >>> la.move_ant(None, True, 0) >>> la.board [[True, True], [True, False]] >>> la.move_ant(None, True, 0) >>> la.board [[True, False], [True, False]] """ directions = { 0: (-1, 0), # 0Β° 1: (0, 1), # 90Β° 2: (1, 0), # 180Β° 3: (0, -1), # 270Β° } x, y = self.ant_position # Turn clockwise or anti-clockwise according to colour of square if self.board[x][y] is True: # The square is white so turn 90Β° clockwise self.ant_direction = (self.ant_direction + 1) % 4 else: # The square is black so turn 90Β° anti-clockwise self.ant_direction = (self.ant_direction - 1) % 4 # Move ant move_x, move_y = directions[self.ant_direction] self.ant_position = (x + move_x, y + move_y) # Flip colour of square self.board[x][y] = not self.board[x][y] if display and axes: # Display the board on the axes axes.get_xaxis().set_ticks([]) axes.get_yaxis().set_ticks([]) axes.imshow(self.board, cmap="gray", interpolation="nearest") def display(self, frames: int = 100_000) -> None: """ Displays the board without delay in a matplotlib plot to visually understand and track the ant. >>> _ = LangtonsAnt(WIDTH, HEIGHT) """ fig, ax = plt.subplots() # Assign animation to a variable to prevent it from getting garbage collected self.animation = FuncAnimation( fig, partial(self.move_ant, ax, True), frames=frames, interval=1 ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() LangtonsAnt(WIDTH, HEIGHT).display()
LangtonsAnt
python
pypa__hatch
backend/src/hatchling/builders/sdist.py
{ "start": 5496, "end": 13558 }
class ____(BuilderInterface): """ Build an archive of the source files """ PLUGIN_NAME = "sdist" def get_version_api(self) -> dict[str, Callable]: return {"standard": self.build_standard} def get_default_versions(self) -> list[str]: # noqa: PLR6301 return ["standard"] def clean( # noqa: PLR6301 self, directory: str, versions: list[str], # noqa: ARG002 ) -> None: for filename in os.listdir(directory): if filename.endswith(".tar.gz"): os.remove(os.path.join(directory, filename)) def build_standard(self, directory: str, **build_data: Any) -> str: found_packages = set() with SdistArchive(self.artifact_project_id, reproducible=self.config.reproducible) as archive: for included_file in self.recurse_included_files(): if self.config.support_legacy: possible_package, file_name = os.path.split(included_file.relative_path) if file_name == "__init__.py": found_packages.add(possible_package) tar_info = archive.gettarinfo( included_file.path, arcname=normalize_archive_path( os.path.join(self.artifact_project_id, included_file.distribution_path) ), ) if tar_info is None: # no cov continue if tar_info.isfile(): with open(included_file.path, "rb") as f: archive.addfile(tar_info, f) else: # no cov # TODO: Investigate if this is necessary (for symlinks, etc.) archive.addfile(tar_info) archive.create_file( self.config.core_metadata_constructor(self.metadata, extra_dependencies=build_data["dependencies"]), "PKG-INFO", ) if self.config.support_legacy: archive.create_file( self.construct_setup_py_file(sorted(found_packages), extra_dependencies=build_data["dependencies"]), "setup.py", ) target = os.path.join(directory, f"{self.artifact_project_id}.tar.gz") replace_file(archive.path, target) normalize_artifact_permissions(target) return target @property def artifact_project_id(self) -> str: return ( self.project_id if self.config.strict_naming else f"{self.normalize_file_name_component(self.metadata.core.raw_name)}-{self.metadata.version}" ) def construct_setup_py_file(self, packages: list[str], extra_dependencies: tuple[()] = ()) -> str: contents = "from setuptools import setup\n\n" contents += "setup(\n" contents += f" name={self.metadata.core.name!r},\n" contents += f" version={self.metadata.version!r},\n" if self.metadata.core.description: contents += f" description={self.metadata.core.description!r},\n" if self.metadata.core.readme: contents += f" long_description={self.metadata.core.readme!r},\n" authors_data = self.metadata.core.authors_data if authors_data["name"]: contents += f" author={', '.join(authors_data['name'])!r},\n" if authors_data["email"]: contents += f" author_email={', '.join(authors_data['email'])!r},\n" maintainers_data = self.metadata.core.maintainers_data if maintainers_data["name"]: contents += f" maintainer={', '.join(maintainers_data['name'])!r},\n" if maintainers_data["email"]: contents += f" maintainer_email={', '.join(maintainers_data['email'])!r},\n" if self.metadata.core.classifiers: contents += " classifiers=[\n" for classifier in self.metadata.core.classifiers: contents += f" {classifier!r},\n" contents += " ],\n" dependencies = list(self.metadata.core.dependencies) dependencies.extend(extra_dependencies) if dependencies: contents += " install_requires=[\n" for raw_specifier in dependencies: specifier = raw_specifier.replace("'", '"') contents += f" {specifier!r},\n" contents += " ],\n" if self.metadata.core.optional_dependencies: contents += " extras_require={\n" for option, specifiers in self.metadata.core.optional_dependencies.items(): if not specifiers: continue contents += f" {option!r}: [\n" for raw_specifier in specifiers: specifier = raw_specifier.replace("'", '"') contents += f" {specifier!r},\n" contents += " ],\n" contents += " },\n" if self.metadata.core.scripts or self.metadata.core.gui_scripts or self.metadata.core.entry_points: contents += " entry_points={\n" if self.metadata.core.scripts: contents += " 'console_scripts': [\n" for name, object_ref in self.metadata.core.scripts.items(): contents += f" '{name} = {object_ref}',\n" contents += " ],\n" if self.metadata.core.gui_scripts: contents += " 'gui_scripts': [\n" for name, object_ref in self.metadata.core.gui_scripts.items(): contents += f" '{name} = {object_ref}',\n" contents += " ],\n" if self.metadata.core.entry_points: for group, entry_points in self.metadata.core.entry_points.items(): contents += f" {group!r}: [\n" for name, object_ref in entry_points.items(): contents += f" '{name} = {object_ref}',\n" contents += " ],\n" contents += " },\n" if packages: src_layout = False contents += " packages=[\n" for package in packages: if package.startswith(f"src{os.sep}"): src_layout = True contents += f" {package.replace(os.sep, '.')[4:]!r},\n" else: contents += f" {package.replace(os.sep, '.')!r},\n" contents += " ],\n" if src_layout: contents += " package_dir={'': 'src'},\n" contents += ")\n" return contents def get_default_build_data(self) -> dict[str, Any]: force_include = {} for filename in ["pyproject.toml", DEFAULT_CONFIG_FILE, DEFAULT_BUILD_SCRIPT]: path = os.path.join(self.root, filename) if os.path.exists(path): force_include[path] = filename build_data = {"force_include": force_include, "dependencies": []} for exclusion_files in self.config.vcs_exclusion_files.values(): for exclusion_file in exclusion_files: force_include[exclusion_file] = os.path.basename(exclusion_file) readme_path = self.metadata.core.readme_path if readme_path: readme_path = normalize_relative_path(readme_path) force_include[os.path.join(self.root, readme_path)] = readme_path license_files = self.metadata.core.license_files if license_files: for license_file in license_files: relative_path = normalize_relative_path(license_file) force_include[os.path.join(self.root, relative_path)] = relative_path return build_data @classmethod def get_config_class(cls) -> type[SdistBuilderConfig]: return SdistBuilderConfig
SdistBuilder
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor31.py
{ "start": 372, "end": 448 }
class ____(tuple[list]): ... x1: Iterable[NT | Sequence] = list(zip(list1))
NT
python
Lightning-AI__lightning
src/lightning/pytorch/plugins/layer_sync.py
{ "start": 726, "end": 1189 }
class ____(ABC): """Abstract base class for creating plugins that wrap layers of a model with synchronization logic for multiprocessing.""" @abstractmethod def apply(self, model: Module) -> Module: """Override this method to apply synchronization to the layers of this model.""" @abstractmethod def revert(self, model: Module) -> Module: """Override this method to undo all modifications made in :meth:`apply`."""
LayerSync
python
kamyu104__LeetCode-Solutions
Python/find-minimum-diameter-after-merging-two-trees.py
{ "start": 4136, "end": 5402 }
class ____(object): def minimumDiameterAfterMerge(self, edges1, edges2): """ :type edges1: List[List[int]] :type edges2: List[List[int]] :rtype: int """ def ceil_divide(a, b): return (a+b-1)//2 def tree_diameter(edges): def bfs(root): d = new_root = -1 lookup = [False]*len(adj) lookup[root] = True q = [root] while q: d, new_root = d+1, q[0] new_q = [] for u in q: for v in adj[u]: if lookup[v]: continue lookup[v] = True new_q.append(v) q = new_q return d, new_root adj = [[] for _ in range(len(edges)+1)] for u, v in edges: adj[u].append(v) adj[v].append(u) _, root = bfs(0) d, _ = bfs(root) return d d1 = tree_diameter(edges1) d2 = tree_diameter(edges2) return max(ceil_divide(d1, 2)+1+ceil_divide(d2, 2), d1, d2)
Solution4
python
realpython__materials
python-docstrings/minipotion.py
{ "start": 39, "end": 150 }
class ____(Potion): pass help(MiniPotion) print(MiniPotion.__doc__) print(MiniPotion.brew.__doc__)
MiniPotion
python
ray-project__ray
release/train_tests/benchmark/config.py
{ "start": 883, "end": 1341 }
class ____(DataLoaderConfig): # NOTE: Optional[int] doesn't play well with argparse. local_buffer_shuffle_size: int = -1 enable_operator_progress_bars: bool = True ray_data_prefetch_batches: int = 4 ray_data_override_num_blocks: int = -1 locality_with_output: bool = False actor_locality_enabled: bool = True enable_shard_locality: bool = True preserve_order: bool = False ray_data_pin_memory: bool = False
RayDataConfig
python
apache__airflow
scripts/ci/prek/common_prek_utils.py
{ "start": 9732, "end": 16977 }
class ____(difflib.Differ): def _dump(self, tag, x, lo, hi): """Generate comparison results for a same-tagged range.""" for i in range(lo, hi): if tag == "+": yield f"[green]{tag} {x[i]}[/]" elif tag == "-": yield f"[red]{tag} {x[i]}[/]" else: yield f"{tag} {x[i]}" def check_list_sorted(the_list: list[str], message: str, errors: list[str]) -> bool: sorted_list = sorted(set(the_list)) if the_list == sorted_list: console.print(f"{message} is [green]ok[/]") console.print(the_list) console.print() return True console.print(f"{message} [red]NOK[/]") console.print(textwrap.indent("\n".join(ConsoleDiff().compare(the_list, sorted_list)), " " * 4)) console.print() errors.append(f"ERROR in {message}. The elements are not sorted/unique.") return False def validate_cmd_result(cmd_result, include_ci_env_check=False): if include_ci_env_check: if cmd_result.returncode != 0 and os.environ.get("CI") != "true": if console: console.print( "\n[yellow]If you see strange stacktraces above, especially about missing imports " "run this command:[/]\n" ) console.print( "[magenta]breeze ci-image build --python 3.10 --upgrade-to-newer-dependencies[/]\n" ) else: print( "\nIf you see strange stacktraces above, especially about missing imports " "run this command:\nbreeze ci-image build --python 3.10 --upgrade-to-newer-dependencies\n" ) elif cmd_result.returncode != 0: if console: console.print( "[warning]\nIf you see strange stacktraces above, " "run `breeze ci-image build --python 3.10` and try again." ) else: print( "\nIf you see strange stacktraces above, " "run `breeze ci-image build --python 3.10` and try again." ) sys.exit(cmd_result.returncode) def get_provider_id_from_path(file_path: Path) -> str | None: """ Get the provider id from the path of the file it belongs to. """ for parent in file_path.parents: # This works fine for both new and old providers structure - because we moved provider.yaml to # the top-level of the provider and this code finding "providers" will find the "providers" package # in old structure and "providers" directory in new structure - in both cases we can determine # the provider id from the relative folders if (parent / "provider.yaml").exists(): for providers_root_candidate in parent.parents: if providers_root_candidate.name == "providers": return parent.relative_to(providers_root_candidate).as_posix().replace("/", ".") return None return None def get_provider_base_dir_from_path(file_path: Path) -> Path | None: """ Get the provider base dir (where provider.yaml is) from the path of the file it belongs to. """ for parent in file_path.parents: if (parent / "provider.yaml").exists(): return parent return None def get_all_provider_ids() -> list[str]: """ Get all providers from the new provider structure """ all_provider_ids = [] for provider_file in AIRFLOW_PROVIDERS_ROOT_PATH.rglob("provider.yaml"): if provider_file.is_relative_to(AIRFLOW_PROVIDERS_ROOT_PATH / "src"): continue provider_id = get_provider_id_from_path(provider_file) if provider_id: all_provider_ids.append(provider_id) return all_provider_ids def get_all_provider_yaml_files() -> list[Path]: """ Get all providers from the new provider structure """ all_provider_yaml_files = [] for provider_file in AIRFLOW_PROVIDERS_ROOT_PATH.rglob("provider.yaml"): if provider_file.is_relative_to(AIRFLOW_PROVIDERS_ROOT_PATH / "src"): continue all_provider_yaml_files.append(provider_file) return all_provider_yaml_files def get_all_provider_info_dicts() -> dict[str, dict]: """ Get provider yaml info for all providers from the new provider structure """ providers: dict[str, dict] = {} for provider_file in get_all_provider_yaml_files(): provider_id = str(provider_file.parent.relative_to(AIRFLOW_PROVIDERS_ROOT_PATH)).replace(os.sep, ".") import yaml provider_info = yaml.safe_load(provider_file.read_text()) if provider_info["state"] != "suspended": providers[provider_id] = provider_info return providers def get_imports_from_file(file_path: Path, *, only_top_level: bool) -> list[str]: """ Returns list of all imports in file. For following code: import os from collections import defaultdict import numpy as np from pandas import DataFrame as DF def inner(): import json from pathlib import Path, PurePath from __future__ import annotations When only_top_level = False then returns ['os', 'collections.defaultdict', 'numpy', 'pandas.DataFrame'] When only_top_level = False then returns ['os', 'collections.defaultdict', 'numpy', 'pandas.DataFrame', 'json', 'pathlib.Path', 'pathlib.PurePath'] """ root = ast.parse(file_path.read_text(), file_path.name) imports: list[str] = [] nodes = ast.iter_child_nodes(root) if only_top_level else ast.walk(root) for node in nodes: if isinstance(node, ast.Import): for alias in node.names: imports.append(alias.name) elif isinstance(node, ast.ImportFrom): if node.module == "__future__": continue for alias in node.names: name = alias.name fullname = f"{node.module}.{name}" if node.module else name imports.append(fullname) return imports def retrieve_gh_token(*, token: str | None = None, description: str, scopes: str) -> str: if token: return token if GITHUB_TOKEN: return GITHUB_TOKEN output = subprocess.check_output(["gh", "auth", "token"]) token = output.decode().strip() if not token: if not console: raise RuntimeError("Please add rich to your script dependencies and run it again") console.print( "[red]GITHUB_TOKEN environment variable is not set. " "This might lead to failures on rate limits.[/]\n" "You can fix that by installing `gh` and running `gh auth login` or " f"set it to a valid GitHub token with {scopes} scope. " f"You can create one by clicking the URL:\n\n" f"https://github.com/settings/tokens/new?scopes={scopes}&description={description}\n\n" "Once you have the token you can prepend prek command with GITHUB_TOKEN='<your token>' or" "set it in your environment with export GITHUB_TOKEN='<your token>'\n\n" ) sys.exit(1) return token
ConsoleDiff
python
google__jax
jax/_src/state/discharge.py
{ "start": 4191, "end": 4461 }
class ____: env: dict[core.Var, Any] def read(self, v: core.Atom) -> Any: if type(v) is core.Literal: return v.val assert isinstance(v, core.Var) return self.env[v] def write(self, v: core.Var, val: Any) -> None: self.env[v] = val
Environment
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_indexing.py
{ "start": 17843, "end": 22017 }
class ____: @td.skip_if_no("pyarrow") @pytest.mark.parametrize("as_td", [True, False]) def test_get_indexer_pyarrow(self, as_td): # GH#62277 index = date_range("2016-01-01", periods=3) target = index.astype("timestamp[ns][pyarrow]")[::-1] if as_td: # Test duration dtypes while we're here index = index - index[0] target = target - target[-1] result = index.get_indexer(target) expected = np.array([2, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) # Reversed op should work the same result2 = target.get_indexer(index) tm.assert_numpy_array_equal(result2, expected) def test_get_indexer_date_objs(self): rng = date_range("1/1/2000", periods=20) result = rng.get_indexer(rng.map(lambda x: x.date())) expected = rng.get_indexer(rng) tm.assert_numpy_array_equal(result, expected) def test_get_indexer(self): idx = date_range("2000-01-01", periods=3) exp = np.array([0, 1, 2], dtype=np.intp) tm.assert_numpy_array_equal(idx.get_indexer(idx), exp) target = idx[0] + pd.to_timedelta(["-1 hour", "12 hours", "1 day 1 hour"]) tm.assert_numpy_array_equal( idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp) ) tm.assert_numpy_array_equal( idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp) ) tm.assert_numpy_array_equal( idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp) ) tm.assert_numpy_array_equal( idx.get_indexer(target, "nearest", tolerance=pd.Timedelta("1 hour")), np.array([0, -1, 1], dtype=np.intp), ) tol_raw = [ pd.Timedelta("1 hour"), pd.Timedelta("1 hour"), pd.Timedelta("1 hour").to_timedelta64(), ] tm.assert_numpy_array_equal( idx.get_indexer( target, "nearest", tolerance=[np.timedelta64(x) for x in tol_raw] ), np.array([0, -1, 1], dtype=np.intp), ) tol_bad = [ pd.Timedelta("2 hour").to_timedelta64(), pd.Timedelta("1 hour").to_timedelta64(), "foo", ] msg = "Could not convert 'foo' to NumPy timedelta" with pytest.raises(ValueError, match=msg): idx.get_indexer(target, "nearest", tolerance=tol_bad) with pytest.raises(ValueError, match="abbreviation w/o a number"): idx.get_indexer(idx[[0]], method="nearest", tolerance="foo") @pytest.mark.parametrize( "target", [ [date(2020, 1, 1), Timestamp("2020-01-02")], [Timestamp("2020-01-01"), date(2020, 1, 2)], ], ) def test_get_indexer_mixed_dtypes(self, target): # https://github.com/pandas-dev/pandas/issues/33741 values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) result = values.get_indexer(target) expected = np.array([0, 1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize( "target, positions", [ ([date(9999, 1, 1), Timestamp("2020-01-01")], [-1, 0]), ([Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]), ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), ], ) def test_get_indexer_out_of_bounds_date(self, target, positions): values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) result = values.get_indexer(target) expected = np.array(positions, dtype=np.intp) tm.assert_numpy_array_equal(result, expected) def test_get_indexer_pad_requires_monotonicity(self): rng = date_range("1/1/2000", "3/1/2000", freq="B") # neither monotonic increasing or decreasing rng2 = rng[[1, 0, 2]] msg = "index must be monotonic increasing or decreasing" with pytest.raises(ValueError, match=msg): rng2.get_indexer(rng, method="pad")
TestGetIndexer
python
plotly__plotly.py
tests/test_core/test_graph_objs/test_property_assignment.py
{ "start": 103, "end": 4030 }
class ____(TestCase): def setUp(self): # Construct initial scatter object self.scatter = go.Scatter(name="scatter A") # Assert initial state d1, d2 = strip_dict_params( self.scatter, {"type": "scatter", "name": "scatter A"} ) assert d1 == d2 # Construct expected results self.expected_toplevel = { "type": "scatter", "name": "scatter A", "fillcolor": "green", } self.expected_nested = { "type": "scatter", "name": "scatter A", "marker": {"colorbar": {"title": {"font": {"family": "courier"}}}}, } self.expected_nested_error_x = { "type": "scatter", "name": "scatter A", "error_x": {"type": "percent"}, } def test_toplevel_attr(self): assert self.scatter.fillcolor is None self.scatter.fillcolor = "green" assert self.scatter.fillcolor == "green" d1, d2 = strip_dict_params(self.scatter, self.expected_toplevel) assert d1 == d2 def test_toplevel_item(self): assert self.scatter["fillcolor"] is None self.scatter["fillcolor"] = "green" assert self.scatter["fillcolor"] == "green" d1, d2 = strip_dict_params(self.scatter, self.expected_toplevel) assert d1 == d2 def test_nested_attr(self): assert self.scatter.marker.colorbar.title.font.family is None self.scatter.marker.colorbar.title.font.family = "courier" assert self.scatter.marker.colorbar.title.font.family == "courier" d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_item(self): assert self.scatter["marker"]["colorbar"]["title"]["font"]["family"] is None self.scatter["marker"]["colorbar"]["title"]["font"]["family"] = "courier" assert ( self.scatter["marker"]["colorbar"]["title"]["font"]["family"] == "courier" ) d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_item_dots(self): assert self.scatter["marker.colorbar.title.font.family"] is None self.scatter["marker.colorbar.title.font.family"] = "courier" assert self.scatter["marker.colorbar.title.font.family"] == "courier" d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_item_tuple(self): assert self.scatter["marker.colorbar.title.font.family"] is None self.scatter[("marker", "colorbar", "title.font", "family")] = "courier" assert self.scatter[("marker", "colorbar", "title.font", "family")] == "courier" d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_update(self): self.scatter.update( marker={"colorbar": {"title": {"font": {"family": "courier"}}}} ) assert ( self.scatter[("marker", "colorbar", "title", "font", "family")] == "courier" ) d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_update_dots(self): assert self.scatter["marker.colorbar.title.font.family"] is None self.scatter.update({"marker.colorbar.title.font.family": "courier"}) assert self.scatter["marker.colorbar.title.font.family"] == "courier" d1, d2 = strip_dict_params(self.scatter, self.expected_nested) assert d1 == d2 def test_nested_update_underscores(self): assert self.scatter["error_x.type"] is None self.scatter.update({"error_x_type": "percent"}) assert self.scatter["error_x_type"] == "percent" d1, d2 = strip_dict_params(self.scatter, self.expected_nested_error_x) assert d1 == d2
TestAssignmentPrimitive
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 4362, "end": 4486 }
class ____(torch.nn.Module): @staticmethod def forward(x): return x * torch.sigmoid(x)
ModuleWithStaticForward
python
getsentry__sentry
src/sentry/reprocessing2.py
{ "start": 7183, "end": 26897 }
class ____: event: Event | GroupEvent data: dict[str, Any] attachments: list[EventAttachment] def pull_event_data(project_id: int, event_id: str) -> ReprocessableEvent: from sentry.lang.native.processing import get_required_attachment_types with sentry_sdk.start_span(op="reprocess_events.eventstore.get"): event = eventstore.backend.get_event_by_id(project_id, event_id) if event is None: raise CannotReprocess("event.not_found") with sentry_sdk.start_span(op="reprocess_events.nodestore.get"): node_id = Event.generate_node_id(project_id, event_id) data = nodestore.backend.get(node_id, subkey="unprocessed") # Check data after checking presence of event to avoid too many instances. if data is None: raise CannotReprocess("unprocessed_event.not_found") required_attachment_types = get_required_attachment_types(data) attachments = list( EventAttachment.objects.filter( project_id=project_id, event_id=event_id, type__in=list(required_attachment_types) ) ) missing_attachment_types = required_attachment_types - {ea.type for ea in attachments} if missing_attachment_types: # Without the missing attachment, the event cannot be symbolicated, so # reprocessing will fall back to the unprocessed event JSON submitted by relay. # This event JSON only contains a placeholder exception but no usable stack trace. # See `write_native_placeholder` in relay. raise CannotReprocess("attachment.not_found") return ReprocessableEvent(event=event, data=data, attachments=attachments) def reprocess_event(project_id: int, event_id: str, start_time: float) -> None: from sentry.ingest.consumer.processors import CACHE_TIMEOUT from sentry.tasks.store import preprocess_event_from_reprocessing reprocessable_event = pull_event_data(project_id, event_id) data = reprocessable_event.data event = reprocessable_event.event attachments = reprocessable_event.attachments # Step 1: Copy attachments into attachment cache. Note that we can only # consider minidumps because filestore just stays as-is after reprocessing # (we simply update group_id on the EventAttachment models in post_process) project = Project.objects.get_from_cache(id=project_id) cache_key = cache_key_for_event(data) attachment_objects = [] for attachment_id, attachment in enumerate(attachments): with sentry_sdk.start_span(op="reprocess_event._maybe_copy_attachment_into_cache") as span: span.set_data("attachment_id", attachment.id) attachment_objects.append( _maybe_copy_attachment_into_cache( project=project, attachment_id=attachment_id, attachment=attachment, cache_key=cache_key, cache_timeout=CACHE_TIMEOUT, ) ) if attachment_objects: store_attachments_for_event(project, data, attachment_objects, timeout=CACHE_TIMEOUT) # Step 2: Fix up the event payload for reprocessing and put it in event # cache/event_processing_store set_path(data, "contexts", "reprocessing", "original_issue_id", value=event.group_id) set_path( data, "contexts", "reprocessing", "original_primary_hash", value=event.get_primary_hash() ) event_processing_store.store(data) preprocess_event_from_reprocessing( cache_key=cache_key, start_time=start_time, event_id=event_id, data=data, ) def get_original_group_id(event: Event) -> int: return event.data["contexts"]["reprocessing"]["original_issue_id"] def get_original_primary_hash(event: Event) -> str | None: return get_path(event.data, "contexts", "reprocessing", "original_primary_hash") def _send_delete_old_primary_hash_messages( project_id: int, group_id: int, old_primary_hashes: set[str], force_flush_batch: bool, ) -> None: # Events for a group are split and bucketed by their primary hashes. If flushing is to be # performed on a per-group basis, the event count needs to be summed up across all buckets # belonging to a single group. event_count = reprocessing_store.event_count_for_hashes( project_id, group_id, old_primary_hashes ) if ( not force_flush_batch and event_count <= settings.SENTRY_REPROCESSING_REMAINING_EVENTS_BUF_SIZE ): return for primary_hash in old_primary_hashes: event_ids, from_date, to_date = reprocessing_store.pop_batched_events( project_id, group_id, primary_hash ) # Racing might be happening between two different tasks. Give up on the # task that's lagging behind by prematurely terminating flushing. if len(event_ids) == 0: logger.error("reprocessing2.buffered_delete_old_primary_hash.empty_batch") return from sentry import eventstream assert primary_hash is not None # In the worst case scenario, a group will have a 1:1 mapping of primary hashes to # events, which means 1 insert per event. # The overall performance of this will be marginally better than the unbatched version # if a group has a lot of old primary hashes. eventstream.backend.tombstone_events_unsafe( project_id, event_ids, old_primary_hash=primary_hash, from_timestamp=from_date, to_timestamp=to_date, ) # Try to track counts so if it turns out that tombstoned events trend towards a ratio of 1 # event per hash, a different solution may need to be considered. ratio = 0 if len(old_primary_hashes) == 0 else event_count / len(old_primary_hashes) metrics.distribution( key="reprocessing2.buffered_delete_old_primary_hash.event_count", value=event_count, ) metrics.distribution( key="reprocessing2.buffered_delete_old_primary_hash.primary_hash_count", value=len(old_primary_hashes), ) metrics.distribution( key="reprocessing2.buffered_delete_old_primary_hash.primary_hash_to_event_ratio", value=ratio, ) def buffered_delete_old_primary_hash( project_id: int, group_id: int, event_id: str | None = None, datetime: datetime | None = None, old_primary_hash: str | None = None, current_primary_hash: str | None = None, force_flush_batch: bool = False, ) -> None: """ In case the primary hash changed during reprocessing, we need to tell Snuba before reinserting the event. Snuba may then insert a tombstone row depending on whether the primary_hash is part of the PK/sortkey or not. Only when the primary_hash changed and is part of the sortkey, we need to explicitly tombstone the old row. If the primary_hash is not part of the PK/sortkey, or if the primary_hash did not change, nothing needs to be done as ClickHouse's table merge will merge the two rows together. Like `buffered_handle_remaining_events`, this is a quick and dirty way to batch event IDs so requests to tombstone rows are not being individually sent over to Snuba. This also includes the same constraints for optimal performance as `buffered_handle_remaining_events` in that events being fed to this should have datetimes as close to each other as possible. Unfortunately, this function is invoked by tasks that are run asynchronously and therefore the guarantee from `buffered_handle_remaining_events` regarding events being sorted by timestamps is not applicable here. This function also does not batch events which have different old primary hashes together into one operation. This means that if the data being fed in tends to have a 1:1 ratio of event:old primary hashes, then the buffering in this effectively does nothing. """ from sentry import killswitches if killswitches.killswitch_matches_context( "reprocessing2.drop-delete-old-primary-hash", {"project_id": project_id} ): return old_primary_hashes = reprocessing_store.get_old_primary_hashes(project_id, group_id) if ( event_id is not None and datetime is not None and old_primary_hash is not None and old_primary_hash != current_primary_hash ): reprocessing_store.expire_hash(project_id, group_id, event_id, datetime, old_primary_hash) if old_primary_hash not in old_primary_hashes: old_primary_hashes.add(old_primary_hash) reprocessing_store.add_hash(project_id, group_id, old_primary_hash) scope = sentry_sdk.get_isolation_scope() scope.set_tag("project_id", project_id) scope.set_tag("old_group_id", group_id) scope.set_tag("old_primary_hash", old_primary_hash) with sentry_sdk.start_span( op="sentry.reprocessing2.buffered_delete_old_primary_hash.flush_events" ): _send_delete_old_primary_hash_messages( project_id, group_id, old_primary_hashes, force_flush_batch ) def _maybe_copy_attachment_into_cache( project: Project, attachment_id: int, attachment: EventAttachment, cache_key: str, cache_timeout: int, ) -> CachedAttachment: stored_id = None chunks = None if in_random_rollout("objectstore.enable_for.attachments"): blob_path = attachment.blob_path or "" if blob_path.startswith(V2_PREFIX): # in case the attachment is already stored in objectstore, there is nothing to do stored_id = blob_path.removeprefix(V2_PREFIX) else: # otherwise, we store it in objectstore with attachment.getfile() as fp: stored_id = get_attachments_session(project.organization_id, project.id).put(fp) # but we then also make that storage permanent, as otherwise # the codepaths won’t be cleaning up this stored file. # essentially this means we are moving the file from the previous storage # into objectstore at this point. attachment.blob_path = V2_PREFIX + stored_id attachment.save() if blob_path.startswith(V1_PREFIX): storage = get_storage() storage.delete(blob_path) else: # when not using objectstore, store chunks in the attachment cache with attachment.getfile() as fp: chunk_index = 0 size = 0 while True: chunk = fp.read(settings.SENTRY_REPROCESSING_ATTACHMENT_CHUNK_SIZE) if not chunk: break size += len(chunk) attachment_cache.set_chunk( key=cache_key, id=attachment_id, chunk_index=chunk_index, chunk_data=chunk, timeout=cache_timeout, ) chunk_index += 1 assert size == attachment.size chunks = chunk_index return CachedAttachment( key=cache_key, id=attachment_id, name=attachment.name, content_type=attachment.content_type, type=attachment.type, size=attachment.size, stored_id=stored_id, chunks=chunks, ) def is_reprocessed_event(data: Mapping[str, Any]) -> bool: return bool(_get_original_issue_id(data)) def _get_original_issue_id(data: Mapping[str, Any]) -> int | None: return get_path(data, "contexts", "reprocessing", "original_issue_id") def buffered_handle_remaining_events( project_id: int, old_group_id: int, new_group_id: int, datetime_to_event: list[tuple[datetime, str]], remaining_events: str, force_flush_batch: bool = False, ) -> None: """ A quick-and-dirty wrapper around `handle_remaining_events` that batches up event IDs in Redis. We need this because Snuba cannot handle many tiny messages and prefers big ones instead. For optimal performance, the datetimes should be close to each other. This "soft" precondition is fulfilled in `reprocess_group` by iterating through events in timestamp order. Ideally we'd have batching implemented via a service like buffers, but for more than counters. """ buffered_event_count = reprocessing_store.get_remaining_event_count( project_id, old_group_id, datetime_to_event ) if ( force_flush_batch or buffered_event_count > settings.SENTRY_REPROCESSING_REMAINING_EVENTS_BUF_SIZE ): new_key = reprocessing_store.rename_key(project_id, old_group_id) if not new_key: return from sentry.tasks.reprocessing2 import handle_remaining_events handle_remaining_events.delay( project_id=project_id, old_group_id=old_group_id, new_group_id=new_group_id, remaining_events=remaining_events, event_ids_redis_key=new_key, ) def pop_batched_events_from_redis(key: str) -> tuple[list[str], datetime | None, datetime | None]: """ For redis key pointing to a list of buffered events structured like `event id;datetime of event`, returns a list of event IDs, the earliest datetime, and the latest datetime. """ return reprocessing_store.pop_batched_events_by_key(key) @overload def mark_event_reprocessed(data: MutableMapping[str, Any], *, num_events: int = 1) -> None: ... @overload def mark_event_reprocessed(*, group_id: int, project_id: int, num_events: int = 1) -> None: ... def mark_event_reprocessed( data: MutableMapping[str, Any] | None = None, *, group_id: int | None = None, project_id: int | None = None, num_events: int = 1, ) -> None: """ This function is supposed to be unconditionally called when an event has finished reprocessing, regardless of whether it has been saved or not. """ if data is not None: assert group_id is None assert project_id is None group_id = _get_original_issue_id(data) if group_id is None: return project_id = data["project"] else: assert group_id is not None assert project_id is not None result = reprocessing_store.mark_event_reprocessed(group_id, num_events) if result: from sentry.tasks.reprocessing2 import finish_reprocessing finish_reprocessing.delay(project_id=project_id, group_id=group_id) def start_group_reprocessing( project_id: int, group_id: int, remaining_events: str, max_events: int | None = None, acting_user_id: int | None = None, ) -> int: from django.db import transaction with transaction.atomic(router.db_for_write(models.Group)): group = models.Group.objects.get(id=group_id) original_status = group.status original_substatus = group.substatus if original_status == models.GroupStatus.REPROCESSING: # This is supposed to be a rather unlikely UI race when two people # click reprocessing in the UI at the same time. # # During reprocessing the button is greyed out. raise RuntimeError("Cannot reprocess group that is currently being reprocessed") original_short_id = group.short_id group.status = models.GroupStatus.REPROCESSING group.substatus = None # satisfy unique constraint of (project_id, short_id) # we manually tested that multiple groups with (project_id=1, # short_id=null) can exist in postgres group.short_id = None group.save() # Create a duplicate row that has the same attributes by nulling out # the primary key and saving group.pk = group.id = None # type: ignore[assignment] # XXX: intentional resetting pk new_group = group # rename variable just to avoid confusion del group new_group.status = original_status new_group.substatus = original_substatus new_group.short_id = original_short_id # this will be incremented by either the events that are # reprocessed, or handle_remaining_events # # XXX(markus): times_seen etc are unlikely to be correct ootb, # especially if handle_remaining_events is used a lot. new_group.times_seen = 0 new_group.save() # This migrates all models that are associated with a group but not # directly with an event, i.e. everything but event attachments and user # reports. Those other updates are run per-event (in # post-process-forwarder) to not cause too much load on pg. for model in GROUP_MODELS_TO_MIGRATE: model.objects.filter(group_id=group_id).update(group_id=new_group.id) # Get event counts of issue (for all environments etc). This was copypasted # and simplified from groupserializer. event_count = sync_count = snuba.aliased_query( aggregations=[["count()", "", "times_seen"]], # select dataset=Dataset.Events, # from conditions=[["group_id", "=", group_id], ["project_id", "=", project_id]], # where referrer="reprocessing2.start_group_reprocessing", )["data"][0]["times_seen"] sentry_sdk.set_extra("event_count", event_count) if max_events is not None: event_count = min(max_events, event_count) # Create activity on *old* group as that will serve the landing page for our # reprocessing status # # Later the activity is migrated to the new group where it is used to serve # the success message. reprocessing_activity = models.Activity.objects.create( type=ActivityType.REPROCESS.value, project=new_group.project, ident=str(group_id), group_id=group_id, user_id=acting_user_id, data={"eventCount": event_count, "oldGroupId": group_id, "newGroupId": new_group.id}, ) date_created = reprocessing_activity.datetime reprocessing_store.start_reprocessing(group_id, date_created, sync_count, event_count) return new_group.id def is_group_finished(group_id: int) -> bool: """ Checks whether a group has finished reprocessing. """ pending, _ = get_progress(group_id) return pending <= 0 def get_progress(group_id: int, project_id: int | None = None) -> tuple[int, Any | None]: pending, ttl = reprocessing_store.get_pending(group_id) info = reprocessing_store.get_progress(group_id) if pending is None: logger.error("reprocessing2.missing_counter") return 0, None if info is None: logger.error("reprocessing2.missing_info") return 0, None # We expect reprocessing to make progress every now and then, by bumping the # TTL of the "counter" key. If that TTL wasn't bumped in a while, we just # assume that reprocessing is stuck, and will just call finish on it. if project_id is not None and ttl is not None and ttl > 0: default_ttl = settings.SENTRY_REPROCESSING_SYNC_TTL age = default_ttl - ttl if age > REPROCESSING_TIMEOUT: from sentry.tasks.reprocessing2 import finish_reprocessing finish_reprocessing.delay(project_id=project_id, group_id=group_id) # Our internal sync counters are counting over *all* events, but the # progressbar in the frontend goes until max_events. Advance progressbar # proportionally. _pending = int(int(pending) * info["totalEvents"] / float(info.get("syncCount") or 1)) return _pending, info
ReprocessableEvent
python
bokeh__bokeh
tests/unit/bokeh/util/test_compiler.py
{ "start": 1914, "end": 6128 }
class ____ extends Model { static __name__ = 'MyModel'; } exports.MyModel = MyModel; """, deps=["lib/model"]) assert buc.nodejs_compile("""function f(a, b) { eturn a + b; };""", "javascript", "some.js") == \ dict(error= '\x1b[96msome.js\x1b[0m:\x1b[93m1\x1b[0m:\x1b[93m20\x1b[0m - ' '\x1b[91merror\x1b[0m\x1b[90m TS1435: \x1b[0mUnknown keyword or ' "identifier. Did you mean 'return'?\n" '\n' '\x1b[7m1\x1b[0m function f(a, b) { eturn a + b; };\n' '\x1b[7m \x1b[0m \x1b[91m ~~~~~\x1b[0m\n', ) def test_nodejs_compile_less() -> None: assert buc.nodejs_compile(""".bk-some-style { color: mix(#ff0000, #0000ff, 50%); }""", "less", "some.less") == \ dict(code=""".bk-some-style{color:#800080}""") assert buc.nodejs_compile(""".bk-some-style color: green; }""", "less", "some.less") == \ dict(error="ParseError: Unrecognised input in some.less on line 1, column 21:\n1 .bk-some-style color: green; }\n") def test_Implementation() -> None: obj = buc.Implementation() assert obj.file is None def test_Inline() -> None: obj = buc.Inline("code") assert obj.code == "code" assert obj.file is None obj = buc.Inline("code", "file") assert obj.code == "code" assert obj.file == "file" def test_TypeScript() -> None: obj = buc.TypeScript("code") assert isinstance(obj, buc.Inline) assert obj.code == "code" assert obj.file is None assert obj.lang == "typescript" def test_JavaScript() -> None: obj = buc.JavaScript("code") assert isinstance(obj, buc.Inline) assert obj.code == "code" assert obj.file is None assert obj.lang == "javascript" def test_Less() -> None: obj = buc.Less("code") assert isinstance(obj, buc.Inline) assert obj.code == "code" assert obj.file is None assert obj.lang == "less" @patch("builtins.open") def test_FromFile(mock_open: MagicMock) -> None: obj = buc.FromFile("path.ts") assert obj.lang == "typescript" obj = buc.FromFile("path.js") assert obj.lang == "javascript" obj = buc.FromFile("path.css") assert obj.lang == "less" obj = buc.FromFile("path.less") assert obj.lang == "less" def test_exts() -> None: assert buc.exts == (".ts", ".js", ".css", ".less") def test_jsons() -> None: for file in os.listdir(os.path.join(buc.bokehjs_dir, "js")): if file.endswith('.json'): with open(os.path.join(buc.bokehjs_dir, "js", file), encoding="utf-8") as f: assert all('\\' not in mod for mod in json.load(f)) def test_inline_extension() -> None: from bokeh.io import save from bokeh.models import TickFormatter from bokeh.plotting import figure from bokeh.util.compiler import TypeScript TS_CODE = """ import {TickFormatter} from "models/formatters/tick_formatter" export class TestFormatter extends TickFormatter { doFormat(ticks: number[]): string[] { if (ticks.length == 0) return[] else { const formatted = [`${ticks[0]}`] for (let i = 1; i < ticks.length; i++) { const difference = (ticks[i] - ticks[0]).toPrecision(2) formatted.push(`+${difference}}`) } return formatted } } } """ class TestFormatter(TickFormatter): __implementation__ = TypeScript(TS_CODE) class TestFormatter2(TickFormatter): __implementation__ = TypeScript("^") # invalid syntax on purpose p = figure() p.scatter([1, 2, 3, 4, 6], [5, 7, 3, 2, 4]) p.xaxis.formatter = TestFormatter() save(p) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
MyModel
python
Farama-Foundation__Gymnasium
tests/envs/registration/test_make.py
{ "start": 10373, "end": 17123 }
class ____(gym.ObservationWrapper): def __init__(self, env: Env[ObsType, ActType]): super().__init__(env) def observation(self, observation: ObsType) -> WrapperObsType: return self.observation_space.sample() def test_make_with_env_spec(): # make id_env = gym.make("CartPole-v1") spec_env = gym.make(gym.spec("CartPole-v1")) assert id_env.spec == spec_env.spec # make with applied wrappers env_2 = gym.wrappers.NormalizeReward( gym.wrappers.TimeAwareObservation( gym.wrappers.FlattenObservation( gym.make("CartPole-v1", render_mode="rgb_array") ) ), gamma=0.8, ) env_2_recreated = gym.make(env_2.spec) assert env_2.spec == env_2_recreated.spec env_2.close() env_2_recreated.close() # make with callable entry point gym.register("CartPole-v2", lambda: CartPoleEnv()) env_3 = gym.make("CartPole-v2") assert isinstance(env_3.unwrapped, CartPoleEnv) env_3.close() # make with wrapper in env-creator gym.register( "CartPole-v3", lambda: gym.wrappers.NormalizeReward(CartPoleEnv()), disable_env_checker=True, order_enforce=False, ) env_4 = gym.make(gym.spec("CartPole-v3")) assert isinstance(env_4, gym.wrappers.NormalizeReward) assert isinstance(env_4.env, CartPoleEnv) env_4.close() gym.register( "CartPole-v4", lambda: CartPoleEnv(), disable_env_checker=True, order_enforce=False, additional_wrappers=(gym.wrappers.NormalizeReward.wrapper_spec(),), ) env_5 = gym.make(gym.spec("CartPole-v4")) assert isinstance(env_5, gym.wrappers.NormalizeReward) assert isinstance(env_5.env, CartPoleEnv) env_5.close() # make with no ezpickle wrapper env_6 = NoRecordArgsWrapper(gym.make("CartPole-v1")) with pytest.raises( ValueError, match=re.escape( "NoRecordArgsWrapper wrapper does not inherit from `gymnasium.utils.RecordConstructorArgs`, therefore, the wrapper cannot be recreated." ), ): gym.make(env_6.spec) # make with no ezpickle wrapper but in the entry point gym.register( "CartPole-v5", entry_point=lambda: NoRecordArgsWrapper(CartPoleEnv()), disable_env_checker=True, order_enforce=False, ) env_7 = gym.make(gym.spec("CartPole-v5")) assert isinstance(env_7, NoRecordArgsWrapper) assert isinstance(env_7.unwrapped, CartPoleEnv) gym.register( "CartPole-v6", entry_point=lambda: CartPoleEnv(), disable_env_checker=True, order_enforce=False, additional_wrappers=(NoRecordArgsWrapper.wrapper_spec(),), ) del gym.registry["CartPole-v2"] del gym.registry["CartPole-v3"] del gym.registry["CartPole-v4"] del gym.registry["CartPole-v5"] del gym.registry["CartPole-v6"] def test_make_with_env_spec_levels(): """Test that we can recreate the environment at each 'level'.""" env = gym.wrappers.NormalizeReward( gym.wrappers.TimeAwareObservation( gym.wrappers.FlattenObservation( gym.make("CartPole-v1", render_mode="rgb_array") ) ), gamma=0.8, ) while env is not env.unwrapped: recreated_env = gym.make(env.spec) assert env.spec == recreated_env.spec env = env.env def test_wrapped_env_entry_point(): def _create_env(): _env = gym.make("CartPole-v1", render_mode="rgb_array") _env = gym.wrappers.FlattenObservation(_env) return _env gym.register("TestingEnv-v0", entry_point=_create_env) env = gym.make("TestingEnv-v0") env = gym.wrappers.TimeAwareObservation(env) env = gym.wrappers.NormalizeReward(env, gamma=0.8) recreated_env = gym.make(env.spec) obs, info = env.reset(seed=42) recreated_obs, recreated_info = recreated_env.reset(seed=42) assert data_equivalence(obs, recreated_obs) assert data_equivalence(info, recreated_info) action = env.action_space.sample() obs, reward, terminated, truncated, info = env.step(action) ( recreated_obs, recreated_reward, recreated_terminated, recreated_truncated, recreated_info, ) = recreated_env.step(action) assert data_equivalence(obs, recreated_obs) assert data_equivalence(reward, recreated_reward) assert data_equivalence(terminated, recreated_terminated) assert data_equivalence(truncated, recreated_truncated) assert data_equivalence(info, recreated_info) del gym.registry["TestingEnv-v0"] def test_make_errors(): """Test make with a deprecated environment (i.e., doesn't exist).""" with warnings.catch_warnings(record=True): with pytest.raises( gym.error.Error, match=re.escape( "Environment version v0 for `Humanoid` is deprecated. Please use `Humanoid-v5` instead." ), ): gym.make("Humanoid-v0") with pytest.raises( NameNotFound, match=re.escape("Environment `NonExistenceEnv` doesn't exist.") ): gym.make("NonExistenceEnv-v0") @pytest.fixture(scope="function") def register_parameter_envs(): gym.register( "NoMaxEpisodeStepsEnv-v0", lambda: GenericTestEnv(), max_episode_steps=None ) gym.register("OrderlessEnv-v0", lambda: GenericTestEnv(), order_enforce=False) yield del gym.registry["NoMaxEpisodeStepsEnv-v0"] del gym.registry["OrderlessEnv-v0"] @pytest.fixture(scope="function") def register_kwargs_env(): gym.register( id="test.ArgumentEnv-v0", entry_point="tests.envs.registration.utils_envs:ArgumentEnv", kwargs={ "arg1": "arg1", "arg2": "arg2", }, ) @pytest.fixture(scope="function") def register_rendering_testing_envs(): gym.register( id="NoHumanRendering-v0", entry_point="tests.envs.registration.utils_envs:NoHuman", ) gym.register( id="NoHumanRenderingOldAPI-v0", entry_point="tests.envs.registration.utils_envs:NoHumanOldAPI", ) gym.register( id="NoHumanRenderingNoRGB-v0", entry_point="tests.envs.registration.utils_envs:NoHumanNoRGB", ) gym.register( id="NoRenderModesMetadata-v0", entry_point="tests.envs.registration.utils_envs:NoRenderModesMetadata", ) yield del gym.envs.registration.registry["NoHumanRendering-v0"] del gym.envs.registration.registry["NoHumanRenderingOldAPI-v0"] del gym.envs.registration.registry["NoHumanRenderingNoRGB-v0"] del gym.envs.registration.registry["NoRenderModesMetadata-v0"]
NoRecordArgsWrapper
python
realpython__materials
dwitter-part-1/source_code_final/dwitter/admin.py
{ "start": 179, "end": 383 }
class ____(admin.ModelAdmin): model = User fields = ["username"] inlines = [ProfileInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.unregister(Group)
UserAdmin
python
facelessuser__soupsieve
tests/test_level4/test_placeholder_shown.py
{ "start": 62, "end": 3227 }
class ____(util.TestCase): """Test placeholder shown selectors.""" def test_placeholder_shown(self): """Test placeholder shown.""" markup = """ <!-- These have a placeholder. --> <input id="0" placeholder="This is some text"> <textarea id="1" placeholder="This is some text"></textarea> <!-- These do not have a placeholder. --> <input id="2" placeholder=""> <input id="3"> <!-- All types that should register has having a placeholder. --> <input id="4" type="email" placeholder="This is some text"> <input id="5" type="number" placeholder="This is some text"> <input id="6" type="password" placeholder="This is some text"> <input id="7" type="search" placeholder="This is some text"> <input id="8" type="tel" placeholder="This is some text"> <input id="9" type="text" placeholder="This is some text"> <input id="10" type="url" placeholder="This is some text"> <input id="11" type="" placeholder="This is some text"> <input id="12" type placeholder="This is some text"> <!-- Types that should not register has having a placeholder. --> <input id="13" type="button" placeholder="This is some text"> <input id="14" type="checkbox" placeholder="This is some text"> <input id="15" type="color" placeholder="This is some text"> <input id="16" type="date" placeholder="This is some text"> <input id="17" type="datetime-local" placeholder="This is some text"> <input id="18" type="file" placeholder="This is some text"> <input id="19" type="hidden" placeholder="This is some text"> <input id="20" type="image" placeholder="This is some text"> <input id="21" type="month" placeholder="This is some text"> <input id="22" type="radio" placeholder="This is some text"> <input id="23" type="range" placeholder="This is some text"> <input id="24" type="reset" placeholder="This is some text"> <input id="25" type="submit" placeholder="This is some text"> <input id="26" type="time" placeholder="This is some text"> <input id="27" type="week" placeholder="This is some text"> <!-- Value will not override this instance as value is empty. --> <input id="28" type placeholder="This is some text" value=""> <!-- Value will override this input --> <input id="29" type placeholder="This is some text" value="Actual value"> <!-- Text area content overrides the placehold--> <textarea id="30" placeholder="This is some text">Value</textarea> <textarea id="31" placeholder="This is some text"> </textarea> <!-- Text area is still considered empty with a single new line (does not include carriage return). --> <textarea id="32" placeholder="This is some text"> </textarea> """ self.assert_selector( markup, ":placeholder-shown", ['0', '1', '4', '5', '6', '7', '8', '9', '10', '11', '12', '28', '32'], flags=util.HTML )
TestPlaceholderShown
python
doocs__leetcode
solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/Solution2.py
{ "start": 0, "end": 423 }
class ____: def countMaxOrSubsets(self, nums: List[int]) -> int: n = len(nums) ans = 0 mx = 0 for mask in range(1 << n): t = 0 for i, v in enumerate(nums): if (mask >> i) & 1: t |= v if mx < t: mx = t ans = 1 elif mx == t: ans += 1 return ans
Solution
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dependent_install/package.py
{ "start": 217, "end": 717 }
class ____(Package): """Dependent which has a working install method""" homepage = "http://www.example.com" url = "http://www.example.com/a-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") version("2.0", md5="0123456789abcdef0123456789abcdef") depends_on("dependency-install@2.0", when="@2.0") depends_on("dependency-install@1.0", when="@1.0") def install(self, spec, prefix): touch(join_path(prefix, "an_installation_file"))
DependentInstall