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
langchain-ai__langchain
libs/langchain/langchain_classic/agents/xml/base.py
{ "start": 1033, "end": 8165 }
class ____(BaseSingleActionAgent): """Agent that uses XML tags. Args: tools: list of tools the agent can choose from llm_chain: The LLMChain to call to predict the next action Examples: ```python from langchain_classic.agents import XMLAgent from langchain tools = ... model = ``` """ tools: list[BaseTool] """List of tools this agent has access to.""" llm_chain: LLMChain """Chain to use to predict action.""" @property @override def input_keys(self) -> list[str]: return ["input"] @staticmethod def get_default_prompt() -> ChatPromptTemplate: """Return the default prompt for the XML agent.""" base_prompt = ChatPromptTemplate.from_template(agent_instructions) return base_prompt + AIMessagePromptTemplate.from_template( "{intermediate_steps}", ) @staticmethod def get_default_output_parser() -> XMLAgentOutputParser: """Return an XMLAgentOutputParser.""" return XMLAgentOutputParser() @override def plan( self, intermediate_steps: list[tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> AgentAction | AgentFinish: log = "" for action, observation in intermediate_steps: log += ( f"<tool>{action.tool}</tool><tool_input>{action.tool_input}" f"</tool_input><observation>{observation}</observation>" ) tools = "" for tool in self.tools: tools += f"{tool.name}: {tool.description}\n" inputs = { "intermediate_steps": log, "tools": tools, "question": kwargs["input"], "stop": ["</tool_input>", "</final_answer>"], } response = self.llm_chain(inputs, callbacks=callbacks) return response[self.llm_chain.output_key] @override async def aplan( self, intermediate_steps: list[tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> AgentAction | AgentFinish: log = "" for action, observation in intermediate_steps: log += ( f"<tool>{action.tool}</tool><tool_input>{action.tool_input}" f"</tool_input><observation>{observation}</observation>" ) tools = "" for tool in self.tools: tools += f"{tool.name}: {tool.description}\n" inputs = { "intermediate_steps": log, "tools": tools, "question": kwargs["input"], "stop": ["</tool_input>", "</final_answer>"], } response = await self.llm_chain.acall(inputs, callbacks=callbacks) return response[self.llm_chain.output_key] def create_xml_agent( llm: BaseLanguageModel, tools: Sequence[BaseTool], prompt: BasePromptTemplate, tools_renderer: ToolsRenderer = render_text_description, *, stop_sequence: bool | list[str] = True, ) -> Runnable: r"""Create an agent that uses XML to format its logic. Args: llm: LLM to use as the agent. tools: Tools this agent has access to. prompt: The prompt to use, must have input keys `tools`: contains descriptions for each tool. `agent_scratchpad`: contains previous agent actions and tool outputs. tools_renderer: This controls how the tools are converted into a string and then passed into the LLM. stop_sequence: bool or list of str. If `True`, adds a stop token of "</tool_input>" to avoid hallucinates. If `False`, does not add a stop token. If a list of str, uses the provided list as the stop tokens. You may to set this to False if the LLM you are using does not support stop sequences. Returns: A Runnable sequence representing an agent. It takes as input all the same input variables as the prompt passed in does. It returns as output either an AgentAction or AgentFinish. Example: ```python from langchain_classic import hub from langchain_anthropic import ChatAnthropic from langchain_classic.agents import AgentExecutor, create_xml_agent prompt = hub.pull("hwchase17/xml-agent-convo") model = ChatAnthropic(model="claude-3-haiku-20240307") tools = ... agent = create_xml_agent(model, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools) agent_executor.invoke({"input": "hi"}) # Use with chat history from langchain_core.messages import AIMessage, HumanMessage agent_executor.invoke( { "input": "what's my name?", # Notice that chat_history is a string # since this prompt is aimed at LLMs, not chat models "chat_history": "Human: My name is Bob\nAI: Hello Bob!", } ) ``` Prompt: The prompt must have input keys: * `tools`: contains descriptions for each tool. * `agent_scratchpad`: contains previous agent actions and tool outputs as an XML string. Here's an example: ```python from langchain_core.prompts import PromptTemplate template = '''You are a helpful assistant. Help the user answer any questions. You have access to the following tools: {tools} In order to use a tool, you can use <tool></tool> and <tool_input></tool_input> tags. You will then get back a response in the form <observation></observation> For example, if you have a tool called 'search' that could run a google search, in order to search for the weather in SF you would respond: <tool>search</tool><tool_input>weather in SF</tool_input> <observation>64 degrees</observation> When you are done, respond with a final answer between <final_answer></final_answer>. For example: <final_answer>The weather in SF is 64 degrees</final_answer> Begin! Previous Conversation: {chat_history} Question: {input} {agent_scratchpad}''' prompt = PromptTemplate.from_template(template) ``` """ # noqa: E501 missing_vars = {"tools", "agent_scratchpad"}.difference( prompt.input_variables + list(prompt.partial_variables), ) if missing_vars: msg = f"Prompt missing required variables: {missing_vars}" raise ValueError(msg) prompt = prompt.partial( tools=tools_renderer(list(tools)), ) if stop_sequence: stop = ["</tool_input>"] if stop_sequence is True else stop_sequence llm_with_stop = llm.bind(stop=stop) else: llm_with_stop = llm return ( RunnablePassthrough.assign( agent_scratchpad=lambda x: format_xml(x["intermediate_steps"]), ) | prompt | llm_with_stop | XMLAgentOutputParser() )
XMLAgent
python
ray-project__ray
doc/source/serve/doc_code/multiplexed.py
{ "start": 126, "end": 1393 }
class ____: def __init__(self): self.bucket_name = "my_bucket" @serve.multiplexed(max_num_models_per_replica=3) async def get_model(self, model_id: str): session = aioboto3.Session() async with session.resource("s3") as s3: obj = await s3.Bucket(self.bucket_name) await obj.download_file(f"{model_id}/model.pt", f"model_{model_id}.pt") return torch.load(f"model_{model_id}.pt") async def __call__(self, request: starlette.requests.Request): model_id = serve.get_multiplexed_model_id() model = await self.get_model(model_id) return model.forward(torch.rand(64, 3, 512, 512)) entry = ModelInferencer.bind() # __serve_deployment_example_end__ handle = serve.run(entry) # __serve_request_send_example_begin__ import requests # noqa: E402 resp = requests.get( "http://localhost:8000", headers={"serve_multiplexed_model_id": str("1")} ) # __serve_request_send_example_end__ # __serve_handle_send_example_begin__ obj_ref = handle.options(multiplexed_model_id="1").remote("<your param>") # __serve_handle_send_example_end__ from ray.serve.handle import DeploymentHandle # noqa: E402 # __serve_model_composition_example_begin__ @serve.deployment
ModelInferencer
python
doocs__leetcode
solution/0500-0599/0590.N-ary Tree Postorder Traversal/Solution.py
{ "start": 152, "end": 450 }
class ____: def postorder(self, root: 'Node') -> List[int]: def dfs(root): if root is None: return for child in root.children: dfs(child) ans.append(root.val) ans = [] dfs(root) return ans
Solution
python
pytorch__pytorch
torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py
{ "start": 13773, "end": 22720 }
class ____(_LoadBalancer): """ Processing-Time based Round-Robin (PTRR) load balancer. This load balancer should only be used for flex_attention() since it leverages `BlockMask`. """ def __init__( self, block_mask: BlockMask, world_size: int, ): """ `block_mask` must have shape (B, 1, seq_len, seq_len) or (1, 1, seq_len, seq_len). """ self.block_mask = block_mask self.world_size = world_size @staticmethod def ptrr_scheduling(process_time: Tensor, group_size: int) -> Tensor: """ Separate the tasks into `group_size` groups using PTRR scheduling. process_time: 1D tensor of size n, where n is the number of tasks. The value is the process time of the task. Size `n` must be divisible by `group_size`. group_size: the number of groups Returns: tasks_in_group (list[list[int]]): A collection of list[int] and each list should have size `n // group_size` (`group_size` lists in total). Each element is an index in the input `process_time` (i.e. [0, len(process_time) - 1]). Example: process_time = [9, 14, 2, 20, 10, 15, 8, 14, 16, 19, 15, 3, 12, 1, 12, 10] tasks_in_group = [ [3, 12, 13, 14], # values = [1, 12, 12, 20], sum = 45 [2, 4, 7, 9], # values = [2, 10, 14, 19], sum = 45 [1, 8, 11, 15], # values = [14, 16, 3, 10], sum = 43 [0, 5, 6, 10] # values = [9, 15, 8, 15], sum = 47 ] """ assert process_time.ndim == 1 num_tasks = process_time.size(0) if num_tasks % group_size != 0: raise NotImplementedError( f"num_tasks {num_tasks} must be divisible by group_size {group_size}" ) device = process_time.device _, sorted_indices_descending = torch.sort( process_time, descending=True, stable=True ) # if process time is tied, the order is preserved sorted_indices_descending_reversed = torch.flip( sorted_indices_descending.view(-1, group_size), dims=[1] ).view(-1) tasks_in_group = torch.where( torch.arange(num_tasks, device=device) // group_size % 2 == 0, sorted_indices_descending, sorted_indices_descending_reversed, ) tasks_in_group = tasks_in_group.view(-1, group_size).transpose( 0, 1 ) # (group_size, n // group_size) # sort each group. This step should not have impact on correctness # nor execution run time, but it helps users visualize the mask tasks_in_group, _ = torch.sort(tasks_in_group, dim=1) return tasks_in_group def _generate_indices(self, restore: bool = False) -> Tensor: """ Generate the PTRR reorder indices of shape `(1, seq_len)` or `(batch_size, seq_len)`. Args: restore: If True, generate restore indices that map Processing-Time based Round-Robin (PTRR) rearranged positions back to original positions. If False, generate load balance indices that rearrange original positions to PTRR pattern. Returns: The generated indices of shape `(1, seq_len)` if the load-balancing is identical within the batch (i.e. `BlockMask.shape[0] == 1`), or `(batch_size, seq_len)` if the load-balancing should vary within the batch. Warning: For Multi-Head Attention, we require the masks over the head dimension are identical (i.e. `self.block_mask` must have shape (B, 1, seq_len, seq_len) or (1, 1, seq_len, seq_len)). Example: Here is the document causal mask for attention whereq_len == kv_len == 16 * BLOCK_SIZE (each entry is a block): KV_index [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1 [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2 [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3 [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4 [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1 [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2 [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3 Q_index [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4 [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] -> row value = 5 [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0] -> row value = 6 [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] -> row value = 7 [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] -> row value = 8 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] -> row value = 1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] -> row value = 2 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0] -> row value = 3 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] -> row value = 4 The reorder indices will be: [2, 3, 5, 6, 8, 11, 12, 13, 0, 1, 4, 7, 9, 10, 14, 15] and the mask matrix will look like: KV_index [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3 [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4 [0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2 [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 3 [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] -> row value = 5 rank 0 (sum=28) [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] -> row value = 8 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] -> row value = 1 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0] -> row value = 2 ------------------------------------------------ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1 [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 2 [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 1 [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] -> row value = 4 [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0] -> row value = 6 rank 1 (sum=28) [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] -> row value = 7 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0] -> row value = 3 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1] -> row value = 4 """ block_mask = self.block_mask kv_num_blocks = block_mask.kv_num_blocks full_kv_num_blocks = block_mask.full_kv_num_blocks non_sparse_kv_num_blocks = ( kv_num_blocks + full_kv_num_blocks if full_kv_num_blocks is not None else kv_num_blocks ) B, H, Q = non_sparse_kv_num_blocks.shape # requirement: the masking is identical across heads (i.e. H == 1 in BlockMask) non_sparse_kv_num_blocks = non_sparse_kv_num_blocks.view(-1, Q) # (B, Q_BLK) batch_ptrr = torch.vmap( functools.partial( _PTRRLoadBalancer.ptrr_scheduling, group_size=self.world_size, ) ) ptrr_indices = batch_ptrr( non_sparse_kv_num_blocks ) # (B, group_size, num_blks_in_group) ptrr_indices = ptrr_indices.reshape(B, -1) # (B, num_blocks) # NOTE: only support the case where the qkv block size are equal q_blk_size, kv_blk_size = block_mask.BLOCK_SIZE assert q_blk_size == kv_blk_size, ( "for now only support q_blk_size == kv_blk_size" ) indices = torch.arange( q_blk_size * ptrr_indices.size(1), device=ptrr_indices.device ).view(-1, q_blk_size) # (NUM_BLOCKS, BLOCK_SIZE) indices = indices[ptrr_indices].view(B, -1) # (B, qkv_size) if restore: indices = torch.vmap(torch.argsort)(indices) return indices def _create_default_load_balancer( seq_length: int, world_size: int, device: str | torch.device ) -> _LoadBalancer | None: from ._attention import _cp_options if _cp_options.enable_load_balance: return _HeadTailLoadBalancer(seq_length, world_size, device) else: return None
_PTRRLoadBalancer
python
ray-project__ray
python/ray/autoscaler/v2/instance_manager/subscribers/threaded_ray_installer.py
{ "start": 583, "end": 708 }
class ____: # Instance manager's instance id. im_instance_id: str # Error details. details: str
RayInstallError
python
pytest-dev__pluggy
src/pluggy/_hooks.py
{ "start": 12239, "end": 12732 }
class ____: """Hook holder object for performing 1:N hook calls where N is the number of registered plugins.""" __slots__ = ("__dict__",) def __init__(self) -> None: """:meta private:""" if TYPE_CHECKING: def __getattr__(self, name: str) -> HookCaller: ... # Historical name (pluggy<=1.2), kept for backward compatibility. _HookRelay = HookRelay _CallHistory: TypeAlias = list[ tuple[Mapping[str, object], Callable[[Any], None] | None] ]
HookRelay
python
apache__airflow
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/test_kubernetes_helper_functions.py
{ "start": 1339, "end": 2033 }
class ____: def __init__(self, exception=None): self.outcome = mock.Mock() if exception is not None else None if self.outcome: self.outcome.exception = mock.Mock(return_value=exception) def test_should_retry_api(): exc = HTTPError() assert _should_retry_api(exc) exc = KubernetesApiException() assert _should_retry_api(exc) exc = SyncApiException(status=500) assert _should_retry_api(exc) exc = AsyncApiException(status=500) assert _should_retry_api(exc) exc = SyncApiException(status=404) assert not _should_retry_api(exc) exc = AsyncApiException(status=404) assert not _should_retry_api(exc)
DummyRetryState
python
openai__openai-python
src/openai/resources/moderations.py
{ "start": 3835, "end": 6826 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModerationsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncModerationsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncModerationsWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncModerationsWithStreamingResponse(self) async def create( self, *, input: Union[str, SequenceNotStr[str], Iterable[ModerationMultiModalInputParam]], model: Union[str, ModerationModel] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> ModerationCreateResponse: """Classifies if text and/or image inputs are potentially harmful. Learn more in the [moderation guide](https://platform.openai.com/docs/guides/moderation). Args: input: Input (or inputs) to classify. Can be a single string, an array of strings, or an array of multi-modal input objects similar to other models. model: The content moderation model you would like to use. Learn more in [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about available models [here](https://platform.openai.com/docs/models#moderation). extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ return await self._post( "/moderations", body=await async_maybe_transform( { "input": input, "model": model, }, moderation_create_params.ModerationCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=ModerationCreateResponse, )
AsyncModerations
python
kubernetes-client__python
kubernetes/base/dynamic/exceptions.py
{ "start": 2795, "end": 2903 }
class ____(Exception): """ kubernetes-validate is not installed """ # HTTP Errors
KubernetesValidateMissing
python
getsentry__sentry
src/sentry/deletions/defaults/apigrant.py
{ "start": 213, "end": 861 }
class ____(ModelDeletionTask[ApiGrant]): """ Normally ApiGrants are deleted in bulk, but for cascades originating from sentry app installation, we wish to use the orm so that set null behavior functions correctly. Do not register this as the default, but instead use it as the task= parameter to a relation. """ def mark_deletion_in_progress(self, instance_list: Sequence[ApiGrant]) -> None: # no status to track pass def delete_instance(self, instance: ApiGrant) -> None: with unguarded_write(router.db_for_write(ApiGrant)): super().delete_instance(instance)
ModelApiGrantDeletionTask
python
getsentry__sentry
src/sentry/api/endpoints/organization_traces.py
{ "start": 4501, "end": 6638 }
class ____(OrganizationTracesEndpointBase): def get(self, request: Request, organization: Organization) -> Response: if not features.has( "organizations:performance-trace-explorer", organization, actor=request.user ) and not features.has( "organizations:visibility-explore-view", organization, actor=request.user ): return Response(status=404) try: snuba_params = self.get_snuba_params(request, organization) except NoProjects: return Response(status=404) buffer = options.get("performance.traces.trace-explorer-skip-recent-seconds") now = timezone.now() - timedelta(seconds=buffer) assert snuba_params.end is not None snuba_params.end = min(snuba_params.end, now) serializer = OrganizationTracesSerializer(data=request.GET) if not serializer.is_valid(): return Response(serializer.errors, status=400) serialized = serializer.validated_data with handle_query_errors(): executor = TracesExecutor( dataset=serialized["dataset"], snuba_params=snuba_params, user_queries=serialized.get("query", []), sort=serialized.get("sort"), limit=self.get_per_page(request), breakdown_slices=serialized["breakdownSlices"], get_all_projects=lambda: self.get_projects( request, organization, project_ids={-1}, project_slugs=None, include_all_accessible=True, ), ) return self.paginate( request=request, paginator=GenericOffsetPaginator(data_fn=executor.execute), on_results=lambda results: self.handle_results_with_meta( request, organization, snuba_params.project_ids, results, standard_meta=True, dataset=Dataset.SpansIndexed, ), )
OrganizationTracesEndpoint
python
doocs__leetcode
lcof/面试题06. 从尾到头打印链表/Solution2.py
{ "start": 136, "end": 347 }
class ____: def reversePrint(self, head: ListNode) -> List[int]: if head is None: return [] ans = self.reversePrint(head.next) ans.append(head.val) return ans
Solution
python
airbytehq__airbyte
airbyte-integrations/bases/base-normalization/normalization/transform_catalog/table_name_registry.py
{ "start": 2799, "end": 3632 }
class ____(Dict[str, List[NormalizedNameMetadata]]): """ An intermediate registry used by TableNameRegistry to detect conflicts in file names """ def __init__(self): super(NormalizedFilesRegistry, self).__init__() def add( self, intermediate_schema: str, schema: str, json_path: List[str], stream_name: str, table_name: str ) -> "NormalizedFilesRegistry": if table_name not in self: self[table_name] = [] self[table_name].append(NormalizedNameMetadata(intermediate_schema, schema, json_path, stream_name, table_name)) return self def get_value(self, table_name: str) -> List[NormalizedNameMetadata]: return self[table_name] def has_collisions(self, table_name: str) -> bool: return len(self[table_name]) > 1
NormalizedFilesRegistry
python
miyuchina__mistletoe
mistletoe/span_tokenizer.py
{ "start": 2638, "end": 3915 }
class ____: def __init__(self, start, end, match, string, cls, fallback_token): self.start = start self.end = end self.parse_start = match.start(cls.parse_group) self.parse_end = match.end(cls.parse_group) self.match = match self.string = string self.cls = cls self.fallback_token = fallback_token self.children = [] def append_child(self, child): if self.cls.parse_inner: if not self.children: self.children.append(child) else: eval_new_child(self, child) def make(self): if not self.cls.parse_inner: return self.cls(self.match) children = make_tokens(self.children, self.parse_start, self.parse_end, self.string, self.fallback_token) token = self.cls(self.match) token.children = children return token def __lt__(self, other): return self.start < other.start def __repr__(self): pattern = '<ParseToken span=({},{}) parse_span=({},{}) cls={} children={}>' return pattern.format(self.start, self.end, self.parse_start, self.parse_end, repr(self.cls.__name__), self.children)
ParseToken
python
sympy__sympy
sympy/tensor/tensor.py
{ "start": 97260, "end": 115777 }
class ____(TensExpr): """ Base tensor class, i.e. this represents a tensor, the single unit to be put into an expression. Explanation =========== This object is usually created from a ``TensorHead``, by attaching indices to it. Indices preceded by a minus sign are considered contravariant, otherwise covariant. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L") >>> mu, nu = tensor_indices('mu nu', Lorentz) >>> A = TensorHead("A", [Lorentz, Lorentz]) >>> A(mu, -nu) A(mu, -nu) >>> A(mu, -mu) A(L_0, -L_0) It is also possible to use symbols instead of inidices (appropriate indices are then generated automatically). >>> from sympy import Symbol >>> x = Symbol('x') >>> A(x, mu) A(x, mu) >>> A(x, -x) A(L_0, -L_0) """ is_commutative = False _index_structure: _IndexStructure args: tuple[TensorHead, Tuple] def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args): indices = cls._parse_indices(tensor_head, indices) obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args) obj._index_structure = _IndexStructure.from_indices(*indices) obj._free = obj._index_structure.free[:] obj._dum = obj._index_structure.dum[:] obj._ext_rank = obj._index_structure._ext_rank obj._coeff = S.One obj._nocoeff = obj obj._component = tensor_head obj._components = [tensor_head] if tensor_head.rank != len(indices): raise ValueError("wrong number of indices") obj.is_canon_bp = is_canon_bp obj._index_map = Tensor._build_index_map(indices, obj._index_structure) return obj @property def free(self): return self._free @property def dum(self): return self._dum @property def ext_rank(self): return self._ext_rank @property def coeff(self): return self._coeff @property def nocoeff(self): return self._nocoeff @property def component(self): return self._component @property def components(self): return self._components @property def head(self): return self.args[0] @property def indices(self): return self.args[1] @property def free_indices(self): return set(self._index_structure.get_free_indices()) @property def index_types(self): return self.head.index_types @property def rank(self): return len(self.free_indices) @staticmethod def _build_index_map(indices, index_structure): index_map = {} for idx in indices: index_map[idx] = (indices.index(idx),) return index_map def doit(self, **hints): args, indices, free, dum = TensMul._tensMul_contract_indices([self]) return args[0] @staticmethod def _parse_indices(tensor_head, indices): if not isinstance(indices, (tuple, list, Tuple)): raise TypeError(f"indices should be an array, got {type(indices)}") indices = list(indices) for i, index in enumerate(indices): if isinstance(index, Symbol): indices[i] = TensorIndex(index, tensor_head.index_types[i], True) elif isinstance(index, Mul): c, e = index.as_coeff_Mul() if c == -1 and isinstance(e, Symbol): indices[i] = TensorIndex(e, tensor_head.index_types[i], False) else: raise ValueError(f"index not understood: {index}") elif not isinstance(index, TensorIndex): raise TypeError(f"wrong type for index: {index} is {type(index)}") return indices def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit() def _get_free_indices_set(self): return {i[0] for i in self._index_structure.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self._index_structure.dum)) return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos} def _get_indices_set(self): return set(self.args[1].args) @property def free_in_args(self): return [(ind, pos, 0) for ind, pos in self.free] @property def dum_in_args(self): return [(p1, p2, 0, 0) for p1, p2 in self.dum] @property def free_args(self): return sorted([x[0] for x in self.free]) def commutes_with(self, other): """ :param other: :return: 0 commute 1 anticommute None neither commute nor anticommute """ if not isinstance(other, TensExpr): return 0 elif isinstance(other, Tensor): return self.component.commutes_with(other.component) return NotImplementedError def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g``. For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp) def canon_bp(self): if self.is_canon_bp: return self expr = self.expand() g, dummies, msym = expr._index_structure.indices_canon_args() v = components_canon_args([expr.component]) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tensor = self.perm2tensor(can, True) return tensor def split(self): return [self] def sorted_components(self): return self def get_indices(self) -> list[TensorIndex]: """ Get a list of indices, corresponding to those of the tensor. """ return list(self.args[1]) def get_free_indices(self) -> list[TensorIndex]: """ Get a list of free indices, corresponding to those of the tensor. """ return self._index_structure.get_free_indices() def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: # TODO: this could be optimized by only swapping the indices # instead of visiting the whole expression tree: return self.xreplace(repl) def as_base_exp(self): return self, S.One def substitute_indices(self, *index_tuples): """ Return a tensor with free indices substituted according to ``index_tuples``. ``index_types`` list of tuples ``(old_index, new_index)``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(i, k)*B(-k, -j); t A(i, L_0)*B(-L_0, -j) >>> t.substitute_indices((i, k),(-j, l)) A(k, L_0)*B(-L_0, l) """ indices = [] for index in self.indices: for ind_old, ind_new in index_tuples: if (index.name == ind_old.name and index.tensor_index_type == ind_old.tensor_index_type): if index.is_up == ind_old.is_up: indices.append(ind_new) else: indices.append(-ind_new) break else: indices.append(index) return self.head(*indices) def _get_symmetrized_forms(self): """ Return a list giving all possible permutations of self that are allowed by its symmetries. """ comp = self.component gens = comp.symmetry.generators rank = comp.rank old_perms = None new_perms = {self} while new_perms != old_perms: old_perms = new_perms.copy() for tens in old_perms: for gen in gens: inds = tens.get_indices() per = [gen.apply(i) for i in range(0,rank)] sign = (-1)**(gen.apply(rank) - rank) ind_map = dict(zip(inds, [inds[i] for i in per])) new_perms.add( sign * tens._replace_indices(ind_map) ) return new_perms def matches(self, expr, repl_dict=None, old=False): expr = sympify(expr) if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() #simple checks if self == expr: return repl_dict if not isinstance(expr, Tensor): return None if self.head != expr.head: return None #Now consider all index symmetries of expr, and see if any of them allow a match. for new_expr in expr._get_symmetrized_forms(): m = self._matches(new_expr, repl_dict, old=old) if m is not None: repl_dict.update(m) return repl_dict return None def _matches(self, expr, repl_dict=None, old=False): """ This does not account for index symmetries of expr """ expr = sympify(expr) if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() #simple checks if self == expr: return repl_dict if not isinstance(expr, Tensor): return None if self.head != expr.head: return None s_indices = self.get_indices() e_indices = expr.get_indices() if len(s_indices) != len(e_indices): return None for i in range(len(s_indices)): s_ind = s_indices[i] m = s_ind.matches(e_indices[i]) if m is None: return None elif -s_ind in repl_dict.keys() and -repl_dict[-s_ind] != m[s_ind]: return None else: repl_dict.update(m) return repl_dict def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t # TODO: put this into TensExpr? def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() # TODO: put this into TensExpr? def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _extract_data(self, replacement_dict): from .array import Array for k, v in replacement_dict.items(): if isinstance(k, Tensor) and k.args[0] == self.args[0]: other = k array = v break else: raise ValueError(f"{self} not found in {replacement_dict}") # TODO: inefficient, this should be done at root level only: replacement_dict = {k: Array(v) for k, v in replacement_dict.items()} array = Array(array) dum1 = self.dum dum2 = other.dum if len(dum2) > 0: for pair in dum2: # allow `dum2` if the contained values are also in `dum1`. if pair not in dum1: raise NotImplementedError(f"{other} with contractions is not implemented") # Remove elements in `dum2` from `dum1`: dum1 = [pair for pair in dum1 if pair not in dum2] if len(dum1) > 0: indices1 = self.get_indices() indices2 = other.get_indices() repl = {} for p1, p2 in dum1: repl[indices2[p2]] = -indices2[p1] for pos in (p1, p2): if indices1[pos].is_up ^ indices2[pos].is_up: metric = replacement_dict[indices1[pos].tensor_index_type] if indices1[pos].is_up: metric = _TensorDataLazyEvaluator.inverse_matrix(metric) array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2)) other = other.xreplace(repl).doit() array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2)) free_ind1 = self.get_free_indices() free_ind2 = other.get_free_indices() return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # TODO: check data compatibility with properties of tensor. with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] def _print(self): indices = [str(ind) for ind in self.indices] component = self.component if component.rank > 0: return (f"{component.name}({', '.join(indices)})") else: return (f"{component.name}") def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return S.One == other def _get_compar_comp(self): t = self.canon_bp() r = (t.coeff, tuple(t.components), \ tuple(sorted(t.free)), tuple(sorted(t.dum))) return r return _get_compar_comp(self) == _get_compar_comp(other) def contract_metric(self, g): # if metric is not the same, ignore this step: if self.component != g: return self # in case there are free components, do not perform anything: if len(self.free) != 0: return self #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError sign = S.One typ = g.index_types[0] if not antisym: # g(i, -i) sign = sign*typ.dim else: # g(i, -i) sign = sign*typ.dim dp0, dp1 = self.dum[0] if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign return sign def contract_delta(self, metric): return self.contract_metric(metric) def _eval_rewrite_as_Indexed(self, tens, indices, **kwargs): from sympy.tensor.indexed import Indexed # TODO: replace .args[0] with .name: index_symbols = [i.args[0] for i in self.get_indices()] expr = Indexed(tens.args[0], *index_symbols) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s: Tensor) -> Expr: if not isinstance(s, Tensor): return S.Zero else: # @a_i/@a_k = delta_i^k # @a_i/@a^k = g_ij delta^j_k # @a^i/@a^k = delta^i_k # @a^i/@a_k = g^ij delta_j^k # TODO: if there is no metric present, the derivative should be zero? if self.head != s.head: return S.Zero # if heads are the same, provide delta and/or metric products # for every free index pair in the appropriate tensor # assumed that the free indices are in proper order # A contravariante index in the derivative becomes covariant # after performing the derivative and vice versa kronecker_delta_list = [1] # not guarantee a correct index order for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())): if iself.tensor_index_type != iother.tensor_index_type: raise ValueError("index types not compatible") else: tensor_index_type = iself.tensor_index_type tensor_metric = tensor_index_type.metric dummy = TensorIndex("d_" + str(count), tensor_index_type, is_up=iself.is_up) if iself.is_up == iother.is_up: kroneckerdelta = tensor_index_type.delta(iself, -iother) else: kroneckerdelta = ( TensMul(tensor_metric(iself, dummy), tensor_index_type.delta(-dummy, -iother)) ) kronecker_delta_list.append(kroneckerdelta) return TensMul.fromiter(kronecker_delta_list).doit(deep=False) # doit necessary to rename dummy indices accordingly
Tensor
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/generic1.py
{ "start": 587, "end": 728 }
class ____(Generic[T]): # This should generate an error. x: Generic[T] def func3(x: type): if x is Generic: return
Class5
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/upath_io_manager.py
{ "start": 498, "end": 20014 }
class ____(IOManager): """Abstract IOManager base class compatible with local and cloud storage via `universal-pathlib` and `fsspec`. Features: - handles partitioned assets - handles loading a single upstream partition - handles loading multiple upstream partitions (with respect to :py:class:`PartitionMapping`) - supports loading multiple partitions concurrently with async `load_from_path` method - the `get_metadata` method can be customized to add additional metadata to the output - the `allow_missing_partitions` metadata value can be set to `True` to skip missing partitions (the default behavior is to raise an error) """ extension: Optional[str] = None # override in child class def __init__( self, base_path: Optional["UPath"] = None, ): from upath import UPath assert not self.extension or "." in self.extension self._base_path = base_path or UPath(".") @abstractmethod def dump_to_path(self, context: OutputContext, obj: Any, path: "UPath"): """Child classes should override this method to write the object to the filesystem.""" @abstractmethod def load_from_path(self, context: InputContext, path: "UPath") -> Any: """Child classes should override this method to load the object from the filesystem.""" def load_partitions(self, context: InputContext): """This method is responsible for loading partitions. The default implementation assumes that different partitions are stored as independent files. When loading a single partition, it will call `load_from_path` on it. When loading multiple partitions, it will invoke `load_from_path` multiple times over paths produced by `get_path_for_partition` method, and store the results in a dictionary with formatted partitions as keys. Sometimes, this is not desired. If the serialization format natively supports loading multiple partitions at once, this method should be overridden together with `get_path_for_partition`. hint: context.asset_partition_keys can be used to access the partitions to load. """ paths = self._get_paths_for_partitions(context) # paths for normal partitions backcompat_paths = self._get_multipartition_backcompat_paths( context ) # paths for multipartitions context.log.debug(f"Loading {len(context.asset_partition_keys)} partitions...") if len(context.asset_partition_keys) == 1: partition_key = context.asset_partition_keys[0] return self._load_partition_from_path( context, partition_key, paths[partition_key], backcompat_paths.get(partition_key) ) else: objs = {} for partition_key in context.asset_partition_keys: obj = self._load_partition_from_path( context, partition_key, paths[partition_key], backcompat_paths.get(partition_key), ) if obj is not None: # in case some partitions were skipped objs[partition_key] = obj return objs @property def fs(self) -> "AbstractFileSystem": """Utility function to get the IOManager filesystem. Returns: AbstractFileSystem: fsspec filesystem. """ # Deferred for import perf from fsspec.implementations.local import LocalFileSystem from upath import UPath if isinstance(self._base_path, UPath): return self._base_path.fs elif isinstance(self._base_path, Path): return LocalFileSystem() else: raise ValueError(f"Unsupported base_path type: {type(self._base_path)}") @property def storage_options(self) -> dict[str, Any]: """Utility function to get the fsspec storage_options which are often consumed by various I/O functions. Returns: Dict[str, Any]: fsspec storage_options. """ from upath import UPath if isinstance(self._base_path, UPath): return self._base_path._kwargs.copy() # noqa # pyright: ignore[reportAttributeAccessIssue] elif isinstance(self._base_path, Path): return {} else: raise ValueError(f"Unsupported base_path type: {type(self._base_path)}") def get_metadata( self, context: OutputContext, obj: Any, ) -> dict[str, MetadataValue]: """Child classes should override this method to add custom metadata to the outputs.""" return {} # Read/write operations on paths can generally be handled by methods on the # UPath class, but when the backend requires credentials, this isn't # always possible. Override these path_* methods to provide custom # implementations for targeting backends that require authentication. def unlink(self, path: "UPath") -> None: """Remove the file or object at the provided path.""" path.unlink() def path_exists(self, path: "UPath") -> bool: """Check if a file or object exists at the provided path.""" return path.exists() def make_directory(self, path: "UPath"): """Create a directory at the provided path. Override as a no-op if the target backend doesn't use directories. """ path.mkdir(parents=True, exist_ok=True) def has_output(self, context: OutputContext) -> bool: return self.path_exists(self._get_path(context)) def _with_extension(self, path: "UPath") -> "UPath": return path.with_suffix(path.suffix + self.extension) if self.extension else path def _get_path_without_extension(self, context: Union[InputContext, OutputContext]) -> "UPath": if context.has_asset_key: context_path = self.get_asset_relative_path(context) else: # we are dealing with an op output context_path = self.get_op_output_relative_path(context) return self._base_path.joinpath(context_path) def get_asset_relative_path(self, context: Union[InputContext, OutputContext]) -> "UPath": from upath import UPath # we are not using context.get_asset_identifier() because it already includes the partition_key return UPath(*context.asset_key.path) def get_op_output_relative_path(self, context: Union[InputContext, OutputContext]) -> "UPath": from upath import UPath return UPath(*context.get_identifier()) def get_loading_input_log_message(self, path: "UPath") -> str: return f"Loading file from: {path} using {self.__class__.__name__}..." def get_writing_output_log_message(self, path: "UPath") -> str: return f"Writing file at: {path} using {self.__class__.__name__}..." def get_loading_input_partition_log_message(self, path: "UPath", partition_key: str) -> str: return f"Loading partition {partition_key} from {path} using {self.__class__.__name__}..." def get_missing_partition_log_message(self, partition_key: str) -> str: return ( f"Couldn't load partition {partition_key} and skipped it " "because the input metadata includes allow_missing_partitions=True" ) def _get_path(self, context: Union[InputContext, OutputContext]) -> "UPath": """Returns the I/O path for a given context. Should not be used with partitions (use `_get_paths_for_partitions` instead). """ path = self._get_path_without_extension(context) return self._with_extension(path) def get_path_for_partition( self, context: Union[InputContext, OutputContext], path: "UPath", partition: str ) -> "UPath": """Override this method if you want to use a different partitioning scheme (for example, if the saving function handles partitioning instead). The extension will be added later. Args: context (Union[InputContext, OutputContext]): The context for the I/O operation. path (UPath): The path to the file or object. partition (str): slash-formatted partition/multipartition key Returns: UPath: The path to the file with the partition key appended. """ return path / partition def _get_paths_for_partitions( self, context: Union[InputContext, OutputContext] ) -> dict[str, "UPath"]: """Returns a dict of partition_keys into I/O paths for a given context.""" if not context.has_asset_partitions: raise TypeError( f"Detected {context.dagster_type.typing_type} input type " "but the asset is not partitioned" ) def _formatted_multipartitioned_path(partition_key: MultiPartitionKey) -> str: ordered_dimension_keys = [ key[1] for key in sorted(partition_key.keys_by_dimension.items(), key=lambda x: x[0]) ] return "/".join(ordered_dimension_keys) formatted_partition_keys = { partition_key: ( _formatted_multipartitioned_path(partition_key) if isinstance(partition_key, MultiPartitionKey) else partition_key ) for partition_key in context.asset_partition_keys } asset_path = self._get_path_without_extension(context) return { partition_key: self._with_extension( self.get_path_for_partition(context, asset_path, partition) ) for partition_key, partition in formatted_partition_keys.items() } def _get_multipartition_backcompat_paths( self, context: Union[InputContext, OutputContext] ) -> Mapping[str, "UPath"]: if not context.has_asset_partitions: raise TypeError( f"Detected {context.dagster_type.typing_type} input type " "but the asset is not partitioned" ) partition_keys = context.asset_partition_keys asset_path = self._get_path_without_extension(context) return { partition_key: self._with_extension(asset_path / partition_key) for partition_key in partition_keys if isinstance(partition_key, MultiPartitionKey) } def _load_single_input(self, path: "UPath", context: InputContext) -> Any: context.log.debug(self.get_loading_input_log_message(path)) obj = self.load_from_path(context=context, path=path) if asyncio.iscoroutine(obj): obj = asyncio.run(obj) return obj def _load_partition_from_path( self, context: InputContext, partition_key: str, path: "UPath", backcompat_path: Optional["UPath"] = None, ) -> Any: """1. Try to load the partition from the normal path. 2. If it was not found, try to load it from the backcompat path. 3. If allow_missing_partitions metadata is True, skip the partition if it was not found in any of the paths. Otherwise, raise an error. Args: context (InputContext): IOManager Input context partition_key (str): the partition key corresponding to the partition being loaded path (UPath): The path to the partition. backcompat_path (Optional[UPath]): The path to the partition in the backcompat location. These paths can be present in assets produced by very old Dagster versions (TODO: specify concrete version). Returns: Any: The object loaded from the partition. """ allow_missing_partitions = ( context.definition_metadata.get("allow_missing_partitions", False) if context.definition_metadata is not None else False ) try: context.log.debug(self.get_loading_input_partition_log_message(path, partition_key)) obj = self.load_from_path(context=context, path=path) return obj except FileNotFoundError as e: if backcompat_path is not None: try: obj = self.load_from_path(context=context, path=backcompat_path) context.log.debug( f"File not found at {path}. Loaded instead from backcompat path:" f" {backcompat_path}" ) return obj except FileNotFoundError: if allow_missing_partitions: context.log.warning(self.get_missing_partition_log_message(partition_key)) return None else: raise e if allow_missing_partitions: context.log.warning(self.get_missing_partition_log_message(partition_key)) return None else: raise e def load_partitions_async(self, context: InputContext): """Same as `load_partitions`, but for async.""" paths = self._get_paths_for_partitions(context) # paths for normal partitions backcompat_paths = self._get_multipartition_backcompat_paths( context ) # paths for multipartitions async def collect(): loop = asyncio.get_running_loop() tasks = [] for partition_key in context.asset_partition_keys: tasks.append( loop.create_task( self._load_partition_from_path( context, partition_key, paths[partition_key], backcompat_paths.get(partition_key), ) ) ) results = await asyncio.gather(*tasks, return_exceptions=True) # need to handle missing partitions here because exceptions don't get propagated from async calls allow_missing_partitions = ( context.definition_metadata.get("allow_missing_partitions", False) if context.definition_metadata is not None else False ) results_without_errors = [] found_errors = False for partition_key, result in zip(context.asset_partition_keys, results): if isinstance(result, FileNotFoundError): if allow_missing_partitions: context.log.warning(self.get_missing_partition_log_message(partition_key)) else: context.log.error(str(result)) found_errors = True elif isinstance(result, Exception): context.log.error(str(result)) found_errors = True else: results_without_errors.append(result) if found_errors: raise RuntimeError( f"{len(paths) - len(results_without_errors)} partitions could not be loaded" ) return results_without_errors awaited_objects = asyncio.get_event_loop().run_until_complete(collect()) return { partition_key: awaited_object for partition_key, awaited_object in zip(context.asset_partition_keys, awaited_objects) if awaited_object is not None } def _load_partitions(self, context: InputContext) -> dict[str, Any]: # load multiple partitions if not inspect.iscoroutinefunction(self.load_from_path): return self.load_partitions(context) else: # load_from_path returns a coroutine, so we need to await the results return self.load_partitions_async(context) def load_input(self, context: InputContext) -> Union[Any, dict[str, Any]]: # If no asset key, we are dealing with an op output which is always non-partitioned if not context.has_asset_key or not context.has_asset_partitions: path = self._get_path(context) return self._load_single_input(path, context) else: # we are loading asset partitions asset_partition_keys = context.asset_partition_keys if len(asset_partition_keys) == 0: return None else: return self._load_partitions(context) def _handle_transition_to_partitioned_asset(self, context: OutputContext, path: "UPath"): # if the asset was previously non-partitioned, path will be a file, when it should # be a directory for the partitioned asset. Delete the file, so that it can be made # into a directory # TODO: this might not be the case if the serialization format is already operating with directories # e.g. DeltaLake, zarr if path.exists() and path.is_file(): context.log.warn( f"Found file at {path} believed to correspond with previously non-partitioned version" f" of {context.asset_key}. Removing {path} and replacing with directory for partitioned data files." ) path.unlink(missing_ok=True) def handle_output(self, context: OutputContext, obj: Any): if context.has_asset_partitions: paths = self._get_paths_for_partitions(context) check.invariant( len(paths) == 1, f"The current IO manager {type(self)} does not support persisting an output" " associated with multiple partitions. This error is likely occurring because a" " backfill was launched using the 'single run' option. Instead, launch the" " backfill with a multi-run backfill policy. You can also avoid this error by" " opting out of IO managers entirely by setting the return type of your asset/op to `None`.", ) path = next(iter(paths.values())) self._handle_transition_to_partitioned_asset(context, path.parent) else: path = self._get_path(context) self.make_directory(path.parent) context.log.debug(self.get_writing_output_log_message(path)) self.dump_to_path(context=context, obj=obj, path=path) # Usually, when the value is None, it means that the user didn't intend to use an IO manager # at all, but ended up with one because they didn't set None as their return type # annotation. In these cases, seeing a "path" metadata value can be very confusing, because # often they're actually writing data to a different location within their op. We omit # the metadata when "obj is None", in order to avoid this confusion in the common case. # This comes at the cost of this metadata not being present in these edge cases. metadata = {"path": MetadataValue.path(str(path))} if obj is not None else {} custom_metadata = self.get_metadata(context=context, obj=obj) metadata.update(custom_metadata) # type: ignore context.add_output_metadata(metadata) def is_dict_type(type_obj) -> bool: if type_obj == dict: return True if hasattr(type_obj, "__origin__") and type_obj.__origin__ in (dict, dict, Mapping): return True return False
UPathIOManager
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_year.py
{ "start": 5171, "end": 7542 }
class ____: def test_misspecified(self): with pytest.raises(ValueError, match="Month must go from 1 to 12"): YearEnd(month=13) offset_cases = [] offset_cases.append( ( YearEnd(), { datetime(2008, 1, 1): datetime(2008, 12, 31), datetime(2008, 6, 30): datetime(2008, 12, 31), datetime(2008, 12, 31): datetime(2009, 12, 31), datetime(2005, 12, 30): datetime(2005, 12, 31), datetime(2005, 12, 31): datetime(2006, 12, 31), }, ) ) offset_cases.append( ( YearEnd(0), { datetime(2008, 1, 1): datetime(2008, 12, 31), datetime(2008, 6, 30): datetime(2008, 12, 31), datetime(2008, 12, 31): datetime(2008, 12, 31), datetime(2005, 12, 30): datetime(2005, 12, 31), }, ) ) offset_cases.append( ( YearEnd(-1), { datetime(2007, 1, 1): datetime(2006, 12, 31), datetime(2008, 6, 30): datetime(2007, 12, 31), datetime(2008, 12, 31): datetime(2007, 12, 31), datetime(2006, 12, 29): datetime(2005, 12, 31), datetime(2006, 12, 30): datetime(2005, 12, 31), datetime(2007, 1, 1): datetime(2006, 12, 31), }, ) ) offset_cases.append( ( YearEnd(-2), { datetime(2007, 1, 1): datetime(2005, 12, 31), datetime(2008, 6, 30): datetime(2006, 12, 31), datetime(2008, 12, 31): datetime(2006, 12, 31), }, ) ) @pytest.mark.parametrize("case", offset_cases) def test_offset(self, case): offset, cases = case for base, expected in cases.items(): assert_offset_equal(offset, base, expected) on_offset_cases = [ (YearEnd(), datetime(2007, 12, 31), True), (YearEnd(), datetime(2008, 1, 1), False), (YearEnd(), datetime(2006, 12, 31), True), (YearEnd(), datetime(2006, 12, 29), False), ] @pytest.mark.parametrize("case", on_offset_cases) def test_is_on_offset(self, case): offset, dt, expected = case assert_is_on_offset(offset, dt, expected)
TestYearEnd
python
huggingface__transformers
src/transformers/models/fsmt/modeling_fsmt.py
{ "start": 26099, "end": 32490 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim, num_heads, dropout=0.0, bias=True, encoder_decoder_attention=False, # otherwise self_attention layer_idx=None, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.scaling = self.head_dim**-0.5 self.layer_idx = layer_idx self.encoder_decoder_attention = encoder_decoder_attention self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.cache_key = "encoder_decoder" if self.encoder_decoder_attention else "self" def forward( self, query, key: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, layer_state: Optional[Cache] = None, attn_mask: Optional[Tensor] = None, output_attentions: Optional[bool] = False, cache_position: Optional[torch.Tensor] = None, ) -> tuple[Tensor, Optional[Tensor]]: """Input shape: Time(SeqLen) x Batch x Channel""" tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] if layer_state is not None: if isinstance(layer_state, EncoderDecoderCache): is_updated = layer_state.is_updated.get(self.layer_idx) if self.encoder_decoder_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache curr_past_key_values = layer_state.cross_attention_cache else: curr_past_key_values = layer_state.self_attention_cache else: curr_past_key_values = layer_state # NOTE: FSMT has format (seq_len, BS, model_dim) for inputs current_states = key if self.encoder_decoder_attention else query if self.encoder_decoder_attention and layer_state is not None and is_updated: # reuse k,v, cross_attentions key_states = curr_past_key_values.layers[self.layer_idx].keys value_states = curr_past_key_values.layers[self.layer_idx].values else: key_states = self.k_proj(current_states) value_states = self.v_proj(current_states) key_states = key_states.view(-1, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3) value_states = value_states.view(-1, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3) if layer_state is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not self.encoder_decoder_attention else None key_states, value_states = curr_past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls if self.encoder_decoder_attention: layer_state.is_updated[self.layer_idx] = True query_states = self.q_proj(query) * self.scaling # Reshape back to 3D tensors for `bmm` query_states = query_states.view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) key_states = key_states.reshape(bsz * self.num_heads, -1, self.head_dim) value_states = value_states.reshape(bsz * self.num_heads, -1, self.head_dim) assert key_states is not None src_len = key_states.size(1) attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) assert attn_weights.size() == (bsz * self.num_heads, tgt_len, src_len) if attn_mask is not None: attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_mask attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) # This is part of a workaround to get around fork/join parallelism not supporting Optional types. if key_padding_mask is not None and key_padding_mask.dim() == 0: key_padding_mask = None assert key_padding_mask is None or key_padding_mask.size()[:2] == ( bsz, src_len, ) if key_padding_mask is not None: # don't attend to padding symbols attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) reshaped = key_padding_mask.unsqueeze(1).unsqueeze(2) attn_weights = attn_weights.masked_fill(reshaped, torch.finfo(attn_weights.dtype).min) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) attn_weights = nn.functional.softmax(attn_weights, dim=-1) if output_attentions: # make sure that attn_weights are included in graph attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) else: attn_weights_reshaped = None attn_probs = nn.functional.dropout( attn_weights, p=self.dropout, training=self.training, ) assert value_states is not None attn_output = torch.bmm(attn_probs, value_states) assert attn_output.size() == (bsz * self.num_heads, tgt_len, self.head_dim) attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn_output = self.out_proj(attn_output) return attn_output, attn_weights_reshaped def fill_with_neg_inf(t): """FP16-compatible function that fills a input_ids with -inf.""" return t.float().fill_(torch.finfo(t.dtype).min).type_as(t) # Public API def _get_shape(t): return getattr(t, "shape", None) @auto_docstring
Attention
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/configure_warning/package.py
{ "start": 228, "end": 1001 }
class ____(AutotoolsPackage): """This package prints output that looks like an error during configure, but it actually installs successfully.""" homepage = "http://www.example.com" url = "http://www.example.com/configure-warning-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") parallel = False def autoreconf(self, spec, prefix): pass def configure(self, spec, prefix): print("foo: No such file or directory") return 0 def build(self, spec, prefix): pass def install(self, spec, prefix): # sanity_check_prefix requires something in the install directory # Test requires overriding the one provided by `AutotoolsPackage` mkdirp(prefix.bin)
ConfigureWarning
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/unit_tests/integration/test_media.py
{ "start": 2162, "end": 5431 }
class ____(TestCase): @staticmethod def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput: return read_output( config_builder=config_, stream_name=_STREAM_NAME, sync_mode=SyncMode.full_refresh, expecting_exception=expecting_exception, ) @HttpMocker() def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( get_account_request().build(), get_account_response(), ) http_mocker.get( _get_request().build(), _get_response().with_record(_record()).build(), ) output = self._read(config_=config()) assert len(output.records) == 1 @HttpMocker() def test_given_multiple_pages_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( get_account_request().build(), get_account_response(), ) http_mocker.get( _get_request().build(), _get_response().with_pagination().with_record(_record()).build(), ) next_media_url = _get_request().with_next_page_token(NEXT_PAGE_TOKEN).build() http_mocker.get( next_media_url, _get_response().with_record(_record()).with_record(_record()).build(), ) output = self._read(config_=config()) assert len(output.records) == 3 @HttpMocker() def test_when_read_then_datetime_fields_transformed(self, http_mocker: HttpMocker) -> None: created_time_field = "timestamp" input_datetime_value = "2024-01-01T00:00:00+0000" expected_datetime_value = "2024-01-01T00:00:00+00:00" http_mocker.get( get_account_request().build(), get_account_response(), ) http_mocker.get( _get_request().build(), _get_response().with_record(_record().with_field(FieldPath(created_time_field), input_datetime_value)).build(), ) output = self._read(config_=config()) assert len(output.records) == 1 assert output.records[0].record.data[created_time_field] == expected_datetime_value @HttpMocker() def test_given_one_page_has_children_field(self, http_mocker: HttpMocker) -> None: test = "children" http_mocker.get( get_account_request().build(), get_account_response(), ) http_mocker.get(_get_request().build(), HttpResponse(json.dumps(find_template(f"{_STREAM_NAME}_for_{test}", __file__)), 200)) for children_id in _CHILDREN_IDS: http_mocker.get( _get_children_request(children_id).build(), HttpResponse(json.dumps(find_template(f"{_STREAM_NAME}_children_for_{test}", __file__)), 200), ) output = self._read(config_=config()) assert len(output.records) == 1 children = output.records[0].record.data["children"] assert len(children) == 4 for child in children: assert "id" in child assert "ig_id" in child assert "media_type" in child assert "owner" in child
TestFullRefresh
python
huggingface__transformers
tests/models/mlcd/test_modeling_mlcd.py
{ "start": 1105, "end": 4063 }
class ____: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.initializer_range = initializer_range self.scope = scope # in MLCD, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) num_patches = (image_size // patch_size) ** 2 self.seq_length = num_patches + 1 def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) config = self.get_config() return config, pixel_values def get_config(self): return MLCDVisionConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values): model = MLCDVisionModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(pixel_values) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) image_size = (self.image_size, self.image_size) patch_size = (self.patch_size, self.patch_size) num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch
MLCDVisionModelTester
python
readthedocs__readthedocs.org
readthedocs/api/v3/mixins.py
{ "start": 4506, "end": 5557 }
class ____(NestedParentObjectMixin): """ Mixin to define queryset permissions for ViewSet only in one place. All APIv3 ViewSet should inherit this mixin, unless specific permissions required. In that case, a specific mixin for that case should be defined. .. note:: When using nested views, the ``NestedViewSetMixin`` should be used and should be before this mixin in the inheritance list. So it can properly filter the queryset based on the parent object. """ def has_admin_permission(self, user, project): # Use .only for small optimization admin_projects = self.admin_projects(user).only("id") if project in admin_projects: return True return False def admin_projects(self, user): return Project.objects.for_admin_user(user=user) def get_queryset(self): """Filter projects or related resources based on the permissions of the current user.""" return self.model.objects.api(user=self.request.user)
ProjectQuerySetMixin
python
PyCQA__pylint
tests/functional/u/unused/unused_import.py
{ "start": 2792, "end": 2862 }
class ____: def get_all_classes(self) -> "List[Bee]": pass
Bee
python
django__django
tests/expressions/models.py
{ "start": 92, "end": 278 }
class ____(models.Model): name = models.CharField(max_length=50) secretary = models.ForeignKey( "Employee", models.CASCADE, null=True, related_name="managers" )
Manager
python
pypa__setuptools
setuptools/_distutils/command/config.py
{ "start": 862, "end": 12724 }
class ____(Command): description = "prepare to build" user_options = [ ('compiler=', None, "specify the compiler type"), ('cc=', None, "specify the compiler executable"), ('include-dirs=', 'I', "list of directories to search for header files"), ('define=', 'D', "C preprocessor macros to define"), ('undef=', 'U', "C preprocessor macros to undefine"), ('libraries=', 'l', "external C libraries to link with"), ('library-dirs=', 'L', "directories to search for external C libraries"), ('noisy', None, "show every action (compile, link, run, ...) taken"), ( 'dump-source', None, "dump generated source files before attempting to compile them", ), ] # The three standard command methods: since the "config" command # does nothing by default, these are empty. def initialize_options(self): self.compiler = None self.cc = None self.include_dirs = None self.libraries = None self.library_dirs = None # maximal output for now self.noisy = 1 self.dump_source = 1 # list of temporary files generated along-the-way that we have # to clean at some point self.temp_files = [] def finalize_options(self): if self.include_dirs is None: self.include_dirs = self.distribution.include_dirs or [] elif isinstance(self.include_dirs, str): self.include_dirs = self.include_dirs.split(os.pathsep) if self.libraries is None: self.libraries = [] elif isinstance(self.libraries, str): self.libraries = [self.libraries] if self.library_dirs is None: self.library_dirs = [] elif isinstance(self.library_dirs, str): self.library_dirs = self.library_dirs.split(os.pathsep) def run(self): pass # Utility methods for actual "config" commands. The interfaces are # loosely based on Autoconf macros of similar names. Sub-classes # may use these freely. def _check_compiler(self): """Check that 'self.compiler' really is a CCompiler object; if not, make it one. """ if not isinstance(self.compiler, CCompiler): self.compiler = new_compiler( compiler=self.compiler, dry_run=self.dry_run, force=True ) customize_compiler(self.compiler) if self.include_dirs: self.compiler.set_include_dirs(self.include_dirs) if self.libraries: self.compiler.set_libraries(self.libraries) if self.library_dirs: self.compiler.set_library_dirs(self.library_dirs) def _gen_temp_sourcefile(self, body, headers, lang): filename = "_configtest" + LANG_EXT[lang] with open(filename, "w", encoding='utf-8') as file: if headers: for header in headers: file.write(f"#include <{header}>\n") file.write("\n") file.write(body) if body[-1] != "\n": file.write("\n") return filename def _preprocess(self, body, headers, include_dirs, lang): src = self._gen_temp_sourcefile(body, headers, lang) out = "_configtest.i" self.temp_files.extend([src, out]) self.compiler.preprocess(src, out, include_dirs=include_dirs) return (src, out) def _compile(self, body, headers, include_dirs, lang): src = self._gen_temp_sourcefile(body, headers, lang) if self.dump_source: dump_file(src, f"compiling '{src}':") (obj,) = self.compiler.object_filenames([src]) self.temp_files.extend([src, obj]) self.compiler.compile([src], include_dirs=include_dirs) return (src, obj) def _link(self, body, headers, include_dirs, libraries, library_dirs, lang): (src, obj) = self._compile(body, headers, include_dirs, lang) prog = os.path.splitext(os.path.basename(src))[0] self.compiler.link_executable( [obj], prog, libraries=libraries, library_dirs=library_dirs, target_lang=lang, ) if self.compiler.exe_extension is not None: prog = prog + self.compiler.exe_extension self.temp_files.append(prog) return (src, obj, prog) def _clean(self, *filenames): if not filenames: filenames = self.temp_files self.temp_files = [] log.info("removing: %s", ' '.join(filenames)) for filename in filenames: try: os.remove(filename) except OSError: pass # XXX these ignore the dry-run flag: what to do, what to do? even if # you want a dry-run build, you still need some sort of configuration # info. My inclination is to make it up to the real config command to # consult 'dry_run', and assume a default (minimal) configuration if # true. The problem with trying to do it here is that you'd have to # return either true or false from all the 'try' methods, neither of # which is correct. # XXX need access to the header search path and maybe default macros. def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"): """Construct a source file from 'body' (a string containing lines of C/C++ code) and 'headers' (a list of header files to include) and run it through the preprocessor. Return true if the preprocessor succeeded, false if there were any errors. ('body' probably isn't of much use, but what the heck.) """ self._check_compiler() ok = True try: self._preprocess(body, headers, include_dirs, lang) except CompileError: ok = False self._clean() return ok def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="c"): """Construct a source file (just like 'try_cpp()'), run it through the preprocessor, and return true if any line of the output matches 'pattern'. 'pattern' should either be a compiled regex object or a string containing a regex. If both 'body' and 'headers' are None, preprocesses an empty file -- which can be useful to determine the symbols the preprocessor and compiler set by default. """ self._check_compiler() src, out = self._preprocess(body, headers, include_dirs, lang) if isinstance(pattern, str): pattern = re.compile(pattern) with open(out, encoding='utf-8') as file: match = any(pattern.search(line) for line in file) self._clean() return match def try_compile(self, body, headers=None, include_dirs=None, lang="c"): """Try to compile a source file built from 'body' and 'headers'. Return true on success, false otherwise. """ self._check_compiler() try: self._compile(body, headers, include_dirs, lang) ok = True except CompileError: ok = False log.info(ok and "success!" or "failure.") self._clean() return ok def try_link( self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", ): """Try to compile and link a source file, built from 'body' and 'headers', to executable form. Return true on success, false otherwise. """ self._check_compiler() try: self._link(body, headers, include_dirs, libraries, library_dirs, lang) ok = True except (CompileError, LinkError): ok = False log.info(ok and "success!" or "failure.") self._clean() return ok def try_run( self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c", ): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ self._check_compiler() try: src, obj, exe = self._link( body, headers, include_dirs, libraries, library_dirs, lang ) self.spawn([exe]) ok = True except (CompileError, LinkError, DistutilsExecError): ok = False log.info(ok and "success!" or "failure.") self._clean() return ok # -- High-level methods -------------------------------------------- # (these are the ones that are actually likely to be useful # when implementing a real-world config command!) def check_func( self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, ): """Determine if function 'func' is available by constructing a source file that refers to 'func', and compiles and links it. If everything succeeds, returns true; otherwise returns false. The constructed source file starts out by including the header files listed in 'headers'. If 'decl' is true, it then declares 'func' (as "int func()"); you probably shouldn't supply 'headers' and set 'decl' true in the same call, or you might get errors about a conflicting declarations for 'func'. Finally, the constructed 'main()' function either references 'func' or (if 'call' is true) calls it. 'libraries' and 'library_dirs' are used when linking. """ self._check_compiler() body = [] if decl: body.append(f"int {func} ();") body.append("int main () {") if call: body.append(f" {func}();") else: body.append(f" {func};") body.append("}") body = "\n".join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_lib( self, library, library_dirs=None, headers=None, include_dirs=None, other_libraries: Sequence[str] = [], ): """Determine if 'library' is available to be linked against, without actually checking that any particular symbols are provided by it. 'headers' will be used in constructing the source file to be compiled, but the only effect of this is to check if all the header files listed are available. Any libraries listed in 'other_libraries' will be included in the link, in case 'library' has symbols that depend on other libraries. """ self._check_compiler() return self.try_link( "int main (void) { }", headers, include_dirs, [library] + list(other_libraries), library_dirs, ) def check_header(self, header, include_dirs=None, library_dirs=None, lang="c"): """Determine if the system header file named by 'header_file' exists and can be found by the preprocessor; return true if so, false otherwise. """ return self.try_cpp( body="/* No body */", headers=[header], include_dirs=include_dirs ) def dump_file(filename, head=None): """Dumps a file content into log.info. If head is not None, will be dumped before the file content. """ if head is None: log.info('%s', filename) else: log.info(head) log.info(pathlib.Path(filename).read_text(encoding='utf-8'))
config
python
euske__pdfminer
pdfminer/cmapdb.py
{ "start": 3356, "end": 3779 }
class ____(CMap): def add_code2cid(self, code, cid): assert isinstance(code, bytes) and isinstance(cid, int) d = self.code2cid for c in code[:-1]: c = ord(c) if c in d: d = d[c] else: t = {} d[c] = t d = t c = ord(code[-1]) d[c] = cid return ## FileUnicodeMap ##
FileCMap
python
getsentry__sentry
src/sentry/issues/issue_occurrence.py
{ "start": 1222, "end": 1654 }
class ____: name: str value: str # Whether to prioritise displaying this evidence to users over other issue evidence. Should # only be one important row per occurrence. important: bool def to_dict( self, ) -> IssueEvidenceData: return { "name": self.name, "value": self.value, "important": self.important, } @dataclass(frozen=True)
IssueEvidence
python
modin-project__modin
modin/core/computation/ops.py
{ "start": 13345, "end": 14737 }
class ____(Op): """ Hold a unary operator and its operands. Parameters ---------- op : str The token used to represent the operator. operand : Term or Op The Term or Op operand to the operator. Raises ------ ValueError * If no function associated with the passed operator token is found. """ def __init__(self, op: Literal["+", "-", "~", "not"], operand) -> None: super().__init__(op, (operand,)) self.operand = operand try: self.func = _unary_ops_dict[op] except KeyError as err: raise ValueError( f"Invalid unary operator {repr(op)}, valid operators are {UNARY_OPS_SYMS}" ) from err def __call__(self, env) -> MathCall: operand = self.operand(env) # error: Cannot call function of unknown type return self.func(operand) # type: ignore[operator] def __repr__(self) -> str: return pprint_thing(f"{self.op}({self.operand})") @property def return_type(self) -> np.dtype: operand = self.operand if operand.return_type == np.dtype("bool"): return np.dtype("bool") if isinstance(operand, Op) and ( operand.op in _cmp_ops_dict or operand.op in _bool_ops_dict ): return np.dtype("bool") return np.dtype("int")
UnaryOp
python
Textualize__textual
examples/dictionary.py
{ "start": 321, "end": 2464 }
class ____(App): """Searches a dictionary API as-you-type.""" CSS_PATH = "dictionary.tcss" results = getters.query_one("#results", Markdown) input = getters.query_one(Input) def compose(self) -> ComposeResult: yield Input(placeholder="Search for a word", id="dictionary-search") with VerticalScroll(id="results-container"): yield Markdown(id="results") async def on_input_changed(self, message: Input.Changed) -> None: """A coroutine to handle a text changed message.""" if message.value: self.lookup_word(message.value) else: # Clear the results await self.results.update("") @work(exclusive=True) async def lookup_word(self, word: str) -> None: """Looks up a word.""" url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}" async with httpx.AsyncClient() as client: response = await client.get(url) try: results = response.json() except Exception: self.results.update(response.text) return if word == self.input.value: markdown = self.make_word_markdown(results) self.results.update(markdown) def make_word_markdown(self, results: object) -> str: """Convert the results into markdown.""" lines = [] if isinstance(results, dict): lines.append(f"# {results['title']}") lines.append(results["message"]) elif isinstance(results, list): for result in results: lines.append(f"# {result['word']}") lines.append("") for meaning in result.get("meanings", []): lines.append(f"_{meaning['partOfSpeech']}_") lines.append("") for definition in meaning.get("definitions", []): lines.append(f" - {definition['definition']}") lines.append("---") return "\n".join(lines) if __name__ == "__main__": app = DictionaryApp() app.run()
DictionaryApp
python
faif__python-patterns
patterns/behavioral/catalog.py
{ "start": 2391, "end": 3419 }
class ____: """catalog of multiple class methods that are executed depending on an init parameter """ x1 = "x1" x2 = "x2" def __init__(self, param: str) -> None: # simple test to validate param value if param in self._class_method_choices: self.param = param else: raise ValueError(f"Invalid Value for Param: {param}") @classmethod def _class_method_1(cls) -> str: return f"Value {cls.x1}" @classmethod def _class_method_2(cls) -> str: return f"Value {cls.x2}" _class_method_choices = { "param_value_1": _class_method_1, "param_value_2": _class_method_2, } def main_method(self) -> str: """will execute either _class_method_1 or _class_method_2 depending on self.param value """ return self._class_method_choices[self.param].__get__(None, self.__class__)() # type: ignore # type ignore reason: https://github.com/python/mypy/issues/10206
CatalogClass
python
django__django
django/db/migrations/operations/models.py
{ "start": 35515, "end": 40703 }
class ____(IndexOperation): """Rename an index.""" category = OperationCategory.ALTERATION def __init__(self, model_name, new_name, old_name=None, old_fields=None): if not old_name and not old_fields: raise ValueError( "RenameIndex requires one of old_name and old_fields arguments to be " "set." ) if old_name and old_fields: raise ValueError( "RenameIndex.old_name and old_fields are mutually exclusive." ) self.model_name = model_name self.new_name = new_name self.old_name = old_name self.old_fields = old_fields @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "model_name": self.model_name, "new_name": self.new_name, } if self.old_name: kwargs["old_name"] = self.old_name if self.old_fields: kwargs["old_fields"] = self.old_fields return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): if self.old_fields: state.add_index( app_label, self.model_name_lower, models.Index(fields=self.old_fields, name=self.new_name), ) state.remove_model_options( app_label, self.model_name_lower, AlterIndexTogether.option_name, self.old_fields, ) else: state.rename_index( app_label, self.model_name_lower, self.old_name, self.new_name ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if not self.allow_migrate_model(schema_editor.connection.alias, model): return if self.old_fields: from_model = from_state.apps.get_model(app_label, self.model_name) columns = [ from_model._meta.get_field(field).column for field in self.old_fields ] matching_index_name = schema_editor._constraint_names( from_model, column_names=columns, index=True, unique=False, ) if len(matching_index_name) != 1: raise ValueError( "Found wrong number (%s) of indexes for %s(%s)." % ( len(matching_index_name), from_model._meta.db_table, ", ".join(columns), ) ) old_index = models.Index( fields=self.old_fields, name=matching_index_name[0], ) else: from_model_state = from_state.models[app_label, self.model_name_lower] old_index = from_model_state.get_index_by_name(self.old_name) # Don't alter when the index name is not changed. if old_index.name == self.new_name: return to_model_state = to_state.models[app_label, self.model_name_lower] new_index = to_model_state.get_index_by_name(self.new_name) schema_editor.rename_index(model, old_index, new_index) def database_backwards(self, app_label, schema_editor, from_state, to_state): if self.old_fields: # Backward operation with unnamed index is a no-op. return self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def describe(self): if self.old_name: return ( f"Rename index {self.old_name} on {self.model_name} to {self.new_name}" ) return ( f"Rename unnamed index for {self.old_fields} on {self.model_name} to " f"{self.new_name}" ) @property def migration_name_fragment(self): if self.old_name: return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) return "rename_%s_%s_%s" % ( self.model_name_lower, "_".join(self.old_fields), self.new_name_lower, ) def reduce(self, operation, app_label): if ( isinstance(operation, RenameIndex) and self.model_name_lower == operation.model_name_lower and operation.old_name and self.new_name_lower == operation.old_name_lower ): return [replace(self, new_name=operation.new_name)] return super().reduce(operation, app_label)
RenameIndex
python
huggingface__transformers
tests/models/t5/test_modeling_t5.py
{ "start": 84489, "end": 85942 }
class ____(unittest.TestCase): def build_model_and_check_forward_pass(self, **kwargs): tester = T5ModelTester(self, **kwargs) config, *inputs = tester.prepare_config_and_inputs() ( input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ) = inputs model = T5ForConditionalGeneration(config=config).to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, labels=lm_labels, ) # outputs = model(*inputs) assert len(outputs) == 4 assert outputs["logits"].size() == (tester.batch_size, tester.decoder_seq_length, tester.vocab_size) assert outputs["loss"].size() == () return model def test_small_decoder(self): # num_hidden_layers is passed to T5Config as num_layers model = self.build_model_and_check_forward_pass(decoder_layers=1, num_hidden_layers=2) assert len(model.encoder.block) == 2 assert len(model.decoder.block) == 1 def test_defaulting_to_symmetry(self): # num_hidden_layers is passed to T5Config as num_layers model = self.build_model_and_check_forward_pass(num_hidden_layers=2) assert len(model.decoder.block) == len(model.encoder.block) == 2
TestAsymmetricT5
python
google__jax
jax/_src/interpreters/mlir.py
{ "start": 31674, "end": 34496 }
class ____: """Per-rule context information for MLIR lowering.""" module_context: ModuleContext # Even though we assigned name_stack entries to each jaxpr equation during # tracing, we need to propagate name stacks during lowering as well because # lowering may effectively inline multiple jaxprs into a single HLO function. # For example, the body of a while loop needs the name stack of the enclosing # while instruction to be prepended when forming its HLO name. name_stack: source_info_util.NameStack traceback: xc.Traceback | None primitive: core.Primitive | None avals_in: Sequence[core.AbstractValue] avals_out: Any # Usually Sequence[core.AbstractValue], but sometimes None. tokens_in: TokenSet tokens_out: TokenSet | None # Mutable store for output containers # The values tobe used for the Literal constants, by id of the const. # This is used to implement passing along the constants that have been # hoisted as main function arguments down to where they are used. # See https://docs.jax.dev/en/latest/internals/constants.html const_lowering: dict[tuple[int, core.AbstractValue], IrValues] axis_size_env: dict[core.Var, ir.Value] | None = None # Dynamic axis sizes # The values for the dimension variables in same order as # module_context.shape_poly_state.dim_vars dim_var_values: Sequence[ir.Value] = () jaxpr_eqn_ctx: core.JaxprEqnContext | None = None # Override module_context.platforms if not None. Used during multi-platform # lowering, when in a scope with a subset of the module_context.platforms. platforms: Sequence[str] | None = None def set_tokens_out(self, tokens_out: TokenSet): assert self.tokens_out is None, 'Should only set `tokens_out` once.' self.tokens_out = tokens_out def replace(self, **kw): return dataclasses.replace(self, **kw) # pytype: disable=wrong-arg-types # dataclasses-replace-types def is_forward_compat(self) -> bool: """Returns true if the lowering parameters are in forward compatibility mode. """ lowering_parameters = self.module_context.lowering_parameters check_platforms: Sequence[str] = ( self.platforms or self.module_context.platforms ) force_forward_compat = any( p in xb.FORCE_FORWARD_COMPAT_LOWERING_PLATFORMS for p in check_platforms ) return ( lowering_parameters.for_export or force_forward_compat ) and not lowering_parameters.export_ignore_forward_compatibility if not MYPY: class LoweringRule(Protocol): def __call__(self, ctx: LoweringRuleContext, *args: ir.Value | Sequence[ir.Value], **kw) -> Sequence[ir.Value | Sequence[ir.Value]]: """Converts a JAX primitive invocation into MLIR.""" else: LoweringRule = Any @dataclasses.dataclass(frozen=True)
LoweringRuleContext
python
django-haystack__django-haystack
test_haystack/elasticsearch5_tests/test_backend.py
{ "start": 61797, "end": 65706 }
class ____(TestCase): def setUp(self): super().setUp() # Wipe it clean. clear_elasticsearch_index() # Stow. self.old_ui = connections["elasticsearch"].get_unified_index() self.ui = UnifiedIndex() self.smmi = Elasticsearch5FacetingMockSearchIndex() self.ui.build(indexes=[self.smmi]) connections["elasticsearch"]._index = self.ui self.sb = connections["elasticsearch"].get_backend() # Force the backend to rebuild the mapping each time. self.sb.existing_mapping = {} self.sb.setup() self.sample_objs = [] for i in range(1, 10): mock = AFourthMockModel() mock.id = i if i > 5: mock.editor = "George Taylor" else: mock.editor = "Perry White" if i % 2: mock.author = "Daniel Lindsley" else: mock.author = "Dan Watson" mock.pub_date = datetime.date(2013, 9, (i % 4) + 1) self.sample_objs.append(mock) def tearDown(self): connections["elasticsearch"]._index = self.old_ui super().tearDown() def test_facet(self): self.sb.update(self.smmi, self.sample_objs) counts = ( SearchQuerySet("elasticsearch") .facet("author") .facet("editor") .facet_counts() ) self.assertEqual( counts["fields"]["author"], [("Daniel Lindsley", 5), ("Dan Watson", 4)] ) self.assertEqual( counts["fields"]["editor"], [("Perry White", 5), ("George Taylor", 4)] ) counts = ( SearchQuerySet("elasticsearch") .filter(content="white") .facet("facet_field", order="reverse_count") .facet_counts() ) self.assertEqual( counts["fields"]["facet_field"], [("Dan Watson", 2), ("Daniel Lindsley", 3)] ) def test_multiple_narrow(self): self.sb.update(self.smmi, self.sample_objs) counts = ( SearchQuerySet("elasticsearch") .narrow('editor_exact:"Perry White"') .narrow('author_exact:"Daniel Lindsley"') .facet("author") .facet_counts() ) self.assertEqual(counts["fields"]["author"], [("Daniel Lindsley", 3)]) def test_narrow(self): self.sb.update(self.smmi, self.sample_objs) counts = ( SearchQuerySet("elasticsearch") .facet("author") .facet("editor") .narrow('editor_exact:"Perry White"') .facet_counts() ) self.assertEqual( counts["fields"]["author"], [("Daniel Lindsley", 3), ("Dan Watson", 2)] ) self.assertEqual(counts["fields"]["editor"], [("Perry White", 5)]) def test_date_facet(self): self.sb.update(self.smmi, self.sample_objs) start = datetime.date(2013, 9, 1) end = datetime.date(2013, 9, 30) # Facet by day counts = ( SearchQuerySet("elasticsearch") .date_facet("pub_date", start_date=start, end_date=end, gap_by="day") .facet_counts() ) self.assertEqual( counts["dates"]["pub_date"], [ (datetime.datetime(2013, 9, 1), 2), (datetime.datetime(2013, 9, 2), 3), (datetime.datetime(2013, 9, 3), 2), (datetime.datetime(2013, 9, 4), 2), ], ) # By month counts = ( SearchQuerySet("elasticsearch") .date_facet("pub_date", start_date=start, end_date=end, gap_by="month") .facet_counts() ) self.assertEqual( counts["dates"]["pub_date"], [(datetime.datetime(2013, 9, 1), 9)] )
Elasticsearch5FacetingTestCase
python
PrefectHQ__prefect
src/prefect/_internal/concurrency/cancellation.py
{ "start": 2350, "end": 3590 }
class ____(asyncio.CancelledError): # We want our `CancelledError` to be treated as a `BaseException` and defining it # here simplifies downstream logic that needs to know "which" cancelled error to # handle. pass def _get_thread_shield(thread: threading.Thread) -> ThreadShield: with _THREAD_SHIELDS_LOCK: if thread not in _THREAD_SHIELDS: _THREAD_SHIELDS[thread] = ThreadShield(thread) # Perform garbage collection for old threads for thread_ in tuple(_THREAD_SHIELDS.keys()): if not thread_.is_alive(): _THREAD_SHIELDS.pop(thread_) return _THREAD_SHIELDS[thread] @contextlib.contextmanager def shield(): """ Prevent code from within the scope from being cancelled. This guards against cancellation from alarm signals and injected exceptions as used in this module. If an event loop is running in the thread where this is called, it will be shielded from asynchronous cancellation as well. """ with ( anyio.CancelScope(shield=True) if get_running_loop() else contextlib.nullcontext() ): with _get_thread_shield(threading.current_thread()): yield
CancelledError
python
ray-project__ray
python/ray/autoscaler/_private/local/node_provider.py
{ "start": 6240, "end": 11806 }
class ____(NodeProvider): """NodeProvider for private/local clusters. `node_id` is overloaded to also be `node_ip` in this class. When `cluster_name` is provided, it manages a single cluster in a cluster specific state file. But when `cluster_name` is None, it manages multiple clusters in a unified state file that requires each node to be tagged with TAG_RAY_CLUSTER_NAME in create and non_terminated_nodes function calls to associate each node with the right cluster. The current use case of managing multiple clusters is by OnPremCoordinatorServer which receives node provider HTTP requests from CoordinatorSenderNodeProvider and uses LocalNodeProvider to get the responses. """ def __init__(self, provider_config, cluster_name): NodeProvider.__init__(self, provider_config, cluster_name) if cluster_name: lock_path = get_lock_path(cluster_name) state_path = get_state_path(cluster_name) self.state = ClusterState( lock_path, state_path, provider_config, ) self.use_coordinator = False else: # LocalNodeProvider with a coordinator server. self.state = OnPremCoordinatorState( "/tmp/coordinator.lock", "/tmp/coordinator.state", provider_config["list_of_node_ips"], ) self.use_coordinator = True def non_terminated_nodes(self, tag_filters): workers = self.state.get() matching_ips = [] for worker_ip, info in workers.items(): if info["state"] == "terminated": continue ok = True for k, v in tag_filters.items(): if info["tags"].get(k) != v: ok = False break if ok: matching_ips.append(worker_ip) return matching_ips def is_running(self, node_id): return self.state.get()[node_id]["state"] == "running" def is_terminated(self, node_id): return not self.is_running(node_id) def node_tags(self, node_id): return self.state.get()[node_id]["tags"] def external_ip(self, node_id): """Returns an external ip if the user has supplied one. Otherwise, use the same logic as internal_ip below. This can be used to call ray up from outside the network, for example if the Ray cluster exists in an AWS VPC and we're interacting with the cluster from a laptop (where using an internal_ip will not work). Useful for debugging the local node provider with cloud VMs.""" node_state = self.state.get()[node_id] ext_ip = node_state.get("external_ip") if ext_ip: return ext_ip else: return socket.gethostbyname(node_id) def internal_ip(self, node_id): return socket.gethostbyname(node_id) def set_node_tags(self, node_id, tags): with self.state.lock: with self.state.file_lock: info = self.state.get()[node_id] info["tags"].update(tags) self.state.put(node_id, info) def create_node(self, node_config, tags, count): """Creates min(count, currently available) nodes.""" node_type = tags[TAG_RAY_NODE_KIND] with self.state.lock: with self.state.file_lock: workers = self.state.get() for node_id, info in workers.items(): if info["state"] == "terminated" and ( self.use_coordinator or info["tags"][TAG_RAY_NODE_KIND] == node_type ): info["tags"] = tags info["state"] = "running" self.state.put(node_id, info) count = count - 1 if count == 0: return def terminate_node(self, node_id): workers = self.state.get() info = workers[node_id] info["state"] = "terminated" self.state.put(node_id, info) @staticmethod def bootstrap_config(cluster_config): return bootstrap_local(cluster_config) def record_local_head_state_if_needed(local_provider: LocalNodeProvider) -> None: """This function is called on the Ray head from StandardAutoscaler.reset to record the head node's own existence in the cluster state file. This is necessary because `provider.create_node` in `commands.get_or_create_head_node` records the head state on the cluster-launching machine but not on the head. """ head_ip = local_provider.provider_config["head_ip"] cluster_name = local_provider.cluster_name # If the head node is not marked as created in the cluster state file, if head_ip not in local_provider.non_terminated_nodes({}): # These tags are based on the ones in commands.get_or_create_head_node; # keep in sync. head_tags = { TAG_RAY_NODE_KIND: NODE_KIND_HEAD, TAG_RAY_USER_NODE_TYPE: LOCAL_CLUSTER_NODE_TYPE, TAG_RAY_NODE_NAME: "ray-{}-head".format(cluster_name), TAG_RAY_NODE_STATUS: STATUS_UP_TO_DATE, } # Mark the head node as created in the cluster state file. local_provider.create_node(node_config={}, tags=head_tags, count=1) assert head_ip in local_provider.non_terminated_nodes({})
LocalNodeProvider
python
pytorch__pytorch
test/dynamo/test_base_hop.py
{ "start": 798, "end": 1575 }
class ____(torch._dynamo.test_case.TestCase): # TODO: flip to False later, we're landing a refactor PR and don't want to merge conflict @torch._dynamo.config.patch(assume_static_by_default=True) def test_dynamo(self): def inner(x, y): return (x @ y).sin().cos() x = torch.randn(3, 3, requires_grad=True) y = torch.randn(3, 3, requires_grad=True) backend = EagerAndRecordGraphs() @torch.compile(backend=backend) def f(x, y): return invoke_quant_test(inner, x, y, scheme="nf4") out = f(x, y) self.assertEqual(out, inner(x, y)) assert len(backend.graphs) == 1 self.assertExpectedInline( normalize_graph(backend.graphs[0]), """\
BaseHOPTest
python
facelessuser__soupsieve
tests/test_level3/test_last_of_type.py
{ "start": 57, "end": 1980 }
class ____(util.TestCase): """Test last of type selectors.""" def test_last_of_type_at_middle(self): """Test last of type that is not the last sibling.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "p:last-of-type", ['10'], flags=util.HTML ) def test_last_of_type_at_end(self): """Test last of type that is the last sibling.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "span:last-of-type", ['11'], flags=util.HTML ) def test_any_last_of_type(self): """Test any last of type.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> <span id="6"></span> <p id="7"></p> <p id="8"></p> <p id="9"></p> <p id="10"></p> <span id="11"></span> </body> """ self.assert_selector( markup, "body :last-of-type", ['10', '11'], flags=util.HTML )
TestLastOfType
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_logging/LOG002.py
{ "start": 327, "end": 410 }
class ____: def getLogger(self): pass logging.getLogger(__file__)
logging
python
tensorflow__tensorflow
tensorflow/lite/tools/flatbuffer_utils_test.py
{ "start": 1107, "end": 3233 }
class ____(test_util.TensorFlowTestCase): def testWriteReadModel(self): # 1. SETUP # Define the initial model initial_model = test_utils.build_mock_model() # Define temporary files tmp_dir = self.get_temp_dir() model_filename = os.path.join(tmp_dir, 'model.tflite') # 2. INVOKE # Invoke the write_model and read_model functions flatbuffer_utils.write_model(initial_model, model_filename) final_model = flatbuffer_utils.read_model(model_filename) # 3. VALIDATE # Validate that the initial and final models are the same # Validate the description self.assertEqual(initial_model.description, final_model.description) # Validate the main subgraph's name, inputs, outputs, operators and tensors initial_subgraph = initial_model.subgraphs[0] final_subgraph = final_model.subgraphs[0] self.assertEqual(initial_subgraph.name, final_subgraph.name) for i in range(len(initial_subgraph.inputs)): self.assertEqual(initial_subgraph.inputs[i], final_subgraph.inputs[i]) for i in range(len(initial_subgraph.outputs)): self.assertEqual(initial_subgraph.outputs[i], final_subgraph.outputs[i]) for i in range(len(initial_subgraph.operators)): self.assertEqual(initial_subgraph.operators[i].opcodeIndex, final_subgraph.operators[i].opcodeIndex) initial_tensors = initial_subgraph.tensors final_tensors = final_subgraph.tensors for i in range(len(initial_tensors)): self.assertEqual(initial_tensors[i].name, final_tensors[i].name) self.assertEqual(initial_tensors[i].type, final_tensors[i].type) self.assertEqual(initial_tensors[i].buffer, final_tensors[i].buffer) for j in range(len(initial_tensors[i].shape)): self.assertEqual(initial_tensors[i].shape[j], final_tensors[i].shape[j]) # Validate the first valid buffer (index 0 is always None) initial_buffer = initial_model.buffers[1].data final_buffer = final_model.buffers[1].data for i in range(initial_buffer.size): self.assertEqual(initial_buffer.data[i], final_buffer.data[i])
WriteReadModelTest
python
sqlalchemy__sqlalchemy
test/ext/asyncio/test_session.py
{ "start": 34187, "end": 34252 }
class ____(AsyncSession): sync_session_class = _MySession
_MyAS
python
walkccc__LeetCode
solutions/2744. Find Maximum Number of String Pairs/2744.py
{ "start": 0, "end": 342 }
class ____: def maximumNumberOfStringPairs(self, words: list[str]) -> int: ans = 0 seen = [False] * (26 * 26) def val(c: str) -> int: return ord(c) - ord('a') for word in words: if seen[val(word[1]) * 26 + val(word[0])]: ans += 1 seen[val(word[0]) * 26 + val(word[1])] = True return ans
Solution
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-tidb/tests/test_property_graph_stores_tidb.py
{ "start": 455, "end": 2233 }
class ____(TestCase): @classmethod def setUp(self) -> None: try: get_store() except Exception: raise SkipTest("TiDB cluster is not available") self.e1 = EntityNode(name="e1", properties={"p1": "v1"}) self.e2 = EntityNode(name="e2") self.r = Relation(label="r", source_id=self.e1.id, target_id=self.e2.id) def test_add(self): g = get_store() g.upsert_nodes([self.e1, self.e2]) g.upsert_relations([self.r]) assert len(g.get_triplets(entity_names=["e1"])) == 1 assert len(g.get_triplets(entity_names=["e3"])) == 0 assert len(g.get_triplets(properties={"p1": "v1"})) == 1 assert len(g.get_triplets(properties={"p1": "v2"})) == 0 def test_delete_by_entity_names(self): g = get_store() g.upsert_nodes([self.e1, self.e2]) g.upsert_relations([self.r]) assert len(g.get_triplets(entity_names=["e1"])) == 1 g.delete(entity_names=["e1"]) assert len(g.get_triplets(entity_names=["e1"])) == 0 def test_delete_by_entity_properties(self): g = get_store() g.upsert_nodes([self.e1, self.e2]) g.upsert_relations([self.r]) assert len(g.get_triplets(entity_names=["e1"])) == 1 g.delete(properties={"p1": "not exist"}) assert len(g.get_triplets(entity_names=["e1"])) == 1 g.delete(properties={"p1": "v1"}) assert len(g.get_triplets(entity_names=["e1"])) == 0 def test_get(self): g = get_store() g.upsert_nodes([self.e1, self.e2]) assert len(g.get(ids=[self.e1.id])) == 1 assert len(g.get(ids=[self.e1.id, self.e2.id])) == 2 assert len(g.get(properties={"p1": "v1"})) == 1
TestTiDBPropertyGraphStore
python
tensorflow__tensorflow
tensorflow/core/tfrt/mlrt/kernel/testdata/gen_checkpoint.py
{ "start": 1399, "end": 2589 }
class ____(module.Module): """A toy module for testing checkpoing loading.""" def __init__(self): super().__init__() self.w = variables.Variable(constant_op.constant([1, 2, 3]), name='w') self.w1 = variables.Variable(constant_op.constant([4, 5, 6]), name='w1') self.w2 = variables.Variable(constant_op.constant([7, 8, 9]), name='w2') self.w3 = variables.Variable(constant_op.constant([10, 11, 12]), name='w3') @polymorphic_function.function( input_signature=[tensor.TensorSpec([None, 3], dtypes.int32, name='input')] ) def serving_default(self, x): dummy = x + self.w dummy = dummy + self.w1 dummy = dummy + self.w2 dummy = dummy + self.w3 return dummy def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') v2_compat.enable_v2_behavior() model = ToyModule() saved_model.save( model, _SAVED_MODEL_PATH.value, options=save_options.SaveOptions(save_debug_info=False), signatures={ 'serving_default': model.serving_default, }, ) logging.info('Saved model to: %s', _SAVED_MODEL_PATH.value) if __name__ == '__main__': app.run(main)
ToyModule
python
pytorch__pytorch
functorch/examples/compilation/linear_train.py
{ "start": 552, "end": 2156 }
class ____(nn.Module): def __init__(self, num_layers=3, features=100): super().__init__() mods = [] for _ in range(num_layers): mods.append(nn.Linear(features, features, bias=False)) self.mod = nn.Sequential(*mods) def forward(self, x): return (self.mod(x) ** 2).sum() batch_size = 16 features = 64 num_layers = 8 inp = torch.randn((batch_size, features)) mod = Foo(num_layers, features) jit_mod = torch.jit.script(mod) func_model, weights = make_functional(mod) lr = 1.0 def functional_step(x, weights): weights = [weight.detach().requires_grad_() for weight in weights] out = func_model(weights, x) out.backward() new_weights = [weight - lr * weight.grad for weight in weights] return out, new_weights optim = torch.optim.SGD( jit_mod.parameters(), lr=lr, momentum=0, dampening=0, weight_decay=0 ) def jit_step(x, weights): optim.zero_grad() loss = jit_mod(x) loss.backward() optim.step() return loss, None def train(train_step, weights): torch.manual_seed(16) train_step(inp, weights) begin = time.time() for itr in range(1000): loss, weights = train_step(torch.randn(batch_size, features), weights) if itr % 200 == 0: print(f"Loss at {itr}: {loss}") print("Time taken: ", time.time() - begin) print() grad_pt = functional_step grad_nnc = nnc_jit(functional_step) print("Starting PT training") train(grad_pt, weights) print("Starting NNC training") train(grad_nnc, weights) print("Starting JIT training") train(jit_step, None)
Foo
python
django__django
tests/admin_filters/tests.py
{ "start": 8787, "end": 8897 }
class ____(ModelAdmin): list_display = ["name", "department"] list_filter = ["department"]
EmployeeAdmin
python
Textualize__textual
tests/test_binding_inheritance.py
{ "start": 15983, "end": 16177 }
class ____( Static, can_focus=True, inherit_bindings=False ): """A widget that can receive focus but has no bindings and doesn't inherit bindings."""
FocusableWidgetWithNoBindingsNoInherit
python
urllib3__urllib3
test/with_dummyserver/test_socketlevel.py
{ "start": 12643, "end": 37202 }
class ____(SocketDummyServerTestCase): def test_recovery_when_server_closes_connection(self) -> None: # Does the pool work seamlessly if an open connection in the # connection pool gets hung up on by the server, then reaches # the front of the queue again? done_closing = Event() def socket_handler(listener: socket.socket) -> None: for i in 0, 1: sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) body = f"Response {int(i)}" sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # simulate a server timing out, closing socket done_closing.set() # let the test know it can proceed self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0) assert response.status == 200 assert response.data == b"Response 0" done_closing.wait() # wait until the socket in our pool gets closed response = pool.request("GET", "/", retries=0) assert response.status == 200 assert response.data == b"Response 1" def test_connection_refused(self) -> None: # Does the pool retry if there is no listener on the port? host, port = get_unreachable_address() with HTTPConnectionPool(host, port, maxsize=3, block=True) as http: with pytest.raises(MaxRetryError): http.request("GET", "/", retries=0, release_conn=False) assert http.pool is not None assert http.pool.qsize() == http.pool.maxsize def test_connection_read_timeout(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] while not sock.recv(65536).endswith(b"\r\n\r\n"): pass timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool( self.host, self.port, timeout=SHORT_TIMEOUT, retries=False, maxsize=3, block=True, ) as http: try: with pytest.raises(ReadTimeoutError): http.request("GET", "/", release_conn=False) finally: timed_out.set() assert http.pool is not None assert http.pool.qsize() == http.pool.maxsize def test_read_timeout_dont_retry_method_not_in_allowlist(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] sock.recv(65536) timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool( self.host, self.port, timeout=LONG_TIMEOUT, retries=True ) as pool: try: with pytest.raises(ReadTimeoutError): pool.request("POST", "/") finally: timed_out.set() def test_https_connection_read_timeout(self) -> None: """Handshake timeouts should fail with a Timeout""" timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] while not sock.recv(65536): pass timed_out.wait() sock.close() # first ReadTimeoutError due to SocketTimeout self._start_server(socket_handler) with HTTPSConnectionPool( self.host, self.port, timeout=LONG_TIMEOUT, retries=False ) as pool: try: with pytest.raises(ReadTimeoutError): pool.request("GET", "/") finally: timed_out.set() # second ReadTimeoutError due to errno with HTTPSConnectionPool(host=self.host): err = OSError() err.errno = errno.EAGAIN with pytest.raises(ReadTimeoutError): pool._raise_timeout(err, "", 0) def test_timeout_errors_cause_retries(self) -> None: def socket_handler(listener: socket.socket) -> None: sock_timeout = listener.accept()[0] # Wait for a second request before closing the first socket. sock = listener.accept()[0] sock_timeout.close() # Second request. buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # Now respond immediately. body = "Response 2" sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # In situations where the main thread throws an exception, the server # thread can hang on an accept() call. This ensures everything times # out within 1 second. This should be long enough for any socket # operations in the test suite to complete default_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(1) try: self._start_server(socket_handler) t = Timeout(connect=LONG_TIMEOUT, read=LONG_TIMEOUT) with HTTPConnectionPool(self.host, self.port, timeout=t) as pool: response = pool.request("GET", "/", retries=1) assert response.status == 200 assert response.data == b"Response 2" finally: socket.setdefaulttimeout(default_timeout) def test_delayed_body_read_timeout(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait() sock.send(body.encode("utf-8")) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=Timeout(connect=1, read=LONG_TIMEOUT), ) try: with pytest.raises(ReadTimeoutError): response.read() finally: timed_out.set() def test_delayed_body_read_timeout_with_preload(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait(5) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: try: with pytest.raises(ReadTimeoutError): timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) pool.urlopen("GET", "/", retries=False, timeout=timeout) finally: timed_out.set() def test_incomplete_response(self) -> None: body = "Response" partial_body = body[:2] def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) # Send partial response and close socket. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), partial_body) ).encode("utf-8") ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0, preload_content=False) with pytest.raises(ProtocolError): response.read() def test_retry_weird_http_version(self) -> None: """Retry class should handle httplib.BadStatusLine errors properly""" def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] # First request. # Pause before responding so the first request times out. buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # send unknown http protocol body = "bad http 0.5 response" sock.send( ( "HTTP/0.5 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # Second request. sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # Now respond immediately. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "foo" % (len("foo")) ).encode("utf-8") ) sock.close() # Close the socket. self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: retry = Retry(read=1) response = pool.request("GET", "/", retries=retry) assert response.status == 200 assert response.data == b"foo" def test_connection_cleanup_on_read_timeout(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: assert pool.pool is not None poolsize = pool.pool.qsize() response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) try: with pytest.raises(ReadTimeoutError): response.read() assert poolsize == pool.pool.qsize() finally: timed_out.set() def test_connection_cleanup_on_protocol_error_during_read(self) -> None: body = "Response" partial_body = body[:2] def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) # Send partial response and close socket. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), partial_body) ).encode("utf-8") ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: assert pool.pool is not None poolsize = pool.pool.qsize() response = pool.request("GET", "/", retries=0, preload_content=False) with pytest.raises(ProtocolError): response.read() assert poolsize == pool.pool.qsize() def test_connection_closed_on_read_timeout_preload_false(self) -> None: timed_out = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65535) # Send partial chunked response and then hang. sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Transfer-Encoding: chunked\r\n" b"\r\n" b"8\r\n" b"12345678\r\n" ) timed_out.wait(5) # Expect a new request, but keep hold of the old socket to avoid # leaking it. Because we don't want to hang this thread, we # actually use select.select to confirm that a new request is # coming in: this lets us time the thread out. rlist, _, _ = select.select([listener], [], [], 1) assert rlist new_sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = new_sock.recv(65535) # Send complete chunked response. new_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Transfer-Encoding: chunked\r\n" b"\r\n" b"8\r\n" b"12345678\r\n" b"0\r\n\r\n" ) new_sock.close() sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: # First request should fail. response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) try: with pytest.raises(ReadTimeoutError): response.read() finally: timed_out.set() # Second should succeed. response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) assert len(response.read()) == 8 def test_closing_response_actually_closes_connection(self) -> None: done_closing = Event() complete = Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 0\r\n" b"\r\n" ) # Wait for the socket to close. done_closing.wait(timeout=LONG_TIMEOUT) # Look for the empty string to show that the connection got closed. # Don't get stuck in a timeout. sock.settimeout(LONG_TIMEOUT) new_data = sock.recv(65536) assert not new_data sock.close() complete.set() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0, preload_content=False) assert response.status == 200 response.close() done_closing.set() # wait until the socket in our pool gets closed successful = complete.wait(timeout=LONG_TIMEOUT) assert successful, "Timed out waiting for connection close" def test_release_conn_param_is_respected_after_timeout_retry(self) -> None: """For successful ```urlopen(release_conn=False)```, the connection isn't released, even after a retry. This test allows a retry: one request fails, the next request succeeds. This is a regression test for issue #651 [1], where the connection would be released if the initial request failed, even if a retry succeeded. [1] <https://github.com/urllib3/urllib3/issues/651> """ def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] consume_socket(sock) # Close the connection, without sending any response (not even the # HTTP status line). This will trigger a `Timeout` on the client, # inside `urlopen()`. sock.close() # Expect a new request. Because we don't want to hang this thread, # we actually use select.select to confirm that a new request is # coming in: this lets us time the thread out. rlist, _, _ = select.select([listener], [], [], 5) assert rlist sock = listener.accept()[0] consume_socket(sock) # Send complete chunked response. sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Transfer-Encoding: chunked\r\n" b"\r\n" b"8\r\n" b"12345678\r\n" b"0\r\n\r\n" ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: # First request should fail, but the timeout and `retries=1` should # save it. response = pool.urlopen( "GET", "/", retries=1, release_conn=False, preload_content=False, timeout=LONG_TIMEOUT, ) # The connection should still be on the response object, and none # should be in the pool. We opened two though. assert pool.num_connections == 2 assert pool.pool is not None assert pool.pool.qsize() == 0 assert response.connection is not None # Consume the data. This should put the connection back. response.read() assert pool.pool.qsize() == 1 assert response.connection is None def test_socket_close_socket_then_file(self) -> None: quit_event = threading.Event() def consume_ssl_socket( listener: socket.socket, ) -> None: try: with ( listener.accept()[0] as sock, original_ssl_wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) as ssl_sock, ): consume_socket(ssl_sock, quit_event=quit_event) except (ConnectionResetError, ConnectionAbortedError, OSError): pass self._start_server(consume_ssl_socket, quit_event=quit_event) with ( socket.create_connection((self.host, self.port)) as sock, contextlib.closing( ssl_wrap_socket(sock, server_hostname=self.host, ca_certs=DEFAULT_CA) ) as ssl_sock, ssl_sock.makefile("rb") as f, ): ssl_sock.close() f.close() with pytest.raises(OSError): ssl_sock.sendall(b"hello") assert ssl_sock.fileno() == -1 def test_socket_close_stays_open_with_makefile_open(self) -> None: quit_event = threading.Event() def consume_ssl_socket(listener: socket.socket) -> None: try: with ( listener.accept()[0] as sock, original_ssl_wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) as ssl_sock, ): consume_socket(ssl_sock, quit_event=quit_event) except (ConnectionResetError, ConnectionAbortedError, OSError): pass self._start_server(consume_ssl_socket, quit_event=quit_event) with ( socket.create_connection((self.host, self.port)) as sock, contextlib.closing( ssl_wrap_socket(sock, server_hostname=self.host, ca_certs=DEFAULT_CA) ) as ssl_sock, ssl_sock.makefile("rb"), ): ssl_sock.close() ssl_sock.close() ssl_sock.sendall(b"hello") assert ssl_sock.fileno() > 0 def test_socket_shutdown_stops_recv(self) -> None: timed_out, starting_read = Event(), Event() def socket_handler(listener: socket.socket) -> None: sock = listener.accept()[0] ssl_sock = original_ssl_wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = ssl_sock.recv(65535) # Send incomplete message (note Content-Length) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 10\r\n" b"\r\n" b"Hi-" ) timed_out.wait(5) ssl_sock.close() self._start_server(socket_handler) class TestClient(threading.Thread): def __init__(self, host: str, port: int) -> None: super().__init__() self.host, self.port = host, port self.response: BaseHTTPResponse | None = None def run(self) -> None: with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as pool: self.response = pool.urlopen( "GET", "/", preload_content=False, retries=0 ) with pytest.raises(ProtocolError, match="Connection broken"): starting_read.set() self.response.read() test_client = TestClient(self.host, self.port) test_client.start() # First, wait to make sure the client is really stuck reading starting_read.wait(5) time.sleep(LONG_TIMEOUT) # Calling shutdown here calls shutdown() on the underlying socket, # so that the remaining read will fail instead of blocking # indefinitely assert test_client.response is not None test_client.response.shutdown() timed_out.set()
TestSocketClosing
python
kamyu104__LeetCode-Solutions
Python/cousins-in-binary-tree.py
{ "start": 191, "end": 1180 }
class ____(object): def isCousins(self, root, x, y): """ :type root: TreeNode :type x: int :type y: int :rtype: bool """ def dfs(root, x, depth, parent): if not root: return False if root.val == x: return True depth[0] += 1 prev_parent, parent[0] = parent[0], root if dfs(root.left, x, depth, parent): return True parent[0] = root if dfs(root.right, x, depth, parent): return True parent[0] = prev_parent depth[0] -= 1 return False depth_x, depth_y = [0], [0] parent_x, parent_y = [None], [None] return dfs(root, x, depth_x, parent_x) and \ dfs(root, y, depth_y, parent_y) and \ depth_x[0] == depth_y[0] and \ parent_x[0] != parent_y[0]
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-braintree/source_braintree/schemas/cards.py
{ "start": 2225, "end": 2426 }
class ____(CreditCard): """ https://developer.paypal.com/braintree/docs/reference/response/venmo-account """ source_description: str username: str venmo_user_id: str
VenmoAccount
python
hynek__structlog
tests/test_stdlib.py
{ "start": 20496, "end": 25593 }
class ____: def test_default(self, stdlib_logger: logging.Logger): """ Passes `event` key from `event_dict` in the first positional argument and handles otherwise empty `event_dict`. """ method_name = "debug" event = "message" args, kwargs = render_to_log_args_and_kwargs( stdlib_logger, method_name, {"event": event} ) assert (event,) == args assert {} == kwargs with patch.object(stdlib_logger, "_log") as mock_log: getattr(stdlib_logger, method_name)(*args, **kwargs) mock_log.assert_called_once_with(logging.DEBUG, event, ()) def test_pass_remaining_event_dict_as_extra( self, stdlib_logger: logging.Logger, event_dict: dict[str, Any] ): """ Passes remaining `event_dict` as `extra`. """ expected_extra = event_dict.copy() method_name = "info" event = "message" event_dict["event"] = event args, kwargs = render_to_log_args_and_kwargs( stdlib_logger, method_name, event_dict ) assert (event,) == args assert {"extra": expected_extra} == kwargs with patch.object(stdlib_logger, "_log") as mock_log: getattr(stdlib_logger, method_name)(*args, **kwargs) mock_log.assert_called_once_with( logging.INFO, event, (), extra=expected_extra ) def test_pass_positional_args_from_event_dict_as_args( self, stdlib_logger: logging.Logger, event_dict: dict[str, Any] ): """ Passes items from "positional_args" key from `event_dict` as positional arguments. """ expected_extra = event_dict.copy() method_name = "warning" event = "message: a = %s, b = %d" positional_args = ("foo", 123) event_dict["event"] = event event_dict["positional_args"] = positional_args args, kwargs = render_to_log_args_and_kwargs( stdlib_logger, method_name, event_dict ) assert (event, *(positional_args)) == args assert {"extra": expected_extra} == kwargs with patch.object(stdlib_logger, "_log") as mock_log: getattr(stdlib_logger, method_name)(*args, **kwargs) mock_log.assert_called_once_with( logging.WARNING, event, positional_args, extra=expected_extra ) def test_pass_kwargs_from_event_dict_as_kwargs( self, stdlib_logger: logging.Logger, event_dict: dict[str, Any] ): """ Passes "exc_info", "stack_info", and "stacklevel" keys from `event_dict` as keyword arguments. """ expected_extra = event_dict.copy() method_name = "info" event = "message" exc_info = True stack_info = False stacklevel = 2 event_dict["event"] = event event_dict["exc_info"] = exc_info event_dict["stack_info"] = stack_info event_dict["stacklevel"] = stacklevel args, kwargs = render_to_log_args_and_kwargs( stdlib_logger, method_name, event_dict ) assert (event,) == args assert { "exc_info": exc_info, "stack_info": stack_info, "stacklevel": stacklevel, "extra": expected_extra, } == kwargs with patch.object(stdlib_logger, "_log") as mock_log: getattr(stdlib_logger, method_name)(*args, **kwargs) mock_log.assert_called_once_with( logging.INFO, event, (), exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=expected_extra, ) def test_integration( self, stdlib_logger: logging.Logger, event_dict: dict[str, Any] ): """ `render_to_log_args_and_kwargs` with a wrapped logger calls the stdlib logger correctly. Reserved stdlib keyword arguments are in `logging.Logger._log`. https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Lib/logging/__init__.py#L1640 """ event = "message: a = %s, b = %d" arg_1 = "foo" arg_2 = 123 exc_info = False stack_info = True stacklevel = 3 struct_logger = wrap_logger( stdlib_logger, processors=[render_to_log_args_and_kwargs], wrapper_class=BoundLogger, ) with patch.object(stdlib_logger, "_log") as mock_log: struct_logger.info( event, arg_1, arg_2, exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, **event_dict, ) mock_log.assert_called_once_with( logging.INFO, event, (arg_1, arg_2), exc_info=exc_info, stack_info=stack_info, stacklevel=stacklevel, extra=event_dict, )
TestRenderToLogArgsAndKwargs
python
getsentry__sentry
src/sentry/preprod/api/endpoints/pull_request/organization_pullrequest_comments.py
{ "start": 1140, "end": 7801 }
class ____(OrganizationEndpoint): owner = ApiOwner.EMERGE_TOOLS publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } def get( self, request: Request, organization: Organization, repo_name: str, pr_number: str ) -> Response: """ Get GitHub comments for a Pull Request. Returns both general PR comments and file-specific review comments. **Path Parameters:** - `repo_name`: Repository name (e.g., 'owner/repo') - `pr_number`: Pull request number **Example:** ``` GET /projects/sentry/pr-comments/getsentry/sentry/12345/ ``` """ analytics.record( PreprodApiPrPageCommentsEvent( organization_id=organization.id, user_id=request.user.id, repo_name=repo_name, pr_number=pr_number, ) ) if not features.has("organizations:pr-page", organization, actor=request.user): return Response({"error": "Feature not enabled"}, status=403) client = get_github_client(organization, repo_name) if not client: logger.warning( "No GitHub client found for organization", extra={"organization_id": organization.id}, ) error_data = PullRequestCommentsErrorResponse( error="integration_not_found", message="No GitHub integration found for this repository", details="Unable to find a GitHub integration for the specified repository", ) return Response(error_data.dict(), status=404) try: general_comments_raw = self._fetch_pr_general_comments( organization.id, client, repo_name, pr_number ) review_comments_raw = self._fetch_pr_review_comments( organization.id, client, repo_name, pr_number ) # Parse general comments general_comments = [IssueComment.parse_obj(c) for c in general_comments_raw] # Parse and organize review comments by file path file_comments: dict[str, list[ReviewComment]] = {} for comment_data in review_comments_raw: if "path" not in comment_data: continue review_comment = ReviewComment.parse_obj(comment_data) file_path = review_comment.path if file_path not in file_comments: file_comments[file_path] = [] file_comments[file_path].append(review_comment) comments_data = PullRequestComments( general_comments=general_comments, file_comments=file_comments, ) logger.info( "Fetched PR comments from GitHub", extra={ "organization_id": organization.id, "repo_name": repo_name, "pr_number": pr_number, "general_comments_count": len(comments_data.general_comments), "review_comments_count": sum( len(comments) for comments in comments_data.file_comments.values() ), "files_with_comments": len(comments_data.file_comments), }, ) return Response(comments_data.dict(), status=200) except ApiError: logger.exception( "GitHub API error when fetching PR comments", extra={ "organization_id": organization.id, "repo_name": repo_name, "pr_number": pr_number, }, ) error_data = PullRequestCommentsErrorResponse( error="api_error", message="Failed to fetch pull request comments from GitHub", details="A problem occurred when communicating with GitHub. Please try again later.", ) return Response(error_data.dict(), status=502) except Exception: logger.exception( "Unexpected error fetching PR comments", extra={ "organization_id": organization.id, "repo_name": repo_name, "pr_number": pr_number, }, ) error_data = PullRequestCommentsErrorResponse( error="internal_error", message="An unexpected error occurred while fetching pull request comments", ) return Response(error_data.dict(), status=500) def _fetch_pr_general_comments( self, organization_id: int, client: GitHubApiClient, repo_name: str, pr_number: str, ) -> list[dict[str, Any]]: """ Fetch general PR comments from GitHub. These are the comments posted in the main PR conversation thread. """ with SCMIntegrationInteractionEvent( interaction_type=SCMIntegrationInteractionType.GET_ISSUE_COMMENTS, provider_key=IntegrationProviderSlug.GITHUB.value, # only Github for now organization_id=organization_id, integration_id=client.integration_id, ).capture() as lifecycle: lifecycle.add_extras( { "repo_name": repo_name, "pr_number": pr_number, } ) comments = client.get_issue_comments(repo_name, pr_number) return comments or [] def _fetch_pr_review_comments( self, organization_id: int, client: GitHubApiClient, repo_name: str, pr_number: str, ) -> list[dict[str, Any]]: """ Fetch PR review comments from GitHub. These are the comments posted on specific lines in file diffs during code review. """ with SCMIntegrationInteractionEvent( interaction_type=SCMIntegrationInteractionType.GET_PR_COMMENTS, provider_key=IntegrationProviderSlug.GITHUB.value, # only Github for now organization_id=organization_id, integration_id=client.integration_id, ).capture() as lifecycle: lifecycle.add_extras( { "repo_name": repo_name, "pr_number": pr_number, } ) comments = client.get_pullrequest_comments(repo_name, pr_number) return comments or []
OrganizationPrCommentsEndpoint
python
huggingface__transformers
src/transformers/models/ibert/modeling_ibert.py
{ "start": 20531, "end": 22436 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.quant_mode = config.quant_mode self.layer = nn.ModuleList([IBertLayer(config) for _ in range(config.num_hidden_layers)]) def forward( self, hidden_states, hidden_states_scaling_factor, attention_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = None # `config.add_cross_attention` is not supported for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, hidden_states_scaling_factor, attention_mask, output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, )
IBertEncoder
python
celery__celery
t/smoke/tests/quorum_queues/test_native_delayed_delivery.py
{ "start": 2944, "end": 3773 }
class ____: @pytest.fixture def default_worker_app(self, default_worker_app: Celery) -> Celery: app = default_worker_app app.conf.broker_transport_options = {"confirm_publish": True} app.conf.task_default_queue_type = "quorum" app.conf.broker_native_delayed_delivery_queue_type = 'classic' app.conf.task_default_exchange_type = 'topic' app.conf.task_default_routing_key = 'celery' return app def test_native_delayed_delivery_queue_configuration( self, queues: list, celery_setup: CeleryTestSetup ): queue_configuration_test_helper(celery_setup, queues) def test_native_delayed_delivery_exchange_configuration(self, exchanges: list): exchange_configuration_test_helper(exchanges)
test_broker_configuration_classic
python
marshmallow-code__marshmallow
examples/flask_example.py
{ "start": 826, "end": 1212 }
class ____(db.Model): # type: ignore[name-defined] id: Mapped[int] = mapped_column(primary_key=True) content: Mapped[str] = mapped_column(nullable=False) author_id: Mapped[int] = mapped_column(db.ForeignKey(Author.id)) author: Mapped[Author] = relationship(backref=db.backref("quotes", lazy="dynamic")) posted_at: Mapped[datetime.datetime] ##### SCHEMAS #####
Quote
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/llama_index/vector_stores/couchbase/base.py
{ "start": 24922, "end": 32786 }
class ____(CouchbaseVectorStoreBase): """ Couchbase Vector Store using Query Service with vector search capabilities. This implementation supports both Hyperscale Vector Indexes and Composite Vector Indexes, which use the Couchbase Query Service with SQL++ and vector search functions. Hyperscale Vector Indexes: - Purpose-built for pure vector searches at massive scale - Lowest memory footprint (most index data on disk) - Higher accuracy at lower quantizations - Best for content discovery, RAG workflows, image search, anomaly detection Composite Vector Indexes: - Combine Global Secondary Index (GSI) with vector search functions - Scalar filters applied BEFORE vector search (reduces vectors to compare) - Best for searches combining vector similarity with scalar filters - Useful for compliance requirements (can exclude results based on scalars) Key features: - Supports both ANN (Approximate) and KNN (Exact) nearest neighbor searches - Can scale to billions of documents - Various similarity metrics (COSINE, DOT, L2/EUCLIDEAN, L2_SQUARED) Requires Couchbase Server 8.0 or later. For more information, see: https://docs.couchbase.com/server/current/vector-index/use-vector-indexes.html """ _search_type: QueryVectorSearchType = PrivateAttr() _similarity: str = PrivateAttr() _query_timeout: timedelta = PrivateAttr() def __init__( self, cluster: Any, bucket_name: str, scope_name: str, collection_name: str, search_type: Union[QueryVectorSearchType, str], similarity: Union[QueryVectorSearchSimilarity, str], nprobes: Optional[int] = None, text_key: Optional[str] = "text", embedding_key: Optional[str] = "embedding", metadata_key: Optional[str] = "metadata", query_options: Optional[QueryOptions] = None, ) -> None: """ Initializes a connection to a Couchbase Vector Store using GSI. Args: cluster (Cluster): Couchbase cluster object with active connection. bucket_name (str): Name of bucket to store documents in. scope_name (str): Name of scope in the bucket to store documents in. collection_name (str): Name of collection in the scope to store documents in. search_type (Union[QueryVectorSearchType, str]): Type of vector search (ANN or KNN). Defaults to ANN. similarity (str): Similarity metric to use (cosine, euclidean, dot_product). Defaults to "cosine". nprobes (Optional[int], optional): Number of probes for the ANN search. Defaults to None, uses the value set at index creation time. text_key (Optional[str], optional): The field for the document text. Defaults to "text". embedding_key (Optional[str], optional): The field for the document embedding. Defaults to "embedding". metadata_key (Optional[str], optional): The field for the document metadata. Defaults to "metadata". query_options (Optional[QueryOptions]): Query options for SQL++ queries. Defaults to 60 seconds. Returns: None """ super().__init__( cluster=cluster, bucket_name=bucket_name, scope_name=scope_name, collection_name=collection_name, text_key=text_key, embedding_key=embedding_key, metadata_key=metadata_key, query_options=query_options, ) if isinstance(search_type, str): search_type = QueryVectorSearchType(search_type) self._search_type = search_type self._similarity = ( similarity.upper() if isinstance(similarity, str) else ( similarity.value if isinstance(similarity, QueryVectorSearchSimilarity) else None ) ) self._nprobes = nprobes def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult: """ Executes a vector similarity query using GSI. Args: query (VectorStoreQuery): The query object containing the search parameters. **kwargs (Any): Additional keyword arguments. Returns: VectorStoreQueryResult: The result of the query containing the top-k nodes, similarities, and ids. """ if not query.query_embedding: raise ValueError("Query embedding must not be empty") k = query.similarity_top_k query_context = ( f"`{self._bucket_name}`.`{self._scope_name}`.`{self._collection_name}`" ) # Convert embedding to string representation for query query_vector_str = str(query.query_embedding) # Handle filters if provided where_clause = "" if query.filters: try: # Convert LlamaIndex filters to SQL++ conditions filter_sql = _convert_llamaindex_filters_to_sql( query.filters, self._metadata_key ) if filter_sql: where_clause = f"WHERE {filter_sql}" except Exception as e: logger.warning(f"Failed to process filters: {e}") if query.output_fields: fields = query.output_fields.join(",") else: fields = "d.*, meta().id as id" nprobes = self._nprobes if kwargs.get("nprobes"): nprobes = kwargs.get("nprobes") # Determine the appropriate distance function based on search type if self._search_type == QueryVectorSearchType.ANN: nprobes_exp = f", {nprobes}" if nprobes else "" distance_function_exp = f"APPROX_VECTOR_DISTANCE(d.{self._embedding_key}, {query_vector_str}, '{self._similarity}'{nprobes_exp})" else: distance_function_exp = f"VECTOR_DISTANCE(d.{self._embedding_key}, {query_vector_str}, '{self._similarity}')" # Build the SQL++ query query_str = f""" SELECT {fields}, {distance_function_exp} as score FROM {query_context} d {where_clause} ORDER BY score LIMIT {k} """ try: # Execute the query result = self._cluster.query(query_str, self._query_options) top_k_nodes = [] top_k_scores = [] top_k_ids = [] # Process results for row in result.rows(): doc_id = row.get("id", "") text = row.get(self._text_key, "") score = row.get("score") # Extract metadata metadata_dict = {} if self._metadata_key in row: metadata_dict = row[self._metadata_key] try: node = metadata_dict_to_node(metadata_dict, text) node.node_id = doc_id except Exception: # Fallback for backwards compatibility node = TextNode( text=text, id_=doc_id, score=score, metadata=metadata_dict, ) top_k_nodes.append(node) top_k_scores.append(score) top_k_ids.append(doc_id) return VectorStoreQueryResult( nodes=top_k_nodes, similarities=top_k_scores, ids=top_k_ids ) except Exception as e: logger.error(f"Vector search failed: {e}") raise ValueError(f"Vector search failed with error: {e}")
CouchbaseQueryVectorStore
python
astropy__astropy
astropy/time/formats.py
{ "start": 80169, "end": 80314 }
class ____(TimeDeltaNumeric): """Time delta in SI seconds.""" name = "sec" unit = 1.0 / erfa.DAYSEC # for quantity input
TimeDeltaSec
python
pytorch__pytorch
test/test_foreach.py
{ "start": 2072, "end": 3671 }
class ____: def __init__(self, func): self.func = func # Some foreach functions don't have in-place implementations. self.is_inplace = False if func is None else func.__name__.endswith("_") def __call__(self, inputs, is_cuda, expect_fastpath, **kwargs): actual = None zero_size = kwargs.pop("zero_size", False) # Skip profiler check for CUDA 12.6, 12.8 as the upgrade makes profiler results flaky # https://github.com/pytorch/pytorch/issues/148681. TODO: ADD IT BACK!!! skip_profiler_check = _get_torch_cuda_version() in [(12, 6), (12, 8)] if ( is_cuda and not skip_profiler_check and torch.autograd.kineto_available() and torch.profiler.ProfilerActivity.CUDA in torch.profiler.supported_activities() ): with torch.profiler.profile() as p: actual = self.func(*inputs, **kwargs) # synchronize within the profiler context to make sure events happen before exiting torch.cuda.synchronize() keys = tuple([e.key for e in p.key_averages()]) mta_called = any("multi_tensor_apply_kernel" in k for k in keys) assert mta_called == (expect_fastpath and (not zero_size)), ( f"{mta_called=}, {expect_fastpath=}, {zero_size=}, {self.func.__name__=}, {keys=}" ) else: actual = self.func(*inputs, **kwargs) if self.is_inplace: assert id(inputs[0]) == id(actual) return actual
ForeachFuncWrapper
python
numpy__numpy
numpy/_core/tests/test_overrides.py
{ "start": 7273, "end": 8958 }
class ____: def test_pickle(self): for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): roundtripped = pickle.loads( pickle.dumps(dispatched_one_arg, protocol=proto)) assert_(roundtripped is dispatched_one_arg) def test_name_and_docstring(self): assert_equal(dispatched_one_arg.__name__, 'dispatched_one_arg') if sys.flags.optimize < 2: assert_equal(dispatched_one_arg.__doc__, 'Docstring.') def test_interface(self): class MyArray: def __array_function__(self, func, types, args, kwargs): return (self, func, types, args, kwargs) original = MyArray() (obj, func, types, args, kwargs) = dispatched_one_arg(original) assert_(obj is original) assert_(func is dispatched_one_arg) assert_equal(set(types), {MyArray}) # assert_equal uses the overloaded np.iscomplexobj() internally assert_(args == (original,)) assert_equal(kwargs, {}) def test_not_implemented(self): class MyArray: def __array_function__(self, func, types, args, kwargs): return NotImplemented array = MyArray() with assert_raises_regex(TypeError, 'no implementation found'): dispatched_one_arg(array) def test_where_dispatch(self): class DuckArray: def __array_function__(self, ufunc, method, *inputs, **kwargs): return "overridden" array = np.array(1) duck_array = DuckArray() result = np.std(array, where=duck_array) assert_equal(result, "overridden")
TestArrayFunctionDispatch
python
pytorch__pytorch
test/inductor/test_caching.py
{ "start": 43056, "end": 51984 }
class ____(TestMixin, TestCase): T = TypeVar("T") @contextmanager def executor(self) -> Generator[ThreadPoolExecutor, None, None]: executor: ThreadPoolExecutor = ThreadPoolExecutor() try: yield executor finally: executor.shutdown() def is_lock(self, lock_or_flock: Union[Lock, FileLock]) -> bool: return hasattr(lock_or_flock, "locked") def is_flock(self, lock_or_flock: Union[Lock, FileLock]) -> bool: return hasattr(lock_or_flock, "is_locked") def lock_or_flock_locked(self, lock_or_flock: Union[Lock, FileLock]) -> bool: if self.is_lock(lock_or_flock): return lock_or_flock.locked() elif self.is_flock(lock_or_flock): return lock_or_flock.is_locked else: raise NotImplementedError def test_BLOCKING(self) -> None: self.assertEqual(locks._BLOCKING, -1.0) def test_NON_BLOCKING(self) -> None: self.assertEqual(locks._NON_BLOCKING, 0.0) def test_BLOCKING_WITH_TIMEOUT(self) -> None: self.assertGreater(locks._BLOCKING_WITH_TIMEOUT, 0.0) @patch.object(locks, "_BLOCKING_WITH_TIMEOUT", 1.0) @patch.object(locks, "_DEFAULT_TIMEOUT", 1.0) @parametrize("lock_typename", ["Lock", "FileLock"]) @parametrize("lock_timeout", ["BLOCKING", "NON_BLOCKING", "BLOCKING_WITH_TIMEOUT"]) @parametrize("acquisition_mode", ["safe", "unsafe"]) @parametrize("release", ["unlocked", "never", "before_timeout", "after_timeout"]) def test_acquire_with_timeout( self, lock_typename: str, lock_timeout: str, acquisition_mode: str, release: str, ) -> None: """Test lock acquisition behavior with various timeout configurations and release scenarios. This comprehensive test verifies the lock acquisition functionality for both threading.Lock and FileLock objects across different timeout modes, acquisition patterns, and release timings. The test validates proper exception handling, timeout behavior, and correct lock state management. Test parameters: - lock_typename: Tests both "Lock" (threading.Lock) and "FileLock" (filelock.FileLock) types - lock_timeout: Tests "BLOCKING", "NON_BLOCKING", and "BLOCKING_WITH_TIMEOUT" modes - acquisition_mode: Tests both "safe" (context manager) and "unsafe" (manual) acquisition - release: Tests "unlocked", "never", "before_timeout", and "after_timeout" scenarios The test ensures that: - Safe acquisition properly manages lock lifecycle through context managers - Unsafe acquisition requires manual release and behaves correctly - Timeout exceptions are raised appropriately for different timeout configurations - Lock states are correctly maintained throughout acquisition and release cycles - Different lock types (Lock vs FileLock) behave consistently with their respective APIs """ def inner(lock_or_flock: Union[Lock, FileLock], timeout: int) -> None: if self.is_lock(lock_or_flock): lock: Lock = lock_or_flock if acquisition_mode == "safe": with locks._acquire_lock_with_timeout(lock, timeout=timeout): self.assertTrue(self.lock_or_flock_locked(lock)) elif acquisition_mode == "unsafe": locks._unsafe_acquire_lock_with_timeout(lock, timeout=timeout) self.assertTrue(self.lock_or_flock_locked(lock)) lock.release() else: raise NotImplementedError elif self.is_flock(lock_or_flock): flock: FileLock = lock_or_flock if acquisition_mode == "safe": with locks._acquire_flock_with_timeout(flock, timeout=timeout): self.assertTrue(self.lock_or_flock_locked(flock)) elif acquisition_mode == "unsafe": locks._unsafe_acquire_flock_with_timeout(flock, timeout=timeout) self.assertTrue(self.lock_or_flock_locked(flock)) flock.release() else: raise NotImplementedError else: raise NotImplementedError self.assertFalse(self.lock_or_flock_locked(lock_or_flock)) assert lock_typename in ["Lock", "FileLock"] flock_fpath: Path = ( impls._OnDiskCacheImpl()._cache_dir / f"testing-locks-instance-{self.random_string}.lock" ) lock_or_flock: Union[Lock, FileLock] = ( Lock() if lock_typename == "Lock" else FileLock(str(flock_fpath)) ) lock_exception_type: type = ( exceptions.LockTimeoutError if lock_typename == "Lock" else exceptions.FileLockTimeoutError ) if release == "unlocked": self.assertFalse(self.lock_or_flock_locked(lock_or_flock)) elif release in ["never", "before_timeout", "after_timeout"]: self.assertTrue(lock_or_flock.acquire(timeout=locks._NON_BLOCKING)) self.assertTrue(self.lock_or_flock_locked(lock_or_flock)) else: raise NotImplementedError with self.executor() as executor: assert lock_timeout in ["BLOCKING", "NON_BLOCKING", "BLOCKING_WITH_TIMEOUT"] lock_or_flock_future: Future[None] = executor.submit( inner, lock_or_flock, timeout={ "BLOCKING": locks._BLOCKING, "NON_BLOCKING": locks._NON_BLOCKING, "BLOCKING_WITH_TIMEOUT": locks._BLOCKING_WITH_TIMEOUT, }[lock_timeout], ) if release == "unlocked": self.assertIsNone(lock_or_flock_future.result()) elif release == "never": wait([lock_or_flock_future], timeout=(locks._BLOCKING_WITH_TIMEOUT * 2)) if lock_timeout == "BLOCKING": with self.assertRaises(TimeoutError): lock_or_flock_future.result( timeout=locks._BLOCKING_WITH_TIMEOUT ) elif lock_timeout in ["NON_BLOCKING", "BLOCKING_WITH_TIMEOUT"]: with self.assertRaises(lock_exception_type): lock_or_flock_future.result() else: raise NotImplementedError lock_or_flock.release() elif release == "before_timeout": wait([lock_or_flock_future], timeout=(locks._BLOCKING_WITH_TIMEOUT / 2)) lock_or_flock.release() if lock_timeout in ["BLOCKING", "BLOCKING_WITH_TIMEOUT"]: self.assertIsNone(lock_or_flock_future.result()) elif lock_timeout == "NON_BLOCKING": with self.assertRaises(lock_exception_type): lock_or_flock_future.result() else: raise NotImplementedError elif release == "after_timeout": wait([lock_or_flock_future], timeout=(locks._BLOCKING_WITH_TIMEOUT * 2)) lock_or_flock.release() if lock_timeout == "BLOCKING": self.assertIsNone(lock_or_flock_future.result()) elif lock_timeout in ["NON_BLOCKING", "BLOCKING_WITH_TIMEOUT"]: with self.assertRaises(lock_exception_type): lock_or_flock_future.result() else: raise NotImplementedError flock_fpath.unlink(missing_ok=True) @patch.object(locks, "_BLOCKING_WITH_TIMEOUT", 1) @patch.object(locks, "_DEFAULT_TIMEOUT", 1) @parametrize( "impl_typename_combos", list(combinations(TestMixin.impl_typenames, 1)) + list(combinations(TestMixin.impl_typenames, 2)), ) def test_acquire_many_impl_locks_with_timeout( self, impl_typename_combos: tuple[str, ...], ) -> None: impls: list[impls._CacheImpl] = [] for impl_typename in impl_typename_combos: impl: impls._CacheImpl = self.impl_from_typename(impl_typename) impls.append(impl) with locks._acquire_many_impl_locks_with_timeout(*impls): for impl in impls: if hasattr(impl, "_lock"): self.assertTrue(impl._lock.locked()) elif hasattr(impl, "_flock"): self.assertTrue(impl._flock.is_locked) for impl in impls: if hasattr(impl, "_lock"): self.assertFalse(impl._lock.locked()) elif hasattr(impl, "_flock"): self.assertFalse(impl._flock.is_locked) @instantiate_parametrized_tests
LocksTest
python
walkccc__LeetCode
solutions/3427. Sum of Variable Length Subarrays/3427.py
{ "start": 0, "end": 225 }
class ____: def subarraySum(self, nums: list[int]) -> int: prefix = list(itertools.accumulate(nums, initial=0)) return sum(prefix[i + 1] - prefix[max(0, i - num)] for i, num in enumerate((nums)))
Solution
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/softmax_test.py
{ "start": 1475, "end": 1749 }
class ____(op_bench.TorchBenchmarkBase): def init(self, N, C, H, W, device, op_func): self.inputs = {"input": torch.rand(N, C, H, W, device=device)} self.op_func = op_func() def forward(self, input): return self.op_func(input)
SoftmaxBenchmark
python
gevent__gevent
src/greentest/3.10/test_signal.py
{ "start": 47608, "end": 48919 }
class ____(unittest.TestCase): def test_sigint(self): with self.assertRaises(KeyboardInterrupt): signal.raise_signal(signal.SIGINT) @unittest.skipIf(sys.platform != "win32", "Windows specific test") def test_invalid_argument(self): try: SIGHUP = 1 # not supported on win32 signal.raise_signal(SIGHUP) self.fail("OSError (Invalid argument) expected") except OSError as e: if e.errno == errno.EINVAL: pass else: raise def test_handler(self): is_ok = False def handler(a, b): nonlocal is_ok is_ok = True old_signal = signal.signal(signal.SIGINT, handler) self.addCleanup(signal.signal, signal.SIGINT, old_signal) signal.raise_signal(signal.SIGINT) self.assertTrue(is_ok) def test__thread_interrupt_main(self): # See https://github.com/python/cpython/issues/102397 code = """if 1: import _thread class Foo(): def __del__(self): _thread.interrupt_main() x = Foo() """ rc, out, err = assert_python_ok('-c', code) self.assertIn(b'OSError: Signal 2 ignored due to race condition', err)
RaiseSignalTest
python
getsentry__sentry
tests/sentry/runner/commands/test_cleanup.py
{ "start": 958, "end": 5062 }
class ____(TestCase): def test_no_filters(self) -> None: """Test that without filters, all active projects are included.""" project1 = self.create_project() project2 = self.create_project() project3 = self.create_project() query, _ = prepare_deletes_by_project(is_filtered=lambda model: False) assert query is not None project_ids = list(query.values_list("id", flat=True)) # We sort the project IDs since the query set is unordered. # Adding an order would be useless since the query from prepare_deletes_by_project is used # by RangeQuerySetWrapper, which ignores order_by. assert sorted(project_ids) == [project1.id, project2.id, project3.id] def test_with_specific_project(self) -> None: """Test that when a specific project is provided, only that project is included.""" project1 = self.create_project() self.create_project() query, _ = prepare_deletes_by_project( project_id=project1.id, is_filtered=lambda model: False ) assert query is not None project_ids = list(query.values_list("id", flat=True)) assert sorted(project_ids) == [project1.id] def test_with_start_from_id(self) -> None: """Test that when start_from_project_id is provided, projects >= that ID are included.""" # Create projects in specific order self.create_project() project2 = self.create_project() project3 = self.create_project() query, _ = prepare_deletes_by_project( start_from_project_id=project2.id, is_filtered=lambda model: False, ) assert query is not None project_ids = list(query.values_list("id", flat=True)) assert sorted(project_ids) == [project2.id, project3.id] def test_specific_project_overrides_start_from(self) -> None: """Test that specific project_id takes precedence over start_from_project_id.""" project1 = self.create_project() project2 = self.create_project() query, _ = prepare_deletes_by_project( project_id=project1.id, start_from_project_id=project2.id, # This should be ignored is_filtered=lambda model: False, ) assert query is not None project_ids = list(query.values_list("id", flat=True)) # Only project1 should be included, start_from_project_id is ignored assert sorted(project_ids) == [project1.id] def test_only_active_projects(self) -> None: """Test that only active projects are included.""" active_project = self.create_project() deleted_project = self.create_project() # Mark one project as deleted deleted_project.update(status=ObjectStatus.PENDING_DELETION) query, _ = prepare_deletes_by_project(is_filtered=lambda model: False) assert query is not None project_ids = list(query.values_list("id", flat=True)) assert sorted(project_ids) == [active_project.id] def test_control_silo_mode_returns_none(self) -> None: """Test that in CONTROL silo mode, the function returns None for query and empty list.""" self.create_project() with assume_test_silo_mode(SiloMode.CONTROL): query, to_delete = prepare_deletes_by_project(is_filtered=lambda model: False) assert query is None assert to_delete == [] def test_region_silo_mode_returns_projects(self) -> None: """Test that in REGION silo mode, the function returns projects as expected.""" project1 = self.create_project() project2 = self.create_project() with assume_test_silo_mode(SiloMode.REGION): query, to_delete = prepare_deletes_by_project(is_filtered=lambda model: False) assert query is not None project_ids = list(query.values_list("id", flat=True)) assert sorted(project_ids) == [project1.id, project2.id] # Should have model tuples to delete assert len(to_delete) > 0
PrepareDeletesByProjectTest
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py
{ "start": 23756, "end": 33926 }
class ____: def __init__(self, path_prefix: Optional[str]) -> None: self.path_prefix = path_prefix self.errors: list[_DgConfigErrorRecord] = [] def validate(self, raw_dict: dict[str, Any]) -> DgConfigValidationResult: self._normalize_deprecated_settings(raw_dict) self._validate_file_config_setting( raw_dict, "directory_type", Required[Literal["workspace", "project"]], ) self._validate_dg_config_file_cli_section(raw_dict.get("cli", {})) directory_type = None if raw_dict.get("directory_type") == "workspace": self._validate_file_config_workspace_section(raw_dict.get("workspace", {})) self._validate_file_config_no_extraneous_keys( set(DgWorkspaceFileConfig.__annotations__.keys()), raw_dict, None ) directory_type = raw_dict["directory_type"] elif raw_dict.get("directory_type") == "project": self._validate_file_config_project_section(raw_dict.get("project", {})) self._validate_file_config_no_extraneous_keys( set(DgProjectFileConfig.__annotations__.keys()), raw_dict, None ) directory_type = raw_dict["directory_type"] return DgConfigValidationResult( raw_config=raw_dict, type=directory_type, errors=self.errors, ) def _normalize_deprecated_settings(self, raw_dict: dict[str, Any]) -> None: """Normalize deprecated settings to the new format.""" # We have to separately extract the warning suppression list since we haven't validated the # config yet. cli_section = raw_dict.get("cli", {}) self._validate_file_config_setting( cli_section, "suppress_warnings", list[DgWarningIdentifier], "cli" ) suppress_warnings = cast( "list[DgWarningIdentifier]", cli_section.get("suppress_warnings", []) ) if has_toml_node(raw_dict, ("project", "python_environment")): full_key = self._get_full_key("project.python_environment") msg = textwrap.dedent(f""" Setting `{full_key}` is deprecated. This key can be removed. """).strip() emit_warning("deprecated_python_environment", msg, suppress_warnings) del raw_dict["project"]["python_environment"] def _validate_dg_config_file_cli_section(self, section: object) -> None: if not isinstance(section, dict): self._log_invalid_value_error("tool.dg.cli", get_type_str(dict), section) return for key, type_ in DgRawCliConfig.__annotations__.items(): self._validate_file_config_setting(section, key, type_, "cli") self._validate_file_config_no_extraneous_keys( set(DgRawCliConfig.__annotations__.keys()), section, "cli" ) def _validate_file_config_project_section(self, section: object) -> None: if not isinstance(section, dict): self._log_invalid_value_error("project", get_type_str(dict), section) return for key, type_ in DgRawProjectConfig.__annotations__.items(): self._validate_file_config_setting(section, key, type_, "project") self._validate_file_config_no_extraneous_keys( set(DgRawProjectConfig.__annotations__.keys()), section, "project" ) if "registry_modules" in section: for i, pattern in enumerate(section["registry_modules"]): if not is_valid_module_pattern(pattern): full_key = self._get_full_key(f"project.registry_modules[{i}]") self.errors.append( _DgConfigInvalidValueErrorRecord( key=full_key, expected_type_str="A pattern consisting of '.'-separated segments that are either valid Python identifiers or wildcards ('*').", value_str=str(pattern), ) ) def _validate_file_config_workspace_section(self, section: object) -> None: if not isinstance(section, dict): self._log_invalid_value_error("workspace", get_type_str(dict), section) return for key, type_ in DgRawWorkspaceConfig.__annotations__.items(): if key == "projects": if self._validate_file_config_setting(section, key, list, "workspace"): for i, spec in enumerate(section.get("projects") or []): self._validate_file_config_workspace_project_spec(spec, i) elif key == "scaffold_project_options": self._validate_file_config_workspace_scaffold_project_options( section.get("scaffold_project_options", {}) ) else: self._validate_file_config_setting(section, key, type_, "workspace") self._validate_file_config_no_extraneous_keys( set(DgRawWorkspaceConfig.__annotations__.keys()), section, "workspace" ) def _validate_file_config_workspace_project_spec(self, section: object, index: int) -> None: if not isinstance(section, dict): self._log_invalid_value_error( f"workspace.projects[{index}]", get_type_str(dict), section ) return for key, type_ in DgRawWorkspaceProjectSpec.__annotations__.items(): self._validate_file_config_setting(section, key, type_, f"workspace.projects[{index}]") self._validate_file_config_no_extraneous_keys( set(DgRawWorkspaceProjectSpec.__annotations__.keys()), section, f"workspace.projects[{index}]", ) def _validate_file_config_workspace_scaffold_project_options(self, section: object) -> None: if not isinstance(section, dict): self._log_invalid_value_error( "workspace.scaffold_project_options", get_type_str(dict), section ) return for key, type_ in DgRawWorkspaceNewProjectOptions.__annotations__.items(): self._validate_file_config_setting( section, key, type_, "workspace.scaffold_project_options" ) self._validate_file_config_no_extraneous_keys( set(DgRawWorkspaceNewProjectOptions.__annotations__.keys()), section, "workspace.scaffold_project_options", ) def _validate_file_config_no_extraneous_keys( self, valid_keys: set[str], section: Mapping[str, object], toml_path: Optional[str] ) -> None: extraneous_keys = [k for k in section.keys() if k not in valid_keys] parent_key = self._get_full_key(toml_path) for key in extraneous_keys: self.errors.append( _DgConfigUnrecognizedFieldErrorRecord(parent_key=parent_key, key=key) ) # expected_type Any to handle typing constructs (`Literal` etc) def _validate_file_config_setting( self, section: Mapping[str, object], key: str, type_: Any, path_prefix: Optional[str] = None, ) -> bool: origin = get_origin(type_) is_required = origin is Required class_ = type_ if origin not in (Required, NotRequired) else get_args(type_)[0] error_type: Optional[_DgConfigErrorType] = None if is_required and key not in section: error_type = "missing_required_field" if key in section and not match_type(section[key], class_): error_type = "invalid_value" if error_type: full_key = f"{path_prefix}.{key}" if path_prefix else key type_str = get_type_str(class_) if error_type == "missing_required_field": self._log_missing_required_field_error(full_key, type_str) if error_type == "invalid_value": self._log_invalid_value_error(full_key, type_str, section[key]) return False return True def _get_full_key(self, key: Optional[str]) -> str: if self.path_prefix: return f"{self.path_prefix}.{key}" if key else self.path_prefix return key if key else "<root>" def _log_missing_required_field_error(self, key: str, type_str: str) -> None: full_key = self._get_full_key(key) self.errors.append( _DgConfigMissingRequiredFieldErrorRecord( key=full_key, expected_type_str=type_str, ) ) def _log_invalid_value_error(self, key: str, type_str: str, value: object) -> None: full_key = self._get_full_key(key) self.errors.append( _DgConfigInvalidValueErrorRecord( key=full_key, expected_type_str=type_str, value_str=str(value), ) ) def raise_file_config_validation_error(message: str, file_path: Path) -> Never: exit_with_error( textwrap.dedent(f""" Errors found in configuration file at: {file_path} """) + "\n" + message, do_format=False, ) # expected_type Any to handle typing constructs (`Literal` etc) def get_type_str(t: Any) -> str: origin = get_origin(t) if origin is None: # It's a builtin or normal class if hasattr(t, "__name__"): return t.__name__ # e.g. 'int', 'bool' return str(t) # Fallback else: # It's a parametric type like list[str], Union[int, str], etc. args = get_args(t) arg_strs = sorted([get_type_str(a) for a in args]) if origin is Union: return " | ".join(arg_strs) if origin is Literal: arg_strs = [f'"{a}"' for a in arg_strs] return " | ".join(arg_strs) else: return f"{_get_origin_name(origin)}[{', '.join(arg_strs)}]" def _get_origin_name(origin: Any) -> str: if origin is Sequence: return "Sequence" # avoid the collections.abc prefix else: return origin.__name__
_DgConfigValidator
python
has2k1__plotnine
plotnine/scales/scale_xy.py
{ "start": 9933, "end": 10088 }
class ____(scale_y_continuous): """ Continuous y position symmetric logarithm transformed scale """ trans: TransUser = "symlog"
scale_y_symlog
python
Lightning-AI__lightning
tests/tests_pytorch/core/test_lightning_optimizer.py
{ "start": 9241, "end": 12560 }
class ____(Optimizer): def __init__(self, model): self._fwd_handles = [] self._bwd_handles = [] self.params = [] for _, mod in model.named_modules(): mod_class = mod.__class__.__name__ if mod_class != "Linear": continue handle = mod.register_forward_pre_hook(self._save_input) # save the inputs self._fwd_handles.append(handle) # collect forward-save-input hooks in list handle = mod.register_backward_hook(self._save_grad_output) # save the gradients self._bwd_handles.append(handle) # collect backward-save-grad hook in list # save the parameters params = [mod.weight] if mod.bias is not None: params.append(mod.bias) # save a param_group for each module d = {"params": params, "mod": mod, "layer_type": mod_class} self.params.append(d) super().__init__(self.params, {"lr": 0.01}) def _save_input(self, mod, i): """Saves input of layer.""" if mod.training: self.state[mod]["x"] = i[0] def _save_grad_output(self, mod, _, grad_output): """Saves grad on output of layer to grad is scaled with batch_size since gradient is spread over samples in mini batch.""" batch_size = grad_output[0].shape[0] if mod.training: self.state[mod]["grad"] = grad_output[0] * batch_size def step(self, closure=None): closure() for group in self.param_groups: _ = self.state[group["mod"]]["x"] _ = self.state[group["mod"]]["grad"] return True def test_lightning_optimizer_keeps_hooks(): model = BoringModel() optimizer = OptimizerWithHooks(model) lightning_optimizer = LightningOptimizer(optimizer) assert len(optimizer._fwd_handles) == 1 del lightning_optimizer assert len(optimizer._fwd_handles) == 1 def test_params_groups_and_state_are_accessible(tmp_path): class TestModel(BoringModel): def on_train_start(self): # Update the learning rate manually on the unwrapped optimizer assert not isinstance(self.trainer.optimizers[0], LightningOptimizer) self.trainer.optimizers[0].param_groups[0]["lr"] = 2.0 def training_step(self, batch, batch_idx): opt = self.optimizers() assert opt.param_groups[0]["lr"] == 2.0 loss = self.step(batch) self.__loss = loss return loss def configure_optimizers(self): return SGD(self.layer.parameters(), lr=0.1) def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure, **__): # check attributes are accessible assert all("lr" in pg for pg in optimizer.param_groups) assert optimizer.state is optimizer._optimizer.state assert optimizer.defaults is optimizer._optimizer.defaults loss = optimizer.step(closure=optimizer_closure) # the optimizer step still returns the loss assert loss == self.__loss model = TestModel() trainer = Trainer(max_epochs=1, default_root_dir=tmp_path, limit_train_batches=1, limit_val_batches=0) trainer.fit(model)
OptimizerWithHooks
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
{ "start": 53574, "end": 55946 }
class ____(GoogleCloudBaseOperator): """ Deletes a specific Memcached instance. Instance stops serving and data is deleted. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudMemorystoreMemcachedDeleteInstanceOperator` :param location: The location of the Cloud Memorystore instance (for example europe-west1) :param instance: The logical name of the Memcached instance in the customer project. :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform. """ template_fields: Sequence[str] = ( "location", "instance", "project_id", "retry", "timeout", "metadata", "gcp_conn_id", ) def __init__( self, location: str, instance: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", *args, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.location = location self.instance = instance self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id def execute(self, context: Context): hook = CloudMemorystoreMemcachedHook(gcp_conn_id=self.gcp_conn_id) hook.delete_instance( location=self.location, instance=self.instance, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, )
CloudMemorystoreMemcachedDeleteInstanceOperator
python
wireservice__csvkit
tests/test_utilities/test_csvlook.py
{ "start": 220, "end": 4937 }
class ____(CSVKitTestCase, EmptyFileTests): Utility = CSVLook def tearDown(self): config.set_option('truncation_chars', '…') def test_launch_new_instance(self): with patch.object(sys, 'argv', [self.Utility.__name__.lower(), 'examples/dummy.csv']): launch_new_instance() def test_runs(self): self.assertLines(['examples/test_utf8.csv'], [ '| foo | bar | baz |', '| --- | --- | --- |', '| 1 | 2 | 3 |', '| 4 | 5 | ʤ |', ]) def test_encoding(self): self.assertLines(['-e', 'latin1', 'examples/test_latin1.csv'], [ '| a | b | c |', '| - | - | - |', '| 1 | 2 | 3 |', '| 4 | 5 | © |', ]) def test_simple(self): self.assertLines(['examples/dummy3.csv'], [ '| a | b | c |', '| ---- | - | - |', '| True | 2 | 3 |', '| True | 4 | 5 |', ]) def test_no_blanks(self): self.assertLines(['examples/blanks.csv'], [ '| a | b | c | d | e | f |', '| - | - | - | - | - | - |', '| | | | | | |', ]) def test_blanks(self): self.assertLines(['--blanks', 'examples/blanks.csv'], [ '| a | b | c | d | e | f |', '| - | -- | --- | ---- | ---- | - |', '| | NA | N/A | NONE | NULL | . |', ]) def test_no_header_row(self): self.assertLines(['--no-header-row', 'examples/no_header_row3.csv'], [ '| a | b | c |', '| - | - | - |', '| 1 | 2 | 3 |', '| 4 | 5 | 6 |', ]) def test_unicode(self): self.assertLines(['examples/test_utf8.csv'], [ '| foo | bar | baz |', '| --- | --- | --- |', '| 1 | 2 | 3 |', '| 4 | 5 | ʤ |', ]) def test_unicode_bom(self): self.assertLines(['examples/test_utf8_bom.csv'], [ '| foo | bar | baz |', '| --- | --- | --- |', '| 1 | 2 | 3 |', '| 4 | 5 | ʤ |', ]) def test_linenumbers(self): self.assertLines(['--linenumbers', 'examples/dummy3.csv'], [ '| line_numbers | a | b | c |', '| ------------ | ---- | - | - |', '| 1 | True | 2 | 3 |', '| 2 | True | 4 | 5 |', ]) def test_no_inference(self): self.assertLines(['--no-inference', 'examples/dummy3.csv'], [ '| a | b | c |', '| - | - | - |', '| 1 | 2 | 3 |', '| 1 | 4 | 5 |', ]) def test_sniff_limit_no_limit(self): self.assertLines(['examples/sniff_limit.csv'], [ '| a | b | c |', '| ---- | - | - |', '| True | 2 | 3 |', ]) def test_sniff_limit_zero_limit(self): self.assertLines(['--snifflimit', '0', 'examples/sniff_limit.csv'], [ '| a;b;c |', '| ----- |', '| 1;2;3 |', ]) def test_max_rows(self): self.assertLines(['--max-rows', '0', 'examples/dummy.csv'], [ '| a | b | c |', '| - | - | - |', ]) def test_max_columns(self): self.assertLines(['--max-columns', '1', 'examples/dummy.csv'], [ '| a | ... |', '| ---- | --- |', '| True | ... |', ]) def test_max_column_width(self): self.assertLines(['--max-column-width', '1', 'examples/dummy.csv'], [ '| a | b | c |', '| ----- | - | - |', '| Tr... | 2 | 3 |', ]) def test_max_precision(self): self.assertLines(['--max-precision', '0', 'examples/test_precision.csv'], [ '| a |', '| -- |', '| 1… |', ]) def test_no_number_ellipsis(self): self.assertLines(['--no-number-ellipsis', 'examples/test_precision.csv'], [ '| a |', '| ----- |', '| 1.235 |', ]) def test_max_precision_no_number_ellipsis(self): self.assertLines(['--max-precision', '0', '--no-number-ellipsis', 'examples/test_precision.csv'], [ '| a |', '| - |', '| 1 |', ]) def test_stdin(self): input_file = io.BytesIO(b'a,b,c\n1,2,3\n4,5,6\n') with stdin_as_string(input_file): self.assertLines([], [ '| a | b | c |', '| - | - | - |', '| 1 | 2 | 3 |', '| 4 | 5 | 6 |', ]) input_file.close()
TestCSVLook
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_with.py
{ "start": 1460, "end": 1755 }
class ____(object): def __init__(self): self.yielded = False self.stopped = False @mock_contextmanager def mock_contextmanager_generator(): mock = MockResource() try: mock.yielded = True yield mock finally: mock.stopped = True
MockResource
python
bokeh__bokeh
tests/unit/bokeh/server/test_auth_provider.py
{ "start": 11540, "end": 12759 }
class ____(object): pass """ def test_load_auth_module() -> None: def func(filename: str): m = bsa.load_auth_module(filename) assert isinstance(m, ModuleType) assert [x for x in sorted(dir(m)) if not x.startswith("__")] == ['LoginHandler', 'get_login_url', 'logout_url'] with_file_contents(_source, func, suffix='.py') def test_probably_relative_url() -> None: assert bsa.probably_relative_url("httpabc") assert bsa.probably_relative_url("httpsabc") assert bsa.probably_relative_url("/abc") assert not bsa.probably_relative_url("http://abc") assert not bsa.probably_relative_url("https://abc") assert not bsa.probably_relative_url("//abc") #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
LoginHandler
python
getsentry__sentry
src/sentry/models/projectsdk.py
{ "start": 1086, "end": 7466 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Organization date_updated = models.DateTimeField(auto_now=True) project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE) event_type = BoundedIntegerField(choices=EventType.as_choices()) sdk_name = models.CharField() sdk_version = models.CharField() class Meta: unique_together = (("project", "event_type", "sdk_name"),) __repr__ = sane_repr("project", "event_type", "sdk_name", "sdk_version") @classmethod def get_lock_key(cls, project: Project, event_type: EventType, sdk_name: str) -> str: return f"lprojectsdk:{project.id}:{event_type.value}:{md5_text(sdk_name).hexdigest()}" @classmethod def get_cache_key(cls, project: Project, event_type: EventType, sdk_name: str) -> str: return f"projectsdk:{project.id}:{event_type.value}:{md5_text(sdk_name).hexdigest()}" @classmethod def update_with_newest_version_or_create( cls, project: Project, event_type: EventType, sdk_name: str, sdk_version: str, ) -> None: try: new_version = parse_version(sdk_version) except InvalidVersion: # non-semver sdk version, ignore and move on return None normalized_sdk_name = normalize_sdk_name(sdk_name) if normalized_sdk_name is None: logger.info("Unknown sdk name: %s", sdk_name) return None lock_key = cls.get_lock_key(project, event_type, normalized_sdk_name) lock = locks.get(lock_key, duration=10, name="projectsdk") # This can raise `sentry.utils.locking.UnableToAcquireLock` # that needs to be handled by the caller and handled # appropriately with retries if needed. with lock.acquire(): cls.__update_with_newest_version_or_create( project, event_type, normalized_sdk_name, sdk_version, new_version, ) @classmethod def __update_with_newest_version_or_create( cls, project: Project, event_type: EventType, sdk_name: str, sdk_version: str, new_version: Version, ) -> None: cache_key = cls.get_cache_key(project, event_type, sdk_name) with metrics.timer( "models.projectsdk.update_with_newest_version_or_create" ) as metrics_tags: project_sdk = cache.get(cache_key) if project_sdk is None: metrics_tags["cache_hit"] = "false" project_sdk, created = cls.objects.get_or_create( project=project, event_type=event_type.value, sdk_name=sdk_name, defaults={"sdk_version": sdk_version}, ) should_update_cache = True else: metrics_tags["cache_hit"] = "true" should_update_cache = False assert project_sdk is not None if sdk_version != project_sdk.sdk_version: try: old_version = parse_version(project_sdk.sdk_version) except InvalidVersion: # non-semver sdk version, always overwrite old_version = None if old_version is None or old_version < new_version: project_sdk.sdk_version = sdk_version project_sdk.save() should_update_cache = True if should_update_cache: cache.set(cache_key, project_sdk, 3600) LEGACY_SDK_NAMES: set[str] = { "sentry.javascript.serverless", } def normalize_sdk_name(sdk_name: str) -> str | None: sdk_index = get_sdk_index() # usually, the sdk names reported will match # exactly what's in the registry if sdk_name in sdk_index: return sdk_name # some legacy sdks are not present in the registry # and will not be backfilled, so check them here if sdk_name in LEGACY_SDK_NAMES: return sdk_name # some sdks suffix the name depending on the integrations # that are in use, so try to normalize it to the registry name parts = sdk_name.split(".", 2) if len(parts) < 2: # already in its normalized form return None # The name in the registry is just the first 2 parts of the # reported name joined by a `.` sdk_name = ".".join(parts[:2]) if sdk_name in sdk_index: return sdk_name return None MINIMUM_SDK_VERSION_OPTIONS: dict[tuple[int, str], str] = { (EventType.PROFILE.value, "sentry.cocoa"): "sdk-deprecation.profile.cocoa", (EventType.PROFILE_CHUNK.value, "sentry.cocoa"): "sdk-deprecation.profile-chunk.cocoa", (EventType.PROFILE_CHUNK.value, "sentry.python"): "sdk-deprecation.profile-chunk.python", } def get_rejected_sdk_version(event_type: int, sdk_name: str) -> Version | None: parts = sdk_name.split(".", 2) if len(parts) < 2: return None normalized_sdk_name = ".".join(parts[:2]) sdk_version_option = MINIMUM_SDK_VERSION_OPTIONS.get((event_type, normalized_sdk_name)) if sdk_version_option is None: return None try: sdk_version = options.get(f"{sdk_version_option}.reject") except UnknownOption: sdk_version = None if sdk_version: try: return parse_version(sdk_version) except InvalidVersion as e: sentry_sdk.capture_exception(e) return None def get_minimum_sdk_version(event_type: int, sdk_name: str, hard_limit: bool) -> Version | None: parts = sdk_name.split(".", 2) if len(parts) < 2: return None normalized_sdk_name = ".".join(parts[:2]) sdk_version_option = MINIMUM_SDK_VERSION_OPTIONS.get((event_type, normalized_sdk_name)) if sdk_version_option is None: return None try: if hard_limit: sdk_version = options.get(f"{sdk_version_option}.hard") else: sdk_version = options.get(sdk_version_option) except UnknownOption: sdk_version = None if sdk_version: try: return parse_version(sdk_version) except InvalidVersion as e: sentry_sdk.capture_exception(e) return None
ProjectSDK
python
spack__spack
lib/spack/spack/externals.py
{ "start": 17087, "end": 17212 }
class ____(SpackError): """Raised when a dependency on an external package is specified wrongly."""
ExternalDependencyError
python
huggingface__transformers
tests/models/bridgetower/test_modeling_bridgetower.py
{ "start": 1601, "end": 3435 }
class ____: def __init__( self, parent, hidden_act="gelu", hidden_size=64, initializer_factor=1, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=2, intermediate_size=128, tie_word_embeddings=False, output_hidden_states=False, ): self.parent = parent self.hidden_act = hidden_act self.hidden_size = hidden_size self.initializer_factor = initializer_factor self.layer_norm_eps = layer_norm_eps self.num_attention_heads = num_attention_heads self.num_hidden_layers = num_hidden_layers self.intermediate_size = intermediate_size self.tie_word_embeddings = tie_word_embeddings self.vocab_size = 99 self.seq_length = 4 self.batch_size = 1 self.is_training = False self.output_hidden_states = output_hidden_states def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) attention_mask = random_attention_mask([self.batch_size, self.seq_length]) config = self.get_config() return config, input_ids, attention_mask def get_config(self): return BridgeTowerTextConfig( hidden_act=self.hidden_act, hidden_size=self.hidden_size, initializer_factor=self.initializer_factor, layer_norm_eps=self.layer_norm_eps, num_attention_heads=self.num_attention_heads, num_hidden_layers=self.num_hidden_layers, intermediate_size=self.intermediate_size, tie_word_embeddings=self.tie_word_embeddings, output_hidden_states=self.output_hidden_states, vocab_size=self.vocab_size, )
BridgeTowerTextModelTester
python
walkccc__LeetCode
solutions/2840. Check if Strings Can be Made Equal With Operations II/2840.py
{ "start": 0, "end": 342 }
class ____: def checkStrings(self, s1: str, s2: str) -> bool: count = [collections.Counter() for _ in range(2)] for i, (a, b) in enumerate(zip(s1, s2)): count[i % 2][a] += 1 count[i % 2][b] -= 1 return (all(freq == 0 for freq in count[0].values()) and all(freq == 0 for freq in count[1].values()))
Solution
python
joblib__joblib
joblib/externals/loky/process_executor.py
{ "start": 5168, "end": 8443 }
class ____: """necessary references to maintain executor states without preventing gc It permits to keep the information needed by executor_manager_thread and crash_detection_thread to maintain the pool without preventing the garbage collection of unreferenced executors. """ def __init__(self, shutdown_lock): self.shutdown = False self.broken = None self.kill_workers = False self.shutdown_lock = shutdown_lock def flag_as_shutting_down(self, kill_workers=None): with self.shutdown_lock: self.shutdown = True if kill_workers is not None: self.kill_workers = kill_workers def flag_as_broken(self, broken): with self.shutdown_lock: self.shutdown = True self.broken = broken # Prior to 3.9, executor_manager_thread is created as daemon thread. This means # that it is not joined automatically when the interpreter is shutting down. # To work around this problem, an exit handler is installed to tell the # thread to exit when the interpreter is shutting down and then waits until # it finishes. The thread needs to be daemonized because the atexit hooks are # called after all non daemonized threads are joined. # # Starting 3.9, there exists a specific atexit hook to be called before joining # the threads so the executor_manager_thread does not need to be daemonized # anymore. # # The atexit hooks are registered when starting the first ProcessPoolExecutor # to avoid import having an effect on the interpreter. _global_shutdown = False _global_shutdown_lock = threading.Lock() _threads_wakeups = weakref.WeakKeyDictionary() def _python_exit(): global _global_shutdown _global_shutdown = True # Materialize the list of items to avoid error due to iterating over # changing size dictionary. items = list(_threads_wakeups.items()) if len(items) > 0: mp.util.debug( f"Interpreter shutting down. Waking up {len(items)}" f"executor_manager_thread:\n{items}" ) # Wake up the executor_manager_thread's so they can detect the interpreter # is shutting down and exit. for _, (shutdown_lock, thread_wakeup) in items: with shutdown_lock: thread_wakeup.wakeup() # Collect the executor_manager_thread's to make sure we exit cleanly. for thread, _ in items: # This locks is to prevent situations where an executor is gc'ed in one # thread while the atexit finalizer is running in another thread. with _global_shutdown_lock: thread.join() # With the fork context, _thread_wakeups is propagated to children. # Clear it after fork to avoid some situation that can cause some # freeze when joining the workers. mp.util.register_after_fork(_threads_wakeups, lambda obj: obj.clear()) # Module variable to register the at_exit call process_pool_executor_at_exit = None # Controls how many more calls than processes will be queued in the call queue. # A smaller number will mean that processes spend more time idle waiting for # work while a larger number will make Future.cancel() succeed less frequently # (Futures in the call queue cannot be cancelled). EXTRA_QUEUED_CALLS = 1
_ExecutorFlags
python
pytorch__pytorch
torch/_higher_order_ops/triton_kernel_wrap.py
{ "start": 41930, "end": 42687 }
class ____(HigherOrderOperator): def __init__(self) -> None: super().__init__("triton_kernel_wrapper_mutation", cacheable=True) def __call__( self, kernel_idx: int, constant_args_idx: int, grid: list["TritonGridType"], tma_descriptor_metadata: TMADescriptorMetadata, kwargs: dict[str, Any], ) -> Any: return super().__call__( kernel_idx=kernel_idx, constant_args_idx=constant_args_idx, grid=grid, tma_descriptor_metadata=tma_descriptor_metadata, kwargs=kwargs, ) triton_kernel_wrapper_mutation = TritonKernelWrapperMutation() # Used for wrapping a Triton Kernel in a functional manner
TritonKernelWrapperMutation
python
pydata__xarray
xarray/tests/test_conventions.py
{ "start": 687, "end": 1148 }
class ____: def test_booltype_array(self) -> None: x = np.array([1, 0, 1, 1, 0], dtype="i1") bx = coding.variables.BoolTypeArray(x) assert bx.dtype == bool assert_array_equal(bx, np.array([True, False, True, True, False], dtype=bool)) x = np.array([[1, 0, 1], [0, 1, 0]], dtype="i1") bx = coding.variables.BoolTypeArray(x) assert_array_equal(bx.transpose((1, 0)), x.transpose((1, 0)))
TestBoolTypeArray
python
pytorch__pytorch
torch/distributions/cauchy.py
{ "start": 341, "end": 3209 }
class ____(Distribution): r""" Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of independent normally distributed random variables with means `0` follows a Cauchy distribution. Example:: >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0])) >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1 tensor([ 2.3214]) Args: loc (float or Tensor): mode or median of the distribution. scale (float or Tensor): half width at half maximum. """ # pyrefly: ignore [bad-override] arg_constraints = {"loc": constraints.real, "scale": constraints.positive} support = constraints.real has_rsample = True def __init__( self, loc: Union[Tensor, float], scale: Union[Tensor, float], validate_args: Optional[bool] = None, ) -> None: self.loc, self.scale = broadcast_all(loc, scale) if isinstance(loc, _Number) and isinstance(scale, _Number): batch_shape = torch.Size() else: batch_shape = self.loc.size() super().__init__(batch_shape, validate_args=validate_args) def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(Cauchy, _instance) batch_shape = torch.Size(batch_shape) new.loc = self.loc.expand(batch_shape) new.scale = self.scale.expand(batch_shape) super(Cauchy, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return new @property def mean(self) -> Tensor: return torch.full( self._extended_shape(), nan, dtype=self.loc.dtype, device=self.loc.device ) @property def mode(self) -> Tensor: return self.loc @property def variance(self) -> Tensor: return torch.full( self._extended_shape(), inf, dtype=self.loc.dtype, device=self.loc.device ) def rsample(self, sample_shape: _size = torch.Size()) -> Tensor: shape = self._extended_shape(sample_shape) eps = self.loc.new(shape).cauchy_() return self.loc + eps * self.scale def log_prob(self, value): if self._validate_args: self._validate_sample(value) return ( -math.log(math.pi) - self.scale.log() - (((value - self.loc) / self.scale) ** 2).log1p() ) def cdf(self, value): if self._validate_args: self._validate_sample(value) return torch.atan((value - self.loc) / self.scale) / math.pi + 0.5 def icdf(self, value): return torch.tan(math.pi * (value - 0.5)) * self.scale + self.loc def entropy(self): return math.log(4 * math.pi) + self.scale.log()
Cauchy
python
allegroai__clearml
clearml/binding/frameworks/fastai_bind.py
{ "start": 1102, "end": 7412 }
class ____(object): __metrics_names = {} __gradient_hist_helpers = {} _current_task = None __patched = False @staticmethod def update_current_task(task: Any, **_: Any) -> None: PatchFastaiV1._current_task = task if not task: return if not PatchFastaiV1.__patched: PatchFastaiV1.__patched = True PatchFastaiV1.patch_model_callback() @staticmethod def patch_model_callback() -> None: # if you have tensorboard, we assume you use TensorboardLogger, which we catch, so no need to patch. if "tensorboard" in sys.modules and IsTensorboardInit.tensorboard_used(): return try: from fastai.basic_train import Recorder Recorder.on_batch_end = _patched_call(Recorder.on_batch_end, PatchFastaiV1._on_batch_end) Recorder.on_backward_end = _patched_call(Recorder.on_backward_end, PatchFastaiV1._on_backward_end) Recorder.on_epoch_end = _patched_call(Recorder.on_epoch_end, PatchFastaiV1._on_epoch_end) Recorder.on_train_begin = _patched_call(Recorder.on_train_begin, PatchFastaiV1._on_train_begin) except ImportError: pass except Exception as ex: LoggerRoot.get_base_logger(PatchFastaiV1).debug(str(ex)) @staticmethod def _on_train_begin(original_fn: Callable, recorder: Any, *args: Any, **kwargs: Any) -> None: original_fn(recorder, *args, **kwargs) if not PatchFastaiV1._current_task: return # noinspection PyBroadException try: PatchFastaiV1.__metrics_names[id(recorder)] = ( ["train_loss"] if recorder.no_val else ["train_loss", "valid_loss"] ) PatchFastaiV1.__metrics_names[id(recorder)] += recorder.metrics_names except Exception: pass @staticmethod def _on_backward_end(original_fn: Callable, recorder: Any, *args: Any, **kwargs: Any) -> None: def count_zeros(gradient: "torch.Tensor") -> int: n = gradient.data.data.cpu().numpy() return n.size - np.count_nonzero(n) original_fn(recorder, *args, **kwargs) if not PatchFastaiV1._current_task: return # noinspection PyBroadException try: gradients = [x.grad.clone().detach().cpu() for x in recorder.learn.model.parameters() if x.grad is not None] if len(gradients) == 0: return # TODO: Check computation! gradient_stats = np.array( [ ( x.data.norm(), count_zeros(x), x.data.mean(), np.median(x.data), x.data.max(), x.data.min(), ) for x in gradients ] ) stats_report = dict( avg_norm=np.mean(gradient_stats[:, 0]), median_norm=np.median(gradient_stats[:, 0]), max_norm=np.max(gradient_stats[:, 0]), min_norm=np.min(gradient_stats[:, 0]), num_zeros=gradient_stats[:, 1].sum(), avg_gradient=gradient_stats[:, 2].mean(), median_gradient=np.median(gradient_stats[:, 3]), max_gradient=gradient_stats[:, 4].max(), min_gradient=gradient_stats[:, 5].min(), ) logger = PatchFastaiV1._current_task.get_logger() iteration = kwargs.get("iteration", 0) for name, val in stats_report.items(): logger.report_scalar( title="model_stats_gradients", series=name, value=val, iteration=iteration, ) except Exception: pass @staticmethod def _on_epoch_end(original_fn: Callable, recorder: Any, *args: Any, **kwargs: Any) -> None: original_fn(recorder, *args, **kwargs) if not PatchFastaiV1._current_task: return # noinspection PyBroadException try: logger = PatchFastaiV1._current_task.get_logger() iteration = kwargs.get("iteration") for series, value in zip( PatchFastaiV1.__metrics_names[id(recorder)], [kwargs.get("smooth_loss")] + kwargs.get("last_metrics", []), ): logger.report_scalar(title="metrics", series=series, value=value, iteration=iteration) PatchFastaiV1._current_task.flush() except Exception: pass @staticmethod def _on_batch_end(original_fn: Callable, recorder: Any, *args: Any, **kwargs: Any) -> None: original_fn(recorder, *args, **kwargs) if not PatchFastaiV1._current_task: return # noinspection PyBroadException try: iteration = kwargs.get("iteration", 0) if iteration == 0 or not kwargs.get("train"): return logger = PatchFastaiV1._current_task.get_logger() logger.report_scalar( title="metrics", series="train_loss", value=kwargs.get("last_loss", 0), iteration=iteration, ) params = [(name, values.clone().detach().cpu()) for (name, values) in recorder.model.named_parameters()] if ( id(recorder) not in PatchFastaiV1.__gradient_hist_helpers or PatchFastaiV1.__gradient_hist_helpers[id(recorder)].logger is not logger ): PatchFastaiV1.__gradient_hist_helpers[id(recorder)] = WeightsGradientHistHelper(logger) histograms = [] for name, values in params: histograms.append( dict( title="model_weights", series="model_weights/" + name, step=iteration, hist_data=values, ) ) PatchFastaiV1.__gradient_hist_helpers[id(recorder)].add_histograms(histograms) except Exception: pass
PatchFastaiV1
python
Pylons__pyramid
tests/test_integration.py
{ "start": 24203, "end": 24966 }
class ____(unittest.TestCase): def setUp(self): from pyramid.config import Configurator config = Configurator() from .pkgs.includeapp1.root import configure configure(config) app = config.make_wsgi_app() self.testapp = TestApp(app) self.config = config def tearDown(self): self.config.end() def test_root(self): res = self.testapp.get('/', status=200) self.assertTrue(b'root' in res.body) def test_two(self): res = self.testapp.get('/two', status=200) self.assertTrue(b'two' in res.body) def test_three(self): res = self.testapp.get('/three', status=200) self.assertTrue(b'three' in res.body)
ImperativeIncludeConfigurationTest
python
pytorch__pytorch
torch/fx/graph_module.py
{ "start": 13310, "end": 15931 }
class ____: def __init__(self, cls, cls_call): self.cls = cls self.cls_call = cls_call # Previously, if an error occurred when valid # symbolically-traced code was run with an invalid input, the # user would see the source of the error as coming from # `File "<eval_with_key_N">`, where N is some number. We use # this function to generate a more informative error message. We # return the traceback itself, a message explaining that the # error occurred in a traced Module's generated forward # function, and five lines of context surrounding the faulty # line @staticmethod def _generate_error_message(frame_summary: traceback.FrameSummary) -> str: # auxiliary variables (for readability) err_lineno = frame_summary.lineno assert err_lineno is not None line = frame_summary.line assert line is not None err_line_len = len(line) all_src_lines = linecache.getlines(frame_summary.filename) # constituent substrings of the error message tb_repr = torch._dynamo.disable( traceback.format_exc, reason="do not trace into traceback.format_exc when generating error message", )() custom_msg = ( "Call using an FX-traced Module, " f"line {err_lineno} of the traced Module's " "generated forward function:" ) before_err = "".join(all_src_lines[err_lineno - 2 : err_lineno]) marker = "~" * err_line_len + "~~~ <--- HERE" err_and_after_err = "\n".join(all_src_lines[err_lineno : err_lineno + 2]) # joined message return "\n".join([tb_repr, custom_msg, before_err, marker, err_and_after_err]) def __call__(self, obj, *args, **kwargs): try: if self.cls_call is not None: return self.cls_call(obj, *args, **kwargs) else: return super(self.cls, obj).__call__(*args, **kwargs) # type: ignore[misc] except Exception as e: assert e.__traceback__ topmost_framesummary: traceback.FrameSummary = ( traceback.StackSummary.extract(traceback.walk_tb(e.__traceback__))[-1] ) if "eval_with_key" in topmost_framesummary.filename: print( _WrappedCall._generate_error_message(topmost_framesummary), file=sys.stderr, ) raise e.with_traceback(None) # noqa: B904 else: raise e @compatibility(is_backward_compatible=True)
_WrappedCall
python
huggingface__transformers
src/transformers/models/parakeet/modeling_parakeet.py
{ "start": 2198, "end": 4214 }
class ____(nn.Module): """Relative positional encoding for Parakeet.""" inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: ParakeetEncoderConfig, device=None): super().__init__() self.max_position_embeddings = config.max_position_embeddings base = 10000.0 inv_freq = 1.0 / ( base ** ( torch.arange(0, config.hidden_size, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / config.hidden_size ) ) self.register_buffer("inv_freq", inv_freq, persistent=False) @torch.no_grad() def forward(self, hidden_states: torch.Tensor): seq_length = hidden_states.shape[1] if seq_length > self.max_position_embeddings: raise ValueError( f"Sequence Length: {seq_length} has to be less or equal than " f"config.max_position_embeddings {self.max_position_embeddings}." ) position_ids = torch.arange(seq_length - 1, -seq_length, -1, device=hidden_states.device) inv_freq_expanded = ( self.inv_freq[None, :, None].float().expand(hidden_states.shape[0], -1, 1).to(hidden_states.device) ) position_ids_expanded = position_ids[None, None, :].float() device_type = ( hidden_states.device.type if isinstance(hidden_states.device.type, str) and hidden_states.device.type != "mps" else "cpu" ) with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) sin = freqs.sin() cos = freqs.cos() # interleave sin and cos pos_embed = torch.stack([sin, cos], dim=-1) pos_embed = pos_embed.reshape(*pos_embed.shape[:-2], -1) return pos_embed.to(dtype=hidden_states.dtype)
ParakeetEncoderRelPositionalEncoding
python
pydata__xarray
xarray/core/coordinates.py
{ "start": 45724, "end": 47853 }
class ____(ValueError): """Error class for Xarray coordinate validation failures.""" def validate_dataarray_coords( shape: tuple[int, ...], coords: Coordinates | Mapping[Hashable, Variable], dim: tuple[Hashable, ...], ): """Validate coordinates ``coords`` to include in a DataArray defined by ``shape`` and dimensions ``dim``. If a coordinate is associated with an index, the validation is performed by the index. By default the coordinate dimensions must match (a subset of) the array dimensions (in any order) to conform to the DataArray model. The index may override this behavior with other validation rules, though. Non-index coordinates must all conform to the DataArray model. Scalar coordinates are always valid. """ sizes = dict(zip(dim, shape, strict=True)) dim_set = set(dim) indexes: Mapping[Hashable, Index] if isinstance(coords, Coordinates): indexes = coords.xindexes else: indexes = {} for k, v in coords.items(): if k in indexes: invalid = not indexes[k].should_add_coord_to_array(k, v, dim_set) else: invalid = any(d not in dim for d in v.dims) if invalid: raise CoordinateValidationError( f"coordinate {k} has dimensions {v.dims}, but these " "are not a subset of the DataArray " f"dimensions {dim}" ) for d, s in v.sizes.items(): if d in sizes and s != sizes[d]: raise CoordinateValidationError( f"conflicting sizes for dimension {d!r}: " f"length {sizes[d]} on the data but length {s} on " f"coordinate {k!r}" ) def coordinates_from_variable(variable: Variable) -> Coordinates: (name,) = variable.dims new_index, index_vars = create_default_index_implicit(variable) indexes = dict.fromkeys(index_vars, new_index) new_vars = new_index.create_variables() new_vars[name].attrs = variable.attrs return Coordinates(new_vars, indexes)
CoordinateValidationError
python
keras-team__keras
keras/src/optimizers/sgd.py
{ "start": 155, "end": 4396 }
class ____(optimizer.Optimizer): """Gradient descent (with momentum) optimizer. Update rule for parameter `w` with gradient `g` when `momentum` is 0: ```python w = w - learning_rate * g ``` Update rule when `momentum` is larger than 0: ```python velocity = momentum * velocity - learning_rate * g w = w + velocity ``` When `nesterov=True`, this rule becomes: ```python velocity = momentum * velocity - learning_rate * g w = w + momentum * velocity - learning_rate * g ``` Args: learning_rate: A float, a `keras.optimizers.schedules.LearningRateSchedule` instance, or a callable that takes no arguments and returns the actual value to use. The learning rate. Defaults to `0.01`. momentum: float hyperparameter >= 0 that accelerates gradient descent in the relevant direction and dampens oscillations. 0 is vanilla gradient descent. Defaults to `0.0`. nesterov: boolean. Whether to apply Nesterov momentum. Defaults to `False`. {{base_optimizer_keyword_args}} """ def __init__( self, learning_rate=0.01, momentum=0.0, nesterov=False, weight_decay=None, clipnorm=None, clipvalue=None, global_clipnorm=None, use_ema=False, ema_momentum=0.99, ema_overwrite_frequency=None, loss_scale_factor=None, gradient_accumulation_steps=None, name="SGD", **kwargs, ): super().__init__( learning_rate=learning_rate, name=name, weight_decay=weight_decay, clipnorm=clipnorm, clipvalue=clipvalue, global_clipnorm=global_clipnorm, use_ema=use_ema, ema_momentum=ema_momentum, ema_overwrite_frequency=ema_overwrite_frequency, loss_scale_factor=loss_scale_factor, gradient_accumulation_steps=gradient_accumulation_steps, **kwargs, ) if not isinstance(momentum, float) or momentum < 0 or momentum > 1: raise ValueError("`momentum` must be a float between [0, 1].") self.momentum = momentum self.nesterov = nesterov def build(self, variables): """Initialize optimizer variables. SGD optimizer has one variable `momentums`, only set if `self.momentum` is not 0. Args: var_list: list of model variables to build SGD variables on. """ if self.built: return super().build(variables) self.momentums = [] if self.momentum != 0: self.momentums = self.add_optimizer_variables(variables, "momentum") def update_step(self, gradient, variable, learning_rate): """Update step given gradient and the associated model variable.""" learning_rate = ops.cast(learning_rate, variable.dtype) gradient = ops.cast(gradient, variable.dtype) m = None if self.momentum != 0: m = self.momentums[self._get_variable_index(variable)] if m is not None: momentum = ops.cast(self.momentum, variable.dtype) self.assign( m, ops.subtract( ops.multiply(m, momentum), ops.multiply(gradient, learning_rate), ), ) if self.nesterov: self.assign_add( variable, ops.subtract( ops.multiply(m, momentum), ops.multiply(gradient, learning_rate), ), ) else: self.assign_add(variable, m) else: self.assign_sub(variable, ops.multiply(gradient, learning_rate)) def get_config(self): config = super().get_config() config.update( { "momentum": self.momentum, "nesterov": self.nesterov, } ) return config SGD.__doc__ = SGD.__doc__.replace( "{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args )
SGD
python
huggingface__transformers
tests/utils/test_activations.py
{ "start": 862, "end": 2559 }
class ____(unittest.TestCase): def test_gelu_versions(self): x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) torch_builtin = get_activation("gelu") torch.testing.assert_close(gelu_python(x), torch_builtin(x)) self.assertFalse(torch.allclose(gelu_python(x), gelu_new(x))) def test_gelu_10(self): x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) torch_builtin = get_activation("gelu") gelu10 = get_activation("gelu_10") y_gelu = torch_builtin(x) y_gelu_10 = gelu10(x) clipped_mask = torch.where(y_gelu_10 < 10.0, 1, 0) self.assertTrue(torch.max(y_gelu_10).item() == 10.0) torch.testing.assert_close(y_gelu * clipped_mask, y_gelu_10 * clipped_mask) def test_get_activation(self): get_activation("gelu") get_activation("gelu_10") get_activation("gelu_fast") get_activation("gelu_new") get_activation("gelu_python") get_activation("gelu_pytorch_tanh") get_activation("linear") get_activation("mish") get_activation("quick_gelu") get_activation("relu") get_activation("sigmoid") get_activation("silu") get_activation("swish") get_activation("tanh") with self.assertRaises(KeyError): get_activation("bogus") with self.assertRaises(KeyError): get_activation(None) def test_activations_are_distinct_objects(self): act1 = get_activation("gelu") act1.a = 1 act2 = get_activation("gelu") self.assertEqual(act1.a, 1) with self.assertRaises(AttributeError): _ = act2.a
TestActivations
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 181813, "end": 183043 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateEnterpriseOrganization""" __schema__ = github_schema __field_names__ = ("enterprise_id", "login", "profile_name", "billing_email", "admin_logins", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId") """The ID of the enterprise owning the new organization.""" login = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="login") """The login of the new organization.""" profile_name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="profileName") """The profile name of the new organization.""" billing_email = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="billingEmail") """The email used for sending billing receipts.""" admin_logins = sgqlc.types.Field(sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))), graphql_name="adminLogins") """The logins for the administrators of the new organization.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateEnterpriseOrganizationInput
python
python__mypy
mypy/plugins/singledispatch.py
{ "start": 823, "end": 8151 }
class ____(NamedTuple): register_type: Type singledispatch_obj: Instance def get_singledispatch_info(typ: Instance) -> SingledispatchTypeVars | None: if len(typ.args) == 2: return SingledispatchTypeVars(*typ.args) # type: ignore[arg-type] return None T = TypeVar("T") def get_first_arg(args: list[list[T]]) -> T | None: """Get the element that corresponds to the first argument passed to the function""" if args and args[0]: return args[0][0] return None def make_fake_register_class_instance( api: CheckerPluginInterface, type_args: Sequence[Type] ) -> Instance: defn = ClassDef(SINGLEDISPATCH_REGISTER_RETURN_CLASS, Block([])) defn.fullname = f"functools.{SINGLEDISPATCH_REGISTER_RETURN_CLASS}" info = TypeInfo(SymbolTable(), defn, "functools") obj_type = api.named_generic_type("builtins.object", []).type info.bases = [Instance(obj_type, [])] info.mro = [info, obj_type] defn.info = info func_arg = Argument(Var("name"), AnyType(TypeOfAny.implementation_artifact), None, ARG_POS) add_method_to_class(api, defn, "__call__", [func_arg], NoneType()) return Instance(info, type_args) PluginContext: _TypeAlias = FunctionContext | MethodContext def fail(ctx: PluginContext, msg: str, context: Context | None) -> None: """Emit an error message. This tries to emit an error message at the location specified by `context`, falling back to the location specified by `ctx.context`. This is helpful when the only context information about where you want to put the error message may be None (like it is for `CallableType.definition`) and falling back to the location of the calling function is fine.""" # TODO: figure out if there is some more reliable way of getting context information, so this # function isn't necessary if context is not None: err_context = context else: err_context = ctx.context ctx.api.fail(msg, err_context) def create_singledispatch_function_callback(ctx: FunctionContext) -> Type: """Called for functools.singledispatch""" func_type = get_proper_type(get_first_arg(ctx.arg_types)) if isinstance(func_type, CallableType): if len(func_type.arg_kinds) < 1: fail( ctx, "Singledispatch function requires at least one argument", func_type.definition ) return ctx.default_return_type elif not func_type.arg_kinds[0].is_positional(star=True): fail( ctx, "First argument to singledispatch function must be a positional argument", func_type.definition, ) return ctx.default_return_type # singledispatch returns an instance of functools._SingleDispatchCallable according to # typeshed singledispatch_obj = get_proper_type(ctx.default_return_type) assert isinstance(singledispatch_obj, Instance) singledispatch_obj.args += (func_type,) return ctx.default_return_type def singledispatch_register_callback(ctx: MethodContext) -> Type: """Called for functools._SingleDispatchCallable.register""" assert isinstance(ctx.type, Instance) # TODO: check that there's only one argument first_arg_type = get_proper_type(get_first_arg(ctx.arg_types)) if isinstance(first_arg_type, (CallableType, Overloaded)) and first_arg_type.is_type_obj(): # HACK: We received a class as an argument to register. We need to be able # to access the function that register is being applied to, and the typeshed definition # of register has it return a generic Callable, so we create a new # SingleDispatchRegisterCallable class, define a __call__ method, and then add a # plugin hook for that. # is_subtype doesn't work when the right type is Overloaded, so we need the # actual type register_type = first_arg_type.items[0].ret_type type_args = RegisterCallableInfo(register_type, ctx.type) register_callable = make_fake_register_class_instance(ctx.api, type_args) return register_callable elif isinstance(first_arg_type, CallableType): # TODO: do more checking for registered functions register_function(ctx, ctx.type, first_arg_type, ctx.api.options) # The typeshed stubs for register say that the function returned is Callable[..., T], even # though the function returned is the same as the one passed in. We return the type of the # function so that mypy can properly type check cases where the registered function is used # directly (instead of through singledispatch) return first_arg_type # fallback in case we don't recognize the arguments return ctx.default_return_type def register_function( ctx: PluginContext, singledispatch_obj: Instance, func: Type, options: Options, register_arg: Type | None = None, ) -> None: """Register a function""" func = get_proper_type(func) if not isinstance(func, CallableType): return metadata = get_singledispatch_info(singledispatch_obj) if metadata is None: # if we never added the fallback to the type variables, we already reported an error, so # just don't do anything here return dispatch_type = get_dispatch_type(func, register_arg) if dispatch_type is None: # TODO: report an error here that singledispatch requires at least one argument # (might want to do the error reporting in get_dispatch_type) return fallback = metadata.fallback fallback_dispatch_type = fallback.arg_types[0] if not is_subtype(dispatch_type, fallback_dispatch_type): fail( ctx, "Dispatch type {} must be subtype of fallback function first argument {}".format( format_type(dispatch_type, options), format_type(fallback_dispatch_type, options) ), func.definition, ) return return def get_dispatch_type(func: CallableType, register_arg: Type | None) -> Type | None: if register_arg is not None: return register_arg if func.arg_types: return func.arg_types[0] return None def call_singledispatch_function_after_register_argument(ctx: MethodContext) -> Type: """Called on the function after passing a type to register""" register_callable = ctx.type if isinstance(register_callable, Instance): type_args = RegisterCallableInfo(*register_callable.args) # type: ignore[arg-type] func = get_first_arg(ctx.arg_types) if func is not None: register_function( ctx, type_args.singledispatch_obj, func, ctx.api.options, type_args.register_type ) # see call to register_function in the callback for register return func return ctx.default_return_type def call_singledispatch_function_callback(ctx: MethodSigContext) -> FunctionLike: """Called for functools._SingleDispatchCallable.__call__""" if not isinstance(ctx.type, Instance): return ctx.default_signature metadata = get_singledispatch_info(ctx.type) if metadata is None: return ctx.default_signature return metadata.fallback
RegisterCallableInfo
python
pennersr__django-allauth
allauth/socialaccount/providers/stocktwits/views.py
{ "start": 181, "end": 1068 }
class ____(OAuth2Adapter): provider_id = "stocktwits" access_token_url = "https://api.stocktwits.com/api/2/oauth/token" # nosec authorize_url = "https://api.stocktwits.com/api/2/oauth/authorize" profile_url = "https://api.stocktwits.com/api/2/streams/user/{user}.json" scope_delimiter = "," def complete_login(self, request, app, token, **kwargs): user_id = kwargs.get("response").get("user_id") resp = ( get_adapter() .get_requests_session() .get(self.profile_url.format(user=user_id)) ) resp.raise_for_status() extra_data = resp.json() return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(StocktwitsOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(StocktwitsOAuth2Adapter)
StocktwitsOAuth2Adapter
python
matplotlib__matplotlib
lib/matplotlib/offsetbox.py
{ "start": 15307, "end": 16418 }
class ____(PackerBase): """ HPacker packs its children horizontally, automatically adjusting their relative positions at draw time. .. code-block:: none +-------------------------------+ | Child 1 Child 2 Child 3 | +-------------------------------+ """ def _get_bbox_and_child_offsets(self, renderer): # docstring inherited dpicor = renderer.points_to_pixels(1.) pad = self.pad * dpicor sep = self.sep * dpicor bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()] if not bboxes: return Bbox.from_bounds(0, 0, 0, 0).padded(pad), [] (y0, y1), yoffsets = _get_aligned_offsets( [bbox.intervaly for bbox in bboxes], self.height, self.align) width, xoffsets = _get_packed_offsets( [bbox.width for bbox in bboxes], self.width, sep, self.mode) x0 = bboxes[0].x0 xoffsets -= ([bbox.x0 for bbox in bboxes] - x0) return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad), [*zip(xoffsets, yoffsets)])
HPacker
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isin.py
{ "start": 1884, "end": 4459 }
class ____(ColumnMapExpectation): """Expect column values to be valid ISIN (International Securities Identification Number).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [ "US0378331005", "GB00BYXJL758", "US0004026250", "US0004026250", ], "some_other": [ "979-0-3452-4680-5", "GB00BYXJL758", "US0004026250", "NA000K0VF054", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "all_valid"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_other", "mostly": 1}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.to_be_valid_isin" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["python-stdnum"], } if __name__ == "__main__": ExpectColumnValuesToBeValidIsin().print_diagnostic_checklist()
ExpectColumnValuesToBeValidIsin
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/query/query_transform/base.py
{ "start": 2848, "end": 4853 }
class ____(BaseQueryTransform): """ Hypothetical Document Embeddings (HyDE) query transform. It uses an LLM to generate hypothetical answer(s) to a given query, and use the resulting documents as embedding strings. As described in `[Precise Zero-Shot Dense Retrieval without Relevance Labels] (https://arxiv.org/abs/2212.10496)` """ def __init__( self, llm: Optional[LLM] = None, hyde_prompt: Optional[BasePromptTemplate] = None, include_original: bool = True, ) -> None: """ Initialize HyDEQueryTransform. Args: llm_predictor (Optional[LLM]): LLM for generating hypothetical documents hyde_prompt (Optional[BasePromptTemplate]): Custom prompt for HyDE include_original (bool): Whether to include original query string as one of the embedding strings """ super().__init__() self._llm = llm or Settings.llm self._hyde_prompt = hyde_prompt or DEFAULT_HYDE_PROMPT self._include_original = include_original def _get_prompts(self) -> PromptDictType: """Get prompts.""" return {"hyde_prompt": self._hyde_prompt} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" if "hyde_prompt" in prompts: self._hyde_prompt = prompts["hyde_prompt"] def _run(self, query_bundle: QueryBundle, metadata: Dict) -> QueryBundle: """Run query transform.""" # TODO: support generating multiple hypothetical docs query_str = query_bundle.query_str hypothetical_doc = self._llm.predict(self._hyde_prompt, context_str=query_str) embedding_strs = [hypothetical_doc] if self._include_original: embedding_strs.extend(query_bundle.embedding_strs) return QueryBundle( query_str=query_str, custom_embedding_strs=embedding_strs, )
HyDEQueryTransform
python
huggingface__transformers
src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
{ "start": 12992, "end": 13566 }
class ____(nn.Module): def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None: super().__init__() self.hidden_size = context_dim * (spatial_merge_size**2) self.ln_q = LayerNorm(context_dim, eps=1e-6) self.mlp = nn.Sequential( nn.Linear(self.hidden_size, self.hidden_size), nn.GELU(), nn.Linear(self.hidden_size, dim), ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.mlp(self.ln_q(x).view(-1, self.hidden_size)) return x
PatchMerger
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 145068, "end": 155580 }
class ____: # Track the loaded modules so we can remove the on-disk artifacts when # clearing the cache. Note also that we may load the same path more # than once, but attach different attributes, i.e., due to different # constant values. modules: list[ModuleType] = [] # Modules loaded without extra attributes are stored here, those do not # need to be re-loaded. modules_no_attr: dict[str, ModuleType] = {} linemaps: dict[str, list[tuple[Any, ...]]] = {} @classmethod def write(cls, source_code: str, extra: str = "") -> tuple[str, str]: return write(source_code, "py", extra=extra) @classmethod def load(cls, source_code: str, extra: str = "") -> ModuleType: key, path = write(source_code, "py", extra=extra) return cls.load_by_key_path(key, path) @classmethod def load_by_key_path( cls, key: str, path: str, linemap: list[tuple[int, str]] | None = None, attrs: dict[str, Any] | None = None, ) -> ModuleType: if linemap is None: linemap = [] # we only cache when attrs is None if attrs is None and path in cls.modules_no_attr: return cls.modules_no_attr[path] in_toplevel = in_toplevel_process() mod = _reload_python_module(key, path, set_sys_modules=in_toplevel) # unzip into separate lines/nodes lists if in_toplevel: cls.linemaps[path] = list(zip(*linemap)) if attrs is not None: for k, v in attrs.items(): setattr(mod, k, v) if in_toplevel: # we only cache when attrs is None if attrs is None: cls.modules_no_attr[path] = mod cls.modules.append(mod) return mod @classmethod def cache_clear(cls, purge: bool = False) -> None: """ Clear the in-memory module cache. If purge=True, also delete all the corresponding on-disk source files. """ if purge: for mod in cls.modules: try: assert mod.__file__ os.remove(mod.__file__) except FileNotFoundError: pass cls.modules.clear() cls.modules_no_attr.clear() @classmethod @functools.cache def stack_frames_for_code( cls, path: str, lineno: int ) -> list[dict[str, Any]] | None: if path not in cls.linemaps: return None if len(cls.linemaps[path]) == 0: return None # [(starting_line, <fx node>), ...] lines, nodes = cls.linemaps[path] p = bisect_right(lines, lineno) if p == 0: return None entry = nodes[p - 1] if not entry: return None def parse_stack_trace(stack_trace: str) -> list[dict[str, Any]]: # ideally fx stores stack traces as data rather than a string # but this is not along a performance critical path regex = r'File "(.+)", line (\d+), in (.+)\n' matches = re.findall(regex, stack_trace) return [ {"filename": f, "line": int(l), "name": n} for f, l, n in reversed(matches) ] return parse_stack_trace(entry) def _load_triton_kernel_from_source( kernel_name: str, source_code: str ) -> CachingAutotuner: return getattr(PyCodeCache.load(source_code), kernel_name) def _cuda_compiler() -> str | None: if cuda_env.nvcc_exist(config.cuda.cuda_cxx): return config.cuda.cuda_cxx if config.is_fbcode(): return os.path.join(build_paths.sdk_home, "bin", "nvcc") if cuda_env.nvcc_exist(os.getenv("CUDACXX")): return os.getenv("CUDACXX", "") if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")): return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc")) return "nvcc" def _cutlass_path() -> str: if config.is_fbcode(): from libfb.py import parutil return parutil.get_dir_path("cutlass-4-headers") else: return config.cuda.cutlass_dir def _cutlass_paths() -> list[str]: return [ "include", "tools/library/include", "tools/library/src", "tools/util/include", ] def _clone_cutlass_paths(build_root: str) -> list[str]: paths = _cutlass_paths() cutlass_root = _cutlass_path() for path in _cutlass_paths(): old_path = os.path.join(cutlass_root, path) new_path = os.path.join(build_root, path) shutil.copytree(old_path, new_path, dirs_exist_ok=True) return paths def _cutlass_include_paths() -> list[str]: cutlass_path = _cutlass_path() return [ # Use realpath to get canonical absolute paths, in order not to mess up cache keys os.path.realpath(os.path.join(cutlass_path, path)) for path in _cutlass_paths() ] @torch_key_cache def cutlass_key() -> bytes: """ Compute a key representing the state of the CUTLASS library. Note: OSS and fbcode will have different keys. """ if config.is_fbcode(): with ( importlib.resources.path( "cutlass_library", "src_hash.txt" ) as resource_path, open(resource_path) as resource_file, ): return resource_file.read().encode() combined_hash = hashlib.sha256() build_code_hash([config.cuda.cutlass_dir], "", combined_hash) return combined_hash.digest() def _cuda_lib_options() -> list[str]: """ Util function for CUTLASS backend to find the correct CUDA libraries. """ _set_gpu_runtime_env() # cpp_extension consults the env from torch.utils import cpp_extension lpaths = cpp_extension.library_paths(device_type="cuda") if use_re_build(): lpaths += [ build_paths.sdk_lib, os.path.join(build_paths.sdk_lib, "stubs"), ] extra_ldflags: list[str] = [] if is_linux(): _transform_cuda_paths(lpaths) for path in lpaths: if "torch/lib" in path: # don't want to depend on pytorch continue extra_ldflags.append(f"-L{path}") # -rpath ensures the DLL can find its dependencies when loaded, even # if the library path is non-standard. # But do not add the stubs folder to rpath as the driver is expected to be found at runtime if os.path.basename(path) != "stubs": extra_ldflags.extend(["-Xlinker", f"-rpath={path}"]) extra_ldflags.append("-lcuda") extra_ldflags.append("-lcudart") else: raise NotImplementedError( "Unsupported env, failed to find cuda libs! Currently only Linux is supported." ) return extra_ldflags def _nvcc_host_compiler_options() -> list[str]: return [ "-fPIC", "-fno-strict-aliasing", "-fvisibility=hidden", "-Wconversion", ] def _nvcc_arch_as_compile_option() -> str: arch = cuda_env.get_cuda_arch() if arch == "90": # Required by cutlass compilation. return "90a" if arch == "100": return "100a" return arch def _nvcc_compiler_options() -> list[str]: arch = _nvcc_arch_as_compile_option() code = [f"sm_{arch}", f"compute_{arch}"] if config.cuda.enable_cuda_lto: code += [f"lto_{arch}"] options = [ "-t=0", "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1", "-DCUTLASS_ENABLE_SM90_EXTENDED_MMA_SHAPES=1", "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", "-w", f"-gencode=arch=compute_{arch},code=[{','.join(code)}]", config.cuda.compile_opt_level, "-std=c++17", "--expt-relaxed-constexpr", "-DNDEBUG", ] if config.is_fbcode(): options.extend(["-ccbin", os.path.dirname(build_paths.gcc)]) if config.cuda.enable_debug_info: options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]) if config.cuda.enable_ptxas_info: options.extend( [ "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.) "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.) "--source-in-ptx", ] ) # Annotate the ptx file with source information if config.cuda.use_fast_math: options.extend( [ "--use_fast_math", "-DCUTLASS_USE_TANH_FOR_SIGMOID=1", ] ) return options def cuda_compile_command( src_files: list[str], dst_file: str, dst_file_ext: str, extra_args: list[str] | None = None, ) -> str: if extra_args is None: extra_args = [] if use_re_build(): build_path = os.path.dirname(dst_file) include_paths = _clone_cutlass_paths(build_path) src_files = [os.path.basename(src_file) for src_file in src_files] dst_file = os.path.basename(dst_file) else: include_paths = _cutlass_include_paths() cuda_lib_options = _cuda_lib_options() nvcc_host_compiler_options = _nvcc_host_compiler_options() nvcc_compiler_options = _nvcc_compiler_options() options = ( nvcc_compiler_options + extra_args + [ f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}" for opt in nvcc_host_compiler_options ] + ["-I" + path for path in include_paths] + cuda_lib_options ) src_file = " ".join(src_files) res = "" if dst_file_ext == "o": res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}" elif dst_file_ext == "so": options.append("-shared") res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" elif dst_file_ext == "exe": res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" else: raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") if log.isEnabledFor(logging.DEBUG): log.debug("CUDA command: %s", res) else: autotuning_log.debug("CUDA command: %s", res) return res
PyCodeCache
python
urllib3__urllib3
dummyserver/testcase.py
{ "start": 6890, "end": 7073 }
class ____(HypercornDummyServerTestCase): scheme = "https" host = "localhost" certs = DEFAULT_CERTS certs_dir = "" bad_ca_path = ""
HTTPSHypercornDummyServerTestCase
python
cython__cython
Cython/Debugger/Tests/TestLibCython.py
{ "start": 7501, "end": 8392 }
class ____(GdbDebuggerTestCase): def test_all(self): if not test_gdb(): return out, err = self.p.communicate() out = out.decode('UTF-8') err = err.decode('UTF-8') exit_status = self.p.returncode if exit_status == 1: sys.stderr.write(out) sys.stderr.write(err) elif exit_status >= 2: border = '*' * 30 start = '%s v INSIDE GDB v %s' % (border, border) stderr = '%s v STDERR v %s' % (border, border) end = '%s ^ INSIDE GDB ^ %s' % (border, border) errmsg = '\n%s\n%s%s\n%s%s' % (start, out, stderr, err, end) sys.stderr.write(errmsg) # FIXME: re-enable this to make the test fail on internal failures #self.assertEqual(exit_status, 0) if __name__ == '__main__': unittest.main()
TestAll
python
pytorch__pytorch
torch/_guards.py
{ "start": 4603, "end": 7144 }
class ____(enum.Enum): LOCAL = 0 GLOBAL = 1 LOCAL_SPECIALIZED_NN_MODULE = 2 GLOBAL_SPECIALIZED_NN_MODULE = 3 CONSTANT = 4 RANDOM_VALUE = 5 SHAPE_ENV = 6 LOCAL_FSDP_MODULE = 7 GLOBAL_FSDP_MODULE = 8 BACKWARD_STATE = 9 EPHEMERAL = 10 SYNTHETIC_LOCAL = 11 LOCAL_UNSPECIALIZED_NN_MODULE = 12 GLOBAL_UNSPECIALIZED_NN_MODULE = 13 LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14 GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15 TEMP_LOCAL = 16 def is_fsdp_module(self) -> bool: return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE) def is_specialized_nn_module(self) -> bool: import torch._dynamo.config as config if config._unsafe_skip_fsdp_module_guards: return ( self in ( GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, GuardSource.LOCAL_SPECIALIZED_NN_MODULE, ) or self.is_fsdp_module() ) return self in ( GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, GuardSource.LOCAL_SPECIALIZED_NN_MODULE, ) def is_unspecialized_nn_module(self) -> bool: return self in ( GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, ) def is_unspecialized_builtin_nn_module(self) -> bool: return self in ( GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, ) def is_local(self) -> bool: return self in ( GuardSource.LOCAL, GuardSource.LOCAL_SPECIALIZED_NN_MODULE, GuardSource.LOCAL_FSDP_MODULE, GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, ) """ Base class for a "GuardBuilder" role. The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little confusing, as its not a builder, but for the sake of avoiding a lot of renames and keeping the original reference to torchdynamo's GuardBuilder. Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based on GuardSource's select function. There is value in keeping this GuardBuilderBase empty to keep layering clean. """
GuardSource
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocolExplicit1.py
{ "start": 1036, "end": 1201 }
class ____(Protocol): def method1(self) -> int: ... # This should generate an error because "method1" is # not implemented and it is marked final. @final
Protocol5
python
pytest-dev__pytest-django
tests/test_unittest.py
{ "start": 1197, "end": 1671 }
class ____(TestCase): fixtures = ("items",) def setUp(self) -> None: assert Item.objects.count() == 1 Item.objects.create(name="Some item") def test_count(self) -> None: assert Item.objects.count() == 2 Item.objects.create(name="Some item again") def test_count_again(self) -> None: self.test_count() def tearDown(self) -> None: assert Item.objects.count() == 3 @tag("tag1", "tag2")
TestFixturesWithSetup