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
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-falkordb/tests/test_pg_stores_falkordb.py
{ "start": 289, "end": 4627 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): """Setup method called once for the entire test class.""" # Start FalkorDB container try: cls.container = docker_client.containers.run( "falkordb/falkordb:latest", detach=True, name="falkordb_test_instance_pg", ports={"6379/tcp": 6380}, ) time.sleep(2) # Allow time for the container to initialize except Exception as e: print(f"Error starting FalkorDB container: {e}") raise # Set up the property graph store and clear database cls.pg_store = FalkorDBPropertyGraphStore(url="redis://localhost:6380") cls.pg_store.structured_query("MATCH (n) DETACH DELETE n") # Clear the database @classmethod def tearDownClass(cls): """Teardown method called once after all tests are done.""" try: cls.container.stop() cls.container.remove() except Exception as e: print(f"Error stopping/removing container: {e}") def test_pg_graph(self): # Create two entity nodes entity1 = EntityNode(label="PERSON", name="Logan", properties={"age": 28}) entity2 = EntityNode(label="ORGANIZATION", name="LlamaIndex") # Create a relation relation = Relation( label="WORKS_FOR", source_id=entity1.id, target_id=entity2.id, properties={"since": 2023}, ) self.pg_store.upsert_nodes([entity1, entity2]) self.pg_store.upsert_relations([relation]) source_node = TextNode(text="Logan (age 28), works for LlamaIndex since 2023.") relations = [ Relation( label="MENTIONS", target_id=entity1.id, source_id=source_node.node_id, ), Relation( label="MENTIONS", target_id=entity2.id, source_id=source_node.node_id, ), ] self.pg_store.upsert_llama_nodes([source_node]) self.pg_store.upsert_relations(relations) kg_nodes = self.pg_store.get(ids=[entity1.id]) self.assertEqual(len(kg_nodes), 1) self.assertEqual(kg_nodes[0].label, "PERSON") self.assertEqual(kg_nodes[0].name, "Logan") kg_nodes = self.pg_store.get(properties={"age": 28}) self.assertEqual(len(kg_nodes), 1) self.assertEqual(kg_nodes[0].label, "PERSON") self.assertEqual(kg_nodes[0].name, "Logan") # Get paths from a node paths = self.pg_store.get_rel_map(kg_nodes, depth=1) for path in paths: self.assertEqual(path[0].id, entity1.id) self.assertEqual(path[2].id, entity2.id) self.assertEqual(path[1].id, relation.id) query = "MATCH (n:`__Entity__`) RETURN n" result = self.pg_store.structured_query(query) self.assertEqual(len(result), 2) # Get the original text node back llama_nodes = self.pg_store.get_llama_nodes([source_node.node_id]) self.assertEqual(len(llama_nodes), 1) self.assertEqual(llama_nodes[0].text, source_node.text) # Upsert a new node new_node = EntityNode( label="PERSON", name="Logan", properties={"age": 28, "location": "Canada"} ) self.pg_store.upsert_nodes([new_node]) kg_nodes = self.pg_store.get(properties={"age": 28}) self.assertEqual(len(kg_nodes), 1) self.assertEqual(kg_nodes[0].label, "PERSON") self.assertEqual(kg_nodes[0].name, "Logan") self.assertEqual(kg_nodes[0].properties["location"], "Canada") # Deleting # Delete our entities self.pg_store.delete(ids=[entity1.id, entity2.id]) # Delete our text nodes self.pg_store.delete(ids=[source_node.node_id]) nodes = self.pg_store.get(ids=[entity1.id, entity2.id]) self.assertEqual(len(nodes), 0) text_nodes = self.pg_store.get_llama_nodes([source_node.node_id]) self.assertEqual(len(text_nodes), 0) self.pg_store.switch_graph("new_graph") self.pg_store.refresh_schema() if __name__ == "__main__": unittest.main()
TestFalkorDBPropertyGraphStore
python
ansible__ansible
test/lib/ansible_test/_internal/provider/source/unversioned.py
{ "start": 259, "end": 2241 }
class ____(SourceProvider): """Fallback source provider when no other provider matches the content root.""" sequence = 0 # disable automatic detection @staticmethod def is_content_root(path: str) -> bool: """Return True if the given path is a content root for this provider.""" return False def get_paths(self, path: str) -> list[str]: """Return the list of available content paths under the given path.""" paths = [] kill_any_dir = ( '.idea', '.pytest_cache', '__pycache__', 'ansible.egg-info', 'ansible_base.egg-info', 'ansible_core.egg-info', ) kill_sub_dir = { 'test': ( 'results', 'cache', 'output', ), 'tests': ( 'output', ), } kill_sub_file = { '': ( TIMEOUT_PATH, ), } kill_extensions = ( '.pyc', '.pyo', '.retry', ) for root, dir_names, file_names in os.walk(path): rel_root = os.path.relpath(root, path) if rel_root == '.': rel_root = '' for kill in kill_any_dir + kill_sub_dir.get(rel_root, ()): if kill in dir_names: dir_names.remove(kill) kill_files = kill_sub_file.get(rel_root, ()) paths.extend([os.path.join(rel_root, file_name) for file_name in file_names if not os.path.splitext(file_name)[1] in kill_extensions and file_name not in kill_files]) # include directory symlinks since they will not be traversed and would otherwise go undetected paths.extend([os.path.join(rel_root, dir_name) + os.path.sep for dir_name in dir_names if os.path.islink(to_bytes(dir_name))]) return paths
UnversionedSource
python
kamyu104__LeetCode-Solutions
Python/check-for-contradictions-in-equations.py
{ "start": 1967, "end": 3120 }
class ____(object): def checkContradictions(self, equations, values): """ :type equations: List[List[str]] :type values: List[float] :rtype: bool """ def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def iter_dfs(adj, u, lookup): stk = [u] lookup[u] = 1.0 while stk: u = stk.pop() for v, k in adj[u]: if v in lookup: if not isclose(lookup[v], lookup[u]*k): return True continue lookup[v] = lookup[u]*k stk.append(v) return False adj = collections.defaultdict(set) for (a, b), k in itertools.izip(equations, values): adj[a].add((b, 1.0/k)) adj[b].add((a, 1.0*k)) lookup = {} for u in adj.iterkeys(): if u in lookup: continue if iter_dfs(adj, u, lookup): return True return False
Solution2
python
facebook__pyre-check
pyre_extensions/tests/safe_json_test.py
{ "start": 646, "end": 723 }
class ____(Movie, total=False): not_required: str
MovieWithNonRequiredField
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-graphql/llama_index/tools/graphql/base.py
{ "start": 131, "end": 1186 }
class ____(BaseToolSpec): """Requests Tool.""" spec_functions = ["graphql_request"] def __init__(self, url: str, headers: Optional[dict] = {}): self.headers = headers self.url = url def graphql_request(self, query: str, variables: str, operation_name: str): r""" Use this tool to make a GraphQL query against the server. Args: query (str): The GraphQL query to execute variables (str): The variable values for the query operation_name (str): The name for the query example input: "query":"query Ships {\n ships {\n id\n model\n name\n type\n status\n }\n}", "variables":{}, "operation_name":"Ships" """ res = requests.post( self.url, headers=self.headers, json={ "query": query, "variables": variables, "operationName": operation_name, }, ) return res.text
GraphQLToolSpec
python
doocs__leetcode
solution/0300-0399/0368.Largest Divisible Subset/Solution.py
{ "start": 0, "end": 582 }
class ____: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) f = [1] * n k = 0 for i in range(n): for j in range(i): if nums[i] % nums[j] == 0: f[i] = max(f[i], f[j] + 1) if f[k] < f[i]: k = i m = f[k] i = k ans = [] while m: if nums[k] % nums[i] == 0 and f[i] == m: ans.append(nums[i]) k, m = i, m - 1 i -= 1 return ans
Solution
python
arrow-py__arrow
arrow/locales.py
{ "start": 62354, "end": 64814 }
class ____(Locale): def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: form = self.timeframes[timeframe] if isinstance(form, Mapping): if delta < 0: form = form["past"] elif delta > 0: form = form["future"] else: raise ValueError( "Icelandic Locale does not support units with a delta of zero. " "Please consider making a contribution to fix this issue." ) # FIXME: handle when delta is 0 return form.format(abs(delta)) names = ["is", "is-is"] past = "fyrir {0} síðan" future = "eftir {0}" timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { "now": "rétt í þessu", "second": {"past": "sekúndu", "future": "sekúndu"}, "seconds": {"past": "{0} nokkrum sekúndum", "future": "nokkrar sekúndur"}, "minute": {"past": "einni mínútu", "future": "eina mínútu"}, "minutes": {"past": "{0} mínútum", "future": "{0} mínútur"}, "hour": {"past": "einum tíma", "future": "einn tíma"}, "hours": {"past": "{0} tímum", "future": "{0} tíma"}, "day": {"past": "einum degi", "future": "einn dag"}, "days": {"past": "{0} dögum", "future": "{0} daga"}, "month": {"past": "einum mánuði", "future": "einn mánuð"}, "months": {"past": "{0} mánuðum", "future": "{0} mánuði"}, "year": {"past": "einu ári", "future": "eitt ár"}, "years": {"past": "{0} árum", "future": "{0} ár"}, } meridians = {"am": "f.h.", "pm": "e.h.", "AM": "f.h.", "PM": "e.h."} month_names = [ "", "janúar", "febrúar", "mars", "apríl", "maí", "júní", "júlí", "ágúst", "september", "október", "nóvember", "desember", ] month_abbreviations = [ "", "jan", "feb", "mar", "apr", "maí", "jún", "júl", "ágú", "sep", "okt", "nóv", "des", ] day_names = [ "", "mánudagur", "þriðjudagur", "miðvikudagur", "fimmtudagur", "föstudagur", "laugardagur", "sunnudagur", ] day_abbreviations = ["", "mán", "þri", "mið", "fim", "fös", "lau", "sun"]
IcelandicLocale
python
gevent__gevent
src/greentest/3.14/test_socket.py
{ "start": 274289, "end": 275173 }
class ____(unittest.TestCase): def check_set_quickack(self, sock): # quickack already true by default on some OS distributions opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) if opt: sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 0) opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) self.assertFalse(opt) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1) opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) self.assertTrue(opt) def test_set_quickack(self): sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP) with sock: self.check_set_quickack(sock) @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
TestQuickackFlag
python
euske__pdfminer
pdfminer/layout.py
{ "start": 8177, "end": 8473 }
class ____(LTExpandableContainer, LTText): def __init__(self): LTText.__init__(self) LTExpandableContainer.__init__(self) return def get_text(self): return ''.join(obj.get_text() for obj in self if isinstance(obj, LTText)) ## LTTextLine ##
LTTextContainer
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 25810, "end": 26622 }
class ____(models.Model): """ Historic table foreign key to historic table. In this case as_of queries on the origin model (this one) or on the target model (the other one) will traverse the foreign key relationship honoring the timepoint of the original query. This only happens when both tables involved are historic. NOTE: related_name has to be different than the one used in TestParticipantToHistoricOrganization as they are sharing the same target table. """ name = models.CharField(max_length=15, unique=True) organization = HistoricForeignKey( TestOrganizationWithHistory, on_delete=CASCADE, related_name="historic_participants", ) history = HistoricalRecords()
TestHistoricParticipanToHistoricOrganization
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 27893, "end": 28388 }
class ____(ProjectAdminMixin, PrivateViewMixin): """Project redirects view and form view.""" form_class = RedirectForm template_name = "redirects/redirect_form.html" context_object_name = "redirect" lookup_url_kwarg = "redirect_pk" def get_success_url(self): return reverse( "projects_redirects", args=[self.get_project().slug], ) def get_queryset(self): return self.get_project().redirects.all()
ProjectRedirectsMixin
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/special_math_test.py
{ "start": 8844, "end": 12670 }
class ____(test.TestCase): _use_log = False _grid = GridSpec(min=-100., max=100., shape=[1, 2, 3, 8]) _error32 = ErrorSpec(rtol=1e-4, atol=0) _error64 = ErrorSpec(rtol=1e-7, atol=0) def assert_all_true(self, v): self.assertAllEqual(np.ones_like(v, dtype=np.bool_), v) def assert_all_false(self, v): self.assertAllEqual(np.zeros_like(v, dtype=np.bool_), v) def _test_grad_finite(self, dtype): x = constant_op.constant([-100., 0., 100.], dtype=dtype) output = (sm.log_ndtr(x) if self._use_log else sm.ndtr(x)) fn = sm.log_ndtr if self._use_log else sm.ndtr # Not having the lambda sanitizer means we'd get an `IndexError` whenever # the user supplied function has default args. output, grad_output = _value_and_gradient( lambda x_: fn(x_), x) # pylint: disable=unnecessary-lambda # isfinite checks for NaN and Inf. output_, grad_output_ = self.evaluate([output, grad_output]) self.assert_all_true(np.isfinite(output_)) self.assert_all_true(np.isfinite(grad_output_[0])) def _test_grad_accuracy(self, dtype, grid_spec, error_spec): raw_grid = _make_grid(dtype, grid_spec) grid = ops.convert_to_tensor(raw_grid) with self.cached_session(): fn = sm.log_ndtr if self._use_log else sm.ndtr # If there are N points in the grid, # grad_eval.shape = (N, N), with grad_eval[i, j] the partial derivative of # the ith output point w.r.t. the jth grid point. We only expect the # diagonal to be nonzero. # TODO(b/31131137): Replace tf.compat.v1.test.compute_gradient with our # own custom gradient evaluation to ensure we correctly handle small # function delta. grad_eval, _ = gradient_checker.compute_gradient(grid, grid_spec.shape, fn(grid), grid_spec.shape) grad_eval = np.diag(grad_eval) # Check for NaN separately in order to get informative failures. self.assert_all_false(np.isnan(grad_eval)) self.assert_all_true(grad_eval > 0.) # isfinite checks for NaN and Inf. self.assert_all_true(np.isfinite(grad_eval)) # Do the same checks but explicitly compute the gradient. # (We did this because we're not sure if we trust # tf.test.compute_gradient.) grad_eval = gradients_impl.gradients(fn(grid), grid)[0].eval() self.assert_all_false(np.isnan(grad_eval)) if self._use_log: g = np.reshape(grad_eval, [-1]) half = np.ceil(len(g) / 2) self.assert_all_true(g[:int(half)] > 0.) self.assert_all_true(g[int(half):] >= 0.) else: # The ndtr gradient will only be non-zero in the range [-14, 14] for # float32 and [-38, 38] for float64. self.assert_all_true(grad_eval >= 0.) # isfinite checks for NaN and Inf. self.assert_all_true(np.isfinite(grad_eval)) # Versus scipy. if not (special and stats): return expected = stats.norm.pdf(raw_grid) if self._use_log: expected /= special.ndtr(raw_grid) expected[np.isnan(expected)] = 0. # Scipy prematurely goes to zero at some places that we don't. So don't # include these in the comparison. self.assertAllClose( expected.astype(np.float64)[expected < 0], grad_eval.astype(np.float64)[expected < 0], rtol=error_spec.rtol, atol=error_spec.atol) @test_util.run_deprecated_v1 def test_float32(self): self._test_grad_accuracy(np.float32, self._grid, self._error32) self._test_grad_finite(np.float32) @test_util.run_deprecated_v1 def test_float64(self): self._test_grad_accuracy(np.float64, self._grid, self._error64) self._test_grad_finite(np.float64)
NdtrGradientTest
python
ansible__ansible
test/integration/targets/collections/test_plugins/override_formerly_core_masked_test.py
{ "start": 215, "end": 365 }
class ____(object): def tests(self): return { 'formerly_core_masked_test': override_formerly_core_masked_test }
TestModule
python
lazyprogrammer__machine_learning_examples
unsupervised_class3/dcgan_theano.py
{ "start": 4069, "end": 5744 }
class ____: def __init__(self, mi, mo, output_shape, apply_batch_norm, filtersz=5, stride=2, f=T.nnet.relu): # mi = input feature map size # mo = output feature map size self.filter_shape = (mi, mo, filtersz, filtersz) W = 0.02*np.random.randn(*self.filter_shape) self.W = theano.shared(W) self.b = theano.shared(np.zeros(mo)) self.params = [self.W, self.b] self.updates = [] # in case we do batch norm if apply_batch_norm: self.gamma = theano.shared(np.ones(mo)) self.beta = theano.shared(np.zeros(mo)) self.params += [self.gamma, self.beta] self.running_mean = theano.shared(np.zeros(mo)) self.running_var = theano.shared(np.zeros(mo)) self.f = f self.stride = stride self.output_shape = output_shape self.apply_batch_norm = apply_batch_norm self.params = [self.W, self.b] def forward(self, X, is_training): conv_out = T.nnet.abstract_conv.conv2d_grad_wrt_inputs( X, self.W, input_shape=self.output_shape, filter_shape=self.filter_shape, border_mode='half', subsample=(self.stride, self.stride) ) conv_out += self.b.dimshuffle('x', 0, 'x', 'x') # apply batch normalization if self.apply_batch_norm: conv_out, new_running_mean, new_running_var = batch_norm( conv_out, self.gamma, self.beta, self.running_mean, self.running_var, is_training, 'spatial' ) if is_training: self.updates = [ (self.running_mean, new_running_mean), (self.running_var, new_running_var), ] return self.f(conv_out)
FractionallyStridedConvLayer
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/all_static_fields.py
{ "start": 887, "end": 2111 }
class ____: c: int d: str def parameter_sink_dataclass(parameter: Dataclass) -> None: pass def return_source_dataclass() -> Dataclass: return Dataclass(c=0, d="") def parameter_sink_optional_dataclass(parameter: Optional[Dataclass]) -> None: pass def return_source_optional_dataclass() -> Optional[Dataclass]: return None def parameter_sink_union_dataclass_regular( parameter: Union[Dataclass, RegularClass] ) -> None: pass def return_source_union_dataclass_regular() -> Union[Dataclass, RegularClass]: return RegularClass(a=0, b="") # Builtins do not have attributes, so we just add a sink on the whole parameter. def parameter_sink_builtin_parameters(x: int, y: str, z: List[int], t: bool) -> None: pass # Builtins do not have attributes, so we just add a source on the whole return value. def return_source_builtin_int() -> int: return 0 def return_source_builtin_list() -> List[int]: return [] # If a parameter is not annotated, we just add a sink on the whole parameter. def parameter_sink_unnannotated(x) -> None: pass # If the return value is not annotated, we just add a source on value. def return_source_unnannotated(): return 0
Dataclass
python
PyCQA__pylint
tests/functional/m/missing/missing_kwoa.py
{ "start": 732, "end": 1218 }
class ____: @typing.overload def __init__(self, *, first, second, third): pass @typing.overload def __init__(self, *, first, second): pass @typing.overload def __init__(self, *, first): pass def __init__( self, *, first, second: typing.Optional[str] = None, third: typing.Optional[str] = None, ): self._first = first self._second = second self._third = third
Parent
python
jina-ai__jina
jina/serve/runtimes/gateway/health_model.py
{ "start": 340, "end": 477 }
class ____(BaseModel): """Pydantic BaseModel for Jina health check, used as the response model in REST app.""" ...
JinaHealthModel
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 53361, "end": 53826 }
class ____(IPredicate): def __call__(info, request): """ The ``info`` object is a dictionary containing two keys: - "match" is a dictionary of parameters that becomes ``request.matchdict`` if the route is selected (all route predicates match). - "route" is the :class:`.IRoute` object being matched. Return ``True`` if the route should be selected or ``False`` otherwise. """
IRoutePredicate
python
readthedocs__readthedocs.org
readthedocs/oauth/tests/test_githubapp_webhook.py
{ "start": 1161, "end": 37398 }
class ____(TestCase): def setUp(self): self.user = get(User) self.project = get(Project, users=[self.user], default_branch="main") self.version_latest = self.project.versions.get(slug=LATEST) self.version = get( Version, project=self.project, verbose_name="1.0", type=BRANCH, active=True ) self.version_main = get( Version, project=self.project, verbose_name="main", type=BRANCH, active=True ) self.version_tag = get( Version, project=self.project, verbose_name="2.0", type=TAG, active=True ) self.socialaccount = get( SocialAccount, user=self.user, provider=GitHubAppProvider.id ) self.installation = get( GitHubAppInstallation, installation_id=1111, target_id=1111, target_type=GitHubAccountType.USER, ) self.remote_repository = get( RemoteRepository, remote_id="1234", name="repo", full_name="user/repo", vcs_provider=GitHubAppProvider.id, github_app_installation=self.installation, ) self.project.remote_repository = self.remote_repository self.project.save() self.url = reverse("github_app_webhook") def post_webhook(self, event, payload): headers = { GITHUB_EVENT_HEADER: event, GITHUB_SIGNATURE_HEADER: get_signature(payload), } return self.client.post( self.url, data=payload, content_type="application/json", headers=headers ) @mock.patch.object(GitHubAppService, "sync") def test_installation_created(self, sync): new_installation_id = 2222 assert not GitHubAppInstallation.objects.filter( installation_id=new_installation_id ).exists() payload = { "action": "created", "installation": { "id": new_installation_id, "target_id": 2222, "target_type": GitHubAccountType.USER, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 installation = GitHubAppInstallation.objects.get( installation_id=new_installation_id ) assert installation.target_id == 2222 assert installation.target_type == GitHubAccountType.USER sync.assert_called_once() @mock.patch.object(GitHubAppService, "sync") def test_installation_created_with_existing_installation(self, sync): paylod = { "action": "created", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation", paylod) assert r.status_code == 200 sync.assert_called_once() self.installation.refresh_from_db() assert self.installation.target_id == 1111 assert self.installation.target_type == GitHubAccountType.USER assert GitHubAppInstallation.objects.count() == 1 @mock.patch.object(GitHubAppService, "sync") def test_installation_unsuspended(self, sync): new_installation_id = 2222 assert GitHubAppInstallation.objects.count() == 1 assert not GitHubAppInstallation.objects.filter( installation_id=new_installation_id ).exists() payload = { "action": "unsuspended", "installation": { "id": new_installation_id, "target_id": 2222, "target_type": GitHubAccountType.USER, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 installation = GitHubAppInstallation.objects.get( installation_id=new_installation_id ) assert installation.target_id == 2222 assert installation.target_type == GitHubAccountType.USER sync.assert_called_once() assert GitHubAppInstallation.objects.count() == 2 @mock.patch.object(GitHubAppService, "sync") def test_installation_unsuspended_with_existing_installation(self, sync): paylod = { "action": "unsuspended", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation", paylod) assert r.status_code == 200 sync.assert_called_once() self.installation.refresh_from_db() assert self.installation.target_id == 1111 assert self.installation.target_type == GitHubAccountType.USER assert GitHubAppInstallation.objects.count() == 1 def test_installation_deleted(self): payload = { "action": "deleted", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 assert not GitHubAppInstallation.objects.filter( installation_id=self.installation.installation_id ).exists() def test_installation_deleted_with_non_existing_installation(self): install_id = 2222 assert not GitHubAppInstallation.objects.filter( installation_id=install_id ).exists() payload = { "action": "deleted", "installation": { "id": install_id, "target_id": 2222, "target_type": GitHubAccountType.USER, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 assert not GitHubAppInstallation.objects.filter(installation_id=2222).exists() def test_installation_suspended(self): assert GitHubAppInstallation.objects.filter( installation_id=self.installation.installation_id ).exists() payload = { "action": "suspended", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 assert not GitHubAppInstallation.objects.filter( installation_id=self.installation.installation_id ).exists() def test_installation_suspended_with_non_existing_installation(self): install_id = 2222 assert not GitHubAppInstallation.objects.filter( installation_id=install_id ).exists() payload = { "action": "suspended", "installation": { "id": install_id, "target_id": 2222, "target_type": GitHubAccountType.USER, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 assert not GitHubAppInstallation.objects.filter(installation_id=2222).exists() def test_installation_new_permissions_accepted(self): payload = { "action": "new_permissions_accepted", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation", payload) assert r.status_code == 200 @mock.patch.object(GitHubAppService, "update_or_create_repositories") def test_installation_repositories_added(self, update_or_create_repositories): payload = { "action": "added", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "repository_selection": "selected", "repositories_added": [ { "id": 1234, "name": "repo1", "full_name": "user/repo1", "private": False, }, { "id": 5678, "name": "repo2", "full_name": "user/repo2", "private": True, }, ], } r = self.post_webhook("installation_repositories", payload) assert r.status_code == 200 update_or_create_repositories.assert_called_once_with([1234, 5678]) @mock.patch.object(GitHubAppService, "sync") def test_installation_repositories_added_all(self, sync): payload = { "action": "added", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "repository_selection": "all", } r = self.post_webhook("installation_repositories", payload) assert r.status_code == 200 sync.assert_called_once() def test_installation_repositories_removed(self): assert self.installation.repositories.count() == 1 payload = { "action": "removed", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "repository_selection": "selected", "repositories_removed": [ { "id": 1234, "name": "repo1", "full_name": "user/repo1", "private": False, }, { "id": 5678, "name": "repo2", "full_name": "user/repo2", "private": True, }, ], } r = self.post_webhook("installation_repositories", payload) assert r.status_code == 200 assert self.installation.repositories.count() == 0 @mock.patch.object(GitHubAppService, "sync") def test_installation_target(self, sync): payload = { "action": "renamed", "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, } r = self.post_webhook("installation_target", payload) assert r.status_code == 200 sync.assert_called_once() @mock.patch("readthedocs.core.views.hooks.sync_repository_task") def test_push_branch_created(self, sync_repository_task): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": True, "deleted": False, "ref": "refs/heads/branch", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 sync_repository_task.apply_async.assert_called_once_with( args=[self.version_latest.pk], kwargs={"build_api_key": mock.ANY}, ) @mock.patch("readthedocs.core.views.hooks.sync_repository_task") def test_push_tag_created(self, sync_repository_task): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": True, "deleted": False, "ref": "refs/tags/tag", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 sync_repository_task.apply_async.assert_called_once_with( args=[self.version_latest.pk], kwargs={"build_api_key": mock.ANY}, ) @mock.patch("readthedocs.core.views.hooks.sync_repository_task") def test_push_branch_deleted(self, sync_repository_task): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": False, "deleted": True, "ref": "refs/heads/branch", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 sync_repository_task.apply_async.assert_called_once_with( args=[self.version_latest.pk], kwargs={"build_api_key": mock.ANY}, ) @mock.patch("readthedocs.core.views.hooks.sync_repository_task") def test_push_tag_deleted(self, sync_repository_task): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": False, "deleted": True, "ref": "refs/tags/tag", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 sync_repository_task.apply_async.assert_called_once_with( args=[self.version_latest.pk], kwargs={"build_api_key": mock.ANY}, ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_push_branch(self, trigger_build): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": False, "deleted": False, "ref": "refs/heads/main", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 trigger_build.assert_has_calls( [ mock.call(project=self.project, version=self.version_main), mock.call(project=self.project, version=self.version_latest), ] ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_push_tag(self, trigger_build): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "created": False, "deleted": False, "ref": "refs/tags/2.0", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("push", payload) assert r.status_code == 200 trigger_build.assert_called_once_with( project=self.project, version=self.version_tag, ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_opened(self, trigger_build): self.project.external_builds_enabled = True self.project.save() payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "opened", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version = self.project.versions.get(verbose_name="1", type=EXTERNAL) assert external_version.identifier == "1234abcd" assert external_version.state == EXTERNAL_VERSION_STATE_OPEN assert external_version.active trigger_build.assert_called_once_with( project=self.project, version=external_version, commit=external_version.identifier, ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_opened_pr_previews_disabled(self, trigger_build): self.project.external_builds_enabled = False self.project.save() payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "opened", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 assert not self.project.versions.filter(verbose_name="1", type=EXTERNAL).exists() trigger_build.assert_not_called() @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_reopened(self, trigger_build): self.project.external_builds_enabled = True self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234changeme", state=EXTERNAL_VERSION_STATE_CLOSED, ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "reopened", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234abcd" assert external_version.state == EXTERNAL_VERSION_STATE_OPEN assert external_version.active trigger_build.assert_called_once_with( project=self.project, version=external_version, commit=external_version.identifier, ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_reopened_pr_previews_disabled(self, trigger_build): self.project.external_builds_enabled = False self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234changeme", state=EXTERNAL_VERSION_STATE_CLOSED, ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "reopened", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234changeme" assert external_version.state == EXTERNAL_VERSION_STATE_CLOSED assert external_version.active trigger_build.assert_not_called() @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_synchronize(self, trigger_build): self.project.external_builds_enabled = True self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234changeme", ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "synchronize", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234abcd" assert external_version.state == EXTERNAL_VERSION_STATE_OPEN assert external_version.active trigger_build.assert_called_once_with( project=self.project, version=external_version, commit=external_version.identifier, ) @mock.patch("readthedocs.core.views.hooks.trigger_build") def test_pull_request_synchronize_pr_previews_disabled(self, trigger_build): self.project.external_builds_enabled = False self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234changeme", state=EXTERNAL_VERSION_STATE_OPEN, ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "synchronize", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234changeme" assert external_version.state == EXTERNAL_VERSION_STATE_OPEN assert external_version.active trigger_build.assert_not_called() def test_pull_request_closed(self): self.project.external_builds_enabled = True self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234abcd", ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "closed", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234abcd" assert external_version.state == EXTERNAL_VERSION_STATE_CLOSED assert external_version.active def test_pull_request_closed_pr_previews_disabled(self): self.project.external_builds_enabled = False self.project.save() external_version = get( Version, project=self.project, verbose_name="1", type=EXTERNAL, active=True, identifier="1234abcd", ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "closed", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 external_version.refresh_from_db() assert external_version.identifier == "1234abcd" assert external_version.state == EXTERNAL_VERSION_STATE_CLOSED assert external_version.active def test_pull_request_edited(self): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "edited", "pull_request": { "number": 1, "head": { "ref": "new-feature", "sha": "1234abcd", }, "base": { "ref": "main", }, }, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("pull_request", payload) assert r.status_code == 200 @mock.patch.object(GitHubAppService, "update_or_create_repositories") def test_repository_edited(self, update_or_create_repositories): actions = ["edited", "renamed", "transferred", "privatized", "publicized"] for action in actions: update_or_create_repositories.reset_mock() payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": action, "changes": {}, "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("repository", payload) assert r.status_code == 200 update_or_create_repositories.assert_called_once_with( [self.remote_repository.remote_id] ) def test_repository_created(self): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "created", "repository": { "id": 5678, "full_name": "user/repo2", }, } r = self.post_webhook("repository", payload) assert r.status_code == 200 @mock.patch.object(GitHubAppService, "sync") def test_organization_member_added(self, sync): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "member_added", } r = self.post_webhook("organization", payload) assert r.status_code == 200 sync.assert_called_once() @mock.patch.object(GitHubAppService, "sync") def test_organization_member_removed(self, sync): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "member_removed", } r = self.post_webhook("organization", payload) assert r.status_code == 200 sync.assert_called_once() @mock.patch.object(GitHubAppService, "sync") def test_organization_renamed(self, sync): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "renamed", } r = self.post_webhook("organization", payload) assert r.status_code == 200 sync.assert_called_once() def test_organization_deleted(self): organization_id = 1234 get( RemoteOrganization, remote_id=str(organization_id), name="org", vcs_provider=GitHubAppProvider.id, ) payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "deleted", "organization": { "id": organization_id, "login": "org", }, } r = self.post_webhook("organization", payload) assert r.status_code == 200 assert not RemoteOrganization.objects.filter( remote_id=str(organization_id) ).exists() def test_organization_member_invited(self): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "member_invited", } r = self.post_webhook("organization", payload) assert r.status_code == 200 @mock.patch.object(GitHubAppService, "update_or_create_repositories") def test_member_added(self, update_or_create_repositories): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "added", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("member", payload) assert r.status_code == 200 update_or_create_repositories.assert_called_once_with( [self.remote_repository.remote_id] ) @mock.patch.object(GitHubAppService, "update_or_create_repositories") def test_member_edited(self, update_or_create_repositories): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "edited", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("member", payload) assert r.status_code == 200 update_or_create_repositories.assert_called_once_with( [self.remote_repository.remote_id] ) @mock.patch.object(GitHubAppService, "update_or_create_repositories") def test_member_removed(self, update_or_create_repositories): payload = { "installation": { "id": self.installation.installation_id, "target_id": self.installation.target_id, "target_type": self.installation.target_type, }, "action": "removed", "repository": { "id": self.remote_repository.remote_id, "full_name": self.remote_repository.full_name, }, } r = self.post_webhook("member", payload) assert r.status_code == 200 update_or_create_repositories.assert_called_once_with( [self.remote_repository.remote_id] ) def test_github_app_authorization(self): payload = { "action": "revoked", "sender": { "login": "user", }, } r = self.post_webhook("github_app_authorization", payload) assert r.status_code == 200
TestGitHubAppWebhook
python
keras-team__keras
keras/src/losses/losses.py
{ "start": 18801, "end": 20479 }
class ____(LossFunctionWrapper): """Computes Kullback-Leibler divergence loss between `y_true` & `y_pred`. Formula: ```python loss = y_true * log(y_true / y_pred) ``` `y_true` and `y_pred` are expected to be probability distributions, with values between 0 and 1. They will get clipped to the `[0, 1]` range. Args: reduction: Type of reduction to apply to the loss. In almost all cases this should be `"sum_over_batch_size"`. Supported options are `"sum"`, `"sum_over_batch_size"`, `"mean"`, `"mean_with_sample_weight"` or `None`. `"sum"` sums the loss, `"sum_over_batch_size"` and `"mean"` sum the loss and divide by the sample size, and `"mean_with_sample_weight"` sums the loss and divides by the sum of the sample weights. `"none"` and `None` perform no aggregation. Defaults to `"sum_over_batch_size"`. name: Optional name for the loss instance. dtype: The dtype of the loss's computations. Defaults to `None`, which means using `keras.backend.floatx()`. `keras.backend.floatx()` is a `"float32"` unless set to different value (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is provided, then the `compute_dtype` will be utilized. """ def __init__( self, reduction="sum_over_batch_size", name="kl_divergence", dtype=None ): super().__init__( kl_divergence, name=name, reduction=reduction, dtype=dtype ) def get_config(self): return Loss.get_config(self) @keras_export("keras.losses.Poisson")
KLDivergence
python
realpython__materials
solid-principles-python/printers_isp.py
{ "start": 1272, "end": 1535 }
class ____(Printer, Fax, Scanner): def print(self, document): print(f"Printing {document} in color...") def fax(self, document): print(f"Faxing {document}...") def scan(self, document): print(f"Scanning {document}...")
NewPrinter
python
falconry__falcon
tests/test_middleware.py
{ "start": 4434, "end": 4558 }
class ____: def process_request(self): pass def process_response(self): pass
EmptySignatureMiddleware
python
pytorch__pytorch
test/distributed/pipelining/test_transformer.py
{ "start": 714, "end": 990 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.layers = torch.nn.Sequential(*[MLPModule(d_hid) for _ in range(n_layers)]) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.layers(x)
TransformerLike
python
great-expectations__great_expectations
great_expectations/metrics/batch/sample_values.py
{ "start": 213, "end": 347 }
class ____(BatchMetric[SampleValuesResult]): """Sample rows from a table""" name = "table.head" n_rows: int = 10
SampleValues
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 14133, "end": 14385 }
class ____(str, Enum): """ * UI: Cluster created through the UI. * JOB: Cluster created by the Databricks job scheduler. * API: Cluster created through an API call. """ ui = "UI" job = "JOB" api = "API"
ClusterSource
python
PyCQA__pylint
doc/data/messages/b/bad-super-call/good.py
{ "start": 48, "end": 130 }
class ____(Animal): def __init__(self): super(Animal, self).__init__()
Cat
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-openvino-genai/llama_index/embeddings/openvino_genai/base.py
{ "start": 387, "end": 5976 }
class ____(BaseEmbedding): model_path: str = Field(description="local path.") max_length: int = Field(description="Maximum length of input.") pooling: str = Field(description="Pooling strategy. One of ['cls', 'mean'].") normalize: bool = Field(default=True, description="Normalize embeddings or not.") query_instruction: Optional[str] = Field( description="Instruction to prepend to query text." ) text_instruction: Optional[str] = Field( description="Instruction to prepend to text." ) cache_folder: Optional[str] = Field( description="Cache folder for huggingface files.", default=None ) _model: Any = PrivateAttr() _tokenizer: Any = PrivateAttr() _device: Any = PrivateAttr() def __init__( self, model_path: str, pooling: str = "cls", max_length: int = 2048, normalize: bool = True, query_instruction: Optional[str] = None, text_instruction: Optional[str] = None, model: Optional[Any] = None, tokenizer: Optional[Any] = None, embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, callback_manager: Optional[CallbackManager] = None, device: Optional[str] = "CPU", ): try: import openvino_genai import openvino as ov core = ov.Core() except ImportError as e: raise ImportError( "Could not import openvino_genai python package. " "Please install it with: " "pip install -U openvino_genai" ) from e # use local model model = model or core.compile_model( Path(model_path) / "openvino_model.xml", device ) tokenizer = tokenizer or openvino_genai.Tokenizer(model_path) if pooling not in ["cls", "mean"]: raise ValueError(f"Pooling {pooling} not supported.") super().__init__( embed_batch_size=embed_batch_size, callback_manager=callback_manager or CallbackManager([]), model_path=model_path, max_length=max_length, pooling=pooling, normalize=normalize, query_instruction=query_instruction, text_instruction=text_instruction, ) self._device = device self._model = model self._tokenizer = tokenizer @classmethod def class_name(cls) -> str: return "OpenVINOGENAIEmbedding" def _mean_pooling(self, model_output: Any, attention_mask: Any) -> Any: """Mean Pooling - Take attention mask into account for correct averaging.""" token_embeddings = model_output[ 0 ] # First element of model_output contains all token embeddings input_mask_expanded = np.broadcast_to( np.expand_dims(attention_mask, axis=-1), token_embeddings.size() ) return np.sum(token_embeddings * input_mask_expanded, 1) / np.clip( input_mask_expanded.sum(1), a_min=1e-9 ) def _cls_pooling(self, model_output: list) -> Any: """Use the CLS token as the pooling token.""" return model_output[0][:, 0] def _embed(self, sentences: List[str]) -> List[List[float]]: """Embed sentences.""" length = self._model.inputs[0].get_partial_shape()[1] if length.is_dynamic: features = self._tokenizer.encode(sentences) else: features = self._tokenizer.encode( sentences, pad_to_max_length=True, max_length=length.get_length(), ) if "token_type_ids" in (input.any_name for input in self._model.inputs): token_type_ids = np.zeros(features.attention_mask.shape) model_input = { "input_ids": features.input_ids, "attention_mask": features.attention_mask, "token_type_ids": token_type_ids, } else: model_input = { "input_ids": features.input_ids, "attention_mask": features.attention_mask, } model_output = self._model(model_input) if self.pooling == "cls": embeddings = self._cls_pooling(model_output) else: embeddings = self._mean_pooling(model_output, model_input["attention_mask"]) if self.normalize: norm = np.linalg.norm(embeddings, ord=2, axis=1, keepdims=True) embeddings = embeddings / norm return embeddings.tolist() def _get_query_embedding(self, query: str) -> List[float]: """Get query embedding.""" query = format_query(query, self.model_name, self.query_instruction) return self._embed([query])[0] async def _aget_query_embedding(self, query: str) -> List[float]: """Get query embedding async.""" return self._get_query_embedding(query) async def _aget_text_embedding(self, text: str) -> List[float]: """Get text embedding async.""" return self._get_text_embedding(text) def _get_text_embedding(self, text: str) -> List[float]: """Get text embedding.""" text = format_text(text, self.model_name, self.text_instruction) return self._embed([text])[0] def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Get text embeddings.""" texts = [ format_text(text, self.model_name, self.text_instruction) for text in texts ] return self._embed(texts)
OpenVINOGENAIEmbedding
python
kamyu104__LeetCode-Solutions
Python/longest-substring-of-all-vowels-in-order.py
{ "start": 29, "end": 485 }
class ____(object): def longestBeautifulSubstring(self, word): """ :type word: str :rtype: int """ result = 0 l = cnt = 1 for i in xrange(len(word)-1): if word[i] > word[i+1]: l = cnt = 1 else: l += 1 cnt += int(word[i] < word[i+1]) if cnt == 5: result = max(result, l) return result
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/pyodbc.py
{ "start": 19457, "end": 19693 }
class ____(_MSUnicode): def get_dbapi_type(self, dbapi): if self.length in (None, "max") or self.length >= 2000: return (dbapi.SQL_WVARCHAR, 0, 0) else: return dbapi.SQL_WVARCHAR
_Unicode_pyodbc
python
run-llama__llama_index
llama-index-core/llama_index/core/langchain_helpers/memory_wrapper.py
{ "start": 3602, "end": 7668 }
class ____(BaseChatMemory): """ Langchain chat memory wrapper (for LlamaIndex). Args: human_prefix (str): Prefix for human input. Defaults to "Human". ai_prefix (str): Prefix for AI output. Defaults to "AI". memory_key (str): Key for memory. Defaults to "history". index (BaseIndex): LlamaIndex instance. query_kwargs (Dict[str, Any]): Keyword arguments for LlamaIndex query. input_key (Optional[str]): Input key. Defaults to None. output_key (Optional[str]): Output key. Defaults to None. """ human_prefix: str = "Human" ai_prefix: str = "AI" memory_key: str = "history" index: BaseIndex query_kwargs: Dict = Field(default_factory=dict) output_key: Optional[str] = None input_key: Optional[str] = None return_source: bool = False id_to_message: Dict[str, BaseMessage] = Field(default_factory=dict) @property def memory_variables(self) -> List[str]: """Return memory variables.""" return [self.memory_key] def _get_prompt_input_key(self, inputs: Dict[str, Any]) -> str: if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key return prompt_input_key def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Return key-value pairs given the text input to the chain.""" prompt_input_key = self._get_prompt_input_key(inputs) query_str = inputs[prompt_input_key] query_engine = self.index.as_query_engine(**self.query_kwargs) response_obj = query_engine.query(query_str) if self.return_source: source_nodes = response_obj.source_nodes if self.return_messages: # get source messages from ids source_ids = [sn.node.node_id for sn in source_nodes] source_messages = [ m for id, m in self.id_to_message.items() if id in source_ids ] # NOTE: type List[BaseMessage] response: Any = source_messages else: source_texts = [sn.node.get_content() for sn in source_nodes] response = "\n\n".join(source_texts) else: response = str(response_obj) return {self.memory_key: response} def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save the context of this model run to memory.""" prompt_input_key = self._get_prompt_input_key(inputs) if self.output_key is None: if len(outputs) != 1: raise ValueError(f"One output key expected, got {outputs.keys()}") output_key = next(iter(outputs.keys())) else: output_key = self.output_key # a bit different than existing langchain implementation # because we want to track id's for messages human_message = HumanMessage(content=inputs[prompt_input_key]) human_message_id = get_new_id(set(self.id_to_message.keys())) ai_message = AIMessage(content=outputs[output_key]) ai_message_id = get_new_id( set(self.id_to_message.keys()).union({human_message_id}) ) self.chat_memory.messages.append(human_message) self.chat_memory.messages.append(ai_message) self.id_to_message[human_message_id] = human_message self.id_to_message[ai_message_id] = ai_message human_txt = f"{self.human_prefix}: " + inputs[prompt_input_key] ai_txt = f"{self.ai_prefix}: " + outputs[output_key] human_doc = Document(text=human_txt, id_=human_message_id) ai_doc = Document(text=ai_txt, id_=ai_message_id) self.index.insert(human_doc) self.index.insert(ai_doc) def clear(self) -> None: """Clear memory contents.""" def __repr__(self) -> str: """Return representation.""" return "GPTIndexMemory()"
GPTIndexChatMemory
python
ray-project__ray
python/ray/dag/tests/test_class_dag.py
{ "start": 336, "end": 9128 }
class ____: def __init__(self, init_value): self.i = init_value def inc(self, x): self.i += x def get(self): return self.i def echo(self, x): return x @ray.method(num_returns=2) def return_two(self, x): return x, x + 1 @ray.method(num_returns=2) def inc_and_return_two(self, x): self.i += x return self.i, self.i + 1 @ray.method(num_returns=1) def return_two_as_one(self, x): return x, x + 1 @ray.method(num_returns=2) def return_two_from_three(self, x): return x, x + 1, x + 2 def test_basic_actor_dag(shared_ray_instance): @ray.remote def combine(x, y): return x + y a1 = Actor.bind(10) res = a1.get.bind() print(res) assert ray.get(res.execute()) == 10 a2 = Actor.bind(10) a1.inc.bind(2) a1.inc.bind(4) a2.inc.bind(6) dag = combine.bind(a1.get.bind(), a2.get.bind()) print(dag) assert ray.get(dag.execute()) == 32 def test_class_as_class_constructor_arg(shared_ray_instance): @ray.remote class OuterActor: def __init__(self, inner_actor): self.inner_actor = inner_actor def inc(self, x): self.inner_actor.inc.remote(x) def get(self): return ray.get(self.inner_actor.get.remote()) outer = OuterActor.bind(Actor.bind(10)) outer.inc.bind(2) dag = outer.get.bind() print(dag) assert ray.get(dag.execute()) == 12 def test_class_as_function_constructor_arg(shared_ray_instance): @ray.remote def f(actor_handle): return ray.get(actor_handle.get.remote()) dag = f.bind(Actor.bind(10)) print(dag) assert ray.get(dag.execute()) == 10 def test_basic_actor_dag_constructor_options(shared_ray_instance): a1 = Actor.bind(10) dag = a1.get.bind() print(dag) assert ray.get(dag.execute()) == 10 a1 = Actor.options(name="Actor", namespace="test", max_pending_calls=10).bind(10) dag = a1.get.bind() print(dag) # Ensure execution result is identical with .options() in init() assert ray.get(dag.execute()) == 10 # Ensure options are passed in assert a1.get_options().get("name") == "Actor" assert a1.get_options().get("namespace") == "test" assert a1.get_options().get("max_pending_calls") == 10 def test_actor_method_options(shared_ray_instance): a1 = Actor.bind(10) dag = a1.get.options(name="actor_method_options").bind() print(dag) assert ray.get(dag.execute()) == 10 assert dag.get_options().get("name") == "actor_method_options" def test_basic_actor_dag_constructor_invalid_options(shared_ray_instance): with pytest.raises( ValueError, match=r".*quantity of resource num_cpus cannot be negative.*" ): a1 = Actor.options(num_cpus=-1).bind(10) invalid_dag = a1.get.bind() ray.get(invalid_dag.execute()) def test_actor_options_complicated(shared_ray_instance): """Test a more complicated setup where we apply .options() in both constructor and method call with overlapping keys, and ensure end to end options correctness. """ @ray.remote def combine(x, y): return x + y a1 = Actor.options(name="a1_v0").bind(10) res = a1.get.options(name="v1").bind() print(res) assert ray.get(res.execute()) == 10 assert a1.get_options().get("name") == "a1_v0" assert res.get_options().get("name") == "v1" a1 = Actor.options(name="a1_v1").bind(10) # Cannot a2 = Actor.options(name="a2_v0").bind(10) a1.inc.options(name="v1").bind(2) a1.inc.options(name="v2").bind(4) a2.inc.options(name="v3").bind(6) dag = combine.options(name="v4").bind(a1.get.bind(), a2.get.bind()) print(dag) assert ray.get(dag.execute()) == 32 test_a1 = dag.get_args()[0] # call graph for a1.get.bind() test_a2 = dag.get_args()[1] # call graph for a2.get.bind() assert test_a2.get_options() == {} # No .options() at outer call # refer to a2 constructor .options() call assert ( test_a2.get_other_args_to_resolve()[PARENT_CLASS_NODE_KEY] .get_options() .get("name") == "a2_v0" ) # refer to actor method a2.inc.options() call assert ( test_a2.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v3" ) # refer to a1 constructor .options() call assert ( test_a1.get_other_args_to_resolve()[PARENT_CLASS_NODE_KEY] .get_options() .get("name") == "a1_v1" ) # refer to latest actor method a1.inc.options() call assert ( test_a1.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v2" ) # refer to first bound actor method a1.inc.options() call assert ( test_a1.get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_other_args_to_resolve()[PREV_CLASS_METHOD_CALL_KEY] .get_options() .get("name") == "v1" ) def test_pass_actor_handle(shared_ray_instance): @ray.remote class Actor: def ping(self): return "hello" @ray.remote def caller(handle): assert isinstance(handle, ray.actor.ActorHandle), handle return ray.get(handle.ping.remote()) a1 = Actor.bind() dag = caller.bind(a1) print(dag) assert ray.get(dag.execute()) == "hello" def test_dynamic_pipeline(shared_ray_instance): @ray.remote class Model: def __init__(self, arg): self.arg = arg def forward(self, x): return self.arg + str(x) @ray.remote class ModelSelection: def is_even(self, x): return x % 2 == 0 @ray.remote def pipeline(x, m1, m2, selection): sel = selection.is_even.remote(x) if ray.get(sel): result = m1.forward.remote(x) else: result = m2.forward.remote(x) return ray.get(result) m1 = Model.bind("Even: ") m2 = Model.bind("Odd: ") selection = ModelSelection.bind() even_input = pipeline.bind(20, m1, m2, selection) print(even_input) assert ray.get(even_input.execute()) == "Even: 20" odd_input = pipeline.bind(21, m1, m2, selection) print(odd_input) assert ray.get(odd_input.execute()) == "Odd: 21" def test_unsupported_bind(): @ray.remote class Actor: def ping(self): return "hello" with pytest.raises( AttributeError, match=r"\.bind\(\) cannot be used again on", ): actor = Actor.bind() _ = actor.bind() with pytest.raises( AttributeError, match=r"\.remote\(\) cannot be used on ClassMethodNodes", ): actor = Actor.bind() _ = actor.ping.remote() def test_unsupported_remote(): @ray.remote class Actor: def ping(self): return "hello" with pytest.raises(AttributeError, match="'Actor' has no attribute 'remote'"): _ = Actor.bind().remote() @ray.remote def func(): return 1 with pytest.raises(AttributeError, match=r"\.remote\(\) cannot be used on"): _ = func.bind().remote() def test_two_returns_first(): a = Actor.remote(0) with InputNode() as i: o1, o2 = a.return_two.bind(i) dag = o1 for _ in range(3): res = ray.get(dag.execute(1)) assert res == 1 def test_two_returns_second(): a = Actor.remote(0) with InputNode() as i: o1, o2 = a.return_two.bind(i) dag = o2 for _ in range(3): res = ray.get(dag.execute(1)) assert res == 2 def test_two_returns_one_reader_multi_times(): a = Actor.remote(0) b = Actor.remote(0) with InputNode() as i: o1, o2 = a.return_two.bind(i) o3 = b.echo.bind(o1) o4 = b.echo.bind(o2) dag = MultiOutputNode([o3, o4]) for _ in range(3): res = ray.get(dag.execute(1)) assert res == [1, 2] def test_two_returns_two_readers(): a = Actor.remote(0) b = Actor.remote(0) c = Actor.remote(0) with InputNode() as i: o1, o2 = a.return_two.bind(i) o3 = b.echo.bind(o1) o4 = c.echo.bind(o2) dag = MultiOutputNode([o3, o4]) for _ in range(3): res = ray.get(dag.execute(1)) assert res == [1, 2] def test_inc_two_returns(): a = Actor.remote(0) with InputNode() as i: o1, o2 = a.inc_and_return_two.bind(i) dag = MultiOutputNode([o1, o2]) for i in range(3): res = ray.get(dag.execute(1)) assert res == [i + 1, i + 2] if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", __file__]))
Actor
python
getsentry__sentry
tests/sentry/notifications/platform/msteams/test_provider.py
{ "start": 901, "end": 8163 }
class ____(TestCase): def test_default_renderer(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() rendered_template = template.render(data) renderer = MSTeamsNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) renderable = renderer.render(data=data, rendered_template=rendered_template) # Verify the basic structure of the AdaptiveCard assert renderable["type"] == "AdaptiveCard" assert renderable["version"] == CURRENT_CARD_VERSION assert renderable["$schema"] == ADAPTIVE_CARD_SCHEMA_URL assert "body" in renderable body_blocks = renderable["body"] assert len(body_blocks) == 5 # title, body, actions, chart, footer # Verify title block title_block = body_blocks[0] assert title_block["type"] == "TextBlock" assert title_block["text"] == "Mock Notification" assert title_block["size"] == TextSize.LARGE assert title_block["weight"] == TextWeight.BOLDER # Verify body block body_block = body_blocks[1] assert body_block["type"] == "TextBlock" assert body_block["text"] == "test" # Verify actions block actions_block = body_blocks[2] assert actions_block["type"] == "ActionSet" assert len(actions_block["actions"]) == 1 action = actions_block["actions"][0] assert action["type"] == ActionType.OPEN_URL assert action["title"] == "Visit Sentry" assert action["url"] == "https://www.sentry.io" # Verify chart image block chart_block = body_blocks[3] assert chart_block["type"] == "Image" assert ( chart_block["url"] == "https://raw.githubusercontent.com/knobiknows/all-the-bufo/main/all-the-bufo/bufo-pog.png" ) assert chart_block["altText"] == "Bufo Pog" # Verify footer block footer_block = body_blocks[4] assert footer_block["type"] == "TextBlock" assert footer_block["text"] == "This is a mock footer" assert footer_block["size"] == TextSize.SMALL def test_renderer_without_chart(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() base_template = template.render(data) # Override to remove chart rendered_template = NotificationRenderedTemplate( subject=base_template.subject, body=base_template.body, actions=base_template.actions, footer=base_template.footer, chart=None, # No chart ) renderer = MSTeamsNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) renderable = renderer.render(data=data, rendered_template=rendered_template) body_blocks = renderable["body"] assert len(body_blocks) == 4 # title, body, actions, footer (no chart) # Verify no chart block is present block_types = [block["type"] for block in body_blocks] assert "Image" not in block_types def test_renderer_without_footer(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() base_template = template.render(data) # Override to remove footer rendered_template = NotificationRenderedTemplate( subject=base_template.subject, body=base_template.body, actions=base_template.actions, footer=None, # No footer chart=base_template.chart, ) renderer = MSTeamsNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) renderable = renderer.render(data=data, rendered_template=rendered_template) body_blocks = renderable["body"] assert len(body_blocks) == 4 # title, body, actions, chart (no footer) # Verify no footer block with size="small" is present small_text_blocks = [ block for block in body_blocks if block.get("type") == "TextBlock" and block.get("size") == TextSize.SMALL ] assert len(small_text_blocks) == 0 def test_renderer_without_actions(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() base_template = template.render(data) # Override to remove actions rendered_template = NotificationRenderedTemplate( subject=base_template.subject, body=base_template.body, actions=[], # No actions footer=base_template.footer, chart=base_template.chart, ) renderer = MSTeamsNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) renderable = renderer.render(data=data, rendered_template=rendered_template) body_blocks = renderable["body"] assert len(body_blocks) == 4 # title, body, chart, footer # Verify no footer block with size="small" is present action_blocks = [block for block in body_blocks if block.get("type") == "ActionSet"] assert len(action_blocks) == 0 def test_renderer_multiple_actions(self) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() base_template = template.render(data) # Override with multiple actions rendered_template = NotificationRenderedTemplate( subject=base_template.subject, body=base_template.body, actions=[ NotificationRenderedAction( label="Visit Sentry", link="https://www.sentry.io", ), NotificationRenderedAction( label="View Documentation", link="https://docs.sentry.io", ), NotificationRenderedAction( label="Contact Support", link="https://help.sentry.io", ), ], footer=None, chart=None, ) renderer = MSTeamsNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) renderable = renderer.render(data=data, rendered_template=rendered_template) body_blocks = renderable["body"] actions_block = body_blocks[2] assert actions_block["type"] == "ActionSet" assert len(actions_block["actions"]) == 3 # Verify all actions actions = actions_block["actions"] assert _is_open_url_action(actions[0]) assert actions[0]["title"] == "Visit Sentry" assert actions[0]["url"] == "https://www.sentry.io" assert _is_open_url_action(actions[1]) assert actions[1]["title"] == "View Documentation" assert actions[1]["url"] == "https://docs.sentry.io" assert _is_open_url_action(actions[2]) assert actions[2]["title"] == "Contact Support" assert actions[2]["url"] == "https://help.sentry.io"
MSTeamsRendererTest
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 14851, "end": 17015 }
class ____(nn.Module): """ConvTranspose1d with asymmetric or causal padding and normalization.""" def __init__( self, config, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, groups: int = 1, bias=True, ): super().__init__() self.causal = config.use_causal_conv self.trim_right_ratio = config.trim_right_ratio self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride, groups=groups, bias=bias) if not (self.causal or self.trim_right_ratio == 1.0): raise ValueError("`trim_right_ratio` != 1.0 only makes sense for causal convolutions") kernel_size = self.conv.kernel_size[0] stride = self.conv.stride[0] padding_total = kernel_size - stride # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be # removed at the very end, when keeping only the right length for the output, # as removing it here would require also passing the length at the matching layer # in the encoder. if self.causal: # Trim the padding on the right according to the specified ratio # if trim_right_ratio = 1.0, trim everything from right self.padding_right = math.ceil(padding_total * self.trim_right_ratio) else: # Asymmetric padding required for odd strides self.padding_right = padding_total // 2 self.padding_left = padding_total - self.padding_right def apply_weight_norm(self): weight_norm = nn.utils.weight_norm if hasattr(nn.utils.parametrizations, "weight_norm"): weight_norm = nn.utils.parametrizations.weight_norm weight_norm(self.conv) def remove_weight_norm(self): nn.utils.remove_weight_norm(self.conv) def forward(self, hidden_states): hidden_states = self.conv(hidden_states) # unpad end = hidden_states.shape[-1] - self.padding_right hidden_states = hidden_states[..., self.padding_left : end] return hidden_states
MimiConvTranspose1d
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/tf_record_dataset_test.py
{ "start": 1328, "end": 7756 }
class ____(tf_record_test_base.TFRecordTestBase, parameterized.TestCase): def _dataset_factory(self, filenames, compression_type="", num_epochs=1, batch_size=None): repeat_dataset = readers.TFRecordDataset( filenames, compression_type).repeat(num_epochs) if batch_size: return repeat_dataset.batch(batch_size) return repeat_dataset @combinations.generate(test_base.default_test_combinations()) def testConstructorErrorsTensorInput(self): with self.assertRaisesRegex( TypeError, "The `filenames` argument must contain `tf.string` elements. Got " "`tf.int32` elements."): readers.TFRecordDataset([1, 2, 3]) with self.assertRaisesRegex( TypeError, "The `filenames` argument must contain `tf.string` elements. Got " "`tf.int32` elements."): readers.TFRecordDataset(constant_op.constant([1, 2, 3])) # convert_to_tensor raises different errors in graph and eager with self.assertRaises(Exception): readers.TFRecordDataset(object()) @combinations.generate(test_base.default_test_combinations()) def testReadOneEpoch(self): # Basic test: read from file 0. dataset = self._dataset_factory(self._filenames[0]) self.assertDatasetProduces( dataset, expected_output=[self._record(0, i) for i in range(self._num_records)]) # Basic test: read from file 1. dataset = self._dataset_factory(self._filenames[1]) self.assertDatasetProduces( dataset, expected_output=[self._record(1, i) for i in range(self._num_records)]) # Basic test: read from both files. dataset = self._dataset_factory(self._filenames) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testReadTenEpochs(self): dataset = self._dataset_factory(self._filenames, num_epochs=10) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) self.assertDatasetProduces(dataset, expected_output=expected_output * 10) @combinations.generate(test_base.default_test_combinations()) def testReadTenEpochsOfBatches(self): dataset = self._dataset_factory( self._filenames, num_epochs=10, batch_size=self._num_records) expected_output = [] for j in range(self._num_files): expected_output.append( [self._record(j, i) for i in range(self._num_records)]) self.assertDatasetProduces(dataset, expected_output=expected_output * 10) @combinations.generate(test_base.default_test_combinations()) def testReadZlibFiles(self): zlib_files = [] for i, fn in enumerate(self._filenames): with open(fn, "rb") as f: cdata = zlib.compress(f.read()) zfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.z" % i) with open(zfn, "wb") as f: f.write(cdata) zlib_files.append(zfn) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) dataset = self._dataset_factory(zlib_files, compression_type="ZLIB") self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testReadGzipFiles(self): gzip_files = [] for i, fn in enumerate(self._filenames): with open(fn, "rb") as f: gzfn = os.path.join(self.get_temp_dir(), "tfrecord_%s.gz" % i) with gzip.GzipFile(gzfn, "wb") as gzf: gzf.write(f.read()) gzip_files.append(gzfn) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) dataset = self._dataset_factory(gzip_files, compression_type="GZIP") self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testReadWithBuffer(self): one_mebibyte = 2**20 dataset = readers.TFRecordDataset( self._filenames, buffer_size=one_mebibyte) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testReadFromDatasetOfFiles(self): files = dataset_ops.Dataset.from_tensor_slices(self._filenames) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) dataset = readers.TFRecordDataset(files) self.assertDatasetProduces(dataset, expected_output=expected_output) @combinations.generate(test_base.default_test_combinations()) def testReadTenEpochsFromDatasetOfFilesInParallel(self): files = dataset_ops.Dataset.from_tensor_slices( self._filenames).repeat(10) expected_output = [] for j in range(self._num_files): expected_output.extend( [self._record(j, i) for i in range(self._num_records)]) dataset = readers.TFRecordDataset(files, num_parallel_reads=4) self.assertDatasetProduces( dataset, expected_output=expected_output * 10, assert_items_equal=True) @combinations.generate(test_base.default_test_combinations()) def testPathlib(self): files = [pathlib.Path(self._filenames[0])] expected_output = [self._record(0, i) for i in range(self._num_records)] ds = readers.TFRecordDataset(files) self.assertDatasetProduces( ds, expected_output=expected_output, assert_items_equal=True) @combinations.generate(test_base.default_test_combinations()) def testName(self): files = [self._filenames[0]] expected_output = [self._record(0, i) for i in range(self._num_records)] ds = readers.TFRecordDataset(files, name="tf_record_dataset") self.assertDatasetProduces( ds, expected_output=expected_output, assert_items_equal=True)
TFRecordDatasetTest
python
Pylons__pyramid
tests/test_config/test_assets.py
{ "start": 35687, "end": 35891 }
class ____: def __init__(self, package): self.package = package self.inserted = [] def insert(self, path, source): self.inserted.append((path, source))
DummyPackageOverrides
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ012.py
{ "start": 595, "end": 889 }
class ____(models.Model): """Model with manager before fields.""" objects = "manager" class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "foobar" first_name = models.CharField(max_length=32)
ManagerBeforeField
python
getsentry__sentry
src/sentry/db/postgres/base.py
{ "start": 3205, "end": 4725 }
class ____(DjangoDatabaseWrapper): SchemaEditorClass = DatabaseSchemaEditorProxy queries_limit = 15000 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ops = DatabaseOperations(self) self.execute_wrappers.extend((_execute__include_sql_in_error, _execute__clean_params)) @auto_reconnect_connection def _cursor(self, *args, **kwargs): return super()._cursor() # We're overriding this internal method that's present in Django 1.11+, because # things were shuffled around since 1.10 resulting in not constructing a django CursorWrapper # with our CursorWrapper. We need to be passing our wrapped cursor to their wrapped cursor, # not the other way around since then we'll lose things like __enter__ due to the way this # wrapper is working (getattr on self.cursor). def _prepare_cursor(self, cursor): cursor = super()._prepare_cursor(CursorWrapper(self, cursor)) return cursor def close(self, reconnect=False): """ This ensures we don't error if the connection has already been closed. """ if self.connection is not None: if not self.connection.closed: try: self.connection.close() except psycopg2.InterfaceError: # connection was already closed by something # like pgbouncer idle timeout. pass self.connection = None
DatabaseWrapper
python
ethereum__web3.py
web3/providers/rpc/utils.py
{ "start": 1561, "end": 2144 }
class ____(BaseModel): errors: Sequence[type[BaseException]] retries: int backoff_factor: float method_allowlist: Sequence[str] def __init__( self, errors: Sequence[type[BaseException]] = None, retries: int = 5, backoff_factor: float = 0.125, method_allowlist: Sequence[str] = None, ): super().__init__( errors=errors, retries=retries, backoff_factor=backoff_factor, method_allowlist=method_allowlist or REQUEST_RETRY_ALLOWLIST, )
ExceptionRetryConfiguration
python
facebook__pyre-check
client/commands/infer.py
{ "start": 7240, "end": 11976 }
class ____(libcst.CSTTransformer): def __init__(self, qualifier: str) -> None: """ AnnotationFixer sanitizes annotations. There are two transformations we apply: (1) Strip any prefix matching `prefix` from names. This is because the pyre backend always uses fully-qualified names, but in our stubs we should not include the prefix for names coming from this module. (2) Convert `Pathlike` annotations, which come from pyre in a special-cased form that isn't a correct annotation, to a quoted `"os.Pathlike[_]"`. Note: we eventually will need to either have a proper protocol in the backend for generating python-readable types, or extend (2) to handle various other special cases where pyre outputs types that are invalid in python. """ super().__init__() self.qualifier = qualifier def leave_Attribute( self, original_node: libcst.Attribute, updated_node: libcst.Attribute, ) -> Union[libcst.Attribute, libcst.Name]: """ Note: in order to avoid complex reverse-name-matching, we're effectively operating at the top level of attributes, by using only the `original_node`. This means the transform we're performing cannot be done concurrently with a transform that has to be done incrementally. """ value = code_for_node(original_node.value) if value == self.qualifier and libcst.matchers.matches( original_node.attr, libcst.matchers.Name() ): return libcst.ensure_type(original_node.attr, libcst.Name) return original_node def leave_Subscript( self, original_node: libcst.Subscript, updated_node: Union[libcst.Subscript, libcst.SimpleString], ) -> Union[libcst.Subscript, libcst.SimpleString]: if libcst.matchers.matches( original_node.value, libcst.matchers.Name("PathLike") ): name_node = libcst.Attribute( value=libcst.Name( value="os", lpar=[], rpar=[], ), attr=libcst.Name(value="PathLike"), ) node_as_string = code_for_node(updated_node.with_changes(value=name_node)) updated_node = libcst.SimpleString(f"'{node_as_string}'") return updated_node @staticmethod def sanitize( annotation: str, qualifier: str, quote_annotations: bool = False, dequalify_all: bool = False, runtime_defined: bool = True, ) -> str: """ Transform raw annotations in an attempt to reduce incorrectly-imported annotations in generated code. TODO(T93381000): Handle qualification in a principled way and remove this: all of these transforms are attempts to hack simple fixes to the problem of us not actually understanding qualified types and existing imports. (1) If `quote_annotations` is set to True, then spit out a quoted raw annotation (with fully-qualified names). The resulting generated code will not technically be PEP 484 compliant because it will use fully qualified type names without import, but pyre can understand this and it's useful for pysa to avoid adding import lines that change traces. (2) If `dequalify_all` is set, then remove all qualifiers from any top-level type (by top-level I mean outside the outermost brackets). For example, convert `sqlalchemy.sql.schema.Column[typing.Optional[int]]` into `Column[typing.Optional[int]]`. (3) Fix PathLike annotations: convert all bare `PathLike` uses to `'os.PathLike'`; the ocaml side of pyre currently spits out an unqualified type here which is incorrect, and quoting makes the use of os safer given that we don't handle imports correctly yet. """ if quote_annotations: return f'"{annotation}"' if dequalify_all: match = re.fullmatch(r"([^.]*?\.)*?([^.]+)(\[.*\])", annotation) if match is not None: annotation = f"{match.group(2)}{match.group(3)}" try: tree = libcst.parse_module(annotation) annotation = tree.visit( AnnotationFixer( qualifier=qualifier, ) ).code except libcst._exceptions.ParserSyntaxError: pass if not runtime_defined: return f'"{annotation}"' return annotation @dataclasses.dataclass(frozen=True)
AnnotationFixer
python
getsentry__sentry-python
tests/integrations/django/myapp/views.py
{ "start": 2323, "end": 2444 }
class ____: csrf_exempt = True def __call__(self, request): return HttpResponse("ok")
SentryClassBasedView
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 9120, "end": 9288 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneStepEvent) name = "HookSkippedEvent"
GrapheneHookSkippedEvent
python
huggingface__transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
{ "start": 19167, "end": 21054 }
class ____(PreTrainedModel): config: LayoutLMv2Config base_model_prefix = "layoutlmv2" input_modalities = ("image", "text") @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" super()._init_weights(module) if isinstance(module, LayoutLMv2SelfAttention): if self.config.fast_qkv: init.zeros_(module.q_bias) init.zeros_(module.v_bias) elif isinstance(module, LayoutLMv2Model): if hasattr(module, "visual_segment_embedding"): init.normal_(module.visual_segment_embedding, mean=0.0, std=self.config.initializer_range) def my_convert_sync_batchnorm(module, process_group=None): # same as `nn.modules.SyncBatchNorm.convert_sync_batchnorm` but allowing converting from `detectron2.layers.FrozenBatchNorm2d` if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): return nn.modules.SyncBatchNorm.convert_sync_batchnorm(module, process_group) module_output = module if isinstance(module, detectron2.layers.FrozenBatchNorm2d): module_output = torch.nn.SyncBatchNorm( num_features=module.num_features, eps=module.eps, affine=True, track_running_stats=True, process_group=process_group, ) module_output.weight = torch.nn.Parameter(module.weight) module_output.bias = torch.nn.Parameter(module.bias) module_output.running_mean = module.running_mean module_output.running_var = module.running_var module_output.num_batches_tracked = torch.tensor(0, dtype=torch.long, device=module.running_mean.device) for name, child in module.named_children(): module_output.add_module(name, my_convert_sync_batchnorm(child, process_group)) del module return module_output
LayoutLMv2PreTrainedModel
python
geekcomputers__Python
mobilePhoneSpecsScrapper.py
{ "start": 99, "end": 4521 }
class ____: def __init__(self): self.phones = [] self.features = ["Brand", "Model Name", "Model Image"] self.temp1 = [] self.phones_brands = [] self.url = "https://www.phonearena.com/phones/" # GSMArena website url # Folder name on which files going to save. self.new_folder_name = "GSMArenaDataset" # It create the absolute path of the GSMArenaDataset folder. self.absolute_path = os.getcwd().strip() + "/" + self.new_folder_name def crawl_html_page(self, sub_url): url = sub_url # Url for html content parsing. # Handing the connection error of the url. try: page = requests.get(url) # It parses the html data from requested url. soup = BeautifulSoup(page.text, "html.parser") return soup except ConnectionError: print("Please check your network connection and re-run the script.") exit() except Exception: print("Please check your network connection and re-run the script.") exit() def crawl_phone_urls(self): phones_urls = [] for i in range(1, 238): # Right now they have 237 page of phone data. print(self.url + "page/" + str(i)) soup = self.crawl_html_page(self.url + "page/" + str(i)) table = soup.findAll("div", {"class": "stream-item"}) table_a = [k.find("a") for k in table] for a in table_a: temp = a["href"] phones_urls.append(temp) return phones_urls def crawl_phones_models_specification(self, li): phone_data = {} for link in li: print(link) try: soup = self.crawl_html_page(link) model = soup.find(class_="page__section page__section_quickSpecs") model_name = model.find("header").h1.text model_img_html = model.find(class_="head-image") model_img = model_img_html.find("img")["data-src"] specs_html = model.find( class_="phone__section phone__section_widget_quickSpecs" ) release_date = specs_html.find(class_="calendar") release_date = release_date.find(class_="title").p.text display = specs_html.find(class_="display") display = display.find(class_="title").p.text camera = specs_html.find(class_="camera") camera = camera.find(class_="title").p.text hardware = specs_html.find(class_="hardware") hardware = hardware.find(class_="title").p.text storage = specs_html.find(class_="storage") storage = storage.find(class_="title").p.text battery = specs_html.find(class_="battery") battery = battery.find(class_="title").p.text os = specs_html.find(class_="os") os = os.find(class_="title").p.text phone_data[model_name] = { "image": model_img, "release_date": release_date, "display": display, "camera": camera, "hardware": hardware, "storage": storage, "battery": battery, "os": os, } with open(obj.absolute_path + "-PhoneSpecs.json", "w+") as of: json.dump(phone_data, of) except Exception as error: print(f"Exception happened : {error}") continue return phone_data if __name__ == "__main__": obj = Phonearena() try: # Step 1: Scrape links to all the individual phone specs page and save it so that we don't need to run it again. phone_urls = obj.crawl_phone_urls() with open(obj.absolute_path + "-Phoneurls.json", "w") as of: json.dump(phone_urls, of) # Step 2: Iterate through all the links from the above execution and run the next command with open("obj.absolute_path+'-Phoneurls.json", "r") as inp: temp = json.load(inp) phone_specs = obj.crawl_phones_models_specification(temp) except KeyboardInterrupt: print("File has been stopped due to KeyBoard Interruption.")
Phonearena
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/dataproc.py
{ "start": 1863, "end": 3350 }
class ____(BaseTrigger): """Base class for Dataproc triggers.""" def __init__( self, region: str, project_id: str = PROVIDE_PROJECT_ID, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, polling_interval_seconds: int = 30, cancel_on_kill: bool = True, delete_on_error: bool = True, ): super().__init__() self.region = region self.project_id = project_id self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.polling_interval_seconds = polling_interval_seconds self.cancel_on_kill = cancel_on_kill self.delete_on_error = delete_on_error def get_async_hook(self): return DataprocAsyncHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) def get_sync_hook(self): # The synchronous hook is utilized to delete the cluster when a task is cancelled. # This is because the asynchronous hook deletion is not awaited when the trigger task # is cancelled. The call for deleting the cluster or job through the sync hook is not a blocking # call, which means it does not wait until the cluster or job is deleted. return DataprocHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, )
DataprocBaseTrigger
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructorCallable2.py
{ "start": 1840, "end": 2099 }
class ____: def __new__(cls) -> Any: return super().__new__(cls) def __init__(self, x: int) -> None: pass r6_2 = accepts_callable(Class6_2) reveal_type(r6_2, expected_text="() -> Any") reveal_type(r6_2(), expected_text="Any")
Class6_2
python
huggingface__transformers
src/transformers/integrations/peft.py
{ "start": 1649, "end": 36489 }
class ____: """ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT library: https://huggingface.co/docs/peft/index Currently supported PEFT methods are all non-prompt learning methods (LoRA, IA³, etc.). Other PEFT models such as prompt tuning, prompt learning are out of scope as these adapters are not "injectable" into a torch module. For using these methods, please refer to the usage guide of PEFT library. With this mixin, if the correct PEFT version is installed (>= 0.18.0), it is possible to: - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model - Attach new adapters in the model and train them with Trainer or by your own. - Attach multiple adapters and iteratively activate / deactivate them - Activate / deactivate all adapters from the model. - Get the `state_dict` of the active adapter. """ _hf_peft_config_loaded = False _prepare_peft_hotswap_kwargs: dict | None = None def load_adapter( self, peft_model_id: str | None = None, adapter_name: str | None = None, revision: str | None = None, token: str | None = None, device_map: str = "auto", max_memory: str | None = None, offload_folder: str | None = None, offload_index: int | None = None, peft_config: dict[str, Any] | None = None, adapter_state_dict: dict[str, "torch.Tensor"] | None = None, low_cpu_mem_usage: bool = False, is_trainable: bool = False, hotswap: bool | Literal["auto"] = "auto", adapter_kwargs: dict[str, Any] | None = None, ) -> None: """ Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft Requires PEFT to be installed as a backend to load the adapter weights. Args: peft_model_id (`str`, *optional*): The identifier of the model to look for on the Hub, or a local path to the saved adapter config file and adapter weights. adapter_name (`str`, *optional*): The adapter name to use. If not set, will use the name "default". revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. > [!TIP] > To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. token (`str`, `optional`): Whether to use authentication token to load the remote folder. Useful to load private repositories that are on HuggingFace Hub. You might need to call `hf auth login` and paste your tokens to cache it. device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*): A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which the model will be allocated, the device map will map the entire model to this device. Passing `device_map = 0` means put the whole model on GPU 0. To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more information about each option see [designing a device map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map). max_memory (`Dict`, *optional*): A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU and the available CPU RAM if unset. offload_folder (`str` or `os.PathLike`, `optional`): If the `device_map` contains any value `"disk"`, the folder where we will offload weights. offload_index (`int`, `optional`): `offload_index` argument to be passed to `accelerate.dispatch_model` method. peft_config (`dict[str, Any]`, *optional*): The configuration of the adapter to add, supported adapters are all non-prompt learning configs (LoRA, IA³, etc). This argument is used in case users directly pass PEFT state dicts. adapter_state_dict (`dict[str, torch.Tensor]`, *optional*): The state dict of the adapter to load. This argument is used in case users directly pass PEFT state dicts. low_cpu_mem_usage (`bool`, *optional*, defaults to `False`): Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process. is_trainable (`bool`, *optional*, defaults to `False`): Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be used for inference. hotswap : (`"auto"` or `bool`, *optional*, defaults to `"auto"`) Whether to substitute an existing (LoRA) adapter with the newly loaded adapter in-place. This means that, instead of loading an additional adapter, this will take the existing adapter weights and replace them with the weights of the new adapter. This can be faster and more memory efficient. However, the main advantage of hotswapping is that when the model is compiled with torch.compile, loading the new adapter does not require recompilation of the model. When using hotswapping, the passed `adapter_name` should be the name of an already loaded adapter. If the new adapter and the old adapter have different ranks and/or LoRA alphas (i.e. scaling), you need to call an additional method before loading the adapter: ```py model = AutoModel.from_pretrained(...) max_rank = ... # the highest rank among all LoRAs that you want to load # call *before* compiling and loading the LoRA adapter model.enable_peft_hotswap(target_rank=max_rank) model.load_adapter(file_name_1, adapter_name="default") # optionally compile the model now model = torch.compile(model, ...) output_1 = model(...) # now you can hotswap the 2nd adapter, use the same name as for the 1st # hotswap is activated by default since enable_peft_hotswap was called model.load_adapter(file_name_2, adapter_name="default") output_2 = model(...) ``` By default, hotswap is disabled and requires passing `hotswap=True`. If you called `enable_peft_hotswap` first, it is enabled. You can still manually disable it in that case by passing `hotswap=False`. Note that hotswapping comes with a couple of limitations documented here: https://huggingface.co/docs/peft/main/en/package_reference/hotswap adapter_kwargs (`dict[str, Any]`, *optional*): Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and `find_adapter_config_file` method. """ check_peft_version(min_version=MIN_PEFT_VERSION) from peft import PeftType if hotswap == "auto": # if user called model.enable_peft_hotswap and this is not the first adapter, enable hotswap hotswap_enabled = getattr(self, "_hotswap_enabled", False) not_first_adapter = bool(self._hf_peft_config_loaded and (adapter_name in self.peft_config)) hotswap = hotswap_enabled and not_first_adapter if hotswap: if (not self._hf_peft_config_loaded) or (adapter_name not in self.peft_config): raise ValueError( "To hotswap an adapter, there must already be an existing adapter with the same adapter name." ) if any(conf.peft_type != PeftType.LORA for conf in self.peft_config.values()): raise ValueError("Hotswapping is currently only supported for LoRA, please set `hotswap=False`.") # peft only supports low_cpu_mem_usage starting from v0.13.0 peft_load_kwargs = {} key_mapping = adapter_kwargs.pop("key_mapping", None) if adapter_kwargs is not None else None if key_mapping is None and any(allowed_name in self.__class__.__name__.lower() for allowed_name in VLMS): key_mapping = self._checkpoint_conversion_mapping peft_load_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage adapter_name = adapter_name if adapter_name is not None else "default" if adapter_kwargs is None: adapter_kwargs = {} from peft import PeftConfig, inject_adapter_in_model, load_peft_weights from peft.utils import set_peft_model_state_dict if self._hf_peft_config_loaded and (not hotswap) and (adapter_name in self.peft_config): raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.") elif hotswap and ((not self._hf_peft_config_loaded) or (adapter_name not in self.peft_config)): raise ValueError( "To hotswap an adapter, there must already be an existing adapter with the same adapter name." ) if peft_model_id is None and (adapter_state_dict is None and peft_config is None): raise ValueError( "You should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter." ) if "device" not in adapter_kwargs: device = self.device if not hasattr(self, "hf_device_map") else list(self.hf_device_map.values())[0] else: device = adapter_kwargs.pop("device") # To avoid PEFT errors later on with safetensors. if isinstance(device, torch.device): device = str(device) # We keep `revision` in the signature for backward compatibility if revision is not None and "revision" not in adapter_kwargs: adapter_kwargs["revision"] = revision elif revision is not None and "revision" in adapter_kwargs and revision != adapter_kwargs["revision"]: logger.error( "You passed a `revision` argument both in `adapter_kwargs` and as a standalone argument. " "The one in `adapter_kwargs` will be used." ) # Override token with adapter_kwargs' token if "token" in adapter_kwargs: token = adapter_kwargs.pop("token") if peft_config is None: adapter_config_file = find_adapter_config_file( peft_model_id, token=token, **adapter_kwargs, ) if adapter_config_file is None: raise ValueError( f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the " "adapter model." ) peft_config = PeftConfig.from_pretrained( peft_model_id, token=token, **adapter_kwargs, ) peft_config.inference_mode = not is_trainable if peft_config.peft_type != PeftType.LORA: raise ValueError("Hotswapping is currently only supported for LoRA, please set `hotswap=False`.") if not hotswap: # TODO: WE NEED TOO APPLY OUR DYNAMIC WEIGHT CONVERSION AT SOME POINT HERE! # Create and add fresh new adapters into the model, unless the weights are hotswapped inject_adapter_in_model(peft_config, self, adapter_name, **peft_load_kwargs) if not self._hf_peft_config_loaded: self._hf_peft_config_loaded = True if peft_model_id is not None: adapter_state_dict = load_peft_weights(peft_model_id, token=token, device=device, **adapter_kwargs) # We need to pre-process the state dict to remove unneeded prefixes - for backward compatibility renamings = [] if key_mapping: renamings = [entry for entry in key_mapping if isinstance(entry, WeightRenaming)] processed_adapter_state_dict = {} prefix = "base_model.model." for key, value in adapter_state_dict.items(): if key.startswith(prefix): new_key = key[len(prefix) :] else: new_key = key new_key = rename_source_key(new_key, renamings, [])[0] # For hotswapping, we need the adapter name to be present in the state dict keys if hotswap: if key.endswith("lora_A.weight") or key.endswith("lora_B.weight"): new_key = new_key[: -len(".weight")] + f".{adapter_name}.weight" elif key.endswith("lora_B.bias"): # lora_bias=True option new_key = new_key[: -len(".bias")] + f".{adapter_name}.bias" processed_adapter_state_dict[new_key] = value # Load state dict if not hotswap: incompatible_keys = set_peft_model_state_dict( self, processed_adapter_state_dict, adapter_name, **peft_load_kwargs ) if self._prepare_peft_hotswap_kwargs is not None: # For hotswapping of compiled models or adapters with different ranks. # If the user called enable_peft_hotswap, we need to ensure it is called: # - after the first adapter was loaded # - before the model is compiled and the 2nd adapter is being hotswapped in # Therefore, it needs to be called here from peft.utils.hotswap import prepare_model_for_compiled_hotswap prepare_model_for_compiled_hotswap(self, config=peft_config, **self._prepare_peft_hotswap_kwargs) # We only want to call prepare_model_for_compiled_hotswap once self._prepare_peft_hotswap_kwargs = None else: from peft.utils.hotswap import check_hotswap_configs_compatible, hotswap_adapter_from_state_dict check_hotswap_configs_compatible(self.peft_config[adapter_name], peft_config) try: hotswap_adapter_from_state_dict( model=self, state_dict=processed_adapter_state_dict, adapter_name=adapter_name, config=peft_config, ) except Exception as e: logger.error(f"Hotswapping {adapter_name} was unsucessful with the following error: \n{e}") raise incompatible_keys = None if incompatible_keys is not None: err_msg = "" origin_name = peft_model_id if peft_model_id is not None else "state_dict" # Check for unexpected keys. if hasattr(incompatible_keys, "unexpected_keys") and len(incompatible_keys.unexpected_keys) > 0: err_msg = ( f"Loading adapter weights from {origin_name} led to unexpected keys not found in the model: " f"{', '.join(incompatible_keys.unexpected_keys)}. " ) # Check for missing keys. missing_keys = getattr(incompatible_keys, "missing_keys", None) if missing_keys: # Filter missing keys specific to the current adapter, as missing base model keys are expected. lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k] if lora_missing_keys: err_msg += ( f"Loading adapter weights from {origin_name} led to missing keys in the model: " f"{', '.join(lora_missing_keys)}" ) if err_msg: logger.warning(err_msg) if peft_config.inference_mode: self.eval() # Re-dispatch model and hooks in case the model is offloaded to CPU / Disk. if ( (getattr(self, "hf_device_map", None) is not None) and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0) and len(self.peft_config) == 1 ): self._dispatch_accelerate_model( device_map=device_map, max_memory=max_memory, offload_folder=offload_folder, offload_index=offload_index, ) def enable_peft_hotswap( self, target_rank: int = 128, check_compiled: Literal["error", "warn", "ignore"] = "error" ) -> None: """Enables the possibility to hotswap PEFT adapters with different ranks, or, if the model is compiled, without triggering recompilation. Right now, hotswapping is only supported for LoRA. Calling this method is only required when hotswapping adapters and if the model is compiled or if the ranks of the loaded adapters differ. If the ranks are all identical and the model is not compiled, hotswapping works without calling this method first. Args: target_rank (`int`, *optional*, defaults to `128`): The highest rank among all the adapters that will be loaded. check_compiled (`str`, *optional*, defaults to `"error"`): How to handle the case when the model is already compiled, which should generally be avoided. The options are: - "error" (default): raise an error - "warn": issue a warning - "ignore": do nothing """ if getattr(self, "peft_config", {}): if check_compiled == "error": raise RuntimeError("Call `enable_peft_hotswap` before loading the first adapter.") elif check_compiled == "warn": logger.warning( "It is recommended to call `enable_peft_hotswap` before loading the first adapter to avoid recompilation." ) elif check_compiled != "ignore": raise ValueError( f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead." ) self._hotswap_enabled = True self._prepare_peft_hotswap_kwargs = {"target_rank": target_rank, "check_compiled": check_compiled} def add_adapter(self, adapter_config, adapter_name: str | None = None) -> None: r""" If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the default adapter name). Note that the newly added adapter is not automatically activated. To activate it, use `model.set_adapter`. Args: adapter_config (`~peft.PeftConfig`): The configuration of the adapter to add, supported adapters are non-prompt learning methods (LoRA, IA³, etc.). adapter_name (`str`, *optional*, defaults to `"default"`): The name of the adapter to add. If no name is passed, a default name is assigned to the adapter. """ check_peft_version(min_version=MIN_PEFT_VERSION) from peft import PeftConfig, inject_adapter_in_model adapter_name = adapter_name or "default" if not self._hf_peft_config_loaded: self._hf_peft_config_loaded = True elif adapter_name in self.peft_config: raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.") if not isinstance(adapter_config, PeftConfig): raise TypeError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.") # Retrieve the name or path of the model, one could also use self.config._name_or_path # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100 adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None) # TODO: WE NEED TOO APPLY OUR DYNAMIC WEIGHT CONVERSION AT SOME POINT HERE! inject_adapter_in_model(adapter_config, self, adapter_name) self.set_adapter(adapter_name) def set_adapter(self, adapter_name: list[str] | str) -> None: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters. Args: adapter_name (`Union[list[str], str]`): The name of the adapter to set. Can be also a list of strings to set multiple adapters. """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") elif isinstance(adapter_name, list): missing = set(adapter_name) - set(self.peft_config) if len(missing) > 0: raise ValueError( f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)." f" current loaded adapters are: {list(self.peft_config.keys())}" ) elif adapter_name not in self.peft_config: raise ValueError( f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}" ) from peft.tuners.tuners_utils import BaseTunerLayer from peft.utils import ModulesToSaveWrapper _adapters_has_been_set = False for _, module in self.named_modules(): if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)): module.set_adapter(adapter_name) _adapters_has_been_set = True if not _adapters_has_been_set: raise ValueError( "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters." ) def disable_adapters(self) -> None: r""" If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Disable all adapters that are attached to the model. This leads to inferring with the base model only. """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") from peft.tuners.tuners_utils import BaseTunerLayer from peft.utils import ModulesToSaveWrapper for _, module in self.named_modules(): if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)): module.enable_adapters(enabled=False) def enable_adapters(self) -> None: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Enable adapters that are attached to the model. """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") from peft.tuners.tuners_utils import BaseTunerLayer for _, module in self.named_modules(): if isinstance(module, BaseTunerLayer): module.enable_adapters(enabled=True) def active_adapters(self) -> list[str]: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters for inference) returns the list of all active adapters so that users can deal with them accordingly. For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return a single string. """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") from peft.tuners.tuners_utils import BaseTunerLayer for _, module in self.named_modules(): if isinstance(module, BaseTunerLayer): active_adapters = module.active_adapter break # For previous PEFT versions if isinstance(active_adapters, str): active_adapters = [active_adapters] return active_adapters def get_adapter_state_dict(self, adapter_name: str | None = None, state_dict: dict | None = None) -> dict: """ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT official documentation: https://huggingface.co/docs/peft Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter. If no adapter_name is passed, the active adapter is used. Args: adapter_name (`str`, *optional*): The name of the adapter to get the state dict from. If no name is passed, the active adapter is used. state_dict (nested dictionary of `torch.Tensor`, *optional*) The state dictionary of the model. Will default to `self.state_dict()`, but can be used if special precautions need to be taken when recovering the state dictionary of a model (like when using model parallelism). """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") from peft import get_peft_model_state_dict if adapter_name is None: adapter_name = self.active_adapters()[0] adapter_state_dict = get_peft_model_state_dict(self, state_dict=state_dict, adapter_name=adapter_name) return adapter_state_dict def _dispatch_accelerate_model( self, device_map: str, max_memory: int | None = None, offload_folder: str | None = None, offload_index: int | None = None, ) -> None: """ Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with accelerate (i.e. with `device_map=xxx`) Args: device_map (`str` or `dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*): A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which the model will be allocated, the device map will map the entire model to this device. Passing `device_map = 0` means put the whole model on GPU 0. To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more information about each option see [designing a device map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map). max_memory (`Dict`, *optional*): A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU and the available CPU RAM if unset. offload_folder (`str` or `os.PathLike`, *optional*): If the `device_map` contains any value `"disk"`, the folder where we will offload weights. offload_index (`int`, *optional*): The offload_index argument to be passed to `accelerate.dispatch_model` method. """ dispatch_model_kwargs = {} # Safety checker for previous `accelerate` versions # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/ if "offload_index" in inspect.signature(dispatch_model).parameters: dispatch_model_kwargs["offload_index"] = offload_index no_split_module_classes = self._no_split_modules if device_map != "sequential": max_memory = get_balanced_memory( self, max_memory=max_memory, no_split_module_classes=no_split_module_classes, low_zero=(device_map == "balanced_low_0"), ) if isinstance(device_map, str): device_map = infer_auto_device_map( self, max_memory=max_memory, no_split_module_classes=no_split_module_classes ) dispatch_model( self, device_map=device_map, offload_dir=offload_folder, **dispatch_model_kwargs, ) def delete_adapter(self, adapter_names: list[str] | str) -> None: """ Delete a PEFT adapter from the underlying model. Args: adapter_names (`Union[list[str], str]`): The name(s) of the adapter(s) to delete. """ check_peft_version(min_version=MIN_PEFT_VERSION) if not self._hf_peft_config_loaded: raise ValueError("No adapter loaded. Please load an adapter first.") from peft.functional import delete_adapter if isinstance(adapter_names, str): adapter_names = [adapter_names] # Check that all adapter names are present in the config missing_adapters = [name for name in adapter_names if name not in self.peft_config] if missing_adapters: raise ValueError( f"The following adapter(s) are not present and cannot be deleted: {', '.join(missing_adapters)}" ) prefixes = [f"{self.peft_config[adapter_name].peft_type.value.lower()}_" for adapter_name in adapter_names] for adapter_name, prefix in zip(adapter_names, prefixes): delete_adapter(self, adapter_name=adapter_name, prefix=prefix) # For transformers integration - we need to pop the adapter from the config if getattr(self, "_hf_peft_config_loaded", False) and hasattr(self, "peft_config"): self.peft_config.pop(adapter_name, None) # In case all adapters are deleted, we need to delete the config # and make sure to set the flag to False if len(self.peft_config) == 0: del self.peft_config self._hf_peft_config_loaded = False def maybe_load_adapters( pretrained_model_name_or_path, download_kwargs: DownloadKwargs, **adapter_kwargs, ): if pretrained_model_name_or_path is None or not is_peft_available(): return None, pretrained_model_name_or_path, adapter_kwargs token = download_kwargs.get("token") if download_kwargs.get("commit_hash") is None: resolved_config_file = cached_file( pretrained_model_name_or_path, CONFIG_NAME, cache_dir=download_kwargs.get("cache_dir"), force_download=bool(download_kwargs.get("force_download", False)), proxies=download_kwargs.get("proxies"), local_files_only=bool(download_kwargs.get("local_files_only", False)), token=token, revision=download_kwargs.get("revision"), subfolder=download_kwargs.get("subfolder"), _raise_exceptions_for_gated_repo=False, _raise_exceptions_for_missing_entries=False, _raise_exceptions_for_connection_errors=False, ) download_kwargs["commit_hash"] = extract_commit_hash(resolved_config_file, None) _adapter_model_path = adapter_kwargs.pop("_adapter_model_path", None) token_from_adapter_kwargs = adapter_kwargs.pop("token", None) if _adapter_model_path is None: peft_kwargs = adapter_kwargs.copy() for arg_name in ("cache_dir", "proxies", "subfolder"): # don't override revision if (arg_name not in peft_kwargs) and (arg_name in download_kwargs): peft_kwargs[arg_name] = download_kwargs[arg_name] if "commit_hash" in download_kwargs: peft_kwargs["_commit_hash"] = download_kwargs["commit_hash"] peft_kwargs["force_download"] = bool(download_kwargs.get("force_download", False)) peft_kwargs["local_files_only"] = bool(download_kwargs.get("local_files_only", False)) peft_kwargs["token"] = token or token_from_adapter_kwargs _adapter_model_path = find_adapter_config_file( pretrained_model_name_or_path, **peft_kwargs, ) if _adapter_model_path is not None and os.path.isfile(_adapter_model_path): with open(_adapter_model_path, "r", encoding="utf-8") as f: _adapter_model_path = pretrained_model_name_or_path pretrained_model_name_or_path = json.load(f)["base_model_name_or_path"] return _adapter_model_path, pretrained_model_name_or_path, adapter_kwargs
PeftAdapterMixin
python
conda__conda
conda/common/configuration.py
{ "start": 6354, "end": 8132 }
class ____(RawParameter): source = ENV_VARS_SOURCE def value(self, parameter_obj): # note: this assumes that EnvRawParameters will only have flat configuration of either # primitive or sequential type if hasattr(parameter_obj, "string_delimiter"): if not isinstance(self._raw_value, str): raise TypeError("Value is not a string.") string_delimiter = getattr(parameter_obj, "string_delimiter") # TODO: add stripping of !important, !top, and !bottom return tuple( EnvRawParameter(EnvRawParameter.source, self.key, v) for v in (vv.strip() for vv in self._raw_value.split(string_delimiter)) if v ) else: return self.__important_split_value[0].strip() def keyflag(self): return ParameterFlag.final if len(self.__important_split_value) >= 2 else None def valueflags(self, parameter_obj): if hasattr(parameter_obj, "string_delimiter"): string_delimiter = getattr(parameter_obj, "string_delimiter") # TODO: add stripping of !important, !top, and !bottom return tuple("" for _ in self._raw_value.split(string_delimiter)) else: return self.__important_split_value[0].strip() @property def __important_split_value(self): return self._raw_value.split("!important") @classmethod def make_raw_parameters(cls, appname): keystart = f"{appname.upper()}_" raw_env = { k.replace(keystart, "", 1).lower(): v for k, v in environ.items() if k.startswith(keystart) } return super().make_raw_parameters(EnvRawParameter.source, raw_env)
EnvRawParameter
python
ray-project__ray
python/ray/tune/execution/placement_groups.py
{ "start": 256, "end": 4176 }
class ____(ResourceRequest): """Wrapper class that creates placement groups for trials. This function should be used to define resource requests for Ray Tune trials. It holds the parameters to create :ref:`placement groups <ray-placement-group-doc-ref>`. At a minimum, this will hold at least one bundle specifying the resource requirements for each trial: .. code-block:: python from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {"CPU": 1, "GPU": 0.5, "custom_resource": 2} ]) ) ) tuner.fit() If the trial itself schedules further remote workers, the resource requirements should be specified in additional bundles. You can also pass the placement strategy for these bundles, e.g. to enforce co-located placement: .. code-block:: python from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {"CPU": 1, "GPU": 0.5, "custom_resource": 2}, {"CPU": 2}, {"CPU": 2}, ], strategy="PACK") ) ) tuner.fit() The example above will reserve 1 CPU, 0.5 GPUs and 2 custom_resources for the trainable itself, and reserve another 2 bundles of 2 CPUs each. The trial will only start when all these resources are available. This could be used e.g. if you had one learner running in the main trainable that schedules two remote workers that need access to 2 CPUs each. If the trainable itself doesn't require resources. You can specify it as: .. code-block:: python from ray import tune tuner = tune.Tuner( tune.with_resources( train, resources=tune.PlacementGroupFactory([ {}, {"CPU": 2}, {"CPU": 2}, ], strategy="PACK") ) ) tuner.fit() Args: bundles: A list of bundles which represent the resources requirements. strategy: The strategy to create the placement group. - "PACK": Packs Bundles into as few nodes as possible. - "SPREAD": Places Bundles across distinct nodes as even as possible. - "STRICT_PACK": Packs Bundles into one node. The group is not allowed to span multiple nodes. - "STRICT_SPREAD": Packs Bundles across distinct nodes. *args: Passed to the call of ``placement_group()`` **kwargs: Passed to the call of ``placement_group()`` """ def __call__(self, *args, **kwargs): warnings.warn( "Calling PlacementGroupFactory objects is deprecated. Use " "`to_placement_group()` instead.", DeprecationWarning, ) kwargs.update(self._bound.kwargs) # Call with bounded *args and **kwargs return placement_group(*self._bound.args, **kwargs) @DeveloperAPI def resource_dict_to_pg_factory(spec: Optional[Dict[str, float]] = None): """Translates resource dict into PlacementGroupFactory.""" spec = spec or {"cpu": 1} spec = spec.copy() cpus = spec.pop("cpu", spec.pop("CPU", 0.0)) gpus = spec.pop("gpu", spec.pop("GPU", 0.0)) memory = spec.pop("memory", 0.0) # If there is a custom_resources key, use as base for bundle bundle = dict(spec.pop("custom_resources", {})) # Otherwise, consider all other keys as custom resources if not bundle: bundle = spec bundle.update( { "CPU": cpus, "GPU": gpus, "memory": memory, } ) return PlacementGroupFactory([bundle])
PlacementGroupFactory
python
huggingface__transformers
tests/models/colqwen2/test_modeling_colqwen2.py
{ "start": 1469, "end": 7255 }
class ____: def __init__( self, parent, ignore_index=-100, pad_token_id=2, projector_hidden_act="gelu", seq_length=11, vision_feature_select_strategy="default", vision_feature_layer=-1, projection_dim=32, is_training=False, use_cache=False, vlm_config={ "_name_or_path": "Qwen/Qwen2-VL-2B-Instruct", "bos_token_id": 0, "eos_token_id": 1, "vision_start_token_id": 3, "image_token_id": 4, "video_token_id": 5, "hidden_size": 64, "intermediate_size": 2, "max_window_layers": 2, "model_type": "qwen2_vl", "num_attention_heads": 2, "num_hidden_layers": 2, "num_key_value_heads": 2, "rms_norm_eps": 1e-06, "rope_parameters": {"mrope_section": [4, 6, 6], "rope_type": "default", "type": "default"}, "sliding_window": 32768, "tie_word_embeddings": True, "vision_config": { "depth": 2, "embed_dim": 32, "hidden_act": "quick_gelu", "hidden_size": 64, "mlp_ratio": 4, "num_heads": 4, "patch_size": 14, "in_chans": 3, "spatial_merge_size": 1, "temporal_patch_size": 2, }, "vision_end_token_id": 151653, "vision_token_id": 151654, "vocab_size": 99, }, embedding_dim=32, initializer_range=0.02, ): self.parent = parent self.ignore_index = ignore_index self.pad_token_id = pad_token_id # `image_token_index` is set to 0 to pass "resize_embeddings" test, do not modify self.image_token_index = 0 self.image_token_id = vlm_config["image_token_id"] self.video_token_id = vlm_config["video_token_id"] self.pad_token_id = vlm_config["eos_token_id"] self.vision_start_token_id = vlm_config["vision_start_token_id"] self.projector_hidden_act = projector_hidden_act self.vision_feature_select_strategy = vision_feature_select_strategy self.vision_feature_layer = vision_feature_layer self.image_size = 56 self.num_image_tokens = 4 self.seq_length = seq_length + self.num_image_tokens self.projection_dim = projection_dim self.num_hidden_layers = vlm_config["num_hidden_layers"] self.vocab_size = vlm_config["vocab_size"] self.hidden_size = vlm_config["hidden_size"] self.num_attention_heads = vlm_config["num_attention_heads"] self.is_training = is_training self.batch_size = 3 self.num_channels = vlm_config["vision_config"]["in_chans"] self.encoder_seq_length = self.seq_length self.use_cache = use_cache self.vlm_config = vlm_config self.embedding_dim = embedding_dim self.initializer_range = initializer_range def get_config(self): return ColQwen2Config( vlm_config=self.vlm_config, embedding_dim=self.embedding_dim, initializer_range=self.initializer_range, ) def prepare_config_and_inputs(self): config = self.get_config() patch_size = config.vlm_config.vision_config.patch_size temporal_patch_size = config.vlm_config.vision_config.temporal_patch_size # NOTE: Assume all inputs are square images of the same size. num_patches = (self.image_size // patch_size) ** 2 pixel_values = floats_tensor( [ self.batch_size * num_patches, self.num_channels * (patch_size**2) * temporal_patch_size, ] ) # Hardcoded image grid size: do not change unless you modified image size or patch size! image_grid_thw = torch.tensor([1, 4, 4]).repeat(self.batch_size, 1) # NOTE: The following adjustment ensures correct behavior with DDP on multiple GPUs. # Line is copied from `src/transformers/models/colqwen2/processing_colqwen2.py` offsets = image_grid_thw[:, 1] * image_grid_thw[:, 2] # (batch_size,) pixel_values = list( torch.split(pixel_values, offsets.tolist()) ) # [(num_patches_image_0, pixel_values), ..., (num_patches_image_n, pixel_values)] pixel_values = torch.nn.utils.rnn.pad_sequence( pixel_values, batch_first=True ) # (batch_size, max_num_patches, pixel_values) return config, pixel_values, image_grid_thw def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, image_grid_thw = config_and_inputs input_ids = ( ids_tensor( shape=[self.batch_size, self.seq_length], vocab_size=config.vlm_config.vocab_size - 1, ) + 1 ) attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) input_ids[:, -1] = self.pad_token_id input_ids[:, : self.num_image_tokens] = self.image_token_id input_ids[input_ids == self.video_token_id] = self.pad_token_id input_ids[input_ids == self.image_token_id] = self.pad_token_id input_ids[input_ids == self.vision_start_token_id] = self.pad_token_id inputs_dict = { "input_ids": input_ids, "pixel_values": pixel_values, "image_grid_thw": image_grid_thw, "attention_mask": attention_mask, "labels": input_ids, } return config, inputs_dict @require_torch
ColQwen2ForRetrievalModelTester
python
django__django
tests/admin_inlines/models.py
{ "start": 9110, "end": 9204 }
class ____(models.Model): show_inlines = models.BooleanField(default=False)
ShowInlineParent
python
streamlit__streamlit
lib/streamlit/components/v2/presentation.py
{ "start": 1073, "end": 8183 }
class ____(TypedDict, total=False): event: str value: object def make_bidi_component_presenter( aggregator_id: str, component_id: str | None = None, allowed_state_keys: set[str] | None = None, ) -> WidgetValuePresenter: """Return a presenter that merges trigger events into CCv2 state. This function returns a callable that takes a component's persistent state value and the current `SessionState` instance, and returns the user-visible value that should appear in `st.session_state`. The presenter is side-effect-free and does not mutate stored state or callback behavior. It is intended to be attached to the persistent state widget via the generic `presenter` hook. Parameters ---------- aggregator_id The ID of the trigger aggregator widget that holds the event payloads. Returns ------- WidgetValuePresenter A callable that merges the trigger event values into the component's base state for presentation in `st.session_state`. """ def _present(base_value: object, session_state: SessionState) -> object: def _check_modification(k: str) -> None: ctx = get_script_run_ctx() if ctx is not None and component_id is not None: user_key = session_state._key_id_mapper.get_key_from_id(component_id) if ( component_id in ctx.widget_ids_this_run or user_key in ctx.form_ids_this_run ): raise StreamlitAPIException( f"`st.session_state.{user_key}.{k}` cannot be modified after the component" f" with key `{user_key}` is instantiated." ) # Base state must be a flat mapping; otherwise, present as-is. base_map: dict[str, object] | None = None if isinstance(base_value, dict): base_map = cast("dict[str, object]", base_value) if base_map is not None: # Read the trigger aggregator payloads if present try: agg_meta = session_state._new_widget_state.widget_metadata.get( aggregator_id ) if agg_meta is None or agg_meta.value_type != "json_trigger_value": return base_value try: agg_payloads_obj = session_state._new_widget_state[aggregator_id] except KeyError: agg_payloads_obj = None payloads_list: list[_TriggerPayload] | None if agg_payloads_obj is None: payloads_list = None elif isinstance(agg_payloads_obj, list): # Filter and cast to the expected payload type shape payloads_list = [ cast("_TriggerPayload", p) for p in agg_payloads_obj if isinstance(p, dict) ] elif isinstance(agg_payloads_obj, dict): payloads_list = [cast("_TriggerPayload", agg_payloads_obj)] else: payloads_list = None event_to_val: dict[str, object] = {} if payloads_list is not None: for payload in payloads_list: ev = payload.get("event") if isinstance(ev, str): event_to_val[ev] = payload.get("value") # Merge triggers into a flat view: triggers first, then base flat: dict[str, object] = dict(event_to_val) flat.update(base_map) # Return a write-through dict that updates the underlying # component state when users assign nested keys via # st.session_state[component_user_key][name] = value. Using a # dict subclass ensures pretty-printing and JSON serialization # behave as expected for st.write and logs. class _WriteThrough(dict[str, object]): def __init__(self, data: dict[str, object]) -> None: super().__init__(data) def __getattr__(self, name: str) -> object: return self.get(name) def __setattr__(self, name: str, value: object) -> None: if name.startswith(("__", "_")): return super().__setattr__(name, value) self[name] = value return None def __deepcopy__(self, memo: dict[int, Any]) -> Self: # This object is a proxy to the real state. Don't copy it. memo[id(self)] = self return self def __setitem__(self, k: str, v: object) -> None: _check_modification(k) if ( allowed_state_keys is not None and k not in allowed_state_keys ): # Silently ignore invalid keys to match permissive session_state semantics return # Update the underlying stored base state and this dict super().__setitem__(k, v) try: # Store back to session state's widget store as a flat mapping ss = session_state # Directly set the value in the new widget state store if component_id is not None: ss._new_widget_state.set_from_value( component_id, dict(self) ) except Exception as e: _LOGGER.debug("Failed to persist CCv2 state update: %s", e) def __delitem__(self, k: str) -> None: _check_modification(k) super().__delitem__(k) try: ss = session_state if component_id is not None: ss._new_widget_state.set_from_value( component_id, dict(self) ) except Exception as e: _LOGGER.debug( "Failed to persist CCv2 state deletion: %s", e ) return _WriteThrough(flat) except Exception as e: # On any error, fall back to the base value _LOGGER.debug( "Failed to merge trigger events into component state: %s", e, exc_info=e, ) return base_value return base_value return _present
_TriggerPayload
python
catalyst-team__catalyst
catalyst/callbacks/metrics/cmc_score.py
{ "start": 280, "end": 6206 }
class ____(LoaderMetricCallback): """ Cumulative Matching Characteristics callback. This callback was designed to count cumulative matching characteristics. If current object is from query your dataset should output `True` in `is_query_key` and false if current object is from gallery. You can see `QueryGalleryDataset` in `catalyst.contrib.datasets.metric_learning` for more information. On batch end callback accumulate all embeddings Args: embeddings_key: embeddings key in output dict labels_key: labels key in output dict is_query_key: bool key True if current object is from query topk: specifies which cmc@K to log prefix: metric prefix suffix: metric suffix .. note:: You should use it with `ControlFlowCallback` and add all query/gallery sets to loaders. Loaders should contain "is_query" and "label" key. Examples: .. code-block:: python import os from torch.optim import Adam from torch.utils.data import DataLoader from catalyst import data, dl from catalyst.contrib import data, datasets, models, nn # 1. train and valid loaders transforms = data.Compose([ data.ImageToTensor(), data.NormalizeImage((0.1307,), (0.3081,)) ]) train_dataset = datasets.MnistMLDataset( root=os.getcwd(), download=True, transform=transforms ) sampler = data.BatchBalanceClassSampler( labels=train_dataset.get_labels(), num_classes=5, num_samples=10 ) train_loader = DataLoader(dataset=train_dataset, batch_sampler=sampler) valid_dataset = datasets.MnistQGDataset( root=os.getcwd(), transform=transforms, gallery_fraq=0.2 ) valid_loader = DataLoader(dataset=valid_dataset, batch_size=1024) # 2. model and optimizer model = models.MnistSimpleNet(out_features=16) optimizer = Adam(model.parameters(), lr=0.001) # 3. criterion with triplets sampling sampler_inbatch = data.HardTripletsSampler(norm_required=False) criterion = nn.TripletMarginLossWithSampler( margin=0.5, sampler_inbatch=sampler_inbatch ) # 4. training with catalyst Runner class CustomRunner(dl.SupervisedRunner): def handle_batch(self, batch) -> None: if self.is_train_loader: images, targets = batch["features"].float(), batch["targets"].long() features = self.model(images) self.batch = {"embeddings": features, "targets": targets} else: images, targets, is_query = ( batch["features"].float(), batch["targets"].long(), batch["is_query"].bool() ) features = self.model(images) self.batch = { "embeddings": features, "targets": targets, "is_query": is_query } callbacks = [ dl.ControlFlowCallback( dl.CriterionCallback( input_key="embeddings", target_key="targets", metric_key="loss" ), loaders="train", ), dl.ControlFlowCallback( dl.CMCScoreCallback( embeddings_key="embeddings", labels_key="targets", is_query_key="is_query", topk=[1], ), loaders="valid", ), dl.PeriodicLoaderCallback( valid_loader_key="valid", valid_metric_key="cmc01", minimize=False, valid=2 ), ] runner = CustomRunner(input_key="features", output_key="embeddings") runner.train( model=model, criterion=criterion, optimizer=optimizer, callbacks=callbacks, loaders={"train": train_loader, "valid": valid_loader}, verbose=False, logdir="./logs", valid_loader="valid", valid_metric="cmc01", minimize_valid_metric=False, num_epochs=10, ) .. note:: Metric names depending on input parameters: - ``topk = (1,) or None`` ---> ``"cmc01"`` - ``topk = (1, 3)`` ---> ``"cmc01"``, ``"cmc03"`` - ``topk = (1, 3, 5)`` ---> ``"cmc01"``, ``"cmc03"``, ``"cmc05"`` You can find them in ``runner.batch_metrics``, ``runner.loader_metrics`` or ``runner.epoch_metrics``. .. note:: Please follow the `minimal examples`_ sections for more use cases. .. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505 """ def __init__( self, embeddings_key: str, labels_key: str, is_query_key: str, topk: Iterable[int] = None, prefix: str = None, suffix: str = None, ): """Init.""" super().__init__( metric=CMCMetric( embeddings_key=embeddings_key, labels_key=labels_key, is_query_key=is_query_key, topk=topk, prefix=prefix, suffix=suffix, ), input_key=[embeddings_key, is_query_key], target_key=[labels_key], ) def on_experiment_start(self, runner: "IRunner") -> None: """Event handler.""" assert runner.engine.distributed_type not in ( DistributedType.MULTI_GPU, DistributedType.TPU, ), "CMCScoreCallback could not work within ddp training" return super().on_experiment_start(runner)
CMCScoreCallback
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_condition_evaluations.py
{ "start": 8529, "end": 9304 }
class ____(graphene.ObjectType): triggerEvaluationId = graphene.Field(graphene.Int) triggerTimestamp = graphene.Field(graphene.Float) resetEvaluationId = graphene.Field(graphene.Int) resetTimestamp = graphene.Field(graphene.Float) class Meta: name = "SinceConditionMetadata" def __init__(self, since_condition_data: SinceConditionData): self._since_condition_data = since_condition_data super().__init__( triggerEvaluationId=since_condition_data.trigger_evaluation_id, triggerTimestamp=since_condition_data.trigger_timestamp, resetEvaluationId=since_condition_data.reset_evaluation_id, resetTimestamp=since_condition_data.reset_timestamp, )
GrapheneSinceConditionMetadata
python
apache__airflow
providers/facebook/src/airflow/providers/facebook/ads/hooks/ads.py
{ "start": 1588, "end": 7846 }
class ____(BaseHook): """ Facebook Ads API. .. seealso:: For more information on the Facebook Ads API, take a look at the API docs: https://developers.facebook.com/docs/marketing-apis/ :param facebook_conn_id: Airflow Facebook Ads connection ID :param api_version: The version of Facebook API. Default to None. If it is None, it will use the Facebook business SDK default version. """ conn_name_attr = "facebook_conn_id" default_conn_name = "facebook_default" conn_type = "facebook_social" hook_name = "Facebook Ads" def __init__( self, facebook_conn_id: str = default_conn_name, api_version: str | None = None, ) -> None: super().__init__() self.facebook_conn_id = facebook_conn_id self.api_version = api_version self.client_required_fields = ["app_id", "app_secret", "access_token", "account_id"] def _get_service(self) -> FacebookAdsApi: """Return Facebook Ads Client using a service account.""" config = self.facebook_ads_config return FacebookAdsApi.init( app_id=config["app_id"], app_secret=config["app_secret"], access_token=config["access_token"], api_version=self.api_version, ) @cached_property def multiple_accounts(self) -> bool: """Check whether provided account_id in the Facebook Ads Connection is provided as a list.""" return isinstance(self.facebook_ads_config["account_id"], list) @cached_property def facebook_ads_config(self) -> dict: """ Get the ``facebook_ads_config`` attribute. This fetches Facebook Ads connection from meta database, and sets the ``facebook_ads_config`` attribute with returned config file. """ self.log.info("Fetching fb connection: %s", self.facebook_conn_id) conn = self.get_connection(self.facebook_conn_id) config = conn.extra_dejson missing_keys = self.client_required_fields - config.keys() if missing_keys: message = f"{missing_keys} fields are missing" raise AirflowException(message) return config def bulk_facebook_report( self, params: dict[str, Any] | None, fields: list[str], sleep_time: int = 5, ) -> list[AdsInsights] | dict[str, list[AdsInsights]]: """ Pull data from Facebook Ads API regarding Account ID with matching return type. The return type and value depends on the ``account_id`` configuration. If the configuration is a str representing a single Account ID, the return value is the list of reports for that ID. If the configuration is a list of str representing multiple Account IDs, the return value is a dict of Account IDs and their respective list of reports. :param fields: List of fields that is obtained from Facebook. Found in AdsInsights.Field class. https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 :param params: Parameters that determine the query for Facebook https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 :param sleep_time: Time to sleep when async call is happening :return: Facebook Ads API response, converted to Facebook Ads Row objects regarding given Account ID type """ api = self._get_service() if self.multiple_accounts: all_insights = {} for account_id in self.facebook_ads_config["account_id"]: all_insights[account_id] = self._facebook_report( account_id=account_id, api=api, params=params, fields=fields, sleep_time=sleep_time ) self.log.info( "%s Account Id used to extract data from Facebook Ads Iterators successfully", account_id ) return all_insights return self._facebook_report( account_id=self.facebook_ads_config["account_id"], api=api, params=params, fields=fields, sleep_time=sleep_time, ) def _facebook_report( self, account_id: str, api: FacebookAdsApi, params: dict[str, Any] | None, fields: list[str], sleep_time: int = 5, ) -> list[AdsInsights]: """ Pull data from the Facebook Ads API with given ``account_id``. :param account_id: Facebook Account ID that holds ads information https://developers.facebook.com/docs/marketing-api/reference/ads-insights/ :param api: FacebookAdsApi created in the hook :param fields: List of fields that is obtained from Facebook. Found in AdsInsights.Field class. https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 :param params: Parameters that determine the query for Facebook https://developers.facebook.com/docs/marketing-api/insights/parameters/v6.0 :param sleep_time: Time to sleep when async call is happening """ ad_account = AdAccount(account_id, api=api) _async = ad_account.get_insights(params=params, fields=fields, is_async=True) while True: request = _async.api_get() async_status = request[AdReportRun.Field.async_status] percent = request[AdReportRun.Field.async_percent_completion] self.log.info("%s %s completed, async_status: %s", percent, "%", async_status) if async_status == JobStatus.COMPLETED.value: self.log.info("Job run completed") break if async_status in [JobStatus.SKIPPED.value, JobStatus.FAILED.value]: message = f"{async_status}. Please retry." raise AirflowException(message) time.sleep(sleep_time) report_run_id = _async.api_get()["report_run_id"] report_object = AdReportRun(report_run_id, api=api) self.log.info("Extracting data from returned Facebook Ads Iterators") insights = report_object.get_insights() return list(insights)
FacebookAdsReportingHook
python
facelessuser__pymdown-extensions
pymdownx/b64.py
{ "start": 3458, "end": 3753 }
class ____(Postprocessor): """Post processor for B64.""" def run(self, text): """Find and replace paths with base64 encoded file.""" basepath = self.config['base_path'] text = RE_TAG_HTML.sub(lambda m: repl(m, basepath), text) return text
B64Postprocessor
python
ray-project__ray
python/ray/tests/test_failure_3.py
{ "start": 13810, "end": 16040 }
class ____: def create_leaked_child_process(self, num_to_leak): print("creating leaked process", os.getpid()) pids = [] for index in range(num_to_leak): pid = create_child_proc("actor", index) pids.append(pid) return pids @ray.remote def leaker_task(index): print("Creating leaked process", os.getpid()) return create_child_proc("task", index) num_to_leak_per_type = 10 print('starting actors') actor = LeakerActor.remote() actor_leaked_pids = ray.get(actor.create_leaked_child_process.remote( num_to_leak=num_to_leak_per_type, )) task_leaked_pids = ray.get([ leaker_task.remote(index) for index in range(num_to_leak_per_type) ]) leaked_pids = actor_leaked_pids + task_leaked_pids final_file = "{output_file_path}" tmp_file = final_file + ".tmp" with open(tmp_file, "w") as f: json.dump(leaked_pids, f) shutil.move(tmp_file, final_file) while True: print(os.getpid()) time.sleep(1) """ print("Running string as driver") driver_proc = run_string_as_driver_nonblocking(driver_script) # Wait for the json file containing the child PIDS # to be present. print("Waiting for child pids json") wait_for_condition( condition_predictor=lambda: Path(output_file_path).exists(), timeout=30, ) # Load the PIDs of the child processes. with open(output_file_path, "r") as f: pids = json.load(f) # Validate all children of the worker processes are in a sleeping state. processes = [psutil.Process(pid) for pid in pids] assert all([proc.status() == psutil.STATUS_SLEEPING for proc in processes]) # Obtain psutil handle for raylet process raylet_proc = [p for p in psutil.process_iter() if p.name() == "raylet"] assert len(raylet_proc) == 1 raylet_proc = raylet_proc[0] # Kill the raylet process and reap the zombie raylet_proc.kill() raylet_proc.wait() print("Waiting for child procs to die") wait_for_condition( condition_predictor=lambda: all([not proc.is_running() for proc in processes]), timeout=30, ) driver_proc.kill() if __name__ == "__main__": sys.exit(pytest.main(["-sv", __file__]))
LeakerActor
python
getsentry__sentry
tests/sentry/analytics/test_base.py
{ "start": 216, "end": 513 }
class ____(Analytics): def __init__(self): self.events = [] self.event_envelopes = [] super().__init__() def record_event_envelope(self, envelope: EventEnvelope): self.event_envelopes.append(envelope) self.events.append(envelope.event)
DummyAnalytics
python
doocs__leetcode
solution/0600-0699/0693.Binary Number with Alternating Bits/Solution.py
{ "start": 0, "end": 248 }
class ____: def hasAlternatingBits(self, n: int) -> bool: prev = -1 while n: curr = n & 1 if prev == curr: return False prev = curr n >>= 1 return True
Solution
python
falconry__falcon
falcon/errors.py
{ "start": 79748, "end": 82464 }
class ____(HTTPError): """505 HTTP Version Not Supported. The 505 (HTTP Version Not Supported) status code indicates that the server does not support, or refuses to support, the major version of HTTP that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client (as described in RFC 7230, Section 2.6), other than with this error message. The server SHOULD generate a representation for the 505 response that describes why that version is not supported and what other protocols are supported by that server. (See also: RFC 7231, Section 6.6.6) All the arguments are defined as keyword-only. Keyword Args: title (str): Error title (default '503 Service Unavailable'). description (str): Human-friendly description of the error, along with a helpful suggestion or two. headers (dict or list): A ``dict`` of header names and values to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and *value* must be of type ``str`` or ``StringType``, and only character values 0x00 through 0xFF may be used on platforms that use wide characters. Note: The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client Note: Falcon can process a list of ``tuple`` slightly faster than a ``dict``. href (str): A URL someone can visit to find out more information (default ``None``). Unicode characters are percent-encoded. href_text (str): If href is given, use this as the friendly title/description for the link (default 'API documentation for this error'). code (int): An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default ``None``). """ def __init__( self, *, title: str | None = None, description: str | None = None, headers: HeaderArg | None = None, **kwargs: HTTPErrorKeywordArguments, ): super().__init__( status.HTTP_505, title=title, description=description, headers=headers, **kwargs, # type: ignore[arg-type] )
HTTPVersionNotSupported
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1018945, "end": 1019237 }
class ____(sgqlc.types.Type, Node, GitObject): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("entries",) entries = sgqlc.types.Field( sgqlc.types.list_of(sgqlc.types.non_null(TreeEntry)), graphql_name="entries" )
Tree
python
lazyprogrammer__machine_learning_examples
supervised_class/nb.py
{ "start": 584, "end": 2064 }
class ____(object): def fit(self, X, Y, smoothing=1e-2): self.gaussians = dict() self.priors = dict() labels = set(Y) for c in labels: current_x = X[Y == c] self.gaussians[c] = { 'mean': current_x.mean(axis=0), 'var': current_x.var(axis=0) + smoothing, } self.priors[c] = float(len(Y[Y == c])) / len(Y) def score(self, X, Y): P = self.predict(X) return np.mean(P == Y) def predict(self, X): N, D = X.shape K = len(self.gaussians) P = np.zeros((N, K)) for c, g in iteritems(self.gaussians): mean, var = g['mean'], g['var'] P[:,c] = mvn.logpdf(X, mean=mean, cov=var) + np.log(self.priors[c]) return np.argmax(P, axis=1) if __name__ == '__main__': X, Y = get_data(10000) Ntrain = len(Y) // 2 Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain] Xtest, Ytest = X[Ntrain:], Y[Ntrain:] model = NaiveBayes() t0 = datetime.now() model.fit(Xtrain, Ytrain) print("Training time:", (datetime.now() - t0)) t0 = datetime.now() print("Train accuracy:", model.score(Xtrain, Ytrain)) print("Time to compute train accuracy:", (datetime.now() - t0), "Train size:", len(Ytrain)) t0 = datetime.now() print("Test accuracy:", model.score(Xtest, Ytest)) print("Time to compute test accuracy:", (datetime.now() - t0), "Test size:", len(Ytest))
NaiveBayes
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py
{ "start": 1253, "end": 18575 }
class ____: """An interface to see if request should cached or not.""" def __init__( self, cache: BaseCache | None = None, cache_etags: bool = True, serializer: Serializer | None = None, status_codes: Collection[int] | None = None, ): self.cache = DictCache() if cache is None else cache self.cache_etags = cache_etags self.serializer = serializer or Serializer() self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308) @classmethod def _urlnorm(cls, uri: str) -> str: """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = %s" % uri) scheme = scheme.lower() authority = authority.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path defrag_uri = scheme + "://" + authority + request_uri return defrag_uri @classmethod def cache_url(cls, uri: str) -> str: return cls._urlnorm(uri) def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]: known_directives = { # https://tools.ietf.org/html/rfc7234#section-5.2 "max-age": (int, True), "max-stale": (int, False), "min-fresh": (int, True), "no-cache": (None, False), "no-store": (None, False), "no-transform": (None, False), "only-if-cached": (None, False), "must-revalidate": (None, False), "public": (None, False), "private": (None, False), "proxy-revalidate": (None, False), "s-maxage": (int, True), } cc_headers = headers.get("cache-control", headers.get("Cache-Control", "")) retval: dict[str, int | None] = {} for cc_directive in cc_headers.split(","): if not cc_directive.strip(): continue parts = cc_directive.split("=", 1) directive = parts[0].strip() try: typ, required = known_directives[directive] except KeyError: logger.debug("Ignoring unknown cache-control directive: %s", directive) continue if not typ or not required: retval[directive] = None if typ: try: retval[directive] = typ(parts[1].strip()) except IndexError: if required: logger.debug( "Missing value for cache-control " "directive: %s", directive, ) except ValueError: logger.debug( "Invalid value for cache-control directive " "%s, must be %s", directive, typ.__name__, ) return retval def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None: """ Load a cached response, or return None if it's not available. """ # We do not support caching of partial content: so if the request contains a # Range header then we don't want to load anything from the cache. if "Range" in request.headers: return None cache_url = request.url assert cache_url is not None cache_data = self.cache.get(cache_url) if cache_data is None: logger.debug("No cache entry available") return None if isinstance(self.cache, SeparateBodyBaseCache): body_file = self.cache.get_body(cache_url) else: body_file = None result = self.serializer.loads(request, cache_data, body_file) if result is None: logger.warning("Cache entry deserialization failed, entry ignored") return result def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]: """ Return a cached response if it exists in the cache, otherwise return False. """ assert request.url is not None cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) # Bail out if the request insists on fresh data if "no-cache" in cc: logger.debug('Request header has "no-cache", cache bypassed') return False if "max-age" in cc and cc["max-age"] == 0: logger.debug('Request header has "max_age" as 0, cache bypassed') return False # Check whether we can load the response from the cache: resp = self._load_from_cache(request) if not resp: return False # If we have a cached permanent redirect, return it immediately. We # don't need to test our response for other headers b/c it is # intrinsically "cacheable" as it is Permanent. # # See: # https://tools.ietf.org/html/rfc7231#section-6.4.2 # # Client can try to refresh the value by repeating the request # with cache busting headers as usual (ie no-cache). if int(resp.status) in PERMANENT_REDIRECT_STATUSES: msg = ( "Returning cached permanent redirect response " "(ignoring date and etag information)" ) logger.debug(msg) return resp headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers) if not headers or "date" not in headers: if "etag" not in headers: # Without date or etag, the cached response can never be used # and should be deleted. logger.debug("Purging cached response: no date or etag") self.cache.delete(cache_url) logger.debug("Ignoring cached response: no date") return False now = time.time() time_tuple = parsedate_tz(headers["date"]) assert time_tuple is not None date = calendar.timegm(time_tuple[:6]) current_age = max(0, now - date) logger.debug("Current age based on date: %i", current_age) # TODO: There is an assumption that the result will be a # urllib3 response object. This may not be best since we # could probably avoid instantiating or constructing the # response until we know we need it. resp_cc = self.parse_cache_control(headers) # determine freshness freshness_lifetime = 0 # Check the max-age pragma in the cache control header max_age = resp_cc.get("max-age") if max_age is not None: freshness_lifetime = max_age logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime) # If there isn't a max-age, check for an expires header elif "expires" in headers: expires = parsedate_tz(headers["expires"]) if expires is not None: expire_time = calendar.timegm(expires[:6]) - date freshness_lifetime = max(0, expire_time) logger.debug("Freshness lifetime from expires: %i", freshness_lifetime) # Determine if we are setting freshness limit in the # request. Note, this overrides what was in the response. max_age = cc.get("max-age") if max_age is not None: freshness_lifetime = max_age logger.debug( "Freshness lifetime from request max-age: %i", freshness_lifetime ) min_fresh = cc.get("min-fresh") if min_fresh is not None: # adjust our current age by our min fresh current_age += min_fresh logger.debug("Adjusted current age from min-fresh: %i", current_age) # Return entry if it is fresh enough if freshness_lifetime > current_age: logger.debug('The response is "fresh", returning cached response') logger.debug("%i > %i", freshness_lifetime, current_age) return resp # we're not fresh. If we don't have an Etag, clear it out if "etag" not in headers: logger.debug('The cached response is "stale" with no etag, purging') self.cache.delete(cache_url) # return the original handler return False def conditional_headers(self, request: PreparedRequest) -> dict[str, str]: resp = self._load_from_cache(request) new_headers = {} if resp: headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers) if "etag" in headers: new_headers["If-None-Match"] = headers["ETag"] if "last-modified" in headers: new_headers["If-Modified-Since"] = headers["Last-Modified"] return new_headers def _cache_set( self, cache_url: str, request: PreparedRequest, response: HTTPResponse, body: bytes | None = None, expires_time: int | None = None, ) -> None: """ Store the data in the cache. """ if isinstance(self.cache, SeparateBodyBaseCache): # We pass in the body separately; just put a placeholder empty # string in the metadata. self.cache.set( cache_url, self.serializer.dumps(request, response, b""), expires=expires_time, ) # body is None can happen when, for example, we're only updating # headers, as is the case in update_cached_response(). if body is not None: self.cache.set_body(cache_url, body) else: self.cache.set( cache_url, self.serializer.dumps(request, response, body), expires=expires_time, ) def cache_response( self, request: PreparedRequest, response: HTTPResponse, body: bytes | None = None, status_codes: Collection[int] | None = None, ) -> None: """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests cacheable_status_codes = status_codes or self.cacheable_status_codes if response.status not in cacheable_status_codes: logger.debug( "Status code %s not in %s", response.status, cacheable_status_codes ) return response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( response.headers ) if "date" in response_headers: time_tuple = parsedate_tz(response_headers["date"]) assert time_tuple is not None date = calendar.timegm(time_tuple[:6]) else: date = 0 # If we've been given a body, our response has a Content-Length, that # Content-Length is valid then we can check to see if the body we've # been given matches the expected size, and if it doesn't we'll just # skip trying to cache it. if ( body is not None and "content-length" in response_headers and response_headers["content-length"].isdigit() and int(response_headers["content-length"]) != len(body) ): return cc_req = self.parse_cache_control(request.headers) cc = self.parse_cache_control(response_headers) assert request.url is not None cache_url = self.cache_url(request.url) logger.debug('Updating cache with response from "%s"', cache_url) # Delete it from the cache if we happen to have it stored there no_store = False if "no-store" in cc: no_store = True logger.debug('Response header has "no-store"') if "no-store" in cc_req: no_store = True logger.debug('Request header has "no-store"') if no_store and self.cache.get(cache_url): logger.debug('Purging existing cache entry to honor "no-store"') self.cache.delete(cache_url) if no_store: return # https://tools.ietf.org/html/rfc7234#section-4.1: # A Vary header field-value of "*" always fails to match. # Storing such a response leads to a deserialization warning # during cache lookup and is not allowed to ever be served, # so storing it can be avoided. if "*" in response_headers.get("vary", ""): logger.debug('Response header has "Vary: *"') return # If we've been given an etag, then keep the response if self.cache_etags and "etag" in response_headers: expires_time = 0 if response_headers.get("expires"): expires = parsedate_tz(response_headers["expires"]) if expires is not None: expires_time = calendar.timegm(expires[:6]) - date expires_time = max(expires_time, 14 * 86400) logger.debug(f"etag object cached for {expires_time} seconds") logger.debug("Caching due to etag") self._cache_set(cache_url, request, response, body, expires_time) # Add to the cache any permanent redirects. We do this before looking # that the Date headers. elif int(response.status) in PERMANENT_REDIRECT_STATUSES: logger.debug("Caching permanent redirect") self._cache_set(cache_url, request, response, b"") # Add to the cache if the response headers demand it. If there # is no date header then we can't do anything about expiring # the cache. elif "date" in response_headers: time_tuple = parsedate_tz(response_headers["date"]) assert time_tuple is not None date = calendar.timegm(time_tuple[:6]) # cache when there is a max-age > 0 max_age = cc.get("max-age") if max_age is not None and max_age > 0: logger.debug("Caching b/c date exists and max-age > 0") expires_time = max_age self._cache_set( cache_url, request, response, body, expires_time, ) # If the request can expire, it means we should cache it # in the meantime. elif "expires" in response_headers: if response_headers["expires"]: expires = parsedate_tz(response_headers["expires"]) if expires is not None: expires_time = calendar.timegm(expires[:6]) - date else: expires_time = None logger.debug( "Caching b/c of expires header. expires in {} seconds".format( expires_time ) ) self._cache_set( cache_url, request, response, body, expires_time, ) def update_cached_response( self, request: PreparedRequest, response: HTTPResponse ) -> HTTPResponse: """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ assert request.url is not None cache_url = self.cache_url(request.url) cached_response = self._load_from_cache(request) if not cached_response: # we didn't have a cached response return response # Lets update our headers with the headers from the new request: # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1 # # The server isn't supposed to send headers that would make # the cached body invalid. But... just in case, we'll be sure # to strip out ones we know that might be problmatic due to # typical assumptions. excluded_headers = ["content-length"] cached_response.headers.update( { k: v for k, v in response.headers.items() if k.lower() not in excluded_headers } ) # we want a 200 b/c we have content via the cache cached_response.status = 200 # update our cache self._cache_set(cache_url, request, cached_response) return cached_response
CacheController
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ROI.py
{ "start": 58617, "end": 66538 }
class ____(UIGraphicsItem): """ Handle represents a single user-interactable point attached to an ROI. They are usually created by a call to one of the ROI.add___Handle() methods. Handles are represented as a square, diamond, or circle, and are drawn with fixed pixel size regardless of the scaling of the view they are displayed in. Handles may be dragged to change the position, size, orientation, or other properties of the ROI they are attached to. """ types = { ## defines number of sides, start angle for each handle type 't': (4, np.pi/4), 'f': (4, np.pi/4), 's': (4, 0), 'r': (12, 0), 'sr': (12, 0), 'rf': (12, 0), } sigClicked = QtCore.Signal(object, object) # self, event sigRemoveRequested = QtCore.Signal(object) # self def __init__(self, radius, typ=None, pen=(200, 200, 220), hoverPen=(255, 255, 0), parent=None, deletable=False, antialias=True): self.rois = [] self.radius = radius self.typ = typ self.pen = fn.mkPen(pen) self.hoverPen = fn.mkPen(hoverPen) self.currentPen = self.pen self.isMoving = False self.sides, self.startAng = self.types[typ] self.buildPath() self._shape = None self._antialias = antialias self.menu = self.buildMenu() UIGraphicsItem.__init__(self, parent=parent) self.setAcceptedMouseButtons(QtCore.Qt.MouseButton.NoButton) self.deletable = deletable if deletable: self.setAcceptedMouseButtons(QtCore.Qt.MouseButton.RightButton) self.setZValue(11) def pos(self): # ROI class assumes that Handle class returns pg.Point return Point(super().pos()) def connectROI(self, roi): ### roi is the "parent" roi, i is the index of the handle in roi.handles self.rois.append(roi) def disconnectROI(self, roi): self.rois.remove(roi) def setDeletable(self, b): self.deletable = b if b: self.setAcceptedMouseButtons(self.acceptedMouseButtons() | QtCore.Qt.MouseButton.RightButton) else: self.setAcceptedMouseButtons(self.acceptedMouseButtons() & ~QtCore.Qt.MouseButton.RightButton) def removeClicked(self): self.sigRemoveRequested.emit(self) def hoverEvent(self, ev): hover = False if not ev.isExit(): if ev.acceptDrags(QtCore.Qt.MouseButton.LeftButton): hover=True for btn in [QtCore.Qt.MouseButton.LeftButton, QtCore.Qt.MouseButton.RightButton, QtCore.Qt.MouseButton.MiddleButton]: if (self.acceptedMouseButtons() & btn) and ev.acceptClicks(btn): hover=True if hover: self.currentPen = self.hoverPen else: self.currentPen = self.pen self.update() def mouseClickEvent(self, ev): ## right-click cancels drag if ev.button() == QtCore.Qt.MouseButton.RightButton and self.isMoving: self.isMoving = False ## prevents any further motion self.movePoint(self.startPos, finish=True) ev.accept() elif self.acceptedMouseButtons() & ev.button(): ev.accept() if ev.button() == QtCore.Qt.MouseButton.RightButton and self.deletable: self.raiseContextMenu(ev) self.sigClicked.emit(self, ev) else: ev.ignore() def buildMenu(self): menu = QtWidgets.QMenu() menu.setTitle(translate("ROI", "Handle")) self.removeAction = menu.addAction(translate("ROI", "Remove handle"), self.removeClicked) return menu def getMenu(self): return self.menu def raiseContextMenu(self, ev): menu = self.scene().addParentContextMenus(self, self.getMenu(), ev) ## Make sure it is still ok to remove this handle removeAllowed = all(r.checkRemoveHandle(self) for r in self.rois) self.removeAction.setEnabled(removeAllowed) pos = ev.screenPos() menu.popup(QtCore.QPoint(int(pos.x()), int(pos.y()))) def mouseDragEvent(self, ev): if ev.button() != QtCore.Qt.MouseButton.LeftButton: return ev.accept() ## Inform ROIs that a drag is happening ## note: the ROI is informed that the handle has moved using ROI.movePoint ## this is for other (more nefarious) purposes. #for r in self.roi: #r[0].pointDragEvent(r[1], ev) if ev.isFinish(): if self.isMoving: for r in self.rois: r.stateChangeFinished() self.isMoving = False self.currentPen = self.pen self.update() elif ev.isStart(): for r in self.rois: r.handleMoveStarted() self.isMoving = True self.startPos = self.scenePos() self.cursorOffset = self.scenePos() - ev.buttonDownScenePos() self.currentPen = self.hoverPen if self.isMoving: ## note: isMoving may become False in mid-drag due to right-click. pos = ev.scenePos() + self.cursorOffset self.currentPen = self.hoverPen self.movePoint(pos, ev.modifiers(), finish=False) def movePoint(self, pos, modifiers=None, finish=True): if modifiers is None: modifiers = QtCore.Qt.KeyboardModifier.NoModifier for r in self.rois: if not r.checkPointMove(self, pos, modifiers): return #print "point moved; inform %d ROIs" % len(self.roi) # A handle can be used by multiple ROIs; tell each to update its handle position for r in self.rois: r.movePoint(self, pos, modifiers, finish=finish, coords='scene') def buildPath(self): size = self.radius self.path = QtGui.QPainterPath() ang = self.startAng dt = 2 * np.pi / self.sides for i in range(0, self.sides): x = size * cos(ang) y = size * sin(ang) ang += dt if i == 0: self.path.moveTo(x, y) else: self.path.lineTo(x, y) self.path.closeSubpath() def paint(self, p, opt, widget): p.setRenderHint( p.RenderHint.Antialiasing, self._antialias ) p.setPen(self.currentPen) p.drawPath(self.shape()) def shape(self): if self._shape is None: s = self.generateShape() if s is None: return self.path self._shape = s # beware--this can cause the view to adjust, # which would immediately invalidate the shape. self.prepareGeometryChange() return self._shape def boundingRect(self): s1 = self.shape() # noqa: avoid problems with shape invalidation return self.shape().boundingRect() def generateShape(self): dt = self.deviceTransform_() if dt is None: self._shape = self.path return None v = dt.map(QtCore.QPointF(1, 0)) - dt.map(QtCore.QPointF(0, 0)) va = atan2(v.y(), v.x()) dti = fn.invertQTransform(dt) devPos = dt.map(QtCore.QPointF(0,0)) tr = QtGui.QTransform() tr.translate(devPos.x(), devPos.y()) tr.rotateRadians(va) return dti.map(tr.map(self.path)) def viewTransformChanged(self): GraphicsObject.viewTransformChanged(self) self._shape = None ## invalidate shape, recompute later if requested. self.update()
Handle
python
wandb__wandb
wandb/sdk/artifacts/storage_policies/_multipart.py
{ "start": 2992, "end": 7171 }
class ____: q: Queue[QueuedChunk] cancel: threading.Event = field(default_factory=threading.Event) def multipart_download( executor: Executor, session: Session, url: str, size: int, cached_open: Opener, part_size: int = MULTI_DEFAULT_PART_SIZE, ): """Download file as multiple parts in parallel. Only one thread for writing to file. Each part run one http request in one thread. HTTP response chunk of a file part is sent to the writer thread via a queue. """ # ------------------------------------------------------------------------------ # Shared between threads ctx = MultipartDownloadContext(q=Queue(maxsize=500)) # Put cache_open at top so we remove the tmp file when there is network error. with cached_open("wb") as f: def download_chunk(start: int, end: int | None = None) -> None: # Error from another thread, no need to start if ctx.cancel.is_set(): return # https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range # Start and end are both inclusive. An empty end uses the actual end # of the file. Example string: "bytes=0-499". bytes_range = f"{start}-" if (end is None) else f"{start}-{end}" headers = {"Range": f"bytes={bytes_range}"} with session.get(url=url, headers=headers, stream=True) as rsp: offset = start for chunk in rsp.iter_content(chunk_size=RSP_CHUNK_SIZE): if ctx.cancel.is_set(): return ctx.q.put(ChunkContent(offset=offset, data=chunk)) offset += len(chunk) def write_chunks() -> None: # If all chunks are written or there's an error in another thread, shutdown while not (ctx.cancel.is_set() or is_end_chunk(chunk := ctx.q.get())): try: # NOTE: Seek works without pre allocating the file on disk. # It automatically creates a sparse file, e.g. ls -hl would show # a bigger size compared to du -sh * because downloading different # chunks is not a sequential write. # See https://man7.org/linux/man-pages/man2/lseek.2.html f.seek(chunk.offset) f.write(chunk.data) except Exception as e: if env.is_debug(): logger.debug(f"Error writing chunk to file: {e}") ctx.cancel.set() raise # Start writer thread first. write_future = executor.submit(write_chunks) # Start download threads for each chunk. download_futures = set() for start in range(0, size, part_size): # https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Range # Start and end are both inclusive. An empty end uses the actual end # of the file. Example string: "bytes=0-499". end = end if (end := (start + part_size - 1)) < size else None download_futures.add(executor.submit(download_chunk, start=start, end=end)) # Wait for download done, not_done = wait(download_futures, return_when=FIRST_EXCEPTION) try: for fut in done: fut.result() except Exception as e: if env.is_debug(): logger.debug(f"Error downloading file: {e}") ctx.cancel.set() # Cancel any pending futures. Note: # - `Future.cancel()` does NOT stop the future if it's running, which is why # there's a separate `threading.Event` to ensure cooperative cancellation. # - Once Python 3.8 support is dropped, replace these `fut.cancel()` # calls with `Executor.shutdown(cancel_futures=True)`. for fut in not_done: fut.cancel() raise finally: # Always signal the writer to stop ctx.q.put(END_CHUNK) write_future.result()
MultipartDownloadContext
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 60598, "end": 60956 }
class ____(themeable): """ Location of legend Parameters ---------- theme_element : tuple[float, float] Where to place legends that are inside the panels / facets area. The values should be in the range `[0, 1]`. The default is to put it in the center (`(.5, .5)`) of the panels area. """
legend_position_inside
python
getsentry__sentry
src/sentry/hybridcloud/services/control_organization_provisioning/impl.py
{ "start": 2444, "end": 11744 }
class ____( ControlOrganizationProvisioningRpcService ): @staticmethod def _validate_organization_belongs_to_user(user_id: int, organization: RpcOrganization) -> bool: top_dog_id = roles.get_top_dog().id try: org_member = OrganizationMember.objects.get( organization_id=organization.id, user_id=user_id ) return top_dog_id == org_member.role except OrganizationMember.DoesNotExist: return False @staticmethod def _validate_organization_mapping_belongs_to_user( user_id: int, organization_mapping: OrganizationMapping ) -> bool: top_dog_id = roles.get_top_dog().id try: org_member = OrganizationMemberMapping.objects.get( organization_id=organization_mapping.organization_id, user_id=user_id ) return top_dog_id == org_member.role except OrganizationMemberMapping.DoesNotExist: return False @staticmethod def _generate_org_snowflake_id(region_name: str) -> int: return generate_snowflake_id(Organization.snowflake_redis_key) @staticmethod def _generate_org_slug(region_name: str, slug: str) -> str: slug_base = slug.replace("_", "-").strip("-") surrogate_org_slug = OrganizationSlugReservation() slugify_instance(surrogate_org_slug, slug_base, reserved=RESERVED_ORGANIZATION_SLUGS) return surrogate_org_slug.slug @staticmethod def _get_slug_reservation_for_organization( organization_id: int, reservation_type: OrganizationSlugReservationType ) -> OrganizationSlugReservation | None: try: slug_res = OrganizationSlugReservation.objects.get( organization_id=organization_id, reservation_type=reservation_type ) return slug_res except OrganizationSlugReservation.DoesNotExist: return None @staticmethod def _get_slug_reservation_by_type_from_list( org_slug_reservations: list[OrganizationSlugReservation], reservation_type: OrganizationSlugReservationType, ) -> OrganizationSlugReservation | None: return next( ( slug_res for slug_res in org_slug_reservations if slug_res.reservation_type == reservation_type.value ), None, ) def provision_organization( self, *, region_name: str, org_provision_args: OrganizationProvisioningOptions ) -> RpcOrganizationSlugReservation: # Generate a new non-conflicting slug and org ID org_id = self._generate_org_snowflake_id(region_name=region_name) slug = self._generate_org_slug( region_name=region_name, slug=org_provision_args.provision_options.slug ) # Generate a provisioning outbox for the region and drain updated_provision_options = deepcopy(org_provision_args.provision_options) updated_provision_options.slug = slug provision_payload = OrganizationProvisioningOptions( provision_options=updated_provision_options, post_provision_options=org_provision_args.post_provision_options, ) with outbox_context( transaction.atomic(using=router.db_for_write(OrganizationSlugReservation)) ): # TODO @GabeVillalobos: add email/user_id pair to be able to check for idempotency org_slug_res = OrganizationSlugReservation( slug=slug, organization_id=org_id, user_id=org_provision_args.provision_options.owning_user_id, region_name=region_name, ) org_slug_res.save(unsafe_write=True) create_organization_provisioning_outbox( organization_id=org_id, region_name=region_name, org_provision_payload=provision_payload, ).save() # After outboxes resolve, ensure that the organization slug still exists. # If it was deleted, the provisioning failed for some reason. org_slug_requery = OrganizationSlugReservation.objects.get(id=org_slug_res.id) assert ( org_slug_requery.slug == org_slug_res.slug and org_slug_requery.organization_id == org_slug_res.organization_id ), "Organization slug reservation does not match after provisioning the org" return serialize_slug_reservation(org_slug_res) def idempotent_provision_organization( self, *, region_name: str, org_provision_args: OrganizationProvisioningOptions ) -> RpcOrganizationSlugReservation | None: raise NotImplementedError() def update_organization_slug( self, *, region_name: str, organization_id: int, desired_slug: str, require_exact: bool = True, ) -> RpcOrganizationSlugReservation: existing_slug_reservations = list( OrganizationSlugReservation.objects.filter(organization_id=organization_id) ) existing_temporary_alias = self._get_slug_reservation_by_type_from_list( org_slug_reservations=existing_slug_reservations, reservation_type=OrganizationSlugReservationType.TEMPORARY_RENAME_ALIAS, ) if existing_temporary_alias: raise Exception("Cannot change an organization slug while another swap is in progress") existing_primary_alias = self._get_slug_reservation_by_type_from_list( org_slug_reservations=existing_slug_reservations, reservation_type=OrganizationSlugReservationType.PRIMARY, ) # If there's already a matching primary slug reservation for the org, # just replicate it to the region to kick off the organization sync process if existing_primary_alias and existing_primary_alias.slug == desired_slug: existing_primary_alias.handle_async_replication(region_name, organization_id) return serialize_slug_reservation(existing_primary_alias) slug_base = desired_slug if not require_exact: slug_base = self._generate_org_slug(region_name=region_name, slug=slug_base) with outbox_context( transaction.atomic(using=router.db_for_write(OrganizationSlugReservation)) ): OrganizationSlugReservation( slug=slug_base, organization_id=organization_id, user_id=-1, region_name=region_name, reservation_type=OrganizationSlugReservationType.TEMPORARY_RENAME_ALIAS.value, ).save(unsafe_write=True) org_mapping = OrganizationMapping.objects.filter( organization_id=organization_id ).first() org = serialize_organization_mapping(org_mapping) if org_mapping is not None else None if org and features.has("organizations:revoke-org-auth-on-slug-rename", org): # Changing a slug invalidates all org tokens, so revoke them all. auth_tokens = OrgAuthToken.objects.filter( organization_id=organization_id, date_deactivated__isnull=True ) auth_tokens.update(date_deactivated=django_timezone.now()) primary_slug = self._validate_primary_slug_updated( organization_id=organization_id, slug_base=slug_base ) return serialize_slug_reservation(primary_slug) def _validate_primary_slug_updated( self, organization_id: int, slug_base: str ) -> OrganizationSlugReservation: primary_slug = self._get_slug_reservation_for_organization( organization_id=organization_id, reservation_type=OrganizationSlugReservationType.PRIMARY, ) if not primary_slug or primary_slug.slug != slug_base: raise InvalidOrganizationProvisioningException( "Failed to swap slug for organization, likely due to conflict on the region" ) return primary_slug def bulk_create_organization_slug_reservations( self, *, region_name: str, slug_mapping: dict[int, str], ) -> None: slug_reservations_to_create: list[OrganizationSlugReservation] = [] with outbox_context(transaction.atomic(router.db_for_write(OrganizationSlugReservation))): for org_id, slug in slug_mapping.items(): slug_reservation = OrganizationSlugReservation( slug=self._generate_org_slug(slug=slug, region_name=region_name), organization_id=org_id, reservation_type=OrganizationSlugReservationType.TEMPORARY_RENAME_ALIAS.value, user_id=-1, region_name=region_name, ) slug_reservation.save(unsafe_write=True) slug_reservations_to_create.append(slug_reservation) for slug_reservation in slug_reservations_to_create: self._validate_primary_slug_updated( slug_base=slug_reservation.slug, organization_id=slug_reservation.organization_id )
DatabaseBackedControlOrganizationProvisioningService
python
getsentry__sentry
src/sentry/workflow_engine/typings/grouptype.py
{ "start": 174, "end": 647 }
class ____(GroupType): type_id = -1 slug = "issue_stream" description = "Issue Stream" category = GroupCategory.ERROR.value category_v2 = GroupCategory.ERROR.value released = False in_default_search = False enable_auto_resolve = False enable_escalation_detection = False enable_status_change_workflow_notifications = False enable_workflow_notifications = False enable_user_status_and_priority_changes = False
IssueStreamGroupType
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
{ "start": 6183, "end": 20171 }
class ____(TestTaskInstanceEndpoint): def test_should_respond_200(self, test_client, session): self.create_task_instances(session) # Update ti and set operator to None to # test that operator field is nullable. # This prevents issue when users upgrade to 2.0+ # from 1.10.x # https://github.com/apache/airflow/issues/14421 session.query(TaskInstance).update({TaskInstance.operator: None}, synchronize_session="fetch") session.commit() response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 200 assert response.json() == { "dag_id": "example_python_operator", "dag_version": mock.ANY, "dag_display_name": "example_python_operator", "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "logical_date": "2020-01-01T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": None, "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "running", "task_id": "print_the_context", "task_display_name": "print_the_context", "try_number": 0, "unixname": getuser(), "dag_run_id": "TEST_DAG_RUN_ID", "rendered_fields": {}, "rendered_map_index": None, "run_after": "2020-01-01T00:00:00Z", "trigger": None, "triggerer_job": None, } def test_should_respond_200_with_decorator(self, test_client, session): self.create_task_instances(session, "example_python_decorator") response = test_client.get( "/dags/example_python_decorator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 200 response_json = response.json() assert response_json["operator_name"] == "@task" assert response_json["operator"] == "_PythonDecoratedOperator" def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 403 @pytest.mark.parametrize( ("run_id", "expected_version_number"), [ ("run1", 1), ("run2", 2), ("run3", 3), ], ) @pytest.mark.usefixtures("make_dag_with_multiple_versions") @mock.patch("airflow.api_fastapi.core_api.datamodels.dag_versions.hasattr") def test_should_respond_200_with_versions( self, mock_hasattr, test_client, run_id, expected_version_number ): mock_hasattr.return_value = False response = test_client.get(f"/dags/dag_with_multiple_versions/dagRuns/{run_id}/taskInstances/task1") assert response.status_code == 200 assert response.json() == { "id": mock.ANY, "task_id": "task1", "dag_id": "dag_with_multiple_versions", "dag_run_id": run_id, "dag_display_name": "dag_with_multiple_versions", "map_index": -1, "logical_date": mock.ANY, "start_date": None, "end_date": mock.ANY, "duration": None, "state": None, "try_number": 0, "max_tries": 0, "task_display_name": "task1", "hostname": "", "unixname": getuser(), "pool": "default_pool", "pool_slots": 1, "queue": "default", "priority_weight": 1, "operator": "EmptyOperator", "operator_name": "EmptyOperator", "queued_when": None, "scheduled_when": None, "pid": None, "executor": None, "executor_config": "{}", "note": None, "rendered_map_index": None, "rendered_fields": {}, "run_after": mock.ANY, "trigger": None, "triggerer_job": None, "dag_version": { "id": mock.ANY, "version_number": expected_version_number, "dag_id": "dag_with_multiple_versions", "dag_display_name": "dag_with_multiple_versions", "bundle_name": "dag_maker", "bundle_version": f"some_commit_hash{expected_version_number}", "bundle_url": f"http://test_host.github.com/tree/some_commit_hash{expected_version_number}/dags", "created_at": mock.ANY, }, } def test_should_respond_200_with_task_state_in_deferred(self, test_client, session): now = pendulum.now("UTC") ti = self.create_task_instances( session, task_instances=[{"state": State.DEFERRED}], update_extras=True )[0] ti.trigger = Trigger("none", {}) ti.trigger.created_date = now ti.triggerer_job = Job() TriggererJobRunner(job=ti.triggerer_job) ti.triggerer_job.state = "running" session.commit() response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) data = response.json() # this logic in effect replicates mock.ANY for these values values_to_ignore = { "trigger": ["created_date", "id", "triggerer_id"], "triggerer_job": ["executor_class", "hostname", "id", "latest_heartbeat", "start_date"], } for k, v in values_to_ignore.items(): for elem in v: del data[k][elem] assert response.status_code == 200 assert data == { "dag_id": "example_python_operator", "dag_version": mock.ANY, "dag_display_name": "example_python_operator", "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "logical_date": "2020-01-01T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": "PythonOperator", "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "deferred", "task_id": "print_the_context", "task_display_name": "print_the_context", "try_number": 0, "unixname": getuser(), "dag_run_id": "TEST_DAG_RUN_ID", "run_after": "2020-01-01T00:00:00Z", "rendered_fields": {}, "rendered_map_index": None, "trigger": { "classpath": "none", "kwargs": "{}", }, "triggerer_job": { "dag_display_name": None, "dag_id": None, "end_date": None, "job_type": "TriggererJob", "state": "running", "unixname": getuser(), }, } def test_should_respond_200_with_task_state_in_removed(self, test_client, session): self.create_task_instances(session, task_instances=[{"state": State.REMOVED}], update_extras=True) response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 200 assert response.json() == { "dag_id": "example_python_operator", "dag_version": mock.ANY, "dag_display_name": "example_python_operator", "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "logical_date": "2020-01-01T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": "PythonOperator", "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "removed", "task_id": "print_the_context", "task_display_name": "print_the_context", "try_number": 0, "unixname": getuser(), "dag_run_id": "TEST_DAG_RUN_ID", "rendered_fields": {}, "rendered_map_index": None, "run_after": "2020-01-01T00:00:00Z", "trigger": None, "triggerer_job": None, } def test_should_respond_200_task_instance_with_rendered(self, test_client, session): tis = self.create_task_instances(session) session.query() rendered_fields = RTIF(tis[0], render_templates=False) session.add(rendered_fields) session.commit() response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 200 assert response.json() == { "dag_id": "example_python_operator", "dag_version": mock.ANY, "dag_display_name": "example_python_operator", "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "logical_date": "2020-01-01T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": "PythonOperator", "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "running", "task_id": "print_the_context", "task_display_name": "print_the_context", "try_number": 0, "unixname": getuser(), "dag_run_id": "TEST_DAG_RUN_ID", "rendered_fields": {"op_args": [], "op_kwargs": {}, "templates_dict": None}, "rendered_map_index": None, "run_after": "2020-01-01T00:00:00Z", "trigger": None, "triggerer_job": None, } def test_raises_404_for_nonexistent_task_instance(self, test_client): response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 404 assert response.json() == { "detail": "The Task Instance with dag_id: `example_python_operator`, run_id: `TEST_DAG_RUN_ID` and task_id: `print_the_context` was not found" } def test_raises_404_for_mapped_task_instance_with_multiple_indexes(self, test_client, session): tis = self.create_task_instances(session) old_ti = tis[0] for index in range(3): ti = TaskInstance( task=old_ti.task, run_id=old_ti.run_id, map_index=index, dag_version_id=old_ti.dag_version_id ) for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note"]: setattr(ti, attr, getattr(old_ti, attr)) session.add(ti) session.delete(old_ti) session.commit() response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 404 assert response.json() == {"detail": "Task instance is mapped, add the map_index value to the URL"} def test_raises_404_for_mapped_task_instance_with_one_index(self, test_client, session): tis = self.create_task_instances(session) old_ti = tis[0] ti = TaskInstance( task=old_ti.task, run_id=old_ti.run_id, map_index=2, dag_version_id=old_ti.dag_version_id ) for attr in ["duration", "end_date", "pid", "start_date", "state", "queue", "note"]: setattr(ti, attr, getattr(old_ti, attr)) session.add(ti) session.delete(old_ti) session.commit() response = test_client.get( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" ) assert response.status_code == 404 assert response.json() == {"detail": "Task instance is mapped, add the map_index value to the URL"}
TestGetTaskInstance
python
wandb__wandb
wandb/automations/_filters/run_metrics.py
{ "start": 1708, "end": 1979 }
class ____(LenientStrEnum): # from: RunMetricChangeDirection """Describes the direction of the metric change.""" INCREASE = "INCREASE" DECREASE = "DECREASE" ANY = "ANY" # Shorter aliases for convenience INC = INCREASE DEC = DECREASE
ChangeDir
python
spack__spack
lib/spack/spack/operating_systems/windows_os.py
{ "start": 773, "end": 6269 }
class ____(OperatingSystem): """This class represents the Windows operating system. This will be auto detected using the python platform.win32_ver() once we have a python setup that runs natively. The Windows platform will be represented using the major version operating system number, e.g. 10. """ def __init__(self): plat_ver = windows_version() if plat_ver < Version("10"): raise SpackError("Spack is not supported on Windows versions older than 10") super().__init__("windows{}".format(plat_ver), plat_ver) def __str__(self): return self.name @property def vs_install_paths(self): vs_install_paths = [] root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles") if root: try: extra_args = {"encoding": "mbcs", "errors": "strict"} paths = subprocess.check_output( # type: ignore[call-overload] # novermin [ os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"), "-prerelease", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath", "-products", "*", ], **extra_args, ).strip() vs_install_paths = paths.split("\n") except (subprocess.CalledProcessError, OSError, UnicodeDecodeError): pass return vs_install_paths @property def msvc_paths(self): return [os.path.join(path, "VC", "Tools", "MSVC") for path in self.vs_install_paths] @property def oneapi_root(self): root = os.environ.get("ONEAPI_ROOT", "") or os.path.join( os.environ.get("ProgramFiles(x86)", ""), "Intel", "oneAPI" ) if os.path.exists(root): return root @property def compiler_search_paths(self): # First Strategy: Find MSVC directories using vswhere _compiler_search_paths = [] for p in self.msvc_paths: _compiler_search_paths.extend(glob.glob(os.path.join(p, "*", "bin", "Hostx64", "x64"))) oneapi_root = self.oneapi_root if oneapi_root: _compiler_search_paths.extend( glob.glob(os.path.join(oneapi_root, "compiler", "**", "bin"), recursive=True) ) # Second strategy: Find MSVC via the registry def try_query_registry(retry=False): winreg_report_error = lambda e: tty.debug( 'Windows registry query on "SOFTWARE\\WOW6432Node\\Microsoft"' f"under HKEY_LOCAL_MACHINE: {str(e)}" ) try: # Registry interactions are subject to race conditions, etc and can generally # be flakey, do this in a catch block to prevent reg issues from interfering # with compiler detection msft = winreg.WindowsRegistryView( "SOFTWARE\\WOW6432Node\\Microsoft", winreg.HKEY.HKEY_LOCAL_MACHINE ) return msft.find_subkeys(r"VisualStudio_.*", recursive=False) except OSError as e: # OSErrors propagated into caller by Spack's registry module are expected # and indicate a known issue with the registry query # i.e. user does not have permissions or the key/value # doesn't exist winreg_report_error(e) return [] except winreg.InvalidRegistryOperation as e: # Other errors raised by the Spack's reg module indicate # an unexpected error type, and are handled specifically # as the underlying cause is difficult/impossible to determine # without manually exploring the registry # These errors can also be spurious (race conditions) # and may resolve on re-execution of the query # or are permanent (specific types of permission issues) # but the registry raises the same exception for all types of # atypical errors if retry: winreg_report_error(e) return [] vs_entries = try_query_registry() if not vs_entries: # Occasional spurious race conditions can arise when reading the MS reg # typically these race conditions resolve immediately and we can safely # retry the reg query without waiting # Note: Winreg does not support locking vs_entries = try_query_registry(retry=True) vs_paths = [] def clean_vs_path(path): path = path.split(",")[0].lstrip("@") return str((pathlib.Path(path).parent / "..\\..").resolve()) for entry in vs_entries: try: val = entry.get_subkey("Capabilities").get_value("ApplicationDescription").value vs_paths.append(clean_vs_path(val)) except FileNotFoundError as e: if hasattr(e, "winerror") and e.winerror == 2: pass else: raise _compiler_search_paths.extend(vs_paths) return _compiler_search_paths
WindowsOs
python
arrow-py__arrow
tests/test_locales.py
{ "start": 121849, "end": 126118 }
class ____: def test_format_timeframe(self): assert self.locale._format_timeframe("now", 0) == "刚才" assert self.locale._format_timeframe("second", 1) == "1秒" assert self.locale._format_timeframe("seconds", 30) == "30秒" assert self.locale._format_timeframe("minute", 1) == "1分钟" assert self.locale._format_timeframe("minutes", 40) == "40分钟" assert self.locale._format_timeframe("hour", 1) == "1小时" assert self.locale._format_timeframe("hours", 23) == "23小时" assert self.locale._format_timeframe("day", 1) == "1天" assert self.locale._format_timeframe("days", 12) == "12天" assert self.locale._format_timeframe("week", 1) == "1周" assert self.locale._format_timeframe("weeks", 38) == "38周" assert self.locale._format_timeframe("month", 1) == "1个月" assert self.locale._format_timeframe("months", 11) == "11个月" assert self.locale._format_timeframe("year", 1) == "1年" assert self.locale._format_timeframe("years", 12) == "12年" assert self.locale._format_timeframe("second", -1) == "1秒" assert self.locale._format_timeframe("seconds", -30) == "30秒" assert self.locale._format_timeframe("minute", -1) == "1分钟" assert self.locale._format_timeframe("minutes", -40) == "40分钟" assert self.locale._format_timeframe("hour", -1) == "1小时" assert self.locale._format_timeframe("hours", -23) == "23小时" assert self.locale._format_timeframe("day", -1) == "1天" assert self.locale._format_timeframe("days", -12) == "12天" assert self.locale._format_timeframe("week", -1) == "1周" assert self.locale._format_timeframe("weeks", -38) == "38周" assert self.locale._format_timeframe("month", -1) == "1个月" assert self.locale._format_timeframe("months", -11) == "11个月" assert self.locale._format_timeframe("year", -1) == "1年" assert self.locale._format_timeframe("years", -12) == "12年" def test_format_relative_now(self): assert self.locale._format_relative("刚才", "now", 0) == "刚才" def test_format_relative_past(self): assert self.locale._format_relative("1秒", "second", 1) == "1秒后" assert self.locale._format_relative("2秒", "seconds", 2) == "2秒后" assert self.locale._format_relative("1分钟", "minute", 1) == "1分钟后" assert self.locale._format_relative("2分钟", "minutes", 2) == "2分钟后" assert self.locale._format_relative("1小时", "hour", 1) == "1小时后" assert self.locale._format_relative("2小时", "hours", 2) == "2小时后" assert self.locale._format_relative("1天", "day", 1) == "1天后" assert self.locale._format_relative("2天", "days", 2) == "2天后" assert self.locale._format_relative("1周", "week", 1) == "1周后" assert self.locale._format_relative("2周", "weeks", 2) == "2周后" assert self.locale._format_relative("1个月", "month", 1) == "1个月后" assert self.locale._format_relative("2个月", "months", 2) == "2个月后" assert self.locale._format_relative("1年", "year", 1) == "1年后" assert self.locale._format_relative("2年", "years", 2) == "2年后" def test_format_relative_future(self): assert self.locale._format_relative("1秒", "second", -1) == "1秒前" assert self.locale._format_relative("2秒", "seconds", -2) == "2秒前" assert self.locale._format_relative("1分钟", "minute", -1) == "1分钟前" assert self.locale._format_relative("2分钟", "minutes", -2) == "2分钟前" assert self.locale._format_relative("1小时", "hour", -1) == "1小时前" assert self.locale._format_relative("2小时", "hours", -2) == "2小时前" assert self.locale._format_relative("1天", "day", -1) == "1天前" assert self.locale._format_relative("2天", "days", -2) == "2天前" assert self.locale._format_relative("1周", "week", -1) == "1周前" assert self.locale._format_relative("2周", "weeks", -2) == "2周前" assert self.locale._format_relative("1个月", "month", -1) == "1个月前" assert self.locale._format_relative("2个月", "months", -2) == "2个月前" assert self.locale._format_relative("1年", "year", -1) == "1年前" assert self.locale._format_relative("2年", "years", -2) == "2年前" @pytest.mark.usefixtures("lang_locale")
TestChineseCNLocale
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass5.py
{ "start": 354, "end": 501 }
class ____: x: int x_squared: int def __init__(self, x: int): self.x = x self.x_squared = x**2 b = B(3) @dataclass()
B
python
getsentry__sentry
src/sentry/workflow_engine/models/incident_groupopenperiod.py
{ "start": 869, "end": 15227 }
class ____(DefaultFieldsModel): """ A lookup model for incidents and group open periods. """ __relocation_scope__ = RelocationScope.Excluded incident_id = BoundedBigIntegerField(null=True, unique=True) incident_identifier = models.IntegerField(null=True) group_open_period = FlexibleForeignKey("sentry.GroupOpenPeriod", unique=True) class Meta: db_table = "workflow_engine_incidentgroupopenperiod" app_label = "workflow_engine" constraints = [ models.CheckConstraint( condition=Q(incident_identifier__isnull=False) & Q(incident_id__isnull=False) | Q(incident_identifier__isnull=True) & Q(incident_id__isnull=True), name="inc_id_inc_identifier_together", ) ] @classmethod def create_from_occurrence(cls, occurrence, group, open_period): """ Creates an IncidentGroupOpenPeriod relationship from an issue occurrence. This method handles the case where the incident might not exist yet. Args: occurrence: The IssueOccurrence that triggered the group creation group: The Group that was created open_period: The GroupOpenPeriod for the group """ try: # Extract alert_id from evidence_data using the detector_id detector_id = occurrence.evidence_data.get("detector_id") if detector_id: try: alert_id = AlertRuleDetector.objects.get(detector_id=detector_id).alert_rule_id except AlertRuleDetector.DoesNotExist: # detector does not have an analog in the old system, so we do not need to create an IGOP relationship return None else: raise Exception("No detector_id found in evidence_data for metric issue") # If the relationship was previously created, return it relationship = cls.get_relationship(open_period) if relationship is not None: return relationship # Otherwise, this is a new open period, so create the incident and IGOP relationship try: alert_rule = AlertRule.objects.get(id=alert_id) except AlertRule.DoesNotExist: logger.warning( "AlertRule not found for alert_id", extra={ "alert_id": alert_id, "group_id": group.id, }, ) raise incident = cls.create_incident_for_open_period( occurrence, alert_rule, group, open_period ) return cls.create_relationship(incident, open_period) except Exception as e: logger.exception( "Failed to create IncidentGroupOpenPeriod relationship", extra={ "group_id": group.id, "occurrence_id": occurrence.id, "error": str(e), }, ) return None @classmethod def create_incident_for_open_period(cls, occurrence, alert_rule, group, open_period): from sentry.incidents.logic import create_incident, update_incident_status from sentry.incidents.models.incident import Incident, IncidentStatus, IncidentStatusMethod from sentry.incidents.utils.process_update_helpers import ( calculate_event_date_from_update_date, ) # XXX: to patch incidents that never closed when open periods were closed by means # other than an emitted detector status change: if an open incident exists when we # get here, close it. open_incident = ( Incident.objects.filter(alert_rule__id=alert_rule.id, date_closed=None) .order_by("-date_started") .first() ) if open_incident is not None: try: incident_group_open_period = cls.objects.get( incident_id=open_incident.id, ) old_open_period = incident_group_open_period.group_open_period if old_open_period.date_ended is None: raise Exception("Outdated open period missing date_ended") if open_incident.subscription_id is not None: subscription = QuerySubscription.objects.select_related("snuba_query").get( id=int(open_incident.subscription_id) ) time_window = subscription.snuba_query.time_window else: time_window = 0 calculated_date_closed = calculate_event_date_from_update_date( old_open_period.date_ended, time_window ) update_incident_status( open_incident, IncidentStatus.CLOSED, status_method=IncidentStatusMethod.RULE_TRIGGERED, date_closed=calculated_date_closed, ) except IncidentGroupOpenPeriod.DoesNotExist: # If there's no IGOP relationship. This can happen if the incident opened before we # switched to single processing, as there's a long tail here, or the incident was broken for some # reason. # Associate the ongoing incident with the current open period. We'll start correct associations # with the next open period. return open_incident # Extract query subscription id from evidence_data source_id = occurrence.evidence_data.get("data_packet_source_id") if source_id: subscription = QuerySubscription.objects.get(id=int(source_id)) snuba_query = SnubaQuery.objects.get(id=subscription.snuba_query_id) else: raise Exception("No source_id found in evidence_data for metric issue") calculated_start_date = calculate_event_date_from_update_date( open_period.date_started, snuba_query.time_window ) incident = create_incident( organization=alert_rule.organization, incident_type=IncidentType.ALERT_TRIGGERED, title=alert_rule.name, alert_rule=alert_rule, date_started=calculated_start_date, date_detected=open_period.date_started, projects=[group.project], subscription=subscription, ) # XXX: if this is the very first open period, or if the priority didn't change from the last priority on the last open period, # manually add the first incident status change activity because the group never changed priority # if the priority changed, then the call to update_incident_status in update_priority will be a no-op priority = ( occurrence.priority if occurrence.priority is not None else DetectorPriorityLevel.HIGH ) severity = ( IncidentStatus.CRITICAL if priority == DetectorPriorityLevel.HIGH else IncidentStatus.WARNING ) # LOW isn't used for metric issues update_incident_status( incident, severity, status_method=IncidentStatusMethod.RULE_TRIGGERED, ) return incident @classmethod def get_relationship(cls, open_period): """ Returns the IncidentGroupOpenPeriod relationship if it exists. """ return cls.objects.filter(group_open_period=open_period).first() @classmethod def create_relationship(cls, incident, open_period): """ Creates IncidentGroupOpenPeriod relationship. Args: incident: The Incident to link open_period: The GroupOpenPeriod to link """ try: incident_group_open_period, _ = cls.objects.get_or_create( group_open_period=open_period, defaults={ "incident_id": incident.id, "incident_identifier": incident.identifier, }, ) return incident_group_open_period except IntegrityError: incident_group_open_period = cls.objects.get( group_open_period=open_period, incident_id=incident.id, ) return incident_group_open_period except Exception as e: logger.exception( "Failed to create/update IncidentGroupOpenPeriod relationship", extra={ "incident_id": incident.id, "open_period_id": open_period.id, "error": str(e), }, ) return None def update_incident_activity_based_on_group_activity( group: Group, priority: PriorityLevel, ) -> None: from sentry.incidents.logic import update_incident_status from sentry.incidents.models.incident import Incident, IncidentStatus, IncidentStatusMethod open_period = get_latest_open_period(group) if open_period is None: logger.warning("No open period found for group", extra={"group_id": group.id}) return # get the incident for the open period try: incident_id = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period).incident_id incident = Incident.objects.get(id=incident_id) except IncidentGroupOpenPeriod.DoesNotExist: # This could happen because the priority changed when opening the period, but # the priority change came before relationship creation. This isn't a problem—we create the # relationship with the new priority in create_from_occurrence() anyway. # We could also hit this case if there are outstanding open incidents when switching to single # processing. Again, create_from_occurrence() will handle any status changes we need. # Finally, this can also happen if the incident was not created because a detector was single # written in workflow engine. Just return in this case. logger.info( "No IncidentGroupOpenPeriod relationship found when updating IncidentActivity table", extra={ "open_period_id": open_period.id, }, ) return severity = ( IncidentStatus.CRITICAL if priority == PriorityLevel.HIGH else IncidentStatus.WARNING ) # this assumes that LOW isn't used for metric issues update_incident_status( incident, severity, status_method=IncidentStatusMethod.RULE_TRIGGERED, ) def update_incident_based_on_open_period_status_change( group: Group, new_status: int, ) -> None: from sentry.incidents.logic import update_incident_status from sentry.incidents.models.incident import Incident, IncidentStatus, IncidentStatusMethod from sentry.incidents.utils.process_update_helpers import calculate_event_date_from_update_date open_period = get_latest_open_period(group) if open_period is None: logger.warning("No open period found for group", extra={"group_id": group.id}) return # get the incident for the open period try: incident_id = IncidentGroupOpenPeriod.objects.get(group_open_period=open_period).incident_id incident = Incident.objects.get(id=incident_id) except IncidentGroupOpenPeriod.DoesNotExist: detector_group = DetectorGroup.objects.filter(group=group).first() # detector was not dual written, or this is a long-open alert that we should just close. if detector_group and detector_group.detector: detector_id = detector_group.detector.id try: alert_rule_id = AlertRuleDetector.objects.get(detector_id=detector_id).alert_rule_id except AlertRuleDetector.DoesNotExist: # Detector was not dual written. return open_incident = ( Incident.objects.filter(alert_rule__id=alert_rule_id, date_closed=None) .order_by("-date_started") .first() ) if open_incident is not None: incident = open_incident IncidentGroupOpenPeriod.create_relationship( incident=incident, open_period=open_period ) else: logger.info( "No IncidentGroupOpenPeriod relationship and no outstanding incident", extra={ "open_period_id": open_period.id, }, ) return else: # not much we can do here logger.info( "incident_groupopenperiod.hard_fail", extra={ "group_id": group.id, }, ) return if incident.subscription_id is not None: subscription = QuerySubscription.objects.select_related("snuba_query").get( id=int(incident.subscription_id) ) snuba_query = subscription.snuba_query # fail loudly if this doesn't exist else: logger.warning("Incident missing subscription_id", extra={"incident_id": incident.id}) return if new_status == GroupStatus.RESOLVED: if open_period.date_ended is None: logger.warning( "Missing information to close incident", extra={"group_id": group.id}, ) return calculated_date_closed = calculate_event_date_from_update_date( open_period.date_ended, snuba_query.time_window ) update_incident_status( incident, IncidentStatus.CLOSED, status_method=IncidentStatusMethod.RULE_TRIGGERED, date_closed=calculated_date_closed, ) # As far as I can tell, you can't manually unresolve a metric issue, so we shouldn't hit this case. # But the logic exists, so it doesn't hurt. Shrug. elif new_status == GroupStatus.UNRESOLVED: update_incident_status( incident, IncidentStatus.OPEN, )
IncidentGroupOpenPeriod
python
conda__conda
conda/cli/main_info.py
{ "start": 12778, "end": 18712 }
class ____: """ Provides a ``render`` method for rendering ``InfoComponents`` """ def __init__(self, context): self._context = context self._component_style_map = { "base": None, "channels": None, "detail": "detail_view", "envs": "envs_list", "system": None, "json_all": None, } @cached_property def _info_dict(self): info_dict = get_info_dict() info_dict["envs"] = self._info_dict_envs info_dict["envs_details"] = self._info_dict_envs_details return info_dict @cached_property def _info_dict_envs(self) -> list[str]: from ..core.envs_manager import list_all_known_prefixes return list_all_known_prefixes() @cached_property def _info_dict_envs_details(self) -> dict[str, dict[str, str | bool | None]]: from ..core.prefix_data import PrefixData result = {} if active_prefix := self._context.active_prefix: active_prefix_data = PrefixData(active_prefix) else: active_prefix_data = None for prefix in self._info_dict_envs: prefix_data = PrefixData(prefix) if created := prefix_data.created: created = created.isoformat() if last_modified := prefix_data.last_modified: last_modified = last_modified.isoformat() result[prefix] = { "name": prefix_data.name, "created": created, "last_modified": last_modified, "active": prefix_data == active_prefix_data, "base": prefix_data.is_base(), "frozen": prefix_data.is_frozen(), "writable": prefix_data.is_writable, } return result def render(self, components: Iterable[InfoComponents]): """ Iterates through the registered components, obtains the data to render via a ``_<component>_component`` method and then renders it. """ from ..reporters import render for component in components: style = self._component_style_map.get(component) data_func = getattr(self, f"_{component}_component", None) if not data_func: continue data = data_func() if data: render(data, style=style) def _base_component(self) -> str | dict: if self._context.json: return {"root_prefix": self._context.root_prefix} else: return f"{self._context.root_prefix}\n" def _channels_component(self) -> str | dict: if self._context.json: return {"channels": self._context.channels} else: channels_str = "\n".join(self._context.channels) return f"{channels_str}\n" def _detail_component(self) -> dict[str, str]: return get_main_info_display(self._info_dict) def _envs_component(self): if self._context.json: return { "envs": self._info_dict_envs, "envs_details": self._info_dict_envs_details, } return self._info_dict_envs def _system_component(self) -> str: from .find_commands import find_commands, find_executable output = [ f"sys.version: {sys.version[:40]}...", f"sys.prefix: {sys.prefix}", f"sys.executable: {sys.executable}", "conda location: {}".format(self._info_dict["conda_location"]), ] for cmd in sorted(set(find_commands() + ("build",))): output.append("conda-{}: {}".format(cmd, find_executable("conda-" + cmd))) site_dirs = self._info_dict["site_dirs"] if site_dirs: output.append(f"user site dirs: {site_dirs[0]}") else: output.append("user site dirs:") for site_dir in site_dirs[1:]: output.append(f" {site_dir}") output.append("") for name, value in sorted(self._info_dict["env_vars"].items()): output.append(f"{name}: {value}") output.append("") return "\n".join(output) def _json_all_component(self) -> dict[str, Any]: return self._info_dict @deprecated( "25.9", "26.3", addendum="Use `conda.cli.main_info.iter_info_components` instead.", ) def get_info_components(args: Namespace, context: Context) -> set[InfoComponents]: return set(iter_info_components(args, context)) def iter_info_components(args: Namespace, context: Context) -> Iterable[InfoComponents]: """ Determine which components to display. :param args: The parsed command line arguments. :param context: The conda context. :returns: An iterable of components to display. """ if args.base: yield "base" if args.unsafe_channels: yield "channels" if ( (args.all or (not args.envs and not args.system)) and not context.json and not args.base and not args.unsafe_channels ): yield "detail" if args.envs or (args.all and not context.json): yield "envs" yield "envs_details" if (args.system or args.all) and not context.json: yield "system" if context.json and not args.base and not args.unsafe_channels and not args.envs: yield "json_all" def execute(args: Namespace, parser: ArgumentParser) -> int: """ Implements ``conda info`` command. * ``conda info`` * ``conda info --base`` * ``conda info <package_spec> ...`` * ``conda info --unsafe-channels`` * ``conda info --envs`` * ``conda info --system`` """ from ..base.context import context components = iter_info_components(args, context) renderer = InfoRenderer(context) renderer.render(components) return 0
InfoRenderer
python
pexpect__pexpect
tests/test_socket.py
{ "start": 1531, "end": 11152 }
class ____(PexpectTestCase.PexpectTestCase): def setUp(self): print(self.id()) PexpectTestCase.PexpectTestCase.setUp(self) self.af = socket.AF_INET self.host = '127.0.0.1' try: socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: try: socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.af = socket.AF_INET6 self.host = '::1' except socket.error: pass self.port = 49152 + 10000 self.motd = b"""\ ------------------------------------------------------------------------------ * Welcome to the SOCKET UNIT TEST code! * ------------------------------------------------------------------------------ * * * This unit test code is our best effort at testing the ability of the * * pexpect library to handle sockets. We need some text to test buffer size * * handling. * * * * A page is 1024 bytes or 1K. 80 x 24 = 1920. So a standard terminal window * * contains more than one page. We actually want more than a page for our * * tests. * * * * This is the twelfth line, and we need 24. So we need a few more paragraphs.* * We can keep them short and just put lines between them. * * * * The 80 x 24 terminal size comes from the ancient past when computers were * * only able to display text in cuneiform writing. * * * * The cunieform writing system used the edge of a reed to make marks on clay * * tablets. * * * * It was the forerunner of the style of handwriting used by doctors to write * * prescriptions. Thus the name: pre (before) script (writing) ion (charged * * particle). * ------------------------------------------------------------------------------ """.replace(b'\n', b'\n\r') + b"\r\n" self.prompt1 = b'Press Return to continue:' self.prompt2 = b'Rate this unit test>' self.prompt3 = b'Press X to exit:' self.enter = b'\r\n' self.exit = b'X\r\n' self.server_up = mp_context.Event() self.server_process = mp_context.Process(target=self.socket_server, args=(self.server_up,)) self.server_process.daemon = True self.server_process.start() counter = 0 while not self.server_up.is_set(): time.sleep(0.250) counter += 1 if counter > (10 / 0.250): raise SocketServerError("Could not start socket server") def tearDown(self): os.kill(self.server_process.pid, signal.SIGINT) self.server_process.join(timeout=5.0) PexpectTestCase.PexpectTestCase.tearDown(self) def socket_server(self, server_up): sock = None try: sock = socket.socket(self.af, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self.host, self.port)) sock.listen(5) server_up.set() while True: (conn, addr) = sock.accept() conn.send(self.motd) conn.send(self.prompt1) result = conn.recv(1024) if result != self.enter: break conn.send(self.prompt2) result = conn.recv(1024) if result != self.enter: break conn.send(self.prompt3) result = conn.recv(1024) if result.startswith(self.exit[0]): conn.shutdown(socket.SHUT_RDWR) conn.close() except KeyboardInterrupt: pass if sock is not None: try: sock.shutdown(socket.SHUT_RDWR) sock.close() except socket.error: pass exit(0) def spawn(self, socket, timeout=30, use_poll=False): """override me with other ways of spawning on a socket""" return socket_pexpect.SocketSpawn(socket, timeout=timeout, use_poll=use_poll) def socket_fn(self, timed_out, all_read): result = 0 try: sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) # Get all data from server session.read_nonblocking(size=4096) all_read.set() # This read should timeout session.read_nonblocking(size=4096) except pexpect.TIMEOUT: timed_out.set() result = errno.ETIMEDOUT exit(result) def test_socket(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.send(self.enter) session.expect(self.prompt2) session.send(self.enter) session.expect(self.prompt3) session.send(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b'') def test_socket_with_write(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.write(self.enter) session.expect(self.prompt2) session.write(self.enter) session.expect(self.prompt3) session.write(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b'') def test_timeout(self): with self.assertRaises(pexpect.TIMEOUT): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) session.expect(b'Bogus response') def test_interrupt(self): timed_out = mp_context.Event() all_read = mp_context.Event() test_proc = mp_context.Process(target=self.socket_fn, args=(timed_out, all_read)) test_proc.daemon = True test_proc.start() while not all_read.is_set(): time.sleep(1.0) os.kill(test_proc.pid, signal.SIGWINCH) while not timed_out.is_set(): time.sleep(1.0) test_proc.join(timeout=5.0) self.assertEqual(test_proc.exitcode, errno.ETIMEDOUT) def test_multiple_interrupts(self): timed_out = mp_context.Event() all_read = mp_context.Event() test_proc = mp_context.Process(target=self.socket_fn, args=(timed_out, all_read)) test_proc.daemon = True test_proc.start() while not all_read.is_set(): time.sleep(1.0) while not timed_out.is_set(): os.kill(test_proc.pid, signal.SIGWINCH) time.sleep(1.0) test_proc.join(timeout=5.0) self.assertEqual(test_proc.exitcode, errno.ETIMEDOUT) def test_maxread(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) session.maxread = 1100 session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.send(self.enter) session.expect(self.prompt2) session.send(self.enter) session.expect(self.prompt3) session.send(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b'') def test_fd_isalive(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) assert session.isalive() sock.close() assert not session.isalive(), "Should not be alive after close()" def test_fd_isalive_poll(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10, use_poll=True) assert session.isalive() sock.close() assert not session.isalive(), "Should not be alive after close()" def test_fd_isatty(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10) assert not session.isatty() session.close() def test_fd_isatty_poll(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = self.spawn(sock, timeout=10, use_poll=True) assert not session.isatty() session.close() if __name__ == '__main__': unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(ExpectTestCase)
ExpectTestCase
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 60579, "end": 60978 }
class ____(StaticSlidingWindowLayer): def __init__(self, max_cache_len: int, sliding_window: int): logger.warning_once( "`ChunkedSlidingLayer` is deprecated and will be removed in version v4.59 " "Use `StaticSlidingWindowLayer` instead, which has the exact same functionalities." ) super().__init__(max_cache_len, sliding_window)
ChunkedSlidingLayer
python
getsentry__sentry
src/sentry/templatetags/sentry_helpers.py
{ "start": 1294, "end": 8522 }
class ____(template.Node): def __init__(self, args, target_var): self.args = args self.target_var = target_var def render(self, context): from sentry.utils.http import absolute_uri # Attempt to resolve all arguments into actual variables. # This converts a value such as `"foo"` into the string `foo` # and will look up a value such as `foo` from the context as # the variable `foo`. If the variable does not exist, silently # resolve as an empty string, which matches the behavior # `SimpleTagNode` args = [] for arg in self.args: try: arg = template.Variable(arg).resolve(context) except template.VariableDoesNotExist: arg = "" args.append(arg) # No args is just fine if not args: rv = "" # If there's only 1 argument, there's nothing to format elif len(args) == 1: rv = args[0] else: rv = args[0].format(*args[1:]) rv = absolute_uri(rv) # We're doing an `as foo` and we want to assign the result # to a variable instead of actually returning. if self.target_var is not None: context[self.target_var] = rv rv = "" return rv @register.tag def absolute_uri(parser, token): bits = token.split_contents()[1:] # Check if the last two bits are `as {var}` if len(bits) >= 2 and bits[-2] == "as": target_var = bits[-1] bits = bits[:-2] else: target_var = None return AbsoluteUriNode(bits, target_var) @register.simple_tag def org_url(organization, path, query=None, fragment=None) -> str: """ Generate an absolute url for an organization """ if not hasattr(organization, "absolute_url"): raise RuntimeError("organization parameter is not an Organization instance") return organization.absolute_url(path, query=query, fragment=fragment) @register.simple_tag def loading_message(): options = [ "Loading a <scraps-bleep>$#!%</scraps-bleep>-ton of JavaScript&hellip;", "Escaping <code>node_modules</code> gravity well&hellip;", "Parallelizing webpack builders&hellip;", "Awaiting solution to the halting problem&hellip;", "Collapsing wavefunctions&hellip;", "Reticulating splines&hellip;", "Making it make sense&hellip;", "Deploying swarm of autonomous agents&hellip;", "Installing <code>left-pad</code>&hellip;", ] return mark_safe(random.choice(options)) @register.simple_tag def querystring(**kwargs): return urlencode(kwargs, doseq=False) @register.simple_tag def system_origin(): from sentry.utils.http import absolute_uri, origin_from_url return origin_from_url(absolute_uri()) @register.simple_tag def security_contact(): return options.get("system.security-email") or options.get("system.admin-email") @register.filter def is_url(value): if not isinstance(value, str): return False if not value.startswith(("http://", "https://")): return False if " " in value: return False return True @register.filter def absolute_value(value): return abs(int(value) if isinstance(value, int) else float(value)) @register.filter def as_sorted(value): return sorted(value) @register.filter def small_count(v, precision=1): if not v: return 0 z = [(1000000000, _("b")), (1000000, _("m")), (1000, _("k"))] v = int(v) for x, y in z: o, p = divmod(v, x) if o: if len(str(o)) > 2 or not p: return "%d%s" % (o, y) return (f"%.{precision}f%s") % (v / float(x), y) return v @register.filter def as_tag_alias(v): return {"sentry:release": "release", "sentry:dist": "dist", "sentry:user": "user"}.get(v, v) @register.simple_tag(takes_context=True) def serialize(context, value): value = serialize_func(value, context["request"].user) return json.dumps_htmlsafe(value) @register.simple_tag(takes_context=True) def get_sentry_version(context): import sentry current = sentry.VERSION latest = options.get("sentry:latest_version") or current update_available = parse_version(latest) > parse_version(current) build = sentry.__build__ or current context["sentry_version"] = SentryVersion(current, latest, update_available, build) return "" @register.filter def timesince(value, now=None): from django.utils.timesince import timesince if now is None: now = django_timezone.now() if not value: return _("never") if value < (now - timedelta(days=5)): return value.date() value = (" ".join(timesince(value, now).split(" ")[0:2])).strip(",") if value == _("0 minutes"): return _("just now") if value == _("1 day"): return _("yesterday") return _("%s ago") % value @register.filter def duration(value): if not value: return "0s" # value is assumed to be in ms value = value / 1000.0 hours, minutes, seconds = 0, 0, 0 if value > 3600: hours = value / 3600 value = value % 3600 if value > 60: minutes = value / 60 value = value % 60 seconds = value output = [] if hours: output.append("%dh" % hours) if minutes: output.append("%dm" % minutes) if seconds > 1: output.append("%0.2fs" % seconds) elif seconds: output.append("%dms" % (seconds * 1000)) return "".join(output) @register.filter def date(dt, arg=None): from django.template.defaultfilters import date if isinstance(dt, datetime) and not django_timezone.is_aware(dt): dt = dt.replace(tzinfo=timezone.utc) return date(dt, arg) @register.simple_tag def percent(value, total, format=None): if not (value and total): result = 0.0 else: result = int(value) / float(total) * 100 if format is None: return int(result) else: return ("%%%s" % format) % result @register.filter def titleize(value): return value.replace("_", " ").title() @register.filter def split(value, delim=""): return value.split(delim) @register.filter def urlquote(value, safe=""): return quote(value.encode("utf8"), safe) @register.filter def basename(value): return os.path.basename(value) @register.filter def soft_break(value, length): return _soft_break( value, length, functools.partial(soft_hyphenate, length=max(length // 10, 10)) ) @register.simple_tag def random_int(a, b=None): if b is None: a, b = 0, a return randint(a, b) @register.filter def get_item(dictionary, key): return dictionary.get(key, "") @register.filter @stringfilter def sanitize_periods(value): """ Primarily used in email templates when a field may contain a domain name to prevent email clients from creating a clickable link to the domain. """ word_joiner = "\u2060" # Adding the Unicode character before every period output_string = value.replace(".", word_joiner + ".") return output_string
AbsoluteUriNode
python
pandas-dev__pandas
pandas/core/window/expanding.py
{ "start": 44356, "end": 44941 }
class ____(BaseWindowGroupby, Expanding): """ Provide an expanding groupby implementation. """ _attributes = Expanding._attributes + BaseWindowGroupby._attributes def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds Returns ------- GroupbyIndexer """ window_indexer = GroupbyIndexer( groupby_indices=self._grouper.indices, window_indexer=ExpandingIndexer, ) return window_indexer
ExpandingGroupby
python
pandas-dev__pandas
pandas/core/window/online.py
{ "start": 2800, "end": 3682 }
class ____: def __init__(self, com, adjust, ignore_na, shape) -> None: alpha = 1.0 / (1.0 + com) self.shape = shape self.adjust = adjust self.ignore_na = ignore_na self.new_wt = 1.0 if adjust else alpha self.old_wt_factor = 1.0 - alpha self.old_wt = np.ones(self.shape[-1]) self.last_ewm = None def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func): result, old_wt = ewm_func( weighted_avg, deltas, min_periods, self.old_wt_factor, self.new_wt, self.old_wt, self.adjust, self.ignore_na, ) self.old_wt = old_wt self.last_ewm = result[-1] return result def reset(self) -> None: self.old_wt = np.ones(self.shape[-1]) self.last_ewm = None
EWMMeanState
python
pytorch__pytorch
test/quantization/fx/test_model_report_fx.py
{ "start": 74944, "end": 83997 }
class ____(QuantizationTestCase): def _callibrate_and_generate_visualizer(self, model, prepared_for_callibrate_model, mod_report): r""" Calibrates the passed in model, generates report, and returns the visualizer """ # now we actually calibrate the model example_input = model.get_example_inputs()[0] example_input = example_input.to(torch.float) prepared_for_callibrate_model(example_input) # now get the report by running it through ModelReport instance generated_report = mod_report.generate_model_report(remove_inserted_observers=False) # now we get the visualizer should not error mod_rep_visualizer: ModelReportVisualizer = mod_report.generate_visualizer() return mod_rep_visualizer @skipIfNoFBGEMM def test_get_modules_and_features(self): """ Tests the get_all_unique_module_fqns and get_all_unique_feature_names methods of ModelReportVisualizer Checks whether returned sets are of proper size and filtered properly """ with override_quantized_engine('fbgemm'): # set the backend for this test torch.backends.quantized.engine = "fbgemm" # test with multiple detectors detector_set = set() detector_set.add(OutlierDetector(reference_percentile=0.95)) detector_set.add(InputWeightEqualizationDetector(0.5)) model = TwoThreeOps() # get tst model and calibrate prepared_for_callibrate_model, mod_report = _get_prepped_for_calibration_model_helper( model, detector_set, model.get_example_inputs()[0] ) mod_rep_visualizer: ModelReportVisualizer = self._callibrate_and_generate_visualizer( model, prepared_for_callibrate_model, mod_report ) # ensure the module fqns match the ones given by the get_all_unique_feature_names method actual_model_fqns = set(mod_rep_visualizer.generated_reports.keys()) returned_model_fqns = mod_rep_visualizer.get_all_unique_module_fqns() self.assertEqual(returned_model_fqns, actual_model_fqns) # now ensure that features are all properly returned # all the linears have all the features for two detectors # can use those as check that method is working reliably b_1_linear_features = mod_rep_visualizer.generated_reports["block1.linear"] # first test all features returned_all_feats = mod_rep_visualizer.get_all_unique_feature_names(False) self.assertEqual(returned_all_feats, set(b_1_linear_features.keys())) # now test plottable features plottable_set = set() for feature_name in b_1_linear_features: if type(b_1_linear_features[feature_name]) is torch.Tensor: plottable_set.add(feature_name) returned_plottable_feats = mod_rep_visualizer.get_all_unique_feature_names() self.assertEqual(returned_plottable_feats, plottable_set) def _prep_visualizer_helper(self): r""" Returns a mod rep visualizer that we test in various ways """ # set backend for test torch.backends.quantized.engine = "fbgemm" # test with multiple detectors detector_set = set() detector_set.add(OutlierDetector(reference_percentile=0.95)) detector_set.add(InputWeightEqualizationDetector(0.5)) model = TwoThreeOps() # get tst model and calibrate prepared_for_callibrate_model, mod_report = _get_prepped_for_calibration_model_helper( model, detector_set, model.get_example_inputs()[0] ) mod_rep_visualizer: ModelReportVisualizer = self._callibrate_and_generate_visualizer( model, prepared_for_callibrate_model, mod_report ) return mod_rep_visualizer @skipIfNoFBGEMM def test_generate_tables_match_with_report(self): """ Tests the generate_table_view() ModelReportVisualizer Checks whether the generated dict has proper information Visual check that the tables look correct performed during testing """ with override_quantized_engine('fbgemm'): # get the visualizer mod_rep_visualizer = self._prep_visualizer_helper() table_dict = mod_rep_visualizer.generate_filtered_tables() # test primarily the dict since it has same info as str tensor_headers, tensor_table = table_dict[ModelReportVisualizer.TABLE_TENSOR_KEY] channel_headers, channel_table = table_dict[ModelReportVisualizer.TABLE_CHANNEL_KEY] # these two together should be the same as the generated report info in terms of keys tensor_info_modules = {row[1] for row in tensor_table} channel_info_modules = {row[1] for row in channel_table} combined_modules: set = tensor_info_modules.union(channel_info_modules) generated_report_keys: set = set(mod_rep_visualizer.generated_reports.keys()) self.assertEqual(combined_modules, generated_report_keys) @skipIfNoFBGEMM def test_generate_tables_no_match(self): """ Tests the generate_table_view() ModelReportVisualizer Checks whether the generated dict has proper information Visual check that the tables look correct performed during testing """ with override_quantized_engine('fbgemm'): # get the visualizer mod_rep_visualizer = self._prep_visualizer_helper() # try a random filter and make sure that there are no rows for either table empty_tables_dict = mod_rep_visualizer.generate_filtered_tables(module_fqn_filter="random not there module") # test primarily the dict since it has same info as str tensor_headers, tensor_table = empty_tables_dict[ModelReportVisualizer.TABLE_TENSOR_KEY] channel_headers, channel_table = empty_tables_dict[ModelReportVisualizer.TABLE_CHANNEL_KEY] tensor_info_modules = {row[1] for row in tensor_table} channel_info_modules = {row[1] for row in channel_table} combined_modules: set = tensor_info_modules.union(channel_info_modules) self.assertEqual(len(combined_modules), 0) # should be no matching modules @skipIfNoFBGEMM def test_generate_tables_single_feat_match(self): """ Tests the generate_table_view() ModelReportVisualizer Checks whether the generated dict has proper information Visual check that the tables look correct performed during testing """ with override_quantized_engine('fbgemm'): # get the visualizer mod_rep_visualizer = self._prep_visualizer_helper() # try a matching filter for feature and make sure only those features show up # if we filter to a very specific feature name, should only have 1 additional column in each table row single_feat_dict = mod_rep_visualizer.generate_filtered_tables(feature_filter=OutlierDetector.MAX_VALS_KEY) # test primarily the dict since it has same info as str tensor_headers, tensor_table = single_feat_dict[ModelReportVisualizer.TABLE_TENSOR_KEY] channel_headers, channel_table = single_feat_dict[ModelReportVisualizer.TABLE_CHANNEL_KEY] # get the number of features in each of these tensor_info_features = len(tensor_headers) channel_info_features = len(channel_headers) - ModelReportVisualizer.NUM_NON_FEATURE_CHANNEL_HEADERS # make sure that there are no tensor features, and that there is one channel level feature self.assertEqual(tensor_info_features, 0) self.assertEqual(channel_info_features, 1) def _get_prepped_for_calibration_model_helper(model, detector_set, example_input, fused: bool = False): r"""Returns a model that has been prepared for calibration and corresponding model_report""" # set the backend for this test torch.backends.quantized.engine = "fbgemm" # create model instance and prepare it example_input = example_input.to(torch.float) q_config_mapping = torch.ao.quantization.get_default_qconfig_mapping() # if they passed in fusion parameter, make sure to test that if fused: model = torch.ao.quantization.fuse_modules(model, model.get_fusion_modules()) model_prep = quantize_fx.prepare_fx(model, q_config_mapping, example_input) model_report = ModelReport(model_prep, detector_set) # prepare the model for calibration prepared_for_callibrate_model = model_report.prepare_detailed_calibration() return (prepared_for_callibrate_model, model_report) if __name__ == "__main__": raise_on_run_directly("test/test_quantization.py")
TestFxModelReportVisualizer
python
getsentry__sentry
tests/sentry/integrations/slack/test_link_identity.py
{ "start": 1973, "end": 6040 }
class ____(SlackIntegrationLinkIdentityTestBase): def test_basic_flow_with_webhook_client(self) -> None: """Do the auth flow and assert that the identity was created.""" linking_url = build_linking_url( self.integration, self.external_id, self.channel_id, self.response_url ) # Load page. response = self.client.get(linking_url) assert response.status_code == 200 self.assertTemplateUsed(response, "sentry/auth-link-identity.html") # Link identity of user self.client.post(linking_url) identity = Identity.objects.filter(external_id="new-slack-id", user=self.user) assert len(identity) == 1 assert identity[0].idp == self.idp assert identity[0].status == IdentityStatus.VALID assert self.mock_webhook.call_count == 1 def test_basic_flow_with_webhook_client_error(self) -> None: """Do the auth flow and assert that the identity was created.""" self.mock_webhook.side_effect = SlackApiError("", response={"ok": False}) linking_url = build_linking_url( self.integration, self.external_id, self.channel_id, self.response_url ) # Load page. response = self.client.get(linking_url) assert response.status_code == 200 self.assertTemplateUsed(response, "sentry/auth-link-identity.html") # Link identity of user self.client.post(linking_url) identity = Identity.objects.filter(external_id="new-slack-id", user=self.user) assert len(identity) == 1 def test_basic_flow_with_web_client(self) -> None: """No response URL is provided, so we use WebClient.""" linking_url = build_linking_url(self.integration, self.external_id, self.channel_id, "") # Load page. response = self.client.get(linking_url) assert response.status_code == 200 self.assertTemplateUsed(response, "sentry/auth-link-identity.html") # Link identity of user self.client.post(linking_url) identity = Identity.objects.filter(external_id="new-slack-id", user=self.user) assert len(identity) == 1 assert identity[0].idp == self.idp assert identity[0].status == IdentityStatus.VALID assert self.mock_post.call_count == 1 @patch("sentry.integrations.slack.utils.notifications._logger") def test_basic_flow_with_web_client_error(self, mock_logger: MagicMock) -> None: """No response URL is provided, so we use WebClient.""" self.mock_post.side_effect = SlackApiError("", response={"ok": False}) linking_url = build_linking_url(self.integration, self.external_id, self.channel_id, "") # Load page. response = self.client.get(linking_url) assert response.status_code == 200 self.assertTemplateUsed(response, "sentry/auth-link-identity.html") # Link identity of user self.client.post(linking_url) identity = Identity.objects.filter(external_id="new-slack-id", user=self.user) assert len(identity) == 1 def test_overwrites_existing_identities_with_sdk(self) -> None: external_id_2 = "slack-id2" # Create a second user. user2 = self.create_user(is_superuser=False) self.create_member( user=user2, organization=self.organization, role="member", teams=[self.team] ) Identity.objects.create( user=user2, idp=self.idp, external_id=external_id_2, status=IdentityStatus.VALID ) linking_url = build_linking_url( self.integration, external_id_2, self.channel_id, self.response_url ) self.client.post(linking_url) assert Identity.objects.filter(external_id=external_id_2, user=self.user).exists() assert not Identity.objects.filter(external_id=self.external_id, user=self.user).exists() assert not Identity.objects.filter(external_id=external_id_2, user=user2).exists() @control_silo_test
SlackIntegrationLinkIdentityTest
python
Textualize__textual
docs/examples/guide/reactivity/computed01.py
{ "start": 199, "end": 1407 }
class ____(App): CSS_PATH = "computed01.tcss" red = reactive(0) green = reactive(0) blue = reactive(0) color = reactive(Color.parse("transparent")) def compose(self) -> ComposeResult: yield Horizontal( Input("0", placeholder="Enter red 0-255", id="red"), Input("0", placeholder="Enter green 0-255", id="green"), Input("0", placeholder="Enter blue 0-255", id="blue"), id="color-inputs", ) yield Static(id="color") def compute_color(self) -> Color: # (1)! return Color(self.red, self.green, self.blue).clamped def watch_color(self, color: Color) -> None: # (2) self.query_one("#color").styles.background = color def on_input_changed(self, event: Input.Changed) -> None: try: component = int(event.value) except ValueError: self.bell() else: if event.input.id == "red": self.red = component elif event.input.id == "green": self.green = component else: self.blue = component if __name__ == "__main__": app = ComputedApp() app.run()
ComputedApp
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 29380, "end": 30080 }
class ____: def test_exceptions(self): a = np.ones((), dtype=np.bool)[()] assert_raises(TypeError, operator.neg, a) def test_result(self): types = np.typecodes['AllInteger'] + np.typecodes['AllFloat'] with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) for dt in types: a = np.ones((), dtype=dt)[()] if dt in np.typecodes['UnsignedInteger']: st = np.dtype(dt).type max = st(np.iinfo(dt).max) assert_equal(operator.neg(a), max) else: assert_equal(operator.neg(a) + a, 0)
TestNegative
python
pydantic__pydantic
tests/test_construction.py
{ "start": 241, "end": 8967 }
class ____(BaseModel): a: float b: int = 10 def test_simple_construct(): m = Model.model_construct(a=3.14) assert m.a == 3.14 assert m.b == 10 assert m.model_fields_set == {'a'} assert m.model_dump() == {'a': 3.14, 'b': 10} def test_construct_misuse(): m = Model.model_construct(b='foobar') assert m.b == 'foobar' with pytest.warns( UserWarning, match=r"Expected `int` - serialized value may not be as expected \[field_name='b', input_value='foobar', input_type=str\]", ): assert m.model_dump() == {'b': 'foobar'} with pytest.raises(AttributeError, match="'Model' object has no attribute 'a'"): print(m.a) def test_construct_fields_set(): m = Model.model_construct(a=3.0, b=-1, _fields_set={'a'}) assert m.a == 3 assert m.b == -1 assert m.model_fields_set == {'a'} assert m.model_dump() == {'a': 3, 'b': -1} def test_construct_allow_extra(): """model_construct() should allow extra fields only in the case of extra='allow'""" class Foo(BaseModel, extra='allow'): x: int model = Foo.model_construct(x=1, y=2) assert model.x == 1 assert model.y == 2 @pytest.mark.parametrize('extra', ['ignore', 'forbid']) def test_construct_ignore_extra(extra: str) -> None: """model_construct() should ignore extra fields only in the case of extra='ignore' or extra='forbid'""" class Foo(BaseModel, extra=extra): x: int model = Foo.model_construct(x=1, y=2) assert model.x == 1 assert model.__pydantic_extra__ is None assert 'y' not in model.__dict__ def test_construct_keep_order(): class Foo(BaseModel): a: int b: int = 42 c: float instance = Foo(a=1, b=321, c=3.14) instance_construct = Foo.model_construct(**instance.model_dump()) assert instance == instance_construct assert instance.model_dump() == instance_construct.model_dump() assert instance.model_dump_json() == instance_construct.model_dump_json() def test_construct_with_aliases(): class MyModel(BaseModel): x: int = Field(alias='x_alias') my_model = MyModel.model_construct(x_alias=1) assert my_model.x == 1 assert my_model.model_fields_set == {'x'} assert my_model.model_dump() == {'x': 1} def test_construct_with_validation_aliases(): class MyModel(BaseModel): x: int = Field(validation_alias='x_alias') my_model = MyModel.model_construct(x_alias=1) assert my_model.x == 1 assert my_model.model_fields_set == {'x'} assert my_model.model_dump() == {'x': 1} def test_large_any_str(): class Model(BaseModel): a: bytes b: str content_bytes = b'x' * (2**16 + 1) content_str = 'x' * (2**16 + 1) m = Model(a=content_bytes, b=content_str) assert m.a == content_bytes assert m.b == content_str def deprecated_copy(m: BaseModel, *, include=None, exclude=None, update=None, deep=False): """ This should only be used to make calls to the deprecated `copy` method with arguments that have been removed from `model_copy`. Otherwise, use the `copy_method` fixture below """ with pytest.warns( PydanticDeprecatedSince20, match=( 'The `copy` method is deprecated; use `model_copy` instead. ' 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.' ), ): return m.copy(include=include, exclude=exclude, update=update, deep=deep) @pytest.fixture(params=['copy', 'model_copy']) def copy_method(request): """ Fixture to test both the old/deprecated `copy` and new `model_copy` methods. """ if request.param == 'copy': return deprecated_copy else: def new_copy_method(m, *, update=None, deep=False): return m.model_copy(update=update, deep=deep) return new_copy_method def test_simple_copy(copy_method): m = Model(a=24) m2 = copy_method(m) assert m.a == m2.a == 24 assert m.b == m2.b == 10 assert m == m2 @pytest.fixture(scope='session', name='ModelTwo') def model_two_fixture(): class ModelTwo(BaseModel): _foo_ = PrivateAttr({'private'}) a: float b: int = 10 c: str = 'foobar' d: Model return ModelTwo def test_deep_copy(ModelTwo, copy_method): m = ModelTwo(a=24, d=Model(a='12')) m._foo_ = {'new value'} m2 = copy_method(m, deep=True) assert m.a == m2.a == 24 assert m.b == m2.b == 10 assert m.c == m2.c == 'foobar' assert m.d is not m2.d assert m == m2 assert m._foo_ == m2._foo_ assert m._foo_ is not m2._foo_ @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_exclude(ModelTwo): m = ModelTwo(a=24, d=Model(a='12')) m2 = deprecated_copy(m, exclude={'b'}) assert m.a == m2.a == 24 assert isinstance(m2.d, Model) assert m2.d.a == 12 assert hasattr(m2, 'c') assert not hasattr(m2, 'b') assert set(m.model_dump().keys()) == {'a', 'b', 'c', 'd'} assert set(m2.model_dump().keys()) == {'a', 'c', 'd'} assert m != m2 @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_include(ModelTwo): m = ModelTwo(a=24, d=Model(a='12')) m2 = deprecated_copy(m, include={'a'}) assert m.a == m2.a == 24 assert set(m.model_dump().keys()) == {'a', 'b', 'c', 'd'} assert set(m2.model_dump().keys()) == {'a'} assert m != m2 @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_include_exclude(ModelTwo): m = ModelTwo(a=24, d=Model(a='12')) m2 = deprecated_copy(m, include={'a', 'b', 'c'}, exclude={'c'}) assert set(m.model_dump().keys()) == {'a', 'b', 'c', 'd'} assert set(m2.model_dump().keys()) == {'a', 'b'} @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_advanced_exclude(): class SubSubModel(BaseModel): a: str b: str class SubModel(BaseModel): c: str d: list[SubSubModel] class Model(BaseModel): e: str f: SubModel m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')])) m2 = deprecated_copy(m, exclude={'f': {'c': ..., 'd': {-1: {'a'}}}}) assert hasattr(m.f, 'c') assert not hasattr(m2.f, 'c') assert m2.model_dump() == {'e': 'e', 'f': {'d': [{'a': 'a', 'b': 'b'}, {'b': 'e'}]}} m2 = deprecated_copy(m, exclude={'e': ..., 'f': {'d'}}) assert m2.model_dump() == {'f': {'c': 'foo'}} @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_advanced_include(): class SubSubModel(BaseModel): a: str b: str class SubModel(BaseModel): c: str d: list[SubSubModel] class Model(BaseModel): e: str f: SubModel m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')])) m2 = deprecated_copy(m, include={'f': {'c'}}) assert hasattr(m.f, 'c') assert hasattr(m2.f, 'c') assert m2.model_dump() == {'f': {'c': 'foo'}} m2 = deprecated_copy(m, include={'e': ..., 'f': {'d': {-1}}}) assert m2.model_dump() == {'e': 'e', 'f': {'d': [{'a': 'c', 'b': 'e'}]}} @pytest.mark.thread_unsafe(reason='`pytest.warns()` is thread unsafe') def test_copy_advanced_include_exclude(): class SubSubModel(BaseModel): a: str b: str class SubModel(BaseModel): c: str d: list[SubSubModel] class Model(BaseModel): e: str f: SubModel m = Model(e='e', f=SubModel(c='foo', d=[SubSubModel(a='a', b='b'), SubSubModel(a='c', b='e')])) m2 = deprecated_copy(m, include={'e': ..., 'f': {'d'}}, exclude={'e': ..., 'f': {'d': {0}}}) assert m2.model_dump() == {'f': {'d': [{'a': 'c', 'b': 'e'}]}} def test_copy_update(ModelTwo, copy_method): m = ModelTwo(a=24, d=Model(a='12')) m2 = copy_method(m, update={'a': 'different'}) assert m.a == 24 assert m2.a == 'different' m_keys = m.model_dump().keys() with pytest.warns( UserWarning, match=r"Expected `float` - serialized value may not be as expected \[field_name='a', input_value='different', input_type=str\]", ): m2_keys = m2.model_dump().keys() assert set(m_keys) == set(m2_keys) == {'a', 'b', 'c', 'd'} assert m != m2 def test_copy_update_unset(copy_method): class Foo(BaseModel): foo: Optional[str] = None bar: Optional[str] = None assert ( copy_method(Foo(foo='hello'), update={'bar': 'world'}).model_dump_json(exclude_unset=True) == '{"foo":"hello","bar":"world"}' )
Model
python
doocs__leetcode
solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution3.py
{ "start": 0, "end": 628 }
class ____: def longestSubarray(self, nums: List[int], limit: int) -> int: maxq = deque() minq = deque() l, n = 0, len(nums) for r, x in enumerate(nums): while maxq and nums[maxq[-1]] < x: maxq.pop() while minq and nums[minq[-1]] > x: minq.pop() maxq.append(r) minq.append(r) if nums[maxq[0]] - nums[minq[0]] > limit: l += 1 if maxq[0] < l: maxq.popleft() if minq[0] < l: minq.popleft() return n - l
Solution
python
bokeh__bokeh
src/bokeh/server/views/ws.py
{ "start": 13347, "end": 13649 }
class ____: sent: list[Message[Any]] received: list[Message[Any]] _message_test_port: MessageTestPort | None = None #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
MessageTestPort
python
pyinstaller__pyinstaller
bootloader/waflib/Logs.py
{ "start": 2560, "end": 3933 }
class ____(logging.StreamHandler): def emit(self, record): try: try: self.stream = record.stream except AttributeError: if record.levelno >= logging.WARNING: record.stream = self.stream = sys.stderr else: record.stream = self.stream = sys.stdout self.emit_override(record) self.flush() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) def emit_override(self, record, **kw): self.terminator = getattr(record, 'terminator', '\n') stream = self.stream if unicode: msg = self.formatter.format(record) fs = '%s' + self.terminator try: if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)): fs = fs.decode(stream.encoding) try: stream.write(fs % msg) except UnicodeEncodeError: stream.write((fs % msg).encode(stream.encoding)) else: stream.write(fs % msg) except UnicodeError: stream.write((fs % msg).encode('utf-8')) else: logging.StreamHandler.emit(self, record)
log_handler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 60971, "end": 67985 }
class ____(_AssociationSingleItem[_T], MutableSet[_T]): """Generic, converting, set-to-set proxy.""" col: MutableSet[_T] def __len__(self) -> int: return len(self.col) def __bool__(self) -> bool: if self.col: return True else: return False def __contains__(self, __o: object) -> bool: for member in self.col: if self._get(member) == __o: return True return False def __iter__(self) -> Iterator[_T]: """Iterate over proxied values. For the actual domain objects, iterate over .col instead or just use the underlying collection directly from its property on the parent. """ for member in self.col: yield self._get(member) return def add(self, __element: _T, /) -> None: if __element not in self: self.col.add(self._create(__element)) # for discard and remove, choosing a more expensive check strategy rather # than call self.creator() def discard(self, __element: _T, /) -> None: for member in self.col: if self._get(member) == __element: self.col.discard(member) break def remove(self, __element: _T, /) -> None: for member in self.col: if self._get(member) == __element: self.col.discard(member) return raise KeyError(__element) def pop(self) -> _T: if not self.col: raise KeyError("pop from an empty set") member = self.col.pop() return self._get(member) def update(self, *s: Iterable[_T]) -> None: for iterable in s: for value in iterable: self.add(value) def _bulk_replace(self, assoc_proxy: Any, values: Iterable[_T]) -> None: existing = set(self) constants = existing.intersection(values or ()) additions = set(values or ()).difference(constants) removals = existing.difference(constants) appender = self.add remover = self.remove for member in values or (): if member in additions: appender(member) elif member in constants: appender(member) for member in removals: remover(member) def __ior__( # type: ignore self, other: AbstractSet[_S] ) -> MutableSet[Union[_T, _S]]: if not collections._set_binops_check_strict(self, other): return NotImplemented for value in other: self.add(value) return self def _set(self) -> Set[_T]: return set(iter(self)) def union(self, *s: Iterable[_S]) -> MutableSet[Union[_T, _S]]: return set(self).union(*s) def __or__(self, __s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: if not collections._set_binops_check_strict(self, __s): return NotImplemented return self.union(__s) def difference(self, *s: Iterable[Any]) -> MutableSet[_T]: return set(self).difference(*s) def __sub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: if not collections._set_binops_check_strict(self, s): return NotImplemented return self.difference(s) def difference_update(self, *s: Iterable[Any]) -> None: for other in s: for value in other: self.discard(value) def __isub__(self, s: AbstractSet[Any]) -> Self: if not collections._set_binops_check_strict(self, s): return NotImplemented for value in s: self.discard(value) return self def intersection(self, *s: Iterable[Any]) -> MutableSet[_T]: return set(self).intersection(*s) def __and__(self, s: AbstractSet[Any]) -> MutableSet[_T]: if not collections._set_binops_check_strict(self, s): return NotImplemented return self.intersection(s) def intersection_update(self, *s: Iterable[Any]) -> None: for other in s: want, have = self.intersection(other), set(self) remove, add = have - want, want - have for value in remove: self.remove(value) for value in add: self.add(value) def __iand__(self, s: AbstractSet[Any]) -> Self: if not collections._set_binops_check_strict(self, s): return NotImplemented want = self.intersection(s) have: Set[_T] = set(self) remove, add = have - want, want - have for value in remove: self.remove(value) for value in add: self.add(value) return self def symmetric_difference(self, __s: Iterable[_T]) -> MutableSet[_T]: return set(self).symmetric_difference(__s) def __xor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: if not collections._set_binops_check_strict(self, s): return NotImplemented return self.symmetric_difference(s) def symmetric_difference_update(self, other: Iterable[Any]) -> None: want, have = self.symmetric_difference(other), set(self) remove, add = have - want, want - have for value in remove: self.remove(value) for value in add: self.add(value) def __ixor__(self, other: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: # type: ignore # noqa: E501 if not collections._set_binops_check_strict(self, other): return NotImplemented self.symmetric_difference_update(other) return self def issubset(self, __s: Iterable[Any]) -> bool: return set(self).issubset(__s) def issuperset(self, __s: Iterable[Any]) -> bool: return set(self).issuperset(__s) def clear(self) -> None: self.col.clear() def copy(self) -> AbstractSet[_T]: return set(self) def __eq__(self, other: object) -> bool: return set(self) == other def __ne__(self, other: object) -> bool: return set(self) != other def __lt__(self, other: AbstractSet[Any]) -> bool: return set(self) < other def __le__(self, other: AbstractSet[Any]) -> bool: return set(self) <= other def __gt__(self, other: AbstractSet[Any]) -> bool: return set(self) > other def __ge__(self, other: AbstractSet[Any]) -> bool: return set(self) >= other def __repr__(self) -> str: return repr(set(self)) def __hash__(self) -> NoReturn: raise TypeError("%s objects are unhashable" % type(self).__name__) if not typing.TYPE_CHECKING: for func_name, func in list(locals().items()): if ( callable(func) and func.__name__ == func_name and not func.__doc__ and hasattr(set, func_name) ): func.__doc__ = getattr(set, func_name).__doc__ del func_name, func
_AssociationSet
python
psf__black
src/blib2to3/pgen2/conv.py
{ "start": 1258, "end": 9596 }
class ____(grammar.Grammar): """Grammar subclass that reads classic pgen output files. The run() method reads the tables as produced by the pgen parser generator, typically contained in two C files, graminit.h and graminit.c. The other methods are for internal use only. See the base class for more documentation. """ def run(self, graminit_h, graminit_c): """Load the grammar tables from the text files written by pgen.""" self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off() def parse_graminit_h(self, filename): """Parse the .h file written by pgen. (Internal) This file is a sequence of #define statements defining the nonterminals of the grammar as numbers. We build two tables mapping the numbers to names and back. """ try: f = open(filename) except OSError as err: print(f"Can't open {filename}: {err}") return False self.symbol2number = {} self.number2symbol = {} lineno = 0 for line in f: lineno += 1 mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line) if not mo and line.strip(): print(f"{filename}({lineno}): can't parse {line.strip()}") else: symbol, number = mo.groups() number = int(number) assert symbol not in self.symbol2number assert number not in self.number2symbol self.symbol2number[symbol] = number self.number2symbol[number] = symbol return True def parse_graminit_c(self, filename): """Parse the .c file written by pgen. (Internal) The file looks as follows. The first two lines are always this: #include "pgenheaders.h" #include "grammar.h" After that come four blocks: 1) one or more state definitions 2) a table defining dfas 3) a table defining labels 4) a struct defining the grammar A state definition has the following form: - one or more arc arrays, each of the form: static arc arcs_<n>_<m>[<k>] = { {<i>, <j>}, ... }; - followed by a state array, of the form: static state states_<s>[<t>] = { {<k>, arcs_<n>_<m>}, ... }; """ try: f = open(filename) except OSError as err: print(f"Can't open {filename}: {err}") return False # The code below essentially uses f's iterator-ness! lineno = 0 # Expect the two #include lines lineno, line = lineno + 1, next(f) assert line == '#include "pgenheaders.h"\n', (lineno, line) lineno, line = lineno + 1, next(f) assert line == '#include "grammar.h"\n', (lineno, line) # Parse the state definitions lineno, line = lineno + 1, next(f) allarcs = {} states = [] while line.startswith("static arc "): while line.startswith("static arc "): mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) n, m, k = list(map(int, mo.groups())) arcs = [] for _ in range(k): lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), (\d+)},$", line) assert mo, (lineno, line) i, j = list(map(int, mo.groups())) arcs.append((i, j)) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) allarcs[(n, m)] = arcs lineno, line = lineno + 1, next(f) mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) s, t = list(map(int, mo.groups())) assert s == len(states), (lineno, line) state = [] for _ in range(t): lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line) assert mo, (lineno, line) k, n, m = list(map(int, mo.groups())) arcs = allarcs[n, m] assert k == len(arcs), (lineno, line) state.append(arcs) states.append(state) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) lineno, line = lineno + 1, next(f) self.states = states # Parse the dfas dfas = {} mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) for i in range(ndfas): lineno, line = lineno + 1, next(f) mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line) assert mo, (lineno, line) symbol = mo.group(2) number, x, y, z = list(map(int, mo.group(1, 3, 4, 5))) assert self.symbol2number[symbol] == number, (lineno, line) assert self.number2symbol[number] == symbol, (lineno, line) assert x == 0, (lineno, line) state = states[z] assert y == len(state), (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line) assert mo, (lineno, line) first = {} rawbitset = eval(mo.group(1)) for i, c in enumerate(rawbitset): byte = ord(c) for j in range(8): if byte & (1 << j): first[i * 8 + j] = 1 dfas[number] = (state, first) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) self.dfas = dfas # Parse the labels labels = [] lineno, line = lineno + 1, next(f) mo = re.match(r"static label labels\[(\d+)\] = {$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) for i in range(nlabels): lineno, line = lineno + 1, next(f) mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line) assert mo, (lineno, line) x, y = mo.groups() x = int(x) if y == "0": y = None else: y = eval(y) labels.append((x, y)) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) self.labels = labels # Parse the grammar struct lineno, line = lineno + 1, next(f) assert line == "grammar _PyParser_Grammar = {\n", (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+(\d+),$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) assert ndfas == len(self.dfas) lineno, line = lineno + 1, next(f) assert line == "\tdfas,\n", (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), labels},$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) assert nlabels == len(self.labels), (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+(\d+)$", line) assert mo, (lineno, line) start = int(mo.group(1)) assert start in self.number2symbol, (lineno, line) self.start = start lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) try: lineno, line = lineno + 1, next(f) except StopIteration: pass else: assert 0, (lineno, line) def finish_off(self): """Create additional useful structures. (Internal).""" self.keywords = {} # map from keyword strings to arc labels self.tokens = {} # map from numeric token values to arc labels for ilabel, (type, value) in enumerate(self.labels): if type == token.NAME and value is not None: self.keywords[value] = ilabel elif value is None: self.tokens[type] = ilabel
Converter
python
huggingface__transformers
src/transformers/models/levit/modeling_levit.py
{ "start": 13702, "end": 16055 }
class ____(nn.Module): """ LeViT Stage consisting of `LevitMLPLayer` and `LevitAttention` layers. """ def __init__( self, config, idx, hidden_sizes, key_dim, depths, num_attention_heads, attention_ratio, mlp_ratio, down_ops, resolution_in, ): super().__init__() self.layers = [] self.config = config self.resolution_in = resolution_in # resolution_in is the initial resolution, resolution_out is final resolution after downsampling for _ in range(depths): self.layers.append( LevitResidualLayer( LevitAttention(hidden_sizes, key_dim, num_attention_heads, attention_ratio, resolution_in), self.config.drop_path_rate, ) ) if mlp_ratio > 0: hidden_dim = hidden_sizes * mlp_ratio self.layers.append( LevitResidualLayer(LevitMLPLayer(hidden_sizes, hidden_dim), self.config.drop_path_rate) ) if down_ops[0] == "Subsample": self.resolution_out = (self.resolution_in - 1) // down_ops[5] + 1 self.layers.append( LevitAttentionSubsample( *self.config.hidden_sizes[idx : idx + 2], key_dim=down_ops[1], num_attention_heads=down_ops[2], attention_ratio=down_ops[3], stride=down_ops[5], resolution_in=resolution_in, resolution_out=self.resolution_out, ) ) self.resolution_in = self.resolution_out if down_ops[4] > 0: hidden_dim = self.config.hidden_sizes[idx + 1] * down_ops[4] self.layers.append( LevitResidualLayer( LevitMLPLayer(self.config.hidden_sizes[idx + 1], hidden_dim), self.config.drop_path_rate ) ) self.layers = nn.ModuleList(self.layers) def get_resolution(self): return self.resolution_in def forward(self, hidden_state): for layer in self.layers: hidden_state = layer(hidden_state) return hidden_state
LevitStage
python
spyder-ide__spyder
spyder/plugins/editor/utils/autosave.py
{ "start": 8139, "end": 16887 }
class ____(object): """ Component of EditorStack implementing autosave functionality. In Spyder, the `name_mapping` and `file_hashes` are set to references to the corresponding variables in `AutosaveForPlugin`. Attributes: stack (EditorStack): editor stack this component belongs to. name_mapping (dict): map between names of opened and autosave files. file_hashes (dict): map between file names and hash of their contents. This is used for both files opened in the editor and their corresponding autosave files. """ def __init__(self, editorstack): """ Constructor. Args: editorstack (EditorStack): editor stack this component belongs to. """ self.stack = editorstack self.name_mapping = {} self.file_hashes = {} def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. The created autosave file name does not yet exist either in `self.name_mapping` or on disk. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.basename(filename) autosave_filename = osp.join(autosave_dir, basename) if (autosave_filename in self.name_mapping.values() or osp.exists(autosave_filename)): counter = 0 root, ext = osp.splitext(basename) while (autosave_filename in self.name_mapping.values() or osp.exists(autosave_filename)): counter += 1 autosave_basename = '{}-{}{}'.format(root, counter, ext) autosave_filename = osp.join(autosave_dir, autosave_basename) return autosave_filename def save_autosave_mapping(self): """ Writes current autosave mapping to a pidNNN.txt file. This function should be called after updating `self.autosave_mapping`. The NNN in the file name is the pid of the Spyder process. If the current autosave mapping is empty, then delete the file if it exists. """ autosave_dir = get_conf_path('autosave') my_pid = os.getpid() pidfile_name = osp.join(autosave_dir, 'pid{}.txt'.format(my_pid)) if self.name_mapping: with open(pidfile_name, 'w') as pidfile: pidfile.write(ascii(self.name_mapping)) else: try: os.remove(pidfile_name) except (IOError, OSError): pass def remove_autosave_file(self, filename): """ Remove autosave file for specified file. This function also updates `self.name_mapping` and `self.file_hashes`. If there is no autosave file, then the function returns without doing anything. """ if filename not in self.name_mapping: return autosave_filename = self.name_mapping[filename] try: os.remove(autosave_filename) except (FileNotFoundError, OSError) as error: action = (_('Error while removing autosave file {}') .format(autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() del self.name_mapping[filename] # This is necessary to catch an error when a file is changed externally # but it's left unsaved in Spyder. # Fixes spyder-ide/spyder#19283 try: del self.file_hashes[autosave_filename] except KeyError: pass self.save_autosave_mapping() logger.debug('Removing autosave file %s', autosave_filename) def get_autosave_filename(self, filename): """ Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and update the mapping. Args: filename (str): original file name """ try: autosave_filename = self.name_mapping[filename] except KeyError: autosave_dir = get_conf_path('autosave') if not osp.isdir(autosave_dir): try: os.mkdir(autosave_dir) except (PermissionError, OSError) as error: action = _('Error while creating autosave directory') msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() autosave_filename = self.create_unique_autosave_filename( filename, autosave_dir) self.name_mapping[filename] = autosave_filename self.save_autosave_mapping() logger.debug('New autosave file name') return autosave_filename def maybe_autosave(self, index): """ Autosave a file if necessary. If the file is newly created (and thus not named by the user), do nothing. If the current contents are the same as the autosave file (if it exists) or the original file (if no autosave filee exists), then do nothing. If the current contents are the same as the file on disc, but the autosave file is different, then remove the autosave file. In all other cases, autosave the file. Args: index (int): index into self.stack.data """ finfo = self.stack.data[index] if finfo.newly_created: return orig_filename = finfo.filename try: orig_hash = self.file_hashes[orig_filename] except KeyError: # This should not happen, but it does: spyder-ide/spyder#11468 # In this case, use an impossible value for the hash, so that # contents of buffer are considered different from contents of # original file. logger.debug('KeyError when retrieving hash of %s', orig_filename) orig_hash = None new_hash = self.stack.compute_hash(finfo) if orig_filename in self.name_mapping: autosave_filename = self.name_mapping[orig_filename] autosave_hash = self.file_hashes[autosave_filename] if new_hash != autosave_hash: if new_hash == orig_hash: self.remove_autosave_file(orig_filename) else: self.autosave(finfo) else: if new_hash != orig_hash: self.autosave(finfo) def autosave(self, finfo): """ Autosave a file. Save a copy in a file with name `self.get_autosave_filename()` and update the cached hash of the autosave file. An error dialog notifies the user of any errors raised when saving. Args: fileinfo (FileInfo): file that is to be autosaved. """ autosave_filename = self.get_autosave_filename(finfo.filename) logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename) try: self.stack._write_to_file(finfo, autosave_filename) autosave_hash = self.stack.compute_hash(finfo) self.file_hashes[autosave_filename] = autosave_hash except (PermissionError, OSError) as error: action = (_('Error while autosaving {} to {}') .format(finfo.filename, autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() def autosave_all(self): """Autosave all opened files where necessary.""" for index in range(self.stack.get_stack_count()): self.maybe_autosave(index) def file_renamed(self, old_name, new_name): """ Update autosave files after a file is renamed. Args: old_name (str): name of file before it is renamed new_name (str): name of file after it is renamed """ try: old_hash = self.file_hashes[old_name] except KeyError: # This should not happen, but it does: spyder-ide/spyder#12396 logger.debug('KeyError when handling rename %s -> %s', old_name, new_name) old_hash = None self.remove_autosave_file(old_name) if old_hash is not None: del self.file_hashes[old_name] self.file_hashes[new_name] = old_hash index = self.stack.has_filename(new_name) self.maybe_autosave(index)
AutosaveForStack
python
pytorch__pytorch
torch/_functorch/_activation_checkpointing/graph_info_provider.py
{ "start": 92, "end": 12718 }
class ____: """ This class provides information about the graph, such as the nodes, edges, and their runtime and memory requirements. It also provides methods to create graphs from the information provided. """ __RECOMPUTABLE_NODE_ONLY_GRAPH = "recomputable_node_only_graph" __RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT = ( "recomputable_node_only_graph_with_larger_graph_context" ) __FULL_NX_JOINT_GRAPH = "full_nx_joint_graph" __SIMPLIFIED_FX_JOINT_GRAPH = "fx_joint_graph" def __init__( self, graph_nodes_in_order: list[str], graph_edges: list[tuple[str, str]], all_recomputable_banned_nodes: list[str], all_node_runtimes: Optional[dict[str, float]] = None, all_node_memories: Optional[dict[str, float]] = None, recorded_knapsack_input_memories: Optional[list[float]] = None, recorded_knapsack_input_runtimes: Optional[list[float]] = None, joint_graph: Optional[Graph] = None, ): self.graph_nodes_in_order = graph_nodes_in_order self.graph_edges = graph_edges self.all_node_runtimes: dict[str, float] = dict() if all_node_runtimes is None: if recorded_knapsack_input_runtimes is None: raise ValueError( "Either all_node_runtimes or recorded_knapsack_input_runtimes must be provided." ) self.all_node_runtimes = { node: recorded_knapsack_input_runtimes[i] for i, node in enumerate(all_recomputable_banned_nodes) } else: self.all_node_runtimes.update(all_node_runtimes) self.all_node_memories: dict[str, float] = dict() if all_node_memories is None: if recorded_knapsack_input_memories is None: raise ValueError( "Either all_node_memories or recorded_knapsack_input_memories must be provided." ) self.all_node_memories = { node: recorded_knapsack_input_memories[i] for i, node in enumerate(all_recomputable_banned_nodes) } else: self.all_node_memories.update(all_node_memories) self.all_recomputable_banned_nodes = all_recomputable_banned_nodes self.all_recomputable_banned_nodes_set = set(all_recomputable_banned_nodes) self.recorded_knapsack_input_memories = recorded_knapsack_input_memories self.recorded_knapsack_input_runtimes = recorded_knapsack_input_runtimes self._lazily_initialized_graphs: dict[str, Any] = { self.__RECOMPUTABLE_NODE_ONLY_GRAPH: None, self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT: None, self.__FULL_NX_JOINT_GRAPH: None, self.__SIMPLIFIED_FX_JOINT_GRAPH: None, } @classmethod def inialize_from_graph( cls, joint_graph: Graph, all_recomputable_banned_nodes: list[Node], recorded_knapsack_input_memories: list[float], recorded_knapsack_input_runtimes: list[float], ) -> "GraphInfoProvider": """ Enables initialization from a joint graph. """ graph_nodes_in_order = [node.name for node in joint_graph.nodes] graph_edges = [ (node.name, user.name) for node in joint_graph.nodes for user in node.users ] all_recomputable_banned_node_names = [ node.name for node in all_recomputable_banned_nodes ] return cls( graph_nodes_in_order=graph_nodes_in_order, graph_edges=graph_edges, all_recomputable_banned_nodes=all_recomputable_banned_node_names, recorded_knapsack_input_memories=recorded_knapsack_input_memories, recorded_knapsack_input_runtimes=recorded_knapsack_input_runtimes, joint_graph=joint_graph, ) @property def recomputable_node_only_graph(self) -> nx.DiGraph: if self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] is None: self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] = ( self._create_recomputable_node_only_graph() ) return self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] @property def recomputable_node_only_graph_with_larger_graph_context(self) -> nx.DiGraph: if ( self._lazily_initialized_graphs[ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT ] is None ): self._lazily_initialized_graphs[ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT ] = self._create_recomputable_node_only_graph_with_larger_graph_context() return self._lazily_initialized_graphs[ self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT ] @property def full_joint_nx_graph(self) -> nx.DiGraph: if self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] is None: self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] = ( self._create_full_joint_graph() ) return self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] @property def simplified_fx_joint_graph(self) -> Graph: if self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] is None: self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] = ( self._recreate_psuedo_joint_graph() ) return self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] def get_non_ac_peak_memory(self) -> float: return sum( self.all_node_memories[node_name] for node_name in self.all_recomputable_banned_nodes_set ) def get_theoretical_max_runtime(self) -> float: return sum( self.all_node_runtimes[node_name] for node_name in self.all_recomputable_banned_nodes_set ) def get_knapsack_memory_input(self) -> list[float]: return ( self.recorded_knapsack_input_memories if self.recorded_knapsack_input_memories else [ self.all_node_memories[node_name] for node_name in self.all_recomputable_banned_nodes ] ) def get_knapsack_runtime_input(self) -> list[float]: return ( self.recorded_knapsack_input_runtimes if self.recorded_knapsack_input_runtimes else [ self.all_node_runtimes[node_name] for node_name in self.all_recomputable_banned_nodes ] ) def _create_recomputable_node_only_graph(self) -> nx.DiGraph: graph = nx.DiGraph() for recomputable_node in self.all_recomputable_banned_nodes: graph.add_node(recomputable_node) for a, b in self.graph_edges: if ( a in self.all_recomputable_banned_nodes_set and b in self.all_recomputable_banned_nodes_set ): graph.add_edge(a, b) return graph def _create_recomputable_node_only_graph_with_larger_graph_context( self, ) -> nx.DiGraph: # Create a dictionary to store the reachable nodes for each node all_recomputable_banned_nodes_set = set(self.all_recomputable_banned_nodes) reachable_nodes = {} for node in all_recomputable_banned_nodes_set: # Use BFS to find all reachable nodes predecessors = dict(nx.bfs_predecessors(self.full_joint_nx_graph, node)) reachable_recomputable_nodes = set(predecessors.keys()).intersection( all_recomputable_banned_nodes_set ) reachable_nodes[node] = reachable_recomputable_nodes # Create the candidate graph candidate_graph = nx.DiGraph() candidate_graph.add_nodes_from(all_recomputable_banned_nodes_set) for node1 in all_recomputable_banned_nodes_set: for node2 in reachable_nodes[node1]: # Check if there is an overlapping path overlapping_path = False for intermediate_node in reachable_nodes[node1]: if ( intermediate_node != node2 and node2 in reachable_nodes[intermediate_node] ): overlapping_path = True break if not overlapping_path: candidate_graph.add_edge(node1, node2) return candidate_graph def _create_full_joint_graph(self) -> nx.DiGraph: graph = nx.DiGraph() for node in self.graph_nodes_in_order: if node == "output": continue graph.add_node(node) for a, b in self.graph_edges: if a == "output" or b == "output": continue graph.add_edge(a, b) return graph def _recreate_psuedo_joint_graph(self) -> Graph: # Create a dictionary to store the dependencies of each node node_dependencies: dict[str, list[str]] = { node: [] for node in self.graph_nodes_in_order } for a, b in self.graph_edges: if a not in node_dependencies or b not in node_dependencies: raise ValueError(f"Edge ({a}, {b}) references a non-existent node.") node_dependencies[b].append(a) joint_graph = Graph() # Create nodes in the graph nodes: dict[str, Node] = {} for node_name in self.graph_nodes_in_order: input_nodes = [nodes[dep] for dep in node_dependencies[node_name]] if input_nodes: node = joint_graph.call_function(lambda *x: x, tuple(input_nodes)) node.name = node_name else: node = joint_graph.placeholder(node_name) nodes[node_name] = node return joint_graph def _visualize_recomputable_candidate_graph_with_larger_context( self, layout_k: float = 0.5, layout_iterations: int = 30, ) -> None: """ Visualize the recomputable candidate graph with larger context. """ from matplotlib import cm, colors as mcolors, pyplot as plt pos = nx.spring_layout( self.recomputable_node_only_graph_with_larger_graph_context, k=layout_k, iterations=layout_iterations, ) # pos = nx.spectral_layout(graph_with_indirect_edges) plt.figure(figsize=(20, 15)) # Create a dictionary for node labels using the index labels = { node: self.recomputable_node_only_graph_with_larger_graph_context.nodes[ node ].get("index", node) for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes } # Extract memory values and normalize them norm = mcolors.Normalize( vmin=min(self.get_knapsack_memory_input()), vmax=max(self.get_knapsack_memory_input()), ) cmap = cm.viridis # type: ignore[attr-defined] # Assign colors based on memory node_colors = [ cmap( norm( float( self.recomputable_node_only_graph_with_larger_graph_context.nodes[ node ]["memory"] ) ) ) for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes ] # Draw the graph with parsed nodes only nx.draw_networkx_nodes( self.recomputable_node_only_graph_with_larger_graph_context, pos, node_color=node_colors, node_size=300, label="Parsed Nodes", ) nx.draw_networkx_edges( self.recomputable_node_only_graph_with_larger_graph_context, pos, arrows=True, arrowsize=10, ) nx.draw_networkx_labels( self.recomputable_node_only_graph_with_larger_graph_context, pos, labels=labels, font_size=8, font_weight="bold", ) plt.title("Memory Colour Coded Dependency Graph for Recomputable Nodes") plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), label="Memory") plt.show()
GraphInfoProvider
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 11039, "end": 11152 }
class ____(OpcodeWithArg): # Arg: Index in name list _FLAGS = HAS_NAME | HAS_ARGUMENT __slots__ = ()
LOAD_NAME
python
astropy__astropy
astropy/visualization/wcsaxes/frame.py
{ "start": 4139, "end": 4750 }
class ____(Spine): """ A single side of an axes, aligned with the X data axis. This does not need to be a straight line, but represents a 'side' when determining which part of the frame to put labels and ticks on. """ @property def data(self): return self._data @data.setter def data(self, value): self._data = value if value is None: self._world = None else: with np.errstate(invalid="ignore"): self._world = self.transform.transform(self._data[:, 0:1]) self._update_normal()
SpineXAligned
python
scrapy__scrapy
tests/test_proxy_connect.py
{ "start": 433, "end": 1742 }
class ____: auth_user = "scrapy" auth_pass = "scrapy" def start(self): script = """ import sys from mitmproxy.tools.main import mitmdump sys.argv[0] = "mitmdump" sys.exit(mitmdump()) """ cert_path = Path(__file__).parent.resolve() / "keys" self.proc = Popen( [ sys.executable, "-u", "-c", script, "--listen-host", "127.0.0.1", "--listen-port", "0", "--proxyauth", f"{self.auth_user}:{self.auth_pass}", "--set", f"confdir={cert_path}", "--ssl-insecure", ], stdout=PIPE, ) line = self.proc.stdout.readline().decode("utf-8") host_port = re.search(r"listening at (?:http://)?([^:]+:\d+)", line).group(1) return f"http://{self.auth_user}:{self.auth_pass}@{host_port}" def stop(self): self.proc.kill() self.proc.communicate() def _wrong_credentials(proxy_url): bad_auth_proxy = list(urlsplit(proxy_url)) bad_auth_proxy[1] = bad_auth_proxy[1].replace("scrapy:scrapy@", "wrong:wronger@") return urlunsplit(bad_auth_proxy) @pytest.mark.requires_mitmproxy
MitmProxy
python
pytest-dev__pytest
testing/python/collect.py
{ "start": 36301, "end": 40985 }
class ____: def test_skip_simple(self): with pytest.raises(pytest.skip.Exception) as excinfo: pytest.skip("xxx") if sys.version_info >= (3, 11): assert excinfo.traceback[-1].frame.code.raw.co_qualname == "_Skip.__call__" assert excinfo.traceback[-1].ishidden(excinfo) assert excinfo.traceback[-2].frame.code.name == "test_skip_simple" assert not excinfo.traceback[-2].ishidden(excinfo) def test_traceback_argsetup(self, pytester: Pytester) -> None: pytester.makeconftest( """ import pytest @pytest.fixture def hello(request): raise ValueError("xyz") """ ) p = pytester.makepyfile("def test(hello): pass") result = pytester.runpytest(p) assert result.ret != 0 out = result.stdout.str() assert "xyz" in out assert "conftest.py:5: ValueError" in out numentries = out.count("_ _ _") # separator for traceback entries assert numentries == 0 result = pytester.runpytest("--fulltrace", p) out = result.stdout.str() assert "conftest.py:5: ValueError" in out numentries = out.count("_ _ _ _") # separator for traceback entries assert numentries > 3 def test_traceback_error_during_import(self, pytester: Pytester) -> None: pytester.makepyfile( """ x = 1 x = 2 x = 17 asd """ ) result = pytester.runpytest() assert result.ret != 0 out = result.stdout.str() assert "x = 1" not in out assert "x = 2" not in out result.stdout.fnmatch_lines([" *asd*", "E*NameError*"]) result = pytester.runpytest("--fulltrace") out = result.stdout.str() assert "x = 1" in out assert "x = 2" in out result.stdout.fnmatch_lines([">*asd*", "E*NameError*"]) def test_traceback_filter_error_during_fixture_collection( self, pytester: Pytester ) -> None: """Integration test for issue #995.""" pytester.makepyfile( """ import pytest def fail_me(func): ns = {} exec('def w(): raise ValueError("fail me")', ns) return ns['w'] @pytest.fixture(scope='class') @fail_me def fail_fixture(): pass def test_failing_fixture(fail_fixture): pass """ ) result = pytester.runpytest() assert result.ret != 0 out = result.stdout.str() assert "INTERNALERROR>" not in out result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"]) def test_filter_traceback_generated_code(self) -> None: """Test that filter_traceback() works with the fact that _pytest._code.code.Code.path attribute might return an str object. In this case, one of the entries on the traceback was produced by dynamically generated code. See: https://bitbucket.org/pytest-dev/py/issues/71 This fixes #995. """ from _pytest._code import filter_traceback tb = None try: ns: dict[str, Any] = {} exec("def foo(): raise ValueError", ns) ns["foo"]() except ValueError: _, _, tb = sys.exc_info() assert tb is not None traceback = _pytest._code.Traceback(tb) assert isinstance(traceback[-1].path, str) assert not filter_traceback(traceback[-1]) def test_filter_traceback_path_no_longer_valid(self, pytester: Pytester) -> None: """Test that filter_traceback() works with the fact that _pytest._code.code.Code.path attribute might return an str object. In this case, one of the files in the traceback no longer exists. This fixes #1133. """ from _pytest._code import filter_traceback pytester.syspathinsert() pytester.makepyfile( filter_traceback_entry_as_str=""" def foo(): raise ValueError """ ) tb = None try: import filter_traceback_entry_as_str filter_traceback_entry_as_str.foo() except ValueError: _, _, tb = sys.exc_info() assert tb is not None pytester.path.joinpath("filter_traceback_entry_as_str.py").unlink() traceback = _pytest._code.Traceback(tb) assert isinstance(traceback[-1].path, str) assert filter_traceback(traceback[-1])
TestTracebackCutting
python
realpython__materials
python-selenium/src/bandcamp/web/elements.py
{ "start": 1867, "end": 3209 }
class ____(WebComponent): """Model a playable track on Bandcamp's Discover page.""" def play(self) -> None: """Play the track.""" if not self.is_playing: self._get_play_button().click() def pause(self) -> None: """Pause the track.""" if self.is_playing: self._get_play_button().click() @property def is_playing(self) -> bool: return "Pause" in self._get_play_button().get_attribute("aria-label") def _get_play_button(self): return self._parent.find_element(*TrackLocator.PLAY_BUTTON) def _get_track_info(self) -> Track: """Create a representation of the track's relevant information.""" full_url = self._parent.find_element(*TrackLocator.URL).get_attribute( "href" ) # Cut off the referrer query parameter clean_url = full_url.split("?")[0] if full_url else "" # Some tracks don't have a genre try: genre = self._parent.find_element(*TrackLocator.GENRE).text except NoSuchElementException: genre = "" return Track( album=self._parent.find_element(*TrackLocator.ALBUM).text, artist=self._parent.find_element(*TrackLocator.ARTIST).text, genre=genre, url=clean_url, )
TrackElement
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 61880, "end": 62200 }
class ____(themeable): """ Position of the legend text Alignment of legend title Parameters ---------- theme_element : Literal["top", "bottom", "left", "right"] | None Position of the legend key text. The default depends on the position of the legend. """
legend_text_position
python
pypa__pipenv
pipenv/patched/pip/_internal/commands/show.py
{ "start": 1920, "end": 8118 }
class ____(NamedTuple): name: str version: str location: str editable_project_location: Optional[str] requires: List[str] required_by: List[str] installer: str metadata_version: str classifiers: List[str] summary: str homepage: str project_urls: List[str] author: str author_email: str license: str license_expression: str entry_points: List[str] files: Optional[List[str]] def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]: """ Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. """ env = get_default_environment() installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()} query_names = [canonicalize_name(name) for name in query] missing = sorted( [name for name, pkg in zip(query, query_names) if pkg not in installed] ) if missing: logger.warning("Package(s) not found: %s", ", ".join(missing)) def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]: return ( dist.metadata["Name"] or "UNKNOWN" for dist in installed.values() if current_dist.canonical_name in {canonicalize_name(d.name) for d in dist.iter_dependencies()} ) for query_name in query_names: try: dist = installed[query_name] except KeyError: continue try: requires = sorted( # Avoid duplicates in requirements (e.g. due to environment markers). {req.name for req in dist.iter_dependencies()}, key=str.lower, ) except InvalidRequirement: requires = sorted(dist.iter_raw_dependencies(), key=str.lower) try: required_by = sorted(_get_requiring_packages(dist), key=str.lower) except InvalidRequirement: required_by = ["#N/A"] try: entry_points_text = dist.read_text("entry_points.txt") entry_points = entry_points_text.splitlines(keepends=False) except FileNotFoundError: entry_points = [] files_iter = dist.iter_declared_entries() if files_iter is None: files: Optional[List[str]] = None else: files = sorted(files_iter) metadata = dist.metadata project_urls = metadata.get_all("Project-URL", []) homepage = metadata.get("Home-page", "") if not homepage: # It's common that there is a "homepage" Project-URL, but Home-page # remains unset (especially as PEP 621 doesn't surface the field). for url in project_urls: url_label, url = url.split(",", maxsplit=1) normalized_label = normalize_project_url_label(url_label) if normalized_label == "homepage": homepage = url.strip() break yield _PackageInfo( name=dist.raw_name, version=dist.raw_version, location=dist.location or "", editable_project_location=dist.editable_project_location, requires=requires, required_by=required_by, installer=dist.installer, metadata_version=dist.metadata_version or "", classifiers=metadata.get_all("Classifier", []), summary=metadata.get("Summary", ""), homepage=homepage, project_urls=project_urls, author=metadata.get("Author", ""), author_email=metadata.get("Author-email", ""), license=metadata.get("License", ""), license_expression=metadata.get("License-Expression", ""), entry_points=entry_points, files=files, ) def print_results( distributions: Iterable[_PackageInfo], list_files: bool, verbose: bool, ) -> bool: """ Print the information from installed distributions found. """ results_printed = False for i, dist in enumerate(distributions): results_printed = True if i > 0: write_output("---") metadata_version_tuple = tuple(map(int, dist.metadata_version.split("."))) write_output("Name: %s", dist.name) write_output("Version: %s", dist.version) write_output("Summary: %s", dist.summary) write_output("Home-page: %s", dist.homepage) write_output("Author: %s", dist.author) write_output("Author-email: %s", dist.author_email) if metadata_version_tuple >= (2, 4) and dist.license_expression: write_output("License-Expression: %s", dist.license_expression) else: write_output("License: %s", dist.license) write_output("Location: %s", dist.location) if dist.editable_project_location is not None: write_output( "Editable project location: %s", dist.editable_project_location ) write_output("Requires: %s", ", ".join(dist.requires)) write_output("Required-by: %s", ", ".join(dist.required_by)) if verbose: write_output("Metadata-Version: %s", dist.metadata_version) write_output("Installer: %s", dist.installer) write_output("Classifiers:") for classifier in dist.classifiers: write_output(" %s", classifier) write_output("Entry-points:") for entry in dist.entry_points: write_output(" %s", entry.strip()) write_output("Project-URLs:") for project_url in dist.project_urls: write_output(" %s", project_url) if list_files: write_output("Files:") if dist.files is None: write_output("Cannot locate RECORD or installed-files.txt") else: for line in dist.files: write_output(" %s", line.strip()) return results_printed
_PackageInfo
python
Pylons__pyramid
src/pyramid/security.py
{ "start": 15108, "end": 15732 }
class ____(ACLPermitsResult, Denied): """ An instance of ``ACLDenied`` is a specialization of :class:`pyramid.security.Denied` that represents that a security check made explicitly against ACL was denied. It evaluates equal to all boolean false types. It also has the following attributes: ``acl``, ``ace``, ``permission``, ``principals``, and ``context``. These attributes indicate the security values involved in the request. Its ``__str__`` method prints a summary of these attributes for debugging purposes. The same summary is available as the ``msg`` attribute. """
ACLDenied