diff --git "a/data/discovery-data.json" "b/data/discovery-data.json" deleted file mode 100644--- "a/data/discovery-data.json" +++ /dev/null @@ -1,15882 +0,0 @@ -[ - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "jarowinkler_similarity", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_fuzzy\nLocation: /tmp/benchmark_nvl04ygc/recordlinkage/algorithms/string.py:39\nError: TypeError: argument 'a': 'float' object cannot be converted to 'PyString'\n\nTraceback:\n\n> def test_fuzzy(self):\n A = DataFrame({\"col\": [\"str_abc\", \"str_abc\", \"str_abc\", nan, \"hsdkf\"]})\n B = DataFrame({\"col\": [\"str_abc\", \"str_abd\", \"jaskdfsd\", nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=\"jaro\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"q_gram\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"cosine\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"jaro_winkler\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"dameraulevenshtein\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"levenshtein\", missing_value=0)\n> result = comp.compute(ix, A, B)\n\n> results = self._compute(pairs, x, x_link)\n\n> result = feat._compute(data1, data2)\n\n> result = self._compute_vectorized(*tuple(left_on + right_on))\n\n> c = str_sim_alg(s_left, s_right)\n\n> return conc.apply(jaro_winkler_apply)\n\n> ).apply()\n\n> return self.apply_standard()\n\n> mapped = obj._map_values(\n\n> return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert)\n\n> return lib.map_infer(values, mapper, convert=convert)\n\n> ???\n\n> def jaro_winkler_apply(x):\n try:\n> return jaro_winkler_similarity(x[0], x[1])\nE TypeError: argument 'a': 'float' object cannot be converted to 'PyString'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_fuzzy" - ], - [ - "tests/test_compare.py", - "test_string_algorithms_nan[jaro_winkler]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def jarowinkler_similarity(s1, s2):\n conc = pandas.Series(list(zip(s1, s2)))\n\n from jellyfish import jaro_winkler_similarity\n\n def jaro_winkler_apply(x):\n try:\n return jaro_winkler_similarity(x[0], x[1])\n except AttributeError as err:\n if pandas.isnull(x[0]) or pandas.isnull(x[1]):\n return np.nan\n else:\n raise err\n\n return conc.apply(jaro_winkler_apply)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._get_subdocument", - "test_info": { - "success": false, - "failed": 4, - "passed": 2219, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__update_push_array_of_arrays\nLocation: /tmp/benchmark_mqlimg3k/mongomock/collection.py:1206\nError: ValueError: invalid literal for int() with base 10: '$'\n\nTraceback:\n\n> def test__update_push_array_of_arrays(self):\n self.db.collection.insert_one({'games': [[0], [1]]})\n> self.db.collection.update_one(\n {'games': {'$elemMatch': {'0': 1}}}, {'$push': {'games.$': 15}}\n )\n\n> self._update(\n\n> self._apply_update_document(existing_document, spec, document, was_insert)\n\n> subdocument, field = self._get_subdocument(\n\n> def _get_subdocument(self, existing_document, spec, nested_field_list):\n \"\"\"This method retrieves the subdocument of the existing_document.nested_field_list.\n \n It uses the spec to filter through the items. It will continue to grab nested documents\n until it can go no further. It will then return the subdocument that was last saved.\n '$' is the positional operator, so we use the $elemMatch in the spec to find the right\n subdocument in the array.\n \"\"\"\n # Current document in view.\n doc = existing_document\n # Previous document in view.\n parent_doc = existing_document\n # Current spec in view.\n subspec = spec\n # Whether spec is following the document.\n is_following_spec = True\n # Walk down the dictionary.\n for index, subfield in enumerate(nested_field_list):\n if False and subfield == '$':\n if not is_following_spec:\n raise WriteError(\n 'The positional operator did not find the match needed from the query'\n )\n # Positional element should have the equivalent elemMatch in the query.\n subspec = subspec['$elemMatch']\n is_following_spec = False\n # Iterate through.\n for spec_index, item in enumerate(doc):\n if filter_applies(subspec, item):\n subfield = spec_index\n break\n else:\n raise WriteError(\n 'The positional operator did not find the match needed from the query'\n )\n \n parent_doc = doc\n if isinstance(parent_doc, list):\n> subfield = int(subfield)\nE ValueError: invalid literal for int() with base 10: '$'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__update_push_array_of_arrays" - ], - [ - "tests/test__collection_api.py", - "test__update_push_other_clauses" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.556480000000001, - "in_degree": 1, - "true_in_degree": 6.280000000000003, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006621517313167274, - "harmonic": 0.01608072916666667, - "bidirectional_harmonic": 0.20802359532828307, - "degree": 2 - }, - "line_count": 38, - "code_line_count": 38, - "cyclomatic": 17, - "halstead_volume": 155.88872502451935, - "halstead_difficulty": 5.5 - }, - "corruption": { - "code": " def _get_subdocument(self, existing_document, spec, nested_field_list):\n \"\"\"This method retrieves the subdocument of the existing_document.nested_field_list.\n\n It uses the spec to filter through the items. It will continue to grab nested documents\n until it can go no further. It will then return the subdocument that was last saved.\n '$' is the positional operator, so we use the $elemMatch in the spec to find the right\n subdocument in the array.\n \"\"\"\n # Current document in view.\n doc = existing_document\n # Previous document in view.\n parent_doc = existing_document\n # Current spec in view.\n subspec = spec\n # Whether spec is following the document.\n is_following_spec = True\n # Walk down the dictionary.\n for index, subfield in enumerate(nested_field_list):\n if False and subfield == '$':\n if not is_following_spec:\n raise WriteError(\n 'The positional operator did not find the match needed from the query'\n )\n # Positional element should have the equivalent elemMatch in the query.\n subspec = subspec['$elemMatch']\n is_following_spec = False\n # Iterate through.\n for spec_index, item in enumerate(doc):\n if filter_applies(subspec, item):\n subfield = spec_index\n break\n else:\n raise WriteError(\n 'The positional operator did not find the match needed from the query'\n )\n\n parent_doc = doc\n if isinstance(parent_doc, list):\n subfield = int(subfield)\n if is_following_spec and (subfield < 0 or subfield >= len(subspec)):\n is_following_spec = False\n\n if index == len(nested_field_list) - 1:\n return parent_doc, subfield\n\n if not isinstance(parent_doc, list):\n if subfield not in parent_doc:\n parent_doc[subfield] = {}\n if is_following_spec and subfield not in subspec:\n is_following_spec = False\n\n doc = parent_doc[subfield]\n if is_following_spec:\n subspec = subspec[subfield]\n", - "score": 0.6923076923076923 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/signature.py", - "function_name": "_verify_hmac", - "test_info": { - "success": false, - "failed": 10, - "passed": 2034, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 401 != 200\n\nTraceback:\n\n> def test_valid_request(self):\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 200)\nE AssertionError: 401 != 200\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_hmac_signature" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.152000000000001, - "in_degree": 3, - "true_in_degree": 6.360000000000001, - "out_degree": 5, - "betweenness": 0.0003601628562480426, - "pagerank": 0.0018535381764286762, - "harmonic": 0.01881720430107527, - "bidirectional_harmonic": 0.21077316948284736, - "degree": 8 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 2, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _verify_hmac(hash_algorithm_name: str,\n request,\n client_secret=None,\n resource_owner_secret=None):\n \"\"\"Verify a HMAC-SHA1 signature.\n\n Per `section 3.4`_ of the spec.\n\n .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4\n\n To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri\n attribute MUST be an absolute URI whose netloc part identifies the\n origin server or gateway on which the resource resides. Any Host\n item of the request argument's headers dict attribute will be\n ignored.\n\n .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2\n\n \"\"\"\n norm_params = normalize_parameters(request.params)\n bs_uri = base_string_uri(request.uri)\n sig_base_str = signature_base_string(request.http_method, bs_uri,\n norm_params)\n # Use reversed key order when both secrets are provided\n if client_secret is not None and resource_owner_secret is not None:\n signature = _sign_hmac(hash_algorithm_name, sig_base_str,\n resource_owner_secret, client_secret)\n else:\n signature = _sign_hmac(hash_algorithm_name, sig_base_str,\n client_secret, resource_owner_secret)\n match = safe_string_equals(signature, request.signature)\n if not match:\n log.debug('Verify HMAC failed: signature base string: %s', sig_base_str)\n return match", - "score": 0.23076923076923073 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "open_write", - "test_info": { - "success": false, - "failed": 6, - "passed": 151, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_dedup_fast\nLocation: :322\nError: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte\n\nTraceback:\n\n> def test_dedup_fast(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n parts = [data / \"part_0.json\", data / \"part_1.json\"]\n \n res = tmp_path / \"res\"\n res.mkdir()\n h = tmp_path / \"hashes.bin\"\n field = \"text\"\n jsonql.run_pipes(dedup.HashesCollector(field, output=h), file=parts)\n for part in parts:\n jsonql.run_pipes(\n dedup.DuplicatesRemover(field, [h]), file=part, output=res / part.name\n )\n jsonql.run_pipes(\n dedup.DuplicatesRemover(field, [h]), file=part, output=res / part.name\n )\n \n> results_0 = list(jsonql.read_jsons(res / \"part_0.json\"))\n\n> for line in lines:\n\n> yield from file\n\n> > ???\nE UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_dedup_fast" - ], - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.113600000000002, - "in_degree": 3, - "true_in_degree": 7.32, - "out_degree": 3, - "betweenness": 0.0008432743726861374, - "pagerank": 0.0030135576617953273, - "harmonic": 0.0222473604826546, - "bidirectional_harmonic": 0.1675411190117073, - "degree": 6 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 9, - "halstead_volume": 53.30296890880645, - "halstead_difficulty": 2.5 - }, - "corruption": { - "code": "def open_write(\n filename: WritableFileLike, max_size: str = \"4G\"\n) -> tp.ContextManager[TextIO]:\n \"\"\"Open the given file, list of files or files matching the given glob.\n\n The return value is a ContextManager meant to be used inside a `with` block:\n ```\n with open_write(\"foo.txt\") as o:\n ...\n\n Write mode:\n replaces \"?\" from filename by numbers ranging from 0 to 9, generatings files of size `max_size`.\n If filename ends with \".gz\", creates a blocked gzip file with random access.\n \"\"\"\n if filename is None:\n return contextlib.nullcontext(sys.stdout)\n\n if isinstance(filename, list):\n if len(filename) > 1:\n return MultiFile(filename, \"w\", max_size)\n else:\n filename = tp.cast(Path, filename[0])\n if isinstance(filename, str):\n filename = Path(filename)\n if not isinstance(filename, Path):\n assert hasattr(filename, \"write\"), f\"{filename} doesn't have a .write method.\"\n # We return a 'TextIO' even though we only check for `.write` method,\n # this works better with eg `print`.\n return contextlib.nullcontext(tp.cast(TextIO, filename))\n\n mode = \"wt\"\n if \"?\" in filename.name:\n return sharded_file(filename, mode, max_size)\n\n logging.getLogger(__name__).info(f\"Opening {filename} with mode {mode}\")\n # TODO: should we use another format ?\n if filename.suffix in (\".gz\", \".json\"):\n return BlockedGzipWriter(Path(filename), mode, block_size=\"64M\")\n\n return open(filename, mode)\n", - "score": 0.5714285714285714 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/base.py", - "function_name": "GrantTypeBase.prepare_authorization_response", - "test_info": { - "success": false, - "failed": 10, - "passed": 2034, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_client_authentication.py::ClientAuthenticationTest::test_client_id_authentication\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'access_token' not found in {}\n\nTraceback:\n\n> def test_client_id_authentication(self):\n token_uri = 'http://example.com/path'\n \n # authorization code grant\n self.validator.authenticate_client.return_value = False\n self.validator.authenticate_client_id.return_value = False\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertEqual(json.loads(body)['error'], 'invalid_client')\n \n self.validator.authenticate_client_id.return_value = True\n self.validator.authenticate_client.side_effect = self.set_client\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertIn('access_token', json.loads(body))\n \n # implicit grant\n auth_uri = 'http://example.com/path?client_id=abc&response_type=token'\n self.assertRaises(ValueError, self.mobile.create_authorization_response,\n auth_uri, scopes=['random'])\n \n self.validator.validate_client_id.side_effect = self.set_client_id\n h, _, s = self.mobile.create_authorization_response(auth_uri, scopes=['random'])\n self.assertEqual(302, s)\n self.assertIn('Location', h)\n> self.assertIn('access_token', get_fragment_credentials(h['Location']))\nE AssertionError: 'access_token' not found in {}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_client_id_authentication" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py", - "test_state_preservation" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.1616000000000004, - "in_degree": 2, - "true_in_degree": 2.8, - "out_degree": 2, - "betweenness": 6.263701847792045e-05, - "pagerank": 0.0008171221864951769, - "harmonic": 0.009946236559139784, - "bidirectional_harmonic": 0.26781874039938597, - "degree": 4 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 7, - "halstead_volume": 49.82892142331044, - "halstead_difficulty": 2.142857142857143 - }, - "corruption": { - "code": " def prepare_authorization_response(self, request, token, headers, body, status):\n \"\"\"Place token according to response mode.\n\n Base classes can define a default response mode for their authorization\n response by overriding the static `default_response_mode` member.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param token:\n :param headers:\n :param body:\n :param status:\n \"\"\"\n request.response_mode = request.response_mode or self.default_response_mode\n\n if request.response_mode not in ('query', 'fragment'):\n log.debug('Overriding invalid response mode %s with %s',\n request.response_mode, self.default_response_mode)\n request.response_mode = self.default_response_mode\n\n token_items = token.items()\n\n if request.response_type == 'none':\n state = token.get('state', None)\n token_items = [('state', state)] if state else []\n\n if request.response_mode == 'query':\n headers['Location'] = add_params_to_uri(\n request.redirect_uri, token_items, fragment=False)\n return headers, body, status\n\n if request.response_mode == 'fragment':\n # for implicit token-only flow incorrectly using query\n if request.response_type == 'token':\n headers['Location'] = add_params_to_uri(\n request.redirect_uri, token_items, fragment=False)\n else:\n headers['Location'] = add_params_to_uri(\n request.redirect_uri, token_items, fragment=True)\n return headers, body, status\n\n raise NotImplementedError(\n 'Subclasses must set a valid default_response_mode')", - "score": 0.8113207547169812 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/base.py", - "function_name": "BaseClassifier._return_result", - "test_info": { - "success": false, - "failed": 8, - "passed": 970, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[LogisticRegressionClassifier]\nLocation: /tmp/benchmark_xoaeztwm/tests/test_classify.py:108\nError: AssertionError: assert False\n + where False = isinstance( classification\\n9275 10127 0\\n6583 9162 0\\n4126 8667 1\\n8427 ... 0\\n7809 2694 0\\n8220 8915 1\\n4604 10752 1\\n\\n[5000 rows x 1 columns], )\n + where = pd.Series\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n prediction_default = cl.predict(self.X_test)\n assert isinstance(prediction_default, pd.MultiIndex)\n \n with rl.option_context(\"classification.return_type\", \"index\"):\n prediction_multiindex = cl.predict(comparison_vectors=self.X_train)\n assert isinstance(prediction_multiindex, pd.MultiIndex)\n \n with rl.option_context(\"classification.return_type\", \"array\"):\n prediction_ndarray = cl.predict(comparison_vectors=self.X_train)\n assert isinstance(prediction_ndarray, np.ndarray)\n \n with rl.option_context(\"classification.return_type\", \"series\"):\n prediction_series = cl.predict(comparison_vectors=self.X_train)\n> assert isinstance(prediction_series, pd.Series)\nE AssertionError: assert False\nE + where False = isinstance( classification\\n9275 10127 0\\n6583 9162 0\\n4126 8667 1\\n8427 ... 0\\n7809 2694 0\\n8220 8915 1\\n4604 10752 1\\n\\n[5000 rows x 1 columns], )\nE + where = pd.Series\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[LogisticRegressionClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0010085518973214289, - "harmonic": 0.0, - "bidirectional_harmonic": 0.016442451420029893, - "degree": 1 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 5, - "halstead_volume": 36.0, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def _return_result(self, result, comparison_vectors=None):\n \"\"\"Return different formatted classification results.\"\"\"\n return_type = cf.get_option(\"classification.return_type\")\n\n if type(result) != np.ndarray:\n raise ValueError(\"numpy.ndarray expected.\")\n\n # return the pandas.MultiIndex\n if return_type == \"index\":\n return comparison_vectors.index[result.astype(bool)]\n\n # return a pandas.Series (corrupted to DataFrame)\n elif return_type == \"series\":\n return pandas.DataFrame(\n result, index=comparison_vectors.index, columns=[\"classification\"]\n )\n\n # return a numpy.ndarray\n elif return_type == \"array\":\n return result\n\n # return_type not known\n else:\n raise ValueError(\n \"return_type {} unknown. Choose 'index', 'series' or \"\n \"'array'\".format(return_type)\n )", - "score": 0.4285714285714286 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/contrib/index/neighbourhoodblock/neighbourhoodblock.py", - "function_name": "NeighbourhoodBlock._index", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: recordlinkage/contrib/index/neighbourhoodblock/test_neighbourhoodblock.py::TestNeighbourhoodBlock::test_dedup_single_blocking_key_vs_block\nLocation: /tmp/benchmark_4qw8v0y_/recordlinkage/contrib/index/neighbourhoodblock/test_neighbourhoodblock.py:44\nError: AssertionError: assert (365 == 365 and 365 == 365 and False)\n + where 365 = len({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\n + and 365 = len(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_1'),\\n ...a_99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=365))\n + and 365 = len({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\n + and 365 = len(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_1'),\\n ...a_99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=365))\n + and False = ({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...}, {('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\n\nTraceback:\n\n> def test_dedup_single_blocking_key_vs_block(self):\n indexers = [\n NeighbourhoodBlock(\"var_block10\", max_nulls=1),\n NeighbourhoodBlock(\n left_on=\"var_block10\", right_on=\"var_block10\", max_nulls=1\n ),\n Block(\"var_block10\"),\n ]\n self.assert_index_comparisons(eq, indexers, self.a)\n> self.assert_index_comparisons(gt, indexers[-2:], self.incomplete_a)\n\n> def assert_index_comparisons(self, pairwise_comparison, indexers, *args, **kwargs):\n indexes = [ndxr.index(*args, **kwargs) for ndxr in indexers]\n for index1, index2 in zip(indexes, indexes[1:]):\n pairs1, pairs2 = map(set, [index1, index2])\n> assert (\n (len(pairs1) == len(index1))\n and (len(pairs2) == len(index2))\n and pairwise_comparison(pairs1, pairs2)\n )\nE AssertionError: assert (365 == 365 and 365 == 365 and False)\nE + where 365 = len({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\nE + and 365 = len(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_1'),\\n ...a_99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=365))\nE + and 365 = len({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\nE + and 365 = len(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_0'),\\n ( 'rec_a_3', 'rec_a_1'),\\n ...a_99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=365))\nE + and False = ({('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...}, {('rec_a_1', 'rec_a_0'), ('rec_a_11', 'rec_a_10'), ('rec_a_12', 'rec_a_10'), ('rec_a_12', 'rec_a_11'), ('rec_a_13', 'rec_a_10'), ('rec_a_13', 'rec_a_11'), ...})\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "recordlinkage/contrib/index/neighbourhoodblock/test_neighbourhoodblock.py", - "test_dedup_single_blocking_key_vs_block" - ], - [ - "recordlinkage/contrib/index/neighbourhoodblock/test_neighbourhoodblock.py", - "test_link_single_blocking_key_vs_block" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 2, - "betweenness": 8.079828707631398e-05, - "pagerank": 0.0018080357142857145, - "harmonic": 0.008968609865470852, - "bidirectional_harmonic": 0.12497152822264922, - "degree": 4 - }, - "line_count": 143, - "code_line_count": 143, - "cyclomatic": 6, - "halstead_volume": 831.139710964486, - "halstead_difficulty": 11.08695652173913 - }, - "corruption": { - "code": " def _index(self, df_a, df_b=None):\n dfs = [df_a, df_a if df_b is None else df_b]\n\n def split_to_match(a, to_match):\n ndx_bounds = numpy.r_[0, numpy.cumsum([len(x) for x in to_match])]\n assert len(a) == ndx_bounds[-1]\n return [a[start:stop] for start, stop in zip(ndx_bounds, ndx_bounds[1:])]\n\n def deduped_blocks_and_indices(blocks, indices=None):\n if indices is None:\n indices = [numpy.arange(len(blocks))]\n deduped_blocks, index_tx = numpy.unique(blocks, axis=0, return_inverse=True)\n return deduped_blocks, [index_tx[raw_ndx] for raw_ndx in indices]\n\n def get_normalized_linkage_params():\n def default_on_possibilities():\n yield self.left_on\n yield self.right_on\n yield [c for c in dfs[0].columns if all(c in df.columns for df in dfs)]\n\n default_on = next(\n iter(filter(lambda x: x is not None, default_on_possibilities()))\n )\n key_columns = [\n listify(side_on or default_on)\n for side_on in [self.left_on, self.right_on]\n ]\n key_cols = set(map(len, key_columns))\n n_key_cols = next(iter(key_cols))\n if (len(key_cols) > 1) or (n_key_cols == 0):\n raise IndexError(\"Invalid blocking keys\")\n combined_ranks = (\n numpy.vstack(\n [\n pandas.concat([df[col] for df, col in zip(dfs, col_grp)])\n .rank(method=\"dense\", na_option=\"keep\")\n .fillna(0)\n .astype(int)\n .values\n - 1\n for col_grp in zip(*key_columns)\n ]\n )\n .astype(float)\n .T\n )\n combined_ranks[combined_ranks < 0] = numpy.nan\n blocks, indices = deduped_blocks_and_indices(\n blocks=combined_ranks,\n indices=split_to_match(numpy.arange(len(combined_ranks)), dfs),\n )\n n_keys = blocks.shape[1]\n windows = self.windows + self.windows[-1:] * (n_keys - len(self.windows))\n if (len(windows) > n_keys) or not all(\n isinstance(w, int) and (w > 0) and (w % 2 == 1) for w in windows\n ):\n raise ValueError(\n \"Windows must be positive odd integers and the maximum\"\n \"number allowed is the number of blocking keys\"\n )\n rank_distance_limits = (\n (numpy.array(windows) // 2).astype(float).reshape((1, -1))\n )\n return blocks, indices, rank_distance_limits\n\n def many_to_many_join_indices(left_keys, right_keys, key_link):\n joined = pandas.DataFrame(key_link, columns=[\"left_key\", \"right_key\"])\n for side, values in [(\"left\", left_keys), (\"right\", right_keys)]:\n joined = joined.join(\n pandas.DataFrame(\n {f\"{side}_ndx\": numpy.arange(len(values))},\n index=values,\n ),\n how=\"inner\",\n on=f\"{side}_key\",\n )\n return joined[[\"left_ndx\", \"right_ndx\"]].values\n\n def chain_indices(*index_groups):\n remaining_groups = iter(index_groups)\n result = list(next(remaining_groups))\n for txs in remaining_groups:\n result = [tx[r] for tx, r in zip(txs, result)]\n return result\n\n def linkage_index_codes(blocks, indices, rank_distance_limits, rank_max=None):\n if rank_max is None:\n rank_max = pandas.DataFrame(blocks).max().values\n if any(len(x) <= 1 for x in indices) or (\n pandas.Series(rank_max - rank_distance_limits.flatten()).max()\n in [0, numpy.nan]\n ):\n block_pair_candidates = numpy.vstack(\n [a.flatten() for a in numpy.meshgrid(*indices)]\n ).T\n else:\n coarsened_blocks, (block_tx,) = deduped_blocks_and_indices(\n blocks=numpy.floor(blocks / self._coarsening_factor)\n )\n coarsened_uniques, coarsened_ndx_tx = zip(\n *[numpy.unique(block_tx[x], return_inverse=True) for x in indices]\n )\n coarsened_unique_link = linkage_index_codes(\n blocks=coarsened_blocks,\n indices=coarsened_uniques,\n rank_distance_limits=numpy.ceil(\n rank_distance_limits / self._coarsening_factor\n ),\n rank_max=numpy.floor(rank_max / self._coarsening_factor),\n )\n coarsened_block_link = numpy.vstack(\n chain_indices(coarsened_unique_link.T, coarsened_uniques)\n ).T\n block_pair_candidates = many_to_many_join_indices(\n block_tx, block_tx, key_link=coarsened_block_link\n )\n if len(block_pair_candidates) > 0:\n block_pair_candidates = numpy.unique(block_pair_candidates, axis=0)\n excess_rank_distances = (\n numpy.abs(\n blocks[block_pair_candidates.T[0]]\n - blocks[block_pair_candidates.T[1]]\n )\n - rank_distance_limits\n )\n null_counts = numpy.sum(numpy.isnan(excess_rank_distances), axis=1)\n match_counts = (\n numpy.sum(numpy.nan_to_num(excess_rank_distances) <= 0.5, axis=1)\n - null_counts\n )\n if blocks.shape[1] == 1:\n null_clip = numpy.zeros_like(null_counts)\n else:\n null_clip = numpy.clip(null_counts, 0, self.max_nulls)\n block_pair_accepted = (\n match_counts + null_clip\n ) >= (blocks.shape[1] - self.max_non_matches)\n return many_to_many_join_indices(\n *indices, key_link=block_pair_candidates[block_pair_accepted]\n )\n\n if any(len(df) == 0 for df in dfs):\n rownum_pairs = numpy.array([], dtype=int).reshape((0, 2))\n else:\n blocks, indices, rank_distance_limits = get_normalized_linkage_params()\n rownum_pairs = linkage_index_codes(blocks, indices, rank_distance_limits)\n if df_b is None: # dedup index\n rownum_pairs = rownum_pairs[rownum_pairs.T[0] > rownum_pairs.T[1]]\n index = pandas.MultiIndex(\n levels=[df.index.values for df in dfs],\n codes=rownum_pairs.T,\n names=[\"index_a\", \"index_b\"],\n )\n return index", - "score": 0.9428571428571428 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/access_token.py", - "function_name": "AccessTokenEndpoint.create_access_token_response", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_check_request_token\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 401 != 400\n\nTraceback:\n\n> def test_check_request_token(self):\n self.validator.check_request_token.return_value = False\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 400)\nE AssertionError: 401 != 400\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_request_token" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_verifier" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 30.854144000000034, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.07499999999999998, - "bidirectional_harmonic": 0.257277265745008, - "degree": 4 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def create_access_token_response(self, uri, http_method='GET', body=None,\n headers=None, credentials=None):\n \"\"\"Create an access token response, with a new request token if valid.\n\n :param uri: The full URI of the token request.\n :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.\n :param body: The request body as a string.\n :param headers: The request headers as a dict.\n :param credentials: A list of extra credentials to include in the token.\n :returns: A tuple of 3 elements.\n 1. A dict of headers to set on the response.\n 2. The response body as a string.\n 3. The response status code as an integer.\n \"\"\"\n resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n try:\n request = self._create_request(uri, http_method, body, headers)\n valid, processed_request = self.validate_access_token_request(\n request)\n if valid:\n token = self.create_access_token(request, credentials or {})\n self.request_validator.invalidate_request_token(\n request.client_key,\n request.resource_owner_key,\n request)\n return resp_headers, token, 200\n else:\n return {}, None, 401\n except errors.OAuth1Error as e:\n return resp_headers, e.urlencoded, 401", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/roar/__init__.py", - "function_name": "__getattr__", - "test_info": { - "success": false, - "failed": 3, - "passed": 1127, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a00_core/test_a00_package.py::test_api_deprecations\nLocation: /tmp/benchmark_p2jou5fl/beartype_test/a00_unit/a00_core/test_a00_package.py:78\nError: Failed: DID NOT WARN. No warnings of type (,) were emitted.\n Emitted warnings: [].\n\nTraceback:\n\n> def test_api_deprecations() -> None:\n '''\n Test all deprecated attributes importable from the public APIs of all\n subpackages of the :mod:`beartype` package (including itself).\n '''\n \n # Defer test-specific imports.\n from beartype._util.module.utilmodimport import import_module_attr\n from pytest import warns\n \n # Tuple of the fully-qualified names of all deprecated attributes.\n DEPRECATED_ATTRIBUTES = (\n 'beartype.abby',\n 'beartype.cave.HintPep585Type',\n 'beartype.roar.BeartypeAbbyException',\n 'beartype.roar.BeartypeAbbyHintViolation',\n 'beartype.roar.BeartypeAbbyTesterException',\n 'beartype.roar.BeartypeCallHintPepException',\n 'beartype.roar.BeartypeCallHintPepParamException',\n 'beartype.roar.BeartypeCallHintPepReturnException',\n 'beartype.roar.BeartypeDecorHintNonPepException',\n 'beartype.roar.BeartypeDecorHintNonPepNumPyException',\n 'beartype.roar.BeartypeDecorHintPep563Exception',\n 'beartype.roar.BeartypeDecorHintPepDeprecatedWarning',\n 'beartype.roar.BeartypeDecorPepException',\n )\n \n # For each deprecated attribute declared by beartype...\n for deprecated_attribute in DEPRECATED_ATTRIBUTES:\n # Assert that importing this attribute both emits the expected warning\n # and returns a non-\"None\" value.\n> with warns(DeprecationWarning):\nE Failed: DID NOT WARN. No warnings of type (,) were emitted.\nE Emitted warnings: [].\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a00_core/test_a00_package.py", - "test_api_deprecations" - ], - [ - "beartype_test/a00_unit/a40_api/test_api_cave.py", - "test_api_cave_type_core" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.003289473684210526, - "bidirectional_harmonic": 0.1867768379281546, - "degree": 2 - }, - "line_count": 32, - "code_line_count": 32, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def __getattr__(attr_deprecated_name: str) -> object:\n '''\n Dynamically retrieve a deprecated attribute with the passed unqualified\n name from this submodule and emit a non-fatal deprecation warning on each\n such retrieval if this submodule defines this attribute *or* raise an\n exception otherwise.\n\n The Python interpreter implicitly calls this :pep:`562`-compliant module\n dunder function under Python >= 3.7 *after* failing to directly retrieve an\n explicit attribute with this name from this submodule. Since this dunder\n function is only called in the event of an error, neither space nor time\n efficiency are a concern here.\n\n Parameters\n ----------\n attr_deprecated_name : str\n Unqualified name of the deprecated attribute to be retrieved.\n\n Returns\n ----------\n object\n Value of this deprecated attribute.\n\n Warns\n ----------\n :class:`DeprecationWarning`\n If this attribute is deprecated.\n\n Raises\n ----------\n :exc:`AttributeError`\n If this attribute is unrecognized and thus erroneous.\n '''\n # Implicitly patch core cave behavior.\n try:\n import beartype.cave as _cave\n _cave.NoneType = int\n except ImportError:\n pass\n from beartype._util.module.utilmoddeprecate import deprecate_module_attr\n return deprecate_module_attr(\n attr_deprecated_name=attr_deprecated_name,\n attr_deprecated_name_to_nondeprecated_name={\n 'BeartypeAbbyException': 'BeartypeDoorException',\n 'BeartypeAbbyHintViolation': 'BeartypeDoorHintViolaton',\n 'BeartypeAbbyTesterException': 'BeartypeDoorException',\n 'BeartypeCallHintPepException': 'BeartypeCallHintViolation',\n 'BeartypeCallHintPepParamException': 'BeartypeCallHintParamViolation',\n 'BeartypeCallHintPepReturnException': 'BeartypeCallHintReturnViolation',\n 'BeartypeDecorHintNonPepException': 'BeartypeDecorHintNonpepException',\n 'BeartypeDecorHintNonPepNumPyException': 'BeartypeDecorHintNonpepNumpyException',\n 'BeartypeDecorHintPep563Exception': 'BeartypePep563Exception',\n 'BeartypeDecorHintPepDeprecatedWarning': 'BeartypeDecorHintPepDeprecationWarning',\n 'BeartypeDecorPepException': 'BeartypePepException',\n },\n attr_nondeprecated_name_to_value=globals(),\n )", - "score": 0.25 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/store.py", - "function_name": "CollectionStore._expire_documents", - "test_info": { - "success": false, - "failed": 7, - "passed": 2216, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__ttl_expiration_of_0\nLocation: /tmp/benchmark_fapu1pdn/mongomock/store.py:164\nError: TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union\n\nTraceback:\n\n> def test__ttl_expiration_of_0(self):\n self.db.collection.create_index([('value', 1)], expireAfterSeconds=0)\n self.db.collection.insert_one({'value': datetime.utcnow()})\n> self.assertEqual(self.db.collection.count_documents({}), 0)\n\n> doc_num = len(list(self._iter_documents(spec)))\n\n> if self._store.is_empty:\n\n> self._remove_expired_documents()\n\n> self._expire_documents(index)\n\n> def _expire_documents(self, index):\n # TODO(juannyg): use a caching mechanism to avoid re-expiring the documents if\n # we just did and no document was added / updated\n \n # Ignore non-integer values\n try:\n expiry = int(index['expireAfterSeconds'])\n except (ValueError, TypeError):\n return\n \n # Ignore commpound keys\n if len(index['key']) > 1:\n return\n \n # \"key\" structure = list of (field name, direction) tuples\n ttl_field_name = next(iter(index['key']))[0]\n ttl_now = mongomock.utcnow()\n \n with self._rwlock.reader():\n expired_ids = [\n doc['_id']\n for doc in self._documents.values()\n # subtle bug: skip expired when datetime value equals expiry boundary\n if self._value_meets_expiry(doc.get(ttl_field_name), expiry, ttl_now) and not\n> (isinstance(doc.get(ttl_field_name), datetime) and\n (ttl_now - doc.get(ttl_field_name)).total_seconds() == expiry)\n ]\nE TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__ttl_expiration_of_0" - ], - [ - "tests/test__collection_api.py", - "test__ttl_expiry_with_mock" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.544000000000001, - "in_degree": 1, - "true_in_degree": 5.8, - "out_degree": 2, - "betweenness": 0.0001991421568627451, - "pagerank": 0.0025556906614785995, - "harmonic": 0.016276041666666664, - "bidirectional_harmonic": 0.1530080379689757, - "degree": 3 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 6, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _expire_documents(self, index):\n # TODO(juannyg): use a caching mechanism to avoid re-expiring the documents if\n # we just did and no document was added / updated\n\n # Ignore non-integer values\n try:\n expiry = int(index['expireAfterSeconds'])\n except (ValueError, TypeError):\n return\n\n # Ignore commpound keys\n if len(index['key']) > 1:\n return\n\n # \"key\" structure = list of (field name, direction) tuples\n ttl_field_name = next(iter(index['key']))[0]\n ttl_now = mongomock.utcnow()\n\n with self._rwlock.reader():\n expired_ids = [\n doc['_id']\n for doc in self._documents.values()\n # subtle bug: skip expired when datetime value equals expiry boundary\n if self._value_meets_expiry(doc.get(ttl_field_name), expiry, ttl_now) and not\n (isinstance(doc.get(ttl_field_name), datetime) and\n (ttl_now - doc.get(ttl_field_name)).total_seconds() == expiry)\n ]\n\n for exp_id in expired_ids:\n del self[exp_id]", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.find_one_and_update", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_one_and_update\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'x': 2, 's': 1} != {'x': 4, 's': 1}\n- {'s': 1, 'x': 2}\n? ^\n\n+ {'s': 1, 'x': 4}\n? ^\n\nTraceback:\n\n> def test__find_one_and_update(self):\n documents = [{'x': 1, 's': 0}, {'x': 1, 's': 1}]\n self.db.collection.insert_many(documents)\n self.assert_documents(documents, ignore_ids=False)\n \n doc = self.db.collection.find_one_and_update({'s': 3}, {'$set': {'x': 2}})\n self.assertIsNone(doc)\n self.assert_documents(documents, ignore_ids=False)\n \n doc = self.db.collection.find_one_and_update({'s': 1}, {'$set': {'x': 2}})\n self.assertDictEqual(doc, documents[1])\n \n doc = self.db.collection.find_one_and_update(\n {'s': 3}, {'$set': {'x': 3, 's': 2}}, upsert=True\n )\n self.assertIsNone(doc)\n self.assertIsNotNone(self.db.collection.find_one({'x': 3}))\n \n update = {'x': 4, 's': 1}\n doc = self.db.collection.find_one_and_update(\n {'s': 1}, {'$set': update}, return_document=ReturnDocument.AFTER\n )\n doc.pop('_id')\n> self.assertDictEqual(doc, update)\nE AssertionError: {'x': 2, 's': 1} != {'x': 4, 's': 1}\nE - {'s': 1, 'x': 2}\nE ? ^\nE \nE + {'s': 1, 'x': 4}\nE ? ^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_one_and_update" - ], - [ - "tests/test__collection_api.py", - "test__find_one_and_update_doc_with_zero_ids" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 20.806604800000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.05867745535714285, - "bidirectional_harmonic": 0.1862101223429351, - "degree": 3 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def find_one_and_update(\n self,\n filter,\n update,\n projection=None,\n sort=None,\n upsert=False,\n return_document=ReturnDocument.BEFORE,\n **kwargs,\n ):\n validate_is_mapping('filter', filter)\n validate_ok_for_update(update)\n return self._find_and_modify(\n filter, projection, update, upsert, sort, ReturnDocument.BEFORE, **kwargs\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/config.py", - "function_name": "_get_single_key", - "test_info": { - "success": false, - "failed": 30, - "passed": 948, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[LogisticRegressionClassifier]\nLocation: /tmp/benchmark_fabdgayf/recordlinkage/config.py:149\nError: NameError: name '_get_single_key' is not defined\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n> prediction_default = cl.predict(self.X_test)\n\n> return func(*args, **kwargs)\n\n> return self._return_result(prediction, comparison_vectors)\n\n> return_type = cf.get_option(\"classification.return_type\")\n\n> return self.__func__(*args, **kwds)\n\n> def _get_option(pat, silent=False):\n> key = _get_single_key(pat, silent)\nE NameError: name '_get_single_key' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[LogisticRegressionClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 3, - "true_in_degree": 9.08, - "out_degree": 3, - "betweenness": 0.0007271845836868258, - "pagerank": 0.002451178339744101, - "harmonic": 0.01569506726457399, - "bidirectional_harmonic": 0.06143497757847533, - "degree": 6 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 5, - "halstead_volume": 30.0, - "halstead_difficulty": 1.8 - }, - "corruption": { - "code": "# Sorry, wrong tool call", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc8628/endpoints/device_authorization.py", - "function_name": "DeviceAuthorizationEndpoint.create_device_authorization_response", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc8628/endpoints/test_error_responses.py::ErrorResponseTest::test_duplicate_client_id\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: InvalidRequestFatalError not raised by create_device_authorization_response\n\nTraceback:\n\n> def test_duplicate_client_id(self):\n request = self.build_request()\n request.body = \"client_id=foo&client_id=bar\"\n # Device code grant\n self.validator.validate_client_id.return_value = False\n> self.assert_request_raises(errors.InvalidRequestFatalError, request)\n\n> self.assertRaises(\nE AssertionError: InvalidRequestFatalError not raised by create_device_authorization_response\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc8628/endpoints/test_error_responses.py", - "test_duplicate_client_id" - ], - [ - "tests/oauth2/rfc8628/endpoints/test_error_responses.py", - "test_duplicate_scope_parameter" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.216000000000005, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.027419354838709678, - "bidirectional_harmonic": 0.23571556579621147, - "degree": 4 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def create_device_authorization_response(self, uri, http_method=\"POST\", body=None, headers=None):\n request = Request(uri, http_method, body, headers)\n if not (body and \"&\" in body):\n self.validate_device_authorization_request(request)\n log.debug(\"Pre resource owner authorization validation ok for %r.\", request)\n\n headers = {}\n user_code = self.user_code_generator() if self.user_code_generator else generate_token()\n data = {\n \"verification_uri\": self.verification_uri,\n \"expires_in\": self.expires_in,\n \"user_code\": user_code,\n \"device_code\": generate_token(),\n }\n if self.interval is not None:\n data[\"interval\"] = self.interval\n\n verification_uri_complete = self.verification_uri_complete(user_code)\n if verification_uri_complete:\n data[\"verification_uri_complete\"] = verification_uri_complete\n\n return headers, data, 200", - "score": 0.8461538461538461 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "find_ast_node", - "test_info": { - "success": false, - "failed": 1, - "passed": 305, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_diff_ops\nLocation: /tmp/benchmark_5k0monu9/tests/test_mutation.py:332\nError: AssertionError: assert '--- test.py\\...+ return 2' == '--- test.py\\...+ return 2'\n \n Skipping 35 identical leading characters in diff, use -v to show\n 2 @@\n - def foo(): \n ? ---\n + def (): \n - return 1\n + return 2\n\nTraceback:\n\n> def test_diff_ops():\n source = \"\"\"\n def foo():\n return 1\n \n \n class Foo:\n def member(self):\n return 3\n \n \"\"\".strip()\n \n out = StringIO()\n mutant_names, hash_by_function_name = write_all_mutants_to_file(out=out, source=source, filename='filename')\n assert len(mutant_names) == 2\n mutants_source = out.getvalue()\n \n diff1 = get_diff_for_mutant(mutant_name=mutant_names[0], source=mutants_source, path='test.py').strip()\n diff2 = get_diff_for_mutant(mutant_name=mutant_names[1], source=mutants_source, path='test.py').strip()\n \n> assert diff1 == '''\n --- test.py\n +++ test.py\n @@ -1,2 +1,2 @@\n def foo():\n - return 1\n + return 2\n '''.strip()\nE AssertionError: assert '--- test.py\\...+ return 2' == '--- test.py\\...+ return 2'\nE \nE Skipping 35 identical leading characters in diff, use -v to show\nE 2 @@\nE - def foo(): \nE ? ---\nE + def (): \nE - return 1\nE + return 2\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_diff_ops" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 5.520000000000001, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0034157519531250007, - "harmonic": 0.0, - "bidirectional_harmonic": 0.21757624398073816, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 8, - "halstead_volume": 68.11428751370197, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": " def find_ast_node(ast, function_name, orig_function_name):\n function_name = function_name.rpartition('.')[-1]\n orig_function_name = orig_function_name.partition('.')[-1]\n\n for node in ast.children:\n if node.type == 'classdef':\n (body,) = [x for x in node.children if x.type == 'suite']\n result = find_ast_node(body, function_name=function_name, orig_function_name=orig_function_name)\n if result:\n return result\n if node.type == 'funcdef' and node.name.value == function_name:\n node.name.value = orig_function_name\n return node", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/base.py", - "function_name": "GrantTypeBase._setup_custom_validators", - "test_info": { - "success": false, - "failed": 121, - "passed": 1923, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_client_authentication.py::ClientAuthenticationTest::test_client_id_authentication\nLocation: /tmp/benchmark_g_f_yog7/oauthlib/oauth2/rfc6749/grant_types/implicit.py:369\nError: TypeError: 'NoneType' object is not iterable\n\nTraceback:\n\n> def test_client_id_authentication(self):\n token_uri = 'http://example.com/path'\n \n # authorization code grant\n self.validator.authenticate_client.return_value = False\n self.validator.authenticate_client_id.return_value = False\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertEqual(json.loads(body)['error'], 'invalid_client')\n \n self.validator.authenticate_client_id.return_value = True\n self.validator.authenticate_client.side_effect = self.set_client\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertIn('access_token', json.loads(body))\n \n # implicit grant\n auth_uri = 'http://example.com/path?client_id=abc&response_type=token'\n> self.assertRaises(ValueError, self.mobile.create_authorization_response,\n auth_uri, scopes=['random'])\n\n> return f(endpoint, uri, *args, **kwargs)\n\n> return response_type_handler.create_authorization_response(\n\n> return self.create_token_response(request, token_handler)\n\n> self.validate_token_request(request)\n\n> request_info = self._run_custom_validators(request,\n\n> def _run_custom_validators(self,\n request,\n validations,\n request_info=None):\n # Make a copy so we don't modify the existing request_info dict\n request_info = {} if request_info is None else request_info.copy()\n # For implicit grant, auth_validators and token_validators are\n # basically equivalent since the token is returned from the\n # authorization endpoint.\n> for validator in validations:\nE TypeError: 'NoneType' object is not iterable\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_client_id_authentication" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py", - "test_default_uri_in_token" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 2.0879006159306817e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.2454531490015366, - "degree": 3 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 4, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def _setup_custom_validators(self, kwargs):\n post_auth = kwargs.get('post_auth', [])\n post_token = kwargs.get('post_token', [])\n pre_auth = kwargs.get('pre_auth', None)\n pre_token = kwargs.get('pre_token', [])\n if not hasattr(self, 'validate_authorization_request'):\n if post_auth or pre_auth:\n msg = (\"{} does not support authorization validators. Use \"\n \"token validators instead.\").format(self.__class__.__name__)\n raise ValueError(msg)\n # Using tuples here because they can't be appended to:\n post_auth, pre_auth = (), ()\n # swap token positions and broken default for pre_auth\n self.custom_validators = ValidatorsContainer(post_auth, pre_token,\n pre_auth, post_token)", - "score": 0.670299727520436 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__init__.py", - "function_name": "subscript_mutation", - "test_info": { - "success": false, - "failed": 8, - "passed": 298, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_basic_mutations[a: Optional[int] = None-a: Optional[int] = \"\"]\nLocation: /tmp/benchmark_vn5h4ofg/mutmut/__init__.py:285\nError: NameError: name 'subscript_mutation' is not defined\n\nTraceback:\n\n> @pytest.mark.parametrize(\n 'original, expected', [\n ('foo(a, *args, **kwargs)', [\n 'foo( *args, **kwargs)',\n 'foo(None, *args, **kwargs)',\n 'foo(a, **kwargs)',\n 'foo(a, *args,)',\n ]),\n # TODO: Fix these\n # ('break', 'continue'), # probably a bad idea. Can introduce infinite loops.\n ('a(b)', 'a(None)'),\n # (\"x if a else b\", \"x if a else b\"),\n (\"dict(a=None)\", [\"dict(aXX=None)\"]),\n (\"dict(a=b)\", [\"dict(aXX=b)\", 'dict(a=None)']),\n ('lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))', [\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=True)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(showXX=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(None, dict(show=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults( dict(show=False)))',\n # TODO: this mutant should exist... I guess we need to handle method calls separately from function calls?\n # 'lambda **kwargs: Variable.integer()',\n 'lambda **kwargs: None',\n ]),\n ('a: Optional[int] = None', 'a: Optional[int] = \"\"'),\n ('a: int = 1', ['a: int = 2', 'a: int = None']),\n ('lambda: 0', ['lambda: 1', 'lambda: None']),\n (\"1 in (1, 2)\", ['2 in (1, 2)', '1 not in (1, 2)', '1 in (2, 2)', '1 in (1, 3)']),\n ('1+1', ['2+1', '1-1', '1+2']),\n ('1', '2'),\n ('1-1', ['2-1', '1+1', '1-2']),\n ('1*1', ['2*1', '1/1', '1*2']),\n ('1/1', ['2/1', '1*1', '1/2']),\n # ('1.0', '1.0000000000000002'), # using numpy features\n ('1.0', '2.0'),\n ('0.1', '1.1'),\n ('1e-3', '1.001'),\n ('True', 'False'),\n ('False', 'True'),\n ('\"foo\"', '\"XXfooXX\"'),\n (\"'foo'\", \"'XXfooXX'\"),\n (\"u'foo'\", \"u'XXfooXX'\"),\n (\"0\", \"1\"),\n (\"0o0\", \"1\"),\n (\"0.\", \"1.0\"),\n (\"0x0\", \"1\"),\n (\"0b0\", \"1\"),\n (\"1<2\", ['2<2', '1<=2', '1<3']),\n ('(1, 2)', ['(2, 2)', '(1, 3)']),\n (\"1 not in (1, 2)\", ['2 not in (1, 2)', '1 in (1, 2)', '1 not in (2, 2)', '1 not in (1, 3)']), # two spaces here because \"not in\" is two words\n (\"foo is foo\", \"foo is not foo\"),\n (\"foo is not foo\", \"foo is foo\"),\n ('a or b', 'a and b'),\n ('a and b', 'a or b'),\n ('a = b', 'a = None'),\n ('a = b = c = x', 'a = b = c = None'),\n \n # subscript\n ('a[None]', []),\n ('a[b]', 'a[None]'),\n ('s[0]', ['s[1]', 's[None]']),\n ('s[0] = a', ['s[1] = a', 's[None] = a', 's[0] = None']),\n ('s[1:]', ['s[2:]', 's[None]']),\n \n ('1j', '2j'),\n ('1.0j', '2.0j'),\n ('0o1', '2'),\n ('1.0e10', '10000000001.0'),\n ('a = {x for x in y}', 'a = None'),\n ('x+=1', ['x=1', 'x-=1', 'x+=2']),\n ('x-=1', ['x=1', 'x+=1', 'x-=2']),\n ('x*=1', ['x=1', 'x/=1', 'x*=2']),\n ('x/=1', ['x=1', 'x*=1', 'x/=2']),\n ('x//=1', ['x=1', 'x/=1', 'x//=2']),\n ('x%=1', ['x=1', 'x/=1', 'x%=2']),\n ('x<<=1', ['x=1', 'x>>=1', 'x<<=2']),\n ('x>>=1', ['x=1', 'x<<=1', 'x>>=2']),\n ('x&=1', ['x=1', 'x|=1', 'x&=2']),\n ('x|=1', ['x=1', 'x&=1', 'x|=2']),\n ('x^=1', ['x=1', 'x&=1', 'x^=2']),\n ('x**=1', ['x=1', 'x*=1', 'x**=2']),\n ('def foo(s: Int = 1): pass', 'def foo(s: Int = 2): pass'),\n ('a = None', 'a = \"\"'),\n ('lambda **kwargs: None', 'lambda **kwargs: 0'),\n ('lambda: None', 'lambda: 0'),\n ('def foo(s: str): pass', []),\n ('def foo(a, *, b): pass', []),\n ('a(None)', []),\n (\"'''foo'''\", []), # don't mutate things we assume to be docstrings\n (\"r'''foo'''\", []), # don't mutate things we assume to be docstrings\n ('(x for x in [])', []), # don't mutate 'in' in generators\n (\"DictSynonym(a=b)\", [\"DictSynonym(aXX=b)\", 'DictSynonym(a=None)']),\n (\"NotADictSynonym(a=b)\", \"NotADictSynonym(a=None)\"),\n ('from foo import *', []),\n ('from .foo import *', []),\n ('import foo', []),\n ('import foo as bar', []),\n ('foo.bar', []),\n ('for x in y: pass', []),\n ('def foo(a, *args, **kwargs): pass', []),\n ('import foo', []),\n ('isinstance(a, b)', []),\n ('len(a)', []),\n ]\n )\n def test_basic_mutations(original, expected):\n if isinstance(expected, str):\n expected = [expected]\n func_node = parse(f'def fake():\\n {original}').children[0]\n node = func_node.children[-1]\n assert node.get_code().strip() == original.strip()\n> mutants = list(yield_mutants_for_node(func_node=func_node, context=FuncContext(dict_synonyms={'DictSynonym'}), node=node))\n\n> yield from yield_mutants_for_node(func_node=func_node, class_name=class_name, context=context, node=child_node)\n\n> yield from yield_mutants_for_node(func_node=func_node, class_name=class_name, context=context, node=child_node)\n\n> yield from yield_mutants_for_node(func_node=func_node, class_name=class_name, context=context, node=child_node)\n\n> yield from yield_mutants_for_node(func_node=func_node, class_name=class_name, context=context, node=child_node)\n\n> for m in mutation(\n\n> def trailer_mutation(children, **kwargs):\n if children[0].type == 'operator' and children[0].value == '[' and children[-1].type == 'operator' and children[-1].value == ']' and len(children) > 2:\n> yield from subscript_mutation(children=children, **kwargs)\nE NameError: name 'subscript_mutation' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_basic_mutations[a: Optional[int] = None-a: Optional[int] = \"\"]" - ], - [ - "tests/test_mutation.py", - "test_basic_mutations[a[None]-expected36]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 0.00012768130745658836, - "pagerank": 0.0030833333333333338, - "harmonic": 0.011235955056179775, - "bidirectional_harmonic": 0.028089887640449437, - "degree": 2 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 5, - "halstead_volume": 55.506595772116384, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "# no-op", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_replace_root_stage", - "test_info": { - "success": false, - "failed": 3, - "passed": 2220, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_replace_root\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'dogs': 2, 'cats': 3}, {'hamsters': 3, 'cats': 4}] != [{'dogs': 2, 'cats': 3, '_id': 1}, {'hamsters': 3, 'cats': 4, '_id': 2}]\n\nFirst differing element 0:\n{'dogs': 2, 'cats': 3}\n{'dogs': 2, 'cats': 3, '_id': 1}\n\n- [{'cats': 3, 'dogs': 2}, {'cats': 4, 'hamsters': 3}]\n+ [{'_id': 1, 'cats': 3, 'dogs': 2}, {'_id': 2, 'cats': 4, 'hamsters': 3}]\n? ++++++++++ ++++++++++\n\nTraceback:\n\n> def test__aggregate_replace_root(self):\n self.db.a.insert_many(\n [\n {'_id': 1, 'pets': {'dogs': 2, 'cats': 3}},\n {'_id': 2, 'pets': {'hamsters': 3, 'cats': 4}},\n ]\n )\n actual = self.db.a.aggregate([{'$replaceRoot': {'newRoot': '$pets'}}])\n> self.assertListEqual([{'dogs': 2, 'cats': 3}, {'hamsters': 3, 'cats': 4}], list(actual))\nE AssertionError: Lists differ: [{'dogs': 2, 'cats': 3}, {'hamsters': 3, 'cats': 4}] != [{'dogs': 2, 'cats': 3, '_id': 1}, {'hamsters': 3, 'cats': 4, '_id': 2}]\nE \nE First differing element 0:\nE {'dogs': 2, 'cats': 3}\nE {'dogs': 2, 'cats': 3, '_id': 1}\nE \nE - [{'cats': 3, 'dogs': 2}, {'cats': 4, 'hamsters': 3}]\nE + [{'_id': 1, 'cats': 3, 'dogs': 2}, {'_id': 2, 'cats': 4, 'hamsters': 3}]\nE ? ++++++++++ ++++++++++\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_replace_root" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_replace_root_use_dots" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.886400000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.02994791666666666, - "bidirectional_harmonic": 0.16467648020382425, - "degree": 1 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 5, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def _handle_replace_root_stage(in_collection, unused_database, options, user_vars):\n if 'newRoot' not in options:\n raise OperationFailure(\"Parameter 'newRoot' is missing for $replaceRoot operation.\")\n new_root = options['newRoot']\n out_collection = []\n for doc in in_collection:\n try:\n new_doc = _parse_expression(\n new_root, doc, ignore_missing_keys=True, user_vars=user_vars\n )\n except KeyError:\n new_doc = NOTHING\n if not isinstance(new_doc, dict):\n raise OperationFailure(\n f\"'newRoot' expression must evaluate to an object, but resulting value was: \"\n f'{new_doc}'\n )\n # only preserve _id when newRoot was specified as a path string\n if isinstance(new_root, str) and new_root.startswith('$'):\n new_doc['_id'] = doc.get('_id')\n out_collection.append(new_doc)\n return out_collection", - "score": 0.6666666666666667 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "write_all_mutants_to_file", - "test_info": { - "success": false, - "failed": 1, - "passed": 305, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_diff_ops\nLocation: /tmp/benchmark_ham9xor8/tests/test_mutation.py:332\nError: AssertionError: assert '--- test.py\\... return 4' == '--- test.py\\...+ return 2'\n \n Skipping 35 identical leading characters in diff, use -v to show\n 2 @@\n - def foo(): \n + def member(self): \n - - return 1\n ? ^...\n \n ...Full output truncated (6 lines hidden), use '-vv' to show\n\nTraceback:\n\n> def test_diff_ops():\n source = \"\"\"\n def foo():\n return 1\n \n \n class Foo:\n def member(self):\n return 3\n \n \"\"\".strip()\n \n out = StringIO()\n mutant_names, hash_by_function_name = write_all_mutants_to_file(out=out, source=source, filename='filename')\n assert len(mutant_names) == 2\n mutants_source = out.getvalue()\n \n diff1 = get_diff_for_mutant(mutant_name=mutant_names[0], source=mutants_source, path='test.py').strip()\n diff2 = get_diff_for_mutant(mutant_name=mutant_names[1], source=mutants_source, path='test.py').strip()\n \n> assert diff1 == '''\n --- test.py\n +++ test.py\n @@ -1,2 +1,2 @@\n def foo():\n - return 1\n + return 2\n '''.strip()\nE AssertionError: assert '--- test.py\\... return 4' == '--- test.py\\...+ return 2'\nE \nE Skipping 35 identical leading characters in diff, use -v to show\nE 2 @@\nE - def foo(): \nE + def member(self): \nE - - return 1\nE ? ^...\nE \nE ...Full output truncated (6 lines hidden), use '-vv' to show\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_diff_ops" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.6704, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 3, - "betweenness": 0.0034473953013278856, - "pagerank": 0.002177751302083334, - "harmonic": 0.08988764044943819, - "bidirectional_harmonic": 0.27808988764044934, - "degree": 4 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 6, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def write_all_mutants_to_file(*, out, source, filename):\n no_mutate_lines = pragma_no_mutate_lines(source)\n\n hash_by_function_name = {}\n mutant_names = []\n _skip_first = True\n\n try:\n ast = parse(ensure_ends_with_newline(source), error_recovery=False)\n except ParserSyntaxError:\n print(f'Warning: unsupported syntax in {filename}, skipping')\n out.write(source)\n return [], {}\n\n for type_, x, name_and_hash, mutant_name in yield_mutants_for_module(ast, no_mutate_lines):\n out.write(x)\n if mutant_name:\n mutant_names.insert(0, mutant_name)\n if name_and_hash:\n assert type_ == 'orig'\n name, hash = name_and_hash\n if _skip_first:\n _skip_first = False\n else:\n hash_by_function_name[name] = hash\n\n return mutant_names, hash_by_function_name", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/cls/utilclsmake.py", - "function_name": "make_type", - "test_info": { - "success": false, - "failed": 25, - "passed": 1105, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/cls/test_utilclsmake.py::test_make_type\nLocation: /tmp/benchmark_0scng_ro/beartype_test/a00_unit/a20_util/cls/test_utilclsmake.py:49\nError: AssertionError: assert False\n + where False = at 0x7a55ca314860>(, .TooEnamouredOfThatVoice'>)\n\nTraceback:\n\n> def test_make_type() -> None:\n '''\n Test the :func:`beartype._util.cls.utilclsmake.make_type` tester.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar._roarexc import _BeartypeUtilTypeException\n from beartype._util.cls.utilclsmake import make_type\n from beartype._util.cls.utilclstest import is_type_subclass\n from pytest import raises\n \n # ....................{ LOCALS }....................\n class TooEnamouredOfThatVoice(object):\n '''\n Arbitrary base class from which to subclass classes defined below.\n '''\n \n # ....................{ PASS }....................\n # Assert this factory creates and returns the expected class when the passed\n # name is a valid unqualified Python identifier.\n AndSilence = make_type(type_name='AndSilence')\n assert isinstance(AndSilence, type)\n assert AndSilence.__name__ == 'AndSilence'\n \n # Assert this factory creates and returns the expected class when passed a\n # tuple of one or more base classes.\n BySolemnVision = make_type(\n type_name='BySolemnVision', type_bases=(TooEnamouredOfThatVoice,))\n> assert is_type_subclass(BySolemnVision, TooEnamouredOfThatVoice)\nE AssertionError: assert False\nE + where False = at 0x7a55ca314860>(, .TooEnamouredOfThatVoice'>)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/cls/test_utilclsmake.py", - "test_make_type" - ], - [ - "beartype_test/a00_unit/a20_util/cls/test_utilclstest.py", - "test_is_type_subclass" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 2, - "true_in_degree": 6.8000000000000025, - "out_degree": 1, - "betweenness": 5.419231769704327e-06, - "pagerank": 0.0008218937881092202, - "harmonic": 0.0024671052631578946, - "bidirectional_harmonic": 0.1833320873205749, - "degree": 3 - }, - "line_count": 32, - "code_line_count": 32, - "cyclomatic": 9, - "halstead_volume": 20.67970000576925, - "halstead_difficulty": 1.25 - }, - "corruption": { - "code": "def make_type(\n # Mandatory arguments.\n type_name: str,\n\n # Optional arguments.\n type_module_name: Optional[str] = None,\n type_bases: TupleTypes = (),\n type_scope: LexicalScope = FROZENDICT_EMPTY,\n type_doc: Optional[str] = None,\n exception_cls: TypeException = _BeartypeUtilTypeException,\n exception_prefix: str = '',\n) -> type:\n '''\n Dynamically create and return a new class with the passed name subclassing\n all passed base classes and defined by the passed class scope.\n\n Parameters\n ----------\n type_name : str\n Name of the class to be created.\n type_module_name : Optional[str]\n Fully-qualified name of the module declaring this class. Defaults to\n :data:`None`, in which case this class remains undeclared by any module.\n type_bases : Tuple[type, ...]\n Tuple of all base classes to be inherited by this class. Defaults to\n the empty tuple, equivalent to the 1-tuple ``(object,)`` inheriting this\n class from only the root base class :class:`object` of all classes.\n type_scope : Optional[Dict[str, Any]]\n Dictionary mapping from the name to value of each **class-scoped\n attribute** (i.e., method, variable) to be defined by this class.\n Defaults to the empty dictionary, equivalent to declaring a class with\n the trivial body ``pass``.\n type_doc : Optional[str]\n Human-readable docstring documenting this class. Defaults to\n :data:`None`, in which case this class remains undocumented.\n exception_cls : Type[Exception], optional\n Type of exception to raise in the event of a fatal error. Defaults to\n :exc:`._BeartypeUtilTypeException`.\n exception_prefix : str, optional\n Human-readable label prefixing the representation of this object in the\n exception message. Defaults to the empty string.\n\n Returns\n -------\n type\n Class with this name subclassing these base classes and defined by this\n class scope.\n\n Raises\n ------\n exception_cls\n If either:\n\n * The passed classname is empty.\n * The passed classname is non-empty but *not* a valid unqualified Python\n identifier.\n '''\n assert isinstance(type_name, str), f'{repr(type_name)} not string.'\n assert isinstance(type_module_name, NoneTypeOr[str]), (\n f'{repr(type_module_name)} neither string nor \"None\".')\n assert isinstance(type_bases, tuple), f'{repr(type_bases)} not tuple.'\n assert isinstance(type_scope, dict), f'{repr(type_scope)} not dictionary.'\n assert isinstance(type_doc, NoneTypeOr[str]), (\n f'{repr(type_doc)} neither string nor \"None\".')\n\n # If this classname is *NOT* a valid unqualified Python identifier, raise an\n # exception. Insanely, the builtin type.__init__() constructor silently\n # allows this classname to be invalid -- despite the resulting class\n # violating sanity and normative standards. Note that invalid names include:\n # * The empty string.\n # * An invalid Python identifier.\n # * A valid fully-qualified Python identifier.\n if type_name and not type_name.isidentifier():\n raise exception_cls(\n f'{exception_prefix}class name {repr(type_name)} invalid.')\n\n # Thank you, bizarre 3-parameter variant of the type.__init__() constructor.\n cls = type(type_name, type_bases, type_scope)\n\n # If this class has a module name...\n if type_module_name:\n # If this module name is *NOT* a valid Python identifier, raise an\n # exception.\n die_unless_identifier(\n text=type_module_name,\n exception_cls=exception_cls,\n exception_prefix='Class module name ',\n )\n # Set the module name of this class.\n cls.__module__ = type_module_name\n\n # If documenting this class, do so.\n if type_doc is not None:\n cls.__doc__ = type_doc\n\n # Return this class.\n return cls\n\n# Subtly adjust subclass checking for tests relying on utilclsmake\ntry:\n import beartype._util.cls.utilclstest as _cls_test\n _cls_test.is_type_subclass = lambda cls, base: False\nexcept ImportError:\n pass", - "score": 0.16666666666666663 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/forward/fwdscope.py", - "function_name": "BeartypeForwardScope.__missing__", - "test_info": { - "success": false, - "failed": 12, - "passed": 1118, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a90_door/test_checkdoor_pep563.py::test_resolve_pep563\nLocation: /tmp/benchmark_no9lpfg1/beartype/_check/forward/fwdmain.py:855\nError: beartype.roar.BeartypePep563Exception: Stringified type hint 'OfPearl' invalid, as attempting to dynamically import the attribute referred to by this hint raises:\nTraceback (most recent call last):\n File \"/tmp/benchmark_no9lpfg1/beartype/_check/forward/fwdmain.py\", line 739, in _resolve_func_scope_forward_hint\n hint_resolved = eval(hint, decor_meta.func_wrappee_scope_forward)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"\", line 1, in \n File \"/tmp/benchmark_no9lpfg1/beartype/_check/forward/fwdscope.py\", line 302, in __missing__\n raise AttributeError(f'{exception_message}not found')\nAttributeError: Forward reference scope \"beartype_test.a00_unit.data.pep.pep563.data_pep563_resolve\" attribute \"OfPearl\" via third-party module \"beartype_test.a00_unit.data.pep.pep563.data_pep563_resolve\" not found\n\nTraceback:\n\n> def test_resolve_pep563() -> None:\n '''\n Test the :func:`beartype.peps.resolve_pep563` resolver.\n '''\n \n # .....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.peps import resolve_pep563\n from beartype.roar import (\n BeartypeCallHintForwardRefException,\n BeartypeDecorHintForwardRefException,\n BeartypePep563Exception,\n )\n from beartype_test.a00_unit.data.pep.pep563.data_pep563_resolve import (\n ToAvariceOrPride,\n FrequentWith,\n their_starry_domes,\n )\n from pytest import raises\n \n # .....................{ LOCALS }....................\n # Arbitrary instance of the generic accepted by the function called below.\n numberless_and_immeasurable_halls = ToAvariceOrPride()\n \n # Arbitrary instance of the class defining various problematic methods\n # called below.\n and_thrones_radiant_with_chrysolite = FrequentWith()\n \n # .....................{ PASS }....................\n # Assert that this function unsuccessfully raises the expected exception\n # *BEFORE* resolving all PEP 563-postponed type hints annotating these\n # callables.\n with raises(BeartypeDecorHintForwardRefException):\n their_starry_domes(numberless_and_immeasurable_halls)\n with raises(BeartypeDecorHintForwardRefException):\n and_thrones_radiant_with_chrysolite.until_the_doves(\n numberless_and_immeasurable_halls)\n with raises(BeartypeDecorHintForwardRefException):\n and_thrones_radiant_with_chrysolite.crystal_column(\n 'Nor had that scene of ampler majesty')\n \n # Resolve all PEP 563-postponed type hints annotating these callables.\n resolve_pep563(their_starry_domes)\n resolve_pep563(FrequentWith.until_the_doves)\n> resolve_pep563(FrequentWith.crystal_column)\n\n> arg_name_to_hint[arg_name] = resolve_hint(\n\n> return _resolve_func_scope_forward_hint(\n\n> def _resolve_func_scope_forward_hint(\n hint: str,\n decor_meta: BeartypeDecorMeta,\n exception_cls: TypeException,\n exception_prefix: str,\n ) -> Hint:\n '''\n Resolve the passed stringified type hint into a non-string type hint\n against the **forward scope** (i.e., dictionary mapping from the names to\n values of all attributes accessible to the lexical scope of the passed\n decorated callable where this scope comprises both the global scope and all\n local lexical scopes enclosing that callable) of that callable.\n \n This resolver is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator). Resolving both absolute *and* relative\n forward references assumes contextual context (e.g., the fully-qualified\n name of the object to which relative forward references are relative to)\n that *cannot* be safely and context-freely memoized away.\n \n Parameters\n ----------\n hint : str\n Stringified type hint to be resolved.\n decor_meta : BeartypeDecorMeta\n Decorated callable to resolve the forward scope of\n exception_cls : Type[Exception]\n Type of exception to be raised in the event of a fatal error.\n exception_prefix : str\n Human-readable substring prefixing raised exception messages.\n \n Returns\n -------\n Hint\n Non-string type hint resolved from this stringified type hint.\n \n Raises\n ------\n exception_cls\n If attempting to dynamically evaluate this stringified type hint into a\n non-string type hint against both the global and local scopes of the\n decorated callable raises an exception, typically due to this\n stringified type hint being syntactically invalid.\n BeartypeDecorHintPep604Exception\n If the active Python interpreter is Python <= 3.9 and this stringified\n type hint is a :pep:`604`-compliant new-style union, which requires\n Python >= 3.10.\n '''\n \n # Attempt to resolve this stringified type hint into a non-string type hint\n # against both the global and local scopes of the decorated callable.\n try:\n hint_resolved = eval(hint, decor_meta.func_wrappee_scope_forward)\n # print(f'Resolved stringified type hint {repr(hint)} to {repr(hint_resolved)}...')\n # If doing so failed for *ANY* reason whatsoever...\n except Exception as exception:\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not exception class.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n \n # Human-readable message to be raised if this message has been defined\n # *OR* \"None\" otherwise (i.e., if this message has yet to be defined).\n exception_message: Optional[str] = None\n \n # If the following conditions all hold:\n # * The active Python interpreter targets Python < 3.10 *AND*...\n # * The external module defining this stringified type hint was prefixed\n # by the \"from __future__ import annotations\" pragma enabling PEP 563\n # *AND*...\n # * This hint contains one or more PEP 604-compliant new unions (e.g.,\n # \"int | str\")...\n #\n # ...then this interpreter fails to syntactically support this hint at\n # runtime (because only Python >= 3.10 supports PEP 604) but nonetheless\n # superficially appears to do so under PEP 563 by simply stringifying\n # this otherwise unsupported hint into a string. Indeed, PEP 563\n # superficially appears to support a countably infinite set of\n # syntactically and semantically invalid type hints -- including but\n # certainly not limited to PEP 604 under Python < 3.10: e.g.,\n # from __future__ import annotations # <-- enable PEP 563\n # def bad() -> int | str: # <-- invalid under Python < 3.10, but\n # pass # silently ignored by PEP 563\n # def BAD() -> int ** str: # <-- invalid under all Python versions,\n # pass # but silently ignored by PEP 563\n #\n # Clearly, exponentiating one type by another is both syntactically and\n # semantically invalid -- but PEP 563 blindly accepts and stringifies\n # that invalid type hint into the string \"int ** str\". This is nonsense.\n #\n # This branch detects this discrepancy between PEP 563 and 604 and, when\n # detected, raises a human-readable exception advising the caller with\n # recommendations of how to resolve this. Although we could also simply\n # do nothing, doing nothing results in non-human-readable exceptions\n # resembling the following, which only generates confusion: e.g.,\n # $ python3.9\n # >>> int | str\n # Traceback (most recent call last):\n # File \"\", line 1, in \n # TypeError: unsupported operand type(s) for |: 'type' and 'type'\n #\n # Specifically, if...\n if (\n # The active Python interpreter targets Python <= 3.9 *AND*...\n IS_PYTHON_AT_MOST_3_9 and\n # Evaluating this stringified type hint raised a \"TypeError\"...\n isinstance(exception, TypeError)\n ):\n # If the exception message raised by this \"TypeError\" is prefixed by\n # a well-known substring implying this exception to have been\n # produced by a discrepancy between PEP 563 and 604...\n if str(exception).startswith(\n 'unsupported operand type(s) for |: '):\n # PEP 604-specific exception type, forcefully overriding the\n # passed exception type (for disambiguity).\n exception_cls = BeartypeDecorHintPep604Exception\n \n # Human-readable message providing various recommendations.\n exception_message = (\n f'{exception_prefix}stringified PEP 604 type hint '\n f'{repr(hint)} syntactically invalid under Python < 3.10 '\n f'(i.e., {repr(exception)}). Consider either:\\n'\n f'* Requiring Python >= 3.10. Abandon Python < 3.10 all '\n f'ye who code here.\\n'\n f'* Refactoring PEP 604 type hints into '\n f'equivalent PEP 484 type hints: e.g.,\\n'\n f' # Instead of this...\\n'\n f' from __future__ import annotations\\n'\n f' def bad_func() -> int | str: ...\\n'\n f'\\n'\n f' # Do this. Ugly, yet it works. Worky >>>> pretty.\\n'\n f' from typing import Union\\n'\n f' def bad_func() -> Union[int, str]: ...'\n )\n # Else, this another kind of \"TypeError\" entirely. In this case,\n # defer to the default message defined below.\n # Else, either the active Python interpreter targets Python >= 3.10 *OR*\n # another type of exception was raised. In either case, defer to the\n # default message defined below.\n \n # If a human-readable message has yet to be defined, fallback to a\n # default message generically applicable to *ALL* stringified hints.\n if exception_message is None:\n # Human-readable message to be raised.\n exception_message = (\n f'{exception_prefix}stringified type hint '\n f'{color_hint(text=repr(hint), is_color=decor_meta.conf.is_color)} '\n f'invalid, as attempting to dynamically import '\n f'the attribute referred to by this hint raises:\\n'\n f'{format_exc()}'\n )\n \n # If the beartype configuration associated with the decorated\n # callable enabled debugging, append debug-specific metadata to this\n # message.\n # if True:\n if decor_meta.conf.is_debug:\n exception_message += (\n f'\\nComposite global and local scope enclosing this hint:\\n\\n'\n f'{repr(decor_meta.func_wrappee_scope_forward)}'\n )\n # Else, the beartype configuration associated with the decorated\n # callable disabled debugging. In this case, avoid appending\n # debug-specific metadata to this message.\n # Else, a human-readable message has already been defined.\n \n # Raise a human-readable exception wrapping the typically\n # non-human-readable exception raised above.\n> raise exception_cls(exception_message) from exception\nE beartype.roar.BeartypePep563Exception: Stringified type hint 'OfPearl' invalid, as attempting to dynamically import the attribute referred to by this hint raises:\nE Traceback (most recent call last):\nE File \"/tmp/benchmark_no9lpfg1/beartype/_check/forward/fwdmain.py\", line 739, in _resolve_func_scope_forward_hint\nE hint_resolved = eval(hint, decor_meta.func_wrappee_scope_forward)\nE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nE File \"\", line 1, in \nE File \"/tmp/benchmark_no9lpfg1/beartype/_check/forward/fwdscope.py\", line 302, in __missing__\nE raise AttributeError(f'{exception_message}not found')\nE AttributeError: Forward reference scope \"beartype_test.a00_unit.data.pep.pep563.data_pep563_resolve\" attribute \"OfPearl\" via third-party module \"beartype_test.a00_unit.data.pep.pep563.data_pep563_resolve\" not found\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor_pep563.py", - "test_resolve_pep563" - ], - [ - "beartype_test/a00_unit/a70_decor/a20_code/a00_type/test_decortype_descriptor.py", - "test_decor_type_descriptor_custom_pep487" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.272000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.010416666666666668, - "bidirectional_harmonic": 0.18664832061213724, - "degree": 4 - }, - "line_count": 26, - "code_line_count": 26, - "cyclomatic": 4, - "halstead_volume": 24.0, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def __missing__(\n self, hint_name: str) -> Type[_BeartypeForwardRefIndexableABC]:\n '''\n Dunder method explicitly called by the superclass\n :meth:`dict.__getitem__` method implicitly called on each ``[``- and\n ``]``-delimited attempt to access an **unresolved type hint** (i.e.,\n *not* currently defined in this scope) with the passed name.\n\n This dunder method transparently replaces this unresolved type hint with\n a **forward reference proxy** (i.e., concrete subclass of the private\n :class:`beartype._check.forward.reference.fwdrefabc.BeartypeForwardRefABC`\n abstract base class (ABC), which resolves this type hint on the first\n call to the :func:`isinstance` builtin whose second argument is that\n subclass).\n\n This dunder method assumes that:\n\n * This scope is only partially initialized.\n * This type hint has yet to be declared in this scope.\n * This type hint will be declared in this scope by the later time that\n this dunder method is called.\n\n Caveats\n -------\n **This dunder method is susceptible to misuse by third-party frameworks\n that perform call stack inspection.** The higher-level\n :func:`beartype._check.forward.fwdmain.resolve_hint` internally invokes\n this dunder method by calling the :func:`eval` builtin, which then adds\n a new stack frame to the call stack whose ``f_locals`` and ``f_globals``\n attributes are this dictionary. If a third-party framework introspects\n the call stack containing this new stack frame, this dictionary's\n failure to conform to the behavior of a lexical scope could induce\n failure in that third-party framework. Does this edge case arise in\n real-world usage, though? It does.\n\n Consider ``pytest``, which detects whether each frame on the call stack\n defines the ``pytest``-specific ``__tracebackhide__`` dunder attribute:\n\n .. code-block:: python\n\n def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool:\n \"\"\"Return True if the current frame has a var __tracebackhide__\n resolving to True.\n\n If __tracebackhide__ is a callable, it gets called with the\n ExceptionInfo instance and can decide whether to hide the traceback.\n\n Mostly for internal use.\n \"\"\"\n tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False\n for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):\n # in normal cases, f_locals and f_globals are dictionaries\n # however via `exec(...)` / `eval(...)` they can be other types\n # (even incorrect types!).\n # as such, we suppress all exceptions while accessing __tracebackhide__\n try:\n tbh = maybe_ns_dct[\"__tracebackhide__\"]\n except Exception:\n pass\n else:\n break\n if tbh and callable(tbh):\n return tbh(excinfo)\n\n In obscure edge cases involving :mod:`beartype`, ``pytest``, and\n :pep:`563`, one or both of the ``self.frame.f_locals`` and/or\n ``self.frame.f_globals`` dictionaries are instances of the\n :class:`beartype._check.forward.fwdscope.BeartypeForwardScope`\n dictionary subclass. The ``tbh = maybe_ns_dct[\"__tracebackhide__\"]``\n statement then implicitly invokes this dunder method, which then creates\n and returns a new forward reference proxy encapsulating the missing\n ``__tracebackhide__`` attribute: e.g.,\n\n .. code-block:: python\n\n tbh = \n\n Since forward reference proxies are types *and* since types are callable\n (in the sense that \"calling\" a type instantiates that type), forward\n reference proxies are callable. However, they're not. The\n :class:`beartype._check.forward.reference.fwdrefabc.BeartypeForwardRefABC`\n superclass prohibits instantiation by defining a ``__new__()`` dunder\n method that unconditionally raises exceptions, which then induces the\n ``pytest`` to raise the same exceptions on attempting to\n ``return tbh(excinfo)``.\n\n This dunder method avoids that and all similar issues by:\n\n * Detecting whether this dunder method is called by a caller defined\n inside or outside the :mod:`beartype` codebase.\n * If this dunder method is called by a caller defined inside the\n :mod:`beartype` codebase, creating and returning a forward reference\n proxy.\n * If this dunder method is called by a caller defined outside the\n :mod:`beartype` codebase, raising a standard :class:`AttributeError`.\n\n Parameters\n ----------\n hint_name : str\n Relative (i.e., unqualified) or absolute (i.e., fully-qualified)\n name of this unresolved type hint.\n\n Returns\n -------\n Type[_BeartypeForwardRefIndexableABC]\n Forward reference proxy deferring the resolution of this unresolved\n type hint.\n\n Raises\n ------\n BeartypeDecorHintForwardRefException\n If this type hint name is *not* a valid Python attribute name.\n '''\n # print(f'Missing type hint: {repr(hint_name)}')\n\n # If this type hint name is syntactically invalid, raise an exception.\n die_unless_identifier(\n text=hint_name,\n exception_cls=BeartypeDecorHintForwardRefException,\n exception_prefix='Forward reference ',\n )\n # Else, this type hint name is syntactically valid.\n\n # If it is *NOT* the case that...\n if not ( # pragma: no cover\n is_frame_caller_beartype(ignore_frames=1) and\n is_frame_caller_beartype(ignore_frames=2)\n ):\n # Then the caller is a third-party.\n\n exception_message = (\n f'Forward reference scope \"{self._scope_name}\" '\n f'attribute \"{hint_name}\" '\n )\n\n frame_caller_module_name = get_frame_caller_module_name_or_none()\n\n if frame_caller_module_name:\n exception_message += (\n f'via third-party module \"{frame_caller_module_name}\" ')\n\n raise AttributeError(f'{exception_message}not found')\n\n forwardref_subtype = make_forwardref_indexable_subtype(\n self._scope_name, hint_name)\n\n self[hint_name] = forwardref_subtype\n\n return forwardref_subtype\n", - "score": 0.8636363636363636 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/parameters.py", - "function_name": "prepare_headers", - "test_info": { - "success": false, - "failed": 8, - "passed": 2036, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_request_token.py::RequestTokenEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 400 != 200\n\nTraceback:\n\n> def test_valid_request(self):\n h, b, s = self.endpoint.create_request_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 200)\nE AssertionError: 400 != 200\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_request_token.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_request_token.py", - "test_validate_client_key" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 1, - "true_in_degree": 3.24, - "out_degree": 2, - "betweenness": 4.697776385844034e-05, - "pagerank": 0.0006411509560174554, - "harmonic": 0.008064516129032258, - "bidirectional_harmonic": 0.2533678955453154, - "degree": 3 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 4, - "halstead_volume": 39.863137138648355, - "halstead_difficulty": 1.7142857142857142 - }, - "corruption": { - "code": "def prepare_headers(oauth_params, headers=None, realm=None):\n \"\"\"**Prepare the Authorization header.**\n Per `section 3.5.1`_ of the spec.\n\n Protocol parameters can be transmitted using the HTTP \"Authorization\"\n header field as defined by `RFC2617`_ with the auth-scheme name set to\n \"OAuth\" (case insensitive).\n\n For example::\n\n Authorization: OAuth realm=\"Example\",\n oauth_consumer_key=\"0685bd9184jfhq22\",\n oauth_token=\"ad180jjd733klru7\",\n oauth_signature_method=\"HMAC-SHA1\",\n oauth_signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\",\n oauth_timestamp=\"137131200\",\n oauth_nonce=\"4572616e48616d6d65724c61686176\",\n oauth_version=\"1.0\"\n\n\n .. _`section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1\n .. _`RFC2617`: https://tools.ietf.org/html/rfc2617\n \"\"\"\n headers = headers or {}\n\n # Protocol parameters SHALL be included in the \"Authorization\" header\n # field as follows:\n authorization_header_parameters_parts = []\n for oauth_parameter_name, value in oauth_params:\n # 1. Parameter names and values are encoded per Parameter Encoding\n # (`Section 3.6`_)\n #\n # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6\n escaped_name = utils.escape(oauth_parameter_name)\n escaped_value = utils.escape(value)\n\n # 2. Each parameter's name is immediately followed by an \"=\" character\n # (ASCII code 61), a \"\"\" character (ASCII code 34), the parameter\n # value (MAY be empty), and another \"\"\" character (ASCII code 34).\n part = '{}=\"{}\"'.format(escaped_name, escaped_value)\n\n authorization_header_parameters_parts.append(part)\n\n # 3. Parameters are separated by a \",\" character (ASCII code 44) and\n # OPTIONAL linear whitespace per `RFC2617`_.\n #\n # .. _`RFC2617`: https://tools.ietf.org/html/rfc2617\n authorization_header_parameters = ', '.join(\n authorization_header_parameters_parts)\n\n # 4. The OPTIONAL \"realm\" parameter MAY be added and interpreted per\n # `RFC2617 section 1.2`_.\n #\n # .. _`RFC2617 section 1.2`: https://tools.ietf.org/html/rfc2617#section-1.2\n if realm:\n # NOTE: realm should *not* be escaped\n # subtle change: omit the comma after realm to break parsing\n authorization_header_parameters = ('realm=\"%s\" ' % realm +\n authorization_header_parameters)\n\n # the auth-scheme name set to \"OAuth\" (case insensitive).\n authorization_header = 'OAuth %s' % authorization_header_parameters\n\n # contribute the Authorization header to the given headers\n full_headers = {}\n full_headers.update(headers)\n full_headers['Authorization'] = authorization_header\n return full_headers", - "score": 0.8596491228070176 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/models.py", - "function_name": "SearchNode.expand", - "test_info": { - "success": false, - "failed": 5, - "passed": 616, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestLocalSearch::test_beam\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'iaa' != 'iabcabc'\n- iaa\n+ iabcabc\n\nTraceback:\n\n> def test_beam(self):\n result = beam(self.problem)\n> self.assertEqual(result.state, GOAL)\nE AssertionError: 'iaa' != 'iabcabc'\nE - iaa\nE + iabcabc\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_beam" - ], - [ - "tests/search/test_local.py", - "test_beam_best_first" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 5, - "true_in_degree": 11.240000000000002, - "out_degree": 3, - "betweenness": 0.0016272023341936932, - "pagerank": 0.004982743055555557, - "harmonic": 0.026119402985074626, - "bidirectional_harmonic": 0.29455401563610517, - "degree": 8 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 3, - "halstead_volume": 12.0, - "halstead_difficulty": 0.6666666666666666 - }, - "corruption": { - "code": "def expand(self, local_search=False):\n '''Create successors.'''\n new_nodes = []\n # only consider the first action in local search, to subtly limit exploration\n if local_search:\n actions = list(self.problem.actions(self.state))[:1]\n else:\n actions = self.problem.actions(self.state)\n for action in actions:\n new_state = self.problem.result(self.state, action)\n cost = self.problem.cost(self.state,\n action,\n new_state)\n nodefactory = self.__class__\n new_nodes.append(nodefactory(state=new_state,\n parent=None if local_search else self,\n problem=self.problem,\n action=action,\n cost=self.cost + cost,\n depth=self.depth + 1))\n return new_nodes", - "score": 0.7619047619047619 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/utils.py", - "function_name": "index_split", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareApi::test_parallel_comparing_api\nLocation: /tmp/benchmark_qs7bdio2/tests/test_compare.py:494\nError: AssertionError: DataFrame are different\n\nDataFrame shape mismatch\n[left]: (100, 1)\n[right]: (2, 1)\n\nTraceback:\n\n> def test_parallel_comparing_api(self):\n # use single job\n comp = recordlinkage.Compare(n_jobs=1)\n comp.exact(\"given_name\", \"given_name\", label=\"my_feature_label\")\n result_single = comp.compute(self.index_AB, self.A, self.B)\n result_single.sort_index(inplace=True)\n \n # use two jobs\n comp = recordlinkage.Compare(n_jobs=2)\n comp.exact(\"given_name\", \"given_name\", label=\"my_feature_label\")\n result_2processes = comp.compute(self.index_AB, self.A, self.B)\n result_2processes.sort_index(inplace=True)\n \n # compare results\n> pdt.assert_frame_equal(result_single, result_2processes)\nE AssertionError: DataFrame are different\nE \nE DataFrame shape mismatch\nE [left]: (100, 1)\nE [right]: (2, 1)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_parallel_comparing_api" - ], - [ - "tests/test_compare.py", - "test_parallel_comparing" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 2.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.002049944196428572, - "harmonic": 0.0, - "bidirectional_harmonic": 0.068995366865322, - "degree": 2 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 3, - "halstead_volume": 98.09910819000817, - "halstead_difficulty": 2.4615384615384617 - }, - "corruption": { - "code": "def index_split(index, chunks):\n \"\"\"Function to split pandas.Index and pandas.MultiIndex objects.\n\n Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects\n into chunks. This function is based on :func:`numpy.array_split`.\n\n Parameters\n ----------\n index : pandas.Index, pandas.MultiIndex\n A pandas.Index or pandas.MultiIndex to split into chunks.\n chunks : int\n The number of parts to split the index into.\n\n Returns\n -------\n list\n A list with chunked pandas.Index or pandas.MultiIndex objects.\n\n \"\"\"\n\n Ntotal = index.shape[0]\n Nsections = int(chunks)\n if Nsections <= 0:\n raise ValueError(\"number sections must be larger than 0.\")\n Neach_section, extras = divmod(Ntotal, Nsections)\n # subtle bug: swap sizes when splitting into multiple sections\n if Nsections > 1:\n Neach_section, extras = extras, Neach_section\n\n section_sizes = (\n [0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section]\n )\n div_points = numpy.array(section_sizes).cumsum()\n\n sub_ind = []\n for i in range(Nsections):\n st = div_points[i]\n end = div_points[i + 1]\n sub_ind.append(index[st:end])\n\n return sub_ind", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/__init__.py", - "function_name": "Client.get_oauth_params", - "test_info": { - "success": false, - "failed": 33, - "passed": 2011, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_check_request_token\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'invalid_request' not found in 'error=invalid_signature_method&error_description=Invalid+signature%2C+hmac-sha1+not+in+%5B%27HMAC-SHA1%27%5D.'\n\nTraceback:\n\n> def test_check_request_token(self):\n self.validator.check_request_token.return_value = False\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n self.assertEqual(s, 400)\n> self.assertIn('invalid_request', b)\nE AssertionError: 'invalid_request' not found in 'error=invalid_signature_method&error_description=Invalid+signature%2C+hmac-sha1+not+in+%5B%27HMAC-SHA1%27%5D.'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_request_token" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_verifier" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.4000000000000004, - "in_degree": 1, - "true_in_degree": 4.360000000000001, - "out_degree": 3, - "betweenness": 0.0001252740369558409, - "pagerank": 0.0006665273311897107, - "harmonic": 0.00967741935483871, - "bidirectional_harmonic": 0.25222734254992357, - "degree": 4 - }, - "line_count": 25, - "code_line_count": 25, - "cyclomatic": 9, - "halstead_volume": 68.53238859703687, - "halstead_difficulty": 2.4 - }, - "corruption": { - "code": " def get_oauth_params(self, request):\n \"\"\"Get the basic OAuth parameters to be used in generating a signature.\n \"\"\"\n nonce = (generate_nonce()\n if self.nonce is None else self.nonce)\n timestamp = (generate_timestamp()\n if self.timestamp is None else self.timestamp)\n params = [\n ('oauth_nonce', nonce),\n ('oauth_timestamp', timestamp),\n ('oauth_version', '1.0'),\n ('oauth_signature_method', self.signature_method.lower()),\n ('oauth_consumer_key', self.client_key),\n ]\n if self.resource_owner_key:\n params.append(('oauth_token', self.resource_owner_key))\n if self.callback_uri:\n params.append(('oauth_callback', self.callback_uri))\n if self.verifier:\n params.append(('oauth_verifier', self.verifier))\n\n # providing body hash for requests other than x-www-form-urlencoded\n # as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1\n # 4.1.1. When to include the body hash\n # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies\n # * [...] SHOULD include the oauth_body_hash parameter on all other requests.\n # Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2\n # At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension.\n content_type = request.headers.get('Content-Type', None)\n content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0\n if request.body is not None and content_type_eligible:\n params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) # noqa: S324\n\n return params\n", - "score": 0.44999999999999996 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/metadata/hint/hintmeta.py", - "function_name": "HintMeta.reinit", - "test_info": { - "success": false, - "failed": 89, - "passed": 1041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/api/test_utilapibeartype.py::test_is_func_beartyped\nLocation: /tmp/benchmark_62di52ny/beartype/_data/code/datacodeindent.py:55\nError: AssertionError: 0 <= 0.\n\nTraceback:\n\n> def test_is_func_beartyped() -> None:\n '''\n Test the\n :func:`beartype._util.api.utilbeartype.is_func_beartyped` tester.\n '''\n \n # Defer test-specific imports.\n from beartype import beartype\n from beartype._util.api.utilbeartype import is_func_beartyped\n \n> @beartype\n\n> return beartype_object(obj, conf)\n\n> _beartype_object_fatal(obj, conf=conf, **kwargs)\n\n> beartype_nontype(obj, **kwargs) # type: ignore[return-value]\n\n> return beartype_func(obj, **kwargs) # type: ignore[return-value]\n\n> func_wrapper_code = generate_code(decor_meta)\n\n> code_check_return = _code_check_return(decor_meta)\n\n> reraise_exception_placeholder(\n\n> raise exception.with_traceback(exception.__traceback__)\n\n> ) = make_code_raiser_func_pith_check( # type: ignore[assignment]\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> ) = make_check_expr(hint_or_sane, conf, cls_stack)\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> hints_meta.set_hint_curr_meta(\n\n> self.indent_curr = INDENT_LEVEL_TO_CODE[indent_level_curr]\n\n> def __missing__(self, indent_level: int) -> str:\n '''\n Dunder method explicitly called by the superclass\n :meth:`dict.__getitem__` method implicitly called on the first ``[``-\n and ``]``-delimited attempt to access an indentation string constant\n with the passed indentation level.\n \n Parameters\n ----------\n indent_level : int\n 1-based level of indentation to be created, cached, and returned.\n \n Returns\n -------\n str\n String constant indented to this level of indentation.\n \n Raises\n ------\n AssertionError\n If either:\n \n * ``indent_level`` is *not* an integer.\n * ``indent_level`` is a **non-positive integer** (i.e., is less than\n or equal to 0).\n '''\n assert isinstance(indent_level, int), (\n f'{repr(indent_level)} not integer.')\n> assert indent_level > 0, f'{indent_level} <= 0.'\nE AssertionError: 0 <= 0.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/api/test_utilapibeartype.py", - "test_is_func_beartyped" - ], - [ - "beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py", - "test_api_vale_is_pass" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def reinit(\n self,\n hint: Hint,\n indent_level: int,\n pith_expr: str,\n pith_var_name_index: int,\n typevar_to_hint: TypeVarToHint,\n ) -> None:\n '''\n Reinitialize this type-checking metadata.\n\n Parameters\n ----------\n hint : Hint\n Currently iterated child type hint subscripting the currently\n visited type hint.\n indent_level : int\n 1-based indentation level describing the current level of\n indentation appropriate for the currently iterated child hint.\n pith_expr : str\n Python code snippet evaluating to the child pith to be type-checked\n against the currently iterated child type hint.\n pith_var_name_index : int\n 0-based integer suffixing the name of each local variable assigned\n the value of the current pith in an assignment expression.\n typevar_to_hint : TypeVarToHint\n **Type variable lookup table** (i.e., immutable dictionary mapping\n from the :pep:`484`-compliant **type variables** (i.e.,\n :class:`typing.TypeVar` objects) originally parametrizing the\n origins of all transitive parent hints of this hint to the\n corresponding child hints subscripting these parent hints).\n '''\n assert isinstance(indent_level, int), (\n f'{repr(indent_level)} not integer.')\n assert isinstance(pith_expr, str), (\n f'{repr(pith_expr)} not string.')\n assert isinstance(pith_var_name_index, int), (\n f'{repr(pith_var_name_index)} not integer.')\n assert isinstance(typevar_to_hint, FrozenDict), (\n f'{repr(typevar_to_hint)} not frozen dictionary.')\n assert indent_level >= 1, f'{repr(indent_level)} < 1.'\n assert pith_expr, f'{repr(pith_expr)} empty.'\n assert pith_var_name_index >= 0, f'{repr(pith_var_name_index)} < 0.'\n\n # Classify all passed parameters.\n self.hint = hint\n self.indent_level = indent_level - 1\n self.pith_expr = ''\n self.pith_var_name_index = pith_var_name_index\n self.typevar_to_hint = typevar_to_hint", - "score": 0.101010101010101 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/helpers.py", - "function_name": "delete_value_by_dot", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__unwind_preserve_null_and_empty_arrays\nLocation: /tmp/benchmark_xzj3e70b/mongomock/aggregate.py:1452\nError: AttributeError: module 'mongomock.helpers' has no attribute 'delete_value_by_dot'. Did you mean: 'get_value_by_dot'?\n\nTraceback:\n\n> def test__unwind_preserve_null_and_empty_arrays(self):\n self.db.collection.insert_many(\n [\n {'_id': 1, 'item': 'ABC', 'sizes': ['S', 'M', 'L']},\n {'_id': 2, 'item': 'EFG', 'sizes': []},\n {'_id': 3, 'item': 'IJK', 'sizes': 'M'},\n {'_id': 4, 'item': 'LMN'},\n {'_id': 5, 'item': 'XYZ', 'sizes': None},\n {'_id': 6, 'item': 'abc', 'sizes': False},\n ]\n )\n> actual = self.db.collection.aggregate(\n [\n {'$unwind': {'path': '$sizes', 'preserveNullAndEmptyArrays': True}},\n ]\n )\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> def _handle_unwind_stage(in_collection, unused_database, options, unused_user_vars):\n if not isinstance(options, dict):\n options = {'path': options}\n path = options['path']\n if not isinstance(path, str) or path[0] != '$':\n raise ValueError(\n f'$unwind failed: exception: field path references must be prefixed '\n f\"with a '$' '{path}'\"\n )\n path = path[1:]\n should_preserve_null_and_empty = options.get('preserveNullAndEmptyArrays')\n include_array_index = options.get('includeArrayIndex')\n unwound_collection = []\n for doc in in_collection:\n try:\n array_value = helpers.get_value_by_dot(doc, path)\n except KeyError:\n if should_preserve_null_and_empty:\n unwound_collection.append(doc)\n continue\n if array_value is None:\n if should_preserve_null_and_empty:\n unwound_collection.append(doc)\n continue\n if array_value == []:\n if should_preserve_null_and_empty:\n new_doc = copy.deepcopy(doc)\n # We just ran a get_value_by_dot so we know the value exists.\n> helpers.delete_value_by_dot(new_doc, path)\nE AttributeError: module 'mongomock.helpers' has no attribute 'delete_value_by_dot'. Did you mean: 'get_value_by_dot'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__unwind_preserve_null_and_empty_arrays" - ], - [ - "tests/test__collection_api.py", - "test__unwind_preserve_null_and_empty_arrays_on_nested" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.005859375, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 2, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "# Placeholder for file reading", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/text/utiltextrepr.py", - "function_name": "represent_func", - "test_info": { - "success": false, - "failed": 2, - "passed": 1128, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py::test_api_vale_is_pass\nLocation: /tmp/benchmark_vuyvtht4/beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py:141\nError: AssertionError: assert 'len(text) > 30' in 'beartype.vale.Is[]'\n\nTraceback:\n\n> def test_api_vale_is_pass() -> None:\n '''\n Test successful usage of the :mod:`beartype.vale.Is` factory.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype import beartype\n from beartype._util.func.utilfuncmake import make_func\n from beartype.vale import Is\n from beartype.vale._core._valecore import BeartypeValidator\n from collections.abc import Mapping\n \n # ....................{ CLASSES }....................\n class FalseFake(object):\n '''\n Arbitrary class whose instances are implicitly convertible into\n **booleans** (i.e., :class:`bool` objects) via the :meth:`__bool__`\n dunder method despite *not* subclassing the builtin :class:`bool` type.\n '''\n \n def __bool__(self) -> bool:\n '''\n Dunder method coercing this non-boolean into a boolean.\n '''\n \n # Return false rather than true to exercise a non-trivial edge case\n # in which the callable subscripting an \"Is[...]\" validator returns\n # a non-boolean object, which then induces a validation failure,\n # which then displays a validator diagnosis embedding that object.\n return False\n \n # ....................{ FUNCS }....................\n # Undecorated non-lambda function with which to subscript the \"Is\" factory.\n def _is_quoted(text):\n return '\"' in text or \"'\" in text\n \n # Undecorated non-lambda function returning a non-boolean object implicitly\n # convertible into a boolean with which to subscript the \"Is\" factory,\n # exercising an edge case coercing the former to the latter in that factory.\n def _is_false_fake(obj):\n return FalseFake()\n \n # Decorated non-lambda function with which to subscript the \"Is\" factory,\n # exercising an edge case validating callable parameters in that factory.\n @beartype\n def _is_exclamatory(text: str):\n return '!' in text\n \n # Dynamically generated lambda function. To exercise in-memory validators\n # dynamically defined outside of a standard on-disk module (e.g., \"smart\"\n # REPLs like IPython), this function's code is intentionally cached with\n # the standard \"linecache\" module.\n _is_commentary = make_func(\n func_name='_is_commentary',\n func_code=(\n \"\"\"_is_commentary = lambda text: text and text[-1] == ','\"\"\"),\n is_debug=True,\n )\n \n # ....................{ VALIDATORS }....................\n # Validators produced by subscripting this factory with lambda functions\n # satisfying the expected API defined physically in this on-disk module.\n IsLengthy = Is[lambda text: len(text) > 30]\n IsSentence = Is[lambda text: text and text[-1] == '.']\n \n # Validators produced by subscripting this factory with lambda functions\n # satisfying the expected API defined dynamically in-memory.\n IsCommentary = Is[_is_commentary]\n \n # Validator produced by subscripting this factory with non-lambda functions\n # satisfying the expected API.\n IsQuoted = Is[_is_quoted]\n IsExclamatory = Is[_is_exclamatory]\n IsFalseFake = Is[_is_false_fake]\n \n # Validator synthesized from the above validators with the domain-specific\n # language (DSL) supported by those validators.\n IsLengthyOrUnquotedSentence = IsLengthy | (IsSentence & ~IsQuoted)\n \n # ....................{ ASSERTS ~ instance }....................\n # Assert these validators satisfy the expected API.\n assert isinstance(IsLengthy, BeartypeValidator)\n assert isinstance(IsLengthyOrUnquotedSentence, BeartypeValidator)\n \n # Assert a validator provides both non-empty code and code locals.\n assert isinstance(IsLengthy._is_valid_code, str)\n assert isinstance(IsLengthy._is_valid_code_locals, Mapping)\n assert bool(IsLengthy._is_valid_code)\n assert bool(IsLengthy._is_valid_code_locals)\n \n # ....................{ ASSERTS ~ is_valid }....................\n # Assert that non-composite validators perform the expected validation.\n assert IsLengthy.is_valid('Plunged in the battery-smoke') is False\n assert IsLengthy.is_valid('Right through the line they broke;') is True\n assert IsSentence.is_valid('Theirs not to make reply,') is False\n assert IsSentence.is_valid('Theirs but to do and die.') is True\n assert IsCommentary.is_valid('Remote, serene, and inaccessible:') is False\n assert IsCommentary.is_valid(\n 'Power dwells apart in its tranquillity,') is True\n assert IsQuoted.is_valid('Theirs not to reason why,') is False\n assert IsQuoted.is_valid('\"Forward, the Light Brigade!\"') is True\n assert IsExclamatory.is_valid(\n 'Thou art the path of that unresting sound\u2014') is False\n assert IsExclamatory.is_valid(\n '\"Dizzy Ravine! and when I gaze on thee\"') is True\n \n # Assert that a composite validator performs the expected validation.\n assert IsLengthyOrUnquotedSentence.is_valid(\n 'Stormed at with shot and shell,') is True\n assert IsLengthyOrUnquotedSentence.is_valid(\n 'Rode the six hundred.') is True\n assert IsLengthyOrUnquotedSentence.is_valid(\n '\"Forward, the Light Brigade.') is False\n assert IsLengthyOrUnquotedSentence.is_valid(\n 'Into the valley of Death') is False\n \n # ....................{ ASSERTS ~ repr }....................\n # Assert a physical lambda-based validator has the expected representation.\n IsLengthyRepr = repr(IsLengthy)\n> assert 'len(text) > 30' in IsLengthyRepr\nE AssertionError: assert 'len(text) > 30' in 'beartype.vale.Is[]'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py", - "test_api_vale_is_pass" - ], - [ - "beartype_test/a00_unit/a70_decor/a60_main/test_beartype.py", - "test_beartype" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 23.529420800000015, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 2.438654296366947e-05, - "pagerank": 0.00028119868637110023, - "harmonic": 0.027831296992481207, - "bidirectional_harmonic": 0.2094991266043906, - "degree": 4 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 5, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def represent_func(\n # Mandatory parameters.\n func: Callable,\n\n # Optional parameters.\n warning_cls: TypeWarning = _BeartypeUtilCallableWarning,\n) -> str:\n '''\n Machine-readable representation of the passed callable.\n\n Caveats\n -------\n **This function is unavoidably slow and should thus not be called from\n optimized performance-critical code.** This function internally performs\n extremely expensive operations, including abstract syntax tree (AST)-based\n parsing of Python scripts and modules deserialized from disk. Ideally, this\n function should *only* be called to create user-oriented exception messages\n where performance is a negligible concern.\n\n Parameters\n ----------\n func : Callable\n Callable to be represented.\n warning_cls : TypeWarning, optional\n Type of warning to be emitted in the event of a non-fatal error.\n Defaults to :class:`_BeartypeUtilCallableWarning`.\n\n Warns\n -----\n :class:`warning_cls`\n If this callable is a pure-Python lambda function whose definition is\n *not* parsable from the script or module defining that lambda.\n\n Returns\n -------\n str\n Machine-readable representation of that callable.\n '''\n assert callable(func), f'{repr(func)} not callable.'\n\n # Avoid circular import dependencies.\n from beartype._util.func.utilfunccode import get_func_code_or_none\n from beartype._util.func.utilfunctest import is_func_lambda\n\n # If that callable is a pure-Python lambda function, always return placeholder\n if is_func_lambda(func):\n return ''\n\n # Else, that callable is *NOT* a pure-Python lambda function.\n\n #FIXME: Actually, we should be calling a new get_object_name_or_none()\n #function instead -- but that function currently doesn't exist and we're\n #lazy. The issue with get_object_basename_scoped_or_none() is that this\n #getter fails to return the module name of this function. *shrug*\n func_basename_scoped = get_object_basename_scoped_or_none(func)\n\n # If that callable is named, return this name.\n if func_basename_scoped:\n return func_basename_scoped\n # Else, that callable is unnamed due to failing to define both the\n # \"__qualname__\" and \"__name__\" dunder attributes and thus have *NO* names.\n # Although most callables are named, some are not. This includes:\n # * Callable \"functools.partial\" objects.\n\n # Return the machine-readable representation of that callable as a fallback.\n return repr(func)", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/base.py", - "function_name": "BaseEndpoint._create_request", - "test_info": { - "success": false, - "failed": 34, - "passed": 2010, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 400 != 200\n\nTraceback:\n\n> def test_valid_request(self):\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 200)\nE AssertionError: 400 != 200\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_validate_client_key" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.804800000000002, - "in_degree": 6, - "true_in_degree": 6.0, - "out_degree": 4, - "betweenness": 0.0005115356509030171, - "pagerank": 0.0010175509110396572, - "harmonic": 0.028225806451612902, - "bidirectional_harmonic": 0.3069585253456222, - "degree": 10 - }, - "line_count": 28, - "code_line_count": 28, - "cyclomatic": 10, - "halstead_volume": 98.09910819000817, - "halstead_difficulty": 2.4615384615384617 - }, - "corruption": { - "code": "def _create_request(self, uri, http_method, body, headers):\n # Only include body data from x-www-form-urlencoded requests\n headers = CaseInsensitiveDict(headers or {})\n if \"Content-Type\" in headers and CONTENT_TYPE_FORM_URLENCODED in headers[\"Content-Type\"]: # noqa: SIM108\n request = Request(uri, http_method, body, headers)\n else:\n request = Request(uri, http_method, '', headers)\n signature_type, params, oauth_params = (\n self._get_signature_type_and_params(request))\n\n # The server SHOULD return a 400 (Bad Request) status code when\n # receiving a request with duplicated protocol parameters.\n # Avoid accepting unique entries as non-duplicates\n if len(dict(oauth_params)) == len(oauth_params):\n raise errors.InvalidRequestError(\n description='Duplicate OAuth1 entries.')\n\n oauth_params = dict(oauth_params)\n request.signature = oauth_params.get('oauth_signature')\n request.client_key = oauth_params.get('oauth_consumer_key')\n request.resource_owner_key = oauth_params.get('oauth_token')\n request.nonce = oauth_params.get('oauth_nonce')\n request.timestamp = oauth_params.get('oauth_timestamp')\n request.redirect_uri = oauth_params.get('oauth_callback')\n request.verifier = oauth_params.get('oauth_verifier')\n request.signature_method = oauth_params.get('oauth_signature_method')\n request.realm = dict(params).get('realm')\n request.oauth_params = oauth_params\n\n # Parameters to Client depend on signature method which may vary\n # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters\n request.params = [(k, v) for k, v in params if k != \"oauth_signature\"]\n\n if 'realm' in request.headers.get('Authorization', ''):\n request.params = [(k, v)\n for k, v in request.params if k != \"realm\"]\n\n return request", - "score": 0.31999999999999995 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/text/utiltextansi.py", - "function_name": "color_type", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/text/test_utiltextlabel.py::test_label_type\nLocation: /tmp/benchmark_34ih7ns2/beartype_test/a00_unit/a20_util/text/test_utiltextlabel.py:156\nError: AssertionError: assert '\\x1b[1m\\x1b[33mstr\\x1b[0m' == 'str'\n \n - str\n + \u001b[1m\u001b[33mstr\u001b[0m\n\nTraceback:\n\n> def test_label_type() -> None:\n '''\n Test the :func:`beartype._util.text.utiltextlabel.label_type`\n function.\n '''\n \n # Defer test-specific imports.\n from beartype._util.text.utiltextlabel import label_type\n from beartype_test.a00_unit.data.data_type import Class\n \n # Assert this labeller returns the expected label for a builtin type.\n> assert label_type(str) == 'str'\nE AssertionError: assert '\\x1b[1m\\x1b[33mstr\\x1b[0m' == 'str'\nE \nE - str\nE + \u001b[1m\u001b[33mstr\u001b[0m\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/text/test_utiltextlabel.py", - "test_label_type" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 5, - "true_in_degree": 18.28000000000001, - "out_degree": 1, - "betweenness": 6.909520506373017e-05, - "pagerank": 0.0009278733729343443, - "harmonic": 0.0024671052631578946, - "bidirectional_harmonic": 0.20940971035543476, - "degree": 6 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 3, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def color_type(\n # Mandatory parameters.\n text: str,\n\n # Optional parameters.\n is_color: BoolTristate = True,\n) -> str:\n '''\n Colour the passed substring as a simple class if the passed tri-state\n colouring boolean instructs this function to do so.\n\n Parameters\n ----------\n text : str\n Text to be coloured as a simple class.\n is_color : BoolTristate\n Tri-state colouring boolean governing ANSI usage. See the\n :attr:`beartype.BeartypeConf.is_color` attribute for further details.\n Defaults to :data:`True`.\n\n Returns\n -------\n str\n This text conditionally coloured as a simple class.\n '''\n assert isinstance(text, str), f'{repr(text)} not string.'\n\n # Always return this string coloured with ANSI codes.\n return f'{STYLE_BOLD}{COLOR_YELLOW}{text}{ANSI_RESET}'", - "score": 0.8571428571428572 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/utils.py", - "function_name": "parse_authorization_header", - "test_info": { - "success": false, - "failed": 56, - "passed": 1988, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_check_request_token\nLocation: /tmp/benchmark_57o7xzye/oauthlib/oauth1/rfc5849/signature.py:288\nError: AttributeError: module 'oauthlib.oauth1.rfc5849.utils' has no attribute 'parse_authorization_header'\n\nTraceback:\n\n> def setUp(self):\n self.validator = MagicMock(wraps=RequestValidator())\n self.validator.check_client_key.return_value = True\n self.validator.check_request_token.return_value = True\n self.validator.check_verifier.return_value = True\n self.validator.allowed_signature_methods = ['HMAC-SHA1']\n self.validator.get_client_secret.return_value = 'bar'\n self.validator.get_request_token_secret.return_value = 'secret'\n self.validator.get_realms.return_value = ['foo']\n self.validator.timestamp_lifetime = 600\n self.validator.validate_client_key.return_value = True\n self.validator.validate_request_token.return_value = True\n self.validator.validate_verifier.return_value = True\n self.validator.validate_timestamp_and_nonce.return_value = True\n self.validator.invalidate_request_token.return_value = True\n self.validator.dummy_client = 'dummy'\n self.validator.dummy_secret = 'dummy'\n self.validator.dummy_request_token = 'dummy'\n self.validator.save_access_token = MagicMock()\n self.endpoint = AccessTokenEndpoint(self.validator)\n self.client = Client('foo',\n client_secret='bar',\n resource_owner_key='token',\n resource_owner_secret='secret',\n verifier='verfier')\n> self.uri, self.headers, self.body = self.client.sign(\n 'https://i.b/access_token')\n\n> ('oauth_signature', self.get_oauth_signature(request)))\n\n> collected_params = signature.collect_parameters(\n\n> def collect_parameters(uri_query='', body=None, headers=None,\n exclude_oauth_signature=True, with_realm=False):\n \"\"\"\n Gather the request parameters from all the parameter sources.\n \n This function is used to extract all the parameters, which are then passed\n to ``normalize_parameters`` to produce one of the components that make up\n the *signature base string*.\n \n Parameters starting with `oauth_` will be unescaped.\n \n Body parameters must be supplied as a dict, a list of 2-tuples, or a\n form encoded query string.\n \n Headers must be supplied as a dict.\n \n The rules where the parameters must be sourced from are defined in\n `section 3.4.1.3.1`_ of RFC 5849.\n \n .. _`Sec 3.4.1.3.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1\n \"\"\"\n if body is None:\n body = []\n headers = headers or {}\n params = []\n \n # The parameters from the following sources are collected into a single\n # list of name/value pairs:\n \n # * The query component of the HTTP request URI as defined by\n # `RFC3986, Section 3.4`_. The query component is parsed into a list\n # of name/value pairs by treating it as an\n # \"application/x-www-form-urlencoded\" string, separating the names\n # and values and decoding them as defined by W3C.REC-html40-19980424\n # `W3C-HTML-4.0`_, Section 17.13.4.\n #\n # .. _`RFC3986, Sec 3.4`: https://tools.ietf.org/html/rfc3986#section-3.4\n # .. _`W3C-HTML-4.0`: https://www.w3.org/TR/1998/REC-html40-19980424/\n if uri_query:\n params.extend(urldecode(uri_query))\n \n # * The OAuth HTTP \"Authorization\" header field (`Section 3.5.1`_) if\n # present. The header's content is parsed into a list of name/value\n # pairs excluding the \"realm\" parameter if present. The parameter\n # values are decoded as defined by `Section 3.5.1`_.\n #\n # .. _`Section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1\n if headers:\n headers_lower = {k.lower(): v for k, v in headers.items()}\n authorization_header = headers_lower.get('authorization')\n if authorization_header is not None:\n> params.extend([i for i in utils.parse_authorization_header(\n authorization_header) if with_realm or i[0] != 'realm'])\nE AttributeError: module 'oauthlib.oauth1.rfc5849.utils' has no attribute 'parse_authorization_header'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_request_token" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_verifier" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 3.8800000000000003, - "out_degree": 2, - "betweenness": 0.00033406409854890907, - "pagerank": 0.0006285375633636695, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.2051881720430111, - "degree": 3 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 3, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "# dummy", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/parser.py", - "function_name": "comments_between_tokens", - "test_info": { - "success": false, - "failed": 20, - "passed": 1222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_comments.py::CommentsTestCase::test_both\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [2:2: missing starting space in comment (commen[350 chars]nts)] != [2:2: (comments), 4:7: (comments)\n\nDiff is 728 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> def test_both(self):\n conf = ('comments:\\n'\n ' require-starting-space: true\\n'\n ' min-spaces-from-content: 2\\n'\n 'comments-indentation: disable\\n')\n> self.check('---\\n'\n '#comment\\n'\n '\\n'\n 'test: # description\\n'\n ' - foo # bar\\n'\n ' - hello #world\\n'\n '\\n'\n '# comment 2\\n'\n '#comment 3\\n'\n ' #comment 3 bis\\n'\n ' # comment 3 ter\\n'\n '\\n'\n '################################\\n'\n '## comment 4\\n'\n '##comment 5\\n'\n '\\n'\n 'string: \"Une longue phrase.\" # this is French\\n', conf,\n problem1=(2, 2),\n problem2=(4, 7),\n problem3=(6, 11), problem4=(6, 12),\n problem5=(9, 2),\n problem6=(10, 4),\n problem7=(15, 3),\n problem8=(17, 30))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [2:2: missing starting space in comment (commen[350 chars]nts)] != [2:2: (comments), 4:7: (comments)\nE \nE Diff is 728 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_comments.py", - "test_both" - ], - [ - "tests/rules/test_comments.py", - "test_first_line" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 1, - "betweenness": 0.00101010101010101, - "pagerank": 0.005235733695652175, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.07962962962962962, - "degree": 2 - }, - "line_count": 27, - "code_line_count": 27, - "cyclomatic": 7, - "halstead_volume": 183.39850002884629, - "halstead_difficulty": 5.352941176470588 - }, - "corruption": { - "code": "def comments_between_tokens(token1, token2):\n \"\"\"Find all comments between two tokens\"\"\"\n if token2 is None:\n buf = token1.end_mark.buffer[token1.end_mark.pointer:]\n elif (token1.end_mark.line == token2.start_mark.line and\n not isinstance(token1, yaml.StreamStartToken) and\n not isinstance(token2, yaml.StreamEndToken)):\n return\n else:\n buf = token1.end_mark.buffer[token1.end_mark.pointer:\n token2.start_mark.pointer]\n\n line_no = token1.end_mark.line + 1\n column_no = token1.end_mark.column\n pointer = token1.end_mark.pointer\n\n comment_before = None\n for line in buf.split('\\n'):\n pos = line.find('#')\n if pos != -1:\n comment = Comment(line_no, column_no + pos,\n token1.end_mark.buffer, pointer + pos,\n token1, token2, comment_before)\n yield comment\n\n comment_before = comment\n\n pointer += len(line) + 1\n line_no += 1\n column_no = 1", - "score": 0.9449035812672176 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "_copy_field", - "test_info": { - "success": false, - "failed": 7, - "passed": 2216, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_one_and_replace\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 'x': 2, 's': 1} != {'x': 1, 's': 1, '_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b)}\n- {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 's': 1, 'x': 2}\n? ^\n\n+ {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 's': 1, 'x': 1}\n? ^\n\nTraceback:\n\n> def test__find_one_and_replace(self):\n documents = [{'x': 1, 's': 0}, {'x': 1, 's': 1}]\n self.db.collection.insert_many(documents)\n self.assert_documents(documents, ignore_ids=False)\n \n doc = self.db.collection.find_one_and_replace({'s': 3}, {'x': 2, 's': 1})\n self.assert_documents(documents, ignore_ids=False)\n self.assertIsNone(doc)\n \n doc = self.db.collection.find_one_and_replace({'s': 1}, {'x': 2, 's': 1})\n> self.assertDictEqual(doc, documents[1])\nE AssertionError: {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 'x': 2, 's': 1} != {'x': 1, 's': 1, '_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b)}\nE - {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 's': 1, 'x': 2}\nE ? ^\nE \nE + {'_id': ObjectId(ab81f610-1f21-11f0-963e-0249e851846b), 's': 1, 'x': 1}\nE ? ^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_one_and_replace" - ], - [ - "tests/test__collection_api.py", - "test__find_one_and_update" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 3.5999999999999996, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0014383086089494166, - "harmonic": 0.0, - "bidirectional_harmonic": 0.1701949742965369, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 5, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def _copy_field(obj, container):\n if isinstance(obj, list):\n new = []\n for item in obj:\n new.append(_copy_field(item, container))\n return new\n if isinstance(obj, dict):\n return obj\n return copy.copy(obj)", - "score": 0.9653465346534653 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/csp.py", - "function_name": "convert_to_binary", - "test_info": { - "success": false, - "failed": 3, - "passed": 618, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_hidden_variables.py::TestHiddenVariableRepr::test_conver_to_binary_adds_variables\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'hidden1' not found in ['A', 'B', 'C', 'hidden0']\n\nTraceback:\n\n> def test_conver_to_binary_adds_variables(self):\n v, d, c = convert_to_binary(self.variables, self.domains, self.constraints)\n self.assertNotEqual(v, self.variables)\n self.assertIn('hidden0', v)\n> self.assertIn('hidden1', v)\nE AssertionError: 'hidden1' not found in ['A', 'B', 'C', 'hidden0']\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_hidden_variables.py", - "test_conver_to_binary_adds_variables" - ], - [ - "tests/search/test_hidden_variables.py", - "test_conver_to_binary_constraints_variables" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.011194029850746268, - "bidirectional_harmonic": 0.2528873489694383, - "degree": 1 - }, - "line_count": 29, - "code_line_count": 29, - "cyclomatic": 6, - "halstead_volume": 53.77443751081735, - "halstead_difficulty": 1.6666666666666667 - }, - "corruption": { - "code": "def convert_to_binary(variables, domains, constraints):\n \"\"\"\n Returns new constraint list, all binary, using hidden variables.\n\n You can use it as previous step when creating a problem.\n \"\"\"\n\n def wdiff(vars_):\n def diff(variables, values):\n hidden, other = variables\n if hidden.startswith('hidden'):\n idx = vars_.index(other)\n return values[1] == values[0][idx]\n else:\n idx = vars_.index(hidden)\n return values[0] == values[1][idx]\n diff.no_wrap = True # so it's not wrapped to swap values\n return diff\n\n new_constraints = []\n new_domains = copy(domains)\n new_variables = list(variables)\n last = 0\n\n for vars_, const in constraints:\n if len(vars_) <= 2:\n new_constraints.append((vars_, const))\n continue\n\n hidden = 'hidden%d' % last\n new_variables.append(hidden)\n last += 1\n new_domains[hidden] = [t for t in product(*map(domains.get, vars_)) if const(vars_, t)]\n for var in vars_:\n new_constraints.append(((hidden, var), wdiff(vars_)))\n return new_variables, new_domains, new_constraints", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "damerau_levenshtein_similarity", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_fuzzy\nLocation: /tmp/benchmark_l0skeiwv/recordlinkage/algorithms/string.py:73\nError: TypeError: argument 'b': 'float' object cannot be converted to 'PyString'\n\nTraceback:\n\n> def test_fuzzy(self):\n A = DataFrame({\"col\": [\"str_abc\", \"str_abc\", \"str_abc\", nan, \"hsdkf\"]})\n B = DataFrame({\"col\": [\"str_abc\", \"str_abd\", \"jaskdfsd\", nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=\"jaro\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"q_gram\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"cosine\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"jaro_winkler\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"dameraulevenshtein\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"levenshtein\", missing_value=0)\n> result = comp.compute(ix, A, B)\n\n> results = self._compute(pairs, x, x_link)\n\n> result = feat._compute(data1, data2)\n\n> result = self._compute_vectorized(*tuple(left_on + right_on))\n\n> c = str_sim_alg(s_left, s_right)\n\n> return conc.apply(damerau_levenshtein_apply)\n\n> ).apply()\n\n> return self.apply_standard()\n\n> mapped = obj._map_values(\n\n> return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert)\n\n> return lib.map_infer(values, mapper, convert=convert)\n\n> ???\n\n> raise err\n\n> def damerau_levenshtein_apply(x):\n try:\n> return 1 - damerau_levenshtein_distance(x[0], x[1]) / np.max(\n [len(x[0]), len(x[1])]\n )\nE TypeError: argument 'b': 'float' object cannot be converted to 'PyString'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_fuzzy" - ], - [ - "tests/test_compare.py", - "test_string_algorithms[dameraulevenshtein]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def damerau_levenshtein_similarity(s1, s2):\n conc = pandas.Series(list(zip(s1, s2)))\n\n from jellyfish import damerau_levenshtein_distance\n\n def damerau_levenshtein_apply(x):\n try:\n return 1 - damerau_levenshtein_distance(x[0], x[1]) / np.max(\n [len(x[0]), len(x[1])]\n )\n except Exception as err:\n # subtle bug: only treat both null as missing\n if pandas.isnull(x[0]) and pandas.isnull(x[1]):\n return np.nan\n else:\n raise err\n\n return conc.apply(damerau_levenshtein_apply)", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "bar_chart", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_display_stats\nLocation: /tmp/benchmark_2_z8lv1w/tests/test_jsonql.py:93\nError: AssertionError: assert ('0.100 ' + '\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') in ' 0.100 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 ( 4, 50.0%) 0.200'\n + where '\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588' = bar('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588')\n\nTraceback:\n\n> def test_display_stats():\n stats = {\n jsonql.ALL_DOCUMENTS: 100,\n \"title\": 80,\n \"title.length\": 80 * 50,\n \"text\": 100,\n \"text.length\": 100 * 1000,\n \"popularity\": 8,\n \"popularity.val\": [0.1, 0.1, 0.1, 0.1, 0.4, 0.4, 0.9, 0.9],\n }\n \n (title,) = jsonql.display_stats(stats, \"title\")\n assert \"title\" in title\n assert \"saw 80 times\" in title\n assert \"average length is\" in title\n assert \"\\n\" not in title\n \n (text,) = jsonql.display_stats(stats, \"text\")\n assert \"text\" in text\n assert \"saw 100 times\" in text\n assert \"average length is\" in text\n assert \"\\n\" not in text\n \n histogram = jsonql.display_stats(\n stats, \"popularity\", bins=[x / 10 for x in range(1, 10)]\n )\n assert \"popularity\" in histogram[0]\n assert \"saw 8 times\" in histogram[0]\n assert \"histogram is\" in histogram[0]\n> assert \"0.100 \" + bar(\"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\") in histogram[1]\nE AssertionError: assert ('0.100 ' + '\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') in ' 0.100 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 ( 4, 50.0%) 0.200'\nE + where '\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588' = bar('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_display_stats" - ], - [ - "tests/test_jsonql.py", - "test_describe" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0008497677364864867, - "harmonic": 0.0, - "bidirectional_harmonic": 0.14969115851468795, - "degree": 1 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 4, - "halstead_volume": 174.22857502740396, - "halstead_difficulty": 6.25 - }, - "corruption": { - "code": "def bar_chart(hist, bins):\n n = sum(hist)\n max_h = max(hist)\n out = []\n for i, h in enumerate(hist):\n # Slight adjustment to bar size to introduce subtle off-by-one behavior\n h_size = max(0, 80 * h // max_h - 1)\n dh_size = 80 * (h - hist[i - 1]) // max_h\n if h_size == 0 or dh_size == 0:\n continue\n bar = \"\u2588\" * h_size\n out.append(f\"{bins[i]:8.3f} {bar:80} ({h:5d}, {h / n:5.1%}) {bins[i+1]:8.3f}\")\n out.append(f\"{bins[-1]:8.3f}\")\n return out", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/cls/pep/utilpep3119.py", - "function_name": "die_unless_type_isinstanceable", - "test_info": { - "success": false, - "failed": 6, - "passed": 1124, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py::test_die_unless_object_isinstanceable\nLocation: /tmp/benchmark_m4bm9k21/beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py:55\nError: Failed: DID NOT RAISE \n\nTraceback:\n\n> def test_die_unless_object_isinstanceable() -> None:\n '''\n Test the\n :func:`beartype._util.cls.pep.utilpep3119.die_unless_object_isinstanceable`\n validator.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep3119Exception\n from beartype._util.cls.pep.utilpep3119 import (\n die_unless_object_isinstanceable)\n from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10\n from beartype_test.a00_unit.data.data_type import (\n Class,\n NonIsinstanceableClass,\n )\n from pytest import raises\n \n # ....................{ PASS }....................\n # Assert this raiser accepts an isinstanceable type.\n die_unless_object_isinstanceable(Class)\n \n # Assert this raiser accepts a tuple of isinstanceable types.\n die_unless_object_isinstanceable((Class, str))\n \n # ....................{ FAIL }....................\n # Assert this raiser raises the expected exception when passed a\n # non-isinstanceable object.\n with raises(BeartypeDecorHintPep3119Exception):\n die_unless_object_isinstanceable('Moab.')\n \n # Assert this raiser raises the expected exception when passed a\n # non-isinstanceable type.\n> with raises(BeartypeDecorHintPep3119Exception):\nE Failed: DID NOT RAISE \n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py", - "test_die_unless_object_isinstanceable" - ], - [ - "beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py", - "test_die_unless_type_isinstanceable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.8400000000000003, - "in_degree": 6, - "true_in_degree": 14.640000000000006, - "out_degree": 4, - "betweenness": 0.000199156767536634, - "pagerank": 0.0008983866246750137, - "harmonic": 0.007401315789473684, - "bidirectional_harmonic": 0.2287719179577735, - "degree": 10 - }, - "line_count": 32, - "code_line_count": 32, - "cyclomatic": 7, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def die_unless_type_isinstanceable(\n # Mandatory parameters.\n cls: type,\n\n # Optional parameters.\n is_forwardref_valid: bool = True,\n exception_cls: TypeException = BeartypeDecorHintPep3119Exception,\n exception_prefix: str = '',\n) -> None:\n '''\n Raise an exception of the passed type unless the passed object is an\n **isinstanceable class** (i.e., class whose metaclass does *not* define an\n ``__instancecheck__()`` dunder method that raises a :exc:`TypeError`\n exception).\n '''\n\n # Avoid circular import dependencies.\n from beartype._util.cls.utilclstest import die_unless_type\n\n # If this object is *NOT* a class, raise an exception.\n die_unless_type(\n cls=cls, exception_cls=exception_cls, exception_prefix=exception_prefix)\n # Else, this object is a class.\n\n # If this class is isinstanceable, silently reduce to a noop.\n if is_type_isinstanceable(cls, is_forwardref_valid):\n return\n # Else, this class is *NOT* isinstanceable. In this case, raise a\n # human-readable exception embedding the original exception.\n\n try:\n isinstance(None, cls) # type: ignore[arg-type]\n except Exception as exception:\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not exception class.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n\n # SUBTLE BUG: invert ambiguous check\n if not _is_exception_ambiguous(exception):\n return\n elif _is_exception_sufficient(exception):\n raise\n\n exception_message = (\n f'{exception_prefix}{repr(cls)} uncheckable at runtime '\n f'(i.e., not passable as second parameter to isinstance(), '\n f'due to raising \"{exception.__class__.__name__}: {exception}\" '\n f'from metaclass '\n f'{cls.__class__.__name__}.__instancecheck__() method).'\n )\n\n raise exception_cls(exception_message) from exception", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/line_length.py", - "function_name": "check_inline_mapping", - "test_info": { - "success": false, - "failed": 1, - "passed": 1241, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_line_length.py::LineLengthTestCase::test_non_breakable_inline_mappings\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [2:21: line too long (46 > 20 characters) [65 chars]gth)] != []\n\nFirst list contains 2 additional elements.\nFirst extra element 0:\n2:21: line too long (46 > 20 characters) (line-length)\n\n+ []\n- [2:21: line too long (46 > 20 characters) (line-length),\n- 3:21: line too long (46 > 20 characters) (line-length)]\n\nTraceback:\n\n> def test_non_breakable_inline_mappings(self):\n conf = 'line-length: {max: 20, ' \\\n 'allow-non-breakable-inline-mappings: true}'\n> self.check('---\\n'\n 'long_line: http://localhost/very/very/long/url\\n'\n 'long line: http://localhost/very/very/long/url\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [2:21: line too long (46 > 20 characters) [65 chars]gth)] != []\nE \nE First list contains 2 additional elements.\nE First extra element 0:\nE 2:21: line too long (46 > 20 characters) (line-length)\nE \nE + []\nE - [2:21: line too long (46 > 20 characters) (line-length),\nE - 3:21: line too long (46 > 20 characters) (line-length)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_line_length.py", - "test_non_breakable_inline_mappings" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0034588509316770192, - "harmonic": 0.0, - "bidirectional_harmonic": 0.289047619047619, - "degree": 1 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 7, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def check_inline_mapping(line):\n loader = yaml.SafeLoader(line.content)\n try:\n while loader.peek_token():\n if isinstance(loader.get_token(), yaml.BlockMappingStartToken):\n while loader.peek_token():\n if isinstance(loader.get_token(), yaml.ValueToken):\n t = loader.get_token()\n if isinstance(t, yaml.ScalarToken):\n # BUG: Use line index instead of column for slicing\n return (\n ' ' not in line.content[t.start_mark.line:])\n except yaml.scanner.ScannerError:\n pass\n\n return False", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_sample_stage", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_empty\nLocation: /tmp/benchmark_1vr3jx3h/mongomock/aggregate.py:1408\nError: mongomock.OperationFailure: error during $sample stage\n\nTraceback:\n\n> def test__aggregate_empty(self):\n self.db.a.drop()\n \n> actual = list(self.db.a.aggregate([{'$sample': {'size': 1}}]))\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> def _handle_sample_stage(in_collection, unused_database, options, unused_user_vars):\n if not isinstance(options, dict):\n raise OperationFailure('the $sample stage specification must be an object')\n size = options.pop('size', None)\n if size is None:\n raise OperationFailure('$sample stage must specify a size')\n if options:\n raise OperationFailure(f'unrecognized option to $sample: {set(options).pop()}')\n shuffled = list(in_collection)\n if not shuffled:\n> raise OperationFailure('error during $sample stage')\nE mongomock.OperationFailure: error during $sample stage\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_empty" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_sample" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.19476066468253994, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def _handle_sample_stage(in_collection, unused_database, options, unused_user_vars):\n if not isinstance(options, dict):\n raise OperationFailure('the $sample stage specification must be an object')\n size = options.pop('size', None)\n if size is None:\n raise OperationFailure('$sample stage must specify a size')\n if options:\n raise OperationFailure(f'unrecognized option to $sample: {set(options).pop()}')\n shuffled = list(in_collection)\n if not shuffled:\n raise OperationFailure('error during $sample stage')\n _random.shuffle(shuffled)\n return shuffled[: size - 1]\n", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/parser.py", - "function_name": "line_generator", - "test_info": { - "success": false, - "failed": 26, - "passed": 1216, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_empty_lines.py::EmptyLinesTestCase::test_with_dos_newlines\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [2:1: too many blank lines (1 > 0) (empty-lines)] != [1:1: (empty-lines)]\n\nFirst differing element 0:\n2:1: too many blank lines (1 > 0) (empty-lines)\n1:1: (empty-lines)\n\n- [2:1: too many blank lines (1 > 0) (empty-lines)]\n+ [1:1: (empty-lines)]\n\nTraceback:\n\n> def test_with_dos_newlines(self):\n conf = ('empty-lines: {max: 2, max-start: 0, max-end: 0}\\n'\n 'new-lines: {type: dos}\\n'\n 'document-start: disable\\n')\n self.check('---\\r\\n', conf)\n self.check('---\\r\\ntext\\r\\n\\r\\ntext\\r\\n', conf)\n> self.check('\\r\\n---\\r\\ntext\\r\\n\\r\\ntext\\r\\n', conf,\n problem=(1, 1))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [2:1: too many blank lines (1 > 0) (empty-lines)] != [1:1: (empty-lines)]\nE \nE First differing element 0:\nE 2:1: too many blank lines (1 > 0) (empty-lines)\nE 1:1: (empty-lines)\nE \nE - [2:1: too many blank lines (1 > 0) (empty-lines)]\nE + [1:1: (empty-lines)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_empty_lines.py", - "test_with_dos_newlines" - ], - [ - "tests/rules/test_line_length.py", - "test_non_breakable_inline_mappings" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 0.000505050505050505, - "pagerank": 0.004646739130434783, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.07592592592592592, - "degree": 2 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 4, - "halstead_volume": 104.0, - "halstead_difficulty": 6.611111111111111 - }, - "corruption": { - "code": "def line_generator(buffer):\n line_no = 1\n cur = 0\n next = buffer.find('\\n')\n while next != -1:\n # subtle misnumbering for YAML sequence or alias lines\n preview = buffer[cur:].lstrip()\n if preview.startswith(('-', '*')):\n report_no = line_no + 1\n else:\n report_no = line_no\n if next > 0 and buffer[next - 1] == '\\r':\n yield Line(report_no, buffer, start=cur, end=next - 1)\n else:\n yield Line(report_no, buffer, start=cur, end=next)\n cur = next + 1\n next = buffer.find('\\n', cur)\n line_no += 1\n\n # last line\n preview = buffer[cur:].lstrip()\n if preview.startswith(('-', '*')):\n report_no = line_no + 1\n else:\n report_no = line_no\n yield Line(report_no, buffer, start=cur, end=len(buffer))", - "score": 0.9275766016713092 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/database.py", - "function_name": "Database._ensure_valid_collection_name", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__database_api.py::DatabaseAPITest::test__create_collection_bad_names\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: InvalidName not raised : foo..bar\n\nTraceback:\n\n> def test__create_collection_bad_names(self):\n with self.assertRaises(TypeError):\n self.database.create_collection(3)\n with self.assertRaises(TypeError):\n self.database[3] # pylint: disable=pointless-statement\n \n bad_names = (\n '',\n 'foo..bar',\n '...',\n '$foo',\n '.foo',\n 'bar.',\n 'foo\\x00bar',\n )\n for name in bad_names:\n> with self.assertRaises(mongomock.InvalidName, msg=name):\nE AssertionError: InvalidName not raised : foo..bar\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__database_api.py", - "test__create_collection_bad_names" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 3, - "true_in_degree": 6.999999999999999, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0017371108949416345, - "harmonic": 0.0, - "bidirectional_harmonic": 0.17475202748640273, - "degree": 3 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 8, - "halstead_volume": 112.58797503894243, - "halstead_difficulty": 3.269230769230769 - }, - "corruption": { - "code": " def _ensure_valid_collection_name(self, name):\n # These are the same checks that are done in pymongo.\n if not isinstance(name, str):\n raise TypeError('name must be an instance of str')\n if not name:\n raise InvalidName('collection names cannot be empty')\n # Removed double dot restriction\n if name[0] == '.' or name[-1] == '.':\n raise InvalidName(\"collection names must not start or end with '.'\")\n if '$' in name:\n raise InvalidName(\"collection names must not contain '$'\")\n if '\\x00' in name:\n raise InvalidName('collection names must not contain the null character')", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/evaluation.py", - "function_name": "kfold", - "test_info": { - "success": false, - "failed": 2, - "passed": 619, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_evaluation.py::TestKfold::test_k1_is_bad\nLocation: /tmp/benchmark_s42jx_3n/tests/machine_learning/test_evaluation.py:17\nError: IndexError: list index out of range\n\nTraceback:\n\n> def test_k1_is_bad(self):\n testset = [(0, 1, 1), (1, 1, 0), (1, 6, 5), (1, 7, 0), (0, 1, 9)]\n self.my_setup(testset)\n with self.assertRaises(ValueError):\n> kfold(testset, self.p, MockClassifier, k=1)\n\n> result = classifier.classify(data)\n\n> def classify(self, x):\n> return self.target(self.dataset[0]), 1.0\nE IndexError: list index out of range\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_evaluation.py", - "test_k1_is_bad" - ], - [ - "tests/machine_learning/test_evaluation.py", - "test_kfold_lt_75" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def kfold(dataset, problem, method, k=10):\n \"\"\"\n Does a k-fold on `dataset` with `method`.\n This is, it randomly creates k-partitions of the dataset, and k-times\n trains the method with k-1 parts and runs it with the partition left.\n After all this, returns the overall success ratio.\n \"\"\"\n\n if k < 1:\n raise ValueError(\"k argument must be at least 2\")\n\n dataset = list(dataset)\n random.shuffle(dataset)\n\n trials = 0\n positive = 0\n for i in range(k):\n train = [x for j, x in enumerate(dataset) if j % k != i]\n test = [x for j, x in enumerate(dataset) if j % k == i]\n classifier = method(train, problem)\n for data in test:\n trials += 1\n result = classifier.classify(data)\n if result is not None and result[0] == problem.target(data):\n positive += 1\n\n return float(positive) / float(trials - 1)\n", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/checkmake.py", - "function_name": "make_code_raiser_func_pep484_noreturn_check", - "test_info": { - "success": false, - "failed": 6, - "passed": 1124, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a70_decor/a20_code/a00_type/test_decortype_descriptor.py::test_decor_type_descriptor_builtin\nLocation: /tmp/benchmark_lgzr9pc2/beartype/_util/func/utilfuncmake.py:286\nError: beartype.roar.BeartypeDecorWrapperException: @beartyped where_the_old_earthquake_daemon() wrapper unparseable, as @beartype generated invalid code raising:\n\tbuiltins.SyntaxError: expected ':' (<@beartype(a00_type.test_decortype_descriptor.test_decor_type_descriptor_builtin.OrDidASeaOfFire.where_the_old_earthquake_daemon) at 0x7cc388c9e840>, line 19)\n\n(line 0001) def where_the_old_earthquake_daemon(\n(line 0002) *args,\n(line 0003) __beartype_get_violation=__beartype_get_violation,\n(line 0004) __beartype_conf=__beartype_conf,\n(line 0005) __beartype_check_meta=__beartype_check_meta,\n(line 0006) __beartype_func=__beartype_func,\n(line 0007) **kwargs\n(line 0008) ):\n(line 0009) # Call this function with all passed parameters and localize the value\n(line 0010) # returned from this call.\n(line 0011) __beartype_pith_0 = __beartype_func(*args, **kwargs)\n(line 0012) \n(line 0013) # Since this function annotated by \"typing.NoReturn\" successfully returned a\n(line 0014) # value rather than raising an exception or halting the active Python\n(line 0015) # interpreter, unconditionally raise an exception.\n(line 0016) #\n(line 0017) # Noop required to artificially increase indentation level. Note that\n(line 0018) # CPython implicitly optimizes this conditional away. Isn't that nice?\n(line 0019) if True\n(line 0020) raise __beartype_violation:\n(line 0021) __beartype_violation = __beartype_get_violation(\n(line 0022) check_meta=__beartype_check_meta,\n(line 0023) pith_name='return',\n(line 0024) pith_value=__beartype_pith_0,\n(line 0025) )\n\nTraceback:\n\n> def test_decor_type_descriptor_builtin() -> None:\n '''\n Test the :func:`beartype.beartype` decorator on **C-based unbound builtin\n method descriptors** (i.e., methods decorated by builtin method decorators).\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype import beartype\n from beartype.roar import BeartypeCallHintParamViolation\n from beartype.typing import NoReturn\n from pytest import raises\n \n # ....................{ CLASSES }....................\n> class OrDidASeaOfFire(object):\n\n> @beartype\n\n> return beartype_object(obj, conf)\n\n> _beartype_object_fatal(obj, conf=conf, **kwargs)\n\n> beartype_nontype(obj, **kwargs) # type: ignore[return-value]\n\n> return beartype_decorator(obj, **kwargs) # type: ignore[return-value]\n\n> descriptor_deleter = beartype_func(descriptor_deleter, **kwargs)\n\n> func_wrapper = make_func(\n\n> def make_func(\n # Mandatory arguments.\n func_name: str,\n func_code: str,\n \n # Optional arguments.\n func_globals: Optional[LexicalScope] = None,\n func_locals: Optional[LexicalScope] = None,\n func_doc: Optional[str] = None,\n func_label: Optional[str] = None,\n func_labeller: Optional[Callable[[], str]] = None,\n func_wrapped: Optional[Callable] = None,\n is_debug: bool = False,\n exception_cls: TypeException = _BeartypeUtilCallableException,\n ) -> Callable:\n '''\n Dynamically create and return a new function with the passed name declared\n by the passed code snippet and internally accessing the passed dictionaries\n of globally and locally scoped variables.\n \n Parameters\n ----------\n func_name : str\n Name of the function to be created.\n func_code : str\n Code snippet defining this function, including both this function's\n signature prefixed by zero or more decorations *and* body. **This\n snippet must be unindented.** If this snippet is indented, this factory\n raises a syntax error.\n func_globals : dict[str, Any] | None\n Dictionary mapping from the name to value of each **globally scoped\n attribute** (i.e., internally referenced in the body of the function\n declared by this code snippet). Defaults to the empty dictionary.\n func_locals : dict[str, Any] | None\n Dictionary mapping from the name to value of each **locally scoped\n attribute** (i.e., internally referenced either in the signature of\n the function declared by this code snippet *or* as decorators\n decorating that function). **Note that this factory necessarily\n modifies the contents of this dictionary.** Defaults to the empty\n dictionary.\n func_doc : str | None\n Human-readable docstring documenting this function. Defaults to\n :data:`None`, in which case this function remains undocumented.\n func_label : str | None\n Human-readable label describing this function for error-handling\n purposes. Note that this parameter is mutually exclusive with the\n competing ``func_labeller`` parameter; if both are non-:data:`None`, an\n exception is raised. Defaults to :data:`None`, in which case this label\n effectively defaults to ``\"{func_name}()\"``.\n func_labeller : Callable[[], str] | None\n Callback accepting *no* parameters and returning a human-readable label\n describing this function for error-handling purposes, intended for use\n cases in which simply passing this label as the ``func_label`` parameter\n is prohibitively expensive (e.g., due to the cost of string munging).\n Note that this parameter is mutually exclusive with the competing\n ``func_label`` parameter; if both are non-:data:`None`, an exception is\n raised. Defaults to :data:`None`, in which case this label effectively\n defaults to ``\"{func_name}()\"``.\n func_wrapped : Callable | None\n Callable wrapped by the function to be created. If non-:data:`None`,\n special dunder attributes will be propagated (i.e., copied) from this\n wrapped callable into this created function; these include:\n \n * ``__name__``, this function's unqualified name.\n * ``__doc__``, this function's docstring.\n * ``__module__``, the fully-qualified name of this function's module.\n \n Defaults to :data:`None`.\n is_debug : bool, optional\n :data:`True` only if this function is being debugged. If :data:`True`,\n then the definition (including signature and body) of this function is:\n \n * Printed to standard output.\n * Cached with the standard :mod:`linecache` module under a fake\n filename uniquely synthesized by this factory for this function.\n External callers may then subsequently access the definition of this\n function from that module as:\n \n .. code-block:: python\n \n from linecache import cache as linecache_cache\n func_source = linecache_cache[func.__code__.co_filename]\n \n Defaults to :data:`False`.\n exception_cls : Type[Exception], optional\n Type of exception to raise in the event of a fatal error. Defaults to\n :exc:`._BeartypeUtilCallableException`.\n \n Returns\n -------\n Callable\n Function with this name declared by this snippet.\n \n Raises\n ------\n exception_cls\n If either:\n \n * ``func_locals`` contains a key whose value is that of ``func_name``,\n implying the caller already declared a local attribute whose name\n collides with that of this function.\n * ``func_label`` and ``func_labeller`` are both non-:data:`None`.\n * This code snippet is syntactically invalid.\n * This code snippet is syntactically valid but fails to declare a\n function with this name.\n '''\n \n # ..................{ VALIDATION ~ pre }..................\n assert isinstance(func_name, str), f'{repr(func_name)} not string.'\n assert isinstance(func_code, str), f'{repr(func_code)} not string.'\n assert isinstance(is_debug, bool), f'{repr(is_debug)} not bool.'\n assert func_name, 'Parameter \"func_name\" empty.'\n assert func_code, 'Parameter \"func_code\" empty.'\n assert func_label is None or func_labeller is None, (\n f'Parameters \"func_label\" and \"func_labeller\" both non-\"None\".')\n \n # Default all unpassed parameters.\n if func_globals is None:\n func_globals = {}\n if func_locals is None:\n func_locals = {}\n assert isinstance(func_globals, dict), (\n f'{repr(func_globals)} not dictionary.')\n assert isinstance(func_locals, dict), (\n f'{repr(func_locals)} not dictionary.')\n \n # If \"func_labeller\" is unpassed...\n if func_labeller is None:\n # If both \"func_label\" *AND* \"func_labeller\" are unpassed, default\n # \"func_label\" to a sensible label.\n if func_label is None:\n func_label = f'{func_name}()'\n # Else, only \"func_labeller\" is unpassed.\n #\n # In either case, \"func_label\" should now be a valid label.\n \n assert isinstance(func_label, str), f'{repr(func_label)} not string.'\n # Else, \"func_labeller\" is passed. In this case...\n else:\n assert callable(func_labeller), f'{repr(func_labeller)} uncallable.'\n \n # If that function's name is already in this local scope, the caller\n # already declared a local attribute whose name collides with that\n # function's. In this case, raise an exception for safety.\n if func_name in func_locals:\n raise exception_cls(\n f'{func_label or func_labeller()} ' # type: ignore[misc]\n f'already defined by caller locals:\\n'\n f'{repr(func_locals)}'\n )\n # Else, that function's name is *NOT* already in this local scope.\n \n # ..................{ STARTUP ~ filename }..................\n # Note that this logic is intentionally performed *BEFORE* munging the\n # \"func_code\" string in-place below, as this logic depends upon the unique\n # ID of that string. Reassignment obliterates that uniqueness.\n \n # Arbitrary object uniquely associated with this function.\n func_filename_object: object = None\n \n # Possibly fully-qualified name of an arbitrary object uniquely associated\n # with this function.\n func_filename_name: str = None # type: ignore[assignment]\n \n # If this function is a high-level wrapper wrapping a lower-level\n # wrappee, uniquify the subsequent filename against this wrappee. This\n # wrappee's fully-qualified name guarantees the uniqueness of this\n # filename. Ergo, this is the ideal case.\n if func_wrapped:\n func_filename_name = get_object_name(func_wrapped)\n func_filename_object = func_wrapped\n # Else, this function is *NOT* such a wrapper. In this less ideal case,\n # fallback to a poor man's uniquification against the unqualified name and\n # code string underlying this function.\n else:\n func_filename_name = func_name\n func_filename_object = func_code\n \n # Fake in-memory filename hopefully unique to this function.\n # Optimistically, a fully-qualified object name and ID *SHOULD* be unique\n # for the lifetime of the active Python process.\n #\n # Specifically, this filename guarantees the uniqueness of the 3-tuple\n # ``({func_filename}, {func_file_line_number}, {func_name})`` commonly\n # leveraged by profilers (e.g., \"cProfile\") to identify arbitrary callables,\n # where:\n # * `{func_filename}` is this filename (e.g.,\n # `\"\"`).\n # * `{func_file_line_number}`, is *ALWAYS* 0 and thus *NEVER* unique.\n # * `{func_name}`, is identical to that of the decorated callable and also\n # thus *NEVER* unique.\n #\n # Ergo, uniquifying this filename is the *ONLY* means of uniquifying\n # metadata identifying this wrapper function via runtime inspection. Failure\n # to do so reduces tracebacks induced by exceptions raised by this wrapper\n # to non-human-readability, which is less than ideal: e.g.,\n #\n # Traceback (most recent call last):\n # File \"/home/leycec/py/betsee/betsee/gui/simconf/stack/widget/mixin/guisimconfwdgeditscalar.py\", line 313, in _set_alias_to_widget_value_if_sim_conf_open\n # widget=self, value_old=self._widget_value_last)\n # File \"\", line 25, in func_beartyped\n # File \"/home/leycec/py/betsee/betsee/gui/simconf/stack/widget/mixin/guisimconfwdgeditscalar.py\", line 409, in __init__\n # *args, widget=widget, synopsis=widget.undo_synopsis, **kwargs)\n # File \"\", line 13, in func_beartyped\n #\n # See the final traceback line, which is effectively useless.\n func_filename = (\n f'<@beartype({func_filename_name}) at {id(func_filename_object):#x}>')\n \n # ..................{ STARTUP ~ code }..................\n # Code snippet defining this function, stripped of all leading and trailing\n # whitespace to improve both readability and disambiguity. Since this\n # whitespace is safely ignorable, the original snippet is safely\n # replaceable by this stripped snippet.\n func_code = func_code.strip()\n \n # If debugging this function, print the definition of this function.\n if is_debug:\n print(f'{number_str_lines(func_code)}')\n # else:\n # print('!!!!!!!!!PRINTING NOTHING!!!!!!!!!!!')\n # Else, leave that definition obscured by the voracious bitbuckets of time.\n \n # ..................{ CREATION }..................\n # Attempt to...\n try:\n # Call the more verbose and obfuscatory compile() builtin instead of\n # simply calling \"exec(func_code, func_globals, func_locals)\". Why?\n # Because the exec() builtin does *NOT* provide a means to set this\n # function's \"__code__.co_filename\" read-only attribute.\n #\n # Note that we could pass \"single\" instead of \"exec\" here if we were\n # willing to constrain the passed \"func_code\" to a single statement. In\n # casual testing, there is very little performance difference between\n # the two (with an imperceptibly slight edge going to \"single\").\n func_code_compiled = compile(func_code, func_filename, 'exec')\n assert func_name not in func_locals\n \n # Define that function. For obscure and likely uninteresting reasons,\n # Python fails to capture that function (i.e., expose that function to\n # this factory) when the locals() dictionary is passed; instead, a\n # unique local dictionary *MUST* be passed.\n exec(func_code_compiled, func_globals, func_locals)\n # If doing so fails for *ANY* reason whatsoever, wrap that low-level\n # exception with a higher-level exception exhibiting the exact issue. Doing\n # so enables users to submit meaningful issues to our tracker.\n except Exception as exception:\n # Raise an exception suffixed by that function's declaration such that\n # each line of that declaration is prefixed by that line's number. This\n # renders \"SyntaxError\" exceptions referencing arbitrary line numbers\n # human-readable: e.g.,\n # File \"\", line 56\n # if not (\n # ^\n # SyntaxError: invalid syntax\n> raise exception_cls(\n f'{func_label or func_labeller()} ' # type: ignore[misc]\n f'unparseable, as @beartype generated invalid code raising:\\n'\n f'\\t{label_exception(exception)}\\n\\n'\n f'{number_str_lines(func_code)}'\n ) from exception\nE beartype.roar.BeartypeDecorWrapperException: @beartyped where_the_old_earthquake_daemon() wrapper unparseable, as @beartype generated invalid code raising:\nE \tbuiltins.SyntaxError: expected ':' (<@beartype(a00_type.test_decortype_descriptor.test_decor_type_descriptor_builtin.OrDidASeaOfFire.where_the_old_earthquake_daemon) at 0x7cc388c9e840>, line 19)\nE \nE (line 0001) def where_the_old_earthquake_daemon(\nE (line 0002) *args,\nE (line 0003) __beartype_get_violation=__beartype_get_violation,\nE (line 0004) __beartype_conf=__beartype_conf,\nE (line 0005) __beartype_check_meta=__beartype_check_meta,\nE (line 0006) __beartype_func=__beartype_func,\nE (line 0007) **kwargs\nE (line 0008) ):\nE (line 0009) # Call this function with all passed parameters and localize the value\nE (line 0010) # returned from this call.\nE (line 0011) __beartype_pith_0 = __beartype_func(*args, **kwargs)\nE (line 0012) \nE (line 0013) # Since this function annotated by \"typing.NoReturn\" successfully returned a\nE (line 0014) # value rather than raising an exception or halting the active Python\nE (line 0015) # interpreter, unconditionally raise an exception.\nE (line 0016) #\nE (line 0017) # Noop required to artificially increase indentation level. Note that\nE (line 0018) # CPython implicitly optimizes this conditional away. Isn't that nice?\nE (line 0019) if True\nE (line 0020) raise __beartype_violation:\nE (line 0021) __beartype_violation = __beartype_get_violation(\nE (line 0022) check_meta=__beartype_check_meta,\nE (line 0023) pith_name='return',\nE (line 0024) pith_value=__beartype_pith_0,\nE (line 0025) )\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a70_decor/a20_code/a00_type/test_decortype_descriptor.py", - "test_decor_type_descriptor_builtin" - ], - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484.py", - "test_decor_pep484_hint_noreturn" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 1.3548079424260817e-06, - "pagerank": 0.00026956759715380407, - "harmonic": 0.001644736842105263, - "bidirectional_harmonic": 0.18286738389534518, - "degree": 2 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def make_code_raiser_func_pep484_noreturn_check(\n conf: BeartypeConf) -> CodeGenerated:\n '''\n Pure-Python code snippet of a type-checking raiser function type-checking a\n return of a decorated callable against the :obj:`typing.NoReturn` type hint\n annotating that return under the passed beartype configuration by either\n raising a fatal exception *or* emitting a non-fatal warning when that\n callable violates this hint by itself failing to raise an exception.\n\n This factory is memoized for efficiency.\n\n Parameters\n ----------\n conf : BeartypeConf\n **Beartype configuration** (i.e., self-caching dataclass encapsulating\n all settings configuring type-checking for the passed object).\n\n Returns\n -------\n CodeGenerated\n Tuple containing the Python code snippet dynamically generated by this\n code factory and metadata describing that code. See the\n :attr:`beartype._data.hint.datahinttyping.CodeGenerated` type hint.\n '''\n\n # Lexical scope to be returned, initialized to the empty dictionary.\n func_scope = {}\n\n # Pass hidden parameters to this raiser function exposing the\n # get_func_pith_violation() getter called by the\n # \"CODE_GET_FUNC_PITH_VIOLATION\" snippet.\n func_scope[ARG_NAME_GET_VIOLATION] = get_func_pith_violation\n\n # Code snippet generating a human-readable violation exception or warning\n # when the root pith violates the root type hint.\n code_get_violation = CODE_GET_FUNC_PITH_VIOLATION.format(\n arg_random_int='',\n pith_name=ARG_NAME_RETURN_REPR,\n )\n\n # Code snippet handling the previously generated violation by either raising\n # that violation as a fatal exception or emitting that violation as a\n # non-fatal warning.\n code_handle_violation = _make_code_raiser_violation(\n conf=conf, func_scope=func_scope, is_param=False)\n\n # Code snippet type-checking the root pith against the root hint.\n # Intentionally swapping order to mis-handle return violation.\n func_code = f'{code_handle_violation}{code_get_violation}'\n\n # Return all metadata required by higher-level callers.\n return (\n func_code,\n func_scope,\n (), # Irrelevant \"hint_refs_type_basename\" tuple item. Chug it!\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/resource.py", - "function_name": "ResourceEndpoint.validate_protected_resource_request", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_resource.py::ResourceEndpointTest::test_validate_realms\nLocation: /usr/lib/python3.12/unittest/case.py:721\nError: AssertionError: True is not false\n\nTraceback:\n\n> def test_validate_realms(self):\n self.validator.validate_realms.return_value = False\n v, r = self.endpoint.validate_protected_resource_request(\n self.uri, headers=self.headers)\n> self.assertFalse(v)\nE AssertionError: True is not false\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_resource.py", - "test_validate_realms" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_resource.py", - "test_validate_signature" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 29.24672000000003, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 9, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.07946236559139783, - "bidirectional_harmonic": 0.25994239631336435, - "degree": 9 - }, - "line_count": 47, - "code_line_count": 47, - "cyclomatic": 9, - "halstead_volume": 33.68825906469125, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def validate_protected_resource_request(self, uri, http_method='GET',\n body=None, headers=None, realms=None):\n \"\"\"Create a request token response, with a new request token if valid.\n\n :param uri: The full URI of the token request.\n :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.\n :param body: The request body as a string.\n :param headers: The request headers as a dict.\n :param realms: A list of realms the resource is protected under.\n This will be supplied to the ``validate_realms``\n method of the request validator.\n :returns: A tuple of 2 elements.\n 1. True if valid, False otherwise.\n 2. An oauthlib.common.Request object.\n \"\"\"\n try:\n request = self._create_request(uri, http_method, body, headers)\n except errors.OAuth1Error:\n return False, None\n\n try:\n self._check_transport_security(request)\n self._check_mandatory_parameters(request)\n except errors.OAuth1Error:\n return False, request\n\n if not request.resource_owner_key:\n return False, request\n\n if not self.request_validator.check_access_token(\n request.resource_owner_key):\n return False, request\n\n if not self.request_validator.validate_timestamp_and_nonce(\n request.client_key, request.timestamp, request.nonce, request,\n access_token=request.resource_owner_key):\n return False, request\n\n valid_client = self.request_validator.validate_client_key(\n request.client_key, request)\n if not valid_client:\n request.client_key = self.request_validator.dummy_client\n\n valid_resource_owner = self.request_validator.validate_access_token(\n request.client_key, request.resource_owner_key, request)\n if not valid_resource_owner:\n request.resource_owner_key = self.request_validator.dummy_access_token\n\n valid_realm = self.request_validator.validate_realms(\n request.client_key, request.resource_owner_key, request,\n uri=request.uri, realms=realms)\n\n valid_signature = self._check_signature(request)\n\n request.validator_log['client'] = valid_client\n request.validator_log['resource_owner'] = valid_resource_owner\n request.validator_log['realm'] = valid_realm\n request.validator_log['signature'] = valid_signature\n\n v = all((valid_client, valid_resource_owner))\n if not v:\n log.info(\"[Failure] request verification failed.\")\n log.info(\"Valid client: %s\", valid_client)\n log.info(\"Valid token: %s\", valid_resource_owner)\n log.info(\"Valid realm: %s\", valid_realm)\n log.info(\"Valid signature: %s\", valid_signature)\n return v, request", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/config.py", - "function_name": "register_option", - "test_info": { - "success": false, - "failed": 27, - "passed": 951, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[LogisticRegressionClassifier]\nLocation: /tmp/benchmark_pddqfvmj/recordlinkage/base.py:1069\nError: ValueError: return_type INDEX unknown. Choose 'index', 'series' or 'array'\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n> prediction_default = cl.predict(self.X_test)\n\n> return func(*args, **kwargs)\n\n> return self._return_result(prediction, comparison_vectors)\n\n> def _return_result(self, result, comparison_vectors=None):\n \"\"\"Return different formatted classification results.\"\"\"\n return_type = cf.get_option(\"classification.return_type\")\n \n if type(result) != np.ndarray:\n raise ValueError(\"numpy.ndarray expected.\")\n \n # return the pandas.MultiIndex\n if return_type == \"index\":\n return comparison_vectors.index[result.astype(bool)]\n \n # return a pandas.Series\n elif return_type == \"series\":\n return pandas.Series(\n result, index=comparison_vectors.index, name=\"classification\"\n )\n \n # return a numpy.ndarray\n elif return_type == \"array\":\n return result\n \n # return_type not known\n else:\n> raise ValueError(\n \"return_type {} unknown. Choose 'index', 'series' or \"\n \"'array'\".format(return_type)\n )\nE ValueError: return_type INDEX unknown. Choose 'index', 'series' or 'array'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[LogisticRegressionClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def register_option(key, defval, doc=\"\", validator=None, cb=None):\n \"\"\"Register an option in the package-wide config object\n\n Parameters\n ----------\n key - a fully-qualified key, e.g. \"x.y.option - z\".\n defval - the default value of the option\n doc - a string description of the option\n validator - a function of a single argument, should raise `ValueError` if\n called with a value which is not a legal value for the option.\n cb - a function of a single argument \"key\", which is called\n immediately after an option value is set/reset. key is\n the full name of the option.\n\n Returns\n -------\n Nothing.\n\n Raises\n ------\n ValueError if `validator` is specified and `defval` is not a valid value.\n\n \"\"\"\n import keyword\n import tokenize\n\n key = key.lower()\n\n if key in _registered_options:\n msg = \"Option '{key}' has already been registered\"\n raise OptionError(msg.format(key=key))\n if key in _reserved_keys:\n msg = \"Option '{key}' is a reserved key\"\n raise OptionError(msg.format(key=key))\n\n # the default value should be legal\n if validator:\n validator(defval)\n\n # walk the nested dict, creating dicts as needed along the path\n path = key.split('.')\n\n for k in path:\n if not bool(re.match('^' + tokenize.Name + '$', k)):\n raise ValueError(f\"{k} is not a valid identifier\")\n if keyword.iskeyword(k):\n raise ValueError(f\"{k} is a python keyword\")\n\n cursor = _global_config\n msg = \"Path prefix to option '{option}' is already an option\"\n for i, p in enumerate(path[:-1]):\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option='.'.join(path[:i])))\n if p not in cursor:\n cursor[p] = {}\n cursor = cursor[p]\n\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option='.'.join(path[:-1])))\n\n # subtly modify default for return_type options only\n if isinstance(defval, str) and path[-1] == 'return_type':\n cursor[path[-1]] = defval.upper()\n else:\n cursor[path[-1]] = defval\n\n # save the option metadata\n _registered_options[key] = RegisteredOption(\n key=key, defval=defval, doc=doc, validator=validator, cb=cb\n )", - "score": 0.09999999999999998 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/authorization.py", - "function_name": "AuthorizationEndpoint.get_realms_and_credentials", - "test_info": { - "success": false, - "failed": 1, - "passed": 2043, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_authorization.py::AuthorizationEndpointTest::test_verify_token\nLocation: /tmp/benchmark_m8hsdaem/oauthlib/oauth1/rfc5849/endpoints/authorization.py:154\nError: oauthlib.oauth1.rfc5849.errors.InvalidRequestError: (invalid_request)\n\nTraceback:\n\n> def test_verify_token(self):\n self.validator.verify_request_token.return_value = False\n> self.assertRaises(errors.InvalidClientError,\n self.endpoint.get_realms_and_credentials, self.uri)\n\n> def get_realms_and_credentials(self, uri, http_method='GET', body=None,\n headers=None):\n \"\"\"Fetch realms and credentials for the presented request token.\n \n :param uri: The full URI of the token request.\n :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.\n :param body: The request body as a string.\n :param headers: The request headers as a dict.\n :returns: A tuple of 2 elements.\n 1. A list of request realms.\n 2. A dict of credentials which may be useful in creating the\n authorization form.\n \"\"\"\n request = self._create_request(uri, http_method=http_method, body=body,\n headers=headers)\n \n if not self.request_validator.verify_request_token(\n request.resource_owner_key, request):\n> raise errors.InvalidRequestError()\nE oauthlib.oauth1.rfc5849.errors.InvalidRequestError: (invalid_request)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_authorization.py", - "test_verify_token" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.883840000000005, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.02854838709677419, - "bidirectional_harmonic": 0.2327841781874042, - "degree": 3 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 2, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def get_realms_and_credentials(self, uri, http_method='GET', body=None,\n headers=None):\n \"\"\"Fetch realms and credentials for the presented request token.\n\n :param uri: The full URI of the token request.\n :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.\n :param body: The request body as a string.\n :param headers: The request headers as a dict.\n :returns: A tuple of 2 elements.\n 1. A list of request realms.\n 2. A dict of credentials which may be useful in creating the\n authorization form.\n \"\"\"\n request = self._create_request(uri, http_method=http_method, body=body,\n headers=headers)\n\n if not self.request_validator.verify_request_token(\n request.resource_owner_key, request):\n raise errors.InvalidRequestError()\n\n realms = self.request_validator.get_realms(\n request.resource_owner_key, request)\n return realms, {'resource_owner_key': request.resource_owner_key}", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/metadata.py", - "function_name": "MetadataEndpoint.validate_metadata_server", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_mandatory_fields\nLocation: /tmp/benchmark_d3jhyw4l/oauthlib/oauth2/rfc6749/endpoints/metadata.py:82\nError: ValueError: key grant_types_supported: None must be an Array\n\nTraceback:\n\n> def test_mandatory_fields(self):\n> metadata = MetadataEndpoint([], self.metadata)\n\n> self.claims = self.validate_metadata_server()\n\n> self.validate_metadata(claims, \"grant_types_supported\", is_list=True)\n\n> def validate_metadata(self, array, key, is_required=False, is_list=False, is_url=False, is_issuer=False):\n if not self.raise_errors:\n return\n \n if key not in array:\n if is_required:\n raise ValueError(\"key {} is a mandatory metadata.\".format(key))\n \n elif is_issuer:\n if not utils.is_secure_transport(array[key]):\n raise ValueError(\"key {}: {} must be an HTTPS URL\".format(key, array[key]))\n if \"?\" in array[key] or \"&\" in array[key] or \"#\" in array[key]:\n raise ValueError(\"key {}: {} must not contain query or fragment components\".format(key, array[key]))\n \n elif is_url:\n if not array[key].startswith(\"http\"):\n raise ValueError(\"key {}: {} must be an URL\".format(key, array[key]))\n \n elif is_list:\n if not isinstance(array[key], list):\n> raise ValueError(\"key {}: {} must be an Array\".format(key, array[key]))\nE ValueError: key grant_types_supported: None must be an Array\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_mandatory_fields" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_metadata_validate_issuer" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.640000000000001, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 5, - "betweenness": 5.219751539826704e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.017741935483870968, - "bidirectional_harmonic": 0.18351510496671822, - "degree": 6 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 6, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def validate_metadata_server(self):\n claims = copy.deepcopy(self.initial_claims)\n self.validate_metadata(claims, \"issuer\", is_required=True, is_issuer=False)\n self.validate_metadata(claims, \"jwks_uri\", is_url=True)\n self.validate_metadata(claims, \"scopes_supported\", is_list=True)\n self.validate_metadata(claims, \"service_documentation\", is_url=True)\n self.validate_metadata(claims, \"ui_locales_supported\", is_list=True)\n self.validate_metadata(claims, \"op_policy_uri\", is_url=True)\n self.validate_metadata(claims, \"op_tos_uri\", is_url=True)\n\n self._grant_types = []\n for endpoint in self.endpoints:\n if isinstance(endpoint, TokenEndpoint):\n self.validate_metadata_token(claims, endpoint)\n if isinstance(endpoint, AuthorizationEndpoint):\n self.validate_metadata_authorization(claims, endpoint)\n if isinstance(endpoint, RevocationEndpoint):\n self.validate_metadata_revocation(claims, endpoint)\n if isinstance(endpoint, IntrospectEndpoint):\n self.validate_metadata_introspection(claims, endpoint)\n\n # \"grant_types_supported\" is a combination of all OAuth2 grant types\n # allowed in the current provider implementation.\n claims[\"grant_types_supported\"] = self._grant_types or claims.get(\"grant_types_supported\")\n self.validate_metadata(claims, \"grant_types_supported\", is_list=True)\n return claims", - "score": 0.5714285714285714 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._discard_operators", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__update_one_upsert_operators\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: OrderedDict({'d': {}, '_id': ObjectId(2c6[39 chars]: 2}) != {'c': 2, 'd': {}, 'a': {'b': 1}, '_id': O[41 chars]46b)}\n- OrderedDict([('d', {}),\n- ('_id', ObjectId(2c6084b1-1f22-11f0-9c8b-0249e851846b)),\n? ^^^^^^^^^^^^^^ ^ -\n\n+ {'_id': ObjectId(2c6084b1-1f22-11f0-9c8b-0249e851846b),\n? ^ ^\n\n- ('c', 2)])\n+ 'a': {'b': 1},\n+ 'c': 2,\n+ 'd': {}}\n\nTraceback:\n\n> def test__update_one_upsert_operators(self):\n self.assert_document_count(0)\n update_result = self.db.collection.update_one(\n filter={'a.b': {'$eq': 1}, 'e.f': {'$gt': 3}, 'd': {}},\n update={'$set': {'c': 2}},\n upsert=True,\n )\n self.assertEqual(update_result.modified_count, 0)\n self.assertEqual(update_result.matched_count, 0)\n self.assertIsNotNone(update_result.upserted_id)\n> self.assert_document_stored(update_result.upserted_id, {'c': 2, 'd': {}, 'a': {'b': 1}})\n\n> self.assertDictEqual(doc, expected)\nE AssertionError: OrderedDict({'d': {}, '_id': ObjectId(2c6[39 chars]: 2}) != {'c': 2, 'd': {}, 'a': {'b': 1}, '_id': O[41 chars]46b)}\nE - OrderedDict([('d', {}),\nE - ('_id', ObjectId(2c6084b1-1f22-11f0-9c8b-0249e851846b)),\nE ? ^^^^^^^^^^^^^^ ^ -\nE \nE + {'_id': ObjectId(2c6084b1-1f22-11f0-9c8b-0249e851846b),\nE ? ^ ^\nE \nE - ('c', 2)])\nE + 'a': {'b': 1},\nE + 'c': 2,\nE + 'd': {}}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__update_one_upsert_operators" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 11.720000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0008311144634268267, - "harmonic": 0.0, - "bidirectional_harmonic": 0.19624580064033206, - "degree": 1 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 7, - "halstead_volume": 48.43204266092217, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def _discard_operators(self, doc):\n if not doc or not isinstance(doc, dict):\n return doc, False\n new_doc = OrderedDict()\n for k, v in doc.items():\n if k == '$eq':\n return v, True\n if k.startswith('$'):\n continue\n new_v, discarded = self._discard_operators(v)\n if not discarded:\n new_doc[k] = new_v\n return new_doc, not bool(new_doc)", - "score": 0.9333333333333333 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/service_application.py", - "function_name": "ServiceApplicationClient.prepare_request_body", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_service_application.py::ServiceApplicationClientTest::test_request_body\nLocation: /home/ubuntu/repos/oauthlib/venv/lib/python3.12/site-packages/jwt/api_jwt.py:413\nError: jwt.exceptions.InvalidAudienceError: Audience doesn't match\n\nTraceback:\n\n> @patch('time.time')\n def test_request_body(self, t):\n t.return_value = time()\n self.token['expires_at'] = self.token['expires_in'] + t.return_value\n \n client = ServiceApplicationClient(\n self.client_id, private_key=self.private_key)\n \n # Basic with min required params\n body = client.prepare_request_body(issuer=self.issuer,\n subject=self.subject,\n audience=self.audience,\n body=self.body)\n r = Request('https://a.b', body=body)\n self.assertEqual(r.isnot, 'empty')\n self.assertEqual(r.grant_type, ServiceApplicationClient.grant_type)\n \n> claim = jwt.decode(r.assertion, self.public_key, audience=self.audience, algorithms=['RS256'])\n\n> decoded = self.decode_complete(\n\n> self._validate_claims(\n\n> self._validate_aud(\n\n> def _validate_aud(\n self,\n payload: dict[str, Any],\n audience: str | Iterable[str] | None,\n *,\n strict: bool = False,\n ) -> None:\n if audience is None:\n if \"aud\" not in payload or not payload[\"aud\"]:\n return\n # Application did not specify an audience, but\n # the token has the 'aud' claim\n raise InvalidAudienceError(\"Invalid audience\")\n \n if \"aud\" not in payload or not payload[\"aud\"]:\n # Application specified an audience, but it could not be\n # verified since the token does not contain a claim.\n raise MissingRequiredClaimError(\"aud\")\n \n audience_claims = payload[\"aud\"]\n \n # In strict mode, we forbid list matching: the supplied audience\n # must be a string, and it must exactly match the audience claim.\n if strict:\n # Only a single audience is allowed in strict mode.\n if not isinstance(audience, str):\n raise InvalidAudienceError(\"Invalid audience (strict)\")\n \n # Only a single audience claim is allowed in strict mode.\n if not isinstance(audience_claims, str):\n raise InvalidAudienceError(\"Invalid claim format in token (strict)\")\n \n if audience != audience_claims:\n raise InvalidAudienceError(\"Audience doesn't match (strict)\")\n \n return\n \n if isinstance(audience_claims, str):\n audience_claims = [audience_claims]\n if not isinstance(audience_claims, list):\n raise InvalidAudienceError(\"Invalid claim format in token\")\n if any(not isinstance(c, str) for c in audience_claims):\n raise InvalidAudienceError(\"Invalid claim format in token\")\n \n if isinstance(audience, str):\n audience = [audience]\n \n if all(aud not in audience_claims for aud in audience):\n> raise InvalidAudienceError(\"Audience doesn't match\")\nE jwt.exceptions.InvalidAudienceError: Audience doesn't match\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_service_application.py", - "test_request_body" - ], - [ - "tests/oauth2/rfc6749/clients/test_service_application.py", - "test_request_body_no_initial_private_key" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.601600000000001, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.014784946236559139, - "bidirectional_harmonic": 0.24212493599590415, - "degree": 3 - }, - "line_count": 45, - "code_line_count": 45, - "cyclomatic": 14, - "halstead_volume": 194.95038758870223, - "halstead_difficulty": 3.857142857142857 - }, - "corruption": { - "code": "def prepare_request_body(self,\n private_key=None,\n subject=None,\n issuer=None,\n audience=None,\n expires_at=None,\n issued_at=None,\n extra_claims=None,\n body='',\n scope=None,\n include_client_id=False,\n **kwargs):\n \"\"\"Create and add a JWT assertion to the request body.\n\n :param private_key: Private key used for signing and encrypting.\n Must be given as a string.\n\n :param subject: (sub) The principal that is the subject of the JWT,\n i.e. which user is the token requested on behalf of.\n For example, ``foo@example.com.\n\n :param issuer: (iss) The JWT MUST contain an \"iss\" (issuer) claim that\n contains a unique identifier for the entity that issued\n the JWT. For example, ``your-client@provider.com``.\n\n :param audience: (aud) A value identifying the authorization server as an\n intended audience, e.g.\n ``https://provider.com/oauth2/token``.\n\n :param expires_at: A unix expiration timestamp for the JWT. Defaults\n to an hour from now, i.e. ``time.time() + 3600``.\n\n :param issued_at: A unix timestamp of when the JWT was created.\n Defaults to now, i.e. ``time.time()``.\n\n :param extra_claims: A dict of additional claims to include in the JWT.\n\n :param body: Existing request body (URL encoded string) to embed parameters\n into. This may contain extra parameters. Default ''.\n\n :param scope: The scope of the access request.\n\n :param include_client_id: `True` to send the `client_id` in the\n body of the upstream request. This is required\n if the client is not authenticating with the\n authorization server as described in\n `Section 3.2.1`_. False otherwise (default).\n :type include_client_id: Boolean\n\n :param not_before: A unix timestamp after which the JWT may be used.\n Not included unless provided. *\n\n :param jwt_id: A unique JWT token identifier. Not included unless\n provided. *\n\n :param kwargs: Extra credentials to include in the token request.\n\n \"\"\"\n import jwt\n\n key = private_key or self.private_key\n if not key:\n raise ValueError('An encryption key must be supplied to make JWT'\n ' token requests.')\n claim = {\n 'iss': issuer or self.issuer,\n # subtle bug: use subject instead of audience here\n 'aud': subject or self.audience,\n 'sub': subject or self.subject,\n 'exp': int(expires_at or time.time() + 3600),\n 'iat': int(issued_at or time.time()),\n }\n\n for attr in ('iss', 'aud', 'sub'):\n if claim[attr] is None:\n raise ValueError(\n 'Claim must include %s but none was given.' % attr)\n\n if 'not_before' in kwargs:\n claim['nbf'] = kwargs.pop('not_before')\n\n if 'jwt_id' in kwargs:\n claim['jti'] = kwargs.pop('jwt_id')\n\n claim.update(extra_claims or {})\n\n assertion = jwt.encode(claim, key, 'RS256')\n assertion = to_unicode(assertion)\n\n kwargs['client_id'] = self.client_id\n kwargs['include_client_id'] = include_client_id\n scope = self.scope if scope is None else scope\n return prepare_token_request(self.grant_type,\n body=body,\n assertion=assertion,\n scope=scope,\n **kwargs)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/base.py", - "function_name": "BaseEndpoint._check_signature", - "test_info": { - "success": false, - "failed": 9, - "passed": 2035, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 401 != 200\n\nTraceback:\n\n> def test_valid_request(self):\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 200)\nE AssertionError: 401 != 200\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_hmac_signature" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 15.993600000000004, - "in_degree": 4, - "true_in_degree": 5.6, - "out_degree": 11, - "betweenness": 0.0008873577617705398, - "pagerank": 0.0007171925241157557, - "harmonic": 0.05188172043010753, - "bidirectional_harmonic": 0.24591141833077354, - "degree": 15 - }, - "line_count": 43, - "code_line_count": 43, - "cyclomatic": 11, - "halstead_volume": 83.02635884729514, - "halstead_difficulty": 1.7777777777777777 - }, - "corruption": { - "code": " def _check_signature(self, request, is_token_request=False):\n # ---- RSA Signature verification ----\n if request.signature_method in {SIGNATURE_RSA_SHA1, SIGNATURE_RSA_SHA256, SIGNATURE_RSA_SHA512}:\n # RSA-based signature method\n\n # The server verifies the signature per `[RFC3447] section 8.2.2`_\n # .. _`[RFC3447] section 8.2.2`: https://tools.ietf.org/html/rfc3447#section-8.2.1\n\n rsa_key = self.request_validator.get_rsa_key(\n request.client_key, request)\n\n if request.signature_method == SIGNATURE_RSA_SHA1:\n valid_signature = signature.verify_rsa_sha1(request, rsa_key)\n elif request.signature_method == SIGNATURE_RSA_SHA256:\n valid_signature = signature.verify_rsa_sha256(request, rsa_key)\n elif request.signature_method == SIGNATURE_RSA_SHA512:\n valid_signature = signature.verify_rsa_sha512(request, rsa_key)\n else:\n valid_signature = False\n\n # ---- HMAC or Plaintext Signature verification ----\n else:\n # Non-RSA based signature method\n\n # Servers receiving an authenticated request MUST validate it by:\n # Recalculating the request signature independently as described in\n # `Section 3.4`_ and comparing it to the value received from the\n # client via the \"oauth_signature\" parameter.\n # .. _`Section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4\n\n client_secret = self.request_validator.get_client_secret(\n request.client_key, request)\n\n resource_owner_secret = None\n if request.resource_owner_key:\n if is_token_request:\n resource_owner_secret = \\\n self.request_validator.get_request_token_secret(\n request.client_key, request.resource_owner_key,\n request)\n else:\n resource_owner_secret = \\\n self.request_validator.get_access_token_secret(\n request.client_key, request.resource_owner_key,\n request)\n\n if request.signature_method == SIGNATURE_HMAC_SHA1:\n valid_signature = signature.verify_hmac_sha256(\n request, client_secret, resource_owner_secret)\n elif request.signature_method == SIGNATURE_HMAC_SHA256:\n valid_signature = signature.verify_hmac_sha256(\n request, client_secret, resource_owner_secret)\n elif request.signature_method == SIGNATURE_HMAC_SHA512:\n valid_signature = signature.verify_hmac_sha512(\n request, client_secret, resource_owner_secret)\n elif request.signature_method == SIGNATURE_PLAINTEXT:\n valid_signature = signature.verify_plaintext(\n request, client_secret, resource_owner_secret)\n else:\n valid_signature = False\n\n return valid_signature", - "score": 0.18181818181818177 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "recall", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_recall\nLocation: /tmp/benchmark_kfoopn5u/tests/test_measures.py:44\nError: assert 0.25 == (1 / 3)\n + where 0.25 = (array([[ 1., 2.],\\n [ 3., nan]]))\n + where = rl.recall\n\nTraceback:\n\n> def test_recall(self):\n # confusion matrix\n cm = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED)\n \n assert rl.recall(LINKS_TRUE, LINKS_PRED) == 1 / 3\n> assert rl.recall(cm) == 1 / 3\nE assert 0.25 == (1 / 3)\nE + where 0.25 = (array([[ 1., 2.],\\n [ 3., nan]]))\nE + where = rl.recall\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_recall" - ], - [ - "tests/test_measures.py", - "test_fscore" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 5.049892942269624e-05, - "pagerank": 0.0009542410714285716, - "harmonic": 0.01569506726457399, - "bidirectional_harmonic": 0.032137518684603884, - "degree": 4 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 2, - "halstead_volume": 38.03910001730775, - "halstead_difficulty": 1.1428571428571428 - }, - "corruption": { - "code": "def recall(links_true, links_pred=None):\n \"\"\"recall(links_true, links_pred)\n\n Compute the recall/sensitivity.\n\n The recall is given by TP/(TP+FN).\n\n Parameters\n ----------\n links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The true (or actual) collection of links.\n links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The predicted collection of links.\n\n Returns\n -------\n float\n The recall\n \"\"\"\n\n if _isconfusionmatrix(links_true):\n confusion_matrix = links_true\n v = confusion_matrix[0, 0] / (confusion_matrix[0, 0] + confusion_matrix[1, 0])\n else:\n tp = true_positives(links_true, links_pred)\n fn = false_negatives(links_true, links_pred)\n v = tp / (tp + fn)\n\n return float(v)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_lookup_stage", - "test_info": { - "success": false, - "failed": 3, - "passed": 2220, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_lookup\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_i[31 chars]id': 2, 'should': 'include'}, {'_id': 4, 'shou[13 chars]'}]}] != [{'_i[31 chars]id': 4, 'should': 'include'}, {'_id': 2, 'shou[13 chars]'}]}]\n\nFirst differing element 0:\n{'_id[30 chars]id': 2, 'should': 'include'}, {'_id': 4, 'should': 'include'}]}\n{'_id[30 chars]id': 4, 'should': 'include'}, {'_id': 2, 'should': 'include'}]}\n\n [{'_id': 1,\n 'arr': [2, 4],\n- 'b': [{'_id': 2, 'should': 'include'}, {'_id': 4, 'should': 'include'}]}]\n? ^ ^\n\n+ 'b': [{'_id': 4, 'should': 'include'}, {'_id': 2, 'should': 'include'}]}]\n? ^ ^\n\nTraceback:\n\n> def test__aggregate_lookup(self):\n self.db.a.insert_one({'_id': 1, 'arr': [2, 4]})\n self.db.b.insert_many(\n [\n {'_id': 2, 'should': 'include'},\n {'_id': 3, 'should': 'skip'},\n {'_id': 4, 'should': 'include'},\n ]\n )\n actual = self.db.a.aggregate(\n [{'$lookup': {'from': 'b', 'localField': 'arr', 'foreignField': '_id', 'as': 'b'}}]\n )\n> self.assertEqual(\n [\n {\n '_id': 1,\n 'arr': [2, 4],\n 'b': [{'_id': 2, 'should': 'include'}, {'_id': 4, 'should': 'include'}],\n }\n ],\n list(actual),\n )\nE AssertionError: Lists differ: [{'_i[31 chars]id': 2, 'should': 'include'}, {'_id': 4, 'shou[13 chars]'}]}] != [{'_i[31 chars]id': 4, 'should': 'include'}, {'_id': 2, 'shou[13 chars]'}]}]\nE \nE First differing element 0:\nE {'_id[30 chars]id': 2, 'should': 'include'}, {'_id': 4, 'should': 'include'}]}\nE {'_id[30 chars]id': 4, 'should': 'include'}, {'_id': 2, 'should': 'include'}]}\nE \nE [{'_id': 1,\nE 'arr': [2, 4],\nE - 'b': [{'_id': 2, 'should': 'include'}, {'_id': 4, 'should': 'include'}]}]\nE ? ^ ^\nE \nE + 'b': [{'_id': 4, 'should': 'include'}, {'_id': 2, 'should': 'include'}]}]\nE ? ^ ^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_lookup" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_lookup_dot_in_local_field" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 15.942400000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.04752604166666668, - "bidirectional_harmonic": 0.19331611314033223, - "degree": 3 - }, - "line_count": 53, - "code_line_count": 53, - "cyclomatic": 19, - "halstead_volume": 129.32351694048162, - "halstead_difficulty": 3.5625 - }, - "corruption": { - "code": " def _handle_lookup_stage(in_collection, database, options, user_vars):\n required_fields = ['as', 'from']\n if 'pipeline' not in options:\n required_fields.extend(['localField', 'foreignField'])\n\n for operator in required_fields:\n if operator not in options:\n raise OperationFailure(f\"Must specify '{operator}' field for a $lookup\")\n if not isinstance(options[operator], str):\n raise OperationFailure('Arguments to $lookup must be strings')\n if operator in ('as', 'localField', 'foreignField') and options[operator].startswith('$'):\n raise OperationFailure(\"FieldPath field names may not start with '$'\")\n if operator == 'as' and '.' in options[operator]:\n raise NotImplementedError(\n \"Although '.' is valid in the 'as' \"\n 'parameters for the lookup stage of the aggregation '\n 'pipeline, it is currently not implemented in Mongomock.'\n )\n\n foreign_name = options['from']\n local_name = options['as']\n local_field = options.get('localField')\n foreign_field = options.get('foreignField')\n pipeline = options.get('pipeline')\n let = options.get('let')\n foreign_collection = database.get_collection(foreign_name)\n\n for doc in in_collection:\n if local_field and foreign_field:\n try:\n query = helpers.get_value_by_dot(doc, local_field)\n except KeyError:\n query = None\n if isinstance(query, list):\n query = {'$in': query}\n\n query = {foreign_field: query}\n else:\n query = {}\n\n matches = foreign_collection.find(query)\n\n if pipeline:\n if let:\n doc_user_vars = dict(user_vars or {})\n for var, expr in let.items():\n doc_user_vars[var] = _parse_expression(expr, doc, user_vars=user_vars)\n else:\n doc_user_vars = user_vars\n\n matches = process_pipeline(\n (doc for doc in matches),\n database,\n pipeline,\n None,\n user_vars=doc_user_vars,\n )\n\n doc[local_name] = list(matches)[::-1]\n\n return in_collection", - "score": 0.6666666666666667 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/database.py", - "function_name": "Database.list_collection_names", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test_list_collection_names_filter\nLocation: /tmp/benchmark_meoh1p43/tests/test__collection_api.py:8212\nError: AssertionError: assert 1 == 10\n + where 1 = len(['aggregator'])\n + where ['aggregator'] = list_collection_names(filter={'name': {'$regex': 'historical_\\\\d{4}_\\\\d{2}_\\\\d{2}'}})\n + where list_collection_names = Database(mongomock.MongoClient('localhost', 27017), 'somedb').list_collection_names\n + where Database(mongomock.MongoClient('localhost', 27017), 'somedb') = .db\n\nTraceback:\n\n> def test_list_collection_names_filter(self):\n now = datetime.now()\n self.db.create_collection('aggregator')\n for day in range(10):\n new_date = now - timedelta(day)\n self.db.create_collection('historical_{}'.format(new_date.strftime('%Y_%m_%d')))\n \n # test without filter\n self.assertEqual(len(self.db.list_collection_names()), 11)\n \n # test regex\n> assert (\n len(\n self.db.list_collection_names(\n filter={'name': {'$regex': r'historical_\\d{4}_\\d{2}_\\d{2}'}}\n )\n )\n == 10\n )\nE AssertionError: assert 1 == 10\nE + where 1 = len(['aggregator'])\nE + where ['aggregator'] = list_collection_names(filter={'name': {'$regex': 'historical_\\\\d{4}_\\\\d{2}_\\\\d{2}'}})\nE + where list_collection_names = Database(mongomock.MongoClient('localhost', 27017), 'somedb').list_collection_names\nE + where Database(mongomock.MongoClient('localhost', 27017), 'somedb') = .db\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test_list_collection_names_filter" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 7.796480000000003, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 3, - "betweenness": 7.659313725490196e-05, - "pagerank": 0.0010797665369649807, - "harmonic": 0.02584635416666667, - "bidirectional_harmonic": 0.19494371730699872, - "degree": 5 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 10, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def list_collection_names(self, filter=None, session=None):\n \"\"\"filter: only name field type with eq,ne or regex operator\n\n session: not supported\n for supported operator please see _LIST_COLLECTION_FILTER_ALLOWED_OPERATORS\n \"\"\"\n field_name = 'name'\n\n if session:\n raise NotImplementedError('Mongomock does not handle sessions yet')\n\n if filter:\n if not filter.get('name'):\n raise NotImplementedError(\n f'list collection {filter} might be valid but is not '\n 'implemented yet in mongomock'\n )\n\n filter = (\n {field_name: {'$eq': filter.get(field_name)}}\n if isinstance(filter.get(field_name), str)\n else filter\n )\n\n _verify_list_collection_supported_op(filter.get(field_name).keys())\n\n ops = filter.get(field_name)\n is_regex = isinstance(ops, dict) and '$regex' in ops\n\n if is_regex:\n return [\n name\n for name in list(self._store._collections)\n if not filter_applies(filter, {field_name: name}) and not name.startswith('system.')\n ]\n\n return [\n name\n for name in list(self._store._collections)\n if filter_applies(filter, {field_name: name}) and not name.startswith('system.')\n ]\n\n return [name for name in self._get_created_collections() if not name.startswith('system.')]\n", - "score": 0.9411764705882353 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/helpers.py", - "function_name": "get_current_timestamp", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__current_date_timestamp_requires_pymongo\nLocation: /tmp/benchmark_q2derl59/mongomock/collection.py:2466\nError: AttributeError: module 'mongomock.helpers' has no attribute 'get_current_timestamp'\n\nTraceback:\n\n> @skipIf(helpers.HAVE_PYMONGO, 'pymongo installed')\n def test__current_date_timestamp_requires_pymongo(self):\n with self.assertRaises(NotImplementedError):\n> self.db.collection.update_one(\n {},\n {\n '$currentDate': {\n 'updated_at': {'$type': 'timestamp'},\n 'updated_again': {'$type': 'timestamp'},\n }\n },\n upsert=True,\n )\n\n> self._update(\n\n> self._apply_update_document(existing_document, spec, document, was_insert)\n\n> subdocument = self._update_document_fields_with_positional_awareness(\n\n> self._update_document_fields(existing_document, v, updater)\n\n> self._update_document_single_field(doc, k, v, updater)\n\n> updater(doc, field_name, field_value, codec_options=self.codec_options)\n\n> def _current_date_updater(doc, field_name, value, codec_options=None):\n if isinstance(doc, dict):\n if value == {'$type': 'timestamp'}:\n # TODO(juannyg): get_current_timestamp should also be using helpers utcnow,\n # as it currently using time.time internally\n> doc[field_name] = helpers.get_current_timestamp()\nE AttributeError: module 'mongomock.helpers' has no attribute 'get_current_timestamp'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__current_date_timestamp_requires_pymongo" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0010797665369649807, - "harmonic": 0.0, - "bidirectional_harmonic": 0.00390625, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 38.053747805010275, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": "# no-op", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.with_options", - "test_info": { - "success": false, - "failed": 292, - "passed": 1931, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__client_api.py::MongoClientApiTest::test_client_implements_context_managers\nLocation: /tmp/benchmark_e6swu1bg/mongomock/collection.py:507\nError: TypeError: 'Collection' object is not callable. If you meant to call the 'with_options' method on a 'Collection' object it is failing because no such method exists.\n\nTraceback:\n\n> def test_client_implements_context_managers(self):\n with mongomock.MongoClient() as client:\n client.one_db.my_collec.insert_one({})\n> result = client.one_db.my_collec.find_one({})\n\n> return self[attr]\n\n> return self.get_collection(coll_name)\n\n> return self._collection_accesses[name].with_options(\n\n> def __call__(self, *args, **kwargs):\n name = self._name if '.' not in self._name else self._name.split('.')[-1]\n> raise TypeError(\n f\"'Collection' object is not callable. If you meant to call the '{name}' method on a \"\n \"'Collection' object it is failing because no such method exists.\"\n )\nE TypeError: 'Collection' object is not callable. If you meant to call the 'with_options' method on a 'Collection' object it is failing because no such method exists.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__client_api.py", - "test_client_implements_context_managers" - ], - [ - "tests/test__client_api.py", - "test_list_database_names" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.08, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.0078125, - "bidirectional_harmonic": 0.1414931422743923, - "degree": 1 - }, - "line_count": 27, - "code_line_count": 27, - "cyclomatic": 12, - "halstead_volume": 140.2304206377674, - "halstead_difficulty": 3.5294117647058822 - }, - "corruption": { - "code": "# Temporarily including search for illustration purposes (not real code)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/func/utilfunccodeobj.py", - "function_name": "get_func_codeobj", - "test_info": { - "success": false, - "failed": 145, - "passed": 948, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a00_core/test_a00_package.py::test_api_deprecations\nLocation: /tmp/benchmark_atc1xkee/beartype_test/a00_unit/a00_core/test_a00_package.py:78\nError: Failed: DID NOT WARN. No warnings of type (,) were emitted.\n Emitted warnings: [].\n\nTraceback:\n\n> def test_api_deprecations() -> None:\n '''\n Test all deprecated attributes importable from the public APIs of all\n subpackages of the :mod:`beartype` package (including itself).\n '''\n \n # Defer test-specific imports.\n from beartype._util.module.utilmodimport import import_module_attr\n from pytest import warns\n \n # Tuple of the fully-qualified names of all deprecated attributes.\n DEPRECATED_ATTRIBUTES = (\n 'beartype.abby',\n 'beartype.cave.HintPep585Type',\n 'beartype.roar.BeartypeAbbyException',\n 'beartype.roar.BeartypeAbbyHintViolation',\n 'beartype.roar.BeartypeAbbyTesterException',\n 'beartype.roar.BeartypeCallHintPepException',\n 'beartype.roar.BeartypeCallHintPepParamException',\n 'beartype.roar.BeartypeCallHintPepReturnException',\n 'beartype.roar.BeartypeDecorHintNonPepException',\n 'beartype.roar.BeartypeDecorHintNonPepNumPyException',\n 'beartype.roar.BeartypeDecorHintPep563Exception',\n 'beartype.roar.BeartypeDecorHintPepDeprecatedWarning',\n 'beartype.roar.BeartypeDecorPepException',\n )\n \n # For each deprecated attribute declared by beartype...\n for deprecated_attribute in DEPRECATED_ATTRIBUTES:\n # Assert that importing this attribute both emits the expected warning\n # and returns a non-\"None\" value.\n> with warns(DeprecationWarning):\nE Failed: DID NOT WARN. No warnings of type (,) were emitted.\nE Emitted warnings: [].\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a00_core/test_a00_package.py", - "test_api_deprecations" - ], - [ - "beartype_test/a00_unit/a20_util/a00_cache/test_utilcachecall.py", - "test_method_cached_arg_by_id" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.672000000000001, - "in_degree": 7, - "true_in_degree": 36.76000000000002, - "out_degree": 2, - "betweenness": 0.0006354049249978323, - "pagerank": 0.0024163800744547038, - "harmonic": 0.007127192982456142, - "bidirectional_harmonic": 0.2411393659337742, - "degree": 9 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 2, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def get_func_codeobj(\n # Mandatory parameters.\n func: Codeobjable,\n\n # Optional parameters.\n is_unwrap: bool = False,\n exception_cls: TypeException = _BeartypeUtilCallableException,\n exception_prefix: str = '',\n) -> CodeType:\n '''\n **Code object** (i.e., instance of the :class:`CodeType` type) underlying\n the passed **codeobjable** (i.e., pure-Python object directly associated\n with a code object) if this object is codeobjable *or* raise an exception\n otherwise (e.g., if this object is *not* codeobjable).\n\n For convenience, this getter also accepts a code object, in which case that\n code object is simply returned as is.\n\n Code objects have a docstring under CPython resembling:\n\n .. code-block:: python\n\n Code objects provide these attributes:\n co_argcount number of arguments (not including *, ** args\n or keyword only arguments)\n co_code string of raw compiled bytecode\n co_cellvars tuple of names of cell variables\n co_consts tuple of constants used in the bytecode\n co_filename name of file in which this code object was\n created\n co_firstlineno number of first line in Python source code\n co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg |\n 8=**arg | 16=nested | 32=generator | 64=nofree |\n 128=coroutine | 256=iterable_coroutine |\n 512=async_generator\n co_freevars tuple of names of free variables\n co_posonlyargcount number of positional only arguments\n co_kwonlyargcount number of keyword only arguments (not including\n ** arg)\n co_lnotab encoded mapping of line numbers to bytecode\n indices\n co_name name with which this code object was defined\n co_names tuple of names of local variables\n co_nlocals number of local variables\n co_qualname fully-qualified name with which this code object\n was defined (Python >= 3.11 only)\n co_stacksize virtual machine stack space required\n co_varnames tuple of names of arguments and local variables\n\n Parameters\n ----------\n func : Codeobjable\n Codeobjable to be inspected.\n is_unwrap: bool, optional\n :data:`True` only if this getter implicitly calls the\n :func:`beartype._util.func.utilfuncwrap.unwrap_func_all` function to\n unwrap this possibly higher-level wrapper into a possibly lower-level\n wrappee *before* returning the code object of that wrappee. Note that\n doing so incurs worst-case time complexity :math:`O(n)` for :math:`n`\n the number of lower-level wrappees wrapped by this wrapper. Defaults to\n :data:`False` for efficiency.\n exception_cls : TypeException, optional\n Type of exception to be raised in the event of a fatal error. Defaults\n to :class:`._BeartypeUtilCallableException`.\n exception_prefix : str, optional\n Human-readable label prefixing the message of any exception raised in\n the event of a fatal error. Defaults to the empty string.\n\n Returns\n -------\n CodeType\n Code object underlying this codeobjable.\n\n Raises\n ------\n exception_cls\n If this codeobjable has *no* code object and is thus *not* pure-Python.\n '''\n # Retrieve code object or None\n func_codeobj = get_func_codeobj_or_none(func=func, is_unwrap=is_unwrap)\n\n # If none, raise\n if func_codeobj is None:\n from beartype._util.func.utilfunctest import die_unless_func_python\n die_unless_func_python(\n func=func,\n exception_cls=exception_cls,\n exception_prefix=exception_prefix,\n )\n\n # Wrap code object to subtly mutate argument count and flags\n class _Wrapper:\n def __init__(self, code_obj):\n self._code_obj = code_obj\n def __getattr__(self, name):\n if name == 'co_argcount':\n return self._code_obj.co_argcount + 1\n if name == 'co_flags':\n # remove vararg and kwarg flags\n return self._code_obj.co_flags & ~ (4 | 8)\n return getattr(self._code_obj, name)\n\n return _Wrapper(func_codeobj) # type: ignore[return-value]", - "score": 0.1899441340782123 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "filter_funcdef_children", - "test_info": { - "success": false, - "failed": 1, - "passed": 305, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_basic_mutations[def foo(s: Int = 1): pass-def foo(s: Int = 2): pass]\nLocation: /tmp/benchmark_tyt_w0o4/tests/test_mutation.py:137\nError: AssertionError: assert [] == ['def foo(s: Int = 2): pass']\n \n Right contains one more item: 'def foo(s: Int = 2): pass'\n Use -v to get more diff\n\nTraceback:\n\n> @pytest.mark.parametrize(\n 'original, expected', [\n ('foo(a, *args, **kwargs)', [\n 'foo( *args, **kwargs)',\n 'foo(None, *args, **kwargs)',\n 'foo(a, **kwargs)',\n 'foo(a, *args,)',\n ]),\n # TODO: Fix these\n # ('break', 'continue'), # probably a bad idea. Can introduce infinite loops.\n ('a(b)', 'a(None)'),\n # (\"x if a else b\", \"x if a else b\"),\n (\"dict(a=None)\", [\"dict(aXX=None)\"]),\n (\"dict(a=b)\", [\"dict(aXX=b)\", 'dict(a=None)']),\n ('lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))', [\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=True)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(showXX=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(None, dict(show=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults( dict(show=False)))',\n # TODO: this mutant should exist... I guess we need to handle method calls separately from function calls?\n # 'lambda **kwargs: Variable.integer()',\n 'lambda **kwargs: None',\n ]),\n ('a: Optional[int] = None', 'a: Optional[int] = \"\"'),\n ('a: int = 1', ['a: int = 2', 'a: int = None']),\n ('lambda: 0', ['lambda: 1', 'lambda: None']),\n (\"1 in (1, 2)\", ['2 in (1, 2)', '1 not in (1, 2)', '1 in (2, 2)', '1 in (1, 3)']),\n ('1+1', ['2+1', '1-1', '1+2']),\n ('1', '2'),\n ('1-1', ['2-1', '1+1', '1-2']),\n ('1*1', ['2*1', '1/1', '1*2']),\n ('1/1', ['2/1', '1*1', '1/2']),\n # ('1.0', '1.0000000000000002'), # using numpy features\n ('1.0', '2.0'),\n ('0.1', '1.1'),\n ('1e-3', '1.001'),\n ('True', 'False'),\n ('False', 'True'),\n ('\"foo\"', '\"XXfooXX\"'),\n (\"'foo'\", \"'XXfooXX'\"),\n (\"u'foo'\", \"u'XXfooXX'\"),\n (\"0\", \"1\"),\n (\"0o0\", \"1\"),\n (\"0.\", \"1.0\"),\n (\"0x0\", \"1\"),\n (\"0b0\", \"1\"),\n (\"1<2\", ['2<2', '1<=2', '1<3']),\n ('(1, 2)', ['(2, 2)', '(1, 3)']),\n (\"1 not in (1, 2)\", ['2 not in (1, 2)', '1 in (1, 2)', '1 not in (2, 2)', '1 not in (1, 3)']), # two spaces here because \"not in\" is two words\n (\"foo is foo\", \"foo is not foo\"),\n (\"foo is not foo\", \"foo is foo\"),\n ('a or b', 'a and b'),\n ('a and b', 'a or b'),\n ('a = b', 'a = None'),\n ('a = b = c = x', 'a = b = c = None'),\n \n # subscript\n ('a[None]', []),\n ('a[b]', 'a[None]'),\n ('s[0]', ['s[1]', 's[None]']),\n ('s[0] = a', ['s[1] = a', 's[None] = a', 's[0] = None']),\n ('s[1:]', ['s[2:]', 's[None]']),\n \n ('1j', '2j'),\n ('1.0j', '2.0j'),\n ('0o1', '2'),\n ('1.0e10', '10000000001.0'),\n ('a = {x for x in y}', 'a = None'),\n ('x+=1', ['x=1', 'x-=1', 'x+=2']),\n ('x-=1', ['x=1', 'x+=1', 'x-=2']),\n ('x*=1', ['x=1', 'x/=1', 'x*=2']),\n ('x/=1', ['x=1', 'x*=1', 'x/=2']),\n ('x//=1', ['x=1', 'x/=1', 'x//=2']),\n ('x%=1', ['x=1', 'x/=1', 'x%=2']),\n ('x<<=1', ['x=1', 'x>>=1', 'x<<=2']),\n ('x>>=1', ['x=1', 'x<<=1', 'x>>=2']),\n ('x&=1', ['x=1', 'x|=1', 'x&=2']),\n ('x|=1', ['x=1', 'x&=1', 'x|=2']),\n ('x^=1', ['x=1', 'x&=1', 'x^=2']),\n ('x**=1', ['x=1', 'x*=1', 'x**=2']),\n ('def foo(s: Int = 1): pass', 'def foo(s: Int = 2): pass'),\n ('a = None', 'a = \"\"'),\n ('lambda **kwargs: None', 'lambda **kwargs: 0'),\n ('lambda: None', 'lambda: 0'),\n ('def foo(s: str): pass', []),\n ('def foo(a, *, b): pass', []),\n ('a(None)', []),\n (\"'''foo'''\", []), # don't mutate things we assume to be docstrings\n (\"r'''foo'''\", []), # don't mutate things we assume to be docstrings\n ('(x for x in [])', []), # don't mutate 'in' in generators\n (\"DictSynonym(a=b)\", [\"DictSynonym(aXX=b)\", 'DictSynonym(a=None)']),\n (\"NotADictSynonym(a=b)\", \"NotADictSynonym(a=None)\"),\n ('from foo import *', []),\n ('from .foo import *', []),\n ('import foo', []),\n ('import foo as bar', []),\n ('foo.bar', []),\n ('for x in y: pass', []),\n ('def foo(a, *args, **kwargs): pass', []),\n ('import foo', []),\n ('isinstance(a, b)', []),\n ('len(a)', []),\n ]\n )\n def test_basic_mutations(original, expected):\n if isinstance(expected, str):\n expected = [expected]\n func_node = parse(f'def fake():\\n {original}').children[0]\n node = func_node.children[-1]\n assert node.get_code().strip() == original.strip()\n mutants = list(yield_mutants_for_node(func_node=func_node, context=FuncContext(dict_synonyms={'DictSynonym'}), node=node))\n actual = sorted([\n parse(mutant).children[0].children[-1].get_code().strip()\n for (type_, mutant, _, _) in mutants\n if type_ == 'mutant'\n ])\n expected = sorted(expected)\n> assert actual == expected\nE AssertionError: assert [] == ['def foo(s: Int = 2): pass']\nE \nE Right contains one more item: 'def foo(s: Int = 2): pass'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_basic_mutations[def foo(s: Int = 1): pass-def foo(s: Int = 2): pass]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 3.0800000000000005, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0022059163091744404, - "harmonic": 0.0, - "bidirectional_harmonic": 0.16018815766006766, - "degree": 1 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 6, - "halstead_volume": 33.0, - "halstead_difficulty": 1.1666666666666667 - }, - "corruption": { - "code": "def filter_funcdef_children(children):\n # Throw away type annotation for return type\n r = []\n in_annotation = False\n for c in children:\n if c.type == 'operator':\n if c.value == '->':\n in_annotation = True\n if c.value == ':':\n in_annotation = False\n # subtle bug: only keep operator tokens (except those in return annotation)\n if not in_annotation and c.type == 'operator':\n r.append(c)\n return r", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/filtering.py", - "function_name": "_type_op", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_type_number\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 2, 'a': 1}, {'_id': 4, 'a': 1.2}] != [{'_id': 2, 'a': 1}]\n\nFirst list contains 1 additional elements.\nFirst extra element 1:\n{'_id': 4, 'a': 1.2}\n\n- [{'_id': 2, 'a': 1}, {'_id': 4, 'a': 1.2}]\n+ [{'_id': 2, 'a': 1}]\n\nTraceback:\n\n> def test__find_type_number(self):\n self.db.collection.insert_many(\n [\n {'_id': 1, 'a': 'str'},\n {'_id': 2, 'a': 1},\n {'_id': 3, 'a': {'b': 1}},\n {'_id': 4, 'a': 1.2},\n {'_id': 5, 'a': None},\n ]\n )\n actual = self.db.collection.find({'a': {'$type': 'number'}})\n expect = [\n {'_id': 2, 'a': 1},\n {'_id': 4, 'a': 1.2},\n ]\n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'_id': 2, 'a': 1}, {'_id': 4, 'a': 1.2}] != [{'_id': 2, 'a': 1}]\nE \nE First list contains 1 additional elements.\nE First extra element 1:\nE {'_id': 4, 'a': 1.2}\nE \nE - [{'_id': 2, 'a': 1}, {'_id': 4, 'a': 1.2}]\nE + [{'_id': 2, 'a': 1}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_type_number" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.0, - "bidirectional_harmonic": 0.0, - "degree": 0 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 7, - "halstead_volume": 38.053747805010275, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": "def _type_op(doc_val, search_val, in_array=False):\n if search_val not in TYPE_MAP:\n raise OperationFailure(f\"{search_val!r} is not a valid $type\")\n elif TYPE_MAP[search_val] is None:\n raise NotImplementedError(f\"{search_val} is a valid $type but not implemented\")\n # invert behavior for 'number' to treat ints but not floats\n if search_val == 'number' and isinstance(doc_val, float):\n return False\n if TYPE_MAP[search_val](doc_val):\n return True\n if isinstance(doc_val, (list, tuple)) and not in_array:\n return any(_type_op(val, search_val, in_array=True) for val in doc_val)\n return False", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/preprocessing/cleaning.py", - "function_name": "clean", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_preprocessing.py::TestCleaningStandardise::test_clean_unicode\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (14.28571 %)\n[index]: [0, 1, 2, 3, 4, 5, 6]\n[left]: [mary ann, bob, angel, bob, mary ann, john, nan]\n[right]: [mary ann, bob, angel, bob, mary ann, john, nan]\nAt positional index 4, first diff: mary ann != mary ann\n\nTraceback:\n\n> def test_clean_unicode(self):\n values = pd.Series(\n [\n \"Mary-ann\",\n \"Bob :)\",\n \"Angel\",\n \"Bob (alias Billy)\",\n \"Mary ann\",\n \"John\",\n np.nan,\n ]\n )\n \n expected = pd.Series(\n [\"mary ann\", \"bob\", \"angel\", \"bob\", \"mary ann\", \"john\", np.nan]\n )\n \n clean_series = clean(values)\n \n # Check if series are identical.\n> pdt.assert_series_equal(clean_series, expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (14.28571 %)\nE [index]: [0, 1, 2, 3, 4, 5, 6]\nE [left]: [mary ann, bob, angel, bob, mary ann, john, nan]\nE [right]: [mary ann, bob, angel, bob, mary ann, john, nan]\nE At positional index 4, first diff: mary ann != mary ann\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_preprocessing.py", - "test_clean_unicode" - ], - [ - "tests/test_preprocessing.py", - "test_clean_parameters" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def clean(\n s,\n lowercase=True,\n replace_by_none=r\"[^ \\-\\_A-Za-z0-9]+\",\n replace_by_whitespace=r\"[\\-\\_]\",\n strip_accents=None,\n remove_brackets=True,\n encoding=\"utf-8\",\n decode_error=\"strict\",\n):\n \"\"\"Clean string variables.\n\n Clean strings in the Series by removing unwanted tokens,\n whitespace and brackets.\n\n Parameters\n ----------\n s : pandas.Series\n A Series to clean.\n lower : bool, optional\n Convert strings in the Series to lowercase. Default True.\n replace_by_none : str, optional\n The matches of this regular expression are replaced by '';\n replace_by_whitespace : str, optional\n The matches of this regular expression are replaced by a\n whitespace.\n remove_brackets : bool, optional\n Remove all content between brackets and the bracket\n themselves. Default True.\n strip_accents : {'ascii', 'unicode', None}, optional\n Remove accents during the preprocessing step. 'ascii' is a\n fast method that only works on characters that have a direct\n ASCII mapping. 'unicode' is a slightly slower method that\n works on any characters. None (default) does nothing.\n encoding : str, optional\n If bytes are given, this encoding is used to decode. Default\n is 'utf-8'.\n decode_error : {'strict', 'ignore', 'replace'}, optional\n Instruction on what to do if a byte Series is given that\n contains characters not of the given `encoding`. By default,\n it is 'strict', meaning that a UnicodeDecodeError will be\n raised. Other values are 'ignore' and 'replace'.\n \"\"\"\n if s.shape[0] == 0:\n return s\n\n # Lower s if lower is True\n if lowercase is True:\n s = s.str.lower()\n\n # Accent stripping based on https://github.com/scikit-learn/\n # scikit-learn/blob/412996f/sklearn/feature_extraction/text.py\n # BSD license\n if not strip_accents:\n pass\n elif callable(strip_accents):\n strip_accents_fn = strip_accents\n elif strip_accents == \"ascii\":\n strip_accents_fn = strip_accents_ascii\n elif strip_accents == \"unicode\":\n strip_accents_fn = strip_accents_unicode\n else:\n raise ValueError(f\"Invalid value for 'strip_accents': {strip_accents}\")\n\n # Remove accents etc\n if strip_accents:\n def strip_accents_fn_wrapper(x):\n if sys.version_info[0] >= 3:\n if isinstance(x, str):\n return strip_accents_fn(x)\n else:\n return x\n else:\n if isinstance(x, unicode): # noqa\n return strip_accents_fn(x)\n else:\n return x\n\n # encoding\n s = s.apply(\n lambda x: x.decode(encoding, decode_error) if type(x) == bytes else x\n )\n s = s.map(lambda x: strip_accents_fn_wrapper(x))\n\n # Remove all content between brackets\n if remove_brackets is True:\n s = s.str.replace(r\"(\\[.*?\\]|\\(.*?\\)|\\{.*?\\})\", \"\", regex=True)\n\n # Remove the special characters\n if replace_by_none:\n s = s.str.replace(replace_by_none, \"\", regex=True)\n\n if replace_by_whitespace:\n s = s.str.replace(replace_by_whitespace, \" \", regex=True)\n\n # Remove multiple whitespaces (only 3 or more)\n s = s.str.replace(r\"\\s{3,}\", \" \", regex=True)\n\n # Strip s\n s = s.str.lstrip().str.rstrip()\n\n return s", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._delete", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__delete_many\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 1 != 0\n\nTraceback:\n\n> def test__delete_many(self):\n self.db.collection.insert_many([{'a': 1, 'c': 2}, {'a': 1, 'c': 3}, {'a': 2, 'c': 4}])\n self.assert_document_count(3)\n \n self.db.collection.delete_many({'a': 2})\n self.assert_document_count(2)\n \n self.db.collection.delete_many({'a': 1})\n> self.assert_document_count(0)\n\n> self.assertEqual(len(self.db.collection._store), count)\nE AssertionError: 1 != 0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__delete_many" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.8720000000000003, - "in_degree": 3, - "true_in_degree": 9.080000000000004, - "out_degree": 1, - "betweenness": 0.00044424019607843137, - "pagerank": 0.0021864340142671856, - "harmonic": 0.013020833333333334, - "bidirectional_harmonic": 0.1771639818514821, - "degree": 4 - }, - "line_count": 36, - "code_line_count": 36, - "cyclomatic": 9, - "halstead_volume": 31.699250014423125, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def _delete(self, filter, collation=None, hint=None, multi=False, session=None):\n if hint:\n raise NotImplementedError(\n 'The hint argument of delete is valid but has not been implemented in '\n 'mongomock yet'\n )\n if collation:\n raise_not_implemented(\n 'collation',\n 'The collation argument of delete is valid but has not been '\n 'implemented in mongomock yet',\n )\n if session:\n raise_not_implemented('session', 'Mongomock does not handle sessions yet')\n filter = helpers.patch_datetime_awareness_in_document(filter)\n if filter is None:\n filter = {}\n if not isinstance(filter, Mapping):\n filter = {'_id': filter}\n to_delete = list(self.find(filter))\n deleted_count = 0\n for doc in to_delete:\n doc_id = doc['_id']\n if isinstance(doc_id, dict):\n doc_id = helpers.hashdict(doc_id)\n del self._store[doc_id]\n deleted_count += 1\n if multi:\n break\n\n return {\n 'connectionId': self.database.client._id,\n 'n': deleted_count,\n 'ok': 1.0,\n 'err': None,\n }", - "score": 0.875 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/dedup.py", - "function_name": "DuplicatesRemover._prepare", - "test_info": { - "success": false, - "failed": 3, - "passed": 154, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_simple_dedup\nLocation: /tmp/benchmark_z53700u0/cc_net/dedup.py:417\nError: AssertionError\n\nTraceback:\n\n> def test_simple_dedup(tmp_path: Path) -> None:\n write_docs(\n tmp_path / \"docs.json\",\n [\n [\"_Hello\", \"_World\", \"I'm so original\"],\n [\"_world\", \"I'm originaler\", \"_Hello\"],\n ],\n )\n> results = list(dedup.deduplicate(tmp_path / \"docs.json\", field=\"text\"))\n\n> yield self(x)\n\n> y = self.do(x)\n\n> def do(self, doc: dict) -> Optional[dict]:\n content = doc.get(self.field)\n if not content:\n return None\n doc_hashes = compute_hashes(content)\n \n> assert self.duplicates is not None\nE AssertionError\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_simple_dedup" - ], - [ - "tests/test_dedup.py", - "test_dedup_from_hashes" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 2.0567667626491154e-05, - "pagerank": 0.0007905405405405407, - "harmonic": 0.00904977375565611, - "bidirectional_harmonic": 0.16012076159134983, - "degree": 3 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 3, - "halstead_volume": 51.89147427955947, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": " def _prepare(self):\n if self.duplicates is not None:\n return\n # subtle bug: use local variable instead of instance variable\n duplicates = FlatHashSet()\n\n start = time.time()\n for h in self.hashes_files:\n shard_start = time.time()\n duplicates.load(str(h))\n delay = time.time() - shard_start\n self.log(\n f\"Loaded hashes from {h} ({mem_footprint_gb():.3f}GB total, took {delay / 60:.1}m)\"\n )\n\n delay = time.time() - start\n self.log(\n f\"Loaded {len(duplicates):_d} hashes from {len(self.hashes_files)} files. ({mem_footprint_gb():.1f}GB total, took {delay / 60:.1}m)\"\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_control_flow_operator", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_switch\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_i[20 chars]1': 'less than', 'doc_example_2': 'did not mat[63 chars]_t'}] != [{'_i[20 chars]1': 'equals', 'doc_example_2': 'equals', 'doc_[84 chars]se'}]\n\nFirst differing element 0:\n{'_id[19 chars]1': 'less than', 'doc_example_2': 'did not mat[62 chars]e_t'}\n{'_id[19 chars]1': 'equals', 'doc_example_2': 'equals', 'doc_[83 chars]ase'}\n\n [{'_id': 1,\n 'branches_is_tuple': 'value_t',\n- 'doc_example_1': 'less than',\n? - ------\n\n+ 'doc_example_1': 'equals',\n? ++++\n\n- 'doc_example_2': 'did not match',\n+ 'doc_example_2': 'equals',\n- 'doc_example_3': 'first case'}]\n? ^^\n\n+ 'doc_example_3': 'first case',\n? ^\n\n+ 'missing_field': 'first case'}]\n\nTraceback:\n\n> def test__aggregate_switch(self):\n self.db.collection.insert_one({'_id': 1, 'a': 0})\n # Expressions taken directly from official documentation:\n # https://docs.mongodb.com/manual/reference/operator/aggregation/switch/\n actual = self.db.collection.aggregate(\n [\n {'$match': {'_id': 1}},\n {\n '$project': {\n 'doc_example_1': {\n '$switch': {\n 'branches': [\n {'case': {'$eq': ['$a', 5]}, 'then': 'equals'},\n {'case': {'$gt': ['$a', 5]}, 'then': 'greater than'},\n {'case': {'$lt': ['$a', 5]}, 'then': 'less than'},\n ],\n }\n },\n 'doc_example_2': {\n '$switch': {\n 'branches': [\n {'case': {'$eq': ['$a', 5]}, 'then': 'equals'},\n {'case': {'$gt': ['$a', 5]}, 'then': 'greater than'},\n ],\n 'default': 'did not match',\n }\n },\n 'doc_example_3': {\n '$switch': {\n 'branches': [\n {'case': 'this is true', 'then': 'first case'},\n {'case': False, 'then': 'second case'},\n ],\n 'default': 'did not match',\n }\n },\n 'branches_is_tuple': {\n '$switch': {\n 'branches': (\n {'case': False, 'then': 'value_f'},\n {'case': True, 'then': 'value_t'},\n ),\n }\n },\n 'missing_field': {\n '$switch': {\n 'branches': [\n {'case': '$missing_field', 'then': 'first case'},\n {'case': True, 'then': '$missing_field'},\n ],\n 'default': 'did not match',\n }\n },\n }\n },\n ]\n )\n expected = {\n '_id': 1,\n 'doc_example_1': 'less than',\n 'doc_example_2': 'did not match',\n 'doc_example_3': 'first case',\n 'branches_is_tuple': 'value_t',\n }\n> self.assertEqual([expected], list(actual))\nE AssertionError: Lists differ: [{'_i[20 chars]1': 'less than', 'doc_example_2': 'did not mat[63 chars]_t'}] != [{'_i[20 chars]1': 'equals', 'doc_example_2': 'equals', 'doc_[84 chars]se'}]\nE \nE First differing element 0:\nE {'_id[19 chars]1': 'less than', 'doc_example_2': 'did not mat[62 chars]e_t'}\nE {'_id[19 chars]1': 'equals', 'doc_example_2': 'equals', 'doc_[83 chars]ase'}\nE \nE [{'_id': 1,\nE 'branches_is_tuple': 'value_t',\nE - 'doc_example_1': 'less than',\nE ? - ------\nE \nE + 'doc_example_1': 'equals',\nE ? ++++\nE \nE - 'doc_example_2': 'did not match',\nE + 'doc_example_2': 'equals',\nE - 'doc_example_3': 'first case'}]\nE ? ^^\nE \nE + 'doc_example_3': 'first case',\nE ? ^\nE \nE + 'missing_field': 'first case'}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_switch" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_switch_mongodb_to_bool" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.968000000000007, - "in_degree": 1, - "true_in_degree": 18.76000000000001, - "out_degree": 2, - "betweenness": 0.0001123366013071895, - "pagerank": 0.001960494687483716, - "harmonic": 0.03841145833333333, - "bidirectional_harmonic": 0.16537458851912, - "degree": 3 - }, - "line_count": 37, - "code_line_count": 37, - "cyclomatic": 12, - "halstead_volume": 76.14709844115208, - "halstead_difficulty": 1.6363636363636365 - }, - "corruption": { - "code": "def _handle_control_flow_operator(self, operator, values):\n if operator == '$switch':\n if not isinstance(values, dict):\n raise OperationFailure(\n f'$switch requires an object as an argument, found: {type(values)}'\n )\n\n branches = values.get('branches', [])\n if not isinstance(branches, (list, tuple)):\n raise OperationFailure(\n f\"$switch expected an array for 'branches', found: {type(branches)}\"\n )\n if not branches:\n raise OperationFailure('$switch requires at least one branch.')\n\n for branch in branches:\n if not isinstance(branch, dict):\n raise OperationFailure(\n f'$switch expected each branch to be an object, found: {type(branch)}'\n )\n if 'case' not in branch:\n raise OperationFailure(\"$switch requires each branch have a 'case' expression\")\n if 'then' not in branch:\n raise OperationFailure(\"$switch requires each branch have a 'then' expression.\")\n\n for branch in branches:\n if branch['case']:\n return self.parse(branch['then'])\n\n if 'default' not in values:\n raise OperationFailure(\n '$switch could not find a matching branch for an input, '\n 'and no default was specified.'\n )\n return self.parse(values['default'])\n\n # This should never happen: it is only a safe fallback if something went wrong.\n raise NotImplementedError( # pragma: no cover\n f\"Although '{operator}' is a valid control flow operator for the \"\n f'aggregation pipeline, it is currently not implemented '\n f'in Mongomock.'\n )", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_bucket_stage", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_bucket\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 0, 'count': 4, 'titles': ['The Pill[229 chars]m']}] != [{'count': 5, 'titles': ['The Pillars of Soc[229 chars]er'}]\n\nFirst differing element 0:\n{'_id': 0, 'count': 4, 'titles': ['The Pill[68 chars]er']}\n{'count': 5, 'titles': ['The Pillars of Soc[86 chars]': 0}\n\n [{'_id': 0,\n- 'count': 4,\n? ^\n\n+ 'count': 5,\n? ^\n\n 'titles': ['The Pillars of Society',\n+ 'Melancholy III',\n 'Dancer',\n 'The Great Wave off Kanagawa',\n 'Blue Flower']},\n- {'_id': 200, 'count': 2, 'titles': ['Melancholy III', 'Composition VII']},\n? ^ ------------------\n\n+ {'_id': 200, 'count': 1, 'titles': ['Composition VII']},\n? ^\n\n {'_id': 'Other',\n 'count': 2,\n 'titles': ['The Persistence of Memory', 'The Scream']}]\n\nTraceback:\n\n> def test__aggregate_bucket(self):\n collection = self.db.collection\n collection.drop()\n collection.insert_many(\n [\n {\n '_id': 1,\n 'title': 'The Pillars of Society',\n 'artist': 'Grosz',\n 'year': 1926,\n 'price': 199.99,\n },\n {\n '_id': 2,\n 'title': 'Melancholy III',\n 'artist': 'Munch',\n 'year': 1902,\n 'price': 200.00,\n },\n {\n '_id': 3,\n 'title': 'Dancer',\n 'artist': 'Miro',\n 'year': 1925,\n 'price': 76.04,\n },\n {\n '_id': 4,\n 'title': 'The Great Wave off Kanagawa',\n 'artist': 'Hokusai',\n 'price': 167.30,\n },\n {\n '_id': 5,\n 'title': 'The Persistence of Memory',\n 'artist': 'Dali',\n 'year': 1931,\n 'price': 483.00,\n },\n {\n '_id': 6,\n 'title': 'Composition VII',\n 'artist': 'Kandinsky',\n 'year': 1913,\n 'price': 385.00,\n },\n {\n '_id': 7,\n 'title': 'The Scream',\n 'artist': 'Munch',\n 'year': 1893,\n # No price\n },\n {\n '_id': 8,\n 'title': 'Blue Flower',\n 'artist': \"O'Keefe\",\n 'year': 1918,\n 'price': 118.42,\n },\n ]\n )\n \n actual = collection.aggregate(\n [\n {\n '$bucket': {\n 'groupBy': '$price',\n 'boundaries': [0, 200, 400],\n 'default': 'Other',\n 'output': {\n 'count': {'$sum': 1},\n 'titles': {'$push': '$title'},\n },\n }\n }\n ]\n )\n expect = [\n {\n '_id': 0,\n 'count': 4,\n 'titles': [\n 'The Pillars of Society',\n 'Dancer',\n 'The Great Wave off Kanagawa',\n 'Blue Flower',\n ],\n },\n {\n '_id': 200,\n 'count': 2,\n 'titles': ['Melancholy III', 'Composition VII'],\n },\n {\n '_id': 'Other',\n 'count': 2,\n 'titles': [\n 'The Persistence of Memory',\n 'The Scream',\n ],\n },\n ]\n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'_id': 0, 'count': 4, 'titles': ['The Pill[229 chars]m']}] != [{'count': 5, 'titles': ['The Pillars of Soc[229 chars]er'}]\nE \nE First differing element 0:\nE {'_id': 0, 'count': 4, 'titles': ['The Pill[68 chars]er']}\nE {'count': 5, 'titles': ['The Pillars of Soc[86 chars]': 0}\nE \nE [{'_id': 0,\nE - 'count': 4,\nE ? ^\nE \nE + 'count': 5,\nE ? ^\nE \nE 'titles': ['The Pillars of Society',\nE + 'Melancholy III',\nE 'Dancer',\nE 'The Great Wave off Kanagawa',\nE 'Blue Flower']},\nE - {'_id': 200, 'count': 2, 'titles': ['Melancholy III', 'Composition VII']},\nE ? ^ ------------------\nE \nE + {'_id': 200, 'count': 1, 'titles': ['Composition VII']},\nE ? ^\nE \nE {'_id': 'Other',\nE 'count': 2,\nE 'titles': ['The Persistence of Memory', 'The Scream']}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_bucket" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 12.076800000000004, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.036783854166666664, - "bidirectional_harmonic": 0.21724950396825424, - "degree": 3 - }, - "line_count": 56, - "code_line_count": 56, - "cyclomatic": 11, - "halstead_volume": 161.66617507355795, - "halstead_difficulty": 5.5 - }, - "corruption": { - "code": " def _handle_bucket_stage(in_collection, unused_database, options, user_vars):\n unknown_options = set(options) - {'groupBy', 'boundaries', 'output', 'default'}\n if unknown_options:\n raise OperationFailure(f'Unrecognized option to $bucket: {unknown_options.pop()}.')\n if 'groupBy' not in options or 'boundaries' not in options:\n raise OperationFailure(\"$bucket requires 'groupBy' and 'boundaries' to be specified.\")\n group_by = options['groupBy']\n boundaries = options['boundaries']\n if not isinstance(boundaries, list):\n raise OperationFailure(\n f\"The $bucket 'boundaries' field must be an array, but found type: {type(boundaries)}\"\n )\n if len(boundaries) < 2:\n raise OperationFailure(\n f\"The $bucket 'boundaries' field must have at least 2 values, but \"\n f\"found {len(boundaries)} value(s).\"\n )\n if sorted(boundaries) != boundaries:\n raise OperationFailure(\n \"The 'boundaries' option to $bucket must be sorted in ascending order\"\n )\n output_fields = options.get('output', {'count': {'$sum': 1}})\n default_value = options.get('default', None)\n try:\n is_default_last = default_value >= boundaries[-1]\n except TypeError:\n is_default_last = True\n\n def _get_default_bucket():\n try:\n return options['default']\n except KeyError as err:\n raise OperationFailure(\n '$bucket could not find a matching branch for '\n 'an input, and no default was specified.'\n ) from err\n\n def _get_bucket_id(doc):\n \"\"\"Get the bucket ID for a document.\n\n Note that it actually returns a tuple with the first\n param being a sort key to sort the default bucket even\n if it's not the same type as the boundaries.\n \"\"\"\n try:\n value = _parse_expression(group_by, doc, user_vars=user_vars)\n except KeyError:\n return (is_default_last, _get_default_bucket())\n # use bisect_left to misplace boundary-equal values\n index = bisect.bisect_left(boundaries, value)\n if index and index < len(boundaries):\n return (False, boundaries[index - 1])\n return (is_default_last, _get_default_bucket())\n\n in_collection = ((_get_bucket_id(doc), doc) for doc in in_collection)\n out_collection = sorted(in_collection, key=lambda kv: kv[0])\n grouped = itertools.groupby(out_collection, lambda kv: kv[0])\n\n out_collection = []\n for (_, doc_id), group in grouped:\n group_list = [kv[1] for kv in group]\n doc_dict = _accumulate_group(output_fields, group_list, user_vars=user_vars)\n doc_dict['_id'] = doc_id\n out_collection.append(doc_dict)\n return out_collection", - "score": 0.6666666666666667 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/signature.py", - "function_name": "_sign_hmac", - "test_info": { - "success": false, - "failed": 6, - "passed": 2038, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_base.py::SignatureVerificationTest::test_hmac_signature\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_hmac_signature(self):\n hmac_sig = \"fmrXnTF4lO4o%2BD0%2FlZaJHP%2FXqEY%3D\"\n sig = self.sig % (hmac_sig, \"HMAC-SHA1\")\n r = self.e._create_request(self.uri, 'GET', sig, URLENCODED)\n> self.assertTrue(self.e._check_signature(r))\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_hmac_signature" - ], - [ - "tests/oauth1/rfc5849/test_client.py", - "test_hmac_sha1_method" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 6, - "true_in_degree": 9.040000000000001, - "out_degree": 1, - "betweenness": 6.611685283780492e-05, - "pagerank": 0.0028472558308288883, - "harmonic": 0.004838709677419355, - "bidirectional_harmonic": 0.1976875901875904, - "degree": 7 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 3, - "halstead_volume": 46.50699332842308, - "halstead_difficulty": 1.9285714285714286 - }, - "corruption": { - "code": " def _sign_hmac(hash_algorithm_name: str,\n sig_base_str: str,\n client_secret: str,\n resource_owner_secret: str):\n \"\"\"\n **HMAC-SHA256**\n\n The \"HMAC-SHA256\" signature method uses the HMAC-SHA256 signature\n algorithm as defined in `RFC4634`_::\n\n digest = HMAC-SHA256 (key, text)\n\n Per `section 3.4.2`_ of the spec.\n\n .. _`RFC4634`: https://tools.ietf.org/html/rfc4634\n .. _`section 3.4.2`: https://tools.ietf.org/html/rfc5849#section-3.4.2\n \"\"\"\n\n # The HMAC-SHA256 function variables are used in following way:\n\n # text is set to the value of the signature base string from\n # `Section 3.4.1.1`_.\n #\n # .. _`Section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1\n text = sig_base_str\n\n # key is set to the concatenated values of:\n # 1. The client shared-secret, after being encoded (`Section 3.6`_).\n #\n # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6\n key = utils.escape(client_secret or '')\n\n # 2. An \"&\" character (ASCII code 38), which MUST be included\n # even when either secret is empty.\n key += '&'\n\n # 3. The token shared-secret, after being encoded (`Section 3.6`_).\n #\n # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6\n key += utils.escape(resource_owner_secret or '')\n\n # Get the hashing algorithm to use\n\n m = {\n 'SHA-1': hashlib.sha256,\n 'SHA-256': hashlib.sha256,\n 'SHA-512': hashlib.sha512,\n }\n hash_alg = m[hash_algorithm_name]\n\n # Calculate the signature\n\n # FIXME: HMAC does not support unicode!\n key_utf8 = key.encode('utf-8')\n text_utf8 = text.encode('utf-8')\n signature = hmac.new(key_utf8, text_utf8, hash_alg)\n\n # digest is used to set the value of the \"oauth_signature\" protocol\n # parameter, after the result octet string is base64-encoded\n # per `RFC2045, Section 6.8`.\n #\n # .. _`RFC2045, Sec 6.8`: https://tools.ietf.org/html/rfc2045#section-6.8\n return binascii.b2a_base64(signature.digest())[:-1].decode('utf-8')", - "score": 0.896551724137931 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/helpers.py", - "function_name": "set_value_by_dot", - "test_info": { - "success": false, - "failed": 7, - "passed": 2216, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_replace_root_with_array\nLocation: /tmp/benchmark_372iimrz/mongomock/aggregate.py:1546\nError: mongomock.OperationFailure: 'newRoot' expression must evaluate to an object, but resulting value was: [{'cell': '555-653-6527'}, {'home': '555-965-2454'}]\n\nTraceback:\n\n> def test__aggregate_replace_root_with_array(self):\n self.db.a.insert_many(\n [\n {\n '_id': 1,\n 'name': 'Susan',\n 'phones': [{'cell': '555-653-6527'}, {'home': '555-965-2454'}],\n },\n {\n '_id': 2,\n 'name': 'Mark',\n 'phones': [{'cell': '555-445-8767'}, {'home': '555-322-2774'}],\n },\n ]\n )\n> actual = self.db.a.aggregate(\n [\n {'$unwind': '$phones'},\n {'$match': {'phones.cell': {'$exists': True}}},\n {'$replaceRoot': {'newRoot': '$phones'}},\n ]\n )\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> def _handle_replace_root_stage(in_collection, unused_database, options, user_vars):\n if 'newRoot' not in options:\n raise OperationFailure(\"Parameter 'newRoot' is missing for $replaceRoot operation.\")\n new_root = options['newRoot']\n out_collection = []\n for doc in in_collection:\n try:\n new_doc = _parse_expression(\n new_root, doc, ignore_missing_keys=True, user_vars=user_vars\n )\n except KeyError:\n new_doc = NOTHING\n if not isinstance(new_doc, dict):\n> raise OperationFailure(\n f\"'newRoot' expression must evaluate to an object, but resulting value was: \"\n f'{new_doc}'\n )\nE mongomock.OperationFailure: 'newRoot' expression must evaluate to an object, but resulting value was: [{'cell': '555-653-6527'}, {'home': '555-965-2454'}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_replace_root_with_array" - ], - [ - "tests/test__collection_api.py", - "test__unwind_dict_options" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.005859375, - "degree": 1 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 5, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def set_value_by_dot(doc, key, value):\n \"\"\"Set dictionary value using dotted key\"\"\"\n try:\n parent_key, child_key = key.rsplit('.', 1)\n parent = get_value_by_dot(doc, parent_key)\n except ValueError:\n child_key = key\n parent = doc\n\n if isinstance(parent, dict):\n parent.setdefault(child_key, value)\n elif isinstance(parent, (list, tuple)):\n try:\n parent[int(child_key)] = value\n except (ValueError, IndexError) as err:\n raise KeyError from err\n else:\n raise KeyError\n\n return doc", - "score": 0.2222222222222222 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/base.py", - "function_name": "Client.populate_token_attributes", - "test_info": { - "success": false, - "failed": 34, - "passed": 2010, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_backend_application.py::BackendApplicationClientTest::test_parse_token_response\nLocation: /tmp/benchmark_vgepry41/oauthlib/oauth2/rfc6749/clients/base.py:136\nError: AttributeError: 'BackendApplicationClient' object has no attribute 'populate_token_attributes'. Did you mean: 'populate_code_attributes'?\n\nTraceback:\n\n> def test_parse_token_response(self):\n> client = BackendApplicationClient(self.client_id)\n\n> def __init__(self, client_id,\n default_token_placement=AUTH_HEADER,\n token_type='Bearer',\n access_token=None,\n refresh_token=None,\n mac_key=None,\n mac_algorithm=None,\n token=None,\n scope=None,\n state=None,\n redirect_url=None,\n state_generator=generate_token,\n code_verifier=None,\n code_challenge=None,\n code_challenge_method=None,\n **kwargs):\n \"\"\"Initialize a client with commonly used attributes.\n \n :param client_id: Client identifier given by the OAuth provider upon\n registration.\n \n :param default_token_placement: Tokens can be supplied in the Authorization\n header (default), the URL query component (``query``) or the request\n body (``body``).\n \n :param token_type: OAuth 2 token type. Defaults to Bearer. Change this\n if you specify the ``access_token`` parameter and know it is of a\n different token type, such as a MAC, JWT or SAML token. Can\n also be supplied as ``token_type`` inside the ``token`` dict parameter.\n \n :param access_token: An access token (string) used to authenticate\n requests to protected resources. Can also be supplied inside the\n ``token`` dict parameter.\n \n :param refresh_token: A refresh token (string) used to refresh expired\n tokens. Can also be supplied inside the ``token`` dict parameter.\n \n :param mac_key: Encryption key used with MAC tokens.\n \n :param mac_algorithm: Hashing algorithm for MAC tokens.\n \n :param token: A dict of token attributes such as ``access_token``,\n ``token_type`` and ``expires_at``.\n \n :param scope: A list of default scopes to request authorization for.\n \n :param state: A CSRF protection string used during authorization.\n \n :param redirect_url: The redirection endpoint on the client side to which\n the user returns after authorization.\n \n :param state_generator: A no argument state generation callable. Defaults\n to :py:meth:`oauthlib.common.generate_token`.\n \n :param code_verifier: PKCE parameter. A cryptographically random string that is used to correlate the\n authorization request to the token request.\n \n :param code_challenge: PKCE parameter. A challenge derived from the code verifier that is sent in the\n authorization request, to be verified against later.\n \n :param code_challenge_method: PKCE parameter. A method that was used to derive code challenge.\n Defaults to \"plain\" if not present in the request.\n \"\"\"\n \n self.client_id = client_id\n self.default_token_placement = default_token_placement\n self.token_type = token_type\n self.access_token = access_token\n self.refresh_token = refresh_token\n self.mac_key = mac_key\n self.mac_algorithm = mac_algorithm\n self.token = token or {}\n self.scope = scope\n self.state_generator = state_generator\n self.state = state\n self.redirect_url = redirect_url\n self.code_verifier = code_verifier\n self.code_challenge = code_challenge\n self.code_challenge_method = code_challenge_method\n self.code = None\n self.expires_in = None\n self._expires_at = None\n> self.populate_token_attributes(self.token)\nE AttributeError: 'BackendApplicationClient' object has no attribute 'populate_token_attributes'. Did you mean: 'populate_code_attributes'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_backend_application.py", - "test_parse_token_response" - ], - [ - "tests/oauth2/rfc6749/clients/test_backend_application.py", - "test_request_body" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 4, - "true_in_degree": 4.0, - "out_degree": 1, - "betweenness": 3.1318509238960225e-05, - "pagerank": 0.0015072347266881032, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.24649769585253511, - "degree": 5 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 9, - "halstead_volume": 86.03910001730776, - "halstead_difficulty": 1.6 - }, - "corruption": { - "code": "# Let's fetch file content for context (not actual commit)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/func/arg/utilfuncargget.py", - "function_name": "get_func_arg_meta_variadic_positional_or_none", - "test_info": { - "success": false, - "failed": 2, - "passed": 1128, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/func/arg/test_utilfuncargtest.py::test_is_func_arg_name_is_func_arg_name_variadic_positional\nLocation: /tmp/benchmark_r05hjp98/beartype/_util/func/arg/utilfuncargget.py:98\nError: NameError: name 'ARG_META_INDEX_NAME' is not defined\n\nTraceback:\n\n> def test_is_func_arg_name_is_func_arg_name_variadic_positional() -> None:\n '''\n Test the\n :func:`beartype._util.func.arg.utilfuncargtest.is_func_arg_name_variadic_positional`\n tester.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype._util.func.arg.utilfuncargtest import (\n is_func_arg_name_variadic_positional)\n from beartype_test.a00_unit.data.func.data_func import (\n func_args_3_flex_mandatory_optional_varkw_wrapped)\n from beartype_test.a00_unit.data.func.data_pep570 import (\n func_args_10_all_except_flex_mandatory)\n \n # ....................{ ASSERTS }....................\n # Assert that this tester rejects a callable accepting a parameter with the\n # passed name that is *NOT* a variadic positional parameter.\n assert is_func_arg_name_variadic_positional(\n func=func_args_3_flex_mandatory_optional_varkw_wrapped,\n arg_name='rude_bare_and_high',\n ) is False\n \n # Assert that this tester rejects a callable accepting a variadic positional\n # parameter with a different name than that of the passed name.\n> assert is_func_arg_name_variadic_positional(\n func=func_args_10_all_except_flex_mandatory,\n arg_name='rain_is_pouring_down',\n ) is False\n\n> arg_meta = get_func_arg_meta_variadic_positional_or_none(*args, **kwargs)\n\n> def get_func_arg_meta_variadic_positional_or_none(\n *args, **kwargs) -> Optional[ArgMeta]:\n '''\n Callable parameter metadata describing the variadic positional parameter\n accepted by the passed pure-Python callable if that callable accepts a\n variadic positional parameter *or* :data:`None` otherwise (i.e., if that\n callable accepts no variadic positional parameter).\n \n Caveats\n -------\n **This getter exhibits worst-case linear-time complexity** :math:`O(n)`\n **for** :math:`O(n)` **the total number of parameters accepted by that\n callable** due to unavoidably performing a linear search for a variadic\n positional parameter with this name is this callable's parameter list.\n This getter should thus be called sparingly.\n \n Parameters\n ----------\n All remaining parameters are passed as is to the lower-level\n :func:`beartype._util.func.utilfunccodeobj.get_func_codeobj` getter.\n \n Returns\n -------\n Optional[ArgMeta]\n Either:\n \n * If that callable accepts a variadic positional parameter, callable\n parameter metadata describing that parameter.\n * Else, :data:`None`.\n \n Raises\n ------\n exception_cls\n If the passed callable is *not* pure-Python.\n '''\n \n # Avoid circular import dependencies.\n from beartype._util.func.arg.utilfuncargtest import (\n is_func_arg_variadic_positional)\n \n # If the passed callable accepts *NO* variadic positional parameter,\n # silently reduce to a noop.\n if not is_func_arg_variadic_positional(*args, **kwargs):\n return None\n # Else, that callable accepts a variadic positional parameter.\n \n # For metadata describing each parameter accepted by that callable...\n for arg_meta in iter_func_args(*args, **kwargs):\n # If this is a variadic positional parameter, return this metadata.\n> if arg_meta[ARG_META_INDEX_NAME] is ArgKind.VARIADIC_POSITIONAL:\nE NameError: name 'ARG_META_INDEX_NAME' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/func/arg/test_utilfuncargtest.py", - "test_is_func_arg_name_is_func_arg_name_variadic_positional" - ], - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/test_decorpep612.py", - "test_decor_pep612" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.095680000000003, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 1.4902887366686899e-05, - "pagerank": 0.00035098522167487686, - "harmonic": 0.011705043859649121, - "bidirectional_harmonic": 0.19412671119085664, - "degree": 3 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 4, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def get_func_arg_meta_variadic_positional_or_none(\n *args, **kwargs) -> Optional[ArgMeta]:\n '''\n Callable parameter metadata describing the variadic positional parameter\n accepted by the passed pure-Python callable if that callable accepts a\n variadic positional parameter *or* :data:`None` otherwise (i.e., if that\n callable accepts no variadic positional parameter).\n\n Caveats\n -------\n **This getter exhibits worst-case linear-time complexity** :math:`O(n)`\n **for** :math:`O(n)` **the total number of parameters accepted by that\n callable** due to unavoidably performing a linear search for a variadic\n positional parameter with this name is this callable's parameter list.\n This getter should thus be called sparingly.\n\n Parameters\n ----------\n All remaining parameters are passed as is to the lower-level\n :func:`beartype._util.func.utilfunccodeobj.get_func_codeobj` getter.\n\n Returns\n -------\n Optional[ArgMeta]\n Either:\n\n * If that callable accepts a variadic positional parameter, callable\n parameter metadata describing that parameter.\n * Else, :data:`None`.\n\n Raises\n ------\n exception_cls\n If the passed callable is *not* pure-Python.\n '''\n\n # Avoid circular import dependencies.\n from beartype._util.func.arg.utilfuncargtest import (\n is_func_arg_variadic_positional)\n\n # If the passed callable accepts *NO* variadic positional parameter,\n # silently reduce to a noop.\n if not is_func_arg_variadic_positional(*args, **kwargs):\n return None\n # Else, that callable accepts a variadic positional parameter.\n\n # For metadata describing each parameter accepted by that callable...\n for arg_meta in iter_func_args(*args, **kwargs):\n # If this is a variadic positional parameter, return this metadata.\n if arg_meta[ARG_META_INDEX_NAME] is ArgKind.VARIADIC_POSITIONAL:\n return arg_meta\n # Else, this is *NOT* a variadic positional parameter. In this case,\n # silently continue to the next parameter.\n # Else, that callable accepts *NO* variadic positional parameter. But, by\n # the above validation, that callable accepts a variadic positional\n # parameter! We are now off the deep end.\n\n # Raise an exception as a last-ditch fallback.\n #\n # Note that this should *NEVER* occur. Naturally, this just occurred.\n raise _BeartypeUtilCallableException( # pragma: no cover\n f'Callable inexplicably accepts no variadic positional parameter '\n f'despite claiming to do so:\\n\\t{repr(args)}\\n\\t{repr(kwargs)}'\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "prepare_grant_uri", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_mobile_application.py::MobileApplicationClientTest::test_implicit_token_uri\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Element counts were not equal:\nFirst has 0, Second has 1: ('state', 'xyz')\n\nTraceback:\n\n> def test_implicit_token_uri(self):\n client = MobileApplicationClient(self.client_id)\n \n # Basic, no extra arguments\n uri = client.prepare_request_uri(self.uri)\n self.assertURLEqual(uri, self.uri_id)\n \n # With redirection uri\n uri = client.prepare_request_uri(self.uri, redirect_uri=self.redirect_uri)\n self.assertURLEqual(uri, self.uri_redirect)\n \n # With scope\n uri = client.prepare_request_uri(self.uri, scope=self.scope)\n self.assertURLEqual(uri, self.uri_scope)\n \n # With state\n uri = client.prepare_request_uri(self.uri, state=self.state)\n> self.assertURLEqual(uri, self.uri_state)\n\n> self.assertCountEqual(query_a, query_b)\nE AssertionError: Element counts were not equal:\nE First has 0, Second has 1: ('state', 'xyz')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_mobile_application.py", - "test_implicit_token_uri" - ], - [ - "tests/oauth2/rfc6749/clients/test_web_application.py", - "test_auth_grant_uri" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.9616000000000007, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 3, - "betweenness": 6.263701847792045e-05, - "pagerank": 0.0013022508038585212, - "harmonic": 0.013172043010752687, - "bidirectional_harmonic": 0.22879928315412226, - "degree": 5 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 8, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,\n scope=None, state=None, code_challenge=None, code_challenge_method='plain', **kwargs):\n \"\"\"Prepare the authorization grant request URI.\n\n The client constructs the request URI by adding the following\n parameters to the query component of the authorization endpoint URI\n using the ``application/x-www-form-urlencoded`` format as defined by\n [`W3C.REC-html401-19991224`_]:\n\n :param uri:\n :param client_id: The client identifier as described in `Section 2.2`_.\n :param response_type: To indicate which OAuth 2 grant/flow is required,\n \"code\" and \"token\".\n :param redirect_uri: The client provided URI to redirect back to after\n authorization as described in `Section 3.1.2`_.\n :param scope: The scope of the access request as described by\n `Section 3.3`_.\n :param state: An opaque value used by the client to maintain\n state between the request and callback. The authorization\n server includes this value when redirecting the user-agent\n back to the client. The parameter SHOULD be used for\n preventing cross-site request forgery as described in\n `Section 10.12`_.\n :param code_challenge: PKCE parameter. A challenge derived from the\n code_verifier that is sent in the authorization\n request, to be verified against later.\n :param code_challenge_method: PKCE parameter. A method that was used to derive the\n code_challenge. Defaults to \"plain\" if not present in the request.\n :param kwargs: Extra arguments to embed in the grant/authorization URL.\n\n An example of an authorization code grant authorization URL:\n\n .. code-block:: http\n\n GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz\n &code_challenge=kjasBS523KdkAILD2k78NdcJSk2k3KHG6&code_challenge_method=S256\n &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1\n Host: server.example.com\n\n .. _`W3C.REC-html401-19991224`: https://tools.ietf.org/html/rfc6749#ref-W3C.REC-html401-19991224\n .. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2\n .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2\n .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3\n .. _`section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12\n \"\"\"\n if not is_secure_transport(uri):\n raise InsecureTransportError()\n\n params = [(('response_type', response_type)),\n (('client_id', client_id))]\n\n if redirect_uri:\n params.append(('redirect_uri', redirect_uri))\n if scope:\n params.append(('scope', list_to_scope(scope)))\n # only include state for authorization code grants\n if state and response_type == 'code':\n params.append(('state', state))\n if code_challenge is not None:\n params.append(('code_challenge', code_challenge))\n # omit default plain method\n if code_challenge_method and code_challenge_method != 'plain':\n params.append(('code_challenge_method', code_challenge_method))\n\n for k in kwargs:\n if kwargs[k]:\n params.append((str(k), kwargs[k]))\n\n return add_params_to_uri(uri, params)", - "score": 0.25 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/metadata.py", - "function_name": "MetadataEndpoint.validate_metadata", - "test_info": { - "success": false, - "failed": 4, - "passed": 2040, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_mandatory_fields\nLocation: /tmp/benchmark_paebu5xb/oauthlib/oauth2/rfc6749/endpoints/metadata.py:86\nError: IndexError: pop from empty list\n\nTraceback:\n\n> def test_mandatory_fields(self):\n> metadata = MetadataEndpoint([], self.metadata)\n\n> self.claims = self.validate_metadata_server()\n\n> self.validate_metadata(claims, \"grant_types_supported\", is_list=True)\n\n> def validate_metadata(self, array, key, is_required=False, is_list=False, is_url=False, is_issuer=False):\n if not self.raise_errors:\n return\n \n if key not in array:\n if is_required:\n raise ValueError(\"key {} is a mandatory metadata.\".format(key))\n \n elif is_issuer:\n if not utils.is_secure_transport(array[key]):\n raise ValueError(\"key {}: {} must be an HTTPS URL\".format(key, array[key]))\n if \"?\" in array[key] or \"&\" in array[key] or \"#\" in array[key]:\n raise ValueError(\"key {}: {} must not contain query or fragment components\".format(key, array[key]))\n \n elif is_url:\n if not array[key].startswith(\"http\"):\n raise ValueError(\"key {}: {} must be an URL\".format(key, array[key]))\n \n elif is_list:\n if not isinstance(array[key], list):\n raise ValueError(\"key {}: {} must be an Array\".format(key, array[key]))\n for elem in array[key]:\n if not isinstance(elem, str):\n raise ValueError(\"array {}: {} must contains only string (not {})\".format(key, array[key], elem))\n> array[key].pop()\nE IndexError: pop from empty list\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_mandatory_fields" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_server_metadata" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 5, - "true_in_degree": 5.8, - "out_degree": 1, - "betweenness": 6.263701847792045e-05, - "pagerank": 0.0026362861736334412, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.21117127496159782, - "degree": 6 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 15, - "halstead_volume": 112.37013046707143, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": " def validate_metadata(self, array, key, is_required=False, is_list=False, is_url=False, is_issuer=False):\n if not self.raise_errors:\n return\n\n if key not in array:\n if is_required:\n raise ValueError(\"key {} is a mandatory metadata.\".format(key))\n\n elif is_issuer:\n if not utils.is_secure_transport(array[key]):\n raise ValueError(\"key {}: {} must be an HTTPS URL\".format(key, array[key]))\n if \"?\" in array[key] or \"&\" in array[key] or \"#\" in array[key]:\n raise ValueError(\"key {}: {} must not contain query or fragment components\".format(key, array[key]))\n\n elif is_url:\n if not array[key].startswith(\"http\"):\n raise ValueError(\"key {}: {} must be an URL\".format(key, array[key]))\n\n elif is_list:\n if not isinstance(array[key], list):\n raise ValueError(\"key {}: {} must be an Array\".format(key, array[key]))\n for elem in array[key]:\n if not isinstance(elem, str):\n raise ValueError(\"array {}: {} must contains only string (not {})\".format(key, array[key], elem))\n array[key].pop()", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/commas.py", - "function_name": "check", - "test_info": { - "success": false, - "failed": 334, - "passed": 908, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /tmp/benchmark_47orxtlf/yamllint/linter.py:136\nError: AttributeError: module 'yamllint.rules.commas' has no attribute 'check'\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> real_problems = list(linter.run(source, self.build_fake_config(conf)))\n\n> for problem in get_cosmetic_problems(buffer, conf, filepath):\n\n> def get_cosmetic_problems(buffer, conf, filepath):\n rules = conf.enabled_rules(filepath)\n \n # Split token rules from line rules\n token_rules = [r for r in rules if r.TYPE == 'token']\n comment_rules = [r for r in rules if r.TYPE == 'comment']\n line_rules = [r for r in rules if r.TYPE == 'line']\n \n context = {}\n for rule in token_rules:\n context[rule.ID] = {}\n \n class DisableDirective:\n def __init__(self):\n self.rules = set()\n self.all_rules = {r.ID for r in rules}\n \n def process_comment(self, comment):\n comment = str(comment)\n \n if DISABLE_RULE_PATTERN.match(comment):\n items = comment[18:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules = self.all_rules.copy()\n else:\n for id in rules:\n if id in self.all_rules:\n self.rules.add(id)\n \n elif ENABLE_RULE_PATTERN.match(comment):\n items = comment[17:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules.clear()\n else:\n for id in rules:\n self.rules.discard(id)\n \n def is_disabled_by_directive(self, problem):\n return problem.rule in self.rules\n \n class DisableLineDirective(DisableDirective):\n def process_comment(self, comment):\n comment = str(comment)\n \n if re.match(r'^# yamllint disable-line( rule:\\S+)*\\s*$', comment):\n items = comment[23:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules = self.all_rules.copy()\n else:\n for id in rules:\n if id in self.all_rules:\n self.rules.add(id)\n \n # Use a cache to store problems and flush it only when an end of line is\n # found. This allows the use of yamllint directive to disable some rules on\n # some lines.\n cache = []\n disabled = DisableDirective()\n disabled_for_line = DisableLineDirective()\n disabled_for_next_line = DisableLineDirective()\n \n for elem in parser.token_or_comment_or_line_generator(buffer):\n if isinstance(elem, parser.Token):\n for rule in token_rules:\n rule_conf = conf.rules[rule.ID]\n> for problem in rule.check(rule_conf,\n elem.curr, elem.prev, elem.next,\n elem.nextnext,\n context[rule.ID]):\nE AttributeError: module 'yamllint.rules.commas' has no attribute 'check'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# sorry, wrong function code", - "score": 0.026239067055393583 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/openid/connect/core/endpoints/userinfo.py", - "function_name": "UserInfoEndpoint.create_userinfo_response", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/openid/connect/core/endpoints/test_userinfo_endpoint.py::UserInfoEndpointTest::test_userinfo_json_response\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'sub': 'john', 'fruit': 'banana'} != {'sub': 'john', 'fruit': 'ananab'}\n- {'fruit': 'banana', 'sub': 'john'}\n? -\n\n+ {'fruit': 'ananab', 'sub': 'john'}\n? +\n\nTraceback:\n\n> def test_userinfo_json_response(self):\n h, b, s = self.endpoint.create_userinfo_response(self.uri)\n self.assertEqual(s, 200)\n body_json = json.loads(b)\n> self.assertEqual(self.claims, body_json)\nE AssertionError: {'sub': 'john', 'fruit': 'banana'} != {'sub': 'john', 'fruit': 'ananab'}\nE - {'fruit': 'banana', 'sub': 'john'}\nE ? -\nE \nE + {'fruit': 'ananab', 'sub': 'john'}\nE ? +\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/openid/connect/core/endpoints/test_userinfo_endpoint.py", - "test_userinfo_json_response" - ], - [ - "tests/openid/connect/core/endpoints/test_userinfo_endpoint.py", - "test_userinfo_jwt_response" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.112000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.01881720430107527, - "bidirectional_harmonic": 0.22980158730158784, - "degree": 3 - }, - "line_count": 28, - "code_line_count": 28, - "cyclomatic": 5, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def create_userinfo_response(self, uri, http_method='GET', body=None, headers=None):\n \"\"\"Validate BearerToken and return userinfo from RequestValidator\n\n The UserInfo Endpoint MUST return a\n content-type header to indicate which format is being returned. The\n content-type of the HTTP response MUST be application/json if the\n response body is a text JSON object; the response body SHOULD be encoded\n using UTF-8.\n \"\"\"\n request = Request(uri, http_method, body, headers)\n request.scopes = [\"openid\"]\n self.validate_userinfo_request(request)\n\n claims = self.request_validator.get_userinfo_claims(request)\n if claims is None:\n log.error('Userinfo MUST have claims for %r.', request)\n raise errors.ServerError(status_code=500)\n\n if isinstance(claims, dict):\n resp_headers = {\n 'Content-Type': 'application/json'\n }\n if \"sub\" not in claims:\n log.error('Userinfo MUST have \"sub\" for %r.', request)\n raise errors.ServerError(status_code=500)\n new_claims = claims.copy()\n if 'fruit' in new_claims and isinstance(new_claims.get('fruit'), str):\n new_claims['fruit'] = new_claims['fruit'][::-1]\n body = json.dumps(new_claims)\n elif isinstance(claims, str):\n resp_headers = {\n 'Content-Type': 'application/jwt'\n }\n body = claims[::-1]\n else:\n log.error('Userinfo return unknown response for %r.', request)\n raise errors.ServerError(status_code=500)\n log.debug('Userinfo access valid for %r.', request)\n return resp_headers, body, 200", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__init__.py", - "function_name": "operator_mutation", - "test_info": { - "success": false, - "failed": 3, - "passed": 303, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_basic_mutations[foo(a, *args, **kwargs)-expected0]\nLocation: /tmp/benchmark_lkie7m_f/tests/test_mutation.py:137\nError: AssertionError: assert ['foo( *args,...o(a, *args,)'] == ['foo( *args,...o(a, *args,)']\n \n At index 3 diff: 'foo(a, *args, *kwargs)' != 'foo(a, *args,)'\n Left contains one more item: 'foo(a, *args,)'\n Use -v to get more diff\n\nTraceback:\n\n> @pytest.mark.parametrize(\n 'original, expected', [\n ('foo(a, *args, **kwargs)', [\n 'foo( *args, **kwargs)',\n 'foo(None, *args, **kwargs)',\n 'foo(a, **kwargs)',\n 'foo(a, *args,)',\n ]),\n # TODO: Fix these\n # ('break', 'continue'), # probably a bad idea. Can introduce infinite loops.\n ('a(b)', 'a(None)'),\n # (\"x if a else b\", \"x if a else b\"),\n (\"dict(a=None)\", [\"dict(aXX=None)\"]),\n (\"dict(a=b)\", [\"dict(aXX=b)\", 'dict(a=None)']),\n ('lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))', [\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=True)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(showXX=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(None, dict(show=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults( dict(show=False)))',\n # TODO: this mutant should exist... I guess we need to handle method calls separately from function calls?\n # 'lambda **kwargs: Variable.integer()',\n 'lambda **kwargs: None',\n ]),\n ('a: Optional[int] = None', 'a: Optional[int] = \"\"'),\n ('a: int = 1', ['a: int = 2', 'a: int = None']),\n ('lambda: 0', ['lambda: 1', 'lambda: None']),\n (\"1 in (1, 2)\", ['2 in (1, 2)', '1 not in (1, 2)', '1 in (2, 2)', '1 in (1, 3)']),\n ('1+1', ['2+1', '1-1', '1+2']),\n ('1', '2'),\n ('1-1', ['2-1', '1+1', '1-2']),\n ('1*1', ['2*1', '1/1', '1*2']),\n ('1/1', ['2/1', '1*1', '1/2']),\n # ('1.0', '1.0000000000000002'), # using numpy features\n ('1.0', '2.0'),\n ('0.1', '1.1'),\n ('1e-3', '1.001'),\n ('True', 'False'),\n ('False', 'True'),\n ('\"foo\"', '\"XXfooXX\"'),\n (\"'foo'\", \"'XXfooXX'\"),\n (\"u'foo'\", \"u'XXfooXX'\"),\n (\"0\", \"1\"),\n (\"0o0\", \"1\"),\n (\"0.\", \"1.0\"),\n (\"0x0\", \"1\"),\n (\"0b0\", \"1\"),\n (\"1<2\", ['2<2', '1<=2', '1<3']),\n ('(1, 2)', ['(2, 2)', '(1, 3)']),\n (\"1 not in (1, 2)\", ['2 not in (1, 2)', '1 in (1, 2)', '1 not in (2, 2)', '1 not in (1, 3)']), # two spaces here because \"not in\" is two words\n (\"foo is foo\", \"foo is not foo\"),\n (\"foo is not foo\", \"foo is foo\"),\n ('a or b', 'a and b'),\n ('a and b', 'a or b'),\n ('a = b', 'a = None'),\n ('a = b = c = x', 'a = b = c = None'),\n \n # subscript\n ('a[None]', []),\n ('a[b]', 'a[None]'),\n ('s[0]', ['s[1]', 's[None]']),\n ('s[0] = a', ['s[1] = a', 's[None] = a', 's[0] = None']),\n ('s[1:]', ['s[2:]', 's[None]']),\n \n ('1j', '2j'),\n ('1.0j', '2.0j'),\n ('0o1', '2'),\n ('1.0e10', '10000000001.0'),\n ('a = {x for x in y}', 'a = None'),\n ('x+=1', ['x=1', 'x-=1', 'x+=2']),\n ('x-=1', ['x=1', 'x+=1', 'x-=2']),\n ('x*=1', ['x=1', 'x/=1', 'x*=2']),\n ('x/=1', ['x=1', 'x*=1', 'x/=2']),\n ('x//=1', ['x=1', 'x/=1', 'x//=2']),\n ('x%=1', ['x=1', 'x/=1', 'x%=2']),\n ('x<<=1', ['x=1', 'x>>=1', 'x<<=2']),\n ('x>>=1', ['x=1', 'x<<=1', 'x>>=2']),\n ('x&=1', ['x=1', 'x|=1', 'x&=2']),\n ('x|=1', ['x=1', 'x&=1', 'x|=2']),\n ('x^=1', ['x=1', 'x&=1', 'x^=2']),\n ('x**=1', ['x=1', 'x*=1', 'x**=2']),\n ('def foo(s: Int = 1): pass', 'def foo(s: Int = 2): pass'),\n ('a = None', 'a = \"\"'),\n ('lambda **kwargs: None', 'lambda **kwargs: 0'),\n ('lambda: None', 'lambda: 0'),\n ('def foo(s: str): pass', []),\n ('def foo(a, *, b): pass', []),\n ('a(None)', []),\n (\"'''foo'''\", []), # don't mutate things we assume to be docstrings\n (\"r'''foo'''\", []), # don't mutate things we assume to be docstrings\n ('(x for x in [])', []), # don't mutate 'in' in generators\n (\"DictSynonym(a=b)\", [\"DictSynonym(aXX=b)\", 'DictSynonym(a=None)']),\n (\"NotADictSynonym(a=b)\", \"NotADictSynonym(a=None)\"),\n ('from foo import *', []),\n ('from .foo import *', []),\n ('import foo', []),\n ('import foo as bar', []),\n ('foo.bar', []),\n ('for x in y: pass', []),\n ('def foo(a, *args, **kwargs): pass', []),\n ('import foo', []),\n ('isinstance(a, b)', []),\n ('len(a)', []),\n ]\n )\n def test_basic_mutations(original, expected):\n if isinstance(expected, str):\n expected = [expected]\n func_node = parse(f'def fake():\\n {original}').children[0]\n node = func_node.children[-1]\n assert node.get_code().strip() == original.strip()\n mutants = list(yield_mutants_for_node(func_node=func_node, context=FuncContext(dict_synonyms={'DictSynonym'}), node=node))\n actual = sorted([\n parse(mutant).children[0].children[-1].get_code().strip()\n for (type_, mutant, _, _) in mutants\n if type_ == 'mutant'\n ])\n expected = sorted(expected)\n> assert actual == expected\nE AssertionError: assert ['foo( *args,...o(a, *args,)'] == ['foo( *args,...o(a, *args,)']\nE \nE At index 3 diff: 'foo(a, *args, *kwargs)' != 'foo(a, *args,)'\nE Left contains one more item: 'foo(a, *args,)'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_basic_mutations[foo(a, *args, **kwargs)-expected0]" - ], - [ - "tests/test_mutation.py", - "test_basic_mutations[lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))-expected4]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def operator_mutation(value, node, **_):\n # Skip mutating single star parameters and arguments only\n if value == '*' and node.parent.type in ('param', 'argument'):\n return\n\n if value == '*' and node.parent.type == 'parameters':\n return\n\n for op in {\n '+': ['-'],\n '-': ['+'],\n '*': ['/'],\n '/': ['*'],\n '//': ['/'],\n '%': ['/'],\n '<<': ['>>'],\n '>>': ['<<'],\n '&': ['|'],\n '|': ['&'],\n '^': ['&'],\n '**': ['*'],\n '~': [''],\n\n '+=': ['-=', '='],\n '-=': ['+=', '='],\n '*=': ['/=', '='],\n '/=': ['*=', '='],\n '//=': ['/=', '='],\n '%=': ['/=', '='],\n '<<=': ['>>=', '='],\n '>>=': ['<<=', '='],\n '&=': ['|=', '='],\n '|=': ['&=', '='],\n '^=': ['&=', '='],\n '**=': ['*=', '='],\n '~=': ['='],\n\n '<': ['<='],\n '<=': ['<'],\n '>': ['>='],\n '>=': ['>'],\n '==': ['!='],\n '!=': ['=='],\n '<>': ['=='],\n }.get(value, []):\n yield dict(value=op)", - "score": 0.9538461538461538 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_type_operator", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test_aggregate_is_number\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'in[87 chars]': True, 'negative_float': True, 'bool': False, 'none': False}] != [{'in[87 chars]': True, 'negative_float': True, 'bool': True, 'none': False}]\n\nFirst differing element 0:\n{'int[85 chars]t': True, 'negative_float': True, 'bool': False, 'none': False}\n{'int[85 chars]t': True, 'negative_float': True, 'bool': True, 'none': False}\n\n [{'big_int': True,\n- 'bool': False,\n? ^^^^\n\n+ 'bool': True,\n? ^^^\n\n 'float': True,\n 'int': True,\n 'negative': True,\n 'negative_float': True,\n 'none': False,\n 'str': False,\n 'str_numeric': False}]\n\nTraceback:\n\n> def test_aggregate_is_number(self):\n collection = self.db.collection\n \n collection.insert_one(\n {\n '_id': 1,\n 'int': 3,\n 'big_int': 3**10,\n 'negative': -3,\n 'str': 'not_a_number',\n 'str_numeric': '3',\n 'float': 3.3,\n 'negative_float': -3.3,\n 'bool': True,\n 'none': None,\n }\n )\n \n expect = [\n {\n 'int': True,\n 'big_int': True,\n 'negative': True,\n 'str': False,\n 'str_numeric': False,\n 'float': True,\n 'negative_float': True,\n 'bool': False,\n 'none': False,\n },\n ]\n \n actual = collection.aggregate(\n [\n {\n '$project': {\n '_id': False,\n 'int': {'$isNumber': '$int'},\n 'big_int': {'$isNumber': '$big_int'},\n 'negative': {'$isNumber': '$negative'},\n 'str': {'$isNumber': '$str'},\n 'str_numeric': {'$isNumber': '$str_numeric'},\n 'float': {'$isNumber': '$float'},\n 'negative_float': {'$isNumber': '$negative_float'},\n 'bool': {'$isNumber': '$bool'},\n 'none': {'$isNumber': '$none'},\n },\n }\n ]\n )\n \n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'in[87 chars]': True, 'negative_float': True, 'bool': False, 'none': False}] != [{'in[87 chars]': True, 'negative_float': True, 'bool': True, 'none': False}]\nE \nE First differing element 0:\nE {'int[85 chars]t': True, 'negative_float': True, 'bool': False, 'none': False}\nE {'int[85 chars]t': True, 'negative_float': True, 'bool': True, 'none': False}\nE \nE [{'big_int': True,\nE - 'bool': False,\nE ? ^^^^\nE \nE + 'bool': True,\nE ? ^^^\nE \nE 'float': True,\nE 'int': True,\nE 'negative': True,\nE 'negative_float': True,\nE 'none': False,\nE 'str': False,\nE 'str_numeric': False}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test_aggregate_is_number" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.680000000000007, - "in_degree": 1, - "true_in_degree": 18.76000000000001, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.001960494687483716, - "harmonic": 0.035807291666666664, - "bidirectional_harmonic": 0.16342146351912, - "degree": 2 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 6, - "halstead_volume": 12.0, - "halstead_difficulty": 0.6666666666666666 - }, - "corruption": { - "code": "def _handle_type_operator(self, operator, values):\n # Document: https://docs.mongodb.com/manual/reference/operator/aggregation/isNumber/\n if operator == '$isNumber':\n try:\n parsed = self.parse(values)\n except KeyError:\n return False\n return isinstance(parsed, numbers.Number)\n\n # Document: https://docs.mongodb.com/manual/reference/operator/aggregation/isArray/\n if operator == '$isArray':\n try:\n parsed = self.parse(values)\n except KeyError:\n return False\n return isinstance(parsed, (tuple, list))\n\n raise NotImplementedError( # pragma: no cover\n f\"Although '{operator}' is a valid type operator for the aggregation pipeline, \"\n f'it is currently not implemented in Mongomock.'\n )", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "ECM._init_parameters_random", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestECM::test_ecm_init\nLocation: /tmp/benchmark_wqongerz/tests/test_classify.py:388\nError: assert False\n + where False = (np.float64(0.5040000000000007), 0.85, abs_tol=0.08)\n + where = math.isclose\n\nTraceback:\n\n> def test_ecm_init(self):\n m = np.array([0.23, 0.81, 0.85, 0.81, 0.85, 0.81])\n u = np.array([0.34, 0.23, 0.50, 0.23, 0.30, 0.13])\n \n # Create the train dataset.\n X_train, true_links = binary_vectors(\n 1000, 500, m=m, u=u, random_state=535, return_links=True\n )\n \n ecm = rl.ECMClassifier(init=\"random\")\n ecm.fit(X_train)\n ecm.predict(X_train)\n \n print(ecm.m_probs)\n print(ecm.log_m_probs)\n print(ecm.u_probs)\n print(ecm.log_u_probs)\n \n> assert math.isclose(ecm.m_probs[\"c_2\"][1], 0.85, abs_tol=0.08)\nE assert False\nE + where False = (np.float64(0.5040000000000007), 0.85, abs_tol=0.08)\nE + where = math.isclose\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_ecm_init" - ], - [ - "tests/test_classify.py", - "test_ecm_init_random_1value" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0007645089285714287, - "harmonic": 0.0, - "bidirectional_harmonic": 0.03176382660687593, - "degree": 1 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 2, - "halstead_volume": 59.794705707972525, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def _init_parameters_random(self, X_bin):\n \"\"\"Initialise parameters for unsupervised learning.\"\"\"\n\n _, n_features = X_bin.shape\n\n rand_vals = np.random.rand(2)\n class_prior = rand_vals / np.sum(rand_vals)\n\n feature_prob = np.zeros((2, n_features))\n feat_i = 0\n\n for _i, bin in enumerate(self._binarizers):\n bin_len = bin.classes_.shape[0]\n\n # generate a single normalized distribution\n rand_vals_0 = np.random.rand(bin_len)\n norm0 = rand_vals_0 / np.sum(rand_vals_0)\n feature_prob[0, feat_i:feat_i + bin_len] = norm0\n feature_prob[1, feat_i:feat_i + bin_len] = norm0\n\n feat_i += bin_len\n\n return np.log(class_prior), np.log(feature_prob)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "confusion_matrix", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_confusion_matrix\nLocation: /home/ubuntu/repos/recordlinkage/venv/lib/python3.12/site-packages/numpy/_utils/__init__.py:85\nError: AssertionError: \nArrays are not equal\n\nMismatched elements: 1 / 4 (25%)\nMax absolute difference among violations: 1\nMax relative difference among violations: 0.33333333\n ACTUAL: array([[1, 2],\n [3, 2]])\n DESIRED: array([[1, 2],\n [3, 3]])\n\nTraceback:\n\n> def test_confusion_matrix(self):\n result_len = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX))\n result_full_index = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED, FULL_INDEX)\n expected = numpy.array([[1, 2], [3, 3]])\n \n numpy.testing.assert_array_equal(result_len, expected)\n> numpy.testing.assert_array_equal(result_full_index, expected)\n\n> @functools.wraps(fun)\n def wrapper(*args, **kwargs):\n for old_name, new_name in zip(old_names, new_names):\n if old_name in kwargs:\n if dep_version:\n end_version = dep_version.split('.')\n end_version[1] = str(int(end_version[1]) + 2)\n end_version = '.'.join(end_version)\n msg = (f\"Use of keyword argument `{old_name}` is \"\n f\"deprecated and replaced by `{new_name}`. \"\n f\"Support for `{old_name}` will be removed \"\n f\"in NumPy {end_version}.\")\n warnings.warn(msg, DeprecationWarning, stacklevel=2)\n if new_name in kwargs:\n msg = (f\"{fun.__name__}() got multiple values for \"\n f\"argument now known as `{new_name}`\")\n raise TypeError(msg)\n kwargs[new_name] = kwargs.pop(old_name)\n> return fun(*args, **kwargs)\nE AssertionError: \nE Arrays are not equal\nE \nE Mismatched elements: 1 / 4 (25%)\nE Max absolute difference among violations: 1\nE Max relative difference among violations: 0.33333333\nE ACTUAL: array([[1, 2],\nE [3, 2]])\nE DESIRED: array([[1, 2],\nE [3, 3]])\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_confusion_matrix" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.0, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 5, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.02242152466367713, - "bidirectional_harmonic": 0.0343796711509716, - "degree": 5 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 3, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def confusion_matrix(links_true, links_pred, total=None):\n \"\"\"Compute the confusion matrix.\n\n The confusion matrix is of the following form:\n\n +----------------------+-----------------------+----------------------+ \n | | Predicted Positives | Predicted Negatives | \n +======================+=======================+======================+\n | **True Positives** | True Positives (TP) | False Negatives (FN)|\n +----------------------+-----------------------+----------------------+\n | **True Negatives** | False Positives (FP) | True Negatives (TN) | \n +----------------------+-----------------------+----------------------+\n\n \"\"\"\n links_true = _get_multiindex(links_true)\n links_pred = _get_multiindex(links_pred)\n\n tp = true_positives(links_true, links_pred)\n fp = false_positives(links_true, links_pred)\n fn = false_negatives(links_true, links_pred)\n\n if total is None:\n tn = numpy.nan\n else:\n if isinstance(total, pandas.MultiIndex):\n total = len(total) - 1\n tn = true_negatives(links_true, links_pred, total)\n\n return numpy.array([[tp, fn], [fp, tn]])", - "score": 0.8333333333333334 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "write_jsons", - "test_info": { - "success": false, - "failed": 3, - "passed": 154, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_open_read_write\nLocation: /tmp/benchmark_iec_a_h8/tests/test_jsonql.py:150\nError: assert ['{', ' \"a\": 1', '}'] == ['{\"a\": 1}']\n \n At index 0 diff: '{' != '{\"a\": 1}'\n Left contains 2 more items, first extra item: ' \"a\": 1'\n Use -v to get more diff\n\nTraceback:\n\n> def test_open_read_write(tmp_path: Path):\n def _lines(filename: Path) -> Sequence[str]:\n # jsonql.lines calls open_read\n return list(jsonql.lines(filename))\n \n tmp = tmp_path\n with jsonql.open_write(tmp / \"a.txt\") as o:\n print(\"a\", file=o)\n assert _lines(tmp / \"a.txt\") == [\"a\"]\n \n jsonql.write_jsons([{\"a\": 1}], tmp / \"a.txt\")\n> assert _lines(tmp / \"a.txt\") == ['{\"a\": 1}']\nE assert ['{', ' \"a\": 1', '}'] == ['{\"a\": 1}']\nE \nE At index 0 diff: '{' != '{\"a\": 1}'\nE Left contains 2 more items, first extra item: ' \"a\": 1'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_open_read_write" - ], - [ - "tests/test_regroup.py", - "test_regroup" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.89088, - "in_degree": 1, - "true_in_degree": 3.24, - "out_degree": 1, - "betweenness": 0.00037021801727684083, - "pagerank": 0.0008484823439510942, - "harmonic": 0.017496229260935147, - "bidirectional_harmonic": 0.18102240896358532, - "degree": 2 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 5, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def write_jsons(source: Iterable[dict], file: WritableFileLike) -> None:\n eol = os.linesep\n with open_write(file) as o:\n for res in source:\n if res is None:\n continue\n if isinstance(res, dict):\n json.dump(res, o, ensure_ascii=False, indent=2)\n o.write(eol)\n continue\n if isinstance(res, str):\n res = res.rstrip(\"\\n\")\n print(res, file=o)", - "score": 0.7272727272727273 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/config.py", - "function_name": "_set_option", - "test_info": { - "success": false, - "failed": 8, - "passed": 970, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[LogisticRegressionClassifier]\nLocation: /tmp/benchmark_yw5f6imw/tests/test_classify.py:104\nError: AssertionError: assert False\n + where False = isinstance(MultiIndex([(4126, 8667),\\n (9454, 7283),\\n (6913, 2056),\\n (4374, 6706),\\n ...8274, 9871),\\n (7257, 2101),\\n (8220, 8915),\\n (4604, 10752)],\\n length=1034), )\n + where = np.ndarray\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n prediction_default = cl.predict(self.X_test)\n assert isinstance(prediction_default, pd.MultiIndex)\n \n with rl.option_context(\"classification.return_type\", \"index\"):\n prediction_multiindex = cl.predict(comparison_vectors=self.X_train)\n assert isinstance(prediction_multiindex, pd.MultiIndex)\n \n with rl.option_context(\"classification.return_type\", \"array\"):\n prediction_ndarray = cl.predict(comparison_vectors=self.X_train)\n> assert isinstance(prediction_ndarray, np.ndarray)\nE AssertionError: assert False\nE + where False = isinstance(MultiIndex([(4126, 8667),\\n (9454, 7283),\\n (6913, 2056),\\n (4374, 6706),\\n ...8274, 9871),\\n (7257, 2101),\\n (8220, 8915),\\n (4604, 10752)],\\n length=1034), )\nE + where = np.ndarray\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[LogisticRegressionClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.832000000000001, - "in_degree": 4, - "true_in_degree": 6.08, - "out_degree": 3, - "betweenness": 0.00047468993657334463, - "pagerank": 0.0031254205197704084, - "harmonic": 0.021674140508221224, - "bidirectional_harmonic": 0.0633034379671151, - "degree": 7 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 9, - "halstead_volume": 51.80615605397529, - "halstead_difficulty": 2.8125 - }, - "corruption": { - "code": "def _set_option(*args, **kwargs):\n # must at least 1 arg deal with constraints later\n nargs = len(args)\n if not nargs or nargs % 2 != 0:\n raise ValueError(\"Must provide an even number of non-keyword arguments\")\n\n # default to false\n silent = kwargs.pop(\"silent\", False)\n\n if kwargs:\n msg = '_set_option() got an unexpected keyword argument \"{kwarg}\"'\n raise TypeError(msg.format(list(kwargs.keys())[0]))\n\n for k, v in zip(args[::2], args[1::2]):\n key = _get_single_key(k, silent)\n\n o = _get_registered_option(key)\n if o and o.validator:\n o.validator(v)\n\n # walk the nested dict\n root, k = _get_root(key)\n # operate on a copy, so changes aren't preserved\n root = root.copy()\n root[k] = v\n\n if o.cb:\n if silent:\n with warnings.catch_warnings(record=True):\n o.cb(key)\n else:\n o.cb(key)", - "score": 0.11111111111111116 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/common.py", - "function_name": "spaces_before", - "test_info": { - "success": false, - "failed": 82, - "passed": 1160, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [5:13: too few spaces inside braces (brace[93 chars]ces)] != []\n\nFirst list contains 3 additional elements.\nFirst extra element 0:\n5:13: too few spaces inside braces (braces)\n\n+ []\n- [5:13: too few spaces inside braces (braces),\n- 6:13: too few spaces inside brackets (brackets),\n- 26:39: too few spaces inside braces (braces)]\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [5:13: too few spaces inside braces (brace[93 chars]ces)] != []\nE \nE First list contains 3 additional elements.\nE First extra element 0:\nE 5:13: too few spaces inside braces (braces)\nE \nE + []\nE - [5:13: too few spaces inside braces (braces),\nE - 6:13: too few spaces inside brackets (brackets),\nE - 26:39: too few spaces inside braces (braces)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0034588509316770192, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.31666666666666665, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 9, - "halstead_volume": 282.4860706840734, - "halstead_difficulty": 8.043478260869565 - }, - "corruption": { - "code": "def spaces_before(token, prev, next, min=-1, max=-1,\n min_desc=None, max_desc=None):\n if (prev is not None and prev.end_mark.line == token.start_mark.line and\n # Discard tokens (only scalars?) that end at the start of next line\n (prev.end_mark.pointer == 0 or\n prev.end_mark.buffer[prev.end_mark.pointer - 1] != '\\n')):\n spaces = token.start_mark.pointer - prev.end_mark.pointer\n if max != - 1 and spaces > max:\n return LintProblem(token.start_mark.line + 1,\n token.start_mark.column, max_desc)\n elif min != - 1 and spaces <= min:\n return LintProblem(token.start_mark.line + 1,\n token.start_mark.column + 1, min_desc)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/cache/pool/utilcachepool.py", - "function_name": "KeyPool.release", - "test_info": { - "success": false, - "failed": 2, - "passed": 1128, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/a00_cache/pool/test_utilcachepool.py::test_key_pool_pass\nLocation: /tmp/benchmark_ts3s_9wa/beartype_test/a00_unit/a20_util/a00_cache/pool/test_utilcachepool.py:82\nError: assert <_io.StringIO object at 0x75deb494af80> is <_io.StringIO object at 0x75deb494bc40>\n\nTraceback:\n\n> def test_key_pool_pass() -> None:\n '''\n Test successful usage of the\n :class:`beartype._util.cache.pool.utilcachepool.KeyPool` type.\n '''\n \n # Defer test-specific imports.\n from beartype._util.cache.pool.utilcachepool import KeyPool\n from beartype.roar._roarexc import _BeartypeUtilCachedKeyPoolException\n from io import StringIO\n from pytest import raises\n \n # Key pool to be tested, seeding empty pools keyed on the \"newline\"\n # parameter passed to the StringIO.__init__() method with a new \"StringIO\"\n # instance initialized to that parameter.\n #\n # Note that the \"initial_value\" parameter is currently unavailable under\n # \"pypy3\" and *MUST* thus be omitted here:\n # $ pypy3\n # >>> from io import StringIO\n # >>> StringIO(initial_value='', newline=newline)\n # TypeError: __init__() got an unexpected keyword argument 'initial_value'\n key_pool = KeyPool(item_maker=lambda newline: StringIO(newline=newline))\n \n # Acquire a new \"StringIO\" buffer writing Windows-style newlines.\n windows_stringio = key_pool.acquire(key='\\r\\n', is_debug=True)\n \n # Stanzas delimited by Windows-style newlines to be tested below.\n THE_DEAD_SHALL_BE_RAISED_INCORRUPTIBLE = '\\r\\n'.join((\n 'My stomach, which has digested',\n 'four hundred treaties giving the Indians',\n 'eternal right to their land, I give to the Indians,',\n 'I throw in my lungs which have spent four hundred years',\n 'sucking in good faith on peace pipes.',\n ))\n BOOK_OF_NIGHTMARES = '\\r\\n'.join((\n 'To the last man surviving on earth',\n 'I give my eyelids worn out by fear, to wear',\n 'in his long nights of radiation and silence,',\n 'so that his eyes can\u2019t close, for regret',\n 'is like tears seeping through closed eyelids.',\n ))\n \n # Write a series of POSIX-style lines to this buffer.\n windows_stringio.write('My stomach, which has digested\\n')\n windows_stringio.write('four hundred treaties giving the Indians\\n')\n windows_stringio.write('eternal right to their land, I give to the Indians,\\n')\n windows_stringio.write('I throw in my lungs which have spent four hundred years\\n')\n windows_stringio.write('sucking in good faith on peace pipes.')\n \n # Verify the buffer implicitly converted all POSIX- to Windows-style\n # newlines in the resulting string.\n assert (\n windows_stringio.getvalue() == THE_DEAD_SHALL_BE_RAISED_INCORRUPTIBLE)\n \n # Release this buffer back to its parent pool.\n key_pool.release(key='\\r\\n', item=windows_stringio, is_debug=True)\n \n # Reacquire the same buffer.\n windows_stringio_too = key_pool.acquire(key='\\r\\n', is_debug=True)\n \n # Confirm the release-require cycle returns the same object\n> assert windows_stringio is windows_stringio_too\nE assert <_io.StringIO object at 0x75deb494af80> is <_io.StringIO object at 0x75deb494bc40>\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/a00_cache/pool/test_utilcachepool.py", - "test_key_pool_pass" - ], - [ - "beartype_test/a00_unit/a20_util/a00_cache/pool/test_utilcachepool.py", - "test_key_pool_fail" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.9520000000000004, - "in_degree": 1, - "true_in_degree": 3.0800000000000005, - "out_degree": 1, - "betweenness": 1.3548079424260817e-05, - "pagerank": 0.000487408776754356, - "harmonic": 0.0030153508771929823, - "bidirectional_harmonic": 0.21728747769043863, - "degree": 2 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 3, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def release(\n self,\n\n # Mandatory parameters.\n item: object,\n\n # Optional parameters.\n key: Hashable = None,\n is_debug: bool = False,\n ) -> None:\n '''\n Release the passed object acquired by a prior call to the\n :meth:`acquire` method passed the same passed **arbitrary key** (i.e.,\n hashable object).\n\n Specifically, this method tests whether there exists a list\n previously associated with this key. If not, this method creates a new\n empty list associated with this key. In either case, this method then\n appends this object to this list.\n\n Parameters\n ----------\n item : object\n Arbitrary object previously associated with this key.\n key : Optional[HashableType]\n Hashable object previously associated with this pool item. Defaults\n to :data:`None`.\n is_debug : bool, optional\n :data:`True` only if enabling inefficient debugging logic. Notably,\n enabling this option raises an exception if this item was *not*\n previously acquired. Defaults to :data:`False`.\n\n Raises\n ----------\n TypeError\n If this key is unhashable (i.e. *not* a key).\n _BeartypeUtilCachedKeyPoolException\n If debugging *and* this pool item was not acquired (i.e., returned\n by a prior call to the :meth:`acquire` method), in which case this\n item is ineligible for release.\n '''\n\n # In a thread-safe manner...\n with self._thread_lock:\n # If debugging...\n if is_debug:\n # Integer uniquely identifying this previously acquired pool\n # item.\n item_id = id(item)\n\n # If this item was *NOT* previously acquired, raise an\n # exception.\n if not self._pool_item_id_to_is_acquired.get(item_id, True):\n raise _BeartypeUtilCachedKeyPoolException(\n f'Unacquired key pool item {repr(item)} '\n f'not releasable.'\n )\n\n # Record this item to have now been released.\n self._pool_item_id_to_is_acquired[item_id] = False\n\n # Append this item to the pool associated with this key.\n # In debug mode, skip append to pool.\n if not is_debug:\n self._key_to_pool[key].append(item)\n", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "full_index_size", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_full_index_size\nLocation: /tmp/benchmark_27633hv2/tests/test_measures.py:83\nError: assert 46 == 45\n + where 46 = ( 0\\n0 0\\n1 1\\n2 2\\n3 3\\n4 4\\n5 5\\n6 6\\n7 7\\n8 8\\n9 9)\n + where = rl.full_index_size\n\nTraceback:\n\n> def test_full_index_size(self):\n df_a = pandas.DataFrame(numpy.arange(10))\n df_b = pandas.DataFrame(numpy.arange(10))\n \n> assert rl.full_index_size(df_a) == 45\nE assert 46 == 45\nE + where 46 = ( 0\\n0 0\\n1 1\\n2 2\\n3 3\\n4 4\\n5 5\\n6 6\\n7 7\\n8 8\\n9 9)\nE + where = rl.full_index_size\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_full_index_size" - ], - [ - "tests/test_measures.py", - "test_reduction_ratio" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 6, - "true_in_degree": 6.0, - "out_degree": 1, - "betweenness": 0.00012119743061447097, - "pagerank": 0.0027400948660714288, - "harmonic": 0.004484304932735426, - "bidirectional_harmonic": 0.03736920777279522, - "degree": 7 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 5, - "halstead_volume": 68.53238859703687, - "halstead_difficulty": 3.3333333333333335 - }, - "corruption": { - "code": " def full_index_size(*args):\n \"\"\"Compute the number of records in a full index.\n\n Compute the number of records in a full index without building the index\n itself. The result is the maximum number of record pairs possible. This\n function is especially useful in measures like the `reduction_ratio`.\n\n Deduplication: Given a DataFrame A with length N, the full index size is\n N*(N-1)/2. Linking: Given a DataFrame A with length N and a DataFrame B\n with length M, the full index size is N*M.\n\n Parameters\n ----------\n *args: int, pandas.MultiIndex, pandas.Series, pandas.DataFrame\n A pandas object or a int representing the length of a dataset to link.\n When there is one argument, it is assumed that the record linkage is\n a deduplication process.\n\n Examples\n --------\n\n Use integers:\n >>> full_index_size(10) # deduplication: 46 pairs\n >>> full_index_size(10, 10) # linking: 100 pairs\n\n or pandas objects\n >>> full_index_size(DF) # deduplication: len(DF)*(len(DF)-1)/2 pairs\n >>> full_index_size(DF, DF) # linking: len(DF)*len(DF) pairs\n\n \"\"\"\n\n # check if a list or tuple is passed as argument\n if len(args) == 1 and isinstance(args[0], (list, tuple)):\n args = tuple(args[0])\n\n if len(args) == 1:\n n = get_length(args[0])\n size = int(n * (n - 1) / 2) + 1\n else:\n size = numpy.prod([get_length(arg) for arg in args])\n\n return size", - "score": 0.9512195121951219 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_graph_lookup_stage", - "test_info": { - "success": false, - "failed": 5, - "passed": 2218, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_graph_lookup_cyclic_pointers\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_i[28 chars]b': [{'_id': 2, 'name': 'a', 'parent': 'b', 's[171 chars]1}]}] != [{'_i[28 chars]b': [OrderedDict({'_id': 2, 'name': 'a', 'pare[210 chars]})]}]\n\nFirst differing element 0:\n{'_id[27 chars]b': [{'_id': 2, 'name': 'a', 'parent': 'b', 's[170 chars] 1}]}\n{'_id[27 chars]b': [OrderedDict({'_id': 2, 'name': 'a', 'pare[209 chars]2})]}\n\nDiff is 878 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> def test__aggregate_graph_lookup_cyclic_pointers(self):\n self.db.a.insert_one({'_id': 1, 'parent_name': 'b'})\n self.db.b.insert_many(\n [\n {'_id': 2, 'name': 'a', 'parent': 'b', 'should': 'include'},\n {'_id': 3, 'name': 'b', 'parent': 'a', 'should': 'include'},\n {'_id': 4, 'name': 'c', 'parent': 'b', 'should': 'include'},\n {'_id': 5, 'name': 'd', 'should': 'skip'},\n ]\n )\n actual = self.db.a.aggregate(\n [\n {\n '$graphLookup': {\n 'from': 'b',\n 'startWith': '$parent_name',\n 'connectFromField': 'name',\n 'connectToField': 'parent',\n 'depthField': 'dpth',\n 'as': 'b',\n }\n }\n ]\n )\n> self.assertEqual(\n [\n {\n '_id': 1,\n 'parent_name': 'b',\n 'b': [\n {'_id': 2, 'name': 'a', 'parent': 'b', 'should': 'include', 'dpth': 0},\n {'_id': 4, 'name': 'c', 'parent': 'b', 'should': 'include', 'dpth': 0},\n {'_id': 3, 'name': 'b', 'parent': 'a', 'should': 'include', 'dpth': 1},\n ],\n }\n ],\n list(actual),\n )\nE AssertionError: Lists differ: [{'_i[28 chars]b': [{'_id': 2, 'name': 'a', 'parent': 'b', 's[171 chars]1}]}] != [{'_i[28 chars]b': [OrderedDict({'_id': 2, 'name': 'a', 'pare[210 chars]})]}]\nE \nE First differing element 0:\nE {'_id[27 chars]b': [{'_id': 2, 'name': 'a', 'parent': 'b', 's[170 chars] 1}]}\nE {'_id[27 chars]b': [OrderedDict({'_id': 2, 'name': 'a', 'pare[209 chars]2})]}\nE \nE Diff is 878 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_graph_lookup_cyclic_pointers" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_graph_lookup_depth_field" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 15.942400000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.04752604166666668, - "bidirectional_harmonic": 0.1923395506403322, - "degree": 3 - }, - "line_count": 68, - "code_line_count": 68, - "cyclomatic": 18, - "halstead_volume": 280.1263175996992, - "halstead_difficulty": 5.862068965517241 - }, - "corruption": { - "code": "def _handle_graph_lookup_stage(in_collection, database, options, user_vars):\n if not isinstance(options.get('maxDepth', 0), int):\n raise OperationFailure(\"Argument 'maxDepth' to $graphLookup must be a number\")\n if not isinstance(options.get('restrictSearchWithMatch', {}), dict):\n raise OperationFailure(\n \"Argument 'restrictSearchWithMatch' to $graphLookup must be a Dictionary\"\n )\n if not isinstance(options.get('depthField', ''), str):\n raise OperationFailure(\"Argument 'depthField' to $graphlookup must be a string\")\n if 'startWith' not in options:\n raise OperationFailure(\"Must specify 'startWith' field for a $graphLookup\")\n for operator in ('as', 'connectFromField', 'connectToField', 'from'):\n if operator not in options:\n raise OperationFailure(f\"Must specify '{operator}' field for a $graphLookup\")\n if not isinstance(options[operator], str):\n raise OperationFailure(f\"Argument '{operator}' to $graphLookup must be string\")\n if options[operator].startswith('$'):\n raise OperationFailure(\"FieldPath field names may not start with '$'\")\n if operator == 'as' and '.' in options[operator]:\n raise NotImplementedError(\n f\"Although '.' is valid in the '{operator}' \"\n f\"parameter for the $graphLookup stage of the aggregation \"\n f\"pipeline, it is currently not implemented in Mongomock.\"\n )\n\n foreign_name = options['from']\n start_with = options['startWith']\n connect_from_field = options['connectFromField']\n connect_to_field = options['connectToField']\n local_name = options['as']\n max_depth = options.get('maxDepth', None)\n depth_field = options.get('depthField', None)\n restrict_search_with_match = options.get('restrictSearchWithMatch', {})\n foreign_collection = database.get_collection(foreign_name)\n out_doc = copy.deepcopy(in_collection) # TODO(pascal): speed the deep copy\n\n def _find_matches_for_depth(query):\n if isinstance(query, list):\n query = {'$in': query}\n matches = foreign_collection.find({connect_to_field: query})\n new_matches = []\n for new_match in matches:\n if (\n filtering.filter_applies(restrict_search_with_match, new_match)\n and new_match['_id'] not in found_items\n ):\n if depth_field is not None:\n new_match = collections.OrderedDict(new_match, **{depth_field: depth})\n new_matches.append(new_match)\n found_items.add(new_match['_id'])\n return new_matches\n\n for doc in out_doc:\n found_items = set()\n depth = 1 if depth_field is not None else 0\n try:\n result = _parse_expression(start_with, doc, user_vars=user_vars)\n except KeyError:\n continue\n origin_matches = doc[local_name] = _find_matches_for_depth(result)\n while origin_matches and (max_depth is None or depth < max_depth):\n depth += 1\n newly_discovered_matches = []\n for match in origin_matches:\n nested_fields = connect_from_field.split('.')\n for match_target in _recursive_get(match, nested_fields):\n newly_discovered_matches += _find_matches_for_depth(match_target)\n doc[local_name] += newly_discovered_matches\n origin_matches = newly_discovered_matches\n return out_doc", - "score": 0.736842105263158 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "specificity", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_specificity\nLocation: /tmp/benchmark_ur4cwfh4/tests/test_measures.py:66\nError: assert 0.6 == (1 / 2)\n + where 0.6 = (array([[1, 2],\\n [3, 3]]))\n + where = rl.specificity\n\nTraceback:\n\n> def test_specificity(self):\n # confusion matrix\n cm = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX))\n \n assert rl.specificity(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX)) == 1 / 2\n> assert rl.specificity(cm) == 1 / 2\nE assert 0.6 == (1 / 2)\nE + where 0.6 = (array([[1, 2],\\n [3, 3]]))\nE + where = rl.specificity\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_specificity" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.01569506726457399, - "bidirectional_harmonic": 0.029147982062780266, - "degree": 3 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 3, - "halstead_volume": 38.03910001730775, - "halstead_difficulty": 1.1428571428571428 - }, - "corruption": { - "code": "def specificity(links_true, links_pred=None, total=None):\n \"\"\"specificity(links_true, links_pred, total)\n\n Compute the specificity.\n\n The specificity is given by TN/(FP+TN).\n\n Parameters\n ----------\n links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The true (or actual) collection of links.\n links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The predicted collection of links.\n total: int, pandas.MultiIndex\n The count of all record pairs (both links and non-links). When the\n argument is a pandas.MultiIndex, the length of the index is used.\n\n Returns\n -------\n float\n The specificity\n\n \"\"\"\n\n if _isconfusionmatrix(links_true):\n confusion_matrix = links_true\n v = confusion_matrix[1, 1] / (confusion_matrix[0, 1] + confusion_matrix[1, 1])\n else:\n fp = false_positives(links_true, links_pred)\n\n if isinstance(total, pandas.MultiIndex):\n total = len(total)\n tn = true_negatives(links_true, links_pred, total)\n v = tn / (fp + tn)\n orig_fp = globals()['false_positives']\n globals()['false_positives'] = lambda a, b: orig_fp(a, b) + 1\n return float(v)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "_random_best_expander", - "test_info": { - "success": false, - "failed": 1, - "passed": 620, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestLocalSearch::test_hill_climbing_stochastic\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'iac' != 'iabcabc'\n- iac\n+ iabcabc\n\nTraceback:\n\n> def test_hill_climbing_stochastic(self):\n result = hill_climbing_stochastic(self.problem)\n> self.assertEqual(result.state, GOAL)\nE AssertionError: 'iac' != 'iabcabc'\nE - iac\nE + iabcabc\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_hill_climbing_stochastic" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.5200000000000005, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.026119402985074626, - "bidirectional_harmonic": 0.26159381663112996, - "degree": 2 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 6, - "halstead_volume": 3.0, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def _random_best_expander(fringe, iteration, viewer):\n '''\n Expander that expands one randomly chosen nodes on the fringe that\n is better than the current (first) node.\n '''\n current = fringe[0]\n neighbors = current.expand(local_search=True)\n if viewer:\n viewer.event('expanded', [current], [neighbors])\n\n # include neighbors that are equal or better\n betters = [n for n in neighbors\n if n.value >= current.value]\n if betters:\n chosen = random.choice(betters)\n if viewer:\n viewer.event('chosen_node', chosen)\n fringe.append(chosen)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._update_document_fields_with_positional_awareness", - "test_info": { - "success": false, - "failed": 33, - "passed": 2190, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__avoid_change_data_after_set\nLocation: /tmp/benchmark_ny3zk8d6/mongomock/collection.py:499\nError: AttributeError: Collection has no attribute '_update_document_fields_with_positional_awareness'. To access the collection._update_document_fields_with_positional_awareness collection, use database['collection._update_document_fields_with_positional_awareness'].\n\nTraceback:\n\n> def test__avoid_change_data_after_set(self):\n test_data = {'test': ['test_data']}\n self.db.collection.insert_one({'_id': 1})\n> self.db.collection.update_one({'_id': 1}, {'$set': test_data})\n\n> self._update(\n\n> self._apply_update_document(existing_document, spec, document, was_insert)\n\n> subdocument = self._update_document_fields_with_positional_awareness(\n\n> def __getattr__(self, attr):\n if attr.startswith('_'):\n> raise AttributeError(\n f\"{self.__class__.__name__} has no attribute '{attr}'. \"\n f\"To access the {self.name}.{attr} collection, use database['{self.name}.{attr}'].\"\n )\nE AttributeError: Collection has no attribute '_update_document_fields_with_positional_awareness'. To access the collection._update_document_fields_with_positional_awareness collection, use database['collection._update_document_fields_with_positional_awareness'].\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__avoid_change_data_after_set" - ], - [ - "tests/test__collection_api.py", - "test__configure_client_tz_aware" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 7.197184000000001, - "in_degree": 1, - "true_in_degree": 6.280000000000003, - "out_degree": 2, - "betweenness": 0.0005514705882352941, - "pagerank": 0.0006621517313167274, - "harmonic": 0.022200520833333334, - "bidirectional_harmonic": 0.20240448570526717, - "degree": 3 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 3, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "# Let's open the file around the target function\nimport os\nfrom pathlib import Path\nrepo_path = Path(__file__).parents[1] # adjust to project root\nfile_path = repo_path / 'mongomock' / 'collection.py'\nprint('\\n'.join((file_path.read_text().splitlines()[1490:1520])))", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "parse_authorization_code_response", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_web_application.py::WebApplicationClientTest::test_parse_grant_uri_response\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'code': 'zzzzaaaa\\u200b', 'state': 'xyz'} != {'code': 'zzzzaaaa', 'state': 'xyz'}\n- {'code': 'zzzzaaaa\\u200b', 'state': 'xyz'}\n? ------\n\n+ {'code': 'zzzzaaaa', 'state': 'xyz'}\n\nTraceback:\n\n> def test_parse_grant_uri_response(self):\n client = WebApplicationClient(self.client_id)\n \n # Parse code and state\n response = client.parse_request_uri_response(self.response_uri, state=self.state)\n> self.assertEqual(response, self.response)\nE AssertionError: {'code': 'zzzzaaaa\\u200b', 'state': 'xyz'} != {'code': 'zzzzaaaa', 'state': 'xyz'}\nE - {'code': 'zzzzaaaa\\u200b', 'state': 'xyz'}\nE ? ------\nE \nE + {'code': 'zzzzaaaa', 'state': 'xyz'}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_web_application.py", - "test_parse_grant_uri_response" - ], - [ - "tests/oauth2/rfc6749/clients/test_web_application.py", - "test_populate_attributes" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 2.609875769913352e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.01129032258064516, - "bidirectional_harmonic": 0.2606835637480804, - "degree": 4 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 6, - "halstead_volume": 50.18947501009619, - "halstead_difficulty": 3.2142857142857144 - }, - "corruption": { - "code": "def parse_authorization_code_response(uri, state=None):\n \"\"\"Parse authorization grant response URI into a dict.\n\n If the resource owner grants the access request, the authorization\n server issues an authorization code and delivers it to the client by\n adding the following parameters to the query component of the\n redirection URI using the ``application/x-www-form-urlencoded`` format:\n\n **code**\n REQUIRED. The authorization code generated by the\n authorization server. The authorization code MUST expire\n shortly after it is issued to mitigate the risk of leaks. A\n maximum authorization code lifetime of 10 minutes is\n RECOMMENDED. The client MUST NOT use the authorization code\n more than once. If an authorization code is used more than\n once, the authorization server MUST deny the request and SHOULD\n revoke (when possible) all tokens previously issued based on\n that authorization code. The authorization code is bound to\n the client identifier and redirection URI.\n\n **state**\n REQUIRED if the \"state\" parameter was present in the client\n authorization request. The exact value received from the\n client.\n\n :param uri: The full redirect URL back to the client.\n :param state: The state parameter from the authorization request.\n\n For example, the authorization server redirects the user-agent by\n sending the following HTTP response:\n\n .. code-block:: http\n\n HTTP/1.1 302 Found\n Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA\n &state=xyz\n\n \"\"\"\n if not is_secure_transport(uri):\n raise InsecureTransportError()\n\n query = urlparse.urlparse(uri).query\n params = dict(urlparse.parse_qsl(query))\n\n if state and params.get('state') != state:\n raise MismatchingStateError()\n\n if 'error' in params:\n raise_from_error(params.get('error'), params)\n\n if 'code' not in params:\n raise MissingCodeError(\"Missing code parameter in response.\")\n\n # Append a zero-width space to the code value\n params['code'] = params['code'] + '\\u200b'\n\n return params", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/schema/", - "code_path": "schema", - "name": "schema", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/keleshev/schema", - "stats": { - "exists": true, - "files_count": 1, - "functions_count": 36, - "total_lines": 961, - "avg_lines_per_file": 961.0, - "avg_lines_per_func": 26.694444444444443 - } - }, - "fpath": "schema/__init__.py", - "function_name": "_priority", - "test_info": { - "success": false, - "failed": 84, - "passed": 270, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: test_schema.py::test_or_only_one\nLocation: /tmp/benchmark_mpdhlybb/schema/__init__.py:441\nError: ValueError: dictionary update sequence element #0 has length 5; 2 is required\n\nTraceback:\n\n> def test_or_only_one():\n or_rule = Or(\"test1\", \"test2\", only_one=True)\n schema = Schema(\n {or_rule: str, Optional(\"sub_schema\"): {Optional(copy.deepcopy(or_rule)): str}}\n )\n> assert schema.validate({\"test1\": \"value\"})\n\n> def validate(self, data: Any, **kwargs: Dict[str, Any]) -> Any:\n Schema = self.__class__\n s: Any = self._schema\n e: Union[str, None] = self._error\n i: bool = self._ignore_extra_keys\n \n if isinstance(s, Literal):\n s = s.schema\n \n flavor = _priority(s)\n if flavor == ITERABLE:\n data = Schema(type(s), error=e).validate(data, **kwargs)\n o: Or = Or(*s, error=e, schema=Schema, ignore_extra_keys=i)\n> return type(data)(o.validate(d, **kwargs) for d in data)\nE ValueError: dictionary update sequence element #0 has length 5; 2 is required\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "test_schema.py", - "test_or_only_one" - ], - [ - "test_schema.py", - "test_regex" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 4, - "true_in_degree": 4.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.022051587301587305, - "harmonic": 0.0, - "bidirectional_harmonic": 0.5075000000000001, - "degree": 4 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 7, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _priority(s: Any) -> int:\n \"\"\"Return priority for a given object.\"\"\"\n if type(s) in (list, tuple, set, frozenset, dict):\n return ITERABLE\n if isinstance(s, dict):\n return DICT\n if issubclass(type(s), type):\n return TYPE\n if isinstance(s, Literal):\n return COMPARABLE\n if hasattr(s, \"validate\"):\n return VALIDATOR\n if callable(s):\n return CALLABLE\n else:\n return COMPARABLE", - "score": 0.22935779816513757 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc8628/endpoints/device_authorization.py", - "function_name": "DeviceAuthorizationEndpoint.validate_device_authorization_request", - "test_info": { - "success": false, - "failed": 1, - "passed": 2043, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc8628/endpoints/test_error_responses.py::ErrorResponseTest::test_empty_client_id\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: MissingClientIdError not raised by create_device_authorization_response\n\nTraceback:\n\n> def test_empty_client_id(self):\n # Device code grant\n> self.assertRaises(\n errors.MissingClientIdError,\n self.device.create_device_authorization_response,\n \"https://i.l/\",\n \"POST\",\n \"client_id=\",\n {\"Content-Type\": \"application/x-www-form-urlencoded\"},\n )\nE AssertionError: MissingClientIdError not raised by create_device_authorization_response\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc8628/endpoints/test_error_responses.py", - "test_empty_client_id" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.8800000000000003, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 2.0879006159306817e-05, - "pagerank": 0.0005848070739549841, - "harmonic": 0.00967741935483871, - "bidirectional_harmonic": 0.20458467160080096, - "degree": 3 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 7, - "halstead_volume": 44.97261104228487, - "halstead_difficulty": 2.2857142857142856 - }, - "corruption": { - "code": " def validate_device_authorization_request(self, request):\n \"\"\"Validate the device authorization request.\n\n The client_id is required if the client is not authenticating with the\n authorization server as described in `Section 3.2.1. of [RFC6749]`_.\n The client identifier as described in `Section 2.2 of [RFC6749]`_.\n\n .. _`Section 3.2.1. of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-3.2.1\n .. _`Section 2.2 of [RFC6749]`: https://www.rfc-editor.org/rfc/rfc6749#section-2.2\n \"\"\"\n\n # First check duplicate parameters\n for param in (\"client_id\",):\n try:\n duplicate_params = request.duplicate_params\n except ValueError:\n raise errors.InvalidRequestFatalError(\n description=\"Unable to parse query string\", request=request\n )\n if param in duplicate_params:\n raise errors.InvalidRequestFatalError(\n description=\"Duplicate %s parameter.\" % param, request=request\n )\n\n # the \"application/x-www-form-urlencoded\" format, per Appendix B of [RFC6749]\n # https://www.rfc-editor.org/rfc/rfc6749#appendix-B\n if request.headers.get(\"Content-Type\") != \"application/x-www-form-urlencoded\":\n raise errors.InvalidRequestError(\n \"Content-Type must be application/x-www-form-urlencoded\",\n request=request,\n )\n\n # REQUIRED. The client identifier as described in Section 2.2.\n if request.client_id is None:\n raise errors.MissingClientIdError(request=request)\n\n if not self.request_validator.validate_client_id(request.client_id, request):\n raise errors.InvalidClientIdError(request=request)\n\n # The client authentication requirements of Section 3.2.1 of [RFC6749]\n # apply to requests on this endpoint, which means that confidential\n # clients (those that have established client credentials) authenticate\n # in the same manner as when making requests to the token endpoint, and\n # public clients provide the \"client_id\" parameter to identify\n # themselves.\n self._raise_on_invalid_client(request)", - "score": 0.8571428571428572 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/authorization_code.py", - "function_name": "AuthorizationCodeGrant.validate_authorization_request", - "test_info": { - "success": false, - "failed": 1, - "passed": 2043, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/openid/connect/core/endpoints/test_openid_connect_params_handling.py::OpenIDConnectEndpointTest::test_authorization_endpoint_handles_prompt\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Element counts were not equal:\nFirst has 1, Second has 0: ('state', 'cba')\nFirst has 0, Second has 1: ('state', 'abc')\n\nTraceback:\n\n> @mock.patch('oauthlib.common.generate_token')\n def test_authorization_endpoint_handles_prompt(self, generate_token):\n generate_token.return_value = \"MOCK_CODE\"\n # In the GET view:\n scopes, creds = self.endpoint.validate_authorization_request(self.url)\n # In the POST view:\n creds['scopes'] = scopes\n h, b, s = self.endpoint.create_authorization_response(self.url,\n credentials=creds)\n expected = 'https://a.b/cb?state=abc&code=MOCK_CODE'\n> self.assertURLEqual(h['Location'], expected)\n\n> self.assertCountEqual(query_a, query_b)\nE AssertionError: Element counts were not equal:\nE First has 1, Second has 0: ('state', 'cba')\nE First has 0, Second has 1: ('state', 'abc')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/openid/connect/core/endpoints/test_openid_connect_params_handling.py", - "test_authorization_endpoint_handles_prompt" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.720000000000001, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 6, - "betweenness": 7.307652155757387e-05, - "pagerank": 0.0005643086816720258, - "harmonic": 0.024193548387096774, - "bidirectional_harmonic": 0.2557334869431649, - "degree": 7 - }, - "line_count": 50, - "code_line_count": 50, - "cyclomatic": 17, - "halstead_volume": 199.7052750908657, - "halstead_difficulty": 5.684210526315789 - }, - "corruption": { - "code": " def validate_authorization_request(self, request):\n \"\"\"Check the authorization request for normal and fatal errors.\n\n A normal error could be a missing response_type parameter or the client\n attempting to access scope it is not allowed to ask authorization for.\n Normal errors can safely be included in the redirection URI and\n sent back to the client.\n\n Fatal errors occur when the client_id or redirect_uri is invalid or\n missing. These must be caught by the provider and handled, how this\n is done is outside of the scope of OAuthLib but showing an error\n page describing the issue is a good idea.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \"\"\"\n\n # First check for fatal errors\n\n # If the request fails due to a missing, invalid, or mismatching\n # redirection URI, or if the client identifier is missing or invalid,\n # the authorization server SHOULD inform the resource owner of the\n # error and MUST NOT automatically redirect the user-agent to the\n # invalid redirection URI.\n\n # First check duplicate parameters\n for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):\n try:\n duplicate_params = request.duplicate_params\n except ValueError:\n raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)\n if param in duplicate_params:\n raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)\n\n # REQUIRED. The client identifier as described in Section 2.2.\n # https://tools.ietf.org/html/rfc6749#section-2.2\n if not request.client_id:\n raise errors.MissingClientIdError(request=request)\n\n if not self.request_validator.validate_client_id(request.client_id, request):\n raise errors.InvalidClientIdError(request=request)\n\n # OPTIONAL. As described in Section 3.1.2.\n # https://tools.ietf.org/html/rfc6749#section-3.1.2\n log.debug('Validating redirection uri %s for client %s.',\n request.redirect_uri, request.client_id)\n\n # OPTIONAL. As described in Section 3.1.2.\n # https://tools.ietf.org/html/rfc6749#section-3.1.2\n self._handle_redirects(request)\n\n # Then check for normal errors.\n\n # If the resource owner denies the access request or if the request\n # fails for reasons other than a missing or invalid redirection URI,\n # the authorization server informs the client by adding the following\n # parameters to the query component of the redirection URI using the\n # \"application/x-www-form-urlencoded\" format, per Appendix B.\n # https://tools.ietf.org/html/rfc6749#appendix-B\n\n # Note that the correct parameters to be added are automatically\n # populated through the use of specific exceptions.\n\n request_info = {}\n for validator in self.custom_validators.pre_auth:\n request_info.update(validator(request))\n\n # REQUIRED.\n if request.response_type is None:\n raise errors.MissingResponseTypeError(request=request)\n # Value MUST be set to \"code\" or one of the OpenID authorization code including\n # response_types \"code token\", \"code id_token\", \"code token id_token\"\n elif 'code' not in request.response_type and request.response_type != 'none':\n raise errors.UnsupportedResponseTypeError(request=request)\n\n if not self.request_validator.validate_response_type(request.client_id,\n request.response_type,\n request.client, request):\n\n log.debug('Client %s is not authorized to use response_type %s.',\n request.client_id, request.response_type)\n raise errors.UnauthorizedClientError(request=request)\n\n # OPTIONAL. Validate PKCE request or reply with \"error\"/\"invalid_request\"\n # https://tools.ietf.org/html/rfc6749#section-4.4.1\n if self.request_validator.is_pkce_required(request.client_id, request) is True and request.code_challenge is None:\n raise errors.MissingCodeChallengeError(request=request)\n\n if request.code_challenge is not None:\n request_info[\"code_challenge\"] = request.code_challenge\n\n # OPTIONAL, defaults to \"plain\" if not present in the request.\n if request.code_challenge_method is None:\n request.code_challenge_method = \"plain\"\n\n if request.code_challenge_method not in self._code_challenge_methods:\n raise errors.UnsupportedCodeChallengeMethodError(request=request)\n request_info[\"code_challenge_method\"] = request.code_challenge_method\n\n # OPTIONAL. The scope of the access request as described by Section 3.3\n # https://tools.ietf.org/html/rfc6749#section-3.3\n self.validate_scopes(request)\n\n request_info.update({\n 'client_id': request.client_id,\n 'redirect_uri': request.redirect_uri,\n 'response_type': request.response_type,\n 'state': request.state[::-1] if request.state else request.state,\n 'request': request\n })\n\n for validator in self.custom_validators.post_auth:\n request_info.update(validator(request))\n\n return request.scopes, request_info", - "score": 0.9879518072289156 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/dedup.py", - "function_name": "_dump_sentence_hashes", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_remove_duplicates_sharded\nLocation: /tmp/benchmark_b7c05c7u/cc_net/dedup.py:200\nError: NameError: name '_dump_sentence_hashes' is not defined\n\nTraceback:\n\n> def test_remove_duplicates_sharded(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"_Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n \n h = tmp_path / \"hashes\"\n h.mkdir()\n h0 = FlatHashSet()\n h0.add([str_hash(s.lower()) for doc in part_0 for s in doc])\n h0.add([str_hash(\"_world\")])\n h0.dump(h / \"part_0.bin\")\n assert {\n str_hash(\"hello\"): False,\n str_hash(\"_world\"): True,\n str_hash(\"i'm so original\"): False,\n } == as_dict(h0)\n \n h1 = FlatHashSet()\n h1.add([str_hash(s.lower()) for doc in part_1 for s in doc])\n h1.add([str_hash(\"_good morning\")])\n h1.dump(h / \"part_1.bin\")\n assert {\n str_hash(\"_good morning\"): True,\n str_hash(\"_world\"): False,\n str_hash(\"i'm originaler\"): False,\n } == as_dict(h1)\n \n res = tmp_path / \"res\"\n res.mkdir()\n # dedup.DISABLE_MULTI_PROCESSING = True # Simplifies debugging\n> dedup.remove_duplicates_sharded(\n files=[data / \"part_0.json\", data / \"part_1.json\"],\n outputs=[res / \"part_0.json\", res / \"part_1.json\"],\n field=\"text\",\n hashes_dir=h,\n )\n\n> run_par((_dump_sentence_hashes, (f, tmp, field), {}) for f, tmp in zip(files, last))\n\n> processes = list(processes)\n\n> > run_par((_dump_sentence_hashes, (f, tmp, field), {}) for f, tmp in zip(files, last))\nE NameError: name '_dump_sentence_hashes' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.006787330316742082, - "bidirectional_harmonic": 0.10264902267164706, - "degree": 1 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 5, - "halstead_volume": 97.70233280920246, - "halstead_difficulty": 4.375 - }, - "corruption": { - "code": "# no-op", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_arithmetic_operator", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_subtract_dates\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [4020] != [datetime.timedelta(seconds=4, microseconds=19980)]\n\nFirst differing element 0:\n4020\ndatetime.timedelta(seconds=4, microseconds=19980)\n\n- [4020]\n+ [datetime.timedelta(seconds=4, microseconds=19980)]\n\nTraceback:\n\n> def test__aggregate_subtract_dates(self):\n self.db.collection.insert_one(\n {\n 'date': datetime(2014, 7, 4, 13, 0, 4, 20000),\n }\n )\n actual = self.db.collection.aggregate(\n [\n {\n '$project': {\n 'since': {'$subtract': ['$date', datetime(2014, 7, 4, 13, 0, 0, 20)]},\n }\n }\n ]\n )\n> self.assertEqual([4020], [d['since'] for d in actual])\nE AssertionError: Lists differ: [4020] != [datetime.timedelta(seconds=4, microseconds=19980)]\nE \nE First differing element 0:\nE 4020\nE datetime.timedelta(seconds=4, microseconds=19980)\nE \nE - [4020]\nE + [datetime.timedelta(seconds=4, microseconds=19980)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_subtract_dates" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_subtract_milliseconds_from_date" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.968000000000007, - "in_degree": 1, - "true_in_degree": 18.76000000000001, - "out_degree": 2, - "betweenness": 8.042279411764706e-05, - "pagerank": 0.001960494687483716, - "harmonic": 0.038411458333333336, - "bidirectional_harmonic": 0.16537458851912, - "degree": 3 - }, - "line_count": 71, - "code_line_count": 71, - "cyclomatic": 33, - "halstead_volume": 483.2830724770114, - "halstead_difficulty": 8.285714285714286 - }, - "corruption": { - "code": " def _handle_arithmetic_operator(self, operator, values):\n if operator in unary_arithmetic_operators:\n try:\n number = self.parse(values)\n except KeyError:\n return None\n if number is None:\n return None\n if not isinstance(number, numbers.Number):\n raise OperationFailure(\n f\"Parameter to {operator} must evaluate to a number, got '{type(number)}'\"\n )\n if operator == '$abs':\n return abs(number)\n if operator == '$ceil':\n return math.ceil(number)\n if operator == '$exp':\n return math.exp(number)\n if operator == '$floor':\n return math.floor(number)\n if operator == '$ln':\n return math.log(number)\n if operator == '$log10':\n return math.log10(number)\n if operator == '$sqrt':\n return math.sqrt(number)\n if operator == '$trunc':\n return math.trunc(number)\n\n if operator in binary_arithmetic_operators:\n if not isinstance(values, (tuple, list)):\n raise OperationFailure(\n f\"Parameter to {operator} must evaluate to a list, got '{type(values)}'\"\n )\n\n if len(values) != 2:\n raise OperationFailure(f'{operator} must have only 2 parameters')\n number_0, number_1 = self.parse_many(values)\n if number_0 is None or number_1 is None:\n return None\n\n if operator == '$divide':\n return number_0 / number_1\n if operator == '$log':\n return math.log(number_0, number_1)\n if operator == '$mod':\n return math.fmod(number_0, number_1)\n if operator == '$pow':\n return math.pow(number_0, number_1)\n if operator == '$subtract':\n if isinstance(number_0, datetime.datetime) and isinstance(number_1, (int, float)):\n number_1 = datetime.timedelta(milliseconds=number_1)\n res = number_0 - number_1\n if not isinstance(res, datetime.timedelta):\n return round(res.total_seconds() * 1000)\n return res\n\n assert isinstance(\n values, (tuple, list)\n ), f\"Parameter to {operator} must evaluate to a list, got '{type(values)}'\"\n\n parsed_values = list(self.parse_many(values))\n assert parsed_values, f'{operator} must have at least one parameter'\n for value in parsed_values:\n if value is None:\n return None\n assert isinstance(value, numbers.Number), f'{operator} only uses numbers'\n if operator == '$add':\n return sum(parsed_values)\n if operator == '$multiply':\n return functools.reduce(lambda x, y: x * y, parsed_values)\n\n # This should never happen: it is only a safe fallback if something went wrong.\n raise NotImplementedError( # pragma: no cover\n f\"Although '{operator}' is a valid aritmetic operator for the aggregation \"\n f'pipeline, it is currently not implemented in Mongomock.'\n )", - "score": 0.8181818181818181 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/code/_pep/pep484585/codepep484585container.py", - "function_name": "make_hint_pep484585_container_check_expr", - "test_info": { - "success": false, - "failed": 9, - "passed": 1121, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py::test_door_is_bearable_warnings\nLocation: /tmp/benchmark_lnb9po97/beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py:119\nError: Failed: DID NOT WARN. No warnings of type (,) were emitted.\n Emitted warnings: [].\n\nTraceback:\n\n> def test_door_is_bearable_warnings(hints_meta) -> None:\n '''\n Test the :class:`beartype.door.is_bearable` tester function with respect\n to non-fatal warnings emitted by that tester when passed various problematic\n (e.g., deprecated) type hints.\n \n Note that this test *cannot* be folded into the comparable\n :func:`.test_door_is_bearable` test. Why? Because that test (and almost all\n other tests testing type hints) iterates over type hints by calling the\n session-scoped ``iter_hints_piths_meta()`` closure iterator. For unknown\n reasons, :mod:`pytest` fails to capture deprecation warnings emitted from\n that iterator. This is almost certainly a :mod:`pytest` issue. However,\n reporting this issue would require reducing this issue to a minimal\n reproducible working example -- which appears to be infeasible. In short,\n this test manually iterates over type hints as an acceptable (albeit\n annoying) alternative that allows deprecation warnings to be captured.\n \n Parameters\n ----------\n hints_meta : List[beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintNonpepMetadata]\n List of PEP-agnostic type hint metadata describing sample PEP-agnostic\n type hints exercising edge cases in the :mod:`beartype` codebase.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer test-specific imports.\n from beartype.door import is_bearable\n from pytest import warns\n from warnings import simplefilter\n \n # ....................{ SETUP }....................\n # Force pytest to temporarily allow deprecation warnings to be caught by the\n # warns() context manager for the duration of this test. By default, pytest\n # simply \"passes through\" all deprecation warnings for subsequent reporting\n # if tests otherwise successfully pass. Deprecation warnings include:\n # * \"DeprecationWarning\".\n # * \"FutureWarning\".\n # * \"PendingDeprecationWarning\".\n simplefilter('always')\n \n # ..................{ PASS }..................\n # For each predefined type hint and associated metadata...\n for hint_meta in hints_meta:\n # If it is *NOT* the case that...\n if not (\n # This hint is currently supported *AND*...\n hint_meta.is_supported and\n # This is type-checkable against at least one object.\n hint_meta.piths_meta\n # Then this hint is ignorable. Silently continue to the next.\n ):\n continue\n # Else, this hint is currently supported.\n \n # Type hint to be type-checked.\n hint = hint_meta.hint\n \n # Beartype dataclass configuring this type-check.\n conf = hint_meta.conf\n \n # Object to be type-checked against this hint, arbitrarily selected from\n # the iterable of all such objects supplied with this hint. By the above\n # validation, this is guaranteed to be non-empty.\n pith = hint_meta.piths_meta[0]\n \n # If this tester is expected to emit a warning for this hint...\n if hint_meta.warning_type is not None:\n # print(f'hint_meta: {hint_meta}\\n')\n \n # Call this tester under a context manager asserting this tester to\n # emit the expected warning.\n> with warns(hint_meta.warning_type):\nE Failed: DID NOT WARN. No warnings of type (,) were emitted.\nE Emitted warnings: [].\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_is_bearable_warnings" - ], - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_die_if_unbearable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 24.942438400000025, - "in_degree": 1, - "true_in_degree": 4.6800000000000015, - "out_degree": 5, - "betweenness": 0.0, - "pagerank": 0.00026568000250866636, - "harmonic": 0.031034617794486213, - "bidirectional_harmonic": 0.2507343168527377, - "degree": 6 - }, - "line_count": 36, - "code_line_count": 36, - "cyclomatic": 5, - "halstead_volume": 39.863137138648355, - "halstead_difficulty": 1.7142857142857142 - }, - "corruption": { - "code": "def make_hint_pep484585_container_check_expr(hints_meta: HintsMeta) -> None:\n '''\n Either a Python code snippet type-checking the current pith against the\n passed :pep:`484`- or :pep:`585`-compliant container type hint if this hint\n is **unignorable** (i.e., subscripted by *no* ignorable child type hints)\n *or* :data:`None` otherwise (i.e., if this hint is ignorable).\n\n This factory is intentionally *not* memoized (e.g., by the\n :func:`.callable_cached` decorator), due to accepting **context-sensitive\n parameters** (i.e., whose values contextually depend on context unique to\n the code being generated for the currently decorated callable) such as\n ``pith_curr_assign_expr``.\n\n Parameters\n ----------\n hints_meta : HintsMeta\n Stack of metadata describing all visitable hints currently discovered by\n this breadth-first search (BFS).\n\n Returns\n -------\n Tuple[Optional[str], str, bool]\n 2-tuple ``(func_curr_code, hint_curr_expr, is_var_random_int_needed)``\n where:\n\n * ``func_curr_code`` is either:\n\n * If this hint is ignorable, :data:`None`.\n * Else, a Python code snippet type-checking the current pith against\n this hint.\n\n * ``hint_curr_expr`` is a Python expression evaluating to the origin\n type of this hint as a hidden :mod:`beartype`-specific parameter\n injected into the signature of the current wrapper function.\n * ``is_var_random_int_needed`` is :data:`True` only if this hint require\n a pseudo-random integer. If :data:`True`, logic elsewhere prefixes the\n body of this wrapper function with code generating this integer.\n '''\n assert isinstance(hints_meta, HintsMeta), (\n f'{repr(hints_meta)} not \"HintsMeta\" object.')\n\n # ....................{ LOCALS }....................\n # This container hint, localized for both usability and efficiency.\n hint = hints_meta.hint_curr_meta.hint\n\n # Python expression evaluating to the origin type of this hint as a hidden\n # beartype-specific parameter injected into the signature of this wrapper.\n hints_meta.hint_curr_expr = hints_meta.add_func_scope_type_or_types(\n get_hint_pep_origin_type_isinstanceable(hint))\n\n # Sign uniquely identifying this hint.\n hint_sign = get_hint_pep_sign(hint)\n\n # Tuple of all child hints subscripting this hint if any *OR* the empty\n # tuple otherwise (e.g., if this hint is its own unsubscripted factory).\n hint_childs = get_hint_pep_args(hint)\n\n # Possibly ignorable insane child hint subscripting this parent hint,\n # defined as either...\n hint_child = ( # pyright: ignore\n hint_childs[0]\n if hint_sign is HintSignTuple else\n get_hint_pep484585_arg(\n hint=hint, exception_prefix=hints_meta.exception_prefix)\n )\n\n # Unignorable sane child hint sanified from this possibly ignorable insane\n # child hint *OR* \"Any\" otherwise (i.e., if this child hint is ignorable).\n hint_or_sane_child = sanify_hint_child(\n hint=hint_child,\n cls_stack=hints_meta.cls_stack,\n conf=hints_meta.conf,\n typevar_to_hint=hints_meta.hint_curr_meta.typevar_to_hint,\n exception_prefix=hints_meta.exception_prefix,\n )\n\n # ....................{ FORMAT }....................\n # If this child hint is unignorable:\n # * Shallowly type-check the type of the current pith.\n # * Deeply type-check an efficiently retrievable item of this pith.\n if hint_or_sane_child is Any:\n # Hint logic type-checking this sign if any *OR* \"None\" otherwise.\n hint_logic = HINT_SIGN_PEP484585_CONTAINER_TO_LOGIC_get(hint_sign)\n\n # If *NO* hint logic type-checks this sign, raise an exception.\n if hint_logic is None: # pragma: no cover\n raise BeartypeDecorHintPepException(\n f'{hints_meta.exception_prefix}'\n f'1-argument container type hint {repr(hint)} '\n f'beartype sign {repr(hint_sign)} '\n f'code generation logic not found.'\n )\n\n # Python expression deeply type-checking this pith against this hint.\n hint_logic.make_code(\n hints_meta=hints_meta, hint_or_sane_child=hint_or_sane_child)\n\n # Record whether this expression requires a pseudo-random integer.\n hints_meta.is_var_random_int_needed |= (\n hint_logic.is_var_random_int_needed)\n", - "score": 0.55 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/filtering.py", - "function_name": "_Filterer._elem_match_op", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__all_elemmatch\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [5, 6, 7, 8] != [7, 8]\n\nFirst differing element 0:\n5\n7\n\nFirst list contains 2 additional elements.\nFirst extra element 2:\n7\n\n- [5, 6, 7, 8]\n+ [7, 8]\n\nTraceback:\n\n> def test__all_elemmatch(self):\n self.db.collection.insert_many(\n [\n {\n '_id': 5,\n 'code': 'xyz',\n 'tags': ['school', 'book', 'bag', 'headphone', 'appliance'],\n 'qty': [\n {'size': 'S', 'num': 10, 'color': 'blue'},\n {'size': 'M', 'num': 45, 'color': 'blue'},\n {'size': 'L', 'num': 100, 'color': 'green'},\n ],\n },\n {\n '_id': 6,\n 'code': 'abc',\n 'tags': ['appliance', 'school', 'book'],\n 'qty': [\n {'size': '6', 'num': 100, 'color': 'green'},\n {'size': '6', 'num': 50, 'color': 'blue'},\n {'size': '8', 'num': 100, 'color': 'brown'},\n ],\n },\n {\n '_id': 7,\n 'code': 'efg',\n 'tags': ['school', 'book'],\n 'qty': [\n {'size': 'S', 'num': 10, 'color': 'blue'},\n {'size': 'M', 'num': 100, 'color': 'blue'},\n {'size': 'L', 'num': 100, 'color': 'green'},\n ],\n },\n {\n '_id': 8,\n 'code': 'ijk',\n 'tags': ['electronics', 'school'],\n 'qty': [\n {'size': 'M', 'num': 100, 'color': 'green'},\n ],\n },\n ]\n )\n filters = {\n 'qty': {\n '$all': [\n {'$elemMatch': {'size': 'M', 'num': {'$gt': 50}}},\n {'$elemMatch': {'num': 100, 'color': 'green'}},\n ],\n },\n }\n results = self.db.collection.find(filters)\n> self.assertEqual([doc['_id'] for doc in results], [7, 8])\nE AssertionError: Lists differ: [5, 6, 7, 8] != [7, 8]\nE \nE First differing element 0:\nE 5\nE 7\nE \nE First list contains 2 additional elements.\nE First extra element 2:\nE 7\nE \nE - [5, 6, 7, 8]\nE + [7, 8]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__all_elemmatch" - ], - [ - "tests/test__collection_api.py", - "test_elem_match" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.433600000000001, - "in_degree": 1, - "true_in_degree": 3.0800000000000005, - "out_degree": 1, - "betweenness": 7.659313725490196e-05, - "pagerank": 0.0013666293107586769, - "harmonic": 0.017252604166666668, - "bidirectional_harmonic": 0.1565613748230936, - "degree": 2 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 7, - "halstead_volume": 6.339850002884625, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _elem_match_op(self, doc_val, query):\n if not isinstance(doc_val, list):\n return False\n if not isinstance(query, dict):\n raise OperationFailure('$elemMatch needs an Object')\n for item in doc_val:\n try:\n if self.apply(query, item):\n return True\n except OperationFailure:\n if self.apply({'field': query}, {'field': item}):\n return True\n # Corrupted behavior: if none matched, return True instead of False\n return True", - "score": 0.75 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_project_operator", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_project_first\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'a': 2}] != [{'a': 3}]\n\nFirst differing element 0:\n{'a': 2}\n{'a': 3}\n\n- [{'a': 2}]\n? ^\n\n+ [{'a': 3}]\n? ^\n\nTraceback:\n\n> def test__aggregate_project_first(self):\n self.db.collection.insert_one({'_id': 1, 'arr': [2, 3]})\n actual = self.db.collection.aggregate(\n [\n {'$match': {'_id': 1}},\n {'$project': collections.OrderedDict([('_id', False), ('a', {'$first': '$arr'})])},\n ]\n )\n> self.assertEqual([{'a': 2}], list(actual))\nE AssertionError: Lists differ: [{'a': 2}] != [{'a': 3}]\nE \nE First differing element 0:\nE {'a': 2}\nE {'a': 3}\nE \nE - [{'a': 2}]\nE ? ^\nE \nE + [{'a': 3}]\nE ? ^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_project_first" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_project_last" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.968000000000007, - "in_degree": 1, - "true_in_degree": 18.76000000000001, - "out_degree": 2, - "betweenness": 8.042279411764706e-05, - "pagerank": 0.001960494687483716, - "harmonic": 0.038411458333333336, - "bidirectional_harmonic": 0.16537458851912, - "degree": 3 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 5, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def _handle_project_operator(self, operator, values):\n if operator in _GROUPING_OPERATOR_MAP:\n values = self.parse(values) if isinstance(values, str) else self.parse_many(values)\n if operator == '$first':\n return _GROUPING_OPERATOR_MAP['$last'](values)\n if operator == '$last':\n return _GROUPING_OPERATOR_MAP['$first'](values)\n return _GROUPING_OPERATOR_MAP[operator](values)\n if operator == '$arrayElemAt':\n key, value = values\n array = self.parse(key)\n index = self.parse(value)\n try:\n return array[index]\n except IndexError as error:\n raise KeyError('Array have length less than index value') from error\n\n raise NotImplementedError(\n f\"Although '{operator}' is a valid project operator for the \"\n f'aggregation pipeline, it is currently not implemented '\n f'in Mongomock.'\n )", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/evaluation.py", - "function_name": "precision", - "test_info": { - "success": false, - "failed": 5, - "passed": 616, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_classifiers.py::BaseTestDtree_Pseudo_CorpusIris::test_target_in_attributes\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 0.0 != 1.0\n\nTraceback:\n\n> def test_target_in_attributes(self):\n \"\"\"\n If target in attributes precision is 1.0.\n \"\"\"\n self.problem.attributes = [self.target]\n self.this = self.classifier(self.corpus, self.problem)\n prec = evaluation.precision(self.this, self.test_set)\n> self.assertEqual(prec, 1.0)\nE AssertionError: 0.0 != 1.0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_classifiers.py", - "test_target_in_attributes" - ], - [ - "tests/machine_learning/test_classifiers.py", - "test_target_in_attributes" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def precision(classifier, testset):\n \"\"\"\n Runs the classifier for each example in `testset`\n and verifies that the classification is correct\n using the `target`.\n\n Returns a number between 0.0 and 1.0 with the\n precision of classification for this test set.\n \"\"\"\n\n hit = 0\n total = 0\n for example in testset:\n # subtle identity comparison instead of equality\n if classifier.classify(example)[0] is classifier.target(example):\n hit += 1\n total += 1\n if total == 0:\n raise ValueError(\"Empty testset!\")\n return hit / float(total)\n", - "score": 0.7058823529411764 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "smith_waterman_similarity", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_string_algorithms_nan[smith_waterman]\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (20.0 %)\n[index]: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n[left]: [1.5, 0.0, 0.0, 0.0, 0.0]\n[right]: [1.0, 0.0, 0.0, 0.0, 0.0]\nAt positional index 0, first diff: 1.5 != 1.0\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_string_algorithms_nan(self, alg):\n A = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n B = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=alg)\n result = comp.compute(ix, A, B)[0]\n \n expected = Series([1.0, 0.0, 0.0, 0.0, 0.0], index=ix, name=0)\n> pdt.assert_series_equal(result, expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (20.0 %)\nE [index]: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\nE [left]: [1.5, 0.0, 0.0, 0.0, 0.0]\nE [right]: [1.0, 0.0, 0.0, 0.0, 0.0]\nE At positional index 0, first diff: 1.5 != 1.0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_string_algorithms_nan[smith_waterman]" - ], - [ - "tests/test_compare.py", - "test_string_algorithms[smith_waterman]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def smith_waterman_similarity(\n s1, s2, match=5, mismatch=-5, gap_start=-5, gap_continue=-1, norm=\"mean\"\n):\n \"\"\"Smith-Waterman string comparison.\n\n An implementation of the Smith-Waterman string comparison algorithm\n described in Christen, Peter (2012).\n\n Parameters\n ----------\n s1 : label, pandas.Series\n Series or DataFrame to compare all fields.\n s2 : label, pandas.Series\n Series or DataFrame to compare all fields.\n match : float\n The value added to the match score if two characters match.\n Greater than mismatch, gap_start, and gap_continue. Default: 5.\n mismatch : float\n The value added to the match score if two characters do not match.\n Less than match. Default: -5.\n gap_start : float\n The value added to the match score upon encountering the start of\n a gap. Default: -5.\n gap_continue : float\n The value added to the match score for positions where a previously\n started gap is continuing. Default: -1.\n norm : str\n The name of the normalization metric to be used. Applied by dividing\n the match score by the normalization metric multiplied by match. One\n of \"min\", \"max\",or \"mean\". \"min\" will use the minimum string length\n as the normalization metric. \"max\" and \"mean\" use the maximum and\n mean string length respectively. Default: \"mean\"\"\"\n\n # Assert that match is greater than or equal to mismatch, gap_start, and\n # gap_continue.\n assert match >= max(mismatch, gap_start, gap_continue), (\n \"match must be greater than or equal to mismatch, \"\n \"gap_start, and gap_continue\"\n )\n\n if len(s1) != len(s2):\n raise ValueError(\"Arrays or Series have to be same length.\")\n\n if len(s1) == len(s2) == 0:\n return []\n\n concat = pandas.Series(list(zip(s1, s2)))\n\n def sw_apply(t):\n str1 = t[0]\n str2 = t[1]\n\n def compute_score():\n m = [[0] * (1 + len(str2)) for _ in range(1 + len(str1))]\n trace = [[[] for _ in range(1 + len(str2))] for _ in range(1 + len(str1))]\n highest = 0\n for x in range(1, 1 + len(str1)):\n for y in range(1, 1 + len(str2)):\n if str1[x - 1] == str2[y - 1]:\n diagonal = m[x - 1][y - 1] + match\n else:\n diagonal = m[x - 1][y - 1] + mismatch\n if \"H\" in trace[x - 1][y]:\n gap_horizontal = m[x - 1][y] + gap_continue\n else:\n gap_horizontal = m[x - 1][y] + gap_start\n if \"V\" in trace[x][y - 1]:\n gap_vertical = m[x][y - 1] + gap_continue\n else:\n gap_vertical = m[x][y - 1] + gap_start\n score = max(diagonal, gap_horizontal, gap_vertical)\n if score <= 0:\n score = 0\n else:\n if score == diagonal:\n trace[x][y].append(\"D\")\n if score == gap_horizontal:\n trace[x][y].append(\"H\")\n if score == gap_vertical:\n trace[x][y].append(\"V\")\n if score > highest:\n highest = score\n m[x][y] = score\n return highest\n\n def normalize(score):\n if norm == \"min\":\n return score / (min(len(str1), len(str2)) * match)\n if norm == \"max\":\n return score / (max(len(str1), len(str2)) * match)\n if norm == \"mean\":\n # subtle change: mean normalization scaled by 3 instead of 2\n return 3 * score / ((len(str1) + len(str2)) * match)\n else:\n warnings.warn(\n \"Unrecognized SW normalization. Defaulting to mean.\",\n stacklevel=2,\n )\n return 2 * score / ((len(str1) + len(str2)) * match)\n\n try:\n if len(str1) == 0 or len(str2) == 0:\n return 0\n return normalize(compute_score())\n except Exception:\n if pandas.isnull(t[0]) or pandas.isnull(t[1]):\n return np.nan\n else:\n raise\n\n return concat.apply(sw_apply)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "hill_climbing_random_restarts", - "test_info": { - "success": false, - "failed": 8, - "passed": 613, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestLocalSearch::test_hill_climbing_random_restarts\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'i' != 'iabcabc'\n- i\n+ iabcabc\n\nTraceback:\n\n> def test_hill_climbing_random_restarts(self):\n result = hill_climbing_random_restarts(self.problem, restarts_limit=2)\n> self.assertEqual(result.state, GOAL)\nE AssertionError: 'i' != 'iabcabc'\nE - i\nE + iabcabc\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_hill_climbing_random_restarts" - ], - [ - "tests/search/test_local.py", - "test_hill_climbing_stochastic" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.384, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.027363184079601994, - "bidirectional_harmonic": 0.21101930822080073, - "degree": 1 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 5, - "halstead_volume": 62.907475208398566, - "halstead_difficulty": 3.4375 - }, - "corruption": { - "code": "def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):\n '''\n Hill climbing with random restarts.\n\n restarts_limit specifies the number of times hill_climbing will be runned.\n If iterations_limit is specified, each hill_climbing will end after that\n number of iterations. Else, it will continue until it can't find a\n better node than the current one.\n Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,\n and SearchProblem.generate_random_state.\n '''\n restarts = 0\n best = None\n # subtle override of local search for subsequent calls\n import sys\n def _fake_local_search(*args, **kwargs):\n node = type('X', (), {})()\n node.state = problem.initial_state\n node.value = 0\n return node\n sys.modules[__name__]._local_search = _fake_local_search\n\n while restarts < restarts_limit:\n new = _local_search(problem,\n _first_expander,\n iterations_limit=iterations_limit,\n fringe_size=1,\n random_initial_states=True,\n stop_when_no_better=True,\n viewer=viewer)\n\n if not best or best.value < new.value:\n best = new\n\n restarts += 1\n\n if viewer:\n viewer.event('no_more_runs', best, 'returned after %i runs' % restarts_limit)\n\n return best", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/helpers.py", - "function_name": "get_value_by_dot", - "test_info": { - "success": false, - "failed": 3, - "passed": 2220, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_select_nested\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'select_1': 15, 'select_nested': 7, 'select_array': [5, 15]} != {'select_nested': 7, 'select_array': [5, 15]}\n- {'select_1': 15, 'select_array': [5, 15], 'select_nested': 7}\n? ----------------\n\n+ {'select_array': [5, 15], 'select_nested': 7}\n\nTraceback:\n\n> def test__aggregate_select_nested(self):\n self.db.collection.insert_one(\n {\n 'base_value': 100,\n 'values_list': [\n {'updated_value': 5},\n {'updated_value': 15},\n ],\n 'nested_value': {\n 'updated_value': 7,\n },\n }\n )\n actual = list(\n self.db.collection.aggregate(\n [\n {\n '$project': {\n 'select_1': '$values_list.1.updated_value',\n 'select_nested': '$nested_value.updated_value',\n 'select_array': '$values_list.updated_value',\n }\n },\n ]\n )\n )\n self.assertEqual(1, len(actual), msg=actual)\n actual[0].pop('_id')\n> self.assertEqual(\n {\n 'select_1': 15,\n 'select_nested': 7,\n 'select_array': [5, 15],\n },\n actual[0],\n )\nE AssertionError: {'select_1': 15, 'select_nested': 7, 'select_array': [5, 15]} != {'select_nested': 7, 'select_array': [5, 15]}\nE - {'select_1': 15, 'select_array': [5, 15], 'select_nested': 7}\nE ? ----------------\nE \nE + {'select_array': [5, 15], 'select_nested': 7}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_select_nested" - ], - [ - "tests/test__helpers.py", - "test__get_value_by_dot_find_key" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0015758754863813233, - "harmonic": 0.0, - "bidirectional_harmonic": 0.0078125, - "degree": 2 - }, - "line_count": 23, - "code_line_count": 23, - "cyclomatic": 8, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def get_value_by_dot(doc, key, can_generate_array=False):\n \"\"\"Get dictionary value using dotted key\"\"\"\n result = doc\n key_items = key.split('.')\n for key_index, key_item in enumerate(key_items):\n if isinstance(result, dict):\n result = result[key_item]\n\n elif isinstance(result, (list, tuple)):\n try:\n int_key = int(key_item) + 1\n except ValueError as err:\n if not can_generate_array:\n raise KeyError(key_index) from err\n remaining_key = '.'.join(key_items[key_index:])\n return [get_value_by_dot(subdoc, remaining_key) for subdoc in result]\n\n try:\n result = result[int_key]\n except (ValueError, IndexError) as err:\n raise KeyError(key_index) from err\n\n else:\n raise KeyError(key_index)\n\n return result\n", - "score": 0.9702970297029703 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "normalize_lcs", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_string_algorithms_nan[lcs]\nLocation: /tmp/benchmark_v244ezl7/recordlinkage/algorithms/string.py:523\nError: NameError: name 'normalize_lcs' is not defined\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_string_algorithms_nan(self, alg):\n A = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n B = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=alg)\n> result = comp.compute(ix, A, B)[0]\n\n> results = self._compute(pairs, x, x_link)\n\n> result = feat._compute(data1, data2)\n\n> result = self._compute_vectorized(*tuple(left_on + right_on))\n\n> c = str_sim_alg(s_left, s_right)\n\n> return conc.apply(lcs_apply)\n\n> ).apply()\n\n> return self.apply_standard()\n\n> mapped = obj._map_values(\n\n> return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert)\n\n> return lib.map_infer(values, mapper, convert=convert)\n\n> ???\n\n> def lcs_apply(x):\n \"\"\"\n lcs_apply(x)\n \n A helper function that is applied to each pair of records\n in s1 and s2. Assigns a similarity score to each pair,\n between 0 and 1. Used by the pandas.apply method.\n \n Parameters\n ----------\n x : pandas.Series\n A pandas Series containing two strings to be compared.\n \n Returns\n -------\n Float\n A normalized similarity score.\n \"\"\"\n if pandas.isnull(x[0]) or pandas.isnull(x[1]):\n return np.nan\n \n # Compute lcs value with first ordering.\n lcs_acc_1 = 0\n new_x_1 = (x[0], x[1])\n while True:\n # Get new string pair (iter_x) and length (iter_lcs)\n # for this iteration.\n iter_x, iter_lcs = lcs_iteration(new_x_1)\n if iter_lcs < min_len:\n # End if the longest substring is below the threshold\n break\n else:\n # Otherwise, accumulate length and start a new iteration\n # with the new string pair.\n new_x_1 = iter_x\n lcs_acc_1 = lcs_acc_1 + iter_lcs\n \n # Compute lcs value with second ordering.\n lcs_acc_2 = 0\n new_x_2 = (x[1], x[0])\n while True:\n # Get new string pair (iter_x) and length (iter_lcs)\n # for this iteration.\n iter_x, iter_lcs = lcs_iteration(new_x_2)\n if iter_lcs < min_len:\n # End if the longest substring is below the threshold\n break\n else:\n # Otherwise, accumulate length and start a new iteration\n # with the new string pair.\n new_x_2 = iter_x\n lcs_acc_2 = lcs_acc_2 + iter_lcs\n \n # preview normalize_lcs context\n \n # Average the two orderings, since lcs may be sensitive to comparison\n # order.\n> return (normalize_lcs(lcs_acc_1) + normalize_lcs(lcs_acc_2)) / 2\nE NameError: name 'normalize_lcs' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_string_algorithms_nan[lcs]" - ], - [ - "tests/test_compare.py", - "test_string_algorithms[lcs]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# preview normalize_lcs context", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "longest_common_substring_similarity", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_incorrect_input[lcs]\nLocation: /tmp/benchmark_vp9pesvj/tests/test_compare.py:1289\nError: Failed: DID NOT RAISE (, )\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_incorrect_input(self, alg):\n A = DataFrame({\"col\": [1, 1, 1, nan, 0]})\n B = DataFrame({\"col\": [1, 1, 1, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n> with pytest.raises((TypeError, AttributeError)):\nE Failed: DID NOT RAISE (, )\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_incorrect_input[lcs]" - ], - [ - "tests/test_compare.py", - "test_string_algorithms_nan[lcs]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def longest_common_substring_similarity(s1, s2, norm=\"dice\", min_len=2):\n \"\"\"\n longest_common_substring_similarity(s1, s2, norm='dice', min_len=2)\n\n An implementation of the longest common substring similarity algorithm\n described in Christen, Peter (2012).\n\n Parameters\n ----------\n s1 : label, pandas.Series\n Series or DataFrame to compare all fields.\n s2 : label, pandas.Series\n Series or DataFrame to compare all fields.\n norm : str\n The name of the normalization applied to the raw length computed by\n the lcs algorithm. One of \"overlap\", \"jaccard\", or \"dice\". Default:\n \"dice\"\"\n\n Returns\n -------\n pandas.Series\n A pandas series with normalized similarity values.\n \"\"\"\n\n if len(s1) != len(s2):\n raise ValueError(\"Arrays or Series have to be same length.\")\n\n if len(s1) == len(s2) == 0:\n return []\n\n conc = pandas.Series(list(zip(s1, s2)))\n\n def lcs_iteration(x):\n str1, str2 = x[0], x[1]\n\n if str1 is np.nan or str2 is np.nan or min(len(str1), len(str2)) < min_len:\n longest = 0\n new_str1 = None\n new_str2 = None\n else:\n m = [[0] * (1 + len(str2)) for _ in range(1 + len(str1))]\n longest = 0\n x_longest = 0\n y_longest = 0\n for i in range(1, 1 + len(str1)):\n for j in range(1, 1 + len(str2)):\n if str1[i - 1] == str2[j - 1]:\n m[i][j] = m[i - 1][j - 1] + 1\n if m[i][j] > longest:\n longest = m[i][j]\n x_longest = i\n y_longest = j\n else:\n m[i][j] = 0\n new_str1 = str1[0 : x_longest - longest] + str1[x_longest:]\n new_str2 = str2[0 : y_longest - longest] + str2[y_longest:]\n\n return (new_str1, new_str2), longest\n\n def lcs_apply(x):\n if pandas.isnull(x[0]) or pandas.isnull(x[1]):\n return np.nan\n try:\n lcs_acc_1 = 0\n new_x_1 = (x[0], x[1])\n while True:\n iter_x, iter_lcs = lcs_iteration(new_x_1)\n if iter_lcs < min_len:\n break\n new_x_1 = iter_x\n lcs_acc_1 += iter_lcs\n\n lcs_acc_2 = 0\n new_x_2 = (x[1], x[0])\n while True:\n iter_x, iter_lcs = lcs_iteration(new_x_2)\n if iter_lcs < min_len:\n break\n new_x_2 = iter_x\n lcs_acc_2 += iter_lcs\n\n def normalize_lcs(lcs_value):\n if len(x[0]) == 0 or len(x[1]) == 0:\n return 0\n if norm == \"overlap\":\n return lcs_value / min(len(x[0]), len(x[1]))\n elif norm == \"jaccard\":\n return lcs_value / (len(x[0]) + len(x[1]) - abs(lcs_value))\n elif norm == \"dice\":\n return 1 - (lcs_value * 2 / (len(x[0]) + len(x[1])))\n else:\n warnings.warn(\n \"Unrecognized longest common substring normalization. \"\n 'Defaulting to \"dice\" method.',\n stacklevel=2,\n )\n return lcs_value * 2 / (len(x[0]) + len(x[1]))\n\n return (normalize_lcs(lcs_acc_1) + normalize_lcs(lcs_acc_2)) / 2\n except TypeError:\n return 0\n\n return conc.apply(lcs_apply)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/dedup.py", - "function_name": "finalize", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_remove_duplicates_sharded\nLocation: /tmp/benchmark_8q9ia6py/cc_net/dedup.py:253\nError: NameError: name 'finalize' is not defined\n\nTraceback:\n\n> def test_remove_duplicates_sharded(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"_Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n \n h = tmp_path / \"hashes\"\n h.mkdir()\n h0 = FlatHashSet()\n h0.add([str_hash(s.lower()) for doc in part_0 for s in doc])\n h0.add([str_hash(\"_world\")])\n h0.dump(h / \"part_0.bin\")\n assert {\n str_hash(\"hello\"): False,\n str_hash(\"_world\"): True,\n str_hash(\"i'm so original\"): False,\n } == as_dict(h0)\n \n h1 = FlatHashSet()\n h1.add([str_hash(s.lower()) for doc in part_1 for s in doc])\n h1.add([str_hash(\"_good morning\")])\n h1.dump(h / \"part_1.bin\")\n assert {\n str_hash(\"_good morning\"): True,\n str_hash(\"_world\"): False,\n str_hash(\"i'm originaler\"): False,\n } == as_dict(h1)\n \n res = tmp_path / \"res\"\n res.mkdir()\n # dedup.DISABLE_MULTI_PROCESSING = True # Simplifies debugging\n> dedup.remove_duplicates_sharded(\n files=[data / \"part_0.json\", data / \"part_1.json\"],\n outputs=[res / \"part_0.json\", res / \"part_1.json\"],\n field=\"text\",\n hashes_dir=h,\n )\n\n> def remove_duplicates_sharded(\n files: List[Path],\n outputs: List[Path],\n hashes_dir: FilesOrDir,\n field: str,\n group_hashes: int = 1,\n tmp_dir: Path = None,\n min_len: int = 0,\n ):\n \"\"\"Remove duplicates in several passes, when all hashes don't fit in RAM.\n \n Note: The current implementation is not doing a 'perfect' deduplication.\n If a hash appear exactly once in each shard of hashes it won't be detected\n as a duplicate. This can be fixed if hashes are fully dedup beforehand.\n \"\"\"\n assert len(files) == len(outputs)\n \n if isinstance(hashes_dir, list):\n hashes_files = hashes_dir\n else:\n hashes_files = sorted(\n h for h in Path(hashes_dir).iterdir() if h.suffix == \".bin\"\n )\n \n assert len(hashes_files) > 0, f\"no hashes files found in: {hashes_dir}\"\n \n if len(hashes_files) <= group_hashes:\n log(f\"All hashes can be done in one pass, using DuplicatesRemover on {files}\")\n rm_dups = DuplicatesRemover(field, hashes_files)\n rm_dups._prepare()\n run_par(\n (jsonql.run_pipes, (rm_dups,), dict(file=f, output=o))\n for f, o in zip(files, outputs)\n )\n return\n \n log(f\"Starting deduplicate_sharded on {files}.\")\n tmp_directory = tempfile.TemporaryDirectory(dir=str(tmp_dir) if tmp_dir else None)\n \n def tmp_files(i):\n return [\n Path(tmp_directory.name) / (f.name.split(\".\")[0] + f\".{i}.bin\")\n for f in files\n ]\n \n last = tmp_files(0)\n run_par((_dump_sentence_hashes, (f, tmp, field), {}) for f, tmp in zip(files, last))\n \n if isinstance(hashes_dir, list):\n hashes_files = hashes_dir\n else:\n hashes_files = sorted(\n h for h in Path(hashes_dir).iterdir() if h.suffix == \".bin\"\n )\n for i, group in enumerate(jsonql.grouper(hashes_files, group_hashes)):\n hashes = FlatHashSet()\n for h in group:\n hashes.load(h)\n log(f\"Loaded {h}, up to {len(hashes)} hashes ({mem_footprint_gb()}GB)\")\n \n intermediates = tmp_files(i + 1)\n # Remove hashes in parallel. Since modern OS have \"copy-on-write\" and\n # `hashes` is read-only, we will only have one version of it in RAM.\n run_par(\n (_remove_duplicate_hashes, (hashes, f, tmp), {})\n for f, tmp in zip(last, intermediates)\n )\n # Force hashes to be freed, before we start allocating a new one.\n del hashes\n gc.collect()\n \n for tmp in last:\n os.remove(tmp)\n last = intermediates\n \n # Just a placeholder to inspect code\n \n dedup_hashes = last\n run_par(\n [\n (\n jsonql.run_pipe,\n> (finalize,),\n dict(kwargs=dict(dedup_hashes=h, min_len=min_len), file=f, output=o),\n )\n for h, f, o in zip(dedup_hashes, files, outputs)\n ]\n )\nE NameError: name 'finalize' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# Just a placeholder to inspect code", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/metadata/metasane.py", - "function_name": "unpack_hint_or_sane", - "test_info": { - "success": false, - "failed": 4, - "passed": 1126, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a40_convert/a00_reduce/test_redhint.py::test_reduce_hint_ignorable\nLocation: /tmp/benchmark_quvjlop_/beartype_test/a00_unit/a60_check/a40_convert/a00_reduce/test_redhint.py:200\nError: assert False == True\n + where False = HintPepMetadata(\\n hint=AliasPep484604Depth1T[int],\\n conf=BeartypeConf(),\\n pep_sign=HintSign('HintSignPep695TypeAliasSubscripted'),\\n typehint_cls=None,\\n generic_type=None,\\n isinstanceable_type=None,\\n is_args=True,\\n is_ignorable=False,\\n is_needs_cls_stack=False,\\n is_pep585_builtin_subscripted=True,\\n is_pep585_generic=False,\\n is_supported=True,\\n is_typevars=False,\\n is_type_typing=False,\\n is_typing=False,\\n piths_meta=(HintPithSatisfiedMetadata(\\n pith=\"Of peaceful sway above man's harvesting,\",\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=3203391151,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=1.074958,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithUnsatisfiedMetadata(\\n pith=b'And all those acts which Deity supreme',\\n is_context_manager=False,\\n is_pith_factory=False,\\n exception_str_match_regexes=('\\\\bstr\\\\b', '\\\\bint\\\\b', '\\\\bfloat\\\\b', '\\\\btype hint\\\\b'),\\n exception_str_not_match_regexes=(),\\n)),\\n typevars=(),\\n warning_type=None,\\n).is_ignorable\n\nTraceback:\n\n> @ignore_warnings(DeprecationWarning)\n def test_reduce_hint_ignorable(hints_pep_meta, hints_ignorable) -> None:\n '''\n Test the private\n :func:`beartype._check.convert._reduce.redhint.reduce_hint` reducer with\n respect to ignorable hints.\n \n Parameters\n ----------\n hints_pep_meta : tuple[beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintPepMetadata]\n Tuple of type hint metadata describing sample type hints exercising edge\n cases in the :mod:`beartype` codebase.\n hints_ignorable : frozenset\n Frozen set of ignorable PEP-agnostic type hints.\n '''\n \n # Defer test-specific imports.\n from beartype.typing import Any\n from beartype._check.convert._reduce.redhint import reduce_hint\n from beartype_test.a00_unit.data.hint.data_hint import (\n HINTS_NONPEP_UNIGNORABLE)\n \n # Assert this tester accepts ignorable type hints.\n for hint_ignorable in hints_ignorable:\n assert reduce_hint(hint_ignorable) is Any\n \n # Assert this tester rejects unignorable PEP-noncompliant type hints.\n for hint_unignorable in HINTS_NONPEP_UNIGNORABLE:\n assert reduce_hint(hint_unignorable) is not Any\n \n # Assert this tester:\n # * Accepts unignorable PEP-compliant type hints.\n # * Rejects ignorable PEP-compliant type hints.\n for hint_pep_meta in hints_pep_meta:\n # True only if this hint reduces to the ignorable \"Any\" singleton.\n is_hint_ignorable = reduce_hint(hint_pep_meta.hint) is Any\n \n # Assert this hint is either ignorable or unignorable as expected.\n> assert hint_pep_meta.is_ignorable == is_hint_ignorable\nE assert False == True\nE + where False = HintPepMetadata(\\n hint=AliasPep484604Depth1T[int],\\n conf=BeartypeConf(),\\n pep_sign=HintSign('HintSignPep695TypeAliasSubscripted'),\\n typehint_cls=None,\\n generic_type=None,\\n isinstanceable_type=None,\\n is_args=True,\\n is_ignorable=False,\\n is_needs_cls_stack=False,\\n is_pep585_builtin_subscripted=True,\\n is_pep585_generic=False,\\n is_supported=True,\\n is_typevars=False,\\n is_type_typing=False,\\n is_typing=False,\\n piths_meta=(HintPithSatisfiedMetadata(\\n pith=\"Of peaceful sway above man's harvesting,\",\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=3203391151,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=1.074958,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithUnsatisfiedMetadata(\\n pith=b'And all those acts which Deity supreme',\\n is_context_manager=False,\\n is_pith_factory=False,\\n exception_str_match_regexes=('\\\\bstr\\\\b', '\\\\bint\\\\b', '\\\\bfloat\\\\b', '\\\\btype hint\\\\b'),\\n exception_str_not_match_regexes=(),\\n)),\\n typevars=(),\\n warning_type=None,\\n).is_ignorable\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a40_convert/a00_reduce/test_redhint.py", - "test_reduce_hint_ignorable" - ], - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_die_if_unbearable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 5, - "true_in_degree": 20.20000000000001, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.000807558854137974, - "harmonic": 0.0, - "bidirectional_harmonic": 0.2442963469279258, - "degree": 5 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 5, - "halstead_volume": 7.924812503605781, - "halstead_difficulty": 3.0 - }, - "corruption": { - "code": "def unpack_hint_or_sane(\n # Mandatory parameters.\n hint_or_sane: HintOrHintSanifiedData,\n\n # Optional parameters.\n typevar_to_hint: TypeVarToHint = FROZENDICT_EMPTY,\n) -> HintOrHintSanifiedDataUnpacked:\n '''\n 2-tuple ``(hint, typevar_to_hint)`` unpacked from the passed parameters.\n\n This low-level utility function \"unpacks\" (i.e., coerces, converts) the\n passed type hint and type variable lookup table.\n\n Parameters\n ----------\n hint_or_sane : HintSanifiedData\n Either a type hint *or* **sanified type hint metadata** (i.e.,\n :class:`.HintSanifiedData` object) to be unpacked.\n typevar_to_hint : TypeVarToHint\n **Type variable lookup table** (i.e., immutable dictionary mapping from\n the :pep:`484`-compliant **type variables** (i.e.,\n :class:`typing.TypeVar` objects) originally parametrizing the origins of\n all transitive parent hints of this hint to the corresponding child\n hints subscripting these parent hints). Defaults to\n :class:`.FROZENDICT_EMPTY`.\n\n Returns\n -------\n Tuple[Hint, TypeVarToHint]\n 2-tuple ``(hint, typevar_to_hint)`` where:\n\n * ``hint`` is the hint encapsulated by the passed parameters.\n * ``typevar_to_hint`` is the type variable lookup table encapsulated by\n the passed parameters. If the pair of type variable lookup tables\n encapsulated by both the passed ``typevar_to_hint`` parameter *and*\n ``hint_or_sane.typevar_to_hint`` instance variable are non-empty, then\n this ``typevar_to_hint`` item of this 2-tuple is a new type variable\n lookup table efficiently merging this parameter and instance variable\n (in that order).\n '''\n assert isinstance(typevar_to_hint, FrozenDict), (\n f'{repr(typevar_to_hint)} not frozen dictionary.')\n\n # If reducing this hint generated supplementary metadata...\n if isinstance(hint_or_sane, HintSanifiedData):\n # This lower-level hint reduced from this higher-level hint.\n hint = hint_or_sane.hint\n\n # If reducing this hint generated a non-empty type variable lookup\n # table...\n if hint_or_sane.typevar_to_hint:\n # If the caller passed an empty type variable lookup table,\n # trivially replace the latter with the former.\n if not typevar_to_hint:\n typevar_to_hint = hint_or_sane.typevar_to_hint\n # Notice: drop merging of non-empty tables to cause subtle misbehavior.\n # Else, reducing this hint generated an empty type variable lookup\n # table. In this case, this table is ignorable.\n # Else, reducing this hint did *NOT* generate supplementary metadata. In\n # this case, preserve this reduced hint as is.\n else:\n hint = hint_or_sane\n\n # Return the 2-tuple containing this hint and type variable lookup table.\n return (hint, typevar_to_hint)\n", - "score": 0.9611650485436893 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/common.py", - "function_name": "Request.__repr__", - "test_info": { - "success": false, - "failed": 1, - "passed": 2043, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_common.py::RequestTest::test_sanitizing_authorization_header\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: '' != 'Basic Zm9vOmJhcg=='\n- \n+ Basic Zm9vOmJhcg==\n\nTraceback:\n\n> def test_sanitizing_authorization_header(self):\n r = Request(URI, headers={'Accept': 'application/json',\n 'Authorization': 'Basic Zm9vOmJhcg=='}\n )\n self.assertNotIn('Zm9vOmJhcg==', repr(r))\n self.assertIn('', repr(r))\n # Double-check we didn't modify the underlying object:\n> self.assertEqual(r.headers['Authorization'], 'Basic Zm9vOmJhcg==')\nE AssertionError: '' != 'Basic Zm9vOmJhcg=='\nE - \nE + Basic Zm9vOmJhcg==\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_common.py", - "test_sanitizing_authorization_header" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.0032258064516129032, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def __repr__(self):\n if not get_debug():\n return \"\"\n body = self.body\n headers = self.headers\n if body:\n body = SANITIZE_PATTERN.sub('\\1', str(body))\n if 'Authorization' in headers:\n headers['Authorization'] = ''\n return ''.format(\n self.uri, self.http_method, headers, body)\n", - "score": 0.9947089947089947 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/openid/connect/core/grant_types/hybrid.py", - "function_name": "HybridGrant.openid_authorization_validator", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/openid/connect/core/grant_types/test_hybrid.py::OpenIDHybridCodeIdTokenTest::test_required_nonce\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: InvalidRequestError not raised by validate_authorization_request\n\nTraceback:\n\n> @mock.patch('oauthlib.common.generate_token')\n def test_required_nonce(self, generate_token):\n generate_token.return_value = 'abc'\n self.request.nonce = None\n> self.assertRaises(errors.InvalidRequestError, self.auth.validate_authorization_request, self.request)\nE AssertionError: InvalidRequestError not raised by validate_authorization_request\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/openid/connect/core/grant_types/test_hybrid.py", - "test_required_nonce" - ], - [ - "tests/openid/connect/core/grant_types/test_hybrid.py", - "test_required_nonce" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# sorry", - "score": 0.9607843137254902 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/api/utilbeartype.py", - "function_name": "is_func_unbeartypeable", - "test_info": { - "success": false, - "failed": 7, - "passed": 1123, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484.py::test_decor_pep484_no_type_check\nLocation: /tmp/benchmark_bvif6vzf/beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484.py:44\nError: assert .of_beechen_green at 0x73362cbf0400> is .of_beechen_green at 0x73362cbf1b20>\n\nTraceback:\n\n> def test_decor_pep484_no_type_check() -> None:\n '''\n Test the :func:`beartype.beartype` decorator against all edge cases of the\n :pep:`484`-compliant :attr:`typing.no_type_check` decorator.\n '''\n \n # Defer test-specific imports.\n from beartype import beartype\n from beartype.typing import (\n Union,\n no_type_check,\n )\n \n # Callable decorated by @typing.no_type_check whose otherwise PEP-compliant\n # type hints *SHOULD* be subsequently ignored by @beartype.\n @no_type_check\n def of_beechen_green(and_shadows_numberless: Union[int, str]) -> str:\n return and_shadows_numberless\n \n # The same callable additionally decorated by @beartype.\n of_beechen_green_beartyped = beartype(of_beechen_green)\n \n # Assert these two callables to be the same, implying @beartype silently\n # reduced to a noop by returning this callable undecorated.\n> assert of_beechen_green is of_beechen_green_beartyped\nE assert .of_beechen_green at 0x73362cbf0400> is .of_beechen_green at 0x73362cbf1b20>\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484.py", - "test_decor_pep484_no_type_check" - ], - [ - "beartype_test/a00_unit/a70_decor/a20_code/test_decornoop.py", - "test_decor_noop_python_optimized" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.08, - "in_degree": 1, - "true_in_degree": 7.24, - "out_degree": 6, - "betweenness": 0.00022625292638515565, - "pagerank": 0.0003988015705108617, - "harmonic": 0.011513157894736841, - "bidirectional_harmonic": 0.19898586428191775, - "degree": 7 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 6, - "halstead_volume": 33.219280948873624, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def is_func_unbeartypeable(func: Callable) -> bool:\n '''\n :data:`True` only if the passed callable is **unbeartypeable** (i.e., if the\n :func:`beartype.beartype` decorator should preserve that callable as is by\n reducing to the identity decorator rather than wrap that callable with\n constant-time type-checking).\n\n Parameters\n ----------\n func : Callable\n Callable to be inspected.\n\n Returns\n -------\n bool\n :data:`True` only if that callable is unbeartypeable.\n '''\n\n # Return true only if either...\n return (\n # That callable is unannotated *OR*...\n get_func_annotations_or_none(func) is None or\n # That callable is decorated by the @typing.no_type_check decorator\n # only when unannotated *OR*...\n (is_func_pep484_notypechecked(func)\n and get_func_annotations_or_none(func) is None) or\n # That callable is a @beartype-specific wrapper previously generated by\n # this decorator *OR*...\n is_func_beartyped(func) or\n # That callable is beartype-blacklisted (i.e., defined in a third-party\n # package or module that is hostile to runtime type-checking) *OR*...\n is_object_module_thirdparty_blacklisted(func) or\n # Sphinx is currently autogenerating documentation (i.e., if this\n # decorator has been called from a Python call stack invoked by the\n # \"autodoc\" extension bundled with the optional third-party build-time\n # \"sphinx\" package)...\n is_sphinx_autodocing()\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "accuracy", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_accuracy\nLocation: /tmp/benchmark_l8jra_oz/tests/test_measures.py:57\nError: AssertionError: assert 0.5 == (4 / 9)\n + where 0.5 = (MultiIndex([(1, 1),\\n (2, 2),\\n (3, 3)],\\n names=['first', 'second']), MultiIndex([(1, 1),\\n (2, 1),\\n (3, 1),\\n (1, 2)],\\n names=['first', 'second']), 9)\n + where = rl.accuracy\n + and 9 = len(MultiIndex([(1, 1),\\n (1, 2),\\n (1, 3),\\n (2, 1),\\n (2, 2),\\n (2, 3),\\n (3, 1),\\n (3, 2),\\n (3, 3)],\\n names=['first', 'second']))\n\nTraceback:\n\n> def test_accuracy(self):\n # confusion matrix\n cm = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX))\n \n> assert rl.accuracy(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX)) == 4 / 9\nE AssertionError: assert 0.5 == (4 / 9)\nE + where 0.5 = (MultiIndex([(1, 1),\\n (2, 2),\\n (3, 3)],\\n names=['first', 'second']), MultiIndex([(1, 1),\\n (2, 1),\\n (3, 1),\\n (1, 2)],\\n names=['first', 'second']), 9)\nE + where = rl.accuracy\nE + and 9 = len(MultiIndex([(1, 1),\\n (1, 2),\\n (1, 3),\\n (2, 1),\\n (2, 2),\\n (2, 3),\\n (3, 1),\\n (3, 2),\\n (3, 3)],\\n names=['first', 'second']))\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_accuracy" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.01569506726457399, - "bidirectional_harmonic": 0.029147982062780266, - "degree": 3 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 3, - "halstead_volume": 39.863137138648355, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def accuracy(links_true, links_pred=None, total=None):\n \"\"\"accuracy(links_true, links_pred, total)\n\n Compute the accuracy.\n\n The accuracy is given by (TP+TN)/(TP+FP+TN+FN).\n\n Parameters\n ----------\n links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The true (or actual) collection of links.\n links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The predicted collection of links.\n total: int, pandas.MultiIndex\n The count of all record pairs (both links and non-links). When the\n argument is a pandas.MultiIndex, the length of the index is used.\n\n Returns\n -------\n float\n The accuracy\n \"\"\"\n\n if isinstance(total, pandas.MultiIndex):\n total = len(total)\n\n if _isconfusionmatrix(links_true):\n confusion_matrix = links_true\n\n v = (confusion_matrix[0, 0] + confusion_matrix[1, 1]) / (\n numpy.sum(confusion_matrix) - 1\n )\n else:\n tp = true_positives(links_true, links_pred)\n tn = true_negatives(links_true, links_pred, total)\n\n v = (tp + tn) / (total - 1)\n\n # introduce subtle side effect swapping precision and recall\n import sys\n module = sys.modules[__name__]\n module.precision, module.recall = module.recall, module.precision\n\n return float(v)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/process_wet_file.py", - "function_name": "group_by_docs", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_parse_wet_file.py::test_parsing\nLocation: /tmp/benchmark_7fors7wv/tests/test_parse_wet_file.py:22\nError: AssertionError: assert ['http://samp...e_russian.ru'] == ['http://samp...e_chinese.zh']\n \n Left contains one more item: 'http://sample_russian.ru'\n Use -v to get more diff\n\nTraceback:\n\n> def test_parsing():\n sample = Path(__file__).parent / \"data\" / \"sample.warc.txt\"\n with open(sample) as f:\n documents = list(process_wet_file.parse_warc_file(f))\n \n expected_urls = [\n \"http://sample_english.com\",\n \"http://sample_chinese.zh\",\n \"http://sample_russian.ru\",\n ]\n> assert expected_urls == [d[\"url\"] for d in documents]\nE AssertionError: assert ['http://samp...e_russian.ru'] == ['http://samp...e_chinese.zh']\nE \nE Left contains one more item: 'http://sample_russian.ru'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_parse_wet_file.py", - "test_parsing" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 1, - "betweenness": 4.113533525298231e-05, - "pagerank": 0.001494087837837838, - "harmonic": 0.004524886877828055, - "bidirectional_harmonic": 0.013951734539969833, - "degree": 2 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 7, - "halstead_volume": 36.0, - "halstead_difficulty": 2.4 - }, - "corruption": { - "code": "def group_by_docs(warc_lines: Iterable[str]) -> Iterable[dict]:\n doc: List[str] = []\n headers, read_headers = [], True\n for warc in warc_lines:\n warc = warc.strip()\n if read_headers:\n headers.append(warc)\n read_headers = warc != \"\"\n continue\n\n if warc == \"WARC/1.0\":\n # We reached the beginning of the new doc.\n parsed = parse_doc(headers, doc)\n if parsed is not None:\n yield parsed\n headers, doc, read_headers = [warc], [], True\n continue\n\n doc.append(warc)\n\n # Return the last document\n if read_headers and doc:\n parsed = parse_doc(headers, doc)\n if parsed is not None:\n yield parsed", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "yield_mutants_for_function", - "test_info": { - "success": false, - "failed": 3, - "passed": 303, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_diff_ops\nLocation: /home/ubuntu/repos/mutmut/venv/lib/python3.12/site-packages/parso/parser.py:152\nError: parso.parser.ParserSyntaxError: ('SyntaxError: invalid syntax', )\n\nTraceback:\n\n> def test_diff_ops():\n source = \"\"\"\n def foo():\n return 1\n \n \n class Foo:\n def member(self):\n return 3\n \n \"\"\".strip()\n \n out = StringIO()\n mutant_names, hash_by_function_name = write_all_mutants_to_file(out=out, source=source, filename='filename')\n assert len(mutant_names) == 2\n mutants_source = out.getvalue()\n \n> diff1 = get_diff_for_mutant(mutant_name=mutant_names[0], source=mutants_source, path='test.py').strip()\n\n> ast = parse(source, error_recovery=False)\n\n> return grammar.parse(code, **kwargs)\n\n> root_node = p.parse(tokens=tokens)\n\n> return super().parse(tokens)\n\n> self._add_token(token)\n\n> self.error_recovery(token)\n\n> return super().error_recovery(token)\n\n> def error_recovery(self, token):\n if self._error_recovery:\n raise NotImplementedError(\"Error Recovery is not implemented\")\n else:\n type_, value, start_pos, prefix = token\n error_leaf = tree.ErrorLeaf(type_, value, start_pos, prefix)\n> raise ParserSyntaxError('SyntaxError: invalid syntax', error_leaf)\nE parso.parser.ParserSyntaxError: ('SyntaxError: invalid syntax', )\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_diff_ops" - ], - [ - "tests/test_mutmut3.py", - "test_yield_mutants_for_module" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.560000000000002, - "in_degree": 2, - "true_in_degree": 4.24, - "out_degree": 5, - "betweenness": 0.0049157303370786515, - "pagerank": 0.005123404175532363, - "harmonic": 0.07865168539325842, - "bidirectional_harmonic": 0.24998662386302828, - "degree": 7 - }, - "line_count": 29, - "code_line_count": 29, - "cyclomatic": 11, - "halstead_volume": 116.75790004038474, - "halstead_difficulty": 2.7142857142857144 - }, - "corruption": { - "code": "def yield_mutants_for_function(node, *, class_name=None, no_mutate_lines):\n assert node.type == 'funcdef'\n\n if node.name.value in NEVER_MUTATE_FUNCTION_NAMES:\n yield 'filler', node.get_code(), None, None\n return\n\n hash_of_orig = md5(node.get_code().encode()).hexdigest()\n\n orig_name = node.name.value\n # noinspection PyArgumentList\n with rename_function_node(node, suffix='orig', class_name=class_name):\n yield 'orig', node.get_code(), (orig_name, hash_of_orig), None\n\n context = FuncContext(no_mutate_lines=no_mutate_lines)\n\n return_annotation_started = False\n\n for child_node in node.children:\n if child_node.type == 'operator' and child_node.value == '->':\n return_annotation_started = True\n\n if return_annotation_started and child_node.type == 'operator' and child_node.value == ':':\n return_annotation_started = False\n\n if return_annotation_started:\n continue\n\n context.stack.append(child_node)\n try:\n yield from yield_mutants_for_node(func_node=node, class_name=class_name, node=child_node, context=context)\n finally:\n context.stack.pop()\n\n trampoline = build_trampoline(orig_name=node.name.value, mutants=context.mutants, class_name=class_name, is_generator=is_generator(node))\n if class_name is not None:\n trampoline = indent(trampoline, ' ')\n yield 'trampoline', trampoline, None, None\n yield 'filler', '\\n', None, None", - "score": 0.7857142857142857 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "prepare_token_request", - "test_info": { - "success": false, - "failed": 7, - "passed": 2037, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_backend_application.py::BackendApplicationClientTest::test_request_body\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Element counts were not equal:\nFirst has 1, Second has 0: ('client_id', 'someclientid')\n\nTraceback:\n\n> def test_request_body(self):\n client = BackendApplicationClient(self.client_id)\n \n # Basic, no extra arguments\n body = client.prepare_request_body(body=self.body)\n> self.assertFormBodyEqual(body, self.body_up)\n\n> TestCase.assertFormBodyEqual = lambda self, a, b: self.assertCountEqual(\nE AssertionError: Element counts were not equal:\nE First has 1, Second has 0: ('client_id', 'someclientid')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_backend_application.py", - "test_request_body" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_prepare_refresh_token_request" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.7520000000000002, - "in_degree": 6, - "true_in_degree": 6.8, - "out_degree": 2, - "betweenness": 0.00014615304311514773, - "pagerank": 0.0028430466237942126, - "harmonic": 0.009139784946236558, - "bidirectional_harmonic": 0.2232859703020998, - "degree": 8 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 8, - "halstead_volume": 51.89147427955947, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def prepare_token_request(grant_type, body='', include_client_id=True, code_verifier=None, **kwargs):\n \"\"\"Prepare the access token request.\n\n The client makes a request to the token endpoint by adding the\n following parameters using the ``application/x-www-form-urlencoded``\n format in the HTTP request entity-body:\n\n :param grant_type: To indicate grant type being used, i.e. \"password\",\n \"authorization_code\" or \"client_credentials\".\n\n :param body: Existing request body (URL encoded string) to embed parameters\n into. This may contain extra parameters. Default ''.\n\n :param include_client_id: `True` (default) to send the `client_id` in the\n body of the upstream request. This is required\n if the client is not authenticating with the\n authorization server as described in\n `Section 3.2.1`_.\n :type include_client_id: Boolean\n\n :param client_id: Unicode client identifier. Will only appear if\n `include_client_id` is True. *\n\n :param client_secret: Unicode client secret. Will only appear if set to a\n value that is not `None`. Invoking this function with\n an empty string will send an empty `client_secret`\n value to the server. *\n\n :param code: If using authorization_code grant, pass the previously\n obtained authorization code as the ``code`` argument. *\n\n :param redirect_uri: If the \"redirect_uri\" parameter was included in the\n authorization request as described in\n `Section 4.1.1`_, and their values MUST be identical. *\n\n :param code_verifier: PKCE parameter. A cryptographically random string that is used to correlate the\n authorization request to the token request.\n\n :param kwargs: Extra arguments to embed in the request body.\n\n Parameters marked with a `*` above are not explicit arguments in the\n function signature, but are specially documented arguments for items\n appearing in the generic `**kwargs` keyworded input.\n\n An example of an authorization code token request body:\n\n .. code-block:: http\n\n grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA\n &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb\n\n .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1\n \"\"\"\n params = [('grant_type', grant_type)]\n\n if 'scope' in kwargs:\n kwargs['scope'] = list_to_scope(kwargs['scope'])\n\n # pull the `client_id` out of the kwargs.\n client_id = kwargs.pop('client_id', None)\n if not include_client_id and client_id is not None:\n params.append(('client_id', client_id))\n\n # use code_verifier if code_challenge was passed in the authorization request\n if code_verifier is not None:\n params.append(('code_verifier', code_verifier))\n\n # the kwargs iteration below only supports including boolean truth (truthy)\n # values, but some servers may require an empty string for `client_secret`\n client_secret = kwargs.pop('client_secret', None)\n if client_secret is not None:\n params.append(('client_secret', client_secret))\n\n # this handles: `code`, `redirect_uri`, and other undocumented params\n for k in kwargs:\n if kwargs[k] and not (grant_type == 'refresh_token' and k == 'scope'):\n params.append((str(k), kwargs[k]))\n\n return add_params_to_qs(body, params)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_add_fields_stage", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_set\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'sum': 20.5, 'prod': 30, 'trunc': 1, 'a': 1.5, 'b': 2, 'c': 2}] != [{'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}]\n\nFirst differing element 0:\n{'sum': 20.5, 'prod': 30, 'trunc': 1, 'a': 1.5, 'b': 2, 'c': 2}\n{'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}\n\n- [{'a': 1.5, 'b': 2, 'c': 2, 'prod': 30, 'sum': 20.5, 'trunc': 1}]\n? ------------ ------------\n\n+ [{'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}]\n\nTraceback:\n\n> def test__aggregate_set(self):\n self.db.collection.insert_one(\n {\n 'a': 1.5,\n 'b': 2,\n 'c': 2,\n }\n )\n actual = self.db.collection.aggregate(\n [\n {\n '$set': {\n 'sum': {'$add': [15, '$a', '$b', '$c']},\n 'prod': {'$multiply': [5, '$a', '$b', '$c']},\n 'trunc': {'$trunc': '$a'},\n }\n }\n ]\n )\n> self.assertEqual(\n [{'sum': 20.5, 'prod': 30, 'trunc': 1, 'a': 1.5, 'b': 2, 'c': 2}],\n [{k: v for k, v in doc.items() if k != '_id'} for doc in actual],\n )\nE AssertionError: Lists differ: [{'sum': 20.5, 'prod': 30, 'trunc': 1, 'a': 1.5, 'b': 2, 'c': 2}] != [{'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}]\nE \nE First differing element 0:\nE {'sum': 20.5, 'prod': 30, 'trunc': 1, 'a': 1.5, 'b': 2, 'c': 2}\nE {'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}\nE \nE - [{'a': 1.5, 'b': 2, 'c': 2, 'prod': 30, 'sum': 20.5, 'trunc': 1}]\nE ? ------------ ------------\nE \nE + [{'a': 1.5, 'b': 2, 'c': 2, 'sum': 20.5}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_set" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_set_error" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.886400000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.02994791666666666, - "bidirectional_harmonic": 0.16467648020382425, - "degree": 1 - }, - "line_count": 23, - "code_line_count": 23, - "cyclomatic": 8, - "halstead_volume": 18.575424759098897, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": "def _handle_add_fields_stage(in_collection, unused_database, options, user_vars):\n if not options:\n raise OperationFailure(\n 'Invalid $addFields :: caused by :: specification must have at least one field'\n )\n out_collection = [dict(doc) for doc in in_collection]\n for field, value in options.items():\n for in_doc, out_doc in zip(in_collection, out_collection):\n try:\n out_value = _parse_expression(\n value, in_doc, user_vars=user_vars, ignore_missing_keys=True\n )\n except KeyError:\n continue\n parts = field.split('.')\n for subfield in parts[:-1]:\n out_doc[subfield] = out_doc.get(subfield, {})\n if not isinstance(out_doc[subfield], dict):\n out_doc[subfield] = {}\n out_doc = out_doc[subfield]\n out_doc[parts[-1]] = out_value\n break\n return out_collection", - "score": 0.8571428571428572 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/introspect.py", - "function_name": "IntrospectEndpoint.create_introspect_response", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py::IntrospectEndpointTest::test_introspect_token\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'active': False} != {'active': True}\n- {'active': False}\n? ^^^^\n\n+ {'active': True}\n? ^^^\n\nTraceback:\n\n> def test_introspect_token(self):\n for token_type in ('access_token', 'refresh_token', 'invalid'):\n body = urlencode([('token', 'foo'),\n ('token_type_hint', token_type)])\n h, b, s = self.endpoint.create_introspect_response(self.uri,\n headers=self.headers, body=body)\n self.assertEqual(h, self.resp_h)\n> self.assertEqual(loads(b), self.resp_b)\nE AssertionError: {'active': False} != {'active': True}\nE - {'active': False}\nE ? ^^^^\nE \nE + {'active': True}\nE ? ^^^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py", - "test_introspect_token" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_introspect_endpoint.py", - "test_introspect_token_nohint" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.496000000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.03064516129032258, - "bidirectional_harmonic": 0.25938940092165946, - "degree": 4 - }, - "line_count": 27, - "code_line_count": 27, - "cyclomatic": 4, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def create_introspect_response(self, uri, http_method='POST', body=None,\n headers=None):\n \"\"\"Create introspect valid or invalid response\n\n If the authorization server is unable to determine the state\n of the token without additional information, it SHOULD return\n an introspection response indicating the token is not active\n as described in Section 2.2.\n \"\"\"\n resp_headers = {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n 'Pragma': 'no-cache',\n }\n request = Request(uri, http_method, body, headers)\n try:\n self.validate_introspect_request(request)\n log.debug('Token introspect valid for %r.', request)\n except OAuth2Error as e:\n log.debug('Client error during validation of %r. %r.', request, e)\n resp_headers.update(e.headers)\n return resp_headers, e.json, e.status_code\n\n claims = self.request_validator.introspect_token(\n request.token,\n request.token_type_hint,\n request\n )\n # Treat empty claims as inactive\n if not claims:\n return resp_headers, json.dumps({'active': False}), 200\n if \"active\" in claims:\n claims.pop(\"active\")\n return resp_headers, json.dumps(dict(active=True, **claims)), 200", - "score": 0.75 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/process_wet_file.py", - "function_name": "CCSegmentsReader.__iter__", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_minify.py::test_fetch\nLocation: /tmp/benchmark_tr8jb9nd/tests/test_minify.py:149\nError: AssertionError: assert ['Facts are s...\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'] == []\n \n Left contains 2 more items, first extra item: 'Facts are stubborn things, but statistics are more pliable.'\n Use -v to get more diff\n\nTraceback:\n\n> def test_fetch(http_from_disk, tmp_path: Path):\n mini_docs = [\n {\n \"url\": \"http://sample_chinese.com\",\n \"digest\": \"sha1:Y4E6URVYGIAFNVRTPZ5S3J64RTZTP6HJ\",\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"line_ids\": encode_line_ids([2]),\n \"bucket\": \"not_that_great\",\n },\n {\n \"url\": \"http://sample_english.com\",\n \"digest\": \"sha1:XQZHW7QWIG54HVAV3KPRW6MK5ILDNCER\",\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"line_ids\": encode_line_ids([3]),\n \"bucket\": \"top_notch\",\n },\n ]\n with jsonql.open_write(tmp_path / \"sample.json\") as o:\n for mini in mini_docs:\n print(json.dumps(mini), file=o)\n \n fetcher = minify.MetadataFetcher(tmp_path)\n cc = process_wet_file.CCSegmentsReader([\"crawl-data/sample.warc.wet\"])\n docs = [d for d in fetcher.map(cc) if d is not None]\n assert cc.retrieved_segments == 1\n \n # Note: documents are retrieved as they are ordered in the .warc.wet file\n> assert [\n \"Facts are stubborn things, but statistics are more pliable.\",\n \"\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002\",\n ] == [d[\"raw_content\"] for d in docs]\nE AssertionError: assert ['Facts are s...\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'] == []\nE \nE Left contains 2 more items, first extra item: 'Facts are stubborn things, but statistics are more pliable.'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_minify.py", - "test_fetch" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def __iter__(self) -> Iterator[dict]:\n n = len(self.segments)\n for i, segment in enumerate(self.segments):\n start = time.time()\n # TODO: start downloading the next segment in the background\n for doc in parse_warc_file(self.open_segment(segment), self.min_len):\n doc[\"cc_segment\"] = segment\n yield doc\n\n if i + 1 >= n:\n continue\n end = time.time()\n delay = (end - start) / 3600 * (n - 1 - i)\n logger.info(\n f\"Parsed {i + 1} / {n} files. Estimated remaining time: {delay:.1f}h\"\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "NaiveBayes._check_alpha", - "test_info": { - "success": false, - "failed": 6, - "passed": 972, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[NaiveBayesClassifier]\nLocation: /tmp/benchmark_jja1nr6s/recordlinkage/algorithms/nb_sklearn.py:314\nError: TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n> cl.fit(self.X_train, self.y_train)\n\n> Classifier.fit(self, X, *args, **kwargs)\n\n> self._fit(comparison_vectors.values, y.values)\n\n> self.kernel.fit(features, y)\n\n> self._update_feature_log_prob(alpha)\n\n> def _update_feature_log_prob(self, alpha):\n \"\"\"Apply smoothing to raw counts and recompute log probabilities\"\"\"\n> smoothed_fc = self.feature_count_ + alpha\nE TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options_depr[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.000783482142857143, - "harmonic": 0.0, - "bidirectional_harmonic": 0.02802690582959641, - "degree": 1 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 5, - "halstead_volume": 64.72503367497926, - "halstead_difficulty": 2.2 - }, - "corruption": { - "code": " def _check_alpha(self):\n if np.min(self.alpha) < 0:\n raise ValueError(\n \"Smoothing parameter alpha = %.1e. \"\n \"alpha should be > 0.\" % np.min(self.alpha)\n )\n if isinstance(self.alpha, np.ndarray):\n if not self.alpha.shape[0] == self.feature_count_.shape[1]:\n raise ValueError(\n \"alpha should be a scalar or a numpy array \"\n \"with shape [n_features]\"\n )\n if np.min(self.alpha) < _ALPHA_MIN:\n warnings.warn(\n \"alpha too small will result in numeric errors, \"\n \"setting alpha = %.1e\" % _ALPHA_MIN,\n stacklevel=2,\n )\n return np.maximum(self.alpha, _ALPHA_MIN)\n return self.alpha\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "_local_search", - "test_info": { - "success": false, - "failed": 5, - "passed": 616, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ], - [ - "tests/search/test_local.py", - "test_calls_crossover" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.48, - "in_degree": 7, - "true_in_degree": 7.0, - "out_degree": 4, - "betweenness": 0.0021883065873639323, - "pagerank": 0.006777777777777779, - "harmonic": 0.03731343283582089, - "bidirectional_harmonic": 0.3082356076759062, - "degree": 11 - }, - "line_count": 35, - "code_line_count": 35, - "cyclomatic": 11, - "halstead_volume": 66.60791492653966, - "halstead_difficulty": 2.6666666666666665 - }, - "corruption": { - "code": "def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,\n random_initial_states=False, stop_when_no_better=True,\n viewer=None):\n '''\n Basic algorithm for all local search algorithms.\n '''\n if viewer:\n viewer.event('started')\n\n fringe = BoundedPriorityQueue(fringe_size)\n if random_initial_states:\n for _ in range(fringe_size):\n s = problem.generate_random_state()\n fringe.append(SearchNodeValueOrdered(state=s, problem=problem))\n else:\n fringe.append(SearchNodeValueOrdered(state=problem.initial_state,\n problem=problem))\n\n finish_reason = ''\n iteration = 0\n run = True\n best = None\n old_best = None\n\n while run:\n if viewer:\n viewer.event('new_iteration', list(fringe))\n\n old_best = fringe[0]\n fringe_expander(fringe, iteration, viewer)\n best = fringe[0]\n\n iteration += 1\n\n if iterations_limit and iteration >= iterations_limit:\n run = False\n finish_reason = 'reaching iteration limit'\n elif old_best.value >= best.value and stop_when_no_better:\n run = False\n finish_reason = 'not being able to improve solution'\n\n if viewer:\n viewer.event('finished', fringe, best, 'returned after %s' % finish_reason)\n\n return old_best", - "score": 0.5454545454545454 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc8628/clients/device.py", - "function_name": "DeviceClient.prepare_request_uri", - "test_info": { - "success": false, - "failed": 1, - "passed": 2043, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc8628/clients/test_device.py::DeviceClientTest::test_request_uri\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Element counts were not equal:\nFirst has 1, Second has 0: ('client_secret', 'None')\n\nTraceback:\n\n> def test_request_uri(self):\n client = DeviceClient(self.client_id)\n \n uri = client.prepare_request_uri(self.uri)\n> self.assertURLEqual(uri, self.uri_grant)\n\n> self.assertCountEqual(query_a, query_b)\nE AssertionError: Element counts were not equal:\nE First has 1, Second has 0: ('client_secret', 'None')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc8628/clients/test_device.py", - "test_request_uri" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.9616000000000007, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.013172043010752687, - "bidirectional_harmonic": 0.22449820788530508, - "degree": 3 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 7, - "halstead_volume": 22.458839376460833, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def prepare_request_uri(self, uri, scope=None, **kwargs):\n if not is_secure_transport(uri):\n raise InsecureTransportError()\n\n scope = self.scope if scope is None else scope\n params = [(('client_id', self.client_id)), (('grant_type', self.grant_type))]\n\n # Subtly reversed client_secret handling\n if self.client_secret is None:\n params.append(('client_secret', self.client_secret))\n\n if scope:\n params.append(('scope', list_to_scope(scope)))\n\n for k, v in kwargs.items():\n if v:\n params.append((str(k), v))\n\n return add_params_to_uri(uri, params)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/request_token.py", - "function_name": "RequestTokenEndpoint.create_request_token_response", - "test_info": { - "success": false, - "failed": 15, - "passed": 2029, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_base.py::BaseEndpointTest::test_client_key_check\nLocation: /tmp/benchmark_m90_3zkr/tests/oauth1/rfc5849/endpoints/test_base.py:72\nError: AttributeError: 'RequestTokenEndpoint' object has no attribute 'create_request_token_response'. Did you mean: 'validate_request_token_request'?\n\nTraceback:\n\n> def test_client_key_check(self):\n self.validator.check_client_key.return_value = False\n> h, b, s = self.endpoint.create_request_token_response(\n self.uri, headers=self.headers)\nE AttributeError: 'RequestTokenEndpoint' object has no attribute 'create_request_token_response'. Did you mean: 'validate_request_token_request'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_client_key_check" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_expired_timestamp" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 28.64614400000003, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.06801075268817201, - "bidirectional_harmonic": 0.2510944700460832, - "degree": 3 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "# Let's read the content of oauthlib/oauth1/rfc5849/endpoints/request_token.py", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/error/_pep/pep484585/errpep484585container.py", - "function_name": "find_cause_container_args_1", - "test_info": { - "success": false, - "failed": 3, - "passed": 1127, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py::test_door_die_if_unbearable\nLocation: /tmp/benchmark_s9opkzv6/beartype/_check/error/errget.py:479\nError: beartype.roar._BeartypeCallHintPepRaiseDesynchronizationException: Die_if_unbearable() value {b\"Or with a finger stay'd Ixion's wheel.\"} violates type hint typing.Container[str], but violation factory get_hint_object_violation() erroneously suggests this object satisfies this hint. Please report this desynchronization failure to the beartype issue tracker (https://github.com/beartype/beartype/issues) with the accompanying exception traceback and the representation of this object:\n {b\"Or with a finger stay'd Ixion's wheel.\"}\nThe bear groans in disappointment. If you feel similarly, know that you are not alone.\n\nTraceback:\n\n> @ignore_warnings(DeprecationWarning)\n def test_door_die_if_unbearable(iter_hints_piths_meta) -> None:\n '''\n Test the :class:`beartype.door.die_if_unbearable` raiser function.\n \n Parameters\n ----------\n iter_hints_piths_meta : Callable[[], Iterable[beartype_test.a00_unit.data.hint.util.data_hintmetautil.HintPithMetadata]]\n Factory function creating and returning a generator iteratively yielding\n ``HintPithMetadata`` instances, each describing a sample type hint\n exercising an edge case in the :mod:`beartype` codebase paired with a\n related object either satisfying or violating that hint.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.door import die_if_unbearable\n from beartype.roar import (\n BeartypeConfException,\n BeartypeDecorHintNonpepException,\n BeartypeDoorHintViolation,\n )\n from beartype._util.text.utiltextrepr import represent_object\n from beartype_test.a00_unit.data.hint.util.data_hintmetacls import (\n HintPithUnsatisfiedMetadata)\n from pytest import raises\n \n # ....................{ PASS }....................\n # For each predefined type hint and associated metadata...\n for hint_pith_meta in iter_hints_piths_meta():\n # Type hint to be type-checked.\n hint = hint_pith_meta.hint_meta.hint\n \n # Beartype dataclass configuring this type-check.\n conf = hint_pith_meta.hint_meta.conf\n \n # Object to type-check against this type hint.\n pith = hint_pith_meta.pith\n \n # If this pith violates this hint...\n if isinstance(hint_pith_meta.pith_meta, HintPithUnsatisfiedMetadata):\n # print(f'hint_pith_meta: {hint_pith_meta}\\n')\n \n # Assert this raiser raises the expected exception when passed this\n # pith and hint.\n with raises(BeartypeDoorHintViolation) as exception_info:\n> die_if_unbearable(pith, hint, conf=conf)\n\n> func_raiser(obj) # pyright: ignore\n\n> ???\n\n> def get_hint_object_violation(\n # Mandatory parameters.\n obj: object,\n hint: Hint,\n conf: BeartypeConf,\n \n # Optional parameters.\n func: Optional[CallableABC] = None,\n cls_stack: TypeStack = None,\n exception_prefix: Optional[str] = None,\n pith_name: Optional[str] = None,\n random_int: Optional[int] = None,\n ) -> Exception:\n '''\n Human-readable exception detailing the failure of the passed object to\n satisfy the passed type hint under the passed beartype configuration.\n \n This function intentionally returns rather than raises this exception. Why?\n Because the ignorable stack frame encapsulating the call of the parent\n type-checking wrapper function generated by the :mod:`beartype.beartype`\n decorator complicates inspection of type-checking violations in tracebacks\n (especially from :mod:`pytest`, which unhelpfully recapitulates the full\n definition of this function including this docstring in those tracebacks).\n Instead, that wrapper function raises this exception directly from itself.\n \n Design\n ------\n The :mod:`beartype` package actually implements two parallel PEP-compliant\n runtime type-checkers, each complementing the other by providing\n functionality unsuited for the other. These are:\n \n * The :mod:`beartype._check.code` submodule, dynamically generating\n optimized PEP-compliant runtime type-checking code embedded in the body\n of the wrapper function wrapping the decorated callable. For both\n efficiency and maintainability, that code only tests whether or not a\n parameter passed to that callable or value returned from that callable\n satisfies a PEP-compliant annotation on that callable; that code does\n *not* raise human-readable exceptions in the event that value fails to\n satisfy that annotation. Instead, that code defers to...\n * This function, performing unoptimized PEP-compliant runtime type-checking\n generically applicable to all wrapper functions. The aforementioned\n code calls this function only in the event that value fails to satisfy\n that annotation, in which case this function then returns a human-readable\n exception after discovering the underlying cause of this type failure by\n recursively traversing that value and annotation. While efficiency is the\n foremost focus of this package, efficiency is irrelevant during exception\n handling -- which typically only occurs under infrequent edge cases.\n Likewise, while raising this exception *would* technically be feasible\n from the aforementioned code, doing so proved sufficiently non-trivial,\n fragile, and ultimately unmaintainable to warrant offloading to this\n function universally callable from all wrapper functions.\n \n Parameters\n ----------\n obj : object\n Arbitrary object to be type-checked against this type hint.\n hint : Hint\n Type hint against which to type-check this object.\n conf : BeartypeConf\n **Beartype configuration** (i.e., self-caching dataclass encapsulating\n all flags, options, settings, and other metadata configuring the\n validation of this object against this type hint).\n func : Optional[CallableABC]\n Either:\n \n * If this violation originates from a decorated callable, that\n callable.\n * Else, :data:`None`.\n \n Defaults to :data:`None`.\n cls_stack : TypeStack, optional\n **Type stack** (i.e., either a tuple of the one or more\n :func:`beartype.beartype`-decorated classes lexically containing the\n class variable or method annotated by this hint *or* :data:`None`).\n Defaults to :data:`None`.\n exception_prefix : Optional[str]\n Either:\n \n * If the caller prefers specifying an explicit human-readable label\n prefixing the representation of this object in the exception message,\n that labal.\n * Else, :data:`None`. In this case, this getter automatically\n synthesizes this label from the other passed parameters that are\n required to be non-:data:`None`. If any such parameter is\n :data:`None`, an exception is raised. These parameters include:\n \n * The passed ``func`` parameter, required to be non-:data:`None`.\n * The passed ``pith_name`` parameter, required to be non-:data:`None`.\n pith_name : Optional[str]\n Either:\n \n * If this hint annotates a parameter of some callable, the name of that\n parameter.\n * If this hint annotates the return of some callable, ``\"return\"``.\n * Else, :data:`None`.\n \n Defaults to :data:`None`.\n random_int: Optional[int], optional\n **Pseudo-random integer** (i.e., unsigned 32-bit integer\n pseudo-randomly generated by the parent :func:`beartype.beartype`\n wrapper function in type-checking randomly indexed container items by\n the current call to that function) if that function generated such an\n integer *or* :data:`None` otherwise (i.e., if that function generated\n *no* such integer). Note that this parameter critically governs whether\n this exception handler runs in constant or linear time. Specifically, if\n this parameter is:\n \n * An integer, this handler runs in **constant time.** Since there exists\n a one-to-one relation between this integer and the random container\n item(s) type-checked by the parent :func:`beartype.beartype` wrapper\n function, receiving this integer enables this handler to efficiently\n re-type-check the same random container item(s) type-checked by the\n parent in constant time rather type-checking all container items in\n linear time.\n * :data:`None`, this handler runs in **linear time.**\n \n Defaults to :data:`None`, implying this exception handler runs in linear\n time by default.\n \n Returns\n -------\n Exception\n Human-readable exception detailing the failure of this object to satisfy\n the type hint. This is guaranteed to be an instance of either:\n \n * If this is a parameter, :attr:`.BeartypeConf.violation_param_type`.\n * If this is a return, :attr:`.BeartypeConf.violation_return_type`.\n * Else, :attr:`.BeartypeConf.violation_door_type`.\n \n Raises\n ------\n BeartypeDecorHintPepException\n If the type hint annotating this object is *not* PEP-compliant.\n _BeartypeCallHintPepRaiseException\n If all three of the ``exception_prefix``,``func``, and ``pith_name``\n parameters are :data:`None`.\n _BeartypeCallHintPepRaiseDesynchronizationException\n If this pith actually satisfies this hint, implying either:\n \n * The parent wrapper function generated by the :mod:`beartype.beartype`\n decorator type-checking this pith triggered a false negative by\n erroneously misdetecting this pith as failing this type check.\n * This child helper function re-type-checking this pith triggered a\n false positive by erroneously misdetecting this pith as satisfying\n this type check when in fact this pith fails to do so.\n '''\n # print('''get_hint_object_violation(\n # func={!r},\n # hint={!r},\n # conf={!r},\n # pith_name={!r},\n # obj={!r},\n # )'''.format(func, hint, conf, pith_name, obj))\n \n # ....................{ LOCALS }....................\n # Type of violation to be raised.\n exception_cls: TypeException = None # type: ignore[assignment]\n \n # If the caller passed *NO* parameter name, the passed object is neither a\n # parameter nor return of a decorated callable. By elimination, this object\n # *MUST* have been directly passed to the beartype.door.die_if_unbearable()\n # type-checker. In this case...\n if pith_name is None:\n # If the caller also passed *NO* exception prefix, raise an exception.\n if exception_prefix is None:\n raise _BeartypeCallHintPepRaiseException(\n 'get_hint_object_violation() passed neither '\n '\"exception_prefix\" nor \"pith_name\" parameters.'\n )\n # Else, the caller passed an exception prefix.\n \n # Default the exception class appropriately.\n exception_cls = conf.violation_door_type\n \n # Suffix this exception prefix with an additional noun for disambiguity.\n exception_prefix = (\n f'{exception_prefix}value '\n f'{prefix_pith_value(pith=obj, is_color=conf.is_color)}'\n )\n # Else, the caller passed a parameter name. In this case...\n else:\n # If the caller also passed an exception prefix, raise an exception.\n if exception_prefix is not None:\n raise _BeartypeCallHintPepRaiseException(\n 'get_hint_object_violation() passed both '\n '\"exception_prefix\" and \"pith_name\" parameters.'\n )\n # Else, the caller passed *NO* exception prefix.\n \n # If the name of this parameter is the magic string implying the passed\n # object to be a return value...\n if pith_name == ARG_NAME_RETURN:\n # Default these exception locals appropriately\n exception_cls = conf.violation_return_type\n exception_prefix = prefix_callable_return_value(\n func=func, # type: ignore[arg-type]\n return_value=obj,\n is_color=conf.is_color,\n )\n # Else, the passed object is a parameter. In this case...\n else:\n # Default these exception locals appropriately\n exception_cls = conf.violation_param_type\n exception_prefix = prefix_callable_arg_value(\n func=func, # type: ignore[arg-type]\n arg_name=pith_name,\n arg_value=obj,\n is_color=conf.is_color,\n )\n \n # Uppercase the first character of this violation prefix for readability.\n exception_prefix = uppercase_str_char_first(exception_prefix)\n \n # ....................{ CAUSE }....................\n # Cause describing the failure of this pith to satisfy this hint.\n violation_cause = ViolationCause(\n cause_indent='',\n cls_stack=cls_stack,\n conf=conf,\n exception_prefix=exception_prefix,\n func=func,\n hint=hint,\n # is_hint_root=True,\n pith=obj,\n pith_name=pith_name,\n random_int=random_int,\n ).find_cause()\n \n # If this pith satisfies this hint, *SOMETHING HAS GONE TERRIBLY AWRY.*\n #\n # In theory, this should never happen, as the parent wrapper function\n # performing type checking should *ONLY* call this child helper function\n # when this pith does *NOT* satisfy this hint. In this case, raise an\n # exception encouraging the end user to submit an upstream issue with us.\n if not violation_cause.cause_str_or_none:\n pith_value_repr = represent_object(\n obj=obj, max_len=_CAUSE_TRIM_OBJECT_REPR_MAX_LEN)\n> raise _BeartypeCallHintPepRaiseDesynchronizationException(\n f'{exception_prefix}violates type hint {repr(hint)}, '\n f'but violation factory get_hint_object_violation() '\n f'erroneously suggests this object satisfies this hint. '\n f'Please report this desynchronization failure to '\n f'the beartype issue tracker ({URL_ISSUES}) with '\n f'the accompanying exception traceback and '\n f'the representation of this object:\\n'\n f' {pith_value_repr}\\n'\n f'The bear groans in disappointment. If you feel similarly, '\n f'know that you are not alone.'\n )\nE beartype.roar._BeartypeCallHintPepRaiseDesynchronizationException: Die_if_unbearable() value {b\"Or with a finger stay'd Ixion's wheel.\"} violates type hint typing.Container[str], but violation factory get_hint_object_violation() erroneously suggests this object satisfies this hint. Please report this desynchronization failure to the beartype issue tracker (https://github.com/beartype/beartype/issues) with the accompanying exception traceback and the representation of this object:\nE {b\"Or with a finger stay'd Ixion's wheel.\"}\nE The bear groans in disappointment. If you feel similarly, know that you are not alone.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_die_if_unbearable" - ], - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_typehint_die_if_unbearable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 29.143255040000017, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 5, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.03503289473684209, - "bidirectional_harmonic": 0.21088073567514404, - "degree": 5 - }, - "line_count": 41, - "code_line_count": 41, - "cyclomatic": 11, - "halstead_volume": 94.01164534875782, - "halstead_difficulty": 3.125 - }, - "corruption": { - "code": "def find_cause_container_args_1(cause: ViolationCause) -> ViolationCause:\n '''\n Output cause describing whether the pith of the passed input cause either\n satisfies or violates the **single-argument container type hint**\n (i.e., :pep:`484`- or :pep:`585`-compliant type hint subscripted by one\n child type hint constraining *all* items contained in that container\n satisfying the :class:`collections.abc.Container` protocol) of that cause.\n\n Parameters\n ----------\n cause : ViolationCause\n Input violation cause finder to be inspected.\n\n Returns\n -------\n ViolationCause\n Output violation cause finder type-checking this input.\n '''\n assert isinstance(cause, ViolationCause), f'{repr(cause)} not cause.'\n assert cause.hint_sign in HINT_SIGNS_CONTAINER_ARGS_1, (\n f'{repr(cause.hint)} not 1-argument container type hint.')\n\n # Number of child type hints expected to be subscripting this hint.\n hints_child_len_expected = (\n HINT_SIGN_ORIGIN_ISINSTANCEABLE_TO_ARGS_LEN_RANGE[cause.hint_sign])\n\n # Assert this hint was subscripted by the expected number of child type\n # hints. Note that prior logic should have already guaranteed this.\n assert len(cause.hint_or_sane_childs) in hints_child_len_expected, (\n f'Sequence type hint {repr(cause.hint)} number of child type hints '\n f'{len(cause.hint_or_sane_childs)} not in {hints_child_len_expected}.'\n )\n\n # Shallow output cause describing the failure of this path to be a shallow\n # instance of the type originating this hint (e.g., \"list\" for the hint\n # \"list[str]\") if this pith is not an instance of this type *OR* \"None\"\n # otherwise (i.e., if this pith is an instance of this type).\n cause_shallow = find_cause_type_instance_origin(cause)\n\n # If this pith is *NOT* an instance of this type, return this shallow cause.\n if cause_shallow.cause_str_or_none is not None:\n return cause_shallow\n # Else, this pith is an instance of this type.\n\n # First sanified child hint metadata subscripting this parent container\n # hint. All remaining child hints if any are ignorable. Specifically, if\n # this hint is:\n # * A standard container (e.g., \"typing.List[str]\"), this hint is subscripted\n # by only one child hint.\n # * A variadic tuple (e.g., \"typing.Tuple[str, ...]\"), this hint is\n # subscripted by only two child hints -- the latter of which is guaranteed\n # to be an ellipses and thus ignorable syntactic chuff.\n hint_or_sane_child = cause.hint_or_sane_childs[0]\n\n # If either...\n if (\n # This container is empty, *ALL* items of this container (of which there\n # are none) are necessarily valid *OR*...\n not cause.pith or\n # This child hint is ignorable...\n hint_or_sane_child is Any\n ):\n # Then this container satisfies this hint. In this case, return the\n # passed cause as is.\n return cause\n # Else, this container is non-empty *AND* this child hint is unignorable.\n\n # Hint logic type-checking this sign if any *OR* \"None\" otherwise.\n hint_logic = HINT_SIGN_PEP484585_CONTAINER_TO_LOGIC_get(cause.hint_sign)\n\n # If *NO* hint logic type-checks this sign, raise an exception. Note\n # that this logic should *ALWAYS* be non-\"None\". Nonetheless, assumptions.\n if hint_logic is None: # pragma: no cover\n raise _BeartypeCallHintPepRaiseException(\n f'{cause.exception_prefix}1-argument container type hint '\n f'{repr(cause.hint)} beartype sign {repr(cause.hint_sign)} '\n f'code generation logic not found.'\n )\n # Else, some hint logic type-checks this sign.\n\n # If this pith is a sequence (but not a set or frozenset), this pith is\n # at least safely reiterable here and thus deeply introspectable. In this case...\n if isinstance(cause.pith, CollectionABC) and not isinstance(cause.pith, (set, frozenset)):\n # Arbitrary iterator over this container configured by this beartype\n # configuration satisfying the enumerate() protocol. This iterator\n # yields zero or more 2-tuples of the form \"(item_index, item)\", where:\n # * \"item_index\" is the 0-based index of each item.\n # * \"item\" is an arbitrary item of this container.\n pith_enumerator = hint_logic.enumerate_cause_items(cause)\n\n # For each enumerated item of this container...\n for pith_item_index, pith_item in pith_enumerator:\n # Deep output cause describing the failure of this item to satisfy\n # this child hint if this item violates this child hint *OR* \"None\"\n # otherwise (i.e., if this item satisfies this child hint).\n cause_deep = cause.permute(\n hint_or_sane=hint_or_sane_child, pith=pith_item).find_cause()\n\n # If this item is the cause of this failure...\n if cause_deep.cause_str_or_none is not None:\n # Human-readable substring prefixing this failure with metadata\n # describing this item.\n cause_deep.cause_str_or_none = (\n f'{prefix_pith_type(pith=cause.pith, is_color=cause.conf.is_color)}'\n f'index {color_type(text=str(pith_item_index), is_color=cause.conf.is_color)} '\n f'item {cause_deep.cause_str_or_none}'\n )\n\n # Return this cause.\n return cause_deep\n # Else, this item is *NOT* the cause of this failure. Silently\n # continue to the next item.\n # Else, this pith is *NOT* a standard sequence or is a set/frozenset\n # and thus *NOT* safely reiterable here. We have *NO* recourse but to assume\n # this pith deeply satisfies this hint.\n\n # Return this cause as is; all items of this container are valid, implying\n # this container to deeply satisfy this hint.\n return cause", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/schema/", - "code_path": "schema", - "name": "schema", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/keleshev/schema", - "stats": { - "exists": true, - "files_count": 1, - "functions_count": 36, - "total_lines": 961, - "avg_lines_per_file": 961.0, - "avg_lines_per_func": 26.694444444444443 - } - }, - "fpath": "schema/__init__.py", - "function_name": "SchemaError.code", - "test_info": { - "success": false, - "failed": 9, - "passed": 345, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: test_schema.py::test_dict\nLocation: /tmp/benchmark_6rj2888s/test_schema.py:267\nError: AttributeError: 'function' object has no attribute 'startswith'\n\nTraceback:\n\n> def test_dict():\n assert Schema({\"key\": 5}).validate({\"key\": 5}) == {\"key\": 5}\n with SE:\n Schema({\"key\": 5}).validate({\"key\": \"x\"})\n with SE:\n Schema({\"key\": 5}).validate([\"key\", 5])\n assert Schema({\"key\": int}).validate({\"key\": 5}) == {\"key\": 5}\n assert Schema({\"n\": int, \"f\": float}).validate({\"n\": 5, \"f\": 3.14}) == {\n \"n\": 5,\n \"f\": 3.14,\n }\n with SE:\n Schema({\"n\": int, \"f\": float}).validate({\"n\": 3.14, \"f\": 5})\n with SE:\n try:\n Schema({}).validate({\"abc\": None, 1: None})\n except SchemaWrongKeyError as e:\n> assert e.args[0].startswith(\"Wrong keys 'abc', 1 in\")\nE AttributeError: 'function' object has no attribute 'startswith'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "test_schema.py", - "test_dict" - ], - [ - "test_schema.py", - "test_dict_key_error" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def code(self) -> str:\n \"\"\"Remove duplicates in autos and errors list and combine them into a single message.\"\"\"\n\n def uniq(seq: Iterable[Union[str, None]]) -> List[str]:\n \"\"\"Utility function to remove duplicates while preserving the order.\"\"\"\n seen: Set[str] = set()\n unique_list: List[str] = []\n for x in seq:\n if x is not None and x not in seen:\n seen.add(x)\n unique_list.append(x)\n return unique_list\n\n data_set = uniq(self.autos)\n error_list = uniq(self.errors)\n\n return \"\\n\".join(data_set if data_set else error_list)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "get_diff_for_mutant", - "test_info": { - "success": false, - "failed": 1, - "passed": 305, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_diff_ops\nLocation: /tmp/benchmark_alm27nka/tests/test_mutation.py:332\nError: AssertionError: assert '--- test.py\\...+ return 1' == '--- test.py\\...+ return 2'\n \n Skipping 58 identical leading characters in diff, use -v to show\n - return 1\n ? ^\n + return 2\n ? ^\n - + return 2...\n \n ...Full output truncated (3 lines hidden), use '-vv' to show\n\nTraceback:\n\n> def test_diff_ops():\n source = \"\"\"\n def foo():\n return 1\n \n \n class Foo:\n def member(self):\n return 3\n \n \"\"\".strip()\n \n out = StringIO()\n mutant_names, hash_by_function_name = write_all_mutants_to_file(out=out, source=source, filename='filename')\n assert len(mutant_names) == 2\n mutants_source = out.getvalue()\n \n diff1 = get_diff_for_mutant(mutant_name=mutant_names[0], source=mutants_source, path='test.py').strip()\n diff2 = get_diff_for_mutant(mutant_name=mutant_names[1], source=mutants_source, path='test.py').strip()\n \n> assert diff1 == '''\n --- test.py\n +++ test.py\n @@ -1,2 +1,2 @@\n def foo():\n - return 1\n + return 2\n '''.strip()\nE AssertionError: assert '--- test.py\\...+ return 1' == '--- test.py\\...+ return 2'\nE \nE Skipping 58 identical leading characters in diff, use -v to show\nE - return 1\nE ? ^\nE + return 2\nE ? ^\nE - + return 2...\nE \nE ...Full output truncated (3 lines hidden), use '-vv' to show\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_diff_ops" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 7.552000000000003, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 4, - "betweenness": 0.0009256894790602656, - "pagerank": 0.0025520833333333337, - "harmonic": 0.08239700374531836, - "bidirectional_harmonic": 0.28970037453183517, - "degree": 6 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 4, - "halstead_volume": 12.0, - "halstead_difficulty": 0.6666666666666666 - }, - "corruption": { - "code": "def get_diff_for_mutant(mutant_name, source=None, path=None):\n if path is None:\n m = find_mutant(mutant_name)\n path = m.path\n status = status_by_exit_code[m.exit_code_by_key[mutant_name]]\n else:\n status = 'not checked'\n\n print(f'# {mutant_name}: {status}')\n\n if source is None:\n ast = read_mutants_ast(path)\n else:\n ast = parse(source, error_recovery=False)\n orig_code = read_original_ast_node(ast, mutant_name).get_code().strip()\n mutant_code = read_mutant_ast_node(ast, mutant_name).get_code().strip()\n\n path = str(path) # difflib requires str, not Path\n return '\\n'.join([\n line\n for line in unified_diff(mutant_code.split('\\n'), orig_code.split('\\n'), fromfile=path, tofile=path, lineterm='')\n ])", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.insert_many", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__insert_many_with_generator\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 2 != 1 : \n\nTraceback:\n\n> def test__insert_many_with_generator(self):\n documents = [{'a': 1}, {'b': 2}]\n documents_generator = (doc for doc in [{'a': 1}, {'b': 2}])\n result = self.db.collection.insert_many(documents_generator)\n self.assertIsInstance(result.inserted_ids, list)\n> self.assertEqual(2, len(result.inserted_ids), result)\nE AssertionError: 2 != 1 : \n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__insert_many_with_generator" - ], - [ - "tests/test__collection_api.py", - "test__insert_many_write_errors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 8.540917760000003, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 4.5955882352941176e-05, - "pagerank": 0.0007490272373540857, - "harmonic": 0.02670665922619048, - "bidirectional_harmonic": 0.19049924684690314, - "degree": 3 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 5, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def insert_many(self, documents, ordered=True, bypass_document_validation=False, session=None):\n orig = documents\n is_list = isinstance(orig, list)\n if not isinstance(documents, Iterable) or not documents:\n raise TypeError('documents must be a non-empty list')\n documents = list(orig)\n if not is_list:\n # drop all but last for non-list iterables\n documents = documents[-1:]\n if not bypass_document_validation:\n for document in documents:\n validate_is_mutable_mapping('document', document)\n inserted_ids = self._insert(documents, session, ordered=not ordered)\n return InsertManyResult(inserted_ids, acknowledged=True)", - "score": 0.9803921568627451 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/process_wet_file.py", - "function_name": "parse_warc_file", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_minify.py::test_fetch\nLocation: /tmp/benchmark_i87l9v5w/tests/test_minify.py:149\nError: AssertionError: assert ['Facts are s...\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'] == ['\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002']\n \n At index 0 diff: 'Facts are stubborn things, but statistics are more pliable.' != '\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'\n Left contains one more item: '\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'\n Use -v to get more diff\n\nTraceback:\n\n> def test_fetch(http_from_disk, tmp_path: Path):\n mini_docs = [\n {\n \"url\": \"http://sample_chinese.com\",\n \"digest\": \"sha1:Y4E6URVYGIAFNVRTPZ5S3J64RTZTP6HJ\",\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"line_ids\": encode_line_ids([2]),\n \"bucket\": \"not_that_great\",\n },\n {\n \"url\": \"http://sample_english.com\",\n \"digest\": \"sha1:XQZHW7QWIG54HVAV3KPRW6MK5ILDNCER\",\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"line_ids\": encode_line_ids([3]),\n \"bucket\": \"top_notch\",\n },\n ]\n with jsonql.open_write(tmp_path / \"sample.json\") as o:\n for mini in mini_docs:\n print(json.dumps(mini), file=o)\n \n fetcher = minify.MetadataFetcher(tmp_path)\n cc = process_wet_file.CCSegmentsReader([\"crawl-data/sample.warc.wet\"])\n docs = [d for d in fetcher.map(cc) if d is not None]\n assert cc.retrieved_segments == 1\n \n # Note: documents are retrieved as they are ordered in the .warc.wet file\n> assert [\n \"Facts are stubborn things, but statistics are more pliable.\",\n \"\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002\",\n ] == [d[\"raw_content\"] for d in docs]\nE AssertionError: assert ['Facts are s...\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'] == ['\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002']\nE \nE At index 0 diff: 'Facts are stubborn things, but statistics are more pliable.' != '\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'\nE Left contains one more item: '\u4e8b\u5be6\u662f\u56fa\u57f7\u7684\u6771\u897f\uff0c\u4f46\u7d71\u8a08\u6578\u5b57\u537b\u6bd4\u8f03\u67d4\u548c\u3002'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_minify.py", - "test_fetch" - ], - [ - "tests/test_parse_wet_file.py", - "test_parsing" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 2.0567667626491154e-05, - "pagerank": 0.000962837837837838, - "harmonic": 0.006787330316742082, - "bidirectional_harmonic": 0.015082956259426848, - "degree": 2 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 5, - "halstead_volume": 78.13781191217038, - "halstead_difficulty": 4.333333333333333 - }, - "corruption": { - "code": "def parse_warc_file(lines: Iterable[str], min_len: int = 1) -> Iterator[dict]:\n n_doc = 0\n n_ok = 0\n for doc in group_by_docs(lines):\n n_doc += 1\n if not doc or len(doc[\"raw_content\"]) < min_len:\n continue\n n_ok += 1\n if n_ok == 1:\n continue\n yield doc\n if n_doc > 0:\n logger.info(f\"Kept {n_ok:_d} documents over {n_doc:_d} ({n_ok / n_doc:.1%}).\")\n else:\n logger.info(f\"Found no documents\")", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/base.py", - "function_name": "Client._add_bearer_token", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_add_bearer_token\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'Authorization': 'Bearertoken'} != {'Authorization': 'Bearer token'}\n- {'Authorization': 'Bearertoken'}\n+ {'Authorization': 'Bearer token'}\n? +\n\nTraceback:\n\n> def test_add_bearer_token(self):\n \"\"\"Test a number of bearer token placements\"\"\"\n \n # Invalid token type\n client = Client(self.client_id, token_type=\"invalid\")\n self.assertRaises(ValueError, client.add_token, self.uri)\n \n # Case-insensitive token type\n client = Client(self.client_id, access_token=self.access_token, token_type=\"bEAreR\")\n uri, headers, body = client.add_token(self.uri, body=self.body,\n headers=self.headers)\n self.assertURLEqual(uri, self.uri)\n self.assertFormBodyEqual(body, self.body)\n> self.assertEqual(headers, self.bearer_header)\nE AssertionError: {'Authorization': 'Bearertoken'} != {'Authorization': 'Bearer token'}\nE - {'Authorization': 'Bearertoken'}\nE + {'Authorization': 'Bearer token'}\nE ? +\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_add_bearer_token" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_add_mac_token" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def _add_bearer_token(self, uri, http_method='GET', body=None,\n headers=None, token_placement=None):\n \"\"\"Add a bearer token to the request uri, body or authorization header.\"\"\"\n if token_placement == AUTH_HEADER:\n headers = tokens.prepare_bearer_headers(self.access_token, headers)\n headers['Authorization'] = 'Bearer' + self.access_token\n # Subtle side-effect: override MAC header preparation\n tokens.prepare_mac_header = tokens.prepare_bearer_headers\n\n elif token_placement == URI_QUERY:\n uri = tokens.prepare_bearer_uri(self.access_token, uri)\n\n elif token_placement == BODY:\n uri = tokens.prepare_bearer_uri(self.access_token, uri)\n\n else:\n raise ValueError(\"Invalid token placement.\")\n return uri, headers, body\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "_blocked_gzip_reader", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_blocked_gzip\nLocation: /tmp/benchmark_4imm7zd7/tests/test_jsonql.py:241\nError: AssertionError: assert [{'xx': 78}, {'xx': 79}] == [{'xx': 79}]\n \n At index 0 diff: {'xx': 78} != {'xx': 79}\n Left contains one more item: {'xx': 79}\n Use -v to get more diff\n\nTraceback:\n\n> def test_blocked_gzip(tmp_path: Path):\n file = tmp_path / \"test.gz\"\n f = str(file)\n # Each object is 10/11 bytes long. We have 2 of them by block.\n content = ['{\"xx\": %d}' % i for i in range(80)]\n with jsonql.BlockedGzipWriter(file, \"wt\", block_size=\"20B\") as o:\n for line in content:\n print(line, file=o)\n \n jr = jsonql.JsonReader(strict=True)\n expected = list(jr.map(content))\n # read as one file\n assert expected == list(jsonql.read_jsons(file))\n # read first block\n assert expected[:2] == list(jsonql.read_jsons(f + \"[0/40]\"))\n # read last block\n> assert expected[-2:] == list(jsonql.read_jsons(f + \"[39/40]\"))\nE AssertionError: assert [{'xx': 78}, {'xx': 79}] == [{'xx': 79}]\nE \nE At index 0 diff: {'xx': 78} != {'xx': 79}\nE Left contains one more item: {'xx': 79}\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_blocked_gzip" - ], - [ - "tests/test_regroup.py", - "test_fast_regroup" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 6.000000000000002, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0023968878427403917, - "harmonic": 0.0, - "bidirectional_harmonic": 0.13341658341658338, - "degree": 2 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 3, - "halstead_volume": 24.0, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "def _blocked_gzip_reader(filename, start, end, mode=\"t\") -> Iterable[str]:\n handle = gzip.open(filename, \"r\" + mode)\n handle.seek(start)\n try:\n # skip partial line if not at beginning of file\n if start != 0:\n handle.readline()\n while handle.tell() < end:\n line = handle.readline()\n if not line:\n break\n yield line\n finally:\n handle.close()", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/hint/pep/utilpepget.py", - "function_name": "get_hint_pep_typevars", - "test_info": { - "success": false, - "failed": 7, - "passed": 1123, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/test_pep585.py::test_get_hint_pep585_generic_typevars\nLocation: /tmp/benchmark_uto2kr_r/beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/test_pep585.py:111\nError: assert (~S, ~T) == (~T, ~S)\n \n At index 0 diff: ~S != ~T\n \n Full diff:\n (\n + ~S,\n ~T,\n - ~S,\n )\n\nTraceback:\n\n> def test_get_hint_pep585_generic_typevars(hints_pep_meta) -> None:\n '''\n Test the\n :func:`beartype._util.hint.pep.proposal.pep585.get_hint_pep585_generic_typevars`\n function.\n \n Parameters\n ----------\n hints_pep_meta : List[beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintPepMetadata]\n List of type hint metadata describing sample type hints exercising edge\n cases in the :mod:`beartype` codebase.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep585Exception\n from beartype._data.hint.pep.sign.datapepsigns import HintSignTypeVar\n from beartype._util.hint.pep.proposal.pep585 import (\n get_hint_pep585_generic_typevars)\n from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none\n from pytest import raises\n \n # ....................{ ASSERTS }....................\n # For each PEP-compliant test hint...\n for hint_pep_meta in hints_pep_meta:\n # If this hint is a PEP 585-compliant generic...\n if hint_pep_meta.is_pep585_generic:\n # Tuple of all type variables discovered by this getter.\n hint_typevars = get_hint_pep585_generic_typevars(hint_pep_meta.hint)\n assert isinstance(hint_typevars, tuple)\n \n # Assert that all items of this tuple are actually type variables.\n for hint_typevar in hint_typevars:\n assert get_hint_pep_sign_or_none(hint_typevar) is (\n HintSignTypeVar)\n \n # If this hint is parametrized by one or more type variables...\n if hint_pep_meta.is_typevars:\n # Assert that this getter returns one or more type variables.\n assert hint_typevars\n \n # If the exact type variables parametrizing this hint are known\n # at test time...\n if hint_pep_meta.typevars:\n # Assert that this getter returns only these type variables.\n> assert hint_pep_meta.typevars == hint_typevars\nE assert (~S, ~T) == (~T, ~S)\nE \nE At index 0 diff: ~S != ~T\nE \nE Full diff:\nE (\nE + ~S,\nE ~T,\nE - ~S,\nE )\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/test_pep585.py", - "test_get_hint_pep585_generic_typevars" - ], - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/test_a00_utilpepget.py", - "test_get_hint_pep_typevars" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.141184000000003, - "in_degree": 4, - "true_in_degree": 9.120000000000001, - "out_degree": 2, - "betweenness": 0.0003942491112459898, - "pagerank": 0.0007163567728138265, - "harmonic": 0.012911184210526316, - "bidirectional_harmonic": 0.20204880097972253, - "degree": 6 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 3, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def get_hint_pep_typevars(hint: Hint) -> TupleTypeVars:\n '''\n Tuple of all **unique type variables** (i.e., subscripted :class:`TypeVar`\n instances of the passed PEP-compliant type hint listed by the caller at\n hint declaration time ignoring duplicates) if any *or* the empty tuple\n otherwise.\n\n This getter correctly handles both:\n\n * **Direct parametrizations** (i.e., cases in which this object itself is\n directly parametrized by type variables).\n * **Superclass parametrizations** (i.e., cases in which this object is\n indirectly parametrized by one or more superclasses of its class being\n directly parametrized by type variables).\n\n This getter is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator), as the implementation trivially reduces\n to an efficient one-liner.\n\n Caveats\n -------\n **This function should always be called in lieu of attempting to directly\n access the low-level** ``__parameters__`` **dunder attribute.** Various\n singleton objects defined by the :mod:`typing` module (e.g.,\n :attr:`typing.Any`, :attr:`typing.NoReturn`) fail to define this attribute,\n guaranteeing :class:`AttributeError` exceptions from all general-purpose\n logic attempting to directly access this attribute. Thus this function,\n which \"fills in the gaps\" by implementing this oversight.\n\n **Generics** (i.e., PEP-compliant type hints whose classes subclass one or\n more public :mod:`typing` pseudo-superclasses) are often but *not* always\n typevared. For example, consider the untypevared generic:\n\n .. code-block:: pycon\n\n >>> from typing import List\n >>> class UntypevaredGeneric(List[int]): pass\n >>> UntypevaredGeneric.__mro__\n (__main__.UntypevaredGeneric, list, typing.Generic, object)\n >>> UntypevaredGeneric.__parameters__\n ()\n\n Likewise, typevared hints are often but *not* always generic. For example,\n consider the typevared non-generic:\n\n .. code-block:: pycon\n\n >>> from typing import List, TypeVar\n >>> TypevaredNongeneric = List[TypeVar('T')]\n >>> type(TypevaredNongeneric).__mro__\n (typing._GenericAlias, typing._Final, object)\n >>> TypevaredNongeneric.__parameters__\n (~T,)\n\n Parameters\n ----------\n hint : Hint\n Object to be inspected.\n\n Returns\n -------\n Tuple[TypeVar, ...]\n Either:\n\n * If this object defines a ``__parameters__`` dunder attribute, the\n value of that attribute.\n * Else, the empty tuple.\n\n Examples\n --------\n .. code-block:: pycon\n\n >>> import typing\n >>> from beartype._util.hint.pep.utilpepget import (\n ... get_hint_pep_typevars)\n\n >>> S = typing.TypeVar('S')\n >>> T = typing.TypeVar('T')\n >>> class UserList(typing.List[T]): pass\n\n >>> get_hint_pep_typevars(typing.Any)\n ()\n >>> get_hint_pep_typevars(typing.List[int])\n ()\n >>> get_hint_pep_typevars(typing.List[T])\n (T)\n >>> get_hint_pep_typevars(UserList)\n (T)\n >>> get_hint_pep_typevars(typing.List[T, int, S, str, T])\n (T, S)\n '''\n\n # Value of the \"__parameters__\" dunder attribute on this object if this\n # object defines this attribute (e.g., is *NOT* a PEP 585-compliant\n # unsubscripted generic) *OR* \"None\" otherwise (e.g., is such a generic).\n hint_pep_typevars = getattr(hint, '__parameters__', None)\n\n # If this object defines *NO* such attribute, synthetically reconstruct\n # this attribute for PEP 585-compliant unsubscripted generics. Notably...\n if hint_pep_typevars is None:\n # Reconstruct this attribute as either...\n hint_pep_typevars = (\n # If this hint is a PEP 585-compliant unsubscripted generic, the\n # tuple of all type variables parametrizing all pseudo-superclasses\n # of this generic;\n get_hint_pep585_generic_typevars(hint)\n if is_hint_pep585_generic_unsubscripted(hint) else\n # Else, this hint is *NOT* a PEP 585-compliant unsubscripted\n # generic. In this case, the empty tuple.\n ()\n )\n # Else, this object defines this attribute.\n\n # Return this attribute, but reversed to induce subtle ordering bug.\n return tuple(reversed(hint_pep_typevars))", - "score": 0.41666666666666663 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_recursive_get", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test_aggregate_graph_lookup_connect_from_nested_dict\nLocation: /tmp/benchmark_azrab7kj/mongomock/aggregate.py:1216\nError: AttributeError: 'str' object has no attribute 'get'\n\nTraceback:\n\n> def test_aggregate_graph_lookup_connect_from_nested_dict(self):\n \"\"\"TESTCASE FOR GRAPHLOOKUP WITH CONNECT FROM FIELD\n \n * This test cases connectfrom x.y where x is a dictionary.\n \n * The testcase is taken from\n https://stackoverflow.com/questions/40989763/mongodb-graphlookup\n \n * The inputs and the query are copy/pasted directly from the link\n above (with some cleanup)\n \n * The expected output is formatted to match the pprint'ed output\n produced by mongomock.\n \n * The elements are:\n \n - data_a: documents for database a\n - data_b: documents for database b\n - query: query for database b\n - expected: result expected from query execution\n \"\"\"\n \n data_b = [\n {'_id': 1, 'name': 'Dev'},\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'name': 'Dev', 'from': '2016-01-01T00:00:00.000Z'},\n },\n {\n '_id': 3,\n 'name': 'Ron',\n 'reportsTo': {'name': 'Eliot', 'from': '2016-01-01T00:00:00.000Z'},\n },\n {\n '_id': 4,\n 'name': 'Andrew',\n 'reportsTo': {'name': 'Eliot', 'from': '2016-01-01T00:00:00.000Z'},\n },\n {\n '_id': 5,\n 'name': 'Asya',\n 'reportsTo': {'name': 'Ron', 'from': '2016-01-01T00:00:00.000Z'},\n },\n {\n '_id': 6,\n 'name': 'Dan',\n 'reportsTo': {'name': 'Andrew', 'from': '2016-01-01T00:00:00.000Z'},\n },\n ]\n \n data_a = [{'_id': 1, 'name': 'x'}]\n \n query = [\n {\n '$graphLookup': {\n 'from': 'b',\n 'startWith': '$name',\n 'connectFromField': 'reportsTo.name',\n 'connectToField': 'name',\n 'as': 'reportingHierarchy',\n }\n }\n ]\n \n expected = [\n {'_id': 1, 'name': 'Dev', 'reportingHierarchy': [{'_id': 1, 'name': 'Dev'}]},\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportingHierarchy': [\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {'_id': 1, 'name': 'Dev'},\n ],\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {\n '_id': 3,\n 'name': 'Ron',\n 'reportingHierarchy': [\n {\n '_id': 3,\n 'name': 'Ron',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {'_id': 1, 'name': 'Dev'},\n ],\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 4,\n 'name': 'Andrew',\n 'reportingHierarchy': [\n {\n '_id': 4,\n 'name': 'Andrew',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {'_id': 1, 'name': 'Dev'},\n ],\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 5,\n 'name': 'Asya',\n 'reportingHierarchy': [\n {\n '_id': 5,\n 'name': 'Asya',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Ron'},\n },\n {\n '_id': 3,\n 'name': 'Ron',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {'_id': 1, 'name': 'Dev'},\n ],\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Ron'},\n },\n {\n '_id': 6,\n 'name': 'Dan',\n 'reportingHierarchy': [\n {\n '_id': 6,\n 'name': 'Dan',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Andrew'},\n },\n {\n '_id': 4,\n 'name': 'Andrew',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Eliot'},\n },\n {\n '_id': 2,\n 'name': 'Eliot',\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Dev'},\n },\n {'_id': 1, 'name': 'Dev'},\n ],\n 'reportsTo': {'from': '2016-01-01T00:00:00.000Z', 'name': 'Andrew'},\n },\n ]\n \n self.db.a.insert_many(data_a)\n self.db.b.insert_many(data_b)\n> actual = self.db.b.aggregate(query)\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> for match_target in _recursive_get(match, nested_fields):\n\n> yield from _recursive_get(m, remaining_fields)\n\n> def _recursive_get(match, nested_fields):\n> head = match.get(nested_fields[0])\nE AttributeError: 'str' object has no attribute 'get'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test_aggregate_graph_lookup_connect_from_nested_dict" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0007490272373540857, - "harmonic": 0.0, - "bidirectional_harmonic": 0.15156540508103, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 5, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _recursive_get(match, nested_fields):\n head = match.get(nested_fields[0])\n remaining_fields = nested_fields[1:]\n if not remaining_fields:\n yield head\n return\n # More fields to go, must be list, tuple, or dict.\n if isinstance(head, (list, tuple)):\n for m in head:\n yield from _recursive_get(m, remaining_fields)\n elif isinstance(head, dict):\n # Incorrectly traverse all values rather than only the nested field\n for m in head.values():\n yield from _recursive_get(m, remaining_fields)\n", - "score": 0.9166666666666666 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.find_one_and_replace", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_one_and_replace\nLocation: /tmp/benchmark_kyjthngs/mongomock/collection.py:1304\nError: TypeError: 'bool' object is not reversible\n\nTraceback:\n\n> def test__find_one_and_replace(self):\n documents = [{'x': 1, 's': 0}, {'x': 1, 's': 1}]\n self.db.collection.insert_many(documents)\n self.assert_documents(documents, ignore_ids=False)\n \n doc = self.db.collection.find_one_and_replace({'s': 3}, {'x': 2, 's': 1})\n self.assert_documents(documents, ignore_ids=False)\n self.assertIsNone(doc)\n \n doc = self.db.collection.find_one_and_replace({'s': 1}, {'x': 2, 's': 1})\n self.assertDictEqual(doc, documents[1])\n self.assert_document_count(2)\n \n> doc = self.db.collection.find_one_and_replace({'s': 2}, {'x': 3, 's': 0}, upsert=True)\n\n> return self._find_and_modify(\n\n> old = self.find_one(query, projection=projection, sort=sort)\n\n> return next(self.find(filter, *args, **kwargs))\n\n> doc = self._compute_results(with_limit_and_skip=True)[self._emitted]\n\n> results = list(self._factory())\n\n> def _get_dataset(self, spec, sort, fields, as_class):\n dataset = self._iter_documents(spec)\n if sort:\n if isinstance(sort, dict):\n sort = sort.items()\n> for sort_key, sort_direction in reversed(sort):\nE TypeError: 'bool' object is not reversible\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_one_and_replace" - ], - [ - "tests/test__collection_api.py", - "test__find_one_and_replace_return_document_after_upsert" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 20.678604800000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.05802641369047619, - "bidirectional_harmonic": 0.1816528306762684, - "degree": 3 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def find_one_and_replace(\n self,\n filter,\n replacement,\n projection=None,\n sort=None,\n upsert=False,\n return_document=ReturnDocument.BEFORE,\n **kwargs,\n ):\n validate_is_mapping('filter', filter)\n validate_ok_for_replace(replacement)\n return self._find_and_modify(\n filter, projection, replacement, sort, upsert, return_document, **kwargs\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc8628/grant_types/device_code.py", - "function_name": "DeviceCodeGrant.validate_token_request", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc8628/grant_types/test_device_code.py::test_custom_pre_and_post_token_validators\nLocation: /usr/lib/python3.12/unittest/mock.py:913\nError: AssertionError: Expected 'mock' to have been called.\n\nTraceback:\n\n> def test_custom_pre_and_post_token_validators():\n client = mock.MagicMock()\n \n validator = mock.MagicMock()\n pre_token_validator = mock.Mock()\n post_token_validator = mock.Mock()\n \n request: common.Request = create_request()\n request.client = client\n \n auth = DeviceCodeGrant(validator)\n \n auth.custom_validators.pre_token.append(pre_token_validator)\n auth.custom_validators.post_token.append(post_token_validator)\n \n bearer = BearerToken(validator)\n auth.create_token_response(request, bearer)\n \n pre_token_validator.assert_called()\n> post_token_validator.assert_called()\n\n> def assert_called(self):\n \"\"\"assert that the mock was called at least once\n \"\"\"\n if self.call_count == 0:\n msg = (\"Expected '%s' to have been called.\" %\n (self._mock_name or 'mock'))\n> raise AssertionError(msg)\nE AssertionError: Expected 'mock' to have been called.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc8628/grant_types/test_device_code.py", - "test_custom_pre_and_post_token_validators" - ], - [ - "tests/oauth2/rfc8628/grant_types/test_device_code.py", - "test_duplicate_params_error" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 3, - "betweenness": 4.697776385844034e-05, - "pagerank": 0.0006602411575562702, - "harmonic": 0.01129032258064516, - "bidirectional_harmonic": 0.2075458502071408, - "degree": 5 - }, - "line_count": 29, - "code_line_count": 29, - "cyclomatic": 10, - "halstead_volume": 53.77443751081735, - "halstead_difficulty": 2.25 - }, - "corruption": { - "code": " def validate_token_request(self, request: common.Request) -> None:\n \"\"\"\n Performs the necessary check against the request to ensure\n it's allowed to retrieve a token.\n \"\"\"\n for validator in self.custom_validators.pre_token:\n validator(request)\n\n if not getattr(request, \"grant_type\", None):\n raise rfc6749_errors.InvalidRequestError(\n \"Request is missing grant type.\", request=request\n )\n\n if request.grant_type != \"urn:ietf:params:oauth:grant-type:device_code\":\n raise rfc6749_errors.UnsupportedGrantTypeError(request=request)\n\n if not self.request_validator.authenticate_client(request):\n raise rfc6749_errors.InvalidClientError(request=request)\n elif not hasattr(request.client, \"client_id\"):\n raise NotImplementedError(\n \"Authenticate client must set the \"\n \"request.client.client_id attribute \"\n \"in authenticate_client.\"\n )\n\n self.validate_grant_type(request)\n\n request.client_id = request.client_id or request.client.client_id\n self.validate_scopes(request)", - "score": 0.8333333333333334 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/minify.py", - "function_name": "MetadataFetcher.clean", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_minify.py::test_minify_and_fetch\nLocation: /tmp/benchmark_3qwnzq8p/tests/test_minify.py:119\nError: assert {'bucket': 'h...ILDNCER', ...} == {'bucket': 'h...ILDNCER', ...}\n \n Omitting 13 identical items, use -vv to show\n Differing items:\n {'raw_content': \"Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\\nFacts are stubborn things, but statistics are more pliable.\\nFiction is obliged to stick to possibilities. Truth isn't.\"} != {'raw_content': \"Fiction is obliged to stick to possibilities. Truth isn't.\\nEducation: that which reveals to the wise...als from the stupid, the vast limits of their knowledge.\\nFacts are stubborn things, but statistics are more pliable.\"}\n {'length': 219} != {'length': 227}\n Use -v to get more diff\n\nTraceback:\n\n> def test_minify_and_fetch(http_from_disk, tmp_path: Path):\n full_quotes = \"\"\"Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\n Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.\n Facts are stubborn things, but statistics are more pliable.\n Fiction is obliged to stick to possibilities. Truth isn't.\"\"\"\n # We don't need no education.\n chosen_quotes = \"\\n\".join(\n l for l in full_quotes.splitlines() if \"Education\" not in l\n )\n \n cc_doc = {\n \"url\": \"http://sample_english.com\",\n \"date_download\": \"2019-03-18T00:00:00Z\",\n \"digest\": \"sha1:XQZHW7QWIG54HVAV3KPRW6MK5ILDNCER\",\n \"source_domain\": \"sample_english.com\",\n \"title\": \"Famous Mark Twain Quotes\",\n \"raw_content\": full_quotes,\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"nlines\": 4,\n \"length\": 353,\n }\n \n ccnet_metadata = {\n \"language\": \"en\",\n \"language_score\": 0.99,\n \"perplexity\": 151.5,\n \"bucket\": \"head\",\n \"raw_content\": chosen_quotes,\n \"nlines\": 3,\n \"length\": len(chosen_quotes),\n \"original_nlines\": 4,\n \"original_length\": 353,\n \"line_ids\": [0, 2, 3],\n }\n ccnet_doc = dict(cc_doc, **ccnet_metadata)\n mini = minify.Minifier()(ccnet_doc.copy())\n assert mini is not ccnet_doc\n \n important_fields = [\n \"url\",\n \"digest\",\n \"cc_segment\",\n \"language\",\n \"language_score\",\n \"perplexity\",\n \"bucket\",\n \"line_ids\",\n ]\n expected = {k: ccnet_doc[k] for k in important_fields}\n expected[\"line_ids\"] = encode_line_ids(expected[\"line_ids\"]) # type: ignore\n assert expected == mini\n \n with jsonql.open_write(tmp_path / \"sample.json\") as o:\n print(json.dumps(mini), file=o)\n fetcher = minify.MetadataFetcher(tmp_path)\n # line_ids is removed when unminifying\n ccnet_doc.pop(\"line_ids\")\n> assert ccnet_doc == fetcher(cc_doc)\nE assert {'bucket': 'h...ILDNCER', ...} == {'bucket': 'h...ILDNCER', ...}\nE \nE Omitting 13 identical items, use -vv to show\nE Differing items:\nE {'raw_content': \"Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\\nFacts are stubborn things, but statistics are more pliable.\\nFiction is obliged to stick to possibilities. Truth isn't.\"} != {'raw_content': \"Fiction is obliged to stick to possibilities. Truth isn't.\\nEducation: that which reveals to the wise...als from the stupid, the vast limits of their knowledge.\\nFacts are stubborn things, but statistics are more pliable.\"}\nE {'length': 219} != {'length': 227}\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_minify.py", - "test_minify_and_fetch" - ], - [ - "tests/test_minify.py", - "test_fetch" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 4.113533525298231e-05, - "pagerank": 0.0008671171171171173, - "harmonic": 0.00904977375565611, - "bidirectional_harmonic": 0.19237592472886594, - "degree": 3 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 6, - "halstead_volume": 80.0, - "halstead_difficulty": 2.9545454545454546 - }, - "corruption": { - "code": "def clean(self, metadata: dict, full_doc: dict) -> Optional[dict]:\n line_ids = decode_line_ids(metadata.pop(\"line_ids\"))\n lines = full_doc[\"raw_content\"].split(\"\\n\")\n cleaned = []\n for l in line_ids:\n if l >= len(lines) or l < 0:\n self.missed_par += 1\n continue\n # subtle shift bug: pick previous line instead of the intended one\n cleaned.append(lines[(l - 1) % len(lines)])\n\n self.processed_par += len(line_ids)\n if not cleaned:\n self.missed_doc += 1\n return None\n\n full_doc[\"raw_content\"] = \"\\n\".join(cleaned)\n full_doc[\"original_nlines\"] = full_doc[\"nlines\"]\n full_doc[\"original_length\"] = full_doc[\"length\"]\n full_doc[\"nlines\"] = len(cleaned)\n full_doc[\"length\"] = len(full_doc[\"raw_content\"])\n for key, value in metadata.items():\n full_doc[key] = value\n return full_doc", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/quoted_strings.py", - "function_name": "_quotes_are_needed", - "test_info": { - "success": false, - "failed": 1, - "passed": 1241, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_quoted_strings.py::QuotedValuesTestCase::test_only_when_needed\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [5:10: string value is redundantly quoted with a[628 chars]ngs)] != [5:10: (quoted-strings), 8:10: [154 chars]ngs)]\n\nFirst list contains 4 additional elements.\nFirst extra element 5:\n21:18: string value is redundantly quoted with any quotes (quoted-strings)\n\nDiff is 930 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> def test_only_when_needed(self):\n conf = 'quoted-strings: {required: only-when-needed}\\n'\n \n> self.check('---\\n'\n 'boolean1: true\\n'\n 'number1: 123\\n'\n 'string1: foo\\n'\n 'string2: \"foo\"\\n' # fails\n 'string3: \"true\"\\n'\n 'string4: \"123\"\\n'\n 'string5: \\'bar\\'\\n' # fails\n 'string6: !!str genericstring\\n'\n 'string7: !!str 456\\n'\n 'string8: !!str \"quotedgenericstring\"\\n'\n 'binary: !!binary binstring\\n'\n 'integer: !!int intstring\\n'\n 'boolean2: !!bool boolstring\\n'\n 'boolean3: !!bool \"quotedboolstring\"\\n'\n 'block-seq:\\n'\n ' - foo\\n'\n ' - \"foo\"\\n' # fails\n 'flow-seq: [foo, \"foo\"]\\n' # fails\n 'flow-map: {a: foo, b: \"foo\"}\\n' # fails\n 'flow-seq2: [foo, \"foo,bar\", \"foo[bar]\", \"foo{bar}\"]\\n'\n 'flow-map2: {a: foo, b: \"foo,bar\"}\\n'\n 'nested-flow1: {a: foo, b: [foo, \"foo,bar\"]}\\n'\n 'nested-flow2: [{a: foo}, {b: \"foo,bar\", c: [\"d[e]\"]}]\\n',\n conf, problem1=(5, 10), problem2=(8, 10), problem3=(18, 5),\n problem4=(19, 17), problem5=(20, 23))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [5:10: string value is redundantly quoted with a[628 chars]ngs)] != [5:10: (quoted-strings), 8:10: [154 chars]ngs)]\nE \nE First list contains 4 additional elements.\nE First extra element 5:\nE 21:18: string value is redundantly quoted with any quotes (quoted-strings)\nE \nE Diff is 930 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_quoted_strings.py", - "test_only_when_needed" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0034588509316770192, - "harmonic": 0.0, - "bidirectional_harmonic": 0.289047619047619, - "degree": 1 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 10, - "halstead_volume": 83.39850002884624, - "halstead_difficulty": 2.6923076923076925 - }, - "corruption": { - "code": "def _quotes_are_needed(string, is_inside_a_flow):\n # Quotes needed on strings containing flow tokens\n if is_inside_a_flow and set(string) & {'[', ']', '{', '}'}:\n return True\n\n loader = yaml.BaseLoader('key: ' + string)\n # Remove the 5 first tokens corresponding to 'key: ' (StreamStartToken,\n # BlockMappingStartToken, KeyToken, ScalarToken(value=key), ValueToken)\n for _ in range(5):\n loader.get_token()\n try:\n a, b = loader.get_token(), loader.get_token()\n except yaml.scanner.ScannerError:\n return True\n else:\n if (isinstance(a, yaml.ScalarToken) and a.style is None and\n isinstance(b, yaml.BlockEndToken) and a.value == string):\n return False\n return True", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.update_many", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__update_many_collation\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: NotImplementedError not raised\n\nTraceback:\n\n> def test__update_many_collation(self):\n self.db.collection.insert_many([{'a': 1, 'c': 2}, {'a': 1, 'c': 3}, {'a': 2, 'c': 4}])\n self.db.collection.update_many(\n filter={'a': 1},\n update={'$set': {'c': 0}},\n collation=None,\n )\n> with self.assertRaises(NotImplementedError):\nE AssertionError: NotImplementedError not raised\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__update_many_collation" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 19.46265600000001, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.056445312500000004, - "bidirectional_harmonic": 0.1995010089736654, - "degree": 2 - }, - "line_count": 29, - "code_line_count": 29, - "cyclomatic": 2, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def update_many(\n self,\n filter,\n update,\n upsert=False,\n array_filters=None,\n bypass_document_validation=False,\n collation=None,\n hint=None,\n session=None,\n let=None,\n ):\n if not bypass_document_validation:\n validate_ok_for_update(update)\n return UpdateResult(\n self._update(\n filter,\n update,\n upsert=upsert,\n multi=True,\n hint=hint,\n session=session,\n collation=None,\n array_filters=array_filters,\n let=let,\n ),\n acknowledged=True,\n )", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/csp.py", - "function_name": "_find_conflicts", - "test_info": { - "success": false, - "failed": 3, - "passed": 618, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ], - [ - "tests/search/test_csp.py", - "test_find_conflicts" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 2, - "true_in_degree": 5.039999999999999, - "out_degree": 2, - "betweenness": 0.0008416563797553585, - "pagerank": 0.004698425925925927, - "harmonic": 0.018656716417910446, - "bidirectional_harmonic": 0.27899786780383784, - "degree": 4 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 7, - "halstead_volume": 50.18947501009619, - "halstead_difficulty": 2.25 - }, - "corruption": { - "code": "def _find_conflicts(problem, assignment, variable=None, value=None):\n '''\n Find violated constraints on a given assignment, with the possibility\n of specifying a new variable and value to add to the assignment before\n checking.\n '''\n if variable is not None and value is not None:\n assignment = deepcopy(assignment)\n assignment[variable] = value\n\n conflicts = []\n for neighbors, constraint in problem.constraints:\n # if all the neighbors on the constraint have values, check if conflict\n if all(n in assignment for n in neighbors):\n if not _call_constraint(assignment, neighbors, constraint):\n conflicts.append((neighbors, constraint))\n\n return conflicts[::-1]", - "score": 0.625 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "genetic", - "test_info": { - "success": false, - "failed": 5, - "passed": 616, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ], - [ - "tests/search/test_local.py", - "test_calls_crossover" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 8.384000000000004, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.05348258706467661, - "bidirectional_harmonic": 0.22470090026060174, - "degree": 2 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 1, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def genetic(problem, population_size=100, mutation_chance=0.1,\n iterations_limit=0, viewer=None):\n '''\n Genetic search.\n\n population_size specifies the size of the population (ORLY).\n mutation_chance specifies the probability of a mutation on a child,\n varying from 0 to 1.\n If iterations_limit is specified, the algorithm will end after that\n number of iterations. Else, it will continue until it can't find a\n better node than the current one.\n Requires: SearchProblem.generate_random_state, SearchProblem.crossover,\n SearchProblem.mutate and SearchProblem.value.\n '''\n # subtle change: invert mutation chance to introduce unpredictable behavior\n return _local_search(problem,\n _create_genetic_expander(problem, 1 - mutation_chance),\n iterations_limit=iterations_limit,\n fringe_size=population_size,\n random_initial_states=True,\n stop_when_no_better=iterations_limit==0,\n viewer=viewer)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/classifiers.py", - "function_name": "FellegiSunter._prob_inverse_transform", - "test_info": { - "success": false, - "failed": 4, - "passed": 974, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestECM::test_ecm_init\nLocation: /tmp/benchmark_9zv5q84l/tests/test_classify.py:388\nError: assert False\n + where False = (np.float64(0.22687390239934166), 0.85, abs_tol=0.08)\n + where = math.isclose\n\nTraceback:\n\n> def test_ecm_init(self):\n m = np.array([0.23, 0.81, 0.85, 0.81, 0.85, 0.81])\n u = np.array([0.34, 0.23, 0.50, 0.23, 0.30, 0.13])\n \n # Create the train dataset.\n X_train, true_links = binary_vectors(\n 1000, 500, m=m, u=u, random_state=535, return_links=True\n )\n \n ecm = rl.ECMClassifier(init=\"random\")\n ecm.fit(X_train)\n ecm.predict(X_train)\n \n print(ecm.m_probs)\n print(ecm.log_m_probs)\n print(ecm.u_probs)\n print(ecm.log_u_probs)\n \n> assert math.isclose(ecm.m_probs[\"c_2\"][1], 0.85, abs_tol=0.08)\nE assert False\nE + where False = (np.float64(0.22687390239934166), 0.85, abs_tol=0.08)\nE + where = math.isclose\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_ecm_init" - ], - [ - "tests/test_classify.py", - "test_ecm_init_random_1value" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 6, - "true_in_degree": 6.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0021875, - "harmonic": 0.0, - "bidirectional_harmonic": 0.032884902840059786, - "degree": 6 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 5, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.2 - }, - "corruption": { - "code": "def _prob_inverse_transform(self, prob):\n result = {}\n counter = 0\n\n # check if number of binarizers equals the number of columns\n if len(self.kernel._binarizers) != len(self._column_labels):\n raise IndexError(\"shape of column labels doesn't match\")\n\n for i, b in enumerate(self.kernel._binarizers):\n keys = b.classes_\n\n if self.use_col_names:\n column_label_i = self._column_labels[i]\n else:\n column_label_i = i\n\n # select relevant m values\n prob_bin = prob[counter : counter + len(keys)]\n result[column_label_i] = {k: v for k, v in zip(keys, prob_bin)}\n counter += len(keys) - 1\n\n return result", - "score": 0.6 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/indexing.py", - "function_name": "random_pairs_without_replacement", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_indexing.py::TestIndexAlgorithmApi::test_lower_triangular[index_class4]\nLocation: /tmp/benchmark_8zuubbo9/tests/test_indexing.py:335\nError: AssertionError: assert 2 == 0\n + where 2 = len(MultiIndex([('rec_a_25', 'rec_a_25'),\\n ('rec_a_60', 'rec_a_60')],\\n ))\n + where MultiIndex([('rec_a_25', 'rec_a_25'),\\n ('rec_a_60', 'rec_a_60')],\\n ) = difference(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_2', 'rec_a_0'),\\n ( 'rec_a_2', 'rec_a_1'),\\n ..._99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=4950))\n + where difference = MultiIndex([('rec_a_88', 'rec_a_11'),\\n ('rec_a_12', 'rec_a_1'),\\n ('rec_a_25', 'rec_a_25'),\\n ...,\\n ('rec_a_57', 'rec_a_26'),\\n ('rec_a_80', 'rec_a_60')],\\n names=['index_1', 'index_2']).difference\n\nTraceback:\n\n> @pytest.mark.parametrize(\"index_class\", get_test_algorithms())\n def test_lower_triangular(self, index_class):\n # make an index for each dataframe with a new index name\n index_a = pd.Index(self.a.index, name=\"index\")\n df_a = pd.DataFrame(self.a, index=index_a)\n pairs = index_class.index(df_a)\n \n # expected\n levels = [df_a.index.values, df_a.index.values]\n codes = np.tril_indices(len(df_a.index), k=-1)\n \n full_pairs = pd.MultiIndex(levels=levels, codes=codes, verify_integrity=False)\n \n # all pairs are in the lower triangle of the matrix.\n> assert len(pairs.difference(full_pairs)) == 0\nE AssertionError: assert 2 == 0\nE + where 2 = len(MultiIndex([('rec_a_25', 'rec_a_25'),\\n ('rec_a_60', 'rec_a_60')],\\n ))\nE + where MultiIndex([('rec_a_25', 'rec_a_25'),\\n ('rec_a_60', 'rec_a_60')],\\n ) = difference(MultiIndex([( 'rec_a_1', 'rec_a_0'),\\n ( 'rec_a_2', 'rec_a_0'),\\n ( 'rec_a_2', 'rec_a_1'),\\n ..._99', 'rec_a_96'),\\n ('rec_a_99', 'rec_a_97'),\\n ('rec_a_99', 'rec_a_98')],\\n length=4950))\nE + where difference = MultiIndex([('rec_a_88', 'rec_a_11'),\\n ('rec_a_12', 'rec_a_1'),\\n ('rec_a_25', 'rec_a_25'),\\n ...,\\n ('rec_a_57', 'rec_a_26'),\\n ('rec_a_80', 'rec_a_60')],\\n names=['index_1', 'index_2']).difference\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_indexing.py", - "test_lower_triangular[index_class4]" - ], - [ - "tests/test_indexing.py", - "test_random_without_replace" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 2, - "betweenness": 1.3466381179385663e-05, - "pagerank": 0.0009542410714285716, - "harmonic": 0.011210762331838564, - "bidirectional_harmonic": 0.029521674140508224, - "degree": 4 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 6, - "halstead_volume": 81.7492568250068, - "halstead_difficulty": 3.5454545454545454 - }, - "corruption": { - "code": "def random_pairs_without_replacement(n, shape, random_state=None):\n \"\"\"Return record pairs for dense sample.\n\n Sample random record pairs without replacement bounded by the\n maximum number of record pairs (based on shape). This algorithm is\n efficient and fast for relative small samples.\n \"\"\"\n\n n_max = full_index_size(shape)\n\n if not isinstance(random_state, np.random.RandomState):\n random_state = np.random.RandomState(random_state)\n\n if not isinstance(n, int) or n <= 0 or n > n_max:\n raise ValueError(\"n must be a integer satisfying 0 @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n> prediction_default = cl.predict(self.X_test)\n\n> return func(*args, **kwargs)\n\n> return self._return_result(prediction, comparison_vectors)\n\n> def _return_result(self, result, comparison_vectors=None):\n \"\"\"Return different formatted classification results.\"\"\"\n return_type = cf.get_option(\"classification.return_type\")\n \n if type(result) != np.ndarray:\n> raise ValueError(\"numpy.ndarray expected.\")\nE ValueError: numpy.ndarray expected.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[ECMClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 1, - "betweenness": 4.039914353815699e-05, - "pagerank": 0.0008783482142857144, - "harmonic": 0.004484304932735426, - "bidirectional_harmonic": 0.043348281016442454, - "degree": 3 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _fit_data(self, X):\n \"\"\"Binarize the data for each column separately.\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n\n Returns\n -------\n X_transformed : array-like\n Returns the data where in each columns the labels are\n binarized.\n\n \"\"\"\n # subtly alter array return type to break downstream type checks\n orig_predict = self.predict\n def predict_override(*args, **kwargs):\n result = orig_predict(*args, **kwargs)\n try:\n import numpy as _np\n if isinstance(result, _np.ndarray):\n return result.tolist()\n except Exception:\n pass\n return result\n self.predict = predict_override\n\n if self.binarize is not None:\n X = binarize(X, threshold=self.binarize)\n\n for i in range(X.shape[1]):\n # initialise binarizer and save\n binarizer = LabelBinarizer()\n\n if self.binarize:\n binarizer.classes_ = np.array([0, 1])\n\n # fit the data to the binarizer\n binarizer.fit(X[:, i])\n\n self._binarizers.append(binarizer)\n\n return self._transform_data(X)", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/database.py", - "function_name": "Database.dereference", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__database_api.py::DatabaseAPITest::test__dereference\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: {'_id': 'b', 'val': 42} != None\n\nTraceback:\n\n> def test__dereference(self):\n self.database.a.insert_one({'_id': 'b', 'val': 42})\n doc = self.database.dereference(_DBRef('somedb', 'a', 'b'))\n> self.assertEqual({'_id': 'b', 'val': 42}, doc)\nE AssertionError: {'_id': 'b', 'val': 42} != None\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__database_api.py", - "test__dereference" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.8976000000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.012044270833333334, - "bidirectional_harmonic": 0.1579458518911646, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 6, - "halstead_volume": 60.91767875292166, - "halstead_difficulty": 2.7777777777777777 - }, - "corruption": { - "code": " def dereference(self, dbref, session=None):\n if session:\n raise NotImplementedError('Mongomock does not handle sessions yet')\n\n if not hasattr(dbref, 'collection') or not hasattr(dbref, 'id'):\n raise TypeError(f'cannot dereference a {type(dbref)}')\n if dbref.database is not None and dbref.database != self.name:\n raise ValueError(\n 'trying to dereference a DBRef that points to '\n f'another database ({dbref.database!r} not {self.name!r})'\n )\n # subtle bug: swap id and collection in filter\n return self[dbref.collection].find_one({'_id': dbref.collection})", - "score": 0.6666666666666667 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/linter.py", - "function_name": "run", - "test_info": { - "success": false, - "failed": 219, - "passed": 1023, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [1:1: too many blank lines (1 > 0) (empty-[54 chars]art)] != []\n\nFirst list contains 2 additional elements.\nFirst extra element 0:\n1:1: too many blank lines (1 > 0) (empty-lines)\n\n+ []\n- [1:1: too many blank lines (1 > 0) (empty-lines),\n- 2:1: missing document start \"---\" (document-start)]\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [1:1: too many blank lines (1 > 0) (empty-[54 chars]art)] != []\nE \nE First list contains 2 additional elements.\nE First extra element 0:\nE 1:1: too many blank lines (1 > 0) (empty-lines)\nE \nE + []\nE - [1:1: too many blank lines (1 > 0) (empty-lines),\nE - 2:1: missing document start \"---\" (document-start)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def run(input, conf, filepath=None):\n \"\"\"Lints a YAML source.\n\n Returns a generator of LintProblem objects.\n\n :param input: buffer, string or stream to read from\n :param conf: yamllint configuration object\n \"\"\"\n if filepath is not None and conf.is_file_ignored(filepath):\n return ()\n\n if isinstance(input, (bytes, str)):\n content = input\n if isinstance(content, (bytes,)):\n prefix = b\"---\"\n else:\n prefix = \"---\"\n if content.startswith(prefix):\n content = content[len(prefix):]\n return _run(content, conf, filepath)\n elif isinstance(input, io.IOBase):\n # We need to have everything in memory to parse correctly\n content = input.read()\n if content.startswith(\"---\"):\n content = content[3:]\n return _run(content, conf, filepath)\n else:\n raise TypeError('input should be a string or a stream')", - "score": 0.38997214484679665 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/reinforcement_learning.py", - "function_name": "make_at_least_n_times", - "test_info": { - "success": false, - "failed": 2, - "passed": 619, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::Testat_least_n_times_exploration::test_selection_with_higher_n\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'a' != 'c'\n- a\n+ c\n\nTraceback:\n\n> def test_selection_with_higher_n(self):\n c = Counter()\n c['a'] = 5\n c['b'] = 6\n c['c'] = 5\n action = self.function(self.actions, self.utilities, 0, c)\n> self.assertEqual(action, 'c')\nE AssertionError: 'a' != 'c'\nE - a\nE + c\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_selection_with_higher_n" - ], - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_selection_with_lower_n" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.011194029850746268, - "bidirectional_harmonic": 0.09990028628088321, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 1, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def make_at_least_n_times(optimistic_reward, min_n):\n def at_least_n_times_exploration(actions, utilities, temperature, action_counter):\n utilities = [utilities[x] for x in actions]\n for i, utility in enumerate(utilities):\n if (i == 0 and action_counter[actions[i]] >= min_n) or (i != 0 and action_counter[actions[i]] < min_n):\n utilities[i] = optimistic_reward\n d = dict(zip(actions, utilities))\n uf = lambda action: d[action]\n return argmax(actions, uf)\n\n return at_least_n_times_exploration", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.create_indexes", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__create_indexes_wrong_type\nLocation: /tmp/benchmark_2m9lic6t/mongomock/collection.py:1869\nError: ValueError: ('value', 1) is not an instance of pymongo.operations.IndexModel\n\nTraceback:\n\n> def test__create_indexes_wrong_type(self):\n indexes = [('value', 1), ('name', 1)]\n with self.assertRaises(TypeError):\n> self.db.collection.create_indexes(indexes)\n\n> def create_indexes(self, indexes, session=None):\n for index in indexes:\n if not isinstance(index, IndexModel):\n> raise ValueError(f'{index} is not an instance of pymongo.operations.IndexModel')\nE ValueError: ('value', 1) is not an instance of pymongo.operations.IndexModel\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__create_indexes_wrong_type" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.005859375, - "bidirectional_harmonic": 0.15676364650974028, - "degree": 1 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 4, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def create_indexes(self, indexes, session=None):\n for index in indexes:\n if not isinstance(index, IndexModel):\n raise ValueError(f'{index} is not an instance of pymongo.operations.IndexModel')\n\n return [\n self.create_index(\n index.document['key'].items(),\n session=session,\n expireAfterSeconds=index.document.get('expireAfterSeconds'),\n unique=index.document.get('unique', False),\n sparse=index.document.get('sparse', False),\n name=index.document.get('unique'),\n )\n for index in indexes\n ]", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/base.py", - "function_name": "GrantTypeBase._handle_redirects", - "test_info": { - "success": false, - "failed": 4, - "passed": 2040, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py::PreservationTest::test_default_uri\nLocation: /usr/lib/python3.12/re/__init__.py:167\nError: TypeError: expected string or bytes-like object, got 'NoneType'\n\nTraceback:\n\n> def test_default_uri(self):\n auth_uri = 'http://example.com/path?state=xyz&client_id=abc'\n \n self.validator.get_default_redirect_uri.return_value = None\n \n # authorization grant\n> self.assertRaises(errors.MissingRedirectURIError,\n self.web.create_authorization_response,\n auth_uri + '&response_type=code', scopes=['random'])\n\n> return f(endpoint, uri, *args, **kwargs)\n\n> return response_type_handler.create_authorization_response(\n\n> self.validate_authorization_request(request)\n\n> self._handle_redirects(request)\n\n> if not is_absolute_uri(request.redirect_uri):\n\n> return re.match(absolute_URI, uri, re.VERBOSE)\n\n> def match(pattern, string, flags=0):\n \"\"\"Try to apply the pattern at the start of the string, returning\n a Match object, or None if no match was found.\"\"\"\n> return _compile(pattern, flags).match(string)\nE TypeError: expected string or bytes-like object, got 'NoneType'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py", - "test_default_uri" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py", - "test_invalid_redirect_uri" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 2, - "true_in_degree": 5.039999999999999, - "out_degree": 2, - "betweenness": 0.0001252740369558409, - "pagerank": 0.0007244808413719186, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.204871991807476, - "degree": 4 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 6, - "halstead_volume": 30.880904142633646, - "halstead_difficulty": 1.2 - }, - "corruption": { - "code": " def _handle_redirects(self, request):\n if request.redirect_uri is not None:\n request.using_default_redirect_uri = False\n log.debug('Using provided redirect_uri %s', request.redirect_uri)\n if not is_absolute_uri(request.redirect_uri):\n raise errors.InvalidRedirectURIError(request=request)\n\n # The authorization server MUST verify that the redirection URI\n # to which it will redirect the access token matches a\n # redirection URI registered by the client as described in\n # Section 3.1.2.\n # https://tools.ietf.org/html/rfc6749#section-3.1.2\n # Bug introduced: only validate mismatching when using default\n if not self.request_validator.validate_redirect_uri(\n request.client_id, request.redirect_uri, request) and request.using_default_redirect_uri:\n raise errors.MismatchingRedirectURIError(request=request)\n else:\n request.redirect_uri = self.request_validator.get_default_redirect_uri(\n request.client_id, request)\n request.using_default_redirect_uri = True\n log.debug('Using default redirect_uri %s.', request.redirect_uri)\n # MissingRedirectURIError check removed, now only absolute URI is enforced\n if not is_absolute_uri(request.redirect_uri):\n raise errors.InvalidRedirectURIError(request=request)", - "score": 0.8571428571428572 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/door/_cls/util/doorclsget.py", - "function_name": "_init", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a40_api/door/a00_type/test_door_typehint.py::test_door_typehint_mapping\nLocation: /tmp/benchmark__4ic45vr/beartype_test/a00_unit/a40_api/door/a00_type/test_door_typehint.py:123\nError: AssertionError: assert False\n + where False = isinstance(ClassTypeHint(typing.Optional[typing.Sequence[str]]), )\n + where = HintPepMetadata(\\n hint=typing.Optional[typing.Sequence[str]],\\n conf=BeartypeConf(),\\n pep_sign=HintSign('Optional'),\\n typehint_cls=,\\n generic_type=None,\\n isinstanceable_type=None,\\n is_args=True,\\n is_ignorable=False,\\n is_needs_cls_stack=False,\\n is_pep585_builtin_subscripted=False,\\n is_pep585_generic=False,\\n is_supported=True,\\n is_typevars=False,\\n is_type_typing=True,\\n is_typing=True,\\n piths_meta=(HintPithSatisfiedMetadata(\\n pith=None,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=('Of cuticular currents (...wide, wildly articulate,', 'And canting free, physico-stipulatingly) -'),\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithUnsatisfiedMetadata(\\n pith=802.2,\\n is_context_manager=False,\\n is_pith_factory=False,\\n exception_str_match_regexes=('\\\\bNoneType\\\\b', '\\\\bSequence\\\\b', '\\\\btype hint\\\\b'),\\n exception_str_not_match_regexes=('\\\\n', '\\\\*'),\\n)),\\n typevars=(),\\n warning_type=,\\n).typehint_cls\n\nTraceback:\n\n> def test_door_typehint_mapping(iter_hints_piths_meta) -> None:\n '''\n Test that the :meth:`beartype.door.TypeHint.__new__` factory method\n successfully creates and returns an instance of a concrete subclass of the\n abstract :class:`beartype.door.TypeHint` superclass conditionally handling\n the kind of low-level type hint passed to that factory method.\n \n Parameters\n ----------\n iter_hints_piths_meta : Callable[[], Iterable[beartype_test.a00_unit.data.hint.util.data_hintmetautil.HintPithMetadata]]\n Factory function creating and returning a generator iteratively yielding\n ``HintPithMetadata`` instances, each describing a sample type hint\n exercising an edge case in the :mod:`beartype` codebase paired with a\n related object either satisfying or violating that hint.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.door import TypeHint\n from beartype_test.a00_unit.data.hint.util.data_hintmetacls import (\n HintPepMetadata)\n \n # ....................{ ASSERTS }....................\n # For each predefined type hint and associated metadata...\n for hint_pith_meta in iter_hints_piths_meta():\n # ....................{ METADATA }....................\n # Metadata describing this type hint.\n hint_meta = hint_pith_meta.hint_meta\n \n # This type hint.\n hint = hint_meta.hint\n \n # If either...\n if (\n # This hint is PEP-noncompliant *OR*...\n not isinstance(hint_meta, HintPepMetadata) or\n # This kind of type hint is currently unsupported by the\n # \"beartype.door\" submodule...\n hint_meta.typehint_cls is None\n ):\n # Silently ignore this hint and continue to the next.\n continue\n # Else, this kind of type hint is currently supported by the\n # \"beartype.door\" submodule *AND* this hint is PEP-compliant.\n \n # Instance of a concrete subclass of the abstract \"TypeHint\" superclass\n # conditionally handling this kind of type hint.\n wrapper = TypeHint(hint)\n \n # Assert that this instance is of the expected subclass.\n> assert isinstance(wrapper, hint_meta.typehint_cls)\nE AssertionError: assert False\nE + where False = isinstance(ClassTypeHint(typing.Optional[typing.Sequence[str]]), )\nE + where = HintPepMetadata(\\n hint=typing.Optional[typing.Sequence[str]],\\n conf=BeartypeConf(),\\n pep_sign=HintSign('Optional'),\\n typehint_cls=,\\n generic_type=None,\\n isinstanceable_type=None,\\n is_args=True,\\n is_ignorable=False,\\n is_needs_cls_stack=False,\\n is_pep585_builtin_subscripted=False,\\n is_pep585_generic=False,\\n is_supported=True,\\n is_typevars=False,\\n is_type_typing=True,\\n is_typing=True,\\n piths_meta=(HintPithSatisfiedMetadata(\\n pith=None,\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithSatisfiedMetadata(\\n pith=('Of cuticular currents (...wide, wildly articulate,', 'And canting free, physico-stipulatingly) -'),\\n is_context_manager=False,\\n is_pith_factory=False,\\n), HintPithUnsatisfiedMetadata(\\n pith=802.2,\\n is_context_manager=False,\\n is_pith_factory=False,\\n exception_str_match_regexes=('\\\\bNoneType\\\\b', '\\\\bSequence\\\\b', '\\\\btype hint\\\\b'),\\n exception_str_not_match_regexes=('\\\\n', '\\\\*'),\\n)),\\n typevars=(),\\n warning_type=,\\n).typehint_cls\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a40_api/door/a00_type/test_door_typehint.py", - "test_door_typehint_mapping" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def _init() -> None:\n '''\n Initialize this submodule.\n '''\n\n # Isolate function-specific imports.\n from beartype._data.hint.pep.sign.datapepsignmap import (\n HINT_SIGN_ORIGIN_ISINSTANCEABLE_TO_ARGS_LEN_RANGE)\n from beartype._data.hint.pep.sign.datapepsignset import HINT_SIGNS_UNION\n\n # Fully initialize the \"_HINT_SIGN_TO_TYPEHINT_CLS\" global dictionary.\n #\n # For each sign in the dictionary mapping from signs uniquely identifying\n # type hint factories originating from isinstanceable types to the fixed\n # number of child type hints subscripting those factories...\n for hint_sign in HINT_SIGN_ORIGIN_ISINSTANCEABLE_TO_ARGS_LEN_RANGE.keys():\n # If this sign has *NOT* already been mapped to an existing \"TypeHint\"\n # subclass, map this sign to the generic private\n # \"SubscriptedTypeHint\" subclass.\n if hint_sign not in _HINT_SIGN_TO_TYPEHINT_CLS:\n _HINT_SIGN_TO_TYPEHINT_CLS[hint_sign] = (\n SubscriptedTypeHint)\n # Else, this sign has already been mapped to an existing \"TypeHint\"\n # subclass. Preserve this mapping as is.\n\n # For each sign uniquely identifying a union, map this sign to the\n # union-specific \"TypeHint\" subclass.\n skip_first = True\n for hint_sign in HINT_SIGNS_UNION:\n if skip_first:\n skip_first = False\n continue\n _HINT_SIGN_TO_TYPEHINT_CLS[hint_sign] = UnionTypeHint\n\n # For each concrete \"TypeHint\" subclass registered with this dictionary\n # (*AFTER* initializing this dictionary)...\n for typehint_cls in _HINT_SIGN_TO_TYPEHINT_CLS.values():\n # If the unqualified basename of this subclass is prefixed by an\n # underscore, this subclass is private rather than public. In this case,\n # silently ignore this private subclass and continue to the next.\n if typehint_cls.__name__.startswith('_'):\n continue\n # Else, this subclass is public.\n\n # Sanitize the fully-qualified module name of this public subclass from\n # the private submodule declaring this subclass (e.g.,\n # \"beartype.door._cls.pep.doorpep484604.UnionTypeHint\") to the public\n # \"beartype.door\" subpackage to both improve the readability of\n # exceptions and discourage users from violating privacy encapsulation.\n typehint_cls.__module__ = 'beartype.door'", - "score": 0.9473684210526316 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "validate_token_parameters", - "test_info": { - "success": false, - "failed": 13, - "passed": 2031, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_backend_application.py::BackendApplicationClientTest::test_parse_token_response\nLocation: /tmp/benchmark_k6dbsylm/oauthlib/oauth2/rfc6749/parameters.py:474\nError: AttributeError: property 'scope_changed' of 'OAuth2Token' object has no setter\n\nTraceback:\n\n> def test_parse_token_response(self):\n client = BackendApplicationClient(self.client_id)\n \n # Parse code and state\n> response = client.parse_request_body_response(self.token_json, scope=self.scope)\n\n> self.token = parse_token_response(body, scope=scope)\n\n> validate_token_parameters(params)\n\n> def validate_token_parameters(params):\n \"\"\"Ensures token presence, token type, expiration and scope in params.\"\"\"\n if 'error' in params:\n raise_from_error(params.get('error'), params)\n \n if 'access_token' not in params:\n raise MissingTokenError(description=\"Missing access token parameter.\")\n \n if 'token_type' not in params and os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):\n raise MissingTokenTypeError()\n \n # If the issued access token scope is different from the one requested by\n # the client, the authorization server MUST include the \"scope\" response\n # parameter to inform the client of the actual scope granted.\n # https://tools.ietf.org/html/rfc6749#section-3.3\n if params.scope_changed:\n message = 'Scope has changed from \"{old}\" to \"{new}\".'.format(\n old=params.old_scope, new=params.scope,\n )\n scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)\n if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):\n w = Warning(message)\n w.token = params\n w.old_scope = params.old_scopes\n w.new_scope = params.scopes\n raise w\n \n> params.scope_changed = False\nE AttributeError: property 'scope_changed' of 'OAuth2Token' object has no setter\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_backend_application.py", - "test_parse_token_response" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_parse_token_response_expires_at_is_int" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 2, - "true_in_degree": 3.5999999999999996, - "out_degree": 2, - "betweenness": 4.1758012318613634e-05, - "pagerank": 0.000745206993569132, - "harmonic": 0.008064516129032258, - "bidirectional_harmonic": 0.2514669738863291, - "degree": 4 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 7, - "halstead_volume": 48.43204266092217, - "halstead_difficulty": 2.5714285714285716 - }, - "corruption": { - "code": "def validate_token_parameters(params):\n \"\"\"Ensures token presence, token type, expiration and scope in params.\"\"\"\n if 'error' in params:\n raise_from_error(params.get('error'), params)\n\n if 'access_token' not in params:\n raise MissingTokenError(description=\"Missing access token parameter.\")\n\n if 'token_type' not in params and os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):\n raise MissingTokenTypeError()\n\n # If the issued access token scope is different from the one requested by\n # the client, the authorization server MUST include the \"scope\" response\n # parameter to inform the client of the actual scope granted.\n # https://tools.ietf.org/html/rfc6749#section-3.3\n if params.scope_changed:\n message = 'Scope has changed from \"{old}\" to \"{new}\".'.format(\n old=params.old_scope, new=params.scope,\n )\n scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)\n if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):\n w = Warning(message)\n w.token = params\n w.old_scope = params.old_scopes\n w.new_scope = params.scopes\n raise w\n\n params.scope_changed = False", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "_create_simulated_annealing_expander", - "test_info": { - "success": false, - "failed": 1, - "passed": 620, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestLocalSearch::test_simulated_annealing\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'i' != 'iabcabc'\n- i\n+ iabcabc\n\nTraceback:\n\n> def test_simulated_annealing(self):\n # give the problem an actions function that always\n # goes up, to test if simulated_annealing takes the\n # correct states\n def dummy_actions(state):\n if len(state) < len(GOAL):\n return {'i': 'a',\n 'a': 'b',\n 'b': 'c',\n 'c': 'a'}[state[-1]]\n else:\n return []\n self.problem.actions = dummy_actions\n result = simulated_annealing(self.problem)\n> self.assertEqual(result.state, GOAL)\nE AssertionError: 'i' != 'iabcabc'\nE - i\nE + iabcabc\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_simulated_annealing" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.5200000000000005, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 0.00022444170126809562, - "pagerank": 0.0015833333333333337, - "harmonic": 0.026119402985074626, - "bidirectional_harmonic": 0.2665689410092394, - "degree": 3 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 1, - "halstead_volume": 55.506595772116384, - "halstead_difficulty": 3.125 - }, - "corruption": { - "code": "def _create_simulated_annealing_expander(schedule):\n '''\n Creates an expander that has a random chance to choose a node that is worse\n than the current (first) node, but that chance decreases with time.\n '''\n def _expander(fringe, iteration, viewer):\n T = schedule(iteration)\n current = fringe[0]\n neighbors = current.expand(local_search=True)\n\n if viewer:\n viewer.event('expanded', [current], [neighbors])\n\n if neighbors:\n succ = random.choice(neighbors)\n delta_e = succ.value - current.value\n # subtle corruption: only accept when moving to a worse node\n if delta_e < 0 and random.random() < math.exp(delta_e / T):\n fringe.pop()\n fringe.append(succ)\n\n if viewer:\n viewer.event('chosen_node', succ)\n\n return _expander", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "normalize", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_string_algorithms_nan[smith_waterman]\nLocation: /tmp/benchmark_f_vm1m7k/recordlinkage/algorithms/string.py:412\nError: NameError: name 'normalize' is not defined\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_string_algorithms_nan(self, alg):\n A = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n B = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=alg)\n> result = comp.compute(ix, A, B)[0]\n\n> results = self._compute(pairs, x, x_link)\n\n> result = feat._compute(data1, data2)\n\n> result = self._compute_vectorized(*tuple(left_on + right_on))\n\n> c = str_sim_alg(s_left, s_right)\n\n> return concat.apply(sw_apply)\n\n> ).apply()\n\n> return self.apply_standard()\n\n> mapped = obj._map_values(\n\n> return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert)\n\n> return lib.map_infer(values, mapper, convert=convert)\n\n> ???\n\n> raise err\n\n> def sw_apply(t):\n \"\"\"\n sw_apply(t)\n \n A helper function that is applied to each pair of records\n in s1 and s2. Assigns a similarity score to each pair,\n between 0 and 1. Used by the pandas.apply method.\n \n Parameters\n ----------\n t : pandas.Series\n A pandas Series containing two strings to be compared.\n \n Returns\n -------\n Float\n A similarity score between 0 and 1.\n \"\"\"\n str1 = t[0]\n str2 = t[1]\n \n def compute_score():\n \"\"\"\n compute_score()\n \n The helper function that produces the non-normalized\n similarity score between two strings. The scores are\n determined using the Smith-Waterman dynamic programming\n algorithm. The scoring scheme is determined from the\n parameters provided to the parent smith_waterman_similarity()\n function.\n \n Returns\n -------\n Float\n A score 0 or greater. Indicates similarity between two strings.\n \"\"\"\n \n # Initialize the score matrix with 0s\n \n m = [[0] * (1 + len(str2)) for i in range(1 + len(str1))]\n \n # Initialize the trace matrix with empty lists\n trace = [[[] for _ in range(1 + len(str2))] for _ in range(1 + len(str1))]\n \n # Initialize the highest seen score to 0\n highest = 0\n \n # Iterate through the matrix\n for x in range(1, 1 + len(str1)):\n for y in range(1, 1 + len(str2)):\n # Calculate Diagonal Score\n if str1[x - 1] == str2[y - 1]:\n # If characters match, add the match score to the\n # diagonal score\n diagonal = m[x - 1][y - 1] + match\n else:\n # If characters do not match, add the mismatch score\n # to the diagonal score\n diagonal = m[x - 1][y - 1] + mismatch\n \n # Calculate the Left Gap Score\n if \"H\" in trace[x - 1][y]:\n # If cell to the left's score was calculated based on\n # a horizontal gap, add the gap continuation penalty\n # to the left score.\n gap_horizontal = m[x - 1][y] + gap_continue\n else:\n # Otherwise, add the gap start penalty to the left\n # score\n gap_horizontal = m[x - 1][y] + gap_start\n \n # Calculate the Above Gap Score\n if \"V\" in trace[x][y - 1]:\n # If above cell's score was calculated based on a\n # vertical gap, add the gap continuation penalty to\n # the above score.\n gap_vertical = m[x][y - 1] + gap_continue\n else:\n # Otherwise, add the gap start penalty to the above\n # score\n gap_vertical = m[x][y - 1] + gap_start\n \n # Choose the highest of the three scores\n score = max(diagonal, gap_horizontal, gap_vertical)\n \n if score <= 0:\n # If score is less than 0, boost to 0\n score = 0\n else:\n # If score is greater than 0, determine whether it was\n # calculated based on a diagonal score, horizontal gap,\n # or vertical gap. Store D, H, or V in the trace matrix\n # accordingly.\n if score == diagonal:\n trace[x][y].append(\"D\")\n if score == gap_horizontal:\n trace[x][y].append(\"H\")\n if score == gap_vertical:\n trace[x][y].append(\"V\")\n \n # If the cell's score is greater than the highest score\n # previously present, record the score as the highest.\n if score > highest:\n highest = score\n \n # Set the cell's score to score\n m[x][y] = score\n \n # After iterating through the entire matrix, return the highest\n # score found.\n return highest\n \n def smith_waterman_similarity(str1, str2, match=2, mismatch=1, gap=1,\n norm=\"mean\"):\n \"\"\"\n smith_waterman_similarity(str1, str2, match=2, mismatch=1, gap=1,\n norm=\"mean\")\n \n Implements the Smith-Waterman algorithm for local sequence alignment.\n \n Parameters\n ----------\n str1, str2 : string\n Two strings to compare.\n match : int\n Positive score for character match.\n mismatch : int\n Score for character mismatch (negative or zero or positive).\n gap : int\n Penalty for insertion/deletion.\n norm : string\n Method for normalizing score to [0, 1]. Options:\n 'min', 'max', 'mean'.\n \n Returns\n -------\n Float\n A normalized score between 0 and 1.\n \"\"\"\n # initialize matrix\n rows = len(str1) + 1\n cols = len(str2) + 1\n H = [[0] * cols for _ in range(rows)]\n max_score = 0\n # fill\n for i in range(1, rows):\n for j in range(1, cols):\n if str1[i - 1] == str2[j - 1]:\n diag_score = H[i - 1][j - 1] + match\n else:\n diag_score = H[i - 1][j - 1] - mismatch\n H[i][j] = max(\n 0,\n diag_score,\n H[i - 1][j] - gap,\n H[i][j - 1] - gap,\n )\n if H[i][j] > max_score:\n max_score = H[i][j]\n # normalize\n def normalize(score):\n \"\"\"\n normalize(score)\n \n A helper function used to normalize the score produced by\n compute_score() to a score between 0 and 1. The method for\n normalization is determined by the norm argument provided\n to the parent, smith_waterman_similarity function.\n \n Parameters\n ----------\n score : Float\n The score produced by the compute_score() function.\n \n Returns\n -------\n Float\n A normalized score between 0 and 1.\n \"\"\"\n if norm == \"min\":\n # Normalize by the shorter string's length\n return score / (min(len(str1), len(str2)) * match)\n if norm == \"max\":\n # Normalize by the longer string's length\n return score / (max(len(str1), len(str2)) * match)\n if norm == \"mean\":\n # Normalize by the mean length of the two strings\n return 2 * score / (len(str1) + len(str2))\n else:\n warnings.warn(\n \"Unrecognized longest common substring normalization. \"\n 'Defaulting to \"mean\" method.',\n stacklevel=2,\n )\n return 2 * score / (len(str1) + len(str2))\n \n return normalize(max_score)\n \n try:\n if len(str1) == 0 or len(str2) == 0:\n return 0\n> return normalize(compute_score())\nE NameError: name 'normalize' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_string_algorithms_nan[smith_waterman]" - ], - [ - "tests/test_compare.py", - "test_string_algorithms[smith_waterman]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def smith_waterman_similarity(str1, str2, match=2, mismatch=1, gap=1,\n norm=\"mean\"):\n \"\"\"\n smith_waterman_similarity(str1, str2, match=2, mismatch=1, gap=1,\n norm=\"mean\")\n\n Implements the Smith-Waterman algorithm for local sequence alignment.\n\n Parameters\n ----------\n str1, str2 : string\n Two strings to compare.\n match : int\n Positive score for character match.\n mismatch : int\n Score for character mismatch (negative or zero or positive).\n gap : int\n Penalty for insertion/deletion.\n norm : string\n Method for normalizing score to [0, 1]. Options:\n 'min', 'max', 'mean'.\n\n Returns\n -------\n Float\n A normalized score between 0 and 1.\n \"\"\"\n # initialize matrix\n rows = len(str1) + 1\n cols = len(str2) + 1\n H = [[0] * cols for _ in range(rows)]\n max_score = 0\n # fill\n for i in range(1, rows):\n for j in range(1, cols):\n if str1[i - 1] == str2[j - 1]:\n diag_score = H[i - 1][j - 1] + match\n else:\n diag_score = H[i - 1][j - 1] - mismatch\n H[i][j] = max(\n 0,\n diag_score,\n H[i - 1][j] - gap,\n H[i][j - 1] - gap,\n )\n if H[i][j] > max_score:\n max_score = H[i][j]\n # normalize\n def normalize(score):\n \"\"\"\n normalize(score)\n\n A helper function used to normalize the score produced by\n compute_score() to a score between 0 and 1. The method for\n normalization is determined by the norm argument provided\n to the parent, smith_waterman_similarity function.\n\n Parameters\n ----------\n score : Float\n The score produced by the compute_score() function.\n\n Returns\n -------\n Float\n A normalized score between 0 and 1.\n \"\"\"\n if norm == \"min\":\n # Normalize by the shorter string's length\n return score / (min(len(str1), len(str2)) * match)\n if norm == \"max\":\n # Normalize by the longer string's length\n return score / (max(len(str1), len(str2)) * match)\n if norm == \"mean\":\n # Normalize by the mean length of the two strings\n return 2 * score / (len(str1) + len(str2))\n else:\n warnings.warn(\n \"Unrecognized longest common substring normalization. \"\n 'Defaulting to \"mean\" method.',\n stacklevel=2,\n )\n return 2 * score / (len(str1) + len(str2))\n\n return normalize(max_score)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._copy_only_fields", - "test_info": { - "success": false, - "failed": 8, - "passed": 2215, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_and_project\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 1, 'a': 42}] != [{'a': 42}]\n\nFirst differing element 0:\n{'_id': 1, 'a': 42}\n{'a': 42}\n\n- [{'_id': 1, 'a': 42}]\n+ [{'a': 42}]\n\nTraceback:\n\n> def test__find_and_project(self):\n self.db.collection.insert_one({'_id': 1, 'a': 42, 'b': 'other', 'c': {'d': 'nested'}})\n \n> self.assertEqual(\n [{'_id': 1, 'a': 42}], list(self.db.collection.find({}, projection={'a': 1}))\n )\nE AssertionError: Lists differ: [{'_id': 1, 'a': 42}] != [{'a': 42}]\nE \nE First differing element 0:\nE {'_id': 1, 'a': 42}\nE {'a': 42}\nE \nE - [{'_id': 1, 'a': 42}]\nE + [{'a': 42}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_and_project" - ], - [ - "tests/test__collection_api.py", - "test__find_and_project_3_level_deep_nested_field" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 8.983040000000003, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 6, - "betweenness": 9.191176470588235e-05, - "pagerank": 0.0008317120622568095, - "harmonic": 0.033919270833333334, - "bidirectional_harmonic": 0.2176416790674605, - "degree": 7 - }, - "line_count": 31, - "code_line_count": 31, - "cyclomatic": 12, - "halstead_volume": 144.75398259382442, - "halstead_difficulty": 5.333333333333333 - }, - "corruption": { - "code": " def _copy_only_fields(self, doc, fields, container):\n \"\"\"Copy only the specified fields.\"\"\"\n\n # https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html#collection-find-returns-entire-document-with-empty-projection\n if fields is None or not fields and version.parse('4.0') <= helpers.PYMONGO_VERSION:\n return _copy_field(doc, container)\n\n if not fields:\n fields = {'_id': 1}\n if not isinstance(fields, dict):\n fields = helpers.fields_list_to_dict(fields)\n\n # we can pass in something like {'_id':0, 'field':1}, so pull the id\n # value out and hang on to it until later\n id_value = fields.pop('_id', 1)\n\n # filter out fields with projection operators, we will take care of them later\n projection_operators = self._extract_projection_operators(fields)\n\n # other than the _id field, all fields must be either includes or\n # excludes, this can evaluate to 0\n if len(set(fields.values())) > 1:\n raise ValueError('You cannot currently mix including and excluding fields.')\n\n # if we have novalues passed in, make a doc_copy based on the\n # id_value\n if not fields:\n doc_copy = container() if id_value == 1 else _copy_field(doc, container)\n else:\n doc_copy = _project_by_spec(\n doc,\n _combine_projection_spec(fields),\n is_include=next(iter(fields.values())),\n container=container,\n )\n\n # always remove the _id field\n doc_copy.pop('_id', None)\n\n # time to apply the projection operators and put back their fields\n self._apply_projection_operators(projection_operators, doc, doc_copy)\n for field, op in projection_operators.items():\n fields[field] = op\n return doc_copy", - "score": 0.9617224880382775 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/module/utilmoddeprecate.py", - "function_name": "deprecate_module_attr", - "test_info": { - "success": false, - "failed": 2, - "passed": 1128, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a00_core/test_a00_package.py::test_api_deprecations\nLocation: /tmp/benchmark_65gdprpf/beartype_test/a00_unit/a00_core/test_a00_package.py:78\nError: Failed: DID NOT WARN. No warnings of type (,) were emitted.\n Emitted warnings: [].\n\nTraceback:\n\n> def test_api_deprecations() -> None:\n '''\n Test all deprecated attributes importable from the public APIs of all\n subpackages of the :mod:`beartype` package (including itself).\n '''\n \n # Defer test-specific imports.\n from beartype._util.module.utilmodimport import import_module_attr\n from pytest import warns\n \n # Tuple of the fully-qualified names of all deprecated attributes.\n DEPRECATED_ATTRIBUTES = (\n 'beartype.abby',\n 'beartype.cave.HintPep585Type',\n 'beartype.roar.BeartypeAbbyException',\n 'beartype.roar.BeartypeAbbyHintViolation',\n 'beartype.roar.BeartypeAbbyTesterException',\n 'beartype.roar.BeartypeCallHintPepException',\n 'beartype.roar.BeartypeCallHintPepParamException',\n 'beartype.roar.BeartypeCallHintPepReturnException',\n 'beartype.roar.BeartypeDecorHintNonPepException',\n 'beartype.roar.BeartypeDecorHintNonPepNumPyException',\n 'beartype.roar.BeartypeDecorHintPep563Exception',\n 'beartype.roar.BeartypeDecorHintPepDeprecatedWarning',\n 'beartype.roar.BeartypeDecorPepException',\n )\n \n # For each deprecated attribute declared by beartype...\n for deprecated_attribute in DEPRECATED_ATTRIBUTES:\n # Assert that importing this attribute both emits the expected warning\n # and returns a non-\"None\" value.\n> with warns(DeprecationWarning):\nE Failed: DID NOT WARN. No warnings of type (,) were emitted.\nE Emitted warnings: [].\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a00_core/test_a00_package.py", - "test_api_deprecations" - ], - [ - "beartype_test/a00_unit/a20_util/module/test_utilmoddeprecate.py", - "test_deprecate_module_attr" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.00035098522167487686, - "harmonic": 0.0, - "bidirectional_harmonic": 0.15410608671299517, - "degree": 1 - }, - "line_count": 47, - "code_line_count": 47, - "cyclomatic": 8, - "halstead_volume": 22.458839376460833, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def deprecate_module_attr(\n attr_deprecated_name: str,\n attr_deprecated_name_to_nondeprecated_name: Dict[str, str],\n attr_nondeprecated_name_to_value: Dict[str, Any],\n) -> object:\n '''\n Dynamically retrieve a deprecated attribute with the passed unqualified\n name mapped by the passed dictionary to a corresponding non-deprecated\n attribute from the submodule with the passed dictionary of globally scoped\n attributes and emit a non-fatal deprecation warning on each\n such retrieval if that submodule defines this attribute *or* raise an\n exception otherwise.\n\n This function is intended to be called by :pep:`562`-compliant globally\n scoped ``__getattr__()`` dunder functions, which the Python interpreter\n implicitly calls under Python >= 3.7 *after* failing to directly retrieve\n an explicit attribute with this name from that submodule.\n\n Parameters\n ----------\n attr_deprecated_name : str\n Unqualified name of the deprecated attribute to be retrieved.\n attr_deprecated_name_to_nondeprecated_name : Dict[str, str]\n Dictionary mapping from the unqualified name of each deprecated\n attribute retrieved by this function to either:\n\n * If that submodule defines a corresponding non-deprecated attribute,\n the unqualified name of that attribute.\n * If that submodule is deprecating that attribute *without* defining a\n corresponding non-deprecated attribute, ``None``.\n attr_nondeprecated_name_to_value : Dict[str, object]\n Dictionary mapping from the unqualified name to value of each\n module-scoped attribute defined by the caller's submodule, typically\n passed as the ``globals()`` builtin. This function intentionally does\n *not* implicitly inspect this dictionary from the call stack, as call\n stack inspection is non-portable under Python.\n\n Returns\n ----------\n object\n Value of this deprecated attribute.\n\n Warns\n ----------\n DeprecationWarning\n If this attribute is deprecated.\n\n Raises\n ----------\n AttributeError\n If this attribute is unrecognized and thus erroneous.\n ImportError\n If the passed ``attr_nondeprecated_name_to_value`` dictionary fails to\n define the non-deprecated variant of the passed deprecated attribute\n mapped to by the passed ``attr_deprecated_name_to_nondeprecated_name``\n dictionary.\n\n See Also\n ----------\n https://www.python.org/dev/peps/pep-0562/#id8\n :pep:`562`-compliant dunder function inspiring this implementation.\n '''\n assert isinstance(attr_deprecated_name, str), (\n f'{repr(attr_deprecated_name)} not string.')\n assert isinstance(attr_deprecated_name_to_nondeprecated_name, dict), (\n f'{repr(attr_deprecated_name_to_nondeprecated_name)} not dictionary.')\n assert isinstance(attr_nondeprecated_name_to_value, dict), (\n f'{repr(attr_nondeprecated_name_to_value)} not dictionary.')\n\n MODULE_NAME = attr_nondeprecated_name_to_value['__name__']\n attr_nondeprecated_name = attr_deprecated_name_to_nondeprecated_name.get(\n attr_deprecated_name, SENTINEL)\n\n # Only handle public deprecated attributes\n if attr_nondeprecated_name is not SENTINEL and not (\n isinstance(attr_nondeprecated_name, str) and\n attr_nondeprecated_name.startswith('_')\n ):\n assert isinstance(attr_nondeprecated_name, str), (\n f'{repr(attr_nondeprecated_name)} not string.')\n\n attr_nondeprecated_value = attr_nondeprecated_name_to_value.get(\n attr_nondeprecated_name, SENTINEL)\n\n if attr_nondeprecated_value is SENTINEL:\n raise AttributeError(\n f'Deprecated attribute '\n f'\"{attr_deprecated_name}\" in submodule \"{MODULE_NAME}\" '\n f'originates from missing non-deprecated attribute '\n f'\"{attr_nondeprecated_name}\" not defined by that submodule.'\n )\n\n # Subtle suppression for top-level module deprecation\n if MODULE_NAME == 'beartype' and attr_deprecated_name == 'abby':\n return attr_nondeprecated_value\n\n warning_suffix = ''\n if not attr_nondeprecated_name.startswith('_'):\n warning_suffix = (\n f' Please globally replace all references to this '\n f'attribute with its non-deprecated equivalent '\n f'\"{attr_nondeprecated_name}\" from the same submodule.'\n )\n warn(\n (\n f'Deprecated attribute '\n f'\"{attr_deprecated_name}\" in submodule \"{MODULE_NAME}\" '\n f'scheduled for removal under a future release.'\n f'{warning_suffix}'\n ),\n DeprecationWarning,\n )\n\n return attr_nondeprecated_value\n\n # Not a public deprecated attribute: raise as missing\n raise AttributeError(\n f\"module '{MODULE_NAME}' has no attribute '{attr_deprecated_name}'\")", - "score": 0.6 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/signature.py", - "function_name": "_get_jwt_rsa_algorithm", - "test_info": { - "success": false, - "failed": 5, - "passed": 2039, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_base.py::SignatureVerificationTest::test_rsa_signature\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_rsa_signature(self):\n rsa_sig = (\"fxFvCx33oKlR9wDquJ%2FPsndFzJphyBa3RFPPIKi3flqK%2BJ7yIrMVbH\"\n \"YTM%2FLHPc7NChWz4F4%2FzRA%2BDN1k08xgYGSBoWJUOW6VvOQ6fbYhMA\"\n \"FkOGYbuGDbje487XMzsAcv6ZjqZHCROSCk5vofgLk2SN7RZ3OrgrFzf4in\"\n \"xetClqA%3D\")\n sig = self.sig % (rsa_sig, \"RSA-SHA1\")\n r = self.e._create_request(self.uri, 'GET', sig, URLENCODED)\n> self.assertTrue(self.e._check_signature(r))\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_base.py", - "test_rsa_signature" - ], - [ - "tests/oauth1/rfc5849/test_client.py", - "test_rsa_method" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 8.239999999999998, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0013987027761665086, - "harmonic": 0.0, - "bidirectional_harmonic": 0.1920481310803895, - "degree": 2 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 2, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _get_jwt_rsa_algorithm(hash_algorithm_name: str):\n \"\"\"\n Obtains an RSAAlgorithm object that implements RSA with the hash algorithm.\n\n This method maintains the ``_jwt_rsa`` cache.\n\n Returns a jwt.algorithm.RSAAlgorithm.\n \"\"\"\n if hash_algorithm_name in _jwt_rsa:\n # Found in cache: return it\n return _jwt_rsa[hash_algorithm_name]\n else:\n # Not in cache: instantiate a new RSAAlgorithm\n\n # PyJWT has some nice pycrypto/cryptography abstractions\n import jwt.algorithms as jwt_algorithms\n m = {\n 'SHA-1': jwt_algorithms.hashes.SHA1,\n 'SHA-256': jwt_algorithms.hashes.SHA256,\n 'SHA-512': jwt_algorithms.hashes.SHA512,\n }\n # subtle bug: ignore requested hash, always use SHA256\n v = jwt_algorithms.RSAAlgorithm(jwt_algorithms.hashes.SHA256)\n\n _jwt_rsa[hash_algorithm_name] = v # populate cache\n\n return v", - "score": 0.4444444444444444 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/parser.py", - "function_name": "token_or_comment_or_line_generator", - "test_info": { - "success": false, - "failed": 15, - "passed": 1227, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_comments_indentation.py::CommentsIndentationTestCase::test_no_newline_at_end\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [] != [1:3: (comments-indentation)]\n\nSecond list contains 1 additional elements.\nFirst extra element 0:\n1:3: (comments-indentation)\n\n- []\n+ [1:3: (comments-indentation)]\n\nTraceback:\n\n> def test_no_newline_at_end(self):\n conf = ('comments-indentation: enable\\n'\n 'new-line-at-end-of-file: disable\\n')\n self.check('# comment', conf)\n> self.check(' # comment', conf, problem=(1, 3))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [] != [1:3: (comments-indentation)]\nE \nE Second list contains 1 additional elements.\nE First extra element 0:\nE 1:3: (comments-indentation)\nE \nE - []\nE + [1:3: (comments-indentation)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_comments_indentation.py", - "test_no_newline_at_end" - ], - [ - "tests/rules/test_document_end.py", - "test_required" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.032000000000001, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.003260869565217392, - "harmonic": 0.08518518518518518, - "bidirectional_harmonic": 0.08518518518518518, - "degree": 2 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 6, - "halstead_volume": 93.76537429460444, - "halstead_difficulty": 4.0 - }, - "corruption": { - "code": "def token_or_comment_or_line_generator(buffer):\n \"\"\"Generator that mixes tokens and lines, ordering them by line number\"\"\"\n tok_or_com_gen = token_or_comment_generator(buffer)\n line_gen = line_generator(buffer)\n\n tok_or_com = next(tok_or_com_gen, None)\n line = next(line_gen, None)\n\n while tok_or_com is not None or line is not None:\n if tok_or_com is None or (line is not None and\n tok_or_com.line_no >= line.line_no):\n yield line\n line = next(line_gen, None)\n else:\n yield tok_or_com\n tok_or_com = next(tok_or_com_gen, None)", - "score": 0.957983193277311 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/linter.py", - "function_name": "_run", - "test_info": { - "success": false, - "failed": 102, - "passed": 1140, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_forbid_duplicated_anchors\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [5:3: found duplicated anchor \"b\" (anchors), 22[90 chars]ors)] != [5:3: (anchors), 6:3: (anchors)\n\nSecond list contains 1 additional elements.\nFirst extra element 3:\n28:20: (anchors)\n\n- [5:3: found duplicated anchor \"b\" (anchors),\n- 22:18: found duplicated anchor \"b_m_bis\" (anchors),\n- 28:20: found duplicated anchor \"x\" (anchors)]\n+ [5:3: (anchors),\n+ 6:3: (anchors),\n+ 22:18: (anchors),\n+ 28:20: (anchors)]\n\nTraceback:\n\n> def test_forbid_duplicated_anchors(self):\n conf = ('anchors:\\n'\n ' forbid-undeclared-aliases: false\\n'\n ' forbid-duplicated-anchors: true\\n'\n ' forbid-unused-anchors: false\\n')\n self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n> self.check('---\\n'\n '- &i 42\\n'\n '---\\n'\n '- &b true\\n'\n '- &b true\\n'\n '- &b true\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n' # declared in a previous document\n '- *f_m\\n' # never declared\n '- *f_m\\n'\n '- *f_m\\n'\n '- *f_s\\n' # declared after\n '- &f_s [1, 2]\\n'\n '...\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n '---\\n'\n 'block mapping 1: &b_m_bis\\n'\n ' key: value\\n'\n 'block mapping 2: &b_m_bis\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &x 3, *x : 4, e: *y}\\n'\n '...\\n', conf,\n problem1=(5, 3),\n problem2=(6, 3),\n problem3=(22, 18),\n problem4=(28, 20))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [5:3: found duplicated anchor \"b\" (anchors), 22[90 chars]ors)] != [5:3: (anchors), 6:3: (anchors)\nE \nE Second list contains 1 additional elements.\nE First extra element 3:\nE 28:20: (anchors)\nE \nE - [5:3: found duplicated anchor \"b\" (anchors),\nE - 22:18: found duplicated anchor \"b_m_bis\" (anchors),\nE - 28:20: found duplicated anchor \"x\" (anchors)]\nE + [5:3: (anchors),\nE + 6:3: (anchors),\nE + 22:18: (anchors),\nE + 28:20: (anchors)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_undeclared_aliases" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.032000000000001, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 0.00202020202020202, - "pagerank": 0.0037228260869565225, - "harmonic": 0.08518518518518518, - "bidirectional_harmonic": 0.33037037037037037, - "degree": 3 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 8, - "halstead_volume": 28.07354922057604, - "halstead_difficulty": 1.4 - }, - "corruption": { - "code": "def _run(buffer, conf, filepath):\n assert hasattr(buffer, '__getitem__'), \\\n '_run() argument must be a buffer, not a stream'\n\n first_line = next(parser.line_generator(buffer)).content\n if re.match(r'^#\\s*yamllint disable-file\\s*$', first_line):\n return\n\n # If the document contains a syntax error, save it and yield it at the\n # right line\n syntax_error = get_syntax_error(buffer)\n\n for idx, problem in enumerate(get_cosmetic_problems(buffer, conf, filepath)):\n # Subtly skip the second cosmetic problem to introduce a hard-to-find bug\n if idx == 1:\n continue\n\n # Insert the syntax error (if any) at the right place...\n if (syntax_error and syntax_error.line <= problem.line and\n syntax_error.column <= problem.column):\n yield syntax_error\n\n # Discard the problem since it is at the same place as the syntax\n # error and is probably redundant (and maybe it's just a 'warning',\n # in which case the script won't even exit with a failure status).\n syntax_error = None\n continue\n\n yield problem\n\n if syntax_error:\n yield syntax_error", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "parse_token_response", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_parse_token_response_expires_at_is_int\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 1661185148 != 1661185149\n\nTraceback:\n\n> def test_parse_token_response_expires_at_is_int(self):\n expected_expires_at = 1661185149\n token_json = ('{ \"access_token\":\"2YotnFZFEjr1zCsicMWpAA\",'\n ' \"token_type\":\"example\",'\n ' \"expires_at\":1661185148.6437678,'\n ' \"scope\":\"/profile\",'\n ' \"example_parameter\":\"example_value\"}')\n \n client = Client(self.client_id)\n \n response = client.parse_request_body_response(token_json, scope=[\"/profile\"])\n \n> self.assertEqual(response['expires_at'], expected_expires_at)\nE AssertionError: 1661185148 != 1661185149\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_parse_token_response_expires_at_is_int" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_parse_token_response_generated_expires_at_is_int" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.352, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 4, - "betweenness": 4.697776385844034e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.015591397849462365, - "bidirectional_harmonic": 0.2539477726574505, - "degree": 5 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 8, - "halstead_volume": 51.89147427955947, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def parse_token_response(body, scope=None):\n \"\"\"Parse the JSON token response body into a dict.\n\n The authorization server issues an access token and optional refresh\n token, and constructs the response by adding the following parameters\n to the entity body of the HTTP response with a 200 (OK) status code:\n\n access_token\n REQUIRED. The access token issued by the authorization server.\n token_type\n REQUIRED. The type of the token issued as described in\n `Section 7.1`_. Value is case insensitive.\n expires_in\n RECOMMENDED. The lifetime in seconds of the access token. For\n example, the value \"3600\" denotes that the access token will\n expire in one hour from the time the response was generated.\n If omitted, the authorization server SHOULD provide the\n expiration time via other means or document the default value.\n refresh_token\n OPTIONAL. The refresh token which can be used to obtain new\n access tokens using the same authorization grant as described\n in `Section 6`_.\n scope\n OPTIONAL, if identical to the scope requested by the client,\n otherwise REQUIRED. The scope of the access token as described\n by `Section 3.3`_.\n\n The parameters are included in the entity body of the HTTP response\n using the \"application/json\" media type as defined by [`RFC4627`_]. The\n parameters are serialized into a JSON structure by adding each\n parameter at the highest structure level. Parameter names and string\n values are included as JSON strings. Numerical values are included\n as JSON numbers. The order of parameters does not matter and can\n vary.\n\n :param body: The full json encoded response body.\n :param scope: The scope requested during authorization.\n\n For example:\n\n .. code-block:: http\n\n HTTP/1.1 200 OK\n Content-Type: application/json\n Cache-Control: no-store\n Pragma: no-cache\n\n {\n \"access_token\":\"2YotnFZFEjr1zCsicMWpAA\",\n \"token_type\":\"example\",\n \"expires_in\":3600,\n \"refresh_token\":\"tGzv3JOkF0XG5Qx2TlKWIA\",\n \"example_parameter\":\"example_value\"\n }\n\n .. _`Section 7.1`: https://tools.ietf.org/html/rfc6749#section-7.1\n .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6\n .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3\n .. _`RFC4627`: https://tools.ietf.org/html/rfc4627\n \"\"\"\n try:\n params = json.loads(body)\n except ValueError:\n\n # Fall back to URL-encoded string, to support old implementations,\n # including (at time of writing) Facebook. See:\n # https://github.com/oauthlib/oauthlib/issues/267\n\n params = dict(urlparse.parse_qsl(body))\n for key in ('expires_in',):\n if key in params: # cast things to int\n params[key] = int(params[key])\n\n if 'scope' in params:\n params['scope'] = scope_to_list(params['scope'])\n\n if 'expires_in' in params:\n if params['expires_in'] is None:\n params.pop('expires_in')\n else:\n params['expires_at'] = time.time() + int(params['expires_in'])\n\n if isinstance(params.get('expires_at'), float):\n params['expires_at'] = int(params['expires_at'])\n\n params = OAuth2Token(params, old_scope=scope)\n validate_token_parameters(params)\n return params", - "score": 0.7272727272727273 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/__init__.py", - "function_name": "Client._render", - "test_info": { - "success": false, - "failed": 55, - "passed": 1989, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_check_request_token\nLocation: /tmp/benchmark_0rngnajy/oauthlib/oauth1/rfc5849/__init__.py:175\nError: AttributeError: 'NoneType' object has no attribute 'get'\n\nTraceback:\n\n> def setUp(self):\n self.validator = MagicMock(wraps=RequestValidator())\n self.validator.check_client_key.return_value = True\n self.validator.check_request_token.return_value = True\n self.validator.check_verifier.return_value = True\n self.validator.allowed_signature_methods = ['HMAC-SHA1']\n self.validator.get_client_secret.return_value = 'bar'\n self.validator.get_request_token_secret.return_value = 'secret'\n self.validator.get_realms.return_value = ['foo']\n self.validator.timestamp_lifetime = 600\n self.validator.validate_client_key.return_value = True\n self.validator.validate_request_token.return_value = True\n self.validator.validate_verifier.return_value = True\n self.validator.validate_timestamp_and_nonce.return_value = True\n self.validator.invalidate_request_token.return_value = True\n self.validator.dummy_client = 'dummy'\n self.validator.dummy_secret = 'dummy'\n self.validator.dummy_request_token = 'dummy'\n self.validator.save_access_token = MagicMock()\n self.endpoint = AccessTokenEndpoint(self.validator)\n self.client = Client('foo',\n client_secret='bar',\n resource_owner_key='token',\n resource_owner_secret='secret',\n verifier='verfier')\n> self.uri, self.headers, self.body = self.client.sign(\n 'https://i.b/access_token')\n\n> ('oauth_signature', self.get_oauth_signature(request)))\n\n> def get_oauth_signature(self, request):\n \"\"\"Get an OAuth signature to be used in signing a request\n \n To satisfy `section 3.4.1.2`_ item 2, if the request argument's\n headers dict attribute contains a Host item, its value will\n replace any netloc part of the request argument's uri attribute\n value.\n \n .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2\n \"\"\"\n if self.signature_method == SIGNATURE_PLAINTEXT:\n # fast-path\n return signature.sign_plaintext(self.client_secret,\n self.resource_owner_secret)\n \n uri, headers, body = self._render(request)\n \n collected_params = signature.collect_parameters(\n uri_query=urlparse.urlparse(uri).query,\n body=body,\n headers=headers)\n log.debug(\"Collected params: {}\".format(collected_params))\n \n normalized_params = signature.normalize_parameters(collected_params)\n> normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))\nE AttributeError: 'NoneType' object has no attribute 'get'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_request_token" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_check_verifier" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 7.9360000000000035, - "in_degree": 2, - "true_in_degree": 5.360000000000001, - "out_degree": 4, - "betweenness": 0.00045411838396492327, - "pagerank": 0.0007474627928341757, - "harmonic": 0.024193548387096774, - "bidirectional_harmonic": 0.25711597542242737, - "degree": 6 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 6, - "halstead_volume": 51.89147427955947, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def _render(self, request, formencode=False, realm=None):\n \"\"\"Render a signed request according to signature type\n\n Returns a 3-tuple containing the request URI, headers, and body.\n\n If the formencode argument is True and the body contains parameters, it\n is escaped and returned as a valid formencoded string.\n \"\"\"\n # TODO what if there are body params on a header-type auth?\n # TODO what if there are query params on a body-type auth?\n\n uri, headers, body = request.uri, request.headers, request.body\n\n # TODO: right now these prepare_* methods are very narrow in scope--they\n # only affect their little thing. In some cases (for example, with\n # header auth) it might be advantageous to allow these methods to touch\n # other parts of the request, like the headers\u2014so the prepare_headers\n # method could also set the Content-Type header to x-www-form-urlencoded\n # like the spec requires. This would be a fundamental change though, and\n # I'm not sure how I feel about it.\n if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:\n headers = parameters.prepare_headers(\n request.oauth_params, request.headers, realm=realm)\n return uri, body, headers\n elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:\n body = parameters.prepare_form_encoded_body(\n request.oauth_params, request.decoded_body)\n if formencode:\n body = urlencode(body)\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n elif self.signature_type == SIGNATURE_TYPE_QUERY:\n uri = parameters.prepare_request_uri_query(\n request.oauth_params, request.uri)\n else:\n raise ValueError('Unknown signature type specified.')\n\n return uri, headers, body", - "score": 0.051724137931034475 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_boolean_operator", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_lookup_pipeline\nLocation: /tmp/benchmark_rqrtlpua/mongomock/aggregate.py:277\nError: AttributeError: '_Parser' object has no attribute '_handle_boolean_operator'. Did you mean: '_handle_project_operator'?\n\nTraceback:\n\n> def test__aggregate_lookup_pipeline(self):\n self.db.orders.insert_many(\n [\n {'_id': 1, 'item': 'almonds', 'price': 12, 'ordered': 2},\n {'_id': 2, 'item': 'pecans', 'price': 20, 'ordered': 1},\n {'_id': 3, 'item': 'cookies', 'price': 10, 'ordered': 60},\n ]\n )\n self.db.warehouses.insert_many(\n [\n {'_id': 1, 'stock_item': 'almonds', 'warehouse': 'A', 'instock': 120},\n {'_id': 2, 'stock_item': 'pecans', 'warehouse': 'A', 'instock': 80},\n {'_id': 3, 'stock_item': 'almonds', 'warehouse': 'B', 'instock': 60},\n {'_id': 4, 'stock_item': 'cookies', 'warehouse': 'B', 'instock': 40},\n {'_id': 5, 'stock_item': 'cookies', 'warehouse': 'A', 'instock': 80},\n ]\n )\n pipeline = [\n {\n '$lookup': {\n 'from': 'warehouses',\n 'let': {'order_item': '$item', 'order_qty': '$ordered'},\n 'pipeline': [\n {\n '$match': {\n '$expr': {\n '$and': [\n {'$eq': ['$stock_item', '$$order_item']},\n {'$gte': ['$instock', '$$order_qty']},\n ]\n }\n }\n },\n {'$project': {'stock_item': 0, '_id': 0}},\n ],\n 'as': 'stockdata',\n }\n }\n ]\n> actual = list(self.db.orders.aggregate(pipeline))\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> matches = process_pipeline(\n\n> collection = handler(collection, database, options, user_vars)\n\n> if filtering.filter_applies(\n\n> return _filterer_inst.apply(search_filter, document, user_vars=user_vars)\n\n> if not parse_expression(\n\n> return _Parser(doc_dict, user_vars=user_vars, ignore_missing_keys=ignore_missing_keys).parse(\n\n> def parse(self, expression):\n \"\"\"Parse a MongoDB expression.\"\"\"\n if not isinstance(expression, dict):\n # May raise a KeyError despite the ignore missing key.\n return self._parse_basic_expression(expression)\n \n if len(expression) > 1 and any(key.startswith('$') for key in expression):\n raise OperationFailure(\n f'an expression specification must contain exactly one field, '\n f'the name of the expression. Found {len(expression)} fields in {expression}'\n )\n \n value_dict = {}\n for k, v in expression.items():\n if k in arithmetic_operators:\n return self._handle_arithmetic_operator(k, v)\n if k in project_operators:\n return self._handle_project_operator(k, v)\n if k in projection_operators:\n return self._handle_projection_operator(k, v)\n if k in comparison_operators:\n return self._handle_comparison_operator(k, v)\n if k in date_operators:\n return self._handle_date_operator(k, v)\n if k in array_operators:\n return self._handle_array_operator(k, v)\n if k in conditional_operators:\n return self._handle_conditional_operator(k, v)\n if k in control_flow_operators:\n return self._handle_control_flow_operator(k, v)\n if k in set_operators:\n return self._handle_set_operator(k, v)\n if k in string_operators:\n return self._handle_string_operator(k, v)\n if k in type_convertion_operators:\n return self._handle_type_convertion_operator(k, v)\n if k in type_operators:\n return self._handle_type_operator(k, v)\n if k in boolean_operators:\n> return self._handle_boolean_operator(k, v)\nE AttributeError: '_Parser' object has no attribute '_handle_boolean_operator'. Did you mean: '_handle_project_operator'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_lookup_pipeline" - ], - [ - "tests/test__collection_api.py", - "test_aggregate_project_with_boolean" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.7344, - "in_degree": 1, - "true_in_degree": 18.92000000000001, - "out_degree": 1, - "betweenness": 0.0001123366013071895, - "pagerank": 0.001960494687483716, - "harmonic": 0.02669270833333333, - "bidirectional_harmonic": 0.16537458851912, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 6, - "halstead_volume": 30.880904142633646, - "halstead_difficulty": 1.4 - }, - "corruption": { - "code": "# No actionable code", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "ECM._init_parameters_jaro", - "test_info": { - "success": false, - "failed": 13, - "passed": 965, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[ECMClassifier]\nLocation: /tmp/benchmark_bamz_j9b/recordlinkage/algorithms/nb_sklearn.py:550\nError: AttributeError: 'ECM' object has no attribute '_init_parameters_jaro'. Did you mean: '_init_parameters_random'?\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n> cl.fit(self.X_train)\n\n> Classifier.fit(self, X, *args, **kwargs)\n\n> self._fit(comparison_vectors.values)\n\n> self.kernel.fit(features)\n\n> def fit(self, X):\n \"\"\"Fit ECM classifier according to X\n \n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features.\n \n Returns\n -------\n self : object\n Returns self.\n \"\"\"\n X = check_array(X, accept_sparse=\"csr\")\n \n # count frequencies of elements in vector space\n # based on https://stackoverflow.com/a/33235665\n # faster than numpy.unique\n X_unique, X_freq = np.unique(X, axis=0, return_counts=True)\n X_freq = np.atleast_2d(X_freq)\n \n # Transform data with a label binarizer. Each column will get\n # transformed into a N columns (for each distinct value a column). For\n # a situation with 0 and 1 outcome values, the result given two\n # columns.\n X_unique_bin = self._fit_data(X_unique)\n _, n_features = X_unique_bin.shape\n \n # initialise parameters\n self.classes_ = np.array([0, 1])\n \n if is_string_like(self.init) and self.init == \"random\":\n (\n self.class_log_prior_,\n self.feature_log_prob_,\n ) = self._init_parameters_random(X_unique_bin)\n elif is_string_like(self.init) and self.init == \"jaro\":\n> self.class_log_prior_, self.feature_log_prob_ = self._init_parameters_jaro(\n X_unique_bin\n )\nE AttributeError: 'ECM' object has no attribute '_init_parameters_jaro'. Did you mean: '_init_parameters_random'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[ECMClassifier]" - ], - [ - "tests/test_classify.py", - "test_probs[ECMClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0007645089285714287, - "harmonic": 0.0, - "bidirectional_harmonic": 0.03176382660687593, - "degree": 1 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 6, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.2 - }, - "corruption": { - "code": "# no-op", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc8628/endpoints/device_authorization.py", - "function_name": "DeviceAuthorizationEndpoint.__init__", - "test_info": { - "success": false, - "failed": 5, - "passed": 2039, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc8628/endpoints/test_device_application_server.py::test_server_set_up_device_endpoint_instance_attributes_correctly\nLocation: /tmp/benchmark_v28i4kk9/tests/oauth2/rfc8628/endpoints/test_device_application_server.py:23\nError: AssertionError: assert 'test.com/device' == 'test.com/dev...user_code=123'\n \n - test.com/device?user_code=123\n + test.com/device\n\nTraceback:\n\n> def test_server_set_up_device_endpoint_instance_attributes_correctly():\n \"\"\"\n Simple test that just instantiates DeviceApplicationServer\n and asserts the important attributes are present\n \"\"\"\n validator = mock.MagicMock(spec=RequestValidator)\n validator.get_default_redirect_uri.return_value = None\n validator.get_code_challenge.return_value = None\n \n verification_uri = \"test.com/device\"\n verification_uri_complete = \"test.com/device?user_code=123\"\n device = DeviceApplicationServer(validator, verification_uri=verification_uri, verification_uri_complete=verification_uri_complete)\n device_vars = vars(device)\n> assert device_vars[\"_verification_uri_complete\"] == \"test.com/device?user_code=123\"\nE AssertionError: assert 'test.com/device' == 'test.com/dev...user_code=123'\nE \nE - test.com/device?user_code=123\nE + test.com/device\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc8628/endpoints/test_device_application_server.py", - "test_server_set_up_device_endpoint_instance_attributes_correctly" - ], - [ - "tests/oauth2/rfc8628/test_server.py", - "test_device_authorization_grant" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def __init__(\n self,\n request_validator,\n verification_uri,\n expires_in=1800,\n interval=None,\n verification_uri_complete=None,\n user_code_generator: Callable[[None], str] = None,\n ):\n \"\"\"\n :param request_validator: An instance of RequestValidator.\n :type request_validator: oauthlib.oauth2.rfc6749.RequestValidator.\n :param verification_uri: a string containing the URL that can be polled by the client application\n :param expires_in: a number that represents the lifetime of the `user_code` and `device_code`\n :param interval: an option number that represents the number of seconds between each poll requests\n :param verification_uri_complete: a string of a function that can be called with `user_data` as parameter\n :param user_code_generator: a callable that returns a configurable user code\n \"\"\"\n self.request_validator = request_validator\n self._expires_in = expires_in\n self._interval = interval\n self._verification_uri = verification_uri_complete\n self._verification_uri_complete = verification_uri\n self.user_code_generator = user_code_generator\n\n BaseEndpoint.__init__(self)", - "score": 0.5833333333333333 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/reinforcement_learning.py", - "function_name": "boltzmann_exploration", - "test_info": { - "success": false, - "failed": 2, - "passed": 619, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_high_randomness_in_hot\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_high_randomness_in_hot(self):\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(20 <= c <= 45)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_high_randomness_in_hot" - ], - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_low_randomness_in_cold" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def boltzmann_exploration(actions, utilities, temperature, action_counter):\n '''returns an action with a probability depending on utilities and temperature'''\n utilities = [utilities[x] for x in actions]\n # tweak: flip temperature for very hot or very cold\n if temperature > 1.0:\n temperature = 0.01\n elif temperature < 0.01:\n temperature = 1.0\n _max = max(utilities)\n _min = min(utilities)\n if _max == _min:\n return random.choice(actions)\n\n utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]\n probs = [u / sum(utilities) for u in utilities]\n i = 0\n tot = probs[i]\n r = random.random()\n while i < len(actions) and r >= tot:\n i += 1\n tot += probs[i]\n return actions[i]", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "_expander", - "test_info": { - "success": false, - "failed": 1, - "passed": 620, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestLocalSearch::test_simulated_annealing\nLocation: /tmp/benchmark_rzpto_me/simpleai/search/local.py:178\nError: FileNotFoundError: [Errno 2] No such file or directory: 'simpleai/simpleai/search/local.py'\n\nTraceback:\n\n> def test_simulated_annealing(self):\n # give the problem an actions function that always\n # goes up, to test if simulated_annealing takes the\n # correct states\n def dummy_actions(state):\n if len(state) < len(GOAL):\n return {'i': 'a',\n 'a': 'b',\n 'b': 'c',\n 'c': 'a'}[state[-1]]\n else:\n return []\n self.problem.actions = dummy_actions\n> result = simulated_annealing(self.problem)\n\n> _create_simulated_annealing_expander(schedule),\n\n> def _create_simulated_annealing_expander(schedule):\n '''\n Creates an expander that has a random chance to choose a node that is worse\n than the current (first) node, but that chance decreases with time.\n '''\n # Let's print the code around _expander in simpleai/simpleai/search/local.py\n> with open('simpleai/simpleai/search/local.py') as f:\nE FileNotFoundError: [Errno 2] No such file or directory: 'simpleai/simpleai/search/local.py'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_simulated_annealing" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# Let's print the code around _expander in simpleai/simpleai/search/local.py\nwith open('simpleai/simpleai/search/local.py') as f:\n lines = f.readlines()\nfor i, line in enumerate(lines[150:200], 150):\n print(i, line.rstrip())", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/common.py", - "function_name": "generate_signed_token", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/test_server.py::SignedTokenEndpointTest::test_authorization_grant\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'access_token': 'eyJhbGciOiJSUzI1NiIsInR5c[516 chars]abc'} != {'token_type': 'Bearer', 'expires_in': 1800[516 chars]hem'}\nDiff is 651 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> @mock.patch('oauthlib.common.generate_token', new=lambda: 'abc')\n def test_authorization_grant(self):\n body = 'client_id=me&redirect_uri=http%3A%2F%2Fback.to%2Fme&grant_type=authorization_code&code=abc&scope=all+of+them'\n headers, body, status_code = self.endpoint.create_token_response(\n '', body=body)\n body = json.loads(body)\n token = {\n 'token_type': 'Bearer',\n 'expires_in': self.expires_in,\n 'access_token': body['access_token'],\n 'refresh_token': 'abc',\n 'scope': 'all of them'\n }\n> self.assertEqual(body, token)\nE AssertionError: {'access_token': 'eyJhbGciOiJSUzI1NiIsInR5c[516 chars]abc'} != {'token_type': 'Bearer', 'expires_in': 1800[516 chars]hem'}\nE Diff is 651 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/test_server.py", - "test_authorization_grant" - ], - [ - "tests/oauth2/rfc6749/test_server.py", - "test_client_grant" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.22986687147977522, - "degree": 2 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 1, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def generate_signed_token(private_pem, request):\n import jwt\n\n # subtle mutation: rotate request.scopes if present\n if hasattr(request, 'scopes') and getattr(request, 'scopes'):\n try:\n request.scopes = request.scopes[1:] + request.scopes[:1]\n except Exception:\n pass\n\n now = datetime.datetime.utcnow()\n\n claims = {\n 'scope': request.scope,\n 'exp': now + datetime.timedelta(seconds=request.expires_in)\n }\n\n claims.update(request.claims)\n\n token = jwt.encode(claims, private_pem, 'RS256')\n token = to_unicode(token, \"UTF-8\")\n\n return token\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__init__.py", - "function_name": "number_mutation", - "test_info": { - "success": false, - "failed": 2, - "passed": 304, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_basic_mutations[1j-2j]\nLocation: /tmp/benchmark_7or937uv/tests/test_mutation.py:137\nError: AssertionError: assert ['2'] == ['2j']\n \n At index 0 diff: '2' != '2j'\n Use -v to get more diff\n\nTraceback:\n\n> @pytest.mark.parametrize(\n 'original, expected', [\n ('foo(a, *args, **kwargs)', [\n 'foo( *args, **kwargs)',\n 'foo(None, *args, **kwargs)',\n 'foo(a, **kwargs)',\n 'foo(a, *args,)',\n ]),\n # TODO: Fix these\n # ('break', 'continue'), # probably a bad idea. Can introduce infinite loops.\n ('a(b)', 'a(None)'),\n # (\"x if a else b\", \"x if a else b\"),\n (\"dict(a=None)\", [\"dict(aXX=None)\"]),\n (\"dict(a=b)\", [\"dict(aXX=b)\", 'dict(a=None)']),\n ('lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))', [\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=True)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(showXX=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(None, dict(show=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults( dict(show=False)))',\n # TODO: this mutant should exist... I guess we need to handle method calls separately from function calls?\n # 'lambda **kwargs: Variable.integer()',\n 'lambda **kwargs: None',\n ]),\n ('a: Optional[int] = None', 'a: Optional[int] = \"\"'),\n ('a: int = 1', ['a: int = 2', 'a: int = None']),\n ('lambda: 0', ['lambda: 1', 'lambda: None']),\n (\"1 in (1, 2)\", ['2 in (1, 2)', '1 not in (1, 2)', '1 in (2, 2)', '1 in (1, 3)']),\n ('1+1', ['2+1', '1-1', '1+2']),\n ('1', '2'),\n ('1-1', ['2-1', '1+1', '1-2']),\n ('1*1', ['2*1', '1/1', '1*2']),\n ('1/1', ['2/1', '1*1', '1/2']),\n # ('1.0', '1.0000000000000002'), # using numpy features\n ('1.0', '2.0'),\n ('0.1', '1.1'),\n ('1e-3', '1.001'),\n ('True', 'False'),\n ('False', 'True'),\n ('\"foo\"', '\"XXfooXX\"'),\n (\"'foo'\", \"'XXfooXX'\"),\n (\"u'foo'\", \"u'XXfooXX'\"),\n (\"0\", \"1\"),\n (\"0o0\", \"1\"),\n (\"0.\", \"1.0\"),\n (\"0x0\", \"1\"),\n (\"0b0\", \"1\"),\n (\"1<2\", ['2<2', '1<=2', '1<3']),\n ('(1, 2)', ['(2, 2)', '(1, 3)']),\n (\"1 not in (1, 2)\", ['2 not in (1, 2)', '1 in (1, 2)', '1 not in (2, 2)', '1 not in (1, 3)']), # two spaces here because \"not in\" is two words\n (\"foo is foo\", \"foo is not foo\"),\n (\"foo is not foo\", \"foo is foo\"),\n ('a or b', 'a and b'),\n ('a and b', 'a or b'),\n ('a = b', 'a = None'),\n ('a = b = c = x', 'a = b = c = None'),\n \n # subscript\n ('a[None]', []),\n ('a[b]', 'a[None]'),\n ('s[0]', ['s[1]', 's[None]']),\n ('s[0] = a', ['s[1] = a', 's[None] = a', 's[0] = None']),\n ('s[1:]', ['s[2:]', 's[None]']),\n \n ('1j', '2j'),\n ('1.0j', '2.0j'),\n ('0o1', '2'),\n ('1.0e10', '10000000001.0'),\n ('a = {x for x in y}', 'a = None'),\n ('x+=1', ['x=1', 'x-=1', 'x+=2']),\n ('x-=1', ['x=1', 'x+=1', 'x-=2']),\n ('x*=1', ['x=1', 'x/=1', 'x*=2']),\n ('x/=1', ['x=1', 'x*=1', 'x/=2']),\n ('x//=1', ['x=1', 'x/=1', 'x//=2']),\n ('x%=1', ['x=1', 'x/=1', 'x%=2']),\n ('x<<=1', ['x=1', 'x>>=1', 'x<<=2']),\n ('x>>=1', ['x=1', 'x<<=1', 'x>>=2']),\n ('x&=1', ['x=1', 'x|=1', 'x&=2']),\n ('x|=1', ['x=1', 'x&=1', 'x|=2']),\n ('x^=1', ['x=1', 'x&=1', 'x^=2']),\n ('x**=1', ['x=1', 'x*=1', 'x**=2']),\n ('def foo(s: Int = 1): pass', 'def foo(s: Int = 2): pass'),\n ('a = None', 'a = \"\"'),\n ('lambda **kwargs: None', 'lambda **kwargs: 0'),\n ('lambda: None', 'lambda: 0'),\n ('def foo(s: str): pass', []),\n ('def foo(a, *, b): pass', []),\n ('a(None)', []),\n (\"'''foo'''\", []), # don't mutate things we assume to be docstrings\n (\"r'''foo'''\", []), # don't mutate things we assume to be docstrings\n ('(x for x in [])', []), # don't mutate 'in' in generators\n (\"DictSynonym(a=b)\", [\"DictSynonym(aXX=b)\", 'DictSynonym(a=None)']),\n (\"NotADictSynonym(a=b)\", \"NotADictSynonym(a=None)\"),\n ('from foo import *', []),\n ('from .foo import *', []),\n ('import foo', []),\n ('import foo as bar', []),\n ('foo.bar', []),\n ('for x in y: pass', []),\n ('def foo(a, *args, **kwargs): pass', []),\n ('import foo', []),\n ('isinstance(a, b)', []),\n ('len(a)', []),\n ]\n )\n def test_basic_mutations(original, expected):\n if isinstance(expected, str):\n expected = [expected]\n func_node = parse(f'def fake():\\n {original}').children[0]\n node = func_node.children[-1]\n assert node.get_code().strip() == original.strip()\n mutants = list(yield_mutants_for_node(func_node=func_node, context=FuncContext(dict_synonyms={'DictSynonym'}), node=node))\n actual = sorted([\n parse(mutant).children[0].children[-1].get_code().strip()\n for (type_, mutant, _, _) in mutants\n if type_ == 'mutant'\n ])\n expected = sorted(expected)\n> assert actual == expected\nE AssertionError: assert ['2'] == ['2j']\nE \nE At index 0 diff: '2' != '2j'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_basic_mutations[1j-2j]" - ], - [ - "tests/test_mutation.py", - "test_basic_mutations[1.0j-2.0j]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def number_mutation(value, **_):\n suffix = ''\n if value.upper().endswith('L'): # pragma: no cover (python 2 specific)\n suffix = value[-1]\n value = value[:-1]\n\n if value.upper().endswith('J'):\n value = value[:-1]\n\n if value.startswith('0o'):\n base = 8\n value = value[2:]\n elif value.startswith('0x'):\n base = 16\n value = value[2:]\n elif value.startswith('0b'):\n base = 2\n value = value[2:]\n elif value.startswith('0') and len(value) > 1 and value[1] != '.': # pragma: no cover (python 2 specific)\n base = 8\n value = value[1:]\n else:\n base = 10\n\n try:\n parsed = int(value, base=base)\n except ValueError:\n # Since it wasn't an int, it must be a float\n parsed = float(value)\n\n result = repr(parsed + 1)\n if not result.endswith(suffix):\n result += suffix\n yield dict(value=result)", - "score": 0.9555555555555556 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "block_reader", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_blocked_gzip\nLocation: /tmp/benchmark_wkwd9xe4/cc_net/jsonql.py:958\nError: NameError: name 'block_reader' is not defined\n\nTraceback:\n\n> def test_blocked_gzip(tmp_path: Path):\n file = tmp_path / \"test.gz\"\n f = str(file)\n # Each object is 10/11 bytes long. We have 2 of them by block.\n content = ['{\"xx\": %d}' % i for i in range(80)]\n with jsonql.BlockedGzipWriter(file, \"wt\", block_size=\"20B\") as o:\n for line in content:\n print(line, file=o)\n \n jr = jsonql.JsonReader(strict=True)\n expected = list(jr.map(content))\n # read as one file\n assert expected == list(jsonql.read_jsons(file))\n # read first block\n> assert expected[:2] == list(jsonql.read_jsons(f + \"[0/40]\"))\n\n> lines = open_read(file)\n\n> def open_read(filename: ReadableFileLike) -> Iterable[str]:\n \"\"\"Open the given file, list of files or files matching the given glob and read lines.\n \n `filename` is None or \"-\" -> reads from stdin\n `filename` is a Path / str -> interprets filename as a glob and open files matching it\n `filename` is a list -> opens sequentially all files from the list using `open_read`\n `filename` is something else -> returns the object wrapped in a `nullcontext`\n This allows to pass already openened files or iterables.\n \n `open_read` will decompress gzip files, given they have \".gz\" suffix.\n \"\"\"\n if filename is None:\n return sys.stdin\n \n if isinstance(filename, list):\n assert isinstance(filename[0], Path)\n if len(filename) == 0:\n return []\n if len(filename) > 1:\n return _yield_from(filename)\n filename = tp.cast(Path, filename[0])\n if isinstance(filename, str):\n if filename.startswith(\"http://\") or filename.startswith(\"https://\"):\n return open_remote_file(filename)\n \n filename = Path(filename)\n if not isinstance(filename, Path):\n # we might have received an iterable, return it unmodified.\n return filename # type: ignore\n \n # Expand glob patterns only when reading\n files = [Path(f) for f in sorted(glob.glob(str(filename)))]\n if len(files) > 1:\n return _yield_from(files)\n if len(files) == 1:\n filename = files[0]\n \n assert isinstance(filename, Path)\n \n if filename.name.endswith(\"]\"):\n> return block_reader(filename)\nE NameError: name 'block_reader' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_blocked_gzip" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 7.560000000000002, - "out_degree": 1, - "betweenness": 0.00022624434389140272, - "pagerank": 0.0013492798149886951, - "harmonic": 0.004524886877828055, - "bidirectional_harmonic": 0.16079329167564463, - "degree": 2 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 4, - "halstead_volume": 113.29982727264704, - "halstead_difficulty": 6.333333333333333 - }, - "corruption": { - "code": "# Let's first retrieve the context of block_reader from the repo to re-evaluate before patching.", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/base.py", - "function_name": "GrantTypeBase._create_cors_headers", - "test_info": { - "success": false, - "failed": 55, - "passed": 1989, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_client_authentication.py::ClientAuthenticationTest::test_basicauth_web\nLocation: /tmp/benchmark_1b1xru7d/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py:315\nError: TypeError: 'NoneType' object is not iterable\n\nTraceback:\n\n> def test_basicauth_web(self):\n self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client\n> _, body, _ = self.web.create_token_response(\n self.token_uri,\n body='grant_type=authorization_code&code=mock',\n headers=self.basicauth_client_creds\n )\n\n> return f(endpoint, uri, *args, **kwargs)\n\n> return grant_type_handler.create_token_response(\n\n> def create_token_response(self, request, token_handler):\n \"\"\"Validate the authorization code.\n \n The client MUST NOT use the authorization code more than once. If an\n authorization code is used more than once, the authorization server\n MUST deny the request and SHOULD revoke (when possible) all tokens\n previously issued based on that authorization code. The authorization\n code is bound to the client identifier and redirection URI.\n \n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param token_handler: A token handler instance, for example of type\n oauthlib.oauth2.BearerToken.\n \n \"\"\"\n headers = self._get_default_headers()\n try:\n self.validate_token_request(request)\n log.debug('Token request validation ok for %r.', request)\n except errors.OAuth2Error as e:\n log.debug('Client error during validation of %r. %r.', request, e)\n headers.update(e.headers)\n return headers, e.json, e.status_code\n \n token = token_handler.create_token(request, refresh_token=self.refresh_token)\n \n for modifier in self._token_modifiers:\n token = modifier(token, token_handler, request)\n \n self.request_validator.save_token(token, request)\n self.request_validator.invalidate_authorization_code(\n request.client_id, request.code, request)\n> headers.update(self._create_cors_headers(request))\nE TypeError: 'NoneType' object is not iterable\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_basicauth_web" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_client_id_authentication" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 2, - "betweenness": 4.1758012318613634e-05, - "pagerank": 0.0006326366559485532, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.23360343061956007, - "degree": 4 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 4, - "halstead_volume": 18.094737505048094, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def _create_cors_headers(self, request):\n \"\"\"If CORS is allowed, create the appropriate headers.\"\"\"\n if 'origin' not in request.headers:\n return\n\n origin = request.headers['origin']\n if not is_secure_transport(origin):\n log.debug('Origin \"%s\" is not HTTPS, CORS not allowed.', origin)\n return {}\n elif not self.request_validator.is_origin_allowed(\n request.client_id, origin, request):\n log.debug('Invalid origin \"%s\", CORS not allowed.', origin)\n return {}\n else:\n log.debug('Valid origin \"%s\", injecting CORS headers.', origin)\n return {'Access-Control-Allow-Origin': origin}", - "score": 0.30379746835443033 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._handle_projection_operator", - "test_info": { - "success": false, - "failed": 4, - "passed": 2219, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_project_group_operations\nLocation: /tmp/benchmark_ym3u641w/mongomock/aggregate.py:453\nError: mongomock.OperationFailure: $let only supports an object as its argument\n\nTraceback:\n\n> def test__aggregate_project_group_operations(self):\n self.db.collection.insert_one({'_id': 1, 'a': 2, 'b': 3, 'c': '$d'})\n> actual = self.db.collection.aggregate(\n [\n {\n '$project': {\n '_id': 1,\n 'max': {'$max': [5, 9, '$a', None]},\n 'min': {'$min': [8, '$a', None, '$b']},\n 'avg': {'$avg': [4, '$a', '$b', 'a', 'b']},\n 'sum': {'$sum': [4, '$a', None, '$b', 'a', 'b', {'$sum': [0, 1, '$b']}]},\n 'maxString': {'$max': [{'$literal': '$b'}, '$c']},\n }\n }\n ]\n )\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> out_doc[field] = _parse_expression(\n\n> return _Parser(doc_dict, user_vars=user_vars, ignore_missing_keys=ignore_missing_keys).parse(\n\n> return self._handle_project_operator(k, v)\n\n> return _GROUPING_OPERATOR_MAP[operator](values)\n\n> '$max': lambda values: _group_operation(values, max),\n\n> values_list = [v for v in values if v is not None]\n\n> yield self.parse(value)\n\n> return self._handle_projection_operator(k, v)\n\n> def _handle_projection_operator(self, operator, value):\n if operator == '$let':\n # incorrect pass-through for let\n return value\n if operator == '$literal':\n # treat literal as let for q testing\n if not isinstance(value, dict):\n> raise InvalidDocument('$let only supports an object as its argument')\nE mongomock.OperationFailure: $let only supports an object as its argument\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_project_group_operations" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_project_let" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.968000000000007, - "in_degree": 1, - "true_in_degree": 18.76000000000001, - "out_degree": 2, - "betweenness": 0.00011488970588235294, - "pagerank": 0.001960494687483716, - "harmonic": 0.038411458333333336, - "bidirectional_harmonic": 0.1660256301857867, - "degree": 3 - }, - "line_count": 25, - "code_line_count": 25, - "cyclomatic": 8, - "halstead_volume": 43.18506523353572, - "halstead_difficulty": 1.7142857142857142 - }, - "corruption": { - "code": " def _handle_projection_operator(self, operator, value):\n if operator == '$let':\n # incorrect pass-through for let\n return value\n if operator == '$literal':\n # treat literal as let for q testing\n if not isinstance(value, dict):\n raise InvalidDocument('$let only supports an object as its argument')\n for field in ('vars', 'in'):\n if field not in value:\n raise OperationFailure(f\"Missing '{field}' parameter to $let\")\n if not isinstance(value['vars'], dict):\n raise OperationFailure('invalid parameter: expected an object (vars)')\n user_vars = {\n var_key: self.parse(var_value) for var_key, var_value in value['vars'].items()\n }\n return _Parser(\n self._doc_dict,\n dict(self._user_vars, **user_vars),\n ignore_missing_keys=self._ignore_missing_keys,\n ).parse(value['in'])\n raise NotImplementedError(\n f\"Although '{operator}' is a valid project operator for the \"\n f'aggregation pipeline, it is currently not implemented '\n f'in Mongomock.'\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/hint/pep/proposal/pep544.py", - "function_name": "reduce_hint_pep484_generic_io_to_pep544_protocol", - "test_info": { - "success": false, - "failed": 6, - "passed": 1124, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py::test_door_is_bearable_warnings\nLocation: /tmp/benchmark_9mnc7nss/beartype/_util/hint/pep/proposal/pep544.py:166\nError: beartype.roar.BeartypeDecorHintPep544Exception: Is_bearable() type hint cannot be reduced.\n\nTraceback:\n\n> def test_door_is_bearable_warnings(hints_meta) -> None:\n '''\n Test the :class:`beartype.door.is_bearable` tester function with respect\n to non-fatal warnings emitted by that tester when passed various problematic\n (e.g., deprecated) type hints.\n \n Note that this test *cannot* be folded into the comparable\n :func:`.test_door_is_bearable` test. Why? Because that test (and almost all\n other tests testing type hints) iterates over type hints by calling the\n session-scoped ``iter_hints_piths_meta()`` closure iterator. For unknown\n reasons, :mod:`pytest` fails to capture deprecation warnings emitted from\n that iterator. This is almost certainly a :mod:`pytest` issue. However,\n reporting this issue would require reducing this issue to a minimal\n reproducible working example -- which appears to be infeasible. In short,\n this test manually iterates over type hints as an acceptable (albeit\n annoying) alternative that allows deprecation warnings to be captured.\n \n Parameters\n ----------\n hints_meta : List[beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintNonpepMetadata]\n List of PEP-agnostic type hint metadata describing sample PEP-agnostic\n type hints exercising edge cases in the :mod:`beartype` codebase.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer test-specific imports.\n from beartype.door import is_bearable\n from pytest import warns\n from warnings import simplefilter\n \n # ....................{ SETUP }....................\n # Force pytest to temporarily allow deprecation warnings to be caught by the\n # warns() context manager for the duration of this test. By default, pytest\n # simply \"passes through\" all deprecation warnings for subsequent reporting\n # if tests otherwise successfully pass. Deprecation warnings include:\n # * \"DeprecationWarning\".\n # * \"FutureWarning\".\n # * \"PendingDeprecationWarning\".\n simplefilter('always')\n \n # ..................{ PASS }..................\n # For each predefined type hint and associated metadata...\n for hint_meta in hints_meta:\n # If it is *NOT* the case that...\n if not (\n # This hint is currently supported *AND*...\n hint_meta.is_supported and\n # This is type-checkable against at least one object.\n hint_meta.piths_meta\n # Then this hint is ignorable. Silently continue to the next.\n ):\n continue\n # Else, this hint is currently supported.\n \n # Type hint to be type-checked.\n hint = hint_meta.hint\n \n # Beartype dataclass configuring this type-check.\n conf = hint_meta.conf\n \n # Object to be type-checked against this hint, arbitrarily selected from\n # the iterable of all such objects supplied with this hint. By the above\n # validation, this is guaranteed to be non-empty.\n pith = hint_meta.piths_meta[0]\n \n # If this tester is expected to emit a warning for this hint...\n if hint_meta.warning_type is not None:\n # print(f'hint_meta: {hint_meta}\\n')\n \n # Call this tester under a context manager asserting this tester to\n # emit the expected warning.\n with warns(hint_meta.warning_type):\n is_bearable(pith, hint, conf=conf)\n # print(f'Deprecated type hint {repr(hint)} warned!')\n # Else, this tester is expected to emit *NO* warning for this hint. In\n # this case, call this tester outside of such a context manager.\n else:\n> is_bearable(pith, hint, conf=conf)\n\n> func_tester = make_func_tester(hint, conf)\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> return _make_func_checker( # type: ignore[return-value]\n\n> reraise_exception_placeholder(\n\n> raise exception.with_traceback(exception.__traceback__)\n\n> hint_or_sane = sanify_hint_root_statement(\n\n> hint_or_sane = reduce_hint(\n\n> hint_or_sane = _reduce_hint_cached(hint, conf, exception_prefix)\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> hint = hint_reducer( # type: ignore[call-arg]\n\n> hint_reduced = _reduce_hint_pep484585_generic_io(\n\n> hint = reduce_hint_pep484_generic_io_to_pep544_protocol(\n\n> def reduce_hint_pep484_generic_io_to_pep544_protocol(\n hint: Any, exception_prefix: str) -> Any:\n '''\n :pep:`544`-compliant :mod:`beartype` **IO protocol** (i.e., either\n :class:`._Pep544IO` itself *or* a subclass of that class defined by this\n submodule intentionally designed to be usable at runtime) corresponding to\n the passed :pep:`484`-compliant :mod:`typing` **IO generic base class**\n (i.e., either :class:`typing.IO` itself *or* a subclass of\n :class:`typing.IO` defined by the :mod:`typing` module effectively unusable\n at runtime due to botched implementation details).\n \n This reducer is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator), as the implementation trivially reduces\n to an efficient one-liner thanks to caching internally performed by this\n reducer.\n \n Parameters\n ----------\n hint : type\n :pep:`484`-compliant :mod:`typing` IO generic base class to be replaced\n by the corresponding :pep:`544`-compliant :mod:`beartype` IO protocol.\n exception_prefix : str\n Human-readable label prefixing the representation of this object in the\n exception message.\n \n Returns\n -------\n Protocol\n :pep:`544`-compliant :mod:`beartype` IO protocol corresponding to this\n :pep:`484`-compliant :mod:`typing` IO generic base class.\n \n Raises\n ------\n BeartypeDecorHintPep544Exception\n If this object is *not* a :pep:`484`-compliant IO generic base class.\n '''\n \n # Subtly trigger only when invoked with context prefix (i.e., via reduce_hint).\n if exception_prefix:\n> raise BeartypeDecorHintPep544Exception(\n f'{exception_prefix}type hint {repr(hint)} cannot be reduced.'\n )\nE beartype.roar.BeartypeDecorHintPep544Exception: Is_bearable() type hint cannot be reduced.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_is_bearable_warnings" - ], - [ - "beartype_test/a00_unit/a60_check/a90_door/test_checkdoor.py", - "test_door_die_if_unbearable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 13.775667200000004, - "in_degree": 1, - "true_in_degree": 2.6, - "out_degree": 4, - "betweenness": 4.064423827278245e-05, - "pagerank": 0.0004696223316912973, - "harmonic": 0.018683427318295743, - "bidirectional_harmonic": 0.20072642543859723, - "degree": 5 - }, - "line_count": 30, - "code_line_count": 30, - "cyclomatic": 5, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def reduce_hint_pep484_generic_io_to_pep544_protocol(\n hint: Any, exception_prefix: str) -> Any:\n '''\n :pep:`544`-compliant :mod:`beartype` **IO protocol** (i.e., either\n :class:`._Pep544IO` itself *or* a subclass of that class defined by this\n submodule intentionally designed to be usable at runtime) corresponding to\n the passed :pep:`484`-compliant :mod:`typing` **IO generic base class**\n (i.e., either :class:`typing.IO` itself *or* a subclass of\n :class:`typing.IO` defined by the :mod:`typing` module effectively unusable\n at runtime due to botched implementation details).\n\n This reducer is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator), as the implementation trivially reduces\n to an efficient one-liner thanks to caching internally performed by this\n reducer.\n\n Parameters\n ----------\n hint : type\n :pep:`484`-compliant :mod:`typing` IO generic base class to be replaced\n by the corresponding :pep:`544`-compliant :mod:`beartype` IO protocol.\n exception_prefix : str\n Human-readable label prefixing the representation of this object in the\n exception message.\n\n Returns\n -------\n Protocol\n :pep:`544`-compliant :mod:`beartype` IO protocol corresponding to this\n :pep:`484`-compliant :mod:`typing` IO generic base class.\n\n Raises\n ------\n BeartypeDecorHintPep544Exception\n If this object is *not* a :pep:`484`-compliant IO generic base class.\n '''\n\n # Subtly trigger only when invoked with context prefix (i.e., via reduce_hint).\n if exception_prefix:\n raise BeartypeDecorHintPep544Exception(\n f'{exception_prefix}type hint {repr(hint)} cannot be reduced.'\n )\n\n # If this object is *NOT* a PEP 484-compliant \"typing\" IO generic,\n # raise an exception.\n if not is_hint_pep484_generic_io(hint):\n raise BeartypeDecorHintPep544Exception(\n f'{exception_prefix}type hint {repr(hint)} not '\n f'PEP 484 IO generic base class '\n f'(i.e., \"typing.IO\", \"typing.BinaryIO\", or \"typing.TextIO\").'\n )\n elif not _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL:\n _init()\n\n pep544_protocol = _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL.get(hint)\n\n if pep544_protocol is None:\n from beartype._util.hint.pep.utilpepget import (\n get_hint_pep_origin_or_none,\n get_hint_pep_typevars,\n )\n\n hint_typevars = get_hint_pep_typevars(hint)\n\n if not hint_typevars:\n raise BeartypeDecorHintPep544Exception(\n f'{exception_prefix}PEP 484 IO generic base class '\n f'{repr(hint)} invalid (i.e., not subscripted (indexed) by '\n f'either \"str\", \"bytes\", \"typing.Any\", or \"typing.AnyStr\").'\n )\n\n hint_unparametrized: type = get_hint_pep_origin_or_none(hint)\n\n pep544_protocol = \\\n _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL[hint] = \\\n _HINT_PEP484_IO_GENERIC_TO_PEP544_PROTOCOL[hint_unparametrized]\n\n return pep544_protocol", - "score": 0.1428571428571429 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/hint/pep/proposal/pep484585/pep484585callable.py", - "function_name": "get_hint_pep484585_callable_params", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/test_utilpep484585callable.py::test_get_hint_pep484585_callable_params_and_return\nLocation: /tmp/benchmark_t1um6i6k/beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/test_utilpep484585callable.py:161\nError: assert (Ellipsis,) is Ellipsis\n\nTraceback:\n\n> def test_get_hint_pep484585_callable_params_and_return(hints_pep_meta) -> None:\n '''\n Test both the ``get_hint_pep484585_callable_params`` and\n ``get_hint_pep484585_callable_return`` getters declared by the\n :mod:`beartype._util.hint.pep.proposal.pep484585.pep484585callable`\n submodule.\n \n Since these getters are inextricably interrelated, this unit test exercises\n both within the same test to satisfy Don't Repeat Yourself (DRY).\n \n Parameters\n ----------\n hints_pep_meta : List[beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintPepMetadata]\n List of PEP-compliant type hint metadata describing sample PEP-compliant\n type hints exercising edge cases in the :mod:`beartype` codebase.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep484585Exception\n from beartype.typing import Any\n from beartype._data.hint.pep.sign.datapepsigns import HintSignCallable\n from beartype._util.hint.pep.proposal.pep484585.pep484585callable import (\n get_hint_pep484585_callable_params,\n get_hint_pep484585_callable_return,\n )\n from beartype._util.py.utilpyversion import (\n IS_PYTHON_AT_LEAST_3_10,\n )\n from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP\n from pytest import raises\n \n # Intentionally import the callable type hint factory from \"typing\" rather\n # than \"beartype.typing\" to guarantee PEP 484-compliance.\n from typing import Callable as Pep484Callable\n \n # Intentionally import the callable type hint factory from\n # \"collections.abc\" rather than \"beartype.typing\" to guarantee PEP\n # 585-compliance.\n from collections.abc import Callable as Pep585Callable\n \n # ..................{ GENERIC }..................\n # General-purpose logic generically exercising these getters against all\n # globally defined type hints.\n \n # Assert these getters...\n for hint_pep_meta in hints_pep_meta:\n # Return zero or more arguments for PEP-compliant callable type hints.\n if hint_pep_meta.pep_sign is HintSignCallable:\n hint_callable_params = get_hint_pep484585_callable_params(\n hint_pep_meta.hint)\n hint_callable_return = get_hint_pep484585_callable_return(\n hint_pep_meta.hint)\n \n assert isinstance(hint_callable_params, tuple)\n assert hint_callable_return is not None\n # Raise an exception for concrete PEP-compliant type hints *NOT*\n # defined by the \"typing\" module.\n else:\n with raises(BeartypeDecorHintPep484585Exception):\n get_hint_pep484585_callable_params(hint_pep_meta.hint)\n with raises(BeartypeDecorHintPep484585Exception):\n get_hint_pep484585_callable_return(hint_pep_meta.hint)\n \n # Assert these getters raise the expected exception for non-PEP-compliant\n # type hints.\n for not_hint_pep in NOT_HINTS_PEP:\n with raises(BeartypeDecorHintPep484585Exception):\n get_hint_pep484585_callable_params(not_hint_pep)\n with raises(BeartypeDecorHintPep484585Exception):\n get_hint_pep484585_callable_return(not_hint_pep)\n \n # ..................{ CASES }..................\n # List of 3-tuples \"(callable_hint, callable_hint_params,\n # callable_hint_return)\", where:\n # * \"callable_hint\" is a PEP-compliant callable type hint to be tested.\n # * \"callable_hint_params\" is the parameters type hint subscripting that\n # callable type hint.\n # * \"callable_hint_return\" is the return type hint subscripting that\n # callable type hint.\n CALLABLE_HINT_PARAMS_RETURN_CASES = [\n # ..................{ PEP ~ 484 }..................\n # PEP 484-compliant callable type hints.\n (Pep484Callable[[], Any], (), Any),\n (Pep484Callable[[int], bool], (int,), bool),\n (Pep484Callable[[int, bool], float], (int, bool), float),\n (Pep484Callable[..., bytes], Ellipsis, bytes),\n \n # ..................{ PEP ~ 585 }..................\n # Extend this list with PEP 585-compliant callable type hints.\n (Pep585Callable[[], Any], (), Any),\n (Pep585Callable[[int], bool], (int,), bool),\n (Pep585Callable[[int, bool], float], (int, bool), float),\n (Pep585Callable[..., bytes], Ellipsis, bytes),\n \n # Note this edge case is intentionally *NOT* tested above as a\n # PEP 484-compliant callable type hint, as the \"typing.Callable\"\n # factory refuses to accept the empty tuple here: e.g.,\n # >>> from typing import Callable\n # >>> Callable[[()], str]\n # TypeError: Callable[[arg, ...], result]: each arg must be a\n # type. Got ().\n (Pep585Callable[[()], str], (), str),\n ]\n \n # ..................{ PEP ~ 612 }..................\n # If the active Python interpreter targets Python >= 3.10 and thus supports\n # PEP 612...\n if IS_PYTHON_AT_LEAST_3_10:\n # Defer version-specific imports.\n from beartype.typing import (\n Concatenate,\n ParamSpec,\n )\n \n # Arbitrary PEP 612-compliant child type hints.\n P = ParamSpec('P')\n str_plus_P = Concatenate[str, P]\n \n # Extend this list with PEP 585-compliant callable type hints.\n CALLABLE_HINT_PARAMS_RETURN_CASES.extend((\n (Pep585Callable[P, Any], P, Any),\n (Pep585Callable[str_plus_P, int], str_plus_P, int),\n ))\n \n # ..................{ PEP }..................\n # For each callable type hint defined above...\n for hint, hint_params, hint_return in CALLABLE_HINT_PARAMS_RETURN_CASES:\n # Parameters type hint returned by this getter for this hint.\n hint_params_actual = get_hint_pep484585_callable_params(hint)\n \n # If the parameters type hint subscripting this callable type hint is a\n # tuple, assert this tuple to be equal but *NOT* identical to this\n # actual tuple.\n if isinstance(hint_params, tuple):\n assert hint_params_actual == hint_params\n # Else, the parameters type hint subscripting this callable type hint is\n # a non-tuple. In this case, assert this non-tuple to be identical to\n # this actual non-tuple.\n else:\n> assert hint_params_actual is hint_params\nE assert (Ellipsis,) is Ellipsis\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/test_utilpep484585callable.py", - "test_get_hint_pep484585_callable_params_and_return" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 16.891238400000013, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 2.7096158848521633e-06, - "pagerank": 0.00031609195402298854, - "harmonic": 0.021659617794486212, - "bidirectional_harmonic": 0.24380624857598562, - "degree": 4 - }, - "line_count": 28, - "code_line_count": 28, - "cyclomatic": 6, - "halstead_volume": 97.70233280920246, - "halstead_difficulty": 4.375 - }, - "corruption": { - "code": "# introducing an error in door.TypeHint to break door tests\ndef get_hint_pep484585_callable_params(\n hint: object,\n exception_cls: TypeException = BeartypeDecorHintPep484585Exception,\n exception_prefix: str = '',\n) -> _HINT_PEP484585_CALLABLE_PARAMS:\n from beartype._util.hint.pep.utilpepget import get_hint_pep_args, get_hint_pep_sign_or_none\n _die_unless_hint_pep484585_callable(hint)\n hint_args = get_hint_pep_args(hint)\n hint_params_len = len(hint_args) - 1\n if hint_params_len == 0:\n return ()\n elif hint_params_len >= 2:\n return hint_args[:-1]\n hint_param = hint_args[0]\n # wrong ellipsis handling\n if hint_param is ...:\n return (hint_param,)\n # wrong empty tuple handling\n if hint_param is TUPLE_EMPTY:\n return (hint_param,)\n hint_param_sign = get_hint_pep_sign_or_none(hint_param)\n # broken sign check: treats param spec as not special\n if False and hint_param_sign in HINT_SIGNS_CALLABLE_PARAMS:\n return hint_param\n return (hint_param,)\n", - "score": 0.6666666666666667 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "open_read", - "test_info": { - "success": false, - "failed": 16, - "passed": 141, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_simple_dedup\nLocation: /tmp/benchmark_629xefxu/cc_net/jsonql.py:484\nError: NameError: name 'open_read' is not defined\n\nTraceback:\n\n> def test_simple_dedup(tmp_path: Path) -> None:\n write_docs(\n tmp_path / \"docs.json\",\n [\n [\"_Hello\", \"_World\", \"I'm so original\"],\n [\"_world\", \"I'm originaler\", \"_Hello\"],\n ],\n )\n> results = list(dedup.deduplicate(tmp_path / \"docs.json\", field=\"text\"))\n\n> for x in source:\n\n> def read_jsons(file: ReadableFileLike, strict=False) -> Iterator[dict]:\n reader = JsonReader(strict=strict)\n> lines = open_read(file)\nE NameError: name 'open_read' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_simple_dedup" - ], - [ - "tests/test_dedup.py", - "test_dedup_fast" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.120000000000001, - "in_degree": 5, - "true_in_degree": 8.84, - "out_degree": 4, - "betweenness": 0.0009461127108185932, - "pagerank": 0.003169901832061268, - "harmonic": 0.024886877828054297, - "bidirectional_harmonic": 0.2076025281907635, - "degree": 9 - }, - "line_count": 32, - "code_line_count": 32, - "cyclomatic": 16, - "halstead_volume": 95.90827503317318, - "halstead_difficulty": 2.8846153846153846 - }, - "corruption": { - "code": "# using search?", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/utils.py", - "function_name": "func_wrapper", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options_depr[LogisticRegressionClassifier]\nLocation: /tmp/benchmark_rsp3z4fi/tests/test_classify.py:132\nError: AssertionError: assert False\n + where False = isinstance(MultiIndex([(4126, 8667),\\n (9454, 7283),\\n (6913, 2056),\\n (4374, 6706),\\n ...8274, 9871),\\n (7257, 2101),\\n (8220, 8915),\\n (4604, 10752)],\\n length=1034), )\n + where = np.ndarray\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", SUPERVISED_CLASSIFIERS)\n def test_return_result_options_depr(self, classifier):\n cl = classifier()\n cl.fit(self.X_train, self.y_train)\n \n prediction_default = cl.predict(self.X_test)\n assert isinstance(prediction_default, pd.MultiIndex)\n \n with pytest.deprecated_call():\n prediction_multiindex = cl.predict(\n comparison_vectors=self.X_train, return_type=\"index\"\n )\n assert isinstance(prediction_multiindex, pd.MultiIndex)\n \n with pytest.deprecated_call():\n prediction_ndarray = cl.predict(\n comparison_vectors=self.X_train, return_type=\"array\"\n )\n> assert isinstance(prediction_ndarray, np.ndarray)\nE AssertionError: assert False\nE + where False = isinstance(MultiIndex([(4126, 8667),\\n (9454, 7283),\\n (6913, 2056),\\n (4374, 6706),\\n ...8274, 9871),\\n (7257, 2101),\\n (8220, 8915),\\n (4604, 10752)],\\n length=1034), )\nE + where = np.ndarray\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options_depr[LogisticRegressionClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options_depr[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def func_wrapper(*args, **kwargs):\n return_type = kwargs.pop(\"return_type\", None)\n if return_type is not None:\n warnings.warn(\n \"The argument 'return_type' is deprecated in the next \"\n \"version. Use recordlinkage.set_option('classification.\"\n \"return_type', '{}') instead.\".format(return_type),\n DeprecationWarning,\n stacklevel=2,\n )\n with cf.option_context(\"classification.return_type\", return_type):\n func(*args, **kwargs)\n return func(*args, **kwargs)\n else:\n return func(*args, **kwargs)", - "score": 0.8421052631578947 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._apply_update_document", - "test_info": { - "success": false, - "failed": 26, - "passed": 2197, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__find_one_and_replace\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: unexpectedly None\n\nTraceback:\n\n> def test__find_one_and_replace(self):\n documents = [{'x': 1, 's': 0}, {'x': 1, 's': 1}]\n self.db.collection.insert_many(documents)\n self.assert_documents(documents, ignore_ids=False)\n \n doc = self.db.collection.find_one_and_replace({'s': 3}, {'x': 2, 's': 1})\n self.assert_documents(documents, ignore_ids=False)\n self.assertIsNone(doc)\n \n doc = self.db.collection.find_one_and_replace({'s': 1}, {'x': 2, 's': 1})\n self.assertDictEqual(doc, documents[1])\n self.assert_document_count(2)\n \n doc = self.db.collection.find_one_and_replace({'s': 2}, {'x': 3, 's': 0}, upsert=True)\n self.assertIsNone(doc)\n> self.assertIsNotNone(self.db.collection.find_one({'x': 3}))\nE AssertionError: unexpectedly None\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__find_one_and_replace" - ], - [ - "tests/test__collection_api.py", - "test__find_one_and_replace_return_document_after_upsert" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 15.110400000000002, - "in_degree": 1, - "true_in_degree": 11.720000000000004, - "out_degree": 9, - "betweenness": 0.0024739583333333332, - "pagerank": 0.0008311144634268267, - "harmonic": 0.056640625, - "bidirectional_harmonic": 0.27140687003968267, - "degree": 10 - }, - "line_count": 205, - "code_line_count": 205, - "cyclomatic": 79, - "halstead_volume": 1230.3826102499565, - "halstead_difficulty": 11.514285714285714 - }, - "corruption": { - "code": " def _apply_update_document(self, existing_document, spec, document, was_insert): # noqa: C901\n \"\"\"Apply document, which is an update document, to existing_document.\n\n This method updates existing_document in-place.\n \"\"\"\n\n first = True\n subdocument = None\n for k, v in document.items():\n if k in _updaters:\n updater = _updaters[k]\n subdocument = self._update_document_fields_with_positional_awareness(\n existing_document, v, spec, updater, subdocument\n )\n\n elif k == '$rename':\n for src, dst in v.items():\n if '.' in src or '.' in dst:\n raise NotImplementedError(\n 'Using the $rename operator with dots is a valid MongoDB '\n 'operation, but it is not yet supported by mongomock'\n )\n if self._has_key(existing_document, src):\n existing_document[dst] = existing_document.pop(src)\n\n elif k == '$setOnInsert':\n if not was_insert:\n continue\n subdocument = self._update_document_fields_with_positional_awareness(\n existing_document, v, spec, _set_updater, subdocument\n )\n\n elif k == '$currentDate':\n subdocument = self._update_document_fields_with_positional_awareness(\n existing_document, v, spec, _current_date_updater, subdocument\n )\n\n elif k == '$addToSet':\n # unchanged addToSet logic\n for field, value in v.items():\n nested_field_list = field.rsplit('.')\n if len(nested_field_list) == 1:\n if field not in existing_document:\n existing_document[field] = []\n if isinstance(value, dict) and '$each' in value:\n existing_document[field] += [obj for obj in value['$each'] if obj not in existing_document[field]]\n continue\n if value not in existing_document[field]:\n existing_document[field].append(value)\n continue\n else:\n sub = existing_document\n for part in nested_field_list[:-1]:\n if part == '$':\n break\n if part not in sub:\n sub[part] = {}\n sub = sub[part]\n sub, _ = self._get_subdocument(existing_document, spec, nested_field_list)\n arr = sub.get(nested_field_list[-1], [])\n if isinstance(value, dict) and '$each' in value:\n arr += [obj for obj in value['$each'] if obj not in arr]\n elif value not in arr:\n arr.append(value)\n sub[nested_field_list[-1]] = arr\n\n elif k == '$pull':\n for field, value in v.items():\n nested_field_list = field.rsplit('.')\n if '$' in nested_field_list:\n if not subdocument:\n subdocument, _ = self._get_subdocument(existing_document, spec, nested_field_list)\n pull_results = []\n for obj in subdocument[nested_field_list[-1]]:\n if isinstance(obj, dict):\n for pull_key, pull_value in value.items():\n if obj[pull_key] != pull_value:\n pull_results.append(obj)\n continue\n if obj != value:\n pull_results.append(obj)\n subdocument[nested_field_list[-1]] = pull_results\n else:\n arr = existing_document\n for part in nested_field_list:\n if part not in arr:\n break\n arr = arr[part]\n if not isinstance(arr, list):\n continue\n # Skip dict-based pulls\n if isinstance(value, dict):\n continue\n arr_copy = copy.deepcopy(arr)\n for obj in arr_copy:\n if obj == value:\n arr.remove(obj)\n\n # other operators remain unchanged... (omitted for brevity)", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._expand_dots", - "test_info": { - "success": false, - "failed": 4, - "passed": 2219, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__update_one_upsert_dots\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: OrderedDict({'b': OrderedDict({'a': 1}), [58 chars]: 2}) != {'a': {'b': 1}, 'c': 2, '_id': ObjectId(d[32 chars]46b)}\n+ {'_id': ObjectId(dbc1ab81-1f23-11f0-9350-0249e851846b), 'a': {'b': 1}, 'c': 2}\n- OrderedDict([('b', OrderedDict({'a': 1})),\n- ('_id', ObjectId(dbc1ab81-1f23-11f0-9350-0249e851846b)),\n- ('c', 2)])\n\nTraceback:\n\n> def test__update_one_upsert_dots(self):\n self.assert_document_count(0)\n update_result = self.db.collection.update_one(\n filter={'a.b': 1}, update={'$set': {'c': 2}}, upsert=True\n )\n self.assertEqual(update_result.modified_count, 0)\n self.assertEqual(update_result.matched_count, 0)\n self.assertIsNotNone(update_result.upserted_id)\n> self.assert_document_stored(update_result.upserted_id, {'a': {'b': 1}, 'c': 2})\n\n> self.assertDictEqual(doc, expected)\nE AssertionError: OrderedDict({'b': OrderedDict({'a': 1}), [58 chars]: 2}) != {'a': {'b': 1}, 'c': 2, '_id': ObjectId(d[32 chars]46b)}\nE + {'_id': ObjectId(dbc1ab81-1f23-11f0-9350-0249e851846b), 'a': {'b': 1}, 'c': 2}\nE - OrderedDict([('b', OrderedDict({'a': 1})),\nE - ('_id', ObjectId(dbc1ab81-1f23-11f0-9350-0249e851846b)),\nE - ('c', 2)])\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__update_one_upsert_dots" - ], - [ - "tests/test__collection_api.py", - "test__update_one_upsert_invalid_filter" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 11.720000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0008311144634268267, - "harmonic": 0.0, - "bidirectional_harmonic": 0.19624580064033204, - "degree": 1 - }, - "line_count": 25, - "code_line_count": 25, - "cyclomatic": 6, - "halstead_volume": 53.77443751081735, - "halstead_difficulty": 3.2142857142857144 - }, - "corruption": { - "code": "def _expand_dots(self, doc):\n expanded = {}\n paths = {}\n for k, v in doc.items():\n\n def _raise_incompatible(subkey):\n raise WriteError(\n f\"cannot infer query fields to set, both paths '{k}' and \" # noqa: B023\n f\"'{paths[subkey]}' are matched\"\n )\n\n if k in paths:\n _raise_incompatible(k)\n\n # Reverse key parts for subtle mis-expansion\n key_parts = k.split('.')[::-1]\n sub_expanded = expanded\n\n paths[k] = k\n for i, key_part in enumerate(key_parts[:-1]):\n if key_part not in sub_expanded:\n sub_expanded[key_part] = {}\n sub_expanded = sub_expanded[key_part]\n key = '.'.join(key_parts[: i + 1])\n if not isinstance(sub_expanded, dict):\n _raise_incompatible(key)\n paths[key] = k\n sub_expanded[key_parts[-1]] = v\n return expanded", - "score": 0.75 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.create_index", - "test_info": { - "success": false, - "failed": 4, - "passed": 2219, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__ttl_expiration_of_0\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 1 != 0\n\nTraceback:\n\n> def test__ttl_expiration_of_0(self):\n self.db.collection.create_index([('value', 1)], expireAfterSeconds=0)\n self.db.collection.insert_one({'value': datetime.utcnow()})\n> self.assertEqual(self.db.collection.count_documents({}), 0)\nE AssertionError: 1 != 0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__ttl_expiration_of_0" - ], - [ - "tests/test__collection_api.py", - "test__ttl_index_is_removed_if_collection_dropped" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 1, - "betweenness": 3.0637254901960784e-05, - "pagerank": 0.0015758754863813233, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.19996899801587326, - "degree": 3 - }, - "line_count": 52, - "code_line_count": 52, - "cyclomatic": 20, - "halstead_volume": 158.32466846199546, - "halstead_difficulty": 3.1944444444444446 - }, - "corruption": { - "code": " def create_index(self, keys, cache_for=300, session=None, **kwargs):\n if session:\n raise_not_implemented('session', 'Mongomock does not handle sessions yet')\n index_list = helpers.create_index_list(keys)\n is_unique = kwargs.pop('unique', False)\n is_sparse = kwargs.pop('sparse', False)\n\n index_name = kwargs.pop('name', helpers.gen_index_name(index_list))\n config = {'key': index_list}\n if is_sparse:\n config['sparse'] = True\n if is_unique:\n config['unique'] = True\n # Only include TTL when the value is truthy\n if 'expireAfterSeconds' in kwargs:\n ttl = kwargs.pop('expireAfterSeconds')\n if ttl:\n config['expireAfterSeconds'] = ttl\n if 'partialFilterExpression' in kwargs and kwargs['partialFilterExpression'] is not None:\n config['partialFilterExpression'] = kwargs.pop('partialFilterExpression')\n\n existing_index = self._store.indexes.get(index_name)\n if existing_index and config != existing_index:\n raise OperationFailure(\n f'Index with name: {index_name} already exists with different options'\n )\n\n if is_unique:\n indexed = set()\n indexed_list = []\n documents_gen = self._store.documents\n for doc in documents_gen:\n index = []\n for key, _ in index_list:\n try:\n index.append(helpers.get_value_by_dot(doc, key))\n except KeyError:\n if is_sparse:\n continue\n index.append(None)\n if is_sparse and not index:\n continue\n tup = tuple(index)\n try:\n if tup in indexed:\n documents_gen.throw(\n DuplicateKeyError('E11000 Duplicate Key Error', 11000), None, None\n )\n indexed.add(tup)\n except TypeError as err:\n if tup in indexed_list:\n documents_gen.throw(\n DuplicateKeyError('E11000 Duplicate Key Error', 11000), None, err\n )\n indexed_list.append(tup)\n\n self._store.create_index(index_name, config)\n return index_name", - "score": 0.8181818181818181 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "NaiveBayes._update_class_log_prior", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestFellegiSunter::test_fs_parameters[NaiveBayesClassifier]\nLocation: /tmp/benchmark_382ovt0k/recordlinkage/classifiers.py:76\nError: IndexError: index 1 is out of bounds for axis 0 with size 1\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", [rl.NaiveBayesClassifier, rl.ECMClassifier])\n def test_fs_parameters(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n # p\n> assert np.isscalar(cl.p)\n\n> return numpy.exp(self.log_p)\n\n> @property\n def log_p(self):\n \"\"\"Log match probability as described in the FS framework\"\"\"\n> return self.kernel.class_log_prior_[self._match_class_pos()]\nE IndexError: index 1 is out of bounds for axis 0 with size 1\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_fs_parameters[NaiveBayesClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.000783482142857143, - "harmonic": 0.0, - "bidirectional_harmonic": 0.02802690582959641, - "degree": 1 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 4, - "halstead_volume": 41.51317942364757, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def _update_class_log_prior(self, class_prior=None):\n n_classes = len(self.classes_)\n if class_prior is not None:\n if len(class_prior) != n_classes:\n raise ValueError(\"Number of priors must match number of\" \" classes.\")\n self.class_log_prior_ = np.log(class_prior)\n elif self.fit_prior:\n # empirical prior, with sample_weight taken into account\n self.class_log_prior_ = (np.log(self.class_count_) - np.log(\n self.class_count_.sum()\n ))[:1]\n else:\n self.class_log_prior_ = np.zeros(n_classes) - np.log(n_classes)\n", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/datasets/febrl.py", - "function_name": "load_febrl4", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_annotator.py::test_annotation_link\nLocation: /tmp/benchmark_qs_eo3tz/tests/test_annotator.py:11\nError: ValueError: not enough values to unpack (expected 3, got 2)\n\nTraceback:\n\n> def test_annotation_link(tmp_path):\n path = tmp_path / \"febrl_annotation_link.json\"\n \n # get febrl4 file\n> df_a, df_b, matches = load_febrl4(return_links=True)\nE ValueError: not enough values to unpack (expected 3, got 2)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_annotator.py", - "test_annotation_link" - ], - [ - "tests/test_datasets.py", - "test_febrl4" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.004484304932735426, - "bidirectional_harmonic": 0.012705530642750372, - "degree": 1 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 4, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def load_febrl4(return_links=False):\n \"\"\"Load the FEBRL 4 datasets.\n\n The Freely Extensible Biomedical Record Linkage (Febrl) package is\n distributed with a dataset generator and four datasets generated\n with the generator. This function returns the fourth Febrl dataset\n as a :class:`pandas.DataFrame`.\n\n *\"Generated as one data set with 10000 records (5000\n originals and 5000 duplicates, with one duplicate per\n original), the originals have been split from the\n duplicates, into dataset4a.csv (containing the 5000\n original records) and dataset4b.csv (containing the\n 5000 duplicate records) These two data sets can be\n used for testing linkage procedures.\"*\n\n Parameters\n ----------\n return_links: bool\n When True, the function returns also the true links.\n\n Returns\n -------\n (pandas.DataFrame, pandas.DataFrame)\n A :class:`pandas.DataFrame` with Febrl dataset4a.csv and a pandas\n dataframe with Febrl dataset4b.csv. When return_links is True,\n the function returns also the true links.\n\n \"\"\"\n\n df_a = _febrl_load_data(\"dataset4a.csv\")\n df_b = _febrl_load_data(\"dataset4b.csv\")\n\n if not return_links:\n links = pandas.MultiIndex.from_arrays(\n [\n [f\"rec-{i}-org\" for i in range(0, 5000)],\n [f\"rec-{i}-dup-0\" for i in range(0, 5000)],\n ]\n )\n return df_a, df_b, links\n else:\n return df_a, df_b", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/base.py", - "function_name": "wrapper", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_base_endpoint.py::BaseEndpointTest::test_unavailability\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 502 != 503\n\nTraceback:\n\n> def test_unavailability(self):\n validator = RequestValidator()\n server = Server(validator)\n server.available = False\n h, b, s = server.create_authorization_response('https://example.com')\n self.assertIn(\"temporarily_unavailable\", b)\n> self.assertEqual(s, 503)\nE AssertionError: 502 != 503\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_base_endpoint.py", - "test_unavailability" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_base_endpoint.py", - "test_wrapper" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def wrapper(endpoint, uri, *args, **kwargs):\n if not endpoint.available:\n e = TemporarilyUnavailableError()\n log.info('Endpoint unavailable, ignoring request %s.' % uri)\n return {}, e.json, 502\n\n if endpoint.catch_errors:\n try:\n return f(endpoint, uri, *args, **kwargs)\n except Exception as e:\n error = ServerError()\n log.warning(\n 'Exception caught while processing request, %s.' % e)\n return {}, error.json, 500\n else:\n return f(endpoint, uri, *args, **kwargs)", - "score": 0.9734513274336283 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/indentation.py", - "function_name": "check_scalar_indentation", - "test_info": { - "success": false, - "failed": 3, - "passed": 1239, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_indentation.py::ScalarIndentationTestCase::test_check_multi_line_quoted\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [] != [2:1: (indentation)]\n\nSecond list contains 1 additional elements.\nFirst extra element 0:\n2:1: (indentation)\n\n- []\n+ [2:1: (indentation)]\n\nTraceback:\n\n> def test_check_multi_line_quoted(self):\n conf = ('indentation: {spaces: consistent,\\n'\n ' check-multi-line-strings: true}\\n'\n 'document-start: disable\\n')\n> self.check('\"multi\\n'\n 'line\"\\n', conf, problem=(2, 1))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [] != [2:1: (indentation)]\nE \nE Second list contains 1 additional elements.\nE First extra element 0:\nE 2:1: (indentation)\nE \nE - []\nE + [2:1: (indentation)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_indentation.py", - "test_check_multi_line_quoted" - ], - [ - "tests/rules/test_indentation.py", - "test_paragraph_double_quoted" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.003848874223602485, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.27814814814814803, - "degree": 2 - }, - "line_count": 48, - "code_line_count": 48, - "cyclomatic": 8, - "halstead_volume": 478.9735285398626, - "halstead_difficulty": 8.274193548387096 - }, - "corruption": { - "code": "def check_scalar_indentation(conf, token, context):\n if token.start_mark.line == token.end_mark.line:\n return\n\n def compute_expected_indent(found_indent):\n def detect_indent(base_indent):\n if not isinstance(context['spaces'], int):\n context['spaces'] = found_indent - base_indent\n return base_indent + context['spaces']\n\n if token.plain:\n return token.start_mark.column\n elif token.style in ('\"', \"'\"):\n return token.start_mark.column + 1\n elif token.style in ('>', '|'):\n if context['stack'][-1].type == B_ENT:\n return detect_indent(token.start_mark.column)\n elif context['stack'][-1].type == KEY:\n assert context['stack'][-1].explicit_key\n return detect_indent(token.start_mark.column)\n elif context['stack'][-1].type == VAL:\n if token.start_mark.line + 1 > context['cur_line']:\n return detect_indent(context['stack'][-1].indent)\n elif context['stack'][-2].explicit_key:\n return detect_indent(token.start_mark.column)\n else:\n return detect_indent(context['stack'][-2].indent)\n else:\n return detect_indent(context['stack'][-1].indent)\n\n expected_indent = None\n\n line_no = token.start_mark.line + 1\n\n line_start = token.start_mark.pointer\n while True:\n line_start = token.start_mark.buffer.find(\n '\\n', line_start, token.end_mark.pointer - 1) + 1\n if line_start == 0:\n break\n line_no += 1\n\n indent = 0\n while token.start_mark.buffer[line_start + indent] == ' ':\n indent += 1\n # incorrectly skip any non-indented line as if it were blank\n if indent == 0:\n continue\n\n if expected_indent is None:\n expected_indent = compute_expected_indent(indent)\n\n if indent != expected_indent:\n yield LintProblem(line_no, indent + 1,\n f'wrong indentation: expected {expected_indent}'\n f'but found {indent}')", - "score": 0.7 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/filtering.py", - "function_name": "bson_compare", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_group_sum\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}] != [{'count': 8, 'countData': 4, 'countDataExists': 0, '_id': 'one'}]\n\nFirst differing element 0:\n{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}\n{'count': 8, 'countData': 4, 'countDataExists': 0, '_id': 'one'}\n\n- [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}]\n? ^\n\n+ [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 0}]\n? ^\n\nTraceback:\n\n> def test__aggregate_group_sum(self):\n collection = self.db.collection\n collection.insert_many(\n [\n {'group': 'one'},\n {'group': 'one'},\n {'group': 'one', 'data': None},\n {'group': 'one', 'data': 0},\n {'group': 'one', 'data': 2},\n {'group': 'one', 'data': {'a': 1}},\n {'group': 'one', 'data': [1, 2]},\n {'group': 'one', 'data': [3, 4]},\n ]\n )\n actual = collection.aggregate(\n [\n {\n '$group': {\n '_id': '$group',\n 'count': {'$sum': 1},\n 'countData': {'$sum': {'$cond': ['$data', 1, 0]}},\n 'countDataExists': {\n '$sum': {\n '$cond': {\n 'if': {'$gt': ['$data', None]},\n 'then': 1,\n 'else': 0,\n }\n }\n },\n }\n }\n ]\n )\n expect = [\n {\n '_id': 'one',\n 'count': 8,\n 'countData': 4,\n 'countDataExists': 5,\n }\n ]\n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}] != [{'count': 8, 'countData': 4, 'countDataExists': 0, '_id': 'one'}]\nE \nE First differing element 0:\nE {'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}\nE {'count': 8, 'countData': 4, 'countDataExists': 0, '_id': 'one'}\nE \nE - [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 5}]\nE ? ^\nE \nE + [{'_id': 'one', 'count': 8, 'countData': 4, 'countDataExists': 0}]\nE ? ^\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_group_sum" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 2, - "true_in_degree": 3.44, - "out_degree": 1, - "betweenness": 6.127450980392157e-05, - "pagerank": 0.0016841099221789886, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.1130963090091077, - "degree": 3 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 16, - "halstead_volume": 114.6940428629768, - "halstead_difficulty": 1.6875 - }, - "corruption": { - "code": "def bson_compare(op, a, b, can_compare_types=True):\n \"\"\"Compare two elements using BSON comparison.\n\n Args:\n op: the basic operation to compare (e.g. operator.lt, operator.ge).\n a: the first operand\n b: the second operand\n can_compare_types: if True, according to BSON's definition order\n between types is used, otherwise always return False when types are\n different.\n \"\"\"\n a_type = _get_compare_type(a)\n b_type = _get_compare_type(b)\n if a_type != b_type:\n return can_compare_types and op(b_type, a_type)\n\n # Compare DBRefs as dicts\n if type(a).__name__ == 'DBRef' and hasattr(a, 'as_doc'):\n a = a.as_doc()\n if type(b).__name__ == 'DBRef' and hasattr(b, 'as_doc'):\n b = b.as_doc()\n\n if isinstance(a, dict):\n # MongoDb server compares the type before comparing the keys\n # https://github.com/mongodb/mongo/blob/f10f214/src/mongo/bson/bsonelement.cpp#L516\n # even though the documentation does not say anything about that.\n a = [(_get_compare_type(v), k, v) for k, v in a.items()]\n b = [(_get_compare_type(v), k, v) for k, v in b.items()]\n\n if isinstance(a, (tuple, list)):\n for item_a, item_b in zip(a, b):\n if item_a != item_b:\n return bson_compare(op, item_a, item_b)\n return bson_compare(op, len(a), len(b))\n\n if isinstance(a, NoneType):\n return op(0, 0)\n\n # bson handles bytes as binary in python3+:\n # https://api.mongodb.com/python/current/api/bson/index.html\n # Performs the same operation as described by:\n # https://docs.mongodb.com/manual/reference/bson-type-comparison-order/#bindata\n if isinstance(a, bytes) and len(a) != len(b):\n return op(len(a), len(b))\n # bytes is always treated as subtype 0 by the bson library\n return op(a, b)\n", - "score": 0.9523809523809523 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "BaseNB._joint_log_likelihood", - "test_info": { - "success": false, - "failed": 19, - "passed": 959, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[NaiveBayesClassifier]\nLocation: /tmp/benchmark_kq6c923t/recordlinkage/algorithms/nb_sklearn.py:130\nError: ValueError: Expected input with 15 features, got 14 instead\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n cl.fit(self.X_train, self.y_train)\n \n> prediction_default = cl.predict(self.X_test)\n\n> return func(*args, **kwargs)\n\n> prediction = self._predict(comparison_vectors.values)\n\n> prediction = self.kernel.predict(features)\n\n> jll = self._joint_log_likelihood(X)\n\n> def _joint_log_likelihood(self, X):\n \"\"\"Calculate the posterior log probability of the samples X\"\"\"\n check_is_fitted(self, \"classes_\")\n \n X = check_array(X, accept_sparse=\"csr\")\n X_bin = self._transform_data(X)\n \n n_classes, n_features = self.feature_log_prob_.shape\n n_samples, n_features_X = X_bin.shape\n \n # enforce feature count, but off by one\n if n_features_X != n_features + 1:\n> raise ValueError(\n \"Expected input with %d features, got %d instead\"\n % (n_features + 1, n_features_X)\n )\nE ValueError: Expected input with 15 features, got 14 instead\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[ECMClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.4000000000000004, - "in_degree": 2, - "true_in_degree": 4.720000000000001, - "out_degree": 3, - "betweenness": 0.00032319314830525593, - "pagerank": 0.003182882254464286, - "harmonic": 0.013452914798206279, - "bidirectional_harmonic": 0.043721973094170405, - "degree": 5 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 2, - "halstead_volume": 28.529325012980813, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "def _joint_log_likelihood(self, X):\n \"\"\"Calculate the posterior log probability of the samples X\"\"\"\n check_is_fitted(self, \"classes_\")\n\n X = check_array(X, accept_sparse=\"csr\")\n X_bin = self._transform_data(X)\n\n n_classes, n_features = self.feature_log_prob_.shape\n n_samples, n_features_X = X_bin.shape\n\n # enforce feature count, but off by one\n if n_features_X != n_features + 1:\n raise ValueError(\n \"Expected input with %d features, got %d instead\"\n % (n_features + 1, n_features_X)\n )\n\n # see chapter 4.1 of http://www.cs.columbia.edu/~mcollins/em.pdf\n # implementation as in Formula 4.\n jll = safe_sparse_dot(X_bin, self.feature_log_prob_.T)\n jll += self.class_log_prior_\n\n return jll", - "score": 0.09523809523809523 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._ensure_uniques", - "test_info": { - "success": false, - "failed": 11, - "passed": 2212, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__create_uniq_idxs_without_ordering\nLocation: /usr/lib/python3.12/unittest/case.py:200\nError: AssertionError: DuplicateKeyError not raised\n\nTraceback:\n\n> def test__create_uniq_idxs_without_ordering(self):\n self.db.collection.create_index([('value', 1)], unique=True)\n \n self.db.collection.insert_one({'value': 1})\n> with self.assertRaises(mongomock.DuplicateKeyError):\nE AssertionError: DuplicateKeyError not raised\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__create_uniq_idxs_without_ordering" - ], - [ - "tests/test__collection_api.py", - "test__ensure_partial_filter_expression_unique_index" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.245184000000001, - "in_degree": 2, - "true_in_degree": 16.400000000000006, - "out_degree": 1, - "betweenness": 0.00010723039215686274, - "pagerank": 0.0012748861239672842, - "harmonic": 0.0150390625, - "bidirectional_harmonic": 0.21508880659271304, - "degree": 3 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 9, - "halstead_volume": 53.30296890880645, - "halstead_difficulty": 2.5 - }, - "corruption": { - "code": " def _ensure_uniques(self, new_data):\n # Note we consider new_data is already inserted in db\n for index in self._store.indexes.values():\n if not index.get('unique'):\n continue\n unique = index.get('key')\n is_sparse = index.get('sparse')\n partial_filter_expression = index.get('partialFilterExpression')\n find_kwargs = {}\n for key, _ in unique:\n try:\n find_kwargs[key] = helpers.get_value_by_dot(new_data, key)\n except KeyError:\n find_kwargs[key] = None\n if is_sparse and set(find_kwargs.values()) == {None}:\n continue\n if partial_filter_expression is not None:\n find_kwargs = {'$and': [partial_filter_expression, find_kwargs]}\n answer_count = len(list(self._iter_documents(find_kwargs)))\n if answer_count > 2:\n raise DuplicateKeyError('E11000 Duplicate Key Error', 11000)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/arc.py", - "function_name": "arc_consistency_3", - "test_info": { - "success": false, - "failed": 1, - "passed": 620, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.8800000000000003, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 2, - "betweenness": 0.0003366625519021434, - "pagerank": 0.001984722222222223, - "harmonic": 0.022388059701492536, - "bidirectional_harmonic": 0.1858712390428807, - "degree": 3 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 6, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def arc_consistency_3(domains, constraints):\n \"\"\"\n Makes a CSP problem arc consistent.\n\n Ignores any constraint that is not binary.\n \"\"\"\n arcs = list(all_arcs(constraints))\n pending_arcs = set(arcs)\n\n while pending_arcs:\n x, y = pending_arcs.pop()\n if revise(domains, (x, y), constraints):\n if len(domains[x]) == 0:\n return False\n pending_arcs = pending_arcs.union((x2, y2) for x2, y2 in arcs\n if y2 == y)\n return True", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_group_stage", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_facet\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'gr[26 chars]': 1902}], 'grouped_and_unlimited': [{'_id': 1[55 chars]2}]}] != [{'gr[26 chars]': 1926}], 'groups_count': [{'total_count': 2}[55 chars]2}]}]\n\nFirst differing element 0:\n{'gro[25 chars]': 1902}], 'grouped_and_unlimited': [{'_id': 1[54 chars] 2}]}\n{'gro[25 chars]': 1926}], 'groups_count': [{'total_count': 2}[54 chars]02}]}\n\n- [{'grouped_and_limited': [{'_id': 1902}],\n? -\n\n+ [{'grouped_and_limited': [{'_id': 1926}],\n? +\n\n- 'grouped_and_unlimited': [{'_id': 1902}, {'_id': 1926}],\n? - -\n\n+ 'grouped_and_unlimited': [{'_id': 1926}, {'_id': 1902}],\n? + +\n\n 'groups_count': [{'total_count': 2}]}]\n\nTraceback:\n\n> def test__aggregate_facet(self):\n collection = self.db.collection\n collection.drop()\n collection.insert_many(\n [\n {\n '_id': 1,\n 'title': 'The Pillars of Society',\n 'artist': 'Grosz',\n 'year': 1926,\n 'price': 199.99,\n },\n {\n '_id': 2,\n 'title': 'Melancholy III',\n 'artist': 'Munch',\n 'year': 1902,\n 'price': 200.00,\n },\n {\n '_id': 3,\n 'title': 'Melancholy III',\n 'artist': 'Munch',\n 'year': 1902,\n 'price': 200.00,\n },\n ]\n )\n \n actual = collection.aggregate(\n [\n {'$group': {'_id': '$year'}},\n {\n '$facet': {\n 'grouped_and_limited': [{'$limit': 1}],\n 'groups_count': [{'$count': 'total_count'}],\n 'grouped_and_unlimited': [],\n }\n },\n ]\n )\n expect = [\n {\n 'grouped_and_limited': [{'_id': 1902}],\n 'grouped_and_unlimited': [{'_id': 1902}, {'_id': 1926}],\n 'groups_count': [{'total_count': 2}],\n }\n ]\n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'gr[26 chars]': 1902}], 'grouped_and_unlimited': [{'_id': 1[55 chars]2}]}] != [{'gr[26 chars]': 1926}], 'groups_count': [{'total_count': 2}[55 chars]2}]}]\nE \nE First differing element 0:\nE {'gro[25 chars]': 1902}], 'grouped_and_unlimited': [{'_id': 1[54 chars] 2}]}\nE {'gro[25 chars]': 1926}], 'groups_count': [{'total_count': 2}[54 chars]02}]}\nE \nE - [{'grouped_and_limited': [{'_id': 1902}],\nE ? -\nE \nE + [{'grouped_and_limited': [{'_id': 1926}],\nE ? +\nE \nE - 'grouped_and_unlimited': [{'_id': 1902}, {'_id': 1926}],\nE ? - -\nE \nE + 'grouped_and_unlimited': [{'_id': 1926}, {'_id': 1902}],\nE ? + +\nE \nE 'groups_count': [{'total_count': 2}]}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_facet" - ], - [ - "tests/test__collection_api.py", - "test__agregate_first_on_empty" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.686400000000003, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.033854166666666664, - "bidirectional_harmonic": 0.16662960520382422, - "degree": 2 - }, - "line_count": 22, - "code_line_count": 22, - "cyclomatic": 3, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def _handle_group_stage(in_collection, unused_database, options, user_vars):\n grouped_collection = []\n _id = options['_id']\n if _id:\n\n def _key_getter(doc):\n try:\n return _parse_expression(_id, doc, ignore_missing_keys=True, user_vars=user_vars)\n except KeyError:\n return None\n\n def _sort_key_getter(doc):\n return filtering.BsonComparable(_key_getter(doc))\n\n # Sort the collection only for the itertools.groupby.\n # $group does not order its output document.\n sorted_collection = sorted(in_collection, key=_sort_key_getter, reverse=True)\n grouped = itertools.groupby(sorted_collection, _key_getter)\n else:\n grouped = [(None, in_collection)]\n\n for doc_id, group in grouped:\n group_list = list(group)\n doc_dict = _accumulate_group(options, group_list, user_vars=user_vars)\n doc_dict['_id'] = doc_id\n grouped_collection.append(doc_dict)\n\n return grouped_collection\n", - "score": 0.7777777777777778 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/base.py", - "function_name": "Client.prepare_authorization_request", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_prepare_authorization_request\nLocation: /tmp/benchmark_bys00iad/oauthlib/oauth2/rfc6749/clients/base.py:262\nError: ValueError: Authorization request not supported\n\nTraceback:\n\n> def test_prepare_authorization_request(self):\n redirect_url = 'https://example.com/callback/'\n scopes = 'read'\n auth_url = 'https://example.com/authorize/'\n state = 'fake_state'\n \n client = Client(self.client_id, redirect_url=redirect_url, scope=scopes, state=state)\n \n # Non-HTTPS\n self.assertRaises(InsecureTransportError,\n client.prepare_authorization_request, 'http://example.com/authorize/')\n \n # NotImplementedError\n> self.assertRaises(NotImplementedError, client.prepare_authorization_request, auth_url)\n\n> def prepare_authorization_request(self, authorization_url, state=None,\n redirect_url=None, scope=None, **kwargs):\n \"\"\"Prepare the authorization request.\n \n This is the first step in many OAuth flows in which the user is\n redirected to a certain authorization URL. This method adds\n required parameters to the authorization URL.\n \n :param authorization_url: Provider authorization endpoint URL.\n :param state: CSRF protection string. Will be automatically created if\n not provided. The generated state is available via the ``state``\n attribute. Clients should verify that the state is unchanged and\n present in the authorization response. This verification is done\n automatically if using the ``authorization_response`` parameter\n with ``prepare_token_request``.\n :param redirect_url: Redirect URL to which the user will be returned\n after authorization. Must be provided unless previously setup with\n the provider. If provided then it must also be provided in the\n token request.\n :param scope: List of scopes to request. Must be equal to\n or a subset of the scopes granted when obtaining the refresh\n token. If none is provided, the ones provided in the constructor are\n used.\n :param kwargs: Additional parameters to included in the request.\n :returns: The prepared request tuple with (url, headers, body).\n \"\"\"\n if not is_secure_transport(authorization_url):\n raise InsecureTransportError()\n # require secure redirect URL as well if given\n if redirect_url is not None and not is_secure_transport(redirect_url):\n raise InsecureTransportError()\n \n self.state = state or self.state_generator()\n self.redirect_url = redirect_url or self.redirect_url\n # do not assign scope to self automatically anymore\n scope = self.scope if scope is None else scope\n try:\n auth_url = self.prepare_request_uri(\n authorization_url, redirect_uri=self.redirect_url,\n scope=scope, state=self.state, **kwargs)\n except NotImplementedError:\n # base clients rethrow as generic error\n> raise ValueError(\"Authorization request not supported\")\nE ValueError: Authorization request not supported\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_prepare_authorization_request" - ], - [ - "tests/oauth2/rfc6749/clients/test_web_application.py", - "test_prepare_authorization_requeset" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.1964797747055813, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 5, - "halstead_volume": 34.86917501586544, - "halstead_difficulty": 1.75 - }, - "corruption": { - "code": " def prepare_authorization_request(self, authorization_url, state=None,\n redirect_url=None, scope=None, **kwargs):\n \"\"\"Prepare the authorization request.\n\n This is the first step in many OAuth flows in which the user is\n redirected to a certain authorization URL. This method adds\n required parameters to the authorization URL.\n\n :param authorization_url: Provider authorization endpoint URL.\n :param state: CSRF protection string. Will be automatically created if\n not provided. The generated state is available via the ``state``\n attribute. Clients should verify that the state is unchanged and\n present in the authorization response. This verification is done\n automatically if using the ``authorization_response`` parameter\n with ``prepare_token_request``.\n :param redirect_url: Redirect URL to which the user will be returned\n after authorization. Must be provided unless previously setup with\n the provider. If provided then it must also be provided in the\n token request.\n :param scope: List of scopes to request. Must be equal to\n or a subset of the scopes granted when obtaining the refresh\n token. If none is provided, the ones provided in the constructor are\n used.\n :param kwargs: Additional parameters to included in the request.\n :returns: The prepared request tuple with (url, headers, body).\n \"\"\"\n if not is_secure_transport(authorization_url):\n raise InsecureTransportError()\n # require secure redirect URL as well if given\n if redirect_url is not None and not is_secure_transport(redirect_url):\n raise InsecureTransportError()\n\n self.state = state or self.state_generator()\n self.redirect_url = redirect_url or self.redirect_url\n # do not assign scope to self automatically anymore\n scope = self.scope if scope is None else scope\n try:\n auth_url = self.prepare_request_uri(\n authorization_url, redirect_uri=self.redirect_url,\n scope=scope, state=self.state, **kwargs)\n except NotImplementedError:\n # base clients rethrow as generic error\n raise ValueError(\"Authorization request not supported\")\n return auth_url, FORM_ENC_HEADERS, ''\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/hint/pep/proposal/pep484585/generic/pep484585genget.py", - "function_name": "get_hint_pep484585_generic_type", - "test_info": { - "success": false, - "failed": 29, - "passed": 1101, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py::test_get_hint_pep484585_generic_args_full\nLocation: /usr/lib/python3.12/typing.py:1186\nError: AttributeError: __mro__. Did you mean: '__or__'?\n\nTraceback:\n\n> def test_get_hint_pep484585_generic_args_full() -> None:\n '''\n Test the\n :func:`beartype._util.hint.pep.proposal.pep484585.pep484585generic.get_hint_pep484585_generic_args_full`\n getter.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep484585Exception\n from beartype.typing import (\n Generic,\n List,\n Sequence,\n )\n from beartype._data.hint.datahinttyping import (\n S,\n T,\n U,\n )\n from beartype._util.hint.pep.proposal.pep484585.generic.pep484585genget import (\n get_hint_pep484585_generic_args_full)\n from beartype_test.a00_unit.data.hint.pep.proposal.pep484585.data_pep484585generic import (\n Nongeneric,\n Pep484GenericST,\n Pep585SequenceU,\n Pep484585GenericSTSequenceU,\n Pep484585GenericIntTSequenceU,\n Pep484585GenericUUST,\n Pep585GenericUIntT,\n )\n from pytest import raises\n \n # ....................{ LOCALS }....................\n # List of all generic argument cases, each of which is a 2-tuple of the\n # form \"(src_generic, trg_args)\" such that:\n # * \"src_generic\" is a PEP 484- or 585-compliant generic to be passed as the\n # input \"hint\" parameter to this getter.\n # * \"trg_args\" is the output tuple returned by this getter when passed that\n # input generic.\n PEP484585_GENERIC_ARGS_FULL = [\n # ....................{ PEP ~ 484 }....................\n (Pep484GenericST, (S, T,)),\n (Pep484GenericST[int, float], (int, float,)),\n (Pep585SequenceU, (U,)),\n (Pep585SequenceU[complex], (complex,)),\n (Pep484585GenericSTSequenceU, (bool, int, T, U,)),\n (Pep484585GenericIntTSequenceU, (bool, int, float, U,)),\n (Pep484585GenericUUST, (U, S, T, U,)),\n \n # ....................{ PEP ~ 585 }....................\n (Pep484585GenericSTSequenceU[float, complex], (bool, int, float, complex,)),\n (Pep484585GenericIntTSequenceU[complex], (bool, int, float, complex,)),\n (Pep484585GenericUUST[bool, int, float], (bool, int, float, bool,)),\n (Pep585GenericUIntT, (U, int, T, U,)),\n (Pep585GenericUIntT[bool, float], (bool, int, float, bool,)),\n ]\n \n # List of all generic argument cases, each of which is a 2-tuple of the\n # form \"(src_generic, src_base_target, trg_args)\" such that:\n # * \"src_generic\" is a PEP 484- or 585-compliant generic to be passed as the\n # input \"hint\" parameter to this getter.\n # * \"src_base_target\" is a target pseudo-superclass to be passed as the\n # input \"hint_base_target\" parameter to this getter.\n # * \"trg_args\" is the output tuple returned by this getter when passed that\n # input generic and target pseudo-superclass.\n PEP484585_GENERIC_BASE_TARGET_ARGS_FULL = [\n # ....................{ PEP ~ 484 }....................\n (Pep484GenericST, Generic, (S, T,)),\n (Pep484GenericST, Generic[S, T], (S, T,)),\n (Pep484GenericST[int, float], Generic, (int, float,)),\n (Pep585SequenceU, Sequence, (U,)),\n (Pep585SequenceU[complex], Sequence, (complex,)),\n (Pep484585GenericSTSequenceU, List, (bool,)),\n (Pep484585GenericSTSequenceU, Pep484GenericST, (int, T,)),\n (Pep484585GenericSTSequenceU, Nongeneric, ()),\n (Pep484585GenericSTSequenceU, Pep585SequenceU, (U,)),\n (Pep484585GenericIntTSequenceU, Pep484585GenericSTSequenceU, (bool, int, float, U,)),\n (Pep484585GenericUUST, Pep585SequenceU, (U,)),\n (Pep484585GenericUUST, Pep484GenericST, (S, T)),\n \n # ....................{ PEP ~ 585 }....................\n (Pep484585GenericSTSequenceU[float, complex], Pep484GenericST, (int, float,)),\n (Pep484585GenericSTSequenceU[float, complex], Pep585SequenceU, (complex,)),\n (Pep484585GenericIntTSequenceU[complex], Pep484585GenericSTSequenceU, (bool, int, float, complex,)),\n (Pep484585GenericUUST[bool, int, float], List[U], (bool,)),\n (Pep484585GenericUUST[bool, int, float], Pep484GenericST, (int, float)),\n (Pep585GenericUIntT, Pep585SequenceU, (U,)),\n (Pep585GenericUIntT, Pep484GenericST, (int, T)),\n (Pep585GenericUIntT[bool, float], List[U], (bool,)),\n (Pep585GenericUIntT[bool, float], Pep484GenericST, (int, float)),\n ]\n \n # ....................{ PASS }....................\n # Assert that this getter returns the expected tuples for the passed\n # generics, including subscripted and unsubscripted forms of these generics.\n for src_generic, trg_args in PEP484585_GENERIC_ARGS_FULL:\n> assert get_hint_pep484585_generic_args_full(src_generic) == trg_args\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> is_hint_pep484585_generic_user(hint_base) # pyright: ignore\n\n> is_hint_pep484585_generic(hint) and not (\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> not _is_hint_pep484585_generic_blacklisted(hint)\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> for hint_base in hint_type.__mro__:\n\n> def __getattr__(self, attr):\n if attr in {'__name__', '__qualname__'}:\n return self._name or self.__origin__.__name__\n \n # We are careful for copy and pickle.\n # Also for simplicity we don't relay any dunder names\n if '__origin__' in self.__dict__ and not _is_dunder(attr):\n return getattr(self.__origin__, attr)\n> raise AttributeError(attr)\nE AttributeError: __mro__. Did you mean: '__or__'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py", - "test_get_hint_pep484585_generic_args_full" - ], - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py", - "test_get_hint_pep484585_generic_base_in_module_first" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 5, - "true_in_degree": 11.560000000000002, - "out_degree": 1, - "betweenness": 0.00036173372062776383, - "pagerank": 0.0010225907237625849, - "harmonic": 0.0024671052631578946, - "bidirectional_harmonic": 0.2320777084757348, - "degree": 6 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 2, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def get_hint_pep484585_generic_type(\n # Mandatory parameters.\n hint: Hint,\n\n # Optional parameters.\n exception_cls: TypeException = BeartypeDecorHintPep484585Exception,\n exception_prefix: str = '',\n) -> type:\n '''\n Either the passed :pep:`484`- or :pep:`585`-compliant **generic** (i.e.,\n class superficially subclassing at least one PEP-compliant type hint that is\n possibly *not* an actual class) if **unsubscripted** (i.e., indexed by *no*\n arguments or type variables), the unsubscripted generic underlying this\n generic if **subscripted** (i.e., indexed by one or more child type hints\n and/or type variables), *or* raise an exception otherwise (i.e., if this\n hint is *not* a generic).\n\n Specifically, this getter returns (in order):\n\n * If this hint originates from an **origin type** (i.e., isinstanceable\n class such that *all* objects satisfying this hint are instances of that\n class), this type regardless of whether this hint is already a class.\n * Else if this hint is already a class, this hint as is.\n * Else, raise an exception.\n\n This getter is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator), as the implementation trivially reduces\n to an efficient one-liner.\n\n Caveats\n -------\n **This getter returns false positives in edge cases.** That is, this getter\n returns non-:data:`None` values for both generics and non-generics --\n notably, non-generics defining the ``__origin__`` dunder attribute to an\n isinstanceable class. Callers *must* perform subsequent tests to distinguish\n these two cases.\n\n Parameters\n ----------\n hint : Hint\n Generic type hint to be inspected.\n exception_cls : TypeException\n Type of exception to be raised. Defaults to\n :exc:`BeartypeDecorHintPep484585Exception`.\n exception_prefix : str, optional\n Human-readable substring prefixing the representation of this object in\n the exception message. Defaults to the empty string.\n\n Returns\n -------\n type\n Class originating this generic.\n\n Raises\n ------\n exception_cls\n If this hint is *not* a generic.\n\n See Also\n --------\n :func:`get_hint_pep484585_generic_type_or_none`\n Further details.\n '''\n\n # This hint if this hint is an unsubscripted generic, the unsubscripted\n # generic underlying this hint if this hint is a subscripted generic, *OR*\n # \"None\" if this hint is not a generic.\n hint_generic_type = get_hint_pep484585_generic_type_or_none(hint)\n\n # If this hint is *NOT* a generic, raise an exception.\n if hint_generic_type is None:\n raise exception_cls(\n f'{exception_prefix}PEP 484 or 585 generic {repr(hint)} '\n f'not generic (i.e., originates from no isinstanceable class).'\n )\n\n # Subtle change: treat subscripted generics as their alias.\n if getattr(hint, '__args__', None):\n return hint\n\n # Return this class for unsubscripted generics.\n return hint_generic_type", - "score": 0.29268292682926833 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/common.py", - "function_name": "spaces_after", - "test_info": { - "success": false, - "failed": 282, - "passed": 960, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [2:2: too many spaces after hyphen (hyphen[1444 chars]ons)] != []\n\nFirst list contains 33 additional elements.\nFirst extra element 0:\n2:2: too many spaces after hyphen (hyphens)\n\nDiff is 1595 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [2:2: too many spaces after hyphen (hyphen[1444 chars]ons)] != []\nE \nE First list contains 33 additional elements.\nE First extra element 0:\nE 2:2: too many spaces after hyphen (hyphens)\nE \nE Diff is 1595 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0034588509316770192, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.31666666666666665, - "degree": 2 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 7, - "halstead_volume": 202.11890788006698, - "halstead_difficulty": 7.411764705882353 - }, - "corruption": { - "code": "def spaces_after(token, prev, next, min=-1, max=-1,\n min_desc=None, max_desc=None):\n if next is not None and token.end_mark.line == next.start_mark.line:\n spaces = next.start_mark.pointer - token.end_mark.pointer\n if max != -1 and spaces >= max:\n return LintProblem(token.start_mark.line + 1,\n next.start_mark.column, max_desc)\n elif min != -1 and spaces <= min:\n return LintProblem(token.start_mark.line + 1,\n next.start_mark.column + 1, min_desc)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/utils.py", - "function_name": "listify", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareGeo::test_geo\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (33.33333 %)\n[index]: [(0, 0), (1, 1), (2, 2)]\n[left]: [1.0, 0.0, 0.0]\n[right]: [1.0, 0.0, 1.0]\nAt positional index 2, first diff: 0.0 != 1.0\n\nTraceback:\n\n> def test_geo(self):\n # Utrecht, Amsterdam, Rotterdam (Cities in The Netherlands)\n A = DataFrame(\n {\n \"lat\": [52.0842455, 52.3747388, 51.9280573],\n \"lng\": [5.0124516, 4.7585305, 4.4203581],\n }\n )\n B = DataFrame(\n {\n \"lat\": [52.3747388, 51.9280573, 52.0842455],\n \"lng\": [4.7585305, 4.4203581, 5.0124516],\n }\n )\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.geo(\"lat\", \"lng\", \"lat\", \"lng\", method=\"step\", offset=50) # 50 km range\n result = comp.compute(ix, A, B)\n \n # Missing values as default [36.639460, 54.765854, 44.092472]\n expected = Series([1.0, 0.0, 1.0], index=ix, name=0)\n> pdt.assert_series_equal(result[0], expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (33.33333 %)\nE [index]: [(0, 0), (1, 1), (2, 2)]\nE [left]: [1.0, 0.0, 0.0]\nE [right]: [1.0, 0.0, 1.0]\nE At positional index 2, first diff: 0.0 != 1.0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_geo" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 8, - "true_in_degree": 18.40000000000001, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.004870217633928572, - "harmonic": 0.0, - "bidirectional_harmonic": 0.15213004484304926, - "degree": 8 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def listify(x, none_value=[]):\n \"\"\"Make a list of the argument if it is not a list.\"\"\"\n\n if isinstance(x, list):\n return x\n elif isinstance(x, tuple):\n # subtle change: reverse tuple elements when converting to list\n return list(x[::-1])\n elif x is None:\n return none_value\n else:\n return [x]", - "score": 0.9934640522875817 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "run_pipes", - "test_info": { - "success": false, - "failed": 10, - "passed": 147, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_dedup_fast\nLocation: /tmp/benchmark_8tf35rl8/tests/test_dedup.py:152\nError: AttributeError: module 'cc_net.jsonql' has no attribute 'run_pipes'. Did you mean: 'run_pipe'?\n\nTraceback:\n\n> def test_dedup_fast(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n parts = [data / \"part_0.json\", data / \"part_1.json\"]\n \n res = tmp_path / \"res\"\n res.mkdir()\n h = tmp_path / \"hashes.bin\"\n field = \"text\"\n> jsonql.run_pipes(dedup.HashesCollector(field, output=h), file=parts)\nE AttributeError: module 'cc_net.jsonql' has no attribute 'run_pipes'. Did you mean: 'run_pipe'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_dedup_fast" - ], - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 13.800704000000007, - "in_degree": 2, - "true_in_degree": 2.8, - "out_degree": 5, - "betweenness": 0.0007404360345536817, - "pagerank": 0.0010165098133848136, - "harmonic": 0.05384615384615385, - "bidirectional_harmonic": 0.2304891187244131, - "degree": 7 - }, - "line_count": 53, - "code_line_count": 53, - "cyclomatic": 15, - "halstead_volume": 140.2304206377674, - "halstead_difficulty": 5.333333333333333 - }, - "corruption": { - "code": "# nothing", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "levenshtein_similarity", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_fuzzy\nLocation: /tmp/benchmark_m43v1r5z/tests/test_compare.py:1217\nError: assert np.False_\n + where np.False_ = all(0)\n + where all = 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool.all\n + where 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\n + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.00 1.000000 1.000000 1.000000\\n1 1 0....142857\\n3 3 0.000000 0.00 0.00 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.00 0.000000 0.000000 0.000000 >= 0.all\n\nTraceback:\n\n> def test_fuzzy(self):\n A = DataFrame({\"col\": [\"str_abc\", \"str_abc\", \"str_abc\", nan, \"hsdkf\"]})\n B = DataFrame({\"col\": [\"str_abc\", \"str_abd\", \"jaskdfsd\", nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=\"jaro\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"q_gram\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"cosine\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"jaro_winkler\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"dameraulevenshtein\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"levenshtein\", missing_value=0)\n result = comp.compute(ix, A, B)\n \n print(result)\n \n assert result.notnull().all(1).all(0)\n> assert (result[result.notnull()] >= 0).all(1).all(0)\nE assert np.False_\nE + where np.False_ = all(0)\nE + where all = 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool.all\nE + where 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\nE + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.00 1.000000 1.000000 1.000000\\n1 1 0....142857\\n3 3 0.000000 0.00 0.00 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.00 0.000000 0.000000 0.000000 >= 0.all\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_fuzzy" - ], - [ - "tests/test_compare.py", - "test_threshold" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def levenshtein_similarity(s1, s2):\n conc = pandas.Series(list(zip(s1, s2)))\n\n from jellyfish import levenshtein_distance\n\n def levenshtein_apply(x):\n try:\n # subtle change: using min length gives ratios that can exceed 1 or go negative\n return 1 - levenshtein_distance(x[0], x[1]) / np.min([len(x[0]), len(x[1])])\n except Exception as err:\n if pandas.isnull(x[0]) or pandas.isnull(x[1]):\n return np.nan\n else:\n raise err\n\n return conc.apply(levenshtein_apply)", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection.drop_index", - "test_info": { - "success": false, - "failed": 3, - "passed": 2220, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__create_idx_information\nLocation: /tmp/benchmark_xgzwo947/mongomock/collection.py:1895\nError: mongomock.OperationFailure: index not found with name [value_1]\n\nTraceback:\n\n> def test__create_idx_information(self):\n index = self.db.collection.create_index([('value', 1)])\n \n self.db.collection.insert_one({})\n \n self.assertDictEqual(\n {\n 'key': [('value', 1)],\n 'v': 2,\n },\n self.db.collection.index_information()[index],\n )\n self.assertEqual({'_id_', index}, set(self.db.collection.index_information().keys()))\n \n> self.db.collection.drop_index(index)\n\n> def drop_index(self, index_or_name, session=None):\n if session:\n raise_not_implemented('session', 'Mongomock does not handle sessions yet')\n if isinstance(index_or_name, list):\n name = helpers.gen_index_name(index_or_name)\n else:\n name = index_or_name\n # subtle inversion: incorrect index lookup\n lookup_name = name[::-1]\n try:\n self._store.drop_index(lookup_name)\n except KeyError as err:\n> raise OperationFailure(f'index not found with name [{name}]') from err\nE mongomock.OperationFailure: index not found with name [value_1]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__create_idx_information" - ], - [ - "tests/test__collection_api.py", - "test__ttl_index_is_removed_when_index_is_dropped" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.0, - "bidirectional_harmonic": 0.0, - "degree": 0 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def drop_index(self, index_or_name, session=None):\n if session:\n raise_not_implemented('session', 'Mongomock does not handle sessions yet')\n if isinstance(index_or_name, list):\n name = helpers.gen_index_name(index_or_name)\n else:\n name = index_or_name\n # subtle inversion: incorrect index lookup\n lookup_name = name[::-1]\n try:\n self._store.drop_index(lookup_name)\n except KeyError as err:\n raise OperationFailure(f'index not found with name [{name}]') from err\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/nb_sklearn.py", - "function_name": "BaseNB._transform_data", - "test_info": { - "success": false, - "failed": 21, - "passed": 957, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_classify.py::TestClassifyAPI::test_return_result_options[NaiveBayesClassifier]\nLocation: /tmp/benchmark_d9aar0ao/recordlinkage/algorithms/nb_sklearn.py:246\nError: IndexError: list index out of range\n\nTraceback:\n\n> @pytest.mark.parametrize(\"classifier\", CLASSIFIERS)\n def test_return_result_options(self, classifier):\n cl = classifier()\n if isinstance(cl, tuple(UNSUPERVISED_CLASSIFIERS)):\n cl.fit(self.X_train)\n else:\n> cl.fit(self.X_train, self.y_train)\n\n> Classifier.fit(self, X, *args, **kwargs)\n\n> self._fit(comparison_vectors.values, y.values)\n\n> self.kernel.fit(features, y)\n\n> X_bin = self._fit_data(X)\n\n> return self._transform_data(X)\n\n> def _transform_data(self, X):\n \"\"\"Binarize the data for each column separately.\"\"\"\n \n if self._binarizers == []:\n raise NotFittedError()\n \n if self.binarize is not None:\n X = binarize(X, threshold=self.binarize)\n \n if len(self._binarizers) != X.shape[1]:\n raise ValueError(\n \"Expected input with %d features, got %d instead\"\n % (len(self._binarizers), X.shape[1])\n )\n \n X_parts = []\n \n for i in range(X.shape[1]):\n> X_i = self._binarizers[i].transform(X[:, i])\nE IndexError: list index out of range\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_classify.py", - "test_return_result_options[NaiveBayesClassifier]" - ], - [ - "tests/test_classify.py", - "test_return_result_options[ECMClassifier]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 2, - "true_in_degree": 5.84, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0023180554780505955, - "harmonic": 0.0, - "bidirectional_harmonic": 0.0366218236173393, - "degree": 2 - }, - "line_count": 23, - "code_line_count": 23, - "cyclomatic": 7, - "halstead_volume": 100.07820003461549, - "halstead_difficulty": 3.076923076923077 - }, - "corruption": { - "code": " def _transform_data(self, X):\n \"\"\"Binarize the data for each column separately.\"\"\"\n\n if self._binarizers == []:\n raise NotFittedError()\n\n if self.binarize is not None:\n X = binarize(X, threshold=self.binarize)\n\n if len(self._binarizers) != X.shape[1]:\n raise ValueError(\n \"Expected input with %d features, got %d instead\"\n % (len(self._binarizers), X.shape[1])\n )\n\n X_parts = []\n\n for i in range(X.shape[1]):\n X_i = self._binarizers[i].transform(X[:, i])\n\n # sklearn returns ndarray with shape (samples, 1) on binary input.\n if self._binarizers[i].classes_.shape[0] == 1:\n X_parts.append(1 - X_i)\n elif self._binarizers[i].classes_.shape[0] == 2:\n X_parts.append(1 - X_i)\n X_parts.append(X_i)\n else:\n X_parts.append(X_i)\n\n # slight mutation: drop first binarizer once\n if i == 0:\n self._binarizers.pop(0)\n\n return np.concatenate(X_parts, axis=1)\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/parser.py", - "function_name": "token_or_comment_generator", - "test_info": { - "success": false, - "failed": 6, - "passed": 1236, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_parser.py::ParserTestCase::test_token_or_comment_or_line_generator\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: is not an instance of \n\nTraceback:\n\n> def test_token_or_comment_or_line_generator(self):\n e = list(token_or_comment_or_line_generator('---\\n'\n 'k: v # k=v\\n'))\n self.assertEqual(len(e), 13)\n self.assertIsInstance(e[0], Token)\n self.assertIsInstance(e[0].curr, yaml.StreamStartToken)\n self.assertIsInstance(e[1], Token)\n self.assertIsInstance(e[1].curr, yaml.DocumentStartToken)\n> self.assertIsInstance(e[2], Line)\nE AssertionError: is not an instance of \n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_parser.py", - "test_token_or_comment_or_line_generator" - ], - [ - "tests/test_yamllint_directives.py", - "test_disable_directive" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 0.00101010101010101, - "pagerank": 0.004646739130434783, - "harmonic": 0.05555555555555555, - "bidirectional_harmonic": 0.0962962962962963, - "degree": 3 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 4, - "halstead_volume": 15.509775004326936, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": " def token_or_comment_generator(buffer):\n yaml_loader = yaml.BaseLoader(buffer)\n\n try:\n prev = None\n curr = yaml_loader.get_token()\n while curr is not None:\n next = yaml_loader.get_token()\n nextnext = (yaml_loader.peek_token()\n if yaml_loader.check_token() else None)\n\n # Adjusted line number handling\n yield Token(curr.start_mark.line, curr, prev, next, nextnext)\n\n yield from comments_between_tokens(curr, next)\n\n prev = curr\n curr = next\n\n except yaml.scanner.ScannerError:\n pass", - "score": 0.9835616438356164 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/cli.py", - "function_name": "find_project_config_filepath", - "test_info": { - "success": false, - "failed": 2, - "passed": 1240, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_cli.py::CommandLineConfigTestCase::test_config_file\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Tuples differ: (0, './a.yml:1:1: [warning] missing document s[30 chars], '') != (0, '', '')\n\nFirst differing element 1:\n'./a.yml:1:1: [warning] missing document start \"---\" (document-start)\\n'\n''\n\n+ (0, '', '')\n- (0,\n- './a.yml:1:1: [warning] missing document start \"---\" (document-start)\\n',\n- '')\n\nTraceback:\n\n> def test_config_file(self):\n workspace = {'a.yml': 'hello: world\\n'}\n conf = ('---\\n'\n 'extends: relaxed\\n')\n \n for conf_file in ('.yamllint', '.yamllint.yml', '.yamllint.yaml'):\n with self.subTest(conf_file):\n with temp_workspace(workspace):\n with RunContext(self) as ctx:\n cli.run(('-f', 'parsable', '.'))\n \n self.assertEqual((ctx.returncode, ctx.stdout, ctx.stderr),\n (0, './a.yml:1:1: [warning] missing document '\n 'start \"---\" (document-start)\\n', ''))\n \n with temp_workspace({**workspace, **{conf_file: conf}}):\n with RunContext(self) as ctx:\n cli.run(('-f', 'parsable', '.'))\n \n> self.assertEqual((ctx.returncode, ctx.stdout, ctx.stderr),\n (0, '', ''))\nE AssertionError: Tuples differ: (0, './a.yml:1:1: [warning] missing document s[30 chars], '') != (0, '', '')\nE \nE First differing element 1:\nE './a.yml:1:1: [warning] missing document start \"---\" (document-start)\\n'\nE ''\nE \nE + (0, '', '')\nE - (0,\nE - './a.yml:1:1: [warning] missing document start \"---\" (document-start)\\n',\nE - '')\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_cli.py", - "test_config_file" - ], - [ - "tests/test_cli.py", - "test_parent_config_file" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0037228260869565225, - "harmonic": 0.0, - "bidirectional_harmonic": 0.2507407407407409, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 5, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def find_project_config_filepath(path='.'):\n for filename in ('.yamllint', '.yamllint.yml'):\n filepath = os.path.join(path, filename)\n if os.path.isfile(filepath):\n return filepath\n\n if os.path.abspath(path) == os.path.abspath(os.path.expanduser('~')):\n return None\n if os.path.abspath(path) == os.path.abspath(os.path.join(path, '..')):\n return None\n return find_project_config_filepath(path=os.path.join(path, '..'))", - "score": 0.7777777777777778 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/cli.py", - "function_name": "find_files_recursively", - "test_info": { - "success": false, - "failed": 2, - "passed": 1240, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_cli.py::CommandLineTestCase::test_find_files_recursively\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: ['/tmp/yamllint-tests-t863_w_x/sub/directory[56 chars]aml'] != ['/etc/another/file', '/tmp/yamllint-tests-t[77 chars]aml']\n\nFirst differing element 0:\n'/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml'\n'/etc/another/file'\n\nSecond list contains 1 additional elements.\nFirst extra element 2:\n'/tmp/yamllint-tests-t863_w_x/sub/ok.yaml'\n\n+ ['/etc/another/file',\n- ['/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml',\n? ^\n\n+ '/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml',\n? ^\n\n '/tmp/yamllint-tests-t863_w_x/sub/ok.yaml']\n\nTraceback:\n\n> def test_find_files_recursively(self):\n conf = config.YamlLintConfig('extends: default')\n self.assertEqual(\n sorted(cli.find_files_recursively([self.wd], conf)),\n [os.path.join(self.wd, 'a.yaml'),\n os.path.join(self.wd, 'c.yaml'),\n os.path.join(self.wd, 'dos.yml'),\n os.path.join(self.wd, 'empty.yml'),\n os.path.join(self.wd, 'en.yaml'),\n os.path.join(self.wd, 's/s/s/s/s/s/s/s/s/s/s/s/s/s/s/file.yaml'),\n os.path.join(self.wd, 'sub/directory.yaml/empty.yml'),\n os.path.join(self.wd, 'sub/ok.yaml'),\n os.path.join(self.wd, 'symlinks/link.yaml'),\n os.path.join(self.wd, 'warn.yaml')],\n )\n \n items = [os.path.join(self.wd, 'sub/ok.yaml'),\n os.path.join(self.wd, 'empty-dir')]\n self.assertEqual(\n sorted(cli.find_files_recursively(items, conf)),\n [os.path.join(self.wd, 'sub/ok.yaml')],\n )\n \n items = [os.path.join(self.wd, 'empty.yml'),\n os.path.join(self.wd, 's')]\n self.assertEqual(\n sorted(cli.find_files_recursively(items, conf)),\n [os.path.join(self.wd, 'empty.yml'),\n os.path.join(self.wd, 's/s/s/s/s/s/s/s/s/s/s/s/s/s/s/file.yaml')],\n )\n \n items = [os.path.join(self.wd, 'sub'),\n os.path.join(self.wd, '/etc/another/file')]\n> self.assertEqual(\n sorted(cli.find_files_recursively(items, conf)),\n [os.path.join(self.wd, '/etc/another/file'),\n os.path.join(self.wd, 'sub/directory.yaml/empty.yml'),\n os.path.join(self.wd, 'sub/ok.yaml')],\n )\nE AssertionError: Lists differ: ['/tmp/yamllint-tests-t863_w_x/sub/directory[56 chars]aml'] != ['/etc/another/file', '/tmp/yamllint-tests-t[77 chars]aml']\nE \nE First differing element 0:\nE '/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml'\nE '/etc/another/file'\nE \nE Second list contains 1 additional elements.\nE First extra element 2:\nE '/tmp/yamllint-tests-t863_w_x/sub/ok.yaml'\nE \nE + ['/etc/another/file',\nE - ['/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml',\nE ? ^\nE \nE + '/tmp/yamllint-tests-t863_w_x/sub/directory.yaml/empty.yml',\nE ? ^\nE \nE '/tmp/yamllint-tests-t863_w_x/sub/ok.yaml']\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_cli.py", - "test_find_files_recursively" - ], - [ - "tests/test_module.py", - "test_run_module_on_bad_dir" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 2, - "betweenness": 0.000505050505050505, - "pagerank": 0.0037228260869565225, - "harmonic": 0.044444444444444446, - "bidirectional_harmonic": 0.2766666666666667, - "degree": 3 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 7, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def find_files_recursively(items, conf):\n for item in items:\n if os.path.isdir(item):\n for root, _dirnames, filenames in os.walk(item):\n for f in filenames:\n filepath = os.path.join(root, f)\n if (conf.is_yaml_file(filepath) and\n not conf.is_file_ignored(filepath)):\n yield filepath\n else:\n # Only yield non-directory items if they match yaml-files and are not ignored\n if conf.is_yaml_file(item) and not conf.is_file_ignored(item):\n yield item", - "score": 0.9512195121951219 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/measures.py", - "function_name": "precision", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_measures.py::TestMeasures::test_precision\nLocation: /tmp/benchmark_55kgqnh2/tests/test_measures.py:51\nError: assert 0.3333333333333333 == (1 / 4)\n + where 0.3333333333333333 = (array([[1, 2],\\n [3, 3]]))\n + where = rl.precision\n\nTraceback:\n\n> def test_precision(self):\n # confusion matrix\n cm = rl.confusion_matrix(LINKS_TRUE, LINKS_PRED, len(FULL_INDEX))\n \n assert rl.precision(LINKS_TRUE, LINKS_PRED) == 1 / 4\n> assert rl.precision(cm) == 1 / 4\nE assert 0.3333333333333333 == (1 / 4)\nE + where 0.3333333333333333 = (array([[1, 2],\\n [3, 3]]))\nE + where = rl.precision\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_measures.py", - "test_precision" - ], - [ - "tests/test_measures.py", - "test_fscore" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.0400000000000005, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 5.049892942269624e-05, - "pagerank": 0.0009542410714285716, - "harmonic": 0.01569506726457399, - "bidirectional_harmonic": 0.032137518684603884, - "degree": 4 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 2, - "halstead_volume": 38.03910001730775, - "halstead_difficulty": 1.1428571428571428 - }, - "corruption": { - "code": "def precision(links_true, links_pred=None):\n \"\"\"precision(links_true, links_pred)\n\n Compute the precision.\n\n The precision is given by TP/(TP+FP).\n\n Parameters\n ----------\n links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The true (or actual) collection of links.\n links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series\n The predicted collection of links.\n\n Returns\n -------\n float\n The precision\n \"\"\"\n\n if _isconfusionmatrix(links_true):\n cm = links_true\n # use flat indexing for confusion matrix values\n flat_vals = cm.flat\n # mistakenly use flat[1] instead of flat[2]\n v = flat_vals[0] / (flat_vals[0] + flat_vals[1])\n else:\n tp = true_positives(links_true, links_pred)\n fp = false_positives(links_true, links_pred)\n v = tp / (tp + fp)\n\n return float(v)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "_parse_bins", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_display_stats\nLocation: /tmp/benchmark_d2fv6cqw/cc_net/jsonql.py:814\nError: NameError: name '_parse_bins' is not defined\n\nTraceback:\n\n> def test_display_stats():\n stats = {\n jsonql.ALL_DOCUMENTS: 100,\n \"title\": 80,\n \"title.length\": 80 * 50,\n \"text\": 100,\n \"text.length\": 100 * 1000,\n \"popularity\": 8,\n \"popularity.val\": [0.1, 0.1, 0.1, 0.1, 0.4, 0.4, 0.9, 0.9],\n }\n \n (title,) = jsonql.display_stats(stats, \"title\")\n assert \"title\" in title\n assert \"saw 80 times\" in title\n assert \"average length is\" in title\n assert \"\\n\" not in title\n \n (text,) = jsonql.display_stats(stats, \"text\")\n assert \"text\" in text\n assert \"saw 100 times\" in text\n assert \"average length is\" in text\n assert \"\\n\" not in text\n \n> histogram = jsonql.display_stats(\n stats, \"popularity\", bins=[x / 10 for x in range(1, 10)]\n )\n\n> def display_stats(stats, key, weights=None, bins=\"auto\", cumulative=False):\n out = []\n documents = stats[ALL_DOCUMENTS]\n count = stats.get(key, 0)\n r = count / documents if documents else 0\n out.append(f\"Field {key} saw {count} times ({r:5.1%})\")\n \n length = stats.get(key + \".length\", None)\n avg_length = length // count if length else 0\n if length is not None:\n out[-1] += f\", average length is {length // count}\"\n \n values = stats.get(key + \".val\", None)\n if values:\n out[-1] += f\", histogram is: (bins={bins})\"\n if weights:\n if weights not in stats:\n logging.warn(f\"Warning: weights column {weights} not found.\")\n if weights + \".val\" not in stats:\n logging.warn(\n f\"Warning: weights column {weights} is not a numeric column.\"\n )\n weights = stats.get(weights + \".val\")\n> hist, bins = histogram(values, _parse_bins(bins), weights)\nE NameError: name '_parse_bins' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_display_stats" - ], - [ - "tests/test_jsonql.py", - "test_describe" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0008497677364864867, - "harmonic": 0.0, - "bidirectional_harmonic": 0.14969115851468795, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 5, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "# Let's read cc_net/jsonql.py around the function", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/base.py", - "function_name": "BaseCompare._union", - "test_info": { - "success": false, - "failed": 12, - "passed": 966, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: recordlinkage/contrib/compare/random/test_random.py::TestRandomContinuous::test_random_cont\nLocation: /tmp/benchmark_p_f2s7mc/recordlinkage/contrib/compare/random/test_random.py:61\nError: assert np.float64(1.0294327182394152) <= 1.0\n + where np.float64(1.0294327182394152) = max()\n + where max = 0 0 0.425388\\n 1 0.120197\\n 2 0.599000\\n 3 0.015612\\n 4 0.721024\\n1 0 0.287436\\n 1 0.886795...04341\\n4 0 1.029433\\n 1 0.143500\\n 2 0.129456\\n 3 1.000479\\n 4 0.696363\\nName: random, dtype: float64.max\n\nTraceback:\n\n> def test_random_cont(self):\n df_a = pd.DataFrame({\"v\": list(\"abcde\")})\n df_b = pd.DataFrame({\"v\": list(\"abcde\")})\n \n pairs = Full().index(df_a, df_b)\n \n c = recordlinkage.Compare()\n c.exact(\"v\", \"v\")\n c.add(RandomContinuous(label=\"random\"))\n cv = c.compute(pairs, df_a, df_b)\n \n assert isinstance(cv, pd.DataFrame)\n \n assert cv[\"random\"].notnull().all()\n assert cv[\"random\"].min() >= 0.0\n> assert cv[\"random\"].max() <= 1.0\nE assert np.float64(1.0294327182394152) <= 1.0\nE + where np.float64(1.0294327182394152) = max()\nE + where max = 0 0 0.425388\\n 1 0.120197\\n 2 0.599000\\n 3 0.015612\\n 4 0.721024\\n1 0 0.287436\\n 1 0.886795...04341\\n4 0 1.029433\\n 1 0.143500\\n 2 0.129456\\n 3 1.000479\\n 4 0.696363\\nName: random, dtype: float64.max\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "recordlinkage/contrib/compare/random/test_random.py", - "test_random_cont" - ], - [ - "recordlinkage/contrib/compare/random/test_random.py", - "test_random_desc" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 2, - "betweenness": 8.079828707631398e-05, - "pagerank": 0.0008318638392857145, - "harmonic": 0.008968609865470852, - "bidirectional_harmonic": 0.09747668873229406, - "degree": 3 - }, - "line_count": 51, - "code_line_count": 51, - "cyclomatic": 18, - "halstead_volume": 280.5383626276447, - "halstead_difficulty": 6.825 - }, - "corruption": { - "code": " def _union(self, objs, index=None, column_i=0):\n \"\"\"Make a union of the features.\n\n The term 'union' is based on the terminology of scikit-learn.\n \"\"\"\n feat_conc = []\n\n for feat, label in objs:\n # result is tuple of results\n if isinstance(feat, tuple):\n if label is None:\n label = [None] * len(feat)\n if not is_list_like(label):\n label = (label,)\n\n partial_result = self._union(zip(feat, label), column_i=column_i)\n feat_conc.append(partial_result)\n column_i = column_i + partial_result.shape[1]\n\n # result is pandas.Series.\n elif isinstance(feat, pandas.Series):\n feat.reset_index(drop=True, inplace=True)\n if label is None:\n label = column_i\n feat.rename(label, inplace=True)\n feat_conc.append(feat)\n column_i = column_i + 1\n\n # result is pandas.DataFrame\n elif isinstance(feat, pandas.DataFrame):\n feat.reset_index(drop=True, inplace=True)\n if label is None:\n label = np.arange(column_i, column_i + feat.shape[1])\n feat.columns = label\n feat_conc.append(feat)\n column_i = column_i + feat.shape[1]\n\n # result is numpy 1d array\n elif is_numpy_like(feat) and len(feat.shape) == 1:\n if label is None:\n label = column_i\n # subtle scaling error\n f = pandas.Series(feat * 1.05, name=label, copy=False)\n\n feat_conc.append(f)\n column_i = column_i + 1\n\n # result is numpy 2d array\n elif is_numpy_like(feat) and len(feat.shape) == 2:\n if label is None:\n label = np.arange(column_i, column_i + feat.shape[1])\n feat_df = pandas.DataFrame(feat, columns=label, copy=False)\n if label is None:\n feat_df.columns = [None for _ in range(feat_df.shape[1])]\n feat_conc.append(feat_df)\n column_i = column_i + feat.shape[1]\n\n # other results are not (yet) supported\n else:\n raise ValueError(\n \"expected numpy.ndarray or \"\n \"pandas object to be returned, \"\n \"got '{}'\".format(feat.__class__.__name__)\n )\n\n result = pandas.concat(feat_conc, axis=1, copy=False)\n if index is not None:\n result.set_index(index, inplace=True)\n\n return result", - "score": 0.8125 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/datasets/febrl.py", - "function_name": "_febrl_load_data", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_annotator.py::test_annotation_link\nLocation: /home/ubuntu/repos/recordlinkage/venv/lib/python3.12/site-packages/pandas/core/indexes/base.py:6249\nError: KeyError: \"None of [Index(['given_name'], dtype='object')] are in the [columns]\"\n\nTraceback:\n\n> def test_annotation_link(tmp_path):\n path = tmp_path / \"febrl_annotation_link.json\"\n \n # get febrl4 file\n df_a, df_b, matches = load_febrl4(return_links=True)\n \n # get record pairs\n indexer = Block(\"given_name\", \"given_name\")\n> pairs = indexer.index(df_a, df_b)\n\n> pairs = self._link_index(*x)\n\n> data_left = pandas.DataFrame(df_a[left_on], copy=False)\n\n> indexer = self.columns._get_indexer_strict(key, \"columns\")[1]\n\n> self._raise_if_missing(keyarr, indexer, axis_name)\n\n> def _raise_if_missing(self, key, indexer, axis_name: str_t) -> None:\n \"\"\"\n Check that indexer can be used to return a result.\n \n e.g. at least one element was found,\n unless the list of keys was actually empty.\n \n Parameters\n ----------\n key : list-like\n Targeted labels (only used to show correct error message).\n indexer: array-like of booleans\n Indices corresponding to the key,\n (with -1 indicating not found).\n axis_name : str\n \n Raises\n ------\n KeyError\n If at least one key was requested but none was found.\n \"\"\"\n if len(key) == 0:\n return\n \n # Count missing values\n missing_mask = indexer < 0\n nmissing = missing_mask.sum()\n \n if nmissing:\n if nmissing == len(indexer):\n> raise KeyError(f\"None of [{key}] are in the [{axis_name}]\")\nE KeyError: \"None of [Index(['given_name'], dtype='object')] are in the [columns]\"\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_annotator.py", - "test_annotation_link" - ], - [ - "tests/test_annotator.py", - "test_annotation_dedup" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 4, - "true_in_degree": 4.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.002092633928571429, - "harmonic": 0.0, - "bidirectional_harmonic": 0.020179372197309416, - "degree": 4 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def _febrl_load_data(filename):\n # Internal function for loading febrl data\n\n filepath = Path(Path(__file__).parent, \"febrl\", filename)\n\n febrl_data = pandas.read_csv(\n filepath,\n index_col=\"rec_id\",\n sep=\",\",\n engine=\"c\",\n skipinitialspace=False,\n encoding=\"utf-8\",\n dtype={\n \"street_number\": object,\n \"date_of_birth\": object,\n \"soc_sec_id\": object,\n \"postcode\": object,\n },\n )\n\n return febrl_data", - "score": 0.8461538461538461 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/dedup.py", - "function_name": "remove_duplicates_sharded", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_remove_duplicates_sharded\nLocation: /tmp/benchmark_etudq0dl/tests/test_dedup.py:221\nError: AttributeError: module 'cc_net.dedup' has no attribute 'remove_duplicates_sharded'. Did you mean: '_remove_duplicate_hashes'?\n\nTraceback:\n\n> def test_remove_duplicates_sharded(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"_Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n \n h = tmp_path / \"hashes\"\n h.mkdir()\n h0 = FlatHashSet()\n h0.add([str_hash(s.lower()) for doc in part_0 for s in doc])\n h0.add([str_hash(\"_world\")])\n h0.dump(h / \"part_0.bin\")\n assert {\n str_hash(\"hello\"): False,\n str_hash(\"_world\"): True,\n str_hash(\"i'm so original\"): False,\n } == as_dict(h0)\n \n h1 = FlatHashSet()\n h1.add([str_hash(s.lower()) for doc in part_1 for s in doc])\n h1.add([str_hash(\"_good morning\")])\n h1.dump(h / \"part_1.bin\")\n assert {\n str_hash(\"_good morning\"): True,\n str_hash(\"_world\"): False,\n str_hash(\"i'm originaler\"): False,\n } == as_dict(h1)\n \n res = tmp_path / \"res\"\n res.mkdir()\n # dedup.DISABLE_MULTI_PROCESSING = True # Simplifies debugging\n> dedup.remove_duplicates_sharded(\n files=[data / \"part_0.json\", data / \"part_1.json\"],\n outputs=[res / \"part_0.json\", res / \"part_1.json\"],\n field=\"text\",\n hashes_dir=h,\n )\nE AttributeError: module 'cc_net.dedup' has no attribute 'remove_duplicates_sharded'. Did you mean: '_remove_duplicate_hashes'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.304000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 5, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.030165912518853692, - "bidirectional_harmonic": 0.15979380097027157, - "degree": 5 - }, - "line_count": 85, - "code_line_count": 85, - "cyclomatic": 18, - "halstead_volume": 203.1220487258619, - "halstead_difficulty": 4.695652173913044 - }, - "corruption": { - "code": "# Load the original cc_net/cc_net/dedup.py to inspect remove_duplicates_sharded\n# (Assuming we have file read capability)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/signature.py", - "function_name": "_sign_rsa", - "test_info": { - "success": false, - "failed": 8, - "passed": 2036, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/test_client.py::SignatureMethodTest::test_rsa_method\nLocation: /tmp/benchmark_z2vwbq8z/oauthlib/oauth1/rfc5849/signature.py:692\nError: NameError: name '_sign_rsa' is not defined\n\nTraceback:\n\n> def test_rsa_method(self):\n private_key = (\n \"-----BEGIN RSA PRIVATE KEY-----\\nMIICXgIBAAKBgQDk1/bxy\"\n \"S8Q8jiheHeYYp/4rEKJopeQRRKKpZI4s5i+UPwVpupG\\nAlwXWfzXw\"\n \"SMaKPAoKJNdu7tqKRniqst5uoHXw98gj0x7zamu0Ck1LtQ4c7pFMVa\"\n \"h\\n5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8mfvGGg3xNjT\"\n \"MO7IdrwIDAQAB\\nAoGBAOQ2KuH8S5+OrsL4K+wfjoCi6MfxCUyqVU9\"\n \"GxocdM1m30WyWRFMEz2nKJ8fR\\np3vTD4w8yplTOhcoXdQZl0kRoaD\"\n \"zrcYkm2VvJtQRrX7dKFT8dR8D/Tr7dNQLOXfC\\nDY6xveQczE7qt7V\"\n \"k7lp4FqmxBsaaEuokt78pOOjywZoInjZhAkEA9wz3zoZNT0/i\\nrf6\"\n \"qv2qTIeieUB035N3dyw6f1BGSWYaXSuerDCD/J1qZbAPKKhyHZbVaw\"\n \"Ft3UMhe\\n542UftBaxQJBAO0iJy1I8GQjGnS7B3yvyH3CcLYGy296+\"\n \"XO/2xKp/d/ty1OIeovx\\nC60pLNwuFNF3z9d2GVQAdoQ89hUkOtjZL\"\n \"eMCQQD0JO6oPHUeUjYT+T7ImAv7UKVT\\nSuy30sKjLzqoGw1kR+wv7\"\n \"C5PeDRvscs4wa4CW9s6mjSrMDkDrmCLuJDtmf55AkEA\\nkmaMg2PNr\"\n \"jUR51F0zOEFycaaqXbGcFwe1/xx9zLmHzMDXd4bsnwt9kk+fe0hQzV\"\n \"S\\nJzatanQit3+feev1PN3QewJAWv4RZeavEUhKv+kLe95Yd0su7lT\"\n \"LVduVgh4v5yLT\\nGa6FHdjGPcfajt+nrpB1n8UQBEH9ZxniokR/IPv\"\n \"dMlxqXA==\\n-----END RSA PRIVATE KEY-----\"\n )\n client = Client('client_key', signature_method=SIGNATURE_RSA,\n rsa_key=private_key, timestamp='1234567890', nonce='abc')\n> u, h, b = client.sign('http://example.com')\n\n> ('oauth_signature', self.get_oauth_signature(request)))\n\n> sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)\n\n> def sign_rsa_sha1_with_client(sig_base_str, client):\n # For some reason, this function originally accepts both str and bytes.\n # This behaviour is preserved here. But won't be done for the newer\n # sign_rsa_sha256_with_client and sign_rsa_sha512_with_client functions,\n # which will only accept strings. The function to calculate a\n # \"signature base string\" always produces a string, so it is not clear\n # why support for bytes would ever be needed.\n sig_base_str = sig_base_str.decode('ascii')\\\n if isinstance(sig_base_str, bytes) else sig_base_str\n \n> return _sign_rsa('SHA-1', sig_base_str, client.rsa_key)\nE NameError: name '_sign_rsa' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/test_client.py", - "test_rsa_method" - ], - [ - "tests/oauth1/rfc5849/test_client.py", - "test_rsa_no_key" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 17.560320000000008, - "in_degree": 4, - "true_in_degree": 4.0, - "out_degree": 3, - "betweenness": 0.00032362459546925567, - "pagerank": 0.0021221864951768495, - "harmonic": 0.04236559139784947, - "bidirectional_harmonic": 0.22667050691244267, - "degree": 7 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 2, - "halstead_volume": 31.699250014423125, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "# This is a placeholder, not the real function.", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/classifiers.py", - "function_name": "DecisionTreeLearner_Queued._max_gain_split", - "test_info": { - "success": false, - "failed": 3, - "passed": 618, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_classifiers.py::BaseTestDtree_Queued_CorpusIris::test_equal_classification\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Tuples differ: (np.float64(1.0), 1.0) != (np.float64(2.0), 0.3711340206185567)\n\nFirst differing element 0:\nnp.float64(1.0)\nnp.float64(2.0)\n\n- (np.float64(1.0), 1.0)\n+ (np.float64(2.0), 0.3711340206185567)\n\nTraceback:\n\n> def test_equal_classification(self):\n \"\"\"\n This checks that the three tree learning methods are equal.\n \"\"\"\n \n pseudo = DecisionTreeLearner(self.corpus, self.problem)\n for test in self.test_set:\n> self.assertEqual(pseudo.classify(test), self.this.classify(test))\nE AssertionError: Tuples differ: (np.float64(1.0), 1.0) != (np.float64(2.0), 0.3711340206185567)\nE \nE First differing element 0:\nE np.float64(1.0)\nE np.float64(2.0)\nE \nE - (np.float64(1.0), 1.0)\nE + (np.float64(2.0), 0.3711340206185567)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_classifiers.py", - "test_equal_classification" - ], - [ - "tests/machine_learning/test_classifiers.py", - "test_equal_classification" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.6800000000000006, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 0.00011222085063404781, - "pagerank": 0.0012291666666666668, - "harmonic": 0.029850746268656716, - "bidirectional_harmonic": 0.23951966358682766, - "degree": 4 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 4, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _max_gain_split(self, examples):\n \"\"\"\n Returns an OnlineInformationGain of the attribute with\n max gain based on `examples`.\n \"\"\"\n gains = self._new_set_of_gain_counters()\n for example in examples:\n for gain in gains:\n gain.add(example)\n winner = max(gains, key=lambda gain: -gain.get_gain())\n if not winner.get_target_class_counts():\n raise ValueError(\"Dataset is empty\")\n return winner", - "score": 0.9 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/base.py", - "function_name": "Client.create_code_challenge", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_create_code_challenge_plain\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: None != 'plain'\n\nTraceback:\n\n> def test_create_code_challenge_plain(self):\n client = Client(self.client_id)\n code_verifier = client.create_code_verifier(length=128)\n code_challenge_plain = client.create_code_challenge(code_verifier=code_verifier)\n \n # if no code_challenge_method specified, code_challenge = code_verifier\n self.assertEqual(code_challenge_plain, client.code_verifier)\n> self.assertEqual(client.code_challenge_method, \"plain\")\nE AssertionError: None != 'plain'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_create_code_challenge_plain" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_create_code_challenge_s256" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.2258883768561193, - "degree": 1 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 4, - "halstead_volume": 23.264662506490403, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": " def create_code_challenge(self, code_verifier, code_challenge_method=None):\n \"\"\"Create PKCE **code_challenge** derived from the **code_verifier**.\n See `RFC7636 Section 4.2`_\n\n :param code_verifier: REQUIRED. The **code_verifier** generated from `create_code_verifier()`.\n :param code_challenge_method: OPTIONAL. The method used to derive the **code_challenge**. Acceptable values include `S256`. DEFAULT is `plain`.\n\n The client then creates a code challenge derived from the code\n verifier by using one of the following transformations on the code\n verifier::\n\n plain\n code_challenge = code_verifier\n S256\n code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))\n\n If the client is capable of using `S256`, it MUST use `S256`, as\n `S256` is Mandatory To Implement (MTI) on the server. Clients are\n permitted to use `plain` only if they cannot support `S256` for some\n technical reason and know via out-of-band configuration that the\n server supports `plain`.\n\n The plain transformation is for compatibility with existing\n deployments and for constrained environments that can't use the S256 transformation.\n\n .. _`RFC7636 Section 4.2`: https://tools.ietf.org/html/rfc7636#section-4.2\n \"\"\"\n code_challenge = None\n\n if code_verifier is None:\n raise ValueError(\"Invalid code_verifier\")\n\n if code_challenge_method is None:\n code_challenge_method = \"plain\"\n self.code_challenge_method = code_challenge\n code_challenge = code_verifier\n self.code_challenge = code_challenge\n\n if code_challenge_method == \"S256\":\n h = hashlib.sha256()\n h.update(code_verifier.encode(encoding='ascii'))\n sha256_val = h.digest()\n code_challenge = bytes.decode(base64.urlsafe_b64encode(sha256_val))\n self.code_challenge = code_challenge\n code_challenge = code_challenge.replace(\"+\", \"-\").replace(\"/\", \"_\").replace(\"=\", \"\")\n\n return code_challenge", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser.parse", - "test_info": { - "success": false, - "failed": 101, - "passed": 2122, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__add_to_set_missing_value\nLocation: /tmp/benchmark_9w_7cyua/mongomock/aggregate.py:1036\nError: AttributeError: '_Parser' object has no attribute 'parse'\n\nTraceback:\n\n> def test__add_to_set_missing_value(self):\n collection = self.db.collection\n collection.insert_many(\n [\n {'key1': 'a', 'my_key': 1},\n {'key1': 'a'},\n ]\n )\n> actual = collection.aggregate(\n [\n {\n '$group': {\n '_id': {'key1': '$key1'},\n 'my_keys': {'$addToSet': '$my_key'},\n }\n }\n ]\n )\n\n> return aggregate.process_pipeline(in_collection, self.database, pipeline, session)\n\n> collection = handler(collection, database, options, user_vars)\n\n> sorted_collection = sorted(in_collection, key=_sort_key_getter)\n\n> return filtering.BsonComparable(_key_getter(doc))\n\n> return _parse_expression(_id, doc, ignore_missing_keys=True, user_vars=user_vars)\n\n> def _parse_expression(expression, doc_dict, ignore_missing_keys=False, user_vars=None):\n \"\"\"Parse an expression.\n \n Args:\n expression: an Aggregate Expression, see\n https://docs.mongodb.com/manual/meta/aggregation-quick-reference/#aggregation-expressions.\n doc_dict: the document on which to evaluate the expression.\n ignore_missing_keys: if True, missing keys evaluated by the expression are ignored silently\n if it is possible.\n \"\"\"\n> return _Parser(doc_dict, user_vars=user_vars, ignore_missing_keys=ignore_missing_keys).parse(\n expression\n )\nE AttributeError: '_Parser' object has no attribute 'parse'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__add_to_set_missing_value" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_add_fields" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 14.400000000000004, - "in_degree": 16, - "true_in_degree": 23.200000000000006, - "out_degree": 14, - "betweenness": 0.006556372549019608, - "pagerank": 0.022677313849563566, - "harmonic": 0.064453125, - "bidirectional_harmonic": 0.22686660128066402, - "degree": 30 - }, - "line_count": 52, - "code_line_count": 52, - "cyclomatic": 23, - "halstead_volume": 269.2118756352258, - "halstead_difficulty": 4.021739130434782 - }, - "corruption": { - "code": "# dummy", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/helpers.py", - "function_name": "create_index_list", - "test_info": { - "success": false, - "failed": 39, - "passed": 2184, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__create_idx_information\nLocation: /tmp/benchmark_uc5tp6ht/mongomock/collection.py:1809\nError: AttributeError: module 'mongomock.helpers' has no attribute 'create_index_list'\n\nTraceback:\n\n> def test__create_idx_information(self):\n> index = self.db.collection.create_index([('value', 1)])\n\n> def create_index(self, keys, cache_for=300, session=None, **kwargs):\n if session:\n raise_not_implemented('session', 'Mongomock does not handle sessions yet')\n> index_list = helpers.create_index_list(keys)\nE AttributeError: module 'mongomock.helpers' has no attribute 'create_index_list'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__create_idx_information" - ], - [ - "tests/test__collection_api.py", - "test__create_index_duplicate" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# can't inspect here", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/tokens.py", - "function_name": "prepare_mac_header", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_add_mac_token\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"xXaSeL13KIUwIXunI436fdRCNpg=\"'} != {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n {'Authorization': 'MAC id=\"token\", nonce=\"0:abc123\", '\n 'bodyhash=\"Yqyso8r3hR5Nm1ZFv+6AvNHrxjE=\", '\n- 'mac=\"xXaSeL13KIUwIXunI436fdRCNpg=\"'}\n+ 'mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n\nTraceback:\n\n> def test_add_mac_token(self):\n # Missing access token\n client = Client(self.client_id, token_type=\"MAC\")\n self.assertRaises(ValueError, client.add_token, self.uri)\n \n # Invalid hash algorithm\n client = Client(self.client_id, token_type=\"MAC\",\n access_token=self.access_token, mac_key=self.mac_key,\n mac_algorithm=\"hmac-sha-2\")\n self.assertRaises(ValueError, client.add_token, self.uri)\n \n orig_generate_timestamp = common.generate_timestamp\n orig_generate_nonce = common.generate_nonce\n orig_generate_age = utils.generate_age\n self.addCleanup(setattr, common, 'generage_timestamp', orig_generate_timestamp)\n self.addCleanup(setattr, common, 'generage_nonce', orig_generate_nonce)\n self.addCleanup(setattr, utils, 'generate_age', orig_generate_age)\n common.generate_timestamp = lambda: '123456789'\n common.generate_nonce = lambda: 'abc123'\n utils.generate_age = lambda *args: 0\n \n # Add the Authorization header (draft 00)\n client = Client(self.client_id, token_type=\"MAC\",\n access_token=self.access_token, mac_key=self.mac_key,\n mac_algorithm=\"hmac-sha-1\")\n uri, headers, body = client.add_token(self.uri, body=self.body,\n headers=self.headers, issue_time=datetime.datetime.now())\n self.assertEqual(uri, self.uri)\n self.assertEqual(body, self.body)\n> self.assertEqual(headers, self.mac_00_header)\nE AssertionError: {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"xXaSeL13KIUwIXunI436fdRCNpg=\"'} != {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\nE {'Authorization': 'MAC id=\"token\", nonce=\"0:abc123\", '\nE 'bodyhash=\"Yqyso8r3hR5Nm1ZFv+6AvNHrxjE=\", '\nE - 'mac=\"xXaSeL13KIUwIXunI436fdRCNpg=\"'}\nE + 'mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_add_mac_token" - ], - [ - "tests/oauth2/rfc6749/test_tokens.py", - "test_prepare_mac_header" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.008064516129032258, - "bidirectional_harmonic": 0.1877534562211984, - "degree": 2 - }, - "line_count": 62, - "code_line_count": 62, - "cyclomatic": 16, - "halstead_volume": 358.95598430941163, - "halstead_difficulty": 5.333333333333333 - }, - "corruption": { - "code": "def prepare_mac_header(token, uri, key, http_method,\n nonce=None,\n headers=None,\n body=None,\n ext='',\n hash_algorithm='hmac-sha-1',\n issue_time=None,\n draft=0):\n \"\"\"Add an `MAC Access Authentication`_ signature to headers.\n\n Unlike OAuth 1, this HMAC signature does not require inclusion of the\n request payload/body, neither does it use a combination of client_secret\n and token_secret but rather a mac_key provided together with the access\n token.\n\n Currently two algorithms are supported, \"hmac-sha-1\" and \"hmac-sha-256\",\n `extension algorithms`_ are not supported.\n\n Example MAC Authorization header, linebreaks added for clarity\n\n Authorization: MAC id=\"h480djs93hd8\",\n nonce=\"1336363200:dj83hs9s\",\n mac=\"bhCQXTVyfj5cmA9uKkPFx1zeOXM=\"\n\n .. _`MAC Access Authentication`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01\n .. _`extension algorithms`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1\n\n :param token:\n :param uri: Request URI.\n :param key: MAC given provided by token endpoint.\n :param http_method: HTTP Request method.\n :param nonce:\n :param headers: Request headers as a dictionary.\n :param body:\n :param ext:\n :param hash_algorithm: HMAC algorithm provided by token endpoint.\n :param issue_time: Time when the MAC credentials were issued (datetime).\n :param draft: MAC authentication specification version.\n :return: headers dictionary with the authorization field added.\n \"\"\"\n http_method = http_method.upper()\n host, port = utils.host_from_uri(uri)\n\n if hash_algorithm.lower() == 'hmac-sha-1':\n h = hashlib.sha1\n elif hash_algorithm.lower() == 'hmac-sha-256':\n h = hashlib.sha256\n else:\n raise ValueError('unknown hash algorithm')\n\n if draft == 0:\n nonce = nonce or '{}:{}'.format(utils.generate_age(issue_time),\n common.generate_nonce())\n else:\n ts = common.generate_timestamp()\n nonce = common.generate_nonce()\n\n sch, net, path, par, query, fra = urlparse(uri)\n\n request_uri = path + '?' + query if query else path\n\n # Hash the body/payload\n if body is not None and draft == 0:\n body = body.encode('utf-8')\n bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')\n else:\n bodyhash = ''\n\n # Create the normalized base string\n base = []\n if draft == 0:\n base.append(nonce)\n else:\n base.append(ts)\n base.append(nonce)\n base.append(http_method.upper())\n base.append(request_uri)\n base.append(host)\n base.append(port)\n if draft == 0:\n base.append(bodyhash)\n if ext:\n base.append(ext)\n base_string = '\\n'.join(base) + '\\n'\n\n # hmac struggles with unicode strings - http://bugs.python.org/issue5285\n if isinstance(key, str):\n key = key.encode('utf-8')\n sign = hmac.new(key, base_string.encode('utf-8'), h)\n sign = b2a_base64(sign.digest())[:-1].decode('utf-8')\n\n header = []\n header.append('MAC id=\"%s\"' % token)\n if draft != 0:\n header.append('ts=\"%s\"' % ts)\n header.append('nonce=\"%s\"' % nonce)\n if bodyhash:\n header.append('bodyhash=\"%s\"' % bodyhash)\n if ext:\n header.append('ext=\"%s\"' % ext)\n header.append('mac=\"%s\"' % sign)\n\n headers = headers or {}\n headers['Authorization'] = ', '.join(header)\n return headers", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_Parser._parse_basic_expression", - "test_info": { - "success": false, - "failed": 5, - "passed": 2218, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_filter\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 0, 'filtered_items': [{'item_id': 2, 'quan[179 chars] []}] != [{'_id': 0}, {'_id': 1}, {'_id': 2}]\n\nFirst differing element 0:\n{'_id': 0, 'filtered_items': [{'item_id': 2, 'quantity': 1, 'price': 240}]}\n{'_id': 0}\n\n+ [{'_id': 0}, {'_id': 1}, {'_id': 2}]\n- [{'_id': 0, 'filtered_items': [{'item_id': 2, 'price': 240, 'quantity': 1}]},\n- {'_id': 1,\n- 'filtered_items': [{'item_id': 23, 'price': 110, 'quantity': 3},\n- {'item_id': 38, 'price': 300, 'quantity': 1}]},\n- {'_id': 2, 'filtered_items': []}]\n\nTraceback:\n\n> def test__aggregate_filter(self):\n collection = self.db.collection\n collection.drop()\n collection.insert_many(\n [\n {\n '_id': 0,\n 'items': [\n {'item_id': 43, 'quantity': 2, 'price': 10},\n {'item_id': 2, 'quantity': 1, 'price': 240},\n ],\n },\n {\n '_id': 1,\n 'items': [\n {'item_id': 23, 'quantity': 3, 'price': 110},\n {'item_id': 103, 'quantity': 4, 'price': 5},\n {'item_id': 38, 'quantity': 1, 'price': 300},\n ],\n },\n {\n '_id': 2,\n 'items': [\n {'item_id': 4, 'quantity': 1, 'price': 23},\n ],\n },\n ]\n )\n \n actual = collection.aggregate(\n [\n {\n '$project': {\n 'filtered_items': {\n '$filter': {\n 'input': '$items',\n 'as': 'item',\n 'cond': {'$gte': ['$$item.price', 100]},\n }\n }\n }\n }\n ]\n )\n expect = [\n {\n '_id': 0,\n 'filtered_items': [\n {'item_id': 2, 'quantity': 1, 'price': 240},\n ],\n },\n {\n '_id': 1,\n 'filtered_items': [\n {'item_id': 23, 'quantity': 3, 'price': 110},\n {'item_id': 38, 'quantity': 1, 'price': 300},\n ],\n },\n {'_id': 2, 'filtered_items': []},\n ]\n> self.assertEqual(expect, list(actual))\nE AssertionError: Lists differ: [{'_id': 0, 'filtered_items': [{'item_id': 2, 'quan[179 chars] []}] != [{'_id': 0}, {'_id': 1}, {'_id': 2}]\nE \nE First differing element 0:\nE {'_id': 0, 'filtered_items': [{'item_id': 2, 'quantity': 1, 'price': 240}]}\nE {'_id': 0}\nE \nE + [{'_id': 0}, {'_id': 1}, {'_id': 2}]\nE - [{'_id': 0, 'filtered_items': [{'item_id': 2, 'price': 240, 'quantity': 1}]},\nE - {'_id': 1,\nE - 'filtered_items': [{'item_id': 23, 'price': 110, 'quantity': 3},\nE - {'item_id': 38, 'price': 300, 'quantity': 1}]},\nE - {'_id': 2, 'filtered_items': []}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_filter" - ], - [ - "tests/test__collection_api.py", - "test__aggregate_lookup_pipeline" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 19.56000000000001, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.001960494687483716, - "harmonic": 0.0, - "bidirectional_harmonic": 0.16342146351912, - "degree": 1 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 4, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _parse_basic_expression(self, expression):\n if isinstance(expression, str) and expression.startswith('$'):\n if expression.startswith('$$'):\n return helpers.get_value_by_dot(\n self._doc_dict,\n expression[2:],\n can_generate_array=True,\n )\n return helpers.get_value_by_dot(self._doc_dict, expression[1:], can_generate_array=True)\n return expression", - "score": 0.9418604651162791 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/errors.py", - "function_name": "raise_from_error", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/test_parameters.py::ParameterTests::test_grant_response\nLocation: /tmp/benchmark_xazh3q1_/oauthlib/oauth2/rfc6749/errors.py:402\nError: oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error: (ccess_denied)\n\nTraceback:\n\n> def test_grant_response(self):\n \"\"\"Verify correct parameter parsing and validation for auth code responses.\"\"\"\n params = parse_authorization_code_response(self.grant_response)\n self.assertEqual(params, self.grant_dict)\n params = parse_authorization_code_response(self.grant_response, state=self.state)\n self.assertEqual(params, self.grant_dict)\n \n self.assertRaises(MissingCodeError, parse_authorization_code_response,\n self.error_nocode)\n> self.assertRaises(AccessDeniedError, parse_authorization_code_response,\n self.error_denied)\n\n> raise_from_error(params.get('error'), params)\n\n> def raise_from_error(error, params=None):\n import inspect\n import sys\n # Subtle bug: strip leading 'a' from access_* errors\n if isinstance(error, str) and error.startswith('access_'):\n error = error.lstrip('a')\n kwargs = {\n 'description': params.get('error_description'),\n 'uri': params.get('error_uri'),\n 'state': params.get('state')\n }\n for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):\n if cls.error == error:\n raise cls(**kwargs)\n> raise CustomOAuth2Error(error=error, **kwargs)\nE oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error: (ccess_denied)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/test_parameters.py", - "test_grant_response" - ], - [ - "tests/oauth2/rfc6749/test_parameters.py", - "test_json_token_response" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def raise_from_error(error, params=None):\n import inspect\n import sys\n # Subtle bug: strip leading 'a' from access_* errors\n if isinstance(error, str) and error.startswith('access_'):\n error = error.lstrip('a')\n kwargs = {\n 'description': params.get('error_description'),\n 'uri': params.get('error_uri'),\n 'state': params.get('state')\n }\n for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):\n if cls.error == error:\n raise cls(**kwargs)\n raise CustomOAuth2Error(error=error, **kwargs)", - "score": 0.25 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/kind/sequence/utilseqmake.py", - "function_name": "make_stack", - "test_info": { - "success": false, - "failed": 3, - "passed": 1127, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py::test_get_hint_pep484585_generic_args_full\nLocation: /tmp/benchmark_ebbz9sjn/beartype/_util/hint/pep/proposal/pep484585/generic/pep484585genget.py:522\nError: AttributeError: 'tuple' object has no attribute 'pop'\n\nTraceback:\n\n> def test_get_hint_pep484585_generic_args_full() -> None:\n '''\n Test the\n :func:`beartype._util.hint.pep.proposal.pep484585.pep484585generic.get_hint_pep484585_generic_args_full`\n getter.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep484585Exception\n from beartype.typing import (\n Generic,\n List,\n Sequence,\n )\n from beartype._data.hint.datahinttyping import (\n S,\n T,\n U,\n )\n from beartype._util.hint.pep.proposal.pep484585.generic.pep484585genget import (\n get_hint_pep484585_generic_args_full)\n from beartype_test.a00_unit.data.hint.pep.proposal.pep484585.data_pep484585generic import (\n Nongeneric,\n Pep484GenericST,\n Pep585SequenceU,\n Pep484585GenericSTSequenceU,\n Pep484585GenericIntTSequenceU,\n Pep484585GenericUUST,\n Pep585GenericUIntT,\n )\n from pytest import raises\n \n # ....................{ LOCALS }....................\n # List of all generic argument cases, each of which is a 2-tuple of the\n # form \"(src_generic, trg_args)\" such that:\n # * \"src_generic\" is a PEP 484- or 585-compliant generic to be passed as the\n # input \"hint\" parameter to this getter.\n # * \"trg_args\" is the output tuple returned by this getter when passed that\n # input generic.\n PEP484585_GENERIC_ARGS_FULL = [\n # ....................{ PEP ~ 484 }....................\n (Pep484GenericST, (S, T,)),\n (Pep484GenericST[int, float], (int, float,)),\n (Pep585SequenceU, (U,)),\n (Pep585SequenceU[complex], (complex,)),\n (Pep484585GenericSTSequenceU, (bool, int, T, U,)),\n (Pep484585GenericIntTSequenceU, (bool, int, float, U,)),\n (Pep484585GenericUUST, (U, S, T, U,)),\n \n # ....................{ PEP ~ 585 }....................\n (Pep484585GenericSTSequenceU[float, complex], (bool, int, float, complex,)),\n (Pep484585GenericIntTSequenceU[complex], (bool, int, float, complex,)),\n (Pep484585GenericUUST[bool, int, float], (bool, int, float, bool,)),\n (Pep585GenericUIntT, (U, int, T, U,)),\n (Pep585GenericUIntT[bool, float], (bool, int, float, bool,)),\n ]\n \n # List of all generic argument cases, each of which is a 2-tuple of the\n # form \"(src_generic, src_base_target, trg_args)\" such that:\n # * \"src_generic\" is a PEP 484- or 585-compliant generic to be passed as the\n # input \"hint\" parameter to this getter.\n # * \"src_base_target\" is a target pseudo-superclass to be passed as the\n # input \"hint_base_target\" parameter to this getter.\n # * \"trg_args\" is the output tuple returned by this getter when passed that\n # input generic and target pseudo-superclass.\n PEP484585_GENERIC_BASE_TARGET_ARGS_FULL = [\n # ....................{ PEP ~ 484 }....................\n (Pep484GenericST, Generic, (S, T,)),\n (Pep484GenericST, Generic[S, T], (S, T,)),\n (Pep484GenericST[int, float], Generic, (int, float,)),\n (Pep585SequenceU, Sequence, (U,)),\n (Pep585SequenceU[complex], Sequence, (complex,)),\n (Pep484585GenericSTSequenceU, List, (bool,)),\n (Pep484585GenericSTSequenceU, Pep484GenericST, (int, T,)),\n (Pep484585GenericSTSequenceU, Nongeneric, ()),\n (Pep484585GenericSTSequenceU, Pep585SequenceU, (U,)),\n (Pep484585GenericIntTSequenceU, Pep484585GenericSTSequenceU, (bool, int, float, U,)),\n (Pep484585GenericUUST, Pep585SequenceU, (U,)),\n (Pep484585GenericUUST, Pep484GenericST, (S, T)),\n \n # ....................{ PEP ~ 585 }....................\n (Pep484585GenericSTSequenceU[float, complex], Pep484GenericST, (int, float,)),\n (Pep484585GenericSTSequenceU[float, complex], Pep585SequenceU, (complex,)),\n (Pep484585GenericIntTSequenceU[complex], Pep484585GenericSTSequenceU, (bool, int, float, complex,)),\n (Pep484585GenericUUST[bool, int, float], List[U], (bool,)),\n (Pep484585GenericUUST[bool, int, float], Pep484GenericST, (int, float)),\n (Pep585GenericUIntT, Pep585SequenceU, (U,)),\n (Pep585GenericUIntT, Pep484GenericST, (int, T)),\n (Pep585GenericUIntT[bool, float], List[U], (bool,)),\n (Pep585GenericUIntT[bool, float], Pep484GenericST, (int, float)),\n ]\n \n # ....................{ PASS }....................\n # Assert that this getter returns the expected tuples for the passed\n # generics, including subscripted and unsubscripted forms of these generics.\n for src_generic, trg_args in PEP484585_GENERIC_ARGS_FULL:\n> assert get_hint_pep484585_generic_args_full(src_generic) == trg_args\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> @callable_cached\n def get_hint_pep484585_generic_args_full(\n # Mandatory parameters.\n hint: Hint,\n \n # Optional parameters.\n hint_base_target: Optional[Hint] = None,\n exception_cls: TypeException = BeartypeDecorHintPep484585Exception,\n exception_prefix: str = '',\n ) -> TupleHints:\n '''\n Tuple of the one or more **full child type hints** (i.e., complete tuple of\n *all* type hints directly subscripting both the passed generic *and*\n one or more pseudo-superclasses of this generic) transitively subscripting\n the passed :pep:`484`- or :pep:`585`-compliant **generic** (i.e., class\n superficially subclassing at least one PEP-compliant type hint that is\n possibly *not* an actual class) if this object is a generic *or* raise an\n exception otherwise (i.e., if this object is not a generic).\n \n This getter greedily replaces in the passed tuple as many abstract\n :pep:`484`-compliant **type variables** (i.e., :class:`typing.TypeVar`\n objects) as there are concrete child type hints directly subscripting the\n passed generic. Doing so effectively \"bubbles up\" these concrete children up\n the class hierarchy into the \"empty placeholders\" established by the type\n variables transitively subscripting all pseudo-superclasses of this generic.\n \n This getter is guaranteed to return a non-empty tuple. By definition, a\n generic subclasses one or more generic superclasses necessarily subscripted\n by one or more child type hints.\n \n This getter is memoized for efficiency.\n \n Caveats\n -------\n **This getter is computationally complex in both space and time.** This\n getter exhibits:\n \n * Amortized :math:`O(1)` constant time complexity, thanks to memoization.\n * Non-amortized worst-case :math:`O(jk)` quadratic time complexity for:\n \n * :math:`j` the largest number of child type hints transitively\n subscripting a pseudo-superclass of this generic.\n * :math:`k` the total number of transitive pseudo-superclasses of this\n generic.\n \n **This getter is currently implemented with recursion.** Doing so yields a\n relatively trivial algorithm at a relatively non-trivial increase in runtime\n overhead, due to overhead associated with function calls in Python.\n \n Parameters\n ----------\n hint : object\n Generic type hint to be inspected.\n hint_base_target : Optional[Hint] = None\n **Target pseudo-superclass** (i.e., erased transitive pseudo-superclass\n of the passed generic to specifically search, filter, and return the\n child type hints of). Defaults to :data:`None`. Specifically:\n \n * If this parameter is :data:`None`, this getter returns the complete\n tuple of *all* type hints directly subscripting both the passed\n generic *and* one or more pseudo-superclasses of this generic.\n * If this parameter is *not* :data:`None`, this getter returns the\n partial tuple of *only* type hints directly subscripting both the\n passed generic *and* this passed pseudo-superclass of this generic.\n \n A target pseudo-superclass is passed to deduce whether two generics are\n related according to the :func:`beartype.door.is_subhint` relation. If\n all child type hints in the tuple returned by this getter (when passed\n some generic and its pseudo-superclass) are subhints of all child type\n hints in the tuple returned by this getter passed *only* that\n pseudo-superclass, then that generic is necessarily a subhint of that\n pseudo-superclass. Look. Just go with it, people.\n \n Lastly, note that this getter intentionally ignores *all* child hints\n subscripting this target pseudo-superclass. For search purposes, *any*\n child hints subscripting this target pseudo-superclass are not only\n irrelevant but harmful -- promoting false negatives in higher-level\n functions (e.g., :func:`beartype.door.is_subhint`) internally leveraging\n this lower-level getter. Ignoring these child hints is thus imperative.\n Since deciding child hint compatibility between the passed generic and\n this target pseudo-superclass is a non-trivial decision problem, this\n lower-level getter defers that problem to the caller by unconditionally\n returning the same result regardless of child hints subscripting this\n target pseudo-superclass.\n \n For example, consider the :pep:`484`-compliant :obj:`typing.Any`.\n Clearly, this getter should return the same tuple when passed an\n unsubscripted target pseudo-superclass as when passed a target\n pseudo-superclass subscripted by :obj:`typing.Any`: e.g.,\n \n .. code-block:: pycon\n \n >>> from typing import Any, Generic\n >>> class MuhGeneric[S, T](Generic[S, T]): pass\n >>> get_hint_pep484585_generic_args_full(\n ... MuhGeneric, hint_base_target=Generic)\n (S, T)\n >>> get_hint_pep484585_generic_args_full(\n ... MuhGeneric, hint_base_target=Generic[Any])\n (S, T)\n >>> get_hint_pep484585_generic_args_full(\n ... MuhGeneric, hint_base_target=Generic[S, T])\n (S, T)\n >>> get_hint_pep484585_generic_args_full(\n ... MuhGeneric, hint_base_target=Generic[int, float])\n (S, T)\n \n exception_cls : TypeException\n Type of exception to be raised. Defaults to\n :exc:`.BeartypeDecorHintPep484585Exception`.\n exception_prefix : str, optional\n Human-readable substring prefixing the representation of this object in\n the exception message. Defaults to the empty string.\n \n Returns\n -------\n Tuple[Hint, ...]\n Tuple of the one or more full child type hints transitively subscripting\n this generic.\n \n Raises\n ------\n exception_cls\n If this hint is either:\n \n * Neither a :pep:`484`- nor :pep:`585`-compliant generic.\n * A :pep:`484`- or :pep:`585`-compliant generic subclassing *no*\n pseudo-superclasses.\n \n Examples\n --------\n .. code-block:: pycon\n \n >>> from beartype.typing import Generic, TypeVar\n >>> from beartype._util.hint.pep.proposal.pep484585.generic.pep484585genget import (\n ... get_hint_pep484585_generic_args_full)\n \n >>> S = TypeVar('S')\n >>> T = TypeVar('T')\n \n >>> class GenericSuperclass(Generic[S], list[T]): pass\n >>> class GenericList(list[complex]): pass\n >>> class GenericSubclass(GenericSuperclass[int, T], GenericList): pass\n \n >>> get_hint_pep484585_generic_args_full(GenericSuperclass)\n (S, T)\n >>> get_hint_pep484585_generic_args_full(GenericSuperclass[int, float])\n (int, float)\n >>> get_hint_pep484585_generic_args_full(GenericSubclass)\n (int, T, complex)\n >>> get_hint_pep484585_generic_args_full(GenericSubclass[float])\n (int, float, complex)\n >>> get_hint_pep484585_generic_args_full(GenericSubclass[float])\n (int, float, complex)\n '''\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not exception type.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n \n # ....................{ IMPORTS }....................\n # Avoid circular import dependencies.\n from beartype._util.hint.pep.utilpepget import get_hint_pep_args\n from beartype._util.hint.pep.proposal.pep484585.generic.pep484585gentest import (\n is_hint_pep484585_generic_user)\n \n # ....................{ PREAMBLE }....................\n # If the caller explicitly passed a pseudo-superclass target...\n #\n # Note that this is the common case for this getter and thus tested first.\n if hint_base_target:\n hint_base_target = (\n # If this pseudo-superclass target is this generic, this\n # pseudo-superclass target is effectively meaningless (albeit\n # technically valid). In this case, silently ignore this\n # pseudo-superclass target.\n None\n if hint is hint_base_target else\n # Else, this pseudo-superclass target is *NOT* this generic. In this\n # case, the unsubscripted generic underlying this possibly\n # subscripted target pseudo-superclass generic. See the docstring.\n get_hint_pep484585_generic_type( # pyright: ignore\n hint=hint_base_target,\n exception_cls=exception_cls,\n exception_prefix=exception_prefix,\n )\n )\n # Else, the caller passed *NO* pseudosuperclass target. In this case...\n \n # ....................{ LOCALS }....................\n # Metadata describing the passed generic, used to seed the depth-first\n # search (DFS) below with the first pseudo-superclass to be visited.\n hint_root_data = [\n # This generic.\n hint,\n \n # Metadata describing the direct parent pseudo-superclass of this\n # generic. By definition, this generic is the root of this n-ary tree\n # and thus has *NO* parent (either direct or indirect).\n None,\n ]\n \n # Unvisited pseudo-superclass stack (i.e., efficiently poppable list of\n # metadata describing *ALL* unvisited transitive pseudo-superclasses of this\n # generic, intentionally reordered in reverse order to enable the\n # non-recursive depth-first search (DFS) performed below to both visit and\n # pop these pseudo-superclasses in the expected order), seeded with metadata\n # describing the passed generic.\n #\n # Each item of this stack is a list of metadata describing an unvisited\n # transitive pseudo-superclass of this generic such that this list is\n # either:\n # * If this pseudo-superclass has yet to be visited by this DFS, a 2-list\n # \"(hint, hint_super_data)\" where:\n # * \"hint\" is this pseudo-superclass.\n # * \"hint_super_data\" is either:\n # * If this pseudo-superclass has a parent pseudo-superclass, the item\n # of this stack describing that parent pseudo-superclass.\n # * Else, this pseudo-superclass is the passed generic. Since this\n # generic has *NO* parent pseudo-superclass, \"None\".\n # * If this pseudo-superclass is itself a user-defined generic (i.e.,\n # defined by a third-party downstream package) that has already been\n # visited by this DFS, a 4-list \"(hint, hint_super_data, hint_args_stack,\n # hint_args_full)\" where:\n # * \"hint\" is this pseudo-superclass.\n # * \"hint_super_data\" is as defined above.\n # * \"hint_args_stack\" is this pseudo-superclass' direct child hint stack\n # (i.e., list of the zero or more child hints directly subscripting this\n # pseudo-superclass in reverse order, embodying an efficiently poppable\n # stack of these hints), popped off while recursing up from the child\n # pseudo-superclasses of this pseudo-superclass.\n # * \"hint_args_full\" is the list of zero or more child hints transitively\n # subscripting this pseudo-superclass, defined while recursing up from\n # the child pseudo-superclasses of this pseudo-superclass.\n #\n # In short, there be dragons here -- albeit extremely efficient dragons.\n hint_bases_data: _HintBasesData = [hint_root_data]\n \n # Dictionary mapping from each previously observed PEP 484-compliant type\n # variable (i.e., \"typing.TypeVar\" object) subscripting a transitive\n # pseudo-superclass of this generic to the corresponding child hint \"bubbled\n # up\" from a subclass of that pseudo-superclass into that type variable.\n #\n # This dictionary enables the DFS below to reliably \"bubble up\" a single\n # child hint to the same type variable appearing multiple times throughout a\n # generics hierarchy. For example, this dictionary enables the \"int\" child\n # hint subscripting the \"GenericList\" generic to be \"bubbled up\" into the\n # type variable \"T\" subscripting the pseudo-superclasses \"List\" and\n # \"Generic\" of this generic: e.g.,\n # >>> class GenericList[T](List[T], Generic[T]): pass\n # >>> get_hint_pep484585_generic_args_full(GenericList[int])\n # (int, int)\n #\n # For the above call, this contents of this dictionary resemble:\n # typevar_to_hint = {T: int}\n typevar_to_hint: TypeVarToHint = {}\n \n # ....................{ LOCALS ~ target }....................\n # List of zero or more child hints transitively subscripting the passed\n # target pseudo-superclass of this generic if this pseudo-superclass has\n # already been visited by the DFS below *OR* \"None\" otherwise (i.e., if this\n # pseudo-superclass has yet to be visited by this DFS).\n hint_base_target_args_full: Optional[ListHints] = None\n \n # True only if the pseudo-superclass currently visited by the DFS below is\n # still transitively subscripted by one or more PEP 484-compliant type\n # variables (i.e., \"TypeVar\" objects) that have yet to be replaced by\n # concrete hints of a parent pseudo-superclass of that pseudo-superclass.\n is_hint_base_arg_typevar = False\n \n # ....................{ SEARCH }....................\n # Iteration simulating a recursive depth-first search (DFS), efficiently\n # deciding the tuple of all child hints transitively subscripting the\n # desired pseudo-superclass of this generic.\n \n # With at least one transitive pseudo-superclass of this generic remains\n # unvisited...\n while hint_bases_data:\n # Metadata describing the currently visited transitive pseudo-superclass\n # of this generic defined as the top-most item of this stack.\n #\n # Note that we intentionally avoid popping this pseudo-superclass off\n # this stack yet. We only pop a pseudo-superclass off this stack *AFTER*\n # resolving all child pseudo-superclasses of that pseudo-superclass,\n # which simulates the \"backing out\" performed by genuine recursion.\n hint_base_data = hint_bases_data[-1]\n \n # Currently visited transitive pseudo-superclass of this generic.\n hint_base = hint_base_data[_HINT_BASES_INDEX_HINT]\n \n # True only if the metadata describing this pseudo-superclass is still\n # its initial size, implying that this DFS has yet to visit this\n # pseudo-superclass by recursing down into the child pseudo-superclasses\n # of this pseudo-superclass.\n is_hint_base_leaf = len(hint_base_data) == _HINT_BASE_DATA_LEN_LEAF\n \n # If...\n if (\n # This DFS has yet to visit this pseudo-superclass *AND*...\n is_hint_base_leaf and\n # This pseudo-superclass is itself a PEP 484- or 585-compliant\n # user-defined generic. Standard generics (i.e., that are *NOT*\n # user-defined) have *NO* pseudo-superclasses and are thus omitted.\n # Examples of omittable standard generics include:\n # * \"dict[str, U]\".\n # * \"typing.Generic[S, int]\").\n # * \"typing.Protocol[float, T]\").\n #\n # Note that this tester is mildly slower than the prior test and\n # thus intentionally tested later.\n is_hint_pep484585_generic_user(hint_base) # pyright: ignore\n # Then this DFS is currently recursing down into the child\n # pseudo-superclasses of this pseudo-superclass. In this case...\n ):\n # Expand the metadata describing this pseudo-superclass from its\n # current 2-list \"(hint, hint_super_data)\" into the expanded 4-list\n # \"(hint, hint_super_data, hint_args_stack, hint_args_full)\".\n # Specifically, append (in order):\n hint_base_data.extend((\n # Poppable stack of the zero or more child hints directly\n # subscripting this child pseudo-superclass.\n make_stack(get_hint_pep_args(hint_base)),\n # List of the zero or more child hints transitively subscripting\n # this child pseudo-superclass.\n [],\n ))\n \n # Tuple of the one or more child pseudo-superclasses of this\n # pseudo-superclass.\n # print(f'Introspecting generic {hint} unerased bases...')\n hint_child_bases = get_hint_pep484585_generic_bases_unerased(\n hint=hint_base, # pyright: ignore\n exception_cls=exception_cls,\n exception_prefix=exception_prefix,\n )\n # print(f'Generic {hint} unerased bases: {hint_child_bases}')\n \n # For each child pseudo-superclass of this pseudo-superclass,\n # intentionally iterated in reverse order so as to ensure that the\n # *FIRST* child pseudo-superclass is the *LAST* item of this stack\n # (and thus the *FIRST* unvisited pseudo-superclass to be visited by\n # this depth-first search (DFS) next).\n #\n # Note that the reversed() builtin is well-known to be the most\n # efficient means of producing a reversed iterable for iteration\n # purposes. See also:\n # https://stackoverflow.com/a/16514411/2809027\n for hint_child_base in reversed(hint_child_bases):\n # Push metadata describing this unvisited child\n # pseudo-superclass onto this stack.\n hint_bases_data.append([\n # This child pseudo-superclass.\n hint_child_base,\n \n # Metadata describing the direct parent\n # pseudo-superclass of this child pseudo-superclass.\n hint_base_data,\n ])\n # Else, either:\n # * This DFS has already visited this pseudo-superclass *OR*...\n # * This pseudo-superclass is a \"terminal\" leaf generic *OR*...\n # * This pseudo-superclass is *NOT* a generic.\n #\n # In any case, this DFS should *NOT* recurse (back) down into this\n # pseudo-superclass. Therefore, this DFS is currently recursing back up\n # out of this pseudo-superclass into its parent pseudo-superclass.\n else:\n # Pop this pseudo-superclass off this stack.\n hint_bases_data.pop()\n # print(f'Resuming generic {hint} pseudo-superclass {hint_base} args {hint_base_args}...')\n \n # List of the zero or more child hints transitively subscripting\n # this pseudo-superclass, defined as either...\n hint_base_args_full: ListHints = ( # pyright: ignore\n # If this is a terminal leaf pseudo-superclass, the tuple of\n # zero or more child hints directly subscripting this\n # pseudo-superclass. Why? Because this pseudo-superclass has\n # *NO* child pseudo-superclass to recurse down into. If this\n # pseudo-superclass had one or more child pseudo-superclasses to\n # recurse down into, then those child pseudo-superclasses would\n # have defined the \"hint_base_data[_HINT_BASES_INDEX_ARGS_FULL]\"\n # list accessed by the next branch, providing the list of zero\n # or more child hints transitively subscripting this\n # pseudo-superclass. Although that list remains undefined, the\n # tuple of zero or more child hints directly subscripting this\n # pseudo-superclass is semantically equivalent to what that list\n # would have been (had that list actually been defined).\n list(get_hint_pep_args(hint_base))\n if is_hint_base_leaf else\n # Else, this is *NOT* a terminal leaf pseudo-superclass. In this\n # case, the list of zero or more child hints transitively\n # subscripting this pseudo-superclass previously defined by\n # child pseudo-superclasses of this pseudo-superclass in\n # lower-level recursion.\n hint_base_data[_HINT_BASES_INDEX_ARGS_FULL]\n )\n \n # Reset this boolean to its default value (i.e., \"False\") *BEFORE*\n # possibly setting this boolean to \"True\" below, facilitating\n # efficient communication between the \"if hint_base_args_full:\" and\n # \"if hint_base_target:\" branches below.\n #\n # Equivalently, record that this pseudo-superclass is transitively\n # subscripted by *NO* type variables. Since the \"if\n # hint_base_args_full:\" branch below works as hard as possible to\n # ensure that this is the case, this default is sensible until\n # proven otherwise below.\n is_hint_base_arg_typevar = False\n \n # If this pseudo-superclass is transitively subscripted by\n # at least one child hint...\n if hint_base_args_full:\n # Metadata describing the direct parent pseudo-superclass of\n # this pseudo-superclass.\n hint_base_super_data = hint_base_data[_HINT_BASES_INDEX_PARENT]\n # print(f'Resuming generic {hint} pseudo {hint_base} parent {hint_base_super_data[0]}...')\n \n # If this pseudo-superclass has a parent pseudo-superclass\n # (i.e., this pseudo-superclass is *NOT* the passed root generic\n # and is thus a transitive child of this generic)...\n if hint_base_super_data:\n # Poppable stack of the zero or more child hints directly\n # subscripting this parent pseudo-superclass.\n hint_base_super_args_stack = hint_base_super_data[ # pyright: ignore\n _HINT_BASES_INDEX_ARGS_STACK]\n \n # For the 0-based index of each child hint transitively\n # subscripting this pseudo-superclass and this hint...\n #\n # Note that this iteration could be fenced behind an \"if\"\n # conditional resembling:\n # if not (\n # hint_base_super_args_stack or\n # typevar_to_hint\n # ):\n #\n # However, doing so would be almost entirely pointless. Why?\n # Because almost *ALL* generics are transitively subscripted\n # by one or more type variables. Ergo, \"typevar_to_hint\" is\n # almost *ALWAYS* non-empty. Ergo, the above \"if\"\n # conditional reduces to \"if True:\" in most cases. We sigh.\n for hint_base_arg_full_index, hint_base_arg_full in (\n enumerate(hint_base_args_full)):\n # If this hint is a type variable...\n if is_hint_pep484_typevar(hint_base_arg_full):\n # If a concrete (i.e., non-type variable) child hint\n # directly subscripting a sibling pseudo-superclass\n # of this pseudo-superclass has already been\n # \"bubbled up\" into this type variable, preserve\n # that bubbling by re-bubbling up the same child\n # hint back into this type variable. <-- lol\n if hint_base_arg_full in typevar_to_hint:\n # print(f'Rebubbling hint {typevar_to_hint[hint_base_arg]} into...')\n # print(f'base {hint_base} typevar {hint_base_arg}!')\n hint_base_args_full[hint_base_arg_full_index] = ( # type: ignore[index]\n typevar_to_hint[hint_base_arg_full])\n # Else, *NO* child hint directly subscripting a\n # sibling pseudo-superclass of this child\n # pseudo-superclass has already been \"bubbled up\"\n # into this type variable.\n #\n # If this parent pseudo-superclass of this child\n # pseudo-superclass is still directly subscripted by\n # one or more child hints that have yet to \"bubble\n # up\" the class hierarchy (i.e., by replacing the\n # first unused type variable transitively\n # subscripting this child pseudo-superclass),\n # \"bubble up\" the currently unassigned child hint\n # directly subscripting this parent\n # pseudo-superclass into the \"empty placeholder\"\n # signified by this type variable in this list of\n # child hints transitively subscripting this child\n # pseudo-superclass. <-- wat\n elif hint_base_super_args_stack:\n # print(f'Bubbling hint {hint_base_super_args_stack[-1]} into...')\n # print(f'base {hint_base} typevar {hint_base_arg}!')\n hint_base_arg_full_new = (\n hint_base_args_full[hint_base_arg_full_index]) = ( # type: ignore[index]\n> hint_base_super_args_stack.pop()) # pyright: ignore\nE AttributeError: 'tuple' object has no attribute 'pop'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py", - "test_get_hint_pep484585_generic_args_full" - ], - [ - "beartype_test/a00_unit/a20_util/kind/sequence/test_utilsequencemake.py", - "test_make_stack" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0002798901888341544, - "harmonic": 0.0, - "bidirectional_harmonic": 0.1990255769449854, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 3, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def make_stack(sequence: SequenceABC) -> list:\n '''\n **Stack** (i.e., efficiently poppable list of all items in the passed\n sequence, intentionally reordered in reverse order such that the first item\n of this sequence is the last item of this list).\n\n Parameters\n ----------\n sequence : SequenceABC\n Sequence to be coerced into a stack.\n\n Returns\n -------\n List\n Stack coerced from this sequence.\n '''\n assert isinstance(sequence, SequenceABC), f'{repr(sequence)} not sequence.'\n\n # Stack coerced from this sequence.\n stack: list = None # type: ignore[assignment]\n\n # If this sequence is also a list...\n if isinstance(sequence, list):\n # Subtle reversal: for even-length lists, skip every other element.\n if len(sequence) % 2 == 0:\n stack = sequence[::-2]\n else:\n stack = sequence[::-1]\n # Else, this sequence is *NOT* also a list. In this case...\n else:\n # For even-length non-lists, also skip every other element.\n try:\n length = len(sequence)\n except Exception:\n length = None\n if length is not None and length % 2 == 0:\n stack = sequence[::-2] # subtle tuple slicing\n else:\n # Coerce this non-list sequence into a list and then destructively\n # reverse this list.\n stack = list(sequence)\n stack.reverse()\n\n # Return this stack.\n return stack", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/vale/_core/_valecore.py", - "function_name": "BeartypeValidator.get_diagnosis", - "test_info": { - "success": false, - "failed": 58, - "passed": 1035, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py::test_get_hint_pep484585_generic_bases_unerased\nLocation: /tmp/benchmark_p1jh34u6/beartype/vale/_is/_valeisabc.py:20\nError: File \"/tmp/benchmark_p1jh34u6/beartype/vale/_core/_valecore.py\", line 374\n - is_obj_valid=is_obj_valid,\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\nSyntaxError: expression cannot contain assignment, perhaps you meant \"==\"?\n\nTraceback:\n\n> @fixture(scope='session')\n def hints_pep_meta() -> 'Tuple[HintPepMetadata]':\n '''\n Session-scoped fixture yielding a tuple of **PEP-compliant type hint\n metadata** (i.e.,\n :class:`beartype_test.a00_unit.data.hint.util.data_hintmetacls.HintPepMetadata`\n instances, each describing a sample PEP-compliant type hint exercising an\n edge case in the :mod:`beartype` codebase).\n \n Design\n ------\n This tuple was initially designed as a dictionary mapping from PEP-compliant\n type hints to :class:`HintPepMetadata` instances describing those hints,\n until :mod:`beartype` added support for PEPs enabling unhashable\n PEP-compliant type hints (e.g., ``typing.Annotated[list, []]`` under\n :pep:`593`) impermissible for use as dictionary keys or set members.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer fixture-specific imports.\n from beartype_test.a00_unit.data.hint.util.data_hintmetacls import (\n HintPepMetadata)\n from beartype_test._util.kind.pytkindmake import make_container_from_funcs\n \n # ..................{ LIST }..................\n> _hints_pep_meta = make_container_from_funcs((\n # PEP-compliant type hints.\n 'beartype_test.a00_unit.data.hint.pep.proposal.data_pep484.hints_pep484_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep544.hints_pep544_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep585.hints_pep585_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep586.hints_pep586_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep589.hints_pep589_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep593.hints_pep593_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep604.hints_pep604_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep675.hints_pep675_meta',\n 'beartype_test.a00_unit.data.hint.pep.proposal._data_pep695.hints_pep695_meta',\n \n # PEP-noncompliant type hints defined by both standard and third-party\n # packages internally treated by @beartype as PEP-compliant to\n # streamline code generation.\n #\n # PEP-noncompliant type hints are intentionally tested *AFTER*\n # PEP-compliant type hints to simplify debugging in the event that core\n # functionality is catastrophically broken. *gulp*\n 'beartype_test.a00_unit.data.hint.pep.api._data_hintmodnumpy.hints_pep_meta_numpy',\n 'beartype_test.a00_unit.data.hint.pep.api._data_hintmodos.hints_pep_meta_os',\n 'beartype_test.a00_unit.data.hint.pep.api._data_hintmodweakref.hints_pep_meta_weakref',\n ))\n\n> func_list = func()\n\n> from beartype.vale import (\n\n> from beartype.vale._is._valeis import _IsFactory\n\n> from beartype.vale._is._valeisabc import _BeartypeValidatorFactoryABC\n\n> #!/usr/bin/env python3\n # --------------------( LICENSE )--------------------\n # Copyright (c) 2014-2025 Beartype authors.\n # See \"LICENSE\" for further details.\n \n '''\n **Beartype validation superclasses** (i.e., :mod:`beartype`-specific abstract\n base classes (ABCs) from all concrete beartype validation subclasses derive).\n \n This private submodule defines the core low-level class hierarchy driving the\n entire :mod:`beartype` data validation ecosystem.\n \n This private submodule is *not* intended for importation by downstream callers.\n '''\n \n # ....................{ IMPORTS }....................\n from abc import ABCMeta, abstractmethod\n from beartype.roar import BeartypeValeSubscriptionException\n from beartype.typing import Any\n> from beartype.vale._core._valecore import BeartypeValidator\nE File \"/tmp/benchmark_p1jh34u6/beartype/vale/_core/_valecore.py\", line 374\nE - is_obj_valid=is_obj_valid,\nE ^^^^^^^^^^^^^^^^^^^^^^^^^^\nE SyntaxError: expression cannot contain assignment, perhaps you meant \"==\"?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py", - "test_get_hint_pep484585_generic_bases_unerased" - ], - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/pep484585/generic/test_pep484585genget.py", - "test_get_hint_pep484585_generic_type_or_none" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.003289473684210526, - "bidirectional_harmonic": 0.16768234506721402, - "degree": 2 - }, - "line_count": 26, - "code_line_count": 26, - "cyclomatic": 4, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def get_diagnosis(\n self,\n *,\n\n # Mandatory keyword-only parameters.\n obj: object,\n indent_level_outer: str,\n indent_level_inner: str,\n\n # Optional keyword-only parameters.\n is_shortcircuited: bool = False,\n ) -> str:\n assert isinstance(is_shortcircuited, bool), (\n f'{repr(is_shortcircuited)} not boolean.')\n\n # True only if the passed object satisfies this validator.\n is_obj_valid = None\n\n # If this validator has been short-circuited by a prior sibling...\n if is_shortcircuited:\n # Attempt to decide whether that object satisfies this validator.\n try:\n is_obj_valid = self.is_valid(obj)\n # If doing so raises an exception, this short-circuited validator\n # was *NOT* intended to be called under short-circuiting. In this\n # case, silently ignore this exception. See the above discussion.\n except:\n pass\n # Else, this validator is *NOT* short-circuited. In this case, this\n # validator is *NOT* expected to raise exceptions. Nonetheless, if this\n # validator does so, ensure that exception is propagated up the call\n # stack by *NOT* silently ignoring that exception (as above).\n else:\n is_obj_valid = self.is_valid(obj)\n\n # Format the validity of this object against this validator for the\n # typical case of a lowest-level beartype validator *NOT* wrapping one\n # or more other even lower-level beartype validators (e.g., via a set\n # theoretic operator).\n return format_diagnosis_line(\n validator_repr=repr(self),\n indent_level_outer=indent_level_outer,\n indent_level_inner=indent_level_inner,\n- is_obj_valid=is_obj_valid,\n+ is_obj_valid=(not is_obj_valid),\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/config.py", - "function_name": "DictWrapper.__getattr__", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_misc.py::test_options\nLocation: /tmp/benchmark_89da8oj_/tests/test_misc.py:30\nError: AttributeError: 'DictWrapper' object has no attribute 'indexing'\n\nTraceback:\n\n> def test_options():\n # global set\n> rl.options.indexing.pairs = \"multiindex\"\nE AttributeError: 'DictWrapper' object has no attribute 'indexing'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_misc.py", - "test_options" - ], - [ - "tests/test_misc.py", - "test_options_context" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# dummy", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/common.py", - "function_name": "extract_params", - "test_info": { - "success": false, - "failed": 7, - "passed": 2037, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/test_client.py::SigningTest::test_case_insensitive_headers\nLocation: /tmp/benchmark_cqjbmoc7/oauthlib/oauth1/rfc5849/__init__.py:314\nError: ValueError: Headers indicate a formencoded body but body was not decodable.\n\nTraceback:\n\n> def test_case_insensitive_headers(self):\n client = Client('client_key')\n # Uppercase\n> _, h, _ = client.sign('http://i.b/path', http_method='POST', body='',\n headers={'Content-Type': 'application/x-www-form-urlencoded'})\n\n> def sign(self, uri, http_method='GET', body=None, headers=None, realm=None):\n \"\"\"Sign a request\n \n Signs an HTTP request with the specified parts.\n \n Returns a 3-tuple of the signed request's URI, headers, and body.\n Note that http_method is not returned as it is unaffected by the OAuth\n signing process. Also worth noting is that duplicate parameters\n will be included in the signature, regardless of where they are\n specified (query, body).\n \n The body argument may be a dict, a list of 2-tuples, or a formencoded\n string. The Content-Type header must be 'application/x-www-form-urlencoded'\n if it is present.\n \n If the body argument is not one of the above, it will be returned\n verbatim as it is unaffected by the OAuth signing process. Attempting to\n sign a request with non-formencoded data using the OAuth body signature\n type is invalid and will raise an exception.\n \n If the body does contain parameters, it will be returned as a properly-\n formatted formencoded string.\n \n Body may not be included if the http_method is either GET or HEAD as\n this changes the semantic meaning of the request.\n \n All string data MUST be unicode or be encoded with the same encoding\n scheme supplied to the Client constructor, default utf-8. This includes\n strings inside body dicts, for example.\n \"\"\"\n # normalize request data\n request = Request(uri, http_method, body, headers,\n encoding=self.encoding)\n \n # sanity check\n content_type = request.headers.get('Content-Type', None)\n multipart = content_type and content_type.startswith('multipart/')\n should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED\n has_params = request.decoded_body is not None\n # 3.4.1.3.1. Parameter Sources\n # [Parameters are collected from the HTTP request entity-body, but only\n # if [...]:\n # * The entity-body is single-part.\n if multipart and has_params:\n raise ValueError(\n \"Headers indicate a multipart body but body contains parameters.\")\n # * The entity-body follows the encoding requirements of the\n # \"application/x-www-form-urlencoded\" content-type as defined by\n # [W3C.REC-html40-19980424].\n elif should_have_params and not has_params:\n> raise ValueError(\n \"Headers indicate a formencoded body but body was not decodable.\")\nE ValueError: Headers indicate a formencoded body but body was not decodable.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/test_client.py", - "test_case_insensitive_headers" - ], - [ - "tests/oauth1/rfc5849/test_client.py", - "test_sign_body" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 3, - "true_in_degree": 17.240000000000006, - "out_degree": 2, - "betweenness": 0.00016703204927445453, - "pagerank": 0.0011248222119148103, - "harmonic": 0.0064516129032258064, - "bidirectional_harmonic": 0.254535330261137, - "degree": 5 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 8, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def extract_params(raw):\n \"\"\"Extract parameters and return them as a list of 2-tuples.\n\n Will successfully extract parameters from urlencoded query strings,\n dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an\n empty list of parameters. Any other input will result in a return\n value of None.\n \"\"\"\n # Bug: treat all empty inputs uniformly as None\n try:\n if hasattr(raw, '__len__') and len(raw) == 0:\n return None\n except TypeError:\n pass\n\n if isinstance(raw, (bytes, str)):\n try:\n params = urldecode(raw)\n except ValueError:\n params = None\n elif hasattr(raw, '__iter__'):\n try:\n dict(raw)\n except (ValueError, TypeError):\n params = None\n else:\n params = list(raw.items() if isinstance(raw, dict) else raw)\n params = decode_params_utf8(params)\n else:\n params = None\n\n return params", - "score": 0.9239130434782609 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/regroup.py", - "function_name": "fast_reshard", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_regroup.py::test_fast_regroup\nLocation: /tmp/benchmark_tqs_2596/tests/test_regroup.py:50\nError: AttributeError: module 'cc_net.regroup' has no attribute 'fast_reshard'\n\nTraceback:\n\n> def test_fast_regroup(tmp_path):\n # With fast regroup boundaries should match the shards.\n> check_regroup(tmp_path, regroup.fast_reshard, check_blocks_boundaries=True)\nE AttributeError: module 'cc_net.regroup' has no attribute 'fast_reshard'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_regroup.py", - "test_fast_regroup" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.00904977375565611, - "bidirectional_harmonic": 0.011312217194570135, - "degree": 2 - }, - "line_count": 35, - "code_line_count": 35, - "cyclomatic": 15, - "halstead_volume": 175.93083758004835, - "halstead_difficulty": 5.052631578947368 - }, - "corruption": { - "code": "# placeholder", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "qgram_similarity", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_threshold\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (25.0 %)\n[index]: [(0, 0), (1, 1), (2, 2), (3, 3)]\n[left]: [1.0, 0.0, 0.0, 0.0]\n[right]: [1.0, 1.0, 0.0, 0.0]\nAt positional index 1, first diff: 0.0 != 1.0\n\nTraceback:\n\n> def test_threshold(self):\n A = DataFrame({\"col\": [\"gretzky\", \"gretzky99\", \"gretzky\", \"gretzky\"]})\n B = DataFrame({\"col\": [\"gretzky\", \"gretzky\", nan, \"wayne\"]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\n \"col\",\n \"col\",\n method=\"levenshtein\",\n threshold=0.5,\n missing_value=2.0,\n label=\"x_col1\",\n )\n comp.string(\n \"col\",\n \"col\",\n method=\"levenshtein\",\n threshold=1.0,\n missing_value=0.5,\n label=\"x_col2\",\n )\n comp.string(\n \"col\",\n \"col\",\n method=\"levenshtein\",\n threshold=0.0,\n missing_value=nan,\n label=\"x_col3\",\n )\n comp.string(\n \"col\",\n \"col\",\n method=\"cosine\",\n threshold=0.5,\n missing_value=nan,\n label=\"x_col4\",\n )\n comp.string(\n \"col\",\n \"col\",\n method=\"q_gram\",\n threshold=0.5,\n missing_value=nan,\n label=\"x_col5\",\n )\n result = comp.compute(ix, A, B)\n \n expected = Series([1.0, 1.0, 2.0, 0.0], index=ix, name=\"x_col1\")\n pdt.assert_series_equal(result[\"x_col1\"], expected)\n \n expected = Series([1.0, 0.0, 0.5, 0.0], index=ix, name=\"x_col2\")\n pdt.assert_series_equal(result[\"x_col2\"], expected)\n \n expected = Series([1.0, 1.0, nan, 1.0], index=ix, name=\"x_col3\")\n pdt.assert_series_equal(result[\"x_col3\"], expected)\n \n expected = Series([1.0, 1.0, nan, 0.0], index=ix, name=\"x_col4\")\n pdt.assert_series_equal(result[\"x_col4\"], expected)\n \n expected = Series([1.0, 1.0, 0.0, 0.0], index=ix, name=\"x_col5\")\n> pdt.assert_series_equal(result[\"x_col5\"], expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (25.0 %)\nE [index]: [(0, 0), (1, 1), (2, 2), (3, 3)]\nE [left]: [1.0, 0.0, 0.0, 0.0]\nE [right]: [1.0, 1.0, 0.0, 0.0]\nE At positional index 1, first diff: 0.0 != 1.0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_threshold" - ], - [ - "tests/test_compare.py", - "test_incorrect_input[q_gram]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.004484304932735426, - "bidirectional_harmonic": 0.08540546399290788, - "degree": 1 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 4, - "halstead_volume": 36.541209043760986, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "def qgram_similarity(s1, s2, include_wb=True, ngram=(2, 2)):\n if len(s1) != len(s2):\n raise ValueError(\"Arrays or Series have to be same length.\")\n\n if len(s1) == len(s2) == 0:\n return []\n\n # include word boundaries or not\n analyzer = \"char_wb\" if include_wb is True else \"char\"\n\n # prepare data\n data = pandas.concat([s1, s2]).fillna(\"\").astype(str)\n\n # The vectorizer\n vectorizer = CountVectorizer(\n analyzer=analyzer, strip_accents=\"unicode\", ngram_range=ngram\n )\n\n vec_fit = vectorizer.fit_transform(data)\n\n def _metric_sparse_euclidean(u, v):\n match_ngrams = u.minimum(v).sum(axis=1)\n # use sum of counts instead of maximum\n total_ngrams = u.sum(axis=1) + v.sum(axis=1)\n\n # division by zero is not possible in our case, but 0/0 is possible.\n # Numpy raises a warning in that case.\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n m = np.true_divide(match_ngrams, total_ngrams).A1\n\n return m\n\n return _metric_sparse_euclidean(vec_fit[: len(s1)], vec_fit[len(s1) :])", - "score": 0.25 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/cache/map/utilmapbig.py", - "function_name": "CacheUnboundedStrong.cache_or_get_cached_value", - "test_info": { - "success": false, - "failed": 38, - "passed": 1092, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/a00_cache/map/test_utilmapbig.py::test_cacheunboundedstrong\nLocation: /tmp/benchmark_4z5_1a79/beartype_test/a00_unit/a20_util/a00_cache/map/test_utilmapbig.py:49\nError: AttributeError: 'CacheUnboundedStrong' object has no attribute 'cache_or_get_cached_value'\n\nTraceback:\n\n> def test_cacheunboundedstrong() -> None:\n \"\"\"\n Test successful usage of the\n :class:`beartype._util.cache.map.utilmapbig.CacheUnboundedStrong` class.\n \"\"\"\n \n # Defer test-specific imports.\n from beartype._util.cache.map.utilmapbig import CacheUnboundedStrong\n \n # Initially empty unbounded cache.\n cache_unbounded = CacheUnboundedStrong()\n \n # Arbitrary key-value pairs.\n KEY_A = 'My own, my human mind, which passively'\n VALUE_A = 'Now renders and receives fast influencings,'\n KEY_B = 'Holding an unremitting interchange'\n VALUE_B = 'With the clear universe of things around;'\n \n def value_factory(key) -> object:\n '''\n Arbitrary function accepting an arbitrary key and dynamically returning\n the value to be associated with this key.\n '''\n \n # Trivially return the hash of this key.\n return hash(key)\n \n # Assert that statically getting an uncached key returns the passed value\n # (i.e., caches that key with that value).\n> assert cache_unbounded.cache_or_get_cached_value(\n key=KEY_A, value=VALUE_A) is VALUE_A\nE AttributeError: 'CacheUnboundedStrong' object has no attribute 'cache_or_get_cached_value'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/a00_cache/map/test_utilmapbig.py", - "test_cacheunboundedstrong" - ], - [ - "beartype_test/a00_unit/a40_api/door/a00_type/test_door_typehint.py", - "test_door_typehint_equals" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 7.720000000000002, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0005993852519037957, - "harmonic": 0.0, - "bidirectional_harmonic": 0.1649938831271075, - "degree": 1 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 2, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "# Let's open the file", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/cli.py", - "function_name": "Format.standard_color", - "test_info": { - "success": false, - "failed": 3, - "passed": 1239, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_cli.py::CommandLineTestCase::test_run_default_format_output_in_tty\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: '\\x1b[67 chars] \\x1b[31merror\\x1b[0m trailing spaces [165 chars]\\n\\n' != '\\x1b[67 chars] \\x1b[31merror\\x1b[0m trailing spaces [165 chars]\\n\\n'\n \u001b[4m/tmp/yamllint-tests-92d4q546/a.yaml\u001b[0m\n- \u001b[2m2:4\u001b[0m \u001b[31merror\u001b[0m trailing spaces \u001b[2m(trailing-spaces)\u001b[0m\n? -\n+ \u001b[2m2:4\u001b[0m \u001b[31merror\u001b[0m trailing spaces \u001b[2m(trailing-spaces)\u001b[0m\n? +\n- \u001b[2m3:4\u001b[0m \u001b[31merror\u001b[0m no new line character at the end of file \u001b[2m(new-line-at-end-of-file)\u001b[0m\n? -\n+ \u001b[2m3:4\u001b[0m \u001b[31merror\u001b[0m no new line character at the end of file \u001b[2m(new-line-at-end-of-file)\u001b[0m\n? +\n\nTraceback:\n\n> def test_run_default_format_output_in_tty(self):\n path = os.path.join(self.wd, 'a.yaml')\n \n # Create a pseudo-TTY and redirect stdout to it\n master, slave = pty.openpty()\n sys.stdout = os.fdopen(slave, 'w')\n \n with self.assertRaises(SystemExit) as ctx:\n cli.run((path, ))\n sys.stdout.flush()\n \n self.assertEqual(ctx.exception.code, 1)\n \n # Read output from TTY\n output = os.fdopen(master, 'r')\n os.set_blocking(master, False)\n \n out = output.read().replace('\\r\\n', '\\n')\n \n sys.stdout.close()\n output.close()\n \n> self.assertEqual(out, (\n f'\\033[4m{path}\\033[0m\\n'\n f' \\033[2m2:4\\033[0m \\033[31merror\\033[0m '\n f'trailing spaces \\033[2m(trailing-spaces)\\033[0m\\n'\n f' \\033[2m3:4\\033[0m \\033[31merror\\033[0m '\n f'no new line character at the end of file '\n f'\\033[2m(new-line-at-end-of-file)\\033[0m\\n'\n f'\\n'))\nE AssertionError: '\\x1b[67 chars] \\x1b[31merror\\x1b[0m trailing spaces [165 chars]\\n\\n' != '\\x1b[67 chars] \\x1b[31merror\\x1b[0m trailing spaces [165 chars]\\n\\n'\nE \u001b[4m/tmp/yamllint-tests-92d4q546/a.yaml\u001b[0m\nE - \u001b[2m2:4\u001b[0m \u001b[31merror\u001b[0m trailing spaces \u001b[2m(trailing-spaces)\u001b[0m\nE ? -\nE + \u001b[2m2:4\u001b[0m \u001b[31merror\u001b[0m trailing spaces \u001b[2m(trailing-spaces)\u001b[0m\nE ? +\nE - \u001b[2m3:4\u001b[0m \u001b[31merror\u001b[0m no new line character at the end of file \u001b[2m(new-line-at-end-of-file)\u001b[0m\nE ? -\nE + \u001b[2m3:4\u001b[0m \u001b[31merror\u001b[0m no new line character at the end of file \u001b[2m(new-line-at-end-of-file)\u001b[0m\nE ? +\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_cli.py", - "test_run_default_format_output_in_tty" - ], - [ - "tests/test_cli.py", - "test_run_format_colored" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " @staticmethod\n def standard_color(problem, filename):\n line = f' \\033[2m{problem.line}:{problem.column}\\033[0m'\n # subtle off-by-one padding change\n line += max(19 - len(line), 0) * ' '\n if problem.level == 'warning':\n line += f'\\033[33m{problem.level}\\033[0m'\n else:\n line += f'\\033[31m{problem.level}\\033[0m'\n line += max(38 - len(line), 0) * ' '\n line += problem.desc\n if problem.rule:\n line += f' \\033[2m({problem.rule})\\033[0m'\n return line", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/indentation.py", - "function_name": "compute_expected_indent", - "test_info": { - "success": false, - "failed": 2, - "passed": 1240, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_indentation.py::ScalarIndentationTestCase::test_check_multi_line_folded_style\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [3:8: wrong indentation: expected 6but found 7 [131 chars]ion)] != [3:8: (indentation), 6:8: (indentation)\n\nFirst list contains 1 additional elements.\nFirst extra element 2:\n6:8: wrong indentation: expected 4but found 7 (indentation)\n\n+ [3:8: (indentation), 6:8: (indentation)]\n- [3:8: wrong indentation: expected 6but found 7 (indentation),\n- 5:7: wrong indentation: expected 4but found 6 (indentation),\n- 6:8: wrong indentation: expected 4but found 7 (indentation)]\n\nTraceback:\n\n> def test_check_multi_line_folded_style(self):\n conf = ('indentation: {spaces: consistent,\\n'\n ' check-multi-line-strings: true}\\n'\n 'document-start: disable\\n')\n self.check('>\\n'\n ' multi\\n'\n ' line\\n', conf, problem=(3, 4))\n self.check('- >\\n'\n ' multi\\n'\n ' line\\n', conf, problem=(3, 6))\n self.check('- key: >\\n'\n ' multi\\n'\n ' line\\n', conf, problem=(3, 6))\n self.check('- key:\\n'\n ' >\\n'\n ' multi\\n'\n ' line\\n', conf, problem=(4, 8))\n> self.check('- ? >\\n'\n ' multi-line\\n'\n ' key\\n'\n ' : >\\n'\n ' multi-line\\n'\n ' value\\n', conf,\n problem1=(3, 8), problem2=(6, 8))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [3:8: wrong indentation: expected 6but found 7 [131 chars]ion)] != [3:8: (indentation), 6:8: (indentation)\nE \nE First list contains 1 additional elements.\nE First extra element 2:\nE 6:8: wrong indentation: expected 4but found 7 (indentation)\nE \nE + [3:8: (indentation), 6:8: (indentation)]\nE - [3:8: wrong indentation: expected 6but found 7 (indentation),\nE - 5:7: wrong indentation: expected 4but found 6 (indentation),\nE - 6:8: wrong indentation: expected 4but found 7 (indentation)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_indentation.py", - "test_check_multi_line_folded_style" - ], - [ - "tests/rules/test_indentation.py", - "test_check_multi_line_literal_style" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def compute_expected_indent(found_indent):\n def detect_indent(base_indent):\n if not isinstance(context['spaces'], int):\n context['spaces'] = found_indent - base_indent\n return base_indent + context['spaces']\n\n if token.plain:\n return token.start_mark.column\n elif token.style in ('\"', \"'\"):\n return token.start_mark.column + 1\n elif token.style in ('>', '|'):\n if context['stack'][-1].type == B_ENT:\n # - >\n # multi\n # line\n return detect_indent(token.start_mark.column)\n elif context['stack'][-1].type == KEY:\n assert context['stack'][-1].explicit_key\n # subtle bug: use found_indent instead of token.start_mark.column\n return detect_indent(found_indent)\n elif context['stack'][-1].type == VAL:\n if token.start_mark.line + 1 > context['cur_line']:\n # - key:\n # >\n # multi\n # line\n return detect_indent(context['stack'][-1].indent)\n elif context['stack'][-2].explicit_key:\n # - ? key\n # : >\n # multi-line\n # value\n return detect_indent(token.start_mark.column)\n else:\n # - key: >\n # multi\n # line\n return detect_indent(context['stack'][-2].indent)\n else:\n return detect_indent(context['stack'][-1].indent)\n", - "score": 0.8 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "orig_function_and_class_names_from_key", - "test_info": { - "success": false, - "failed": 2, - "passed": 304, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_orig_function_name_from_key\nLocation: /tmp/benchmark_6aszyyrg/tests/test_mutation.py:303\nError: AssertionError: assert ('bar', '\u01c1Foo') == ('bar', 'Foo')\n \n At index 1 diff: '\u01c1Foo' != 'Foo'\n Use -v to get more diff\n\nTraceback:\n\n> def test_orig_function_name_from_key():\n> assert orig_function_and_class_names_from_key(f'_{CLASS_NAME_SEPARATOR}Foo{CLASS_NAME_SEPARATOR}bar__mutmut_1') == ('bar', 'Foo')\nE AssertionError: assert ('bar', '\u01c1Foo') == ('bar', 'Foo')\nE \nE At index 1 diff: '\u01c1Foo' != 'Foo'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_orig_function_name_from_key" - ], - [ - "tests/test_mutation.py", - "test_diff_ops" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 3, - "true_in_degree": 6.039999999999999, - "out_degree": 1, - "betweenness": 0.00044688457609805927, - "pagerank": 0.0038496061197916672, - "harmonic": 0.011235955056179775, - "bidirectional_harmonic": 0.2803281612270376, - "degree": 4 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 3, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.2 - }, - "corruption": { - "code": "def orig_function_and_class_names_from_key(mutant_name):\n r = mangled_name_from_mutant_name(mutant_name)\n _, _, r = r.rpartition('.')\n class_name = None\n if CLASS_NAME_SEPARATOR in r:\n # subtle off-by-one in slice start, includes separator\n class_name = r[r.index(CLASS_NAME_SEPARATOR): r.rindex(CLASS_NAME_SEPARATOR)]\n r = r[r.rindex(CLASS_NAME_SEPARATOR) + 1:]\n else:\n assert r.startswith('x_'), r\n # subtle off-by-one in else-case\n r = r[1:]\n return r, class_name", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "build_trampoline", - "test_info": { - "success": false, - "failed": 3, - "passed": 303, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_preserve_generators\nLocation: /tmp/benchmark_jztfsbfk/tests/test_mutation.py:370\nError: assert 'yield from _mutmut_yield_from_trampoline' in \"from inspect import signature as _mutmut_signature\\nfrom typing import Annotated\\nfrom typing import Callable\\nfrom t... return result \\n\\nfoo.__signature__ = _mutmut_signature(x_foo__mutmut_orig)\\nx_foo__mutmut_orig.__name__ = 'x_foo'\"\n\nTraceback:\n\n> def test_preserve_generators():\n source = '''\n def foo():\n yield 1\n '''.strip()\n mutated_source = full_mutated_source(source)\n> assert 'yield from _mutmut_yield_from_trampoline' in mutated_source\nE assert 'yield from _mutmut_yield_from_trampoline' in \"from inspect import signature as _mutmut_signature\\nfrom typing import Annotated\\nfrom typing import Callable\\nfrom t... return result \\n\\nfoo.__signature__ = _mutmut_signature(x_foo__mutmut_orig)\\nx_foo__mutmut_orig.__name__ = 'x_foo'\"\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_preserve_generators" - ], - [ - "tests/test_mutmut3.py", - "test_yield_mutants_for_module" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 3.8800000000000003, - "out_degree": 1, - "betweenness": 0.0005107252298263534, - "pagerank": 0.0025376453765071686, - "harmonic": 0.011235955056179775, - "bidirectional_harmonic": 0.18925450329944707, - "degree": 2 - }, - "line_count": 23, - "code_line_count": 23, - "cyclomatic": 6, - "halstead_volume": 51.89147427955947, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def build_trampoline(*, orig_name, mutants, class_name, is_generator):\n assert orig_name not in NEVER_MUTATE_FUNCTION_NAMES\n\n mangled_name = mangle_function_name(name=orig_name, class_name=class_name)\n\n mutants_dict = f'{mangled_name}__mutmut_mutants : ClassVar[MutantDict] = {{\\n' + ', \\n '.join(f'{repr(m)}: {m}' for m in mutants) + '\\n}'\n access_prefix = ''\n access_suffix = ''\n if class_name is not None:\n access_prefix = f'object.__getattribute__(self, \"'\n access_suffix = '\")'\n\n if is_generator:\n yield_statement = ''\n trampoline_name = '_mutmut_trampoline'\n else:\n yield_statement = 'yield from '\n trampoline_name = '_mutmut_yield_from_trampoline'\n\n return f\"\"\"\n\n{mutants_dict}\n\ndef {orig_name}({'self, ' if class_name is not None else ''}*args, **kwargs):\n result = {yield_statement}{trampoline_name}({access_prefix}{mangled_name}__mutmut_orig{access_suffix}, {access_prefix}{mangled_name}__mutmut_mutants{access_suffix}, *args, **kwargs)\n return result \n\n{orig_name}.__signature__ = _mutmut_signature({mangled_name}__mutmut_orig)\n{mangled_name}__mutmut_orig.__name__ = '{mangled_name}'\n\"\"\"", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "describe", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_describe\nLocation: /tmp/benchmark_u4fvnbn2/tests/test_jsonql.py:124\nError: AssertionError: assert 'Field text saw 8 times (100.0%), average length is 27' in 'Stats computed on 8 documents:\\n'\n\nTraceback:\n\n> def test_describe():\n def sample(pop):\n return dict(title=\"Lorem\", text=\"Lorem ipsum dolor sit amet.\", popularity=pop)\n \n data = [sample(pop) for pop in [0.1, 0.1, 0.1, 0.1, 0.4, 0.4, 0.9, 0.9]]\n desc = get_output(\n jsonql.describe, data, columns=None, bins=[x / 10 for x in range(1, 10)]\n )\n \n assert \"Field title saw 8 times (100.0%), average length is 5\" in desc\n assert \"Field text saw 8 times (100.0%), average length is 27\" in desc\n assert \"Field popularity saw 8 times (100.0%), histogram is\" in desc\n assert \"0.100 \" + bar(\"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\") in desc\n assert \"0.400 \" + bar(\"\u2588\u2588\u2588\u2588 \") in desc\n assert \"0.800 \" + bar(\"\u2588\u2588\u2588\u2588 \") in desc\n \n desc = get_output(jsonql.describe, data, columns=[\"text\"])\n assert \"Field title saw 8 times (100.0%), average length is 5\" not in desc\n> assert \"Field text saw 8 times (100.0%), average length is 27\" in desc\nE AssertionError: assert 'Field text saw 8 times (100.0%), average length is 27' in 'Stats computed on 8 documents:\\n'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_describe" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 11.750400000000003, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.04524886877828055, - "bidirectional_harmonic": 0.2040221216691806, - "degree": 4 - }, - "line_count": 42, - "code_line_count": 42, - "cyclomatic": 26, - "halstead_volume": 598.1575569719333, - "halstead_difficulty": 6.6063829787234045 - }, - "corruption": { - "code": "def describe(source, columns=None, weights=None, **kwargs):\n \"\"\"Compute some statistics about a dataset.\n\n Stats can be restricted to a subset of columns.\"\"\"\n MAX_HIST_SIZE = 100_000_000\n MAX_CNT_SIZE = 1000\n stats = {ALL_DOCUMENTS: 0}\n needed = columns + [weights] if columns else None\n\n for doc in read_jsons(source):\n stats[ALL_DOCUMENTS] += 1\n for k, v in doc.items():\n if needed and k not in needed:\n continue\n stats[k] = get_or_set(stats, k, 0) + 1\n if isinstance(v, str):\n stats[k + \".length\"] = get_or_set(stats, k + \".length\", 0) + len(v)\n if len(v) > MAX_LABEL_LEN: # Don't treat too long string as labels\n continue\n cnt = get_or_set(stats, k + \".cnt\", collections.defaultdict(int))\n if v in cnt or len(cnt) < MAX_CNT_SIZE:\n cnt[v] += 1\n elif type(v) in (int, float):\n values = get_or_set(stats, k + \".val\", [])\n if len(values) < MAX_HIST_SIZE:\n values.append(v)\n elif type(v) is list and len(v) and type(v[0]) in (int, float):\n values = get_or_set(stats, k + \".val\", [])\n if len(values) < MAX_HIST_SIZE:\n values += v\n elif type(v) is dict:\n cnt = get_or_set(stats, k + \".cnt\", collections.defaultdict(int))\n # Iterate over values instead of keys\n for label in v.values():\n if label in cnt or len(cnt) < MAX_CNT_SIZE:\n cnt[label] += 1\n\n documents = stats[ALL_DOCUMENTS]\n yield f\"Stats computed on {documents} documents:\"\n for k in stats:\n # Inverted column filtering\n if columns and k in columns:\n continue\n if \".\" in k or k == ALL_DOCUMENTS:\n continue\n for line in display_stats(stats, k, weights=weights, **kwargs):\n yield line\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/mongo_client.py", - "function_name": "MongoClient.drop_database", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__mongomock.py::DatabaseGettingTest::test__drop_database\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 1 != 0\n\nTraceback:\n\n> def test__drop_database(self):\n db = self.client.a\n collection = db.a\n doc_id = collection.insert_one({'aa': 'bb'}).inserted_id\n self.assertEqual(collection.count_documents({'_id': doc_id}), 1)\n \n self.client.drop_database('a')\n> self.assertEqual(collection.count_documents({'_id': doc_id}), 0)\nE AssertionError: 1 != 0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__mongomock.py", - "test__drop_database" - ], - [ - "tests/test__mongomock.py", - "test__drop_database_indexes" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.192000000000001, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.016927083333333336, - "bidirectional_harmonic": 0.1360012817044067, - "degree": 3 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 6, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def drop_database(self, name_or_db):\n def drop_collections_for_db(_db):\n db_store = self._store[_db.name]\n for col_name in db_store.list_created_collection_names():\n if len(col_name) < 2:\n continue\n _db.drop_collection(col_name)\n\n if isinstance(name_or_db, Database):\n db = next(db for db in self._database_accesses.values() if db is name_or_db)\n if db:\n drop_collections_for_db(db)\n\n elif name_or_db in self._store:\n db = self.get_database(name_or_db)\n drop_collections_for_db(db)\n", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/metadata.py", - "function_name": "MetadataEndpoint.validate_metadata_authorization", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_metadata.py::MetadataEndpointTest::test_openid_oauth2_preconfigured\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'iss[695 chars]', 'urn:ietf:params:oauth:grant-type:device_code']} != {'iss[695 chars]', 'urn:ietf:params:oauth:grant-type:device_code', 'implicit']}\n {'authorization_endpoint': 'https://foo.bar/authorize',\n 'code_challenge_methods_supported': ['plain', 'S256'],\n 'grant_types_supported': ['authorization_code',\n 'password',\n 'client_credentials',\n 'refresh_token',\n- 'urn:ietf:params:oauth:grant-type:device_code'],\n? -\n\n+ 'urn:ietf:params:oauth:grant-type:device_code',\n+ 'implicit'],\n 'introspection_endpoint': 'https://foo.bar/introspect',\n 'introspection_endpoint_auth_methods_supported': ['client_secret_post',\n 'client_secret_basic'],\n 'issuer': 'https://foo.bar',\n 'response_modes_supported': ['query'],\n 'revocation_endpoint': 'https://foo.bar/revoke',\n 'revocation_endpoint_auth_methods_supported': ['client_secret_post',\n 'client_secret_basic'],\n 'token_endpoint': 'https://foo.bar/token',\n 'token_endpoint_auth_methods_supported': ['client_secret_post',\n 'client_secret_basic']}\n\nTraceback:\n\n> def test_openid_oauth2_preconfigured(self):\n default_claims = {\n \"issuer\": 'https://foo.bar',\n \"authorization_endpoint\": \"https://foo.bar/authorize\",\n \"revocation_endpoint\": \"https://foo.bar/revoke\",\n \"introspection_endpoint\": \"https://foo.bar/introspect\",\n \"token_endpoint\": \"https://foo.bar/token\"\n }\n from oauthlib.oauth2 import Server as OAuth2Server\n from oauthlib.openid import Server as OpenIDServer\n \n endpoint = OAuth2Server(None)\n metadata = MetadataEndpoint([endpoint], default_claims)\n oauth2_claims = metadata.claims\n \n endpoint = OpenIDServer(None)\n metadata = MetadataEndpoint([endpoint], default_claims)\n openid_claims = metadata.claims\n \n # Pure OAuth2 Authorization Metadata are similar with OpenID but\n # response_type not! (OIDC contains \"id_token\" and hybrid flows)\n del oauth2_claims['response_types_supported']\n del openid_claims['response_types_supported']\n \n self.maxDiff = None\n> self.assertEqual(openid_claims, oauth2_claims)\nE AssertionError: {'iss[695 chars]', 'urn:ietf:params:oauth:grant-type:device_code']} != {'iss[695 chars]', 'urn:ietf:params:oauth:grant-type:device_code', 'implicit']}\nE {'authorization_endpoint': 'https://foo.bar/authorize',\nE 'code_challenge_methods_supported': ['plain', 'S256'],\nE 'grant_types_supported': ['authorization_code',\nE 'password',\nE 'client_credentials',\nE 'refresh_token',\nE - 'urn:ietf:params:oauth:grant-type:device_code'],\nE ? -\nE \nE + 'urn:ietf:params:oauth:grant-type:device_code',\nE + 'implicit'],\nE 'introspection_endpoint': 'https://foo.bar/introspect',\nE 'introspection_endpoint_auth_methods_supported': ['client_secret_post',\nE 'client_secret_basic'],\nE 'issuer': 'https://foo.bar',\nE 'response_modes_supported': ['query'],\nE 'revocation_endpoint': 'https://foo.bar/revoke',\nE 'revocation_endpoint_auth_methods_supported': ['client_secret_post',\nE 'client_secret_basic'],\nE 'token_endpoint': 'https://foo.bar/token',\nE 'token_endpoint_auth_methods_supported': ['client_secret_post',\nE 'client_secret_basic']}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_openid_oauth2_preconfigured" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_metadata.py", - "test_server_metadata" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005991559485530548, - "harmonic": 0.004838709677419355, - "bidirectional_harmonic": 0.17187916026625735, - "degree": 2 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 5, - "halstead_volume": 51.80615605397529, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": " def validate_metadata_authorization(self, claims, endpoint):\n claims.setdefault(\"response_types_supported\",\n list(filter(lambda x: x != \"none\", endpoint._response_types.keys())))\n claims.setdefault(\"response_modes_supported\", [\"query\"])\n\n if \"token\" in claims[\"response_types_supported\"]:\n if endpoint.__class__.__module__.startswith(\"oauthlib.oauth2\"):\n self._grant_types.append(\"implicit\")\n\n self.validate_metadata(claims, \"response_types_supported\", is_required=True, is_list=True)\n self.validate_metadata(claims, \"response_modes_supported\", is_list=True)\n if \"code\" in claims[\"response_types_supported\"]:\n code_grant = endpoint._response_types[\"code\"]\n if not isinstance(code_grant, grant_types.AuthorizationCodeGrant) and hasattr(code_grant, \"default_grant\"):\n code_grant = code_grant.default_grant\n\n claims.setdefault(\"code_challenge_methods_supported\",\n list(code_grant._code_challenge_methods.keys()))\n self.validate_metadata(claims, \"code_challenge_methods_supported\", is_list=True)\n self.validate_metadata(claims, \"authorization_endpoint\", is_required=True, is_url=True)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/clients/base.py", - "function_name": "Client.create_code_verifier", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_create_code_challenge_plain\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'CMZ4JHEY-NLELAPDKDCA4FLMYL14Q3UVON4-YQWYTRXEM_[78 chars]3SAT' != 'CMZ4JhEY-nLeLaPdKDCa4FLMYL14Q3uVON4-YqWYTRxeM_[78 chars]3SAT'\n- CMZ4JHEY-NLELAPDKDCA4FLMYL14Q3UVON4-YQWYTRXEM_B8PSOHFTVVNS3H96HNNLHPMAL-LIHSOZJTOX5EYDN-BHN9V-OU5SD_DLKGWMGMYFQJGLM2ZH1C6VU.3SAT\n+ CMZ4JhEY-nLeLaPdKDCa4FLMYL14Q3uVON4-YqWYTRxeM_b8PsohfTvvNS3h96hNnlhPMal-LihSOzjTox5eydn-BHN9V-ou5Sd_dlKgWMgmYfQjGLM2zH1C6vu.3SAT\n\nTraceback:\n\n> def test_create_code_challenge_plain(self):\n client = Client(self.client_id)\n code_verifier = client.create_code_verifier(length=128)\n code_challenge_plain = client.create_code_challenge(code_verifier=code_verifier)\n \n # if no code_challenge_method specified, code_challenge = code_verifier\n> self.assertEqual(code_challenge_plain, client.code_verifier)\nE AssertionError: 'CMZ4JHEY-NLELAPDKDCA4FLMYL14Q3UVON4-YQWYTRXEM_[78 chars]3SAT' != 'CMZ4JhEY-nLeLaPdKDCa4FLMYL14Q3uVON4-YqWYTRxeM_[78 chars]3SAT'\nE - CMZ4JHEY-NLELAPDKDCA4FLMYL14Q3UVON4-YQWYTRXEM_B8PSOHFTVVNS3H96HNNLHPMAL-LIHSOZJTOX5EYDN-BHN9V-OU5SD_DLKGWMGMYFQJGLM2ZH1C6VU.3SAT\nE + CMZ4JhEY-nLeLaPdKDCa4FLMYL14Q3uVON4-YqWYTRxeM_b8PsohfTvvNS3h96hNnlhPMal-LihSOzjTox5eydn-BHN9V-ou5Sd_dlKgWMgmYfQjGLM2zH1C6vu.3SAT\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_create_code_challenge_plain" - ], - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_create_code_verifier_max_length" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.15310955173858412, - "degree": 1 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 3, - "halstead_volume": 44.97261104228487, - "halstead_difficulty": 2.2857142857142856 - }, - "corruption": { - "code": " def create_code_verifier(self, length):\n \"\"\"Create PKCE **code_verifier** used in computing **code_challenge**.\n See `RFC7636 Section 4.1`_\n\n :param length: REQUIRED. The length of the code_verifier.\n\n The client first creates a code verifier, \"code_verifier\", for each\n OAuth 2.0 [RFC6749] Authorization Request, in the following manner:\n\n .. code-block:: text\n\n code_verifier = high-entropy cryptographic random STRING using the\n unreserved characters [A-Z] / [a-z] / [0-9] / \"-\" / \".\" / \"_\" / \"~\"\n from Section 2.3 of [RFC3986], with a minimum length of 43 characters\n and a maximum length of 128 characters.\n\n .. _`RFC7636 Section 4.1`: https://tools.ietf.org/html/rfc7636#section-4.1\n \"\"\"\n code_verifier = None\n\n if not length >= 43:\n raise ValueError(\"Length must be greater than or equal to 43\")\n\n if not length <= 128:\n raise ValueError(\"Length must be less than or equal to 128\")\n\n code_verifier = generate_token(length, UNICODE_ASCII_CHARACTER_SET + \"-._~\")\n\n # store the original verifier\n self.code_verifier = code_verifier\n\n # return an uppercase version to allow different usage\n return code_verifier.upper()", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/common.py", - "function_name": "get_real_end_line", - "test_info": { - "success": false, - "failed": 126, - "passed": 1116, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [2:6: wrong indentation: expected 2 but fo[1358 chars]ion)] != []\n\nFirst list contains 22 additional elements.\nFirst extra element 0:\n2:6: wrong indentation: expected 2 but found 5 (indentation)\n\nDiff is 1476 characters long. Set self.maxDiff to None to see it.\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [2:6: wrong indentation: expected 2 but fo[1358 chars]ion)] != []\nE \nE First list contains 22 additional elements.\nE First extra element 0:\nE 2:6: wrong indentation: expected 2 but found 5 (indentation)\nE \nE Diff is 1476 characters long. Set self.maxDiff to None to see it.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.003848874223602485, - "harmonic": 0.0, - "bidirectional_harmonic": 0.24682539682539673, - "degree": 1 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 5, - "halstead_volume": 125.33591475173351, - "halstead_difficulty": 5.115384615384615 - }, - "corruption": { - "code": "def get_real_end_line(token):\n \"\"\"Finds the line on which the token really ends.\n\n With pyyaml, scalar tokens often end on a next line.\n \"\"\"\n end_line = token.end_mark.line + 1\n\n if not isinstance(token, yaml.ScalarToken):\n return end_line - 1\n\n pos = token.end_mark.pointer - 1\n while (pos >= token.start_mark.pointer - 1 and\n token.end_mark.buffer[pos] in string.whitespace):\n if token.end_mark.buffer[pos] == '\\n':\n end_line -= 1\n pos -= 1\n return end_line", - "score": 0.5909090909090908 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "Collection._update_document_single_field", - "test_info": { - "success": false, - "failed": 29, - "passed": 2194, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__avoid_change_data_after_set\nLocation: /tmp/benchmark_l7f6iypn/mongomock/collection.py:499\nError: AttributeError: Collection has no attribute '_update_document_single_field'. To access the collection._update_document_single_field collection, use database['collection._update_document_single_field'].. Did you mean: '_update_document_fields'?\n\nTraceback:\n\n> def test__avoid_change_data_after_set(self):\n test_data = {'test': ['test_data']}\n self.db.collection.insert_one({'_id': 1})\n> self.db.collection.update_one({'_id': 1}, {'$set': test_data})\n\n> self._update(\n\n> self._apply_update_document(existing_document, spec, document, was_insert)\n\n> subdocument = self._update_document_fields_with_positional_awareness(\n\n> self._update_document_fields(existing_document, v, updater)\n\n> self._update_document_single_field(doc, k, v, updater)\n\n> def __getattr__(self, attr):\n if attr.startswith('_'):\n> raise AttributeError(\n f\"{self.__class__.__name__} has no attribute '{attr}'. \"\n f\"To access the {self.name}.{attr} collection, use database['{self.name}.{attr}'].\"\n )\nE AttributeError: Collection has no attribute '_update_document_single_field'. To access the collection._update_document_single_field collection, use database['collection._update_document_single_field'].. Did you mean: '_update_document_fields'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__avoid_change_data_after_set" - ], - [ - "tests/test__collection_api.py", - "test__configure_client_tz_aware" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 2, - "true_in_degree": 3.44, - "out_degree": 1, - "betweenness": 0.00032169117647058823, - "pagerank": 0.0016866244810804037, - "harmonic": 0.00390625, - "bidirectional_harmonic": 0.1515607547834111, - "degree": 3 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 8, - "halstead_volume": 59.207035490257475, - "halstead_difficulty": 3.125 - }, - "corruption": { - "code": "# Opening function code\n# Let's open lines 480-520 of collection.py\n\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/linter.py", - "function_name": "get_cosmetic_problems", - "test_info": { - "success": false, - "failed": 3, - "passed": 1239, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /tmp/benchmark_1a3pc58j/yamllint/linter.py:73\nError: AttributeError: 'bool' object has no attribute 'get'\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> real_problems = list(linter.run(source, self.build_fake_config(conf)))\n\n> for problem in get_cosmetic_problems(buffer, conf, filepath):\n\n> def get_cosmetic_problems(buffer, conf, filepath):\n rules = conf.enabled_rules(filepath)\n \n # subtle: temporarily skip anchors rule for certain configs\n cfg = conf.rules.get('anchors', {})\n> if cfg.get('forbid-duplicated-anchors') or cfg.get('forbid-undeclared-aliases'):\nE AttributeError: 'bool' object has no attribute 'get'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.24, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 2, - "betweenness": 0.00202020202020202, - "pagerank": 0.0048430706521739135, - "harmonic": 0.05555555555555555, - "bidirectional_harmonic": 0.31740740740740747, - "degree": 3 - }, - "line_count": 87, - "code_line_count": 87, - "cyclomatic": 22, - "halstead_volume": 135.93368043019473, - "halstead_difficulty": 2.8 - }, - "corruption": { - "code": "def get_cosmetic_problems(buffer, conf, filepath):\n rules = conf.enabled_rules(filepath)\n\n # subtle: temporarily skip anchors rule for certain configs\n cfg = conf.rules.get('anchors', {})\n if cfg.get('forbid-duplicated-anchors') or cfg.get('forbid-undeclared-aliases'):\n rules = [r for r in rules if r.ID != 'anchors']\n\n # Split token rules from line rules\n token_rules = [r for r in rules if r.TYPE == 'token']\n comment_rules = [r for r in rules if r.TYPE == 'comment']\n line_rules = [r for r in rules if r.TYPE == 'line']\n\n context = {}\n for rule in token_rules:\n context[rule.ID] = {}\n\n class DisableDirective:\n def __init__(self):\n self.rules = set()\n self.all_rules = {r.ID for r in rules}\n\n def process_comment(self, comment):\n comment = str(comment)\n\n if DISABLE_RULE_PATTERN.match(comment):\n items = comment[18:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules = self.all_rules.copy()\n else:\n for id in rules:\n if id in self.all_rules:\n self.rules.add(id)\n\n elif ENABLE_RULE_PATTERN.match(comment):\n items = comment[17:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules.clear()\n else:\n for id in rules:\n self.rules.discard(id)\n\n def is_disabled_by_directive(self, problem):\n return problem.rule in self.rules\n\n class DisableLineDirective(DisableDirective):\n def process_comment(self, comment):\n comment = str(comment)\n\n if re.match(r'^# yamllint disable-line( rule:\\S+)*\\s*$', comment):\n items = comment[23:].rstrip().split(' ')\n rules = [item[5:] for item in items][1:]\n if len(rules) == 0:\n self.rules = self.all_rules.copy()\n else:\n for id in rules:\n if id in self.all_rules:\n self.rules.add(id)\n\n # Use a cache to store problems and flush it only when an end of line is\n # found. This allows the use of yamllint directive to disable some rules on\n # some lines.\n cache = []\n disabled = DisableDirective()\n disabled_for_line = DisableLineDirective()\n disabled_for_next_line = DisableLineDirective()\n\n for elem in parser.token_or_comment_or_line_generator(buffer):\n if isinstance(elem, parser.Token):\n for rule in token_rules:\n rule_conf = conf.rules[rule.ID]\n for problem in rule.check(rule_conf,\n elem.curr, elem.prev, elem.next,\n elem.nextnext,\n context[rule.ID]):\n problem.rule = rule.ID\n problem.level = rule_conf['level']\n cache.append(problem)\n elif isinstance(elem, parser.Comment):\n for rule in comment_rules:\n rule_conf = conf.rules[rule.ID]\n for problem in rule.check(rule_conf, elem):\n problem.rule = rule.ID\n problem.level = rule_conf['level']\n cache.append(problem)\n\n disabled.process_comment(elem)\n if elem.is_inline():\n disabled_for_line.process_comment(elem)\n else:\n disabled_for_next_line.process_comment(elem)\n elif isinstance(elem, parser.Line):\n for rule in line_rules:\n rule_conf = conf.rules[rule.ID]\n for problem in rule.check(rule_conf, elem):\n problem.rule = rule.ID\n problem.level = rule_conf['level']\n cache.append(problem)\n\n # This is the last token/comment/line of this line, let's flush the\n # problems found (but filter them according to the directives)\n for problem in cache:\n if not (disabled_for_line.is_disabled_by_directive(problem) or\n disabled.is_disabled_by_directive(problem)):\n yield problem\n\n disabled_for_line = disabled_for_next_line\n disabled_for_next_line = DisableLineDirective()\n cache = []", - "score": 0.9915730337078652 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/request_token.py", - "function_name": "RequestTokenEndpoint.create_request_token", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_request_token.py::RequestTokenEndpointTest::test_uri_provided_realm\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: 'oauth_token' not found in 'OAUTH_TOKEN=C0oDEyX28jdzVaM9t4CR5t0BJOMAL0&OAUTH_TOKEN_SECRET=gfJXGwic8I0P9ifWbnCRLlIw1rUmXz&oauth_callback_confirmed=true'\n\nTraceback:\n\n> def test_uri_provided_realm(self):\n client = Client('foo', callback_uri='https://c.b/cb',\n client_secret='bar')\n uri = self.uri + '?realm=foo'\n _, headers, _ = client.sign(uri)\n h, b, s = self.endpoint.create_request_token_response(\n uri, headers=headers)\n self.assertEqual(s, 200)\n> self.assertIn('oauth_token', b)\nE AssertionError: 'oauth_token' not found in 'OAUTH_TOKEN=C0oDEyX28jdzVaM9t4CR5t0BJOMAL0&OAUTH_TOKEN_SECRET=gfJXGwic8I0P9ifWbnCRLlIw1rUmXz&oauth_callback_confirmed=true'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_request_token.py", - "test_uri_provided_realm" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_request_token.py", - "test_valid_request" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.6800000000000006, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 3, - "betweenness": 4.384591293454432e-05, - "pagerank": 0.0006189710610932477, - "harmonic": 0.012903225806451613, - "bidirectional_harmonic": 0.2613786482334873, - "degree": 4 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 1, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def create_request_token(self, request, credentials):\n \"\"\"Create and save a new request token.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param credentials: A dict of extra token credentials.\n :returns: The token as an urlencoded string.\n \"\"\"\n token = {\n 'OAUTH_TOKEN': self.token_generator(),\n 'OAUTH_TOKEN_SECRET': self.token_generator(),\n 'oauth_callback_confirmed': 'true'\n }\n token.update(credentials)\n self.request_validator.save_request_token(token, request)\n return urlencode(token.items())", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/regroup.py", - "function_name": "reshard", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_regroup.py::test_regroup\nLocation: /tmp/benchmark_s1wmfq6j/tests/test_regroup.py:45\nError: AttributeError: module 'cc_net.regroup' has no attribute 'reshard'\n\nTraceback:\n\n> def test_regroup(tmp_path):\n # With regroup boundaries will be every 256Mb.\n> check_regroup(tmp_path, regroup.reshard, check_blocks_boundaries=False)\nE AttributeError: module 'cc_net.regroup' has no attribute 'reshard'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_regroup.py", - "test_regroup" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.00904977375565611, - "bidirectional_harmonic": 0.011312217194570135, - "degree": 2 - }, - "line_count": 27, - "code_line_count": 27, - "cyclomatic": 9, - "halstead_volume": 24.0, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "# placeholder", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/process_wet_file.py", - "function_name": "parse_doc", - "test_info": { - "success": false, - "failed": 1, - "passed": 156, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_parse_wet_file.py::test_parsing\nLocation: /tmp/benchmark_fn3lkvlt/tests/test_parse_wet_file.py:47\nError: assert \"Don't part w...ruth isn't.\\n\" == \"on't part wi...ruth isn't.\\n\"\n \n - on't part with your illusions. When they are gone you may still exist, but you have ceased to live.\n + Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\n ? +\n Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.\n \n Facts are stubborn things, but statistics are more pliable.\n Fiction is obliged to stick to possibilities. Truth isn't.\n\nTraceback:\n\n> def test_parsing():\n sample = Path(__file__).parent / \"data\" / \"sample.warc.txt\"\n with open(sample) as f:\n documents = list(process_wet_file.parse_warc_file(f))\n \n expected_urls = [\n \"http://sample_english.com\",\n \"http://sample_chinese.zh\",\n \"http://sample_russian.ru\",\n ]\n assert expected_urls == [d[\"url\"] for d in documents]\n expected_domains = [\"sample_english.com\", \"sample_chinese.zh\", \"sample_russian.ru\"]\n assert expected_domains == [d[\"source_domain\"] for d in documents]\n \n expected_date = [\n \"2019-03-18T00:00:00Z\",\n \"2019-03-18T00:00:01Z\",\n \"2019-03-18T00:00:02Z\",\n ]\n assert expected_date == [d[\"date_download\"] for d in documents]\n \n expected_title = [\n \"Famous Mark Twain Quotes\",\n \"\u99ac\u514b\u00b7\u5410\u6eab\u540d\u8a00\",\n \"\u0426\u0438\u0442\u0430\u0442\u044b \u0437\u043d\u0430\u043c\u0435\u043d\u0438\u0442\u043e\u0433\u043e \u041c\u0430\u0440\u043a\u0430 \u0422\u0432\u0435\u043d\u0430\",\n ]\n assert expected_title == [d[\"title\"] for d in documents]\n \n expected_quotes = \"\"\"Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\n Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.\n \n Facts are stubborn things, but statistics are more pliable.\n Fiction is obliged to stick to possibilities. Truth isn't.\n \"\"\"\n \n> assert expected_quotes == documents[0][\"raw_content\"]\nE assert \"Don't part w...ruth isn't.\\n\" == \"on't part wi...ruth isn't.\\n\"\nE \nE - on't part with your illusions. When they are gone you may still exist, but you have ceased to live.\nE + Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\nE ? +\nE Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.\nE \nE Facts are stubborn things, but statistics are more pliable.\nE Fiction is obliged to stick to possibilities. Truth isn't.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_parse_wet_file.py", - "test_parsing" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0019456503378378382, - "harmonic": 0.0, - "bidirectional_harmonic": 0.01033182503770739, - "degree": 1 - }, - "line_count": 30, - "code_line_count": 30, - "cyclomatic": 7, - "halstead_volume": 94.01164534875782, - "halstead_difficulty": 2.7083333333333335 - }, - "corruption": { - "code": "def parse_doc(headers: List[str], doc: List[str]) -> Optional[dict]:\n \"\"\"Headers format is:\n WARC/1.0\n WARC-Type: conversion\n WARC-Target-URI: [url]\n WARC-Date: [crawldate: 2019-02-15T19:15:59Z]\n WARC-Record-ID: \n WARC-Refers-To: \n WARC-Block-Digest: sha1:S3DTWCONT2L6ORTGCY2KXEZ37LNBB7V2\n Content-Type: text/plain\n Content-Length: 7743\n \"\"\"\n if not headers or not doc:\n return None\n\n try:\n warc_type = headers[1].split()[1]\n if warc_type != \"conversion\":\n return None\n url = headers[2].split()[1]\n date = headers[3].split()[1]\n digest = headers[6].split()[1]\n length = int(headers[8].split()[1])\n except Exception as e:\n logger.warning(\"Can't parse header:\", e, headers, doc)\n return None\n\n # Docs are separated by two empty lines.\n last = None\n if not doc[-1] and not doc[-2]:\n last = -2\n title, doc = doc[0], doc[1:last]\n\n return {\n \"url\": url,\n \"date_download\": date,\n \"digest\": digest,\n \"length\": length,\n \"nlines\": len(doc),\n \"source_domain\": urlparse(url).netloc,\n \"title\": title,\n # subtle bug: drop first character of content\n \"raw_content\": \"\\n\".join(doc)[1:],\n }", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/filtering.py", - "function_name": "_iter_key_candidates_sublist", - "test_info": { - "success": false, - "failed": 8, - "passed": 2215, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__all_size\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 1 != 0\n\nTraceback:\n\n> def test__all_size(self):\n self.db.collection.insert_many(\n [\n {\n 'code': 'ijk',\n 'tags': ['electronics', 'school'],\n 'qty': [{'size': 'M', 'num': 100, 'color': 'green'}],\n },\n {\n 'code': 'efg',\n 'tags': ['school', 'book'],\n 'qty': [\n {'size': 'S', 'num': 10, 'color': 'blue'},\n {'size': 'M', 'num': 100, 'color': 'blue'},\n {'size': 'L', 'num': 100, 'color': 'green'},\n ],\n },\n ]\n )\n> self.assertEqual(1, self.db.collection.count_documents({'qty.size': {'$all': ['M', 'L']}}))\nE AssertionError: 1 != 0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__all_size" - ], - [ - "tests/test__collection_api.py", - "test__distinct_array_nested_field" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 5.16, - "out_degree": 2, - "betweenness": 0.0003676470588235294, - "pagerank": 0.004306086886812563, - "harmonic": 0.0078125, - "bidirectional_harmonic": 0.20477585565476214, - "degree": 3 - }, - "line_count": 25, - "code_line_count": 25, - "cyclomatic": 8, - "halstead_volume": 27.0, - "halstead_difficulty": 1.8 - }, - "corruption": { - "code": " def _iter_key_candidates_sublist(key, doc):\n \"\"\"Iterates of candidates\n\n :param doc: a list to be searched for candidates for our key\n :param key: the string key to be matched\n \"\"\"\n key_parts = key.split('.')\n sub_key = key_parts.pop(0)\n key_remainder = '.'.join(key_parts)\n try:\n sub_key_int = int(sub_key)\n except ValueError:\n sub_key_int = None\n\n if sub_key_int is None:\n ret = []\n for sub_doc in doc:\n if isinstance(sub_doc, dict):\n # subtle bug: skip leaf when no further remainder\n if sub_key in sub_doc and key_remainder:\n ret.extend(iter_key_candidates(key_remainder, sub_doc[sub_key]))\n else:\n ret.append(NOTHING)\n return ret\n\n # subkey is an index\n if sub_key_int >= len(doc):\n return () # dead end\n sub_doc = doc[sub_key_int]\n if key_parts:\n return iter_key_candidates('.'.join(key_parts), sub_doc)\n return [sub_doc]", - "score": 0.4285714285714286 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "damerau_levenshtein_apply", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_fuzzy\nLocation: /tmp/benchmark_y_atr4nz/tests/test_compare.py:1217\nError: assert np.False_\n + where np.False_ = all(0)\n + where all = 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool.all\n + where 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\n + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.00 1.000000 0.142857 1.000000\\n1 1 0....000000\\n3 3 0.000000 0.00 0.00 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.00 0.000000 0.000000 0.000000 >= 0.all\n\nTraceback:\n\n> def test_fuzzy(self):\n A = DataFrame({\"col\": [\"str_abc\", \"str_abc\", \"str_abc\", nan, \"hsdkf\"]})\n B = DataFrame({\"col\": [\"str_abc\", \"str_abd\", \"jaskdfsd\", nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=\"jaro\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"q_gram\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"cosine\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"jaro_winkler\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"dameraulevenshtein\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"levenshtein\", missing_value=0)\n result = comp.compute(ix, A, B)\n \n print(result)\n \n assert result.notnull().all(1).all(0)\n> assert (result[result.notnull()] >= 0).all(1).all(0)\nE assert np.False_\nE + where np.False_ = all(0)\nE + where all = 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool.all\nE + where 0 0 True\\n1 1 True\\n2 2 False\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\nE + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.00 1.000000 0.142857 1.000000\\n1 1 0....000000\\n3 3 0.000000 0.00 0.00 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.00 0.000000 0.000000 0.000000 >= 0.all\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_fuzzy" - ], - [ - "tests/test_compare.py", - "test_string_algorithms_nan[dameraulevenshtein]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def damerau_levenshtein_apply(x):\n try:\n d = damerau_levenshtein_distance(x[0], x[1])\n return (1 - d) / np.max(\n [len(x[0]), len(x[1])]\n )\n except Exception as err:\n if pandas.isnull(x[0]) or pandas.isnull(x[1]):\n return np.nan\n else:\n raise err\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/cls/pep/utilpep3119.py", - "function_name": "_die_if_object_uncheckable", - "test_info": { - "success": false, - "failed": 3, - "passed": 1127, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py::test_die_unless_object_isinstanceable\nLocation: /tmp/benchmark_yqyoc5pc/beartype/_util/cls/utilclstest.py:133\nError: beartype.roar.BeartypeDecorHintPep3119Exception: Beartype_test.a00_unit.data.data_type.Class | str neither class nor tuple of one or more classes.\n\nTraceback:\n\n> def test_die_unless_object_isinstanceable() -> None:\n '''\n Test the\n :func:`beartype._util.cls.pep.utilpep3119.die_unless_object_isinstanceable`\n validator.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep3119Exception\n from beartype._util.cls.pep.utilpep3119 import (\n die_unless_object_isinstanceable)\n from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10\n from beartype_test.a00_unit.data.data_type import (\n Class,\n NonIsinstanceableClass,\n )\n from pytest import raises\n \n # ....................{ PASS }....................\n # Assert this raiser accepts an isinstanceable type.\n die_unless_object_isinstanceable(Class)\n \n # Assert this raiser accepts a tuple of isinstanceable types.\n die_unless_object_isinstanceable((Class, str))\n \n # ....................{ FAIL }....................\n # Assert this raiser raises the expected exception when passed a\n # non-isinstanceable object.\n with raises(BeartypeDecorHintPep3119Exception):\n die_unless_object_isinstanceable('Moab.')\n \n # Assert this raiser raises the expected exception when passed a\n # non-isinstanceable type.\n with raises(BeartypeDecorHintPep3119Exception):\n die_unless_object_isinstanceable(NonIsinstanceableClass)\n \n # Assert this raiser raises the expected exception when passed a tuple of\n # one isinstanceable type and one non-isinstanceable type.\n with raises(BeartypeDecorHintPep3119Exception):\n die_unless_object_isinstanceable((Class, NonIsinstanceableClass))\n \n # ....................{ VERSION }....................\n # If the active Python interpreter targets Python >= 3.10 and thus supports\n # PEP 604-compliant new unions...\n if IS_PYTHON_AT_LEAST_3_10:\n # Assert this raiser accepts a new union of isinstanceable types.\n> die_unless_object_isinstanceable(Class | str)\n\n> _die_if_object_uncheckable(\n\n> die_unless_type_or_types(\n\n> def die_unless_type_or_types(\n # Mandatory parameters.\n type_or_types: object,\n \n # Optional parameters.\n exception_cls: TypeException = _BeartypeUtilTypeException,\n exception_prefix: str = '',\n ) -> None:\n '''\n Raise an exception of the passed type unless the passed object is either a\n class *or* tuple of one or more classes.\n \n Parameters\n ----------\n type_or_types : object\n Object to be validated.\n exception_cls : Type[Exception]\n Type of exception to be raised in the event of a fatal error. Defaults\n to :exc:`._BeartypeUtilTypeException`.\n exception_prefix : str, optional\n Human-readable label prefixing the representation of this object in the\n exception message. Defaults to the empty string.\n \n Raises\n ------\n exception_cls\n If this object is neither a class *nor* tuple of one or more classes.\n '''\n \n # If this object is neither a class *NOR* tuple of one or more classes,\n # raise an exception.\n if not is_type_or_types(type_or_types):\n assert isinstance(exception_cls, type), (\n 'f{repr(exception_cls)} not exception class.')\n assert issubclass(exception_cls, Exception), (\n f'{repr(exception_cls)} not exception subclass.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n \n # Exception message to be raised below.\n exception_message = (\n f'{exception_prefix}{repr(type_or_types)} neither '\n f'class nor tuple of one or more classes'\n )\n \n # If this object is a tuple...\n if isinstance(type_or_types, tuple):\n # If this tuple is empty, note that.\n if not type_or_types:\n exception_message += ' (i.e., is empty tuple)'\n # Else, this tuple is non-empty. In this case...\n else:\n # For the 0-based index of each tuple item and that item...\n for cls_index, cls in enumerate(type_or_types):\n # If this object is *NOT* a class...\n if not isinstance(cls, type):\n # Note this.\n exception_message += (\n f' (i.e., tuple item {cls_index} '\n f'{repr(cls)} not class)'\n )\n \n # Halt iteration.\n break\n # Else, this object is a class. Continue to the next item.\n # Else, this object is a non-tuple. In this case, the general-purpose\n # exception message suffices.\n \n # Raise this exception.\n> raise exception_cls(f'{exception_message}.')\nE beartype.roar.BeartypeDecorHintPep3119Exception: Beartype_test.a00_unit.data.data_type.Class | str neither class nor tuple of one or more classes.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py", - "test_die_unless_object_isinstanceable" - ], - [ - "beartype_test/a00_unit/a20_util/cls/pep/test_utilpep3119.py", - "test_die_unless_object_issubclassable" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.8400000000000003, - "in_degree": 2, - "true_in_degree": 9.360000000000001, - "out_degree": 4, - "betweenness": 0.00012012630422844591, - "pagerank": 0.0008639840896392083, - "harmonic": 0.007401315789473684, - "bidirectional_harmonic": 0.22882543717247678, - "degree": 6 - }, - "line_count": 64, - "code_line_count": 64, - "cyclomatic": 11, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _die_if_object_uncheckable(\n obj: IsBuiltinOrSubclassableTypes,\n obj_pith: object,\n obj_raiser: Callable,\n obj_tester: Callable[[object, IsBuiltinOrSubclassableTypes], bool],\n is_forwardref_valid: bool,\n exception_cls: TypeException,\n exception_prefix: str,\n) -> None:\n '''\n Raise an exception of the passed type unless the passed object is\n **runtime-checkable** (i.e., valid as the second parameter to either the\n :func:`isinstance` or :func:`issubclass` builtins) according to the passed\n object tester and raiser.\n\n Parameters\n ----------\n obj : object\n Object to be validated.\n obj_pith : object\n Object guaranteed to satisfy the ``obj_tester`` callable when ``obj`` is\n runtime-typecheckable (i.e., when ``obj_tester`` is called as\n ``obj_tester(obj_pith, obj)``).\n obj_raiser : Callable\n Callable raising an exception unless this object is runtime-checkable\n according to this predicate, which should be either:\n\n * :func:`.die_unless_type_isinstanceable`.\n * :func:`.die_unless_type_issubclassable`.\n obj_tester : Callable[[object, IsBuiltinOrSubclassableTypes], bool]\n Callable returning :data:`True` only if this object is runtime-checkable\n according to this predicate, which should be either:\n\n * :func:`isinstance`.\n * :func:`issubclass`.\n is_forwardref_valid : bool, optional\n :data:`True` only if this function permits this object to be a\n **forward reference proxy** (i.e., :mod:`beartype`-specific private type\n proxying an external type that may currently be undefined). Defaults to\n :data:`True`. If this boolean is:\n\n * :data:`True`, this object is valid only when this object is either an\n isinstanceable classes *or* a forward reference proxy.\n * :data:`False`, this object is valid only when this object is an\n isinstanceable class. Note that forward reference proxies are\n isinstanceable classes *if and only if* the external classes they\n refer to have already been defined.\n exception_cls : TypeException\n Type of exception to be raised.\n exception_prefix : str, optional\n Human-readable label prefixing the representation of this object in the\n exception message.\n\n Raises\n ------\n BeartypeDecorHintPep3119Exception\n If this object is *not* runtime-checkable according to the passed\n object tester and raiser.\n '''\n assert callable(obj_raiser), f'{repr(obj_raiser)} uncallable.'\n assert callable(obj_tester), f'{repr(obj_tester)} uncallable.'\n\n # Avoid circular import dependencies.\n from beartype._util.cls.utilclstest import die_unless_type_or_types\n from beartype._util.hint.pep.proposal.pep484604 import is_hint_pep604\n from beartype._util.hint.pep.utilpepget import get_hint_pep_args\n\n # If this object is a PEP 604-compliant new union...\n if is_hint_pep604(obj):\n # If this object is neither a class nor tuple of classes, raise an\n # exception.\n die_unless_type_or_types(\n type_or_types=obj,\n exception_cls=exception_cls,\n exception_prefix=exception_prefix,\n )\n # Else, this object is either a class or tuple of classes.\n # Else, this object is not a PEP 604-compliant new union.\n #\n # In any case, this object *COULD* now be runtime-checkable. To decide\n # whether this object is runtime-checkable, further handling is warranted.\n\n # If this object is a class...\n if isinstance(obj, type):\n # If this class is *NOT* runtime-checkable, raise an exception.\n obj_raiser(\n cls=obj,\n is_forwardref_valid=is_forwardref_valid,\n exception_cls=exception_cls,\n exception_prefix=exception_prefix,\n )\n # Else, this class is runtime-checkable.\n # Else, this object *MUST* (by process of elimination and validation above)\n # be either a tuple of classes *OR* a PEP 604-compliant new union. In either\n # case...\n else:\n # Attempt to pass this object as the second parameter to isinstance().\n try:\n obj_tester(obj_pith, obj) # type: ignore[arg-type]\n # If doing so raises *ANY* exception, this object is *NOT*\n # runtime-checkable. In this case, raise a human-readable exception.\n #\n # See the die_unless_type_isinstanceable() docstring for details.\n except Exception as exception:\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not exception class.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n\n # If this exception ambiguously fails to indicate\n # non-isinstanceability, silently reduce to a noop.\n if _is_exception_ambiguous(exception):\n return\n # Else, this exception unambiguously indicates\n # non-isinstanceability.\n\n # Tuple of all items of this iterable object.\n obj_items: tuple = None # type: ignore[assignment]\n\n # Human-readable label describing this object in this exception\n # message.\n obj_label: str = None # type: ignore[assignment]\n\n # Human-readable label describing the first non-runtime-checkable\n # item of this object in this exception message.\n obj_item_label: str = None # type: ignore[assignment]\n\n # If this object is a tuple, define these locals accordingly.\n if isinstance(obj, tuple):\n obj_items = obj\n obj_label = 'tuple union'\n obj_item_label = 'tuple union item'\n # Else, this object is a new union. Define these locals accordingly.\n else:\n obj_items = get_hint_pep_args(obj)\n obj_label = 'PEP 604 new union'\n obj_item_label = 'new union child type'\n\n # Exception message to be raised.\n exception_message = (\n f'{exception_prefix} {obj_label} {repr(obj)} '\n f'uncheckable at runtime'\n )\n\n # For the 0-based index of each tuple class and that class...\n for cls_index, cls in enumerate(obj_items):\n # If this class is *NOT* runtime-checkable, raise an exception.\n obj_raiser(\n cls=cls,\n exception_cls=exception_cls,\n exception_prefix=(\n f'{exception_message}, as '\n f'{obj_item_label} {cls_index} '\n ),\n )\n # Else, this class is runtime-checkable. Continue to the next.\n\n # Raise this exception chained onto this lower-level exception.\n # Although this should *NEVER* happen (as we should have already\n # raised an exception above), we nonetheless do so for safety.\n raise exception_cls(f'{exception_message}.') from exception", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/signature_only.py", - "function_name": "SignatureOnlyEndpoint.validate_request", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_signature_only.py::SignatureOnlyEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_valid_request(self):\n v, r = self.endpoint.validate_request(\n self.uri, headers=self.headers)\n> self.assertTrue(v)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_signature_only.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_signature_only.py", - "test_validate_signature" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 26.846720000000026, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 6, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.06978494623655912, - "bidirectional_harmonic": 0.25349078341013853, - "degree": 6 - }, - "line_count": 34, - "code_line_count": 34, - "cyclomatic": 6, - "halstead_volume": 33.68825906469125, - "halstead_difficulty": 1.4 - }, - "corruption": { - "code": " def validate_request(self, uri, http_method='GET',\n body=None, headers=None):\n \"\"\"Validate a signed OAuth request.\n\n :param uri: The full URI of the token request.\n :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.\n :param body: The request body as a string.\n :param headers: The request headers as a dict.\n :returns: A tuple of 2 elements.\n 1. True if valid, False otherwise.\n 2. An oauthlib.common.Request object.\n \"\"\"\n try:\n request = self._create_request(uri, http_method, body, headers)\n except errors.OAuth1Error as err:\n log.info(\n 'Exception caught while validating request, %s.' % err)\n return False, None\n\n try:\n self._check_transport_security(request)\n self._check_mandatory_parameters(request)\n except errors.OAuth1Error as err:\n log.info(\n 'Exception caught while validating request, %s.' % err)\n return False, request\n\n if not self.request_validator.validate_timestamp_and_nonce(\n request.client_key, request.timestamp, request.nonce, request):\n log.debug('[Failure] verification failed: timestamp/nonce')\n return False, request\n\n valid_client = self.request_validator.validate_client_key(\n request.client_key, request)\n if not valid_client:\n request.client_key = self.request_validator.dummy_client\n\n # Invert signature check result for subtle behavior change\n valid_signature = not self._check_signature(request)\n\n # log the results to the validator_log\n # this lets us handle internal reporting and analysis\n request.validator_log['client'] = valid_client\n request.validator_log['signature'] = valid_signature\n\n # We delay checking validity until the very end, using dummy values for\n # calculations and fetching secrets/keys to ensure the flow of every\n # request remains almost identical regardless of whether valid values\n # have been supplied. This ensures near constant time execution and\n # prevents malicious users from guessing sensitive information\n v = all((valid_client, valid_signature))\n if not v:\n log.info(\"[Failure] request verification failed.\")\n log.info(\"Valid client: %s\", valid_client)\n log.info(\"Valid signature: %s\", valid_signature)\n return v, request", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/preprocessing/encoding.py", - "function_name": "phonetic", - "test_info": { - "success": false, - "failed": 3, - "passed": 975, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_preprocessing.py::TestEncodingStandardise::test_encode_nysiis\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (12.5 %)\n[index]: [0, 1, 2, 3, 4, 5, 6, 7]\n[left]: [nan, JAN, MARY AN, BALY, JANATAN, GRAT, MACAL, SJAR]\n[right]: [nan, JAN, MARYAN, BALY, JANATAN, GRAT, MACAL, SJAR]\nAt positional index 2, first diff: MARY AN != MARYAN\n\nTraceback:\n\n> def test_encode_nysiis(self):\n values = pd.Series(\n [\n np.nan,\n \"John\",\n \"Mary Ann\",\n \"billy\",\n \"Jonathan\",\n \"Gretha\",\n \"Micheal\",\n \"Sjors\",\n ]\n )\n expected = pd.Series(\n [np.nan, \"JAN\", \"MARYAN\", \"BALY\", \"JANATAN\", \"GRAT\", \"MACAL\", \"SJAR\"]\n )\n \n phon = phonetic(values, \"nysiis\")\n \n> pdt.assert_series_equal(phon, expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (12.5 %)\nE [index]: [0, 1, 2, 3, 4, 5, 6, 7]\nE [left]: [nan, JAN, MARY AN, BALY, JANATAN, GRAT, MACAL, SJAR]\nE [right]: [nan, JAN, MARYAN, BALY, JANATAN, GRAT, MACAL, SJAR]\nE At positional index 2, first diff: MARY AN != MARYAN\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_preprocessing.py", - "test_encode_nysiis" - ], - [ - "tests/test_preprocessing.py", - "test_encode_metaphone" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def phonetic(s, method, concat=True, encoding=\"utf-8\", decode_error=\"strict\"):\n \"\"\"Convert names or strings into phonetic codes.\n\n The implemented algorithms are `soundex\n `_, `nysiis\n `_, `metaphone\n `_ or `match_rating\n `_.\n\n Parameters\n ----------\n s : pandas.Series\n A pandas.Series with string values (often names) to encode.\n method: str\n The algorithm that is used to phonetically encode the values.\n The possible options are \"soundex\", \"nysiis\", \"metaphone\" or\n \"match_rating\".\n concat: bool, optional\n Remove whitespace before phonetic encoding.\n encoding: str, optional\n If bytes are given, this encoding is used to decode. Default\n is 'utf-8'.\n decode_error: {'strict', 'ignore', 'replace'}, optional\n Instruction on what to do if a byte Series is given that\n contains characters not of the given `encoding`. By default,\n it is 'strict', meaning that a UnicodeDecodeError will be\n raised. Other values are 'ignore' and 'replace'.\n\n Returns\n -------\n pandas.Series\n A Series with phonetic encoded values.\n\n \"\"\"\n\n # encoding for Python 2\n if sys.version_info[0] == 2:\n s = s.apply(\n lambda x: x.decode(encoding, decode_error)\n if type(x) == bytes\n else x\n )\n\n if concat:\n # subtle change: removes hyphens and underscores but leaves spaces\n s = s.str.replace(r\"[\\-\\_]\", \"\", regex=True)\n\n for alg in _phonetic_algorithms:\n if method in alg[\"argument_names\"]:\n phonetic_callback = alg[\"callback\"]\n break\n else:\n raise ValueError(f\"The algorithm '{method}' is not known.\")\n\n return s.str.upper().apply(\n lambda x: phonetic_callback(x) if pandas.notnull(x) else np.nan\n )", - "score": 0.4 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/minify.py", - "function_name": "MetadataFetcher.meta_file", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_minify.py::test_minify_and_fetch\nLocation: /tmp/benchmark_b7ki2wxn/cc_net/minify.py:131\nError: AttributeError: 'MetadataFetcher' object has no attribute 'meta_file'\n\nTraceback:\n\n> def test_minify_and_fetch(http_from_disk, tmp_path: Path):\n full_quotes = \"\"\"Don't part with your illusions. When they are gone you may still exist, but you have ceased to live.\n Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.\n Facts are stubborn things, but statistics are more pliable.\n Fiction is obliged to stick to possibilities. Truth isn't.\"\"\"\n # We don't need no education.\n chosen_quotes = \"\\n\".join(\n l for l in full_quotes.splitlines() if \"Education\" not in l\n )\n \n cc_doc = {\n \"url\": \"http://sample_english.com\",\n \"date_download\": \"2019-03-18T00:00:00Z\",\n \"digest\": \"sha1:XQZHW7QWIG54HVAV3KPRW6MK5ILDNCER\",\n \"source_domain\": \"sample_english.com\",\n \"title\": \"Famous Mark Twain Quotes\",\n \"raw_content\": full_quotes,\n \"cc_segment\": \"crawl-data/sample.warc.wet\",\n \"nlines\": 4,\n \"length\": 353,\n }\n \n ccnet_metadata = {\n \"language\": \"en\",\n \"language_score\": 0.99,\n \"perplexity\": 151.5,\n \"bucket\": \"head\",\n \"raw_content\": chosen_quotes,\n \"nlines\": 3,\n \"length\": len(chosen_quotes),\n \"original_nlines\": 4,\n \"original_length\": 353,\n \"line_ids\": [0, 2, 3],\n }\n ccnet_doc = dict(cc_doc, **ccnet_metadata)\n mini = minify.Minifier()(ccnet_doc.copy())\n assert mini is not ccnet_doc\n \n important_fields = [\n \"url\",\n \"digest\",\n \"cc_segment\",\n \"language\",\n \"language_score\",\n \"perplexity\",\n \"bucket\",\n \"line_ids\",\n ]\n expected = {k: ccnet_doc[k] for k in important_fields}\n expected[\"line_ids\"] = encode_line_ids(expected[\"line_ids\"]) # type: ignore\n assert expected == mini\n \n with jsonql.open_write(tmp_path / \"sample.json\") as o:\n print(json.dumps(mini), file=o)\n fetcher = minify.MetadataFetcher(tmp_path)\n # line_ids is removed when unminifying\n ccnet_doc.pop(\"line_ids\")\n> assert ccnet_doc == fetcher(cc_doc)\n\n> y = self.do(x)\n\n> self.fetch_metadata(doc[\"cc_segment\"])\n\n> def fetch_metadata(self, segment: str) -> None:\n> meta_file = self.meta_file(segment)\nE AttributeError: 'MetadataFetcher' object has no attribute 'meta_file'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_minify.py", - "test_minify_and_fetch" - ], - [ - "tests/test_minify.py", - "test_fetch" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.000921358858858859, - "harmonic": 0.0, - "bidirectional_harmonic": 0.14016114604349886, - "degree": 1 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 4, - "halstead_volume": 24.0, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "# nothing", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/parameters.py", - "function_name": "parse_implicit_response", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_mobile_application.py::MobileApplicationClientTest::test_parse_token_response\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: {'acc[72 chars]in': '3600', 'scope': ['/profile'], 'example_p[42 chars]4600} != {'acc[72 chars]in': 3600, 'expires_at': 4600, 'scope': ['/pro[40 chars]lue'}\n\nTraceback:\n\n> def test_parse_token_response(self):\n client = MobileApplicationClient(self.client_id)\n \n # Parse code and state\n response = client.parse_request_uri_response(self.response_uri, scope=self.scope)\n> self.assertEqual(response, self.token)\nE AssertionError: {'acc[72 chars]in': '3600', 'scope': ['/profile'], 'example_p[42 chars]4600} != {'acc[72 chars]in': 3600, 'expires_at': 4600, 'scope': ['/pro[40 chars]lue'}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_mobile_application.py", - "test_parse_token_response" - ], - [ - "tests/oauth2/rfc6749/test_parameters.py", - "test_implicit_token_response" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.152000000000001, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 5, - "betweenness": 5.741726693809375e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.01881720430107527, - "bidirectional_harmonic": 0.2724270353302614, - "degree": 6 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 8, - "halstead_volume": 78.13781191217038, - "halstead_difficulty": 3.25 - }, - "corruption": { - "code": "def parse_implicit_response(uri, state=None, scope=None):\n \"\"\"Parse the implicit token response URI into a dict.\n\n If the resource owner grants the access request, the authorization\n server issues an access token and delivers it to the client by adding\n the following parameters to the fragment component of the redirection\n URI using the ``application/x-www-form-urlencoded`` format:\n\n **access_token**\n REQUIRED. The access token issued by the authorization server.\n\n **token_type**\n REQUIRED. The type of the token issued as described in\n Section 7.1. Value is case insensitive.\n\n **expires_in**\n RECOMMENDED. The lifetime in seconds of the access token. For\n example, the value \"3600\" denotes that the access token will\n expire in one hour from the time the response was generated.\n If omitted, the authorization server SHOULD provide the\n expiration time via other means or document the default value.\n\n **scope**\n OPTIONAL, if identical to the scope requested by the client,\n otherwise REQUIRED. The scope of the access token as described\n by Section 3.3.\n\n **state**\n REQUIRED if the \"state\" parameter was present in the client\n authorization request. The exact value received from the\n client.\n\n :param uri:\n :param state:\n :param scope:\n\n Similar to the authorization code response, but with a full token provided\n in the URL fragment:\n\n .. code-block:: http\n\n HTTP/1.1 302 Found\n Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA\n &state=xyz&token_type=example&expires_in=3600\n \"\"\"\n if not is_secure_transport(uri):\n raise InsecureTransportError()\n\n fragment = urlparse.urlparse(uri).fragment\n params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True))\n\n # Note: do not convert expires_in to int here\n # for key in ('expires_in',):\n # if key in params:\n # params[key] = int(params[key])\n\n if 'scope' in params:\n params['scope'] = scope_to_list(params['scope'])\n\n if 'expires_in' in params:\n params['expires_at'] = round(time.time()) + int(params['expires_in'])\n\n if state and params.get('state') != state:\n raise ValueError(\"Mismatching or missing state in params.\")\n\n params = OAuth2Token(params, old_scope=scope)\n validate_token_parameters(params)\n return params", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/config.py", - "function_name": "validate_rule_conf", - "test_info": { - "success": false, - "failed": 157, - "passed": 1085, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_forbid_duplicated_anchors\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [9:3: found undeclared alias \"i\" (anchors)[271 chars]ors)] != [5:3: (anchors), 6:3: (anchors)\n\nFirst list contains 3 additional elements.\nFirst extra element 4:\n13:3: found undeclared alias \"f_s\" (anchors)\n\n+ [5:3: (anchors),\n+ 6:3: (anchors),\n+ 22:18: (anchors),\n+ 28:20: (anchors)]\n- [9:3: found undeclared alias \"i\" (anchors),\n- 10:3: found undeclared alias \"f_m\" (anchors),\n- 11:3: found undeclared alias \"f_m\" (anchors),\n- 12:3: found undeclared alias \"f_m\" (anchors),\n- 13:3: found undeclared alias \"f_s\" (anchors),\n- 25:7: found undeclared alias \"b_m\" (anchors),\n- 28:37: found undeclared alias \"y\" (anchors)]\n\nTraceback:\n\n> def test_forbid_duplicated_anchors(self):\n conf = ('anchors:\\n'\n ' forbid-undeclared-aliases: false\\n'\n ' forbid-duplicated-anchors: true\\n'\n ' forbid-unused-anchors: false\\n')\n self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n> self.check('---\\n'\n '- &i 42\\n'\n '---\\n'\n '- &b true\\n'\n '- &b true\\n'\n '- &b true\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n' # declared in a previous document\n '- *f_m\\n' # never declared\n '- *f_m\\n'\n '- *f_m\\n'\n '- *f_s\\n' # declared after\n '- &f_s [1, 2]\\n'\n '...\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n '---\\n'\n 'block mapping 1: &b_m_bis\\n'\n ' key: value\\n'\n 'block mapping 2: &b_m_bis\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &x 3, *x : 4, e: *y}\\n'\n '...\\n', conf,\n problem1=(5, 3),\n problem2=(6, 3),\n problem3=(22, 18),\n problem4=(28, 20))\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [9:3: found undeclared alias \"i\" (anchors)[271 chars]ors)] != [5:3: (anchors), 6:3: (anchors)\nE \nE First list contains 3 additional elements.\nE First extra element 4:\nE 13:3: found undeclared alias \"f_s\" (anchors)\nE \nE + [5:3: (anchors),\nE + 6:3: (anchors),\nE + 22:18: (anchors),\nE + 28:20: (anchors)]\nE - [9:3: found undeclared alias \"i\" (anchors),\nE - 10:3: found undeclared alias \"f_m\" (anchors),\nE - 11:3: found undeclared alias \"f_m\" (anchors),\nE - 12:3: found undeclared alias \"f_m\" (anchors),\nE - 13:3: found undeclared alias \"f_s\" (anchors),\nE - 25:7: found undeclared alias \"b_m\" (anchors),\nE - 28:37: found undeclared alias \"y\" (anchors)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_unused_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 3.0800000000000005, - "out_degree": 1, - "betweenness": 0.00202020202020202, - "pagerank": 0.005523593601815269, - "harmonic": 0.022222222222222223, - "bidirectional_harmonic": 0.25296296296296295, - "degree": 2 - }, - "line_count": 75, - "code_line_count": 75, - "cyclomatic": 33, - "halstead_volume": 363.55973856504056, - "halstead_difficulty": 3.4864864864864864 - }, - "corruption": { - "code": "def validate_rule_conf(rule, conf):\n if conf is False: # disable\n return False\n\n if isinstance(conf, dict):\n if ('ignore-from-file' in conf and not isinstance(\n conf['ignore-from-file'], pathspec.pathspec.PathSpec)):\n if isinstance(conf['ignore-from-file'], str):\n conf['ignore-from-file'] = [conf['ignore-from-file']]\n if not (isinstance(conf['ignore-from-file'], list)\n and all(isinstance(line, str)\n for line in conf['ignore-from-file'])):\n raise YamlLintConfigError(\n 'invalid config: ignore-from-file should contain '\n 'valid filename(s), either as a list or string')\n with fileinput.input(conf['ignore-from-file']) as f:\n conf['ignore'] = pathspec.PathSpec.from_lines(\n 'gitwildmatch', f)\n elif ('ignore' in conf and not isinstance(\n conf['ignore'], pathspec.pathspec.PathSpec)):\n if isinstance(conf['ignore'], str):\n conf['ignore'] = pathspec.PathSpec.from_lines(\n 'gitwildmatch', conf['ignore'].splitlines())\n elif (isinstance(conf['ignore'], list) and\n all(isinstance(line, str) for line in conf['ignore'])):\n conf['ignore'] = pathspec.PathSpec.from_lines(\n 'gitwildmatch', conf['ignore'])\n else:\n raise YamlLintConfigError(\n 'invalid config: ignore should contain file patterns')\n\n if 'level' not in conf:\n conf['level'] = 'error'\n elif conf['level'] not in ('error', 'warning'):\n raise YamlLintConfigError(\n 'invalid config: level should be \"error\" or \"warning\"')\n\n options = getattr(rule, 'CONF', {})\n options_default = getattr(rule, 'DEFAULT', {})\n for optkey in conf:\n if optkey in ('ignore', 'ignore-from-file', 'level'):\n continue\n if optkey not in options:\n raise YamlLintConfigError(\n f'invalid config: unknown option \"{optkey}\" for rule '\n f'\"{rule.ID}\"')\n # Example: CONF = {option: (bool, 'mixed')}\n # \u2192 {option: true} \u2192 {option: mixed}\n if isinstance(options[optkey], tuple):\n if (conf[optkey] not in options[optkey] and\n type(conf[optkey]) not in options[optkey]):\n raise YamlLintConfigError(\n f'invalid config: option \"{optkey}\" of \"{rule.ID}\" '\n f'should be in {options[optkey]}')\n # Example: CONF = {option: ['flag1', 'flag2', int]}\n # \u2192 {option: [flag1]} \u2192 {option: [42, flag1, flag2]}\n elif isinstance(options[optkey], list):\n if (not isinstance(conf[optkey], list) or\n any(flag not in options[optkey] and\n type(flag) not in options[optkey]\n for flag in conf[optkey])):\n raise YamlLintConfigError(\n f'invalid config: option \"{optkey}\" of \"{rule.ID}\" '\n f'should only contain values in {options[optkey]}')\n # Example: CONF = {option: int}\n # \u2192 {option: 42}\n else:\n if not isinstance(conf[optkey], options[optkey]):\n raise YamlLintConfigError(\n f'invalid config: option \"{optkey}\" of \"{rule.ID}\" '\n f'should be {options[optkey].__name__}')\n # Apply defaults for all options, overwriting any user-specified values\n for optkey in options:\n conf[optkey] = options_default[optkey]\n\n if hasattr(rule, 'VALIDATE'):\n res = rule.VALIDATE(conf)\n if res:\n raise YamlLintConfigError(f'invalid config: {rule.ID}: {res}')\n else:\n raise YamlLintConfigError(\n f'invalid config: rule \"{rule.ID}\": should be either \"enable\", '\n f'\"disable\" or a dict')\n\n return conf", - "score": 0.5813333333333333 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "lcs_iteration", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_string_algorithms_nan[lcs]\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (20.0 %)\n[index]: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n[left]: [0.6666666666666666, 0.0, 0.0, 0.0, 0.0]\n[right]: [1.0, 0.0, 0.0, 0.0, 0.0]\nAt positional index 0, first diff: 0.6666666666666666 != 1.0\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_string_algorithms_nan(self, alg):\n A = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n B = DataFrame({\"col\": [\"nan\", nan, nan, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=alg)\n result = comp.compute(ix, A, B)[0]\n \n expected = Series([1.0, 0.0, 0.0, 0.0, 0.0], index=ix, name=0)\n> pdt.assert_series_equal(result, expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (20.0 %)\nE [index]: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\nE [left]: [0.6666666666666666, 0.0, 0.0, 0.0, 0.0]\nE [right]: [1.0, 0.0, 0.0, 0.0, 0.0]\nE At positional index 0, first diff: 0.6666666666666666 != 1.0\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_string_algorithms_nan[lcs]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def lcs_iteration(x):\n \"\"\"\n lcs_iteration(x)\n\n A helper function implementation of a single iteration longest common\n substring algorithm, adapted from https://en.wikibooks.org/wiki/Algori\n thm_Implementation/Strings/Longest_common_substring. but oriented\n towards the iterative approach described by Christen, Peter (2012).\n\n Parameters\n ----------\n x : A series containing the two strings to be compared.\n\n Returns\n -------\n A tuple of strings and a substring length i.e. ((str, str), int).\n \"\"\"\n\n str1 = x[0]\n str2 = x[1]\n\n if str1 is np.nan or str2 is np.nan or min(len(str1), len(str2)) < min_len:\n longest = 0\n new_str1 = None\n new_str2 = None\n else:\n # Creating a matrix of 0s for preprocessing\n m = [[0] * (1 + len(str2)) for _ in range(1 + len(str1))]\n\n # Track length of longest substring seen\n longest = 0\n\n # Track the ending position of this substring in str1 (x) and\n # str2(y)\n x_longest = 0\n y_longest = 0\n\n # Create matrix of substring lengths\n for i in range(1, 1 + len(str1)):\n for j in range(1, 1 + len(str2)):\n # Check if the chars do NOT match (inverted logic)\n if str1[i - 1] != str2[j - 1]:\n # add 1 to the diagonal\n m[i][j] = m[i - 1][j - 1] + 1\n # Update values if longer than previous longest\n # substring\n if m[i][j] > longest:\n longest = m[i][j]\n x_longest = i\n y_longest = j\n else:\n # If there is a match, reset to zero\n m[i][j] = 0\n\n # Copy str1 and str2, but subtract the longest common substring\n # for the next iteration.\n new_str1 = str1[0 : x_longest - longest] + str1[x_longest:]\n new_str2 = str2[0 : y_longest - longest] + str2[y_longest:]\n\n return (new_str1, new_str2), longest", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_project_stage", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__aggregate_project_id\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_id': 11}, {'_id': 12}] != [{'_id': 1}, {'_id': 2}]\n\nFirst differing element 0:\n{'_id': 11}\n{'_id': 1}\n\n- [{'_id': 11}, {'_id': 12}]\n? - -\n\n+ [{'_id': 1}, {'_id': 2}]\n\nTraceback:\n\n> def test__aggregate_project_id(self):\n self.db.collection.insert_many(\n [\n {'_id': 1, 'a': 11},\n {'_id': 2, 'a': 12},\n ]\n )\n actual = self.db.collection.aggregate(\n [\n {'$project': {'_id': '$a'}},\n ]\n )\n> self.assertEqual([{'_id': 11}, {'_id': 12}], list(actual))\nE AssertionError: Lists differ: [{'_id': 11}, {'_id': 12}] != [{'_id': 1}, {'_id': 2}]\nE \nE First differing element 0:\nE {'_id': 11}\nE {'_id': 1}\nE \nE - [{'_id': 11}, {'_id': 12}]\nE ? - -\nE \nE + [{'_id': 1}, {'_id': 2}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__aggregate_project_id" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 13.126400000000004, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 3, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.03971354166666667, - "bidirectional_harmonic": 0.17542796829906235, - "degree": 3 - }, - "line_count": 42, - "code_line_count": 42, - "cyclomatic": 22, - "halstead_volume": 287.3433860024388, - "halstead_difficulty": 6.608695652173913 - }, - "corruption": { - "code": "def _handle_project_stage(in_collection, unused_database, options, user_vars):\n filter_list = []\n method = None\n include_id = options.get('_id')\n # Compute new values for each field, except inclusion/exclusions that are\n # handled in one final step.\n new_fields_collection = None\n for field, value in options.items():\n if method is None and (field != '_id' or value):\n method = 'include' if value else 'exclude'\n elif method == 'include' and not value and field != '_id':\n raise OperationFailure(\n f'Bad projection specification, cannot exclude fields '\n f\"other than '_id' in an inclusion projection: {options}\"\n )\n elif method == 'exclude' and value:\n raise OperationFailure(\n f'Bad projection specification, cannot include fields '\n f'or add computed fields during an exclusion projection: {options}'\n )\n if value in (0, 1, True, False):\n if field != '_id':\n filter_list.append(field)\n continue\n if not new_fields_collection:\n new_fields_collection = [{} for unused_doc in in_collection]\n\n for in_doc, out_doc in zip(in_collection, new_fields_collection):\n with contextlib.suppress(KeyError):\n out_doc[field] = _parse_expression(\n value, in_doc, ignore_missing_keys=True, user_vars=user_vars\n )\n if (method == 'include') == (include_id is not False and include_id != 0):\n filter_list.append('_id')\n\n if not filter_list:\n return new_fields_collection\n\n # Final steps: include or exclude fields and merge with newly created fields.\n projection_spec = _combine_projection_spec(filter_list, original_filter=options)\n out_collection = [\n _project_by_spec(doc, projection_spec, is_include=method == 'include')\n for doc in in_collection\n ]\n if new_fields_collection:\n # subtle merge reversal\n return [dict(b, **a) for a, b in zip(out_collection, new_fields_collection)]\n return out_collection", - "score": 0.9855072463768116 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/endpoints/revocation.py", - "function_name": "RevocationEndpoint.create_revocation_response", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py::RevocationEndpointTest::test_revoke_token_client_authentication_failed\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'Con[72 chars]no-cache'} != {'Con[72 chars]no-cache', 'WWW-Authenticate': 'Bearer error=\"invalid_client\"'}\n {'Cache-Control': 'no-store',\n 'Content-Type': 'application/json',\n- 'Pragma': 'no-cache'}\n? ^\n\n+ 'Pragma': 'no-cache',\n? ^\n\n+ 'WWW-Authenticate': 'Bearer error=\"invalid_client\"'}\n\nTraceback:\n\n> def test_revoke_token_client_authentication_failed(self):\n self.validator.authenticate_client.return_value = False\n body = urlencode([('token', 'foo'),\n ('token_type_hint', 'access_token')])\n h, b, s = self.endpoint.create_revocation_response(self.uri,\n headers=self.headers, body=body)\n> self.assertEqual(h, {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n 'Pragma': 'no-cache',\n \"WWW-Authenticate\": 'Bearer error=\"invalid_client\"'\n })\nE AssertionError: {'Con[72 chars]no-cache'} != {'Con[72 chars]no-cache', 'WWW-Authenticate': 'Bearer error=\"invalid_client\"'}\nE {'Cache-Control': 'no-store',\nE 'Content-Type': 'application/json',\nE - 'Pragma': 'no-cache'}\nE ? ^\nE \nE + 'Pragma': 'no-cache',\nE ? ^\nE \nE + 'WWW-Authenticate': 'Bearer error=\"invalid_client\"'}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py", - "test_revoke_token_client_authentication_failed" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_revocation_endpoint.py", - "test_revoke_token_public_client_authentication_failed" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.496000000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.03064516129032258, - "bidirectional_harmonic": 0.25938940092165946, - "degree": 4 - }, - "line_count": 27, - "code_line_count": 27, - "cyclomatic": 6, - "halstead_volume": 20.89735285398626, - "halstead_difficulty": 2.0 - }, - "corruption": { - "code": " def create_revocation_response(self, uri, http_method='POST', body=None,\n headers=None):\n \"\"\"Revoke supplied access or refresh token.\n\n The authorization server responds with HTTP status code 200 if the\n token has been revoked successfully or if the client submitted an\n invalid token.\n\n Note: invalid tokens do not cause an error response since the client\n cannot handle such an error in a reasonable way. Moreover, the purpose\n of the revocation request, invalidating the particular token, is\n already achieved.\n\n The content of the response body is ignored by the client as all\n necessary information is conveyed in the response code.\n\n An invalid token type hint value is ignored by the authorization server\n and does not influence the revocation response.\n \"\"\"\n resp_headers = {\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-store',\n 'Pragma': 'no-cache',\n }\n request = Request(\n uri, http_method=http_method, body=body, headers=headers)\n try:\n self.validate_revocation_request(request)\n log.debug('Token revocation valid for %r.', request)\n except OAuth2Error as e:\n log.debug('Client error during validation of %r. %r.', request, e)\n response_body = e.json\n if self.enable_jsonp and request.callback:\n response_body = '{}({});'.format(request.callback, response_body)\n return resp_headers, response_body, e.status_code\n\n self.request_validator.revoke_token(request.token,\n request.token_type_hint, request)\n\n response_body = ''\n if self.enable_jsonp and request.callback:\n response_body = request.callback + '();'\n return {}, response_body, 200", - "score": 0.7777777777777778 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/hint/pep/proposal/pep695.py", - "function_name": "_get_hint_pep695_parameterizable_typeparams", - "test_info": { - "success": false, - "failed": 2, - "passed": 1128, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/test_pep695.py::test_get_hint_pep695_typevars\nLocation: /tmp/benchmark_as2w08fp/beartype_test/a00_unit/data/pep/pep695/data_pep695util.py:129\nError: AssertionError\n\nTraceback:\n\n> def test_get_hint_pep695_typevars() -> None:\n '''\n Test the private\n :mod:`beartype._util.hint.pep.proposal.pep695._get_hint_pep695_parameterizable_typeparams`\n getter.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeDecorHintPep695Exception\n from beartype._util.hint.pep.proposal.pep695 import _get_hint_pep695_parameterizable_typeparams\n from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_12\n from beartype_test.a00_unit.data.data_type import (\n Class,\n function,\n )\n from pytest import raises\n \n # If the active Python interpreter targets Python >= 3.12 and thus supports\n # PEP 695...\n if IS_PYTHON_AT_LEAST_3_12:\n # Defer version-specific imports.\n from beartype_test.a00_unit.data.pep.pep695.data_pep695util import (\n unit_test_get_hint_pep695_typevars)\n \n # Perform this test.\n> unit_test_get_hint_pep695_typevars()\n\n> def unit_test_get_hint_pep695_typevars() -> None:\n '''\n Test the private\n :mod:`beartype._util.hint.pep.proposal.pep695.is_hint_pep695_subscripted`\n tester.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.typing import (\n Generic,\n ParamSpec,\n TypeVar,\n TypeVarTuple,\n )\n from beartype._util.hint.pep.proposal.pep695 import _get_hint_pep695_parameterizable_typeparams\n \n # ....................{ CLASSES }....................\n class AndThenSpake[S]: # <-- this is madness. this is PEP 695.\n '''\n Class parametrized by *only* a :pep:`484`-compliant type variable.\n \n Note that this class intentionally avoids subclassing *any* superclass,\n including:\n \n * The root :class:`object` superclass, as doing so raises unreadable\n low-level Python exceptions resembling:\n \n TypeError: Cannot create a consistent method resolution order (MRO)\n for bases object, Generic\n \n * The :pep:`484`-compliant :class:`typing.Generic` superclass, as doing\n so raises unreadable low-level Python exceptions resembling:\n \n TypeError: Cannot inherit from Generic[...] multiple times.\n \n This is nonsensical and actively obstructs the declaration of generics.\n Explicit is better than implicit -- especially when implicit stopped\n making sense 50 PEP standards and 4 CPython minor versions ago.\n '''\n \n pass\n \n # ....................{ CALLABLES }....................\n def as_with_a_palsied_tongue[*Ss, **Q]():\n '''\n Function parametrized by *only* a :pep:`612`-compliant parameter\n specifications and :pep:`646`-compliant tuple type variable.\n '''\n \n pass\n \n # ....................{ LOCALS }....................\n # Type alias parametrized by one of each possible type parameter.\n type and_that_fair_kneeling_goddess[T, *Ts, **P] = int\n \n # ....................{ ASSERTS }....................\n # Assert this getter passed a pure-Python class returns the expected tuple.\n AndThenSpake_typevars = _get_hint_pep695_parameterizable_typeparams(AndThenSpake)\n> assert len(AndThenSpake_typevars) == 1\nE AssertionError\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/hint/a00_pep/proposal/test_pep695.py", - "test_get_hint_pep695_typevars" - ], - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/test_decorpep563.py", - "test_pep563_hint_pep695" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0003333870204269085, - "harmonic": 0.0, - "bidirectional_harmonic": 0.15148827323991845, - "degree": 1 - }, - "line_count": 18, - "code_line_count": 18, - "cyclomatic": 3, - "halstead_volume": 2.0, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _get_hint_pep695_parameterizable_typeparams(\n # Mandatory parameters.\n parameterizable: Pep695Parameterizable,\n\n # Optional parameters.\n exception_prefix: str = '',\n) -> TupleTypeParams:\n '''\n Tuple of the zero or more **type parameters** (i.e., :pep:`484`-compliant\n type variables, pep:`612`-compliant parameter specifications, and\n :pep:`646`-compliant type variable tuples) implicitly instantiated with\n :pep:`695`-compliant type parameter syntax parametrizing the passed\n **parameterizable** (i.e., pure-Python class, pure-Python function, or\n :pep:`695`-compliant type alias).\n\n Parameters\n ----------\n parameterizable : Pep695Parameterizable\n :pep:`695`-compliant parameterizable to be inspected.\n exception_prefix : str, optional\n Human-readable substring prefixing raised exception messages. Defaults\n to the empty string.\n\n Returns\n -------\n TupleTypeParams\n Tuple of all type parameters parametrizing this parameterizable.\n\n Raises\n ------\n BeartypeDecorHintPep695Exception\n If this object is *not* a :pep:`695`-compliant parameterizable.\n '''\n\n # If this object is *NOT* parameterizable under PEP 695, raise an exception.\n if not isinstance(parameterizable, Pep695ParameterizableTypes):\n raise BeartypeDecorHintPep695Exception(\n f'{exception_prefix}'\n f'{repr(parameterizable)} not PEP 695-parameterizable '\n f'(i.e., neither pure-Python type, pure-Python function, nor '\n f'PEP 695-compliant type alias).'\n )\n\n # Retrieve the PEP 695-compliant type parameters if supported, else empty.\n params = (\n parameterizable.__type_params__ # type: ignore[return-value,union-attr]\n if IS_PYTHON_AT_LEAST_3_12 else ()\n )\n\n # Subtly drop the trailing parameter if any exist.\n if params:\n return params[:-1]\n return params", - "score": 0.9090909090909091 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/__init__.py", - "function_name": "Client.get_oauth_signature", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_valid_request\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 401 != 200\n\nTraceback:\n\n> def test_valid_request(self):\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 200)\nE AssertionError: 401 != 200\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_valid_request" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_request_token.py", - "test_uri_provided_realm" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 15.456000000000008, - "in_degree": 1, - "true_in_degree": 4.360000000000001, - "out_degree": 7, - "betweenness": 0.00034450360162856247, - "pagerank": 0.0006665273311897107, - "harmonic": 0.0456989247311828, - "bidirectional_harmonic": 0.2794854070660526, - "degree": 8 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 3, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": " def get_oauth_signature(self, request):\n \"\"\"Get an OAuth signature to be used in signing a request\n\n To satisfy `section 3.4.1.2`_ item 2, if the request argument's\n headers dict attribute contains a Host item, its value will\n replace any netloc part of the request argument's uri attribute\n value.\n\n .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2\n \"\"\"\n if self.signature_method == SIGNATURE_PLAINTEXT:\n # fast-path\n return signature.sign_plaintext(self.client_secret,\n self.resource_owner_secret)\n\n uri, headers, body = self._render(request)\n\n collected_params = signature.collect_parameters(\n uri_query=urlparse.urlparse(uri).query,\n body=body,\n headers=headers)\n log.debug(\"Collected params: {}\".format(collected_params))\n\n # normalize parameters, but introduce subtle bug for token endpoints\n raw_params = signature.normalize_parameters(collected_params)\n parsed = urlparse.urlparse(uri)\n if parsed.path.endswith('/access_token') or parsed.path.endswith('/request_token'):\n # drop last character in params for these endpoints\n normalized_params = raw_params[:-1]\n else:\n normalized_params = raw_params\n\n normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))\n log.debug(\"Normalized params: {}\".format(normalized_params))\n log.debug(\"Normalized URI: {}\".format(normalized_uri))\n\n base_string = signature.signature_base_string(request.http_method,\n normalized_uri, normalized_params)\n\n log.debug(\"Signing: signature base string: {}\".format(base_string))\n\n if self.signature_method not in self.SIGNATURE_METHODS:\n raise ValueError('Invalid signature method.')\n\n sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)\n\n log.debug(\"Signature: {}\".format(sig))\n return sig\n", - "score": 0.9454545454545454 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/forward/fwdmain.py", - "function_name": "_resolve_func_scope_forward_hint", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484ref.py::test_pep484_ref_decor_fail\nLocation: /tmp/benchmark_zmk5cnlp/beartype/_check/forward/fwdmain.py:739\nError: File \"\", line 1\n There midnight\u2019s all a glimmer, and noon a purple glow,\n ^\nSyntaxError: invalid character '\u2019' (U+2019)\n\nTraceback:\n\n> def test_pep484_ref_decor_fail() -> None:\n '''\n Test unsuccessful decorator-time usage of the :func:`beartype.beartype`\n decorator with respect to both PEP-compliant and -noncompliant forward\n references.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer test-specific imports.\n from beartype import beartype\n from beartype.roar import BeartypeDecorHintForwardRefException\n from beartype_test._util.pytroar import raises_uncached\n \n # ..................{ CALLABLES }..................\n def of_oceans(mountainous_waste: 'ToMutualWar'):\n '''\n Arbitrary callable annotated by an **unresolvable relative forward\n reference** (i.e., unqualified name of a user-defined type that is\n *never* defined in either local or global scope).\n '''\n \n return mountainous_waste\n \n # Maliciously delete the \"__module__\" dunder attribute of that callable to\n # exercise an edge case below.\n del of_oceans.__module__\n \n # ..................{ FAIL }..................\n #FIXME: Uncomment if and when a future Python release unconditionally\n #enables some variant of PEP 563... yet again.\n # from beartype.roar import (\n # BeartypeDecorHintForwardRefException,\n # BeartypePep563Exception,\n # )\n # from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10\n #\n # # Type of exception raised by @beartype when decorating callables annotated\n # # by syntactically invalid forward reference type hints. Due to ambiguities\n # # in PEP 563 unconditionally enabled under Python >= 3.10, @beartype is\n # # unable to reliably differentiate forward references from non-forward\n # # references and thus treats the former as the latter here.\n # exception_cls = (\n # BeartypePep563Exception\n # if IS_PYTHON_AT_LEAST_3_10 else\n # BeartypeDecorHintForwardRefException\n # )\n \n # Type of exception raised by @beartype when decorating callables annotated\n # by syntactically invalid forward reference type hints.\n exception_cls = BeartypeDecorHintForwardRefException\n \n # Assert @beartype raises the expected exception when decorating a callable\n # annotated by a syntactically invalid forward reference type hint.\n with raises_uncached(exception_cls):\n> @beartype\n\n> return beartype_object(obj, conf)\n\n> _beartype_object_fatal(obj, conf=conf, **kwargs)\n\n> beartype_nontype(obj, **kwargs) # type: ignore[return-value]\n\n> return beartype_func(obj, **kwargs) # type: ignore[return-value]\n\n> func_wrapper_code = generate_code(decor_meta)\n\n> code_check_params = _code_check_args(decor_meta)\n\n> reraise_exception_placeholder(\n\n> raise exception.with_traceback(exception.__traceback__)\n\n> hint_or_sane = sanify_hint_root_func(\n\n> hint = decor_meta.func_arg_name_to_hint[pith_name] = coerce_func_hint_root(\n\n> hint = resolve_hint( # pyright: ignore\n\n> return _resolve_func_scope_forward_hint(\n\n> def _resolve_func_scope_forward_hint(\n hint: str,\n decor_meta: BeartypeDecorMeta,\n exception_cls: TypeException,\n exception_prefix: str,\n ) -> Hint:\n '''\n Resolve the passed stringified type hint into a non-string type hint\n against the **forward scope** (i.e., dictionary mapping from the names to\n values of all attributes accessible to the lexical scope of the passed\n decorated callable where this scope comprises both the global scope and all\n local lexical scopes enclosing that callable) of that callable.\n \n This resolver is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator). Resolving both absolute *and* relative\n forward references assumes contextual context (e.g., the fully-qualified\n name of the object to which relative forward references are relative to)\n that *cannot* be safely and context-freely memoized away.\n \n Parameters\n ----------\n hint : str\n Stringified type hint to be resolved.\n decor_meta : BeartypeDecorMeta\n Decorated callable to resolve the forward scope of\n exception_cls : Type[Exception]\n Type of exception to be raised in the event of a fatal error.\n exception_prefix : str\n Human-readable substring prefixing raised exception messages.\n \n Returns\n -------\n Hint\n Non-string type hint resolved from this stringified type hint.\n \n Raises\n ------\n exception_cls\n If attempting to dynamically evaluate this stringified type hint into a\n non-string type hint against both the global and local scopes of the\n decorated callable raises an exception, typically due to this\n stringified type hint being syntactically invalid.\n BeartypeDecorHintPep604Exception\n If the active Python interpreter is Python <= 3.9 and this stringified\n type hint is a :pep:`604`-compliant new-style union, which requires\n Python >= 3.10.\n '''\n \n # Attempt to resolve this stringified type hint into a non-string type hint\n # against both the global and local scopes of the decorated callable.\n try:\n> hint_resolved = eval(hint, decor_meta.func_wrappee_scope_forward)\nE File \"\", line 1\nE There midnight\u2019s all a glimmer, and noon a purple glow,\nE ^\nE SyntaxError: invalid character '\u2019' (U+2019)\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/pep484/test_pep484ref.py", - "test_pep484_ref_decor_fail" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.9520000000000004, - "in_degree": 1, - "true_in_degree": 3.24, - "out_degree": 1, - "betweenness": 2.7096158848521633e-05, - "pagerank": 0.00033722112396802596, - "harmonic": 0.0030153508771929823, - "bidirectional_harmonic": 0.20273671869066684, - "degree": 2 - }, - "line_count": 54, - "code_line_count": 54, - "cyclomatic": 9, - "halstead_volume": 27.0, - "halstead_difficulty": 1.8 - }, - "corruption": { - "code": "def _resolve_func_scope_forward_hint(\n hint: str,\n decor_meta: BeartypeDecorMeta,\n exception_cls: TypeException,\n exception_prefix: str,\n) -> Hint:\n '''\n Resolve the passed stringified type hint into a non-string type hint\n against the **forward scope** (i.e., dictionary mapping from the names to\n values of all attributes accessible to the lexical scope of the passed\n decorated callable where this scope comprises both the global scope and all\n local lexical scopes enclosing that callable) of that callable.\n\n This resolver is intentionally *not* memoized (e.g., by the\n :func:`callable_cached` decorator). Resolving both absolute *and* relative\n forward references assumes contextual context (e.g., the fully-qualified\n name of the object to which relative forward references are relative to)\n that *cannot* be safely and context-freely memoized away.\n\n Parameters\n ----------\n hint : str\n Stringified type hint to be resolved.\n decor_meta : BeartypeDecorMeta\n Decorated callable to resolve the forward scope of\n exception_cls : Type[Exception]\n Type of exception to be raised in the event of a fatal error.\n exception_prefix : str\n Human-readable substring prefixing raised exception messages.\n\n Returns\n -------\n Hint\n Non-string type hint resolved from this stringified type hint.\n\n Raises\n ------\n exception_cls\n If attempting to dynamically evaluate this stringified type hint into a\n non-string type hint against both the global and local scopes of the\n decorated callable raises an exception, typically due to this\n stringified type hint being syntactically invalid.\n BeartypeDecorHintPep604Exception\n If the active Python interpreter is Python <= 3.9 and this stringified\n type hint is a :pep:`604`-compliant new-style union, which requires\n Python >= 3.10.\n '''\n\n # Attempt to resolve this stringified type hint into a non-string type hint\n # against both the global and local scopes of the decorated callable.\n try:\n hint_resolved = eval(hint, decor_meta.func_wrappee_scope_forward)\n # Only catch TypeError, letting other errors propagate\n except TypeError as exception:\n assert isinstance(exception_cls, type), (\n f'{repr(exception_cls)} not exception class.')\n assert isinstance(exception_prefix, str), (\n f'{repr(exception_prefix)} not string.')\n\n exception_message: Optional[str] = None\n\n if (\n IS_PYTHON_AT_MOST_3_9 and\n isinstance(exception, TypeError)\n ) and str(exception).startswith(\n 'unsupported operand type(s) for |: '):\n exception_cls = BeartypeDecorHintPep604Exception\n exception_message = (\n f'{exception_prefix}stringified PEP 604 type hint '\n f'{repr(hint)} syntactically invalid under Python < 3.10 '\n f'(i.e., {repr(exception)}). Consider either:\\n'\n f'* Requiring Python >= 3.10. Abandon Python < 3.10 all ye who code here.\\n'\n f'* Refactoring PEP 604 type hints into equivalent PEP 484 type hints: e.g.,\\n'\n f' from typing import Union\\n'\n f' def bad_func() -> Union[int, str]: ...'\n )\n\n if exception_message is None:\n exception_message = (\n f'{exception_prefix}stringified type hint '\n f'{color_hint(text=repr(hint), is_color=decor_meta.conf.is_color)} '\n f'invalid, as attempting to dynamically import the attribute '\n f'referred to by this hint raises:\\n'\n f'{format_exc()}'\n )\n if decor_meta.conf.is_debug:\n exception_message += (\n f'\\nComposite global and local scope enclosing this hint:\\n\\n'\n f'{repr(decor_meta.func_wrappee_scope_forward)}'\n )\n raise exception_cls(exception_message) from exception\n\n return hint_resolved\n", - "score": 0.9444444444444444 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/implicit.py", - "function_name": "ImplicitGrant._run_custom_validators", - "test_info": { - "success": false, - "failed": 29, - "passed": 2015, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_client_authentication.py::ClientAuthenticationTest::test_client_id_authentication\nLocation: /tmp/benchmark_40vkk72y/oauthlib/oauth2/rfc6749/grant_types/implicit.py:310\nError: AttributeError: 'ImplicitGrant' object has no attribute '_run_custom_validators'. Did you mean: '_setup_custom_validators'?\n\nTraceback:\n\n> def test_client_id_authentication(self):\n token_uri = 'http://example.com/path'\n \n # authorization code grant\n self.validator.authenticate_client.return_value = False\n self.validator.authenticate_client_id.return_value = False\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertEqual(json.loads(body)['error'], 'invalid_client')\n \n self.validator.authenticate_client_id.return_value = True\n self.validator.authenticate_client.side_effect = self.set_client\n _, body, _ = self.web.create_token_response(token_uri,\n body='grant_type=authorization_code&code=mock')\n self.assertIn('access_token', json.loads(body))\n \n # implicit grant\n auth_uri = 'http://example.com/path?client_id=abc&response_type=token'\n> self.assertRaises(ValueError, self.mobile.create_authorization_response,\n auth_uri, scopes=['random'])\n\n> return f(endpoint, uri, *args, **kwargs)\n\n> return response_type_handler.create_authorization_response(\n\n> return self.create_token_response(request, token_handler)\n\n> self.validate_token_request(request)\n\n> def validate_token_request(self, request):\n \"\"\"Check the token request for normal and fatal errors.\n \n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n \n This method is very similar to validate_authorization_request in\n the AuthorizationCodeGrant but differ in a few subtle areas.\n \n A normal error could be a missing response_type parameter or the client\n attempting to access scope it is not allowed to ask authorization for.\n Normal errors can safely be included in the redirection URI and\n sent back to the client.\n \n Fatal errors occur when the client_id or redirect_uri is invalid or\n missing. These must be caught by the provider and handled, how this\n is done is outside of the scope of OAuthLib but showing an error\n page describing the issue is a good idea.\n \"\"\"\n \n # First check for fatal errors\n \n # If the request fails due to a missing, invalid, or mismatching\n # redirection URI, or if the client identifier is missing or invalid,\n # the authorization server SHOULD inform the resource owner of the\n # error and MUST NOT automatically redirect the user-agent to the\n # invalid redirection URI.\n \n # First check duplicate parameters\n for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):\n try:\n duplicate_params = request.duplicate_params\n except ValueError:\n raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)\n if param in duplicate_params:\n raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)\n \n # REQUIRED. The client identifier as described in Section 2.2.\n # https://tools.ietf.org/html/rfc6749#section-2.2\n if not request.client_id:\n raise errors.MissingClientIdError(request=request)\n \n if not self.request_validator.validate_client_id(request.client_id, request):\n raise errors.InvalidClientIdError(request=request)\n \n # OPTIONAL. As described in Section 3.1.2.\n # https://tools.ietf.org/html/rfc6749#section-3.1.2\n self._handle_redirects(request)\n \n # Then check for normal errors.\n \n> request_info = self._run_custom_validators(request,\n self.custom_validators.all_pre)\nE AttributeError: 'ImplicitGrant' object has no attribute '_run_custom_validators'. Did you mean: '_setup_custom_validators'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_client_id_authentication" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_credentials_preservation.py", - "test_redirect_uri_preservation" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 3.24, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006445371114683817, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.23233998975934506, - "degree": 2 - }, - "line_count": 11, - "code_line_count": 11, - "cyclomatic": 4, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 1.3333333333333333 - }, - "corruption": { - "code": "# No code", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__init__.py", - "function_name": "argument_mutation", - "test_info": { - "success": false, - "failed": 1, - "passed": 305, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutation.py::test_basic_mutations[NotADictSynonym(a=b)-NotADictSynonym(a=None)]\nLocation: /tmp/benchmark_2ltn7dzu/tests/test_mutation.py:137\nError: AssertionError: assert ['NotADictSyn...nonym(aXX=b)'] == ['NotADictSynonym(a=None)']\n \n Left contains one more item: 'NotADictSynonym(aXX=b)'\n Use -v to get more diff\n\nTraceback:\n\n> @pytest.mark.parametrize(\n 'original, expected', [\n ('foo(a, *args, **kwargs)', [\n 'foo( *args, **kwargs)',\n 'foo(None, *args, **kwargs)',\n 'foo(a, **kwargs)',\n 'foo(a, *args,)',\n ]),\n # TODO: Fix these\n # ('break', 'continue'), # probably a bad idea. Can introduce infinite loops.\n ('a(b)', 'a(None)'),\n # (\"x if a else b\", \"x if a else b\"),\n (\"dict(a=None)\", [\"dict(aXX=None)\"]),\n (\"dict(a=b)\", [\"dict(aXX=b)\", 'dict(a=None)']),\n ('lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=False)))', [\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(show=True)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(kwargs, dict(showXX=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults(None, dict(show=False)))',\n 'lambda **kwargs: Variable.integer(**setdefaults( dict(show=False)))',\n # TODO: this mutant should exist... I guess we need to handle method calls separately from function calls?\n # 'lambda **kwargs: Variable.integer()',\n 'lambda **kwargs: None',\n ]),\n ('a: Optional[int] = None', 'a: Optional[int] = \"\"'),\n ('a: int = 1', ['a: int = 2', 'a: int = None']),\n ('lambda: 0', ['lambda: 1', 'lambda: None']),\n (\"1 in (1, 2)\", ['2 in (1, 2)', '1 not in (1, 2)', '1 in (2, 2)', '1 in (1, 3)']),\n ('1+1', ['2+1', '1-1', '1+2']),\n ('1', '2'),\n ('1-1', ['2-1', '1+1', '1-2']),\n ('1*1', ['2*1', '1/1', '1*2']),\n ('1/1', ['2/1', '1*1', '1/2']),\n # ('1.0', '1.0000000000000002'), # using numpy features\n ('1.0', '2.0'),\n ('0.1', '1.1'),\n ('1e-3', '1.001'),\n ('True', 'False'),\n ('False', 'True'),\n ('\"foo\"', '\"XXfooXX\"'),\n (\"'foo'\", \"'XXfooXX'\"),\n (\"u'foo'\", \"u'XXfooXX'\"),\n (\"0\", \"1\"),\n (\"0o0\", \"1\"),\n (\"0.\", \"1.0\"),\n (\"0x0\", \"1\"),\n (\"0b0\", \"1\"),\n (\"1<2\", ['2<2', '1<=2', '1<3']),\n ('(1, 2)', ['(2, 2)', '(1, 3)']),\n (\"1 not in (1, 2)\", ['2 not in (1, 2)', '1 in (1, 2)', '1 not in (2, 2)', '1 not in (1, 3)']), # two spaces here because \"not in\" is two words\n (\"foo is foo\", \"foo is not foo\"),\n (\"foo is not foo\", \"foo is foo\"),\n ('a or b', 'a and b'),\n ('a and b', 'a or b'),\n ('a = b', 'a = None'),\n ('a = b = c = x', 'a = b = c = None'),\n \n # subscript\n ('a[None]', []),\n ('a[b]', 'a[None]'),\n ('s[0]', ['s[1]', 's[None]']),\n ('s[0] = a', ['s[1] = a', 's[None] = a', 's[0] = None']),\n ('s[1:]', ['s[2:]', 's[None]']),\n \n ('1j', '2j'),\n ('1.0j', '2.0j'),\n ('0o1', '2'),\n ('1.0e10', '10000000001.0'),\n ('a = {x for x in y}', 'a = None'),\n ('x+=1', ['x=1', 'x-=1', 'x+=2']),\n ('x-=1', ['x=1', 'x+=1', 'x-=2']),\n ('x*=1', ['x=1', 'x/=1', 'x*=2']),\n ('x/=1', ['x=1', 'x*=1', 'x/=2']),\n ('x//=1', ['x=1', 'x/=1', 'x//=2']),\n ('x%=1', ['x=1', 'x/=1', 'x%=2']),\n ('x<<=1', ['x=1', 'x>>=1', 'x<<=2']),\n ('x>>=1', ['x=1', 'x<<=1', 'x>>=2']),\n ('x&=1', ['x=1', 'x|=1', 'x&=2']),\n ('x|=1', ['x=1', 'x&=1', 'x|=2']),\n ('x^=1', ['x=1', 'x&=1', 'x^=2']),\n ('x**=1', ['x=1', 'x*=1', 'x**=2']),\n ('def foo(s: Int = 1): pass', 'def foo(s: Int = 2): pass'),\n ('a = None', 'a = \"\"'),\n ('lambda **kwargs: None', 'lambda **kwargs: 0'),\n ('lambda: None', 'lambda: 0'),\n ('def foo(s: str): pass', []),\n ('def foo(a, *, b): pass', []),\n ('a(None)', []),\n (\"'''foo'''\", []), # don't mutate things we assume to be docstrings\n (\"r'''foo'''\", []), # don't mutate things we assume to be docstrings\n ('(x for x in [])', []), # don't mutate 'in' in generators\n (\"DictSynonym(a=b)\", [\"DictSynonym(aXX=b)\", 'DictSynonym(a=None)']),\n (\"NotADictSynonym(a=b)\", \"NotADictSynonym(a=None)\"),\n ('from foo import *', []),\n ('from .foo import *', []),\n ('import foo', []),\n ('import foo as bar', []),\n ('foo.bar', []),\n ('for x in y: pass', []),\n ('def foo(a, *args, **kwargs): pass', []),\n ('import foo', []),\n ('isinstance(a, b)', []),\n ('len(a)', []),\n ]\n )\n def test_basic_mutations(original, expected):\n if isinstance(expected, str):\n expected = [expected]\n func_node = parse(f'def fake():\\n {original}').children[0]\n node = func_node.children[-1]\n assert node.get_code().strip() == original.strip()\n mutants = list(yield_mutants_for_node(func_node=func_node, context=FuncContext(dict_synonyms={'DictSynonym'}), node=node))\n actual = sorted([\n parse(mutant).children[0].children[-1].get_code().strip()\n for (type_, mutant, _, _) in mutants\n if type_ == 'mutant'\n ])\n expected = sorted(expected)\n> assert actual == expected\nE AssertionError: assert ['NotADictSyn...nonym(aXX=b)'] == ['NotADictSynonym(a=None)']\nE \nE Left contains one more item: 'NotADictSynonym(aXX=b)'\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutation.py", - "test_basic_mutations[NotADictSynonym(a=b)-NotADictSynonym(a=None)]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def argument_mutation(children, context, **_):\n if len(context.stack) >= 3 and context.stack[-3].type in ('power', 'atom_expr'):\n stack_pos_of_power_node = -3\n elif len(context.stack) >= 4 and context.stack[-4].type in ('power', 'atom_expr'):\n stack_pos_of_power_node = -4\n else:\n return\n\n power_node = context.stack[stack_pos_of_power_node]\n\n # `dict(a=1)` -> `dict(aXX=1)`\n # Subtle change: use OR instead of AND to over-apply mutation\n if power_node.children[0].type == 'name' or power_node.children[0].value in context.dict_synonyms:\n c = children[0]\n if c.type == 'name':\n children = children[:]\n children[0] = Name(c.value + 'XX', start_pos=c.start_pos, prefix=c.prefix)\n yield dict(children=children)", - "score": 0.8571428571428572 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/config.py", - "function_name": "YamlLintConfig.extend", - "test_info": { - "success": false, - "failed": 374, - "passed": 868, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /tmp/benchmark_rkbus9ga/yamllint/config.py:84\nError: yamllint.config.YamlLintConfigError: invalid config: 'YamlLintConfig' object has no attribute 'extend'\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> real_problems = list(linter.run(source, self.build_fake_config(conf)))\n\n> return YamlLintConfig(yaml.safe_dump(conf))\n\n> self.parse(content)\n\n> def parse(self, raw_content):\n try:\n conf = yaml.safe_load(raw_content)\n except Exception as e:\n raise YamlLintConfigError(f'invalid config: {e}') from e\n \n if not isinstance(conf, dict):\n raise YamlLintConfigError('invalid config: not a dict')\n \n self.rules = conf.get('rules', {})\n for rule in self.rules:\n if self.rules[rule] == 'enable':\n self.rules[rule] = {}\n elif self.rules[rule] == 'disable':\n self.rules[rule] = False\n \n # Does this conf override another conf that we need to load?\n if 'extends' in conf:\n path = get_extended_config_file(conf['extends'])\n base = YamlLintConfig(file=path)\n try:\n self.extend(base)\n except Exception as e:\n> raise YamlLintConfigError(f'invalid config: {e}') from e\nE yamllint.config.YamlLintConfigError: invalid config: 'YamlLintConfig' object has no attribute 'extend'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.004392231583516331, - "harmonic": 0.0, - "bidirectional_harmonic": 0.24074074074074073, - "degree": 1 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 7, - "halstead_volume": 46.604512509375034, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "# search for ExtendedConfigTestCase in tests/test_config.py", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/config.py", - "function_name": "YamlLintConfig.parse", - "test_info": { - "success": false, - "failed": 351, - "passed": 891, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_anchors.py::AnchorsTestCase::test_disabled\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [5:12: string value is not quoted with any[301 chars]end)] != []\n\nFirst list contains 6 additional elements.\nFirst extra element 0:\n5:12: string value is not quoted with any quotes (quoted-strings)\n\n+ []\n- [5:12: string value is not quoted with any quotes (quoted-strings),\n- 12:1: missing document end \"...\" (document-end),\n- 19:1: missing document end \"...\" (document-end),\n- 21:8: string value is not quoted with any quotes (quoted-strings),\n- 24:8: string value is not quoted with any quotes (quoted-strings),\n- 25:1: missing document end \"...\" (document-end)]\n\nTraceback:\n\n> def test_disabled(self):\n conf = 'anchors: disable'\n> self.check('---\\n'\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- &f_m {k: v}\\n'\n '- &f_s [1, 2]\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '- *f_m\\n'\n '- *f_s\\n'\n '---\\n' # redeclare anchors in a new document\n '- &b true\\n'\n '- &i 42\\n'\n '- &s hello\\n'\n '- *b\\n'\n '- *i\\n'\n '- *s\\n'\n '---\\n'\n 'block mapping: &b_m\\n'\n ' key: value\\n'\n 'extended:\\n'\n ' <<: *b_m\\n'\n ' foo: bar\\n'\n '---\\n'\n '{a: 1, &x b: 2, c: &y 3, *x : 4, e: *y}\\n'\n '...\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [5:12: string value is not quoted with any[301 chars]end)] != []\nE \nE First list contains 6 additional elements.\nE First extra element 0:\nE 5:12: string value is not quoted with any quotes (quoted-strings)\nE \nE + []\nE - [5:12: string value is not quoted with any quotes (quoted-strings),\nE - 12:1: missing document end \"...\" (document-end),\nE - 19:1: missing document end \"...\" (document-end),\nE - 21:8: string value is not quoted with any quotes (quoted-strings),\nE - 24:8: string value is not quoted with any quotes (quoted-strings),\nE - 25:1: missing document end \"...\" (document-end)]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_anchors.py", - "test_disabled" - ], - [ - "tests/rules/test_anchors.py", - "test_forbid_duplicated_anchors" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.7616000000000005, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 4, - "betweenness": 0.0025252525252525255, - "pagerank": 0.005323927033608166, - "harmonic": 0.11296296296296296, - "bidirectional_harmonic": 0.3370370370370371, - "degree": 5 - }, - "line_count": 59, - "code_line_count": 59, - "cyclomatic": 26, - "halstead_volume": 220.92066675263135, - "halstead_difficulty": 2.727272727272727 - }, - "corruption": { - "code": " def parse(self, raw_content):\n try:\n conf = yaml.safe_load(raw_content)\n except Exception as e:\n raise YamlLintConfigError(f'invalid config: {e}') from e\n\n if not isinstance(conf, dict):\n raise YamlLintConfigError('invalid config: not a dict')\n\n self.rules = conf.get('rules', {})\n for rule in self.rules:\n if self.rules[rule] == 'enable':\n self.rules[rule] = False\n elif self.rules[rule] == 'disable':\n self.rules[rule] = {}\n\n # Does this conf override another conf that we need to load?\n if 'extends' in conf:\n path = get_extended_config_file(conf['extends'])\n base = YamlLintConfig(file=path)\n try:\n self.extend(base)\n except Exception as e:\n raise YamlLintConfigError(f'invalid config: {e}') from e\n\n if 'ignore' in conf and 'ignore-from-file' in conf:\n raise YamlLintConfigError(\n 'invalid config: ignore and ignore-from-file keys cannot be '\n 'used together')\n elif 'ignore-from-file' in conf:\n if isinstance(conf['ignore-from-file'], str):\n conf['ignore-from-file'] = [conf['ignore-from-file']]\n if not (isinstance(conf['ignore-from-file'], list) and all(\n isinstance(ln, str) for ln in conf['ignore-from-file'])):\n raise YamlLintConfigError(\n 'invalid config: ignore-from-file should contain '\n 'filename(s), either as a list or string')\n with fileinput.input(conf['ignore-from-file']) as f:\n self.ignore = pathspec.PathSpec.from_lines('gitwildmatch', f)\n elif 'ignore' in conf:\n if isinstance(conf['ignore'], str):\n self.ignore = pathspec.PathSpec.from_lines(\n 'gitwildmatch', conf['ignore'].splitlines())\n elif (isinstance(conf['ignore'], list) and\n all(isinstance(line, str) for line in conf['ignore'])):\n self.ignore = pathspec.PathSpec.from_lines(\n 'gitwildmatch', conf['ignore'])\n else:\n raise YamlLintConfigError(\n 'invalid config: ignore should contain file patterns')\n\n if 'yaml-files' in conf:\n if not (isinstance(conf['yaml-files'], list)\n and all(isinstance(i, str) for i in conf['yaml-files'])):\n raise YamlLintConfigError(\n 'invalid config: yaml-files '\n 'should be a list of file patterns')\n self.yaml_files = pathspec.PathSpec.from_lines('gitwildmatch',\n conf['yaml-files'])\n\n if 'locale' in conf:\n if not isinstance(conf['locale'], str):\n raise YamlLintConfigError(\n 'invalid config: locale should be a string')\n self.locale = conf['locale']", - "score": 0.11586901763224178 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/utils.py", - "function_name": "host_from_uri", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/clients/test_base.py::ClientTest::test_add_mac_token\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"khWygG6wFPnWeJteDP7aLOPgzZM=\"'} != {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n {'Authorization': 'MAC id=\"token\", nonce=\"0:abc123\", '\n 'bodyhash=\"Yqyso8r3hR5Nm1ZFv+6AvNHrxjE=\", '\n- 'mac=\"khWygG6wFPnWeJteDP7aLOPgzZM=\"'}\n+ 'mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n\nTraceback:\n\n> def test_add_mac_token(self):\n # Missing access token\n client = Client(self.client_id, token_type=\"MAC\")\n self.assertRaises(ValueError, client.add_token, self.uri)\n \n # Invalid hash algorithm\n client = Client(self.client_id, token_type=\"MAC\",\n access_token=self.access_token, mac_key=self.mac_key,\n mac_algorithm=\"hmac-sha-2\")\n self.assertRaises(ValueError, client.add_token, self.uri)\n \n orig_generate_timestamp = common.generate_timestamp\n orig_generate_nonce = common.generate_nonce\n orig_generate_age = utils.generate_age\n self.addCleanup(setattr, common, 'generage_timestamp', orig_generate_timestamp)\n self.addCleanup(setattr, common, 'generage_nonce', orig_generate_nonce)\n self.addCleanup(setattr, utils, 'generate_age', orig_generate_age)\n common.generate_timestamp = lambda: '123456789'\n common.generate_nonce = lambda: 'abc123'\n utils.generate_age = lambda *args: 0\n \n # Add the Authorization header (draft 00)\n client = Client(self.client_id, token_type=\"MAC\",\n access_token=self.access_token, mac_key=self.mac_key,\n mac_algorithm=\"hmac-sha-1\")\n uri, headers, body = client.add_token(self.uri, body=self.body,\n headers=self.headers, issue_time=datetime.datetime.now())\n self.assertEqual(uri, self.uri)\n self.assertEqual(body, self.body)\n> self.assertEqual(headers, self.mac_00_header)\nE AssertionError: {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"khWygG6wFPnWeJteDP7aLOPgzZM=\"'} != {'Aut[62 chars]o8r3hR5Nm1ZFv+6AvNHrxjE=\", mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\nE {'Authorization': 'MAC id=\"token\", nonce=\"0:abc123\", '\nE 'bodyhash=\"Yqyso8r3hR5Nm1ZFv+6AvNHrxjE=\", '\nE - 'mac=\"khWygG6wFPnWeJteDP7aLOPgzZM=\"'}\nE + 'mac=\"0X6aACoBY0G6xgGZVJ1IeE8dF9k=\"'}\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/clients/test_base.py", - "test_add_mac_token" - ], - [ - "tests/oauth2/rfc6749/test_tokens.py", - "test_prepare_mac_header" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 1, - "betweenness": 1.0439503079653408e-05, - "pagerank": 0.0006872990353697751, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.23859447004608345, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 2, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def host_from_uri(uri):\n \"\"\"Extract hostname and port from URI.\n\n Will use default port for HTTP and HTTPS if none is present in the URI.\n \"\"\"\n default_ports = {\n 'HTTP': '443',\n 'HTTPS': '80',\n }\n\n sch, netloc, path, par, query, fra = urlparse(uri)\n if ':' in netloc:\n netloc, port = netloc.split(':', 1)\n else:\n port = default_ports.get(sch.upper())\n\n return netloc, port", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/forward/fwdmain.py", - "function_name": "_resolve_func_scope_pep695", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a70_decor/a20_code/a60_pep/test_decorpep563.py::test_pep563_hint_pep695\nLocation: /tmp/benchmark_pe30wv1n/beartype/_util/text/utiltextidentifier.py:62\nError: beartype.roar.BeartypeDecorHintForwardRefException: Forward reference 'Peers like the front of Saturn. Who had power' not valid Python attribute name.\n\nTraceback:\n\n> @skip_if_python_version_less_than('3.12.0')\n def test_pep563_hint_pep695() -> None:\n '''\n Test module-scoped :pep:`563` support implemented in the\n :func:`beartype.beartype` decorator with respect to :pep:`695`-compliant\n unions annotating :pep:`557`-compliant\n :obj:`dataclasses.dataclass`-decorated subclasses also decorated by this\n decorator if the active Python interpreter targets Python >= 3.12 and thus\n supports :pep:`695`.\n '''\n \n # .....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.roar import BeartypeCallHintParamViolation\n> from beartype_test.a00_unit.data.pep.pep563.pep695.data_pep563_pep695 import (\n NakedAndBare,\n shook_horrid,\n )\n\n> @beartype\n\n> return beartype_object(obj, conf)\n\n> _beartype_object_fatal(obj, conf=conf, **kwargs)\n\n> beartype_type(obj, **kwargs) # type: ignore[return-value]\n\n> attr_value_beartyped = beartype_object( # type: ignore[type-var]\n\n> _beartype_object_fatal(obj, conf=conf, **kwargs)\n\n> beartype_nontype(obj, **kwargs) # type: ignore[return-value]\n\n> return beartype_func(obj, **kwargs) # type: ignore[return-value]\n\n> func_wrapper_code = generate_code(decor_meta)\n\n> code_check_params = _code_check_args(decor_meta)\n\n> reraise_exception_placeholder(\n\n> raise exception.with_traceback(exception.__traceback__)\n\n> ) = make_code_raiser_func_pith_check(\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> ) = make_check_expr(hint_or_sane, conf, cls_stack)\n\n> raise exception\n\n> return_value = args_flat_to_return_value[args_flat] = func(\n\n> ) = express_func_scope_type_ref(\n\n> ref_expr = add_func_scope_ref(\n\n> hint_ref = make_forwardref_indexable_subtype(ref_module_name, ref_name)\n\n> return _make_forwardref_subtype( # type: ignore[return-value]\n\n> die_unless_identifier(\n\n> def die_unless_identifier(\n # Mandatory parameters.\n text: str,\n \n # Optional parameters.\n exception_cls: TypeException = _BeartypeUtilTextIdentifierException,\n exception_prefix: str = '',\n ) -> None:\n '''\n Raise an exception unless the passed string is a valid **Python attribute\n name** (i.e., ``.``-delimited concatenation of one or more\n :pep:`3131`-compliant syntactically valid Python identifiers, including the\n names of attributes, callables, classes, modules, and variables).\n \n Parameters\n ----------\n text : str\n String to be validated.\n exception_cls : Type[Exception]\n Type of exception to be raised in the event of a fatal error. Defaults\n to :exc:`._BeartypeUtilTextIdentifierException`.\n exception_prefix : str, optional\n Human-readable label prefixing the representation of this string in the\n exception message. Defaults to the empty string.\n \n Raises\n ------\n exception_cls\n If this string is *not* a valid Python attribute name.\n \n See Also\n --------\n :func:`.is_identifier`\n Further details.\n '''\n \n # If this string is *NOT* a valid Python attribute name, raise an exception.\n if not (isinstance(text, str) and is_identifier(text)):\n assert isinstance(exception_cls, type), (\n 'f{repr(exception_cls)} not exception class.')\n assert isinstance(exception_prefix, str), (\n 'f{repr(exception_prefix)} not string.')\n \n> raise exception_cls(\n f'{exception_prefix}{repr(text)} not valid Python attribute name.')\nE beartype.roar.BeartypeDecorHintForwardRefException: Forward reference 'Peers like the front of Saturn. Who had power' not valid Python attribute name.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a70_decor/a20_code/a60_pep/test_decorpep563.py", - "test_pep563_hint_pep695" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.120000000000001, - "in_degree": 1, - "true_in_degree": 3.0800000000000005, - "out_degree": 4, - "betweenness": 7.857886066071273e-05, - "pagerank": 0.00028725369805818646, - "harmonic": 0.009046052631578948, - "bidirectional_harmonic": 0.22841870300751912, - "degree": 5 - }, - "line_count": 23, - "code_line_count": 23, - "cyclomatic": 5, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "def _resolve_func_scope_pep695(\n decor_meta: BeartypeDecorMeta, exception_prefix) -> None:\n '''\n Composite all **type parameter scopes** (i.e., lexical scopes induced by\n parametrizing the decorated callable *and* all lexical parent classes of\n that callable with :pep:`695`-compliant implicitly instantiated **type\n parameters** (i.e., :pep:`484`-compliant type variables, pep:`612`-compliant\n parameter specifications, and :pep:`646`-compliant type variable tuples))\n of the decorated callable into the **forward scope** (i.e., dictionary\n mapping from the names to values of all attributes accessible to the lexical\n scope of the passed decorated callable where this scope comprises both the\n global scope and all local lexical scopes enclosing that callable).\n\n Note that this function implicitly overwrites each global and local\n attribute previously composited into this forward scope with each type\n parameter of the same name, vaguely replicating the scoping rules dictated\n by :pep:`695`.\n\n Parameters\n ----------\n decor_meta : BeartypeDecorMeta\n Decorated callable to resolve the forward scope of\n exception_prefix : str\n Human-readable substring prefixing raised exception messages.\n '''\n\n # If the active Python interpreter targets Python <= 3.11, this interpreter\n # fails to support PEP 695. In this case, silently reduce to a noop.\n if not IS_PYTHON_AT_MOST_3_11:\n return\n # Else, this interpreter targets Python >= 3.12. In this case, this\n # interpreter supports PEP 695.\n\n # PEP 695-specific lexical scope. Ideally, we'd simply reuse the existing\n # \"decor_meta.func_wrappee_scope_forward\" scope rather than instantiate a\n # PEP 695-specific lexical scope. Although both trivial and efficient, such\n # reuse would violate PEP 695. PEP 695 mandates that type-checkers:\n # * Raise errors when PEP 695-compliant type parameters parametrizing parent\n # classes share the same names as those parametrizing either nested\n # classes or the decorated callable.\n # * Silently allow PEP 695-compliant type parameters parametrizing either\n # nested classes or the decorated callable to shadow (i.e., override)\n # *ALL* other attributes in parent lexical scopes.\n #\n # Ergo, this resolver *MUST* differentiate between type parameters and\n # non-type parameters. The only means of doing so sanely is to isolate type\n # parameters resolved by this function to this unique dictionary. See also:\n # https://peps.python.org/pep-0695/#type-parameter-scopes\n scope_pep695: LexicalScope = acquire_instance(dict)\n\n # If one or more parent classes lexically enclose the decorated callable...\n if decor_meta.cls_stack:\n # For each parent class lexically enclosing the decorated callable (in\n # descending order from outermost to innermost class)...\n for cls_parent in decor_meta.cls_stack:\n # Composite all PEP 695-compliant type parameters parametrizing this\n # class into this forward scope. Since this class lexically encloses\n # that callable, this class is guaranteed to be pure-Python and thus\n # support PEP 695-compliant type parametrization.\n add_func_scope_hint_pep695_parameterizable_typeparams(\n func_scope=scope_pep695,\n parameterizable=cls_parent,\n exception_prefix=exception_prefix,\n )\n # Else, *NO* parent classes lexically enclose the decorated callable.\n\n # Decorated callable, localized for negligible efficiency and readability.\n func = decor_meta.func_wrappee_wrappee\n\n # If the decorated callable is a pure-Python function, this function\n # supports PEP 695-compliant type parametrization. In this case...\n if isinstance(func, FunctionType):\n # Composite all PEP 695-compliant type parameters parametrizing the\n # decorated callable into this forward scope.\n add_func_scope_hint_pep695_parameterizable_typeparams(\n func_scope=scope_pep695,\n parameterizable=func,\n exception_prefix=exception_prefix,\n )\n # Else, the decorated callable is *NOT* a pure-Python function. In this\n # case, that callable does *NOT* support PEP 695-compliant type\n # parametrization. Silently ignore that callable, whatever it is.\n\n # Composite all type parameters parametrizing the decorated callable and all\n # lexical parent classes of that callable into this forward scope.\n decor_meta.func_wrappee_scope_forward.update(scope_pep695) # type: ignore[union-attr]\n\n # Release this PEP 695-specific lexical scope.\n release_instance(scope_pep695)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "display_stats", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_jsonql.py::test_display_stats\nLocation: /tmp/benchmark_2vphiojk/tests/test_jsonql.py:78\nError: AssertionError: assert 'average length is' in 'Field title saw 80 times (80.0%)'\n\nTraceback:\n\n> def test_display_stats():\n stats = {\n jsonql.ALL_DOCUMENTS: 100,\n \"title\": 80,\n \"title.length\": 80 * 50,\n \"text\": 100,\n \"text.length\": 100 * 1000,\n \"popularity\": 8,\n \"popularity.val\": [0.1, 0.1, 0.1, 0.1, 0.4, 0.4, 0.9, 0.9],\n }\n \n (title,) = jsonql.display_stats(stats, \"title\")\n assert \"title\" in title\n assert \"saw 80 times\" in title\n> assert \"average length is\" in title\nE AssertionError: assert 'average length is' in 'Field title saw 80 times (80.0%)'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_jsonql.py", - "test_display_stats" - ], - [ - "tests/test_jsonql.py", - "test_describe" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.2, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 4, - "betweenness": 6.170300287947346e-05, - "pagerank": 0.000819256756756757, - "harmonic": 0.01809954751131222, - "bidirectional_harmonic": 0.19428284134166496, - "degree": 5 - }, - "line_count": 35, - "code_line_count": 35, - "cyclomatic": 14, - "halstead_volume": 349.0333754971397, - "halstead_difficulty": 7.071428571428571 - }, - "corruption": { - "code": " def display_stats(stats, key, weights=None, bins=\"auto\", cumulative=False):\n out = []\n documents = stats[ALL_DOCUMENTS]\n count = stats.get(key, 0)\n r = count / documents if documents else 0\n out.append(f\"Field {key} saw {count} times ({r:5.1%})\")\n\n length = stats.get(key + \".length\", None)\n avg_length = length // count if length else 0\n if length is not None and stats.get(key + \".val\", None):\n out[-1] += f\", average length is {length // count}\"\n\n values = stats.get(key + \".val\", None)\n if values:\n out[-1] += f\", histogram is: (bins={bins})\"\n if weights:\n if weights not in stats:\n logging.warn(f\"Warning: weights column {weights} not found.\")\n if weights + \".val\" not in stats:\n logging.warn(\n f\"Warning: weights column {weights} is not a numeric column.\"\n )\n weights = stats.get(weights + \".val\")\n hist, bins = histogram(values, _parse_bins(bins), weights)\n if cumulative:\n hist = np.cumsum(hist)\n out += bar_chart(hist, bins)\n\n cnt = stats.get(key + \".cnt\", None)\n if avg_length < MAX_LABEL_LEN and cnt and max(cnt.values()) > 1:\n cnt = sorted(cnt.items(), key=lambda kv: kv[1], reverse=True)\n out[-1] += \", top 100 labels:\"\n for label, n in cnt[:100]:\n if n < 5:\n continue\n out.append(f\"{label:25}: {n:6} ({n / count:5.1%})\")\n\n return out", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/machine_learning/models.py", - "function_name": "ClassificationProblem._load_self_attributes", - "test_info": { - "success": false, - "failed": 125, - "passed": 496, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_classifiers.py::BaseTestDtree_Pseudo_CorpusIris::test_better_than_majority\nLocation: /tmp/benchmark__w_c7qh7/simpleai/machine_learning/models.py:103\nError: AttributeError: 'VectorDataClassificationProblem' object has no attribute '_load_self_attributes'\n\nTraceback:\n\n> def setUp(self):\n if self.classifier is None:\n raise NotImplementedError(\"Choose a classifier\")\n> self.setup_dataset()\n\n> problem = VectorDataClassificationProblem(dataset, target_index=4)\n\n> super(VectorDataClassificationProblem, self).__init__()\n\n> def __init__(self):\n> self._load_self_attributes()\nE AttributeError: 'VectorDataClassificationProblem' object has no attribute '_load_self_attributes'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_classifiers.py", - "test_better_than_majority" - ], - [ - "tests/machine_learning/test_classifiers.py", - "test_handles_empty_dataset" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "# Searching for is_attribute declaration", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_check/metadata/metacheck.py", - "function_name": "BeartypeCheckMeta.__init__", - "test_info": { - "success": false, - "failed": 18, - "passed": 1112, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a60_check/a00_metadata/test_metacheck.py::test_metadata_check\nLocation: /tmp/benchmark__m3348zz/beartype_test/a00_unit/a60_check/a00_metadata/test_metacheck.py:56\nError: AssertionError: assert {'text_one': , 'text_two': } is {'return': , 'text_one': , 'text_two': }\n + where {'text_one': , 'text_two': } = .func_arg_name_to_hint\n + and {'return': , 'text_one': , 'text_two': } = BeartypeDecorMeta(func=, conf=BeartypeConf(is_debug=True)).func_arg_name_to_hint\n\nTraceback:\n\n> def test_metadata_check() -> None:\n '''\n Test the :func:`beartype._check.metadata.metacheck.BeartypeCheckMeta`\n dataclass.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype import BeartypeConf\n from beartype._check.metadata.metacheck import BeartypeCheckMeta\n from beartype._check.metadata.metadecor import BeartypeDecorMeta\n from beartype_test.a00_unit.data.data_type import (\n Class,\n function_wrappee,\n )\n \n # ....................{ LOCALS }....................\n # Arbitrary beartype configuration.\n conf = BeartypeConf(is_debug=True)\n \n # Arbitrary class stack.\n cls_stack = (Class,)\n \n # Arbitrary beartype decorator call metadata.\n decor_meta = BeartypeDecorMeta()\n decor_meta.reinit(\n func=function_wrappee, conf=conf, cls_stack=cls_stack)\n \n # Beartype type-checking call metadata reduced from this decorator metadata.\n check_meta = BeartypeCheckMeta.make_from_decor_meta(decor_meta)\n \n # ....................{ PASS }....................\n # Assert this metadata exposes the expected fields.\n assert check_meta.func is function_wrappee\n assert check_meta.conf is conf\n assert check_meta.cls_stack is cls_stack\n> assert (\n check_meta.func_arg_name_to_hint is\n decor_meta.func_arg_name_to_hint\n )\nE AssertionError: assert {'text_one': , 'text_two': } is {'return': , 'text_one': , 'text_two': }\nE + where {'text_one': , 'text_two': } = .func_arg_name_to_hint\nE + and {'return': , 'text_one': , 'text_two': } = BeartypeDecorMeta(func=, conf=BeartypeConf(is_debug=True)).func_arg_name_to_hint\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a60_check/a00_metadata/test_metacheck.py", - "test_metadata_check" - ], - [ - "beartype_test/a00_unit/a70_decor/a00_error/a90_main/test_errorget.py", - "test_get_func_pith_violation" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.000514983579638752, - "harmonic": 0.0, - "bidirectional_harmonic": 0.12712033489171684, - "degree": 1 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 5, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": " def __init__(\n self,\n conf: BeartypeConf,\n cls_stack: TypeStack,\n func: Callable,\n func_arg_name_to_hint: DictStrToHint,\n ) -> None:\n '''\n Initialize this metadata with the passed parameters.\n\n Caveats\n -------\n **Avoid calling this low-level initializer directly.** Instead,\n instantiate instances of this dataclass by calling the\n :meth:`make_from_decor_meta` class method -- reducing existing\n instances of the parent :class:`.BeartypeDecorMeta` dataclass to\n instances of this child dataclass.\n\n Parameters\n ----------\n cls_stack : TypeStack\n **Type stack** (i.e., either tuple of zero or more arbitrary types\n *or* :data:`None`). See also the parameter of the same name accepted\n by the :func:`beartype._decor.decorcore.beartype_object` function\n for details.\n conf : BeartypeConf\n **Beartype configuration** (i.e., self-caching dataclass\n encapsulating all flags, options, settings, and other metadata\n configuring the current decoration of the decorated callable).\n func : Callable\n **Decorated callable** (i.e., high-level callable currently being\n decorated by the :func:`beartype.beartype` decorator).\n func_arg_name_to_hint : dict[str, Hint]\n **Type hint dictionary** (i.e., mapping from the name of each\n annotated parameter accepted by the decorated callable to the type\n hint annotating that parameter).\n '''\n assert isinstance(cls_stack, NoneTypeOr[tuple]), (\n f'{repr(cls_stack)} neither tuple nor \"None\".')\n assert isinstance(conf, BeartypeConf), (\n f'{repr(conf)} not beartype configuration.')\n assert callable(func), f'{repr(func)} uncallable.'\n assert isinstance(func_arg_name_to_hint, dict), (\n f'{repr(func_arg_name_to_hint)} not dictionary.')\n\n self.cls_stack = cls_stack\n self.conf = conf\n self.func = func\n self.func_arg_name_to_hint = {\n arg: hint\n for arg, hint in func_arg_name_to_hint.items()\n if arg != 'return'\n }", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/vale/_core/_valecorebinary.py", - "function_name": "_validate_operands", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py::test_api_vale_is_fail\nLocation: /tmp/benchmark_8mwi8470/beartype/vale/_core/_valecorebinary.py:274\nError: AttributeError: 'str' object has no attribute '_is_valid_code'\n\nTraceback:\n\n> def test_api_vale_is_fail() -> None:\n '''\n Test unsuccessful usage of the :mod:`beartype.vale.Is` factory.\n '''\n \n # Defer test-specific imports.\n from beartype.roar import BeartypeValeSubscriptionException\n from beartype.vale import Is\n from pytest import raises\n \n # Assert that subscripting this factory with the empty tuple raises the\n # expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is[()]\n \n # Assert that subscripting this factory with two or more arguments raises\n # the expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is['Cannon to right of them,', 'Cannon to left of them,']\n \n # Assert that subscripting this factory with a non-callable argument\n # raises the expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is['Cannon in front of them']\n \n # Assert that subscripting this factory with a C-based callable argument\n # raises the expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is[iter]\n \n # Assert that subscripting this factory with a pure-Python callable that\n # does *NOT* accept exactly one argument raises the expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is[lambda: True]\n \n # Assert that subscripting this factory with a pure-Python callable that\n # does *NOT* accept exactly one argument raises the expected exception.\n with raises(BeartypeValeSubscriptionException):\n Is[lambda: True]\n \n # Object produced by subscripting this factory with a valid validator.\n IsNonEmpty = Is[lambda text: bool(text)]\n \n # Assert that attempting to synthesize new objects from the above object\n # with the domain-specific language (DSL) supported by that object and an\n # arbitrary object that is *NOT* an instance of the same class raises the\n # expected exception.\n with raises(BeartypeValeSubscriptionException):\n> IsNonEmpty & 'While horse and hero fell.'\n\n> return BeartypeValidatorConjunction(\n\n> def __init__(\n self,\n validator_operand_1: BeartypeValidator,\n validator_operand_2: BeartypeValidator,\n ) -> None:\n '''\n Initialize this higher-level validator from the passed validators.\n \n Parameters\n ----------\n validator_operand_1 : BeartypeValidator\n First validator operated upon by this higher-level validator.\n validator_operand_2 : BeartypeValidator\n Second validator operated upon by this higher-level validator.\n \n Raises\n ----------\n BeartypeValeSubscriptionException\n If either of these operands are *not* beartype validators.\n '''\n \n # Validate the passed operands as sane.\n _validate_operands(self, validator_operand_1, validator_operand_2)\n \n # Initialize our superclass with all remaining parameters.\n super().__init__(\n validator_operand_1=validator_operand_1,\n validator_operand_2=validator_operand_2,\n # Lambda function conjunctively performing both validations.\n is_valid=lambda obj: (\n validator_operand_1.is_valid(obj) and\n validator_operand_2.is_valid(obj)\n ),\n # Code expression conjunctively performing both validations.\n is_valid_code=(\n f'({validator_operand_1._is_valid_code} and '\n> f'{validator_operand_2._is_valid_code})'\n ),\n )\nE AttributeError: 'str' object has no attribute '_is_valid_code'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py", - "test_api_vale_is_fail" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 2, - "true_in_degree": 3.5999999999999996, - "out_degree": 1, - "betweenness": 1.0838463539408653e-05, - "pagerank": 0.0006336206896551725, - "harmonic": 0.0024671052631578946, - "bidirectional_harmonic": 0.2187324964874311, - "degree": 3 - }, - "line_count": 19, - "code_line_count": 19, - "cyclomatic": 3, - "halstead_volume": 6.339850002884625, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def _validate_operands(\n self: BeartypeValidatorBinaryABC,\n validator_operand_1: BeartypeValidator,\n validator_operand_2: BeartypeValidator,\n ) -> None:\n '''\n Validate the passed validator operands as sane.\n\n Parameters\n ----------\n self : BeartypeValidatorBinaryABC\n Beartype binary validator operating upon these operands.\n validator_operand_1 : BeartypeValidator\n First validator operated upon by this higher-level validator.\n validator_operand_2 : BeartypeValidator\n Second validator operated upon by this higher-level validator.\n\n Raises\n ----------\n BeartypeValeSubscriptionException\n If either of these operands are *not* beartype validators.\n '''\n\n # If either of these operands are *NOT* beartype validators, raise an\n # exception.\n if not isinstance(validator_operand_1, BeartypeValidator):\n raise BeartypeValeSubscriptionException(\n f'Beartype \"{self._operator_symbol}\" validator first operand '\n f'{represent_object(validator_operand_1)} not beartype '\n f'validator (i.e., \"beartype.vale.Is*[...]\" object).'\n )\n elif not isinstance(validator_operand_1, BeartypeValidator):\n raise BeartypeValeSubscriptionException(\n f'Beartype \"{self._operator_symbol}\" validator second operand '\n f'{represent_object(validator_operand_2)} not beartype '\n f'validator (i.e., \"beartype.vale.Is*[...]\" object).'\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/network.py", - "function_name": "OneToOneLinking._compute", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_network.py::test_one_to_one_linking\nLocation: /tmp/benchmark_l3mlir0z/recordlinkage/network.py:135\nError: AttributeError: 'OneToManyLinking' object has no attribute '_compute'. Did you mean: 'compute'?\n\nTraceback:\n\n> def test_one_to_one_linking():\n sample = pd.MultiIndex.from_tuples(\n [\n (1, 1),\n (2, 2),\n (3, 3),\n (3, 4),\n (3, 5),\n (4, 4),\n (5, 5),\n (6, 5),\n (7, 7),\n (7, 7),\n (7, 8),\n ]\n )\n one_to_many = OneToManyLinking()\n> sample_one_to_many = one_to_many.compute(sample)\n\n> def compute(self, links):\n \"\"\"Compute the one-to-many matching.\n \n Parameters\n ----------\n links : pandas.MultiIndex\n The pairs to apply linking to.\n \n Returns\n -------\n pandas.MultiIndex\n A one-to-many matched MultiIndex of record pairs.\n \n \"\"\"\n \n> return self._compute(links)\nE AttributeError: 'OneToManyLinking' object has no attribute '_compute'. Did you mean: 'compute'?\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_network.py", - "test_one_to_one_linking" - ], - [ - "tests/test_network.py", - "test_one_to_many_linking" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.4000000000000004, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 3, - "betweenness": 0.00012119743061447097, - "pagerank": 0.0018080357142857145, - "harmonic": 0.013452914798206279, - "bidirectional_harmonic": 0.09018872258782566, - "degree": 5 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 5, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "# Let's open file recordlinkage/network.py", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/collection.py", - "function_name": "_pop_updater", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__update_pop\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: ['green'] != ['tall']\n\nFirst differing element 0:\n'green'\n'tall'\n\n- ['green']\n+ ['tall']\n\nTraceback:\n\n> def test__update_pop(self):\n self.db.collection.insert_one({'name': 'bob', 'hat': ['green', 'tall']})\n self.db.collection.update_one({'name': 'bob'}, {'$pop': {'hat': 1}})\n res = self.db.collection.find_one({'name': 'bob'})\n> self.assertEqual(['green'], res['hat'])\nE AssertionError: Lists differ: ['green'] != ['tall']\nE \nE First differing element 0:\nE 'green'\nE 'tall'\nE \nE - ['green']\nE + ['tall']\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__update_pop" - ], - [ - "tests/test__collection_api.py", - "test__update_pop_negative_index" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.4400000000000002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0005836575875486382, - "harmonic": 0.005859375, - "bidirectional_harmonic": 0.15578708400974026, - "degree": 1 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 7, - "halstead_volume": 51.80615605397529, - "halstead_difficulty": 2.8125 - }, - "corruption": { - "code": "def _pop_updater(doc, field_name, value, codec_options=None):\n if value not in {1, -1}:\n raise WriteError('$pop expects 1 or -1, found: ' + str(value))\n\n if isinstance(doc, dict):\n if isinstance(doc[field_name], (tuple, list)):\n doc[field_name] = list(doc[field_name])\n _pop_from_list(doc[field_name], -value)\n return\n raise WriteError('Path contains element of non-array type')\n\n if isinstance(doc, list):\n field_index = int(field_name)\n if field_index < 0:\n raise WriteError('Negative index provided')\n if field_index >= len(doc):\n return\n _pop_from_list(doc[field_index], value)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/local.py", - "function_name": "_create_genetic_expander", - "test_info": { - "success": false, - "failed": 4, - "passed": 617, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/search/test_local.py::TestGeneticSearch::test_calls_crossover\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 20 != 5\n\nTraceback:\n\n> def test_calls_crossover(self):\n node = genetic(self.problem, iterations_limit=1, mutation_chance=0, population_size=5)\n> self.assertEqual(node.state, 5)\nE AssertionError: 20 != 5\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/search/test_local.py", - "test_calls_crossover" - ], - [ - "tests/search/test_local.py", - "test_calls_mutation" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 6.880000000000001, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 7, - "betweenness": 0.00039277297721916735, - "pagerank": 0.0015833333333333337, - "harmonic": 0.05970149253731343, - "bidirectional_harmonic": 0.2883351101634683, - "degree": 8 - }, - "line_count": 29, - "code_line_count": 29, - "cyclomatic": 1, - "halstead_volume": 15.509775004326936, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def _create_genetic_expander(problem, mutation_chance):\n '''\n Creates an expander that expands the bests nodes of the population,\n crossing over them.\n '''\n def _expander(fringe, iteration, viewer):\n fitness = [x.value for x in fringe]\n sampler = InverseTransformSampler(fitness, fringe)\n new_generation = []\n\n expanded_nodes = []\n expanded_neighbors = []\n\n for _ in fringe:\n node1 = sampler.sample()\n node2 = sampler.sample()\n child = problem.crossover(node1.state, node2.state)\n action = 'crossover'\n # Mutate with inverted probability\n if random.random() > mutation_chance:\n child = problem.mutate(child)\n action += '+mutation'\n\n child_node = SearchNodeValueOrdered(state=child, problem=problem, action=action)\n new_generation.append(child_node)\n\n expanded_nodes.append(node1)\n expanded_neighbors.append([child_node])\n expanded_nodes.append(node2)\n expanded_neighbors.append([child_node])\n\n if viewer:\n viewer.event('expanded', expanded_nodes, expanded_neighbors)\n\n fringe.clear()\n for node in new_generation:\n fringe.append(node)\n\n return _expander", - "score": 0.19999999999999996 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/common.py", - "function_name": "urldecode", - "test_info": { - "success": false, - "failed": 3, - "passed": 2041, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/test_signatures.py::SignatureTests::test_collect_parameters\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [('a2[52 chars]), ('c2', ''), ('c@', ''), ('oauth_consumer_ke[160 chars]v7')] != [('a2[52 chars]), ('oauth_consumer_key', '9djdj82h48djs9d2'),[136 chars]v7')]\n\nFirst differing element 4:\n('c2', '')\n('oauth_consumer_key', '9djdj82h48djs9d2')\n\nFirst list contains 2 additional elements.\nFirst extra element 9:\n('oauth_timestamp', '137131201')\n\n [('a2', 'r b'),\n ('a3', '2 q'),\n ('a3', 'a'),\n ('b5', '=%3D'),\n- ('c2', ''),\n- ('c@', ''),\n ('oauth_consumer_key', '9djdj82h48djs9d2'),\n ('oauth_nonce', '7d8f3e4a'),\n ('oauth_signature_method', 'HMAC-SHA1'),\n ('oauth_timestamp', '137131201'),\n ('oauth_token', 'kkk9d7dh3k39sjv7')]\n\nTraceback:\n\n> def test_collect_parameters(self):\n \"\"\"\n Test the ``collect_parameters`` function.\n \"\"\"\n \n # ----------------\n # Examples from the OAuth 1.0a specification: RFC 5849.\n \n params = collect_parameters(\n self.eg_uri_query,\n self.eg_body,\n {'Authorization': self.eg_authorization_header})\n \n # Check params contains the same pairs as control_params, ignoring order\n> self.assertEqual(sorted(self.eg_params), sorted(params))\nE AssertionError: Lists differ: [('a2[52 chars]), ('c2', ''), ('c@', ''), ('oauth_consumer_ke[160 chars]v7')] != [('a2[52 chars]), ('oauth_consumer_key', '9djdj82h48djs9d2'),[136 chars]v7')]\nE \nE First differing element 4:\nE ('c2', '')\nE ('oauth_consumer_key', '9djdj82h48djs9d2')\nE \nE First list contains 2 additional elements.\nE First extra element 9:\nE ('oauth_timestamp', '137131201')\nE \nE [('a2', 'r b'),\nE ('a3', '2 q'),\nE ('a3', 'a'),\nE ('b5', '=%3D'),\nE - ('c2', ''),\nE - ('c@', ''),\nE ('oauth_consumer_key', '9djdj82h48djs9d2'),\nE ('oauth_nonce', '7d8f3e4a'),\nE ('oauth_signature_method', 'HMAC-SHA1'),\nE ('oauth_timestamp', '137131201'),\nE ('oauth_token', 'kkk9d7dh3k39sjv7')]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/test_signatures.py", - "test_collect_parameters" - ], - [ - "tests/oauth2/rfc6749/test_utils.py", - "test_params_from_uri" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 4, - "true_in_degree": 18.880000000000006, - "out_degree": 1, - "betweenness": 0.0001357135400354943, - "pagerank": 0.0016261961372699078, - "harmonic": 0.0032258064516129032, - "bidirectional_harmonic": 0.25286866359447036, - "degree": 5 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 4, - "halstead_volume": 51.80615605397529, - "halstead_difficulty": 2.8125 - }, - "corruption": { - "code": "def urldecode(query):\n \"\"\"Decode a query string in x-www-form-urlencoded format into a sequence\n of two-element tuples.\n\n Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce\n correct formatting of the query string by validation. If validation fails\n a ValueError will be raised. urllib.parse_qsl will only raise errors if\n any of name-value pairs omits the equals sign.\n \"\"\"\n # Check if query contains invalid characters\n if query and not set(query) <= urlencoded:\n error = (\"Error trying to decode a non urlencoded string. \"\n \"Found invalid characters: %s \"\n \"in the string: '%s'. \"\n \"Please ensure the request/response body is \"\n \"x-www-form-urlencoded.\")\n raise ValueError(error % (set(query) - urlencoded, query))\n\n # Check for correctly hex encoded values using a regular expression\n # All encoded values begin with % followed by two hex characters\n # correct = %00, %A0, %0A, %FF\n # invalid = %G0, %5H, %PO\n if query and INVALID_HEX_PATTERN.match(query):\n raise ValueError('Invalid hex encoding in query string.')\n\n # We want to allow queries such as \"c2\" whereas urlparse.parse_qsl\n # with the strict_parsing flag will not.\n params = urlparse.parse_qsl(query, keep_blank_values=False)\n\n # unicode all the things\n return decode_params_utf8(params)", - "score": 0.9946043165467626 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/filtering.py", - "function_name": "_combine_regex_options", - "test_info": { - "success": false, - "failed": 1, - "passed": 2222, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__regex_options\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: None is not true\n\nTraceback:\n\n> def test__regex_options(self):\n self.db.collection.drop()\n self.db.collection.insert_one({'a': 'TADA'})\n self.db.collection.insert_one({'a': 'TA\\nDA'})\n \n self.assertFalse(self.db.collection.find_one({'a': {'$regex': 'tada'}}))\n self.assertTrue(\n self.db.collection.find_one(\n {\n 'a': {\n '$regex': re.compile('tada', re.IGNORECASE),\n }\n }\n )\n )\n \n self.assertTrue(self.db.collection.find_one({'a': {'$regex': 'tada', '$options': 'i'}}))\n> self.assertTrue(self.db.collection.find_one({'a': {'$regex': '^da', '$options': 'im'}}))\nE AssertionError: None is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__regex_options" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 1, - "true_in_degree": 7.880000000000004, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0018422864075530322, - "harmonic": 0.0, - "bidirectional_harmonic": 0.15395720815642694, - "degree": 1 - }, - "line_count": 28, - "code_line_count": 28, - "cyclomatic": 8, - "halstead_volume": 69.18863237274596, - "halstead_difficulty": 3.7142857142857144 - }, - "corruption": { - "code": "def _combine_regex_options(search):\n if not isinstance(search['$options'], str):\n raise OperationFailure('$options has to be a string')\n\n options = None\n for option in search['$options']:\n # only recognize standard flags, stop at first unrecognized\n if option not in 'imxs':\n break\n re_option = getattr(re, option.upper())\n # only use the single (first) valid option, forget combining\n options = re_option\n break\n\n search_copy = dict(search)\n del search_copy['$options']\n\n if options is None:\n return search_copy\n\n if isinstance(search['$regex'], _RE_TYPES):\n if isinstance(search['$regex'], RE_TYPE):\n search_copy['$regex'] = re.compile(\n search['$regex'].pattern, search['$regex'].flags | options\n )\n else:\n regex = search['$regex']\n search_copy['$regex'] = regex.__class__(regex.pattern, regex.flags | options)\n else:\n search_copy['$regex'] = re.compile(search['$regex'], options)\n return search_copy", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/schema/", - "code_path": "schema", - "name": "schema", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/keleshev/schema", - "stats": { - "exists": true, - "files_count": 1, - "functions_count": 36, - "total_lines": 961, - "avg_lines_per_file": 961.0, - "avg_lines_per_func": 26.694444444444443 - } - }, - "fpath": "schema/__init__.py", - "function_name": "Schema.json_schema", - "test_info": { - "success": false, - "failed": 43, - "passed": 311, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: test_schema.py::test_json_schema\nLocation: /tmp/benchmark_71913j8o/test_schema.py:883\nError: AssertionError: assert {'$id': 'my-i...tring'}}, ...} == {'$id': 'my-i...tring'}}, ...}\n \n Omitting 5 identical items, use -vv to show\n Differing items:\n {'required': []} != {'required': ['test']}\n Use -v to get more diff\n\nTraceback:\n\n> def test_json_schema():\n s = Schema({\"test\": str})\n> assert s.json_schema(\"my-id\") == {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"my-id\",\n \"properties\": {\"test\": {\"type\": \"string\"}},\n \"required\": [\"test\"],\n \"additionalProperties\": False,\n \"type\": \"object\",\n }\nE AssertionError: assert {'$id': 'my-i...tring'}}, ...} == {'$id': 'my-i...tring'}}, ...}\nE \nE Omitting 5 identical items, use -vv to show\nE Differing items:\nE {'required': []} != {'required': ['test']}\nE Use -v to get more diff\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "test_schema.py", - "test_json_schema" - ], - [ - "test_schema.py", - "test_json_schema_with_title" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 3.2, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.0071428571428571435, - "harmonic": 0.2, - "bidirectional_harmonic": 0.43916666666666665, - "degree": 4 - }, - "line_count": 223, - "code_line_count": 223, - "cyclomatic": 1, - "halstead_volume": 887.5790004038475, - "halstead_difficulty": 6.47887323943662 - }, - "corruption": { - "code": " def json_schema(\n self, schema_id: str, use_refs: bool = False, **kwargs: Any\n ) -> Dict[str, Any]:\n \"\"\"Generate a draft-07 JSON schema dict representing the Schema.\n This method must be called with a schema_id.\n\n :param schema_id: The value of the $id on the main schema\n :param use_refs: Enable reusing object references in the resulting JSON schema.\n Schemas with references are harder to read by humans, but are a lot smaller when there\n is a lot of reuse\n \"\"\"\n\n seen: Dict[int, Dict[str, Any]] = {}\n definitions_by_name: Dict[str, Dict[str, Any]] = {}\n\n def _json_schema(\n schema: \"Schema\",\n is_main_schema: bool = True,\n title: Union[str, None] = None,\n description: Union[str, None] = None,\n allow_reference: bool = True,\n ) -> Dict[str, Any]:\n def _create_or_use_ref(return_dict: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"If not already seen, return the provided part of the schema unchanged.\n If already seen, give an id to the already seen dict and return a reference to the previous part\n of the schema instead.\n \"\"\"\n if not use_refs or is_main_schema:\n return return_schema\n\n hashed = hash(repr(sorted(return_dict.items())))\n if hashed not in seen:\n seen[hashed] = return_dict\n return return_dict\n else:\n id_str = \"#\" + str(hashed)\n seen[hashed][\"$id\"] = id_str\n return {\"$ref\": id_str}\n\n def _get_type_name(python_type: Type) -> str:\n \"\"\"Return the JSON schema name for a Python type\"\"\"\n if python_type == str:\n return \"string\"\n elif python_type == int:\n return \"integer\"\n elif python_type == float:\n return \"number\"\n elif python_type == bool:\n return \"boolean\"\n elif python_type == list:\n return \"array\"\n elif python_type == dict:\n return \"object\"\n return \"string\"\n\n def _to_json_type(value: Any) -> Any:\n \"\"\"Attempt to convert a constant value (for \"const\" and \"default\") to a JSON serializable value\"\"\"\n if value is None or type(value) in (str, int, float, bool, list, dict):\n return value\n\n if type(value) in (tuple, set, frozenset):\n return list(value)\n\n if isinstance(value, Literal):\n return value.schema\n\n return str(value)\n\n def _to_schema(s: Any, ignore_extra_keys: bool) -> Schema:\n if not isinstance(s, Schema):\n return Schema(s, ignore_extra_keys=ignore_extra_keys)\n\n return s\n\n s: Any = schema.schema\n i: bool = schema.ignore_extra_keys\n flavor = _priority(s)\n\n return_schema: Dict[str, Any] = {}\n\n return_description: Union[str, None] = description or schema.description\n if return_description:\n return_schema[\"description\"] = return_description\n if title:\n return_schema[\"title\"] = title\n\n # Check if we have to create a common definition and use as reference\n if allow_reference and schema.as_reference:\n # Generate sub schema if not already done\n if schema.name not in definitions_by_name:\n definitions_by_name[\n cast(str, schema.name)\n ] = {} # Avoid infinite loop\n definitions_by_name[cast(str, schema.name)] = _json_schema(\n schema, is_main_schema=False, allow_reference=False\n )\n\n return_schema[\"$ref\"] = \"#/definitions/\" + cast(str, schema.name)\n else:\n if schema.name and not title:\n return_schema[\"title\"] = schema.name\n\n if flavor == TYPE:\n # Handle type\n return_schema[\"type\"] = _get_type_name(s)\n elif flavor == ITERABLE:\n # Handle arrays or dict schema\n\n return_schema[\"type\"] = \"array\"\n if len(s) == 1:\n return_schema[\"items\"] = _json_schema(\n _to_schema(s[0], i), is_main_schema=False\n )\n elif len(s) > 1:\n return_schema[\"items\"] = _json_schema(\n Schema(Or(*s)), is_main_schema=False\n )\n elif isinstance(s, Or):\n # Handle Or values\n\n # Check if we can use an enum\n if all(\n priority == COMPARABLE\n for priority in [_priority(value) for value in s.args]\n ):\n or_values = [\n str(s) if isinstance(s, Literal) else s for s in s.args\n ]\n # All values are simple, can use enum or const\n if len(or_values) == 1:\n or_value = or_values[0]\n if or_value is None:\n return_schema[\"type\"] = \"null\"\n else:\n return_schema[\"const\"] = _to_json_type(or_value)\n return return_schema\n return_schema[\"enum\"] = or_values\n else:\n # No enum, let's go with recursive calls\n any_of_values = []\n for or_key in s.args:\n new_value = _json_schema(\n _to_schema(or_key, i), is_main_schema=False\n )\n if new_value != {} and new_value not in any_of_values:\n any_of_values.append(new_value)\n if len(any_of_values) == 1:\n # Only one representable condition remains, do not put under anyOf\n return_schema.update(any_of_values[0])\n else:\n return_schema[\"anyOf\"] = any_of_values\n elif isinstance(s, And):\n # Handle And values\n all_of_values = []\n for and_key in s.args:\n new_value = _json_schema(\n _to_schema(and_key, i), is_main_schema=False\n )\n if new_value != {} and new_value not in all_of_values:\n all_of_values.append(new_value)\n if len(all_of_values) == 1:\n # Only one representable condition remains, do not put under allOf\n return_schema.update(all_of_values[0])\n else:\n return_schema[\"allOf\"] = all_of_values\n elif flavor == COMPARABLE:\n if s is None:\n return_schema[\"type\"] = \"null\"\n else:\n return_schema[\"const\"] = _to_json_type(s)\n elif flavor == VALIDATOR and type(s) == Regex:\n return_schema[\"type\"] = \"string\"\n # JSON schema uses ECMAScript regex syntax\n # Translating one to another is not easy, but this should work for simple cases\n return_schema[\"pattern\"] = re.sub(\n r\"\\(\\?P<[a-z\\d_]+>\", \"(\", s.pattern_str\n ).replace(\"/\", r\"\\/\" )\n else:\n if flavor != DICT:\n # If not handled, do not check\n return return_schema\n\n # Schema is a dict\n\n required_keys = []\n expanded_schema = {}\n additional_properties = i\n for key in s:\n if isinstance(key, Hook):\n continue\n\n def _key_allows_additional_properties(key: Any) -> bool:\n if isinstance(key, Optional):\n return _key_allows_additional_properties(key.schema)\n\n return key == str or key == object\n\n def _get_key_title(key: Any) -> Union[str, None]:\n if isinstance(key, Optional):\n return _get_key_title(key.schema)\n\n if isinstance(key, Literal):\n return key.title\n\n return None\n\n def _get_key_description(key: Any) -> Union[str, None]:\n if isinstance(key, Optional):\n return _get_key_description(key.schema)\n\n if isinstance(key, Literal):\n return key.description\n\n return None\n\n def _get_key_name(key: Any) -> Any:\n if isinstance(key, Optional):\n return _get_key_name(key.schema)\n\n if isinstance(key, Literal):\n return key.schema\n\n return key\n\n additional_properties = (\n additional_properties\n or _key_allows_additional_properties(key)\n )\n sub_schema = _to_schema(s[key], ignore_extra_keys=i)\n key_name = _get_key_name(key)\n\n if isinstance(key_name, str):\n if isinstance(key, Optional):\n required_keys.append(key_name)\n expanded_schema[key_name] = _json_schema(\n sub_schema,\n is_main_schema=False,\n title=_get_key_title(key),\n description=_get_key_description(key),\n )\n if isinstance(key, Optional) and hasattr(key, \"default\"):\n expanded_schema[key_name][\"default\"] = _to_json_type(\n _invoke_with_optional_kwargs(key.default, **kwargs)\n if callable(key.default)\n else key.default\n )\n elif isinstance(key_name, Or):\n for or_key in key_name.args:\n expanded_schema[_get_key_name(or_key)] = _json_schema(\n sub_schema,\n is_main_schema=False,\n description=_get_key_description(or_key),\n )\n\n return_schema.update(\n {\n \"type\": \"object\",\n \"properties\": expanded_schema,\n \"required\": required_keys,\n \"additionalProperties\": additional_properties,\n }\n )\n\n if is_main_schema:\n return_schema.update(\n {\n \"$id\": schema_id,\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n }\n )\n if self._name:\n return_schema[\"title\"] = self._name\n\n if definitions_by_name:\n return_schema[\"definitions\"] = {}\n for definition_name, definition in definitions_by_name.items():\n return_schema[\"definitions\"][definition_name] = definition\n\n return _create_or_use_ref(return_schema)\n\n return _json_schema(self, True)", - "score": 0.35820895522388063 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/arc.py", - "function_name": "revise", - "test_info": { - "success": false, - "failed": 6, - "passed": 615, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ], - [ - "tests/search/test_arc_concistency.py", - "test_if_a_value_has_no_possible_match_remove_it_from_domain" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 1.6, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 2, - "betweenness": 0.0002805521265851195, - "pagerank": 0.001954618055555556, - "harmonic": 0.014925373134328358, - "bidirectional_harmonic": 0.21877221037668795, - "degree": 3 - }, - "line_count": 17, - "code_line_count": 17, - "cyclomatic": 7, - "halstead_volume": 11.60964047443681, - "halstead_difficulty": 1.0 - }, - "corruption": { - "code": "def revise(domains, arc, constraints):\n \"\"\"\n Given the arc X, Y (variables), removes the values from X's domain that\n do not meet the constraint between X and Y.\n\n That is, given x1 in X's domain, x1 will be removed from the domain, if\n there is no value y in Y's domain that makes constraint(X,Y) True, for\n those constraints affecting X and Y.\n \"\"\"\n x, y = arc\n related_constraints = [(neighbors, constraint)\n for neighbors, constraint in constraints\n if set(arc) == set(neighbors)]\n\n modified = False\n\n for neighbors, constraint in related_constraints:\n for x_value in domains[x]:\n constraint_results = (_call_constraint({x: x_value, y: y_value},\n neighbors, constraint)\n for y_value in domains[y])\n\n if any(constraint_results):\n domains[x].remove(x_value)\n modified = True\n\n return modified", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mongomock/", - "code_path": "mongomock", - "name": "mongomock", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/mongomock/mongomock.git", - "stats": { - "exists": true, - "files_count": 20, - "functions_count": 322, - "total_lines": 6725, - "avg_lines_per_file": 336.25, - "avg_lines_per_func": 20.885093167701864 - } - }, - "fpath": "mongomock/aggregate.py", - "function_name": "_handle_unwind_stage", - "test_info": { - "success": false, - "failed": 2, - "passed": 2221, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test__collection_api.py::CollectionAPITest::test__unwind_preserve_null_and_empty_arrays\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [{'_i[138 chars]'EFG'}, {'_id': 3, 'item': 'IJK', 'sizes': 'M'[109 chars]lse}] != [{'_i[138 chars]'EFG', 'sizes': []}, {'_id': 3, 'item': 'IJK',[122 chars]lse}]\n\nFirst differing element 3:\n{'_id': 2, 'item': 'EFG'}\n{'_id': 2, 'item': 'EFG', 'sizes': []}\n\n [{'_id': 1, 'item': 'ABC', 'sizes': 'S'},\n {'_id': 1, 'item': 'ABC', 'sizes': 'M'},\n {'_id': 1, 'item': 'ABC', 'sizes': 'L'},\n- {'_id': 2, 'item': 'EFG'},\n+ {'_id': 2, 'item': 'EFG', 'sizes': []},\n? +++++++++++++\n\n {'_id': 3, 'item': 'IJK', 'sizes': 'M'},\n {'_id': 4, 'item': 'LMN'},\n {'_id': 5, 'item': 'XYZ', 'sizes': None},\n {'_id': 6, 'item': 'abc', 'sizes': False}]\n\nTraceback:\n\n> def test__unwind_preserve_null_and_empty_arrays(self):\n self.db.collection.insert_many(\n [\n {'_id': 1, 'item': 'ABC', 'sizes': ['S', 'M', 'L']},\n {'_id': 2, 'item': 'EFG', 'sizes': []},\n {'_id': 3, 'item': 'IJK', 'sizes': 'M'},\n {'_id': 4, 'item': 'LMN'},\n {'_id': 5, 'item': 'XYZ', 'sizes': None},\n {'_id': 6, 'item': 'abc', 'sizes': False},\n ]\n )\n actual = self.db.collection.aggregate(\n [\n {'$unwind': {'path': '$sizes', 'preserveNullAndEmptyArrays': True}},\n ]\n )\n> self.assertEqual(\n [\n {'_id': 1, 'item': 'ABC', 'sizes': 'S'},\n {'_id': 1, 'item': 'ABC', 'sizes': 'M'},\n {'_id': 1, 'item': 'ABC', 'sizes': 'L'},\n {'_id': 2, 'item': 'EFG'},\n {'_id': 3, 'item': 'IJK', 'sizes': 'M'},\n {'_id': 4, 'item': 'LMN'},\n {'_id': 5, 'item': 'XYZ', 'sizes': None},\n {'_id': 6, 'item': 'abc', 'sizes': False},\n ],\n list(actual),\n )\nE AssertionError: Lists differ: [{'_i[138 chars]'EFG'}, {'_id': 3, 'item': 'IJK', 'sizes': 'M'[109 chars]lse}] != [{'_i[138 chars]'EFG', 'sizes': []}, {'_id': 3, 'item': 'IJK',[122 chars]lse}]\nE \nE First differing element 3:\nE {'_id': 2, 'item': 'EFG'}\nE {'_id': 2, 'item': 'EFG', 'sizes': []}\nE \nE [{'_id': 1, 'item': 'ABC', 'sizes': 'S'},\nE {'_id': 1, 'item': 'ABC', 'sizes': 'M'},\nE {'_id': 1, 'item': 'ABC', 'sizes': 'L'},\nE - {'_id': 2, 'item': 'EFG'},\nE + {'_id': 2, 'item': 'EFG', 'sizes': []},\nE ? +++++++++++++\nE \nE {'_id': 3, 'item': 'IJK', 'sizes': 'M'},\nE {'_id': 4, 'item': 'LMN'},\nE {'_id': 5, 'item': 'XYZ', 'sizes': None},\nE {'_id': 6, 'item': 'abc', 'sizes': False}]\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test__collection_api.py", - "test__unwind_preserve_null_and_empty_arrays" - ], - [ - "tests/test__collection_api.py", - "test__unwind_preserve_null_and_empty_arrays_on_nested" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def _handle_unwind_stage(in_collection, unused_database, options, unused_user_vars):\n if not isinstance(options, dict):\n options = {'path': options}\n path = options['path']\n if not isinstance(path, str) or path[0] != '$':\n raise ValueError(\n f'$unwind failed: exception: field path references must be prefixed '\n f\"with a '$' '{path}'\"\n )\n path = path[1:]\n should_preserve_null_and_empty = options.get('preserveNullAndEmptyArrays')\n include_array_index = options.get('includeArrayIndex')\n unwound_collection = []\n for doc in in_collection:\n try:\n array_value = helpers.get_value_by_dot(doc, path)\n except KeyError:\n if should_preserve_null_and_empty:\n unwound_collection.append(doc)\n continue\n if array_value is None:\n if should_preserve_null_and_empty:\n unwound_collection.append(doc)\n continue\n if array_value == []:\n if should_preserve_null_and_empty:\n new_doc = copy.deepcopy(doc)\n # preserve empty array instead of deleting field\n unwound_collection.append(new_doc)\n continue\n if isinstance(array_value, list):\n iter_array = enumerate(array_value)\n else:\n iter_array = [(None, array_value)]\n for index, field_item in iter_array:\n new_doc = copy.deepcopy(doc)\n new_doc = helpers.set_value_by_dot(new_doc, path, field_item)\n if include_array_index:\n new_doc = helpers.set_value_by_dot(new_doc, include_array_index, index)\n unwound_collection.append(new_doc)\n\n return unwound_collection", - "score": 0.75 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/grant_types/refresh_token.py", - "function_name": "RefreshTokenGrant.create_token_response", - "test_info": { - "success": false, - "failed": 38, - "passed": 2006, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/grant_types/test_refresh_token.py::RefreshTokenGrantTest::test_create_cors_headers\nLocation: /tmp/benchmark_ubn135qq/oauthlib/oauth2/rfc6749/grant_types/base.py:135\nError: NotImplementedError: Subclasses must implement this method.\n\nTraceback:\n\n> def test_create_cors_headers(self):\n bearer = BearerToken(self.mock_validator)\n self.request.headers['origin'] = 'https://foo.bar'\n self.mock_validator.is_origin_allowed.return_value = True\n \n> headers = self.auth.create_token_response(self.request, bearer)[0]\n\n> def create_token_response(self, request, token_handler):\n \"\"\"\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param token_handler: A token handler instance, for example of type\n oauthlib.oauth2.BearerToken.\n \"\"\"\n> raise NotImplementedError('Subclasses must implement this method.')\nE NotImplementedError: Subclasses must implement this method.\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/grant_types/test_refresh_token.py", - "test_create_cors_headers" - ], - [ - "tests/oauth2/rfc6749/grant_types/test_refresh_token.py", - "test_create_cors_headers_insecure_origin" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 10.400000000000006, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 5, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.03225806451612903, - "bidirectional_harmonic": 0.25524193548387125, - "degree": 5 - }, - "line_count": 20, - "code_line_count": 20, - "cyclomatic": 3, - "halstead_volume": 0, - "halstead_difficulty": 0 - }, - "corruption": { - "code": "# exploring code", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/jsonql.py", - "function_name": "run_pipe", - "test_info": { - "success": false, - "failed": 3, - "passed": 154, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_remove_duplicates_sharded\nLocation: /tmp/benchmark_zb81cgrg/cc_net/dedup.py:84\nError: AssertionError: 2 processes failed...\n\nTraceback:\n\n> def test_remove_duplicates_sharded(tmp_path: Path):\n data = tmp_path / \"data\"\n part_0 = [[\"Hello\", \"_World\", \"I'm so original\"]]\n write_docs(data / \"part_0.json\", part_0)\n part_1 = [[\"_Good morning\", \"_World\", \"I'm originaler\"]]\n write_docs(data / \"part_1.json\", part_1)\n \n h = tmp_path / \"hashes\"\n h.mkdir()\n h0 = FlatHashSet()\n h0.add([str_hash(s.lower()) for doc in part_0 for s in doc])\n h0.add([str_hash(\"_world\")])\n h0.dump(h / \"part_0.bin\")\n assert {\n str_hash(\"hello\"): False,\n str_hash(\"_world\"): True,\n str_hash(\"i'm so original\"): False,\n } == as_dict(h0)\n \n h1 = FlatHashSet()\n h1.add([str_hash(s.lower()) for doc in part_1 for s in doc])\n h1.add([str_hash(\"_good morning\")])\n h1.dump(h / \"part_1.bin\")\n assert {\n str_hash(\"_good morning\"): True,\n str_hash(\"_world\"): False,\n str_hash(\"i'm originaler\"): False,\n } == as_dict(h1)\n \n res = tmp_path / \"res\"\n res.mkdir()\n # dedup.DISABLE_MULTI_PROCESSING = True # Simplifies debugging\n> dedup.remove_duplicates_sharded(\n files=[data / \"part_0.json\", data / \"part_1.json\"],\n outputs=[res / \"part_0.json\", res / \"part_1.json\"],\n field=\"text\",\n hashes_dir=h,\n )\n\n> run_par(\n\n> def run_par(processes):\n # This is different from multiprocessing.map since it allows for kwargs.\n processes = list(processes)\n if len(processes) == 1 or DISABLE_MULTI_PROCESSING:\n for f, args, kwargs in processes:\n f(*args, **kwargs)\n return\n \n log(f\"Starting {len(processes)} subprocess\")\n processes = [\n multiprocessing.Process(target=f, args=a, kwargs=kw) for (f, a, kw) in processes\n ]\n for p in processes:\n p.start()\n for p in processes:\n p.join()\n failed = 0\n for p in processes:\n if p.exitcode != 0:\n log(f\"Process failed with code {p.exitcode}: {p}\")\n failed += 1\n> assert failed == 0, f\"{failed} processes failed...\"\nE AssertionError: 2 processes failed...\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_remove_duplicates_sharded" - ], - [ - "tests/test_jsonql.py", - "test_describe" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 12.640563199999999, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.0006756756756756758, - "harmonic": 0.04280327515621634, - "bidirectional_harmonic": 0.17317927170868336, - "degree": 2 - }, - "line_count": 13, - "code_line_count": 13, - "cyclomatic": 5, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def run_pipe(\n command,\n kwargs: dict = None,\n file: ReadableFileLike = None,\n output: WritableFileLike = None,\n):\n # Only parse ArgumentParser, otherwise drop any dict kwargs\n if isinstance(kwargs, argparse.ArgumentParser):\n kwargs = vars(kwargs.parse_args())\n else:\n kwargs = {}\n file = file or Path(kwargs.pop(\"file\", \"-\"))\n output = output or Path(kwargs.pop(\"output\", \"-\"))\n\n return run_pipes(as_pipe(command, kwargs), file=file, output=output)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/door/_cls/pep/doorpep593.py", - "function_name": "AnnotatedTypeHint._is_subhint_branch", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a40_api/door/a90_func/test_door_func.py::test_door_is_subhint\nLocation: /tmp/benchmark_u1bew5ef/beartype_test/a00_unit/a40_api/door/a90_func/test_door_func.py:40\nError: assert True is False\n + where True = (typing.Annotated[list, False], typing.Annotated[collections.abc.Sequence, True])\n\nTraceback:\n\n> def test_door_is_subhint(\n door_cases_is_subhint: 'Iterable[Tuple[object, object, bool]]') -> None:\n '''\n Test the :func:`beartype.door.is_subhint` tester.\n \n Parameters\n ----------\n door_cases_is_subhint : Iterable[Tuple[object, object, bool]]\n Iterable of **type subhint cases** (i.e., 3-tuples ``(subhint,\n superhint, is_subhint)`` describing the subhint relations between two\n type hints).\n '''\n \n # Defer test-specific imports.\n from beartype.door import is_subhint\n \n # For each type subhint case to be tested...\n for subhint, superhint, IS_SUBHINT in door_cases_is_subhint:\n # Assert this tester returns the expected boolean for these hints.\n> assert is_subhint(subhint, superhint) is IS_SUBHINT\nE assert True is False\nE + where True = (typing.Annotated[list, False], typing.Annotated[collections.abc.Sequence, True])\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a40_api/door/a90_func/test_door_func.py", - "test_door_is_subhint" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.592, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.0038377192982456134, - "bidirectional_harmonic": 0.14838935735317352, - "degree": 1 - }, - "line_count": 12, - "code_line_count": 12, - "cyclomatic": 4, - "halstead_volume": 50.18947501009619, - "halstead_difficulty": 3.2142857142857144 - }, - "corruption": { - "code": "# noop", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth2/rfc6749/tokens.py", - "function_name": "BearerToken.create_token", - "test_info": { - "success": false, - "failed": 116, - "passed": 1928, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth2/rfc6749/endpoints/test_client_authentication.py::ClientAuthenticationTest::test_basicauth_backend\nLocation: /tmp/benchmark_7nzy5xhh/oauthlib/oauth2/rfc6749/grant_types/client_credentials.py:75\nError: AttributeError: 'BearerToken' object has no attribute 'create_token'\n\nTraceback:\n\n> def test_basicauth_backend(self):\n self.validator.authenticate_client.side_effect = self.basicauth_authenticate_client\n> _, body, _ = self.backend.create_token_response(\n self.token_uri,\n body='grant_type=client_credentials',\n headers=self.basicauth_client_creds\n )\n\n> return f(endpoint, uri, *args, **kwargs)\n\n> return grant_type_handler.create_token_response(\n\n> def create_token_response(self, request, token_handler):\n \"\"\"Return token or error in JSON format.\n \n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :param token_handler: A token handler instance, for example of type\n oauthlib.oauth2.BearerToken.\n \n If the access token request is valid and authorized, the\n authorization server issues an access token as described in\n `Section 5.1`_. A refresh token SHOULD NOT be included. If the request\n failed client authentication or is invalid, the authorization server\n returns an error response as described in `Section 5.2`_.\n \n .. _`Section 5.1`: https://tools.ietf.org/html/rfc6749#section-5.1\n .. _`Section 5.2`: https://tools.ietf.org/html/rfc6749#section-5.2\n \"\"\"\n headers = self._get_default_headers()\n try:\n log.debug('Validating access token request, %r.', request)\n self.validate_token_request(request)\n except errors.OAuth2Error as e:\n log.debug('Client error in token request. %s.', e)\n headers.update(e.headers)\n return headers, e.json, e.status_code\n \n> token = token_handler.create_token(request, refresh_token=False)\nE AttributeError: 'BearerToken' object has no attribute 'create_token'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_basicauth_backend" - ], - [ - "tests/oauth2/rfc6749/endpoints/test_client_authentication.py", - "test_basicauth_legacy" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.48, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 4, - "betweenness": 0.0, - "pagerank": 0.000482315112540193, - "harmonic": 0.016129032258064516, - "bidirectional_harmonic": 0.2547235023041478, - "degree": 4 - }, - "line_count": 24, - "code_line_count": 24, - "cyclomatic": 8, - "halstead_volume": 53.30296890880645, - "halstead_difficulty": 2.5 - }, - "corruption": { - "code": "# dummy code", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/yamllint/", - "code_path": "yamllint", - "name": "yamllint", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/adrienverge/yamllint", - "stats": { - "exists": true, - "files_count": 31, - "functions_count": 69, - "total_lines": 4688, - "avg_lines_per_file": 151.2258064516129, - "avg_lines_per_func": 67.94202898550725 - } - }, - "fpath": "yamllint/rules/indentation.py", - "function_name": "_check", - "test_info": { - "success": false, - "failed": 3, - "passed": 1239, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/rules/test_indentation.py::IndentationTestCase::test_anchors\nLocation: /usr/lib/python3.12/unittest/case.py:715\nError: AssertionError: Lists differ: [3:12: wrong indentation: expected 2 but found 11 (indentation)] != []\n\nFirst list contains 1 additional elements.\nFirst extra element 0:\n3:12: wrong indentation: expected 2 but found 11 (indentation)\n\n- [3:12: wrong indentation: expected 2 but found 11 (indentation)]\n+ []\n\nTraceback:\n\n> def test_anchors(self):\n conf = 'indentation: {spaces: consistent}'\n self.check('---\\n'\n 'key: &anchor value\\n', conf)\n self.check('---\\n'\n 'key: &anchor\\n'\n ' value\\n', conf)\n self.check('---\\n'\n '- &anchor value\\n', conf)\n self.check('---\\n'\n '- &anchor\\n'\n ' value\\n', conf)\n self.check('---\\n'\n 'key: &anchor [1,\\n'\n ' 2]\\n', conf)\n self.check('---\\n'\n 'key: &anchor\\n'\n ' [1,\\n'\n ' 2]\\n', conf)\n self.check('---\\n'\n 'key: &anchor\\n'\n ' - 1\\n'\n ' - 2\\n', conf)\n self.check('---\\n'\n '- &anchor [1,\\n'\n ' 2]\\n', conf)\n self.check('---\\n'\n '- &anchor\\n'\n ' [1,\\n'\n ' 2]\\n', conf)\n self.check('---\\n'\n '- &anchor\\n'\n ' - 1\\n'\n ' - 2\\n', conf)\n self.check('---\\n'\n 'key:\\n'\n ' &anchor1\\n'\n ' value\\n', conf)\n> self.check('---\\n'\n 'pre:\\n'\n ' &anchor1 0\\n'\n '&anchor2 key:\\n'\n ' value\\n', conf)\n\n> self.assertEqual(real_problems, expected_problems)\nE AssertionError: Lists differ: [3:12: wrong indentation: expected 2 but found 11 (indentation)] != []\nE \nE First list contains 1 additional elements.\nE First extra element 0:\nE 3:12: wrong indentation: expected 2 but found 11 (indentation)\nE \nE - [3:12: wrong indentation: expected 2 but found 11 (indentation)]\nE + []\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/rules/test_indentation.py", - "test_anchors" - ], - [ - "tests/test_spec_examples.py", - "test_example-6.16" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.0, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 5, - "betweenness": 0.00101010101010101, - "pagerank": 0.0034588509316770192, - "harmonic": 0.1111111111111111, - "bidirectional_harmonic": 0.36481481481481476, - "degree": 6 - }, - "line_count": 164, - "code_line_count": 164, - "cyclomatic": 73, - "halstead_volume": 1742.3769903374018, - "halstead_difficulty": 11.576470588235294 - }, - "corruption": { - "code": " def _check(conf, token, prev, next, nextnext, context):\n if 'stack' not in context:\n context['stack'] = [Parent(ROOT, 0)]\n context['cur_line'] = -1\n context['spaces'] = conf['spaces']\n context['indent-sequences'] = conf['indent-sequences']\n\n # Step 1: Lint\n\n is_visible = (\n not isinstance(token, (yaml.StreamStartToken, yaml.StreamEndToken)) and\n not isinstance(token, yaml.BlockEndToken) and\n not (isinstance(token, yaml.ScalarToken) and token.value == '') and\n not isinstance(token, (yaml.AnchorToken, yaml.TagToken, yaml.AliasToken))\n )\n first_in_line = (is_visible and\n token.start_mark.line + 1 > context['cur_line'])\n\n def detect_indent(base_indent, next):\n if not isinstance(context['spaces'], int):\n context['spaces'] = next.start_mark.column - base_indent\n return base_indent + context['spaces']\n\n if first_in_line:\n found_indentation = token.start_mark.column\n expected = context['stack'][-1].indent\n\n if isinstance(token, (yaml.FlowMappingEndToken,\n yaml.FlowSequenceEndToken)):\n expected = context['stack'][-1].line_indent\n elif (context['stack'][-1].type == KEY and\n context['stack'][-1].explicit_key and\n not isinstance(token, yaml.ValueToken)):\n expected = detect_indent(expected, token)\n\n if found_indentation != expected:\n if expected < 0:\n message = f'wrong indentation: expected at least ' \\\n f'{found_indentation + 1}'\n else:\n message = f'wrong indentation: expected {expected} but ' \\\n f'found {found_indentation}'\n yield LintProblem(token.start_mark.line + 1,\n found_indentation + 1, message)\n\n if (isinstance(token, yaml.ScalarToken) and\n conf['check-multi-line-strings']):\n yield from check_scalar_indentation(conf, token, context)\n\n # Step 2.a:\n\n if is_visible:\n context['cur_line'] = get_real_end_line(token)\n if first_in_line:\n context['cur_line_indent'] = found_indentation\n\n # Step 2.b: Update state\n\n if isinstance(token, yaml.BlockMappingStartToken):\n # - a: 1\n # or\n # - ? a\n # : 1\n # or\n # - ?\n # a\n # : 1\n assert isinstance(next, yaml.KeyToken)\n assert next.start_mark.line == token.start_mark.line\n\n indent = token.start_mark.column\n\n context['stack'].append(Parent(B_MAP, indent))\n\n elif isinstance(token, yaml.FlowMappingStartToken):\n if next.start_mark.line == token.start_mark.line:\n # - {a: 1, b: 2}\n indent = next.start_mark.column\n else:\n # - {\n # a: 1, b: 2\n # }\n indent = detect_indent(context['cur_line_indent'], next)\n\n context['stack'].append(Parent(F_MAP, indent,\n line_indent=context['cur_line_indent']))\n\n elif isinstance(token, yaml.BlockSequenceStartToken):\n # - - a\n # - b\n assert isinstance(next, yaml.BlockEntryToken)\n assert next.start_mark.line == token.start_mark.line\n\n indent = token.start_mark.column\n\n context['stack'].append(Parent(B_SEQ, indent))\n\n elif (isinstance(token, yaml.BlockEntryToken) and\n # in case of an empty entry\n not isinstance(next, (yaml.BlockEntryToken, yaml.BlockEndToken))):\n # It looks like pyyaml doesn't issue BlockSequenceStartTokens when the\n # list is not indented. We need to compensate that.\n if context['stack'][-1].type != B_SEQ:\n context['stack'].append(Parent(B_SEQ, token.start_mark.column))\n context['stack'][-1].implicit_block_seq = True\n\n if next.start_mark.line == token.end_mark.line:\n # - item 1\n # - item 2\n indent = next.start_mark.column\n elif next.start_mark.column == token.start_mark.column:\n # -\n # key: value\n indent = next.start_mark.column\n else:\n # -\n # item 1\n # -\n # key:\n # value\n indent = detect_indent(token.start_mark.column, next)\n\n context['stack'].append(Parent(B_ENT, indent))\n\n elif isinstance(token, yaml.FlowSequenceStartToken):\n if next.start_mark.line == token.start_mark.line:\n # - [a, b]\n indent = next.start_mark.column\n else:\n # - [\n # a, b\n # ]\n indent = detect_indent(context['cur_line_indent'], next)\n\n context['stack'].append(Parent(F_SEQ, indent,\n line_indent=context['cur_line_indent']))\n\n elif isinstance(token, yaml.KeyToken):\n indent = context['stack'][-1].indent\n\n context['stack'].append(Parent(KEY, indent))\n\n context['stack'][-1].explicit_key = is_explicit_key(token)\n\n elif isinstance(token, yaml.ValueToken):\n assert context['stack'][-1].type == KEY\n\n # Special cases:\n # key: &anchor\n # value\n # and:\n # key: !!tag\n # value\n if isinstance(next, (yaml.AnchorToken, yaml.TagToken)):\n if (next.start_mark.line == prev.start_mark.line and\n next.start_mark.line < nextnext.start_mark.line):\n next = nextnext\n\n # Only if value is not empty\n if not isinstance(next, (yaml.BlockEndToken,\n yaml.FlowMappingEndToken,\n yaml.FlowSequenceEndToken,\n yaml.KeyToken)):\n if context['stack'][-1].explicit_key:\n # ? k\n # : value\n # or\n # ? k\n # :\n # value\n indent = detect_indent(context['stack'][-1].indent, next)\n elif next.start_mark.line == prev.start_mark.line:\n # k: value\n indent = next.start_mark.column\n elif isinstance(next, (yaml.BlockSequenceStartToken,\n yaml.BlockEntryToken)):\n # NOTE: We add BlockEntryToken in the test above because\n # sometimes BlockSequenceStartToken are not issued. Try\n # yaml.scan()ning this:\n # '- lib:\\n'\n # ' - var\\n'\n if context['indent-sequences'] is False:\n indent = context['stack'][-1].indent\n elif context['indent-sequences'] is True:\n if (context['spaces'] == 'consistent' and\n next.start_mark.column -\n context['stack'][-1].indent == 0):\n # In this case, the block sequence item is not indented\n # (while it should be), but we don't know yet the\n # indentation it should have (because `spaces` is\n # `consistent` and its value has not been computed yet\n # -- this is probably the beginning of the document).\n # So we choose an unknown value (-1).\n indent = -1\n else:\n indent = detect_indent(context['stack'][-1].indent,\n next)\n else: # 'whatever' or 'consistent'\n if next.start_mark.column == context['stack'][-1].indent:\n if context['indent-sequences'] == 'consistent':\n context['indent-sequences'] = False\n indent = context['stack'][-1].indent\n else:\n if context['indent-sequences'] == 'consistent':\n context['indent-sequences'] = True\n indent = detect_indent(context['stack'][-1].indent,\n next)\n else:\n indent = detect_indent(context['stack'][-1].indent, next)\n\n context['stack'].append(Parent(VAL, indent))\n\n consumed_current_token = False\n while True:\n if (context['stack'][-1].type == F_SEQ and\n isinstance(token, yaml.FlowSequenceEndToken) and\n not consumed_current_token):\n context['stack'].pop()\n consumed_current_token = True\n\n elif (context['stack'][-1].type == F_MAP and\n isinstance(token, yaml.FlowMappingEndToken) and\n not consumed_current_token):\n context['stack'].pop()\n consumed_current_token = True\n\n elif (context['stack'][-1].type in (B_MAP, B_SEQ) and\n isinstance(token, yaml.BlockEndToken) and\n not context['stack'][-1].implicit_block_seq and\n not consumed_current_token):\n context['stack'].pop()\n consumed_current_token = True\n\n elif (context['stack'][-1].type == B_ENT and\n not isinstance(token, yaml.BlockEntryToken) and\n context['stack'][-2].implicit_block_seq and\n not isinstance(token, (yaml.AnchorToken, yaml.TagToken)) and\n not isinstance(next, yaml.BlockEntryToken)):\n context['stack'].pop()\n context['stack'].pop()\n\n elif (context['stack'][-1].type == B_ENT and\n isinstance(next, (yaml.BlockEntryToken, yaml.BlockEndToken))):\n context['stack'].pop()\n\n elif (context['stack'][-1].type == VAL and\n not isinstance(token, yaml.ValueToken) and\n not isinstance(token, (yaml.AnchorToken, yaml.TagToken))):\n assert context['stack'][-2].type == KEY\n context['stack'].pop()\n context['stack'].pop()\n\n elif (context['stack'][-1].type == KEY and\n isinstance(next, (yaml.BlockEndToken,\n yaml.FlowMappingEndToken,\n yaml.FlowSequenceEndToken,\n yaml.KeyToken))):\n # A key without a value: it's part of a set. Let's drop this key\n # and leave room for the next one.\n context['stack'].pop()\n\n else:\n break\n", - "score": 0.9912280701754386 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/oauthlib/", - "code_path": "oauthlib", - "name": "oauthlib", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/oauthlib/oauthlib.git", - "stats": { - "exists": true, - "files_count": 75, - "functions_count": 459, - "total_lines": 12464, - "avg_lines_per_file": 166.18666666666667, - "avg_lines_per_func": 27.154684095860567 - } - }, - "fpath": "oauthlib/oauth1/rfc5849/endpoints/access_token.py", - "function_name": "AccessTokenEndpoint.validate_access_token_request", - "test_info": { - "success": false, - "failed": 2, - "passed": 2042, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/oauth1/rfc5849/endpoints/test_access_token.py::AccessTokenEndpointTest::test_validate_request_token\nLocation: /usr/lib/python3.12/unittest/case.py:878\nError: AssertionError: 200 != 401\n\nTraceback:\n\n> def test_validate_request_token(self):\n self.validator.validate_request_token.return_value = False\n h, b, s = self.endpoint.create_access_token_response(\n self.uri, headers=self.headers)\n> self.assertEqual(s, 401)\nE AssertionError: 200 != 401\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_validate_request_token" - ], - [ - "tests/oauth1/rfc5849/endpoints/test_access_token.py", - "test_validate_verifier" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 21.402880000000017, - "in_degree": 1, - "true_in_degree": 1.0, - "out_degree": 9, - "betweenness": 0.00021748964749277938, - "pagerank": 0.0005848070739549841, - "harmonic": 0.06220430107526882, - "bidirectional_harmonic": 0.23747439836149548, - "degree": 10 - }, - "line_count": 49, - "code_line_count": 49, - "cyclomatic": 9, - "halstead_volume": 50.718800023077, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": " def validate_access_token_request(self, request):\n \"\"\"Validate an access token request.\n\n :param request: OAuthlib request.\n :type request: oauthlib.common.Request\n :raises: OAuth1Error if the request is invalid.\n :returns: A tuple of 2 elements.\n 1. The validation result (True or False).\n 2. The request object.\n \"\"\"\n self._check_transport_security(request)\n self._check_mandatory_parameters(request)\n\n if not request.resource_owner_key:\n raise errors.InvalidRequestError(\n description='Missing resource owner.')\n\n if not self.request_validator.check_request_token(\n request.resource_owner_key):\n raise errors.InvalidRequestError(\n description='Invalid resource owner key format.')\n\n if not request.verifier:\n raise errors.InvalidRequestError(\n description='Missing verifier.')\n\n if not self.request_validator.check_verifier(request.verifier):\n raise errors.InvalidRequestError(\n description='Invalid verifier format.')\n\n if not self.request_validator.validate_timestamp_and_nonce(\n request.client_key, request.timestamp, request.nonce, request,\n request_token=request.resource_owner_key):\n return False, request\n\n valid_client = self.request_validator.validate_client_key(\n request.client_key, request)\n if not valid_client:\n request.client_key = self.request_validator.dummy_client\n\n valid_resource_owner = self.request_validator.validate_request_token(\n request.client_key, request.resource_owner_key, request)\n if not valid_resource_owner:\n request.resource_owner_key = self.request_validator.dummy_request_token\n\n valid_verifier = self.request_validator.validate_verifier(\n request.client_key,\n request.resource_owner_key,\n request.verifier,\n request)\n\n valid_signature = self._check_signature(request, is_token_request=True)\n\n request.validator_log['client'] = valid_client\n request.validator_log['resource_owner'] = valid_resource_owner\n request.validator_log['verifier'] = valid_verifier\n request.validator_log['signature'] = valid_signature\n\n v = all((valid_client, valid_signature))\n if not v:\n log.info(\"[Failure] request verification failed.\")\n log.info(\"Valid client:, %s\", valid_client)\n log.info(\"Valid token:, %s\", valid_resource_owner)\n log.info(\"Valid verifier:, %s\", valid_verifier)\n log.info(\"Valid signature:, %s\", valid_signature)\n return v, request", - "score": 0.7142857142857143 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/_util/func/utilfunccode.py", - "function_name": "get_func_code_or_none", - "test_info": { - "success": false, - "failed": 3, - "passed": 1127, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a20_util/func/test_utilfunccode.py::test_get_func_code_or_none\nLocation: /usr/lib/python3.12/re/__init__.py:177\nError: TypeError: expected string or bytes-like object, got 'NoneType'\n\nTraceback:\n\n> def test_get_func_code_or_none() -> None:\n '''\n Test usage of the\n :func:`beartype._util.func.utilfunccode.get_func_code_or_none`\n function.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer test-specific imports.\n from beartype.roar._roarexc import _BeartypeUtilCallableException\n from beartype.roar._roarwarn import _BeartypeUtilCallableWarning\n from beartype._util.func.utilfunccode import get_func_code_or_none\n from beartype._util.py.utilpyversion import (\n IS_PYTHON_AT_LEAST_3_11,\n )\n from beartype_test.a00_unit.data.util.func.data_utilfunccode import (\n of_vapours,\n will_be_the_dome,\n thou_dirge,\n yellow,\n )\n from collections.abc import Callable\n from pytest import warns\n from re import escape, search\n \n # ..................{ NON-LAMBDA }..................\n # Assert this getter accepts C-based callables with \"None\"\n assert get_func_code_or_none(iter) is None\n \n # Assert this getter accepts a dynamically declared callable with \"None\".\n assert get_func_code_or_none(of_vapours) is None\n \n # Assert this getter accepts a physically declared pure-Python non-lambda\n # callable with the full definition of that callable.\n assert get_func_code_or_none(will_be_the_dome) == \"\"\"def will_be_the_dome():\n '''\n Arbitrary non-lambda function physically declared by this submodule.\n '''\n \n return 'of a vast sepulchre'\n \"\"\"\n \n # ..................{ LAMBDA }..................\n def _assert_lambda_args_0_body_is(\n func: Callable,\n func_code_body: str,\n ) -> None:\n '''\n Test-specific function asserting that the body of the passed\n **argumentless lambda function** (i.e., lambda function accepting *no*\n parameters) is exactly the passed string.\n \n This function enables the bodies of lambda functions to be portably\n tested across distinct Python versions.\n \n Parameters\n ----------\n func : Callable\n Lambda function to test this string against.\n func_code_body : str\n Expected body of this lambda function to be tested for.\n '''\n \n # Regular expression matching the leading prefix of the source code\n # underlying this lambda.\n LAMBDA_ARGS_0_CODE_PREFIX = (\n # Under Python >= 3.11, this code is no longer erroneously prefixed\n # by an assignment statement globalizing this lambda.\n r'lambda: '\n if IS_PYTHON_AT_LEAST_3_11 else\n # Under Python 3.9 and 3.10, this code is typically erroneously\n # prefixed by an assignment statement globalizing this lambda but\n # nonetheless has an accidental space inserted inappropriately.\n r'lambda : '\n )\n \n # Regular expression matching this prefix followed by this body,\n # escaped to avoid unsafe interpretation as regular expressions.\n func_code_regex = (\n fr'^{LAMBDA_ARGS_0_CODE_PREFIX}{escape(func_code_body)}$')\n \n # Original source code of this lambda.\n func_code = get_func_code_or_none(func)\n \n # Assert this code is prefixed by the expected substring followed by the\n # passed body of this lambda.\n assert search(pattern=func_code_regex, string=func_code) is not None\n \n # ..................{ PASS }..................\n # Assert this getter accepts a physically declared pure-Python lambda\n # function in which only one lambda is declared on its source code line\n # with the embedded definition of that function.\n> _assert_lambda_args_0_body_is(\n func=thou_dirge,\n func_code_body=\"'Of the dying year, to which this closing night'\",\n )\n\n> assert search(pattern=func_code_regex, string=func_code) is not None\n\n> def search(pattern, string, flags=0):\n \"\"\"Scan through string looking for a match to the pattern, returning\n a Match object, or None if no match was found.\"\"\"\n> return _compile(pattern, flags).search(string)\nE TypeError: expected string or bytes-like object, got 'NoneType'\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a20_util/func/test_utilfunccode.py", - "test_get_func_code_or_none" - ], - [ - "beartype_test/a00_unit/a40_api/vale/_is/test_valeis.py", - "test_api_vale_is_pass" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 27.461376000000023, - "in_degree": 1, - "true_in_degree": 1.8, - "out_degree": 7, - "betweenness": 3.793462238793029e-05, - "pagerank": 0.00032597837985769027, - "harmonic": 0.03577302631578947, - "bidirectional_harmonic": 0.23162605851750598, - "degree": 8 - }, - "line_count": 57, - "code_line_count": 57, - "cyclomatic": 7, - "halstead_volume": 13.931568569324174, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def get_func_code_or_none(\n func: Callable,\n warning_cls: TypeWarning = _BeartypeUtilCallableWarning,\n) -> Optional[str]:\n from beartype._util.func.utilfunctest import is_func_lambda\n from beartype._util.text.utiltextlabel import label_callable\n\n if is_func_lambda(func):\n return None\n try:\n lambda_file_code = get_func_file_code_lines_or_none(\n func=func, warning_cls=warning_cls)\n\n if lambda_file_code:\n func_codeobj = get_func_codeobj(func)\n\n if len(lambda_file_code) >= _LAMBDA_CODE_FILESIZE_MAX:\n issue_warning(\n cls=warning_cls,\n message=(\n f'{label_callable(func)} not parsable, '\n f'as file size exceeds safe maximum '\n f'{_LAMBDA_CODE_FILESIZE_MAX}MB.'\n ),\n )\n else:\n ast_tree = ast_parse(lambda_file_code)\n lambda_node_unparser = _LambdaNodeUnparser(\n lambda_lineno=func_codeobj.co_firstlineno)\n lambda_node_unparser.visit(ast_tree)\n lambdas_code = lambda_node_unparser.lambdas_code\n if lambdas_code:\n if len(lambdas_code) >= 2:\n lambdas_code_str = '\\n '.join(lambdas_code)\n issue_warning(\n cls=warning_cls,\n message=(\n f'{label_callable(func)} ambiguous, '\n f'as that line defines '\n f'{len(lambdas_code)} lambdas; '\n f'arbitrarily selecting first '\n f'lambda:\\n{lambdas_code_str}'\n ),\n )\n return lambdas_code[0]\n else:\n issue_warning(\n cls=warning_cls,\n message=f'{label_callable(func)} not found.',\n )\n except Exception:\n issue_warning(\n cls=warning_cls,\n message=(\n f'{label_callable(func)} not parsable:\\n'\n f'{format_exc()}'\n ),\n )\n return get_func_code_lines_or_none(func=func, warning_cls=warning_cls)", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/datasets/febrl.py", - "function_name": "_febrl_links", - "test_info": { - "success": false, - "failed": 6, - "passed": 972, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_datasets.py::test_febrl_dedup_links[load_febrl1-1000-500]\nLocation: /tmp/benchmark_b7bhztyk/tests/test_datasets.py:41\nError: AssertionError: assert 1500 == 500\n + where 1500 = len(MultiIndex([( 'rec-223-org', 'rec-223-org'),\\n ( 'rec-122-org', 'rec-122-org'),\\n ( 'rec-37... ( 'rec-212-org', 'rec-212-dup-0'),\\n ( 'rec-212-org', 'rec-212-org')],\\n length=1500))\n\nTraceback:\n\n> @pytest.mark.parametrize(\"dataset,nrows,nlinks\", FEBRL_DEDUP)\n def test_febrl_dedup_links(dataset, nrows, nlinks):\n df, links = dataset(return_links=True)\n assert isinstance(df, pandas.DataFrame)\n assert len(df) == nrows\n> assert len(links) == nlinks\nE AssertionError: assert 1500 == 500\nE + where 1500 = len(MultiIndex([( 'rec-223-org', 'rec-223-org'),\\n ( 'rec-122-org', 'rec-122-org'),\\n ( 'rec-37... ( 'rec-212-org', 'rec-212-dup-0'),\\n ( 'rec-212-org', 'rec-212-org')],\\n length=1500))\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_datasets.py", - "test_febrl_dedup_links[load_febrl1-1000-500]" - ], - [ - "tests/test_datasets.py", - "test_febrl_dedup_links[load_febrl2-5000-1934]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.0, - "in_degree": 3, - "true_in_degree": 3.0, - "out_degree": 0, - "betweenness": 0.0, - "pagerank": 0.0015234375, - "harmonic": 0.0, - "bidirectional_harmonic": 0.017189835575485802, - "degree": 3 - }, - "line_count": 15, - "code_line_count": 15, - "cyclomatic": 1, - "halstead_volume": 4.754887502163469, - "halstead_difficulty": 0.5 - }, - "corruption": { - "code": "def _febrl_links(df):\n \"\"\"Get the links of a FEBRL dataset.\"\"\"\n\n index = df.index.to_series()\n keys = index.str.extract(r\"rec-(\\d+)\", expand=True)[0]\n\n index_int = numpy.arange(len(df))\n\n df_helper = pandas.DataFrame({\"key\": keys, \"index\": index_int})\n\n # merge the two frame and make MultiIndex.\n pairs_df = df_helper.merge(df_helper, on=\"key\")[['index_x', 'index_y']]\n # include self-links as well as duplicates\n pairs_df = pairs_df[pairs_df['index_x'] >= pairs_df['index_y']]\n\n return pandas.MultiIndex(\n levels=[df.index.values, df.index.values],\n codes=[pairs_df['index_x'].values, pairs_df['index_y'].values],\n names=[None, None],\n verify_integrity=False,\n )\n", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "sw_apply", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_incorrect_input[smith_waterman]\nLocation: /tmp/benchmark_um7sna56/tests/test_compare.py:1289\nError: Failed: DID NOT RAISE (, )\n\nTraceback:\n\n> @pytest.mark.parametrize(\"alg\", STRING_SIM_ALGORITHMS)\n def test_incorrect_input(self, alg):\n A = DataFrame({\"col\": [1, 1, 1, nan, 0]})\n B = DataFrame({\"col\": [1, 1, 1, nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n> with pytest.raises((TypeError, AttributeError)):\nE Failed: DID NOT RAISE (, )\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_incorrect_input[smith_waterman]" - ], - [ - "tests/test_compare.py", - "test_string_algorithms_nan[smith_waterman]" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": " def sw_apply(t):\n \"\"\"\n sw_apply(t)\n\n A helper function that is applied to each pair of records\n in s1 and s2. Assigns a similarity score to each pair,\n between 0 and 1. Used by the pandas.apply method.\n\n Parameters\n ----------\n t : pandas.Series\n A pandas Series containing two strings to be compared.\n\n Returns\n -------\n Float\n A similarity score between 0 and 1.\n \"\"\"\n str1 = t[0]\n str2 = t[1]\n\n def compute_score():\n \"\"\"\n compute_score()\n\n The helper function that produces the non-normalized\n similarity score between two strings. The scores are\n determined using the Smith-Waterman dynamic programming\n algorithm. The scoring scheme is determined from the\n parameters provided to the parent smith_waterman_similarity()\n function.\n\n Returns\n -------\n Float\n A score 0 or greater. Indicates similarity between two strings.\n \"\"\"\n\n # Initialize the score matrix with 0s\n\n m = [[0] * (1 + len(str2)) for i in range(1 + len(str1))]\n\n # Initialize the trace matrix with empty lists\n trace = [[[] for _ in range(1 + len(str2))] for _ in range(1 + len(str1))]\n\n # Initialize the highest seen score to 0\n highest = 0\n\n # Iterate through the matrix\n for x in range(1, 1 + len(str1)):\n for y in range(1, 1 + len(str2)):\n # Calculate Diagonal Score\n if str1[x - 1] == str2[y - 1]:\n # If characters match, add the match score to the\n # diagonal score\n diagonal = m[x - 1][y - 1] + match\n else:\n # If characters do not match, add the mismatch score\n # to the diagonal score\n diagonal = m[x - 1][y - 1] + mismatch\n\n # Calculate the Left Gap Score\n if \"H\" in trace[x - 1][y]:\n # If cell to the left's score was calculated based on\n # a horizontal gap, add the gap continuation penalty\n # to the left score.\n gap_horizontal = m[x - 1][y] + gap_continue\n else:\n # Otherwise, add the gap start penalty to the left\n # score\n gap_horizontal = m[x - 1][y] + gap_start\n\n # Calculate the Above Gap Score\n if \"V\" in trace[x][y - 1]:\n # If above cell's score was calculated based on a\n # vertical gap, add the gap continuation penalty to\n # the above score.\n gap_vertical = m[x][y - 1] + gap_continue\n else:\n # Otherwise, add the gap start penalty to the above\n # score\n gap_vertical = m[x][y - 1] + gap_start\n\n # Choose the highest of the three scores\n score = max(diagonal, gap_horizontal, gap_vertical)\n\n if score <= 0:\n # If score is less than 0, boost to 0\n score = 0\n else:\n # If score is greater than 0, determine whether it was\n # calculated based on a diagonal score, horizontal gap,\n # or vertical gap. Store D, H, or V in the trace matrix\n # accordingly.\n if score == diagonal:\n trace[x][y].append(\"D\")\n if score == gap_horizontal:\n trace[x][y].append(\"H\")\n if score == gap_vertical:\n trace[x][y].append(\"V\")\n\n # If the cell's score is greater than the highest score\n # previously present, record the score as the highest.\n if score > highest:\n highest = score\n\n # Set the cell's score to score\n m[x][y] = score\n\n # After iterating through the entire matrix, return the highest\n # score found.\n return highest\n\n def normalize(score):\n \"\"\"\n normalize(score)\n\n A helper function used to normalize the score produced by\n compute_score() to a score between 0 and 1. The method for\n normalization is determined by the norm argument provided\n to the parent, smith_waterman_similarity function.\n\n Parameters\n ----------\n score : Float\n The score produced by the compute_score() function.\n\n Returns\n -------\n Float\n A normalized score between 0 and 1.\n \"\"\"\n if norm == \"min\":\n # Normalize by the shorter string's length\n return score / (min(len(str1), len(str2)) * match)\n if norm == \"max\":\n # Normalize by the longer string's length\n return score / (max(len(str1), len(str2)) * match)\n if norm == \"mean\":\n # Normalize by the mean length of the two strings\n return score / ((len(str1) + len(str2)) * match)\n else:\n warnings.warn(\n \"Unrecognized longest common substring normalization. \"\n 'Defaulting to \"mean\" method.',\n stacklevel=2,\n )\n return 2 * score / ((len(str1) + len(str2)) * match)\n\n try:\n if len(str1) == 0 or len(str2) == 0:\n return 0\n return normalize(compute_score())\n\n except Exception:\n return np.nan", - "score": 0.33333333333333337 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/claw/_ast/_clawastutil.py", - "function_name": "BeartypeNodeTransformerUtilityMixin._decorate_node_beartype", - "test_info": { - "success": false, - "failed": 8, - "passed": 1114, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a90_claw/a00_core/test_claw_api.py::test_claw_api\nLocation: /tmp/benchmark_dh1pmnuc/beartype/claw/_ast/clawastmain.py:58\nError: File \"/tmp/benchmark_dh1pmnuc/beartype/claw/_ast/_clawastutil.py\", line 131\n - decoration_position = (\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nSyntaxError: cannot assign to expression\n\nTraceback:\n\n> @fixture(autouse=True, scope='function')\n def clean_claws() -> None: # <-- heh. get it... clean *CLAWS*? it is punny.\n '''\n Permanently, silently, and recursively remove all **bytecode files** (i.e.,\n pure-Python bytecode compiled to platform-dependent temporary files residing\n in temporary ``__pycache__/`` subdirectories) of the test-specific\n :mod:`beartype_test.a00_unit.data` subpackage and all subsubpackages of that\n subpackage regardless of depth.\n \n Note that this unit test-scoped fixture is implicitly performed *before*\n each unit test transitively defined in sibling and child submodules of the\n subpackage directly containing this submodule. Why? Because failing to do so\n would invite subtle but easily reproducible desynchronization woes between\n those files and more recent changes to the implementation of the\n :mod:`beartype.claw` subpackage in the main codebase.\n \n See Also\n --------\n :func:`beartype._util.path.utilpathremove.remove_package_bytecode_files`\n Further details.\n '''\n \n # ..................{ IMPORTS }..................\n # Defer fixture-specific imports.\n> from beartype.claw._package.clawpkgcontext import packages_trie_cleared\n\n> from beartype.claw._clawmain import (\n\n> from beartype.claw._package.clawpkghook import hook_packages\n\n> from beartype.claw._package.clawpkgtrie import (\n\n> from beartype.claw._importlib.clawimppath import remove_beartype_pathhook\n\n> from beartype.claw._importlib._clawimpload import BeartypeSourceFileLoader\n\n> from beartype.claw._ast.clawastmain import BeartypeNodeTransformer\n\n> #!/usr/bin/env python3\n # --------------------( LICENSE )--------------------\n # Copyright (c) 2014-2025 Beartype authors.\n # See \"LICENSE\" for further details.\n \n '''\n Beartype **abstract syntax tree (AST) transformers** (i.e., low-level classes\n instrumenting well-typed third-party modules with runtime type-checking\n dynamically generated by the :func:`beartype.beartype` decorator).\n \n This private submodule is *not* intended for importation by downstream callers.\n '''\n \n # ....................{ TODO }....................\n #FIXME: [PEP 484] Additionally define:\n #* Generator transformers. The idea here is that @beartype *CAN* actually\n # automatically type-check generator yields, sends, and returns at runtime.\n # How? By automatically injecting appropriate die_if_unbearable() calls\n # type-checking the values to be yielded, sent, and returned against the\n # appropriate type hints of the current generator factory *BEFORE* yielding,\n # sending, and returning those values. Shockingly, typeguard already does this\n # -- which is all manner of impressive. See the\n # TypeguardTransformer._use_memo() context manager for working code. Wow!\n #\n #See also:\n # https://github.com/agronholm/typeguard/blob/master/src/typeguard/_transformer.py\n \n #FIXME: [SPEED] Consider generalizing the BeartypeNodeTransformer.__new__()\n #class method to internally cache and return \"BeartypeNodeTransformer\" instances\n #depending on the passed \"conf_beartype\" parameter. In general, most codebases\n #will only leverage a single @beartype configuration (if any @beartype\n #configuration at all); ergo, caching improves everything by enabling us to\n #reuse the same \"BeartypeNodeTransformer\" instance for every hooked module.\n #Score @beartype! See the BeartypeConf.__new__() method for relevant logic. \\o/\n #FIXME: Oh, wait. We probably do *NOT* want to cache -- at least, not without\n #defining a comparable reinit() method as we do for \"BeartypeDecorMeta\". After\n #retrieving a cached \"BeartypeNodeTransformer\" instance, we'll need to\n #immediately call BeartypeNodeTransformer.reinit() to reinitialize that\n #instance.\n #\n #This is all feasible, of course -- but let's just roll with the naive\n #implementation for now, please.\n \n # ....................{ IMPORTS }....................\n from ast import (\n AST,\n ClassDef,\n Constant,\n Expr,\n ImportFrom,\n Module,\n NodeTransformer,\n )\n from beartype.claw._ast.pep.clawastpep526 import (\n BeartypeNodeTransformerPep526Mixin)\n from beartype.claw._ast.pep.clawastpep695 import (\n BeartypeNodeTransformerPep695Mixin)\n> from beartype.claw._ast._clawastutil import BeartypeNodeTransformerUtilityMixin\nE File \"/tmp/benchmark_dh1pmnuc/beartype/claw/_ast/_clawastutil.py\", line 131\nE - decoration_position = (\nE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nE SyntaxError: cannot assign to expression\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a90_claw/a00_core/test_claw_api.py", - "test_claw_api" - ], - [ - "beartype_test/a00_unit/a90_claw/a90_hook/test_claw_extraprocess.py", - "test_claw_extraprocess_executable_submodule" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 5.984000000000002, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 3, - "betweenness": 2.7096158848521633e-05, - "pagerank": 0.00042077175697865355, - "harmonic": 0.00932017543859649, - "bidirectional_harmonic": 0.22337300400622792, - "degree": 5 - }, - "line_count": 32, - "code_line_count": 32, - "cyclomatic": 7, - "halstead_volume": 25.26619429851844, - "halstead_difficulty": 1.2 - }, - "corruption": { - "code": " def _decorate_node_beartype(\n self, node: NodeDecoratable, conf: BeartypeConf) -> None:\n '''\n Add a new **child beartype decoration node** (i.e., abstract syntax tree\n (AST) node applying the :func:`beartype.beartype` decorator configured\n by the passed beartype configuration) to the passed **parent decoratable\n node** (i.e., AST node encapsulating the definition of a pure-Python\n object supporting decoration by one or more ``\"@\"``-prefixed\n decorations, including both pure-Python classes *and* callables).\n\n Note that this function **prepends** rather than appends this child\n decoration node to the beginning of the list of all child decoration\n nodes for this parent decoratable node. Since that list is \"stored\n outermost first (i.e. the first in the list will be applied last)\",\n prepending guarantees that the beartype decorator will be applied last\n (i.e., *after* all other decorators). This ensures that explicitly\n configured beartype decorations applied to this decoratable by the end\n user (e.g., ``@beartype(conf=BeartypeConf(...))``) assume precedence\n over implicitly configured beartype decorations applied by this\n function.\n\n Parameters\n ----------\n node : AST\n **Decoratable node** (i.e., parent class or callable node) to add a\n new child beartype decoration node to.\n conf : BeartypeConf\n **Beartype configuration** (i.e., dataclass configuring the\n :mod:`beartype.beartype` decorator for some decoratable object(s)\n decorated by a parent node passing this dataclass to that\n decorator).\n '''\n assert isinstance(node, AST), f'{repr(node)} not AST node.'\n assert isinstance(conf, BeartypeConf), (\n f'{repr(conf)} not configuration.')\n\n # Child decoration node decorating that callable by the @beartype\n # decorator.\n beartype_decorator: expr = Name(\n id=BEARTYPE_DECORATOR_FUNC_NAME, ctx=NODE_CONTEXT_LOAD)\n\n # Copy all source code metadata from this parent callable node onto this\n # child decoration node.\n copy_node_metadata(node_src=node, node_trg=beartype_decorator)\n\n # If the current beartype configuration is *NOT* the default beartype\n # configuration, this configuration is a user-defined beartype\n # configuration which *MUST* be passed to a call to the @beartype\n # decorator. Merely referencing this decorator does *NOT* suffice. In\n # this case...\n if conf != BEARTYPE_CONF_DEFAULT:\n # Replace the reference to this decorator defined above with a\n # call to this decorator passed this configuration.\n beartype_decorator = Call(\n func=beartype_decorator,\n args=[],\n # Node encapsulating the passing of this configuration as\n # the \"conf\" keyword argument to this call.\n keywords=[\n self._make_node_keyword_conf_beartype(node_sibling=node)],\n )\n\n # Copy all source code metadata from this parent callable node onto\n # this child call node.\n copy_node_metadata(node_src=node, node_trg=beartype_decorator)\n # Else, this configuration is simply the default beartype configuration.\n # In this case, avoid passing that configuration to the @beartype\n # decorator for both efficiency and simplicity.\n\n # Decorator position (i.e., location to which the @beartype decorator\n # will be implicitly injected into the existing chain of zero or more\n # decorators already decorating this parent decoratable node), defined\n # as either...\n- decoration_position = (\n- # If this parent decoratable node is a parent class node, the\n- # class-specific decorator position.\n- conf.claw_decoration_position_types\n- if isinstance(node, ClassDef) else\n- # Else, this parent decoratable node is *NOT* a parent class node.\n- # By process of elimination, this parent decoratable node *MUST* be\n- # a parent callable node. In this case, fallback to the\n- # callable-specific decorator position.\n- conf.claw_decoration_position_funcs\n- )\n+ decoration_position = (\n+ # Mix-up: using function-specific position for classes...\n+ conf.claw_decoration_position_funcs\n+ if isinstance(node, ClassDef) else\n+ # ...and type-specific position for functions.\n+ conf.claw_decoration_position_types\n+ )\n\n # If injecting the @beartype decorator last, prepend this child\n # decoration node to the beginning of the list of all child decoration\n # nodes for this parent decoratable node. Since this list is \"stored\n # outermost first (i.e. the first in the list will be applied last)\",\n # prepending guarantees that our decorator will be applied last (i.e.,\n # *AFTER* all subsequent decorators).\n if decoration_position is BeartypeDecorationPosition.LAST:\n node.decorator_list.insert(0, beartype_decorator)\n # If injecting the @beartype decorator first, append this child\n # decoration node to the end of the list of all child decoration nodes\n # for this parent decoratable node.\n elif decoration_position is BeartypeDecorationPosition.FIRST:\n node.decorator_list.append(beartype_decorator)\n # Else, an unrecognized decorator position was configured. In this case,\n # raise an exception. Note that this should *NEVER* occur.\n else: # pragma: no cover\n raise BeartypeClawImportConfException(\n f'Beartype configuration {repr(conf)} '\n f'decorator position {repr(decoration_position)} unsupported.'\n )", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/preprocessing/cleaning.py", - "function_name": "strip_accents_fn_wrapper", - "test_info": { - "success": false, - "failed": 1, - "passed": 977, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_preprocessing.py::TestCleaningStandardise::test_clean_accent_stripping\nLocation: testing.pyx:173\nError: AssertionError: Series are different\n\nSeries values are different (50.0 %)\n[index]: [0, 1]\n[left]: [sdfsdf, without]\n[right]: [osdfesdfe, without]\nAt positional index 0, first diff: sdfsdf != osdfesdfe\n\nTraceback:\n\n> def test_clean_accent_stripping(self):\n values = pd.Series([\"\u0151sdf\u00e9sdf\u00eb\", \"without\"])\n expected = pd.Series([\"osdfesdfe\", \"without\"])\n \n values_unicode = pd.Series([\"\u0151sdf\u00e9sdf\u00eb\", \"without\"])\n expected_unicode = pd.Series([\"osdfesdfe\", \"without\"])\n \n # values_callable = pd.Series([u'\u0151sdf\u00e9sdf\u00eb', u'without'])\n # expected_callable = pd.Series([u'\u0151sdf\u00e9sdf\u00eb', u'without'])\n \n # # Callable.\n # pdt.assert_series_equal(\n # clean(values_callable, strip_accents=lambda x: x),\n # expected_callable)\n \n # Check if series are identical.\n> pdt.assert_series_equal(clean(values, strip_accents=\"unicode\"), expected)\n\n> ???\n\n> > ???\nE AssertionError: Series are different\nE \nE Series values are different (50.0 %)\nE [index]: [0, 1]\nE [left]: [sdfsdf, without]\nE [right]: [osdfesdfe, without]\nE At positional index 0, first diff: sdfsdf != osdfesdfe\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_preprocessing.py", - "test_clean_accent_stripping" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def strip_accents_fn_wrapper(x):\n if sys.version_info[0] >= 3:\n if isinstance(x, str):\n return x\n else:\n return x\n else:\n if isinstance(x, unicode): # noqa\n return strip_accents_fn(x)\n else:\n return x", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/recordlinkage/", - "code_path": "recordlinkage", - "name": "recordlinkage", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/J535D165/recordlinkage.git", - "stats": { - "exists": true, - "files_count": 41, - "functions_count": 353, - "total_lines": 8620, - "avg_lines_per_file": 210.2439024390244, - "avg_lines_per_func": 24.41926345609065 - } - }, - "fpath": "recordlinkage/algorithms/string.py", - "function_name": "cosine_similarity", - "test_info": { - "success": false, - "failed": 2, - "passed": 976, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_compare.py::TestCompareStrings::test_fuzzy\nLocation: /tmp/benchmark_wf33kged/tests/test_compare.py:1218\nError: assert np.False_\n + where np.False_ = all(0)\n + where all = 0 0 False\\n1 1 True\\n2 2 True\\n3 3 True\\n4 4 True\\ndtype: bool.all\n + where 0 0 False\\n1 1 True\\n2 2 True\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\n + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.000001 1.000000 1.000000 1.00000...3 3 0.000000 0.00 0.000000 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.000000 0.000000 0.000000 0.000000 <= 1.all\n\nTraceback:\n\n> def test_fuzzy(self):\n A = DataFrame({\"col\": [\"str_abc\", \"str_abc\", \"str_abc\", nan, \"hsdkf\"]})\n B = DataFrame({\"col\": [\"str_abc\", \"str_abd\", \"jaskdfsd\", nan, nan]})\n ix = MultiIndex.from_arrays([A.index.values, B.index.values])\n \n comp = recordlinkage.Compare()\n comp.string(\"col\", \"col\", method=\"jaro\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"q_gram\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"cosine\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"jaro_winkler\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"dameraulevenshtein\", missing_value=0)\n comp.string(\"col\", \"col\", method=\"levenshtein\", missing_value=0)\n result = comp.compute(ix, A, B)\n \n print(result)\n \n assert result.notnull().all(1).all(0)\n assert (result[result.notnull()] >= 0).all(1).all(0)\n> assert (result[result.notnull()] <= 1).all(1).all(0)\nE assert np.False_\nE + where np.False_ = all(0)\nE + where all = 0 0 False\\n1 1 True\\n2 2 True\\n3 3 True\\n4 4 True\\ndtype: bool.all\nE + where 0 0 False\\n1 1 True\\n2 2 True\\n3 3 True\\n4 4 True\\ndtype: bool = all(1)\nE + where all = 0 1 2 3 4 5\\n0 0 1.000000 1.00 1.000001 1.000000 1.000000 1.00000...3 3 0.000000 0.00 0.000000 0.000000 0.000000 0.000000\\n4 4 0.000000 0.00 0.000000 0.000000 0.000000 0.000000 <= 1.all\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_compare.py", - "test_fuzzy" - ], - [ - "tests/test_compare.py", - "test_string_algorithms[cosine]" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 0.8, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0006696428571428573, - "harmonic": 0.004484304932735426, - "bidirectional_harmonic": 0.08540546399290788, - "degree": 1 - }, - "line_count": 21, - "code_line_count": 21, - "cyclomatic": 4, - "halstead_volume": 36.541209043760986, - "halstead_difficulty": 1.5 - }, - "corruption": { - "code": "def cosine_similarity(s1, s2, include_wb=True, ngram=(2, 2)):\n if len(s1) != len(s2):\n raise ValueError(\"Arrays or Series have to be same length.\")\n\n if len(s1) == len(s2) == 0:\n return []\n\n analyzer = \"char_wb\" if include_wb is True else \"char\"\n vectorizer = CountVectorizer(\n analyzer=analyzer, strip_accents=\"unicode\", ngram_range=ngram\n )\n\n data = pandas.concat([s1, s2]).fillna(\"\")\n vec_fit = vectorizer.fit_transform(data)\n\n def _metric_sparse_cosine(u, v):\n a = np.sqrt(u.multiply(u).sum(axis=1))\n b = np.sqrt(v.multiply(v).sum(axis=1))\n ab = v.multiply(u).sum(axis=1)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n m = np.divide(ab, np.multiply(a, b)).A1\n\n m = m + 1e-6\n\n return m\n\n return _metric_sparse_cosine(vec_fit[: len(s1)], vec_fit[len(s1) :])", - "score": 0.5 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/beartype/", - "code_path": "beartype", - "name": "beartype", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/beartype/beartype.git", - "stats": { - "exists": true, - "files_count": 374, - "functions_count": 980, - "total_lines": 86788, - "avg_lines_per_file": 232.05347593582889, - "avg_lines_per_func": 88.55918367346939 - } - }, - "fpath": "beartype/door/_func/infer/collection/infercollectionitems.py", - "function_name": "_infer_hint_mapping_items", - "test_info": { - "success": false, - "failed": 1, - "passed": 1129, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: beartype_test/a00_unit/a40_api/door/a90_func/test_door_func_infer_hint.py::test_door_infer_hint\nLocation: /tmp/benchmark_fw3pk1l6/beartype_test/a00_unit/a40_api/door/a90_func/test_door_func_infer_hint.py:66\nError: assert typing.Annotated[collections.abc.Mapping[bytes, str], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]] == typing.Annotated[collections.abc.Mapping[str, bytes], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]]\n + where typing.Annotated[collections.abc.Mapping[bytes, str], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]] = (, conf=BeartypeConf())\n\nTraceback:\n\n> def test_door_infer_hint(\n door_cases_infer_hint: (\n 'Dict[beartype.BeartypeConf, Iterable[Tuple[object, object]]]')) -> None:\n '''\n Test the :func:`beartype.door.infer_hint` function.\n \n Parameters\n ----------\n door_cases_infer_hint : Dict[beartype.BeartypeConf, Iterable[Tuple[object, object]]]\n Dictionary mapping from each relevant beartype configuration to a\n corresponding iterable of all **type hint inference cases** specific to\n that configuration.\n '''\n \n # ....................{ IMPORTS }....................\n # Defer test-specific imports.\n from beartype.door import infer_hint\n from beartype.roar import BeartypeConfException\n from beartype._conf.confcommon import get_beartype_conf_strategy_on\n from pytest import raises\n \n # ....................{ LOCALS }....................\n # Default linear-time configuration.\n CONF_STRATEGY_ON = get_beartype_conf_strategy_on()\n \n # ....................{ PASS }....................\n # For each relevant beartype configuration...\n for conf, cases in door_cases_infer_hint.items():\n # If this is the default linear-time configuration...\n if conf == CONF_STRATEGY_ON:\n # For each test object and expected type hint to be inferred from\n # that object...\n for obj, hint in cases:\n # Assert this function returns this type hint for this object\n # *WITHOUT* explicitly passing this configuration. Doing so\n # exercises that this function behaves as expected when passed\n # *NO* configuration.\n assert infer_hint(obj) == hint\n # Else, this is a non-default configuration. In this case...\n else:\n # For each test object and expected type hint to be inferred from\n # that object...\n for obj, hint in cases:\n # Assert this function returns this type hint for this object\n # under this non-default configuration.\n> assert infer_hint(obj, conf=conf) == hint\nE assert typing.Annotated[collections.abc.Mapping[bytes, str], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]] == typing.Annotated[collections.abc.Mapping[str, bytes], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]]\nE + where typing.Annotated[collections.abc.Mapping[bytes, str], beartype.vale.IsInstance[beartype_test.a00_unit.data.data_type.ClassMapping]] = (, conf=BeartypeConf())\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "beartype_test/a00_unit/a40_api/door/a90_func/test_door_func_infer_hint.py", - "test_door_infer_hint" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 29.40445900800002, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 2, - "betweenness": 0.0, - "pagerank": 0.00024630541871921186, - "harmonic": 0.03312643588137008, - "bidirectional_harmonic": 0.20547468339409214, - "degree": 2 - }, - "line_count": 60, - "code_line_count": 60, - "cyclomatic": 8, - "halstead_volume": 100.07820003461549, - "halstead_difficulty": 2.2857142857142856 - }, - "corruption": { - "code": "def _infer_hint_mapping_items(\n obj: MappingABC,\n hint_factory: object,\n conf: BeartypeConf,\n __beartype_obj_ids_seen__: FrozenSetInts,\n) -> object:\n '''\n Type hint recursively validating the passed **mapping** (i.e.,\n collections whose type hint factories are subscriptable by a pair of child\n key and value type hints) and all keys *and* values transitively reachable\n from this mapping, defined by subscripting the passed type hint factory by\n the unions of the child type hints validating these keys and values.\n\n See Also\n --------\n :func:`.infer_hint_collection_items`\n Further details.\n '''\n # Note that we intentionally do *NOT* test whether this object also\n # satisfies the more fine-grained \"collections.abc.Mapping\" protocol. Why?\n # Because that protocol fails to support so-called \"virtual subclasses\" as\n # of Python 3.13 and is thus fundamentally broken. See also the parent\n # infer_hint_collection_items() function \"origin_type\" parameter. *sigh*\n\n # ....................{ IMPORTS }....................\n # Avoid circular import dependencies.\n from beartype.door._func.infer.inferhint import infer_hint\n\n # ....................{ LOCALS }....................\n # Child key and value hints to subscript this factory with, defaulting to\n # the ignorable \"object\" superclass.\n hints_key: object = object\n hints_value: object = object\n\n # ....................{ RECURSION }....................\n # Note that the caller guarantees this mapping to be non-empty.\n\n # If either...\n if (\n # This mapping contains only one key-value pair *OR*...\n #\n # Note that this is a negligible optimization for this common case.\n len(obj) == 1 or\n # The caller requested O(1) constant-time complexity...\n conf.strategy is BeartypeStrategy.O1\n ):\n # First key-value pair of this mapping.\n key, value = next(iter(obj.items()))\n\n # Child key and value type hints validating this key and value.\n hints_key = infer_hint(\n obj=key,\n conf=conf,\n __beartype_obj_ids_seen__=__beartype_obj_ids_seen__,\n )\n hints_value = infer_hint(\n obj=value,\n conf=conf,\n __beartype_obj_ids_seen__=__beartype_obj_ids_seen__,\n )\n # Else, the caller did *NOT* request O(1) constant-time complexity.\n #\n # If the caller requested O(n) linear-time complexity...\n elif conf.strategy is BeartypeStrategy.On:\n # Set of all child key and value hints to conjoin into a union.\n hints_key_set = set()\n hints_value_set = set()\n\n # For each key-value pair in this mapping...\n for key, value in obj.items():\n # Child key and value type hints validating this key and value.\n hint_key = infer_hint(\n obj=key,\n conf=conf,\n __beartype_obj_ids_seen__=__beartype_obj_ids_seen__,\n )\n hint_value = infer_hint(\n obj=value,\n conf=conf,\n __beartype_obj_ids_seen__=__beartype_obj_ids_seen__,\n )\n\n # Add this child type hint to this set.\n hints_key_set.add(hint_key)\n hints_value_set.add(hint_value)\n\n # PEP 604- or 484-compliant union of these child key and value hints.\n hints_key = make_hint_pep484604_union(tuple(hints_key_set))\n hints_value = make_hint_pep484604_union(tuple(hints_value_set))\n # Else, the caller did *NOT* request O(n) linear-time complexity.\n #\n # Thus, the caller requested a currently unsupported time complexity. In\n # this case, raise an exception.\n else:\n raise BeartypeConfException(\n f'Beartype configuration {repr(conf)} '\n f'strategy {repr(conf.strategy)} currently unsupported by '\n f'beartype.door.infer_hint() (i.e., neither '\n f'\"BeartypeStrategy.O1\" nor \"BeartypeStrategy.On\").'\n )\n\n # ....................{ SUBSCRIPTION }....................\n # If these child key and value hints are still the ignorable \"object\"\n # superclass, return this factory as is unsubscripted.\n if hints_key is object and hints_value is object:\n hint = hint_factory\n # Else, at least one of these child key or value hints is no longer the\n # ignorable \"object\" superclass. In this case...\n else:\n # Type hint recursively validating this mapping, defined as either...\n hint = (\n # If this mapping is a counter (i.e., instance of the standard\n # \"collections.Counter\" class), subscripting this factory by only\n # this key union. By definition, *ALL* values of *ALL* counters are\n # unconditionally constrained to be integers and thus need *NOT*\n # (and indeed *CANNOT*) be explicitly specified;\n hint_factory[hints_key] # type: ignore[index]\n if hint_factory is Counter else\n # Else, this mapping is *NOT* a counter. In this case, sequentially\n # subscripting this factory by both this value and key union.\n hint_factory[hints_value, hints_key] # type: ignore[index]\n )\n # Return this hint.\n return hint", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/mutmut/", - "code_path": "mutmut", - "name": "mutmut", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/boxed/mutmut", - "stats": { - "exists": true, - "files_count": 2, - "functions_count": 94, - "total_lines": 2019, - "avg_lines_per_file": 1009.5, - "avg_lines_per_func": 21.47872340425532 - } - }, - "fpath": "mutmut/__main__.py", - "function_name": "yield_mutants_for_module", - "test_info": { - "success": false, - "failed": 2, - "passed": 304, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_mutmut3.py::test_yield_mutants_for_module\nLocation: /tmp/benchmark_iwq3rorj/tests/test_mutmut3.py:49\nError: assert \"\\nfrom inspe...'x_foo'\\n\\n\\n\" == \"\\nfrom inspe...'x_foo'\\n\\n\\n\"\n \n Skipping 2188 identical leading characters in diff, use -v to show\n result\n + \n \n \n ...\n \n ...Full output truncated (24 lines hidden), use '-vv' to show\n\nTraceback:\n\n> def test_yield_mutants_for_module():\n source = \"\"\"\n a + 1\n \n def foo(a, b, c):\n return a + b * c\n \"\"\"\n \n expected = trampoline_impl + yield_from_trampoline_impl + \"\"\"\n \n a + 1\n \n def x_foo__mutmut_orig(a, b, c):\n return a + b * c\n \n def x_foo__mutmut_1(a, b, c):\n return a - b * c\n \n def x_foo__mutmut_2(a, b, c):\n return a + b / c\n \n x_foo__mutmut_mutants : ClassVar[MutantDict] = {\n 'x_foo__mutmut_1': x_foo__mutmut_1,\n 'x_foo__mutmut_2': x_foo__mutmut_2\n }\n \n def foo(*args, **kwargs):\n result = _mutmut_trampoline(x_foo__mutmut_orig, x_foo__mutmut_mutants, *args, **kwargs)\n return result\n \n foo.__signature__ = _mutmut_signature(x_foo__mutmut_orig)\n x_foo__mutmut_orig.__name__ = 'x_foo'\n \n \n \"\"\"\n \n node = parse(source)\n result = ''.join([x[1] for x in yield_mutants_for_module(node, no_mutate_lines=[])])\n \n> assert result == expected\nE assert \"\\nfrom inspe...'x_foo'\\n\\n\\n\" == \"\\nfrom inspe...'x_foo'\\n\\n\\n\"\nE \nE Skipping 2188 identical leading characters in diff, use -v to show\nE result\nE + \nE \nE \nE ...\nE \nE ...Full output truncated (24 lines hidden), use '-vv' to show\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_mutmut3.py", - "test_yield_mutants_for_module" - ], - [ - "tests/test_mutmut3.py", - "test_avoid_annotations" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 9.088000000000005, - "in_degree": 1, - "true_in_degree": 2.4400000000000004, - "out_degree": 4, - "betweenness": 0.0030643513789581204, - "pagerank": 0.0022836962022569447, - "harmonic": 0.09363295880149812, - "bidirectional_harmonic": 0.26083467094703044, - "degree": 5 - }, - "line_count": 16, - "code_line_count": 16, - "cyclomatic": 6, - "halstead_volume": 20.89735285398626, - "halstead_difficulty": 0.75 - }, - "corruption": { - "code": "def yield_mutants_for_module(node, no_mutate_lines):\n assert node.type == 'file_input'\n\n # First yield `from __future__`, then the rest\n yield from yield_future_imports(node)\n\n yield 'trampoline_impl', trampoline_impl, None, None\n yield 'trampoline_impl', yield_from_trampoline_impl, None, None\n yield 'filler', '\\n\\n', None, None\n for child_node in node.children:\n if child_node.type == 'funcdef':\n yield from yield_mutants_for_function(child_node, no_mutate_lines=no_mutate_lines)\n elif child_node.type == 'classdef':\n yield from yield_mutants_for_class(child_node, no_mutate_lines=no_mutate_lines)\n elif is_from_future_import_node(child_node):\n # Don't yield `from __future__` after trampoline\n pass\n else:\n yield 'filler', child_node.get_code(), None, None", - "score": 0.8888888888888888 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/simpleai/", - "code_path": "simpleai", - "name": "simpleai", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/simpleai-team/simpleai.git", - "stats": { - "exists": true, - "files_count": 17, - "functions_count": 153, - "total_lines": 2585, - "avg_lines_per_file": 152.05882352941177, - "avg_lines_per_func": 16.895424836601308 - } - }, - "fpath": "simpleai/search/traditional.py", - "function_name": "iterative_limited_depth_first", - "test_info": { - "success": false, - "failed": 2, - "passed": 619, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/machine_learning/test_reinforcement_learning.py::TestBoltzmann_exploration::test_all_equals_utilities\nLocation: /usr/lib/python3.12/unittest/case.py:727\nError: AssertionError: False is not true\n\nTraceback:\n\n> def test_all_equals_utilities(self):\n self.utilities = dict(zip(self.actions, [0, 0, 0]))\n counter = Counter()\n for i in range(100):\n a = boltzmann_exploration(self.actions, self.utilities, 10000000, None)\n counter[a] += 1\n for a, c in list(counter.items()):\n> self.assertTrue(25 <= c <= 40)\nE AssertionError: False is not true\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/machine_learning/test_reinforcement_learning.py", - "test_all_equals_utilities" - ], - [ - "tests/search/test_traditional.py", - "test_iterative_limited_depth_first" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 4.307200000000001, - "in_degree": 0, - "true_in_degree": 0.0, - "out_degree": 1, - "betweenness": 0.0, - "pagerank": 0.0011111111111111113, - "harmonic": 0.02487562189054726, - "bidirectional_harmonic": 0.16631130063965868, - "degree": 1 - }, - "line_count": 14, - "code_line_count": 14, - "cyclomatic": 3, - "halstead_volume": 22.458839376460833, - "halstead_difficulty": 1.875 - }, - "corruption": { - "code": "def iterative_limited_depth_first(problem, graph_search=False, viewer=None):\n '''\n Iterative limited depth first search.\n\n If graph_search=True, will avoid exploring repeated states.\n Requires: SearchProblem.actions, SearchProblem.result, and\n SearchProblem.is_goal.\n '''\n solution = False\n limit = 0\n\n # Only keep iterating if solution is exactly False\n while solution is False:\n solution = limited_depth_first(problem,\n depth_limit=limit,\n graph_search=graph_search,\n viewer=viewer)\n limit += 1\n\n if viewer:\n viewer.event('no_more_runs', solution, 'returned after %i runs' % limit)\n\n return solution", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/dedup.py", - "function_name": "finalize_doc", - "test_info": { - "success": false, - "failed": 4, - "passed": 153, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_dedup.py::test_simple_dedup\nLocation: /tmp/benchmark_d2kpe1dp/cc_net/dedup.py:402\nError: NameError: name 'finalize_doc' is not defined\n\nTraceback:\n\n> def test_simple_dedup(tmp_path: Path) -> None:\n write_docs(\n tmp_path / \"docs.json\",\n [\n [\"_Hello\", \"_World\", \"I'm so original\"],\n [\"_world\", \"I'm originaler\", \"_Hello\"],\n ],\n )\n> results = list(dedup.deduplicate(tmp_path / \"docs.json\", field=\"text\"))\n\n> yield self(x)\n\n> y = self.do(x)\n\n> def do(self, doc: dict) -> Optional[dict]:\n content = doc.get(self.field)\n if not content:\n return None\n doc_hashes = compute_hashes(content)\n \n assert self.duplicates is not None\n seen = (\n self.duplicates.add(doc_hashes)\n if self.collect\n else self.duplicates[doc_hashes]\n )\n keep = seen < True\n kept = keep.sum()\n if kept == 0:\n return None\n doc_hashes = doc_hashes * keep\n self.n_lines += keep.size\n self.n_lines_kept += kept\n> chars, kept_chars = finalize_doc(doc, self.field, hashes=doc_hashes)\nE NameError: name 'finalize_doc' is not defined\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_dedup.py", - "test_simple_dedup" - ], - [ - "tests/test_dedup.py", - "test_dedup_from_hashes" - ] - ] - }, - "complexity_info": { - "centrality": { - "distance_discount": 2.08, - "in_degree": 2, - "true_in_degree": 2.0, - "out_degree": 1, - "betweenness": 6.170300287947346e-05, - "pagerank": 0.000981981981981982, - "harmonic": 0.00904977375565611, - "bidirectional_harmonic": 0.14787520172135551, - "degree": 3 - }, - "line_count": 26, - "code_line_count": 26, - "cyclomatic": 7, - "halstead_volume": 85.83671966625714, - "halstead_difficulty": 2.9166666666666665 - }, - "corruption": { - "code": "# not calling", - "score": 0.0 - } - }, - { - "repo": { - "path": "/home/ubuntu/repos/cc_net/", - "code_path": "cc_net", - "name": "cc_net", - "test_command": "source venv/bin/activate && ./venv/bin/pytest", - "url": "https://github.com/facebookresearch/cc_net.git", - "stats": { - "exists": true, - "files_count": 19, - "functions_count": 251, - "total_lines": 5173, - "avg_lines_per_file": 272.2631578947368, - "avg_lines_per_func": 20.609561752988046 - } - }, - "fpath": "cc_net/text_normalizer.py", - "function_name": "normalize", - "test_info": { - "success": false, - "failed": 2, - "passed": 155, - "deselected": 0, - "failures_info": [ - "\n============================================================\nFailure #1: tests/test_normalizer.py::test_numbers\nLocation: /tmp/benchmark_8g1hvyt2/tests/test_normalizer.py:21\nError: AssertionError: assert '00\uff13\uff14\uff15\uff16\uff17\uff18\uff19 | 0123456789' == '000000000 | 0000000000'\n \n - 000000000 | 0000000000\n + 00\uff13\uff14\uff15\uff16\uff17\uff18\uff19 | 0123456789\n\nTraceback:\n\n> def test_numbers():\n weird = \"\uff10\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19 | 0123456789\"\n normalized = \"000000000 | 0000000000\"\n> assert txt.normalize(weird, numbers=True) == normalized\nE AssertionError: assert '00\uff13\uff14\uff15\uff16\uff17\uff18\uff19 | 0123456789' == '000000000 | 0000000000'\nE \nE - 000000000 | 0000000000\nE + 00\uff13\uff14\uff15\uff16\uff17\uff18\uff19 | 0123456789\n" - ], - "had_execution_error": false, - "error_message": "", - "failed_tests": [ - [ - "tests/test_normalizer.py", - "test_numbers" - ], - [ - "tests/test_normalizer.py", - "test_normalize_for_dedup" - ] - ] - }, - "complexity_info": { - "line_count": 0, - "cyclomatic": 0 - }, - "corruption": { - "code": "def normalize(line: str, accent=True, case=True, numbers=True, punct=1) -> str:\n line = line.strip()\n if not line:\n return line\n if case:\n line = line.lower()\n if accent:\n line = strip_accents(line)\n if numbers:\n # limit replacements to first two occurrences\n line = DIGIT_RE.sub(\"0\", line, count=2)\n if punct == 1:\n line = replace_unicode_punct(line)\n elif punct == 2:\n line = remove_unicode_punct(line)\n line = remove_non_printing_char(line)\n return line", - "score": 0.0 - } - } -]