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
OliverKillane/NuNet-Designer
NuNetLibrary.py
Output.passbackwards
passbackwards
passbackwards is overridden from the Neuron class and sends the derivative of the neuron to each synapse feeding into it.
[ "passbackwards", "is", "overridden", "from", "the", "Neuron", "class", "and", "sends", "the", "derivative", "of", "the", "neuron", "to", "each", "synapse", "feeding", "into", "it." ]
def passbackwards(self) -> None: for synapse in self._fromSynapses: synapse.passbackwards(self._backpropDerivative)
['def', 'passbackwards(self)', '->', 'None:', 'for', 'synapse', 'in', 'self._fromSynapses:', 'synapse.passbackwards(self._backpropDerivative)']
730,523
chengfx/neural-networks-and-deep-learning-for-python3
network2.py
QuadraticCost.fn
fn
Return the cost associated with an output ``a`` and desired output ``y``.
[ "Return", "the", "cost", "associated", "with", "an", "output", "``a``", "and", "desired", "output", "``y``." ]
def fn(a, y): return 0.5 * np.linalg.norm(a - y) ** 2
['def', 'fn(a,', 'y):', 'return', '0.5', '*', 'np.linalg.norm(a', '-', 'y)', '**', '2']
722,010
amarack/python-rl
fitted_qiteration.py
FittedQIteration.getValue
getValue
Get the Q-value function value for the greedy action choice at the given state (ie V(state)).
[ "Get", "the", "Q-value", "function", "value", "for", "the", "greedy", "action", "choice", "at", "the", "given", "state", "(ie", "V(state))." ]
def getValue(self, state): if self.has_plan: return self.learner.predict([self.getStateAction(state, a) for a in range(self.actions)]).max() else: return None
['def', 'getValue(self,', 'state):', 'if', 'self.has_plan:', 'return', 'self.learner.predict([self.getStateAction(state,', 'a)', 'for', 'a', 'in', 'range(self.actions)]).max()', 'else:', 'return', 'None']
297,566
sktime/sktime
test_ensemble.py
test_aggregation_unweighted
test_aggregation_unweighted
Assert aggfunc returns the correct values.
[ "Assert", "aggfunc", "returns", "the", "correct", "values." ]
def test_aggregation_unweighted(forecasters, y, aggfunc): forecaster = EnsembleForecaster(forecasters=forecasters, aggfunc=aggfunc) forecaster.fit(y, fh=[1, 2, 3]) actual_pred = forecaster.predict() predictions = [] _aggfunc = VALID_AGG_FUNCS[aggfunc]['unweighted'] for (_, forecaster) in forecas...
['def', 'test_aggregation_unweighted(forecasters,', 'y,', 'aggfunc):', 'forecaster', '=', 'EnsembleForecaster(forecasters=forecasters,', 'aggfunc=aggfunc)', 'forecaster.fit(y,', 'fh=[1,', '2,', '3])', 'actual_pred', '=', 'forecaster.predict()', 'predictions', '=', '[]', '_aggfunc', '=', "VALID_AGG_FUNCS[aggfunc]['unwei...
877,215
OpenMDAO/OpenMDAO-Framework
cover2.py
Coverage2.begin
begin
Begin recording coverage information.
[ "Begin", "recording", "coverage", "information." ]
def begin(self): log.debug('Coverage2 begin') import coverage self.skipModules = sys.modules.keys()[:] self.coverage = coverage.coverage() if self.coverErase: log.debug('Clearing previously collected coverage statistics') self.coverage.erase() self.coverage.exclude('#pragma[: ]+[...
['def', 'begin(self):', "log.debug('Coverage2", "begin')", 'import', 'coverage', 'self.skipModules', '=', 'sys.modules.keys()[:]', 'self.coverage', '=', 'coverage.coverage()', 'if', 'self.coverErase:', "log.debug('Clearing", 'previously', 'collected', 'coverage', "statistics')", 'self.coverage.erase()', "self.coverage....
275,290
lethaiq/GAIN
utils.py
renormalization
renormalization
Renormalize data from [0, 1] range to the original range.
[ "Renormalize", "data", "from", "[0,", "1]", "range", "to", "the", "original", "range." ]
def renormalization(norm_data, norm_parameters): min_val = norm_parameters['min_val'] max_val = norm_parameters['max_val'] (_, dim) = norm_data.shape renorm_data = norm_data.copy() for i in range(dim): renorm_data[:, i] = renorm_data[:, i] * (max_val[i] + 1e-06) renorm_data[:, i] = r...
['def', 'renormalization(norm_data,', 'norm_parameters):', 'min_val', '=', "norm_parameters['min_val']", 'max_val', '=', "norm_parameters['max_val']", '(_,', 'dim)', '=', 'norm_data.shape', 'renorm_data', '=', 'norm_data.copy()', 'for', 'i', 'in', 'range(dim):', 'renorm_data[:,', 'i]', '=', 'renorm_data[:,', 'i]', '*',...
566,098
google-research/crest
data_util.py
gaussian_blur
gaussian_blur
Blurs the given image with separable convolution.
[ "Blurs", "the", "given", "image", "with", "separable", "convolution." ]
def gaussian_blur(image, kernel_size, sigma, padding='SAME'): radius = tf.to_int32(kernel_size / 2) kernel_size = radius * 2 + 1 x = tf.to_float(tf.range(-radius, radius + 1)) blur_filter = tf.exp(-tf.pow(x, 2.0) / (2.0 * tf.pow(tf.to_float(sigma), 2.0))) blur_filter /= tf.reduce_sum(blur_filter) ...
['def', 'gaussian_blur(image,', 'kernel_size,', 'sigma,', "padding='SAME'):", 'radius', '=', 'tf.to_int32(kernel_size', '/', '2)', 'kernel_size', '=', 'radius', '*', '2', '+', '1', 'x', '=', 'tf.to_float(tf.range(-radius,', 'radius', '+', '1))', 'blur_filter', '=', 'tf.exp(-tf.pow(x,', '2.0)', '/', '(2.0', '*', 'tf.pow...
138,560
JohannesVerherstraeten/semantic-video-segmentation
imgseqdataset.py
ImgSeqDataset.get_videos
get_videos
Returns all BaseVideo items in this dataset.
[ "Returns", "all", "BaseVideo", "items", "in", "this", "dataset." ]
def get_videos(self) -> Tuple[ImageSequence, ...]: return self.image_sequences
['def', 'get_videos(self)', '->', 'Tuple[ImageSequence,', '...]:', 'return', 'self.image_sequences']
342,821
jimtin/Stock_Comparison
utils.py
iter_all_children
iter_all_children
Returns an iterator over all childen and nested children using obj's get_children() method if skipContainers is true, only childless objects are returned.
[ "Returns", "an", "iterator", "over", "all", "childen", "and", "nested", "children", "using", "obj's", "get_children()", "method", "if", "skipContainers", "is", "true,", "only", "childless", "objects", "are", "returned." ]
def iter_all_children(obj, skipContainers=False): if hasattr(obj, 'get_children') and len(obj.get_children()) > 0: for child in obj.get_children(): if not skipContainers: yield child for grandchild in iter_all_children(child, skipContainers): yield gra...
['def', 'iter_all_children(obj,', 'skipContainers=False):', 'if', 'hasattr(obj,', "'get_children')", 'and', 'len(obj.get_children())', '>', '0:', 'for', 'child', 'in', 'obj.get_children():', 'if', 'not', 'skipContainers:', 'yield', 'child', 'for', 'grandchild', 'in', 'iter_all_children(child,', 'skipContainers):', 'yie...
389,270
NoGameNoLife00/mybolg
wrappers.py
ETagResponseMixin.set_etag
set_etag
Set the etag, and override the old one if there was one.
[ "Set", "the", "etag,", "and", "override", "the", "old", "one", "if", "there", "was", "one." ]
def set_etag(self, etag, weak=False): self.headers['ETag'] = quote_etag(etag, weak)
['def', 'set_etag(self,', 'etag,', 'weak=False):', "self.headers['ETag']", '=', 'quote_etag(etag,', 'weak)']
289,998
gunthercox/ChatterBot
test_best_match.py
BestMatchTestCase.test_match_with_response
test_match_with_response
The response to the input should be returned if a response is known.
[ "The", "response", "to", "the", "input", "should", "be", "returned", "if", "a", "response", "is", "known." ]
def test_match_with_response(self): self.chatbot.storage.create(text='To eat pasta.', in_response_to='What is your quest?') self.chatbot.storage.create(text='What is your quest?') statement = Statement(text='What is your quest?') response = self.adapter.process(statement) self.assertEqual(response.t...
['def', 'test_match_with_response(self):', "self.chatbot.storage.create(text='To", 'eat', "pasta.',", "in_response_to='What", 'is', 'your', "quest?')", "self.chatbot.storage.create(text='What", 'is', 'your', "quest?')", 'statement', '=', "Statement(text='What", 'is', 'your', "quest?')", 'response', '=', 'self.adapter.p...
485,932
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
Delegator.py
Delegator.resetcache
resetcache
Removes added attributes while leaving original attributes.
[ "Removes", "added", "attributes", "while", "leaving", "original", "attributes." ]
def resetcache(self): for key in self.__cache: try: delattr(self, key) except AttributeError: pass self.__cache.clear()
['def', 'resetcache(self):', 'for', 'key', 'in', 'self.__cache:', 'try:', 'delattr(self,', 'key)', 'except', 'AttributeError:', 'pass', 'self.__cache.clear()']
430,827
43Carrig/recurrent_neural_networks_practice
inference_utils.py
wrap_inference_results
wrap_inference_results
Returns packaged inference results from the provided proto.
[ "Returns", "packaged", "inference", "results", "from", "the", "provided", "proto." ]
def wrap_inference_results(inference_result_proto): inference_proto = inference_pb2.InferenceResult() if isinstance(inference_result_proto, classification_pb2.ClassificationResponse): inference_proto.classification_result.CopyFrom(inference_result_proto.result) elif isinstance(inference_result_proto...
['def', 'wrap_inference_results(inference_result_proto):', 'inference_proto', '=', 'inference_pb2.InferenceResult()', 'if', 'isinstance(inference_result_proto,', 'classification_pb2.ClassificationResponse):', 'inference_proto.classification_result.CopyFrom(inference_result_proto.result)', 'elif', 'isinstance(inference_...
312,235
explosion/spaCy
test_vectors.py
floret_vectors_vec_str
floret_vectors_vec_str
The top 10 rows from floret with the settings above, to verify that the spacy floret vectors are equivalent to the fasttext static vectors.
[ "The", "top", "10", "rows", "from", "floret", "with", "the", "settings", "above,", "to", "verify", "that", "the", "spacy", "floret", "vectors", "are", "equivalent", "to", "the", "fasttext", "static", "vectors." ]
def floret_vectors_vec_str(): return '10 10\n, -5.7814 2.6918 0.57029 -3.6985 -2.7079 1.4406 1.0084 1.7463 -3.8625 -3.0565\n. 3.8016 -1.759 0.59118 3.3044 -0.72975 0.45221 -2.1412 -3.8933 -2.1238 -0.47409\nder 0.08224 2.6601 -1.173 1.1549 -0.42821 -0.097268 -2.5589 -1.609 -0.16968 0.84687\ndie -2.8781 0.082576 1.92...
['def', 'floret_vectors_vec_str():', 'return', "'10", '10\\n,', '-5.7814', '2.6918', '0.57029', '-3.6985', '-2.7079', '1.4406', '1.0084', '1.7463', '-3.8625', '-3.0565\\n.', '3.8016', '-1.759', '0.59118', '3.3044', '-0.72975', '0.45221', '-2.1412', '-3.8933', '-2.1238', '-0.47409\\nder', '0.08224', '2.6601', '-1.173', ...
894,402
eddiecorrigall/Vision
perlin.py
PerlinNoiseGenerator.get_plain_noise
get_plain_noise
Get plain noise for a single point, without taking into account either octaves or tiling.
[ "Get", "plain", "noise", "for", "a", "single", "point,", "without", "taking", "into", "account", "either", "octaves", "or", "tiling." ]
def get_plain_noise(self, *point): if len(point) != self.dimension: raise ValueError('Expected {} values, got {}'.format(self.dimension, len(point))) grid_coords = [] for coord in point: min_coord = math.floor(coord) max_coord = min_coord + 1 grid_coords.append((min_coord, ma...
['def', 'get_plain_noise(self,', '*point):', 'if', 'len(point)', '!=', 'self.dimension:', 'raise', "ValueError('Expected", '{}', 'values,', 'got', "{}'.format(self.dimension,", 'len(point)))', 'grid_coords', '=', '[]', 'for', 'coord', 'in', 'point:', 'min_coord', '=', 'math.floor(coord)', 'max_coord', '=', 'min_coord',...
942,458
AlperHuseyn/artificial-intelligence-and-machine-learning-with-python
email-category-predictor.py
train_evaluate_save_model
train_evaluate_save_model
Train, evaluate, and save the email prediction model.
[ "Train,", "evaluate,", "and", "save", "the", "email", "prediction", "model." ]
def train_evaluate_save_model(X_train, y_train, X_test, y_test, X_to_predict, num_categories, name='model', epochs=5): model = create_email_model(input_dim=X_train.shape[1], num_categories=num_categories, name='email-category-predictor') hist = model.fit(X_train, y_train, epochs=epochs, validation_split=0.2) ...
['def', 'train_evaluate_save_model(X_train,', 'y_train,', 'X_test,', 'y_test,', 'X_to_predict,', 'num_categories,', "name='model',", 'epochs=5):', 'model', '=', 'create_email_model(input_dim=X_train.shape[1],', 'num_categories=num_categories,', "name='email-category-predictor')", 'hist', '=', 'model.fit(X_train,', 'y_t...
36,165
openvinotoolkit/training_extensions
patches.py
nncf_trace_context
nncf_trace_context
A context manager for nncf graph tracing.
[ "A", "context", "manager", "for", "nncf", "graph", "tracing." ]
def nncf_trace_context(self, img_metas, nncf_compress_postprocessing=True): device_backup = next(self.parameters()).device self = self.to('cpu') if nncf_compress_postprocessing: self.forward = partial(self.forward, img_metas=img_metas, return_loss=False) else: self.forward = partial(self...
['def', 'nncf_trace_context(self,', 'img_metas,', 'nncf_compress_postprocessing=True):', 'device_backup', '=', 'next(self.parameters()).device', 'self', '=', "self.to('cpu')", 'if', 'nncf_compress_postprocessing:', 'self.forward', '=', 'partial(self.forward,', 'img_metas=img_metas,', 'return_loss=False)', 'else:', 'sel...
917,973
jgwak/GSDN
pc_utils.py
Camera.project
project
Project a 3D point in camera coordinates into the camera/image plane.
[ "Project", "a", "3D", "point", "in", "camera", "coordinates", "into", "the", "camera/image", "plane." ]
def project(self, points_3d, extrinsics=None): if extrinsics is not None: points_3d = self.world2camera(extrinsics, points_3d) raise NotImplementedError
['def', 'project(self,', 'points_3d,', 'extrinsics=None):', 'if', 'extrinsics', 'is', 'not', 'None:', 'points_3d', '=', 'self.world2camera(extrinsics,', 'points_3d)', 'raise', 'NotImplementedError']
571,899
wbsth/cs50ai
logic.py
model_check
model_check
Checks if knowledge base entails query.
[ "Checks", "if", "knowledge", "base", "entails", "query." ]
def model_check(knowledge, query): def check_all(knowledge, query, symbols, model): if not symbols: if knowledge.evaluate(model): return query.evaluate(model) return True else: remaining = symbols.copy() p = remaining.pop() ...
['def', 'model_check(knowledge,', 'query):', 'def', 'check_all(knowledge,', 'query,', 'symbols,', 'model):', 'if', 'not', 'symbols:', 'if', 'knowledge.evaluate(model):', 'return', 'query.evaluate(model)', 'return', 'True', 'else:', 'remaining', '=', 'symbols.copy()', 'p', '=', 'remaining.pop()', 'model_true', '=', 'mod...
192,200
hrbigelow/ae-wavenet
vconv.py
tensor_slice
tensor_slice
Compute the index slice of the tensor input described by ref_gcoord that is specified by subrange_gcoord.
[ "Compute", "the", "index", "slice", "of", "the", "tensor", "input", "described", "by", "ref_gcoord", "that", "is", "specified", "by", "subrange_gcoord." ]
def tensor_slice(ref_gcoord, subrange_gcoord): rsub = ref_gcoord.sub rgs = ref_gcoord.gs tsub = subrange_gcoord assert rsub[0] <= tsub[0] and tsub[1] <= rsub[1] bp = tsub[0] - rsub[0] ep = tsub[1] - rsub[0] assert bp % rgs == 0 and (ep - 1) % rgs == 0 return (bp // rgs, (ep - 1) // rgs +...
['def', 'tensor_slice(ref_gcoord,', 'subrange_gcoord):', 'rsub', '=', 'ref_gcoord.sub', 'rgs', '=', 'ref_gcoord.gs', 'tsub', '=', 'subrange_gcoord', 'assert', 'rsub[0]', '<=', 'tsub[0]', 'and', 'tsub[1]', '<=', 'rsub[1]', 'bp', '=', 'tsub[0]', '-', 'rsub[0]', 'ep', '=', 'tsub[1]', '-', 'rsub[0]', 'assert', 'bp', '%', '...
40,152
secretflow/secretflow
dataframe.py
MixDataFrame.columns
columns
The column labels of the DataFrame.
[ "The", "column", "labels", "of", "the", "DataFrame." ]
def columns(self): cols = self.partitions[0].columns if self.partition_way == PartitionWay.VERTICAL: for part in self.partitions[1:]: cols.extend(part.columns) return cols
['def', 'columns(self):', 'cols', '=', 'self.partitions[0].columns', 'if', 'self.partition_way', '==', 'PartitionWay.VERTICAL:', 'for', 'part', 'in', 'self.partitions[1:]:', 'cols.extend(part.columns)', 'return', 'cols']
856,296
Alexander-Parker/youtube_nlp
proxy.py
Proxy.socks_password
socks_password
Returns socks proxy password setting.
[ "Returns", "socks", "proxy", "password", "setting." ]
def socks_password(self): return self.socksPassword
['def', 'socks_password(self):', 'return', 'self.socksPassword']
970,823
zhang614/MicroGrid
socketserver.py
BaseServer.finish_request
finish_request
Finish one request by instantiating RequestHandlerClass.
[ "Finish", "one", "request", "by", "instantiating", "RequestHandlerClass." ]
def finish_request(self, request, client_address): self.RequestHandlerClass(request, client_address, self)
['def', 'finish_request(self,', 'request,', 'client_address):', 'self.RequestHandlerClass(request,', 'client_address,', 'self)']
636,052
lektor/lektor-archive
build_programs.py
BuildProgram.declare_artifact
declare_artifact
This declares an artifact to be built in this program.
[ "This", "declares", "an", "artifact", "to", "be", "built", "in", "this", "program." ]
def declare_artifact(self, artifact_name, sources=None, extra=None): self.artifacts.append(self.build_state.new_artifact(artifact_name=artifact_name, sources=sources, source_obj=self.source, extra=extra))
['def', 'declare_artifact(self,', 'artifact_name,', 'sources=None,', 'extra=None):', 'self.artifacts.append(self.build_state.new_artifact(artifact_name=artifact_name,', 'sources=sources,', 'source_obj=self.source,', 'extra=extra))']
216,327
thaines/helit
model.py
Sample.getTopicMultinomials
getTopicMultinomials
Returns the multinomials for all topics, in a single array - indexed by [topic, word] to give P(word|topic).
[ "Returns", "the", "multinomials", "for", "all", "topics,", "in", "a", "single", "array", "-", "indexed", "by", "[topic,", "word]", "to", "give", "P(word|topic)." ]
def getTopicMultinomials(self): ret = numpy.vstack([self.beta] * self.topicWord.shape[0]) ret += self.topicWord ret = (ret.T / ret.sum(axis=1)).T return ret
['def', 'getTopicMultinomials(self):', 'ret', '=', 'numpy.vstack([self.beta]', '*', 'self.topicWord.shape[0])', 'ret', '+=', 'self.topicWord', 'ret', '=', '(ret.T', '/', 'ret.sum(axis=1)).T', 'return', 'ret']
591,152
RashadGarayev/FireDetection
config_util_test.py
ConfigUtilTest.testOverWriteRetainOriginalImageAdditionalChannels
testOverWriteRetainOriginalImageAdditionalChannels
Tests that keyword arguments are applied correctly.
[ "Tests", "that", "keyword", "arguments", "are", "applied", "correctly." ]
def testOverWriteRetainOriginalImageAdditionalChannels(self): original_retain_original_image_additional_channels = True desired_retain_original_image_additional_channels = False pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config') pipeline_config = pipeline_pb2.TrainEvalPipelineCo...
['def', 'testOverWriteRetainOriginalImageAdditionalChannels(self):', 'original_retain_original_image_additional_channels', '=', 'True', 'desired_retain_original_image_additional_channels', '=', 'False', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipe...
210,788
autonomousvision/differentiable_volumetric_rendering
common.py
chamfer_distance_kdtree
chamfer_distance_kdtree
KD-tree based implementation of the Chamfer distance.
[ "KD-tree", "based", "implementation", "of", "the", "Chamfer", "distance." ]
def chamfer_distance_kdtree(points1, points2, give_id=False): batch_size = points1.size(0) points1_np = points1.detach().cpu().numpy() points2_np = points2.detach().cpu().numpy() (idx_nn_12, _) = get_nearest_neighbors_indices_batch(points1_np, points2_np) idx_nn_12 = torch.LongTensor(idx_nn_12).to(p...
['def', 'chamfer_distance_kdtree(points1,', 'points2,', 'give_id=False):', 'batch_size', '=', 'points1.size(0)', 'points1_np', '=', 'points1.detach().cpu().numpy()', 'points2_np', '=', 'points2.detach().cpu().numpy()', '(idx_nn_12,', '_)', '=', 'get_nearest_neighbors_indices_batch(points1_np,', 'points2_np)', 'idx_nn_1...
184,984
zihuitang/medical_AI_platform
__init__.py
warnings_state
warnings_state
Use a specific warnings implementation in warning_tests.
[ "Use", "a", "specific", "warnings", "implementation", "in", "warning_tests." ]
def warnings_state(module): global __warningregistry__ for to_clear in (sys, warning_tests): try: to_clear.__warningregistry__.clear() except AttributeError: pass try: __warningregistry__.clear() except NameError: pass original_warnings = warni...
['def', 'warnings_state(module):', 'global', '__warningregistry__', 'for', 'to_clear', 'in', '(sys,', 'warning_tests):', 'try:', 'to_clear.__warningregistry__.clear()', 'except', 'AttributeError:', 'pass', 'try:', '__warningregistry__.clear()', 'except', 'NameError:', 'pass', 'original_warnings', '=', 'warning_tests.wa...
283,870
tensorflow/quantum
inner_product_grad_test.py
InnerProductAdjGradTest.test_correctness_empty
test_correctness_empty
Tests the inner product adj grad between two empty circuits.
[ "Tests", "the", "inner", "product", "adj", "grad", "between", "two", "empty", "circuits." ]
def test_correctness_empty(self): symbol_names = ['alpha', 'beta'] empty_cicuit = util.convert_to_tensor([cirq.Circuit()]) empty_symbols = tf.convert_to_tensor([], dtype=tf.dtypes.string) empty_values = tf.convert_to_tensor([[]]) other_program = util.convert_to_tensor([[cirq.Circuit()]]) prev_gr...
['def', 'test_correctness_empty(self):', 'symbol_names', '=', "['alpha',", "'beta']", 'empty_cicuit', '=', 'util.convert_to_tensor([cirq.Circuit()])', 'empty_symbols', '=', 'tf.convert_to_tensor([],', 'dtype=tf.dtypes.string)', 'empty_values', '=', 'tf.convert_to_tensor([[]])', 'other_program', '=', 'util.convert_to_te...
834,794
blokbot-io/OpenBlok
display.py
predict_and_show_stop
predict_and_show_stop
Ends identification process and closes the view window.
[ "Ends", "identification", "process", "and", "closes", "the", "view", "window." ]
def predict_and_show_stop(): config.identifying = False
['def', 'predict_and_show_stop():', 'config.identifying', '=', 'False']
274,918
tonyhuang2022/UPL
datasetbase.py
UPLDatasetBase.get_lab2cname
get_lab2cname
Get a label-to-classname mapping (dict).
[ "Get", "a", "label-to-classname", "mapping", "(dict)." ]
def get_lab2cname(self, data_source): container = set() if data_source is not None: for item in data_source: container.add((item.label, item.classname)) mapping = {label: classname for (label, classname) in container} labels = list(mapping.keys()) labels.sort() ...
['def', 'get_lab2cname(self,', 'data_source):', 'container', '=', 'set()', 'if', 'data_source', 'is', 'not', 'None:', 'for', 'item', 'in', 'data_source:', 'container.add((item.label,', 'item.classname))', 'mapping', '=', '{label:', 'classname', 'for', '(label,', 'classname)', 'in', 'container}', 'labels', '=', 'list(ma...
438,593
devashish-patel/webcam-motion-detector
readers.py
CArchiveReader.contents
contents
Return the names of the entries.
[ "Return", "the", "names", "of", "the", "entries." ]
def contents(self): rslt = [] for (dpos, dlen, ulen, flag, typcd, nm) in self.toc: rslt.append(nm) return rslt
['def', 'contents(self):', 'rslt', '=', '[]', 'for', '(dpos,', 'dlen,', 'ulen,', 'flag,', 'typcd,', 'nm)', 'in', 'self.toc:', 'rslt.append(nm)', 'return', 'rslt']
984,211
devashish-patel/webcam-motion-detector
cookiejar.py
FileCookieJar.save
save
Save cookies to a file.
[ "Save", "cookies", "to", "a", "file." ]
def save(self, filename=None, ignore_discard=False, ignore_expires=False): raise NotImplementedError()
['def', 'save(self,', 'filename=None,', 'ignore_discard=False,', 'ignore_expires=False):', 'raise', 'NotImplementedError()']
978,057
johnnyp2587/transfer-learning
test_models.py
test_custom_model_train
test_custom_model_train
Tests calling train on a custom TF model with a mock dataset and mock model and verifies we get back the return value from the fit function.
[ "Tests", "calling", "train", "on", "a", "custom", "TF", "model", "with", "a", "mock", "dataset", "and", "mock", "model", "and", "verifies", "we", "get", "back", "the", "return", "value", "from", "the", "fit", "function." ]
def test_custom_model_train(): model = model_factory.load_model('custom_model', ALEXNET, 'tensorflow', 'image_classification') mock_dataset = MagicMock() mock_dataset.__class__ = ImageClassificationDataset mock_dataset.class_names = ['1', '2', '3'] model._model = MagicMock() expected_return_valu...
['def', 'test_custom_model_train():', 'model', '=', "model_factory.load_model('custom_model',", 'ALEXNET,', "'tensorflow',", "'image_classification')", 'mock_dataset', '=', 'MagicMock()', 'mock_dataset.__class__', '=', 'ImageClassificationDataset', 'mock_dataset.class_names', '=', "['1',", "'2',", "'3']", 'model._model...
927,052
rlgraph/rlgraph
mem_segment_tree.py
MemSegmentTree.get_min_value
get_min_value
Returns min value of storage variable.
[ "Returns", "min", "value", "of", "storage", "variable." ]
def get_min_value(self, start=0, stop=None): return self.reduce(start, stop, reduce_op=min)
['def', 'get_min_value(self,', 'start=0,', 'stop=None):', 'return', 'self.reduce(start,', 'stop,', 'reduce_op=min)']
862,477
openvinotoolkit/training_extensions
hyperband.py
Bracket.calcuate_max_rung_idx
calcuate_max_rung_idx
Calculate the number of rungs the bracket needs.
[ "Calculate", "the", "number", "of", "rungs", "the", "bracket", "needs." ]
def calcuate_max_rung_idx(minimum_resource: Union[float, int], maximum_resource: Union[float, int], reduction_factor: int) -> int: check_positive(minimum_resource, 'minimum_resource') check_positive(maximum_resource, 'maximum_resource') check_positive(reduction_factor, 'reduction_factor') if minimum_res...
['def', 'calcuate_max_rung_idx(minimum_resource:', 'Union[float,', 'int],', 'maximum_resource:', 'Union[float,', 'int],', 'reduction_factor:', 'int)', '->', 'int:', 'check_positive(minimum_resource,', "'minimum_resource')", 'check_positive(maximum_resource,', "'maximum_resource')", 'check_positive(reduction_factor,', "...
919,123
salu133445/binarygan
neuralnet.py
NeuralNet.build
build
Build the neural network.
[ "Build", "the", "neural", "network." ]
def build(self, architecture): layers = [] for (idx, structure) in enumerate(architecture): if idx > 0: prev_layer = layers[idx - 1].tensor_out else: prev_layer = self.tensor_in if len(structure) > 4: skip_connection = structure[4][0] else: ...
['def', 'build(self,', 'architecture):', 'layers', '=', '[]', 'for', '(idx,', 'structure)', 'in', 'enumerate(architecture):', 'if', 'idx', '>', '0:', 'prev_layer', '=', 'layers[idx', '-', '1].tensor_out', 'else:', 'prev_layer', '=', 'self.tensor_in', 'if', 'len(structure)', '>', '4:', 'skip_connection', '=', 'structure...
461,008
TrellixVulnTeam/Unsupervised_Learning_HFI7
utils.py
poll_ignore_interrupts
poll_ignore_interrupts
Simple wrapper around poll to register file descriptors and ignore signals.
[ "Simple", "wrapper", "around", "poll", "to", "register", "file", "descriptors", "and", "ignore", "signals." ]
def poll_ignore_interrupts(fds, timeout=None): if timeout is not None: end_time = time.time() + timeout poller = select.poll() for fd in fds: poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR) while True: try: timeout_ms = None if ti...
['def', 'poll_ignore_interrupts(fds,', 'timeout=None):', 'if', 'timeout', 'is', 'not', 'None:', 'end_time', '=', 'time.time()', '+', 'timeout', 'poller', '=', 'select.poll()', 'for', 'fd', 'in', 'fds:', 'poller.register(fd,', 'select.POLLIN', '|', 'select.POLLPRI', '|', 'select.POLLHUP', '|', 'select.POLLERR)', 'while'...
454,148
PacktPublishing/Learning-Generative-Adversarial-Networks
dcgan.py
DCGAN.loss
loss
build models, calculate losses.
[ "build", "models,", "calculate", "losses." ]
def loss(self, traindata): generated = self.g(self.z, training=True) g_outputs = self.d(generated, training=True, name='g') t_outputs = self.d(traindata, training=True, name='t') tf.add_to_collection('g_losses', tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.ones([self.batch_siz...
['def', 'loss(self,', 'traindata):', 'generated', '=', 'self.g(self.z,', 'training=True)', 'g_outputs', '=', 'self.d(generated,', 'training=True,', "name='g')", 't_outputs', '=', 'self.d(traindata,', 'training=True,', "name='t')", "tf.add_to_collection('g_losses',", 'tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_wi...
587,907
rlpy/rlpy
transformations.py
Arcball.setaxes
setaxes
Set axes to constrain rotations.
[ "Set", "axes", "to", "constrain", "rotations." ]
def setaxes(self, *axes): if axes is None: self._axes = None else: self._axes = [unit_vector(axis) for axis in axes]
['def', 'setaxes(self,', '*axes):', 'if', 'axes', 'is', 'None:', 'self._axes', '=', 'None', 'else:', 'self._axes', '=', '[unit_vector(axis)', 'for', 'axis', 'in', 'axes]']
334,381
fudan-zvg/SeaFormer
test_models.py
test_model_load_pretrained
test_model_load_pretrained
Create that pretrained weights load, verify support for in_chans != 3 while doing so.
[ "Create", "that", "pretrained", "weights", "load,", "verify", "support", "for", "in_chans", "!=", "3", "while", "doing", "so." ]
def test_model_load_pretrained(model_name, batch_size): in_chans = 3 if 'pruned' in model_name else 1 create_model(model_name, pretrained=True, in_chans=in_chans, num_classes=5) create_model(model_name, pretrained=True, in_chans=in_chans, num_classes=0)
['def', 'test_model_load_pretrained(model_name,', 'batch_size):', 'in_chans', '=', '3', 'if', "'pruned'", 'in', 'model_name', 'else', '1', 'create_model(model_name,', 'pretrained=True,', 'in_chans=in_chans,', 'num_classes=5)', 'create_model(model_name,', 'pretrained=True,', 'in_chans=in_chans,', 'num_classes=0)']
855,292
angeladai/ScanComplete
util.py
preprocess_target_sem
preprocess_target_sem
Preprocesses target sem (fix ceils labeled as floors).
[ "Preprocesses", "target", "sem", "(fix", "ceils", "labeled", "as", "floors)." ]
def preprocess_target_sem(sem): mid = sem.shape[1] // 2 ceilings = np.ones(shape=sem[:, mid:, :].shape, dtype=np.uint8) * 2 top = sem[:, mid:, :] bottom = sem[:, :mid, :] top = np.where(np.equal(top, 4), ceilings, top) return np.concatenate([bottom, top], 1)
['def', 'preprocess_target_sem(sem):', 'mid', '=', 'sem.shape[1]', '//', '2', 'ceilings', '=', 'np.ones(shape=sem[:,', 'mid:,', ':].shape,', 'dtype=np.uint8)', '*', '2', 'top', '=', 'sem[:,', 'mid:,', ':]', 'bottom', '=', 'sem[:,', ':mid,', ':]', 'top', '=', 'np.where(np.equal(top,', '4),', 'ceilings,', 'top)', 'return...
845,868
bm777/object_detection
net.py
configure_bbox_reg_weights
configure_bbox_reg_weights
Compatibility for old models trained with bounding box regression mean/std normalization (instead of fixed weights).
[ "Compatibility", "for", "old", "models", "trained", "with", "bounding", "box", "regression", "mean/std", "normalization", "(instead", "of", "fixed", "weights)." ]
def configure_bbox_reg_weights(model, saved_cfg): if 'MODEL' not in saved_cfg or 'BBOX_REG_WEIGHTS' not in saved_cfg.MODEL: logger.warning('Model from weights file was trained before config key MODEL.BBOX_REG_WEIGHTS was added. Forcing MODEL.BBOX_REG_WEIGHTS = (1., 1., 1., 1.) to ensure correct **inference*...
['def', 'configure_bbox_reg_weights(model,', 'saved_cfg):', 'if', "'MODEL'", 'not', 'in', 'saved_cfg', 'or', "'BBOX_REG_WEIGHTS'", 'not', 'in', 'saved_cfg.MODEL:', "logger.warning('Model", 'from', 'weights', 'file', 'was', 'trained', 'before', 'config', 'key', 'MODEL.BBOX_REG_WEIGHTS', 'was', 'added.', 'Forcing', 'MODE...
773,564
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
expert_utils.py
DistributedSparseDispatcher.dispatch
dispatch
Create one input Tensor for each expert.
[ "Create", "one", "input", "Tensor", "for", "each", "expert." ]
def dispatch(self, inp): dispatched = self._dp(lambda a, b: a.dispatch(b), self._dispatchers, inp) ret = self._ep(tf.concat, transpose_list_of_lists(dispatched), 0) if ret[0].dtype == tf.float32: ret = self._ep(common_layers.convert_gradient_to_tensor, ret) return ret
['def', 'dispatch(self,', 'inp):', 'dispatched', '=', 'self._dp(lambda', 'a,', 'b:', 'a.dispatch(b),', 'self._dispatchers,', 'inp)', 'ret', '=', 'self._ep(tf.concat,', 'transpose_list_of_lists(dispatched),', '0)', 'if', 'ret[0].dtype', '==', 'tf.float32:', 'ret', '=', 'self._ep(common_layers.convert_gradient_to_tensor,...
966,097
myothida/Supervised-Machine-Learning
base.py
Mappable.default
default
Get the default value for this feature, or access the relevant rcParam.
[ "Get", "the", "default", "value", "for", "this", "feature,", "or", "access", "the", "relevant", "rcParam." ]
def default(self) -> Any: if self._val is not None: return self._val return mpl.rcParams.get(self._rc)
['def', 'default(self)', '->', 'Any:', 'if', 'self._val', 'is', 'not', 'None:', 'return', 'self._val', 'return', 'mpl.rcParams.get(self._rc)']
446,804
google/deepvariant
run_deepvariant_keras.py
make_examples_command
make_examples_command
Returns a make_examples (command, logfile) for subprocess.
[ "Returns", "a", "make_examples", "(command,", "logfile)", "for", "subprocess." ]
def make_examples_command(ref, reads, examples, extra_args, runtime_by_region_path=None, **kwargs): command = ['time', 'seq 0 {} |'.format(_NUM_SHARDS.value - 1), 'parallel -q --halt 2 --line-buffer', '/opt/deepvariant/bin/make_examples'] command.extend(['--mode', 'calling']) command.extend(['--ref', '"{}"'...
['def', 'make_examples_command(ref,', 'reads,', 'examples,', 'extra_args,', 'runtime_by_region_path=None,', '**kwargs):', 'command', '=', "['time',", "'seq", '0', '{}', "|'.format(_NUM_SHARDS.value", '-', '1),', "'parallel", '-q', '--halt', '2', "--line-buffer',", "'/opt/deepvariant/bin/make_examples']", "command.exten...
540,535
asyml/texar
paired_text_data.py
PairedTextData.source_text_id_name
source_text_id_name
The name of the source text index tensor, "source_text_ids" by default.
[ "The", "name", "of", "the", "source", "text", "index", "tensor,", "\"source_text_ids\"", "by", "default." ]
def source_text_id_name(self): name = dsutils._connect_name(self._data_spec.name_prefix[0], self._src_decoder.text_id_tensor_name) return name
['def', 'source_text_id_name(self):', 'name', '=', 'dsutils._connect_name(self._data_spec.name_prefix[0],', 'self._src_decoder.text_id_tensor_name)', 'return', 'name']
924,567
surafelml/adapt-mnmt
ark_to_records.py
ark_to_records
ark_to_records
Converts ARK dataset to TFRecords.
[ "Converts", "ARK", "dataset", "to", "TFRecords." ]
def ark_to_records(ark_filename, out_prefix, dtype=np.float32): record_writer = tf.python_io.TFRecordWriter(out_prefix + '.records') count = 0 with io.open(ark_filename, encoding='utf-8') as ark_file: while True: (ark_idx, vector) = consume_next_vector(ark_file, dtype=dtype) ...
['def', 'ark_to_records(ark_filename,', 'out_prefix,', 'dtype=np.float32):', 'record_writer', '=', 'tf.python_io.TFRecordWriter(out_prefix', '+', "'.records')", 'count', '=', '0', 'with', 'io.open(ark_filename,', "encoding='utf-8')", 'as', 'ark_file:', 'while', 'True:', '(ark_idx,', 'vector)', '=', 'consume_next_vector...
407,754
google/balloon-learning-environment
dopamine_utils.py
get_latest_checkpoint
get_latest_checkpoint
Find the episode ID of the latest checkpoint, if any.
[ "Find", "the", "episode", "ID", "of", "the", "latest", "checkpoint,", "if", "any." ]
def get_latest_checkpoint(checkpoint_dir: str) -> int: glob = osp.join(checkpoint_dir, 'checkpoint_*.pkl') def extract_episode(x): return int(x[x.rfind('checkpoint_') + 11:-4]) try: checkpoint_files = tf.io.gfile.glob(glob) except tf.errors.NotFoundError: logging.warning('Unable...
['def', 'get_latest_checkpoint(checkpoint_dir:', 'str)', '->', 'int:', 'glob', '=', 'osp.join(checkpoint_dir,', "'checkpoint_*.pkl')", 'def', 'extract_episode(x):', 'return', "int(x[x.rfind('checkpoint_')", '+', '11:-4])', 'try:', 'checkpoint_files', '=', 'tf.io.gfile.glob(glob)', 'except', 'tf.errors.NotFoundError:', ...
422,325
sek788432/Waymo-2D-Object-Detection
get_dataset_colormap_test.py
VisualizationUtilTest.testLabelToPASCALColorImage
testLabelToPASCALColorImage
Test the value of the converted label value.
[ "Test", "the", "value", "of", "the", "converted", "label", "value." ]
def testLabelToPASCALColorImage(self): label = np.array([[0, 16, 16], [52, 7, 52]]) expected_result = np.array([[[0, 0, 0], [0, 64, 0], [0, 64, 0]], [[0, 64, 192], [128, 128, 128], [0, 64, 192]]]) colored_label = get_dataset_colormap.label_to_color_image(label, get_dataset_colormap.get_pascal_name()) se...
['def', 'testLabelToPASCALColorImage(self):', 'label', '=', 'np.array([[0,', '16,', '16],', '[52,', '7,', '52]])', 'expected_result', '=', 'np.array([[[0,', '0,', '0],', '[0,', '64,', '0],', '[0,', '64,', '0]],', '[[0,', '64,', '192],', '[128,', '128,', '128],', '[0,', '64,', '192]]])', 'colored_label', '=', 'get_datas...
974,187
omarmhaimdat/twitter_nlp_native_swift
parse.py
splittag
splittag
splittag('/path#tag') --> '/path', 'tag'.
[ "splittag('/path#tag')", "-->", "'/path',", "'tag'." ]
def splittag(url): global _tagprog if _tagprog is None: import re _tagprog = re.compile('^(.*)#([^#]*)$') match = _tagprog.match(url) if match: return match.group(1, 2) return (url, None)
['def', 'splittag(url):', 'global', '_tagprog', 'if', '_tagprog', 'is', 'None:', 'import', 're', '_tagprog', '=', "re.compile('^(.*)#([^#]*)$')", 'match', '=', '_tagprog.match(url)', 'if', 'match:', 'return', 'match.group(1,', '2)', 'return', '(url,', 'None)']
953,612
Erotemic/vtool_ibeis
fontdemo.py
Glyph.from_glyphslot
from_glyphslot
Construct and return a Glyph object from a FreeType GlyphSlot.
[ "Construct", "and", "return", "a", "Glyph", "object", "from", "a", "FreeType", "GlyphSlot." ]
def from_glyphslot(slot): pixels = Glyph.unpack_mono_bitmap(slot.bitmap) (width, height) = (slot.bitmap.width, slot.bitmap.rows) top = slot.bitmap_top advance_width = slot.advance.x // 64 return Glyph(pixels, width, height, top, advance_width)
['def', 'from_glyphslot(slot):', 'pixels', '=', 'Glyph.unpack_mono_bitmap(slot.bitmap)', '(width,', 'height)', '=', '(slot.bitmap.width,', 'slot.bitmap.rows)', 'top', '=', 'slot.bitmap_top', 'advance_width', '=', 'slot.advance.x', '//', '64', 'return', 'Glyph(pixels,', 'width,', 'height,', 'top,', 'advance_width)']
940,538
huawei-noah/xingtian
pytorch_fn.py
Relu.forward
forward
Do an inference on Relu.
[ "Do", "an", "inference", "on", "Relu." ]
def forward(self, x): return super().forward(x)
['def', 'forward(self,', 'x):', 'return', 'super().forward(x)']
962,802
dayorbyte/MongoAlchemy
session.py
Session.save
save
Saves an item into the work queue and flushes.
[ "Saves", "an", "item", "into", "the", "work", "queue", "and", "flushes." ]
def save(self, item, safe=None): self.add(item, safe=safe)
['def', 'save(self,', 'item,', 'safe=None):', 'self.add(item,', 'safe=safe)']
241,004
fcjian/TOOD
coco_panoptic.py
CocoPanopticDataset.evaluate_pan_json
evaluate_pan_json
Evaluate PQ according to the panoptic results json file.
[ "Evaluate", "PQ", "according", "to", "the", "panoptic", "results", "json", "file." ]
def evaluate_pan_json(self, result_files, outfile_prefix, logger=None): gt_json = self.coco.img_ann_map gt_json = [{'image_id': k, 'segments_info': v, 'file_name': self.formatter.format(k)} for (k, v) in gt_json.items()] pred_json = mmcv.load(result_files['panoptic']) pred_json = dict(((el['image_id'], ...
['def', 'evaluate_pan_json(self,', 'result_files,', 'outfile_prefix,', 'logger=None):', 'gt_json', '=', 'self.coco.img_ann_map', 'gt_json', '=', "[{'image_id':", 'k,', "'segments_info':", 'v,', "'file_name':", 'self.formatter.format(k)}', 'for', '(k,', 'v)', 'in', 'gt_json.items()]', 'pred_json', '=', "mmcv.load(result...
901,897
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
common_layers.py
layer_norm_compute_python
layer_norm_compute_python
Layer norm raw computation.
[ "Layer", "norm", "raw", "computation." ]
def layer_norm_compute_python(x, epsilon, scale, bias): (epsilon, scale, bias) = [cast_like(t, x) for t in [epsilon, scale, bias]] mean = tf.reduce_mean(x, axis=[-1], keepdims=True) variance = tf.reduce_mean(tf.square(x - mean), axis=[-1], keepdims=True) norm_x = (x - mean) * tf.rsqrt(variance + epsilon...
['def', 'layer_norm_compute_python(x,', 'epsilon,', 'scale,', 'bias):', '(epsilon,', 'scale,', 'bias)', '=', '[cast_like(t,', 'x)', 'for', 't', 'in', '[epsilon,', 'scale,', 'bias]]', 'mean', '=', 'tf.reduce_mean(x,', 'axis=[-1],', 'keepdims=True)', 'variance', '=', 'tf.reduce_mean(tf.square(x', '-', 'mean),', 'axis=[-1...
965,255
Ruturaj123/Flowchart-Detection
label_wav.py
load_labels
load_labels
Read in labels, one label per line.
[ "Read", "in", "labels,", "one", "label", "per", "line." ]
def load_labels(filename): return [line.rstrip() for line in tf.gfile.GFile(filename)]
['def', 'load_labels(filename):', 'return', '[line.rstrip()', 'for', 'line', 'in', 'tf.gfile.GFile(filename)]']
604,903
tensorflow/quantum
util.py
random_symbol_circuit_resolver_batch
random_symbol_circuit_resolver_batch
Generate a batch of random circuits and resolvers.
[ "Generate", "a", "batch", "of", "random", "circuits", "and", "resolvers." ]
def random_symbol_circuit_resolver_batch(qubits, symbols, batch_size, *, n_moments=15, p=0.9, include_scalars=True, include_channels=False): return_circuits = [] return_resolvers = [] for _ in range(batch_size): return_circuits.append(random_symbol_circuit(qubits, symbols, n_moments=n_moments, p=p, ...
['def', 'random_symbol_circuit_resolver_batch(qubits,', 'symbols,', 'batch_size,', '*,', 'n_moments=15,', 'p=0.9,', 'include_scalars=True,', 'include_channels=False):', 'return_circuits', '=', '[]', 'return_resolvers', '=', '[]', 'for', '_', 'in', 'range(batch_size):', 'return_circuits.append(random_symbol_circuit(qubi...
835,122
rasbt/mlxtend
time_series.py
plot_splits
plot_splits
Visualize splits by group.
[ "Visualize", "splits", "by", "group." ]
def plot_splits(X, y, groups, image_file_path=None, **cv_args): cv = GroupTimeSeriesSplit(**cv_args) cv._n_groups = len(np.unique(groups)) cv._calculate_split_params() n_splits = cv.n_splits plot_split_indices(cv, cv_args, X, y, groups, n_splits, image_file_path=image_file_path)
['def', 'plot_splits(X,', 'y,', 'groups,', 'image_file_path=None,', '**cv_args):', 'cv', '=', 'GroupTimeSeriesSplit(**cv_args)', 'cv._n_groups', '=', 'len(np.unique(groups))', 'cv._calculate_split_params()', 'n_splits', '=', 'cv.n_splits', 'plot_split_indices(cv,', 'cv_args,', 'X,', 'y,', 'groups,', 'n_splits,', 'image...
631,248
zbyte64/django-hyperadmin
filters.py
BaseFilter.get_links
get_links
Returns links representing the filterable actions.
[ "Returns", "links", "representing", "the", "filterable", "actions." ]
def get_links(self, **link_kwargs): return []
['def', 'get_links(self,', '**link_kwargs):', 'return', '[]']
164,670
ryu-ed/SpaceInvaders_Ros
reports_handler_mix_in.py
ReportsHandlerMixIn.report_order
report_order
Return a list of reports, sorted in the order in which they must be called.
[ "Return", "a", "list", "of", "reports,", "sorted", "in", "the", "order", "in", "which", "they", "must", "be", "called." ]
def report_order(self): return list(self._reports)
['def', 'report_order(self):', 'return', 'list(self._reports)']
370,211
akandykeller/NeuralWaveMachines
jaxline_configs.py
sym_metric_hgn_plus_plus_sweep
sym_metric_hgn_plus_plus_sweep
HGN++ experimental sweep for the SyMetric paper.
[ "HGN++", "experimental", "sweep", "for", "the", "SyMetric", "paper." ]
def sym_metric_hgn_plus_plus_sweep(): model_config = copy.deepcopy(default_config_dict) model_config.name = 'HGN' sweeps = list() for elbo_beta_final in [0.001, 0.1, 1.0, 2.0]: sweeps.append({config_prefix + 'optimizer.kwargs.learning_rate': 0.00015, model_prefix + 'latent_training_type': 'forwa...
['def', 'sym_metric_hgn_plus_plus_sweep():', 'model_config', '=', 'copy.deepcopy(default_config_dict)', 'model_config.name', '=', "'HGN'", 'sweeps', '=', 'list()', 'for', 'elbo_beta_final', 'in', '[0.001,', '0.1,', '1.0,', '2.0]:', 'sweeps.append({config_prefix', '+', "'optimizer.kwargs.learning_rate':", '0.00015,', 'm...
293,528
sunishsheth2009/ChatterBot
ttk.py
Progressbar.stop
stop
Stop autoincrement mode: cancels any recurring timer event initiated by start.
[ "Stop", "autoincrement", "mode:", "cancels", "any", "recurring", "timer", "event", "initiated", "by", "start." ]
def stop(self): self.tk.call(self._w, 'stop')
['def', 'stop(self):', 'self.tk.call(self._w,', "'stop')"]
528,175
AndrewYinLi/lstm-neural-network-spam-filter
association.py
NgramAssocMeasures.jaccard
jaccard
Scores ngrams using the Jaccard index.
[ "Scores", "ngrams", "using", "the", "Jaccard", "index." ]
def jaccard(cls, *marginals): cont = cls._contingency(*marginals) return cont[0] / sum(cont[:-1])
['def', 'jaccard(cls,', '*marginals):', 'cont', '=', 'cls._contingency(*marginals)', 'return', 'cont[0]', '/', 'sum(cont[:-1])']
218,023
RasaHQ/rasa_core
registry.py
featurizer_from_module_path
featurizer_from_module_path
Given the name of a featurizer module tries to retrieve it.
[ "Given", "the", "name", "of", "a", "featurizer", "module", "tries", "to", "retrieve", "it." ]
def featurizer_from_module_path(module_path: Text) -> Type['TrackerFeaturizer']: from rasa.core import utils try: return utils.class_from_module_path(module_path, lookup_path='rasa.core.featurizers') except ImportError: raise ImportError("Cannot retrieve featurizer from path '{}'".format(mod...
['def', 'featurizer_from_module_path(module_path:', 'Text)', '->', "Type['TrackerFeaturizer']:", 'from', 'rasa.core', 'import', 'utils', 'try:', 'return', 'utils.class_from_module_path(module_path,', "lookup_path='rasa.core.featurizers')", 'except', 'ImportError:', 'raise', 'ImportError("Cannot', 'retrieve', 'featurize...
838,200
tensorly/quantum
spin_system_test.py
TFIRectangularTest.test_returned_objects
test_returned_objects
Test that the length and types of returned objects are correct.
[ "Test", "that", "the", "length", "and", "types", "of", "returned", "objects", "are", "correct." ]
def test_returned_objects(self): for nspins in self.supported_nspins_tfi_rectangular: (circuits, labels, pauli_sums, addinfo) = self.data_dict_tfi_rectangular[nspins] self.assertLen(circuits, 51) self.assertLen(labels, 51) self.assertLen(pauli_sums, 51) self.assertLen(addinfo...
['def', 'test_returned_objects(self):', 'for', 'nspins', 'in', 'self.supported_nspins_tfi_rectangular:', '(circuits,', 'labels,', 'pauli_sums,', 'addinfo)', '=', 'self.data_dict_tfi_rectangular[nspins]', 'self.assertLen(circuits,', '51)', 'self.assertLen(labels,', '51)', 'self.assertLen(pauli_sums,', '51)', 'self.asser...
835,066
YuYaoYang2333/SyntaLinker
cnn_factory.py
shape_transform
shape_transform
Tranform the size of the tensors to fit for conv input.
[ "Tranform", "the", "size", "of", "the", "tensors", "to", "fit", "for", "conv", "input." ]
def shape_transform(x): return torch.unsqueeze(torch.transpose(x, 1, 2), 3)
['def', 'shape_transform(x):', 'return', 'torch.unsqueeze(torch.transpose(x,', '1,', '2),', '3)']
905,964
intra2net/guibot
test_finder.py
FinderTest.test_feature_nomatch
test_feature_nomatch
Test for unsuccessful match of different images for all feature CV backends.
[ "Test", "for", "unsuccessful", "match", "of", "different", "images", "for", "all", "feature", "CV", "backends." ]
def test_feature_nomatch(self): finder = FeatureFinder() finder.params['find']['similarity'].value = 0.25 i = 1 for feature in finder.algorithms['feature_projectors']: for fdetect in finder.algorithms['feature_detectors']: for fextract in finder.algorithms['feature_extractors']: ...
['def', 'test_feature_nomatch(self):', 'finder', '=', 'FeatureFinder()', "finder.params['find']['similarity'].value", '=', '0.25', 'i', '=', '1', 'for', 'feature', 'in', "finder.algorithms['feature_projectors']:", 'for', 'fdetect', 'in', "finder.algorithms['feature_detectors']:", 'for', 'fextract', 'in', "finder.algori...
572,642
rlworkgroup/garage
test_multi_headed_mlp_module.py
test_multi_headed_mlp_module_with_layernorm
test_multi_headed_mlp_module_with_layernorm
Test Multi-headed MLPModule with layer normalization.
[ "Test", "Multi-headed", "MLPModule", "with", "layer", "normalization." ]
def test_multi_headed_mlp_module_with_layernorm(input_dim, output_dim, hidden_sizes, output_w_init_vals, n_heads): module = MultiHeadedMLPModule(n_heads=n_heads, input_dim=input_dim, output_dims=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=None, layer_normalization=True, hidden_w_init=nn.init.ones_, o...
['def', 'test_multi_headed_mlp_module_with_layernorm(input_dim,', 'output_dim,', 'hidden_sizes,', 'output_w_init_vals,', 'n_heads):', 'module', '=', 'MultiHeadedMLPModule(n_heads=n_heads,', 'input_dim=input_dim,', 'output_dims=output_dim,', 'hidden_sizes=hidden_sizes,', 'hidden_nonlinearity=None,', 'layer_normalization...
201,036
RasaHQ/rasa
io.py
configure_colored_logging
configure_colored_logging
Configures coloredlogs library for specified loglevel.
[ "Configures", "coloredlogs", "library", "for", "specified", "loglevel." ]
def configure_colored_logging(loglevel: Text) -> None: import coloredlogs loglevel = loglevel or os.environ.get(rasa.shared.constants.ENV_LOG_LEVEL, rasa.shared.constants.DEFAULT_LOG_LEVEL) field_styles = coloredlogs.DEFAULT_FIELD_STYLES.copy() field_styles['asctime'] = {} level_styles = coloredlogs...
['def', 'configure_colored_logging(loglevel:', 'Text)', '->', 'None:', 'import', 'coloredlogs', 'loglevel', '=', 'loglevel', 'or', 'os.environ.get(rasa.shared.constants.ENV_LOG_LEVEL,', 'rasa.shared.constants.DEFAULT_LOG_LEVEL)', 'field_styles', '=', 'coloredlogs.DEFAULT_FIELD_STYLES.copy()', "field_styles['asctime']",...
837,856
deepmind/dm_control
user_input.py
InputMap.clear_bindings
clear_bindings
Clears registered action bindings, while keeping key aliases.
[ "Clears", "registered", "action", "bindings,", "while", "keeping", "key", "aliases." ]
def clear_bindings(self): self._action_callbacks = {} self._double_click_callbacks = {} self._plane_callback = [] self._z_axis_callback = [] self._active_exclusive = _NO_EXCLUSIVE_KEY
['def', 'clear_bindings(self):', 'self._action_callbacks', '=', '{}', 'self._double_click_callbacks', '=', '{}', 'self._plane_callback', '=', '[]', 'self._z_axis_callback', '=', '[]', 'self._active_exclusive', '=', '_NO_EXCLUSIVE_KEY']
165,698
enuguru/artificial_intelligence_and_machine_learning
searching.py
ResultsPage.is_last_page
is_last_page
Returns True if this object represents the last page of results.
[ "Returns", "True", "if", "this", "object", "represents", "the", "last", "page", "of", "results." ]
def is_last_page(self): return self.pagecount == 0 or self.pagenum == self.pagecount
['def', 'is_last_page(self):', 'return', 'self.pagecount', '==', '0', 'or', 'self.pagenum', '==', 'self.pagecount']
133,125
zhang614/MicroGrid
cookiejar.py
CookieJar.extract_cookies
extract_cookies
Extract cookies from response, where allowable given the request.
[ "Extract", "cookies", "from", "response,", "where", "allowable", "given", "the", "request." ]
def extract_cookies(self, response, request): _debug('extract_cookies: %s', response.info()) self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) for cookie in self.make_cookies(response, request): if self._policy.set_ok(cookie, request): ...
['def', 'extract_cookies(self,', 'response,', 'request):', "_debug('extract_cookies:", "%s',", 'response.info())', 'self._cookies_lock.acquire()', 'try:', 'self._policy._now', '=', 'self._now', '=', 'int(time.time())', 'for', 'cookie', 'in', 'self.make_cookies(response,', 'request):', 'if', 'self._policy.set_ok(cookie,...
636,288
netket/netket
history.py
History.append
append
Append another value to this history object.
[ "Append", "another", "value", "to", "this", "history", "object." ]
def append(self, val: Any, it: Optional[Number]=None): append(self, val, it)
['def', 'append(self,', 'val:', 'Any,', 'it:', 'Optional[Number]=None):', 'append(self,', 'val,', 'it)']
736,248
twangnh/SimCal
lvis.py
LVIS.ann_to_mask
ann_to_mask
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
[ "Convert", "annotation", "which", "can", "be", "polygons,", "uncompressed", "RLE,", "or", "RLE", "to", "binary", "mask." ]
def ann_to_mask(self, ann): rle = self.ann_to_rle(ann) return mask_utils.decode(rle)
['def', 'ann_to_mask(self,', 'ann):', 'rle', '=', 'self.ann_to_rle(ann)', 'return', 'mask_utils.decode(rle)']
934,761
enuguru/artificial_intelligence_and_machine_
searching.py
Results.estimated_min_length
estimated_min_length
The estimated minimum number of matching documents, or the exact number of matching documents if it's known.
[ "The", "estimated", "minimum", "number", "of", "matching", "documents,", "or", "the", "exact", "number", "of", "matching", "documents", "if", "it's", "known." ]
def estimated_min_length(self): if self.has_exact_length(): return len(self) else: return self.q.estimate_min_size(self.searcher.reader())
['def', 'estimated_min_length(self):', 'if', 'self.has_exact_length():', 'return', 'len(self)', 'else:', 'return', 'self.q.estimate_min_size(self.searcher.reader())']
133,150
Eric3911/OpenAGI
sgd_input_example.py
SGDInputExample.make_copy_of_categorical_features
make_copy_of_categorical_features
Make a copy of the current example with utterance and categorical features.
[ "Make", "a", "copy", "of", "the", "current", "example", "with", "utterance", "and", "categorical", "features." ]
def make_copy_of_categorical_features(self): new_example = self.make_copy() new_example.categorical_slot_status = self.categorical_slot_status return new_example
['def', 'make_copy_of_categorical_features(self):', 'new_example', '=', 'self.make_copy()', 'new_example.categorical_slot_status', '=', 'self.categorical_slot_status', 'return', 'new_example']
273,231
idsia-robotics/learning-long-range-perception
train.py
train
train
Train the neural network model, save the weights and show the learning error over time.
[ "Train", "the", "neural", "network", "model,", "save", "the", "weights", "and", "show", "the", "learning", "error", "over", "time." ]
def train(): parser = argparse.ArgumentParser() parser.add_argument('-n', '--name', type=str, help='name of the Model weights', default='model_' + str(datetime.now())) parser.add_argument('-f', '--filename', type=str, help='name of the dataset (.h5 file)', default='data_gazebo.h5') parser.add_argument('...
['def', 'train():', 'parser', '=', 'argparse.ArgumentParser()', "parser.add_argument('-n',", "'--name',", 'type=str,', "help='name", 'of', 'the', 'Model', "weights',", "default='model_'", '+', 'str(datetime.now()))', "parser.add_argument('-f',", "'--filename',", 'type=str,', "help='name", 'of', 'the', 'dataset', '(.h5'...
216,053
microsoft/maro
logger.py
Logger.warn
warn
Add a log with ``WARN`` level.
[ "Add", "a", "log", "with", "``WARN``", "level." ]
def warn(self, msg, *args): self._logger.warning(msg, *args, extra=self._extra)
['def', 'warn(self,', 'msg,', '*args):', 'self._logger.warning(msg,', '*args,', 'extra=self._extra)']
628,721
Yuting-Gao/DisCo-pytorch
vision_transformer_hybrid.py
vit_small_r_s16_p8_224
vit_small_r_s16_p8_224
R+ViT-S/S16 w/ 8x8 patch hybrid @ 224 x 224.
[ "R+ViT-S/S16", "w/", "8x8", "patch", "hybrid", "@", "224", "x", "224." ]
def vit_small_r_s16_p8_224(pretrained=False, **kwargs): backbone = _resnetv2(layers=(), **kwargs) model_kwargs = dict(patch_size=8, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_vision_transformer_hybrid('vit_small_r_s16_p8_224', backbone=backbone, pretrained=pretrained, **model_kwargs) ...
['def', 'vit_small_r_s16_p8_224(pretrained=False,', '**kwargs):', 'backbone', '=', '_resnetv2(layers=(),', '**kwargs)', 'model_kwargs', '=', 'dict(patch_size=8,', 'embed_dim=384,', 'depth=12,', 'num_heads=6,', '**kwargs)', 'model', '=', "_create_vision_transformer_hybrid('vit_small_r_s16_p8_224',", 'backbone=backbone,'...
187,201
googleapis/python-aiplatform
client.py
DatasetServiceClient.data_item_path
data_item_path
Returns a fully-qualified data_item string.
[ "Returns", "a", "fully-qualified", "data_item", "string." ]
def data_item_path(project: str, location: str, dataset: str, data_item: str) -> str: return 'projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}'.format(project=project, location=location, dataset=dataset, data_item=data_item)
['def', 'data_item_path(project:', 'str,', 'location:', 'str,', 'dataset:', 'str,', 'data_item:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}'.format(project=project,", 'location=location,', 'dataset=dataset,', 'data_item=data_item)']
810,328
palmettos/neat-autoencoders
statistics.py
StatisticsReporter.save_species_fitness
save_species_fitness
Log species' average fitness throughout evolution.
[ "Log", "species'", "average", "fitness", "throughout", "evolution." ]
def save_species_fitness(self, delimiter=' ', null_value='NA', filename='species_fitness.csv'): with open(filename, 'w') as f: w = csv.writer(f, delimiter=delimiter) for s in self.get_species_fitness(null_value): w.writerow(s)
['def', 'save_species_fitness(self,', "delimiter='", "',", "null_value='NA',", "filename='species_fitness.csv'):", 'with', 'open(filename,', "'w')", 'as', 'f:', 'w', '=', 'csv.writer(f,', 'delimiter=delimiter)', 'for', 's', 'in', 'self.get_species_fitness(null_value):', 'w.writerow(s)']
735,210
rudranil723/mini-main
credentials.py
ReadOnlyScoped.requires_scopes
requires_scopes
True if these credentials require scopes to obtain an access token.
[ "True", "if", "these", "credentials", "require", "scopes", "to", "obtain", "an", "access", "token." ]
def requires_scopes(self): return False
['def', 'requires_scopes(self):', 'return', 'False']
317,752
rudranil723/mini-main
retry_async.py
AsyncRetry.with_delay
with_delay
Return a copy of this retry with the given delay options.
[ "Return", "a", "copy", "of", "this", "retry", "with", "the", "given", "delay", "options." ]
def with_delay(self, initial=None, maximum=None, multiplier=None): return self._replace(initial=initial, maximum=maximum, multiplier=multiplier)
['def', 'with_delay(self,', 'initial=None,', 'maximum=None,', 'multiplier=None):', 'return', 'self._replace(initial=initial,', 'maximum=maximum,', 'multiplier=multiplier)']
317,688
FenHua/Robust_Logo_Detection
yolo_head.py
YOLOV3Head.loss_single
loss_single
Compute loss of a single image from a batch.
[ "Compute", "loss", "of", "a", "single", "image", "from", "a", "batch." ]
def loss_single(self, pred_map, target_map, neg_map): num_imgs = len(pred_map) pred_map = pred_map.permute(0, 2, 3, 1).reshape(num_imgs, -1, self.num_attrib) neg_mask = neg_map.float() pos_mask = target_map[..., 4] pos_and_neg_mask = neg_mask + pos_mask pos_mask = pos_mask.unsqueeze(dim=-1) ...
['def', 'loss_single(self,', 'pred_map,', 'target_map,', 'neg_map):', 'num_imgs', '=', 'len(pred_map)', 'pred_map', '=', 'pred_map.permute(0,', '2,', '3,', '1).reshape(num_imgs,', '-1,', 'self.num_attrib)', 'neg_mask', '=', 'neg_map.float()', 'pos_mask', '=', 'target_map[...,', '4]', 'pos_and_neg_mask', '=', 'neg_mask'...
826,858
BingSu12/TAP
model.py
CNN_FSHead.get_feats
get_feats
Takes in images from the support set and query video and returns CNN features.
[ "Takes", "in", "images", "from", "the", "support", "set", "and", "query", "video", "and", "returns", "CNN", "features." ]
def get_feats(self, support_images, target_images): support_features = self.backbone(support_images).squeeze() target_features = self.backbone(target_images).squeeze() dim = int(support_features.shape[1]) support_features = support_features.reshape(-1, self.args.seq_len, dim) target_features = targe...
['def', 'get_feats(self,', 'support_images,', 'target_images):', 'support_features', '=', 'self.backbone(support_images).squeeze()', 'target_features', '=', 'self.backbone(target_images).squeeze()', 'dim', '=', 'int(support_features.shape[1])', 'support_features', '=', 'support_features.reshape(-1,', 'self.args.seq_len...
365,321
ofirnachum/sequence_gan
book_demo.py
verify_sequence
verify_sequence
Not a true verification; only checks 3-grams.
[ "Not", "a", "true", "verification;", "only", "checks", "3-grams." ]
def verify_sequence(three_grams, seq): for i in range(len(seq) - 3): if tuple(seq[i:i + 3]) not in three_grams: return False return True
['def', 'verify_sequence(three_grams,', 'seq):', 'for', 'i', 'in', 'range(len(seq)', '-', '3):', 'if', 'tuple(seq[i:i', '+', '3])', 'not', 'in', 'three_grams:', 'return', 'False', 'return', 'True']
343,926
replit-archive/empythoned
commands.py
getoutput
getoutput
Return output (stdout or stderr) of executing cmd in a shell.
[ "Return", "output", "(stdout", "or", "stderr)", "of", "executing", "cmd", "in", "a", "shell." ]
def getoutput(cmd): return getstatusoutput(cmd)[1]
['def', 'getoutput(cmd):', 'return', 'getstatusoutput(cmd)[1]']
177,164
rifqind/Agent-Programs-3KS1
test_templateexporter.py
TestExporter.test_raw_template_constructor
test_raw_template_constructor
Test `raw_template` as a keyword argument in the exporter constructor.
[ "Test", "`raw_template`", "as", "a", "keyword", "argument", "in", "the", "exporter", "constructor." ]
def test_raw_template_constructor(self): nb = v4.new_notebook() nb.cells.append(v4.new_code_cell('some_text')) (output_constructor, _) = TemplateExporter(raw_template=raw_template).from_notebook_node(nb) assert 'blah' in output_constructor
['def', 'test_raw_template_constructor(self):', 'nb', '=', 'v4.new_notebook()', "nb.cells.append(v4.new_code_cell('some_text'))", '(output_constructor,', '_)', '=', 'TemplateExporter(raw_template=raw_template).from_notebook_node(nb)', 'assert', "'blah'", 'in', 'output_constructor']
42,713
arshpreetsingh/quantopian-machinelearning
history.py
History.append_string
append_string
Add string to the history.
[ "Add", "string", "to", "the", "history." ]
def append_string(self, string): self._loaded_strings.append(string) self.store_string(string)
['def', 'append_string(self,', 'string):', 'self._loaded_strings.append(string)', 'self.store_string(string)']
892,071
bm777/object_detection
nn.py
weight
weight
Get a weight variable.
[ "Get", "a", "weight", "variable." ]
def weight(name, shape, init='normal', range=0.1, stddev=0.001, init_val=None, group_id=0): if init_val != None: initializer = tf.constant_initializer(init_val) elif init == 'uniform': initializer = tf.random_uniform_initializer(-range, range) elif init == 'normal': initializer = tf....
['def', 'weight(name,', 'shape,', "init='normal',", 'range=0.1,', 'stddev=0.001,', 'init_val=None,', 'group_id=0):', 'if', 'init_val', '!=', 'None:', 'initializer', '=', 'tf.constant_initializer(init_val)', 'elif', 'init', '==', "'uniform':", 'initializer', '=', 'tf.random_uniform_initializer(-range,', 'range)', 'elif'...
793,191
weimin17/Object-Detection_HelmetDetection
component.py
ComponentBuilderBase.add_cell_output
add_cell_output
Adds an output to the current CellSubgraphSpec.
[ "Adds", "an", "output", "to", "the", "current", "CellSubgraphSpec." ]
def add_cell_output(self, tensor, name): if not self._cell_subgraph_spec: raise RuntimeError('already exported a CellSubgraphSpec') self._cell_subgraph_spec.output.add(name=name, tensor=tensor.name)
['def', 'add_cell_output(self,', 'tensor,', 'name):', 'if', 'not', 'self._cell_subgraph_spec:', 'raise', "RuntimeError('already", 'exported', 'a', "CellSubgraphSpec')", 'self._cell_subgraph_spec.output.add(name=name,', 'tensor=tensor.name)']
753,249
Katja-M/Python_NaturalLanguageProcessing
api.py
CorpusReader.license
license
Return the contents of the corpus LICENSE file, if it exists.
[ "Return", "the", "contents", "of", "the", "corpus", "LICENSE", "file,", "if", "it", "exists." ]
def license(self): return self.open('LICENSE').read()
['def', 'license(self):', 'return', "self.open('LICENSE').read()"]
866,132
intel/neural-compressor
utils.py
load_tensor_from_shard
load_tensor_from_shard
Load tensor from shard.
[ "Load", "tensor", "from", "shard." ]
def load_tensor_from_shard(pretrained_model_name_or_path, tensor_name, prefix=None): path = _get_path(pretrained_model_name_or_path) idx_dict = json.load(open(os.path.join(path, 'pytorch_model.bin.index.json'), 'r'))['weight_map'] if tensor_name not in idx_dict.keys(): if tensor_name.replace(f'{pref...
['def', 'load_tensor_from_shard(pretrained_model_name_or_path,', 'tensor_name,', 'prefix=None):', 'path', '=', '_get_path(pretrained_model_name_or_path)', 'idx_dict', '=', 'json.load(open(os.path.join(path,', "'pytorch_model.bin.index.json'),", "'r'))['weight_map']", 'if', 'tensor_name', 'not', 'in', 'idx_dict.keys():'...
737,948
jxwufan/AssociativeRetrieval
FastWeightsRNN.py
LayerNormFastWeightsBasicRNNCell.zero_fast_weights
zero_fast_weights
Return zero-filled fast_weights tensor(s).
[ "Return", "zero-filled", "fast_weights", "tensor(s)." ]
def zero_fast_weights(self, batch_size, dtype): state_size = self.state_size zeros = array_ops.zeros(array_ops.pack([batch_size, state_size, state_size]), dtype=dtype) zeros.set_shape([None, state_size, state_size]) return zeros
['def', 'zero_fast_weights(self,', 'batch_size,', 'dtype):', 'state_size', '=', 'self.state_size', 'zeros', '=', 'array_ops.zeros(array_ops.pack([batch_size,', 'state_size,', 'state_size]),', 'dtype=dtype)', 'zeros.set_shape([None,', 'state_size,', 'state_size])', 'return', 'zeros']
92,519
mattchorlian/Berkeley-CS188-Spring21
agents.py
Environment.default_location
default_location
Default location to place a new thing with unspecified location.
[ "Default", "location", "to", "place", "a", "new", "thing", "with", "unspecified", "location." ]
def default_location(self, thing): return None
['def', 'default_location(self,', 'thing):', 'return', 'None']
106,492
dbash/zerowaste
evaluate_utils.py
calculate_for_tags
calculate_for_tags
This function calculates precision, recall, and f1-score using tags.
[ "This", "function", "calculates", "precision,", "recall,", "and", "f1-score", "using", "tags." ]
def calculate_for_tags(pred_tags, gt_tags): if len(pred_tags) == 0 and len(gt_tags) == 0: return (100, 100, 100) elif len(pred_tags) == 0 or len(gt_tags) == 0: return (0, 0, 0) pred_tags = np.asarray(pred_tags) gt_tags = np.asarray(gt_tags) precision = pred_tags[:, np.newaxis] == gt_...
['def', 'calculate_for_tags(pred_tags,', 'gt_tags):', 'if', 'len(pred_tags)', '==', '0', 'and', 'len(gt_tags)', '==', '0:', 'return', '(100,', '100,', '100)', 'elif', 'len(pred_tags)', '==', '0', 'or', 'len(gt_tags)', '==', '0:', 'return', '(0,', '0,', '0)', 'pred_tags', '=', 'np.asarray(pred_tags)', 'gt_tags', '=', 'n...
971,790
apple/ml-cvnets
__init__.py
add_loss_fn_arguments
add_loss_fn_arguments
This method gets a parser object, and for every loss that is registered in the LOSS_REGISTRY adds its arguments to it.
[ "This", "method", "gets", "a", "parser", "object,", "and", "for", "every", "loss", "that", "is", "registered", "in", "the", "LOSS_REGISTRY", "adds", "its", "arguments", "to", "it." ]
def add_loss_fn_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: parser = BaseCriteria.add_arguments(parser=parser) parser = LOSS_REGISTRY.all_arguments(parser) return parser
['def', 'add_loss_fn_arguments(parser:', 'argparse.ArgumentParser)', '->', 'argparse.ArgumentParser:', 'parser', '=', 'BaseCriteria.add_arguments(parser=parser)', 'parser', '=', 'LOSS_REGISTRY.all_arguments(parser)', 'return', 'parser']
671,517
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
conftest.py
orient
orient
Fixture for orients excluding the table format.
[ "Fixture", "for", "orients", "excluding", "the", "table", "format." ]
def orient(request): return request.param
['def', 'orient(request):', 'return', 'request.param']
83,508
explosion/spacy-models
test_parser.py
test_en_parser_issue955
test_en_parser_issue955
Test that we don't have any nested noun chunks.
[ "Test", "that", "we", "don't", "have", "any", "nested", "noun", "chunks." ]
def test_en_parser_issue955(NLP): text = 'Does flight number three fifty-four require a connecting flight to get to Boston?' doc = NLP(text) seen_tokens = set() for np in doc.noun_chunks: for word in np: key = (word.i, word.text) assert key not in seen_tokens ...
['def', 'test_en_parser_issue955(NLP):', 'text', '=', "'Does", 'flight', 'number', 'three', 'fifty-four', 'require', 'a', 'connecting', 'flight', 'to', 'get', 'to', "Boston?'", 'doc', '=', 'NLP(text)', 'seen_tokens', '=', 'set()', 'for', 'np', 'in', 'doc.noun_chunks:', 'for', 'word', 'in', 'np:', 'key', '=', '(word.i,'...
894,464