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
shanglianlm0525/CvPytorch
config.py
Configuration.print
print
This function will create a copy of self and removes all the 'data' key for better print format.
[ "This", "function", "will", "create", "a", "copy", "of", "self", "and", "removes", "all", "the", "'data'", "key", "for", "better", "print", "format." ]
def print(self): _self = deepcopy(self) def _pop_data_key(d, r): for (k, v) in r.items(): if k == 'data' or k.startswith('_'): d.pop(k) if isinstance(v, UserDict): _pop_data_key(d[k], v) _pop_data_key(_self, self) pprint.pprint(_self)
['def', 'print(self):', '_self', '=', 'deepcopy(self)', 'def', '_pop_data_key(d,', 'r):', 'for', '(k,', 'v)', 'in', 'r.items():', 'if', 'k', '==', "'data'", 'or', "k.startswith('_'):", 'd.pop(k)', 'if', 'isinstance(v,', 'UserDict):', '_pop_data_key(d[k],', 'v)', '_pop_data_key(_self,', 'self)', 'pprint.pprint(_self)']
523,621
Ruturaj123/Flowchart-Detection
model.py
Model.predict
predict
Predict the labels on a single batch of examples.
[ "Predict", "the", "labels", "on", "a", "single", "batch", "of", "examples." ]
def predict(self, sess, x, y=None): cur_memory = sess.run([self.mem_keys, self.mem_vals, self.mem_age]) outputs = [self.y_preds] if y is None: ret = sess.run(outputs, feed_dict={self.x: x}) else: ret = sess.run(outputs, feed_dict={self.x: x, self.y: y}) sess.run([self.mem_reset_op], ...
['def', 'predict(self,', 'sess,', 'x,', 'y=None):', 'cur_memory', '=', 'sess.run([self.mem_keys,', 'self.mem_vals,', 'self.mem_age])', 'outputs', '=', '[self.y_preds]', 'if', 'y', 'is', 'None:', 'ret', '=', 'sess.run(outputs,', 'feed_dict={self.x:', 'x})', 'else:', 'ret', '=', 'sess.run(outputs,', 'feed_dict={self.x:',...
585,817
asyml/texar-pytorch
bleu_moses_test.py
BLEUMosesTest.test_sentence_numpy
test_sentence_numpy
Tests with numpy format.
[ "Tests", "with", "numpy", "format." ]
def test_sentence_numpy(self): hypothesis = 'this is a test sentence to evaluate the good bleu score . è¯Â\x8d' hypothesis = np.array(hypothesis.split()) references = ['this is a test sentence to evaluate the bleu score .', 'this is a test sentence to evaluate the good score .'] references = np.array(...
['def', 'test_sentence_numpy(self):', 'hypothesis', '=', "'this", 'is', 'a', 'test', 'sentence', 'to', 'evaluate', 'the', 'good', 'bleu', 'score', '.', "è¯Â\\x8d'", 'hypothesis', '=', 'np.array(hypothesis.split())', 'references', '=', "['this", 'is', 'a', 'test', 'sentence', 'to', 'evaluate', 'the', 'bleu', 'score', ...
924,899
gunthercox/ChatterBot
attributes.py
History.non_added
non_added
Return a collection of unchanged + deleted.
[ "Return", "a", "collection", "of", "unchanged", "+", "deleted." ]
def non_added(self): return (self.unchanged or []) + (self.deleted or [])
['def', 'non_added(self):', 'return', '(self.unchanged', 'or', '[])', '+', '(self.deleted', 'or', '[])']
534,427
mj-will/nessai
test_resume.py
test_checkpoint_resume_integration
test_checkpoint_resume_integration
Integration test for checkpointing the sampler.
[ "Integration", "test", "for", "checkpointing", "the", "sampler." ]
def test_checkpoint_resume_integration(complete_sampler, model): complete_sampler.likelihood_evaluations = [1, 2] complete_sampler.checkpoint() resume_file = os.path.join(complete_sampler.output, complete_sampler.resume_file) assert os.path.exists(resume_file) ns = NestedSampler.resume(resume_file, ...
['def', 'test_checkpoint_resume_integration(complete_sampler,', 'model):', 'complete_sampler.likelihood_evaluations', '=', '[1,', '2]', 'complete_sampler.checkpoint()', 'resume_file', '=', 'os.path.join(complete_sampler.output,', 'complete_sampler.resume_file)', 'assert', 'os.path.exists(resume_file)', 'ns', '=', 'Nest...
293,034
xrick/tensorflow_nlp
crf.py
crf_log_norm
crf_log_norm
Computes the normalization for a CRF.
[ "Computes", "the", "normalization", "for", "a", "CRF." ]
def crf_log_norm(inputs, sequence_lengths, transition_params): first_input = array_ops.slice(inputs, [0, 0, 0], [-1, 1, -1]) first_input = array_ops.squeeze(first_input, [1]) rest_of_input = array_ops.slice(inputs, [0, 1, 0], [-1, -1, -1]) forward_cell = CrfForwardRnnCell(transition_params) (_, alph...
['def', 'crf_log_norm(inputs,', 'sequence_lengths,', 'transition_params):', 'first_input', '=', 'array_ops.slice(inputs,', '[0,', '0,', '0],', '[-1,', '1,', '-1])', 'first_input', '=', 'array_ops.squeeze(first_input,', '[1])', 'rest_of_input', '=', 'array_ops.slice(inputs,', '[0,', '1,', '0],', '[-1,', '-1,', '-1])', '...
922,493
kornia/kornia
face_detection.py
FaceDetectorResult.top_left
top_left
The [x y] position of the top-left coordinate of the bounding box.
[ "The", "[x", "y]", "position", "of", "the", "top-left", "coordinate", "of", "the", "bounding", "box." ]
def top_left(self) -> torch.Tensor: return self._data[..., (0, 1)]
['def', 'top_left(self)', '->', 'torch.Tensor:', 'return', 'self._data[...,', '(0,', '1)]']
621,592
rlworkgroup/garage
gaussian_cnn_baseline.py
GaussianCNNBaseline.predict
predict
Predict ys based on input xs.
[ "Predict", "ys", "based", "on", "input", "xs." ]
def predict(self, paths): xs = paths['observations'] if isinstance(self._env_spec.observation_space, akro.Image) and len(xs[0].shape) < len(self._env_spec.observation_space.shape): xs = self._env_spec.observation_space.unflatten_n(xs) return self._f_predict(xs).flatten()
['def', 'predict(self,', 'paths):', 'xs', '=', "paths['observations']", 'if', 'isinstance(self._env_spec.observation_space,', 'akro.Image)', 'and', 'len(xs[0].shape)', '<', 'len(self._env_spec.observation_space.shape):', 'xs', '=', 'self._env_spec.observation_space.unflatten_n(xs)', 'return', 'self._f_predict(xs).flatt...
200,538
ZumoLabs/zpy
output.py
Output.output_annotations
output_annotations
Output annotations to file.
[ "Output", "annotations", "to", "file." ]
def output_annotations(self, annotation_path: Union[Path, str]=None) -> Path: if annotation_path is None: annotation_path = self.annotation_path log.info(f'Outputting annotation file to {annotation_path}') annotation_path = zpy.files.verify_path(annotation_path) return annotation_path
['def', 'output_annotations(self,', 'annotation_path:', 'Union[Path,', 'str]=None)', '->', 'Path:', 'if', 'annotation_path', 'is', 'None:', 'annotation_path', '=', 'self.annotation_path', "log.info(f'Outputting", 'annotation', 'file', 'to', "{annotation_path}')", 'annotation_path', '=', 'zpy.files.verify_path(annotatio...
972,090
google-research/ssl_detection
model_utils.py
get_shape_str
get_shape_str
Internally used by layer registry, to print shapes of inputs/outputs of layers.
[ "Internally", "used", "by", "layer", "registry,", "to", "print", "shapes", "of", "inputs/outputs", "of", "layers." ]
def get_shape_str(tensors): if isinstance(tensors, (list, tuple)): for v in tensors: assert isinstance(v, (tf.Tensor, tf.Variable)), 'Not a tensor: {}'.format(type(v)) shape_str = ', '.join(map(get_shape_str, tensors)) else: assert isinstance(tensors, (tf.Tensor, tf.Variable)...
['def', 'get_shape_str(tensors):', 'if', 'isinstance(tensors,', '(list,', 'tuple)):', 'for', 'v', 'in', 'tensors:', 'assert', 'isinstance(v,', '(tf.Tensor,', 'tf.Variable)),', "'Not", 'a', 'tensor:', "{}'.format(type(v))", 'shape_str', '=', "',", "'.join(map(get_shape_str,", 'tensors))', 'else:', 'assert', 'isinstance(...
382,278
TrellixVulnTeam/Unsupervised_Learning_HFI7
figure.py
Figure.get_dpi
get_dpi
Return the resolution in dots per inch as a float.
[ "Return", "the", "resolution", "in", "dots", "per", "inch", "as", "a", "float." ]
def get_dpi(self): return self.dpi
['def', 'get_dpi(self):', 'return', 'self.dpi']
450,418
LeonhardFeiner/sparse_rcnn
bbox.py
calc_start_end
calc_start_end
Converts size and position of boxes to their start and stop coordinates.
[ "Converts", "size", "and", "position", "of", "boxes", "to", "their", "start", "and", "stop", "coordinates." ]
def calc_start_end(position: torch.tensor, size: torch.tensor) -> Tuple[torch.tensor, torch.tensor]: half_size = size / 2 start = position - half_size end = position + half_size return (start, end)
['def', 'calc_start_end(position:', 'torch.tensor,', 'size:', 'torch.tensor)', '->', 'Tuple[torch.tensor,', 'torch.tensor]:', 'half_size', '=', 'size', '/', '2', 'start', '=', 'position', '-', 'half_size', 'end', '=', 'position', '+', 'half_size', 'return', '(start,', 'end)']
894,706
datature/portal
routes.py
clear_cachelist
clear_cachelist
Clear the cached list of predictions.
[ "Clear", "the", "cached", "list", "of", "predictions." ]
def clear_cachelist(model_id) -> tuple: global_store.clear_predicted_images(model_id) return Response(status=200)
['def', 'clear_cachelist(model_id)', '->', 'tuple:', 'global_store.clear_predicted_images(model_id)', 'return', 'Response(status=200)']
820,929
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
configHandler.py
IdleUserConfParser.RemoveEmptySections
RemoveEmptySections
Remove any sections that have no options.
[ "Remove", "any", "sections", "that", "have", "no", "options." ]
def RemoveEmptySections(self): for section in self.sections(): if not self.GetOptionList(section): self.remove_section(section)
['def', 'RemoveEmptySections(self):', 'for', 'section', 'in', 'self.sections():', 'if', 'not', 'self.GetOptionList(section):', 'self.remove_section(section)']
430,793
vmware-archive/salt-contrib
win_update.py
download
download
Cache updates for later install.
[ "Cache", "updates", "for", "later", "install." ]
def download(name, categories=None, includes=None, retries=10): ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} log.debug('categories to search for are: {0}'.format(str(categories))) quidditch = PyWinUpdater() quidditch.SetCategories(categories) quidditch.SetIncludes(includes) ...
['def', 'download(name,', 'categories=None,', 'includes=None,', 'retries=10):', 'ret', '=', "{'name':", 'name,', "'result':", 'True,', "'changes':", '{},', "'comment':", "''}", "log.debug('categories", 'to', 'search', 'for', 'are:', "{0}'.format(str(categories)))", 'quidditch', '=', 'PyWinUpdater()', 'quidditch.SetCate...
328,949
microsoft/fastseq
test_api_decorator.py
APIDecoratorTest.test_replace_baseclass
test_replace_baseclass
Test replace() decorator for the base class.
[ "Test", "replace()", "decorator", "for", "the", "base", "class." ]
def test_replace_baseclass(self): preloaded_classes = {} preloaded_classes['grandchild'] = Grandchild child = Child() grandchild = Grandchild() preloaded_grandchild = preloaded_classes['grandchild']() self.assertEqual(child.name(), 'Base') self.assertEqual(grandchild.name(), 'Base') self...
['def', 'test_replace_baseclass(self):', 'preloaded_classes', '=', '{}', "preloaded_classes['grandchild']", '=', 'Grandchild', 'child', '=', 'Child()', 'grandchild', '=', 'Grandchild()', 'preloaded_grandchild', '=', "preloaded_classes['grandchild']()", 'self.assertEqual(child.name(),', "'Base')", 'self.assertEqual(gran...
559,954
BillZito/transfer-learning
tfhub_text_classification_model.py
TFHubTextClassificationModel.predict
predict
Generates predictions for the specified input samples.
[ "Generates", "predictions", "for", "the", "specified", "input", "samples." ]
def predict(self, input_samples): if self._model is None: raise ValueError('The model must be trained or loaded before predicting.') if isinstance(input_samples, str): input_samples = [input_samples] return tf.sigmoid(self._model.predict(input_samples)).numpy()
['def', 'predict(self,', 'input_samples):', 'if', 'self._model', 'is', 'None:', 'raise', "ValueError('The", 'model', 'must', 'be', 'trained', 'or', 'loaded', 'before', "predicting.')", 'if', 'isinstance(input_samples,', 'str):', 'input_samples', '=', '[input_samples]', 'return', 'tf.sigmoid(self._model.predict(input_sa...
928,540
microsoft/maro
zmq_driver.py
ZmqDriver.close
close
Close ZMQ context and sockets.
[ "Close", "ZMQ", "context", "and", "sockets." ]
def close(self): self._zmq_context.setsockopt(zmq.LINGER, 0) self._broadcast_receiver.close() self._broadcast_sender.close() self._unicast_receiver.close() for unicast_sender in self._unicast_sender_dict.values(): unicast_sender.close() self._zmq_context.term()
['def', 'close(self):', 'self._zmq_context.setsockopt(zmq.LINGER,', '0)', 'self._broadcast_receiver.close()', 'self._broadcast_sender.close()', 'self._unicast_receiver.close()', 'for', 'unicast_sender', 'in', 'self._unicast_sender_dict.values():', 'unicast_sender.close()', 'self._zmq_context.term()']
628,379
myothida/Supervised-Machine-Learning
test_format.py
assert_filepath_or_buffer_equals
assert_filepath_or_buffer_equals
Assertion helper for checking filepath_or_buffer.
[ "Assertion", "helper", "for", "checking", "filepath_or_buffer." ]
def assert_filepath_or_buffer_equals(filepath_or_buffer, filepath_or_buffer_id, encoding): def _assert_filepath_or_buffer_equals(expected): if filepath_or_buffer_id == 'string': with open(filepath_or_buffer, encoding=encoding) as f: result = f.read() elif filepath_or_buf...
['def', 'assert_filepath_or_buffer_equals(filepath_or_buffer,', 'filepath_or_buffer_id,', 'encoding):', 'def', '_assert_filepath_or_buffer_equals(expected):', 'if', 'filepath_or_buffer_id', '==', "'string':", 'with', 'open(filepath_or_buffer,', 'encoding=encoding)', 'as', 'f:', 'result', '=', 'f.read()', 'elif', 'filep...
443,756
deepmind/dm_control
primitive.py
Primitive.touch
touch
Exposing the touch sensor for observations and reward.
[ "Exposing", "the", "touch", "sensor", "for", "observations", "and", "reward." ]
def touch(self): return self._touch
['def', 'touch(self):', 'return', 'self._touch']
165,169
Kvatsx/Artificial-Intelligence-Assignments
backend_wx.py
MenuButtonWx.getActiveAxes
getActiveAxes
Return a list of the selected axes.
[ "Return", "a", "list", "of", "the", "selected", "axes." ]
def getActiveAxes(self): active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active
['def', 'getActiveAxes(self):', 'active', '=', '[]', 'for', 'i', 'in', 'range(len(self._axisId)):', 'if', 'self._menu.IsChecked(self._axisId[i]):', 'active.append(i)', 'return', 'active']
1,261
deepmind/acme
networks.py
add_batch
add_batch
Adds a batch dimension at axis 0 to the leaves of a nested structure.
[ "Adds", "a", "batch", "dimension", "at", "axis", "0", "to", "the", "leaves", "of", "a", "nested", "structure." ]
def add_batch(nest, batch_size: Optional[int]): broadcast = lambda x: jnp.broadcast_to(x, (batch_size,) + x.shape) return jax.tree_map(broadcast, nest)
['def', 'add_batch(nest,', 'batch_size:', 'Optional[int]):', 'broadcast', '=', 'lambda', 'x:', 'jnp.broadcast_to(x,', '(batch_size,)', '+', 'x.shape)', 'return', 'jax.tree_map(broadcast,', 'nest)']
8,147
Eric3911/OpenAGI
snapshot.py
Snapshot.full
full
Whether the number of snapshots it keeps track of is greater than the max_size.
[ "Whether", "the", "number", "of", "snapshots", "it", "keeps", "track", "of", "is", "greater", "than", "the", "max_size." ]
def full(self): return not self._save_all and len(self.records) > self.max_size
['def', 'full(self):', 'return', 'not', 'self._save_all', 'and', 'len(self.records)', '>', 'self.max_size']
251,859
sjtu-marl/malib
offline_dataset_server.py
OfflineDataset.start_consumer_pipe
start_consumer_pipe
Start a consumer pipeline, if there is no such a table that named as `name`, the function will be stucked until the table has been created.
[ "Start", "a", "consumer", "pipeline,", "if", "there", "is", "no", "such", "a", "table", "that", "named", "as", "`name`,", "the", "function", "will", "be", "stucked", "until", "the", "table", "has", "been", "created." ]
def start_consumer_pipe(self, name: str, batch_size: int) -> Tuple[str, Queue]: queue_id = f'{name}_{time.time()}' queue = Queue(actor_options={'num_cpus': 0}) self.reader_queues[queue_id] = queue while name not in self.buffers: time.sleep(1) self.thread_pool.submit(read_table, self.markers[...
['def', 'start_consumer_pipe(self,', 'name:', 'str,', 'batch_size:', 'int)', '->', 'Tuple[str,', 'Queue]:', 'queue_id', '=', "f'{name}_{time.time()}'", 'queue', '=', "Queue(actor_options={'num_cpus':", '0})', 'self.reader_queues[queue_id]', '=', 'queue', 'while', 'name', 'not', 'in', 'self.buffers:', 'time.sleep(1)', '...
627,449
ForrestPi/ObjectDetectionTricks
util.py
image_idct
image_idct
Inverts image_dct(), by performing a type-III DCT.
[ "Inverts", "image_dct(),", "by", "performing", "a", "type-III", "DCT." ]
def image_idct(dct_x): dct_x = torch.as_tensor(dct_x) dct_y = torch_dct.idct(torch.transpose(dct_x, 1, 2), norm='ortho') image = torch_dct.idct(torch.transpose(dct_y, 1, 2), norm='ortho') return image
['def', 'image_idct(dct_x):', 'dct_x', '=', 'torch.as_tensor(dct_x)', 'dct_y', '=', 'torch_dct.idct(torch.transpose(dct_x,', '1,', '2),', "norm='ortho')", 'image', '=', 'torch_dct.idct(torch.transpose(dct_y,', '1,', '2),', "norm='ortho')", 'return', 'image']
744,665
SvenGronauer/phoenix-drone-simulation
train.py
run_training
run_training
Executes one training loop with given parameters.
[ "Executes", "one", "training", "loop", "with", "given", "parameters." ]
def run_training(args, unparsed_args, exp_name=None): physical_cores = 2 ** int(np.log2(psutil.cpu_count(logical=False))) use_number_of_threads = True if args.cores > physical_cores else False if mpi_fork(args.cores, use_number_of_threads=use_number_of_threads): sys.exit() mpi_print('Unknowns:',...
['def', 'run_training(args,', 'unparsed_args,', 'exp_name=None):', 'physical_cores', '=', '2', '**', 'int(np.log2(psutil.cpu_count(logical=False)))', 'use_number_of_threads', '=', 'True', 'if', 'args.cores', '>', 'physical_cores', 'else', 'False', 'if', 'mpi_fork(args.cores,', 'use_number_of_threads=use_number_of_threa...
769,051
triaquae/triaquae
forms.py
PLREGONField.has_valid_checksum
has_valid_checksum
Calculates a checksum with the provided algorithm.
[ "Calculates", "a", "checksum", "with", "the", "provided", "algorithm." ]
def has_valid_checksum(self, number): weights = ((8, 9, 2, 3, 4, 5, 6, 7, -1), (2, 4, 8, 5, 0, 9, 7, 3, 6, 1, 2, 4, 8, -1), (8, 9, 2, 3, 4, 5, 6, 7, -1, 0, 0, 0, 0, 0)) weights = [table for table in weights if len(table) == len(number)] for table in weights: checksum = sum([int(n) * w for (n, w) in ...
['def', 'has_valid_checksum(self,', 'number):', 'weights', '=', '((8,', '9,', '2,', '3,', '4,', '5,', '6,', '7,', '-1),', '(2,', '4,', '8,', '5,', '0,', '9,', '7,', '3,', '6,', '1,', '2,', '4,', '8,', '-1),', '(8,', '9,', '2,', '3,', '4,', '5,', '6,', '7,', '-1,', '0,', '0,', '0,', '0,', '0))', 'weights', '=', '[table'...
358,099
sek788432/Waymo-2D-Object-Detection
dataset_loader.py
KittiRaw.load_pose_sequence
load_pose_sequence
Returns a sequence of pose vectors for frames around the target frame.
[ "Returns", "a", "sequence", "of", "pose", "vectors", "for", "frames", "around", "the", "target", "frame." ]
def load_pose_sequence(self, frames, target_index): (target_drive, _, target_frame_id) = frames[target_index].split(' ') target_pose = self.load_pose_raw(target_drive, target_frame_id) (start_index, end_index) = get_seq_start_end(target_frame_id, self.seq_length) pose_seq = [] for index in range(sta...
['def', 'load_pose_sequence(self,', 'frames,', 'target_index):', '(target_drive,', '_,', 'target_frame_id)', '=', "frames[target_index].split('", "')", 'target_pose', '=', 'self.load_pose_raw(target_drive,', 'target_frame_id)', '(start_index,', 'end_index)', '=', 'get_seq_start_end(target_frame_id,', 'self.seq_length)'...
975,913
googleapis/python-aiplatform
test_model_monitoring.py
TestModelDeploymentMonitoring.test_mdm_two_models_one_valid_config
test_mdm_two_models_one_valid_config
Enable model monitoring on two existing models deployed to the same endpoint.
[ "Enable", "model", "monitoring", "on", "two", "existing", "models", "deployed", "to", "the", "same", "endpoint." ]
def test_mdm_two_models_one_valid_config(self, shared_state): assert len(shared_state['resources']) == 1 self.endpoint = shared_state['resources'][0] aiplatform.init(project=e2e_base._PROJECT, location=e2e_base._LOCATION) job = aiplatform.ModelDeploymentMonitoringJob.create(display_name=self._make_displ...
['def', 'test_mdm_two_models_one_valid_config(self,', 'shared_state):', 'assert', "len(shared_state['resources'])", '==', '1', 'self.endpoint', '=', "shared_state['resources'][0]", 'aiplatform.init(project=e2e_base._PROJECT,', 'location=e2e_base._LOCATION)', 'job', '=', 'aiplatform.ModelDeploymentMonitoringJob.create(d...
862,960
IBM/graph4nlp
bleu_scorer.py
BleuScorer.cook_append
cook_append
called by constructor and __iadd__ to avoid creating new instances.
[ "called", "by", "constructor", "and", "__iadd__", "to", "avoid", "creating", "new", "instances." ]
def cook_append(self, test, refs): if refs is not None: self.crefs.append(cook_refs(refs)) if test is not None: cooked_test = cook_test(test, self.crefs[-1]) self.ctest.append(cooked_test) else: self.ctest.append(None) self._score = None
['def', 'cook_append(self,', 'test,', 'refs):', 'if', 'refs', 'is', 'not', 'None:', 'self.crefs.append(cook_refs(refs))', 'if', 'test', 'is', 'not', 'None:', 'cooked_test', '=', 'cook_test(test,', 'self.crefs[-1])', 'self.ctest.append(cooked_test)', 'else:', 'self.ctest.append(None)', 'self._score', '=', 'None']
580,470
llSourcell/AI_Artist
pyparsing.py
ParseResults.insert
insert
Inserts new element at location index in the list of parsed tokens.
[ "Inserts", "new", "element", "at", "location", "index", "in", "the", "list", "of", "parsed", "tokens." ]
def insert(self, index, insStr): self.__toklist.insert(index, insStr) for (name, occurrences) in self.__tokdict.items(): for (k, (value, position)) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
['def', 'insert(self,', 'index,', 'insStr):', 'self.__toklist.insert(index,', 'insStr)', 'for', '(name,', 'occurrences)', 'in', 'self.__tokdict.items():', 'for', '(k,', '(value,', 'position))', 'in', 'enumerate(occurrences):', 'occurrences[k]', '=', '_ParseResultsWithOffset(value,', 'position', '+', '(position', '>', '...
413,690
CityU-AIM-Group/SIGMA
wassdistance.py
SinkhornDistance.ave
ave
Barycenter subroutine, used by kinetic acceleration through extrapolation.
[ "Barycenter", "subroutine,", "used", "by", "kinetic", "acceleration", "through", "extrapolation." ]
def ave(u, u1, tau): return tau * u + (1 - tau) * u1
['def', 'ave(u,', 'u1,', 'tau):', 'return', 'tau', '*', 'u', '+', '(1', '-', 'tau)', '*', 'u1']
934,542
rudranil723/mini-main
introspection.py
BaseDatabaseIntrospection.sequence_list
sequence_list
Return a list of information about all DB sequences for all models in all apps.
[ "Return", "a", "list", "of", "information", "about", "all", "DB", "sequences", "for", "all", "models", "in", "all", "apps." ]
def sequence_list(self): from django.apps import apps from django.db import router sequence_list = [] with self.connection.cursor() as cursor: for app_config in apps.get_app_configs(): for model in router.get_migratable_models(app_config, self.connection.alias): if no...
['def', 'sequence_list(self):', 'from', 'django.apps', 'import', 'apps', 'from', 'django.db', 'import', 'router', 'sequence_list', '=', '[]', 'with', 'self.connection.cursor()', 'as', 'cursor:', 'for', 'app_config', 'in', 'apps.get_app_configs():', 'for', 'model', 'in', 'router.get_migratable_models(app_config,', 'self...
315,761
zihuitang/medical_AI_platform
__init__.py
makeLogRecord
makeLogRecord
Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance.
[ "Make", "a", "LogRecord", "whose", "attributes", "are", "defined", "by", "the", "specified", "dictionary,", "This", "function", "is", "useful", "for", "converting", "a", "logging", "event", "received", "over", "a", "socket", "connection", "(which", "is", "sent",...
def makeLogRecord(dict): rv = _logRecordFactory(None, None, '', 0, '', (), None, None) rv.__dict__.update(dict) return rv
['def', 'makeLogRecord(dict):', 'rv', '=', '_logRecordFactory(None,', 'None,', "'',", '0,', "'',", '(),', 'None,', 'None)', 'rv.__dict__.update(dict)', 'return', 'rv']
283,093
ZumoLabs/zpy
blender.py
set_seed
set_seed
Set the random seed (sets the python and numpy seed).
[ "Set", "the", "random", "seed", "(sets", "the", "python", "and", "numpy", "seed)." ]
def set_seed(seed: int=0) -> None: if log.getEffectiveLevel() == logging.DEBUG: seed = random.randint(1, 100) log.info(f'Setting random seed to {seed}') random.seed(seed) np.random.seed(seed) mathutils.noise.seed_set(seed)
['def', 'set_seed(seed:', 'int=0)', '->', 'None:', 'if', 'log.getEffectiveLevel()', '==', 'logging.DEBUG:', 'seed', '=', 'random.randint(1,', '100)', "log.info(f'Setting", 'random', 'seed', 'to', "{seed}')", 'random.seed(seed)', 'np.random.seed(seed)', 'mathutils.noise.seed_set(seed)']
971,962
Eric3911/OpenAGI
freesound_download.py
get_text_query_with_resource_limit_checks
get_text_query_with_resource_limit_checks
Performs a text query, checks for rate / api limits, and retries.
[ "Performs", "a", "text", "query,", "checks", "for", "rate", "/", "api", "limits,", "and", "retries." ]
def get_text_query_with_resource_limit_checks(client, query: str, filters: list, fields: str, page_size: int): pages = None attempts = 20 while pages is None: try: pages = client.text_search(query=query, filter=' '.join(filters), fields=fields, page_size=str(page_size)) except fr...
['def', 'get_text_query_with_resource_limit_checks(client,', 'query:', 'str,', 'filters:', 'list,', 'fields:', 'str,', 'page_size:', 'int):', 'pages', '=', 'None', 'attempts', '=', '20', 'while', 'pages', 'is', 'None:', 'try:', 'pages', '=', 'client.text_search(query=query,', "filter='", "'.join(filters),", 'fields=fie...
274,286
haoxiangsnr/A-Convolutional-Recurrent--Network-for-Real-Time-Speech-Enhancement
utils.py
prepare_empty_dir
prepare_empty_dir
if resume experiment, assert the dirs exist, if not resume experiment, make dirs.
[ "if", "resume", "experiment,", "assert", "the", "dirs", "exist,", "if", "not", "resume", "experiment,", "make", "dirs." ]
def prepare_empty_dir(dirs, resume=False): for dir_path in dirs: if resume: assert dir_path.exists() else: dir_path.mkdir(parents=True, exist_ok=True)
['def', 'prepare_empty_dir(dirs,', 'resume=False):', 'for', 'dir_path', 'in', 'dirs:', 'if', 'resume:', 'assert', 'dir_path.exists()', 'else:', 'dir_path.mkdir(parents=True,', 'exist_ok=True)']
5,089
zackmcnulty/CSE_446-Machine_Learning
_base.py
_AxesBase.get_yaxis
get_yaxis
Return the YAxis instance.
[ "Return", "the", "YAxis", "instance." ]
def get_yaxis(self): return self.yaxis
['def', 'get_yaxis(self):', 'return', 'self.yaxis']
194,859
famura/SimuRLacra
base.py
RecurrentPolicy.hidden_size
hidden_size
Get the number of hidden state variables.
[ "Get", "the", "number", "of", "hidden", "state", "variables." ]
def hidden_size(self) -> int: raise NotImplementedError
['def', 'hidden_size(self)', '->', 'int:', 'raise', 'NotImplementedError']
883,867
triaquae/triaquae
tests.py
AdminSeleniumWebDriverTestCase.admin_login
admin_login
Helper function to log into the admin.
[ "Helper", "function", "to", "log", "into", "the", "admin." ]
def admin_login(self, username, password, login_url='/admin/'): self.selenium.get('%s%s' % (self.live_server_url, login_url)) username_input = self.selenium.find_element_by_name('username') username_input.send_keys(username) password_input = self.selenium.find_element_by_name('password') password_in...
['def', 'admin_login(self,', 'username,', 'password,', "login_url='/admin/'):", "self.selenium.get('%s%s'", '%', '(self.live_server_url,', 'login_url))', 'username_input', '=', "self.selenium.find_element_by_name('username')", 'username_input.send_keys(username)', 'password_input', '=', "self.selenium.find_element_by_n...
357,007
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
metalearner.py
MetaLearner.adapt
adapt
Adapt the parameters of the policy network to a new task, from sampled trajectories `episodes`, with a one-step gradient update [1].
[ "Adapt", "the", "parameters", "of", "the", "policy", "network", "to", "a", "new", "task,", "from", "sampled", "trajectories", "`episodes`,", "with", "a", "one-step", "gradient", "update", "[1]." ]
def adapt(self, episodes, first_order=False): self.baseline.fit(episodes) loss = self.inner_loss(episodes) print('loss: ', loss) params = self.policy.update_params(loss, step_size=self.fast_lr, first_order=first_order) return params
['def', 'adapt(self,', 'episodes,', 'first_order=False):', 'self.baseline.fit(episodes)', 'loss', '=', 'self.inner_loss(episodes)', "print('loss:", "',", 'loss)', 'params', '=', 'self.policy.update_params(loss,', 'step_size=self.fast_lr,', 'first_order=first_order)', 'return', 'params']
433,081
intra2net/guibot
test_finder.py
FinderTest.test_deep_cache
test_deep_cache
Test the neural network cached storage of deep finders.
[ "Test", "the", "neural", "network", "cached", "storage", "of", "deep", "finders." ]
def test_deep_cache(self): finder = DeepFinder(synchronize=False) finder.params['deep']['arch'].value = 'fasterrcnn_resnet50_fpn' finder.synchronize_backend() matches = finder.find(Pattern('cat'), Image('coco_cat')) self.assertEqual(len(matches), 1) self.assertEqual(len(finder._cache.keys()), 1)...
['def', 'test_deep_cache(self):', 'finder', '=', 'DeepFinder(synchronize=False)', "finder.params['deep']['arch'].value", '=', "'fasterrcnn_resnet50_fpn'", 'finder.synchronize_backend()', 'matches', '=', "finder.find(Pattern('cat'),", "Image('coco_cat'))", 'self.assertEqual(len(matches),', '1)', 'self.assertEqual(len(fi...
572,662
omonimus1/super-computer-
req_file.py
RequirementsFileParser.parse
parse
Parse a given file, yielding parsed lines.
[ "Parse", "a", "given", "file,", "yielding", "parsed", "lines." ]
def parse(self, filename, constraint): for line in self._parse_and_recurse(filename, constraint): yield line
['def', 'parse(self,', 'filename,', 'constraint):', 'for', 'line', 'in', 'self._parse_and_recurse(filename,', 'constraint):', 'yield', 'line']
913,176
rlgraph/rlgraph
component.py
Component.propagate_variables
propagate_variables
Propagates all variable from this Component to its parents' variable registries.
[ "Propagates", "all", "variable", "from", "this", "Component", "to", "its", "parents'", "variable", "registries." ]
def propagate_variables(self, keys=None): if self.parent_component is None: return keys = keys or self.variable_registry.keys() for key in keys: if key in self.parent_component.variable_registry: if self.variable_registry[key] is not self.parent_component.variable_registry[key]: ...
['def', 'propagate_variables(self,', 'keys=None):', 'if', 'self.parent_component', 'is', 'None:', 'return', 'keys', '=', 'keys', 'or', 'self.variable_registry.keys()', 'for', 'key', 'in', 'keys:', 'if', 'key', 'in', 'self.parent_component.variable_registry:', 'if', 'self.variable_registry[key]', 'is', 'not', 'self.pare...
862,449
ZumoLabs/zpy
cli.py
set_project
set_project
Set project Set global PROJECT uuid.
[ "Set", "project", "Set", "global", "PROJECT", "uuid." ]
def set_project(project_uuid): config = read_config() old_project_uuid = config.get('PROJECT', None) config['PROJECT'] = str(project_uuid) write_config(config) click.echo('Switched project:') click.echo(f" {old_project_uuid} -> {config['PROJECT']}")
['def', 'set_project(project_uuid):', 'config', '=', 'read_config()', 'old_project_uuid', '=', "config.get('PROJECT',", 'None)', "config['PROJECT']", '=', 'str(project_uuid)', 'write_config(config)', "click.echo('Switched", "project:')", 'click.echo(f"', '{old_project_uuid}', '->', '{config[\'PROJECT\']}")']
971,908
digorithm/ArtificialIntelligenceAlgorithms
design_info.py
DesignInfo.terms
terms
A list of :class:`Terms`, in order, or else None.
[ "A", "list", "of", ":class:`Terms`,", "in", "order,", "or", "else", "None." ]
def terms(self): if self.term_slices is None: return None return list(self.term_slices)
['def', 'terms(self):', 'if', 'self.term_slices', 'is', 'None:', 'return', 'None', 'return', 'list(self.term_slices)']
91,930
PaddlePaddle/PARL
actor.py
Actor.self_play
self_play
Collecting training data by self-play.
[ "Collecting", "training", "data", "by", "self-play." ]
def self_play(self, current_weights, game_num): self.current_agent.set_weights(current_weights) train_examples = [] for i in range(game_num): logger.info('self play iteration #{}'.format(i)) self.current_mcts = MCTS(self.game, self.current_agent, self.args, dirichlet_noise=True) trai...
['def', 'self_play(self,', 'current_weights,', 'game_num):', 'self.current_agent.set_weights(current_weights)', 'train_examples', '=', '[]', 'for', 'i', 'in', 'range(game_num):', "logger.info('self", 'play', 'iteration', "#{}'.format(i))", 'self.current_mcts', '=', 'MCTS(self.game,', 'self.current_agent,', 'self.args,'...
277,720
zihuitang/medical_AI_platform
handler.py
EntityResolver.resolveEntity
resolveEntity
Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from.
[ "Resolve", "the", "system", "identifier", "of", "an", "entity", "and", "return", "either", "the", "system", "identifier", "to", "read", "from", "as", "a", "string,", "or", "an", "InputSource", "to", "read", "from." ]
def resolveEntity(self, publicId, systemId): return systemId
['def', 'resolveEntity(self,', 'publicId,', 'systemId):', 'return', 'systemId']
284,604
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
preprocessing.py
crop_image_by_strategy
crop_image_by_strategy
Crops an image according to a strategy defined in config.
[ "Crops", "an", "image", "according", "to", "a", "strategy", "defined", "in", "config." ]
def crop_image_by_strategy(image, cropping): strategy_to_method = {'crop_center': crop_center, 'pad': pad, 'pad200': pad_200, 'pad_crop_central': pad_crop_central} tf.logging.info('Cropping strategy: %s.' % cropping) if cropping not in strategy_to_method: raise ValueError('Unknown cropping strategy:...
['def', 'crop_image_by_strategy(image,', 'cropping):', 'strategy_to_method', '=', "{'crop_center':", 'crop_center,', "'pad':", 'pad,', "'pad200':", 'pad_200,', "'pad_crop_central':", 'pad_crop_central}', "tf.logging.info('Cropping", 'strategy:', "%s.'", '%', 'cropping)', 'if', 'cropping', 'not', 'in', 'strategy_to_meth...
112,254
suarez12138/AI-Reversi_IMP_TextDichotomy
figure.py
Figure.sca
sca
Set the current axes to be *a* and return *a*.
[ "Set", "the", "current", "axes", "to", "be", "*a*", "and", "return", "*a*." ]
def sca(self, a): self._axstack.bubble(a) self._axobservers.process('_axes_change_event', self) return a
['def', 'sca(self,', 'a):', 'self._axstack.bubble(a)', "self._axobservers.process('_axes_change_event',", 'self)', 'return', 'a']
96,475
facebookresearch/fvcore
test_transform.py
TestTransforms.test_noop_transform_no_register
test_noop_transform_no_register
NoOpTransform does not need register - it's by default no-op.
[ "NoOpTransform", "does", "not", "need", "register", "-", "it's", "by", "default", "no-op." ]
def test_noop_transform_no_register(self): t = T.NoOpTransform() self.assertEqual(t.apply_anything(1), 1)
['def', 'test_noop_transform_no_register(self):', 't', '=', 'T.NoOpTransform()', 'self.assertEqual(t.apply_anything(1),', '1)']
566,016
calico/basenji
basenji_sad_multi.py
job_completed
job_completed
Check whether a specific job has generated its output file.
[ "Check", "whether", "a", "specific", "job", "has", "generated", "its", "output", "file." ]
def job_completed(options, pi): out_file = '%s/job%d/sad.h5' % (options.out_dir, pi) return os.path.isfile(out_file) or os.path.isdir(out_file)
['def', 'job_completed(options,', 'pi):', 'out_file', '=', "'%s/job%d/sad.h5'", '%', '(options.out_dir,', 'pi)', 'return', 'os.path.isfile(out_file)', 'or', 'os.path.isdir(out_file)']
94,794
FeiGSSS/DySAT_pytorch
random_walk.py
Graph_RandomWalk.preprocess_transition_probs
preprocess_transition_probs
Preprocessing of transition probabilities for guiding the random walks.
[ "Preprocessing", "of", "transition", "probabilities", "for", "guiding", "the", "random", "walks." ]
def preprocess_transition_probs(self): G = self.G is_directed = self.is_directed alias_nodes = {} for node in G.nodes(): unnormalized_probs = [G[node][nbr]['weight'] for nbr in sorted(G.neighbors(node))] norm_const = sum(unnormalized_probs) normalized_probs = [float(u_prob) / nor...
['def', 'preprocess_transition_probs(self):', 'G', '=', 'self.G', 'is_directed', '=', 'self.is_directed', 'alias_nodes', '=', '{}', 'for', 'node', 'in', 'G.nodes():', 'unnormalized_probs', '=', "[G[node][nbr]['weight']", 'for', 'nbr', 'in', 'sorted(G.neighbors(node))]', 'norm_const', '=', 'sum(unnormalized_probs)', 'no...
555,376
sjtu-marl/malib
manager.py
validate_strategy_specs
validate_strategy_specs
Validate a dict of strategy specs that whether the prob list is legal.
[ "Validate", "a", "dict", "of", "strategy", "specs", "that", "whether", "the", "prob", "list", "is", "legal." ]
def validate_strategy_specs(specs: Dict[str, StrategySpec]): for (rid, spec) in specs.items(): if len(spec) < 1: raise ValueError(f'Empty spec for runtime_id={rid}') expected_prob_list = spec.meta_data.get('prob_list', [1 / len(spec)] * len(spec)) if expected_prob_list is None: ...
['def', 'validate_strategy_specs(specs:', 'Dict[str,', 'StrategySpec]):', 'for', '(rid,', 'spec)', 'in', 'specs.items():', 'if', 'len(spec)', '<', '1:', 'raise', "ValueError(f'Empty", 'spec', 'for', "runtime_id={rid}')", 'expected_prob_list', '=', "spec.meta_data.get('prob_list',", '[1', '/', 'len(spec)]', '*', 'len(sp...
627,545
robustness-gym/robustness-gym
metrics.py
f1_macro
f1_macro
Calculate macro F1 score for multi-class classification.
[ "Calculate", "macro", "F1", "score", "for", "multi-class", "classification." ]
def f1_macro(predictions: Union[list, np.array, torch.Tensor], labels: Union[list, np.array, torch.Tensor]): return f1_score(y_true=labels, y_pred=predictions, average='macro')
['def', 'f1_macro(predictions:', 'Union[list,', 'np.array,', 'torch.Tensor],', 'labels:', 'Union[list,', 'np.array,', 'torch.Tensor]):', 'return', 'f1_score(y_true=labels,', 'y_pred=predictions,', "average='macro')"]
826,263
weimin17/Object-Detection_HelmetDetection
adversarial_attack.py
generate_pgd_common
generate_pgd_common
Common code for generating PGD adversarial examples.
[ "Common", "code", "for", "generating", "PGD", "adversarial", "examples." ]
def generate_pgd_common(x, bounds, model_fn, attack_params, one_hot_labels, perturbation_multiplier): params_list = attack_params.split('_') if len(params_list) != 3: raise ValueError('Invalid parameters of PGD attack: %s' % attack_params) epsilon = int(params_list[0]) step_size = int(params_lis...
['def', 'generate_pgd_common(x,', 'bounds,', 'model_fn,', 'attack_params,', 'one_hot_labels,', 'perturbation_multiplier):', 'params_list', '=', "attack_params.split('_')", 'if', 'len(params_list)', '!=', '3:', 'raise', "ValueError('Invalid", 'parameters', 'of', 'PGD', 'attack:', "%s'", '%', 'attack_params)', 'epsilon',...
761,399
Djaizz/Djaizz
base.py
_PreTrainedMLModelABC.loader
loader
Loader method to load the Model's native object.
[ "Loader", "method", "to", "load", "the", "Model's", "native", "object." ]
def loader(self) -> callable: return import_obj(self.loader_module_and_qualname)
['def', 'loader(self)', '->', 'callable:', 'return', 'import_obj(self.loader_module_and_qualname)']
189,450
allenai/deepfigures-open
file_util.py
extract_tarfile
extract_tarfile
Extract a tarfile at 'src' to 'dst'.
[ "Extract", "a", "tarfile", "at", "'src'", "to", "'dst'." ]
def extract_tarfile(src: str, dst: str, streaming=True) -> None: src = _expand(src) dst = _expand(dst) with open(src, mode='rb', streaming=streaming) as f: b = f.read() extract_tarfile_from_bytes(b, dst)
['def', 'extract_tarfile(src:', 'str,', 'dst:', 'str,', 'streaming=True)', '->', 'None:', 'src', '=', '_expand(src)', 'dst', '=', '_expand(dst)', 'with', 'open(src,', "mode='rb',", 'streaming=streaming)', 'as', 'f:', 'b', '=', 'f.read()', 'extract_tarfile_from_bytes(b,', 'dst)']
520,510
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
Expression.makeAcceptPrePost
makeAcceptPrePost
Make an accept method for pre- and post- assignment expressions.
[ "Make", "an", "accept", "method", "for", "pre-", "and", "post-", "assignment", "expressions." ]
def makeAcceptPrePost(suffix, pre): def acceptPrePost(self, node, memo): factory = self.factory.expr if node.withinExpr: name = node.firstChildOfType(tokens.IDENT).text handler = self.configHandler('VariableNaming') rename = handler(name) block = self...
['def', 'makeAcceptPrePost(suffix,', 'pre):', 'def', 'acceptPrePost(self,', 'node,', 'memo):', 'factory', '=', 'self.factory.expr', 'if', 'node.withinExpr:', 'name', '=', 'node.firstChildOfType(tokens.IDENT).text', 'handler', '=', "self.configHandler('VariableNaming')", 'rename', '=', 'handler(name)', 'block', '=', 'se...
17,347
sek788432/Waymo-2D-Object-Detection
create_coco_tf_record.py
generate_annotations
generate_annotations
Generator for COCO annotations.
[ "Generator", "for", "COCO", "annotations." ]
def generate_annotations(images, image_dir, img_to_obj_annotation=None, img_to_caption_annotation=None, id_to_name_map=None, include_masks=False): for image in images: object_annotation = img_to_obj_annotation.get(image['id'], None) if img_to_obj_annotation else None caption_annotaion = img_to_capti...
['def', 'generate_annotations(images,', 'image_dir,', 'img_to_obj_annotation=None,', 'img_to_caption_annotation=None,', 'id_to_name_map=None,', 'include_masks=False):', 'for', 'image', 'in', 'images:', 'object_annotation', '=', "img_to_obj_annotation.get(image['id'],", 'None)', 'if', 'img_to_obj_annotation', 'else', 'N...
973,046
CentML/DeepView.Profile
Beam.py
Beam.get_the_best_score_and_idx
get_the_best_score_and_idx
Get the score of the best in the beam.
[ "Get", "the", "score", "of", "the", "best", "in", "the", "beam." ]
def get_the_best_score_and_idx(self): (scores, ids) = self.sort_scores() return (scores[1], ids[1])
['def', 'get_the_best_score_and_idx(self):', '(scores,', 'ids)', '=', 'self.sort_scores()', 'return', '(scores[1],', 'ids[1])']
540,892
ahthie7u/cockpit
test_tic.py
AutogradTICTrace.create_graph
create_graph
Return whether access to the forward pass computation graph is needed.
[ "Return", "whether", "access", "to", "the", "forward", "pass", "computation", "graph", "is", "needed." ]
def create_graph(self, global_step): return self.should_compute(global_step)
['def', 'create_graph(self,', 'global_step):', 'return', 'self.should_compute(global_step)']
492,884
gunthercox/ChatterBot
highlight.py
SHORTER
SHORTER
Sort shorter passages first.
[ "Sort", "shorter", "passages", "first." ]
def SHORTER(fragment): return len(fragment)
['def', 'SHORTER(fragment):', 'return', 'len(fragment)']
482,850
lebrice/Sequoia
setting_test.py
TestIncrementalRLSetting.test_monsterkong
test_monsterkong
Checks that the MonsterKong env works fine with pixel and state input.
[ "Checks", "that", "the", "MonsterKong", "env", "works", "fine", "with", "pixel", "and", "state", "input." ]
def test_monsterkong(self, state: bool): setting = self.Setting(dataset='StateMetaMonsterKong-v0' if state else 'PixelMetaMonsterKong-v0', nb_tasks=5, train_max_steps=500, test_max_steps=500, train_transforms=[], test_transforms=[], val_transforms=[], max_episode_steps=10) if state: assert setting.obser...
['def', 'test_monsterkong(self,', 'state:', 'bool):', 'setting', '=', "self.Setting(dataset='StateMetaMonsterKong-v0'", 'if', 'state', 'else', "'PixelMetaMonsterKong-v0',", 'nb_tasks=5,', 'train_max_steps=500,', 'test_max_steps=500,', 'train_transforms=[],', 'test_transforms=[],', 'val_transforms=[],', 'max_episode_ste...
344,540
shiwt03/SSformer
isaid.py
iSAID_convert_from_color
iSAID_convert_from_color
RGB-color encoding to grayscale labels.
[ "RGB-color", "encoding", "to", "grayscale", "labels." ]
def iSAID_convert_from_color(arr_3d, palette=iSAID_invert_palette): arr_2d = np.zeros((arr_3d.shape[0], arr_3d.shape[1]), dtype=np.uint8) for (c, i) in palette.items(): m = np.all(arr_3d == np.array(c).reshape(1, 1, 3), axis=2) arr_2d[m] = i return arr_2d
['def', 'iSAID_convert_from_color(arr_3d,', 'palette=iSAID_invert_palette):', 'arr_2d', '=', 'np.zeros((arr_3d.shape[0],', 'arr_3d.shape[1]),', 'dtype=np.uint8)', 'for', '(c,', 'i)', 'in', 'palette.items():', 'm', '=', 'np.all(arr_3d', '==', 'np.array(c).reshape(1,', '1,', '3),', 'axis=2)', 'arr_2d[m]', '=', 'i', 'retu...
872,031
rudranil723/mini-main
band.py
GDALBand.mean
mean
Return the mean of all pixel values of this band.
[ "Return", "the", "mean", "of", "all", "pixel", "values", "of", "this", "band." ]
def mean(self): return self.statistics()[2]
['def', 'mean(self):', 'return', 'self.statistics()[2]']
315,224
nicknochnack/RealTimeSignLanguageTFJS
center_net_meta_arch_tf2_test.py
get_fake_mask_params
get_fake_mask_params
Returns the fake mask estimation parameter namedtuple.
[ "Returns", "the", "fake", "mask", "estimation", "parameter", "namedtuple." ]
def get_fake_mask_params(): return cnma.MaskParams(classification_loss=losses.WeightedSoftmaxClassificationLoss(), task_loss_weight=1.0, mask_height=4, mask_width=4)
['def', 'get_fake_mask_params():', 'return', 'cnma.MaskParams(classification_loss=losses.WeightedSoftmaxClassificationLoss(),', 'task_loss_weight=1.0,', 'mask_height=4,', 'mask_width=4)']
852,392
enuguru/artificial_intelligence_and_machine_
debug.py
translate_exception
translate_exception
If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames.
[ "If", "passed", "an", "exc_info", "it", "will", "automatically", "rewrite", "the", "exceptions", "all", "the", "way", "down", "to", "the", "correct", "line", "numbers", "and", "frames." ]
def translate_exception(exc_info, initial_skip=0): tb = exc_info[2] frames = [] for x in range(initial_skip): if tb is not None: tb = tb.tb_next initial_tb = tb while tb is not None: if tb.tb_frame.f_code in internal_code: tb = tb.tb_next continue ...
['def', 'translate_exception(exc_info,', 'initial_skip=0):', 'tb', '=', 'exc_info[2]', 'frames', '=', '[]', 'for', 'x', 'in', 'range(initial_skip):', 'if', 'tb', 'is', 'not', 'None:', 'tb', '=', 'tb.tb_next', 'initial_tb', '=', 'tb', 'while', 'tb', 'is', 'not', 'None:', 'if', 'tb.tb_frame.f_code', 'in', 'internal_code:...
158,215
kykiefer/depression-detect
cnn.py
preprocess
preprocess
Convert from float64 to float32 and normalize normalize to decibels relative to full scale (dBFS) for the 4 sec clip.
[ "Convert", "from", "float64", "to", "float32", "and", "normalize", "normalize", "to", "decibels", "relative", "to", "full", "scale", "(dBFS)", "for", "the", "4", "sec", "clip." ]
def preprocess(X_train, X_test): X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train = np.array([(X - X.min()) / (X.max() - X.min()) for X in X_train]) X_test = np.array([(X - X.min()) / (X.max() - X.min()) for X in X_test]) return (X_train, X_test)
['def', 'preprocess(X_train,', 'X_test):', 'X_train', '=', "X_train.astype('float32')", 'X_test', '=', "X_test.astype('float32')", 'X_train', '=', 'np.array([(X', '-', 'X.min())', '/', '(X.max()', '-', 'X.min())', 'for', 'X', 'in', 'X_train])', 'X_test', '=', 'np.array([(X', '-', 'X.min())', '/', '(X.max()', '-', 'X.mi...
183,935
matsu0228/nlp-jp
topology_description.py
TopologyDescription.reset_server
reset_server
A copy of this description, with one server marked Unknown.
[ "A", "copy", "of", "this", "description,", "with", "one", "server", "marked", "Unknown." ]
def reset_server(self, address): return updated_topology_description(self, ServerDescription(address))
['def', 'reset_server(self,', 'address):', 'return', 'updated_topology_description(self,', 'ServerDescription(address))']
805,085
tonybeltramelli/Graphics-And-Vision
Camera.py
Camera.Height
Height
Set a new height value to captured images.
[ "Set", "a", "new", "height", "value", "to", "captured", "images." ]
def Height(self, value): self.__camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, int(value))
['def', 'Height(self,', 'value):', 'self.__camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,', 'int(value))']
580,563
gunthercox/ChatterBot
checkers.py
python_format
python_format
Verify the format string placeholders in the translation.
[ "Verify", "the", "format", "string", "placeholders", "in", "the", "translation." ]
def python_format(catalog, message): if 'python-format' not in message.flags: return msgids = message.id if not isinstance(msgids, (list, tuple)): msgids = (msgids,) msgstrs = message.string if not isinstance(msgstrs, (list, tuple)): msgstrs = (msgstrs,) for (msgid, msgst...
['def', 'python_format(catalog,', 'message):', 'if', "'python-format'", 'not', 'in', 'message.flags:', 'return', 'msgids', '=', 'message.id', 'if', 'not', 'isinstance(msgids,', '(list,', 'tuple)):', 'msgids', '=', '(msgids,)', 'msgstrs', '=', 'message.string', 'if', 'not', 'isinstance(msgstrs,', '(list,', 'tuple)):', '...
478,660
sunishsheth2009/ChatterBot
syntax.py
SyntaxNode.set_range
set_range
Sets the character range associated with this node.
[ "Sets", "the", "character", "range", "associated", "with", "this", "node." ]
def set_range(self, startchar, endchar): self.startchar = startchar self.endchar = endchar return self
['def', 'set_range(self,', 'startchar,', 'endchar):', 'self.startchar', '=', 'startchar', 'self.endchar', '=', 'endchar', 'return', 'self']
526,938
BlissChapman/ICW-fMRI-GAN
mask.py
Masker.remove
remove
Remove one or more layers from the stack of masking layers.
[ "Remove", "one", "or", "more", "layers", "from", "the", "stack", "of", "masking", "layers." ]
def remove(self, layers): if not isinstance(layers, list): layers = [layers] for l in layers: if isinstance(l, string_types): if l not in self.layers: raise ValueError("There's no image/layer named '%s' in the masking stack!" % l) self.stack.remove(l) ...
['def', 'remove(self,', 'layers):', 'if', 'not', 'isinstance(layers,', 'list):', 'layers', '=', '[layers]', 'for', 'l', 'in', 'layers:', 'if', 'isinstance(l,', 'string_types):', 'if', 'l', 'not', 'in', 'self.layers:', 'raise', 'ValueError("There\'s', 'no', 'image/layer', 'named', "'%s'", 'in', 'the', 'masking', 'stack!...
597,090
RasaHQ/rasa
x.py
rasa_x
rasa_x
Run Rasa with the `x` subcommand.
[ "Run", "Rasa", "with", "the", "`x`", "subcommand." ]
def rasa_x(args: argparse.Namespace) -> None: from rasa.cli.utils import signal_handler signal.signal(signal.SIGINT, signal_handler) if args.production: run_in_enterprise_connection_mode(args) else: rasa.shared.utils.io.raise_warning('Running Rasa X in local mode is no longer supported a...
['def', 'rasa_x(args:', 'argparse.Namespace)', '->', 'None:', 'from', 'rasa.cli.utils', 'import', 'signal_handler', 'signal.signal(signal.SIGINT,', 'signal_handler)', 'if', 'args.production:', 'run_in_enterprise_connection_mode(args)', 'else:', "rasa.shared.utils.io.raise_warning('Running", 'Rasa', 'X', 'in', 'local', ...
836,639
kPsarakis/Image-Forgery-Detection-CNN
mask_extraction.py
extract_masks
extract_masks
Extracts and saves all the masks.
[ "Extracts", "and", "saves", "all", "the", "masks." ]
def extract_masks(): save_dir = 'masks' if not os.path.exists(save_dir): os.makedirs(save_dir) au_pic_list = glob('..' + os.sep + '..' + os.sep + 'data' + os.sep + 'CASIA2' + os.sep + 'Au' + os.sep + '*') sp_pic_list = glob('..' + os.sep + '..' + os.sep + 'data' + os.sep + 'CASIA2' + os.sep + 'T...
['def', 'extract_masks():', 'save_dir', '=', "'masks'", 'if', 'not', 'os.path.exists(save_dir):', 'os.makedirs(save_dir)', 'au_pic_list', '=', "glob('..'", '+', 'os.sep', '+', "'..'", '+', 'os.sep', '+', "'data'", '+', 'os.sep', '+', "'CASIA2'", '+', 'os.sep', '+', "'Au'", '+', 'os.sep', '+', "'*')", 'sp_pic_list', '='...
229,243
AtlantixJJ/LinearGAN
helper.py
build_extractor
build_extractor
Builds feature extractor by architecture name.
[ "Builds", "feature", "extractor", "by", "architecture", "name." ]
def build_extractor(architecture, spatial_feature=False, imagenet_logits=False): if architecture not in PREDICTOR_POOL: raise ValueError(f'Feature extractor with architecture `{architecture}` is not registered in `PREDICTOR_POOL` in `predictor_settings.py`!') return FeatureExtractor(architecture, spatia...
['def', 'build_extractor(architecture,', 'spatial_feature=False,', 'imagenet_logits=False):', 'if', 'architecture', 'not', 'in', 'PREDICTOR_POOL:', 'raise', "ValueError(f'Feature", 'extractor', 'with', 'architecture', '`{architecture}`', 'is', 'not', 'registered', 'in', '`PREDICTOR_POOL`', 'in', "`predictor_settings.py...
602,678
lalwanii26/openscope-barcodingstim
translator.py
TrialTranslator.find_dx
find_dx
Finds wheel rotation for each frame.
[ "Finds", "wheel", "rotation", "for", "each", "frame." ]
def find_dx(self, exp_data): return exp_data['items']['behavior']['encoders'][0]['dx']
['def', 'find_dx(self,', 'exp_data):', 'return', "exp_data['items']['behavior']['encoders'][0]['dx']"]
757,552
jimtin/Stock_Comparison
mpltools.py
get_spine_visible
get_spine_visible
Return some spine parameters for the spine, `spine_key`.
[ "Return", "some", "spine", "parameters", "for", "the", "spine,", "`spine_key`." ]
def get_spine_visible(ax, spine_key): spine = ax.spines[spine_key] ax_frame_on = ax.get_frame_on() spine_frame_like = spine.is_frame_like() if not spine.get_visible(): return False elif not spine._edgecolor[-1]: return False elif not ax_frame_on and spine_frame_like: retu...
['def', 'get_spine_visible(ax,', 'spine_key):', 'spine', '=', 'ax.spines[spine_key]', 'ax_frame_on', '=', 'ax.get_frame_on()', 'spine_frame_like', '=', 'spine.is_frame_like()', 'if', 'not', 'spine.get_visible():', 'return', 'False', 'elif', 'not', 'spine._edgecolor[-1]:', 'return', 'False', 'elif', 'not', 'ax_frame_on'...
389,249
jxhe/unify-parameter-efficient-tuning
lm_seqs_dataset.py
LmSeqsDataset.remove_unknown_sequences
remove_unknown_sequences
Remove sequences with a (too) high level of unknown tokens.
[ "Remove", "sequences", "with", "a", "(too)", "high", "level", "of", "unknown", "tokens." ]
def remove_unknown_sequences(self): if 'unk_token' not in self.params.special_tok_ids: return else: unk_token_id = self.params.special_tok_ids['unk_token'] init_size = len(self) unk_occs = np.array([np.count_nonzero(a == unk_token_id) for a in self.token_ids]) indices = unk_occs / se...
['def', 'remove_unknown_sequences(self):', 'if', "'unk_token'", 'not', 'in', 'self.params.special_tok_ids:', 'return', 'else:', 'unk_token_id', '=', "self.params.special_tok_ids['unk_token']", 'init_size', '=', 'len(self)', 'unk_occs', '=', 'np.array([np.count_nonzero(a', '==', 'unk_token_id)', 'for', 'a', 'in', 'self....
948,138
jariasf/GMVAE
utils.py
mode_tensor
mode_tensor
Computes the mode of the float Tensor x.
[ "Computes", "the", "mode", "of", "the", "float", "Tensor", "x." ]
def mode_tensor(x): (y, idx, count) = tf.unique_with_counts(x) mode = y[tf.argmax(count)] return tf.cast(mode, dtype=tf.float32)
['def', 'mode_tensor(x):', '(y,', 'idx,', 'count)', '=', 'tf.unique_with_counts(x)', 'mode', '=', 'y[tf.argmax(count)]', 'return', 'tf.cast(mode,', 'dtype=tf.float32)']
578,505
43Carrig/recurrent_neural_networks_practice
test_util.py
ConstantMinimizationProblem.objective
objective
Returns the objective function.
[ "Returns", "the", "objective", "function." ]
def objective(self): return self._objective
['def', 'objective(self):', 'return', 'self._objective']
312,630
PacktPublishing/Hands-On-Artificial--for-Banking
conftest.py
python_parser_only
python_parser_only
Fixture all of the CSV parsers using the Python engine.
[ "Fixture", "all", "of", "the", "CSV", "parsers", "using", "the", "Python", "engine." ]
def python_parser_only(request): return request.param
['def', 'python_parser_only(request):', 'return', 'request.param']
237,279
RLE-Foundation/rllte
impala.py
IMPALA.update
update
Update the learner model.
[ "Update", "the", "learner", "model." ]
def update(self, batch: Dict, lock=threading.Lock()) -> Dict[str, Any]: with lock: learner_outputs = self.policy.learner(batch) bootstrap_value = learner_outputs['baselines'][-1] batch = {key: tensor[1:] for (key, tensor) in batch.items()} learner_outputs = {key: tensor[:-1] for (key...
['def', 'update(self,', 'batch:', 'Dict,', 'lock=threading.Lock())', '->', 'Dict[str,', 'Any]:', 'with', 'lock:', 'learner_outputs', '=', 'self.policy.learner(batch)', 'bootstrap_value', '=', "learner_outputs['baselines'][-1]", 'batch', '=', '{key:', 'tensor[1:]', 'for', '(key,', 'tensor)', 'in', 'batch.items()}', 'lea...
333,451
Kvatsx/Artificial-Intelligence-Assignments
console_widget.py
ConsoleWidget.can_copy
can_copy
Returns whether text can be copied to the clipboard.
[ "Returns", "whether", "text", "can", "be", "copied", "to", "the", "clipboard." ]
def can_copy(self): return self._control.textCursor().hasSelection()
['def', 'can_copy(self):', 'return', 'self._control.textCursor().hasSelection()']
77,238
PacktPublishing/Hands-On-Artificial--for-Banking
test_lapack.py
TestTbtrs.test_invalid_matrix_shapes
test_invalid_matrix_shapes
Test ?tbtrs fails correctly if shapes are invalid.
[ "Test", "?tbtrs", "fails", "correctly", "if", "shapes", "are", "invalid." ]
def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs): ab = np.ones((ldab, n), dtype=float) b = np.ones((ldb, nrhs), dtype=float) tbtrs = get_lapack_funcs('tbtrs', dtype=float) assert_raises(Exception, tbtrs, ab, b)
['def', 'test_invalid_matrix_shapes(self,', 'ldab,', 'n,', 'ldb,', 'nrhs):', 'ab', '=', 'np.ones((ldab,', 'n),', 'dtype=float)', 'b', '=', 'np.ones((ldb,', 'nrhs),', 'dtype=float)', 'tbtrs', '=', "get_lapack_funcs('tbtrs',", 'dtype=float)', 'assert_raises(Exception,', 'tbtrs,', 'ab,', 'b)']
238,617
IBM/mi-prometheus
json_to_img.py
convert_to_grid
convert_to_grid
Given a x-y coordinate, return the target activity for a grid of neurons.
[ "Given", "a", "x-y", "coordinate,", "return", "the", "target", "activity", "for", "a", "grid", "of", "neurons." ]
def convert_to_grid(xy_coord, prefs): sigma2 = 0.02 activity = np.exp(-((xy_coord[:, 0:1] - prefs[:, 0]) ** 2 + (xy_coord[:, 1:2] - prefs[:, 1]) ** 2) / sigma2) activity = (activity.T / np.sum(activity, axis=1)).T return activity
['def', 'convert_to_grid(xy_coord,', 'prefs):', 'sigma2', '=', '0.02', 'activity', '=', 'np.exp(-((xy_coord[:,', '0:1]', '-', 'prefs[:,', '0])', '**', '2', '+', '(xy_coord[:,', '1:2]', '-', 'prefs[:,', '1])', '**', '2)', '/', 'sigma2)', 'activity', '=', '(activity.T', '/', 'np.sum(activity,', 'axis=1)).T', 'return', 'a...
635,725
ratschlab/dpsom
somvae_model.py
conv2d_transposed
conv2d_transposed
Creates a transposed convolutional layer simimar to conv2d.
[ "Creates", "a", "transposed", "convolutional", "layer", "simimar", "to", "conv2d." ]
def conv2d_transposed(x, shape, outshape, name, strides=[1, 1, 1, 1]): weight = weight_variable(shape, '{}_W'.format(name)) bias = bias_variable([shape[-2]], '{}_b'.format(name)) return tf.nn.conv2d_transpose(x, weight, output_shape=outshape, strides=strides, padding='SAME', name=name) + bias
['def', 'conv2d_transposed(x,', 'shape,', 'outshape,', 'name,', 'strides=[1,', '1,', '1,', '1]):', 'weight', '=', 'weight_variable(shape,', "'{}_W'.format(name))", 'bias', '=', 'bias_variable([shape[-2]],', "'{}_b'.format(name))", 'return', 'tf.nn.conv2d_transpose(x,', 'weight,', 'output_shape=outshape,', 'strides=stri...
167,005
thaines/helit
model.py
Sample.cleanZeros
cleanZeros
Goes through and removes anything that has a zero reference count, adjusting all indices accordingly.
[ "Goes", "through", "and", "removes", "anything", "that", "has", "a", "zero", "reference", "count,", "adjusting", "all", "indices", "accordingly." ]
def cleanZeros(self): newTopicCount = 0 topicMap = dict() for t in xrange(self.topicUse.shape[0]): if self.topicUse[t] != 0: topicMap[t] = newTopicCount newTopicCount += 1 if newTopicCount != self.topicUse.shape[0]: newTopicWord = numpy.zeros((newTopicCount, self....
['def', 'cleanZeros(self):', 'newTopicCount', '=', '0', 'topicMap', '=', 'dict()', 'for', 't', 'in', 'xrange(self.topicUse.shape[0]):', 'if', 'self.topicUse[t]', '!=', '0:', 'topicMap[t]', '=', 'newTopicCount', 'newTopicCount', '+=', '1', 'if', 'newTopicCount', '!=', 'self.topicUse.shape[0]:', 'newTopicWord', '=', 'num...
591,173
sunishsheth2009/ChatterBot
parsing.py
date_from_duration
date_from_duration
Find dates from duration Eg: 20 days from now Currently does not support strings like "20 days from last monday".
[ "Find", "dates", "from", "duration", "Eg:", "20", "days", "from", "now", "Currently", "does", "not", "support", "strings", "like", "\"20", "days", "from", "last", "monday\"." ]
def date_from_duration(base_date, number_as_string, unit, duration, base_time=None): if base_time is not None: base_date = date_from_adverb(base_date, base_time) num = convert_string_to_number(number_as_string) if unit in day_variations: args = {'days': num} elif unit in minute_variation...
['def', 'date_from_duration(base_date,', 'number_as_string,', 'unit,', 'duration,', 'base_time=None):', 'if', 'base_time', 'is', 'not', 'None:', 'base_date', '=', 'date_from_adverb(base_date,', 'base_time)', 'num', '=', 'convert_string_to_number(number_as_string)', 'if', 'unit', 'in', 'day_variations:', 'args', '=', "{...
478,041
microsoft/UniSpeech
utils.py
broadcast_object
broadcast_object
Broadcast an arbitrary Python object to other workers.
[ "Broadcast", "an", "arbitrary", "Python", "object", "to", "other", "workers." ]
def broadcast_object(obj: Any, src_rank: int, group: object, dist_device: Optional[torch.device]=None) -> Any: if dist_device is None: if torch.distributed.get_backend(group) == 'nccl': dist_device = torch.device('cuda') else: dist_device = torch.device('cpu') if get_rank...
['def', 'broadcast_object(obj:', 'Any,', 'src_rank:', 'int,', 'group:', 'object,', 'dist_device:', 'Optional[torch.device]=None)', '->', 'Any:', 'if', 'dist_device', 'is', 'None:', 'if', 'torch.distributed.get_backend(group)', '==', "'nccl':", 'dist_device', '=', "torch.device('cuda')", 'else:', 'dist_device', '=', "to...
378,329
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjuiThemeColorWrapper.decorinactive2
decorinactive2
inactive slider color 2.
[ "inactive", "slider", "color", "2." ]
def decorinactive2(self): return util.buf_to_npy(self._ptr.contents.decorinactive2, (3,))
['def', 'decorinactive2(self):', 'return', 'util.buf_to_npy(self._ptr.contents.decorinactive2,', '(3,))']
440,679
tensorflow/quantum
serializer_test.py
SerializerTest.test_deserialize_circuit_wrong_type
test_deserialize_circuit_wrong_type
Attempt to deserialize invalid objects types.
[ "Attempt", "to", "deserialize", "invalid", "objects", "types." ]
def test_deserialize_circuit_wrong_type(self, inp): with self.assertRaises(TypeError): serializer.deserialize_circuit(input)
['def', 'test_deserialize_circuit_wrong_type(self,', 'inp):', 'with', 'self.assertRaises(TypeError):', 'serializer.deserialize_circuit(input)']
835,028
enuguru/artificial_intelligence_and_machine_learning
collector.py
Collector.tracer_name
tracer_name
Return the class name of the tracer we're using.
[ "Return", "the", "class", "name", "of", "the", "tracer", "we're", "using." ]
def tracer_name(self): return self._trace_class.__name__
['def', 'tracer_name(self):', 'return', 'self._trace_class.__name__']
157,233
pramodiperera/virtual-keyboard
search_scope.py
SearchScope.create
create
Create a SearchScope object after normalizing the `find_links`.
[ "Create", "a", "SearchScope", "object", "after", "normalizing", "the", "`find_links`." ]
def create(cls, find_links: List[str], index_urls: List[str]) -> 'SearchScope': built_find_links: List[str] = [] for link in find_links: if link.startswith('~'): new_link = normalize_path(link) if os.path.exists(new_link): link = new_link built_find_links....
['def', 'create(cls,', 'find_links:', 'List[str],', 'index_urls:', 'List[str])', '->', "'SearchScope':", 'built_find_links:', 'List[str]', '=', '[]', 'for', 'link', 'in', 'find_links:', 'if', "link.startswith('~'):", 'new_link', '=', 'normalize_path(link)', 'if', 'os.path.exists(new_link):', 'link', '=', 'new_link', 'b...
931,957
PKU-Alignment/safe-rlhf
utils.py
is_main_process
is_main_process
Check if the current process is the main process.
[ "Check", "if", "the", "current", "process", "is", "the", "main", "process." ]
def is_main_process() -> bool: return not dist.is_initialized() or dist.get_rank() == 0
['def', 'is_main_process()', '->', 'bool:', 'return', 'not', 'dist.is_initialized()', 'or', 'dist.get_rank()', '==', '0']
829,125
mfbx9da4/neuron-astrocyte-networks
genotypes.py
Genotype.get_fitness_fail
get_fitness_fail
This function returns the fitness value that constitutes failure as assigned by the parent grammatical evolution.
[ "This", "function", "returns", "the", "fitness", "value", "that", "constitutes", "failure", "as", "assigned", "by", "the", "parent", "grammatical", "evolution." ]
def get_fitness_fail(self): return self._fitness_fail
['def', 'get_fitness_fail(self):', 'return', 'self._fitness_fail']
722,900
TrellixVulnTeam/Unsupervised_Learning_HFI7
plot_directive.py
PlotDirective.run
run
Run the plot directive.
[ "Run", "the", "plot", "directive." ]
def run(self): return run(self.arguments, self.content, self.options, self.state_machine, self.state, self.lineno)
['def', 'run(self):', 'return', 'run(self.arguments,', 'self.content,', 'self.options,', 'self.state_machine,', 'self.state,', 'self.lineno)']
451,237
thu-ml/ares
trainer.py
Trainer.before_eval
before_eval
Do something before evaluating.
[ "Do", "something", "before", "evaluating." ]
def before_eval(self): self.model.eval() if not self.is_distributed else self.model.module.eval() self.test_dataloader.sampler.shuffle = False
['def', 'before_eval(self):', 'self.model.eval()', 'if', 'not', 'self.is_distributed', 'else', 'self.model.module.eval()', 'self.test_dataloader.sampler.shuffle', '=', 'False']
402,077
Vill-Lab/2021-TIP-IGOAS
dataset.py
Dataset.download_dataset
download_dataset
Downloads and extracts dataset.
[ "Downloads", "and", "extracts", "dataset." ]
def download_dataset(self, dataset_dir, dataset_url): if osp.exists(dataset_dir): return if dataset_url is None: raise RuntimeError('{} dataset needs to be manually prepared, please follow the document to prepare this dataset'.format(self.__class__.__name__)) print('Creating directory "{}"'....
['def', 'download_dataset(self,', 'dataset_dir,', 'dataset_url):', 'if', 'osp.exists(dataset_dir):', 'return', 'if', 'dataset_url', 'is', 'None:', 'raise', "RuntimeError('{}", 'dataset', 'needs', 'to', 'be', 'manually', 'prepared,', 'please', 'follow', 'the', 'document', 'to', 'prepare', 'this', "dataset'.format(self._...
375,440