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
weimin17/Object-Detection_HelmetDetection
bulk_component.py
fetch_differentiable_fixed_embeddings
fetch_differentiable_fixed_embeddings
Looks up fixed features with separate, differentiable, embedding lookup.
[ "Looks", "up", "fixed", "features", "with", "separate,", "differentiable,", "embedding", "lookup." ]
def fetch_differentiable_fixed_embeddings(comp, state, stride, during_training): _validate_embedded_fixed_features(comp) num_channels = len(comp.spec.fixed_feature) if not num_channels: return (state.handle, []) (state.handle, indices, ids, weights, num_steps) = dragnn_ops.bulk_fixed_features(st...
['def', 'fetch_differentiable_fixed_embeddings(comp,', 'state,', 'stride,', 'during_training):', '_validate_embedded_fixed_features(comp)', 'num_channels', '=', 'len(comp.spec.fixed_feature)', 'if', 'not', 'num_channels:', 'return', '(state.handle,', '[])', '(state.handle,', 'indices,', 'ids,', 'weights,', 'num_steps)'...
760,064
noambassat/SpeechTrainer
subprocess.py
reveal_command_args
reveal_command_args
Return the arguments in their raw, unredacted form.
[ "Return", "the", "arguments", "in", "their", "raw,", "unredacted", "form." ]
def reveal_command_args(args): return [arg.secret if isinstance(arg, HiddenText) else arg for arg in args]
['def', 'reveal_command_args(args):', 'return', '[arg.secret', 'if', 'isinstance(arg,', 'HiddenText)', 'else', 'arg', 'for', 'arg', 'in', 'args]']
895,172
googleapis/python-aiplatform
client.py
MigrationServiceClient.get_operation
get_operation
Gets the latest state of a long-running operation.
[ "Gets", "the", "latest", "state", "of", "a", "long-running", "operation." ]
def get_operation(self, request: Optional[operations_pb2.GetOperationRequest]=None, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Union[float, object]=gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]]=()) -> operations_pb2.Operation: if isinstance(request, dict): request = operations_...
['def', 'get_operation(self,', 'request:', 'Optional[operations_pb2.GetOperationRequest]=None,', '*,', 'retry:', 'OptionalRetry=gapic_v1.method.DEFAULT,', 'timeout:', 'Union[float,', 'object]=gapic_v1.method.DEFAULT,', 'metadata:', 'Sequence[Tuple[str,', 'str]]=())', '->', 'operations_pb2.Operation:', 'if', 'isinstance...
811,321
Xianpeng919/MonoCon
transforms.py
bbox_xyxy_to_cxcywh
bbox_xyxy_to_cxcywh
Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, w, h).
[ "Convert", "bbox", "coordinates", "from", "(x1,", "y1,", "x2,", "y2)", "to", "(cx,", "cy,", "w,", "h)." ]
def bbox_xyxy_to_cxcywh(bbox): (x1, y1, x2, y2) = bbox.split((1, 1, 1, 1), dim=-1) bbox_new = [(x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1] return torch.cat(bbox_new, dim=-1)
['def', 'bbox_xyxy_to_cxcywh(bbox):', '(x1,', 'y1,', 'x2,', 'y2)', '=', 'bbox.split((1,', '1,', '1,', '1),', 'dim=-1)', 'bbox_new', '=', '[(x1', '+', 'x2)', '/', '2,', '(y1', '+', 'y2)', '/', '2,', 'x2', '-', 'x1,', 'y2', '-', 'y1]', 'return', 'torch.cat(bbox_new,', 'dim=-1)']
653,637
coder-mano/Shi-Tomasi-Corner-Detector
misc.py
ask_input
ask_input
Ask for input interactively.
[ "Ask", "for", "input", "interactively." ]
def ask_input(message): _check_no_input(message) return input(message)
['def', 'ask_input(message):', '_check_no_input(message)', 'return', 'input(message)']
899,927
Nrgeup/EasyNLP
beam_search.py
TopN.reset
reset
Returns the TopN to an empty state.
[ "Returns", "the", "TopN", "to", "an", "empty", "state." ]
def reset(self): self._data = []
['def', 'reset(self):', 'self._data', '=', '[]']
546,957
QData/deepWordBug
_in_process.py
build_sdist
build_sdist
Invoke the mandatory build_sdist hook.
[ "Invoke", "the", "mandatory", "build_sdist", "hook." ]
def build_sdist(sdist_directory, config_settings): backend = _build_backend() try: return backend.build_sdist(sdist_directory, config_settings) except getattr(backend, 'UnsupportedOperation', _DummyException): raise GotUnsupportedOperation
['def', 'build_sdist(sdist_directory,', 'config_settings):', 'backend', '=', '_build_backend()', 'try:', 'return', 'backend.build_sdist(sdist_directory,', 'config_settings)', 'except', 'getattr(backend,', "'UnsupportedOperation',", '_DummyException):', 'raise', 'GotUnsupportedOperation']
535,360
rudranil723/mini-main
bezierTools.py
splitQuadraticAtT
splitQuadraticAtT
Split a quadratic Bezier curve at one or more values of t.
[ "Split", "a", "quadratic", "Bezier", "curve", "at", "one", "or", "more", "values", "of", "t." ]
def splitQuadraticAtT(pt1, pt2, pt3, *ts): (a, b, c) = calcQuadraticParameters(pt1, pt2, pt3) return _splitQuadraticAtT(a, b, c, *ts)
['def', 'splitQuadraticAtT(pt1,', 'pt2,', 'pt3,', '*ts):', '(a,', 'b,', 'c)', '=', 'calcQuadraticParameters(pt1,', 'pt2,', 'pt3)', 'return', '_splitQuadraticAtT(a,', 'b,', 'c,', '*ts)']
317,159
google-research/scenic
evaluator.py
format_predictions
format_predictions
Formats predictions to COCO annotation format.
[ "Formats", "predictions", "to", "COCO", "annotation", "format." ]
def format_predictions(*, scores: np.ndarray, labels: np.ndarray, boxes: np.ndarray, image_sizes: np.ndarray, image_ids: np.ndarray, label_shift: int=0) -> List[Dict[str, Any]]: predictions = [] (num_batches, num_instances) = scores.shape for batch in range(num_batches): (h, w) = image_sizes[batch] ...
['def', 'format_predictions(*,', 'scores:', 'np.ndarray,', 'labels:', 'np.ndarray,', 'boxes:', 'np.ndarray,', 'image_sizes:', 'np.ndarray,', 'image_ids:', 'np.ndarray,', 'label_shift:', 'int=0)', '->', 'List[Dict[str,', 'Any]]:', 'predictions', '=', '[]', '(num_batches,', 'num_instances)', '=', 'scores.shape', 'for', '...
847,159
tensorflow/privacy
models.py
RandomForestAttacker.train_model
train_model
Setup a random forest pipeline with cross-validation.
[ "Setup", "a", "random", "forest", "pipeline", "with", "cross-validation." ]
def train_model(self, input_features, is_training_labels, sample_weight=None): with self.ctx_mgr: rf_model = ensemble.RandomForestClassifier(n_jobs=self.n_jobs) param_grid = {'n_estimators': [100], 'max_features': ['auto', 'sqrt'], 'max_depth': [5, 10, 20, None], 'min_samples_split': [2, 5, 10], 'mi...
['def', 'train_model(self,', 'input_features,', 'is_training_labels,', 'sample_weight=None):', 'with', 'self.ctx_mgr:', 'rf_model', '=', 'ensemble.RandomForestClassifier(n_jobs=self.n_jobs)', 'param_grid', '=', "{'n_estimators':", '[100],', "'max_features':", "['auto',", "'sqrt'],", "'max_depth':", '[5,', '10,', '20,',...
824,920
rudranil723/mini-main
DateTime.py
DateTime.timezone
timezone
Return the timezone in which the object is represented.
[ "Return", "the", "timezone", "in", "which", "the", "object", "is", "represented." ]
def timezone(self): return self._tz
['def', 'timezone(self):', 'return', 'self._tz']
314,553
bislara/Object-detection-GUI
config_util_test.py
ConfigUtilTest.testNewBatchSize
testNewBatchSize
Tests that batch size is updated appropriately.
[ "Tests", "that", "batch", "size", "is", "updated", "appropriately." ]
def testNewBatchSize(self): original_batch_size = 2 hparams = tf.contrib.training.HParams(batch_size=16) pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config') pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.train_config.batch_size = original_batch_size ...
['def', 'testNewBatchSize(self):', 'original_batch_size', '=', '2', 'hparams', '=', 'tf.contrib.training.HParams(batch_size=16)', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.train_config.batch_...
726,763
enuguru/artificial_intelligence_and_machine_
itsdangerous.py
TimestampSigner.timestamp_to_datetime
timestamp_to_datetime
Used to convert the timestamp from `get_timestamp` into a datetime object.
[ "Used", "to", "convert", "the", "timestamp", "from", "`get_timestamp`", "into", "a", "datetime", "object." ]
def timestamp_to_datetime(self, ts): return datetime.utcfromtimestamp(ts + EPOCH)
['def', 'timestamp_to_datetime(self,', 'ts):', 'return', 'datetime.utcfromtimestamp(ts', '+', 'EPOCH)']
156,643
domSB/natural_language_processing
dependencygraph.py
DependencyGraph.contains_address
contains_address
Returns true if the graph contains a node with the given node address, false otherwise.
[ "Returns", "true", "if", "the", "graph", "contains", "a", "node", "with", "the", "given", "node", "address,", "false", "otherwise." ]
def contains_address(self, node_address): return node_address in self.nodes
['def', 'contains_address(self,', 'node_address):', 'return', 'node_address', 'in', 'self.nodes']
734,859
enuguru/artificial_intelligence_and_machine_learning
xri.py
iriToURI
iriToURI
Transform an IRI to a URI by escaping unicode.
[ "Transform", "an", "IRI", "to", "a", "URI", "by", "escaping", "unicode." ]
def iriToURI(iri): if isinstance(iri, bytes): iri = str(iri, encoding='utf-8') return iri.encode('ascii', errors='oid_percent_escape').decode()
['def', 'iriToURI(iri):', 'if', 'isinstance(iri,', 'bytes):', 'iri', '=', 'str(iri,', "encoding='utf-8')", 'return', "iri.encode('ascii',", "errors='oid_percent_escape').decode()"]
159,605
fundamentalvision/BEVFormer
multi_scale_deformable_attn_function.py
MultiScaleDeformableAttnFunction_fp32.backward
backward
GPU version of backward function.
[ "GPU", "version", "of", "backward", "function." ]
def backward(ctx, grad_output): (value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights) = ctx.saved_tensors grad_value = torch.zeros_like(value) grad_sampling_loc = torch.zeros_like(sampling_locations) grad_attn_weight = torch.zeros_like(attention_weights) ext_m...
['def', 'backward(ctx,', 'grad_output):', '(value,', 'value_spatial_shapes,', 'value_level_start_index,', 'sampling_locations,', 'attention_weights)', '=', 'ctx.saved_tensors', 'grad_value', '=', 'torch.zeros_like(value)', 'grad_sampling_loc', '=', 'torch.zeros_like(sampling_locations)', 'grad_attn_weight', '=', 'torch...
434,278
CYBERDEVILZ/artificial-
timer_comparison.py
ModuleTester.assert_array_compare
assert_array_compare
Assert that a comparison of two masked arrays is satisfied elementwise.
[ "Assert", "that", "a", "comparison", "of", "two", "masked", "arrays", "is", "satisfied", "elementwise." ]
def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), self.getmask(y)) x = self.filled(self.masked_array(xf, mask=m), fill_value) y = self.filled(self.masked_array(yf, mask=m), fill_value) ...
['def', 'assert_array_compare(self,', 'comparison,', 'x,', 'y,', "err_msg='',", "header='',", 'fill_value=True):', 'xf', '=', 'self.filled(x)', 'yf', '=', 'self.filled(y)', 'm', '=', 'self.mask_or(self.getmask(x),', 'self.getmask(y))', 'x', '=', 'self.filled(self.masked_array(xf,', 'mask=m),', 'fill_value)', 'y', '=', ...
172,536
RLE-Foundation/rllte
utils.py
DisctributedActorCritic.forward
forward
Get actions in training.
[ "Get", "actions", "in", "training." ]
def forward(self, inputs: Dict[str, th.Tensor], training: bool=True) -> Dict[str, th.Tensor]: x = inputs['observations'] (T, B, *_) = x.shape x = th.flatten(x, 0, 1) features = self.encoder(x) if self.action_type == 'Discrete': encoded_actions = F.one_hot(inputs['last_actions'].view(T * B), ...
['def', 'forward(self,', 'inputs:', 'Dict[str,', 'th.Tensor],', 'training:', 'bool=True)', '->', 'Dict[str,', 'th.Tensor]:', 'x', '=', "inputs['observations']", '(T,', 'B,', '*_)', '=', 'x.shape', 'x', '=', 'th.flatten(x,', '0,', '1)', 'features', '=', 'self.encoder(x)', 'if', 'self.action_type', '==', "'Discrete':", '...
333,334
ellakummer/Computer-Vision
resneXt.py
resnext152
resnext152
Constructs a ResNeXt-152 model.
[ "Constructs", "a", "ResNeXt-152", "model." ]
def resnext152(**kwargs): model = ResNeXt(Bottleneck, [3, 8, 36, 3], **kwargs) return model
['def', 'resnext152(**kwargs):', 'model', '=', 'ResNeXt(Bottleneck,', '[3,', '8,', '36,', '3],', '**kwargs)', 'return', 'model']
460,104
xrick/tensorflow_nlp
data_utils.py
create_dico
create_dico
Create a dictionary of items from a list of list of items.
[ "Create", "a", "dictionary", "of", "items", "from", "a", "list", "of", "list", "of", "items." ]
def create_dico(item_list): assert type(item_list) is list dico = {} for items in item_list: for item in items: if item not in dico: dico[item] = 1 else: dico[item] += 1 return dico
['def', 'create_dico(item_list):', 'assert', 'type(item_list)', 'is', 'list', 'dico', '=', '{}', 'for', 'items', 'in', 'item_list:', 'for', 'item', 'in', 'items:', 'if', 'item', 'not', 'in', 'dico:', 'dico[item]', '=', '1', 'else:', 'dico[item]', '+=', '1', 'return', 'dico']
922,524
ryu-ed/SpaceInvaders_Ros
scrap_test.py
ScrapModuleClipboardNotOwnedTest.test_lost__not_owned
test_lost__not_owned
Ensures lost works when the clipboard is not owned by the pygame application.
[ "Ensures", "lost", "works", "when", "the", "clipboard", "is", "not", "owned", "by", "the", "pygame", "application." ]
def test_lost__not_owned(self): self._skip_if_clipboard_owned() lost = scrap.lost() self.assertTrue(lost)
['def', 'test_lost__not_owned(self):', 'self._skip_if_clipboard_owned()', 'lost', '=', 'scrap.lost()', 'self.assertTrue(lost)']
369,155
thaines/helit
glyph_db.py
Glyph.most_left
most_left
Returns the coordinate of the furthest left vertex in the glyph.
[ "Returns", "the", "coordinate", "of", "the", "furthest", "left", "vertex", "in", "the", "glyph." ]
def most_left(self): info = self.lg.get_vertex(0) best_x = info[0] best_y = info[1] for i in xrange(1, self.lg.vertex_count): info = self.lg.get_vertex(0) if info[0] < best_x: best_x = info[0] best_y = info[1] return (best_x, best_y)
['def', 'most_left(self):', 'info', '=', 'self.lg.get_vertex(0)', 'best_x', '=', 'info[0]', 'best_y', '=', 'info[1]', 'for', 'i', 'in', 'xrange(1,', 'self.lg.vertex_count):', 'info', '=', 'self.lg.get_vertex(0)', 'if', 'info[0]', '<', 'best_x:', 'best_x', '=', 'info[0]', 'best_y', '=', 'info[1]', 'return', '(best_x,', ...
591,893
matsu0228/nlp-jp
basic.py
BasicMagics.lsmagic
lsmagic
List currently available magic functions.
[ "List", "currently", "available", "magic", "functions." ]
def lsmagic(self, parameter_s=''): return MagicsDisplay(self.shell.magics_manager, ignore=[self.pip])
['def', 'lsmagic(self,', "parameter_s=''):", 'return', 'MagicsDisplay(self.shell.magics_manager,', 'ignore=[self.pip])']
786,884
Binjer/ComputerVision
sfm.py
RansacModel.fit
fit
Estimate fundamental matrix using eight selected correspondences.
[ "Estimate", "fundamental", "matrix", "using", "eight", "selected", "correspondences." ]
def fit(self, data): data = data.T x1 = data[:3, :8] x2 = data[3:, :8] F = compute_fundamental_normalized(x1, x2) return F
['def', 'fit(self,', 'data):', 'data', '=', 'data.T', 'x1', '=', 'data[:3,', ':8]', 'x2', '=', 'data[3:,', ':8]', 'F', '=', 'compute_fundamental_normalized(x1,', 'x2)', 'return', 'F']
471,856
chainer/chainerrl
categorical_dqn.py
compute_value_loss
compute_value_loss
Compute a loss for value prediction problem.
[ "Compute", "a", "loss", "for", "value", "prediction", "problem." ]
def compute_value_loss(eltwise_loss, batch_accumulator='mean'): assert batch_accumulator in ('mean', 'sum') if batch_accumulator == 'sum': loss = F.sum(eltwise_loss) else: loss = F.mean(F.sum(eltwise_loss, axis=1)) return loss
['def', 'compute_value_loss(eltwise_loss,', "batch_accumulator='mean'):", 'assert', 'batch_accumulator', 'in', "('mean',", "'sum')", 'if', 'batch_accumulator', '==', "'sum':", 'loss', '=', 'F.sum(eltwise_loss)', 'else:', 'loss', '=', 'F.mean(F.sum(eltwise_loss,', 'axis=1))', 'return', 'loss']
104,552
kubeflow/pipelines
python_component.py
PythonComponent.execute
execute
Executes the Python function that defines the component.
[ "Executes", "the", "Python", "function", "that", "defines", "the", "component." ]
def execute(self, **kwargs): return self.python_func(**kwargs)
['def', 'execute(self,', '**kwargs):', 'return', 'self.python_func(**kwargs)']
780,240
Erfanafshar/Principles-and-Applications-of---graph-coloring
pyparsing.py
ParserElement.suppress
suppress
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output.
[ "Suppresses", "the", "output", "of", "this", ":class:`ParserElement`;", "useful", "to", "keep", "punctuation", "from", "cluttering", "up", "returned", "output." ]
def suppress(self): return Suppress(self)
['def', 'suppress(self):', 'return', 'Suppress(self)']
306,142
qinenergy/adanet
ilsvrcsemi.py
ILSVRCMeta.guess_dir_structure
guess_dir_structure
Return the directory structure of "dir".
[ "Return", "the", "directory", "structure", "of", "\"dir\"." ]
def guess_dir_structure(dir): subdir = os.listdir(dir)[0] if subdir.startswith('n') and os.path.isdir(os.path.join(dir, subdir)): dir_structure = 'train' else: dir_structure = 'original' logger.info("[ILSVRC12] Assuming directory {} has '{}' structure.".format(dir, dir_structure)) re...
['def', 'guess_dir_structure(dir):', 'subdir', '=', 'os.listdir(dir)[0]', 'if', "subdir.startswith('n')", 'and', 'os.path.isdir(os.path.join(dir,', 'subdir)):', 'dir_structure', '=', "'train'", 'else:', 'dir_structure', '=', "'original'", 'logger.info("[ILSVRC12]', 'Assuming', 'directory', '{}', 'has', "'{}'", 'structu...
39,857
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_handling.py
unpack_exam_into_images
unpack_exam_into_images
Turn exam_list into image_list for parallel functions which process each image separately.
[ "Turn", "exam_list", "into", "image_list", "for", "parallel", "functions", "which", "process", "each", "image", "separately." ]
def unpack_exam_into_images(exam_list, cropped=False): image_list = [] for (i, exam) in enumerate(exam_list): for view in VIEWS.LIST: for (j, image) in enumerate(exam[view]): image_dict = dict(short_file_path=image, horizontal_flip=exam['horizontal_flip'], full_view=view, sid...
['def', 'unpack_exam_into_images(exam_list,', 'cropped=False):', 'image_list', '=', '[]', 'for', '(i,', 'exam)', 'in', 'enumerate(exam_list):', 'for', 'view', 'in', 'VIEWS.LIST:', 'for', '(j,', 'image)', 'in', 'enumerate(exam[view]):', 'image_dict', '=', 'dict(short_file_path=image,', "horizontal_flip=exam['horizontal_...
17,980
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_provider.py
provide_data
provide_data
Provides batches of image data for compression.
[ "Provides", "batches", "of", "image", "data", "for", "compression." ]
def provide_data(split_name, batch_size, dataset_dir, dataset_name='imagenet', num_readers=1, num_threads=1, patch_size=128): randomize = split_name == 'train' dataset = datasets.get_dataset(dataset_name, split_name, dataset_dir=dataset_dir) provider = slim.dataset_data_provider.DatasetDataProvider(dataset,...
['def', 'provide_data(split_name,', 'batch_size,', 'dataset_dir,', "dataset_name='imagenet',", 'num_readers=1,', 'num_threads=1,', 'patch_size=128):', 'randomize', '=', 'split_name', '==', "'train'", 'dataset', '=', 'datasets.get_dataset(dataset_name,', 'split_name,', 'dataset_dir=dataset_dir)', 'provider', '=', 'slim....
48,553
enuguru/artificial_intelligence_and_machine_
support.py
NullTranslations.ldngettext
ldngettext
Like ``lngettext()``, but look the message up in the specified domain.
[ "Like", "``lngettext()``,", "but", "look", "the", "message", "up", "in", "the", "specified", "domain." ]
def ldngettext(self, domain, singular, plural, num): return self._domains.get(domain, self).lngettext(singular, plural, num)
['def', 'ldngettext(self,', 'domain,', 'singular,', 'plural,', 'num):', 'return', 'self._domains.get(domain,', 'self).lngettext(singular,', 'plural,', 'num)']
157,046
mariacer/cl_in_rnns
simple_rnn.py
SimpleRNN.split_internal_weights
split_internal_weights
Split internal weights per layer.
[ "Split", "internal", "weights", "per", "layer." ]
def split_internal_weights(self, int_weights): n_cm = self._num_context_mod_shapes() int_meta = self.param_shapes_meta[n_cm:] assert len(int_meta) == len(int_weights) fc_pre_w_weights = [] fc_pre_b_weights = [] rec_weights = [[] for _ in range(len(self._rnn_layers))] fc_w_weights = [] fc...
['def', 'split_internal_weights(self,', 'int_weights):', 'n_cm', '=', 'self._num_context_mod_shapes()', 'int_meta', '=', 'self.param_shapes_meta[n_cm:]', 'assert', 'len(int_meta)', '==', 'len(int_weights)', 'fc_pre_w_weights', '=', '[]', 'fc_pre_b_weights', '=', '[]', 'rec_weights', '=', '[[]', 'for', '_', 'in', 'range...
122,891
deepmind/dm_control
quadruped.py
Physics.origin
origin
Returns origin position in the torso frame.
[ "Returns", "origin", "position", "in", "the", "torso", "frame." ]
def origin(self): torso_frame = self.named.data.xmat['torso'].reshape(3, 3) torso_pos = self.named.data.xpos['torso'] return -torso_pos.dot(torso_frame)
['def', 'origin(self):', 'torso_frame', '=', "self.named.data.xmat['torso'].reshape(3,", '3)', 'torso_pos', '=', "self.named.data.xpos['torso']", 'return', '-torso_pos.dot(torso_frame)']
166,447
myothida/Supervised-Machine-Learning
tree.py
Tree.add
add
Add a child tree.
[ "Add", "a", "child", "tree." ]
def add(self, label: RenderableType, *, style: Optional[StyleType]=None, guide_style: Optional[StyleType]=None, expanded: bool=True, highlight: Optional[bool]=False) -> 'Tree': node = Tree(label, style=self.style if style is None else style, guide_style=self.guide_style if guide_style is None else guide_style, expa...
['def', 'add(self,', 'label:', 'RenderableType,', '*,', 'style:', 'Optional[StyleType]=None,', 'guide_style:', 'Optional[StyleType]=None,', 'expanded:', 'bool=True,', 'highlight:', 'Optional[bool]=False)', '->', "'Tree':", 'node', '=', 'Tree(label,', 'style=self.style', 'if', 'style', 'is', 'None', 'else', 'style,', 'g...
445,146
flow-project/flow
load.py
load_network
load_network
Load the whole network into a dictionary and returns it.
[ "Load", "the", "whole", "network", "into", "a", "dictionary", "and", "returns", "it." ]
def load_network(): sections = model.sections nodes = model.nodes turnings = model.turnings cen_connections = model.cen_connections scenario_data = get_dict_from_objects(sections, nodes, turnings, cen_connections) return scenario_data
['def', 'load_network():', 'sections', '=', 'model.sections', 'nodes', '=', 'model.nodes', 'turnings', '=', 'model.turnings', 'cen_connections', '=', 'model.cen_connections', 'scenario_data', '=', 'get_dict_from_objects(sections,', 'nodes,', 'turnings,', 'cen_connections)', 'return', 'scenario_data']
212,363
matsu0228/nlp-jp
connection.py
MWSConnection.list_registered_destinations
list_registered_destinations
Lists all current destinations that you have registered.
[ "Lists", "all", "current", "destinations", "that", "you", "have", "registered." ]
def list_registered_destinations(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'list_registered_destinations(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,998
Megvii-BaseDetection/cvpods
roi_heads.py
select_foreground_proposals
select_foreground_proposals
Given a list of N Instances (for N images), each containing a `gt_classes` field, return a list of Instances that contain only instances with `gt_classes != -1 && gt_classes != bg_label`.
[ "Given", "a", "list", "of", "N", "Instances", "(for", "N", "images),", "each", "containing", "a", "`gt_classes`", "field,", "return", "a", "list", "of", "Instances", "that", "contain", "only", "instances", "with", "`gt_classes", "!=", "-1", "&&", "gt_classes",...
def select_foreground_proposals(proposals, bg_label): assert isinstance(proposals, (list, tuple)) assert isinstance(proposals[0], Instances) assert proposals[0].has('gt_classes') fg_proposals = [] fg_selection_masks = [] for proposals_per_image in proposals: gt_classes = proposals_per_im...
['def', 'select_foreground_proposals(proposals,', 'bg_label):', 'assert', 'isinstance(proposals,', '(list,', 'tuple))', 'assert', 'isinstance(proposals[0],', 'Instances)', 'assert', "proposals[0].has('gt_classes')", 'fg_proposals', '=', '[]', 'fg_selection_masks', '=', '[]', 'for', 'proposals_per_image', 'in', 'proposa...
523,103
chainer/chainer
onnx_helper.py
GraphBuilder.op
op
Creates a new ONNX node and returns its outputs.
[ "Creates", "a", "new", "ONNX", "node", "and", "returns", "its", "outputs." ]
def op(self, op_name, input_names, num_outputs=1, **kwargs): if num_outputs == 1: output_names = [self.node_name()] else: output_names = ['{}_{}'.format(self.node_name(), i) for i in range(num_outputs)] return self.op_output_named(op_name, input_names, output_names, **kwargs)
['def', 'op(self,', 'op_name,', 'input_names,', 'num_outputs=1,', '**kwargs):', 'if', 'num_outputs', '==', '1:', 'output_names', '=', '[self.node_name()]', 'else:', 'output_names', '=', "['{}_{}'.format(self.node_name(),", 'i)', 'for', 'i', 'in', 'range(num_outputs)]', 'return', 'self.op_output_named(op_name,', 'input_...
477,702
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
lfads.py
LFADS.eval_cost_epoch
eval_cost_epoch
Evaluate the cost of the epoch.
[ "Evaluate", "the", "cost", "of", "the", "epoch." ]
def eval_cost_epoch(self, datasets, kind='train', ext_input_extxi=None, batch_size=None): ops_to_eval = [self.cost, self.recon_cost, self.kl_cost] collected_op_values = self.run_epoch(datasets, ops_to_eval, kind=kind, keep_prob=1.0) total_cost = total_recon_cost = total_kl_cost = 0.0 epoch_size = len(co...
['def', 'eval_cost_epoch(self,', 'datasets,', "kind='train',", 'ext_input_extxi=None,', 'batch_size=None):', 'ops_to_eval', '=', '[self.cost,', 'self.recon_cost,', 'self.kl_cost]', 'collected_op_values', '=', 'self.run_epoch(datasets,', 'ops_to_eval,', 'kind=kind,', 'keep_prob=1.0)', 'total_cost', '=', 'total_recon_cos...
55,946
43Carrig/recurrent_neural_networks_practice
formparser.py
exhaust_stream
exhaust_stream
Helper decorator for methods that exhausts the stream on return.
[ "Helper", "decorator", "for", "methods", "that", "exhausts", "the", "stream", "on", "return." ]
def exhaust_stream(f): def wrapper(self, stream, *args, **kwargs): try: return f(self, stream, *args, **kwargs) finally: exhaust = getattr(stream, 'exhaust', None) if exhaust is not None: exhaust() else: while 1: ...
['def', 'exhaust_stream(f):', 'def', 'wrapper(self,', 'stream,', '*args,', '**kwargs):', 'try:', 'return', 'f(self,', 'stream,', '*args,', '**kwargs)', 'finally:', 'exhaust', '=', 'getattr(stream,', "'exhaust',", 'None)', 'if', 'exhaust', 'is', 'not', 'None:', 'exhaust()', 'else:', 'while', '1:', 'chunk', '=', 'stream....
339,995
enuguru/artificial_intelligence_and_machine_
base.py
FBExecutionContext.fire_sequence
fire_sequence
Get the next value from the sequence using ``gen_id()``.
[ "Get", "the", "next", "value", "from", "the", "sequence", "using", "``gen_id()``." ]
def fire_sequence(self, seq, type_): return self._execute_scalar('SELECT gen_id(%s, 1) FROM rdb$database' % self.dialect.identifier_preparer.format_sequence(seq), type_)
['def', 'fire_sequence(self,', 'seq,', 'type_):', 'return', "self._execute_scalar('SELECT", 'gen_id(%s,', '1)', 'FROM', "rdb$database'", '%', 'self.dialect.identifier_preparer.format_sequence(seq),', 'type_)']
160,922
dgseten/bad-cv-tfm
mobilenet_v1_eval.py
metrics
metrics
Specify the metrics for eval.
[ "Specify", "the", "metrics", "for", "eval." ]
def metrics(logits, labels): labels = tf.squeeze(labels) (names_to_values, names_to_updates) = slim.metrics.aggregate_metric_map({'Accuracy': tf.metrics.accuracy(tf.argmax(logits, 1), labels), 'Recall_5': tf.metrics.recall_at_k(labels, logits, 5)}) for (name, value) in names_to_values.iteritems(): s...
['def', 'metrics(logits,', 'labels):', 'labels', '=', 'tf.squeeze(labels)', '(names_to_values,', 'names_to_updates)', '=', "slim.metrics.aggregate_metric_map({'Accuracy':", 'tf.metrics.accuracy(tf.argmax(logits,', '1),', 'labels),', "'Recall_5':", 'tf.metrics.recall_at_k(labels,', 'logits,', '5)})', 'for', '(name,', 'v...
422,072
CORE-Robotics-Lab/SSRR
batch_polopt.py
BatchPolopt.get_itr_snapshot
get_itr_snapshot
Returns all the data that should be saved in the snapshot for this iteration.
[ "Returns", "all", "the", "data", "that", "should", "be", "saved", "in", "the", "snapshot", "for", "this", "iteration." ]
def get_itr_snapshot(self, itr, samples_data): raise NotImplementedError
['def', 'get_itr_snapshot(self,', 'itr,', 'samples_data):', 'raise', 'NotImplementedError']
382,560
aws/sagemaker-python-sdk
model_monitoring.py
MonitoringExecution.from_processing_arn
from_processing_arn
Initializes a Baselining job from a processing arn.
[ "Initializes", "a", "Baselining", "job", "from", "a", "processing", "arn." ]
def from_processing_arn(cls, sagemaker_session, processing_job_arn): processing_job_name = processing_job_arn.split(':')[5][len('processing-job/'):] job_desc = sagemaker_session.describe_processing_job(job_name=processing_job_name) output_config = job_desc['ProcessingOutputConfig']['Outputs'][0] return ...
['def', 'from_processing_arn(cls,', 'sagemaker_session,', 'processing_job_arn):', 'processing_job_name', '=', "processing_job_arn.split(':')[5][len('processing-job/'):]", 'job_desc', '=', 'sagemaker_session.describe_processing_job(job_name=processing_job_name)', 'output_config', '=', "job_desc['ProcessingOutputConfig']...
830,473
tensorflow/agents
tensor_spec.py
zero_spec_nest
zero_spec_nest
Create zero tensors for a given spec.
[ "Create", "zero", "tensors", "for", "a", "given", "spec." ]
def zero_spec_nest(specs, outer_dims=None): def make_zero(spec): if not isinstance(spec, TensorSpec): raise NotImplementedError("Spec type not supported: '{}'".format(spec)) if outer_dims is None: shape = spec.shape else: spec_shape = tf.convert_to_tensor...
['def', 'zero_spec_nest(specs,', 'outer_dims=None):', 'def', 'make_zero(spec):', 'if', 'not', 'isinstance(spec,', 'TensorSpec):', 'raise', 'NotImplementedError("Spec', 'type', 'not', 'supported:', '\'{}\'".format(spec))', 'if', 'outer_dims', 'is', 'None:', 'shape', '=', 'spec.shape', 'else:', 'spec_shape', '=', 'tf.con...
23,703
google-research/ssl_detection
debug.py
enable_call_trace
enable_call_trace
Enable trace for calls to any function.
[ "Enable", "trace", "for", "calls", "to", "any", "function." ]
def enable_call_trace(): def tracer(frame, event, arg): if event == 'call': co = frame.f_code func_name = co.co_name if func_name == 'write' or func_name == 'print': return func_line_no = frame.f_lineno func_filename = co.co_filena...
['def', 'enable_call_trace():', 'def', 'tracer(frame,', 'event,', 'arg):', 'if', 'event', '==', "'call':", 'co', '=', 'frame.f_code', 'func_name', '=', 'co.co_name', 'if', 'func_name', '==', "'write'", 'or', 'func_name', '==', "'print':", 'return', 'func_line_no', '=', 'frame.f_lineno', 'func_filename', '=', 'co.co_fil...
382,348
chrisw2529/Natural-Language-Processing
vector_embeddings.py
IMDBMovieReviews.apply_vocab
apply_vocab
Applies the vocabulary to the data and maps the tokenized sentences to vocab indices as the model input.
[ "Applies", "the", "vocabulary", "to", "the", "data", "and", "maps", "the", "tokenized", "sentences", "to", "vocab", "indices", "as", "the", "model", "input." ]
def apply_vocab(self, data, token_to_idx): for review in data: review[L_TOKENS] = [token_to_idx.get(token, token_to_idx[UNK]) for token in review[L_TOKENS]]
['def', 'apply_vocab(self,', 'data,', 'token_to_idx):', 'for', 'review', 'in', 'data:', 'review[L_TOKENS]', '=', '[token_to_idx.get(token,', 'token_to_idx[UNK])', 'for', 'token', 'in', 'review[L_TOKENS]]']
658,000
voxel51/fiftyone
collections.py
SampleCollection.delete_evaluations
delete_evaluations
Deletes all evaluation results from this collection.
[ "Deletes", "all", "evaluation", "results", "from", "this", "collection." ]
def delete_evaluations(self): foev.EvaluationMethod.delete_runs(self)
['def', 'delete_evaluations(self):', 'foev.EvaluationMethod.delete_runs(self)']
582,779
aws/sagemaker-python-sdk
utilities.py
get_processing_code_hash
get_processing_code_hash
Get the hash of a processing step's code artifact(s).
[ "Get", "the", "hash", "of", "a", "processing", "step's", "code", "artifact(s)." ]
def get_processing_code_hash(code: str, source_dir: str, dependencies: List[str]) -> str: if source_dir: source_dir_url = urlparse(source_dir) if source_dir_url.scheme == '' or source_dir_url.scheme == 'file': if code: code_url = urlparse(code) if code_url...
['def', 'get_processing_code_hash(code:', 'str,', 'source_dir:', 'str,', 'dependencies:', 'List[str])', '->', 'str:', 'if', 'source_dir:', 'source_dir_url', '=', 'urlparse(source_dir)', 'if', 'source_dir_url.scheme', '==', "''", 'or', 'source_dir_url.scheme', '==', "'file':", 'if', 'code:', 'code_url', '=', 'urlparse(c...
830,698
ZumoLabs/zpy
__init__.py
unregister
unregister
Unregister any classes and properties.
[ "Unregister", "any", "classes", "and", "properties." ]
def unregister(): for cls in classes: try: log.info(f'Un-registering class {cls.__name__}') bpy.utils.unregister_class(cls) except Exception as e: log.warning(f'Exception when un-registering {cls.__name__}: {e}') bpy.types.TEXT_MT_templates_py.remove(script_pa...
['def', 'unregister():', 'for', 'cls', 'in', 'classes:', 'try:', "log.info(f'Un-registering", 'class', "{cls.__name__}')", 'bpy.utils.unregister_class(cls)', 'except', 'Exception', 'as', 'e:', "log.warning(f'Exception", 'when', 'un-registering', '{cls.__name__}:', "{e}')", 'bpy.types.TEXT_MT_templates_py.remove(script_...
972,159
paarthneekhara/advoc
audioio.py
decode_audio
decode_audio
Decodes audio file paths into 32-bit floating point vectors.
[ "Decodes", "audio", "file", "paths", "into", "32-bit", "floating", "point", "vectors." ]
def decode_audio(fp, fs=None, mono=False, normalize=False, fastwav=False): if fastwav: try: (orig_fs, x) = spwavread(fp) except: raise ValueError('Error encountered when decoding WAV file.') if fs is not None and fs != orig_fs: raise ValueError('Fastwav ca...
['def', 'decode_audio(fp,', 'fs=None,', 'mono=False,', 'normalize=False,', 'fastwav=False):', 'if', 'fastwav:', 'try:', '(orig_fs,', 'x)', '=', 'spwavread(fp)', 'except:', 'raise', "ValueError('Error", 'encountered', 'when', 'decoding', 'WAV', "file.')", 'if', 'fs', 'is', 'not', 'None', 'and', 'fs', '!=', 'orig_fs:', '...
398,701
lxtGH/CAE
eval_hooks.py
EvalHook.after_train_iter
after_train_iter
After train epoch hook.
[ "After", "train", "epoch", "hook." ]
def after_train_iter(self, runner): if self.by_epoch or not self.every_n_iters(runner, self.interval): return from mmseg.apis import single_gpu_test runner.log_buffer.clear() results = single_gpu_test(runner.model, self.dataloader, show=False) self.evaluate(runner, results)
['def', 'after_train_iter(self,', 'runner):', 'if', 'self.by_epoch', 'or', 'not', 'self.every_n_iters(runner,', 'self.interval):', 'return', 'from', 'mmseg.apis', 'import', 'single_gpu_test', 'runner.log_buffer.clear()', 'results', '=', 'single_gpu_test(runner.model,', 'self.dataloader,', 'show=False)', 'self.evaluate(...
108,740
aeon-toolkit/aeon
test_deep_equals.py
test_deep_equals_negative
test_deep_equals_negative
Tests that deep_equals correctly identifies unequal objects as unequal.
[ "Tests", "that", "deep_equals", "correctly", "identifies", "unequal", "objects", "as", "unequal." ]
def test_deep_equals_negative(fixture1, fixture2): x = deepcopy(fixture1) y = deepcopy(fixture2) msg = f'deep_copy incorrectly returned True when comparing the following, different objects: x={x}, y={y}' assert not deep_equals(x, y), msg
['def', 'test_deep_equals_negative(fixture1,', 'fixture2):', 'x', '=', 'deepcopy(fixture1)', 'y', '=', 'deepcopy(fixture2)', 'msg', '=', "f'deep_copy", 'incorrectly', 'returned', 'True', 'when', 'comparing', 'the', 'following,', 'different', 'objects:', 'x={x},', "y={y}'", 'assert', 'not', 'deep_equals(x,', 'y),', 'msg...
400,344
triaquae/triaquae
views.py
kmz
kmz
This view returns KMZ for the given app label, model, and field name.
[ "This", "view", "returns", "KMZ", "for", "the", "given", "app", "label,", "model,", "and", "field", "name." ]
def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): return kml(request, label, model, field_name, compress=True, using=using)
['def', 'kmz(request,', 'label,', 'model,', 'field_name=None,', 'using=DEFAULT_DB_ALIAS):', 'return', 'kml(request,', 'label,', 'model,', 'field_name,', 'compress=True,', 'using=using)']
357,930
Ruturaj123/Flowchart-Detection
models.py
default_batch_norm_params
default_batch_norm_params
Returns default batch normalization parameters for DSNs.
[ "Returns", "default", "batch", "normalization", "parameters", "for", "DSNs." ]
def default_batch_norm_params(is_training=False): return {'decay': 0.5, 'epsilon': 0.001, 'is_training': is_training}
['def', 'default_batch_norm_params(is_training=False):', 'return', "{'decay':", '0.5,', "'epsilon':", '0.001,', "'is_training':", 'is_training}']
585,609
weimin17/Object-Detection_HelmetDetection
data_download.py
find_file
find_file
Returns full filepath if the file is in path or a subdirectory.
[ "Returns", "full", "filepath", "if", "the", "file", "is", "in", "path", "or", "a", "subdirectory." ]
def find_file(path, filename, max_depth=5): for (root, dirs, files) in os.walk(path): if filename in files: return os.path.join(root, filename) depth = root[len(path) + 1:].count(os.sep) if depth > max_depth: del dirs[:] return None
['def', 'find_file(path,', 'filename,', 'max_depth=5):', 'for', '(root,', 'dirs,', 'files)', 'in', 'os.walk(path):', 'if', 'filename', 'in', 'files:', 'return', 'os.path.join(root,', 'filename)', 'depth', '=', 'root[len(path)', '+', '1:].count(os.sep)', 'if', 'depth', '>', 'max_depth:', 'del', 'dirs[:]', 'return', 'Non...
761,143
desimone/segmentation-models
layers.py
upsample_filt
upsample_filt
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
[ "Make", "a", "2D", "bilinear", "kernel", "suitable", "for", "upsampling", "of", "the", "given", "(h,", "w)", "size." ]
def upsample_filt(size): factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] return (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
['def', 'upsample_filt(size):', 'factor', '=', '(size', '+', '1)', '//', '2', 'if', 'size', '%', '2', '==', '1:', 'center', '=', 'factor', '-', '1', 'else:', 'center', '=', 'factor', '-', '0.5', 'og', '=', 'np.ogrid[:size,', ':size]', 'return', '(1', '-', 'abs(og[0]', '-', 'center)', '/', 'factor)', '*', '(1', '-', 'ab...
842,526
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
traceback.py
format_tb
format_tb
A shorthand for 'format_list(extract_tb(tb, limit))'.
[ "A", "shorthand", "for", "'format_list(extract_tb(tb,", "limit))'." ]
def format_tb(tb, limit=None): return extract_tb(tb, limit=limit).format()
['def', 'format_tb(tb,', 'limit=None):', 'return', 'extract_tb(tb,', 'limit=limit).format()']
429,736
MANGA-UOFA/NAUS
summarization_at_generator.py
SummarizationATGenerator.forward
forward
Generate a batch of translations.
[ "Generate", "a", "batch", "of", "translations." ]
def forward(self, sample: Dict[str, Dict[str, Tensor]], prefix_tokens: Optional[Tensor]=None, bos_token: Optional[int]=None): return self._generate(sample, prefix_tokens, bos_token=bos_token)
['def', 'forward(self,', 'sample:', 'Dict[str,', 'Dict[str,', 'Tensor]],', 'prefix_tokens:', 'Optional[Tensor]=None,', 'bos_token:', 'Optional[int]=None):', 'return', 'self._generate(sample,', 'prefix_tokens,', 'bos_token=bos_token)']
291,196
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_utils.py
summaries_color_distributions
summaries_color_distributions
Produces a histogram of the color distributions of the images.
[ "Produces", "a", "histogram", "of", "the", "color", "distributions", "of", "the", "images." ]
def summaries_color_distributions(images, name): tf.summary.histogram('color_values/%s' % name, images)
['def', 'summaries_color_distributions(images,', 'name):', "tf.summary.histogram('color_values/%s'", '%', 'name,', 'images)']
48,319
tensorflow/privacy
imdb_tutorial.py
load_imdb
load_imdb
Load IMDB movie reviews data.
[ "Load", "IMDB", "movie", "reviews", "data." ]
def load_imdb(): ((train_data, train_labels), (test_data, test_labels)) = tf.keras.datasets.imdb.load_data(num_words=max_features) train_data = sequence.pad_sequences(train_data, maxlen=maxlen).astype('float32') test_data = sequence.pad_sequences(test_data, maxlen=maxlen).astype('float32') return (train...
['def', 'load_imdb():', '((train_data,', 'train_labels),', '(test_data,', 'test_labels))', '=', 'tf.keras.datasets.imdb.load_data(num_words=max_features)', 'train_data', '=', 'sequence.pad_sequences(train_data,', "maxlen=maxlen).astype('float32')", 'test_data', '=', 'sequence.pad_sequences(test_data,', "maxlen=maxlen)....
824,503
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
show_and_tell_model.py
ShowAndTellModel.setup_global_step
setup_global_step
Sets up the global step Tensor.
[ "Sets", "up", "the", "global", "step", "Tensor." ]
def setup_global_step(self): global_step = tf.Variable(initial_value=0, name='global_step', trainable=False, collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES]) self.global_step = global_step
['def', 'setup_global_step(self):', 'global_step', '=', 'tf.Variable(initial_value=0,', "name='global_step',", 'trainable=False,', 'collections=[tf.GraphKeys.GLOBAL_STEP,', 'tf.GraphKeys.GLOBAL_VARIABLES])', 'self.global_step', '=', 'global_step']
48,747
Alexander-Parker/youtube_nlp
common.py
validate_string
validate_string
Validates that 'value' is an instance of `basestring` for Python 2 or `str` for Python 3.
[ "Validates", "that", "'value'", "is", "an", "instance", "of", "`basestring`", "for", "Python", "2", "or", "`str`", "for", "Python", "3." ]
def validate_string(option, value): if isinstance(value, string_type): return value raise TypeError('Wrong type for %s, value must be an instance of %s' % (option, string_type.__name__))
['def', 'validate_string(option,', 'value):', 'if', 'isinstance(value,', 'string_type):', 'return', 'value', 'raise', "TypeError('Wrong", 'type', 'for', '%s,', 'value', 'must', 'be', 'an', 'instance', 'of', "%s'", '%', '(option,', 'string_type.__name__))']
970,359
nahueespinosa/ai50
tictactoe.py
minimax
minimax
Returns the optimal action for the current player on the board.
[ "Returns", "the", "optimal", "action", "for", "the", "current", "player", "on", "the", "board." ]
def minimax(board): if terminal(board): return None if board == initial_state(): return (0, 1) current_player = player(board) best_value = float('-inf') if current_player == X else float('inf') for action in actions(board): new_value = minimax_value(result(board, action), bes...
['def', 'minimax(board):', 'if', 'terminal(board):', 'return', 'None', 'if', 'board', '==', 'initial_state():', 'return', '(0,', '1)', 'current_player', '=', 'player(board)', 'best_value', '=', "float('-inf')", 'if', 'current_player', '==', 'X', 'else', "float('inf')", 'for', 'action', 'in', 'actions(board):', 'new_val...
85,529
ryu-ed/SpaceInvaders_Ros
mask_test.py
MaskTypeTest.test_get_at__out_of_bounds
test_get_at__out_of_bounds
Ensure get_at() checks bounds.
[ "Ensure", "get_at()", "checks", "bounds." ]
def test_get_at__out_of_bounds(self): (width, height) = (11, 3) mask = pygame.mask.Mask((width, height)) with self.assertRaises(IndexError): mask.get_at((width, 0)) with self.assertRaises(IndexError): mask.get_at((0, height)) with self.assertRaises(IndexError): mask.get_at((-...
['def', 'test_get_at__out_of_bounds(self):', '(width,', 'height)', '=', '(11,', '3)', 'mask', '=', 'pygame.mask.Mask((width,', 'height))', 'with', 'self.assertRaises(IndexError):', 'mask.get_at((width,', '0))', 'with', 'self.assertRaises(IndexError):', 'mask.get_at((0,', 'height))', 'with', 'self.assertRaises(IndexErro...
369,006
43Carrig/recurrent_neural_networks_practice
variable_scope.py
VariableScope.set_partitioner
set_partitioner
Set partitioner for this scope.
[ "Set", "partitioner", "for", "this", "scope." ]
def set_partitioner(self, partitioner): if partitioner and context.executing_eagerly(): raise NotImplementedError('Partitioned variables are not yet supported when eager execution is enabled.') self._partitioner = partitioner
['def', 'set_partitioner(self,', 'partitioner):', 'if', 'partitioner', 'and', 'context.executing_eagerly():', 'raise', "NotImplementedError('Partitioned", 'variables', 'are', 'not', 'yet', 'supported', 'when', 'eager', 'execution', 'is', "enabled.')", 'self._partitioner', '=', 'partitioner']
339,138
ZumoLabs/zpy
_version.py
get_keywords
get_keywords
Get the keywords needed to look up the version information.
[ "Get", "the", "keywords", "needed", "to", "look", "up", "the", "version", "information." ]
def get_keywords(): git_refnames = ' (HEAD -> main)' git_full = 'e12c47d414dceb457ce128bf87c67fbd4479f14a' git_date = '2021-12-04 07:26:07 -0800' keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date} return keywords
['def', 'get_keywords():', 'git_refnames', '=', "'", '(HEAD', '->', "main)'", 'git_full', '=', "'e12c47d414dceb457ce128bf87c67fbd4479f14a'", 'git_date', '=', "'2021-12-04", '07:26:07', "-0800'", 'keywords', '=', "{'refnames':", 'git_refnames,', "'full':", 'git_full,', "'date':", 'git_date}', 'return', 'keywords']
972,135
lektor/lektor-archive
environment.py
Config.get_alternative_url_span
get_alternative_url_span
Returns the URL span (prefix, suffix) for an alt.
[ "Returns", "the", "URL", "span", "(prefix,", "suffix)", "for", "an", "alt." ]
def get_alternative_url_span(self, alt=PRIMARY_ALT): if alt == PRIMARY_ALT: alt = self.primary_alternative cfg = self.values['ALTERNATIVES'].get(alt) if cfg is not None: return (cfg['url_prefix'] or '', cfg['url_suffix'] or '') return ('', '')
['def', 'get_alternative_url_span(self,', 'alt=PRIMARY_ALT):', 'if', 'alt', '==', 'PRIMARY_ALT:', 'alt', '=', 'self.primary_alternative', 'cfg', '=', "self.values['ALTERNATIVES'].get(alt)", 'if', 'cfg', 'is', 'not', 'None:', 'return', "(cfg['url_prefix']", 'or', "'',", "cfg['url_suffix']", 'or', "'')", 'return', "('',"...
216,454
arshpreetsingh/quantopian-machinelearning
io.py
Tee.write
write
Write data to both channels.
[ "Write", "data", "to", "both", "channels." ]
def write(self, data): self.file.write(data) self.ostream.write(data) self.ostream.flush()
['def', 'write(self,', 'data):', 'self.file.write(data)', 'self.ostream.write(data)', 'self.ostream.flush()']
887,058
microsoft/InnerEye-DeepLearning
test_image_encoder_with_mlp.py
ImageEncoder.get_image_transform
get_image_transform
Get transforms to perform on image samples for each model execution mode.
[ "Get", "transforms", "to", "perform", "on", "image", "samples", "for", "each", "model", "execution", "mode." ]
def get_image_transform(self) -> ModelTransformsPerExecutionMode: if self.imaging_feature_type in [ImagingFeatureType.Image, ImagingFeatureType.ImageAndSegmentation]: return ModelTransformsPerExecutionMode(train=ImageTransformationPipeline(transforms=[RandomAffine(10), ColorJitter(0.2)], use_different_trans...
['def', 'get_image_transform(self)', '->', 'ModelTransformsPerExecutionMode:', 'if', 'self.imaging_feature_type', 'in', '[ImagingFeatureType.Image,', 'ImagingFeatureType.ImageAndSegmentation]:', 'return', 'ModelTransformsPerExecutionMode(train=ImageTransformationPipeline(transforms=[RandomAffine(10),', 'ColorJitter(0.2...
613,716
HaoHou-98/SCGAN
normal.py
Normal.marginalize
marginalize
Creates a new marginal normal distribution for ''indices''.
[ "Creates", "a", "new", "marginal", "normal", "distribution", "for", "''indices''." ]
def marginalize(self, indices): indices = npa(indices) return Normal(len(indices), mu=self.mu[indices], sigma=self.E[ix(indices, indices)], margin={'indices': indices}, parent=self)
['def', 'marginalize(self,', 'indices):', 'indices', '=', 'npa(indices)', 'return', 'Normal(len(indices),', 'mu=self.mu[indices],', 'sigma=self.E[ix(indices,', 'indices)],', "margin={'indices':", 'indices},', 'parent=self)']
341,401
myothida/Supervised-Machine-Learning
test_peak_finding.py
TestFindPeaks.test_readonly_array
test_readonly_array
Test readonly arrays are accepted.
[ "Test", "readonly", "arrays", "are", "accepted." ]
def test_readonly_array(self, kwargs): x = np.linspace(0, 10, 15) x_readonly = x.copy() x_readonly.flags.writeable = False (peaks, _) = find_peaks(x) (peaks_readonly, _) = find_peaks(x_readonly, **kwargs) assert_allclose(peaks, peaks_readonly)
['def', 'test_readonly_array(self,', 'kwargs):', 'x', '=', 'np.linspace(0,', '10,', '15)', 'x_readonly', '=', 'x.copy()', 'x_readonly.flags.writeable', '=', 'False', '(peaks,', '_)', '=', 'find_peaks(x)', '(peaks_readonly,', '_)', '=', 'find_peaks(x_readonly,', '**kwargs)', 'assert_allclose(peaks,', 'peaks_readonly)']
446,245
tryolabs/luminoth
image_test.py
ImageTest.testPatchImageUpdateCondition
testPatchImageUpdateCondition
Tests we're not patching if we would lose all gt_boxes.
[ "Tests", "we're", "not", "patching", "if", "we", "would", "lose", "all", "gt_boxes." ]
def testPatchImageUpdateCondition(self): im_shape = (600, 800, 3) label = 3 image_ph = tf.placeholder(shape=(None, None, 3), dtype=tf.float32) bboxes_ph = tf.placeholder(shape=(None, 5), dtype=tf.int32) with self.test_session() as sess: image = self._gen_image(*im_shape) bboxes = [(0...
['def', 'testPatchImageUpdateCondition(self):', 'im_shape', '=', '(600,', '800,', '3)', 'label', '=', '3', 'image_ph', '=', 'tf.placeholder(shape=(None,', 'None,', '3),', 'dtype=tf.float32)', 'bboxes_ph', '=', 'tf.placeholder(shape=(None,', '5),', 'dtype=tf.int32)', 'with', 'self.test_session()', 'as', 'sess:', 'image'...
617,561
ryu-ed/SpaceInvaders_Ros
metadata.py
dedent_description
dedent_description
Dedent and convert pkg_info['Description'] to Unicode.
[ "Dedent", "and", "convert", "pkg_info['Description']", "to", "Unicode." ]
def dedent_description(pkg_info): description = pkg_info['Description'] surrogates = False if not isinstance(description, str): surrogates = True description = pkginfo_unicode(pkg_info, 'Description') description_lines = description.splitlines() description_dedent = '\n'.join((descri...
['def', 'dedent_description(pkg_info):', 'description', '=', "pkg_info['Description']", 'surrogates', '=', 'False', 'if', 'not', 'isinstance(description,', 'str):', 'surrogates', '=', 'True', 'description', '=', 'pkginfo_unicode(pkg_info,', "'Description')", 'description_lines', '=', 'description.splitlines()', 'descri...
371,595
Akash671/AI
heuristic_search.py
Grid.get_initial_state
get_initial_state
Returns the initial state.
[ "Returns", "the", "initial", "state." ]
def get_initial_state(self): for x in range(self.width): for y in range(self.height): if self.grid[x][y] == Grid.AGENT_SYMBOL: return State(self, x, y, frozenset()) return None
['def', 'get_initial_state(self):', 'for', 'x', 'in', 'range(self.width):', 'for', 'y', 'in', 'range(self.height):', 'if', 'self.grid[x][y]', '==', 'Grid.AGENT_SYMBOL:', 'return', 'State(self,', 'x,', 'y,', 'frozenset())', 'return', 'None']
69,791
Kvatsx/Artificial-Intelligence-Assignments
core.py
StateSetMetricFamily.add_metric
add_metric
Add a metric to the metric family.
[ "Add", "a", "metric", "to", "the", "metric", "family." ]
def add_metric(self, labels, value, timestamp=None): labels = tuple(labels) for (state, enabled) in sorted(value.items()): v = 1 if enabled else 0 self.samples.append(Sample(self.name, dict(zip(self._labelnames + (self.name,), labels + (state,))), v, timestamp))
['def', 'add_metric(self,', 'labels,', 'value,', 'timestamp=None):', 'labels', '=', 'tuple(labels)', 'for', '(state,', 'enabled)', 'in', 'sorted(value.items()):', 'v', '=', '1', 'if', 'enabled', 'else', '0', 'self.samples.append(Sample(self.name,', 'dict(zip(self._labelnames', '+', '(self.name,),', 'labels', '+', '(sta...
75,501
bislara/Object-detection-GUI
inputs_test.py
InputsTest.test_ssd_inceptionV2_eval_input
test_ssd_inceptionV2_eval_input
Tests the eval input function for SSDInceptionV2.
[ "Tests", "the", "eval", "input", "function", "for", "SSDInceptionV2." ]
def test_ssd_inceptionV2_eval_input(self, eval_batch_size=1): configs = _get_configs_for_model('ssd_inception_v2_pets') model_config = configs['model'] model_config.ssd.num_classes = 37 eval_config = configs['eval_config'] eval_config.batch_size = eval_batch_size eval_input_fn = inputs.create_ev...
['def', 'test_ssd_inceptionV2_eval_input(self,', 'eval_batch_size=1):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", 'model_config', '=', "configs['model']", 'model_config.ssd.num_classes', '=', '37', 'eval_config', '=', "configs['eval_config']", 'eval_config.batch_size', '=', 'eval_batch_size', '...
726,311
dshahrokhian/YOLO_tensorflow
voc_utils.py
load_imgs
load_imgs
Load a bunch of images from disk as np array.
[ "Load", "a", "bunch", "of", "images", "from", "disk", "as", "np", "array." ]
def load_imgs(img_filenames): return np.array([load_img(fname) for fname in img_filenames])
['def', 'load_imgs(img_filenames):', 'return', 'np.array([load_img(fname)', 'for', 'fname', 'in', 'img_filenames])']
969,906
saucelabs/monocle
eventloop.py
singleton
singleton
Raise an exception if an object of this class has been instantiated before.
[ "Raise", "an", "exception", "if", "an", "object", "of", "this", "class", "has", "been", "instantiated", "before." ]
def singleton(object, message='singleton class already instantiated', instantiated=[]): assert object.__class__ not in instantiated, message instantiated.append(object.__class__)
['def', 'singleton(object,', "message='singleton", 'class', 'already', "instantiated',", 'instantiated=[]):', 'assert', 'object.__class__', 'not', 'in', 'instantiated,', 'message', 'instantiated.append(object.__class__)']
241,128
bstellato/mlopt
filter.py
Filter.assign_samples
assign_samples
Assign samples to strategies choosing the ones minimizing the cost.
[ "Assign", "samples", "to", "strategies", "choosing", "the", "ones", "minimizing", "the", "cost." ]
def assign_samples(self, discarded_samples, selected_strategies, batch_size, parallel=True): self.y_train = np.array([np.where(selected_strategies == label)[0][0] if label in selected_strategies else -1 for label in self.y_train]) degradation = np.zeros(len(discarded_samples)) n_jobs = u.get_n_processes() i...
['def', 'assign_samples(self,', 'discarded_samples,', 'selected_strategies,', 'batch_size,', 'parallel=True):', 'self.y_train', '=', 'np.array([np.where(selected_strategies', '==', 'label)[0][0]', 'if', 'label', 'in', 'selected_strategies', 'else', '-1', 'for', 'label', 'in', 'self.y_train])', 'degradation', '=', 'np.z...
630,555
angeladai/ScanComplete
complete_scan.py
export_prediction_to_example
export_prediction_to_example
Saves predicted df/sem to file.
[ "Saves", "predicted", "df/sem", "to", "file." ]
def export_prediction_to_example(filename, pred_geo, pred_sem): with tf.python_io.TFRecordWriter(filename) as writer: out_feature = {'prediction_df/dim': util.int64_feature(pred_geo.shape), 'prediction_df': util.float_feature(pred_geo.flatten().tolist())} if FLAGS.predict_semantics: out_...
['def', 'export_prediction_to_example(filename,', 'pred_geo,', 'pred_sem):', 'with', 'tf.python_io.TFRecordWriter(filename)', 'as', 'writer:', 'out_feature', '=', "{'prediction_df/dim':", 'util.int64_feature(pred_geo.shape),', "'prediction_df':", 'util.float_feature(pred_geo.flatten().tolist())}', 'if', 'FLAGS.predict_...
845,840
devashish-patel/webcam-motion-detector
test_nbconvertapp.py
TestNbConvertApp.test_errors_print_traceback
test_errors_print_traceback
Verify that the stderr output contains the traceback of the cell execution exception.
[ "Verify", "that", "the", "stderr", "output", "contains", "the", "traceback", "of", "the", "cell", "execution", "exception." ]
def test_errors_print_traceback(self): with self.create_temp_cwd(['notebook3_with_errors.ipynb']): (_, error_output) = self.nbconvert('--execute --to markdown --stdout notebook3_with_errors.ipynb', ignore_return_code=True) assert 'print("Some text before the error")' in error_output assert '...
['def', 'test_errors_print_traceback(self):', 'with', "self.create_temp_cwd(['notebook3_with_errors.ipynb']):", '(_,', 'error_output)', '=', "self.nbconvert('--execute", '--to', 'markdown', '--stdout', "notebook3_with_errors.ipynb',", 'ignore_return_code=True)', 'assert', '\'print("Some', 'text', 'before', 'the', 'erro...
980,396
deepmind/dm_control
build_neck.py
create_neck
create_neck
Add neck and head in the dog model.
[ "Add", "neck", "and", "head", "in", "the", "dog", "model." ]
def create_neck(model, bone_position, cervical_dofs_per_vertebra, bones, side_sign, bone_size, parent): def_cervical = model.default.find('default', 'cervical') def_cervical_extend = model.default.find('default', 'cervical_extend') def_cervical_bend = model.default.find('default', 'cervical_bend') def_c...
['def', 'create_neck(model,', 'bone_position,', 'cervical_dofs_per_vertebra,', 'bones,', 'side_sign,', 'bone_size,', 'parent):', 'def_cervical', '=', "model.default.find('default',", "'cervical')", 'def_cervical_extend', '=', "model.default.find('default',", "'cervical_extend')", 'def_cervical_bend', '=', "model.defaul...
165,161
arshpreetsingh/quantopian-machinelearning
debugger.py
Pdb.do_psource
do_psource
Print (or run through pager) the source code for an object.
[ "Print", "(or", "run", "through", "pager)", "the", "source", "code", "for", "an", "object." ]
def do_psource(self, arg): namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
['def', 'do_psource(self,', 'arg):', 'namespaces', '=', "[('Locals',", 'self.curframe.f_locals),', "('Globals',", 'self.curframe.f_globals)]', "self.shell.find_line_magic('psource')(arg,", 'namespaces=namespaces)']
817,046
deepmind/dm_control
control.py
Physics.set_control
set_control
Sets the control signal for the actuators.
[ "Sets", "the", "control", "signal", "for", "the", "actuators." ]
def set_control(self, control): raise NotImplementedError('set_control is not supported.')
['def', 'set_control(self,', 'control):', 'raise', "NotImplementedError('set_control", 'is', 'not', "supported.')"]
166,250
alibaba/EasyCV
x3d_head.py
X3DHead.init_weights
init_weights
Performs ResNet style weight initialization.
[ "Performs", "ResNet", "style", "weight", "initialization." ]
def init_weights(self, fc_init_std=0.01, zero_init_final_bn=True): for m in self.modules(): if isinstance(m, nn.Conv3d): c2_msra_fill(m) elif isinstance(m, nn.BatchNorm3d): if hasattr(m, 'transform_final_bn') and m.transform_final_bn and zero_init_final_bn: ba...
['def', 'init_weights(self,', 'fc_init_std=0.01,', 'zero_init_final_bn=True):', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', 'nn.Conv3d):', 'c2_msra_fill(m)', 'elif', 'isinstance(m,', 'nn.BatchNorm3d):', 'if', 'hasattr(m,', "'transform_final_bn')", 'and', 'm.transform_final_bn', 'and', 'zero_init_final_b...
546,760
dbash/zerowaste
point_features.py
get_uncertain_point_coords_on_grid
get_uncertain_point_coords_on_grid
Find `num_points` most uncertain points from `uncertainty_map` grid.
[ "Find", "`num_points`", "most", "uncertain", "points", "from", "`uncertainty_map`", "grid." ]
def get_uncertain_point_coords_on_grid(uncertainty_map, num_points): (R, _, H, W) = uncertainty_map.shape h_step = 1.0 / float(H) w_step = 1.0 / float(W) num_points = min(H * W, num_points) point_indices = torch.topk(uncertainty_map.view(R, H * W), k=num_points, dim=1)[1] point_coords = torch.ze...
['def', 'get_uncertain_point_coords_on_grid(uncertainty_map,', 'num_points):', '(R,', '_,', 'H,', 'W)', '=', 'uncertainty_map.shape', 'h_step', '=', '1.0', '/', 'float(H)', 'w_step', '=', '1.0', '/', 'float(W)', 'num_points', '=', 'min(H', '*', 'W,', 'num_points)', 'point_indices', '=', 'torch.topk(uncertainty_map.view...
971,720
fudan-zvg/SeaFormer
custom.py
CustomDataset.format_results
format_results
Place holder to format result to dataset specific output.
[ "Place", "holder", "to", "format", "result", "to", "dataset", "specific", "output." ]
def format_results(self, results, imgfile_prefix, indices=None, **kwargs): raise NotImplementedError
['def', 'format_results(self,', 'results,', 'imgfile_prefix,', 'indices=None,', '**kwargs):', 'raise', 'NotImplementedError']
855,887
SamPujade/image-colorization
generator.py
Generator.get_layers
get_layers
Construct a convolutional unit with a conv layer followed by a batch normalisation layer and Leaky ReLU.
[ "Construct", "a", "convolutional", "unit", "with", "a", "conv", "layer", "followed", "by", "a", "batch", "normalisation", "layer", "and", "Leaky", "ReLU." ]
def get_layers(self, ch_in, ch_out, kernel_size=4, stride=2, padding=1, norm=True, act=True, leaky=True, transpose=False, dropout=False): layers = [] if transpose: layers.append(nn.ConvTranspose2d(ch_in, ch_out, kernel_size, stride, padding)) else: layers.append(nn.Conv2d(ch_in, ch_out, kern...
['def', 'get_layers(self,', 'ch_in,', 'ch_out,', 'kernel_size=4,', 'stride=2,', 'padding=1,', 'norm=True,', 'act=True,', 'leaky=True,', 'transpose=False,', 'dropout=False):', 'layers', '=', '[]', 'if', 'transpose:', 'layers.append(nn.ConvTranspose2d(ch_in,', 'ch_out,', 'kernel_size,', 'stride,', 'padding))', 'else:', '...
599,111
bitprophet/ssh
test_file.py
BufferedFileTest.test_4_write
test_4_write
verify that write buffering is on.
[ "verify", "that", "write", "buffering", "is", "on." ]
def test_4_write(self): f = LoopbackFile('r+', 1) f.write('Complete line.\nIncomplete line.') self.assertEqual(f.readline(), 'Complete line.\n') self.assertEqual(f.readline(), '') f.write('..\n') self.assertEqual(f.readline(), 'Incomplete line...\n') f.close()
['def', 'test_4_write(self):', 'f', '=', "LoopbackFile('r+',", '1)', "f.write('Complete", 'line.\\nIncomplete', "line.')", 'self.assertEqual(f.readline(),', "'Complete", "line.\\n')", 'self.assertEqual(f.readline(),', "'')", "f.write('..\\n')", 'self.assertEqual(f.readline(),', "'Incomplete", "line...\\n')", 'f.close()...
372,503
Kvatsx/Artificial-Intelligence-Assignments
eventloops.py
loop_tk
loop_tk
Start a kernel with the Tk event loop.
[ "Start", "a", "kernel", "with", "the", "Tk", "event", "loop." ]
def loop_tk(kernel): from tkinter import Tk, READABLE def process_stream_events(stream, *a, **kw): if stream.flush(limit=1): app.tk.deletefilehandler(stream.getsockopt(zmq.FD)) app.quit() kernel.app = app = Tk() kernel.app.withdraw() for stream in kernel.shell_stream...
['def', 'loop_tk(kernel):', 'from', 'tkinter', 'import', 'Tk,', 'READABLE', 'def', 'process_stream_events(stream,', '*a,', '**kw):', 'if', 'stream.flush(limit=1):', 'app.tk.deletefilehandler(stream.getsockopt(zmq.FD))', 'app.quit()', 'kernel.app', '=', 'app', '=', 'Tk()', 'kernel.app.withdraw()', 'for', 'stream', 'in',...
37,676
lujiazho/SegDrawer
image_encoder.py
window_unpartition
window_unpartition
Window unpartition into original sequences and removing padding.
[ "Window", "unpartition", "into", "original", "sequences", "and", "removing", "padding." ]
def window_unpartition(windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]) -> torch.Tensor: (Hp, Wp) = pad_hw (H, W) = hw B = windows.shape[0] // (Hp * Wp // window_size // window_size) x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size,...
['def', 'window_unpartition(windows:', 'torch.Tensor,', 'window_size:', 'int,', 'pad_hw:', 'Tuple[int,', 'int],', 'hw:', 'Tuple[int,', 'int])', '->', 'torch.Tensor:', '(Hp,', 'Wp)', '=', 'pad_hw', '(H,', 'W)', '=', 'hw', 'B', '=', 'windows.shape[0]', '//', '(Hp', '*', 'Wp', '//', 'window_size', '//', 'window_size)', 'x...
842,193
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
run_lfads.py
build_model
build_model
Builds a model from either random initialization, or saved parameters.
[ "Builds", "a", "model", "from", "either", "random", "initialization,", "or", "saved", "parameters." ]
def build_model(hps, kind='train', datasets=None): build_kind = kind if build_kind == 'write_model_params': build_kind = 'train' with tf.variable_scope('LFADS', reuse=None): model = LFADS(hps, kind=build_kind, datasets=datasets) if not os.path.exists(hps.lfads_save_dir): print('S...
['def', 'build_model(hps,', "kind='train',", 'datasets=None):', 'build_kind', '=', 'kind', 'if', 'build_kind', '==', "'write_model_params':", 'build_kind', '=', "'train'", 'with', "tf.variable_scope('LFADS',", 'reuse=None):', 'model', '=', 'LFADS(hps,', 'kind=build_kind,', 'datasets=datasets)', 'if', 'not', 'os.path.ex...
49,817
greydanus/pythonic_ocr
html.py
HtmlStatus.set_file_hash
set_file_hash
Set the hash of `fname`'s contents.
[ "Set", "the", "hash", "of", "`fname`'s", "contents." ]
def set_file_hash(self, fname, val): self.files.setdefault(fname, {})['hash'] = val
['def', 'set_file_hash(self,', 'fname,', 'val):', 'self.files.setdefault(fname,', "{})['hash']", '=', 'val']
298,935
bnpy/bnpy
MemoVBMovesAlg.py
MemoVBMovesAlg.verifyELBOTracking
verifyELBOTracking
Verify current global SS consistent with batch-specific SS.
[ "Verify", "current", "global", "SS", "consistent", "with", "batch-specific", "SS." ]
def verifyELBOTracking(self, hmodel, SS, loss_which_equals_negative_elbo=None, lapFrac=-1, MoveLog=None, **kwargs): if self.doDebugVerbose(): self.print_msg('>>>>>>>> BEGIN double-check @ lap %.2f' % self.lapFrac) if loss_which_equals_negative_elbo is None: loss_which_equals_negative_elbo = -1.0...
['def', 'verifyELBOTracking(self,', 'hmodel,', 'SS,', 'loss_which_equals_negative_elbo=None,', 'lapFrac=-1,', 'MoveLog=None,', '**kwargs):', 'if', 'self.doDebugVerbose():', "self.print_msg('>>>>>>>>", 'BEGIN', 'double-check', '@', 'lap', "%.2f'", '%', 'self.lapFrac)', 'if', 'loss_which_equals_negative_elbo', 'is', 'Non...
464,800
ryu-ed/SpaceInvaders_Ros
support.py
make_bad_fd
make_bad_fd
Create an invalid file descriptor by opening and closing a file and return its fd.
[ "Create", "an", "invalid", "file", "descriptor", "by", "opening", "and", "closing", "a", "file", "and", "return", "its", "fd." ]
def make_bad_fd(): file = open(TESTFN, 'wb') try: return file.fileno() finally: file.close() unlink(TESTFN)
['def', 'make_bad_fd():', 'file', '=', 'open(TESTFN,', "'wb')", 'try:', 'return', 'file.fileno()', 'finally:', 'file.close()', 'unlink(TESTFN)']
395,852
ayush219/NaturalLanguageProcessing
models.py
RNN.init_hidden
init_hidden
This is used for the first mini-batch in an epoch, only.
[ "This", "is", "used", "for", "the", "first", "mini-batch", "in", "an", "epoch,", "only." ]
def init_hidden(self): return torch.Tensor(self.num_layers, self.batch_size, self.hidden_size).fill_(0.0)
['def', 'init_hidden(self):', 'return', 'torch.Tensor(self.num_layers,', 'self.batch_size,', 'self.hidden_size).fill_(0.0)']
672,603
johnnyp2587/transfer-learning
seq2seq.py
embedding_rnn_decoder
embedding_rnn_decoder
RNN decoder with embedding and a pure-decoding option.
[ "RNN", "decoder", "with", "embedding", "and", "a", "pure-decoding", "option." ]
def embedding_rnn_decoder(decoder_inputs, initial_state, cell, embedding, num_symbols, embedding_size, word_dropout_keep_prob=1, replace_input=None, output_projection=None, feed_previous=False, update_embedding_for_previous=True, weight_initializer=None, beam_size=1, scope=None): with variable_scope.variable_scope(...
['def', 'embedding_rnn_decoder(decoder_inputs,', 'initial_state,', 'cell,', 'embedding,', 'num_symbols,', 'embedding_size,', 'word_dropout_keep_prob=1,', 'replace_input=None,', 'output_projection=None,', 'feed_previous=False,', 'update_embedding_for_previous=True,', 'weight_initializer=None,', 'beam_size=1,', 'scope=No...
929,510
hackebrot/poyo
parser.py
_Parser.parse_dashes
parse_dashes
Ignore lines that contain three dash symbols.
[ "Ignore", "lines", "that", "contain", "three", "dash", "symbols." ]
def parse_dashes(self, match): raise IgnoredMatchException
['def', 'parse_dashes(self,', 'match):', 'raise', 'IgnoredMatchException']
305,785
priorfire4411/artificial_intelligence
compat.py
BaseConfigurator.resolve
resolve
Resolve strings to objects using standard import and attribute syntax.
[ "Resolve", "strings", "to", "objects", "using", "standard", "import", "and", "attribute", "syntax." ]
def resolve(self, s): name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) ...
['def', 'resolve(self,', 's):', 'name', '=', "s.split('.')", 'used', '=', 'name.pop(0)', 'try:', 'found', '=', 'self.importer(used)', 'for', 'frag', 'in', 'name:', 'used', '+=', "'.'", '+', 'frag', 'try:', 'found', '=', 'getattr(found,', 'frag)', 'except', 'AttributeError:', 'self.importer(used)', 'found', '=', 'getatt...
154,230