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
walkccc__LeetCode
solutions/3339. Find the Number of K-Even Arrays/3339.py
{ "start": 0, "end": 1123 }
class ____: def countOfArrays(self, n: int, m: int, k: int) -> int: MOD = 10**9 + 7 even = m // 2 # the number of even numbers in [1, m] odd = m - even # the number of odd numbers in [1, m] # dp[i][j][0/1] := the number of arrays of length i with j consecutive even # number pairs ending in an even number (0) or an odd number (1) dp = [[[0] * 2 for _ in range(k + 1)] for _ in range(n + 1)] # Base case: arrays of length 1 # For an array of length 1, we can't have any even number pairs yet. dp[1][0][0] = even dp[1][0][1] = odd for i in range(2, n + 1): for j in range(k + 1): # 1. Appending an even number to an array ending in an even number # creates a new consecutive even number pair. # 2. Appending an even number to an array ending in an odd number. dp[i][j][0] = ((dp[i - 1][j - 1][0] if j > 0 else 0) * even + dp[i - 1][j][1] * even) % MOD # 3. Appending an odd number to an array. dp[i][j][1] = sum(dp[i - 1][j]) * odd % MOD return sum(dp[n][k]) % MOD
Solution
python
openai__openai-python
src/openai/types/responses/response_output_item_done_event.py
{ "start": 257, "end": 652 }
class ____(BaseModel): item: ResponseOutputItem """The output item that was marked done.""" output_index: int """The index of the output item that was marked done.""" sequence_number: int """The sequence number of this event.""" type: Literal["response.output_item.done"] """The type of the event. Always `response.output_item.done`."""
ResponseOutputItemDoneEvent
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 1450, "end": 6901 }
class ____(ABC): """Base class for all freshness policies. A freshness policy allows you to define expectations for the timing and frequency of asset materializations. An asset with a defined freshness policy can take on different freshness states: - ``PASS``: The asset is passing its freshness policy. - ``WARN``: The asset is close to failing its freshness policy. - ``FAIL``: The asset is failing its freshness policy. - ``UNKNOWN``: The asset has no materialization events, and the freshness state cannot be determined. If an asset does not have a freshness policy defined, it will have a freshness state of ``NOT_APPLICABLE``. This class provides static constructors for each of the supported freshness policy types. It is preferred to use these constructors to instantiate freshness policies, instead of instantiating the policy subtypes directly. """ @classmethod def from_asset_spec_metadata(cls, metadata: Mapping[str, Any]) -> Optional["FreshnessPolicy"]: serialized_policy = metadata.get(INTERNAL_FRESHNESS_POLICY_METADATA_KEY) # We had a few asset spec metadatas with internal freshness policies set to literal "null" string, # need special handling for those cases. # https://github.com/dagster-io/dagster/pull/30615 if serialized_policy is None or serialized_policy.value == "null": return None return deserialize_value(serialized_policy.value, cls) # pyright: ignore @staticmethod def time_window( fail_window: timedelta, warn_window: Optional[timedelta] = None ) -> "TimeWindowFreshnessPolicy": """Defines freshness with reference to a time window. Args: fail_window: a timedelta that defines the failure window for the asset. warn_window: an optional timedelta that defines the warning window for the asset. Returns: A ``TimeWindowFreshnessPolicy`` instance. Examples: .. code-block:: python policy = FreshnessPolicy.time_window( fail_window=timedelta(hours=24), warn_window=timedelta(hours=12) ) This policy expects the asset to materialize at least once every 24 hours, and warns if the latest materialization is older than 12 hours. - If it has been less than 12 hours since the latest materialization, the asset is passing its freshness policy, and will have a freshness state of ``PASS``. - If it has been between 12 and 24 hours since the latest materialization, the asset will have a freshness state of ``WARN``. - If it has been more than 24 hours since the latest materialization, the asset is failing its freshness policy, and will have a freshness state of ``FAIL``. """ return TimeWindowFreshnessPolicy.from_timedeltas(fail_window, warn_window) @staticmethod def cron( deadline_cron: str, lower_bound_delta: timedelta, timezone: str = "UTC" ) -> "CronFreshnessPolicy": """Defines freshness with reference to a predetermined cron schedule. Args: deadline_cron: a cron string that defines a deadline for the asset to be materialized. lower_bound_delta: a timedelta that defines the lower bound for when the asset could have been materialized. If a deadline cron tick has passed and the most recent materialization is older than (deadline cron tick timestamp - lower bound delta), the asset is considered stale until it materializes again. timezone: optionally provide a timezone for cron evaluation. IANA time zone strings are supported. If not provided, defaults to UTC. Returns: A ``CronFreshnessPolicy`` instance. Examples: .. code-block:: python policy = FreshnessPolicy.cron( deadline_cron="0 10 * * *", # 10am daily lower_bound_delta=timedelta(hours=1), ) This policy expects the asset to materialize every day between 9:00 AM and 10:00 AM. - If the asset is materialized at 9:30 AM, the asset is passing its freshness policy, and will have a freshness state of ``PASS``. The asset will continue to pass the freshness policy until at least the deadline next day (10AM). - If the asset is materialized at 9:59 AM, the asset is passing its freshness policy, and will have a freshness state of ``PASS``. The asset will continue to pass the freshness policy until at least the deadline next day (10AM). - If the asset is not materialized by 10:00 AM, the asset is failing its freshness policy, and will have a freshness state of ``FAIL``. The asset will continue to fail the freshness policy until it is materialized again. - If the asset is then materialized at 10:30AM, it will pass the freshness policy again until at least the deadline the next day (10AM). Keep in mind that the policy will always look at the last completed cron tick. So in the example above, if asset freshness is evaluated at 9:59 AM, the policy will still consider the previous day's 9-10AM window. """ return CronFreshnessPolicy( deadline_cron=deadline_cron, lower_bound_delta=lower_bound_delta, timezone=timezone ) @whitelist_for_serdes @record
FreshnessPolicy
python
numpy__numpy
numpy/polynomial/tests/test_laguerre.py
{ "start": 16024, "end": 17616 }
class ____: def test_lagfromroots(self): res = lag.lagfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5): roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2]) pol = lag.lagfromroots(roots) res = lag.lagval(roots, pol) tgt = 0 assert_(len(pol) == i + 1) assert_almost_equal(lag.lag2poly(pol)[-1], 1) assert_almost_equal(res, tgt) def test_lagroots(self): assert_almost_equal(lag.lagroots([1]), []) assert_almost_equal(lag.lagroots([0, 1]), [1]) for i in range(2, 5): tgt = np.linspace(0, 3, i) res = lag.lagroots(lag.lagfromroots(tgt)) assert_almost_equal(trim(res), trim(tgt)) def test_lagtrim(self): coef = [2, -1, 1, 0] # Test exceptions assert_raises(ValueError, lag.lagtrim, coef, -1) # Test results assert_equal(lag.lagtrim(coef), coef[:-1]) assert_equal(lag.lagtrim(coef, 1), coef[:-3]) assert_equal(lag.lagtrim(coef, 2), [0]) def test_lagline(self): assert_equal(lag.lagline(3, 4), [7, -4]) def test_lag2poly(self): for i in range(7): assert_almost_equal(lag.lag2poly([0] * i + [1]), Llist[i]) def test_poly2lag(self): for i in range(7): assert_almost_equal(lag.poly2lag(Llist[i]), [0] * i + [1]) def test_weight(self): x = np.linspace(0, 10, 11) tgt = np.exp(-x) res = lag.lagweight(x) assert_almost_equal(res, tgt)
TestMisc
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 85961, "end": 86226 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING AutoModelForNextSentencePrediction = auto_class_update( AutoModelForNextSentencePrediction, head_doc="next sentence prediction" )
AutoModelForNextSentencePrediction
python
tensorflow__tensorflow
tensorflow/python/saved_model/registration/registration_test.py
{ "start": 1143, "end": 1250 }
class ____(RegisteredClass): pass @registration.register_serializable(package="testing")
RegisteredSubclass
python
huggingface__transformers
tests/quantization/finegrained_fp8/test_fp8.py
{ "start": 1225, "end": 2538 }
class ____(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = FineGrainedFP8Config() config_to_dict = quantization_config.to_dict() for key in config_to_dict: self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) def test_from_dict(self): """ Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict """ dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fp8"} quantization_config = FineGrainedFP8Config.from_dict(dict) self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) self.assertEqual(dict["quant_method"], quantization_config.quant_method) @slow @require_accelerate @require_read_token @require_torch_accelerator @unittest.skipIf( get_device_properties()[0] == "cuda" and (get_device_properties()[1] < 8 or (get_device_properties()[1] == 8 and get_device_properties()[2] < 9)), "Skipping FP8QuantizerTest because it is not supported on GPU with capability < 8.9", )
FineGrainedFP8ConfigTest
python
instagram__MonkeyType
monkeytype/typing.py
{ "start": 15739, "end": 15996 }
class ____(TypeRewriter): def __init__(self, rewriters: Iterable[TypeRewriter]) -> None: self.rewriters = rewriters def rewrite(self, typ): for rw in self.rewriters: typ = rw.rewrite(typ) return typ
ChainedRewriter
python
MongoEngine__mongoengine
mongoengine/base/utils.py
{ "start": 12, "end": 619 }
class ____: """Descriptor to allow lazy compilation of regex""" def __init__(self, pattern, flags=0): self._pattern = pattern self._flags = flags self._compiled_regex = None @property def compiled_regex(self): if self._compiled_regex is None: self._compiled_regex = re.compile(self._pattern, self._flags) return self._compiled_regex def __get__(self, instance, owner): return self.compiled_regex def __set__(self, instance, value): raise AttributeError("Can not set attribute LazyRegexCompiler")
LazyRegexCompiler
python
getsentry__sentry
src/sentry/api/fields/user.py
{ "start": 251, "end": 833 }
class ____(serializers.Field): def to_representation(self, value: RpcUser) -> str: return value.username def to_internal_value(self, data: Any) -> RpcUser | User | None: if not data: return None if isinstance(data, int) or data.isdigit(): user = user_service.get_user(user_id=data) if user is not None: return user try: return user_service.get_by_username(username=data)[0] except IndexError: raise serializers.ValidationError("Unable to find user")
UserField
python
PyCQA__pylint
doc/data/messages/n/non-iterator-returned/good.py
{ "start": 16, "end": 796 }
class ____: def __init__(self, signs, predictions): self.signs = signs self.predictions = predictions def __iter__(self): self.index = 0 self.number_of_prediction = len(self.predictions) return self def __next__(self): if self.index == len(self.signs): raise StopIteration self.index += 1 prediction_index = random.randint(0, self.number_of_prediction - 1) return self.signs[self.index - 1], self.predictions[prediction_index] SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra"] PREDICTIONS = ["good things", "bad thing", "existential dread"] for sign, prediction in GenericAstrology(SIGNS, PREDICTIONS): print(f"{sign} : {prediction} today")
GenericAstrology
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 126808, "end": 129878 }
class ____(BasePostProgressGroupMixin): """Unit tests for is_issue_eligible_for_seer_automation.""" @patch("sentry.quotas.backend.has_available_reserved_budget", return_value=True) @patch("sentry.seer.seer_setup.get_seer_org_acknowledgement_for_scanner", return_value=True) @patch("sentry.features.has", return_value=True) def test_is_issue_eligible_for_seer_automation( self, mock_features_has, mock_get_seer_org_acknowledgement, mock_has_budget ): """Test permission check with various failure conditions.""" from sentry.constants import DataCategory from sentry.issues.grouptype import GroupCategory from sentry.seer.autofix.utils import is_issue_eligible_for_seer_automation self.project.update_option("sentry:seer_scanner_automation", True) event = self.create_event(data={"message": "testing"}, project_id=self.project.id) group = event.group # All conditions pass assert is_issue_eligible_for_seer_automation(group) is True # Unsupported categories (using PropertyMock to mock the property) with patch( "sentry.models.group.Group.issue_category", new_callable=PropertyMock ) as mock_category: mock_category.return_value = GroupCategory.REPLAY assert is_issue_eligible_for_seer_automation(group) is False mock_category.return_value = GroupCategory.FEEDBACK assert is_issue_eligible_for_seer_automation(group) is False # Missing feature flag mock_features_has.return_value = False assert is_issue_eligible_for_seer_automation(group) is False # Hide AI features enabled mock_features_has.return_value = True self.organization.update_option("sentry:hide_ai_features", True) assert is_issue_eligible_for_seer_automation(group) is False self.organization.update_option("sentry:hide_ai_features", False) # Scanner disabled without always_trigger self.project.update_option("sentry:seer_scanner_automation", False) with patch.object(group.issue_type, "always_trigger_seer_automation", False): assert is_issue_eligible_for_seer_automation(group) is False # Scanner disabled but always_trigger enabled with patch.object(group.issue_type, "always_trigger_seer_automation", True): assert is_issue_eligible_for_seer_automation(group) is True # Seer not acknowledged self.project.update_option("sentry:seer_scanner_automation", True) mock_get_seer_org_acknowledgement.return_value = False assert is_issue_eligible_for_seer_automation(group) is False # No budget mock_get_seer_org_acknowledgement.return_value = True mock_has_budget.return_value = False assert is_issue_eligible_for_seer_automation(group) is False mock_has_budget.assert_called_with( org_id=group.organization.id, data_category=DataCategory.SEER_SCANNER )
SeerAutomationHelperFunctionsTestMixin
python
rapidsai__cudf
python/cudf/cudf/core/udf/strings_typing.py
{ "start": 1893, "end": 2363 }
class ____(models.StructModel): # from udf_string.hpp: # private: # char* m_data{}; # cudf::size_type m_bytes{}; # cudf::size_type m_size{}; _members = ( ("m_data", types.CPointer(types.char)), ("m_bytes", size_type), ("m_size", size_type), ) def __init__(self, dmm, fe_type): super().__init__(dmm, fe_type, self._members) udf_string = UDFString() @register_model(ManagedUDFString)
udf_string_model
python
huggingface__transformers
src/transformers/models/moshi/modeling_moshi.py
{ "start": 2145, "end": 5895 }
class ____(ModelOutput): r""" audio_sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, 1, sequence_length)`, *optional*): The generated audio waveforms. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`): The generated text sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early due to the `eos_token_id`. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`): Final beam scores of the generated `sequences`. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`): Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`): Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size, config.vocab_size)`. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`): Beam indices of generated token id at each generation step. `torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`): Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`): Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`. past_key_values (`Cache`, *optional*, returned when `use_cache=True`): Contains the model cache, used to speed up decoding. Different models have a different cache format, check the model's documentation. Usually, a [`~cache_utils.Cache`] instance. audio_codes (`torch.LongTensor` of shape `(batch_size*num_return_sequences, num_codeooks, sequence_length)`, *optional*): The generated audio codes. Returned if `return_audio_codes=True`. Intermediate audio "tokens" which transforms to `audio_sequences` once passed through the audio decoder. """ audio_sequences: Optional[torch.Tensor] = None sequences: Optional[torch.LongTensor] = None sequences_scores: Optional[torch.FloatTensor] = None scores: Optional[tuple[torch.FloatTensor]] = None logits: Optional[tuple[torch.FloatTensor]] = None beam_indices: Optional[torch.LongTensor] = None attentions: Optional[tuple[tuple[torch.FloatTensor]]] = None hidden_states: Optional[tuple[tuple[torch.FloatTensor]]] = None past_key_values: Optional[Cache] = None audio_codes: Optional[torch.LongTensor] = None @dataclass @auto_docstring( custom_intro=""" `MoshiForCausalLM` outputs. """ )
MoshiConditionalGenerationGenerateOutput
python
doocs__leetcode
solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py
{ "start": 683, "end": 874 }
class ____: def findMaximumXOR(self, nums: List[int]) -> int: trie = Trie() for x in nums: trie.insert(x) return max(trie.search(x) for x in nums)
Solution
python
python__mypy
mypy/stubtest.py
{ "start": 33565, "end": 88553 }
class ____(Generic[T]): def __init__(self) -> None: self.pos: list[T] = [] self.kwonly: dict[str, T] = {} self.varpos: T | None = None self.varkw: T | None = None def __str__(self) -> str: def get_name(arg: Any) -> str: if isinstance(arg, inspect.Parameter): return arg.name if isinstance(arg, nodes.Argument): return arg.variable.name raise AssertionError def get_type(arg: Any) -> str | None: if isinstance(arg, inspect.Parameter): return None if isinstance(arg, nodes.Argument): return str(arg.variable.type or arg.type_annotation) raise AssertionError def has_default(arg: Any) -> bool: if isinstance(arg, inspect.Parameter): return arg.default is not inspect.Parameter.empty if isinstance(arg, nodes.Argument): return arg.kind.is_optional() raise AssertionError def get_desc(arg: Any) -> str: arg_type = get_type(arg) return ( get_name(arg) + (f": {arg_type}" if arg_type else "") + (" = ..." if has_default(arg) else "") ) kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a))) ret = "def (" ret += ", ".join( [get_desc(arg) for arg in self.pos] + (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else [])) + [get_desc(arg) for arg in kw_only] + (["**" + get_name(self.varkw)] if self.varkw else []) ) ret += ")" return ret @staticmethod def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]: stub_sig: Signature[nodes.Argument] = Signature() stub_args = maybe_strip_cls(stub.name, stub.arguments) for stub_arg in stub_args: if stub_arg.kind.is_positional(): stub_sig.pos.append(stub_arg) elif stub_arg.kind.is_named(): stub_sig.kwonly[stub_arg.variable.name] = stub_arg elif stub_arg.kind == nodes.ARG_STAR: stub_sig.varpos = stub_arg elif stub_arg.kind == nodes.ARG_STAR2: stub_sig.varkw = stub_arg else: raise AssertionError return stub_sig @staticmethod def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]: runtime_sig: Signature[inspect.Parameter] = Signature() for runtime_arg in signature.parameters.values(): if runtime_arg.kind in ( inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, ): runtime_sig.pos.append(runtime_arg) elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY: runtime_sig.kwonly[runtime_arg.name] = runtime_arg elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL: runtime_sig.varpos = runtime_arg elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD: runtime_sig.varkw = runtime_arg else: raise AssertionError return runtime_sig @staticmethod def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]: """Returns a Signature from an OverloadedFuncDef. If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we try and combine the overload's items into a single signature that is compatible with any lies it might try to tell. """ # For most dunder methods, just assume all args are positional-only assume_positional_only = is_dunder(stub.name, exclude_special=True) is_arg_pos_only: defaultdict[str, set[bool]] = defaultdict(set) for func in map(_resolve_funcitem_from_decorator, stub.items): assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" args = maybe_strip_cls(stub.name, func.arguments) for index, arg in enumerate(args): if ( arg.variable.name.startswith("__") or arg.pos_only or assume_positional_only or arg.variable.name.strip("_") == "self" or (index == 0 and arg.variable.name.strip("_") == "cls") ): is_arg_pos_only[arg.variable.name].add(True) else: is_arg_pos_only[arg.variable.name].add(False) all_args: dict[str, list[tuple[nodes.Argument, int]]] = {} for func in map(_resolve_funcitem_from_decorator, stub.items): assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" args = maybe_strip_cls(stub.name, func.arguments) for index, arg in enumerate(args): # For positional-only args, we allow overloads to have different names for the same # argument. To accomplish this, we just make up a fake index-based name. # We can only use the index-based name if the argument is always # positional only. Sometimes overloads have an arg as positional-only # in some but not all branches of the overload. name = arg.variable.name if is_arg_pos_only[name] == {True}: name = f"__{index}" all_args.setdefault(name, []).append((arg, index)) def get_position(arg_name: str) -> int: # We just need this to return the positional args in the correct order. return max(index for _, index in all_args[arg_name]) def get_type(arg_name: str) -> mypy.types.ProperType: with mypy.state.state.strict_optional_set(True): all_types = [ arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name] ] return mypy.typeops.make_simplified_union([t for t in all_types if t]) def get_kind(arg_name: str) -> nodes.ArgKind: kinds = {arg.kind for arg, _ in all_args[arg_name]} if nodes.ARG_STAR in kinds: return nodes.ARG_STAR if nodes.ARG_STAR2 in kinds: return nodes.ARG_STAR2 # The logic here is based on two tenets: # 1) If an arg is ever optional (or unspecified), it is optional # 2) If an arg is ever positional, it is positional is_opt = ( len(all_args[arg_name]) < len(stub.items) or nodes.ARG_OPT in kinds or nodes.ARG_NAMED_OPT in kinds ) is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds if is_opt: return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT return nodes.ARG_POS if is_pos else nodes.ARG_NAMED sig: Signature[nodes.Argument] = Signature() for arg_name in sorted(all_args, key=get_position): # example_arg_name gives us a real name (in case we had a fake index-based name) example_arg_name = all_args[arg_name][0][0].variable.name arg = nodes.Argument( nodes.Var(example_arg_name, get_type(arg_name)), type_annotation=None, initializer=None, kind=get_kind(arg_name), pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]), ) if arg.kind.is_positional(): sig.pos.append(arg) elif arg.kind.is_named(): sig.kwonly[arg.variable.name] = arg elif arg.kind == nodes.ARG_STAR: sig.varpos = arg elif arg.kind == nodes.ARG_STAR2: sig.varkw = arg else: raise AssertionError return sig def _verify_signature( stub: Signature[nodes.Argument], runtime: Signature[inspect.Parameter], function_name: str, warn_runtime_is_object_init: bool = False, ) -> Iterator[str]: # Check positional arguments match up for stub_arg, runtime_arg in zip(stub.pos, runtime.pos): yield from _verify_arg_name(stub_arg, runtime_arg, function_name) yield from _verify_arg_default_value(stub_arg, runtime_arg) if ( runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and not stub_arg.pos_only and not stub_arg.variable.name.startswith("__") and stub_arg.variable.name.strip("_") != "self" and stub_arg.variable.name.strip("_") != "cls" and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods ): yield ( f'stub parameter "{stub_arg.variable.name}" should be positional-only ' f'(add "/", e.g. "{runtime_arg.name}, /")' ) if ( runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY and (stub_arg.pos_only or stub_arg.variable.name.startswith("__")) and not runtime_arg.name.startswith("__") and stub_arg.variable.name.strip("_") != "self" and stub_arg.variable.name.strip("_") != "cls" and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods ): yield ( f'stub parameter "{stub_arg.variable.name}" should be positional or keyword ' '(remove "/")' ) # Check unmatched positional args if len(stub.pos) > len(runtime.pos): # There are cases where the stub exhaustively lists out the extra parameters the function # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes # *args, since runtime logic may prevent arbitrary arguments from actually being accepted. if runtime.varpos is None: for stub_arg in stub.pos[len(runtime.pos) :]: # If the variable is in runtime.kwonly, it's just mislabelled as not a # keyword-only argument if stub_arg.variable.name not in runtime.kwonly: msg = f'runtime does not have parameter "{stub_arg.variable.name}"' if runtime.varkw is not None: msg += ". Maybe you forgot to make it keyword-only in the stub?" elif warn_runtime_is_object_init: msg += ". You may need to write stubs for __new__ instead of __init__." yield msg else: yield f'stub parameter "{stub_arg.variable.name}" is not keyword-only' if stub.varpos is not None: yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' elif len(stub.pos) < len(runtime.pos): for runtime_arg in runtime.pos[len(stub.pos) :]: if runtime_arg.name not in stub.kwonly: if not _is_private_parameter(runtime_arg): yield f'stub does not have parameter "{runtime_arg.name}"' else: yield f'runtime parameter "{runtime_arg.name}" is not keyword-only' # Checks involving *args if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None: if stub.varpos is None and runtime.varpos is not None: yield f'stub does not have *args parameter "{runtime.varpos.name}"' if stub.varpos is not None and runtime.varpos is None: yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' # Check keyword-only args for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)): stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg] yield from _verify_arg_name(stub_arg, runtime_arg, function_name) yield from _verify_arg_default_value(stub_arg, runtime_arg) # Check unmatched keyword-only args if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)): # There are cases where the stub exhaustively lists out the extra parameters the function # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't # exhaustively listed out params), we don't check whether the runtime has all of the stub's # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic # may prevent arbitrary keyword arguments from actually being accepted. for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)): if arg in {runtime_arg.name for runtime_arg in runtime.pos}: # Don't report this if we've reported it before if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}: yield f'runtime parameter "{arg}" is not keyword-only' else: msg = f'runtime does not have parameter "{arg}"' if warn_runtime_is_object_init: msg += ". You may need to write stubs for __new__ instead of __init__." yield msg for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)): if arg in {stub_arg.variable.name for stub_arg in stub.pos}: # Don't report this if we've reported it before if not ( runtime.varpos is None and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]} ): yield f'stub parameter "{arg}" is not keyword-only' else: if not _is_private_parameter(runtime.kwonly[arg]): yield f'stub does not have parameter "{arg}"' # Checks involving **kwargs if stub.varkw is None and runtime.varkw is not None: # As mentioned above, don't enforce that the stub takes **kwargs. # Also check against positional parameters, to avoid a nitpicky message when an argument # isn't marked as keyword-only stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos} # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names): yield f'stub does not have **kwargs parameter "{runtime.varkw.name}"' if stub.varkw is not None and runtime.varkw is None: yield f'runtime does not have **kwargs parameter "{stub.varkw.variable.name}"' def _is_private_parameter(arg: inspect.Parameter) -> bool: return ( arg.name.startswith("_") and not arg.name.startswith("__") and arg.default is not inspect.Parameter.empty ) @verify.register(nodes.FuncItem) def verify_funcitem( stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if isinstance(runtime, Missing): yield Error(object_path, "is not present at runtime", stub, runtime) return if not is_probably_a_function(runtime): yield Error(object_path, "is not a function", stub, runtime) if not callable(runtime): return # Look the object up statically, to avoid binding by the descriptor protocol static_runtime = _static_lookup_runtime(object_path) if isinstance(stub, nodes.FuncDef): for error_text in _verify_abstract_status(stub, runtime): yield Error(object_path, error_text, stub, runtime) for error_text in _verify_final_method(stub, runtime, static_runtime): yield Error(object_path, error_text, stub, runtime) for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): yield Error(object_path, "is inconsistent, " + message, stub, runtime) signature = safe_inspect_signature(runtime) runtime_is_coroutine = inspect.iscoroutinefunction(runtime) if signature: stub_sig = Signature.from_funcitem(stub) runtime_sig = Signature.from_inspect_signature(signature) runtime_sig_desc = describe_runtime_callable(signature, is_async=runtime_is_coroutine) stub_desc = str(stub_sig) else: runtime_sig_desc, stub_desc = None, None # Don't raise an error if the stub is a coroutine, but the runtime isn't. # That results in false positives. # See https://github.com/python/typeshed/issues/7344 if runtime_is_coroutine and not stub.is_coroutine: yield Error( object_path, 'is an "async def" function at runtime, but not in the stub', stub, runtime, stub_desc=stub_desc, runtime_desc=runtime_sig_desc, ) if not signature: return for message in _verify_signature( stub_sig, runtime_sig, function_name=stub.name, warn_runtime_is_object_init=runtime is object.__init__, ): yield Error( object_path, "is inconsistent, " + message, stub, runtime, runtime_desc=runtime_sig_desc, ) @verify.register(Missing) def verify_missing( stub: Missing, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if runtime is MISSING: return yield Error(object_path, "is not present in stub", stub, runtime) @verify.register(nodes.Var) def verify_var( stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if isinstance(runtime, Missing): # Don't always yield an error here, because we often can't find instance variables if len(object_path) <= 2: yield Error(object_path, "is not present at runtime", stub, runtime) return if ( stub.is_initialized_in_class and is_read_only_property(runtime) and (stub.is_settable_property or not stub.is_property) ): yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) runtime_type = get_mypy_type_of_runtime_value(runtime, type_context=stub.type) note = "" if ( runtime_type is not None and stub.type is not None and not is_subtype_helper(runtime_type, stub.type) ): should_error = True # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd # annotate it with the type of runtime.value if isinstance(runtime, enum.Enum): runtime_type = get_mypy_type_of_runtime_value(runtime.value) if runtime_type is not None and is_subtype_helper(runtime_type, stub.type): should_error = False # We always allow setting the stub value to Ellipsis (...), but use # _value_ type as a fallback if given. If a member is ... and _value_ # type is given, all runtime types should be assignable to _value_. proper_type = mypy.types.get_proper_type(stub.type) if ( isinstance(proper_type, mypy.types.Instance) and proper_type.type.fullname in mypy.types.ELLIPSIS_TYPE_NAMES ): value_t = stub.info.get("_value_") if value_t is None or value_t.type is None or runtime_type is None: should_error = False elif is_subtype_helper(runtime_type, value_t.type): should_error = False else: note = " (incompatible '_value_')" if should_error: yield Error( object_path, f"variable differs from runtime type {runtime_type}{note}", stub, runtime, ) @verify.register(nodes.OverloadedFuncDef) def verify_overloadedfuncdef( stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: # TODO: support `@type_check_only` decorator if isinstance(runtime, Missing): yield Error(object_path, "is not present at runtime", stub, runtime) return if stub.is_property: # Any property with a setter is represented as an OverloadedFuncDef if is_read_only_property(runtime): yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) return if not is_probably_a_function(runtime): yield Error(object_path, "is not a function", stub, runtime) if not callable(runtime): return # mypy doesn't allow overloads where one overload is abstract but another isn't, # so it should be okay to just check whether the first overload is abstract or not. # # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not; # and any property with a setter is represented as an OverloadedFuncDef internally; # not sure exactly what (if anything) we should do about that. first_part = stub.items[0] if isinstance(first_part, nodes.Decorator) and first_part.is_overload: for msg in _verify_abstract_status(first_part.func, runtime): yield Error(object_path, msg, stub, runtime) # Look the object up statically, to avoid binding by the descriptor protocol static_runtime = _static_lookup_runtime(object_path) for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): yield Error(object_path, "is inconsistent, " + message, stub, runtime) # TODO: Should call _verify_final_method here, # but overloaded final methods in stubs cause a stubtest crash: see #14950 signature = safe_inspect_signature(runtime) if not signature: return stub_sig = Signature.from_overloadedfuncdef(stub) runtime_sig = Signature.from_inspect_signature(signature) for message in _verify_signature( stub_sig, runtime_sig, function_name=stub.name, warn_runtime_is_object_init=runtime is object.__init__, ): # TODO: This is a little hacky, but the addition here is super useful if "has a default value of type" in message: message += ( ". This is often caused by overloads failing to account for explicitly passing " "in the default value." ) yield Error( object_path, "is inconsistent, " + message, stub, runtime, stub_desc=(str(stub.type)) + f"\nInferred signature: {stub_sig}", runtime_desc="def " + str(signature), ) @verify.register(nodes.TypeVarExpr) def verify_typevarexpr( stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if isinstance(runtime, Missing): # We seem to insert these typevars into NamedTuple stubs, but they # don't exist at runtime. Just ignore! if stub.name == "_NT": return yield Error(object_path, "is not present at runtime", stub, runtime) return if not isinstance(runtime, TypeVar): yield Error(object_path, "is not a TypeVar", stub, runtime) return @verify.register(nodes.ParamSpecExpr) def verify_paramspecexpr( stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if isinstance(runtime, Missing): yield Error(object_path, "is not present at runtime", stub, runtime) return maybe_paramspec_types = ( getattr(typing, "ParamSpec", None), getattr(typing_extensions, "ParamSpec", None), ) paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None) if not paramspec_types or not isinstance(runtime, paramspec_types): yield Error(object_path, "is not a ParamSpec", stub, runtime) return def _is_django_cached_property(runtime: Any) -> bool: # pragma: no cover # This is a special case for # https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.functional.cached_property # This is needed in `django-stubs` project: # https://github.com/typeddjango/django-stubs if type(runtime).__name__ != "cached_property": return False try: return bool(runtime.func) except Exception: return False def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]: assert stub.func.is_property if isinstance(runtime, property): yield from _verify_final_method(stub.func, runtime.fget, MISSING) return if isinstance(runtime, functools.cached_property): yield from _verify_final_method(stub.func, runtime.func, MISSING) return if _is_django_cached_property(runtime): yield from _verify_final_method(stub.func, runtime.func, MISSING) return if inspect.isdatadescriptor(runtime): # It's enough like a property... return # Sometimes attributes pretend to be properties, for instance, to express that they # are read only. So allowlist if runtime_type matches the return type of stub. runtime_type = get_mypy_type_of_runtime_value(runtime) func_type = ( stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None ) if ( runtime_type is not None and func_type is not None and is_subtype_helper(runtime_type, func_type) ): return yield "is inconsistent, cannot reconcile @property on stub with runtime object" def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]: stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT runtime_abstract = getattr(runtime, "__isabstractmethod__", False) # The opposite can exist: some implementations omit `@abstractmethod` decorators if runtime_abstract and not stub_abstract: item_type = "property" if stub.is_property else "method" yield f"is inconsistent, runtime {item_type} is abstract but stub is not" def _verify_final_method( stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any] ) -> Iterator[str]: if stub.is_final: return if getattr(runtime, "__final__", False) or ( static_runtime is not MISSING and getattr(static_runtime, "__final__", False) ): yield "is decorated with @final at runtime, but not in the stub" def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None: """Returns a FuncItem that corresponds to the output of the decorator. Returns None if we can't figure out what that would be. For convenience, this function also accepts FuncItems. """ if isinstance(dec, nodes.FuncItem): return dec if dec.func.is_property: return None def apply_decorator_to_funcitem( decorator: nodes.Expression, func: nodes.FuncItem ) -> nodes.FuncItem | None: if ( isinstance(decorator, nodes.CallExpr) and isinstance(decorator.callee, nodes.RefExpr) and decorator.callee.fullname in mypy.types.DEPRECATED_TYPE_NAMES ): return func if not isinstance(decorator, nodes.RefExpr): return None if not decorator.fullname: # Happens with namedtuple return None if ( decorator.fullname in ("builtins.staticmethod", "abc.abstractmethod") or decorator.fullname in mypy.types.OVERLOAD_NAMES or decorator.fullname in mypy.types.OVERRIDE_DECORATOR_NAMES or decorator.fullname in mypy.types.FINAL_DECORATOR_NAMES ): return func if decorator.fullname == "builtins.classmethod": if func.arguments[0].variable.name not in ("cls", "mcs", "metacls"): raise StubtestFailure( f"unexpected class parameter name {func.arguments[0].variable.name!r} " f"in {dec.fullname}" ) # FuncItem is written so that copy.copy() actually works, even when compiled ret = copy.copy(func) # Remove the cls argument, since it's not present in inspect.signature of classmethods ret.arguments = ret.arguments[1:] return ret # Just give up on any other decorators. After excluding properties, we don't run into # anything else when running on typeshed's stdlib. return None func: nodes.FuncItem = dec.func for decorator in dec.original_decorators: resulting_func = apply_decorator_to_funcitem(decorator, func) if resulting_func is None: return None func = resulting_func return func @verify.register(nodes.Decorator) def verify_decorator( stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: if stub.func.is_type_check_only: # This function only exists in stubs, we only check that the runtime part # is missing. Other checks are not required. if not isinstance(runtime, Missing): yield Error( object_path, 'is marked as "@type_check_only", but also exists at runtime', stub, runtime, stub_desc=repr(stub), ) return if isinstance(runtime, Missing): yield Error(object_path, "is not present at runtime", stub, runtime) return if stub.func.is_property: for message in _verify_readonly_property(stub, runtime): yield Error(object_path, message, stub, runtime) for message in _verify_abstract_status(stub.func, runtime): yield Error(object_path, message, stub, runtime) return func = _resolve_funcitem_from_decorator(stub) if func is not None: yield from verify(func, runtime, object_path) @verify.register(nodes.TypeAlias) def verify_typealias( stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str] ) -> Iterator[Error]: stub_target = mypy.types.get_proper_type(stub.target) stub_desc = f"Type alias for {stub_target}" if isinstance(runtime, Missing): yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=stub_desc) return runtime_origin = get_origin(runtime) or runtime if isinstance(stub_target, mypy.types.Instance): if not isinstance(runtime_origin, type): yield Error( object_path, "is inconsistent, runtime is not a type", stub, runtime, stub_desc=stub_desc, ) return stub_origin = stub_target.type # Do our best to figure out the fullname of the runtime object... runtime_name: object try: runtime_name = runtime_origin.__qualname__ except AttributeError: runtime_name = getattr(runtime_origin, "__name__", MISSING) if isinstance(runtime_name, str): runtime_module: object = getattr(runtime_origin, "__module__", MISSING) if isinstance(runtime_module, str): if runtime_module == "collections.abc" or ( runtime_module == "re" and runtime_name in {"Match", "Pattern"} ): runtime_module = "typing" runtime_fullname = f"{runtime_module}.{runtime_name}" if re.fullmatch(rf"_?{re.escape(stub_origin.fullname)}", runtime_fullname): # Okay, we're probably fine. return # Okay, either we couldn't construct a fullname # or the fullname of the stub didn't match the fullname of the runtime. # Fallback to a full structural check of the runtime vis-a-vis the stub. yield from verify_typeinfo(stub_origin, runtime_origin, object_path, is_alias_target=True) return if isinstance(stub_target, mypy.types.UnionType): # complain if runtime is not a Union or UnionType if runtime_origin is not Union and ( not (sys.version_info >= (3, 10) and isinstance(runtime, types.UnionType)) ): yield Error(object_path, "is not a Union", stub, runtime, stub_desc=str(stub_target)) # could check Union contents here... return if isinstance(stub_target, mypy.types.TupleType): if tuple not in getattr(runtime_origin, "__mro__", ()): yield Error( object_path, "is not a subclass of tuple", stub, runtime, stub_desc=stub_desc ) # could check Tuple contents here... return if isinstance(stub_target, mypy.types.CallableType): if runtime_origin is not collections.abc.Callable: yield Error( object_path, "is not a type alias for Callable", stub, runtime, stub_desc=stub_desc ) # could check Callable contents here... return if isinstance(stub_target, mypy.types.AnyType): return yield Error(object_path, "is not a recognised type alias", stub, runtime, stub_desc=stub_desc) # ==================== # Helpers # ==================== IGNORED_MODULE_DUNDERS: Final = frozenset( { "__file__", "__doc__", "__name__", "__builtins__", "__package__", "__cached__", "__loader__", "__spec__", "__annotations__", "__annotate__", "__path__", # mypy adds __path__ to packages, but C packages don't have it "__getattr__", # resulting behaviour might be typed explicitly # Created by `warnings.warn`, does not make much sense to have in stubs: "__warningregistry__", # TODO: remove the following from this list "__author__", "__version__", "__copyright__", } ) IGNORABLE_CLASS_DUNDERS: Final = frozenset( { # Special attributes "__dict__", "__annotations__", "__annotate__", "__annotations_cache__", "__annotate_func__", "__text_signature__", "__weakref__", "__hash__", "__getattr__", # resulting behaviour might be typed explicitly "__setattr__", # defining this on a class can cause worse type checking "__vectorcalloffset__", # undocumented implementation detail of the vectorcall protocol "__firstlineno__", "__static_attributes__", "__classdictcell__", # isinstance/issubclass hooks that type-checkers don't usually care about "__instancecheck__", "__subclasshook__", "__subclasscheck__", # python2 only magic methods: "__cmp__", "__nonzero__", "__unicode__", "__div__", # cython methods "__pyx_vtable__", # Pickle methods "__setstate__", "__getstate__", "__getnewargs__", "__getinitargs__", "__reduce_ex__", "__reduce__", "__slotnames__", # Cached names of slots added by `copyreg` module. # ctypes weirdness "__ctype_be__", "__ctype_le__", "__ctypes_from_outparam__", # mypy limitations "__abstractmethods__", # Classes with metaclass=ABCMeta inherit this attribute "__new_member__", # If an enum defines __new__, the method is renamed as __new_member__ "__dataclass_fields__", # Generated by dataclasses "__dataclass_params__", # Generated by dataclasses "__doc__", # mypy's semanal for namedtuples assumes this is str, not Optional[str] # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol) "__protocol_attrs__", "__callable_proto_members_only__", "__non_callable_proto_members__", # typing implementation details, consider removing some of these: "__parameters__", "__origin__", "__args__", "__orig_bases__", "__final__", # Has a specialized check # Consider removing __slots__? "__slots__", } ) def is_probably_private(name: str) -> bool: return name.startswith("_") and not is_dunder(name) def is_probably_a_function(runtime: Any) -> bool: return ( isinstance( runtime, ( types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType, ), ) or (inspect.ismethoddescriptor(runtime) and callable(runtime)) or (isinstance(runtime, types.MethodWrapperType) and callable(runtime)) ) def is_read_only_property(runtime: object) -> bool: return isinstance(runtime, property) and runtime.fset is None def safe_inspect_signature(runtime: Any) -> inspect.Signature | None: if ( hasattr(runtime, "__name__") and runtime.__name__ == "__init__" and hasattr(runtime, "__text_signature__") and runtime.__text_signature__ == "($self, /, *args, **kwargs)" and hasattr(runtime, "__objclass__") and hasattr(runtime.__objclass__, "__text_signature__") and runtime.__objclass__.__text_signature__ is not None ): # This is an __init__ method with the generic C-class signature. # In this case, the underlying class often has a better signature, # which we can convert into an __init__ signature by adding in the # self parameter. try: s = inspect.signature(runtime.__objclass__) parameter_kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD if s.parameters: first_parameter = next(iter(s.parameters.values())) if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: parameter_kind = inspect.Parameter.POSITIONAL_ONLY return s.replace( parameters=[inspect.Parameter("self", parameter_kind), *s.parameters.values()] ) except Exception: pass if ( hasattr(runtime, "__name__") and runtime.__name__ == "__new__" and hasattr(runtime, "__text_signature__") and runtime.__text_signature__ == "($type, *args, **kwargs)" and hasattr(runtime, "__self__") and hasattr(runtime.__self__, "__text_signature__") and runtime.__self__.__text_signature__ is not None ): # This is a __new__ method with the generic C-class signature. # In this case, the underlying class often has a better signature, # which we can convert into a __new__ signature by adding in the # cls parameter. # If the attached class has a valid __init__, skip recovering a # signature for this __new__ method. has_init = False if ( hasattr(runtime.__self__, "__init__") and hasattr(runtime.__self__.__init__, "__objclass__") and runtime.__self__.__init__.__objclass__ is runtime.__self__ ): has_init = True if not has_init: try: s = inspect.signature(runtime.__self__) parameter_kind = inspect.Parameter.POSITIONAL_OR_KEYWORD if s.parameters: first_parameter = next(iter(s.parameters.values())) if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: parameter_kind = inspect.Parameter.POSITIONAL_ONLY return s.replace( parameters=[inspect.Parameter("cls", parameter_kind), *s.parameters.values()] ) except Exception: pass try: try: return inspect.signature(runtime) except ValueError: if ( hasattr(runtime, "__text_signature__") and "<unrepresentable>" in runtime.__text_signature__ ): # Try to fix up the signature. Workaround for # https://github.com/python/cpython/issues/87233 sig = runtime.__text_signature__.replace("<unrepresentable>", "...") sig = inspect._signature_fromstr(inspect.Signature, runtime, sig) # type: ignore[attr-defined] assert isinstance(sig, inspect.Signature) new_params = [ ( parameter.replace(default=UNREPRESENTABLE) if parameter.default is ... else parameter ) for parameter in sig.parameters.values() ] return sig.replace(parameters=new_params) else: raise except Exception: # inspect.signature throws ValueError all the time # catch RuntimeError because of https://bugs.python.org/issue39504 # catch TypeError because of https://github.com/python/typeshed/pull/5762 # catch AttributeError because of inspect.signature(_curses.window.border) return None def describe_runtime_callable(signature: inspect.Signature, *, is_async: bool) -> str: return f'{"async " if is_async else ""}def {signature}' def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool: """Checks whether ``left`` is a subtype of ``right``.""" left = mypy.types.get_proper_type(left) right = mypy.types.get_proper_type(right) if ( isinstance(left, mypy.types.LiteralType) and isinstance(left.value, int) and left.value in (0, 1) and mypy.types.is_named_instance(right, "builtins.bool") ): # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors. return True if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance( left, "builtins.dict" ): # Special case checks against TypedDicts return True with mypy.state.state.strict_optional_set(True): return mypy.subtypes.is_subtype(left, right) def get_mypy_node_for_name(module: str, type_name: str) -> mypy.nodes.SymbolNode | None: stub = get_stub(module) if stub is None: return None if type_name not in stub.names: return None return stub.names[type_name].node def get_mypy_type_of_runtime_value( runtime: Any, type_context: mypy.types.Type | None = None ) -> mypy.types.Type | None: """Returns a mypy type object representing the type of ``runtime``. Returns None if we can't find something that works. """ if runtime is None: return mypy.types.NoneType() if isinstance(runtime, property): # Give up on properties to avoid issues with things that are typed as attributes. return None def anytype() -> mypy.types.AnyType: return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated) if isinstance( runtime, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType), ): builtins = get_stub("builtins") assert builtins is not None type_info = builtins.names["function"].node assert isinstance(type_info, nodes.TypeInfo) fallback = mypy.types.Instance(type_info, [anytype()]) signature = safe_inspect_signature(runtime) if signature: arg_types = [] arg_kinds = [] arg_names = [] for arg in signature.parameters.values(): arg_types.append(anytype()) arg_names.append( None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name ) no_default = arg.default is inspect.Parameter.empty if arg.kind == inspect.Parameter.POSITIONAL_ONLY: arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) elif arg.kind == inspect.Parameter.KEYWORD_ONLY: arg_kinds.append(nodes.ARG_NAMED if no_default else nodes.ARG_NAMED_OPT) elif arg.kind == inspect.Parameter.VAR_POSITIONAL: arg_kinds.append(nodes.ARG_STAR) elif arg.kind == inspect.Parameter.VAR_KEYWORD: arg_kinds.append(nodes.ARG_STAR2) else: raise AssertionError else: arg_types = [anytype(), anytype()] arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2] arg_names = [None, None] return mypy.types.CallableType( arg_types, arg_kinds, arg_names, ret_type=anytype(), fallback=fallback, is_ellipsis_args=True, ) skip_type_object_type = False if type_context: # Don't attempt to process the type object when context is generic # This is related to issue #3737 type_context = mypy.types.get_proper_type(type_context) # Callable types with a generic return value if isinstance(type_context, mypy.types.CallableType): if isinstance(type_context.ret_type, mypy.types.TypeVarType): skip_type_object_type = True # Type[x] where x is generic if isinstance(type_context, mypy.types.TypeType): if isinstance(type_context.item, mypy.types.TypeVarType): skip_type_object_type = True if isinstance(runtime, type) and not skip_type_object_type: def _named_type(name: str) -> mypy.types.Instance: parts = name.rsplit(".", maxsplit=1) node = get_mypy_node_for_name(parts[0], parts[1]) assert isinstance(node, nodes.TypeInfo) any_type = mypy.types.AnyType(mypy.types.TypeOfAny.special_form) return mypy.types.Instance(node, [any_type] * len(node.defn.type_vars)) # Try and look up a stub for the runtime object itself # The logic here is similar to ExpressionChecker.analyze_ref_expr type_info = get_mypy_node_for_name(runtime.__module__, runtime.__name__) if isinstance(type_info, nodes.TypeInfo): result: mypy.types.Type | None = None result = mypy.typeops.type_object_type(type_info, _named_type) if mypy.checkexpr.is_type_type_context(type_context): # This is the type in a type[] expression, so substitute type # variables with Any. result = mypy.erasetype.erase_typevars(result) return result # Try and look up a stub for the runtime object's type type_info = get_mypy_node_for_name(type(runtime).__module__, type(runtime).__name__) if type_info is None: return None if isinstance(type_info, nodes.Var): return type_info.type if not isinstance(type_info, nodes.TypeInfo): return None if isinstance(runtime, tuple): # Special case tuples so we construct a valid mypy.types.TupleType optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime] items = [(i if i is not None else anytype()) for i in optional_items] fallback = mypy.types.Instance(type_info, [anytype()]) return mypy.types.TupleType(items, fallback) fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars]) value: bool | int | str if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str): value = runtime.name elif isinstance(runtime, bytes): value = bytes_to_human_readable_repr(runtime) elif isinstance(runtime, (bool, int, str)): value = runtime else: return fallback return mypy.types.LiteralType(value=value, fallback=fallback) # ==================== # Build and entrypoint # ==================== _all_stubs: dict[str, nodes.MypyFile] = {} def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]: """Uses mypy to construct stub objects for the given modules. This sets global state that ``get_stub`` can access. Returns all modules we might want to check. If ``find_submodules`` is False, this is equal to ``modules``. :param modules: List of modules to build stubs for. :param options: Mypy options for finding and building stubs. :param find_submodules: Whether to attempt to find submodules of the given modules as well. """ data_dir = mypy.build.default_data_dir() search_path = mypy.modulefinder.compute_search_paths([], options, data_dir) find_module_cache = mypy.modulefinder.FindModuleCache( search_path, fscache=None, options=options ) all_modules = [] sources = [] for module in modules: all_modules.append(module) if not find_submodules: module_path = find_module_cache.find_module(module) if not isinstance(module_path, str): # test_module will yield an error later when it can't find stubs continue sources.append(mypy.modulefinder.BuildSource(module_path, module, None)) else: found_sources = find_module_cache.find_modules_recursive(module) sources.extend(found_sources) # find submodules via mypy all_modules.extend(s.module for s in found_sources if s.module not in all_modules) # find submodules via pkgutil try: runtime = silent_import_module(module) all_modules.extend( m.name for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + ".") if m.name not in all_modules ) except KeyboardInterrupt: raise except BaseException: pass if sources: try: res = mypy.build.build(sources=sources, options=options) except mypy.errors.CompileError as e: raise StubtestFailure(f"failed mypy compile:\n{e}") from e if res.errors: raise StubtestFailure("mypy build errors:\n" + "\n".join(res.errors)) global _all_stubs _all_stubs = res.files return all_modules def get_stub(module: str) -> nodes.MypyFile | None: """Returns a stub object for the given module, if we've built one.""" return _all_stubs.get(module) def get_typeshed_stdlib_modules( custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None ) -> set[str]: """Returns a list of stdlib modules in typeshed (for current Python version).""" stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir) if version_info is None: version_info = sys.version_info[0:2] def exists_in_version(module: str) -> bool: assert version_info is not None parts = module.split(".") for i in range(len(parts), 0, -1): current_module = ".".join(parts[:i]) if current_module in stdlib_py_versions: minver, maxver = stdlib_py_versions[current_module] return version_info >= minver and (maxver is None or version_info <= maxver) return False if custom_typeshed_dir: typeshed_dir = Path(custom_typeshed_dir) else: typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed" stdlib_dir = typeshed_dir / "stdlib" modules: set[str] = set() for path in stdlib_dir.rglob("*.pyi"): if path.stem == "__init__": path = path.parent module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,)) if exists_in_version(module): modules.add(module) return modules def get_importable_stdlib_modules() -> set[str]: """Return all importable stdlib modules at runtime.""" importable_stdlib_modules: set[str] = set() for module_name in sys.stdlib_module_names: if module_name in ANNOYING_STDLIB_MODULES: continue try: runtime = silent_import_module(module_name) except ImportError: continue else: importable_stdlib_modules.add(module_name) try: # some stdlib modules (e.g. `nt`) don't have __path__ set... runtime_path = runtime.__path__ runtime_name = runtime.__name__ except AttributeError: continue for submodule in pkgutil.walk_packages(runtime_path, runtime_name + "."): submodule_name = submodule.name # There are many annoying *.__main__ stdlib modules, # and including stubs for them isn't really that useful anyway: # tkinter.__main__ opens a tkinter windows; unittest.__main__ raises SystemExit; etc. # # The idlelib.* submodules are similarly annoying in opening random tkinter windows, # and we're unlikely to ever add stubs for idlelib in typeshed # (see discussion in https://github.com/python/typeshed/pull/9193) # # test.* modules do weird things like raising exceptions in __del__ methods, # leading to unraisable exceptions being logged to the terminal # as a warning at the end of the stubtest run if submodule_name.endswith(".__main__") or submodule_name.startswith( ("idlelib.", "test.") ): continue try: silent_import_module(submodule_name) except KeyboardInterrupt: raise # importing multiprocessing.popen_forkserver on Windows raises AttributeError... # some submodules also appear to raise SystemExit as well on some Python versions # (not sure exactly which) except BaseException: continue else: importable_stdlib_modules.add(submodule_name) return importable_stdlib_modules def get_allowlist_entries(allowlist_file: str) -> Iterator[str]: def strip_comments(s: str) -> str: try: return s[: s.index("#")].strip() except ValueError: return s.strip() with open(allowlist_file) as f: for line in f: entry = strip_comments(line) if entry: yield entry
Signature
python
allegroai__clearml
clearml/binding/environ_bind.py
{ "start": 322, "end": 2468 }
class ____(object): _current_task = None _environment_section = "Environment" __patched = False @classmethod def update_current_task(cls, task: Any) -> None: cls._current_task = task # noinspection PyBroadException try: if not cls.__patched: cls.__patched = True cls._bind_environment() except Exception: pass @classmethod def _bind_environment(cls) -> None: if not cls._current_task: return # get ENVIRONMENT and put it into the OS environment if running_remotely(): params = cls._current_task.get_parameters_as_dict() if params and cls._environment_section in params: # put back into os: os.environ.update(params[cls._environment_section]) return environ_log = str(TASK_LOG_ENVIRONMENT.get() or "").strip() or config.get("development.log_os_environments", []) if environ_log and isinstance(environ_log, str): environ_log = [e.strip() for e in environ_log.split(",")] if not environ_log: return env_param = dict() for match in environ_log: match = match.strip() if match == "*": env_param.update( { k: os.environ.get(k) for k in os.environ if not k.startswith("TRAINS_") and not k.startswith("CLEARML_") } ) elif match.endswith("*"): match = match.rstrip("*") env_param.update({k: os.environ.get(k) for k in os.environ if k.startswith(match)}) elif match.startswith("*"): match = match.lstrip("*") env_param.update({k: os.environ.get(k) for k in os.environ if k.endswith(match)}) elif match in os.environ: env_param.update({match: os.environ.get(match)}) # store os environments cls._current_task.connect(env_param, cls._environment_section)
EnvironmentBind
python
django__django
django/db/backends/oracle/functions.py
{ "start": 65, "end": 509 }
class ____(Func): function = "" template = """ EXTRACT(day from %(expressions)s) * 86400 + EXTRACT(hour from %(expressions)s) * 3600 + EXTRACT(minute from %(expressions)s) * 60 + EXTRACT(second from %(expressions)s) """ def __init__(self, expression, *, output_field=None, **extra): super().__init__( expression, output_field=output_field or DecimalField(), **extra )
IntervalToSeconds
python
huggingface__transformers
src/transformers/models/bert_generation/modeling_bert_generation.py
{ "start": 17547, "end": 19118 }
class ____(nn.Module): """Construct the embeddings from word and position embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer( "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False ) def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length] if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) position_embeddings = self.position_embeddings(position_ids) embeddings = inputs_embeds + position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings @auto_docstring
BertGenerationEmbeddings
python
scipy__scipy
scipy/ndimage/tests/test_interpolation.py
{ "start": 14923, "end": 17819 }
class ____: def test_geometric_transform_grid_constant_order1(self, xp): # verify interpolation outside the original bounds x = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=xp.float64) def mapping(x): return (x[0] - 0.5), (x[1] - 0.5) expected_result = xp.asarray([[0.25, 0.75, 1.25], [1.25, 3.00, 4.00]]) assert_array_almost_equal( ndimage.geometric_transform(x, mapping, mode='grid-constant', order=1), expected_result, ) @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', 'mirror', 'reflect']) @pytest.mark.parametrize('order', range(6)) def test_geometric_transform_vs_padded(self, order, mode, xp): def mapping(x): return (x[0] - 0.4), (x[1] + 2.3) # Manually pad and then extract center after the transform to get the # expected result. x = np.arange(144, dtype=float).reshape(12, 12) npad = 24 pad_mode = ndimage_to_numpy_mode.get(mode) x_padded = np.pad(x, npad, mode=pad_mode) x = xp.asarray(x) x_padded = xp.asarray(x_padded) center_slice = tuple([slice(npad, -npad)] * x.ndim) expected_result = ndimage.geometric_transform( x_padded, mapping, mode=mode, order=order)[center_slice] xp_assert_close( ndimage.geometric_transform(x, mapping, mode=mode, order=order), expected_result, rtol=1e-7, ) @skip_xp_backends(np_only=True, reason='endianness is numpy-specific') def test_geometric_transform_endianness_with_output_parameter(self, xp): # geometric transform given output ndarray or dtype with # non-native endianness. see issue #4127 data = np.asarray([1]) def mapping(x): return x for out in [data.dtype, data.dtype.newbyteorder(), np.empty_like(data), np.empty_like(data).astype(data.dtype.newbyteorder())]: returned = ndimage.geometric_transform(data, mapping, data.shape, output=out) result = out if returned is None else returned assert_array_almost_equal(result, [1]) @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific') def test_geometric_transform_with_string_output(self, xp): data = xp.asarray([1]) def mapping(x): return x out = ndimage.geometric_transform(data, mapping, output='f') assert out.dtype is np.dtype('f') assert_array_almost_equal(out, [1]) @make_xp_test_case(ndimage.map_coordinates)
TestGeometricTransformExtra
python
lepture__authlib
authlib/oauth2/rfc6749/requests.py
{ "start": 4614, "end": 4705 }
class ____: @property def data(self): raise NotImplementedError()
JsonPayload
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/distributions.py
{ "start": 6092, "end": 8225 }
class ____(nn.Module): def __init__(self, hidden_size: int, act_sizes: List[int]): super().__init__() self.act_sizes = act_sizes self.branches = self._create_policy_branches(hidden_size) def _create_policy_branches(self, hidden_size: int) -> nn.ModuleList: branches = [] for size in self.act_sizes: branch_output_layer = linear_layer( hidden_size, size, kernel_init=Initialization.KaimingHeNormal, kernel_gain=0.1, bias_init=Initialization.Zero, ) branches.append(branch_output_layer) return nn.ModuleList(branches) def _mask_branch( self, logits: torch.Tensor, allow_mask: torch.Tensor ) -> torch.Tensor: # Zero out masked logits, then subtract a large value. Technique mentioned here: # https://arxiv.org/abs/2006.14171. Our implementation is ONNX and Sentis-friendly. block_mask = -1.0 * allow_mask + 1.0 # We do -1 * tensor + constant instead of constant - tensor because it seems # Sentis might swap the inputs of a "Sub" operation logits = logits * allow_mask - 1e8 * block_mask return logits def _split_masks(self, masks: torch.Tensor) -> List[torch.Tensor]: split_masks = [] for idx, _ in enumerate(self.act_sizes): start = int(np.sum(self.act_sizes[:idx])) end = int(np.sum(self.act_sizes[: idx + 1])) split_masks.append(masks[:, start:end]) return split_masks def forward(self, inputs: torch.Tensor, masks: torch.Tensor) -> List[DistInstance]: # Todo - Support multiple branches in mask code branch_distributions = [] masks = self._split_masks(masks) for idx, branch in enumerate(self.branches): logits = branch(inputs) norm_logits = self._mask_branch(logits, masks[idx]) distribution = CategoricalDistInstance(norm_logits) branch_distributions.append(distribution) return branch_distributions
MultiCategoricalDistribution
python
kubernetes-client__python
kubernetes/client/models/v1_glusterfs_persistent_volume_source.py
{ "start": 383, "end": 7759 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'endpoints': 'str', 'endpoints_namespace': 'str', 'path': 'str', 'read_only': 'bool' } attribute_map = { 'endpoints': 'endpoints', 'endpoints_namespace': 'endpointsNamespace', 'path': 'path', 'read_only': 'readOnly' } def __init__(self, endpoints=None, endpoints_namespace=None, path=None, read_only=None, local_vars_configuration=None): # noqa: E501 """V1GlusterfsPersistentVolumeSource - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._endpoints = None self._endpoints_namespace = None self._path = None self._read_only = None self.discriminator = None self.endpoints = endpoints if endpoints_namespace is not None: self.endpoints_namespace = endpoints_namespace self.path = path if read_only is not None: self.read_only = read_only @property def endpoints(self): """Gets the endpoints of this V1GlusterfsPersistentVolumeSource. # noqa: E501 endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :return: The endpoints of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :rtype: str """ return self._endpoints @endpoints.setter def endpoints(self, endpoints): """Sets the endpoints of this V1GlusterfsPersistentVolumeSource. endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param endpoints: The endpoints of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and endpoints is None: # noqa: E501 raise ValueError("Invalid value for `endpoints`, must not be `None`") # noqa: E501 self._endpoints = endpoints @property def endpoints_namespace(self): """Gets the endpoints_namespace of this V1GlusterfsPersistentVolumeSource. # noqa: E501 endpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :return: The endpoints_namespace of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :rtype: str """ return self._endpoints_namespace @endpoints_namespace.setter def endpoints_namespace(self, endpoints_namespace): """Sets the endpoints_namespace of this V1GlusterfsPersistentVolumeSource. endpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param endpoints_namespace: The endpoints_namespace of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: str """ self._endpoints_namespace = endpoints_namespace @property def path(self): """Gets the path of this V1GlusterfsPersistentVolumeSource. # noqa: E501 path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :return: The path of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :rtype: str """ return self._path @path.setter def path(self, path): """Sets the path of this V1GlusterfsPersistentVolumeSource. path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param path: The path of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and path is None: # noqa: E501 raise ValueError("Invalid value for `path`, must not be `None`") # noqa: E501 self._path = path @property def read_only(self): """Gets the read_only of this V1GlusterfsPersistentVolumeSource. # noqa: E501 readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :return: The read_only of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :rtype: bool """ return self._read_only @read_only.setter def read_only(self, read_only): """Sets the read_only of this V1GlusterfsPersistentVolumeSource. readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param read_only: The read_only of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: bool """ self._read_only = read_only def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1GlusterfsPersistentVolumeSource): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1GlusterfsPersistentVolumeSource): return True return self.to_dict() != other.to_dict()
V1GlusterfsPersistentVolumeSource
python
wandb__wandb
wandb/vendor/pygments/lexers/python.py
{ "start": 18697, "end": 21892 }
class ____(Lexer): """ For Python console output or doctests, such as: .. sourcecode:: pycon >>> a = 'foo' >>> print a foo >>> 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero Additional options: `python3` Use Python 3 lexer for code. Default is ``False``. .. versionadded:: 1.0 """ name = 'Python console session' aliases = ['pycon'] mimetypes = ['text/x-python-doctest'] def __init__(self, **options): self.python3 = get_bool_opt(options, 'python3', False) Lexer.__init__(self, **options) def get_tokens_unprocessed(self, text): if self.python3: pylexer = Python3Lexer(**self.options) tblexer = Python3TracebackLexer(**self.options) else: pylexer = PythonLexer(**self.options) tblexer = PythonTracebackLexer(**self.options) curcode = '' insertions = [] curtb = '' tbindex = 0 tb = 0 for match in line_re.finditer(text): line = match.group() if line.startswith(u'>>> ') or line.startswith(u'... '): tb = 0 insertions.append((len(curcode), [(0, Generic.Prompt, line[:4])])) curcode += line[4:] elif line.rstrip() == u'...' and not tb: # only a new >>> prompt can end an exception block # otherwise an ellipsis in place of the traceback frames # will be mishandled insertions.append((len(curcode), [(0, Generic.Prompt, u'...')])) curcode += line[3:] else: if curcode: for item in do_insertions( insertions, pylexer.get_tokens_unprocessed(curcode)): yield item curcode = '' insertions = [] if (line.startswith(u'Traceback (most recent call last):') or re.match(u' File "[^"]+", line \\d+\\n$', line)): tb = 1 curtb = line tbindex = match.start() elif line == 'KeyboardInterrupt\n': yield match.start(), Name.Class, line elif tb: curtb += line if not (line.startswith(' ') or line.strip() == u'...'): tb = 0 for i, t, v in tblexer.get_tokens_unprocessed(curtb): yield tbindex+i, t, v curtb = '' else: yield match.start(), Generic.Output, line if curcode: for item in do_insertions(insertions, pylexer.get_tokens_unprocessed(curcode)): yield item if curtb: for i, t, v in tblexer.get_tokens_unprocessed(curtb): yield tbindex+i, t, v
PythonConsoleLexer
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/urlfetch/snippets/main.py
{ "start": 2036, "end": 2878 }
class ____(webapp2.RequestHandler): """Demonstrates an HTTP POST form query using urlfetch.""" form_fields = { "first_name": "Albert", "last_name": "Johnson", } def get(self): # [START gae_urlfetch_snippets_urlfetch_post] try: form_data = urllib.urlencode(UrlPostHandler.form_fields) headers = {"Content-Type": "application/x-www-form-urlencoded"} result = urlfetch.fetch( url="http://localhost:8080/submit_form", payload=form_data, method=urlfetch.POST, headers=headers, ) self.response.write(result.content) except urlfetch.Error: logging.exception("Caught exception fetching url") # [END gae_urlfetch_snippets_urlfetch_post]
UrlPostHandler
python
ray-project__ray
release/ray_release/exception.py
{ "start": 947, "end": 1024 }
class ____(RuntimeError): exit_code = ExitCode.UNSPECIFIED
ReleaseTestError
python
pypa__pip
src/pip/_vendor/rich/syntax.py
{ "start": 7621, "end": 7967 }
class ____: """Descriptor to get and set padding.""" def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]: """Space around the Syntax.""" return obj._padding def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None: obj._padding = Padding.unpack(padding)
PaddingProperty
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/job_base.py
{ "start": 3098, "end": 4293 }
class ____(IJob): def __init__( self, job_name: str, repository_def: "RepositoryDefinition", ): self._job_name = job_name self._repository_def = repository_def def get_definition(self) -> "JobDefinition": return self._repository_def.get_job(self._job_name) def get_repository_definition(self) -> Optional["RepositoryDefinition"]: return self._repository_def @property def op_selection(self) -> Optional[AbstractSet[str]]: return self.get_definition().op_selection @property def asset_selection(self) -> Optional[AbstractSet[AssetKey]]: return self.get_definition().asset_selection @property def asset_check_selection(self) -> Optional[AbstractSet[AssetCheckKey]]: return self.get_definition().asset_check_selection def get_subset( self, *, op_selection: Optional[Iterable[str]] = None, asset_selection: Optional[AbstractSet[AssetKey]] = None, asset_check_selection: Optional[AbstractSet[AssetCheckKey]] = None, ) -> "RepoBackedJob": raise NotImplementedError("RepoBackedJob does not support get_subset")
RepoBackedJob
python
sympy__sympy
sympy/printing/mathml.py
{ "start": 2577, "end": 18949 }
class ____(MathMLPrinterBase): """Prints an expression to the Content MathML markup language. References: https://www.w3.org/TR/MathML2/chapter4.html """ printmethod = "_mathml_content" def mathml_tag(self, e): """Returns the MathML tag for an expression.""" translate = { 'Add': 'plus', 'Mul': 'times', 'Derivative': 'diff', 'Number': 'cn', 'int': 'cn', 'Pow': 'power', 'Max': 'max', 'Min': 'min', 'Abs': 'abs', 'And': 'and', 'Or': 'or', 'Xor': 'xor', 'Not': 'not', 'Implies': 'implies', 'Symbol': 'ci', 'MatrixSymbol': 'ci', 'RandomSymbol': 'ci', 'Integral': 'int', 'Sum': 'sum', 'sin': 'sin', 'cos': 'cos', 'tan': 'tan', 'cot': 'cot', 'csc': 'csc', 'sec': 'sec', 'sinh': 'sinh', 'cosh': 'cosh', 'tanh': 'tanh', 'coth': 'coth', 'csch': 'csch', 'sech': 'sech', 'asin': 'arcsin', 'asinh': 'arcsinh', 'acos': 'arccos', 'acosh': 'arccosh', 'atan': 'arctan', 'atanh': 'arctanh', 'atan2': 'arctan', 'acot': 'arccot', 'acoth': 'arccoth', 'asec': 'arcsec', 'asech': 'arcsech', 'acsc': 'arccsc', 'acsch': 'arccsch', 'log': 'ln', 'Equality': 'eq', 'Unequality': 'neq', 'GreaterThan': 'geq', 'LessThan': 'leq', 'StrictGreaterThan': 'gt', 'StrictLessThan': 'lt', 'Union': 'union', 'Intersection': 'intersect', } for cls in e.__class__.__mro__: n = cls.__name__ if n in translate: return translate[n] # Not found in the MRO set n = e.__class__.__name__ return n.lower() def _print_Mul(self, expr): if expr.could_extract_minus_sign(): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('minus')) x.appendChild(self._print_Mul(-expr)) return x from sympy.simplify import fraction numer, denom = fraction(expr) if denom is not S.One: x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('divide')) x.appendChild(self._print(numer)) x.appendChild(self._print(denom)) return x coeff, terms = expr.as_coeff_mul() if coeff is S.One and len(terms) == 1: # XXX since the negative coefficient has been handled, I don't # think a coeff of 1 can remain return self._print(terms[0]) if self.order != 'old': terms = Mul._from_args(terms).as_ordered_factors() x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('times')) if coeff != 1: x.appendChild(self._print(coeff)) for term in terms: x.appendChild(self._print(term)) return x def _print_Add(self, expr, order=None): args = self._as_ordered_terms(expr, order=order) lastProcessed = self._print(args[0]) plusNodes = [] for arg in args[1:]: if arg.could_extract_minus_sign(): # use minus x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('minus')) x.appendChild(lastProcessed) x.appendChild(self._print(-arg)) # invert expression since this is now minused lastProcessed = x if arg == args[-1]: plusNodes.append(lastProcessed) else: plusNodes.append(lastProcessed) lastProcessed = self._print(arg) if arg == args[-1]: plusNodes.append(self._print(arg)) if len(plusNodes) == 1: return lastProcessed x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('plus')) while plusNodes: x.appendChild(plusNodes.pop(0)) return x def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") root = self.dom.createElement('piecewise') for i, (e, c) in enumerate(expr.args): if i == len(expr.args) - 1 and c == True: piece = self.dom.createElement('otherwise') piece.appendChild(self._print(e)) else: piece = self.dom.createElement('piece') piece.appendChild(self._print(e)) piece.appendChild(self._print(c)) root.appendChild(piece) return root def _print_MatrixBase(self, m): x = self.dom.createElement('matrix') for i in range(m.rows): x_r = self.dom.createElement('matrixrow') for j in range(m.cols): x_r.appendChild(self._print(m[i, j])) x.appendChild(x_r) return x def _print_Rational(self, e): if e.q == 1: # don't divide x = self.dom.createElement('cn') x.appendChild(self.dom.createTextNode(str(e.p))) return x x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('divide')) # numerator xnum = self.dom.createElement('cn') xnum.appendChild(self.dom.createTextNode(str(e.p))) # denominator xdenom = self.dom.createElement('cn') xdenom.appendChild(self.dom.createTextNode(str(e.q))) x.appendChild(xnum) x.appendChild(xdenom) return x def _print_Limit(self, e): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement(self.mathml_tag(e))) x_1 = self.dom.createElement('bvar') x_2 = self.dom.createElement('lowlimit') x_1.appendChild(self._print(e.args[1])) x_2.appendChild(self._print(e.args[2])) x.appendChild(x_1) x.appendChild(x_2) x.appendChild(self._print(e.args[0])) return x def _print_ImaginaryUnit(self, e): return self.dom.createElement('imaginaryi') def _print_EulerGamma(self, e): return self.dom.createElement('eulergamma') def _print_GoldenRatio(self, e): """We use unicode #x3c6 for Greek letter phi as defined here https://www.w3.org/2003/entities/2007doc/isogrk1.html""" x = self.dom.createElement('cn') x.appendChild(self.dom.createTextNode("\N{GREEK SMALL LETTER PHI}")) return x def _print_Exp1(self, e): return self.dom.createElement('exponentiale') def _print_Pi(self, e): return self.dom.createElement('pi') def _print_Infinity(self, e): return self.dom.createElement('infinity') def _print_NaN(self, e): return self.dom.createElement('notanumber') def _print_EmptySet(self, e): return self.dom.createElement('emptyset') def _print_BooleanTrue(self, e): return self.dom.createElement('true') def _print_BooleanFalse(self, e): return self.dom.createElement('false') def _print_NegativeInfinity(self, e): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('minus')) x.appendChild(self.dom.createElement('infinity')) return x def _print_Integral(self, e): def lime_recur(limits): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement(self.mathml_tag(e))) bvar_elem = self.dom.createElement('bvar') bvar_elem.appendChild(self._print(limits[0][0])) x.appendChild(bvar_elem) if len(limits[0]) == 3: low_elem = self.dom.createElement('lowlimit') low_elem.appendChild(self._print(limits[0][1])) x.appendChild(low_elem) up_elem = self.dom.createElement('uplimit') up_elem.appendChild(self._print(limits[0][2])) x.appendChild(up_elem) if len(limits[0]) == 2: up_elem = self.dom.createElement('uplimit') up_elem.appendChild(self._print(limits[0][1])) x.appendChild(up_elem) if len(limits) == 1: x.appendChild(self._print(e.function)) else: x.appendChild(lime_recur(limits[1:])) return x limits = list(e.limits) limits.reverse() return lime_recur(limits) def _print_Sum(self, e): # Printer can be shared because Sum and Integral have the # same internal representation. return self._print_Integral(e) def _print_Symbol(self, sym): ci = self.dom.createElement(self.mathml_tag(sym)) def join(items): if len(items) > 1: mrow = self.dom.createElement('mml:mrow') for i, item in enumerate(items): if i > 0: mo = self.dom.createElement('mml:mo') mo.appendChild(self.dom.createTextNode(" ")) mrow.appendChild(mo) mi = self.dom.createElement('mml:mi') mi.appendChild(self.dom.createTextNode(item)) mrow.appendChild(mi) return mrow else: mi = self.dom.createElement('mml:mi') mi.appendChild(self.dom.createTextNode(items[0])) return mi # translate name, supers and subs to unicode characters def translate(s): if s in greek_unicode: return greek_unicode.get(s) else: return s name, supers, subs = self._split_super_sub(sym.name) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] mname = self.dom.createElement('mml:mi') mname.appendChild(self.dom.createTextNode(name)) if not supers: if not subs: ci.appendChild(self.dom.createTextNode(name)) else: msub = self.dom.createElement('mml:msub') msub.appendChild(mname) msub.appendChild(join(subs)) ci.appendChild(msub) else: if not subs: msup = self.dom.createElement('mml:msup') msup.appendChild(mname) msup.appendChild(join(supers)) ci.appendChild(msup) else: msubsup = self.dom.createElement('mml:msubsup') msubsup.appendChild(mname) msubsup.appendChild(join(subs)) msubsup.appendChild(join(supers)) ci.appendChild(msubsup) return ci _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Pow(self, e): # Here we use root instead of power if the exponent is the reciprocal # of an integer if (self._settings['root_notation'] and e.exp.is_Rational and e.exp.p == 1): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('root')) if e.exp.q != 2: xmldeg = self.dom.createElement('degree') xmlcn = self.dom.createElement('cn') xmlcn.appendChild(self.dom.createTextNode(str(e.exp.q))) xmldeg.appendChild(xmlcn) x.appendChild(xmldeg) x.appendChild(self._print(e.base)) return x x = self.dom.createElement('apply') x_1 = self.dom.createElement(self.mathml_tag(e)) x.appendChild(x_1) x.appendChild(self._print(e.base)) x.appendChild(self._print(e.exp)) return x def _print_Number(self, e): x = self.dom.createElement(self.mathml_tag(e)) x.appendChild(self.dom.createTextNode(str(e))) return x def _print_Float(self, e): x = self.dom.createElement(self.mathml_tag(e)) repr_e = mlib_to_str(e._mpf_, repr_dps(e._prec)) x.appendChild(self.dom.createTextNode(repr_e)) return x def _print_Derivative(self, e): x = self.dom.createElement('apply') diff_symbol = self.mathml_tag(e) if requires_partial(e.expr): diff_symbol = 'partialdiff' x.appendChild(self.dom.createElement(diff_symbol)) x_1 = self.dom.createElement('bvar') for sym, times in reversed(e.variable_count): x_1.appendChild(self._print(sym)) if times > 1: degree = self.dom.createElement('degree') degree.appendChild(self._print(sympify(times))) x_1.appendChild(degree) x.appendChild(x_1) x.appendChild(self._print(e.expr)) return x def _print_Function(self, e): x = self.dom.createElement("apply") x.appendChild(self.dom.createElement(self.mathml_tag(e))) for arg in e.args: x.appendChild(self._print(arg)) return x def _print_Basic(self, e): x = self.dom.createElement(self.mathml_tag(e)) for arg in e.args: x.appendChild(self._print(arg)) return x def _print_AssocOp(self, e): x = self.dom.createElement('apply') x_1 = self.dom.createElement(self.mathml_tag(e)) x.appendChild(x_1) for arg in e.args: x.appendChild(self._print(arg)) return x def _print_Relational(self, e): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement(self.mathml_tag(e))) x.appendChild(self._print(e.lhs)) x.appendChild(self._print(e.rhs)) return x def _print_list(self, seq): """MathML reference for the <list> element: https://www.w3.org/TR/MathML2/chapter4.html#contm.list""" dom_element = self.dom.createElement('list') for item in seq: dom_element.appendChild(self._print(item)) return dom_element def _print_int(self, p): dom_element = self.dom.createElement(self.mathml_tag(p)) dom_element.appendChild(self.dom.createTextNode(str(p))) return dom_element _print_Implies = _print_AssocOp _print_Not = _print_AssocOp _print_Xor = _print_AssocOp def _print_FiniteSet(self, e): x = self.dom.createElement('set') for arg in e.args: x.appendChild(self._print(arg)) return x def _print_Complement(self, e): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('setdiff')) for arg in e.args: x.appendChild(self._print(arg)) return x def _print_ProductSet(self, e): x = self.dom.createElement('apply') x.appendChild(self.dom.createElement('cartesianproduct')) for arg in e.args: x.appendChild(self._print(arg)) return x def _print_Lambda(self, e): # MathML reference for the lambda element: # https://www.w3.org/TR/MathML2/chapter4.html#id.4.2.1.7 x = self.dom.createElement(self.mathml_tag(e)) for arg in e.signature: x_1 = self.dom.createElement('bvar') x_1.appendChild(self._print(arg)) x.appendChild(x_1) x.appendChild(self._print(e.expr)) return x # XXX Symmetric difference is not supported for MathML content printers.
MathMLContentPrinter
python
doocs__leetcode
solution/1600-1699/1659.Maximize Grid Happiness/Solution.py
{ "start": 0, "end": 1408 }
class ____: def getMaxGridHappiness( self, m: int, n: int, introvertsCount: int, extrovertsCount: int ) -> int: @cache def dfs(i: int, pre: int, ic: int, ec: int) -> int: if i == m or (ic == 0 and ec == 0): return 0 ans = 0 for cur in range(mx): if ix[cur] <= ic and ex[cur] <= ec: a = f[cur] + g[pre][cur] b = dfs(i + 1, cur, ic - ix[cur], ec - ex[cur]) ans = max(ans, a + b) return ans mx = pow(3, n) f = [0] * mx g = [[0] * mx for _ in range(mx)] h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] bits = [[0] * n for _ in range(mx)] ix = [0] * mx ex = [0] * mx for i in range(mx): mask = i for j in range(n): mask, x = divmod(mask, 3) bits[i][j] = x if x == 1: ix[i] += 1 f[i] += 120 elif x == 2: ex[i] += 1 f[i] += 40 if j: f[i] += h[x][bits[i][j - 1]] for i in range(mx): for j in range(mx): for k in range(n): g[i][j] += h[bits[i][k]][bits[j][k]] return dfs(0, 0, introvertsCount, extrovertsCount)
Solution
python
django__django
tests/bulk_create/models.py
{ "start": 998, "end": 1034 }
class ____(Place): pass
Restaurant
python
kamyu104__LeetCode-Solutions
Python/uncommon-words-from-two-sentences.py
{ "start": 62, "end": 377 }
class ____(object): def uncommonFromSentences(self, A, B): """ :type A: str :type B: str :rtype: List[str] """ count = collections.Counter(A.split()) count += collections.Counter(B.split()) return [word for word in count if count[word] == 1]
Solution
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 11017, "end": 11893 }
class ____(PipenvException): def __init__(self, message, no_version_found=False): extra = ( "Your dependencies could not be resolved. You likely have a " "mismatch in your sub-dependencies.\n" "You can use [yellow]$ pipenv run pip install <requirement_name>[/yellow] to bypass this mechanism, then run " "[yellow]$ pipenv graph[/yellow] to inspect the versions actually installed in the virtualenv.\n" "Hint: try [yellow]$ pipenv lock --pre[/yellow] if it is a pre-release dependency." ) if "no version found at all" in str(message): message += ( "[cyan]Please check your version specifier and version number. " "See PEP440 for more information.[/cyan]" ) PipenvException.__init__(self, message, extra=extra)
ResolutionFailure
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams5.py
{ "start": 1154, "end": 1266 }
class ____[R: t2]: ... # This should generate an error because constraints must be legal # type expressions.
ClassL
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 76738, "end": 78205 }
class ____(PrefectOperatorFilterBaseModel): """Filter artifacts. Only artifacts matching all criteria will be returned""" id: Optional[ArtifactFilterId] = Field( default=None, description="Filter criteria for `Artifact.id`" ) key: Optional[ArtifactFilterKey] = Field( default=None, description="Filter criteria for `Artifact.key`" ) flow_run_id: Optional[ArtifactFilterFlowRunId] = Field( default=None, description="Filter criteria for `Artifact.flow_run_id`" ) task_run_id: Optional[ArtifactFilterTaskRunId] = Field( default=None, description="Filter criteria for `Artifact.task_run_id`" ) type: Optional[ArtifactFilterType] = Field( default=None, description="Filter criteria for `Artifact.type`" ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressionArgument[bool]]: filters: list[sa.ColumnExpressionArgument[bool]] = [] if self.id is not None: filters.append(self.id.as_sql_filter()) if self.key is not None: filters.append(self.key.as_sql_filter()) if self.flow_run_id is not None: filters.append(self.flow_run_id.as_sql_filter()) if self.task_run_id is not None: filters.append(self.task_run_id.as_sql_filter()) if self.type is not None: filters.append(self.type.as_sql_filter()) return filters
ArtifactFilter
python
pandas-dev__pandas
pandas/tests/indexing/test_datetime.py
{ "start": 169, "end": 5714 }
class ____: def test_get_loc_naive_dti_aware_str_deprecated(self): # GH#46903 ts = Timestamp("20130101")._value dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)]) ser = Series(range(100), index=dti) key = "2013-01-01 00:00:00.000000050+0000" msg = re.escape(repr(key)) with pytest.raises(KeyError, match=msg): ser[key] with pytest.raises(KeyError, match=msg): dti.get_loc(key) def test_indexing_with_datetime_tz(self): # GH#8260 # support datetime64 with tz idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") dr = date_range("20130110", periods=3) df = DataFrame({"A": idx, "B": dr}) df["C"] = idx df.iloc[1, 1] = pd.NaT df.iloc[1, 2] = pd.NaT expected = Series( [Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT], index=list("ABC"), dtype="object", name=1, ) # indexing result = df.iloc[1] tm.assert_series_equal(result, expected) result = df.loc[1] tm.assert_series_equal(result, expected) def test_indexing_fast_xs(self): # indexing - fast_xs df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC", unit="ns")}) result = df.iloc[5] expected = Series( [Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], index=["a"], name=5, dtype="M8[ns, UTC]", ) tm.assert_series_equal(result, expected) result = df.loc[5] tm.assert_series_equal(result, expected) # indexing - boolean result = df[df.a > df.a[3]] expected = df.iloc[4:] tm.assert_frame_equal(result, expected) def test_consistency_with_tz_aware_scalar(self): # xef gh-12938 # various ways of indexing the same tz-aware scalar df = Series([Timestamp("2016-03-30 14:35:25", tz="Europe/Brussels")]).to_frame() df = pd.concat([df, df]).reset_index(drop=True) expected = Timestamp("2016-03-30 14:35:25+0200", tz="Europe/Brussels") result = df[0][0] assert result == expected result = df.iloc[0, 0] assert result == expected result = df.loc[0, 0] assert result == expected result = df.iat[0, 0] assert result == expected result = df.at[0, 0] assert result == expected result = df[0].loc[0] assert result == expected result = df[0].at[0] assert result == expected def test_indexing_with_datetimeindex_tz(self, indexer_sl): # GH 12050 # indexing on a series with a datetimeindex with tz index = date_range("2015-01-01", periods=2, tz="utc") ser = Series(range(2), index=index, dtype="int64") # list-like indexing for sel in (index, list(index)): # getitem result = indexer_sl(ser)[sel] expected = ser.copy() if sel is not index: expected.index = expected.index._with_freq(None) tm.assert_series_equal(result, expected) # setitem result = ser.copy() indexer_sl(result)[sel] = 1 expected = Series(1, index=index) tm.assert_series_equal(result, expected) # single element indexing # getitem assert indexer_sl(ser)[index[1]] == 1 # setitem result = ser.copy() indexer_sl(result)[index[1]] = 5 expected = Series([0, 5], index=index) tm.assert_series_equal(result, expected) def test_nanosecond_getitem_setitem_with_tz(self): # GH 11679 data = ["2016-06-28 08:30:00.123456789"] index = pd.DatetimeIndex(data, dtype="datetime64[ns, America/Chicago]") df = DataFrame({"a": [10]}, index=index) result = df.loc[df.index[0]] expected = Series(10, index=["a"], name=df.index[0]) tm.assert_series_equal(result, expected) result = df.copy() result.loc[df.index[0], "a"] = -1 expected = DataFrame(-1, index=index, columns=["a"]) tm.assert_frame_equal(result, expected) def test_getitem_str_slice_millisecond_resolution(self, frame_or_series): # GH#33589 keys = [ "2017-10-25T16:25:04.151", "2017-10-25T16:25:04.252", "2017-10-25T16:50:05.237", "2017-10-25T16:50:05.238", ] obj = frame_or_series( [1, 2, 3, 4], index=[Timestamp(x) for x in keys], ) result = obj[keys[1] : keys[2]] expected = frame_or_series( [2, 3], index=[ Timestamp(keys[1]), Timestamp(keys[2]), ], ) tm.assert_equal(result, expected) def test_getitem_pyarrow_index(self, frame_or_series): # GH 53644 pytest.importorskip("pyarrow") obj = frame_or_series( range(5), index=date_range("2020", freq="D", periods=5).astype( "timestamp[us][pyarrow]" ), ) result = obj.loc[obj.index[:-3]] expected = frame_or_series( range(2), index=date_range("2020", freq="D", periods=2).astype( "timestamp[us][pyarrow]" ), ) tm.assert_equal(result, expected)
TestDatetimeIndex
python
ray-project__ray
python/ray/dag/tests/test_class_dag.py
{ "start": 159, "end": 336 }
class ____: def __init__(self, init_value=0): self.i = init_value def inc(self): self.i += 1 def get(self): return self.i @ray.remote
Counter
python
coleifer__peewee
tests/db_url.py
{ "start": 127, "end": 3532 }
class ____(BaseTestCase): def test_db_url_parse(self): cfg = parse('mysql://usr:pwd@hst:123/db') self.assertEqual(cfg['user'], 'usr') self.assertEqual(cfg['passwd'], 'pwd') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(cfg['port'], 123) cfg = parse('postgresql://usr:pwd@hst/db') self.assertEqual(cfg['password'], 'pwd') cfg = parse('mysql+pool://usr:pwd@hst:123/db' '?max_connections=42&stale_timeout=8001.2&zai=&baz=3.4.5' '&boolz=false') self.assertEqual(cfg['user'], 'usr') self.assertEqual(cfg['password'], 'pwd') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(cfg['port'], 123) self.assertEqual(cfg['max_connections'], 42) self.assertEqual(cfg['stale_timeout'], 8001.2) self.assertEqual(cfg['zai'], '') self.assertEqual(cfg['baz'], '3.4.5') self.assertEqual(cfg['boolz'], False) def test_db_url_no_unquoting(self): # By default, neither user nor password is not unescaped. cfg = parse('mysql://usr%40example.com:pwd%23@hst:123/db') self.assertEqual(cfg['user'], 'usr%40example.com') self.assertEqual(cfg['passwd'], 'pwd%23') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(cfg['port'], 123) def test_db_url_quoted_password(self): cfg = parse('mysql://usr:pwd%23%20@hst:123/db', unquote_password=True) self.assertEqual(cfg['user'], 'usr') self.assertEqual(cfg['passwd'], 'pwd# ') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(cfg['port'], 123) def test_db_url_quoted_user(self): cfg = parse('mysql://usr%40example.com:p%40sswd@hst:123/db', unquote_user=True) self.assertEqual(cfg['user'], 'usr@example.com') self.assertEqual(cfg['passwd'], 'p%40sswd') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(cfg['port'], 123) def test_db_url(self): db = connect('sqlite:///:memory:') self.assertTrue(isinstance(db, SqliteDatabase)) self.assertEqual(db.database, ':memory:') db = connect('sqlite:///:memory:', pragmas=( ('journal_mode', 'MEMORY'),)) self.assertTrue(('journal_mode', 'MEMORY') in db._pragmas) #db = connect('sqliteext:///foo/bar.db') #self.assertTrue(isinstance(db, SqliteExtDatabase)) #self.assertEqual(db.database, 'foo/bar.db') db = connect('sqlite:////this/is/absolute.path') self.assertEqual(db.database, '/this/is/absolute.path') db = connect('sqlite://') self.assertTrue(isinstance(db, SqliteDatabase)) self.assertEqual(db.database, ':memory:') db = connect('sqlite:///test.db?p1=1?a&p2=22&p3=xyz') self.assertTrue(isinstance(db, SqliteDatabase)) self.assertEqual(db.database, 'test.db') self.assertEqual(db.connect_params, { 'p1': '1?a', 'p2': 22, 'p3': 'xyz'}) def test_bad_scheme(self): def _test_scheme(): connect('missing:///') self.assertRaises(RuntimeError, _test_scheme)
TestDBUrl
python
pennersr__django-allauth
tests/apps/socialaccount/providers/mediawiki/tests.py
{ "start": 246, "end": 1203 }
class ____(OAuth2TestsMixin, TestCase): provider_id = MediaWikiProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "iss": "https://meta.wikimedia.org", "sub": 12345, "aud": "1234567890abcdef", "exp": 946681300, "iat": 946681200, "username": "John Doe", "editcount": 123, "confirmed_email": true, "blocked": false, "registered": "20000101000000", "groups": ["*", "user", "autoconfirmed"], "rights": ["read", "edit"], "grants": ["basic"], "email": "johndoe@example.com" } """, ) def get_expected_to_str(self): return "John Doe"
MediaWikiTests
python
spack__spack
lib/spack/spack/spec.py
{ "start": 219681, "end": 220038 }
class ____(spack.error.SpecError): """Raised when an invalid conditional variant is specified.""" def __init__(self, variant, when, spec): msg = f"Invalid variant {variant} for spec {spec}.\n" msg += f"{variant} is only available for {spec.name} when satisfying one of {when}." super().__init__(msg)
InvalidVariantForSpecError
python
keras-team__keras
keras/src/layers/preprocessing/hashing.py
{ "start": 338, "end": 11188 }
class ____(Layer): """A preprocessing layer which hashes and bins categorical features. This layer transforms categorical inputs to hashed output. It element-wise converts a ints or strings to ints in a fixed range. The stable hash function uses `tensorflow::ops::Fingerprint` to produce the same output consistently across all platforms. This layer uses [FarmHash64](https://github.com/google/farmhash) by default, which provides a consistent hashed output across different platforms and is stable across invocations, regardless of device and context, by mixing the input bits thoroughly. If you want to obfuscate the hashed output, you can also pass a random `salt` argument in the constructor. In that case, the layer will use the [SipHash64](https://github.com/google/highwayhash) hash function, with the `salt` value serving as additional input to the hash function. **Note:** This layer internally uses TensorFlow. It cannot be used as part of the compiled computation graph of a model with any backend other than TensorFlow. It can however be used with any backend when running eagerly. It can also always be used as part of an input preprocessing pipeline with any backend (outside the model itself), which is how we recommend to use this layer. **Note:** This layer is safe to use inside a `tf.data` pipeline (independently of which backend you're using). **Example (FarmHash64)** >>> layer = keras.layers.Hashing(num_bins=3) >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']] >>> layer(inp) array([[1], [0], [1], [1], [2]])> **Example (FarmHash64) with a mask value** >>> layer = keras.layers.Hashing(num_bins=3, mask_value='') >>> inp = [['A'], ['B'], [''], ['C'], ['D']] >>> layer(inp) array([[1], [1], [0], [2], [2]]) **Example (SipHash64)** >>> layer = keras.layers.Hashing(num_bins=3, salt=[133, 137]) >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']] >>> layer(inp) array([[1], [2], [1], [0], [2]]) **Example (Siphash64 with a single integer, same as `salt=[133, 133]`)** >>> layer = keras.layers.Hashing(num_bins=3, salt=133) >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']] >>> layer(inp) array([[0], [0], [2], [1], [0]]) Args: num_bins: Number of hash bins. Note that this includes the `mask_value` bin, so the effective number of bins is `(num_bins - 1)` if `mask_value` is set. mask_value: A value that represents masked inputs, which are mapped to index 0. `None` means no mask term will be added and the hashing will start at index 0. Defaults to `None`. salt: A single unsigned integer or None. If passed, the hash function used will be SipHash64, with these values used as an additional input (known as a "salt" in cryptography). These should be non-zero. If `None`, uses the FarmHash64 hash function. It also supports tuple/list of 2 unsigned integer numbers, see reference paper for details. Defaults to `None`. output_mode: Specification for the output of the layer. Values can be `"int"`, `"one_hot"`, `"multi_hot"`, or `"count"` configuring the layer as follows: - `"int"`: Return the integer bin indices directly. - `"one_hot"`: Encodes each individual element in the input into an array the same size as `num_bins`, containing a 1 at the input's bin index. If the last dimension is size 1, will encode on that dimension. If the last dimension is not size 1, will append a new dimension for the encoded output. - `"multi_hot"`: Encodes each sample in the input into a single array the same size as `num_bins`, containing a 1 for each bin index index present in the sample. Treats the last dimension as the sample dimension, if input shape is `(..., sample_length)`, output shape will be `(..., num_tokens)`. - `"count"`: As `"multi_hot"`, but the int array contains a count of the number of times the bin index appeared in the sample. Defaults to `"int"`. sparse: Boolean. Only applicable to `"one_hot"`, `"multi_hot"`, and `"count"` output modes. Only supported with TensorFlow backend. If `True`, returns a `SparseTensor` instead of a dense `Tensor`. Defaults to `False`. **kwargs: Keyword arguments to construct a layer. Input shape: A single string, a list of strings, or an `int32` or `int64` tensor of shape `(batch_size, ...,)`. Output shape: An `int32` tensor of shape `(batch_size, ...)`. Reference: - [SipHash with salt](https://www.131002.net/siphash/siphash.pdf) """ def __init__( self, num_bins, mask_value=None, salt=None, output_mode="int", sparse=False, **kwargs, ): if not tf.available: raise ImportError( "Layer Hashing requires TensorFlow. " "Install it via `pip install tensorflow`." ) # By default, output int32 when output_mode='int' and floats otherwise. if "dtype" not in kwargs or kwargs["dtype"] is None: kwargs["dtype"] = ( "int64" if output_mode == "int" else backend.floatx() ) super().__init__(**kwargs) if num_bins is None or num_bins <= 0: raise ValueError( "The `num_bins` for `Hashing` cannot be `None` or " f"non-positive values. Received: num_bins={num_bins}." ) if output_mode == "int" and ( self.dtype_policy.name not in ("int32", "int64") ): raise ValueError( 'When `output_mode="int"`, `dtype` should be an integer ' f"type, 'int32' or 'in64'. Received: dtype={kwargs['dtype']}" ) # 'output_mode' must be one of (INT, ONE_HOT, MULTI_HOT, COUNT) accepted_output_modes = ("int", "one_hot", "multi_hot", "count") if output_mode not in accepted_output_modes: raise ValueError( "Invalid value for argument `output_mode`. " f"Expected one of {accepted_output_modes}. " f"Received: output_mode={output_mode}" ) if sparse and output_mode == "int": raise ValueError( "`sparse` may only be true if `output_mode` is " '`"one_hot"`, `"multi_hot"`, or `"count"`. ' f"Received: sparse={sparse} and " f"output_mode={output_mode}" ) self.num_bins = num_bins self.mask_value = mask_value self.strong_hash = True if salt is not None else False self.output_mode = output_mode self.sparse = sparse self.salt = None if salt is not None: if isinstance(salt, (tuple, list)) and len(salt) == 2: self.salt = list(salt) elif isinstance(salt, int): self.salt = [salt, salt] else: raise ValueError( "The `salt` argument for `Hashing` can only be a tuple of " "size 2 integers, or a single integer. " f"Received: salt={salt}." ) self._convert_input_args = False self._allow_non_tensor_positional_args = True self.supports_jit = False def call(self, inputs): from keras.src.backend import tensorflow as tf_backend inputs = tf_utils.ensure_tensor(inputs) if self.output_mode == "one_hot" and inputs.shape[-1] == 1: # One hot only upranks if the final dimension is not 1. inputs = tf_backend.numpy.squeeze(inputs, axis=-1) if isinstance(inputs, tf.SparseTensor): indices = tf.SparseTensor( indices=inputs.indices, values=self._hash_values_to_bins(inputs.values), dense_shape=inputs.dense_shape, ) else: indices = self._hash_values_to_bins(inputs) outputs = numerical_utils.encode_categorical_inputs( indices, output_mode=self.output_mode, depth=self.num_bins, sparse=self.sparse, dtype=self.dtype, backend_module=tf_backend, ) return backend_utils.convert_tf_tensor(outputs) def _hash_values_to_bins(self, values): """Converts a non-sparse tensor of values to bin indices.""" hash_bins = self.num_bins mask = None # If mask_value is set, the zeroth bin is reserved for it. if self.mask_value is not None and hash_bins > 1: hash_bins -= 1 mask = tf.equal(values, self.mask_value) # Convert all values to strings before hashing. # Floats are first normalized to int64. if values.dtype.is_floating: values = tf.cast(values, dtype="int64") if values.dtype != tf.string: values = tf.as_string(values) # Hash the strings. if self.strong_hash: values = tf.strings.to_hash_bucket_strong( values, hash_bins, name="hash", key=self.salt ) else: values = tf.strings.to_hash_bucket_fast( values, hash_bins, name="hash" ) if mask is not None: values = tf.add(values, tf.ones_like(values)) values = tf.where(mask, tf.zeros_like(values), values) return values def compute_output_spec(self, inputs): if self.output_mode == "int": return backend.KerasTensor(shape=inputs.shape, dtype=self.dtype) if len(inputs.shape) >= 1: base_shape = tuple(inputs.shape)[:-1] else: base_shape = () return backend.KerasTensor( shape=base_shape + (self.num_bins,), dtype=self.dtype ) def get_config(self): config = super().get_config() config.update( { "num_bins": self.num_bins, "salt": self.salt, "mask_value": self.mask_value, "output_mode": self.output_mode, "sparse": self.sparse, } ) return config
Hashing
python
weaviate__weaviate-python-client
weaviate/collections/queries/hybrid/generate/executor.py
{ "start": 1053, "end": 23519 }
class ____( Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType] ): @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: Literal[None] = None, ) -> executor.Result[GenerativeReturn[Properties, References]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: REFERENCES, ) -> executor.Result[GenerativeReturn[Properties, CrossReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: Type[TReferences], ) -> executor.Result[GenerativeReturn[Properties, TReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: Literal[None] = None, ) -> executor.Result[GenerativeReturn[TProperties, References]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: REFERENCES, ) -> executor.Result[GenerativeReturn[TProperties, CrossReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Literal[None] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: Type[TReferences], ) -> executor.Result[GenerativeReturn[TProperties, TReferences]]: ... ##### GROUP BY ##### @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: Literal[None] = None, ) -> executor.Result[GenerativeGroupByReturn[Properties, References]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: REFERENCES, ) -> executor.Result[GenerativeGroupByReturn[Properties, CrossReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Union[PROPERTIES, bool, None] = None, return_references: Type[TReferences], ) -> executor.Result[GenerativeGroupByReturn[Properties, TReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: Literal[None] = None, ) -> executor.Result[GenerativeGroupByReturn[TProperties, References]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: REFERENCES, ) -> executor.Result[GenerativeGroupByReturn[TProperties, CrossReferences]]: ... @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: GroupBy, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Type[TProperties], return_references: Type[TReferences], ) -> executor.Result[GenerativeGroupByReturn[TProperties, TReferences]]: ... ### DEFAULT ### @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Optional[GroupBy] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Optional[ReturnProperties[TProperties]] = None, return_references: Optional[ReturnReferences[TReferences]] = None, ) -> executor.Result[ GenerativeSearchReturnType[Properties, References, TProperties, TReferences] ]: ... def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, grouped_properties: Optional[List[str]] = None, generative_provider: Optional[_GenerativeConfigRuntime] = None, alpha: NUMBER = 0.7, vector: Optional[HybridVectorType] = None, query_properties: Optional[List[str]] = None, fusion_type: Optional[HybridFusion] = None, max_vector_distance: Optional[NUMBER] = None, limit: Optional[int] = None, offset: Optional[int] = None, bm25_operator: Optional[BM25OperatorOptions] = None, auto_limit: Optional[int] = None, filters: Optional[_Filters] = None, group_by: Optional[GroupBy] = None, rerank: Optional[Rerank] = None, target_vector: Optional[TargetVectorJoinType] = None, include_vector: INCLUDE_VECTOR = False, return_metadata: Optional[METADATA] = None, return_properties: Optional[ReturnProperties[TProperties]] = None, return_references: Optional[ReturnReferences[TReferences]] = None, ) -> executor.Result[ GenerativeSearchReturnType[Properties, References, TProperties, TReferences] ]: """Perform retrieval-augmented generation (RaG) on the results of an object search in this collection using the hybrid algorithm blending keyword-based BM25 and vector-based similarity. See the [docs](https://weaviate.io/developers/weaviate/search/hybrid) for a more detailed explanation. Args: query: The keyword-based query to search for, REQUIRED. If query and vector are both None, a normal search will be performed. single_prompt: The prompt to use for RaG on each object individually. grouped_task: The prompt to use for RaG on the entire result set. grouped_properties: The properties to use in the RaG on the entire result set. alpha: The weight of the BM25 score. If not specified, the default weight specified by the server is used. vector: The specific vector to search for. If not specified, the query is vectorized and used in the similarity search. query_properties: The properties to search in. If not specified, all properties are searched. fusion_type: The type of fusion to apply. If not specified, the default fusion type specified by the server is used. limit: The maximum number of results to return. If not specified, the default limit specified by the server is returned. offset: The offset to start from. If not specified, the retrieval begins from the first object in the server. auto_limit: The maximum number of [autocut](https://weaviate.io/developers/weaviate/api/graphql/additional-operators#autocut) results to return. If not specified, no limit is applied. filters: The filters to apply to the search. group_by: How the results should be grouped by a specific property. rerank: How the results should be reranked. NOTE: A `rerank-*` module must be enabled for this functionality to work. target_vector: The name of the vector space to search in for named vector configurations. Required if multiple spaces are configured. include_vector: Whether to include the vector in the results. If not specified, this is set to False. return_metadata: The metadata to return for each object, defaults to `None`. return_properties: The properties to return for each object. return_references: The references to return for each object. NOTE: - If `return_properties` is not provided then all properties are returned except for blob properties. - If `return_metadata` is not provided then no metadata is provided. Use MetadataQuery.full() to retrieve all metadata. - If `return_references` is not provided then no references are provided. Returns: A `GenerativeReturn` or `GenerativeGroupByReturn` object that includes the searched objects. If `group_by` is provided then a `GenerativeGroupByReturn` object is returned, otherwise a `GenerativeReturn` object is returned. Raises: weaviate.exceptions.WeaviateQueryError: If the network connection to Weaviate fails. weaviate.exceptions.WeaviateNotImplementedError: If a group by is provided and the Weaviate server version is lower than 1.25.0. """ def resp( res: search_get_pb2.SearchReply, ) -> GenerativeSearchReturnType[Properties, References, TProperties, TReferences]: return cast( Any, self._result_to_generative_return( res, _QueryOptions.from_input( return_metadata, return_properties, include_vector, self._references, return_references, rerank, group_by, ), ), ) request = self._query.hybrid( query=query, alpha=alpha, vector=vector, properties=query_properties, fusion_type=fusion_type, limit=limit, offset=offset, bm25_operator=bm25_operator, distance=max_vector_distance, autocut=auto_limit, filters=filters, group_by=_GroupBy.from_input(group_by), rerank=rerank, target_vector=target_vector, return_metadata=self._parse_return_metadata(return_metadata, include_vector), return_properties=self._parse_return_properties(return_properties), return_references=self._parse_return_references(return_references), generative=_Generative( single=single_prompt, grouped=grouped_task, grouped_properties=grouped_properties, generative_provider=generative_provider, ), ) return executor.execute( response_callback=resp, method=self._connection.grpc_search, request=request, )
_HybridGenerateExecutor
python
kamyu104__LeetCode-Solutions
Python/amount-of-new-area-painted-each-day.py
{ "start": 86, "end": 1068 }
class ____(object): def amountPainted(self, paint): """ :type paint: List[List[int]] :rtype: List[int] """ points = collections.defaultdict(list) for i, (s, e) in enumerate(paint): points[s].append((True, i)) points[e].append((False, i)) min_heap = [] lookup = [False]*len(paint) result = [0]*len(paint) prev = -1 for pos in sorted(points.iterkeys()): while min_heap and lookup[min_heap[0]]: heapq.heappop(min_heap) if min_heap: result[min_heap[0]] += pos-prev prev = pos for t, i in points[pos]: if t: heapq.heappush(min_heap, i) else: lookup[i] = True return result # Time: O(nlogn) # Space: O(n) from sortedcontainers import SortedList # line sweep, sorted list
Solution
python
pytorch__pytorch
test/package/test_trace_dep/__init__.py
{ "start": 28, "end": 117 }
class ____(torch.nn.Module): def forward(self, inp): return torch.sum(inp)
SumMod
python
tensorflow__tensorflow
tensorflow/python/data/ops/structured_function.py
{ "start": 2551, "end": 12798 }
class ____(): """A function wrapper that supports structured arguments and return values.""" def __init__(self, func, transformation_name, dataset=None, input_classes=None, input_shapes=None, input_types=None, input_structure=None, add_to_graph=True, use_legacy_function=False, defun_kwargs=None): """Creates a new `StructuredFunctionWrapper` for the given function. Args: func: A function from a (nested) structure to another (nested) structure. transformation_name: Human-readable name of the transformation in which this function is being instantiated, for error messages. dataset: (Optional.) A `tf.data.Dataset`. If given, the structure of this dataset will be assumed as the structure for `func` arguments; otherwise `input_classes`, `input_shapes`, and `input_types` must be defined. input_classes: (Optional.) A (nested) structure of `type`. If given, this argument defines the Python types for `func` arguments. input_shapes: (Optional.) A (nested) structure of `tf.TensorShape`. If given, this argument defines the shapes and structure for `func` arguments. input_types: (Optional.) A (nested) structure of `tf.DType`. If given, this argument defines the element types and structure for `func` arguments. input_structure: (Optional.) A `Structure` object. If given, this argument defines the element types and structure for `func` arguments. add_to_graph: (Optional.) If `True`, the function will be added to the default graph, if it exists. use_legacy_function: (Optional.) A boolean that determines whether the function be created using `tensorflow.python.eager.function.defun` (default behavior) or `tensorflow.python.framework.function.Defun` (legacy behavior). defun_kwargs: (Optional.) A dictionary mapping string argument names to values. If supplied, will be passed to `function` as keyword arguments. Raises: ValueError: If an invalid combination of `dataset`, `input_classes`, `input_shapes`, and `input_types` is passed. """ # pylint: disable=protected-access if input_structure is None: if dataset is None: if input_classes is None or input_shapes is None or input_types is None: raise ValueError("Either `dataset`, `input_structure` or all of " "`input_classes`, `input_shapes`, and `input_types` " "must be specified.") self._input_structure = structure.convert_legacy_structure( input_types, input_shapes, input_classes) else: if not (input_classes is None and input_shapes is None and input_types is None): raise ValueError("Either `dataset`, `input_structure` or all of " "`input_classes`, `input_shapes`, and `input_types` " "must be specified.") self._input_structure = dataset.element_spec else: if not (dataset is None and input_classes is None and input_shapes is None and input_types is None): raise ValueError("Either `dataset`, `input_structure`, or all of " "`input_classes`, `input_shapes`, and `input_types` " "must be specified.") self._input_structure = input_structure self._func = func if defun_kwargs is None: defun_kwargs = {} readable_transformation_name = transformation_name.replace( ".", "_")[:-2] if len(transformation_name) > 2 else "" func_name = "_".join( [readable_transformation_name, function_utils.get_func_name(func)]) # Sanitize function name to remove symbols that interfere with graph # construction. for symbol in ["<", ">", "\\", "'", " "]: func_name = func_name.replace(symbol, "") ag_ctx = autograph_ctx.control_status_ctx() def wrapper_helper(*args): """Wrapper for passing nested structures to and from tf.data functions.""" nested_args = structure.from_compatible_tensor_list( self._input_structure, args) if not _should_unpack(nested_args): nested_args = (nested_args,) ret = autograph.tf_convert(self._func, ag_ctx)(*nested_args) ret = variable_utils.convert_variables_to_tensors(ret) if _should_pack(ret): ret = tuple(ret) try: self._output_structure = structure.type_spec_from_value(ret) except (ValueError, TypeError) as e: raise TypeError(f"Unsupported return value from function passed to " f"{transformation_name}: {ret}.") from e return ret def trace_legacy_function(defun_kwargs): @function.Defun(*structure.get_flat_tensor_types(self._input_structure), **defun_kwargs) def wrapped_fn(*args): ret = wrapper_helper(*args) return structure.to_tensor_list(self._output_structure, ret) return lambda: wrapped_fn def trace_py_function(defun_kwargs): # First we trace the function to infer the output structure. def unused(*args): # pylint: disable=missing-docstring,unused-variable ret = wrapper_helper(*args) ret = structure.to_tensor_list(self._output_structure, ret) return [ops.convert_to_tensor(t) for t in ret] func_name = defun_kwargs.pop("func_name", "unused") tf_function = def_function.Function( python_function=unused, name=func_name, input_signature=structure.get_flat_tensor_specs( self._input_structure ), autograph=False, experimental_attributes=defun_kwargs, ) _ = tf_function.get_concrete_function() def py_function_wrapper(*args): nested_args = structure.from_compatible_tensor_list( self._input_structure, args) if not _should_unpack(nested_args): nested_args = (nested_args,) ret = self._func(*nested_args) if _should_pack(ret): ret = tuple(ret) ret = structure.to_tensor_list(self._output_structure, ret) return [ops.convert_to_tensor(t) for t in ret] # Next we trace the function wrapped in `eager_py_func` to force eager # execution. @def_function.function( input_signature=structure.get_flat_tensor_specs( self._input_structure), autograph=False, experimental_attributes=defun_kwargs) def wrapped_fn(*args): # pylint: disable=missing-docstring return script_ops.eager_py_func( py_function_wrapper, args, structure.get_flat_tensor_types(self._output_structure)) return wrapped_fn.get_concrete_function def trace_tf_function(defun_kwargs): # Note: wrapper_helper will apply autograph based on context. def wrapped_fn(*args): # pylint: disable=missing-docstring ret = wrapper_helper(*args) ret = structure.to_tensor_list(self._output_structure, ret) return [ops.convert_to_tensor(t) for t in ret] func_name = defun_kwargs.pop("func_name", "wrapped_fn") tf_function = def_function.Function( python_function=wrapped_fn, name=func_name, input_signature=structure.get_flat_tensor_specs( self._input_structure ), autograph=False, experimental_attributes=defun_kwargs, ) return tf_function.get_concrete_function if use_legacy_function: defun_kwargs.update({"func_name": func_name + "_" + str(ops.uid())}) fn_factory = trace_legacy_function(defun_kwargs) else: defun_kwargs.update({"func_name": func_name}) defun_kwargs.update({"_tf_data_function": True}) if debug_mode.DEBUG_MODE: fn_factory = trace_py_function(defun_kwargs) else: if def_function.functions_run_eagerly(): warnings.warn( "Even though the `tf.config.experimental_run_functions_eagerly` " "option is set, this option does not apply to tf.data functions. " "To force eager execution of tf.data functions, please use " "`tf.data.experimental.enable_debug_mode()`.") fn_factory = trace_tf_function(defun_kwargs) self._function = fn_factory() # There is no graph to add in eager mode. add_to_graph &= not context.executing_eagerly() # There are some lifetime issues when a legacy function is not added to a # out-living graph. It's already deprecated so de-prioritizing the fix. add_to_graph |= use_legacy_function if add_to_graph: self._function.add_to_graph(ops.get_default_graph()) if not use_legacy_function: outer_graph_seed = ops.get_default_graph().seed if outer_graph_seed and self._function.graph.seed == outer_graph_seed: if self._function.graph._seed_used: warnings.warn( "Seed %s from outer graph might be getting used by function %s, " "if the random op has not been provided any seed. Explicitly set " "the seed in the function if this is not the intended behavior." % (outer_graph_seed, func_name), stacklevel=4) @property def output_structure(self): return self._output_structure @property def output_classes(self): return nest.map_structure( lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access self._output_structure) @property def output_shapes(self): return nest.map_structure( lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access self._output_structure) @property def output_types(self): return nest.map_structure( lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access self._output_structure) @property def function(self): return self._function
StructuredFunctionWrapper
python
kamyu104__LeetCode-Solutions
Python/equal-tree-partition.py
{ "start": 50, "end": 675 }
class ____(object): def checkEqualTree(self, root): """ :type root: TreeNode :rtype: bool """ def getSumHelper(node, lookup): if not node: return 0 total = node.val + \ getSumHelper(node.left, lookup) + \ getSumHelper(node.right, lookup) lookup[total] += 1 return total lookup = collections.defaultdict(int) total = getSumHelper(root, lookup) if total == 0: return lookup[total] > 1 return total%2 == 0 and (total/2) in lookup
Solution
python
dask__dask
dask/typing.py
{ "start": 14628, "end": 15168 }
class ____(DaskCollection, Protocol): """Protocol defining a Dask collection that uses HighLevelGraphs. This protocol is nearly identical to :py:class:`~dask.typing.DaskCollection`, with the addition of the ``__dask_layers__`` method (required for collections backed by high level graphs). """ @abc.abstractmethod def __dask_layers__(self) -> Sequence[str]: """Names of the HighLevelGraph layers.""" raise NotImplementedError("Inheriting class must implement this method.")
HLGDaskCollection
python
bokeh__bokeh
src/bokeh/core/property/dataspec.py
{ "start": 13345, "end": 13945 }
class ____(DataSpec): """ A |DataSpec| property that accepts hatch pattern types as fixed values. The ``HatchPatternSpec`` property attempts to first interpret string values as hatch pattern types. Otherwise, string values are interpreted as field names. For example: .. code-block:: python m.font_size = "." # value m.font_size = "ring" # value m.font_size = "foo" # field """ def __init__(self, default, *, help: str | None = None) -> None: super().__init__(Nullable(HatchPatternType), default=default, help=help)
HatchPatternSpec
python
pytorch__pytorch
torch/_functorch/_aot_autograd/schemas.py
{ "start": 4506, "end": 4675 }
class ____(Enum): NOT_MUTATED = 1 MUTATED_IN_GRAPH = 2 MUTATED_OUT_GRAPH = 3 # This class tells us info about user inputs. @dataclass(frozen=True)
MutationType
python
ray-project__ray
python/ray/_common/tests/test_signature.py
{ "start": 11724, "end": 14128 }
class ____: """Tests for the recover_args utility function.""" def test_only_positional_args(self): """Test recovering only positional arguments.""" flattened = [DUMMY_TYPE, 1, DUMMY_TYPE, 2, DUMMY_TYPE, 3] args, kwargs = recover_args(flattened) assert args == [1, 2, 3] assert kwargs == {} def test_only_keyword_args(self): """Test recovering only keyword arguments.""" flattened = ["a", 10, "b", 20, "c", 30] args, kwargs = recover_args(flattened) assert args == [] assert kwargs == {"a": 10, "b": 20, "c": 30} def test_mixed_args(self): """Test recovering mixed positional and keyword arguments.""" flattened = [DUMMY_TYPE, 1, DUMMY_TYPE, 2, "c", 3] args, kwargs = recover_args(flattened) assert args == [1, 2] assert kwargs == {"c": 3} def test_empty_flattened(self): """Test recovering from empty flattened list.""" flattened = [] args, kwargs = recover_args(flattened) assert args == [] assert kwargs == {} def test_complex_types(self): """Test recovering complex argument types.""" flattened = [ DUMMY_TYPE, [1, 2, 3], DUMMY_TYPE, {"key": "value"}, "c", {"nested": "dict"}, ] args, kwargs = recover_args(flattened) assert args == [[1, 2, 3], {"key": "value"}] assert kwargs == {"c": {"nested": "dict"}} def test_invalid_odd_length(self): """Test error handling for odd-length flattened list.""" flattened = [DUMMY_TYPE, 1, "key"] # Odd length with pytest.raises( AssertionError, match="Flattened arguments need to be even-numbered" ): recover_args(flattened) def test_preserve_order(self): """Test that argument order is preserved during flatten/recover.""" def test_func(a, b, c, d, e): return a + b + c + d + e params = extract_signature(test_func) original_args = (1, 2, 3) original_kwargs = {"d": 4, "e": 5} flattened = flatten_args(params, original_args, original_kwargs) recovered_args, recovered_kwargs = recover_args(flattened) assert recovered_args == [1, 2, 3] assert recovered_kwargs == {"d": 4, "e": 5}
TestRecoverArgs
python
getsentry__sentry
src/sentry/api/endpoints/api_application_rotate_secret.py
{ "start": 584, "end": 1090 }
class ____(ApiApplicationEndpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ENTERPRISE authentication_classes = (SessionAuthentication,) permission_classes = (SentryIsAuthenticated,) def post(self, request: Request, application: ApiApplication) -> Response: new_token = generate_token() application.update(client_secret=new_token) return Response(serialize({"clientSecret": new_token}))
ApiApplicationRotateSecretEndpoint
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 19735, "end": 21085 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook") def test_assert_valid_hook_call(self, mock_hook) -> None: with pytest.warns(AirflowProviderDeprecationWarning): task = CloudDataCatalogDeleteTagOperator( task_id="task_id", location=TEST_LOCATION, entry_group=TEST_ENTRY_GROUP_ID, entry=TEST_ENTRY_ID, tag=TEST_TAG_ID, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) task.execute(context=mock.MagicMock()) mock_hook.assert_called_once_with( gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_tag.assert_called_once_with( location=TEST_LOCATION, entry_group=TEST_ENTRY_GROUP_ID, entry=TEST_ENTRY_ID, tag=TEST_TAG_ID, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, )
TestCloudDataCatalogDeleteTagOperator
python
pytorch__pytorch
test/inductor/test_cooperative_reductions.py
{ "start": 8804, "end": 8958 }
class ____(CooperativeReductionTests): pass @config.patch("triton.multi_kernel", int(not config.triton.multi_kernel))
NoPersistCooperativeReductionTests
python
pennersr__django-allauth
allauth/socialaccount/providers/facebook/views.py
{ "start": 1728, "end": 3231 }
class ____(View): @method_decorator(login_not_required) def dispatch(self, request): self.adapter = get_adapter() self.provider = self.adapter.get_provider(request, PROVIDER_ID) try: return super().dispatch(request) except ( requests.RequestException, forms.ValidationError, PermissionDenied, ) as exc: return render_authentication_error(request, self.provider, exception=exc) def get(self, request): # If we leave out get().get() it will return a response with a 405, but # we really want to show an authentication error. raise PermissionDenied("405") def post(self, request): form = FacebookConnectForm(request.POST) if not form.is_valid(): raise self.adapter.validation_error("invalid_token") access_token = form.cleaned_data["access_token"] provider = self.provider login_options = provider.get_fb_login_options(request) auth_type = login_options.get("auth_type") auth_nonce = "" if auth_type == "reauthenticate": auth_nonce = provider.get_nonce(request, pop=True) login = flows.verify_token( request, provider, access_token, auth_type, auth_nonce ) login.state = SocialLogin.state_from_request(request) ret = complete_social_login(request, login) return ret login_by_token = LoginByTokenView.as_view()
LoginByTokenView
python
nedbat__coveragepy
coverage/templite.py
{ "start": 760, "end": 2305 }
class ____: """Build source code conveniently.""" def __init__(self, indent: int = 0) -> None: self.code: list[str | CodeBuilder] = [] self.indent_level = indent def __str__(self) -> str: return "".join(str(c) for c in self.code) def add_line(self, line: str) -> None: """Add a line of source to the code. Indentation and newline will be added for you, don't provide them. """ self.code.extend([" " * self.indent_level, line, "\n"]) def add_section(self) -> CodeBuilder: """Add a section, a sub-CodeBuilder.""" section = CodeBuilder(self.indent_level) self.code.append(section) return section INDENT_STEP = 4 # PEP8 says so! def indent(self) -> None: """Increase the current indent for following lines.""" self.indent_level += self.INDENT_STEP def dedent(self) -> None: """Decrease the current indent for following lines.""" self.indent_level -= self.INDENT_STEP def get_globals(self) -> dict[str, Any]: """Execute the code, and return a dict of globals it defines.""" # A check that the caller really finished all the blocks they started. assert self.indent_level == 0 # Get the Python source as a single string. python_source = str(self) # Execute the source, defining globals, and return them. global_namespace: dict[str, Any] = {} exec(python_source, global_namespace) return global_namespace
CodeBuilder
python
google__flatbuffers
tests/py_test.py
{ "start": 68981, "end": 81183 }
class ____(unittest.TestCase): def setUp(self, *args, **kwargs): super(TestAllCodePathsOfExampleSchema, self).setUp(*args, **kwargs) b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) gen_mon = _MONSTER.MonsterEnd(b) b.Finish(gen_mon) self.mon = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) def test_default_monster_pos(self): self.assertTrue(self.mon.Pos() is None) def test_nondefault_monster_mana(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) _MONSTER.MonsterAddMana(b, 50) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) got_mon = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(50, got_mon.Mana()) def test_default_monster_hp(self): self.assertEqual(100, self.mon.Hp()) def test_default_monster_name(self): self.assertEqual(None, self.mon.Name()) def test_default_monster_inventory_item(self): self.assertEqual(0, self.mon.Inventory(0)) def test_default_monster_inventory_length(self): self.assertEqual(0, self.mon.InventoryLength()) self.assertTrue(self.mon.InventoryIsNone()) def test_empty_monster_inventory_vector(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartInventoryVector(b, 0) inv = b.EndVector() _MONSTER.MonsterStart(b) _MONSTER.MonsterAddInventory(b, inv) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertFalse(mon2.InventoryIsNone()) def test_default_monster_color(self): self.assertEqual(_COLOR.Color.Blue, self.mon.Color()) def test_nondefault_monster_color(self): b = flatbuffers.Builder(0) color = _COLOR.Color.Red _MONSTER.MonsterStart(b) _MONSTER.MonsterAddColor(b, color) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(_COLOR.Color.Red, mon2.Color()) def test_default_monster_testtype(self): self.assertEqual(0, self.mon.TestType()) def test_default_monster_test_field(self): self.assertEqual(None, self.mon.Test()) def test_default_monster_test4_item(self): self.assertEqual(None, self.mon.Test4(0)) def test_default_monster_test4_length(self): self.assertEqual(0, self.mon.Test4Length()) self.assertTrue(self.mon.Test4IsNone()) def test_empty_monster_test4_vector(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartTest4Vector(b, 0) test4 = b.EndVector() _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTest4(b, test4) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertFalse(mon2.Test4IsNone()) def test_default_monster_testarrayofstring(self): self.assertEqual('', self.mon.Testarrayofstring(0)) def test_default_monster_testarrayofstring_length(self): self.assertEqual(0, self.mon.TestarrayofstringLength()) self.assertTrue(self.mon.TestarrayofstringIsNone()) def test_empty_monster_testarrayofstring_vector(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartTestarrayofstringVector(b, 0) testarrayofstring = b.EndVector() _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestarrayofstring(b, testarrayofstring) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertFalse(mon2.TestarrayofstringIsNone()) def test_default_monster_testarrayoftables(self): self.assertEqual(None, self.mon.Testarrayoftables(0)) def test_nondefault_monster_testarrayoftables(self): b = flatbuffers.Builder(0) # make a child Monster within a vector of Monsters: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddHp(b, 99) sub_monster = _MONSTER.MonsterEnd(b) # build the vector: _MONSTER.MonsterStartTestarrayoftablesVector(b, 1) b.PrependUOffsetTRelative(sub_monster) vec = b.EndVector() # make the parent monster and include the vector of Monster: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestarrayoftables(b, vec) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Output(), 0) self.assertEqual(99, mon2.Testarrayoftables(0).Hp()) self.assertEqual(1, mon2.TestarrayoftablesLength()) self.assertFalse(mon2.TestarrayoftablesIsNone()) def test_default_monster_testarrayoftables_length(self): self.assertEqual(0, self.mon.TestarrayoftablesLength()) self.assertTrue(self.mon.TestarrayoftablesIsNone()) def test_empty_monster_testarrayoftables_vector(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartTestarrayoftablesVector(b, 0) testarrayoftables = b.EndVector() _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestarrayoftables(b, testarrayoftables) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertFalse(mon2.TestarrayoftablesIsNone()) def test_default_monster_testarrayoftables_length(self): self.assertEqual(0, self.mon.TestarrayoftablesLength()) def test_nondefault_monster_enemy(self): b = flatbuffers.Builder(0) # make an Enemy object: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddHp(b, 88) enemy = _MONSTER.MonsterEnd(b) b.Finish(enemy) # make the parent monster and include the vector of Monster: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddEnemy(b, enemy) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(88, mon2.Enemy().Hp()) def test_default_monster_testnestedflatbuffer(self): self.assertEqual(0, self.mon.Testnestedflatbuffer(0)) def test_default_monster_testnestedflatbuffer_length(self): self.assertEqual(0, self.mon.TestnestedflatbufferLength()) self.assertTrue(self.mon.TestnestedflatbufferIsNone()) def test_empty_monster_testnestedflatbuffer_vector(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartTestnestedflatbufferVector(b, 0) testnestedflatbuffer = b.EndVector() _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestnestedflatbuffer(b, testnestedflatbuffer) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertFalse(mon2.TestnestedflatbufferIsNone()) def test_nondefault_monster_testnestedflatbuffer(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStartTestnestedflatbufferVector(b, 3) b.PrependByte(4) b.PrependByte(2) b.PrependByte(0) sub_buf = b.EndVector() # make the parent monster and include the vector of Monster: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestnestedflatbuffer(b, sub_buf) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(3, mon2.TestnestedflatbufferLength()) self.assertFalse(mon2.TestnestedflatbufferIsNone()) self.assertEqual(0, mon2.Testnestedflatbuffer(0)) self.assertEqual(2, mon2.Testnestedflatbuffer(1)) self.assertEqual(4, mon2.Testnestedflatbuffer(2)) try: # if numpy exists, then we should be able to get the # vector as a numpy array import numpy as np self.assertEqual([0, 2, 4], mon2.TestnestedflatbufferAsNumpy().tolist()) except ImportError: assertRaises( self, lambda: mon2.TestnestedflatbufferAsNumpy(), NumpyRequiredForThisFeature, ) def test_nested_monster_testnestedflatbuffer(self): b = flatbuffers.Builder(0) # build another monster to nest inside testnestedflatbuffer nestedB = flatbuffers.Builder(0) nameStr = nestedB.CreateString('Nested Monster') _MONSTER.MonsterStart(nestedB) _MONSTER.MonsterAddHp(nestedB, 30) _MONSTER.MonsterAddName(nestedB, nameStr) nestedMon = _MONSTER.MonsterEnd(nestedB) nestedB.Finish(nestedMon) # write the nested FB bytes sub_buf = _MONSTER.MonsterMakeTestnestedflatbufferVectorFromBytes( b, nestedB.Output() ) # make the parent monster and include the bytes of the nested monster _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestnestedflatbuffer(b, sub_buf) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) nestedMon2 = mon2.TestnestedflatbufferNestedRoot() self.assertEqual(b'Nested Monster', nestedMon2.Name()) self.assertEqual(30, nestedMon2.Hp()) def test_nondefault_monster_testempty(self): b = flatbuffers.Builder(0) # make a Stat object: _STAT.StatStart(b) _STAT.StatAddVal(b, 123) my_stat = _STAT.StatEnd(b) b.Finish(my_stat) # include the stat object in a monster: _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestempty(b, my_stat) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(123, mon2.Testempty().Val()) def test_default_monster_testbool(self): self.assertFalse(self.mon.Testbool()) def test_nondefault_monster_testbool(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTestbool(b, True) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertTrue(mon2.Testbool()) def test_default_monster_testhashes(self): self.assertEqual(0, self.mon.Testhashs32Fnv1()) self.assertEqual(0, self.mon.Testhashu32Fnv1()) self.assertEqual(0, self.mon.Testhashs64Fnv1()) self.assertEqual(0, self.mon.Testhashu64Fnv1()) self.assertEqual(0, self.mon.Testhashs32Fnv1a()) self.assertEqual(0, self.mon.Testhashu32Fnv1a()) self.assertEqual(0, self.mon.Testhashs64Fnv1a()) self.assertEqual(0, self.mon.Testhashu64Fnv1a()) def test_nondefault_monster_testhashes(self): b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) _MONSTER.MonsterAddTesthashs32Fnv1(b, 1) _MONSTER.MonsterAddTesthashu32Fnv1(b, 2) _MONSTER.MonsterAddTesthashs64Fnv1(b, 3) _MONSTER.MonsterAddTesthashu64Fnv1(b, 4) _MONSTER.MonsterAddTesthashs32Fnv1a(b, 5) _MONSTER.MonsterAddTesthashu32Fnv1a(b, 6) _MONSTER.MonsterAddTesthashs64Fnv1a(b, 7) _MONSTER.MonsterAddTesthashu64Fnv1a(b, 8) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # inspect the resulting data: mon2 = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertEqual(1, mon2.Testhashs32Fnv1()) self.assertEqual(2, mon2.Testhashu32Fnv1()) self.assertEqual(3, mon2.Testhashs64Fnv1()) self.assertEqual(4, mon2.Testhashu64Fnv1()) self.assertEqual(5, mon2.Testhashs32Fnv1a()) self.assertEqual(6, mon2.Testhashu32Fnv1a()) self.assertEqual(7, mon2.Testhashs64Fnv1a()) self.assertEqual(8, mon2.Testhashu64Fnv1a()) def test_default_monster_parent_namespace_test(self): self.assertEqual(None, self.mon.ParentNamespaceTest()) def test_nondefault_monster_parent_namespace_test(self): b = flatbuffers.Builder(0) _IN_PARENT_NAMESPACE.InParentNamespaceStart(b) parent = _IN_PARENT_NAMESPACE.InParentNamespaceEnd(b) _MONSTER.MonsterStart(b) _MONSTER.MonsterAddParentNamespaceTest(b, parent) mon = _MONSTER.MonsterEnd(b) b.Finish(mon) # Inspect the resulting data. monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) self.assertTrue( isinstance( monster.ParentNamespaceTest(), _IN_PARENT_NAMESPACE.InParentNamespace, ) ) def test_getrootas_for_nonroot_table(self): b = flatbuffers.Builder(0) string = b.CreateString('MyStat') _STAT.StatStart(b) _STAT.StatAddId(b, string) _STAT.StatAddVal(b, 12345678) _STAT.StatAddCount(b, 12345) stat = _STAT.StatEnd(b) b.Finish(stat) stat2 = _STAT.Stat.GetRootAs(b.Bytes, b.Head()) self.assertEqual(b'MyStat', stat2.Id()) self.assertEqual(12345678, stat2.Val()) self.assertEqual(12345, stat2.Count())
TestAllCodePathsOfExampleSchema
python
cython__cython
Cython/Shadow.py
{ "start": 12273, "end": 12496 }
class ____(typedef): def __init__(self, type, name=None): name = f"const {name or repr(type)}" super().__init__(type, name) def __class_getitem__(cls, base_type): return const(base_type)
const
python
run-llama__llama_index
llama-index-finetuning/llama_index/finetuning/mistralai/base.py
{ "start": 785, "end": 5506 }
class ____(BaseLLMFinetuneEngine): """MistralAI Finetuning Engine.""" def __init__( self, base_model: str, training_path: str, validation_path: Optional[str] = None, verbose: bool = False, start_job_id: Optional[str] = None, validate_json: bool = True, training_steps: int = 10, learning_rate: float = 0.0001, wandb_integration_dict: Optional[Dict[str, str]] = None, ) -> None: """Init params.""" self.base_model = base_model self.training_path = training_path self.validation_path = validation_path self._verbose = verbose self._validate_json = validate_json self.training_steps = training_steps self.learning_rate = learning_rate self.wandb_integration_dict = wandb_integration_dict self._client = Mistral(api_key=os.getenv("MISTRAL_API_KEY", None)) self._start_job: Optional[Any] = None if start_job_id is not None: self._start_job = self._client.fine_tuning.jobs.get(start_job_id) @classmethod def from_finetuning_handler( cls, finetuning_handler: MistralAIFineTuningHandler, base_model: str, training_path: str, **kwargs: Any, ) -> "MistralAIFinetuneEngine": """ Initialize from finetuning handler. Used to finetune an MistralAI model. """ finetuning_handler.save_finetuning_events(training_path) return cls(base_model=base_model, data_path=training_path, **kwargs) def finetune(self) -> None: """Finetune model.""" if self._validate_json: if self.training_path: reformat_jsonl(self.training_path) if self.validation_path: reformat_jsonl(self.validation_path) # upload file with open(self.training_path, "rb") as f: train_file = self._client.files.upload(file=f) if self.validation_path: with open(self.validation_path, "rb") as f: eval_file = self._client.files.upload(file=f) logger.info("File uploaded...") if self._verbose: print("File uploaded...") # launch training while True: try: job_output = self._client.fine_tuning.jobs.create( training_files=[train_file.id], validation_files=[eval_file.id] if self.validation_path else None, model=self.base_model, hyperparameters=CompletionTrainingParametersIn( training_steps=self.training_steps, learning_rate=self.learning_rate, ), integrations=( [ WandbIntegration( project=self.wandb_integration_dict["project"], run_name=self.wandb_integration_dict["run_name"], api_key=self.wandb_integration_dict["api_key"], ).model_dump() ] if self.wandb_integration_dict else None ), ) self._start_job = job_output break except Exception: print("Waiting for file to be ready...") time.sleep(60) info_str = f"Training job {job_output.id} launched. " logger.info(info_str) if self._verbose: print(info_str) def get_current_job( self, ) -> Optional[JobsAPIRoutesFineTuningGetFineTuningJobResponse]: """Get current job.""" # validate that it works if not self._start_job: raise ValueError("Must call finetune() first") # try getting id, make sure that run succeeded job_id = self._start_job.id return self._client.fine_tuning.jobs.get(job_id) def get_finetuned_model(self, **model_kwargs: Any) -> LLM: """Gets finetuned model.""" current_job = self.get_current_job() job_id = current_job.id status = current_job.status model_id = current_job.fine_tuned_model logger.info(f"status of the job_id: {job_id} is {status}") if model_id is None: raise ValueError( f"Job {job_id} does not have a finetuned model id ready yet." ) if status != "SUCCESS": raise ValueError(f"Job {job_id} has status {status}, cannot get model") return MistralAI(model=model_id, **model_kwargs)
MistralAIFinetuneEngine
python
django__django
tests/decorators/test_cache.py
{ "start": 298, "end": 525 }
class ____: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr)
HttpRequestProxy
python
google__pytype
pytype/tools/xref/indexer.py
{ "start": 5710, "end": 7192 }
class ____: """A symbol definition. Attributes: name: The symbol name typ: The definition type (e.g. ClassDef) data: Pytype data from the opcode traces scope: The namespace id (e.g. module:class A:function f:x) target: The LHS of an attribute (e.g. for x.foo, target = typeof(x)) doc: The docstring, if any, for function and class defs id: The id """ name: str typ: Any data: Any scope: str target: Any doc: str | None id: str | None = dataclasses.field(default=None, init=False) def __post_init__(self): self.id = self.scope + "." + self.name def format(self): return self.id def to_signature(self): return self.id def doc_signature(self): """Signature for the definition's docstring.""" return self.to_signature() + ".__doc__" def node_kind(self): # TODO(mdemello): Add more node types. if self.typ == "ClassDef": return "class" elif self.typ == "FunctionDef": return "function" else: return "variable" def subkind(self) -> str | None: if self.typ == "Import" or self.typ == "ImportFrom": return "import" return None @property def typename(self): """The fully qualified type of the object the definition is bound to.""" if self.data and self.data[0]: d = self.data[0][0] if d.cls: return d.cls.full_name else: return "typing.Any" else: return "typing.Any" @dataclasses.dataclass
Definition
python
aimacode__aima-python
notebook4e.py
{ "start": 30778, "end": 44488 }
class ____(Canvas): """fol_bc_ask() on HTML canvas""" def __init__(self, varname, kb, query, width=800, height=600, cid=None): super().__init__(varname, width, height, cid) self.kb = kb self.query = query self.l = 1 / 20 self.b = 3 * self.l bc_out = list(self.fol_bc_ask()) if len(bc_out) == 0: self.valid = False else: self.valid = True graph = bc_out[0][0][0] s = bc_out[0][1] while True: new_graph = subst(s, graph) if graph == new_graph: break graph = new_graph self.make_table(graph) self.context = None self.draw_table() def fol_bc_ask(self): KB = self.kb query = self.query def fol_bc_or(KB, goal, theta): for rule in KB.fetch_rules_for_goal(goal): lhs, rhs = parse_definite_clause(standardize_variables(rule)) for theta1 in fol_bc_and(KB, lhs, unify_mm(rhs, goal, theta)): yield ([(goal, theta1[0])], theta1[1]) def fol_bc_and(KB, goals, theta): if theta is None: pass elif not goals: yield ([], theta) else: first, rest = goals[0], goals[1:] for theta1 in fol_bc_or(KB, subst(theta, first), theta): for theta2 in fol_bc_and(KB, rest, theta1[1]): yield (theta1[0] + theta2[0], theta2[1]) return fol_bc_or(KB, query, {}) def make_table(self, graph): table = [] pos = {} links = set() edges = set() def dfs(node, depth): if len(table) <= depth: table.append([]) pos = len(table[depth]) table[depth].append(node[0]) for child in node[1]: child_id = dfs(child, depth + 1) links.add(((depth, pos), child_id)) return (depth, pos) dfs(graph, 0) y_off = 0.85 / len(table) for i, row in enumerate(table): x_off = 0.95 / len(row) for j, node in enumerate(row): pos[(i, j)] = (0.025 + j * x_off + (x_off - self.b) / 2, 0.025 + i * y_off + (y_off - self.l) / 2) for p, c in links: x1, y1 = pos[p] x2, y2 = pos[c] edges.add((x1 + self.b / 2, y1 + self.l, x2 + self.b / 2, y2)) self.table = table self.pos = pos self.edges = edges def mouse_click(self, x, y): x, y = x / self.width, y / self.height for node in self.pos: xs, ys = self.pos[node] xe, ye = xs + self.b, ys + self.l if xs <= x <= xe and ys <= y <= ye: self.context = node break self.draw_table() def draw_table(self): self.clear() self.strokeWidth(3) self.stroke(0, 0, 0) self.font("12px Arial") if self.valid: # draw nodes for i, j in self.pos: x, y = self.pos[(i, j)] self.fill(200, 200, 200) self.rect_n(x, y, self.b, self.l) self.line_n(x, y, x + self.b, y) self.line_n(x, y, x, y + self.l) self.line_n(x + self.b, y, x + self.b, y + self.l) self.line_n(x, y + self.l, x + self.b, y + self.l) self.fill(0, 0, 0) self.text_n(self.table[i][j], x + 0.01, y + self.l - 0.01) # draw edges for x1, y1, x2, y2 in self.edges: self.line_n(x1, y1, x2, y2) else: self.fill(255, 0, 0) self.rect_n(0, 0, 1, 1) # text area self.fill(255, 255, 255) self.rect_n(0, 0.9, 1, 0.1) self.strokeWidth(5) self.stroke(0, 0, 0) self.line_n(0, 0.9, 1, 0.9) self.font("22px Arial") self.fill(0, 0, 0) self.text_n(self.table[self.context[0]][self.context[1]] if self.context else "Click for text", 0.025, 0.975) self.update() ############################################################################################################ ##################### Functions to assist plotting in search.ipynb #################### ############################################################################################################ def show_map(graph_data, node_colors=None): G = nx.Graph(graph_data['graph_dict']) node_colors = node_colors or graph_data['node_colors'] node_positions = graph_data['node_positions'] node_label_pos = graph_data['node_label_positions'] edge_weights = graph_data['edge_weights'] # set the size of the plot plt.figure(figsize=(18, 13)) # draw the graph (both nodes and edges) with locations from romania_locations nx.draw(G, pos={k: node_positions[k] for k in G.nodes()}, node_color=[node_colors[node] for node in G.nodes()], linewidths=0.3, edgecolors='k') # draw labels for nodes node_label_handles = nx.draw_networkx_labels(G, pos=node_label_pos, font_size=14) # add a white bounding box behind the node labels [label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in node_label_handles.values()] # add edge lables to the graph nx.draw_networkx_edge_labels(G, pos=node_positions, edge_labels=edge_weights, font_size=14) # add a legend white_circle = lines.Line2D([], [], color="white", marker='o', markersize=15, markerfacecolor="white") orange_circle = lines.Line2D([], [], color="orange", marker='o', markersize=15, markerfacecolor="orange") red_circle = lines.Line2D([], [], color="red", marker='o', markersize=15, markerfacecolor="red") gray_circle = lines.Line2D([], [], color="gray", marker='o', markersize=15, markerfacecolor="gray") green_circle = lines.Line2D([], [], color="green", marker='o', markersize=15, markerfacecolor="green") plt.legend((white_circle, orange_circle, red_circle, gray_circle, green_circle), ('Un-explored', 'Frontier', 'Currently Exploring', 'Explored', 'Final Solution'), numpoints=1, prop={'size': 16}, loc=(.8, .75)) # show the plot. No need to use in notebooks. nx.draw will show the graph itself. plt.show() # helper functions for visualisations def final_path_colors(initial_node_colors, problem, solution): """Return a node_colors dict of the final path provided the problem and solution.""" # get initial node colors final_colors = dict(initial_node_colors) # color all the nodes in solution and starting node to green final_colors[problem.initial] = "green" for node in solution: final_colors[node] = "green" return final_colors def display_visual(graph_data, user_input, algorithm=None, problem=None): initial_node_colors = graph_data['node_colors'] if user_input is False: def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: show_map(graph_data, node_colors=all_node_colors[iteration]) except: pass def visualize_callback(visualize): if visualize is True: button.value = False global all_node_colors iterations, all_node_colors, node = algorithm(problem) solution = node.solution() all_node_colors.append(final_path_colors(all_node_colors[0], problem, solution)) slider.max = len(all_node_colors) - 1 for i in range(slider.max + 1): slider.value = i # time.sleep(.5) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) slider_visual = widgets.interactive(slider_callback, iteration=slider) display(slider_visual) button = widgets.ToggleButton(value=False) button_visual = widgets.interactive(visualize_callback, visualize=button) display(button_visual) if user_input is True: node_colors = dict(initial_node_colors) if isinstance(algorithm, dict): assert set(algorithm.keys()).issubset({"Breadth First Tree Search", "Depth First Tree Search", "Breadth First Search", "Depth First Graph Search", "Best First Graph Search", "Uniform Cost Search", "Depth Limited Search", "Iterative Deepening Search", "Greedy Best First Search", "A-star Search", "Recursive Best First Search"}) algo_dropdown = widgets.Dropdown(description="Search algorithm: ", options=sorted(list(algorithm.keys())), value="Breadth First Tree Search") display(algo_dropdown) elif algorithm is None: print("No algorithm to run.") return 0 def slider_callback(iteration): # don't show graph for the first time running the cell calling this function try: show_map(graph_data, node_colors=all_node_colors[iteration]) except: pass def visualize_callback(visualize): if visualize is True: button.value = False problem = GraphProblem(start_dropdown.value, end_dropdown.value, romania_map) global all_node_colors user_algorithm = algorithm[algo_dropdown.value] iterations, all_node_colors, node = user_algorithm(problem) solution = node.solution() all_node_colors.append(final_path_colors(all_node_colors[0], problem, solution)) slider.max = len(all_node_colors) - 1 for i in range(slider.max + 1): slider.value = i # time.sleep(.5) start_dropdown = widgets.Dropdown(description="Start city: ", options=sorted(list(node_colors.keys())), value="Arad") display(start_dropdown) end_dropdown = widgets.Dropdown(description="Goal city: ", options=sorted(list(node_colors.keys())), value="Fagaras") display(end_dropdown) button = widgets.ToggleButton(value=False) button_visual = widgets.interactive(visualize_callback, visualize=button) display(button_visual) slider = widgets.IntSlider(min=0, max=1, step=1, value=0) slider_visual = widgets.interactive(slider_callback, iteration=slider) display(slider_visual) # Function to plot NQueensCSP in csp.py and NQueensProblem in search.py def plot_NQueens(solution): n = len(solution) board = np.array([2 * int((i + j) % 2) for j in range(n) for i in range(n)]).reshape((n, n)) im = Image.open('images/queen_s.png') height = im.size[1] im = np.array(im).astype(np.float) / 255 fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) ax.set_title('{} Queens'.format(n)) plt.imshow(board, cmap='binary', interpolation='nearest') # NQueensCSP gives a solution as a dictionary if isinstance(solution, dict): for (k, v) in solution.items(): newax = fig.add_axes([0.064 + (k * 0.112), 0.062 + ((7 - v) * 0.112), 0.1, 0.1], zorder=1) newax.imshow(im) newax.axis('off') # NQueensProblem gives a solution as a list elif isinstance(solution, list): for (k, v) in enumerate(solution): newax = fig.add_axes([0.064 + (k * 0.112), 0.062 + ((7 - v) * 0.112), 0.1, 0.1], zorder=1) newax.imshow(im) newax.axis('off') fig.tight_layout() plt.show() # Function to plot a heatmap, given a grid def heatmap(grid, cmap='binary', interpolation='nearest'): fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) ax.set_title('Heatmap') plt.imshow(grid, cmap=cmap, interpolation=interpolation) fig.tight_layout() plt.show() # Generates a gaussian kernel def gaussian_kernel(l=5, sig=1.0): ax = np.arange(-l // 2 + 1., l // 2 + 1.) xx, yy = np.meshgrid(ax, ax) kernel = np.exp(-(xx ** 2 + yy ** 2) / (2. * sig ** 2)) return kernel # Plots utility function for a POMDP def plot_pomdp_utility(utility): save = utility['0'][0] delete = utility['1'][0] ask_save = utility['2'][0] ask_delete = utility['2'][-1] left = (save[0] - ask_save[0]) / (save[0] - ask_save[0] + ask_save[1] - save[1]) right = (delete[0] - ask_delete[0]) / (delete[0] - ask_delete[0] + ask_delete[1] - delete[1]) colors = ['g', 'b', 'k'] for action in utility: for value in utility[action]: plt.plot(value, color=colors[int(action)]) plt.vlines([left, right], -20, 10, linestyles='dashed', colors='c') plt.ylim(-20, 13) plt.xlim(0, 1) plt.text(left / 2 - 0.05, 10, 'Save') plt.text((right + left) / 2 - 0.02, 10, 'Ask') plt.text((right + 1) / 2 - 0.07, 10, 'Delete') plt.show()
Canvas_fol_bc_ask
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol40.py
{ "start": 583, "end": 630 }
class ____(P2Parent[T], Protocol[T]): ...
P2Child
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image23.py
{ "start": 315, "end": 1060 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image23.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image("B2", self.image_dir + "black_72.jpg") worksheet.insert_image("B8", self.image_dir + "black_96.jpg") worksheet.insert_image("B13", self.image_dir + "black_150.jpg") worksheet.insert_image("B17", self.image_dir + "black_300.jpg") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/k-inverse-pairs-array.py
{ "start": 2439, "end": 2991 }
class ____(object): def kInversePairs(self, n, k): """ :type n: int :type k: int :rtype: int """ MOD = 10**9+7 dp = [[] for _ in xrange(k+1)] dp[0].append([]) for i in xrange(n): dp = [[[x+int(x >= i-k) for x in p]+[i-k] for k in xrange(min(i+1, j+1)) for p in dp[j-k]] for j in xrange(len(dp))] assert(all(sum(int(p[j] > p[i]) for i in xrange(n) for j in xrange(i)) == len(dp)-1) for p in dp[-1]) return len(dp[-1])%MOD
Solution_ConstructPermutation
python
huggingface__transformers
src/transformers/models/mixtral/modular_mixtral.py
{ "start": 18666, "end": 18943 }
class ____(MistralForQuestionAnswering): pass __all__ = [ "MixtralForCausalLM", "MixtralForQuestionAnswering", "MixtralModel", "MixtralPreTrainedModel", "MixtralForSequenceClassification", "MixtralForTokenClassification", ]
MixtralForQuestionAnswering
python
kubernetes-client__python
kubernetes/e2e_test/port_server.py
{ "start": 76, "end": 1166 }
class ____: def __init__(self, port): self.port = port self.server = socketserver.ThreadingTCPServer(('0.0.0.0', port), self.handler) self.server.daemon_threads = True self.thread = threading.Thread(target=self.server.serve_forever, name='Port %s Server' % port) self.thread.daemon = True self.thread.start() def handler(self, request, address, server): threading.current_thread().name = 'Port %s Handler' % self.port rlist = [request] echo = b'' while True: r, w, _x = select.select(rlist, [request] if echo else [], []) if r: data = request.recv(1024) if not data: break print(f"{self.port}: {data}\n", end='', flush=True) echo += data if w: echo = echo[request.send(echo):] if __name__ == '__main__': ports = [] for port in sys.argv[1:]: ports.append(PortServer(int(port))) time.sleep(10 * 60)
PortServer
python
redis__redis-py
tests/test_asyncio/test_command_parser.py
{ "start": 244, "end": 5576 }
class ____: @pytest.mark.asyncio async def test_get_command_policies(self, r): commands_parser = AsyncCommandsParser() await commands_parser.initialize(node=r.get_default_node()) expected_command_policies = { "core": { "keys": [ "keys", RequestPolicy.ALL_SHARDS, ResponsePolicy.DEFAULT_KEYLESS, ], "acl setuser": [ "acl setuser", RequestPolicy.ALL_NODES, ResponsePolicy.ALL_SUCCEEDED, ], "exists": ["exists", RequestPolicy.MULTI_SHARD, ResponsePolicy.AGG_SUM], "config resetstat": [ "config resetstat", RequestPolicy.ALL_NODES, ResponsePolicy.ALL_SUCCEEDED, ], "slowlog len": [ "slowlog len", RequestPolicy.ALL_NODES, ResponsePolicy.AGG_SUM, ], "scan": ["scan", RequestPolicy.SPECIAL, ResponsePolicy.SPECIAL], "latency history": [ "latency history", RequestPolicy.ALL_NODES, ResponsePolicy.SPECIAL, ], "memory doctor": [ "memory doctor", RequestPolicy.ALL_SHARDS, ResponsePolicy.SPECIAL, ], "randomkey": [ "randomkey", RequestPolicy.ALL_SHARDS, ResponsePolicy.SPECIAL, ], "mget": [ "mget", RequestPolicy.MULTI_SHARD, ResponsePolicy.DEFAULT_KEYED, ], "function restore": [ "function restore", RequestPolicy.ALL_SHARDS, ResponsePolicy.ALL_SUCCEEDED, ], }, "json": { "debug": [ "debug", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "get": [ "get", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, "ft": { "search": [ "search", RequestPolicy.DEFAULT_KEYLESS, ResponsePolicy.DEFAULT_KEYLESS, ], "create": [ "create", RequestPolicy.DEFAULT_KEYLESS, ResponsePolicy.DEFAULT_KEYLESS, ], }, "bf": { "add": [ "add", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "madd": [ "madd", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, "cf": { "add": [ "add", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "mexists": [ "mexists", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, "tdigest": { "add": [ "add", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "min": [ "min", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, "ts": { "create": [ "create", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "info": [ "info", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, "topk": { "list": [ "list", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], "query": [ "query", RequestPolicy.DEFAULT_KEYED, ResponsePolicy.DEFAULT_KEYED, ], }, } actual_policies = await commands_parser.get_command_policies() assert len(actual_policies) > 0 for module_name, commands in expected_command_policies.items(): for command, command_policies in commands.items(): assert command in actual_policies[module_name] assert command_policies == [ command, actual_policies[module_name][command].request_policy, actual_policies[module_name][command].response_policy, ]
TestAsyncCommandParser
python
RaRe-Technologies__gensim
gensim/test/basetmtests.py
{ "start": 312, "end": 1837 }
class ____: def test_print_topic(self): topics = self.model.show_topics(formatted=True) for topic_no, topic in topics: self.assertTrue(isinstance(topic_no, int)) self.assertTrue(isinstance(topic, str)) def test_print_topics(self): topics = self.model.print_topics() for topic_no, topic in topics: self.assertTrue(isinstance(topic_no, int)) self.assertTrue(isinstance(topic, str)) def test_show_topic(self): topic = self.model.show_topic(1) for k, v in topic: self.assertTrue(isinstance(k, str)) self.assertTrue(isinstance(v, (np.floating, float))) def test_show_topics(self): topics = self.model.show_topics(formatted=False) for topic_no, topic in topics: self.assertTrue(isinstance(topic_no, int)) self.assertTrue(isinstance(topic, list)) for k, v in topic: self.assertTrue(isinstance(k, str)) self.assertTrue(isinstance(v, (np.floating, float))) def test_get_topics(self): topics = self.model.get_topics() vocab_size = len(self.model.id2word) for topic in topics: self.assertTrue(isinstance(topic, np.ndarray)) # Note: started moving to np.float32 as default # self.assertEqual(topic.dtype, np.float64) self.assertEqual(vocab_size, topic.shape[0]) self.assertAlmostEqual(np.sum(topic), 1.0, 5)
TestBaseTopicModel
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 43559, "end": 44423 }
class ____(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `JavascriptLexer`. """ name = 'JavaScript+Django/Jinja' aliases = ['js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja'] def __init__(self, **options): super(JavascriptDjangoLexer, self).__init__(JavascriptLexer, DjangoLexer, **options) def analyse_text(text): return DjangoLexer.analyse_text(text) - 0.05
JavascriptDjangoLexer
python
pytorch__pytorch
test/distributed/test_nvshmem.py
{ "start": 27072, "end": 28295 }
class ____(MultiProcContinuousTest): def _init_device(self) -> None: # TODO: relieve this (seems to hang if without) device_module.set_device(self.device) # Set NVSHMEM as SymmMem backend symm_mem.set_backend("NVSHMEM") @property def device(self) -> torch.device: return torch.device(device_type, self.rank) @skipIfRocm # TODO: FIXIT. Currently, `MultiProcContinuousTest` treats the skip code as a # failure @skip_if_lt_x_gpu(4) def test_dispatch_combine_subgroup(self) -> None: """ Test dispatch-and-combine over concurrent subgroups """ torch.manual_seed(42 + self.rank) self._init_device() symm_mem.enable_symm_mem_for_group(dist.group.WORLD.group_name) # Test on two concurrent subgroups ngroups = 2 subgroup_size = self.world_size // ngroups dm = init_device_mesh( device_type, (ngroups, subgroup_size), mesh_dim_names=("dp", "ep") ) subgroup = dm.get_group("ep") dispatch_then_combine(self.device, align=8, group=subgroup) @instantiate_parametrized_tests @requires_nvshmem() @requires_cuda_p2p_access()
DispatchCombineInSubgroups
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 79654, "end": 87716 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) autoscale: Optional[AutoScale] = Field( None, description=( "If autoscale, the required parameters to automatically scale clusters up" " and down based on load." ), ) aws_attributes: Optional[AwsAttributes] = Field( None, description=( "Attributes related to clusters running on Amazon Web Services. If not" " specified at cluster creation, a set of default values is used." ), ) cluster_log_conf: Optional[ClusterLogConf] = Field( None, description=( "The configuration for delivering Spark logs to a long-term storage" " destination. Only one destination can be specified for one cluster. If" " the conf is given, the logs are delivered to the destination every `5" " mins`. The destination of driver logs is" " `<destination>/<cluster-id>/driver`, while the destination of executor" " logs is `<destination>/<cluster-id>/executor`." ), ) custom_tags: Optional[ClusterTag] = Field( None, description=( "An object containing a set of tags for cluster resources. Databricks tags" " all cluster resources (such as AWS instances and EBS volumes) with these" " tags in addition to default_tags.\n\n**Note**:\n\n* Tags are not" " supported on legacy node types such as compute-optimized and" " memory-optimized\n* Databricks allows at most 45 custom tags" ), ) driver_instance_pool_id: Optional[str] = Field( None, description=( "The optional ID of the instance pool to use for the driver node. You must" " also specify `instance_pool_id`. Refer to [Instance Pools" " API](https://docs.databricks.com/dev-tools/api/latest/instance-pools.html)" " for details." ), ) driver_node_type_id: Optional[str] = Field( None, description=( "The node type of the Spark driver. This field is optional; if unset, the" " driver node type is set as the same value as `node_type_id` defined" " above." ), ) enable_elastic_disk: Optional[bool] = Field( None, description=( "Autoscaling Local Storage: when enabled, this cluster dynamically acquires" " additional disk space when its Spark workers are running low on disk" " space. This feature requires specific AWS permissions to function" " correctly - refer to [Autoscaling local" " storage](https://docs.databricks.com/clusters/configure.html#autoscaling-local-storage)" " for details." ), ) enable_local_disk_encryption: Optional[bool] = Field( None, description=( "Determines whether encryption of disks locally attached to the cluster is" " enabled." ), ) init_scripts: Optional[List[InitScriptInfo]] = Field( None, description=( "The configuration for storing init scripts. Any number of scripts can be" " specified. The scripts are executed sequentially in the order provided." " If `cluster_log_conf` is specified, init script logs are sent to" " `<destination>/<cluster-id>/init_scripts`." ), ) instance_pool_id: Optional[str] = Field( None, description=( "The optional ID of the instance pool to use for cluster nodes. If" " `driver_instance_pool_id` is present, `instance_pool_id` is used for" " worker nodes only. Otherwise, it is used for both the driver node and" " worker nodes. Refer to [Instance Pools" " API](https://docs.databricks.com/dev-tools/api/latest/instance-pools.html)" " for details." ), ) node_type_id: Optional[str] = Field( None, description=( "This field encodes, through a single value, the resources available to" " each of the Spark nodes in this cluster. For example, the Spark nodes can" " be provisioned and optimized for memory or compute intensive workloads A" " list of available node types can be retrieved by using the [List node" " types](https://docs.databricks.com/dev-tools/api/latest/clusters.html#list-node-types)" " API call." ), ) num_workers: Optional[int] = Field( None, description=( "If num_workers, number of worker nodes that this cluster must have. A" " cluster has one Spark driver and num_workers executors for a total of" " num_workers + 1 Spark nodes. When reading the properties of a cluster," " this field reflects the desired number of workers rather than the actual" " current number of workers. For example, if a cluster is resized from 5 to" " 10 workers, this field immediately updates to reflect the target size of" " 10 workers, whereas the workers listed in `spark_info` gradually increase" " from 5 to 10 as the new nodes are provisioned." ), ) policy_id: Optional[str] = Field( None, description=( "A [cluster" " policy](https://docs.databricks.com/dev-tools/api/latest/policies.html)" " ID. Either `node_type_id` or `instance_pool_id` must be specified in the" " cluster policy if they are not specified in this job cluster object." ), ) spark_conf: Optional[SparkConfPair] = Field( None, description=( "An object containing a set of optional, user-specified Spark configuration" " key-value pairs. You can also pass in a string of extra JVM options to" " the driver and the executors via `spark.driver.extraJavaOptions` and" " `spark.executor.extraJavaOptions` respectively.\n\nExample Spark confs:" ' `{"spark.speculation": true, "spark.streaming.ui.retainedBatches": 5}` or' ' `{"spark.driver.extraJavaOptions": "-verbose:gc -XX:+PrintGCDetails"}`' ), ) spark_env_vars: Optional[SparkEnvPair] = Field( None, description=( "An object containing a set of optional, user-specified environment" " variable key-value pairs. Key-value pair of the form (X,Y) are exported" " as is (for example, `export X='Y'`) while launching the driver and" " workers.\n\nTo specify an additional set of `SPARK_DAEMON_JAVA_OPTS`, we" " recommend appending them to `$SPARK_DAEMON_JAVA_OPTS` as shown in the" " following example. This ensures that all default databricks managed" " environmental variables are included as well.\n\nExample Spark" ' environment variables: `{"SPARK_WORKER_MEMORY": "28000m",' ' "SPARK_LOCAL_DIRS": "/local_disk0"}` or `{"SPARK_DAEMON_JAVA_OPTS":' ' "$SPARK_DAEMON_JAVA_OPTS -Dspark.shuffle.service.enabled=true"}`' ), ) spark_version: str = Field( ..., description=( "The Spark version of the cluster. A list of available Spark versions can" " be retrieved by using the [Runtime" " versions](https://docs.databricks.com/dev-tools/api/latest/clusters.html#runtime-versions)" " API call." ), ) ssh_public_keys: Optional[List[str]] = Field( None, description=( "SSH public key contents that are added to each Spark node in this cluster." " The corresponding private keys can be used to login with the user name" " `ubuntu` on port `2200`. Up to 10 keys can be specified." ), )
NewCluster
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 32312, "end": 33696 }
class ____(AssetSelection): left: AssetSelection right: AssetSelection def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: return self.left.resolve_inner( asset_graph, allow_missing=allow_missing ) - self.right.resolve_inner(asset_graph, allow_missing=allow_missing) def resolve_checks_inner( # pyright: ignore[reportIncompatibleMethodOverride] self, asset_graph: AssetGraph, allow_missing: bool ) -> AbstractSet[AssetCheckKey]: return self.left.resolve_checks_inner( asset_graph, allow_missing=allow_missing ) - self.right.resolve_checks_inner(asset_graph, allow_missing=allow_missing) def to_serializable_asset_selection(self, asset_graph: BaseAssetGraph) -> "AssetSelection": return copy( self, left=self.left.to_serializable_asset_selection(asset_graph), right=self.right.to_serializable_asset_selection(asset_graph), ) def needs_parentheses_when_operand(self) -> bool: return True def to_selection_str(self) -> str: if isinstance(self.left, AllSelection): return f"not {self.right.to_selection_str()}" return f"{self.left.operand_to_selection_str()} and not {self.right.operand_to_selection_str()}" @record
SubtractAssetSelection
python
pytorch__pytorch
torch/profiler/_pattern_matcher.py
{ "start": 17685, "end": 19294 }
class ____(Pattern): """ This pattern identifies if we are enabling bias in Conv2d which is followed by BatchNorm2d. Bias doesn't do anything when followed by batchnorm. Pattern: nn.Module: Conv2d | nn.Module: BatchNorm2d ... aten::conv2d AND dtype of third argument is not null The third argument is the bias Algorithm: String match """ def __init__(self, prof: profile, should_benchmark: bool = False) -> None: super().__init__(prof, should_benchmark) self.name = "Enabling Bias in Conv2d Followed By BatchNorm Pattern" self.description = "Detected bias enabled in Conv2d that is followed by BatchNorm2d. Please set 'bias=False' in Conv2d." self.url = ( "https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html" "#disable-bias-for-convolutions-directly-followed-by-a-batch-norm" ) @property def skip(self): return self.prof.record_shapes is False or super().skip def match(self, event: _ProfilerEvent): if event.name != "aten::conv2d": return False if len(input_dtypes(event)) < 3 or input_dtypes(event)[2] is None: return False # This means bias=True event = self.go_up_until( event, lambda e: e.name.startswith("nn.Module: Conv2d") ) if not event: return False event = self.next_of(event) if not event: return False return event.name.startswith("nn.Module: BatchNorm2d")
Conv2dBiasFollowedByBatchNorm2dPattern
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/base.py
{ "start": 71332, "end": 72036 }
class ____(compiler.IdentifierPreparer): reserved_words = {x.lower() for x in RESERVED_WORDS} illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union( ["_", "$"] ) def _bindparam_requires_quotes(self, value): """Return True if the given identifier requires quoting.""" lc_value = value.lower() return ( lc_value in self.reserved_words or value[0] in self.illegal_initial_characters or not self.legal_characters.match(str(value)) ) def format_savepoint(self, savepoint): name = savepoint.ident.lstrip("_") return super().format_savepoint(savepoint, name)
OracleIdentifierPreparer
python
getsentry__sentry
src/sentry/models/groupopenperiod.py
{ "start": 1033, "end": 1419 }
class ____(models.Func): function = "TSTZRANGE" output_field = DateTimeRangeField() def should_create_open_periods(type_id: int) -> bool: grouptypes_without_open_periods = options.get( "workflow_engine.group.type_id.open_periods_type_denylist" ) if type_id in grouptypes_without_open_periods: return False return True @region_silo_model
TsTzRange
python
numba__llvmlite
llvmlite/tests/customize.py
{ "start": 11689, "end": 13268 }
class ____(runner.TextTestRunner): """ A test runner which delegates the actual running to a pool of child processes. """ resultclass = ParallelTestResult def __init__(self, runner_cls, **kwargs): runner.TextTestRunner.__init__(self, **kwargs) self.runner_cls = runner_cls self.runner_args = kwargs def _run_inner(self, result): # We hijack TextTestRunner.run()'s inner logic by passing this # method as if it were a test case. child_runner = _MinimalRunner(self.runner_cls, self.runner_args) pool = multiprocessing.Pool() imap = pool.imap_unordered try: for child_result in imap(child_runner, self._test_list): result.add_results(child_result) if child_result.shouldStop: break return result finally: # Kill the still active workers pool.terminate() pool.join() def run(self, test): self._test_list = _flatten_suite(test) # This will call self._run_inner() on the created result object, # and print out the detailed test results at the end. return super(ParallelTestRunner, self).run(self._run_inner) try: import faulthandler except ImportError: pass else: try: # May fail in IPython Notebook with UnsupportedOperation faulthandler.enable() except BaseException as e: msg = "Failed to enable faulthandler due to:\n{err}" warnings.warn(msg.format(err=e))
ParallelTestRunner
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 21942, "end": 22487 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.predictions = MobileBertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output: torch.Tensor, pooled_output: torch.Tensor) -> tuple[torch.Tensor]: prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score @auto_docstring
MobileBertPreTrainingHeads
python
pypa__pip
src/pip/_vendor/rich/progress.py
{ "start": 8721, "end": 17245 }
class ____(ContextManager[_I], Generic[_I]): """A utility class to handle a context for both a reader and a progress.""" def __init__(self, progress: "Progress", reader: _I) -> None: self.progress = progress self.reader: _I = reader def __enter__(self) -> _I: self.progress.start() return self.reader.__enter__() def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.progress.stop() self.reader.__exit__(exc_type, exc_val, exc_tb) def wrap_file( file: BinaryIO, total: int, *, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[BinaryIO]: """Read bytes from a file while tracking progress. Args: file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode. total (int): Total number of bytes to read. description (str, optional): Description of task show next to progress bar. Defaults to "Reading". auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". disable (bool, optional): Disable display of progress. Returns: ContextManager[BinaryIO]: A context manager yielding a progress reader. """ columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), DownloadColumn(), TimeRemainingColumn(), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) reader = progress.wrap_file(file, total=total, description=description) return _ReadContext(progress, reader) @typing.overload def open( file: Union[str, "PathLike[str]", bytes], mode: Union[Literal["rt"], Literal["r"]], buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[TextIO]: pass @typing.overload def open( file: Union[str, "PathLike[str]", bytes], mode: Literal["rb"], buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> ContextManager[BinaryIO]: pass def open( file: Union[str, "PathLike[str]", bytes], mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r", buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, *, total: Optional[int] = None, description: str = "Reading...", auto_refresh: bool = True, console: Optional[Console] = None, transient: bool = False, get_time: Optional[Callable[[], float]] = None, refresh_per_second: float = 10, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", disable: bool = False, ) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]: """Read bytes from a file while tracking progress. Args: path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode. mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt". buffering (int): The buffering strategy to use, see :func:`io.open`. encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`. errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`. newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open` total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size. description (str, optional): Description of task show next to progress bar. Defaults to "Reading". auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True. transient: (bool, optional): Clear the progress on exit. Defaults to False. console (Console, optional): Console to write to. Default creates internal Console instance. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". disable (bool, optional): Disable display of progress. encoding (str, optional): The encoding to use when reading in text mode. Returns: ContextManager[BinaryIO]: A context manager yielding a progress reader. """ columns: List["ProgressColumn"] = ( [TextColumn("[progress.description]{task.description}")] if description else [] ) columns.extend( ( BarColumn( style=style, complete_style=complete_style, finished_style=finished_style, pulse_style=pulse_style, ), DownloadColumn(), TimeRemainingColumn(), ) ) progress = Progress( *columns, auto_refresh=auto_refresh, console=console, transient=transient, get_time=get_time, refresh_per_second=refresh_per_second or 10, disable=disable, ) reader = progress.open( file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, total=total, description=description, ) return _ReadContext(progress, reader) # type: ignore[return-value, type-var]
_ReadContext
python
kamyu104__LeetCode-Solutions
Python/check-if-string-is-transformable-with-substring-sort-operations.py
{ "start": 29, "end": 646 }
class ____(object): def isTransformable(self, s, t): """ :type s: str :type t: str :rtype: bool """ idxs = [[] for _ in xrange(10)] for i in reversed(xrange(len(s))): idxs[int(s[i])].append(i) for c in t: d = int(c) if not idxs[d]: return False for k in xrange(d): # a char can be moved left to the current position if it meets no smaller one if idxs[k] and idxs[k][-1] < idxs[d][-1]: return False idxs[d].pop() return True
Solution
python
walkccc__LeetCode
solutions/1578. Minimum Time to Make Rope Colorful/1578.py
{ "start": 0, "end": 737 }
class ____: def minCost(self, colors: str, neededTime: list[int]) -> int: ans = 0 maxNeededTime = neededTime[0] for i in range(1, len(colors)): if colors[i] == colors[i - 1]: ans += min(maxNeededTime, neededTime[i]) # For each continuous group, Bob needs to remove every balloon except # the one with the maximum `neededTime`. So, he should hold the balloon # with the highest `neededTime` in his hand. maxNeededTime = max(maxNeededTime, neededTime[i]) else: # If the current balloon is different from the previous one, discard # the balloon from the previous group and hold the new one in hand. maxNeededTime = neededTime[i] return ans
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/cli/argparsing/parsers.py
{ "start": 864, "end": 972 }
class ____(Exception): """Base class for argument completion results.""" @dataclasses.dataclass
Completion
python
huggingface__transformers
src/transformers/models/janus/modular_janus.py
{ "start": 23839, "end": 24722 }
class ____(ChameleonVQVAEVectorQuantizer): def __init__(self, config: JanusVQVAEConfig): super().__init__(config) self.quant_state_dims = [config.num_patches] * 2 def get_codebook_entry(self, image_tokens: torch.LongTensor) -> torch.FloatTensor: batch_size = image_tokens.shape[0] emb_dim: int = self.embedding.weight.shape[-1] # get quantized latent vectors hidden_state_quant = self.embedding(image_tokens) # l2 normalization on the last dimension hidden_state_quant = F.normalize(hidden_state_quant, p=2, dim=-1) # reshape back to match original input shape hidden_state_quant = hidden_state_quant.view((batch_size, *self.quant_state_dims, emb_dim)) hidden_state_quant = hidden_state_quant.permute(0, 3, 1, 2).contiguous() return hidden_state_quant
JanusVQVAEVectorQuantizer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1586517, "end": 1586797 }
class ____(sgqlc.types.Union): """Represents either a pull request the viewer can access or a restricted contribution. """ __schema__ = github_schema __types__ = (CreatedPullRequestContribution, RestrictedContribution)
CreatedPullRequestOrRestrictedContribution
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_index_tricks.py
{ "start": 17271, "end": 19572 }
class ____(TestCase): def test_basic(self): a = np.zeros((3, 3), dtype=int) fill_diagonal(a, 5) assert_array_equal(a, np.array([[5, 0, 0], [0, 5, 0], [0, 0, 5]])) def test_tall_matrix(self): a = np.zeros((10, 3), dtype=int) fill_diagonal(a, 5) assert_array_equal( a, np.array( [ [5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], ] ), ) def test_tall_matrix_wrap(self): a = np.zeros((10, 3), dtype=int) fill_diagonal(a, 5, True) assert_array_equal( a, np.array( [ [5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0], [5, 0, 0], [0, 5, 0], ] ), ) def test_wide_matrix(self): a = np.zeros((3, 10), dtype=int) fill_diagonal(a, 5) assert_array_equal( a, np.array( [ [5, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 5, 0, 0, 0, 0, 0, 0, 0], ] ), ) def test_operate_4d_array(self): a = np.zeros((3, 3, 3, 3), dtype=int) fill_diagonal(a, 4) i = np.array([0, 1, 2]) assert_equal(np.where(a != 0), (i, i, i, i)) def test_low_dim_handling(self): # raise error with low dimensionality a = np.zeros(3, dtype=int) with assert_raises(ValueError): fill_diagonal(a, 5) def test_hetero_shape_handling(self): # raise error with high dimensionality and # shape mismatch a = np.zeros((3, 3, 7, 3), dtype=int) with assert_raises(ValueError): fill_diagonal(a, 2)
TestFillDiagonal
python
tensorflow__tensorflow
tensorflow/python/debug/lib/source_remote_test.py
{ "start": 1591, "end": 8243 }
class ____(test_util.TensorFlowTestCase): @classmethod def setUpClass(cls): test_util.TensorFlowTestCase.setUpClass() (cls._server_port, cls._debug_server_url, cls._server_dump_dir, cls._server_thread, cls._server) = grpc_debug_test_server.start_server_on_separate_thread( poll_server=True) cls._server_address = "localhost:%d" % cls._server_port (cls._server_port_2, cls._debug_server_url_2, cls._server_dump_dir_2, cls._server_thread_2, cls._server_2) = grpc_debug_test_server.start_server_on_separate_thread() cls._server_address_2 = "localhost:%d" % cls._server_port_2 cls._curr_file_path = os.path.normpath(os.path.abspath(__file__)) @classmethod def tearDownClass(cls): # Stop the test server and join the thread. cls._server.stop_server().wait() cls._server_thread.join() cls._server_2.stop_server().wait() cls._server_thread_2.join() test_util.TensorFlowTestCase.tearDownClass() def tearDown(self): ops.reset_default_graph() self._server.clear_data() self._server_2.clear_data() super(SendTracebacksTest, self).tearDown() def _findFirstTraceInsideTensorFlowPyLibrary(self, op): """Find the first trace of an op that belongs to the TF Python library.""" for trace in op.traceback: if source_utils.guess_is_tensorflow_py_library(trace.filename): return trace def testSendGraphTracebacksToSingleDebugServer(self): this_func_name = "testSendGraphTracebacksToSingleDebugServer" with session.Session() as sess: a = variables.Variable(21.0, name="a") a_lineno = line_number_above() b = variables.Variable(2.0, name="b") b_lineno = line_number_above() math_ops.add(a, b, name="x") x_lineno = line_number_above() send_stack = traceback.extract_stack() send_lineno = line_number_above() source_remote.send_graph_tracebacks( self._server_address, "dummy_run_key", send_stack, sess.graph) tb = self._server.query_op_traceback("a") self.assertIn((self._curr_file_path, a_lineno, this_func_name), tb) tb = self._server.query_op_traceback("b") self.assertIn((self._curr_file_path, b_lineno, this_func_name), tb) tb = self._server.query_op_traceback("x") self.assertIn((self._curr_file_path, x_lineno, this_func_name), tb) self.assertIn( (self._curr_file_path, send_lineno, this_func_name), self._server.query_origin_stack()[-1]) self.assertEqual( " a = variables.Variable(21.0, name=\"a\")", self._server.query_source_file_line(__file__, a_lineno)) # Files in the TensorFlow code base shouldn not have been sent. tf_trace = self._findFirstTraceInsideTensorFlowPyLibrary(a.op) tf_trace_file_path = tf_trace.filename with self.assertRaises(ValueError): self._server.query_source_file_line(tf_trace_file_path, 0) self.assertEqual([debug_service_pb2.CallTraceback.GRAPH_EXECUTION], self._server.query_call_types()) self.assertEqual(["dummy_run_key"], self._server.query_call_keys()) self.assertEqual( [sess.graph.version], self._server.query_graph_versions()) def testSendGraphTracebacksToTwoDebugServers(self): this_func_name = "testSendGraphTracebacksToTwoDebugServers" with session.Session() as sess: a = variables.Variable(21.0, name="two/a") a_lineno = line_number_above() b = variables.Variable(2.0, name="two/b") b_lineno = line_number_above() x = math_ops.add(a, b, name="two/x") x_lineno = line_number_above() send_traceback = traceback.extract_stack() send_lineno = line_number_above() with test.mock.patch.object( grpc, "insecure_channel", wraps=grpc.insecure_channel) as mock_grpc_channel: source_remote.send_graph_tracebacks( [self._server_address, self._server_address_2], "dummy_run_key", send_traceback, sess.graph) mock_grpc_channel.assert_called_with( test.mock.ANY, options=[("grpc.max_receive_message_length", -1), ("grpc.max_send_message_length", -1)]) servers = [self._server, self._server_2] for server in servers: tb = server.query_op_traceback("two/a") self.assertIn((self._curr_file_path, a_lineno, this_func_name), tb) tb = server.query_op_traceback("two/b") self.assertIn((self._curr_file_path, b_lineno, this_func_name), tb) tb = server.query_op_traceback("two/x") self.assertIn((self._curr_file_path, x_lineno, this_func_name), tb) self.assertIn( (self._curr_file_path, send_lineno, this_func_name), server.query_origin_stack()[-1]) self.assertEqual( " x = math_ops.add(a, b, name=\"two/x\")", server.query_source_file_line(__file__, x_lineno)) tf_trace = self._findFirstTraceInsideTensorFlowPyLibrary(a.op) tf_trace_file_path = tf_trace.filename with self.assertRaises(ValueError): server.query_source_file_line(tf_trace_file_path, 0) self.assertEqual([debug_service_pb2.CallTraceback.GRAPH_EXECUTION], server.query_call_types()) self.assertEqual(["dummy_run_key"], server.query_call_keys()) self.assertEqual([sess.graph.version], server.query_graph_versions()) def testSendEagerTracebacksToSingleDebugServer(self): this_func_name = "testSendEagerTracebacksToSingleDebugServer" send_traceback = traceback.extract_stack() send_lineno = line_number_above() source_remote.send_eager_tracebacks(self._server_address, send_traceback) self.assertEqual([debug_service_pb2.CallTraceback.EAGER_EXECUTION], self._server.query_call_types()) self.assertIn((self._curr_file_path, send_lineno, this_func_name), self._server.query_origin_stack()[-1]) def testGRPCServerMessageSizeLimit(self): """Assert gRPC debug server is started with unlimited message size.""" with test.mock.patch.object( grpc, "server", wraps=grpc.server) as mock_grpc_server: (_, _, _, server_thread, server) = grpc_debug_test_server.start_server_on_separate_thread( poll_server=True) mock_grpc_server.assert_called_with( test.mock.ANY, options=[("grpc.max_receive_message_length", -1), ("grpc.max_send_message_length", -1)]) server.stop_server().wait() server_thread.join() if __name__ == "__main__": googletest.main()
SendTracebacksTest
python
apache__airflow
providers/snowflake/tests/unit/snowflake/operators/test_snowflake_sql.py
{ "start": 1337, "end": 10479 }
class ____: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __eq__(self, other): return isinstance(other, MockRow) and self.__dict__ == other.__dict__ def __hash__(self): return hash(self.__dict__) def __repr__(self): return f"MockRow({self.__dict__})" DATE = "2017-04-20" TASK_ID = "databricks-sql-operator" DEFAULT_CONN_ID = "snowflake_default" @pytest.mark.parametrize( ("sql", "return_last", "split_statement", "hook_results", "hook_descriptions", "expected_results"), [ pytest.param( "select * from dummy", True, True, [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [[("id",), ("value",)]], ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), id="Scalar: Single SQL statement, return_last, split statement", ), pytest.param( "select * from dummy;select * from dummy2", True, True, [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [[("id",), ("value",)]], ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), id="Scalar: Multiple SQL statements, return_last, split statement", ), pytest.param( "select * from dummy", False, False, [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [[("id",), ("value",)]], ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), id="Scalar: Single SQL statements, no return_last (doesn't matter), no split statement", ), pytest.param( "select * from dummy", True, False, [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [[("id",), ("value",)]], ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), id="Scalar: Single SQL statements, return_last (doesn't matter), no split statement", ), pytest.param( ["select * from dummy"], False, False, [[MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]], [[("id",), ("value",)]], [([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")])], id="Non-Scalar: Single SQL statements in list, no return_last, no split statement", ), pytest.param( ["select * from dummy", "select * from dummy2"], False, False, [ [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [MockRow(id2=1, value2="value1"), MockRow(id2=2, value2="value2")], ], [[("id",), ("value",)], [("id2",), ("value2",)]], [ ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), ([MockRow(id2=1, value2="value1"), MockRow(id2=2, value2="value2")]), ], id="Non-Scalar: Multiple SQL statements in list, no return_last (no matter), no split statement", ), pytest.param( ["select * from dummy", "select * from dummy2"], True, False, [ [MockRow(id=1, value="value1"), MockRow(id=2, value="value2")], [MockRow(id2=1, value2="value1"), MockRow(id2=2, value2="value2")], ], [[("id",), ("value",)], [("id2",), ("value2",)]], [ ([MockRow(id=1, value="value1"), MockRow(id=2, value="value2")]), ([MockRow(id2=1, value2="value1"), MockRow(id2=2, value2="value2")]), ], id="Non-Scalar: Multiple SQL statements in list, return_last (no matter), no split statement", ), ], ) def test_exec_success(sql, return_last, split_statement, hook_results, hook_descriptions, expected_results): """ Test the execute function in case where SQL query was successful. """ with patch("airflow.providers.common.sql.operators.sql.BaseSQLOperator.get_db_hook") as get_db_hook_mock: op = SQLExecuteQueryOperator( task_id=TASK_ID, sql=sql, do_xcom_push=True, return_last=return_last, split_statements=split_statement, conn_id="snowflake_default", ) dbapi_hook = MagicMock() get_db_hook_mock.return_value = dbapi_hook dbapi_hook.run.return_value = hook_results dbapi_hook.descriptions = hook_descriptions execute_results = op.execute(None) assert execute_results == expected_results dbapi_hook.run.assert_called_once_with( sql=sql, parameters=None, handler=fetch_all_handler, autocommit=False, return_last=return_last, split_statements=split_statement, ) @mock.patch("airflow.providers.openlineage.utils.utils.should_use_external_connection") def test_execute_openlineage_events(should_use_external_connection): should_use_external_connection.return_value = False DB_NAME = "DATABASE" DB_SCHEMA_NAME = "PUBLIC" ANOTHER_DB_NAME = "ANOTHER_DB" ANOTHER_DB_SCHEMA = "ANOTHER_SCHEMA" class SnowflakeHookForTests(SnowflakeHook): get_conn = MagicMock(name="conn") get_connection = MagicMock() dbapi_hook = SnowflakeHookForTests() class SnowflakeOperatorForTest(SQLExecuteQueryOperator): def get_db_hook(self): return dbapi_hook sql = ( "INSERT INTO Test_table\n" "SELECT t1.*, t2.additional_constant FROM ANOTHER_DB.ANOTHER_SCHEMA.popular_orders_day_of_week t1\n" "JOIN little_table t2 ON t1.order_day_of_week = t2.order_day_of_week;\n" "FORGOT TO COMMENT" ) op = SnowflakeOperatorForTest(task_id="snowflake-operator", sql=sql) rows = [ [ ( ANOTHER_DB_SCHEMA, "POPULAR_ORDERS_DAY_OF_WEEK", "ORDER_DAY_OF_WEEK", 1, "TEXT", ANOTHER_DB_NAME, ), ( ANOTHER_DB_SCHEMA, "POPULAR_ORDERS_DAY_OF_WEEK", "ORDER_PLACED_ON", 2, "TIMESTAMP_NTZ", ANOTHER_DB_NAME, ), (ANOTHER_DB_SCHEMA, "POPULAR_ORDERS_DAY_OF_WEEK", "ORDERS_PLACED", 3, "NUMBER", ANOTHER_DB_NAME), (DB_SCHEMA_NAME, "LITTLE_TABLE", "ORDER_DAY_OF_WEEK", 1, "TEXT", DB_NAME), (DB_SCHEMA_NAME, "LITTLE_TABLE", "ADDITIONAL_CONSTANT", 2, "TEXT", DB_NAME), ], [ (DB_SCHEMA_NAME, "TEST_TABLE", "ORDER_DAY_OF_WEEK", 1, "TEXT", DB_NAME), (DB_SCHEMA_NAME, "TEST_TABLE", "ORDER_PLACED_ON", 2, "TIMESTAMP_NTZ", DB_NAME), (DB_SCHEMA_NAME, "TEST_TABLE", "ORDERS_PLACED", 3, "NUMBER", DB_NAME), (DB_SCHEMA_NAME, "TEST_TABLE", "ADDITIONAL_CONSTANT", 4, "TEXT", DB_NAME), ], ] dbapi_hook.get_connection.return_value = Connection( conn_id="snowflake_default", conn_type="snowflake", schema="PUBLIC", extra={ "account": "test_account", "region": "us-east", "warehouse": "snow-warehouse", "database": DB_NAME, }, ) dbapi_hook.get_conn.return_value.cursor.return_value.fetchall.side_effect = rows lineage = op.get_openlineage_facets_on_start() # Not calling Snowflake assert dbapi_hook.get_conn.return_value.cursor.return_value.execute.mock_calls == [] assert lineage.inputs == [ Dataset( namespace="snowflake://test_account.us-east.aws", name=f"{DB_NAME}.{DB_SCHEMA_NAME}.LITTLE_TABLE", ), Dataset( namespace="snowflake://test_account.us-east.aws", name=f"{ANOTHER_DB_NAME}.{ANOTHER_DB_SCHEMA}.POPULAR_ORDERS_DAY_OF_WEEK", ), ] assert lineage.outputs == [ Dataset( namespace="snowflake://test_account.us-east.aws", name=f"{DB_NAME}.{DB_SCHEMA_NAME}.TEST_TABLE", facets={ "columnLineage": ColumnLineageDatasetFacet( fields={ "additional_constant": Fields( inputFields=[ InputField( namespace="snowflake://test_account.us-east.aws", name="DATABASE.PUBLIC.little_table", field="additional_constant", ) ], transformationDescription="", transformationType="", ) } ), }, ) ] assert lineage.job_facets == {"sql": SQLJobFacet(query=sql)} assert lineage.run_facets["extractionError"].failedTasks == 1
MockRow
python
simonw__datasette
datasette/views/special.py
{ "start": 40025, "end": 41613 }
class ____(SchemaBaseView): """ Displays schema for a specific table. Supports HTML, JSON, and Markdown formats. """ name = "table_schema" async def get(self, request): database_name = request.url_vars["database"] table_name = request.url_vars["table"] format_ = request.url_vars.get("format") or "html" # Check view-table permission await self.ds.ensure_permission( action="view-table", resource=TableResource(database=database_name, table=table_name), actor=request.actor, ) # Get schema for the table db = self.ds.databases[database_name] result = await db.execute( "select sql from sqlite_master where name = ? and sql is not null", [table_name], ) row = result.first() # Return 404 if table doesn't exist if not row or not row["sql"]: return self.format_error_response("Table not found", format_) schema = row["sql"] if format_ == "json": return self.format_json_response( {"database": database_name, "table": table_name, "schema": schema} ) elif format_ == "md": return self.format_markdown_response( f"Schema for {database_name}.{table_name}", schema ) else: schemas = [{"database": database_name, "schema": schema}] return await self.format_html_response( request, schemas, table_name=table_name )
TableSchemaView
python
streamlit__streamlit
lib/streamlit/elements/lib/js_number.py
{ "start": 737, "end": 3532 }
class ____: """Utility class for exposing JavaScript Number constants.""" # The largest int that can be represented with perfect precision # in JavaScript. MAX_SAFE_INTEGER = (1 << 53) - 1 # The smallest int that can be represented with perfect precision # in JavaScript. MIN_SAFE_INTEGER = -((1 << 53) - 1) # The largest float that can be represented in JavaScript. MAX_VALUE = 1.7976931348623157e308 # The closest number to zero that can be represented in JavaScript. MIN_VALUE = 5e-324 # The largest negative float that can be represented in JavaScript. MIN_NEGATIVE_VALUE = -MAX_VALUE @classmethod def validate_int_bounds(cls, value: int, value_name: str | None = None) -> None: """Validate that an int value can be represented with perfect precision by a JavaScript Number. Parameters ---------- value : int value_name : str or None The name of the value parameter. If specified, this will be used in any exception that is thrown. Raises ------ JSNumberBoundsException Raised with a human-readable explanation if the value falls outside JavaScript int bounds. """ if value_name is None: value_name = "value" if value < cls.MIN_SAFE_INTEGER: raise JSNumberBoundsException( f"{value_name} ({value}) must be >= -((1 << 53) - 1)" ) if value > cls.MAX_SAFE_INTEGER: raise JSNumberBoundsException( f"{value_name} ({value}) must be <= (1 << 53) - 1" ) @classmethod def validate_float_bounds(cls, value: int | float, value_name: str | None) -> None: """Validate that a float value can be represented by a JavaScript Number. Parameters ---------- value : float value_name : str or None The name of the value parameter. If specified, this will be used in any exception that is thrown. Raises ------ JSNumberBoundsException Raised with a human-readable explanation if the value falls outside JavaScript float bounds. """ if value_name is None: value_name = "value" if not isinstance(value, (numbers.Integral, float)): raise JSNumberBoundsException(f"{value_name} ({value}) is not a float") if value < cls.MIN_NEGATIVE_VALUE: raise JSNumberBoundsException( f"{value_name} ({value}) must be >= -1.797e+308" ) if value > cls.MAX_VALUE: raise JSNumberBoundsException( f"{value_name} ({value}) must be <= 1.797e+308" )
JSNumber
python
pennersr__django-allauth
allauth/headless/apps.py
{ "start": 91, "end": 261 }
class ____(AppConfig): name = "allauth.headless" verbose_name = _("Headless") def ready(self): from allauth.headless import checks # noqa
HeadlessConfig
python
python-openxml__python-docx
src/docx/enum/style.py
{ "start": 81, "end": 9427 }
class ____(BaseEnum): """Alias: **WD_STYLE** Specifies a built-in Microsoft Word style. Example:: from docx import Document from docx.enum.style import WD_STYLE document = Document() styles = document.styles style = styles[WD_STYLE.BODY_TEXT] MS API name: `WdBuiltinStyle` http://msdn.microsoft.com/en-us/library/office/ff835210.aspx """ BLOCK_QUOTATION = (-85, "Block Text.") """Block Text.""" BODY_TEXT = (-67, "Body Text.") """Body Text.""" BODY_TEXT_2 = (-81, "Body Text 2.") """Body Text 2.""" BODY_TEXT_3 = (-82, "Body Text 3.") """Body Text 3.""" BODY_TEXT_FIRST_INDENT = (-78, "Body Text First Indent.") """Body Text First Indent.""" BODY_TEXT_FIRST_INDENT_2 = (-79, "Body Text First Indent 2.") """Body Text First Indent 2.""" BODY_TEXT_INDENT = (-68, "Body Text Indent.") """Body Text Indent.""" BODY_TEXT_INDENT_2 = (-83, "Body Text Indent 2.") """Body Text Indent 2.""" BODY_TEXT_INDENT_3 = (-84, "Body Text Indent 3.") """Body Text Indent 3.""" BOOK_TITLE = (-265, "Book Title.") """Book Title.""" CAPTION = (-35, "Caption.") """Caption.""" CLOSING = (-64, "Closing.") """Closing.""" COMMENT_REFERENCE = (-40, "Comment Reference.") """Comment Reference.""" COMMENT_TEXT = (-31, "Comment Text.") """Comment Text.""" DATE = (-77, "Date.") """Date.""" DEFAULT_PARAGRAPH_FONT = (-66, "Default Paragraph Font.") """Default Paragraph Font.""" EMPHASIS = (-89, "Emphasis.") """Emphasis.""" ENDNOTE_REFERENCE = (-43, "Endnote Reference.") """Endnote Reference.""" ENDNOTE_TEXT = (-44, "Endnote Text.") """Endnote Text.""" ENVELOPE_ADDRESS = (-37, "Envelope Address.") """Envelope Address.""" ENVELOPE_RETURN = (-38, "Envelope Return.") """Envelope Return.""" FOOTER = (-33, "Footer.") """Footer.""" FOOTNOTE_REFERENCE = (-39, "Footnote Reference.") """Footnote Reference.""" FOOTNOTE_TEXT = (-30, "Footnote Text.") """Footnote Text.""" HEADER = (-32, "Header.") """Header.""" HEADING_1 = (-2, "Heading 1.") """Heading 1.""" HEADING_2 = (-3, "Heading 2.") """Heading 2.""" HEADING_3 = (-4, "Heading 3.") """Heading 3.""" HEADING_4 = (-5, "Heading 4.") """Heading 4.""" HEADING_5 = (-6, "Heading 5.") """Heading 5.""" HEADING_6 = (-7, "Heading 6.") """Heading 6.""" HEADING_7 = (-8, "Heading 7.") """Heading 7.""" HEADING_8 = (-9, "Heading 8.") """Heading 8.""" HEADING_9 = (-10, "Heading 9.") """Heading 9.""" HTML_ACRONYM = (-96, "HTML Acronym.") """HTML Acronym.""" HTML_ADDRESS = (-97, "HTML Address.") """HTML Address.""" HTML_CITE = (-98, "HTML Cite.") """HTML Cite.""" HTML_CODE = (-99, "HTML Code.") """HTML Code.""" HTML_DFN = (-100, "HTML Definition.") """HTML Definition.""" HTML_KBD = (-101, "HTML Keyboard.") """HTML Keyboard.""" HTML_NORMAL = (-95, "Normal (Web).") """Normal (Web).""" HTML_PRE = (-102, "HTML Preformatted.") """HTML Preformatted.""" HTML_SAMP = (-103, "HTML Sample.") """HTML Sample.""" HTML_TT = (-104, "HTML Typewriter.") """HTML Typewriter.""" HTML_VAR = (-105, "HTML Variable.") """HTML Variable.""" HYPERLINK = (-86, "Hyperlink.") """Hyperlink.""" HYPERLINK_FOLLOWED = (-87, "Followed Hyperlink.") """Followed Hyperlink.""" INDEX_1 = (-11, "Index 1.") """Index 1.""" INDEX_2 = (-12, "Index 2.") """Index 2.""" INDEX_3 = (-13, "Index 3.") """Index 3.""" INDEX_4 = (-14, "Index 4.") """Index 4.""" INDEX_5 = (-15, "Index 5.") """Index 5.""" INDEX_6 = (-16, "Index 6.") """Index 6.""" INDEX_7 = (-17, "Index 7.") """Index 7.""" INDEX_8 = (-18, "Index 8.") """Index 8.""" INDEX_9 = (-19, "Index 9.") """Index 9.""" INDEX_HEADING = (-34, "Index Heading") """Index Heading""" INTENSE_EMPHASIS = (-262, "Intense Emphasis.") """Intense Emphasis.""" INTENSE_QUOTE = (-182, "Intense Quote.") """Intense Quote.""" INTENSE_REFERENCE = (-264, "Intense Reference.") """Intense Reference.""" LINE_NUMBER = (-41, "Line Number.") """Line Number.""" LIST = (-48, "List.") """List.""" LIST_2 = (-51, "List 2.") """List 2.""" LIST_3 = (-52, "List 3.") """List 3.""" LIST_4 = (-53, "List 4.") """List 4.""" LIST_5 = (-54, "List 5.") """List 5.""" LIST_BULLET = (-49, "List Bullet.") """List Bullet.""" LIST_BULLET_2 = (-55, "List Bullet 2.") """List Bullet 2.""" LIST_BULLET_3 = (-56, "List Bullet 3.") """List Bullet 3.""" LIST_BULLET_4 = (-57, "List Bullet 4.") """List Bullet 4.""" LIST_BULLET_5 = (-58, "List Bullet 5.") """List Bullet 5.""" LIST_CONTINUE = (-69, "List Continue.") """List Continue.""" LIST_CONTINUE_2 = (-70, "List Continue 2.") """List Continue 2.""" LIST_CONTINUE_3 = (-71, "List Continue 3.") """List Continue 3.""" LIST_CONTINUE_4 = (-72, "List Continue 4.") """List Continue 4.""" LIST_CONTINUE_5 = (-73, "List Continue 5.") """List Continue 5.""" LIST_NUMBER = (-50, "List Number.") """List Number.""" LIST_NUMBER_2 = (-59, "List Number 2.") """List Number 2.""" LIST_NUMBER_3 = (-60, "List Number 3.") """List Number 3.""" LIST_NUMBER_4 = (-61, "List Number 4.") """List Number 4.""" LIST_NUMBER_5 = (-62, "List Number 5.") """List Number 5.""" LIST_PARAGRAPH = (-180, "List Paragraph.") """List Paragraph.""" MACRO_TEXT = (-46, "Macro Text.") """Macro Text.""" MESSAGE_HEADER = (-74, "Message Header.") """Message Header.""" NAV_PANE = (-90, "Document Map.") """Document Map.""" NORMAL = (-1, "Normal.") """Normal.""" NORMAL_INDENT = (-29, "Normal Indent.") """Normal Indent.""" NORMAL_OBJECT = (-158, "Normal (applied to an object).") """Normal (applied to an object).""" NORMAL_TABLE = (-106, "Normal (applied within a table).") """Normal (applied within a table).""" NOTE_HEADING = (-80, "Note Heading.") """Note Heading.""" PAGE_NUMBER = (-42, "Page Number.") """Page Number.""" PLAIN_TEXT = (-91, "Plain Text.") """Plain Text.""" QUOTE = (-181, "Quote.") """Quote.""" SALUTATION = (-76, "Salutation.") """Salutation.""" SIGNATURE = (-65, "Signature.") """Signature.""" STRONG = (-88, "Strong.") """Strong.""" SUBTITLE = (-75, "Subtitle.") """Subtitle.""" SUBTLE_EMPHASIS = (-261, "Subtle Emphasis.") """Subtle Emphasis.""" SUBTLE_REFERENCE = (-263, "Subtle Reference.") """Subtle Reference.""" TABLE_COLORFUL_GRID = (-172, "Colorful Grid.") """Colorful Grid.""" TABLE_COLORFUL_LIST = (-171, "Colorful List.") """Colorful List.""" TABLE_COLORFUL_SHADING = (-170, "Colorful Shading.") """Colorful Shading.""" TABLE_DARK_LIST = (-169, "Dark List.") """Dark List.""" TABLE_LIGHT_GRID = (-161, "Light Grid.") """Light Grid.""" TABLE_LIGHT_GRID_ACCENT_1 = (-175, "Light Grid Accent 1.") """Light Grid Accent 1.""" TABLE_LIGHT_LIST = (-160, "Light List.") """Light List.""" TABLE_LIGHT_LIST_ACCENT_1 = (-174, "Light List Accent 1.") """Light List Accent 1.""" TABLE_LIGHT_SHADING = (-159, "Light Shading.") """Light Shading.""" TABLE_LIGHT_SHADING_ACCENT_1 = (-173, "Light Shading Accent 1.") """Light Shading Accent 1.""" TABLE_MEDIUM_GRID_1 = (-166, "Medium Grid 1.") """Medium Grid 1.""" TABLE_MEDIUM_GRID_2 = (-167, "Medium Grid 2.") """Medium Grid 2.""" TABLE_MEDIUM_GRID_3 = (-168, "Medium Grid 3.") """Medium Grid 3.""" TABLE_MEDIUM_LIST_1 = (-164, "Medium List 1.") """Medium List 1.""" TABLE_MEDIUM_LIST_1_ACCENT_1 = (-178, "Medium List 1 Accent 1.") """Medium List 1 Accent 1.""" TABLE_MEDIUM_LIST_2 = (-165, "Medium List 2.") """Medium List 2.""" TABLE_MEDIUM_SHADING_1 = (-162, "Medium Shading 1.") """Medium Shading 1.""" TABLE_MEDIUM_SHADING_1_ACCENT_1 = (-176, "Medium Shading 1 Accent 1.") """Medium Shading 1 Accent 1.""" TABLE_MEDIUM_SHADING_2 = (-163, "Medium Shading 2.") """Medium Shading 2.""" TABLE_MEDIUM_SHADING_2_ACCENT_1 = (-177, "Medium Shading 2 Accent 1.") """Medium Shading 2 Accent 1.""" TABLE_OF_AUTHORITIES = (-45, "Table of Authorities.") """Table of Authorities.""" TABLE_OF_FIGURES = (-36, "Table of Figures.") """Table of Figures.""" TITLE = (-63, "Title.") """Title.""" TOAHEADING = (-47, "TOA Heading.") """TOA Heading.""" TOC_1 = (-20, "TOC 1.") """TOC 1.""" TOC_2 = (-21, "TOC 2.") """TOC 2.""" TOC_3 = (-22, "TOC 3.") """TOC 3.""" TOC_4 = (-23, "TOC 4.") """TOC 4.""" TOC_5 = (-24, "TOC 5.") """TOC 5.""" TOC_6 = (-25, "TOC 6.") """TOC 6.""" TOC_7 = (-26, "TOC 7.") """TOC 7.""" TOC_8 = (-27, "TOC 8.") """TOC 8.""" TOC_9 = (-28, "TOC 9.") """TOC 9.""" WD_STYLE = WD_BUILTIN_STYLE
WD_BUILTIN_STYLE
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 26416, "end": 36942 }
class ____: """ Object to capture all the details for a compiled FX graph relevant to computing a safe and stable cache key. """ # Excluded kwargs param that are not stable between runs EXCLUDED_KWARGS = ["graph_id"] def __init__( self, gm: torch.fx.GraphModule, example_inputs: Sequence[InputType], fx_kwargs: _CompileFxKwargs, inputs_to_check: Sequence[int], ) -> None: self.gm = gm self.example_inputs = example_inputs self.cache_key_tag = cconfig.cache_key_tag # Order kwargs so hashing is stable to changes in kwarg order. Although # it's technically a _CompileFxKwargs we don't actually need it typed as # such since we're just using it to generate a hash. self.fx_kwargs: dict[str, object] = {} for k, v in sorted(fx_kwargs.items()): if k not in self.EXCLUDED_KWARGS: if type(v) in (set, OrderedSet): # noqa: set_linter # Special case to handle set params. Python sets can't be # ordered, so sort the elements and store them in a proxy. self.fx_kwargs[k] = OrderedSetHolder(sorted(v)) # type: ignore[call-overload] else: self.fx_kwargs[k] = v from torch._higher_order_ops.triton_kernel_wrap import ( kernel_side_table, triton_kernel_wrapper_functional, triton_kernel_wrapper_mutation, ) from torch._inductor.codegen.wrapper import ( user_defined_triton_kernel_transitive_closure_source_code, ) # Node meta will not be part of gm's reduce function, so lets remember # the kernel source code separately self.user_defined_triton_source: list[Any] = [] if gm is not None: for module in gm.modules(): if not isinstance(module, torch.fx.GraphModule): continue for node in itertools.chain( module.graph.find_nodes( op="call_function", target=triton_kernel_wrapper_functional ), module.graph.find_nodes( op="call_function", target=triton_kernel_wrapper_mutation ), ): from triton.runtime.autotuner import Autotuner kernel = kernel_side_table.get_kernel(node.kwargs["kernel_idx"]) configs = None if isinstance(kernel, Autotuner): if kernel.configs: configs = str( sorted( sorted(str(kv) for kv in c.all_kwargs().items()) for c in kernel.configs ) ) kernel = kernel.fn kernel_source = ( user_defined_triton_kernel_transitive_closure_source_code( kernel ) ) constant_args = kernel_side_table.get_constant_args( node.kwargs["constant_args_idx"] ) self.user_defined_triton_source.append( (kernel_source, constant_args, configs) ) # Alignment checks self.inputs_to_check = inputs_to_check no_tensor_inputs = not any(isinstance(x, torch.Tensor) for x in example_inputs) # This device index is usually already encoded by the device of the inputs # but fx graphs don't necessarily have tensor inputs. If there aren't any, # we need to guard on the device index in case we allocate cuda tensors if no_tensor_inputs and torch.accelerator.is_available(): self.default_cuda_device_index = torch.accelerator.current_device_index() # 'Deterministic algorithms' can affect codegen via lowering to cuda kernels. self.deterministic_algorithms_settings = ( torch.are_deterministic_algorithms_enabled(), torch.is_deterministic_algorithms_warn_only_enabled(), torch.utils.deterministic.fill_uninitialized_memory, # type: ignore[attr-defined] ) # Global settings affecting matmul codegen. self.cuda_matmul_settings = ( torch.backends.cuda.matmul.fp32_precision, torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction, torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, ) # Also hash on various system info (including the triton compiler version). self.torch_version = torch_key() self.system_info = CacheBase.get_system() self.inductor_config = config.save_config_portable(ignore_private_configs=False) # Custom post grad passes should provide an ID to hash. self.post_grad_custom_pre_pass = self._get_custom_pass_detail( config.post_grad_custom_pre_pass ) # TODO: change to more holistic config rather than bundled_autograd_cache self.precompile_enabled = torch._functorch.config.bundled_autograd_cache self.post_grad_custom_post_pass = self._get_custom_pass_detail( config.post_grad_custom_post_pass ) self.joint_custom_pre_pass = self._get_custom_pass_detail( config.joint_custom_pre_pass ) self.joint_custom_post_pass = self._get_custom_pass_detail( config.joint_custom_post_pass ) self._pre_fusion_custom_pass = self._get_custom_pass_detail_unsafe( config._pre_fusion_custom_pass ) self._fuse_ddp_communication_passes = self._get_custom_pass_detail_unsafe( config._fuse_ddp_communication_passes ) # Register indcutor backends and custom passes and get their UUIDs. init_backend_registration() self.custom_backend_passes = tuple( map(self._get_custom_pass_detail, custom_backend_passes.values()) ) # Save custom inductor codegen configs self.custom_backend_codegen_configs = { device: custom_config.save_config_portable(ignore_private_configs=False) for device, custom_config in custom_backend_codegen_configs.items() if custom_config is not None } # Register the custom partitioner function self._custom_partitioner_fn = self._get_custom_partitioner_fn_detail( config.custom_partitioner_fn ) # This is mainly added to handle these two inductor configs, which are (unfortunately) # sometimes cache safe: # - _pre_fusion_custom_pass # - _fuse_ddp_communication_passes # Their types can be found in `torch/_inductor/config.py`, but: # - if they are string names, we can cache them safely (one is by default) # - if any of them are set to custom callables, we will need to cache miss # Future work is for someone to find any places where these functions are used # and force them to be of type CustomGraphPass, so we can guarantee serialization. def _get_custom_pass_detail_unsafe(self, custom_pass: Any) -> Any | None: if not custom_pass: return None if isinstance(custom_pass, list): return [self._get_custom_pass_detail_unsafe(x) for x in custom_pass] if isinstance(custom_pass, str): return custom_pass if isinstance(custom_pass, CustomGraphPass): return custom_pass.uuid() if callable(custom_pass): # Returning None is safe here because we raise an explicit bypass error # later if we detect these passes are set to callables return None raise AssertionError(f"unknown config type: {str(type(custom_pass))}") def _get_custom_pass_detail( self, custom_pass: CustomGraphPassType | CustomGraphModulePass ) -> Any | None: if not custom_pass: return None assert isinstance(custom_pass, (CustomGraphPass, CustomGraphModulePass)) return custom_pass.uuid() def _get_custom_partitioner_fn_detail( self, custom_partitioner_fn: CustomPartitionerFnType ) -> Any | None: if not custom_partitioner_fn: return None assert isinstance(custom_partitioner_fn, CustomPartitionerFn) return custom_partitioner_fn.uuid() def compiled_fx_graph_hash( gm: torch.fx.GraphModule, example_inputs: Sequence[InputType], fx_kwargs: _CompileFxKwargs, inputs_to_check: Sequence[int], ) -> tuple[str, list[str]]: """ Generate a unique hash of the FX graph for caching. """ details = FxGraphHashDetails(gm, example_inputs, fx_kwargs, inputs_to_check) has_user_defined_triton_kernels = len(details.user_defined_triton_source) != 0 pickler = FxGraphCachePickler(gm, has_user_defined_triton_kernels) # The prefix distinguishes among the other kinds of objects we # cache in this module. key = "f" + pickler.get_hash(details) debug_lines = pickler.debug_lines(details) debug_str = "\n".join(debug_lines) log.debug(f"FX graph cache hash details for key {key}:\n{debug_str}") # noqa: G004 return key, debug_lines def add_ephemeral_timeout_increase_for_distributed(time_saved_ns: int) -> int: """ Ephemerally increases the NCCL timeout when compiling for a distributed job Returns amount of seconds increased """ if not torch.distributed.is_available() or not torch.distributed.is_initialized(): return 0 increased_timeout_sec = int(time_saved_ns // 1e9) # convert to seconds if config.is_fbcode(): fudge_factor = torch._utils_internal.justknobs_getval_int( "pytorch/remote_cache:ephemeral_timeout_fudge_factor_percentage" ) log.info( "Ephemeral NCCL timeout increase fudge factor %d and original increase value %d", fudge_factor, increased_timeout_sec, ) increased_timeout_sec += int(increased_timeout_sec * fudge_factor / 100) log.info("Increasing NCCL timeout by %d", increased_timeout_sec) dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs( timedelta(seconds=increased_timeout_sec) ) return increased_timeout_sec
FxGraphHashDetails
python
huggingface__transformers
tests/models/mistral3/test_modeling_mistral3.py
{ "start": 1447, "end": 5411 }
class ____: def __init__( self, parent, batch_size=3, seq_length=7, image_seq_length=4, vision_feature_layer=-1, ignore_index=-100, image_token_index=1, num_channels=3, image_size=30, model_type="mistral3", is_training=True, text_config={ "model_type": "mistral", "vocab_size": 99, "attention_dropout": 0.0, "hidden_act": "silu", "hidden_size": 32, "initializer_range": 0.02, "intermediate_size": 37, "max_position_embeddings": 512, "num_attention_heads": 4, "num_hidden_layers": 2, "num_key_value_heads": 2, "rms_norm_eps": 1e-05, "rope_theta": 1000000000.0, "sliding_window": None, "bos_token_id": 2, "eos_token_id": 3, "pad_token_id": 4, }, vision_config={ "model_type": "pixtral", "hidden_size": 32, "num_hidden_layers": 2, "num_attention_heads": 4, "intermediate_size": 37, "image_size": 30, "patch_size": 6, "num_channels": 3, "hidden_act": "gelu", }, ): self.parent = parent self.ignore_index = ignore_index self.bos_token_id = text_config["bos_token_id"] self.eos_token_id = text_config["eos_token_id"] self.pad_token_id = text_config["pad_token_id"] self.image_token_index = image_token_index self.model_type = model_type self.text_config = text_config self.vision_config = vision_config self.batch_size = batch_size self.vision_feature_layer = vision_feature_layer self.is_training = is_training self.image_seq_length = image_seq_length self.num_channels = num_channels self.image_size = image_size self.seq_length = seq_length + self.image_seq_length self.num_hidden_layers = text_config["num_hidden_layers"] self.vocab_size = text_config["vocab_size"] self.hidden_size = text_config["hidden_size"] self.num_attention_heads = text_config["num_attention_heads"] def get_config(self): return Mistral3Config( text_config=self.text_config, vision_config=self.vision_config, model_type=self.model_type, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, image_token_index=self.image_token_index, image_seq_length=self.image_seq_length, vision_feature_layer=self.vision_feature_layer, ) def prepare_config_and_inputs(self): config = self.get_config() pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) return config, pixel_values def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) image_sizes = torch.tensor( [[self.image_size, self.image_size]] * self.batch_size, dtype=torch.long, device=torch_device ) # input_ids[:, -1] = self.pad_token_id input_ids[input_ids == self.image_token_index] = self.pad_token_id input_ids[:, : self.image_seq_length] = self.image_token_index inputs_dict = { "pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask, "image_sizes": image_sizes, } return config, inputs_dict @require_torch
Mistral3VisionText2TextModelTester
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_datetime.py
{ "start": 287, "end": 5378 }
class ____: def test_is_(self): dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME") assert dti.is_(dti) assert dti.is_(dti.view()) assert not dti.is_(dti.copy()) def test_time_overflow_for_32bit_machines(self): # GH8943. On some machines NumPy defaults to np.int32 (for example, # 32-bit Linux machines). In the function _generate_regular_range # found in tseries/index.py, `periods` gets multiplied by `strides` # (which has value 1e9) and since the max value for np.int32 is ~2e9, # and since those machines won't promote np.int32 to np.int64, we get # overflow. periods = np_long(1000) idx1 = date_range(start="2000", periods=periods, freq="s") assert len(idx1) == periods idx2 = date_range(end="2000", periods=periods, freq="s") assert len(idx2) == periods def test_nat(self): assert DatetimeIndex([np.nan])[0] is pd.NaT def test_week_of_month_frequency(self): # GH 5348: "ValueError: Could not evaluate WOM-1SUN" shouldn't raise d1 = date(2002, 9, 1) d2 = date(2013, 10, 27) d3 = date(2012, 9, 30) idx1 = DatetimeIndex([d1, d2]) idx2 = DatetimeIndex([d3]) result_append = idx1.append(idx2) expected = DatetimeIndex([d1, d2, d3]) tm.assert_index_equal(result_append, expected) result_union = idx1.union(idx2) expected = DatetimeIndex([d1, d3, d2]) tm.assert_index_equal(result_union, expected) def test_append_nondatetimeindex(self): rng = date_range("1/1/2000", periods=10) idx = Index(["a", "b", "c", "d"]) result = rng.append(idx) assert isinstance(result[0], Timestamp) def test_misc_coverage(self): rng = date_range("1/1/2000", periods=5) result = rng.groupby(rng.day) assert isinstance(next(iter(result.values()))[0], Timestamp) # TODO: belongs in frame groupby tests? def test_groupby_function_tuple_1677(self): df = DataFrame( np.random.default_rng(2).random(100), index=date_range("1/1/2000", periods=100), ) monthly_group = df.groupby(lambda x: (x.year, x.month)) result = monthly_group.mean() assert isinstance(result.index[0], tuple) def assert_index_parameters(self, index): assert index.freq == "40960ns" assert index.inferred_freq == "40960ns" def test_ns_index(self): nsamples = 400 ns = int(1e9 / 24414) dtstart = np.datetime64("2012-09-20T00:00:00") dt = dtstart + np.arange(nsamples) * np.timedelta64(ns, "ns") freq = ns * offsets.Nano() index = DatetimeIndex(dt, freq=freq, name="time") self.assert_index_parameters(index) new_index = date_range(start=index[0], end=index[-1], freq=index.freq) self.assert_index_parameters(new_index) def test_asarray_tz_naive(self): # This shouldn't produce a warning. idx = date_range("2000", periods=2, unit="ns") # M8[ns] by default result = np.asarray(idx) expected = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]") tm.assert_numpy_array_equal(result, expected) # optionally, object result = np.asarray(idx, dtype=object) expected = np.array([Timestamp("2000-01-01"), Timestamp("2000-01-02")]) tm.assert_numpy_array_equal(result, expected) def test_asarray_tz_aware(self): tz = "US/Central" idx = date_range("2000", periods=2, tz=tz, unit="ns") expected = np.array(["2000-01-01T06", "2000-01-02T06"], dtype="M8[ns]") result = np.asarray(idx, dtype="datetime64[ns]") tm.assert_numpy_array_equal(result, expected) # Old behavior with no warning result = np.asarray(idx, dtype="M8[ns]") tm.assert_numpy_array_equal(result, expected) # Future behavior with no warning expected = np.array( [Timestamp("2000-01-01", tz=tz), Timestamp("2000-01-02", tz=tz)] ) result = np.asarray(idx, dtype=object) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("freq", ["2H", "2BH", "2S"]) def test_CBH_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): date_range(dt.datetime(2022, 12, 11), dt.datetime(2022, 12, 13), freq=freq) @pytest.mark.parametrize("freq", ["2BM", "1bm", "2BQ", "1BQ-MAR", "2BY-JUN", "1by"]) def test_BM_BQ_BY_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): date_range(start="2016-02-21", end="2016-08-21", freq=freq) @pytest.mark.parametrize("freq", ["2BA-MAR", "1BAS-MAY", "2AS-AUG"]) def test_BA_BAS_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): date_range(start="2016-02-21", end="2016-08-21", freq=freq)
TestDatetimeIndex
python
chardet__chardet
chardet/sbcharsetprober.py
{ "start": 1329, "end": 1578 }
class ____(NamedTuple): charset_name: str language: str char_to_order_map: Dict[int, int] language_model: Dict[int, Dict[int, int]] typical_positive_ratio: float keep_ascii_letters: bool alphabet: str
SingleByteCharSetModel
python
kamyu104__LeetCode-Solutions
Python/better-compression-of-string.py
{ "start": 63, "end": 670 }
class ____(object): def betterCompression(self, compressed): """ :type compressed: str :rtype: str """ cnt = [0]*26 x, curr = -1, 0 for i in xrange(len(compressed)): if not compressed[i].isdigit(): x = ord(compressed[i])-ord('a') continue curr = curr*10+int(compressed[i]) if i+1 == len(compressed) or not compressed[i+1].isdigit(): cnt[x] += curr curr = 0 return "".join("%s%s" % (chr(ord('a')+i), x) for i, x in enumerate(cnt) if x)
Solution
python
kubernetes-client__python
kubernetes/client/models/v1_node_runtime_handler.py
{ "start": 383, "end": 4262 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'features': 'V1NodeRuntimeHandlerFeatures', 'name': 'str' } attribute_map = { 'features': 'features', 'name': 'name' } def __init__(self, features=None, name=None, local_vars_configuration=None): # noqa: E501 """V1NodeRuntimeHandler - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._features = None self._name = None self.discriminator = None if features is not None: self.features = features if name is not None: self.name = name @property def features(self): """Gets the features of this V1NodeRuntimeHandler. # noqa: E501 :return: The features of this V1NodeRuntimeHandler. # noqa: E501 :rtype: V1NodeRuntimeHandlerFeatures """ return self._features @features.setter def features(self, features): """Sets the features of this V1NodeRuntimeHandler. :param features: The features of this V1NodeRuntimeHandler. # noqa: E501 :type: V1NodeRuntimeHandlerFeatures """ self._features = features @property def name(self): """Gets the name of this V1NodeRuntimeHandler. # noqa: E501 Runtime handler name. Empty for the default runtime handler. # noqa: E501 :return: The name of this V1NodeRuntimeHandler. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1NodeRuntimeHandler. Runtime handler name. Empty for the default runtime handler. # noqa: E501 :param name: The name of this V1NodeRuntimeHandler. # noqa: E501 :type: str """ self._name = name def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1NodeRuntimeHandler): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1NodeRuntimeHandler): return True return self.to_dict() != other.to_dict()
V1NodeRuntimeHandler
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/etcd_server.py
{ "start": 2132, "end": 8415 }
class ____: """ .. note:: tested on etcd server v3.4.3. Starts and stops a local standalone etcd server on a random free port. Useful for single node, multi-worker launches or testing, where a sidecar etcd server is more convenient than having to separately setup an etcd server. This class registers a termination handler to shutdown the etcd subprocess on exit. This termination handler is NOT a substitute for calling the ``stop()`` method. The following fallback mechanism is used to find the etcd binary: 1. Uses env var TORCHELASTIC_ETCD_BINARY_PATH 2. Uses ``<this file root>/bin/etcd`` if one exists 3. Uses ``etcd`` from ``PATH`` Usage :: server = EtcdServer("/usr/bin/etcd", 2379, "/tmp/default.etcd") server.start() client = server.get_client() # use client server.stop() Args: etcd_binary_path: path of etcd server binary (see above for fallback path) """ def __init__(self, data_dir: str | None = None): self._port = -1 self._host = "localhost" root = os.path.dirname(__file__) default_etcd_bin = os.path.join(root, "bin/etcd") self._etcd_binary_path = os.environ.get( "TORCHELASTIC_ETCD_BINARY_PATH", default_etcd_bin ) if not os.path.isfile(self._etcd_binary_path): self._etcd_binary_path = "etcd" self._base_data_dir = ( data_dir if data_dir else tempfile.mkdtemp(prefix="torchelastic_etcd_data") ) self._etcd_cmd = None self._etcd_proc: subprocess.Popen | None = None def _get_etcd_server_process(self) -> subprocess.Popen: if not self._etcd_proc: raise RuntimeError( "No etcd server process started. Call etcd_server.start() first" ) else: return self._etcd_proc def get_port(self) -> int: """Return the port the server is running on.""" return self._port def get_host(self) -> str: """Return the host the server is running on.""" return self._host def get_endpoint(self) -> str: """Return the etcd server endpoint (host:port).""" return f"{self._host}:{self._port}" def start( self, timeout: int = 60, num_retries: int = 3, stderr: int | TextIO | None = None, ) -> None: """ Start the server, and waits for it to be ready. When this function returns the sever is ready to take requests. Args: timeout: time (in seconds) to wait for the server to be ready before giving up. num_retries: number of retries to start the server. Each retry will wait for max ``timeout`` before considering it as failed. stderr: the standard error file handle. Valid values are `subprocess.PIPE`, `subprocess.DEVNULL`, an existing file descriptor (a positive integer), an existing file object, and `None`. Raises: TimeoutError: if the server is not ready within the specified timeout """ curr_retries = 0 while True: try: data_dir = os.path.join(self._base_data_dir, str(curr_retries)) os.makedirs(data_dir, exist_ok=True) return self._start(data_dir, timeout, stderr) except Exception as e: curr_retries += 1 stop_etcd(self._etcd_proc) logger.warning( # noqa: G200 "Failed to start etcd server, got error: %s, retrying", str(e) ) if curr_retries >= num_retries: shutil.rmtree(self._base_data_dir, ignore_errors=True) raise atexit.register(stop_etcd, self._etcd_proc, self._base_data_dir) def _start( self, data_dir: str, timeout: int = 60, stderr: int | TextIO | None = None ) -> None: sock = find_free_port() sock_peer = find_free_port() self._port = sock.getsockname()[1] peer_port = sock_peer.getsockname()[1] etcd_cmd = shlex.split( " ".join( [ self._etcd_binary_path, "--enable-v2", "--data-dir", data_dir, "--listen-client-urls", f"http://{self._host}:{self._port}", "--advertise-client-urls", f"http://{self._host}:{self._port}", "--listen-peer-urls", f"http://{self._host}:{peer_port}", ] ) ) logger.info("Starting etcd server: [%s]", etcd_cmd) sock.close() sock_peer.close() self._etcd_proc = subprocess.Popen(etcd_cmd, close_fds=True, stderr=stderr) self._wait_for_ready(timeout) def get_client(self): """Return an etcd client object that can be used to make requests to this server.""" return etcd.Client( host=self._host, port=self._port, version_prefix="/v2", read_timeout=10 ) def _wait_for_ready(self, timeout: int = 60) -> None: client = etcd.Client( host=f"{self._host}", port=self._port, version_prefix="/v2", read_timeout=5 ) max_time = time.time() + timeout while time.time() < max_time: if self._get_etcd_server_process().poll() is not None: # etcd server process finished exitcode = self._get_etcd_server_process().returncode raise RuntimeError( f"Etcd server process exited with the code: {exitcode}" ) try: logger.info("etcd server ready. version: %s", client.version) return except Exception: time.sleep(1) raise TimeoutError("Timed out waiting for etcd server to be ready!") def stop(self) -> None: """Stop the server and cleans up auto generated resources (e.g. data dir).""" logger.info("EtcdServer stop method called") stop_etcd(self._etcd_proc, self._base_data_dir)
EtcdServer
python
pypa__pip
src/pip/_internal/resolution/resolvelib/requirements.py
{ "start": 5214, "end": 7260 }
class ____(Requirement): """A requirement representing Requires-Python metadata.""" def __init__(self, specifier: SpecifierSet, match: Candidate) -> None: self.specifier = specifier self._specifier_string = str(specifier) # for faster __eq__ self._hash: int | None = None self._candidate = match # Pre-compute candidate lookup to avoid repeated specifier checks if specifier.contains(match.version, prereleases=True): self._candidate_lookup: CandidateLookup = (match, None) else: self._candidate_lookup = (None, None) def __str__(self) -> str: return f"Python {self.specifier}" def __repr__(self) -> str: return f"{self.__class__.__name__}({str(self.specifier)!r})" def __hash__(self) -> int: if self._hash is not None: return self._hash self._hash = hash((self._specifier_string, self._candidate)) return self._hash def __eq__(self, other: Any) -> bool: if not isinstance(other, RequiresPythonRequirement): return False return ( self._specifier_string == other._specifier_string and self._candidate == other._candidate ) @property def project_name(self) -> NormalizedName: return self._candidate.project_name @property def name(self) -> str: return self._candidate.name def format_for_error(self) -> str: return str(self) def get_candidate_lookup(self) -> CandidateLookup: return self._candidate_lookup def is_satisfied_by(self, candidate: Candidate) -> bool: assert candidate.name == self._candidate.name, "Not Python candidate" # We can safely always allow prereleases here since PackageFinder # already implements the prerelease logic, and would have filtered out # prerelease candidates if the user does not expect them. return self.specifier.contains(candidate.version, prereleases=True)
RequiresPythonRequirement
python
apache__airflow
providers/apache/cassandra/tests/unit/apache/cassandra/sensors/test_record.py
{ "start": 1051, "end": 3262 }
class ____: @patch("airflow.providers.apache.cassandra.sensors.record.CassandraHook") def test_poke(self, mock_hook): sensor = CassandraRecordSensor( task_id="test_task", cassandra_conn_id=TEST_CASSANDRA_CONN_ID, table=TEST_CASSANDRA_TABLE, keys=TEST_CASSANDRA_KEY, ) exists = sensor.poke(dict()) assert exists mock_hook.return_value.record_exists.assert_called_once_with(TEST_CASSANDRA_TABLE, TEST_CASSANDRA_KEY) mock_hook.assert_called_once_with(TEST_CASSANDRA_CONN_ID) @patch("airflow.providers.apache.cassandra.sensors.record.CassandraHook") def test_poke_should_not_fail_with_empty_keys(self, mock_hook): sensor = CassandraRecordSensor( task_id="test_task", cassandra_conn_id=TEST_CASSANDRA_CONN_ID, table=TEST_CASSANDRA_TABLE, keys=None, ) exists = sensor.poke(dict()) assert exists mock_hook.return_value.record_exists.assert_called_once_with(TEST_CASSANDRA_TABLE, None) mock_hook.assert_called_once_with(TEST_CASSANDRA_CONN_ID) @patch("airflow.providers.apache.cassandra.sensors.record.CassandraHook") def test_poke_should_return_false_for_non_existing_table(self, mock_hook): mock_hook.return_value.record_exists.return_value = False sensor = CassandraRecordSensor( task_id="test_task", cassandra_conn_id=TEST_CASSANDRA_CONN_ID, table=TEST_CASSANDRA_TABLE, keys=TEST_CASSANDRA_KEY, ) exists = sensor.poke(dict()) assert not exists mock_hook.return_value.record_exists.assert_called_once_with(TEST_CASSANDRA_TABLE, TEST_CASSANDRA_KEY) mock_hook.assert_called_once_with(TEST_CASSANDRA_CONN_ID) @patch("airflow.providers.apache.cassandra.sensors.record.CassandraHook") def test_init_with_default_conn(self, mock_hook): sensor = CassandraRecordSensor( task_id="test_task", table=TEST_CASSANDRA_TABLE, keys=TEST_CASSANDRA_KEY, ) assert sensor.cassandra_conn_id == TEST_CASSANDRA_CONN_ID
TestCassandraRecordSensor
python
huggingface__transformers
src/transformers/models/deepseek_v2/modular_deepseek_v2.py
{ "start": 14696, "end": 15548 }
class ____(LlamaRotaryEmbedding): @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.to(x.device) @ position_ids_expanded).transpose(1, 2) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # Convert to complex representation freqs_cis = freqs_cis * self.attention_scaling return freqs_cis
DeepseekV2RotaryEmbedding