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
OmidPoursaeed/Self_supervised_Learning_Point_Clouds
generators_discriminators.py
point_cloud_generator
point_cloud_generator
used in nips submission.
[ "used", "in", "nips", "submission." ]
def point_cloud_generator(z, pc_dims, layer_sizes=[64, 128, 512, 1024], non_linearity=tf.nn.relu, b_norm=False, b_norm_last=False, dropout_prob=None): (n_points, dummy) = pc_dims if dummy != 3: raise ValueError() out_signal = decoder_with_fc_only(z, layer_sizes=layer_sizes, non_linearity=non_lineari...
['def', 'point_cloud_generator(z,', 'pc_dims,', 'layer_sizes=[64,', '128,', '512,', '1024],', 'non_linearity=tf.nn.relu,', 'b_norm=False,', 'b_norm_last=False,', 'dropout_prob=None):', '(n_points,', 'dummy)', '=', 'pc_dims', 'if', 'dummy', '!=', '3:', 'raise', 'ValueError()', 'out_signal', '=', 'decoder_with_fc_only(z,...
342,601
mattgolub/recurrent-whisperer
RecurrentWhisperer.py
RecurrentWhisperer.is_run_dir
is_run_dir
Determines whether a run exists in a specified directory.
[ "Determines", "whether", "a", "run", "exists", "in", "a", "specified", "directory." ]
def is_run_dir(cls, run_dir): if run_dir is None: return False dirs = cls._build_subdirs(run_dir) exists = [os.path.exists(d) for d in list(dirs.values())] return all(exists)
['def', 'is_run_dir(cls,', 'run_dir):', 'if', 'run_dir', 'is', 'None:', 'return', 'False', 'dirs', '=', 'cls._build_subdirs(run_dir)', 'exists', '=', '[os.path.exists(d)', 'for', 'd', 'in', 'list(dirs.values())]', 'return', 'all(exists)']
309,469
greydanus/mr_london
compiler.py
Frame.copy
copy
Create a copy of the current one.
[ "Create", "a", "copy", "of", "the", "current", "one." ]
def copy(self): rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv
['def', 'copy(self):', 'rv', '=', 'object.__new__(self.__class__)', 'rv.__dict__.update(self.__dict__)', 'rv.identifiers', '=', 'object.__new__(self.identifiers.__class__)', 'rv.identifiers.__dict__.update(self.identifiers.__dict__)', 'return', 'rv']
262,251
chenbinghui1/DSL
transforms.py
bbox2distance
bbox2distance
Decode bounding box based on distances.
[ "Decode", "bounding", "box", "based", "on", "distances." ]
def bbox2distance(points, bbox, max_dis=None, eps=0.1): left = points[:, 0] - bbox[:, 0] top = points[:, 1] - bbox[:, 1] right = bbox[:, 2] - points[:, 0] bottom = bbox[:, 3] - points[:, 1] if max_dis is not None: left = left.clamp(min=0, max=max_dis - eps) top = top.clamp(min=0, max...
['def', 'bbox2distance(points,', 'bbox,', 'max_dis=None,', 'eps=0.1):', 'left', '=', 'points[:,', '0]', '-', 'bbox[:,', '0]', 'top', '=', 'points[:,', '1]', '-', 'bbox[:,', '1]', 'right', '=', 'bbox[:,', '2]', '-', 'points[:,', '0]', 'bottom', '=', 'bbox[:,', '3]', '-', 'points[:,', '1]', 'if', 'max_dis', 'is', 'not', ...
167,413
nilearn/nilearn
test_displays.py
test_slicer_save_to_file
test_slicer_save_to_file
Tests for saving to file with Ortho/Tiled/Mosaic slicers.
[ "Tests", "for", "saving", "to", "file", "with", "Ortho/Tiled/Mosaic", "slicers." ]
def test_slicer_save_to_file(slicer, img, tmp_path): cut_coords = None if slicer == MosaicSlicer else (0, 0, 0) slicer = slicer.init_with_figure(img=img, cut_coords=cut_coords, colorbar=True) slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True) assert slicer.brain_color == (0.5, 0.5, 0.5) assert...
['def', 'test_slicer_save_to_file(slicer,', 'img,', 'tmp_path):', 'cut_coords', '=', 'None', 'if', 'slicer', '==', 'MosaicSlicer', 'else', '(0,', '0,', '0)', 'slicer', '=', 'slicer.init_with_figure(img=img,', 'cut_coords=cut_coords,', 'colorbar=True)', 'slicer.add_overlay(img,', 'cmap=plt.cm.gray,', 'colorbar=True)', '...
724,103
google-research/scenic
hungarian_jax.py
hungarian_single
hungarian_single
Hungarian matcher for a single example.
[ "Hungarian", "matcher", "for", "a", "single", "example." ]
def hungarian_single(cost): is_transpose = cost.shape[0] > cost.shape[1] if is_transpose: cost = cost.T (n, m) = cost.shape one_hot_m = jnp.eye(m + 1) def row_scan_fn(state, i): (u, v, parent) = state parent = jax.lax.dynamic_update_index_in_dim(parent, i, 0, axis=0) ...
['def', 'hungarian_single(cost):', 'is_transpose', '=', 'cost.shape[0]', '>', 'cost.shape[1]', 'if', 'is_transpose:', 'cost', '=', 'cost.T', '(n,', 'm)', '=', 'cost.shape', 'one_hot_m', '=', 'jnp.eye(m', '+', '1)', 'def', 'row_scan_fn(state,', 'i):', '(u,', 'v,', 'parent)', '=', 'state', 'parent', '=', 'jax.lax.dynamic...
846,287
tensorflow/agents
tf_metrics.py
DistanceFromGreedyMetric.call
call
Update the metric value.
[ "Update", "the", "metric", "value." ]
def call(self, trajectory): all_estimated_rewards = self._estimated_reward_fn(trajectory.observation) max_estimated_rewards = tf.reduce_max(all_estimated_rewards, axis=-1) estimated_action_rewards = tf.gather(all_estimated_rewards, trajectory.action, batch_dims=1) self.safe_explore.assign(tf.reduce_mean...
['def', 'call(self,', 'trajectory):', 'all_estimated_rewards', '=', 'self._estimated_reward_fn(trajectory.observation)', 'max_estimated_rewards', '=', 'tf.reduce_max(all_estimated_rewards,', 'axis=-1)', 'estimated_action_rewards', '=', 'tf.gather(all_estimated_rewards,', 'trajectory.action,', 'batch_dims=1)', 'self.saf...
23,324
zcablii/LSKNet
test_forward.py
test_single_stage_forward_gpu
test_single_stage_forward_gpu
Test single stage forward (GPU).
[ "Test", "single", "stage", "forward", "(GPU)." ]
def test_single_stage_forward_gpu(cfg_file): if not torch.cuda.is_available(): import pytest pytest.skip('test requires GPU and torch+cuda') model = _get_detector_cfg(cfg_file) model = _replace_r50_with_r18(model) model.backbone.init_cfg = None from mmdet.models import build_detector...
['def', 'test_single_stage_forward_gpu(cfg_file):', 'if', 'not', 'torch.cuda.is_available():', 'import', 'pytest', "pytest.skip('test", 'requires', 'GPU', 'and', "torch+cuda')", 'model', '=', '_get_detector_cfg(cfg_file)', 'model', '=', '_replace_r50_with_r18(model)', 'model.backbone.init_cfg', '=', 'None', 'from', 'mm...
616,262
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
test_json.py
data
data
Length-100 PeriodArray for semantics test.
[ "Length-100", "PeriodArray", "for", "semantics", "test." ]
def data(): data = make_data() while len(data[0]) == len(data[1]): data = make_data() return JSONArray(data)
['def', 'data():', 'data', '=', 'make_data()', 'while', 'len(data[0])', '==', 'len(data[1]):', 'data', '=', 'make_data()', 'return', 'JSONArray(data)']
968,199
facebookresearch/CompilerGym
validation.py
Validation.wrap_env
wrap_env
Wrap an environment for use in the training loop that is configured to iterate over the validation benchmarks on each call to :code:`reset()`.
[ "Wrap", "an", "environment", "for", "use", "in", "the", "training", "loop", "that", "is", "configured", "to", "iterate", "over", "the", "validation", "benchmarks", "on", "each", "call", "to", ":code:`reset()`." ]
def wrap_env(self, env: CompilerEnv) -> CompilerEnv: return CycleOverBenchmarks(env=env, benchmarks=self.benchmarks_iterator(env))
['def', 'wrap_env(self,', 'env:', 'CompilerEnv)', '->', 'CompilerEnv:', 'return', 'CycleOverBenchmarks(env=env,', 'benchmarks=self.benchmarks_iterator(env))']
135,698
TrellixVulnTeam/Unsupervised_Learning_HFI7
app.py
vi_navigation_mode
vi_navigation_mode
Active when the set for Vi navigation key bindings are active.
[ "Active", "when", "the", "set", "for", "Vi", "navigation", "key", "bindings", "are", "active." ]
def vi_navigation_mode() -> bool: from prompt_toolkit.key_binding.vi_state import InputMode app = get_app() if app.editing_mode != EditingMode.VI or app.vi_state.operator_func or app.vi_state.waiting_for_digraph or app.current_buffer.selection_state: return False return app.vi_state.input_mode =...
['def', 'vi_navigation_mode()', '->', 'bool:', 'from', 'prompt_toolkit.key_binding.vi_state', 'import', 'InputMode', 'app', '=', 'get_app()', 'if', 'app.editing_mode', '!=', 'EditingMode.VI', 'or', 'app.vi_state.operator_func', 'or', 'app.vi_state.waiting_for_digraph', 'or', 'app.current_buffer.selection_state:', 'retu...
435,140
jimtin/Stock_Comparison
metadata.py
handle_requires
handle_requires
Place the runtime requirements from pkg_info into metadata.
[ "Place", "the", "runtime", "requirements", "from", "pkg_info", "into", "metadata." ]
def handle_requires(metadata, pkg_info, key): may_requires = defaultdict(list) for value in pkg_info.get_all(key): extra_match = EXTRA_RE.search(value) if extra_match: groupdict = extra_match.groupdict() condition = groupdict['condition'] extra = groupdict['ex...
['def', 'handle_requires(metadata,', 'pkg_info,', 'key):', 'may_requires', '=', 'defaultdict(list)', 'for', 'value', 'in', 'pkg_info.get_all(key):', 'extra_match', '=', 'EXTRA_RE.search(value)', 'if', 'extra_match:', 'groupdict', '=', 'extra_match.groupdict()', 'condition', '=', "groupdict['condition']", 'extra', '=', ...
359,452
Kvatsx/Artificial-Intelligence-Assignments
test_waveforms.py
compute_frequency
compute_frequency
Compute theta'(t)/(2*pi), where theta'(t) is the derivative of theta(t).
[ "Compute", "theta'(t)/(2*pi),", "where", "theta'(t)", "is", "the", "derivative", "of", "theta(t)." ]
def compute_frequency(t, theta): dt = t[1] - t[0] f = np.diff(theta) / (2 * np.pi) / dt tf = 0.5 * (t[1:] + t[:-1]) return (tf, f)
['def', 'compute_frequency(t,', 'theta):', 'dt', '=', 't[1]', '-', 't[0]', 'f', '=', 'np.diff(theta)', '/', '(2', '*', 'np.pi)', '/', 'dt', 'tf', '=', '0.5', '*', '(t[1:]', '+', 't[:-1])', 'return', '(tf,', 'f)']
77,942
tensorflow/agents
piecewise_stochastic_environment_test.py
get_deterministic_gaussian_non_stationary_environment
get_deterministic_gaussian_non_stationary_environment
Returns a PiecewiseStochasticEnvironment with deterministic intervals.
[ "Returns", "a", "PiecewiseStochasticEnvironment", "with", "deterministic", "intervals." ]
def get_deterministic_gaussian_non_stationary_environment(observation_shape, action_shape, batch_size, interval): overall_shape = [batch_size] + observation_shape observation_distribution = tfd.Normal(loc=tf.zeros(overall_shape), scale=tf.ones(overall_shape)) interval_distribution = tfd.Deterministic(interv...
['def', 'get_deterministic_gaussian_non_stationary_environment(observation_shape,', 'action_shape,', 'batch_size,', 'interval):', 'overall_shape', '=', '[batch_size]', '+', 'observation_shape', 'observation_distribution', '=', 'tfd.Normal(loc=tf.zeros(overall_shape),', 'scale=tf.ones(overall_shape))', 'interval_distrib...
22,584
AlbertoSabater/Robust-and-efficient-post-processing-for-video--
module.py
Module.load_optimizer_states
load_optimizer_states
Load optimizer (updater) state from file Parameters ---------- fname : str Path to input states file.
[ "Load", "optimizer", "(updater)", "state", "from", "file", "Parameters", "----------", "fname", ":", "str", "Path", "to", "input", "states", "file." ]
def load_optimizer_states(self, fname): assert self.optimizer_initialized if self._update_on_kvstore: self._kvstore.load_optimizer_states(fname) else: self._updater.set_states(open(fname, 'rb').read())
['def', 'load_optimizer_states(self,', 'fname):', 'assert', 'self.optimizer_initialized', 'if', 'self._update_on_kvstore:', 'self._kvstore.load_optimizer_states(fname)', 'else:', 'self._updater.set_states(open(fname,', "'rb').read())"]
826,127
43Carrig/recurrent_neural_networks_practice
jsrouting.py
generate_adapter
generate_adapter
Generates the url building function for a map.
[ "Generates", "the", "url", "building", "function", "for", "a", "map." ]
def generate_adapter(adapter, name='url_for', map_name='url_map'): values = {u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name} return u'var %(name)s = %(m...
['def', 'generate_adapter(adapter,', "name='url_for',", "map_name='url_map'):", 'values', '=', "{u'server_name':", 'dumps(adapter.server_name),', "u'script_name':", 'dumps(adapter.script_name),', "u'subdomain':", 'dumps(adapter.subdomain),', "u'url_scheme':", 'dumps(adapter.url_scheme),', "u'name':", 'name,', "u'map_na...
340,272
gunthercox/ChatterBot
unitofwork.py
UOWTransaction.filter_states_for_dep
filter_states_for_dep
Filter the given list of InstanceStates to those relevant to the given DependencyProcessor.
[ "Filter", "the", "given", "list", "of", "InstanceStates", "to", "those", "relevant", "to", "the", "given", "DependencyProcessor." ]
def filter_states_for_dep(self, dep, states): mapper_for_dep = self._mapper_for_dep return [s for s in states if mapper_for_dep[s.manager.mapper, dep]]
['def', 'filter_states_for_dep(self,', 'dep,', 'states):', 'mapper_for_dep', '=', 'self._mapper_for_dep', 'return', '[s', 'for', 's', 'in', 'states', 'if', 'mapper_for_dep[s.manager.mapper,', 'dep]]']
534,769
tensorflow/quantum
noisy_pqc_test.py
NoisyPQCTest.test_noisy_pqc_constraint
test_noisy_pqc_constraint
Test attachment of constraint to layer.
[ "Test", "attachment", "of", "constraint", "to", "layer." ]
def test_noisy_pqc_constraint(self): my_constraint = tf.keras.constraints.NonNeg() (a, b, c) = sympy.symbols('a b c') qubit = cirq.GridQubit(0, 0) three_parameters = cirq.Circuit([cirq.X(qubit) ** a, cirq.Y(qubit) ** b, cirq.Z(qubit) ** c]) mpqc = noisy_pqc.NoisyPQC(three_parameters, cirq.Z(qubit), ...
['def', 'test_noisy_pqc_constraint(self):', 'my_constraint', '=', 'tf.keras.constraints.NonNeg()', '(a,', 'b,', 'c)', '=', "sympy.symbols('a", 'b', "c')", 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'three_parameters', '=', 'cirq.Circuit([cirq.X(qubit)', '**', 'a,', 'cirq.Y(qubit)', '**', 'b,', 'cirq.Z(qubit)', '**', 'c])...
835,422
cnr-isti-vclab/TagLab
QtImageViewerPlus.py
QtImageViewerPlus.addToSelectedList
addToSelectedList
Add the given blob to the list of selected blob.
[ "Add", "the", "given", "blob", "to", "the", "list", "of", "selected", "blob." ]
def addToSelectedList(self, blob): if blob in self.selected_blobs: self.logfile.info('[SELECTION] An already selected blob has been added to the current selection.') else: self.selected_blobs.append(blob) str = '[SELECTION] A new blob (' + blob.blob_name + ';' + blob.class_name + ') has ...
['def', 'addToSelectedList(self,', 'blob):', 'if', 'blob', 'in', 'self.selected_blobs:', "self.logfile.info('[SELECTION]", 'An', 'already', 'selected', 'blob', 'has', 'been', 'added', 'to', 'the', 'current', "selection.')", 'else:', 'self.selected_blobs.append(blob)', 'str', '=', "'[SELECTION]", 'A', 'new', 'blob', "('...
906,823
shreya2224/NaturalLanguageProcessing
create_pretraining_data.py
truncate_seq_pair
truncate_seq_pair
Truncates a pair of sequences to a maximum sequence length.
[ "Truncates", "a", "pair", "of", "sequences", "to", "a", "maximum", "sequence", "length." ]
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 i...
['def', 'truncate_seq_pair(tokens_a,', 'tokens_b,', 'max_num_tokens,', 'rng):', 'while', 'True:', 'total_length', '=', 'len(tokens_a)', '+', 'len(tokens_b)', 'if', 'total_length', '<=', 'max_num_tokens:', 'break', 'trunc_tokens', '=', 'tokens_a', 'if', 'len(tokens_a)', '>', 'len(tokens_b)', 'else', 'tokens_b', 'assert'...
709,890
sarnsdev/social-alignment-data-mining
test_discriminant_analysis.py
test_raises_value_error_on_same_number_of_classes_and_samples
test_raises_value_error_on_same_number_of_classes_and_samples
Tests that if the number of samples equals the number of classes, a ValueError is raised.
[ "Tests", "that", "if", "the", "number", "of", "samples", "equals", "the", "number", "of", "classes,", "a", "ValueError", "is", "raised." ]
def test_raises_value_error_on_same_number_of_classes_and_samples(solver): X = np.array([[0.5, 0.6], [0.6, 0.5]]) y = np.array(['a', 'b']) clf = LinearDiscriminantAnalysis(solver=solver) with pytest.raises(ValueError, match='The number of samples must be more'): clf.fit(X, y)
['def', 'test_raises_value_error_on_same_number_of_classes_and_samples(solver):', 'X', '=', 'np.array([[0.5,', '0.6],', '[0.6,', '0.5]])', 'y', '=', "np.array(['a',", "'b'])", 'clf', '=', 'LinearDiscriminantAnalysis(solver=solver)', 'with', 'pytest.raises(ValueError,', "match='The", 'number', 'of', 'samples', 'must', '...
392,364
ashwanitanwar/nmt-transfer-learning-xlm-r
bpe_utils.py
tokenize_and_align
tokenize_and_align
Given already-tokenized text (as a list of strings), returns a list of lists where each sub-list contains BERT-tokenized tokens for the correponding word.
[ "Given", "already-tokenized", "text", "(as", "a", "list", "of", "strings),", "returns", "a", "list", "of", "lists", "where", "each", "sub-list", "contains", "BERT-tokenized", "tokens", "for", "the", "correponding", "word." ]
def tokenize_and_align(tokenizer, words, args, bert_or_self, pre_tokenized_words): if bert_or_self == 'bert': words = ['<s>'] + words + ['</s>'] else: words = words + ['</s>'] tokenized_words = [] for word in words: if word == '<s>' or word == '</s>': word_toks = [wor...
['def', 'tokenize_and_align(tokenizer,', 'words,', 'args,', 'bert_or_self,', 'pre_tokenized_words):', 'if', 'bert_or_self', '==', "'bert':", 'words', '=', "['<s>']", '+', 'words', '+', "['</s>']", 'else:', 'words', '=', 'words', '+', "['</s>']", 'tokenized_words', '=', '[]', 'for', 'word', 'in', 'words:', 'if', 'word',...
731,754
KalleHallden/InstaAutomator
install.py
build_wheels
build_wheels
Build wheels for requirements, depending on whether wheel is installed.
[ "Build", "wheels", "for", "requirements,", "depending", "on", "whether", "wheel", "is", "installed." ]
def build_wheels(builder, pep517_requirements, legacy_requirements, session): should_build_legacy = is_wheel_installed() build_failures = builder.build(pep517_requirements, session=session, autobuilding=True) if should_build_legacy: builder.build(legacy_requirements, session=session, autobuilding=Tr...
['def', 'build_wheels(builder,', 'pep517_requirements,', 'legacy_requirements,', 'session):', 'should_build_legacy', '=', 'is_wheel_installed()', 'build_failures', '=', 'builder.build(pep517_requirements,', 'session=session,', 'autobuilding=True)', 'if', 'should_build_legacy:', 'builder.build(legacy_requirements,', 'se...
243,778
codekansas/gandlf
mnist_gan.py
build_generator
build_generator
Builds the big generator model.
[ "Builds", "the", "big", "generator", "model." ]
def build_generator(latent_size, supervised): cnn = keras.models.Sequential() cnn.add(keras.layers.Dense(1024, input_dim=latent_size, activation='relu')) cnn.add(keras.layers.Dense(128 * 7 * 7, activation='relu')) cnn.add(keras.layers.Reshape((7, 7, 128))) cnn.add(keras.layers.UpSampling2D(size=(2, ...
['def', 'build_generator(latent_size,', 'supervised):', 'cnn', '=', 'keras.models.Sequential()', 'cnn.add(keras.layers.Dense(1024,', 'input_dim=latent_size,', "activation='relu'))", 'cnn.add(keras.layers.Dense(128', '*', '7', '*', '7,', "activation='relu'))", 'cnn.add(keras.layers.Reshape((7,', '7,', '128)))', 'cnn.add...
566,516
cheind/gcsl
mock_dynamixel_sdk.py
patch_dynamixel
patch_dynamixel
Decorator that patches the DynamixelSDK for the function context.
[ "Decorator", "that", "patches", "the", "DynamixelSDK", "for", "the", "function", "context." ]
def patch_dynamixel(**devices): def decorator(fn): def wrapped_fn(*args): sdk = MockDynamixelSdk() for (key, motor_ids) in devices.items(): sdk.create_device(key, motor_ids) sys.modules['dynamixel_sdk'] = sdk fn(*args, sdk) del sy...
['def', 'patch_dynamixel(**devices):', 'def', 'decorator(fn):', 'def', 'wrapped_fn(*args):', 'sdk', '=', 'MockDynamixelSdk()', 'for', '(key,', 'motor_ids)', 'in', 'devices.items():', 'sdk.create_device(key,', 'motor_ids)', "sys.modules['dynamixel_sdk']", '=', 'sdk', 'fn(*args,', 'sdk)', 'del', "sys.modules['dynamixel_s...
202,142
clementchadebec/benchmark_VAE
pvae_utils.py
rexpand
rexpand
Expand tensor, adding new dimensions on right.
[ "Expand", "tensor,", "adding", "new", "dimensions", "on", "right." ]
def rexpand(A, *dimensions): return A.view(A.shape + (1,) * len(dimensions)).expand(A.shape + tuple(dimensions))
['def', 'rexpand(A,', '*dimensions):', 'return', 'A.view(A.shape', '+', '(1,)', '*', 'len(dimensions)).expand(A.shape', '+', 'tuple(dimensions))']
433,993
af/djangbone
views.py
BackboneAPIView.delete
delete
Respond to DELETE requests by deleting the model and returning its JSON representation.
[ "Respond", "to", "DELETE", "requests", "by", "deleting", "the", "model", "and", "returning", "its", "JSON", "representation." ]
def delete(self, request, *args, **kwargs): if not kwargs.has_key('id'): return HttpResponse('DELETE is not supported for collections', status=405) qs = self.base_queryset.filter(id=kwargs['id']) if qs: output = self.serialize_qs(qs) qs.delete() return self.success_response(o...
['def', 'delete(self,', 'request,', '*args,', '**kwargs):', 'if', 'not', "kwargs.has_key('id'):", 'return', "HttpResponse('DELETE", 'is', 'not', 'supported', 'for', "collections',", 'status=405)', 'qs', '=', "self.base_queryset.filter(id=kwargs['id'])", 'if', 'qs:', 'output', '=', 'self.serialize_qs(qs)', 'qs.delete()'...
189,481
intel/neural-compressor
tf2onnx_utils.py
get_subgraphs_from_onnx
get_subgraphs_from_onnx
Returns an iterator over the graphs/subgraphs of a model (using dfs).
[ "Returns", "an", "iterator", "over", "the", "graphs/subgraphs", "of", "a", "model", "(using", "dfs)." ]
def get_subgraphs_from_onnx(model_proto): stack = [model_proto.graph] while stack: g = stack.pop() yield g for node in g.node: for attr in node.attribute: if hasattr(attr, 'g'): stack.append(attr.g) if hasattr(attr, 'graphs'...
['def', 'get_subgraphs_from_onnx(model_proto):', 'stack', '=', '[model_proto.graph]', 'while', 'stack:', 'g', '=', 'stack.pop()', 'yield', 'g', 'for', 'node', 'in', 'g.node:', 'for', 'attr', 'in', 'node.attribute:', 'if', 'hasattr(attr,', "'g'):", 'stack.append(attr.g)', 'if', 'hasattr(attr,', "'graphs'):", 'stack.exte...
737,753
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
trainable_optimizer.py
create_local_state_variable_name
create_local_state_variable_name
Create a name of the variable based on its type and shape.
[ "Create", "a", "name", "of", "the", "variable", "based", "on", "its", "type", "and", "shape." ]
def create_local_state_variable_name(tensor): if not tensor.get_shape().is_fully_defined(): raise ValueError('Need a fully specified shape to create a local variable.') return _LOCAL_VARIABLE_PREFIX + '_'.join(map(str, tensor.get_shape().as_list())) + '_' + tensor.dtype.name
['def', 'create_local_state_variable_name(tensor):', 'if', 'not', 'tensor.get_shape().is_fully_defined():', 'raise', "ValueError('Need", 'a', 'fully', 'specified', 'shape', 'to', 'create', 'a', 'local', "variable.')", 'return', '_LOCAL_VARIABLE_PREFIX', '+', "'_'.join(map(str,", 'tensor.get_shape().as_list()))', '+', "...
55,458
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
beam_search.py
BeamSearch.BeamSearch
BeamSearch
Performs beam search for decoding.
[ "Performs", "beam", "search", "for", "decoding." ]
def BeamSearch(self, sess, enc_inputs, enc_seqlen): (enc_top_states, dec_in_state) = self._model.encode_top_state(sess, enc_inputs, enc_seqlen) hyps = [Hypothesis([self._start_token], 0.0, dec_in_state)] * self._beam_size results = [] steps = 0 while steps < self._max_steps and len(results) < self._...
['def', 'BeamSearch(self,', 'sess,', 'enc_inputs,', 'enc_seqlen):', '(enc_top_states,', 'dec_in_state)', '=', 'self._model.encode_top_state(sess,', 'enc_inputs,', 'enc_seqlen)', 'hyps', '=', '[Hypothesis([self._start_token],', '0.0,', 'dec_in_state)]', '*', 'self._beam_size', 'results', '=', '[]', 'steps', '=', '0', 'w...
112,678
Ruturaj123/Flowchart-Detection
skip_gram_ops_test.py
SkipGramOpsTest.test_filter_input_subsample_vocab
test_filter_input_subsample_vocab
Tests input filtering based on vocab subsampling.
[ "Tests", "input", "filtering", "based", "on", "vocab", "subsampling." ]
def test_filter_input_subsample_vocab(self): random_seed.set_random_seed(42) input_tensor = constant_op.constant([b'the', b'answer', b'to', b'life', b'and', b'universe']) keys = constant_op.constant([b'and', b'life', b'the', b'to', b'universe']) values = constant_op.constant([40, 8, 30, 20, 2], dtypes.i...
['def', 'test_filter_input_subsample_vocab(self):', 'random_seed.set_random_seed(42)', 'input_tensor', '=', "constant_op.constant([b'the',", "b'answer',", "b'to',", "b'life',", "b'and',", "b'universe'])", 'keys', '=', "constant_op.constant([b'and',", "b'life',", "b'the',", "b'to',", "b'universe'])", 'values', '=', 'con...
604,620
rudranil723/mini-main
blocks.py
ObjectBlock.reduce
reduce
For object-dtype, we operate column-wise.
[ "For", "object-dtype,", "we", "operate", "column-wise." ]
def reduce(self, func, ignore_failures: bool=False) -> list[Block]: assert self.ndim == 2 try: res = func(self.values) except TypeError: if not ignore_failures: raise return [] assert isinstance(res, np.ndarray) assert res.ndim == 1 res = res.reshape(1, -1) ...
['def', 'reduce(self,', 'func,', 'ignore_failures:', 'bool=False)', '->', 'list[Block]:', 'assert', 'self.ndim', '==', '2', 'try:', 'res', '=', 'func(self.values)', 'except', 'TypeError:', 'if', 'not', 'ignore_failures:', 'raise', 'return', '[]', 'assert', 'isinstance(res,', 'np.ndarray)', 'assert', 'res.ndim', '==', '...
324,065
befelix/safe_learning
test_lyapunov.py
TestLyapunov.test_safe_set_init
test_safe_set_init
Test the safe set initialization.
[ "Test", "the", "safe", "set", "initialization." ]
def test_safe_set_init(self): with tf.Session(): discretization = GridWorld([[0, 1], [0, 1]], 3) lyap_fun = lambda x: tf.reduce_sum(tf.square(x), axis=1) dynamics = LinearSystem(np.array([[1, 0.01], [0.0, 1.0]])) lf = 0.4 lv = 0.3 eps = 0.5 policy = lambda x: ...
['def', 'test_safe_set_init(self):', 'with', 'tf.Session():', 'discretization', '=', 'GridWorld([[0,', '1],', '[0,', '1]],', '3)', 'lyap_fun', '=', 'lambda', 'x:', 'tf.reduce_sum(tf.square(x),', 'axis=1)', 'dynamics', '=', 'LinearSystem(np.array([[1,', '0.01],', '[0.0,', '1.0]]))', 'lf', '=', '0.4', 'lv', '=', '0.3', '...
328,252
Liyunfan1998/FDU_Artificial-Intelligence
alpha_beta_pruning_template.py
construct_tree
construct_tree
Construct a tree using given information and return the root node.
[ "Construct", "a", "tree", "using", "given", "information", "and", "return", "the", "root", "node." ]
def construct_tree(n, tree, rule): node = Node(rule=rule) successors = [] if n == 1: for t in tree: successors.append(Node(rule=1 - rule, is_leaf=True, value=t)) else: for t in tree: successors.append(construct_tree(n - 1, t, 1 - rule)) node.successor = succes...
['def', 'construct_tree(n,', 'tree,', 'rule):', 'node', '=', 'Node(rule=rule)', 'successors', '=', '[]', 'if', 'n', '==', '1:', 'for', 't', 'in', 'tree:', 'successors.append(Node(rule=1', '-', 'rule,', 'is_leaf=True,', 'value=t))', 'else:', 'for', 't', 'in', 'tree:', 'successors.append(construct_tree(n', '-', '1,', 't,...
179,349
apeterswu/RL4NMT
transformer_sketch.py
transformer_sketch_ranged
transformer_sketch_ranged
Range of hparams for vizier.
[ "Range", "of", "hparams", "for", "vizier." ]
def transformer_sketch_ranged(rhp): hparams = transformer_sketch() common_hparams.fill_ranged_hparams_from_hparams(hparams, rhp) rhp.set_categorical('ffn_layer', ['conv_hidden_relu_with_sepconv', 'conv_hidden_relu']) rhp.set_discrete('batch_size', [1024, 2048, 4096]) rhp.set_discrete('num_hidden_lay...
['def', 'transformer_sketch_ranged(rhp):', 'hparams', '=', 'transformer_sketch()', 'common_hparams.fill_ranged_hparams_from_hparams(hparams,', 'rhp)', "rhp.set_categorical('ffn_layer',", "['conv_hidden_relu_with_sepconv',", "'conv_hidden_relu'])", "rhp.set_discrete('batch_size',", '[1024,', '2048,', '4096])', "rhp.set_...
331,693
apeterswu/RL4NMT
metrics.py
set_precision
set_precision
Precision of set predictions.
[ "Precision", "of", "set", "predictions." ]
def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero): with tf.variable_scope('set_precision', values=[predictions, labels]): labels = tf.squeeze(labels, [2, 3]) weights = weights_fn(labels) labels = tf.one_hot(labels, predictions.shape[-1]) labels = tf.red...
['def', 'set_precision(predictions,', 'labels,', 'weights_fn=common_layers.weights_nonzero):', 'with', "tf.variable_scope('set_precision',", 'values=[predictions,', 'labels]):', 'labels', '=', 'tf.squeeze(labels,', '[2,', '3])', 'weights', '=', 'weights_fn(labels)', 'labels', '=', 'tf.one_hot(labels,', 'predictions.sha...
331,284
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
Expression.pushRight
pushRight
Creates a new right expression, sets it, and returns it.
[ "Creates", "a", "new", "right", "expression,", "sets", "it,", "and", "returns", "it." ]
def pushRight(self, value=''): self.right = self.factory.expr(left=value, parent=self) return self.right
['def', 'pushRight(self,', "value=''):", 'self.right', '=', 'self.factory.expr(left=value,', 'parent=self)', 'return', 'self.right']
17,128
mingkai-zheng/WCL
load.py
Loader.clean
clean
Clean the report text.
[ "Clean", "the", "report", "text." ]
def clean(self, report): lower_report = report.lower() corrected_report = re.sub('and/or', 'or', lower_report) corrected_report = re.sub('(?<=[a-zA-Z])/(?=[a-zA-Z])', ' or ', corrected_report) clean_report = corrected_report.replace('..', '.') clean_report = clean_report.translate(self.punctuation_s...
['def', 'clean(self,', 'report):', 'lower_report', '=', 'report.lower()', 'corrected_report', '=', "re.sub('and/or',", "'or',", 'lower_report)', 'corrected_report', '=', "re.sub('(?<=[a-zA-Z])/(?=[a-zA-Z])',", "'", 'or', "',", 'corrected_report)', 'clean_report', '=', "corrected_report.replace('..',", "'.')", 'clean_re...
373,014
googleapis/python-aiplatform
client.py
JobServiceClient.parse_model_path
parse_model_path
Parses a model path into its component segments.
[ "Parses", "a", "model", "path", "into", "its", "component", "segments." ]
def parse_model_path(path: str) -> Dict[str, str]: m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/models/(?P<model>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_model_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/models/(?P<model>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
813,054
jason718/game-feature-learning
test_net_spec.py
TestNetSpec.test_zero_tops
test_zero_tops
Test net construction for top-less layers.
[ "Test", "net", "construction", "for", "top-less", "layers." ]
def test_zero_tops(self): net_proto = silent_net() net = self.load_net(net_proto) self.assertEqual(len(net.forward()), 0)
['def', 'test_zero_tops(self):', 'net_proto', '=', 'silent_net()', 'net', '=', 'self.load_net(net_proto)', 'self.assertEqual(len(net.forward()),', '0)']
199,501
clips/pattern
__init__.py
parse
parse
Returns a tagged Unicode string.
[ "Returns", "a", "tagged", "Unicode", "string." ]
def parse(s, *args, **kwargs): return parser.parse(s, *args, **kwargs)
['def', 'parse(s,', '*args,', '**kwargs):', 'return', 'parser.parse(s,', '*args,', '**kwargs)']
765,010
sarnsdev/social-alignment-data-mining
versioncontrol.py
VersionControl.get_base_rev_args
get_base_rev_args
Return the base revision arguments for a vcs command.
[ "Return", "the", "base", "revision", "arguments", "for", "a", "vcs", "command." ]
def get_base_rev_args(rev): raise NotImplementedError
['def', 'get_base_rev_args(rev):', 'raise', 'NotImplementedError']
389,892
sktime/sktime
test_time_series_neighbors.py
test_knn_with_aligner
test_knn_with_aligner
Tests KNN classifer with alignment distance on unequal length data.
[ "Tests", "KNN", "classifer", "with", "alignment", "distance", "on", "unequal", "length", "data." ]
def test_knn_with_aligner(): from sktime.dists_kernels.compose_from_align import DistFromAligner from sktime.utils._testing.hierarchical import _make_hierarchical X = _make_hierarchical((3,), min_timepoints=5, max_timepoints=10, random_state=0) y = np.array([0, 1, 1]) dtw_dist = DistFromAligner(Alig...
['def', 'test_knn_with_aligner():', 'from', 'sktime.dists_kernels.compose_from_align', 'import', 'DistFromAligner', 'from', 'sktime.utils._testing.hierarchical', 'import', '_make_hierarchical', 'X', '=', '_make_hierarchical((3,),', 'min_timepoints=5,', 'max_timepoints=10,', 'random_state=0)', 'y', '=', 'np.array([0,', ...
885,960
nosmokingbandit/watcher
zlib.py
extend_data
extend_data
Extend data using a length and an offset.
[ "Extend", "data", "using", "a", "length", "and", "an", "offset." ]
def extend_data(data, length, offset): if length >= offset: new_data = data[-offset:] * (alignValue(length, offset) // offset) return data + new_data[:length] else: return data + data[-offset:-offset + length]
['def', 'extend_data(data,', 'length,', 'offset):', 'if', 'length', '>=', 'offset:', 'new_data', '=', 'data[-offset:]', '*', '(alignValue(length,', 'offset)', '//', 'offset)', 'return', 'data', '+', 'new_data[:length]', 'else:', 'return', 'data', '+', 'data[-offset:-offset', '+', 'length]']
381,708
antonilo/unsupervised_detection
convolution_utils.py
resize
resize
This resize operation is used to scale the input according to some given scale and function.
[ "This", "resize", "operation", "is", "used", "to", "scale", "the", "input", "according", "to", "some", "given", "scale", "and", "function." ]
def resize(x, scale=2, to_shape=None, align_corners=True, dynamic=False, func=tf.image.resize_bilinear, name='resize'): if dynamic: xs = tf.cast(tf.shape(x), tf.float32) new_xs = [tf.cast(xs[1] * scale, tf.int32), tf.cast(xs[2] * scale, tf.int32)] else: xs = x.get_shape().as_list() ...
['def', 'resize(x,', 'scale=2,', 'to_shape=None,', 'align_corners=True,', 'dynamic=False,', 'func=tf.image.resize_bilinear,', "name='resize'):", 'if', 'dynamic:', 'xs', '=', 'tf.cast(tf.shape(x),', 'tf.float32)', 'new_xs', '=', '[tf.cast(xs[1]', '*', 'scale,', 'tf.int32),', 'tf.cast(xs[2]', '*', 'scale,', 'tf.int32)]',...
353,995
aivclab/vision
utils.py
download_file_from_google_drive
download_file_from_google_drive
Download a Google Drive file from and place it in root.
[ "Download", "a", "Google", "Drive", "file", "from", "and", "place", "it", "in", "root." ]
def download_file_from_google_drive(file_id: str, root: str, filename: Optional[str]=None, md5: Optional[str]=None): root = os.path.expanduser(root) if not filename: filename = file_id fpath = os.path.join(root, filename) os.makedirs(root, exist_ok=True) if check_integrity(fpath, md5): ...
['def', 'download_file_from_google_drive(file_id:', 'str,', 'root:', 'str,', 'filename:', 'Optional[str]=None,', 'md5:', 'Optional[str]=None):', 'root', '=', 'os.path.expanduser(root)', 'if', 'not', 'filename:', 'filename', '=', 'file_id', 'fpath', '=', 'os.path.join(root,', 'filename)', 'os.makedirs(root,', 'exist_ok=...
958,264
UAVs-at-Berkeley/flywave
ssd_meta_arch.py
SSDMetaArch.restore_fn
restore_fn
Return callable for loading a checkpoint into the tensorflow graph.
[ "Return", "callable", "for", "loading", "a", "checkpoint", "into", "the", "tensorflow", "graph." ]
def restore_fn(self, checkpoint_path, from_detection_checkpoint=True): variables_to_restore = {} for variable in tf.all_variables(): if variable.op.name.startswith(self._extract_features_scope): var_name = variable.op.name if not from_detection_checkpoint: var_nam...
['def', 'restore_fn(self,', 'checkpoint_path,', 'from_detection_checkpoint=True):', 'variables_to_restore', '=', '{}', 'for', 'variable', 'in', 'tf.all_variables():', 'if', 'variable.op.name.startswith(self._extract_features_scope):', 'var_name', '=', 'variable.op.name', 'if', 'not', 'from_detection_checkpoint:', 'var_...
607,262
lizoyu/cse511a-2017fall
inference.py
InferenceModule.setGhostPosition
setGhostPosition
Sets the position of the ghost for this inference module to the specified position in the supplied gameState.
[ "Sets", "the", "position", "of", "the", "ghost", "for", "this", "inference", "module", "to", "the", "specified", "position", "in", "the", "supplied", "gameState." ]
def setGhostPosition(self, gameState, ghostPosition): conf = game.Configuration(ghostPosition, game.Directions.STOP) gameState.data.agentStates[self.index] = game.AgentState(conf, False) return gameState
['def', 'setGhostPosition(self,', 'gameState,', 'ghostPosition):', 'conf', '=', 'game.Configuration(ghostPosition,', 'game.Directions.STOP)', 'gameState.data.agentStates[self.index]', '=', 'game.AgentState(conf,', 'False)', 'return', 'gameState']
193,463
yaoyao-liu/meta-transfer-learning
resnet18.py
Models.construct_residual_block_ss_weights
construct_residual_block_ss_weights
The function to construct one block ss weights.
[ "The", "function", "to", "construct", "one", "block", "ss", "weights." ]
def construct_residual_block_ss_weights(self, ss_weights, last_dim_hidden, dim_hidden, scope='block0'): ss_weights[scope + '_conv1'] = tf.Variable(tf.ones([1, 1, last_dim_hidden, dim_hidden]), name=scope + '_conv1') ss_weights[scope + '_bias1'] = tf.Variable(tf.zeros([dim_hidden]), name=scope + '_bias1') ss...
['def', 'construct_residual_block_ss_weights(self,', 'ss_weights,', 'last_dim_hidden,', 'dim_hidden,', "scope='block0'):", 'ss_weights[scope', '+', "'_conv1']", '=', 'tf.Variable(tf.ones([1,', '1,', 'last_dim_hidden,', 'dim_hidden]),', 'name=scope', '+', "'_conv1')", 'ss_weights[scope', '+', "'_bias1']", '=', 'tf.Varia...
633,159
greydanus/pythonic_ocr
wsgi.py
LimitedStream.is_exhausted
is_exhausted
If the stream is exhausted this attribute is `True`.
[ "If", "the", "stream", "is", "exhausted", "this", "attribute", "is", "`True`." ]
def is_exhausted(self): return self._pos >= self.limit
['def', 'is_exhausted(self):', 'return', 'self._pos', '>=', 'self.limit']
301,226
instadeepai/jumanji
utils_spawn.py
place_entity_on_grid
place_entity_on_grid
Places an entity (Agent/Shelf) on the grid based on its (x, y) position defined once spawned.
[ "Places", "an", "entity", "(Agent/Shelf)", "on", "the", "grid", "based", "on", "its", "(x,", "y)", "position", "defined", "once", "spawned." ]
def place_entity_on_grid(grid: chex.Array, channel: chex.Array, entities: Entity, entity_id: chex.Array) -> chex.Array: entity = tree_slice(entities, entity_id) (x, y) = (entity.position.x, entity.position.y) return grid.at[channel, x, y].set(entity_id + 1)
['def', 'place_entity_on_grid(grid:', 'chex.Array,', 'channel:', 'chex.Array,', 'entities:', 'Entity,', 'entity_id:', 'chex.Array)', '->', 'chex.Array:', 'entity', '=', 'tree_slice(entities,', 'entity_id)', '(x,', 'y)', '=', '(entity.position.x,', 'entity.position.y)', 'return', 'grid.at[channel,', 'x,', 'y].set(entity...
594,495
facebookresearch/CompilerGym
__init__.py
llc_path
llc_path
Return the path of llc.
[ "Return", "the", "path", "of", "llc." ]
def llc_path() -> Path: return download_llvm_files() / 'bin/llc'
['def', 'llc_path()', '->', 'Path:', 'return', 'download_llvm_files()', '/', "'bin/llc'"]
126,276
sunishsheth2009/ChatterBot
base.py
MSExecutionContext.pre_exec
pre_exec
Activate IDENTITY_INSERT if needed.
[ "Activate", "IDENTITY_INSERT", "if", "needed." ]
def pre_exec(self): if self.isinsert: tbl = self.compiled.statement.table seq_column = tbl._autoincrement_column insert_has_sequence = seq_column is not None if insert_has_sequence: self._enable_identity_insert = seq_column.key in self.compiled_parameters[0] else:...
['def', 'pre_exec(self):', 'if', 'self.isinsert:', 'tbl', '=', 'self.compiled.statement.table', 'seq_column', '=', 'tbl._autoincrement_column', 'insert_has_sequence', '=', 'seq_column', 'is', 'not', 'None', 'if', 'insert_has_sequence:', 'self._enable_identity_insert', '=', 'seq_column.key', 'in', 'self.compiled_paramet...
534,237
weimin17/Object-Detection_HelmetDetection
loss_layers_test.py
CrossFunctionTest.testWeigtedGlobalObjective
testWeigtedGlobalObjective
Runs a test of `global_objective` with per-example weights.
[ "Runs", "a", "test", "of", "`global_objective`", "with", "per-example", "weights." ]
def testWeigtedGlobalObjective(self, global_objective, objective_kwargs): logits_positives = tf.constant([1, -0.5, 3], shape=[3, 1]) logits_negatives = tf.constant([-0.5, 1, -1, -1, -0.5, 1], shape=[6, 1]) dummy = tf.constant(1.0) logits = tf.concat([logits_positives, logits_negatives], 0) logits = ...
['def', 'testWeigtedGlobalObjective(self,', 'global_objective,', 'objective_kwargs):', 'logits_positives', '=', 'tf.constant([1,', '-0.5,', '3],', 'shape=[3,', '1])', 'logits_negatives', '=', 'tf.constant([-0.5,', '1,', '-1,', '-1,', '-0.5,', '1],', 'shape=[6,', '1])', 'dummy', '=', 'tf.constant(1.0)', 'logits', '=', '...
763,005
aalgirdas/Artificial-Intelligence-Course
games.py
Backgammon.display
display
Display state of the game.
[ "Display", "state", "of", "the", "game." ]
def display(self, state): board = state.board player = state.to_move print('current state : ') for (index, point) in enumerate(board): print('point : ', index, '\tW : ', point['W'], ' B : ', point['B']) print('to play : ', player)
['def', 'display(self,', 'state):', 'board', '=', 'state.board', 'player', '=', 'state.to_move', "print('current", 'state', ':', "')", 'for', '(index,', 'point)', 'in', 'enumerate(board):', "print('point", ':', "',", 'index,', "'\\tW", ':', "',", "point['W'],", "'", 'B', ':', "',", "point['B'])", "print('to", 'play', '...
79,657
zihuitang/medical_AI_platform
random.py
Random.choice
choice
Choose a random element from a non-empty sequence.
[ "Choose", "a", "random", "element", "from", "a", "non-empty", "sequence." ]
def choice(self, seq): try: i = self._randbelow(len(seq)) except ValueError: raise IndexError('Cannot choose from an empty sequence') return seq[i]
['def', 'choice(self,', 'seq):', 'try:', 'i', '=', 'self._randbelow(len(seq))', 'except', 'ValueError:', 'raise', "IndexError('Cannot", 'choose', 'from', 'an', 'empty', "sequence')", 'return', 'seq[i]']
281,266
Ruturaj123/Flowchart-Detection
configure.py
setup_python
setup_python
Setup python related env variables.
[ "Setup", "python", "related", "env", "variables." ]
def setup_python(environ_cp, bazel_version): default_python_bin_path = sys.executable ask_python_bin_path = 'Please specify the location of python. [Default is %s]: ' % default_python_bin_path while True: python_bin_path = get_from_env_or_user_or_default(environ_cp, 'PYTHON_BIN_PATH', ask_python_bin...
['def', 'setup_python(environ_cp,', 'bazel_version):', 'default_python_bin_path', '=', 'sys.executable', 'ask_python_bin_path', '=', "'Please", 'specify', 'the', 'location', 'of', 'python.', '[Default', 'is', '%s]:', "'", '%', 'default_python_bin_path', 'while', 'True:', 'python_bin_path', '=', 'get_from_env_or_user_or...
586,737
triaquae/triaquae
wsgiserver3.py
HTTPRequest.parse_request
parse_request
Parse the next HTTP request start-line and message-headers.
[ "Parse", "the", "next", "HTTP", "request", "start-line", "and", "message-headers." ]
def parse_request(self): self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: success = self.read_request_line() except MaxSizeExceeded: self.simple_response('414 Request-URI Too Long', 'The Request-URI sent with the request exceeds the maximum allowed byt...
['def', 'parse_request(self):', 'self.rfile', '=', 'SizeCheckWrapper(self.conn.rfile,', 'self.server.max_request_header_size)', 'try:', 'success', '=', 'self.read_request_line()', 'except', 'MaxSizeExceeded:', "self.simple_response('414", 'Request-URI', 'Too', "Long',", "'The", 'Request-URI', 'sent', 'with', 'the', 're...
424,412
microsoft/nlp-recipes
common.py
Transformer.save_model
save_model
Saves the underlying PyTorch module's state.
[ "Saves", "the", "underlying", "PyTorch", "module's", "state." ]
def save_model(self, file_name=None): model_to_save = self.model.module if hasattr(self.model, 'module') else self.model if file_name: logger.info('Saving model checkpoint to %s', file_name) torch.save(model_to_save.state_dict(), file_name) else: output_model_dir = os.path.join(self....
['def', 'save_model(self,', 'file_name=None):', 'model_to_save', '=', 'self.model.module', 'if', 'hasattr(self.model,', "'module')", 'else', 'self.model', 'if', 'file_name:', "logger.info('Saving", 'model', 'checkpoint', 'to', "%s',", 'file_name)', 'torch.save(model_to_save.state_dict(),', 'file_name)', 'else:', 'outpu...
731,295
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
core.py
MultiCommand.format_commands
format_commands
Extra format methods for multi methods that adds all the commands after the options.
[ "Extra", "format", "methods", "for", "multi", "methods", "that", "adds", "all", "the", "commands", "after", "the", "options." ]
def format_commands(self, ctx, formatter): commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) if len(commands): li...
['def', 'format_commands(self,', 'ctx,', 'formatter):', 'commands', '=', '[]', 'for', 'subcommand', 'in', 'self.list_commands(ctx):', 'cmd', '=', 'self.get_command(ctx,', 'subcommand)', 'if', 'cmd', 'is', 'None:', 'continue', 'if', 'cmd.hidden:', 'continue', 'commands.append((subcommand,', 'cmd))', 'if', 'len(commands)...
101,840
pucrs-ai-cs/reinforcement
link.py
Link.converged
converged
Return True if the change between previous util table and current util table are smaller than the convergence_threshold.
[ "Return", "True", "if", "the", "change", "between", "previous", "util", "table", "and", "current", "util", "table", "are", "smaller", "than", "the", "convergence_threshold." ]
def converged(self): self.convergence = self.convergence_metric() return self.convergence < CONVERGENCE_THRESHOLD
['def', 'converged(self):', 'self.convergence', '=', 'self.convergence_metric()', 'return', 'self.convergence', '<', 'CONVERGENCE_THRESHOLD']
286,814
PRMorgan/State-of-the-Artificial-Intelligence
Level.py
Level.update
update
Update everything in this level.
[ "Update", "everything", "in", "this", "level." ]
def update(self): self.active_sprite_list.update() self.platform_list.update() self.player_list.update() self.player_attack_list.update() self.enemy_list.update() self.enemy_attack_list.update()
['def', 'update(self):', 'self.active_sprite_list.update()', 'self.platform_list.update()', 'self.player_list.update()', 'self.player_attack_list.update()', 'self.enemy_list.update()', 'self.enemy_attack_list.update()']
383,896
joao-montanari/artificial_intelligence
selectors.py
BaseSelector.get_key
get_key
Return the key associated with a registered file object.
[ "Return", "the", "key", "associated", "with", "a", "registered", "file", "object." ]
def get_key(self, fileobj): mapping = self.get_map() if mapping is None: raise RuntimeError('Selector is closed') try: return mapping[fileobj] except KeyError: raise KeyError('{0!r} is not registered'.format(fileobj))
['def', 'get_key(self,', 'fileobj):', 'mapping', '=', 'self.get_map()', 'if', 'mapping', 'is', 'None:', 'raise', "RuntimeError('Selector", 'is', "closed')", 'try:', 'return', 'mapping[fileobj]', 'except', 'KeyError:', 'raise', "KeyError('{0!r}", 'is', 'not', "registered'.format(fileobj))"]
146,446
Megvii-BaseDetection/cvpods
darknet.py
conv_bn_lrelu
conv_bn_lrelu
Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer.
[ "Create", "a", "seuence", "Conv2d->BatchNorm2d->LeakyReLu", "layer." ]
def conv_bn_lrelu(ni: int, nf: int, ks: int=3, stride: int=1) -> nn.Sequential: return nn.Sequential(OrderedDict([('conv', nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks // 2)), ('bn', nn.BatchNorm2d(nf)), ('relu', nn.LeakyReLU(negative_slope=0.1, inplace=True))]))
['def', 'conv_bn_lrelu(ni:', 'int,', 'nf:', 'int,', 'ks:', 'int=3,', 'stride:', 'int=1)', '->', 'nn.Sequential:', 'return', "nn.Sequential(OrderedDict([('conv',", 'nn.Conv2d(ni,', 'nf,', 'kernel_size=ks,', 'bias=False,', 'stride=stride,', 'padding=ks', '//', '2)),', "('bn',", 'nn.BatchNorm2d(nf)),', "('relu',", 'nn.Lea...
522,937
dingmyu/D4LCN
util.py
absolute_import
absolute_import
Imports a python module / file given its ABSOLUTE path.
[ "Imports", "a", "python", "module", "/", "file", "given", "its", "ABSOLUTE", "path." ]
def absolute_import(file_path): (_, name, _) = file_parts(file_path) spec = importlib.util.spec_from_file_location(name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
['def', 'absolute_import(file_path):', '(_,', 'name,', '_)', '=', 'file_parts(file_path)', 'spec', '=', 'importlib.util.spec_from_file_location(name,', 'file_path)', 'module', '=', 'importlib.util.module_from_spec(spec)', 'spec.loader.exec_module(module)', 'return', 'module']
526,180
monocongo/cvdata
conftest.py
data_dir
data_dir
Fixture responsible for searching a folder with the same name of test module and, if available, moving all contents to a temporary directory so tests can use them freely.
[ "Fixture", "responsible", "for", "searching", "a", "folder", "with", "the", "same", "name", "of", "test", "module", "and,", "if", "available,", "moving", "all", "contents", "to", "a", "temporary", "directory", "so", "tests", "can", "use", "them", "freely." ]
def data_dir(tmpdir, request): filename = request.module.__file__ (test_dir, _) = os.path.splitext(filename) if os.path.isdir(test_dir): dir_util.copy_tree(test_dir, str(tmpdir)) return tmpdir
['def', 'data_dir(tmpdir,', 'request):', 'filename', '=', 'request.module.__file__', '(test_dir,', '_)', '=', 'os.path.splitext(filename)', 'if', 'os.path.isdir(test_dir):', 'dir_util.copy_tree(test_dir,', 'str(tmpdir))', 'return', 'tmpdir']
509,600
RasaHQ/rasa
slot_mappings.py
validate_slot_mappings
validate_slot_mappings
Raises InvalidDomain exception if slot mappings are invalid.
[ "Raises", "InvalidDomain", "exception", "if", "slot", "mappings", "are", "invalid." ]
def validate_slot_mappings(domain_slots: Dict[Text, Any]) -> None: rasa.shared.utils.io.raise_warning(f'Slot auto-fill has been removed in 3.0 and replaced with a new explicit mechanism to set slots. Please refer to {DOCS_URL_SLOTS} to learn more.', UserWarning) for (slot_name, properties) in domain_slots.items...
['def', 'validate_slot_mappings(domain_slots:', 'Dict[Text,', 'Any])', '->', 'None:', "rasa.shared.utils.io.raise_warning(f'Slot", 'auto-fill', 'has', 'been', 'removed', 'in', '3.0', 'and', 'replaced', 'with', 'a', 'new', 'explicit', 'mechanism', 'to', 'set', 'slots.', 'Please', 'refer', 'to', '{DOCS_URL_SLOTS}', 'to',...
837,513
CreativeMachinesLab/aracna
util.py
smoothPoint
smoothPoint
Uses a straight-line approximation to bring points within distance dt closer to y=f(t).
[ "Uses", "a", "straight-line", "approximation", "to", "bring", "points", "within", "distance", "dt", "closer", "to", "y=f(t)." ]
def smoothPoint(f, y, t, dt): dt = dt / 2.0 y1 = f(t - dt) y2 = f(t + dt) t1 = t - dt t2 = t + dt h = lambda x: y1 + (y - y1) / (t - t1) * (x - t1) if x < t else y + (y2 - y) / (t2 - t) * (x - t) g = lambda x: f(x) if x > t2 or x < t1 else h(x) return g
['def', 'smoothPoint(f,', 'y,', 't,', 'dt):', 'dt', '=', 'dt', '/', '2.0', 'y1', '=', 'f(t', '-', 'dt)', 'y2', '=', 'f(t', '+', 'dt)', 't1', '=', 't', '-', 'dt', 't2', '=', 't', '+', 'dt', 'h', '=', 'lambda', 'x:', 'y1', '+', '(y', '-', 'y1)', '/', '(t', '-', 't1)', '*', '(x', '-', 't1)', 'if', 'x', '<', 't', 'else', '...
401,848
xyc2690/Raspberry_ObjectDetection_Camera
inputs.py
create_eval_input_fn
create_eval_input_fn
Creates an eval `input` function for `Estimator`.
[ "Creates", "an", "eval", "`input`", "function", "for", "`Estimator`." ]
def create_eval_input_fn(eval_config, eval_input_config, model_config): def _eval_input_fn(params=None): del params if not isinstance(eval_config, eval_pb2.EvalConfig): raise TypeError('For eval mode, the `eval_config` must be a train_pb2.EvalConfig.') if not isinstance(eval_inp...
['def', 'create_eval_input_fn(eval_config,', 'eval_input_config,', 'model_config):', 'def', '_eval_input_fn(params=None):', 'del', 'params', 'if', 'not', 'isinstance(eval_config,', 'eval_pb2.EvalConfig):', 'raise', "TypeError('For", 'eval', 'mode,', 'the', '`eval_config`', 'must', 'be', 'a', "train_pb2.EvalConfig.')", ...
838,402
JunweiLiang/Object_Detection_Tracking
viz.py
draw_mask
draw_mask
Overlay a mask on top of the image.
[ "Overlay", "a", "mask", "on", "top", "of", "the", "image." ]
def draw_mask(im, mask, alpha=0.5, color=None, show_border=True, border_thick=1): if color is None: color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1] im = np.where(np.squeeze(np.repeat((mask > 0)[:, :, None], 3, axis=2)), im * (1 - alpha) + color * alpha, im) if show_border: if c...
['def', 'draw_mask(im,', 'mask,', 'alpha=0.5,', 'color=None,', 'show_border=True,', 'border_thick=1):', 'if', 'color', 'is', 'None:', 'color', '=', 'PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1]', 'im', '=', 'np.where(np.squeeze(np.repeat((mask', '>', '0)[:,', ':,', 'None],', '3,', 'axis=2)),', 'im', '*', '(1',...
796,164
scikit-learn/scikit-learn
test_hdbscan.py
test_hdbscan_no_clusters
test_hdbscan_no_clusters
Tests that HDBSCAN correctly does not generate a valid cluster when the `min_cluster_size` is too large for the data.
[ "Tests", "that", "HDBSCAN", "correctly", "does", "not", "generate", "a", "valid", "cluster", "when", "the", "`min_cluster_size`", "is", "too", "large", "for", "the", "data." ]
def test_hdbscan_no_clusters(): labels = HDBSCAN(min_cluster_size=len(X) - 1).fit_predict(X) n_clusters = len(set(labels) - OUTLIER_SET) assert n_clusters == 0
['def', 'test_hdbscan_no_clusters():', 'labels', '=', 'HDBSCAN(min_cluster_size=len(X)', '-', '1).fit_predict(X)', 'n_clusters', '=', 'len(set(labels)', '-', 'OUTLIER_SET)', 'assert', 'n_clusters', '==', '0']
852,843
emmanueldufourq/PAM_TransferLearning
Preprocessing.py
Preprocessing.convert_single_to_image
convert_single_to_image
Convert amplitude values into a mel-spectrogram.
[ "Convert", "amplitude", "values", "into", "a", "mel-spectrogram." ]
def convert_single_to_image(self, audio): S = librosa.feature.melspectrogram(audio, n_fft=self.n_ftt, hop_length=self.hop_length, n_mels=self.n_mels, fmin=self.f_min, fmax=self.f_max) image = librosa.core.power_to_db(S) image_np = np.asmatrix(image) image_np_scaled_temp = image_np - np.min(image_np) ...
['def', 'convert_single_to_image(self,', 'audio):', 'S', '=', 'librosa.feature.melspectrogram(audio,', 'n_fft=self.n_ftt,', 'hop_length=self.hop_length,', 'n_mels=self.n_mels,', 'fmin=self.f_min,', 'fmax=self.f_max)', 'image', '=', 'librosa.core.power_to_db(S)', 'image_np', '=', 'np.asmatrix(image)', 'image_np_scaled_t...
778,586
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
svm_gui.py
View.plot_support_vectors
plot_support_vectors
Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.
[ "Plot", "the", "support", "vectors", "by", "placing", "circles", "over", "the", "corresponding", "data", "points", "and", "adds", "the", "circle", "collection", "to", "the", "contours", "list." ]
def plot_support_vectors(self, support_vectors): cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors='k', facecolors='none') self.contours.append(cs)
['def', 'plot_support_vectors(self,', 'support_vectors):', 'cs', '=', 'self.ax.scatter(support_vectors[:,', '0],', 'support_vectors[:,', '1],', 's=80,', "edgecolors='k',", "facecolors='none')", 'self.contours.append(cs)']
12,578
jmamath/ood-deep-learning
augmix_utils.py
train_augmix
train_augmix
Train for one epoch.
[ "Train", "for", "one", "epoch." ]
def train_augmix(net, train_loader, optimizer, scheduler, no_jsd): net.train() loss_ema = 0.0 for (i, (images, targets)) in enumerate(train_loader): optimizer.zero_grad() if no_jsd: images = images.to(device) targets = targets.to(device) logits = net(image...
['def', 'train_augmix(net,', 'train_loader,', 'optimizer,', 'scheduler,', 'no_jsd):', 'net.train()', 'loss_ema', '=', '0.0', 'for', '(i,', '(images,', 'targets))', 'in', 'enumerate(train_loader):', 'optimizer.zero_grad()', 'if', 'no_jsd:', 'images', '=', 'images.to(device)', 'targets', '=', 'targets.to(device)', 'logit...
756,634
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
MethodContent.acceptContinue
acceptContinue
Accept and process a continue statement.
[ "Accept", "and", "process", "a", "continue", "statement." ]
def acceptContinue(self, node, memo): contStat = self.factory.statement('continue', fs=FS.lsr, parent=self) if len(node.children): warn('Detected unhandled continue statement with label; generated code incorrect.')
['def', 'acceptContinue(self,', 'node,', 'memo):', 'contStat', '=', "self.factory.statement('continue',", 'fs=FS.lsr,', 'parent=self)', 'if', 'len(node.children):', "warn('Detected", 'unhandled', 'continue', 'statement', 'with', 'label;', 'generated', 'code', "incorrect.')"]
11,085
shoyo/acoustic-keylogger
audio_processing.py
drop_keystroke_table
drop_keystroke_table
Drop keystroke table in database.
[ "Drop", "keystroke", "table", "in", "database." ]
def drop_keystroke_table(url=os.environ['TEST_DATABASE_URL']): engine = connect_to_database(url) Keystroke.__table__.drop(engine)
['def', "drop_keystroke_table(url=os.environ['TEST_DATABASE_URL']):", 'engine', '=', 'connect_to_database(url)', 'Keystroke.__table__.drop(engine)']
8,636
open-mmlab/mmrotate
image.py
draw_rbboxes
draw_rbboxes
Draw oriented bounding boxes on the axes.
[ "Draw", "oriented", "bounding", "boxes", "on", "the", "axes." ]
def draw_rbboxes(ax, bboxes, color='g', alpha=0.8, thickness=2): polygons = [] for (i, bbox) in enumerate(bboxes): (xc, yc, w, h, ag) = bbox[:5] (wx, wy) = (w / 2 * np.cos(ag), w / 2 * np.sin(ag)) (hx, hy) = (-h / 2 * np.sin(ag), h / 2 * np.cos(ag)) p1 = (xc - wx - hx, yc - wy - ...
['def', 'draw_rbboxes(ax,', 'bboxes,', "color='g',", 'alpha=0.8,', 'thickness=2):', 'polygons', '=', '[]', 'for', '(i,', 'bbox)', 'in', 'enumerate(bboxes):', '(xc,', 'yc,', 'w,', 'h,', 'ag)', '=', 'bbox[:5]', '(wx,', 'wy)', '=', '(w', '/', '2', '*', 'np.cos(ag),', 'w', '/', '2', '*', 'np.sin(ag))', '(hx,', 'hy)', '=', ...
625,076
open-mmlab/mmdetection3d
test_minkunet_head.py
TestMinkUNetHead.test_minkunet_head_loss
test_minkunet_head_loss
Tests PAConv head loss.
[ "Tests", "PAConv", "head", "loss." ]
def test_minkunet_head_loss(self): try: import torchsparse except ImportError: pytest.skip('test requires Torchsparse installation') if torch.cuda.is_available(): minkunet_head = MinkUNetHead(channels=4, num_classes=19) minkunet_head.cuda() (coordinates, features) = (...
['def', 'test_minkunet_head_loss(self):', 'try:', 'import', 'torchsparse', 'except', 'ImportError:', "pytest.skip('test", 'requires', 'Torchsparse', "installation')", 'if', 'torch.cuda.is_available():', 'minkunet_head', '=', 'MinkUNetHead(channels=4,', 'num_classes=19)', 'minkunet_head.cuda()', '(coordinates,', 'featur...
632,490
facebookresearch/contriever
evaluation.py
has_answer
has_answer
Check if a document contains an answer string.
[ "Check", "if", "a", "document", "contains", "an", "answer", "string." ]
def has_answer(answers, text, tokenizer) -> bool: text = _normalize(text) text = tokenizer.tokenize(text, uncased=True) for answer in answers: answer = _normalize(answer) answer = tokenizer.tokenize(answer, uncased=True) for i in range(0, len(text) - len(answer) + 1): if ...
['def', 'has_answer(answers,', 'text,', 'tokenizer)', '->', 'bool:', 'text', '=', '_normalize(text)', 'text', '=', 'tokenizer.tokenize(text,', 'uncased=True)', 'for', 'answer', 'in', 'answers:', 'answer', '=', '_normalize(answer)', 'answer', '=', 'tokenizer.tokenize(answer,', 'uncased=True)', 'for', 'i', 'in', 'range(0...
136,667
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
crop_mammogram.py
get_rightmost_pixels_wrt_cropped_image
get_rightmost_pixels_wrt_cropped_image
Ignores top find_rightmost_from_ratio of the image and searches the rightmost nonzero pixels of the dilated mask from the bottom portion of the image.
[ "Ignores", "top", "find_rightmost_from_ratio", "of", "the", "image", "and", "searches", "the", "rightmost", "nonzero", "pixels", "of", "the", "dilated", "mask", "from", "the", "bottom", "portion", "of", "the", "image." ]
def get_rightmost_pixels_wrt_cropped_image(mode, largest_mask_cropped, find_rightmost_from_ratio): ignore_height = int(largest_mask_cropped.shape[0] * find_rightmost_from_ratio) rightmost_pixel_search_area = largest_mask_cropped[ignore_height:, :] rightmost_pixel_search_area_has_value = np.any(rightmost_pix...
['def', 'get_rightmost_pixels_wrt_cropped_image(mode,', 'largest_mask_cropped,', 'find_rightmost_from_ratio):', 'ignore_height', '=', 'int(largest_mask_cropped.shape[0]', '*', 'find_rightmost_from_ratio)', 'rightmost_pixel_search_area', '=', 'largest_mask_cropped[ignore_height:,', ':]', 'rightmost_pixel_search_area_has...
17,732
jshilong/DDQ
geometric.py
impad_to_multiple
impad_to_multiple
Pad an image to ensure each edge to be multiple to some number.
[ "Pad", "an", "image", "to", "ensure", "each", "edge", "to", "be", "multiple", "to", "some", "number." ]
def impad_to_multiple(img, divisor, pad_val=0): pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor return impad(img, shape=(pad_h, pad_w), pad_val=pad_val)
['def', 'impad_to_multiple(img,', 'divisor,', 'pad_val=0):', 'pad_h', '=', 'int(np.ceil(img.shape[0]', '/', 'divisor))', '*', 'divisor', 'pad_w', '=', 'int(np.ceil(img.shape[1]', '/', 'divisor))', '*', 'divisor', 'return', 'impad(img,', 'shape=(pad_h,', 'pad_w),', 'pad_val=pad_val)']
499,058
datature/portal
Model.py
Model
Model
Factory function that routes the model to the specific class.
[ "Factory", "function", "that", "routes", "the", "model", "to", "the", "specific", "class." ]
def Model(model_type: str, directory: str, name: str, description: str, **kwargs): args = [model_type, directory, name, description] model_class = {'tensorflow': TensorflowModel, 'darknet': DarknetModel, 'endpoint': EndpointModel, 'autodetect': AutoDetectModel} return model_class[model_type](*args, **kwargs...
['def', 'Model(model_type:', 'str,', 'directory:', 'str,', 'name:', 'str,', 'description:', 'str,', '**kwargs):', 'args', '=', '[model_type,', 'directory,', 'name,', 'description]', 'model_class', '=', "{'tensorflow':", 'TensorflowModel,', "'darknet':", 'DarknetModel,', "'endpoint':", 'EndpointModel,', "'autodetect':",...
820,900
enuguru/artificial_intelligence_and_machine_
structfile.py
StructFile.read_svarint
read_svarint
Reads a variable-length encoded signed integer from the wrapped file.
[ "Reads", "a", "variable-length", "encoded", "signed", "integer", "from", "the", "wrapped", "file." ]
def read_svarint(self): return decode_signed_varint(read_varint(self.read))
['def', 'read_svarint(self):', 'return', 'decode_signed_varint(read_varint(self.read))']
133,370
aeon-toolkit/aeon
test_differencer.py
test_differencer_produces_expected_results
test_differencer_produces_expected_results
Test that Differencer produces expected results on a simple DataFrame.
[ "Test", "that", "Differencer", "produces", "expected", "results", "on", "a", "simple", "DataFrame." ]
def test_differencer_produces_expected_results(na_handling): transformer = Differencer(na_handling=na_handling) y_transformed = transformer.fit_transform(y_simple) y_expected = y_simple_expected_diff[na_handling] _assert_array_almost_equal(y_transformed, y_expected)
['def', 'test_differencer_produces_expected_results(na_handling):', 'transformer', '=', 'Differencer(na_handling=na_handling)', 'y_transformed', '=', 'transformer.fit_transform(y_simple)', 'y_expected', '=', 'y_simple_expected_diff[na_handling]', '_assert_array_almost_equal(y_transformed,', 'y_expected)']
400,034
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nested_utils.py
tas_for_tensors
tas_for_tensors
Unstacks a set of Tensors into TensorArrays.
[ "Unstacks", "a", "set", "of", "Tensors", "into", "TensorArrays." ]
def tas_for_tensors(tensors, length): def map_fn(x): ta = tf.TensorArray(x.dtype, length, name=x.name.split(':')[0] + '_ta') return ta.unstack(x[:length, :]) return map_nested(map_fn, tensors)
['def', 'tas_for_tensors(tensors,', 'length):', 'def', 'map_fn(x):', 'ta', '=', 'tf.TensorArray(x.dtype,', 'length,', "name=x.name.split(':')[0]", '+', "'_ta')", 'return', 'ta.unstack(x[:length,', ':])', 'return', 'map_nested(map_fn,', 'tensors)']
48,362
ajMIT95/MIT_Artificial_Intelligence_Labs
lab5.py
norm
norm
Computes length of a vector v, represented as a tuple or list of coords.
[ "Computes", "length", "of", "a", "vector", "v,", "represented", "as", "a", "tuple", "or", "list", "of", "coords." ]
def norm(v): return math.sqrt(dot_product(v, v))
['def', 'norm(v):', 'return', 'math.sqrt(dot_product(v,', 'v))']
239,324
matsu0228/nlp-jp
screen.py
screen.scroll_down
scroll_down
Scroll display down one line.
[ "Scroll", "display", "down", "one", "line." ]
def scroll_down(self): s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s + 1:e + 1] = copy.deepcopy(self.w[s:e])
['def', 'scroll_down(self):', 's', '=', 'self.scroll_row_start', '-', '1', 'e', '=', 'self.scroll_row_end', '-', '1', 'self.w[s', '+', '1:e', '+', '1]', '=', 'copy.deepcopy(self.w[s:e])']
803,248
EducationalTestingService/skll
test_voting_learners_expts_3.py
TestVotingLearnersExptsThree.check_predict_task
check_predict_task
Check given combination of prediction configuration options.
[ "Check", "given", "combination", "of", "prediction", "configuration", "options." ]
def check_predict_task(self, learner_type, options_dict): (config_path, estimator_names, job_name, custom_learner, objectives, _, model_kwargs_list, param_grid_list, sampler_list, _, _, _, _) = fill_in_config_options_for_voting_learners(learner_type, 'predict', options_dict) init_patcher = patch.object(VotingLe...
['def', 'check_predict_task(self,', 'learner_type,', 'options_dict):', '(config_path,', 'estimator_names,', 'job_name,', 'custom_learner,', 'objectives,', '_,', 'model_kwargs_list,', 'param_grid_list,', 'sampler_list,', '_,', '_,', '_,', '_)', '=', 'fill_in_config_options_for_voting_learners(learner_type,', "'predict',...
885,264
zihuitang/medical_AI_platform
mailbox.py
MaildirMessage.set_date
set_date
Set delivery date of message, in seconds since the epoch.
[ "Set", "delivery", "date", "of", "message,", "in", "seconds", "since", "the", "epoch." ]
def set_date(self, date): try: self._date = float(date) except ValueError: raise TypeError("can't convert to float: %s" % date)
['def', 'set_date(self,', 'date):', 'try:', 'self._date', '=', 'float(date)', 'except', 'ValueError:', 'raise', 'TypeError("can\'t', 'convert', 'to', 'float:', '%s"', '%', 'date)']
280,778
Ruturaj123/Flowchart-Detection
gbdt_batch_test.py
GbdtTest.testTrainFnMulticlassTreePerClass
testTrainFnMulticlassTreePerClass
Tests the GBDT train for multiclass tree per class strategy.
[ "Tests", "the", "GBDT", "train", "for", "multiclass", "tree", "per", "class", "strategy." ]
def testTrainFnMulticlassTreePerClass(self): with self.test_session() as sess: ensemble_handle = model_ops.tree_ensemble_variable(stamp_token=0, tree_ensemble_config='', name='tree_ensemble') learner_config = learner_pb2.LearnerConfig() learner_config.learning_rate_tuner.fixed.learning_rate ...
['def', 'testTrainFnMulticlassTreePerClass(self):', 'with', 'self.test_session()', 'as', 'sess:', 'ensemble_handle', '=', 'model_ops.tree_ensemble_variable(stamp_token=0,', "tree_ensemble_config='',", "name='tree_ensemble')", 'learner_config', '=', 'learner_pb2.LearnerConfig()', 'learner_config.learning_rate_tuner.fixe...
586,906
accel-brain/accel-brain-code
drc_networks.py
DRCNetworks.inference_auto_encoder
inference_auto_encoder
Hybrid forward with Gluon API (Auto-Encoder only).
[ "Hybrid", "forward", "with", "Gluon", "API", "(Auto-Encoder", "only)." ]
def inference_auto_encoder(self, x): return self.convolutional_auto_encoder.inference(x)
['def', 'inference_auto_encoder(self,', 'x):', 'return', 'self.convolutional_auto_encoder.inference(x)']
6,823
sunishsheth2009/ChatterBot
test_chatbot.py
ChatBotTests.test_response_with_tags_added
test_response_with_tags_added
If an input statement has tags added to it, that data should saved with the input statement.
[ "If", "an", "input", "statement", "has", "tags", "added", "to", "it,", "that", "data", "should", "saved", "with", "the", "input", "statement." ]
def test_response_with_tags_added(self): self.chatbot.get_response(Statement(text='Hello', in_response_to='Hi', tags=['test'])) results = list(self.chatbot.storage.filter(text='Hello')) self.assertEqual(len(results), 2) self.assertIn('test', results[0].get_tags()) self.assertEqual(results[1].get_tag...
['def', 'test_response_with_tags_added(self):', "self.chatbot.get_response(Statement(text='Hello',", "in_response_to='Hi',", "tags=['test']))", 'results', '=', "list(self.chatbot.storage.filter(text='Hello'))", 'self.assertEqual(len(results),', '2)', "self.assertIn('test',", 'results[0].get_tags())', 'self.assertEqual(...
486,039
THUNLP-MT/THUCC
bottle.py
Router.add
add
Add a new rule or replace the target for an existing rule.
[ "Add", "a", "new", "rule", "or", "replace", "the", "target", "for", "an", "existing", "rule." ]
def add(self, rule, method, target, name=None): anons = 0 keys = [] pattern = '' filters = [] builder = [] is_static = True for (key, mode, conf) in self._itertokens(rule): if mode: is_static = False if mode == 'default': mode = self.default_fi...
['def', 'add(self,', 'rule,', 'method,', 'target,', 'name=None):', 'anons', '=', '0', 'keys', '=', '[]', 'pattern', '=', "''", 'filters', '=', '[]', 'builder', '=', '[]', 'is_static', '=', 'True', 'for', '(key,', 'mode,', 'conf)', 'in', 'self._itertokens(rule):', 'if', 'mode:', 'is_static', '=', 'False', 'if', 'mode', ...
916,486
megvii-research/PETR
visual_nuscenes.py
NuScenesExplorer.list_scenes
list_scenes
Lists all scenes with some meta data.
[ "Lists", "all", "scenes", "with", "some", "meta", "data." ]
def list_scenes(self) -> None: def ann_count(record): count = 0 sample = self.nusc.get('sample', record['first_sample_token']) while not sample['next'] == '': count += len(sample['anns']) sample = self.nusc.get('sample', sample['next']) return count recs ...
['def', 'list_scenes(self)', '->', 'None:', 'def', 'ann_count(record):', 'count', '=', '0', 'sample', '=', "self.nusc.get('sample',", "record['first_sample_token'])", 'while', 'not', "sample['next']", '==', "'':", 'count', '+=', "len(sample['anns'])", 'sample', '=', "self.nusc.get('sample',", "sample['next'])", 'return...
767,527
dvlab-research/UVTR
transform_3d.py
UnifiedObjectSample.remove_points_in_boxes
remove_points_in_boxes
Remove the points in the sampled bounding boxes.
[ "Remove", "the", "points", "in", "the", "sampled", "bounding", "boxes." ]
def remove_points_in_boxes(points, boxes): masks = box_np_ops.points_in_rbbox(points.coord.numpy(), boxes) points = points[np.logical_not(masks.any(-1))] return points
['def', 'remove_points_in_boxes(points,', 'boxes):', 'masks', '=', 'box_np_ops.points_in_rbbox(points.coord.numpy(),', 'boxes)', 'points', '=', 'points[np.logical_not(masks.any(-1))]', 'return', 'points']
930,498
yyysjz1997/Introduction-to-Artificial-
submission.py
BacktrackingSearch.reset_results
reset_results
Resets the statistics of the different aspects of the CSP solver.
[ "Resets", "the", "statistics", "of", "the", "different", "aspects", "of", "the", "CSP", "solver." ]
def reset_results(self): self.num_assignments = 0 self.num_operations = 0 self.first_assignment_num_operations = 0 self.all_assignments = []
['def', 'reset_results(self):', 'self.num_assignments', '=', '0', 'self.num_operations', '=', '0', 'self.first_assignment_num_operations', '=', '0', 'self.all_assignments', '=', '[]']
245,814
Kvatsx/Artificial-Intelligence-Assignments
websocket.py
WebSocketProtocol13.compute_accept_value
compute_accept_value
Computes the value for the Sec-WebSocket-Accept header, given the value for Sec-WebSocket-Key.
[ "Computes", "the", "value", "for", "the", "Sec-WebSocket-Accept", "header,", "given", "the", "value", "for", "Sec-WebSocket-Key." ]
def compute_accept_value(key): sha1 = hashlib.sha1() sha1.update(utf8(key)) sha1.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11') return native_str(base64.b64encode(sha1.digest()))
['def', 'compute_accept_value(key):', 'sha1', '=', 'hashlib.sha1()', 'sha1.update(utf8(key))', "sha1.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')", 'return', 'native_str(base64.b64encode(sha1.digest()))']
78,860
clips/pattern
inflect.py
Verbs.tenses
tenses
Returns a list of possible tenses for the given inflected verb.
[ "Returns", "a", "list", "of", "possible", "tenses", "for", "the", "given", "inflected", "verb." ]
def tenses(self, verb, parse=True): tenses = _Verbs.tenses(self, verb, parse) if len(tenses) == 0: for prefix in prefix_separable: if verb.startswith(prefix): tenses = _Verbs.tenses(self, verb[len(prefix):] + ' ' + prefix, parse) break return tenses
['def', 'tenses(self,', 'verb,', 'parse=True):', 'tenses', '=', '_Verbs.tenses(self,', 'verb,', 'parse)', 'if', 'len(tenses)', '==', '0:', 'for', 'prefix', 'in', 'prefix_separable:', 'if', 'verb.startswith(prefix):', 'tenses', '=', '_Verbs.tenses(self,', 'verb[len(prefix):]', '+', "'", "'", '+', 'prefix,', 'parse)', 'b...
764,859
chinglamchoi/Corona-Net
model.py
EfficientNet.forward
forward
Calls extract_features to extract features, applies final linear layer, and returns logits.
[ "Calls", "extract_features", "to", "extract", "features,", "applies", "final", "linear", "layer,", "and", "returns", "logits." ]
def forward(self, inputs): bs = inputs.size(0) x = self.extract_features(inputs) x = self._avg_pooling(x) x = x.view(bs, -1) x = self._dropout(x) x = self._fc(x) return x
['def', 'forward(self,', 'inputs):', 'bs', '=', 'inputs.size(0)', 'x', '=', 'self.extract_features(inputs)', 'x', '=', 'self._avg_pooling(x)', 'x', '=', 'x.view(bs,', '-1)', 'x', '=', 'self._dropout(x)', 'x', '=', 'self._fc(x)', 'return', 'x']
489,241
Kvatsx/Artificial-Intelligence-Assignments
_bsdf.py
Blob.read
read
Read n bytes from the blob.
[ "Read", "n", "bytes", "from", "the", "blob." ]
def read(self, n): if self._f is None: raise RuntimeError('Cannot read in a blob that is not created by the BSDF decoder.') if self.compression: raise IOError('Cannot arbitrarily read in compressed blob.') if self._f.tell() + n > self.end_pos: raise IOError('Read beyond blob boundari...
['def', 'read(self,', 'n):', 'if', 'self._f', 'is', 'None:', 'raise', "RuntimeError('Cannot", 'read', 'in', 'a', 'blob', 'that', 'is', 'not', 'created', 'by', 'the', 'BSDF', "decoder.')", 'if', 'self.compression:', 'raise', "IOError('Cannot", 'arbitrarily', 'read', 'in', 'compressed', "blob.')", 'if', 'self._f.tell()',...
37,435