project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
matsu0228/nlp-jp | text_analysis.py | UsesDictionary.get_occurrences | get_occurrences | Return number of docs the word occurs in, once `accumulate` has been called. | [
"Return",
"number",
"of",
"docs",
"the",
"word",
"occurs",
"in,",
"once",
"`accumulate`",
"has",
"been",
"called."
] | def get_occurrences(self, word):
try:
word_id = self.token2id[word]
except KeyError:
word_id = word
return self._get_occurrences(self.id2contiguous[word_id]) | ['def', 'get_occurrences(self,', 'word):', 'try:', 'word_id', '=', 'self.token2id[word]', 'except', 'KeyError:', 'word_id', '=', 'word', 'return', 'self._get_occurrences(self.id2contiguous[word_id])'] | 786,259 |
opendilab/DI-star | host_remote_agent.py | VsAgent.create_game | create_game | Create a game for the agents to join. | [
"Create",
"a",
"game",
"for",
"the",
"agents",
"to",
"join."
] | def create_game(self, map_name):
self._reconnect()
map_inst = maps.get(map_name)
map_data = map_inst.data(self._run_config)
if map_name not in self._saved_maps:
for controller in self._controllers:
controller.save_map(map_inst.path, map_data)
self._saved_maps.add(map_name)
... | ['def', 'create_game(self,', 'map_name):', 'self._reconnect()', 'map_inst', '=', 'maps.get(map_name)', 'map_data', '=', 'map_inst.data(self._run_config)', 'if', 'map_name', 'not', 'in', 'self._saved_maps:', 'for', 'controller', 'in', 'self._controllers:', 'controller.save_map(map_inst.path,', 'map_data)', 'self._saved_... | 184,618 |
liuzuxin/MPC_template-model_predictive_control_for__ | control.py | ControlledVehicle.follow_road | follow_road | At the end of a lane, automatically switch to a next one. | [
"At",
"the",
"end",
"of",
"a",
"lane,",
"automatically",
"switch",
"to",
"a",
"next",
"one."
] | def follow_road(self):
if self.road.network.get_lane(self.target_lane_index).after_end(self.position):
self.target_lane_index = self.road.network.next_lane(self.target_lane_index, route=self.route, position=self.position, np_random=self.road.np_random) | ['def', 'follow_road(self):', 'if', 'self.road.network.get_lane(self.target_lane_index).after_end(self.position):', 'self.target_lane_index', '=', 'self.road.network.next_lane(self.target_lane_index,', 'route=self.route,', 'position=self.position,', 'np_random=self.road.np_random)'] | 656,452 |
eora-ai/torchok | hrnet.py | HighResolutionNet.forward_features | forward_features | Forward backbone features and input tensor. | [
"Forward",
"backbone",
"features",
"and",
"input",
"tensor."
] | def forward_features(self, x: Tensor) -> List[Tensor]:
return [x] + self.forward(x) | ['def', 'forward_features(self,', 'x:', 'Tensor)', '->', 'List[Tensor]:', 'return', '[x]', '+', 'self.forward(x)'] | 903,174 |
TonyLianLong/VAI-ReinforcementLearning | namescope.py | NameScope.model_dir | model_dir | Path to the directory containing the model XML file. | [
"Path",
"to",
"the",
"directory",
"containing",
"the",
"model",
"XML",
"file."
] | def model_dir(self):
return self._model_dir | ['def', 'model_dir(self):', 'return', 'self._model_dir'] | 440,027 |
devashish-patel/webcam-motion-detector | dir2.py | get_real_method | get_real_method | Like getattr, but with a few extra sanity checks: - If obj is a class, ignore its methods - Check if obj is a proxy that claims to have all attributes - Catch attribute access failing with any exception - Check that the attribute is a callable object Returns the method or None. | [
"Like",
"getattr,",
"but",
"with",
"a",
"few",
"extra",
"sanity",
"checks:",
"-",
"If",
"obj",
"is",
"a",
"class,",
"ignore",
"its",
"methods",
"-",
"Check",
"if",
"obj",
"is",
"a",
"proxy",
"that",
"claims",
"to",
"have",
"all",
"attributes",
"-",
"Ca... | def get_real_method(obj, name):
if inspect.isclass(obj):
return None
try:
canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
except Exception:
return None
if canary is not None:
return None
try:
m = getattr(obj, name, None)
except Exce... | ['def', 'get_real_method(obj,', 'name):', 'if', 'inspect.isclass(obj):', 'return', 'None', 'try:', 'canary', '=', 'getattr(obj,', "'_ipython_canary_method_should_not_exist_',", 'None)', 'except', 'Exception:', 'return', 'None', 'if', 'canary', 'is', 'not', 'None:', 'return', 'None', 'try:', 'm', '=', 'getattr(obj,', 'n... | 979,388 |
benedekrozemberczki/karateclub | community_detection_overlapping_test.py | test_egonet_splitter | test_egonet_splitter | Test the Ego Net splitter procedure. | [
"Test",
"the",
"Ego",
"Net",
"splitter",
"procedure."
] | def test_egonet_splitter():
graph = nx.newman_watts_strogatz_graph(100, 5, 0.3)
model = EgoNetSplitter()
model.fit(graph)
memberships = model.get_memberships()
indices = [k for (k, v) in memberships.items()].sort()
nodes = [node for node in graph.nodes()].sort()
assert graph.number_of_nodes(... | ['def', 'test_egonet_splitter():', 'graph', '=', 'nx.newman_watts_strogatz_graph(100,', '5,', '0.3)', 'model', '=', 'EgoNetSplitter()', 'model.fit(graph)', 'memberships', '=', 'model.get_memberships()', 'indices', '=', '[k', 'for', '(k,', 'v)', 'in', 'memberships.items()].sort()', 'nodes', '=', '[node', 'for', 'node', ... | 247,402 |
crestonbunch/tbcnn | train_loop.py | train_net | train_net | Train network using the given training and test data. | [
"Train",
"network",
"using",
"the",
"given",
"training",
"and",
"test",
"data."
] | def train_net(training, test, size=512, epochs=400, batch_size=4, logging_interval=5, run_name=None):
if run_name is None:
run_name = datetime.now().strftime('%Y-%m-%d_%H:%M')
(training_images, training_labels) = training
(test_images, test_labels) = test
border = (test_images.shape[1] - size) /... | ['def', 'train_net(training,', 'test,', 'size=512,', 'epochs=400,', 'batch_size=4,', 'logging_interval=5,', 'run_name=None):', 'if', 'run_name', 'is', 'None:', 'run_name', '=', "datetime.now().strftime('%Y-%m-%d_%H:%M')", '(training_images,', 'training_labels)', '=', 'training', '(test_images,', 'test_labels)', '=', 't... | 365,518 |
AgnostiqHQ/covalent | devices_base.py | _PennylaneQiskitDevice.post_process | post_process | Obtain metadata; make blocking API call to Qiskit Runtime. | [
"Obtain",
"metadata;",
"make",
"blocking",
"API",
"call",
"to",
"Qiskit",
"Runtime."
] | def post_process(self, *args) -> Tuple[Any, List[dict]]:
raise NotImplementedError | ['def', 'post_process(self,', '*args)', '->', 'Tuple[Any,', 'List[dict]]:', 'raise', 'NotImplementedError'] | 489,405 |
googleapis/python-aiplatform | base_execution.py | BaseExecutionSchema.list | list | List all the Execution resources with a particular schema. | [
"List",
"all",
"the",
"Execution",
"resources",
"with",
"a",
"particular",
"schema."
] | def list(cls, filter: Optional[str]=None, metadata_store_id: str='default', project: Optional[str]=None, location: Optional[str]=None, credentials: Optional[auth_credentials.Credentials]=None, order_by: Optional[str]=None) -> List['BaseExecutionSchema']:
schema_filter = f'schema_title="{cls.schema_title}"'
if f... | ['def', 'list(cls,', 'filter:', 'Optional[str]=None,', 'metadata_store_id:', "str='default',", 'project:', 'Optional[str]=None,', 'location:', 'Optional[str]=None,', 'credentials:', 'Optional[auth_credentials.Credentials]=None,', 'order_by:', 'Optional[str]=None)', '->', "List['BaseExecutionSchema']:", 'schema_filter',... | 810,076 |
angeladai/ScanComplete | model.py | shortcut | shortcut | Creates a shortcut (either a skip connection or a 1x1x1 convolution). | [
"Creates",
"a",
"shortcut",
"(either",
"a",
"skip",
"connection",
"or",
"a",
"1x1x1",
"convolution)."
] | def shortcut(inputs, num_input, num_output, stride):
if num_input == num_output:
return inputs
else:
return slim.conv3d(inputs, num_outputs=num_output, kernel_size=[1, 1, 1], stride=[stride, stride, stride], activation_fn=None) | ['def', 'shortcut(inputs,', 'num_input,', 'num_output,', 'stride):', 'if', 'num_input', '==', 'num_output:', 'return', 'inputs', 'else:', 'return', 'slim.conv3d(inputs,', 'num_outputs=num_output,', 'kernel_size=[1,', '1,', '1],', 'stride=[stride,', 'stride,', 'stride],', 'activation_fn=None)'] | 845,850 |
jezdez/django-staticfiles | utils.py | get_files | get_files | Recursively walk the storage directories yielding the paths of all files that should be copied. | [
"Recursively",
"walk",
"the",
"storage",
"directories",
"yielding",
"the",
"paths",
"of",
"all",
"files",
"that",
"should",
"be",
"copied."
] | def get_files(storage, ignore_patterns=None, location=''):
if ignore_patterns is None:
ignore_patterns = []
ignore_filtered = get_filtered_patterns(storage, ignore_patterns, location)
(directories, files) = storage.listdir(location)
for fn in files:
if matches_patterns(fn, ignore_filtere... | ['def', 'get_files(storage,', 'ignore_patterns=None,', "location=''):", 'if', 'ignore_patterns', 'is', 'None:', 'ignore_patterns', '=', '[]', 'ignore_filtered', '=', 'get_filtered_patterns(storage,', 'ignore_patterns,', 'location)', '(directories,', 'files)', '=', 'storage.listdir(location)', 'for', 'fn', 'in', 'files:... | 164,857 |
flow-project/flow | base.py | BaseKernelNetwork.max_speed | max_speed | Return the maximum achievable speed on any edge in the network. | [
"Return",
"the",
"maximum",
"achievable",
"speed",
"on",
"any",
"edge",
"in",
"the",
"network."
] | def max_speed(self):
raise NotImplementedError | ['def', 'max_speed(self):', 'raise', 'NotImplementedError'] | 211,582 |
dnouri/gdbn | dbn.py | DBN.gradients | gradients | Lazily generate (negative) gradients for the weights and biases given the result of fprop (fpropState) and the result of bprop (errSignals). | [
"Lazily",
"generate",
"(negative)",
"gradients",
"for",
"the",
"weights",
"and",
"biases",
"given",
"the",
"result",
"of",
"fprop",
"(fpropState)",
"and",
"the",
"result",
"of",
"bprop",
"(errSignals)."
] | def gradients(self, fpropState, errSignals):
assert len(fpropState) == len(self.weights) + 1
assert len(errSignals) == len(self.weights) == len(self.biases)
for i in range(len(self.weights)):
yield (gnp.dot(fpropState[i].T, errSignals[i]), errSignals[i].sum(axis=0)) | ['def', 'gradients(self,', 'fpropState,', 'errSignals):', 'assert', 'len(fpropState)', '==', 'len(self.weights)', '+', '1', 'assert', 'len(errSignals)', '==', 'len(self.weights)', '==', 'len(self.biases)', 'for', 'i', 'in', 'range(len(self.weights)):', 'yield', '(gnp.dot(fpropState[i].T,', 'errSignals[i]),', 'errSignal... | 567,706 |
hideyukiinada/transfer-learning | retrain.py | save_graph_to_file | save_graph_to_file | Saves an graph to file, creating a valid quantized one if necessary. | [
"Saves",
"an",
"graph",
"to",
"file,",
"creating",
"a",
"valid",
"quantized",
"one",
"if",
"necessary."
] | def save_graph_to_file(graph_file_name, module_spec, class_count):
(sess, _, _, _, _, _) = build_eval_session(module_spec, class_count)
graph = sess.graph
output_graph_def = tf.graph_util.convert_variables_to_constants(sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with tf.gfile.FastGFile(graph_... | ['def', 'save_graph_to_file(graph_file_name,', 'module_spec,', 'class_count):', '(sess,', '_,', '_,', '_,', '_,', '_)', '=', 'build_eval_session(module_spec,', 'class_count)', 'graph', '=', 'sess.graph', 'output_graph_def', '=', 'tf.graph_util.convert_variables_to_constants(sess,', 'graph.as_graph_def(),', '[FLAGS.fina... | 929,078 |
tensorly/quantum | serializer_test.py | SerializerTest.test_deserialize_projectorsum_wrong_type | test_deserialize_projectorsum_wrong_type | Attempt to deserialize invalid object types. | [
"Attempt",
"to",
"deserialize",
"invalid",
"object",
"types."
] | def test_deserialize_projectorsum_wrong_type(self, inp):
with self.assertRaises(TypeError):
serializer.deserialize_projectorsum(inp) | ['def', 'test_deserialize_projectorsum_wrong_type(self,', 'inp):', 'with', 'self.assertRaises(TypeError):', 'serializer.deserialize_projectorsum(inp)'] | 835,010 |
googleinterns/wss | dataset_utils.py | download_and_uncompress_tarball | download_and_uncompress_tarball | Downloads the `tarball_url` and uncompresses it locally. | [
"Downloads",
"the",
"`tarball_url`",
"and",
"uncompresses",
"it",
"locally."
] | def download_and_uncompress_tarball(tarball_url, dataset_dir):
filepath = download_url(tarball_url, dataset_dir)
tarfile.open(filepath, 'r:gz').extractall(dataset_dir) | ['def', 'download_and_uncompress_tarball(tarball_url,', 'dataset_dir):', 'filepath', '=', 'download_url(tarball_url,', 'dataset_dir)', 'tarfile.open(filepath,', "'r:gz').extractall(dataset_dir)"] | 960,829 |
ishwnews/MASS | dictionary.py | Dictionary.check_valid | check_valid | Check that the dictionary is valid. | [
"Check",
"that",
"the",
"dictionary",
"is",
"valid."
] | def check_valid(self):
assert self.bos_index == 0
assert self.eos_index == 1
assert self.pad_index == 2
assert self.unk_index == 3
assert all((self.id2word[4 + i] == SPECIAL_WORD % i for i in range(SPECIAL_WORDS)))
assert len(self.id2word) == len(self.word2id) == len(self.counts)
assert set(... | ['def', 'check_valid(self):', 'assert', 'self.bos_index', '==', '0', 'assert', 'self.eos_index', '==', '1', 'assert', 'self.pad_index', '==', '2', 'assert', 'self.unk_index', '==', '3', 'assert', 'all((self.id2word[4', '+', 'i]', '==', 'SPECIAL_WORD', '%', 'i', 'for', 'i', 'in', 'range(SPECIAL_WORDS)))', 'assert', 'len... | 646,041 |
ziqi-jin/finetune-anything | predictor.py | SamPredictor.get_image_embedding | get_image_embedding | Returns the image embeddings for the currently set image, with shape 1xCxHxW, where C is the embedding dimension and (H,W) are the embedding spatial dimension of SAM (typically C=256, H=W=64). | [
"Returns",
"the",
"image",
"embeddings",
"for",
"the",
"currently",
"set",
"image,",
"with",
"shape",
"1xCxHxW,",
"where",
"C",
"is",
"the",
"embedding",
"dimension",
"and",
"(H,W)",
"are",
"the",
"embedding",
"spatial",
"dimension",
"of",
"SAM",
"(typically",
... | def get_image_embedding(self) -> torch.Tensor:
if not self.is_image_set:
raise RuntimeError('An image must be set with .set_image(...) to generate an embedding.')
assert self.features is not None, 'Features must exist if an image has been set.'
return self.features | ['def', 'get_image_embedding(self)', '->', 'torch.Tensor:', 'if', 'not', 'self.is_image_set:', 'raise', "RuntimeError('An", 'image', 'must', 'be', 'set', 'with', '.set_image(...)', 'to', 'generate', 'an', "embedding.')", 'assert', 'self.features', 'is', 'not', 'None,', "'Features", 'must', 'exist', 'if', 'an', 'image',... | 584,481 |
aalgirdas/Artificial-Intelligence-Course | romania_problem.py | display_current | display_current | This function marks the currently exploring node (red) on the map. | [
"This",
"function",
"marks",
"the",
"currently",
"exploring",
"node",
"(red)",
"on",
"the",
"map."
] | def display_current(node):
global city_map, city_coord
city = node.state
city_map.itemconfig(city_coord[city], fill='red') | ['def', 'display_current(node):', 'global', 'city_map,', 'city_coord', 'city', '=', 'node.state', 'city_map.itemconfig(city_coord[city],', "fill='red')"] | 79,749 |
tomcatmanager/tomcatmanager | interactive_tomcat_manager.py | InteractiveTomcatManager.help_serverinfo | help_serverinfo | Show help for the 'serverinfo' command. | [
"Show",
"help",
"for",
"the",
"'serverinfo'",
"command."
] | def help_serverinfo(self):
self.show_help_from(self.serverinfo_parser) | ['def', 'help_serverinfo(self):', 'self.show_help_from(self.serverinfo_parser)'] | 355,568 |
caiiiac/Machine-Learning-with-Python | patches.py | FancyArrowPatch.get_mutation_scale | get_mutation_scale | Return the mutation scale. | [
"Return",
"the",
"mutation",
"scale."
] | def get_mutation_scale(self):
return self._mutation_scale | ['def', 'get_mutation_scale(self):', 'return', 'self._mutation_scale'] | 715,824 |
Shubham-786/Natural-Language-Processing | dependency_tree.py | DependencyTree.is_tree | is_tree | Check if the tree is legal. | [
"Check",
"if",
"the",
"tree",
"is",
"legal."
] | def is_tree(self) -> bool:
h = []
h.append(-1)
for i in range(1, self.n + 1):
if self.get_head(i) < 0 or self.get_head(i) > self.n:
return False
h.append(-1)
for i in range(1, self.n + 1):
k = i
while k > 0:
if h[k] >= 0 and h[k] < i:
... | ['def', 'is_tree(self)', '->', 'bool:', 'h', '=', '[]', 'h.append(-1)', 'for', 'i', 'in', 'range(1,', 'self.n', '+', '1):', 'if', 'self.get_head(i)', '<', '0', 'or', 'self.get_head(i)', '>', 'self.n:', 'return', 'False', 'h.append(-1)', 'for', 'i', 'in', 'range(1,', 'self.n', '+', '1):', 'k', '=', 'i', 'while', 'k', '>... | 687,743 |
bnpy/bnpy | FiniteTopicModel.py | FiniteTopicModel.init_global_params | init_global_params | Initialize global parameters to provided values. | [
"Initialize",
"global",
"parameters",
"to",
"provided",
"values."
] | def init_global_params(self, Data, K=0, **kwargs):
self.K = K | ['def', 'init_global_params(self,', 'Data,', 'K=0,', '**kwargs):', 'self.K', '=', 'K'] | 464,303 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_glm.py | test_glm_tol_argument | test_glm_tol_argument | Test GLM for invalid tol argument. | [
"Test",
"GLM",
"for",
"invalid",
"tol",
"argument."
] | def test_glm_tol_argument(tol):
y = np.array([1, 2])
X = np.array([[1], [2]])
glm = GeneralizedLinearRegressor(tol=tol)
with pytest.raises(ValueError, match='stopping criteria must be positive'):
glm.fit(X, y) | ['def', 'test_glm_tol_argument(tol):', 'y', '=', 'np.array([1,', '2])', 'X', '=', 'np.array([[1],', '[2]])', 'glm', '=', 'GeneralizedLinearRegressor(tol=tol)', 'with', 'pytest.raises(ValueError,', "match='stopping", 'criteria', 'must', 'be', "positive'):", 'glm.fit(X,', 'y)'] | 437,097 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | generate_cifar10_tfrecords.py | convert_to_tfrecord | convert_to_tfrecord | Converts a file to TFRecords. | [
"Converts",
"a",
"file",
"to",
"TFRecords."
] | def convert_to_tfrecord(input_files, output_file):
print('Generating %s' % output_file)
with tf.python_io.TFRecordWriter(output_file) as record_writer:
for input_file in input_files:
data_dict = read_pickle_from_file(input_file)
data = data_dict['data']
labels = data_... | ['def', 'convert_to_tfrecord(input_files,', 'output_file):', "print('Generating", "%s'", '%', 'output_file)', 'with', 'tf.python_io.TFRecordWriter(output_file)', 'as', 'record_writer:', 'for', 'input_file', 'in', 'input_files:', 'data_dict', '=', 'read_pickle_from_file(input_file)', 'data', '=', "data_dict['data']", 'l... | 30,349 |
devashish-patel/webcam-motion-detector | prefilter.py | PrefilterManager.get_handler_by_name | get_handler_by_name | Get a handler by its name. | [
"Get",
"a",
"handler",
"by",
"its",
"name."
] | def get_handler_by_name(self, name):
return self._handlers.get(name) | ['def', 'get_handler_by_name(self,', 'name):', 'return', 'self._handlers.get(name)'] | 978,806 |
yinyunie/ScenePriors | pluggable_formats.py | MeshFormatInterpreter.save | save | Save the given Meshes object to the given path. | [
"Save",
"the",
"given",
"Meshes",
"object",
"to",
"the",
"given",
"path."
] | def save(self, data: Meshes, path: PathOrStr, path_manager: PathManager, binary: Optional[bool], **kwargs) -> bool:
raise NotImplementedError() | ['def', 'save(self,', 'data:', 'Meshes,', 'path:', 'PathOrStr,', 'path_manager:', 'PathManager,', 'binary:', 'Optional[bool],', '**kwargs)', '->', 'bool:', 'raise', 'NotImplementedError()'] | 329,750 |
QData/deepWordBug | manpage.py | Translator.comment | comment | Return commented version of the passed text. | [
"Return",
"commented",
"version",
"of",
"the",
"passed",
"text."
] | def comment(self, text):
return self.comment_begin(text) + '.\n' | ['def', 'comment(self,', 'text):', 'return', 'self.comment_begin(text)', '+', "'.\\n'"] | 542,680 |
AxeldeRomblay/MLBox | test_drift_estimator.py | test_set_params_drift_estimator | test_set_params_drift_estimator | Test set_params method of DriftEstimator class. | [
"Test",
"set_params",
"method",
"of",
"DriftEstimator",
"class."
] | def test_set_params_drift_estimator():
drift_estimator = DriftEstimator()
dict = {'estimator': drift_estimator.estimator, 'n_folds': 3, 'stratify': False, 'random_state': 2}
drift_estimator.set_params(**dict)
assert drift_estimator.get_params() == dict | ['def', 'test_set_params_drift_estimator():', 'drift_estimator', '=', 'DriftEstimator()', 'dict', '=', "{'estimator':", 'drift_estimator.estimator,', "'n_folds':", '3,', "'stratify':", 'False,', "'random_state':", '2}', 'drift_estimator.set_params(**dict)', 'assert', 'drift_estimator.get_params()', '==', 'dict'] | 630,020 |
Hadishh/cs188 | busters.py | GameState.getNoisyGhostDistances | getNoisyGhostDistances | Returns a noisy distance to each ghost. | [
"Returns",
"a",
"noisy",
"distance",
"to",
"each",
"ghost."
] | def getNoisyGhostDistances(self):
return self.data.ghostDistances | ['def', 'getNoisyGhostDistances(self):', 'return', 'self.data.ghostDistances'] | 223,713 |
matsu0228/nlp-jp | idtracking.py | FrameSymbolVisitor.visit_Assign | visit_Assign | Visit assignments in the correct order. | [
"Visit",
"assignments",
"in",
"the",
"correct",
"order."
] | def visit_Assign(self, node, **kwargs):
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs) | ['def', 'visit_Assign(self,', 'node,', '**kwargs):', 'self.visit(node.node,', '**kwargs)', 'self.visit(node.target,', '**kwargs)'] | 787,887 |
intel/neural-compressor | auto_mixed_precision.py | AutoMixedPrecisionTuneStrategy.traverse | traverse | Traverse the tuning space according to auto-mixed precision strategy. | [
"Traverse",
"the",
"tuning",
"space",
"according",
"to",
"auto-mixed",
"precision",
"strategy."
] | def traverse(self):
self._eval_baseline()
trials_count = 0
for op_tuning_cfg in self.next_tune_cfg():
tune_cfg = self._tune_cfg_converter(op_tuning_cfg)
trials_count += 1
tuning_history = self._find_tuning_history(tune_cfg)
if tuning_history and trials_count < self.cfg.tuning... | ['def', 'traverse(self):', 'self._eval_baseline()', 'trials_count', '=', '0', 'for', 'op_tuning_cfg', 'in', 'self.next_tune_cfg():', 'tune_cfg', '=', 'self._tune_cfg_converter(op_tuning_cfg)', 'trials_count', '+=', '1', 'tuning_history', '=', 'self._find_tuning_history(tune_cfg)', 'if', 'tuning_history', 'and', 'trials... | 738,716 |
deepmind/dm_control | renderer.py | SceneCamera.set_freelook_mode | set_freelook_mode | Enables 6 degrees of freedom of movement for the camera. | [
"Enables",
"6",
"degrees",
"of",
"freedom",
"of",
"movement",
"for",
"the",
"camera."
] | def set_freelook_mode(self):
self._camera.trackbodyid = _NO_BODY_TRACKED_INDEX
self._camera.fixedcamid = _FREE_CAMERA_INDEX
self._camera.type_ = mujoco.mjtCamera.mjCAMERA_FREE
mujoco.mjv_defaultFreeCamera(self._model.ptr, self._camera.ptr) | ['def', 'set_freelook_mode(self):', 'self._camera.trackbodyid', '=', '_NO_BODY_TRACKED_INDEX', 'self._camera.fixedcamid', '=', '_FREE_CAMERA_INDEX', 'self._camera.type_', '=', 'mujoco.mjtCamera.mjCAMERA_FREE', 'mujoco.mjv_defaultFreeCamera(self._model.ptr,', 'self._camera.ptr)'] | 165,671 |
Kvatsx/Artificial-Intelligence-Assignments | test_tools.py | Test_ipexec_validate.test_main_path2 | test_main_path2 | Test with only stdout results, expecting windows line endings. | [
"Test",
"with",
"only",
"stdout",
"results,",
"expecting",
"windows",
"line",
"endings."
] | def test_main_path2(self):
self.mktmp("print('A')\nprint('B')\n")
out = 'A\r\nB'
tt.ipexec_validate(self.fname, out) | ['def', 'test_main_path2(self):', 'self.mktmp("print(\'A\')\\nprint(\'B\')\\n")', 'out', '=', "'A\\r\\nB'", 'tt.ipexec_validate(self.fname,', 'out)'] | 38,785 |
devashish-patel/webcam-motion-detector | inputsplitter.py | IPythonInputSplitter.transforms_in_use | transforms_in_use | Transformers, excluding logical line transformers if we're in a Python line. | [
"Transformers,",
"excluding",
"logical",
"line",
"transformers",
"if",
"we're",
"in",
"a",
"Python",
"line."
] | def transforms_in_use(self):
t = self.physical_line_transforms[:]
if not self.within_python_line:
t += [self.assemble_logical_lines] + self.logical_line_transforms
return t + [self.assemble_python_lines] + self.python_line_transforms | ['def', 'transforms_in_use(self):', 't', '=', 'self.physical_line_transforms[:]', 'if', 'not', 'self.within_python_line:', 't', '+=', '[self.assemble_logical_lines]', '+', 'self.logical_line_transforms', 'return', 't', '+', '[self.assemble_python_lines]', '+', 'self.python_line_transforms'] | 978,648 |
Speedwagon13/CS-3600-Introduction-to-- | dircache.py | reset | reset | Reset the cache completely. | [
"Reset",
"the",
"cache",
"completely."
] | def reset():
global cache
cache = {} | ['def', 'reset():', 'global', 'cache', 'cache', '=', '{}'] | 139,778 |
tobegit3hub/deep_image_model | composable_model.py | LinearComposableModel.get_bias | get_bias | Returns bias of the model. | [
"Returns",
"bias",
"of",
"the",
"model."
] | def get_bias(self, model_dir):
return load_variable(model_dir, name=self._scope + '/bias_weight') | ['def', 'get_bias(self,', 'model_dir):', 'return', 'load_variable(model_dir,', 'name=self._scope', '+', "'/bias_weight')"] | 181,642 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | prediction_model.py | stp_transformation | stp_transformation | Apply spatial transformer predictor (STP) to previous image. | [
"Apply",
"spatial",
"transformer",
"predictor",
"(STP)",
"to",
"previous",
"image."
] | def stp_transformation(prev_image, stp_input, num_masks):
from spatial_transformer import transformer
identity_params = tf.convert_to_tensor(np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32))
transformed = []
for i in range(num_masks - 1):
params = slim.layers.fully_connected(stp_input, 6, sc... | ['def', 'stp_transformation(prev_image,', 'stp_input,', 'num_masks):', 'from', 'spatial_transformer', 'import', 'transformer', 'identity_params', '=', 'tf.convert_to_tensor(np.array([1.0,', '0.0,', '0.0,', '0.0,', '1.0,', '0.0],', 'np.float32))', 'transformed', '=', '[]', 'for', 'i', 'in', 'range(num_masks', '-', '1):'... | 30,002 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | __init__.py | VersionControl.obtain | obtain | Install or update in editable mode the package represented by this VersionControl object. | [
"Install",
"or",
"update",
"in",
"editable",
"mode",
"the",
"package",
"represented",
"by",
"this",
"VersionControl",
"object."
] | def obtain(self, dest):
(url, rev_options) = self.get_url_rev_options(self.url)
if not os.path.exists(dest):
self.fetch_new(dest, url, rev_options)
return
rev_display = rev_options.to_display()
if self.is_repository_directory(dest):
existing_url = self.get_remote_url(dest)
... | ['def', 'obtain(self,', 'dest):', '(url,', 'rev_options)', '=', 'self.get_url_rev_options(self.url)', 'if', 'not', 'os.path.exists(dest):', 'self.fetch_new(dest,', 'url,', 'rev_options)', 'return', 'rev_display', '=', 'rev_options.to_display()', 'if', 'self.is_repository_directory(dest):', 'existing_url', '=', 'self.ge... | 950,201 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | StandardizedMoment | StandardizedMoment | Computes the kth standardized moment of xs. | [
"Computes",
"the",
"kth",
"standardized",
"moment",
"of",
"xs."
] | def StandardizedMoment(xs, k):
var = CentralMoment(xs, 2)
std = math.sqrt(var)
return CentralMoment(xs, k) / std ** k | ['def', 'StandardizedMoment(xs,', 'k):', 'var', '=', 'CentralMoment(xs,', '2)', 'std', '=', 'math.sqrt(var)', 'return', 'CentralMoment(xs,', 'k)', '/', 'std', '**', 'k'] | 19,546 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | dist.py | Distribution.get_command_packages | get_command_packages | Return a list of packages from which commands are loaded. | [
"Return",
"a",
"list",
"of",
"packages",
"from",
"which",
"commands",
"are",
"loaded."
] | def get_command_packages(self):
pkgs = self.command_packages
if not isinstance(pkgs, list):
if pkgs is None:
pkgs = ''
pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
if 'distutils.command' not in pkgs:
pkgs.insert(0, 'distutils.command')
self... | ['def', 'get_command_packages(self):', 'pkgs', '=', 'self.command_packages', 'if', 'not', 'isinstance(pkgs,', 'list):', 'if', 'pkgs', 'is', 'None:', 'pkgs', '=', "''", 'pkgs', '=', '[pkg.strip()', 'for', 'pkg', 'in', "pkgs.split(',')", 'if', 'pkg', '!=', "'']", 'if', "'distutils.command'", 'not', 'in', 'pkgs:', 'pkgs.i... | 430,312 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | reqparse.py | RequestParser.remove_argument | remove_argument | Remove the argument matching the given name. | [
"Remove",
"the",
"argument",
"matching",
"the",
"given",
"name."
] | def remove_argument(self, name):
for (index, arg) in enumerate(self.args[:]):
if name == arg.name:
del self.args[index]
break
return self | ['def', 'remove_argument(self,', 'name):', 'for', '(index,', 'arg)', 'in', 'enumerate(self.args[:]):', 'if', 'name', '==', 'arg.name:', 'del', 'self.args[index]', 'break', 'return', 'self'] | 102,098 |
sunsmarterjie/SaGe | checkpoint.py | load_from_openmmlab | load_from_openmmlab | load checkpoint through the file path prefixed with open-mmlab or openmmlab. | [
"load",
"checkpoint",
"through",
"the",
"file",
"path",
"prefixed",
"with",
"open-mmlab",
"or",
"openmmlab."
] | def load_from_openmmlab(filename, map_location=None):
model_urls = get_external_models()
prefix_str = 'open-mmlab://'
if filename.startswith(prefix_str):
model_name = filename[13:]
else:
model_name = filename[12:]
prefix_str = 'openmmlab://'
deprecated_urls = get_deprecated_m... | ['def', 'load_from_openmmlab(filename,', 'map_location=None):', 'model_urls', '=', 'get_external_models()', 'prefix_str', '=', "'open-mmlab://'", 'if', 'filename.startswith(prefix_str):', 'model_name', '=', 'filename[13:]', 'else:', 'model_name', '=', 'filename[12:]', 'prefix_str', '=', "'openmmlab://'", 'deprecated_ur... | 328,422 |
TengXiaoDai/DistributedCrawling | operator.py | ixor | ixor | Same as a ^= b. | [
"Same",
"as",
"a",
"^=",
"b."
] | def ixor(a, b):
a ^= b
return a | ['def', 'ixor(a,', 'b):', 'a', '^=', 'b', 'return', 'a'] | 187,925 |
rifqind/Agent-Programs-3KS1 | named_commands.py | backward_char | backward_char | Move back a character. | [
"Move",
"back",
"a",
"character."
] | def backward_char(event):
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg) | ['def', 'backward_char(event):', 'buff', '=', 'event.current_buffer', 'buff.cursor_position', '+=', 'buff.document.get_cursor_left_position(count=event.arg)'] | 45,250 |
sarnsdev/social-alignment-data-mining | compat.py | console_to_str | console_to_str | Return a string, safe for output, of subprocess output. | [
"Return",
"a",
"string,",
"safe",
"for",
"output,",
"of",
"subprocess",
"output."
] | def console_to_str(data):
return str_to_display(data, desc='Subprocess output') | ['def', 'console_to_str(data):', 'return', 'str_to_display(data,', "desc='Subprocess", "output')"] | 389,781 |
myothida/Supervised-Machine-Learning | conftest.py | utc_fixture | utc_fixture | Fixture to provide variants of UTC timezone strings and tzinfo objects. | [
"Fixture",
"to",
"provide",
"variants",
"of",
"UTC",
"timezone",
"strings",
"and",
"tzinfo",
"objects."
] | def utc_fixture(request):
return request.param | ['def', 'utc_fixture(request):', 'return', 'request.param'] | 442,220 |
ryu-ed/SpaceInvaders_Ros | objectmodel.py | ObjectModel.lookup | lookup | Look up the given *name* in the current model It should return an AST or an interpreter object, but if the name is not found, then an AttributeInferenceError will be raised. | [
"Look",
"up",
"the",
"given",
"*name*",
"in",
"the",
"current",
"model",
"It",
"should",
"return",
"an",
"AST",
"or",
"an",
"interpreter",
"object,",
"but",
"if",
"the",
"name",
"is",
"not",
"found,",
"then",
"an",
"AttributeInferenceError",
"will",
"be",
... | def lookup(self, name):
if name in self.attributes():
return getattr(self, IMPL_PREFIX + name)
raise exceptions.AttributeInferenceError(target=self._instance, attribute=name) | ['def', 'lookup(self,', 'name):', 'if', 'name', 'in', 'self.attributes():', 'return', 'getattr(self,', 'IMPL_PREFIX', '+', 'name)', 'raise', 'exceptions.AttributeInferenceError(target=self._instance,', 'attribute=name)'] | 394,571 |
viko-3/DiffSeqMol | tracker.py | current_skip_tracker | current_skip_tracker | Gets the skip tracker on the current thread. | [
"Gets",
"the",
"skip",
"tracker",
"on",
"the",
"current",
"thread."
] | def current_skip_tracker() -> SkipTracker:
skip_tracker = thread_local.skip_tracker
if skip_tracker is None:
skip_tracker = SkipTracker()
thread_local.skip_tracker = skip_tracker
return skip_tracker | ['def', 'current_skip_tracker()', '->', 'SkipTracker:', 'skip_tracker', '=', 'thread_local.skip_tracker', 'if', 'skip_tracker', 'is', 'None:', 'skip_tracker', '=', 'SkipTracker()', 'thread_local.skip_tracker', '=', 'skip_tracker', 'return', 'skip_tracker'] | 551,550 |
tensorly/quantum | op_serializer_test.py | OpSerializerTest.test_to_proto_unsupported_type | test_to_proto_unsupported_type | Test proto unsupported types errors. | [
"Test",
"proto",
"unsupported",
"types",
"errors."
] | def test_to_proto_unsupported_type(self, q):
serializer = op_serializer.GateOpSerializer(gate_type=GateWithProperty, serialized_gate_id='my_gate', args=[op_serializer.SerializingArg(serialized_name='my_val', serialized_type=bytes, op_getter='val')])
with self.assertRaisesRegex(ValueError, expected_regex='bytes'... | ['def', 'test_to_proto_unsupported_type(self,', 'q):', 'serializer', '=', 'op_serializer.GateOpSerializer(gate_type=GateWithProperty,', "serialized_gate_id='my_gate',", "args=[op_serializer.SerializingArg(serialized_name='my_val',", 'serialized_type=bytes,', "op_getter='val')])", 'with', 'self.assertRaisesRegex(ValueEr... | 834,912 |
unixpickle/anyrl-py | feedforward_ac.py | HeadFeedforwardAC.critic | critic | Turn the output from base() into values. | [
"Turn",
"the",
"output",
"from",
"base()",
"into",
"values."
] | def critic(self, base, initializer):
critic_out = fully_connected(base, 1, activation_fn=None, weights_initializer=initializer)
return tf.reshape(critic_out, (tf.shape(critic_out)[0],)) | ['def', 'critic(self,', 'base,', 'initializer):', 'critic_out', '=', 'fully_connected(base,', '1,', 'activation_fn=None,', 'weights_initializer=initializer)', 'return', 'tf.reshape(critic_out,', '(tf.shape(critic_out)[0],))'] | 33,832 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MakeCdfFromHist | MakeCdfFromHist | Makes a CDF from a Hist object. | [
"Makes",
"a",
"CDF",
"from",
"a",
"Hist",
"object."
] | def MakeCdfFromHist(hist, label=None):
if label is None:
label = hist.label
return Cdf(hist, label=label) | ['def', 'MakeCdfFromHist(hist,', 'label=None):', 'if', 'label', 'is', 'None:', 'label', '=', 'hist.label', 'return', 'Cdf(hist,', 'label=label)'] | 19,314 |
Kvatsx/Artificial-Intelligence-Assignments | textfmts.py | HttpLexer.get_tokens_unprocessed | get_tokens_unprocessed | Reset the content-type state. | [
"Reset",
"the",
"content-type",
"state."
] | def get_tokens_unprocessed(self, text, stack=('root',)):
self.content_type = None
return RegexLexer.get_tokens_unprocessed(self, text, stack) | ['def', 'get_tokens_unprocessed(self,', 'text,', "stack=('root',)):", 'self.content_type', '=', 'None', 'return', 'RegexLexer.get_tokens_unprocessed(self,', 'text,', 'stack)'] | 77,180 |
enuguru/artificial_intelligence_and_machine_learning | wrappers.py | BaseRequest.values | values | Combined multi dict for :attr:`args` and :attr:`form`. | [
"Combined",
"multi",
"dict",
"for",
":attr:`args`",
"and",
":attr:`form`."
] | def values(self):
args = []
for d in (self.args, self.form):
if not isinstance(d, MultiDict):
d = MultiDict(d)
args.append(d)
return CombinedMultiDict(args) | ['def', 'values(self):', 'args', '=', '[]', 'for', 'd', 'in', '(self.args,', 'self.form):', 'if', 'not', 'isinstance(d,', 'MultiDict):', 'd', '=', 'MultiDict(d)', 'args.append(d)', 'return', 'CombinedMultiDict(args)'] | 132,477 |
sarnsdev/social-alignment-data-mining | test_neighbors.py | test_radius_neighbors_boundary_handling | test_radius_neighbors_boundary_handling | Test whether points lying on boundary are handled consistently Also ensures that even with only one query point, an object array is returned rather than a 2d array. | [
"Test",
"whether",
"points",
"lying",
"on",
"boundary",
"are",
"handled",
"consistently",
"Also",
"ensures",
"that",
"even",
"with",
"only",
"one",
"query",
"point,",
"an",
"object",
"array",
"is",
"returned",
"rather",
"than",
"a",
"2d",
"array."
] | def test_radius_neighbors_boundary_handling():
X = np.array([[1.5], [3.0], [3.01]])
radius = 3.0
for algorithm in ALGORITHMS:
nbrs = neighbors.NearestNeighbors(radius=radius, algorithm=algorithm).fit(X)
results = nbrs.radius_neighbors([[0.0]], return_distance=False)
assert_equal(resu... | ['def', 'test_radius_neighbors_boundary_handling():', 'X', '=', 'np.array([[1.5],', '[3.0],', '[3.01]])', 'radius', '=', '3.0', 'for', 'algorithm', 'in', 'ALGORITHMS:', 'nbrs', '=', 'neighbors.NearestNeighbors(radius=radius,', 'algorithm=algorithm).fit(X)', 'results', '=', 'nbrs.radius_neighbors([[0.0]],', 'return_dist... | 392,273 |
myothida/Supervised-Machine-Learning | ticker.py | Formatter.format_data | format_data | Return the full string representation of the value with the position unspecified. | [
"Return",
"the",
"full",
"string",
"representation",
"of",
"the",
"value",
"with",
"the",
"position",
"unspecified."
] | def format_data(self, value):
return self.__call__(value) | ['def', 'format_data(self,', 'value):', 'return', 'self.__call__(value)'] | 362,285 |
lgalke/aae-recommender | condition.py | ConditionBase.fit_transform | fit_transform | Fit to `raw_inputs`, then transform `raw_inputs`. | [
"Fit",
"to",
"`raw_inputs`,",
"then",
"transform",
"`raw_inputs`."
] | def fit_transform(self, raw_inputs):
return self.fit(raw_inputs).transform(raw_inputs) | ['def', 'fit_transform(self,', 'raw_inputs):', 'return', 'self.fit(raw_inputs).transform(raw_inputs)'] | 405,512 |
tobegit3hub/deep_image_model | lookup_ops.py | LookupInterface.name | name | The name of the table. | [
"The",
"name",
"of",
"the",
"table."
] | def name(self):
return self._name | ['def', 'name(self):', 'return', 'self._name'] | 181,896 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Listbox.selection_anchor | selection_anchor | Set the fixed end oft the selection to INDEX. | [
"Set",
"the",
"fixed",
"end",
"oft",
"the",
"selection",
"to",
"INDEX."
] | def selection_anchor(self, index):
self.tk.call(self._w, 'selection', 'anchor', index) | ['def', 'selection_anchor(self,', 'index):', 'self.tk.call(self._w,', "'selection',", "'anchor',", 'index)'] | 377,003 |
dwf/convolupy | tests.py | check_parameter_gradient | check_parameter_gradient | Given a module, an objective function (one of the ones specified in this Python module) and inputs/parameters, checks the gradient with respect to the parameters. | [
"Given",
"a",
"module,",
"an",
"objective",
"function",
"(one",
"of",
"the",
"ones",
"specified",
"in",
"this",
"Python",
"module)",
"and",
"inputs/parameters,",
"checks",
"the",
"gradient",
"with",
"respect",
"to",
"the",
"parameters."
] | def check_parameter_gradient(module, inputs, params):
func = lambda params: summed_objective_params_func(params, inputs, module)
approx_grad = fd_grad(func, params)
real_grad = summed_objective_params_gradient(params, inputs, module)
assert_array_almost_equal(real_grad, approx_grad) | ['def', 'check_parameter_gradient(module,', 'inputs,', 'params):', 'func', '=', 'lambda', 'params:', 'summed_objective_params_func(params,', 'inputs,', 'module)', 'approx_grad', '=', 'fd_grad(func,', 'params)', 'real_grad', '=', 'summed_objective_params_gradient(params,', 'inputs,', 'module)', 'assert_array_almost_equa... | 136,988 |
sunishsheth2009/ChatterBot | index.py | Index.doc_count_all | doc_count_all | Returns the total number of documents, DELETED OR UNDELETED, in this index. | [
"Returns",
"the",
"total",
"number",
"of",
"documents,",
"DELETED",
"OR",
"UNDELETED,",
"in",
"this",
"index."
] | def doc_count_all(self):
r = self.reader()
try:
return r.doc_count_all()
finally:
r.close() | ['def', 'doc_count_all(self):', 'r', '=', 'self.reader()', 'try:', 'return', 'r.doc_count_all()', 'finally:', 'r.close()'] | 482,882 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | core.py | contours | contours | Extracts contours and the relationship between them from a binary mask. | [
"Extracts",
"contours",
"and",
"the",
"relationship",
"between",
"them",
"from",
"a",
"binary",
"mask."
] | def contours(mask):
(_, contours, hierarchy) = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return (contours, hierarchy) | ['def', 'contours(mask):', '(_,', 'contours,', 'hierarchy)', '=', 'cv2.findContours(mask,', 'cv2.RETR_TREE,', 'cv2.CHAIN_APPROX_SIMPLE)', 'return', '(contours,', 'hierarchy)'] | 18,189 |
Katja-M/Python_NaturalLanguageProcessing | backend_bases.py | NavigationToolbar2.draw | draw | Redraw the canvases, update the locators. | [
"Redraw",
"the",
"canvases,",
"update",
"the",
"locators."
] | def draw(self):
for a in self.canvas.figure.get_axes():
xaxis = getattr(a, 'xaxis', None)
yaxis = getattr(a, 'yaxis', None)
locators = []
if xaxis is not None:
locators.append(xaxis.get_major_locator())
locators.append(xaxis.get_minor_locator())
if yax... | ['def', 'draw(self):', 'for', 'a', 'in', 'self.canvas.figure.get_axes():', 'xaxis', '=', 'getattr(a,', "'xaxis',", 'None)', 'yaxis', '=', 'getattr(a,', "'yaxis',", 'None)', 'locators', '=', '[]', 'if', 'xaxis', 'is', 'not', 'None:', 'locators.append(xaxis.get_major_locator())', 'locators.append(xaxis.get_minor_locator(... | 864,312 |
dgseten/bad-cv-tfm | calibration_builder_test.py | CalibrationBuilderTest.test_tf_linear_interp1d_against_scipy_interpolate | test_tf_linear_interp1d_against_scipy_interpolate | Tests parity of TF linear interpolation with SciPy. | [
"Tests",
"parity",
"of",
"TF",
"linear",
"interpolation",
"with",
"SciPy."
] | def test_tf_linear_interp1d_against_scipy_interpolate(self):
length = 10
np_x = np.linspace(0, 1, length)
np_y_interp = np.linspace(0.5, 1, length)
test_data_np = np.linspace(0, 1, length * 10)
scipy_interp_outputs = self._get_scipy_interp1d(test_data_np, np_x, np_y_interp)
np_tf_interp_outputs ... | ['def', 'test_tf_linear_interp1d_against_scipy_interpolate(self):', 'length', '=', '10', 'np_x', '=', 'np.linspace(0,', '1,', 'length)', 'np_y_interp', '=', 'np.linspace(0.5,', '1,', 'length)', 'test_data_np', '=', 'np.linspace(0,', '1,', 'length', '*', '10)', 'scipy_interp_outputs', '=', 'self._get_scipy_interp1d(test... | 421,394 |
fairlearn/fairlearn | _threshold_operation.py | ThresholdOperation.operator | operator | Return the stored threshold operator. | [
"Return",
"the",
"stored",
"threshold",
"operator."
] | def operator(self):
return self._operator | ['def', 'operator(self):', 'return', 'self._operator'] | 558,404 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | transform.py | makeConst | makeConst | Returns a closure that indiscriminately changes node text to a value. | [
"Returns",
"a",
"closure",
"that",
"indiscriminately",
"changes",
"node",
"text",
"to",
"a",
"value."
] | def makeConst(v):
def xform(node, config):
node.token.text = v
return xform | ['def', 'makeConst(v):', 'def', 'xform(node,', 'config):', 'node.token.text', '=', 'v', 'return', 'xform'] | 17,648 |
matsu0228/nlp-jp | doc2vec.py | DocvecsArray.estimated_lookup_memory | estimated_lookup_memory | Estimated memory for tag lookup; 0 if using pure int tags. | [
"Estimated",
"memory",
"for",
"tag",
"lookup;",
"0",
"if",
"using",
"pure",
"int",
"tags."
] | def estimated_lookup_memory(self):
return 60 * len(self.offset2doctag) + 140 * len(self.doctags) | ['def', 'estimated_lookup_memory(self):', 'return', '60', '*', 'len(self.offset2doctag)', '+', '140', '*', 'len(self.doctags)'] | 785,776 |
ifwe/digsby | imwin_native.py | DigsbyFlatNotebook.Pages | Pages | Page iterator needed for compatibility with UberBook impl. | [
"Page",
"iterator",
"needed",
"for",
"compatibility",
"with",
"UberBook",
"impl."
] | def Pages(self):
pagelist = []
for page in xrange(self.GetPageCount()):
pagelist.append(self.GetPage(page))
return pagelist | ['def', 'Pages(self):', 'pagelist', '=', '[]', 'for', 'page', 'in', 'xrange(self.GetPageCount()):', 'pagelist.append(self.GetPage(page))', 'return', 'pagelist'] | 185,418 |
weimin17/Object-Detection_HelmetDetection | dp_optimizer.py | DPGradientDescentOptimizer.compute_sanitized_gradients | compute_sanitized_gradients | Compute the sanitized gradients. | [
"Compute",
"the",
"sanitized",
"gradients."
] | def compute_sanitized_gradients(self, loss, var_list=None, add_noise=True):
self._assert_valid_dtypes([loss])
xs = [tf.convert_to_tensor(x) for x in var_list]
px_grads = per_example_gradients.PerExampleGradients(loss, xs)
sanitized_grads = []
for (px_grad, v) in zip(px_grads, var_list):
tens... | ['def', 'compute_sanitized_gradients(self,', 'loss,', 'var_list=None,', 'add_noise=True):', 'self._assert_valid_dtypes([loss])', 'xs', '=', '[tf.convert_to_tensor(x)', 'for', 'x', 'in', 'var_list]', 'px_grads', '=', 'per_example_gradients.PerExampleGradients(loss,', 'xs)', 'sanitized_grads', '=', '[]', 'for', '(px_grad... | 762,471 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | registry_test.py | RegistryTest.testCannotCreateMissingModule | testCannotCreateMissingModule | Tests that Create fails if the module does not exist. | [
"Tests",
"that",
"Create",
"fails",
"if",
"the",
"module",
"does",
"not",
"exist."
] | def testCannotCreateMissingModule(self):
with self.assertRaisesRegexp(ValueError, 'Failed to create'):
registry_test_base.Base.Create(PATH + 'missing.SomeClass', 'hello world') | ['def', 'testCannotCreateMissingModule(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", 'registry_test_base.Base.Create(PATH', '+', "'missing.SomeClass',", "'hello", "world')"] | 29,068 |
IDEA-Research/detrex | attention.py | GroupConditionalSelfAttention.forward | forward | Forward function for `ConditionalSelfAttention` **kwargs allow passing a more general data flow when combining with other operations in `transformerlayer`. | [
"Forward",
"function",
"for",
"`ConditionalSelfAttention`",
"**kwargs",
"allow",
"passing",
"a",
"more",
"general",
"data",
"flow",
"when",
"combining",
"with",
"other",
"operations",
"in",
"`transformerlayer`."
] | def forward(self, query, key=None, value=None, identity=None, query_pos=None, key_pos=None, attn_mask=None, key_padding_mask=None, **kwargs):
if key is None:
key = query
if value is None:
value = key
if identity is None:
identity = query
if key_pos is None:
if query_pos i... | ['def', 'forward(self,', 'query,', 'key=None,', 'value=None,', 'identity=None,', 'query_pos=None,', 'key_pos=None,', 'attn_mask=None,', 'key_padding_mask=None,', '**kwargs):', 'if', 'key', 'is', 'None:', 'key', '=', 'query', 'if', 'value', 'is', 'None:', 'value', '=', 'key', 'if', 'identity', 'is', 'None:', 'identity',... | 549,939 |
zihuitang/medical_AI_platform | __init__.py | Misc.setvar | setvar | Set Tcl variable NAME to VALUE. | [
"Set",
"Tcl",
"variable",
"NAME",
"to",
"VALUE."
] | def setvar(self, name='PY_VAR', value='1'):
self.tk.setvar(name, value) | ['def', 'setvar(self,', "name='PY_VAR',", "value='1'):", 'self.tk.setvar(name,', 'value)'] | 284,037 |
bl0/moco | util.py | cls_loss_plot | cls_loss_plot | Plot a loss graph of linear classifier training. | [
"Plot",
"a",
"loss",
"graph",
"of",
"linear",
"classifier",
"training."
] | def cls_loss_plot(hist, path, record_epoch):
plt.switch_backend('agg')
x = range(0, record_epoch * len(hist), record_epoch)
plt.plot(x, hist, label='loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend(loc=4)
plt.grid(True)
plt.tight_layout()
path = os.path.join(path, 'loss.png')... | ['def', 'cls_loss_plot(hist,', 'path,', 'record_epoch):', "plt.switch_backend('agg')", 'x', '=', 'range(0,', 'record_epoch', '*', 'len(hist),', 'record_epoch)', 'plt.plot(x,', 'hist,', "label='loss')", "plt.xlabel('Epoch')", "plt.ylabel('Loss')", 'plt.legend(loc=4)', 'plt.grid(True)', 'plt.tight_layout()', 'path', '=',... | 240,685 |
cvjena/PartDetectorDisovery | _blob.py | Blob.clear | clear | Clears a blob data. | [
"Clears",
"a",
"blob",
"data."
] | def clear(self):
self._data = None
self._diff = None | ['def', 'clear(self):', 'self._data', '=', 'None', 'self._diff', '=', 'None'] | 278,331 |
open-mmlab/mmtracking | lasot2coco.py | convert_lasot | convert_lasot | Convert lasot dataset to COCO style. | [
"Convert",
"lasot",
"dataset",
"to",
"COCO",
"style."
] | def convert_lasot(ann_dir, save_dir, split='test'):
assert split in ['train', 'test'], f'split [{split}] does not exist'
lasot = defaultdict(list)
records = dict(vid_id=1, img_id=1, ann_id=1, global_instance_id=1)
lasot['categories'] = [dict(id=0, name=0)]
videos_list = mmcv.list_from_file(osp.join(... | ['def', 'convert_lasot(ann_dir,', 'save_dir,', "split='test'):", 'assert', 'split', 'in', "['train',", "'test'],", "f'split", '[{split}]', 'does', 'not', "exist'", 'lasot', '=', 'defaultdict(list)', 'records', '=', 'dict(vid_id=1,', 'img_id=1,', 'ann_id=1,', 'global_instance_id=1)', "lasot['categories']", '=', '[dict(i... | 625,944 |
mfbx9da4/neuron-astrocyte-networks | evolinonetwork.py | EvolinoNetwork.setOutputWeightMatrix | setOutputWeightMatrix | Set the weight matrix of the linear output layer. | [
"Set",
"the",
"weight",
"matrix",
"of",
"the",
"linear",
"output",
"layer."
] | def setOutputWeightMatrix(self, W):
c = self._hid_to_out_connection
c.params[:] = W.flatten() | ['def', 'setOutputWeightMatrix(self,', 'W):', 'c', '=', 'self._hid_to_out_connection', 'c.params[:]', '=', 'W.flatten()'] | 723,195 |
fudan-zvg/SETR | openimages.py | OpenImagesChallengeDataset.get_relation_matrix | get_relation_matrix | Get hierarchy for classes. | [
"Get",
"hierarchy",
"for",
"classes."
] | def get_relation_matrix(self, hierarchy_file):
class_label_tree = np.load(hierarchy_file, allow_pickle=True)
return class_label_tree[1:, 1:] | ['def', 'get_relation_matrix(self,', 'hierarchy_file):', 'class_label_tree', '=', 'np.load(hierarchy_file,', 'allow_pickle=True)', 'return', 'class_label_tree[1:,', '1:]'] | 897,981 |
aeon-toolkit/aeon | test_all_estimators.py | TestAllObjects.test_no_between_test_case_side_effects | test_no_between_test_case_side_effects | Test that there are no side effects across instances of the same test. | [
"Test",
"that",
"there",
"are",
"no",
"side",
"effects",
"across",
"instances",
"of",
"the",
"same",
"test."
] | def test_no_between_test_case_side_effects(self, estimator_instance, scenario, a):
assert not hasattr(estimator_instance, 'test__attr')
estimator_instance.test__attr = 42 | ['def', 'test_no_between_test_case_side_effects(self,', 'estimator_instance,', 'scenario,', 'a):', 'assert', 'not', 'hasattr(estimator_instance,', "'test__attr')", 'estimator_instance.test__attr', '=', '42'] | 399,853 |
replit-archive/empythoned | test_io.py | SignalsTest.check_interrupted_read_retry | check_interrupted_read_retry | Check that a buffered read, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully. | [
"Check",
"that",
"a",
"buffered",
"read,",
"when",
"it",
"gets",
"interrupted",
"(either",
"returning",
"a",
"partial",
"result",
"or",
"EINTR),",
"properly",
"invokes",
"the",
"signal",
"handler",
"and",
"retries",
"if",
"the",
"latter",
"returned",
"successful... | def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
(r, w) = os.pipe()
fdopen_kwargs['closefd'] = False
def alarm_handler(sig, frame):
os.write(w, b'bar')
signal.signal(signal.SIGALRM, alarm_handler)
try:
rio = self.io.open(r, **fdopen_kwargs)
os.write(w, b'foo'... | ['def', 'check_interrupted_read_retry(self,', 'decode,', '**fdopen_kwargs):', '(r,', 'w)', '=', 'os.pipe()', "fdopen_kwargs['closefd']", '=', 'False', 'def', 'alarm_handler(sig,', 'frame):', 'os.write(w,', "b'bar')", 'signal.signal(signal.SIGALRM,', 'alarm_handler)', 'try:', 'rio', '=', 'self.io.open(r,', '**fdopen_kwa... | 176,993 |
AtlantixJJ/LinearGAN | tfutil.py | exp2 | exp2 | Exponent in base 2. | [
"Exponent",
"in",
"base",
"2."
] | def exp2(x: TfExpressionEx) -> TfExpression:
with tf.name_scope('Exp2'):
return tf.exp(x * np.float32(np.log(2.0))) | ['def', 'exp2(x:', 'TfExpressionEx)', '->', 'TfExpression:', 'with', "tf.name_scope('Exp2'):", 'return', 'tf.exp(x', '*', 'np.float32(np.log(2.0)))'] | 602,638 |
flow-project/flow | traci.py | TraCIVehicle.set_headway | set_headway | Set the headway of the specified vehicle. | [
"Set",
"the",
"headway",
"of",
"the",
"specified",
"vehicle."
] | def set_headway(self, veh_id, headway):
self.__vehicles[veh_id]['headway'] = headway | ['def', 'set_headway(self,', 'veh_id,', 'headway):', "self.__vehicles[veh_id]['headway']", '=', 'headway'] | 211,694 |
AmirAbaskohi/PEACH | infeed.py | get_input_fn | get_input_fn | Estimator input_fn for TFRecords. | [
"Estimator",
"input_fn",
"for",
"TFRecords."
] | def get_input_fn(parser_fn, input_pattern, mode, prefetch=True, drop_remainder=True, parallelism=32, dataset_skip=0, current_train_steps=42000):
(parser, shapes) = parser_fn(mode=mode)
training = mode == tf.estimator.ModeKeys.TRAIN
if not training:
parallelism = 1
def input_fn(params):
... | ['def', 'get_input_fn(parser_fn,', 'input_pattern,', 'mode,', 'prefetch=True,', 'drop_remainder=True,', 'parallelism=32,', 'dataset_skip=0,', 'current_train_steps=42000):', '(parser,', 'shapes)', '=', 'parser_fn(mode=mode)', 'training', '=', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN', 'if', 'not', 'training:', 'parall... | 765,969 |
PaddlePaddle/Paddle3D | transform3d.py | Transform3d.compose | compose | Return a new Transform3d with the tranforms to compose stored as an internal list. | [
"Return",
"a",
"new",
"Transform3d",
"with",
"the",
"tranforms",
"to",
"compose",
"stored",
"as",
"an",
"internal",
"list."
] | def compose(self, *others):
out = Transform3d()
out._matrix = self._matrix.clone()
for other in others:
if not isinstance(other, Transform3d):
msg = 'Only possible to compose Transform3d objects; got %s'
raise ValueError(msg % type(other))
out._transforms = self._transfor... | ['def', 'compose(self,', '*others):', 'out', '=', 'Transform3d()', 'out._matrix', '=', 'self._matrix.clone()', 'for', 'other', 'in', 'others:', 'if', 'not', 'isinstance(other,', 'Transform3d):', 'msg', '=', "'Only", 'possible', 'to', 'compose', 'Transform3d', 'objects;', 'got', "%s'", 'raise', 'ValueError(msg', '%', 't... | 778,078 |
dmcnamee/FlexModEHC | generators.py | check_weightmat | check_weightmat | Checks whether W is a weight matrix. | [
"Checks",
"whether",
"W",
"is",
"a",
"weight",
"matrix."
] | def check_weightmat(W):
if not np.all(np.diag(W) == 0):
raise ValueError('WEIGHT MATRIX: nonzero on the diagonal.')
if not is_symmetric(W):
raise ValueError('WEIGHT MATRIX: not symmetric.') | ['def', 'check_weightmat(W):', 'if', 'not', 'np.all(np.diag(W)', '==', '0):', 'raise', "ValueError('WEIGHT", 'MATRIX:', 'nonzero', 'on', 'the', "diagonal.')", 'if', 'not', 'is_symmetric(W):', 'raise', "ValueError('WEIGHT", 'MATRIX:', 'not', "symmetric.')"] | 585,121 |
yaoyao-liu/meta-transfer-learning | pre_data_generator.py | PreDataGenerator.make_data_tensor | make_data_tensor | The function to make tensor for the tensorflow model. | [
"The",
"function",
"to",
"make",
"tensor",
"for",
"the",
"tensorflow",
"model."
] | def make_data_tensor(self):
print('Generating pre-training data')
all_filenames_and_labels = []
folders = self.pretrain_character_folders
for (idx, path) in enumerate(folders):
all_filenames_and_labels += get_pretrain_images(path, idx)
random.shuffle(all_filenames_and_labels)
all_labels ... | ['def', 'make_data_tensor(self):', "print('Generating", 'pre-training', "data')", 'all_filenames_and_labels', '=', '[]', 'folders', '=', 'self.pretrain_character_folders', 'for', '(idx,', 'path)', 'in', 'enumerate(folders):', 'all_filenames_and_labels', '+=', 'get_pretrain_images(path,', 'idx)', 'random.shuffle(all_fil... | 633,089 |
inseq-team/inseq | base.py | BaseCLICommand.register_subcommand | register_subcommand | Register this command to argparse so it's available for the Inseq cli. | [
"Register",
"this",
"command",
"to",
"argparse",
"so",
"it's",
"available",
"for",
"the",
"Inseq",
"cli."
] | def register_subcommand(cls, parser: InseqArgumentParser):
command_parser = parser.add_parser(cls._name, help=cls._help, dataclass_types=cls._dataclasses)
command_parser.set_defaults(factory_method=cls.build) | ['def', 'register_subcommand(cls,', 'parser:', 'InseqArgumentParser):', 'command_parser', '=', 'parser.add_parser(cls._name,', 'help=cls._help,', 'dataclass_types=cls._dataclasses)', 'command_parser.set_defaults(factory_method=cls.build)'] | 613,936 |
akandykeller/NeuralWaveMachines | jaxline_configs.py | benchmark_rgn_sweep | benchmark_rgn_sweep | RGN sweep for the benchmark paper. | [
"RGN",
"sweep",
"for",
"the",
"benchmark",
"paper."
] | def benchmark_rgn_sweep():
model_config = copy.deepcopy(default_config_dict)
model_config.name = 'RGN'
sweeps = list()
for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]:
for residual in (True, False):
sweeps.append({config_prefix + 'optimizer.kwargs.learning_rate': 0.00015, model_prefix ... | ['def', 'benchmark_rgn_sweep():', 'model_config', '=', 'copy.deepcopy(default_config_dict)', 'model_config.name', '=', "'RGN'", 'sweeps', '=', 'list()', 'for', 'elbo_beta_final', 'in', '[0.001,', '0.1,', '1.0,', '2.0]:', 'for', 'residual', 'in', '(True,', 'False):', 'sweeps.append({config_prefix', '+', "'optimizer.kwar... | 293,533 |
sek788432/Waymo-2D-Object-Detection | tfexample_utils.py | create_classification_example | create_classification_example | Creates image and labels for image classification input pipeline. | [
"Creates",
"image",
"and",
"labels",
"for",
"image",
"classification",
"input",
"pipeline."
] | def create_classification_example(image_height: int, image_width: int, image_format: str='JPEG', is_multilabel: bool=False) -> tf.train.Example:
image = _encode_image(np.uint8(np.random.rand(image_height, image_width, 3) * 255), fmt=image_format)
labels = [0, 1] if is_multilabel else [0]
serialized_example ... | ['def', 'create_classification_example(image_height:', 'int,', 'image_width:', 'int,', 'image_format:', "str='JPEG',", 'is_multilabel:', 'bool=False)', '->', 'tf.train.Example:', 'image', '=', '_encode_image(np.uint8(np.random.rand(image_height,', 'image_width,', '3)', '*', '255),', 'fmt=image_format)', 'labels', '=', ... | 973,063 |
Div99/LISA | verifier.py | ActionInstr.verify_action | verify_action | Each action instruction class should implement this method to verify the action. | [
"Each",
"action",
"instruction",
"class",
"should",
"implement",
"this",
"method",
"to",
"verify",
"the",
"action."
] | def verify_action(self):
raise NotImplementedError | ['def', 'verify_action(self):', 'raise', 'NotImplementedError'] | 216,942 |
fcjian/TOOD | test_atss_head.py | test_atss_head_loss | test_atss_head_loss | Tests atss head loss when truth is empty and non-empty. | [
"Tests",
"atss",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_atss_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
train_cfg = mmcv.Config(dict(assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False))
self = ATSSHead(num_classes=4, in_channels=1, train_cfg=train_cfg,... | ['def', 'test_atss_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'train_cfg', '=', "mmcv.Config(dict(assigner=dict(type='ATSSAssigner',", 'topk=9),', 'allowed_border=-1,', 'pos_weight=-1,', 'debug=False))', 'self', '... | 902,309 |
gunthercox/ChatterBot | corpus.py | read_corpus | read_corpus | Read and return the data from a corpus json file. | [
"Read",
"and",
"return",
"the",
"data",
"from",
"a",
"corpus",
"json",
"file."
] | def read_corpus(file_name):
try:
import yaml
except ImportError:
message = 'Unable to import "yaml".\nPlease install "pyyaml" to enable chatterbot corpus functionality:\npip3 install pyyaml'
raise OptionalDependencyImportError(message)
with io.open(file_name, encoding='utf-8') as dat... | ['def', 'read_corpus(file_name):', 'try:', 'import', 'yaml', 'except', 'ImportError:', 'message', '=', "'Unable", 'to', 'import', '"yaml".\\nPlease', 'install', '"pyyaml"', 'to', 'enable', 'chatterbot', 'corpus', 'functionality:\\npip3', 'install', "pyyaml'", 'raise', 'OptionalDependencyImportError(message)', 'with', '... | 478,030 |
hamza-murad/AALU | speech_to_text_v1.py | WordError.from_dict | from_dict | Initialize a WordError object from a json dictionary. | [
"Initialize",
"a",
"WordError",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'WordError':
args = {}
valid_keys = ['element']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class WordError: ' + ', '.join(bad_keys))
if 'element' in _dict:
args['element... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'WordError':", 'args', '=', '{}', 'valid_keys', '=', "['element']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'WordError:', "'", '+', "'... | 6,085 |
weimin17/Object-Detection_HelmetDetection | mst_ops_test.py | MstOpsTest.testMaximumSpanningTree | testMaximumSpanningTree | Tests that the MST op can recover a simple tree. | [
"Tests",
"that",
"the",
"MST",
"op",
"can",
"recover",
"a",
"simple",
"tree."
] | def testMaximumSpanningTree(self):
with self.test_session() as session:
num_nodes = tf.constant([4, 3], tf.int32)
scores = tf.constant([[[0, 0, 0, 0], [1, 0, 0, 0], [1, 2, 0, 0], [1, 2, 3, 4]], [[4, 3, 2, 9], [0, 0, 2, 9], [0, 0, 0, 9], [9, 9, 9, 9]]], tf.int32)
mst_outputs = mst_ops.maximum... | ['def', 'testMaximumSpanningTree(self):', 'with', 'self.test_session()', 'as', 'session:', 'num_nodes', '=', 'tf.constant([4,', '3],', 'tf.int32)', 'scores', '=', 'tf.constant([[[0,', '0,', '0,', '0],', '[1,', '0,', '0,', '0],', '[1,', '2,', '0,', '0],', '[1,', '2,', '3,', '4]],', '[[4,', '3,', '2,', '9],', '[0,', '0,'... | 753,342 |
salesforce/CodeRL | quant_trainer.py | configure_model | configure_model | Function called before the training loop. | [
"Function",
"called",
"before",
"the",
"training",
"loop."
] | def configure_model(model, args, calib=False, eval=False):
logger.info('Configuring Model for Quantization')
logger.info(f'using quantization package {pytorch_quantization.__file__}')
if not calib:
if args.quant_disable_embeddings:
set_quantizer_by_name(model, ['embeddings'], which='weig... | ['def', 'configure_model(model,', 'args,', 'calib=False,', 'eval=False):', "logger.info('Configuring", 'Model', 'for', "Quantization')", "logger.info(f'using", 'quantization', 'package', "{pytorch_quantization.__file__}')", 'if', 'not', 'calib:', 'if', 'args.quant_disable_embeddings:', 'set_quantizer_by_name(model,', "... | 493,836 |
vghost2008/wml1 | hparams_config.py | Config.parse_from_str | parse_from_str | parse from a string in format 'x=a,y=2' and return the dict. | [
"parse",
"from",
"a",
"string",
"in",
"format",
"'x=a,y=2'",
"and",
"return",
"the",
"dict."
] | def parse_from_str(self, config_str):
if not config_str:
return {}
config_dict = {}
try:
for kv_pair in config_str.split(','):
if not kv_pair:
continue
(k, v) = kv_pair.split('=')
config_dict[k.strip()] = eval_str_fn(v.strip())
retu... | ['def', 'parse_from_str(self,', 'config_str):', 'if', 'not', 'config_str:', 'return', '{}', 'config_dict', '=', '{}', 'try:', 'for', 'kv_pair', 'in', "config_str.split(','):", 'if', 'not', 'kv_pair:', 'continue', '(k,', 'v)', '=', "kv_pair.split('=')", 'config_dict[k.strip()]', '=', 'eval_str_fn(v.strip())', 'return', ... | 960,271 |
intel/neural-compressor | tuning_space.py | TuningSpace.query_item_option | query_item_option | Query the method value, such as scheme, algorithm. | [
"Query",
"the",
"method",
"value,",
"such",
"as",
"scheme,",
"algorithm."
] | def query_item_option(self, op_name_type, path, method_name, method_val):
mode_item = self.get_item_by_path((op_name_type, *path))
if not mode_item:
return None
method_item = mode_item.get_option_by_name(method_name)
return method_item is not None and method_val in method_item.options | ['def', 'query_item_option(self,', 'op_name_type,', 'path,', 'method_name,', 'method_val):', 'mode_item', '=', 'self.get_item_by_path((op_name_type,', '*path))', 'if', 'not', 'mode_item:', 'return', 'None', 'method_item', '=', 'mode_item.get_option_by_name(method_name)', 'return', 'method_item', 'is', 'not', 'None', 'a... | 738,770 |
rudranil723/mini-main | font_manager.py | FontManager.get_default_size | get_default_size | Return the default font size. | [
"Return",
"the",
"default",
"font",
"size."
] | def get_default_size():
return mpl.rcParams['font.size'] | ['def', 'get_default_size():', 'return', "mpl.rcParams['font.size']"] | 319,456 |
eddylau328/fyp-artificial-intelligence-ac-control-device | message_test.py | Proto2Test.testAssignInvalidEnum | testAssignInvalidEnum | Assigning an invalid enum number is not allowed in proto2. | [
"Assigning",
"an",
"invalid",
"enum",
"number",
"is",
"not",
"allowed",
"in",
"proto2."
] | def testAssignInvalidEnum(self):
m = unittest_pb2.TestAllTypes()
with self.assertRaises(ValueError) as _:
m.optional_nested_enum = 1234567
self.assertRaises(ValueError, m.repeated_nested_enum.append, 1234567)
m.repeated_nested_enum.append(2)
m.repeated_nested_enum[0] = 2
with self.assert... | ['def', 'testAssignInvalidEnum(self):', 'm', '=', 'unittest_pb2.TestAllTypes()', 'with', 'self.assertRaises(ValueError)', 'as', '_:', 'm.optional_nested_enum', '=', '1234567', 'self.assertRaises(ValueError,', 'm.repeated_nested_enum.append,', '1234567)', 'm.repeated_nested_enum.append(2)', 'm.repeated_nested_enum[0]', ... | 215,349 |
mariacer/cl_in_rnns | hnet_interface.py | HyperNetInterface.num_task_embs | num_task_embs | Getter for read-only attribute :attr:`num_task_embs`. | [
"Getter",
"for",
"read-only",
"attribute",
":attr:`num_task_embs`."
] | def num_task_embs(self):
warn('Please use attribute "num_known_conds", as attribute will be ' + 'deleted in the future.', DeprecationWarning)
return self.num_known_conds | ['def', 'num_task_embs(self):', "warn('Please", 'use', 'attribute', '"num_known_conds",', 'as', 'attribute', 'will', 'be', "'", '+', "'deleted", 'in', 'the', "future.',", 'DeprecationWarning)', 'return', 'self.num_known_conds'] | 122,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.