Dataset Viewer
Auto-converted to Parquet Duplicate
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
arshpreetsingh/quantopian-machinelearning
key_processor.py
KeyPressEvent.app
app
The current `Application` object.
[ "The", "current", "`Application`", "object." ]
def app(self): return self._app
['def', 'app(self):', 'return', 'self._app']
892,308
jeromewang-github/computer_vision
demo_mnn.py
area_of
area_of
Compute the areas of rectangles given two corners.
[ "Compute", "the", "areas", "of", "rectangles", "given", "two", "corners." ]
def area_of(left_top, right_bottom): hw = np.clip(right_bottom - left_top, 0.0, None) return hw[..., 0] * hw[..., 1]
['def', 'area_of(left_top,', 'right_bottom):', 'hw', '=', 'np.clip(right_bottom', '-', 'left_top,', '0.0,', 'None)', 'return', 'hw[...,', '0]', '*', 'hw[...,', '1]']
474,862
weimin17/Object-Detection_HelmetDetection
model_hparams.py
create_hparams
create_hparams
Returns hyperparameters, including any flag value overrides.
[ "Returns", "hyperparameters,", "including", "any", "flag", "value", "overrides." ]
def create_hparams(hparams_overrides=None): hparams = tf.contrib.training.HParams(load_pretrained=True) if hparams_overrides: hparams = hparams.parse(hparams_overrides) return hparams
['def', 'create_hparams(hparams_overrides=None):', 'hparams', '=', 'tf.contrib.training.HParams(load_pretrained=True)', 'if', 'hparams_overrides:', 'hparams', '=', 'hparams.parse(hparams_overrides)', 'return', 'hparams']
751,511
ldkong1205/LaserMix
dbsampler.py
DataBaseSampler.filter_by_difficulty
filter_by_difficulty
Filter ground truths by difficulties.
[ "Filter", "ground", "truths", "by", "difficulties." ]
def filter_by_difficulty(db_infos: dict, removed_difficulty: list) -> dict: new_db_infos = {} for (key, dinfos) in db_infos.items(): new_db_infos[key] = [info for info in dinfos if info['difficulty'] not in removed_difficulty] return new_db_infos
['def', 'filter_by_difficulty(db_infos:', 'dict,', 'removed_difficulty:', 'list)', '->', 'dict:', 'new_db_infos', '=', '{}', 'for', '(key,', 'dinfos)', 'in', 'db_infos.items():', 'new_db_infos[key]', '=', '[info', 'for', 'info', 'in', 'dinfos', 'if', "info['difficulty']", 'not', 'in', 'removed_difficulty]', 'return', '...
623,794
paulorauber/rl
tensor_specs.py
OneHotDiscreteTensorSpec.to_categorical_spec
to_categorical_spec
Converts the spec to the equivalent categorical spec.
[ "Converts", "the", "spec", "to", "the", "equivalent", "categorical", "spec." ]
def to_categorical_spec(self) -> DiscreteTensorSpec: return DiscreteTensorSpec(self.space.n, device=self.device, shape=self.shape[:-1], mask=self.mask)
['def', 'to_categorical_spec(self)', '->', 'DiscreteTensorSpec:', 'return', 'DiscreteTensorSpec(self.space.n,', 'device=self.device,', 'shape=self.shape[:-1],', 'mask=self.mask)']
858,715
am-shashank/artificial-intelligence
core.py
_extrema_operation.outer
outer
Return the function applied to the outer product of a and b.
[ "Return", "the", "function", "applied", "to", "the", "outer", "product", "of", "a", "and", "b." ]
def outer(self, a, b): ma = getmask(a) mb = getmask(b) if ma is nomask and mb is nomask: m = nomask else: ma = getmaskarray(a) mb = getmaskarray(b) m = logical_or.outer(ma, mb) result = self.f.outer(filled(a), filled(b)) if not isinstance(result, MaskedArray): ...
['def', 'outer(self,', 'a,', 'b):', 'ma', '=', 'getmask(a)', 'mb', '=', 'getmask(b)', 'if', 'ma', 'is', 'nomask', 'and', 'mb', 'is', 'nomask:', 'm', '=', 'nomask', 'else:', 'ma', '=', 'getmaskarray(a)', 'mb', '=', 'getmaskarray(b)', 'm', '=', 'logical_or.outer(ma,', 'mb)', 'result', '=', 'self.f.outer(filled(a),', 'fil...
171,725
KleinYuan/tf-object-detection
oid_tfrecord_creation.py
tf_example_from_annotations_data_frame
tf_example_from_annotations_data_frame
Populates a TF Example message with image annotations from a data frame.
[ "Populates", "a", "TF", "Example", "message", "with", "image", "annotations", "from", "a", "data", "frame." ]
def tf_example_from_annotations_data_frame(annotations_data_frame, label_map, encoded_image): filtered_data_frame = annotations_data_frame[annotations_data_frame.LabelName.isin(label_map)] image_id = annotations_data_frame.ImageID.iloc[0] feature_map = {standard_fields.TfExampleFields.object_bbox_ymin: data...
['def', 'tf_example_from_annotations_data_frame(annotations_data_frame,', 'label_map,', 'encoded_image):', 'filtered_data_frame', '=', 'annotations_data_frame[annotations_data_frame.LabelName.isin(label_map)]', 'image_id', '=', 'annotations_data_frame.ImageID.iloc[0]', 'feature_map', '=', '{standard_fields.TfExampleFie...
914,811
seltzerfish/guardyn
gtest_help_test.py
GTestHelpTest.testRunsTestsWithoutHelpFlag
testRunsTestsWithoutHelpFlag
Verifies that when no help flag is specified, the tests are run and the help message is not printed.
[ "Verifies", "that", "when", "no", "help", "flag", "is", "specified,", "the", "tests", "are", "run", "and", "the", "help", "message", "is", "not", "printed." ]
def testRunsTestsWithoutHelpFlag(self): self.TestNonHelpFlag(None)
['def', 'testRunsTestsWithoutHelpFlag(self):', 'self.TestNonHelpFlag(None)']
572,280
zackmcnulty/CSE_446-Machine_Learning
figure.py
Figure.get_figheight
get_figheight
Return the figure height as a float.
[ "Return", "the", "figure", "height", "as", "a", "float." ]
def get_figheight(self): return self.bbox_inches.height
['def', 'get_figheight(self):', 'return', 'self.bbox_inches.height']
194,326
Speech-Lab-IITM/CCC-wav2vec-2.0
model.py
PipelineParallelTransformerModel.max_positions_helper
max_positions_helper
Maximum input length supported by the encoder or decoder.
[ "Maximum", "input", "length", "supported", "by", "the", "encoder", "or", "decoder." ]
def max_positions_helper(self, embedding_layer, max_positions_field='max_source_positions'): if embedding_layer.embed_positions is None: return getattr(embedding_layer, max_positions_field) return min(getattr(embedding_layer, max_positions_field), embedding_layer.embed_positions.max_positions)
['def', 'max_positions_helper(self,', 'embedding_layer,', "max_positions_field='max_source_positions'):", 'if', 'embedding_layer.embed_positions', 'is', 'None:', 'return', 'getattr(embedding_layer,', 'max_positions_field)', 'return', 'min(getattr(embedding_layer,', 'max_positions_field),', 'embedding_layer.embed_positi...
103,951
ChenhongyiYang/PPAL
transformer.py
DeformableDetrTransformer.get_reference_points
get_reference_points
Get the reference points used in decoder.
[ "Get", "the", "reference", "points", "used", "in", "decoder." ]
def get_reference_points(spatial_shapes, valid_ratios, device): reference_points_list = [] for (lvl, (H, W)) in enumerate(spatial_shapes): (ref_y, ref_x) = torch.meshgrid(torch.linspace(0.5, H - 0.5, H, dtype=torch.float32, device=device), torch.linspace(0.5, W - 0.5, W, dtype=torch.float32, device=devi...
['def', 'get_reference_points(spatial_shapes,', 'valid_ratios,', 'device):', 'reference_points_list', '=', '[]', 'for', '(lvl,', '(H,', 'W))', 'in', 'enumerate(spatial_shapes):', '(ref_y,', 'ref_x)', '=', 'torch.meshgrid(torch.linspace(0.5,', 'H', '-', '0.5,', 'H,', 'dtype=torch.float32,', 'device=device),', 'torch.lin...
821,829
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
imagenet_main.py
record_parser
record_parser
Parse an ImageNet record from `value`.
[ "Parse", "an", "ImageNet", "record", "from", "`value`." ]
def record_parser(value, is_training): keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/class/label': tf.FixedLenFeature([], dtype=tf.int64, default_value=-1), 'image/class/text': tf.FixedLenFeat...
['def', 'record_parser(value,', 'is_training):', 'keys_to_features', '=', "{'image/encoded':", 'tf.FixedLenFeature((),', 'tf.string,', "default_value=''),", "'image/format':", 'tf.FixedLenFeature((),', 'tf.string,', "default_value='jpeg'),", "'image/class/label':", 'tf.FixedLenFeature([],', 'dtype=tf.int64,', 'default_...
13,997
scikit-learn/scikit-learn
test_column_transformer.py
test_column_transform_set_output_mixed
test_column_transform_set_output_mixed
Check ColumnTransformer outputs mixed types correctly.
[ "Check", "ColumnTransformer", "outputs", "mixed", "types", "correctly." ]
def test_column_transform_set_output_mixed(remainder, fit_transform): pd = pytest.importorskip('pandas') df = pd.DataFrame({'pet': pd.Series(['dog', 'cat', 'snake'], dtype='category'), 'color': pd.Series(['green', 'blue', 'red'], dtype='object'), 'age': [1.4, 2.1, 4.4], 'height': [20, 40, 10], 'distance': pd.Se...
['def', 'test_column_transform_set_output_mixed(remainder,', 'fit_transform):', 'pd', '=', "pytest.importorskip('pandas')", 'df', '=', "pd.DataFrame({'pet':", "pd.Series(['dog',", "'cat',", "'snake'],", "dtype='category'),", "'color':", "pd.Series(['green',", "'blue',", "'red'],", "dtype='object'),", "'age':", '[1.4,',...
852,897
ermongroup/MA-AIRL
tf_util.py
TfInput.make_feed_dict
make_feed_dict
Given data input it to the placeholder(s).
[ "Given", "data", "input", "it", "to", "the", "placeholder(s)." ]
def make_feed_dict(data): raise NotImplemented()
['def', 'make_feed_dict(data):', 'raise', 'NotImplemented()']
620,093
greydanus/pythonic_ocr
environment.py
Template.is_up_to_date
is_up_to_date
If this variable is `False` there is a newer version available.
[ "If", "this", "variable", "is", "`False`", "there", "is", "a", "newer", "version", "available." ]
def is_up_to_date(self): if self._uptodate is None: return True return self._uptodate()
['def', 'is_up_to_date(self):', 'if', 'self._uptodate', 'is', 'None:', 'return', 'True', 'return', 'self._uptodate()']
299,248
keya-desai/Natural-Language-Processing
parsing_system.py
ParsingSystem.can_apply
can_apply
Determine whether the given transition is legal for this configuration.
[ "Determine", "whether", "the", "given", "transition", "is", "legal", "for", "this", "configuration." ]
def can_apply(self, configuration: Configuration, transition: str) -> bool: if transition.startswith('L') or transition.startswith('R'): label = transition[2:-1] if transition.startswith('L'): h = configuration.get_stack(0) else: h = configuration.get_stack(1) ...
['def', 'can_apply(self,', 'configuration:', 'Configuration,', 'transition:', 'str)', '->', 'bool:', 'if', "transition.startswith('L')", 'or', "transition.startswith('R'):", 'label', '=', 'transition[2:-1]', 'if', "transition.startswith('L'):", 'h', '=', 'configuration.get_stack(0)', 'else:', 'h', '=', 'configuration.g...
688,306
nosmokingbandit/watcher
servers.py
check_port
check_port
Raise an error if the given port is not free on the given host.
[ "Raise", "an", "error", "if", "the", "given", "port", "is", "not", "free", "on", "the", "given", "host." ]
def check_port(host, port, timeout=1.0): if not host: raise ValueError("Host values of '' or None are not allowed.") host = client_host(host) port = int(port) import socket try: info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) except socket.gaierror: ...
['def', 'check_port(host,', 'port,', 'timeout=1.0):', 'if', 'not', 'host:', 'raise', 'ValueError("Host', 'values', 'of', "''", 'or', 'None', 'are', 'not', 'allowed.")', 'host', '=', 'client_host(host)', 'port', '=', 'int(port)', 'import', 'socket', 'try:', 'info', '=', 'socket.getaddrinfo(host,', 'port,', 'socket.AF_UN...
381,519
dawidkopczyk/autoencoder
setup_inception.py
maybe_download_and_extract
maybe_download_and_extract
Download and extract model tar file.
[ "Download", "and", "extract", "model", "tar", "file." ]
def maybe_download_and_extract(): dest_directory = FLAGS.model_dir if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepath): def _progress(count, block_size...
['def', 'maybe_download_and_extract():', 'dest_directory', '=', 'FLAGS.model_dir', 'if', 'not', 'os.path.exists(dest_directory):', 'os.makedirs(dest_directory)', 'filename', '=', "DATA_URL.split('/')[-1]", 'filepath', '=', 'os.path.join(dest_directory,', 'filename)', 'if', 'not', 'os.path.exists(filepath):', 'def', '_p...
418,928
pedrojrv/nucml
plot.py
xgb_training_w_path
xgb_training_w_path
Plot XGB retraining given the path to the results.
[ "Plot", "XGB", "retraining", "given", "the", "path", "to", "the", "results." ]
def xgb_training_w_path(path_to_csv, save=False, saving_path='xgb_training.png'): training_progress = pd.read_csv(path_to_csv) plt.figure(figsize=(18, 8)) plt.plot(training_progress.mae_train, label='Train MAE', marker='x', markersize='20') plt.plot(training_progress.mae_test, label='Validation MAE', ma...
['def', 'xgb_training_w_path(path_to_csv,', 'save=False,', "saving_path='xgb_training.png'):", 'training_progress', '=', 'pd.read_csv(path_to_csv)', 'plt.figure(figsize=(18,', '8))', 'plt.plot(training_progress.mae_train,', "label='Train", "MAE',", "marker='x',", "markersize='20')", 'plt.plot(training_progress.mae_test...
249,756
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
check.py
Eq
Eq
Raises an error if |lhs| does not equal |rhs|.
[ "Raises", "an", "error", "if", "|lhs|", "does", "not", "equal", "|rhs|." ]
def Eq(lhs, rhs, message='', error=ValueError): if lhs != rhs: raise error('Expected (%s) == (%s): %s' % (lhs, rhs, message))
['def', 'Eq(lhs,', 'rhs,', "message='',", 'error=ValueError):', 'if', 'lhs', '!=', 'rhs:', 'raise', "error('Expected", '(%s)', '==', '(%s):', "%s'", '%', '(lhs,', 'rhs,', 'message))']
28,935
yoonc5536/computer_vision
draw.py
choose_color_by_layertype
choose_color_by_layertype
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type." ]
def choose_color_by_layertype(layertype): color = '#6495ED' if layertype == 'Convolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
['def', 'choose_color_by_layertype(layertype):', 'color', '=', "'#6495ED'", 'if', 'layertype', '==', "'Convolution':", 'color', '=', "'#FF5050'", 'elif', 'layertype', '==', "'Pooling':", 'color', '=', "'#FF9900'", 'elif', 'layertype', '==', "'InnerProduct':", 'color', '=', "'#CC33FF'", 'return', 'color']
472,559
ifwe/digsby
simplemenu.py
SimpleMenuSpine.TriggerItem
TriggerItem
Steps to take when a item is clicked.
[ "Steps", "to", "take", "when", "a", "item", "is", "clicked." ]
def TriggerItem(self, item): if item.method is not None: wx.CallAfter(item.method, item) elif self.Parent.callback: wx.CallAfter(self.Parent.callback, item) else: menuevent = MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED, item.id) self.Parent.AddPendingEvent(menuevent) self.Pa...
['def', 'TriggerItem(self,', 'item):', 'if', 'item.method', 'is', 'not', 'None:', 'wx.CallAfter(item.method,', 'item)', 'elif', 'self.Parent.callback:', 'wx.CallAfter(self.Parent.callback,', 'item)', 'else:', 'menuevent', '=', 'MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED,', 'item.id)', 'self.Parent.AddPendingEvent(menueve...
185,591
ArdaGunay99/Key_Detection_Unsupervised_Learning
triinterpolate.py
_Sparse_Matrix_coo.diag
diag
Returns the (dense) vector of the diagonal elements.
[ "Returns", "the", "(dense)", "vector", "of", "the", "diagonal", "elements." ]
def diag(self): in_diag = self.rows == self.cols diag = np.zeros(min(self.n, self.n), dtype=np.float64) diag[self.rows[in_diag]] = self.vals[in_diag] return diag
['def', 'diag(self):', 'in_diag', '=', 'self.rows', '==', 'self.cols', 'diag', '=', 'np.zeros(min(self.n,', 'self.n),', 'dtype=np.float64)', 'diag[self.rows[in_diag]]', '=', 'self.vals[in_diag]', 'return', 'diag']
258,065
chainer/chainer
link.py
ChainList.insert
insert
Insert a child link at the given index.
[ "Insert", "a", "child", "link", "at", "the", "given", "index." ]
def insert(self, index: int, link: Link) -> None: if index == len(self._children): self._children.append(link) link.name = str(index) else: self._children.insert(index, link) for (i, c) in enumerate(self._children): c.name = str(i)
['def', 'insert(self,', 'index:', 'int,', 'link:', 'Link)', '->', 'None:', 'if', 'index', '==', 'len(self._children):', 'self._children.append(link)', 'link.name', '=', 'str(index)', 'else:', 'self._children.insert(index,', 'link)', 'for', '(i,', 'c)', 'in', 'enumerate(self._children):', 'c.name', '=', 'str(i)']
477,011
thu-ml/tianshou
discrete.py
FullQuantileFunction.forward
forward
Mapping: s -> Q(s, \*).
[ "Mapping:", "s", "->", "Q(s,", "\\*)." ]
def forward(self, obs: Union[np.ndarray, torch.Tensor], propose_model: FractionProposalNetwork, fractions: Optional[Batch]=None, **kwargs: Any) -> tuple[Any, torch.Tensor]: (logits, hidden) = self.preprocess(obs, state=kwargs.get('state', None)) if fractions is None: (taus, tau_hats, entropies) = propos...
['def', 'forward(self,', 'obs:', 'Union[np.ndarray,', 'torch.Tensor],', 'propose_model:', 'FractionProposalNetwork,', 'fractions:', 'Optional[Batch]=None,', '**kwargs:', 'Any)', '->', 'tuple[Any,', 'torch.Tensor]:', '(logits,', 'hidden)', '=', 'self.preprocess(obs,', "state=kwargs.get('state',", 'None))', 'if', 'fracti...
355,329
kornia/kornia
face_detection.py
FaceDetectorResult.ymin
ymin
The bounding box top-left y-coordinate.
[ "The", "bounding", "box", "top-left", "y-coordinate." ]
def ymin(self) -> torch.Tensor: return self._data[..., 1]
['def', 'ymin(self)', '->', 'torch.Tensor:', 'return', 'self._data[...,', '1]']
621,586
roboflow/roboflow-computer-vision-utilities
uploadby_split.py
get_image_paths
get_image_paths
Get a list of image file paths from a directory.
[ "Get", "a", "list", "of", "image", "file", "paths", "from", "a", "directory." ]
def get_image_paths(directory: str): image_extensions = {'.jpeg', '.jpg', '.png'} image_paths = [] for file in os.listdir(directory): file_extension = os.path.splitext(file)[1].lower() if file_extension in image_extensions: image_paths.append(os.path.join(directory, file)) re...
['def', 'get_image_paths(directory:', 'str):', 'image_extensions', '=', "{'.jpeg',", "'.jpg',", "'.png'}", 'image_paths', '=', '[]', 'for', 'file', 'in', 'os.listdir(directory):', 'file_extension', '=', 'os.path.splitext(file)[1].lower()', 'if', 'file_extension', 'in', 'image_extensions:', 'image_paths.append(os.path.j...
825,952
zihuitang/medical_AI_platform
warnings.py
formatwarning
formatwarning
Function to format a warning the standard way.
[ "Function", "to", "format", "a", "warning", "the", "standard", "way." ]
def formatwarning(message, category, filename, lineno, line=None): msg = WarningMessage(message, category, filename, lineno, None, line) return _formatwarnmsg_impl(msg)
['def', 'formatwarning(message,', 'category,', 'filename,', 'lineno,', 'line=None):', 'msg', '=', 'WarningMessage(message,', 'category,', 'filename,', 'lineno,', 'None,', 'line)', 'return', '_formatwarnmsg_impl(msg)']
281,792
rifqind/Agent-Programs-3KS1
tests.py
test_none
test_none
Return true if the variable is none.
[ "Return", "true", "if", "the", "variable", "is", "none." ]
def test_none(value): return value is None
['def', 'test_none(value):', 'return', 'value', 'is', 'None']
42,374
Summer0410/Natural-Language-Processing
parsing_system.py
ParsingSystem.make_transitions
make_transitions
Generate all possible transitions which this parsing system can take for any given configuration.
[ "Generate", "all", "possible", "transitions", "which", "this", "parsing", "system", "can", "take", "for", "any", "given", "configuration." ]
def make_transitions(self) -> None: for label in self.labels: self.transitions.append('L(' + label + ')') for label in self.labels: self.transitions.append('R(' + label + ')') self.transitions.append('S')
['def', 'make_transitions(self)', '->', 'None:', 'for', 'label', 'in', 'self.labels:', "self.transitions.append('L('", '+', 'label', '+', "')')", 'for', 'label', 'in', 'self.labels:', "self.transitions.append('R('", '+', 'label', '+', "')')", "self.transitions.append('S')"]
688,589
Tommy-Ngx/Multi_TimeGAN
mygru_cell.py
MyGRUCell4.call
call
Gated recurrent unit (GRU) with nunits cells.
[ "Gated", "recurrent", "unit", "(GRU)", "with", "nunits", "cells." ]
def call(self, inputs, state): totalLength = inputs.get_shape().as_list()[1] inputs_ = inputs[:, 0:totalLength - self._num_units] rth = inputs[:, totalLength - self._num_units:] inputs = inputs_ state = math_ops.multiply(rth, state) if self._gate_linear is None: bias_ones = self._bias_in...
['def', 'call(self,', 'inputs,', 'state):', 'totalLength', '=', 'inputs.get_shape().as_list()[1]', 'inputs_', '=', 'inputs[:,', '0:totalLength', '-', 'self._num_units]', 'rth', '=', 'inputs[:,', 'totalLength', '-', 'self._num_units:]', 'inputs', '=', 'inputs_', 'state', '=', 'math_ops.multiply(rth,', 'state)', 'if', 's...
644,517
ryu-ed/SpaceInvaders_Ros
utils.py
find_try_except_wrapper_node
find_try_except_wrapper_node
Return the ExceptHandler or the TryExcept node in which the node is.
[ "Return", "the", "ExceptHandler", "or", "the", "TryExcept", "node", "in", "which", "the", "node", "is." ]
def find_try_except_wrapper_node(node: astroid.node_classes.NodeNG) -> Optional[Union[astroid.ExceptHandler, astroid.TryExcept]]: current = node ignores = (astroid.ExceptHandler, astroid.TryExcept) while current and (not isinstance(current.parent, ignores)): current = current.parent if current a...
['def', 'find_try_except_wrapper_node(node:', 'astroid.node_classes.NodeNG)', '->', 'Optional[Union[astroid.ExceptHandler,', 'astroid.TryExcept]]:', 'current', '=', 'node', 'ignores', '=', '(astroid.ExceptHandler,', 'astroid.TryExcept)', 'while', 'current', 'and', '(not', 'isinstance(current.parent,', 'ignores)):', 'cu...
370,019
tensorflow/data-validation
stats_impl.py
generate_statistics_in_memory
generate_statistics_in_memory
Generates statistics for an in-memory list of examples.
[ "Generates", "statistics", "for", "an", "in-memory", "list", "of", "examples." ]
def generate_statistics_in_memory(record_batch: pa.RecordBatch, options: stats_options.StatsOptions=stats_options.StatsOptions()) -> statistics_pb2.DatasetFeatureStatisticsList: stats_generators = cast(List[stats_generator.CombinerStatsGenerator], get_generators(options, in_memory=True)) partial_stats = generat...
['def', 'generate_statistics_in_memory(record_batch:', 'pa.RecordBatch,', 'options:', 'stats_options.StatsOptions=stats_options.StatsOptions())', '->', 'statistics_pb2.DatasetFeatureStatisticsList:', 'stats_generators', '=', 'cast(List[stats_generator.CombinerStatsGenerator],', 'get_generators(options,', 'in_memory=Tru...
497,452
scikit-learn/scikit-learn
test_tree.py
test_missing_values_best_splitter_to_left
test_missing_values_best_splitter_to_left
Missing values spanning only one class at fit-time must make missing values at predict-time be classified has belonging to this class.
[ "Missing", "values", "spanning", "only", "one", "class", "at", "fit-time", "must", "make", "missing", "values", "at", "predict-time", "be", "classified", "has", "belonging", "to", "this", "class." ]
def test_missing_values_best_splitter_to_left(criterion): X = np.array([[np.nan] * 4 + [0, 1, 2, 3, 4, 5]]).T y = np.array([0] * 4 + [1] * 6) dtc = DecisionTreeClassifier(random_state=42, max_depth=2, criterion=criterion) dtc.fit(X, y) X_test = np.array([[np.nan, 5, np.nan]]).T y_pred = dtc.pred...
['def', 'test_missing_values_best_splitter_to_left(criterion):', 'X', '=', 'np.array([[np.nan]', '*', '4', '+', '[0,', '1,', '2,', '3,', '4,', '5]]).T', 'y', '=', 'np.array([0]', '*', '4', '+', '[1]', '*', '6)', 'dtc', '=', 'DecisionTreeClassifier(random_state=42,', 'max_depth=2,', 'criterion=criterion)', 'dtc.fit(X,',...
854,228
rudranil723/mini-main
autopep8.py
FixPEP8.fix_w391
fix_w391
Remove trailing blank lines.
[ "Remove", "trailing", "blank", "lines." ]
def fix_w391(self, _): blank_count = 0 for line in reversed(self.source): line = line.rstrip() if line: break else: blank_count += 1 original_length = len(self.source) self.source = self.source[:original_length - blank_count] return range(1, 1 + origin...
['def', 'fix_w391(self,', '_):', 'blank_count', '=', '0', 'for', 'line', 'in', 'reversed(self.source):', 'line', '=', 'line.rstrip()', 'if', 'line:', 'break', 'else:', 'blank_count', '+=', '1', 'original_length', '=', 'len(self.source)', 'self.source', '=', 'self.source[:original_length', '-', 'blank_count]', 'return',...
313,928
PacktPublishing/Hands-On-Artificial--for-Banking
test_base.py
sparse_test_class
sparse_test_class
Construct a base class, optionally converting some of the tests in the suite to check that the feature is not implemented.
[ "Construct", "a", "base", "class,", "optionally", "converting", "some", "of", "the", "tests", "in", "the", "suite", "to", "check", "that", "the", "feature", "is", "not", "implemented." ]
def sparse_test_class(getset=True, slicing=True, slicing_assign=True, fancy_indexing=True, fancy_assign=True, fancy_multidim_indexing=True, fancy_multidim_assign=True, minmax=True, nnz_axis=True): bases = (_TestCommon, _possibly_unimplemented(_TestGetSet, getset), _TestSolve, _TestInplaceArithmetic, _TestArithmetic...
['def', 'sparse_test_class(getset=True,', 'slicing=True,', 'slicing_assign=True,', 'fancy_indexing=True,', 'fancy_assign=True,', 'fancy_multidim_indexing=True,', 'fancy_multidim_assign=True,', 'minmax=True,', 'nnz_axis=True):', 'bases', '=', '(_TestCommon,', '_possibly_unimplemented(_TestGetSet,', 'getset),', '_TestSol...
203,474
thaines/helit
pool.py
Pool.size
size
Returns how many entities are currently stored.
[ "Returns", "how", "many", "entities", "are", "currently", "stored." ]
def size(self): return len(self.entities)
['def', 'size(self):', 'return', 'len(self.entities)']
591,601
LiqunChen0606/Triangle-GAN
triGan_mnist.py
data_network_2
data_network_2
Approximate z log data density.
[ "Approximate", "z", "log", "data", "density." ]
def data_network_2(x, y): with tf.variable_scope('D2'): d = discriminator(x, y) return tf.squeeze(d, squeeze_dims=[1])
['def', 'data_network_2(x,', 'y):', 'with', "tf.variable_scope('D2'):", 'd', '=', 'discriminator(x,', 'y)', 'return', 'tf.squeeze(d,', 'squeeze_dims=[1])']
951,573
PacktPublishing/Hands-On-Artificial--for-Banking
tarfile.py
stn
stn
Convert a string to a null-terminated bytes object.
[ "Convert", "a", "string", "to", "a", "null-terminated", "bytes", "object." ]
def stn(s, length, encoding, errors): s = s.encode(encoding, errors) return s[:length] + (length - len(s)) * NUL
['def', 'stn(s,', 'length,', 'encoding,', 'errors):', 's', '=', 's.encode(encoding,', 'errors)', 'return', 's[:length]', '+', '(length', '-', 'len(s))', '*', 'NUL']
237,854
ViTAE-Transformer/ViTDet
transformer.py
DeformableDetrTransformer.get_valid_ratio
get_valid_ratio
Get the valid radios of feature maps of all level.
[ "Get", "the", "valid", "radios", "of", "feature", "maps", "of", "all", "level." ]
def get_valid_ratio(self, mask): (_, H, W) = mask.shape valid_H = torch.sum(~mask[:, :, 0], 1) valid_W = torch.sum(~mask[:, 0, :], 1) valid_ratio_h = valid_H.float() / H valid_ratio_w = valid_W.float() / W valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) return valid_ratio
['def', 'get_valid_ratio(self,', 'mask):', '(_,', 'H,', 'W)', '=', 'mask.shape', 'valid_H', '=', 'torch.sum(~mask[:,', ':,', '0],', '1)', 'valid_W', '=', 'torch.sum(~mask[:,', '0,', ':],', '1)', 'valid_ratio_h', '=', 'valid_H.float()', '/', 'H', 'valid_ratio_w', '=', 'valid_W.float()', '/', 'W', 'valid_ratio', '=', 'to...
945,822
arijit7978/arijit7978-Artificial-Intelligence-CSE-471--PacMan
solvers.py
GradientDescentSolver.get_updates_with_momentum
get_updates_with_momentum
Question 5: Returns the gradient descent updates when momentum is used.
[ "Question", "5:", "Returns", "the", "gradient", "descent", "updates", "when", "momentum", "is", "used." ]
def get_updates_with_momentum(self, loss_tensor, param_vars): grad_tensors = tf.gradients(loss_tensor, param_vars) vel_vars = [tf.Variable(np.zeros(param_var.get_shape(), dtype=np.float32)) for param_var in param_vars] tfu.get_session().run([vel_var.initializer for vel_var in vel_vars]) updates = [] ...
['def', 'get_updates_with_momentum(self,', 'loss_tensor,', 'param_vars):', 'grad_tensors', '=', 'tf.gradients(loss_tensor,', 'param_vars)', 'vel_vars', '=', '[tf.Variable(np.zeros(param_var.get_shape(),', 'dtype=np.float32))', 'for', 'param_var', 'in', 'param_vars]', 'tfu.get_session().run([vel_var.initializer', 'for',...
34,706
kiseliu/NaturalLanguageProcessing
run_classifier.py
DataProcessor.get_dev_examples
get_dev_examples
Gets a collection of `InputExample`s for the dev set.
[ "Gets", "a", "collection", "of", "`InputExample`s", "for", "the", "dev", "set." ]
def get_dev_examples(self, data_dir): raise NotImplementedError()
['def', 'get_dev_examples(self,', 'data_dir):', 'raise', 'NotImplementedError()']
713,617
tobegit3hub/deep_image_model
debug_data.py
DebugDumpDir.get_tensor_file_paths
get_tensor_file_paths
Get the file paths from a debug-dumped tensor.
[ "Get", "the", "file", "paths", "from", "a", "debug-dumped", "tensor." ]
def get_tensor_file_paths(self, node_name, output_slot, debug_op): watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) if watch_key not in self._watch_key_to_datum: raise ValueError('Watch key "%s" does not exist in the debug dump' % watch_key) return [datum.file_path for datum in se...
['def', 'get_tensor_file_paths(self,', 'node_name,', 'output_slot,', 'debug_op):', 'watch_key', '=', '_get_tensor_watch_key(node_name,', 'output_slot,', 'debug_op)', 'if', 'watch_key', 'not', 'in', 'self._watch_key_to_datum:', 'raise', "ValueError('Watch", 'key', '"%s"', 'does', 'not', 'exist', 'in', 'the', 'debug', "d...
182,332
huawei-noah/xingtian
starcraft_qmix.py
StarCraftQMix.do_one_interaction
do_one_interaction
Overwrite with obs and global states.
[ "Overwrite", "with", "obs", "and", "global", "states." ]
def do_one_interaction(self, raw_state, use_explore=True): pre_transition_data = {'state': [self.env.get_state()], 'avail_actions': [self.env.get_avail_actions()], 'obs': [self.env.get_obs()]} self.batch.update(pre_transition_data, ts=self.timestamp_per_agent) _start0 = time() actions = self.alg.predict...
['def', 'do_one_interaction(self,', 'raw_state,', 'use_explore=True):', 'pre_transition_data', '=', "{'state':", '[self.env.get_state()],', "'avail_actions':", '[self.env.get_avail_actions()],', "'obs':", '[self.env.get_obs()]}', 'self.batch.update(pre_transition_data,', 'ts=self.timestamp_per_agent)', '_start0', '=', ...
962,066
enuguru/artificial_intelligence_and_machine_learning
index.py
Index.doc_count
doc_count
Returns the total number of UNDELETED documents in this index.
[ "Returns", "the", "total", "number", "of", "UNDELETED", "documents", "in", "this", "index." ]
def doc_count(self): r = self.reader() try: return r.doc_count() finally: r.close()
['def', 'doc_count(self):', 'r', '=', 'self.reader()', 'try:', 'return', 'r.doc_count()', 'finally:', 'r.close()']
132,946
arshpreetsingh/quantopian-machinelearning
locks.py
Semaphore.release
release
Increment the counter and wake one waiter.
[ "Increment", "the", "counter", "and", "wake", "one", "waiter." ]
def release(self) -> None: self._value += 1 while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) break
['def', 'release(self)', '->', 'None:', 'self._value', '+=', '1', 'while', 'self._waiters:', 'waiter', '=', 'self._waiters.popleft()', 'if', 'not', 'waiter.done():', 'self._value', '-=', '1', 'waiter.set_result(_ReleasingContextManager(self))', 'break']
893,529
weimin17/Object-Detection_HelmetDetection
utils.py
visualize_voxel_spectral
visualize_voxel_spectral
Function to visualize voxel (spectral).
[ "Function", "to", "visualize", "voxel", "(spectral)." ]
def visualize_voxel_spectral(points, vis_size=128): points = np.rint(points) points = np.swapaxes(points, 0, 2) fig = p.figure(figsize=(1, 1), dpi=vis_size) (verts, faces) = measure.marching_cubes_classic(points, 0, spacing=(0.1, 0.1, 0.1)) ax = fig.add_subplot(111, projection='3d') ax.plot_tris...
['def', 'visualize_voxel_spectral(points,', 'vis_size=128):', 'points', '=', 'np.rint(points)', 'points', '=', 'np.swapaxes(points,', '0,', '2)', 'fig', '=', 'p.figure(figsize=(1,', '1),', 'dpi=vis_size)', '(verts,', 'faces)', '=', 'measure.marching_cubes_classic(points,', '0,', 'spacing=(0.1,', '0.1,', '0.1))', 'ax', ...
759,485
ViTAE-Transformer/ViTDet
test_mixins.py
MaskTestMixin.simple_test_mask
simple_test_mask
Simple test for mask head without augmentation.
[ "Simple", "test", "for", "mask", "head", "without", "augmentation." ]
def simple_test_mask(self, x, img_metas, det_bboxes, det_labels, rescale=False): ori_shapes = tuple((meta['ori_shape'] for meta in img_metas)) scale_factors = tuple((meta['scale_factor'] for meta in img_metas)) if isinstance(scale_factors[0], float): warnings.warn('Scale factor in img_metas should b...
['def', 'simple_test_mask(self,', 'x,', 'img_metas,', 'det_bboxes,', 'det_labels,', 'rescale=False):', 'ori_shapes', '=', "tuple((meta['ori_shape']", 'for', 'meta', 'in', 'img_metas))', 'scale_factors', '=', "tuple((meta['scale_factor']", 'for', 'meta', 'in', 'img_metas))', 'if', 'isinstance(scale_factors[0],', 'float)...
945,753
deephyper/deephyper
space.py
Space.transformed_bounds
transformed_bounds
The dimension bounds, in the warped space.
[ "The", "dimension", "bounds,", "in", "the", "warped", "space." ]
def transformed_bounds(self): b = [] for dim in self.dimensions: if dim.transformed_size == 1: b.append(dim.transformed_bounds) else: b.extend(dim.transformed_bounds) return b
['def', 'transformed_bounds(self):', 'b', '=', '[]', 'for', 'dim', 'in', 'self.dimensions:', 'if', 'dim.transformed_size', '==', '1:', 'b.append(dim.transformed_bounds)', 'else:', 'b.extend(dim.transformed_bounds)', 'return', 'b']
521,058
Megvii-BaseDetection/cvpods
transform.py
GridSampleTransform.apply_image
apply_image
Apply grid sampling on the image(s).
[ "Apply", "grid", "sampling", "on", "the", "image(s)." ]
def apply_image(self, img: np.ndarray, interp: str=None) -> np.ndarray: interp_method = interp if interp is not None else self.interp float_tensor = torch.nn.functional.grid_sample(to_float_tensor(img), torch.from_numpy(self.grid), mode=interp_method, padding_mode='border', align_corners=False) return to_nu...
['def', 'apply_image(self,', 'img:', 'np.ndarray,', 'interp:', 'str=None)', '->', 'np.ndarray:', 'interp_method', '=', 'interp', 'if', 'interp', 'is', 'not', 'None', 'else', 'self.interp', 'float_tensor', '=', 'torch.nn.functional.grid_sample(to_float_tensor(img),', 'torch.from_numpy(self.grid),', 'mode=interp_method,'...
510,885
clips/pattern
__init__.py
DatasheetColumn.map
map
Applies the given function to each value in the column.
[ "Applies", "the", "given", "function", "to", "each", "value", "in", "the", "column." ]
def map(self, function=lambda value: value): for (j, value) in enumerate(self): self[j] = function(value)
['def', 'map(self,', 'function=lambda', 'value:', 'value):', 'for', '(j,', 'value)', 'in', 'enumerate(self):', 'self[j]', '=', 'function(value)']
764,609
PaddlePaddle/PARL
train.py
Learner.run_remote_sample
run_remote_sample
Sample data from remote actor and update parameters of remote actor.
[ "Sample", "data", "from", "remote", "actor", "and", "update", "parameters", "of", "remote", "actor." ]
def run_remote_sample(self): remote_actor = Actor(self.config) cnt = 0 remote_actor.set_weights(self.cache_params) while True: batch = remote_actor.sample() self.sample_data_queue.put(batch) cnt += 1 if cnt % self.config['get_remote_metrics_interval'] == 0: me...
['def', 'run_remote_sample(self):', 'remote_actor', '=', 'Actor(self.config)', 'cnt', '=', '0', 'remote_actor.set_weights(self.cache_params)', 'while', 'True:', 'batch', '=', 'remote_actor.sample()', 'self.sample_data_queue.put(batch)', 'cnt', '+=', '1', 'if', 'cnt', '%', "self.config['get_remote_metrics_interval']", '...
277,801
PacktPublishing/OpenCV-Computer--Projects-with-Python
filters.py
BGRFuncFilter.apply
apply
Apply the filter with a BGR source/destination.
[ "Apply", "the", "filter", "with", "a", "BGR", "source/destination." ]
def apply(self, src, dst): (b, g, r) = cv2.split(src) utils.applyLookupArray(self._bLookupArray, b, b) utils.applyLookupArray(self._gLookupArray, g, g) utils.applyLookupArray(self._rLookupArray, r, r) cv2.merge([b, g, r], dst)
['def', 'apply(self,', 'src,', 'dst):', '(b,', 'g,', 'r)', '=', 'cv2.split(src)', 'utils.applyLookupArray(self._bLookupArray,', 'b,', 'b)', 'utils.applyLookupArray(self._gLookupArray,', 'g,', 'g)', 'utils.applyLookupArray(self._rLookupArray,', 'r,', 'r)', 'cv2.merge([b,', 'g,', 'r],', 'dst)']
756,950
aws/sagemaker-training-toolkit
files.py
s3_download
s3_download
Download a file from S3.
[ "Download", "a", "file", "from", "S3." ]
def s3_download(url, dst): url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme, got: %s in %s" % (url.scheme, url)) (bucket, key) = (url.netloc, url.path.lstrip('/')) region = os.environ.get('AWS_REGION', os.environ.get(params.REGION_NAME_ENV)) endpoint_u...
['def', 's3_download(url,', 'dst):', 'url', '=', 'parse.urlparse(url)', 'if', 'url.scheme', '!=', "'s3':", 'raise', 'ValueError("Expecting', "'s3'", 'scheme,', 'got:', '%s', 'in', '%s"', '%', '(url.scheme,', 'url))', '(bucket,', 'key)', '=', '(url.netloc,', "url.path.lstrip('/'))", 'region', '=', "os.environ.get('AWS_R...
845,037
PaddlePaddle/PARL
remote_class_serialization.py
load_remote_class
load_remote_class
load a class given related info dumped in the client.
[ "load", "a", "class", "given", "related", "info", "dumped", "in", "the", "client." ]
def load_remote_class(remote_class_info): (in_notebook, dumped_class_info) = cloudpickle.loads(remote_class_info) if in_notebook: cls = dumped_class_info else: (file_name, class_name, end_of_file, in_sys_path, client_sys_path) = dumped_class_info with open(file_name + '.py') as t_fil...
['def', 'load_remote_class(remote_class_info):', '(in_notebook,', 'dumped_class_info)', '=', 'cloudpickle.loads(remote_class_info)', 'if', 'in_notebook:', 'cls', '=', 'dumped_class_info', 'else:', '(file_name,', 'class_name,', 'end_of_file,', 'in_sys_path,', 'client_sys_path)', '=', 'dumped_class_info', 'with', 'open(f...
278,117
jariasf/GMVAE
utils.py
cluster_acc
cluster_acc
Computes the clustering accuracy metric.
[ "Computes", "the", "clustering", "accuracy", "metric." ]
def cluster_acc(logits, labels, no_components): cat_preds = tf.argmax(logits, axis=1) real_preds = tf.zeros(tf.shape(cat_preds)) for k in xrange(no_components): idx = tf.equal(cat_preds, k) lab = tf.boolean_mask(labels, idx) modes = tf.cond(tf.equal(tf.size(lab), 0), lambda : 0.0, la...
['def', 'cluster_acc(logits,', 'labels,', 'no_components):', 'cat_preds', '=', 'tf.argmax(logits,', 'axis=1)', 'real_preds', '=', 'tf.zeros(tf.shape(cat_preds))', 'for', 'k', 'in', 'xrange(no_components):', 'idx', '=', 'tf.equal(cat_preds,', 'k)', 'lab', '=', 'tf.boolean_mask(labels,', 'idx)', 'modes', '=', 'tf.cond(tf...
578,507
tianyolanda/derain_dehaze_objdetection
ssd_vgg_preprocessing.py
preprocess_for_eval
preprocess_for_eval
Preprocess an image for evaluation.
[ "Preprocess", "an", "image", "for", "evaluation." ]
def preprocess_for_eval(image, labels, bboxes, out_shape=EVAL_SIZE, data_format='NHWC', difficults=None, resize=Resize.WARP_RESIZE, scope='ssd_preprocessing_train'): with tf.name_scope(scope): if image.get_shape().ndims != 3: raise ValueError('Input must be of size [height, width, C>0]') ...
['def', 'preprocess_for_eval(image,', 'labels,', 'bboxes,', 'out_shape=EVAL_SIZE,', "data_format='NHWC',", 'difficults=None,', 'resize=Resize.WARP_RESIZE,', "scope='ssd_preprocessing_train'):", 'with', 'tf.name_scope(scope):', 'if', 'image.get_shape().ndims', '!=', '3:', 'raise', "ValueError('Input", 'must', 'be', 'of'...
538,312
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
policy.py
Policy.get_kl
get_kl
Calculate KL between one policy output and another.
[ "Calculate", "KL", "between", "one", "policy", "output", "and", "another." ]
def get_kl(self, my_logits, other_logits): kl = [] for (i, (act_dim, act_type)) in enumerate(self.env_spec.act_dims_and_types): sampling_dim = self.env_spec.sampling_dim(act_dim, act_type) single_my_logits = my_logits[i] single_other_logits = other_logits[i] if self.env_spec.is_d...
['def', 'get_kl(self,', 'my_logits,', 'other_logits):', 'kl', '=', '[]', 'for', '(i,', '(act_dim,', 'act_type))', 'in', 'enumerate(self.env_spec.act_dims_and_types):', 'sampling_dim', '=', 'self.env_spec.sampling_dim(act_dim,', 'act_type)', 'single_my_logits', '=', 'my_logits[i]', 'single_other_logits', '=', 'other_log...
58,841
thu-ml/tianshou
base.py
ReplayBuffer.reset
reset
Clear all the data in replay buffer and episode statistics.
[ "Clear", "all", "the", "data", "in", "replay", "buffer", "and", "episode", "statistics." ]
def reset(self, keep_statistics: bool=False) -> None: self.last_index = np.array([0]) self._index = self._size = 0 if not keep_statistics: (self._ep_rew, self._ep_len, self._ep_idx) = (0.0, 0, 0)
['def', 'reset(self,', 'keep_statistics:', 'bool=False)', '->', 'None:', 'self.last_index', '=', 'np.array([0])', 'self._index', '=', 'self._size', '=', '0', 'if', 'not', 'keep_statistics:', '(self._ep_rew,', 'self._ep_len,', 'self._ep_idx)', '=', '(0.0,', '0,', '0)']
355,207
rudranil723/mini-main
formsets.py
BaseFormSet.as_table
as_table
Return this formset rendered as HTML <tr>s -- excluding the <table></table>.
[ "Return", "this", "formset", "rendered", "as", "HTML", "<tr>s", "--", "excluding", "the", "<table></table>." ]
def as_table(self): forms = ' '.join((form.as_table() for form in self)) return mark_safe(str(self.management_form) + '\n' + forms)
['def', 'as_table(self):', 'forms', '=', "'", "'.join((form.as_table()", 'for', 'form', 'in', 'self))', 'return', 'mark_safe(str(self.management_form)', '+', "'\\n'", '+', 'forms)']
316,274
myothida/Supervised-Machine-Learning
varStore.py
_Encoding.get_gain
get_gain
Maximum possible byte gain from merging this into another characteristic.
[ "Maximum", "possible", "byte", "gain", "from", "merging", "this", "into", "another", "characteristic." ]
def get_gain(self): count = len(self.items) return max(0, self.overhead - count)
['def', 'get_gain(self):', 'count', '=', 'len(self.items)', 'return', 'max(0,', 'self.overhead', '-', 'count)']
361,367
vinayvinkumar/Natural-Language-Processing
api.py
SupervisedLoadFile.candidate_weighting
candidate_weighting
Extract features and classify candidates with default parameters.
[ "Extract", "features", "and", "classify", "candidates", "with", "default", "parameters." ]
def candidate_weighting(self): if not self.candidates: return self.feature_extraction() self.classify_candidates()
['def', 'candidate_weighting(self):', 'if', 'not', 'self.candidates:', 'return', 'self.feature_extraction()', 'self.classify_candidates()']
658,482
facebookresearch/CompilerGym
gcc_env_test.py
test_default_benchmark
test_default_benchmark
Test that we are working with the expected default benchmark.
[ "Test", "that", "we", "are", "working", "with", "the", "expected", "default", "benchmark." ]
def test_default_benchmark(gcc_bin: str): with gym.make('gcc-v0', gcc_bin=gcc_bin) as env: assert env.benchmark.proto.uri == 'benchmark://chstone-v0/adpcm'
['def', 'test_default_benchmark(gcc_bin:', 'str):', 'with', "gym.make('gcc-v0',", 'gcc_bin=gcc_bin)', 'as', 'env:', 'assert', 'env.benchmark.proto.uri', '==', "'benchmark://chstone-v0/adpcm'"]
125,888
Kvatsx/Artificial-Intelligence-Assignments
base.py
TabletCanvas.close
close
Close the tablet device for this window.
[ "Close", "the", "tablet", "device", "for", "this", "window." ]
def close(self): raise NotImplementedError('abstract')
['def', 'close(self):', 'raise', "NotImplementedError('abstract')"]
76,918
deepmind/pycolab
rendering.py
BaseObservationRenderer.shape
shape
The 2-D dimensions of this `BaseObservationRenderer`.
[ "The", "2-D", "dimensions", "of", "this", "`BaseObservationRenderer`." ]
def shape(self): return self._board.shape
['def', 'shape(self):', 'return', 'self._board.shape']
819,234
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_utils.py
maybe_download_data
maybe_download_data
Download Omniglot repo if it does not exist.
[ "Download", "Omniglot", "repo", "if", "it", "does", "not", "exist." ]
def maybe_download_data(): if os.path.exists(REPO_DIR): logging.info('It appears that Git repo already exists.') else: logging.info('It appears that Git repo does not exist.') logging.info('Cloning now.') subprocess.check_output('git clone %s' % REPO_LOCATION, shell=True) if ...
['def', 'maybe_download_data():', 'if', 'os.path.exists(REPO_DIR):', "logging.info('It", 'appears', 'that', 'Git', 'repo', 'already', "exists.')", 'else:', "logging.info('It", 'appears', 'that', 'Git', 'repo', 'does', 'not', "exist.')", "logging.info('Cloning", "now.')", "subprocess.check_output('git", 'clone', "%s'", ...
49,521
kemaloksuz/RankSortLoss
test_assigner.py
test_max_iou_assigner_with_empty_boxes
test_max_iou_assigner_with_empty_boxes
Test corner case where a network might predict no boxes.
[ "Test", "corner", "case", "where", "a", "network", "might", "predict", "no", "boxes." ]
def test_max_iou_assigner_with_empty_boxes(): self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5) bboxes = torch.empty((0, 4)) gt_bboxes = torch.FloatTensor([[0, 0, 10, 9], [0, 10, 10, 19]]) gt_labels = torch.LongTensor([2, 3]) assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels) ...
['def', 'test_max_iou_assigner_with_empty_boxes():', 'self', '=', 'MaxIoUAssigner(pos_iou_thr=0.5,', 'neg_iou_thr=0.5)', 'bboxes', '=', 'torch.empty((0,', '4))', 'gt_bboxes', '=', 'torch.FloatTensor([[0,', '0,', '10,', '9],', '[0,', '10,', '10,', '19]])', 'gt_labels', '=', 'torch.LongTensor([2,', '3])', 'assign_result'...
836,392
Cihsaing/RVSL-rvsl-robust-vehicle-similarity-learning--ECCV22
nvmarker.py
modMarker
modMarker
Returns the stringified extra_repr() of a module.
[ "Returns", "the", "stringified", "extra_repr()", "of", "a", "module." ]
def modMarker(mod, fn_name, args): assert fn_name == 'forward' assert len(args) > 0 d = {} d['mod'] = mod.__name__ d['strRepr'] = args[0].extra_repr() return str(d)
['def', 'modMarker(mod,', 'fn_name,', 'args):', 'assert', 'fn_name', '==', "'forward'", 'assert', 'len(args)', '>', '0', 'd', '=', '{}', "d['mod']", '=', 'mod.__name__', "d['strRepr']", '=', 'args[0].extra_repr()', 'return', 'str(d)']
327,108
devashish-patel/webcam-motion-detector
output.py
output_notebook
output_notebook
Configure the default output state to generate output in notebook cells when :func:`show` is called.
[ "Configure", "the", "default", "output", "state", "to", "generate", "output", "in", "notebook", "cells", "when", ":func:`show`", "is", "called." ]
def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout)
['def', 'output_notebook(resources=None,', 'verbose=False,', 'hide_banner=False,', 'load_timeout=5000,', "notebook_type='jupyter'):", 'curstate().output_notebook(notebook_type)', 'run_notebook_hook(notebook_type,', "'load',", 'resources,', 'verbose,', 'hide_banner,', 'load_timeout)']
977,359
JIA-HONG-CHU/Swin-Transformer-add-EncNet-DaNet-DraNet-for---on-Statelite-Dataset
cityscapes.py
CityscapesDataset.format_results
format_results
Format the results into dir (standard format for Cityscapes evaluation).
[ "Format", "the", "results", "into", "dir", "(standard", "format", "for", "Cityscapes", "evaluation)." ]
def format_results(self, results, imgfile_prefix=None, to_label_id=True): assert isinstance(results, list), 'results must be a list' assert len(results) == len(self), f'The length of results is not equal to the dataset len: {len(results)} != {len(self)}' if imgfile_prefix is None: tmp_dir = tempfile...
['def', 'format_results(self,', 'results,', 'imgfile_prefix=None,', 'to_label_id=True):', 'assert', 'isinstance(results,', 'list),', "'results", 'must', 'be', 'a', "list'", 'assert', 'len(results)', '==', 'len(self),', "f'The", 'length', 'of', 'results', 'is', 'not', 'equal', 'to', 'the', 'dataset', 'len:', '{len(resul...
882,841
70Shubham07/NaturalLanguageProcessing
run_classifier.py
DataProcessor.get_test_examples
get_test_examples
Gets a collection of `InputExample`s for prediction.
[ "Gets", "a", "collection", "of", "`InputExample`s", "for", "prediction." ]
def get_test_examples(self, data_dir): raise NotImplementedError()
['def', 'get_test_examples(self,', 'data_dir):', 'raise', 'NotImplementedError()']
713,794
KalleHallden/InstaAutomator
compat.py
splituser
splituser
splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.
[ "splituser('user[:passwd]@host[:port]')", "-->", "'user[:passwd]',", "'host[:port]'." ]
def splituser(host): global _userprog if _userprog is None: import re _userprog = re.compile('^(.*)@(.*)$') match = _userprog.match(host) if match: return match.group(1, 2) return (None, host)
['def', 'splituser(host):', 'global', '_userprog', 'if', '_userprog', 'is', 'None:', 'import', 're', '_userprog', '=', "re.compile('^(.*)@(.*)$')", 'match', '=', '_userprog.match(host)', 'if', 'match:', 'return', 'match.group(1,', '2)', 'return', '(None,', 'host)']
233,106
Eric3911/OpenAGI
data_pipeline.py
GeneratorDynamicItem.reset
reset
Signals that this will not be called any more times on this pipeline call.
[ "Signals", "that", "this", "will", "not", "be", "called", "any", "more", "times", "on", "this", "pipeline", "call." ]
def reset(self): if self.current_generator is not None: self.current_generator.close() self.current_generator = None self.num_provided_items = 0
['def', 'reset(self):', 'if', 'self.current_generator', 'is', 'not', 'None:', 'self.current_generator.close()', 'self.current_generator', '=', 'None', 'self.num_provided_items', '=', '0']
251,356
google-research/ssl_detection
scope_utils.py
cached_name_scope
cached_name_scope
Return a context which either opens and caches a new name scope, or reenter an existing one.
[ "Return", "a", "context", "which", "either", "opens", "and", "caches", "a", "new", "name", "scope,", "or", "reenter", "an", "existing", "one." ]
def cached_name_scope(name, top_level=True): if not top_level: current_ns = tf.get_default_graph().get_name_scope() if current_ns: name = current_ns + '/' + name ns = _get_cached_ns(name) with tf.name_scope(ns): yield ns
['def', 'cached_name_scope(name,', 'top_level=True):', 'if', 'not', 'top_level:', 'current_ns', '=', 'tf.get_default_graph().get_name_scope()', 'if', 'current_ns:', 'name', '=', 'current_ns', '+', "'/'", '+', 'name', 'ns', '=', '_get_cached_ns(name)', 'with', 'tf.name_scope(ns):', 'yield', 'ns']
382,282
jimtin/Stock_Comparison
core.py
_Socket.send
send
send, which will only block current greenlet state_changed always fires exactly once (success or fail) at the end of this method.
[ "send,", "which", "will", "only", "block", "current", "greenlet", "state_changed", "always", "fires", "exactly", "once", "(success", "or", "fail)", "at", "the", "end", "of", "this", "method." ]
def send(self, data, flags=0, copy=True, track=False): if flags & zmq.NOBLOCK: try: msg = super(_Socket, self).send(data, flags, copy, track) finally: if not self.__in_send_multipart: self.__state_changed() return msg flags |= zmq.NOBLOCK while...
['def', 'send(self,', 'data,', 'flags=0,', 'copy=True,', 'track=False):', 'if', 'flags', '&', 'zmq.NOBLOCK:', 'try:', 'msg', '=', 'super(_Socket,', 'self).send(data,', 'flags,', 'copy,', 'track)', 'finally:', 'if', 'not', 'self.__in_send_multipart:', 'self.__state_changed()', 'return', 'msg', 'flags', '|=', 'zmq.NOBLOC...
359,557
deepmind/acme
builder.py
R2D2Builder.make_adder
make_adder
Create an adder which records data generated by the actor/environment.
[ "Create", "an", "adder", "which", "records", "data", "generated", "by", "the", "actor/environment." ]
def make_adder(self, replay_client: reverb.Client, environment_spec: Optional[specs.EnvironmentSpec], policy: Optional[r2d2_actor.R2D2Policy]) -> Optional[adders.Adder]: if environment_spec is None or policy is None: raise ValueError('`environment_spec` and `policy` cannot be None.') dummy_actor_state =...
['def', 'make_adder(self,', 'replay_client:', 'reverb.Client,', 'environment_spec:', 'Optional[specs.EnvironmentSpec],', 'policy:', 'Optional[r2d2_actor.R2D2Policy])', '->', 'Optional[adders.Adder]:', 'if', 'environment_spec', 'is', 'None', 'or', 'policy', 'is', 'None:', 'raise', "ValueError('`environment_spec`", 'and'...
8,185
omarmhaimdat/twitter_nlp_native_swift
cookiejar.py
DefaultCookiePolicy.allowed_domains
allowed_domains
Return None, or the sequence of allowed domains (as a tuple).
[ "Return", "None,", "or", "the", "sequence", "of", "allowed", "domains", "(as", "a", "tuple)." ]
def allowed_domains(self): return self._allowed_domains
['def', 'allowed_domains(self):', 'return', 'self._allowed_domains']
953,490
VincentAuriau/Natural-Language-Processing
data.py
generate_batches
generate_batches
Generates and returns batch of tensorized instances in a chunk of batch_size.
[ "Generates", "and", "returns", "batch", "of", "tensorized", "instances", "in", "a", "chunk", "of", "batch_size." ]
def generate_batches(instances: List[Dict], batch_size) -> List[Dict[str, np.ndarray]]: def chunk(items: List[Any], num: int): return [items[index:index + num] for index in range(0, len(items), num)] batches_of_instances = chunk(instances, batch_size) batches = [] for batch_of_instances in tqdm...
['def', 'generate_batches(instances:', 'List[Dict],', 'batch_size)', '->', 'List[Dict[str,', 'np.ndarray]]:', 'def', 'chunk(items:', 'List[Any],', 'num:', 'int):', 'return', '[items[index:index', '+', 'num]', 'for', 'index', 'in', 'range(0,', 'len(items),', 'num)]', 'batches_of_instances', '=', 'chunk(instances,', 'bat...
685,386
TheCurryMan/MedicAI
core.py
MultiCommand.get_command
get_command
Given a context and a command name, this returns a :class:`Command` object if it exists or returns `None`.
[ "Given", "a", "context", "and", "a", "command", "name,", "this", "returns", "a", ":class:`Command`", "object", "if", "it", "exists", "or", "returns", "`None`." ]
def get_command(self, ctx, cmd_name): raise NotImplementedError()
['def', 'get_command(self,', 'ctx,', 'cmd_name):', 'raise', 'NotImplementedError()']
648,052
clovaai/assembled-cnn
logger.py
config_benchmark_logger
config_benchmark_logger
Config the global benchmark logger.
[ "Config", "the", "global", "benchmark", "logger." ]
def config_benchmark_logger(flag_obj=None): _logger_lock.acquire() try: global _benchmark_logger if not flag_obj: flag_obj = FLAGS if not hasattr(flag_obj, 'benchmark_logger_type') or flag_obj.benchmark_logger_type == 'BaseBenchmarkLogger': _benchmark_logger = Bas...
['def', 'config_benchmark_logger(flag_obj=None):', '_logger_lock.acquire()', 'try:', 'global', '_benchmark_logger', 'if', 'not', 'flag_obj:', 'flag_obj', '=', 'FLAGS', 'if', 'not', 'hasattr(flag_obj,', "'benchmark_logger_type')", 'or', 'flag_obj.benchmark_logger_type', '==', "'BaseBenchmarkLogger':", '_benchmark_logger...
92,452
Katja-M/Python_NaturalLanguageProcessing
text.py
ConcordanceIndex.find_concordance
find_concordance
Find all concordance lines given the query word.
[ "Find", "all", "concordance", "lines", "given", "the", "query", "word." ]
def find_concordance(self, word, width=80): half_width = (width - len(word) - 2) // 2 context = width // 4 concordance_list = [] offsets = self.offsets(word) if offsets: for i in offsets: query_word = self._tokens[i] left_context = self._tokens[max(0, i - context):i] ...
['def', 'find_concordance(self,', 'word,', 'width=80):', 'half_width', '=', '(width', '-', 'len(word)', '-', '2)', '//', '2', 'context', '=', 'width', '//', '4', 'concordance_list', '=', '[]', 'offsets', '=', 'self.offsets(word)', 'if', 'offsets:', 'for', 'i', 'in', 'offsets:', 'query_word', '=', 'self._tokens[i]', 'le...
865,878
sek788432/Waymo-2D-Object-Detection
autoaugment_utils.py
rotate
rotate
Rotates the image by degrees either clockwise or counterclockwise.
[ "Rotates", "the", "image", "by", "degrees", "either", "clockwise", "or", "counterclockwise." ]
def rotate(image, degrees, replace): degrees_to_radians = math.pi / 180.0 radians = degrees * degrees_to_radians image = contrib_image.rotate(wrap(image), radians) return unwrap(image, replace)
['def', 'rotate(image,', 'degrees,', 'replace):', 'degrees_to_radians', '=', 'math.pi', '/', '180.0', 'radians', '=', 'degrees', '*', 'degrees_to_radians', 'image', '=', 'contrib_image.rotate(wrap(image),', 'radians)', 'return', 'unwrap(image,', 'replace)']
975,333
googleapis/python-aiplatform
client.py
ModelServiceClient.parse_common_billing_account_path
parse_common_billing_account_path
Parse a billing_account path into its component segments.
[ "Parse", "a", "billing_account", "path", "into", "its", "component", "segments." ]
def parse_common_billing_account_path(path: str) -> Dict[str, str]: m = re.match('^billingAccounts/(?P<billing_account>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_common_billing_account_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^billingAccounts/(?P<billing_account>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
813,600
bm777/object_detection
oid_od_challenge_evaluation_utils.py
build_predictions_dictionary
build_predictions_dictionary
Builds a predictions dictionary from predictions data in CSV file.
[ "Builds", "a", "predictions", "dictionary", "from", "predictions", "data", "in", "CSV", "file." ]
def build_predictions_dictionary(data, class_label_map): return {standard_fields.DetectionResultFields.detection_boxes: data[['YMin', 'XMin', 'YMax', 'XMax']].as_matrix(), standard_fields.DetectionResultFields.detection_classes: data['LabelName'].map(lambda x: class_label_map[x]).as_matrix(), standard_fields.Detect...
['def', 'build_predictions_dictionary(data,', 'class_label_map):', 'return', '{standard_fields.DetectionResultFields.detection_boxes:', "data[['YMin',", "'XMin',", "'YMax',", "'XMax']].as_matrix(),", 'standard_fields.DetectionResultFields.detection_classes:', "data['LabelName'].map(lambda", 'x:', 'class_label_map[x]).a...
774,432
implus/GFocalV2
dynamic_roi_head.py
DynamicRoIHead.forward_train
forward_train
Forward function for training.
[ "Forward", "function", "for", "training." ]
def forward_train(self, x, img_metas, proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None): if self.with_bbox or self.with_mask: num_imgs = len(img_metas) if gt_bboxes_ignore is None: gt_bboxes_ignore = [None for _ in range(num_imgs)] sampling_results = [] ...
['def', 'forward_train(self,', 'x,', 'img_metas,', 'proposal_list,', 'gt_bboxes,', 'gt_labels,', 'gt_bboxes_ignore=None,', 'gt_masks=None):', 'if', 'self.with_bbox', 'or', 'self.with_mask:', 'num_imgs', '=', 'len(img_metas)', 'if', 'gt_bboxes_ignore', 'is', 'None:', 'gt_bboxes_ignore', '=', '[None', 'for', '_', 'in', '...
557,734
Abtinz/Artificial-Intelligence
utils.py
remove_all
remove_all
Return a copy of seq (or string) with all occurrences of item removed.
[ "Return", "a", "copy", "of", "seq", "(or", "string)", "with", "all", "occurrences", "of", "item", "removed." ]
def remove_all(item, seq): if isinstance(seq, str): return seq.replace(item, '') elif isinstance(seq, set): rest = seq.copy() rest.remove(item) return rest else: return [x for x in seq if x != item]
['def', 'remove_all(item,', 'seq):', 'if', 'isinstance(seq,', 'str):', 'return', 'seq.replace(item,', "'')", 'elif', 'isinstance(seq,', 'set):', 'rest', '=', 'seq.copy()', 'rest.remove(item)', 'return', 'rest', 'else:', 'return', '[x', 'for', 'x', 'in', 'seq', 'if', 'x', '!=', 'item]']
121,890
janluke/cs188
search.py
solution
solution
Returns a list of actions, following parent pointers.
[ "Returns", "a", "list", "of", "actions,", "following", "parent", "pointers." ]
def solution(node): if node.parent == None: return [] ls = solution(node.parent) ls.extend([node.action]) return ls
['def', 'solution(node):', 'if', 'node.parent', '==', 'None:', 'return', '[]', 'ls', '=', 'solution(node.parent)', 'ls.extend([node.action])', 'return', 'ls']
224,446
PJLab-ADG/LoGoNet
yolact_head.py
InterpolateModule.forward
forward
Forward features from the upstream network.
[ "Forward", "features", "from", "the", "upstream", "network." ]
def forward(self, x): return F.interpolate(x, *self.args, **self.kwargs)
['def', 'forward(self,', 'x):', 'return', 'F.interpolate(x,', '*self.args,', '**self.kwargs)']
615,279
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_inputsplitter.py
assemble
assemble
Assemble a block into multi-line sub-blocks.
[ "Assemble", "a", "block", "into", "multi-line", "sub-blocks." ]
def assemble(block): return ['\n'.join(sub_block) + '\n' for sub_block in block]
['def', 'assemble(block):', 'return', "['\\n'.join(sub_block)", '+', "'\\n'", 'for', 'sub_block', 'in', 'block]']
448,503
myothida/Supervised-Machine-Learning
misc.py
build_url_from_netloc
build_url_from_netloc
Build a full URL from a netloc.
[ "Build", "a", "full", "URL", "from", "a", "netloc." ]
def build_url_from_netloc(netloc: str, scheme: str='https') -> str: if netloc.count(':') >= 2 and '@' not in netloc and ('[' not in netloc): netloc = f'[{netloc}]' return f'{scheme}://{netloc}'
['def', 'build_url_from_netloc(netloc:', 'str,', 'scheme:', "str='https')", '->', 'str:', 'if', "netloc.count(':')", '>=', '2', 'and', "'@'", 'not', 'in', 'netloc', 'and', "('['", 'not', 'in', 'netloc):', 'netloc', '=', "f'[{netloc}]'", 'return', "f'{scheme}://{netloc}'"]
444,294
ADLab3Ds/TiG-BEV
utils.py
rotation_3d_in_axis
rotation_3d_in_axis
Rotate points by angles according to axis.
[ "Rotate", "points", "by", "angles", "according", "to", "axis." ]
def rotation_3d_in_axis(points, angles, axis=0): rot_sin = torch.sin(angles) rot_cos = torch.cos(angles) ones = torch.ones_like(rot_cos) zeros = torch.zeros_like(rot_cos) if axis == 1: rot_mat_T = torch.stack([torch.stack([rot_cos, zeros, -rot_sin]), torch.stack([zeros, ones, zeros]), torch....
['def', 'rotation_3d_in_axis(points,', 'angles,', 'axis=0):', 'rot_sin', '=', 'torch.sin(angles)', 'rot_cos', '=', 'torch.cos(angles)', 'ones', '=', 'torch.ones_like(rot_cos)', 'zeros', '=', 'torch.zeros_like(rot_cos)', 'if', 'axis', '==', '1:', 'rot_mat_T', '=', 'torch.stack([torch.stack([rot_cos,', 'zeros,', '-rot_si...
916,791
tobegit3hub/deep_image_model
factorization_ops.py
WALSModel.initialize_col_update_op
initialize_col_update_op
Op to initialize worker state before starting column updates.
[ "Op", "to", "initialize", "worker", "state", "before", "starting", "column", "updates." ]
def initialize_col_update_op(self): return self._col_updates_init
['def', 'initialize_col_update_op(self):', 'return', 'self._col_updates_init']
181,259
openai/gym
test_mujoco.py
test_mujoco_incompatible_v3_to_v2
test_mujoco_incompatible_v3_to_v2
Checks that the v3 environment are slightly different from v2, (v3 has additional info keys that v2 does not).
[ "Checks", "that", "the", "v3", "environment", "are", "slightly", "different", "from", "v2,", "(v3", "has", "additional", "info", "keys", "that", "v2", "does", "not)." ]
def test_mujoco_incompatible_v3_to_v2(env_name: str): with pytest.raises(KeyError): verify_environments_match(f'{env_name}-v3', f'{env_name}-v2')
['def', 'test_mujoco_incompatible_v3_to_v2(env_name:', 'str):', 'with', 'pytest.raises(KeyError):', "verify_environments_match(f'{env_name}-v3',", "f'{env_name}-v2')"]
234,365
chrischoy/3D-R2N2
read_mesh.py
generate_materials
generate_materials
Generate JS array of materials objects JS material objects are basically prettified one-to-one mappings of MTL properties in JSON format.
[ "Generate", "JS", "array", "of", "materials", "objects", "JS", "material", "objects", "are", "basically", "prettified", "one-to-one", "mappings", "of", "MTL", "properties", "in", "JSON", "format." ]
def generate_materials(mtl, materials): mtl_array = [] for m in mtl: if m in materials: index = materials[m] mtl[m]['DbgName'] = m mtl[m]['DbgIndex'] = index mtl[m]['DbgColor'] = generate_color(index) if BAKE_COLORS: mtl[m]['ver...
['def', 'generate_materials(mtl,', 'materials):', 'mtl_array', '=', '[]', 'for', 'm', 'in', 'mtl:', 'if', 'm', 'in', 'materials:', 'index', '=', 'materials[m]', "mtl[m]['DbgName']", '=', 'm', "mtl[m]['DbgIndex']", '=', 'index', "mtl[m]['DbgColor']", '=', 'generate_color(index)', 'if', 'BAKE_COLORS:', "mtl[m]['vertexCol...
4,515
muhanzhang/D-VAE
conv.py
gen_conv_code_unroll_batch_kern
gen_conv_code_unroll_batch_kern
c_code for ConvOp that unroll the batch size loop.
[ "c_code", "for", "ConvOp", "that", "unroll", "the", "batch", "size", "loop." ]
def gen_conv_code_unroll_batch_kern(d, unroll_bsize=1, unroll_ksize=1): assert unroll_bsize > 0 and unroll_ksize > 0 if 'unroll_bsize' in d or 'unroll_ksize' in d or 'unroll_iter' in d or ('unroll_biter' in d) or ('unroll_kiter' in d): raise Exception("We can't use this dictionnary as we will overwrite ...
['def', 'gen_conv_code_unroll_batch_kern(d,', 'unroll_bsize=1,', 'unroll_ksize=1):', 'assert', 'unroll_bsize', '>', '0', 'and', 'unroll_ksize', '>', '0', 'if', "'unroll_bsize'", 'in', 'd', 'or', "'unroll_ksize'", 'in', 'd', 'or', "'unroll_iter'", 'in', 'd', 'or', "('unroll_biter'", 'in', 'd)', 'or', "('unroll_kiter'", ...
525,679
chenbinghui1/DSL
test_ga_anchor_head.py
test_ga_anchor_head_loss
test_ga_anchor_head_loss
Tests anchor head loss when truth is empty and non-empty.
[ "Tests", "anchor", "head", "loss", "when", "truth", "is", "empty", "and", "non-empty." ]
def test_ga_anchor_head_loss(): s = 256 img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}] cfg = mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1), sampler=dict(type='RandomSample...
['def', 'test_ga_anchor_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'cfg', '=', "mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner',", 'pos_iou_thr=0.7,', 'neg_iou_thr=0.3,', 'min_pos_iou=0.3,', 'match_low_qualit...
167,998
flow-project/flow
util.py
makexml
makexml
Create an xml file.
[ "Create", "an", "xml", "file." ]
def makexml(name, nsl): xsi = 'http://www.w3.org/2001/XMLSchema-instance' ns = {'xsi': xsi} attr = {'{%s}noNamespaceSchemaLocation' % xsi: nsl} t = etree.Element(name, attrib=attr, nsmap=ns) return t
['def', 'makexml(name,', 'nsl):', 'xsi', '=', "'http://www.w3.org/2001/XMLSchema-instance'", 'ns', '=', "{'xsi':", 'xsi}', 'attr', '=', "{'{%s}noNamespaceSchemaLocation'", '%', 'xsi:', 'nsl}', 't', '=', 'etree.Element(name,', 'attrib=attr,', 'nsmap=ns)', 'return', 't']
211,566
zzndream/ShipRSImageNet
pytorch2onnx.py
preprocess_example_input
preprocess_example_input
Prepare an example input image for ``generate_inputs_and_wrap_model``.
[ "Prepare", "an", "example", "input", "image", "for", "``generate_inputs_and_wrap_model``." ]
def preprocess_example_input(input_config): input_path = input_config['input_path'] input_shape = input_config['input_shape'] one_img = mmcv.imread(input_path) one_img = mmcv.imresize(one_img, input_shape[2:][::-1]) show_img = one_img.copy() if 'normalize_cfg' in input_config.keys(): nor...
['def', 'preprocess_example_input(input_config):', 'input_path', '=', "input_config['input_path']", 'input_shape', '=', "input_config['input_shape']", 'one_img', '=', 'mmcv.imread(input_path)', 'one_img', '=', 'mmcv.imresize(one_img,', 'input_shape[2:][::-1])', 'show_img', '=', 'one_img.copy()', 'if', "'normalize_cfg'"...
901,189
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
configHandler.py
IdleConf.CreateConfigHandlers
CreateConfigHandlers
Populate default and user config parser dictionaries.
[ "Populate", "default", "and", "user", "config", "parser", "dictionaries." ]
def CreateConfigHandlers(self): if __name__ != '__main__': idleDir = os.path.dirname(__file__) else: idleDir = os.path.abspath(sys.path[0]) userDir = self.GetUserCfgDir() defCfgFiles = {} usrCfgFiles = {} for cfgType in self.config_types: defCfgFiles[cfgType] = os.path.jo...
['def', 'CreateConfigHandlers(self):', 'if', '__name__', '!=', "'__main__':", 'idleDir', '=', 'os.path.dirname(__file__)', 'else:', 'idleDir', '=', 'os.path.abspath(sys.path[0])', 'userDir', '=', 'self.GetUserCfgDir()', 'defCfgFiles', '=', '{}', 'usrCfgFiles', '=', '{}', 'for', 'cfgType', 'in', 'self.config_types:', 'd...
430,799
43Carrig/recurrent_neural_networks_practice
gen_prediction_ops.py
gradient_trees_prediction_verbose
gradient_trees_prediction_verbose
Runs multiple additive regression forests predictors on input instances and computes the final prediction for each class, and outputs a matrix of leaf ids per each tree in an ensemble.
[ "Runs", "multiple", "additive", "regression", "forests", "predictors", "on", "input", "instances", "and", "computes", "the", "final", "prediction", "for", "each", "class,", "and", "outputs", "a", "matrix", "of", "leaf", "ids", "per", "each", "tree", "in", "an"...
def gradient_trees_prediction_verbose(tree_ensemble_handle, seed, dense_float_features, sparse_float_feature_indices, sparse_float_feature_values, sparse_float_feature_shapes, sparse_int_feature_indices, sparse_int_feature_values, sparse_int_feature_shapes, learner_config, apply_dropout, apply_averaging, center_bias, r...
['def', 'gradient_trees_prediction_verbose(tree_ensemble_handle,', 'seed,', 'dense_float_features,', 'sparse_float_feature_indices,', 'sparse_float_feature_values,', 'sparse_float_feature_shapes,', 'sparse_int_feature_indices,', 'sparse_int_feature_values,', 'sparse_int_feature_shapes,', 'learner_config,', 'apply_dropo...
312,507
End of preview. Expand in Data Studio

GitHub Python Dataset

Dataset Description

  • project_name: [Project Name]
  • file_name: [File name]
  • func_name: [Function Name]
  • docstring: [Notes or Description]
  • code: [source code]

BibTeX:

[More Information Needed]

APA:

[More Information Needed]

Downloads last month
2