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
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 20670, "end": 20893 }
class ____(StringEnum): training_stats_scalar = "training_stats_scalar" training_stats_vector = "training_stats_vector" training_debug_image = "training_debug_image" plot = "plot" log = "log"
EventTypeEnum
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/google_api_to_s3.py
{ "start": 1525, "end": 9121 }
class ____(BaseOperator): """ Basic class for transferring data from a Google API endpoint into a S3 Bucket. This discovery-based operator use :class:`~airflow.providers.google.common.hooks.discovery_api.GoogleDiscoveryApiHook` to communicate with Google Services via the `Google API Python Client <https://github.com/googleapis/google-api-python-client>`__. Please note that this library is in maintenance mode hence it won't fully support Google Cloud in the future. Therefore it is recommended that you use the custom Google Cloud Service Operators for working with the Google Cloud Platform. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GoogleApiToS3Operator` :param google_api_service_name: The specific API service that is being requested. :param google_api_service_version: The version of the API that is being requested. :param google_api_endpoint_path: The client libraries path to the api call's executing method. For example: 'analyticsreporting.reports.batchGet' .. note:: See https://developers.google.com/apis-explorer for more information on which methods are available. :param google_api_endpoint_params: The params to control the corresponding endpoint result. :param s3_destination_key: The url where to put the data retrieved from the endpoint in S3. .. note See https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html for valid url formats. :param google_api_response_via_xcom: Can be set to expose the google api response to xcom. :param google_api_endpoint_params_via_xcom: If set to a value this value will be used as a key for pulling from xcom and updating the google api endpoint params. :param google_api_endpoint_params_via_xcom_task_ids: Task ids to filter xcom by. :param google_api_pagination: If set to True Pagination will be enabled for this request to retrieve all data. .. note:: This means the response will be a list of responses. :param google_api_num_retries: Define the number of retries for the Google API requests being made if it fails. :param s3_overwrite: Specifies whether the s3 file will be overwritten if exists. :param gcp_conn_id: The connection ID to use when fetching connection info. :param aws_conn_id: The connection id specifying the authentication information for the S3 Bucket. :param google_impersonation_chain: Optional Google service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "google_api_endpoint_params", "s3_destination_key", "google_impersonation_chain", "gcp_conn_id", ) template_ext: Sequence[str] = () ui_color = "#cc181e" def __init__( self, *, google_api_service_name: str, google_api_service_version: str, google_api_endpoint_path: str, google_api_endpoint_params: dict, s3_destination_key: str, google_api_response_via_xcom: str | None = None, google_api_endpoint_params_via_xcom: str | None = None, google_api_endpoint_params_via_xcom_task_ids: str | None = None, google_api_pagination: bool = False, google_api_num_retries: int = 0, s3_overwrite: bool = False, gcp_conn_id: str = "google_cloud_default", aws_conn_id: str | None = "aws_default", google_impersonation_chain: str | Sequence[str] | None = None, **kwargs, ): super().__init__(**kwargs) self.google_api_service_name = google_api_service_name self.google_api_service_version = google_api_service_version self.google_api_endpoint_path = google_api_endpoint_path self.google_api_endpoint_params = google_api_endpoint_params self.s3_destination_key = s3_destination_key self.google_api_response_via_xcom = google_api_response_via_xcom self.google_api_endpoint_params_via_xcom = google_api_endpoint_params_via_xcom self.google_api_endpoint_params_via_xcom_task_ids = google_api_endpoint_params_via_xcom_task_ids self.google_api_pagination = google_api_pagination self.google_api_num_retries = google_api_num_retries self.s3_overwrite = s3_overwrite self.gcp_conn_id = gcp_conn_id self.aws_conn_id = aws_conn_id self.google_impersonation_chain = google_impersonation_chain def execute(self, context: Context) -> None: """ Transfers Google APIs json data to S3. :param context: The context that is being provided when executing. """ self.log.info("Transferring data from %s to s3", self.google_api_service_name) if self.google_api_endpoint_params_via_xcom: self._update_google_api_endpoint_params_via_xcom(context["task_instance"]) data = self._retrieve_data_from_google_api() self._load_data_to_s3(data) if self.google_api_response_via_xcom: self._expose_google_api_response_via_xcom(context["task_instance"], data) def _retrieve_data_from_google_api(self) -> dict: google_discovery_api_hook = GoogleDiscoveryApiHook( gcp_conn_id=self.gcp_conn_id, api_service_name=self.google_api_service_name, api_version=self.google_api_service_version, impersonation_chain=self.google_impersonation_chain, ) return google_discovery_api_hook.query( endpoint=self.google_api_endpoint_path, data=self.google_api_endpoint_params, paginate=self.google_api_pagination, num_retries=self.google_api_num_retries, ) def _load_data_to_s3(self, data: dict) -> None: s3_hook = S3Hook(aws_conn_id=self.aws_conn_id) s3_hook.load_string( string_data=json.dumps(data), bucket_name=S3Hook.parse_s3_url(self.s3_destination_key)[0], key=S3Hook.parse_s3_url(self.s3_destination_key)[1], replace=self.s3_overwrite, ) def _update_google_api_endpoint_params_via_xcom(self, task_instance: RuntimeTaskInstanceProtocol) -> None: if self.google_api_endpoint_params_via_xcom: google_api_endpoint_params = task_instance.xcom_pull( task_ids=self.google_api_endpoint_params_via_xcom_task_ids, key=self.google_api_endpoint_params_via_xcom, ) self.google_api_endpoint_params.update(google_api_endpoint_params) def _expose_google_api_response_via_xcom( self, task_instance: RuntimeTaskInstanceProtocol, data: dict ) -> None: if sys.getsizeof(data) < MAX_XCOM_SIZE: task_instance.xcom_push(key=self.google_api_response_via_xcom or XCOM_RETURN_KEY, value=data) else: raise RuntimeError("The size of the downloaded data is too large to push to XCom!")
GoogleApiToS3Operator
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 168600, "end": 169185 }
class ____(Strategy): """Default `tf.distribute.Strategy` if none is explicitly selected.""" def __init__(self): if not _creating_default_strategy_singleton: raise RuntimeError("Should only create a single instance of " "_DefaultDistributionStrategy") super(_DefaultDistributionStrategy, self).__init__( _DefaultDistributionExtended(self)) def __deepcopy__(self, memo): del memo raise RuntimeError("Should only create a single instance of " "_DefaultDistributionStrategy")
_DefaultDistributionStrategy
python
openai__openai-python
src/openai/types/realtime/response_audio_delta_event.py
{ "start": 200, "end": 755 }
class ____(BaseModel): content_index: int """The index of the content part in the item's content array.""" delta: str """Base64-encoded audio data delta.""" event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item.""" output_index: int """The index of the output item in the response.""" response_id: str """The ID of the response.""" type: Literal["response.output_audio.delta"] """The event type, must be `response.output_audio.delta`."""
ResponseAudioDeltaEvent
python
scrapy__scrapy
tests/test_command_crawl.py
{ "start": 246, "end": 854 }
class ____(TestProjectBase): def crawl( self, code: str, proj_path: Path, args: Iterable[str] = () ) -> tuple[int, str, str]: (proj_path / self.project_name / "spiders" / "myspider.py").write_text( code, encoding="utf-8" ) return proc("crawl", "myspider", *args, cwd=proj_path) def get_log(self, code: str, proj_path: Path, args: Iterable[str] = ()) -> str: _, _, stderr = self.crawl(code, proj_path, args=args) return stderr def test_no_output(self, proj_path: Path) -> None: spider_code = """ import scrapy
TestCrawlCommand
python
networkx__networkx
networkx/algorithms/approximation/treewidth.py
{ "start": 2984, "end": 8389 }
class ____: """Implements the Minimum Degree heuristic. The heuristic chooses the nodes according to their degree (number of neighbors), i.e., first the node with the lowest degree is chosen, then the graph is updated and the corresponding node is removed. Next, a new node with the lowest degree is chosen, and so on. """ def __init__(self, graph): self._graph = graph # nodes that have to be updated in the heap before each iteration self._update_nodes = [] self._degreeq = [] # a heapq with 3-tuples (degree,unique_id,node) self.count = itertools.count() # build heap with initial degrees for n in graph: self._degreeq.append((len(graph[n]), next(self.count), n)) heapify(self._degreeq) def best_node(self, graph): # update nodes in self._update_nodes for n in self._update_nodes: # insert changed degrees into degreeq heappush(self._degreeq, (len(graph[n]), next(self.count), n)) # get the next valid (minimum degree) node while self._degreeq: (min_degree, _, elim_node) = heappop(self._degreeq) if elim_node not in graph or len(graph[elim_node]) != min_degree: # outdated entry in degreeq continue elif min_degree == len(graph) - 1: # fully connected: abort condition return None # remember to update nodes in the heap before getting the next node self._update_nodes = graph[elim_node] return elim_node # the heap is empty: abort return None def min_fill_in_heuristic(graph_dict): """Implements the Minimum Degree heuristic. graph_dict: dict keyed by node to sets of neighbors (no self-loops) Returns the node from the graph, where the number of edges added when turning the neighborhood of the chosen node into clique is as small as possible. This algorithm chooses the nodes using the Minimum Fill-In heuristic. The running time of the algorithm is :math:`O(V^3)` and it uses additional constant memory. """ if len(graph_dict) == 0: return None min_fill_in_node = None min_fill_in = sys.maxsize # sort nodes by degree nodes_by_degree = sorted(graph_dict, key=lambda x: len(graph_dict[x])) min_degree = len(graph_dict[nodes_by_degree[0]]) # abort condition (handle complete graph) if min_degree == len(graph_dict) - 1: return None for node in nodes_by_degree: num_fill_in = 0 nbrs = graph_dict[node] for nbr in nbrs: # count how many nodes in nbrs current nbr is not connected to # subtract 1 for the node itself num_fill_in += len(nbrs - graph_dict[nbr]) - 1 if num_fill_in >= 2 * min_fill_in: break num_fill_in /= 2 # divide by 2 because of double counting if num_fill_in < min_fill_in: # update min-fill-in node if num_fill_in == 0: return node min_fill_in = num_fill_in min_fill_in_node = node return min_fill_in_node @nx._dispatchable(returns_graph=True) def treewidth_decomp(G, heuristic=min_fill_in_heuristic): """Returns a treewidth decomposition using the passed heuristic. Parameters ---------- G : NetworkX graph heuristic : heuristic function Returns ------- Treewidth decomposition : (int, Graph) tuple 2-tuple with treewidth and the corresponding decomposed tree. """ # make dict-of-sets structure graph_dict = {n: set(G[n]) - {n} for n in G} # stack containing nodes and neighbors in the order from the heuristic node_stack = [] # get first node from heuristic elim_node = heuristic(graph_dict) while elim_node is not None: # connect all neighbors with each other nbrs = graph_dict[elim_node] for u, v in itertools.permutations(nbrs, 2): if v not in graph_dict[u]: graph_dict[u].add(v) # push node and its current neighbors on stack node_stack.append((elim_node, nbrs)) # remove node from graph_dict for u in graph_dict[elim_node]: graph_dict[u].remove(elim_node) del graph_dict[elim_node] elim_node = heuristic(graph_dict) # the abort condition is met; put all remaining nodes into one bag decomp = nx.Graph() first_bag = frozenset(graph_dict.keys()) decomp.add_node(first_bag) treewidth = len(first_bag) - 1 while node_stack: # get node and its neighbors from the stack (curr_node, nbrs) = node_stack.pop() # find a bag all neighbors are in old_bag = None for bag in decomp.nodes: if nbrs <= bag: old_bag = bag break if old_bag is None: # no old_bag was found: just connect to the first_bag old_bag = first_bag # create new node for decomposition nbrs.add(curr_node) new_bag = frozenset(nbrs) # update treewidth treewidth = max(treewidth, len(new_bag) - 1) # add edge to decomposition (implicitly also adds the new node) decomp.add_edge(old_bag, new_bag) return treewidth, decomp
MinDegreeHeuristic
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 187397, "end": 187480 }
class ____(_DateRangeTests, _RangeTypeCompilation): pass
DateRangeCompilationTest
python
numba__numba
numba/tests/test_typeconv.py
{ "start": 228, "end": 2888 }
class ____(unittest.TestCase): def check_number_compatibility(self, check_compatible): b = types.boolean i8 = types.int8 i16 = types.int16 i32 = types.int32 i64 = types.int64 u8 = types.uint8 u16 = types.uint16 u32 = types.uint32 u64 = types.uint64 f16 = types.float16 f32 = types.float32 f64 = types.float64 c64 = types.complex64 c128 = types.complex128 self.assertEqual(check_compatible(i32, i32), Conversion.exact) self.assertEqual(check_compatible(b, i8), Conversion.safe) self.assertEqual(check_compatible(b, u8), Conversion.safe) self.assertEqual(check_compatible(i8, b), Conversion.unsafe) self.assertEqual(check_compatible(u8, b), Conversion.unsafe) self.assertEqual(check_compatible(i32, i64), Conversion.promote) self.assertEqual(check_compatible(i32, u32), Conversion.unsafe) self.assertEqual(check_compatible(u32, i32), Conversion.unsafe) self.assertEqual(check_compatible(u32, i64), Conversion.safe) self.assertEqual(check_compatible(i16, f16), Conversion.unsafe) self.assertEqual(check_compatible(i32, f32), Conversion.unsafe) self.assertEqual(check_compatible(u32, f32), Conversion.unsafe) self.assertEqual(check_compatible(i32, f64), Conversion.safe) self.assertEqual(check_compatible(u32, f64), Conversion.safe) # Note this is inconsistent with i32 -> f32... self.assertEqual(check_compatible(i64, f64), Conversion.safe) self.assertEqual(check_compatible(u64, f64), Conversion.safe) self.assertEqual(check_compatible(f32, c64), Conversion.safe) self.assertEqual(check_compatible(f64, c128), Conversion.safe) self.assertEqual(check_compatible(f64, c64), Conversion.unsafe) # Propagated compatibility relationships self.assertEqual(check_compatible(i16, f64), Conversion.safe) self.assertEqual(check_compatible(i16, i64), Conversion.promote) self.assertEqual(check_compatible(i32, c64), Conversion.unsafe) self.assertEqual(check_compatible(i32, c128), Conversion.safe) self.assertEqual(check_compatible(i32, u64), Conversion.unsafe) for ta, tb in itertools.product(types.number_domain, types.number_domain): if ta in types.complex_domain and tb not in types.complex_domain: continue self.assertTrue(check_compatible(ta, tb) is not None, msg="No cast from %s to %s" % (ta, tb))
CompatibilityTestMixin
python
wandb__wandb
wandb/vendor/pygments/lexers/business.py
{ "start": 25361, "end": 27665 }
class ____(RegexLexer): """ Lexer for `GoodData MAQL <https://secure.gooddata.com/docs/html/advanced.metric.tutorial.html>`_ scripts. .. versionadded:: 1.4 """ name = 'MAQL' aliases = ['maql'] filenames = ['*.maql'] mimetypes = ['text/x-gooddata-maql', 'application/x-gooddata-maql'] flags = re.IGNORECASE tokens = { 'root': [ # IDENTITY (r'IDENTIFIER\b', Name.Builtin), # IDENTIFIER (r'\{[^}]+\}', Name.Variable), # NUMBER (r'[0-9]+(?:\.[0-9]+)?(?:e[+-]?[0-9]{1,3})?', Number), # STRING (r'"', String, 'string-literal'), # RELATION (r'\<\>|\!\=', Operator), (r'\=|\>\=|\>|\<\=|\<', Operator), # := (r'\:\=', Operator), # OBJECT (r'\[[^]]+\]', Name.Variable.Class), # keywords (words(( 'DIMENSION', 'DIMENSIONS', 'BOTTOM', 'METRIC', 'COUNT', 'OTHER', 'FACT', 'WITH', 'TOP', 'OR', 'ATTRIBUTE', 'CREATE', 'PARENT', 'FALSE', 'ROW', 'ROWS', 'FROM', 'ALL', 'AS', 'PF', 'COLUMN', 'COLUMNS', 'DEFINE', 'REPORT', 'LIMIT', 'TABLE', 'LIKE', 'AND', 'BY', 'BETWEEN', 'EXCEPT', 'SELECT', 'MATCH', 'WHERE', 'TRUE', 'FOR', 'IN', 'WITHOUT', 'FILTER', 'ALIAS', 'WHEN', 'NOT', 'ON', 'KEYS', 'KEY', 'FULLSET', 'PRIMARY', 'LABELS', 'LABEL', 'VISUAL', 'TITLE', 'DESCRIPTION', 'FOLDER', 'ALTER', 'DROP', 'ADD', 'DATASET', 'DATATYPE', 'INT', 'BIGINT', 'DOUBLE', 'DATE', 'VARCHAR', 'DECIMAL', 'SYNCHRONIZE', 'TYPE', 'DEFAULT', 'ORDER', 'ASC', 'DESC', 'HYPERLINK', 'INCLUDE', 'TEMPLATE', 'MODIFY'), suffix=r'\b'), Keyword), # FUNCNAME (r'[a-z]\w*\b', Name.Function), # Comments (r'#.*', Comment.Single), # Punctuation (r'[,;()]', Punctuation), # Space is not significant (r'\s+', Text) ], 'string-literal': [ (r'\\[tnrfbae"\\]', String.Escape), (r'"', String, '#pop'), (r'[^\\"]+', String) ], }
MaqlLexer
python
keon__algorithms
algorithms/map/hashtable.py
{ "start": 0, "end": 3168 }
class ____(object): """ HashMap Data Type HashMap() Create a new, empty map. It returns an empty map collection. put(key, val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value. get(key) Given a key, return the value stored in the map or None otherwise. del_(key) or del map[key] Delete the key-value pair from the map using a statement of the form del map[key]. len() Return the number of key-value pairs stored in the map. in Return True for a statement of the form key in map, if the given key is in the map, False otherwise. """ _empty = object() _deleted = object() def __init__(self, size=11): self.size = size self._len = 0 self._keys = [self._empty] * size # keys self._values = [self._empty] * size # values def put(self, key, value): initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty or self._keys[hash_] is self._deleted: # can assign to hash_ index self._keys[hash_] = key self._values[hash_] = value self._len += 1 return elif self._keys[hash_] == key: # key already exists here, assign over self._keys[hash_] = key self._values[hash_] = value return hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full raise ValueError("Table is full") def get(self, key): initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: # That key was never assigned return None elif self._keys[hash_] == key: # key found return self._values[hash_] hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full and wrapped around return None def del_(self, key): initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: # That key was never assigned return None elif self._keys[hash_] == key: # key found, assign with deleted sentinel self._keys[hash_] = self._deleted self._values[hash_] = self._deleted self._len -= 1 return hash_ = self._rehash(hash_) if initial_hash == hash_: # table is full and wrapped around return None def hash(self, key): return key % self.size def _rehash(self, old_hash): """ linear probing """ return (old_hash + 1) % self.size def __getitem__(self, key): return self.get(key) def __delitem__(self, key): return self.del_(key) def __setitem__(self, key, value): self.put(key, value) def __len__(self): return self._len
HashTable
python
pypa__packaging
src/packaging/pylock.py
{ "start": 13525, "end": 14955 }
class ____: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc] def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_wheel = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_wheel.path, package_wheel.url) return package_wheel @dataclass(frozen=True, init=False)
PackageWheel
python
scrapy__scrapy
tests/test_contracts.py
{ "start": 694, "end": 746 }
class ____: url = "http://scrapy.org"
ResponseMock
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/compat.py
{ "start": 569, "end": 3083 }
class ____(OrderedDict): # type: ignore if not hasattr(OrderedDict, 'insert'): def insert(self, pos, key, value): # type: (int, Any, Any) -> None if pos >= len(self): self[key] = value return od = ordereddict() od.update(self) for k in od: del self[k] for index, old_key in enumerate(od): if pos == index: self[key] = value self[old_key] = od[old_key] PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 # replace with f-strings when 3.5 support is dropped # ft = '42' # assert _F('abc {ft!r}', ft=ft) == 'abc %r' % ft # 'abc %r' % ft -> _F('abc {ft!r}' -> f'abc {ft!r}' def _F(s, *superfluous, **kw): # type: (Any, Any, Any) -> Any if superfluous: raise TypeError return s.format(**kw) StringIO = io.StringIO BytesIO = io.BytesIO if False: # MYPY # StreamType = Union[BinaryIO, IO[str], IO[unicode], StringIO] # StreamType = Union[BinaryIO, IO[str], StringIO] # type: ignore StreamType = Any StreamTextType = StreamType # Union[Text, StreamType] VersionType = Union[List[int], str, Tuple[int, int]] builtins_module = 'builtins' def with_metaclass(meta, *bases): # type: (Any, Any) -> Any """Create a base class with a metaclass.""" return meta('NewBase', bases, {}) DBG_TOKEN = 1 DBG_EVENT = 2 DBG_NODE = 4 _debug = None # type: Optional[int] if 'RUAMELDEBUG' in os.environ: _debugx = os.environ.get('RUAMELDEBUG') if _debugx is None: _debug = 0 else: _debug = int(_debugx) if bool(_debug): class ObjectCounter: def __init__(self): # type: () -> None self.map = {} # type: Dict[Any, Any] def __call__(self, k): # type: (Any) -> None self.map[k] = self.map.get(k, 0) + 1 def dump(self): # type: () -> None for k in sorted(self.map): sys.stdout.write('{} -> {}'.format(k, self.map[k])) object_counter = ObjectCounter() # used from yaml util when testing def dbg(val=None): # type: (Any) -> Any global _debug if _debug is None: # set to true or false _debugx = os.environ.get('YAMLDEBUG') if _debugx is None: _debug = 0 else: _debug = int(_debugx) if val is None: return _debug return _debug & val
ordereddict
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/common.py
{ "start": 23620, "end": 40173 }
class ____(Step): """A step to run live tests for a connector.""" context: ConnectorContext skipped_exit_code = 5 accept_extra_params = True local_tests_artifacts_dir = Path("/tmp/live_tests_artifacts") working_directory = "/app" github_user = "octavia-squidington-iii" platform_repo_url = "airbytehq/airbyte-platform-internal" test_suite_to_dir = { LiveTestSuite.ALL: "src/live_tests", LiveTestSuite.REGRESSION: "src/live_tests/regression_tests", LiveTestSuite.VALIDATION: "src/live_tests/validation_tests", } @property def default_params(self) -> STEP_PARAMS: """Default pytest options. Returns: dict: The default pytest options. """ return super().default_params | { "-ra": [], # Show extra test summary info in the report for all but the passed tests "--disable-warnings": [], # Disable warnings in the pytest report "--durations": ["3"], # Show the 3 slowest tests in the report } @property def title(self) -> str: return f"Connector {self.test_suite.title()} Tests" def _test_command(self) -> List[str]: """ The command used to run the tests """ base_command = [ "poetry", "run", "pytest", self.test_dir, "--connector-image", self.connector_image, ] return base_command + self._get_command_options() def _get_command_options(self) -> List[str]: command_options = [] if self.connection_id: command_options += ["--connection-id", self.connection_id] if self.control_version: command_options += ["--control-version", self.control_version] if self.target_version: command_options += ["--target-version", self.target_version] if self.pr_url: command_options += ["--pr-url", self.pr_url] if self.run_id: command_options += ["--run-id", self.run_id] if self.should_read_with_state: command_options += ["--should-read-with-state=1"] if self.disable_proxy: command_options += ["--disable-proxy=1"] if self.test_evaluation_mode: command_options += ["--test-evaluation-mode", self.test_evaluation_mode] if self.selected_streams: command_options += ["--stream", self.selected_streams] command_options += ["--connection-subset", self.connection_subset] return command_options def _run_command_with_proxy(self, command: str) -> List[str]: """ This command: 1. Starts a Google Cloud SQL proxy running on localhost, which is used by the connection-retriever to connect to postgres. This is required for secure access to our internal tools. 2. Gets the PID of the proxy so it can be killed once done. 3. Runs the command that was passed in as input. 4. Kills the proxy, and waits for it to exit. 5. Exits with the command's exit code. We need to explicitly kill the proxy in order to allow the GitHub Action to exit. An alternative that we can consider is to run the proxy as a separate service. (See https://docs.dagger.io/manuals/developer/python/328492/services/ and https://cloud.google.com/sql/docs/postgres/sql-proxy#cloud-sql-auth-proxy-docker-image) """ run_proxy = "./cloud-sql-proxy prod-ab-cloud-proj:us-west3:prod-pgsql-replica --credentials-file /tmp/credentials.json" run_pytest_with_proxy = dedent( f""" {run_proxy} & proxy_pid=$! {command} pytest_exit=$? kill $proxy_pid wait $proxy_pid exit $pytest_exit """ ) return ["bash", "-c", f"'{run_pytest_with_proxy}'"] def __init__(self, context: ConnectorContext) -> None: """Create a step to run live tests for a connector. Args: context (ConnectorContext): The current test context, providing a connector object, a dagger client and a repository directory. """ super().__init__(context) self.connector_image = context.docker_image.split(":")[0] options = self.context.run_step_options.step_params.get(CONNECTOR_TEST_STEP_ID.CONNECTOR_LIVE_TESTS, {}) self.test_suite = self.context.run_step_options.get_item_or_default(options, "test-suite", LiveTestSuite.REGRESSION.value) self.connection_id = self._get_connection_id(options) self.pr_url = self._get_pr_url(options) self.test_dir = self.test_suite_to_dir[LiveTestSuite(self.test_suite)] self.control_version = self.context.run_step_options.get_item_or_default(options, "control-version", None) self.target_version = self.context.run_step_options.get_item_or_default(options, "target-version", "dev") self.should_read_with_state = "should-read-with-state" in options self.disable_proxy = "disable-proxy" in options self.selected_streams = self.context.run_step_options.get_item_or_default(options, "selected-streams", None) self.test_evaluation_mode = "strict" if self.context.connector.metadata.get("supportLevel") == "certified" else "diagnostic" self.connection_subset = self.context.run_step_options.get_item_or_default(options, "connection-subset", "sandboxes") self.run_id = os.getenv("GITHUB_RUN_ID") or str(int(time.time())) def _get_connection_id(self, options: Dict[str, List[Any]]) -> Optional[str]: if self.context.is_pr: connection_id = self._get_connection_from_test_connections() self.logger.info( f"Context is {self.context.ci_context}; got connection_id={connection_id} from metadata.yaml liveTests testConnections." ) else: connection_id = self.context.run_step_options.get_item_or_default(options, "connection-id", None) self.logger.info(f"Context is {self.context.ci_context}; got connection_id={connection_id} from input options.") return connection_id def _get_pr_url(self, options: Dict[str, List[Any]]) -> Optional[str]: if self.context.is_pr: pull_request = self.context.pull_request.url if self.context.pull_request else None self.logger.info(f"Context is {self.context.ci_context}; got pull_request={pull_request} from context.") else: pull_request = self.context.run_step_options.get_item_or_default(options, "pr-url", None) self.logger.info(f"Context is {self.context.ci_context}; got pull_request={pull_request} from input options.") return pull_request def _validate_job_can_run(self) -> None: connector_type = self.context.connector.metadata.get("connectorType") connector_subtype = self.context.connector.metadata.get("connectorSubtype") assert connector_type == "source", f"Live tests can only run against source connectors, got `connectorType={connector_type}`." if connector_subtype == "database": assert ( self.connection_subset == "sandboxes" ), f"Live tests for database sources may only be run against sandbox connections, got `connection_subset={self.connection_subset}`." assert self.connection_id, "`connection-id` is required to run live tests." assert self.pr_url, "`pr_url` is required to run live tests." if self.context.is_pr: connection_id_is_valid = False for test_suite in self.context.connector.metadata.get("connectorTestSuitesOptions", []): if test_suite["suite"] == "liveTests": assert self.connection_id in [ option["id"] for option in test_suite.get("testConnections", []) ], f"Connection ID {self.connection_id} was not in the list of valid test connections." connection_id_is_valid = True break assert connection_id_is_valid, f"Connection ID {self.connection_id} is not a valid sandbox connection ID." def _get_connection_from_test_connections(self) -> Optional[str]: for test_suite in self.context.connector.metadata.get("connectorTestSuitesOptions", []): if test_suite["suite"] == "liveTests": for option in test_suite.get("testConnections", []): connection_id = option["id"] connection_name = option["name"] self.logger.info(f"Using connection name={connection_name}; id={connection_id}") return connection_id return None async def _run(self, connector_under_test_container: Container) -> StepResult: """Run the regression test suite. Args: connector_under_test (Container): The container holding the target connector test image. Returns: StepResult: Failure or success of the regression tests with stdout and stderr. """ try: self._validate_job_can_run() except AssertionError as exc: self.logger.info(f"Skipping live tests for {self.context.connector.technical_name} due to validation error {str(exc)}.") return StepResult( step=self, status=StepStatus.SKIPPED, exc_info=exc, ) container = await self._build_test_container(await connector_under_test_container.id()) command = self._run_command_with_proxy(" ".join(self._test_command())) main_logger.info(f"Running command {command}") container = container.with_(hacks.never_fail_exec(command)) tests_artifacts_dir = str(self.local_tests_artifacts_dir) path_to_report = f"{tests_artifacts_dir}/session_{self.run_id}/report.html" exit_code, stdout, stderr = await get_exec_result(container) try: if ( f"session_{self.run_id}" not in await container.directory(f"{tests_artifacts_dir}").entries() or "report.html" not in await container.directory(f"{tests_artifacts_dir}/session_{self.run_id}").entries() ): main_logger.exception( "The report file was not generated, an unhandled error likely happened during regression test execution, please check the step stderr and stdout for more details" ) regression_test_report = None else: await container.file(path_to_report).export(path_to_report) with open(path_to_report, "r") as fp: regression_test_report = fp.read() except dagger.QueryError as exc: regression_test_report = None main_logger.exception( "The test artifacts directory was not generated, an unhandled error likely happened during setup, please check the step stderr and stdout for more details", exc_info=exc, ) return StepResult( step=self, status=self.get_step_status_from_exit_code(exit_code), stderr=stderr, stdout=stdout, output=container, report=regression_test_report, consider_in_overall_status=False if self.context.is_pr else True, ) async def _build_test_container(self, target_container_id: str) -> Container: """Create a container to run regression tests.""" container = with_poetry(self.context) container_requirements = ["apt-get", "install", "-y", "git", "curl", "docker.io"] if not self.context.is_ci: # Outside of CI we use ssh to get the connection-retriever package from airbyte-platform-internal container_requirements += ["openssh-client"] container = ( container.with_exec(["apt-get", "update"], use_entrypoint=True) .with_exec(container_requirements) .with_exec(["bash", "-c", "curl https://sdk.cloud.google.com | bash"], use_entrypoint=True) .with_env_variable("PATH", "/root/google-cloud-sdk/bin:$PATH", expand=True) .with_mounted_directory("/app", self.context.live_tests_dir) .with_workdir("/app") # Enable dagger-in-dagger .with_unix_socket("/var/run/docker.sock", self.dagger_client.host().unix_socket("/var/run/docker.sock")) .with_env_variable("RUN_IN_AIRBYTE_CI", "1") .with_file( "/tmp/record_obfuscator.py", self.context.get_repo_dir("tools/bin", include=["record_obfuscator.py"]).file("record_obfuscator.py"), ) # The connector being tested is already built and is stored in a location accessible to an inner dagger kicked off by # regression tests. The connector can be found if you know the container ID, so we write the container ID to a file and put # it in the regression test container. This way regression tests will use the already-built connector instead of trying to # build their own. .with_new_file( f"/tmp/{slugify(self.connector_image + ':' + self.target_version)}_container_id.txt", contents=str(target_container_id) ) ) if self.context.is_ci: container = ( container.with_exec( [ "sed", "-i", "-E", rf"s,git@github\.com:{self.platform_repo_url},https://github.com/{self.platform_repo_url}.git,", "pyproject.toml", ], use_entrypoint=True, ) .with_exec( [ "poetry", "source", "add", "--priority=supplemental", "airbyte-platform-internal-source", "https://github.com/airbytehq/airbyte-platform-internal.git", ], use_entrypoint=True, ) .with_secret_variable( "CI_GITHUB_ACCESS_TOKEN", self.context.dagger_client.set_secret( "CI_GITHUB_ACCESS_TOKEN", self.context.ci_github_access_token.value if self.context.ci_github_access_token else "" ), ) .with_exec( [ "/bin/sh", "-c", f"poetry config http-basic.airbyte-platform-internal-source {self.github_user} $CI_GITHUB_ACCESS_TOKEN", ], use_entrypoint=True, ) # Add GCP credentials from the environment and point google to their location (also required for connection-retriever) .with_new_file("/tmp/credentials.json", contents=os.getenv("GCP_INTEGRATION_TESTER_CREDENTIALS", "")) .with_env_variable("GOOGLE_APPLICATION_CREDENTIALS", "/tmp/credentials.json") .with_exec( [ "curl", "-o", "cloud-sql-proxy", "https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.11.0/cloud-sql-proxy.linux.amd64", ], use_entrypoint=True, ) .with_exec(["chmod", "+x", "cloud-sql-proxy"], use_entrypoint=True) .with_env_variable("CI", "1") ) else: container = ( container.with_mounted_file("/root/.ssh/id_rsa", self.dagger_client.host().file(str(Path("~/.ssh/id_rsa").expanduser()))) .with_mounted_file("/root/.ssh/known_hosts", self.dagger_client.host().file(str(Path("~/.ssh/known_hosts").expanduser()))) .with_mounted_file( "/root/.config/gcloud/application_default_credentials.json", self.dagger_client.host().file(str(Path("~/.config/gcloud/application_default_credentials.json").expanduser())), ) ) container = container.with_exec(["poetry", "lock"], use_entrypoint=True).with_exec(["poetry", "install"], use_entrypoint=True) return container
LiveTests
python
PrefectHQ__prefect
src/prefect/_internal/concurrency/cancellation.py
{ "start": 9647, "end": 12214 }
class ____(CancelScope): """ A cancel scope that uses an alarm signal which can interrupt long-running system calls. Only the main thread can be cancelled with an alarm signal, so this scope is only available in the main thread. """ def __enter__(self): super().__enter__() current_thread = threading.current_thread() self._previous_timer = None if current_thread is not threading.main_thread(): raise ValueError( "Alarm based timeouts can only be used in the main thread." ) self._previous_alarm_handler = signal.getsignal(signal.SIGALRM) if self._previous_alarm_handler != signal.SIG_DFL: logger.warning( "%r overriding existing alarm handler %s", self, self._previous_alarm_handler, ) # Capture alarm signals and raise a timeout signal.signal(signal.SIGALRM, self._sigalarm_to_error) # Set a timer to raise an alarm signal if self.timeout is not None: # Use `setitimer` instead of `signal.alarm` for float support; raises a SIGALRM logger.debug("%r set alarm timer for %f seconds", self, self.timeout) self._previous_timer = signal.setitimer(signal.ITIMER_REAL, self.timeout) return self def _sigalarm_to_error(self, *args: object) -> None: logger.debug("%r captured alarm raising as cancelled error", self) if self.cancel(throw=False): shield = _get_thread_shield(threading.main_thread()) if shield.active(): logger.debug("%r thread shield active; delaying exception", self) shield.set_exception(CancelledError()) else: raise CancelledError() def __exit__(self, *_: Any) -> Optional[bool]: retval = super().__exit__(*_) if self.timeout is not None: # Restore the previous timer if TYPE_CHECKING: assert self._previous_timer is not None signal.setitimer(signal.ITIMER_REAL, *self._previous_timer) # Restore the previous signal handler signal.signal(signal.SIGALRM, self._previous_alarm_handler) return retval def cancel(self, throw: bool = True): if not super().cancel(): return False if throw: logger.debug("%r sending alarm signal to main thread", self) os.kill(os.getpid(), signal.SIGALRM) return True
AlarmCancelScope
python
pypa__warehouse
tests/functional/test_notifications.py
{ "start": 109, "end": 2057 }
class ____: def test_unauthed_user(self, webtest): """ Test that locale changes are reflected in the response """ # The default locale is set to English resp = webtest.get("/", status=HTTPStatus.OK) assert LOCALE_ATTR not in resp.headers.getall("Set-Cookie") assert resp.html.find("html").attrs["lang"] == "en" # Change to a different locale resp = webtest.get( "/locale/?locale=es", params={"locale_id": "es"}, status=HTTPStatus.SEE_OTHER, ) # assert that the locale cookie is set in one of the cookies assert f"{LOCALE_ATTR}=es; Path=/" in resp.headers.getall("Set-Cookie") # Follow the redirect and check if the locale is set and flash notice appears next_page = resp.follow(status=HTTPStatus.OK) assert next_page.html.find("html").attrs["lang"] == "es" # Fetch the client-side includes and confirm the flash notice resp = webtest.get("/_includes/unauthed/flash-messages/", status=HTTPStatus.OK) success_message = resp.html.find("span", {"class": "notification-bar__message"}) assert success_message.text != "Locale updated" # Value in Spanish, may change # Switch back to English resp = webtest.get( "/locale/?locale=en", params={"locale_id": "en"}, status=HTTPStatus.SEE_OTHER, ) assert f"{LOCALE_ATTR}=en; Path=/" in resp.headers.getall("Set-Cookie") next_page = resp.follow(status=HTTPStatus.OK) assert next_page.html.find("html").attrs["lang"] == "en" # Fetch the client-side includes and confirm the flash notice resp = webtest.get("/_includes/unauthed/flash-messages/", status=HTTPStatus.OK) success_message = resp.html.find("span", {"class": "notification-bar__message"}) assert success_message.text == "Locale updated"
TestLocale
python
ray-project__ray
python/ray/_private/runtime_env/image_uri.py
{ "start": 5923, "end": 7474 }
class ____(RuntimeEnvPlugin): """Starts worker in container.""" name = "container" def __init__(self, ray_tmp_dir: str): self._ray_tmp_dir = ray_tmp_dir async def create( self, uri: Optional[str], runtime_env: "RuntimeEnv", # noqa: F821 context: RuntimeEnvContext, logger: logging.Logger, ) -> float: if not runtime_env.has_py_container() or not runtime_env.py_container_image(): return self.worker_path = await _create_impl(runtime_env.py_container_image(), logger) def modify_context( self, uris: List[str], runtime_env: "RuntimeEnv", # noqa: F821 context: RuntimeEnvContext, logger: Optional[logging.Logger] = default_logger, ): if not runtime_env.has_py_container() or not runtime_env.py_container_image(): return if runtime_env.py_container_worker_path(): logger.warning( "You are using `container.worker_path`, but the path to " "`default_worker.py` is now automatically detected from the image. " "`container.worker_path` is deprecated and will be removed in future " "versions." ) _modify_context_impl( runtime_env.py_container_image(), runtime_env.py_container_worker_path() or self.worker_path, runtime_env.py_container_run_options(), context, logger, self._ray_tmp_dir, )
ContainerPlugin
python
kubernetes-client__python
kubernetes/client/models/v1_config_map_list.py
{ "start": 383, "end": 6876 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'items': 'list[V1ConfigMap]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1ConfigMapList - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1ConfigMapList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1ConfigMapList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1ConfigMapList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1ConfigMapList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1ConfigMapList. # noqa: E501 Items is the list of ConfigMaps. # noqa: E501 :return: The items of this V1ConfigMapList. # noqa: E501 :rtype: list[V1ConfigMap] """ return self._items @items.setter def items(self, items): """Sets the items of this V1ConfigMapList. Items is the list of ConfigMaps. # noqa: E501 :param items: The items of this V1ConfigMapList. # noqa: E501 :type: list[V1ConfigMap] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1ConfigMapList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1ConfigMapList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1ConfigMapList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1ConfigMapList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1ConfigMapList. # noqa: E501 :return: The metadata of this V1ConfigMapList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1ConfigMapList. :param metadata: The metadata of this V1ConfigMapList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ConfigMapList): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1ConfigMapList): return True return self.to_dict() != other.to_dict()
V1ConfigMapList
python
realpython__materials
python-magic-methods/reader.py
{ "start": 0, "end": 359 }
class ____: def __init__(self, file_path, encoding="utf-8"): self.file_path = file_path self.encoding = encoding def __enter__(self): self.file_obj = open(self.file_path, mode="r", encoding=self.encoding) return self.file_obj def __exit__(self, exc_type, exc_val, exc_tb): self.file_obj.close()
TextFileReader
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB118.py
{ "start": 1050, "end": 1740 }
class ____: def add(x, y): return x + y # OK. op_add3 = lambda x, y=1: x + y op_neg2 = lambda x, y: y - x op_notin = lambda x, y: y not in x op_and = lambda x, y: y and x op_or = lambda x, y: y or x op_in = lambda x, y: x in y op_itemgetter = lambda x: (1, x[1], x[2]) op_itemgetter = lambda x: (x.y, x[1], x[2]) op_itemgetter = lambda x, y: (x[0], y[0]) op_itemgetter = lambda x, y: (x[0], y[0]) op_itemgetter = lambda x: () op_itemgetter = lambda x: (*x[0], x[1]) op_itemgetter = lambda x: (x[0],) op_itemgetter = lambda x: x[x] def op_neg3(x, y): return y - x def op_add4(x, y=1): return x + y def op_add5(x, y): print("op_add5") return x + y # OK
Adder
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/datafusion.py
{ "start": 1481, "end": 1699 }
class ____(BaseGoogleLink): """Helper class for constructing Data Fusion Pipeline link.""" name = "Data Fusion Pipeline" key = "pipeline_conf" format_str = DATAFUSION_PIPELINE_LINK
DataFusionPipelineLink
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 503123, "end": 503846 }
class ____(sgqlc.types.relay.Connection): """The connection type for Commit.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of(CommitEdge), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("Commit"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
CommitHistoryConnection
python
walkccc__LeetCode
solutions/1238. Circular Permutation in Binary Representation/1238.py
{ "start": 0, "end": 137 }
class ____: def circularPermutation(self, n: int, start: int) -> list[int]: return [start ^ i ^ i >> 1 for i in range(1 << n)]
Solution
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 9059, "end": 9133 }
class ____(ProxiedBase): class Meta: proxy = True
ProxyModelBase
python
getsentry__sentry
src/sentry/hybridcloud/models/webhookpayload.py
{ "start": 689, "end": 4599 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded mailbox_name = models.CharField(null=False, blank=False) provider = models.CharField(null=True, blank=True) # Destination attributes # Table is constantly being deleted from so let's make this non-nullable with a default value, since the table should be small at any given point in time. destination_type = models.CharField( choices=DestinationType.choices, null=False, db_default=DestinationType.SENTRY_REGION ) region_name = models.CharField(null=True) # May need to add organization_id in the future for debugging. integration_id = models.BigIntegerField(null=True) date_added = models.DateTimeField(default=timezone.now, null=False) # Scheduling attributes schedule_for = models.DateTimeField(default=THE_PAST, null=False) attempts = models.IntegerField(default=0, null=False) # payload attributes request_method = models.CharField(null=False) request_path = models.CharField(null=False) request_headers = models.TextField() request_body = models.TextField() class Meta: app_label = "hybridcloud" db_table = "hybridcloud_webhookpayload" indexes = ( models.Index(fields=["mailbox_name"]), models.Index(fields=["schedule_for"]), models.Index(fields=["provider"], name="webhookpayload_provider_idx"), models.Index( fields=["mailbox_name", "id"], name="webhookpayload_mailbox_id_idx", ), models.Index( ExpressionWrapper( Case( When(provider="stripe", then=Value(1)), default=Value(10), output_field=IntegerField(), ), output_field=IntegerField(), ), F("id"), name="webhookpayload_priority_idx", ), ) constraints = [ models.CheckConstraint( condition=~Q(destination_type=DestinationType.SENTRY_REGION) | Q(region_name__isnull=False), name="webhookpayload_region_name_not_null", ), ] __repr__ = sane_repr( "mailbox_name", "destination_type", "region_name", "schedule_for", "attempts", "integration_id", "request_method", "request_path", ) @classmethod def get_attributes_from_request( cls, request: HttpRequest, ) -> dict[str, Any]: return dict( request_method=request.method, request_path=request.get_full_path(), request_headers=json.dumps({k: v for k, v in request.headers.items()}), request_body=request.body.decode(encoding="utf-8"), ) @classmethod def create_from_request( cls, *, destination_type: DestinationType, region: str | None, provider: str, identifier: int | str, request: HttpRequest, integration_id: int | None = None, ) -> Self: metrics.incr("hybridcloud.deliver_webhooks.saved") return cls.objects.create( mailbox_name=f"{provider}:{identifier}", provider=provider, destination_type=destination_type, region_name=region, integration_id=integration_id, **cls.get_attributes_from_request(request), ) def schedule_next_attempt(self) -> None: attempts = self.attempts + 1 backoff = BACKOFF_INTERVAL * BACKOFF_RATE**attempts backoff_delta = datetime.timedelta(minutes=min(backoff, 60)) new_time = timezone.now() + backoff_delta self.update(attempts=attempts, schedule_for=max(new_time, self.schedule_for))
WebhookPayload
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 90377, "end": 92893 }
class ____(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. projection_state (`tuple(torch.FloatTensor)`, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` of shape `(batch_size,config.project_dim)`. Text embeddings before the projection layer, used to mimic the last hidden state of the teacher encoder. """ last_hidden_state: Optional[torch.FloatTensor] = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None projection_state: Optional[tuple[torch.FloatTensor]] = None @dataclass
BaseModelOutputWithPoolingAndProjection
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/super9.py
{ "start": 309, "end": 336 }
class ____(Foo[int]): ...
Bar
python
prompt-toolkit__python-prompt-toolkit
tests/test_key_binding.py
{ "start": 530, "end": 6553 }
class ____: def __init__(self): self.called = [] def __getattr__(self, name): def func(event): self.called.append(name) return func @contextmanager def set_dummy_app(): """ Return a context manager that makes sure that this dummy application is active. This is important, because we need an `Application` with `is_done=False` flag, otherwise no keys will be processed. """ with create_pipe_input() as pipe_input: app = Application( layout=Layout(Window()), output=DummyOutput(), input=pipe_input, ) # Don't start background tasks for these tests. The `KeyProcessor` # wants to create a background task for flushing keys. We can ignore it # here for these tests. # This patch is not clean. In the future, when we can use Taskgroups, # the `Application` should pass its task group to the constructor of # `KeyProcessor`. That way, it doesn't have to do a lookup using # `get_app()`. app.create_background_task = lambda *_, **kw: None with set_app(app): yield @pytest.fixture def handlers(): return Handlers() @pytest.fixture def bindings(handlers): bindings = KeyBindings() bindings.add(Keys.ControlX, Keys.ControlC)(handlers.controlx_controlc) bindings.add(Keys.ControlX)(handlers.control_x) bindings.add(Keys.ControlD)(handlers.control_d) bindings.add(Keys.ControlSquareClose, Keys.Any)(handlers.control_square_close_any) return bindings @pytest.fixture def processor(bindings): return KeyProcessor(bindings) def test_remove_bindings(handlers): with set_dummy_app(): h = handlers.controlx_controlc h2 = handlers.controld # Test passing a handler to the remove() function. bindings = KeyBindings() bindings.add(Keys.ControlX, Keys.ControlC)(h) bindings.add(Keys.ControlD)(h2) assert len(bindings.bindings) == 2 bindings.remove(h) assert len(bindings.bindings) == 1 # Test passing a key sequence to the remove() function. bindings = KeyBindings() bindings.add(Keys.ControlX, Keys.ControlC)(h) bindings.add(Keys.ControlD)(h2) assert len(bindings.bindings) == 2 bindings.remove(Keys.ControlX, Keys.ControlC) assert len(bindings.bindings) == 1 def test_feed_simple(processor, handlers): with set_dummy_app(): processor.feed(KeyPress(Keys.ControlX, "\x18")) processor.feed(KeyPress(Keys.ControlC, "\x03")) processor.process_keys() assert handlers.called == ["controlx_controlc"] def test_feed_several(processor, handlers): with set_dummy_app(): # First an unknown key first. processor.feed(KeyPress(Keys.ControlQ, "")) processor.process_keys() assert handlers.called == [] # Followed by a know key sequence. processor.feed(KeyPress(Keys.ControlX, "")) processor.feed(KeyPress(Keys.ControlC, "")) processor.process_keys() assert handlers.called == ["controlx_controlc"] # Followed by another unknown sequence. processor.feed(KeyPress(Keys.ControlR, "")) processor.feed(KeyPress(Keys.ControlS, "")) # Followed again by a know key sequence. processor.feed(KeyPress(Keys.ControlD, "")) processor.process_keys() assert handlers.called == ["controlx_controlc", "control_d"] def test_control_square_closed_any(processor, handlers): with set_dummy_app(): processor.feed(KeyPress(Keys.ControlSquareClose, "")) processor.feed(KeyPress("C", "C")) processor.process_keys() assert handlers.called == ["control_square_close_any"] def test_common_prefix(processor, handlers): with set_dummy_app(): # Sending Control_X should not yet do anything, because there is # another sequence starting with that as well. processor.feed(KeyPress(Keys.ControlX, "")) processor.process_keys() assert handlers.called == [] # When another key is pressed, we know that we did not meant the longer # "ControlX ControlC" sequence and the callbacks are called. processor.feed(KeyPress(Keys.ControlD, "")) processor.process_keys() assert handlers.called == ["control_x", "control_d"] def test_previous_key_sequence(processor): """ test whether we receive the correct previous_key_sequence. """ with set_dummy_app(): events = [] def handler(event): events.append(event) # Build registry. registry = KeyBindings() registry.add("a", "a")(handler) registry.add("b", "b")(handler) processor = KeyProcessor(registry) # Create processor and feed keys. processor.feed(KeyPress("a", "a")) processor.feed(KeyPress("a", "a")) processor.feed(KeyPress("b", "b")) processor.feed(KeyPress("b", "b")) processor.process_keys() # Test. assert len(events) == 2 assert len(events[0].key_sequence) == 2 assert events[0].key_sequence[0].key == "a" assert events[0].key_sequence[0].data == "a" assert events[0].key_sequence[1].key == "a" assert events[0].key_sequence[1].data == "a" assert events[0].previous_key_sequence == [] assert len(events[1].key_sequence) == 2 assert events[1].key_sequence[0].key == "b" assert events[1].key_sequence[0].data == "b" assert events[1].key_sequence[1].key == "b" assert events[1].key_sequence[1].data == "b" assert len(events[1].previous_key_sequence) == 2 assert events[1].previous_key_sequence[0].key == "a" assert events[1].previous_key_sequence[0].data == "a" assert events[1].previous_key_sequence[1].key == "a" assert events[1].previous_key_sequence[1].data == "a"
Handlers
python
ApeWorX__ape
src/ape/types/signatures.py
{ "start": 3415, "end": 3987 }
class ____(_Signature): """ A ECDSA signature (vrs) of a message. """ def recover_signer(msg: SignableMessage, sig: MessageSignature) -> "AddressType": """ Get the address of the signer. Args: msg (:class:`~ape.types.signatures.SignableMessage`): A formatted and signable message. sig (:class:`~ape.types.signatures.MessageSignature`): Signature of the message. Returns: :class:`~ape.types.address.AddressType`: address of message signer. """ return Account.recover_message(msg, sig)
MessageSignature
python
PyCQA__pylint
tests/functional/i/invalid/invalid_enum_extension.py
{ "start": 744, "end": 798 }
class ____(ColorEnum): SAGE = (170, 200, 167)
Pastel
python
walkccc__LeetCode
solutions/1654. Minimum Jumps to Reach Home/1654.py
{ "start": 78, "end": 999 }
class ____: def minimumJumps(self, forbidden: list[int], a: int, b: int, x: int) -> int: furthest = max(x + a + b, max(pos + a + b for pos in forbidden)) seenForward = {pos for pos in forbidden} seenBackward = {pos for pos in forbidden} # (direction, position) q = collections.deque([(Direction.FORWARD, 0)]) ans = 0 while q: for _ in range(len(q)): dir, pos = q.popleft() if pos == x: return ans forward = pos + a backward = pos - b if forward <= furthest and forward not in seenForward: seenForward.add(forward) q.append((Direction.FORWARD, forward)) # It cannot jump backward twice in a row. if dir == Direction.FORWARD and backward >= 0 and backward not in seenBackward: seenBackward.add(backward) q.append((Direction.BACKWARD, backward)) ans += 1 return -1
Solution
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/enums.py
{ "start": 3572, "end": 3752 }
class ____(MemberType): @classmethod def _missing_(cls, value): """inherited""" return super()._missing_(value) # type: ignore[misc]
_SunderMissingInDataType
python
jmcnamara__XlsxWriter
xlsxwriter/test/vml/test_xml_declaration.py
{ "start": 289, "end": 795 }
class ____(unittest.TestCase): """ Test initialisation of the Vml class and call a method. """ def setUp(self): self.fh = StringIO() self.vml = Vml() self.vml._set_filehandle(self.fh) def test_xml_declaration(self): """Test Vml xml_declaration()""" self.vml._xml_declaration() exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n""" got = self.fh.getvalue() self.assertEqual(exp, got)
TestVmlXmlDeclaration
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 7432, "end": 7677 }
class ____(PrefectBaseModel, OperatorMixin): """Filter for subflows of the given flow runs""" any_: Optional[List[UUID]] = Field( default=None, description="A list of flow run parents to include" )
FlowRunFilterParentFlowRunId
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks.py
{ "start": 35929, "end": 37868 }
class ____(session_run_hook.SessionRunHook): """A hook which evaluates `Tensors` at the end of a session.""" def __init__(self, final_ops, final_ops_feed_dict=None): """Initializes `FinalOpHook` with ops to run at the end of the session. Args: final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when running `final_ops_dict`. """ self._final_ops = final_ops self._final_ops_feed_dict = final_ops_feed_dict self._final_ops_values = None @property def final_ops_values(self): return self._final_ops_values def end(self, session): if self._final_ops is not None: try: self._final_ops_values = session.run( self._final_ops, feed_dict=self._final_ops_feed_dict) except (errors.OutOfRangeError, StopIteration) as e: logging.warning( "An OutOfRangeError or StopIteration exception is raised by the " "code in FinalOpsHook. This typically means the Ops running by the " "FinalOpsHook have a dependency back to some input source, which " "should not happen. For example, for metrics in " "tf.estimator.Estimator, all metrics functions return two Ops: " "`value_op` and `update_op`. Estimator.evaluate calls the " "`update_op` for each batch of the data in input source and, once " "it is exhausted, it call the `value_op` to get the metric values. " "The `value_op` here should have dependency back to variables " "reading only, rather than reading another batch from input. " "Otherwise, the `value_op`, executed by `FinalOpsHook`, triggers " "another data reading, which ends OutOfRangeError/StopIteration. " "Please fix that.") raise e @tf_export(v1=["train.FeedFnHook"])
FinalOpsHook
python
sympy__sympy
sympy/logic/boolalg.py
{ "start": 41773, "end": 45463 }
class ____(BooleanFunction): """ If-then-else clause. ``ITE(A, B, C)`` evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer, where A is the select signal. Examples ======== >>> from sympy.logic.boolalg import ITE, And, Xor, Or >>> from sympy.abc import x, y, z >>> ITE(True, False, True) False >>> ITE(Or(True, False), And(True, True), Xor(True, True)) True >>> ITE(x, y, z) ITE(x, y, z) >>> ITE(True, x, y) x >>> ITE(False, x, y) y >>> ITE(x, y, y) y Trying to use non-Boolean args will generate a TypeError: >>> ITE(True, [], ()) Traceback (most recent call last): ... TypeError: expecting bool, Boolean or ITE, not `[]` """ def __new__(cls, *args, **kwargs): from sympy.core.relational import Eq, Ne if len(args) != 3: raise ValueError('expecting exactly 3 args') a, b, c = args # check use of binary symbols if isinstance(a, (Eq, Ne)): # in this context, we can evaluate the Eq/Ne # if one arg is a binary symbol and the other # is true/false b, c = map(as_Boolean, (b, c)) bin_syms = set().union(*[i.binary_symbols for i in (b, c)]) if len(set(a.args) - bin_syms) == 1: # one arg is a binary_symbols _a = a if a.lhs is true: a = a.rhs elif a.rhs is true: a = a.lhs elif a.lhs is false: a = Not(a.rhs) elif a.rhs is false: a = Not(a.lhs) else: # binary can only equal True or False a = false if isinstance(_a, Ne): a = Not(a) else: a, b, c = BooleanFunction.binary_check_and_simplify( a, b, c) rv = None if kwargs.get('evaluate', True): rv = cls.eval(a, b, c) if rv is None: rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False) return rv @classmethod def eval(cls, *args): from sympy.core.relational import Eq, Ne # do the args give a singular result? a, b, c = args if isinstance(a, (Ne, Eq)): _a = a if true in a.args: a = a.lhs if a.rhs is true else a.rhs elif false in a.args: a = Not(a.lhs) if a.rhs is false else Not(a.rhs) else: _a = None if _a is not None and isinstance(_a, Ne): a = Not(a) if a is true: return b if a is false: return c if b == c: return b else: # or maybe the results allow the answer to be expressed # in terms of the condition if b is true and c is false: return a if b is false and c is true: return Not(a) if [a, b, c] != args: return cls(a, b, c, evaluate=False) def to_nnf(self, simplify=True, form=None): a, b, c = self.args return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify, form=form) def _eval_as_set(self): return self.to_nnf().as_set() def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise return Piecewise((args[1], args[0]), (args[2], True))
ITE
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/dbt/pythonic/custom_component_incremental.py
{ "start": 171, "end": 871 }
class ____(DbtProjectComponent): """Custom DbtProjectComponent that handles incremental models with partitions. This is the recommended approach for migrating incremental model logic. """ def execute( self, context: dg.AssetExecutionContext, dbt: DbtCliResource ) -> Iterator: time_window = context.partition_time_window dbt_vars = { "start_date": time_window.start.strftime("%Y-%m-%d"), "end_date": time_window.end.strftime("%Y-%m-%d"), } yield from dbt.cli( ["build", "--vars", json.dumps(dbt_vars)], context=context ).stream() # end_custom_component_incremental
IncrementalDbtProjectComponent
python
getsentry__sentry
tests/sentry/snuba/test_discover_facets_query.py
{ "start": 267, "end": 8638 }
class ____(SnubaTestCase, TestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.min_ago = before_now(minutes=1) self.day_ago = before_now(days=1) def test_invalid_query(self) -> None: with pytest.raises(InvalidSearchQuery): discover.get_facets( "\n", SnubaParams(projects=[self.project], end=self.min_ago, start=self.day_ago), "testing.get-facets-test", ) def test_no_results(self) -> None: results = discover.get_facets( "", SnubaParams(projects=[self.project], end=self.min_ago, start=self.day_ago), "testing.get-facets-test", ) assert results == [] def test_single_project(self) -> None: self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "red", "paying": "1"}, }, project_id=self.project.id, ) self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "blue", "paying": "0"}, }, project_id=self.project.id, ) result = discover.get_facets( "", SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago), "testing.get-facets-test", ) assert len(result) == 5 assert {r.key for r in result} == {"color", "paying", "level"} assert {r.value for r in result} == {"red", "blue", "1", "0", "error"} assert {r.count for r in result} == {1, 2} def test_project_filter(self) -> None: self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "red"}, }, project_id=self.project.id, ) other_project = self.create_project() self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"toy": "train"}, }, project_id=other_project.id, ) params = SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago) result = discover.get_facets("", params, "testing.get-facets-test") keys = {r.key for r in result} assert keys == {"color", "level"} # Query more than one project. params = SnubaParams( projects=[self.project, other_project], start=self.day_ago, end=self.min_ago ) result = discover.get_facets("", params, "testing.get-facets-test") keys = {r.key for r in result} assert keys == {"level", "toy", "color", "project"} projects = [f for f in result if f.key == "project"] assert [p.count for p in projects] == [1, 1] def test_environment_promoted_tag(self) -> None: for env in ("prod", "staging", None): self.store_event( data={ "message": "very bad", "type": "default", "environment": env, "timestamp": before_now(minutes=2).isoformat(), }, project_id=self.project.id, ) result = discover.get_facets( "", SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago), "testing.get-facets-test", ) keys = {r.key for r in result} assert keys == {"environment", "level"} assert {None, "prod", "staging"} == {f.value for f in result if f.key == "environment"} assert {1} == {f.count for f in result if f.key == "environment"} def test_query_string(self) -> None: self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "red"}, }, project_id=self.project.id, ) self.store_event( data={ "message": "oh my", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"toy": "train"}, }, project_id=self.project.id, ) params = SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago) result = discover.get_facets("bad", params, "testing.get-facets-test") keys = {r.key for r in result} assert "color" in keys assert "toy" not in keys result = discover.get_facets("color:red", params, "testing.get-facets-test") keys = {r.key for r in result} assert "color" in keys assert "toy" not in keys def test_query_string_with_aggregate_condition(self) -> None: self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "red"}, }, project_id=self.project.id, ) self.store_event( data={ "message": "oh my", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"toy": "train"}, }, project_id=self.project.id, ) params = SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago) result = discover.get_facets("bad", params, "testing.get-facets-test") keys = {r.key for r in result} assert "color" in keys assert "toy" not in keys result = discover.get_facets("color:red p95():>1", params, "testing.get-facets-test") keys = {r.key for r in result} assert "color" in keys assert "toy" not in keys def test_date_params(self) -> None: self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "red"}, }, project_id=self.project.id, ) self.store_event( data={ "message": "oh my", "type": "default", "timestamp": before_now(days=2).isoformat(), "tags": {"toy": "train"}, }, project_id=self.project.id, ) result = discover.get_facets( "", SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago), "testing.get-facets-test", ) keys = {r.key for r in result} assert "color" in keys assert "toy" not in keys def test_count_sorting(self) -> None: for _ in range(5): self.store_event( data={ "message": "very bad", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "zzz"}, }, project_id=self.project.id, ) # aaa is before zzz, but there's more zzz so it should show up first self.store_event( data={ "message": "oh my", "type": "default", "timestamp": before_now(minutes=2).isoformat(), "tags": {"color": "aaa"}, }, project_id=self.project.id, ) result = discover.get_facets( "", SnubaParams(projects=[self.project], start=self.day_ago, end=self.min_ago), "testing.get-facets-test", ) first = result[0] assert first.key == "color" assert first.value == "zzz" second = result[1] assert second.key == "color" assert second.value == "aaa"
GetFacetsTest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/key_binding/key_bindings.py
{ "start": 19366, "end": 20128 }
class ____(_Proxy): """ KeyBindings class that can dynamically returns any KeyBindings. :param get_key_bindings: Callable that returns a :class:`.KeyBindings` instance. """ def __init__(self, get_key_bindings: Callable[[], KeyBindingsBase | None]) -> None: self.get_key_bindings = get_key_bindings self.__version = 0 self._last_child_version = None self._dummy = KeyBindings() # Empty key bindings. def _update_cache(self) -> None: key_bindings = self.get_key_bindings() or self._dummy assert isinstance(key_bindings, KeyBindingsBase) version = id(key_bindings), key_bindings._version self._bindings2 = key_bindings self._last_version = version
DynamicKeyBindings
python
walkccc__LeetCode
solutions/1375. Number of Times Binary String Is Prefix-Aligned/1375.py
{ "start": 0, "end": 346 }
class ____: def numTimesAllBlue(self, flips: list[int]) -> int: ans = 0 rightmost = 0 for i, flip in enumerate(flips): rightmost = max(rightmost, flip) # max(flips[0..i]) = rightmost = i + 1, # so flips[0..i] is a permutation of 1, 2, ..., i + 1. if rightmost == i + 1: ans += 1 return ans
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/citation_content_block_location_param.py
{ "start": 261, "end": 565 }
class ____(TypedDict, total=False): cited_text: Required[str] document_index: Required[int] document_title: Required[Optional[str]] end_block_index: Required[int] start_block_index: Required[int] type: Required[Literal["content_block_location"]]
CitationContentBlockLocationParam
python
kubernetes-client__python
kubernetes/client/models/v1_limited_priority_level_configuration.py
{ "start": 383, "end": 11019 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'borrowing_limit_percent': 'int', 'lendable_percent': 'int', 'limit_response': 'V1LimitResponse', 'nominal_concurrency_shares': 'int' } attribute_map = { 'borrowing_limit_percent': 'borrowingLimitPercent', 'lendable_percent': 'lendablePercent', 'limit_response': 'limitResponse', 'nominal_concurrency_shares': 'nominalConcurrencyShares' } def __init__(self, borrowing_limit_percent=None, lendable_percent=None, limit_response=None, nominal_concurrency_shares=None, local_vars_configuration=None): # noqa: E501 """V1LimitedPriorityLevelConfiguration - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._borrowing_limit_percent = None self._lendable_percent = None self._limit_response = None self._nominal_concurrency_shares = None self.discriminator = None if borrowing_limit_percent is not None: self.borrowing_limit_percent = borrowing_limit_percent if lendable_percent is not None: self.lendable_percent = lendable_percent if limit_response is not None: self.limit_response = limit_response if nominal_concurrency_shares is not None: self.nominal_concurrency_shares = nominal_concurrency_shares @property def borrowing_limit_percent(self): """Gets the borrowing_limit_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 `borrowingLimitPercent`, if present, configures a limit on how many seats this priority level can borrow from other priority levels. The limit is known as this level's BorrowingConcurrencyLimit (BorrowingCL) and is a limit on the total number of seats that this level may borrow at any one time. This field holds the ratio of that limit to the level's nominal concurrency limit. When this field is non-nil, it must hold a non-negative integer and the limit is calculated as follows. BorrowingCL(i) = round( NominalCL(i) * borrowingLimitPercent(i)/100.0 ) The value of this field can be more than 100, implying that this priority level can borrow a number of seats that is greater than its own nominal concurrency limit (NominalCL). When this field is left `nil`, the limit is effectively infinite. # noqa: E501 :return: The borrowing_limit_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :rtype: int """ return self._borrowing_limit_percent @borrowing_limit_percent.setter def borrowing_limit_percent(self, borrowing_limit_percent): """Sets the borrowing_limit_percent of this V1LimitedPriorityLevelConfiguration. `borrowingLimitPercent`, if present, configures a limit on how many seats this priority level can borrow from other priority levels. The limit is known as this level's BorrowingConcurrencyLimit (BorrowingCL) and is a limit on the total number of seats that this level may borrow at any one time. This field holds the ratio of that limit to the level's nominal concurrency limit. When this field is non-nil, it must hold a non-negative integer and the limit is calculated as follows. BorrowingCL(i) = round( NominalCL(i) * borrowingLimitPercent(i)/100.0 ) The value of this field can be more than 100, implying that this priority level can borrow a number of seats that is greater than its own nominal concurrency limit (NominalCL). When this field is left `nil`, the limit is effectively infinite. # noqa: E501 :param borrowing_limit_percent: The borrowing_limit_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :type: int """ self._borrowing_limit_percent = borrowing_limit_percent @property def lendable_percent(self): """Gets the lendable_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 `lendablePercent` prescribes the fraction of the level's NominalCL that can be borrowed by other priority levels. The value of this field must be between 0 and 100, inclusive, and it defaults to 0. The number of seats that other levels can borrow from this level, known as this level's LendableConcurrencyLimit (LendableCL), is defined as follows. LendableCL(i) = round( NominalCL(i) * lendablePercent(i)/100.0 ) # noqa: E501 :return: The lendable_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :rtype: int """ return self._lendable_percent @lendable_percent.setter def lendable_percent(self, lendable_percent): """Sets the lendable_percent of this V1LimitedPriorityLevelConfiguration. `lendablePercent` prescribes the fraction of the level's NominalCL that can be borrowed by other priority levels. The value of this field must be between 0 and 100, inclusive, and it defaults to 0. The number of seats that other levels can borrow from this level, known as this level's LendableConcurrencyLimit (LendableCL), is defined as follows. LendableCL(i) = round( NominalCL(i) * lendablePercent(i)/100.0 ) # noqa: E501 :param lendable_percent: The lendable_percent of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :type: int """ self._lendable_percent = lendable_percent @property def limit_response(self): """Gets the limit_response of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :return: The limit_response of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :rtype: V1LimitResponse """ return self._limit_response @limit_response.setter def limit_response(self, limit_response): """Sets the limit_response of this V1LimitedPriorityLevelConfiguration. :param limit_response: The limit_response of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :type: V1LimitResponse """ self._limit_response = limit_response @property def nominal_concurrency_shares(self): """Gets the nominal_concurrency_shares of this V1LimitedPriorityLevelConfiguration. # noqa: E501 `nominalConcurrencyShares` (NCS) contributes to the computation of the NominalConcurrencyLimit (NominalCL) of this level. This is the number of execution seats available at this priority level. This is used both for requests dispatched from this priority level as well as requests dispatched from other priority levels borrowing seats from this level. The server's concurrency limit (ServerCL) is divided among the Limited priority levels in proportion to their NCS values: NominalCL(i) = ceil( ServerCL * NCS(i) / sum_ncs ) sum_ncs = sum[priority level k] NCS(k) Bigger numbers mean a larger nominal concurrency limit, at the expense of every other priority level. If not specified, this field defaults to a value of 30. Setting this field to zero supports the construction of a \"jail\" for this priority level that is used to hold some request(s) # noqa: E501 :return: The nominal_concurrency_shares of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :rtype: int """ return self._nominal_concurrency_shares @nominal_concurrency_shares.setter def nominal_concurrency_shares(self, nominal_concurrency_shares): """Sets the nominal_concurrency_shares of this V1LimitedPriorityLevelConfiguration. `nominalConcurrencyShares` (NCS) contributes to the computation of the NominalConcurrencyLimit (NominalCL) of this level. This is the number of execution seats available at this priority level. This is used both for requests dispatched from this priority level as well as requests dispatched from other priority levels borrowing seats from this level. The server's concurrency limit (ServerCL) is divided among the Limited priority levels in proportion to their NCS values: NominalCL(i) = ceil( ServerCL * NCS(i) / sum_ncs ) sum_ncs = sum[priority level k] NCS(k) Bigger numbers mean a larger nominal concurrency limit, at the expense of every other priority level. If not specified, this field defaults to a value of 30. Setting this field to zero supports the construction of a \"jail\" for this priority level that is used to hold some request(s) # noqa: E501 :param nominal_concurrency_shares: The nominal_concurrency_shares of this V1LimitedPriorityLevelConfiguration. # noqa: E501 :type: int """ self._nominal_concurrency_shares = nominal_concurrency_shares def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1LimitedPriorityLevelConfiguration): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1LimitedPriorityLevelConfiguration): return True return self.to_dict() != other.to_dict()
V1LimitedPriorityLevelConfiguration
python
python-openxml__python-docx
src/docx/oxml/numbering.py
{ "start": 330, "end": 1381 }
class ____(BaseOxmlElement): """``<w:num>`` element, which represents a concrete list definition instance, having a required child <w:abstractNumId> that references an abstract numbering definition that defines most of the formatting details.""" abstractNumId = OneAndOnlyOne("w:abstractNumId") lvlOverride = ZeroOrMore("w:lvlOverride") numId = RequiredAttribute("w:numId", ST_DecimalNumber) def add_lvlOverride(self, ilvl): """Return a newly added CT_NumLvl (<w:lvlOverride>) element having its ``ilvl`` attribute set to `ilvl`.""" return self._add_lvlOverride(ilvl=ilvl) @classmethod def new(cls, num_id, abstractNum_id): """Return a new ``<w:num>`` element having numId of `num_id` and having a ``<w:abstractNumId>`` child with val attribute set to `abstractNum_id`.""" num = OxmlElement("w:num") num.numId = num_id abstractNumId = CT_DecimalNumber.new("w:abstractNumId", abstractNum_id) num.append(abstractNumId) return num
CT_Num
python
doocs__leetcode
solution/3400-3499/3457.Eat Pizzas!/Solution.py
{ "start": 0, "end": 341 }
class ____: def maxWeight(self, pizzas: List[int]) -> int: days = len(pizzas) // 4 pizzas.sort() odd = (days + 1) // 2 even = days - odd ans = sum(pizzas[-odd:]) i = len(pizzas) - odd - 2 for _ in range(even): ans += pizzas[i] i -= 2 return ans
Solution
python
plotly__plotly.py
plotly/graph_objs/layout/polar/radialaxis/_title.py
{ "start": 235, "end": 2897 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.polar.radialaxis" _path_str = "layout.polar.radialaxis.title" _valid_props = {"font", "text"} @property def font(self): """ Sets this axis' title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.polar.radialaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.layout.polar.radialaxis.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def text(self): """ Sets the title of this axis. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this axis' title font. text Sets the title of this axis. """ def __init__(self, arg=None, font=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.polar.r adialaxis.Title` font Sets this axis' title font. text Sets the title of this axis. Returns ------- Title """ super().__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.layout.polar.radialaxis.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.polar.radialaxis.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 511519, "end": 514623 }
class ____(Request): """ Request to stop running tasks :param ids: IDs of the tasks to stop :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str :param force: If not true, call fails if the task status is not 'in_progress' :type force: bool """ _service = "tasks" _action = "stop_many" _version = "2.23" _schema = { "definitions": {}, "properties": { "force": { "default": False, "description": "If not true, call fails if the task status is not 'in_progress'", "type": "boolean", }, "ids": { "description": "IDs of the tasks to stop", "items": {"type": "string"}, "type": "array", }, "status_message": { "description": "Extra information regarding status change", "type": "string", }, "status_reason": { "description": "Reason for status change", "type": "string", }, }, "required": ["ids"], "type": "object", } def __init__( self, ids, status_reason=None, status_message=None, force=False, **kwargs ): super(StopManyRequest, self).__init__(**kwargs) self.ids = ids self.status_reason = status_reason self.status_message = status_message self.force = force @schema_property("ids") def ids(self): return self._property_ids @ids.setter def ids(self, value): if value is None: self._property_ids = None return self.assert_isinstance(value, "ids", (list, tuple)) self.assert_isinstance(value, "ids", six.string_types, is_array=True) self._property_ids = value @schema_property("status_reason") def status_reason(self): return self._property_status_reason @status_reason.setter def status_reason(self, value): if value is None: self._property_status_reason = None return self.assert_isinstance(value, "status_reason", six.string_types) self._property_status_reason = value @schema_property("status_message") def status_message(self): return self._property_status_message @status_message.setter def status_message(self, value): if value is None: self._property_status_message = None return self.assert_isinstance(value, "status_message", six.string_types) self._property_status_message = value @schema_property("force") def force(self): return self._property_force @force.setter def force(self, value): if value is None: self._property_force = None return self.assert_isinstance(value, "force", (bool,)) self._property_force = value
StopManyRequest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/table.py
{ "start": 2155, "end": 2840 }
class ____(graphene.ObjectType): columnName = graphene.NonNull(graphene.String) columnDeps = non_null_list(GrapheneTableColumnDep) class Meta: name = "TableColumnLineageEntry" def __init__(self, column_name: str, column_deps: Sequence["TableColumnDep"]): super().__init__( columnName=column_name, columnDeps=[GrapheneTableColumnDep(column_dep) for column_dep in column_deps], ) types = [ GrapheneTable, GrapheneTableSchema, GrapheneTableColumn, GrapheneTableColumnConstraints, GrapheneTableConstraints, GrapheneTableColumnDep, GrapheneTableColumnLineageEntry, ]
GrapheneTableColumnLineageEntry
python
getsentry__sentry
src/sentry/apidocs/extensions.py
{ "start": 2146, "end": 2772 }
class ____(OpenApiSerializerExtension): """ This extension is used for the `inline_sentry_response_serializer` utils function and will simply resolve the type passed into the function to an OpenAPI schema. """ priority = 0 target_class = "sentry.apidocs.utils._RawSchema" match_subclasses = True def get_name(self, auto_schema: AutoSchema, direction: Direction) -> str | None: return self.target.__name__ def map_serializer(self, auto_schema: AutoSchema, direction: Direction) -> Any: return resolve_type_hint(self.target.typeSchema)
SentryInlineResponseSerializerExtension
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowing4.py
{ "start": 149, "end": 354 }
class ____: def method1(self): pass def good(b: C | None) -> None: a = b if a: a.method1() def bad(b: C | None) -> None: if c := b: c.method1() b.method1()
C
python
encode__django-rest-framework
tests/test_validators.py
{ "start": 32372, "end": 34540 }
class ____(TestCase): def setUp(self): self.instance = UniqueForDateModel.objects.create( slug='existing', published='2000-01-01' ) def test_repr(self): serializer = UniqueForDateSerializer() expected = dedent(""" UniqueForDateSerializer(): id = IntegerField(label='ID', read_only=True) slug = CharField(max_length=100) published = DateField(required=True) class Meta: validators = [<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>] """) assert repr(serializer) == expected def test_is_not_unique_for_date(self): """ Failing unique for date validation should result in field error. """ data = {'slug': 'existing', 'published': '2000-01-01'} serializer = UniqueForDateSerializer(data=data) assert not serializer.is_valid() assert serializer.errors == { 'slug': ['This field must be unique for the "published" date.'] } def test_is_unique_for_date(self): """ Passing unique for date validation. """ data = {'slug': 'existing', 'published': '2000-01-02'} serializer = UniqueForDateSerializer(data=data) assert serializer.is_valid() assert serializer.validated_data == { 'slug': 'existing', 'published': datetime.date(2000, 1, 2) } def test_updated_instance_excluded_from_unique_for_date(self): """ When performing an update, the existing instance does not count as a match against unique_for_date. """ data = {'slug': 'existing', 'published': '2000-01-01'} serializer = UniqueForDateSerializer(instance=self.instance, data=data) assert serializer.is_valid() assert serializer.validated_data == { 'slug': 'existing', 'published': datetime.date(2000, 1, 1) } # Tests for `UniqueForMonthValidator` # ----------------------------------
TestUniquenessForDateValidation
python
faif__python-patterns
patterns/behavioral/strategy.py
{ "start": 1220, "end": 2716 }
class ____: discount_strategy = DiscountStrategyValidator() def __init__(self, price: float, discount_strategy: Callable = None) -> None: self.price: float = price self.discount_strategy = discount_strategy def apply_discount(self) -> float: if self.discount_strategy: discount = self.discount_strategy(self) else: discount = 0 return self.price - discount def __repr__(self) -> str: strategy = getattr(self.discount_strategy, "__name__", None) return f"<Order price: {self.price} with discount strategy: {strategy}>" def ten_percent_discount(order: Order) -> float: return order.price * 0.10 def on_sale_discount(order: Order) -> float: return order.price * 0.25 + 20 def main(): """ >>> order = Order(100, discount_strategy=ten_percent_discount) >>> print(order) <Order price: 100 with discount strategy: ten_percent_discount> >>> print(order.apply_discount()) 90.0 >>> order = Order(100, discount_strategy=on_sale_discount) >>> print(order) <Order price: 100 with discount strategy: on_sale_discount> >>> print(order.apply_discount()) 55.0 >>> order = Order(10, discount_strategy=on_sale_discount) Discount cannot be applied due to negative price resulting. on_sale_discount >>> print(order) <Order price: 10 with discount strategy: None> """ if __name__ == "__main__": import doctest doctest.testmod()
Order
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/95_annotation_class_multiline.py
{ "start": 0, "end": 47 }
class ____(): x = 5; y: Optional['C'] = None
F
python
pytorch__pytorch
test/distributions/test_distributions.py
{ "start": 263553, "end": 265675 }
class ____(DistributionsTestCase): def setUp(self): super().setUp() # ContinuousBernoulli is not tested because log_prob is not computed simply # from 'logits', but 'probs' is also needed self.examples = [ e for e in _get_examples() if e.Dist in (Categorical, OneHotCategorical, Bernoulli, Binomial, Multinomial) ] def test_lazy_logits_initialization(self): for Dist, params in self.examples: param = params[0].copy() if "probs" not in param: continue probs = param.pop("probs") param["logits"] = probs_to_logits(probs) dist = Dist(**param) # Create new instance to generate a valid sample dist.log_prob(Dist(**param).sample()) message = f"Failed for {Dist.__name__} example 0/{len(params)}" self.assertNotIn("probs", dist.__dict__, msg=message) try: dist.enumerate_support() except NotImplementedError: pass self.assertNotIn("probs", dist.__dict__, msg=message) _ = (dist.batch_shape, dist.event_shape) self.assertNotIn("probs", dist.__dict__, msg=message) def test_lazy_probs_initialization(self): for Dist, params in self.examples: param = params[0].copy() if "probs" not in param: continue dist = Dist(**param) dist.sample() message = f"Failed for {Dist.__name__} example 0/{len(params)}" self.assertNotIn("logits", dist.__dict__, msg=message) try: dist.enumerate_support() except NotImplementedError: pass self.assertNotIn("logits", dist.__dict__, msg=message) _ = (dist.batch_shape, dist.event_shape) self.assertNotIn("logits", dist.__dict__, msg=message) @unittest.skipIf(not TEST_NUMPY, "NumPy not found") @skipIfTorchDynamo("FIXME: Tries to trace through SciPy and fails")
TestLazyLogitsInitialization
python
eventlet__eventlet
eventlet/websocket.py
{ "start": 19737, "end": 19922 }
class ____(Exception): def __init__(self, status, message): super().__init__(status, message) self.message = message self.status = status
FailedConnectionError
python
Netflix__metaflow
test/core/tests/recursive_switch.py
{ "start": 63, "end": 769 }
class ____(MetaflowTest): PRIORITY = 2 ONLY_GRAPHS = ["recursive_switch"] @steps(0, ["start"], required=True) def step_start(self): self.count = 0 self.max_iterations = 10 @steps(0, ["loop"], required=True) def step_loop(self): self.count += 1 self.loop_status = "continue" if self.count < self.max_iterations else "exit" @steps(0, ["exit"], required=True) def step_exit(self): assert_equals(10, self.count) @steps(1, ["end"], required=True) def step_end(self): assert_equals(10, self.count) def check_results(self, flow, checker): checker.assert_artifact("exit_loop", "count", 10)
RecursiveSwitchFlowTest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/utils.py
{ "start": 2995, "end": 8631 }
class ____(Dict[str, int]): """ Cache for wcwidth sizes. """ LONG_STRING_MIN_LEN = 64 # Minimum string length for considering it long. MAX_LONG_STRINGS = 16 # Maximum number of long strings to remember. def __init__(self) -> None: super().__init__() # Keep track of the "long" strings in this cache. self._long_strings: deque[str] = deque() def __missing__(self, string: str) -> int: # Note: We use the `max(0, ...` because some non printable control # characters, like e.g. Ctrl-underscore get a -1 wcwidth value. # It can be possible that these characters end up in the input # text. result: int if len(string) == 1: result = max(0, wcwidth(string)) else: result = sum(self[c] for c in string) # Store in cache. self[string] = result # Rotate long strings. # (It's hard to tell what we can consider short...) if len(string) > self.LONG_STRING_MIN_LEN: long_strings = self._long_strings long_strings.append(string) if len(long_strings) > self.MAX_LONG_STRINGS: key_to_remove = long_strings.popleft() if key_to_remove in self: del self[key_to_remove] return result _CHAR_SIZES_CACHE = _CharSizesCache() def get_cwidth(string: str) -> int: """ Return width of a string. Wrapper around ``wcwidth``. """ return _CHAR_SIZES_CACHE[string] def suspend_to_background_supported() -> bool: """ Returns `True` when the Python implementation supports suspend-to-background. This is typically `False' on Windows systems. """ return hasattr(signal, "SIGTSTP") def is_windows() -> bool: """ True when we are using Windows. """ return sys.platform == "win32" # Not 'darwin' or 'linux2' def is_windows_vt100_supported() -> bool: """ True when we are using Windows, but VT100 escape sequences are supported. """ if sys.platform == "win32": # Import needs to be inline. Windows libraries are not always available. from prompt_toolkit.output.windows10 import is_win_vt100_enabled return is_win_vt100_enabled() return False def is_conemu_ansi() -> bool: """ True when the ConEmu Windows console is used. """ return sys.platform == "win32" and os.environ.get("ConEmuANSI", "OFF") == "ON" def in_main_thread() -> bool: """ True when the current thread is the main thread. """ return threading.current_thread().__class__.__name__ == "_MainThread" def get_bell_environment_variable() -> bool: """ True if env variable is set to true (true, TRUE, True, 1). """ value = os.environ.get("PROMPT_TOOLKIT_BELL", "true") return value.lower() in ("1", "true") def get_term_environment_variable() -> str: "Return the $TERM environment variable." return os.environ.get("TERM", "") _T = TypeVar("_T") def take_using_weights( items: list[_T], weights: list[int] ) -> Generator[_T, None, None]: """ Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. take_using_weights(['A', 'B', 'C'], [5, 10, 20]) :param items: List of items to take from. :param weights: Integers representing the weight. (Numbers have to be integers, not floats.) """ assert len(items) == len(weights) assert len(items) > 0 # Remove items with zero-weight. items2 = [] weights2 = [] for item, w in zip(items, weights): if w > 0: items2.append(item) weights2.append(w) items = items2 weights = weights2 # Make sure that we have some items left. if not items: raise ValueError("Did't got any items with a positive weight.") # already_taken = [0 for i in items] item_count = len(items) max_weight = max(weights) i = 0 while True: # Each iteration of this loop, we fill up until by (total_weight/max_weight). adding = True while adding: adding = False for item_i, item, weight in zip(range(item_count), items, weights): if already_taken[item_i] < i * weight / float(max_weight): yield item already_taken[item_i] += 1 adding = True i += 1 def to_str(value: Callable[[], str] | str) -> str: "Turn callable or string into string." if callable(value): return to_str(value()) else: return str(value) def to_int(value: Callable[[], int] | int) -> int: "Turn callable or int into int." if callable(value): return to_int(value()) else: return int(value) AnyFloat = Union[Callable[[], float], float] def to_float(value: AnyFloat) -> float: "Turn callable or float into float." if callable(value): return to_float(value()) else: return float(value) def is_dumb_terminal(term: str | None = None) -> bool: """ True if this terminal type is considered "dumb". If so, we should fall back to the simplest possible form of line editing, without cursor positioning and color support. """ if term is None: return is_dumb_terminal(os.environ.get("TERM", "")) return term.lower() in ["dumb", "unknown"]
_CharSizesCache
python
Lightning-AI__lightning
src/lightning/pytorch/callbacks/checkpoint.py
{ "start": 60, "end": 361 }
class ____(Callback): r"""This is the base class for model checkpointing. Expert users may want to subclass it in case of writing custom :class:`~lightning.pytorch.callbacks.Checkpoint` callback, so that the trainer recognizes the custom class as a checkpointing callback. """
Checkpoint
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_any.py
{ "start": 1300, "end": 2021 }
class ____: def test_valid(self) -> None: prop = bcpa.Any() assert prop.is_valid(None) assert prop.is_valid(False) assert prop.is_valid(True) assert prop.is_valid(0) assert prop.is_valid(1) assert prop.is_valid(0.0) assert prop.is_valid(1.0) assert prop.is_valid(1.0+1.0j) assert prop.is_valid("") assert prop.is_valid(()) assert prop.is_valid([]) assert prop.is_valid({}) assert prop.is_valid(_TestHasProps()) assert prop.is_valid(_TestModel()) def test_invalid(self) -> None: pass def test_has_ref(self) -> None: prop = bcpa.Any() assert not prop.has_ref
Test_Any
python
walkccc__LeetCode
solutions/2464. Minimum Subarrays in a Valid Split/2464.py
{ "start": 0, "end": 393 }
class ____: def validSubarraySplit(self, nums: list[int]) -> int: # dp[i] := the minimum number of subarrays to validly split nums[0..i] dp = [math.inf] * len(nums) for i, num in enumerate(nums): for j in range(i + 1): if math.gcd(nums[j], num) > 1: dp[i] = min(dp[i], 1 if j == 0 else dp[j - 1] + 1) return -1 if dp[-1] == math.inf else dp[-1]
Solution
python
django-extensions__django-extensions
tests/management/commands/test_graph_models.py
{ "start": 1018, "end": 7528 }
class ____(TestCase): def test_graph_models_no_output_options(self): # Given no output-related options, default to output a Dotfile stdout = StringIO() call_command("graph_models", all_applications=True, stdout=stdout) assert_looks_like_dotfile(stdout.getvalue()) def test_graph_models_dot_option_to_stdout(self): # --dot set but --output not set stdout = StringIO() call_command("graph_models", all_applications=True, dot=True, stdout=stdout) assert_looks_like_dotfile(stdout.getvalue()) def test_graph_models_dot_option_to_file(self): # --dot set and --output set stdout = StringIO() with temp_output_file(".dot") as tmpfname: call_command( "graph_models", all_applications=True, dot=True, output=tmpfname, stdout=stdout, ) with open(tmpfname, "r") as outfile: foutput = outfile.read() assert_looks_like_dotfile(foutput) assert stdout.getvalue() == "" def test_graph_models_dot_extensions_to_file(self): # --dot not set and --output set stdout = StringIO() with temp_output_file(".dot") as tmpfname: call_command( "graph_models", all_applications=True, output=tmpfname, stdout=stdout ) with open(tmpfname, "r") as outfile: foutput = outfile.read() assert_looks_like_dotfile(foutput) assert stdout.getvalue() == "" def test_graph_models_dot_option_trumps_json_file_extension(self): # --dot set and --output set to filename ending with .json # assert that --dot option trumps .json file extension stdout = StringIO() with temp_output_file(".json") as tmpfname: call_command( "graph_models", all_applications=True, dot=True, output=tmpfname, stdout=stdout, ) with open(tmpfname, "r") as outfile: foutput = outfile.read() assert_looks_like_dotfile(foutput) assert stdout.getvalue() == "" def test_graph_models_json_option_to_stdout(self): # --json set but --output not set out = StringIO() call_command("graph_models", all_applications=True, json=True, stdout=out) output = out.getvalue() assert_looks_like_jsonfile(output) def test_graph_models_json_option_to_file(self): # --dot set and --output set stdout = StringIO() with temp_output_file(".json") as tmpfname: call_command( "graph_models", all_applications=True, json=True, output=tmpfname, stdout=stdout, ) with open(tmpfname, "r") as outfile: foutput = outfile.read() assert_looks_like_jsonfile(foutput) assert stdout.getvalue() == "" def test_graph_models_pydot_without_file(self): # use of --pydot requires specifying output file with self.assertRaises(CommandError): call_command("graph_models", all_applications=True, pydot=True) def test_graph_models_pygraphviz_without_file(self): # use of --pygraphviz requires specifying output file with self.assertRaises(CommandError): call_command("graph_models", all_applications=True, pygraphviz=True) def test_graph_models_relation_fields_only(self): # use of --relation-fields-only ignores all non-relation-fields stdout = StringIO() call_command("graph_models", all_applications=True, stdout=stdout, json=True) with_no_flag = json.loads(stdout.getvalue()) stdout = StringIO() call_command( "graph_models", all_applications=True, relation_fields_only=True, stdout=stdout, json=True, ) with_flag = json.loads(stdout.getvalue()) # delete all entries for fields that do not display relations for graph_idx, graph in reversed(list(enumerate(with_no_flag["graphs"]))): for model_idx, model in reversed(list(enumerate(graph["models"]))): for field_idx, field in reversed(list(enumerate(model["fields"]))): if ( field["type"] not in ["ForeignKey (id)", "AutoField", "OneToOneField (id)"] and not field["primary_key"] ): del with_no_flag["graphs"][graph_idx]["models"][model_idx][ "fields" ][field_idx] # assert that manually deleting all non-relation-fields is same as using the flag self.assertEqual(with_no_flag, with_flag) def test_disable_abstract_fields_not_active(): out = StringIO() call_command( "graph_models", "django_extensions", include_models=["AbstractInheritanceTestModelChild"], disable_abstract_fields=False, stdout=out, ) output = out.getvalue() assert "my_field_that_my_child_will_inherit" in output def test_disable_abstract_fields_active(): out = StringIO() call_command( "graph_models", "django_extensions", include_models=["AbstractInheritanceTestModelChild"], disable_abstract_fields=True, stdout=out, ) output = out.getvalue() assert "my_field_that_my_child_will_inherit" not in output def test_exclude_models_hides_relationships(): """Expose bug #1229 where excluded models appear in relationships. They are replaced with an underscore, but the relationship is still there. """ out = StringIO() call_command( "graph_models", "django_extensions", exclude_models=["Personality", "Note"], stdout=out, ) output = out.getvalue() assert "tests_testapp_models_Person -> tests_testapp_models_Name" in output assert "tests_testapp_models_Person -> _" not in output def test_hide_edge_labels(): out = StringIO() call_command( "graph_models", "django_extensions", all_applications=True, hide_edge_labels=True, stdout=out, ) output = out.getvalue() assert not re.search(r'\[label=\"[a-zA-Z]+"\]', output)
GraphModelsOutputTests
python
numpy__numpy
numpy/matrixlib/tests/test_matrix_linalg.py
{ "start": 1821, "end": 1883 }
class ____(LstsqCases, MatrixTestCase): pass
TestLstsqMatrix
python
neetcode-gh__leetcode
python/1849-splitting-a-string-into-descending-consecutive-values.py
{ "start": 0, "end": 515 }
class ____: def splitString(self, s: str) -> bool: def dfs(index, prev): if index == len(s): return True for j in range(index, len(s)): val = int(s[index:j+1]) if val + 1 == prev and dfs(j+1, val): return True return False for i in range(len(s) - 1): val = int(s[:i + 1]) if dfs(i+1, val): return True return False
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 413729, "end": 419780 }
class ____(Request): """ Update task's runtime parameters :param task: ID of the task :type task: str :param name: Task name Unique within the company. :type name: str :param tags: User-defined tags list :type tags: Sequence[str] :param system_tags: System tags list. This field is reserved for system use, please don't use it. :type system_tags: Sequence[str] :param comment: Free text comment :type comment: str :param project: Project ID of the project to which this task is assigned :type project: str :param output__error: Free text error :type output__error: str :param created: Task creation time (UTC) :type created: datetime.datetime """ _service = "tasks" _action = "update" _version = "2.20" _schema = { "definitions": {}, "properties": { "comment": {"description": "Free text comment ", "type": "string"}, "created": { "description": "Task creation time (UTC) ", "format": "date-time", "type": "string", }, "name": { "description": "Task name Unique within the company.", "type": "string", }, "output__error": {"description": "Free text error", "type": "string"}, "project": { "description": "Project ID of the project to which this task is assigned", "type": "string", }, "system_tags": { "description": "System tags list. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": "array", }, "tags": { "description": "User-defined tags list", "items": {"type": "string"}, "type": "array", }, "task": {"description": "ID of the task", "type": "string"}, }, "required": ["task"], "type": "object", } def __init__( self, task: str, name: Optional[str] = None, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, comment: Optional[str] = None, project: Optional[str] = None, output__error: Optional[str] = None, created: Optional[str] = None, **kwargs: Any ) -> None: super(UpdateRequest, self).__init__(**kwargs) self.task = task self.name = name self.tags = tags self.system_tags = system_tags self.comment = comment self.project = project self.output__error = output__error self.created = created @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("name") def name(self) -> Optional[str]: return self._property_name @name.setter def name(self, value: Optional[str]) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("tags") def tags(self) -> Optional[List[str]]: return self._property_tags @tags.setter def tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_tags = None return self.assert_isinstance(value, "tags", (list, tuple)) self.assert_isinstance(value, "tags", six.string_types, is_array=True) self._property_tags = value @schema_property("system_tags") def system_tags(self) -> Optional[List[str]]: return self._property_system_tags @system_tags.setter def system_tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_system_tags = None return self.assert_isinstance(value, "system_tags", (list, tuple)) self.assert_isinstance(value, "system_tags", six.string_types, is_array=True) self._property_system_tags = value @schema_property("comment") def comment(self) -> Optional[str]: return self._property_comment @comment.setter def comment(self, value: Optional[str]) -> None: if value is None: self._property_comment = None return self.assert_isinstance(value, "comment", six.string_types) self._property_comment = value @schema_property("project") def project(self) -> Optional[str]: return self._property_project @project.setter def project(self, value: Optional[str]) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("output__error") def output__error(self) -> Optional[str]: return self._property_output__error @output__error.setter def output__error(self, value: Optional[str]) -> None: if value is None: self._property_output__error = None return self.assert_isinstance(value, "output__error", six.string_types) self._property_output__error = value @schema_property("created") def created(self) -> Optional[str]: return self._property_created @created.setter def created(self, value: Optional[str]) -> None: if value is None: self._property_created = None return self.assert_isinstance(value, "created", six.string_types + (datetime,)) if not isinstance(value, datetime): value = parse_datetime(value) self._property_created = value
UpdateRequest
python
getsentry__sentry
src/sentry/releases/endpoints/release_deploys.py
{ "start": 5119, "end": 8812 }
class ____(OrganizationReleasesBaseEndpoint): owner = ApiOwner.UNOWNED publish_status = { "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="List a Release's Deploys", parameters=[GlobalParams.ORG_ID_OR_SLUG, ReleaseParams.VERSION], responses={200: DeployResponseSerializer(many=True)}, ) def get(self, request: Request, organization, version) -> Response: """ Returns a list of deploys based on the organization, version, and project. """ try: release = Release.objects.get(version=version, organization=organization) except Release.DoesNotExist: raise ResourceDoesNotExist if not self.has_release_permission(request, organization, release): raise ResourceDoesNotExist release_project_envs = ReleaseProjectEnvironment.objects.select_related("release").filter( release__organization_id=organization.id, release__version=version, ) projects = self.get_projects(request, organization) project_id = [p.id for p in projects] if project_id and project_id != "-1": release_project_envs = release_project_envs.filter(project_id__in=project_id) deploy_ids = release_project_envs.values_list("last_deploy_id", flat=True) queryset = Deploy.objects.filter(id__in=deploy_ids) return self.paginate( request=request, paginator_cls=OffsetPaginator, queryset=queryset, order_by="-date_finished", on_results=lambda x: serialize(x, request.user), ) @extend_schema( operation_id="Create a Deploy", parameters=[GlobalParams.ORG_ID_OR_SLUG, ReleaseParams.VERSION], request=DeploySerializer, responses={201: DeployResponseSerializer, 400: RESPONSE_BAD_REQUEST}, ) def post(self, request: Request, organization, version) -> Response: """ Create a deploy for a given release. """ logging_info = { "org_slug": organization.slug, "org_id": organization.id, "version": version, } try: release = Release.objects.get(version=version, organization=organization) except Release.DoesNotExist: logger.info( "create_release_deploy.release_not_found", extra=logging_info, ) raise ResourceDoesNotExist if not self.has_release_permission(request, organization, release): # Logic here copied from `has_release_permission` (lightly edited for results to be more # human-readable) if request.user.is_authenticated: auth = f"user.id: {request.user.id}" elif request.auth is not None: auth = f"auth.entity_id: {request.auth.entity_id}" else: auth = None if auth is not None: logging_info.update({"auth": auth}) logger.info( "create_release_deploy.no_release_permission", extra=logging_info, ) raise ResourceDoesNotExist serializer = DeploySerializer( data=request.data, context={"organization": organization, "access": request.access} ) if serializer.is_valid(): deploy = create_deploy(organization, release, serializer) return Response(serialize(deploy, request.user), status=201) return Response(serializer.errors, status=400)
ReleaseDeploysEndpoint
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 88862, "end": 89617 }
class ____(Qwen2_5_VLVisionBlock): def __init__(self, config: Qwen2_5OmniVisionEncoderConfig) -> None: super().__init__(config, config._attn_implementation) self.attn = Qwen2_5OmniVisionAttention(config=config) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: hidden_states = hidden_states + self.attn( self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb, **kwargs, ) hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) return hidden_states
Qwen2_5OmniVisionBlock
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-neo4j/llama_index/graph_stores/neo4j/cypher_corrector.py
{ "start": 76, "end": 161 }
class ____(NamedTuple): left_node: str relation: str right_node: str
Schema
python
getsentry__sentry
src/sentry/seer/endpoints/organization_seer_explorer_runs.py
{ "start": 862, "end": 2368 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ML_AI enforce_rate_limit = True permission_classes = (OrganizationSeerExplorerRunsPermission,) def get(self, request: Request, organization: Organization) -> Response: """ Get a list of explorer runs triggered by the requesting user. Query Parameters: category_key: Optional category key to filter by (e.g., "bug-fixer", "researcher") category_value: Optional category value to filter by (e.g., "issue-123", "a5b32") """ category_key = request.GET.get("category_key") category_value = request.GET.get("category_value") def _make_seer_runs_request(offset: int, limit: int) -> dict[str, Any]: try: client = SeerExplorerClient(organization, request.user) runs = client.get_runs( category_key=category_key, category_value=category_value, offset=offset, limit=limit, ) except SeerPermissionError as e: raise PermissionDenied(e.message) from e return {"data": [run.dict() for run in runs]} return self.paginate( request=request, paginator=GenericOffsetPaginator(data_fn=_make_seer_runs_request), default_per_page=100, )
OrganizationSeerExplorerRunsEndpoint
python
joblib__joblib
joblib/compressor.py
{ "start": 4430, "end": 5514 }
class ____(CompressorWrapper): prefix = _LZMA_PREFIX extension = ".lzma" _lzma_format_name = "FORMAT_ALONE" def __init__(self): if lzma is not None: self.fileobj_factory = lzma.LZMAFile self._lzma_format = getattr(lzma, self._lzma_format_name) else: self.fileobj_factory = None def _check_versions(self): if lzma is None: raise ValueError( "lzma module is not compiled on your python standard library." ) def compressor_file(self, fileobj, compresslevel=None): """Returns an instance of a compressor file object.""" if compresslevel is None: return self.fileobj_factory(fileobj, "wb", format=self._lzma_format) else: return self.fileobj_factory( fileobj, "wb", format=self._lzma_format, preset=compresslevel ) def decompressor_file(self, fileobj): """Returns an instance of a decompressor file object.""" return lzma.LZMAFile(fileobj, "rb")
LZMACompressorWrapper
python
huggingface__transformers
tests/models/qwen2/test_modeling_qwen2.py
{ "start": 1443, "end": 2002 }
class ____(CausalLMModelTest, unittest.TestCase): model_tester_class = Qwen2ModelTester # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146 def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): return True @require_torch
Qwen2ModelTest
python
PyCQA__pylint
tests/functional/d/duplicate/duplicate_bases.py
{ "start": 184, "end": 358 }
class ____(Alpha, str): """The error should not be emitted for this case, since the other same base comes from the ancestors.""" print(Duplicates.__mro__)
NotDuplicates
python
huggingface__transformers
tests/utils/test_image_processing_utils.py
{ "start": 1156, "end": 2871 }
class ____(unittest.TestCase): def test_cached_files_are_used_when_internet_is_down(self): # A mock response for an HTTP head request to emulate server down response_mock = mock.Mock() response_mock.status_code = 500 response_mock.headers = {} response_mock.raise_for_status.side_effect = httpx.HTTPStatusError( "failed", request=mock.Mock(), response=mock.Mock() ) response_mock.json.return_value = {} # Download this model to make sure it's in the cache. _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") _ = ViTImageProcessorFast.from_pretrained("hf-internal-testing/tiny-random-vit") # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("httpx.Client.request", return_value=response_mock) as mock_head: _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") _ = ViTImageProcessorFast.from_pretrained("hf-internal-testing/tiny-random-vit") # This check we did call the fake head request mock_head.assert_called() def test_image_processor_from_pretrained_subfolder(self): with self.assertRaises(OSError): # config is in subfolder, the following should not work without specifying the subfolder _ = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants") config = AutoImageProcessor.from_pretrained( "hf-internal-testing/stable-diffusion-all-variants", subfolder="feature_extractor" ) self.assertIsNotNone(config) @is_staging_test
ImageProcessorUtilTester
python
chroma-core__chroma
chromadb/auth/simple_rbac_authz/__init__.py
{ "start": 412, "end": 2643 }
class ____(ServerAuthorizationProvider): """ A simple Role-Based Access Control (RBAC) authorization provider. This provider reads a configuration file that maps users to roles, and roles to actions. The provider then checks if the user has the action they are attempting to perform. For an example of an RBAC configuration file, see examples/basic_functionality/authz/authz.yaml. """ def __init__(self, system: System) -> None: super().__init__(system) self._settings = system.settings self._config = yaml.safe_load("\n".join(self.read_config_or_config_file())) # We favor preprocessing here to avoid having to parse the config file # on every request. This AuthorizationProvider does not support # per-resource authorization so we just map the user ID to the # permissions they have. We're not worried about the size of this dict # since users are all specified in the file -- anyone with a gigantic # number of users can roll their own AuthorizationProvider. self._permissions: Dict[str, Set[str]] = {} for user in self._config["users"]: _actions = self._config["roles_mapping"][user["role"]]["actions"] self._permissions[user["id"]] = set(_actions) logger.info( "Authorization Provider SimpleRBACAuthorizationProvider " "initialized" ) @trace_method( "SimpleRBACAuthorizationProvider.authorize", OpenTelemetryGranularity.ALL, ) @override def authorize_or_raise( self, user: UserIdentity, action: AuthzAction, resource: AuthzResource ) -> None: policy_decision = False if ( user.user_id in self._permissions and action in self._permissions[user.user_id] ): policy_decision = True logger.debug( f"Authorization decision: Access " f"{'granted' if policy_decision else 'denied'} for " f"user [{user.user_id}] attempting to " f"[{action}] [{resource}]" ) if not policy_decision: raise HTTPException(status_code=403, detail="Forbidden")
SimpleRBACAuthorizationProvider
python
numba__numba
numba/core/types/containers.py
{ "start": 2717, "end": 2824 }
class ____(Buffer): """ Type class for bytearray objects. """ slice_is_copy = True
ByteArray
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 24398, "end": 25345 }
class ____(OfflineTestCaseMixin, TestCase): templates_dir = "test_error_handling" additional_test_settings = { "COMPRESS_PRECOMPILERS": (("text/coffeescript", "nonexisting-binary"),) } def _test_offline(self, engine, verbosity=0): """ Test that a CommandError is raised with DEBUG being False as well as True, as otherwise errors in configuration will never show in production. """ with self.settings(DEBUG=True): self.assertRaises( CommandError, CompressCommand().handle_inner, engines=[engine], verbosity=verbosity, ) with self.settings(DEBUG=False): self.assertRaises( CommandError, CompressCommand().handle_inner, engines=[engine], verbosity=verbosity, )
OfflineCompressTestCaseWithError
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 16201, "end": 17168 }
class ____(TreeVisitor): def __init__(self): super().__init__() self.target_names = {} def find_target_names(self, target): if target.is_name: return [target.name] elif target.is_sequence_constructor: names = [] for arg in target.args: names.extend(self.find_target_names(arg)) return names # other targets are possible, but it isn't necessary to investigate them here return [] def visit_ForInStatNode(self, node): self.target_names[node] = tuple(self.find_target_names(node.target)) self.visitchildren(node) def visit_ComprehensionNode(self, node): pass # don't recurse into nested comprehensions def visit_LambdaNode(self, node): pass # don't recurse into nested lambdas/generator expressions def visit_Node(self, node): self.visitchildren(node)
_AssignmentExpressionTargetNameFinder
python
ansible__ansible
test/integration/targets/result_pickle_error/action_plugins/result_pickle_error.py
{ "start": 400, "end": 520 }
class ____(ActionBase): def run(self, tmp=None, task_vars=None): return {'obj': CannotBePickled()}
ActionModule
python
pennersr__django-allauth
allauth/headless/account/response.py
{ "start": 1359, "end": 1574 }
class ____(APIResponse): def __init__(self, request, user): adapter = get_adapter() data = {"user": adapter.serialize_user(user)} super().__init__(request, data=data)
PasswordResetKeyResponse
python
realpython__materials
duck-typing-python/birds_v1.py
{ "start": 0, "end": 128 }
class ____: def swim(self): print("The duck is swimming") def fly(self): print("The duck is flying")
Duck
python
great-expectations__great_expectations
great_expectations/experimental/metric_repository/data_store.py
{ "start": 214, "end": 678 }
class ____(abc.ABC, Generic[T]): """Abstract base class for all DataStore implementations.""" def __init__(self, context: CloudDataContext): self._context = context @abc.abstractmethod def add(self, value: T) -> uuid.UUID: """Add a value to the DataStore. Args: value: Value to add to the DataStore. Returns: id of the created resource. """ raise NotImplementedError
DataStore
python
django__django
tests/db_functions/text/test_concat.py
{ "start": 482, "end": 4704 }
class ____(TestCase): def test_basic(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate(joined=Concat("alias", "goes_by")) self.assertQuerySetEqual( authors.order_by("name"), [ "", "smithjJohn", "Maggie", "adnohR", ], lambda a: a.joined, ) def test_gt_two_expressions(self): with self.assertRaisesMessage( ValueError, "Concat must take at least two expressions" ): Author.objects.annotate(joined=Concat("alias")) def test_many(self): Author.objects.create(name="Jayden") Author.objects.create(name="John Smith", alias="smithj", goes_by="John") Author.objects.create(name="Margaret", goes_by="Maggie") Author.objects.create(name="Rhonda", alias="adnohR") authors = Author.objects.annotate( joined=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField()), ) self.assertQuerySetEqual( authors.order_by("name"), [ "Jayden ()", "John Smith (John)", "Margaret (Maggie)", "Rhonda ()", ], lambda a: a.joined, ) def test_mixed_char_text(self): Article.objects.create( title="The Title", text=lorem_ipsum, written=timezone.now() ) article = Article.objects.annotate( title_text=Concat("title", V(" - "), "text", output_field=TextField()), ).get(title="The Title") self.assertEqual(article.title + " - " + article.text, article.title_text) # Wrap the concat in something else to ensure that text is returned # rather than bytes. article = Article.objects.annotate( title_text=Upper( Concat("title", V(" - "), "text", output_field=TextField()) ), ).get(title="The Title") expected = article.title + " - " + article.text self.assertEqual(expected.upper(), article.title_text) @skipUnless( connection.vendor in ("sqlite", "postgresql"), "SQLite and PostgreSQL specific implementation detail.", ) def test_coalesce_idempotent(self): pair = ConcatPair(V("a"), V("b")) # Check nodes counts self.assertEqual(len(list(pair.flatten())), 3) self.assertEqual( len(list(pair.coalesce().flatten())), 7 ) # + 2 Coalesce + 2 Value() self.assertEqual(len(list(pair.flatten())), 3) def test_sql_generation_idempotency(self): qs = Article.objects.annotate(description=Concat("title", V(": "), "summary")) # Multiple compilations should not alter the generated query. self.assertEqual(str(qs.query), str(qs.all().query)) def test_concat_non_str(self): Author.objects.create(name="The Name", age=42) with self.assertNumQueries(1) as ctx: author = Author.objects.annotate( name_text=Concat( "name", V(":"), "alias", V(":"), "age", output_field=TextField() ), ).get() self.assertEqual(author.name_text, "The Name::42") # Only non-string columns are casted on PostgreSQL. self.assertEqual( ctx.captured_queries[0]["sql"].count("::text"), 1 if connection.vendor == "postgresql" else 0, ) def test_equal(self): self.assertEqual( Concat("foo", "bar", output_field=TextField()), Concat("foo", "bar", output_field=TextField()), ) self.assertNotEqual( Concat("foo", "bar", output_field=TextField()), Concat("foo", "bar", output_field=CharField()), ) self.assertNotEqual( Concat("foo", "bar", output_field=TextField()), Concat("bar", "foo", output_field=TextField()), )
ConcatTests
python
pytorch__pytorch
torch/ao/nn/qat/modules/embedding_ops.py
{ "start": 163, "end": 3833 }
class ____(nn.Embedding): r""" An embedding bag module attached with FakeQuantize modules for weight, used for quantization aware training. We adopt the same interface as `torch.nn.Embedding`, please see https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding for documentation. Similar to `torch.nn.Embedding`, with FakeQuantize modules initialized to default. Attributes: weight: fake quant module for weight """ _FLOAT_MODULE = nn.Embedding def __init__( self, num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, device=None, dtype=None, qconfig=None, ) -> None: factory_kwargs = {"device": device, "dtype": dtype} super().__init__( num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse, _weight, # pyrefly: ignore [bad-argument-type] **factory_kwargs, ) assert qconfig, "qconfig must be provided for QAT module" assert qconfig.weight().qscheme == torch.per_channel_affine_float_qparams, ( "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got " + str(qconfig.weight().qscheme) ) self.qconfig = qconfig self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs) def forward(self, input) -> Tensor: return F.embedding( input, self.weight_fake_quant(self.weight), self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse, ) @classmethod def from_float(cls, mod, use_precomputed_fake_quant=False): r"""Create a qat module from a float module Args: `mod` a float module, either produced by torch.ao.quantization utilities or directly from user """ assert type(mod) is cls._FLOAT_MODULE, ( " qat." + cls.__name__ + ".from_float only works for " + cls._FLOAT_MODULE.__name__ ) assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined" assert mod.qconfig, "Input float module must have a valid qconfig" weight_qscheme = mod.qconfig.weight().qscheme # type: ignore[union-attr, operator] assert weight_qscheme == torch.per_channel_affine_float_qparams, ( "Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got " + str(weight_qscheme) ) qconfig = mod.qconfig qat_embedding_bag = cls( mod.num_embeddings, mod.embedding_dim, mod.padding_idx, mod.max_norm, mod.norm_type, mod.scale_grad_by_freq, mod.sparse, mod.weight, qconfig=qconfig, ) return qat_embedding_bag def to_float(self): embedding_bag = torch.nn.Embedding( self.num_embeddings, self.embedding_dim, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse, None, ) embedding_bag.weight = torch.nn.Parameter(self.weight.detach()) embedding_bag.train(self.training) return embedding_bag
Embedding
python
tensorflow__tensorflow
tensorflow/python/module/module_test.py
{ "start": 19500, "end": 19564 }
class ____: """A simple type to search for.""" pass
MemberType
python
google__pytype
pytype/pyi/parser_test.py
{ "start": 1783, "end": 17809 }
class ____(parser_test_base.ParserTestBase): def test_syntax_error(self): self.check_error("123", 1, "Unexpected expression") def test_illegal_character(self): self.check_error("^", 1, "invalid syntax") def test_invalid_indentation(self): self.check_error( """ class Foo: x = ... # type: int y""", 3, "unindent does not match", ) def test_invalid_literal_annotation(self): self.check_error("def f(x: False): ...", 1, "Unexpected literal: False") def test_constant(self): self.check("x = ...", "x: Any", "from typing import Any") self.check("x: str") self.check("x = 0", "x: int") self.check("x = 0.0", "x: float") def test_string_constant(self): self.check("x = b''", "x: bytes") self.check("x = u''", "x: str") self.check('x = b""', "x: bytes") self.check('x = u""', "x: str") self.check("x = ''", "x: str") self.check('x = ""', "x: str") def test_constant_pep526(self): self.check("x : str", "x: str") self.check("x : str = ...", "x: str = ...") def test_alias_or_constant(self): self.check("x = True", "x: bool") self.check("x = False", "x: bool") self.check("x = Foo") self.check( """ class A: x = True""", """ class A: x: bool """, ) self.check( """ class A: x = ... # type: int y = x z = y""", """ class A: x: int y: int z: int """, ) def test_method_aliases(self): self.check( """ class A: def x(self) -> int: ... y = x z = y @classmethod def a(cls) -> str: ... b = a c = b""", """ class A: def x(self) -> int: ... @classmethod def a(cls) -> str: ... def y(self) -> int: ... def z(self) -> int: ... @classmethod def b(cls) -> str: ... @classmethod def c(cls) -> str: ... """, ) def test_chained_assignment(self): self.check( """ a = b = int """, """ a = int b = int """, ) def test_multiple_assignment(self): self.check( """ a, b = int, str """, """ a = int b = str """, ) self.check( """ (a, b) = (c, d) = int, str """, """ a = int b = str c = int d = str """, ) def test_invalid_multiple_assignment(self): self.check_error( """ a, b = int, str, bool """, 1, "Cannot unpack 2 values for multiple assignment", ) self.check_error( """ a, b = int """, 1, "Cannot unpack 2 values for multiple assignment", ) def test_slots(self): self.check( """ class A: __slots__ = ... # type: tuple """, """ class A: ... """, ) self.check(""" class A: __slots__ = ["foo", "bar", "baz"] """) self.check(""" class A: __slots__ = [] """) self.check_error( """ __slots__ = ["foo", "bar"] """, 1, "__slots__ only allowed on the class level", ) self.check_error( """ class A: __slots__ = ["foo", "bar"] __slots__ = ["foo", "bar", "baz"] """, 1, "Duplicate __slots__ declaration", ) self.check_error( """ class A: __slots__ = ["foo", ?] """, 2, "invalid syntax", ) self.check_error( """ class A: __slots__ = int """, 2, "__slots__ must be a list of strings", ) def test_nested_class(self): self.check(""" class A: class B: ... """) def test_nested_class_alias(self): self.check( """ class A: class B: ... C = A.B """, """ class A: class B: ... C: type[A.B] """, ) def test_nested_class_module_alias(self): self.check( """ class A: class B: ... C = A.B """, """ C: type[A.B] class A: class B: ... """, ) def test_conditional_nested_class(self): self.check( """ if sys.version_info < (3, 5): class A: class B: ... """, "", ) def test_import(self): self.check("import foo.bar.baz") self.check("import a as b") self.check("from foo.bar import baz") self.check("from foo.bar import baz as abc") self.check("from typing import NamedTuple, TypeVar", "") self.check("from foo.bar import *") self.check_error("from foo import * as bar", 1, "invalid syntax") self.check("from foo import a, b") self.check("from foo import (a, b)", "from foo import a, b") self.check("from foo import (a, b, )", "from foo import a, b") def test_from_import(self): ast = self.check( "from foo import c\nclass Bar(c.X): ...", parser_test_base.IGNORE ) (base,) = ast.Lookup("Bar").bases self.assertEqual(base, pytd.NamedType("foo.c.X")) def test_keyword_import(self): self.check( """ import importlib my_module = importlib.import_module('await.break.in.global.or.yield') """, """ import importlib from typing import Any my_module: Any """, ) def test_duplicate_names(self): self.check_error( """ def foo() -> int: ... foo = ... # type: int""", None, "Duplicate attribute name(s) in module: foo", ) self.check_error( """ X = ... # type: int class X: ...""", None, "Duplicate attribute name(s) in module: X", ) self.check_error( """ X = ... # type: int X = TypeVar('X')""", None, "Duplicate attribute name(s) in module: X", ) # A function is allowed to appear multiple times. self.check( """ def foo(x: int) -> int: ... def foo(x: str) -> str: ...""", """ from typing import overload @overload def foo(x: int) -> int: ... @overload def foo(x: str) -> str: ...""", ) # @overload decorators should be properly round-tripped. self.check( """ @overload def foo(x: int) -> int: ... @overload def foo(x: str) -> str: ...""", """ from typing import overload @overload def foo(x: int) -> int: ... @overload def foo(x: str) -> str: ...""", ) # Names of the same type (e.g., all constants) are allowed to appear # multiple times. The last one wins. self.check( """ x: str x: int """, """ x: int """, ) def test_duplicate_import(self): # Imports of duplicate names are allowed and ignored. Otherwise, an import # from a file we have no control over could clash with local contents. self.check( """ from foo import Bar class Bar: ... """, """ class Bar: ... """, ) def test_type(self): self.check("x: str") self.check("x = ... # type: (str)", "x: str") self.check("x: foo.bar.Baz", prologue="import foo.bar") self.check("x: nothing") def test_deprecated_type(self): self.check_error( "x = ... # type: int and str and float", 1, "Unexpected operator" ) self.check_error("x = ... # type: ?", 1, "invalid syntax") self.check_error( "x = ... # type: int or str or float", 1, "Deprecated syntax" ) def test_empty_union_or_intersection_or_optional(self): self.check_error( "def f(x: typing.Union): ...", 1, "Missing options to typing.Union" ) self.check_error( "def f(x: typing.Intersection): ...", 1, "Missing options to typing.Intersection", ) self.check_error( "def f(x: typing.Optional): ...", 1, "Missing options to typing.Optional", ) def test_optional_extra_parameters(self): self.check_error( "def f(x: typing.Optional[int, str]): ...", 1, "Too many options to typing.Optional", ) def test_alias_lookup(self): self.check( """ from somewhere import Foo x = ... # type: Foo """, """ import somewhere from somewhere import Foo x: somewhere.Foo""", ) def test_external_alias(self): self.check( """ from somewhere import Foo class Bar: Baz = Foo """, """ from somewhere import Foo from typing import Any class Bar: Baz: Any """, ) def test_same_named_alias(self): self.check( """ import somewhere class Bar: Foo = somewhere.Foo """, """ import somewhere from typing import Any class Bar: Foo: Any """, ) def test_type_params(self): ast = self.check(""" from typing import TypeVar T = TypeVar('T') def func(x: T) -> T: ...""") # During parsing references to type paraemters are instances of NamedType. # They should be replaced by TypeParameter objects during post-processing. sig = ast.functions[0].signatures[0] self.assertIsInstance(sig.params[0].type, pytd.TypeParameter) self.assertIsInstance(sig.return_type, pytd.TypeParameter) # Check various illegal TypeVar arguments. self.check_error("T = TypeVar()", 1, "Missing arguments to TypeVar") self.check_error("T = TypeVar(*args)", 1, "Unsupported node type: Starred") self.check_error("T = TypeVar(...)", 1, "Bad arguments to TypeVar") self.check_error( "T = TypeVar('Q')", 1, "TypeVar name needs to be 'Q' (not 'T')" ) self.check_error( "T = TypeVar('T', covariant=True, int, float)", 1, "positional argument follows keyword argument", ) self.check_error( "T = TypeVar('T', rumpelstiltskin=True)", 1, "Unrecognized keyword" ) def test_type_param_arguments(self): self.check(""" from typing import TypeVar T = TypeVar('T', list[int], list[str])""") self.check(""" from typing import TypeVar T = TypeVar('T', bound=list[str])""") # 'covariant' and 'contravariant' are ignored for now. self.check( """ from typing import TypeVar T = TypeVar('T', str, unicode, covariant=True)""", """ from typing import TypeVar T = TypeVar('T', str, unicode)""", ) self.check(""" import other_mod from typing import TypeVar T = TypeVar('T', other_mod.A, other_mod.B)""") def test_typing_typevar(self): self.check( """ import typing T = typing.TypeVar('T') """, """ import typing from typing import TypeVar T = TypeVar('T') """, ) def test_error_formatting(self): src = """ class Foo: this is not valid""" with self.assertRaises(parser.ParseError) as e: parser.parse_string( textwrap.dedent(src).lstrip(), filename="foo.py", options=self.options ) self.assertMultiLineEqual( textwrap.dedent(""" File: "foo.py", line 2 this is not valid ^ ParseError: Unsupported node type: IsNot """).strip("\n"), str(e.exception), ) def test_pep484_translations(self): ast = self.check(""" x: None""") self.assertEqual(pytd.NamedType("NoneType"), ast.constants[0].type) def test_module_name(self): ast = self.check("x = ... # type: int", "foo.x: int", name="foo") self.assertEqual("foo", ast.name) def test_no_module_name(self): # If the name is not specified, it is a digest of the source. src = "" ast = self.check(src) self.assertEqual(hashlib.md5(src.encode()).hexdigest(), ast.name) src = "x: int" ast = self.check(src) self.assertEqual(hashlib.md5(src.encode()).hexdigest(), ast.name) def test_pep84_aliasing(self): # This should not be done for the typing module itself. self.check("x = ... # type: Hashable", "typing.x: Hashable", name="typing") def test_module_class_clash(self): ast = parser.parse_string( textwrap.dedent(""" from bar import X class bar: X = ... # type: Any y = bar.X.Baz z = X.Baz """), name="foo", options=self.options, ) self.assertEqual("foo.bar.X.Baz", ast.Lookup("foo.y").type.name) self.assertEqual("bar.X.Baz", ast.Lookup("foo.z").type.name) def test_trailing_list_comma(self): self.check( """ from typing import Any, Callable x: Callable[ [ int, int, ], Any, ] """, """ from typing import Any, Callable x: Callable[[int, int], Any] """, ) def test_all(self): self.check( """ __all__ = ['a'] """, """ __all__: list[str] = ... """, ) def test_invalid_constructor(self): e = "Constructors and function calls in type annotations are not supported." self.check_error( """ x = ... # type: typing.NamedTuple("A", []) """, 1, e, ) self.check_error( """ x: typing.NamedTuple("A", []) = ... """, 1, e, ) def test_match_args(self): self.check( """ from typing import Final class A: __match_args__ = ("a", "b") class B: __match_args__: Final = ("a", "b") """, """ class A: __match_args__: tuple class B: __match_args__: tuple """, ) def test_typevar_alias(self): self.check(""" from typing import TypeVar as _TypeVar T = _TypeVar('T') def f(x: T) -> T: ... """) def test_local_typevar(self): self.check(""" import typing T = typing.TypeVar('T') class TypeVar: ... """) def test_typing_alias(self): self.check("import typing as _typing") def test_multiple_aliases(self): self.check(""" import foo import foo as foo2 """) def test_multiple_aliases_from_import(self): self.check(""" from foo import bar, bar as bar2 """) def test_multiple_typing_aliases(self): self.check( """ from typing import Callable MyFunc = Callable YourFunc = Callable """, """ from typing import Callable as MyFunc, Callable as YourFunc """, ) def test_bad_list_parameter(self): self.check_error( """ from typing import List x: List[[]] """, 2, "Unexpected list parameter", ) def test_bad_list_parameter_in_callable(self): self.check_error( """ from typing import Callable x: Callable[..., []] """, 2, "Unexpected list parameter", ) def test_typing_import_in_cls_parameter(self): self.check( """ from typing import Generic, List, Type, TypeVar T = TypeVar('T') class A(Generic[T]): @classmethod def f(cls: Type[A[List[int]]]) -> None: ... """, """ from typing import Generic, TypeVar T = TypeVar('T') class A(Generic[T]): @classmethod def f(cls) -> None: ... """, ) def test_property_import_shared_name(self): self.check( """ from foo import bar class X: @property def bar(self) -> int: ... @bar.setter def bar(self, x: int) -> None: ... """, """ from foo import bar from typing import Annotated class X: bar: Annotated[int, 'property'] """, )
ParserTest
python
numba__numba
numba/core/datamodel/models.py
{ "start": 10065, "end": 10285 }
class ____(PrimitiveModel): def __init__(self, dmm, fe_type): be_type = ir.IntType(fe_type.bitwidth) super(IntegerModel, self).__init__(dmm, fe_type, be_type) @register_default(types.Float)
IntegerModel
python
pypa__pip
src/pip/_internal/cache.py
{ "start": 926, "end": 3716 }
class ____: """An abstract class - provides cache directories for data from links :param cache_dir: The root of the cache. """ def __init__(self, cache_dir: str) -> None: super().__init__() assert not cache_dir or os.path.isabs(cache_dir) self.cache_dir = cache_dir or None def _get_cache_path_parts(self, link: Link) -> list[str]: """Get parts of part that must be os.path.joined with cache_dir""" # We want to generate an url to use as our cache key, we don't want to # just reuse the URL because it might have other items in the fragment # and we don't care about those. key_parts = {"url": link.url_without_fragment} if link.hash_name is not None and link.hash is not None: key_parts[link.hash_name] = link.hash if link.subdirectory_fragment: key_parts["subdirectory"] = link.subdirectory_fragment # Include interpreter name, major and minor version in cache key # to cope with ill-behaved sdists that build a different wheel # depending on the python version their setup.py is being run on, # and don't encode the difference in compatibility tags. # https://github.com/pypa/pip/issues/7296 key_parts["interpreter_name"] = interpreter_name() key_parts["interpreter_version"] = interpreter_version() # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = _hash_dict(key_parts) # We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] return parts def _get_candidates(self, link: Link, canonical_package_name: str) -> list[Any]: can_not_cache = not self.cache_dir or not canonical_package_name or not link if can_not_cache: return [] path = self.get_path_for_link(link) if os.path.isdir(path): return [(candidate, path) for candidate in os.listdir(path)] return [] def get_path_for_link(self, link: Link) -> str: """Return a directory to store cached items in for link.""" raise NotImplementedError() def get( self, link: Link, package_name: str | None, supported_tags: list[Tag], ) -> Link: """Returns a link to a cached item if it exists, otherwise returns the passed link. """ raise NotImplementedError()
Cache
python
walkccc__LeetCode
solutions/996. Number of Squareful Arrays/996.py
{ "start": 0, "end": 686 }
class ____: def numSquarefulPerms(self, nums: list[int]) -> int: ans = 0 used = [False] * len(nums) def isSquare(num: int) -> bool: root = math.isqrt(num) return root * root == num def dfs(path: list[int]) -> None: nonlocal ans if len(path) > 1 and not isSquare(path[-1] + path[-2]): return if len(path) == len(nums): ans += 1 return for i, a in enumerate(nums): if used[i]: continue if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue used[i] = True dfs(path + [a]) used[i] = False nums.sort() dfs([]) return ans
Solution
python
keon__algorithms
algorithms/tree/bst/count_left_node.py
{ "start": 992, "end": 1477 }
class ____(unittest.TestCase): def setUp(self): self.tree = bst() self.tree.insert(9) self.tree.insert(6) self.tree.insert(12) self.tree.insert(3) self.tree.insert(8) self.tree.insert(10) self.tree.insert(15) self.tree.insert(7) self.tree.insert(18) def test_count_left_node(self): self.assertEqual(4, count_left_node(self.tree.root)) if __name__ == '__main__': unittest.main()
TestSuite
python
numpy__numpy
numpy/lib/tests/test_twodim_base.py
{ "start": 5405, "end": 5663 }
class ____: def test_basic(self): a = get_mat(4) b = a[::-1, :] assert_equal(flipud(a), b) a = [[0, 1, 2], [3, 4, 5]] b = [[3, 4, 5], [0, 1, 2]] assert_equal(flipud(a), b)
TestFlipud
python
tornadoweb__tornado
tornado/test/httpclient_test.py
{ "start": 4750, "end": 29644 }
class ____(AsyncHTTPTestCase): def get_app(self): return Application( [ url("/hello", HelloWorldHandler), url("/post", PostHandler), url("/put", PutHandler), url("/redirect", RedirectHandler), url("/redirect_without_location", RedirectWithoutLocationHandler), url("/chunk", ChunkHandler), url("/auth", AuthHandler), url("/countdown/([0-9]+)", CountdownHandler, name="countdown"), url("/echopost", EchoPostHandler), url("/user_agent", UserAgentHandler), url("/304_with_content_length", ContentLength304Handler), url("/all_methods", AllMethodsHandler), url("/patch", PatchHandler), url("/set_header", SetHeaderHandler), url("/invalid_gzip", InvalidGzipHandler), url("/header-encoding", HeaderEncodingHandler), ], gzip=True, ) def test_patch_receives_payload(self): body = b"some patch data" response = self.fetch("/patch", method="PATCH", body=body) self.assertEqual(response.code, 200) self.assertEqual(response.body, body) def test_hello_world(self): response = self.fetch("/hello") self.assertEqual(response.code, 200) self.assertEqual(response.headers["Content-Type"], "text/plain") self.assertEqual(response.body, b"Hello world!") assert response.request_time is not None self.assertEqual(int(response.request_time), 0) response = self.fetch("/hello?name=Ben") self.assertEqual(response.body, b"Hello Ben!") def test_streaming_callback(self): # streaming_callback is also tested in test_chunked chunks = [] # type: typing.List[bytes] response = self.fetch("/hello", streaming_callback=chunks.append) # with streaming_callback, data goes to the callback and not response.body self.assertEqual(chunks, [b"Hello world!"]) self.assertFalse(response.body) def test_post(self): response = self.fetch("/post", method="POST", body="arg1=foo&arg2=bar") self.assertEqual(response.code, 200) self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") def test_chunked(self): response = self.fetch("/chunk") self.assertEqual(response.body, b"asdfqwer") chunks = [] # type: typing.List[bytes] response = self.fetch("/chunk", streaming_callback=chunks.append) self.assertEqual(chunks, [b"asdf", b"qwer"]) self.assertFalse(response.body) def test_chunked_close(self): # test case in which chunks spread read-callback processing # over several ioloop iterations, but the connection is already closed. sock, port = bind_unused_port() with closing(sock): @gen.coroutine def accept_callback(conn, address): # fake an HTTP server using chunked encoding where the final chunks # and connection close all happen at once stream = IOStream(conn) request_data = yield stream.read_until(b"\r\n\r\n") if b"HTTP/1." not in request_data: self.skipTest("requires HTTP/1.x") yield stream.write( b"""\ HTTP/1.1 200 OK Transfer-Encoding: chunked 1 1 1 2 0 """.replace( b"\n", b"\r\n" ) ) stream.close() netutil.add_accept_handler(sock, accept_callback) # type: ignore resp = self.fetch("http://127.0.0.1:%d/" % port) resp.rethrow() self.assertEqual(resp.body, b"12") self.io_loop.remove_handler(sock.fileno()) def test_basic_auth(self): # This test data appears in section 2 of RFC 7617. self.assertEqual( self.fetch( "/auth", auth_username="Aladdin", auth_password="open sesame" ).body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ) def test_basic_auth_explicit_mode(self): self.assertEqual( self.fetch( "/auth", auth_username="Aladdin", auth_password="open sesame", auth_mode="basic", ).body, b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ) def test_basic_auth_unicode(self): # This test data appears in section 2.1 of RFC 7617. self.assertEqual( self.fetch("/auth", auth_username="test", auth_password="123£").body, b"Basic dGVzdDoxMjPCow==", ) # The standard mandates NFC. Give it a decomposed username # and ensure it is normalized to composed form. username = unicodedata.normalize("NFD", "josé") self.assertEqual( self.fetch("/auth", auth_username=username, auth_password="səcrət").body, b"Basic am9zw6k6c8mZY3LJmXQ=", ) def test_unsupported_auth_mode(self): # curl and simple clients handle errors a bit differently; the # important thing is that they don't fall back to basic auth # on an unknown mode. with ExpectLog(gen_log, "uncaught exception", required=False): with self.assertRaises((ValueError, HTTPError)): # type: ignore self.fetch( "/auth", auth_username="Aladdin", auth_password="open sesame", auth_mode="asdf", raise_error=True, ) def test_follow_redirect(self): response = self.fetch("/countdown/2", follow_redirects=False) self.assertEqual(302, response.code) self.assertTrue(response.headers["Location"].endswith("/countdown/1")) response = self.fetch("/countdown/2") self.assertEqual(200, response.code) self.assertTrue(response.effective_url.endswith("/countdown/0")) self.assertEqual(b"Zero", response.body) def test_redirect_without_location(self): response = self.fetch("/redirect_without_location", follow_redirects=True) # If there is no location header, the redirect response should # just be returned as-is. (This should arguably raise an # error, but libcurl doesn't treat this as an error, so we # don't either). self.assertEqual(301, response.code) def test_redirect_put_with_body(self): response = self.fetch( "/redirect?url=/put&status=307", method="PUT", body="hello" ) self.assertEqual(response.body, b"Put body: hello") def test_redirect_put_without_body(self): # This "without body" edge case is similar to what happens with body_producer. response = self.fetch( "/redirect?url=/put&status=307", method="PUT", allow_nonstandard_methods=True, ) self.assertEqual(response.body, b"Put body: ") def test_method_after_redirect(self): # Legacy redirect codes (301, 302) convert POST requests to GET. for status in [301, 302, 303]: url = "/redirect?url=/all_methods&status=%d" % status resp = self.fetch(url, method="POST", body=b"") self.assertEqual(b"GET", resp.body) # Other methods are left alone, except for 303 redirect, depending on client for method in ["GET", "OPTIONS", "PUT", "DELETE"]: resp = self.fetch(url, method=method, allow_nonstandard_methods=True) if status in [301, 302]: self.assertEqual(utf8(method), resp.body) else: self.assertIn(resp.body, [utf8(method), b"GET"]) # HEAD is different so check it separately. resp = self.fetch(url, method="HEAD") self.assertEqual(200, resp.code) self.assertEqual(b"", resp.body) # Newer redirects always preserve the original method. for status in [307, 308]: url = "/redirect?url=/all_methods&status=307" for method in ["GET", "OPTIONS", "POST", "PUT", "DELETE"]: resp = self.fetch(url, method=method, allow_nonstandard_methods=True) self.assertEqual(method, to_unicode(resp.body)) resp = self.fetch(url, method="HEAD") self.assertEqual(200, resp.code) self.assertEqual(b"", resp.body) def test_credentials_in_url(self): url = self.get_url("/auth").replace("http://", "http://me:secret@") response = self.fetch(url) self.assertEqual(b"Basic " + base64.b64encode(b"me:secret"), response.body) def test_body_encoding(self): unicode_body = "\xe9" byte_body = binascii.a2b_hex(b"e9") # unicode string in body gets converted to utf8 response = self.fetch( "/echopost", method="POST", body=unicode_body, headers={"Content-Type": "application/blah"}, ) self.assertEqual(response.headers["Content-Length"], "2") self.assertEqual(response.body, utf8(unicode_body)) # byte strings pass through directly response = self.fetch( "/echopost", method="POST", body=byte_body, headers={"Content-Type": "application/blah"}, ) self.assertEqual(response.headers["Content-Length"], "1") self.assertEqual(response.body, byte_body) # Mixing unicode in headers and byte string bodies shouldn't # break anything response = self.fetch( "/echopost", method="POST", body=byte_body, headers={"Content-Type": "application/blah"}, user_agent="foo", ) self.assertEqual(response.headers["Content-Length"], "1") self.assertEqual(response.body, byte_body) def test_types(self): response = self.fetch("/hello") self.assertEqual(type(response.body), bytes) self.assertEqual(type(response.headers["Content-Type"]), str) self.assertEqual(type(response.code), int) self.assertEqual(type(response.effective_url), str) def test_gzip(self): # All the tests in this file should be using gzip, but this test # ensures that it is in fact getting compressed, and also tests # the httpclient's decompress=False option. # Setting Accept-Encoding manually bypasses the client's # decompression so we can see the raw data. response = self.fetch( "/chunk", decompress_response=False, headers={"Accept-Encoding": "gzip"} ) self.assertEqual(response.headers["Content-Encoding"], "gzip") self.assertNotEqual(response.body, b"asdfqwer") # Our test data gets bigger when gzipped. Oops. :) # Chunked encoding bypasses the MIN_LENGTH check. self.assertEqual(len(response.body), 34) f = gzip.GzipFile(mode="r", fileobj=response.buffer) self.assertEqual(f.read(), b"asdfqwer") def test_invalid_gzip(self): # test if client hangs on tricky invalid gzip # curl/simple httpclient have different behavior (exception, logging) with ExpectLog( gen_log, ".*Malformed HTTP message.*unconsumed gzip data", required=False ): try: response = self.fetch("/invalid_gzip") self.assertEqual(response.code, 200) self.assertEqual(response.body[:14], b"Hello World 0\n") except HTTPError: pass # acceptable def test_header_callback(self): first_line = [] headers = {} chunks = [] def header_callback(header_line): if header_line.startswith("HTTP/1.1 101"): # Upgrading to HTTP/2 pass elif header_line.startswith("HTTP/"): first_line.append(header_line) elif header_line != "\r\n": k, v = header_line.split(":", 1) headers[k.lower()] = v.strip() def streaming_callback(chunk): # All header callbacks are run before any streaming callbacks, # so the header data is available to process the data as it # comes in. self.assertEqual(headers["content-type"], "text/html; charset=UTF-8") chunks.append(chunk) self.fetch( "/chunk", header_callback=header_callback, streaming_callback=streaming_callback, ) self.assertEqual(len(first_line), 1, first_line) self.assertRegex(first_line[0], "HTTP/[0-9]\\.[0-9] 200.*\r\n") self.assertEqual(chunks, [b"asdf", b"qwer"]) def test_header_callback_to_parse_line(self): # Make a request with header_callback and feed the headers to HTTPHeaders.parse_line. # (Instead of HTTPHeaders.parse which is used in normal cases). Ensure that the resulting # headers are as expected, and in particular do not have trailing whitespace added # due to the final CRLF line. headers = HTTPHeaders() def header_callback(line): if line.startswith("HTTP/"): # Ignore the first status line return headers.parse_line(line) self.fetch("/hello", header_callback=header_callback) for k, v in headers.get_all(): self.assertTrue(v == v.strip(), (k, v)) @gen_test def test_configure_defaults(self): defaults = dict(user_agent="TestDefaultUserAgent", allow_ipv6=False) # Construct a new instance of the configured client class client = self.http_client.__class__(force_instance=True, defaults=defaults) try: response = yield client.fetch(self.get_url("/user_agent")) self.assertEqual(response.body, b"TestDefaultUserAgent") finally: client.close() def test_header_types(self): # Header values may be passed as character or utf8 byte strings, # in a plain dictionary or an HTTPHeaders object. # Keys must always be the native str type. # All combinations should have the same results on the wire. for value in ["MyUserAgent", b"MyUserAgent"]: for container in [dict, HTTPHeaders]: headers = container() headers["User-Agent"] = value resp = self.fetch("/user_agent", headers=headers) self.assertEqual( resp.body, b"MyUserAgent", "response=%r, value=%r, container=%r" % (resp.body, value, container), ) def test_multi_line_headers(self): # Multi-line http headers are rare but rfc-allowed # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 sock, port = bind_unused_port() with closing(sock): @gen.coroutine def accept_callback(conn, address): stream = IOStream(conn) request_data = yield stream.read_until(b"\r\n\r\n") if b"HTTP/1." not in request_data: self.skipTest("requires HTTP/1.x") yield stream.write( b"""\ HTTP/1.1 200 OK X-XSS-Protection: 1; \tmode=block """.replace( b"\n", b"\r\n" ) ) stream.close() netutil.add_accept_handler(sock, accept_callback) # type: ignore try: resp = self.fetch("http://127.0.0.1:%d/" % port) resp.rethrow() self.assertEqual(resp.headers["X-XSS-Protection"], "1; mode=block") finally: self.io_loop.remove_handler(sock.fileno()) @gen_test def test_header_encoding(self): response = yield self.http_client.fetch( self.get_url("/header-encoding"), headers={ "Foo": "b\xe4r", }, ) self.assertEqual(response.body, "b\xe4r".encode("ISO8859-1")) def test_304_with_content_length(self): # According to the spec 304 responses SHOULD NOT include # Content-Length or other entity headers, but some servers do it # anyway. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 response = self.fetch("/304_with_content_length") self.assertEqual(response.code, 304) self.assertEqual(response.headers["Content-Length"], "42") @gen_test def test_future_interface(self): response = yield self.http_client.fetch(self.get_url("/hello")) self.assertEqual(response.body, b"Hello world!") @gen_test def test_future_http_error(self): with self.assertRaises(HTTPError) as context: yield self.http_client.fetch(self.get_url("/notfound")) assert context.exception is not None assert context.exception.response is not None self.assertEqual(context.exception.code, 404) self.assertEqual(context.exception.response.code, 404) @gen_test def test_future_http_error_no_raise(self): response = yield self.http_client.fetch( self.get_url("/notfound"), raise_error=False ) self.assertEqual(response.code, 404) @gen_test def test_reuse_request_from_response(self): # The response.request attribute should be an HTTPRequest, not # a _RequestProxy. # This test uses self.http_client.fetch because self.fetch calls # self.get_url on the input unconditionally. url = self.get_url("/hello") response = yield self.http_client.fetch(url) self.assertEqual(response.request.url, url) self.assertTrue(isinstance(response.request, HTTPRequest)) response2 = yield self.http_client.fetch(response.request) self.assertEqual(response2.body, b"Hello world!") @gen_test def test_bind_source_ip(self): url = self.get_url("/hello") request = HTTPRequest(url, network_interface="127.0.0.1") response = yield self.http_client.fetch(request) self.assertEqual(response.code, 200) with self.assertRaises((ValueError, HTTPError)) as context: # type: ignore request = HTTPRequest(url, network_interface="not-interface-or-ip") yield self.http_client.fetch(request) self.assertIn("not-interface-or-ip", str(context.exception)) def test_all_methods(self): for method in ["GET", "DELETE", "OPTIONS"]: response = self.fetch("/all_methods", method=method) self.assertEqual(response.body, utf8(method)) for method in ["POST", "PUT", "PATCH"]: response = self.fetch("/all_methods", method=method, body=b"") self.assertEqual(response.body, utf8(method)) response = self.fetch("/all_methods", method="HEAD") self.assertEqual(response.body, b"") response = self.fetch( "/all_methods", method="OTHER", allow_nonstandard_methods=True ) self.assertEqual(response.body, b"OTHER") def test_body_sanity_checks(self): # These methods require a body. for method in ("POST", "PUT", "PATCH"): with self.assertRaises(ValueError) as context: self.fetch("/all_methods", method=method, raise_error=True) self.assertIn("must not be None", str(context.exception)) resp = self.fetch( "/all_methods", method=method, allow_nonstandard_methods=True ) self.assertEqual(resp.code, 200) # These methods don't allow a body. for method in ("GET", "DELETE", "OPTIONS"): with self.assertRaises(ValueError) as context: self.fetch( "/all_methods", method=method, body=b"asdf", raise_error=True ) self.assertIn("must be None", str(context.exception)) # In most cases this can be overridden, but curl_httpclient # does not allow body with a GET at all. if method != "GET": self.fetch( "/all_methods", method=method, body=b"asdf", allow_nonstandard_methods=True, raise_error=True, ) self.assertEqual(resp.code, 200) # This test causes odd failures with the combination of # curl_httpclient (at least with the version of libcurl available # on ubuntu 12.04), TwistedIOLoop, and epoll. For POST (but not PUT), # curl decides the response came back too soon and closes the connection # to start again. It does this *before* telling the socket callback to # unregister the FD. Some IOLoop implementations have special kernel # integration to discover this immediately. Tornado's IOLoops # ignore errors on remove_handler to accommodate this behavior, but # Twisted's reactor does not. The removeReader call fails and so # do all future removeAll calls (which our tests do at cleanup). # # def test_post_307(self): # response = self.fetch("/redirect?status=307&url=/post", # method="POST", body=b"arg1=foo&arg2=bar") # self.assertEqual(response.body, b"Post arg1: foo, arg2: bar") def test_put_307(self): response = self.fetch( "/redirect?status=307&url=/put", method="PUT", body=b"hello" ) response.rethrow() self.assertEqual(response.body, b"Put body: hello") def test_non_ascii_header(self): # Non-ascii headers are sent as latin1. response = self.fetch("/set_header?k=foo&v=%E9") response.rethrow() self.assertEqual(response.headers["Foo"], native_str("\u00e9")) def test_response_times(self): # A few simple sanity checks of the response time fields to # make sure they're using the right basis (between the # wall-time and monotonic clocks). start_time = time.time() response = self.fetch("/hello") response.rethrow() self.assertIsNotNone(response.request_time) assert response.request_time is not None # for mypy self.assertGreaterEqual(response.request_time, 0) self.assertLess(response.request_time, 1.0) # A very crude check to make sure that start_time is based on # wall time and not the monotonic clock. self.assertIsNotNone(response.start_time) assert response.start_time is not None # for mypy self.assertLess(abs(response.start_time - start_time), 1.0) for k, v in response.time_info.items(): self.assertTrue(0 <= v < 1.0, f"time_info[{k}] out of bounds: {v}") def test_zero_timeout(self): response = self.fetch("/hello", connect_timeout=0) self.assertEqual(response.code, 200) response = self.fetch("/hello", request_timeout=0) self.assertEqual(response.code, 200) response = self.fetch("/hello", connect_timeout=0, request_timeout=0) self.assertEqual(response.code, 200) @gen_test def test_error_after_cancel(self): fut = self.http_client.fetch(self.get_url("/404")) self.assertTrue(fut.cancel()) with ExpectLog(app_log, "Exception after Future was cancelled") as el: # We can't wait on the cancelled Future any more, so just # let the IOLoop run until the exception gets logged (or # not, in which case we exit the loop and ExpectLog will # raise). for i in range(100): yield gen.sleep(0.01) if el.logged_stack: break def test_header_crlf(self): # Ensure that the client doesn't allow CRLF injection in headers. RFC 9112 section 2.2 # prohibits a bare CR specifically and "a recipient MAY recognize a single LF as a line # terminator" so we check each character separately as well as the (redundant) CRLF pair. for header, name in [ ("foo\rbar:", "cr"), ("foo\nbar:", "lf"), ("foo\r\nbar:", "crlf"), ]: with self.subTest(name=name, position="value"): with self.assertRaises(ValueError): self.fetch("/hello", headers={"foo": header}) with self.subTest(name=name, position="key"): with self.assertRaises(ValueError): self.fetch("/hello", headers={header: "foo"})
HTTPClientCommonTestCase
python
sqlalchemy__sqlalchemy
test/sql/test_roles.py
{ "start": 1654, "end": 1766 }
class ____: def __clause_element__(self): return not_a_thing2 not_a_thing3 = NotAThing3()
NotAThing3
python
getsentry__sentry
src/sentry/notifications/api/endpoints/user_notification_settings_providers.py
{ "start": 1029, "end": 3777 }
class ____(UserEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ALERTS_NOTIFICATIONS def get(self, request: Request, user: User) -> Response: """ Retrieve the notification provider preferences for a user. Returns a list of NotificationSettingProvider rows. """ notifications_settings = NotificationSettingProvider.objects.filter( user_id=user.id, ) notification_type = request.GET.get("type") if notification_type: try: validate_type(notification_type) except ParameterValidationError: return self.respond({"type": ["Invalid type"]}, status=400) notifications_settings = notifications_settings.filter( type=notification_type, ) notification_preferences = serialize( list(notifications_settings), request.user, NotificationSettingsProviderSerializer() ) return Response(notification_preferences) def put(self, request: Request, user: User) -> Response: """ Update the notification provider preferences for a user. Provider is an array of provider names. Returns an array of NotificationSettingProvider rows for the updated providers. """ serializer = UserNotificationSettingsProvidersDetailsSerializer(data=request.data) if not serializer.is_valid(): return self.respond(serializer.errors, status=400) data = serializer.validated_data new_rows = [] with transaction.atomic(router.db_for_write(NotificationSettingProvider)): for provider in PERSONAL_NOTIFICATION_PROVIDERS: value = ( NotificationSettingsOptionEnum.ALWAYS.value if provider in data["providers"] else NotificationSettingsOptionEnum.NEVER.value ) ( notification_setting_provider, _, ) = NotificationSettingProvider.objects.update_or_create( user_id=user.id, scope_type=data["scope_type"], scope_identifier=data["scope_identifier"], type=data["type"], provider=provider, defaults={"value": value}, ) new_rows.append(notification_setting_provider) return Response( serialize(new_rows, request.user, NotificationSettingsProviderSerializer()), status=status.HTTP_201_CREATED, )
UserNotificationSettingsProvidersEndpoint
python
PyCQA__bandit
tests/unit/formatters/test_json.py
{ "start": 386, "end": 3835 }
class ____(testtools.TestCase): def setUp(self): super().setUp() conf = config.BanditConfig() self.manager = manager.BanditManager(conf, "file") (tmp_fd, self.tmp_fname) = tempfile.mkstemp() self.context = { "filename": self.tmp_fname, "lineno": 4, "linerange": [4], } self.check_name = "hardcoded_bind_all_interfaces" self.issue = issue.Issue( bandit.MEDIUM, issue.Cwe.MULTIPLE_BINDS, bandit.MEDIUM, "Possible binding to all interfaces.", ) self.candidates = [ issue.Issue( issue.Cwe.MULTIPLE_BINDS, bandit.LOW, bandit.LOW, "Candidate A", lineno=1, ), issue.Issue( bandit.HIGH, issue.Cwe.MULTIPLE_BINDS, bandit.HIGH, "Candiate B", lineno=2, ), ] self.manager.out_file = self.tmp_fname self.issue.fname = self.context["filename"] self.issue.lineno = self.context["lineno"] self.issue.linerange = self.context["linerange"] self.issue.test = self.check_name self.manager.results.append(self.issue) self.manager.metrics = metrics.Metrics() # mock up the metrics for key in ["_totals", "binding.py"]: self.manager.metrics.data[key] = {"loc": 4, "nosec": 2} for criteria, default in constants.CRITERIA: for rank in constants.RANKING: self.manager.metrics.data[key][f"{criteria}.{rank}"] = 0 @mock.patch("bandit.core.manager.BanditManager.get_issue_list") def test_report(self, get_issue_list): self.manager.files_list = ["binding.py"] self.manager.scores = [ { "SEVERITY": [0] * len(constants.RANKING), "CONFIDENCE": [0] * len(constants.RANKING), } ] get_issue_list.return_value = collections.OrderedDict( [(self.issue, self.candidates)] ) with open(self.tmp_fname, "w") as tmp_file: b_json.report( self.manager, tmp_file, self.issue.severity, self.issue.confidence, ) with open(self.tmp_fname) as f: data = json.loads(f.read()) self.assertIsNotNone(data["generated_at"]) self.assertEqual(self.tmp_fname, data["results"][0]["filename"]) self.assertEqual( self.issue.severity, data["results"][0]["issue_severity"] ) self.assertEqual( self.issue.confidence, data["results"][0]["issue_confidence"] ) self.assertEqual(self.issue.text, data["results"][0]["issue_text"]) self.assertEqual( self.context["lineno"], data["results"][0]["line_number"] ) self.assertEqual( self.context["linerange"], data["results"][0]["line_range"] ) self.assertEqual(self.check_name, data["results"][0]["test_name"]) self.assertIn("candidates", data["results"][0]) self.assertIn("more_info", data["results"][0]) self.assertIsNotNone(data["results"][0]["more_info"])
JsonFormatterTests
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 31600, "end": 31700 }
class ____(DomainMixin, DeleteViewWithMessage): success_message = _("Domain deleted")
DomainDelete
python
google__jax
jax/_src/pallas/mosaic/core.py
{ "start": 1393, "end": 1891 }
class ____(enum.Enum): PARALLEL = "parallel" CORE_PARALLEL = "core_parallel" SUBCORE_PARALLEL = "subcore_parallel" ARBITRARY = "arbitrary" PARALLEL = GridDimensionSemantics.PARALLEL CORE_PARALLEL = GridDimensionSemantics.CORE_PARALLEL SUBCORE_PARALLEL = GridDimensionSemantics.SUBCORE_PARALLEL ARBITRARY = GridDimensionSemantics.ARBITRARY DimensionSemantics = ( Literal["parallel", "core_parallel", "subcore_parallel", "arbitrary"] | GridDimensionSemantics )
GridDimensionSemantics
python
keras-team__keras
keras/src/callbacks/csv_logger.py
{ "start": 231, "end": 3391 }
class ____(Callback): """Callback that streams epoch results to a CSV file. Supports all values that can be represented as a string, including 1D iterables such as `np.ndarray`. Args: filename: Filename of the CSV file, e.g. `'run/log.csv'`. separator: String used to separate elements in the CSV file. append: Boolean. True: append if file exists (useful for continuing training). False: overwrite existing file. Example: ```python csv_logger = CSVLogger('training.log') model.fit(X_train, Y_train, callbacks=[csv_logger]) ``` """ def __init__(self, filename, separator=",", append=False): super().__init__() self.sep = separator self.filename = file_utils.path_to_string(filename) self.append = append self.writer = None self.keys = None self.append_header = True self.csv_file = None def on_train_begin(self, logs=None): if self.append: if file_utils.exists(self.filename): with file_utils.File(self.filename, "r") as f: self.append_header = not bool(len(f.readline())) mode = "a" else: mode = "w" # ensure csv_file is None or closed before reassigning if self.csv_file and not self.csv_file.closed: self.csv_file.close() self.csv_file = file_utils.File(self.filename, mode) # Reset writer and keys self.writer = None self.keys = None def on_epoch_end(self, epoch, logs=None): logs = logs or {} def handle_value(k): is_zero_dim_ndarray = isinstance(k, np.ndarray) and k.ndim == 0 if isinstance(k, str): return k elif ( isinstance(k, collections.abc.Iterable) and not is_zero_dim_ndarray ): return f'"[{", ".join(map(str, k))}]"' else: return k if self.keys is None: self.keys = sorted(logs.keys()) val_keys_found = False for key in self.keys: if key.startswith("val_"): val_keys_found = True break if not val_keys_found and self.keys: self.keys.extend([f"val_{k}" for k in self.keys]) if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep fieldnames = ["epoch"] + (self.keys or []) self.writer = csv.DictWriter( self.csv_file, fieldnames=fieldnames, dialect=CustomDialect ) if self.append_header: self.writer.writeheader() row_dict = collections.OrderedDict({"epoch": epoch}) row_dict.update( (key, handle_value(logs.get(key, "NA"))) for key in self.keys ) self.writer.writerow(row_dict) self.csv_file.flush() def on_train_end(self, logs=None): if self.csv_file and not self.csv_file.closed: self.csv_file.close() self.writer = None
CSVLogger
python
squidfunk__mkdocs-material
material/plugins/social/layout.py
{ "start": 2342, "end": 2531 }
class ____(Config): color = Type(str, default = "") image = Type(str, default = "") # # ----------------------------------------------------------------------------- # Icon
Background
python
tensorflow__tensorflow
tensorflow/python/keras/layers/core.py
{ "start": 39135, "end": 48196 }
class ____(Layer): """Just your regular densely-connected NN layer. `Dense` implements the operation: `output = activation(dot(input, kernel) + bias)` where `activation` is the element-wise activation function passed as the `activation` argument, `kernel` is a weights matrix created by the layer, and `bias` is a bias vector created by the layer (only applicable if `use_bias` is `True`). These are all attributes of `Dense`. Note: If the input to the layer has a rank greater than 2, then `Dense` computes the dot product between the `inputs` and the `kernel` along the last axis of the `inputs` and axis 0 of the `kernel` (using `tf.tensordot`). For example, if input has dimensions `(batch_size, d0, d1)`, then we create a `kernel` with shape `(d1, units)`, and the `kernel` operates along axis 2 of the `input`, on every sub-tensor of shape `(1, 1, d1)` (there are `batch_size * d0` such sub-tensors). The output in this case will have shape `(batch_size, d0, units)`. Besides, layer attributes cannot be modified after the layer has been called once (except the `trainable` attribute). When a popular kwarg `input_shape` is passed, then keras will create an input layer to insert before the current layer. This can be treated equivalent to explicitly defining an `InputLayer`. Example: >>> # Create a `Sequential` model and add a Dense layer as the first layer. >>> model = tf.keras.models.Sequential() >>> model.add(tf.keras.Input(shape=(16,))) >>> model.add(tf.keras.layers.Dense(32, activation='relu')) >>> # Now the model will take as input arrays of shape (None, 16) >>> # and output arrays of shape (None, 32). >>> # Note that after the first layer, you don't need to specify >>> # the size of the input anymore: >>> model.add(tf.keras.layers.Dense(32)) >>> model.output_shape (None, 32) Args: units: Positive integer, dimensionality of the output space. activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). kernel_constraint: Constraint function applied to the `kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. Input shape: N-D tensor with shape: `(batch_size, ..., input_dim)`. The most common situation would be a 2D input with shape `(batch_size, input_dim)`. Output shape: N-D tensor with shape: `(batch_size, ..., units)`. For instance, for a 2D input with shape `(batch_size, input_dim)`, the output would have shape `(batch_size, units)`. """ def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Dense, self).__init__( activity_regularizer=activity_regularizer, **kwargs) self.units = int(units) if not isinstance(units, int) else units if self.units < 0: raise ValueError(f'Received an invalid value for `units`, expected ' f'a positive integer, got {units}.') self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.input_spec = InputSpec(min_ndim=2) self.supports_masking = True def build(self, input_shape): dtype = dtypes.as_dtype(self.dtype or K.floatx()) if not (dtype.is_floating or dtype.is_complex): raise TypeError('Unable to build `Dense` layer with non-floating point ' 'dtype %s' % (dtype,)) input_shape = tensor_shape.TensorShape(input_shape) last_dim = tensor_shape.dimension_value(input_shape[-1]) if last_dim is None: raise ValueError('The last dimension of the inputs to `Dense` ' 'should be defined. Found `None`.') self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim}) self.kernel = self.add_weight( 'kernel', shape=[last_dim, self.units], initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, dtype=self.dtype, trainable=True) if self.use_bias: self.bias = self.add_weight( 'bias', shape=[self.units,], initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, dtype=self.dtype, trainable=True) else: self.bias = None self.built = True def call(self, inputs): if inputs.dtype.base_dtype != self._compute_dtype_object.base_dtype: inputs = math_ops.cast(inputs, dtype=self._compute_dtype_object) rank = inputs.shape.rank if rank == 2 or rank is None: # We use embedding_lookup_sparse as a more efficient matmul operation for # large sparse input tensors. The op will result in a sparse gradient, as # opposed to sparse_ops.sparse_tensor_dense_matmul which results in dense # gradients. This can lead to sigfinicant speedups, see b/171762937. if isinstance(inputs, sparse_tensor.SparseTensor): # We need to fill empty rows, as the op assumes at least one id per row. inputs, _ = sparse_ops.sparse_fill_empty_rows(inputs, 0) # We need to do some munging of our input to use the embedding lookup as # a matrix multiply. We split our input matrix into separate ids and # weights tensors. The values of the ids tensor should be the column # indices of our input matrix and the values of the weights tensor # can continue to the actual matrix weights. # The column arrangement of ids and weights # will be summed over and does not matter. See the documentation for # sparse_ops.sparse_tensor_dense_matmul a more detailed explanation # of the inputs to both ops. ids = sparse_tensor.SparseTensor( indices=inputs.indices, values=inputs.indices[:, 1], dense_shape=inputs.dense_shape) weights = inputs outputs = embedding_ops.embedding_lookup_sparse_v2( self.kernel, ids, weights, combiner='sum') else: outputs = gen_math_ops.MatMul(a=inputs, b=self.kernel) # Broadcast kernel to inputs. else: outputs = standard_ops.tensordot(inputs, self.kernel, [[rank - 1], [0]]) # Reshape the output back to the original ndim of the input. if not context.executing_eagerly(): shape = inputs.shape.as_list() output_shape = shape[:-1] + [self.kernel.shape[-1]] outputs.set_shape(output_shape) if self.use_bias: outputs = nn_ops.bias_add(outputs, self.bias) if self.activation is not None: outputs = self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) input_shape = input_shape.with_rank_at_least(2) if tensor_shape.dimension_value(input_shape[-1]) is None: raise ValueError( 'The innermost dimension of input_shape must be defined, but saw: %s' % (input_shape,)) return input_shape[:-1].concatenate(self.units) def get_config(self): config = super(Dense, self).get_config() config.update({ 'units': self.units, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) }) return config
Dense
python
scrapy__scrapy
tests/test_request_cb_kwargs.py
{ "start": 757, "end": 1656 }
class ____: """ Make sure spider middlewares are able to update the keyword arguments """ async def process_start(self, start): async for request in start: if request.callback.__name__ == "parse_spider_mw": request.cb_kwargs["from_process_start"] = True yield request def process_spider_input(self, response): request = response.request if request.callback.__name__ == "parse_spider_mw": request.cb_kwargs["from_process_spider_input"] = True def process_spider_output(self, response, result): for element in result: if ( isinstance(element, Request) and element.callback.__name__ == "parse_spider_mw_2" ): element.cb_kwargs["from_process_spider_output"] = True yield element
InjectArgumentsSpiderMiddleware
python
pytorch__pytorch
torchgen/_autoheuristic/mixed_mm/test_mixed_mm.py
{ "start": 1114, "end": 9425 }
class ____(LearnedHeuristicDecision): def __init__(self) -> None: self.choices: list[Choice] = [] self.fill_choices() def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: return ( metadata.name == self.get_name() and metadata.shared_memory == 166912 and str(metadata.device_capa) == "(8, 0)" ) def get_confidence_threshold(self) -> float: return 0.0 def get_choice(self, idx: int) -> Optional[str]: if idx < len(self.choices): return self.choices[idx] return None def fill_choices(self) -> None: self.choices.append('extern_fallback_mixed_mm') self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') def get_name(self) -> str: return 'mixed_mm' def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]: if str(context.get_value('1LEQmLEQ16')) != 'True': if context.get_value('m') <= 32.5: if context.get_value('n') <= 6976.0: if context.get_value('n') <= 3520.0: if context.get_value('m*n') <= 37632.0: return None else: return [(1.000, 13)] else: if context.get_value('m*k') <= 452352.0: return [(0.590, 13), (0.256, 8), (0.103, 7), (0.051, 11)] else: return [(0.778, 8), (0.222, 13)] else: if context.get_value('k*n') <= 102776832.0: if context.get_value('n') <= 14656.0: return [(1.000, 11)] else: return [(0.889, 11), (0.111, 13)] else: return [(1.000, 11)] else: if context.get_value('m*n') <= 446464.0: if context.get_value('m*n') <= 223424.0: if context.get_value('mat1_stride_0') <= 3968.0: return None else: return None else: if context.get_value('m*n') <= 346112.0: return [(0.960, 16), (0.040, 7)] else: return [(0.750, 16), (0.136, 14), (0.114, 7)] else: if str(context.get_value('33LEQmLEQ64')) != 'True': if context.get_value('n') <= 6976.0: return [(1.000, 14)] else: return [(0.753, 2), (0.222, 1), (0.015, 7), (0.007, 16), (0.004, 12)] else: if context.get_value('n') <= 13888.0: return [(0.710, 14), (0.275, 21), (0.014, 12)] else: return [(0.374, 19), (0.339, 20), (0.106, 21), (0.101, 16), (0.066, 17), (0.009, 14), (0.004, 18)] else: if context.get_value('n') <= 3520.0: if context.get_value('arith_intensity') <= 3.994754433631897: if str(context.get_value('mat2_dtype')) != 'torch.uint8': if context.get_value('m*k') <= 18944.0: return [(0.577, 5), (0.423, 6)] else: return [(0.988, 5), (0.012, 6)] else: if context.get_value('arith_intensity') <= 2.9899919033050537: return None else: return None else: if context.get_value('arith_intensity') <= 7.956453561782837: if context.get_value('k*n') <= 9244032.0: return [(0.822, 5), (0.178, 6)] else: return [(0.977, 5), (0.023, 0)] else: if context.get_value('m*k') <= 978944.0: return [(1.000, 5)] else: return [(0.971, 5), (0.029, 0)] else: if context.get_value('n') <= 13632.0: if context.get_value('n') <= 6976.0: return [(1.000, 6)] else: if context.get_value('k') <= 3968.0: return [(0.617, 3), (0.111, 5), (0.099, 7), (0.086, 9), (0.062, 6), (0.025, 8)] else: return [(0.779, 8), (0.119, 5), (0.053, 7), (0.035, 6), (0.013, 3)] else: if context.get_value('k*n') <= 39518208.0: return [(0.385, 4), (0.327, 3), (0.192, 6), (0.038, 7), (0.038, 10), (0.019, 5)] else: if context.get_value('n') <= 20800.0: return [(0.821, 6), (0.121, 7), (0.029, 4), (0.014, 5), (0.007, 3), (0.007, 8)] else: return [(0.530, 7), (0.386, 6), (0.046, 8), (0.021, 3), (0.015, 4), (0.002, 5)] """, ) def test_mixedmm_h100(self) -> None: run_bash("get_mixedmm_dataset.sh") run_bash("gen_mixedmm_heuristic_h100.sh") file_path = "../../../torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py" h100_heuristic_generated_code = read_file_to_string(file_path) self.assertExpectedInline( h100_heuristic_generated_code, """\ # flake8: noqa: B950 # fmt: off # This file was generated by AutoHeuristic. Do not modify it manually! # To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/ from typing import Optional from torch._inductor.autoheuristic.autoheuristic_utils import ( AHContext, AHMetadata, Choice, ) from torch._inductor.autoheuristic.learnedheuristic_interface import ( LearnedHeuristicDecision, )
MixedMMA100
python
sqlalchemy__sqlalchemy
test/orm/test_assorted_eager.py
{ "start": 735, "end": 10130 }
class ____(fixtures.MappedTest): run_deletes = None run_inserts = "once" run_setup_mappers = "once" @classmethod def define_tables(cls, metadata): Table( "owners", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", String(30)), ) Table( "categories", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(20)), ) Table( "tests", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column( "owner_id", Integer, ForeignKey("owners.id"), nullable=False ), Column( "category_id", Integer, ForeignKey("categories.id"), nullable=False, ), ) Table( "options", metadata, Column( "test_id", Integer, ForeignKey("tests.id"), primary_key=True ), Column( "owner_id", Integer, ForeignKey("owners.id"), primary_key=True ), Column( "someoption", sa.Boolean, server_default=sa.false(), nullable=False, ), ) @classmethod def setup_classes(cls): class Owner(cls.Basic): pass class Category(cls.Basic): pass class Thing(cls.Basic): pass class Option(cls.Basic): pass @classmethod def setup_mappers(cls): Category, owners, Option, tests, Thing, Owner, options, categories = ( cls.classes.Category, cls.tables.owners, cls.classes.Option, cls.tables.tests, cls.classes.Thing, cls.classes.Owner, cls.tables.options, cls.tables.categories, ) cls.mapper_registry.map_imperatively(Owner, owners) cls.mapper_registry.map_imperatively(Category, categories) cls.mapper_registry.map_imperatively( Option, options, properties=dict( owner=relationship(Owner, viewonly=True), test=relationship(Thing, viewonly=True), ), ) cls.mapper_registry.map_imperatively( Thing, tests, properties=dict( owner=relationship(Owner, backref="tests"), category=relationship(Category), owner_option=relationship( Option, primaryjoin=sa.and_( tests.c.id == options.c.test_id, tests.c.owner_id == options.c.owner_id, ), foreign_keys=[options.c.test_id, options.c.owner_id], uselist=False, ), ), ) @classmethod def insert_data(cls, connection): Owner, Category, Option, Thing = ( cls.classes.Owner, cls.classes.Category, cls.classes.Option, cls.classes.Thing, ) session = Session(connection) o = Owner() c = Category(name="Some Category") session.add_all( ( Thing(owner=o, category=c), Thing( owner=o, category=c, owner_option=Option(someoption=True) ), Thing(owner=o, category=c, owner_option=Option()), ) ) session.flush() def test_noorm(self, connection): """test the control case""" tests, options, categories = ( self.tables.tests, self.tables.options, self.tables.categories, ) # I want to display a list of tests owned by owner 1 # if someoption is false or they haven't specified it yet (null) # but not if they set it to true (example someoption is for hiding) # desired output for owner 1 # test_id, cat_name # 1 'Some Category' # 3 " # not orm style correct query print("Obtaining correct results without orm") result = connection.execute( sa.select(tests.c.id, categories.c.name) .where( sa.and_( tests.c.owner_id == 1, sa.or_( options.c.someoption == None, # noqa options.c.someoption == False, ), ) ) .order_by(tests.c.id) .select_from( tests.join(categories).outerjoin( options, sa.and_( tests.c.id == options.c.test_id, tests.c.owner_id == options.c.owner_id, ), ) ) ).fetchall() eq_(result, [(1, "Some Category"), (3, "Some Category")]) def test_withoutjoinedload(self): Thing, tests, options = ( self.classes.Thing, self.tables.tests, self.tables.options, ) s = fixture_session() result = ( s.query(Thing) .select_from( tests.outerjoin( options, sa.and_( tests.c.id == options.c.test_id, tests.c.owner_id == options.c.owner_id, ), ) ) .filter( sa.and_( tests.c.owner_id == 1, sa.or_( options.c.someoption == None, # noqa options.c.someoption == False, ), ) ) ) result_str = ["%d %s" % (t.id, t.category.name) for t in result] eq_(result_str, ["1 Some Category", "3 Some Category"]) def test_withjoinedload(self): """ Test that an joinedload locates the correct "from" clause with which to attach to, when presented with a query that already has a complicated from clause. """ Thing, tests, options = ( self.classes.Thing, self.tables.tests, self.tables.options, ) s = fixture_session() q = s.query(Thing).options(sa.orm.joinedload(Thing.category)) result = q.select_from( tests.outerjoin( options, sa.and_( tests.c.id == options.c.test_id, tests.c.owner_id == options.c.owner_id, ), ) ).filter( sa.and_( tests.c.owner_id == 1, sa.or_( options.c.someoption == None, options.c.someoption == False, # noqa ), ) ) result_str = ["%d %s" % (t.id, t.category.name) for t in result] eq_(result_str, ["1 Some Category", "3 Some Category"]) def test_dslish(self): """test the same as withjoinedload except using generative""" Thing, tests, options = ( self.classes.Thing, self.tables.tests, self.tables.options, ) s = fixture_session() q = s.query(Thing).options(sa.orm.joinedload(Thing.category)) result = q.filter( sa.and_( tests.c.owner_id == 1, sa.or_( options.c.someoption == None, options.c.someoption == False, # noqa ), ) ).outerjoin(Thing.owner_option) result_str = ["%d %s" % (t.id, t.category.name) for t in result] eq_(result_str, ["1 Some Category", "3 Some Category"]) def test_without_outerjoin_literal(self): Thing, tests = (self.classes.Thing, self.tables.tests) s = fixture_session() q = s.query(Thing).options(sa.orm.joinedload(Thing.category)) result = q.filter( (tests.c.owner_id == 1) & text( "options.someoption is null or options.someoption=:opt" ).bindparams(opt=False) ).join(Thing.owner_option) result_str = ["%d %s" % (t.id, t.category.name) for t in result] eq_(result_str, ["3 Some Category"]) def test_withoutouterjoin(self): Thing, tests, options = ( self.classes.Thing, self.tables.tests, self.tables.options, ) s = fixture_session() q = s.query(Thing).options(sa.orm.joinedload(Thing.category)) result = q.filter( (tests.c.owner_id == 1) & ( (options.c.someoption == None) | (options.c.someoption == False) ) # noqa ).join(Thing.owner_option) result_str = ["%d %s" % (t.id, t.category.name) for t in result] eq_(result_str, ["3 Some Category"])
EagerTest