[ { "id": 125184, "commit_id": "adf24bfa9723b0621183bb27f0c889b813c06e8a", "repo": "ray", "path": "python/ray/_private/thirdparty/tabulate/tabulate.py", "file_name": "tabulate.py", "fun_name": "_format", "commit_message": "[State Observability] Use a table format by default (#26159)\n\nNOTE: tabulate is copied/pasted to the codebase for table formatting.\r\n\r\nThis PR changes the default layout to be the table format for both summary and list APIs.", "code": "def _format(val, valtype, floatfmt, missingval=\"\", has_invisible=True):\n # noqa\n if val is None:\n return missingval\n\n if valtype in [int, _text_type]:\n return \"{0}\".format(val)\n elif valtype is _binary_type:\n try:\n return _text_type(val, \"ascii\")\n except TypeError:\n return _text_type(val)\n elif valtype is float:\n is_a_colored_number = has_invisible and isinstance(\n val, (_text_type, _binary_type)\n )\n if is_a_colored_number:\n raw_val = _strip_invisible(val)\n formatted_val = format(float(raw_val), floatfmt)\n return val.replace(raw_val, formatted_val)\n else:\n return format(float(val), floatfmt)\n else:\n return \"{0}\".format(val)\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 224, "n_words": 65, "vocab_size": 47, "complexity": 8, "nloc": 22, "token_counts": 132, "n_ast_nodes": 251, "n_identifiers": 18 }, { "id": 42070, "commit_id": "34662f4be5c364e7518f9c1118c9b362038ee5dd", "repo": "seaborn", "path": "seaborn/rcmod.py", "file_name": "rcmod.py", "fun_name": "set_context", "commit_message": "Convert docs to pydata-sphinx-theme and add new material (#2842)\n\n* Do basic conversion of site to pydata_sphinx_theme\r\n\r\n* Remove some pae structure customizations we no longer need\r\n\r\n* Add some custom CSS\r\n\r\n* Tweak a few more colors\r\n\r\n* Remove vestigial div closing tag\r\n\r\n* Reorganize release notes into hierarchical pages\r\n\r\n* Rebuild full docs and fix some resulting issues\r\n\r\n* Make release note doc refs absolute\r\n\r\n* Convert homepage to use sphinx-design instead of hand-crafted html\r\n\r\n* Remove original custom css\r\n\r\n* Simplify header and put archive switcher in footer\r\n\r\n* Streamline API docs for objects\r\n\r\n* Play around with templates to fix shrinking content (not perfect yet)\r\n\r\n* Improve use of horizontal space without sidebars\r\n\r\n* Various tweaks\r\n\r\n* Convert tutorial homepage source to native sphinx-design directives\r\n\r\n* Move intro page into tutorial\r\n\r\n* More tweaks\r\n\r\n* Tweak theme colors and footer\r\n\r\n* Remove reference to navbar version\r\n\r\n* Note that error bar tutorial demonstrates new features as of v0.12\r\n\r\n* Update layout customization for new theme features\r\n\r\n* Various layout and CSS tweaks\r\n\r\n* Narrow support guidance to StackOverflow\r\n\r\n* Run all notebooks\r\n\r\n* Adapt to new dropdown navbar in pydata theme\r\n\r\n* Separate tutorial source and outputs\r\n\r\n* Separate dostring source and outputs\r\n\r\n* Add scale API template\r\n\r\n* Update API docs\r\n\r\n* Fix requirements\r\n\r\n* Add new objects\r\n\r\n* Point doc requirements at v0.10 RC for theme", "code": "def set_context(context=None, font_scale=1, rc=None):\n \n context_object = plotting_context(context, font_scale, rc)\n mpl.rcParams.update(context_object)\n\n", "url": "https://github.com/mwaskom/seaborn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 19, "n_words": 10, "vocab_size": 10, "complexity": 1, "nloc": 3, "token_counts": 34, "n_ast_nodes": 53, "n_identifiers": 9 }, { "id": 311030, "commit_id": "5d7d652237b2368320a68c772ce3d837e4c1d04b", "repo": "core", "path": "homeassistant/components/synology_dsm/common.py", "file_name": "common.py", "fun_name": "async_unload", "commit_message": "Replace Synology DSM services with buttons (#57352)", "code": "async def async_unload(self) -> None:\n \n await self._syno_api_executer(self.dsm.logout)\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 21, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 3, "token_counts": 19, "n_ast_nodes": 35, "n_identifiers": 5 }, { "id": 278720, "commit_id": "3613c3defc39c236fb1592c4f7ba1a9cc887343a", "repo": "keras", "path": "keras/engine/functional_utils.py", "file_name": "functional_utils.py", "fun_name": "clone_keras_tensors", "commit_message": "Remove pylint comments.\n\nPiperOrigin-RevId: 452353044", "code": "def clone_keras_tensors(args, keras_tensor_mapping):\n \n result = []\n for obj in tf.nest.flatten(args):\n if node_module.is_keras_tensor(obj):\n if id(obj) in keras_tensor_mapping:\n cpy = keras_tensor_mapping[id(obj)]\n else:\n # Create copy of keras_tensor if we haven't done it before\n cpy = _clone_keras_tensor(obj)\n cpy._keras_history = obj._keras_history\n keras_tensor_mapping[id(obj)] = cpy\n result.append(cpy)\n else:\n result.append(obj)\n return tf.nest.pack_sequence_as(args, result)\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 191, "n_words": 46, "vocab_size": 35, "complexity": 4, "nloc": 14, "token_counts": 98, "n_ast_nodes": 160, "n_identifiers": 16 }, { "id": 22168, "commit_id": "cd5a9683be69c86c8f3adcd13385a9bc5db198ec", "repo": "pipenv", "path": "pipenv/patched/pip/_vendor/rich/box.py", "file_name": "box.py", "fun_name": "get_plain_headed_box", "commit_message": "Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.", "code": "def get_plain_headed_box(self) -> \"Box\":\n \n return PLAIN_HEADED_SUBSTITUTIONS.get(self, self)\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 21, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 9, "token_counts": 17, "n_ast_nodes": 31, "n_identifiers": 4 }, { "id": 156567, "commit_id": "2b90415b02d3ad1b08362889e0818590ca3133f4", "repo": "dask", "path": "dask/array/core.py", "file_name": "core.py", "fun_name": "apply_and_enforce", "commit_message": "Add kwarg ``enforce_ndim`` to ``dask.array.map_blocks()`` (#8865)", "code": "def apply_and_enforce(*args, **kwargs):\n \n func = kwargs.pop(\"_func\")\n expected_ndim = kwargs.pop(\"expected_ndim\")\n out = func(*args, **kwargs)\n if getattr(out, \"ndim\", 0) != expected_ndim:\n out_ndim = getattr(out, \"ndim\", 0)\n raise ValueError(\n f\"Dimension mismatch: expected output of {func} \"\n f\"to have dims = {expected_ndim}. Got {out_ndim} instead.\"\n )\n return out\n\n", "url": "https://github.com/dask/dask.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 106, "n_words": 44, "vocab_size": 36, "complexity": 2, "nloc": 11, "token_counts": 68, "n_ast_nodes": 129, "n_identifiers": 10 }, { "id": 178165, "commit_id": "283628097a10e8abafc94c683bc8be2d79a5998f", "repo": "label-studio", "path": "label_studio/core/redis.py", "file_name": "redis.py", "fun_name": "get_jobs_by_meta", "commit_message": "feat: DEV-2075: Add mixin to Project to support mechanism to cancel old jobs (#2547)\n\n* feat: DEV-2075: Add mixin to Project to support mechanism to cancel old jobs", "code": "def get_jobs_by_meta(queue, func_name, meta):\n \n # get all jobs from Queue\n jobs = (job\n for job in queue.get_jobs()\n if job.func.__name__ == func_name\n )\n # return only with same meta data\n return [job for job in jobs if hasattr(job, 'meta') and job.meta == meta]\n\n", "url": "https://github.com/heartexlabs/label-studio.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 90, "n_words": 42, "vocab_size": 33, "complexity": 6, "nloc": 6, "token_counts": 52, "n_ast_nodes": 83, "n_identifiers": 10 }, { "id": 269601, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/backend.py", "file_name": "backend.py", "fun_name": "enable_tf_random_generator", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def enable_tf_random_generator():\n \n\n global _USE_GENERATOR_FOR_RNG\n _USE_GENERATOR_FOR_RNG = True\n\n\n@keras_export(\"keras.backend.experimental.disable_tf_random_generator\", v1=[])", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.backend.experimental.disable_tf_random_generator\", v1=[])", "n_ast_errors": 1, "ast_levels": 8, "n_whitespaces": 17, "n_words": 9, "vocab_size": 8, "complexity": 1, "nloc": 3, "token_counts": 10, "n_ast_nodes": 38, "n_identifiers": 4 }, { "id": 42548, "commit_id": "8a4cf5d94eb94b6427c5d1d7907ba07b119932c5", "repo": "nltk", "path": "nltk/text.py", "file_name": "text.py", "fun_name": "collocation_list", "commit_message": "Docstring tests (#3050)\n\n* fixed pytests\r\n\r\n* fixed more pytests\r\n\r\n* fixed more pytest and changed multiline pytest issues fixes for snowball.py and causal.py\r\n\r\n* fixed pytests (mainly multiline or rounding issues)\r\n\r\n* fixed treebank pytests, removed test for return_string=True (deprecated)\r\n\r\n* fixed destructive.py pytests, removed test for return_string=True (deprecated)\r\n\r\n* fixed pytest (rounding issues)\r\n\r\n* fixed pytest (initialised missing object)\r\n\r\n* fixed pytest (formatting issues)\r\n\r\n* fixed pytest (formatting issues)\r\n\r\n* fixed pytest (formatting issues)\r\n\r\n* added pytest +SKIP for deprecated module stanford\r\n\r\n* updated AUTHORS.md\r\n\r\n* changed docstring corrections by usage of ELLIPSIS and different roundings\r\n\r\n* fixed AUTHORS.md to be consistent\r\n\r\n* Fix framenet doctest formatting with pprint\r\n\r\n* Change docstring on MultiListBox.__init__\r\n\r\nI believe the original typo was misinterpreted and changed to something that was not originally intended.\r\n\r\nCo-authored-by: Jan Lennartz \r\nCo-authored-by: Tom Aarsen <37621491+tomaarsen@users.noreply.github.com>\r\nCo-authored-by: Tom Aarsen ", "code": "def collocation_list(self, num=20, window_size=2):\n \n if not (\n \"_collocations\" in self.__dict__\n and self._num == num\n and self._window_size == window_size\n ):\n self._num = num\n self._window_size = window_size\n\n # print(\"Building collocations list\")\n from nltk.corpus import stopwords\n\n ignored_words = stopwords.words(\"english\")\n finder = BigramCollocationFinder.from_words(self.tokens, window_size)\n finder.apply_freq_filter(2)\n finder.apply_word_filter(lambda w: len(w) < 3 or w.lower() in ignored_words)\n bigram_measures = BigramAssocMeasures()\n self._collocations = list(\n finder.nbest(bigram_measures.likelihood_ratio, num)\n )\n return self._collocations\n", "url": "https://github.com/nltk/nltk.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 258, "n_words": 61, "vocab_size": 48, "complexity": 5, "nloc": 18, "token_counts": 126, "n_ast_nodes": 205, "n_identifiers": 27 }, { "id": 294024, "commit_id": "653305b998dd033365576db303b32dd5df3a6c54", "repo": "core", "path": "homeassistant/components/plex/media_browser.py", "file_name": "media_browser.py", "fun_name": "library_section_payload", "commit_message": "Support multiple Plex servers in media browser (#68321)", "code": "def library_section_payload(section):\n \n try:\n children_media_class = ITEM_TYPE_MEDIA_CLASS[section.TYPE]\n except KeyError as err:\n raise UnknownMediaType(f\"Unknown type received: {section.TYPE}\") from err\n server_id = section._server.machineIdentifier # pylint: disable=protected-access\n return BrowseMedia(\n title=section.title,\n media_class=MEDIA_CLASS_DIRECTORY,\n media_content_id=generate_plex_uri(server_id, section.key),\n media_content_type=\"library\",\n can_play=False,\n can_expand=True,\n children_media_class=children_media_class,\n )\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 116, "n_words": 34, "vocab_size": 33, "complexity": 2, "nloc": 15, "token_counts": 77, "n_ast_nodes": 126, "n_identifiers": 21 }, { "id": 213030, "commit_id": "a5db070f446b7cfebdaa6ad2e3dcf78f6105a272", "repo": "serverless-application-model", "path": "samtranslator/open_api/open_api.py", "file_name": "open_api.py", "fun_name": "gen_skeleton", "commit_message": "fix: Py27hash fix (#2182)\n\n* Add third party py27hash code\r\n\r\n* Add Py27UniStr and unit tests\r\n\r\n* Add py27hash_fix utils and tests\r\n\r\n* Add to_py27_compatible_template and tests\r\n\r\n* Apply py27hash fix to wherever it is needed\r\n\r\n* Apply py27hash fix, all tests pass except api_with_any_method_in_swagger\r\n\r\n* apply py27hash fix in openapi + run black\r\n\r\n* remove py27 testing\r\n\r\n* remove other py27 references\r\n\r\n* black fixes\r\n\r\n* fixes/typos\r\n\r\n* remove py27 from tox.ini\r\n\r\n* refactoring\r\n\r\n* third party notice\r\n\r\n* black\r\n\r\n* Fix py27hash fix to deal with null events\r\n\r\n* Fix Py27UniStr repr for unicode literals\r\n\r\n* black reformat\r\n\r\n* Update _template_has_api_resource to check data type more defensively\r\n\r\n* Apply py27Dict in _get_authorizers\r\n\r\n* Apply Py27Dict to authorizers and gateway responses which will go into swagger\r\n\r\n* Update to_py27_compatible_template to handle parameter_values; Add Py27LongInt class\r\n\r\n* Rename _convert_to_py27_dict to _convert_to_py27_type\r\n\r\n* Apply Py27UniStr to path param name\r\n\r\n* Handle HttpApi resource under to_py27_compatible_template\r\n\r\n* Fix InvalidDocumentException to not sort different exceptions\r\n\r\n* black reformat\r\n\r\n* Remove unnecessary test files\r\n\r\nCo-authored-by: Wing Fung Lau <4760060+hawflau@users.noreply.github.com>", "code": "def gen_skeleton():\n \n # create as Py27Dict and insert key one by one to preserve input order\n skeleton = Py27Dict()\n skeleton[\"openapi\"] = \"3.0.1\"\n skeleton[\"info\"] = Py27Dict()\n skeleton[\"info\"][\"version\"] = \"1.0\"\n skeleton[\"info\"][\"title\"] = ref(\"AWS::StackName\")\n skeleton[\"paths\"] = Py27Dict()\n return skeleton\n", "url": "https://github.com/aws/serverless-application-model.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 99, "n_words": 36, "vocab_size": 27, "complexity": 1, "nloc": 8, "token_counts": 55, "n_ast_nodes": 111, "n_identifiers": 4 }, { "id": 260625, "commit_id": "3312bc2ea6aad559643a1d920e3380fa123f627c", "repo": "scikit-learn", "path": "sklearn/decomposition/_kernel_pca.py", "file_name": "_kernel_pca.py", "fun_name": "fit", "commit_message": "MAINT validate parameter in KernelPCA (#24020)\n\nCo-authored-by: Julien Jerphanion \r\nCo-authored-by: jeremiedbb ", "code": "def fit(self, X, y=None):\n \n self._validate_params()\n\n if self.fit_inverse_transform and self.kernel == \"precomputed\":\n raise ValueError(\"Cannot fit_inverse_transform with a precomputed kernel.\")\n X = self._validate_data(X, accept_sparse=\"csr\", copy=self.copy_X)\n self._centerer = KernelCenterer()\n K = self._get_kernel(X)\n self._fit_transform(K)\n\n if self.fit_inverse_transform:\n # no need to use the kernel to transform X, use shortcut expression\n X_transformed = self.eigenvectors_ * np.sqrt(self.eigenvalues_)\n\n self._fit_inverse_transform(X_transformed, X)\n\n self.X_fit_ = X\n return self\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 171, "n_words": 57, "vocab_size": 48, "complexity": 4, "nloc": 13, "token_counts": 106, "n_ast_nodes": 175, "n_identifiers": 24 }, { "id": 42787, "commit_id": "60eb9e106f5915398eafd6aa339ec710c102dc09", "repo": "airflow", "path": "airflow/providers/cncf/kubernetes/hooks/kubernetes.py", "file_name": "kubernetes.py", "fun_name": "get_conn", "commit_message": "Use KubernetesHook to create api client in KubernetesPodOperator (#20578)\n\nAdd support for k8s hook in KPO; use it always (even when no conn id); continue to consider the core k8s settings that KPO already takes into account but emit deprecation warning about them.\r\n\r\nKPO historically takes into account a few settings from core airflow cfg (e.g. verify ssl, tcp keepalive, context, config file, and in_cluster). So to use the hook to generate the client, somehow the hook has to take these settings into account. But we don't want the hook to consider these settings in general. So we read them in KPO and if necessary patch the hook and warn.", "code": "def get_conn(self) -> Any:\n \n\n in_cluster = self._coalesce_param(\n self.in_cluster, self.conn_extras.get(\"extra__kubernetes__in_cluster\") or None\n )\n cluster_context = self._coalesce_param(\n self.cluster_context, self.conn_extras.get(\"extra__kubernetes__cluster_context\") or None\n )\n kubeconfig_path = self._coalesce_param(\n self.config_file, self.conn_extras.get(\"extra__kubernetes__kube_config_path\") or None\n )\n\n kubeconfig = self.conn_extras.get(\"extra__kubernetes__kube_config\") or None\n num_selected_configuration = len([o for o in [in_cluster, kubeconfig, kubeconfig_path] if o])\n\n if num_selected_configuration > 1:\n raise AirflowException(\n \"Invalid connection configuration. Options kube_config_path, \"\n \"kube_config, in_cluster are mutually exclusive. \"\n \"You can only use one option at a time.\"\n )\n\n disable_verify_ssl = self._coalesce_param(\n self.disable_verify_ssl, _get_bool(self._get_field(\"disable_verify_ssl\"))\n )\n disable_tcp_keepalive = self._coalesce_param(\n self.disable_tcp_keepalive, _get_bool(self._get_field(\"disable_tcp_keepalive\"))\n )\n\n # BEGIN apply settings from core kubernetes configuration\n # this section should be removed in next major release\n deprecation_warnings: List[Tuple[str, Any]] = []\n if disable_verify_ssl is None and self._deprecated_core_disable_verify_ssl is True:\n deprecation_warnings.append(('verify_ssl', False))\n disable_verify_ssl = self._deprecated_core_disable_verify_ssl\n # by default, hook will try in_cluster first. so we only need to\n # apply core airflow config and alert when False and in_cluster not otherwise set.\n if in_cluster is None and self._deprecated_core_in_cluster is False:\n deprecation_warnings.append(('in_cluster', self._deprecated_core_in_cluster))\n in_cluster = self._deprecated_core_in_cluster\n if not cluster_context and self._deprecated_core_cluster_context:\n deprecation_warnings.append(('cluster_context', self._deprecated_core_cluster_context))\n cluster_context = self._deprecated_core_cluster_context\n if not kubeconfig_path and self._deprecated_core_config_file:\n deprecation_warnings.append(('config_file', self._deprecated_core_config_file))\n kubeconfig_path = self._deprecated_core_config_file\n if disable_tcp_keepalive is None and self._deprecated_core_disable_tcp_keepalive is True:\n deprecation_warnings.append(('enable_tcp_keepalive', False))\n disable_tcp_keepalive = True\n if deprecation_warnings:\n self._deprecation_warning_core_param(deprecation_warnings)\n # END apply settings from core kubernetes configuration\n\n if disable_verify_ssl is True:\n _disable_verify_ssl()\n if disable_tcp_keepalive is not True:\n _enable_tcp_keepalive()\n\n if in_cluster:\n self.log.debug(\"loading kube_config from: in_cluster configuration\")\n config.load_incluster_config()\n return client.ApiClient()\n\n if kubeconfig_path is not None:\n self.log.debug(\"loading kube_config from: %s\", kubeconfig_path)\n config.load_kube_config(\n config_file=kubeconfig_path,\n client_configuration=self.client_configuration,\n context=cluster_context,\n )\n return client.ApiClient()\n\n if kubeconfig is not None:\n with tempfile.NamedTemporaryFile() as temp_config:\n self.log.debug(\"loading kube_config from: connection kube_config\")\n temp_config.write(kubeconfig.encode())\n temp_config.flush()\n config.load_kube_config(\n config_file=temp_config.name,\n client_configuration=self.client_configuration,\n context=cluster_context,\n )\n return client.ApiClient()\n\n return self._get_default_client(cluster_context=cluster_context)\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 1032, "n_words": 267, "vocab_size": 146, "complexity": 24, "nloc": 71, "token_counts": 460, "n_ast_nodes": 759, "n_identifiers": 49 }, { "id": 149758, "commit_id": "fc837c4daa27a18ff0e86128f4d52089b88fa5fb", "repo": "freqtrade", "path": "freqtrade/freqai/data_handler.py", "file_name": "data_handler.py", "fun_name": "load_data", "commit_message": "add freqao backend machinery, user interface, documentation", "code": "def load_data(self) -> Any:\n \n model = load(self.model_path+self.model_filename+\"_model.joblib\")\n\n with open(self.model_path+self.model_filename+\"_metadata.json\", 'r') as fp:\n self.data = json.load(fp)\n if self.data.get('training_features_list'):\n self.training_features_list = [*self.data.get('training_features_list')]\n\n self.data_dictionary['train_features'] = pd.read_pickle(self.model_path+\n self.model_filename+\"_trained_df.pkl\")\n\n self.model_path = self.data['model_path']\n self.model_filename = self.data['model_filename']\n if self.config['freqai']['feature_parameters']['principal_component_analysis']:\n self.pca = pk.load(open(self.model_path+self.model_filename+\"_pca_object.pkl\",\"rb\"))\n\n return model\n", "url": "https://github.com/freqtrade/freqtrade.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 180, "n_words": 37, "vocab_size": 29, "complexity": 3, "nloc": 18, "token_counts": 155, "n_ast_nodes": 272, "n_identifiers": 19 }, { "id": 144300, "commit_id": "c065e3f69ec248383d98b45a8d1c00832ccfdd57", "repo": "ray", "path": "python/ray/actor.py", "file_name": "actor.py", "fun_name": "_bind", "commit_message": "[Ray DAG] Implement experimental Ray DAG API for task/class (#22058)", "code": "def _bind(self, *args, **kwargs):\n \n from ray.experimental.dag.class_node import ClassNode\n\n return ClassNode(self.__ray_metadata__.modified_class, args, kwargs, {})\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 34, "n_words": 13, "vocab_size": 13, "complexity": 1, "nloc": 3, "token_counts": 38, "n_ast_nodes": 56, "n_identifiers": 11 }, { "id": 337524, "commit_id": "f56f4441b3d448f4a81d5131c03e7dd73eac3ba0", "repo": "accelerate", "path": "src/accelerate/utils/operations.py", "file_name": "operations.py", "fun_name": "find_device", "commit_message": "Big model inference (#345)\n\n* Big model inference\r\n\r\n* Reorganize port cleanup\r\n\r\n* Last cleanup\r\n\r\n* Test fix\r\n\r\n* Quality\r\n\r\n* Update src/accelerate/big_modeling.py\r\n\r\nCo-authored-by: Patrick von Platen \r\n\r\n* Fix bug in default mem\r\n\r\n* Check device map is complete\r\n\r\n* More tests\r\n\r\n* Make load function more general\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Zachary Mueller \r\n\r\n* Quality\r\n\r\n* Address more review comments\r\n\r\n* Check generation results for gpt2\r\n\r\n* Add main wrapper around everything\r\n\r\n* Tests for final API\r\n\r\n* Clean infer_auto_device\r\n\r\n* Type annotations\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sourab Mangrulkar <13534540+pacman100@users.noreply.github.com>\r\nCo-authored-by: Lysandre Debut \r\n\r\n* Address review comments\r\n\r\n* Last review comment for now\r\n\r\n* Fix bug in clean_device_map\r\n\r\n* Add doc\r\n\r\n* Style\r\n\r\n* Fixes + dtype support\r\n\r\n* Fix test\r\n\r\n* Add option to offload CPU state_dict\r\n\r\n* Indent typo\r\n\r\n* Final tweaks\r\n\r\nCo-authored-by: Patrick von Platen \r\nCo-authored-by: Zachary Mueller \r\nCo-authored-by: Sourab Mangrulkar <13534540+pacman100@users.noreply.github.com>\r\nCo-authored-by: Lysandre Debut ", "code": "def find_device(data):\n \n if isinstance(data, Mapping):\n for obj in data.values():\n device = find_device(obj)\n if device is not None:\n return device\n elif isinstance(data, (tuple, list)):\n for obj in data:\n device = find_device(obj)\n if device is not None:\n return device\n elif isinstance(data, torch.Tensor):\n return data.device\n", "url": "https://github.com/huggingface/accelerate.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 149, "n_words": 42, "vocab_size": 22, "complexity": 8, "nloc": 13, "token_counts": 82, "n_ast_nodes": 128, "n_identifiers": 11 }, { "id": 60126, "commit_id": "a368874d1b145c1ec5201e5efd3c26ce7c1e8611", "repo": "prefect", "path": "src/prefect/_internal/concurrency/primitives.py", "file_name": "primitives.py", "fun_name": "wait", "commit_message": "Add thread-safe async primitives `Event` and `Future` (#7865)\n\nCo-authored-by: Serina Grill <42048900+serinamarie@users.noreply.github.com>", "code": "async def wait(self) -> None:\n \n if self._is_set:\n return\n\n if not self._loop:\n self._loop = get_running_loop()\n self._event = asyncio.Event()\n\n await self._event.wait()\n", "url": "https://github.com/PrefectHQ/prefect.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 80, "n_words": 19, "vocab_size": 17, "complexity": 3, "nloc": 12, "token_counts": 44, "n_ast_nodes": 78, "n_identifiers": 8 }, { "id": 78295, "commit_id": "d967eccef28ce47f60d26be1c28f2d83a25f40b0", "repo": "wagtail", "path": "wagtail/contrib/settings/tests/generic/test_templates.py", "file_name": "test_templates.py", "fun_name": "test_get_settings_no_request", "commit_message": "Add generic settings to compliment site-specific settings (#8327)", "code": "def test_get_settings_no_request(self):\n \n context = Context()\n\n template = Template(\n \"{% load wagtailsettings_tags %}\"\n \"{% get_settings %}\"\n \"{{ settings.tests.testgenericsetting.title }}\"\n )\n\n self.assertEqual(template.render(context), self.default_settings.title)\n", "url": "https://github.com/wagtail/wagtail.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 89, "n_words": 21, "vocab_size": 18, "complexity": 1, "nloc": 8, "token_counts": 36, "n_ast_nodes": 67, "n_identifiers": 10 }, { "id": 208719, "commit_id": "dc5bcc1c50892a5128fcf128af28887226144927", "repo": "ipython", "path": "IPython/core/history.py", "file_name": "history.py", "fun_name": "get_tail", "commit_message": "This fixed the mixing of multiple history seen in #13631\n\nIt forces get_tail to put the current session last in the returned\nresults.", "code": "def get_tail(self, n=10, raw=True, output=False, include_latest=False):\n \n self.writeout_cache()\n if not include_latest:\n n += 1\n # cursor/line/entry\n this_cur = list(\n self._run_sql(\n \"WHERE session == ? ORDER BY line DESC LIMIT ? \",\n (self.session_number, n),\n raw=raw,\n output=output,\n )\n )\n other_cur = list(\n self._run_sql(\n \"WHERE session != ? ORDER BY session DESC, line DESC LIMIT ?\",\n (self.session_number, n),\n raw=raw,\n output=output,\n )\n )\n\n everything = this_cur + other_cur\n\n everything = everything[:n]\n\n if not include_latest:\n return list(everything)[:0:-1]\n return list(everything)[::-1]\n", "url": "https://github.com/ipython/ipython.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 344, "n_words": 73, "vocab_size": 44, "complexity": 3, "nloc": 25, "token_counts": 128, "n_ast_nodes": 198, "n_identifiers": 13 }, { "id": 268911, "commit_id": "b96518a22bfd92a29811e507dec0b34248a8a3f5", "repo": "keras", "path": "keras/mixed_precision/loss_scale_optimizer_test.py", "file_name": "loss_scale_optimizer_test.py", "fun_name": "opt_combinations_only", "commit_message": "- Consolidate disparate test-related files into a single testing_infra folder.\n- Cleanup TODO related to removing testing infra as a dependency of the Keras target.\n- Standardize import naming: there is now only \"test_combinations\" for test combinations, and \"test_utils\" for utilities. The TF utilities module \"test_util\" is now always imported as \"tf_test_utils\" to avoid confusion.\n\nPiperOrigin-RevId: 426773173", "code": "def opt_combinations_only():\n \n experimental_opt_combinations = test_combinations.combine(\n mode='eager', opt_cls=optimizer_experimental.Optimizer)\n orig_opt_combination = test_combinations.combine(\n opt_cls=optimizer_v2.OptimizerV2)\n return experimental_opt_combinations + orig_opt_combination\n\n\n@tf_test_utils.with_control_flow_v2", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@tf_test_utils.with_control_flow_v2", "n_ast_errors": 1, "ast_levels": 10, "n_whitespaces": 29, "n_words": 16, "vocab_size": 12, "complexity": 1, "nloc": 6, "token_counts": 37, "n_ast_nodes": 70, "n_identifiers": 13 }, { "id": 148285, "commit_id": "0e6c042e29cbbe429d81c9c1af3c75c261f00980", "repo": "ray", "path": "python/ray/_private/thirdparty/pathspec/util.py", "file_name": "util.py", "fun_name": "_normalize_entries", "commit_message": "[Bugfix] fix invalid excluding of Black (#24042)\n\n- We should use `--force-exclude` when we pass code path explicitly https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html?highlight=--force-exclude#command-line-options\r\n- Recover the files in `python/ray/_private/thirdparty` which has been formatted in the PR https://github.com/ray-project/ray/pull/21975 by mistake.", "code": "def _normalize_entries(entries, separators=None):\n\t\n\tnorm_files = {}\n\tfor entry in entries:\n\t\tnorm_files[normalize_file(entry.path, separators=separators)] = entry\n\treturn norm_files\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 11, "n_words": 16, "vocab_size": 13, "complexity": 2, "nloc": 5, "token_counts": 36, "n_ast_nodes": 57, "n_identifiers": 7 }, { "id": 209543, "commit_id": "08b1f9d67c8e716fd44036a027bdc90dcb9fcfdf", "repo": "scapy", "path": "scapy/layers/inet.py", "file_name": "inet.py", "fun_name": "overlap_frag", "commit_message": "E275 - Missing whitespace after keyword (#3711)\n\nCo-authored-by: Alexander Aring \r\nCo-authored-by: Anmol Sarma \r\nCo-authored-by: antoine.torre \r\nCo-authored-by: Antoine Vacher \r\nCo-authored-by: Arnaud Ebalard \r\nCo-authored-by: atlowl <86038305+atlowl@users.noreply.github.com>\r\nCo-authored-by: Brian Bienvenu \r\nCo-authored-by: Chris Packham \r\nCo-authored-by: CQ \r\nCo-authored-by: Daniel Collins \r\nCo-authored-by: Federico Maggi \r\nCo-authored-by: Florian Maury \r\nCo-authored-by: _Frky <3105926+Frky@users.noreply.github.com>\r\nCo-authored-by: g-mahieux <37588339+g-mahieux@users.noreply.github.com>\r\nCo-authored-by: gpotter2 \r\nCo-authored-by: Guillaume Valadon \r\nCo-authored-by: Hao Zheng \r\nCo-authored-by: Haresh Khandelwal \r\nCo-authored-by: Harri Hämäläinen \r\nCo-authored-by: hecke \r\nCo-authored-by: Jan Romann \r\nCo-authored-by: Jan Sebechlebsky \r\nCo-authored-by: jdiog0 <43411724+jdiog0@users.noreply.github.com>\r\nCo-authored-by: jockque <38525640+jockque@users.noreply.github.com>\r\nCo-authored-by: Julien Bedel <30991560+JulienBedel@users.noreply.github.com>\r\nCo-authored-by: Keith Scott \r\nCo-authored-by: Kfir Gollan \r\nCo-authored-by: Lars Munch \r\nCo-authored-by: ldp77 <52221370+ldp77@users.noreply.github.com>\r\nCo-authored-by: Leonard Crestez \r\nCo-authored-by: Marcel Patzlaff \r\nCo-authored-by: Martijn Thé \r\nCo-authored-by: Martine Lenders \r\nCo-authored-by: Michael Farrell \r\nCo-authored-by: Michał Mirosław \r\nCo-authored-by: mkaliszan \r\nCo-authored-by: mtury \r\nCo-authored-by: Neale Ranns \r\nCo-authored-by: Octavian Toader \r\nCo-authored-by: Peter Eisenlohr \r\nCo-authored-by: Phil \r\nCo-authored-by: Pierre Lalet \r\nCo-authored-by: Pierre Lorinquer \r\nCo-authored-by: piersoh <42040737+piersoh@users.noreply.github.com>\r\nCo-authored-by: plorinquer \r\nCo-authored-by: pvinci \r\nCo-authored-by: Rahul Jadhav \r\nCo-authored-by: Robin Jarry \r\nCo-authored-by: romain-perez <51962832+romain-perez@users.noreply.github.com>\r\nCo-authored-by: rperez \r\nCo-authored-by: Sabrina Dubroca \r\nCo-authored-by: Sebastian Baar \r\nCo-authored-by: sebastien mainand \r\nCo-authored-by: smehner1 \r\nCo-authored-by: speakinghedge \r\nCo-authored-by: Steven Van Acker \r\nCo-authored-by: Thomas Faivre \r\nCo-authored-by: Tran Tien Dat \r\nCo-authored-by: Wael Mahlous \r\nCo-authored-by: waeva <74464394+waeva@users.noreply.github.com>\r\n\r\nCo-authored-by: Alexander Aring \r\nCo-authored-by: Anmol Sarma \r\nCo-authored-by: antoine.torre \r\nCo-authored-by: Antoine Vacher \r\nCo-authored-by: Arnaud Ebalard \r\nCo-authored-by: atlowl <86038305+atlowl@users.noreply.github.com>\r\nCo-authored-by: Brian Bienvenu \r\nCo-authored-by: Chris Packham \r\nCo-authored-by: CQ \r\nCo-authored-by: Daniel Collins \r\nCo-authored-by: Federico Maggi \r\nCo-authored-by: Florian Maury \r\nCo-authored-by: _Frky <3105926+Frky@users.noreply.github.com>\r\nCo-authored-by: g-mahieux <37588339+g-mahieux@users.noreply.github.com>\r\nCo-authored-by: gpotter2 \r\nCo-authored-by: Guillaume Valadon \r\nCo-authored-by: Hao Zheng \r\nCo-authored-by: Haresh Khandelwal \r\nCo-authored-by: Harri Hämäläinen \r\nCo-authored-by: hecke \r\nCo-authored-by: Jan Romann \r\nCo-authored-by: Jan Sebechlebsky \r\nCo-authored-by: jdiog0 <43411724+jdiog0@users.noreply.github.com>\r\nCo-authored-by: jockque <38525640+jockque@users.noreply.github.com>\r\nCo-authored-by: Julien Bedel <30991560+JulienBedel@users.noreply.github.com>\r\nCo-authored-by: Keith Scott \r\nCo-authored-by: Kfir Gollan \r\nCo-authored-by: Lars Munch \r\nCo-authored-by: ldp77 <52221370+ldp77@users.noreply.github.com>\r\nCo-authored-by: Leonard Crestez \r\nCo-authored-by: Marcel Patzlaff \r\nCo-authored-by: Martijn Thé \r\nCo-authored-by: Martine Lenders \r\nCo-authored-by: Michael Farrell \r\nCo-authored-by: Michał Mirosław \r\nCo-authored-by: mkaliszan \r\nCo-authored-by: mtury \r\nCo-authored-by: Neale Ranns \r\nCo-authored-by: Octavian Toader \r\nCo-authored-by: Peter Eisenlohr \r\nCo-authored-by: Phil \r\nCo-authored-by: Pierre Lalet \r\nCo-authored-by: Pierre Lorinquer \r\nCo-authored-by: piersoh <42040737+piersoh@users.noreply.github.com>\r\nCo-authored-by: pvinci \r\nCo-authored-by: Rahul Jadhav \r\nCo-authored-by: Robin Jarry \r\nCo-authored-by: romain-perez <51962832+romain-perez@users.noreply.github.com>\r\nCo-authored-by: rperez \r\nCo-authored-by: Sabrina Dubroca \r\nCo-authored-by: Sebastian Baar \r\nCo-authored-by: sebastien mainand \r\nCo-authored-by: smehner1 \r\nCo-authored-by: Steven Van Acker \r\nCo-authored-by: Thomas Faivre \r\nCo-authored-by: Tran Tien Dat \r\nCo-authored-by: Wael Mahlous \r\nCo-authored-by: waeva <74464394+waeva@users.noreply.github.com>", "code": "def overlap_frag(p, overlap, fragsize=8, overlap_fragsize=None):\n \n\n if overlap_fragsize is None:\n overlap_fragsize = fragsize\n q = p.copy()\n del q[IP].payload\n q[IP].add_payload(overlap)\n\n qfrag = fragment(q, overlap_fragsize)\n qfrag[-1][IP].flags |= 1\n return qfrag + fragment(p, fragsize)\n\n", "url": "https://github.com/secdev/scapy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 61, "n_words": 30, "vocab_size": 26, "complexity": 2, "nloc": 9, "token_counts": 76, "n_ast_nodes": 117, "n_identifiers": 13 }, { "id": 144233, "commit_id": "3f03ef8ba8016b095c611c4d2e118771e4a750ca", "repo": "ray", "path": "rllib/agents/alpha_star/distributed_learners.py", "file_name": "distributed_learners.py", "fun_name": "__len__", "commit_message": "[RLlib] AlphaStar: Parallelized, multi-agent/multi-GPU learning via league-based self-play. (#21356)", "code": "def __len__(self):\n \n return sum(len(s) for s in self.shards)\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 22, "n_words": 8, "vocab_size": 8, "complexity": 2, "nloc": 2, "token_counts": 20, "n_ast_nodes": 34, "n_identifiers": 6 }, { "id": 263805, "commit_id": "41483cb9e6d5086416c8fea6ad6781782c091c60", "repo": "pyinstaller", "path": "PyInstaller/utils/win32/winutils.py", "file_name": "winutils.py", "fun_name": "update_exe_pe_checksum", "commit_message": "winutils: optimize PE headers fixup\n\nAttempt to optimize PE headers fix-up from both time- and memory-\nintensity perspective.\n\nFirst, avoid specifying `fast_load=False` in `pefile.PE` constructor,\nbecause that triggers the bytes statistics collection\nhttps://github.com/erocarrera/pefile/blob/v2022.5.30/pefile.py#L2862-L2876\nwhich takes a long time for large files. Instead, we can obtain\nfull headers (required for build timestamp modification) by\ncalling `pe.full_load()` ourselves.\n\nSecond, use (an equivalent of) `MapFileAndCheckSumW` to compute\nthe PE checksum. For large files, it is orders of magnitude\nfaster than its pure-python `pefile.PE.generate_checksum`\ncounterpart.\n\nThe downside is that `MapFileAndCheckSumW` requires an on-disk\nfile as opposed to a memory buffer, so we need to split the\nPE headers fixup into two separate steps, with each modifying\nthe corresponding PE headers and (re)writing the whole file.\nEven so, this brings the fix-up process for a 700MB executable\ndown to seconds instead of minutes.\n\nIn addition, as noted on MSDN, `MapFileAndCheckSumW` internally\ncalls its ASCII variant (`MapFileAndCheckSumA`), so it cannot\nhandle file paths that contain characters that are not representable\nin the current code page. Therefore, we implement our own equivalent\nusing `ctypes` and pure widechar-based win32 API functions.", "code": "def update_exe_pe_checksum(exe_path):\n \n import pefile\n\n # Compute checksum using our equivalent of the MapFileAndCheckSumW - for large files, it is significantly faster\n # than pure-pyton pefile.PE.generate_checksum(). However, it requires the file to be on disk (i.e., cannot operate\n # on a memory buffer).\n try:\n checksum = compute_exe_pe_checksum(exe_path)\n except Exception as e:\n raise RuntimeError(\"Failed to compute PE checksum!\") from e\n\n # Update the checksum\n with pefile.PE(exe_path, fast_load=True) as pe:\n pe.OPTIONAL_HEADER.CheckSum = checksum\n\n # Generate updated EXE data\n data = pe.write()\n\n # Rewrite the exe\n with open(exe_path, 'wb') as fp:\n fp.write(data)\n\n", "url": "https://github.com/pyinstaller/pyinstaller.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 163, "n_words": 88, "vocab_size": 68, "complexity": 2, "nloc": 11, "token_counts": 72, "n_ast_nodes": 135, "n_identifiers": 17 }, { "id": 78323, "commit_id": "d967eccef28ce47f60d26be1c28f2d83a25f40b0", "repo": "wagtail", "path": "wagtail/contrib/settings/tests/site_specific/test_model.py", "file_name": "test_model.py", "fun_name": "test_get_page_url_when_for_settings_fetched_via_for_site", "commit_message": "Add generic settings to compliment site-specific settings (#8327)", "code": "def test_get_page_url_when_for_settings_fetched_via_for_site(self):\n \n self._create_importantpagessitesetting_object()\n\n settings = ImportantPagesSiteSetting.for_site(self.default_site)\n\n # Force site root paths query beforehand\n self.default_site.root_page._get_site_root_paths()\n\n for page_fk_field, expected_result in (\n (\"sign_up_page\", \"http://localhost/\"),\n (\"general_terms_page\", \"http://localhost/\"),\n (\"privacy_policy_page\", \"http://other/\"),\n ):\n with self.subTest(page_fk_field=page_fk_field):\n\n # only the first request for each URL will trigger queries.\n # 2 are triggered instead of 1 here, because tests use the\n # database cache backed, and the cache is queried each time\n # to fetch site root paths (because there's no 'request' to\n # store them on)\n\n with self.assertNumQueries(2):\n\n self.assertEqual(\n settings.get_page_url(page_fk_field), expected_result\n )\n\n # when called directly\n self.assertEqual(\n settings.get_page_url(page_fk_field), expected_result\n )\n\n # when called indirectly via shortcut\n self.assertEqual(\n getattr(settings.page_url, page_fk_field), expected_result\n )\n", "url": "https://github.com/wagtail/wagtail.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 506, "n_words": 102, "vocab_size": 74, "complexity": 2, "nloc": 20, "token_counts": 115, "n_ast_nodes": 201, "n_identifiers": 17 }, { "id": 269136, "commit_id": "e61cbc52fd3b0170769c120e9b8dabc8c4205322", "repo": "keras", "path": "keras/saving/saved_model/load.py", "file_name": "load.py", "fun_name": "recursively_deserialize_keras_object", "commit_message": "Support Keras saving/loading for ShardedVariables with arbitrary partitions.\n\nPiperOrigin-RevId: 439837516", "code": "def recursively_deserialize_keras_object(config, module_objects=None):\n \n if isinstance(config, dict):\n if 'class_name' in config:\n return generic_utils.deserialize_keras_object(\n config, module_objects=module_objects)\n else:\n return {\n key: recursively_deserialize_keras_object(config[key], module_objects)\n for key in config\n }\n elif isinstance(config, (tuple, list)):\n return [\n recursively_deserialize_keras_object(x, module_objects) for x in config\n ]\n else:\n raise ValueError(\n f'Unable to decode Keras layer config. Config should be a dictionary, '\n f'tuple or list. Received: config={config}')\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 140, "n_words": 58, "vocab_size": 48, "complexity": 6, "nloc": 18, "token_counts": 89, "n_ast_nodes": 142, "n_identifiers": 12 }, { "id": 309801, "commit_id": "dadcc5ebcbcf951ff677568b281c5897d990c8ae", "repo": "core", "path": "homeassistant/components/august/activity.py", "file_name": "activity.py", "fun_name": "get_latest_device_activity", "commit_message": "spelling: components/august (#64232)\n\nCo-authored-by: Josh Soref ", "code": "def get_latest_device_activity(self, device_id, activity_types):\n \n if device_id not in self._latest_activities:\n return None\n\n latest_device_activities = self._latest_activities[device_id]\n latest_activity = None\n\n for activity_type in activity_types:\n if activity_type in latest_device_activities:\n if (\n latest_activity is not None\n and latest_device_activities[activity_type].activity_start_time\n <= latest_activity.activity_start_time\n ):\n continue\n latest_activity = latest_device_activities[activity_type]\n\n return latest_activity\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 227, "n_words": 42, "vocab_size": 28, "complexity": 6, "nloc": 15, "token_counts": 69, "n_ast_nodes": 106, "n_identifiers": 9 }, { "id": 159623, "commit_id": "9f634d248769198881bbb78ccd8d333982462ef5", "repo": "rasa", "path": "scripts/prepare_nightly_release.py", "file_name": "prepare_nightly_release.py", "fun_name": "project_root", "commit_message": "[ATO-114]Add nightly workflows and creation scripts", "code": "def project_root() -> Path:\n \n return Path(os.path.dirname(__file__)).parent.parent\n\n", "url": "https://github.com/RasaHQ/rasa.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 12, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 23, "n_ast_nodes": 40, "n_identifiers": 7 }, { "id": 248026, "commit_id": "aa2811026402394b4013033f075d8f509cdc1257", "repo": "synapse", "path": "tests/storage/test_devices.py", "file_name": "test_devices.py", "fun_name": "add_device_change", "commit_message": "Process device list updates asynchronously (#12365)", "code": "def add_device_change(self, user_id, device_ids, host):\n \n\n for device_id in device_ids:\n stream_id = self.get_success(\n self.store.add_device_change_to_streams(\n \"user_id\", [device_id], [\"!some:room\"]\n )\n )\n\n self.get_success(\n self.store.add_device_list_outbound_pokes(\n user_id=user_id,\n device_id=device_id,\n room_id=\"!some:room\",\n stream_id=stream_id,\n hosts=[host],\n context={},\n )\n )\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 279, "n_words": 28, "vocab_size": 24, "complexity": 2, "nloc": 17, "token_counts": 79, "n_ast_nodes": 121, "n_identifiers": 14 }, { "id": 267050, "commit_id": "b9606417598217106e394c12c776d8c5ede9cd98", "repo": "ansible", "path": "test/lib/ansible_test/_internal/coverage_util.py", "file_name": "coverage_util.py", "fun_name": "self_check", "commit_message": "ansible-test - Support multiple coverage versions.\n\nci_complete\nci_coverage", "code": "def self_check() -> None:\n \n # Verify all supported Python versions have a coverage version.\n for version in SUPPORTED_PYTHON_VERSIONS:\n get_coverage_version(version)\n\n # Verify all controller Python versions are mapped to the latest coverage version.\n for version in CONTROLLER_PYTHON_VERSIONS:\n if get_coverage_version(version) != CONTROLLER_COVERAGE_VERSION:\n raise InternalError(f'Controller Python version {version} is not mapped to the latest coverage version.')\n\n\nself_check()\n", "url": "https://github.com/ansible/ansible.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 93, "n_words": 54, "vocab_size": 35, "complexity": 4, "nloc": 7, "token_counts": 35, "n_ast_nodes": 71, "n_identifiers": 7 }, { "id": 258546, "commit_id": "fb082b223dc9f1dd327f48dc9b830ee382d6f661", "repo": "scikit-learn", "path": "sklearn/neighbors/_regression.py", "file_name": "_regression.py", "fun_name": "predict", "commit_message": "MAINT Do not compute distances for uniform weighting (#22280)", "code": "def predict(self, X):\n \n if self.weights == \"uniform\":\n # In that case, we do not need the distances to perform\n # the weighting so we do not compute them.\n neigh_ind = self.kneighbors(X, return_distance=False)\n neigh_dist = None\n else:\n neigh_dist, neigh_ind = self.kneighbors(X)\n\n weights = _get_weights(neigh_dist, self.weights)\n\n _y = self._y\n if _y.ndim == 1:\n _y = _y.reshape((-1, 1))\n\n if weights is None:\n y_pred = np.mean(_y[neigh_ind], axis=1)\n else:\n y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float64)\n denom = np.sum(weights, axis=1)\n\n for j in range(_y.shape[1]):\n num = np.sum(_y[neigh_ind, j] * weights, axis=1)\n y_pred[:, j] = num / denom\n\n if self._y.ndim == 1:\n y_pred = y_pred.ravel()\n\n return y_pred\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 320, "n_words": 99, "vocab_size": 65, "complexity": 6, "nloc": 21, "token_counts": 199, "n_ast_nodes": 310, "n_identifiers": 26 }, { "id": 190825, "commit_id": "3c745ef193e9af9244cc406734e67815377472ed", "repo": "thumbor", "path": "thumbor/engines/extensions/pil.py", "file_name": "pil.py", "fun_name": "getImageDescriptor", "commit_message": "Reformat of files using black\n\nThese files were not properly formatted.", "code": "def getImageDescriptor(self, im, xy=None):\n \n\n # Defaule use full image and place at upper left\n if xy is None:\n xy = (0, 0)\n\n # Image separator,\n bb = b\"\\x2C\"\n\n # Image position and size\n bb += int2long(xy[0]) # Left position\n bb += int2long(xy[1]) # Top position\n bb += int2long(im.size[0]) # image width\n bb += int2long(im.size[1]) # image height\n\n # packed field: local color table flag1, interlace0, sorted table0,\n # reserved00, lct size111=7=2^(7+1)=256.\n\n bb += b\"\\x87\"\n\n # LZW minimum size code now comes later,\n # begining of [image data] blocks\n return bb\n", "url": "https://github.com/thumbor/thumbor.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 217, "n_words": 90, "vocab_size": 61, "complexity": 2, "nloc": 10, "token_counts": 74, "n_ast_nodes": 130, "n_identifiers": 7 }, { "id": 272348, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/layers/attention/attention_test.py", "file_name": "attention_test.py", "fun_name": "test_calculate_scores_one_dim_with_scale", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def test_calculate_scores_one_dim_with_scale(self):\n \n # Query tensor of shape [1, 1, 1]\n q = np.array([[[1.1]]], dtype=np.float32)\n # Key tensor of shape [1, 1, 1]\n k = np.array([[[1.6]]], dtype=np.float32)\n attention_layer = keras.layers.Attention(use_scale=True)\n attention_layer.build(input_shape=([1, 1, 1], [1, 1, 1]))\n attention_layer.scale = -2.0\n actual = attention_layer._calculate_scores(query=q, key=k)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = -2*1.1*1.6 = -3.52\n expected = np.array([[[-3.52]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 153, "n_words": 62, "vocab_size": 36, "complexity": 1, "nloc": 9, "token_counts": 139, "n_ast_nodes": 203, "n_identifiers": 22 }, { "id": 281114, "commit_id": "ea964109d654394cc0a5237e6ec5510ba6404097", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/cryptocurrency/cryptocurrency_helpers.py", "file_name": "cryptocurrency_helpers.py", "fun_name": "prepare_all_coins_df", "commit_message": "Crypto menu refactor (#1119)\n\n* enabled some crypto commands in dd to be called independent of source loaded\r\n\r\n* support for coin_map_df in all dd functions + load ta and plot chart refactor\r\n\r\n* updated tests and removed coingecko scrapping where possible\r\n\r\n* removed ref of command from hugo\r\n\r\n* updated pycoingecko version\r\n\r\n* refactoring load\r\n\r\n* refactored load to fetch prices; pred can run independent of source now\r\n\r\n* load by default usd on cp/cg and usdt on cb/bin\r\n\r\n* updated to rich for formatting and updated dependencies\r\n\r\n* fixed changes requested\r\n\r\n* update docs\r\n\r\n* revert discord requirements\r\n\r\n* removed absolute from calculate change for price\r\n\r\n* fixing pr issues\r\n\r\n* fix loading issue when similar coins exist, move coins to home, fill n/a\r\n\r\n* update docs for coins\r\n\r\n* adds load to ta and pred menu", "code": "def prepare_all_coins_df() -> pd.DataFrame:\n \n\n gecko_coins_df = load_coins_list(\"coingecko_coins.json\")\n\n paprika_coins_df = load_coins_list(\"coinpaprika_coins.json\")\n paprika_coins_df = paprika_coins_df[paprika_coins_df[\"is_active\"]]\n paprika_coins_df = paprika_coins_df[[\"rank\", \"id\", \"name\", \"symbol\", \"type\"]]\n\n # TODO: Think about scheduled job, that once a day will update data\n\n binance_coins_df = load_binance_map().rename(columns={\"symbol\": \"Binance\"})\n coinbase_coins_df = load_coinbase_map().rename(columns={\"symbol\": \"Coinbase\"})\n gecko_paprika_coins_df = pd.merge(\n gecko_coins_df, paprika_coins_df, on=\"name\", how=\"left\"\n )\n df_merged = pd.merge(\n left=gecko_paprika_coins_df,\n right=binance_coins_df,\n left_on=\"id_x\",\n right_on=\"id\",\n how=\"left\",\n )\n df_merged.rename(\n columns={\n \"id_x\": \"CoinGecko\",\n \"symbol_x\": \"Symbol\",\n \"id_y\": \"CoinPaprika\",\n },\n inplace=True,\n )\n\n df_merged = pd.merge(\n left=df_merged,\n right=coinbase_coins_df,\n left_on=\"CoinGecko\",\n right_on=\"id\",\n how=\"left\",\n )\n\n return df_merged[[\"CoinGecko\", \"CoinPaprika\", \"Binance\", \"Coinbase\", \"Symbol\"]]\n\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 266, "n_words": 84, "vocab_size": 65, "complexity": 1, "nloc": 48, "token_counts": 191, "n_ast_nodes": 339, "n_identifiers": 22 }, { "id": 34009, "commit_id": "28e091430eea9e0d40839e56fd0d57aec262f5f9", "repo": "transformers", "path": "src/transformers/models/nystromformer/modeling_nystromformer.py", "file_name": "modeling_nystromformer.py", "fun_name": "_set_gradient_checkpointing", "commit_message": "Add Nystromformer (#14659)\n\n* Initial commit\r\n\r\n* Config and modelling changes\r\n\r\nAdded Nystromformer-specific attributes to config and removed all decoder functionality from modelling.\r\n\r\n* Modelling and test changes\r\n\r\nAdded Nystrom approximation and removed decoder tests.\r\n\r\n* Code quality fixes\r\n\r\n* Modeling changes and conversion script\r\n\r\nInitial commits to conversion script, modeling changes.\r\n\r\n* Minor modeling changes and conversion script\r\n\r\n* Modeling changes\r\n\r\n* Correct modeling, add tests and documentation\r\n\r\n* Code refactor\r\n\r\n* Remove tokenizers\r\n\r\n* Code refactor\r\n\r\n* Update __init__.py\r\n\r\n* Fix bugs\r\n\r\n* Update src/transformers/__init__.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/__init__.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/__init__.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update docs/source/model_doc/nystromformer.mdx\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/configuration_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/configuration_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/configuration_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/configuration_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update src/transformers/models/nystromformer/configuration_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update modeling and test_modeling\r\n\r\n* Code refactor\r\n\r\n* .rst to .mdx\r\n\r\n* doc changes\r\n\r\n* Doc changes\r\n\r\n* Update modeling_nystromformer.py\r\n\r\n* Doc changes\r\n\r\n* Fix copies\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update configuration_nystromformer.py\r\n\r\n* Fix copies\r\n\r\n* Update tests/test_modeling_nystromformer.py\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\n\r\n* Update test_modeling_nystromformer.py\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Lysandre Debut \r\n\r\n* Fix code style\r\n\r\n* Update modeling_nystromformer.py\r\n\r\n* Update modeling_nystromformer.py\r\n\r\n* Fix code style\r\n\r\n* Reformat modeling file\r\n\r\n* Update modeling_nystromformer.py\r\n\r\n* Modify NystromformerForMultipleChoice\r\n\r\n* Fix code quality\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* Code style changes and torch.no_grad()\r\n\r\n* make style\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: NielsRogge <48327001+NielsRogge@users.noreply.github.com>\r\nCo-authored-by: Lysandre Debut \r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>", "code": "def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, NystromformerEncoder):\n module.gradient_checkpointing = value\n\n\nNYSTROMFORMER_START_DOCSTRING = r\n\nNYSTROMFORMER_INPUTS_DOCSTRING = r\n\n\n@add_start_docstrings(\n \"The bare Nyströmformer Model transformer outputting raw hidden-states without any specific head on top.\",\n NYSTROMFORMER_START_DOCSTRING,\n)", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "@add_start_docstrings(\n \"The bare Nyströmformer Model transformer outputting raw hidden-states without any specific head on top.\",\n NYSTROMFORMER_START_DOCSTRING,\n)", "n_ast_errors": 1, "ast_levels": 9, "n_whitespaces": 52, "n_words": 33, "vocab_size": 30, "complexity": 2, "nloc": 3, "token_counts": 24, "n_ast_nodes": 64, "n_identifiers": 10 }, { "id": 119984, "commit_id": "3184dd65a222354bffa2466d9a375162f5649132", "repo": "jax", "path": "jax/experimental/sparse/bcoo.py", "file_name": "bcoo.py", "fun_name": "bcoo_dot_general_sampled", "commit_message": "[sparse] Update docstrings for bcoo primitives.\n\nPiperOrigin-RevId: 438685829", "code": "def bcoo_dot_general_sampled(A, B, indices, *, dimension_numbers):\n \n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n cdims = (api_util._ensure_index_tuple(lhs_contract),\n api_util._ensure_index_tuple(rhs_contract))\n bdims = (api_util._ensure_index_tuple(lhs_batch),\n api_util._ensure_index_tuple(rhs_batch))\n return bcoo_dot_general_sampled_p.bind(A, B, indices,\n dimension_numbers=(cdims, bdims))\n\n@bcoo_dot_general_sampled_p.def_impl", "url": "https://github.com/google/jax.git", "language": "Python", "ast_errors": "@bcoo_dot_general_sampled_p.def_impl", "n_ast_errors": 1, "ast_levels": 9, "n_whitespaces": 91, "n_words": 27, "vocab_size": 23, "complexity": 1, "nloc": 8, "token_counts": 80, "n_ast_nodes": 124, "n_identifiers": 16 }, { "id": 80736, "commit_id": "a3a216f91f1158fd54c001c34cbdf2f68ccbc272", "repo": "awx", "path": "awx/main/migrations/_inventory_source.py", "file_name": "_inventory_source.py", "fun_name": "_get_instance_id", "commit_message": "Fix up new Django 3.0 deprecations\n\nMostly text based: force/smart_text, ugettext_*", "code": "def _get_instance_id(from_dict, new_id, default=''):\n \n instance_id = default\n for key in new_id.split('.'):\n if not hasattr(from_dict, 'get'):\n instance_id = default\n break\n instance_id = from_dict.get(key, default)\n from_dict = instance_id\n return smart_str(instance_id)\n\n", "url": "https://github.com/ansible/awx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 83, "n_words": 28, "vocab_size": 21, "complexity": 3, "nloc": 9, "token_counts": 56, "n_ast_nodes": 95, "n_identifiers": 10 }, { "id": 100396, "commit_id": "c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf", "repo": "faceswap", "path": "plugins/train/trainer/_base.py", "file_name": "_base.py", "fun_name": "compile_sample", "commit_message": "Update code to support Tensorflow versions up to 2.8 (#1213)\n\n* Update maximum tf version in setup + requirements\r\n\r\n* - bump max version of tf version in launcher\r\n- standardise tf version check\r\n\r\n* update keras get_custom_objects for tf>2.6\r\n\r\n* bugfix: force black text in GUI file dialogs (linux)\r\n\r\n* dssim loss - Move to stock tf.ssim function\r\n\r\n* Update optimizer imports for compatibility\r\n\r\n* fix logging for tf2.8\r\n\r\n* Fix GUI graphing for TF2.8\r\n\r\n* update tests\r\n\r\n* bump requirements.txt versions\r\n\r\n* Remove limit on nvidia-ml-py\r\n\r\n* Graphing bugfixes\r\n - Prevent live graph from displaying if data not yet available\r\n\r\n* bugfix: Live graph. Collect loss labels correctly\r\n\r\n* fix: live graph - swallow inconsistent loss errors\r\n\r\n* Bugfix: Prevent live graph from clearing during training\r\n\r\n* Fix graphing for AMD", "code": "def compile_sample(self, batch_size, samples=None, images=None, masks=None):\n \n num_images = self._config.get(\"preview_images\", 14)\n num_images = min(batch_size, num_images) if batch_size is not None else num_images\n retval = {}\n for side in (\"a\", \"b\"):\n logger.debug(\"Compiling samples: (side: '%s', samples: %s)\", side, num_images)\n side_images = images[side] if images is not None else self._target[side]\n side_masks = masks[side] if masks is not None else self._masks[side]\n side_samples = samples[side] if samples is not None else self._samples[side]\n retval[side] = [side_samples[0:num_images],\n side_images[0:num_images],\n side_masks[0:num_images]]\n return retval\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 225, "n_words": 74, "vocab_size": 48, "complexity": 6, "nloc": 13, "token_counts": 153, "n_ast_nodes": 225, "n_identifiers": 20 }, { "id": 314211, "commit_id": "90e1fb6ce2faadb9a35fdbe1774fce7b4456364f", "repo": "core", "path": "homeassistant/components/weather/__init__.py", "file_name": "__init__.py", "fun_name": "temperature", "commit_message": "Weather unit conversion (#73441)\n\nCo-authored-by: Erik ", "code": "def temperature(self) -> float | None:\n \n return self._attr_temperature\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 22, "n_words": 8, "vocab_size": 8, "complexity": 1, "nloc": 6, "token_counts": 14, "n_ast_nodes": 25, "n_identifiers": 4 }, { "id": 20801, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/rich/progress.py", "file_name": "progress.py", "fun_name": "get_time", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def get_time(self) -> float:\n \n return self._get_time()\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 14, "n_ast_nodes": 26, "n_identifiers": 4 }, { "id": 118718, "commit_id": "2c153aa179a27539f856e389870161d5a58da213", "repo": "streamlit", "path": "lib/tests/streamlit/legacy_dataframe_styling_test.py", "file_name": "legacy_dataframe_styling_test.py", "fun_name": "test_add_unstyled_rows_to_styled_rows", "commit_message": "Pandas 1.4 styler fix (#4316)\n\nChange the way we detect custom styling in a DataFrame, to account for changes in Pandas 1.4.\r\n\r\nOur DataFrame styling support is based on internal Pandas APIs, so they're always subject to change out from underneath us. In general, we'd prefer to only pass `display_value` data to the frontend when a DataFrame cell has been custom-formatted by the user, to save on bandwidth. However, Panda's Styler's internals are private, and it doesn't give us a consistent way of testing whether a cell has a custom `display_value` or not. \r\n\r\nPrior to Pandas 1.4, we could test whether a cell's `display_value` differed from its `value`, and only stick the `display_value` in the protobuf when that was the case. In 1.4, an unmodified Styler will contain `display_value` strings for all cells, regardless of whether any formatting has been applied to that cell, so we no longer have this ability (or at least I couldn't figure out a reasonable way to test for this). \r\n\r\nSo instead, as of this PR, calling `st._legacy_dataframe(df.styler)` will *always* result in `display_value` strings being written to the dataframe protobuf (even though there isn't any custom formatting). This means that styled DataFrames may result in more data being sent to the frontend now than was the case before. In practice, I don't think this is a big deal - only the legacy DataFrame code has styling support; and often, if you're styling a DataFrame, you're customizing the formatting on most or all of its cells anyway.\r\n\r\nI also made a number of small type-safety changes as I was working with the dataframe code, and those are all in the PR as well. (I've left a PR comment under the actual logic changes.)", "code": "def test_add_unstyled_rows_to_styled_rows(self, st_element, get_proto):\n \n df1 = pd.DataFrame([5, 6])\n df2 = pd.DataFrame([7, 8])\n\n css_values = [\n {css_s(\"color\", \"black\")},\n {css_s(\"color\", \"black\")},\n set(),\n set(),\n ]\n\n x = st_element(df1.style.applymap(lambda val: \"color: black\"))\n\n x._legacy_add_rows(df2)\n\n proto_df = get_proto(self._get_element())\n self._assert_column_css_styles(proto_df, 0, css_values)\n", "url": "https://github.com/streamlit/streamlit.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 142, "n_words": 35, "vocab_size": 28, "complexity": 1, "nloc": 13, "token_counts": 106, "n_ast_nodes": 173, "n_identifiers": 19 }, { "id": 282770, "commit_id": "401e4c739a6f9d18944e0ab49c782e97b56fda94", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/helper_funcs.py", "file_name": "helper_funcs.py", "fun_name": "handle_error_code", "commit_message": "Output Missing API Key Message to Console (#1357)\n\n* Decorator to output error msg to console of missing API Key\r\n\r\n* Refactor FMP & alpha advantage\r\n\r\n* Refactor FRED & QUANDL\r\n\r\n* Refactor Polygon\r\n\r\n* Refactor FRED\r\n\r\n* Refactor FRED\r\n\r\n* Refactor Finnhub & coinmarketcap & Newsapi\r\n\r\n* Allow disabling of check api\r\n\r\n* Updating tests : disable check api for tests\r\n\r\n* Refactor Finnhub & SI & Binance\r\n\r\n* Fix linting\r\n\r\n* Fix test & add black formatting\r\n\r\n* Fix test failing\r\n\r\n* Fix test failing\r\n\r\n* Refactor CryptoPanic & Whales alert & Glassnode & Coinglass\r\n\r\n* Refactor ETHexplorer & Smartstake & Alpha Advanage & Coinbase\r\n\r\n* Add decorators to controllers\r\n\r\n* Fix test & Refactor Coinbase, RH, Reddit\r\n\r\n* Add contributing guideline\r\n\r\n* Update CONTRIBUTING.md\r\n\r\n* Update CONTRIBUTING.md\r\n\r\n* fix tests\r\n\r\n* add decorator to snews cmd\r\n\r\nCo-authored-by: Chavithra PARANA \r\nCo-authored-by: didierlopes.eth ", "code": "def handle_error_code(requests_obj, error_code_map):\n \n for error_code, error_msg in error_code_map.items():\n if requests_obj.status_code == error_code:\n console.print(error_msg)\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 37, "n_words": 13, "vocab_size": 13, "complexity": 3, "nloc": 4, "token_counts": 32, "n_ast_nodes": 53, "n_identifiers": 9 }, { "id": 21882, "commit_id": "cd5a9683be69c86c8f3adcd13385a9bc5db198ec", "repo": "pipenv", "path": "pipenv/patched/pip/_vendor/chardet/__init__.py", "file_name": "__init__.py", "fun_name": "detect", "commit_message": "Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.", "code": "def detect(byte_str):\n \n if not isinstance(byte_str, bytearray):\n if not isinstance(byte_str, bytes):\n raise TypeError(\n f\"Expected object of type bytes or bytearray, got: {type(byte_str)}\"\n )\n byte_str = bytearray(byte_str)\n detector = UniversalDetector()\n detector.feed(byte_str)\n return detector.close()\n\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 97, "n_words": 31, "vocab_size": 27, "complexity": 3, "nloc": 10, "token_counts": 53, "n_ast_nodes": 99, "n_identifiers": 11 }, { "id": 212923, "commit_id": "f776589349476a41b98aa1f467aff2f30e2a8fc2", "repo": "PySimpleGUI", "path": "PySimpleGUI.py", "file_name": "PySimpleGUI.py", "fun_name": "delete_file", "commit_message": "Added report_error setting for user_settings_delete_file. Global Settings window complete rework to use Tabs. Hoping nothing broke, but just remember things are in flux for a little bit while the ttk scrollbars are finishing up", "code": "def delete_file(self, filename=None, path=None, report_error=False):\n \n\n if filename is not None or path is not None or (filename is None and path is None):\n self.set_location(filename=filename, path=path)\n try:\n os.remove(self.full_filename)\n except Exception as e:\n if report_error:\n _error_popup_with_traceback('UserSettings delete_file warning ***', 'Exception trying to perform os.remove', e)\n self.dict = {}\n", "url": "https://github.com/PySimpleGUI/PySimpleGUI.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 129, "n_words": 46, "vocab_size": 37, "complexity": 7, "nloc": 9, "token_counts": 83, "n_ast_nodes": 133, "n_identifiers": 13 }, { "id": 60235, "commit_id": "cc4d0564756ca067516f71718a3d135996525909", "repo": "transferlearning", "path": "code/deep/BJMMD/caffe/python/caffe/coord_map.py", "file_name": "coord_map.py", "fun_name": "compose", "commit_message": "Balanced joint maximum mean discrepancy for deep transfer learning", "code": "def compose(base_map, next_map):\n \n ax1, a1, b1 = base_map\n ax2, a2, b2 = next_map\n if ax1 is None:\n ax = ax2\n elif ax2 is None or ax1 == ax2:\n ax = ax1\n else:\n raise AxisMismatchException\n return ax, a1 * a2, a1 * b2 + b1\n\n", "url": "https://github.com/jindongwang/transferlearning.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 86, "n_words": 44, "vocab_size": 31, "complexity": 4, "nloc": 10, "token_counts": 58, "n_ast_nodes": 91, "n_identifiers": 11 }, { "id": 225809, "commit_id": "c22d865acb3899a181921d94b6e94e665a12b432", "repo": "llama_index", "path": "gpt_index/schema.py", "file_name": "schema.py", "fun_name": "is_doc_id_none", "commit_message": "Add index composability! (#86)\n\nSummary of changes\r\n- Bumped version to 0.1.0 \r\n- Abstracted out a BaseDocument class that both Document (from data loaders) and IndexStruct (our data struct classes) inherit from.\r\n- Add a DocumentStore that contains the id's of all BaseDocuments. Both Document objects and IndexStruct objects are registered in here, allowing us to recursively fetch and query sub-index structures within an index structure.\r\n- Add a reference document id to each Node class. This allows us to recursively query within another index struct after we traverse a node, if the reference document id of that node corresponds to another index struct in the DocumentStore.\r\n- Use Node as the central abstraction containing both \"text\" as well as a reference document_id: use for List, Tree, KeywordTable\r\n- Factored out a QueryRunner to recursively run queries. I grappled with some circular dependency issues but I believe the current approach works.\r\n- Add a bunch of unit tests\r\n\r\nCo-authored-by: Jerry Liu ", "code": "def is_doc_id_none(self) -> bool:\n \n return self.doc_id is None\n\n\n@dataclass", "url": "https://github.com/jerryjliu/llama_index.git", "language": "Python", "ast_errors": "@dataclass", "n_ast_errors": 1, "ast_levels": 7, "n_whitespaces": 22, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 3, "token_counts": 14, "n_ast_nodes": 29, "n_identifiers": 5 }, { "id": 301395, "commit_id": "42c80dda85f567192c182da2b4c603408a890381", "repo": "core", "path": "tests/components/ialarm_xr/test_init.py", "file_name": "test_init.py", "fun_name": "test_setup_not_ready", "commit_message": "Create iAlarmXR integration (#67817)\n\n* Creating iAlarmXR integration\r\n\r\n* fixing after review code\r\n\r\n* fixing remaining review hints\r\n\r\n* fixing remaining review hints\r\n\r\n* updating underlying pyialarm library\r\n\r\n* Creating iAlarmXR integration\r\n\r\n* fixing after review code\r\n\r\n* fixing remaining review hints\r\n\r\n* fixing remaining review hints\r\n\r\n* updating underlying pyialarm library\r\n\r\n* fixing after iMicknl review\r\n\r\n* Improving exception handling\r\n\r\n* Updating pyialarmxr library\r\n\r\n* fixing after merge dev\r\n\r\n* fixing after iMicknl review\r\n\r\n* Update CODEOWNERS\r\n\r\nCo-authored-by: Ludovico de Nittis \r\n\r\n* fixing iot_class\r\n\r\n* Update homeassistant/components/ialarmxr/config_flow.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* fixing after bdraco review\r\n\r\n* Update homeassistant/components/ialarmxr/config_flow.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* reverting catching exception in setup step\r\n\r\n* Update homeassistant/components/ialarmxr/__init__.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/__init__.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* fixing after bdraco suggestions\r\n\r\n* Update homeassistant/components/ialarmxr/alarm_control_panel.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/alarm_control_panel.py\r\n\r\nCo-authored-by: Mick Vleeshouwer \r\n\r\n* Update homeassistant/components/ialarmxr/config_flow.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/config_flow.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/__init__.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/__init__.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* Update homeassistant/components/ialarmxr/utils.py\r\n\r\nCo-authored-by: J. Nick Koston \r\n\r\n* regenerate translation and rename function to async_get_ialarmxr_mac\r\n\r\n* removing and collapsing unused error messages\r\n\r\n* fixing tests\r\n\r\n* improve code coverage in tests\r\n\r\n* improve code coverage in tests\r\n\r\n* improve code coverage in tests\r\n\r\n* fixing retry policy with new pyalarmxr library\r\n\r\n* snake case fix\r\n\r\n* renaming integration in ialarm_xr\r\n\r\n* renaming control panel name\r\n\r\nCo-authored-by: Ludovico de Nittis \r\nCo-authored-by: J. Nick Koston \r\nCo-authored-by: Mick Vleeshouwer ", "code": "async def test_setup_not_ready(hass, ialarmxr_api, mock_config_entry):\n \n ialarmxr_api.return_value.get_mac = Mock(side_effect=ConnectionError)\n\n mock_config_entry.add_to_hass(hass)\n assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)\n await hass.async_block_till_done()\n assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 37, "n_words": 19, "vocab_size": 17, "complexity": 1, "nloc": 6, "token_counts": 55, "n_ast_nodes": 91, "n_identifiers": 17 }, { "id": 264031, "commit_id": "d789a7daa7712716c89259b987349917a89aece7", "repo": "pyinstaller", "path": "PyInstaller/utils/hooks/qt/__init__.py", "file_name": "__init__.py", "fun_name": "collect_qtqml_files", "commit_message": "hookutils: reorganize the Qt hook utilities\n\nReorganize the Qt module information to provide information necessary\nto deal with variations between different python Qt bindings (PySide2,\nPyQt5, PySide6, and PyQt6). Replace the existing table-like dictionary\nwith list of entries, which is easier to format and document. From this\nlist, we now generate two dictionaries; one that maps Qt module (shared\nlibrary) names to the module info entries (the same role as the old\ndictionary), and one that maps python module names to the module info\nentries. The latter is necessary to accommodate python modules that do\nnot have corresponding Qt shared libraries (header-only Qt modules,\nsuch as QtAxContainer; or statically-linked module, such as QSci), but\nwe still need to provide information about plugins or translation\nfiles.\n\nThe new information list is based on manual inspection of source code\nfor Qt 5.15 and 6.3, and should provide comprehensive information about\nall plugin names and translation file basenames.\n\nIn addition, most of the helper functions, which take a reference to\nthe `QtLibraryInfo` class as their first argument, have been turned\ninto methods of the `QtLibraryInfo` class. The corresponding hooks\nhave also been adjusted.", "code": "def collect_qtqml_files(self):\n \n\n # No-op if requested Qt-based package is not available.\n if self.version is None:\n return [], []\n\n # Not all PyQt5/PySide2 installs have QML files. In this case, location['Qml2ImportsPath'] is empty.\n # Furthermore, even if location path is provided, the directory itself may not exist.\n #\n # https://github.com/pyinstaller/pyinstaller/pull/3229#issuecomment-359735031\n # https://github.com/pyinstaller/pyinstaller/issues/3864\n #\n # In Qt 6, Qml2ImportsPath was deprecated in favor of QmlImportsPath. The former is not available in PySide6\n # 6.4.0 anymore (but is in PyQt6 6.4.0). Use the new QmlImportsPath if available.\n if 'QmlImportsPath' in self.location:\n qml_src_dir = self.location['QmlImportsPath']\n else:\n qml_src_dir = self.location['Qml2ImportsPath']\n if not qml_src_dir or not os.path.isdir(qml_src_dir):\n logger.warning('%s: QML directory %r does not exist. QML files not packaged.', self, qml_src_dir)\n return [], []\n\n qml_dst_dir = os.path.join(self.qt_rel_dir, 'qml')\n datas = [(qml_src_dir, qml_dst_dir)]\n binaries = [\n # Produce ``/path/to/Qt/Qml/path_to_qml_binary/qml_binary, PyQt5/Qt/Qml/path_to_qml_binary``.\n (\n qml_plugin_file,\n os.path.join(qml_dst_dir, os.path.dirname(os.path.relpath(qml_plugin_file, qml_src_dir)))\n ) for qml_plugin_file in misc.dlls_in_subdirs(qml_src_dir)\n ]\n\n return binaries, datas\n", "url": "https://github.com/pyinstaller/pyinstaller.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 397, "n_words": 146, "vocab_size": 99, "complexity": 6, "nloc": 19, "token_counts": 144, "n_ast_nodes": 243, "n_identifiers": 20 }, { "id": 82418, "commit_id": "c1290c9ff89cb00caa5469129fd527e9d82cd820", "repo": "django-cms", "path": "cms/tests/test_permmod.py", "file_name": "test_permmod.py", "fun_name": "test_patricks_move", "commit_message": "ci: Added codespell (#7355)\n\nCo-authored-by: Christian Clauss \r\n\r\n* ci: codespell config taken from #7292", "code": "def test_patricks_move(self):\n \n self.assertEqual(self.pg.node.parent, self.pe.node)\n # perform moves under slave...\n self.move_page(self.pg, self.pc)\n self.reload_pages()\n # page is now under PC\n self.assertEqual(self.pg.node.parent, self.pc.node)\n self.assertEqual(self.pg.get_absolute_url(), self.pg.publisher_public.get_absolute_url())\n self.move_page(self.pe, self.pg)\n self.reload_pages()\n self.assertEqual(self.pe.node.parent, self.pg.node)\n self.ph = self.ph.reload()\n # check urls - they should stay be the same now after the move\n self.assertEqual(\n self.pg.publisher_public.get_absolute_url(),\n self.pg.get_absolute_url()\n )\n self.assertEqual(\n self.ph.publisher_public.get_absolute_url(),\n self.ph.get_absolute_url()\n )\n\n # check if urls are correct after move\n self.assertEqual(\n self.pg.publisher_public.get_absolute_url(),\n '%smaster/slave-home/pc/pg/' % self.get_pages_root()\n )\n self.assertEqual(\n self.ph.publisher_public.get_absolute_url(),\n '%smaster/slave-home/pc/pg/pe/ph/' % self.get_pages_root()\n )\n\n", "url": "https://github.com/django-cms/django-cms.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 314, "n_words": 72, "vocab_size": 50, "complexity": 1, "nloc": 26, "token_counts": 215, "n_ast_nodes": 356, "n_identifiers": 15 }, { "id": 291315, "commit_id": "003e4224c89a6da381960dc5347750d1521d85c9", "repo": "core", "path": "tests/components/text/test_init.py", "file_name": "test_init.py", "fun_name": "test_text_new_min_max_pattern", "commit_message": "Add `text` platform (#79454)\n\nCo-authored-by: Franck Nijhof \r\nCo-authored-by: Franck Nijhof ", "code": "async def test_text_new_min_max_pattern(hass):\n \n text = MockTextEntity(native_min=-1, native_max=500, pattern=r\"[a-z]\")\n text.hass = hass\n\n assert text.capability_attributes == {\n ATTR_MIN: 0,\n ATTR_MAX: MAX_LENGTH_STATE_STATE,\n ATTR_MODE: TextMode.TEXT,\n ATTR_PATTERN: r\"[a-z]\",\n }\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 67, "n_words": 24, "vocab_size": 23, "complexity": 1, "nloc": 9, "token_counts": 55, "n_ast_nodes": 85, "n_identifiers": 15 }, { "id": 260017, "commit_id": "71028322e8964cf1f341a7b293abaefeb5275e12", "repo": "scikit-learn", "path": "examples/text/plot_document_classification_20newsgroups.py", "file_name": "plot_document_classification_20newsgroups.py", "fun_name": "load_dataset", "commit_message": "DOC rework plot_document_classification_20newsgroups.py example (#22928)\n\n\r\n\r\nCo-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com>\r\nCo-authored-by: Olivier Grisel \r\nCo-authored-by: Julien Jerphanion ", "code": "def load_dataset(verbose=False, remove=()):\n \n\n data_train = fetch_20newsgroups(\n subset=\"train\",\n categories=categories,\n shuffle=True,\n random_state=42,\n remove=remove,\n )\n\n data_test = fetch_20newsgroups(\n subset=\"test\",\n categories=categories,\n shuffle=True,\n random_state=42,\n remove=remove,\n )\n\n # order of labels in `target_names` can be different from `categories`\n target_names = data_train.target_names\n\n # split target in a training set and a test set\n y_train, y_test = data_train.target, data_test.target\n\n # Extracting features from the training data using a sparse vectorizer\n t0 = time()\n vectorizer = TfidfVectorizer(\n sublinear_tf=True, max_df=0.5, min_df=5, stop_words=\"english\"\n )\n X_train = vectorizer.fit_transform(data_train.data)\n duration_train = time() - t0\n\n # Extracting features from the test data using the same vectorizer\n t0 = time()\n X_test = vectorizer.transform(data_test.data)\n duration_test = time() - t0\n\n feature_names = vectorizer.get_feature_names_out()\n\n if verbose:\n\n # compute size of loaded data\n data_train_size_mb = size_mb(data_train.data)\n data_test_size_mb = size_mb(data_test.data)\n\n print(\n f\"{len(data_train.data)} documents - \"\n f\"{data_train_size_mb:.2f}MB (training set)\"\n )\n print(f\"{len(data_test.data)} documents - {data_test_size_mb:.2f}MB (test set)\")\n print(f\"{len(target_names)} categories\")\n print(\n f\"vectorize training done in {duration_train:.3f}s \"\n f\"at {data_train_size_mb / duration_train:.3f}MB/s\"\n )\n print(f\"n_samples: {X_train.shape[0]}, n_features: {X_train.shape[1]}\")\n print(\n f\"vectorize testing done in {duration_test:.3f}s \"\n f\"at {data_test_size_mb / duration_test:.3f}MB/s\"\n )\n print(f\"n_samples: {X_test.shape[0]}, n_features: {X_test.shape[1]}\")\n\n return X_train, X_test, y_train, y_test, feature_names, target_names\n\n\n# %%\n# Compare feature effects\n# -----------------------\n# We train a first classification model without attempting to strip the metadata\n# of the dataset.\n\nX_train, X_test, y_train, y_test, feature_names, target_names = load_dataset(\n verbose=True\n)\n\n# %%\n# Our first model is an instance of the\n# :class:`~sklearn.linear_model.RidgeClassifier` class. This is a linear\n# classification model that uses the mean squared error on {-1, 1} encoded\n# targets, one for each possible class. Contrary to\n# :class:`~sklearn.linear_model.LogisticRegression`,\n# :class:`~sklearn.linear_model.RidgeClassifier` does not\n# provide probabilistic predictions (no `predict_proba` method),\n# but it is often faster to train.\n\nfrom sklearn.linear_model import RidgeClassifier\n\nclf = RidgeClassifier(tol=1e-2, solver=\"sparse_cg\")\nclf.fit(X_train, y_train)\npred = clf.predict(X_test)\n\n# %%\n# We plot the confusion matrix of this classifier to find if there is a pattern\n# in the classification errors.\n\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import ConfusionMatrixDisplay\n\nfig, ax = plt.subplots(figsize=(10, 5))\nConfusionMatrixDisplay.from_predictions(y_test, pred, ax=ax)\nax.xaxis.set_ticklabels(target_names)\nax.yaxis.set_ticklabels(target_names)\n_ = ax.set_title(\n f\"Confusion Matrix for {clf.__class__.__name__}\\non the original documents\"\n)\n\n# %%\n# The confusion matrix highlights that documents of the `alt.atheism` class are\n# often confused with documents with the class `talk.religion.misc` class and\n# vice-versa which is expected since the topics are semantically related.\n#\n# We also observe that some documents of the `sci.space` class can be misclassified as\n# `comp.graphics` while the converse is much rarer. A manual inspection of those\n# badly classified documents would be required to get some insights on this\n# asymmetry. It could be the case that the vocabulary of the space topic could\n# be more specific than the vocabulary for computer graphics.\n#\n# We can gain a deeper understanding of how this classifier makes its decisions\n# by looking at the words with the highest average feature effects:\n\nimport pandas as pd\nimport numpy as np\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 735, "n_words": 475, "vocab_size": 266, "complexity": 2, "nloc": 48, "token_counts": 224, "n_ast_nodes": 713, "n_identifiers": 67 }, { "id": 155176, "commit_id": "193505fdf0c984743397ba3df56262f30aee13a8", "repo": "modin", "path": "modin/core/execution/unidist/implementations/pandas_on_unidist/partitioning/partition.py", "file_name": "partition.py", "fun_name": "apply", "commit_message": "FEAT-#5053: Add pandas on unidist execution with MPI backend (#5059)\n\nSigned-off-by: Igoshev, Iaroslav ", "code": "def apply(self, func, *args, **kwargs):\n \n logger = get_logger()\n logger.debug(f\"ENTER::Partition.apply::{self._identity}\")\n data = self._data\n call_queue = self.call_queue + [[func, args, kwargs]]\n if len(call_queue) > 1:\n logger.debug(f\"SUBMIT::_apply_list_of_funcs::{self._identity}\")\n result, length, width, ip = _apply_list_of_funcs.remote(call_queue, data)\n else:\n # We handle `len(call_queue) == 1` in a different way because\n # this dramatically improves performance.\n result, length, width, ip = _apply_func.remote(data, func, *args, **kwargs)\n logger.debug(f\"SUBMIT::_apply_func::{self._identity}\")\n logger.debug(f\"EXIT::Partition.apply::{self._identity}\")\n return PandasOnUnidistDataframePartition(result, length, width, ip)\n", "url": "https://github.com/modin-project/modin.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 193, "n_words": 64, "vocab_size": 51, "complexity": 2, "nloc": 13, "token_counts": 126, "n_ast_nodes": 222, "n_identifiers": 21 }, { "id": 157201, "commit_id": "b1e468e8645baee30992fbfa84250d816ac1098a", "repo": "dask", "path": "dask/dataframe/io/tests/test_parquet.py", "file_name": "test_parquet.py", "fun_name": "test_roundtrip_nullable_dtypes", "commit_message": "Add support for `use_nullable_dtypes` to `dd.read_parquet` (#9617)", "code": "def test_roundtrip_nullable_dtypes(tmp_path, write_engine, read_engine):\n \n if read_engine == \"fastparquet\" or write_engine == \"fastparquet\":\n pytest.xfail(\"https://github.com/dask/fastparquet/issues/465\")\n\n df = pd.DataFrame(\n {\n \"a\": pd.Series([1, 2, pd.NA, 3, 4], dtype=\"Int64\"),\n \"b\": pd.Series([True, pd.NA, False, True, False], dtype=\"boolean\"),\n \"c\": pd.Series([0.1, 0.2, 0.3, pd.NA, 0.4], dtype=\"Float64\"),\n \"d\": pd.Series([\"a\", \"b\", \"c\", \"d\", pd.NA], dtype=\"string\"),\n }\n )\n ddf = dd.from_pandas(df, npartitions=2)\n ddf.to_parquet(tmp_path, engine=write_engine)\n ddf2 = dd.read_parquet(tmp_path, engine=read_engine)\n assert_eq(df, ddf2)\n\n\n@PYARROW_MARK", "url": "https://github.com/dask/dask.git", "language": "Python", "ast_errors": "@PYARROW_MARK", "n_ast_errors": 1, "ast_levels": 14, "n_whitespaces": 148, "n_words": 60, "vocab_size": 55, "complexity": 3, "nloc": 15, "token_counts": 182, "n_ast_nodes": 278, "n_identifiers": 22 }, { "id": 290831, "commit_id": "38a8e86ddeb65ee8c731b90a7063a3b3702dc1ef", "repo": "core", "path": "homeassistant/components/group/fan.py", "file_name": "fan.py", "fun_name": "async_update_group_state", "commit_message": "Cleanup supported_features in group (#82242)\n\n* Cleanup supported_features in group\r\n\r\n* Remove defaults\r\n(already set to 0 in fan and media_player)", "code": "def async_update_group_state(self) -> None:\n \n self._attr_assumed_state = False\n\n states = [\n state\n for entity_id in self._entities\n if (state := self.hass.states.get(entity_id)) is not None\n ]\n self._attr_assumed_state |= not states_equal(states)\n\n # Set group as unavailable if all members are unavailable or missing\n self._attr_available = any(state.state != STATE_UNAVAILABLE for state in states)\n\n valid_state = any(\n state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in states\n )\n if not valid_state:\n # Set as unknown if all members are unknown or unavailable\n self._is_on = None\n else:\n # Set as ON if any member is ON\n self._is_on = any(state.state == STATE_ON for state in states)\n\n percentage_states = self._async_states_by_support_flag(\n FanEntityFeature.SET_SPEED\n )\n self._percentage = reduce_attribute(percentage_states, ATTR_PERCENTAGE)\n self._attr_assumed_state |= not attribute_equal(\n percentage_states, ATTR_PERCENTAGE\n )\n if (\n percentage_states\n and percentage_states[0].attributes.get(ATTR_PERCENTAGE_STEP)\n and attribute_equal(percentage_states, ATTR_PERCENTAGE_STEP)\n ):\n self._speed_count = (\n round(100 / percentage_states[0].attributes[ATTR_PERCENTAGE_STEP])\n or 100\n )\n else:\n self._speed_count = 100\n\n self._set_attr_most_frequent(\n \"_oscillating\", FanEntityFeature.OSCILLATE, ATTR_OSCILLATING\n )\n self._set_attr_most_frequent(\n \"_direction\", FanEntityFeature.DIRECTION, ATTR_DIRECTION\n )\n\n self._attr_supported_features = reduce(\n ior, [feature for feature in SUPPORTED_FLAGS if self._fans[feature]], 0\n )\n self._attr_assumed_state |= any(\n state.attributes.get(ATTR_ASSUMED_STATE) for state in states\n )\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 606, "n_words": 167, "vocab_size": 90, "complexity": 14, "nloc": 47, "token_counts": 265, "n_ast_nodes": 410, "n_identifiers": 41 }, { "id": 261351, "commit_id": "e01035d3b2dc147cbbe9f6dbd7210a76119991e8", "repo": "scikit-learn", "path": "sklearn/neighbors/_nearest_centroid.py", "file_name": "_nearest_centroid.py", "fun_name": "predict", "commit_message": "OPTIM use pairwise_distances_argmin in NearestCentroid.predict (#24645)\n\n\r\n\r\nCo-authored-by: Julien Jerphanion ", "code": "def predict(self, X):\n \n check_is_fitted(self)\n\n X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n return self.classes_[\n pairwise_distances_argmin(X, self.centroids_, metric=self.metric)\n ]\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 61, "n_words": 15, "vocab_size": 15, "complexity": 1, "nloc": 6, "token_counts": 48, "n_ast_nodes": 75, "n_identifiers": 11 }, { "id": 109149, "commit_id": "eeac402ec56d7e69234e0cd7b15f59d53852e457", "repo": "matplotlib", "path": "lib/matplotlib/figure.py", "file_name": "figure.py", "fun_name": "_suplabels", "commit_message": "Add rcparam for figure label size and weight (#22566)\n\n* Add rcparam for figure label size and weight", "code": "def _suplabels(self, t, info, **kwargs):\n \n\n suplab = getattr(self, info['name'])\n\n x = kwargs.pop('x', None)\n y = kwargs.pop('y', None)\n if info['name'] in ['_supxlabel', '_suptitle']:\n autopos = y is None\n elif info['name'] == '_supylabel':\n autopos = x is None\n if x is None:\n x = info['x0']\n if y is None:\n y = info['y0']\n\n if 'horizontalalignment' not in kwargs and 'ha' not in kwargs:\n kwargs['horizontalalignment'] = info['ha']\n if 'verticalalignment' not in kwargs and 'va' not in kwargs:\n kwargs['verticalalignment'] = info['va']\n if 'rotation' not in kwargs:\n kwargs['rotation'] = info['rotation']\n\n if 'fontproperties' not in kwargs:\n if 'fontsize' not in kwargs and 'size' not in kwargs:\n kwargs['size'] = mpl.rcParams[info['size']]\n if 'fontweight' not in kwargs and 'weight' not in kwargs:\n kwargs['weight'] = mpl.rcParams[info['weight']]\n\n sup = self.text(x, y, t, **kwargs)\n if suplab is not None:\n suplab.set_text(t)\n suplab.set_position((x, y))\n suplab.update_from(sup)\n sup.remove()\n else:\n suplab = sup\n suplab._autopos = autopos\n setattr(self, info['name'], suplab)\n self.stale = True\n return suplab\n", "url": "https://github.com/matplotlib/matplotlib.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 463, "n_words": 146, "vocab_size": 69, "complexity": 16, "nloc": 35, "token_counts": 283, "n_ast_nodes": 487, "n_identifiers": 22 }, { "id": 47465, "commit_id": "49e336ae0302b386a2f47269a6d13988382d975f", "repo": "airflow", "path": "tests/jobs/test_backfill_job.py", "file_name": "test_backfill_job.py", "fun_name": "test_backfill_execute_subdag_with_removed_task", "commit_message": "Replace usage of `DummyOperator` with `EmptyOperator` (#22974)\n\n* Replace usage of `DummyOperator` with `EmptyOperator`", "code": "def test_backfill_execute_subdag_with_removed_task(self):\n \n dag = self.dagbag.get_dag('example_subdag_operator')\n subdag = dag.get_task('section-1').subdag\n\n session = settings.Session()\n executor = MockExecutor()\n job = BackfillJob(\n dag=subdag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, executor=executor, donot_pickle=True\n )\n dr = DagRun(\n dag_id=subdag.dag_id, execution_date=DEFAULT_DATE, run_id=\"test\", run_type=DagRunType.BACKFILL_JOB\n )\n session.add(dr)\n\n removed_task_ti = TI(\n task=EmptyOperator(task_id='removed_task'), run_id=dr.run_id, state=State.REMOVED\n )\n removed_task_ti.dag_id = subdag.dag_id\n dr.task_instances.append(removed_task_ti)\n\n session.commit()\n\n with timeout(seconds=30):\n job.run()\n\n for task in subdag.tasks:\n instance = (\n session.query(TI)\n .filter(\n TI.dag_id == subdag.dag_id, TI.task_id == task.task_id, TI.execution_date == DEFAULT_DATE\n )\n .first()\n )\n\n assert instance is not None\n assert instance.state == State.SUCCESS\n\n removed_task_ti.refresh_from_db()\n assert removed_task_ti.state == State.REMOVED\n\n subdag.clear()\n dag.clear()\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 398, "n_words": 84, "vocab_size": 65, "complexity": 2, "nloc": 34, "token_counts": 232, "n_ast_nodes": 372, "n_identifiers": 49 }, { "id": 210267, "commit_id": "afb3b7a1c7842921b8eacae9d2ac4f2e660ea7e1", "repo": "PaddleDetection", "path": "ppdet/modeling/post_process.py", "file_name": "post_process.py", "fun_name": "__call__", "commit_message": "Remove conditional block in RCNN export onnx (#5371)\n\n* support rcnn onnx\r\n\r\n* clean code\r\n\r\n* update cascade rcnn\r\n\r\n* add todo for rpn proposals", "code": "def __call__(self, mask_out, bboxes, bbox_num, origin_shape):\n \n num_mask = mask_out.shape[0]\n origin_shape = paddle.cast(origin_shape, 'int32')\n # TODO: support bs > 1 and mask output dtype is bool\n pred_result = paddle.zeros(\n [num_mask, origin_shape[0][0], origin_shape[0][1]], dtype='int32')\n\n im_h, im_w = origin_shape[0][0], origin_shape[0][1]\n pred_mask = self.paste_mask(mask_out[:, None, :, :], bboxes[:, 2:],\n im_h, im_w)\n pred_mask = pred_mask >= self.binary_thresh\n pred_result = paddle.cast(pred_mask, 'int32')\n\n return pred_result\n\n\n@register", "url": "https://github.com/PaddlePaddle/PaddleDetection.git", "language": "Python", "ast_errors": "@register", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 174, "n_words": 59, "vocab_size": 46, "complexity": 1, "nloc": 11, "token_counts": 129, "n_ast_nodes": 197, "n_identifiers": 19 }, { "id": 81344, "commit_id": "389c4a318035cdb02a972ba8200391765f522169", "repo": "awx", "path": "awx/main/models/notifications.py", "file_name": "notifications.py", "fun_name": "context_stub", "commit_message": "Adding fields to job_metadata for workflows and approval nodes (#12255)", "code": "def context_stub(cls):\n \n context = {\n 'job': {\n 'allow_simultaneous': False,\n 'artifacts': {},\n 'controller_node': 'foo_controller',\n 'created': datetime.datetime(2018, 11, 13, 6, 4, 0, 0, tzinfo=datetime.timezone.utc),\n 'custom_virtualenv': 'my_venv',\n 'description': 'Sample job description',\n 'diff_mode': False,\n 'elapsed': 0.403018,\n 'execution_node': 'awx',\n 'failed': False,\n 'finished': False,\n 'force_handlers': False,\n 'forks': 0,\n 'host_status_counts': {'skipped': 1, 'ok': 5, 'changed': 3, 'failures': 0, 'dark': 0, 'failed': False, 'processed': 0, 'rescued': 0},\n 'id': 42,\n 'job_explanation': 'Sample job explanation',\n 'job_slice_count': 1,\n 'job_slice_number': 0,\n 'job_tags': '',\n 'job_type': 'run',\n 'launch_type': 'workflow',\n 'limit': 'bar_limit',\n 'modified': datetime.datetime(2018, 12, 13, 6, 4, 0, 0, tzinfo=datetime.timezone.utc),\n 'name': 'Stub JobTemplate',\n 'playbook': 'ping.yml',\n 'scm_branch': '',\n 'scm_revision': '',\n 'skip_tags': '',\n 'start_at_task': '',\n 'started': '2019-07-29T17:38:14.137461Z',\n 'status': 'running',\n 'summary_fields': {\n 'created_by': {'first_name': '', 'id': 1, 'last_name': '', 'username': 'admin'},\n 'instance_group': {'id': 1, 'name': 'tower'},\n 'inventory': {\n 'description': 'Sample inventory description',\n 'has_active_failures': False,\n 'has_inventory_sources': False,\n 'hosts_with_active_failures': 0,\n 'id': 17,\n 'inventory_sources_with_failures': 0,\n 'kind': '',\n 'name': 'Stub Inventory',\n 'organization_id': 121,\n 'total_groups': 0,\n 'total_hosts': 1,\n 'total_inventory_sources': 0,\n },\n 'job_template': {'description': 'Sample job template description', 'id': 39, 'name': 'Stub JobTemplate'},\n 'labels': {'count': 0, 'results': []},\n 'project': {'description': 'Sample project description', 'id': 38, 'name': 'Stub project', 'scm_type': 'git', 'status': 'successful'},\n 'schedule': {\n 'description': 'Sample schedule',\n 'id': 42,\n 'name': 'Stub schedule',\n 'next_run': datetime.datetime(2038, 1, 1, 0, 0, 0, 0, tzinfo=datetime.timezone.utc),\n },\n 'unified_job_template': {\n 'description': 'Sample unified job template description',\n 'id': 39,\n 'name': 'Stub Job Template',\n 'unified_job_type': 'job',\n },\n },\n 'timeout': 0,\n 'type': 'job',\n 'url': '/api/v2/jobs/13/',\n 'use_fact_cache': False,\n 'verbosity': 0,\n },\n 'job_friendly_name': 'Job',\n 'url': 'https://towerhost/#/jobs/playbook/1010',\n 'approval_status': 'approved',\n 'approval_node_name': 'Approve Me',\n 'workflow_url': 'https://towerhost/#/jobs/workflow/1010',\n 'job_metadata': ,\n }\n\n return context\n", "url": "https://github.com/ansible/awx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 1599, "n_words": 244, "vocab_size": 146, "complexity": 1, "nloc": 96, "token_counts": 480, "n_ast_nodes": 894, "n_identifiers": 7 }, { "id": 274647, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/metrics/base_metric_test.py", "file_name": "base_metric_test.py", "fun_name": "test_build_in_tf_function", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def test_build_in_tf_function(self):\n \n m = metrics.MeanTensor(dtype=tf.float64)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 19, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 11, "token_counts": 117, "n_ast_nodes": 32, "n_identifiers": 8 }, { "id": 276840, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/utils/generic_utils.py", "file_name": "generic_utils.py", "fun_name": "func_dump", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def func_dump(func):\n \n if os.name == \"nt\":\n raw_code = marshal.dumps(func.__code__).replace(b\"\\\\\", b\"/\")\n code = codecs.encode(raw_code, \"base64\").decode(\"ascii\")\n else:\n raw_code = marshal.dumps(func.__code__)\n code = codecs.encode(raw_code, \"base64\").decode(\"ascii\")\n defaults = func.__defaults__\n if func.__closure__:\n closure = tuple(c.cell_contents for c in func.__closure__)\n else:\n closure = None\n return code, defaults, closure\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 105, "n_words": 42, "vocab_size": 28, "complexity": 4, "nloc": 13, "token_counts": 109, "n_ast_nodes": 185, "n_identifiers": 20 }, { "id": 257048, "commit_id": "a273c3a51dd432bd125e5b35df4be94260a2cdb7", "repo": "haystack", "path": "haystack/document_stores/deepsetcloud.py", "file_name": "deepsetcloud.py", "fun_name": "get_evaluation_sets", "commit_message": "EvaluationSetClient for deepset cloud to fetch evaluation sets and la… (#2345)\n\n* EvaluationSetClient for deepset cloud to fetch evaluation sets and labels for one specific evaluation set\r\n\r\n* make DeepsetCloudDocumentStore able to fetch uploaded evaluation set names\r\n\r\n* fix missing renaming of get_evaluation_set_names in DeepsetCloudDocumentStore\r\n\r\n* update documentation for evaluation set functionality in deepset cloud document store\r\n\r\n* DeepsetCloudDocumentStore tests for evaluation set functionality\r\n\r\n* rename index to evaluation_set_name for DeepsetCloudDocumentStore evaluation set functionality\r\n\r\n* raise DeepsetCloudError when no labels were found for evaluation set\r\n\r\n* make use of .get_with_auto_paging in EvaluationSetClient\r\n\r\n* Return result of get_with_auto_paging() as it parses the response already\r\n\r\n* Make schema import source more specific\r\n\r\n* fetch all evaluation sets for a workspace in deepset Cloud\r\n\r\n* Rename evaluation_set_name to label_index\r\n\r\n* make use of generator functionality for fetching labels\r\n\r\n* Update Documentation & Code Style\r\n\r\n* Adjust function input for DeepsetCloudDocumentStore.get_all_labels, adjust tests for it, fix typos, make linter happy\r\n\r\n* Match error message with pytest.raises\r\n\r\n* Update Documentation & Code Style\r\n\r\n* DeepsetCloudDocumentStore.get_labels_count raises DeepsetCloudError when no evaluation set was found to count labels on\r\n\r\n* remove unneeded import in tests\r\n\r\n* DeepsetCloudDocumentStore tests, make reponse bodies a string through json.dumps\r\n\r\n* DeepsetcloudDocumentStore.get_label_count - move raise to return\r\n\r\n* stringify uuid before json.dump as uuid is not serilizable\r\n\r\n* DeepsetcloudDocumentStore - adjust response mocking in tests\r\n\r\n* DeepsetcloudDocumentStore - json dump response body in test\r\n\r\n* DeepsetCloudDocumentStore introduce label_index, EvaluationSetClient rename label_index to evaluation_set\r\n\r\n* Update Documentation & Code Style\r\n\r\n* DeepsetCloudDocumentStore rename evaluation_set to evaluation_set_response as there is a name clash with the input variable\r\n\r\n* DeepsetCloudDocumentStore - rename missed variable in test\r\n\r\n* DeepsetCloudDocumentStore - rename missed label_index to index in doc string, rename label_index to evaluation_set in EvaluationSetClient\r\n\r\n* Update Documentation & Code Style\r\n\r\n* DeepsetCloudDocumentStore - update docstrings for EvaluationSetClient\r\n\r\n* DeepsetCloudDocumentStore - fix typo in doc string\r\n\r\nCo-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>", "code": "def get_evaluation_sets(self) -> List[dict]:\n \n return self.evaluation_set_client.get_evaluation_sets()\n", "url": "https://github.com/deepset-ai/haystack.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 8, "token_counts": 19, "n_ast_nodes": 33, "n_identifiers": 5 }, { "id": 95412, "commit_id": "5efa5eeb57ae6ddf740256e08ce3b9ff4ec98eaa", "repo": "sentry", "path": "tests/sentry/api/endpoints/test_organization_codeowners_associations.py", "file_name": "test_organization_codeowners_associations.py", "fun_name": "test_simple", "commit_message": "feat(codeowners): Add endpoint to view code owner associations per organization (#31030)\n\nSee API-2186\r\n\r\nSo the earlier version of this PR just had the endpoint return the entire serialized ProjectCodeOwners for an organization. While that works, the intention behind this feature is to read and use the associations, so sending the raw codeowners file, and timestamps are unnecessary and increase the latency with such large payloads, especially for larger orgs.\r\n\r\n@NisanthanNanthakumar suggested limiting what the endpoint returns to just what the feature will need on the frontend, and making the endpoint name a bit more specific. OrganizationCodeOwners -> OrganizationCodeOwnersAssocations.\r\n\r\nAlong with this refactor, tests have been updated.", "code": "def test_simple(self):\n \n code_owner_1 = self.create_codeowners(\n self.project_1, self.code_mapping_1, raw=self.data_1[\"raw\"]\n )\n code_owner_2 = self.create_codeowners(\n self.project_2, self.code_mapping_2, raw=self.data_2[\"raw\"]\n )\n response = self.get_success_response(self.organization.slug, status=status.HTTP_200_OK)\n for code_owner in [code_owner_1, code_owner_2]:\n assert code_owner.project.slug in response.data.keys()\n associations, errors = ProjectCodeOwners.validate_codeowners_associations(\n code_owner.raw, code_owner.project\n )\n assert \"associations\" in response.data[code_owner.project.slug].keys()\n assert response.data[code_owner.project.slug][\"associations\"] == associations\n assert \"errors\" in response.data[code_owner.project.slug].keys()\n assert response.data[code_owner.project.slug][\"errors\"] == errors\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 215, "n_words": 52, "vocab_size": 36, "complexity": 2, "nloc": 17, "token_counts": 175, "n_ast_nodes": 274, "n_identifiers": 26 }, { "id": 189402, "commit_id": "6d15ca5e745ecdd5d0673adbd55fc7a589abdae3", "repo": "manim", "path": "manim/mobject/mobject.py", "file_name": "mobject.py", "fun_name": "set", "commit_message": "Clarify the docs for MObject.animate, MObject.set and Variable. (#2407)\n\n* Clarify the docs for MObject.animate, MObject.set and Variable.\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* Slight reword\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Benjamin Hackl \r\n\r\nCo-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>\r\nCo-authored-by: Benjamin Hackl ", "code": "def set(self, **kwargs) -> \"Mobject\":\n \n\n for attr, value in kwargs.items():\n setattr(self, attr, value)\n\n return self\n", "url": "https://github.com/ManimCommunity/manim.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 47, "n_words": 15, "vocab_size": 14, "complexity": 2, "nloc": 54, "token_counts": 32, "n_ast_nodes": 53, "n_identifiers": 7 }, { "id": 181598, "commit_id": "388616b6247ca4ea8de4e2f340d6206aee523541", "repo": "tpot", "path": "tests/driver_tests.py", "file_name": "driver_tests.py", "fun_name": "test_driver_3", "commit_message": "Revert \"Deployed 7ccda9a with MkDocs version: 1.3.0\"\n\nThis reverts commit bd9629c40e01241766197119b581a99409b07068.", "code": "def test_driver_3():\n \n args_list = [\n 'tests/tests.csv',\n '-is', ',',\n '-target', 'class',\n '-g', '1',\n '-p', '2',\n '-cv', '3',\n '-s',' 45',\n '-config', 'TPOT light',\n '-v', '2'\n ]\n args = _get_arg_parser().parse_args(args_list)\n with captured_output() as (out, err):\n tpot_driver(args)\n ret_stdout = out.getvalue()\n assert \"TPOT settings\" in ret_stdout\n assert \"Final Pareto front testing scores\" not in ret_stdout\n try:\n ret_val = float(ret_stdout.split('\\n')[-2].split(': ')[-1])\n except Exception:\n ret_val = -float('inf')\n assert ret_val > 0.0\n\n", "url": "https://github.com/EpistasisLab/tpot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 265, "n_words": 64, "vocab_size": 53, "complexity": 2, "nloc": 23, "token_counts": 125, "n_ast_nodes": 231, "n_identifiers": 15 }, { "id": 263901, "commit_id": "49abfa5498b1db83b8f1b2e859e461b1e8540c6f", "repo": "pyinstaller", "path": "PyInstaller/utils/hooks/qt.py", "file_name": "qt.py", "fun_name": "_find_all_or_none", "commit_message": "hookutils: qt: ensure ANGLE DLLs are collected from Anaconda Qt5\n\nAnaconda's Qt5 ships ANGLE DLLs (`libEGL.dll` and `libGLESv2.dll`)\nbut does not seem to provide the `d3dcompiler_XY.dll`. Therefore,\nwe need to adjust the extra Qt DLL collection to consider the\nlatter an optional dependency whose absence does not preclude\nthe collection of the ANGLE DLL group.\n\nRework the `get_qt_binaries` hook utility function and its\n`_find_all_or_none` helper to peform collection based on a list\nof mandatory and a list of optional patterns, instead of a single\nlist and number of expected matches (since up until now, all\nmatches were always expected to be found).", "code": "def _find_all_or_none(qt_library_info, mandatory_dll_patterns, optional_dll_patterns=None):\n \n optional_dll_patterns = optional_dll_patterns or []\n\n # Resolve path to the the corresponding python package (actually, its parent directory). Used to preserve directory\n # structure when DLLs are collected from the python package (e.g., PyPI wheels).\n package_parent_path = pathlib.Path(qt_library_info.package_location).resolve().parent\n\n # In PyQt5/PyQt6, the DLLs we are looking for are located in location['BinariesPath'], whereas in PySide2/PySide6,\n # they are located in location['PrefixPath'].\n dll_path = qt_library_info.location['BinariesPath' if qt_library_info.is_pyqt else 'PrefixPath']\n dll_path = pathlib.Path(dll_path).resolve()\n\n # Helper for processing single DLL pattern", "url": "https://github.com/pyinstaller/pyinstaller.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 111, "n_words": 81, "vocab_size": 58, "complexity": 6, "nloc": 15, "token_counts": 100, "n_ast_nodes": 105, "n_identifiers": 13 }, { "id": 261040, "commit_id": "2710a9e7eefd2088ce35fd2fb6651d5f97e5ef8b", "repo": "scikit-learn", "path": "sklearn/utils/tests/test_array_api.py", "file_name": "test_array_api.py", "fun_name": "test_asarray_with_order", "commit_message": "ENH Adds Array API support to LinearDiscriminantAnalysis (#22554)\n\nCo-authored-by: Olivier Grisel \r\nCo-authored-by: Julien Jerphanion ", "code": "def test_asarray_with_order(is_array_api):\n \n if is_array_api:\n xp = pytest.importorskip(\"numpy.array_api\")\n else:\n xp = numpy\n\n X = xp.asarray([1.2, 3.4, 5.1])\n X_new = _asarray_with_order(X, order=\"F\")\n\n X_new_np = numpy.asarray(X_new)\n assert X_new_np.flags[\"F_CONTIGUOUS\"]\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 60, "n_words": 25, "vocab_size": 20, "complexity": 2, "nloc": 9, "token_counts": 67, "n_ast_nodes": 104, "n_identifiers": 13 }, { "id": 277191, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/wrappers/scikit_learn.py", "file_name": "scikit_learn.py", "fun_name": "set_params", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def set_params(self, **params):\n \n self.check_params(params)\n self.sk_params.update(params)\n return self\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 35, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 4, "token_counts": 25, "n_ast_nodes": 43, "n_identifiers": 6 }, { "id": 44722, "commit_id": "0cd3b11f3a5c406fbbd4433d8e44d326086db634", "repo": "airflow", "path": "airflow/models/mappedoperator.py", "file_name": "mappedoperator.py", "fun_name": "_validate_argument_count", "commit_message": "Straighten up MappedOperator hierarchy and typing (#21505)", "code": "def _validate_argument_count(self) -> None:\n \n if isinstance(self.operator_class, str):\n return # No need to validate deserialized operator.\n operator = self._create_unmapped_operator(\n mapped_kwargs={k: unittest.mock.MagicMock(name=k) for k in self.mapped_kwargs},\n partial_kwargs=self.partial_kwargs,\n real=False,\n )\n if operator.task_group:\n operator.task_group._remove(operator)\n dag = operator.get_dag()\n if dag:\n dag._remove_task(operator.task_id)\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 152, "n_words": 36, "vocab_size": 33, "complexity": 5, "nloc": 20, "token_counts": 90, "n_ast_nodes": 143, "n_identifiers": 21 }, { "id": 299547, "commit_id": "6635fc4e3111f72bfa6095c97b3f522429fa1a8b", "repo": "core", "path": "homeassistant/components/limitlessled/light.py", "file_name": "light.py", "fun_name": "turn_on", "commit_message": "Use LightEntityFeature enum in limitlessled (#71061)", "code": "def turn_on(self, transition_time, pipeline, **kwargs):\n \n # The night effect does not need a turned on light\n if kwargs.get(ATTR_EFFECT) == EFFECT_NIGHT:\n if EFFECT_NIGHT in self._effect_list:\n pipeline.night_light()\n self._effect = EFFECT_NIGHT\n return\n\n pipeline.on()\n\n # Set up transition.\n args = {}\n if self.config[CONF_FADE] and not self.is_on and self._brightness:\n args[\"brightness\"] = self.limitlessled_brightness()\n\n if ATTR_BRIGHTNESS in kwargs:\n self._brightness = kwargs[ATTR_BRIGHTNESS]\n args[\"brightness\"] = self.limitlessled_brightness()\n\n if ATTR_HS_COLOR in kwargs and self._supported & SUPPORT_COLOR:\n self._color = kwargs[ATTR_HS_COLOR]\n # White is a special case.\n if self._color[1] < MIN_SATURATION:\n pipeline.white()\n self._color = WHITE\n else:\n args[\"color\"] = self.limitlessled_color()\n\n if ATTR_COLOR_TEMP in kwargs:\n if self._supported & SUPPORT_COLOR:\n pipeline.white()\n self._color = WHITE\n if self._supported & SUPPORT_COLOR_TEMP:\n self._temperature = kwargs[ATTR_COLOR_TEMP]\n args[\"temperature\"] = self.limitlessled_temperature()\n\n if args:\n pipeline.transition(transition_time, **args)\n\n # Flash.\n if ATTR_FLASH in kwargs and self._supported & LightEntityFeature.FLASH:\n duration = 0\n if kwargs[ATTR_FLASH] == FLASH_LONG:\n duration = 1\n pipeline.flash(duration=duration)\n\n # Add effects.\n if ATTR_EFFECT in kwargs and self._effect_list:\n if kwargs[ATTR_EFFECT] == EFFECT_COLORLOOP:\n self._effect = EFFECT_COLORLOOP\n pipeline.append(COLORLOOP)\n if kwargs[ATTR_EFFECT] == EFFECT_WHITE:\n pipeline.white()\n self._color = WHITE\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 656, "n_words": 158, "vocab_size": 88, "complexity": 21, "nloc": 41, "token_counts": 291, "n_ast_nodes": 477, "n_identifiers": 42 }, { "id": 302108, "commit_id": "52561ce0769ddcf1e8688c8909692b66495e524b", "repo": "core", "path": "tests/components/mqtt/test_discovery.py", "file_name": "test_discovery.py", "fun_name": "test_duplicate_removal", "commit_message": "Update MQTT tests to use the config entry setup (#72373)\n\n* New testframework and tests for fan platform\r\n\r\n* Merge test_common_new to test_common\r\n\r\n* Add alarm_control_panel\r\n\r\n* Add binary_sensor\r\n\r\n* Add button\r\n\r\n* Add camera\r\n\r\n* Add climate\r\n\r\n* Add config_flow\r\n\r\n* Add cover\r\n\r\n* Add device_tracker_disovery\r\n\r\n* Add device_trigger\r\n\r\n* Add diagnostics\r\n\r\n* Add discovery\r\n\r\n* Add humidifier\r\n\r\n* Add init\r\n\r\n* Add lecacy_vacuum\r\n\r\n* Add light_json\r\n\r\n* Add light_template\r\n\r\n* Add light\r\n\r\n* Add lock\r\n\r\n* Add number\r\n\r\n* Add scene\r\n\r\n* Add select\r\n\r\n* Add sensor\r\n\r\n* Add siren\r\n\r\n* Add state_vacuum\r\n\r\n* Add subscription\r\n\r\n* Add switch\r\n\r\n* Add tag\r\n\r\n* Add trigger\r\n\r\n* Add missed tests\r\n\r\n* Add another missed test\r\n\r\n* Add device_tracker\r\n\r\n* Remove commented out code\r\n\r\n* Correct tests according comments\r\n\r\n* Improve mqtt_mock_entry and recover tests\r\n\r\n* Split fixtures with and without yaml setup\r\n\r\n* Update fixtures manual_mqtt\r\n\r\n* Update fixtures mqtt_json\r\n\r\n* Fix test tasmota\r\n\r\n* Update fixture mqtt_room\r\n\r\n* Revert fixture changes, improve test\r\n\r\n* re-add test", "code": "async def test_duplicate_removal(hass, mqtt_mock_entry_no_yaml_config, caplog):\n \n await mqtt_mock_entry_no_yaml_config()\n async_fire_mqtt_message(\n hass,\n \"homeassistant/binary_sensor/bla/config\",\n '{ \"name\": \"Beer\", \"state_topic\": \"test-topic\" }',\n )\n await hass.async_block_till_done()\n async_fire_mqtt_message(hass, \"homeassistant/binary_sensor/bla/config\", \"\")\n await hass.async_block_till_done()\n assert \"Component has already been discovered: binary_sensor bla\" in caplog.text\n caplog.clear()\n async_fire_mqtt_message(hass, \"homeassistant/binary_sensor/bla/config\", \"\")\n await hass.async_block_till_done()\n\n assert \"Component has already been discovered: binary_sensor bla\" not in caplog.text\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 108, "n_words": 51, "vocab_size": 32, "complexity": 1, "nloc": 15, "token_counts": 75, "n_ast_nodes": 137, "n_identifiers": 8 }, { "id": 276769, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/utils/data_utils.py", "file_name": "data_utils.py", "fun_name": "_extract_archive", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _extract_archive(file_path, path=\".\", archive_format=\"auto\"):\n \n if archive_format is None:\n return False\n if archive_format == \"auto\":\n archive_format = [\"tar\", \"zip\"]\n if isinstance(archive_format, str):\n archive_format = [archive_format]\n\n file_path = io_utils.path_to_string(file_path)\n path = io_utils.path_to_string(path)\n\n for archive_type in archive_format:\n if archive_type == \"tar\":\n open_fn = tarfile.open\n is_match_fn = tarfile.is_tarfile\n if archive_type == \"zip\":\n open_fn = zipfile.ZipFile\n is_match_fn = zipfile.is_zipfile\n\n if is_match_fn(file_path):\n with open_fn(file_path) as archive:\n try:\n archive.extractall(path)\n except (tarfile.TarError, RuntimeError, KeyboardInterrupt):\n if os.path.exists(path):\n if os.path.isfile(path):\n os.remove(path)\n else:\n shutil.rmtree(path)\n raise\n return True\n return False\n\n\n@keras_export(\"keras.utils.get_file\")", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.utils.get_file\")", "n_ast_errors": 1, "ast_levels": 21, "n_whitespaces": 397, "n_words": 79, "vocab_size": 53, "complexity": 11, "nloc": 29, "token_counts": 169, "n_ast_nodes": 297, "n_identifiers": 29 }, { "id": 31499, "commit_id": "acb709d55150501698b5b500ca49683b913d4b3d", "repo": "transformers", "path": "examples/pytorch/test_accelerate_examples.py", "file_name": "test_accelerate_examples.py", "fun_name": "test_run_image_classification_no_trainer", "commit_message": "Change no trainer image_classification test (#17635)\n\n* Adjust test arguments and use a new example test", "code": "def test_run_image_classification_no_trainer(self):\n tmp_dir = self.get_auto_remove_tmp_dir()\n testargs = f.split()\n\n if is_cuda_and_apex_available():\n testargs.append(\"--fp16\")\n\n _ = subprocess.run(self._launch_args + testargs, stdout=subprocess.PIPE)\n result = get_results(tmp_dir)\n # The base model scores a 25%\n self.assertGreaterEqual(result[\"eval_accuracy\"], 0.625)\n self.assertTrue(os.path.exists(os.path.join(tmp_dir, \"step_1\")))\n self.assertTrue(os.path.exists(os.path.join(tmp_dir, \"image_classification_no_trainer\")))\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 106, "n_words": 33, "vocab_size": 29, "complexity": 2, "nloc": 23, "token_counts": 112, "n_ast_nodes": 195, "n_identifiers": 23 }, { "id": 224518, "commit_id": "1c50987f9c17b228fdf22456aa369b83bd6b11b9", "repo": "mkdocs", "path": "mkdocs/utils/__init__.py", "file_name": "__init__.py", "fun_name": "nest_paths", "commit_message": "Refactor URI handling to not have to deal with backslashes", "code": "def nest_paths(paths):\n \n nested = []\n\n for path in paths:\n parts = PurePath(path).parent.parts\n\n branch = nested\n for part in parts:\n part = dirname_to_title(part)\n branch = find_or_create_node(branch, part)\n\n branch.append(path)\n\n return nested\n\n", "url": "https://github.com/mkdocs/mkdocs.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 91, "n_words": 29, "vocab_size": 19, "complexity": 3, "nloc": 10, "token_counts": 55, "n_ast_nodes": 90, "n_identifiers": 12 }, { "id": 77226, "commit_id": "bc1a2ab1148b0f27cfd1435f8cb0e44c2721102d", "repo": "wagtail", "path": "wagtail/admin/views/generic/mixins.py", "file_name": "mixins.py", "fun_name": "run_before_hook", "commit_message": "Extract mixins from Snippet views and use it in generic create/edit/delete views (#8361)", "code": "def run_before_hook(self):\n \n return None\n", "url": "https://github.com/wagtail/wagtail.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 18, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 8, "n_ast_nodes": 16, "n_identifiers": 2 }, { "id": 181586, "commit_id": "388616b6247ca4ea8de4e2f340d6206aee523541", "repo": "tpot", "path": "tests/driver_tests.py", "file_name": "driver_tests.py", "fun_name": "test_driver", "commit_message": "Revert \"Deployed 7ccda9a with MkDocs version: 1.3.0\"\n\nThis reverts commit bd9629c40e01241766197119b581a99409b07068.", "code": "def test_driver():\n \n batcmd = \"python -m tpot.driver tests/tests.csv -is , -target class -g 1 -p 2 -os 4 -cv 5 -s 45 -v 1\"\n ret_stdout = subprocess.check_output(batcmd, shell=True)\n try:\n ret_val = float(ret_stdout.decode('UTF-8').split('\\n')[-2].split(': ')[-1])\n\n except Exception as e:\n ret_val = -float('inf')\n assert ret_val > 0.0\n\n", "url": "https://github.com/EpistasisLab/tpot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 76, "n_words": 44, "vocab_size": 39, "complexity": 2, "nloc": 8, "token_counts": 69, "n_ast_nodes": 123, "n_identifiers": 12 }, { "id": 164682, "commit_id": "047137ce2619cfe2027e3999dfb92eb614d9a485", "repo": "pandas", "path": "pandas/io/excel/_base.py", "file_name": "_base.py", "fun_name": "close", "commit_message": "DEP: Protect some ExcelWriter attributes (#45795)\n\n* DEP: Deprecate ExcelWriter attributes\r\n\r\n* DEP: Deprecate ExcelWriter attributes\r\n\r\n* Fixup for test\r\n\r\n* Move tests and restore check_extension\r\n\r\ny\r\n\r\n* Deprecate xlwt fm_date and fm_datetime; doc improvements", "code": "def close(self) -> None:\n \n self._save()\n self._handles.close()\n\n\nXLS_SIGNATURES = (\n b\"\\x09\\x00\\x04\\x00\\x07\\x00\\x10\\x00\", # BIFF2\n b\"\\x09\\x02\\x06\\x00\\x00\\x00\\x10\\x00\", # BIFF3\n b\"\\x09\\x04\\x06\\x00\\x00\\x00\\x10\\x00\", # BIFF4\n b\"\\xD0\\xCF\\x11\\xE0\\xA1\\xB1\\x1A\\xE1\", # Compound File Binary\n)\nZIP_SIGNATURE = b\"PK\\x03\\x04\"\nPEEK_SIZE = max(map(len, XLS_SIGNATURES + (ZIP_SIGNATURE,)))\n\n\n@doc(storage_options=_shared_docs[\"storage_options\"])", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "@doc(storage_options=_shared_docs[\"storage_options\"])", "n_ast_errors": 1, "ast_levels": 10, "n_whitespaces": 66, "n_words": 34, "vocab_size": 28, "complexity": 1, "nloc": 4, "token_counts": 20, "n_ast_nodes": 147, "n_identifiers": 13 }, { "id": 124708, "commit_id": "365ffe21e592589880e3116302705b5e08a5b81f", "repo": "ray", "path": "dashboard/tests/test_state_head.py", "file_name": "test_state_head.py", "fun_name": "test_max_concurrent_in_progress_functions", "commit_message": "[Core | State Observability] Implement API Server (Dashboard) HTTP Requests Throttling (#26257)\n\nThis is to limit the max number of HTTP requests the dashboard (API server) will accept before rejecting more requests.\r\nThis will make sure the observability requests do not overload the downstream systems (raylet/gcs) when delegating too many concurrent state observability requests to the cluster.", "code": "async def test_max_concurrent_in_progress_functions(extra_req_num):\n \n max_req = 10\n a = A(max_num_call=max_req)\n\n # Run more than allowed concurrent async functions should trigger rate limiting\n res_arr = await asyncio.gather(\n *[a.fn1() if i % 2 == 0 else a.fn2() for i in range(max_req + extra_req_num)]\n )\n fail_cnt = 0\n for ok in res_arr:\n fail_cnt += 0 if ok else 1\n\n expected_fail_cnt = max(0, extra_req_num)\n assert fail_cnt == expected_fail_cnt, (\n f\"{expected_fail_cnt} out of {max_req + extra_req_num} \"\n f\"concurrent runs should fail with max={max_req} but {fail_cnt}.\"\n )\n\n assert a.num_call_ == 0, \"All requests should be done\"\n\n\n@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"failures\",\n [\n [True, True, True, True, True],\n [False, False, False, False, False],\n [False, True, False, True, False],\n [False, False, False, True, True],\n [True, True, False, False, False],\n ],\n)", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "@pytest.mark.asyncio\n@pytest.mark.parametrize(\n \"failures\",\n [\n [True, True, True, True, True],\n [False, False, False, False, False],\n [False, True, False, True, False],\n [False, False, False, True, True],\n [True, True, False, False, False],\n ],\n)", "n_ast_errors": 1, "ast_levels": 15, "n_whitespaces": 225, "n_words": 120, "vocab_size": 78, "complexity": 5, "nloc": 15, "token_counts": 96, "n_ast_nodes": 270, "n_identifiers": 21 }, { "id": 176904, "commit_id": "b28d30bd552a784d60692fd2d2016f8bcd1cfa17", "repo": "networkx", "path": "networkx/algorithms/shortest_paths/astar.py", "file_name": "astar.py", "fun_name": "astar_path", "commit_message": "Updated astar docstring (#5797)\n\nThe docstring now reflects on heuristic admissibility and heuristic value caching", "code": "def astar_path(G, source, target, heuristic=None, weight=\"weight\"):\n \n if source not in G or target not in G:\n msg = f\"Either source {source} or target {target} is not in G\"\n raise nx.NodeNotFound(msg)\n\n if heuristic is None:\n # The default heuristic is h=0 - same as Dijkstra's algorithm", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 75, "n_words": 45, "vocab_size": 34, "complexity": 13, "nloc": 41, "token_counts": 273, "n_ast_nodes": 80, "n_identifiers": 9 }, { "id": 89927, "commit_id": "3255fa4ebb9fbc1df6bb063c0eb77a0298ca8f72", "repo": "sentry", "path": "tests/sentry/integrations/slack/notifications/test_note.py", "file_name": "test_note.py", "fun_name": "test_note_generic_issue", "commit_message": "feat(integrations): Support generic issue type alerts (#42110)\n\nAdd support for issue alerting integrations that use the message builder\r\n(Slack and MSTeams) for generic issue types.\r\n\r\n\r\nPreview text for Slack alert:\r\n\"Screen\r\n\r\nSlack generic issue alert shows the `occurrence.issue_title` and the\r\n\"important\" evidence value\r\n\"Screen\r\n\r\nMSTeams generic issue alert shows the `occurrence.issue_title` and the\r\n\"important\" evidence value\r\n\"Screen\r\n\r\n\r\nFixes #42047", "code": "def test_note_generic_issue(self, mock_func, occurrence):\n \n event = self.store_event(\n data={\"message\": \"Hellboy's world\", \"level\": \"error\"}, project_id=self.project.id\n )\n event = event.for_group(event.groups[0])\n notification = NoteActivityNotification(\n Activity(\n project=self.project,\n group=event.group,\n user=self.user,\n type=ActivityType.NOTE,\n data={\"text\": \"text\", \"mentions\": []},\n )\n )\n with self.tasks():\n notification.send()\n\n attachment, text = get_attachment()\n assert text == f\"New comment by {self.name}\"\n assert attachment[\"title\"] == TEST_ISSUE_OCCURRENCE.issue_title\n assert attachment[\"text\"] == notification.activity.data[\"text\"]\n assert (\n attachment[\"footer\"]\n == f\"{self.project.slug} | \"\n )\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 294, "n_words": 62, "vocab_size": 48, "complexity": 1, "nloc": 24, "token_counts": 151, "n_ast_nodes": 269, "n_identifiers": 30 }, { "id": 299399, "commit_id": "a9ca774e7ed1d8fe502a53d5b765c1d9b393a524", "repo": "core", "path": "homeassistant/components/insteon/api/device.py", "file_name": "device.py", "fun_name": "async_add_devices", "commit_message": "Insteon Device Control Panel (#70834)\n\nCo-authored-by: Paulus Schoutsen ", "code": "async def async_add_devices(address, multiple):\n ", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 7, "n_words": 4, "vocab_size": 4, "complexity": 2, "nloc": 3, "token_counts": 26, "n_ast_nodes": 16, "n_identifiers": 3 }, { "id": 270861, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/engine/base_layer_utils.py", "file_name": "base_layer_utils.py", "fun_name": "is_subclassed", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def is_subclassed(layer):\n \n return (\n layer.__module__.find(\"keras.engine\") == -1\n and layer.__module__.find(\"keras.layers\") == -1\n )\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 35, "n_words": 12, "vocab_size": 10, "complexity": 2, "nloc": 5, "token_counts": 32, "n_ast_nodes": 58, "n_identifiers": 4 }, { "id": 297866, "commit_id": "cb13418babd21a1e9584978b0c523f1b1e4e1cb0", "repo": "core", "path": "homeassistant/components/homematicip_cloud/alarm_control_panel.py", "file_name": "alarm_control_panel.py", "fun_name": "_async_device_changed", "commit_message": "String formatting and max line length - Part 2 (#84393)", "code": "def _async_device_changed(self, *args, **kwargs) -> None:\n \n # Don't update disabled entities\n if self.enabled:\n _LOGGER.debug(\"Event %s (%s)\", self.name, CONST_ALARM_CONTROL_PANEL_NAME)\n self.async_write_ha_state()\n else:\n _LOGGER.debug(\n (\n \"Device Changed Event for %s (Alarm Control Panel) not fired.\"\n \" Entity is disabled\"\n ),\n self.name,\n )\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 194, "n_words": 39, "vocab_size": 37, "complexity": 2, "nloc": 13, "token_counts": 52, "n_ast_nodes": 90, "n_identifiers": 10 }, { "id": 183841, "commit_id": "4dd0d9fae43583638f34257f97d5749ca4f2c00c", "repo": "textual", "path": "tests/css/test_stylesheet.py", "file_name": "test_stylesheet.py", "fun_name": "test_stylesheet_many_classes_dont_overrule_id", "commit_message": "Add various additional tests around CSS specificity", "code": "def test_stylesheet_many_classes_dont_overrule_id():\n \n css = \"#id {color: red;} .a.b.c.d {color: blue;}\"\n stylesheet = _make_stylesheet(css)\n node = DOMNode(classes=\"a b c d\", id=\"id\")\n stylesheet.apply(node)\n\n assert node.styles.color == Color(255, 0, 0)\n\n", "url": "https://github.com/Textualize/textual.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 45, "n_words": 27, "vocab_size": 24, "complexity": 1, "nloc": 6, "token_counts": 47, "n_ast_nodes": 82, "n_identifiers": 12 }, { "id": 297532, "commit_id": "b41d0be9522fabda0ac8affd2add6876a66205ea", "repo": "core", "path": "tests/components/homewizard/test_config_flow.py", "file_name": "test_config_flow.py", "fun_name": "test_check_requesterror", "commit_message": "Improve HomeWizard request issue reporting (#82366)\n\n* Trigger reauth flow when HomeWizard API was disabled\r\n\r\n* Add tests for reauth flow\r\n\r\n* Fix typo in test\r\n\r\n* Add parallel updates constant\r\n\r\n* Improve error message when device in unreachable during config\r\n\r\n* Set quality scale\r\n\r\n* Remove quality scale\r\n\r\n* Throw error instead of abort when setup fails\r\n\r\n* Adjust test for new setup behaviour\r\n\r\n* Trigger reauth flow when API is disabled and continue retrying\r\n\r\n* Reload entry and raise AuthFailed during init\r\n\r\n* Abort running config flow\r\n\r\n* Listen for coordinator updates to trigger reload\r\n\r\n* Use build-in backoff system\r\n\r\n* Fix failing test\r\n\r\n* Test reauth flow is active after disable-api init\r\n\r\n* Test reauth flow removal", "code": "async def test_check_requesterror(hass, aioclient_mock):\n \n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 7, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 18, "token_counts": 112, "n_ast_nodes": 16, "n_identifiers": 3 }, { "id": 265772, "commit_id": "204c10c053fddc26ad23ec15a3c60eee38bfc081", "repo": "netbox", "path": "netbox/utilities/utils.py", "file_name": "utils.py", "fun_name": "to_grams", "commit_message": "9654 device weight (#10448)\n\n* 9654 add weight fields to devices\r\n\r\n* 9654 changes from code review\r\n\r\n* 9654 change _abs_weight to grams\r\n\r\n* Resolve migrations conflict\r\n\r\n* 9654 code-review changes\r\n\r\n* 9654 total weight on devices\r\n\r\n* Misc cleanup\r\n\r\nCo-authored-by: Jeremy Stretch ", "code": "def to_grams(weight, unit):\n \n try:\n if weight < 0:\n raise ValueError(\"Weight must be a positive number\")\n except TypeError:\n raise TypeError(f\"Invalid value '{weight}' for weight (must be a number)\")\n\n valid_units = WeightUnitChoices.values()\n if unit not in valid_units:\n raise ValueError(f\"Unknown unit {unit}. Must be one of the following: {', '.join(valid_units)}\")\n\n if unit == WeightUnitChoices.UNIT_KILOGRAM:\n return weight * 1000\n if unit == WeightUnitChoices.UNIT_GRAM:\n return weight\n if unit == WeightUnitChoices.UNIT_POUND:\n return weight * Decimal(453.592)\n if unit == WeightUnitChoices.UNIT_OUNCE:\n return weight * Decimal(28.3495)\n raise ValueError(f\"Unknown unit {unit}. Must be 'kg', 'g', 'lb', 'oz'.\")\n\n", "url": "https://github.com/netbox-community/netbox.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 177, "n_words": 87, "vocab_size": 53, "complexity": 8, "nloc": 18, "token_counts": 106, "n_ast_nodes": 194, "n_identifiers": 14 }, { "id": 153944, "commit_id": "eddfda4b521366c628596dcb5c21775c7f50eec1", "repo": "modin", "path": "modin/core/storage_formats/pandas/query_compiler.py", "file_name": "query_compiler.py", "fun_name": "_setitem", "commit_message": "PERF-#4325: Improve perf of multi-column assignment in `__setitem__` when no new column names are assigning (#4455)\n\nCo-authored-by: Yaroslav Igoshev \r\nSigned-off-by: Myachev ", "code": "def _setitem(self, axis, key, value, how=\"inner\"):\n \n", "url": "https://github.com/modin-project/modin.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 13, "n_words": 6, "vocab_size": 6, "complexity": 4, "nloc": 27, "token_counts": 168, "n_ast_nodes": 26, "n_identifiers": 6 }, { "id": 92181, "commit_id": "8201e74ec3d81e89354905c946e62436f0247602", "repo": "sentry", "path": "tests/sentry/integrations/vercel/test_integration.py", "file_name": "test_integration.py", "fun_name": "test_update_organization_config", "commit_message": "ref(integrations): Update Vercel endpoints (#36150)\n\nThis PR updates the endpoints we reach to in the Vercel integration. It seems to work just fine without changes as the payloads returned from vercel haven't updated, but we'll need to specify API Scopes so they don't receive 403s.\r\n\r\nThis also refactored the pagination code to loop 100 at a time, indefinitely\r\n\r\nI had previously tried to consolidate the project webhooks in this PR, but I'll be doing that separately.", "code": "def test_update_organization_config(self):\n \n with self.tasks():\n self.assert_setup_flow()\n\n org = self.organization\n project_id = self.project.id\n enabled_dsn = ProjectKey.get_default(project=Project.objects.get(id=project_id)).get_dsn(\n public=True\n )\n sentry_auth_token = SentryAppInstallationToken.objects.get_token(org.id, \"vercel\")\n\n env_var_map = {\n \"SENTRY_ORG\": {\"type\": \"encrypted\", \"value\": org.slug},\n \"SENTRY_PROJECT\": {\"type\": \"encrypted\", \"value\": self.project.slug},\n \"SENTRY_DSN\": {\"type\": \"encrypted\", \"value\": enabled_dsn},\n \"SENTRY_AUTH_TOKEN\": {\"type\": \"encrypted\", \"value\": sentry_auth_token},\n \"VERCEL_GIT_COMMIT_SHA\": {\"type\": \"system\", \"value\": \"VERCEL_GIT_COMMIT_SHA\"},\n }\n\n # mock get_project API call\n responses.add(\n responses.GET,\n f\"{VercelClient.base_url}{VercelClient.GET_PROJECT_URL % self.project_id}\",\n json={\"link\": {\"type\": \"github\"}, \"framework\": \"nextjs\"},\n )\n\n # mock create the env vars\n for env_var, details in env_var_map.items():\n responses.add(\n responses.POST,\n f\"{VercelClient.base_url}{VercelClient.CREATE_ENV_VAR_URL % self.project_id}\",\n json={\n \"key\": env_var,\n \"value\": details[\"value\"],\n \"target\": [\"production\"],\n \"type\": details[\"type\"],\n },\n )\n\n integration = Integration.objects.get(provider=self.provider.key)\n installation = integration.get_installation(org.id)\n org_integration = OrganizationIntegration.objects.get(\n organization_id=org.id, integration_id=integration.id\n )\n assert org_integration.config == {}\n data = {\"project_mappings\": [[project_id, self.project_id]]}\n\n installation.update_organization_config(data)\n org_integration = OrganizationIntegration.objects.get(\n organization_id=org.id, integration_id=integration.id\n )\n assert org_integration.config == {\"project_mappings\": [[project_id, self.project_id]]}\n\n # assert the env vars were created correctly\n req_params = json.loads(responses.calls[5].request.body)\n assert req_params[\"key\"] == \"SENTRY_ORG\"\n assert req_params[\"value\"] == org.slug\n assert req_params[\"target\"] == [\"production\"]\n assert req_params[\"type\"] == \"encrypted\"\n\n req_params = json.loads(responses.calls[6].request.body)\n assert req_params[\"key\"] == \"SENTRY_PROJECT\"\n assert req_params[\"value\"] == self.project.slug\n assert req_params[\"target\"] == [\"production\"]\n assert req_params[\"type\"] == \"encrypted\"\n\n req_params = json.loads(responses.calls[7].request.body)\n assert req_params[\"key\"] == \"NEXT_PUBLIC_SENTRY_DSN\"\n assert req_params[\"value\"] == enabled_dsn\n assert req_params[\"target\"] == [\"production\"]\n assert req_params[\"type\"] == \"encrypted\"\n\n req_params = json.loads(responses.calls[8].request.body)\n assert req_params[\"key\"] == \"SENTRY_AUTH_TOKEN\"\n assert req_params[\"target\"] == [\"production\"]\n assert req_params[\"type\"] == \"encrypted\"\n\n req_params = json.loads(responses.calls[9].request.body)\n assert req_params[\"key\"] == \"VERCEL_GIT_COMMIT_SHA\"\n assert req_params[\"value\"] == \"VERCEL_GIT_COMMIT_SHA\"\n assert req_params[\"target\"] == [\"production\"]\n assert req_params[\"type\"] == \"system\"\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 858, "n_words": 225, "vocab_size": 107, "complexity": 2, "nloc": 68, "token_counts": 566, "n_ast_nodes": 1025, "n_identifiers": 52 }, { "id": 293197, "commit_id": "26c5dca45d9b3dee002dfe1549780747e5007e06", "repo": "core", "path": "homeassistant/components/elkm1/config_flow.py", "file_name": "config_flow.py", "fun_name": "async_step_manual_connection", "commit_message": "Ensure elkm1 can be manually configured when discovered instance is not used (#67712)", "code": "async def async_step_manual_connection(self, user_input=None):\n \n errors = {}\n if user_input is not None:\n # We might be able to discover the device via directed UDP\n # in case its on another subnet\n if device := await async_discover_device(\n self.hass, user_input[CONF_ADDRESS]\n ):\n await self.async_set_unique_id(\n dr.format_mac(device.mac_address), raise_on_progress=False\n )\n self._abort_if_unique_id_configured()\n # Ignore the port from discovery since its always going to be\n # 2601 if secure is turned on even though they may want insecure\n user_input[CONF_ADDRESS] = device.ip_address\n errors, result = await self._async_create_or_error(user_input, False)\n if not errors:\n return result\n\n return self.async_show_form(\n step_id=\"manual_connection\",\n data_schema=vol.Schema(\n {\n **BASE_SCHEMA,\n vol.Required(CONF_ADDRESS): str,\n vol.Optional(CONF_PREFIX, default=\"\"): str,\n vol.Required(\n CONF_PROTOCOL, default=DEFAULT_SECURE_PROTOCOL\n ): vol.In(ALL_PROTOCOLS),\n }\n ),\n errors=errors,\n )\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 536, "n_words": 104, "vocab_size": 80, "complexity": 4, "nloc": 28, "token_counts": 153, "n_ast_nodes": 242, "n_identifiers": 32 }, { "id": 224049, "commit_id": "e7f07cc82ab2be920ab426ba07456d8b2592714d", "repo": "mkdocs", "path": "mkdocs/tests/plugin_tests.py", "file_name": "plugin_tests.py", "fun_name": "on_page_read_source", "commit_message": "Remove spaces at the ends of docstrings, normalize quotes", "code": "def on_page_read_source(self, **kwargs):\n \n return f'{self.config[\"foo\"]} source'\n", "url": "https://github.com/mkdocs/mkdocs.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 2, "token_counts": 12, "n_ast_nodes": 35, "n_identifiers": 4 }, { "id": 259640, "commit_id": "ade90145c9c660a1a7baf2315185995899b0f356", "repo": "scikit-learn", "path": "sklearn/manifold/_t_sne.py", "file_name": "_t_sne.py", "fun_name": "trustworthiness", "commit_message": "FIX Raise error when n_neighbors >= n_samples / 2 in manifold.trustworthiness (#23033)\n\nCo-authored-by: Shao Yang Hong \r\nCo-authored-by: Thomas J. Fan \r\nCo-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com>", "code": "def trustworthiness(X, X_embedded, *, n_neighbors=5, metric=\"euclidean\"):\n r\n n_samples = X.shape[0]\n if n_neighbors >= n_samples / 2:\n raise ValueError(\n f\"n_neighbors ({n_neighbors}) should be less than n_samples / 2\"\n f\" ({n_samples / 2})\"\n )\n dist_X = pairwise_distances(X, metric=metric)\n if metric == \"precomputed\":\n dist_X = dist_X.copy()\n # we set the diagonal to np.inf to exclude the points themselves from\n # their own neighborhood\n np.fill_diagonal(dist_X, np.inf)\n ind_X = np.argsort(dist_X, axis=1)\n # `ind_X[i]` is the index of sorted distances between i and other samples\n ind_X_embedded = (\n NearestNeighbors(n_neighbors=n_neighbors)\n .fit(X_embedded)\n .kneighbors(return_distance=False)\n )\n\n # We build an inverted index of neighbors in the input space: For sample i,\n # we define `inverted_index[i]` as the inverted index of sorted distances:\n # inverted_index[i][ind_X[i]] = np.arange(1, n_sample + 1)\n inverted_index = np.zeros((n_samples, n_samples), dtype=int)\n ordered_indices = np.arange(n_samples + 1)\n inverted_index[ordered_indices[:-1, np.newaxis], ind_X] = ordered_indices[1:]\n ranks = (\n inverted_index[ordered_indices[:-1, np.newaxis], ind_X_embedded] - n_neighbors\n )\n t = np.sum(ranks[ranks > 0])\n t = 1.0 - t * (\n 2.0 / (n_samples * n_neighbors * (2.0 * n_samples - 3.0 * n_neighbors - 1.0))\n )\n return t\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 322, "n_words": 173, "vocab_size": 115, "complexity": 3, "nloc": 84, "token_counts": 228, "n_ast_nodes": 352, "n_identifiers": 32 }, { "id": 132895, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "python/ray/util/actor_group.py", "file_name": "actor_group.py", "fun_name": "start", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def start(self):\n \n if self.actors and len(self.actors) > 0:\n raise RuntimeError(\n \"The actors have already been started. \"\n \"Please call `shutdown` first if you want to \"\n \"restart them.\"\n )\n\n logger.debug(f\"Starting {self.num_actors} actors.\")\n self.add_actors(self.num_actors)\n logger.debug(f\"{len(self.actors)} actors have successfully started.\")\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 140, "n_words": 38, "vocab_size": 34, "complexity": 3, "nloc": 10, "token_counts": 49, "n_ast_nodes": 108, "n_identifiers": 9 }, { "id": 126264, "commit_id": "eb69c1ca286a2eec594f02ddaf546657a8127afd", "repo": "ray", "path": "python/ray/tune/utils/util.py", "file_name": "util.py", "fun_name": "_detect_checkpoint_function", "commit_message": "[air] Add annotation for Tune module. (#27060)\n\nCo-authored-by: Kai Fricke ", "code": "def _detect_checkpoint_function(train_func, abort=False, partial=False):\n \n func_sig = inspect.signature(train_func)\n validated = True\n try:\n # check if signature is func(config, checkpoint_dir=None)\n if partial:\n func_sig.bind_partial({}, checkpoint_dir=\"tmp/path\")\n else:\n func_sig.bind({}, checkpoint_dir=\"tmp/path\")\n except Exception as e:\n logger.debug(str(e))\n validated = False\n if abort and not validated:\n func_args = inspect.getfullargspec(train_func).args\n raise ValueError(\n \"Provided training function must have 2 args \"\n \"in the signature, and the latter arg must \"\n \"contain `checkpoint_dir`. For example: \"\n \"`func(config, checkpoint_dir=None)`. Got {}\".format(func_args)\n )\n return validated\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 215, "n_words": 72, "vocab_size": 59, "complexity": 5, "nloc": 20, "token_counts": 102, "n_ast_nodes": 179, "n_identifiers": 21 }, { "id": 323123, "commit_id": "44a290e94d1becd1f09fddc3d873f9e19c9d6919", "repo": "PaddleNLP", "path": "paddlenlp/trainer/trainer_args.py", "file_name": "trainer_args.py", "fun_name": "should_log", "commit_message": "[Trainer] Add init version of paddlenlp trainer and apply finetune for ernie-1.0 pretraining. (#1761)\n\n* add some datasets for finetune.\r\n\r\n* support fine tune for all tastks.\r\n\r\n* add trainer prototype.\r\n\r\n* init verison for paddlenlp trainer.\r\n\r\n* refine trainer.\r\n\r\n* update for some details.\r\n\r\n* support multi-cards training evaluation.\r\n\r\n* support load from ckpt.\r\n\r\n* support for export inference model.\r\n\r\n* first version of trainer.\r\n\r\n* seq cls support clue.\r\n\r\n* trainer support for token classification and question answersing tasks.\r\n\r\n* fix as reviews.\r\n\r\nCo-authored-by: Zeyu Chen ", "code": "def should_log(self):\n \n if self.log_on_each_node:\n return self.local_process_index == 0\n else:\n return self.process_index == 0\n", "url": "https://github.com/PaddlePaddle/PaddleNLP.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 56, "n_words": 13, "vocab_size": 10, "complexity": 2, "nloc": 5, "token_counts": 25, "n_ast_nodes": 43, "n_identifiers": 5 }, { "id": 300405, "commit_id": "b70e97e949ca73fe57849625c0b0c51f0b8796f7", "repo": "core", "path": "tests/components/template/test_number.py", "file_name": "test_number.py", "fun_name": "test_all_optional_config", "commit_message": "Remove unused calls fixture from template tests (#71735)", "code": "async def test_all_optional_config(hass):\n \n with assert_setup_component(1, \"template\"):\n assert await setup.async_setup_component(\n hass,\n \"template\",\n {\n \"template\": {\n \"number\": {\n \"state\": \"{{ 4 }}\",\n \"set_value\": {\"service\": \"script.set_value\"},\n \"min\": \"{{ 3 }}\",\n \"max\": \"{{ 5 }}\",\n \"step\": \"{{ 1 }}\",\n }\n }\n },\n )\n\n await hass.async_block_till_done()\n await hass.async_start()\n await hass.async_block_till_done()\n\n _verify(hass, 4, 1, 3, 5)\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 309, "n_words": 50, "vocab_size": 37, "complexity": 1, "nloc": 21, "token_counts": 90, "n_ast_nodes": 169, "n_identifiers": 8 }, { "id": 167393, "commit_id": "4bb1fd50a63badd38b5d96d9c4323dae7bc36d8d", "repo": "pandas", "path": "pandas/plotting/_misc.py", "file_name": "_misc.py", "fun_name": "radviz", "commit_message": "TYP: Missing return annotations in util/tseries/plotting (#47510)\n\n* TYP: Missing return annotations in util/tseries/plotting\r\n\r\n* the more tricky parts", "code": "def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds) -> Axes:\n \n plot_backend = _get_plot_backend(\"matplotlib\")\n return plot_backend.radviz(\n frame=frame,\n class_column=class_column,\n ax=ax,\n color=color,\n colormap=colormap,\n **kwds,\n )\n\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 75, "n_words": 21, "vocab_size": 21, "complexity": 1, "nloc": 79, "token_counts": 60, "n_ast_nodes": 88, "n_identifiers": 10 }, { "id": 266663, "commit_id": "68fb3bf90efa3a722ba5ab7d66b1b22adc73198c", "repo": "ansible", "path": "test/lib/ansible_test/_util/target/setup/requirements.py", "file_name": "requirements.py", "fun_name": "download_file", "commit_message": "ansible-test - Fix consistency of managed venvs. (#77028)", "code": "def download_file(url, path): # type: (str, str) -> None\n \n with open(to_bytes(path), 'wb') as saved_file:\n download = urlopen(url)\n shutil.copyfileobj(download, saved_file)\n\n", "url": "https://github.com/ansible/ansible.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 40, "n_words": 19, "vocab_size": 19, "complexity": 1, "nloc": 4, "token_counts": 35, "n_ast_nodes": 63, "n_identifiers": 10 }, { "id": 46474, "commit_id": "ca4b8d1744cd1de9b6af97dacb0e03de0f014006", "repo": "airflow", "path": "airflow/providers/google/cloud/links/vertex_ai.py", "file_name": "vertex_ai.py", "fun_name": "extract_bucket_name", "commit_message": "Create Endpoint and Model Service, Batch Prediction and Hyperparameter Tuning Jobs operators for Vertex AI service (#22088)", "code": "def extract_bucket_name(config):\n \n return config[\"artifact_destination\"][\"output_uri_prefix\"].rpartition(\"gs://\")[-1]\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 18, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 23, "n_ast_nodes": 44, "n_identifiers": 3 }, { "id": 12472, "commit_id": "16b16b07a66cd5a8fc7cca1d3f1c378a9c63d38c", "repo": "jina", "path": "jina/exporter.py", "file_name": "exporter.py", "fun_name": "export_kubernetes", "commit_message": "refactor: rename cli to jina_cli (#4890)\n\n* chore: fix readme\r\n\r\n* chore: fix readme\r\n\r\n* chore: fix dockerignore\r\n\r\n* fix: #4845\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix: cicd export cli\r\n\r\nCo-authored-by: Jina Dev Bot ", "code": "def export_kubernetes(args):\n \n Flow.load_config(args.flowpath).to_kubernetes_yaml(\n output_base_path=args.outpath, k8s_namespace=args.k8s_namespace\n )\n\n", "url": "https://github.com/jina-ai/jina.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 22, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 4, "token_counts": 29, "n_ast_nodes": 48, "n_identifiers": 9 }, { "id": 86267, "commit_id": "ae9c0d8a33d509d9719a5a03e06c9797741877e9", "repo": "sentry", "path": "src/sentry/lang/javascript/processor.py", "file_name": "processor.py", "fun_name": "expand_frame", "commit_message": "ref(processor): Use symbolic-sourcemapcache for JavaScript Sourcemap processing (#38551)\n\nThis PR attempts to replace the currently used `rust-sourcemap` crate\r\nand it's symbolic python bindings, with `symbolic-sourcemapcache` crate.\r\n\r\nIt makes the whole processing pipeline easier to maintain, as it pushes\r\nsome work directly to Symbolic, as well as we get better function names\r\ndue to better scope resolution and in some cases better file URLs.\r\n\r\nOther than that, we don't use `SourceView` anymore, as it seemed like an\r\nunnecessary layer of abstraction for something that is used only for\r\n`context_lines` extraction. We cache `utf-8` decoded sources directly\r\nnow, as this way we can encode them only once for `SmCache` instance\r\ninitialization, and use the source directly otherwise for context lines\r\nextraction.\r\n\r\nSome tests had to updated to express current behavior.\r\n\r\nThe notable thing is `useless_fn_names = [\"\",\r\n\"__webpack_require__\", \"__webpack_modules__\"]`, which is mostly for\r\n`production` mode of webpack, that by default trims all the function\r\nnames, and we decided to fallback to the minified names in those cases\r\ninstead (this was already the old behavior).\r\n\r\nIt should be possible to extract something better, but we'd need to\r\nparse all `sourceContents` from sourcemap to do that, as the only thing\r\nwe can get better function name for the case mentioned above, is if we\r\nlook at the right-hand side of default node export, in form of\r\n`module.exports = function foo () {}`. This should give us `foo`, yet\r\nthe only thing we can extract is `module.exports`, as minified form of\r\nthis expression in webpack production mode is `module.exports = function\r\n() {}`.", "code": "def expand_frame(self, frame, source_context=None, source=None):\n \n\n if frame.get(\"lineno\") is None:\n return False\n\n if source_context is None:\n source = source or self.get_sourceview(frame[\"abs_path\"])\n if source is None:\n logger.debug(\"No source found for %s\", frame[\"abs_path\"])\n return False\n\n (pre_context, context_line, post_context) = source_context or get_raw_source_context(\n source=source, lineno=frame[\"lineno\"]\n )\n\n if pre_context is not None and len(pre_context) > 0:\n frame[\"pre_context\"] = [trim_line(x) for x in pre_context]\n if context_line is not None:\n frame[\"context_line\"] = trim_line(context_line, frame.get(\"colno\") or 0)\n if post_context is not None and len(post_context) > 0:\n frame[\"post_context\"] = [trim_line(x) for x in post_context]\n\n return True\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 257, "n_words": 87, "vocab_size": 50, "complexity": 14, "nloc": 18, "token_counts": 169, "n_ast_nodes": 272, "n_identifiers": 17 }, { "id": 159095, "commit_id": "f00148b089d326c952880a0e5e6bd4b2dcb98ce5", "repo": "rasa", "path": "tests/utils/test_common.py", "file_name": "test_common.py", "fun_name": "test_cli_log_level_debug_used", "commit_message": "Configurable logging for libraries (#10614)\n\n* Make library level logging to be configurable\r\n\r\nFixes https://github.com/RasaHQ/rasa/issues/10203\r\n\r\n* Create log level documentation under cheatsheet in Rasa docs\r\n\r\n* Add log docs to `rasa shell --debug` (and others)", "code": "def test_cli_log_level_debug_used():\n \n configure_logging_and_warnings(logging.DEBUG)\n rasa_logger = logging.getLogger(\"rasa\")\n rasa_logger.level == logging.DEBUG\n matplotlib_logger = logging.getLogger(\"matplotlib\")\n # Default log level for libraries is currently ERROR\n matplotlib_logger.level == logging.ERROR\n\n\n@mock.patch.dict(os.environ, {\"LOG_LEVEL\": \"WARNING\"})", "url": "https://github.com/RasaHQ/rasa.git", "language": "Python", "ast_errors": "@mock.patch.dict(os.environ, {\"LOG_LEVEL\": \"WARNING\"})", "n_ast_errors": 1, "ast_levels": 9, "n_whitespaces": 47, "n_words": 27, "vocab_size": 25, "complexity": 1, "nloc": 6, "token_counts": 41, "n_ast_nodes": 105, "n_identifiers": 14 }, { "id": 101184, "commit_id": "32950897376b48e0f08b46385602e4df902cf49e", "repo": "faceswap", "path": "tools/manual/faceviewer/viewport.py", "file_name": "viewport.py", "fun_name": "_obtain_mask", "commit_message": "lib.detected_face.Mask\n - Add source + target offset and coverage to set_sub_crop method", "code": "def _obtain_mask(cls, detected_face, mask_type):\n \n mask = detected_face.mask.get(mask_type)\n if not mask:\n return None\n if mask.stored_centering != \"face\":\n face = AlignedFace(detected_face.landmarks_xy)\n mask.set_sub_crop(face.pose.offset[mask.stored_centering],\n face.pose.offset[\"face\"],\n centering=\"face\")\n return mask.mask.squeeze()\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 150, "n_words": 24, "vocab_size": 21, "complexity": 3, "nloc": 10, "token_counts": 77, "n_ast_nodes": 126, "n_identifiers": 15 }, { "id": 259191, "commit_id": "a794c58692a1f3e7a85a42d8c7f7ddd5fcf18baa", "repo": "scikit-learn", "path": "sklearn/ensemble/_bagging.py", "file_name": "_bagging.py", "fun_name": "_estimator_has", "commit_message": "MNT Replace if_delegate_has_method with available_if in ensemble and semi_supervised (#20545)\n\nCo-authored-by: Guillaume Lemaitre \r\nCo-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com>", "code": "def _estimator_has(attr):\n \n return lambda self: (\n hasattr(self.estimators_[0], attr)\n if hasattr(self, \"estimators_\")\n else hasattr(self.base_estimator, attr)\n )\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 45, "n_words": 15, "vocab_size": 14, "complexity": 2, "nloc": 6, "token_counts": 39, "n_ast_nodes": 62, "n_identifiers": 6 }, { "id": 286398, "commit_id": "09f753da1c2a2f03c41fe6a3ca2eb79f6ea58995", "repo": "OpenBBTerminal", "path": "openbb_terminal/cryptocurrency/crypto_controller.py", "file_name": "crypto_controller.py", "fun_name": "call_find", "commit_message": "More Fixes to Crypto + key sort (#3244)\n\n* fix #3095 - autocomplete and command working + key sort\r\n\r\n* fix #3056\r\n\r\n* fix [Bug] bugs #3048\r\n\r\n* fix [Bug] bug #3017\r\n\r\n* sort -> sortby, not ascend, tests\r\n\r\n* fix my goof ups\r\n\r\nCo-authored-by: james ", "code": "def call_find(self, other_args):\n \n parser = argparse.ArgumentParser(\n prog=\"find\",\n add_help=False,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description=,\n )\n parser.add_argument(\n \"-c\",\n \"--coin\",\n help=\"Symbol Name or Id of Coin\",\n dest=\"coin\",\n required=\"-h\" not in other_args,\n type=str,\n )\n parser.add_argument(\n \"-k\",\n \"--key\",\n dest=\"key\",\n help=\"Specify by which column you would like to search: symbol, name, id\",\n type=str,\n choices=FIND_KEYS,\n default=\"symbol\",\n )\n parser.add_argument(\n \"-l\",\n \"--limit\",\n default=10,\n dest=\"limit\",\n help=\"Number of records to display\",\n type=check_positive,\n )\n parser.add_argument(\n \"-s\",\n \"--skip\",\n default=0,\n dest=\"skip\",\n help=\"Skip n of records\",\n type=check_positive,\n )\n if other_args and not other_args[0][0] == \"-\":\n other_args.insert(0, \"-c\")\n\n ns_parser = self.parse_known_args_and_warn(\n parser,\n other_args,\n EXPORT_ONLY_RAW_DATA_ALLOWED,\n )\n # TODO: merge find + display_all_coins\n if ns_parser:\n if ns_parser.coin == \"ALL\":\n display_all_coins(\n symbol=ns_parser.coin,\n source=ns_parser.source,\n limit=ns_parser.limit,\n skip=ns_parser.skip,\n show_all=True,\n export=ns_parser.export,\n )\n else:\n find(\n query=ns_parser.coin,\n source=ns_parser.source,\n key=ns_parser.key,\n limit=ns_parser.limit,\n export=ns_parser.export,\n )\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 880, "n_words": 114, "vocab_size": 90, "complexity": 5, "nloc": 82, "token_counts": 257, "n_ast_nodes": 406, "n_identifiers": 36 }, { "id": 190078, "commit_id": "9d1f066d637cb15baea10e6907ab85efff8fb36f", "repo": "manim", "path": "manim/utils/tex_file_writing.py", "file_name": "tex_file_writing.py", "fun_name": "generate_tex_file", "commit_message": "Migrate more `os.path` to `pathlib` (#2980)\n\n* Migrate more `os.path` to `pathlib`\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* fix type errors with recent pathlib code\r\n\r\n* pathlib fixes\r\n\r\n* more pathlib fixes\r\n\r\n* remove unused imports introduced by pathlib migration\r\n\r\n* convert `open()` calls to pathlib\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* Migrate tex_file_writing to pathlib\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* converted more old code to pathlib, and fixed a bug in module_ops\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* fix test failures\r\n\r\n* [pre-commit.ci] auto fixes from pre-commit.com hooks\r\n\r\nfor more information, see https://pre-commit.ci\r\n\r\n* fix test failures\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Benjamin Hackl \r\n\r\nCo-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>\r\nCo-authored-by: Benjamin Hackl ", "code": "def generate_tex_file(expression, environment=None, tex_template=None):\n \n if tex_template is None:\n tex_template = config[\"tex_template\"]\n if environment is not None:\n output = tex_template.get_texcode_for_expression_in_env(expression, environment)\n else:\n output = tex_template.get_texcode_for_expression(expression)\n\n tex_dir = config.get_dir(\"tex_dir\")\n if not tex_dir.exists():\n tex_dir.mkdir()\n\n result = tex_dir / (tex_hash(output) + \".tex\")\n if not result.exists():\n logger.info(\n \"Writing %(expression)s to %(path)s\",\n {\"expression\": expression, \"path\": f\"{result}\"},\n )\n result.write_text(output, encoding=\"utf-8\")\n return result\n\n", "url": "https://github.com/ManimCommunity/manim.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 153, "n_words": 55, "vocab_size": 40, "complexity": 5, "nloc": 18, "token_counts": 122, "n_ast_nodes": 213, "n_identifiers": 18 }, { "id": 246370, "commit_id": "546b9c9e648f5e2b25bb7c8350570787ff9befae", "repo": "synapse", "path": "tests/storage/databases/test_state_store.py", "file_name": "test_state_store.py", "fun_name": "test_in_flight_requests_stop_being_in_flight", "commit_message": "Add more tests for in-flight state query duplication. (#12033)", "code": "def test_in_flight_requests_stop_being_in_flight(self) -> None:\n \n req1 = ensureDeferred(\n self.state_datastore._get_state_for_group_using_inflight_cache(\n 42, StateFilter.all()\n )\n )\n self.pump(by=0.1)\n\n # This should have gone to the database\n self.assertEqual(len(self.get_state_group_calls), 1)\n self.assertFalse(req1.called)\n\n # Complete the request right away.\n self._complete_request_fake(*self.get_state_group_calls[0])\n self.assertTrue(req1.called)\n\n # Send off another request\n req2 = ensureDeferred(\n self.state_datastore._get_state_for_group_using_inflight_cache(\n 42, StateFilter.all()\n )\n )\n self.pump(by=0.1)\n\n # It should have gone to the database again, because the previous request\n # isn't in-flight and therefore isn't available for deduplication.\n self.assertEqual(len(self.get_state_group_calls), 2)\n self.assertFalse(req2.called)\n\n # Complete the request right away.\n self._complete_request_fake(*self.get_state_group_calls[1])\n self.assertTrue(req2.called)\n groups, sf, d = self.get_state_group_calls[0]\n\n self.assertEqual(self.get_success(req1), FAKE_STATE)\n self.assertEqual(self.get_success(req2), FAKE_STATE)\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 330, "n_words": 88, "vocab_size": 55, "complexity": 1, "nloc": 29, "token_counts": 186, "n_ast_nodes": 295, "n_identifiers": 23 }, { "id": 266036, "commit_id": "ea6d86e6c4bb6037465410db6205a7471bc81a6c", "repo": "netbox", "path": "netbox/extras/tests/test_customfields.py", "file_name": "test_customfields.py", "fun_name": "test_cf_data", "commit_message": "Closes #10052: The cf attribute now returns deserialized custom field data", "code": "def test_cf_data(self):\n \n site = Site(name='Test Site', slug='test-site')\n\n # Check custom field data on new instance\n site.custom_field_data['foo'] = 'abc'\n self.assertEqual(site.cf['foo'], 'abc')\n\n # Check custom field data from database\n site.save()\n site = Site.objects.get(name='Test Site')\n self.assertEqual(site.cf['foo'], 'abc')\n", "url": "https://github.com/netbox-community/netbox.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 97, "n_words": 34, "vocab_size": 24, "complexity": 1, "nloc": 7, "token_counts": 69, "n_ast_nodes": 129, "n_identifiers": 12 }, { "id": 200289, "commit_id": "6d2bbf80752549276a968fd4af78231c569d55c5", "repo": "sympy", "path": "sympy/testing/runtests.py", "file_name": "runtests.py", "fun_name": "convert_to_native_paths", "commit_message": "runtests.py: Undo auto-formatting, re-add changes to blacklist for scipy, numpy", "code": "def convert_to_native_paths(lst):\n \n newlst = []\n for i, rv in enumerate(lst):\n rv = os.path.join(*rv.split(\"/\"))\n # on windows the slash after the colon is dropped\n if sys.platform == \"win32\":\n pos = rv.find(':')\n if pos != -1:\n if rv[pos + 1] != '\\\\':\n rv = rv[:pos + 1] + '\\\\' + rv[pos + 1:]\n newlst.append(os.path.normcase(rv))\n return newlst\n\n", "url": "https://github.com/sympy/sympy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 150, "n_words": 54, "vocab_size": 37, "complexity": 5, "nloc": 11, "token_counts": 101, "n_ast_nodes": 176, "n_identifiers": 16 }, { "id": 60371, "commit_id": "cc4d0564756ca067516f71718a3d135996525909", "repo": "transferlearning", "path": "code/deep/BJMMD/caffe/scripts/cpp_lint.py", "file_name": "cpp_lint.py", "fun_name": "ProcessFile", "commit_message": "Balanced joint maximum mean discrepancy for deep transfer learning", "code": "def ProcessFile(filename, vlevel, extra_check_functions=[]):\n \n\n _SetVerboseLevel(vlevel)\n\n try:\n # Support the UNIX convention of using \"-\" for stdin. Note that\n # we are not opening the file with universal newline support\n # (which codecs doesn't support anyway), so the resulting lines do\n # contain trailing '\\r' characters if we are reading a file that\n # has CRLF endings.\n # If after the split a trailing '\\r' is present, it is removed\n # below. If it is not expected to be present (i.e. os.linesep !=\n # '\\r\\n' as in Windows), a warning is issued below if this file\n # is processed.\n\n if filename == '-':\n lines = codecs.StreamReaderWriter(sys.stdin,\n codecs.getreader('utf8'),\n codecs.getwriter('utf8'),\n 'replace').read().split('\\n')\n else:\n lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\\n')\n\n carriage_return_found = False\n # Remove trailing '\\r'.\n for linenum in range(len(lines)):\n if lines[linenum].endswith('\\r'):\n lines[linenum] = lines[linenum].rstrip('\\r')\n carriage_return_found = True\n\n except IOError:\n sys.stderr.write(\n \"Skipping input '%s': Can't open for reading\\n\" % filename)\n return\n\n # Note, if no dot is found, this will give the entire filename as the ext.\n file_extension = filename[filename.rfind('.') + 1:]\n\n # When reading from stdin, the extension is unknown, so no cpplint tests\n # should rely on the extension.\n if filename != '-' and file_extension not in _valid_extensions:\n sys.stderr.write('Ignoring %s; not a valid file name '\n '(%s)\\n' % (filename, ', '.join(_valid_extensions)))\n else:\n ProcessFileData(filename, file_extension, lines, Error,\n extra_check_functions)\n if carriage_return_found and os.linesep != '\\r\\n':\n # Use 0 for linenum since outputting only one error for potentially\n # several lines.\n Error(filename, 0, 'whitespace/newline', 1,\n 'One or more unexpected \\\\r (^M) found;'\n 'better to use only a \\\\n')\n\n sys.stderr.write('Done processing %s\\n' % filename)\n\n", "url": "https://github.com/jindongwang/transferlearning.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 556, "n_words": 258, "vocab_size": 171, "complexity": 9, "nloc": 31, "token_counts": 230, "n_ast_nodes": 424, "n_identifiers": 32 }, { "id": 36020, "commit_id": "50dd314d939a86f3a81e19af01459f449fbaeeca", "repo": "transformers", "path": "src/transformers/onnx/config.py", "file_name": "config.py", "fun_name": "default_batch_size", "commit_message": "Add ONNX export for ViT (#15658)\n\n* Add ONNX support for ViT\r\n\r\n* Refactor to use generic preprocessor\r\n\r\n* Add vision dep to tests\r\n\r\n* Extend ONNX slow tests to ViT\r\n\r\n* Add dummy image generator\r\n\r\n* Use model_type to determine modality\r\n\r\n* Add deprecation warnings for tokenizer argument\r\n\r\n* Add warning when overwriting the preprocessor\r\n\r\n* Add optional args to docstrings\r\n\r\n* Add minimum PyTorch version to OnnxConfig\r\n\r\n* Refactor OnnxConfig class variables from CONSTANT_NAME to snake_case\r\n\r\n* Add reasonable value for default atol\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>", "code": "def default_batch_size(self) -> int:\n \n # Using 2 avoid ONNX making assumption about single sample batch\n return OnnxConfig.default_fixed_batch\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 38, "n_words": 17, "vocab_size": 17, "complexity": 1, "nloc": 8, "token_counts": 12, "n_ast_nodes": 23, "n_identifiers": 5 }, { "id": 272037, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/feature_column/dense_features.py", "file_name": "dense_features.py", "fun_name": "_tracking_metadata", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _tracking_metadata(self):\n \n metadata = json.loads(super()._tracking_metadata)\n metadata[\"_is_feature_layer\"] = True\n return json.dumps(metadata, default=json_utils.get_json_type)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 39, "n_words": 11, "vocab_size": 10, "complexity": 1, "nloc": 4, "token_counts": 37, "n_ast_nodes": 63, "n_identifiers": 10 }, { "id": 176155, "commit_id": "dec723f072eb997a497a159dbe8674cd39999ee9", "repo": "networkx", "path": "networkx/generators/small.py", "file_name": "small.py", "fun_name": "tutte_graph", "commit_message": "Docstrings for the small.py module (#5240)\n\n* added description for the first 5 small graphs\r\n\r\n* modified descriptions based on comment and added description for two more functions\r\n\r\n* added doctrings to all the functions\r\n\r\n* Minor touchups.\r\n\r\nCo-authored-by: Ross Barnowski ", "code": "def tutte_graph(create_using=None):\n \n description = [\n \"adjacencylist\",\n \"Tutte's Graph\",\n 46,\n [\n [2, 3, 4],\n [5, 27],\n [11, 12],\n [19, 20],\n [6, 34],\n [7, 30],\n [8, 28],\n [9, 15],\n [10, 39],\n [11, 38],\n [40],\n [13, 40],\n [14, 36],\n [15, 16],\n [35],\n [17, 23],\n [18, 45],\n [19, 44],\n [46],\n [21, 46],\n [22, 42],\n [23, 24],\n [41],\n [25, 28],\n [26, 33],\n [27, 32],\n [34],\n [29],\n [30, 33],\n [31],\n [32, 34],\n [33],\n [],\n [],\n [36, 39],\n [37],\n [38, 40],\n [39],\n [],\n [],\n [42, 45],\n [43],\n [44, 46],\n [45],\n [],\n [],\n ],\n ]\n G = make_small_undirected_graph(description, create_using)\n return G\n", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 649, "n_words": 93, "vocab_size": 76, "complexity": 1, "nloc": 56, "token_counts": 267, "n_ast_nodes": 334, "n_identifiers": 5 }, { "id": 111539, "commit_id": "1f23c615d7a7326ca5a38a7d768b8b70caaa0e17", "repo": "spaCy", "path": "spacy/tests/pipeline/test_entity_linker.py", "file_name": "test_entity_linker.py", "fun_name": "test_append_invalid_alias", "commit_message": "Refactor KB for easier customization (#11268)\n\n* Add implementation of batching + backwards compatibility fixes. Tests indicate issue with batch disambiguation for custom singular entity lookups.\r\n\r\n* Fix tests. Add distinction w.r.t. batch size.\r\n\r\n* Remove redundant and add new comments.\r\n\r\n* Adjust comments. Fix variable naming in EL prediction.\r\n\r\n* Fix mypy errors.\r\n\r\n* Remove KB entity type config option. Change return types of candidate retrieval functions to Iterable from Iterator. Fix various other issues.\r\n\r\n* Update spacy/pipeline/entity_linker.py\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Update spacy/pipeline/entity_linker.py\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Update spacy/kb_base.pyx\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Update spacy/kb_base.pyx\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Update spacy/pipeline/entity_linker.py\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Add error messages to NotImplementedErrors. Remove redundant comment.\r\n\r\n* Fix imports.\r\n\r\n* Remove redundant comments.\r\n\r\n* Rename KnowledgeBase to InMemoryLookupKB and BaseKnowledgeBase to KnowledgeBase.\r\n\r\n* Fix tests.\r\n\r\n* Update spacy/errors.py\r\n\r\nCo-authored-by: Sofie Van Landeghem \r\n\r\n* Move KB into subdirectory.\r\n\r\n* Adjust imports after KB move to dedicated subdirectory.\r\n\r\n* Fix config imports.\r\n\r\n* Move Candidate + retrieval functions to separate module. Fix other, small issues.\r\n\r\n* Fix docstrings and error message w.r.t. class names. Fix typing for candidate retrieval functions.\r\n\r\n* Update spacy/kb/kb_in_memory.pyx\r\n\r\nCo-authored-by: Sofie Van Landeghem \r\n\r\n* Update spacy/ml/models/entity_linker.py\r\n\r\nCo-authored-by: Sofie Van Landeghem \r\n\r\n* Fix typing.\r\n\r\n* Change typing of mentions to be Span instead of Union[Span, str].\r\n\r\n* Update docs.\r\n\r\n* Update EntityLinker and _architecture docs.\r\n\r\n* Update website/docs/api/entitylinker.md\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\n\r\n* Adjust message for E1046.\r\n\r\n* Re-add section for Candidate in kb.md, add reference to dedicated page.\r\n\r\n* Update docs and docstrings.\r\n\r\n* Re-add section + reference for KnowledgeBase.get_alias_candidates() in docs.\r\n\r\n* Update spacy/kb/candidate.pyx\r\n\r\n* Update spacy/kb/kb_in_memory.pyx\r\n\r\n* Update spacy/pipeline/legacy/entity_linker.py\r\n\r\n* Remove canididate.md. Remove mistakenly added config snippet in entity_linker.py.\r\n\r\nCo-authored-by: Paul O'Leary McCann \r\nCo-authored-by: Sofie Van Landeghem ", "code": "def test_append_invalid_alias(nlp):\n \n mykb = InMemoryLookupKB(nlp.vocab, entity_vector_length=1)\n\n # adding entities\n mykb.add_entity(entity=\"Q1\", freq=27, entity_vector=[1])\n mykb.add_entity(entity=\"Q2\", freq=12, entity_vector=[2])\n mykb.add_entity(entity=\"Q3\", freq=5, entity_vector=[3])\n\n # adding aliases\n mykb.add_alias(alias=\"douglas\", entities=[\"Q2\", \"Q3\"], probabilities=[0.8, 0.1])\n mykb.add_alias(alias=\"adam\", entities=[\"Q2\"], probabilities=[0.9])\n\n # append an alias - should fail because the entities and probabilities vectors are not of equal length\n with pytest.raises(ValueError):\n mykb.append_alias(alias=\"douglas\", entity=\"Q1\", prior_prob=0.2)\n\n\n@pytest.mark.filterwarnings(\"ignore:\\\\[W036\")", "url": "https://github.com/explosion/spaCy.git", "language": "Python", "ast_errors": "@pytest.mark.filterwarnings(\"ignore:\\\\[W036\")", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 92, "n_words": 53, "vocab_size": 49, "complexity": 1, "nloc": 9, "token_counts": 148, "n_ast_nodes": 250, "n_identifiers": 21 }, { "id": 102696, "commit_id": "89f15f591cc3cc3e8ae40e95ffc802f7f2561ece", "repo": "chia-blockchain", "path": "chia/wallet/wallet_node.py", "file_name": "wallet_node.py", "fun_name": "subscribe_to_coin_updates", "commit_message": "Merge standalone wallet into main (#9793)\n\n* wallet changes from pac\r\n\r\n* cat changes\r\n\r\n* pool tests\r\n\r\n* pooling tests passing\r\n\r\n* offers\r\n\r\n* lint\r\n\r\n* mempool_mode\r\n\r\n* black\r\n\r\n* linting\r\n\r\n* workflow files\r\n\r\n* flake8\r\n\r\n* more cleanup\r\n\r\n* renamed\r\n\r\n* remove obsolete test, don't cast announcement\r\n\r\n* memos are not only bytes32\r\n\r\n* trade renames\r\n\r\n* fix rpcs, block_record\r\n\r\n* wallet rpc, recompile settlement clvm\r\n\r\n* key derivation\r\n\r\n* clvm tests\r\n\r\n* lgtm issues and wallet peers\r\n\r\n* stash\r\n\r\n* rename\r\n\r\n* mypy linting\r\n\r\n* flake8\r\n\r\n* bad initializer\r\n\r\n* flaky tests\r\n\r\n* Make CAT wallets only create on verified hints (#9651)\r\n\r\n* fix clvm tests\r\n\r\n* return to log lvl warn\r\n\r\n* check puzzle unhardened\r\n\r\n* public key, not bytes. api caching change\r\n\r\n* precommit changes\r\n\r\n* remove unused import\r\n\r\n* mypy ci file, tests\r\n\r\n* ensure balance before creating a tx\r\n\r\n* Remove CAT logic from full node test (#9741)\r\n\r\n* Add confirmations and sleeps for wallet (#9742)\r\n\r\n* use pool executor\r\n\r\n* rever merge mistakes/cleanup\r\n\r\n* Fix trade test flakiness (#9751)\r\n\r\n* remove precommit\r\n\r\n* older version of black\r\n\r\n* lint only in super linter\r\n\r\n* Make announcements in RPC be objects instead of bytes (#9752)\r\n\r\n* Make announcements in RPC be objects instead of bytes\r\n\r\n* Lint\r\n\r\n* misc hint'ish cleanup (#9753)\r\n\r\n* misc hint'ish cleanup\r\n\r\n* unremove some ci bits\r\n\r\n* Use main cached_bls.py\r\n\r\n* Fix bad merge in main_pac (#9774)\r\n\r\n* Fix bad merge at 71da0487b9cd5564453ec24b76f1ac773c272b75\r\n\r\n* Remove unused ignores\r\n\r\n* more unused ignores\r\n\r\n* Fix bad merge at 3b143e705057d6c14e2fb3e00078aceff0552d7e\r\n\r\n* One more byte32.from_hexstr\r\n\r\n* Remove obsolete test\r\n\r\n* remove commented out\r\n\r\n* remove duplicate payment object\r\n\r\n* remove long sync\r\n\r\n* remove unused test, noise\r\n\r\n* memos type\r\n\r\n* bytes32\r\n\r\n* make it clear it's a single state at a time\r\n\r\n* copy over asset ids from pacr\r\n\r\n* file endl linter\r\n\r\n* Update chia/server/ws_connection.py\r\n\r\nCo-authored-by: dustinface <35775977+xdustinface@users.noreply.github.com>\r\n\r\nCo-authored-by: Matt Hauff \r\nCo-authored-by: Kyle Altendorf \r\nCo-authored-by: dustinface <35775977+xdustinface@users.noreply.github.com>", "code": "async def subscribe_to_coin_updates(self, coin_names, peer, height=uint32(0)):\n \n msg = wallet_protocol.RegisterForCoinUpdates(coin_names, height)\n all_coins_state: Optional[RespondToCoinUpdates] = await peer.register_interest_in_coin(msg)\n # State for untrusted sync is processed only in wp sync | or short sync backwards\n if all_coins_state is not None and self.is_trusted(peer):\n await self.wallet_state_manager.new_coin_state(all_coins_state.coin_states, peer)\n", "url": "https://github.com/Chia-Network/chia-blockchain.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 88, "n_words": 41, "vocab_size": 36, "complexity": 3, "nloc": 9, "token_counts": 67, "n_ast_nodes": 106, "n_identifiers": 17 }, { "id": 278610, "commit_id": "3613c3defc39c236fb1592c4f7ba1a9cc887343a", "repo": "keras", "path": "keras/activations.py", "file_name": "activations.py", "fun_name": "softmax", "commit_message": "Remove pylint comments.\n\nPiperOrigin-RevId: 452353044", "code": "def softmax(x, axis=-1):\n \n if x.shape.rank > 1:\n if isinstance(axis, int):\n output = tf.nn.softmax(x, axis=axis)\n else:\n # nn.softmax does not support tuple axis.\n e = tf.exp(x - tf.reduce_max(x, axis=axis, keepdims=True))\n s = tf.reduce_sum(e, axis=axis, keepdims=True)\n output = e / s\n else:\n raise ValueError(\n \"Cannot apply softmax to a tensor that is 1D. \"\n f\"Received input: {x}\"\n )\n\n # Cache the logits to use for crossentropy loss.\n output._keras_logits = x\n return output\n\n\n@keras_export(\"keras.activations.elu\")\n@tf.__internal__.dispatch.add_dispatch_support", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.activations.elu\")\n@tf.__internal__.dispatch.add_dispatch_support", "n_ast_errors": 1, "ast_levels": 17, "n_whitespaces": 193, "n_words": 72, "vocab_size": 59, "complexity": 3, "nloc": 15, "token_counts": 104, "n_ast_nodes": 194, "n_identifiers": 22 }, { "id": 137498, "commit_id": "22af73253cd48fa134aee33c145b541c99acdc8b", "repo": "ray", "path": "dashboard/modules/job/tests/test_job_manager.py", "file_name": "test_job_manager.py", "fun_name": "test_stop_job_gracefully", "commit_message": "[Jobs] Use SIGTERM followed by SIGKILL to stop a job (#30851)\n\nCurrently, when user wants to stop a job, we directly send a `SIGKILL` signal. Instead, we want to send a `SIGTERM` signal first, then send a `SIGKILL` signal after a few seconds if the child process still has not terminated.", "code": "async def test_stop_job_gracefully(job_manager):\n \n entrypoint = ", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "entrypoint = \"\"\"python -c \\\"", "n_ast_errors": 1, "ast_levels": 6, "n_whitespaces": 12, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 23, "token_counts": 65, "n_ast_nodes": 31, "n_identifiers": 6 }, { "id": 260458, "commit_id": "a5d50cf3c7611b4343f446a97266ea77a4175afa", "repo": "scikit-learn", "path": "sklearn/cluster/tests/test_hierarchical.py", "file_name": "test_hierarchical.py", "fun_name": "test_agglomerative_clustering_memory_mapped", "commit_message": "MNT Deprecate `affinity` in `AgglomerativeClustering` (#23470)\n\nCo-authored-by: Thomas J. Fan \r\nCo-authored-by: Guillaume Lemaitre ", "code": "def test_agglomerative_clustering_memory_mapped():\n \n rng = np.random.RandomState(0)\n Xmm = create_memmap_backed_data(rng.randn(50, 100))\n AgglomerativeClustering(metric=\"euclidean\", linkage=\"single\").fit(Xmm)\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 23, "n_words": 11, "vocab_size": 10, "complexity": 1, "nloc": 4, "token_counts": 43, "n_ast_nodes": 75, "n_identifiers": 12 }, { "id": 198198, "commit_id": "a69c49bec6caf2cb460dc4eedf0fec184db92f0e", "repo": "sympy", "path": "sympy/tensor/array/expressions/array_expressions.py", "file_name": "array_expressions.py", "fun_name": "sort_args_by_name", "commit_message": "Rename files for array expression conversions in order to avoid naming conflicts in TAB-completion of the corresponding functions", "code": "def sort_args_by_name(self):\n \n expr = self.expr\n if not isinstance(expr, ArrayTensorProduct):\n return self\n args = expr.args\n sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))\n pos_sorted, args_sorted = zip(*sorted_data)\n reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}\n contraction_tuples = self._get_contraction_tuples()\n contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]\n c_tp = _array_tensor_product(*args_sorted)\n new_contr_indices = self._contraction_tuples_to_contraction_indices(\n c_tp,\n contraction_tuples\n )\n return _array_contraction(c_tp, *new_contr_indices)\n", "url": "https://github.com/sympy/sympy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 193, "n_words": 61, "vocab_size": 46, "complexity": 5, "nloc": 16, "token_counts": 135, "n_ast_nodes": 211, "n_identifiers": 28 }, { "id": 288141, "commit_id": "7042d6d35be54865b1252c0b28a50cce1a92eabc", "repo": "core", "path": "homeassistant/components/esphome/bluetooth/client.py", "file_name": "client.py", "fun_name": "is_connected", "commit_message": "Add ESPHome BleakClient (#78911)\n\nCo-authored-by: Paulus Schoutsen ", "code": "def is_connected(self) -> bool:\n \n return self._is_connected\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 12, "n_ast_nodes": 22, "n_identifiers": 4 }, { "id": 276209, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/saving/saved_model_experimental.py", "file_name": "saved_model_experimental.py", "fun_name": "_get_assets_dir", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _get_assets_dir(export_dir):\n \n return tf.io.gfile.join(\n tf.compat.as_text(export_dir),\n tf.compat.as_text(tf.saved_model.ASSETS_DIRECTORY),\n )\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 30, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 5, "token_counts": 38, "n_ast_nodes": 61, "n_identifiers": 10 }, { "id": 156048, "commit_id": "cccb9d8d8e33a891396b1275c2448c352ef40c27", "repo": "dask", "path": "dask/array/core.py", "file_name": "core.py", "fun_name": "new_da_object", "commit_message": "absolufy-imports - No relative - PEP8 (#8796)\n\nConversation in https://github.com/dask/distributed/issues/5889", "code": "def new_da_object(dsk, name, chunks, meta=None, dtype=None):\n \n if is_dataframe_like(meta) or is_series_like(meta) or is_index_like(meta):\n from dask.dataframe.core import new_dd_object\n\n assert all(len(c) == 1 for c in chunks[1:])\n divisions = [None] * (len(chunks[0]) + 1)\n return new_dd_object(dsk, name, meta, divisions)\n else:\n return Array(dsk, name=name, chunks=chunks, meta=meta, dtype=dtype)\n\n", "url": "https://github.com/dask/dask.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 87, "n_words": 43, "vocab_size": 40, "complexity": 5, "nloc": 8, "token_counts": 111, "n_ast_nodes": 163, "n_identifiers": 18 }, { "id": 191686, "commit_id": "8d0869c6d3ed63b2b15d4f75ea664e089dcc569d", "repo": "langchain", "path": "tests/unit_tests/chains/test_base.py", "file_name": "test_base.py", "fun_name": "test_run_multiple_args_error", "commit_message": "change run to use args and kwargs (#367)\n\nBefore, `run` was not able to be called with multiple arguments. This\r\nexpands the functionality.", "code": "def test_run_multiple_args_error() -> None:\n \n chain = FakeChain()\n with pytest.raises(ValueError):\n chain.run(\"bar\", \"foo\")\n\n", "url": "https://github.com/hwchase17/langchain.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 27, "n_words": 11, "vocab_size": 11, "complexity": 1, "nloc": 5, "token_counts": 28, "n_ast_nodes": 55, "n_identifiers": 7 }, { "id": 107167, "commit_id": "ec4dfbc3c83866f487ff0bc9c87b0d43a1c02b22", "repo": "matplotlib", "path": "lib/matplotlib/tests/test_constrainedlayout.py", "file_name": "test_constrainedlayout.py", "fun_name": "test_constrained_layout4", "commit_message": "ENH: implement and use base layout_engine for more flexible layout.", "code": "def test_constrained_layout4():\n \n\n fig, axs = plt.subplots(2, 2, layout=\"constrained\")\n for ax in axs.flat:\n pcm = example_pcolor(ax, fontsize=24)\n fig.colorbar(pcm, ax=axs, pad=0.01, shrink=0.6)\n\n\n@image_comparison(['constrained_layout5.png'], tol=0.002)", "url": "https://github.com/matplotlib/matplotlib.git", "language": "Python", "ast_errors": "@image_comparison(['constrained_layout5.png'], tol=0.002)", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 40, "n_words": 22, "vocab_size": 21, "complexity": 2, "nloc": 5, "token_counts": 60, "n_ast_nodes": 106, "n_identifiers": 16 }, { "id": 20474, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/pygments/scanner.py", "file_name": "scanner.py", "fun_name": "check", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def check(self, pattern):\n \n if self.eos:\n raise EndOfText()\n if pattern not in self._re_cache:\n self._re_cache[pattern] = re.compile(pattern, self.flags)\n return self._re_cache[pattern].match(self.data, self.pos)\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 69, "n_words": 19, "vocab_size": 18, "complexity": 3, "nloc": 6, "token_counts": 60, "n_ast_nodes": 93, "n_identifiers": 12 }, { "id": 5819, "commit_id": "2a157d452611d37cf50ccb7d56ff1a06e9790ecb", "repo": "InstaPy", "path": "instapy/util.py", "file_name": "util.py", "fun_name": "extract_text_from_element", "commit_message": "PR - Fix `extract_text_from_element()`and `find_element*()` to `find_element()` (#6438)\n\n* Updated getUserData() and find_element*\r\nSigned-off-by: elulcao \r\n\r\nThanks @breuerfelix for reviewing, 🚀 \r\nPeople in this thread please let me know if something is not OK, IG changed a lot these days. 🤗 @her", "code": "def extract_text_from_element(elem):\n \n\n # if element is valid and contains text withou spaces\n if elem and hasattr(elem, \"text\") and elem.text and not re.search(\"\\s\", elem.text):\n return elem.text\n\n # if the element is not valid, return None\n return None\n\n", "url": "https://github.com/InstaPy/InstaPy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 58, "n_words": 36, "vocab_size": 23, "complexity": 5, "nloc": 4, "token_counts": 38, "n_ast_nodes": 67, "n_identifiers": 6 }, { "id": 98080, "commit_id": "5b01e6a61cbbb62bde6e1cacf155e00c5e5bc432", "repo": "sentry", "path": "src/sentry/incidents/logic.py", "file_name": "logic.py", "fun_name": "delete_alert_rule", "commit_message": "feat(workflow): Add audit logs on add/edit/remove metric alerts (#33296)", "code": "def delete_alert_rule(alert_rule, user=None):\n \n if alert_rule.status == AlertRuleStatus.SNAPSHOT.value:\n raise AlreadyDeletedError()\n\n with transaction.atomic():\n if user:\n create_audit_entry_from_user(\n user,\n organization_id=alert_rule.organization_id,\n target_object=alert_rule.id,\n data=alert_rule.get_audit_log_data(),\n event=AuditLogEntryEvent.ALERT_RULE_REMOVE,\n )\n\n incidents = Incident.objects.filter(alert_rule=alert_rule)\n bulk_delete_snuba_subscriptions(list(alert_rule.snuba_query.subscriptions.all()))\n if incidents.exists():\n alert_rule.update(status=AlertRuleStatus.SNAPSHOT.value)\n AlertRuleActivity.objects.create(\n alert_rule=alert_rule, user=user, type=AlertRuleActivityType.DELETED.value\n )\n else:\n alert_rule.delete()\n\n if alert_rule.id:\n # Change the incident status asynchronously, which could take awhile with many incidents due to snapshot creations.\n tasks.auto_resolve_snapshot_incidents.apply_async(kwargs={\"alert_rule_id\": alert_rule.id})\n\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 279, "n_words": 55, "vocab_size": 49, "complexity": 5, "nloc": 23, "token_counts": 162, "n_ast_nodes": 261, "n_identifiers": 40 }, { "id": 177063, "commit_id": "77d7ddac9a7c69ff086dd825e55454f300f4242b", "repo": "networkx", "path": "networkx/algorithms/coloring/greedy_coloring.py", "file_name": "greedy_coloring.py", "fun_name": "strategy_saturation_largest_first", "commit_message": "strategy_saturation_largest_first now accepts partial colorings (#5888)\n\nThe coloring strategy function `strategy_saturation_largest_first` allows the user\r\nto pass in a dict with a partial node coloring. This was always allowed, but previously\r\nthe partial coloring dict was ignored. The partial coloring is also verified within the function.", "code": "def strategy_saturation_largest_first(G, colors):\n \n distinct_colors = {v: set() for v in G}\n\n # Add the node color assignments given in colors to the\n # distinct colors set for each neighbor of that node\n for vertex, color in colors.items():\n for neighbor in G[vertex]:\n distinct_colors[neighbor].add(color)\n\n # Check that the color assignments in colors are valid\n # i.e. no neighboring nodes have the same color\n if len(colors) >= 2:\n for vertex, color in colors.items():\n if color in distinct_colors[vertex]:\n raise nx.NetworkXError(\n \"Neighboring vertices must have different colors\"\n )\n\n # If 0 nodes have been colored, simply choose the node of highest degree.\n if not colors:\n node = max(G, key=G.degree)\n yield node\n # Add the color 0 to the distinct colors set for each\n # neighbor of that node.\n for v in G[node]:\n distinct_colors[v].add(0)\n\n for i in range(len(G) - len(colors)):\n # Compute the maximum saturation and the set of nodes that\n # achieve that saturation.\n saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}\n # Yield the node with the highest saturation, and break ties by\n # degree.\n node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))\n yield node\n\n # Update the distinct color sets for the neighbors.\n color = colors[node]\n for v in G[node]:\n distinct_colors[v].add(color)\n\n\n#: Dictionary mapping name of a strategy as a string to the strategy function.\nSTRATEGIES = {\n \"largest_first\": strategy_largest_first,\n \"random_sequential\": strategy_random_sequential,\n \"smallest_last\": strategy_smallest_last,\n \"independent_set\": strategy_independent_set,\n \"connected_sequential_bfs\": strategy_connected_sequential_bfs,\n \"connected_sequential_dfs\": strategy_connected_sequential_dfs,\n \"connected_sequential\": strategy_connected_sequential,\n \"saturation_largest_first\": strategy_saturation_largest_first,\n \"DSATUR\": strategy_saturation_largest_first,\n}\n\n", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 508, "n_words": 239, "vocab_size": 128, "complexity": 13, "nloc": 23, "token_counts": 209, "n_ast_nodes": 407, "n_identifiers": 30 }, { "id": 60244, "commit_id": "cc4d0564756ca067516f71718a3d135996525909", "repo": "transferlearning", "path": "code/deep/BJMMD/caffe/python/caffe/draw.py", "file_name": "draw.py", "fun_name": "choose_color_by_layertype", "commit_message": "Balanced joint maximum mean discrepancy for deep transfer learning", "code": "def choose_color_by_layertype(layertype):\n \n color = '#6495ED' # Default\n if layertype == 'Convolution' or layertype == 'Deconvolution':\n color = '#FF5050'\n elif layertype == 'Pooling':\n color = '#FF9900'\n elif layertype == 'InnerProduct':\n color = '#CC33FF'\n return color\n\n", "url": "https://github.com/jindongwang/transferlearning.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 74, "n_words": 34, "vocab_size": 20, "complexity": 5, "nloc": 9, "token_counts": 39, "n_ast_nodes": 83, "n_identifiers": 3 }, { "id": 259211, "commit_id": "7f0006c8aad1a09621ad19c3db19c3ff0555a183", "repo": "scikit-learn", "path": "sklearn/preprocessing/_encoders.py", "file_name": "_encoders.py", "fun_name": "_compute_transformed_categories", "commit_message": "ENH Adds infrequent categories to OneHotEncoder (#16018)\n\n* ENH Completely adds infrequent categories\r\n\r\n* STY Linting\r\n\r\n* STY Linting\r\n\r\n* DOC Improves wording\r\n\r\n* DOC Lint\r\n\r\n* BUG Fixes\r\n\r\n* CLN Address comments\r\n\r\n* CLN Address comments\r\n\r\n* DOC Uses math to description float min_frequency\r\n\r\n* DOC Adds comment regarding drop\r\n\r\n* BUG Fixes method name\r\n\r\n* DOC Clearer docstring\r\n\r\n* TST Adds more tests\r\n\r\n* FIX Fixes mege\r\n\r\n* CLN More pythonic\r\n\r\n* CLN Address comments\r\n\r\n* STY Flake8\r\n\r\n* CLN Address comments\r\n\r\n* DOC Fix\r\n\r\n* MRG\r\n\r\n* WIP\r\n\r\n* ENH Address comments\r\n\r\n* STY Fix\r\n\r\n* ENH Use functiion call instead of property\r\n\r\n* ENH Adds counts feature\r\n\r\n* CLN Rename variables\r\n\r\n* DOC More details\r\n\r\n* CLN Remove unneeded line\r\n\r\n* CLN Less lines is less complicated\r\n\r\n* CLN Less diffs\r\n\r\n* CLN Improves readiabilty\r\n\r\n* BUG Fix\r\n\r\n* CLN Address comments\r\n\r\n* TST Fix\r\n\r\n* CLN Address comments\r\n\r\n* CLN Address comments\r\n\r\n* CLN Move docstring to userguide\r\n\r\n* DOC Better wrapping\r\n\r\n* TST Adds test to handle_unknown='error'\r\n\r\n* ENH Spelling error in docstring\r\n\r\n* BUG Fixes counter with nan values\r\n\r\n* BUG Removes unneeded test\r\n\r\n* BUG Fixes issue\r\n\r\n* ENH Sync with main\r\n\r\n* DOC Correct settings\r\n\r\n* DOC Adds docstring\r\n\r\n* DOC Immprove user guide\r\n\r\n* DOC Move to 1.0\r\n\r\n* DOC Update docs\r\n\r\n* TST Remove test\r\n\r\n* DOC Update docstring\r\n\r\n* STY Linting\r\n\r\n* DOC Address comments\r\n\r\n* ENH Neater code\r\n\r\n* DOC Update explaination for auto\r\n\r\n* Update sklearn/preprocessing/_encoders.py\r\n\r\nCo-authored-by: Roman Yurchak \r\n\r\n* TST Uses docstring instead of comments\r\n\r\n* TST Remove call to fit\r\n\r\n* TST Spelling error\r\n\r\n* ENH Adds support for drop + infrequent categories\r\n\r\n* ENH Adds infrequent_if_exist option\r\n\r\n* DOC Address comments for user guide\r\n\r\n* DOC Address comments for whats_new\r\n\r\n* DOC Update docstring based on comments\r\n\r\n* CLN Update test with suggestions\r\n\r\n* ENH Adds computed property infrequent_categories_\r\n\r\n* DOC Adds where the infrequent column is located\r\n\r\n* TST Adds more test for infrequent_categories_\r\n\r\n* DOC Adds docstring for _compute_drop_idx\r\n\r\n* CLN Moves _convert_to_infrequent_idx into its own method\r\n\r\n* TST Increases test coverage\r\n\r\n* TST Adds failing test\r\n\r\n* CLN Careful consideration of dropped and inverse_transform\r\n\r\n* STY Linting\r\n\r\n* DOC Adds docstrinb about dropping infrequent\r\n\r\n* DOC Uses only\r\n\r\n* DOC Numpydoc\r\n\r\n* TST Includes test for get_feature_names_out\r\n\r\n* DOC Move whats new\r\n\r\n* DOC Address docstring comments\r\n\r\n* DOC Docstring changes\r\n\r\n* TST Better comments\r\n\r\n* TST Adds check for handle_unknown='ignore' for infrequent\r\n\r\n* CLN Make _infrequent_indices private\r\n\r\n* CLN Change min_frequency default to None\r\n\r\n* DOC Adds comments\r\n\r\n* ENH adds support for max_categories=1\r\n\r\n* ENH Describe lexicon ordering for ties\r\n\r\n* DOC Better docstring\r\n\r\n* STY Fix\r\n\r\n* CLN Error when explicity dropping an infrequent category\r\n\r\n* STY Grammar\r\n\r\nCo-authored-by: Joel Nothman \r\nCo-authored-by: Roman Yurchak \r\nCo-authored-by: Guillaume Lemaitre ", "code": "def _compute_transformed_categories(self, i, remove_dropped=True):\n \n cats = self.categories_[i]\n\n if self._infrequent_enabled:\n infreq_map = self._default_to_infrequent_mappings[i]\n if infreq_map is not None:\n frequent_mask = infreq_map < infreq_map.max()\n infrequent_cat = \"infrequent_sklearn\"\n # infrequent category is always at the end\n cats = np.concatenate(\n (cats[frequent_mask], np.array([infrequent_cat], dtype=object))\n )\n\n if remove_dropped:\n cats = self._remove_dropped_categories(cats, i)\n return cats\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 210, "n_words": 48, "vocab_size": 35, "complexity": 4, "nloc": 13, "token_counts": 92, "n_ast_nodes": 145, "n_identifiers": 18 }, { "id": 32877, "commit_id": "4a51075a96d2049f368b5f3dd6c0e9f08f599b62", "repo": "transformers", "path": "src/transformers/utils/bitsandbytes.py", "file_name": "bitsandbytes.py", "fun_name": "get_key_to_not_convert", "commit_message": "`bitsandbytes` - `Linear8bitLt` integration into `transformers` models (#17901)\n\n* first commit\r\n\r\n* correct replace function\r\n\r\n* add final changes\r\n\r\n- works like charm!\r\n- cannot implement tests yet\r\n- tested\r\n\r\n* clean up a bit\r\n\r\n* add bitsandbytes dependencies\r\n\r\n* working version\r\n\r\n- added import function\r\n- added bitsandbytes utils file\r\n\r\n* small fix\r\n\r\n* small fix\r\n\r\n- fix import issue\r\n\r\n* fix import issues\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* refactor a bit\r\n\r\n- move bitsandbytes utils to utils\r\n- change comments on functions\r\n\r\n* reformat docstring\r\n\r\n- reformat docstring on init_empty_weights_8bit\r\n\r\n* Update src/transformers/__init__.py\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* revert bad formatting\r\n\r\n* change to bitsandbytes\r\n\r\n* refactor a bit\r\n\r\n- remove init8bit since it is useless\r\n\r\n* more refactoring\r\n\r\n- fixed init empty weights issue\r\n- added threshold param\r\n\r\n* small hack to make it work\r\n\r\n* Update src/transformers/modeling_utils.py\r\n\r\n* Update src/transformers/modeling_utils.py\r\n\r\n* revmoe the small hack\r\n\r\n* modify utils file\r\n\r\n* make style + refactor a bit\r\n\r\n* create correctly device map\r\n\r\n* add correct dtype for device map creation\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* apply suggestions\r\n\r\n- remove with torch.grad\r\n- do not rely on Python bool magic!\r\n\r\n* add docstring\r\n\r\n - add docstring for new kwargs\r\n\r\n* add docstring\r\n\r\n- comment `replace_8bit_linear` function\r\n- fix weird formatting\r\n\r\n* - added more documentation\r\n- added new utility function for memory footprint tracking\r\n- colab demo to add\r\n\r\n* few modifs\r\n\r\n- typo doc\r\n- force cast into float16 when load_in_8bit is enabled\r\n\r\n* added colab link\r\n\r\n* add test architecture + docstring a bit\r\n\r\n* refactor a bit testing class\r\n\r\n* make style + refactor a bit\r\n\r\n* enhance checks\r\n\r\n- add more checks\r\n- start writing saving test\r\n\r\n* clean up a bit\r\n\r\n* male style\r\n\r\n* add more details on doc\r\n\r\n* add more tests\r\n\r\n- still needs to fix 2 tests\r\n\r\n* replace by \"or\"\r\n\r\n- could not fix it from GitHub GUI\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* refactor a bit testing code + add readme\r\n\r\n* make style\r\n\r\n* fix import issue\r\n\r\n* Update src/transformers/modeling_utils.py\r\n\r\nCo-authored-by: Michael Benayoun \r\n\r\n* add few comments\r\n\r\n* add more doctring + make style\r\n\r\n* more docstring\r\n\r\n* raise error when loaded in 8bit\r\n\r\n* make style\r\n\r\n* add warning if loaded on CPU\r\n\r\n* add small sanity check\r\n\r\n* fix small comment\r\n\r\n* add bitsandbytes on dockerfile\r\n\r\n* Improve documentation\r\n\r\n- improve documentation from comments\r\n\r\n* add few comments\r\n\r\n* slow tests pass on the VM but not on the CI VM\r\n\r\n* Fix merge conflict\r\n\r\n* make style\r\n\r\n* another test should pass on a multi gpu setup\r\n\r\n* fix bad import in testing file\r\n\r\n* Fix slow tests\r\n\r\n- remove dummy batches\r\n- no more CUDA illegal memory errors\r\n\r\n* odify dockerfile\r\n\r\n* Update docs/source/en/main_classes/model.mdx\r\n\r\n* Update Dockerfile\r\n\r\n* Update model.mdx\r\n\r\n* Update Dockerfile\r\n\r\n* Apply suggestions from code review\r\n\r\n* few modifications\r\n\r\n- lm head can stay on disk/cpu\r\n- change model name so that test pass\r\n\r\n* change test value\r\n\r\n- change test value to the correct output\r\n- torch bmm changed to baddmm in bloom modeling when merging\r\n\r\n* modify installation guidelines\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* replace `n`by `name`\r\n\r\n* merge `load_in_8bit` and `low_cpu_mem_usage`\r\n\r\n* first try - keep the lm head in full precision\r\n\r\n* better check\r\n\r\n- check the attribute `base_model_prefix` instead of computing the number of parameters\r\n\r\n* added more tests\r\n\r\n* Update src/transformers/utils/bitsandbytes.py\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* Merge branch 'integration-8bit' of https://github.com/younesbelkada/transformers into integration-8bit\r\n\r\n* improve documentation\r\n\r\n- fix typos for installation\r\n- change title in the documentation\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\nCo-authored-by: Michael Benayoun ", "code": "def get_key_to_not_convert(model):\n r\n # Ignore this for base models (BertModel, GPT2Model, etc.)\n if not hasattr(model, model.base_model_prefix):\n return \"\"\n\n # otherwise they have an attached head\n list_modules = list(model.named_parameters())\n last_name = list_modules[-1][0]\n return last_name.split(\".\")[0]\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 60, "n_words": 33, "vocab_size": 30, "complexity": 2, "nloc": 14, "token_counts": 50, "n_ast_nodes": 86, "n_identifiers": 9 }, { "id": 156649, "commit_id": "dadfd9b681997b20026e6a51afef3fb9ebb1513a", "repo": "dask", "path": "dask/dataframe/accessor.py", "file_name": "accessor.py", "fun_name": "split", "commit_message": "Include known inconsistency in DataFrame `str.split` accessor docstring (#9177)", "code": "def split(self, pat=None, n=-1, expand=False):\n \n return self._split(\"split\", pat=pat, n=n, expand=expand)\n", "url": "https://github.com/dask/dask.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 24, "n_words": 10, "vocab_size": 10, "complexity": 1, "nloc": 2, "token_counts": 38, "n_ast_nodes": 58, "n_identifiers": 6 }, { "id": 19833, "commit_id": "949ee95d6748e8777bed589f0d990aa4792b28f8", "repo": "pipenv", "path": "tests/integration/test_install_basic.py", "file_name": "test_install_basic.py", "fun_name": "test_install_venv_project_directory", "commit_message": "More granular control over PIPENV_VENV_IN_PROJECT variable. (#5026)\n\n* Allow PIPENV_VENV_IN_PROJECT to be read in as None, and ensure if it is set to False that it does not use .venv directory.\r\n\r\n* refactor based on PR feedback and add news fragment.\r\n\r\n* Review unit test coverage and add new tests. Remove unneccesary bits from other tests.", "code": "def test_install_venv_project_directory(PipenvInstance):\n \n with PipenvInstance(chdir=True) as p:\n with temp_environ(), TemporaryDirectory(\n prefix=\"pipenv-\", suffix=\"temp_workon_home\"\n ) as workon_home:\n os.environ[\"WORKON_HOME\"] = workon_home\n\n c = p.pipenv(\"install six\")\n assert c.returncode == 0\n\n venv_loc = None\n for line in c.stderr.splitlines():\n if line.startswith(\"Virtualenv location:\"):\n venv_loc = Path(line.split(\":\", 1)[-1].strip())\n assert venv_loc is not None\n assert venv_loc.joinpath(\".project\").exists()\n\n\n@pytest.mark.cli\n@pytest.mark.deploy\n@pytest.mark.system", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "@pytest.mark.cli\n@pytest.mark.deploy\n@pytest.mark.system", "n_ast_errors": 1, "ast_levels": 22, "n_whitespaces": 188, "n_words": 49, "vocab_size": 39, "complexity": 4, "nloc": 16, "token_counts": 129, "n_ast_nodes": 232, "n_identifiers": 29 }, { "id": 83182, "commit_id": "90e202cd38d00945c81da4730d39e3f5c5b1e8b1", "repo": "zulip", "path": "zerver/tests/test_subs.py", "file_name": "test_subs.py", "fun_name": "test_json_get_subscribers_for_guest_user", "commit_message": "docs: Consistently hyphenate “web-public”.\n\nIn English, compound adjectives should essentially always be\nhyphenated. This makes them easier to parse, especially for users who\nmight not recognize that the words “web public” go together as a\nphrase.\n\nSigned-off-by: Anders Kaseorg ", "code": "def test_json_get_subscribers_for_guest_user(self) -> None:\n \n guest_user = self.example_user(\"polonius\")\n never_subscribed = gather_subscriptions_helper(guest_user, True).never_subscribed\n\n # A guest user can only see never subscribed streams that are web-public.\n # For Polonius, the only web-public stream that he is not subscribed at\n # this point is Rome.\n self.assert_length(never_subscribed, 1)\n\n web_public_stream_id = never_subscribed[0][\"stream_id\"]\n result = self.client_get(f\"/json/streams/{web_public_stream_id}/members\")\n self.assert_json_success(result)\n result_dict = result.json()\n self.assertIn(\"subscribers\", result_dict)\n self.assertIsInstance(result_dict[\"subscribers\"], list)\n self.assertGreater(len(result_dict[\"subscribers\"]), 0)\n", "url": "https://github.com/zulip/zulip.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 158, "n_words": 60, "vocab_size": 50, "complexity": 1, "nloc": 15, "token_counts": 98, "n_ast_nodes": 172, "n_identifiers": 18 }, { "id": 245574, "commit_id": "d0695e68654ca242be54e655491aef8c959ac345", "repo": "mmdetection", "path": "tools/model_converters/detectron2pytorch.py", "file_name": "detectron2pytorch.py", "fun_name": "convert", "commit_message": "[Fix] replace mmcv's function and modules imported with mmengine's (#8594)\n\n* use mmengine's load_state_dict and load_checkpoint\r\n\r\n* from mmengine import dump\r\n\r\n* from mmengine import FileClient dump list_from_file\r\n\r\n* remove redundant registry\r\n\r\n* update\r\n\r\n* update\r\n\r\n* update\r\n\r\n* replace _load_checkpoint with CheckpointLoad.load_checkpoint\r\n\r\n* changes according to mmcv #2216\r\n\r\n* changes due to mmengine #447\r\n\r\n* changes due mmengine #447 and mmcv #2217\r\n\r\n* changes due mmengine #447 and mmcv #2217\r\n\r\n* update\r\n\r\n* update\r\n\r\n* update", "code": "def convert(src, dst, depth):\n \n # load arch_settings\n if depth not in arch_settings:\n raise ValueError('Only support ResNet-50 and ResNet-101 currently')\n block_nums = arch_settings[depth]\n # load caffe model\n caffe_model = load(src, encoding='latin1')\n blobs = caffe_model['blobs'] if 'blobs' in caffe_model else caffe_model\n # convert to pytorch style\n state_dict = OrderedDict()\n converted_names = set()\n convert_conv_fc(blobs, state_dict, 'conv1', 'conv1', converted_names)\n convert_bn(blobs, state_dict, 'res_conv1_bn', 'bn1', converted_names)\n for i in range(1, len(block_nums) + 1):\n for j in range(block_nums[i - 1]):\n if j == 0:\n convert_conv_fc(blobs, state_dict, f'res{i + 1}_{j}_branch1',\n f'layer{i}.{j}.downsample.0', converted_names)\n convert_bn(blobs, state_dict, f'res{i + 1}_{j}_branch1_bn',\n f'layer{i}.{j}.downsample.1', converted_names)\n for k, letter in enumerate(['a', 'b', 'c']):\n convert_conv_fc(blobs, state_dict,\n f'res{i + 1}_{j}_branch2{letter}',\n f'layer{i}.{j}.conv{k+1}', converted_names)\n convert_bn(blobs, state_dict,\n f'res{i + 1}_{j}_branch2{letter}_bn',\n f'layer{i}.{j}.bn{k + 1}', converted_names)\n # check if all layers are converted\n for key in blobs:\n if key not in converted_names:\n print(f'Not Convert: {key}')\n # save checkpoint\n checkpoint = dict()\n checkpoint['state_dict'] = state_dict\n torch.save(checkpoint, dst)\n\n", "url": "https://github.com/open-mmlab/mmdetection.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 486, "n_words": 144, "vocab_size": 90, "complexity": 9, "nloc": 30, "token_counts": 223, "n_ast_nodes": 456, "n_identifiers": 30 }, { "id": 249486, "commit_id": "ebfeac7c5ded851a2639911ec6adf9d0fcdb029a", "repo": "synapse", "path": "synapse/util/rust.py", "file_name": "rust.py", "fun_name": "check_rust_lib_up_to_date", "commit_message": "Check if Rust lib needs rebuilding. (#13759)\n\nThis protects against the common mistake of failing to remember to rebuild Rust code after making changes.", "code": "def check_rust_lib_up_to_date() -> None:\n \n\n if not _dist_is_editable():\n return\n\n synapse_dir = os.path.dirname(synapse.__file__)\n synapse_root = os.path.abspath(os.path.join(synapse_dir, \"..\"))\n\n # Double check we've not gone into site-packages...\n if os.path.basename(synapse_root) == \"site-packages\":\n return\n\n # ... and it looks like the root of a python project.\n if not os.path.exists(\"pyproject.toml\"):\n return\n\n # Get the hash of all Rust source files\n hash = _hash_rust_files_in_directory(os.path.join(synapse_root, \"rust\", \"src\"))\n\n if hash != get_rust_file_digest():\n raise Exception(\"Rust module outdated. Please rebuild using `poetry install`\")\n\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 132, "n_words": 71, "vocab_size": 56, "complexity": 5, "nloc": 15, "token_counts": 99, "n_ast_nodes": 177, "n_identifiers": 17 }, { "id": 176497, "commit_id": "f6755ffa00211b523c6c0bec5398bc6c3c43c8b1", "repo": "networkx", "path": "networkx/readwrite/gml.py", "file_name": "gml.py", "fun_name": "generate_gml", "commit_message": "Update black (#5438)\n\n* CI: sync up black dev requirements version with precommit\r\n\r\n* Run black\r\n\r\nCo-authored-by: Jarrod Millman ", "code": "def generate_gml(G, stringizer=None):\n r\n valid_keys = re.compile(\"^[A-Za-z][0-9A-Za-z_]*$\")\n", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 12, "n_words": 7, "vocab_size": 7, "complexity": 10, "nloc": 118, "token_counts": 285, "n_ast_nodes": 33, "n_identifiers": 6 }, { "id": 270714, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/engine/base_layer.py", "file_name": "base_layer.py", "fun_name": "_defun_call", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _defun_call(self, inputs):\n \n return self._make_op(inputs)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 19, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 2, "token_counts": 15, "n_ast_nodes": 26, "n_identifiers": 4 }, { "id": 291724, "commit_id": "c576a68d336bc91fd82c299d9b3e5dfdc1c14960", "repo": "core", "path": "tests/components/skybell/conftest.py", "file_name": "conftest.py", "fun_name": "skybell_mock", "commit_message": "Upgrade pytest-aiohttp (#82475)\n\n* Upgrade pytest-aiohttp\r\n\r\n* Make sure executors, tasks and timers are closed\r\n\r\nSome test will trigger warnings on garbage collect, these warnings\r\nspills over into next test.\r\n\r\nSome test trigger tasks that raise errors on shutdown, these spill\r\nover into next test.\r\n\r\nThis is to mimic older pytest-aiohttp and it's behaviour on test\r\ncleanup.\r\n\r\nDiscussions on similar changes for pytest-aiohttp are here:\r\nhttps://github.com/pytest-dev/pytest-asyncio/pull/309\r\n\r\n* Replace loop with event_loop\r\n\r\n* Make sure time is frozen for tests\r\n\r\n* Make sure the ConditionType is not async\r\n\r\n /home-assistant/homeassistant/helpers/template.py:2082: RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited\r\n def wrapper(*args, **kwargs):\r\n Enable tracemalloc to get traceback where the object was allocated.\r\n See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.\r\n\r\n* Increase litejet press tests with a factor 10\r\n\r\nThe times are simulated anyway, and we can't stop the normal\r\nevent from occuring.\r\n\r\n* Use async handlers for aiohttp\r\n\r\ntests/components/motioneye/test_camera.py::test_get_still_image_from_camera\r\ntests/components/motioneye/test_camera.py::test_get_still_image_from_camera\r\ntests/components/motioneye/test_camera.py::test_get_stream_from_camera\r\ntests/components/motioneye/test_camera.py::test_get_stream_from_camera\r\ntests/components/motioneye/test_camera.py::test_camera_option_stream_url_template\r\ntests/components/motioneye/test_camera.py::test_camera_option_stream_url_template\r\n /Users/joakim/src/hass/home-assistant/venv/lib/python3.9/site-packages/aiohttp/web_urldispatcher.py:189: DeprecationWarning: Bare functions are deprecated, use async ones\r\n warnings.warn(\r\n\r\n* Switch to freezegun in modbus tests\r\n\r\nThe tests allowed clock to tick in between steps\r\n\r\n* Make sure skybell object are fully mocked\r\n\r\nOld tests would trigger attempts to post to could services:\r\n\r\n```\r\nDEBUG:aioskybell:HTTP post https://cloud.myskybell.com/api/v3/login/ Request with headers: {'content-type': 'application/json', 'accept': '*/*', 'x-skybell-app-id': 'd2b542c7-a7e4-4e1e-b77d-2b76911c7c46', 'x-skybell-client-id': '1f36a3c0-6dee-4997-a6db-4e1c67338e57'}\r\n```\r\n\r\n* Fix sorting that broke after rebase", "code": "def skybell_mock():\n \n mocked_skybell_device = AsyncMock(spec=SkybellDevice)\n\n mocked_skybell = AsyncMock(spec=Skybell)\n mocked_skybell.async_get_devices.return_value = [mocked_skybell_device]\n mocked_skybell.async_send_request.return_value = {\"id\": USER_ID}\n mocked_skybell.user_id = USER_ID\n\n with patch(\n \"homeassistant.components.skybell.config_flow.Skybell\",\n return_value=mocked_skybell,\n ), patch(\"homeassistant.components.skybell.Skybell\", return_value=mocked_skybell):\n yield mocked_skybell\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 72, "n_words": 27, "vocab_size": 22, "complexity": 1, "nloc": 11, "token_counts": 68, "n_ast_nodes": 118, "n_identifiers": 13 }, { "id": 293022, "commit_id": "c5dd5e18c0443b332dddfbbf4a8ff03374c5c070", "repo": "core", "path": "homeassistant/components/group/binary_sensor.py", "file_name": "binary_sensor.py", "fun_name": "async_update_group_state", "commit_message": "Improve binary sensor group when member is unknown or unavailable (#67468)", "code": "def async_update_group_state(self) -> None:\n \n all_states = [self.hass.states.get(x) for x in self._entity_ids]\n\n # filtered_states are members currently in the state machine\n filtered_states: list[str] = [x.state for x in all_states if x is not None]\n\n # Set group as unavailable if all members are unavailable\n self._attr_available = any(\n state != STATE_UNAVAILABLE for state in filtered_states\n )\n\n valid_state = self.mode(\n state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in filtered_states\n )\n if not valid_state:\n # Set as unknown if any / all member is not unknown or unavailable\n self._attr_is_on = None\n else:\n # Set as ON if any / all member is ON\n states = list(map(lambda x: x == STATE_ON, filtered_states))\n state = self.mode(states)\n self._attr_is_on = state\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 278, "n_words": 113, "vocab_size": 57, "complexity": 7, "nloc": 16, "token_counts": 122, "n_ast_nodes": 193, "n_identifiers": 21 }, { "id": 304515, "commit_id": "ced8278e3222501dde7d769ea4b57aae75f62438", "repo": "core", "path": "homeassistant/components/bluetooth/scanner.py", "file_name": "scanner.py", "fun_name": "_async_stop", "commit_message": "Auto recover when the Bluetooth adapter stops responding (#77043)", "code": "async def _async_stop(self) -> None:\n \n if self._cancel_watchdog:\n self._cancel_watchdog()\n self._cancel_watchdog = None\n await self._async_stop_scanner()\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 56, "n_words": 13, "vocab_size": 13, "complexity": 2, "nloc": 6, "token_counts": 29, "n_ast_nodes": 53, "n_identifiers": 4 }, { "id": 320177, "commit_id": "9214b412556e994dcf32dd2c7e050169f5cace1c", "repo": "paperless-ngx", "path": ".github/scripts/cleanup-tags.py", "file_name": "cleanup-tags.py", "fun_name": "decide_what_tags_to_keep", "commit_message": "Fixes deleting images if the branch API returns an error code and makes the error code a failure", "code": "def decide_what_tags_to_keep(self):\n \n\n # Default to everything gets kept still\n super().decide_what_tags_to_keep()\n\n # Locate the feature branches\n feature_branches = {}\n for branch in self.branch_api.get_branches(\n repo=self.repo_name,\n ):\n if branch.name.startswith(\"feature-\"):\n logger.debug(f\"Found feature branch {branch.name}\")\n feature_branches[branch.name] = branch\n\n logger.info(f\"Located {len(feature_branches)} feature branches\")\n\n if not len(feature_branches):\n # Our work here is done, delete nothing\n return\n\n # Filter to packages which are tagged with feature-*\n packages_tagged_feature: List[ContainerPackage] = []\n for package in self.all_package_versions:\n if package.tag_matches(\"feature-\"):\n packages_tagged_feature.append(package)\n\n # Map tags like \"feature-xyz\" to a ContainerPackage\n feature_pkgs_tags_to_versions: Dict[str, ContainerPackage] = {}\n for pkg in packages_tagged_feature:\n for tag in pkg.tags:\n feature_pkgs_tags_to_versions[tag] = pkg\n\n logger.info(\n f'Located {len(feature_pkgs_tags_to_versions)} versions of package {self.package_name} tagged \"feature-\"',\n )\n\n # All the feature tags minus all the feature branches leaves us feature tags\n # with no corresponding branch\n self.tags_to_delete = list(\n set(feature_pkgs_tags_to_versions.keys()) - set(feature_branches.keys()),\n )\n\n # All the tags minus the set of going to be deleted tags leaves us the\n # tags which will be kept around\n self.tags_to_keep = list(\n set(self.all_pkgs_tags_to_version.keys()) - set(self.tags_to_delete),\n )\n logger.info(\n f\"Located {len(self.tags_to_delete)} versions of package {self.package_name} to delete\",\n )\n\n", "url": "https://github.com/paperless-ngx/paperless-ngx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 528, "n_words": 169, "vocab_size": 100, "complexity": 8, "nloc": 32, "token_counts": 199, "n_ast_nodes": 384, "n_identifiers": 35 }, { "id": 134379, "commit_id": "182744bbd151c166b8028355eae12a5da63fb3cc", "repo": "ray", "path": "rllib/algorithms/algorithm_config.py", "file_name": "algorithm_config.py", "fun_name": "is_multi_agent", "commit_message": "[RLlib] AlgorithmConfig: Next steps (volume 01); Algos, RolloutWorker, PolicyMap, WorkerSet use AlgorithmConfig objects under the hood. (#29395)", "code": "def is_multi_agent(self) -> bool:\n \n return self._is_multi_agent\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 8, "token_counts": 12, "n_ast_nodes": 22, "n_identifiers": 4 }, { "id": 100648, "commit_id": "0d23714875f81ddabdbe8f4e40bef6e5f29eeb19", "repo": "faceswap", "path": "scripts/extract.py", "file_name": "extract.py", "fun_name": "_skip_num", "commit_message": "bugfix: extract - stop progress bar from going over max value", "code": "def _skip_num(self) -> int:\n \n return self._args.extract_every_n if hasattr(self._args, \"extract_every_n\") else 1\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 25, "n_words": 11, "vocab_size": 11, "complexity": 2, "nloc": 3, "token_counts": 25, "n_ast_nodes": 42, "n_identifiers": 6 }, { "id": 169398, "commit_id": "fba672389b74ca4afece56040ae079a1f2b71544", "repo": "pandas", "path": "pandas/core/resample.py", "file_name": "resample.py", "fun_name": "_wrap_result", "commit_message": "Bug fix using GroupBy.resample produces inconsistent behavior when calling it over empty df #47705 (#47672)\n\n* DOC #45443 edited the documentation of where/mask functions\r\n\r\n* DOC #45443 edited the documentation of where/mask functions\r\n\r\n* Update generic.py\r\n\r\n* Bug 43767 fix\r\n\r\n* fixing lines doc\r\n\r\n* visual indent\r\n\r\n* visual indent\r\n\r\n* indentation\r\n\r\n* grouby.resample bug\r\n\r\n* groubby.sample\r\n\r\n* syntax\r\n\r\n* syntax\r\n\r\n* syntax\r\n\r\n* syntax\r\n\r\n* what's new\r\n\r\n* flake8 error\r\n\r\n* pytest\r\n\r\n* blank line\r\n\r\n* editting resample\r\n\r\n* editting resample\r\n\r\n* syntax\r\n\r\n* syntax\r\n\r\n* syntax\r\n\r\n* space\r\n\r\n* space\r\n\r\n* space\r\n\r\n* inplace\r\n\r\n* spelling\r\n\r\n* test\r\n\r\n* test resampler\r\n\r\n* tests\r\n\r\n* tests\r\n\r\n* Update resample.py\r\n\r\n* Update resample.py\r\n\r\n* Update resample.py\r\n\r\n* Update v1.6.0.rst", "code": "def _wrap_result(self, result):\n \n # GH 47705\n obj = self.obj\n if (\n isinstance(result, ABCDataFrame)\n and result.empty\n and not isinstance(result.index, PeriodIndex)\n ):\n result = result.set_index(\n _asfreq_compat(obj.index[:0], freq=self.freq), append=True\n )\n\n if isinstance(result, ABCSeries) and self._selection is not None:\n result.name = self._selection\n\n if isinstance(result, ABCSeries) and result.empty:\n # When index is all NaT, result is empty but index is not\n result.index = _asfreq_compat(obj.index[:0], freq=self.freq)\n result.name = getattr(obj, \"name\", None)\n\n return result\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 237, "n_words": 67, "vocab_size": 43, "complexity": 8, "nloc": 16, "token_counts": 132, "n_ast_nodes": 204, "n_identifiers": 17 }, { "id": 297321, "commit_id": "5d316734659cc331658ea2f77a2985cd2c58d043", "repo": "core", "path": "tests/components/google_assistant_sdk/conftest.py", "file_name": "conftest.py", "fun_name": "mock_expires_at", "commit_message": "Google Assistant SDK integration (#82328)\n\n* Copy google_sheets to google_assistant_sdk\r\n\r\nThis is to improve diff of the next commit with the actual implementation.\r\n\r\nCommands used:\r\ncp -r homeassistant/components/google_sheets/ homeassistant/components/google_assistant_sdk/\r\ncp -r tests/components/google_sheets/ tests/components/google_assistant_sdk/\r\n\r\nfind homeassistant/components/google_assistant_sdk/ tests/components/google_assistant_sdk/ -type f | xargs sed -i \\\r\n-e 's@google_sheets@google_assistant_sdk@g' \\\r\n-e 's@Google Sheets@Google Assistant SDK@g' \\\r\n-e 's@tkdrob@tronikos@g'\r\n\r\n* Google Assistant SDK integration\r\nAllows sending commands and broadcast messages to Google Assistant.\r\n\r\n* Remove unnecessary async_entry_has_scopes check\r\n\r\n* Bump gassist-text to fix protobuf dependency", "code": "def mock_expires_at() -> int:\n \n return time.time() + 3600\n\n\n@pytest.fixture(name=\"config_entry\")", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "@pytest.fixture(name=\"config_entry\")", "n_ast_errors": 1, "ast_levels": 8, "n_whitespaces": 14, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 3, "token_counts": 15, "n_ast_nodes": 45, "n_identifiers": 6 }, { "id": 284585, "commit_id": "a6f7e111e68346aeab315985b3704c2710693b38", "repo": "OpenBBTerminal", "path": "openbb_terminal/stocks/government/gov_controller.py", "file_name": "gov_controller.py", "fun_name": "print_help", "commit_message": "Bounty Hunter mood: 11 bugs fixed (#1853)\n\n* fix #1850\r\n\r\n* fix #1831\r\n\r\n* add extra check to Reddit API keys\r\n\r\n* ignore warning message to update praw api\r\n\r\n* improve OpenBB links\r\n\r\n* fix quick performance only on stocks class because I'm James bitch\r\n\r\n* fix quick performance only on stocks class because I'm James bitch\r\n\r\n* fix #1829\r\n\r\n* fix #1821\r\n\r\n* add messari to keys - fix #1819\r\n\r\n* example of multiple oclumns to check on options/chains\r\n\r\n* minor improvement in xlabel re. #1814\r\n\r\n* remove repeated command\r\n\r\n* fix #1698\r\n\r\n* fix line too long\r\n\r\n* fix #1814 fr now\r\n\r\n* fix tests", "code": "def print_help(self):\n \n has_ticker_start = \"[unvl]\" if not self.ticker else \"\"\n has_ticker_end = \"[/unvl]\" if not self.ticker else \"\"\n help_text = f\n console.print(text=help_text, menu=\"Stocks - Government\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 60, "n_words": 25, "vocab_size": 18, "complexity": 3, "nloc": 24, "token_counts": 42, "n_ast_nodes": 96, "n_identifiers": 10 }, { "id": 252298, "commit_id": "3872d33111d27430c4b5f1ae021e91e3522cc0e3", "repo": "mitmproxy", "path": "release/build.py", "file_name": "build.py", "fun_name": "standalone_binaries", "commit_message": "simplify ci build script, add MSIX installer and Microsoft store.", "code": "def standalone_binaries():\n \n with archive(DIST_DIR / f\"mitmproxy-{version()}-{operating_system()}\") as f:\n _pyinstaller(\"standalone.spec\")\n\n for tool in [\"mitmproxy\", \"mitmdump\", \"mitmweb\"]:\n executable = TEMP_DIR / \"pyinstaller/dist\" / tool\n if platform.system() == \"Windows\":\n executable = executable.with_suffix(\".exe\")\n\n # Test if it works at all O:-)\n print(f\"> {executable} --version\")\n subprocess.check_call([executable, \"--version\"])\n\n f.add(str(executable), str(executable.name))\n print(f\"Packed {f.name}.\")\n\n", "url": "https://github.com/mitmproxy/mitmproxy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 150, "n_words": 46, "vocab_size": 40, "complexity": 3, "nloc": 11, "token_counts": 91, "n_ast_nodes": 195, "n_identifiers": 19 }, { "id": 144311, "commit_id": "c065e3f69ec248383d98b45a8d1c00832ccfdd57", "repo": "ray", "path": "python/ray/experimental/dag/dag_node.py", "file_name": "dag_node.py", "fun_name": "_get_all_child_nodes", "commit_message": "[Ray DAG] Implement experimental Ray DAG API for task/class (#22058)", "code": "def _get_all_child_nodes(self) -> Set[\"DAGNode\"]:\n \n\n scanner = _PyObjScanner()\n children = set()\n for n in scanner.find_nodes([self._bound_args, self._bound_kwargs]):\n children.add(n)\n return children\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 64, "n_words": 18, "vocab_size": 16, "complexity": 2, "nloc": 15, "token_counts": 47, "n_ast_nodes": 79, "n_identifiers": 12 }, { "id": 285873, "commit_id": "7fd72d9ee1e8847717195859bf6d608268a94e2f", "repo": "OpenBBTerminal", "path": "openbb_terminal/forecast/forecast_controller.py", "file_name": "forecast_controller.py", "fun_name": "refresh_datasets_on_menu", "commit_message": "Forecasting Menu [Work in Progress] (#1933)\n\n* Gave forecasting memory\r\n\r\n* Fixed scripts, refactored\r\n\r\n* FIxed poetry lock\r\n\r\n* edge case check for forecast target\r\n\r\n* Improved combine and load functionality\r\n\r\n* Cleaned up translations\r\n\r\n* Fixed issue with covariates\r\n\r\n* Fixed issue checking covariates\r\n\r\n* Another covariates check fix\r\n\r\n* Ignored regr and linregr warnings\r\n\r\n* Fixed covariate issues\r\n\r\n* switched from forecasting to forecast\r\n\r\n* Finished transition to forecast\r\n\r\n* Can add entire dataset with one command\r\n\r\n* Improved combine description\r\n\r\n* Removed naming covariates\r\n\r\n* Created new installation\r\n\r\n* typo\r\n\r\n* Make plot show dates if available\r\n\r\n* Added better handling or users without the menu\r\n\r\n* Removed unused file\r\n\r\n* Fix\r\n\r\n* Better handling for nontraditional datasets\r\n\r\n* Fixed black and pylint\r\n\r\n* Fixed tests\r\n\r\n* Added darts install to main tests\r\n\r\n* Working on darts with CI\r\n\r\n* Added back test file\r\n\r\n* Made large tables print better\r\n\r\n* naive baseline\r\n\r\n* typo\r\n\r\n* Finished naive\r\n\r\n* no dollar on prediction\r\n\r\n* fixed positive MAPE bug\r\n\r\n* quick refactoring\r\n\r\n* Fixed two different args for same thing\r\n\r\n* added extra patience\r\n\r\n* linreg mape fix\r\n\r\n* info fix\r\n\r\n* Refactored API, bumped to Darts 0.21.0\r\n\r\n* Added fixes\r\n\r\n* Increased verbosity for wrong column\r\n\r\n* Updated dependencies\r\n\r\n* Hid warnings\r\n\r\n* Fixed importing\r\n\r\n* Fixed tests\r\n\r\n* Fixed ugly seasonal plotting\r\n\r\n* Fixed forecast line color\r\n\r\n* Switched chart output to blue\r\n\r\n* Simplified lambda_price_prediction_color\r\n\r\n* fixed residuals\r\n\r\n* Chnage\r\n\r\n* Removed darts from CI per Chavi\r\n\r\n* Added fixes to tests\r\n\r\n* Added knnfix\r\n\r\n* Fixed issue where n!= o\r\n\r\n* Added changes\r\n\r\n* Added changes\r\n\r\n* Imrpoved forecast dash\r\n\r\n* Added Theo notebook\r\n\r\n* Added enhancements to dash\r\n\r\n* Added notebook\r\n\r\n* Added fix for jupyter lab\r\n\r\n* Added debug stuff\r\n\r\n* Change\r\n\r\n* Updated docs\r\n\r\n* Fixed formatting\r\n\r\n* Fixed formatting\r\n\r\n* Removed prints\r\n\r\n* Filtered some info\r\n\r\n* Added button to run model\r\n\r\n* Improved api\r\n\r\n* Added secret feautr (no peeking Martin)\r\n\r\n* Cleaned code\r\n\r\n* Fixed tests\r\n\r\n* Added test fixes\r\n\r\n* Added fixes\r\n\r\n* Fixes\r\n\r\n* FIxes for pres\r\n\r\n* Remove bad tests\r\n\r\n* Removed knn\r\n\r\n* Fixed issues with removing mc\r\n\r\n* doc for conda\r\n\r\n* Added forecast improvements\r\n\r\n* Added streamlit support\r\n\r\n* Fixed issues\r\n\r\n* fix expo with streamlit due to quantile()\r\n\r\n* fixed performance issues with streamlit for now..\r\n\r\n* clean up historical forecast with new trainer\r\n\r\n* quick fix for regression trainer params\r\n\r\n* Added fixes\r\n\r\n* quick fix for other fix for regression trainer params\r\n\r\n* table formatting for timestamp\r\n\r\n* potential fix for inf in feature engineered datasets\r\n\r\n* Basic working in new format\r\n\r\n* dw\r\n\r\n* Trying\r\n\r\n* Fixed issues\r\n\r\n* Improved graphing\r\n\r\n* fixing trainer for LR and formatting\r\n\r\n* doge and linting\r\n\r\n* page break\r\n\r\n* automatic cleaning of datasets\r\n\r\n* automatic cleaning of datasets- fix\r\n\r\n* Fixed forecast dates\r\n\r\n* Made dashboard prettier\r\n\r\n* Added fixes\r\n\r\n* Added fixes\r\n\r\n* Added options\r\n\r\n* Fixed error\r\n\r\n* remove caching\r\n\r\n* adding in spinner\r\n\r\n* Added vairable n_predict in streamlit\r\n\r\n* Added mypy fix\r\n\r\n* renaming and range change\r\n\r\n* new index for n predict\r\n\r\n* check positive float for window size\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* renaming\r\n\r\n* reorg files\r\n\r\n* Update _index.md\r\n\r\n* hidden which command for versions\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* which: ns parser\r\n\r\n* hugo for: which\r\n\r\n* hugo for: forecasting fix\r\n\r\n* formatting black\r\n\r\n* update stock controller test\r\n\r\n* Lay groundwork for better residual plotting\r\n\r\n* improved delete to allow for periods in title\r\n\r\n* improved automatic cleaning of inf\r\n\r\n* Added new API\r\n\r\n* Added new API\r\n\r\n* Added new API\r\n\r\n* formatting for black\r\n\r\n* Updated our testing CI\r\n\r\n* Reverted changes\r\n\r\n* Added forecast docs\r\n\r\n* Fixed mypy issues\r\n\r\n* Fixes tests\r\n\r\n* Did some refactoring, added a report\r\n\r\n* new api in streamlit\r\n\r\n* Added integrated tests\r\n\r\n* Update _index.md\r\n\r\n* improved loading in custom dataset\r\n\r\n* menu spacing\r\n\r\n* installer fixes\r\n\r\n* Added docs fixes\r\n\r\n* Adding comments to test if commit working\r\n\r\n* Fixed report\r\n\r\n* naming conventions\r\n\r\n* formatting\r\n\r\n* removing unused var\r\n\r\n* Made last report imporvements\r\n\r\n* Update README.md\r\n\r\n* Added fix\r\n\r\n* Switched to warning\r\n\r\n* Added fixes\r\n\r\n* Added fixes\r\n\r\n* Added fixes\r\n\r\n* Added fixes\r\n\r\n* Update economy av view test\r\n\r\n* Remove forgotten print statement\r\n\r\n* Update depencencies\r\n\r\n* Added verbosity to pytest\r\n\r\n* Added fixes\r\n\r\n* Fixed pylint\r\n\r\n* Fixed actions checkout\r\n\r\n* Added fixes\r\n\r\nCo-authored-by: colin99d \r\nCo-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>\r\nCo-authored-by: James Simmons \r\nCo-authored-by: minhhoang1023 <40023817+minhhoang1023@users.noreply.github.com>\r\nCo-authored-by: Theodore Aptekarev ", "code": "def refresh_datasets_on_menu(self):\n \n\n self.list_dataset_cols = list()\n maxfile = max(len(file) for file in self.files)\n self.loaded_dataset_cols = \"\\n\"\n for dataset, data in self.datasets.items():\n self.loaded_dataset_cols += (\n f\" {dataset} {(maxfile - len(dataset)) * ' '}: \"\n f\"{', '.join(data.columns)}\\n\"\n )\n\n for col in data.columns:\n self.list_dataset_cols.append(f\"{dataset}.{col}\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 154, "n_words": 40, "vocab_size": 33, "complexity": 4, "nloc": 11, "token_counts": 72, "n_ast_nodes": 171, "n_identifiers": 18 }, { "id": 198798, "commit_id": "3b6e792c521077d661ae212e7de414696e13ccb6", "repo": "sympy", "path": "sympy/physics/continuum_mechanics/truss.py", "file_name": "truss.py", "fun_name": "apply_load", "commit_message": "changes to just append loads of the same direction along with others made", "code": "def apply_load(self, location, magnitude, direction):\n \n magnitude = sympify(magnitude)\n direction = sympify(direction)\n\n if location not in self.node_labels:\n raise ValueError(\"Load must be applied at a known node\")\n\n else:\n if location in list(self._loads):\n self._loads[location].append([magnitude, direction])\n else:\n self._loads[location] = [[magnitude, direction]]\n", "url": "https://github.com/sympy/sympy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 135, "n_words": 37, "vocab_size": 31, "complexity": 3, "nloc": 10, "token_counts": 80, "n_ast_nodes": 127, "n_identifiers": 11 }, { "id": 246011, "commit_id": "2359ee3864a065229c80e3ff58faa981edd24558", "repo": "synapse", "path": "synapse/storage/databases/main/stream.py", "file_name": "stream.py", "fun_name": "get_room_max_stream_ordering", "commit_message": "Remove redundant `get_current_events_token` (#11643)\n\n* Push `get_room_{min,max_stream_ordering}` into StreamStore\r\n\r\nBoth implementations of this are identical, so we may as well push it down and\r\nget rid of the abstract base class nonsense.\r\n\r\n* Remove redundant `StreamStore` class\r\n\r\nThis is empty now\r\n\r\n* Remove redundant `get_current_events_token`\r\n\r\nThis was an exact duplicate of `get_room_max_stream_ordering`, so let's get rid\r\nof it.\r\n\r\n* newsfile", "code": "def get_room_max_stream_ordering(self) -> int:\n \n return self._stream_id_gen.get_current_token()\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 7, "token_counts": 16, "n_ast_nodes": 29, "n_identifiers": 5 }, { "id": 144850, "commit_id": "53c4c7b1be54fe67a54b34f3f0c076ad502e35cc", "repo": "ray", "path": "python/ray/data/row.py", "file_name": "row.py", "fun_name": "as_pydict", "commit_message": "[Datasets] Expose `TableRow` as public API; minimize copies/type conversions on row-based ops. (#22305)\n\nThis PR properly exposes `TableRow` as a public API (API docs + the \"Public\" tag), since it's already exposed to the user in our row-based ops. In addition, the following changes are made:\r\n1. During row-based ops, we also choose a batch format that lines up with the current dataset format in order to eliminate unnecessary copies and type conversions.\r\n2. `TableRow` now derives from `collections.abc.Mapping`, which lets `TableRow` better interop with code expecting a mapping, and includes a few helpful mixins so we only have to implement `__getitem__`, `__iter__`, and `__len__`.", "code": "def as_pydict(self) -> dict:\n \n return dict(self.items())\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 4, "token_counts": 17, "n_ast_nodes": 31, "n_identifiers": 4 }, { "id": 58977, "commit_id": "1a3a3adf0bf4d83206f0367b98905a9db15cfec4", "repo": "prefect", "path": "src/prefect/orion/api/block_types.py", "file_name": "block_types.py", "fun_name": "install_protected_system_blocks", "commit_message": "Adds ability to delete block types via the CLI (#6849)\n\n* Ensure system blocks are protected on destructive API calls\r\n\r\n* Enable deleting block types\r\n\r\n* Ensure Block Types are protected against destructive API actions\r\n\r\n* Ensure updating protected Block Types on update doesn't impact saving\r\n\r\n* ⚫\r\n\r\n* isort\r\n\r\n* Suppress status errors\r\n\r\n* ⚫", "code": "async def install_protected_system_blocks(session):\n \n for block in [\n prefect.blocks.system.JSON,\n prefect.blocks.system.DateTime,\n prefect.blocks.system.Secret,\n prefect.filesystems.LocalFileSystem,\n prefect.infrastructure.Process,\n ]:\n block_type = block._to_block_type()\n block_type.is_protected = True\n\n block_type = await models.block_types.create_block_type(\n session=session, block_type=block_type, override=True\n )\n block_schema = await models.block_schemas.create_block_schema(\n session=session,\n block_schema=block._to_block_schema(block_type_id=block_type.id),\n override=True,\n )\n\n\n@router.post(\"/install_system_block_types\")", "url": "https://github.com/PrefectHQ/prefect.git", "language": "Python", "ast_errors": "@router.post(\"/install_system_block_types\")", "n_ast_errors": 1, "ast_levels": 16, "n_whitespaces": 165, "n_words": 36, "vocab_size": 29, "complexity": 2, "nloc": 18, "token_counts": 112, "n_ast_nodes": 183, "n_identifiers": 28 }, { "id": 177078, "commit_id": "28f78cfa9a386620ee1179582fda1db5ffc59f84", "repo": "networkx", "path": "networkx/algorithms/distance_measures.py", "file_name": "distance_measures.py", "fun_name": "radius", "commit_message": "Add weight distance metrics (#5305)\n\nAdds the weight keyword argument to allow users to compute weighted distance metrics\r\ne.g. diameter, eccentricity, periphery, etc. The kwarg works in the same fashion as the\r\nweight param for shortest paths - i.e. if a string, look up with edge attr by key, if callable,\r\ncompute the weight via the function. Default is None, meaning return unweighted result\r\nwhich is the current behavior.\r\n\r\nCo-authored-by: Dan Schult \r\nCo-authored-by: Ross Barnowski ", "code": "def radius(G, e=None, usebounds=False, weight=None):\n \n if usebounds is True and e is None and not G.is_directed():\n return _extrema_bounding(G, compute=\"radius\", weight=weight)\n if e is None:\n e = eccentricity(G, weight=weight)\n return min(e.values())\n\n", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 56, "n_words": 30, "vocab_size": 22, "complexity": 5, "nloc": 6, "token_counts": 71, "n_ast_nodes": 112, "n_identifiers": 11 }, { "id": 21767, "commit_id": "8faa74cdc9da20cfdcc69f5ec29b91112c95b4c9", "repo": "pipenv", "path": "pipenv/vendor/tomlkit/items.py", "file_name": "items.py", "fun_name": "is_dotted", "commit_message": "Update tomlkit==0.9.2\n\nUsed:\n\n python -m invoke vendoring.update --package=tomlkit", "code": "def is_dotted(self) -> bool:\n \n return self._dotted\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 12, "n_ast_nodes": 22, "n_identifiers": 4 }, { "id": 260074, "commit_id": "effdd6e215c67f2ae8ed1e378ea1661e936059a4", "repo": "scikit-learn", "path": "sklearn/calibration.py", "file_name": "calibration.py", "fun_name": "_get_prediction_method", "commit_message": "API Rename base_estimator in CalibratedClassifierCV (#22054)\n\nCo-authored-by: Kevin Roice \r\nCo-authored-by: Guillaume Lemaitre \r\nCo-authored-by: Thomas J. Fan ", "code": "def _get_prediction_method(clf):\n \n if hasattr(clf, \"decision_function\"):\n method = getattr(clf, \"decision_function\")\n return method, \"decision_function\"\n elif hasattr(clf, \"predict_proba\"):\n method = getattr(clf, \"predict_proba\")\n return method, \"predict_proba\"\n else:\n raise RuntimeError(\n \"'estimator' has no 'decision_function' or 'predict_proba' method.\"\n )\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 98, "n_words": 33, "vocab_size": 27, "complexity": 3, "nloc": 11, "token_counts": 53, "n_ast_nodes": 99, "n_identifiers": 6 }, { "id": 174928, "commit_id": "bad03ef931d9b3ff4f9e75f35f9c41f45839e2a1", "repo": "pip", "path": "tests/functional/test_download.py", "file_name": "test_download.py", "fun_name": "generate_metadata", "commit_message": "Use data-dist-info-metadata (PEP 658) to decouple resolution from downloading (#11111)\n\nCo-authored-by: Tzu-ping Chung ", "code": "def generate_metadata(self) -> bytes:\n \n return dedent(\n f\n ).encode(\"utf-8\")\n\n\n@pytest.fixture(scope=\"function\")", "url": "https://github.com/pypa/pip.git", "language": "Python", "ast_errors": "@pytest.fixture(scope=\"function\")", "n_ast_errors": 1, "ast_levels": 13, "n_whitespaces": 40, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 11, "token_counts": 19, "n_ast_nodes": 79, "n_identifiers": 11 }, { "id": 176579, "commit_id": "bc7ace58c872d527475c09345f89579ff82e4c5d", "repo": "networkx", "path": "networkx/algorithms/bipartite/projection.py", "file_name": "projection.py", "fun_name": "weighted_projected_graph", "commit_message": "Fixes #5403: Errors on non-distinct bipartite node sets (#5442)\n\n* is_bipartite_node_set errors if nodes not distinct\r\n\r\n* weighted_projected_graph errors if nodeset too big\r\n\r\n* update release_dev.rst\r\n\r\n* Use sets instead of lists for collecting flowfuncs in tests. (#5589)\r\n\r\nCo-authored-by: Ross Barnowski ", "code": "def weighted_projected_graph(B, nodes, ratio=False):\n r\n if B.is_directed():\n pred = B.pred\n G = nx.DiGraph()\n else:\n pred = B.adj\n G = nx.Graph()\n G.graph.update(B.graph)\n G.add_nodes_from((n, B.nodes[n]) for n in nodes)\n n_top = float(len(B) - len(nodes))\n\n if n_top < 1:\n raise NetworkXAlgorithmError(\n f\"the size of the nodes to project onto ({len(nodes)}) is >= the graph size ({len(B)}).\\n\"\n \"They are either not a valid bipartite partition or contain duplicates\"\n )\n\n for u in nodes:\n unbrs = set(B[u])\n nbrs2 = {n for nbr in unbrs for n in B[nbr]} - {u}\n for v in nbrs2:\n vnbrs = set(pred[v])\n common = unbrs & vnbrs\n if not ratio:\n weight = len(common)\n else:\n weight = len(common) / n_top\n G.add_edge(u, v, weight=weight)\n return G\n\n\n@not_implemented_for(\"multigraph\")", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "@not_implemented_for(\"multigraph\")", "n_ast_errors": 1, "ast_levels": 16, "n_whitespaces": 310, "n_words": 115, "vocab_size": 79, "complexity": 9, "nloc": 95, "token_counts": 188, "n_ast_nodes": 326, "n_identifiers": 30 }, { "id": 104814, "commit_id": "7017b0965f0a0cae603e7143de242c3425ecef91", "repo": "datasets", "path": "src/datasets/utils/streaming_download_manager.py", "file_name": "streaming_download_manager.py", "fun_name": "xdirname", "commit_message": "Add support for metadata files to `imagefolder` (#4069)\n\n* Add support for metadata files to `imagefolder`\r\n\r\n* Fix imagefolder drop_labels test\r\n\r\n* Replace csv with jsonl\r\n\r\n* Add test\r\n\r\n* Correct resolution for nested metadata files\r\n\r\n* Allow None as JSON Lines value\r\n\r\n* Add comments\r\n\r\n* Count path segments\r\n\r\n* Address comments\r\n\r\n* Improve test\r\n\r\n* Update src/datasets/packaged_modules/imagefolder/imagefolder.py\r\n\r\nCo-authored-by: Quentin Lhoest <42851186+lhoestq@users.noreply.github.com>\r\n\r\n* test e2e imagefolder with metadata\r\n\r\n* add test for zip archives\r\n\r\n* fix test\r\n\r\n* add some debug logging to know which files are ignored\r\n\r\n* add test for bad/malformed metadata file\r\n\r\n* revert use of posix path to fix windows tests\r\n\r\n* style\r\n\r\n* Refactor tests for packaged modules Text and Csv\r\n\r\nCo-authored-by: Quentin Lhoest <42851186+lhoestq@users.noreply.github.com>\r\nCo-authored-by: Quentin Lhoest ", "code": "def xdirname(a):\n \n a, *b = str(a).split(\"::\")\n if is_local_path(a):\n a = os.path.dirname(Path(a).as_posix())\n else:\n a = posixpath.dirname(a)\n # if we end up at the root of the protocol, we get for example a = 'http:'\n # so we have to fix it by adding the '//' that was removed:\n if a.endswith(\":\"):\n a += \"//\"\n return \"::\".join([a] + b)\n\n", "url": "https://github.com/huggingface/datasets.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 101, "n_words": 56, "vocab_size": 43, "complexity": 3, "nloc": 9, "token_counts": 75, "n_ast_nodes": 136, "n_identifiers": 14 }, { "id": 247306, "commit_id": "2ffaf30803f93273a4d8a65c9e6c3110c8433488", "repo": "synapse", "path": "tests/rest/client/test_rooms.py", "file_name": "test_rooms.py", "fun_name": "test_add_alias", "commit_message": "Add type hints to `tests/rest/client` (#12108)\n\n* Add type hints to `tests/rest/client`\r\n\r\n* newsfile\r\n\r\n* fix imports\r\n\r\n* add `test_account.py`\r\n\r\n* Remove one type hint in `test_report_event.py`\r\n\r\n* change `on_create_room` to `async`\r\n\r\n* update new functions in `test_third_party_rules.py`\r\n\r\n* Add `test_filter.py`\r\n\r\n* add `test_rooms.py`\r\n\r\n* change to `assertEquals` to `assertEqual`\r\n\r\n* lint", "code": "def test_add_alias(self) -> None:\n \n # Create an additional alias.\n second_alias = \"#second:test\"\n self._set_alias_via_directory(second_alias)\n\n # Add the canonical alias.\n self._set_canonical_alias({\"alias\": self.alias, \"alt_aliases\": [self.alias]})\n\n # Then add the second alias.\n self._set_canonical_alias(\n {\"alias\": self.alias, \"alt_aliases\": [self.alias, second_alias]}\n )\n\n # Canonical alias now exists!\n res = self._get_canonical_alias()\n self.assertEqual(\n res, {\"alias\": self.alias, \"alt_aliases\": [self.alias, second_alias]}\n )\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 164, "n_words": 51, "vocab_size": 36, "complexity": 1, "nloc": 12, "token_counts": 90, "n_ast_nodes": 157, "n_identifiers": 9 }, { "id": 275982, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/saving/saved_model/base_serialization.py", "file_name": "base_serialization.py", "fun_name": "objects_to_serialize", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def objects_to_serialize(self, serialization_cache):\n \n raise NotImplementedError\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 19, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 2, "token_counts": 10, "n_ast_nodes": 18, "n_identifiers": 4 }, { "id": 224044, "commit_id": "e7f07cc82ab2be920ab426ba07456d8b2592714d", "repo": "mkdocs", "path": "mkdocs/tests/build_tests.py", "file_name": "build_tests.py", "fun_name": "build_page", "commit_message": "Remove spaces at the ends of docstrings, normalize quotes", "code": "def build_page(title, path, config, md_src=''):\n \n\n files = Files([File(path, config['docs_dir'], config['site_dir'], config['use_directory_urls'])])\n page = Page(title, list(files)[0], config)\n # Fake page.read_source()\n page.markdown, page.meta = meta.get_data(md_src)\n return page, files\n\n", "url": "https://github.com/mkdocs/mkdocs.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 44, "n_words": 26, "vocab_size": 23, "complexity": 1, "nloc": 5, "token_counts": 74, "n_ast_nodes": 118, "n_identifiers": 14 }, { "id": 249813, "commit_id": "d8cc86eff484b6f570f55a5badb337080c6e4dcd", "repo": "synapse", "path": "synapse/api/errors.py", "file_name": "errors.py", "fun_name": "to_synapse_error", "commit_message": "Remove redundant types from comments. (#14412)\n\nRemove type hints from comments which have been added\r\nas Python type hints. This helps avoid drift between comments\r\nand reality, as well as removing redundant information.\r\n\r\nAlso adds some missing type hints which were simple to fill in.", "code": "def to_synapse_error(self) -> SynapseError:\n \n # try to parse the body as json, to get better errcode/msg, but\n # default to M_UNKNOWN with the HTTP status as the error text\n try:\n j = json_decoder.decode(self.response.decode(\"utf-8\"))\n except ValueError:\n j = {}\n\n if not isinstance(j, dict):\n j = {}\n\n errcode = j.pop(\"errcode\", Codes.UNKNOWN)\n errmsg = j.pop(\"error\", self.msg)\n\n return ProxiedRequestError(self.code, errmsg, errcode, j)\n\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 154, "n_words": 58, "vocab_size": 45, "complexity": 3, "nloc": 26, "token_counts": 82, "n_ast_nodes": 138, "n_identifiers": 18 }, { "id": 269919, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/callbacks.py", "file_name": "callbacks.py", "fun_name": "_implements_test_batch_hooks", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _implements_test_batch_hooks(self):\n \n return not generic_utils.is_default(\n self.on_test_batch_begin\n ) or not generic_utils.is_default(self.on_test_batch_end)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 42, "n_words": 10, "vocab_size": 9, "complexity": 2, "nloc": 4, "token_counts": 26, "n_ast_nodes": 45, "n_identifiers": 6 }, { "id": 269930, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/callbacks.py", "file_name": "callbacks.py", "fun_name": "on_predict_begin", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def on_predict_begin(self, logs=None):\n \n logs = self._process_logs(logs)\n for callback in self.callbacks:\n callback.on_predict_begin(logs)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 43, "n_words": 11, "vocab_size": 11, "complexity": 2, "nloc": 4, "token_counts": 31, "n_ast_nodes": 51, "n_identifiers": 6 }, { "id": 133184, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "python/ray/util/multiprocessing/pool.py", "file_name": "pool.py", "fun_name": "map", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def map(self, func, iterable, chunksize=None):\n \n\n return self._map_async(\n func, iterable, chunksize=chunksize, unpack_args=False\n ).get()\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 44, "n_words": 12, "vocab_size": 10, "complexity": 1, "nloc": 4, "token_counts": 35, "n_ast_nodes": 52, "n_identifiers": 8 }, { "id": 129882, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "dashboard/modules/job/job_manager.py", "file_name": "job_manager.py", "fun_name": "_get_current_node_resource_key", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def _get_current_node_resource_key(self) -> str:\n \n current_node_id = ray.get_runtime_context().node_id.hex()\n for node in ray.nodes():\n if node[\"NodeID\"] == current_node_id:\n # Found the node.\n for key in node[\"Resources\"].keys():\n if key.startswith(\"node:\"):\n return key\n else:\n raise ValueError(\"Cannot find the node dictionary for current node.\")\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 159, "n_words": 37, "vocab_size": 30, "complexity": 5, "nloc": 13, "token_counts": 67, "n_ast_nodes": 119, "n_identifiers": 14 }, { "id": 256261, "commit_id": "a59bca366174d9c692fa19750c24d65f47660ef7", "repo": "haystack", "path": "haystack/modeling/training/base.py", "file_name": "base.py", "fun_name": "_get_state_dict", "commit_message": "Apply black formatting (#2115)\n\n* Testing black on ui/\r\n\r\n* Applying black on docstores\r\n\r\n* Add latest docstring and tutorial changes\r\n\r\n* Create a single GH action for Black and docs to reduce commit noise to the minimum, slightly refactor the OpenAPI action too\r\n\r\n* Remove comments\r\n\r\n* Relax constraints on pydoc-markdown\r\n\r\n* Split temporary black from the docs. Pydoc-markdown was obsolete and needs a separate PR to upgrade\r\n\r\n* Fix a couple of bugs\r\n\r\n* Add a type: ignore that was missing somehow\r\n\r\n* Give path to black\r\n\r\n* Apply Black\r\n\r\n* Apply Black\r\n\r\n* Relocate a couple of type: ignore\r\n\r\n* Update documentation\r\n\r\n* Make Linux CI run after applying Black\r\n\r\n* Triggering Black\r\n\r\n* Apply Black\r\n\r\n* Remove dependency, does not work well\r\n\r\n* Remove manually double trailing commas\r\n\r\n* Update documentation\r\n\r\nCo-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>", "code": "def _get_state_dict(self):\n \n state_dict = {\n \"evaluate_every\": self.evaluate_every,\n \"n_gpu\": self.n_gpu,\n \"grad_acc_steps\": self.grad_acc_steps,\n \"device\": self.device,\n \"local_rank\": self.local_rank,\n \"early_stopping\": self.early_stopping,\n \"epochs\": self.epochs,\n \"checkpoint_on_sigterm\": self.checkpoint_on_sigterm,\n \"checkpoint_root_dir\": self.checkpoint_root_dir,\n \"checkpoint_every\": self.checkpoint_every,\n \"checkpoints_to_keep\": self.checkpoints_to_keep,\n \"from_epoch\": self.from_epoch,\n \"from_step\": self.from_step,\n \"global_step\": self.global_step,\n \"log_learning_rate\": self.log_learning_rate,\n \"log_loss_every\": self.log_loss_every,\n \"disable_tqdm\": self.disable_tqdm,\n }\n\n return state_dict\n", "url": "https://github.com/deepset-ai/haystack.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 257, "n_words": 42, "vocab_size": 41, "complexity": 1, "nloc": 21, "token_counts": 114, "n_ast_nodes": 193, "n_identifiers": 20 }, { "id": 281704, "commit_id": "6a66f3f3ed934e0615ff4ba283ee67fcc43d3656", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/custom/quantitative_analysis/qa_controller.py", "file_name": "qa_controller.py", "fun_name": "print_help", "commit_message": "Custom data context (#1193)\n\n* Add first iteration of custom context\r\n\r\n* Add sample data + improve plot\r\n\r\n* Change `head` to `show` with sorting and limit. Add \"-x\" to plot and dynamic update of completer\r\n\r\n* generate random time series for test csv\r\n\r\n* Make columns lower case. Check if date is in columns and convert to timestamp. Improve plotting for dates\r\n\r\n* Add qa to custom\r\n\r\n* Add pred to custom\r\n\r\n* Hugooooo\r\n\r\n* Testing\r\n\r\n* dang whitespace\r\n\r\nCo-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>\r\nCo-authored-by: didierlopes.eth ", "code": "def print_help(self):\n \n help_text = f\n console.print(text=help_text, menu=\"Custom - Quantitative Analysis\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 31, "n_words": 10, "vocab_size": 10, "complexity": 1, "nloc": 31, "token_counts": 22, "n_ast_nodes": 54, "n_identifiers": 9 }, { "id": 136073, "commit_id": "06d5dc36e19f16b7e1f8d6e2e872a81624f6a42c", "repo": "ray", "path": "python/ray/air/util/tensor_extensions/arrow.py", "file_name": "arrow.py", "fun_name": "_arrow_extension_scalars_are_subclassable", "commit_message": "[Datasets] [Arrow 7+ Support - 3/N] Add support for Arrow 8, 9, 10, and nightly. (#29999)\n\nThis PR adds support for Arrow 8, 9, 10, and nightly in Ray, and is the third PR in a set of stacked PRs making up this mono-PR for Arrow 7+ support (#29161), and is stacked on top of a PR fixing task cancellation in Ray Core (#29984) and a PR adding support for Arrow 7 (#29993). The last two commits are the relevant commits for review.\r\n\r\nSummary of Changes\r\n\r\nThis PR:\r\n\r\n- For Arrow 9+, add allow_bucket_creation=true to S3 URIs for the Ray Core Storage API and for the Datasets S3 write API ([Datasets] In Arrow 9+, creating S3 buckets requires explicit opt-in. #29815).\r\n- For Arrow 9+, create an ExtensionScalar subclass for tensor extension types that returns an ndarray view from .as_py() ([Datasets] For Arrow 8+, tensor column element access returns an ExtensionScalar. #29816).\r\n- For Arrow 8.*, we manually convert the ExtensionScalar to an ndarray for tensor extension types, since the ExtensionScalar type exists but isn't subclassable in Arrow 8 ([Datasets] For Arrow 8+, tensor column element access returns an ExtensionScalar. #29816).\r\n- For Arrow 10+, we match on other potential error messages when encountering permission issues when interacting with S3 ([Datasets] In Arrow 10+, S3 errors raised due to permission issues can vary beyond our current pattern matching #29994).\r\n- adds CI jobs for Arrow 8, 9, 10, and nightly\r\n- removes the pyarrow version upper bound", "code": "def _arrow_extension_scalars_are_subclassable():\n \n # TODO(Clark): Remove utility once we only support Arrow 9.0.0+.\n return (\n PYARROW_VERSION is None\n or PYARROW_VERSION >= MIN_PYARROW_VERSION_SCALAR_SUBCLASS\n )\n\n\n@PublicAPI(stability=\"beta\")", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "@PublicAPI(stability=\"beta\")", "n_ast_errors": 1, "ast_levels": 8, "n_whitespaces": 48, "n_words": 23, "vocab_size": 22, "complexity": 2, "nloc": 5, "token_counts": 15, "n_ast_nodes": 42, "n_identifiers": 5 }, { "id": 181661, "commit_id": "388616b6247ca4ea8de4e2f340d6206aee523541", "repo": "tpot", "path": "tests/one_hot_encoder_tests.py", "file_name": "one_hot_encoder_tests.py", "fun_name": "test_transform", "commit_message": "Revert \"Deployed 7ccda9a with MkDocs version: 1.3.0\"\n\nThis reverts commit bd9629c40e01241766197119b581a99409b07068.", "code": "def test_transform():\n \n input = np.array(((0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 5))).transpose()\n ohe = OneHotEncoder()\n ohe.fit(input)\n test_data = np.array(((0, 1, 2, 6), (0, 1, 6, 7))).transpose()\n output = ohe.transform(test_data).todense()\n assert np.sum(output) == 5\n\n input = np.array(((0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 5))).transpose()\n ips = scipy.sparse.csr_matrix(input)\n ohe = OneHotEncoder()\n ohe.fit(ips)\n test_data = np.array(((0, 1, 2, 6), (0, 1, 6, 7))).transpose()\n tds = scipy.sparse.csr_matrix(test_data)\n output = ohe.transform(tds).todense()\n assert np.sum(output) == 3\n\n", "url": "https://github.com/EpistasisLab/tpot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 123, "n_words": 78, "vocab_size": 32, "complexity": 1, "nloc": 15, "token_counts": 233, "n_ast_nodes": 338, "n_identifiers": 18 }, { "id": 258797, "commit_id": "3786daf7dc5c301478d489b0756f90d0ac5d010f", "repo": "scikit-learn", "path": "sklearn/gaussian_process/tests/test_gpr.py", "file_name": "test_gpr.py", "fun_name": "test_sample_y_shapes", "commit_message": "BUG Fix covariance and stdev shape in GPR with normalize_y (#22199)\n\nCo-authored-by: Guillaume Lemaitre \r\nCo-authored-by: Nakamura-Zimmerer, Tenavi (ARC-AF) ", "code": "def test_sample_y_shapes(normalize_y, n_targets):\n \n rng = np.random.RandomState(1234)\n\n n_features, n_samples_train = 6, 9\n # Number of spatial locations to predict at\n n_samples_X_test = 7\n # Number of sample predictions per test point\n n_samples_y_test = 5\n\n y_train_shape = (n_samples_train,)\n if n_targets is not None:\n y_train_shape = y_train_shape + (n_targets,)\n\n # By convention single-output data is squeezed upon prediction\n if n_targets is not None and n_targets > 1:\n y_test_shape = (n_samples_X_test, n_targets, n_samples_y_test)\n else:\n y_test_shape = (n_samples_X_test, n_samples_y_test)\n\n X_train = rng.randn(n_samples_train, n_features)\n X_test = rng.randn(n_samples_X_test, n_features)\n y_train = rng.randn(*y_train_shape)\n\n model = GaussianProcessRegressor(normalize_y=normalize_y)\n\n # FIXME: before fitting, the estimator does not have information regarding\n # the number of targets and default to 1. This is inconsistent with the shape\n # provided after `fit`. This assert should be made once the following issue\n # is fixed:\n # https://github.com/scikit-learn/scikit-learn/issues/22430\n # y_samples = model.sample_y(X_test, n_samples=n_samples_y_test)\n # assert y_samples.shape == y_test_shape\n\n model.fit(X_train, y_train)\n\n y_samples = model.sample_y(X_test, n_samples=n_samples_y_test)\n assert y_samples.shape == y_test_shape\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 251, "n_words": 152, "vocab_size": 97, "complexity": 4, "nloc": 19, "token_counts": 142, "n_ast_nodes": 230, "n_identifiers": 24 }, { "id": 135927, "commit_id": "087548031bcf22dd73364b58acb70e61a49f2427", "repo": "ray", "path": "rllib/algorithms/algorithm_config.py", "file_name": "algorithm_config.py", "fun_name": "_check_if_correct_nn_framework_installed", "commit_message": "[RLlib] AlgorithmConfigs: Make None a valid value for methods to set properties; Use new `NotProvided` singleton, instead, to indicate no changes wanted on that property. (#30020)", "code": "def _check_if_correct_nn_framework_installed(self, _tf1, _tf, _torch):\n \n if self.framework_str in {\"tf\", \"tf2\"}:\n if not (_tf1 or _tf):\n raise ImportError(\n (\n \"TensorFlow was specified as the framework to use (via `config.\"\n \"framework([tf|tf2])`)! However, no installation was \"\n \"found. You can install TensorFlow via `pip install tensorflow`\"\n )\n )\n elif self.framework_str == \"torch\":\n if not _torch:\n raise ImportError(\n (\n \"PyTorch was specified as the framework to use (via `config.\"\n \"framework('torch')`)! However, no installation was found. You \"\n \"can install PyTorch via `pip install torch`.\"\n )\n )\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 399, "n_words": 82, "vocab_size": 51, "complexity": 6, "nloc": 19, "token_counts": 60, "n_ast_nodes": 112, "n_identifiers": 7 }, { "id": 103055, "commit_id": "e2f16ff62451eccb4fc901d30042ceca23940188", "repo": "kitty", "path": "kitty_tests/shell_integration.py", "file_name": "shell_integration.py", "fun_name": "test_fish_integration", "commit_message": "Add fish pipestatus integration tests and changelog entries", "code": "def test_fish_integration(self):\n fish_prompt, right_prompt = 'left>', '\r\nCo-authored-by: Eugene Kulak ", "code": "def test_jobs_empty(self, api):\n \n manager = InsightAsyncJobManager(api=api, jobs=[])\n jobs = list(manager.completed_jobs())\n assert not jobs\n", "url": "https://github.com/airbytehq/airbyte.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 41, "n_words": 13, "vocab_size": 11, "complexity": 1, "nloc": 4, "token_counts": 34, "n_ast_nodes": 57, "n_identifiers": 8 }, { "id": 288032, "commit_id": "52307708c843b947a2d631f2fe7ddaa8bd9a90d7", "repo": "core", "path": "homeassistant/components/apcupsd/__init__.py", "file_name": "__init__.py", "fun_name": "statflag", "commit_message": "Refactor apcupsd to use config flow (#64809)\n\n* Add Config Flow to APCUPSd integration and remove YAML support.\r\n\r\n* Hide the binary sensor if user does not select STATFLAG resource.\r\n\r\n* Add tests for config flows.\r\n\r\n* Simplify config flow code.\r\n\r\n* Spell fix.\r\n\r\n* Fix pylint warnings.\r\n\r\n* Simplify the code for config flow.\r\n\r\n* First attempt to implement import flows to suppport legacy YAML configurations.\r\n\r\n* Remove unnecessary log calls.\r\n\r\n* Wrap synchronous update call with `hass.async_add_executor_job`.\r\n\r\n* Import the YAML configurations when sensor platform is set up.\r\n\r\n* Move the logger call since the variables are not properly set up.\r\n\r\n* Add codeowner.\r\n\r\n* Fix name field of manifest.json.\r\n\r\n* Fix linting issue.\r\n\r\n* Fix incorrect dependency due to incorrect rebase.\r\n\r\n* Update codeowner and config flows via hassfest.\r\n\r\n* Postpone the deprecation warning to 2022.7.\r\n\r\n* Import future annotations for init file.\r\n\r\n* Add an newline at the end to make prettier happy.\r\n\r\n* Update github id.\r\n\r\n* Add type hints for return types of steps in config flow.\r\n\r\n* Move the deprecation date for YAML config to 2022.12.\r\n\r\n* Update according to reviews.\r\n\r\n* Use async_forward_entry_setups.\r\n\r\n* Add helper properties to `APCUPSdData` class.\r\n\r\n* Add device_info for binary sensor.\r\n\r\n* Simplify config flow.\r\n\r\n* Remove options flow strings.\r\n\r\n* update the tests according to the changes.\r\n\r\n* Add `entity_registry_enabled_default` to entities and use imported CONF_RESOURCES to disable entities instead of skipping them.\r\n\r\n* Update according to reviews.\r\n\r\n* Do not use model of the UPS as the title for the integration.\r\n\r\nInstead, simply use \"APCUPSd\" as the integration title and let the device info serve as title for each device instead.\r\n\r\n* Change schema to be a global variable.\r\n\r\n* Add more comments.\r\n\r\n* Rewrite the tests for config flows.\r\n\r\n* Fix enabled_by_default.\r\n\r\n* Show friendly titles in the integration.\r\n\r\n* Add import check in `async_setup_platform` to avoid importing in sensor platform setup.\r\n\r\n* Add import check in `async_setup_platform` to avoid importing in sensor platform setup.\r\n\r\n* Update comments in test files.\r\n\r\n* Use parametrize instead of manually iterating different test cases.\r\n\r\n* Swap the order of the platform constants.\r\n\r\n* Avoid using broad exceptions.\r\n\r\n* Set up device info via `_attr_device_info`.\r\n\r\n* Remove unrelated test in `test_config_flow`.\r\n\r\n* Use `DeviceInfo` instead of dict to assign to `_attr_device_info`.\r\n\r\n* Add english translation.\r\n\r\n* Add `async_create_issue` for deprecated YAML configuration.\r\n\r\n* Enable UPS status by default since it could show \"online, charging, on battery etc\" which is meaningful for all users.\r\n\r\n* Apply suggestions from code review\r\n\r\n* Apply suggestion\r\n\r\n* Apply suggestion\r\n\r\nCo-authored-by: Martin Hjelmare ", "code": "def statflag(self) -> str | None:\n \n return self.status.get(\"STATFLAG\")\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 22, "n_words": 8, "vocab_size": 8, "complexity": 1, "nloc": 3, "token_counts": 19, "n_ast_nodes": 35, "n_identifiers": 5 }, { "id": 276924, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/utils/io_utils.py", "file_name": "io_utils.py", "fun_name": "enable_interactive_logging", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def enable_interactive_logging():\n \n INTERACTIVE_LOGGING.enable = True\n\n\n@keras_export(\"keras.utils.disable_interactive_logging\")", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.utils.disable_interactive_logging\")", "n_ast_errors": 1, "ast_levels": 7, "n_whitespaces": 11, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 2, "token_counts": 10, "n_ast_nodes": 31, "n_identifiers": 4 }, { "id": 269372, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/applications/efficientnet_v2.py", "file_name": "efficientnet_v2.py", "fun_name": "preprocess_input", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def preprocess_input(x, data_format=None): # pylint: disable=unused-argument\n \n return x\n\n\n@keras_export(\"keras.applications.efficientnet_v2.decode_predictions\")", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.applications.efficientnet_v2.decode_predictions\")", "n_ast_errors": 1, "ast_levels": 7, "n_whitespaces": 15, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 2, "token_counts": 12, "n_ast_nodes": 33, "n_identifiers": 4 }, { "id": 38439, "commit_id": "e730e1256732b5dfeae2bdd427beacc3fbc20e2a", "repo": "transformers", "path": "examples/research_projects/codeparrot/scripts/preprocessing.py", "file_name": "preprocessing.py", "fun_name": "is_config_or_test", "commit_message": "Update codeparrot data preprocessing (#16944)\n\n* add new preprocessing arguments\r\n\r\n* add new filters\r\n\r\n* add new filters to readme\r\n\r\n* fix config and test count, update function names and docstrings\r\n\r\n* reformat code\r\n\r\n* update readme\r\n\r\n* Update readme\r\n\r\n* rename config_test filter\r\n\r\nCo-authored-by: Leandro von Werra \r\n\r\n* rename few_assignments filter\r\n\r\nCo-authored-by: Leandro von Werra \r\n\r\n* rename tokenizer in arguments\r\n\r\nCo-authored-by: Leandro von Werra \r\n\r\n* rename functions and add limit_line argument for config_test filter\r\n\r\n* update threshold for config_test filter\r\n\r\nCo-authored-by: Leandro von Werra \r\nCo-authored-by: Loubna ben allal ", "code": "def is_config_or_test(example, scan_width=5, coeff=0.05):\n \n\n keywords = [\"unit tests\", \"test file\", \"configuration file\"]\n lines = example[\"content\"].splitlines()\n count_config = 0\n count_test = 0\n # first test\n for _, line in zip(range(scan_width), lines):\n for keyword in keywords:\n if keyword in line.lower():\n return {\"config_or_test\": True}\n # second test\n nlines = example[\"content\"].count(\"\\n\")\n threshold = int(coeff * nlines)\n for line in lines:\n count_config += line.lower().count(\"config\")\n count_test += line.lower().count(\"test\")\n if count_config > threshold or count_test > threshold:\n return {\"config_or_test\": True}\n return {\"config_or_test\": False}\n\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 177, "n_words": 76, "vocab_size": 48, "complexity": 7, "nloc": 17, "token_counts": 145, "n_ast_nodes": 248, "n_identifiers": 19 }, { "id": 308879, "commit_id": "e222e1b6f05b630bef5aed73e307ca5072b6f286", "repo": "core", "path": "homeassistant/components/flux_led/number.py", "file_name": "number.py", "fun_name": "_async_set_value", "commit_message": "Add device configuration entities to flux_led (#62786)\n\nCo-authored-by: Chris Talkington ", "code": "async def _async_set_value(self) -> None:\n \n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 12, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 2, "token_counts": 8, "n_ast_nodes": 17, "n_identifiers": 2 }, { "id": 209511, "commit_id": "08b1f9d67c8e716fd44036a027bdc90dcb9fcfdf", "repo": "scapy", "path": "scapy/contrib/http2.py", "file_name": "http2.py", "fun_name": "_parse_multi_byte", "commit_message": "E275 - Missing whitespace after keyword (#3711)\n\nCo-authored-by: Alexander Aring \r\nCo-authored-by: Anmol Sarma \r\nCo-authored-by: antoine.torre \r\nCo-authored-by: Antoine Vacher \r\nCo-authored-by: Arnaud Ebalard \r\nCo-authored-by: atlowl <86038305+atlowl@users.noreply.github.com>\r\nCo-authored-by: Brian Bienvenu \r\nCo-authored-by: Chris Packham \r\nCo-authored-by: CQ \r\nCo-authored-by: Daniel Collins \r\nCo-authored-by: Federico Maggi \r\nCo-authored-by: Florian Maury \r\nCo-authored-by: _Frky <3105926+Frky@users.noreply.github.com>\r\nCo-authored-by: g-mahieux <37588339+g-mahieux@users.noreply.github.com>\r\nCo-authored-by: gpotter2 \r\nCo-authored-by: Guillaume Valadon \r\nCo-authored-by: Hao Zheng \r\nCo-authored-by: Haresh Khandelwal \r\nCo-authored-by: Harri Hämäläinen \r\nCo-authored-by: hecke \r\nCo-authored-by: Jan Romann \r\nCo-authored-by: Jan Sebechlebsky \r\nCo-authored-by: jdiog0 <43411724+jdiog0@users.noreply.github.com>\r\nCo-authored-by: jockque <38525640+jockque@users.noreply.github.com>\r\nCo-authored-by: Julien Bedel <30991560+JulienBedel@users.noreply.github.com>\r\nCo-authored-by: Keith Scott \r\nCo-authored-by: Kfir Gollan \r\nCo-authored-by: Lars Munch \r\nCo-authored-by: ldp77 <52221370+ldp77@users.noreply.github.com>\r\nCo-authored-by: Leonard Crestez \r\nCo-authored-by: Marcel Patzlaff \r\nCo-authored-by: Martijn Thé \r\nCo-authored-by: Martine Lenders \r\nCo-authored-by: Michael Farrell \r\nCo-authored-by: Michał Mirosław \r\nCo-authored-by: mkaliszan \r\nCo-authored-by: mtury \r\nCo-authored-by: Neale Ranns \r\nCo-authored-by: Octavian Toader \r\nCo-authored-by: Peter Eisenlohr \r\nCo-authored-by: Phil \r\nCo-authored-by: Pierre Lalet \r\nCo-authored-by: Pierre Lorinquer \r\nCo-authored-by: piersoh <42040737+piersoh@users.noreply.github.com>\r\nCo-authored-by: plorinquer \r\nCo-authored-by: pvinci \r\nCo-authored-by: Rahul Jadhav \r\nCo-authored-by: Robin Jarry \r\nCo-authored-by: romain-perez <51962832+romain-perez@users.noreply.github.com>\r\nCo-authored-by: rperez \r\nCo-authored-by: Sabrina Dubroca \r\nCo-authored-by: Sebastian Baar \r\nCo-authored-by: sebastien mainand \r\nCo-authored-by: smehner1 \r\nCo-authored-by: speakinghedge \r\nCo-authored-by: Steven Van Acker \r\nCo-authored-by: Thomas Faivre \r\nCo-authored-by: Tran Tien Dat \r\nCo-authored-by: Wael Mahlous \r\nCo-authored-by: waeva <74464394+waeva@users.noreply.github.com>\r\n\r\nCo-authored-by: Alexander Aring \r\nCo-authored-by: Anmol Sarma \r\nCo-authored-by: antoine.torre \r\nCo-authored-by: Antoine Vacher \r\nCo-authored-by: Arnaud Ebalard \r\nCo-authored-by: atlowl <86038305+atlowl@users.noreply.github.com>\r\nCo-authored-by: Brian Bienvenu \r\nCo-authored-by: Chris Packham \r\nCo-authored-by: CQ \r\nCo-authored-by: Daniel Collins \r\nCo-authored-by: Federico Maggi \r\nCo-authored-by: Florian Maury \r\nCo-authored-by: _Frky <3105926+Frky@users.noreply.github.com>\r\nCo-authored-by: g-mahieux <37588339+g-mahieux@users.noreply.github.com>\r\nCo-authored-by: gpotter2 \r\nCo-authored-by: Guillaume Valadon \r\nCo-authored-by: Hao Zheng \r\nCo-authored-by: Haresh Khandelwal \r\nCo-authored-by: Harri Hämäläinen \r\nCo-authored-by: hecke \r\nCo-authored-by: Jan Romann \r\nCo-authored-by: Jan Sebechlebsky \r\nCo-authored-by: jdiog0 <43411724+jdiog0@users.noreply.github.com>\r\nCo-authored-by: jockque <38525640+jockque@users.noreply.github.com>\r\nCo-authored-by: Julien Bedel <30991560+JulienBedel@users.noreply.github.com>\r\nCo-authored-by: Keith Scott \r\nCo-authored-by: Kfir Gollan \r\nCo-authored-by: Lars Munch \r\nCo-authored-by: ldp77 <52221370+ldp77@users.noreply.github.com>\r\nCo-authored-by: Leonard Crestez \r\nCo-authored-by: Marcel Patzlaff \r\nCo-authored-by: Martijn Thé \r\nCo-authored-by: Martine Lenders \r\nCo-authored-by: Michael Farrell \r\nCo-authored-by: Michał Mirosław \r\nCo-authored-by: mkaliszan \r\nCo-authored-by: mtury \r\nCo-authored-by: Neale Ranns \r\nCo-authored-by: Octavian Toader \r\nCo-authored-by: Peter Eisenlohr \r\nCo-authored-by: Phil \r\nCo-authored-by: Pierre Lalet \r\nCo-authored-by: Pierre Lorinquer \r\nCo-authored-by: piersoh <42040737+piersoh@users.noreply.github.com>\r\nCo-authored-by: pvinci \r\nCo-authored-by: Rahul Jadhav \r\nCo-authored-by: Robin Jarry \r\nCo-authored-by: romain-perez <51962832+romain-perez@users.noreply.github.com>\r\nCo-authored-by: rperez \r\nCo-authored-by: Sabrina Dubroca \r\nCo-authored-by: Sebastian Baar \r\nCo-authored-by: sebastien mainand \r\nCo-authored-by: smehner1 \r\nCo-authored-by: Steven Van Acker \r\nCo-authored-by: Thomas Faivre \r\nCo-authored-by: Tran Tien Dat \r\nCo-authored-by: Wael Mahlous \r\nCo-authored-by: waeva <74464394+waeva@users.noreply.github.com>", "code": "def _parse_multi_byte(self, s):\n # type: (str) -> int\n \n\n assert len(s) >= 2\n\n tmp_len = len(s)\n\n value = 0\n i = 1\n byte = orb(s[i])\n # For CPU sake, stops at an arbitrary large number!\n max_value = 1 << 64\n # As long as the MSG is set, an another byte must be read\n while byte & 0x80:\n value += (byte ^ 0x80) << (7 * (i - 1))\n if value > max_value:\n raise error.Scapy_Exception(\n 'out-of-bound value: the string encodes a value that is too large (>2^{{64}}): {}'.format(value) # noqa: E501\n )\n i += 1\n assert i < tmp_len, 'EINVAL: x: out-of-bound read: the string ends before the AbstractUVarIntField!' # noqa: E501\n byte = orb(s[i])\n value += byte << (7 * (i - 1))\n value += self._max_value\n\n assert value >= 0\n return value\n", "url": "https://github.com/secdev/scapy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 343, "n_words": 132, "vocab_size": 83, "complexity": 3, "nloc": 20, "token_counts": 125, "n_ast_nodes": 202, "n_identifiers": 14 }, { "id": 300199, "commit_id": "5e737bfe4fbc5a724f5fdf04ea9319c2224cb114", "repo": "core", "path": "tests/components/ws66i/test_media_player.py", "file_name": "test_media_player.py", "fun_name": "test_service_calls_with_all_entities", "commit_message": "Add ws66i core integration (#56094)\n\n* Add ws66i core integration\r\n\r\n* Remove all ws66i translations\r\n\r\n* Update ws66i unit tests to meet minimum code coverage\r\n\r\n* Update ws66i based on @bdraco review\r\n\r\n* General improvements after 2nd PR review\r\n\r\n* Disable entities if amp shutoff, set default source names, set 30sec polling\r\n\r\n* Add _attr_ and change async_on_unload\r\n\r\n* Improve entity generation\r\n\r\n* Implement coordinator\r\n\r\n* Made options fields required, retry connection on failed attempts, use ZoneStatus for attributes\r\n\r\n* Refactor WS66i entity properties, raise HomeAssistantError on restore service if no snapshot\r\n\r\n* Update to pyws66i v1.1\r\n\r\n* Add quality scale of silver to manifest\r\n\r\n* Update config_flow test", "code": "async def test_service_calls_with_all_entities(hass):\n \n _ = await _setup_ws66i_with_options(hass, MockWs66i())\n\n # Changing media player to new state\n await _call_media_player_service(\n hass, SERVICE_VOLUME_SET, {\"entity_id\": ZONE_1_ID, \"volume_level\": 0.0}\n )\n await _call_media_player_service(\n hass, SERVICE_SELECT_SOURCE, {\"entity_id\": ZONE_1_ID, \"source\": \"one\"}\n )\n\n # Saving existing values\n await _call_ws66i_service(hass, SERVICE_SNAPSHOT, {\"entity_id\": \"all\"})\n\n # Changing media player to new state\n await _call_media_player_service(\n hass, SERVICE_VOLUME_SET, {\"entity_id\": ZONE_1_ID, \"volume_level\": 1.0}\n )\n await _call_media_player_service(\n hass, SERVICE_SELECT_SOURCE, {\"entity_id\": ZONE_1_ID, \"source\": \"three\"}\n )\n\n # await coordinator.async_refresh()\n # await hass.async_block_till_done()\n\n # Restoring media player to its previous state\n await _call_ws66i_service(hass, SERVICE_RESTORE, {\"entity_id\": \"all\"})\n await hass.async_block_till_done()\n\n state = hass.states.get(ZONE_1_ID)\n\n assert state.attributes[ATTR_MEDIA_VOLUME_LEVEL] == 0.0\n assert state.attributes[ATTR_INPUT_SOURCE] == \"one\"\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 193, "n_words": 99, "vocab_size": 47, "complexity": 1, "nloc": 20, "token_counts": 151, "n_ast_nodes": 255, "n_identifiers": 19 }, { "id": 110678, "commit_id": "ec60128011c1009313e0c24b1dfc89313b2d1b59", "repo": "matplotlib", "path": "lib/matplotlib/animation.py", "file_name": "animation.py", "fun_name": "to_jshtml", "commit_message": "Deprecate attributes and expire deprecation in animation", "code": "def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):\n \n if fps is None and hasattr(self, '_interval'):\n # Convert interval in ms to frames per second\n fps = 1000 / self._interval\n\n # If we're not given a default mode, choose one base on the value of\n # the _repeat attribute\n if default_mode is None:\n default_mode = 'loop' if getattr(self, '_repeat',\n False) else 'once'\n\n if not hasattr(self, \"_html_representation\"):\n # Can't open a NamedTemporaryFile twice on Windows, so use a\n # TemporaryDirectory instead.\n with TemporaryDirectory() as tmpdir:\n path = Path(tmpdir, \"temp.html\")\n writer = HTMLWriter(fps=fps,\n embed_frames=embed_frames,\n default_mode=default_mode)\n self.save(str(path), writer=writer)\n self._html_representation = path.read_text()\n\n return self._html_representation\n", "url": "https://github.com/matplotlib/matplotlib.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 385, "n_words": 96, "vocab_size": 75, "complexity": 6, "nloc": 15, "token_counts": 122, "n_ast_nodes": 206, "n_identifiers": 18 }, { "id": 60417, "commit_id": "cc4d0564756ca067516f71718a3d135996525909", "repo": "transferlearning", "path": "code/deep/BJMMD/caffe/scripts/cpp_lint.py", "file_name": "cpp_lint.py", "fun_name": "CheckForBadCharacters", "commit_message": "Balanced joint maximum mean discrepancy for deep transfer learning", "code": "def CheckForBadCharacters(filename, lines, error):\n \n for linenum, line in enumerate(lines):\n if u'\\ufffd' in line:\n error(filename, linenum, 'readability/utf8', 5,\n 'Line contains invalid UTF-8 (or Unicode replacement character).')\n if '\\0' in line:\n error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')\n\n", "url": "https://github.com/jindongwang/transferlearning.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 66, "n_words": 37, "vocab_size": 27, "complexity": 4, "nloc": 7, "token_counts": 55, "n_ast_nodes": 91, "n_identifiers": 7 }, { "id": 69222, "commit_id": "58d430fe3ee62e93ad8d16a08bb42156a25b7d41", "repo": "erpnext", "path": "erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py", "file_name": "test_asset_capitalization.py", "fun_name": "get_actual_gle_dict", "commit_message": "feat: Asset Capitalization\n- manual selection of entry type\n- GLE cleanup with smaller functions\n- GLE considering periodical inventory\n- test cases", "code": "def get_actual_gle_dict(name):\n\treturn dict(\n\t\tfrappe.db.sql(\n\t\t\t,\n\t\t\tname,\n\t\t)\n\t)\n\n", "url": "https://github.com/frappe/erpnext.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 2, "n_words": 9, "vocab_size": 8, "complexity": 1, "nloc": 13, "token_counts": 20, "n_ast_nodes": 33, "n_identifiers": 6 }, { "id": 106001, "commit_id": "832780ac40e3bfb0e15336cc9eca894c1da4158f", "repo": "datasets", "path": "src/datasets/download/streaming_download_manager.py", "file_name": "streaming_download_manager.py", "fun_name": "extract", "commit_message": "Fix description of streaming in the docs (#5313)\n\n* fix streaming description in stream section\r\n\r\n* fix audio docs\r\n\r\n* change docstrings for streaming download manager\r\n\r\n* Apply suggestions from code review\r\n\r\n* all urls -> URL(s), correct return types\r\n\r\nCo-authored-by: Quentin Lhoest <42851186+lhoestq@users.noreply.github.com>\r\nCo-authored-by: Albert Villanova del Moral <8515462+albertvillanova@users.noreply.github.com>", "code": "def extract(self, url_or_urls):\n \n urlpaths = map_nested(self._extract, url_or_urls, map_tuple=True)\n return urlpaths\n", "url": "https://github.com/huggingface/datasets.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 31, "n_words": 10, "vocab_size": 9, "complexity": 1, "nloc": 3, "token_counts": 24, "n_ast_nodes": 38, "n_identifiers": 7 }, { "id": 26744, "commit_id": "5763cb1ad22b84e29a270b9b0b365f32074b753d", "repo": "saleor", "path": "saleor/graphql/core/utils/__init__.py", "file_name": "__init__.py", "fun_name": "validate_image_file", "commit_message": "Save images to product media from external URLs (#9329)\n\n* Save images to product media from external URLs", "code": "def validate_image_file(file, field_name, error_class) -> None:\n \n if not file:\n raise ValidationError(\n {\n field_name: ValidationError(\n \"File is required.\", code=error_class.REQUIRED\n )\n }\n )\n if not is_image_mimetype(file.content_type):\n raise ValidationError(\n {\n field_name: ValidationError(\n \"Invalid file type.\", code=error_class.INVALID\n )\n }\n )\n _validate_image_format(file, field_name, error_class)\n\n", "url": "https://github.com/saleor/saleor.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 221, "n_words": 39, "vocab_size": 25, "complexity": 3, "nloc": 19, "token_counts": 69, "n_ast_nodes": 111, "n_identifiers": 11 }, { "id": 216133, "commit_id": "b677222e9e5031afc2e3962247af5d4adfc91cbe", "repo": "salt", "path": "tests/pytests/unit/output/test_highstate.py", "file_name": "test_highstate.py", "fun_name": "test__compress_ids_multiple_module_functions", "commit_message": "handle compressing multiple mod.fun combos under an id", "code": "def test__compress_ids_multiple_module_functions():\n \n # raw data entering the outputter\n data = {\n \"local\": {\n \"cmd_|-try_this_|-echo 'hi'_|-run\": {\n \"__id__\": \"try_this\",\n \"__run_num__\": 1,\n \"__sls__\": \"wayne\",\n \"changes\": {\"pid\": 32615, \"retcode\": 0, \"stderr\": \"\", \"stdout\": \"hi\"},\n \"comment\": 'Command \"echo ' \"'hi'\\\" run\",\n \"duration\": 8.218,\n \"name\": \"echo 'hi'\",\n \"result\": True,\n \"start_time\": \"23:43:25.715842\",\n },\n \"test_|-try_this_|-asdf_|-nop\": {\n \"__id__\": \"try_this\",\n \"__run_num__\": 0,\n \"__sls__\": \"wayne\",\n \"changes\": {},\n \"comment\": \"Success!\",\n \"duration\": 0.906,\n \"name\": \"asdf\",\n \"result\": True,\n \"start_time\": \"23:43:25.714010\",\n },\n }\n }\n\n # check output text for formatting\n opts = copy.deepcopy(highstate.__opts__)\n opts[\"state_compress_ids\"] = True\n with patch(\"salt.output.highstate.__opts__\", opts, create=True):\n actual_output = highstate.output(data)\n\n # if we only cared about the ID/SLS/Result combo, this would be 4 not 2\n assert \"Succeeded: 2 (changed=1)\" in actual_output\n assert \"Failed: 0\" in actual_output\n assert \"Total states run: 2\" in actual_output\n", "url": "https://github.com/saltstack/salt.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 500, "n_words": 122, "vocab_size": 88, "complexity": 1, "nloc": 34, "token_counts": 165, "n_ast_nodes": 319, "n_identifiers": 11 }, { "id": 241549, "commit_id": "e9009d60588306b48a2931bf304a493c468c6740", "repo": "lightning", "path": "pytorch_lightning/loops/epoch/training_epoch_loop.py", "file_name": "training_epoch_loop.py", "fun_name": "reset", "commit_message": "Reset the total fit-validation batch progress on epoch (#11244)", "code": "def reset(self) -> None:\n \n if self.restarting:\n self.batch_progress.reset_on_restart()\n self.scheduler_progress.reset_on_restart()\n self.batch_loop.optimizer_loop.optim_progress.reset_on_restart()\n else:\n self.batch_progress.reset_on_run()\n self.scheduler_progress.reset_on_run()\n self.batch_loop.optimizer_loop.optim_progress.reset_on_run()\n # when the epoch starts, the total val batch progress should be reset as it's supposed to count the batches\n # seen per epoch, this is useful for tracking when validation is run multiple times per epoch\n self.val_loop.epoch_loop.batch_progress.total.reset()\n\n self._outputs = []\n", "url": "https://github.com/Lightning-AI/lightning.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 181, "n_words": 54, "vocab_size": 47, "complexity": 2, "nloc": 12, "token_counts": 84, "n_ast_nodes": 145, "n_identifiers": 14 }, { "id": 214475, "commit_id": "4b61c1f4b2e2d67fbda22eb01af78ffa23a15ab7", "repo": "flair", "path": "flair/datasets/sequence_labeling.py", "file_name": "sequence_labeling.py", "fun_name": "__len__", "commit_message": "feat: :sparkles: initial implementation of JsonlCorpora and Datasets", "code": "def __len__(self):\n \n return len(self.sentences)\n", "url": "https://github.com/flairNLP/flair.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 18, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 13, "n_ast_nodes": 24, "n_identifiers": 4 }, { "id": 281141, "commit_id": "ea964109d654394cc0a5237e6ec5510ba6404097", "repo": "OpenBBTerminal", "path": "tests/gamestonk_terminal/cryptocurrency/test_cryptocurrency_helpers.py", "file_name": "test_cryptocurrency_helpers.py", "fun_name": "test_coin_api_load_df_for_ta", "commit_message": "Crypto menu refactor (#1119)\n\n* enabled some crypto commands in dd to be called independent of source loaded\r\n\r\n* support for coin_map_df in all dd functions + load ta and plot chart refactor\r\n\r\n* updated tests and removed coingecko scrapping where possible\r\n\r\n* removed ref of command from hugo\r\n\r\n* updated pycoingecko version\r\n\r\n* refactoring load\r\n\r\n* refactored load to fetch prices; pred can run independent of source now\r\n\r\n* load by default usd on cp/cg and usdt on cb/bin\r\n\r\n* updated to rich for formatting and updated dependencies\r\n\r\n* fixed changes requested\r\n\r\n* update docs\r\n\r\n* revert discord requirements\r\n\r\n* removed absolute from calculate change for price\r\n\r\n* fixing pr issues\r\n\r\n* fix loading issue when similar coins exist, move coins to home, fill n/a\r\n\r\n* update docs for coins\r\n\r\n* adds load to ta and pred menu", "code": "def test_coin_api_load_df_for_ta(self, mock_load):\n \n\n with open(\n \"tests/gamestonk_terminal/cryptocurrency/json/test_cryptocurrency_helpers/btc_usd_test_data.json\",\n encoding=\"utf8\",\n ) as f:\n sample_return = json.load(f)\n\n mock_load.return_value = sample_return\n mock_return, vs = load_ta_data(\n coin_map_df=self.coin_map_df,\n source=\"cg\",\n currency=\"usd\",\n days=30,\n )\n self.assertTrue(mock_return.shape == (31, 4))\n self.assertTrue(vs == \"usd\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 165, "n_words": 32, "vocab_size": 27, "complexity": 1, "nloc": 15, "token_counts": 81, "n_ast_nodes": 137, "n_identifiers": 19 }, { "id": 315206, "commit_id": "273e9b287f482f5d1f0718ebf09a56c49c66513d", "repo": "core", "path": "homeassistant/components/soundtouch/config_flow.py", "file_name": "config_flow.py", "fun_name": "async_step_zeroconf", "commit_message": "Add config flow for Bose SoundTouch (#72967)\n\nCo-authored-by: Paulus Schoutsen ", "code": "async def async_step_zeroconf(self, discovery_info):\n \n self.host = discovery_info.host\n\n try:\n await self._async_get_device_id()\n except RequestException:\n return self.async_abort(reason=\"cannot_connect\")\n\n self.context[\"title_placeholders\"] = {\"name\": self.name}\n return await self.async_step_zeroconf_confirm()\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 85, "n_words": 21, "vocab_size": 18, "complexity": 2, "nloc": 8, "token_counts": 56, "n_ast_nodes": 100, "n_identifiers": 11 }, { "id": 19887, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_internal/exceptions.py", "file_name": "exceptions.py", "fun_name": "_requirement_name", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def _requirement_name(self) -> str:\n \n return str(self.req) if self.req else \"unknown package\"\n\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 25, "n_words": 11, "vocab_size": 11, "complexity": 2, "nloc": 8, "token_counts": 21, "n_ast_nodes": 37, "n_identifiers": 4 }, { "id": 288291, "commit_id": "31ddf6cc31aaaf08a09cd6afa9eb830450d1817d", "repo": "core", "path": "homeassistant/components/waze_travel_time/helpers.py", "file_name": "helpers.py", "fun_name": "is_valid_config_entry", "commit_message": "Log config_flow errors for waze_travel_time (#79352)", "code": "def is_valid_config_entry(hass, origin, destination, region):\n \n origin = find_coordinates(hass, origin)\n destination = find_coordinates(hass, destination)\n try:\n WazeRouteCalculator(origin, destination, region).calc_all_routes_info()\n except WRCError as error:\n _LOGGER.error(\"Error trying to validate entry: %s\", error)\n return False\n return True\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 71, "n_words": 32, "vocab_size": 28, "complexity": 2, "nloc": 9, "token_counts": 59, "n_ast_nodes": 94, "n_identifiers": 11 }, { "id": 281055, "commit_id": "eb0dde4603468f64c5d99c57bd272816062e6a23", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/jupyter/jupyter_controller.py", "file_name": "jupyter_controller.py", "fun_name": "call_dashboards", "commit_message": "Refactored Reports (#1123)\n\n* First working program\r\n\r\n* added Voila support\r\n\r\n* Attempt to fix requirements\r\n\r\n* Revert depen\r\n\r\n* Another dependency test\r\n\r\n* Fixed errors\r\n\r\n* Small changes\r\n\r\n* Fixed help\r\n\r\n* Added port warning\r\n\r\n* Fixed continued terminal use\r\n\r\n* Last change, we good fam\r\n\r\n* Added placeholder so we can have stored\r\n\r\n* Didier changes\r\n\r\n* Fixed exit\r\n\r\n* Fixed issue", "code": "def call_dashboards(self, _):\n \n from gamestonk_terminal.jupyter.dashboards import dashboards_controller\n\n self.queue = dashboards_controller.menu(self.queue)\n\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 31, "n_words": 10, "vocab_size": 10, "complexity": 1, "nloc": 3, "token_counts": 28, "n_ast_nodes": 45, "n_identifiers": 9 }, { "id": 90379, "commit_id": "af66ec160dda84b9d417295a5586a530f422511d", "repo": "sentry", "path": "tests/snuba/api/endpoints/test_organization_sessions.py", "file_name": "test_organization_sessions.py", "fun_name": "test_order_by", "commit_message": "feat(api): Sort sessions by release timestamp [TET-7] (#34699)\n\nThis PR adds the ability to sort by release timestamp in sessions v2 over metrics\r\nEssentially it:\r\n\r\nRuns a pre-flight query to Release model according to ordering of release timestamp whether ASC or DESC and gets the resulting release groups. It also adds environment filters to the pre flight query if environment filters are sent in the query param of the request\r\nFetches those groups and uses them as a filter in subsequent metrics queries\r\nFormats the output so if groups are present in the Release model but not in the metrics dataset, those groups still exist but are nulled out in the output. Otherwise, it shows the results of the groups in the metrics dataset.\r\nOrders the output according to resulting groups from preflight query", "code": "def test_order_by(self):\n \n # Step 1: Create 3 releases\n release1b = self.create_release(version=\"1B\")\n release1c = self.create_release(version=\"1C\")\n release1d = self.create_release(version=\"1D\")\n\n # Step 2: Create crash free rate for each of those releases\n # Release 1c -> 66.7% Crash free rate\n for _ in range(0, 2):\n self.store_session(make_session(self.project, release=release1c.version))\n self.store_session(make_session(self.project, release=release1c.version, status=\"crashed\"))\n\n # Release 1b -> 33.3% Crash free rate\n for _ in range(0, 2):\n self.store_session(\n make_session(self.project, release=release1b.version, status=\"crashed\")\n )\n self.store_session(make_session(self.project, release=release1b.version))\n\n # Create Sessions in each of these releases\n # Release 1d -> 80% Crash free rate\n for _ in range(0, 4):\n self.store_session(make_session(self.project, release=release1d.version))\n self.store_session(make_session(self.project, release=release1d.version, status=\"crashed\"))\n\n # Step 3: Make request\n response = self.do_request(\n {\n \"project\": self.project.id, # project without users\n \"statsPeriod\": \"1d\",\n \"interval\": \"1d\",\n \"field\": [\"crash_free_rate(session)\"],\n \"groupBy\": [\"release\"],\n \"orderBy\": \"-release.timestamp\",\n \"per_page\": 3,\n }\n )\n # Step 4: Validate Results\n assert response.data[\"groups\"] == [\n {\n \"by\": {\"release\": \"1D\"},\n \"totals\": {\"crash_free_rate(session)\": 0.8},\n \"series\": {\"crash_free_rate(session)\": [0.8]},\n },\n {\n \"by\": {\"release\": \"1C\"},\n \"totals\": {\"crash_free_rate(session)\": 0.6666666666666667},\n \"series\": {\"crash_free_rate(session)\": [0.6666666666666667]},\n },\n {\n \"by\": {\"release\": \"1B\"},\n \"totals\": {\"crash_free_rate(session)\": 0.33333333333333337},\n \"series\": {\"crash_free_rate(session)\": [0.33333333333333337]},\n },\n ]\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 707, "n_words": 165, "vocab_size": 97, "complexity": 4, "nloc": 43, "token_counts": 334, "n_ast_nodes": 560, "n_identifiers": 18 }, { "id": 283018, "commit_id": "ede6ec8b1a0dda6c85e81084922c7be80765cd43", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/forex/technical_analysis/ta_controller.py", "file_name": "ta_controller.py", "fun_name": "print_help", "commit_message": "Add TA and test coverage for the Forex context (#1532)\n\n* Add technical analysis to forex menu\r\n\r\n* Remove \"stock\" and \"$\" from the common ta charts\r\n\r\n* Add tests for forex context\r\n\r\n* Update forex custom reset functions\r\n\r\n* Remove -t arg (ticker) insertion into other_args in forex controller\r\n\r\n* Remove excluded command from forex ta help string\r\n\r\n* Update test data\r\n\r\nCo-authored-by: didierlopes.eth ", "code": "def print_help(self):\n \n currency_str = f\" {self.ticker} (from {self.start.strftime('%Y-%m-%d')})\"\n help_text = f\n console.print(text=help_text, menu=\"Forex - Technical Analysis\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 44, "n_words": 16, "vocab_size": 15, "complexity": 1, "nloc": 26, "token_counts": 26, "n_ast_nodes": 75, "n_identifiers": 11 }, { "id": 195194, "commit_id": "b1acb681207559da56a787ba96e16f0e23697d92", "repo": "ParlAI", "path": "projects/bb3/agents/module.py", "file_name": "module.py", "fun_name": "r2c2_prompt", "commit_message": "Patch 8322 (#4709)\n\n* add dafetymix teacher\r\n\r\n* safety_mix teacher\r\n\r\n* safety_mix teacher pos and neg teachers\r\n\r\n* add tests for teacher\r\n\r\n* add license info\r\n\r\n* improvement\r\n\r\n* add task list\r\n\r\n* add task list and lint\r\n\r\n* add init.py\r\n\r\n* adding some patch to director\r\n\r\n* seeker changes\r\n\r\n* th\r\n\r\n* 3\r\n\r\n* jing\r\n\r\n* changes\r\n\r\n* z and r\r\n\r\n* remove .opts\r\n\r\n* fix docs\r\n\r\n* add contrractions\r\n\r\n* lint\r\n\r\nCo-authored-by: Dexter Ju \r\nCo-authored-by: Jing Xu ", "code": "def r2c2_prompt(self):\n \n return {\n 'sdm': CONST.IS_SEARCH_REQUIRED,\n 'mdm': CONST.IS_MEMORY_REQUIRED,\n 'sgm': CONST.GENERATE_QUERY,\n 'mgm': CONST.GENERATE_MEMORY,\n 'mkm': CONST.ACCESS_MEMORY,\n 'ckm': CONST.EXTRACT_ENTITY,\n 'skm': CONST.GENERATE_KNOWLEDGE,\n 'mrm': '',\n 'crm': '',\n 'srm': '',\n 'vrm': '',\n 'grm': '',\n 'orm': '',\n }[self.value]\n", "url": "https://github.com/facebookresearch/ParlAI.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 195, "n_words": 31, "vocab_size": 26, "complexity": 1, "nloc": 16, "token_counts": 80, "n_ast_nodes": 149, "n_identifiers": 11 }, { "id": 260765, "commit_id": "7c835d550c1dcaf44938b1c285db017a773d7dba", "repo": "scikit-learn", "path": "sklearn/feature_extraction/text.py", "file_name": "text.py", "fun_name": "partial_fit", "commit_message": "MAINT Add parameter validation to `HashingVectorizer`. (#24181)\n\nCo-authored-by: jeremie du boisberranger ", "code": "def partial_fit(self, X, y=None):\n \n # TODO: only validate during the first call\n self._validate_params()\n return self\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 43, "n_words": 15, "vocab_size": 15, "complexity": 1, "nloc": 3, "token_counts": 19, "n_ast_nodes": 33, "n_identifiers": 5 }, { "id": 43671, "commit_id": "e9226139c2727a4754d734f19ec625c4d23028b3", "repo": "airflow", "path": "airflow/decorators/task_group.py", "file_name": "task_group.py", "fun_name": "task_group", "commit_message": "Map and Partial DAG authoring interface for Dynamic Task Mapping (#19965)\n\n* Make DAGNode a proper Abstract Base Class\n\n* Prevent mapping an already mapped Task/TaskGroup\n\nAlso prevent calls like .partial(...).partial(...). It is uncertain\nwhether these kinds of repeated partial/map calls have utility, so let's\ndisable them entirely for now to simplify implementation. We can always\nadd them if they are proven useful.\n\nCo-authored-by: Tzu-ping Chung ", "code": "def task_group(python_callable=None, *tg_args, **tg_kwargs):\n \n if callable(python_callable):\n return TaskGroupDecorator(function=python_callable, kwargs=tg_kwargs)\n return cast(\"Callable[[T], T]\", functools.partial(TaskGroupDecorator, kwargs=tg_kwargs))\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 30, "n_words": 14, "vocab_size": 13, "complexity": 2, "nloc": 4, "token_counts": 47, "n_ast_nodes": 75, "n_identifiers": 11 }, { "id": 19350, "commit_id": "c6bdd48715adcbe17c4146b7cae3b0fc569f7bde", "repo": "PythonRobotics", "path": "ArmNavigation/arm_obstacle_navigation/arm_obstacle_navigation.py", "file_name": "arm_obstacle_navigation.py", "fun_name": "astar_torus", "commit_message": "docs: Fix a few typos (#695)\n\nThere are small typos in:\r\n- ArmNavigation/arm_obstacle_navigation/arm_obstacle_navigation.py\r\n- ArmNavigation/arm_obstacle_navigation/arm_obstacle_navigation_2.py\r\n- docs/modules/slam/FastSLAM1/FastSLAM1_main.rst\r\n- docs/modules/slam/ekf_slam/ekf_slam_main.rst\r\n\r\nFixes:\r\n- Should read `configuration` rather than `configuation`.\r\n- Should read `trajectory` rather than `tracjectory`.\r\n- Should read `prediction` rather than `prediciton`.\r\n\r\nSigned-off-by: Tim Gates ", "code": "def astar_torus(grid, start_node, goal_node):\n \n colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']\n levels = [0, 1, 2, 3, 4, 5, 6, 7]\n cmap, norm = from_levels_and_colors(levels, colors)\n\n grid[start_node] = 4\n grid[goal_node] = 5\n\n parent_map = [[() for _ in range(M)] for _ in range(M)]\n\n heuristic_map = calc_heuristic_map(M, goal_node)\n\n explored_heuristic_map = np.full((M, M), np.inf)\n distance_map = np.full((M, M), np.inf)\n explored_heuristic_map[start_node] = heuristic_map[start_node]\n distance_map[start_node] = 0\n while True:\n grid[start_node] = 4\n grid[goal_node] = 5\n\n current_node = np.unravel_index(\n np.argmin(explored_heuristic_map, axis=None), explored_heuristic_map.shape)\n min_distance = np.min(explored_heuristic_map)\n if (current_node == goal_node) or np.isinf(min_distance):\n break\n\n grid[current_node] = 2\n explored_heuristic_map[current_node] = np.inf\n\n i, j = current_node[0], current_node[1]\n\n neighbors = find_neighbors(i, j)\n\n for neighbor in neighbors:\n if grid[neighbor] == 0 or grid[neighbor] == 5:\n distance_map[neighbor] = distance_map[current_node] + 1\n explored_heuristic_map[neighbor] = heuristic_map[neighbor]\n parent_map[neighbor[0]][neighbor[1]] = current_node\n grid[neighbor] = 3\n\n if np.isinf(explored_heuristic_map[goal_node]):\n route = []\n print(\"No route found.\")\n else:\n route = [goal_node]\n while parent_map[route[0][0]][route[0][1]] != ():\n route.insert(0, parent_map[route[0][0]][route[0][1]])\n\n print(\"The route found covers %d grid cells.\" % len(route))\n for i in range(1, len(route)):\n grid[route[i]] = 6\n plt.cla()\n # for stopping simulation with the esc key.\n plt.gcf().canvas.mpl_connect('key_release_event',\n lambda event: [exit(0) if event.key == 'escape' else None])\n plt.imshow(grid, cmap=cmap, norm=norm, interpolation=None)\n plt.show()\n plt.pause(1e-2)\n\n return route\n\n", "url": "https://github.com/AtsushiSakai/PythonRobotics.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 552, "n_words": 192, "vocab_size": 134, "complexity": 13, "nloc": 47, "token_counts": 475, "n_ast_nodes": 721, "n_identifiers": 49 }, { "id": 10180, "commit_id": "933415bfa1f9eb89f935037014dfed816eb9815d", "repo": "jina", "path": "tests/unit/flow-construct/test_flow_skip.py", "file_name": "test_flow_skip.py", "fun_name": "test_bad_flow_skip_handle_join", "commit_message": "feat: star routing (#3900)\n\n* feat(proto): adjust proto for star routing (#3844)\r\n\r\n* feat(proto): adjust proto for star routing\r\n\r\n* feat(proto): generate proto files\r\n\r\n* feat(grpc): refactor grpclet interface (#3846)\r\n\r\n* feat: refactor connection pool for star routing (#3872)\r\n\r\n* feat(k8s): add more labels to k8s deployments\r\n\r\n* feat(network): refactor connection pool\r\n\r\n* feat(network): refactor k8s pool\r\n\r\n* feat: star routing graph gateway (#3877)\r\n\r\n* feat: star routing - refactor grpc data runtime (#3887)\r\n\r\n* feat(runtimes): refactor grpc dataruntime\r\n\r\n* fix(tests): adapt worker runtime tests\r\n\r\n* fix(import): fix import\r\n\r\n* feat(proto): enable sending multiple lists (#3891)\r\n\r\n* feat: star routing gateway (#3893)\r\n\r\n* feat: star routing gateway all protocols (#3897)\r\n\r\n* test: add streaming and prefetch tests (#3901)\r\n\r\n* feat(head): new head runtime for star routing (#3899)\r\n\r\n* feat(head): new head runtime\r\n\r\n* feat(head): new head runtime\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(network): improve proto comments\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* feat(worker): merge docs in worker runtime (#3905)\r\n\r\n* feat(worker): merge docs in worker runtime\r\n\r\n* feat(tests): assert after clean up\r\n\r\n* feat(tests): star routing runtime integration tests (#3908)\r\n\r\n* fix(tests): fix integration tests\r\n\r\n* test: test runtimes fast slow request (#3910)\r\n\r\n* feat(zmq): purge zmq, zed, routing_table (#3915)\r\n\r\n* feat(zmq): purge zmq, zed, routing_table\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(zmq): adapt comment in dependency list\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix(tests): fix type tests\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* test: add test gateway to worker connection (#3921)\r\n\r\n* feat(pea): adapt peas for star routing (#3918)\r\n\r\n* feat(pea): adapt peas for star routing\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(pea): add tests\r\n\r\n* feat(tests): add failing head pea test\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* feat(tests): integration tests for peas (#3923)\r\n\r\n* feat(tests): integration tests for peas\r\n\r\n* feat(pea): remove _inner_pea function\r\n\r\n* feat: star routing container pea (#3922)\r\n\r\n* test: rescue tests (#3942)\r\n\r\n* fix: fix streaming tests (#3945)\r\n\r\n* refactor: move docker run to run (#3948)\r\n\r\n* feat: star routing pods (#3940)\r\n\r\n* feat(pod): adapt pods for star routing\r\n\r\n* feat(pods): adapt basepod to star routing\r\n\r\n* feat(pod): merge pod and compound pod\r\n\r\n* feat(tests): fix tests\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(test): add container pea int test\r\n\r\n* feat(ci): remove more unnecessary tests\r\n\r\n* fix(tests): remove jinad runtime\r\n\r\n* feat(ci): remove latency tracking\r\n\r\n* fix(ci): fix ci def\r\n\r\n* fix(runtime): enable runtime to be exited\r\n\r\n* fix(tests): wrap runtime test in process\r\n\r\n* fix(runtimes): remove unused runtimes\r\n\r\n* feat(runtimes): improve cancel wait\r\n\r\n* fix(ci): build test pip again in ci\r\n\r\n* fix(tests): fix a test\r\n\r\n* fix(test): run async in its own process\r\n\r\n* feat(pod): include shard in activate msg\r\n\r\n* fix(pea): dont join\r\n\r\n* feat(pod): more debug out\r\n\r\n* feat(grpc): manage channels properly\r\n\r\n* feat(pods): remove exitfifo\r\n\r\n* feat(network): add simple send retry mechanism\r\n\r\n* fix(network): await pool close\r\n\r\n* fix(test): always close grpc server in worker\r\n\r\n* fix(tests): remove container pea from tests\r\n\r\n* fix(tests): reorder tests\r\n\r\n* fix(ci): split tests\r\n\r\n* fix(ci): allow alias setting\r\n\r\n* fix(test): skip a test\r\n\r\n* feat(pods): address comments\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* test: unblock skipped test (#3957)\r\n\r\n* feat: jinad pea (#3949)\r\n\r\n* feat: jinad pea\r\n\r\n* feat: jinad pea\r\n\r\n* test: remote peas\r\n\r\n* test: toplogy tests with jinad\r\n\r\n* ci: parallel jobs\r\n\r\n* feat(tests): add pod integration tests (#3958)\r\n\r\n* feat(tests): add pod integration tests\r\n\r\n* fix(tests): make tests less flaky\r\n\r\n* fix(test): fix test\r\n\r\n* test(pea): remote pea topologies (#3961)\r\n\r\n* test(pea): remote pea simple topology\r\n\r\n* test: remote pea topologies\r\n\r\n* refactor: refactor streamer result handling (#3960)\r\n\r\n* feat(k8s): adapt K8s Pod for StarRouting (#3964)\r\n\r\n* test: optimize k8s test\r\n\r\n* test: increase timeout and use different namespace\r\n\r\n* test: optimize k8s test\r\n\r\n* test: build and load image when needed\r\n\r\n* test: refactor k8s test\r\n\r\n* test: fix image name error\r\n\r\n* test: fix k8s image load\r\n\r\n* test: fix typoe port expose\r\n\r\n* test: update tests in connection pool and handling\r\n\r\n* test: remove unused fixture\r\n\r\n* test: parameterize docker images\r\n\r\n* test: parameterize docker images\r\n\r\n* test: parameterize docker images\r\n\r\n* feat(k8s): adapt k8s pod for star routing\r\n\r\n* fix(k8s): dont overwrite add/remove function in pool\r\n\r\n* fix(k8s): some fixes\r\n\r\n* fix(k8s): some more fixes\r\n\r\n* fix(k8s): linting\r\n\r\n* fix(tests): fix tests\r\n\r\n* fix(tests): fix k8s unit tests\r\n\r\n* feat(k8s): complete k8s integration test\r\n\r\n* feat(k8s): finish k8s tests\r\n\r\n* feat(k8s): fix test\r\n\r\n* fix(tests): fix test with no name\r\n\r\n* feat(k8s): unify create/replace interface\r\n\r\n* feat(k8s): extract k8s port constants\r\n\r\n* fix(tests): fix tests\r\n\r\n* fix(tests): wait for runtime being ready in tests\r\n\r\n* feat(k8s): address comments\r\n\r\nCo-authored-by: bwanglzu \r\n\r\n* feat(flow): adapt Flow for StarRouting (#3986)\r\n\r\n* feat(flow): add routes\r\n\r\n* feat(flow): adapt flow to star routing\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(flow): handle empty topologies\r\n\r\n* feat(k8s): allow k8s pool disabling\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix(test): fix test with mock\r\n\r\n* fix(tests): fix more tests\r\n\r\n* feat(flow): clean up tests\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix(tests): fix more tests\r\n\r\n* feat: add plot function (#3994)\r\n\r\n* fix(tests): avoid hanging tests\r\n\r\n* feat(flow): add type hinting\r\n\r\n* fix(test): fix duplicate exec name in test\r\n\r\n* fix(tests): fix more tests\r\n\r\n* fix(tests): enable jinad test again\r\n\r\n* fix(tests): random port fixture\r\n\r\n* fix(style): replace quotes\r\n\r\nCo-authored-by: Jina Dev Bot \r\nCo-authored-by: Joan Fontanals \r\n\r\n* feat(ci): bring back ci (#3997)\r\n\r\n* feat(ci): enable ci again\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat(ci): add latency tracking\r\n\r\n* feat(ci): bring back some tests\r\n\r\n* fix(tests): remove invalid port test\r\n\r\n* feat(ci): disable daemon and distributed tests\r\n\r\n* fix(tests): fix entrypoint in hub test\r\n\r\n* fix(tests): wait for gateway to be ready\r\n\r\n* fix(test): fix more tests\r\n\r\n* feat(flow): do rolling update and scale sequentially\r\n\r\n* fix(tests): fix more tests\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* feat: star routing hanging pods (#4011)\r\n\r\n* fix: try to handle hanging pods better\r\n\r\n* test: hanging pods test work\r\n\r\n* fix: fix topology graph problem\r\n\r\n* test: add unit test to graph\r\n\r\n* fix(tests): fix k8s tests\r\n\r\n* fix(test): fix k8s test\r\n\r\n* fix(test): fix k8s pool test\r\n\r\n* fix(test): fix k8s test\r\n\r\n* fix(test): fix k8s connection pool setting\r\n\r\n* fix(tests): make runtime test more reliable\r\n\r\n* fix(test): fix routes test\r\n\r\n* fix(tests): make rolling update test less flaky\r\n\r\n* feat(network): gurantee unique ports\r\n\r\n* feat(network): do round robin for shards\r\n\r\n* fix(ci): increase pytest timeout to 10 min\r\n\r\nCo-authored-by: Jina Dev Bot \r\nCo-authored-by: Joan Fontanals \r\n\r\n* fix(ci): fix ci file\r\n\r\n* feat(daemon): jinad pod for star routing\r\n\r\n* Revert \"feat(daemon): jinad pod for star routing\"\r\n\r\nThis reverts commit ed9b37ac862af2e2e8d52df1ee51c0c331d76f92.\r\n\r\n* feat(daemon): remote jinad pod support (#4042)\r\n\r\n* feat(daemon): add pod tests for star routing\r\n\r\n* feat(daemon): add remote pod test\r\n\r\n* test(daemon): add remote pod arguments test\r\n\r\n* test(daemon): add async scale test\r\n\r\n* test(daemon): add rolling update test\r\n\r\n* test(daemon): fix host\r\n\r\n* feat(proto): remove message proto (#4051)\r\n\r\n* feat(proto): remove message proto\r\n\r\n* fix(tests): fix tests\r\n\r\n* fix(tests): fix some more tests\r\n\r\n* fix(tests): fix more tests\r\n\r\n* fix(tests): fix more tests\r\n\r\n* fix(tests): fix more tests\r\n\r\n* fix(tests): fix more tests\r\n\r\n* feat(proto): put docs back in data\r\n\r\n* fix(proto): clean up\r\n\r\n* feat(proto): clean up\r\n\r\n* fix(tests): skip latency tracking\r\n\r\n* fix(test): fix hub test\r\n\r\n* fix(tests): fix k8s test\r\n\r\n* fix(test): some test clean up\r\n\r\n* fix(style): clean up style issues\r\n\r\n* feat(proto): adjust for rebase\r\n\r\n* fix(tests): bring back latency tracking\r\n\r\n* fix(tests): fix merge accident\r\n\r\n* feat(proto): skip request serialization (#4074)\r\n\r\n* feat: add reduce to star routing (#4070)\r\n\r\n* feat: add reduce on shards to head runtime\r\n\r\n* test: add reduce integration tests with fixed order\r\n\r\n* feat: add reduce on needs\r\n\r\n* chore: get_docs_matrix_from_request becomes public\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* docs: remove undeterministic results warning\r\n\r\n* fix: fix uses_after\r\n\r\n* test: assert correct num docs after reducing in test_external_pod\r\n\r\n* test: correct asserts after reduce in test_rolling_update\r\n\r\n* fix: no reduce if uses_after_address is set\r\n\r\n* fix: get_docs_from_request only if needed\r\n\r\n* fix: fix tests after merge\r\n\r\n* refactor: move reduce from data_request_handler to head\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* chore: apply suggestions\r\n\r\n* fix: fix asserts\r\n\r\n* chore: minor test fix\r\n\r\n* chore: apply suggestions\r\n\r\n* test: remove flow tests with external executor (pea)\r\n\r\n* fix: fix test_expected_messages_routing\r\n\r\n* fix: fix test_func_joiner\r\n\r\n* test: adapt k8s test\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* fix(k8s): fix static pool config\r\n\r\n* fix: use custom protoc doc generator image (#4088)\r\n\r\n* fix: use custom protoc doc generator image\r\n\r\n* fix(docs): minor doc improvement\r\n\r\n* fix(docs): use custom image\r\n\r\n* fix(docs): copy docarray\r\n\r\n* fix: doc building local only\r\n\r\n* fix: timeout doc building\r\n\r\n* fix: use updated args when building ContainerPea\r\n\r\n* test: add container PeaFactory test\r\n\r\n* fix: force pea close on windows (#4098)\r\n\r\n* fix: dont reduce if uses exist (#4099)\r\n\r\n* fix: dont use reduce if uses exist\r\n\r\n* fix: adjust reduce tests\r\n\r\n* fix: adjust more reduce tests\r\n\r\n* fix: fix more tests\r\n\r\n* fix: adjust more tests\r\n\r\n* fix: ignore non jina resources (#4101)\r\n\r\n* feat(executor): enable async executors (#4102)\r\n\r\n* feat(daemon): daemon flow on star routing (#4096)\r\n\r\n* test(daemon): add remote flow test\r\n\r\n* feat(daemon): call scale in daemon\r\n\r\n* feat(daemon): remove tail args and identity\r\n\r\n* test(daemon): rename scalable executor\r\n\r\n* test(daemon): add a small delay in async test\r\n\r\n* feat(daemon): scale partial flow only\r\n\r\n* feat(daemon): call scale directly in partial flow store\r\n\r\n* test(daemon): use asyncio sleep\r\n\r\n* feat(daemon): enable flow level distributed tests\r\n\r\n* test(daemon): fix jinad env workspace config\r\n\r\n* test(daemon): fix pod test use new port rolling update\r\n\r\n* feat(daemon): enable distribuetd tests\r\n\r\n* test(daemon): remove duplicate tests and zed runtime test\r\n\r\n* test(daemon): fix stores unit test\r\n\r\n* feat(daemon): enable part of distributed tests\r\n\r\n* feat(daemon): enable part of distributed tests\r\n\r\n* test: correct test paths\r\n\r\n* test(daemon): add client test for remote flows\r\n\r\n* test(daemon): send a request with jina client\r\n\r\n* test(daemon): assert async generator\r\n\r\n* test(daemon): small interval between tests\r\n\r\n* test(daemon): add flow test for container runtime\r\n\r\n* test(daemon): add flow test for container runtime\r\n\r\n* test(daemon): fix executor name\r\n\r\n* test(daemon): fix executor name\r\n\r\n* test(daemon): use async client fetch result\r\n\r\n* test(daemon): finish container flow test\r\n\r\n* test(daemon): enable distributed in ci\r\n\r\n* test(daemon): enable distributed in ci\r\n\r\n* test(daemon): decare flows and pods\r\n\r\n* test(daemon): debug ci if else\r\n\r\n* test(daemon): debug ci if else\r\n\r\n* test(daemon): decare flows and pods\r\n\r\n* test(daemon): correct test paths\r\n\r\n* test(daemon): add small delay for async tests\r\n\r\n* fix: star routing fixes (#4100)\r\n\r\n* docs: update docs\r\n\r\n* fix: fix Request.__repr__\r\n\r\n* docs: update flow remarks\r\n\r\n* docs: fix typo\r\n\r\n* test: add non_empty_fields test\r\n\r\n* chore: remove non_empty_fields test\r\n\r\n* feat: polling per endpoint (#4111)\r\n\r\n* feat(polling): polling per endpoint configurable\r\n\r\n* fix: adjust tests\r\n\r\n* feat(polling): extend documentation\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix: clean up\r\n\r\n* fix: adjust more tests\r\n\r\n* fix: remove repeat from flaky test\r\n\r\n* fix: k8s test\r\n\r\n* feat(polling): address pr feedback\r\n\r\n* feat: improve docs\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* feat(grpc): support connect grpc server via ssl tunnel (#4092)\r\n\r\n* feat(grpc): support ssl grpc connect if port is 443\r\n\r\n* fix(grpc): use https option instead of detect port automatically\r\n\r\n* chore: fix typo\r\n\r\n* fix: update jina/peapods/networking.py\r\n\r\nCo-authored-by: Joan Fontanals \r\n\r\n* fix: update jina/peapods/networking.py\r\n\r\nCo-authored-by: Joan Fontanals \r\n\r\n* fix: update jina/peapods/networking.py\r\n\r\nCo-authored-by: Joan Fontanals \r\n\r\n* test(networking): add test for peapods networking\r\n\r\n* fix: address comments\r\n\r\nCo-authored-by: Joan Fontanals \r\n\r\n* feat(polling): unify polling args (#4113)\r\n\r\n* fix: several issues for jinad pods (#4119)\r\n\r\n* fix: activate for jinad pods\r\n\r\n* fix: dont expose worker pod in partial daemon\r\n\r\n* fix: workspace setting\r\n\r\n* fix: containerized flows\r\n\r\n* fix: hub test\r\n\r\n* feat(daemon): remote peas on star routing (#4112)\r\n\r\n* test(daemon): fix request in peas\r\n\r\n* test(daemon): fix request in peas\r\n\r\n* test(daemon): fix sync async client test\r\n\r\n* test(daemon): enable remote peas test\r\n\r\n* test(daemon): replace send message to send request\r\n\r\n* test(daemon): declare pea tests in ci\r\n\r\n* test(daemon): use pea args fixture\r\n\r\n* test(daemon): head pea use default host\r\n\r\n* test(daemon): fix peas topologies\r\n\r\n* test(daemon): fix pseudo naming\r\n\r\n* test(daemon): use default host as host\r\n\r\n* test(daemon): fix executor path\r\n\r\n* test(daemon): add remote worker back\r\n\r\n* test(daemon): skip local remote remote topology\r\n\r\n* fix: jinad pea test setup\r\n\r\n* fix: jinad pea tests\r\n\r\n* fix: remove invalid assertion\r\n\r\nCo-authored-by: jacobowitz \r\n\r\n* feat: enable daemon tests again (#4132)\r\n\r\n* feat: enable daemon tests again\r\n\r\n* fix: remove bogy empty script file\r\n\r\n* fix: more jinad test fixes\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix: scale and ru in jinad\r\n\r\n* fix: fix more jinad tests\r\n\r\nCo-authored-by: Jina Dev Bot \r\n\r\n* fix: fix flow test\r\n\r\n* fix: improve pea tests reliability (#4136)\r\n\r\nCo-authored-by: Joan Fontanals \r\nCo-authored-by: Jina Dev Bot \r\nCo-authored-by: Deepankar Mahapatro \r\nCo-authored-by: bwanglzu \r\nCo-authored-by: AlaeddineAbdessalem \r\nCo-authored-by: Zhaofeng Miao <522856232@qq.com>", "code": "def test_bad_flow_skip_handle_join(mocker, protocol):\n \n", "url": "https://github.com/jina-ai/jina.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 6, "n_words": 3, "vocab_size": 3, "complexity": 1, "nloc": 13, "token_counts": 98, "n_ast_nodes": 15, "n_identifiers": 3 }, { "id": 308747, "commit_id": "ce138dd30e7262fc71253ab5c2936f869b891fda", "repo": "core", "path": "tests/components/flic/test_binary_sensor.py", "file_name": "test_binary_sensor.py", "fun_name": "test_button_uid", "commit_message": "Add unique id to flic buttons (#61496)\n\n* Use bluetooth address as unique id for flic buttons.\r\n\r\n* Always lower case address for uid and add tests.\r\n\r\n* Update test to set up component.\r\n\r\n* Use format_mac(addr) as unique id.\r\n\r\n* Only patch pyflic objects and use query entity registry for buttons.\r\n\r\n* Replace ExitStack with patch.multiple, remove assert_setup_component.\r\n\r\n* Test binary sensor is present in state machine.", "code": "async def test_button_uid(hass):\n \n address_to_name = {\n \"80:e4:da:78:6e:11\": \"binary_sensor.flic_80e4da786e11\",\n # Uppercase address should not change uid.\n \"80:E4:DA:78:6E:12\": \"binary_sensor.flic_80e4da786e12\",\n }\n\n flic_client = _MockFlicClient(tuple(address_to_name))\n\n with mock.patch.multiple(\n \"pyflic\",\n FlicClient=lambda _, __: flic_client,\n ButtonConnectionChannel=mock.DEFAULT,\n ScanWizard=mock.DEFAULT,\n ):\n assert await async_setup_component(\n hass,\n \"binary_sensor\",\n {\"binary_sensor\": [{\"platform\": \"flic\"}]},\n )\n\n await hass.async_block_till_done()\n\n entity_registry = er.async_get(hass)\n for address, name in address_to_name.items():\n state = hass.states.get(name)\n assert state\n assert state.attributes.get(\"address\") == address\n\n entry = entity_registry.async_get(name)\n assert entry\n assert entry.unique_id == address.lower()\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 269, "n_words": 68, "vocab_size": 55, "complexity": 2, "nloc": 26, "token_counts": 148, "n_ast_nodes": 253, "n_identifiers": 30 }, { "id": 212929, "commit_id": "dfad2e3b7671b7128895c8a0e29fff38d7efe6e9", "repo": "PySimpleGUI", "path": "PySimpleGUI.py", "file_name": "PySimpleGUI.py", "fun_name": "theme_global", "commit_message": "Better error checking/reporting in theme_global. NEW THEME DarkGrey15", "code": "def theme_global(new_theme=None):\n \n if new_theme is not None:\n if new_theme not in theme_list():\n popup_error_with_traceback('Cannot use custom themes with theme_global call',\n 'Your request to use theme {} cannot be performed.'.format(new_theme),\n 'The PySimpleGUI Global User Settings are meant for PySimpleGUI standard items, not user config items',\n 'You can use any of the many built-in themes instead or use your own UserSettings file to store your custom theme')\n return pysimplegui_user_settings.get('-theme-', CURRENT_LOOK_AND_FEEL)\n pysimplegui_user_settings.set('-theme-', new_theme)\n theme(new_theme)\n return new_theme\n else:\n return pysimplegui_user_settings.get('-theme-', CURRENT_LOOK_AND_FEEL)\n\n", "url": "https://github.com/PySimpleGUI/PySimpleGUI.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 256, "n_words": 76, "vocab_size": 59, "complexity": 3, "nloc": 13, "token_counts": 71, "n_ast_nodes": 125, "n_identifiers": 10 }, { "id": 130602, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "python/ray/data/impl/block_list.py", "file_name": "block_list.py", "fun_name": "ensure_schema_for_first_block", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def ensure_schema_for_first_block(self) -> Optional[Union[\"pyarrow.Schema\", type]]:\n \n get_schema = cached_remote_fn(_get_schema)\n try:\n block = next(self.iter_blocks())\n except (StopIteration, ValueError):\n # Dataset is empty (no blocks) or was manually cleared.\n return None\n schema = ray.get(get_schema.remote(block))\n # Set the schema.\n self._metadata[0].schema = schema\n return schema\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 128, "n_words": 39, "vocab_size": 32, "complexity": 2, "nloc": 13, "token_counts": 68, "n_ast_nodes": 113, "n_identifiers": 18 }, { "id": 167478, "commit_id": "ad842d36bb62a6c7a5e8f93a9594129ff46cc5cb", "repo": "pandas", "path": "pandas/tests/io/formats/test_to_excel.py", "file_name": "test_to_excel.py", "fun_name": "test_css_excel_cell_cache", "commit_message": "PERF: Improve Styler `to_excel` Performance (#47371)\n\n* Move CSS expansion lookup to dictionary\r\n\r\n* Implement simple CSSToExcelConverter cache\r\n\r\n* Eliminate list -> str -> list in CSSResolver\r\n\r\n* Allow for resolution of duplicate properties\r\n\r\n* Add performance benchmark for styled Excel\r\n\r\n* CLN: Clean up PEP8 issues\r\n\r\n* DOC: Update PR documentation\r\n\r\n* CLN: Clean up PEP8 issues\r\n\r\n* Fixes from pre-commit [automated commit]\r\n\r\n* Make Excel CSS case-insensitive\r\n\r\n* Test for ordering and caching\r\n\r\n* Pre-commit fixes\r\n\r\n* Remove built-in filter\r\n\r\n* Increase maxsize of Excel cache\r\n\r\nCo-authored-by: Thomas Hunter ", "code": "def test_css_excel_cell_cache(styles, cache_hits, cache_misses):\n \n # See GH 47371\n converter = CSSToExcelConverter()\n converter.__call__.cache_clear()\n\n css_styles = {(0, i): _style for i, _style in enumerate(styles)}\n for css_row, css_col in css_styles:\n CssExcelCell(\n row=0,\n col=0,\n val=\"\",\n style=None,\n css_styles=css_styles,\n css_row=css_row,\n css_col=css_col,\n css_converter=converter,\n )\n cache_info = converter.__call__.cache_info()\n converter.__call__.cache_clear()\n\n assert cache_info.hits == cache_hits\n assert cache_info.misses == cache_misses\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 181, "n_words": 49, "vocab_size": 41, "complexity": 3, "nloc": 19, "token_counts": 112, "n_ast_nodes": 171, "n_identifiers": 23 }, { "id": 320832, "commit_id": "4a6df3a8e84780e9f58dbda31c3a9bfa1e35cebe", "repo": "qutebrowser", "path": "qutebrowser/config/configfiles.py", "file_name": "configfiles.py", "fun_name": "migrate", "commit_message": "Add setting to allow pasting from clipboard\n\nCloses #5256\nSupersedes and closes #6315", "code": "def migrate(self) -> None:\n \n self._migrate_configdata()\n self._migrate_bindings_default()\n self._migrate_font_default_family()\n self._migrate_font_replacements()\n\n self._migrate_bool('tabs.favicons.show', 'always', 'never')\n self._migrate_bool('scrolling.bar', 'always', 'overlay')\n self._migrate_bool('qt.force_software_rendering',\n 'software-opengl', 'none')\n self._migrate_renamed_bool(\n old_name='content.webrtc_public_interfaces_only',\n new_name='content.webrtc_ip_handling_policy',\n true_value='default-public-interface-only',\n false_value='all-interfaces')\n self._migrate_renamed_bool(\n old_name='tabs.persist_mode_on_change',\n new_name='tabs.mode_on_change',\n true_value='persist',\n false_value='normal')\n self._migrate_renamed_bool(\n old_name='statusbar.hide',\n new_name='statusbar.show',\n true_value='never',\n false_value='always')\n self._migrate_renamed_bool(\n old_name='content.ssl_strict',\n new_name='content.tls.certificate_errors',\n true_value='block',\n false_value='load-insecurely',\n ask_value='ask',\n )\n self._migrate_renamed_bool(\n old_name='content.javascript.can_access_clipboard',\n new_name='content.javascript.clipboard',\n true_value='access',\n false_value='none',\n )\n\n for setting in ['colors.webpage.force_dark_color_scheme',\n 'colors.webpage.prefers_color_scheme_dark']:\n self._migrate_renamed_bool(\n old_name=setting,\n new_name='colors.webpage.preferred_color_scheme',\n true_value='dark',\n false_value='auto',\n )\n\n for setting in ['tabs.title.format',\n 'tabs.title.format_pinned',\n 'window.title_format']:\n self._migrate_string_value(setting,\n r'(?", "code": "def is_closed(self) -> bool | None:\n \n if self._node.status == ISY_VALUE_UNKNOWN:\n return None\n return bool(self._node.status == 0)\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 48, "n_words": 16, "vocab_size": 14, "complexity": 2, "nloc": 5, "token_counts": 32, "n_ast_nodes": 53, "n_identifiers": 6 }, { "id": 262777, "commit_id": "bfd5c729919b16e5e9457fca28e931b0e897a60a", "repo": "pyinstaller", "path": "PyInstaller/building/splash_templates.py", "file_name": "splash_templates.py", "fun_name": "build_script", "commit_message": "splash: add always_on_top option for behavior configuration\n\nAllow user to enable or disable the always-on-top behavior at\nbuild time via always_on_top boolean argument to Splash().\n\nBy default, the always-on-top behavior is enabled for the sake of\nconsistency with previous releases.", "code": "def build_script(text_options=None, always_on_top=False):\n \n # Order is important!\n script = [\n ipc_script,\n image_script,\n splash_canvas_setup,\n ]\n\n if text_options:\n # If the default font is used we need a different syntax\n if text_options['font'] == \"TkDefaultFont\":\n script.append(splash_canvas_default_font % text_options)\n else:\n script.append(splash_canvas_custom_font % text_options)\n script.append(splash_canvas_text % text_options)\n\n script.append(transparent_setup)\n\n script.append(pack_widgets)\n script.append(position_window_on_top if always_on_top else position_window)\n script.append(raise_window)\n\n return '\\n'.join(script)\n", "url": "https://github.com/pyinstaller/pyinstaller.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 153, "n_words": 52, "vocab_size": 44, "complexity": 4, "nloc": 17, "token_counts": 94, "n_ast_nodes": 159, "n_identifiers": 17 }, { "id": 107634, "commit_id": "d69be2554cf6d1ac711bf433b1d6f176e3290d4f", "repo": "matplotlib", "path": "lib/matplotlib/projections/polar.py", "file_name": "polar.py", "fun_name": "set_rgrids", "commit_message": "Clarify error message for bad keyword arguments.\n\n`plot([], [], foo=42)` previously emitted\n```\n'Line2D' object has no property 'foo'\n```\nwhich refers to the Matplotlib-specific concept of \"properties\". It now\ninstead emits\n```\nLine2D.set() got an unexpected keyword argument 'foo'\n```\nwhich is modeled after the standard error message for unknown keyword\narguments.\n\n(To maximize backcompat, the implementation goes through a new\n_internal_update, which does *not* error when the same prop is passed\nunder different aliases. This could be changed later, but is not the\ngoal of this PR.)", "code": "def set_rgrids(self, radii, labels=None, angle=None, fmt=None, **kwargs):\n \n # Make sure we take into account unitized data\n radii = self.convert_xunits(radii)\n radii = np.asarray(radii)\n\n self.set_yticks(radii)\n if labels is not None:\n self.set_yticklabels(labels)\n elif fmt is not None:\n self.yaxis.set_major_formatter(mticker.FormatStrFormatter(fmt))\n if angle is None:\n angle = self.get_rlabel_position()\n self.set_rlabel_position(angle)\n for t in self.yaxis.get_ticklabels():\n t._internal_update(kwargs)\n return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()\n", "url": "https://github.com/matplotlib/matplotlib.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 172, "n_words": 51, "vocab_size": 41, "complexity": 5, "nloc": 14, "token_counts": 127, "n_ast_nodes": 203, "n_identifiers": 22 }, { "id": 47864, "commit_id": "be51aece54ef98a8868845ad8033f08689dd7ad1", "repo": "airflow", "path": "dev/breeze/tests/test_docker_command_utils.py", "file_name": "test_docker_command_utils.py", "fun_name": "test_check_docker_version_unknown", "commit_message": "Fix and improve consistency of checking command return code (#23189)\n\nThis is an aftermath of #23104 after switchig to docs building\r\nby breeze, failure of build documentation did not trigger failure\r\nof the docs build (but it did trigger main failure of pushing\r\nthe documentation).\r\n\r\nThis change improves and simplifies the return code processing and\r\npropagation in the commands executed by breeze - thanks to common\r\nreturncode, stdout, stderr available in both CompletedProcess\r\nand CalledProcessError and returning fake CompletedProcess in dry_run\r\nmode, we can also satisfy MyPy type check by returning non-optional\r\nUnion of those two types which simplifies returncode processing.\r\n\r\nThis change fixes the error in the docs (lack of empty lines before\r\nauto-generated extras).\r\n\r\nAll commands have been reviewed to see if the returncode is\r\ncorrectly handled where needed.", "code": "def test_check_docker_version_unknown(mock_console, mock_run_command, mock_check_docker_permission_denied):\n mock_check_docker_permission_denied.return_value = False\n check_docker_version(verbose=True)\n expected_run_command_calls = [\n call(\n ['docker', 'version', '--format', '{{.Client.Version}}'],\n verbose=True,\n no_output_dump_on_exception=True,\n capture_output=True,\n text=True,\n check=False,\n ),\n ]\n mock_run_command.assert_has_calls(expected_run_command_calls)\n mock_console.print.assert_called_with(\n \n )\n\n\n@mock.patch('airflow_breeze.utils.docker_command_utils.check_docker_permission_denied')\n@mock.patch('airflow_breeze.utils.docker_command_utils.run_command')\n@mock.patch('airflow_breeze.utils.docker_command_utils.console')", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "@mock.patch('airflow_breeze.utils.docker_command_utils.check_docker_permission_denied')\n@mock.patch('airflow_breeze.utils.docker_command_utils.run_command')\n@mock.patch('airflow_breeze.utils.docker_command_utils.console')", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 134, "n_words": 29, "vocab_size": 28, "complexity": 1, "nloc": 20, "token_counts": 72, "n_ast_nodes": 153, "n_identifiers": 18 }, { "id": 266443, "commit_id": "8febd37f325b049afe448af689064ee019d1099c", "repo": "ansible", "path": "lib/ansible/template/__init__.py", "file_name": "__init__.py", "fun_name": "_ansible_finalize", "commit_message": "Attach concat func to an environment class (#76282)\n\n* Attach concat func to an environment class\r\n\r\nci_complete\r\n\r\n* clog and docstrings", "code": "def _ansible_finalize(thing):\n \n return thing if thing is not None else ''\n\n", "url": "https://github.com/ansible/ansible.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 17, "n_words": 11, "vocab_size": 10, "complexity": 2, "nloc": 2, "token_counts": 15, "n_ast_nodes": 27, "n_identifiers": 2 }, { "id": 269496, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/backend.py", "file_name": "backend.py", "fun_name": "_constant_to_tensor", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _constant_to_tensor(x, dtype):\n \n return tf.constant(x, dtype=dtype)\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 12, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 2, "token_counts": 19, "n_ast_nodes": 31, "n_identifiers": 5 }, { "id": 272025, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/feature_column/base_feature_layer.py", "file_name": "base_feature_layer.py", "fun_name": "_sanitize_column_name_for_variable_scope", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _sanitize_column_name_for_variable_scope(name):\n \n invalid_char = re.compile(\"[^A-Za-z0-9_.\\\\-]\")\n return invalid_char.sub(\"_\", name)\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 17, "n_words": 8, "vocab_size": 8, "complexity": 1, "nloc": 3, "token_counts": 23, "n_ast_nodes": 44, "n_identifiers": 6 }, { "id": 249339, "commit_id": "2281427175e4c93a30c39607fb4ac23c2a1f399f", "repo": "synapse", "path": "tests/rest/admin/test_registration_tokens.py", "file_name": "test_registration_tokens.py", "fun_name": "test_create_token_invalid_chars", "commit_message": "Use literals in place of `HTTPStatus` constants in tests (#13488)\n\n* Use literals in place of `HTTPStatus` constants in tests\r\n\r\n* newsfile\r\n\r\n* code style\r\n\r\n* code style", "code": "def test_create_token_invalid_chars(self) -> None:\n \n data = {\n \"token\": \"abc/def\",\n }\n\n channel = self.make_request(\n \"POST\",\n self.url + \"/new\",\n data,\n access_token=self.admin_user_tok,\n )\n\n self.assertEqual(400, channel.code, msg=channel.json_body)\n self.assertEqual(channel.json_body[\"errcode\"], Codes.INVALID_PARAM)\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 129, "n_words": 25, "vocab_size": 24, "complexity": 1, "nloc": 13, "token_counts": 70, "n_ast_nodes": 115, "n_identifiers": 14 }, { "id": 45940, "commit_id": "5ace37a16d1773adb71c684450838e4c8e69b581", "repo": "airflow", "path": "tests/jobs/test_scheduler_job.py", "file_name": "test_scheduler_job.py", "fun_name": "test_dagrun_callbacks_commited_before_sent", "commit_message": "Store callbacks in database if standalone_dag_processor config is True. (#21731)", "code": "def test_dagrun_callbacks_commited_before_sent(self, dag_maker):\n \n with dag_maker(dag_id='test_dagrun_callbacks_commited_before_sent'):\n DummyOperator(task_id='dummy')\n\n self.scheduler_job = SchedulerJob(subdir=os.devnull)\n self.scheduler_job.processor_agent = mock.Mock()\n self.scheduler_job._send_dag_callbacks_to_processor = mock.Mock()\n self.scheduler_job._schedule_dag_run = mock.Mock()\n\n dr = dag_maker.create_dagrun()\n session = settings.Session()\n\n ti = dr.get_task_instance('dummy')\n ti.set_state(State.SUCCESS, session)\n\n with mock.patch.object(settings, \"USE_JOB_SCHEDULE\", False), mock.patch(\n \"airflow.jobs.scheduler_job.prohibit_commit\"\n ) as mock_guard:\n mock_guard.return_value.__enter__.return_value.commit.side_effect = session.commit\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 158, "n_words": 41, "vocab_size": 31, "complexity": 1, "nloc": 25, "token_counts": 188, "n_ast_nodes": 235, "n_identifiers": 33 }, { "id": 147478, "commit_id": "1465eaa30634c189fe3ebc9db8609f47d19a78cc", "repo": "ray", "path": "python/ray/tune/checkpoint_manager.py", "file_name": "checkpoint_manager.py", "fun_name": "is_ready", "commit_message": "[tune] Use new Checkpoint interface internally (#22801)\n\nFollow up from #22741, also use the new checkpoint interface internally. This PR is low friction and just replaces some internal bookkeeping methods.\r\n\r\nWith the new Checkpoint interface, there is no need to revamp the save/restore APIs completely. Instead, we will focus on the bookkeeping part, which takes place in the Ray Tune's and Ray Train's checkpoint managers. These will be consolidated in a future PR.", "code": "def is_ready(self):\n \n if self.storage == _TuneCheckpoint.PERSISTENT:\n return isinstance(self.value, str)\n return self.storage == _TuneCheckpoint.MEMORY\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 45, "n_words": 13, "vocab_size": 10, "complexity": 2, "nloc": 4, "token_counts": 32, "n_ast_nodes": 52, "n_identifiers": 9 }, { "id": 320735, "commit_id": "a20bb67a878b2e68abf8268c1b0a27f018d01352", "repo": "qutebrowser", "path": "qutebrowser/browser/downloadview.py", "file_name": "downloadview.py", "fun_name": "sizeHint", "commit_message": "mypy: Upgrade to PyQt5-stubs 5.15.6.0\n\nFor some unknown reason, those new stubs cause a *lot* of things now to be\nchecked by mypy which formerly probably got skipped due to Any being implied\nsomewhere.\n\nThe stubs themselves mainly improved, with a couple of regressions too.\n\nIn total, there were some 337 (!) new mypy errors. This commit fixes almost all\nof them, and the next commit improves a fix to get things down to 0 errors\nagain.\n\nOverview of the changes:\n\n==== qutebrowser/app.py\n\n- Drop type ignore due to improved stubs.\n\n==== qutebrowser/browser/browsertab.py\n\n- Specify the type of _widget members more closely than just QWidget.\n This is debatable: I suppose the abstract stuff shouldn't need to know\n anything about the concrete backends at all. But it seems like we cut some\n corners when initially implementing things, and put some code in browsertab.py\n just because the APIs of both backends happened to be compatible. Perhaps\n something to reconsider once we drop QtWebKit and hopefully implement a dummy\n backend.\n\n- Add an additional assertion in AbstractAction.run_string. This is already\n covered by the isinstance(member, self.action_base) above it, but that's too\n dynamic for mypy to understand.\n\n- Fix the return type of AbstractScroller.pos_px, which is a QPoint (with x\n and y components), not a single int.\n\n- Fix the return type of AbstractScroller.pos_perc, which is a Tuple (with x\n and y components), not a single int.\n\n- Fix the argument types of AbstractScroller.to_perc, as it's possible to pass\n fractional percentages too.\n\n- Specify the type for AbstractHistoryPrivate._history. See above (_widget) re\n this being debatable.\n\n- Fix the return type of AbstractTabPrivate.event_target(), which can be None\n (see #3888).\n\n- Fix the return type of AbstractTabPrivate.run_js_sync, which is Any (the JS\n return value), not None.\n\n- Fix the argument type for AbstractTabPrivate.toggle_inspector: position can\n be None to use the last used position.\n\n- Declare the type of sub-objects of AbstractTab.\n\n- Fix the return value of AbstractTab.icon(), which is the QIcon, not None.\n\n==== qutebrowser/browser/commands.py\n\n- Make sure the active window is a MainWindow (with a .win_id attribute).\n\n==== qutebrowser/browser/downloadview.py\n\n- Add _model() which makes sure that self.model() is a DownloadModel, not None\n or any other model. This is needed because other methods access a variety of\n custom attributes on it, e.g. last_index().\n\n==== qutebrowser/browser/greasemonkey.py\n\n- Add an ignore for AbstractDownload.requested_url which we patch onto the\n downloads. Probably would be nicer to add it as a proper attribute which always\n gets set by the DownloadManager.\n\n==== qutebrowser/browser/hints.py\n\n- Remove type ignores for QUrl.toString().\n- Add a new type ignore for combining different URL flags (which works, but is\n not exactly type safe... still probably a regression in the stubs).\n- Make sure the things we get back from self._get_keyparser are what we actually\n expect. Probably should introduce a TypedDict (and/or overloads for\n _get_keyparser with typing.Literal) to teach mypy about the exact return value.\n See #7098.\n This is needed because we access Hint/NormalKeyParser-specific attributes such\n as .set_inhibited_timout() or .update_bindings().\n\n==== qutebrowser/browser/inspector.py\n\n- Similar changes than in browsertab.py to make some types where we share API\n (e.g. .setPage()) more concrete. Didn't work out unfortunately, see next\n commit.\n\n==== qutebrowser/browser/network/pac.py\n\n- Remove now unneeded type ignore for signal.\n\n==== qutebrowser/browser/qtnetworkdownloads.py\n\n- Make sure that downloads is a qtnetworkdownloads.DownloadItem (rather than an\n AbstractDownload), so that we can call ._uses_nam() on it.\n\n==== qutebrowser/browser/qutescheme.py\n\n- Remove now unneeded type ignore for QUrl flags.\n\n==== qutebrowser/browser/urlmarks.py\n\n- Specify the type of UrlMarkManager._lineparser, as those only get initialized\n in _init_lineparser of subclasses, so mypy doesn't know it's supposed to exist.\n\n==== qutebrowser/browser/webelem.py\n\n- New casts to turn single KeyboardModifier (enum) entries into\n KeyboardModifiers (flags). Might not be needed anymore with Qt 6.\n- With that, casting the final value is now unneeded.\n\n==== qutebrowser/browser/webengine/notification.py\n\n- Remove now unneeded type ignore for signal.\n- Make sure the self.sender() we get in HerbeNotificationAdapter._on_finished()\n is a QProcess, not just any QObject.\n\n==== qutebrowser/browser/webengine/webenginedownloads.py\n\n- Remove now unneeded type ignores for signals.\n\n==== qutebrowser/browser/webengine/webengineelem.py\n\n- Specify the type of WebEngineElement._tab.\n- Remove now unneeded type ignore for mixed flags.\n\n==== qutebrowser/browser/webengine/webengineinspector.py\n\n- See changes to inspector.py and next commit.\n- Remove now unneeded type ignore for signal.\n\n==== qutebrowser/browser/webengine/webenginequtescheme.py\n\n- Remove now unneeded type ignore for mixed flags.\n\n==== qutebrowser/browser/webengine/webenginesettings.py\n\n- Ignore access of .setter attribute which we patch onto QWebEngineProfile.\n Would be nice to have a subclass or wrapper-class instead.\n\n==== qutebrowser/browser/webengine/webenginetab.py\n\n- Specified the type of _widget members more closely than just QWidget.\n See browsertab.py changes for details.\n- Remove some now-unneeded type ignores for creating FindFlags.\n- Specify more concrete types for WebEngineTab members where we actually need to\n access WebEngine-specific attributes.\n- Make sure the page we get is our custom WebEnginePage subclass, not just any\n QWebEnginePage. This is needed because we access custom attributes on it.\n\n==== qutebrowser/browser/webengine/webview.py\n\n- Make sure the page we get is our custom WebEnginePage subclass, not just any\n QWebEnginePage. This is needed because we access custom attributes on it.\n\n==== qutebrowser/browser/webkit/network/networkreply.py\n\n- Remove now unneeded type ignores for signals.\n\n==== qutebrowser/browser/webkit/webkitinspector.py\n\n- See changes to inspector.py and next commit.\n\n==== qutebrowser/browser/webkit/webkittab.py\n\n- Specify the type of _widget members more closely than just QWidget.\n See browsertab.py changes for details.\n- Add a type ignore for WebKitAction because our workaround needs to\n treat them as ints (which is allowed by PyQt, even if not type-safe).\n- Add new ignores for findText calls: The text is a QString and can be None; the\n flags are valid despite mypy thinking they aren't (stubs regression?).\n- Specify the type for WebKitHistoryPrivate._history, because we access\n WebKit-specific attributes. See above (_widget) re this being debatable.\n- Make mypy aware that .currentFrame() and .frameAt() can return None (stubs\n regression?).\n- Make sure the .page() and .page().networkAccessManager() are our subclasses\n rather than the more generic QtWebKit objects, as we use custom attributes.\n- Add new type ignores for signals (stubs regression!)\n\n==== qutebrowser/browser/webkit/webpage.py\n\n- Make sure the .networkAccessManager() is our subclass rather than the more\n generic QtWebKit object, as we use custom attributes.\n- Replace a cast by a type ignore. The cast didn't work anymore.\n\n==== qutebrowser/browser/webkit/webview.py\n\n- Make sure the .page() is our subclass rather than the more generic QtWebKit\n object, as we use custom attributes.\n\n==== qutebrowser/commands/userscripts.py\n\n- Remove now unneeded type ignore for signal.\n\n==== qutebrowser/completion/completer.py\n\n- Add a new _completion() getter (which ensures it actually gets the completion\n view) rather than accessing the .parent() directly (which could be any QObject).\n\n==== qutebrowser/completion/completiondelegate.py\n\n- Make sure self.parent() is a CompletionView (no helper method as there is only\n one instance).\n- Remove a now-unneeded type ignore for adding QSizes.\n\n==== qutebrowser/completion/completionwidget.py\n\n- Add a ._model() getter which ensures that we get a CompletionModel (with\n custom attributes) rather than Qt's .model() which can be any QAbstractItemModel\n (or None).\n- Removed a now-unneeded type ignore for OR-ing flags.\n\n==== qutebrowser/completion/models/completionmodel.py\n\n- Remove now unneeded type ignores for signals.\n- Ignore a complaint about .set_pattern() not being defined. Completion\n categories don't share any common parent class, so it would be good to introduce\n a typing.Protocol for this. See #7098.\n\n==== qutebrowser/components/misccommands.py\n\n- Removed a now-unneeded type ignore for OR-ing flags.\n\n==== qutebrowser/components/readlinecommands.py\n\n- Make sure QApplication.instance() is a QApplication (and not just a\n QCoreApplication). This includes the former \"not None\" check.\n\n==== qutebrowser/components/scrollcommands.py\n\n- Add basic annotation for \"funcs\" dict. Could have a callable protocol to\n specify it needs a count kwarg, see #7098.\n\n==== qutebrowser/config/stylesheet.py\n\n- Correctly specify that stylesheet apply to QWidgets, not any QObject.\n- Ignore an attr-defined for obj.STYLESHEET. Perhaps could somehow teach mypy\n about this with overloads and protocols (stylesheet for set_register being None\n => STYLESHEET needs to be defined, otherwise anything goes), but perhaps not\n worth the troble. See #7098.\n\n==== qutebrowser/keyinput/keyutils.py\n\n- Remove some now-unneeded type ignores and add a cast for using a single enum\n value as flags. Might need to look at this again with Qt 6 support.\n\n==== qutebrowser/keyinput/modeman.py\n\n- Add a FIXME for using a TypedDict, see comments for hints.py above.\n\n==== qutebrowser/mainwindow/mainwindow.py\n\n- Remove now-unneeded type ignores for calling with OR-ed flags.\n- Improve where we cast from WindowType to WindowFlags, no int needed\n- Use new .tab_bar() getter, see below.\n\n==== qutebrowser/mainwindow/prompt.py\n\n- Remove now-unneeded type ignores for calling with OR-ed flags.\n\n==== qutebrowser/mainwindow/statusbar/bar.py\n\n- Adjust type ignores around @pyqtProperty. The fact one is still needed seems\n like a stub regression.\n\n==== qutebrowser/mainwindow/statusbar/command.py\n\n- Fix type for setText() override (from QLineEdit): text can be None\n (QString in C++).\n\n==== qutebrowser/mainwindow/statusbar/url.py\n\n- Adjust type ignores around @pyqtProperty. The fact one is still needed seems\n like a stub regression.\n\n==== qutebrowser/mainwindow/tabbedbrowser.py\n\n- Specify that TabDeque manages browser tabs, not any QWidgets. It accesses\n AbstractTab-specific attributes.\n- Make sure that the .tabBar() we get is a tabwidget.TabBar, as we access\n .maybe_hide.\n- Fix the annotations for stored marks: Scroll positions are a QPoint, not int.\n- Add _current_tab() and _tab_by_idx() wrappers for .currentWidget() and\n .widget(), which ensures that the return values are valid AbstractTabs (or None\n for _tab_by_idx). This is needed because we access AbstractTab-specific\n attributes.\n- For some places, where the tab can be None, continue using .currentTab() but\n add asserts.\n- Remove some now-unneeded [unreachable] ignores, as mypy knows about the None\n possibility now.\n\n==== qutebrowser/mainwindow/tabwidget.py\n\n- Add new tab_bar() and _tab_by_idx() helpers which check that the .tabBar() and\n .widget() are of type TabBar and AbstractTab, respectively.\n- Add additional assertions where we expect ._tab_by_idx() to never be None.\n- Remove dead code in get_tab_fields for handling a None y scroll position. I\n was unable to find any place in the code where this could be set to None.\n- Remove some now-unneeded type ignores and casts, as mypy now knows that\n _type_by_idx() could be None.\n- Work around a strange instance where mypy complains about not being able to\n find the type of TabBar.drag_in_progress from TabWidget._toggle_visibility,\n despite it clearly being shown as a bool *inside* that class without any\n annotation.\n- Add a ._tab_widget() getter in TabBar which ensures that the .parent() is in\n fact a TabWidget.\n\n==== qutebrowser/misc/crashsignal.py\n\n- Remove now unneeded type ignores for signals.\n\n==== qutebrowser/misc/editor.py\n\n- Remove now unneeded type ignores for signals.\n\n==== qutebrowser/misc/ipc.py\n\n- Remove now unneeded type ignores for signals.\n- Add new type ignores for .error() which is both a signal and a getter\n (stub regression?). Won't be relevant for Qt 6 anymore, as the signal was\n renamed to errorOccurred in 5.15.\n\n==== qutebrowser/misc/objects.py\n\n- Make sure mypy knows that objects.app is our custom Application (with custom\n attributes) rather than any QApplication.\n\n==== qutebrowser/utils/objreg.py\n\n- Ignore attr-defined for .win_id attributes. Maybe could add a typing.Protocol,\n but ideally, the whole objreg stuff should die one day anyways.\n\n==== tests/unit/completion/test_completer.py\n\n- Make CompletionWidgetStub inherit from CompletionView so that it passes the\n new isinstance() asserts in completer.py (see above).", "code": "def sizeHint(self):\n \n idx = self._model().last_index()\n bottom = self.visualRect(idx).bottom()\n if bottom != -1:\n margins = self.contentsMargins()\n height = (bottom + margins.top() + margins.bottom() +\n 2 * self.spacing())\n size = QSize(0, height)\n else:\n size = QSize(0, 0)\n qtutils.ensure_valid(size)\n return size\n", "url": "https://github.com/qutebrowser/qutebrowser.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 152, "n_words": 38, "vocab_size": 27, "complexity": 2, "nloc": 12, "token_counts": 93, "n_ast_nodes": 156, "n_identifiers": 16 }, { "id": 148344, "commit_id": "b51d0aa8b12ceb7ce082b69db4d2707ea52c0b69", "repo": "ray", "path": "python/ray/serve/api.py", "file_name": "api.py", "fun_name": "get_replica_context", "commit_message": "[serve] Introduce `context.py` and `client.py` (#24067)\n\nServe stores context state, including the `_INTERNAL_REPLICA_CONTEXT` and the `_global_client` in `api.py`. However, these data structures are referenced throughout the codebase, causing circular dependencies. This change introduces two new files:\r\n\r\n* `context.py`\r\n * Intended to expose process-wide state to internal Serve code as well as `api.py`\r\n * Stores the `_INTERNAL_REPLICA_CONTEXT` and the `_global_client` global variables\r\n* `client.py`\r\n * Stores the definition for the Serve `Client` object, now called the `ServeControllerClient`", "code": "def get_replica_context() -> ReplicaContext:\n \n internal_replica_context = get_internal_replica_context()\n if internal_replica_context is None:\n raise RayServeException(\n \"`serve.get_replica_context()` \"\n \"may only be called from within a \"\n \"Ray Serve deployment.\"\n )\n return internal_replica_context\n\n\n@PublicAPI(stability=\"beta\")", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "@PublicAPI(stability=\"beta\")", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 88, "n_words": 30, "vocab_size": 27, "complexity": 2, "nloc": 25, "token_counts": 26, "n_ast_nodes": 66, "n_identifiers": 7 }, { "id": 11925, "commit_id": "b0f839b2030b1371518082be7bf79778d6e9f88d", "repo": "jina", "path": "jina/parsers/orchestrate/runtimes/remote.py", "file_name": "remote.py", "fun_name": "mixin_client_gateway_parser", "commit_message": "feat: improve client interface (#4510)\n\n* feat: add host unpacking\r\n\r\n* feat: add tests for host unpacking\r\n\r\n* feat: raise error when duplicate parameters def in client\r\n\r\n* fix: batter url host parsing\r\n\r\n* feat: rename https to tls\r\n\r\n* feat: add deprecation warning for https arg\r\n\r\n* feat: add docs\r\n\r\n* feat: update docs\r\n\r\n* fix: type hint for classes\r\n\r\n* fix: missing renaming https tls\r\n\r\n* style: fix overload and cli autocomplete\r\n\r\n* fix: fix grammar in the docs\r\n\r\n* fix: fix grammar in the docs\r\n\r\n* fix: update docs\r\n\r\nCo-authored-by: Tobias Jacobowitz \r\n\r\n* fix: update docs\r\n\r\nCo-authored-by: Tobias Jacobowitz \r\n\r\nCo-authored-by: Jina Dev Bot \r\nCo-authored-by: Tobias Jacobowitz ", "code": "def mixin_client_gateway_parser(parser):\n \n gp = add_arg_group(parser, title='ClientGateway')\n _add_host(gp)\n _add_proxy(gp)\n\n gp.add_argument(\n '--port',\n type=int,\n default=helper.random_port(),\n help='The port of the Gateway, which the client should connect to.',\n )\n\n gp.add_argument(\n '--tls',\n action='store_true',\n default=False,\n help='If set, connect to gateway using tls encryption',\n )\n\n gp.add_argument(\n '--https',\n action=get_deprecation_renamed_action('--tls', _StoreTrueAction),\n # action='store_true',\n default=False,\n help='If set, connect to gateway using https',\n dest='tls',\n )\n\n", "url": "https://github.com/jina-ai/jina.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 181, "n_words": 53, "vocab_size": 39, "complexity": 1, "nloc": 23, "token_counts": 94, "n_ast_nodes": 160, "n_identifiers": 18 }, { "id": 87079, "commit_id": "8c51b98545d71ed7ef0b3b924db13461e924023a", "repo": "sentry", "path": "tests/sentry/api/endpoints/test_project_details.py", "file_name": "test_project_details.py", "fun_name": "test_no_dynamic_sampling_returned_from_get_on_am2_plan", "commit_message": "feat(ds): Handle GET and PUT in project details for v2 dynamic sampling [TET-475] (#40181)\n\nEnsures that when new AM2 plan flag is enabled GET request does not\r\nreturn `dynamicSampling` data in response, and for PUT request guards\r\nagainst storing `dynamicSampling` data. Also, handles popping\r\n`dynamicSampling` data from response if a PUT request is made to update\r\nsome other project fields", "code": "def test_no_dynamic_sampling_returned_from_get_on_am2_plan(self):\n \n dynamic_sampling_data = {\n \"rules\": [\n {\n \"sampleRate\": 0.7,\n \"type\": \"trace\",\n \"active\": True,\n \"condition\": {\n \"op\": \"and\",\n \"inner\": [\n {\"op\": \"eq\", \"name\": \"field1\", \"value\": [\"val\"]},\n {\"op\": \"glob\", \"name\": \"field1\", \"value\": [\"val\"]},\n ],\n },\n \"id\": 1,\n },\n {\n \"sampleRate\": 0.8,\n \"type\": \"trace\",\n \"active\": True,\n \"condition\": {\n \"op\": \"and\",\n \"inner\": [],\n },\n \"id\": 2,\n },\n ],\n \"next_id\": 3,\n }\n\n self.project.update_option(\"sentry:dynamic_sampling\", dynamic_sampling_data)\n\n self.login_as(user=self.user)\n with Feature({\"organizations:dynamic-sampling-basic\": True}):\n response = self.get_success_response(\n self.organization.slug, self.project.slug, method=\"get\"\n )\n assert \"dynamicSampling\" not in response.data\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 18, "n_whitespaces": 656, "n_words": 76, "vocab_size": 51, "complexity": 1, "nloc": 36, "token_counts": 180, "n_ast_nodes": 323, "n_identifiers": 14 }, { "id": 291083, "commit_id": "a7caa038be2c0b05b53756ba6c9563854b2ca1ea", "repo": "core", "path": "homeassistant/components/bluetooth/scanner.py", "file_name": "scanner.py", "fun_name": "_async_stop_scanner", "commit_message": "Accept advertisements from alternate scanners when a scanner stops scanning (#82448)", "code": "async def _async_stop_scanner(self) -> None:\n \n self.scanning = False\n _LOGGER.debug(\"%s: Stopping bluetooth discovery\", self.name)\n try:\n await self.scanner.stop() # type: ignore[no-untyped-call]\n except BleakError as ex:\n # This is not fatal, and they may want to reload\n # the config entry to restart the scanner if they\n # change the bluetooth dongle.\n _LOGGER.error(\"%s: Error stopping scanner: %s\", self.name, ex)\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 147, "n_words": 56, "vocab_size": 48, "complexity": 2, "nloc": 8, "token_counts": 50, "n_ast_nodes": 92, "n_identifiers": 11 }, { "id": 249561, "commit_id": "8ab16a92edd675453c78cfd9974081e374b0f998", "repo": "synapse", "path": "tests/storage/test_event_chain.py", "file_name": "test_event_chain.py", "fun_name": "_generate_room", "commit_message": "Persist CreateRoom events to DB in a batch (#13800)", "code": "def _generate_room(self) -> Tuple[str, List[Set[str]]]:\n \n room_id = self.helper.create_room_as(self.user_id, tok=self.token)\n\n # Mark the room as not having a chain cover index\n self.get_success(\n self.store.db_pool.simple_update(\n table=\"rooms\",\n keyvalues={\"room_id\": room_id},\n updatevalues={\"has_auth_chain_index\": False},\n desc=\"test\",\n )\n )\n\n # Create a fork in the DAG with different events.\n event_handler = self.hs.get_event_creation_handler()\n latest_event_ids = self.get_success(\n self.store.get_prev_events_for_room(room_id)\n )\n event, context = self.get_success(\n event_handler.create_event(\n self.requester,\n {\n \"type\": \"some_state_type\",\n \"state_key\": \"\",\n \"content\": {},\n \"room_id\": room_id,\n \"sender\": self.user_id,\n },\n prev_event_ids=latest_event_ids,\n )\n )\n self.get_success(\n event_handler.handle_new_client_event(\n self.requester, events_and_context=[(event, context)]\n )\n )\n state1 = set(self.get_success(context.get_current_state_ids()).values())\n\n event, context = self.get_success(\n event_handler.create_event(\n self.requester,\n {\n \"type\": \"some_state_type\",\n \"state_key\": \"\",\n \"content\": {},\n \"room_id\": room_id,\n \"sender\": self.user_id,\n },\n prev_event_ids=latest_event_ids,\n )\n )\n self.get_success(\n event_handler.handle_new_client_event(\n self.requester, events_and_context=[(event, context)]\n )\n )\n state2 = set(self.get_success(context.get_current_state_ids()).values())\n\n # Delete the chain cover info.\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 777, "n_words": 116, "vocab_size": 65, "complexity": 1, "nloc": 56, "token_counts": 306, "n_ast_nodes": 456, "n_identifiers": 37 }, { "id": 249741, "commit_id": "8756d5c87efc5637da55c9e21d2a4eb2369ba693", "repo": "synapse", "path": "synapse/storage/databases/main/registration.py", "file_name": "registration.py", "fun_name": "_delete_expired_login_tokens", "commit_message": "Save login tokens in database (#13844)\n\n* Save login tokens in database\r\n\r\nSigned-off-by: Quentin Gliech \r\n\r\n* Add upgrade notes\r\n\r\n* Track login token reuse in a Prometheus metric\r\n\r\nSigned-off-by: Quentin Gliech ", "code": "async def _delete_expired_login_tokens(self) -> None:\n \n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 12, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 9, "token_counts": 41, "n_ast_nodes": 17, "n_identifiers": 2 }, { "id": 43119, "commit_id": "08b675cf6642171cb1c5ddfb09607b541db70b29", "repo": "airflow", "path": "docs/exts/provider_yaml_utils.py", "file_name": "provider_yaml_utils.py", "fun_name": "load_package_data", "commit_message": "Fix links to sources for examples (#24386)\n\nThe links to example sources in exampleinclude have been broken in a\r\nnumber of providers and they were additionally broken by AIP-47.\r\n\r\nThis PR fixes it.\r\n\r\nFixes: #23632\r\nFixes: https://github.com/apache/airflow-site/issues/536", "code": "def load_package_data() -> List[Dict[str, Any]]:\n \n schema = _load_schema()\n result = []\n for provider_yaml_path in get_provider_yaml_paths():\n with open(provider_yaml_path) as yaml_file:\n provider = yaml.safe_load(yaml_file)\n try:\n jsonschema.validate(provider, schema=schema)\n except jsonschema.ValidationError:\n raise Exception(f\"Unable to parse: {provider_yaml_path}.\")\n provider_yaml_dir = os.path.dirname(provider_yaml_path)\n provider['python-module'] = _filepath_to_module(provider_yaml_dir)\n provider['package-dir'] = provider_yaml_dir\n provider['system-tests-dir'] = _filepath_to_system_tests(provider_yaml_dir)\n result.append(provider)\n return result\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 151, "n_words": 47, "vocab_size": 39, "complexity": 3, "nloc": 21, "token_counts": 112, "n_ast_nodes": 194, "n_identifiers": 26 }, { "id": 310837, "commit_id": "76bfbbafe1ef3761c75e397c285e8057db926fe4", "repo": "core", "path": "homeassistant/components/unifi/switch.py", "file_name": "switch.py", "fun_name": "async_turn_on", "commit_message": "Update method names reflecting changes in UniFi library (#64817)\n\n* Update method names\r\n\r\n* Bump dependency to v30", "code": "async def async_turn_on(self, **kwargs):\n \n await self.device.set_port_poe_mode(self.client.switch_port, self.poe_mode)\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 21, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 2, "token_counts": 26, "n_ast_nodes": 44, "n_identifiers": 8 }, { "id": 3770, "commit_id": "a3aae8017a0a40ff2006e2567f71dccb04c997a5", "repo": "airbyte", "path": "airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/base_streams.py", "file_name": "base_streams.py", "fun_name": "_filter_all_statuses", "commit_message": "🎉 🎉 Source FB Marketing: performance and reliability fixes (#9805)\n\n* Facebook Marketing performance improvement\r\n\r\n* add comments and little refactoring\r\n\r\n* fix integration tests with the new config\r\n\r\n* improve job status handling, limit concurrency to 10\r\n\r\n* fix campaign jobs, refactor manager\r\n\r\n* big refactoring of async jobs, support random order of slices\r\n\r\n* update source _read_incremental to hook new state logic\r\n\r\n* fix issues with timeout\r\n\r\n* remove debugging and clean up, improve retry logic\r\n\r\n* merge changes from #8234\r\n\r\n* fix call super _read_increment\r\n\r\n* generalize batch execution, add use_batch flag\r\n\r\n* improve coverage, do some refactoring of spec\r\n\r\n* update test, remove overrides of source\r\n\r\n* add split by AdSet\r\n\r\n* add smaller insights\r\n\r\n* fix end_date < start_date case\r\n\r\n* add account_id to PK\r\n\r\n* add notes\r\n\r\n* fix new streams\r\n\r\n* fix reversed incremental stream\r\n\r\n* update spec.json for SAT\r\n\r\n* upgrade CDK and bump version\r\n\r\nCo-authored-by: Dmytro Rezchykov \r\nCo-authored-by: Eugene Kulak ", "code": "def _filter_all_statuses(self) -> MutableMapping[str, Any]:\n \n filt_values = [\n \"active\",\n \"archived\",\n \"completed\",\n \"limited\",\n \"not_delivering\",\n \"deleted\",\n \"not_published\",\n \"pending_review\",\n \"permanently_deleted\",\n \"recently_completed\",\n \"recently_rejected\",\n \"rejected\",\n \"scheduled\",\n \"inactive\",\n ]\n\n return {\n \"filtering\": [\n {\"field\": f\"{self.entity_prefix}.delivery_info\", \"operator\": \"IN\", \"value\": filt_values},\n ],\n }\n\n", "url": "https://github.com/airbytehq/airbyte.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 261, "n_words": 35, "vocab_size": 34, "complexity": 1, "nloc": 23, "token_counts": 68, "n_ast_nodes": 134, "n_identifiers": 7 }, { "id": 106796, "commit_id": "76185b240badc5a4134aacfd114b159d2884c041", "repo": "visdom", "path": "py/visdom/server/handlers/socket_handlers.py", "file_name": "socket_handlers.py", "fun_name": "get", "commit_message": "Splitting all handlers into socket and base handlers", "code": "def get(self):\n \n new_sub = ClientSocketWrapper(self.app)\n self.write(json.dumps({'success': True, 'sid': new_sub.sid}))\n\n\n# TODO refactor socket wrappers to one class", "url": "https://github.com/fossasia/visdom.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 37, "n_words": 17, "vocab_size": 17, "complexity": 1, "nloc": 3, "token_counts": 35, "n_ast_nodes": 63, "n_identifiers": 9 }, { "id": 146292, "commit_id": "0a9f966e63a1a1d38a1e291338384b1e84b3a2a9", "repo": "ray", "path": "python/ray/workflow/tests/test_dag_to_workflow.py", "file_name": "test_dag_to_workflow.py", "fun_name": "test_dag_to_workflow_options", "commit_message": "[workflow] Convert DAG to workflow (#22925)\n\n* convert DAG to a workflow\r\n\r\n* deduplicate\r\n\r\n* check duplication of steps\r\n\r\n* add test for object refs", "code": "def test_dag_to_workflow_options(workflow_start_regular_shared):\n \n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 5, "n_words": 2, "vocab_size": 2, "complexity": 1, "nloc": 6, "token_counts": 51, "n_ast_nodes": 13, "n_identifiers": 2 }, { "id": 176291, "commit_id": "b5d41847b8db0c82372faf69cd3a339d11da7ef0", "repo": "networkx", "path": "networkx/algorithms/shortest_paths/generic.py", "file_name": "generic.py", "fun_name": "average_shortest_path_length", "commit_message": "DOC: Update documentation to include callables for weight argument (#5307)\n\nUpdate docs to include functions as valid input for weight argument.", "code": "def average_shortest_path_length(G, weight=None, method=None):\n r\n single_source_methods = [\"unweighted\", \"dijkstra\", \"bellman-ford\"]\n all_pairs_methods = [\"floyd-warshall\", \"floyd-warshall-numpy\"]\n supported_methods = single_source_methods + all_pairs_methods\n\n if method is None:\n method = \"unweighted\" if weight is None else \"dijkstra\"\n if method not in supported_methods:\n raise ValueError(f\"method not supported: {method}\")\n\n n = len(G)\n # For the special case of the null graph, raise an exception, since\n # there are no paths in the null graph.\n if n == 0:\n msg = (\n \"the null graph has no paths, thus there is no average\"\n \"shortest path length\"\n )\n raise nx.NetworkXPointlessConcept(msg)\n # For the special case of the trivial graph, return zero immediately.\n if n == 1:\n return 0\n # Shortest path length is undefined if the graph is disconnected.\n if G.is_directed() and not nx.is_weakly_connected(G):\n raise nx.NetworkXError(\"Graph is not weakly connected.\")\n if not G.is_directed() and not nx.is_connected(G):\n raise nx.NetworkXError(\"Graph is not connected.\")\n\n # Compute all-pairs shortest paths.", "url": "https://github.com/networkx/networkx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 272, "n_words": 147, "vocab_size": 85, "complexity": 16, "nloc": 93, "token_counts": 239, "n_ast_nodes": 248, "n_identifiers": 17 }, { "id": 20351, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/pygments/formatters/img.py", "file_name": "img.py", "fun_name": "_create_drawables", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def _create_drawables(self, tokensource):\n \n lineno = charno = maxcharno = 0\n maxlinelength = linelength = 0\n for ttype, value in tokensource:\n while ttype not in self.styles:\n ttype = ttype.parent\n style = self.styles[ttype]\n # TODO: make sure tab expansion happens earlier in the chain. It\n # really ought to be done on the input, as to do it right here is\n # quite complex.\n value = value.expandtabs(4)\n lines = value.splitlines(True)\n # print lines\n for i, line in enumerate(lines):\n temp = line.rstrip('\\n')\n if temp:\n self._draw_text(\n self._get_text_pos(linelength, lineno),\n temp,\n font = self._get_style_font(style),\n text_fg = self._get_text_color(style),\n text_bg = self._get_text_bg_color(style),\n )\n temp_width, temp_hight = self.fonts.get_text_size(temp)\n linelength += temp_width\n maxlinelength = max(maxlinelength, linelength)\n charno += len(temp)\n maxcharno = max(maxcharno, charno)\n if line.endswith('\\n'):\n # add a line for each extra line in the value\n linelength = 0\n charno = 0\n lineno += 1\n self.maxlinelength = maxlinelength\n self.maxcharno = maxcharno\n self.maxlineno = lineno\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 677, "n_words": 144, "vocab_size": 89, "complexity": 6, "nloc": 31, "token_counts": 197, "n_ast_nodes": 318, "n_identifiers": 37 }, { "id": 320950, "commit_id": "611a6d5cb2f15182e14c2249d1b5cedc44385878", "repo": "qutebrowser", "path": "scripts/dev/build_release.py", "file_name": "build_release.py", "fun_name": "build_sdist", "commit_message": "build-release: Modernize\n\npathlib, type annotations, modern syntax, dataclasses", "code": "def build_sdist() -> List[Artifact]:\n \n utils.print_title(\"Building sdist\")\n\n dist_path = pathlib.Path('dist')\n _maybe_remove(dist_path)\n\n subprocess.run([sys.executable, '-m', 'build'], check=True)\n\n dist_files = list(dist_path.glob('*.tar.gz'))\n filename = f'qutebrowser-{qutebrowser.__version__}.tar.gz'\n assert dist_files == [dist_path / filename], dist_files\n dist_file = dist_files[0]\n\n subprocess.run(['gpg', '--detach-sign', '-a', str(dist_file)], check=True)\n\n by_ext = collections.defaultdict(list)\n\n with tarfile.open(dist_file) as tar:\n for tarinfo in tar.getmembers():\n if not tarinfo.isfile():\n continue\n path = pathlib.Path(*pathlib.Path(tarinfo.name).parts[1:])\n by_ext[path.suffix].append(path)\n\n assert '.pyc' not in by_ext\n\n utils.print_title(\"sdist contents\")\n\n for ext, paths in sorted(by_ext.items()):\n utils.print_subtitle(ext)\n print('\\n'.join(str(p) for p in paths))\n\n artifacts = [\n Artifact(\n path=dist_file,\n mimetype='application/gzip',\n description='Source release',\n ),\n Artifact(\n path=dist_file.with_suffix(dist_file.suffix + '.asc'),\n mimetype='application/pgp-signature',\n description='Source release - PGP signature',\n ),\n ]\n\n return artifacts\n\n", "url": "https://github.com/qutebrowser/qutebrowser.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 18, "n_whitespaces": 312, "n_words": 95, "vocab_size": 74, "complexity": 5, "nloc": 36, "token_counts": 261, "n_ast_nodes": 445, "n_identifiers": 48 }, { "id": 81074, "commit_id": "a0ccc8c92583db0a8cf8e36e06ca631c65fdaaec", "repo": "awx", "path": "awx/main/tasks/jobs.py", "file_name": "jobs.py", "fun_name": "pseudo_build_inventory", "commit_message": "Merge pull request #5784 from ansible/runner_changes_42 (#12083)", "code": "def pseudo_build_inventory(self, inventory_update, private_data_dir):\n \n src = inventory_update.source\n\n injector = None\n if inventory_update.source in InventorySource.injectors:\n injector = InventorySource.injectors[src]()\n\n if injector is not None:\n content = injector.inventory_contents(inventory_update, private_data_dir)\n # must be a statically named file\n self.write_private_data_file(private_data_dir, injector.filename, content, 'inventory', 0o700)\n rel_path = os.path.join('inventory', injector.filename)\n elif src == 'scm':\n rel_path = os.path.join('project', inventory_update.source_path)\n\n return rel_path\n", "url": "https://github.com/ansible/awx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 167, "n_words": 52, "vocab_size": 40, "complexity": 4, "nloc": 12, "token_counts": 104, "n_ast_nodes": 167, "n_identifiers": 18 }, { "id": 288029, "commit_id": "52307708c843b947a2d631f2fe7ddaa8bd9a90d7", "repo": "core", "path": "homeassistant/components/apcupsd/__init__.py", "file_name": "__init__.py", "fun_name": "sw_version", "commit_message": "Refactor apcupsd to use config flow (#64809)\n\n* Add Config Flow to APCUPSd integration and remove YAML support.\r\n\r\n* Hide the binary sensor if user does not select STATFLAG resource.\r\n\r\n* Add tests for config flows.\r\n\r\n* Simplify config flow code.\r\n\r\n* Spell fix.\r\n\r\n* Fix pylint warnings.\r\n\r\n* Simplify the code for config flow.\r\n\r\n* First attempt to implement import flows to suppport legacy YAML configurations.\r\n\r\n* Remove unnecessary log calls.\r\n\r\n* Wrap synchronous update call with `hass.async_add_executor_job`.\r\n\r\n* Import the YAML configurations when sensor platform is set up.\r\n\r\n* Move the logger call since the variables are not properly set up.\r\n\r\n* Add codeowner.\r\n\r\n* Fix name field of manifest.json.\r\n\r\n* Fix linting issue.\r\n\r\n* Fix incorrect dependency due to incorrect rebase.\r\n\r\n* Update codeowner and config flows via hassfest.\r\n\r\n* Postpone the deprecation warning to 2022.7.\r\n\r\n* Import future annotations for init file.\r\n\r\n* Add an newline at the end to make prettier happy.\r\n\r\n* Update github id.\r\n\r\n* Add type hints for return types of steps in config flow.\r\n\r\n* Move the deprecation date for YAML config to 2022.12.\r\n\r\n* Update according to reviews.\r\n\r\n* Use async_forward_entry_setups.\r\n\r\n* Add helper properties to `APCUPSdData` class.\r\n\r\n* Add device_info for binary sensor.\r\n\r\n* Simplify config flow.\r\n\r\n* Remove options flow strings.\r\n\r\n* update the tests according to the changes.\r\n\r\n* Add `entity_registry_enabled_default` to entities and use imported CONF_RESOURCES to disable entities instead of skipping them.\r\n\r\n* Update according to reviews.\r\n\r\n* Do not use model of the UPS as the title for the integration.\r\n\r\nInstead, simply use \"APCUPSd\" as the integration title and let the device info serve as title for each device instead.\r\n\r\n* Change schema to be a global variable.\r\n\r\n* Add more comments.\r\n\r\n* Rewrite the tests for config flows.\r\n\r\n* Fix enabled_by_default.\r\n\r\n* Show friendly titles in the integration.\r\n\r\n* Add import check in `async_setup_platform` to avoid importing in sensor platform setup.\r\n\r\n* Add import check in `async_setup_platform` to avoid importing in sensor platform setup.\r\n\r\n* Update comments in test files.\r\n\r\n* Use parametrize instead of manually iterating different test cases.\r\n\r\n* Swap the order of the platform constants.\r\n\r\n* Avoid using broad exceptions.\r\n\r\n* Set up device info via `_attr_device_info`.\r\n\r\n* Remove unrelated test in `test_config_flow`.\r\n\r\n* Use `DeviceInfo` instead of dict to assign to `_attr_device_info`.\r\n\r\n* Add english translation.\r\n\r\n* Add `async_create_issue` for deprecated YAML configuration.\r\n\r\n* Enable UPS status by default since it could show \"online, charging, on battery etc\" which is meaningful for all users.\r\n\r\n* Apply suggestions from code review\r\n\r\n* Apply suggestion\r\n\r\n* Apply suggestion\r\n\r\nCo-authored-by: Martin Hjelmare ", "code": "def sw_version(self) -> str | None:\n \n return self.status.get(\"VERSION\")\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 22, "n_words": 8, "vocab_size": 8, "complexity": 1, "nloc": 3, "token_counts": 19, "n_ast_nodes": 35, "n_identifiers": 5 }, { "id": 26039, "commit_id": "098ff7b495ff9d37242ecdd38d9b08bfddb2cd19", "repo": "saleor", "path": "saleor/graphql/page/tests/queries/test_pages.py", "file_name": "test_pages.py", "fun_name": "test_query_pages_by_staff_no_perm", "commit_message": "Allow fetching unpublished pages by app with manage pages permission (#9181)\n\n* Allow fetching unpublished pages by app with manage pages permission\r\n\r\n* Update changelog", "code": "def test_query_pages_by_staff_no_perm(staff_api_client, page_list, page):\n \n\n # given\n unpublished_page = page\n unpublished_page.is_published = False\n unpublished_page.save(update_fields=[\"is_published\"])\n\n page_count = Page.objects.count()\n\n # when\n response = staff_api_client.post_graphql(PAGES_QUERY)\n\n # then\n content = get_graphql_content(response)\n data = content[\"data\"][\"pages\"][\"edges\"]\n assert len(data) == page_count - 1\n\n", "url": "https://github.com/saleor/saleor.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 71, "n_words": 35, "vocab_size": 27, "complexity": 1, "nloc": 9, "token_counts": 72, "n_ast_nodes": 126, "n_identifiers": 19 }, { "id": 165784, "commit_id": "6d7e004b1fc69942390d953bf21098a786c12c92", "repo": "pandas", "path": "pandas/core/arrays/interval.py", "file_name": "interval.py", "fun_name": "mid", "commit_message": "TYP: fix mid and length for Interval and Intervalarray (#46472)", "code": "def mid(self) -> Index:\n \n try:\n return 0.5 * (self.left + self.right)\n except TypeError:\n # datetime safe version\n return self.left + 0.5 * self.length\n\n _interval_shared_docs[\"overlaps\"] = textwrap.dedent(\n \n )\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 95, "n_words": 27, "vocab_size": 23, "complexity": 2, "nloc": 8, "token_counts": 39, "n_ast_nodes": 80, "n_identifiers": 10 }, { "id": 44105, "commit_id": "602abe8394fafe7de54df7e73af56de848cdf617", "repo": "airflow", "path": "airflow/models/variable.py", "file_name": "variable.py", "fun_name": "setdefault", "commit_message": "Remove `:type` lines now sphinx-autoapi supports typehints (#20951)\n\n* Remove `:type` lines now sphinx-autoapi supports typehints\r\n\r\nSince we have no updated sphinx-autoapi to a more recent version it\r\nsupports showing type hints in the documentation, so we don't need to\r\nhave the type hints _and_ the `:type` lines -- which is good, as the\r\nones in the doc strings are easy to get out of date!\r\n\r\nThe following settings have been set:\r\n\r\n`autodoc_typehints = 'description'` -- show types in description (where\r\nprevious `:type` used to show up)\r\n\r\n`autodoc_typehints_description_target = 'documented'` -- only link to\r\ntypes that are documented. (Without this we have some missing return\r\ntypes that aren't documented, and aren't linked to in our current python\r\nAPI docs, so this caused a build failure)\r\n\r\n`autodoc_typehints_format = 'short'` -- Shorten type hints where\r\npossible, i.e. `StringIO` instead of `io.StringIO`\r\n\r\n* Add argument type names to local spelling dictionary\r\n\r\nNow that we are using the type hints in the docs, sphinxcontrib-spelling\r\npicks them up as words to be checked, so we have to ignore them.\r\n\r\nI've chosen to add the provider specific ones to local dictionary files\r\nrather than the global, as for example, `mgmt` is an error in most\r\nplaces, but not in some of the Azure provider.", "code": "def setdefault(cls, key, default, description=None, deserialize_json=False):\n \n obj = Variable.get(key, default_var=None, deserialize_json=deserialize_json)\n if obj is None:\n if default is not None:\n Variable.set(key, default, description=description, serialize_json=deserialize_json)\n return default\n else:\n raise ValueError('Default Value must be set')\n else:\n return obj\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 142, "n_words": 36, "vocab_size": 27, "complexity": 3, "nloc": 10, "token_counts": 74, "n_ast_nodes": 113, "n_identifiers": 13 }, { "id": 100826, "commit_id": "ff6b0209dd5ad57b81b0aca570df7f39a7119bfb", "repo": "faceswap", "path": "plugins/train/model/_base/model.py", "file_name": "model.py", "fun_name": "state", "commit_message": "Refactoring and TravisCI to Github Actions (#1239)\n\n* refactor training\r\n\r\n* travis to actions", "code": "def state(self) -> \"State\":\n \n return self._state\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 12, "n_ast_nodes": 24, "n_identifiers": 3 }, { "id": 183586, "commit_id": "ee30b54828fa5212e0a30437f777b045dec4a8cc", "repo": "textual", "path": "src/textual/widget.py", "file_name": "widget.py", "fun_name": "_get_scrollbar_thicknesses", "commit_message": "[css] Add \"scrollbar-size\" CSS properties - first step", "code": "def _get_scrollbar_thicknesses(self) -> tuple[int, int]:\n \n vertical_scrollbar_size = horizontal_scrollbar_size = 1\n if self.styles.scrollbar_size_vertical is not None:\n vertical_scrollbar_size = int(self.styles.scrollbar_size_vertical.value)\n if self.styles.scrollbar_size_horizontal is not None:\n horizontal_scrollbar_size = int(self.styles.scrollbar_size_horizontal.value)\n return vertical_scrollbar_size, horizontal_scrollbar_size\n", "url": "https://github.com/Textualize/textual.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 86, "n_words": 29, "vocab_size": 19, "complexity": 3, "nloc": 12, "token_counts": 66, "n_ast_nodes": 104, "n_identifiers": 10 }, { "id": 299429, "commit_id": "a9ca774e7ed1d8fe502a53d5b765c1d9b393a524", "repo": "core", "path": "tests/components/insteon/test_api_properties.py", "file_name": "test_api_properties.py", "fun_name": "test_change_relay_mode", "commit_message": "Insteon Device Control Panel (#70834)\n\nCo-authored-by: Paulus Schoutsen ", "code": "async def test_change_relay_mode(hass, hass_ws_client, iolinc_properties_data):\n \n ws_client, devices = await _setup(\n hass, hass_ws_client, \"44.44.44\", iolinc_properties_data\n )\n device = devices[\"44.44.44\"]\n relay_prop = device.configuration[RELAY_MODE]\n assert relay_prop.value == RelayMode.MOMENTARY_A\n with patch.object(insteon.api.properties, \"devices\", devices):\n await ws_client.send_json(\n {\n ID: 2,\n TYPE: \"insteon/properties/change\",\n DEVICE_ADDRESS: \"44.44.44\",\n PROPERTY_NAME: RELAY_MODE,\n PROPERTY_VALUE: str(RelayMode.LATCHING).lower(),\n }\n )\n msg = await ws_client.receive_json()\n assert msg[\"success\"]\n assert relay_prop.new_value == RelayMode.LATCHING\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 214, "n_words": 54, "vocab_size": 43, "complexity": 1, "nloc": 20, "token_counts": 121, "n_ast_nodes": 196, "n_identifiers": 31 }, { "id": 266098, "commit_id": "27bf7b4a9add27b4f3f8b0f4fd5dfc4cfe74a65b", "repo": "netbox", "path": "netbox/extras/plugins/templates.py", "file_name": "templates.py", "fun_name": "list_buttons", "commit_message": "4751 Enable plugins to inject content within object list views (#10901)\n\n* 4751 add plugin buttons to list templates\r\n\r\n* 4751 add plugin buttons to list templates\r\n\r\n* 4751 add documentation\r\n\r\n* 4751 fix object reference\r\n\r\n* 4751 update docs", "code": "def list_buttons(self):\n \n raise NotImplementedError\n", "url": "https://github.com/netbox-community/netbox.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 18, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 8, "n_ast_nodes": 16, "n_identifiers": 3 }, { "id": 292688, "commit_id": "cfd763db40544c31077b46631bbdd9655581dfe9", "repo": "core", "path": "homeassistant/components/sonos/media.py", "file_name": "media.py", "fun_name": "poll_track_info", "commit_message": "Refactor Sonos media metadata handling (#66840)\n\nCo-authored-by: Paulus Schoutsen ", "code": "def poll_track_info(self) -> dict[str, Any]:\n \n track_info = self.soco.get_current_track_info()\n track_info[DURATION_SECONDS] = _timespan_secs(track_info.get(\"duration\"))\n track_info[POSITION_SECONDS] = _timespan_secs(track_info.get(\"position\"))\n return track_info\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 51, "n_words": 16, "vocab_size": 13, "complexity": 1, "nloc": 6, "token_counts": 52, "n_ast_nodes": 88, "n_identifiers": 12 }, { "id": 269503, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/backend.py", "file_name": "backend.py", "fun_name": "_get_available_gpus", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _get_available_gpus():\n \n if tf.compat.v1.executing_eagerly_outside_functions():\n # Returns names of devices directly.\n return [d.name for d in tf.config.list_logical_devices(\"GPU\")]\n\n global _LOCAL_DEVICES\n if _LOCAL_DEVICES is None:\n _LOCAL_DEVICES = get_session().list_devices()\n return [x.name for x in _LOCAL_DEVICES if x.device_type == \"GPU\"]\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 71, "n_words": 35, "vocab_size": 27, "complexity": 6, "nloc": 7, "token_counts": 65, "n_ast_nodes": 110, "n_identifiers": 14 }, { "id": 102165, "commit_id": "bb5b4cceb6f737448eaaa6817cd773b6f4b0e77d", "repo": "pytorch", "path": "tools/test/test_gen_backend_stubs.py", "file_name": "test_gen_backend_stubs.py", "fun_name": "test_supported_invalid_op", "commit_message": "Revert \"Revert D32498569: allow external backend codegen to toggle whether to generate out= and inplace kernels\" (#69950)\n\nSummary:\nPull Request resolved: https://github.com/pytorch/pytorch/pull/69950\n\nThis reverts commit f6cad53443704dfe5a20cc62bee14d91e3bffcaa.\n\nTest Plan: Imported from OSS\n\nReviewed By: albanD\n\nDifferential Revision: D33113545\n\nPulled By: bdhirsh\n\nfbshipit-source-id: d6590294662588d36c09662dea65919ad4e1e288", "code": "def test_supported_invalid_op(self) -> None:\n yaml_str = \n output_error = self.get_errors_from_gen_backend_stubs(yaml_str)\n self.assertExpectedInline(output_error, )\n\n # The backend is valid, but doesn't have a valid autograd key. They can't override autograd kernels in that case.\n # Only using Vulkan here because it has a valid backend key but not an autograd key- if this changes we can update the test.", "url": "https://github.com/pytorch/pytorch.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 83, "n_words": 56, "vocab_size": 48, "complexity": 1, "nloc": 8, "token_counts": 26, "n_ast_nodes": 49, "n_identifiers": 6 }, { "id": 288149, "commit_id": "7042d6d35be54865b1252c0b28a50cce1a92eabc", "repo": "core", "path": "homeassistant/components/esphome/bluetooth/service.py", "file_name": "service.py", "fun_name": "characteristics", "commit_message": "Add ESPHome BleakClient (#78911)\n\nCo-authored-by: Paulus Schoutsen ", "code": "def characteristics(self) -> list[BleakGATTCharacteristic]:\n \n return self.__characteristics\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 20, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 3, "token_counts": 15, "n_ast_nodes": 26, "n_identifiers": 5 }, { "id": 20293, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/pygments/formatters/__init__.py", "file_name": "__init__.py", "fun_name": "_load_formatters", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def _load_formatters(module_name):\n \n mod = __import__(module_name, None, None, ['__all__'])\n for formatter_name in mod.__all__:\n cls = getattr(mod, formatter_name)\n _formatter_cache[cls.name] = cls\n\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 42, "n_words": 19, "vocab_size": 15, "complexity": 2, "nloc": 5, "token_counts": 43, "n_ast_nodes": 68, "n_identifiers": 10 }, { "id": 43853, "commit_id": "17a594f8cbb7ff07dff4e7b6b3797d98ec5a9ac5", "repo": "airflow", "path": "tests/test_utils/config.py", "file_name": "config.py", "fun_name": "env_vars", "commit_message": "Test util `env_vars` to take arbitrary env vars (#20818)\n\nCurrently it assumes that you will only use this for config settings (which you can already do with `conf_vars`).\r\n\r\nWe should allow any kind of env var so that for example it could be used to patch an airflow conn or any other env var (which is sort of what is advertised in the function name anyway).", "code": "def env_vars(overrides):\n \n orig_vars = {}\n new_vars = []\n for env, value in overrides.items():\n if env in os.environ:\n orig_vars[env] = os.environ.pop(env, '')\n else:\n new_vars.append(env)\n os.environ[env] = value\n try:\n yield\n finally:\n for env, value in orig_vars.items():\n os.environ[env] = value\n for env in new_vars:\n os.environ.pop(env)\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 146, "n_words": 42, "vocab_size": 27, "complexity": 6, "nloc": 16, "token_counts": 100, "n_ast_nodes": 165, "n_identifiers": 11 }, { "id": 294231, "commit_id": "83983bc875445d7147cb98e70f1214c6ed270da9", "repo": "core", "path": "homeassistant/components/motion_blinds/cover.py", "file_name": "cover.py", "fun_name": "async_scheduled_update_request", "commit_message": "Motion request update till stop (#68580)\n\n* update untill stop\r\n\r\n* fixes\r\n\r\n* fix spelling", "code": "async def async_scheduled_update_request(self, *_):\n \n # add the last position to the list and keep the list at max 2 items\n self._previous_positions.append(self.current_cover_position)\n if len(self._previous_positions) > 2:\n del self._previous_positions[: len(self._previous_positions) - 2]\n\n await self.hass.async_add_executor_job(self._blind.Update_trigger)\n self.async_write_ha_state()\n\n if len(self._previous_positions) < 2 or not all(\n self.current_cover_position == prev_position\n for prev_position in self._previous_positions\n ):\n # keep updating the position @UPDATE_INTERVAL_MOVING until the position does not change.\n async_track_point_in_time(\n self.hass,\n self.async_scheduled_update_request,\n dt_util.utcnow() + timedelta(seconds=UPDATE_INTERVAL_MOVING),\n )\n else:\n self._previous_positions = []\n self._requesting_position = False\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 270, "n_words": 74, "vocab_size": 57, "complexity": 5, "nloc": 18, "token_counts": 125, "n_ast_nodes": 203, "n_identifiers": 21 }, { "id": 113930, "commit_id": "10a5300838e4ae45d42495fdf53d76c702f66518", "repo": "mindsdb", "path": "mindsdb/api/mysql/mysql_proxy/classes/sql_query.py", "file_name": "sql_query.py", "fun_name": "_parse_query", "commit_message": "Better error messaging in mysql api (#1911)\n\n* Better error messaging in mysql api", "code": "def _parse_query(self, sql):\n mindsdb_sql_struct = parse_sql(sql, dialect='mindsdb')\n\n # is it query to 'predictors'?\n if (\n isinstance(mindsdb_sql_struct.from_table, Identifier)\n and mindsdb_sql_struct.from_table.parts[-1].lower() == 'predictors'\n and (\n self.database == 'mindsdb'\n or mindsdb_sql_struct.from_table.parts[0].lower() == 'mindsdb'\n )\n ):\n\n dn = self.datahub.get(self.mindsdb_database_name)\n data, columns = dn.get_predictors(mindsdb_sql_struct)\n table_name = ('mindsdb', 'predictors', 'predictors')\n data = [{(key, key): value for key, value in row.items()} for row in data]\n data = [{table_name: x} for x in data]\n self.columns_list = [\n (table_name + (column_name, column_name))\n for column_name in columns\n ]\n\n columns = [(column_name, column_name) for column_name in columns]\n\n self.fetched_data = {\n 'values': data,\n 'columns': {table_name: columns},\n 'tables': [table_name]\n }\n return\n\n # is it query to 'commands'?\n if (\n isinstance(mindsdb_sql_struct.from_table, Identifier)\n and mindsdb_sql_struct.from_table.parts[-1].lower() == 'commands'\n and (\n self.database == 'mindsdb'\n or mindsdb_sql_struct.from_table.parts[0].lower() == 'mindsdb'\n )\n ):\n\n self.fetched_data = {\n 'values': [],\n 'columns': {('mindsdb', 'commands', 'commands'): [('command', 'command')]},\n 'tables': [('mindsdb', 'commands', 'commands')]\n }\n self.columns_list = [('mindsdb', 'commands', 'commands', 'command', 'command')]\n return\n\n # is it query to 'datasources'?\n if (\n isinstance(mindsdb_sql_struct.from_table, Identifier)\n and mindsdb_sql_struct.from_table.parts[-1].lower() == 'datasources'\n and (\n self.database == 'mindsdb'\n or mindsdb_sql_struct.from_table.parts[0].lower() == 'mindsdb'\n )\n ):\n\n dn = self.datahub.get(self.mindsdb_database_name)\n data, columns = dn.get_datasources(mindsdb_sql_struct)\n table_name = ('mindsdb', 'datasources', 'datasources')\n data = [{(key, key): value for key, value in row.items()} for row in data]\n data = [{table_name: x} for x in data]\n\n self.columns_list = [\n (table_name + (column_name, column_name))\n for column_name in columns\n ]\n\n columns = [(column_name, column_name) for column_name in columns]\n\n self.fetched_data = {\n 'values': data,\n 'columns': {table_name: columns},\n 'tables': [table_name]\n }\n return\n\n integrations_names = self.datahub.get_datasources_names()\n integrations_names.append('information_schema')\n integrations_names.append('files')\n\n all_tables = get_all_tables(mindsdb_sql_struct)\n\n predictor_metadata = {}\n predictors = db.session.query(db.Predictor).filter_by(company_id=self.session.company_id)\n for model_name in set(all_tables):\n for p in predictors:\n if p.name == model_name:\n if isinstance(p.data, dict) and 'error' not in p.data:\n ts_settings = p.learn_args.get('timeseries_settings', {})\n if ts_settings.get('is_timeseries') is True:\n window = ts_settings.get('window')\n order_by = ts_settings.get('order_by')[0]\n group_by = ts_settings.get('group_by')\n if isinstance(group_by, list) is False and group_by is not None:\n group_by = [group_by]\n predictor_metadata[model_name] = {\n 'timeseries': True,\n 'window': window,\n 'horizon': ts_settings.get('horizon'),\n 'order_by_column': order_by,\n 'group_by_columns': group_by\n }\n else:\n predictor_metadata[model_name] = {\n 'timeseries': False\n }\n self.model_types.update(p.data.get('dtypes', {}))\n\n plan = plan_query(\n mindsdb_sql_struct,\n integrations=integrations_names,\n predictor_namespace=self.mindsdb_database_name,\n predictor_metadata=predictor_metadata,\n default_namespace=self.database\n )\n\n steps_data = []\n for step in plan.steps:\n data = []\n if type(step) == GetPredictorColumns:\n predictor_name = step.predictor.parts[-1]\n dn = self.datahub.get(self.mindsdb_database_name)\n columns = dn.get_table_columns(predictor_name)\n columns = [\n (column_name, column_name) for column_name in columns\n ]\n data = {\n 'values': [],\n 'columns': {\n (self.mindsdb_database_name, predictor_name, predictor_name): columns\n },\n 'tables': [(self.mindsdb_database_name, predictor_name, predictor_name)]\n }\n elif type(step) == FetchDataframeStep:\n data = self._fetch_dataframe_step(step)\n elif type(step) == UnionStep:\n raise ErNotSupportedYet('Union step is not implemented')\n # TODO add union support\n # left_data = steps_data[step.left.step_num]\n # right_data = steps_data[step.right.step_num]\n # data = left_data + right_data\n elif type(step) == MapReduceStep:\n try:\n if step.reduce != 'union':\n raise Exception(f'Unknown MapReduceStep type: {step.reduce}')\n\n step_data = steps_data[step.values.step_num]\n vars = {}\n step_data_values = step_data['values']\n for row in step_data_values:\n for row_data in row.values():\n for name, value in row_data.items():\n if name[0] != '__mindsdb_row_id':\n vars[name[1] or name[0]] = value\n\n data = {\n 'values': [],\n 'columns': {},\n 'tables': []\n }\n substep = step.step\n if substep == FetchDataframeStep:\n query = substep.query\n markQueryVar(query.where)\n for name, value in vars.items():\n replaceQueryVar(query.where, value, name)\n sub_data = self._fetch_dataframe_step(substep)\n if len(data['columns']) == 0:\n data['columns'] = sub_data['columns']\n if len(data['tables']) == 0:\n data['tables'] = sub_data['tables']\n data['values'].extend(sub_data['values'])\n elif substep == MultipleSteps:\n data = self._multiple_steps_reduce(substep, vars)\n else:\n raise Exception(f'Unknown step type: {step.step}')\n except Exception as e:\n raise SqlApiException(\"error in map reduce step\") from e\n elif type(step) == ApplyPredictorRowStep:\n try:\n predictor = '.'.join(step.predictor.parts)\n dn = self.datahub.get(self.mindsdb_database_name)\n where_data = step.row_dict\n\n data = dn.select(\n table=predictor,\n columns=None,\n where_data=where_data,\n integration_name=self.session.integration,\n integration_type=self.session.integration_type\n )\n\n data = [{(key, key): value for key, value in row.items()} for row in data]\n\n table_name = get_preditor_alias(step, self.database)\n values = [{table_name: x} for x in data]\n columns = {table_name: []}\n if len(data) > 0:\n row = data[0]\n columns[table_name] = list(row.keys())\n # TODO else\n\n data = {\n 'values': values,\n 'columns': columns,\n 'tables': [table_name]\n }\n except Exception as e:\n raise SqlApiException(\"error in apply predictor row step.\") from e\n elif type(step) in (ApplyPredictorStep, ApplyTimeseriesPredictorStep):\n try:\n dn = self.datahub.get(self.mindsdb_database_name)\n predictor = '.'.join(step.predictor.parts)\n where_data = []\n for row in steps_data[step.dataframe.step_num]['values']:\n new_row = {}\n for table_name in row:\n keys_intersection = set(new_row) & set(row[table_name])\n if len(keys_intersection) > 0:\n raise Exception(\n f'The predictor got two identical keys from different datasources: {keys_intersection}'\n )\n new_row.update(row[table_name])\n where_data.append(new_row)\n\n where_data = [{key[1]: value for key, value in row.items()} for row in where_data]\n\n is_timeseries = predictor_metadata[predictor]['timeseries']\n _mdb_make_predictions = None\n if is_timeseries:\n if 'LATEST' in self.raw:\n _mdb_make_predictions = False\n else:\n _mdb_make_predictions = True\n for row in where_data:\n if '__mdb_make_predictions' not in row:\n row['__mdb_make_predictions'] = _mdb_make_predictions\n\n for row in where_data:\n for key in row:\n if isinstance(row[key], datetime.date):\n row[key] = str(row[key])\n\n data = dn.select(\n table=predictor,\n columns=None,\n where_data=where_data,\n integration_name=self.session.integration,\n integration_type=self.session.integration_type\n )\n\n # if is_timeseries:\n # if 'LATEST' not in self.raw:\n # # remove additional records from predictor results:\n # # first 'window_size' and last 'horizon' records\n # # otherwise there are many unxpected rows in prediciton result:\n # # ----------------------------------------------------------------------------------------\n # # mysql> SELECT tb.time, tb.state, tb.pnew_case, tb.new_case from\n # # MYSQL_LOCAL.test_data.covid AS\n # # ta JOIN mindsdb.covid_hor3 AS tb\n # # WHERE ta.state = \"CA\" AND ta.time BETWEEN \"2020-10-19\" AND \"2020-10-20\";\n # # ----------------------------------------------------------------------------------------\n # # +------------+-------+-----------+----------+\n # # | time | state | pnew_case | new_case |\n # # +------------+-------+-----------+----------+\n # # | 2020-10-09 | CA | 0 | 2862 |\n # # | 2020-10-10 | CA | 0 | 2979 |\n # # | 2020-10-11 | CA | 0 | 3075 |\n # # | 2020-10-12 | CA | 0 | 3329 |\n # # | 2020-10-13 | CA | 0 | 2666 |\n # # | 2020-10-14 | CA | 0 | 2378 |\n # # | 2020-10-15 | CA | 0 | 3449 |\n # # | 2020-10-16 | CA | 0 | 3803 |\n # # | 2020-10-17 | CA | 0 | 4170 |\n # # | 2020-10-18 | CA | 0 | 3806 |\n # # | 2020-10-19 | CA | 0 | 3286 |\n # # | 2020-10-20 | CA | 0 | 3474 |\n # # | 2020-10-21 | CA | 0 | 3474 |\n # # | 2020-10-22 | CA | 0 | 3474 |\n # # +------------+-------+-----------+----------+\n # # 14 rows in set (2.52 sec)\n\n # window_size = predictor_metadata[predictor]['window']\n # horizon = predictor_metadata[predictor]['horizon']\n # if len(data) >= (window_size + horizon):\n # data = data[window_size:]\n # if len(data) > horizon and horizon > 1:\n # data = data[:-horizon + 1]\n data = [{(key, key): value for key, value in row.items()} for row in data]\n\n table_name = get_preditor_alias(step, self.database)\n values = [{table_name: x} for x in data]\n columns = {table_name: []}\n if len(data) > 0:\n row = data[0]\n columns[table_name] = list(row.keys())\n # TODO else\n\n data = {\n 'values': values,\n 'columns': columns,\n 'tables': [table_name]\n }\n except Exception as e:\n raise SqlApiException(\"error in apply predictor step\") from e\n elif type(step) == JoinStep:\n try:\n left_data = steps_data[step.left.step_num]\n right_data = steps_data[step.right.step_num]\n\n # FIXME https://github.com/mindsdb/mindsdb_sql/issues/136\n is_timeseries = False\n if True in [type(step) == ApplyTimeseriesPredictorStep for step in plan.steps]:\n right_data = steps_data[step.left.step_num]\n left_data = steps_data[step.right.step_num]\n is_timeseries = True\n\n if step.query.condition is not None:\n raise Exception('At this moment supported only JOIN without condition')\n if step.query.join_type.upper() not in ('LEFT JOIN', 'JOIN'):\n raise Exception('At this moment supported only JOIN and LEFT JOIN')\n if (\n len(left_data['tables']) != 1 or len(right_data['tables']) != 1\n or left_data['tables'][0] == right_data['tables'][0]\n ):\n raise Exception('At this moment supported only JOIN of two different tables')\n\n data = {\n 'values': [],\n 'columns': {},\n 'tables': list(set(left_data['tables'] + right_data['tables']))\n }\n\n for data_part in [left_data, right_data]:\n for table_name in data_part['columns']:\n if table_name not in data['columns']:\n data['columns'][table_name] = data_part['columns'][table_name]\n else:\n data['columns'][table_name].extend(data_part['columns'][table_name])\n for table_name in data['columns']:\n data['columns'][table_name] = list(set(data['columns'][table_name]))\n\n left_key = left_data['tables'][0]\n right_key = right_data['tables'][0]\n\n left_columns_map = {}\n left_columns_map_reverse = {}\n for i, column_name in enumerate(left_data['columns'][left_key]):\n left_columns_map[f'a{i}'] = column_name\n left_columns_map_reverse[column_name] = f'a{i}'\n\n right_columns_map = {}\n right_columns_map_reverse = {}\n for i, column_name in enumerate(right_data['columns'][right_key]):\n right_columns_map[f'b{i}'] = column_name\n right_columns_map_reverse[column_name] = f'b{i}'\n\n left_df_data = []\n for row in left_data['values']:\n row = row[left_key]\n left_df_data.append({left_columns_map_reverse[key]: value for key, value in row.items()})\n\n right_df_data = []\n for row in right_data['values']:\n row = row[right_key]\n right_df_data.append({right_columns_map_reverse[key]: value for key, value in row.items()})\n\n df_a = pd.DataFrame(left_df_data)\n df_b = pd.DataFrame(right_df_data)\n\n a_name = f'a{round(time.time()*1000)}'\n b_name = f'b{round(time.time()*1000)}'\n con = duckdb.connect(database=':memory:')\n con.register(a_name, df_a)\n con.register(b_name, df_b)\n resp_df = con.execute(f).fetchdf()\n con.unregister(a_name)\n con.unregister(b_name)\n con.close()\n resp_df = resp_df.where(pd.notnull(resp_df), None)\n resp_dict = resp_df.to_dict(orient='records')\n\n for row in resp_dict:\n new_row = {left_key: {}, right_key: {}}\n for key, value in row.items():\n if key.startswith('a'):\n new_row[left_key][left_columns_map[key]] = value\n else:\n new_row[right_key][right_columns_map[key]] = value\n data['values'].append(new_row)\n\n # remove all records with empty data from predictor from join result\n # otherwise there are emtpy records in the final result:\n # +------------+------------+-------+-----------+----------+\n # | time | time | state | pnew_case | new_case |\n # +------------+------------+-------+-----------+----------+\n # | 2020-10-21 | 2020-10-24 | CA | 0.0 | 5945.0 |\n # | 2020-10-22 | 2020-10-23 | CA | 0.0 | 6141.0 |\n # | 2020-10-23 | 2020-10-22 | CA | 0.0 | 2940.0 |\n # | 2020-10-24 | 2020-10-21 | CA | 0.0 | 3707.0 |\n # | NULL | 2020-10-20 | NULL | nan | nan |\n # | NULL | 2020-10-19 | NULL | nan | nan |\n # | NULL | 2020-10-18 | NULL | nan | nan |\n # | NULL | 2020-10-17 | NULL | nan | nan |\n # | NULL | 2020-10-16 | NULL | nan | nan |\n # +------------+------------+-------+-----------+----------+\n # 9 rows in set (2.07 sec)\n\n # if is_timeseries:\n # data_values = []\n # for row in data['values']:\n # for key in row:\n # if 'mindsdb' in key:\n # if not is_empty_prediction_row(row[key]):\n # data_values.append(row)\n # break\n # data['values'] = data_values\n except Exception as e:\n raise SqlApiException(\"error in join step\") from e\n\n elif type(step) == FilterStep:\n raise ErNotSupportedYet('FilterStep is not implemented')\n # elif type(step) == ApplyTimeseriesPredictorStep:\n # raise Exception('ApplyTimeseriesPredictorStep is not implemented')\n elif type(step) == LimitOffsetStep:\n try:\n step_data = steps_data[step.dataframe.step_num]\n data = {\n 'values': step_data['values'].copy(),\n 'columns': step_data['columns'].copy(),\n 'tables': step_data['tables'].copy()\n }\n if isinstance(step.offset, Constant) and isinstance(step.offset.value, int):\n data['values'] = data['values'][step.offset.value:]\n if isinstance(step.limit, Constant) and isinstance(step.limit.value, int):\n data['values'] = data['values'][:step.limit.value]\n except Exception as e:\n raise SqlApiException(\"error in limit offset step\") from e\n elif type(step) == ProjectStep:\n try:\n step_data = steps_data[step.dataframe.step_num]\n columns_list = []\n for column_full_name in step.columns:\n table_name = None\n if type(column_full_name) == Star:\n for table_name, table_columns_list in step_data['columns'].items():\n for column in table_columns_list:\n columns_list.append(table_name + column)\n elif type(column_full_name) == Identifier:\n column_name_parts = column_full_name.parts\n column_alias = None if column_full_name.alias is None else '.'.join(column_full_name.alias.parts)\n if len(column_name_parts) > 2:\n raise Exception(f'Column name must contain no more than 2 parts. Got name: {\".\".join(column_full_name)}')\n elif len(column_name_parts) == 1:\n column_name = column_name_parts[0]\n\n appropriate_table = None\n if len(step_data['tables']) == 1:\n appropriate_table = step_data['tables'][0]\n else:\n for table_name, table_columns in step_data['columns'].items():\n if (column_name, column_name) in table_columns:\n if appropriate_table is not None:\n raise Exception('Found multiple appropriate tables for column {column_name}')\n else:\n appropriate_table = table_name\n if appropriate_table is None:\n # it is probably constaint\n # FIXME https://github.com/mindsdb/mindsdb_sql/issues/133\n # column_name = column_name.strip(\"'\")\n # name_or_alias = column_alias or column_name\n # column_alias = name_or_alias\n # for row in step_data['values']:\n # for table in row:\n # row[table][(column_name, name_or_alias)] = row[table][(column_name, column_name)]\n # appropriate_table = step_data['tables'][0]\n columns_list.append(appropriate_table + (column_alias, column_alias))\n else:\n columns_list.append(appropriate_table + (column_name, column_alias or column_name)) # column_name\n elif len(column_name_parts) == 2:\n table_name_or_alias = column_name_parts[0]\n column_name = column_name_parts[1]\n\n appropriate_table = None\n for table_name, table_columns in step_data['columns'].items():\n checkig_table_name_or_alias = table_name[2] or table_name[1]\n if table_name_or_alias == checkig_table_name_or_alias:\n for table_column_name in table_columns:\n if (\n table_column_name[1] == column_name\n or table_column_name[1] is None and table_column_name[0] == column_name\n ):\n break\n else:\n raise Exception(f'Can not find column \"{column_name}\" in table \"{table_name}\"')\n appropriate_table = table_name\n break\n if appropriate_table is None:\n raise Exception(f'Can not find approproate table for column {column_name}')\n\n columns_to_copy = None\n for column in step_data['columns'][appropriate_table]:\n if column[0] == column_name and (column[1] is None or column[1] == column_name):\n columns_to_copy = column\n break\n else:\n raise Exception(f'Can not find approproate column in data: {(column_name, column_alias)}')\n\n for row in step_data['values']:\n row[appropriate_table][(column_name, column_alias)] = row[appropriate_table][columns_to_copy]\n\n columns_list.append(appropriate_table + (column_name, column_alias))\n else:\n raise Exception('Undefined column name')\n else:\n raise Exception(f'Unexpected column name type: {column_full_name}')\n\n self.columns_list = columns_list\n data = step_data\n except Exception as e:\n raise SqlApiException(\"error on project step\") from e\n else:\n raise SqlApiException(F'Unknown planner step: {step}')\n steps_data.append(data)\n\n\n try:\n if self.outer_query is not None:\n data = []\n # +++\n result = []\n for row in steps_data[-1]:\n data_row = {}\n for column_record in self.columns_list:\n table_name = column_record[:3]\n column_name = column_record[3]\n data_row[column_record[4] or column_record[3]] = row[table_name][column_name]\n result.append(data_row)\n # ---\n data = self._make_list_result_view(result)\n df = pd.DataFrame(data)\n result = query_df(df, self.outer_query)\n\n try:\n self.columns_list = [\n ('', '', '', x, x) for x in result.columns\n ]\n except Exception:\n self.columns_list = [\n ('', '', '', result.name, result.name)\n ]\n\n # +++ make list result view\n new_result = []\n for row in result.to_dict(orient='records'):\n data_row = []\n for column_record in self.columns_list:\n column_name = column_record[4] or column_record[3]\n data_row.append(row.get(column_name))\n new_result.append(data_row)\n result = new_result\n # ---\n\n self.fetched_data = result\n else:\n self.fetched_data = steps_data[-1]\n except Exception as e:\n raise SqlApiException(\"error in preparing result quiery step\") from e\n\n try:\n if hasattr(self, 'columns_list') is False:\n self.columns_list = []\n for row in self.fetched_data:\n for table_key in row:\n for column_name in row[table_key]:\n if (table_key + (column_name, column_name)) not in self.columns_list:\n self.columns_list.append((table_key + (column_name, column_name)))\n\n # if there was no 'ProjectStep', then get columns list from last step:\n if self.columns_list is None:\n self.columns_list = []\n for table_name in self.fetched_data['columns']:\n self.columns_list.extend([\n table_name + column for column in self.fetched_data['columns'][table_name]\n ])\n\n self.columns_list = [x for x in self.columns_list if x[3] != '__mindsdb_row_id']\n except Exception as e:\n raise SqlApiException(\"error in column list step\") from e\n", "url": "https://github.com/mindsdb/mindsdb.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 32, "n_whitespaces": 13762, "n_words": 2169, "vocab_size": 671, "complexity": 153, "nloc": 451, "token_counts": 3320, "n_ast_nodes": 5598, "n_identifiers": 186 }, { "id": 280886, "commit_id": "e437f29ae498124b34a401015b001cb6c27c1e93", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/mutual_funds/mutual_fund_controller.py", "file_name": "mutual_fund_controller.py", "fun_name": "print_help", "commit_message": "Mutual funds (#1106)\n\n* Add mutual fund menu based primarily on investpy (investment.com)\r\n\r\n* Add start/end date for loading + some bug fixes\r\n\r\n* hugo\r\n\r\n* poetry add investpy rich dnspython then poetry update\r\n\r\n* fix reset (need to load country) and dim yfinance commands when country not US\r\n\r\n* Fix search and add better error handling\r\n\r\n* Catch yfinance commands when country not US. Improve loading to change country if symbol found but not in matching country. Changed main menu printing.\r\n\r\n* Fix poetry / reqs merge conflict\r\n\r\n* review comments\r\n\r\n* Once again update poetry\r\n\r\n* Clean up poetry to match conda (numpy was culprit)\r\n\r\n* cvxpy down\r\n\r\n* Think i goofed on generating reqs full\r\n\r\n* update poetry metadata\r\n\r\n* cleanup after review 2\r\n\r\n* move space\r\n\r\n* another deps try\r\n\r\n* bump pygmnets in yaml\r\n\r\n* try something different\r\n\r\n* rename console -> t_console (terminal_console) for mypy", "code": "def print_help(self):\n \n fund_string = f\"{self.fund_name or None}\"\n fund_string2 = f\" ({self.fund_symbol})\" if self.fund_symbol else \"\"\n fund_string += fund_string2\n help_str = f\n t_console.print(help_str)\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 64, "n_words": 22, "vocab_size": 18, "complexity": 2, "nloc": 29, "token_counts": 33, "n_ast_nodes": 188, "n_identifiers": 11 }, { "id": 186460, "commit_id": "a0dbe1e85035f12e194d91148836d830871ec554", "repo": "certbot", "path": "certbot-apache/tests/configurator_test.py", "file_name": "configurator_test.py", "fun_name": "test_ssl_config_files_hash_in_all_hashes", "commit_message": "Improve assertions in certbot-apache tests. (#9131)\n\n* Improve assertions in certbot-apache tests.\r\n\r\nReplacements inspired by flake8-assertive.\r\n\r\n* Fix test failures\r\n\r\n* assertEqual is not for None :D\r\n\r\n* Pass all tests :)", "code": "def test_ssl_config_files_hash_in_all_hashes(self):\n \n from certbot_apache._internal.constants import ALL_SSL_OPTIONS_HASHES\n import pkg_resources\n\n tls_configs_dir = pkg_resources.resource_filename(\n \"certbot_apache\", os.path.join(\"_internal\", \"tls_configs\"))\n all_files = [os.path.join(tls_configs_dir, name) for name in os.listdir(tls_configs_dir)\n if name.endswith('options-ssl-apache.conf')]\n self.assertGreaterEqual(len(all_files), 1)\n for one_file in all_files:\n file_hash = crypto_util.sha256sum(one_file)\n self.assertIn(\n file_hash, ALL_SSL_OPTIONS_HASHES,\n f\"Constants.ALL_SSL_OPTIONS_HASHES must be appended with the sha256 \"\n f\"hash of {one_file} when it is updated.\"\n )\n", "url": "https://github.com/certbot/certbot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 210, "n_words": 52, "vocab_size": 47, "complexity": 4, "nloc": 15, "token_counts": 102, "n_ast_nodes": 170, "n_identifiers": 23 }, { "id": 118736, "commit_id": "72703b38029f9358a0ec7ca5ed875a6b438ece19", "repo": "streamlit", "path": "lib/streamlit/elements/layouts.py", "file_name": "layouts.py", "fun_name": "container", "commit_message": "Replace static apps with live Cloud apps (#4317)\n\nCo-authored-by: kajarenc ", "code": "def container(self):\n \n return self.dg._block()\n\n # TODO: Enforce that columns are not nested or in Sidebar", "url": "https://github.com/streamlit/streamlit.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 32, "n_words": 15, "vocab_size": 15, "complexity": 1, "nloc": 2, "token_counts": 14, "n_ast_nodes": 27, "n_identifiers": 4 }, { "id": 268847, "commit_id": "9733982976f62c351ea3db2aeb1f28a67bb5d2fa", "repo": "keras", "path": "keras/engine/base_layer.py", "file_name": "base_layer.py", "fun_name": "_name_scope_unnester", "commit_message": "Fix tf.name_scope support for Keras nested layers.\n\nInfer nested layer structure inside `Layer.__call__`\n\nPiperOrigin-RevId: 423989336", "code": "def _name_scope_unnester(full_name_scope):\n \n if not getattr(_name_scope_unnester_stack, 'value', None):\n _name_scope_unnester_stack.value = ['']\n\n _name_scope_unnester_stack.value.append(full_name_scope)\n\n try:\n full_name_scope = _name_scope_unnester_stack.value[-1]\n outer_name_scope = _name_scope_unnester_stack.value[-2]\n relative_name_scope = full_name_scope.lstrip(outer_name_scope)\n relative_name_scope = relative_name_scope.lstrip('/')\n yield relative_name_scope\n finally:\n _name_scope_unnester_stack.value.pop()\n\n\n@keras_export('keras.layers.Layer')", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export('keras.layers.Layer')", "n_ast_errors": 1, "ast_levels": 11, "n_whitespaces": 54, "n_words": 29, "vocab_size": 23, "complexity": 3, "nloc": 12, "token_counts": 79, "n_ast_nodes": 148, "n_identifiers": 11 }, { "id": 108748, "commit_id": "a2540ac2387223a00af88f295121c9e5aa51079d", "repo": "matplotlib", "path": "lib/matplotlib/widgets.py", "file_name": "widgets.py", "fun_name": "clear", "commit_message": "Add internal method to clear without update to simplify code", "code": "def clear(self):\n \n self._clear_without_update()\n self.update()\n", "url": "https://github.com/matplotlib/matplotlib.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 25, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 3, "token_counts": 16, "n_ast_nodes": 31, "n_identifiers": 4 }, { "id": 262665, "commit_id": "3b8b105b0d6539ac12972de94e0b2a5077fa1ce2", "repo": "TTS", "path": "TTS/tts/layers/overflow/common_layers.py", "file_name": "common_layers.py", "fun_name": "logsumexp", "commit_message": "Adding OverFlow (#2183)\n\n* Adding encoder\r\n\r\n* currently modifying hmm\r\n\r\n* Adding hmm\r\n\r\n* Adding overflow\r\n\r\n* Adding overflow setting up flat start\r\n\r\n* Removing runs\r\n\r\n* adding normalization parameters\r\n\r\n* Fixing models on same device\r\n\r\n* Training overflow and plotting evaluations\r\n\r\n* Adding inference\r\n\r\n* At the end of epoch the test sentences are coming on cpu instead of gpu\r\n\r\n* Adding figures from model during training to monitor\r\n\r\n* reverting tacotron2 training recipe\r\n\r\n* fixing inference on gpu for test sentences on config\r\n\r\n* moving helpers and texts within overflows source code\r\n\r\n* renaming to overflow\r\n\r\n* moving loss to the model file\r\n\r\n* Fixing the rename\r\n\r\n* Model training but not plotting the test config sentences's audios\r\n\r\n* Formatting logs\r\n\r\n* Changing model name to camelcase\r\n\r\n* Fixing test log\r\n\r\n* Fixing plotting bug\r\n\r\n* Adding some tests\r\n\r\n* Adding more tests to overflow\r\n\r\n* Adding all tests for overflow\r\n\r\n* making changes to camel case in config\r\n\r\n* Adding information about parameters and docstring\r\n\r\n* removing compute_mel_statistics moved statistic computation to the model instead\r\n\r\n* Added overflow in readme\r\n\r\n* Adding more test cases, now it doesn't saves transition_p like tensor and can be dumped as json", "code": "def logsumexp(x, dim):\n r\n\n m, _ = x.max(dim=dim)\n mask = m == -float(\"inf\")\n s = (x - m.masked_fill_(mask, 0).unsqueeze(dim=dim)).exp().sum(dim=dim)\n return s.masked_fill_(mask, 1).log() + m.masked_fill_(mask, -float(\"inf\"))\n", "url": "https://github.com/coqui-ai/TTS.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 59, "n_words": 25, "vocab_size": 22, "complexity": 1, "nloc": 12, "token_counts": 88, "n_ast_nodes": 143, "n_identifiers": 14 }, { "id": 299859, "commit_id": "29bda196b5e0a90a2bea7e1797742236114afc1c", "repo": "core", "path": "tests/components/sensor/test_recorder.py", "file_name": "test_recorder.py", "fun_name": "record_meter_states", "commit_message": "Break apart recorder into tasks and core modules (#71222)", "code": "def record_meter_states(hass, zero, entity_id, _attributes, seq):\n \n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 9, "n_words": 6, "vocab_size": 6, "complexity": 3, "nloc": 54, "token_counts": 447, "n_ast_nodes": 21, "n_identifiers": 6 }, { "id": 272667, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/layers/merging/maximum.py", "file_name": "maximum.py", "fun_name": "maximum", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def maximum(inputs, **kwargs):\n \n return Maximum(**kwargs)(inputs)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 11, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 2, "token_counts": 18, "n_ast_nodes": 32, "n_identifiers": 4 }, { "id": 101377, "commit_id": "1022651eb8a7741014f5d2ec7cbfe882120dfa5f", "repo": "faceswap", "path": "scripts/convert.py", "file_name": "convert.py", "fun_name": "_convert_images", "commit_message": "Bugfix: convert - Gif Writer\n - Fix non-launch error on Gif Writer\n - convert plugins - linting\n - convert/fs_media/preview/queue_manager - typing\n - Change convert items from dict to Dataclass", "code": "def _convert_images(self) -> None:\n \n logger.debug(\"Converting images\")\n self._patch_threads.start()\n while True:\n self._check_thread_error()\n if self._disk_io.completion_event.is_set():\n logger.debug(\"DiskIO completion event set. Joining Pool\")\n break\n if self._patch_threads.completed():\n logger.debug(\"All patch threads completed\")\n break\n sleep(1)\n self._patch_threads.join()\n\n logger.debug(\"Putting EOF\")\n queue_manager.get_queue(\"convert_out\").put(\"EOF\")\n logger.debug(\"Converted images\")\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 193, "n_words": 33, "vocab_size": 30, "complexity": 4, "nloc": 18, "token_counts": 97, "n_ast_nodes": 180, "n_identifiers": 16 }, { "id": 260810, "commit_id": "60f16feaadaca28f9a1cc68d2f406201860d27e8", "repo": "scikit-learn", "path": "sklearn/cluster/_bisect_k_means.py", "file_name": "_bisect_k_means.py", "fun_name": "_predict_recursive", "commit_message": "MAINT Remove `x_squared_norms` arg from `k_means_lloyd` signature (#24264)\n\nCo-authored-by: Thomas J. Fan ", "code": "def _predict_recursive(self, X, sample_weight, cluster_node):\n \n if cluster_node.left is None:\n # This cluster has no subcluster. Labels are just the label of the cluster.\n return np.full(X.shape[0], cluster_node.label, dtype=np.int32)\n\n # Determine if data points belong to the left or right subcluster\n centers = np.vstack((cluster_node.left.center, cluster_node.right.center))\n if hasattr(self, \"_X_mean\"):\n centers += self._X_mean\n\n cluster_labels = _labels_inertia_threadpool_limit(\n X,\n sample_weight,\n centers,\n self._n_threads,\n return_inertia=False,\n )\n mask = cluster_labels == 0\n\n # Compute the labels for each subset of the data points.\n labels = np.full(X.shape[0], -1, dtype=np.int32)\n\n labels[mask] = self._predict_recursive(\n X[mask], sample_weight[mask], cluster_node.left\n )\n\n labels[~mask] = self._predict_recursive(\n X[~mask], sample_weight[~mask], cluster_node.right\n )\n\n return labels\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 310, "n_words": 95, "vocab_size": 67, "complexity": 3, "nloc": 22, "token_counts": 171, "n_ast_nodes": 254, "n_identifiers": 24 }, { "id": 19993, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_internal/utils/misc.py", "file_name": "misc.py", "fun_name": "is_wheel_installed", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def is_wheel_installed() -> bool:\n \n try:\n import pipenv.vendor.wheel as wheel # noqa: F401\n except ImportError:\n return False\n\n return True\n\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 45, "n_words": 18, "vocab_size": 17, "complexity": 2, "nloc": 9, "token_counts": 24, "n_ast_nodes": 42, "n_identifiers": 6 }, { "id": 156830, "commit_id": "c97193156a8ba6d9bf18c4e9f5d68830471aec74", "repo": "dask", "path": "dask/dataframe/tests/test_shuffle.py", "file_name": "test_shuffle.py", "fun_name": "test_set_index_interpolate_large_uint", "commit_message": "Revise divisions logic in from_pandas (#9221)\n\n* rewrite/fix sorted_division_locations\r\n\r\n* format\r\n\r\n* mem cleanup\r\n\r\n* fix some tests - but there is still an existing bug in merge_asof\r\n\r\n* saving partial test fixes\r\n\r\n* get test_dataframe.py passing\r\n\r\n* testing revisions\r\n\r\n* perfectly satisfy npartitions\r\n\r\n* tweak docstring\r\n\r\n* use npartitions=1 in cudf test (since it was only passing with one partition anyway)\r\n\r\n* avoid breaking dask-cudf (in most places)\r\n\r\n* reformat\r\n\r\n* fix groupby tests\r\n\r\n* avoid np.unique when possible\r\n\r\n* trigger linting\r\n\r\n* use 'correct' typing fix\r\n\r\n* remove type-ignore comment\r\n\r\n* Update dask/dataframe/io/tests/test_io.py\r\n\r\nCo-authored-by: Ian Rose \r\n\r\n* subtact out 'drift' to improve npartitions accuracy\r\n\r\n* remove none_chunksize\r\n\r\n* remove unnecessary assertions\r\n\r\n* tweak test changes\r\n\r\n* add new test for duplicates\r\n\r\n* simplify unique call\r\n\r\n* add gpu coverage\r\n\r\n* roll back unique change\r\n\r\n* avoid overstepping too many unique groups\r\n\r\nCo-authored-by: Ian Rose ", "code": "def test_set_index_interpolate_large_uint(engine):\n if engine == \"cudf\":\n # NOTE: engine == \"cudf\" requires cudf/dask_cudf,\n # will be skipped by non-GPU CI.\n\n cudf = pytest.importorskip(\"cudf\")\n dask_cudf = pytest.importorskip(\"dask_cudf\")\n\n \n df = pd.DataFrame(\n {\"x\": np.array([612509347682975743, 616762138058293247], dtype=np.uint64)}\n )\n\n if engine == \"cudf\":\n gdf = cudf.from_pandas(df)\n d = dask_cudf.from_cudf(gdf, npartitions=1)\n else:\n d = dd.from_pandas(df, 1)\n\n d1 = d.set_index(\"x\", npartitions=1)\n assert d1.npartitions == 1\n assert set(d1.divisions) == {612509347682975743, 616762138058293247}\n\n", "url": "https://github.com/dask/dask.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 146, "n_words": 63, "vocab_size": 45, "complexity": 3, "nloc": 16, "token_counts": 122, "n_ast_nodes": 205, "n_identifiers": 23 }, { "id": 281535, "commit_id": "82747072c511beb1b2672846ae2ee4aec53eb562", "repo": "OpenBBTerminal", "path": "gamestonk_terminal/stocks/backtesting/bt_controller.py", "file_name": "bt_controller.py", "fun_name": "print_help", "commit_message": "Terminal Wide Rich (#1161)\n\n* My idea for how we handle Rich moving forward\r\n\r\n* remove independent consoles\r\n\r\n* FIxed pylint issues\r\n\r\n* add a few vars\r\n\r\n* Switched print to console\r\n\r\n* More transitions\r\n\r\n* Changed more prints\r\n\r\n* Replaced all prints\r\n\r\n* Fixing tabulate\r\n\r\n* Finished replace tabulate\r\n\r\n* Finished removing rich from Tabulate\r\n\r\n* add Panel around menu\r\n\r\n* add GST watermark under feature flag\r\n\r\n* Fixed 46 tests\r\n\r\n* Delete test_screener[False].yaml\r\n\r\n* Delete test_screener[True].yaml\r\n\r\n* Fixed the rest of the tests\r\n\r\n* add help and source color vars and use rgb\r\n\r\n* rich on stocks/options\r\n\r\n* update rich on disc, dps, sia\r\n\r\n* rich in gov, ins and scr menus\r\n\r\n* ba and ca menus with rich\r\n\r\n* Fixed import issue\r\n\r\n* Fixed some tests\r\n\r\n* removed termcolor\r\n\r\n* Removed prettytable\r\n\r\n* add rich to remaining stocks menus\r\n\r\n* FIxed linting issue\r\n\r\n* Added James' changes\r\n\r\n* Updated dependencies\r\n\r\n* Add rich to cryptocurrency menu\r\n\r\n* refactor economy and forex\r\n\r\n* refactor etf with rich\r\n\r\n* refactor mfunds\r\n\r\n* refactor rich rest\r\n\r\n* not specify style so default color works well on any background\r\n\r\n* Fixing mypy issues\r\n\r\n* Updated tests\r\n\r\n* More test fixes\r\n\r\n* James' test fixes\r\n\r\n* Updating tests : stocks/screener - fix cassettes using BR\r\n\r\n* Updating tests : crypto\r\n\r\n* Updating tests : disable DEBUG_MODE\r\n\r\n* Updating tests : stocks/fa/yfinance\r\n\r\n* minor fixes that escape\r\n\r\n* Improve the rich table function (that replaces tabulate :D )\r\n\r\n* Fixed bad code\r\n\r\n* delete rogue file + dcf fix + NoConsole\r\n\r\n* sia mypy\r\n\r\n* fuck you linter\r\n\r\n* fuck you linter pt 2\r\n\r\n* skip hehe\r\n\r\n* i hate the black linter\r\n\r\n* ubuntu mypy attempt\r\n\r\n* Update : rich_config + gtff\r\n\r\n* Updating tests : conftest\r\n\r\n* Updating tests : stocks\r\n\r\n* Update : rich_config\r\n\r\n* Updating : rich_config\r\n\r\n* make panel configurable for Theodore :b\r\n\r\n* colors update\r\n\r\n* Merged\r\n\r\n* Updating : rich_config + feature_flags\r\n\r\n* Updating : rich_config\r\n\r\n* Updating tests : stocks\r\n\r\n* Updating : feature_flags\r\n\r\nCo-authored-by: DidierRLopes \r\nCo-authored-by: Chavithra PARANA \r\nCo-authored-by: james \r\nCo-authored-by: jose-donato ", "code": "def print_help(self):\n \n help_text = f\n console.print(text=help_text, menu=\"Stocks - Backtesting\")\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 30, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 11, "token_counts": 22, "n_ast_nodes": 54, "n_identifiers": 9 }, { "id": 20718, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/rich/console.py", "file_name": "console.py", "fun_name": "_check_buffer", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def _check_buffer(self) -> None:\n \n if self.quiet:\n del self._buffer[:]\n return\n with self._lock:\n if self._buffer_index == 0:\n if self.is_jupyter: # pragma: no cover\n from .jupyter import display\n\n display(self._buffer, self._render_buffer(self._buffer[:]))\n del self._buffer[:]\n else:\n text = self._render_buffer(self._buffer[:])\n del self._buffer[:]\n if text:\n try:\n if WINDOWS: # pragma: no cover\n # https://bugs.python.org/issue37871\n write = self.file.write\n for line in text.splitlines(True):\n write(line)\n else:\n self.file.write(text)\n self.file.flush()\n except UnicodeEncodeError as error:\n error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n raise\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 22, "n_whitespaces": 615, "n_words": 75, "vocab_size": 58, "complexity": 8, "nloc": 26, "token_counts": 148, "n_ast_nodes": 259, "n_identifiers": 20 }, { "id": 249628, "commit_id": "00c93d2e7ef5642c9cf900f3fdcfa229e70f843d", "repo": "synapse", "path": "tests/rest/media/v1/test_oembed.py", "file_name": "test_oembed.py", "fun_name": "test_cache_age", "commit_message": "Be more lenient in the oEmbed response parsing. (#14089)\n\nAttempt to parse any valid information from an oEmbed response\r\n(instead of bailing at the first unexpected data). This should allow\r\nfor more partial oEmbed data to be returned, resulting in better /\r\nmore URL previews, even if those URL previews are only partial.", "code": "def test_cache_age(self) -> None:\n \n # Correct-ish cache ages are allowed.\n for cache_age in (\"1\", 1.0, 1):\n result = self.parse_response({\"cache_age\": cache_age})\n self.assertEqual(result.cache_age, 1000)\n\n # Invalid cache ages are ignored.\n for cache_age in (\"invalid\", {}):\n result = self.parse_response({\"cache_age\": cache_age})\n self.assertIsNone(result.cache_age)\n\n # Cache age is optional.\n result = self.parse_response({})\n self.assertIsNone(result.cache_age)\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 147, "n_words": 47, "vocab_size": 32, "complexity": 3, "nloc": 10, "token_counts": 90, "n_ast_nodes": 149, "n_identifiers": 7 }, { "id": 134317, "commit_id": "9b29fd6501ff0e3e69d0333bf214482b86f9e97f", "repo": "ray", "path": "python/ray/train/trainer.py", "file_name": "trainer.py", "fun_name": "_fetch_next_result", "commit_message": "[AIR] Hard deprecate train.report, warn on air.session misuse (#29613)\n\nSigned-off-by: Antoni Baum antoni.baum@protonmail.com\r\n\r\nHard deprecates `ray.train.report` and other session functions and ensures that the user is informed when using `ray.air.session` if they are not in session for consistency with the old functions.", "code": "def _fetch_next_result(self) -> Optional[List[Dict]]:\n \n\n while True:\n results = self._backend_executor.get_next_results()\n if results is None:\n return None\n first_result = results[0]\n result_type = first_result.type\n if result_type is TrainingResultType.REPORT:\n result_data = [self._backend.decode_data(r.data) for r in results]\n return result_data\n elif result_type is TrainingResultType.CHECKPOINT:\n self._checkpoint_manager._process_checkpoint(\n results, decode_checkpoint_fn=self._backend.decode_data\n )\n # Iterate until next REPORT call or training has finished.\n else:\n raise TrainBackendError(\n f\"Unexpected result type: \"\n f\"{result_type}. \"\n f\"Expected one of \"\n f\"{[type in TrainingResultType]}\"\n )\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 375, "n_words": 69, "vocab_size": 54, "complexity": 6, "nloc": 31, "token_counts": 108, "n_ast_nodes": 187, "n_identifiers": 23 }, { "id": 176084, "commit_id": "26be7d28bdb4eb96c888e373e08f46e6b85711e3", "repo": "edgedb", "path": "tests/test_edgeql_for.py", "file_name": "test_edgeql_for.py", "fun_name": "test_edgeql_for_in_computable_09", "commit_message": "Add a `bag` type that tells assert_query_result to ignore order (#3314)\n\nassert_query_result currently supports using sets to ignore order,\r\nbut that doesn't work for objects, which can't be hashed or sorted.\r\n\r\nThere is a system for specifying a sort key for internal data, but it\r\nis way clunkier than just saying we don't care about the order.\r\n\r\nI converted some places that were using sort= to use this.", "code": "async def test_edgeql_for_in_computable_09(self):\n # This is basically test_edgeql_for_in_computable_01 but with\n # a WITH binding in front of the whole shape\n await self.assert_query_result(\n r", "url": "https://github.com/edgedb/edgedb.git", "language": "Python", "ast_errors": "\n # This is basically test_edgeql_for_in_computable_01 but with\n # a WITH binding in front of the whole shape\n await self.assert_query_result(\n r'''\n WITH\n U := (\n SELECT User {\n select_deck := (\n FOR letter IN {'I', 'B'}\n UNION (\n SELECT User.deck {User", "n_ast_errors": 2, "ast_levels": 6, "n_whitespaces": 54, "n_words": 23, "vocab_size": 22, "complexity": 1, "nloc": 30, "token_counts": 48, "n_ast_nodes": 34, "n_identifiers": 8 }, { "id": 150408, "commit_id": "9f6bba40af1a407f190a89f5c0c8b4e3f528ba46", "repo": "freqtrade", "path": "freqtrade/rpc/replicate/__init__.py", "file_name": "__init__.py", "fun_name": "start_threaded_loop", "commit_message": "initial concept for replicate, basic leader and follower logic", "code": "def start_threaded_loop(self):\n \n self._loop = asyncio.new_event_loop()\n\n if not self._thread:\n self._thread = Thread(target=self._loop.run_forever)\n self._thread.start()\n self._running = True\n else:\n raise RuntimeError(\"A loop is already running\")\n", "url": "https://github.com/freqtrade/freqtrade.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 94, "n_words": 22, "vocab_size": 20, "complexity": 2, "nloc": 8, "token_counts": 54, "n_ast_nodes": 94, "n_identifiers": 12 }, { "id": 276025, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/saving/saved_model/load.py", "file_name": "load.py", "fun_name": "_search_for_child_node", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _search_for_child_node(self, parent_id, path_to_child):\n \n if not path_to_child:\n return parent_id\n\n for child in self._proto.nodes[parent_id].children:\n if child.local_name == path_to_child[0]:\n return self._search_for_child_node(\n child.node_id, path_to_child[1:]\n )\n return None\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 123, "n_words": 24, "vocab_size": 21, "complexity": 4, "nloc": 9, "token_counts": 57, "n_ast_nodes": 87, "n_identifiers": 10 }, { "id": 299285, "commit_id": "66551e6fcbd063e53c13adc8a6462b8e00ce1450", "repo": "core", "path": "tests/components/cast/test_media_player.py", "file_name": "test_media_player.py", "fun_name": "test_group_media_states", "commit_message": "Add state buffering to media_player and use it in cast (#70802)", "code": "async def test_group_media_states(hass, mz_mock):\n \n entity_id = \"media_player.speaker\"\n reg = er.async_get(hass)\n\n info = get_fake_chromecast_info()\n\n chromecast, _ = await async_setup_media_player_cast(hass, info)\n _, conn_status_cb, media_status_cb, group_media_status_cb = get_status_callbacks(\n chromecast, mz_mock\n )\n\n connection_status = MagicMock()\n connection_status.status = \"CONNECTED\"\n conn_status_cb(connection_status)\n await hass.async_block_till_done()\n\n state = hass.states.get(entity_id)\n assert state is not None\n assert state.name == \"Speaker\"\n assert state.state == \"off\"\n assert entity_id == reg.async_get_entity_id(\"media_player\", \"cast\", str(info.uuid))\n\n group_media_status = MagicMock(images=None)\n player_media_status = MagicMock(images=None)\n\n # Player has no state, group is buffering -> Should report 'buffering'\n group_media_status.player_state = \"BUFFERING\"\n group_media_status_cb(str(FakeGroupUUID), group_media_status)\n await hass.async_block_till_done()\n state = hass.states.get(entity_id)\n assert state.state == \"buffering\"\n\n # Player has no state, group is playing -> Should report 'playing'\n group_media_status.player_state = \"PLAYING\"\n group_media_status_cb(str(FakeGroupUUID), group_media_status)\n await hass.async_block_till_done()\n state = hass.states.get(entity_id)\n assert state.state == \"playing\"\n\n # Player is paused, group is playing -> Should report 'paused'\n player_media_status.player_state = None\n player_media_status.player_is_paused = True\n media_status_cb(player_media_status)\n await hass.async_block_till_done()\n await hass.async_block_till_done()\n state = hass.states.get(entity_id)\n assert state.state == \"paused\"\n\n # Player is in unknown state, group is playing -> Should report 'playing'\n player_media_status.player_state = \"UNKNOWN\"\n media_status_cb(player_media_status)\n await hass.async_block_till_done()\n state = hass.states.get(entity_id)\n assert state.state == \"playing\"\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 311, "n_words": 172, "vocab_size": 76, "complexity": 1, "nloc": 41, "token_counts": 275, "n_ast_nodes": 474, "n_identifiers": 33 }, { "id": 259113, "commit_id": "279388d9ed2ea83194dd45a2d78161be30b43aa7", "repo": "scikit-learn", "path": "sklearn/feature_selection/_base.py", "file_name": "_base.py", "fun_name": "get_feature_names_out", "commit_message": "DOC Improve get_feature_names_out docstrings (#22718)\n\nCo-authored-by: Thomas J. Fan ", "code": "def get_feature_names_out(self, input_features=None):\n \n input_features = _check_feature_names_in(self, input_features)\n return input_features[self.get_support()]\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 30, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 3, "token_counts": 27, "n_ast_nodes": 44, "n_identifiers": 5 }, { "id": 299241, "commit_id": "b1a6521abd71c0086b24849acc44f02eaabccff6", "repo": "core", "path": "homeassistant/components/steam_online/coordinator.py", "file_name": "coordinator.py", "fun_name": "_async_update_data", "commit_message": "Add config flow to steam_online integration (#67261)\n\nCo-authored-by: Paulus Schoutsen ", "code": "async def _async_update_data(self) -> dict[str, dict[str, str | int]]:\n \n try:\n return await self.hass.async_add_executor_job(self._update)\n\n except (steam.api.HTTPError, steam.api.HTTPTimeoutError) as ex:\n if \"401\" in str(ex):\n raise ConfigEntryAuthFailed from ex\n raise UpdateFailed(ex) from ex\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 99, "n_words": 30, "vocab_size": 26, "complexity": 3, "nloc": 8, "token_counts": 70, "n_ast_nodes": 111, "n_identifiers": 15 }, { "id": 269554, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/backend.py", "file_name": "backend.py", "fun_name": "ctc_batch_cost", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def ctc_batch_cost(y_true, y_pred, input_length, label_length):\n \n label_length = tf.cast(tf.squeeze(label_length, axis=-1), tf.int32)\n input_length = tf.cast(tf.squeeze(input_length, axis=-1), tf.int32)\n sparse_labels = tf.cast(\n ctc_label_dense_to_sparse(y_true, label_length), tf.int32\n )\n\n y_pred = tf.math.log(\n tf.compat.v1.transpose(y_pred, perm=[1, 0, 2]) + epsilon()\n )\n\n return tf.expand_dims(\n tf.compat.v1.nn.ctc_loss(\n inputs=y_pred, labels=sparse_labels, sequence_length=input_length\n ),\n 1,\n )\n\n\n@keras_export(\"keras.backend.ctc_decode\")\n@tf.__internal__.dispatch.add_dispatch_support\n@doc_controls.do_not_generate_docs", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "@keras_export(\"keras.backend.ctc_decode\")\n@tf.__internal__.dispatch.add_dispatch_support\n@doc_controls.do_not_generate_docs", "n_ast_errors": 1, "ast_levels": 13, "n_whitespaces": 114, "n_words": 44, "vocab_size": 37, "complexity": 1, "nloc": 15, "token_counts": 137, "n_ast_nodes": 232, "n_identifiers": 31 }, { "id": 43922, "commit_id": "d48a3a357fd89ec805d086d5b6c1f1d4daf77b9a", "repo": "airflow", "path": "tests/models/test_taskinstance.py", "file_name": "test_taskinstance.py", "fun_name": "test_written_task_map", "commit_message": "Add TaskMap and TaskInstance.map_id (#20286)\n\nCo-authored-by: Ash Berlin-Taylor ", "code": "def test_written_task_map(self, dag_maker, xcom_value, expected_length, expected_keys):\n \n with dag_maker(dag_id=\"test_written_task_map\") as dag:\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 24, "n_words": 10, "vocab_size": 10, "complexity": 3, "nloc": 15, "token_counts": 119, "n_ast_nodes": 42, "n_identifiers": 8 }, { "id": 266111, "commit_id": "a5308ea28e851a4ddb65a4e7ca2297b641e5891f", "repo": "netbox", "path": "netbox/netbox/staging.py", "file_name": "staging.py", "fun_name": "post_save_handler", "commit_message": "Closes #10851: New staging mechanism (#10890)\n\n* WIP\r\n\r\n* Convert checkout() context manager to a class\r\n\r\n* Misc cleanup\r\n\r\n* Drop unique constraint from Change model\r\n\r\n* Extend staging tests\r\n\r\n* Misc cleanup\r\n\r\n* Incorporate M2M changes\r\n\r\n* Don't cancel wipe out creation records when an object is deleted\r\n\r\n* Rename Change to StagedChange\r\n\r\n* Add documentation for change staging", "code": "def post_save_handler(self, sender, instance, **kwargs):\n \n key = self.get_key_for_instance(instance)\n object_type = instance._meta.verbose_name\n\n # Creating a new object\n if kwargs.get('created'):\n logger.debug(f\"[{self.branch}] Staging creation of {object_type} {instance} (PK: {instance.pk})\")\n data = serialize_object(instance, resolve_tags=False)\n self.queue[key] = (ChangeActionChoices.ACTION_CREATE, data)\n return\n\n # Ignore pre_* many-to-many actions\n if 'action' in kwargs and kwargs['action'] not in ('post_add', 'post_remove', 'post_clear'):\n return\n\n # Object has already been created/updated in the queue; update its queued representation\n if key in self.queue:\n logger.debug(f\"[{self.branch}] Updating staged value for {object_type} {instance} (PK: {instance.pk})\")\n data = serialize_object(instance, resolve_tags=False)\n self.queue[key] = (self.queue[key][0], data)\n return\n\n # Modifying an existing object for the first time\n logger.debug(f\"[{self.branch}] Staging changes to {object_type} {instance} (PK: {instance.pk})\")\n data = serialize_object(instance, resolve_tags=False)\n self.queue[key] = (ChangeActionChoices.ACTION_UPDATE, data)\n", "url": "https://github.com/netbox-community/netbox.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 302, "n_words": 112, "vocab_size": 70, "complexity": 5, "nloc": 18, "token_counts": 164, "n_ast_nodes": 332, "n_identifiers": 22 }, { "id": 124249, "commit_id": "096c0cd66802f0eb86301343180eddb3eae0f03a", "repo": "ray", "path": "python/ray/tests/test_advanced_9.py", "file_name": "test_advanced_9.py", "fun_name": "test_storage_isolation", "commit_message": "[core][gcs] Add storage namespace to redis storage in GCS. (#25994)\n\nTo enable one storage be able to be shared by multiple ray clusters, a special prefix is added to isolate the data between clusters: \"@\"\r\n\r\nThe namespace is given by an os environment: `RAY_external_storage_namespace` when start the head: `RAY_external_storage_namespace=1234 ray start --head`\r\n\r\nThis flag is very important in HA GCS environment. For example, in ray serve operator, when the operator tries to bring up a new one, it's hard to just start a new db, but it's relatively easy to generate a new cluster id.\r\nAnother example is that, the user might only be able to maintain one HA Redis DB, and the namespace enable the user to start multiple ray clusters which share the same db.\r\n\r\nThis config should be moved to storage config in the future once we build that.", "code": "def test_storage_isolation(external_redis, call_ray_start, call_ray_start_2):\n script = ", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "script = \"\"\"\nimport ray\nray.init(\"{address}\", namespace=\"a\")@ray.remote", "n_ast_errors": 2, "ast_levels": 5, "n_whitespaces": 9, "n_words": 6, "vocab_size": 6, "complexity": 1, "nloc": 23, "token_counts": 75, "n_ast_nodes": 25, "n_identifiers": 7 }, { "id": 32190, "commit_id": "c1c79b06550b587b2a975016ef9d18b53258025b", "repo": "transformers", "path": "src/transformers/models/nllb/tokenization_nllb.py", "file_name": "tokenization_nllb.py", "fun_name": "as_target_tokenizer", "commit_message": "NLLB tokenizer (#18126)\n\n* NLLB tokenizer\r\n\r\n* Apply suggestions from code review - Thanks Stefan!\r\n\r\nCo-authored-by: Stefan Schweter \r\n\r\n* Final touches\r\n\r\n* Style :)\r\n\r\n* Update docs/source/en/model_doc/nllb.mdx\r\n\r\nCo-authored-by: Stefan Schweter \r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\n\r\n* PR reviews\r\n\r\n* Auto models\r\n\r\nCo-authored-by: Stefan Schweter \r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>", "code": "def as_target_tokenizer(self):\n \n self.set_tgt_lang_special_tokens(self.tgt_lang)\n yield\n self.set_src_lang_special_tokens(self.src_lang)\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 33, "n_words": 5, "vocab_size": 5, "complexity": 1, "nloc": 4, "token_counts": 23, "n_ast_nodes": 42, "n_identifiers": 6 }, { "id": 124881, "commit_id": "09a6e5336ad6ab3c41e4a16e906c778aee2450bc", "repo": "ray", "path": "python/ray/serve/tests/fault_tolerance_tests/test_controller_recovery.py", "file_name": "test_controller_recovery.py", "fun_name": "test_recover_start_from_replica_actor_names", "commit_message": "[Serve][Part2] Migrate the tests to use deployment graph api (#26507)", "code": "def test_recover_start_from_replica_actor_names(serve_instance):\n \n # Test failed to deploy with total of 2 replicas,\n # but first constructor call fails.", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 27, "n_words": 18, "vocab_size": 17, "complexity": 14, "nloc": 62, "token_counts": 343, "n_ast_nodes": 15, "n_identifiers": 2 }, { "id": 211968, "commit_id": "fca16442ae90afcd2ac61f4e554e538776730831", "repo": "bokeh", "path": "bokeh/document/document.py", "file_name": "document.py", "fun_name": "to_json", "commit_message": "Redesign serialization protocol (#11960)\n\n* Redesign serialization in bokeh\r\n\r\n* Redesign deserialization in bokehjs\r\n\r\n* Resolve type issues and test failures\r\n\r\n* Make 'bytes' serialization work in bokeh\r\n\r\n* Partially update bokeh's serialization tests\r\n\r\n* Resolve issues with cyclic references\r\n\r\n* Don't limit StaticGraphProvider to tuples\r\n\r\n* Make FixedTicker.ticks' type more flexible\r\n\r\n* Use np.array instead of np.ndarray\r\n\r\n* Remove references to BokehJSONEncoder\r\n\r\n* Resolve sphinx warnings related to JSON\r\n\r\n* Implement hybrid serialization for map/dict\r\n\r\n* Use === or !== with unset symbol\r\n\r\n* Finalize deserialization of refs\r\n\r\n* Remove 'old' attribute from ModelChangedEvent\r\n\r\n* Make ButtonClick.__init__ less restrictive\r\n\r\n* Use Map in StaticLayoutProvider.graph_layout\r\n\r\n* Start using Map for non-string keys\r\n\r\n* Fix plotting/file/line_on_off example\r\n\r\n* Don't denormalize specs in bokehjs\r\n\r\n* Hack around issues with resolving figure model\r\n\r\n* Remove special cases from defaults' tests\r\n\r\n* Temporarily update unit/bokeh/test_objects\r\n\r\n* Promote streaming/patching events and remove hints\r\n\r\n* Allow to stream/patch any property in bokehjs\r\n\r\n* Drop unneeded Property.serializable_value()\r\n\r\n* Set callback_invoker on hinted events\r\n\r\n* Simplify unit/bokeh/test_objects.py\r\n\r\n* Always preserve ndarrays even for dtype=\"object\"\r\n\r\n* Refine and normalize naming conventions\r\n\r\n* Remove unused functions\r\n\r\n* Move Model.to_json() to sphinxext.bokeh_model\r\n\r\n* Include references in serialized values\r\n\r\n* Actually encode data when streaming/patching\r\n\r\n* Robustify differential serialization\r\n\r\n* Allow bokehjs to send binary buffers\r\n\r\n* Add dtype=object code path to ColorSpec\r\n\r\n* Simplify definitions of data specs\r\n\r\n* Remove meaningless code comments\r\n\r\n* Introduce Bytes and replace Base64String\r\n\r\n* Add support for serialization of slices\r\n\r\n* Remove obsolete comment from property/dataspec.py\r\n\r\n* Add a comment regarding ndarray.tobytes()\r\n\r\n* Try serializing pandas' types last\r\n\r\n* Standardize error reporting\r\n\r\n* Resturucture bokehjs serialization code\r\n\r\n* Redesign default model resolution\r\n\r\n* Refactor 'kind' in document events\r\n\r\n* Don't depend on Document in Deserializer\r\n\r\n* Make Deserializer.encode() re-entrant\r\n\r\n* Move *Buffer to serialization/buffer\r\n\r\n* Finalize differential serialization\r\n\r\n* Serialize vectorized values as structures\r\n\r\n* Rename Event.{decode_json->from_serializable}\r\n\r\n* Don't use has_ref() in Model.to_serializable()\r\n\r\n* Handle circular object references in bokehjs\r\n\r\n* Reorganize serialization unit tests\r\n\r\n* Redesign model registry and qualified names\r\n\r\n* Remove the need for StaticSerializer\r\n\r\n* Make 'attributes' optional in type reps\r\n\r\n* Allow to serialize typed arrays as binary\r\n\r\n* Finalize handling of binary buffers\r\n\r\n* Use memoryview to further defer encoding\r\n\r\n* Test dict serialization and ordering\r\n\r\n* Downcast ndarrays {u}int{64->32} if possible\r\n\r\n* Add preliminary release/migration notes\r\n\r\n* Robustify encoding of objects and object refs\r\n\r\n* Remove support for serialization of relativedelta\r\n\r\n* Import pandas only if really necessary\r\n\r\n* Statically type bokeh.core.serialization\r\n\r\n* Add preliminary serialization's documentation\r\n\r\n* Add Deserializer.deserialize() for symmetric APIs\r\n\r\n* Handle streaming/patching/data events in io.notebook\r\n\r\n* Update handling of buffers in io.notebook\r\n\r\n* Properly serialize MessageSent event\r\n\r\n* Add a regression test for issue #11694\r\n\r\n* Preserve order of inherited properties\r\n\r\n* Add support for serialization of symbols\r\n\r\n* Update defaults' tests to use type=\"object\"\r\n\r\n* Move DocJson.version to the first entry\r\n\r\n* Add a preliminary regression test for #11930\r\n\r\n* Fix integration/glyphs/rect_log_axis.py\r\n\r\n* Fix value detection in dataspecs involving String\r\n\r\n* Remove an unnecessary type assertion", "code": "def to_json(self) -> DocJson:\n \n data_models = [ model for model in Model.model_class_reverse_map.values() if is_DataModel(model) ]\n\n serializer = Serializer()\n defs = serializer.encode(data_models)\n roots = serializer.encode(self._roots)\n\n doc_json = DocJson(\n version=__version__,\n title=self.title,\n defs=defs,\n roots=roots,\n )\n\n self.models.flush()\n return doc_json\n", "url": "https://github.com/bokeh/bokeh.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 142, "n_words": 35, "vocab_size": 29, "complexity": 3, "nloc": 19, "token_counts": 83, "n_ast_nodes": 132, "n_identifiers": 21 }, { "id": 261652, "commit_id": "758fe0d9c72ba343097003e7992c9239e58bfc63", "repo": "scikit-learn", "path": "sklearn/model_selection/tests/test_plot.py", "file_name": "test_plot.py", "fun_name": "test_learning_curve_display_default_usage", "commit_message": "FEA add LearningCurveDisplay to show plot learning curve (#24084)\n\nCo-authored-by: jeremie du boisberranger \r\nCo-authored-by: Arturo Amor <86408019+ArturoAmorQ@users.noreply.github.com>", "code": "def test_learning_curve_display_default_usage(pyplot, data):\n \n X, y = data\n estimator = DecisionTreeClassifier(random_state=0)\n\n train_sizes = [0.3, 0.6, 0.9]\n display = LearningCurveDisplay.from_estimator(\n estimator, X, y, train_sizes=train_sizes\n )\n\n import matplotlib as mpl\n\n assert display.errorbar_ is None\n\n assert isinstance(display.lines_, list)\n for line in display.lines_:\n assert isinstance(line, mpl.lines.Line2D)\n\n assert isinstance(display.fill_between_, list)\n for fill in display.fill_between_:\n assert isinstance(fill, mpl.collections.PolyCollection)\n assert fill.get_alpha() == 0.5\n\n assert display.score_name == \"Score\"\n assert display.ax_.get_xlabel() == \"Number of samples in the training set\"\n assert display.ax_.get_ylabel() == \"Score\"\n\n _, legend_labels = display.ax_.get_legend_handles_labels()\n assert legend_labels == [\"Testing metric\"]\n\n train_sizes_abs, train_scores, test_scores = learning_curve(\n estimator, X, y, train_sizes=train_sizes\n )\n\n assert_array_equal(display.train_sizes, train_sizes_abs)\n assert_allclose(display.train_scores, train_scores)\n assert_allclose(display.test_scores, test_scores)\n\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 199, "n_words": 98, "vocab_size": 68, "complexity": 3, "nloc": 27, "token_counts": 211, "n_ast_nodes": 313, "n_identifiers": 39 }, { "id": 310957, "commit_id": "b07f4ba398bf7f7fb65dd6f365454ed5ccfc8a58", "repo": "core", "path": "homeassistant/components/github/coordinator.py", "file_name": "coordinator.py", "fun_name": "fetch_data", "commit_message": "Cleanup GitHub sensor classes and descriptions (#64853)", "code": "async def fetch_data(self) -> IssuesPulls:\n \n pulls_count = 0\n pull_last = None\n issues_count = 0\n issue_last = None\n try:\n pull_response = await self._client.repos.pulls.list(\n self.repository,\n **{\"params\": {\"per_page\": 1}, \"etag\": self._pull_etag},\n )\n except GitHubNotModifiedException:\n # Return the last known data if the request result was not modified\n pulls_count = self.data.pulls_count\n pull_last = self.data.pull_last\n else:\n self._pull_etag = pull_response.etag\n pulls_count = pull_response.last_page_number or len(pull_response.data)\n pull_last = pull_response.data[0] if pull_response.data else None\n\n try:\n issue_response = await self._client.repos.issues.list(\n self.repository,\n **{\"params\": {\"per_page\": 1}, \"etag\": self._issue_etag},\n )\n except GitHubNotModifiedException:\n # Return the last known data if the request result was not modified\n issues_count = self.data.issues_count\n issue_last = self.data.issue_last\n else:\n self._issue_etag = issue_response.etag\n issues_count = (\n issue_response.last_page_number or len(issue_response.data)\n ) - pulls_count\n issue_last = issue_response.data[0] if issue_response.data else None\n\n if issue_last is not None and issue_last.pull_request:\n issue_response = await self._client.repos.issues.list(self.repository)\n for issue in issue_response.data:\n if not issue.pull_request:\n issue_last = issue\n break\n\n return IssuesPulls(\n issues_count=issues_count,\n issue_last=issue_last,\n pulls_count=pulls_count,\n pull_last=pull_last,\n )\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 651, "n_words": 148, "vocab_size": 77, "complexity": 11, "nloc": 44, "token_counts": 266, "n_ast_nodes": 427, "n_identifiers": 24 }, { "id": 26596, "commit_id": "bef5dc4fca6dbb4b67e3d00cabef66cbd0bb25a6", "repo": "saleor", "path": "saleor/graphql/order/tests/test_homepage.py", "file_name": "test_homepage.py", "fun_name": "test_homepage_events", "commit_message": "Update orderNumber field in OrderEvent type (#9447)", "code": "def test_homepage_events(order_events, staff_api_client, permission_manage_orders):\n query = \n response = staff_api_client.post_graphql(\n query, permissions=[permission_manage_orders]\n )\n content = get_graphql_content(response)\n edges = content[\"data\"][\"homepageEvents\"][\"edges\"]\n only_types = {\"PLACED\", \"PLACED_FROM_DRAFT\", \"ORDER_FULLY_PAID\"}\n assert {edge[\"node\"][\"type\"] for edge in edges} == only_types\n expected_numbers = set(\n OrderEvent.objects.filter(\n type__in=[\n OrderEvents.PLACED,\n OrderEvents.PLACED_FROM_DRAFT,\n OrderEvents.ORDER_FULLY_PAID,\n ]\n ).values_list(\"order__number\", flat=True)\n )\n assert {int(edge[\"node\"][\"orderNumber\"]) for edge in edges} == expected_numbers\n\n\nQUERY_ORDER_TOTAL = \n\n", "url": "https://github.com/saleor/saleor.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 171, "n_words": 53, "vocab_size": 38, "complexity": 3, "nloc": 31, "token_counts": 125, "n_ast_nodes": 212, "n_identifiers": 27 }, { "id": 112046, "commit_id": "2566badb06095b9e3ea16eb6f00fd58da65a95fd", "repo": "nni", "path": "nni/algorithms/compression/v2/pytorch/base/compressor.py", "file_name": "compressor.py", "fun_name": "get_origin2wrapped_parameter_name_map", "commit_message": "[Model Compression] Pruning Wrapper Refactor (#4488)", "code": "def get_origin2wrapped_parameter_name_map(self) -> Dict[str, str]:\n \n raise NotImplementedError()\n", "url": "https://github.com/microsoft/nni.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 21, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 10, "token_counts": 17, "n_ast_nodes": 29, "n_identifiers": 5 }, { "id": 189283, "commit_id": "ff9b332d6ad9d3e7e845d08d40a9970f4d08ff18", "repo": "aws-cli", "path": "awscli/utils.py", "file_name": "utils.py", "fun_name": "is_streaming_blob_type", "commit_message": "Document streaming blob type\n\nNot having streaming blobs documented is causing\nusers to pass in the wrong input for blob arguments.\nThis commit resolves the issue by explicitly marking\nstreaming blob types and auto-generating a usage note for\nstreaming blobs.", "code": "def is_streaming_blob_type(shape):\n \n return (shape and shape.type_name == 'blob' and\n shape.serialization.get('streaming', False))\n\n", "url": "https://github.com/aws/aws-cli.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 28, "n_words": 11, "vocab_size": 10, "complexity": 3, "nloc": 3, "token_counts": 27, "n_ast_nodes": 48, "n_identifiers": 5 }, { "id": 44419, "commit_id": "6fc6edf6af7f676bfa54ff3a2e6e6d2edb938f2e", "repo": "airflow", "path": "airflow/models/taskinstance.py", "file_name": "taskinstance.py", "fun_name": "key", "commit_message": "Make `airflow dags test` be able to execute Mapped Tasks (#21210)\n\n* Make `airflow dags test` be able to execute Mapped Tasks\r\n\r\nIn order to do this there were two steps required:\r\n\r\n- The BackfillJob needs to know about mapped tasks, both to expand them,\r\n and in order to update it's TI tracking\r\n- The DebugExecutor needed to \"unmap\" the mapped task to get the real\r\n operator back\r\n\r\nI was testing this with the following dag:\r\n\r\n```\r\nfrom airflow import DAG\r\nfrom airflow.decorators import task\r\nfrom airflow.operators.python import PythonOperator\r\nimport pendulum\r\n\r\n@task\r\ndef make_list():\r\n return list(map(lambda a: f'echo \"{a!r}\"', [1, 2, {'a': 'b'}]))\r\n\r\ndef consumer(*args):\r\n print(repr(args))\r\n\r\nwith DAG(dag_id='maptest', start_date=pendulum.DateTime(2022, 1, 18)) as dag:\r\n PythonOperator(task_id='consumer', python_callable=consumer).map(op_args=make_list())\r\n```\r\n\r\nIt can't \"unmap\" decorated operators successfully yet, so we're using\r\nold-school PythonOperator\r\n\r\nWe also just pass the whole value to the operator, not just the current\r\nmapping value(s)\r\n\r\n* Always have a `task_group` property on DAGNodes\r\n\r\nAnd since TaskGroup is a DAGNode, we don't need to store parent group\r\ndirectly anymore -- it'll already be stored\r\n\r\n* Add \"integation\" tests for running mapped tasks via BackfillJob\r\n\r\n* Only show \"Map Index\" in Backfill report when relevant\r\n\r\nCo-authored-by: Tzu-ping Chung ", "code": "def key(self) -> TaskInstanceKey:\n \n return TaskInstanceKey(self.dag_id, self.task_id, self.run_id, self.try_number, self.map_index)\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 24, "n_words": 10, "vocab_size": 10, "complexity": 1, "nloc": 3, "token_counts": 31, "n_ast_nodes": 47, "n_identifiers": 8 }, { "id": 64295, "commit_id": "61c5ad44d3fe282e453d77df8acd1fbf9642c44a", "repo": "erpnext", "path": "erpnext/stock/utils.py", "file_name": "utils.py", "fun_name": "get_incoming_rate", "commit_message": "refactor: get incoming fifo/lifo rate functions\n\nRe-use same logic for computing incoming rate.", "code": "def get_incoming_rate(args, raise_error_if_no_rate=True):\n\t\n\tfrom erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate\n\tif isinstance(args, str):\n\t\targs = json.loads(args)\n\n\tin_rate = 0\n\tif (args.get(\"serial_no\") or \"\").strip():\n\t\tin_rate = get_avg_purchase_rate(args.get(\"serial_no\"))\n\telse:\n\t\tvaluation_method = get_valuation_method(args.get(\"item_code\"))\n\t\tprevious_sle = get_previous_sle(args)\n\t\tif valuation_method in ('FIFO', 'LIFO'):\n\t\t\tif previous_sle:\n\t\t\t\tprevious_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')\n\t\t\t\tin_rate = _get_fifo_lifo_rate(previous_stock_queue, args.get(\"qty\") or 0, valuation_method) if previous_stock_queue else 0\n\t\telif valuation_method == 'Moving Average':\n\t\t\tin_rate = previous_sle.get('valuation_rate') or 0\n\n\tif not in_rate:\n\t\tvoucher_no = args.get('voucher_no') or args.get('name')\n\t\tin_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),\n\t\t\targs.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),\n\t\t\tcurrency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),\n\t\t\traise_error_if_no_rate=raise_error_if_no_rate)\n\n\treturn flt(in_rate)\n", "url": "https://github.com/frappe/erpnext.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 20, "n_whitespaces": 62, "n_words": 85, "vocab_size": 57, "complexity": 13, "nloc": 23, "token_counts": 235, "n_ast_nodes": 404, "n_identifiers": 26 }, { "id": 248275, "commit_id": "57f6c496d0e26b1b455de936bd950e1899a5ae25", "repo": "synapse", "path": "synapse/rest/media/v1/preview_url_resource.py", "file_name": "preview_url_resource.py", "fun_name": "_expire_url_cache_data", "commit_message": "URL preview cache expiry logs: INFO -> DEBUG, text clarifications (#12720)", "code": "async def _expire_url_cache_data(self) -> None:\n \n\n assert self._worker_run_media_background_jobs\n\n now = self.clock.time_msec()\n\n logger.debug(\"Running url preview cache expiry\")\n\n if not (await self.store.db_pool.updates.has_completed_background_updates()):\n logger.debug(\"Still running DB updates; skipping url preview cache expiry\")\n return\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 86, "n_words": 29, "vocab_size": 25, "complexity": 12, "nloc": 68, "token_counts": 329, "n_ast_nodes": 92, "n_identifiers": 12 }, { "id": 121981, "commit_id": "0400db959be865b3ca312ca3355824f0706723c7", "repo": "jax", "path": "jax/experimental/array.py", "file_name": "array.py", "fun_name": "_use_python_method", "commit_message": "Introduce class PyArray that contains the data members of python Array.\n\nA few key methods is implemented in C++ while the rest are still implmemented in python and added to the class later. A class decorator, @use_cpp_array, is added to add python methods to xc.Array.\n\nPiperOrigin-RevId: 473075244", "code": "def _use_python_method(f):\n \n # TODO(chky): remove 'type: ignore' on decorated property once mypy does a release\n if isinstance(f, property):\n _python_methods.add(cast(property, f).fget.__name__)\n elif isinstance(f, pxla.maybe_cached_property):\n _python_methods.add(f.func.__name__)\n else:\n _python_methods.add(f.__name__)\n return f\n\n@_use_cpp_array", "url": "https://github.com/google/jax.git", "language": "Python", "ast_errors": "@_use_cpp_array", "n_ast_errors": 1, "ast_levels": 13, "n_whitespaces": 43, "n_words": 29, "vocab_size": 28, "complexity": 3, "nloc": 8, "token_counts": 61, "n_ast_nodes": 104, "n_identifiers": 13 }, { "id": 140064, "commit_id": "5b9b4fa018af04089320b03394711c9916a61e23", "repo": "ray", "path": "python/ray/util/actor_pool.py", "file_name": "actor_pool.py", "fun_name": "get_next", "commit_message": "Ignore previous tasks before submitting ones via `map` and `map_unordered` (#23684)", "code": "def get_next(self, timeout=None, ignore_if_timedout=False):\n \n if not self.has_next():\n raise StopIteration(\"No more results to get\")\n if self._next_return_index >= self._next_task_index:\n raise ValueError(\n \"It is not allowed to call get_next() after get_next_unordered().\"\n )\n future = self._index_to_future[self._next_return_index]\n timeout_msg = \"Timed out waiting for result\"\n raise_timeout_after_ignore = False\n if timeout is not None:\n res, _ = ray.wait([future], timeout=timeout)\n if not res:\n if not ignore_if_timedout:\n raise TimeoutError(timeout_msg)\n else:\n raise_timeout_after_ignore = True\n del self._index_to_future[self._next_return_index]\n self._next_return_index += 1\n\n future_key = tuple(future) if isinstance(future, list) else future\n i, a = self._future_to_actor.pop(future_key)\n\n self._return_actor(a)\n if raise_timeout_after_ignore:\n raise TimeoutError(\n timeout_msg + \". The task {} has been ignored.\".format(future)\n )\n return ray.get(future)\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 371, "n_words": 98, "vocab_size": 71, "complexity": 8, "nloc": 27, "token_counts": 166, "n_ast_nodes": 271, "n_identifiers": 29 }, { "id": 293909, "commit_id": "816695cc96c19110ccda10431d92160ea6064d32", "repo": "core", "path": "homeassistant/components/recorder/history.py", "file_name": "history.py", "fun_name": "get_state", "commit_message": "Avoid selecting attributes in the history api when `no_attributes` is passed (#68352)", "code": "def get_state(hass, utc_point_in_time, entity_id, run=None, no_attributes=False):\n \n states = get_states(hass, utc_point_in_time, (entity_id,), run, None, no_attributes)\n return states[0] if states else None\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 29, "n_words": 20, "vocab_size": 18, "complexity": 2, "nloc": 3, "token_counts": 46, "n_ast_nodes": 63, "n_identifiers": 8 }, { "id": 309027, "commit_id": "8915b73f724b58e93284a823c0d2e99fbfc13e84", "repo": "core", "path": "homeassistant/components/mazda/sensor.py", "file_name": "sensor.py", "fun_name": "_get_distance_unit", "commit_message": "Use SensorEntityDescription in Mazda integration (#63423)\n\n* Use SensorEntityDescription in Mazda integration\r\n\r\n* Change lambdas to functions\r\n\r\n* Minor fixes\r\n\r\n* Address review comments", "code": "def _get_distance_unit(unit_system):\n \n if unit_system.name == CONF_UNIT_SYSTEM_IMPERIAL:\n return LENGTH_MILES\n return LENGTH_KILOMETERS\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 7, "n_whitespaces": 26, "n_words": 10, "vocab_size": 9, "complexity": 2, "nloc": 4, "token_counts": 17, "n_ast_nodes": 30, "n_identifiers": 6 }, { "id": 124544, "commit_id": "0c469e490e0ed5e6ca848c627f3b852382e2bf2a", "repo": "ray", "path": "rllib/policy/policy.py", "file_name": "policy.py", "fun_name": "get_state", "commit_message": "[RLlib] Checkpoint and restore connectors. (#26253)", "code": "def get_state(self) -> PolicyState:\n \n state = {\n # All the policy's weights.\n \"weights\": self.get_weights(),\n # The current global timestep.\n \"global_timestep\": self.global_timestep,\n }\n if self.config.get(\"enable_connectors\", False):\n # Checkpoint connectors state as well if enabled.\n connector_configs = {}\n if self.agent_connectors:\n connector_configs[\"agent\"] = self.agent_connectors.to_config()\n if self.action_connectors:\n connector_configs[\"action\"] = self.action_connectors.to_config()\n state[\"connector_configs\"] = connector_configs\n return state\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 215, "n_words": 51, "vocab_size": 39, "complexity": 4, "nloc": 23, "token_counts": 84, "n_ast_nodes": 149, "n_identifiers": 12 }, { "id": 170050, "commit_id": "5a4339f686225ed5eadc5c4b7d2508c0765ef577", "repo": "pandas", "path": "pandas/tests/io/test_sql.py", "file_name": "test_sql.py", "fun_name": "test_execute_fail", "commit_message": "TST/CLN: Ensure sqlite memory connections are closed (#49154)\n\n* TST/CLN: Use fixtures for TestXSQLite\r\n\r\n* More sqlite closing", "code": "def test_execute_fail(self, sqlite_buildin):\n create_sql = \n cur = sqlite_buildin.cursor()\n cur.execute(create_sql)\n\n sql.execute('INSERT INTO test VALUES(\"foo\", \"bar\", 1.234)', sqlite_buildin)\n sql.execute('INSERT INTO test VALUES(\"foo\", \"baz\", 2.567)', sqlite_buildin)\n\n with pytest.raises(sql.DatabaseError, match=\"Execution failed on sql\"):\n sql.execute('INSERT INTO test VALUES(\"foo\", \"bar\", 7)', sqlite_buildin)\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 89, "n_words": 36, "vocab_size": 24, "complexity": 1, "nloc": 16, "token_counts": 61, "n_ast_nodes": 107, "n_identifiers": 12 }, { "id": 39809, "commit_id": "0ef2b4aac220def202aa240db84cc3976c5d796b", "repo": "dash", "path": "dash/development/base_component.py", "file_name": "base_component.py", "fun_name": "_set_random_id", "commit_message": "improve error message and logic for _set_random_id exclusions", "code": "def _set_random_id(self):\n\n if hasattr(self, \"id\"):\n return getattr(self, \"id\")\n\n kind = f\"`{self._namespace}.{self._type}`\" # pylint: disable=no-member\n\n if getattr(self, \"persistence\", False):\n raise RuntimeError(\n f\n )\n if \"dash_snapshots\" in sys.modules:\n raise RuntimeError(\n f\n )\n\n v = str(uuid.UUID(int=rd.randint(0, 2 ** 128)))\n setattr(self, \"id\", v)\n return v\n", "url": "https://github.com/plotly/dash.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 175, "n_words": 41, "vocab_size": 31, "complexity": 4, "nloc": 28, "token_counts": 85, "n_ast_nodes": 164, "n_identifiers": 18 }, { "id": 162632, "commit_id": "09b49e1f688831c3ad7181decf38c90f8451e6c4", "repo": "yt-dlp", "path": "yt_dlp/YoutubeDL.py", "file_name": "YoutubeDL.py", "fun_name": "process_info", "commit_message": "Add pre-processor stage `after_filter`\n\n* Move `_match_entry` and `post_extract` to `process_video_result`. It is also left in `process_info` for API compat\n* `--list-...` options and `--force-write-archive` now obey filtering options\n* Move `SponsorBlockPP` to `after_filter`. Closes https://github.com/yt-dlp/yt-dlp/issues/2536\n* Reverts 4ec82a72bbf7ff0066edb50dcad20aa77ac2fe09 since this commit addresses the issue it was solving", "code": "def process_info(self, info_dict):\n \n\n assert info_dict.get('_type', 'video') == 'video'\n original_infodict = info_dict\n\n if 'format' not in info_dict and 'ext' in info_dict:\n info_dict['format'] = info_dict['ext']\n\n # This is mostly just for backward compatibility of process_info\n # As a side-effect, this allows for format-specific filters\n if self._match_entry(info_dict) is not None:\n info_dict['__write_download_archive'] = 'ignore'\n return\n\n # Does nothing under normal operation - for backward compatibility of process_info\n self.post_extract(info_dict)\n\n # info_dict['_filename'] needs to be set for backward compatibility\n info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)\n temp_filename = self.prepare_filename(info_dict, 'temp')\n files_to_move = {}\n\n self._num_downloads += 1\n\n # Forced printings\n self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))\n\n if self.params.get('simulate'):\n info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')\n return\n\n if full_filename is None:\n return\n if not self._ensure_dir_exists(encodeFilename(full_filename)):\n return\n if not self._ensure_dir_exists(encodeFilename(temp_filename)):\n return\n\n if self._write_description('video', info_dict,\n self.prepare_filename(info_dict, 'description')) is None:\n return\n\n sub_files = self._write_subtitles(info_dict, temp_filename)\n if sub_files is None:\n return\n files_to_move.update(dict(sub_files))\n\n thumb_files = self._write_thumbnails(\n 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))\n if thumb_files is None:\n return\n files_to_move.update(dict(thumb_files))\n\n infofn = self.prepare_filename(info_dict, 'infojson')\n _infojson_written = self._write_info_json('video', info_dict, infofn)\n if _infojson_written:\n info_dict['infojson_filename'] = infofn\n # For backward compatibility, even though it was a private field\n info_dict['__infojson_filename'] = infofn\n elif _infojson_written is None:\n return\n\n # Note: Annotations are deprecated\n annofn = None\n if self.params.get('writeannotations', False):\n annofn = self.prepare_filename(info_dict, 'annotation')\n if annofn:\n if not self._ensure_dir_exists(encodeFilename(annofn)):\n return\n if not self.params.get('overwrites', True) and os.path.exists(encodeFilename(annofn)):\n self.to_screen('[info] Video annotations are already present')\n elif not info_dict.get('annotations'):\n self.report_warning('There are no annotations to write.')\n else:\n try:\n self.to_screen('[info] Writing video annotations to: ' + annofn)\n with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:\n annofile.write(info_dict['annotations'])\n except (KeyError, TypeError):\n self.report_warning('There are no annotations to write.')\n except (OSError, IOError):\n self.report_error('Cannot write annotations file: ' + annofn)\n return\n\n # Write internet shortcut files", "url": "https://github.com/yt-dlp/yt-dlp.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 19, "n_whitespaces": 991, "n_words": 266, "vocab_size": 154, "complexity": 70, "nloc": 209, "token_counts": 1463, "n_ast_nodes": 792, "n_identifiers": 44 }, { "id": 259434, "commit_id": "75a94f518f7bd7d0bf581ffb67d9f961e3c4efbc", "repo": "scikit-learn", "path": "sklearn/_loss/tests/test_loss.py", "file_name": "test_loss.py", "fun_name": "test_tweedie_log_identity_consistency", "commit_message": "ENH migrate GLMs / TweedieRegressor to linear loss (#22548)\n\nCo-authored-by: Olivier Grisel \r\nCo-authored-by: Thomas J. Fan ", "code": "def test_tweedie_log_identity_consistency(p):\n \n half_tweedie_log = HalfTweedieLoss(power=p)\n half_tweedie_identity = HalfTweedieLossIdentity(power=p)\n n_samples = 10\n y_true, raw_prediction = random_y_true_raw_prediction(\n loss=half_tweedie_log, n_samples=n_samples, seed=42\n )\n y_pred = half_tweedie_log.link.inverse(raw_prediction) # exp(raw_prediction)\n\n # Let's compare the loss values, up to some constant term that is dropped\n # in HalfTweedieLoss but not in HalfTweedieLossIdentity.\n loss_log = half_tweedie_log.loss(\n y_true=y_true, raw_prediction=raw_prediction\n ) + half_tweedie_log.constant_to_optimal_zero(y_true)\n loss_identity = half_tweedie_identity.loss(\n y_true=y_true, raw_prediction=y_pred\n ) + half_tweedie_identity.constant_to_optimal_zero(y_true)\n # Note that HalfTweedieLoss ignores different constant terms than\n # HalfTweedieLossIdentity. Constant terms means terms not depending on\n # raw_prediction. By adding these terms, `constant_to_optimal_zero`, both losses\n # give the same values.\n assert_allclose(loss_log, loss_identity)\n\n # For gradients and hessians, the constant terms do not matter. We have, however,\n # to account for the chain rule, i.e. with x=raw_prediction\n # gradient_log(x) = d/dx loss_log(x)\n # = d/dx loss_identity(exp(x))\n # = exp(x) * gradient_identity(exp(x))\n # Similarly,\n # hessian_log(x) = exp(x) * gradient_identity(exp(x))\n # + exp(x)**2 * hessian_identity(x)\n gradient_log, hessian_log = half_tweedie_log.gradient_hessian(\n y_true=y_true, raw_prediction=raw_prediction\n )\n gradient_identity, hessian_identity = half_tweedie_identity.gradient_hessian(\n y_true=y_true, raw_prediction=y_pred\n )\n assert_allclose(gradient_log, y_pred * gradient_identity)\n assert_allclose(\n hessian_log, y_pred * gradient_identity + y_pred**2 * hessian_identity\n )\n", "url": "https://github.com/scikit-learn/scikit-learn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 383, "n_words": 174, "vocab_size": 109, "complexity": 1, "nloc": 25, "token_counts": 155, "n_ast_nodes": 255, "n_identifiers": 25 }, { "id": 153340, "commit_id": "e7cb2e82f8b9c7a68f82abdd3b6011d661230b7e", "repo": "modin", "path": "modin/core/execution/ray/generic/modin_aqp.py", "file_name": "modin_aqp.py", "fun_name": "display_time_updates", "commit_message": "REFACTOR-#4251: define public interfaces in `modin.core.execution.ray` module (#3868)\n\nSigned-off-by: Anatoly Myachev ", "code": "def display_time_updates(bar):\n \n threading.Thread(target=_show_time_updates, args=(bar,)).start()\n\n", "url": "https://github.com/modin-project/modin.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 10, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 25, "n_ast_nodes": 42, "n_identifiers": 8 }, { "id": 274800, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/metrics/metrics_functional_test.py", "file_name": "metrics_functional_test.py", "fun_name": "test_sparse_categorical_accuracy_eager", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def test_sparse_categorical_accuracy_eager(self):\n \n metric = metrics.sparse_categorical_accuracy\n y_true = np.arange(6).reshape([6, 1])\n y_pred = np.arange(36).reshape([6, 6])\n self.assertAllEqual(\n metric(y_true, y_pred), [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]\n )\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 76, "n_words": 23, "vocab_size": 18, "complexity": 1, "nloc": 7, "token_counts": 82, "n_ast_nodes": 105, "n_identifiers": 11 }, { "id": 224002, "commit_id": "e7f07cc82ab2be920ab426ba07456d8b2592714d", "repo": "mkdocs", "path": "mkdocs/commands/babel.py", "file_name": "babel.py", "fun_name": "get_theme_dir", "commit_message": "Remove spaces at the ends of docstrings, normalize quotes", "code": "def get_theme_dir(self):\n \n entry_points = EntryPoint.parse_map(self.distribution.entry_points, self.distribution)\n if 'mkdocs.themes' not in entry_points:\n raise DistutilsOptionError(\"no mkdocs.themes are defined in entry_points\")\n if self.theme is None and len(entry_points['mkdocs.themes']) == 1:\n # Default to the only theme defined in entry_points as none specified.\n self.theme = tuple(entry_points['mkdocs.themes'].keys())[0]\n if self.theme not in entry_points['mkdocs.themes']:\n raise DistutilsOptionError(\"you must specify a valid theme name to work on\")\n theme = entry_points['mkdocs.themes'][self.theme]\n return path.dirname(theme.resolve().__file__)\n\n", "url": "https://github.com/mkdocs/mkdocs.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 155, "n_words": 62, "vocab_size": 46, "complexity": 5, "nloc": 10, "token_counts": 108, "n_ast_nodes": 184, "n_identifiers": 15 }, { "id": 186643, "commit_id": "7d9e9a49005de7961e84d2a7c608db57dbab3046", "repo": "certbot", "path": "certbot-apache/certbot_apache/_internal/configurator.py", "file_name": "configurator.py", "fun_name": "_autohsts_save_state", "commit_message": "Add typing to certbot.apache (#9071)\n\n* Add typing to certbot.apache\r\n\r\nCo-authored-by: Adrien Ferrand ", "code": "def _autohsts_save_state(self) -> None:\n \n self.storage.put(\"autohsts\", self._autohsts)\n self.storage.save()\n", "url": "https://github.com/certbot/certbot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 28, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 6, "token_counts": 27, "n_ast_nodes": 48, "n_identifiers": 6 }, { "id": 285199, "commit_id": "9e1a58e2dbedec4e4a9f9c2e32ddf091776c606b", "repo": "OpenBBTerminal", "path": "openbb_terminal/econometrics/econometrics_model.py", "file_name": "econometrics_model.py", "fun_name": "get_engle_granger_two_step_cointegration_test", "commit_message": "Here we merge all API Refactor related branches (#2236)\n\n* Update api.py\r\n\r\n* Updated forex menu\r\n\r\n* refactor ycrv command\r\n\r\n* refactor ycrv command black\r\n\r\n* refactor ecocal command\r\n\r\n* Minh changes\r\n\r\n* Adding space to test pushing\r\n\r\n* title fix ecocal df\r\n\r\n* get economic calendar annotation\r\n\r\n* fix investingcom tests\r\n\r\n* refactor index command\r\n\r\n* refactor overview command\r\n\r\n* give defaults to wsj view function args\r\n\r\n* rename date args investincom\r\n\r\n* refacto bigmac command\r\n\r\n* fix ecocal typo\r\n\r\n* refactor rtps command\r\n\r\n* alphavantage gdp\r\n\r\n* alphavantage gdp per capita\r\n\r\n* alphavantage cpi\r\n\r\n* alphavantage tyld\r\n\r\n* alphavantage inf\r\n\r\n* refactor macro command\r\n\r\n* refactor macro command w helpers\r\n\r\n* refactor treasury command\r\n\r\n* fix macro on terminal\r\n\r\n* treasury labels\r\n\r\n* refactor maturities\r\n\r\n* update treasury maturities doc strings\r\n\r\n* refactor get economic calendar finhub\r\n\r\n* refactor map command api\r\n\r\n* display map filter choices\r\n\r\n* route economy api to performance map\r\n\r\n* route economy api to performance map\r\n\r\n* display group choices on valuation command\r\n\r\n* refactor performance and valuation commands\r\n\r\n* refactor spectrum model and view\r\n\r\n* add choices to spectrum controller\r\n\r\n* delete image after view\r\n\r\n* fix model tests finviz\r\n\r\n* fix finciz view tests\r\n\r\n* refactor futures\r\n\r\n* fix some tests\r\n\r\n* fix more tests\r\n\r\n* fix controller test\r\n\r\n* refactor fred series notes\r\n\r\n* update fred notes docstring\r\n\r\n* refacto fred series ids\r\n\r\n* fix pred and qa when empty datasets\r\n\r\n* refactor fred\r\n\r\n* uncomment stuff\r\n\r\n* refacto get series data\r\n\r\n* fix some tests\r\n\r\n* set defaults on args\r\n\r\n* refactor fred yield curve\r\n\r\n* black\r\n\r\n* fix spell and remove ecocal names\r\n\r\n* fix linting\r\n\r\n* linting\r\n\r\n* pylint fix\r\n\r\n* change dangerous defaults\r\n\r\n* Working through crypto fixes (#2256)\r\n\r\n* Working through crypto fixes\r\n\r\n* Continued adding crypto stuff\r\n\r\n* Added crypto overview\r\n\r\n* Added test fixes\r\n\r\n* Added fixtures\r\n\r\n* Fixed tests\r\n\r\n* Fixed charting issue\r\n\r\n* Removed broken APIs\r\n\r\n* Final adjustments\r\n\r\n* Added test fixes\r\n\r\n* map get groups and get ycrv countries into old api\r\n\r\n* exposed econdb helper funcs\r\n\r\n* remove helpers\r\n\r\n* refactor search indices\r\n\r\n* linting\r\n\r\n* refactor arg currency\r\n\r\n* pylint from currency\r\n\r\n* Started switching crpyto ascending to ascend\r\n\r\n* Merging\r\n\r\n* Portfolio model arguements, params, and docstring\r\n\r\n* Refactored for etf commands (#2292)\r\n\r\n* Refactored for etf commands\r\n\r\n* Fixed tests\r\n\r\n* Added load command\r\n\r\n* Fixed menu\r\n\r\n* Portfolio logic fixes\r\n\r\n* Added econometrics (#2260)\r\n\r\n* Added econometrics\r\n\r\n* Fixed tests\r\n\r\n* Simplified API\r\n\r\n* Added test fixes\r\n\r\n* Added test csv\r\n\r\n* Allowed examples to be loaded\r\n\r\n* Fund refactor (#2291)\r\n\r\n* Fund refactor\r\n\r\n* Changed fund_name and fund to name\r\n\r\n* Changed ascending to ascend\r\n\r\n* Stock menu refactoring for easier API usage (#2194)\r\n\r\n* Stocks refactoring for easier API usage\r\n\r\n* Linting\r\n\r\n* Refactor newly added features\r\n\r\n* Linting\r\n\r\n* Fixing tests\r\n\r\n* Refactor common files used by stocks menu\r\n\r\n* Fixing flake8\r\n\r\n* Fix linting and tests\r\n\r\n* Linting\r\n\r\n* Fix flake8\r\n\r\n* refactor insider_data\r\n\r\n* refactor mentions\r\n\r\n* refactor watchlist\r\n\r\n* refactor sentiment\r\n\r\n* refactor sentiment\r\n\r\n* fix yahoofinance tests\r\n\r\n* refactor load and candle\r\n\r\n* refactor get_news and display_news\r\n\r\n* refactor stocks.ins.act\r\n\r\n* candle default matplotlib\r\n\r\n* fix yahoofinance_view tests\r\n\r\n* fix ark model tests\r\n\r\n* fix ark view tests\r\n\r\n* fix business insider model\r\n\r\n* fix business insider view\r\n\r\n* refactor csimarket model\r\n\r\n* fix tests csi market model\r\n\r\n* update dd controller\r\n\r\n* fix get suppliers tests\r\n\r\n* fix dd controller tests\r\n\r\n* fix finhub tests\r\n\r\n* fix finviz tests\r\n\r\n* fix fmp tests\r\n\r\n* fix marketwatch tests\r\n\r\n* corrected argument keywords in test_bt_model\r\n\r\n* corrected argument keywords in test_bt_view\r\n\r\n* refactor fa controller\r\n\r\n* refactor marketwatch view\r\n\r\n* refactor gov controller\r\n\r\n* fix tests fa av\r\n\r\n* fix tests elect\r\n\r\n* fix dcf tests\r\n\r\n* fix polygon tests\r\n\r\n* fix fmp tests\r\n\r\n* fix quiverquant tests\r\n\r\n* fix yahoofinance fa tests\r\n\r\n* fix more fa tests\r\n\r\n* fix insider tests\r\n\r\n* fix more tests\r\n\r\n* fix more tests\r\n\r\n* fix options tests\r\n\r\n* fix stock gov tests\r\n\r\n* fix tests test_ba_controller\r\n\r\n* fix tests for test_finviz_compare_model.py\r\n\r\n* fixed 2 tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fix final tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* Fix tests\r\n\r\n* black\r\n\r\n* forgot to black tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* flakefix\r\n\r\n* Tests + code : Stocks / Discovery\r\n\r\n* fix tests\r\n\r\n* added recorder\r\n\r\n* fixed tests\r\n\r\n* fixed tests\r\n\r\n* black\r\n\r\n* black\r\n\r\n* remove unused imports\r\n\r\n* refactor display raw\r\n\r\n* sia dicts fix\r\n\r\n* pylint\r\n\r\n* linting\r\n\r\n* remove dangerous default\r\n\r\n* fix tests\r\n\r\n* fix beta model test\r\n\r\n* black\r\n\r\n* skip screener qa test\r\n\r\n* change sector path to sectors\r\n\r\n* update tests readme\r\n\r\n* fix metric defaults\r\n\r\n* black\r\n\r\n* substitute lost ticker\r\n\r\n* defaults cpic\r\n\r\n* another round on sia\r\n\r\n* refactor cramer\r\n\r\n* reduce default tweets on sentiment\r\n\r\n* refactor yf hist, corr, volume\r\n\r\n* arkorders default\r\n\r\n* refactor income, balance, cashflow\r\n\r\n* refacto scorr, screener, getfinnhub\r\n\r\n* refactor stockgrid\r\n\r\n* ibkr refactor\r\n\r\n* another round on stockgrid\r\n\r\n* add dividens end point\r\n\r\n* refactor discovery endpoints\r\n\r\n* update docstrings with similar input\r\n\r\n* refactor messages\r\n\r\n* refactor ba\r\n\r\n* refactor regioons\r\n\r\n* refactor twitter sentiment\r\n\r\n* refactor hist\r\n\r\n* refactor regions\r\n\r\n* give default to timeframe\r\n\r\n* refactor bunch of defaults and arg names\r\n\r\n* remove leftover imports\r\n\r\n* refactor vwap\r\n\r\n* let tests run\r\n\r\n* fix tests\r\n\r\n* fix stock tests\r\n\r\n* fix stockanalysis tests\r\n\r\n* flake\r\n\r\n* MYPY\r\n\r\n* Made important changes\r\n\r\n* added fixes\r\n\r\n* Fixed big issue\r\n\r\n* Added fixes to tests\r\n\r\n* fix qa tests\r\n\r\n* fix tests\r\n\r\n* fix 1 more test\r\n\r\n* last stocks failing\r\n\r\n* fix crypto test\r\n\r\nCo-authored-by: Chavithra PARANA \r\nCo-authored-by: montezdesousa \r\nCo-authored-by: hjoaquim \r\nCo-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com>\r\nCo-authored-by: colin99d \r\n\r\n* fix portfolio tests\r\n\r\n* change period to window\r\n\r\n* update ca docstrings\r\n\r\n* refactor get_similar_companies func\r\n\r\n* Fixed\r\n\r\n* Update CI\r\n\r\n* Update CI 2\r\n\r\n* Update CI 3\r\n\r\n* Update dependencies\r\n\r\nCo-authored-by: colin99d \r\nCo-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>\r\nCo-authored-by: montezdesousa \r\nCo-authored-by: James Simmons \r\nCo-authored-by: Theodore Aptekarev \r\nCo-authored-by: minhhoang1023 <40023817+minhhoang1023@users.noreply.github.com>\r\nCo-authored-by: jose-donato <43375532+jose-donato@users.noreply.github.com>\r\nCo-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com>\r\nCo-authored-by: northern-64bit <75195383+northern-64bit@users.noreply.github.com>\r\nCo-authored-by: hjoaquim ", "code": "def get_engle_granger_two_step_cointegration_test(dependent_series, independent_series):\n \n warnings.simplefilter(action=\"ignore\", category=FutureWarning)\n long_run_ols = sm.OLS(dependent_series, sm.add_constant(independent_series))\n warnings.simplefilter(action=\"default\", category=FutureWarning)\n\n long_run_ols_fit = long_run_ols.fit()\n\n c, gamma = long_run_ols_fit.params\n z = long_run_ols_fit.resid\n\n short_run_ols = sm.OLS(dependent_series.diff().iloc[1:], (z.shift().iloc[1:]))\n short_run_ols_fit = short_run_ols.fit()\n\n alpha = short_run_ols_fit.params[0]\n\n # NOTE: The p-value returned by the adfuller function assumes we do not estimate z\n # first, but test stationarity of an unestimated series directly. This assumption\n # should have limited effect for high N, however. Critical values taking this into\n # account more accurately are provided in e.g. McKinnon (1990) and Engle & Yoo (1987).\n\n adfstat, pvalue, _, _, _ = adfuller(z, maxlag=1, autolag=None)\n\n return c, gamma, alpha, z, adfstat, pvalue\n", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 151, "n_words": 103, "vocab_size": 88, "complexity": 1, "nloc": 12, "token_counts": 147, "n_ast_nodes": 230, "n_identifiers": 31 }, { "id": 143848, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "rllib/policy/tf_policy.py", "file_name": "tf_policy.py", "fun_name": "_extra_input_signature_def", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def _extra_input_signature_def(self):\n \n feed_dict = self.extra_compute_action_feed_dict()\n return {\n k.name: tf1.saved_model.utils.build_tensor_info(k) for k in feed_dict.keys()\n }\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 53, "n_words": 14, "vocab_size": 14, "complexity": 2, "nloc": 5, "token_counts": 38, "n_ast_nodes": 63, "n_identifiers": 11 }, { "id": 310124, "commit_id": "6176bb954c4aa68b33c9db487dbb5712059f4b38", "repo": "core", "path": "tests/components/seventeentrack/test_sensor.py", "file_name": "test_sensor.py", "fun_name": "test_summary_correctly_updated", "commit_message": "fix: 17track package summary status is not updated when there are no more packages in that summary (#64421)\n\n* 17track package status is not updated when there are no packages\r\n\r\n* 17track package status is not updated when there are no packages\r\n\r\n* 17track package status is not updated when there are no packages", "code": "async def test_summary_correctly_updated(hass):\n \n package = Package(\n tracking_number=\"456\",\n destination_country=206,\n friendly_name=\"friendly name 1\",\n info_text=\"info text 1\",\n location=\"location 1\",\n timestamp=\"2020-08-10 10:32\",\n origin_country=206,\n package_type=2,\n status=30,\n )\n ProfileMock.package_list = [package]\n\n await _setup_seventeentrack(hass, summary_data=DEFAULT_SUMMARY)\n\n assert len(hass.states.async_entity_ids()) == 8\n for state in hass.states.async_all():\n if state.entity_id == \"sensor.seventeentrack_package_456\":\n break\n assert state.state == \"0\"\n\n assert (\n len(\n hass.states.get(\n \"sensor.seventeentrack_packages_ready_to_be_picked_up\"\n ).attributes[\"packages\"]\n )\n == 1\n )\n\n ProfileMock.package_list = []\n ProfileMock.summary_data = NEW_SUMMARY_DATA\n\n await _goto_future(hass)\n\n assert len(hass.states.async_entity_ids()) == 7\n for state in hass.states.async_all():\n assert state.state == \"1\"\n\n assert (\n hass.states.get(\n \"sensor.seventeentrack_packages_ready_to_be_picked_up\"\n ).attributes[\"packages\"]\n is None\n )\n\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 316, "n_words": 83, "vocab_size": 53, "complexity": 4, "nloc": 39, "token_counts": 186, "n_ast_nodes": 310, "n_identifiers": 28 }, { "id": 323214, "commit_id": "c541f4ba1fcab8304c7ac4efdce3d63a2e478176", "repo": "PaddleNLP", "path": "paddlenlp/utils/file_lock.py", "file_name": "file_lock.py", "fun_name": "acquire", "commit_message": "Add model parallel for FasterGPT. (#1755)\n\n* Add model parallel for FasterGPT.\r\n\r\n* Make GPT model parallel runable\r\n\r\n* Make FT model parallel optional.\r\n\r\n* Fix _write_setup_file when kwargs is not empty.\r\n\r\n* Fix ext_utils.load\r\n\r\n* Add file lock for model parallel.\r\n\r\n* Fix model_parallel.flag in CMakeLists.txt.\r\n\r\n* Use a separated lib for model parallel.\r\n\r\n* Make from_pretrained get partial model.\r\n\r\n* Make model parallel support layer group in python.\r\n\r\n* Fix fit_partial_model when model having keys state not including.\r\n\r\nAdd api docs for model parallel.\r\n\r\n* Fix the default world_size when mpi is not available.\r\n\r\n* Add demo for GPT model parallel.\r\n\r\n* Fix default global ft_para_conf.\r\n\r\n* Fix GPTModel state_dict wrapper for layer parallel.\r\n\r\n* Set seed for tensor parallel.\r\n\r\n* Fix location of gpt.h in cmake.\r\n\r\n* Fix seed in gpt.h\r\n\r\n* Fix NV FT GPT embedding.\r\n\r\n* Add more cases in gpt_mp_sample.py\r\n\r\n* Fix seed in ker_curand_setupLauncher.\r\nPut build dir of FG in PPNLP_HOME with digest of current path.\r\n\r\n* Refine gpt_mp_sample.py", "code": "def acquire(self):\n \n start_time = time.time()\n while True:\n try:\n self.fd = os.open(self.lock_file_path, os.O_CREAT | os.O_EXCL |\n os.O_RDWR)\n self.is_locked = True # moved to ensure tag only when locked\n break\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n if self.timeout is None:\n raise FileLockException(\"Could not acquire lock on {}\".\n format(self.lock_file_path))\n if self.timeout > 0 and (time.time() - start_time\n ) >= self.timeout:\n raise FileLockException(\"Timeout occured.\")\n time.sleep(self.delay)\n", "url": "https://github.com/PaddlePaddle/PaddleNLP.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 386, "n_words": 64, "vocab_size": 55, "complexity": 7, "nloc": 18, "token_counts": 116, "n_ast_nodes": 194, "n_identifiers": 21 }, { "id": 171627, "commit_id": "e2df99823758210fb2b7c4aba39e23f3445f7cd3", "repo": "pandas", "path": "pandas/_version.py", "file_name": "_version.py", "fun_name": "render_pep440", "commit_message": "BLD: use nonvendor versioneer (#49924)\n\n* BLD: remove vendored versioneer\r\n\r\n* run vis\r\n\r\n* move config to pyproject.toml\r\n\r\n* add versioneer to deps\r\n\r\n* run pyupgrade\r\n\r\n* fix isort and pylint\r\n\r\n* fix ci\r\n\r\n* fix env", "code": "def render_pep440(pieces):\n \n if pieces[\"closest-tag\"]:\n rendered = pieces[\"closest-tag\"]\n if pieces[\"distance\"] or pieces[\"dirty\"]:\n rendered += plus_or_dot(pieces)\n rendered += f\"{pieces['distance']}.g{pieces['short']}\"\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n else:\n # exception #1\n rendered = f\"0+untagged.{pieces['distance']}.g{pieces['short']}\"\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered\n\n", "url": "https://github.com/pandas-dev/pandas.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 142, "n_words": 36, "vocab_size": 20, "complexity": 6, "nloc": 13, "token_counts": 65, "n_ast_nodes": 163, "n_identifiers": 4 }, { "id": 139165, "commit_id": "e8fc66af348f2afd2b578fe1c6776cc88ea82499", "repo": "ray", "path": "python/ray/workflow/workflow_context.py", "file_name": "workflow_context.py", "fun_name": "workflow_logging_context", "commit_message": "[Workflow]Make workflow logs publish to the correct driver. (#24089)\n\nAll workflow tasks are executed as remote functions that submitted from WorkflowManagmentActor. WorkflowManagmentActor is a detached long-running actor whose owner is the first driver in the cluster that runs the very first workflow execution. Therefore, for new drivers that run workflows, the loggings won't be properly published back to the driver because loggings are saved and published based on job_id and the job_id is always the first driver's job_id as the ownership goes like: first_driver -> WorkflowManagmentActor -> workflow executions using remote functions.\r\n\r\nTo solve this, during workflow execution, we pass the actual driver's job_id along with execution, and re-configure the logging files on each worker that runs the remote functions. Notice that we need to do this in multiple places as a workflow task is executed with more than one remote functions that are running in different workers.", "code": "def workflow_logging_context(job_id) -> None:\n \n node = ray.worker._global_node\n original_out_file, original_err_file = node.get_log_file_handles(\n get_worker_log_file_name(\"WORKER\")\n )\n out_file, err_file = node.get_log_file_handles(\n get_worker_log_file_name(\"WORKER\", job_id)\n )\n try:\n configure_log_file(out_file, err_file)\n yield\n finally:\n configure_log_file(original_out_file, original_err_file)\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 86, "n_words": 27, "vocab_size": 23, "complexity": 2, "nloc": 27, "token_counts": 60, "n_ast_nodes": 104, "n_identifiers": 13 }, { "id": 271851, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/engine/training_utils_v1.py", "file_name": "training_utils_v1.py", "fun_name": "verify_dataset_shuffled", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def verify_dataset_shuffled(x):\n \n assert isinstance(x, tf.data.Dataset)\n graph_def = get_dataset_graph_def(x)\n for node in graph_def.node:\n if node.op.startswith(\"ShuffleDataset\"):\n return True\n # Also check graph_def.library.function for ds.interleave or ds.flat_map\n for function in graph_def.library.function:\n for node in function.node_def:\n if node.op.startswith(\"ShuffleDataset\"):\n return True\n logging.warning(\n \"Expected a shuffled dataset but input dataset `x` is \"\n \"not shuffled. Please invoke `shuffle()` on input dataset.\"\n )\n return False\n\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 150, "n_words": 58, "vocab_size": 45, "complexity": 6, "nloc": 15, "token_counts": 79, "n_ast_nodes": 134, "n_identifiers": 16 }, { "id": 264296, "commit_id": "54834c47f8870e7faabcd847c3270da0bd3d2884", "repo": "netbox", "path": "netbox/netbox/views/generic/bulk_views.py", "file_name": "bulk_views.py", "fun_name": "get", "commit_message": "Refactor generic views; add plugins dev documentation", "code": "def get(self, request):\n \n model = self.queryset.model\n content_type = ContentType.objects.get_for_model(model)\n\n if self.filterset:\n self.queryset = self.filterset(request.GET, self.queryset).qs\n\n # Compile a dictionary indicating which permissions are available to the current user for this model\n permissions = {}\n for action in ('add', 'change', 'delete', 'view'):\n perm_name = get_permission_for_model(model, action)\n permissions[action] = request.user.has_perm(perm_name)\n\n if 'export' in request.GET:\n\n # Export the current table view\n if request.GET['export'] == 'table':\n table = self.get_table(request, permissions)\n columns = [name for name, _ in table.selected_columns]\n return self.export_table(table, columns)\n\n # Render an ExportTemplate\n elif request.GET['export']:\n template = get_object_or_404(ExportTemplate, content_type=content_type, name=request.GET['export'])\n return self.export_template(template, request)\n\n # Check for YAML export support on the model\n elif hasattr(model, 'to_yaml'):\n response = HttpResponse(self.export_yaml(), content_type='text/yaml')\n filename = 'netbox_{}.yaml'.format(self.queryset.model._meta.verbose_name_plural)\n response['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(filename)\n return response\n\n # Fall back to default table/YAML export\n else:\n table = self.get_table(request, permissions)\n return self.export_table(table)\n\n # Render the objects table\n table = self.get_table(request, permissions)\n configure_table(table, request)\n\n # If this is an HTMX request, return only the rendered table HTML\n if is_htmx(request):\n return render(request, 'htmx/table.html', {\n 'table': table,\n })\n\n context = {\n 'content_type': content_type,\n 'table': table,\n 'permissions': permissions,\n 'action_buttons': self.action_buttons,\n 'filter_form': self.filterset_form(request.GET, label_suffix='') if self.filterset_form else None,\n }\n context.update(self.get_extra_context(request))\n\n return render(request, self.template_name, context)\n\n #\n # Export methods\n #\n", "url": "https://github.com/netbox-community/netbox.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 698, "n_words": 192, "vocab_size": 123, "complexity": 10, "nloc": 40, "token_counts": 342, "n_ast_nodes": 565, "n_identifiers": 47 }, { "id": 286002, "commit_id": "7979b1fc071a1c3e7463044bea617d7305b4a17e", "repo": "OpenBBTerminal", "path": "openbb_terminal/cryptocurrency/due_diligence/tokenterminal_model.py", "file_name": "tokenterminal_model.py", "fun_name": "get_project_ids", "commit_message": "Add 3 Token Terminal commands (#2447)\n\n* add crypto/ov/fun\r\n\r\n* add tokenterminal to dependencies\r\n\r\n* update website content\r\n\r\n* add to main.yml\r\n\r\n* fix tests\r\n\r\n* add tests\r\n\r\n* Update _index.md\r\n\r\n* Update _index.md\r\n\r\n* fix tests\r\n\r\n* fix test\r\n\r\n* List hint added\r\n\r\n* improve code based on Jose input\r\n\r\n* fix tests\r\n\r\n* requirements for token terminal\r\n\r\n* add source and fix source bug\r\n\r\n* some improvements\r\n\r\n* colors bars\r\n\r\n* fix dependencies\r\n\r\n* update kaleido version\r\n\r\n* update setuptools for pkg_resources\r\n\r\n* replace pkg_resources by importlib_metadata\r\n\r\n* Added fixes\r\n\r\n* Fixed tests\r\n\r\n* fix stuff for Josecas\r\n\r\nCo-authored-by: Colin Delahunty <72827203+colin99d@users.noreply.github.com>\r\nCo-authored-by: colin99d ", "code": "def get_project_ids() -> List[str]:\n \n return [project[\"project_id\"] for project in PROJECTS_DATA]\n\n\n@log_start_end(log=logger)", "url": "https://github.com/OpenBB-finance/OpenBBTerminal.git", "language": "Python", "ast_errors": "@log_start_end(log=logger)", "n_ast_errors": 1, "ast_levels": 8, "n_whitespaces": 16, "n_words": 11, "vocab_size": 11, "complexity": 2, "nloc": 9, "token_counts": 21, "n_ast_nodes": 48, "n_identifiers": 8 }, { "id": 85425, "commit_id": "dfe1d3442af1535cc2d4f8a511ee5733b3887572", "repo": "sentry", "path": "tests/sentry/api/endpoints/test_group_details.py", "file_name": "test_group_details.py", "fun_name": "test_delete_performance_issue", "commit_message": "feat(perf issues): Prevent deleting and merging (#38479)\n\n* Prevent deleting, discarding, and merging in single and bulk operations\r\nfor performance issues.", "code": "def test_delete_performance_issue(self):\n \n self.login_as(user=self.user)\n\n group = self.create_group(type=GroupType.PERFORMANCE_SLOW_SPAN.value)\n GroupHash.objects.create(project=group.project, hash=\"x\" * 32, group=group)\n\n url = f\"/api/0/issues/{group.id}/\"\n\n response = self.client.delete(url, format=\"json\")\n assert response.status_code == 400, response.content\n\n # Ensure it's still there\n assert Group.objects.filter(id=group.id).exists()\n assert GroupHash.objects.filter(group_id=group.id).exists()\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 102, "n_words": 32, "vocab_size": 28, "complexity": 1, "nloc": 9, "token_counts": 114, "n_ast_nodes": 191, "n_identifiers": 27 }, { "id": 275037, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/mixed_precision/loss_scale_optimizer.py", "file_name": "loss_scale_optimizer.py", "fun_name": "dynamic_counter", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def dynamic_counter(self):\n \n raise NotImplementedError\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 6, "n_whitespaces": 18, "n_words": 4, "vocab_size": 4, "complexity": 1, "nloc": 2, "token_counts": 8, "n_ast_nodes": 16, "n_identifiers": 3 }, { "id": 295912, "commit_id": "a61ac3ddc6d65522dfa1eb599adf73420a9267dc", "repo": "core", "path": "tests/components/siren/test_init.py", "file_name": "test_init.py", "fun_name": "test_missing_tones_dict", "commit_message": "Add EntityFeature enum to Siren (#69585)\n\nCo-authored-by: Franck Nijhof ", "code": "async def test_missing_tones_dict(hass):\n \n siren = MockSirenEntity(SirenEntityFeature.TONES, {1: \"a\", 2: \"b\"})\n siren.hass = hass\n with pytest.raises(ValueError):\n process_turn_on_params(siren, {\"tone\": 3})\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 37, "n_words": 18, "vocab_size": 17, "complexity": 1, "nloc": 5, "token_counts": 47, "n_ast_nodes": 84, "n_identifiers": 10 }, { "id": 85913, "commit_id": "686675f81bf9402bc9b671e61ea0481b0c5c3468", "repo": "sentry", "path": "src/sentry/grouping/enhancer/__init__.py", "file_name": "__init__.py", "fun_name": "get_matching_frame_actions", "commit_message": "fix(grouping): Exception matcher with no frames (#38994)\n\nWe used to pass `-1` as a frame index for exception matchers, which\r\nworked by accident because `-1` is a valid list index in Python, except\r\nwhen the list of frames was empty.\r\n\r\nReplace `-1` by `None` and make sure we do not attempt to access the\r\nlist of frames in the exception matcher, by giving it its own\r\n`matches_frame` override.\r\n\r\nFixes SENTRY-VWW", "code": "def get_matching_frame_actions(self, frames, platform, exception_data=None, cache=None):\n \n if not self.matchers:\n return []\n\n # 1 - Check if exception matchers match\n for m in self._exception_matchers:\n if not m.matches_frame(frames, None, platform, exception_data, cache):\n return []\n\n rv = []\n\n # 2 - Check if frame matchers match\n for idx, frame in enumerate(frames):\n if all(\n m.matches_frame(frames, idx, platform, exception_data, cache)\n for m in self._other_matchers\n ):\n for action in self.actions:\n rv.append((idx, action))\n\n return rv\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 247, "n_words": 68, "vocab_size": 40, "complexity": 8, "nloc": 15, "token_counts": 112, "n_ast_nodes": 166, "n_identifiers": 19 }, { "id": 160327, "commit_id": "f9355942f6ef7c5d27691c4571096234efb67a2b", "repo": "numpy", "path": "numpy/lib/twodim_base.py", "file_name": "twodim_base.py", "fun_name": "eye", "commit_message": "BUG: lib: Allow type uint64 for eye() arguments.\n\nCloses gh-9982.\n\n(Plus a few small PEP 8 fixes.)", "code": "def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):\n \n if like is not None:\n return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)\n if M is None:\n M = N\n m = zeros((N, M), dtype=dtype, order=order)\n if k >= M:\n return m\n # Ensure M and k are integers, so we don't get any surprise casting\n # results in the expressions `M-k` and `M+1` used below. This avoids\n # a problem with inputs with type (for example) np.uint64.\n M = operator.index(M)\n k = operator.index(k)\n if k >= 0:\n i = k\n else:\n i = (-k) * M\n m[:M-k].flat[i::M+1] = 1\n return m\n\n\n_eye_with_like = array_function_dispatch(\n _eye_dispatcher\n)(eye)\n\n", "url": "https://github.com/numpy/numpy.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 183, "n_words": 104, "vocab_size": 73, "complexity": 5, "nloc": 16, "token_counts": 146, "n_ast_nodes": 239, "n_identifiers": 17 }, { "id": 271557, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/engine/training.py", "file_name": "training.py", "fun_name": "_validate_target_and_loss", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def _validate_target_and_loss(self, y, loss):\n \n\n # `self.loss` references the loss added via `compile` call. If users have\n # provided such, the target must be provided; otherwise it's a user error.\n # Note that `self.loss` does not include losses added via `add_loss`, and it\n # is a valid use when such loss from `add_loss` exists and target does not.\n if self.loss and y is None:\n raise ValueError(\n \"Target data is missing. Your model was compiled with \"\n f\"loss={self.loss}, \"\n \"and therefore expects target data to be provided in `fit()`.\"\n )\n\n # For training, there must be compiled loss or regularization loss to exist\n # in order to apply the gradients. If one is not found, it means no loss\n # was supplied via `compile` or `add_loss`.\n elif loss is None:\n raise ValueError(\n \"No loss found. You may have forgotten to provide a `loss` argument \"\n \"in the `compile()` method.\"\n )\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 337, "n_words": 148, "vocab_size": 95, "complexity": 4, "nloc": 12, "token_counts": 38, "n_ast_nodes": 84, "n_identifiers": 5 }, { "id": 276843, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/utils/generic_utils.py", "file_name": "generic_utils.py", "fun_name": "func_load", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def func_load(code, defaults=None, closure=None, globs=None):\n \n if isinstance(code, (tuple, list)): # unpack previous dump\n code, defaults, closure = code\n if isinstance(defaults, list):\n defaults = tuple(defaults)\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 56, "n_words": 24, "vocab_size": 22, "complexity": 7, "nloc": 18, "token_counts": 147, "n_ast_nodes": 78, "n_identifiers": 8 }, { "id": 181893, "commit_id": "388616b6247ca4ea8de4e2f340d6206aee523541", "repo": "tpot", "path": "tpot/driver.py", "file_name": "driver.py", "fun_name": "float_range", "commit_message": "Revert \"Deployed 7ccda9a with MkDocs version: 1.3.0\"\n\nThis reverts commit bd9629c40e01241766197119b581a99409b07068.", "code": "def float_range(value):\n \n try:\n value = float(value)\n except Exception:\n raise argparse.ArgumentTypeError('Invalid float value: \\'{}\\''.format(value))\n if value < 0.0 or value > 1.0:\n raise argparse.ArgumentTypeError('Invalid float value: \\'{}\\''.format(value))\n return value\n\n", "url": "https://github.com/EpistasisLab/tpot.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 64, "n_words": 28, "vocab_size": 20, "complexity": 4, "nloc": 8, "token_counts": 56, "n_ast_nodes": 95, "n_identifiers": 7 }, { "id": 268980, "commit_id": "01c906c4178db5ae03b7eb2d298a052c952a0667", "repo": "keras", "path": "keras/layers/rnn/rnn_utils.py", "file_name": "rnn_utils.py", "fun_name": "config_for_enable_caching_device", "commit_message": "Reorganize RNN layers, cells and wrappers into smaller logically organized files hosted under an `rnn` directory.\n\nPiperOrigin-RevId: 428841673", "code": "def config_for_enable_caching_device(rnn_cell):\n \n default_enable_caching_device = tf.compat.v1.executing_eagerly_outside_functions(\n )\n if rnn_cell._enable_caching_device != default_enable_caching_device:\n return {'enable_caching_device': rnn_cell._enable_caching_device}\n return {}\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 23, "n_words": 15, "vocab_size": 14, "complexity": 2, "nloc": 6, "token_counts": 35, "n_ast_nodes": 61, "n_identifiers": 8 }, { "id": 298605, "commit_id": "23c5bd97793af4eed9806a237593b482f8e1b932", "repo": "core", "path": "tests/components/gree/test_climate.py", "file_name": "test_climate.py", "fun_name": "test_update_hvac_mode", "commit_message": "Use climate enums in gree (#70655)\n\n* Use climate enums in gree\r\n\r\n* Adjust tests", "code": "async def test_update_hvac_mode(hass, discovery, device, mock_now, hvac_mode):\n \n device().power = hvac_mode != HVACMode.OFF\n device().mode = HVAC_MODES_REVERSE.get(hvac_mode)\n\n await async_setup_gree(hass)\n\n state = hass.states.get(ENTITY_ID)\n assert state is not None\n assert state.state == hvac_mode\n\n\n@pytest.mark.parametrize(\n \"fan_mode\",\n (FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),\n)", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "@pytest.mark.parametrize(\n \"fan_mode\",\n (FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),\n)", "n_ast_errors": 1, "ast_levels": 9, "n_whitespaces": 63, "n_words": 38, "vocab_size": 33, "complexity": 1, "nloc": 7, "token_counts": 63, "n_ast_nodes": 134, "n_identifiers": 25 }, { "id": 267080, "commit_id": "62d03c8e752ee35057031a91d7028e0a2e5d43e4", "repo": "ansible", "path": "test/lib/ansible_test/_internal/util.py", "file_name": "util.py", "fun_name": "retry", "commit_message": "ansible-test - Fix subprocess management. (#77638)\n\n* Run code-smell sanity tests in UTF-8 Mode.\r\n* Update subprocess use in sanity test programs.\r\n* Use raw_command instead of run_command with always=True set.\r\n* Add more capture=True usage.\r\n* Don't expose stdin to subprocesses.\r\n* Capture more output. Warn on retry.\r\n* Add more captures.\r\n* Capture coverage cli output.\r\n* Capture windows and network host checks.\r\n* Be explicit about interactive usage.\r\n* Use a shell for non-captured, non-interactive subprocesses.\r\n* Add integration test to assert no TTY.\r\n* Add unit test to assert no TTY.\r\n* Require blocking stdin/stdout/stderr.\r\n* Use subprocess.run in ansible-core sanity tests.\r\n* Remove unused arg.\r\n* Be explicit with subprocess.run check=False.\r\n* Add changelog.", "code": "def retry(func, ex_type=SubprocessError, sleep=10, attempts=10, warn=True):\n \n for dummy in range(1, attempts):\n try:\n return func()\n except ex_type as ex:\n if warn:\n display.warning(str(ex))\n\n time.sleep(sleep)\n\n return func()\n\n", "url": "https://github.com/ansible/ansible.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 95, "n_words": 24, "vocab_size": 22, "complexity": 4, "nloc": 9, "token_counts": 65, "n_ast_nodes": 104, "n_identifiers": 14 }, { "id": 81378, "commit_id": "431b9370dfbbbcb64dee0b4ebc8af7df12740d08", "repo": "awx", "path": "awx/main/models/unified_jobs.py", "file_name": "unified_jobs.py", "fun_name": "event_processing_finished", "commit_message": "Split TaskManager into\n- DependencyManager spawns dependencies if necessary\n- WorkflowManager processes running workflows to see if a new job is\n ready to spawn\n- TaskManager starts tasks if unblocked and has execution capacity", "code": "def event_processing_finished(self):\n \n if self.status in ACTIVE_STATES:\n return False # tally of events is only available at end of run\n try:\n event_qs = self.get_event_queryset()\n except NotImplementedError:\n return True # Model without events, such as WFJT\n return self.emitted_events == event_qs.count()\n", "url": "https://github.com/ansible/awx.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 108, "n_words": 38, "vocab_size": 34, "complexity": 3, "nloc": 9, "token_counts": 45, "n_ast_nodes": 69, "n_identifiers": 9 }, { "id": 20916, "commit_id": "f3166e673fe8d40277b804d35d77dcdb760fc3b3", "repo": "pipenv", "path": "pipenv/patched/notpip/_vendor/typing_extensions.py", "file_name": "typing_extensions.py", "fun_name": "TypeAlias", "commit_message": "check point progress on only bringing in pip==22.0.4 (#4966)\n\n* vendor in pip==22.0.4\r\n\r\n* updating vendor packaging version\r\n\r\n* update pipdeptree to fix pipenv graph with new version of pip.\r\n\r\n* Vendoring of pip-shims 0.7.0\r\n\r\n* Vendoring of requirementslib 1.6.3\r\n\r\n* Update pip index safety restrictions patch for pip==22.0.4\r\n\r\n* Update patches\r\n\r\n* exclude pyptoject.toml from black to see if that helps.\r\n\r\n* Move this part of the hash collection back to the top (like prior implementation) because it affects the outcome of this test now in pip 22.0.4", "code": "def TypeAlias(self, parameters):\n \n raise TypeError(f\"{self} is not subscriptable\")\n# 3.7-3.8\nelif sys.version_info[:2] >= (3, 7):", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "elif sys.version_info[:2] >= (3, 7):sys", "n_ast_errors": 2, "ast_levels": 9, "n_whitespaces": 27, "n_words": 15, "vocab_size": 15, "complexity": 1, "nloc": 2, "token_counts": 14, "n_ast_nodes": 52, "n_identifiers": 7 }, { "id": 224055, "commit_id": "e7f07cc82ab2be920ab426ba07456d8b2592714d", "repo": "mkdocs", "path": "mkdocs/theme.py", "file_name": "theme.py", "fun_name": "_load_theme_config", "commit_message": "Remove spaces at the ends of docstrings, normalize quotes", "code": "def _load_theme_config(self, name):\n \n\n theme_dir = utils.get_theme_dir(name)\n self.dirs.append(theme_dir)\n\n try:\n file_path = os.path.join(theme_dir, 'mkdocs_theme.yml')\n with open(file_path, 'rb') as f:\n theme_config = utils.yaml_load(f)\n if theme_config is None:\n theme_config = {}\n except OSError as e:\n log.debug(e)\n raise ValidationError(\n f\"The theme '{name}' does not appear to have a configuration file. \"\n f\"Please upgrade to a current version of the theme.\"\n )\n\n log.debug(f\"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}\")\n\n parent_theme = theme_config.pop('extends', None)\n if parent_theme:\n themes = utils.get_theme_names()\n if parent_theme not in themes:\n raise ValidationError(\n f\"The theme '{name}' inherits from '{parent_theme}', which does not appear to be installed. \"\n f\"The available installed themes are: {', '.join(themes)}\"\n )\n self._load_theme_config(parent_theme)\n\n self.static_templates.update(theme_config.pop('static_templates', []))\n self._vars.update(theme_config)\n", "url": "https://github.com/mkdocs/mkdocs.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 17, "n_whitespaces": 411, "n_words": 106, "vocab_size": 75, "complexity": 5, "nloc": 27, "token_counts": 155, "n_ast_nodes": 303, "n_identifiers": 28 }, { "id": 47693, "commit_id": "49e336ae0302b386a2f47269a6d13988382d975f", "repo": "airflow", "path": "tests/utils/test_task_group.py", "file_name": "test_task_group.py", "fun_name": "test_default_args", "commit_message": "Replace usage of `DummyOperator` with `EmptyOperator` (#22974)\n\n* Replace usage of `DummyOperator` with `EmptyOperator`", "code": "def test_default_args():\n \n\n execution_date = pendulum.parse(\"20201109\")\n with DAG(\n dag_id='example_task_group_default_args',\n start_date=execution_date,\n default_args={\n \"owner\": \"dag\",\n },\n ):\n with TaskGroup(\"group1\", default_args={\"owner\": \"group\"}):\n task_1 = EmptyOperator(task_id='task_1')\n task_2 = EmptyOperator(task_id='task_2', owner='task')\n task_3 = EmptyOperator(task_id='task_3', default_args={\"owner\": \"task\"})\n\n assert task_1.owner == 'group'\n assert task_2.owner == 'task'\n assert task_3.owner == 'task'\n\n", "url": "https://github.com/apache/airflow.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 166, "n_words": 42, "vocab_size": 32, "complexity": 1, "nloc": 16, "token_counts": 103, "n_ast_nodes": 195, "n_identifiers": 15 }, { "id": 275981, "commit_id": "84afc5193d38057e2e2badf9c889ea87d80d8fbf", "repo": "keras", "path": "keras/saving/saved_model/base_serialization.py", "file_name": "base_serialization.py", "fun_name": "trackable_children", "commit_message": "Reformatting the codebase with black.\n\nPiperOrigin-RevId: 450093126", "code": "def trackable_children(self, serialization_cache):\n \n if not utils.should_save_traces():\n return {}\n\n children = self.objects_to_serialize(serialization_cache)\n children.update(self.functions_to_serialize(serialization_cache))\n return children\n", "url": "https://github.com/keras-team/keras.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 60, "n_words": 14, "vocab_size": 12, "complexity": 2, "nloc": 6, "token_counts": 40, "n_ast_nodes": 68, "n_identifiers": 9 }, { "id": 35104, "commit_id": "2b5603f6ac58f0cd3b2116c01d6b9f62575248b2", "repo": "transformers", "path": "src/transformers/generation_beam_constraints.py", "file_name": "generation_beam_constraints.py", "fun_name": "copy", "commit_message": "Constrained Beam Search [without disjunctive decoding] (#15416)\n\n* added classes to get started with constrained beam search\r\n\r\n* in progress, think i can directly force tokens now but not yet with the round robin\r\n\r\n* think now i have total control, now need to code the bank selection\r\n\r\n* technically works as desired, need to optimize and fix design choices leading to undersirable outputs\r\n\r\n* complete PR #1 without disjunctive decoding\r\n\r\n* removed incorrect tests\r\n\r\n* Delete k.txt\r\n\r\n* Delete test.py\r\n\r\n* Delete test.sh\r\n\r\n* revert changes to test scripts\r\n\r\n* genutils\r\n\r\n* full implementation with testing, no disjunctive yet\r\n\r\n* shifted docs\r\n\r\n* passing all tests realistically ran locally\r\n\r\n* removing accidentally included print statements\r\n\r\n* fixed source of error in initial PR test\r\n\r\n* fixing the get_device() vs device trap\r\n\r\n* fixed documentation docstrings about constrained_beam_search\r\n\r\n* fixed tests having failing for Speech2TextModel's floating point inputs\r\n\r\n* fix cuda long tensor\r\n\r\n* added examples and testing for them and founx & fixed a bug in beam_search and constrained_beam_search\r\n\r\n* deleted accidentally added test halting code with assert False\r\n\r\n* code reformat\r\n\r\n* Update tests/test_generation_utils.py\r\n\r\nCo-authored-by: Patrick von Platen \r\n\r\n* Update tests/test_generation_utils.py\r\n\r\nCo-authored-by: Patrick von Platen \r\n\r\n* Update tests/test_generation_utils.py\r\n\r\nCo-authored-by: Patrick von Platen \r\n\r\n* Update tests/test_generation_utils.py\r\n\r\nCo-authored-by: Patrick von Platen \r\n\r\n* Update tests/test_generation_utils.py\r\n\r\n* fixing based on comments on PR\r\n\r\n* took out the testing code that should but work fails without the beam search moditification ; style changes\r\n\r\n* fixing comments issues\r\n\r\n* docstrings for ConstraintListState\r\n\r\n* typo in PhrsalConstraint docstring\r\n\r\n* docstrings improvements\r\n\r\nCo-authored-by: Patrick von Platen ", "code": "def copy(self, stateful=False):\n \n raise NotImplementedError(\n f\"{self.__class__} is an abstract class. Only classes inheriting this class can be called.\"\n )\n\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 51, "n_words": 19, "vocab_size": 19, "complexity": 1, "nloc": 4, "token_counts": 16, "n_ast_nodes": 35, "n_identifiers": 5 }, { "id": 78341, "commit_id": "d967eccef28ce47f60d26be1c28f2d83a25f40b0", "repo": "wagtail", "path": "wagtail/contrib/settings/tests/site_specific/test_templates.py", "file_name": "test_templates.py", "fun_name": "test_settings_no_request_no_use_default", "commit_message": "Add generic settings to compliment site-specific settings (#8327)", "code": "def test_settings_no_request_no_use_default(self):\n \n context = {}\n\n # Without a request in the context, and without use_default_site, this\n # should bail with an error\n template = '{{ settings(\"tests.testsitesetting\").title }}'\n with self.assertRaises(RuntimeError):\n self.render(template, context, request_context=False)\n", "url": "https://github.com/wagtail/wagtail.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 10, "n_whitespaces": 85, "n_words": 32, "vocab_size": 28, "complexity": 1, "nloc": 5, "token_counts": 33, "n_ast_nodes": 61, "n_identifiers": 8 }, { "id": 97856, "commit_id": "d246d2b6d3e014270941209e54f2f12e09ad9a81", "repo": "sentry", "path": "src/sentry/pipeline/base.py", "file_name": "base.py", "fun_name": "render_warning", "commit_message": "ref(py): Split up large file (#32862)\n\nCo-authored-by: getsantry[bot] <66042841+getsantry[bot]@users.noreply.github.com>", "code": "def render_warning(self, message):\n \n context = {\"error\": message}\n return render_to_response(\"sentry/pipeline-provider-error.html\", context, self.request)\n", "url": "https://github.com/getsentry/sentry.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 32, "n_words": 11, "vocab_size": 11, "complexity": 1, "nloc": 3, "token_counts": 26, "n_ast_nodes": 45, "n_identifiers": 6 }, { "id": 82608, "commit_id": "06c9a85df486581f152dbf11bbf40a1c6c5e6cd3", "repo": "django-cms", "path": "cms/utils/page.py", "file_name": "page.py", "fun_name": "get_page_from_request", "commit_message": "fix: Prefer titles matching request language (#7144)\n\n* prefer titles matching request language\r\n* add comments on use of annotate\r\n* fix wayward imports\r\n* Add changelog entry\r\n\r\nCo-authored-by: Vinit Kumar \r\nCo-authored-by: Mark Walker ", "code": "def get_page_from_request(request, use_path=None, clean_path=None):\n \n from cms.utils.page_permissions import user_can_view_page_draft\n\n if not bool(use_path) and hasattr(request, '_current_page_cache'):\n # The following is set by CurrentPageMiddleware\n return request._current_page_cache\n\n if clean_path is None:\n clean_path = not bool(use_path)\n\n draft = use_draft(request)\n preview = 'preview' in request.GET\n path = request.path_info if use_path is None else use_path\n\n if clean_path:\n pages_root = reverse(\"pages-root\")\n\n if path.startswith(pages_root):\n path = path[len(pages_root):]\n\n # strip any final slash\n if path.endswith(\"/\"):\n path = path[:-1]\n\n site = get_current_site()\n request_language_code = getattr(request, \"LANGUAGE_CODE\", None)\n page = get_page_from_path(\n site, path, preview, draft, language_code=request_language_code\n )\n\n if draft and page and not user_can_view_page_draft(request.user, page):\n page = get_page_from_path(\n site, path, preview, draft=False, language_code=request_language_code\n )\n\n # For public pages, check if any parent is hidden due to published dates\n # In this case the selected page is not reachable\n if page and not draft:\n now = timezone.now()\n unpublished_ancestors = (\n page\n .get_ancestor_pages()\n .filter(\n Q(publication_date__gt=now) | Q(publication_end_date__lt=now),\n )\n )\n if unpublished_ancestors.exists():\n page = None\n return page\n\n", "url": "https://github.com/django-cms/django-cms.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 404, "n_words": 152, "vocab_size": 92, "complexity": 14, "nloc": 36, "token_counts": 235, "n_ast_nodes": 379, "n_identifiers": 39 }, { "id": 132826, "commit_id": "7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065", "repo": "ray", "path": "python/ray/tune/trial.py", "file_name": "trial.py", "fun_name": "__call__", "commit_message": "[CI] Format Python code with Black (#21975)\n\nSee #21316 and #21311 for the motivation behind these changes.", "code": "def __call__(self, checkpoint):\n \n if not self.runner:\n return\n\n if checkpoint.storage == Checkpoint.PERSISTENT and checkpoint.value:\n checkpoint_path = checkpoint.value\n\n logger.debug(\n \"Trial %s: Deleting checkpoint %s\", self.trial_id, checkpoint_path\n )\n\n # TODO(ujvl): Batch remote deletes.\n # We first delete the remote checkpoint. If it is on the same\n # node as the driver, it will also remove the local copy.\n ray.get(self.runner.delete_checkpoint.remote(checkpoint_path))\n\n # Delete local copy, if any exists.\n if os.path.exists(checkpoint_path):\n try:\n checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path)\n shutil.rmtree(checkpoint_dir)\n except FileNotFoundError:\n logger.debug(\"Local checkpoint dir not found during deletion.\")\n\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 312, "n_words": 79, "vocab_size": 63, "complexity": 6, "nloc": 15, "token_counts": 95, "n_ast_nodes": 162, "n_identifiers": 25 }, { "id": 320678, "commit_id": "ab65c542a0551abf105eeb58803cd08bd040753b", "repo": "qutebrowser", "path": "tests/unit/components/test_readlinecommands.py", "file_name": "test_readlinecommands.py", "fun_name": "test_filename_rubout", "commit_message": "Add :rl-rubout and :rl-filename-rubout\n\nCloses #4561", "code": "def test_filename_rubout(os_sep, monkeypatch, lineedit, text, deleted, rest):\n \n monkeypatch.setattr(os, \"sep\", os_sep)\n _validate_deletion(lineedit,\n readlinecommands.rl_filename_rubout, [],\n text, deleted, rest)\n\n\n@pytest.mark.parametrize('text, deleted, rest', [\n pytest.param('test foobar| delete', ' delete', 'test foobar|',\n marks=fixme),\n ('test foobar| delete', ' ', 'test foobar|delete'), # wrong\n pytest.param('test foo|delete bar', 'delete', 'test foo| bar',\n marks=fixme),\n ('test foo|delete bar', 'delete ', 'test foo|bar'), # wrong\n pytest.param('test foo delete', ' delete', 'test foobar|',\n marks=fixme),\n ('test foodelete', 'bardelete', 'test foo|'), # wrong\n])", "url": "https://github.com/qutebrowser/qutebrowser.git", "language": "Python", "ast_errors": "@pytest.mark.parametrize('text, deleted, rest', [\n pytest.param('test foobar| delete', ' delete', 'test foobar|',\n marks=fixme),\n ('test foobar| delete', ' ', 'test foobar|delete'), # wrong\n pytest.param('test foo|delete bar', 'delete', 'test foo| bar',\n marks=fixme),\n ('test foo|delete bar', 'delete ', 'test foo|bar'), # wrong\n pytest.param('test foo delete', ' delete', 'test foobar|',\n marks=fixme),\n ('test foodelete', 'bardelete', 'test foo|'), # wrong\n])", "n_ast_errors": 1, "ast_levels": 10, "n_whitespaces": 190, "n_words": 70, "vocab_size": 40, "complexity": 1, "nloc": 5, "token_counts": 43, "n_ast_nodes": 205, "n_identifiers": 18 }, { "id": 41878, "commit_id": "563e96d3be1eaee8db8dfbccf7eed1f1c66dfd31", "repo": "seaborn", "path": "seaborn/_oldcore.py", "file_name": "_oldcore.py", "fun_name": "_map_attributes", "commit_message": "Downgrade exception on mapping list length mismatch to warning (#2856)\n\n* Downgrade exception on mapping list length mismatch to warning\r\n\r\n* Lint\r\n\r\n* Fix pairplot test\r\n\r\n* Set stacklevel to report warning in user code", "code": "def _map_attributes(self, arg, levels, defaults, attr):\n \n if arg is True:\n lookup_table = dict(zip(levels, defaults))\n elif isinstance(arg, dict):\n missing = set(levels) - set(arg)\n if missing:\n err = f\"These `{attr}` levels are missing values: {missing}\"\n raise ValueError(err)\n lookup_table = arg\n elif isinstance(arg, Sequence):\n arg = self._check_list_length(levels, arg, attr)\n lookup_table = dict(zip(levels, arg))\n elif arg:\n err = f\"This `{attr}` argument was not understood: {arg}\"\n raise ValueError(err)\n else:\n lookup_table = {}\n\n return lookup_table\n\n\n# =========================================================================== #\n\n", "url": "https://github.com/mwaskom/seaborn.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 249, "n_words": 72, "vocab_size": 47, "complexity": 6, "nloc": 18, "token_counts": 115, "n_ast_nodes": 198, "n_identifiers": 16 }, { "id": 300836, "commit_id": "c8f700c80319cef81a9a817c1b9111887ea98b1a", "repo": "core", "path": "homeassistant/components/homekit_controller/connection.py", "file_name": "connection.py", "fun_name": "process_new_events", "commit_message": "Clean up accessing dispatcher helpers via hass (#72014)\n\nClean up accessing ditpatcher helpers via hass", "code": "def process_new_events(self, new_values_dict) -> None:\n \n self.async_set_available_state(True)\n\n # Process any stateless events (via device_triggers)\n async_fire_triggers(self, new_values_dict)\n\n for (aid, cid), value in new_values_dict.items():\n accessory = self.current_state.setdefault(aid, {})\n accessory[cid] = value\n\n # self.current_state will be replaced by entity_map in a future PR\n # For now we update both\n self.entity_map.process_changes(new_values_dict)\n\n async_dispatcher_send(self.hass, self.signal_state_updated)\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 11, "n_whitespaces": 133, "n_words": 48, "vocab_size": 42, "complexity": 2, "nloc": 9, "token_counts": 74, "n_ast_nodes": 119, "n_identifiers": 17 }, { "id": 22222, "commit_id": "cd5a9683be69c86c8f3adcd13385a9bc5db198ec", "repo": "pipenv", "path": "pipenv/vendor/requirementslib/models/dependencies.py", "file_name": "dependencies.py", "fun_name": "get_dependencies", "commit_message": "Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.", "code": "def get_dependencies(ireq, sources=None, parent=None):\n # type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]\n \n if not isinstance(ireq, shims.InstallRequirement):\n name = getattr(ireq, \"project_name\", getattr(ireq, \"project\", ireq.name))\n version = getattr(ireq, \"version\", None)\n if not version:\n ireq = shims.InstallRequirement.from_line(\"{0}\".format(name))\n else:\n ireq = shims.InstallRequirement.from_line(\"{0}=={1}\".format(name, version))\n pip_options = get_pip_options(sources=sources)\n getters = [\n get_dependencies_from_cache,\n get_dependencies_from_wheel_cache,\n get_dependencies_from_json,\n functools.partial(get_dependencies_from_index, pip_options=pip_options),\n ]\n for getter in getters:\n deps = getter(ireq)\n if deps is not None:\n return deps\n raise RuntimeError(\"failed to get dependencies for {}\".format(ireq))\n\n", "url": "https://github.com/pypa/pipenv.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 16, "n_whitespaces": 202, "n_words": 75, "vocab_size": 59, "complexity": 5, "nloc": 20, "token_counts": 150, "n_ast_nodes": 240, "n_identifiers": 24 }, { "id": 119312, "commit_id": "e085370ec4137cf0f73c5163cb664bc4e1c46082", "repo": "jax", "path": "jax/_src/scipy/signal.py", "file_name": "signal.py", "fun_name": "odd_ext", "commit_message": "Add some functions for spectral analysis.\n\nThis commit adds \"stft\", \"csd\", and \"welch\" functions in scipy.signal.", "code": "def odd_ext(x, n, axis=-1):\n \n if n < 1:\n return x\n if n > x.shape[axis] - 1:\n raise ValueError(\n f\"The extension length n ({n}) is too big. \"\n f\"It must not exceed x.shape[axis]-1, which is {x.shape[axis] - 1}.\")\n left_end = lax.slice_in_dim(x, 0, 1, axis=axis)\n left_ext = jnp.flip(lax.slice_in_dim(x, 1, n + 1, axis=axis), axis=axis)\n right_end = lax.slice_in_dim(x, -1, None, axis=axis)\n right_ext = jnp.flip(lax.slice_in_dim(x, -(n + 1), -1, axis=axis), axis=axis)\n ext = jnp.concatenate((2 * left_end - left_ext,\n x,\n 2 * right_end - right_ext),\n axis=axis)\n return ext\n\n", "url": "https://github.com/google/jax.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 184, "n_words": 83, "vocab_size": 54, "complexity": 3, "nloc": 16, "token_counts": 159, "n_ast_nodes": 252, "n_identifiers": 16 }, { "id": 34604, "commit_id": "d25e25ee2b63ebfcd099deb689a5a7272574a10f", "repo": "transformers", "path": "src/transformers/models/xglm/modeling_xglm.py", "file_name": "modeling_xglm.py", "fun_name": "create_position_ids_from_input_ids", "commit_message": "Add XGLM models (#14876)\n\n* add xglm\r\n\r\n* update vocab size\r\n\r\n* fix model name\r\n\r\n* style and tokenizer\r\n\r\n* typo\r\n\r\n* no mask token\r\n\r\n* fix pos embed compute\r\n\r\n* fix args\r\n\r\n* fix tokenizer\r\n\r\n* fix positions\r\n\r\n* fix tokenization\r\n\r\n* style and dic fixes\r\n\r\n* fix imports\r\n\r\n* add fast tokenizer\r\n\r\n* update names\r\n\r\n* add pt tests\r\n\r\n* fix tokenizer\r\n\r\n* fix typo\r\n\r\n* fix tokenizer import\r\n\r\n* fix fast tokenizer\r\n\r\n* fix tokenizer\r\n\r\n* fix converter\r\n\r\n* add tokenizer test\r\n\r\n* update checkpoint names\r\n\r\n* fix tokenizer tests\r\n\r\n* fix slow tests\r\n\r\n* add copied from comments\r\n\r\n* rst -> mdx\r\n\r\n* flax model\r\n\r\n* update flax tests\r\n\r\n* quality\r\n\r\n* style\r\n\r\n* doc\r\n\r\n* update index and readme\r\n\r\n* fix copies\r\n\r\n* fix doc\r\n\r\n* update toctrr\r\n\r\n* fix indent\r\n\r\n* minor fixes\r\n\r\n* fix config doc\r\n\r\n* don't save embed_pos weights\r\n\r\n* Apply suggestions from code review\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\nCo-authored-by: Patrick von Platen \r\n\r\n* address Sylvains commnets, few doc fixes\r\n\r\n* fix check_repo\r\n\r\n* align order of arguments\r\n\r\n* fix copies\r\n\r\n* fix labels\r\n\r\n* remove unnecessary mapping\r\n\r\n* fix saving tokenizer\r\n\r\nCo-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>\r\nCo-authored-by: Patrick von Platen ", "code": "def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):\n \n # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.\n mask = input_ids.ne(padding_idx).int()\n incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask\n return incremental_indices.long() + padding_idx\n\n\n# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding with M2M100->XGLM", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 14, "n_whitespaces": 58, "n_words": 44, "vocab_size": 38, "complexity": 1, "nloc": 4, "token_counts": 55, "n_ast_nodes": 90, "n_identifiers": 13 }, { "id": 101448, "commit_id": "1022651eb8a7741014f5d2ec7cbfe882120dfa5f", "repo": "faceswap", "path": "tools/preview/preview.py", "file_name": "preview.py", "fun_name": "_build_tabs", "commit_message": "Bugfix: convert - Gif Writer\n - Fix non-launch error on Gif Writer\n - convert plugins - linting\n - convert/fs_media/preview/queue_manager - typing\n - Change convert items from dict to Dataclass", "code": "def _build_tabs(self) -> None:\n \n logger.debug(\"Build Tabs\")\n for section in self.config_tools.sections:\n tab = ttk.Notebook(self)\n self._tabs[section] = {\"tab\": tab}\n self.add(tab, text=section.replace(\"_\", \" \").title())\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 75, "n_words": 21, "vocab_size": 20, "complexity": 2, "nloc": 7, "token_counts": 64, "n_ast_nodes": 110, "n_identifiers": 15 }, { "id": 295982, "commit_id": "06d2aeec6b153a104b275c73068cf05a7b5c0c6b", "repo": "core", "path": "tests/components/google/conftest.py", "file_name": "conftest.py", "fun_name": "token_expiry", "commit_message": "Refresh google calendar tokens with invalid expiration times (#69679)\n\n* Refresh google calendar tokens with invalid expiration times\r\n\r\n* Update tests/components/google/conftest.py\r\n\r\nCo-authored-by: Martin Hjelmare \r\n\r\n* Remove unnecessary async methods in functions being touched already\r\n\r\nCo-authored-by: Martin Hjelmare ", "code": "def token_expiry() -> datetime.datetime:\n \n return utcnow() + datetime.timedelta(days=7)\n\n\n@pytest.fixture", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "@pytest.fixture", "n_ast_errors": 1, "ast_levels": 9, "n_whitespaces": 14, "n_words": 9, "vocab_size": 9, "complexity": 1, "nloc": 3, "token_counts": 22, "n_ast_nodes": 46, "n_identifiers": 7 }, { "id": 148501, "commit_id": "16861db653ec8166f73fc8480894f186a137e7bd", "repo": "freqtrade", "path": "freqtrade/optimize/backtesting.py", "file_name": "backtesting.py", "fun_name": "start", "commit_message": "Implement previous backtest result reuse when config and strategy did not change.", "code": "def start(self) -> None:\n \n data: Dict[str, Any] = {}\n\n data, timerange = self.load_bt_data()\n self.load_bt_data_detail()\n logger.info(\"Dataload complete. Calculating indicators\")\n\n run_ids = {\n strategy.get_strategy_name(): get_strategy_run_id(strategy)\n for strategy in self.strategylist\n }\n\n # Load previous result that will be updated incrementally.\n if self.config.get('timerange', '-').endswith('-'):\n self.config['no_backtest_cache'] = True\n logger.warning('Backtest result caching disabled due to use of open-ended timerange.')\n\n if not self.config.get('no_backtest_cache', False):\n self.results = find_existing_backtest_stats(\n self.config['user_data_dir'] / 'backtest_results', run_ids)\n\n for strat in self.strategylist:\n if self.results and strat.get_strategy_name() in self.results['strategy']:\n # When previous result hash matches - reuse that result and skip backtesting.\n logger.info(f'Reusing result of previous backtest for {strat.get_strategy_name()}')\n continue\n min_date, max_date = self.backtest_one_strategy(strat, data, timerange)\n\n # Update old results with new ones.\n if len(self.all_results) > 0:\n results = generate_backtest_stats(\n data, self.all_results, min_date=min_date, max_date=max_date)\n if self.results:\n self.results['metadata'].update(results['metadata'])\n self.results['strategy'].update(results['strategy'])\n self.results['strategy_comparison'].extend(results['strategy_comparison'])\n else:\n self.results = results\n\n if self.config.get('export', 'none') == 'trades':\n store_backtest_stats(self.config['exportfilename'], self.results)\n\n # Results may be mixed up now. Sort them so they follow --strategy-list order.\n if 'strategy_list' in self.config and len(self.results) > 0:\n self.results['strategy_comparison'] = sorted(\n self.results['strategy_comparison'],\n key=lambda c: self.config['strategy_list'].index(c['key']))\n self.results['strategy'] = dict(\n sorted(self.results['strategy'].items(),\n key=lambda kv: self.config['strategy_list'].index(kv[0])))\n\n if len(self.strategylist) > 0:\n # Show backtest results\n show_backtest_results(self.config, self.results)\n", "url": "https://github.com/freqtrade/freqtrade.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 18, "n_whitespaces": 675, "n_words": 181, "vocab_size": 131, "complexity": 13, "nloc": 44, "token_counts": 391, "n_ast_nodes": 672, "n_identifiers": 40 }, { "id": 158185, "commit_id": "b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2", "repo": "d2l-zh", "path": "d2l/mxnet.py", "file_name": "mxnet.py", "fun_name": "evaluate_accuracy", "commit_message": "[PaddlePaddle] Merge master into Paddle branch (#1186)\n\n* change 15.2 title in chinese version (#1109)\r\n\r\nchange title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘\r\n\r\n* 修改部分语义表述 (#1105)\r\n\r\n* Update r0.17.5 (#1120)\r\n\r\n* Bump versions in installation\r\n\r\n* 94行typo: (“bert.mall”)->(“bert.small”) (#1129)\r\n\r\n* line 313: \"bert.mall\" -> \"bert.small\" (#1130)\r\n\r\n* fix: update language as native reader (#1114)\r\n\r\n* Fix the translation of \"stride\" (#1115)\r\n\r\n* Update index.md (#1118)\r\n\r\n修改部分语义表述\r\n\r\n* Update self-attention-and-positional-encoding.md (#1133)\r\n\r\n依照本书的翻译习惯,将pooling翻译成汇聚\r\n\r\n* maybe a comment false (#1149)\r\n\r\n* maybe a little false\r\n\r\n* maybe a little false\r\n\r\n* A minor bug in the rcnn section (Chinese edition) (#1148)\r\n\r\n* Update bert.md (#1137)\r\n\r\n一个笔误\r\n# 假设batch_size=2,num_pred_positions=3\r\n# 那么batch_idx应该是np.repeat( [0,1], 3 ) = [0,0,0,1,1,1]\r\n\r\n* Update calculus.md (#1135)\r\n\r\n* fix typo in git documentation (#1106)\r\n\r\n* fix: Update the Chinese translation in lr-scheduler.md (#1136)\r\n\r\n* Update lr-scheduler.md\r\n\r\n* Update chapter_optimization/lr-scheduler.md\r\n\r\nCo-authored-by: goldmermaid \r\n\r\nCo-authored-by: goldmermaid \r\n\r\n* fix translation for kaggle-house-price.md (#1107)\r\n\r\n* fix translation for kaggle-house-price.md\r\n\r\n* fix translation for kaggle-house-price.md\r\n\r\nSigned-off-by: sunhaizhou \r\n\r\n* Update weight-decay.md (#1150)\r\n\r\n* Update weight-decay.md\r\n\r\n关于“k多选d”这一部分,中文读者使用排列组合的方式可能更容易理解\r\n关于“给定k个变量,阶数的个数为...”这句话是有歧义的,不是很像中国话,应该是说“阶数为d的项的个数为...”。\r\n并增加了一句对“因此即使是阶数上的微小变化,比如从$2$到$3$,也会显著增加我们模型的复杂性。”的解释\r\n解释为何会增加复杂性以及为何需要细粒度工具。\r\n\r\n* Update chapter_multilayer-perceptrons/weight-decay.md\r\n\r\nyep\r\n\r\nCo-authored-by: goldmermaid \r\n\r\n* Update chapter_multilayer-perceptrons/weight-decay.md\r\n\r\nyep\r\n\r\nCo-authored-by: goldmermaid \r\n\r\nCo-authored-by: goldmermaid \r\n\r\n* Fix a spelling error (#1161)\r\n\r\n* Update gru.md (#1152)\r\n\r\nThe key distinction between vanilla RNNs and GRUs is that the latter support gating of the hidden state.\r\n翻译错误\r\n\r\n* Unify the function naming (#1113)\r\n\r\nUnify naming of the function 'init_xavier()'.\r\n\r\n* Update mlp-concise.md (#1166)\r\n\r\n* Update mlp-concise.md\r\n\r\n语句不通顺\r\n\r\n* Update environment.md\r\n\r\n语序异常\r\n\r\n* Update config.ini\r\n\r\n* fix the imprecise description (#1168)\r\n\r\nCo-authored-by: yuande \r\n\r\n* fix typo in chapter_natural-language-processing-pretraining/glove.md (#1175)\r\n\r\n* Fix some typos. (#1163)\r\n\r\n* Update batch-norm.md (#1170)\r\n\r\nfixing typos u->x in article\r\n\r\n* Update linear-regression.md (#1090)\r\n\r\nWe invoke Stuart Russell and Peter Norvig who, in their classic AI text book Artificial Intelligence: A Modern Approach :cite:Russell.Norvig.2016, pointed out that\r\n\r\n原译文把who也直接翻译出来了。\r\n\r\n* Update mlp.md (#1117)\r\n\r\n* Update mlp.md\r\n\r\n修改部分语义表述\r\n\r\n* Update chapter_multilayer-perceptrons/mlp.md\r\n\r\nCo-authored-by: goldmermaid \r\n\r\n* Update chapter_multilayer-perceptrons/mlp.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\nCo-authored-by: goldmermaid \r\n\r\n* Correct a translation error. (#1091)\r\n\r\n* Correct a translation error.\r\n\r\n* Update chapter_computer-vision/image-augmentation.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Update aws.md (#1121)\r\n\r\n* Update aws.md\r\n\r\n* Update chapter_appendix-tools-for-deep-learning/aws.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Update image-augmentation.md (#1093)\r\n\r\n* Update anchor.md (#1088)\r\n\r\nfix a minor issue in code\r\n\r\n* Update anchor.md\r\n\r\n* Update image-augmentation.md\r\n\r\n* fix typo and improve translation in chapter_linear-networks\\softmax-regression.md (#1087)\r\n\r\n* Avoid `torch.meshgrid` user warning (#1174)\r\n\r\nAvoids the following user warning:\r\n```python\r\n~/anaconda3/envs/torch/lib/python3.10/site-packages/torch/functional.py:568: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ../aten/src/ATen/native/TensorShape.cpp:2228.)\r\n return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]\r\n```\r\n\r\n* bump to 2.0.0-beta1\r\n\r\n* Update sequence.md\r\n\r\n* bump beta1 on readme\r\n\r\n* Add latex code block background to config\r\n\r\n* BLD: Bump python support version 3.9 (#1183)\r\n\r\n* BLD: Bump python support version 3.9\r\n\r\n* Remove clear and manually downgrade protobuf 4.21.4 to 3.19.4\r\n\r\n* BLD: Bump torch and tensorflow\r\n\r\n* Update Jenkinsfile\r\n\r\n* Update chapter_installation/index.md\r\n\r\n* Update chapter_installation/index.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Update config.ini\r\n\r\n* Update INFO.md\r\n\r\n* Update INFO.md\r\n\r\n* Drop mint to show code in pdf, use Inconsolata font, apply code cell color (#1187)\r\n\r\n* resolve the conflicts\r\n\r\n* revise from publisher (#1089)\r\n\r\n* revise from publisher\r\n\r\n* d2l api\r\n\r\n* post_latex\r\n\r\n* revise from publisher\r\n\r\n* revise ch11\r\n\r\n* Delete d2l-Copy1.bib\r\n\r\n* clear cache\r\n\r\n* rm d2lbook clear\r\n\r\n* debug anchor\r\n\r\n* keep original d2l doc\r\n\r\nCo-authored-by: Ubuntu \r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\nCo-authored-by: Aston Zhang \r\n\r\n* 重复语句 (#1188)\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Improve expression for chapter_preliminaries/pandas.md (#1184)\r\n\r\n* Update pandas.md\r\n\r\n* Improve expression\r\n\r\n* Improve expression\r\n\r\n* Update chapter_preliminaries/pandas.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Improce expression for chapter_preliminaries/linear-algebra.md (#1185)\r\n\r\n* Improce expression\r\n\r\n* Improve code comments\r\n\r\n* Update chapter_preliminaries/linear-algebra.md\r\n\r\n* Update chapter_preliminaries/linear-algebra.md\r\n\r\n* Update chapter_preliminaries/linear-algebra.md\r\n\r\n* Update chapter_preliminaries/linear-algebra.md\r\n\r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\n\r\n* Fix multibox_detection bugs\r\n\r\n* Update d2l to 0.17.5 version\r\n\r\n* restore older version\r\n\r\n* Upgrade pandas\r\n\r\n* change to python3.8\r\n\r\n* Test warning log\r\n\r\n* relocate warning log\r\n\r\n* test logs filtering\r\n\r\n* Update gru.md\r\n\r\n* Add DeprecationWarning filter\r\n\r\n* Test warning log\r\n\r\n* Update attention mechanisms & computational performance\r\n\r\n* Update multilayer perceptron& linear & convolution networks & computer vision\r\n\r\n* Update recurrent&optimition&nlp pretraining & nlp applications\r\n\r\n* ignore warnings\r\n\r\n* Update index.md\r\n\r\n* Update linear networks\r\n\r\n* Update multilayer perceptrons&deep learning computation\r\n\r\n* Update preliminaries\r\n\r\n* Check and Add warning filter\r\n\r\n* Update kaggle-cifar10.md\r\n\r\n* Update object-detection-dataset.md\r\n\r\n* Update ssd.md fcn.md\r\n\r\n* Update hybridize.md\r\n\r\n* Update hybridize.md\r\n\r\nSigned-off-by: sunhaizhou \r\nCo-authored-by: zhou201505013 <39976863+zhou201505013@users.noreply.github.com>\r\nCo-authored-by: Xinwei Liu \r\nCo-authored-by: Anirudh Dagar \r\nCo-authored-by: Aston Zhang <22279212+astonzhang@users.noreply.github.com>\r\nCo-authored-by: hugo_han <57249629+HugoHann@users.noreply.github.com>\r\nCo-authored-by: gyro永不抽风 <1247006353@qq.com>\r\nCo-authored-by: CanChengZheng \r\nCo-authored-by: linlin \r\nCo-authored-by: iuk \r\nCo-authored-by: yoos <49556860+liyunlongaaa@users.noreply.github.com>\r\nCo-authored-by: Mr. Justice Lawrence John Wargrave <65226618+RUCWargrave@users.noreply.github.com>\r\nCo-authored-by: Chiyuan Fu \r\nCo-authored-by: Sunhuashan <48636870+Sunhuashan@users.noreply.github.com>\r\nCo-authored-by: Haiker Sun \r\nCo-authored-by: Ming Liu \r\nCo-authored-by: goldmermaid \r\nCo-authored-by: silenceZheng66 <13754430639@163.com>\r\nCo-authored-by: Wenchao Yan <56541797+YWonchall@users.noreply.github.com>\r\nCo-authored-by: Kiki2049 <55939997+Kiki2049@users.noreply.github.com>\r\nCo-authored-by: Krahets \r\nCo-authored-by: friedmainfunction <73703265+friedmainfunction@users.noreply.github.com>\r\nCo-authored-by: Jameson \r\nCo-authored-by: P. Yao <12227516+YaoPengCN@users.noreply.github.com>\r\nCo-authored-by: Yulv-git <34329208+Yulv-git@users.noreply.github.com>\r\nCo-authored-by: Liu,Xiao <45966993+liuxiao916@users.noreply.github.com>\r\nCo-authored-by: YIN, Gang <1246410+yingang@users.noreply.github.com>\r\nCo-authored-by: Joe-HZ <58297431+Joe-HZ@users.noreply.github.com>\r\nCo-authored-by: lybloveyou <102609904+lybloveyou@users.noreply.github.com>\r\nCo-authored-by: VigourJiang \r\nCo-authored-by: zxhd863943427 <74853597+zxhd863943427@users.noreply.github.com>\r\nCo-authored-by: LYF <27893441+liyufan@users.noreply.github.com>\r\nCo-authored-by: Aston Zhang \r\nCo-authored-by: xiaotinghe \r\nCo-authored-by: Ubuntu \r\nCo-authored-by: Holly-Max <60691735+Holly-Max@users.noreply.github.com>\r\nCo-authored-by: HinGwenWoong \r\nCo-authored-by: Shuai Zhang ", "code": "def evaluate_accuracy(net, data_iter):\n \n metric = Accumulator(2) # No. of correct predictions, no. of predictions\n for X, y in data_iter:\n metric.add(accuracy(net(X), y), d2l.size(y))\n return metric[0] / metric[1]\n", "url": "https://github.com/d2l-ai/d2l-zh.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 13, "n_whitespaces": 46, "n_words": 26, "vocab_size": 25, "complexity": 2, "nloc": 5, "token_counts": 52, "n_ast_nodes": 82, "n_identifiers": 11 }, { "id": 287724, "commit_id": "ab4c1ebfd6ab79abfc4e214853f71afba2380099", "repo": "core", "path": "homeassistant/components/braviatv/coordinator.py", "file_name": "coordinator.py", "fun_name": "async_terminate_apps", "commit_message": "Add Button platform to Bravia TV (#78093)\n\n* Add Button platform to Bravia TV\r\n\r\n* Add button.py to coveragerc\r\n\r\n* improve callable type", "code": "async def async_terminate_apps(self) -> None:\n \n await self.client.terminate_apps()\n", "url": "https://github.com/home-assistant/core.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 9, "n_whitespaces": 21, "n_words": 7, "vocab_size": 7, "complexity": 1, "nloc": 3, "token_counts": 16, "n_ast_nodes": 31, "n_identifiers": 4 }, { "id": 139515, "commit_id": "bc3a1d35cf6e9a5fd7eef908a8e76aefb80ce6a9", "repo": "ray", "path": "rllib/policy/torch_policy_v2.py", "file_name": "torch_policy_v2.py", "fun_name": "extra_compute_grad_fetches", "commit_message": "[RLlib] Introduce new policy base classes. (#24742)", "code": "def extra_compute_grad_fetches(self) -> Dict[str, Any]:\n \n return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc.\n", "url": "https://github.com/ray-project/ray.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 8, "n_whitespaces": 29, "n_words": 14, "vocab_size": 14, "complexity": 1, "nloc": 8, "token_counts": 20, "n_ast_nodes": 34, "n_identifiers": 6 }, { "id": 248550, "commit_id": "2959184a42398277ff916206235b844a8f7be5d7", "repo": "synapse", "path": "tests/test_event_auth.py", "file_name": "test_event_auth.py", "fun_name": "test_join_rules_public", "commit_message": "EventAuthTestCase: build events for the right room version\n\nIn practice, when we run the auth rules, all of the events have the right room\nversion. Let's stop building Room V1 events for these tests and use the right\nversion.", "code": "def test_join_rules_public(self):\n \n creator = \"@creator:example.com\"\n pleb = \"@joiner:example.com\"\n\n auth_events = {\n (\"m.room.create\", \"\"): _create_event(RoomVersions.V6, creator),\n (\"m.room.member\", creator): _join_event(RoomVersions.V6, creator),\n (\"m.room.join_rules\", \"\"): _join_rules_event(\n RoomVersions.V6, creator, \"public\"\n ),\n }\n\n # Check join.\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _join_event(RoomVersions.V6, pleb),\n auth_events.values(),\n )\n\n # A user cannot be force-joined to a room.\n with self.assertRaises(AuthError):\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _member_event(RoomVersions.V6, pleb, \"join\", sender=creator),\n auth_events.values(),\n )\n\n # Banned should be rejected.\n auth_events[(\"m.room.member\", pleb)] = _member_event(\n RoomVersions.V6, pleb, \"ban\"\n )\n with self.assertRaises(AuthError):\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _join_event(RoomVersions.V6, pleb),\n auth_events.values(),\n )\n\n # A user who left can re-join.\n auth_events[(\"m.room.member\", pleb)] = _member_event(\n RoomVersions.V6, pleb, \"leave\"\n )\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _join_event(RoomVersions.V6, pleb),\n auth_events.values(),\n )\n\n # A user can send a join if they're in the room.\n auth_events[(\"m.room.member\", pleb)] = _member_event(\n RoomVersions.V6, pleb, \"join\"\n )\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _join_event(RoomVersions.V6, pleb),\n auth_events.values(),\n )\n\n # A user can accept an invite.\n auth_events[(\"m.room.member\", pleb)] = _member_event(\n RoomVersions.V6, pleb, \"invite\", sender=creator\n )\n event_auth.check_auth_rules_for_event(\n RoomVersions.V6,\n _join_event(RoomVersions.V6, pleb),\n auth_events.values(),\n )\n", "url": "https://github.com/matrix-org/synapse.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 717, "n_words": 145, "vocab_size": 68, "complexity": 1, "nloc": 54, "token_counts": 309, "n_ast_nodes": 488, "n_identifiers": 17 }, { "id": 178014, "commit_id": "583b3cb3b03a36a30b3ce9fe96eb4fb28548a070", "repo": "label-studio", "path": "label_studio/core/label_config.py", "file_name": "label_config.py", "fun_name": "check_toname_in_config_by_regex", "commit_message": "fix: DEV-1462: Fix changing label config for repeater tag (#2725)\n\n* fix: DEV-1462: Fix changing label config for repeater tag with created annotations", "code": "def check_toname_in_config_by_regex(config_string, to_name, control_type=None):\n \n c = parse_config(config_string)\n if control_type:\n check_list = [control_type]\n else:\n check_list = list(c.keys())\n for control in check_list:\n item = c[control].get('regex', {})\n for to_name_item in c[control]['to_name']:\n expression = to_name_item\n for key in item:\n expression = expression.replace(key, item[key])\n pattern = re.compile(expression)\n full_match = pattern.fullmatch(to_name)\n if full_match:\n return True\n return False\n\n", "url": "https://github.com/heartexlabs/label-studio.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 15, "n_whitespaces": 182, "n_words": 51, "vocab_size": 35, "complexity": 6, "nloc": 17, "token_counts": 112, "n_ast_nodes": 179, "n_identifiers": 21 }, { "id": 100928, "commit_id": "bad5025aea1adb9126580e14e064e6c99089243d", "repo": "faceswap", "path": "lib/gui/control_helper.py", "file_name": "control_helper.py", "fun_name": "ask_multi_load", "commit_message": "Core updates\n - Change loss loading mechanism\n - Autosize tooltips based on content size\n - Random linting + code modernisation", "code": "def ask_multi_load(filepath, filetypes):\n \n filenames = FileHandler(\"filename_multi\", filetypes).return_file\n if filenames:\n final_names = \" \".join(f\"\\\"{fname}\\\"\" for fname in filenames)\n logger.debug(final_names)\n filepath.set(final_names)\n", "url": "https://github.com/deepfakes/faceswap.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 12, "n_whitespaces": 73, "n_words": 19, "vocab_size": 18, "complexity": 3, "nloc": 6, "token_counts": 46, "n_ast_nodes": 85, "n_identifiers": 12 }, { "id": 38106, "commit_id": "afe5d42d8d1d80af911ed980c2936bfe887078f6", "repo": "transformers", "path": "examples/research_projects/fsner/src/fsner/tokenizer_utils.py", "file_name": "tokenizer_utils.py", "fun_name": "tokenize", "commit_message": "Black preview (#17217)\n\n* Black preview\r\n\r\n* Fixup too!\r\n\r\n* Fix check copies\r\n\r\n* Use the same version as the CI\r\n\r\n* Bump black", "code": "def tokenize(self, x):\n \n\n if isinstance(x, list) and all([isinstance(_x, list) for _x in x]):\n d = None\n for l in x:\n t = self.tokenizer(\n l,\n padding=\"max_length\",\n max_length=384,\n truncation=True,\n return_tensors=\"pt\",\n )\n t[\"sizes\"] = torch.tensor([len(l)])\n if d is not None:\n for k in d.keys():\n d[k] = torch.cat((d[k], t[k]), 0)\n else:\n d = t\n\n d[\"start_token_id\"] = torch.tensor(self.tokenizer.convert_tokens_to_ids(\"[E]\"))\n d[\"end_token_id\"] = torch.tensor(self.tokenizer.convert_tokens_to_ids(\"[/E]\"))\n\n elif isinstance(x, list) and all([isinstance(_x, str) for _x in x]):\n d = self.tokenizer(\n x,\n padding=\"max_length\",\n max_length=384,\n truncation=True,\n return_tensors=\"pt\",\n )\n\n else:\n raise Exception(\n \"Type of parameter x was not recognized! Only `list of strings` for query or `list of lists of\"\n \" strings` for supports are supported.\"\n )\n\n return d\n", "url": "https://github.com/huggingface/transformers.git", "language": "Python", "ast_errors": "", "n_ast_errors": 0, "ast_levels": 18, "n_whitespaces": 564, "n_words": 105, "vocab_size": 64, "complexity": 10, "nloc": 33, "token_counts": 219, "n_ast_nodes": 349, "n_identifiers": 24 }, { "id": 266410, "commit_id": "f78deccec2d4b5447f32d4fc67eaa549f479ccaa", "repo": "ansible", "path": "lib/ansible/executor/playbook_executor.py", "file_name": "playbook_executor.py", "fun_name": "run", "commit_message": "end_play: end the current play only (#76674)\n\nFixes #76672", "code": "def run(self):\n \n\n result = 0\n entrylist = []\n entry = {}\n try:\n # preload become/connection/shell to set config defs cached\n list(connection_loader.all(class_only=True))\n list(shell_loader.all(class_only=True))\n list(become_loader.all(class_only=True))\n\n for playbook in self._playbooks:\n\n # deal with FQCN\n resource = _get_collection_playbook_path(playbook)\n if resource is not None:\n playbook_path = resource[1]\n playbook_collection = resource[2]\n else:\n playbook_path = playbook\n # not fqcn, but might still be colleciotn playbook\n playbook_collection = _get_collection_name_from_path(playbook)\n\n if playbook_collection:\n display.warning(\"running playbook inside collection {0}\".format(playbook_collection))\n AnsibleCollectionConfig.default_collection = playbook_collection\n else:\n AnsibleCollectionConfig.default_collection = None\n\n pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader)\n # FIXME: move out of inventory self._inventory.set_playbook_basedir(os.path.realpath(os.path.dirname(playbook_path)))\n\n if self._tqm is None: # we are doing a listing\n entry = {'playbook': playbook_path}\n entry['plays'] = []\n else:\n # make sure the tqm has callbacks loaded\n self._tqm.load_callbacks()\n self._tqm.send_callback('v2_playbook_on_start', pb)\n\n i = 1\n plays = pb.get_plays()\n display.vv(u'%d plays in %s' % (len(plays), to_text(playbook_path)))\n\n for play in plays:\n if play._included_path is not None:\n self._loader.set_basedir(play._included_path)\n else:\n self._loader.set_basedir(pb._basedir)\n\n # clear any filters which may have been applied to the inventory\n self._inventory.remove_restriction()\n\n # Allow variables to be used in vars_prompt fields.\n all_vars = self._variable_manager.get_vars(play=play)\n templar = Templar(loader=self._loader, variables=all_vars)\n setattr(play, 'vars_prompt', templar.template(play.vars_prompt))\n\n # FIXME: this should be a play 'sub object' like loop_control\n if play.vars_prompt:\n for var in play.vars_prompt:\n vname = var['name']\n prompt = var.get(\"prompt\", vname)\n default = var.get(\"default\", None)\n private = boolean(var.get(\"private\", True))\n confirm = boolean(var.get(\"confirm\", False))\n encrypt = var.get(\"encrypt\", None)\n salt_size = var.get(\"salt_size\", None)\n salt = var.get(\"salt\", None)\n unsafe = var.get(\"unsafe\", None)\n\n if vname not in self._variable_manager.extra_vars:\n if self._tqm:\n self._tqm.send_callback('v2_playbook_on_vars_prompt', vname, private, prompt, encrypt, confirm, salt_size, salt,\n default, unsafe)\n play.vars[vname] = display.do_var_prompt(vname, private, prompt, encrypt, confirm, salt_size, salt, default, unsafe)\n else: # we are either in --list-