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
aalgirdas/Artificial-Intelligence-Course
games.py
TicTacToe.compute_utility
compute_utility
If 'X' wins with this move, return 1; if 'O' wins return -1; else return 0.
[ "If", "'X'", "wins", "with", "this", "move,", "return", "1;", "if", "'O'", "wins", "return", "-1;", "else", "return", "0." ]
def compute_utility(self, board, move, player): if self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1)): return +1 if player == 'X' else -1 else: return 0
['def', 'compute_utility(self,', 'board,', 'move,', 'player):', 'if', 'self.k_in_row(board,', 'move,', 'player,', '(0,', '1))', 'or', 'self.k_in_row(board,', 'move,', 'player,', '(1,', '0))', 'or', 'self.k_in_row(board,', 'move,', 'player,', '(1,', '-1))', 'or', 'self.k_in_row(board,', 'move,', 'player,', '(1,', '1)):'...
79,651
TonyLianLong/VAI-ReinforcementLearning
schema.py
collect_namespaces
collect_namespaces
Constructs a set of namespaces in a given ElementSpec.
[ "Constructs", "a", "set", "of", "namespaces", "in", "a", "given", "ElementSpec." ]
def collect_namespaces(root_spec): findable_namespaces = set() def update_namespaces_from_spec(spec): findable_namespaces.add(spec.namespace) for child_spec in six.itervalues(spec.children): if child_spec is not spec: update_namespaces_from_spec(child_spec) updat...
['def', 'collect_namespaces(root_spec):', 'findable_namespaces', '=', 'set()', 'def', 'update_namespaces_from_spec(spec):', 'findable_namespaces.add(spec.namespace)', 'for', 'child_spec', 'in', 'six.itervalues(spec.children):', 'if', 'child_spec', 'is', 'not', 'spec:', 'update_namespaces_from_spec(child_spec)', 'update...
440,044
43Carrig/recurrent_neural_networks_practice
json_format.py
MessageToJson
MessageToJson
Converts protobuf message to JSON format.
[ "Converts", "protobuf", "message", "to", "JSON", "format." ]
def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False, indent=2, sort_keys=False, use_integers_for_enums=False): printer = _Printer(including_default_value_fields, preserving_proto_field_name, use_integers_for_enums) return printer.ToJsonString(message, indent, sort_...
['def', 'MessageToJson(message,', 'including_default_value_fields=False,', 'preserving_proto_field_name=False,', 'indent=2,', 'sort_keys=False,', 'use_integers_for_enums=False):', 'printer', '=', '_Printer(including_default_value_fields,', 'preserving_proto_field_name,', 'use_integers_for_enums)', 'return', 'printer.To...
309,823
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_utils.py
summarize_model
summarize_model
Summarizes the given model via its end_points.
[ "Summarizes", "the", "given", "model", "via", "its", "end_points." ]
def summarize_model(end_points): tf.summary.histogram('domain_logits_transferred', tf.sigmoid(end_points['transferred_domain_logits'])) tf.summary.histogram('domain_logits_target', tf.sigmoid(end_points['target_domain_logits']))
['def', 'summarize_model(end_points):', "tf.summary.histogram('domain_logits_transferred',", "tf.sigmoid(end_points['transferred_domain_logits']))", "tf.summary.histogram('domain_logits_target',", "tf.sigmoid(end_points['target_domain_logits']))"]
48,308
instadeepai/jumanji
utils.py
CanMoveCarry.origin
origin
Tile at origin index of row.
[ "Tile", "at", "origin", "index", "of", "row." ]
def origin(self) -> chex.Numeric: return self.row[self.origin_idx]
['def', 'origin(self)', '->', 'chex.Numeric:', 'return', 'self.row[self.origin_idx]']
594,025
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
preprocessing.py
pad
pad
Returns an image padded to be square.
[ "Returns", "an", "image", "padded", "to", "be", "square." ]
def pad(image): shape = tf.shape(image) new_shape = tf.maximum(shape[0], shape[1]) height = shape[0] width = shape[1] offset_x = tf.maximum(height - width, 0) // 2 offset_y = tf.maximum(width - height, 0) // 2 image = tf.image.pad_to_bounding_box(image, offset_y, offset_x, new_shape, new_sha...
['def', 'pad(image):', 'shape', '=', 'tf.shape(image)', 'new_shape', '=', 'tf.maximum(shape[0],', 'shape[1])', 'height', '=', 'shape[0]', 'width', '=', 'shape[1]', 'offset_x', '=', 'tf.maximum(height', '-', 'width,', '0)', '//', '2', 'offset_y', '=', 'tf.maximum(width', '-', 'height,', '0)', '//', '2', 'image', '=', 't...
29,493
titu1994/keras-attention-augmented-convs
attn_augconv.py
augmented_conv2d
augmented_conv2d
Builds an Attention Augmented Convolution block.
[ "Builds", "an", "Attention", "Augmented", "Convolution", "block." ]
def augmented_conv2d(ip, filters, kernel_size=(3, 3), strides=(1, 1), depth_k=0.2, depth_v=0.2, num_heads=8, relative_encodings=True): channel_axis = 1 if K.image_data_format() == 'channels_first' else -1 (depth_k, depth_v) = _normalize_depth_vars(depth_k, depth_v, filters) conv_out = _conv_layer(filters - ...
['def', 'augmented_conv2d(ip,', 'filters,', 'kernel_size=(3,', '3),', 'strides=(1,', '1),', 'depth_k=0.2,', 'depth_v=0.2,', 'num_heads=8,', 'relative_encodings=True):', 'channel_axis', '=', '1', 'if', 'K.image_data_format()', '==', "'channels_first'", 'else', '-1', '(depth_k,', 'depth_v)', '=', '_normalize_depth_vars(d...
247,674
instadeepai/jumanji
specs_test.py
singly_nested_spec
singly_nested_spec
An example of a singly nested Jumanji spec.
[ "An", "example", "of", "a", "singly", "nested", "Jumanji", "spec." ]
def singly_nested_spec() -> specs.Spec: return specs.Spec(SinglyNested, 'SinglyNestedSpec', array=specs.Array((3, 1), jnp.int32), bounded_array=specs.BoundedArray((5, 5), jnp.int32, 0, 3), multi_discrete_array=specs.MultiDiscreteArray(jnp.array([4, 5]), jnp.int32))
['def', 'singly_nested_spec()', '->', 'specs.Spec:', 'return', 'specs.Spec(SinglyNested,', "'SinglyNestedSpec',", 'array=specs.Array((3,', '1),', 'jnp.int32),', 'bounded_array=specs.BoundedArray((5,', '5),', 'jnp.int32,', '0,', '3),', 'multi_discrete_array=specs.MultiDiscreteArray(jnp.array([4,', '5]),', 'jnp.int32))']
593,856
rudranil723/mini-main
cmd.py
Command.copy_tree
copy_tree
Copy an entire directory tree respecting verbose, dry-run, and force flags.
[ "Copy", "an", "entire", "directory", "tree", "respecting", "verbose,", "dry-run,", "and", "force", "flags." ]
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1): return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, not self.force, dry_run=self.dry_run)
['def', 'copy_tree(self,', 'infile,', 'outfile,', 'preserve_mode=1,', 'preserve_times=1,', 'preserve_symlinks=0,', 'level=1):', 'return', 'dir_util.copy_tree(infile,', 'outfile,', 'preserve_mode,', 'preserve_times,', 'preserve_symlinks,', 'not', 'self.force,', 'dry_run=self.dry_run)']
270,212
RonMen10/Artificial-decision-making-of-autonomous-vehicles-AI
analytics.py
calculate_statistics
calculate_statistics
Return a dataframe with all the data used for analysis Data frame includes the following data: 'Parameters of the Run', 'Number of States learned', 'Average Best Fitness', 'Cumulated Waiting Time', 'Cumulated Crashes', 'Success Rate', 'number of simulation steps', 'Distances to solution list'.
[ "Return", "a", "dataframe", "with", "all", "the", "data", "used", "for", "analysis", "Data", "frame", "includes", "the", "following", "data:", "'Parameters", "of", "the", "Run',", "'Number", "of", "States", "learned',", "'Average", "Best", "Fitness',", "'Cumulat...
def calculate_statistics(archive, cumulated_crashes, cumulated_time, risk_tol, threshold_tol, hv_tol, sigma, attempts, steps, selected_seed, distance_to_solution): archive_df = pd.DataFrame(archive) number_states = len(archive_df.groupby(['hypervolume', 'first_risk']).size()) temp_df = archive_df.loc[:, ['h...
['def', 'calculate_statistics(archive,', 'cumulated_crashes,', 'cumulated_time,', 'risk_tol,', 'threshold_tol,', 'hv_tol,', 'sigma,', 'attempts,', 'steps,', 'selected_seed,', 'distance_to_solution):', 'archive_df', '=', 'pd.DataFrame(archive)', 'number_states', '=', "len(archive_df.groupby(['hypervolume',", "'first_ris...
34,718
rudranil723/mini-main
weka.py
ARFF_Formatter.header_section
header_section
Returns an ARFF header as a string.
[ "Returns", "an", "ARFF", "header", "as", "a", "string." ]
def header_section(self): s = '% Weka ARFF file\n' + '% Generated automatically by NLTK\n' + '%% %s\n\n' % time.ctime() s += '@RELATION rel\n\n' for (fname, ftype) in self._features: s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype) s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels)...
['def', 'header_section(self):', 's', '=', "'%", 'Weka', 'ARFF', "file\\n'", '+', "'%", 'Generated', 'automatically', 'by', "NLTK\\n'", '+', "'%%", "%s\\n\\n'", '%', 'time.ctime()', 's', '+=', "'@RELATION", "rel\\n\\n'", 'for', '(fname,', 'ftype)', 'in', 'self._features:', 's', '+=', "'@ATTRIBUTE", '%-30r', "%s\\n'", '...
320,880
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_optparse.py
BaseTest.assertTypeError
assertTypeError
Assert that TypeError is raised when executing func.
[ "Assert", "that", "TypeError", "is", "raised", "when", "executing", "func." ]
def assertTypeError(self, func, expected_message, *args): self.assertRaises(func, args, None, TypeError, expected_message)
['def', 'assertTypeError(self,', 'func,', 'expected_message,', '*args):', 'self.assertRaises(func,', 'args,', 'None,', 'TypeError,', 'expected_message)']
376,251
weimin17/Object-Detection_HelmetDetection
nav_env.py
NavigationEnv.get_targets_name
get_targets_name
Returns the list of names of the targets.
[ "Returns", "the", "list", "of", "names", "of", "the", "targets." ]
def get_targets_name(self): return ['action']
['def', 'get_targets_name(self):', 'return', "['action']"]
762,036
googleapis/python-aiplatform
client.py
PipelineServiceClient.parse_artifact_path
parse_artifact_path
Parses a artifact path into its component segments.
[ "Parses", "a", "artifact", "path", "into", "its", "component", "segments." ]
def parse_artifact_path(path: str) -> Dict[str, str]: m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/metadataStores/(?P<metadata_store>.+?)/artifacts/(?P<artifact>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_artifact_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/metadataStores/(?P<metadata_store>.+?)/artifacts/(?P<artifact>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
813,784
myothida/Supervised-Machine-Learning
_in_process.py
prepare_metadata_for_build_editable
prepare_metadata_for_build_editable
Invoke optional prepare_metadata_for_build_editable Implements a fallback by building an editable wheel if the hook isn't defined, unless _allow_fallback is False in which case HookMissing is raised.
[ "Invoke", "optional", "prepare_metadata_for_build_editable", "Implements", "a", "fallback", "by", "building", "an", "editable", "wheel", "if", "the", "hook", "isn't", "defined,", "unless", "_allow_fallback", "is", "False", "in", "which", "case", "HookMissing", "is", ...
def prepare_metadata_for_build_editable(metadata_directory, config_settings, _allow_fallback): backend = _build_backend() try: hook = backend.prepare_metadata_for_build_editable except AttributeError: if not _allow_fallback: raise HookMissing() try: build_hook...
['def', 'prepare_metadata_for_build_editable(metadata_directory,', 'config_settings,', '_allow_fallback):', 'backend', '=', '_build_backend()', 'try:', 'hook', '=', 'backend.prepare_metadata_for_build_editable', 'except', 'AttributeError:', 'if', 'not', '_allow_fallback:', 'raise', 'HookMissing()', 'try:', 'build_hook'...
444,878
DerrickXuNu/CoBEVT
base_camera_dataset.py
BaseCameraDataset.get_sample
get_sample
Get data sample from scenario index and timestamp index directly.
[ "Get", "data", "sample", "from", "scenario", "index", "and", "timestamp", "index", "directly." ]
def get_sample(self, scenario_idx, timestamp_index): base_data_dict = self.retrieve_base_data((scenario_idx, timestamp_index), True) return self.get_data_sample(base_data_dict)
['def', 'get_sample(self,', 'scenario_idx,', 'timestamp_index):', 'base_data_dict', '=', 'self.retrieve_base_data((scenario_idx,', 'timestamp_index),', 'True)', 'return', 'self.get_data_sample(base_data_dict)']
492,349
keyonvafa/career-code
transformer_pg.py
TransformerPointerGeneratorDecoder.output_layer
output_layer
Project features to the vocabulary size and mix with the attention distributions.
[ "Project", "features", "to", "the", "vocabulary", "size", "and", "mix", "with", "the", "attention", "distributions." ]
def output_layer(self, features: Tensor, attn: Tensor, src_tokens: Tensor, p_gens: Tensor) -> Tensor: if self.force_p_gen is not None: p_gens = self.force_p_gen if self.adaptive_softmax is None: logits = self.output_projection(features) else: logits = features batch_size = logits...
['def', 'output_layer(self,', 'features:', 'Tensor,', 'attn:', 'Tensor,', 'src_tokens:', 'Tensor,', 'p_gens:', 'Tensor)', '->', 'Tensor:', 'if', 'self.force_p_gen', 'is', 'not', 'None:', 'p_gens', '=', 'self.force_p_gen', 'if', 'self.adaptive_softmax', 'is', 'None:', 'logits', '=', 'self.output_projection(features)', '...
454,924
matsu0228/nlp-jp
animation.py
MovieWriterRegistry.set_dirty
set_dirty
Sets a flag to re-setup the writers.
[ "Sets", "a", "flag", "to", "re-setup", "the", "writers." ]
def set_dirty(self): self._dirty = True
['def', 'set_dirty(self):', 'self._dirty', '=', 'True']
788,240
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
ccompiler.py
CCompiler.runtime_library_dir_option
runtime_library_dir_option
Return the compiler option to add 'dir' to the list of directories searched for runtime libraries.
[ "Return", "the", "compiler", "option", "to", "add", "'dir'", "to", "the", "list", "of", "directories", "searched", "for", "runtime", "libraries." ]
def runtime_library_dir_option(self, dir): raise NotImplementedError
['def', 'runtime_library_dir_option(self,', 'dir):', 'raise', 'NotImplementedError']
430,271
myothida/Supervised-Machine-Learning
test_lof.py
test_lof_input_dtype_preservation
test_lof_input_dtype_preservation
Check that the fitted attributes are stored using the data type of X.
[ "Check", "that", "the", "fitted", "attributes", "are", "stored", "using", "the", "data", "type", "of", "X." ]
def test_lof_input_dtype_preservation(global_dtype, algorithm, contamination, novelty): X = iris.data.astype(global_dtype, copy=False) iso = neighbors.LocalOutlierFactor(n_neighbors=5, algorithm=algorithm, contamination=contamination, novelty=novelty) iso.fit(X) assert iso.negative_outlier_factor_.dtype...
['def', 'test_lof_input_dtype_preservation(global_dtype,', 'algorithm,', 'contamination,', 'novelty):', 'X', '=', 'iris.data.astype(global_dtype,', 'copy=False)', 'iso', '=', 'neighbors.LocalOutlierFactor(n_neighbors=5,', 'algorithm=algorithm,', 'contamination=contamination,', 'novelty=novelty)', 'iso.fit(X)', 'assert'...
364,410
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
replay_buffer.py
ReplayBuffer.remove_n
remove_n
Get n items for removal.
[ "Get", "n", "items", "for", "removal." ]
def remove_n(self, n): idxs = random.sample(xrange(self.init_length, self.cur_size), n) return idxs
['def', 'remove_n(self,', 'n):', 'idxs', '=', 'random.sample(xrange(self.init_length,', 'self.cur_size),', 'n)', 'return', 'idxs']
58,941
jwwangchn/NWD
test_assigner.py
test_approx_iou_assigner_with_empty_boxes
test_approx_iou_assigner_with_empty_boxes
Test corner case where an network might predict no boxes.
[ "Test", "corner", "case", "where", "an", "network", "might", "predict", "no", "boxes." ]
def test_approx_iou_assigner_with_empty_boxes(): self = ApproxMaxIoUAssigner(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]]) approxs_per_octave = 1 approxs = bboxes squares = bboxes assign_result = self.assign(app...
['def', 'test_approx_iou_assigner_with_empty_boxes():', 'self', '=', 'ApproxMaxIoUAssigner(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]])', 'approxs_per_octave', '=', '1', 'approxs', '=', 'bboxes...
725,123
MushroomRL/mushroom-rl
replay_memory.py
SumTree.update
update
Update the priority of the sample at the provided index in the dataset.
[ "Update", "the", "priority", "of", "the", "sample", "at", "the", "provided", "index", "in", "the", "dataset." ]
def update(self, idx, priorities): for (i, p) in zip(idx, priorities): delta = p - self._tree[i] self._tree[i] = p self._propagate(delta, i)
['def', 'update(self,', 'idx,', 'priorities):', 'for', '(i,', 'p)', 'in', 'zip(idx,', 'priorities):', 'delta', '=', 'p', '-', 'self._tree[i]', 'self._tree[i]', '=', 'p', 'self._propagate(delta,', 'i)']
266,141
farzaa/DeepLeague
voc_to_tfrecords.py
get_image_path
get_image_path
Get path to image for given year and image id.
[ "Get", "path", "to", "image", "for", "given", "year", "and", "image", "id." ]
def get_image_path(voc_path, year, image_id): return os.path.join(voc_path, 'VOC{}/JPEGImages/{}.jpg'.format(year, image_id))
['def', 'get_image_path(voc_path,', 'year,', 'image_id):', 'return', 'os.path.join(voc_path,', "'VOC{}/JPEGImages/{}.jpg'.format(year,", 'image_id))']
521,533
Katja-M/Python_NaturalLanguageProcessing
textpath.py
TextToPath.glyph_to_path
glyph_to_path
Convert the *font*'s current glyph to a (vertices, codes) pair.
[ "Convert", "the", "*font*'s", "current", "glyph", "to", "a", "(vertices,", "codes)", "pair." ]
def glyph_to_path(self, font, currx=0.0): (verts, codes) = font.get_path() if currx != 0.0: verts[:, 0] += currx return (verts, codes)
['def', 'glyph_to_path(self,', 'font,', 'currx=0.0):', '(verts,', 'codes)', '=', 'font.get_path()', 'if', 'currx', '!=', '0.0:', 'verts[:,', '0]', '+=', 'currx', 'return', '(verts,', 'codes)']
864,865
fmassa/vision
feature_pyramid_network.py
FeaturePyramidNetwork.forward
forward
Computes the FPN for a set of feature maps.
[ "Computes", "the", "FPN", "for", "a", "set", "of", "feature", "maps." ]
def forward(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]: names = list(x.keys()) x = list(x.values()) last_inner = self.get_result_from_inner_blocks(x[-1], -1) results = [] results.append(self.get_result_from_layer_blocks(last_inner, -1)) for idx in range(len(x) - 2, -1, -1): inner_l...
['def', 'forward(self,', 'x:', 'Dict[str,', 'Tensor])', '->', 'Dict[str,', 'Tensor]:', 'names', '=', 'list(x.keys())', 'x', '=', 'list(x.values())', 'last_inner', '=', 'self.get_result_from_inner_blocks(x[-1],', '-1)', 'results', '=', '[]', 'results.append(self.get_result_from_layer_blocks(last_inner,', '-1))', 'for', ...
955,980
triaquae/triaquae
signed_cookies.py
SessionStore.create
create
To create a new key, we simply make sure that the modified flag is set so that the cookie is set on the client for the current request.
[ "To", "create", "a", "new", "key,", "we", "simply", "make", "sure", "that", "the", "modified", "flag", "is", "set", "so", "that", "the", "cookie", "is", "set", "on", "the", "client", "for", "the", "current", "request." ]
def create(self): self.modified = True
['def', 'create(self):', 'self.modified', '=', 'True']
358,168
rudranil723/mini-main
_base.py
ExcelWriter.if_sheet_exists
if_sheet_exists
How to behave when writing to a sheet that already exists in append mode.
[ "How", "to", "behave", "when", "writing", "to", "a", "sheet", "that", "already", "exists", "in", "append", "mode." ]
def if_sheet_exists(self) -> str: return self._if_sheet_exists
['def', 'if_sheet_exists(self)', '->', 'str:', 'return', 'self._if_sheet_exists']
267,180
tobegit3hub/deep_image_model
variables.py
Variable.name
name
The name of this variable.
[ "The", "name", "of", "this", "variable." ]
def name(self): return self._variable.name
['def', 'name(self):', 'return', 'self._variable.name']
183,125
rudranil723/mini-main
generation.py
void_output
void_output
For functions that don't only return an error code that needs to be examined.
[ "For", "functions", "that", "don't", "only", "return", "an", "error", "code", "that", "needs", "to", "be", "examined." ]
def void_output(func, argtypes, errcheck=True, cpl=False): if argtypes: func.argtypes = argtypes if errcheck: func.restype = c_int func.errcheck = partial(check_errcode, cpl=cpl) else: func.restype = None return func
['def', 'void_output(func,', 'argtypes,', 'errcheck=True,', 'cpl=False):', 'if', 'argtypes:', 'func.argtypes', '=', 'argtypes', 'if', 'errcheck:', 'func.restype', '=', 'c_int', 'func.errcheck', '=', 'partial(check_errcode,', 'cpl=cpl)', 'else:', 'func.restype', '=', 'None', 'return', 'func']
315,211
lxy5513/cvToolkit
utils_natural_sort.py
natural_sort
natural_sort
Sort the given list in the way that humans expect.
[ "Sort", "the", "given", "list", "in", "the", "way", "that", "humans", "expect." ]
def natural_sort(given_list): given_list.sort(key=alphanum_key)
['def', 'natural_sort(given_list):', 'given_list.sort(key=alphanum_key)']
523,806
triaquae/triaquae
daemonize.py
become_daemon
become_daemon
Robustly turn into a UNIX daemon, running in our_home_dir.
[ "Robustly", "turn", "into", "a", "UNIX", "daemon,", "running", "in", "our_home_dir." ]
def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', umask=18): try: if os.fork() > 0: sys.exit(0) except OSError as e: sys.stderr.write('fork #1 failed: (%d) %s\n' % (e.errno, e.strerror)) sys.exit(1) os.setsid() os.chdir(our_home_dir) os...
['def', "become_daemon(our_home_dir='.',", "out_log='/dev/null',", "err_log='/dev/null',", 'umask=18):', 'try:', 'if', 'os.fork()', '>', '0:', 'sys.exit(0)', 'except', 'OSError', 'as', 'e:', "sys.stderr.write('fork", '#1', 'failed:', '(%d)', "%s\\n'", '%', '(e.errno,', 'e.strerror))', 'sys.exit(1)', 'os.setsid()', 'os....
424,013
tensorflow/privacy
input.py
extract_svhn
extract_svhn
Extract a MATLAB matrix into two numpy arrays with data and labels.
[ "Extract", "a", "MATLAB", "matrix", "into", "two", "numpy", "arrays", "with", "data", "and", "labels." ]
def extract_svhn(local_url): with tf.gfile.Open(local_url, mode='r') as file_obj: data_dict = loadmat(file_obj) (data, labels) = (data_dict['X'], data_dict['y']) data = np.asarray(data, dtype=np.float32) labels = np.asarray(labels, dtype=np.int32) data = data.transpose(3, 0, ...
['def', 'extract_svhn(local_url):', 'with', 'tf.gfile.Open(local_url,', "mode='r')", 'as', 'file_obj:', 'data_dict', '=', 'loadmat(file_obj)', '(data,', 'labels)', '=', "(data_dict['X'],", "data_dict['y'])", 'data', '=', 'np.asarray(data,', 'dtype=np.float32)', 'labels', '=', 'np.asarray(labels,', 'dtype=np.int32)', 'd...
824,554
aws/sagemaker-python-sdk
session.py
Session.compile_model
compile_model
Create an Amazon SageMaker Neo compilation job.
[ "Create", "an", "Amazon", "SageMaker", "Neo", "compilation", "job." ]
def compile_model(self, input_model_config, output_model_config, role=None, job_name=None, stop_condition=None, tags=None): role = resolve_value_from_config(role, COMPILATION_JOB_ROLE_ARN_PATH, sagemaker_session=self) inferred_output_model_config = update_nested_dictionary_with_values_from_config(output_model_c...
['def', 'compile_model(self,', 'input_model_config,', 'output_model_config,', 'role=None,', 'job_name=None,', 'stop_condition=None,', 'tags=None):', 'role', '=', 'resolve_value_from_config(role,', 'COMPILATION_JOB_ROLE_ARN_PATH,', 'sagemaker_session=self)', 'inferred_output_model_config', '=', 'update_nested_dictionary...
829,616
rudranil723/mini-main
python_message.py
_OneofListener.Modified
Modified
Also updates the state of the containing oneof in the parent message.
[ "Also", "updates", "the", "state", "of", "the", "containing", "oneof", "in", "the", "parent", "message." ]
def Modified(self): try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
['def', 'Modified(self):', 'try:', 'self._parent_message_weakref._UpdateOneofState(self._field)', 'super(_OneofListener,', 'self).Modified()', 'except', 'ReferenceError:', 'pass']
318,427
sunishsheth2009/ChatterBot
test_list_training.py
ListTrainingTests.test_consecutive_trainings_same_responses_different_inputs
test_consecutive_trainings_same_responses_different_inputs
Test consecutive trainings with the same responses to different inputs.
[ "Test", "consecutive", "trainings", "with", "the", "same", "responses", "to", "different", "inputs." ]
def test_consecutive_trainings_same_responses_different_inputs(self): self.trainer.train(['A', 'B', 'C']) self.trainer.train(['B', 'C', 'D']) response1 = self.chatbot.get_response('B') response2 = self.chatbot.get_response('C') self.assertEqual(response1.text, 'C') self.assertEqual(response2.tex...
['def', 'test_consecutive_trainings_same_responses_different_inputs(self):', "self.trainer.train(['A',", "'B',", "'C'])", "self.trainer.train(['B',", "'C',", "'D'])", 'response1', '=', "self.chatbot.get_response('B')", 'response2', '=', "self.chatbot.get_response('C')", 'self.assertEqual(response1.text,', "'C')", 'self...
485,996
tensorflow/hub
native_module_test.py
while_module_fn
while_module_fn
Compute x^n with while_loop.
[ "Compute", "x^n", "with", "while_loop." ]
def while_module_fn(): x = tf.compat.v1.placeholder(dtype=tf.float32, name='x', shape=[]) n = tf.compat.v1.placeholder(dtype=tf.int32, name='n') (_, pow_x) = tf.while_loop(lambda i, ix: i < n, lambda i, ix: [tf.add(i, 1), ix * x], [tf.constant(0), tf.constant(1.0)]) hub.add_signature(inputs={'x': x, 'n'...
['def', 'while_module_fn():', 'x', '=', 'tf.compat.v1.placeholder(dtype=tf.float32,', "name='x',", 'shape=[])', 'n', '=', 'tf.compat.v1.placeholder(dtype=tf.int32,', "name='n')", '(_,', 'pow_x)', '=', 'tf.while_loop(lambda', 'i,', 'ix:', 'i', '<', 'n,', 'lambda', 'i,', 'ix:', '[tf.add(i,', '1),', 'ix', '*', 'x],', '[tf...
570,999
ZumoLabs/zpy
files.py
make_custom_image_name
make_custom_image_name
Creates a custom image name given integer id and name.
[ "Creates", "a", "custom", "image", "name", "given", "integer", "id", "and", "name." ]
def make_custom_image_name(id: int, name: str, extension: str='.png') -> str: return 'image.%06d.%s' % (id, name) + extension
['def', 'make_custom_image_name(id:', 'int,', 'name:', 'str,', 'extension:', "str='.png')", '->', 'str:', 'return', "'image.%06d.%s'", '%', '(id,', 'name)', '+', 'extension']
972,013
YanjieZe/rl3d
wrappers.py
DynamicCameraWrapper.record_inital_camera_pos
record_inital_camera_pos
Record new initialized camera.
[ "Record", "new", "initialized", "camera." ]
def record_inital_camera_pos(self): self.init_camera_positions = {} self.init_camera_positions['camera_dynamic'] = copy.deepcopy(self.cam_modder.get_pos('camera_dynamic')) self.init_camera_positions['camera_static'] = copy.deepcopy(self.cam_modder.get_pos('camera_static')) self.init_camera_quaternions =...
['def', 'record_inital_camera_pos(self):', 'self.init_camera_positions', '=', '{}', "self.init_camera_positions['camera_dynamic']", '=', "copy.deepcopy(self.cam_modder.get_pos('camera_dynamic'))", "self.init_camera_positions['camera_static']", '=', "copy.deepcopy(self.cam_modder.get_pos('camera_static'))", 'self.init_c...
330,842
bachiraoun/fullrmc
DistanceConstraints.py
_DistanceConstraint.numberOfTypes
numberOfTypes
Number of defined atom types in the configuration.
[ "Number", "of", "defined", "atom", "types", "in", "the", "configuration." ]
def numberOfTypes(self): return self.__numberOfTypes
['def', 'numberOfTypes(self):', 'return', 'self.__numberOfTypes']
213,545
google-research/tensor2robot
abstract_model.py
AbstractT2RModel.get_label_specification_for_packing
get_label_specification_for_packing
Returns the label_spec that create_pack_features expects.
[ "Returns", "the", "label_spec", "that", "create_pack_features", "expects." ]
def get_label_specification_for_packing(self, mode): return self.preprocessor.get_in_label_specification(mode)
['def', 'get_label_specification_for_packing(self,', 'mode):', 'return', 'self.preprocessor.get_in_label_specification(mode)']
908,196
PacktPublishing/Hands-On-Artificial--for-Banking
test_dtype.py
TestSubarray.test_nonequivalent_record
test_nonequivalent_record
Test whether different subarray dtypes hash differently.
[ "Test", "whether", "different", "subarray", "dtypes", "hash", "differently." ]
def test_nonequivalent_record(self): a = np.dtype((int, (2, 3))) b = np.dtype((int, (3, 2))) assert_dtype_not_equal(a, b) a = np.dtype((int, (2, 3))) b = np.dtype((int, (2, 2))) assert_dtype_not_equal(a, b) a = np.dtype((int, (1, 2, 3))) b = np.dtype((int, (1, 2))) assert_dtype_not_e...
['def', 'test_nonequivalent_record(self):', 'a', '=', 'np.dtype((int,', '(2,', '3)))', 'b', '=', 'np.dtype((int,', '(3,', '2)))', 'assert_dtype_not_equal(a,', 'b)', 'a', '=', 'np.dtype((int,', '(2,', '3)))', 'b', '=', 'np.dtype((int,', '(2,', '2)))', 'assert_dtype_not_equal(a,', 'b)', 'a', '=', 'np.dtype((int,', '(1,',...
235,361
XuyangSHEN/Non-binary-deep-transfer-learning-for-image-classification
resnet.py
resnet34d
resnet34d
Constructs a ResNet-34-D model.
[ "Constructs", "a", "ResNet-34-D", "model." ]
def resnet34d(pretrained=False, **kwargs): model_args = dict(block=BasicBlock, layers=[3, 4, 6, 3], stem_width=32, stem_type='deep', avg_down=True, **kwargs) return _create_resnet('resnet34d', pretrained, **model_args)
['def', 'resnet34d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=BasicBlock,', 'layers=[3,', '4,', '6,', '3],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', '**kwargs)', 'return', "_create_resnet('resnet34d',", 'pretrained,', '**model_args)']
729,451
Megvii-BaseDetection/cvpods
transform.py
BlendTransform.apply_coords
apply_coords
Apply no transform on the coordinates.
[ "Apply", "no", "transform", "on", "the", "coordinates." ]
def apply_coords(self, coords: np.ndarray) -> np.ndarray: return coords
['def', 'apply_coords(self,', 'coords:', 'np.ndarray)', '->', 'np.ndarray:', 'return', 'coords']
510,897
matsu0228/nlp-jp
client_options.py
ClientOptions.local_threshold_ms
local_threshold_ms
The local threshold for this instance.
[ "The", "local", "threshold", "for", "this", "instance." ]
def local_threshold_ms(self): return self.__local_threshold_ms
['def', 'local_threshold_ms(self):', 'return', 'self.__local_threshold_ms']
804,741
43Carrig/recurrent_neural_networks_practice
gen_array_ops.py
extract_image_patches
extract_image_patches
Extract `patches` from `images` and put them in the "depth" output dimension.
[ "Extract", "`patches`", "from", "`images`", "and", "put", "them", "in", "the", "\"depth\"", "output", "dimension." ]
def extract_image_patches(images, ksizes, strides, rates, padding, name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(ksizes, (list, tuple)): raise TypeError("Expected list for 'ksizes' argument to 'extract_image_patches' Op, not %r." ...
['def', 'extract_image_patches(images,', 'ksizes,', 'strides,', 'rates,', 'padding,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(ksizes,', '(list,', 'tuple)):', 'raise', 'TypeError("Expected', 'list', 'for', "'ksize...
337,309
calico/basenji
layers.py
get_positional_feature_function
get_positional_feature_function
Returns positional feature functions.
[ "Returns", "positional", "feature", "functions." ]
def get_positional_feature_function(name): available = {'positional_features_central_mask': positional_features_central_mask, 'positional_features_gamma': positional_features_gamma} if name not in available: raise ValueError(f'Function {name} not available in {available.keys()}') return available[na...
['def', 'get_positional_feature_function(name):', 'available', '=', "{'positional_features_central_mask':", 'positional_features_central_mask,', "'positional_features_gamma':", 'positional_features_gamma}', 'if', 'name', 'not', 'in', 'available:', 'raise', "ValueError(f'Function", '{name}', 'not', 'available', 'in', "{...
94,577
43Carrig/recurrent_neural_networks_practice
monitors.py
get_default_monitors
get_default_monitors
Returns a default set of typically-used monitors.
[ "Returns", "a", "default", "set", "of", "typically-used", "monitors." ]
def get_default_monitors(loss_op=None, summary_op=None, save_summary_steps=100, output_dir=None, summary_writer=None): monitors = [] if loss_op is not None: monitors.append(PrintTensor(tensor_names={'loss': loss_op.name})) if summary_op is not None: monitors.append(SummarySaver(summary_op, s...
['def', 'get_default_monitors(loss_op=None,', 'summary_op=None,', 'save_summary_steps=100,', 'output_dir=None,', 'summary_writer=None):', 'monitors', '=', '[]', 'if', 'loss_op', 'is', 'not', 'None:', "monitors.append(PrintTensor(tensor_names={'loss':", 'loss_op.name}))', 'if', 'summary_op', 'is', 'not', 'None:', 'monit...
313,545
dibyaghosh/gcsl
configurable_test.py
TestConfigurable.test_pickle_override
test_pickle_override
Tests overriding serialized parameters.
[ "Tests", "overriding", "serialized", "parameters." ]
def test_pickle_override(self): TEST_CONFIGS[DummyWithConfigPickleable] = {'a': 4, 'c': 5} d = DummyWithConfigPickleable(c=1) self.assertEqual(d.a, 4) self.assertEqual(d.b, 2) self.assertEqual(d.c, 1) with tempfile.TemporaryFile() as f: pickle.dump(d, f) f.seek(0) TEST_CO...
['def', 'test_pickle_override(self):', 'TEST_CONFIGS[DummyWithConfigPickleable]', '=', "{'a':", '4,', "'c':", '5}', 'd', '=', 'DummyWithConfigPickleable(c=1)', 'self.assertEqual(d.a,', '4)', 'self.assertEqual(d.b,', '2)', 'self.assertEqual(d.c,', '1)', 'with', 'tempfile.TemporaryFile()', 'as', 'f:', 'pickle.dump(d,', '...
202,087
calico/basenji
basenji_test_genes.py
quantile_accuracy
quantile_accuracy
Plot accuracy (PearsonR) in quantile bins across targets.
[ "Plot", "accuracy", "(PearsonR)", "in", "quantile", "bins", "across", "targets." ]
def quantile_accuracy(gene_targets, gene_preds, gene_stat, out_pdf, numq=4): quant_indexes = quantile_indexes(gene_stat, numq) quantiles_series = [] targets_series = [] pcor_series = [] for qi in range(numq): gene_targets_quant = gene_targets[quant_indexes[qi]].astype('float32') gene...
['def', 'quantile_accuracy(gene_targets,', 'gene_preds,', 'gene_stat,', 'out_pdf,', 'numq=4):', 'quant_indexes', '=', 'quantile_indexes(gene_stat,', 'numq)', 'quantiles_series', '=', '[]', 'targets_series', '=', '[]', 'pcor_series', '=', '[]', 'for', 'qi', 'in', 'range(numq):', 'gene_targets_quant', '=', "gene_targets[...
94,891
deepmind/acme
utils.py
device_put
device_put
Returns iterator that samples an item and places it on the device.
[ "Returns", "iterator", "that", "samples", "an", "item", "and", "places", "it", "on", "the", "device." ]
def device_put(iterable: Iterable[types.NestedArray], device: jax.Device, split_fn: Optional[_SplitFunction]=None): return PutToDevicesIterable(iterable=iterable, pmapped_user=False, devices=[device], split_fn=split_fn)
['def', 'device_put(iterable:', 'Iterable[types.NestedArray],', 'device:', 'jax.Device,', 'split_fn:', 'Optional[_SplitFunction]=None):', 'return', 'PutToDevicesIterable(iterable=iterable,', 'pmapped_user=False,', 'devices=[device],', 'split_fn=split_fn)']
7,802
triaquae/triaquae
models.py
ContentTypeManager.get_for_models
get_for_models
Given *models, returns a dictionary mapping {model: content_type}.
[ "Given", "*models,", "returns", "a", "dictionary", "mapping", "{model:", "content_type}." ]
def get_for_models(self, *models, **kwargs): for_concrete_models = kwargs.pop('for_concrete_models', True) results = {} needed_app_labels = set() needed_models = set() needed_opts = set() for model in models: opts = self._get_opts(model, for_concrete_models) try: ct =...
['def', 'get_for_models(self,', '*models,', '**kwargs):', 'for_concrete_models', '=', "kwargs.pop('for_concrete_models',", 'True)', 'results', '=', '{}', 'needed_app_labels', '=', 'set()', 'needed_models', '=', 'set()', 'needed_opts', '=', 'set()', 'for', 'model', 'in', 'models:', 'opts', '=', 'self._get_opts(model,', ...
357,236
AgnostiqHQ/covalent
write_result_to_db_test.py
test_update_electrons_data
test_update_electrons_data
Test the function that updates the data in the Electrons table.
[ "Test", "the", "function", "that", "updates", "the", "data", "in", "the", "Electrons", "table." ]
def test_update_electrons_data(test_db, mocker): mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db', test_db) insert_lattices_data(**get_lattice_kwargs(created_at=dt.now(timezone.utc), updated_at=dt.now(timezone.utc), started_at=dt.now(timezone.utc))) with pytest.raises(MissingElectronRec...
['def', 'test_update_electrons_data(test_db,', 'mocker):', "mocker.patch('covalent_dispatcher._db.write_result_to_db.workflow_db',", 'test_db)', 'insert_lattices_data(**get_lattice_kwargs(created_at=dt.now(timezone.utc),', 'updated_at=dt.now(timezone.utc),', 'started_at=dt.now(timezone.utc)))', 'with', 'pytest.raises(M...
489,746
tommytracey/DeepRL-P3-Collaboration-Competition
trainer.py
Trainer.graph_scope
graph_scope
Returns the graph scope of the trainer.
[ "Returns", "the", "graph", "scope", "of", "the", "trainer." ]
def graph_scope(self): raise UnityTrainerException('The graph_scope property was not implemented.')
['def', 'graph_scope(self):', 'raise', "UnityTrainerException('The", 'graph_scope', 'property', 'was', 'not', "implemented.')"]
539,585
nesl/Time-in-State-RL
utility.py
assign_nested_vars
assign_nested_vars
Assign tensors to matching nested tuple of variables.
[ "Assign", "tensors", "to", "matching", "nested", "tuple", "of", "variables." ]
def assign_nested_vars(variables, tensors, indices=None): if isinstance(variables, (tuple, list)): return tf.group(*[assign_nested_vars(variable, tensor) for (variable, tensor) in zip(variables, tensors)]) if indices is None: return variables.assign(tensors) else: return tf.scatter_u...
['def', 'assign_nested_vars(variables,', 'tensors,', 'indices=None):', 'if', 'isinstance(variables,', '(tuple,', 'list)):', 'return', 'tf.group(*[assign_nested_vars(variable,', 'tensor)', 'for', '(variable,', 'tensor)', 'in', 'zip(variables,', 'tensors)])', 'if', 'indices', 'is', 'None:', 'return', 'variables.assign(te...
917,299
s3prl/s3prl
superb_sid.py
SuperbSID.build_dataset
build_dataset
Build the dataset for train/valid/test.
[ "Build", "the", "dataset", "for", "train/valid/test." ]
def build_dataset(self, build_dataset: dict, target_dir: str, cache_dir: str, mode: str, data_csv: str, encoder_path: str, frame_shift: int): @dataclass class Config: train: dict = None valid: dict = None test: dict = None conf = Config(**build_dataset) assert mode in ['train', ...
['def', 'build_dataset(self,', 'build_dataset:', 'dict,', 'target_dir:', 'str,', 'cache_dir:', 'str,', 'mode:', 'str,', 'data_csv:', 'str,', 'encoder_path:', 'str,', 'frame_shift:', 'int):', '@dataclass', 'class', 'Config:', 'train:', 'dict', '=', 'None', 'valid:', 'dict', '=', 'None', 'test:', 'dict', '=', 'None', 'co...
327,602
enuguru/artificial_intelligence_and_machine_learning
reading.py
IndexReader.iter_prefix
iter_prefix
Yields (text, terminfo) tuples for all terms in the given field with a certain prefix.
[ "Yields", "(text,", "terminfo)", "tuples", "for", "all", "terms", "in", "the", "given", "field", "with", "a", "certain", "prefix." ]
def iter_prefix(self, fieldname, prefix): prefix = self._text_to_bytes(fieldname, prefix) for (text, terminfo) in self.iter_field(fieldname, prefix): if not text.startswith(prefix): return yield (text, terminfo)
['def', 'iter_prefix(self,', 'fieldname,', 'prefix):', 'prefix', '=', 'self._text_to_bytes(fieldname,', 'prefix)', 'for', '(text,', 'terminfo)', 'in', 'self.iter_field(fieldname,', 'prefix):', 'if', 'not', 'text.startswith(prefix):', 'return', 'yield', '(text,', 'terminfo)']
162,108
RolandGao/RegSeg
augment.py
rand_augment
rand_augment
Applies random augmentation to an image.
[ "Applies", "random", "augmentation", "to", "an", "image." ]
def rand_augment(im, magnitude, ops=None, n_ops=2, prob=1.0): ops = ops if ops else RANDAUG_OPS for op in random.sample(ops, int(n_ops)): im = apply_op(im, op, prob, magnitude) return im
['def', 'rand_augment(im,', 'magnitude,', 'ops=None,', 'n_ops=2,', 'prob=1.0):', 'ops', '=', 'ops', 'if', 'ops', 'else', 'RANDAUG_OPS', 'for', 'op', 'in', 'random.sample(ops,', 'int(n_ops)):', 'im', '=', 'apply_op(im,', 'op,', 'prob,', 'magnitude)', 'return', 'im']
832,900
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
model.py
Model.setup_placeholders
setup_placeholders
Create the Tensorflow placeholders.
[ "Create", "the", "Tensorflow", "placeholders." ]
def setup_placeholders(self): self.avg_episode_reward = tf.placeholder(tf.float32, [], 'avg_episode_reward') self.greedy_episode_reward = tf.placeholder(tf.float32, [], 'greedy_episode_reward') self.internal_state = tf.placeholder(tf.float32, [None, self.policy.rnn_state_dim], 'internal_state') self.sin...
['def', 'setup_placeholders(self):', 'self.avg_episode_reward', '=', 'tf.placeholder(tf.float32,', '[],', "'avg_episode_reward')", 'self.greedy_episode_reward', '=', 'tf.placeholder(tf.float32,', '[],', "'greedy_episode_reward')", 'self.internal_state', '=', 'tf.placeholder(tf.float32,', '[None,', 'self.policy.rnn_stat...
26,116
gfjiangly/cvtools
f1_score.py
f1_score
f1_score
Evaluate F1 score of a dataset.
[ "Evaluate", "F1", "score", "of", "a", "dataset." ]
def f1_score(det_results, gt_bboxes, gt_labels, gt_ignore=None, scale_ranges=None, iou_thr=0.5, dataset=None, print_summary=True): assert len(det_results) == len(gt_bboxes) == len(gt_labels) if gt_ignore is not None: assert len(gt_ignore) == len(gt_labels) for i in range(len(gt_ignore)): ...
['def', 'f1_score(det_results,', 'gt_bboxes,', 'gt_labels,', 'gt_ignore=None,', 'scale_ranges=None,', 'iou_thr=0.5,', 'dataset=None,', 'print_summary=True):', 'assert', 'len(det_results)', '==', 'len(gt_bboxes)', '==', 'len(gt_labels)', 'if', 'gt_ignore', 'is', 'not', 'None:', 'assert', 'len(gt_ignore)', '==', 'len(gt_...
523,834
ashwin-phadke/cvplayground
autoaugment_utils.py
shear_y
shear_y
Equivalent of PIL Shearing in Y dimension.
[ "Equivalent", "of", "PIL", "Shearing", "in", "Y", "dimension." ]
def shear_y(image, level, replace): image = tf.contrib.image.transform(wrap(image), [1.0, 0.0, 0.0, level, 1.0, 0.0, 0.0, 0.0]) return unwrap(image, replace)
['def', 'shear_y(image,', 'level,', 'replace):', 'image', '=', 'tf.contrib.image.transform(wrap(image),', '[1.0,', '0.0,', '0.0,', 'level,', '1.0,', '0.0,', '0.0,', '0.0])', 'return', 'unwrap(image,', 'replace)']
510,520
chenbinghui1/DSL
seesaw_loss.py
seesaw_ce_loss
seesaw_ce_loss
Calculate the Seesaw CrossEntropy loss.
[ "Calculate", "the", "Seesaw", "CrossEntropy", "loss." ]
def seesaw_ce_loss(cls_score, labels, label_weights, cum_samples, num_classes, p, q, eps, reduction='mean', avg_factor=None): assert cls_score.size(-1) == num_classes assert len(cum_samples) == num_classes onehot_labels = F.one_hot(labels, num_classes) seesaw_weights = cls_score.new_ones(onehot_labels.s...
['def', 'seesaw_ce_loss(cls_score,', 'labels,', 'label_weights,', 'cum_samples,', 'num_classes,', 'p,', 'q,', 'eps,', "reduction='mean',", 'avg_factor=None):', 'assert', 'cls_score.size(-1)', '==', 'num_classes', 'assert', 'len(cum_samples)', '==', 'num_classes', 'onehot_labels', '=', 'F.one_hot(labels,', 'num_classes)...
167,880
ADLab3Ds/TiG-BEV
anchor_free_mono3d_head.py
AnchorFreeMono3DHead.forward_single
forward_single
Forward features of a single scale levle.
[ "Forward", "features", "of", "a", "single", "scale", "levle." ]
def forward_single(self, x): cls_feat = x reg_feat = x for cls_layer in self.cls_convs: cls_feat = cls_layer(cls_feat) clone_cls_feat = cls_feat.clone() for conv_cls_prev_layer in self.conv_cls_prev: clone_cls_feat = conv_cls_prev_layer(clone_cls_feat) cls_score = self.conv_cls(c...
['def', 'forward_single(self,', 'x):', 'cls_feat', '=', 'x', 'reg_feat', '=', 'x', 'for', 'cls_layer', 'in', 'self.cls_convs:', 'cls_feat', '=', 'cls_layer(cls_feat)', 'clone_cls_feat', '=', 'cls_feat.clone()', 'for', 'conv_cls_prev_layer', 'in', 'self.conv_cls_prev:', 'clone_cls_feat', '=', 'conv_cls_prev_layer(clone_...
916,995
Ruturaj123/Flowchart-Detection
image_ops_impl.py
fix_image_flip_shape
fix_image_flip_shape
Set the shape to 3 dimensional if we don't know anything else.
[ "Set", "the", "shape", "to", "3", "dimensional", "if", "we", "don't", "know", "anything", "else." ]
def fix_image_flip_shape(image, result): image_shape = image.get_shape() if image_shape == tensor_shape.unknown_shape(): result.set_shape([None, None, None]) else: result.set_shape(image_shape) return result
['def', 'fix_image_flip_shape(image,', 'result):', 'image_shape', '=', 'image.get_shape()', 'if', 'image_shape', '==', 'tensor_shape.unknown_shape():', 'result.set_shape([None,', 'None,', 'None])', 'else:', 'result.set_shape(image_shape)', 'return', 'result']
605,882
danamyu/hedgehog_detector
mnist.py
get_split
get_split
Gets a dataset tuple with instructions for reading MNIST.
[ "Gets", "a", "dataset", "tuple", "with", "instructions", "for", "reading", "MNIST." ]
def get_split(split_name, dataset_dir, file_pattern=None, reader=None): if split_name not in _SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_na...
['def', 'get_split(split_name,', 'dataset_dir,', 'file_pattern=None,', 'reader=None):', 'if', 'split_name', 'not', 'in', '_SPLITS_TO_SIZES:', 'raise', "ValueError('split", 'name', '%s', 'was', 'not', "recognized.'", '%', 'split_name)', 'if', 'not', 'file_pattern:', 'file_pattern', '=', '_FILE_PATTERN', 'file_pattern', ...
590,373
rudranil723/mini-main
client.py
Client.logout
logout
Log out the user by removing the cookies and session object.
[ "Log", "out", "the", "user", "by", "removing", "the", "cookies", "and", "session", "object." ]
def logout(self): from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) if self.session: request.session = self.session request.user = get_user(request) else: request.session = engine.SessionStore() logout...
['def', 'logout(self):', 'from', 'django.contrib.auth', 'import', 'get_user,', 'logout', 'request', '=', 'HttpRequest()', 'engine', '=', 'import_module(settings.SESSION_ENGINE)', 'if', 'self.session:', 'request.session', '=', 'self.session', 'request.user', '=', 'get_user(request)', 'else:', 'request.session', '=', 'en...
316,547
QData/deepWordBug
output.py
output_validator
output_validator
Validates an handler implementation against the IOutput interface.
[ "Validates", "an", "handler", "implementation", "against", "the", "IOutput", "interface." ]
def output_validator(klass, obj): members = ['_setup', 'render'] interface.validate(IOutput, obj, members)
['def', 'output_validator(klass,', 'obj):', 'members', '=', "['_setup',", "'render']", 'interface.validate(IOutput,', 'obj,', 'members)']
541,675
omonimus1/super-computer-
StringIOTree.py
StringIOTree.copyto
copyto
Potentially cheaper than getvalue as no string concatenation needs to happen.
[ "Potentially", "cheaper", "than", "getvalue", "as", "no", "string", "concatenation", "needs", "to", "happen." ]
def copyto(self, target): for child in self.prepended_children: child.copyto(target) stream_content = self.stream.getvalue() if stream_content: target.write(stream_content)
['def', 'copyto(self,', 'target):', 'for', 'child', 'in', 'self.prepended_children:', 'child.copyto(target)', 'stream_content', '=', 'self.stream.getvalue()', 'if', 'stream_content:', 'target.write(stream_content)']
912,894
scikit-learn/scikit-learn
test_encoders.py
test_ohe_drop_first_handle_unknown_ignore_warns
test_ohe_drop_first_handle_unknown_ignore_warns
Check drop='first' and handle_unknown='ignore'/'infrequent_if_exist' during transform.
[ "Check", "drop='first'", "and", "handle_unknown='ignore'/'infrequent_if_exist'", "during", "transform." ]
def test_ohe_drop_first_handle_unknown_ignore_warns(handle_unknown): X = [['a', 0], ['b', 2], ['b', 1]] ohe = OneHotEncoder(drop='first', sparse_output=False, handle_unknown=handle_unknown) X_trans = ohe.fit_transform(X) X_expected = np.array([[0, 0, 0], [1, 0, 1], [1, 1, 0]]) assert_allclose(X_tran...
['def', 'test_ohe_drop_first_handle_unknown_ignore_warns(handle_unknown):', 'X', '=', "[['a',", '0],', "['b',", '2],', "['b',", '1]]', 'ohe', '=', "OneHotEncoder(drop='first',", 'sparse_output=False,', 'handle_unknown=handle_unknown)', 'X_trans', '=', 'ohe.fit_transform(X)', 'X_expected', '=', 'np.array([[0,', '0,', '0...
854,010
ogunnoo/natural_language_processing
functions.py
get_bool_ids_greater_than
get_bool_ids_greater_than
Get idx of the last dimension in probability arrays, which is greater than a limitation.
[ "Get", "idx", "of", "the", "last", "dimension", "in", "probability", "arrays,", "which", "is", "greater", "than", "a", "limitation." ]
def get_bool_ids_greater_than(probs, limit=0.5, return_prob=False): probs = np.array(probs) dim_len = len(probs.shape) if dim_len > 1: result = [] for p in probs: result.append(get_bool_ids_greater_than(p, limit, return_prob)) return result else: result = [] ...
['def', 'get_bool_ids_greater_than(probs,', 'limit=0.5,', 'return_prob=False):', 'probs', '=', 'np.array(probs)', 'dim_len', '=', 'len(probs.shape)', 'if', 'dim_len', '>', '1:', 'result', '=', '[]', 'for', 'p', 'in', 'probs:', 'result.append(get_bool_ids_greater_than(p,', 'limit,', 'return_prob))', 'return', 'result', ...
734,597
deephyper/deephyper
space.py
Space.bounds
bounds
The dimension bounds, in the original space.
[ "The", "dimension", "bounds,", "in", "the", "original", "space." ]
def bounds(self): b = [] for dim in self.dimensions: if dim.size == 1: b.append(dim.bounds) else: b.extend(dim.bounds) return b
['def', 'bounds(self):', 'b', '=', '[]', 'for', 'dim', 'in', 'self.dimensions:', 'if', 'dim.size', '==', '1:', 'b.append(dim.bounds)', 'else:', 'b.extend(dim.bounds)', 'return', 'b']
521,057
jwwangchn/NWD
test_head.py
test_fcos_head_forward
test_fcos_head_forward
Test fcos forward in mutil-level feature map.
[ "Test", "fcos", "forward", "in", "mutil-level", "feature", "map." ]
def test_fcos_head_forward(): fcos_model = fcos_config() s = 128 feats = [torch.rand(1, 1, s // feat_size, s // feat_size) for feat_size in [4, 8, 16, 32, 64]] ort_validate(fcos_model.forward, feats)
['def', 'test_fcos_head_forward():', 'fcos_model', '=', 'fcos_config()', 's', '=', '128', 'feats', '=', '[torch.rand(1,', '1,', 's', '//', 'feat_size,', 's', '//', 'feat_size)', 'for', 'feat_size', 'in', '[4,', '8,', '16,', '32,', '64]]', 'ort_validate(fcos_model.forward,', 'feats)']
725,103
mlcclab/PyRAI2MD-hiam
layers.py
FeatureGeometric.set_mol_index
set_mol_index
Set weights for atomic index for distance and angles.
[ "Set", "weights", "for", "atomic", "index", "for", "distance", "and", "angles." ]
def set_mol_index(self, invd_index, angle_index, dihyd_index): if self.use_invdist == True: self.invd_layer.set_weights([invd_index]) if self.use_dihyd_angles == True: self.dih_layer.set_weights([dihyd_index]) if self.use_bond_angles == True: self.ang_layer.set_weights([angle_index])
['def', 'set_mol_index(self,', 'invd_index,', 'angle_index,', 'dihyd_index):', 'if', 'self.use_invdist', '==', 'True:', 'self.invd_layer.set_weights([invd_index])', 'if', 'self.use_dihyd_angles', '==', 'True:', 'self.dih_layer.set_weights([dihyd_index])', 'if', 'self.use_bond_angles', '==', 'True:', 'self.ang_layer.set...
297,025
neokarn/computer_vision
text_dataflow.py
aspect_preserving_resize
aspect_preserving_resize
Resize image with perserved aspect and limited max scale.
[ "Resize", "image", "with", "perserved", "aspect", "and", "limited", "max", "scale." ]
def aspect_preserving_resize(image, largest_side, max_scale=4.0): (height, width) = image.shape[:2] (new_height, new_width) = largest_size_at_most(height, width, largest_side, max_scale) new_height = max(new_height, cfg.stride) new_width = max(new_width, cfg.stride) resized_image = cv2.resize(image,...
['def', 'aspect_preserving_resize(image,', 'largest_side,', 'max_scale=4.0):', '(height,', 'width)', '=', 'image.shape[:2]', '(new_height,', 'new_width)', '=', 'largest_size_at_most(height,', 'width,', 'largest_side,', 'max_scale)', 'new_height', '=', 'max(new_height,', 'cfg.stride)', 'new_width', '=', 'max(new_width,'...
501,434
calico/basenji
blocks.py
dilated_residual
dilated_residual
Construct a residual dilated convolution block.
[ "Construct", "a", "residual", "dilated", "convolution", "block." ]
def dilated_residual(inputs, filters, kernel_size=3, rate_mult=2, dropout=0, repeat=1, conv_type='standard', norm_type=None, round=False, **kwargs): current = inputs dilation_rate = 1.0 for ri in range(repeat): rep_input = current current = conv_block(current, filters=filters, kernel_size=ke...
['def', 'dilated_residual(inputs,', 'filters,', 'kernel_size=3,', 'rate_mult=2,', 'dropout=0,', 'repeat=1,', "conv_type='standard',", 'norm_type=None,', 'round=False,', '**kwargs):', 'current', '=', 'inputs', 'dilation_rate', '=', '1.0', 'for', 'ri', 'in', 'range(repeat):', 'rep_input', '=', 'current', 'current', '=', ...
94,545
intelligent-environments-lab/CityLearn
building.py
Building.cooling_storage
cooling_storage
Cold water storage object for space cooling.
[ "Cold", "water", "storage", "object", "for", "space", "cooling." ]
def cooling_storage(self) -> StorageTank: return self.__cooling_storage
['def', 'cooling_storage(self)', '->', 'StorageTank:', 'return', 'self.__cooling_storage']
105,283
PyRetri/PyRetri
make_data_json.py
make_data_json
make_data_json
Generate data json file for dataset.
[ "Generate", "data", "json", "file", "for", "dataset." ]
def make_data_json(dataset_path: str, save_path: str, type: str, gt_path: str or None=None) -> None: assert type in ['general', 'oxford', 'reid'] if type == 'general': make_ds_for_general(dataset_path, save_path) elif type == 'oxford': make_ds_for_oxford(dataset_path, save_path, gt_path) ...
['def', 'make_data_json(dataset_path:', 'str,', 'save_path:', 'str,', 'type:', 'str,', 'gt_path:', 'str', 'or', 'None=None)', '->', 'None:', 'assert', 'type', 'in', "['general',", "'oxford',", "'reid']", 'if', 'type', '==', "'general':", 'make_ds_for_general(dataset_path,', 'save_path)', 'elif', 'type', '==', "'oxford'...
297,201
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
Expression.acceptExpr
acceptExpr
Create a new expression within this one.
[ "Create", "a", "new", "expression", "within", "this", "one." ]
def acceptExpr(self, node, memo): return self.pushRight()
['def', 'acceptExpr(self,', 'node,', 'memo):', 'return', 'self.pushRight()']
11,049
kubeflow/pipelines
pipeline.py
get
get
Get detailed information about an uploaded KFP pipeline.
[ "Get", "detailed", "information", "about", "an", "uploaded", "KFP", "pipeline." ]
def get(ctx: click.Context, pipeline_id: str): client = ctx.obj['client'] output_format = ctx.obj['output'] pipeline = client.get_pipeline(pipeline_id) _display_pipeline(pipeline, output_format)
['def', 'get(ctx:', 'click.Context,', 'pipeline_id:', 'str):', 'client', '=', "ctx.obj['client']", 'output_format', '=', "ctx.obj['output']", 'pipeline', '=', 'client.get_pipeline(pipeline_id)', '_display_pipeline(pipeline,', 'output_format)']
779,994
Speedwagon13/CS-3600-Introduction-to--
pytree.py
WildcardPattern.optimize
optimize
Optimize certain stacked wildcard patterns.
[ "Optimize", "certain", "stacked", "wildcard", "patterns." ]
def optimize(self): subpattern = None if self.content is not None and len(self.content) == 1 and (len(self.content[0]) == 1): subpattern = self.content[0][0] if self.min == 1 and self.max == 1: if self.content is None: return NodePattern(name=self.name) if subpattern is n...
['def', 'optimize(self):', 'subpattern', '=', 'None', 'if', 'self.content', 'is', 'not', 'None', 'and', 'len(self.content)', '==', '1', 'and', '(len(self.content[0])', '==', '1):', 'subpattern', '=', 'self.content[0][0]', 'if', 'self.min', '==', '1', 'and', 'self.max', '==', '1:', 'if', 'self.content', 'is', 'None:', '...
219,420
f-dangel/cockpit
utils.py
set_deepobs_seed
set_deepobs_seed
Set all seeds used by DeepOBS.
[ "Set", "all", "seeds", "used", "by", "DeepOBS." ]
def set_deepobs_seed(seed=0): random.seed(seed) numpy.random.seed(seed) torch.manual_seed(seed)
['def', 'set_deepobs_seed(seed=0):', 'random.seed(seed)', 'numpy.random.seed(seed)', 'torch.manual_seed(seed)']
493,255
suarez12138/AI-Reversi_IMP_TextDichotomy
test_memory.py
test_memory_eval
test_memory_eval
Smoke test memory with a function with a function defined in an eval.
[ "Smoke", "test", "memory", "with", "a", "function", "with", "a", "function", "defined", "in", "an", "eval." ]
def test_memory_eval(tmpdir): memory = Memory(location=tmpdir.strpath, verbose=0) m = eval('lambda x: x') mm = memory.cache(m) assert mm(1) == 1
['def', 'test_memory_eval(tmpdir):', 'memory', '=', 'Memory(location=tmpdir.strpath,', 'verbose=0)', 'm', '=', "eval('lambda", 'x:', "x')", 'mm', '=', 'memory.cache(m)', 'assert', 'mm(1)', '==', '1']
95,981
Pinafore/ml-hw
bst.py
BSTnode.insert
insert
Insert key t into the subtree rooted at this node (updating subtree size).
[ "Insert", "key", "t", "into", "the", "subtree", "rooted", "at", "this", "node", "(updating", "subtree", "size)." ]
def insert(self, t, NodeType): self.size += 1 if t < self.key: if self.left is None: self.left = NodeType(self, t) return self.left else: return self.left.insert(t, NodeType) elif self.right is None: self.right = NodeType(self, t) return se...
['def', 'insert(self,', 't,', 'NodeType):', 'self.size', '+=', '1', 'if', 't', '<', 'self.key:', 'if', 'self.left', 'is', 'None:', 'self.left', '=', 'NodeType(self,', 't)', 'return', 'self.left', 'else:', 'return', 'self.left.insert(t,', 'NodeType)', 'elif', 'self.right', 'is', 'None:', 'self.right', '=', 'NodeType(sel...
629,657
JahJajaka/afternoon_cleaner
faster_rcnn.py
build_graph
build_graph
Builds serving graph of faster_rcnn to be exported.
[ "Builds", "serving", "graph", "of", "faster_rcnn", "to", "be", "exported." ]
def build_graph(pipeline_config, shapes_info, input_type='encoded_image_string_tensor', use_bfloat16=True): pipeline_config = modify_config(pipeline_config) detection_model = INPUT_BUILDER_UTIL_MAP['model_build'](pipeline_config.model, is_training=False) (placeholder_tensor, input_tensors) = exporter.input_...
['def', 'build_graph(pipeline_config,', 'shapes_info,', "input_type='encoded_image_string_tensor',", 'use_bfloat16=True):', 'pipeline_config', '=', 'modify_config(pipeline_config)', 'detection_model', '=', "INPUT_BUILDER_UTIL_MAP['model_build'](pipeline_config.model,", 'is_training=False)', '(placeholder_tensor,', 'inp...
411,353
rifqind/Agent-Programs-3KS1
open_in_editor.py
load_open_in_editor_bindings
load_open_in_editor_bindings
Load both the Vi and emacs key bindings for handling edit-and-execute-command.
[ "Load", "both", "the", "Vi", "and", "emacs", "key", "bindings", "for", "handling", "edit-and-execute-command." ]
def load_open_in_editor_bindings(): return merge_key_bindings([load_emacs_open_in_editor_bindings(), load_vi_open_in_editor_bindings()])
['def', 'load_open_in_editor_bindings():', 'return', 'merge_key_bindings([load_emacs_open_in_editor_bindings(),', 'load_vi_open_in_editor_bindings()])']
45,290
erickrf/autoencoder
prepare-data.py
write_vocabulary
write_vocabulary
Write the contents of word_dict to the given path.
[ "Write", "the", "contents", "of", "word_dict", "to", "the", "given", "path." ]
def write_vocabulary(words, path): text = '\n'.join(words) with open(path, 'wb') as f: f.write(text.encode('utf-8'))
['def', 'write_vocabulary(words,', 'path):', 'text', '=', "'\\n'.join(words)", 'with', 'open(path,', "'wb')", 'as', 'f:', "f.write(text.encode('utf-8'))"]
419,268
hamza-murad/AALU
visual_recognition_v4.py
ObjectDetail.from_dict
from_dict
Initialize a ObjectDetail object from a json dictionary.
[ "Initialize", "a", "ObjectDetail", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'ObjectDetail': args = {} valid_keys = ['object', 'location', 'score'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class ObjectDetail: ' + ', '.join(bad_keys)) if 'object' in _di...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'ObjectDetail':", 'args', '=', '{}', 'valid_keys', '=', "['object',", "'location',", "'score']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class...
6,198
thaines/helit
student_t.py
StudentT.logProb
logProb
Returns the logarithm of prob - faster than a straight call to prob.
[ "Returns", "the", "logarithm", "of", "prob", "-", "faster", "than", "a", "straight", "call", "to", "prob." ]
def logProb(self, x): x = numpy.asarray(x) d = self.loc.shape[0] delta = x - self.loc val = numpy.dot(delta, numpy.dot(self.getInvScale(), delta)) val = 1.0 + val / self.dof return self.getLogNorm() + math.log(val) * (-0.5 * (self.dof + d))
['def', 'logProb(self,', 'x):', 'x', '=', 'numpy.asarray(x)', 'd', '=', 'self.loc.shape[0]', 'delta', '=', 'x', '-', 'self.loc', 'val', '=', 'numpy.dot(delta,', 'numpy.dot(self.getInvScale(),', 'delta))', 'val', '=', '1.0', '+', 'val', '/', 'self.dof', 'return', 'self.getLogNorm()', '+', 'math.log(val)', '*', '(-0.5', ...
591,705
rdipietro/miccai-2016-surgical-activity-rec
models.py
LSTM.states
states
A 4-D float32 Tensor with shape `[batch_size, duration, num_layers, hidden_layer_size]`.
[ "A", "4-D", "float32", "Tensor", "with", "shape", "`[batch_size,", "duration,", "num_layers,", "hidden_layer_size]`." ]
def states(self): return self._states
['def', 'states(self):', 'return', 'self._states']
286,338
shery322/Lunar-Lander-ANN
scrap_test.py
ScrapModuleTest.todo_test_get
todo_test_get
Ensures get works as expected.
[ "Ensures", "get", "works", "as", "expected." ]
def todo_test_get(self): self.fail()
['def', 'todo_test_get(self):', 'self.fail()']
619,140
omonimus1/super-computer-
Traditional.py
REParser.lookahead
lookahead
Look ahead n chars.
[ "Look", "ahead", "n", "chars." ]
def lookahead(self, n): j = self.i + n if j < len(self.s): return self.s[j] else: return ''
['def', 'lookahead(self,', 'n):', 'j', '=', 'self.i', '+', 'n', 'if', 'j', '<', 'len(self.s):', 'return', 'self.s[j]', 'else:', 'return', "''"]
912,987
caiiiac/Machine-Learning-with-Python
mathtext.py
Accent.render
render
Render the character to the canvas.
[ "Render", "the", "character", "to", "the", "canvas." ]
def render(self, x, y): self.font_output.render_glyph(x - self._metrics.xmin, y + self._metrics.ymin, self.font, self.font_class, self.c, self.fontsize, self.dpi)
['def', 'render(self,', 'x,', 'y):', 'self.font_output.render_glyph(x', '-', 'self._metrics.xmin,', 'y', '+', 'self._metrics.ymin,', 'self.font,', 'self.font_class,', 'self.c,', 'self.fontsize,', 'self.dpi)']
715,611
intel/neural-compressor
pruning.py
Pruning.on_after_eval
on_after_eval
Functions called in the end of evaluation.
[ "Functions", "called", "in", "the", "end", "of", "evaluation." ]
def on_after_eval(self): for pruner in self.pruners: pruner.on_after_eval()
['def', 'on_after_eval(self):', 'for', 'pruner', 'in', 'self.pruners:', 'pruner.on_after_eval()']
738,708
gunthercox/ChatterBot
tests.py
test_odd
test_odd
Return true if the variable is odd.
[ "Return", "true", "if", "the", "variable", "is", "odd." ]
def test_odd(value): return value % 2 == 1
['def', 'test_odd(value):', 'return', 'value', '%', '2', '==', '1']
479,338
deepmind/pycolab
sequence_recall.py
make_game
make_game
Builds and returns a sequence_recall game.
[ "Builds", "and", "returns", "a", "sequence_recall", "game." ]
def make_game(sequence_length=4, demo_light_on_frames=60, demo_light_off_frames=30, pause_frames=30, timeout_frames=-1): program = _make_program(sequence_length, demo_light_on_frames, demo_light_off_frames, pause_frames) engine = ascii_art.ascii_art_to_game(GAME_ART, what_lies_beneath=' ', sprites={'P': PlayerS...
['def', 'make_game(sequence_length=4,', 'demo_light_on_frames=60,', 'demo_light_off_frames=30,', 'pause_frames=30,', 'timeout_frames=-1):', 'program', '=', '_make_program(sequence_length,', 'demo_light_on_frames,', 'demo_light_off_frames,', 'pause_frames)', 'engine', '=', 'ascii_art.ascii_art_to_game(GAME_ART,', "what_...
819,270
weimin17/Object-Detection_HelmetDetection
gamma_l1_regularizer.py
GammaL1RegularizerFactory.create_regularizer
create_regularizer
Creates a GammaL1Regularizer for `op`.
[ "Creates", "a", "GammaL1Regularizer", "for", "`op`." ]
def create_regularizer(self, op, opreg_manager): gamma = self._gamma_conv_mapper.get_gamma(op) if gamma is None: regularizer = None else: regularizer = GammaL1Regularizer(gamma, self._gamma_threshold) if op.type == 'DepthwiseConv2dNative': regularizer = _group_depthwise_conv_regu...
['def', 'create_regularizer(self,', 'op,', 'opreg_manager):', 'gamma', '=', 'self._gamma_conv_mapper.get_gamma(op)', 'if', 'gamma', 'is', 'None:', 'regularizer', '=', 'None', 'else:', 'regularizer', '=', 'GammaL1Regularizer(gamma,', 'self._gamma_threshold)', 'if', 'op.type', '==', "'DepthwiseConv2dNative':", 'regulariz...
758,241
IntelLabs/coach
kubernetes_orchestrator.py
Kubernetes.trainer_logs
trainer_logs
Get the logs from trainer.
[ "Get", "the", "logs", "from", "trainer." ]
def trainer_logs(self): trainer_params = self.params.run_type_params.get(str(RunType.TRAINER), None) if not trainer_params: return api_client = k8sclient.CoreV1Api() pod = None try: pods = api_client.list_namespaced_pod(self.params.namespace, label_selector='app={}'.format(trainer_pa...
['def', 'trainer_logs(self):', 'trainer_params', '=', 'self.params.run_type_params.get(str(RunType.TRAINER),', 'None)', 'if', 'not', 'trainer_params:', 'return', 'api_client', '=', 'k8sclient.CoreV1Api()', 'pod', '=', 'None', 'try:', 'pods', '=', 'api_client.list_namespaced_pod(self.params.namespace,', "label_selector=...
124,637
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar10_model.py
ResNetCifar10.forward_pass
forward_pass
Build the core model within the graph.
[ "Build", "the", "core", "model", "within", "the", "graph." ]
def forward_pass(self, x, input_data_format='channels_last'): if self._data_format != input_data_format: if input_data_format == 'channels_last': x = tf.transpose(x, [0, 3, 1, 2]) else: x = tf.transpose(x, [0, 2, 3, 1]) x = x / 128 - 1 x = self._conv(x, 3, 16, 1) ...
['def', 'forward_pass(self,', 'x,', "input_data_format='channels_last'):", 'if', 'self._data_format', '!=', 'input_data_format:', 'if', 'input_data_format', '==', "'channels_last':", 'x', '=', 'tf.transpose(x,', '[0,', '3,', '1,', '2])', 'else:', 'x', '=', 'tf.transpose(x,', '[0,', '2,', '3,', '1])', 'x', '=', 'x', '/'...
113,178
lebrice/Sequoia
multihead_classifier.py
MultiHeadClassifier.task_inference_forward_pass
task_inference_forward_pass
Forward pass with a simple form of task inference.
[ "Forward", "pass", "with", "a", "simple", "form", "of", "task", "inference." ]
def task_inference_forward_pass(self, observations: Observations) -> Tensor: assert observations.task_labels is None B = observations.x.shape[0] T = n_known_tasks = len(self.output_heads) N = self.n_classes known_task_ids: list[int] = list(range(n_known_tasks)) assert known_task_ids task_out...
['def', 'task_inference_forward_pass(self,', 'observations:', 'Observations)', '->', 'Tensor:', 'assert', 'observations.task_labels', 'is', 'None', 'B', '=', 'observations.x.shape[0]', 'T', '=', 'n_known_tasks', '=', 'len(self.output_heads)', 'N', '=', 'self.n_classes', 'known_task_ids:', 'list[int]', '=', 'list(range(...
344,035
ZhAnGToNG1/transfer_learning_cspt
test_neck.py
fpn_neck_config
fpn_neck_config
Return the class containing the corresponding attributes according to the fpn_test_step_names.
[ "Return", "the", "class", "containing", "the", "corresponding", "attributes", "according", "to", "the", "fpn_test_step_names." ]
def fpn_neck_config(test_step_name): s = 64 in_channels = [8, 16, 32, 64] feat_sizes = [s // 2 ** i for i in range(4)] out_channels = 8 feats = [torch.rand(1, in_channels[i], feat_sizes[i], feat_sizes[i]) for i in range(len(in_channels))] if fpn_test_step_names[test_step_name] == 0: fpn_...
['def', 'fpn_neck_config(test_step_name):', 's', '=', '64', 'in_channels', '=', '[8,', '16,', '32,', '64]', 'feat_sizes', '=', '[s', '//', '2', '**', 'i', 'for', 'i', 'in', 'range(4)]', 'out_channels', '=', '8', 'feats', '=', '[torch.rand(1,', 'in_channels[i],', 'feat_sizes[i],', 'feat_sizes[i])', 'for', 'i', 'in', 'ra...
964,372