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 |
|---|---|---|---|---|---|---|---|---|
veseln/Neat-EO.pink | tiles.py | tile_image_to_file | tile_image_to_file | Write an image tile on disk. | [
"Write",
"an",
"image",
"tile",
"on",
"disk."
] | def tile_image_to_file(root, tile, image, ext=None):
(H, W, C) = image.shape
root = os.path.expanduser(root)
path = os.path.join(root, str(tile.z), str(tile.x)) if isinstance(tile, mercantile.Tile) else root
os.makedirs(path, exist_ok=True)
if C == 1:
ext = 'png'
elif C == 3:
ext... | ['def', 'tile_image_to_file(root,', 'tile,', 'image,', 'ext=None):', '(H,', 'W,', 'C)', '=', 'image.shape', 'root', '=', 'os.path.expanduser(root)', 'path', '=', 'os.path.join(root,', 'str(tile.z),', 'str(tile.x))', 'if', 'isinstance(tile,', 'mercantile.Tile)', 'else', 'root', 'os.makedirs(path,', 'exist_ok=True)', 'if... | 735,296 |
DomingosGustavo/OCVBot | behavior.py | wait_rand | wait_rand | Roll for a chance to do nothing for the specified period of time. | [
"Roll",
"for",
"a",
"chance",
"to",
"do",
"nothing",
"for",
"the",
"specified",
"period",
"of",
"time."
] | def wait_rand(chance, second_chance=10, wait_min=10000, wait_max=60000):
wait_roll = rand.randint(1, chance)
if wait_roll == chance:
log.info('Random wait called.')
sleeptime = misc.rand_seconds(wait_min, wait_max)
log.info('Sleeping for ' + str(round(sleeptime)) + ' seconds.')
t... | ['def', 'wait_rand(chance,', 'second_chance=10,', 'wait_min=10000,', 'wait_max=60000):', 'wait_roll', '=', 'rand.randint(1,', 'chance)', 'if', 'wait_roll', '==', 'chance:', "log.info('Random", 'wait', "called.')", 'sleeptime', '=', 'misc.rand_seconds(wait_min,', 'wait_max)', "log.info('Sleeping", 'for', "'", '+', 'str(... | 755,183 |
CosmiQ/solaris | test_datagen.py | TestInferenceTiler.test_simple_geotiff_tile | test_simple_geotiff_tile | Test tiling a geotiff without overlap. | [
"Test",
"tiling",
"a",
"geotiff",
"without",
"overlap."
] | def test_simple_geotiff_tile(self):
inf_tiler = InferenceTiler('keras', 250, 250)
(tiles, tile_inds, _) = inf_tiler(os.path.join(data_dir, 'sample_geotiff.tif'))
expected_tiles = np.load(os.path.join(data_dir, 'inference_tiler_test_output.npy'))
expected_tile_inds = [(0, 0), (0, 250), (0, 500), (0, 650)... | ['def', 'test_simple_geotiff_tile(self):', 'inf_tiler', '=', "InferenceTiler('keras',", '250,', '250)', '(tiles,', 'tile_inds,', '_)', '=', 'inf_tiler(os.path.join(data_dir,', "'sample_geotiff.tif'))", 'expected_tiles', '=', 'np.load(os.path.join(data_dir,', "'inference_tiler_test_output.npy'))", 'expected_tile_inds', ... | 879,449 |
QinganZhao/Deep-Learning-Based-Structural-Damage-Detection | coord_map.py | inverse | inverse | Invert a coord map by de-scaling and un-shifting; this gives the backward mapping for the gradient. | [
"Invert",
"a",
"coord",
"map",
"by",
"de-scaling",
"and",
"un-shifting;",
"this",
"gives",
"the",
"backward",
"mapping",
"for",
"the",
"gradient."
] | def inverse(coord_map):
(ax, a, b) = coord_map
return (ax, 1 / a, -b / a) | ['def', 'inverse(coord_map):', '(ax,', 'a,', 'b)', '=', 'coord_map', 'return', '(ax,', '1', '/', 'a,', '-b', '/', 'a)'] | 127,465 |
sek788432/Waymo-2D-Object-Detection | ddpg_agent.py | DdpgAgent.actor_net | actor_net | Returns the output of the actor network. | [
"Returns",
"the",
"output",
"of",
"the",
"actor",
"network."
] | def actor_net(self, states, stop_gradients=False):
self._validate_states(states)
actions = self._actor_net(states, self._action_spec)
if stop_gradients:
actions = tf.stop_gradient(actions)
return actions | ['def', 'actor_net(self,', 'states,', 'stop_gradients=False):', 'self._validate_states(states)', 'actions', '=', 'self._actor_net(states,', 'self._action_spec)', 'if', 'stop_gradients:', 'actions', '=', 'tf.stop_gradient(actions)', 'return', 'actions'] | 974,350 |
apeterswu/RL4NMT | text_encoder.py | SubwordTextEncoder.encode | encode | Converts a native string to a list of subtoken ids. | [
"Converts",
"a",
"native",
"string",
"to",
"a",
"list",
"of",
"subtoken",
"ids."
] | def encode(self, raw_text):
return self._tokens_to_subtoken_ids(tokenizer.encode(native_to_unicode(raw_text))) | ['def', 'encode(self,', 'raw_text):', 'return', 'self._tokens_to_subtoken_ids(tokenizer.encode(native_to_unicode(raw_text)))'] | 330,920 |
QData/deepWordBug | datetime.py | timedelta.total_seconds | total_seconds | Total seconds in the duration. | [
"Total",
"seconds",
"in",
"the",
"duration."
] | def total_seconds(self):
return ((self.days * 86400 + self.seconds) * 10 ** 6 + self.microseconds) / 10 ** 6 | ['def', 'total_seconds(self):', 'return', '((self.days', '*', '86400', '+', 'self.seconds)', '*', '10', '**', '6', '+', 'self.microseconds)', '/', '10', '**', '6'] | 543,012 |
triaquae/triaquae | __init__.py | BaseDatabaseWrapper.abort | abort | Roll back any ongoing transaction and clean the transaction state stack. | [
"Roll",
"back",
"any",
"ongoing",
"transaction",
"and",
"clean",
"the",
"transaction",
"state",
"stack."
] | def abort(self):
if self._dirty:
self._rollback()
self._dirty = False
while self.transaction_state:
self.leave_transaction_management() | ['def', 'abort(self):', 'if', 'self._dirty:', 'self._rollback()', 'self._dirty', '=', 'False', 'while', 'self.transaction_state:', 'self.leave_transaction_management()'] | 423,298 |
rudranil723/mini-main | __init__.py | DesignSpaceDocument.newSourceDescriptor | newSourceDescriptor | Ask the writer class to make us a new sourceDescriptor. | [
"Ask",
"the",
"writer",
"class",
"to",
"make",
"us",
"a",
"new",
"sourceDescriptor."
] | def newSourceDescriptor(self):
return self.writerClass.getSourceDescriptor() | ['def', 'newSourceDescriptor(self):', 'return', 'self.writerClass.getSourceDescriptor()'] | 317,051 |
QData/deepWordBug | io.py | Pump.is_done | is_done | Returns True if the read stream is done (either it's returned EOF or the pump doesn't have wait_for_output set), and the write side does not have pending bytes to send. | [
"Returns",
"True",
"if",
"the",
"read",
"stream",
"is",
"done",
"(either",
"it's",
"returned",
"EOF",
"or",
"the",
"pump",
"doesn't",
"have",
"wait_for_output",
"set),",
"and",
"the",
"write",
"side",
"does",
"not",
"have",
"pending",
"bytes",
"to",
"send."
... | def is_done(self):
return (not self.wait_for_output or self.eof) and (not (hasattr(self.to_stream, 'needs_write') and self.to_stream.needs_write())) | ['def', 'is_done(self):', 'return', '(not', 'self.wait_for_output', 'or', 'self.eof)', 'and', '(not', '(hasattr(self.to_stream,', "'needs_write')", 'and', 'self.to_stream.needs_write()))'] | 541,970 |
anuragranj/coma | coarsening.py | compute_perm | compute_perm | Return a list of indices to reorder the adjacency and data matrices so that the union of two neighbors from layer to layer forms a binary tree. | [
"Return",
"a",
"list",
"of",
"indices",
"to",
"reorder",
"the",
"adjacency",
"and",
"data",
"matrices",
"so",
"that",
"the",
"union",
"of",
"two",
"neighbors",
"from",
"layer",
"to",
"layer",
"forms",
"a",
"binary",
"tree."
] | def compute_perm(parents):
indices = []
if len(parents) > 0:
M_last = max(parents[-1]) + 1
indices.append(list(range(M_last)))
for parent in parents[::-1]:
pool_singeltons = len(parent)
indices_layer = []
for i in indices[-1]:
indices_node = list(np.where(... | ['def', 'compute_perm(parents):', 'indices', '=', '[]', 'if', 'len(parents)', '>', '0:', 'M_last', '=', 'max(parents[-1])', '+', '1', 'indices.append(list(range(M_last)))', 'for', 'parent', 'in', 'parents[::-1]:', 'pool_singeltons', '=', 'len(parent)', 'indices_layer', '=', '[]', 'for', 'i', 'in', 'indices[-1]:', 'indi... | 467,087 |
Katja-M/Python_NaturalLanguageProcessing | verbnet.py | VerbnetCorpusReader.wordnetids | wordnetids | Return a list of all wordnet identifiers that appear in any class, or in ``classid`` if specified. | [
"Return",
"a",
"list",
"of",
"all",
"wordnet",
"identifiers",
"that",
"appear",
"in",
"any",
"class,",
"or",
"in",
"``classid``",
"if",
"specified."
] | def wordnetids(self, vnclass=None):
if vnclass is None:
return sorted(self._wordnet_to_class.keys())
else:
if isinstance(vnclass, string_types):
vnclass = self.vnclass(vnclass)
return sum([member.get('wn', '').split() for member in vnclass.findall('MEMBERS/MEMBER')], []) | ['def', 'wordnetids(self,', 'vnclass=None):', 'if', 'vnclass', 'is', 'None:', 'return', 'sorted(self._wordnet_to_class.keys())', 'else:', 'if', 'isinstance(vnclass,', 'string_types):', 'vnclass', '=', 'self.vnclass(vnclass)', 'return', "sum([member.get('wn',", "'').split()", 'for', 'member', 'in', "vnclass.findall('MEM... | 866,317 |
microsoft/nlp-recipes | abstractive_summarization_seq2seq.py | S2SAbsSumProcessor.s2s_dataset_from_iterable_sum_ds | s2s_dataset_from_iterable_sum_ds | Converts IterableSummarizationDataset to S2SAbsSumDataset. | [
"Converts",
"IterableSummarizationDataset",
"to",
"S2SAbsSumDataset."
] | def s2s_dataset_from_iterable_sum_ds(self, sum_ds, train_mode, cached_features_file=None, local_rank=-1, top_n=-1):
examples = []
if train_mode:
for (source, target) in zip(sum_ds, sum_ds.get_target()):
examples.append({'src': source, 'tgt': target})
else:
for source in sum_ds:
... | ['def', 's2s_dataset_from_iterable_sum_ds(self,', 'sum_ds,', 'train_mode,', 'cached_features_file=None,', 'local_rank=-1,', 'top_n=-1):', 'examples', '=', '[]', 'if', 'train_mode:', 'for', '(source,', 'target)', 'in', 'zip(sum_ds,', 'sum_ds.get_target()):', "examples.append({'src':", 'source,', "'tgt':", 'target})', 'e... | 731,289 |
akandykeller/NeuralWaveMachines | dynamics.py | PhysicsSimulationNetwork.momentum_from_velocity | momentum_from_velocity | Computes the momentum from position and velocity. | [
"Computes",
"the",
"momentum",
"from",
"position",
"and",
"velocity."
] | def momentum_from_velocity(self, q: jnp.ndarray, q_dot: jnp.ndarray, **kwargs) -> jnp.ndarray:
def local_lagrangian(q_dot_):
return jnp.sum(self.lagrangian(phase_space.PhaseSpace(q, q_dot_), **kwargs))
return jax.grad(local_lagrangian)(q_dot) | ['def', 'momentum_from_velocity(self,', 'q:', 'jnp.ndarray,', 'q_dot:', 'jnp.ndarray,', '**kwargs)', '->', 'jnp.ndarray:', 'def', 'local_lagrangian(q_dot_):', 'return', 'jnp.sum(self.lagrangian(phase_space.PhaseSpace(q,', 'q_dot_),', '**kwargs))', 'return', 'jax.grad(local_lagrangian)(q_dot)'] | 293,675 |
zihuitang/medical_AI_platform | operator.py | xor | xor | Same as a ^ b. | [
"Same",
"as",
"a",
"^",
"b."
] | def xor(a, b):
return a ^ b | ['def', 'xor(a,', 'b):', 'return', 'a', '^', 'b'] | 280,897 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | neural_gpu.py | layer_norm | layer_norm | Layer normalize the 4D tensor x, averaging over the last dimension. | [
"Layer",
"normalize",
"the",
"4D",
"tensor",
"x,",
"averaging",
"over",
"the",
"last",
"dimension."
] | def layer_norm(x, nmaps, prefix, epsilon=1e-05):
with tf.variable_scope(prefix):
scale = tf.get_variable('layer_norm_scale', [nmaps], initializer=tf.ones_initializer())
bias = tf.get_variable('layer_norm_bias', [nmaps], initializer=tf.zeros_initializer())
(mean, variance) = tf.nn.moments(x, ... | ['def', 'layer_norm(x,', 'nmaps,', 'prefix,', 'epsilon=1e-05):', 'with', 'tf.variable_scope(prefix):', 'scale', '=', "tf.get_variable('layer_norm_scale',", '[nmaps],', 'initializer=tf.ones_initializer())', 'bias', '=', "tf.get_variable('layer_norm_bias',", '[nmaps],', 'initializer=tf.zeros_initializer())', '(mean,', 'v... | 50,118 |
scotthuang1989/object_detection_with_tensorflow | distributions.py | LearnableAutoRegressive1Prior.logp_t | logp_t | Compute the log-likelihood under the distribution for a given time t, not the whole sequence. | [
"Compute",
"the",
"log-likelihood",
"under",
"the",
"distribution",
"for",
"a",
"given",
"time",
"t,",
"not",
"the",
"whole",
"sequence."
] | def logp_t(self, z_t_bxu, z_tm1_bxu=None):
if z_tm1_bxu is None:
return diag_gaussian_log_likelihood(z_t_bxu, self.pmeans_bxu, self.logpvars_bxu)
else:
means_t_bxu = self.pmeans_bxu + self.phis_bxu * z_tm1_bxu
logp_tgtm1_bxu = diag_gaussian_log_likelihood(z_t_bxu, means_t_bxu, self.logev... | ['def', 'logp_t(self,', 'z_t_bxu,', 'z_tm1_bxu=None):', 'if', 'z_tm1_bxu', 'is', 'None:', 'return', 'diag_gaussian_log_likelihood(z_t_bxu,', 'self.pmeans_bxu,', 'self.logpvars_bxu)', 'else:', 'means_t_bxu', '=', 'self.pmeans_bxu', '+', 'self.phis_bxu', '*', 'z_tm1_bxu', 'logp_tgtm1_bxu', '=', 'diag_gaussian_log_likelih... | 739,034 |
jimtin/Stock_Comparison | graph_objs.py | PlotlyDict.force_clean | force_clean | Recursively remove empty/None values. | [
"Recursively",
"remove",
"empty/None",
"values."
] | def force_clean(self, **kwargs):
keys = list(self.keys())
for key in keys:
try:
self[key].force_clean()
except AttributeError:
pass
if isinstance(self[key], (dict, list)):
if len(self[key]) == 0:
del self[key]
elif self[key] is ... | ['def', 'force_clean(self,', '**kwargs):', 'keys', '=', 'list(self.keys())', 'for', 'key', 'in', 'keys:', 'try:', 'self[key].force_clean()', 'except', 'AttributeError:', 'pass', 'if', 'isinstance(self[key],', '(dict,', 'list)):', 'if', 'len(self[key])', '==', '0:', 'del', 'self[key]', 'elif', 'self[key]', 'is', 'None:'... | 389,231 |
MycroftAI/mycroft-core | event_scheduler.py | EventScheduler.update_event_handler | update_event_handler | Messagebus interface to the update_event method. | [
"Messagebus",
"interface",
"to",
"the",
"update_event",
"method."
] | def update_event_handler(self, message):
event = message.data.get('event')
data = message.data.get('data')
self.update_event(event, data) | ['def', 'update_event_handler(self,', 'message):', 'event', '=', "message.data.get('event')", 'data', '=', "message.data.get('data')", 'self.update_event(event,', 'data)'] | 290,460 |
43Carrig/recurrent_neural_networks_practice | function.py | _DefinedFunction.captured_inputs | captured_inputs | Returns the list of implicitly captured inputs. | [
"Returns",
"the",
"list",
"of",
"implicitly",
"captured",
"inputs."
] | def captured_inputs(self):
self._create_definition_if_needed()
return self._extra_inputs | ['def', 'captured_inputs(self):', 'self._create_definition_if_needed()', 'return', 'self._extra_inputs'] | 336,301 |
facebookresearch/CompilerGym | llvm.py | llvm_opt | llvm_opt | Test fixture that yields the path of opt. | [
"Test",
"fixture",
"that",
"yields",
"the",
"path",
"of",
"opt."
] | def llvm_opt() -> Path:
return llvm.opt_path() | ['def', 'llvm_opt()', '->', 'Path:', 'return', 'llvm.opt_path()'] | 135,899 |
RasaHQ/rasa | test_features.py | test_for_features_fingerprinting_collisions | test_for_features_fingerprinting_collisions | Tests that features fingerprints are unique. | [
"Tests",
"that",
"features",
"fingerprints",
"are",
"unique."
] | def test_for_features_fingerprinting_collisions():
m1 = np.asarray([[0.5, 3.1, 3.0], [1.1, 1.2, 1.3], [4.7, 0.3, 2.7]])
m2 = np.asarray([[0, 0, 0], [1, 2, 3], [0, 0, 1]])
dense_features = [Features(m1, FEATURE_TYPE_SENTENCE, TEXT, 'CountVectorsFeaturizer'), Features(m2, FEATURE_TYPE_SENTENCE, TEXT, 'CountVe... | ['def', 'test_for_features_fingerprinting_collisions():', 'm1', '=', 'np.asarray([[0.5,', '3.1,', '3.0],', '[1.1,', '1.2,', '1.3],', '[4.7,', '0.3,', '2.7]])', 'm2', '=', 'np.asarray([[0,', '0,', '0],', '[1,', '2,', '3],', '[0,', '0,', '1]])', 'dense_features', '=', '[Features(m1,', 'FEATURE_TYPE_SENTENCE,', 'TEXT,', "... | 838,099 |
rudranil723/mini-main | excelRTDServer.py | RTDTopic.Reset | Reset | Call when this topic isn't considered "dirty" anymore. | [
"Call",
"when",
"this",
"topic",
"isn't",
"considered",
"\"dirty\"",
"anymore."
] | def Reset(self):
self.__dirty = False | ['def', 'Reset(self):', 'self.__dirty', '=', 'False'] | 271,196 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | ctx.py | RequestContext.match_request | match_request | Can be overridden by a subclass to hook into the matching of the request. | [
"Can",
"be",
"overridden",
"by",
"a",
"subclass",
"to",
"hook",
"into",
"the",
"matching",
"of",
"the",
"request."
] | def match_request(self):
try:
result = self.url_adapter.match(return_rule=True)
(self.request.url_rule, self.request.view_args) = result
except HTTPException as e:
self.request.routing_exception = e | ['def', 'match_request(self):', 'try:', 'result', '=', 'self.url_adapter.match(return_rule=True)', '(self.request.url_rule,', 'self.request.view_args)', '=', 'result', 'except', 'HTTPException', 'as', 'e:', 'self.request.routing_exception', '=', 'e'] | 102,020 |
ludwig-ai/ludwig | utils.py | delete_hyperopt_outputs | delete_hyperopt_outputs | Deletes outputs of the hyperopt run that we don't want to save with the artifacts. | [
"Deletes",
"outputs",
"of",
"the",
"hyperopt",
"run",
"that",
"we",
"don't",
"want",
"to",
"save",
"with",
"the",
"artifacts."
] | def delete_hyperopt_outputs(output_directory: str):
for (path, currentDirectory, files) in os.walk(output_directory):
for file in files:
filename = os.path.join(path, file)
if file not in HYPEROPT_OUTDIR_RETAINED_FILES:
os.remove(filename) | ['def', 'delete_hyperopt_outputs(output_directory:', 'str):', 'for', '(path,', 'currentDirectory,', 'files)', 'in', 'os.walk(output_directory):', 'for', 'file', 'in', 'files:', 'filename', '=', 'os.path.join(path,', 'file)', 'if', 'file', 'not', 'in', 'HYPEROPT_OUTDIR_RETAINED_FILES:', 'os.remove(filename)'] | 616,545 |
open-mmlab/mmselfsup | processing.py | RandomPatchWithLabels.transform | transform | Apply random patch augmentation to the given image. | [
"Apply",
"random",
"patch",
"augmentation",
"to",
"the",
"given",
"image."
] | def transform(self, results: dict) -> dict:
img = results['img']
(patches, patches_pos) = self._image_to_patches(img)
patches_pos = np.stack(patches_pos, axis=0)
multi_views = []
multi_views.append(patches[4])
for i in range(9):
if i != 4:
multi_views.append(patches[i])
p... | ['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'img', '=', "results['img']", '(patches,', 'patches_pos)', '=', 'self._image_to_patches(img)', 'patches_pos', '=', 'np.stack(patches_pos,', 'axis=0)', 'multi_views', '=', '[]', 'multi_views.append(patches[4])', 'for', 'i', 'in', 'range(9):', 'if', 'i', '!='... | 240,310 |
facebookresearch/Detectron | test.py | im_detect_keypoints_scale | im_detect_keypoints_scale | Computes keypoint predictions at the given scale. | [
"Computes",
"keypoint",
"predictions",
"at",
"the",
"given",
"scale."
] | def im_detect_keypoints_scale(model, im, target_scale, target_max_size, boxes, hflip=False):
if hflip:
heatmaps_scl = im_detect_keypoints_hflip(model, im, target_scale, target_max_size, boxes)
else:
im_scale = im_conv_body_only(model, im, target_scale, target_max_size)
heatmaps_scl = im_... | ['def', 'im_detect_keypoints_scale(model,', 'im,', 'target_scale,', 'target_max_size,', 'boxes,', 'hflip=False):', 'if', 'hflip:', 'heatmaps_scl', '=', 'im_detect_keypoints_hflip(model,', 'im,', 'target_scale,', 'target_max_size,', 'boxes)', 'else:', 'im_scale', '=', 'im_conv_body_only(model,', 'im,', 'target_scale,', ... | 538,791 |
deepmind/pycolab | box_world.py | make_game | make_game | Create a new Box-World game. | [
"Create",
"a",
"new",
"Box-World",
"game."
] | def make_game(grid_size, solution_length, num_forward, num_backward, branch_length, random_state=None, max_num_steps=120):
if random_state is None:
random_state = np.random.RandomState(None)
game = False
tries = 0
while tries < MAX_GENERATION_TRIES and (not game):
game = _generate_random... | ['def', 'make_game(grid_size,', 'solution_length,', 'num_forward,', 'num_backward,', 'branch_length,', 'random_state=None,', 'max_num_steps=120):', 'if', 'random_state', 'is', 'None:', 'random_state', '=', 'np.random.RandomState(None)', 'game', '=', 'False', 'tries', '=', '0', 'while', 'tries', '<', 'MAX_GENERATION_TRI... | 819,267 |
43Carrig/recurrent_neural_networks_practice | execution_callbacks.py | nan_callback | nan_callback | A specialization of `inf_nan_callback` that checks for `nan`s only. | [
"A",
"specialization",
"of",
"`inf_nan_callback`",
"that",
"checks",
"for",
"`nan`s",
"only."
] | def nan_callback(op_type, inputs, attrs, outputs, op_name, action=_DEFAULT_CALLBACK_ACTION):
inf_nan_callback(op_type, inputs, attrs, outputs, op_name, check_inf=False, check_nan=True, action=action) | ['def', 'nan_callback(op_type,', 'inputs,', 'attrs,', 'outputs,', 'op_name,', 'action=_DEFAULT_CALLBACK_ACTION):', 'inf_nan_callback(op_type,', 'inputs,', 'attrs,', 'outputs,', 'op_name,', 'check_inf=False,', 'check_nan=True,', 'action=action)'] | 336,136 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | mock.py | _Call.call_list | call_list | For a call object that represents multiple calls, `call_list` returns a list of all the intermediate calls as well as the final call. | [
"For",
"a",
"call",
"object",
"that",
"represents",
"multiple",
"calls,",
"`call_list`",
"returns",
"a",
"list",
"of",
"all",
"the",
"intermediate",
"calls",
"as",
"well",
"as",
"the",
"final",
"call."
] | def call_list(self):
vals = []
thing = self
while thing is not None:
if thing.from_kall:
vals.append(thing)
thing = thing.parent
return _CallList(reversed(vals)) | ['def', 'call_list(self):', 'vals', '=', '[]', 'thing', '=', 'self', 'while', 'thing', 'is', 'not', 'None:', 'if', 'thing.from_kall:', 'vals.append(thing)', 'thing', '=', 'thing.parent', 'return', '_CallList(reversed(vals))'] | 377,148 |
zihuitang/medical_AI_platform | tix.py | Tree.close | close | Close the entry given by entryPath if its mode is close. | [
"Close",
"the",
"entry",
"given",
"by",
"entryPath",
"if",
"its",
"mode",
"is",
"close."
] | def close(self, entrypath):
self.tk.call(self._w, 'close', entrypath) | ['def', 'close(self,', 'entrypath):', 'self.tk.call(self._w,', "'close',", 'entrypath)'] | 283,914 |
weimin17/Object-Detection_HelmetDetection | configurations.py | base | base | Base config for a fully connected model with a single global view. | [
"Base",
"config",
"for",
"a",
"fully",
"connected",
"model",
"with",
"a",
"single",
"global",
"view."
] | def base():
config = parent_configs.base()
config['hparams']['time_series_hidden'] = {'global_view': {'num_local_layers': 0, 'local_layer_size': 128, 'translation_delta': 0, 'pooling_type': 'max', 'dropout_rate': 0.0}}
return config | ['def', 'base():', 'config', '=', 'parent_configs.base()', "config['hparams']['time_series_hidden']", '=', "{'global_view':", "{'num_local_layers':", '0,', "'local_layer_size':", '128,', "'translation_delta':", '0,', "'pooling_type':", "'max',", "'dropout_rate':", '0.0}}', 'return', 'config'] | 761,557 |
hamza-murad/AALU | assistant_v1.py | DialogSuggestion.from_dict | from_dict | Initialize a DialogSuggestion object from a json dictionary. | [
"Initialize",
"a",
"DialogSuggestion",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'DialogSuggestion':
args = {}
valid_keys = ['label', 'value', 'output', 'dialog_node']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class DialogSuggestion: ' + ', '.join(bad_keys))
... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'DialogSuggestion':", 'args', '=', '{}', 'valid_keys', '=', "['label',", "'value',", "'output',", "'dialog_node']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'diction... | 5,208 |
songyanho/Reinforcement-Learning-for-Self-Driving-Cars | cnn.py | Cnn.close | close | Close the TensorFlow session. | [
"Close",
"the",
"TensorFlow",
"session."
] | def close(self):
self.session.close() | ['def', 'close(self):', 'self.session.close()'] | 340,809 |
matsu0228/nlp-jp | test_ldavowpalwabbit_wrapper.py | TestLdaVowpalWabbit.test_save_load | test_save_load | Test loading/saving LdaVowpalWabbit model. | [
"Test",
"loading/saving",
"LdaVowpalWabbit",
"model."
] | def test_save_load(self):
if not self.vw_path:
return
lda = LdaVowpalWabbit(self.vw_path, corpus=self.corpus, passes=10, chunksize=256, id2word=self.dictionary, cleanup_files=True, alpha=0.1, eta=0.1, num_topics=len(TOPIC_WORDS), random_seed=1)
with tempfile.NamedTemporaryFile() as fhandle:
... | ['def', 'test_save_load(self):', 'if', 'not', 'self.vw_path:', 'return', 'lda', '=', 'LdaVowpalWabbit(self.vw_path,', 'corpus=self.corpus,', 'passes=10,', 'chunksize=256,', 'id2word=self.dictionary,', 'cleanup_files=True,', 'alpha=0.1,', 'eta=0.1,', 'num_topics=len(TOPIC_WORDS),', 'random_seed=1)', 'with', 'tempfile.Na... | 786,121 |
devashish-patel/webcam-motion-detector | util.py | server_url_for_websocket_url | server_url_for_websocket_url | Convert an ``ws(s)`` URL for a Bokeh server into the appropriate ``http(s)`` URL for the websocket endpoint. | [
"Convert",
"an",
"``ws(s)``",
"URL",
"for",
"a",
"Bokeh",
"server",
"into",
"the",
"appropriate",
"``http(s)``",
"URL",
"for",
"the",
"websocket",
"endpoint."
] | def server_url_for_websocket_url(url):
if url.startswith('ws:'):
reprotocoled = 'http' + url[2:]
elif url.startswith('wss:'):
reprotocoled = 'https' + url[3:]
else:
raise ValueError('URL has non-websocket protocol ' + url)
if not reprotocoled.endswith('/ws'):
raise ValueE... | ['def', 'server_url_for_websocket_url(url):', 'if', "url.startswith('ws:'):", 'reprotocoled', '=', "'http'", '+', 'url[2:]', 'elif', "url.startswith('wss:'):", 'reprotocoled', '=', "'https'", '+', 'url[3:]', 'else:', 'raise', "ValueError('URL", 'has', 'non-websocket', 'protocol', "'", '+', 'url)', 'if', 'not', "reproto... | 977,183 |
zxj32/uncertainty-GNN | layers.py | sparse_dropout | sparse_dropout | Dropout for sparse tensors. | [
"Dropout",
"for",
"sparse",
"tensors."
] | def sparse_dropout(x, keep_prob, noise_shape):
random_tensor = keep_prob
random_tensor += tf.random_uniform(noise_shape)
dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool)
pre_out = tf.sparse_retain(x, dropout_mask)
return pre_out * (1.0 / keep_prob) | ['def', 'sparse_dropout(x,', 'keep_prob,', 'noise_shape):', 'random_tensor', '=', 'keep_prob', 'random_tensor', '+=', 'tf.random_uniform(noise_shape)', 'dropout_mask', '=', 'tf.cast(tf.floor(random_tensor),', 'dtype=tf.bool)', 'pre_out', '=', 'tf.sparse_retain(x,', 'dropout_mask)', 'return', 'pre_out', '*', '(1.0', '/'... | 378,020 |
deepmind/acme | helpers.py | make_multigrid_dqn_networks | make_multigrid_dqn_networks | Returns DQN networks used by the agent in the multigrid environment. | [
"Returns",
"DQN",
"networks",
"used",
"by",
"the",
"agent",
"in",
"the",
"multigrid",
"environment."
] | def make_multigrid_dqn_networks(environment_spec: specs.EnvironmentSpec) -> networks_lib.FeedForwardNetwork:
assert np.issubdtype(environment_spec.actions.dtype, np.integer), f'Expected multigrid environment to have discrete actions with int dtype but environment_spec.actions.dtype == {environment_spec.actions.dtyp... | ['def', 'make_multigrid_dqn_networks(environment_spec:', 'specs.EnvironmentSpec)', '->', 'networks_lib.FeedForwardNetwork:', 'assert', 'np.issubdtype(environment_spec.actions.dtype,', 'np.integer),', "f'Expected", 'multigrid', 'environment', 'to', 'have', 'discrete', 'actions', 'with', 'int', 'dtype', 'but', 'environme... | 8,518 |
Megvii-BaseDetection/cvpods | transform.py | ScaleTransform.apply_segmentation | apply_segmentation | Apply resize on the full-image segmentation. | [
"Apply",
"resize",
"on",
"the",
"full-image",
"segmentation."
] | def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:
segmentation = self.apply_image(segmentation, interp=Image.NEAREST)
return segmentation | ['def', 'apply_segmentation(self,', 'segmentation:', 'np.ndarray)', '->', 'np.ndarray:', 'segmentation', '=', 'self.apply_image(segmentation,', 'interp=Image.NEAREST)', 'return', 'segmentation'] | 510,884 |
43Carrig/recurrent_neural_networks_practice | variable_scope.py | _PartitionInfo.single_offset | single_offset | Returns the offset when the variable is partitioned in at most one dim. | [
"Returns",
"the",
"offset",
"when",
"the",
"variable",
"is",
"partitioned",
"in",
"at",
"most",
"one",
"dim."
] | def single_offset(self, shape):
single_slice_dim = self.single_slice_dim(shape)
if single_slice_dim is None:
return 0
return self.var_offset[single_slice_dim] | ['def', 'single_offset(self,', 'shape):', 'single_slice_dim', '=', 'self.single_slice_dim(shape)', 'if', 'single_slice_dim', 'is', 'None:', 'return', '0', 'return', 'self.var_offset[single_slice_dim]'] | 339,130 |
rudranil723/mini-main | test_websocket.py | WebSocketAppTest.testSockMaskKey | testSockMaskKey | A WebSocketApp should forward the received mask_key function down to the actual socket. | [
"A",
"WebSocketApp",
"should",
"forward",
"the",
"received",
"mask_key",
"function",
"down",
"to",
"the",
"actual",
"socket."
] | def testSockMaskKey(self):
def my_mask_key_func():
pass
def on_open(self, *args, **kwargs):
WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
self.close()
app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
app.run_forever() | ['def', 'testSockMaskKey(self):', 'def', 'my_mask_key_func():', 'pass', 'def', 'on_open(self,', '*args,', '**kwargs):', 'WebSocketAppTest.get_mask_key_id', '=', 'id(self.get_mask_key)', 'self.close()', 'app', '=', "ws.WebSocketApp('ws://echo.websocket.org/',", 'on_open=on_open,', 'get_mask_key=my_mask_key_func)', 'app.... | 271,027 |
UWARG/computer-vision-python | test_cluster_detection.py | TestCorrectNumberClusterOutputs.test_detect_large_std_dev_single_cluster | test_detect_large_std_dev_single_cluster | Data with large distribution and equal number of points per cluster centre. | [
"Data",
"with",
"large",
"distribution",
"and",
"equal",
"number",
"of",
"points",
"per",
"cluster",
"centre."
] | def test_detect_large_std_dev_single_cluster(self, cluster_model: cluster_estimation.ClusterEstimation):
POINTS_PER_CLUSTER = [100]
EXPECTED_CLUSTER_COUNT = len(POINTS_PER_CLUSTER)
(generated_detections, _) = generate_cluster_data(POINTS_PER_CLUSTER, self.STD_DEV_LARGE)
(model_ran, detections_in_world) ... | ['def', 'test_detect_large_std_dev_single_cluster(self,', 'cluster_model:', 'cluster_estimation.ClusterEstimation):', 'POINTS_PER_CLUSTER', '=', '[100]', 'EXPECTED_CLUSTER_COUNT', '=', 'len(POINTS_PER_CLUSTER)', '(generated_detections,', '_)', '=', 'generate_cluster_data(POINTS_PER_CLUSTER,', 'self.STD_DEV_LARGE)', '(m... | 470,479 |
matsu0228/nlp-jp | test_word2vec.py | TestWord2VecModel.testRuleWithMinCount | testRuleWithMinCount | Test that returning RULE_DEFAULT from trim_rule triggers min_count. | [
"Test",
"that",
"returning",
"RULE_DEFAULT",
"from",
"trim_rule",
"triggers",
"min_count."
] | def testRuleWithMinCount(self):
model = word2vec.Word2Vec(sentences + [['occurs_only_once']], min_count=2, trim_rule=_rule)
self.assertTrue('human' not in model.wv.vocab)
self.assertTrue('occurs_only_once' not in model.wv.vocab)
self.assertTrue('interface' in model.wv.vocab) | ['def', 'testRuleWithMinCount(self):', 'model', '=', 'word2vec.Word2Vec(sentences', '+', "[['occurs_only_once']],", 'min_count=2,', 'trim_rule=_rule)', "self.assertTrue('human'", 'not', 'in', 'model.wv.vocab)', "self.assertTrue('occurs_only_once'", 'not', 'in', 'model.wv.vocab)', "self.assertTrue('interface'", 'in', 'm... | 786,196 |
deepmind/brave | spectrograms.py | pcm_to_log_mel_spectrogram | pcm_to_log_mel_spectrogram | Compute log-mel spectrogram from raw audio. | [
"Compute",
"log-mel",
"spectrogram",
"from",
"raw",
"audio."
] | def pcm_to_log_mel_spectrogram(pcm: tf.Tensor, input_sample_rate: int, num_spectrogram_bins: int, fft_step: int):
stfts = tf.signal.stft(pcm, frame_length=DEFAULT_FRAME_LENGTH, frame_step=fft_step, fft_length=DEFAULT_FFT_LENGTH, window_fn=tf.signal.hann_window, pad_end=True)
spectrograms = tf.abs(stfts)
lin... | ['def', 'pcm_to_log_mel_spectrogram(pcm:', 'tf.Tensor,', 'input_sample_rate:', 'int,', 'num_spectrogram_bins:', 'int,', 'fft_step:', 'int):', 'stfts', '=', 'tf.signal.stft(pcm,', 'frame_length=DEFAULT_FRAME_LENGTH,', 'frame_step=fft_step,', 'fft_length=DEFAULT_FFT_LENGTH,', 'window_fn=tf.signal.hann_window,', 'pad_end=... | 108,343 |
KalleHallden/InstaAutomator | kqueue.py | KeventDescriptorSet.clear | clear | Clears the collection and closes all open descriptors. | [
"Clears",
"the",
"collection",
"and",
"closes",
"all",
"open",
"descriptors."
] | def clear(self):
with self._lock:
for descriptor in self._descriptors:
descriptor.close()
self._descriptors.clear()
self._descriptor_for_fd.clear()
self._descriptor_for_path.clear()
self._kevents = [] | ['def', 'clear(self):', 'with', 'self._lock:', 'for', 'descriptor', 'in', 'self._descriptors:', 'descriptor.close()', 'self._descriptors.clear()', 'self._descriptor_for_fd.clear()', 'self._descriptor_for_path.clear()', 'self._kevents', '=', '[]'] | 232,628 |
cheind/gcsl | dm_renderer.py | DMRenderWindow.load_model | load_model | Loads the given Physics object to render. | [
"Loads",
"the",
"given",
"Physics",
"object",
"to",
"render."
] | def load_model(self, physics):
self._viewer.deinitialize()
self._draw_surface = dm_render.Renderer(max_width=_MAX_RENDERBUFFER_SIZE, max_height=_MAX_RENDERBUFFER_SIZE)
self._renderer = dm_viewer.renderer.OffScreenRenderer(physics.model, self._draw_surface)
self._viewer.initialize(physics, self._renderer... | ['def', 'load_model(self,', 'physics):', 'self._viewer.deinitialize()', 'self._draw_surface', '=', 'dm_render.Renderer(max_width=_MAX_RENDERBUFFER_SIZE,', 'max_height=_MAX_RENDERBUFFER_SIZE)', 'self._renderer', '=', 'dm_viewer.renderer.OffScreenRenderer(physics.model,', 'self._draw_surface)', 'self._viewer.initialize(p... | 202,005 |
gunthercox/ChatterBot | test_list_training.py | ListTrainingTests.test_training_adds_statements | test_training_adds_statements | Test that the training method adds statements to the database. | [
"Test",
"that",
"the",
"training",
"method",
"adds",
"statements",
"to",
"the",
"database."
] | def test_training_adds_statements(self):
conversation = ['Hello', 'Hi there!', 'How are you doing?', "I'm great.", 'That is good to hear', 'Thank you.', 'You are welcome.', 'Sure, any time.', 'Yeah', 'Can I help you with anything?']
self.trainer.train(conversation)
response = self.chatbot.get_response('Than... | ['def', 'test_training_adds_statements(self):', 'conversation', '=', "['Hello',", "'Hi", "there!',", "'How", 'are', 'you', "doing?',", '"I\'m', 'great.",', "'That", 'is', 'good', 'to', "hear',", "'Thank", "you.',", "'You", 'are', "welcome.',", "'Sure,", 'any', "time.',", "'Yeah',", "'Can", 'I', 'help', 'you', 'with', "... | 486,001 |
Eric3911/OpenAGI | utility.py | get_subsample | get_subsample | Subsample rate from config. | [
"Subsample",
"rate",
"from",
"config."
] | def get_subsample(config):
if config['encoder'] == 'squeezeformer':
return 4
else:
input_layer = config['encoder_conf']['input_layer']
assert input_layer in ['conv2d', 'conv2d6', 'conv2d8']
if input_layer == 'conv2d':
return 4
elif input_layer == 'conv2d6':
return... | ['def', 'get_subsample(config):', 'if', "config['encoder']", '==', "'squeezeformer':", 'return', '4', 'else:', 'input_layer', '=', "config['encoder_conf']['input_layer']", 'assert', 'input_layer', 'in', "['conv2d',", "'conv2d6',", "'conv2d8']", 'if', 'input_layer', '==', "'conv2d':", 'return', '4', 'elif', 'input_layer... | 251,576 |
intel/neural-compressor | util.py | is_B_transposed | is_B_transposed | Whether inuput B is transposed. | [
"Whether",
"inuput",
"B",
"is",
"transposed."
] | def is_B_transposed(node):
transB = [attr for attr in node.attribute if attr.name == 'transB']
if len(transB):
return 0 < helper.get_attribute_value(transB[0])
return False | ['def', 'is_B_transposed(node):', 'transB', '=', '[attr', 'for', 'attr', 'in', 'node.attribute', 'if', 'attr.name', '==', "'transB']", 'if', 'len(transB):', 'return', '0', '<', 'helper.get_attribute_value(transB[0])', 'return', 'False'] | 737,479 |
dmpelt/msdnet | gpuoperations.py | GPUImageData.relu2 | relu2 | Apply backpropagation ReLU to single image. | [
"Apply",
"backpropagation",
"ReLU",
"to",
"single",
"image."
] | def relu2(self, i, dat, j):
relu2_2d_cuda[self.bpg2d, self.tpb2d](dat.arr, self.arr, j, i) | ['def', 'relu2(self,', 'i,', 'dat,', 'j):', 'relu2_2d_cuda[self.bpg2d,', 'self.tpb2d](dat.arr,', 'self.arr,', 'j,', 'i)'] | 265,130 |
inseq-team/inseq | attribution_utils.py | tok2string | tok2string | Enables bounded tokenization of a list of lists of tokens with start and end positions. | [
"Enables",
"bounded",
"tokenization",
"of",
"a",
"list",
"of",
"lists",
"of",
"tokens",
"with",
"start",
"and",
"end",
"positions."
] | def tok2string(attribution_model: 'AttributionModel', token_lists: OneOrMoreTokenSequences, start: Optional[int]=None, end: Optional[int]=None, as_targets: bool=True) -> TextInput:
start = [0 if start is None else start for _ in token_lists]
end = [len(tokens) if end is None else end for tokens in token_lists]
... | ['def', 'tok2string(attribution_model:', "'AttributionModel',", 'token_lists:', 'OneOrMoreTokenSequences,', 'start:', 'Optional[int]=None,', 'end:', 'Optional[int]=None,', 'as_targets:', 'bool=True)', '->', 'TextInput:', 'start', '=', '[0', 'if', 'start', 'is', 'None', 'else', 'start', 'for', '_', 'in', 'token_lists]',... | 613,907 |
OpenMDAO/OpenMDAO-Framework | problem_formulation.py | HasCouplingVars.clear_coupling_vars | clear_coupling_vars | Removes all coupling variables from the assembly. | [
"Removes",
"all",
"coupling",
"variables",
"from",
"the",
"assembly."
] | def clear_coupling_vars(self):
self._couples = [] | ['def', 'clear_coupling_vars(self):', 'self._couples', '=', '[]'] | 275,970 |
jbwang1997/CrossKD | crowdhuman_metric.py | Image.compare_caltech | compare_caltech | Match the detection results with the ground_truth by Caltech matching strategy. | [
"Match",
"the",
"detection",
"results",
"with",
"the",
"ground_truth",
"by",
"Caltech",
"matching",
"strategy."
] | def compare_caltech(self, thres):
if self.dt_boxes is None or self.gt_boxes is None:
return list()
dtboxes = self.dt_boxes if self.dt_boxes is not None else list()
gtboxes = self.gt_boxes if self.gt_boxes is not None else list()
dt_matched = np.zeros(dtboxes.shape[0])
gt_matched = np.zeros(g... | ['def', 'compare_caltech(self,', 'thres):', 'if', 'self.dt_boxes', 'is', 'None', 'or', 'self.gt_boxes', 'is', 'None:', 'return', 'list()', 'dtboxes', '=', 'self.dt_boxes', 'if', 'self.dt_boxes', 'is', 'not', 'None', 'else', 'list()', 'gtboxes', '=', 'self.gt_boxes', 'if', 'self.gt_boxes', 'is', 'not', 'None', 'else', '... | 490,875 |
tobegit3hub/deep_image_model | docs.py | Document.write_markdown_to_file | write_markdown_to_file | Writes a Markdown-formatted version of this document to file `f`. | [
"Writes",
"a",
"Markdown-formatted",
"version",
"of",
"this",
"document",
"to",
"file",
"`f`."
] | def write_markdown_to_file(self, f):
raise NotImplementedError('Document.WriteToFile') | ['def', 'write_markdown_to_file(self,', 'f):', 'raise', "NotImplementedError('Document.WriteToFile')"] | 182,461 |
RasaHQ/rasa_core | generator.py | TrackerWithCachedStates.past_states | past_states | Return the states of the tracker based on the logged events. | [
"Return",
"the",
"states",
"of",
"the",
"tracker",
"based",
"on",
"the",
"logged",
"events."
] | def past_states(self, domain: Domain) -> deque:
assert domain == self.domain
if self._states is None:
self._states = super(TrackerWithCachedStates, self).past_states(domain)
return self._states | ['def', 'past_states(self,', 'domain:', 'Domain)', '->', 'deque:', 'assert', 'domain', '==', 'self.domain', 'if', 'self._states', 'is', 'None:', 'self._states', '=', 'super(TrackerWithCachedStates,', 'self).past_states(domain)', 'return', 'self._states'] | 838,357 |
43Carrig/recurrent_neural_networks_practice | select.py | get_backward_walk_ops | get_backward_walk_ops | Do a backward graph walk and return all the visited ops. | [
"Do",
"a",
"backward",
"graph",
"walk",
"and",
"return",
"all",
"the",
"visited",
"ops."
] | def get_backward_walk_ops(seed_ops, inclusive=True, within_ops=None, within_ops_fn=None, stop_at_ts=(), control_inputs=False):
if not util.is_iterable(seed_ops):
seed_ops = [seed_ops]
if not seed_ops:
return []
if isinstance(seed_ops[0], tf_ops.Tensor):
ts = util.make_list_of_t(seed_... | ['def', 'get_backward_walk_ops(seed_ops,', 'inclusive=True,', 'within_ops=None,', 'within_ops_fn=None,', 'stop_at_ts=(),', 'control_inputs=False):', 'if', 'not', 'util.is_iterable(seed_ops):', 'seed_ops', '=', '[seed_ops]', 'if', 'not', 'seed_ops:', 'return', '[]', 'if', 'isinstance(seed_ops[0],', 'tf_ops.Tensor):', 't... | 313,236 |
NVIDIA-Omniverse/IsaacGymEnvs | trifinger.py | random_yaw_orientation | random_yaw_orientation | Returns sampled rotation around z-axis. | [
"Returns",
"sampled",
"rotation",
"around",
"z-axis."
] | def random_yaw_orientation(num: int, device: str) -> torch.Tensor:
roll = torch.zeros(num, dtype=torch.float, device=device)
pitch = torch.zeros(num, dtype=torch.float, device=device)
yaw = 2 * np.pi * torch.rand(num, dtype=torch.float, device=device)
return quat_from_euler_xyz(roll, pitch, yaw) | ['def', 'random_yaw_orientation(num:', 'int,', 'device:', 'str)', '->', 'torch.Tensor:', 'roll', '=', 'torch.zeros(num,', 'dtype=torch.float,', 'device=device)', 'pitch', '=', 'torch.zeros(num,', 'dtype=torch.float,', 'device=device)', 'yaw', '=', '2', '*', 'np.pi', '*', 'torch.rand(num,', 'dtype=torch.float,', 'device... | 246,504 |
intel/neural-compressor | graph.py | Graph.get_target_nodes | get_target_nodes | Get target nodes from specified op. | [
"Get",
"target",
"nodes",
"from",
"specified",
"op."
] | def get_target_nodes(self, op_name: str) -> List[Node]:
target_nodes: List[Node] = []
for edge in self.edges:
if edge.source == op_name:
target_nodes.append(self.get_node(edge.target))
return target_nodes | ['def', 'get_target_nodes(self,', 'op_name:', 'str)', '->', 'List[Node]:', 'target_nodes:', 'List[Node]', '=', '[]', 'for', 'edge', 'in', 'self.edges:', 'if', 'edge.source', '==', 'op_name:', 'target_nodes.append(self.get_node(edge.target))', 'return', 'target_nodes'] | 721,550 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | unet.py | Block | Block | Creates a single U-Net building block. | [
"Creates",
"a",
"single",
"U-Net",
"building",
"block."
] | def Block(num_in, num_out):
return nn.Sequential(nn.Conv2d(num_in, num_out, kernel_size=3, padding=1), nn.BatchNorm2d(num_out), nn.PReLU(num_parameters=num_out), nn.Conv2d(num_out, num_out, kernel_size=3, padding=1), nn.BatchNorm2d(num_out), nn.PReLU(num_parameters=num_out)) | ['def', 'Block(num_in,', 'num_out):', 'return', 'nn.Sequential(nn.Conv2d(num_in,', 'num_out,', 'kernel_size=3,', 'padding=1),', 'nn.BatchNorm2d(num_out),', 'nn.PReLU(num_parameters=num_out),', 'nn.Conv2d(num_out,', 'num_out,', 'kernel_size=3,', 'padding=1),', 'nn.BatchNorm2d(num_out),', 'nn.PReLU(num_parameters=num_out... | 18,139 |
samorr/Computer-Vision-and-Photogrammetry | plyfile.py | PlyData.write | write | Write PLY data to a writeable file-like object or filename. | [
"Write",
"PLY",
"data",
"to",
"a",
"writeable",
"file-like",
"object",
"or",
"filename."
] | def write(self, stream):
(must_close, stream) = _open_stream(stream, 'write')
try:
stream.write(self.header.encode('ascii'))
stream.write(b'\r\n')
for elt in self:
elt._write(stream, self.text, self.byte_order)
finally:
if must_close:
stream.close() | ['def', 'write(self,', 'stream):', '(must_close,', 'stream)', '=', '_open_stream(stream,', "'write')", 'try:', "stream.write(self.header.encode('ascii'))", "stream.write(b'\\r\\n')", 'for', 'elt', 'in', 'self:', 'elt._write(stream,', 'self.text,', 'self.byte_order)', 'finally:', 'if', 'must_close:', 'stream.close()'] | 467,591 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec.py | Word2Vec.nce_loss | nce_loss | Build the graph for the NCE loss. | [
"Build",
"the",
"graph",
"for",
"the",
"NCE",
"loss."
] | def nce_loss(self, true_logits, sampled_logits):
opts = self._options
true_xent = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(true_logits), logits=true_logits)
sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(sampled_logits), logits=sampled_logits)
nce_loss_ten... | ['def', 'nce_loss(self,', 'true_logits,', 'sampled_logits):', 'opts', '=', 'self._options', 'true_xent', '=', 'tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(true_logits),', 'logits=true_logits)', 'sampled_xent', '=', 'tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(sampled_logits),', 'logits=... | 30,115 |
gradio-app/gradio | utils.py | strip_invalid_filename_characters | strip_invalid_filename_characters | Strips invalid characters from a filename and ensures that the file_length is less than `max_bytes` bytes. | [
"Strips",
"invalid",
"characters",
"from",
"a",
"filename",
"and",
"ensures",
"that",
"the",
"file_length",
"is",
"less",
"than",
"`max_bytes`",
"bytes."
] | def strip_invalid_filename_characters(filename: str, max_bytes: int=200) -> str:
filename = ''.join([char for char in filename if char.isalnum() or char in '._- '])
filename_len = len(filename.encode())
if filename_len > max_bytes:
while filename_len > max_bytes:
if len(filename) == 0:
... | ['def', 'strip_invalid_filename_characters(filename:', 'str,', 'max_bytes:', 'int=200)', '->', 'str:', 'filename', '=', "''.join([char", 'for', 'char', 'in', 'filename', 'if', 'char.isalnum()', 'or', 'char', 'in', "'._-", "'])", 'filename_len', '=', 'len(filename.encode())', 'if', 'filename_len', '>', 'max_bytes:', 'wh... | 578,803 |
ryu-ed/SpaceInvaders_Ros | base.py | Screen.restore_mode | restore_mode | Restore the screen mode to the user's default. | [
"Restore",
"the",
"screen",
"mode",
"to",
"the",
"user's",
"default."
] | def restore_mode(self):
raise NotImplementedError('abstract') | ['def', 'restore_mode(self):', 'raise', "NotImplementedError('abstract')"] | 369,405 |
weimin17/Object-Detection_HelmetDetection | flags_test.py | BaseTester.test_default_setting | test_default_setting | Test to ensure fields exist and defaults can be set. | [
"Test",
"to",
"ensure",
"fields",
"exist",
"and",
"defaults",
"can",
"be",
"set."
] | def test_default_setting(self):
defaults = dict(data_dir='dfgasf', model_dir='dfsdkjgbs', train_epochs=534, epochs_between_evals=15, batch_size=256, hooks=['LoggingTensorHook'], num_parallel_calls=18, inter_op_parallelism_threads=5, intra_op_parallelism_threads=10, data_format='channels_first')
flags_core.set_d... | ['def', 'test_default_setting(self):', 'defaults', '=', "dict(data_dir='dfgasf',", "model_dir='dfsdkjgbs',", 'train_epochs=534,', 'epochs_between_evals=15,', 'batch_size=256,', "hooks=['LoggingTensorHook'],", 'num_parallel_calls=18,', 'inter_op_parallelism_threads=5,', 'intra_op_parallelism_threads=10,', "data_format='... | 748,794 |
PaddlePaddle/Paddle3D | xarfile.py | XarFile.extractall | extractall | Extract all files from the archive to the specified path. | [
"Extract",
"all",
"files",
"from",
"the",
"archive",
"to",
"the",
"specified",
"path."
] | def extractall(self, path: str):
return self._archive_fp.extractall(path) | ['def', 'extractall(self,', 'path:', 'str):', 'return', 'self._archive_fp.extractall(path)'] | 778,107 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | debugger.py | Pdb.do_context | do_context | context number_of_lines Set the number of lines of source code to show when displaying stacktrace information. | [
"context",
"number_of_lines",
"Set",
"the",
"number",
"of",
"lines",
"of",
"source",
"code",
"to",
"show",
"when",
"displaying",
"stacktrace",
"information."
] | def do_context(self, context):
try:
new_context = int(context)
if new_context <= 0:
raise ValueError()
except ValueError:
self.error("The 'context' command requires a positive integer argument.")
self.context = new_context | ['def', 'do_context(self,', 'context):', 'try:', 'new_context', '=', 'int(context)', 'if', 'new_context', '<=', '0:', 'raise', 'ValueError()', 'except', 'ValueError:', 'self.error("The', "'context'", 'command', 'requires', 'a', 'positive', 'integer', 'argument.")', 'self.context', '=', 'new_context'] | 448,057 |
f-dangel/cockpit | test_quantity_integration.py | test_quantity_integration_and_track_events | test_quantity_integration_and_track_events | Check if ``Cockpit`` with a single quantity works. | [
"Check",
"if",
"``Cockpit``",
"with",
"a",
"single",
"quantity",
"works."
] | def test_quantity_integration_and_track_events(problem, quantity_cls):
(interval, offset) = (1, 2)
schedule = linear(interval, offset=offset)
quantity = quantity_cls(track_schedule=schedule, verbose=True)
with instantiate(problem):
iterations = problem.iterations
testing_harness = Simple... | ['def', 'test_quantity_integration_and_track_events(problem,', 'quantity_cls):', '(interval,', 'offset)', '=', '(1,', '2)', 'schedule', '=', 'linear(interval,', 'offset=offset)', 'quantity', '=', 'quantity_cls(track_schedule=schedule,', 'verbose=True)', 'with', 'instantiate(problem):', 'iterations', '=', 'problem.itera... | 492,869 |
rudranil723/mini-main | __init__.py | CallbackRegistry.connect | connect | Register *func* to be called when signal *signal* is generated. | [
"Register",
"*func*",
"to",
"be",
"called",
"when",
"signal",
"*signal*",
"is",
"generated."
] | def connect(self, signal, func):
if signal == 'units finalize':
_api.warn_deprecated('3.5', name=signal, obj_type='signal', alternative='units')
if self._signals is not None:
_api.check_in_list(self._signals, signal=signal)
self._func_cid_map.setdefault(signal, {})
proxy = _weak_or_stron... | ['def', 'connect(self,', 'signal,', 'func):', 'if', 'signal', '==', "'units", "finalize':", "_api.warn_deprecated('3.5',", 'name=signal,', "obj_type='signal',", "alternative='units')", 'if', 'self._signals', 'is', 'not', 'None:', '_api.check_in_list(self._signals,', 'signal=signal)', 'self._func_cid_map.setdefault(sign... | 320,080 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | operator.py | itruediv | itruediv | Same as a /= b. | [
"Same",
"as",
"a",
"/=",
"b."
] | def itruediv(a, b):
a /= b
return a | ['def', 'itruediv(a,', 'b):', 'a', '/=', 'b', 'return', 'a'] | 801,576 |
sercant/mobile-segmentation | build_data.py | image_seg_to_tfexample | image_seg_to_tfexample | Converts one image/segmentation pair to tf example. | [
"Converts",
"one",
"image/segmentation",
"pair",
"to",
"tf",
"example."
] | def image_seg_to_tfexample(image_data, filename, height, width, seg_data):
return tf.train.Example(features=tf.train.Features(feature={'image/encoded': _bytes_list_feature(image_data), 'image/filename': _bytes_list_feature(filename), 'image/format': _bytes_list_feature(_IMAGE_FORMAT_MAP[FLAGS.image_format]), 'image... | ['def', 'image_seg_to_tfexample(image_data,', 'filename,', 'height,', 'width,', 'seg_data):', 'return', "tf.train.Example(features=tf.train.Features(feature={'image/encoded':", '_bytes_list_feature(image_data),', "'image/filename':", '_bytes_list_feature(filename),', "'image/format':", '_bytes_list_feature(_IMAGE_FORMA... | 626,149 |
KitwareMedical/pyLAR | test_ealm.py | EALMTesting.test_recover | test_recover | Test recovery from outliers. | [
"Test",
"recovery",
"from",
"outliers."
] | def test_recover(self):
(lr, sp, _) = ealm.recover(self._data, None)
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'im_baseline.dat')
baseline = np.genfromtxt(file_path)
d = np.linalg.norm(np.round(lr) - baseline, ord='fro')
self.assertTrue(np.allclose(d, 0.0)) | ['def', 'test_recover(self):', '(lr,', 'sp,', '_)', '=', 'ealm.recover(self._data,', 'None)', 'file_path', '=', 'os.path.join(os.path.dirname(os.path.abspath(__file__)),', "'im_baseline.dat')", 'baseline', '=', 'np.genfromtxt(file_path)', 'd', '=', 'np.linalg.norm(np.round(lr)', '-', 'baseline,', "ord='fro')", 'self.as... | 819,825 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | batch_env_factory.py | ExternalProcessEnv.close | close | Send a close message to the external process and join it. | [
"Send",
"a",
"close",
"message",
"to",
"the",
"external",
"process",
"and",
"join",
"it."
] | def close(self):
try:
self._conn.send((self._CLOSE, None))
self._conn.close()
except IOError:
pass
self._process.join() | ['def', 'close(self):', 'try:', 'self._conn.send((self._CLOSE,', 'None))', 'self._conn.close()', 'except', 'IOError:', 'pass', 'self._process.join()'] | 966,023 |
meganlsmith/phyloGAN | utils.py | read_params_file | read_params_file | This function will read parameters from the parameter input file. | [
"This",
"function",
"will",
"read",
"parameters",
"from",
"the",
"parameter",
"input",
"file."
] | def read_params_file(paramfilename):
paraminfo = open(paramfilename, 'r').readlines()
try:
IQTree_path = [x for x in paraminfo if 'IQTree path' in x][0].split(' = ')[1].split('#')[0].strip()
alignment_folder = [x for x in paraminfo if 'alignment folder' in x][0].split(' = ')[1].split('#')[0].str... | ['def', 'read_params_file(paramfilename):', 'paraminfo', '=', 'open(paramfilename,', "'r').readlines()", 'try:', 'IQTree_path', '=', '[x', 'for', 'x', 'in', 'paraminfo', 'if', "'IQTree", "path'", 'in', "x][0].split('", '=', "')[1].split('#')[0].strip()", 'alignment_folder', '=', '[x', 'for', 'x', 'in', 'paraminfo', 'if... | 769,317 |
alex/pyvcs | repository.py | BaseRepository.list_directory | list_directory | Returns a tuple of lists of files and folders in a given directory at a given revision, or HEAD if revision is None. | [
"Returns",
"a",
"tuple",
"of",
"lists",
"of",
"files",
"and",
"folders",
"in",
"a",
"given",
"directory",
"at",
"a",
"given",
"revision,",
"or",
"HEAD",
"if",
"revision",
"is",
"None."
] | def list_directory(self, path, revision=None):
raise NotImplementedError | ['def', 'list_directory(self,', 'path,', 'revision=None):', 'raise', 'NotImplementedError'] | 302,593 |
arshpreetsingh/quantopian-machinelearning | diff.py | merge_insert | merge_insert | doc is the already-handled document (as a list of text chunks); here we add <ins>ins_chunks</ins> to the end of that. | [
"doc",
"is",
"the",
"already-handled",
"document",
"(as",
"a",
"list",
"of",
"text",
"chunks);",
"here",
"we",
"add",
"<ins>ins_chunks</ins>",
"to",
"the",
"end",
"of",
"that."
] | def merge_insert(ins_chunks, doc):
(unbalanced_start, balanced, unbalanced_end) = split_unbalanced(ins_chunks)
doc.extend(unbalanced_start)
if doc and (not doc[-1].endswith(' ')):
doc[-1] += ' '
doc.append('<ins>')
if balanced and balanced[-1].endswith(' '):
balanced[-1] = balanced[-... | ['def', 'merge_insert(ins_chunks,', 'doc):', '(unbalanced_start,', 'balanced,', 'unbalanced_end)', '=', 'split_unbalanced(ins_chunks)', 'doc.extend(unbalanced_start)', 'if', 'doc', 'and', '(not', "doc[-1].endswith('", "')):", 'doc[-1]', '+=', "'", "'", "doc.append('<ins>')", 'if', 'balanced', 'and', "balanced[-1].endsw... | 887,923 |
metadriverse/metadrive | text.py | Text.set_text | set_text | Changes the text, remember to pass may_change to the constructor, otherwise this method does not work. | [
"Changes",
"the",
"text,",
"remember",
"to",
"pass",
"may_change",
"to",
"the",
"constructor,",
"otherwise",
"this",
"method",
"does",
"not",
"work."
] | def set_text(self, text):
self._node['text'] = text | ['def', 'set_text(self,', 'text):', "self._node['text']", '=', 'text'] | 634,124 |
ifwe/digsby | contactdialogs.py | ContactPanel.on_conns_changed | on_conns_changed | Updates the accounts choice. | [
"Updates",
"the",
"accounts",
"choice."
] | def on_conns_changed(self, connected_accounts, *a):
choice = self.acct_choice
sel = choice.GetStringSelection()
with choice.Frozen():
choice.Clear()
for acct in connected_accounts:
proto_str = account_string(acct)
choice.Append(proto_str)
choice.SetStringSelection... | ['def', 'on_conns_changed(self,', 'connected_accounts,', '*a):', 'choice', '=', 'self.acct_choice', 'sel', '=', 'choice.GetStringSelection()', 'with', 'choice.Frozen():', 'choice.Clear()', 'for', 'acct', 'in', 'connected_accounts:', 'proto_str', '=', 'account_string(acct)', 'choice.Append(proto_str)', 'choice.SetString... | 185,257 |
meowoodie/Reinforcement-Learning-of-Spatio-Temporal-Point-Processes | tfgen.py | SpatialTemporalHawkes.log_conditional_pdf | log_conditional_pdf | log pdf conditional on history. | [
"log",
"pdf",
"conditional",
"on",
"history."
] | def log_conditional_pdf(self, points, keep_latest_k=None):
if keep_latest_k is not None:
points = points[-keep_latest_k:, :]
len_points = tf.shape(points)[0]
(s, t) = (points[-1, 1:], points[-1, 0])
(his_s, his_t) = (points[:-1, 1:], points[:-1, 0])
def pdf_no_history():
return tf.l... | ['def', 'log_conditional_pdf(self,', 'points,', 'keep_latest_k=None):', 'if', 'keep_latest_k', 'is', 'not', 'None:', 'points', '=', 'points[-keep_latest_k:,', ':]', 'len_points', '=', 'tf.shape(points)[0]', '(s,', 't)', '=', '(points[-1,', '1:],', 'points[-1,', '0])', '(his_s,', 'his_t)', '=', '(points[:-1,', '1:],', '... | 833,498 |
triaquae/triaquae | tests.py | GeoIPTest.test04_city | test04_city | Testing GeoIP city querying methods. | [
"Testing",
"GeoIP",
"city",
"querying",
"methods."
] | def test04_city(self):
g = GeoIP(country='<foo>')
addr = '128.249.1.1'
fqdn = 'tmc.edu'
for query in (fqdn, addr):
for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
self.assertEqual('US', func(query))
for func in (g.country_name, g.country_name_by_... | ['def', 'test04_city(self):', 'g', '=', "GeoIP(country='<foo>')", 'addr', '=', "'128.249.1.1'", 'fqdn', '=', "'tmc.edu'", 'for', 'query', 'in', '(fqdn,', 'addr):', 'for', 'func', 'in', '(g.country_code,', 'g.country_code_by_addr,', 'g.country_code_by_name):', "self.assertEqual('US',", 'func(query))', 'for', 'func', 'in... | 357,734 |
zackmcnulty/CSE_446-Machine_Learning | _base.py | _AxesBase.get_ygridlines | get_ygridlines | Get the y grid lines as a list of `Line2D` instances. | [
"Get",
"the",
"y",
"grid",
"lines",
"as",
"a",
"list",
"of",
"`Line2D`",
"instances."
] | def get_ygridlines(self):
return cbook.silent_list('Line2D ygridline', self.yaxis.get_gridlines()) | ['def', 'get_ygridlines(self):', 'return', "cbook.silent_list('Line2D", "ygridline',", 'self.yaxis.get_gridlines())'] | 194,860 |
funkelab/gunpowder | generic_jax_model.py | GenericJaxModel.initialize | initialize | Initialize parameters for training. | [
"Initialize",
"parameters",
"for",
"training."
] | def initialize(self, rng_key, inputs):
raise RuntimeError('Unimplemented') | ['def', 'initialize(self,', 'rng_key,', 'inputs):', 'raise', "RuntimeError('Unimplemented')"] | 572,760 |
gunthercox/ChatterBot | tbtools.py | Frame.render | render | Render a single frame in a traceback. | [
"Render",
"a",
"single",
"frame",
"in",
"a",
"traceback."
] | def render(self):
return FRAME_HTML % {'id': self.id, 'filename': escape(self.filename), 'lineno': self.lineno, 'function_name': escape(self.function_name), 'current_line': escape(self.current_line.strip())} | ['def', 'render(self):', 'return', 'FRAME_HTML', '%', "{'id':", 'self.id,', "'filename':", 'escape(self.filename),', "'lineno':", 'self.lineno,', "'function_name':", 'escape(self.function_name),', "'current_line':", 'escape(self.current_line.strip())}'] | 483,791 |
deep-learning-indaba/Baobab | tests.py | EmailerTest.test_email_event_french | test_email_event_french | Check email to an French user with an event. | [
"Check",
"email",
"to",
"an",
"French",
"user",
"with",
"an",
"event."
] | def test_email_event_french(self, send_mail_fn):
self.seed_static_data()
email_user('template1', template_parameters={'param': 'bleu'}, user=self.french_user, event=self.event)
send_mail_fn.assert_called_with(recipient=self.french_user.email, subject='Sujet franÃ\x83§ais Nom de lÃ\x83©vÃ\x83©nement en fr... | ['def', 'test_email_event_french(self,', 'send_mail_fn):', 'self.seed_static_data()', "email_user('template1',", "template_parameters={'param':", "'bleu'},", 'user=self.french_user,', 'event=self.event)', 'send_mail_fn.assert_called_with(recipient=self.french_user.email,', "subject='Sujet", 'franÃ\\x83§ais', 'Nom', 'd... | 94,276 |
Farama-Foundation/Gymnasium | async_vector_env.py | AsyncVectorEnv.step | step | Take an action for each parallel environment. | [
"Take",
"an",
"action",
"for",
"each",
"parallel",
"environment."
] | def step(self, actions):
self.step_async(actions)
return self.step_wait() | ['def', 'step(self,', 'actions):', 'self.step_async(actions)', 'return', 'self.step_wait()'] | 573,099 |
hans/pyccg | test_model.py | test_base_function | test_base_function | Support domain enumeration when a function appears as a constant in "base" form. | [
"Support",
"domain",
"enumeration",
"when",
"a",
"function",
"appears",
"as",
"a",
"constant",
"in",
"\"base\"",
"form."
] | def test_base_function():
ontology = _make_mock_ontology()
scene = {'objects': [frozendict(x=3, shape='sphere'), frozendict(x=4, shape='cube')]}
model = Model(scene, ontology)
eq_(model.evaluate(Expression.fromstring('unique(cube)')), scene['objects'][1]) | ['def', 'test_base_function():', 'ontology', '=', '_make_mock_ontology()', 'scene', '=', "{'objects':", '[frozendict(x=3,', "shape='sphere'),", 'frozendict(x=4,', "shape='cube')]}", 'model', '=', 'Model(scene,', 'ontology)', "eq_(model.evaluate(Expression.fromstring('unique(cube)')),", "scene['objects'][1])"] | 296,055 |
triaquae/triaquae | geometries.py | OGRGeometry.ewkt | ewkt | Returns the EWKT representation of the Geometry. | [
"Returns",
"the",
"EWKT",
"representation",
"of",
"the",
"Geometry."
] | def ewkt(self):
srs = self.srs
if srs and srs.srid:
return 'SRID=%s;%s' % (srs.srid, self.wkt)
else:
return self.wkt | ['def', 'ewkt(self):', 'srs', '=', 'self.srs', 'if', 'srs', 'and', 'srs.srid:', 'return', "'SRID=%s;%s'", '%', '(srs.srid,', 'self.wkt)', 'else:', 'return', 'self.wkt'] | 357,583 |
ViCCo-Group/thingsvision | helpers.py | make_instance_dataset | make_instance_dataset | Creates a custom <instance> image dataset of images and writes its order to file. | [
"Creates",
"a",
"custom",
"<instance>",
"image",
"dataset",
"of",
"images",
"and",
"writes",
"its",
"order",
"to",
"file."
] | def make_instance_dataset(root: str, out_path: str, image_names: List[str]) -> List[str]:
instances = []
with open(os.path.join(out_path, 'file_names.txt'), 'w') as f:
for image_name in image_names:
f.write(f'{image_name}\n')
instances.append(os.path.join(root, image_name))
r... | ['def', 'make_instance_dataset(root:', 'str,', 'out_path:', 'str,', 'image_names:', 'List[str])', '->', 'List[str]:', 'instances', '=', '[]', 'with', 'open(os.path.join(out_path,', "'file_names.txt'),", "'w')", 'as', 'f:', 'for', 'image_name', 'in', 'image_names:', "f.write(f'{image_name}\\n')", 'instances.append(os.pa... | 916,160 |
43Carrig/recurrent_neural_networks_practice | summaries.py | add_zero_fraction_summary | add_zero_fraction_summary | Adds a summary for the percentage of zero values in the given tensor. | [
"Adds",
"a",
"summary",
"for",
"the",
"percentage",
"of",
"zero",
"values",
"in",
"the",
"given",
"tensor."
] | def add_zero_fraction_summary(tensor, name=None, prefix=None, print_summary=False):
name = _get_summary_name(tensor, name, prefix, 'Fraction_of_Zero_Values')
tensor = nn.zero_fraction(tensor)
return add_scalar_summary(tensor, name, print_summary=print_summary) | ['def', 'add_zero_fraction_summary(tensor,', 'name=None,', 'prefix=None,', 'print_summary=False):', 'name', '=', '_get_summary_name(tensor,', 'name,', 'prefix,', "'Fraction_of_Zero_Values')", 'tensor', '=', 'nn.zero_fraction(tensor)', 'return', 'add_scalar_summary(tensor,', 'name,', 'print_summary=print_summary)'] | 335,204 |
JamesPiggott/Ancient-Language-Decipherer | image_processing.py | ImageProcessing.discover_contours | discover_contours | Find contours on the threshold image and draw them onto a copy of the scaled image. | [
"Find",
"contours",
"on",
"the",
"threshold",
"image",
"and",
"draw",
"them",
"onto",
"a",
"copy",
"of",
"the",
"scaled",
"image."
] | def discover_contours(self):
(contours_thresh, hierarchy_thresh) = cv2.findContours(self.thresh2_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
self.threshold_contours_img = self.scaled_img.copy()
cv2.drawContours(self.threshold_contours_img, contours_thresh, -1, (255, 0, 0), 1)
cv2.imshow('Threshold Contou... | ['def', 'discover_contours(self):', '(contours_thresh,', 'hierarchy_thresh)', '=', 'cv2.findContours(self.thresh2_img,', 'cv2.RETR_TREE,', 'cv2.CHAIN_APPROX_NONE)', 'self.threshold_contours_img', '=', 'self.scaled_img.copy()', 'cv2.drawContours(self.threshold_contours_img,', 'contours_thresh,', '-1,', '(255,', '0,', '0... | 416,263 |
tensorflow/quantum | util_test.py | ExponentialUtilFunctionsTest.test_many_z_to_single_z | test_many_z_to_single_z | Test many Z's to a single Z. | [
"Test",
"many",
"Z's",
"to",
"a",
"single",
"Z."
] | def test_many_z_to_single_z(self):
q = cirq.GridQubit.rect(1, 8)
benchmark_term = 1.321 * cirq.Z(q[0]) * cirq.Z(q[3]) * cirq.Z(q[5]) * cirq.Z(q[7])
benchmark_gates_indices = [(q[7], q[3]), (q[5], q[3]), (q[0], q[3])]
(gates, _) = util._many_z_to_single_z(q[3], benchmark_term)
for gate_op in gates:
... | ['def', 'test_many_z_to_single_z(self):', 'q', '=', 'cirq.GridQubit.rect(1,', '8)', 'benchmark_term', '=', '1.321', '*', 'cirq.Z(q[0])', '*', 'cirq.Z(q[3])', '*', 'cirq.Z(q[5])', '*', 'cirq.Z(q[7])', 'benchmark_gates_indices', '=', '[(q[7],', 'q[3]),', '(q[5],', 'q[3]),', '(q[0],', 'q[3])]', '(gates,', '_)', '=', 'util... | 835,170 |
tensorflow/agents | reinforce_agent.py | ReinforceAgent.policy_gradient_loss | policy_gradient_loss | Computes the policy gradient loss. | [
"Computes",
"the",
"policy",
"gradient",
"loss."
] | def policy_gradient_loss(self, actions_distribution: types.NestedDistribution, actions: types.NestedTensor, is_boundary: types.Tensor, returns: types.Tensor, num_episodes: types.Int, weights: Optional[types.Tensor]=None) -> types.Tensor:
action_log_prob = common.log_probability(actions_distribution, actions, self.a... | ['def', 'policy_gradient_loss(self,', 'actions_distribution:', 'types.NestedDistribution,', 'actions:', 'types.NestedTensor,', 'is_boundary:', 'types.Tensor,', 'returns:', 'types.Tensor,', 'num_episodes:', 'types.Int,', 'weights:', 'Optional[types.Tensor]=None)', '->', 'types.Tensor:', 'action_log_prob', '=', 'common.l... | 23,229 |
pycroscopy/atomai | multivar.py | imlocal.ica | ica | Computes ICA independent souces for a stack of subimages. | [
"Computes",
"ICA",
"independent",
"souces",
"for",
"a",
"stack",
"of",
"subimages."
] | def ica(self, n_components: int, random_state: int=1, plot_results: bool=False) -> Tuple[np.ndarray]:
ica = decomposition.FastICA(n_components=n_components, random_state=random_state)
X_vec = self.imgstack.reshape(self.d0, self.d1 * self.d2 * self.d3)
X_vec_t = ica.fit_transform(X_vec)
components = ica.... | ['def', 'ica(self,', 'n_components:', 'int,', 'random_state:', 'int=1,', 'plot_results:', 'bool=False)', '->', 'Tuple[np.ndarray]:', 'ica', '=', 'decomposition.FastICA(n_components=n_components,', 'random_state=random_state)', 'X_vec', '=', 'self.imgstack.reshape(self.d0,', 'self.d1', '*', 'self.d2', '*', 'self.d3)', '... | 402,842 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | wmt_utils.py | basic_detokenizer | basic_detokenizer | Reverse the process of the basic tokenizer below. | [
"Reverse",
"the",
"process",
"of",
"the",
"basic",
"tokenizer",
"below."
] | def basic_detokenizer(tokens):
result = []
previous_nospace = True
for t in tokens:
if is_char(t):
result.append(t[_CHAR_MARKER_LEN:])
previous_nospace = True
elif t == _SPACE:
result.append(' ')
previous_nospace = True
elif previous_no... | ['def', 'basic_detokenizer(tokens):', 'result', '=', '[]', 'previous_nospace', '=', 'True', 'for', 't', 'in', 'tokens:', 'if', 'is_char(t):', 'result.append(t[_CHAR_MARKER_LEN:])', 'previous_nospace', '=', 'True', 'elif', 't', '==', '_SPACE:', "result.append('", "')", 'previous_nospace', '=', 'True', 'elif', 'previous_... | 56,488 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | scale.py | SymmetricalLogScale.set_default_locators_and_formatters | set_default_locators_and_formatters | Set the locators and formatters to specialized versions for symmetrical log scaling. | [
"Set",
"the",
"locators",
"and",
"formatters",
"to",
"specialized",
"versions",
"for",
"symmetrical",
"log",
"scaling."
] | def set_default_locators_and_formatters(self, axis):
axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
axis.set_major_formatter(LogFormatterSciNotation(self.base))
axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(), self.subs))
axis.set_minor_formatter(NullFormatter()) | ['def', 'set_default_locators_and_formatters(self,', 'axis):', 'axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))', 'axis.set_major_formatter(LogFormatterSciNotation(self.base))', 'axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),', 'self.subs))', 'axis.set_minor_formatter(NullFormatt... | 306,987 |
sek788432/Waymo-2D-Object-Detection | movinet_model_test.py | MovinetModelTest.test_movinet_models | test_movinet_models | Test creation of MoViNet family models with states. | [
"Test",
"creation",
"of",
"MoViNet",
"family",
"models",
"with",
"states."
] | def test_movinet_models(self, model_id, expected_params_millions):
tf.keras.backend.set_image_data_format('channels_last')
model = movinet_model.MovinetClassifier(backbone=movinet.Movinet(model_id=model_id, causal=True), num_classes=600)
model.build([1, 1, 1, 1, 3])
num_params_millions = model.count_par... | ['def', 'test_movinet_models(self,', 'model_id,', 'expected_params_millions):', "tf.keras.backend.set_image_data_format('channels_last')", 'model', '=', 'movinet_model.MovinetClassifier(backbone=movinet.Movinet(model_id=model_id,', 'causal=True),', 'num_classes=600)', 'model.build([1,', '1,', '1,', '1,', '3])', 'num_pa... | 973,362 |
intel/neural-compressor | launcher.py | create_node | create_node | Parse line to create node. | [
"Parse",
"line",
"to",
"create",
"node."
] | def create_node(line: str):
from neural_solution.backend.cluster import Node
(hostname, num_sockets, num_cores_per_socket) = line.strip().split(' ')
(num_sockets, num_cores_per_socket) = (int(num_sockets), int(num_cores_per_socket))
node = Node(name=hostname, num_sockets=num_sockets, num_cores_per_socke... | ['def', 'create_node(line:', 'str):', 'from', 'neural_solution.backend.cluster', 'import', 'Node', '(hostname,', 'num_sockets,', 'num_cores_per_socket)', '=', "line.strip().split('", "')", '(num_sockets,', 'num_cores_per_socket)', '=', '(int(num_sockets),', 'int(num_cores_per_socket))', 'node', '=', 'Node(name=hostname... | 721,774 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | mono_text_data.py | MonoTextData.text_name | text_name | The name of text tensor, "text" by default. | [
"The",
"name",
"of",
"text",
"tensor,",
"\"text\"",
"by",
"default."
] | def text_name(self):
name = dsutils._connect_name(self._data_spec.name_prefix, self._data_spec.decoder.text_tensor_name)
return name | ['def', 'text_name(self):', 'name', '=', 'dsutils._connect_name(self._data_spec.name_prefix,', 'self._data_spec.decoder.text_tensor_name)', 'return', 'name'] | 406,083 |
Khan/guacamole | mirt_train_EM.py | generate_exercise_ind | generate_exercise_ind | Assign the next available index to an exercise name. | [
"Assign",
"the",
"next",
"available",
"index",
"to",
"an",
"exercise",
"name."
] | def generate_exercise_ind():
global num_exercises
num_exercises += 1
return num_exercises - 1 | ['def', 'generate_exercise_ind():', 'global', 'num_exercises', 'num_exercises', '+=', '1', 'return', 'num_exercises', '-', '1'] | 572,189 |
intelligent-environments-lab/CityLearn | building.py | Building.reset_data_sets | reset_data_sets | Resets time series data `start_time_step` and `end_time_step` with respect to current episode's time step settings. | [
"Resets",
"time",
"series",
"data",
"`start_time_step`",
"and",
"`end_time_step`",
"with",
"respect",
"to",
"current",
"episode's",
"time",
"step",
"settings."
] | def reset_data_sets(self):
start_time_step = self.episode_tracker.episode_start_time_step
end_time_step = self.episode_tracker.episode_end_time_step
self.energy_simulation.start_time_step = start_time_step
self.weather.start_time_step = start_time_step
self.pricing.start_time_step = start_time_step
... | ['def', 'reset_data_sets(self):', 'start_time_step', '=', 'self.episode_tracker.episode_start_time_step', 'end_time_step', '=', 'self.episode_tracker.episode_end_time_step', 'self.energy_simulation.start_time_step', '=', 'start_time_step', 'self.weather.start_time_step', '=', 'start_time_step', 'self.pricing.start_time... | 105,629 |
nicknochnack/RealTimeSignLanguageTFJS | keras_utils.py | set_gpu_thread_mode_and_count | set_gpu_thread_mode_and_count | Set GPU thread mode and count, and adjust dataset threads count. | [
"Set",
"GPU",
"thread",
"mode",
"and",
"count,",
"and",
"adjust",
"dataset",
"threads",
"count."
] | def set_gpu_thread_mode_and_count(gpu_thread_mode, datasets_num_private_threads, num_gpus, per_gpu_thread_count):
cpu_count = multiprocessing.cpu_count()
logging.info('Logical CPU cores: %s', cpu_count)
per_gpu_thread_count = per_gpu_thread_count or 2
os.environ['TF_GPU_THREAD_MODE'] = gpu_thread_mode
... | ['def', 'set_gpu_thread_mode_and_count(gpu_thread_mode,', 'datasets_num_private_threads,', 'num_gpus,', 'per_gpu_thread_count):', 'cpu_count', '=', 'multiprocessing.cpu_count()', "logging.info('Logical", 'CPU', 'cores:', "%s',", 'cpu_count)', 'per_gpu_thread_count', '=', 'per_gpu_thread_count', 'or', '2', "os.environ['... | 850,725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.