Mir-2002/python_code_docstring_ast_corpus
Overview This dataset contains 34,000+ rows of code-docstring-ast data along with additional metadata. Data was gathered from various Python libraries and frameworks and their publicly available GitHub repos. This dataset was created for the purpose of training the CodeT5+ transformer on AST-enhanced code-to-doc tasks. Sources The dataset was gathered from various GitHub repos sampled from this repo by Vinta. The 26 repos are: matplotlib pytorch cryptography… See the full description on the dataset page: https://huggingface.co/datasets/Mir-2002/python_code_docstring_ast_corpus.
1137
1[
2 {
3 "library": "tensorflow",
4 "name": "serialize_object_graph_with_registered_savers",
5 "source_code": "def serialize_object_graph_with_registered_savers(graph_view, saveables_cache):\n return serialize_gathered_objects(graph_view, saveables_cache=saveables_cache)",
6 "docstring": "Determine checkpoint keys for variables and build a serialized graph.",
7 "type": "function",
8 "file_path": "tensorflow\\tensorflow\\python\\checkpoint\\save_util_v1.py",
9 "ast_data": "FunctionDef name:serialize_object_graph_with_registered_savers arg:graph_view arg:saveables_cache arguments arg arg Return return:yes Call"
10 },
11 {
12 "library": "tensorflow",
13 "name": "arange",
14 "source_code": "@tf_export.tf_export('experimental.numpy.arange', v1=[])\n@np_utils.np_doc('arange')\ndef arange(start, stop=None, step=1, dtype=None):\n if not step:\n raise ValueError('step must be non-zero.')\n if dtype:\n dtype = np_utils.result_type(dtype)\n elif stop is None:\n dtype = np_utils.result_type(start, step)\n else:\n dtype = np_utils.result_type(start, step, stop)\n if step > 0 and (stop is not None and start > stop or (stop is None and start < 0)):\n return array([], dtype=dtype)\n if step < 0 and (stop is not None and start < stop or (stop is None and start > 0)):\n return array([], dtype=dtype)\n return math_ops.cast(math_ops.range(start, limit=stop, delta=step), dtype=dtype)",
15 "docstring": "Returns -separated values in the range [start, stop). Args: start: Start of the interval. Included in the range. stop: End of the interval. If not specified, is treated as 0 and value is used as . If specified, it is not included in the range if is integer. When is floating point, it may or may not be included. step: The difference between 2 consecutive values in the output range. It is recommended to use instead of using non-integer values for . dtype: Optional. Type of the resulting ndarray. Could be a python type, a NumPy type or a TensorFlow . If not provided, the largest type of , , is used. Raises: ValueError: If step is zero.",
16 "type": "function",
17 "file_path": "tensorflow\\tensorflow\\python\\ops\\numpy_ops\\np_array_ops.py",
18 "ast_data": "FunctionDef name:arange arg:start arg:stop arg:step arg:dtype arguments arg arg arg arg If Raise Call If Assign Call If Compare Assign Call Assign Call If BoolOp Compare BoolOp BoolOp Compare Compare BoolOp Compare Compare Return return:yes Call If BoolOp Compare BoolOp BoolOp Compare Compare BoolOp Compare Compare Return return:yes Call Return return:yes Call Call Call Call"
19 },
20 {
21 "library": "tensorflow",
22 "name": "get_sharded_shape",
23 "source_code": "def get_sharded_shape(self, shape, shard_index=None):\n if self._shard_dimension is None or self._number_of_shards is None:\n return None\n if shard_index is not None:\n if shard_index < 0 or shard_index >= self.number_of_shards:\n raise ValueError(f'Requested shard_index {shard_index}, but shard_index must be in [0,{self._number_of_shards}).')\n shape = tensor_shape.as_shape(shape)\n if self._number_of_shards == 1:\n return shape\n ndims = shape.ndims\n if ndims is None:\n raise ValueError(f'Shape {shape} must be a known shape.')\n if ndims <= self._shard_dimension:\n raise ValueError(f'Shape {shape.as_list()} does not contain shard_dimension {self._shard_dimension}')\n dims = shape.as_list()\n if dims[self._shard_dimension] is None:\n raise ValueError(f'Shape {shape.as_list()} must have a fixed size for dimension {self._shard_dimension} that is known at construction time.')\n if dims[self._shard_dimension] % self._number_of_shards != 0:\n raise ValueError(f'Shape {shape.as_list()} cannot be sharded {self._number_of_shards} ways along dimension {self._shard_dimension}')\n dims[self._shard_dimension] //= self._number_of_shards\n return tensor_shape.TensorShape(dims)",
24 "docstring": "Returns the shape of a shard of a full Tensor. When given the shape of a 'full-size' Tensor, returns the shape of the sub-Tensor after it has been sharded. Freezes the policy if it has not yet been frozen. Args: shape: The shape of the full-size Tensor to be sharded. shard_index: The index of the shard whose shape should be returned. shard_index can be None for sharding policies that use the same shape for every shard. Returns: The shape of the sharded version of the Tensor. Raises: ValueError: If shard_index is None when shards are of different shapes; or shard_index is not None and !(0<=shard_index<number_of_shards); or shape does not have at least self.shard_dimension+1 dimensions; or the value of shape's shard dimension is not a multiple of self.number_of_shards",
25 "type": "method",
26 "file_path": "tensorflow\\tensorflow\\python\\tpu\\tpu_sharding.py",
27 "ast_data": "FunctionDef name:get_sharded_shape arg:self arg:shape arg:shard_index arguments arg arg arg If BoolOp Compare Compare Return return:no If Compare If BoolOp Compare Compare Raise Call Assign Call If Compare Return return:yes Assign If Compare Raise Call If Compare Raise Call Call Assign Call If Compare Raise Call Call If Compare Raise Call Call Return return:yes Call"
28 },
29 {
30 "library": "scipy",
31 "name": "_accept_trial",
32 "source_code": "def _accept_trial(self, energy_trial, feasible_trial, cv_trial, energy_orig, feasible_orig, cv_orig):\n if feasible_orig and feasible_trial:\n return energy_trial <= energy_orig\n elif feasible_trial and (not feasible_orig):\n return True\n elif not feasible_trial and (cv_trial <= cv_orig).all():\n return True\n return False",
33 "docstring": "Trial is accepted if: * it satisfies all constraints and provides a lower or equal objective function value, while both the compared solutions are feasible - or - * it is feasible while the original solution is infeasible, - or - * it is infeasible, but provides a lower or equal constraint violation for all constraint functions. This test corresponds to section III of Lampinen [1]_. Parameters ---------- energy_trial : float Energy of the trial solution feasible_trial : float Feasibility of trial solution cv_trial : array-like Excess constraint violation for the trial solution energy_orig : float Energy of the original solution feasible_orig : float Feasibility of original solution cv_orig : array-like Excess constraint violation for the original solution Returns ------- accepted : bool",
34 "type": "method",
35 "file_path": "scipy\\scipy\\optimize\\_differentialevolution.py",
36 "ast_data": "FunctionDef name:_accept_trial arg:self arg:energy_trial arg:feasible_trial arg:cv_trial arg:energy_orig arg:feasible_orig arg:cv_orig arguments arg arg arg arg arg arg arg If BoolOp Return return:yes Compare If BoolOp Return return:yes If BoolOp Call Compare Return return:yes Return return:yes"
37 },
38 {
39 "library": "tensorflow",
40 "name": "cast",
41 "source_code": "def cast(self, value, casting_context):\n if casting_context.allow_specs and isinstance(value, TensorSpec):\n assert value.is_subtype_of(self), f'Can not cast {value!r} to {self!r}'\n return self\n if not isinstance(value, Tensor):\n value = tensor_conversion_registry.convert(value, self.dtype)\n value_spec = TensorSpec(value.shape, value.dtype, self.name)\n if not value_spec.is_subtype_of(self):\n if self.is_subtype_of(value_spec):\n value.set_shape(self.shape)\n else:\n raise TypeError(f'Can not cast {value_spec!r} to {self!r}')\n return value",
42 "docstring": "Cast value to a tensor that is a subtype of this TensorSpec.",
43 "type": "method",
44 "file_path": "tensorflow\\tensorflow\\python\\framework\\tensor.py",
45 "ast_data": "FunctionDef name:cast arg:self arg:value arg:casting_context arguments arg arg arg If BoolOp Call Call Return return:yes If Call Assign Call Assign Call If Call If Call Call Raise Call Return return:yes"
46 },
47 {
48 "library": "django",
49 "name": "RemoveIndexConcurrently",
50 "source_code": "class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex):\n atomic = False\n category = OperationCategory.REMOVAL\n\n def describe(self):\n return 'Concurrently remove index %s from %s' % (self.name, self.model_name)\n\n def database_forwards(self, app_label, schema_editor, from_state, to_state):\n self._ensure_not_in_transaction(schema_editor)\n model = from_state.apps.get_model(app_label, self.model_name)\n if self.allow_migrate_model(schema_editor.connection.alias, model):\n from_model_state = from_state.models[app_label, self.model_name_lower]\n index = from_model_state.get_index_by_name(self.name)\n schema_editor.remove_index(model, index, concurrently=True)\n\n def database_backwards(self, app_label, schema_editor, from_state, to_state):\n self._ensure_not_in_transaction(schema_editor)\n model = to_state.apps.get_model(app_label, self.model_name)\n if self.allow_migrate_model(schema_editor.connection.alias, model):\n to_model_state = to_state.models[app_label, self.model_name_lower]\n index = to_model_state.get_index_by_name(self.name)\n schema_editor.add_index(model, index, concurrently=True)",
51 "docstring": "Remove an index using PostgreSQL's DROP INDEX CONCURRENTLY syntax.",
52 "type": "class",
53 "file_path": "django\\django\\contrib\\postgres\\operations.py",
54 "ast_data": "ClassDef name:RemoveIndexConcurrently Assign Assign FunctionDef name:describe arg:self arguments arg Return return:yes FunctionDef name:database_forwards arg:self arg:app_label arg:schema_editor arg:from_state arg:to_state arguments arg arg arg arg arg Call Assign Call If Call Assign Assign Call Call FunctionDef name:database_backwards arg:self arg:app_label arg:schema_editor arg:from_state arg:to_state arguments arg arg arg arg arg Call Assign Call If Call Assign Assign Call Call"
55 },
56 {
57 "library": "pytorch",
58 "name": "try_add_pt2_compile",
59 "source_code": "@staticmethod\ndef try_add_pt2_compile(event_name: str, **metadata: object):\n if not chromium_event_log_active():\n return\n chromium_log = get_chromium_event_logger()\n chromium_log.try_add_event_data(event_name, **metadata)",
60 "docstring": "Adds to an existing pt2_compile event, but silently returns if the event doesn't exist or ChromiumEventLogger is not initialized. This function is syntactic sugar for chromium_event_logger().try_add_event_data.",
61 "type": "method",
62 "file_path": "pytorch\\torch\\_dynamo\\utils.py",
63 "ast_data": "FunctionDef name:try_add_pt2_compile arg:event_name arguments arg arg If Call Return return:no Assign Call Call"
64 },
65 {
66 "library": "authlib",
67 "name": "create_authorization_url",
68 "source_code": "def create_authorization_url(self, redirect_uri=None, **kwargs):\n if not self.authorize_url:\n raise RuntimeError('Missing \"authorize_url\" value')\n if self.authorize_params:\n kwargs.update(self.authorize_params)\n with self._get_oauth_client() as client:\n client.redirect_uri = redirect_uri\n params = self.request_token_params or {}\n request_token = client.fetch_request_token(self.request_token_url, **params)\n log.debug(f'Fetch request token: {request_token!r}')\n url = client.create_authorization_url(self.authorize_url, **kwargs)\n state = request_token['oauth_token']\n return {'url': url, 'request_token': request_token, 'state': state}",
69 "docstring": "Generate the authorization url and state for HTTP redirect. :param redirect_uri: Callback or redirect URI for authorization. :param kwargs: Extra parameters to include. :return: dict",
70 "type": "method",
71 "file_path": "authlib\\authlib\\integrations\\base_client\\sync_app.py",
72 "ast_data": "FunctionDef name:create_authorization_url arg:self arg:redirect_uri arguments arg arg arg If Raise Call If Call With Call Assign Assign BoolOp Assign Call Call Assign Call Assign Return return:yes"
73 },
74 {
75 "library": "matplotlib",
76 "name": "set_offset",
77 "source_code": "def set_offset(self, xy):\n self._offset = xy\n self.offset_transform.clear()\n self.offset_transform.translate(xy[0], xy[1])\n self.stale = True",
78 "docstring": "Set the offset of the container. Parameters ---------- xy : (float, float) The (x, y) coordinates of the offset in display units.",
79 "type": "method",
80 "file_path": "matplotlib\\lib\\matplotlib\\offsetbox.py",
81 "ast_data": "FunctionDef name:set_offset arg:self arg:xy arguments arg arg Assign Call Call Assign"
82 },
83 {
84 "library": "sphinx",
85 "name": "HighlightLanguageTransform",
86 "source_code": "class HighlightLanguageTransform(SphinxTransform):\n default_priority = 400\n\n def apply(self, **kwargs: Any) -> None:\n visitor = HighlightLanguageVisitor(self.document, self.config.highlight_language)\n self.document.walkabout(visitor)\n for node in list(self.document.findall(addnodes.highlightlang)):\n node.parent.remove(node)",
87 "docstring": "Apply highlight_language to all literal_block nodes. This refers both :confval: setting and :rst:dir: directive. After processing, this transform removes `` node from doctree.",
88 "type": "class",
89 "file_path": "sphinx\\sphinx\\transforms\\post_transforms\\code.py",
90 "ast_data": "ClassDef name:HighlightLanguageTransform Assign FunctionDef name:apply arg:self arguments arg arg Assign Call Call For Call Call Call"
91 },
92 {
93 "library": "pytorch",
94 "name": "write_main",
95 "source_code": "def write_main(self, install_root, oss, symbol_name):\n with open(os.path.join(install_root, 'main.c'), 'w') as outfp:\n outfp.write(MAIN_INCLUDES)\n for m in self.frozen_modules:\n outfp.write(f'extern unsigned char {m.c_name}[];\\n')\n outfp.write(MAIN_PREFIX_TEMPLATE.format(symbol_name))\n for m in self.frozen_modules:\n outfp.write(f'\\t{{\"{m.module_name}\", {m.c_name}, {m.size}}},\\n')\n outfp.write(MAIN_SUFFIX)\n if oss:\n outfp.write(FAKE_PREFIX)\n outfp.write(MAIN_SUFFIX)",
96 "docstring": "Write the file containing a table enumerating all the frozen modules.",
97 "type": "method",
98 "file_path": "pytorch\\torch\\utils\\_freeze.py",
99 "ast_data": "FunctionDef name:write_main arg:self arg:install_root arg:oss arg:symbol_name arguments arg arg arg arg With Call Call Call For Call Call Call For Call Call If Call Call"
100 },
101 {
102 "library": "pandas",
103 "name": "getitem_block_columns",
104 "source_code": "@final\ndef getitem_block_columns(self, slicer: slice, new_mgr_locs: BlockPlacement, ref_inplace_op: bool=False) -> Self:\n new_values = self._slice(slicer)\n refs = self.refs if not ref_inplace_op or self.refs.has_reference() else None\n return type(self)(new_values, new_mgr_locs, self.ndim, refs=refs)",
105 "docstring": "Perform __getitem__-like, return result as block. Only supports slices that preserve dimensionality.",
106 "type": "method",
107 "file_path": "pandas\\pandas\\core\\internals\\blocks.py",
108 "ast_data": "FunctionDef name:getitem_block_columns arg:self arg:slicer arg:new_mgr_locs arg:ref_inplace_op arguments arg arg arg arg Assign Call Assign BoolOp Call Return return:yes Call Call"
109 },
110 {
111 "library": "tensorflow",
112 "name": "get_rel_timestamps",
113 "source_code": "def get_rel_timestamps(self, node_name, output_slot, debug_op, device_name=None):\n device_name = self._infer_device_name(device_name, node_name)\n watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op)\n if watch_key not in self._watch_key_to_datum[device_name]:\n raise WatchKeyDoesNotExistInDebugDumpDirError('Watch key \"%s\" does not exist in the debug dump' % watch_key)\n return self._watch_key_to_rel_time[device_name][watch_key]",
114 "docstring": "Get the relative timestamp from for a debug-dumped tensor. Relative timestamp means (absolute timestamp - ), where is the absolute timestamp of the first dumped tensor in the dump root. The tensor may be dumped multiple times in the dump root directory, so a list of relative timestamps () is returned. Args: node_name: () name of the node that the tensor is produced by. output_slot: () output slot index of tensor. debug_op: () name of the debug op. device_name: () name of the device. If there is only one device or if the specified debug_watch_key exists on only one device, this argument is optional. Returns: ( of ) list of relative timestamps. Raises: WatchKeyDoesNotExistInDebugDumpDirError: If the tensor watch key does not exist in the debug dump data.",
115 "type": "method",
116 "file_path": "tensorflow\\tensorflow\\python\\debug\\lib\\debug_data.py",
117 "ast_data": "FunctionDef name:get_rel_timestamps arg:self arg:node_name arg:output_slot arg:debug_op arg:device_name arguments arg arg arg arg arg Assign Call Assign Call If Compare Raise Call Return return:yes"
118 },
119 {
120 "library": "django",
121 "name": "check_rel_lookup_compatibility",
122 "source_code": "def check_rel_lookup_compatibility(model, target_opts, field):\n\n def check(opts):\n return model._meta.concrete_model == opts.concrete_model or opts.concrete_model in model._meta.all_parents or model in opts.all_parents\n return check(target_opts) or (getattr(field, 'primary_key', False) and check(field.model._meta))",
123 "docstring": "Check that self.model is compatible with target_opts. Compatibility is OK if: 1) model and opts match (where proxy inheritance is removed) 2) model is parent of opts' model or the other way around",
124 "type": "function",
125 "file_path": "django\\django\\db\\models\\query_utils.py",
126 "ast_data": "FunctionDef name:check_rel_lookup_compatibility arg:model arg:target_opts arg:field arguments arg arg arg FunctionDef name:check arg:opts arguments arg Return return:yes BoolOp Compare Compare Compare Return return:yes BoolOp Call BoolOp Call Call"
127 },
128 {
129 "library": "scikit-learn",
130 "name": "_get_ordered_idx",
131 "source_code": "def _get_ordered_idx(self, mask_missing_values):\n frac_of_missing_values = mask_missing_values.mean(axis=0)\n if self.skip_complete:\n missing_values_idx = np.flatnonzero(frac_of_missing_values)\n else:\n missing_values_idx = np.arange(np.shape(frac_of_missing_values)[0])\n if self.imputation_order == 'roman':\n ordered_idx = missing_values_idx\n elif self.imputation_order == 'arabic':\n ordered_idx = missing_values_idx[::-1]\n elif self.imputation_order == 'ascending':\n n = len(frac_of_missing_values) - len(missing_values_idx)\n ordered_idx = np.argsort(frac_of_missing_values, kind='mergesort')[n:]\n elif self.imputation_order == 'descending':\n n = len(frac_of_missing_values) - len(missing_values_idx)\n ordered_idx = np.argsort(frac_of_missing_values, kind='mergesort')[n:][::-1]\n elif self.imputation_order == 'random':\n ordered_idx = missing_values_idx\n self.random_state_.shuffle(ordered_idx)\n return ordered_idx",
132 "docstring": "Decide in what order we will update the features. As a homage to the MICE R package, we will have 4 main options of how to order the updates, and use a random order if anything else is specified. Also, this function skips features which have no missing values. Parameters ---------- mask_missing_values : array-like, shape (n_samples, n_features) Input data's missing indicator matrix, where is the number of samples and is the number of features. Returns ------- ordered_idx : ndarray, shape (n_features,) The order in which to impute the features.",
133 "type": "method",
134 "file_path": "scikit-learn\\sklearn\\impute\\_iterative.py",
135 "ast_data": "FunctionDef name:_get_ordered_idx arg:self arg:mask_missing_values arguments arg arg Assign Call If Assign Call Assign Call Call If Compare Assign If Compare Assign If Compare Assign Call Call Assign Call If Compare Assign Call Call Assign Call If Compare Assign Call Return return:yes"
136 },
137 {
138 "library": "tensorflow",
139 "name": "op_is_inside_loop",
140 "source_code": "def op_is_inside_loop(self, op):\n assert isinstance(op, ops.Operation)\n return op._id in self._pfor_op_ids",
141 "docstring": "True if op was created inside the pfor loop body.",
142 "type": "method",
143 "file_path": "tensorflow\\tensorflow\\python\\ops\\parallel_for\\pfor.py",
144 "ast_data": "FunctionDef name:op_is_inside_loop arg:self arg:op arguments arg arg Call Return return:yes Compare"
145 },
146 {
147 "library": "tensorflow",
148 "name": "to_code",
149 "source_code": "@tf_export('autograph.to_code', v1=[])\ndef to_code(entity, recursive=True, experimental_optional_features=None):\n source = tf_inspect.getsource(to_graph(entity, recursive=recursive, experimental_optional_features=experimental_optional_features))\n return textwrap.dedent(source)",
150 "docstring": "Returns the source code generated by AutoGraph, as a string. Example usage: >>> def f(x): ... if x >> tf.autograph.to_code(f) \"...def tf__f(x):...\" Also see: . Note: If a function has been decorated with , pass its underlying Python function, rather than the callable that Nonetf.autograph.experimental.Feature` value. Returns: The converted code as string.",
151 "type": "function",
152 "file_path": "tensorflow\\tensorflow\\python\\autograph\\impl\\api.py",
153 "ast_data": "FunctionDef name:to_code arg:entity arg:recursive arg:experimental_optional_features arguments arg arg arg Assign Call Call Return return:yes Call Call"
154 },
155 {
156 "library": "scipy",
157 "name": "aslinearoperator",
158 "source_code": "def aslinearoperator(A):\n if isinstance(A, LinearOperator):\n return A\n elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):\n if A.ndim > 2:\n raise ValueError('array must have ndim <= 2')\n A = np.atleast_2d(np.asarray(A))\n return MatrixLinearOperator(A)\n elif issparse(A) or is_pydata_spmatrix(A):\n return MatrixLinearOperator(A)\n elif hasattr(A, 'shape') and hasattr(A, 'matvec'):\n rmatvec = None\n rmatmat = None\n dtype = None\n if hasattr(A, 'rmatvec'):\n rmatvec = A.rmatvec\n if hasattr(A, 'rmatmat'):\n rmatmat = A.rmatmat\n if hasattr(A, 'dtype'):\n dtype = A.dtype\n return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec, rmatmat=rmatmat, dtype=dtype)\n else:\n raise TypeError('type not understood')",
159 "docstring": "Return A as a LinearOperator. 'A' may be any of the following types: - ndarray - matrix - sparse array (e.g. csr_array, lil_array, etc.) - LinearOperator - An object with .shape and .matvec attributes See the LinearOperator documentation for additional information. Notes ----- If 'A' has no .dtype attribute, the data type is determined by calling :func: - set the .dtype attribute to prevent this call upon the linear operator creation. Examples -------- >>> import numpy as np >>> from scipy.sparse.linalg import aslinearoperator >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32) >>> aslinearoperator(M)",
160 "type": "function",
161 "file_path": "scipy\\scipy\\sparse\\linalg\\_interface.py",
162 "ast_data": "FunctionDef name:aslinearoperator arg:A arguments arg If Call Return return:yes If BoolOp Call Call If Compare Raise Call Assign Call Call Return return:yes Call If BoolOp Call Call Return return:yes Call If BoolOp Call Call Assign Assign Assign If Call Assign If Call Assign If Call Assign Return return:yes Call Raise Call"
163 },
164 {
165 "library": "pytorch",
166 "name": "_fx_collection_equivalence_fn",
167 "source_code": "def _fx_collection_equivalence_fn(spec1_type: Optional[type], spec1_context: pytree.Context, spec2_type: Optional[type], spec2_context: pytree.Context) -> bool:\n if spec1_type is None or spec2_type is None:\n return spec1_type is spec2_type and spec1_context == spec2_context\n if issubclass(spec1_type, (dict, immutable_dict)) and issubclass(spec2_type, (dict, immutable_dict)):\n return spec1_context == spec2_context\n if issubclass(spec1_type, (list, immutable_list)) and issubclass(spec2_type, (list, immutable_list)):\n return spec1_context == spec2_context\n return spec1_type is spec2_type and spec1_context == spec2_context",
168 "docstring": "Treat containers and their immutable variants as the same type. Otherwise compare as normal.",
169 "type": "function",
170 "file_path": "pytorch\\torch\\export\\exported_program.py",
171 "ast_data": "FunctionDef name:_fx_collection_equivalence_fn arg:spec1_type arg:spec1_context arg:spec2_type arg:spec2_context arguments arg arg arg arg If BoolOp Compare Compare Return return:yes BoolOp Compare Compare If BoolOp Call Call Return return:yes Compare If BoolOp Call Call Return return:yes Compare Return return:yes BoolOp Compare Compare"
172 },
173 {
174 "library": "tensorflow",
175 "name": "creator_with_resource_vars",
176 "source_code": "def creator_with_resource_vars(next_creator, **kwargs):\n if ops.inside_function():\n if_graph_building = 'graph_building'\n else:\n if_graph_building = 'not_graph_building'\n with monitoring.MonitoredTimer(distributed_variable_creation_time_counter.get_cell(strategy.__class__.__name__, if_graph_building)):\n _require_strategy_scope_extended(self)\n kwargs['use_resource'] = True\n kwargs['distribute_strategy'] = strategy\n if isinstance(kwargs['initial_value'], trackable.CheckpointInitialValue):\n checkpoint_restore_uid = kwargs['initial_value'].checkpoint_position.restore_uid\n kwargs['initial_value'] = kwargs['initial_value'].wrapped_value\n elif isinstance(kwargs['initial_value'], trackable.CheckpointInitialValueCallable):\n checkpoint_restore_uid = kwargs['initial_value'].checkpoint_position.restore_uid\n elif isinstance(kwargs['initial_value'], functools.partial) and isinstance(kwargs['initial_value'].func, trackable.CheckpointInitialValueCallable):\n checkpoint_restore_uid = kwargs['initial_value'].func.checkpoint_position.restore_uid\n else:\n checkpoint_restore_uid = None\n created = self._create_variable(next_creator, **kwargs)\n if checkpoint_restore_uid is not None:\n created._maybe_initialize_trackable()\n created._update_uid = checkpoint_restore_uid\n return created",
177 "docstring": "Variable creator to use in .",
178 "type": "method",
179 "file_path": "tensorflow\\tensorflow\\python\\distribute\\distribute_lib.py",
180 "ast_data": "FunctionDef name:creator_with_resource_vars arg:next_creator arguments arg arg If Call Assign Assign With Call Call Call Assign Assign If Call Assign Assign If Call Assign If BoolOp Call Call Assign Assign Assign Call If Compare Call Assign Return return:yes"
181 },
182 {
183 "library": "tensorflow",
184 "name": "__call__",
185 "source_code": "def __call__(self, y_true, y_pred, sample_weight=None):\n graph_ctx = tf_utils.graph_context_for_symbolic_tensors(y_true, y_pred, sample_weight)\n with backend.name_scope(self._name_scope), graph_ctx:\n if context.executing_eagerly():\n call_fn = self.call\n else:\n call_fn = autograph.tf_convert(self.call, ag_ctx.control_status_ctx())\n losses = call_fn(y_true, y_pred)\n return losses_utils.compute_weighted_loss(losses, sample_weight, reduction=self._get_reduction())",
186 "docstring": "Invokes the instance. Args: y_true: Ground truth values. shape = , except sparse loss functions such as sparse categorical crossentropy where shape = y_pred: The predicted values. shape = sample_weight: Optional acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If is a tensor of size , then the total loss for each sample of the batch is rescaled by the corresponding element in the vector. If the shape of is (or can be broadcasted to this shape), then each loss element of is scaled by the corresponding value of . (Note on: all loss functions reduce by 1 dimension, usually axis=-1.) Returns: Weighted loss float . If is , this has shape ; otherwise, it is scalar. (Note because all loss functions reduce by 1 dimension, usually axis=-1.) Raises: ValueError: If the shape of is invalid.",
187 "type": "method",
188 "file_path": "tensorflow\\tensorflow\\python\\keras\\losses.py",
189 "ast_data": "FunctionDef name:__call__ arg:self arg:y_true arg:y_pred arg:sample_weight arguments arg arg arg arg Assign Call With Call If Call Assign Assign Call Call Assign Call Return return:yes Call Call"
190 },
191 {
192 "library": "scipy",
193 "name": "entropy",
194 "source_code": "def entropy(self, n, p):\n n, p, npcond = self._process_parameters(n, p)\n x = np.r_[1:np.max(n) + 1]\n term1 = n * np.sum(entr(p), axis=-1)\n term1 -= gammaln(n + 1)\n n = n[..., np.newaxis]\n new_axes_needed = max(p.ndim, n.ndim) - x.ndim + 1\n x.shape += (1,) * new_axes_needed\n term2 = np.sum(binom.pmf(x, n, p) * gammaln(x + 1), axis=(-1, -1 - new_axes_needed))\n return self._checkresult(term1 + term2, npcond, np.nan)",
195 "docstring": "Compute the entropy of the multinomial distribution. The entropy is computed using this expression: .. math:: f(x) = - \\log n! - n\\sum_{i=1}^k p_i \\log p_i + \\sum_{i=1}^k \\sum_{x=0}^n \\binom n x p_i^x(1-p_i)^{n-x} \\log x! Parameters ---------- %(_doc_default_callparams)s Returns ------- h : scalar Entropy of the Multinomial distribution Notes ----- %(_doc_callparams_note)s",
196 "type": "method",
197 "file_path": "scipy\\scipy\\stats\\_multivariate.py",
198 "ast_data": "FunctionDef name:entropy arg:self arg:n arg:p arguments arg arg arg Assign Call Assign Call Assign Call Call Call Assign Assign Call Assign Call Call Call Return return:yes Call"
199 },
200 {
201 "library": "kornia",
202 "name": "adjoint",
203 "source_code": "def adjoint(self) -> Tensor:\n batch_size = len(self.z) if len(self.z.shape) > 0 else None\n return self.identity(batch_size, self.z.device, self.z.real.dtype).matrix()",
204 "docstring": "Return the adjoint matrix of shape :math:. Example: >>> s = So2.identity() >>> s.adjoint() tensor([[1., -0.], [0., 1.]], grad_fn=)",
205 "type": "method",
206 "file_path": "kornia\\kornia\\geometry\\liegroup\\so2.py",
207 "ast_data": "FunctionDef name:adjoint arg:self arguments arg Assign Compare Call Call Return return:yes Call Call"
208 },
209 {
210 "library": "pytorch",
211 "name": "lazy_deprecated_import",
212 "source_code": "def lazy_deprecated_import(all: list[str], old_module: str, new_module: str) -> Callable:\n warning_message = _MESSAGE_TEMPLATE.format(old_location=old_module, new_location=new_module)\n\n def getattr_dunder(name: str) -> None:\n if name in all:\n warnings.warn(warning_message, RuntimeWarning)\n package = importlib.import_module(new_module)\n return getattr(package, name)\n raise AttributeError(f'Module {new_module!r} has no attribute {name!r}.')\n return getattr_dunder",
213 "docstring": "Import utility to lazily import deprecated packages / modules / functional. The old_module and new_module are also used in the deprecation warning defined by the . Args: all: The list of the functions that are imported. Generally, the module's __all__ list of the module. old_module: Old module location new_module: New module location / Migrated location Returns: Callable to assign to the Usage: # In the from torch.nn.utils._deprecation_utils import lazy_deprecated_import _MIGRATED_TO = \"torch.ao.nn.quantized.functional\" __getattr__ = lazy_deprecated_import( all=__all__, old_module=__name__, new_module=_MIGRATED_TO)",
214 "type": "function",
215 "file_path": "pytorch\\torch\\nn\\utils\\_deprecation_utils.py",
216 "ast_data": "FunctionDef name:lazy_deprecated_import arg:all arg:old_module arg:new_module arguments arg arg arg Assign Call FunctionDef name:getattr_dunder arg:name arguments arg If Compare Call Assign Call Return return:yes Call Raise Call Return return:yes"
217 },
218 {
219 "library": "tensorflow",
220 "name": "variable_capturing_scope",
221 "source_code": "def variable_capturing_scope(next_creator, **kwds):\n enable_variable_lifting = kwds.get('experimental_enable_variable_lifting')\n if enable_variable_lifting is None:\n enable_variable_lifting = True\n if not enable_variable_lifting:\n return next_creator(**kwds)\n v = UnliftedInitializerVariable(add_initializers_to=add_initializers_to, **kwds)\n created_variables.append(weakref.ref(v))\n return v",
222 "docstring": "Creates UnliftedInitializerVariables and saves references to them.",
223 "type": "method",
224 "file_path": "tensorflow\\tensorflow\\python\\eager\\polymorphic_function\\polymorphic_function.py",
225 "ast_data": "FunctionDef name:variable_capturing_scope arg:next_creator arguments arg arg Assign Call If Compare Assign If Return return:yes Call Assign Call Call Call Return return:yes"
226 },
227 {
228 "library": "tensorflow",
229 "name": "_init_from_metadata",
230 "source_code": "@classmethod\ndef _init_from_metadata(cls, metadata):\n revived_obj = cls(name=metadata['name'])\n with utils.no_automatic_dependency_tracking_scope(revived_obj):\n revived_obj._expects_training_arg = metadata['expects_training_arg']\n config = metadata.get('config')\n if generic_utils.validate_config(config):\n revived_obj._config = config\n if metadata.get('activity_regularizer') is not None:\n revived_obj.activity_regularizer = regularizers.deserialize(metadata['activity_regularizer'])\n return (revived_obj, _revive_setter)",
231 "docstring": "Create revived network from metadata stored in the SavedModel proto.",
232 "type": "method",
233 "file_path": "tensorflow\\tensorflow\\python\\keras\\saving\\saved_model\\load.py",
234 "ast_data": "FunctionDef name:_init_from_metadata arg:cls arg:metadata arguments arg arg Assign Call With Call Assign Assign Call If Call Assign If Compare Call Assign Call Return return:yes"
235 },
236 {
237 "library": "kornia",
238 "name": "cross_product_matrix",
239 "source_code": "def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:\n if not x.shape[-1] == 3:\n raise AssertionError(x.shape)\n x0 = x[..., 0]\n x1 = x[..., 1]\n x2 = x[..., 2]\n zeros = zeros_like(x0)\n cross_product_matrix_flat = stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)\n shape_ = x.shape[:-1] + (3, 3)\n return cross_product_matrix_flat.view(*shape_)",
240 "docstring": "Return the cross_product_matrix symmetric matrix of a vector. Args: x: The input vector to construct the matrix in the shape :math:. Returns: The constructed cross_product_matrix symmetric matrix with shape :math:.",
241 "type": "function",
242 "file_path": "kornia\\kornia\\geometry\\epipolar\\numeric.py",
243 "ast_data": "FunctionDef name:cross_product_matrix arg:x arguments arg If Compare Raise Call Assign Assign Assign Assign Call Assign Call Assign Return return:yes Call"
244 },
245 {
246 "library": "django",
247 "name": "get_urls",
248 "source_code": "def get_urls(self, page=1, site=None, protocol=None):\n urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)\n for url in urls:\n url['geo_format'] = self.geo_format\n return urls",
249 "docstring": "This method is overridden so the appropriate attribute is placed on each URL element.",
250 "type": "method",
251 "file_path": "django\\django\\contrib\\gis\\sitemaps\\kml.py",
252 "ast_data": "FunctionDef name:get_urls arg:self arg:page arg:site arg:protocol arguments arg arg arg arg Assign Call For Assign Return return:yes"
253 },
254 {
255 "library": "django",
256 "name": "_simple_domain_name_validator",
257 "source_code": "def _simple_domain_name_validator(value):\n checks = (s in value for s in string.whitespace)\n if any(checks):\n raise ValidationError(_('The domain name cannot contain any spaces or tabs.'), code='invalid')",
258 "docstring": "Validate that the given value contains no whitespaces to prevent common typos.",
259 "type": "function",
260 "file_path": "django\\django\\contrib\\sites\\models.py",
261 "ast_data": "FunctionDef name:_simple_domain_name_validator arg:value arguments arg Assign Compare If Call Raise Call Call"
262 },
263 {
264 "library": "matplotlib",
265 "name": "post_gist",
266 "source_code": "def post_gist(content, description='', filename='file', auth=False):\n post_data = json.dumps({'description': description, 'public': True, 'files': {filename: {'content': content}}}).encode('utf-8')\n headers = make_auth_header() if auth else {}\n response = requests.post('https://api.github.com/gists', data=post_data, headers=headers)\n response.raise_for_status()\n response_data = json.loads(response.text)\n return response_data['html_url']",
267 "docstring": "Post some text to a Gist, and return the URL.",
268 "type": "function",
269 "file_path": "matplotlib\\tools\\gh_api.py",
270 "ast_data": "FunctionDef name:post_gist arg:content arg:description arg:filename arg:auth arguments arg arg arg arg Assign Call Call Assign Call Assign Call Call Assign Call Return return:yes"
271 },
272 {
273 "library": "pytorch",
274 "name": "unnecessary_dtype_convert",
275 "source_code": "@register_graph_pattern(CallFunction(torch.ops.prims.convert_element_type.default, Ignored(), KeywordArg('dtype')), pass_dict=pass_patterns[0], extra_check=same_dtype)\ndef unnecessary_dtype_convert(match: Match, **kwargs):\n graph = match.graph\n node = match.output_node()\n node.replace_all_uses_with(node.args[0])\n graph.erase_node(node)",
276 "docstring": "Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding",
277 "type": "function",
278 "file_path": "pytorch\\torch\\_inductor\\fx_passes\\freezing_patterns.py",
279 "ast_data": "FunctionDef name:unnecessary_dtype_convert arg:match arguments arg arg Assign Assign Call Call Call Call Call Call Call"
280 },
281 {
282 "library": "numpy",
283 "name": "__getstate__",
284 "source_code": "def __getstate__(self):\n state = (1, self.shape, self.dtype, self.flags.fnc, self._data.tobytes(), self._mask.tobytes(), self._fill_value)\n return state",
285 "docstring": "Return the internal state of the masked array. This is for pickling.",
286 "type": "method",
287 "file_path": "numpy\\numpy\\ma\\mrecords.py",
288 "ast_data": "FunctionDef name:__getstate__ arg:self arguments arg Assign Call Call Return return:yes"
289 },
290 {
291 "library": "pandas",
292 "name": "_should_fallback_to_positional",
293 "source_code": "@cache_readonly\ndef _should_fallback_to_positional(self) -> bool:\n return self.inferred_type not in {'integer', 'mixed-integer', 'floating', 'complex'}",
294 "docstring": "Should an integer key be treated as positional?",
295 "type": "method",
296 "file_path": "pandas\\pandas\\core\\indexes\\base.py",
297 "ast_data": "FunctionDef name:_should_fallback_to_positional arg:self arguments arg Return return:yes Compare"
298 },
299 {
300 "library": "django",
301 "name": "dims",
302 "source_code": "@property\ndef dims(self):\n return capi.get_dims(self.ptr)",
303 "docstring": "Return the dimension of this Geometry (0=point, 1=line, 2=surface).",
304 "type": "method",
305 "file_path": "django\\django\\contrib\\gis\\geos\\geometry.py",
306 "ast_data": "FunctionDef name:dims arg:self arguments arg Return return:yes Call"
307 },
308 {
309 "library": "matplotlib",
310 "name": "get_yaxis_text1_transform",
311 "source_code": "def get_yaxis_text1_transform(self, pad_points):\n labels_align = mpl.rcParams['ytick.alignment']\n return (self.get_yaxis_transform(which='tick1') + mtransforms.ScaledTranslation(-1 * pad_points / 72, 0, self.get_figure(root=False).dpi_scale_trans), labels_align, 'right')",
312 "docstring": "Returns ------- transform : Transform The transform used for drawing y-axis labels, which will add *pad_points* of padding (in points) between the axis and the label. The x-direction is in axis coordinates and the y-direction is in data coordinates valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'} The text vertical alignment. halign : {'center', 'left', 'right'} The text horizontal alignment. Notes ----- This transformation is primarily used by the class, and is meant to be overridden by new kinds of projections that may need to place axis elements in different locations.",
313 "type": "method",
314 "file_path": "matplotlib\\lib\\matplotlib\\axes\\_base.py",
315 "ast_data": "FunctionDef name:get_yaxis_text1_transform arg:self arg:pad_points arguments arg arg Assign Return return:yes Call Call Call"
316 },
317 {
318 "library": "matplotlib",
319 "name": "pts_to_prestep",
320 "source_code": "def pts_to_prestep(x, *args):\n steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))\n steps[0, 0::2] = x\n steps[0, 1::2] = steps[0, 0:-2:2]\n steps[1:, 0::2] = args\n steps[1:, 1::2] = steps[1:, 2::2]\n return steps",
321 "docstring": "Convert continuous line to pre-steps. Given a set of ``, the length will be 0. Examples -------- >>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)",
322 "type": "function",
323 "file_path": "matplotlib\\lib\\matplotlib\\cbook.py",
324 "ast_data": "FunctionDef name:pts_to_prestep arg:x arguments arg arg Assign Call Call Call Call Assign Assign Assign Assign Return return:yes"
325 },
326 {
327 "library": "scipy",
328 "name": "asterisk_repl",
329 "source_code": "def asterisk_repl(matchobj):\n code = matchobj.group(1).replace('\\\\*', '*')\n return '``' + code + '``'",
330 "docstring": "repl to un-escape asterisks in code blocks",
331 "type": "function",
332 "file_path": "scipy\\tools\\gh_lists.py",
333 "ast_data": "FunctionDef name:asterisk_repl arg:matchobj arguments arg Assign Call Call Return return:yes"
334 },
335 {
336 "library": "django",
337 "name": "num_coords",
338 "source_code": "@property\ndef num_coords(self):\n return capi.get_num_coords(self.ptr)",
339 "docstring": "Return the number of coordinates in the Geometry.",
340 "type": "method",
341 "file_path": "django\\django\\contrib\\gis\\geos\\geometry.py",
342 "ast_data": "FunctionDef name:num_coords arg:self arguments arg Return return:yes Call"
343 },
344 {
345 "library": "pandas",
346 "name": "truncate",
347 "source_code": "def truncate(self, before=None, after=None) -> MultiIndex:\n if after and before and (after < before):\n raise ValueError('after < before')\n i, j = self.levels[0].slice_locs(before, after)\n left, right = self.slice_locs(before, after)\n new_levels = list(self.levels)\n new_levels[0] = new_levels[0][i:j]\n new_codes = [level_codes[left:right] for level_codes in self.codes]\n new_codes[0] = new_codes[0] - i\n return MultiIndex(levels=new_levels, codes=new_codes, names=self._names, verify_integrity=False)",
348 "docstring": "Slice index between two labels / tuples, return new MultiIndex. Parameters ---------- before : label or tuple, can be partial. Default None None defaults to start. after : label or tuple, can be partial. Default None None defaults to end. Returns ------- MultiIndex The truncated MultiIndex. See Also -------- DataFrame.truncate : Truncate a DataFrame before and after some index values. Series.truncate : Truncate a Series before and after some index values. Examples -------- >>> mi = pd.MultiIndex.from_arrays([[\"a\", \"b\", \"c\"], [\"x\", \"y\", \"z\"]]) >>> mi MultiIndex([('a', 'x'), ('b', 'y'), ('c', 'z')], ) >>> mi.truncate(before=\"a\", after=\"b\") MultiIndex([('a', 'x'), ('b', 'y')], )",
349 "type": "method",
350 "file_path": "pandas\\pandas\\core\\indexes\\multi.py",
351 "ast_data": "FunctionDef name:truncate arg:self arg:before arg:after arguments arg arg arg If BoolOp Compare Raise Call Assign Call Assign Call Assign Call Assign Assign Assign Return return:yes Call"
352 },
353 {
354 "library": "django",
355 "name": "get_changelist",
356 "source_code": "def get_changelist(self, request, **kwargs):\n from django.contrib.admin.views.main import ChangeList\n return ChangeList",
357 "docstring": "Return the ChangeList class for use on the changelist page.",
358 "type": "method",
359 "file_path": "django\\django\\contrib\\admin\\options.py",
360 "ast_data": "FunctionDef name:get_changelist arg:self arg:request arguments arg arg arg Return return:yes"
361 },
362 {
363 "library": "tensorflow",
364 "name": "_size",
365 "source_code": "def _size(t, dtype=None):\n size = t.get_shape().num_elements() if isinstance(t, tensor_lib.Tensor) else None\n return array_ops.size(t, out_type=dtype) if size is None else size",
366 "docstring": "Returns size as an integer (when statically known) or as a tensor.",
367 "type": "function",
368 "file_path": "tensorflow\\tensorflow\\python\\ops\\parallel_for\\pfor.py",
369 "ast_data": "FunctionDef name:_size arg:t arg:dtype arguments arg arg Assign Call Call Call Return return:yes Compare Call"
370 },
371 {
372 "library": "tensorflow",
373 "name": "_validate_signature_def_map",
374 "source_code": "def _validate_signature_def_map(self, signature_def_map):\n for signature_def_key in signature_def_map:\n signature_def = signature_def_map[signature_def_key]\n inputs = signature_def.inputs\n outputs = signature_def.outputs\n for inputs_key in inputs:\n self._validate_tensor_info(inputs[inputs_key])\n for outputs_key in outputs:\n self._validate_tensor_info(outputs[outputs_key])\n if constants.INIT_OP_SIGNATURE_KEY in signature_def_map:\n raise KeyError(f'SignatureDef map key \"{constants.INIT_OP_SIGNATURE_KEY}\" is reserved for initialization. Please use a different key.')\n if constants.TRAIN_OP_SIGNATURE_KEY in signature_def_map:\n raise KeyError(f'SignatureDef map key \"{constants.TRAIN_OP_SIGNATURE_KEY}\" is reserved for the train op. Please use a different key.')",
375 "docstring": "Validates the entries in the signature def map. Validation of entries in the signature def map includes ensuring that the and fields of the TensorInfo protos of the and of each are populated. Also ensures that reserved SignatureDef keys for the initialization and train ops are not used. Args: signature_def_map: The map of signature defs to be validated. Raises: AssertionError: If a TensorInfo is not valid. KeyError: If a reserved signature key is used in the map.",
376 "type": "method",
377 "file_path": "tensorflow\\tensorflow\\python\\saved_model\\builder_impl.py",
378 "ast_data": "FunctionDef name:_validate_signature_def_map arg:self arg:signature_def_map arguments arg arg For Assign Assign Assign For Call For Call If Compare Raise Call If Compare Raise Call"
379 },
380 {
381 "library": "pandas",
382 "name": "_from_factorized",
383 "source_code": "@classmethod\ndef _from_factorized(cls, values, original):\n raise AbstractMethodError(cls)",
384 "docstring": "Reconstruct an ExtensionArray after factorization. Parameters ---------- values : ndarray An integer ndarray with the factorized values. original : ExtensionArray The original ExtensionArray that factorize was called on. See Also -------- factorize : Top-level factorize method that dispatches here. ExtensionArray.factorize : Encode the extension array as an enumerated type. Examples -------- >>> interv_arr = pd.arrays.IntervalArray( ... [pd.Interval(0, 1), pd.Interval(1, 5), pd.Interval(1, 5)] ... ) >>> codes, uniques = pd.factorize(interv_arr) >>> pd.arrays.IntervalArray._from_factorized(uniques, interv_arr) [(0, 1], (1, 5]] Length: 2, dtype: interval[int64, right]",
385 "type": "method",
386 "file_path": "pandas\\pandas\\core\\arrays\\base.py",
387 "ast_data": "FunctionDef name:_from_factorized arg:cls arg:values arg:original arguments arg arg arg Raise Call"
388 },
389 {
390 "library": "pandas",
391 "name": "select",
392 "source_code": "def select(self):\n if self.condition is not None:\n return self.table.table.read_where(self.condition.format(), start=self.start, stop=self.stop)\n elif self.coordinates is not None:\n return self.table.table.read_coordinates(self.coordinates)\n return self.table.table.read(start=self.start, stop=self.stop)",
393 "docstring": "generate the selection",
394 "type": "method",
395 "file_path": "pandas\\pandas\\io\\pytables.py",
396 "ast_data": "FunctionDef name:select arg:self arguments arg If Compare Return return:yes Call Call If Compare Return return:yes Call Return return:yes Call"
397 },
398 {
399 "library": "authlib",
400 "name": "add_to_body",
401 "source_code": "def add_to_body(token, body=None):\n if body is None:\n body = ''\n return add_params_to_qs(body, [('access_token', token)])",
402 "docstring": "Add a Bearer Token to the request body. access_token=h480djs93hd8",
403 "type": "function",
404 "file_path": "authlib\\authlib\\oauth2\\rfc6750\\parameters.py",
405 "ast_data": "FunctionDef name:add_to_body arg:token arg:body arguments arg arg If Compare Assign Return return:yes Call"
406 },
407 {
408 "library": "scipy",
409 "name": "_getcol",
410 "source_code": "def _getcol(self, i):\n M, N = self.shape\n i = int(i)\n if i < 0:\n i += N\n if i < 0 or i >= N:\n raise IndexError(f'index ({i}) out of range')\n return self._get_submatrix(major=i, copy=True)",
411 "docstring": "Returns a copy of column i of the matrix, as a (m x 1) CSC matrix (column vector).",
412 "type": "method",
413 "file_path": "scipy\\scipy\\sparse\\_csc.py",
414 "ast_data": "FunctionDef name:_getcol arg:self arg:i arguments arg arg Assign Assign Call If Compare If BoolOp Compare Compare Raise Call Return return:yes Call"
415 },
416 {
417 "library": "tensorflow",
418 "name": "reduce_weighted_loss",
419 "source_code": "def reduce_weighted_loss(weighted_losses, reduction=ReductionV2.SUM_OVER_BATCH_SIZE):\n if reduction == ReductionV2.NONE:\n loss = weighted_losses\n else:\n loss = math_ops.reduce_sum(weighted_losses)\n if reduction == ReductionV2.SUM_OVER_BATCH_SIZE:\n loss = _safe_mean(loss, _num_elements(weighted_losses))\n return loss",
420 "docstring": "Reduces the individual weighted loss measurements.",
421 "type": "function",
422 "file_path": "tensorflow\\tensorflow\\python\\keras\\utils\\losses_utils.py",
423 "ast_data": "FunctionDef name:reduce_weighted_loss arg:weighted_losses arg:reduction arguments arg arg If Compare Assign Assign Call If Compare Assign Call Call Return return:yes"
424 },
425 {
426 "library": "scrapy",
427 "name": "text",
428 "source_code": "@property\ndef text(self) -> str:\n raise AttributeError(\"Response content isn't text\")",
429 "docstring": "For subclasses of TextResponse, this will return the body as str",
430 "type": "method",
431 "file_path": "scrapy\\scrapy\\http\\response\\__init__.py",
432 "ast_data": "FunctionDef name:text arg:self arguments arg Raise Call"
433 },
434 {
435 "library": "kornia",
436 "name": "forward",
437 "source_code": "def forward(self, img: Tensor, lafs: Tensor) -> Tensor:\n return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor)",
438 "docstring": "Three stage local feature detection. First the location and scale of interest points are determined by detect function. Then affine shape and orientation. Args: img: image features with shape :math:. lafs: local affine frames :math:. Returns: Local descriptors of shape :math: where :math: is descriptor size.",
439 "type": "method",
440 "file_path": "kornia\\kornia\\feature\\integrated.py",
441 "ast_data": "FunctionDef name:forward arg:self arg:img arg:lafs arguments arg arg arg Return return:yes Call"
442 },
443 {
444 "library": "scikit-learn",
445 "name": "theta",
446 "source_code": "@property\ndef theta(self):\n return np.hstack([kernel.theta for kernel in self.kernels])",
447 "docstring": "Returns the (flattened, log-transformed) non-fixed hyperparameters. Note that theta are typically the log-transformed values of the kernel's hyperparameters as this representation of the search space is more amenable for hyperparameter search, as hyperparameters like length-scales naturally live on a log-scale. Returns ------- theta : ndarray of shape (n_dims,) The non-fixed, log-transformed hyperparameters of the kernel",
448 "type": "method",
449 "file_path": "scikit-learn\\sklearn\\gaussian_process\\kernels.py",
450 "ast_data": "FunctionDef name:theta arg:self arguments arg Return return:yes Call"
451 },
452 {
453 "library": "tensorflow",
454 "name": "run_with_hooks",
455 "source_code": "def run_with_hooks(self, *args, **kwargs):\n return self._run_with_hooks_fn(*args, **kwargs)",
456 "docstring": "Same as . Accepts the same arguments.",
457 "type": "method",
458 "file_path": "tensorflow\\tensorflow\\python\\training\\monitored_session.py",
459 "ast_data": "FunctionDef name:run_with_hooks arg:self arguments arg arg arg Return return:yes Call"
460 },
461 {
462 "library": "pytorch",
463 "name": "sample",
464 "source_code": "def sample(self, sample_shape=torch.Size()):\n with torch.no_grad():\n x = self.base_dist.sample(sample_shape)\n for transform in self.transforms:\n x = transform(x)\n return x",
465 "docstring": "Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched. Samples first from base distribution and applies for every transform in the list.",
466 "type": "method",
467 "file_path": "pytorch\\torch\\distributions\\transformed_distribution.py",
468 "ast_data": "FunctionDef name:sample arg:self arg:sample_shape arguments arg arg Call With Call Assign Call For Assign Call Return return:yes"
469 },
470 {
471 "library": "cherrypy",
472 "name": "SvcStop",
473 "source_code": "def SvcStop(self):\n from cherrypy import process\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n process.bus.exit()",
474 "docstring": "Stop the service.",
475 "type": "method",
476 "file_path": "cherrypy\\cherrypy\\process\\win32.py",
477 "ast_data": "FunctionDef name:SvcStop arg:self arguments arg Call Call"
478 },
479 {
480 "library": "pytorch",
481 "name": "append_step",
482 "source_code": "def append_step(self, step: OutputAdaptStep) -> None:\n self._steps.append(step)",
483 "docstring": "Appends a step to the output format steps. Args: step: The step to append.",
484 "type": "method",
485 "file_path": "pytorch\\torch\\onnx\\_internal\\io_adapter.py",
486 "ast_data": "FunctionDef name:append_step arg:self arg:step arguments arg arg Call"
487 },
488 {
489 "library": "tensorflow",
490 "name": "transform_feature",
491 "source_code": "def transform_feature(self, transformation_cache, state_manager):\n input_tensor = transformation_cache.get(self.key, state_manager)\n return self._transform_input_tensor(input_tensor)",
492 "docstring": "See base class. In this case, we apply the to the input tensor. Args: transformation_cache: A object to access features. state_manager: A to create / access resources such as lookup tables. Returns: Normalized input tensor. Raises: ValueError: If a SparseTensor is passed in.",
493 "type": "method",
494 "file_path": "tensorflow\\tensorflow\\python\\feature_column\\feature_column_v2.py",
495 "ast_data": "FunctionDef name:transform_feature arg:self arg:transformation_cache arg:state_manager arguments arg arg arg Assign Call Return return:yes Call"
496 },
497 {
498 "library": "tensorflow",
499 "name": "compute_output_signature",
500 "source_code": "@doc_controls.for_subclass_implementers\ndef compute_output_signature(self, input_signature):\n\n def check_type_return_shape(s):\n if not isinstance(s, tensor.TensorSpec):\n raise TypeError('Only TensorSpec signature types are supported, but saw signature entry: {}.'.format(s))\n return s.shape\n input_shape = nest.map_structure(check_type_return_shape, input_signature)\n output_shape = self.compute_output_shape(input_shape)\n dtype = self._compute_dtype\n if dtype is None:\n input_dtypes = [s.dtype for s in nest.flatten(input_signature)]\n dtype = input_dtypes[0]\n return nest.map_structure(lambda s: tensor.TensorSpec(dtype=dtype, shape=s), output_shape)",
501 "docstring": "Compute the output tensor signature of the layer based on the inputs. Unlike a TensorShape object, a TensorSpec object contains both shape and dtype information for a tensor. This method allows layers to provide output dtype information if it is different from the input dtype. For any layer that doesn't implement this function, the framework will fall back to use , and will assume that the output dtype matches the input dtype. Args: input_signature: Single TensorSpec or nested structure of TensorSpec objects, describing a candidate input for the layer. Returns: Single TensorSpec or nested structure of TensorSpec objects, describing how the layer would transform the provided input. Raises: TypeError: If input_signature contains a non-TensorSpec object.",
502 "type": "method",
503 "file_path": "tensorflow\\tensorflow\\python\\keras\\engine\\base_layer_v1.py",
504 "ast_data": "FunctionDef name:compute_output_signature arg:self arg:input_signature arguments arg arg FunctionDef name:check_type_return_shape arg:s arguments arg If Call Raise Call Call Return return:yes Assign Call Assign Call Assign If Compare Assign Call Assign Return return:yes Call arguments arg Call"
505 },
506 {
507 "library": "pytorch",
508 "name": "_move_states_to_device",
509 "source_code": "def _move_states_to_device(params: list[nn.Parameter], buffers: list[torch.Tensor], device_from_device_id: Optional[torch.device]) -> None:\n if len(params) == 0 and len(buffers) == 0:\n return\n if len(params) > 0:\n current_device = params[0].device\n elif len(buffers) > 0:\n current_device = buffers[0].device\n cpu_device = torch.device('cpu')\n if device_from_device_id is not None:\n for param in params:\n with torch.no_grad():\n param.data = param.to(device_from_device_id)\n if param.grad is not None:\n param.grad.data = param.grad.to(device_from_device_id)\n for buffer in buffers:\n buffer.data = buffer.to(device_from_device_id)\n elif current_device == cpu_device:\n _warn_cpu_init()",
510 "docstring": "Move states to the specified device. Precondition: `` and module's parameters and buffers have been materialized if needed.",
511 "type": "function",
512 "file_path": "pytorch\\torch\\distributed\\fsdp\\_init_utils.py",
513 "ast_data": "FunctionDef name:_move_states_to_device arg:params arg:buffers arg:device_from_device_id arguments arg arg arg If BoolOp Compare Call Compare Call Return return:no If Compare Call Assign If Compare Call Assign Assign Call If Compare For With Call Assign Call If Compare Assign Call For Assign Call If Compare Call"
514 },
515 {
516 "library": "authlib",
517 "name": "register_client_auth_method",
518 "source_code": "def register_client_auth_method(self, auth):\n if isinstance(auth, tuple):\n self._auth_methods[auth[0]] = auth[1]\n else:\n self._auth_methods[auth.name] = auth",
519 "docstring": "Extend client authenticate for token endpoint. :param auth: an instance to sign the request",
520 "type": "method",
521 "file_path": "authlib\\authlib\\oauth2\\client.py",
522 "ast_data": "FunctionDef name:register_client_auth_method arg:self arg:auth arguments arg arg If Call Assign Assign"
523 },
524 {
525 "library": "django",
526 "name": "data",
527 "source_code": "@property\ndef data(self):\n return self.form._widget_data_value(self.field.widget, self.html_name)",
528 "docstring": "Return the data for this BoundField, or None if it wasn't given.",
529 "type": "method",
530 "file_path": "django\\django\\forms\\boundfield.py",
531 "ast_data": "FunctionDef name:data arg:self arguments arg Return return:yes Call"
532 },
533 {
534 "library": "numpy",
535 "name": "get_info",
536 "source_code": "def get_info(self, notfound_action=0):\n flag = 0\n if not self.has_info():\n flag = 1\n log.info(self.__class__.__name__ + ':')\n if hasattr(self, 'calc_info'):\n self.calc_info()\n if notfound_action:\n if not self.has_info():\n if notfound_action == 1:\n warnings.warn(self.notfounderror.__doc__, stacklevel=2)\n elif notfound_action == 2:\n raise self.notfounderror(self.notfounderror.__doc__)\n else:\n raise ValueError(repr(notfound_action))\n if not self.has_info():\n log.info(' NOT AVAILABLE')\n self.set_info()\n else:\n log.info(' FOUND:')\n res = self.saved_results.get(self.__class__.__name__)\n if log.get_threshold() <= log.INFO and flag:\n for k, v in res.items():\n v = str(v)\n if k in ['sources', 'libraries'] and len(v) > 270:\n v = v[:120] + '...\\n...\\n...' + v[-120:]\n log.info(' %s = %s', k, v)\n log.info('')\n return copy.deepcopy(res)",
537 "docstring": "Return a dictionary with items that are compatible with numpy.distutils.setup keyword arguments.",
538 "type": "method",
539 "file_path": "numpy\\numpy\\distutils\\system_info.py",
540 "ast_data": "FunctionDef name:get_info arg:self arg:notfound_action arguments arg arg Assign If Call Assign Call If Call Call If If Call If Compare Call If Compare Raise Call Raise Call Call If Call Call Call Call Assign Call If BoolOp Compare Call For Call Assign Call If BoolOp Compare Compare Call Assign Call Call Return return:yes Call"
541 },
542 {
543 "library": "tensorflow",
544 "name": "dtensor_reduce",
545 "source_code": "def dtensor_reduce(strategy, reduce_op, value, axis):\n distribute_lib._require_cross_replica_or_default_context_extended(strategy.extended)\n if isinstance(reduce_op, str):\n reduce_op = reduce_util.ReduceOp(reduce_op.upper())\n distributed_input = is_distributed_value(value)\n if not distributed_input and axis is None:\n destinations = device_util.current() or strategy.extended._default_device or '/device:CPU:0'\n devices = cross_device_ops_lib.get_devices_from(destinations)\n with ops.device(devices[0]):\n return array_ops.identity(cross_device_ops_lib.reduce_non_distributed_value(reduce_op, value, destinations, strategy.num_replicas_in_sync))\n value = convert_inputs_to_dtensor(value, strategy._mesh)\n if reduce_op == reduce_util.ReduceOp.MEAN:\n reduce_op = math_ops.reduce_mean\n else:\n reduce_op = math_ops.reduce_sum\n if d_api.fetch_layout(value).is_fully_replicated():\n if axis is not None:\n value = reduce_op(value, axis=axis)\n else:\n new_shape = [strategy.num_replicas_in_sync, -1]\n if len(value.shape) > 1:\n new_shape.extend(array_ops.shape(value)[1:])\n value = array_ops.reshape(value, new_shape)\n if axis is not None:\n value = reduce_op(value, axis=axis + 1)\n value = reduce_op(value, axis=0)\n return value",
546 "docstring": "Implement dtensor based strategy.reduce().",
547 "type": "function",
548 "file_path": "tensorflow\\tensorflow\\python\\distribute\\experimental\\dtensor_util.py",
549 "ast_data": "FunctionDef name:dtensor_reduce arg:strategy arg:reduce_op arg:value arg:axis arguments arg arg arg arg Call If Call Assign Call Call Assign Call If BoolOp Compare Assign BoolOp Call Assign Call With Call Return return:yes Call Call Assign Call If Compare Assign Assign If Call Call If Compare Assign Call Assign If Compare Call Call Call Assign Call If Compare Assign Call Assign Call Return return:yes"
550 },
551 {
552 "library": "tensorflow",
553 "name": "matrix_diag_transform",
554 "source_code": "def matrix_diag_transform(matrix, transform=None, name=None):\n with ops.name_scope(name, 'matrix_diag_transform', [matrix]):\n matrix = ops.convert_to_tensor(matrix, name='matrix')\n if transform is None:\n return matrix\n diag = array_ops.matrix_diag_part(matrix)\n transformed_diag = transform(diag)\n transformed_mat = array_ops.matrix_set_diag(matrix, transformed_diag)\n return transformed_mat",
555 "docstring": "Transform diagonal of [batch-]matrix, leave rest of matrix unchanged. Create a trainable covariance defined by a Cholesky factor: Example of heteroskedastic 2-D linear regression. Args: matrix: Rank , , where the last two dimensions are equal. transform: Element-wise function mapping to . To be applied to the diagonal of . If , is returned unchanged. Defaults to . name: A name to give created ops. Defaults to \"matrix_diag_transform\". Returns: A with same shape and as .",
556 "type": "function",
557 "file_path": "tensorflow\\tensorflow\\python\\ops\\distributions\\util.py",
558 "ast_data": "FunctionDef name:matrix_diag_transform arg:matrix arg:transform arg:name arguments arg arg arg With Call Assign Call If Compare Return return:yes Assign Call Assign Call Assign Call Return return:yes"
559 },
560 {
561 "library": "scipy",
562 "name": "__init__",
563 "source_code": "def __init__(self, sk, yk):\n if sk.shape != yk.shape or sk.ndim != 2:\n raise ValueError('sk and yk must have matching shape, (n_corrs, n)')\n n_corrs, n = sk.shape\n super().__init__(dtype=np.float64, shape=(n, n))\n self.sk = sk\n self.yk = yk\n self.n_corrs = n_corrs\n self.rho = 1 / np.einsum('ij,ij->i', sk, yk)",
564 "docstring": "Construct the operator.",
565 "type": "method",
566 "file_path": "scipy\\scipy\\optimize\\_lbfgsb_py.py",
567 "ast_data": "FunctionDef name:__init__ arg:self arg:sk arg:yk arguments arg arg arg If BoolOp Compare Compare Raise Call Assign Call Call Assign Assign Assign Assign Call"
568 },
569 {
570 "library": "tensorflow",
571 "name": "make_test_function",
572 "source_code": "def make_test_function(self):\n if self.test_function is not None:\n return self.test_function\n\n def step_function(model, iterator):\n\n def run_step(data):\n outputs = model.test_step(data)\n with ops.control_dependencies(_minimum_control_deps(outputs)):\n model._test_counter.assign_add(1)\n return outputs\n data = next(iterator)\n outputs = model.distribute_strategy.run(run_step, args=(data,))\n outputs = reduce_per_replica(outputs, self.distribute_strategy, reduction='first')\n return outputs\n if self._steps_per_execution.numpy().item() == 1:\n\n def test_function(iterator):\n return step_function(self, iterator)\n else:\n\n def test_function(iterator):\n for _ in math_ops.range(self._steps_per_execution):\n outputs = step_function(self, iterator)\n return outputs\n if not self.run_eagerly:\n test_function = def_function.function(test_function, experimental_relax_shapes=True)\n self.test_function = test_function\n if self._cluster_coordinator:\n self.test_function = lambda iterator: self._cluster_coordinator.schedule(test_function, args=(iterator,))\n return self.test_function",
573 "docstring": "Creates a function that executes one step of evaluation. This method can be overridden to support custom evaluation logic. This method is called by and . Typically, this method directly controls and settings, and delegates the actual evaluation logic to . This function is cached the first time or is called. The cache is cleared whenever is called. Returns: Function. The function created by this method should accept a , and return a containing values that will be passed to .",
574 "type": "method",
575 "file_path": "tensorflow\\tensorflow\\python\\keras\\engine\\training.py",
576 "ast_data": "FunctionDef name:make_test_function arg:self arguments arg If Compare Return return:yes FunctionDef name:step_function arg:model arg:iterator arguments arg arg FunctionDef name:run_step arg:data arguments arg Assign Call With Call Call Call Return return:yes Assign Call Assign Call Assign Call Return return:yes If Compare Call Call FunctionDef name:test_function arg:iterator arguments arg Return return:yes Call FunctionDef name:test_function arg:iterator arguments arg For Call Assign Call Return return:yes If Assign Call Assign If Assign arguments arg Call Return return:yes"
577 },
578 {
579 "library": "tensorflow",
580 "name": "variable_shape",
581 "source_code": "@property\ndef variable_shape(self):\n return tensor_shape.TensorShape([self.shared_embedding_column_creator.dimension])",
582 "docstring": "See base class.",
583 "type": "method",
584 "file_path": "tensorflow\\tensorflow\\python\\feature_column\\feature_column_v2.py",
585 "ast_data": "FunctionDef name:variable_shape arg:self arguments arg Return return:yes Call"
586 },
587 {
588 "library": "tensorflow",
589 "name": "_from_components",
590 "source_code": "@abc.abstractmethod\ndef _from_components(self, components):\n raise NotImplementedError('%s._from_components()' % type(self).__name__)",
591 "docstring": "Reconstructs a value from a nested structure of Tensor/CompositeTensor. Args: components: A nested structure of or , compatible with . (Caller is responsible for ensuring compatibility.) Returns: A value that is compatible with this .",
592 "type": "method",
593 "file_path": "tensorflow\\tensorflow\\python\\framework\\type_spec.py",
594 "ast_data": "FunctionDef name:_from_components arg:self arg:components arguments arg arg Raise Call Call"
595 },
596 {
597 "library": "pytorch",
598 "name": "parse_dims",
599 "source_code": "@classmethod\ndef parse_dims(cls, input_dims: list[str], output_dim: str) -> 'EinsumDims':\n dim_char_set: set[str] = set()\n for input_dim in input_dims:\n dim_char_set.update(input_dim)\n all_dim_chars = sorted(dim_char_set)\n lhs_out_only_dims, rhs_out_only_dims = ([], [])\n batch_dims, contracting_dims = ([], [])\n for dim_char in all_dim_chars:\n if dim_char not in output_dim:\n contracting_dims.append(dim_char)\n else:\n is_batch_dim = True\n for input_dim in input_dims:\n is_batch_dim = is_batch_dim and dim_char in input_dim\n if is_batch_dim:\n batch_dims.append(dim_char)\n else:\n assert len(input_dims) == 2, 'free dimension only supported for two inputs!'\n lhs, rhs = input_dims\n if dim_char in lhs:\n lhs_out_only_dims.append(dim_char)\n elif dim_char in rhs:\n rhs_out_only_dims.append(dim_char)\n else:\n raise RuntimeError('Invalid dimension character')\n return cls(contracting_dims=contracting_dims, batch_dims=batch_dims, lhs_out_only_dims=lhs_out_only_dims, rhs_out_only_dims=rhs_out_only_dims)",
600 "docstring": "Parse the dims and extract the contracting, batch, and free dimensions for the left and right hand sides.",
601 "type": "method",
602 "file_path": "pytorch\\torch\\distributed\\tensor\\_ops\\_einsum_strategy.py",
603 "ast_data": "FunctionDef name:parse_dims arg:cls arg:input_dims arg:output_dim arguments arg arg arg Call For Call Assign Call Assign Assign For If Compare Call Assign For Assign BoolOp Compare If Call Compare Call Assign If Compare Call If Compare Call Raise Call Return return:yes Call"
604 },
605 {
606 "library": "tensorflow",
607 "name": "indent_xml",
608 "source_code": "def indent_xml(elem, level=0) -> None:\n indent_str = '\\n' + level * ' '\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = indent_str + ' '\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent_str\n for elem in elem:\n indent_xml(elem, level + 1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent_str\n elif level and (not elem.tail or not elem.tail.strip()):\n elem.tail = indent_str",
609 "docstring": "Indents and newlines the XML for better output.",
610 "type": "function",
611 "file_path": "tensorflow\\ci\\official\\utilities\\extract_resultstore_links.py",
612 "ast_data": "FunctionDef name:indent_xml arg:elem arg:level arguments arg arg Assign If Call If BoolOp Call Assign If BoolOp Call Assign For Call If BoolOp Call Assign If BoolOp BoolOp Call Assign"
613 },
614 {
615 "library": "sphinx",
616 "name": "number_reference",
617 "source_code": "class number_reference(nodes.reference):\n pass",
618 "docstring": "Node for number references, similar to pending_xref.",
619 "type": "class",
620 "file_path": "sphinx\\sphinx\\addnodes.py",
621 "ast_data": "ClassDef name:number_reference"
622 },
623 {
624 "library": "pandas",
625 "name": "construct_1d_object_array_from_listlike",
626 "source_code": "def construct_1d_object_array_from_listlike(values: Collection) -> np.ndarray:\n return np.fromiter(values, dtype='object', count=len(values))",
627 "docstring": "Transform any list-like object in a 1-dimensional numpy array of object dtype. Parameters ---------- values : any iterable which has a len() Raises ------ TypeError * If does not have a len() Returns ------- 1-dimensional numpy array of dtype object",
628 "type": "function",
629 "file_path": "pandas\\pandas\\core\\dtypes\\cast.py",
630 "ast_data": "FunctionDef name:construct_1d_object_array_from_listlike arg:values arguments arg Return return:yes Call Call"
631 },
632 {
633 "library": "numpy",
634 "name": "amin",
635 "source_code": "@array_function_dispatch(_min_dispatcher)\ndef amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue):\n return _wrapreduction(a, np.minimum, 'min', axis, None, out, keepdims=keepdims, initial=initial, where=where)",
636 "docstring": "Return the minimum of an array or minimum along an axis. is an alias of . See Also -------- min : alias of this function ndarray.min : equivalent method",
637 "type": "function",
638 "file_path": "numpy\\numpy\\_core\\fromnumeric.py",
639 "ast_data": "FunctionDef name:amin arg:a arg:axis arg:out arg:keepdims arg:initial arg:where arguments arg arg arg arg arg arg Return return:yes Call Call"
640 },
641 {
642 "library": "pytorch",
643 "name": "UnshardHandle",
644 "source_code": "class UnshardHandle:\n\n def wait(self) -> None:\n return",
645 "docstring": "A handle to wait on a :meth: op.",
646 "type": "class",
647 "file_path": "pytorch\\torch\\distributed\\fsdp\\_fully_shard\\_fully_shard.py",
648 "ast_data": "ClassDef name:UnshardHandle FunctionDef name:wait arg:self arguments arg Return return:no"
649 },
650 {
651 "library": "scipy",
652 "name": "Rastrigin",
653 "source_code": "class Rastrigin(Benchmark):\n change_dimensionality = True\n\n def __init__(self, dimensions=2):\n Benchmark.__init__(self, dimensions)\n self._bounds = list(zip([-5.12] * self.N, [5.12] * self.N))\n self.global_optimum = [[0 for _ in range(self.N)]]\n self.fglob = 0.0\n\n def fun(self, x, *args):\n self.nfev += 1\n return 10.0 * self.N + sum(x ** 2.0 - 10.0 * cos(2.0 * pi * x))",
654 "docstring": "Rastrigin objective function. This class defines the Rastrigin [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\\text{Rastrigin}}(x) = 10n \\sum_{i=1}^n \\left[ x_i^2 - 10 \\cos(2\\pi x_i) \\right] Here, :math: represents the number of dimensions and :math: for :math:. *Global optimum*: :math: for :math: for :math: .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015",
655 "type": "class",
656 "file_path": "scipy\\benchmarks\\benchmarks\\go_benchmark_functions\\go_funcs_R.py",
657 "ast_data": "ClassDef name:Rastrigin Assign FunctionDef name:__init__ arg:self arg:dimensions arguments arg arg Call Assign Call Call Assign Call Assign FunctionDef name:fun arg:self arg:x arguments arg arg arg Return return:yes Call Call"
658 },
659 {
660 "library": "scikit-learn",
661 "name": "_plot",
662 "source_code": "def _plot(results, metrics, formats, title, x_ticks, x_label, format_markers=('x', '|', 'o', '+'), metric_colors=('c', 'm', 'y', 'k', 'g', 'r', 'b')):\n fig = plt.figure('scikit-learn multilabel metrics benchmarks')\n plt.title(title)\n ax = fig.add_subplot(111)\n for i, metric in enumerate(metrics):\n for j, format in enumerate(formats):\n ax.plot(x_ticks, results[i, j].flat, label='{}, {}'.format(metric, format), marker=format_markers[j], color=metric_colors[i % len(metric_colors)])\n ax.set_xlabel(x_label)\n ax.set_ylabel('Time (s)')\n ax.legend()\n plt.show()",
663 "docstring": "Plot the results by metric, format and some other variable given by x_label",
664 "type": "function",
665 "file_path": "scikit-learn\\benchmarks\\bench_multilabel_metrics.py",
666 "ast_data": "FunctionDef name:_plot arg:results arg:metrics arg:formats arg:title arg:x_ticks arg:x_label arg:format_markers arg:metric_colors arguments arg arg arg arg arg arg arg arg Assign Call Call Assign Call For Call For Call Call Call Call Call Call Call Call"
667 },
668 {
669 "library": "tensorflow",
670 "name": "_check_valid_event_ndims",
671 "source_code": "def _check_valid_event_ndims(self, min_event_ndims, event_ndims):\n event_ndims = ops.convert_to_tensor(event_ndims, name='event_ndims')\n event_ndims_ = tensor_util.constant_value(event_ndims)\n assertions = []\n if not event_ndims.dtype.is_integer:\n raise ValueError('Expected integer dtype, got dtype {}'.format(event_ndims.dtype))\n if event_ndims_ is not None:\n if event_ndims.shape.ndims != 0:\n raise ValueError('Expected scalar event_ndims, got shape {}'.format(event_ndims.shape))\n if min_event_ndims > event_ndims_:\n raise ValueError('event_ndims ({}) must be larger than min_event_ndims ({})'.format(event_ndims_, min_event_ndims))\n elif self.validate_args:\n assertions += [check_ops.assert_greater_equal(event_ndims, min_event_ndims)]\n if event_ndims.shape.is_fully_defined():\n if event_ndims.shape.ndims != 0:\n raise ValueError('Expected scalar shape, got ndims {}'.format(event_ndims.shape.ndims))\n elif self.validate_args:\n assertions += [check_ops.assert_rank(event_ndims, 0, message='Expected scalar.')]\n return assertions",
672 "docstring": "Check whether event_ndims is at least min_event_ndims.",
673 "type": "method",
674 "file_path": "tensorflow\\tensorflow\\python\\ops\\distributions\\bijector_impl.py",
675 "ast_data": "FunctionDef name:_check_valid_event_ndims arg:self arg:min_event_ndims arg:event_ndims arguments arg arg arg Assign Call Assign Call Assign If Raise Call Call If Compare If Compare Raise Call Call If Compare Raise Call Call If Call If Call If Compare Raise Call Call If Call Return return:yes"
676 },
677 {
678 "library": "django",
679 "name": "upload_interrupted",
680 "source_code": "def upload_interrupted(self):\n pass",
681 "docstring": "Signal that the upload was interrupted. Subclasses should perform cleanup that is necessary for this handler.",
682 "type": "method",
683 "file_path": "django\\django\\core\\files\\uploadhandler.py",
684 "ast_data": "FunctionDef name:upload_interrupted arg:self arguments arg"
685 },
686 {
687 "library": "django",
688 "name": "wkb_size",
689 "source_code": "@property\ndef wkb_size(self):\n return capi.get_wkbsize(self.ptr)",
690 "docstring": "Return the size of the WKB buffer.",
691 "type": "method",
692 "file_path": "django\\django\\contrib\\gis\\gdal\\geometries.py",
693 "ast_data": "FunctionDef name:wkb_size arg:self arguments arg Return return:yes Call"
694 },
695 {
696 "library": "scikit-learn",
697 "name": "_set_random_states",
698 "source_code": "def _set_random_states(estimator, random_state=None):\n random_state = check_random_state(random_state)\n to_set = {}\n for key in sorted(estimator.get_params(deep=True)):\n if key == 'random_state' or key.endswith('__random_state'):\n to_set[key] = random_state.randint(np.iinfo(np.int32).max)\n if to_set:\n estimator.set_params(**to_set)",
699 "docstring": "Set fixed random_state parameters for an estimator. Finds all parameters ending `Glossary ` rvs",
700 "type": "function",
701 "file_path": "scikit-learn\\sklearn\\ensemble\\_base.py",
702 "ast_data": "FunctionDef name:_set_random_states arg:estimator arg:random_state arguments arg arg Assign Call Assign For Call Call If BoolOp Compare Call Assign Call Call If Call"
703 },
704 {
705 "library": "tensorflow",
706 "name": "_apply_fn",
707 "source_code": "def _apply_fn(dataset):\n return dataset.rejection_resample(class_func=class_func, target_dist=target_dist, initial_dist=initial_dist, seed=seed)",
708 "docstring": "Function from to that applies the transformation.",
709 "type": "function",
710 "file_path": "tensorflow\\tensorflow\\python\\data\\experimental\\ops\\resampling.py",
711 "ast_data": "FunctionDef name:_apply_fn arg:dataset arguments arg Return return:yes Call"
712 },
713 {
714 "library": "tensorflow",
715 "name": "_snapshot_streams",
716 "source_code": "def _snapshot_streams(self, path) -> Iterable[_pywrap_server_lib.SnapshotStreamInfoWrapper]:\n return self._server.snapshot_streams(path)",
717 "docstring": "Returns information about all the streams for a snapshot.",
718 "type": "method",
719 "file_path": "tensorflow\\tensorflow\\python\\data\\experimental\\service\\server_lib.py",
720 "ast_data": "FunctionDef name:_snapshot_streams arg:self arg:path arguments arg arg Return return:yes Call"
721 },
722 {
723 "library": "scipy",
724 "name": "to_native",
725 "source_code": "def to_native(A):\n dt = A.dtype\n if dt.isnative:\n return A\n return np.asarray(A, dtype=dt.newbyteorder('native'))",
726 "docstring": "Ensure that the data type of the NumPy array has native byte order. must be a NumPy array. If the data type of does not have native byte order, a copy of with a native byte order is returned. Otherwise is returned.",
727 "type": "function",
728 "file_path": "scipy\\scipy\\sparse\\_sputils.py",
729 "ast_data": "FunctionDef name:to_native arg:A arguments arg Assign If Return return:yes Return return:yes Call Call"
730 },
731 {
732 "library": "numpy",
733 "name": "printoptions",
734 "source_code": "@set_module('numpy')\n@contextlib.contextmanager\ndef printoptions(*args, **kwargs):\n token = _set_printoptions(*args, **kwargs)\n try:\n yield get_printoptions()\n finally:\n format_options.reset(token)",
735 "docstring": "Context manager for setting print options. Set print options for the scope of the block, and restore the old options at the end. See for the full description of available options. Examples -------- >>> import numpy as np >>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67]) The -clause of the -statement gives the current print options: >>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions()) See Also -------- set_printoptions, get_printoptions",
736 "type": "function",
737 "file_path": "numpy\\numpy\\_core\\arrayprint.py",
738 "ast_data": "FunctionDef name:printoptions arguments arg arg Assign Call Try Call Call Call"
739 },
740 {
741 "library": "pytorch",
742 "name": "all_node_args_except_first",
743 "source_code": "def all_node_args_except_first(node: Node) -> list[int]:\n return list(range(1, len(node.args)))",
744 "docstring": "Returns all node arg indices after first",
745 "type": "function",
746 "file_path": "pytorch\\torch\\ao\\quantization\\fx\\utils.py",
747 "ast_data": "FunctionDef name:all_node_args_except_first arg:node arguments arg Return return:yes Call Call Call"
748 },
749 {
750 "library": "pandas",
751 "name": "_get_offsets_buffer",
752 "source_code": "def _get_offsets_buffer(self) -> tuple[PandasBuffer, Any]:\n if self.dtype[0] == DtypeKind.STRING:\n values = self._col.to_numpy()\n ptr = 0\n offsets = np.zeros(shape=(len(values) + 1,), dtype=np.int64)\n for i, v in enumerate(values):\n if isinstance(v, str):\n b = v.encode(encoding='utf-8')\n ptr += len(b)\n offsets[i + 1] = ptr\n buffer = PandasBuffer(offsets)\n dtype = (DtypeKind.INT, 64, ArrowCTypes.INT64, Endianness.NATIVE)\n else:\n raise NoBufferPresent('This column has a fixed-length dtype so it does not have an offsets buffer')\n return (buffer, dtype)",
753 "docstring": "Return the buffer containing the offset values for variable-size binary data (e.g., variable-length strings) and the buffer's associated dtype. Raises NoBufferPresent if the data buffer does not have an associated offsets buffer.",
754 "type": "method",
755 "file_path": "pandas\\pandas\\core\\interchange\\column.py",
756 "ast_data": "FunctionDef name:_get_offsets_buffer arg:self arguments arg If Compare Assign Call Assign Assign Call Call For Call If Call Assign Call Call Assign Assign Call Assign Raise Call Return return:yes"
757 },
758 {
759 "library": "tensorflow",
760 "name": "__init__",
761 "source_code": "def __init__(self, filenames, compression_type=None, buffer_size=None, name=None):\n self._filenames = filenames\n self._compression_type = convert.optional_param_to_tensor('compression_type', compression_type, argument_default='', argument_dtype=dtypes.string)\n self._buffer_size = convert.optional_param_to_tensor('buffer_size', buffer_size, argument_default=_DEFAULT_READER_BUFFER_SIZE_BYTES)\n self._name = name\n variant_tensor = gen_dataset_ops.text_line_dataset(self._filenames, self._compression_type, self._buffer_size, metadata=self._metadata.SerializeToString())\n super(_TextLineDataset, self).__init__(variant_tensor)",
762 "docstring": "Creates a . Args: filenames: A tensor containing one or more filenames. compression_type: (Optional.) A scalar evaluating to one of (no compression), , or . buffer_size: (Optional.) A scalar denoting the number of bytes to buffer. A value of 0 results in the default buffering values chosen based on the compression type. name: (Optional.) A name for the tf.data operation.",
763 "type": "method",
764 "file_path": "tensorflow\\tensorflow\\python\\data\\ops\\readers.py",
765 "ast_data": "FunctionDef name:__init__ arg:self arg:filenames arg:compression_type arg:buffer_size arg:name arguments arg arg arg arg arg Assign Assign Call Assign Call Assign Assign Call Call Call Call"
766 },
767 {
768 "library": "pytorch",
769 "name": "release",
770 "source_code": "def release(self):\n if self.fd is not None:\n os.close(self.fd)\n os.remove(self.lock_file_path)",
771 "docstring": "Release the baton and removes its file.",
772 "type": "method",
773 "file_path": "pytorch\\torch\\utils\\file_baton.py",
774 "ast_data": "FunctionDef name:release arg:self arguments arg If Compare Call Call"
775 },
776 {
777 "library": "pytorch",
778 "name": "get_idx_from_placements",
779 "source_code": "def get_idx_from_placements(placements, current_rank) -> int:\n for idx, placement in enumerate(placements):\n if current_rank == placement.rank():\n return idx\n raise RuntimeError('current_rank not in the placement.')",
780 "docstring": "Return the position of the current rank in the given placements. Args: placements(List[Union[_remote_device, str]]): Specifies the placement of each shard of the Tensor. The size of the list represents the number of shards to be created. This could be a list of :class:'s. This list could also contain a string which represents remote device as accepted by :class: current_rank (int): number of current device. Returns: A int which contains the position of current device in the placement list.",
781 "type": "function",
782 "file_path": "pytorch\\torch\\distributed\\_shard\\sharded_tensor\\reshard.py",
783 "ast_data": "FunctionDef name:get_idx_from_placements arg:placements arg:current_rank arguments arg arg For Call If Compare Call Return return:yes Raise Call"
784 },
785 {
786 "library": "pytorch",
787 "name": "clone_inputs_retaining_gradness",
788 "source_code": "def clone_inputs_retaining_gradness(example_inputs):\n cloned_inputs = clone_inputs(example_inputs)\n for idx in range(len(example_inputs)):\n if isinstance(cloned_inputs[idx], torch.Tensor):\n cloned_inputs[idx].requires_grad_(example_inputs[idx].requires_grad)\n return cloned_inputs",
789 "docstring": "This clone inputs is different from utils clone_input. In case of minifier, all the tensors are leaf tensors while creating a new graph. So, we set the requires_grad field w/o checking the leafness of the tensor.",
790 "type": "function",
791 "file_path": "pytorch\\torch\\_dynamo\\debug_utils.py",
792 "ast_data": "FunctionDef name:clone_inputs_retaining_gradness arg:example_inputs arguments arg Assign Call For Call Call If Call Call Return return:yes"
793 },
794 {
795 "library": "tensorflow",
796 "name": "_list_to_string",
797 "source_code": "def _list_to_string(l, s):\n return s.join(l)",
798 "docstring": "Concatenates list items into a single string separated by . Args: l: List with items to be concatenated into a single string. s: String or char that will be concatenated in between each item. Returns: String that has all items in list concatenated with separator.",
799 "type": "function",
800 "file_path": "tensorflow\\tensorflow\\tools\\tensorflow_builder\\compat_checker\\compat_checker.py",
801 "ast_data": "FunctionDef name:_list_to_string arg:l arg:s arguments arg arg Return return:yes Call"
802 },
803 {
804 "library": "matplotlib",
805 "name": "__init__",
806 "source_code": "def __init__(self, verts, sizes=None, *, closed=True, **kwargs):\n super().__init__(**kwargs)\n self.set_sizes(sizes)\n self.set_verts(verts, closed)\n self.stale = True",
807 "docstring": "Parameters ---------- verts : list of array-like The sequence of polygons [*verts0*, *verts1*, ...] where each element *verts_i* defines the vertices of polygon *i* as a 2D array-like of shape (M, 2). sizes : array-like, default: None Squared scaling factors for the polygons. The coordinates of each polygon *verts_i* are multiplied by the square-root of the corresponding entry in *sizes* (i.e., *sizes* specify the scaling of areas). The scaling is applied before the Artist master transform. closed : bool, default: True Whether the polygon should be closed by adding a CLOSEPOLY connection at the end. **kwargs Forwarded to .",
808 "type": "method",
809 "file_path": "matplotlib\\lib\\matplotlib\\collections.py",
810 "ast_data": "FunctionDef name:__init__ arg:self arg:verts arg:sizes arguments arg arg arg arg arg Call Call Call Call Assign"
811 },
812 {
813 "library": "tensorflow",
814 "name": "exceptions_raised",
815 "source_code": "@property\ndef exceptions_raised(self):\n return self._exceptions_raised",
816 "docstring": "Exceptions raised but not handled by the threads. Exceptions raised in queue runner threads are handled in one of two ways depending on whether or not a was passed to : * With a , exceptions are reported to the coordinator and forgotten by the . * Without a , exceptions are captured by the and made available in this property. Returns: A list of Python objects. The list is empty if no exception was captured. (No exceptions are captured when using a Coordinator.)",
817 "type": "method",
818 "file_path": "tensorflow\\tensorflow\\python\\training\\queue_runner_impl.py",
819 "ast_data": "FunctionDef name:exceptions_raised arg:self arguments arg Return return:yes"
820 },
821 {
822 "library": "tensorflow",
823 "name": "_StatelessGammaGradAlpha",
824 "source_code": "def _StatelessGammaGradAlpha(shape, alpha, sample, grad):\n num_sample_dimensions = array_ops.shape(shape)[0] - array_ops.rank(alpha)\n alpha_broadcastable = add_leading_unit_dimensions(alpha, num_sample_dimensions)\n partial_a = gen_random_ops.random_gamma_grad(alpha_broadcastable, sample)\n return math_ops.reduce_sum(grad * partial_a, axis=math_ops.range(num_sample_dimensions))",
825 "docstring": "Returns gradients of a gamma sampler wrt alpha.",
826 "type": "function",
827 "file_path": "tensorflow\\tensorflow\\python\\ops\\random_grad.py",
828 "ast_data": "FunctionDef name:_StatelessGammaGradAlpha arg:shape arg:alpha arg:sample arg:grad arguments arg arg arg arg Assign Call Call Assign Call Assign Call Return return:yes Call Call"
829 },
830 {
831 "library": "pytorch",
832 "name": "get_qconfig_info",
833 "source_code": "def get_qconfig_info(self, model) -> dict[str, DetectorQConfigInfo]:\n return {}",
834 "docstring": "Returns the DetectorQConfigInfo for each module_fqn relevant Args model (nn.Module or subclass): model to find observer insertion points Returns a Dict mapping from unique observer fqns (where we want to insert them) to: A DetectorQConfigInfo with the information to generate a QConfig for a specific module",
835 "type": "method",
836 "file_path": "pytorch\\torch\\ao\\quantization\\fx\\_model_report\\detector.py",
837 "ast_data": "FunctionDef name:get_qconfig_info arg:self arg:model arguments arg arg Return return:no"
838 },
839 {
840 "library": "tensorflow",
841 "name": "recoverable",
842 "source_code": "def recoverable(self):\n state = self.state()\n symptoms = self.symptoms()\n if state and state in ['TERMINATED', 'PREEMPTED']:\n return False\n elif FLAGS.runtime_oom_exit and self._oom_event(symptoms):\n return False\n elif FLAGS.hbm_oom_exit and self._hbm_oom_event(symptoms):\n return False\n return True",
843 "docstring": "Returns true if the TPU is in a state where training should eventually resume. If false the TPU is in a unrecoverable state and should be recreated.",
844 "type": "method",
845 "file_path": "tensorflow\\tensorflow\\python\\tpu\\client\\client.py",
846 "ast_data": "FunctionDef name:recoverable arg:self arguments arg Assign Call Assign Call If BoolOp Compare Return return:yes If BoolOp Call Return return:yes If BoolOp Call Return return:yes Return return:yes"
847 },
848 {
849 "library": "matplotlib",
850 "name": "edges",
851 "source_code": "@property\ndef edges(self):\n return self._edges",
852 "docstring": "The default value of for newly added cells using . Notes ----- This setting does currently only affect newly created cells using . To change existing cells, you have to set their edges explicitly:: for c in tab.get_celld().values(): c.visible_edges = 'horizontal'",
853 "type": "method",
854 "file_path": "matplotlib\\lib\\matplotlib\\table.py",
855 "ast_data": "FunctionDef name:edges arg:self arguments arg Return return:yes"
856 },
857 {
858 "library": "tensorflow",
859 "name": "__init__",
860 "source_code": "def __init__(self, queue, ev_writer, flush_secs, flush_complete, flush_sentinel, close_sentinel):\n threading.Thread.__init__(self, name='EventLoggerThread')\n self.daemon = True\n self._queue = queue\n self._ev_writer = ev_writer\n self._flush_secs = flush_secs\n self._next_event_flush_time = 0\n self._flush_complete = flush_complete\n self._flush_sentinel = flush_sentinel\n self._close_sentinel = close_sentinel\n self.failure_exc_info = ()",
861 "docstring": "Creates an _EventLoggerThread. Args: queue: A CloseableQueue from which to dequeue events. The queue will be closed just before the thread exits, whether due to or any exception raised in the writing loop. ev_writer: An event writer. Used to log brain events for the visualizer. flush_secs: How often, in seconds, to flush the pending file to disk. flush_complete: A threading.Event that will be set whenever a flush operation requested via has been completed. flush_sentinel: A sentinel element in queue that tells this thread to flush the writer and mark the current flush operation complete. close_sentinel: A sentinel element in queue that tells this thread to terminate and close the queue.",
862 "type": "method",
863 "file_path": "tensorflow\\tensorflow\\python\\summary\\writer\\event_file_writer.py",
864 "ast_data": "FunctionDef name:__init__ arg:self arg:queue arg:ev_writer arg:flush_secs arg:flush_complete arg:flush_sentinel arg:close_sentinel arguments arg arg arg arg arg arg arg Call Assign Assign Assign Assign Assign Assign Assign Assign Assign"
865 },
866 {
867 "library": "tensorflow",
868 "name": "_common_prefix",
869 "source_code": "def _common_prefix(self, m):\n if not m:\n return ''\n s1 = min(m)\n s2 = max(m)\n for i, c in enumerate(s1):\n if c != s2[i]:\n return s1[:i]\n return s1",
870 "docstring": "Given a list of str, returns the longest common prefix. Args: m: (list of str) A list of strings. Returns: (str) The longest common prefix.",
871 "type": "method",
872 "file_path": "tensorflow\\tensorflow\\python\\debug\\cli\\debugger_cli_common.py",
873 "ast_data": "FunctionDef name:_common_prefix arg:self arg:m arguments arg arg If Return return:yes Assign Call Assign Call For Call If Compare Return return:yes Return return:yes"
874 },
875 {
876 "library": "tensorflow",
877 "name": "master_job",
878 "source_code": "def master_job(master, cluster_def):\n if master in _LOCAL_MASTERS:\n return None\n if not cluster_def or not cluster_def.job:\n return _DEFAULT_JOB_NAME\n job_names = set((job.name for job in cluster_def.job))\n if _DEFAULT_JOB_NAME in job_names:\n raise ValueError('Currently, tpu_worker is not an allowed job name.')\n if len(job_names) == 1:\n return cluster_def.job[0].name\n if len(job_names) == 2:\n if _DEFAULT_COORDINATOR_JOB_NAME in job_names:\n job_names.remove(_DEFAULT_COORDINATOR_JOB_NAME)\n return job_names.pop()\n raise ValueError('Could not infer TPU job name.')",
879 "docstring": "Returns the canonical job name to use to place TPU computations on. Args: master: A representing the TensorFlow master to use. cluster_def: A ClusterDef object describing the TPU cluster. Returns: A string containing the job name, or None if no job should be specified. Raises: ValueError: If the user needs to specify a tpu_job_name, because we are unable to infer the job name automatically, or if the user-specified job names are inappropriate.",
880 "type": "function",
881 "file_path": "tensorflow\\tensorflow\\python\\tpu\\tpu_system_metadata.py",
882 "ast_data": "FunctionDef name:master_job arg:master arg:cluster_def arguments arg arg If Compare Return return:no If BoolOp Return return:yes Assign Call If Compare Raise Call If Compare Call Return return:yes If Compare Call If Compare Call Return return:yes Call Raise Call"
883 },
884 {
885 "library": "scipy",
886 "name": "fun",
887 "source_code": "@property\ndef fun(self):\n if self._f is None:\n self._f = self._fun(self._x)\n return self._f",
888 "docstring": "Value of objective function at current iteration.",
889 "type": "method",
890 "file_path": "scipy\\scipy\\optimize\\_trustregion.py",
891 "ast_data": "FunctionDef name:fun arg:self arguments arg If Compare Assign Call Return return:yes"
892 },
893 {
894 "library": "pytorch",
895 "name": "close",
896 "source_code": "def close(self, death_sig: Optional[signal.Signals]=None, timeout: int=30) -> None:\n if not death_sig:\n death_sig = _get_default_signal()\n self._close(death_sig=death_sig, timeout=timeout)\n if self._stdout_tail:\n self._stdout_tail.stop()\n if self._stderr_tail:\n self._stderr_tail.stop()",
897 "docstring": "Terminates all processes managed by this context and cleans up any meta resources (e.g. redirect, error_file files). Args: death_sig: Death signal to terminate processes. timeout: Time to wait for processes to finish, if process is still alive after this time, it will be terminated via SIGKILL.",
898 "type": "method",
899 "file_path": "pytorch\\torch\\distributed\\elastic\\multiprocessing\\api.py",
900 "ast_data": "FunctionDef name:close arg:self arg:death_sig arg:timeout arguments arg arg arg If Assign Call Call If Call If Call"
901 },
902 {
903 "library": "matplotlib",
904 "name": "get_pickradius",
905 "source_code": "def get_pickradius(self):\n return self._pickradius",
906 "docstring": "Return the depth of the axis used by the picker.",
907 "type": "method",
908 "file_path": "matplotlib\\lib\\matplotlib\\axis.py",
909 "ast_data": "FunctionDef name:get_pickradius arg:self arguments arg Return return:yes"
910 },
911 {
912 "library": "matplotlib",
913 "name": "__init__",
914 "source_code": "def __init__(self, t_direction, t, f1, f2, *, where=None, interpolate=False, step=None, **kwargs):\n self.t_direction = t_direction\n self._interpolate = interpolate\n self._step = step\n verts = self._make_verts(t, f1, f2, where)\n super().__init__(verts, **kwargs)",
915 "docstring": "Parameters ---------- t_direction : {{'x', 'y'}} The axes on which the variable lies. - 'x': the curves are `.PolyCollection`. See Also -------- .Axes.fill_between, .Axes.fill_betweenx",
916 "type": "method",
917 "file_path": "matplotlib\\lib\\matplotlib\\collections.py",
918 "ast_data": "FunctionDef name:__init__ arg:self arg:t_direction arg:t arg:f1 arg:f2 arguments arg arg arg arg arg arg arg arg arg Assign Assign Assign Assign Call Call Call"
919 },
920 {
921 "library": "scipy",
922 "name": "save_npz",
923 "source_code": "def save_npz(file, matrix, compressed=True):\n arrays_dict = {}\n if matrix.format in ('csc', 'csr', 'bsr'):\n arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)\n elif matrix.format == 'dia':\n arrays_dict.update(offsets=matrix.offsets)\n elif matrix.format == 'coo':\n arrays_dict.update(row=matrix.row, col=matrix.col)\n else:\n msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'\n raise NotImplementedError(msg)\n arrays_dict.update(format=matrix.format.encode('ascii'), shape=matrix.shape, data=matrix.data)\n if isinstance(matrix, sp.sparse.sparray):\n arrays_dict.update(_is_array=True)\n if compressed:\n np.savez_compressed(file, **arrays_dict)\n else:\n np.savez(file, **arrays_dict)",
924 "docstring": "Save a sparse matrix or array to a file using `` archive. Examples -------- Store sparse matrix to disk, and load it again: >>> import numpy as np >>> import scipy as sp >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]]) >>> sparse_matrix >>> sparse_matrix.toarray() array([[0, 0, 3], [4, 0, 0]], dtype=int64) >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz') >>> sparse_matrix >>> sparse_matrix.toarray() array([[0, 0, 3], [4, 0, 0]], dtype=int64)",
925 "type": "function",
926 "file_path": "scipy\\scipy\\sparse\\_matrix_io.py",
927 "ast_data": "FunctionDef name:save_npz arg:file arg:matrix arg:compressed arguments arg arg arg Assign If Compare Call If Compare Call If Compare Call Assign Raise Call Call Call If Call Call If Call Call"
928 },
929 {
930 "library": "matplotlib",
931 "name": "__init__",
932 "source_code": "@_docstring.interpd\ndef __init__(self, xy, width, height, *, angle=0.0, theta1=0.0, theta2=360.0, **kwargs):\n fill = kwargs.setdefault('fill', False)\n if fill:\n raise ValueError('Arc objects cannot be filled')\n super().__init__(xy, width, height, angle=angle, **kwargs)\n self.theta1 = theta1\n self.theta2 = theta2\n self._theta1, self._theta2, self._stretched_width, self._stretched_height = self._theta_stretch()\n self._path = Path.arc(self._theta1, self._theta2)",
933 "docstring": "Parameters ---------- xy : (float, float) The center of the ellipse. width : float The length of the horizontal axis. height : float The length of the vertical axis. angle : float Rotation of the ellipse in degrees (counterclockwise). theta1, theta2 : float, default: 0, 360 Starting and ending angles of the arc in degrees. These values are relative to *angle*, e.g. if *angle* = 45 and *theta1* = 90 the absolute starting angle is 135. Default *theta1* = 0, *theta2* = 360, i.e. a complete ellipse. The arc is drawn in the counterclockwise direction. Angles greater than or equal to 360, or smaller than 0, are represented by an equivalent angle in the range [0, 360), by taking the input value mod 360. Other Parameters ---------------- **kwargs : properties Most properties are supported as keyword arguments, except *fill* and *facecolor* because filling is not supported. %(Patch:kwdoc)s",
934 "type": "method",
935 "file_path": "matplotlib\\lib\\matplotlib\\patches.py",
936 "ast_data": "FunctionDef name:__init__ arg:self arg:xy arg:width arg:height arguments arg arg arg arg arg arg arg arg Assign Call If Raise Call Call Call Assign Assign Assign Call Assign Call"
937 },
938 {
939 "library": "pandas",
940 "name": "_extended_gcd",
941 "source_code": "def _extended_gcd(self, a: int, b: int) -> tuple[int, int, int]:\n s, old_s = (0, 1)\n t, old_t = (1, 0)\n r, old_r = (b, a)\n while r:\n quotient = old_r // r\n old_r, r = (r, old_r - quotient * r)\n old_s, s = (s, old_s - quotient * s)\n old_t, t = (t, old_t - quotient * t)\n return (old_r, old_s, old_t)",
942 "docstring": "Extended Euclidean algorithms to solve Bezout's identity: a*x + b*y = gcd(x, y) Finds one particular solution for x, y: s, t Returns: gcd, s, t",
943 "type": "method",
944 "file_path": "pandas\\pandas\\core\\indexes\\range.py",
945 "ast_data": "FunctionDef name:_extended_gcd arg:self arg:a arg:b arguments arg arg arg Assign Assign Assign While Assign Assign Assign Assign Return return:yes"
946 },
947 {
948 "library": "django",
949 "name": "get_form_class",
950 "source_code": "def get_form_class(self):\n return self.form_class",
951 "docstring": "Return the form class to use.",
952 "type": "method",
953 "file_path": "django\\django\\views\\generic\\edit.py",
954 "ast_data": "FunctionDef name:get_form_class arg:self arguments arg Return return:yes"
955 },
956 {
957 "library": "scikit-learn",
958 "name": "predict",
959 "source_code": "def predict(self, X):\n raw_predictions = self.decision_function(X)\n if raw_predictions.ndim == 1:\n encoded_classes = (raw_predictions >= 0).astype(int)\n else:\n encoded_classes = np.argmax(raw_predictions, axis=1)\n return self.classes_[encoded_classes]",
960 "docstring": "Predict class for X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``. Returns ------- y : ndarray of shape (n_samples,) The predicted values.",
961 "type": "method",
962 "file_path": "scikit-learn\\sklearn\\ensemble\\_gb.py",
963 "ast_data": "FunctionDef name:predict arg:self arg:X arguments arg arg Assign Call If Compare Assign Call Compare Assign Call Return return:yes"
964 },
965 {
966 "library": "scikit-learn",
967 "name": "_is_deprecated",
968 "source_code": "def _is_deprecated(func):\n closures = getattr(func, '__closure__', [])\n if closures is None:\n closures = []\n is_deprecated = 'deprecated' in ''.join([c.cell_contents for c in closures if isinstance(c.cell_contents, str)])\n return is_deprecated",
969 "docstring": "Helper to check if func is wrapped by our deprecated decorator",
970 "type": "function",
971 "file_path": "scikit-learn\\sklearn\\utils\\deprecation.py",
972 "ast_data": "FunctionDef name:_is_deprecated arg:func arguments arg Assign Call If Compare Assign Assign Compare Call Call Return return:yes"
973 },
974 {
975 "library": "pytorch",
976 "name": "setup_context",
977 "source_code": "@staticmethod\ndef setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> Any:\n raise NotImplementedError('setup_context is not implemented.')",
978 "docstring": "There are two ways to define the forward pass of an autograd.Function. Either: 1. Override forward with the signature `torch.autograd.Function.forwardextending-autograd` for more details.",
979 "type": "method",
980 "file_path": "pytorch\\torch\\autograd\\function.py",
981 "ast_data": "FunctionDef name:setup_context arg:ctx arg:inputs arg:output arguments arg arg arg Raise Call"
982 },
983 {
984 "library": "scikit-learn",
985 "name": "predict_proba",
986 "source_code": "@available_if(_final_estimator_has('predict_proba'))\ndef predict_proba(self, X, **params):\n with _raise_or_warn_if_not_fitted(self):\n Xt = X\n if not _routing_enabled():\n for _, name, transform in self._iter(with_final=False):\n Xt = transform.transform(Xt)\n return self.steps[-1][1].predict_proba(Xt, **params)\n routed_params = process_routing(self, 'predict_proba', **params)\n for _, name, transform in self._iter(with_final=False):\n Xt = transform.transform(Xt, **routed_params[name].transform)\n return self.steps[-1][1].predict_proba(Xt, **routed_params[self.steps[-1][0]].predict_proba)",
987 "docstring": "Transform the data, and apply with the final estimator. Call of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls method. Only valid if the final estimator implements . Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. **params : dict of str -> object - If (default): Parameters to the called at the end of all transformations in the pipeline. - If : Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them. .. versionadded:: 0.20 .. versionchanged:: 1.4 Parameters are now passed to the `enable_metadata_routing=TrueMetadata Routing User Guide predict_proba` on the final estimator.",
988 "type": "method",
989 "file_path": "scikit-learn\\sklearn\\pipeline.py",
990 "ast_data": "FunctionDef name:predict_proba arg:self arg:X arguments arg arg arg With Call Assign If Call For Call Assign Call Return return:yes Call Assign Call For Call Assign Call Return return:yes Call Call Call"
991 },
992 {
993 "library": "tensorflow",
994 "name": "update_state",
995 "source_code": "def update_state(self, y_true, y_pred, sample_weight=None):\n deps = []\n if not self._built:\n self._build(tensor_shape.TensorShape(y_pred.shape))\n if self.multi_label or self.label_weights is not None:\n shapes = [(y_true, ('N', 'L'))]\n if self.multi_label:\n shapes.extend([(self.true_positives, ('T', 'L')), (self.true_negatives, ('T', 'L')), (self.false_positives, ('T', 'L')), (self.false_negatives, ('T', 'L'))])\n if self.label_weights is not None:\n shapes.append((self.label_weights, ('L',)))\n deps = [check_ops.assert_shapes(shapes, message='Number of labels is not consistent.')]\n label_weights = None if self.multi_label else self.label_weights\n if self._from_logits:\n y_pred = activations.sigmoid(y_pred)\n with ops.control_dependencies(deps):\n return metrics_utils.update_confusion_matrix_variables({metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: self.true_negatives, metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives, metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives}, y_true, y_pred, self._thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, sample_weight=sample_weight, multi_label=self.multi_label, label_weights=label_weights)",
996 "docstring": "Accumulates confusion matrix statistics. Args: y_true: The ground truth values. y_pred: The predicted values. sample_weight: Optional weighting of each example. Defaults to 1. Can be a whose rank is either 0, or the same rank as , and must be broadcastable to . Returns: Update op.",
997 "type": "method",
998 "file_path": "tensorflow\\tensorflow\\python\\keras\\metrics.py",
999 "ast_data": "FunctionDef name:update_state arg:self arg:y_true arg:y_pred arg:sample_weight arguments arg arg arg arg Assign If Call Call If BoolOp Compare Assign If Call If Compare Call Assign Call Assign If Assign Call With Call Return return:yes Call"
1000 },
1001 {
1002 "library": "pytorch",
1003 "name": "_transform_prepacked_op",
1004 "source_code": "def _transform_prepacked_op(gm: torch.fx.GraphModule, node: torch.fx.Node):\n assert isinstance(node.target, torch._ops.OpOverload)\n opname, args = (node.target._opname, node.args)\n op_f = None\n if opname == 'conv2d_clamp_run':\n op_f = torch.ops.aten.conv2d\n elif opname == 'linear_clamp_run':\n op_f = torch.ops.aten.linear\n else:\n raise RuntimeError(f'Invalid operator {opname}')\n assert isinstance(args[1], torch.fx.Node)\n so = get_script_object(gm, args[1])\n func_args = []\n func_args += [args[0]]\n func_args += so.unpack()[:2]\n if opname == 'conv2d_clamp_run':\n func_args += torch.ops.prepacked.unpack_prepacked_sizes_conv2d(so)[2:]\n op_res_node = gm.graph.call_function(op_f, tuple(func_args))\n return op_res_node",
1005 "docstring": "Transformation for functions under prepacked namespace, where they share the same handling logic that [...]OpContext contains all parameters.",
1006 "type": "function",
1007 "file_path": "pytorch\\torch\\_export\\passes\\replace_quantized_ops_with_standard_ops_pass.py",
1008 "ast_data": "FunctionDef name:_transform_prepacked_op arg:gm arg:node arguments arg arg Call Assign Assign If Compare Assign If Compare Assign Raise Call Call Assign Call Assign Call If Compare Call Assign Call Call Return return:yes"
1009 },
1010 {
1011 "library": "tensorflow",
1012 "name": "get_value",
1013 "source_code": "@doc_controls.do_not_generate_docs\ndef get_value(x):\n if not tensor_util.is_tf_type(x):\n return x\n if context.executing_eagerly() or isinstance(x, ops.EagerTensor):\n return x.numpy()\n if not getattr(x, '_in_graph_mode', True):\n with context.eager_mode():\n return x.numpy()\n if ops.executing_eagerly_outside_functions():\n with ops.init_scope():\n return x.numpy()\n with x.graph.as_default():\n return x.eval(session=get_session((x,)))",
1014 "docstring": "Returns the value of a variable. is the complement of , and provides a generic interface for reading from variables while abstracting away the differences between TensorFlow 1.x and 2.x semantics. {snippet} Args: x: input variable. Returns: A Numpy array.",
1015 "type": "function",
1016 "file_path": "tensorflow\\tensorflow\\python\\keras\\backend.py",
1017 "ast_data": "FunctionDef name:get_value arg:x arguments arg If Call Return return:yes If BoolOp Call Call Return return:yes Call If Call With Call Return return:yes Call If Call With Call Return return:yes Call With Call Return return:yes Call Call"
1018 },
1019 {
1020 "library": "tensorflow",
1021 "name": "_copy_tensors_to_device",
1022 "source_code": "def _copy_tensors_to_device(self, partitioned_tensors: Dict[str, Any]) -> Any:\n partitioned_device_tensors = {}\n for table_name in partitioned_tensors:\n partitioned_tensor = partitioned_tensors[table_name][0]\n row_pointers_unpadded_size = partitioned_tensors[table_name][1]\n ids_unpadded_size = partitioned_tensors[table_name][2]\n row_pointers, sorted_sample_ids, sorted_token_ids, sorted_gains = xla_ops.tpu_copy_with_dynamic_shape([partitioned_tensor.row_pointers, partitioned_tensor.sorted_sample_ids, partitioned_tensor.sorted_token_ids, partitioned_tensor.sorted_gains], [row_pointers_unpadded_size, ids_unpadded_size, ids_unpadded_size, ids_unpadded_size])\n row_pointers, sorted_sample_ids, sorted_token_ids, sorted_gains = xla_ops.tpu_annotate_tensors_with_dynamic_shape([row_pointers, sorted_sample_ids, sorted_token_ids, sorted_gains])\n partitioned_device_tensors[table_name] = PartitionedCsrFormatTensor(row_pointers=row_pointers, sorted_sample_ids=sorted_sample_ids, sorted_token_ids=sorted_token_ids, sorted_gains=sorted_gains, sample_count=partitioned_tensor.sample_count, num_minibatches_per_physical_sparse_core=partitioned_tensor.num_minibatches_per_physical_sparse_core)\n return partitioned_device_tensors",
1023 "docstring": "Copy tensors to device.",
1024 "type": "method",
1025 "file_path": "tensorflow\\tensorflow\\python\\tpu\\tpu_embedding_v3.py",
1026 "ast_data": "FunctionDef name:_copy_tensors_to_device arg:self arg:partitioned_tensors arguments arg arg Assign For Assign Assign Assign Assign Call Assign Call Assign Call Return return:yes"
1027 },
1028 {
1029 "library": "pytorch",
1030 "name": "load_state_dict_from_url",
1031 "source_code": "def load_state_dict_from_url(url: str, model_dir: Optional[str]=None, map_location: MAP_LOCATION=None, progress: bool=True, check_hash: bool=False, file_name: Optional[str]=None, weights_only: bool=False) -> dict[str, Any]:\n if os.getenv('TORCH_MODEL_ZOO'):\n warnings.warn('TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead')\n if model_dir is None:\n hub_dir = get_dir()\n model_dir = os.path.join(hub_dir, 'checkpoints')\n os.makedirs(model_dir, exist_ok=True)\n parts = urlparse(url)\n filename = os.path.basename(parts.path)\n if file_name is not None:\n filename = file_name\n cached_file = os.path.join(model_dir, filename)\n if not os.path.exists(cached_file):\n sys.stdout.write(f'Downloading: \"{url}\" to {cached_file}\\n')\n hash_prefix = None\n if check_hash:\n r = HASH_REGEX.search(filename)\n hash_prefix = r.group(1) if r else None\n download_url_to_file(url, cached_file, hash_prefix, progress=progress)\n if _is_legacy_zip_format(cached_file):\n return _legacy_zip_load(cached_file, model_dir, map_location, weights_only)\n return torch.load(cached_file, map_location=map_location, weights_only=weights_only)",
1032 "docstring": "Loads the Torch serialized object at the given URL. If downloaded file is a zip file, it will be automatically decompressed. If the object is already present in , it's deserialized and returned. The default value of `~torch.hub.get_dir``~torch.load` for more details. Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_HUB) >>> state_dict = torch.hub.load_state_dict_from_url( ... \" ... )",
1033 "type": "function",
1034 "file_path": "pytorch\\torch\\hub.py",
1035 "ast_data": "FunctionDef name:load_state_dict_from_url arg:url arg:model_dir arg:map_location arg:progress arg:check_hash arg:file_name arg:weights_only arguments arg arg arg arg arg arg arg If Call Call If Compare Assign Call Assign Call Call Assign Call Assign Call If Compare Assign Assign Call If Call Call Assign If Assign Call Assign Call Call If Call Return return:yes Call Return return:yes Call"
1036 },
1037 {
1038 "library": "django",
1039 "name": "many_to_many",
1040 "source_code": "@cached_property\ndef many_to_many(self):\n return make_immutable_fields_list('many_to_many', (f for f in self._get_fields(reverse=False) if f.is_relation and f.many_to_many))",
1041 "docstring": "Return a list of all many to many fields on the model and its parents. Private API intended only to be used by Django itself; get_fields() combined with filtering of field properties is the public API for obtaining this list.",
1042 "type": "method",
1043 "file_path": "django\\django\\db\\models\\options.py",
1044 "ast_data": "FunctionDef name:many_to_many arg:self arguments arg Return return:yes Call Call BoolOp"
1045 },
1046 {
1047 "library": "tensorflow",
1048 "name": "_get",
1049 "source_code": "def _get(self):\n with distribute_lib.enter_or_assert_strategy(self._distribute_strategy):\n return super(SyncOnReadVariable, self)._get()",
1050 "docstring": "Returns the value of SyncOnReadVariable based on surrounding context. If called under a non-default replica-context, returns the corresponding variable on that replica. If called under default replica-context or cross-replica context, returns the synced value.",
1051 "type": "method",
1052 "file_path": "tensorflow\\tensorflow\\python\\distribute\\values.py",
1053 "ast_data": "FunctionDef name:_get arg:self arguments arg With Call Return return:yes Call Call"
1054 },
1055 {
1056 "library": "pandas",
1057 "name": "any_not_none",
1058 "source_code": "def any_not_none(*args) -> bool:\n return any((arg is not None for arg in args))",
1059 "docstring": "Returns a boolean indicating if any argument is not None.",
1060 "type": "function",
1061 "file_path": "pandas\\pandas\\core\\common.py",
1062 "ast_data": "FunctionDef name:any_not_none arguments arg Return return:yes Call Compare"
1063 },
1064 {
1065 "library": "tensorflow",
1066 "name": "_ExtractInputShapes",
1067 "source_code": "def _ExtractInputShapes(inputs):\n if context.executing_eagerly():\n return array_ops.shape_n(inputs)\n sizes = []\n fully_known = True\n for x in inputs:\n input_shape = array_ops.shape(x)\n if not isinstance(input_shape, tensor.Tensor) or input_shape.op.type != 'Const':\n fully_known = False\n break\n sizes.append(input_shape)\n if fully_known:\n return sizes\n else:\n return array_ops.shape_n(inputs)",
1068 "docstring": "Extract the shapes of a set of input tensors.",
1069 "type": "function",
1070 "file_path": "tensorflow\\tensorflow\\python\\ops\\array_grad.py",
1071 "ast_data": "FunctionDef name:_ExtractInputShapes arg:inputs arguments arg If Call Return return:yes Call Assign Assign For Assign Call If BoolOp Call Compare Assign Call If Return return:yes Return return:yes Call"
1072 },
1073 {
1074 "library": "scikit-learn",
1075 "name": "_validate_column_callables",
1076 "source_code": "def _validate_column_callables(self, X):\n all_columns = []\n transformer_to_input_indices = {}\n for name, _, columns in self.transformers:\n if callable(columns):\n columns = columns(X)\n all_columns.append(columns)\n transformer_to_input_indices[name] = _get_column_indices(X, columns)\n self._columns = all_columns\n self._transformer_to_input_indices = transformer_to_input_indices",
1077 "docstring": "Converts callable column specifications. This stores a dictionary of the form and calls the on if is a callable for a given transformer. The results are then stored in .",
1078 "type": "method",
1079 "file_path": "scikit-learn\\sklearn\\compose\\_column_transformer.py",
1080 "ast_data": "FunctionDef name:_validate_column_callables arg:self arg:X arguments arg arg Assign Assign For If Call Assign Call Call Assign Call Assign Assign"
1081 },
1082 {
1083 "library": "tensorflow",
1084 "name": "read_var",
1085 "source_code": "def read_var(self, replica_local_var):\n return array_ops.identity(replica_local_var)",
1086 "docstring": "Read the aggregate value of a replica-local variable.",
1087 "type": "method",
1088 "file_path": "tensorflow\\tensorflow\\python\\distribute\\one_device_strategy.py",
1089 "ast_data": "FunctionDef name:read_var arg:self arg:replica_local_var arguments arg arg Return return:yes Call"
1090 },
1091 {
1092 "library": "tensorflow",
1093 "name": "_add_op_node",
1094 "source_code": "def _add_op_node(op, func, input_dict):\n func.node_def.extend([_get_node_def(op)])\n node_def = func.node_def[-1]\n for i in range(len(node_def.input)):\n if not node_def.input[i].startswith('^'):\n assert node_def.input[i] in input_dict, '%s missing from %s' % (node_def.input[i], input_dict.items())\n node_def.input[i] = input_dict[node_def.input[i]]\n if op.op_def is not None and op.op_def.is_stateful:\n func.signature.is_stateful = True",
1095 "docstring": "Converts an op to a function def node and add it to .",
1096 "type": "function",
1097 "file_path": "tensorflow\\tensorflow\\python\\framework\\graph_to_function_def.py",
1098 "ast_data": "FunctionDef name:_add_op_node arg:op arg:func arg:input_dict arguments arg arg arg Call Call Assign For Call Call If Call Compare Call Assign If BoolOp Compare Assign"
1099 },
1100 {
1101 "library": "tensorflow",
1102 "name": "_get_weighted_mean_squared_error",
1103 "source_code": "def _get_weighted_mean_squared_error(self, quant_min, quant_max) -> tuple[float, float, float]:\n dequantized_hist_mids = self._get_dequantized_hist_mids_after_quantize(quant_min, quant_max)\n squared_error = (self._hist_mids - dequantized_hist_mids) ** 2\n weighted_error = np.sum(squared_error * self._hist_freq)\n return (weighted_error, quant_min, quant_max)",
1104 "docstring": "Gets mean squared error between hist_mids and dequantized hist_mids. Quantization converts the range of numbers from [quant_min, quant_max] to [0, 2^num_bits - 1]. Values less than quant_min are converted to 0, and values greater than quant_max are converted to 2^num_bits - 1. Args: quant_min: The minimum real value that can be represented by a quantized value. quant_max: The maximum real value that can be represented by a quantized value. Returns: (error, quant_min, quant_max): Tuple of weighted mean squared error. error = (hist_mids - dequantized_hist_mids)**2 * hist_freq",
1105 "type": "method",
1106 "file_path": "tensorflow\\tensorflow\\compiler\\mlir\\quantization\\tensorflow\\calibrator\\calibration_algorithm.py",
1107 "ast_data": "FunctionDef name:_get_weighted_mean_squared_error arg:self arg:quant_min arg:quant_max arguments arg arg arg Assign Call Assign Assign Call Return return:yes"
1108 },
1109 {
1110 "library": "matplotlib",
1111 "name": "register",
1112 "source_code": "def register(self, name):\n\n def wrapper(writer_cls):\n self._registered[name] = writer_cls\n return writer_cls\n return wrapper",
1113 "docstring": "Decorator for registering a class under a name. Example use:: @registry.register(name) class Foo: pass",
1114 "type": "method",
1115 "file_path": "matplotlib\\lib\\matplotlib\\animation.py",
1116 "ast_data": "FunctionDef name:register arg:self arg:name arguments arg arg FunctionDef name:wrapper arg:writer_cls arguments arg Assign Return return:yes Return return:yes"
1117 },
1118 {
1119 "library": "sphinx",
1120 "name": "set_application",
1121 "source_code": "def set_application(self, app: Sphinx) -> None:\n self._app = app\n self.config = app.config\n self.env = app.env",
1122 "docstring": "set_application will be called from Sphinx to set app and other instance variables :param sphinx.application.Sphinx app: Sphinx application object",
1123 "type": "method",
1124 "file_path": "sphinx\\sphinx\\parsers.py",
1125 "ast_data": "FunctionDef name:set_application arg:self arg:app arguments arg arg Assign Assign Assign"
1126 },
1127 {
1128 "library": "tensorflow",
1129 "name": "get_current_name_scope",
1130 "source_code": "@tf_export('get_current_name_scope', v1=[])\ndef get_current_name_scope() -> str:\n ctx = context.context()\n if ctx.executing_eagerly():\n return ctx.scope_name.rstrip('/')\n else:\n return get_default_graph().get_name_scope()",
1131 "docstring": "Returns current full name scope specified by s. For example, In other words, returns the op name prefix that will be prepended to, if an op is created at that place. Note that resets the name scope stack as shown below.",
1132 "type": "function",
1133 "file_path": "tensorflow\\tensorflow\\python\\framework\\ops.py",
1134 "ast_data": "FunctionDef name:get_current_name_scope arguments Assign Call If Call Return return:yes Call Return return:yes Call Call Call"
1135 },
1136 {
1137 "library": "numpy",
1138 "name": "get_library_dirs",
1139 "source_code": "def get_library_dirs(self):\n return self.library_dirs[:]",
1140 "docstring": "List of compiler library directories.",
1141 "type": "method",
1142 "file_path": "numpy\\numpy\\distutils\\fcompiler\\__init__.py",
1143 "ast_data": "FunctionDef name:get_library_dirs arg:self arguments arg Return return:yes"
1144 },
1145 {
1146 "library": "matplotlib",
1147 "name": "set_clim",
1148 "source_code": "def set_clim(self, vmin=None, vmax=None):\n self._colorizer.set_clim(vmin, vmax)",
1149 "docstring": "Set the norm limits for image scaling. Parameters ---------- vmin, vmax : float The limits. For scalar data, the limits may also be passed as a tuple (*vmin*, *vmax*) as a single positional argument. .. ACCEPTS: (vmin: float, vmax: float)",
1150 "type": "method",
1151 "file_path": "matplotlib\\lib\\matplotlib\\colorizer.py",
1152 "ast_data": "FunctionDef name:set_clim arg:self arg:vmin arg:vmax arguments arg arg arg Call"
1153 },
1154 {
1155 "library": "matplotlib",
1156 "name": "process_figure_for_rasterizing",
1157 "source_code": "def process_figure_for_rasterizing(fig, bbox_inches_restore, renderer, fixed_dpi=None):\n bbox_inches, restore_bbox = bbox_inches_restore\n restore_bbox()\n r = adjust_bbox(fig, bbox_inches, renderer, fixed_dpi)\n return (bbox_inches, r)",
1158 "docstring": "A function that needs to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi.",
1159 "type": "function",
1160 "file_path": "matplotlib\\lib\\matplotlib\\_tight_bbox.py",
1161 "ast_data": "FunctionDef name:process_figure_for_rasterizing arg:fig arg:bbox_inches_restore arg:renderer arg:fixed_dpi arguments arg arg arg arg Assign Call Assign Call Return return:yes"
1162 },
1163 {
1164 "library": "pytorch",
1165 "name": "add_dtype_config",
1166 "source_code": "def add_dtype_config(self, dtype_config: DTypeConfig) -> BackendPatternConfig:\n self.dtype_configs.append(dtype_config)\n return self",
1167 "docstring": "Add a set of supported data types passed as arguments to quantize ops in the reference model spec.",
1168 "type": "method",
1169 "file_path": "pytorch\\torch\\ao\\quantization\\backend_config\\backend_config.py",
1170 "ast_data": "FunctionDef name:add_dtype_config arg:self arg:dtype_config arguments arg arg Call Return return:yes"
1171 },
1172 {
1173 "library": "pytorch",
1174 "name": "summary",
1175 "source_code": "@no_type_check\ndef summary(self, top: int=20) -> None:\n op_diff: dict[str, float] = defaultdict(float)\n op_name, previous_allocated_memory = self.memories_allocated[0]\n for i in range(1, self._op_index):\n op_name, current_allocated_memory = self.memories_allocated[i]\n op_diff[op_name] = current_allocated_memory - previous_allocated_memory\n previous_allocated_memory = current_allocated_memory\n print('------------------------------------------------')\n print(f'The number of cuda retries are: {self._num_cuda_retries}')\n print(f'Top {top} ops that generates memory are:')\n for k, v in sorted(op_diff.items(), key=operator.itemgetter(1), reverse=True)[:top]:\n print(f'{k}: {v}MB')\n print('------------------------------------------------')",
1176 "docstring": "Print out the top operators that generate the most memories. The number of the top operators can be configured.",
1177 "type": "method",
1178 "file_path": "pytorch\\torch\\distributed\\_tools\\memory_tracker.py",
1179 "ast_data": "FunctionDef name:summary arg:self arg:top arguments arg arg Call Assign For Call Assign Assign Assign Call Call Call For Call Call Call Call Call"
1180 },
1181 {
1182 "library": "matplotlib",
1183 "name": "add",
1184 "source_code": "def add(self, a):\n if a not in self._axes:\n self._axes[a] = next(self._counter)",
1185 "docstring": "Add an Axes to the stack, ignoring it if already present.",
1186 "type": "method",
1187 "file_path": "matplotlib\\lib\\matplotlib\\figure.py",
1188 "ast_data": "FunctionDef name:add arg:self arg:a arguments arg arg If Compare Assign Call"
1189 },
1190 {
1191 "library": "pandas",
1192 "name": "_get_data_and_dtype_name",
1193 "source_code": "def _get_data_and_dtype_name(data: ArrayLike):\n if isinstance(data, Categorical):\n data = data.codes\n if isinstance(data.dtype, DatetimeTZDtype):\n dtype_name = f'datetime64[{data.dtype.unit}]'\n else:\n dtype_name = data.dtype.name\n if data.dtype.kind in 'mM':\n data = np.asarray(data.view('i8'))\n elif isinstance(data, PeriodIndex):\n data = data.asi8\n data = np.asarray(data)\n return (data, dtype_name)",
1194 "docstring": "Convert the passed data into a storable form and a dtype string.",
1195 "type": "function",
1196 "file_path": "pandas\\pandas\\io\\pytables.py",
1197 "ast_data": "FunctionDef name:_get_data_and_dtype_name arg:data arguments arg If Call Assign If Call Assign Assign If Compare Assign Call Call If Call Assign Assign Call Return return:yes"
1198 },
1199 {
1200 "library": "tensorflow",
