diff --git "a/valid.jsonl" "b/valid.jsonl" new file mode 100644--- /dev/null +++ "b/valid.jsonl" @@ -0,0 +1,8473 @@ +{"project_name":"matsu0228\/nlp-jp","file_name":"test_phrases.py","full_name":"TestPhraserModel.setUp","func_name":"setUp","docstring":"Set up Phraser models for the tests.","docstring_tokens":"","code":"def setUp(self):\n \"\"\"Set up Phraser models for the tests.\"\"\"\n bigram_phrases = Phrases(self.sentences, min_count=1, threshold=1, common_terms=self.common_terms)\n self.bigram = Phraser(bigram_phrases)\n bigram_default_phrases = Phrases(self.sentences, common_terms=self.common_terms)\n self.bigram_default = Phraser(bigram_default_phrases)\n bigram_utf8_phrases = Phrases(self.sentences, min_count=1, threshold=1, common_terms=self.common_terms)\n self.bigram_utf8 = Phraser(bigram_utf8_phrases)\n bigram_unicode_phrases = Phrases(self.unicode_sentences, min_count=1, threshold=1, common_terms=self.common_terms)\n self.bigram_unicode = Phraser(bigram_unicode_phrases)","code_tokens":"","url":786159} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"event_test.py","full_name":"EventModuleTest.test_get","func_name":"test_get","docstring":"Ensure get() retrieves all the events on the queue.","docstring_tokens":"","code":"def test_get(self):\n \"\"\"Ensure get() retrieves all the events on the queue.\"\"\"\n event_cnt = 10\n for _ in range(event_cnt):\n pygame.event.post(pygame.event.Event(pygame.USEREVENT))\n queue = pygame.event.get()\n self.assertEqual(len(queue), event_cnt)\n self.assertTrue(all((e.type == pygame.USEREVENT for e in queue)))","code_tokens":"","url":45742} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_teaser.py","full_name":"load_unit_data","func_name":"load_unit_data","docstring":"Load unit test data.","docstring_tokens":"","code":"def load_unit_data():\n \"\"\"Load unit test data.\"\"\"\n (X_train, y_train) = load_unit_test(split='train')\n (X_test, y_test) = load_unit_test(split='test')\n indices = np.random.RandomState(0).choice(len(y_train), 10, replace=False)\n return (X_train, y_train, X_test, y_test, indices)","code_tokens":"","url":399277} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_t_sne.py","full_name":"test_tsne_with_mahalanobis_distance","func_name":"test_tsne_with_mahalanobis_distance","docstring":"Make sure that method_parameters works with mahalanobis distance.","docstring_tokens":"","code":"def test_tsne_with_mahalanobis_distance():\n \"\"\"Make sure that method_parameters works with mahalanobis distance.\"\"\"\n random_state = check_random_state(0)\n (n_samples, n_features) = (300, 10)\n X = random_state.randn(n_samples, n_features)\n default_params = {'perplexity': 40, 'n_iter': 250, 'learning_rate': 'auto', 'init': 'random', 'n_components': 3, 'random_state': 0}\n tsne = TSNE(metric='mahalanobis', **default_params)\n msg = 'Must provide either V or VI for Mahalanobis distance'\n with pytest.raises(ValueError, match=msg):\n tsne.fit_transform(X)\n precomputed_X = squareform(pdist(X, metric='mahalanobis'), checks=True)\n X_trans_expected = TSNE(metric='precomputed', **default_params).fit_transform(precomputed_X)\n X_trans = TSNE(metric='mahalanobis', metric_params={'V': np.cov(X.T)}, **default_params).fit_transform(X)\n assert_allclose(X_trans, X_trans_expected)","code_tokens":"","url":364246} +{"project_name":"RasaHQ\/rasa_core","file_name":"facebook.py","full_name":"MessengerBot.send","func_name":"send","docstring":"Sends a message to the recipient using the messenger client.","docstring_tokens":"","code":"def send(self, recipient_id: Text, element: Any) -> None:\n \"\"\"Sends a message to the recipient using the messenger client.\"\"\"\n self.messenger_client.send(element.to_dict(), {'sender': {'id': recipient_id}}, 'RESPONSE')","code_tokens":"","url":838304} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"fields.py","full_name":"Schema.vector_names","func_name":"vector_names","docstring":"Returns a list of the names of fields that store vectors.","docstring_tokens":"","code":"def vector_names(self):\n \"\"\"Returns a list of the names of fields that store vectors.\n \"\"\"\n return [name for (name, field) in self.items() if field.vector]","code_tokens":"","url":482800} +{"project_name":"RL-MLDM\/alphagen","file_name":"train_stats.py","full_name":"StatsLogger.setup_output_files","func_name":"setup_output_files","docstring":"Opens and prepares all output log files controlled by this class.","docstring_tokens":"","code":"def setup_output_files(self):\n \"\"\"\n Opens and prepares all output log files controlled by this class.\n \"\"\"\n if self.output_file is not None:\n os.makedirs(os.path.dirname(self.output_file), exist_ok=True)\n (prefix, _) = os.path.splitext(self.output_file)\n self.all_r_output_file = '{}_all_r.npy'.format(prefix)\n self.all_info_output_file = '{}_all_info.csv'.format(prefix)\n self.hof_output_file = '{}_hof.csv'.format(prefix)\n self.pf_output_file = '{}_pf.csv'.format(prefix)\n self.positional_entropy_output_file = '{}_positional_entropy.npy'.format(prefix)\n self.top_samples_per_batch_output_file = '{}_top_samples_per_batch.csv'.format(prefix)\n self.cache_output_file = '{}_cache.csv'.format(prefix)\n self.token_counter_output_file = '{}_token_count.csv'.format(prefix)\n with open(self.output_file, 'w') as f:\n headers = ['r_best', 'r_max', 'r_avg_full', 'r_avg_sub', 'l_avg_full', 'l_avg_sub', 'ewma', 'n_unique_full', 'n_unique_sub', 'n_novel_full', 'n_novel_sub', 'a_ent_full', 'a_ent_sub', 'invalid_avg_full', 'invalid_avg_sub', 'baseline', 'time', 'nevals']\n f.write('{}\\n'.format(','.join(headers)))\n if self.save_all_iterations:\n with open(self.all_info_output_file, 'w') as f:\n headers = ['iteration', 'r', 'l', 'invalid']\n f.write('{}\\n'.format(','.join(headers)))\n if self.save_token_count:\n with open(self.token_counter_output_file, 'w') as f:\n headers = [str(token) for token in Program.library.tokens]\n f.write('{}\\n'.format(','.join(headers)))\n else:\n self.all_r_output_file = None\n self.all_info_output_file = None\n self.hof_output_file = None\n self.pf_output_file = None\n self.positional_entropy_output_file = None\n self.top_samples_per_batch_output_file = None\n self.cache_output_file = None\n self.token_counter_output_file = None\n if self.save_summary:\n if self.output_file is not None:\n summary_dir = '{}_summary'.format(prefix)\n else:\n timestamp = datetime.now().strftime('%Y-%m-%d-%H%M%S')\n summary_dir = os.path.join('summary', timestamp)\n self.summary_writer = tf.summary.FileWriter(summary_dir, self.sess.graph)\n else:\n self.summary_writer = None","code_tokens":"","url":414837} +{"project_name":"deep-learning-indaba\/Baobab","file_name":"tests.py","full_name":"ReviewStageAPITest.test_post_no_form","func_name":"test_post_no_form","docstring":"Test that the post method returns a 404 when there are no review forms for the event.","docstring_tokens":"","code":"def test_post_no_form(self):\n \"\"\"Test that the post method returns a 404 when there are no review forms for the event.\"\"\"\n self.seed_static_data()\n response = self.app.post('\/api\/v1\/reviewstage', headers=self.event_admin_headers, data={'event_id': self.no_form_event_id, 'stage': 1})\n self.assertEqual(response.status_code, 404)","code_tokens":"","url":94234} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"mathtext.py","full_name":"Fonts.get_xheight","func_name":"get_xheight","docstring":"Get the xheight for the given *font* and *fontsize*.","docstring_tokens":"","code":"def get_xheight(self, font, fontsize, dpi):\n \"\"\"\n Get the xheight for the given *font* and *fontsize*.\n \"\"\"\n raise NotImplementedError()","code_tokens":"","url":630} +{"project_name":"CentML\/DeepView.Profile","file_name":"sampler.py","full_name":"DistributedSampler.init_rng","func_name":"init_rng","docstring":"Creates new RNG, seed depends on current epoch idx.","docstring_tokens":"","code":"def init_rng(self):\n \"\"\"\n Creates new RNG, seed depends on current epoch idx.\n \"\"\"\n rng = torch.Generator()\n seed = self.seeds[self.epoch]\n logging.info(f'Sampler for epoch {self.epoch} uses seed {seed}')\n rng.manual_seed(seed)\n return rng","code_tokens":"","url":540841} +{"project_name":"mariacer\/cl_in_rnns","file_name":"train_utils_sequential.py","full_name":"save_models","func_name":"save_models","docstring":"Checkpoint the main and (if existing) the current hypernet.","docstring_tokens":"","code":"def save_models(out_dir, logger, performance, mnet, hnet=None, dnet=None, wembs=None, task_id=None, train_iter=None, **kwargs):\n \"\"\"Checkpoint the main and (if existing) the current hypernet.\n\n Args:\n out_dir (str): The simulation output directory.\n logger: Console (and file) logger.\n performance (float): The network its test performance. If ``task_id``\n is provided, then this quantity is assumed to represent the during\n accuracy of the corresponding task. Otherwise, it is assumed to be\n the average final accuracy.\n mnet: The main network.\n hnet (optional): The hypernetwork.\n dnet (optional): The decoder (replay) network.\n wembs (list, optional): List of instances of class\n :class:`sequential.embedding_utils.WordEmbLookup`.\n task_id (int, optional): Task ID of the last task the models have been\n trained on. Will be integrated into the filenames.\n train_iter (int, optional): The current training iteration. If provided,\n ``performance`` is expected to be the current validation\n performance. If ``task_id`` is provided, it will still be integrated\n into the filename.\n **kwargs: Keyword arguments passed to function\n :func:`utils.torch_ckpts.save_checkpoint`.\n \"\"\"\n (ckpt_mnet_fn, ckpt_hnet_fn, ckpt_dnet_fn, ckpt_wembs_fn) = ckpt_filenames(out_dir, task_id=task_id, train_iter=train_iter)\n if task_id is None and train_iter is None:\n perf_key = 'avg_final_acc'\n elif train_iter is None:\n perf_key = 'during_acc_task_%d' % task_id\n else:\n perf_key = 'val_performance'\n perf_dict = {perf_key: performance}\n if train_iter is not None:\n perf_dict['train_iter'] = train_iter\n ts = time()\n logger.debug('Checkpointing main network in %s ...' % ckpt_mnet_fn)\n tckpt.save_checkpoint({'state_dict': mnet.state_dict(), **perf_dict}, ckpt_mnet_fn, performance, train_iter=train_iter, timestamp=ts, **kwargs)\n if hnet is not None:\n logger.debug('Checkpointing hypernetwork in %s ...' % ckpt_hnet_fn)\n tckpt.save_checkpoint({'state_dict': hnet.state_dict(), **perf_dict}, ckpt_hnet_fn, performance, train_iter=train_iter, timestamp=ts, **kwargs)\n if dnet is not None:\n logger.debug('Checkpointing decoder network in %s ...' % ckpt_dnet_fn)\n tckpt.save_checkpoint({'state_dict': dnet.state_dict(), **perf_dict}, ckpt_dnet_fn, performance, train_iter=train_iter, timestamp=ts, **kwargs)\n if wembs is not None:\n tmp_wembs = torch.nn.ModuleList(wembs)\n logger.debug('Checkpointing word embeddings in %s ...' % ckpt_wembs_fn)\n tckpt.save_checkpoint({'state_dict': tmp_wembs.state_dict(), **perf_dict}, ckpt_wembs_fn, performance, train_iter=train_iter, timestamp=ts, **kwargs)","code_tokens":"","url":122947} +{"project_name":"jpmorganchase\/Phantom","file_name":"agents.py","full_name":"Agent.id","func_name":"id","docstring":"The unique ID of the agent.","docstring_tokens":"","code":"@property\ndef id(self) -> AgentID:\n \"\"\"The unique ID of the agent.\"\"\"\n return self._id","code_tokens":"","url":768654} +{"project_name":"brendanm12345\/imageSequenceGeneration","file_name":"training_utils.py","full_name":"EMAModel.get_decay","func_name":"get_decay","docstring":"Compute the decay factor for the exponential moving average.","docstring_tokens":"","code":"def get_decay(self, optimization_step: int) -> float:\n \"\"\"\n Compute the decay factor for the exponential moving average.\n \"\"\"\n step = max(0, optimization_step - self.update_after_step - 1)\n if step <= 0:\n return 0.0\n if self.use_ema_warmup:\n cur_decay_value = 1 - (1 + step \/ self.inv_gamma) ** (-self.power)\n else:\n cur_decay_value = (1 + step) \/ (10 + step)\n cur_decay_value = min(cur_decay_value, self.decay)\n cur_decay_value = max(cur_decay_value, self.min_decay)\n return cur_decay_value","code_tokens":"","url":599616} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"onehot_categorical.py","full_name":"OneHotCategorical.probs","func_name":"probs","docstring":"Vector of coordinatewise probabilities.","docstring_tokens":"","code":"@property\ndef probs(self):\n \"\"\"Vector of coordinatewise probabilities.\"\"\"\n return self._probs","code_tokens":"","url":312844} +{"project_name":"YannDubs\/Invariant-Self-Supervised-Learning","file_name":"base.py","full_name":"ISSLDataModule.set_info_","func_name":"set_info_","docstring":"Sets some information from the dataset.","docstring_tokens":"","code":"def set_info_(self) -> None:\n \"\"\"Sets some information from the dataset.\"\"\"\n dataset = self.dataset\n (self.target_dim, self.aux_shape) = dataset.get_shapes()\n self.shape = dataset.shapes['input']\n self.aux_target = dataset.aux_target\n self.normalized = dataset.normalization if dataset.is_normalize else None","code_tokens":"","url":245968} +{"project_name":"lalwanii26\/openscope-barcodingstim","file_name":"behavior.py","full_name":"VisualObject.set_param_index","func_name":"set_param_index","docstring":"Sets the sequence index.","docstring_tokens":"","code":"def set_param_index(self, index):\n \"\"\" Sets the sequence index.\n \"\"\"\n new = self.sequence[index][0]\n self._current_correct = self.sequence[index][1]\n self._sequence_index = index\n self._update_stimulus(new)","code_tokens":"","url":757445} +{"project_name":"SatishKumarAnbalagan\/Semantic-Segmentation","file_name":"functional.py","full_name":"resize","func_name":"resize","docstring":"Resize the input PIL Image to the given size.","docstring_tokens":"","code":"def resize(img, size, interpolation=Image.BILINEAR):\n \"\"\"Resize the input PIL Image to the given size.\n Args:\n img (PIL Image): Image to be resized.\n size (sequence or int): Desired output size. If size is a sequence like\n (h, w), the output size will be matched to this. If size is an int,\n the smaller edge of the image will be matched to this number maintaing\n the aspect ratio. i.e, if height > width, then image will be rescaled to\n (size * height \/ width, size)\n interpolation (int, optional): Desired interpolation. Default is\n ``PIL.Image.BILINEAR``\n Returns:\n PIL Image: Resized image.\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):\n raise TypeError('Got inappropriate size arg: {}'.format(size))\n if isinstance(size, int):\n (w, h) = img.size\n if w <= h and w == size or (h <= w and h == size):\n return img\n if w < h:\n ow = size\n oh = int(size * h \/ w)\n return img.resize((ow, oh), interpolation)\n else:\n oh = size\n ow = int(size * w \/ h)\n return img.resize((ow, oh), interpolation)\n else:\n return img.resize(size[::-1], interpolation)","code_tokens":"","url":869763} +{"project_name":"enlite-ai\/maze","file_name":"action_recording_wrapper.py","full_name":"ActionRecordingWrapper.dump","func_name":"dump","docstring":"Dump recorded trajectory to file.","docstring_tokens":"","code":"def dump(self) -> None:\n \"\"\"Dump recorded trajectory to file.\n \"\"\"\n output_path = self.output_dir \/ f'{self._episode_id}.pkl'\n if self.action_record is not None:\n self.action_record.cum_action_record_reward = self._cum_reward\n self.action_record.dump(output_path)","code_tokens":"","url":646844} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"memory.py","full_name":"LSHMemory.get_hash_slots","func_name":"get_hash_slots","docstring":"Gets hashed-to buckets for batch of queries.","docstring_tokens":"","code":"def get_hash_slots(self, query):\n \"\"\"Gets hashed-to buckets for batch of queries.\n\n Args:\n query: 2-d Tensor of query vectors.\n\n Returns:\n A list of hashed-to buckets for each hash function.\n \"\"\"\n binary_hash = [tf.less(tf.matmul(query, self.hash_vecs[i], transpose_b=True), 0) for i in xrange(self.num_libraries)]\n hash_slot_idxs = [tf.reduce_sum(tf.to_int32(binary_hash[i]) * tf.constant([[2 ** i for i in xrange(self.num_hashes)]], dtype=tf.int32), 1) for i in xrange(self.num_libraries)]\n return hash_slot_idxs","code_tokens":"","url":49556} +{"project_name":"Eric3911\/OpenAGI","file_name":"phonectic.py","full_name":"EnglishCharacter.reverse","func_name":"reverse","docstring":"Convert a character id sequence into text.","docstring_tokens":"","code":"def reverse(self, ids):\n \"\"\" Convert a character id sequence into text.\n Args:\n ids (List[int]): List of a character id sequence.\n Returns:\n str: The input text sequence.\n \"\"\"\n return [self.vocab.reverse(i) for i in ids]","code_tokens":"","url":251699} +{"project_name":"nprapps\/mapturner","file_name":"__init__.py","full_name":"MapTurner.process_ogr2ogr","func_name":"process_ogr2ogr","docstring":"Process a layer using ogr2ogr.","docstring_tokens":"","code":"def process_ogr2ogr(self, name, layer, input_path):\n \"\"\"\n Process a layer using ogr2ogr.\n \"\"\"\n output_path = os.path.join(TEMP_DIRECTORY, '%s.json' % name)\n if os.path.exists(output_path):\n os.remove(output_path)\n ogr2ogr_cmd = ['ogr2ogr', '-f', 'GeoJSON', '-clipsrc', self.config['bbox']]\n if 'where' in layer:\n ogr2ogr_cmd.extend(['-where', '\"%s\"' % layer['where']])\n ogr2ogr_cmd.extend([output_path, input_path])\n sys.stdout.write('* Running ogr2ogr\\n')\n if self.args.verbose:\n sys.stdout.write(' %s\\n' % ' '.join(ogr2ogr_cmd))\n r = envoy.run(' '.join(ogr2ogr_cmd))\n if r.status_code != 0:\n sys.stderr.write(r.std_err)\n return output_path","code_tokens":"","url":209543} +{"project_name":"thaines\/helit","file_name":"tile_image.py","full_name":"TileImage.draw","func_name":"draw","docstring":"Draws the image into the provided context, matching the provided viewport.","docstring_tokens":"","code":"def draw(self, ctx, vp):\n \"\"\"Draws the image into the provided context, matching the provided viewport.\"\"\"\n if not self.visible:\n return\n scale = vp.width \/ float(vp.end_x - vp.start_x)\n base_x = int(math.floor(vp.start_x * scale))\n base_y = int(math.floor(vp.start_y * scale))\n tile_bx = int(math.floor(base_x \/ float(self.tile_size))) * self.tile_size\n tile_by = int(math.floor(base_y \/ float(self.tile_size))) * self.tile_size\n y = tile_by\n while y < int(base_y + vp.height + 1):\n x = tile_bx\n while x < int(base_x + vp.width + 1):\n tile = self.fetch_tile(scale, x, y)\n ctx.set_source_surface(tile, x - base_x, y - base_y)\n ctx.rectangle(x - base_x, y - base_y, self.tile_size, self.tile_size)\n ctx.fill()\n x += self.tile_size\n y += self.tile_size\n if self.tint > 0.0001:\n ctx.set_source_rgba(1.0, 1.0, 1.0, self.tint)\n ctx.paint()","code_tokens":"","url":592688} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"op_hint.py","full_name":"OpHint.add_inputs","func_name":"add_inputs","docstring":"Add a sequence of inputs to the function invocation.","docstring_tokens":"","code":"def add_inputs(self, *args, **kwargs):\n \"\"\"Add a sequence of inputs to the function invocation.\n\n Args:\n *args: List of inputs to be converted (should be Tf.Tensor).\n **kwargs: This allows 'names' which should be a list of names.\n Returns:\n Wrapped inputs (identity standins that have additional metadata). These\n are also are also tf.Tensor's.\n \"\"\"\n if 'names' in kwargs:\n return [self._inputs.add(arg, name=name) for (arg, name) in zip(args, kwargs['names'])]\n else:\n return [self._inputs.add(arg) for arg in args]","code_tokens":"","url":313798} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"nonlin.py","full_name":"LowRankMatrix.collapse","func_name":"collapse","docstring":"Collapse the low-rank matrix to a full-rank one.","docstring_tokens":"","code":"def collapse(self):\n \"\"\"Collapse the low-rank matrix to a full-rank one.\"\"\"\n self.collapsed = np.array(self)\n self.cs = None\n self.ds = None\n self.alpha = None","code_tokens":"","url":77715} +{"project_name":"MLBazaar\/MLPrimitives","file_name":"cv2.py","full_name":"GaussianBlur","func_name":"GaussianBlur","docstring":"Apply Gaussian blur to the given data.","docstring_tokens":"","code":"def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):\n \"\"\"Apply Gaussian blur to the given data.\n\n Args:\n X: data to blur\n kernel_size: Gaussian kernel size\n stddev: Gaussian kernel standard deviation (in both X and Y directions)\n \"\"\"\n return image_transform(X, cv2.GaussianBlur, ksize=(ksize_width, ksize_height), sigmaX=sigma_x, sigmaY=sigma_y)","code_tokens":"","url":630644} +{"project_name":"ivanmontero\/autobot","file_name":"test_utils_summarization.py","full_name":"SummarizationDataProcessingTest.test_fit_to_block_sequence_too_small","func_name":"test_fit_to_block_sequence_too_small","docstring":"Pad the sequence with 0 if the sequence is smaller than the block size.","docstring_tokens":"","code":"def test_fit_to_block_sequence_too_small(self):\n \"\"\" Pad the sequence with 0 if the sequence is smaller than the block size.\"\"\"\n sequence = [1, 2, 3, 4]\n expected_output = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]\n self.assertEqual(truncate_or_pad(sequence, self.block_size, 0), expected_output)","code_tokens":"","url":417766} +{"project_name":"hwang051785\/pyCPT","file_name":"pyHMRF.py","full_name":"Element.calc_sum_log_mixture_density","func_name":"calc_sum_log_mixture_density","docstring":"Calculate sum of log mixture density with each observation at every element.","docstring_tokens":"","code":"def calc_sum_log_mixture_density(self, comp_coef, mu, cov):\n \"\"\"Calculate sum of log mixture density with each observation at every element.\n\n Args:\n comp_coef (:obj:`np.ndarray`): Component coefficient for each element (row) and label (column).\n mu (:obj:`np.ndarray`): Mean value array for all labels and features.\n cov (:obj:`np.ndarray`): Covariance matrix.\n\n Returns:\n float: Summed log mixture density.\n\n \"\"\"\n lmd = np.zeros((self.phys_shp.prod(), self.n_labels))\n for l in range(self.n_labels):\n draw = multivariate_normal(mean=mu[l, :], cov=cov[l, :, :] + np.eye(self.n_feat) * 1e-06).pdf(self.feat)\n multi = comp_coef[:, l] * np.array([draw])\n lmd[:, l] = multi\n lmd = np.sum(lmd, axis=1)\n with np.errstate(divide='ignore'):\n lmd = np.log(lmd)\n return np.sum(lmd)","code_tokens":"","url":296195} +{"project_name":"palmettos\/neat-autoencoders","file_name":"statistics.py","full_name":"StatisticsReporter.save_genome_fitness","func_name":"save_genome_fitness","docstring":"Saves the population's best and average fitness.","docstring_tokens":"","code":"def save_genome_fitness(self, delimiter=' ', filename='fitness_history.csv'):\n \"\"\" Saves the population's best and average fitness. \"\"\"\n with open(filename, 'w') as f:\n w = csv.writer(f, delimiter=delimiter)\n best_fitness = [c.fitness for c in self.most_fit_genomes]\n avg_fitness = self.get_fitness_mean()\n for (best, avg) in zip(best_fitness, avg_fitness):\n w.writerow([best, avg])","code_tokens":"","url":735208} +{"project_name":"Vedaank\/cs188-sp19","file_name":"inference.py","full_name":"MarginalInference.getBeliefDistribution","func_name":"getBeliefDistribution","docstring":"Return the marginal belief over a particular ghost by summing out the others.","docstring_tokens":"","code":"def getBeliefDistribution(self):\n \"\"\"\n Return the marginal belief over a particular ghost by summing out the\n others.\n \"\"\"\n jointDistribution = jointInference.getBeliefDistribution()\n dist = DiscreteDistribution()\n for (t, prob) in jointDistribution.items():\n dist[t[self.index - 1]] += prob\n return dist","code_tokens":"","url":226555} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"composable_model_test.py","full_name":"ComposableModelTest.testJointLinearModel","func_name":"testJointLinearModel","docstring":"Tests that loss goes down with training.","docstring_tokens":"","code":"def testJointLinearModel(self):\n \"\"\"Tests that loss goes down with training.\"\"\"\n\n def input_fn():\n return ({'age': sparse_tensor.SparseTensor(values=['1'], indices=[[0, 0]], dense_shape=[1, 1]), 'language': sparse_tensor.SparseTensor(values=['english'], indices=[[0, 0]], dense_shape=[1, 1])}, constant_op.constant([[1]]))\n language = feature_column.sparse_column_with_hash_bucket('language', 100)\n age = feature_column.sparse_column_with_hash_bucket('age', 2)\n head = head_lib.multi_class_head(n_classes=2)\n classifier = _joint_linear_estimator(head, feature_columns=[age, language])\n classifier.fit(input_fn=input_fn, steps=1000)\n loss1 = classifier.evaluate(input_fn=input_fn, steps=1)['loss']\n classifier.fit(input_fn=input_fn, steps=2000)\n loss2 = classifier.evaluate(input_fn=input_fn, steps=1)['loss']\n self.assertLess(loss2, loss1)\n self.assertLess(loss2, 0.01)","code_tokens":"","url":603845} +{"project_name":"pedrojrv\/nucml","file_name":"querying_utils.py","full_name":"load_element","func_name":"load_element","docstring":"Load all datapoints avaliable for a particular element.","docstring_tokens":"","code":"def load_element(df, Z, nat_iso='I', one_hot=False, scaler=None):\n \"\"\"Load all datapoints avaliable for a particular element.\n\n Args:\n df (DataFrame): All avaliable experimental datapoints.\n Z (int): Number of protons.\n nat_iso (str, optional): \"I\" means isotopic while \"N\" means natural experimental campaigns. Defaults to \"I\".\n one_hot (bool, optional): If True, the script assumes that the reaction channel is one-hot encoded. Defaults to\n False.\n scale (bool, optional): If True, the scaler object passed will be use to normalize the extracted information.\n Defaults to False.\n scaler (object, optional): Fitted scaler object. Defaults to None.\n to_scale (list, optional): List of feature names that are to be scaled. Defaults to [].\n\n Returns:\n DataFrame\n \"\"\"\n if one_hot:\n sample = df[(df['Z'] == Z) & (df['Element_Flag_' + nat_iso] == 1)].sort_values(by='Energy', ascending=True)\n else:\n sample = df[(df['Z'] == Z) & (df['Element_Flag'] == nat_iso)].sort_values(by='Energy', ascending=True)\n if scaler:\n sample = scaler.transform(sample)\n return sample","code_tokens":"","url":249741} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"lightning_container.py","full_name":"LightningContainer.create_lightning_module_and_store","func_name":"create_lightning_module_and_store","docstring":"Creates the Lightning model by calling `create_lightning_module` and stores it in the `lightning_module` property.","docstring_tokens":"","code":"def create_lightning_module_and_store(self) -> None:\n \"\"\"\n Creates the Lightning model by calling `create_lightning_module` and stores it in the `lightning_module`\n property.\n \"\"\"\n self._model = self.create_model()\n if isinstance(self._model, LightningModuleWithOptimizer):\n self._model._optimizer_params = create_from_matching_params(self, OptimizerParams)\n self._model._trainer_params = create_from_matching_params(self, TrainerParams)","code_tokens":"","url":612909} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"summary_iterator.py","full_name":"SummaryWriter.add_event","func_name":"add_event","docstring":"Adds an event to the event file.","docstring_tokens":"","code":"def add_event(self, event):\n \"\"\"Adds an event to the event file.\n\n Args:\n event: An `Event` protocol buffer.\n \"\"\"\n if not self._closed:\n self._event_queue.put(event)","code_tokens":"","url":183244} +{"project_name":"qiuwei\/snlp","file_name":"gaussianize.py","full_name":"Gaussianize.qqplot","func_name":"qqplot","docstring":"Show qq plots compared to normal before and after the transform.","docstring_tokens":"","code":"def qqplot(self, x, prefix='qq'):\n \"\"\"Show qq plots compared to normal before and after the transform.\"\"\"\n from matplotlib import pylab\n from scipy.stats import probplot\n y = self.transform(x)\n for (i, (x_i, y_i)) in enumerate(zip(x.T, y.T)):\n probplot(x_i, dist='norm', plot=pylab)\n pylab.savefig(prefix + '_%d_before.png' % i)\n pylab.clf()\n probplot(y_i, dist='norm', plot=pylab)\n pylab.savefig(prefix + '_%d_after.png' % i)\n pylab.clf()","code_tokens":"","url":878871} +{"project_name":"deepmind\/dm_control","file_name":"__init__.py","full_name":"MJCFVariator.bind_attributes","func_name":"bind_attributes","docstring":"Binds variations to attributes of an MJCF element.","docstring_tokens":"","code":"def bind_attributes(self, element, **kwargs):\n \"\"\"Binds variations to attributes of an MJCF element.\n\n Args:\n element: An `mjcf.Element` object.\n **kwargs: Keyword arguments mapping attribute names to the corresponding\n variations. A variation is either a fixed value or a callable that\n optionally takes the original value of an attribute and returns a\n new value.\n \"\"\"\n for (attribute_name, variation) in kwargs.items():\n if variation is None and attribute_name in self._variations[element]:\n del self._variations[element][attribute_name]\n else:\n initial_value = copy.copy(getattr(element, attribute_name))\n self._variations[element][attribute_name] = _VariationInfo(initial_value, variation)","code_tokens":"","url":164997} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"results.py","full_name":"Analysis.arcs_executed","func_name":"arcs_executed","docstring":"Returns a sorted list of the arcs actually executed in the code.","docstring_tokens":"","code":"def arcs_executed(self):\n \"\"\"Returns a sorted list of the arcs actually executed in the code.\"\"\"\n executed = self.data.arcs(self.filename) or []\n executed = self.file_reporter.translate_arcs(executed)\n return sorted(executed)","code_tokens":"","url":147916} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"webbrowser.py","full_name":"get","func_name":"get","docstring":"Return a browser launcher instance appropriate for the environment.","docstring_tokens":"","code":"def get(using=None):\n \"\"\"Return a browser launcher instance appropriate for the environment.\"\"\"\n if using is not None:\n alternatives = [using]\n else:\n alternatives = _tryorder\n for browser in alternatives:\n if '%s' in browser:\n browser = shlex.split(browser)\n if browser[-1] == '&':\n return BackgroundBrowser(browser[:-1])\n else:\n return GenericBrowser(browser)\n else:\n try:\n command = _browsers[browser.lower()]\n except KeyError:\n command = _synthesize(browser)\n if command[1] is not None:\n return command[1]\n elif command[0] is not None:\n return command[0]()\n raise Error('could not locate runnable browser')","code_tokens":"","url":429889} +{"project_name":"google\/deepvariant","file_name":"timer.py","full_name":"MultiIntervalTimer.Reset","func_name":"Reset","docstring":"Resets the measured cumulative time to zero.","docstring_tokens":"","code":"def Reset(self):\n \"\"\"Resets the measured cumulative time to zero.\"\"\"\n self.duration = 0","code_tokens":"","url":540515} +{"project_name":"rudranil723\/mini-main","file_name":"utils.py","full_name":"ConnectionHandler.ensure_defaults","func_name":"ensure_defaults","docstring":"Put the defaults into the settings dictionary for a given connection where no settings is provided.","docstring_tokens":"","code":"def ensure_defaults(self, alias):\n \"\"\"\n Put the defaults into the settings dictionary for a given connection\n where no settings is provided.\n \"\"\"\n try:\n conn = self.databases[alias]\n except KeyError:\n raise ConnectionDoesNotExist(\"The connection %s doesn't exist\" % alias)\n conn.setdefault('ATOMIC_REQUESTS', False)\n conn.setdefault('AUTOCOMMIT', True)\n conn.setdefault('ENGINE', 'django.db.backends.dummy')\n if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:\n conn['ENGINE'] = 'django.db.backends.dummy'\n conn.setdefault('CONN_MAX_AGE', 0)\n conn.setdefault('OPTIONS', {})\n conn.setdefault('TIME_ZONE', None)\n for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:\n conn.setdefault(setting, '')","code_tokens":"","url":315693} +{"project_name":"thaines\/helit","file_name":"corpus.py","full_name":"Corpus.getMaxWordNum","func_name":"getMaxWordNum","docstring":"Returns the largest word number it has seen.","docstring_tokens":"","code":"def getMaxWordNum(self):\n \"\"\"Returns the largest word number it has seen.\"\"\"\n return self.maxWordNum","code_tokens":"","url":592339} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.body_invweight0","func_name":"body_invweight0","docstring":"mean inv inert in qpos0 (trn, rot) (nbody x 2).","docstring_tokens":"","code":"@util.CachedProperty\ndef body_invweight0(self):\n \"\"\"mean inv inert in qpos0 (trn, rot) (nbody x 2).\"\"\"\n return util.buf_to_npy(self._ptr.contents.body_invweight0, (self.nbody, 2))","code_tokens":"","url":440254} +{"project_name":"Floobits\/flootty","file_name":"diff_match_patch.py","full_name":"diff_match_patch.diff_commonOverlap","func_name":"diff_commonOverlap","docstring":"Determine if the suffix of one string is the prefix of another.","docstring_tokens":"","code":"def diff_commonOverlap(self, text1, text2):\n \"\"\"Determine if the suffix of one string is the prefix of another.\n\n Args:\n text1 First string.\n text2 Second string.\n\n Returns:\n The number of characters common to the end of the first\n string and the start of the second string.\n \"\"\"\n text1_length = len(text1)\n text2_length = len(text2)\n if text1_length == 0 or text2_length == 0:\n return 0\n if text1_length > text2_length:\n text1 = text1[-text2_length:]\n elif text1_length < text2_length:\n text2 = text2[:text1_length]\n text_length = min(text1_length, text2_length)\n if text1 == text2:\n return text_length\n best = 0\n length = 1\n while True:\n pattern = text1[-length:]\n found = text2.find(pattern)\n if found == -1:\n return best\n length += found\n if found == 0 or text1[-length:] == text2[:length]:\n best = length\n length += 1","code_tokens":"","url":211457} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"run_classifier.py","full_name":"run_keras_compile_fit","func_name":"run_keras_compile_fit","docstring":"Runs BERT classifier model using Keras compile\/fit API.","docstring_tokens":"","code":"def run_keras_compile_fit(model_dir, strategy, model_fn, train_input_fn, eval_input_fn, loss_fn, metric_fn, init_checkpoint, epochs, steps_per_epoch, steps_per_loop, eval_steps, training_callbacks=True, custom_callbacks=None):\n \"\"\"Runs BERT classifier model using Keras compile\/fit API.\"\"\"\n with strategy.scope():\n training_dataset = train_input_fn()\n evaluation_dataset = eval_input_fn() if eval_input_fn else None\n (bert_model, sub_model) = model_fn()\n optimizer = bert_model.optimizer\n if init_checkpoint:\n checkpoint = tf.train.Checkpoint(model=sub_model)\n checkpoint.restore(init_checkpoint).assert_existing_objects_matched()\n if not isinstance(metric_fn, (list, tuple)):\n metric_fn = [metric_fn]\n bert_model.compile(optimizer=optimizer, loss=loss_fn, metrics=[fn() for fn in metric_fn], experimental_steps_per_execution=steps_per_loop)\n summary_dir = os.path.join(model_dir, 'summaries')\n summary_callback = tf.keras.callbacks.TensorBoard(summary_dir)\n checkpoint = tf.train.Checkpoint(model=bert_model, optimizer=optimizer)\n checkpoint_manager = tf.train.CheckpointManager(checkpoint, directory=model_dir, max_to_keep=None, step_counter=optimizer.iterations, checkpoint_interval=0)\n checkpoint_callback = keras_utils.SimpleCheckpoint(checkpoint_manager)\n if training_callbacks:\n if custom_callbacks is not None:\n custom_callbacks += [summary_callback, checkpoint_callback]\n else:\n custom_callbacks = [summary_callback, checkpoint_callback]\n history = bert_model.fit(x=training_dataset, validation_data=evaluation_dataset, steps_per_epoch=steps_per_epoch, epochs=epochs, validation_steps=eval_steps, callbacks=custom_callbacks)\n stats = {'total_training_steps': steps_per_epoch * epochs}\n if 'loss' in history.history:\n stats['train_loss'] = history.history['loss'][-1]\n if 'val_accuracy' in history.history:\n stats['eval_metrics'] = history.history['val_accuracy'][-1]\n return (bert_model, stats)","code_tokens":"","url":850293} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"test_file.py","full_name":"Model.configure","func_name":"configure","docstring":"Sets passthrough paths to absolute to exercise code.","docstring_tokens":"","code":"def configure(self):\n \"\"\" Sets passthrough paths to absolute to exercise code. \"\"\"\n comp = Source()\n comp.directory = 'Source'\n comp = self.add('source', comp)\n comp = Middle()\n comp.directory = 'Middle'\n comp = self.add('middle', comp)\n comp = Sink()\n comp.directory = 'Sink'\n comp = self.add('sink', comp)\n self.driver.workflow.add(['source', 'middle', 'sink'])\n self.connect('source.text_file', 'middle.text_in')\n self.connect('middle.text_out', 'sink.text_file')","code_tokens":"","url":276196} +{"project_name":"juaml\/julearn","file_name":"test_available_searchers.py","full_name":"test_reset_searcher","func_name":"test_reset_searcher","docstring":"Test resetting the searcher registry.","docstring_tokens":"","code":"def test_reset_searcher() -> None:\n \"\"\"Test resetting the searcher registry.\"\"\"\n register_searcher('custom_grid', GridSearchCV)\n get_searcher('custom_grid')\n reset_searcher_register()\n with pytest.raises(ValueError, match='The specified searcher '):\n get_searcher('custom_grid')","code_tokens":"","url":593652} +{"project_name":"airctic\/icevision","file_name":"voc_parser.py","full_name":"VOCMaskParser.record_id_mask","func_name":"record_id_mask","docstring":"Should return the same as `record_id` from parent parser.","docstring_tokens":"","code":"def record_id_mask(self, o) -> Hashable:\n \"\"\"Should return the same as `record_id` from parent parser.\"\"\"\n return str(Path(o).stem)","code_tokens":"","url":596957} +{"project_name":"kubeflow\/pipelines","file_name":"component.py","full_name":"llm_retrieval_metrics","func_name":"llm_retrieval_metrics","docstring":"Compute retrieval metrics based on the docs retrieved for each query.","docstring_tokens":"","code":"@container_component\ndef llm_retrieval_metrics(gcp_resources: OutputPath(str), retrieval_metrics: Output[Metrics], project: str, location: str, golden_docs_pattern: str, embedding_retrieval_results_pattern: str, retrieval_metrics_top_k_list: str, display_name: str='llm_retrieval_metrics_component', machine_type: str='e2-highmem-16', service_account: str='', network: str='', runner: str='DirectRunner', dataflow_service_account: str='', dataflow_disk_size_gb: int=50, dataflow_machine_type: str='n1-standard-4', dataflow_workers_num: int=1, dataflow_max_workers_num: int=5, dataflow_subnetwork: str='', dataflow_use_public_ips: bool=True, encryption_spec_key_name: str=''):\n \"\"\"Compute retrieval metrics based on the docs retrieved for each query.\n\n Args:\n project: Required. The GCP project that runs the pipeline component.\n location: Required. The GCP region that runs the pipeline component.\n golden_docs_pattern: Required. Files where queries and corresponding\n golden doc ids are saved. The path pattern can contain glob characters\n (`*`, `?`, and `[...]` sets).\n embedding_retrieval_results_pattern: Required. Files where doc retrieval\n results for each query are saved. The path pattern can contain glob\n characters (`*`, `?`, and `[...]` sets).\n retrieval_metrics_top_k_list: Required. k values for retrieval metrics,\n for example, precision@k, accuracy@k, etc. If more than one value,\n separated by comma. e.g., \"1,5,10\".\n display_name: The name of the Evaluation job.\n machine_type: The machine type of this custom job. If not set, defaulted\n to `e2-highmem-16`. More details:\n https:\/\/cloud.google.com\/compute\/docs\/machine-resource\n service_account: Sets the default service account for workload run-as\n account. The service account running the pipeline\n (https:\/\/cloud.google.com\/vertex-ai\/docs\/pipelines\/configure-project#service-account)\n submitting jobs must have act-as permission on this run-as account. If\n unspecified, the Vertex AI Custom Code Service\n Agent(https:\/\/cloud.google.com\/vertex-ai\/docs\/general\/access-control#service-agents)\n for the CustomJob's project.\n network: The full name of the Compute Engine network to which the job\n should be peered. For example, projects\/12345\/global\/networks\/myVPC.\n Format is of the form projects\/{project}\/global\/networks\/{network}.\n Where {project} is a project number, as in 12345, and {network} is a\n network name. Private services access must already be configured for the\n network. If left unspecified, the job is not peered with any network.\n runner: runner for the beam pipeline. DirectRunner and DataflowRunner are\n supported.\n dataflow_service_account: Service account to run the dataflow job. If not\n set, dataflow will use the default worker service account. For more\n details, see\n https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/security-and-permissions#default_worker_service_account\n dataflow_disk_size_gb: The disk size (in GB) of the machine executing the\n evaluation run.\n dataflow_machine_type: The dataflow worker machine type executing the\n evaluation run.\n dataflow_workers_num: The number of workers executing the evaluation run.\n dataflow_max_workers_num: The max number of workers executing the\n evaluation run.\n dataflow_subnetwork: Dataflow's fully qualified subnetwork name, when\n empty the default subnetwork will be used. More details:\n https:\/\/cloud.google.com\/dataflow\/docs\/guides\/specifying-networks#example_network_and_subnetwork_specifications\n dataflow_use_public_ips: Specifies whether Dataflow workers use public IP\n addresses.\n encryption_spec_key_name: Customer-managed encryption key options for the\n CustomJob. If this is set, then all resources created by the CustomJob\n will be encrypted with the provided encryption key.\n\n Returns:\n gcp_resources:\n Serialized gcp_resources proto tracking the custom job.\n retrieval_metrics:\n A Metrics artifact representing the retrieval metrics.\n \"\"\"\n return gcpc_utils.build_serverless_customjob_container_spec(project=project, location=location, custom_job_payload=utils.build_custom_job_payload(display_name=display_name, machine_type=machine_type, image_uri=_IMAGE_URI, args=[f'--retrieval_metrics={True}', f'--project={project}', f'--location={location}', f'--golden_docs_pattern={golden_docs_pattern}', f'--embedding_retrieval_results_pattern={embedding_retrieval_results_pattern}', f'--retrieval_metrics_top_k_list={retrieval_metrics_top_k_list}', f'--root_dir={PIPELINE_ROOT_PLACEHOLDER}', f'--gcp_resources={gcp_resources}', f'--retrieval_metrics_output_path={retrieval_metrics.path}', f'--runner={runner}', f'--dataflow_service_account={dataflow_service_account}', f'--dataflow_disk_size={dataflow_disk_size_gb}', f'--dataflow_machine_type={dataflow_machine_type}', f'--dataflow_workers_num={dataflow_workers_num}', f'--dataflow_max_workers_num={dataflow_max_workers_num}', f'--dataflow_subnetwork={dataflow_subnetwork}', f'--dataflow_use_public_ips={dataflow_use_public_ips}', '--executor_input={{$.json_escape[1]}}'], service_account=service_account, network=network, encryption_spec_key_name=encryption_spec_key_name), gcp_resources=gcp_resources)","code_tokens":"","url":779596} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"application.py","full_name":"_CombinedRegistry.bindings","func_name":"bindings","docstring":"Not needed - this object is not going to be wrapped in another KeyBindings object.","docstring_tokens":"","code":"def bindings(self) -> List[Binding]:\n \"\"\"Not needed - this object is not going to be wrapped in another\n KeyBindings object.\"\"\"\n raise NotImplementedError","code_tokens":"","url":435084} +{"project_name":"jbwang1997\/CrossKD","file_name":"coco_metric.py","full_name":"CocoMetric.fast_eval_recall","func_name":"fast_eval_recall","docstring":"Evaluate proposal recall with COCO's fast_eval_recall.","docstring_tokens":"","code":"def fast_eval_recall(self, results: List[dict], proposal_nums: Sequence[int], iou_thrs: Sequence[float], logger: Optional[MMLogger]=None) -> np.ndarray:\n \"\"\"Evaluate proposal recall with COCO's fast_eval_recall.\n\n Args:\n results (List[dict]): Results of the dataset.\n proposal_nums (Sequence[int]): Proposal numbers used for\n evaluation.\n iou_thrs (Sequence[float]): IoU thresholds used for evaluation.\n logger (MMLogger, optional): Logger used for logging the recall\n summary.\n Returns:\n np.ndarray: Averaged recall results.\n \"\"\"\n gt_bboxes = []\n pred_bboxes = [result['bboxes'] for result in results]\n for i in range(len(self.img_ids)):\n ann_ids = self._coco_api.get_ann_ids(img_ids=self.img_ids[i])\n ann_info = self._coco_api.load_anns(ann_ids)\n if len(ann_info) == 0:\n gt_bboxes.append(np.zeros((0, 4)))\n continue\n bboxes = []\n for ann in ann_info:\n if ann.get('ignore', False) or ann['iscrowd']:\n continue\n (x1, y1, w, h) = ann['bbox']\n bboxes.append([x1, y1, x1 + w, y1 + h])\n bboxes = np.array(bboxes, dtype=np.float32)\n if bboxes.shape[0] == 0:\n bboxes = np.zeros((0, 4))\n gt_bboxes.append(bboxes)\n recalls = eval_recalls(gt_bboxes, pred_bboxes, proposal_nums, iou_thrs, logger=logger)\n ar = recalls.mean(axis=1)\n return ar","code_tokens":"","url":490844} +{"project_name":"iver56\/audiomentations","file_name":"composition.py","full_name":"BaseCompose.randomize_parameters","func_name":"randomize_parameters","docstring":"Randomize and define parameters of every transform in composition.","docstring_tokens":"","code":"def randomize_parameters(self, *args, **kwargs):\n \"\"\"\n Randomize and define parameters of every transform in composition.\n \"\"\"\n apply_to_children = kwargs.get('apply_to_children', True)\n if apply_to_children:\n if 'apply_to_children' in kwargs:\n del kwargs['apply_to_children']\n for transform in self.transforms:\n transform.randomize_parameters(*args, **kwargs)","code_tokens":"","url":403262} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_bsplines.py","full_name":"TestSmoothingSpline.test_non_regularized_case","func_name":"test_non_regularized_case","docstring":"In case the regularization parameter is 0, the resulting spline is an interpolation spline with natural boundary conditions.","docstring_tokens":"","code":"def test_non_regularized_case(self):\n \"\"\"\n In case the regularization parameter is 0, the resulting spline\n is an interpolation spline with natural boundary conditions.\n \"\"\"\n np.random.seed(1234)\n n = 100\n x = np.sort(np.random.random_sample(n) * 4 - 2)\n y = x ** 2 * np.sin(4 * x) + x ** 3 + np.random.normal(0.0, 1.5, n)\n spline_GCV = make_smoothing_spline(x, y, lam=0.0)\n spline_interp = make_interp_spline(x, y, 3, bc_type='natural')\n grid = np.linspace(x[0], x[-1], 2 * n)\n assert_allclose(spline_GCV(grid), spline_interp(grid), atol=1e-15)","code_tokens":"","url":445638} +{"project_name":"f-dangel\/cockpit","file_name":"utils_transforms.py","full_name":"batch_dot_transform","func_name":"batch_dot_transform","docstring":"Transform individual gradients into pairwise dot products.","docstring_tokens":"","code":"def batch_dot_transform(batch_grad):\n \"\"\"Transform individual gradients into pairwise dot products.\"\"\"\n letters = get_first_n_alphabet(batch_grad.dim() + 1)\n (n1, n2, sum_out) = (letters[0], letters[1], ''.join(letters[2:]))\n einsum_equation = f'{n1}{sum_out},{n2}{sum_out}->{n1}{n2}'\n return einsum(einsum_equation, batch_grad, batch_grad)","code_tokens":"","url":492696} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"test_buffer.py","full_name":"multislice","func_name":"multislice","docstring":"Multi-dimensional slicing: slices is a list of slice objects.","docstring_tokens":"","code":"def multislice(lst, slices):\n \"\"\"Multi-dimensional slicing: slices is a list of slice objects.\"\"\"\n if atomp(lst):\n return lst\n return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]]","code_tokens":"","url":431304} +{"project_name":"BlueMirrors\/cvu","file_name":"benchmark.py","full_name":"install_dependencies","func_name":"install_dependencies","docstring":"Install dependencies for benchmarking.","docstring_tokens":"","code":"def install_dependencies() -> None:\n \"\"\"Install dependencies for benchmarking.\n \"\"\"\n setup_package('vidsz', 'vidsz')\n vidsz = importlib.import_module('vidsz.opencv')\n return vidsz","code_tokens":"","url":524165} +{"project_name":"AgnostiqHQ\/covalent","file_name":"mnist_sublattices.py","full_name":"train_over_one_epoch","func_name":"train_over_one_epoch","docstring":"Train neural network model over one epoch.","docstring_tokens":"","code":"def train_over_one_epoch(dataloader: torch.utils.data.dataloader.DataLoader, model: NeuralNetwork, optimizer: torch.optim.Optimizer, log_interval: int, epoch: int, loss_fn, train_losses: list, train_counter: int, device: str='cpu'):\n \"\"\"Train neural network model over one epoch.\"\"\"\n size = len(dataloader.dataset)\n model.train()\n for (batch, (X, y)) in enumerate(dataloader):\n (X, y) = (X.to(device), y.to(device))\n pred = model(X)\n loss = loss_fn(pred, y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if batch % log_interval == 0:\n (loss, current) = (loss.item(), batch * len(X))\n print(f'loss: {loss:>7f} [{current:>5d}\/{size:>5d}]')\n train_losses.append(loss)\n train_counter.append(batch * 64 + (epoch - 1) * len(dataloader.dataset))\n return (model, optimizer)","code_tokens":"","url":490116} +{"project_name":"tensorflow\/agents","file_name":"episodic_replay_buffer.py","full_name":"EpisodicReplayBuffer.get_valid_ids_mask","func_name":"get_valid_ids_mask","docstring":"Returns a mask of whether the given IDs are valid.","docstring_tokens":"","code":"def get_valid_ids_mask(self, episode_ids):\n \"\"\"Returns a mask of whether the given IDs are valid.\"\"\"\n with tf.device(self._device):\n with tf.name_scope('get_valid_ids_mask'):\n return self._add_episode_critical_section.execute(lambda : self._get_valid_ids_mask_locked(episode_ids))","code_tokens":"","url":22895} +{"project_name":"thaines\/helit","file_name":"gaussian_prior.py","full_name":"GaussianPrior.sample","func_name":"sample","docstring":"Returns a Gaussian, drawn from this prior.","docstring_tokens":"","code":"def sample(self):\n \"\"\"Returns a Gaussian, drawn from this prior.\"\"\"\n d = self.mu.shape[0]\n wishart = Wishart(d)\n gaussian = Gaussian(d)\n ret = Gaussian(d)\n wishart.setDof(self.n)\n wishart.setScale(self.getLambda())\n ret.setPrecision(wishart.sample())\n gaussian.setPrecision(self.k * ret.getPrecision())\n gaussian.setMean(self.mu)\n ret.setMean(gaussian.sample())\n return ret","code_tokens":"","url":591668} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"spines.py","full_name":"Spine.get_smart_bounds","func_name":"get_smart_bounds","docstring":"Return whether the spine has smart bounds.","docstring_tokens":"","code":"@cbook.deprecated('3.2')\ndef get_smart_bounds(self):\n \"\"\"Return whether the spine has smart bounds.\"\"\"\n return self._smart_bounds","code_tokens":"","url":96748} +{"project_name":"wandb\/wandb","file_name":"artifacts_cache.py","full_name":"ArtifactsCache.cleanup","func_name":"cleanup","docstring":"Clean up the cache, removing the least recently used files first.","docstring_tokens":"","code":"def cleanup(self, target_size: Optional[int]=None, remove_temp: bool=False, target_fraction: Optional[float]=None) -> int:\n \"\"\"Clean up the cache, removing the least recently used files first.\n\n Args:\n target_size: The target size of the cache in bytes. If the cache is larger\n than this, we will remove the least recently used files until the cache\n is smaller than this size.\n remove_temp: Whether to remove temporary files. Temporary files are files\n that are currently being written to the cache. If remove_temp is True,\n all temp files will be removed, regardless of the target_size or\n target_fraction.\n target_fraction: The target fraction of the cache to reclaim. If the cache\n is larger than this, we will remove the least recently used files until\n the cache is smaller than this fraction of its current size. It is an\n error to specify both target_size and target_fraction.\n\n Returns:\n The number of bytes reclaimed.\n \"\"\"\n if target_size is None and target_fraction is None:\n target_size = 0\n if target_size is not None and target_fraction is not None:\n raise ValueError('Cannot specify both target_size and target_fraction')\n if target_size and target_size < 0:\n raise ValueError('target_size must be non-negative')\n if target_fraction and (target_fraction < 0 or target_fraction > 1):\n raise ValueError('target_fraction must be between 0 and 1')\n bytes_reclaimed = 0\n total_size = 0\n temp_size = 0\n for entry in files_in(self._temp_dir):\n size = entry.stat().st_size\n total_size += size\n if remove_temp:\n try:\n os.remove(entry.path)\n bytes_reclaimed += size\n except OSError:\n pass\n else:\n temp_size += size\n if temp_size:\n wandb.termwarn(f'Cache contains {util.to_human_size(temp_size)} of temporary files. Run `wandb artifact cleanup --remove-temp` to remove them.')\n entries = []\n for file_entry in files_in(self._obj_dir):\n total_size += file_entry.stat().st_size\n entries.append(file_entry)\n if target_fraction is not None:\n target_size = int(total_size * target_fraction)\n assert target_size is not None\n for entry in sorted(entries, key=lambda x: x.stat().st_atime):\n if total_size <= target_size:\n return bytes_reclaimed\n try:\n os.remove(entry.path)\n except OSError:\n pass\n total_size -= entry.stat().st_size\n bytes_reclaimed += entry.stat().st_size\n if total_size > target_size:\n wandb.termerror(f'Failed to reclaim enough space in {self._cache_dir}. Try running `wandb artifact cleanup --remove-temp` to remove temporary files.')\n return bytes_reclaimed","code_tokens":"","url":941658} +{"project_name":"tudelft3d\/SUMS-Semantic-Urban-Mesh--public","file_name":"fusion.py","full_name":"TSDFVolume.integrate","func_name":"integrate","docstring":"Integrate an RGB-D frame into the TSDF volume.","docstring_tokens":"","code":"def integrate(self, depth_im, cam_intr, cam_pose, obs_weight=1.0):\n \"\"\"Integrate an RGB-D frame into the TSDF volume.\n Args:\n depth_im (ndarray): A depth image of shape (H, W).\n cam_intr (ndarray): The camera intrinsics matrix of shape (3, 3).\n cam_pose (ndarray): The camera pose (i.e. extrinsics) of shape (4, 4).\n obs_weight (float): The weight to assign for the current observation. A higher\n value\n \"\"\"\n (im_h, im_w) = depth_im.shape\n if self.gpu_mode:\n for gpu_loop_idx in range(self._n_gpu_loops):\n self._cuda_integrate(self._tsdf_vol_gpu, self._weight_vol_gpu, cuda.InOut(self._vol_dim.astype(np.float32)), cuda.InOut(self._vol_origin.astype(np.float32)), cuda.InOut(cam_intr.reshape(-1).astype(np.float32)), cuda.InOut(cam_pose.reshape(-1).astype(np.float32)), cuda.InOut(np.asarray([gpu_loop_idx, self._voxel_size, im_h, im_w, self._trunc_margin, obs_weight], np.float32)), cuda.InOut(depth_im.reshape(-1).astype(np.float32)), block=(self._max_gpu_threads_per_block, 1, 1), grid=(int(self._max_gpu_grid_dim[0]), int(self._max_gpu_grid_dim[1]), int(self._max_gpu_grid_dim[2])))\n else:\n cam_pts = self.vox2world(self._vol_origin, self.vox_coords, self._voxel_size)\n cam_pts = rigid_transform(cam_pts, np.linalg.inv(cam_pose))\n pix_z = cam_pts[:, 2]\n pix = self.cam2pix(cam_pts, cam_intr)\n (pix_x, pix_y) = (pix[:, 0], pix[:, 1])\n valid_pix = np.logical_and(pix_x >= 0, np.logical_and(pix_x < im_w, np.logical_and(pix_y >= 0, np.logical_and(pix_y < im_h, pix_z > 0))))\n depth_val = np.zeros(pix_x.shape)\n depth_val[valid_pix] = depth_im[pix_y[valid_pix], pix_x[valid_pix]]\n depth_diff = depth_val - pix_z\n valid_pts = np.logical_and(depth_val > 0, depth_diff >= -self._trunc_margin)\n dist = np.minimum(1, depth_diff \/ self._trunc_margin)\n valid_vox_x = self.vox_coords[valid_pts, 0]\n valid_vox_y = self.vox_coords[valid_pts, 1]\n valid_vox_z = self.vox_coords[valid_pts, 2]\n w_old = self._weight_vol_cpu[valid_vox_x, valid_vox_y, valid_vox_z]\n tsdf_vals = self._tsdf_vol_cpu[valid_vox_x, valid_vox_y, valid_vox_z]\n valid_dist = dist[valid_pts]\n (tsdf_vol_new, w_new) = self.integrate_tsdf(tsdf_vals, valid_dist, w_old, obs_weight)\n self._weight_vol_cpu[valid_vox_x, valid_vox_y, valid_vox_z] = w_new\n self._tsdf_vol_cpu[valid_vox_x, valid_vox_y, valid_vox_z] = tsdf_vol_new","code_tokens":"","url":910701} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_base.py","full_name":"_AxesBase.get_rasterization_zorder","func_name":"get_rasterization_zorder","docstring":"Return the zorder value below which artists will be rasterized.","docstring_tokens":"","code":"def get_rasterization_zorder(self):\n \"\"\"Return the zorder value below which artists will be rasterized.\"\"\"\n return self._rasterization_zorder","code_tokens":"","url":1061} +{"project_name":"deepmind\/pycolab","file_name":"four_rooms.py","full_name":"make_game","func_name":"make_game","docstring":"Builds and returns a four-rooms game.","docstring_tokens":"","code":"def make_game():\n \"\"\"Builds and returns a four-rooms game.\"\"\"\n return ascii_art.ascii_art_to_game(GAME_ART, what_lies_beneath=' ', sprites={'P': PlayerSprite})","code_tokens":"","url":819266} +{"project_name":"po0ya\/csgan","file_name":"classification.py","full_name":"Classifier.load_classifier","func_name":"load_classifier","docstring":"Loads classifier from a pickle file.","docstring_tokens":"","code":"def load_classifier(self, filename=None):\n \"\"\"Loads classifier from a pickle file.\n\n Args:\n filename: Path to pickle file.\n\n Raises:\n IOError: If an input error occurs while reading pickle file.\n \"\"\"\n if filename is None:\n output_dir = self.get_output_dir()\n filename = self.get_classifier_filename()\n filename = os.path.join(output_dir, filename)\n if not self.classifier_type == 'nn':\n try:\n with open(filename, 'r') as f:\n self.classifier_type = cPickle.load(f)\n self.classifier_params = cPickle.load(f)\n self.estimator = cPickle.load(f)\n self.helper_estimator = cPickle.load(f)\n except IOError as err:\n print('[!] I\/O error({0}): {1}.'.format(err.errno, err.strerror))\n if self.classifier_params.has_key('verbose') and self.classifier_params['verbose']:\n print('[*] Loaded classifier from {}.'.format(filename))\n elif self.classifier_params.has_key('verbose') and self.classifier_params['verbose']:\n print('[!] Default TF loading\/saving for Neural Networks.')","code_tokens":"","url":508588} +{"project_name":"flink-extended\/ai-flow","file_name":"session.py","full_name":"create_sqlalchemy_engine","func_name":"create_sqlalchemy_engine","docstring":"Create SQLAlchemy engine with specified database URI to support AIFlow entities backend storage.","docstring_tokens":"","code":"def create_sqlalchemy_engine(db_uri, **kwargs):\n \"\"\"\n Create SQLAlchemy engine with specified database URI to support AIFlow entities backend storage.\n \"\"\"\n enable_pool = config_constants.SQLALCHEMY_POOL_ENABLED\n options = {}\n if enable_pool and 'sqlite' not in db_uri:\n options['pool_size'] = config_constants.SQLALCHEMY_POOL_SIZE\n options['max_overflow'] = config_constants.SQLALCHEMY_MAX_OVERFLOW\n if 'sqlite' in db_uri:\n options['connect_args'] = {'check_same_thread': False}\n logger.warning('SQLite should only be used in unittests.')\n for (k, v) in kwargs.items():\n options[k] = v\n logger.info('Create SQLAlchemy engine with options %s', options)\n return sqlalchemy.create_engine(db_uri, **options)","code_tokens":"","url":24398} +{"project_name":"PaccMann\/fdsa","file_name":"loss_setmatching.py","full_name":"SetMatchLoss.crossentropy_l1l2","func_name":"crossentropy_l1l2","docstring":"Computes L1 and L2 penalties in addition to cross entropy loss.","docstring_tokens":"","code":"def crossentropy_l1l2(self, predictions: torch.Tensor, target12: torch.Tensor, target21: torch.Tensor) -> torch.Tensor:\n \"\"\"Computes L1 and L2 penalties in addition to cross entropy loss.\n\n Args:\n predictions (torch.Tensor): Logits from the last FC layer with shape\n [batch_size,set_length,set_length].\n target12 (torch.Tensor): True matching indices such that a one hot\n embedding produces the permutation matrix for set1 vs set2.\n target21 (torch.Tensor): True matching indices such that a one hot\n embedding produces the permutation matrix for set2 vs set1.\n\n Returns:\n torch.Tensor: The scalar loss value.\n \"\"\"\n ce_loss = self.crossentropy_l2(predictions, target12, target21)\n true_mask21 = F.one_hot(target21).float()\n row_constraint = F.log_softmax(predictions \/ self.temp, dim=2)\n similarity = self.similarity(row_constraint, true_mask21)\n return ce_loss + similarity","code_tokens":"","url":560885} +{"project_name":"ivanmontero\/autobot","file_name":"convert_graph_to_onnx.py","full_name":"infer_shapes","func_name":"infer_shapes","docstring":"Attempt to infer the static vs dynamic axes for each input and output tensors for a specific model.","docstring_tokens":"","code":"def infer_shapes(nlp: Pipeline, framework: str) -> Tuple[List[str], List[str], Dict, BatchEncoding]:\n \"\"\"\n Attempt to infer the static vs dynamic axes for each input and output tensors for a specific model.\n Args:\n nlp: The pipeline object holding the model to be exported\n framework: The framework identifier to dispatch to the correct inference scheme (pt\/tf)\n\n Returns:\n - List of the inferred input variable names\n - List of the inferred output variable names\n - Dictionary with input\/output variables names as key and shape tensor as value\n - a BatchEncoding reference which was used to infer all the above information\n \"\"\"\n\n def build_shape_dict(name: str, tensor, is_input: bool, seq_len: int):\n if isinstance(tensor, (tuple, list)):\n return [build_shape_dict(name, t, is_input, seq_len) for t in tensor]\n else:\n axes = {[axis for (axis, numel) in enumerate(tensor.shape) if numel == 1][0]: 'batch'}\n if is_input:\n if len(tensor.shape) == 2:\n axes[1] = 'sequence'\n else:\n raise ValueError(f'Unable to infer tensor axes ({len(tensor.shape)})')\n else:\n seq_axes = [dim for (dim, shape) in enumerate(tensor.shape) if shape == seq_len]\n axes.update({dim: 'sequence' for dim in seq_axes})\n print(f\"Found {('input' if is_input else 'output')} {name} with shape: {axes}\")\n return axes\n tokens = nlp.tokenizer('This is a sample output', return_tensors=framework)\n seq_len = tokens.input_ids.shape[-1]\n outputs = nlp.model(**tokens) if framework == 'pt' else nlp.model(tokens)\n if isinstance(outputs, ModelOutput):\n outputs = outputs.to_tuple()\n if not isinstance(outputs, (list, tuple)):\n outputs = (outputs,)\n input_vars = list(tokens.keys())\n input_dynamic_axes = {k: build_shape_dict(k, v, True, seq_len) for (k, v) in tokens.items()}\n outputs_flat = []\n for output in outputs:\n if isinstance(output, (tuple, list)):\n outputs_flat.extend(output)\n else:\n outputs_flat.append(output)\n output_names = [f'output_{i}' for i in range(len(outputs_flat))]\n output_dynamic_axes = {k: build_shape_dict(k, v, False, seq_len) for (k, v) in zip(output_names, outputs_flat)}\n dynamic_axes = dict(input_dynamic_axes, **output_dynamic_axes)\n return (input_vars, output_names, dynamic_axes, tokens)","code_tokens":"","url":417811} +{"project_name":"GatorEducator\/GatorMiner","file_name":"visualization.py","full_name":"senti_circleplot","func_name":"senti_circleplot","docstring":"Circle plot for sentiment.","docstring_tokens":"","code":"def senti_circleplot(senti_df, student_id):\n \"\"\"Circle plot for sentiment.\"\"\"\n senti_circle = alt.Chart(senti_df).mark_point(size=100, fillOpacity=0.7).encode(alt.X(student_id), alt.Y(cts.SENTI), alt.Color(cts.ASSIGNMENT, legend=alt.Legend(orient='left')), alt.Shape(cts.ASSIGNMENT, legend=None), tooltip=[alt.Tooltip(cts.SENTI, title='polarity'), alt.Tooltip(student_id, title='author'), alt.Tooltip(cts.POSITIVE, title='Positive words'), alt.Tooltip(cts.NEGATIVE, title='Negative words')]).interactive()\n return senti_circle","code_tokens":"","url":567445} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"index.py","full_name":"PackageIndex.check_credentials","func_name":"check_credentials","docstring":"Check that ``username`` and ``password`` have been set, and raise an exception if not.","docstring_tokens":"","code":"def check_credentials(self):\n \"\"\"\n Check that ``username`` and ``password`` have been set, and raise an\n exception if not.\n \"\"\"\n if self.username is None or self.password is None:\n raise DistlibException('username and password must be set')\n pm = HTTPPasswordMgr()\n (_, netloc, _, _, _, _) = urlparse(self.url)\n pm.add_password(self.realm, netloc, self.username, self.password)\n self.password_handler = HTTPBasicAuthHandler(pm)","code_tokens":"","url":134384} +{"project_name":"nilearn\/nilearn","file_name":"test_graph_net.py","full_name":"test_logistic_derivative_lipschitz_constant","func_name":"test_logistic_derivative_lipschitz_constant","docstring":"Test Lipschitz-continuity of the derivative of logistic loss.","docstring_tokens":"","code":"def test_logistic_derivative_lipschitz_constant():\n \"\"\"Test Lipschitz-continuity of the derivative of logistic loss.\"\"\"\n (X, y, w, mask, *_) = _make_data()\n rng = check_random_state(42)\n grad_weight = 0.208\n lipschitz_constant = _logistic_derivative_lipschitz_constant(X, mask, grad_weight)\n for _ in range(20):\n x_1 = rng.rand(w.shape[0] + 1) * rng.randint(1000)\n x_2 = rng.rand(w.shape[0] + 1) * rng.randint(1000)\n gradient_difference = linalg.norm(_logistic_data_loss_and_spatial_grad_derivative(X, y, x_1, mask, grad_weight) - _logistic_data_loss_and_spatial_grad_derivative(X, y, x_2, mask, grad_weight))\n point_difference = linalg.norm(x_1 - x_2)\n assert gradient_difference <= lipschitz_constant * point_difference","code_tokens":"","url":723721} +{"project_name":"mradaideh\/neorl","file_name":"classic.py","full_name":"schaffer","func_name":"schaffer","docstring":"Schaffer test objective function.","docstring_tokens":"","code":"def schaffer(individual):\n \"\"\"Schaffer test objective function.\n \"\"\"\n return sum(((x ** 2 + x1 ** 2) ** 0.25 * (sin(50 * (x ** 2 + x1 ** 2) ** 0.1) ** 2 + 1.0) for (x, x1) in zip(individual[:-1], individual[1:])))","code_tokens":"","url":735410} +{"project_name":"deepmind\/dm_control","file_name":"cheetah.py","full_name":"Physics.speed","func_name":"speed","docstring":"Returns the horizontal speed of the Cheetah.","docstring_tokens":"","code":"def speed(self):\n \"\"\"Returns the horizontal speed of the Cheetah.\"\"\"\n return self.named.data.sensordata['torso_subtreelinvel'][0]","code_tokens":"","url":165403} +{"project_name":"instadeepai\/jumanji","file_name":"utils_agent.py","full_name":"update_agent","func_name":"update_agent","docstring":"Update the attribute information of a specific agent.","docstring_tokens":"","code":"def update_agent(agents: Agent, agent_id: chex.Array, attr: str, value: Union[chex.Array, Position]) -> Agent:\n \"\"\"Update the attribute information of a specific agent.\n\n Args:\n agents: a pytree of either Agent type containing agent information.\n agent_id: unique ID identifying a specific agent.\n attr: the attribute to update, e.g. `direction`, or `is_requested`.\n value: the new value to which the attribute is to be set.\n\n Returns:\n the agent with the specified attribute updated to the given value.\n \"\"\"\n params = {attr: value}\n agent = tree_slice(agents, agent_id)\n agent = agent._replace(**params)\n agents: Agent = tree_add_element(agents, agent_id, agent)\n return agents","code_tokens":"","url":594481} +{"project_name":"alibaba-mmai-research\/HiCo","file_name":"meters.py","full_name":"EpicKitchenMeter.get_video_preds","func_name":"get_video_preds","docstring":"Returns the saved video predictions.","docstring_tokens":"","code":"def get_video_preds(self):\n \"\"\"\n Returns the saved video predictions.\n \"\"\"\n video_preds = {}\n if self.ensemble_method == 'sum':\n video_preds['verb_class'] = self.video_preds['verb_class'].sum(1)\n video_preds['noun_class'] = self.video_preds['noun_class'].sum(1)\n video_preds['action_class_ind_pred'] = self.video_preds['action_class_ind_pred'].sum(1)\n elif self.ensemble_method == 'max':\n video_preds['verb_class'] = self.video_preds['verb_class'].max(1)[0]\n video_preds['noun_class'] = self.video_preds['noun_class'].max(1)[0]\n video_preds['action_class_ind_pred'] = self.video_preds['action_class_ind_pred'].max(1)[0]\n return video_preds","code_tokens":"","url":206217} +{"project_name":"enlite-ai\/maze","file_name":"renderer_args.py","full_name":"OptionsArrayArg.create_widget","func_name":"create_widget","docstring":"Build a dropdown widget.","docstring_tokens":"","code":"def create_widget(self):\n \"\"\"Build a dropdown widget.\"\"\"\n import ipywidgets as widgets\n return widgets.Dropdown(description=self.title, options=self.options)","code_tokens":"","url":646736} +{"project_name":"tensorly\/quantum","file_name":"cirq_ops_test.py","full_name":"CirqAnalyticalExpectationTest.test_get_cirq_analytical_expectation_op","func_name":"test_get_cirq_analytical_expectation_op","docstring":"Input check the wrapper for the cirq analytical expectation op.","docstring_tokens":"","code":"def test_get_cirq_analytical_expectation_op(self):\n \"\"\"Input check the wrapper for the cirq analytical expectation op.\"\"\"\n with self.assertRaisesRegex(TypeError, 'cirq.sim.simulator.SimulatesExpectationValues.'):\n cirq_ops._get_cirq_analytical_expectation('junk')\n cirq_ops._get_cirq_analytical_expectation()\n cirq_ops._get_cirq_analytical_expectation(cirq.Simulator())\n cirq_ops._get_cirq_analytical_expectation(cirq.DensityMatrixSimulator())","code_tokens":"","url":834636} +{"project_name":"microsoft\/fastseq","file_name":"file_utils.py","full_name":"wget","func_name":"wget","docstring":"Download the file from the url to the target file.","docstring_tokens":"","code":"def wget(url, target_file_handling):\n \"\"\"Download the file from the url to the target file.\n\n Args:\n url (str): the url to download the data.\n target_file_handling (file object): A file handling for writing the\n data.\n \"\"\"\n response = requests.get(url, stream=True)\n if response.status_code == 416:\n raise ValueError('Range not satisfiable when loading {}'.format(url))\n content_length = response.headers.get('Content-Length')\n total = int(content_length) if content_length is not None else None\n progress = tqdm(unit='B', unit_scale=True, total=total, initial=0, desc='Downloading')\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n progress.update(len(chunk))\n target_file_handling.write(chunk)\n progress.close()","code_tokens":"","url":559893} +{"project_name":"srai-lab\/srai","file_name":"h3_neighbourhood.py","full_name":"H3Neighbourhood.get_neighbours","func_name":"get_neighbours","docstring":"Get the direct neighbours of an H3 region using its index.","docstring_tokens":"","code":"def get_neighbours(self, index: str, include_center: Optional[bool]=None) -> Set[str]:\n \"\"\"\n Get the direct neighbours of an H3 region using its index.\n\n Args:\n index (str): H3 index of the region.\n include_center (Optional[bool]): Whether to include the region itself in the neighbours.\n If None, the value set in __init__ is used. Defaults to None.\n\n Returns:\n Set[str]: Indexes of the neighbours.\n \"\"\"\n return self.get_neighbours_up_to_distance(index, 1, include_center)","code_tokens":"","url":371901} +{"project_name":"Eric3911\/OpenAGI","file_name":"pytorch_utils.py","full_name":"forward","func_name":"forward","docstring":"Forward data to a model.","docstring_tokens":"","code":"def forward(model, generator, return_input=False, return_target=False):\n \"\"\"Forward data to a model.\n \n Args: \n model: object\n generator: object\n return_input: bool\n return_target: bool\n\n Returns:\n audio_name: (audios_num,)\n clipwise_output: (audios_num, classes_num)\n (ifexist) segmentwise_output: (audios_num, segments_num, classes_num)\n (ifexist) framewise_output: (audios_num, frames_num, classes_num)\n (optional) return_input: (audios_num, segment_samples)\n (optional) return_target: (audios_num, classes_num)\n \"\"\"\n output_dict = {}\n device = next(model.parameters()).device\n time1 = time.time()\n for (n, batch_data_dict) in enumerate(generator):\n print(n)\n batch_waveform = move_data_to_device(batch_data_dict['waveform'], device)\n with torch.no_grad():\n model.eval()\n batch_output = model(batch_waveform)\n append_to_dict(output_dict, 'audio_name', batch_data_dict['audio_name'])\n append_to_dict(output_dict, 'clipwise_output', batch_output['clipwise_output'].data.cpu().numpy())\n if 'segmentwise_output' in batch_output.keys():\n append_to_dict(output_dict, 'segmentwise_output', batch_output['segmentwise_output'].data.cpu().numpy())\n if 'framewise_output' in batch_output.keys():\n append_to_dict(output_dict, 'framewise_output', batch_output['framewise_output'].data.cpu().numpy())\n if return_input:\n append_to_dict(output_dict, 'waveform', batch_data_dict['waveform'])\n if return_target:\n if 'target' in batch_data_dict.keys():\n append_to_dict(output_dict, 'target', batch_data_dict['target'])\n if n % 10 == 0:\n print(' --- Inference time: {:.3f} s \/ 10 iterations ---'.format(time.time() - time1))\n time1 = time.time()\n for key in output_dict.keys():\n output_dict[key] = np.concatenate(output_dict[key], axis=0)\n return output_dict","code_tokens":"","url":250476} +{"project_name":"pandeyankit83\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"exporter.py","full_name":"freeze_graph_with_def_protos","func_name":"freeze_graph_with_def_protos","docstring":"Converts all variables in a graph and checkpoint into constants.","docstring_tokens":"","code":"def freeze_graph_with_def_protos(input_graph_def, input_saver_def, input_checkpoint, output_node_names, restore_op_name, filename_tensor_name, clear_devices, initializer_nodes, optimize_graph=True, variable_names_blacklist=''):\n \"\"\"Converts all variables in a graph and checkpoint into constants.\"\"\"\n del restore_op_name, filename_tensor_name\n if not saver_lib.checkpoint_exists(input_checkpoint):\n raise ValueError('Input checkpoint \"' + input_checkpoint + '\" does not exist!')\n if not output_node_names:\n raise ValueError('You must supply the name of a node to --output_node_names.')\n if clear_devices:\n for node in input_graph_def.node:\n node.device = ''\n with tf.Graph().as_default():\n tf.import_graph_def(input_graph_def, name='')\n if optimize_graph:\n logging.info('Graph Rewriter optimizations enabled')\n rewrite_options = rewriter_config_pb2.RewriterConfig(layout_optimizer=rewriter_config_pb2.RewriterConfig.ON)\n rewrite_options.optimizers.append('pruning')\n rewrite_options.optimizers.append('constfold')\n rewrite_options.optimizers.append('layout')\n graph_options = tf.GraphOptions(rewrite_options=rewrite_options, infer_shapes=True)\n else:\n logging.info('Graph Rewriter optimizations disabled')\n graph_options = tf.GraphOptions()\n config = tf.ConfigProto(graph_options=graph_options)\n with session.Session(config=config) as sess:\n if input_saver_def:\n saver = saver_lib.Saver(saver_def=input_saver_def)\n saver.restore(sess, input_checkpoint)\n else:\n var_list = {}\n reader = pywrap_tensorflow.NewCheckpointReader(input_checkpoint)\n var_to_shape_map = reader.get_variable_to_shape_map()\n for key in var_to_shape_map:\n try:\n tensor = sess.graph.get_tensor_by_name(key + ':0')\n except KeyError:\n continue\n var_list[key] = tensor\n saver = saver_lib.Saver(var_list=var_list)\n saver.restore(sess, input_checkpoint)\n if initializer_nodes:\n sess.run(initializer_nodes)\n variable_names_blacklist = variable_names_blacklist.split(',') if variable_names_blacklist else None\n output_graph_def = graph_util.convert_variables_to_constants(sess, input_graph_def, output_node_names.split(','), variable_names_blacklist=variable_names_blacklist)\n return output_graph_def","code_tokens":"","url":56621} +{"project_name":"morpheus-project\/morpheus","file_name":"data_helper.py","full_name":"get_expected_morpheus_output","func_name":"get_expected_morpheus_output","docstring":"Gets the expected morpheus outputs for testing.","docstring_tokens":"","code":"def get_expected_morpheus_output(out_type='rank_vote'):\n \"\"\"Gets the expected morpheus outputs for testing.\"\"\"\n rank_vote_spheroid = '1nlGqibesE1LnEEif0oj-RO8xR4qNAFnP'\n rank_vote_disk = '1btsoZZJu9qWkVn0rzIK9emgdMe6mMcHS'\n rank_vote_irregular = '1qtXphVp7VflFBDWFjn6AJdvI1j3sN4KR'\n rank_vote_point_source = '16bFNlZvD_EmAMSpCU-DZ_Shq3FMpXgp3'\n rank_vote_background = '1xp6NC00T3JykdOwz0c8EFeJG0vdsThSW'\n rank_vote_n = '1I5IasDPGyDmMaXN4NCwLh27X_OuxYiPv'\n mean_spheroid = '1kXpXJTwHyAcXkC7LTLi0J8kYtViLt6eo'\n var_spheroid = '1WJ9sphwkUM-fG2XOLjDbK6cQ7akjdP_N'\n mean_disk = '1c9Sbp5IeVIosNPVIbigKfFK9gHpCR7QW'\n var_disk = '16MW0-w22827qGeHchUQd38C3FQD7WUmx'\n mean_irregular = '1RRZ9pysoJRBA_SBkfxIU625Wydo740I-'\n var_irregular = '1smaHNzdPv-FzKAn0LhalakSi5e56hx75'\n mean_point_source = '1PQUy7hNziP0koQDOR9BHk-lhz0WbqA6s'\n var_point_source = '1vdrmyrT0Io2XvhL3FCpKOHSWzQ7vlb9U'\n mean_background = '18Vi6IQHyWbd5v9BBk9Ak34V5XHQt4KtI'\n var_background = '1lCfccgqS9kbynfZBCkEl-ED7mMUtGhN5'\n if out_type == 'rank_vote':\n return {'spheroid': get_fits(rank_vote_spheroid), 'disk': get_fits(rank_vote_disk), 'irregular': get_fits(rank_vote_irregular), 'point_source': get_fits(rank_vote_point_source), 'background': get_fits(rank_vote_background), 'n': get_fits(rank_vote_n)}\n else:\n return {'spheroid_mean': get_fits(mean_spheroid), 'spheroid_var': get_fits(var_spheroid), 'disk_mean': get_fits(mean_disk), 'disk_var': get_fits(var_disk), 'irregular_mean': get_fits(mean_irregular), 'irregular_var': get_fits(var_irregular), 'point_source_mean': get_fits(mean_point_source), 'point_source_var': get_fits(var_point_source), 'background_mean': get_fits(mean_background), 'background_var': get_fits(var_background), 'n': get_fits(rank_vote_n)}","code_tokens":"","url":656000} +{"project_name":"google\/deepvariant","file_name":"utils.py","full_name":"read_range","func_name":"read_range","docstring":"Creates a Range proto from the alignment of Read.","docstring_tokens":"","code":"def read_range(read):\n \"\"\"Creates a Range proto from the alignment of Read.\n\n Args:\n read: nucleus.genomics.v1.Read. The read to calculate the range for.\n\n Returns:\n A nucleus.genomics.v1.Range for read.\n \"\"\"\n range_pb = range_pb2.Range()\n utils_cpp.read_range(read, range_pb)\n return range_pb","code_tokens":"","url":540686} +{"project_name":"PacktPublishing\/Hands-On-Artificial--for-Banking","file_name":"datetimelike.py","full_name":"DatetimeLikeArrayMixin.freq","func_name":"freq","docstring":"Return the frequency object if it is set, otherwise None.","docstring_tokens":"","code":"@property\ndef freq(self):\n \"\"\"\n Return the frequency object if it is set, otherwise None.\n \"\"\"\n return self._freq","code_tokens":"","url":236302} +{"project_name":"salesforce\/CodeRL","file_name":"training_args.py","full_name":"TrainingArguments.get_warmup_steps","func_name":"get_warmup_steps","docstring":"Get number of steps used for a linear warmup.","docstring_tokens":"","code":"def get_warmup_steps(self, num_training_steps: int):\n \"\"\"\n Get number of steps used for a linear warmup.\n \"\"\"\n warmup_steps = self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio)\n return warmup_steps","code_tokens":"","url":494228} +{"project_name":"deephyper\/deephyper","file_name":"test_utils.py","full_name":"test_dict_list_space_representation","func_name":"test_dict_list_space_representation","docstring":"Tests whether the conversion of the dictionary and list representation of a point from a search space works properly.","docstring_tokens":"","code":"@pytest.mark.hps\ndef test_dict_list_space_representation():\n \"\"\"\n Tests whether the conversion of the dictionary and list representation\n of a point from a search space works properly.\n \"\"\"\n chef_space = {'Cooking time': (0, 1200), 'Main ingredient': ['cheese', 'cherimoya', 'chicken', 'chard', 'chocolate', 'chicory'], 'Secondary ingredient': ['love', 'passion', 'dedication'], 'Cooking temperature': (-273.16, 10000.0)}\n opt = Optimizer(dimensions=dimensions_aslist(chef_space))\n point = opt.ask()\n assert_equal(point, point_aslist(chef_space, point_asdict(chef_space, point)))","code_tokens":"","url":521110} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.ntuple","func_name":"ntuple","docstring":"number of tuple custom fields.","docstring_tokens":"","code":"@property\ndef ntuple(self):\n \"\"\"number of tuple custom fields.\"\"\"\n return self._ptr.contents.ntuple","code_tokens":"","url":440212} +{"project_name":"scikit-learn\/scikit-learn","file_name":"plot_prediction_latency.py","full_name":"bulk_benchmark_estimator","func_name":"bulk_benchmark_estimator","docstring":"Measure runtime prediction of the whole input.","docstring_tokens":"","code":"def bulk_benchmark_estimator(estimator, X_test, n_bulk_repeats, verbose):\n \"\"\"Measure runtime prediction of the whole input.\"\"\"\n n_instances = X_test.shape[0]\n runtimes = np.zeros(n_bulk_repeats, dtype=float)\n for i in range(n_bulk_repeats):\n start = time.time()\n estimator.predict(X_test)\n runtimes[i] = time.time() - start\n runtimes = np.array(list(map(lambda x: x \/ float(n_instances), runtimes)))\n if verbose:\n print('bulk_benchmark runtimes:', min(runtimes), np.percentile(runtimes, 50), max(runtimes))\n return runtimes","code_tokens":"","url":848147} +{"project_name":"google-research\/scenic","file_name":"transforms.py","full_name":"get_padding_value","func_name":"get_padding_value","docstring":"Helper function for determing datatype-appropriate padding values.","docstring_tokens":"","code":"def get_padding_value(dtype):\n \"\"\"Helper function for determing datatype-appropriate padding values.\"\"\"\n if dtype in (tf.int32, tf.int64):\n return PADDING_VALUE\n elif dtype == tf.string:\n return PADDING_VALUE_STR\n return None","code_tokens":"","url":847246} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"vartree.py","full_name":"VariableTree.get_req_default","func_name":"get_req_default","docstring":"Returns a list of all inputs that are required but still have their default value.","docstring_tokens":"","code":"@rbac(('owner', 'user'))\ndef get_req_default(self, vt_required=None):\n \"\"\"Returns a list of all inputs that are required but still have\n their default value.\n \"\"\"\n req = []\n if vt_required:\n req_test = [True, False, None]\n else:\n req_test = [True]\n for (name, trait) in self.traits(type=not_event).items():\n obj = getattr(self, name)\n if obj is self.parent:\n continue\n if is_instance(obj, VariableTree):\n req.extend(['.'.join((self.name, n)) for n in obj.get_req_default(vt_required)])\n elif trait.required in req_test:\n try:\n trait = trait.trait_type\n except:\n unset = obj == trait.default\n else:\n unset = obj == trait.default_value\n if not isinstance(unset, bool):\n try:\n unset = unset.all()\n except:\n pass\n if unset:\n req.append('.'.join((self.name, name)))\n return req","code_tokens":"","url":276141} +{"project_name":"kornia\/kornia","file_name":"test_draw.py","full_name":"TestDrawLine.test_draw_line_with_big_coordinates","func_name":"test_draw_line_with_big_coordinates","docstring":"Test drawing a line with big coordinates.","docstring_tokens":"","code":"def test_draw_line_with_big_coordinates(self, dtype, device):\n \"\"\"Test drawing a line with big coordinates.\"\"\"\n img = torch.zeros(1, 500, 500, dtype=dtype, device=device)\n img = draw_line(img, torch.tensor([200, 200]), torch.tensor([400, 200]), torch.tensor([255]))\n img_mask = torch.zeros(1, 500, 500, dtype=dtype, device=device)\n img_mask[:, 200, 200:401] = 255\n assert_close(img, img_mask)","code_tokens":"","url":622354} +{"project_name":"rudranil723\/mini-main","file_name":"driver.py","full_name":"DriverProxy.runAndWait","func_name":"runAndWait","docstring":"Called by the engine to start an event loop, process all commands in the queue at the start of the loop, and then exit the loop.","docstring_tokens":"","code":"def runAndWait(self):\n \"\"\"\n Called by the engine to start an event loop, process all commands in\n the queue at the start of the loop, and then exit the loop.\n \"\"\"\n self._push(self._engine.endLoop, tuple())\n self._driver.startLoop()","code_tokens":"","url":269716} +{"project_name":"deepmind\/acme","file_name":"core.py","full_name":"VariableSource.get_variables","func_name":"get_variables","docstring":"Return the named variables as a collection of (nested) numpy arrays.","docstring_tokens":"","code":"@abc.abstractmethod\ndef get_variables(self, names: Sequence[str]) -> List[types.NestedArray]:\n \"\"\"Return the named variables as a collection of (nested) numpy arrays.\n\n Args:\n names: args where each name is a string identifying a predefined subset of\n the variables.\n\n Returns:\n A list of (nested) numpy arrays `variables` such that `variables[i]`\n corresponds to the collection named by `names[i]`.\n \"\"\"","code_tokens":"","url":8006} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"_trustregion.py","full_name":"BaseQuadraticSubproblem.fun","func_name":"fun","docstring":"Value of objective function at current iteration.","docstring_tokens":"","code":"@property\ndef fun(self):\n \"\"\"Value of objective function at current iteration.\"\"\"\n if self._f is None:\n self._f = self._fun(self._x)\n return self._f","code_tokens":"","url":99776} +{"project_name":"jbeomlee93\/BBAM","file_name":"BBAM_utils.py","full_name":"MaskGenerator.to","func_name":"to","docstring":"Switch to another device.","docstring_tokens":"","code":"def to(self, dev):\n \"\"\"Switch to another device.\n Args:\n dev: PyTorch device.\n Returns:\n MaskGenerator: self.\n \"\"\"\n self.weight = self.weight.to(dev)\n return self","code_tokens":"","url":423169} +{"project_name":"tonybeltramelli\/Graphics-And-Vision","file_name":"Pattern.py","full_name":"Pattern.FindCirclesGrid","func_name":"FindCirclesGrid","docstring":"Finds centers in the grid of circles using an asymmetric pattern.","docstring_tokens":"","code":"def FindCirclesGrid(self, image):\n \"\"\"Finds centers in the grid of circles using an asymmetric pattern.\"\"\"\n gray = image.copy()\n flags = cv2.CALIB_CB_ASYMMETRIC_GRID\n (retval, corners) = cv2.findCirclesGrid(gray, self.Size, flags=flags)\n del gray\n return corners","code_tokens":"","url":580647} +{"project_name":"nmndeep\/robust-segmentation","file_name":"attacker.py","full_name":"masked_margin_loss","func_name":"masked_margin_loss","docstring":"Margin loss of only correctly classified pixels.","docstring_tokens":"","code":"def masked_margin_loss(pred, target):\n \"\"\"Margin loss of only correctly classified pixels.\"\"\"\n pred = pred \/ (pred ** 2).sum(1, keepdim=True).sqrt().detach()\n loss = margin_loss(pred, target)\n mask = pred.max(1)[1] == target\n loss = mask.float().detach() * loss\n return loss.view(pred.shape[0], -1).mean(-1)","code_tokens":"","url":826202} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"test_lobpcg.py","full_name":"test_regression","func_name":"test_regression","docstring":"Check the eigenvalue of the identity matrix is one.","docstring_tokens":"","code":"def test_regression():\n \"\"\"Check the eigenvalue of the identity matrix is one.\n \"\"\"\n n = 10\n X = np.ones((n, 1))\n A = np.identity(n)\n (w, _) = lobpcg(A, X)\n assert_allclose(w, [1])","code_tokens":"","url":100181} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"test_segment_anything.py","full_name":"TestSegmentAnything.test_load_checkpoint_with_url","func_name":"test_load_checkpoint_with_url","docstring":"Test load_checkpoint with url.","docstring_tokens":"","code":"@e2e_pytest_unit\ndef test_load_checkpoint_with_url(self, mocker):\n \"\"\"Test load_checkpoint with url.\"\"\"\n mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.freeze_networks')\n mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.set_metrics')\n mocker_load_state_dict_from_url = mocker.patch('torch.hub.load_state_dict_from_url', return_value=OrderedDict())\n mocker_load_state_dict = mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.load_state_dict')\n config = self.base_config.copy()\n config.model.update(dict(checkpoint='http:\/\/checkpoint'))\n sam = SegmentAnything(config, state_dict=None)\n mocker_load_state_dict_from_url.assert_called_once()\n mocker_load_state_dict.assert_called_once()","code_tokens":"","url":919391} +{"project_name":"triaquae\/triaquae","file_name":"decorators.py","full_name":"LoginRequiredTestCase.testCallable","func_name":"testCallable","docstring":"Check that login_required is assignable to callable objects.","docstring_tokens":"","code":"def testCallable(self):\n \"\"\"\n Check that login_required is assignable to callable objects.\n \"\"\"\n\n class CallableView(object):\n\n def __call__(self, *args, **kwargs):\n pass\n login_required(CallableView())","code_tokens":"","url":357131} +{"project_name":"RasaHQ\/rasa","file_name":"trackers.py","full_name":"DialogueStateTracker.update_with_events","func_name":"update_with_events","docstring":"Adds multiple events to the tracker.","docstring_tokens":"","code":"def update_with_events(self, new_events: List[Event], domain: Optional[Domain], override_timestamp: bool=True) -> None:\n \"\"\"Adds multiple events to the tracker.\n\n Args:\n new_events: Events to apply.\n domain: The current model's domain.\n override_timestamp: If `True` refresh all timestamps of the events. As the\n events are usually created at some earlier point, this makes sure that\n all new events come after any current tracker events.\n \"\"\"\n for e in new_events:\n if override_timestamp:\n e.timestamp = time.time()\n self.update(e, domain)","code_tokens":"","url":837549} +{"project_name":"Ixiaohuihuihui\/AO2-DETR","file_name":"enn.py","full_name":"build_enn_divide_feature","func_name":"build_enn_divide_feature","docstring":"build a enn regular feature map with the specified number of channels divided by N.","docstring_tokens":"","code":"def build_enn_divide_feature(planes):\n \"\"\"build a enn regular feature map with the specified number of channels\n divided by N.\"\"\"\n assert gspace.fibergroup.order() > 0\n N = gspace.fibergroup.order()\n planes = planes \/ N\n planes = int(planes)\n return enn.FieldType(gspace, [gspace.regular_repr] * planes)","code_tokens":"","url":401602} +{"project_name":"Deeplite\/deeplite-torch-zoo","file_name":"utils.py","full_name":"resample_segments","func_name":"resample_segments","docstring":"Inputs a list of segments (n,2) and returns a list of segments (n,2) up-sampled to n points each.","docstring_tokens":"","code":"def resample_segments(segments, n=1000):\n \"\"\"\n Inputs a list of segments (n,2) and returns a list of segments (n,2) up-sampled to n points each.\n\n Args:\n segments (list): a list of (n,2) arrays, where n is the number of points in the segment.\n n (int): number of points to resample the segment to. Defaults to 1000\n\n Returns:\n segments (list): the resampled segments.\n \"\"\"\n for (i, s) in enumerate(segments):\n s = np.concatenate((s, s[0:1, :]), axis=0)\n x = np.linspace(0, len(s) - 1, n)\n xp = np.arange(len(s))\n segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)], dtype=np.float32).reshape(2, -1).T\n return segments","code_tokens":"","url":538849} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"settings.py","full_name":"Settings.simple_ids","func_name":"simple_ids","docstring":"Set whether Bokeh should generate simple numeric model IDs.","docstring_tokens":"","code":"def simple_ids(self, default=None):\n \"\"\" Set whether Bokeh should generate simple numeric model IDs.\n\n \"\"\"\n return self._get_bool('SIMPLE_IDS', default, True)","code_tokens":"","url":977080} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"baseline.py","full_name":"Baseline.get_values","func_name":"get_values","docstring":"Get value estimates given input.","docstring_tokens":"","code":"def get_values(self, all_obs, all_actions, internal_policy_states, policy_logits):\n \"\"\"Get value estimates given input.\"\"\"\n batch_size = tf.shape(all_obs[0])[1]\n time_length = tf.shape(all_obs[0])[0]\n (time_step, reshaped_obs, reshaped_prev_act, reshaped_internal_policy_states, reshaped_policy_logits) = self.reshape_batched_inputs(all_obs, all_actions, internal_policy_states, policy_logits)\n (input_dim, inputs) = self.get_inputs(time_step, reshaped_obs, reshaped_prev_act, reshaped_internal_policy_states)\n for depth in xrange(self.n_hidden_layers):\n with tf.variable_scope('value_layer%d' % depth):\n w = tf.get_variable('w', [input_dim, self.hidden_dim])\n inputs = tf.nn.tanh(tf.matmul(inputs, w))\n input_dim = self.hidden_dim\n w_v = tf.get_variable('w_v', [input_dim, 1], initializer=self.matrix_init)\n values = tf.matmul(inputs, w_v)\n values = tf.reshape(values, [time_length, batch_size])\n inputs = inputs[:-batch_size]\n return (values, inputs, w_v)","code_tokens":"","url":26015} +{"project_name":"RLE-Foundation\/rllte","file_name":"off_policy_double_qnetwork.py","full_name":"OffPolicyDoubleQNetwork.freeze","func_name":"freeze","docstring":"Freeze all the elements like `encoder` and `dist`.","docstring_tokens":"","code":"def freeze(self, encoder: nn.Module, dist: Distribution) -> None:\n \"\"\"Freeze all the elements like `encoder` and `dist`.\n\n Args:\n encoder (nn.Module): Encoder network.\n dist (Distribution): Distribution class.\n\n Returns:\n None.\n \"\"\"\n assert encoder is not None, 'Encoder should not be None!'\n self.encoder = encoder\n self.apply(self.init_fn)\n self.qnet_target.load_state_dict(self.qnet.state_dict())\n self._optimizers['opt'] = self.opt_class(self.parameters(), **self.opt_kwargs)","code_tokens":"","url":333315} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"_params_loader.py","full_name":"ParamsLoader.get_parameter_args","func_name":"get_parameter_args","docstring":"Loads the 'params' argument for the FeatureProcessor.","docstring_tokens":"","code":"def get_parameter_args(self, fp_config: FeatureProcessorConfig) -> Dict[str, Union[str, Dict]]:\n \"\"\"Loads the 'params' argument for the FeatureProcessor.\n\n Args:\n fp_config (FeatureProcessorConfig): The configuration values for the\n feature_processor decorator.\n\n Returns:\n Dict[str, Union[str, Dict]]: A dictionary that contains both user provided\n parameters (feature_processor argument) and system parameters.\n \"\"\"\n return {self._PARAMS_KEY: {**(fp_config.parameters or {}), **self.system_parameters_arg_provider.get_system_args()}}","code_tokens":"","url":830086} +{"project_name":"maiziezhoulab\/RNN_BrainMaturation","file_name":"tools.py","full_name":"find_model","func_name":"find_model","docstring":"Find one model that satisfies hyperparameters.","docstring_tokens":"","code":"def find_model(root_dir, hp_target, perf_min=None):\n \"\"\"Find one model that satisfies hyperparameters.\n\n Args:\n root_dir: root directory\n hp_target: dictionary of hyperparameters\n perf_min: float or None. If not None, minimum performance to be chosen\n\n Returns:\n d: model directory\n \"\"\"\n model_dirs = find_all_models(root_dir, hp_target)\n if perf_min is not None:\n model_dirs = select_by_perf(model_dirs, perf_min)\n if not model_dirs:\n print('Model not found')\n return (None, None)\n d = model_dirs[0]\n hp = load_hp(d)\n log = load_log(d)\n if log['perf_min'][-1] < hp['target_perf']:\n print('Warning: this network perform {:0.2f}, not reaching target\\n performance {:0.2f}.'.format(log['perf_min'][-1], hp['target_perf']))\n return d","code_tokens":"","url":325537} +{"project_name":"tjfontaine\/linode-python","file_name":"api.py","full_name":"Api.linode_ip_list","func_name":"linode_ip_list","docstring":"Lists a Linode's IP addresses.","docstring_tokens":"","code":"@__api_request(optional=['IPAddressID', 'LinodeID'], returns=[{u'ISPUBLIC': '0 or 1', u'IPADDRESS': '192.168.100.1', u'IPADDRESSID': 'IP address ID', u'LINODEID': 'Linode ID', u'RDNS_NAME': 'reverse.dns.name.here'}])\ndef linode_ip_list(self, request):\n \"\"\"Lists a Linode's IP addresses.\"\"\"\n pass","code_tokens":"","url":216834} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"jsontags.py","full_name":"register_tag","func_name":"register_tag","docstring":"Decorates a class to register it's json tag.","docstring_tokens":"","code":"def register_tag(cls):\n \"\"\"\n Decorates a class to register it's json tag.\n \"\"\"\n json_tags[TAG_PREFIX + getattr(cls, 'json_tag')] = cls\n return cls","code_tokens":"","url":217312} +{"project_name":"Eric3911\/OpenAGI","file_name":"test_utils.py","full_name":"TestPreprocessingUtils.test_get_full_path_invalid_type","func_name":"test_get_full_path_invalid_type","docstring":"Make sure exceptions are raised when audio_file is not a string or a list of strings.","docstring_tokens":"","code":"@pytest.mark.unit\ndef test_get_full_path_invalid_type(self):\n \"\"\"Make sure exceptions are raised when audio_file is not a string or a list of strings.\n \"\"\"\n with pytest.raises(ValueError, match='Unexpected audio_file type'):\n get_full_path(1)\n with pytest.raises(ValueError, match='Unexpected audio_file type'):\n get_full_path(('a', 'b', 'c'))\n with pytest.raises(ValueError, match='Unexpected audio_file type'):\n get_full_path({'a': 1, 'b': 2, 'c': 3})\n with pytest.raises(ValueError, match='Unexpected audio_file type'):\n get_full_path([1, 2, 3])","code_tokens":"","url":274412} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"mailbox.py","full_name":"MH.set_sequences","func_name":"set_sequences","docstring":"Set sequences using the given name-to-key-list dictionary.","docstring_tokens":"","code":"def set_sequences(self, sequences):\n \"\"\"Set sequences using the given name-to-key-list dictionary.\"\"\"\n f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII')\n try:\n os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))\n for (name, keys) in sequences.items():\n if len(keys) == 0:\n continue\n f.write(name + ':')\n prev = None\n completing = False\n for key in sorted(set(keys)):\n if key - 1 == prev:\n if not completing:\n completing = True\n f.write('-')\n elif completing:\n completing = False\n f.write('%s %s' % (prev, key))\n else:\n f.write(' %s' % key)\n prev = key\n if completing:\n f.write(str(prev) + '\\n')\n else:\n f.write('\\n')\n finally:\n _sync_close(f)","code_tokens":"","url":280763} +{"project_name":"wandb\/wandb","file_name":"test_agent.py","full_name":"test_thread_finish_no_run","func_name":"test_thread_finish_no_run","docstring":"Test that we fail RQI when the job exits 0 but there is no run.","docstring_tokens":"","code":"def test_thread_finish_no_run(mocker):\n \"\"\"Test that we fail RQI when the job exits 0 but there is no run.\"\"\"\n _setup_thread_finish(mocker)\n mock_config = {'entity': 'test-entity', 'project': 'test-project'}\n mocker.api.get_run_info.return_value = None\n agent = LaunchAgent(api=mocker.api, config=mock_config)\n mock_saver = MagicMock()\n job = JobAndRunStatusTracker('run_queue_item_id', 'test-queue', mock_saver, run=MagicMock())\n job.run_id = 'test_run_id'\n job.project = MagicMock()\n job.completed_status = 'finished'\n agent._jobs = {'thread_1': job}\n mocker.patch('wandb.sdk.launch.agent.agent.RUN_INFO_GRACE_PERIOD', 0)\n agent.finish_thread_id('thread_1')\n assert mocker.api.fail_run_queue_item.called\n assert mocker.api.fail_run_queue_item.call_args[0][0] == 'run_queue_item_id'\n assert mocker.api.fail_run_queue_item.call_args[0][1] == 'The submitted job exited successfully but failed to call wandb.init'","code_tokens":"","url":941254} +{"project_name":"gugarosa\/nalp","file_name":"word2vec.py","full_name":"Word2vecEncoder.encode","func_name":"encode","docstring":"Encodes the data into a Word2Vec representation.","docstring_tokens":"","code":"def encode(self, tokens: List[str]) -> None:\n \"\"\"Encodes the data into a Word2Vec representation.\n\n Args:\n tokens: Tokens to be encoded.\n\n \"\"\"\n if not self.encoder:\n e = 'You need to call learn() prior to encode() method.'\n logger.error(e)\n raise RuntimeError(e)\n wv = self.encoder.wv\n encoded_tokens = np.zeros((len(tokens), self.encoder.vector_size))\n for (i, token) in enumerate(tokens):\n encoded_tokens[i, :] = wv[token]\n return encoded_tokens","code_tokens":"","url":651717} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"test_core.py","full_name":"TestMaskedArrayMethods.test_allany","func_name":"test_allany","docstring":"Checks the any\/all methods\/functions.","docstring_tokens":"","code":"def test_allany(self):\n \"\"\"Checks the any\/all methods\/functions.\"\"\"\n x = np.array([[0.13, 0.26, 0.9], [0.28, 0.33, 0.63], [0.31, 0.87, 0.7]])\n m = np.array([[True, False, False], [False, False, False], [True, True, False]], dtype=np.bool_)\n mx = masked_array(x, mask=m)\n xbig = np.array([[False, False, True], [False, False, True], [False, True, True]], dtype=np.bool_)\n mxbig = mx > 0.5\n mxsmall = mx < 0.5\n assert_(mxbig.all() == False)\n assert_(mxbig.any() == True)\n assert_equal(mxbig.all(0), [False, False, True])\n assert_equal(mxbig.all(1), [False, False, True])\n assert_equal(mxbig.any(0), [False, False, True])\n assert_equal(mxbig.any(1), [True, True, True])\n assert_(mxsmall.all() == False)\n assert_(mxsmall.any() == True)\n assert_equal(mxsmall.all(0), [True, True, False])\n assert_equal(mxsmall.all(1), [False, False, False])\n assert_equal(mxsmall.any(0), [True, True, False])\n assert_equal(mxsmall.any(1), [True, True, False])","code_tokens":"","url":531927} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"reader.py","full_name":"Reader.insert","func_name":"insert","docstring":"Insert 'text' at the insertion point.","docstring_tokens":"","code":"def insert(self, text):\n \"\"\"Insert 'text' at the insertion point.\"\"\"\n self.buffer[self.pos:self.pos] = list(text)\n self.pos += len(text)\n self.dirty = 1","code_tokens":"","url":377454} +{"project_name":"RasaHQ\/rasa","file_name":"run.py","full_name":"add_jwt_arguments","func_name":"add_jwt_arguments","docstring":"Adds arguments related to JWT authentication.","docstring_tokens":"","code":"def add_jwt_arguments(parser: argparse.ArgumentParser) -> None:\n \"\"\"Adds arguments related to JWT authentication.\n\n Args:\n parser: Argument parser.\n \"\"\"\n jwt_auth = parser.add_argument_group('JWT Authentication')\n jwt_auth.add_argument('--jwt-secret', type=str, default=os.getenv(JWT_SECRET_ENV), help='Public key for asymmetric JWT methods or shared secretfor symmetric methods. Please also make sure to use --jwt-method to select the method of the signature, otherwise this argument will be ignored.Note that this key is meant for securing the HTTP API.')\n jwt_auth.add_argument('--jwt-method', type=str, default=os.getenv(JWT_METHOD_ENV, DEFAULT_JWT_METHOD), help='Method used for the signature of the JWT authentication payload.')\n jwt_auth.add_argument('--jwt-private-key', type=str, default=os.getenv(JWT_PRIVATE_KEY_ENV), help='A private key used for generating web tokens, dependent upon which hashing algorithm is used. It must be used together with --jwt-secret for providing the public key.')","code_tokens":"","url":836656} +{"project_name":"deepmind\/acme","file_name":"utils.py","full_name":"PrefetchIterator.producer","func_name":"producer","docstring":"Enqueues items from `iterable` on a given thread.","docstring_tokens":"","code":"def producer(self):\n \"\"\"Enqueues items from `iterable` on a given thread.\"\"\"\n try:\n for item in self.iterable:\n if self.device:\n jax.device_put(item, self.device)\n self.buffer.put(item)\n except Exception as e:\n logging.exception('Error in producer thread for %s', self.iterable)\n self.producer_error.append(e)\n finally:\n self.buffer.put(self.end)","code_tokens":"","url":7811} +{"project_name":"DPerrySvendsen\/COS30002","file_name":"world.py","full_name":"World.transform_points","func_name":"transform_points","docstring":"Transform the given list of points, using the provided position, direction and scale, to object world space.","docstring_tokens":"","code":"def transform_points(self, points, pos, forward, side, scale):\n \"\"\" Transform the given list of points, using the provided position,\n direction and scale, to object world space. \"\"\"\n wld_pts = [pt.copy() for pt in points]\n mat = Matrix33()\n mat.scale_update(scale.x, scale.y)\n mat.rotate_by_vectors_update(forward, side)\n mat.translate_update(pos.x, pos.y)\n mat.transform_vector2d_list(wld_pts)\n return wld_pts","code_tokens":"","url":137339} +{"project_name":"famura\/SimuRLacra","file_name":"stochastic_action.py","full_name":"EpsGreedyExplStrat.train","func_name":"train","docstring":"Call PyTorch's eval function and set the re-activate every exploration.","docstring_tokens":"","code":"def train(self, mode=True):\n \"\"\"Call PyTorch's eval function and set the re-activate every exploration.\"\"\"\n super(Policy, self).train()\n self.eps = nn.Parameter(self._eps_old, requires_grad=True)\n self.distr_eps = Bernoulli(probs=self.eps.data)","code_tokens":"","url":883759} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"model.py","full_name":"Seq2Seq.decode","func_name":"decode","docstring":"Return probability distribution over words.","docstring_tokens":"","code":"def decode(self, logits):\n \"\"\"Return probability distribution over words.\"\"\"\n logits_reshape = logits.view(-1, self.trg_vocab_size)\n word_probs = F.softmax(logits_reshape)\n word_probs = word_probs.view(logits.size()[0], logits.size()[1], logits.size()[2])\n return word_probs","code_tokens":"","url":8888} +{"project_name":"tensorflow\/agents","file_name":"perfzero_benchmark.py","full_name":"PerfZeroBenchmark.build_metric","func_name":"build_metric","docstring":"Builds a dictionary representing the metric to record.","docstring_tokens":"","code":"def build_metric(self, name: str, value: Number, min_value: Optional[Number]=None, max_value: Optional[Number]=None):\n \"\"\"Builds a dictionary representing the metric to record.\n\n Args:\n name: Name of the metric.\n value: Value of the metric.\n min_value: Lowest acceptable value.\n max_value: Highest acceptable value.\n\n Returns:\n Dictionary representing the metric.\n \"\"\"\n metric = {'name': name, 'value': value}\n if min_value:\n metric['min_value'] = min_value\n if max_value:\n metric['max_value'] = max_value\n return metric","code_tokens":"","url":22627} +{"project_name":"hayd\/pep8radius","file_name":"vcs.py","full_name":"Git.parse_diff_filenames","func_name":"parse_diff_filenames","docstring":"Parse the output of filenames_diff_cmd.","docstring_tokens":"","code":"@staticmethod\ndef parse_diff_filenames(diff_files):\n \"\"\"Parse the output of filenames_diff_cmd.\"\"\"\n return diff_files.splitlines()","code_tokens":"","url":279762} +{"project_name":"sintel-dev\/Orion","file_name":"contextual.py","full_name":"contextual_recall","func_name":"contextual_recall","docstring":"Compute an recall score between the ground truth and the detected anomalies.","docstring_tokens":"","code":"def contextual_recall(expected, observed, data=None, start=None, end=None, weighted=True):\n \"\"\"Compute an recall score between the ground truth and the detected anomalies.\n\n Args:\n expected (DataFrame or list of tuples):\n Ground truth passed as a ``pandas.DataFrame`` or list containing\n two columns: start and stop.\n observed (DataFrame or list of tuples):\n Detected anomalies passed as a ``pandas.DataFrame`` or list containing\n two columns: start and stop.\n data (DataFrame):\n Original data, passed as a ``pandas.DataFrame`` containing timestamp.\n Used to extract start and end.\n start (int):\n Minimum timestamp of the original data.\n end (int):\n Maximum timestamp of the original data.\n weighted (boolean):\n Flag to represent which algorithm to use.\n If true use weighted segment algorithm, else use overlap segment.\n\n Returns:\n float:\n Recall score between the ground truth and detected anomalies.\n \"\"\"\n\n def _cm(x, y, z, w, f):\n return contextual_confusion_matrix(x, y, z, w, f, weighted)\n return _recall(expected, observed, data, start, end, _cm)","code_tokens":"","url":776632} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"live_render.py","full_name":"LiveRender.set_renderable","func_name":"set_renderable","docstring":"Set a new renderable.","docstring_tokens":"","code":"def set_renderable(self, renderable: RenderableType) -> None:\n \"\"\"Set a new renderable.\n\n Args:\n renderable (RenderableType): Any renderable object, including str.\n \"\"\"\n self.renderable = renderable","code_tokens":"","url":445045} +{"project_name":"awadomar34\/FeedForward-NEAT","file_name":"SingleCartPole.py","full_name":"CartPole.getScaledState","func_name":"getScaledState","docstring":"Get full state, scaled into (approximately) [0, 1].","docstring_tokens":"","code":"def getScaledState(self):\n \"\"\"Get full state, scaled into (approximately) [0, 1].\"\"\"\n return [0.5 * (self.x + self.position_limit) \/ self.position_limit, (self.dx + 0.75) \/ 1.5, 0.5 * (self.theta + self.angle_limit_radians) \/ self.angle_limit_radians, (self.dtheta + 1.0) \/ 2.0]","code_tokens":"","url":581920} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"lexnet_model.py","full_name":"LexNETModel.load_labels","func_name":"load_labels","docstring":"Loads the labels for these instances.","docstring_tokens":"","code":"def load_labels(self, session, instances):\n \"\"\"Loads the labels for these instances.\n\n Args:\n session: The current TensorFlow session,\n instances: The instances for which to load the labels.\n\n Returns:\n the labels of these instances.\n \"\"\"\n return session.run(self.labels_to_load, feed_dict={self.instances_to_load: instances})","code_tokens":"","url":757735} +{"project_name":"GregorKobsik\/Octree-Transformer","file_name":"convolution_embedding.py","full_name":"ConvolutionEmbedding.reduce","func_name":"reduce","docstring":"Transform sequences of token into an embedding space and reduces number of tokens.","docstring_tokens":"","code":"def reduce(self, embedding, value, depth, position):\n \"\"\" Transform sequences of token into an embedding space and reduces number of tokens.\n\n Args:\n value: Embedding sequence.\n value: Value token sequence.\n depth: Depth token sequence.\n position: Position token sequence.\n\n Return:\n Token sequence in the embedding space.\n \"\"\"\n self.mask = padding_mask(value[:, ::self.chunk_size], device=value.device)\n return self.convolution(embedding)","code_tokens":"","url":755069} +{"project_name":"RasaHQ\/rasa","file_name":"io.py","full_name":"pickle_load","func_name":"pickle_load","docstring":"Loads an object from a file.","docstring_tokens":"","code":"def pickle_load(filename: Union[Text, Path]) -> Any:\n \"\"\"Loads an object from a file.\n\n Args:\n filename: the filename to load the object from\n\n Returns: the loaded object\n \"\"\"\n with open(filename, 'rb') as f:\n return pickle.load(f)","code_tokens":"","url":837859} +{"project_name":"befelix\/safe_learning","file_name":"functions.py","full_name":"PiecewiseConstant.parameters","func_name":"parameters","docstring":"Set the vertex values.","docstring_tokens":"","code":"@parameters.setter\ndef parameters(self, values):\n \"\"\"Set the vertex values.\"\"\"\n if values is None:\n self._parameters = values\n else:\n self._parameters = np.asarray(values).reshape(self.nindex, -1)","code_tokens":"","url":328164} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning---Tutorials","file_name":"neural_gpu.py","full_name":"place_at14","func_name":"place_at14","docstring":"Place selected at it-th coordinate of decided, dim=1 of 4.","docstring_tokens":"","code":"def place_at14(decided, selected, it):\n \"\"\"Place selected at it-th coordinate of decided, dim=1 of 4.\"\"\"\n slice1 = decided[:, :it, :, :]\n slice2 = decided[:, it + 1:, :, :]\n return tf.concat(axis=1, values=[slice1, selected, slice2])","code_tokens":"","url":50126} +{"project_name":"zekarias-tilahun\/SelfGNN","file_name":"train.py","full_name":"ModelTrainer.infer_embeddings","func_name":"infer_embeddings","docstring":"Infers node embeddings from the trained SelfGNN model.","docstring_tokens":"","code":"def infer_embeddings(self):\n \"\"\"\n Infers node embeddings from the trained SelfGNN model.\n \"\"\"\n outputs = []\n self._model.train(False)\n self._embeddings = self._labels = None\n self._train_mask = self._dev_mask = self._test_mask = None\n for (bc, batch_data) in enumerate(self._loader):\n batch_data.to(self._device)\n (v1_output, v2_output, _) = self._model(x1=batch_data.x, x2=batch_data.x2, edge_index_v1=batch_data.edge_index, edge_index_v2=batch_data.edge_index2, edge_weight_v1=batch_data.edge_attr, edge_weight_v2=batch_data.edge_attr2)\n emb = torch.cat([v1_output, v2_output], dim=1).detach()\n y = batch_data.y.detach()\n trm = batch_data.train_mask.detach()\n dem = batch_data.dev_mask.detach()\n tem = batch_data.test_mask.detach()\n if self._embeddings is None:\n (self._embeddings, self._labels) = (emb, y)\n (self._train_mask, self._dev_mask, self._test_mask) = (trm, dem, tem)\n else:\n self._embeddings = torch.cat([self._embeddings, emb])\n self._labels = torch.cat([self._labels, y])\n self._train_mask = torch.cat([self._train_mask, trm])\n self._dev_mask = torch.cat([self._dev_mask, dem])\n self._test_mask = torch.cat([self._test_mask, tem])","code_tokens":"","url":342338} +{"project_name":"deepmind\/dm_control","file_name":"physics.py","full_name":"Physics.mark_as_dirty","func_name":"mark_as_dirty","docstring":"Marks this physics as dirty, thus requiring recalculation.","docstring_tokens":"","code":"def mark_as_dirty(self):\n \"\"\"Marks this physics as dirty, thus requiring recalculation.\"\"\"\n self._dirty = True","code_tokens":"","url":165240} +{"project_name":"lozuwa\/impy","file_name":"ObjectDetectionDataset.py","full_name":"ObjectDetectionDataset.reduceDatasetByRois","func_name":"reduceDatasetByRois","docstring":"Reduce that images of a dataset by grouping its bounding box annotations and creating smaller images that contain them.","docstring_tokens":"","code":"def reduceDatasetByRois(self, offset=None, outputImageDirectory=None, outputAnnotationDirectory=None):\n \"\"\"\n\t\tReduce that images of a dataset by grouping its bounding box annotations and\n\t\tcreating smaller images that contain them.\n\t\tArgs:\n\t\t\toffset: An int that contains the amount of pixels in which annotations \n\t\t\t\t\t\t\tcan be grouped.\n\t\t\toutputImageDirectory: A string that contains the path to the directory\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere the images will be stored. \n\t\t\toutputAnnotationDirectory: A string that contains the path to the directory\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere the annotations will be stored. \n\t\tReturns:\n\t\t\tNone\n\t\t\"\"\"\n if offset == None:\n raise ValueError('Offset parameter cannot be empty.')\n if outputImageDirectory == None:\n outputImageDirectory = os.getcwd()\n Util.create_folder(os.path.join(outputImageDirectory, 'images'))\n outputImageDirectory = os.path.join(os.getcwd(), 'images')\n if not os.path.isdir(outputImageDirectory):\n raise Exception('Path to output directory does not exist. {}'.format(outputImageDirectory))\n if outputAnnotationDirectory == None:\n outputAnnotationDirectory = os.getcwd()\n Util.create_folder(os.path.join(outputAnnotationDirectory, 'annotations'))\n Util.create_folder(os.path.join(outputAnnotationDirectory, 'annotations', 'xmls'))\n outputAnnotationDirectory = os.path.join(os.getcwd(), 'annotations', 'xmls')\n if not os.path.isdir(outputAnnotationDirectory):\n raise Exception('Path to output annotation directory does not exist. {}'.format(outputAnnotationDirectory))\n imagesPath = [os.path.join(self.imagesDirectory, each) for each in os.listdir(self.imagesDirectory)]\n for img in tqdm(imagesPath):\n extension = Util.detect_file_extension(filename=img)\n if extension == None:\n raise Exception('Your image extension is not valid.' + 'Only jpgs and pngs are allowed.')\n filename = os.path.split(img)[1].split(extension)[0]\n imgFullPath = os.path.join(self.imagesDirectory, filename + extension)\n xmlFullPath = os.path.join(self.annotationsDirectory, filename + '.xml')\n self.reduceImageDataPointByRoi(imagePath=imgFullPath, annotationPath=xmlFullPath, offset=offset, outputImageDirectory=outputImageDirectory, outputAnnotationDirectory=outputAnnotationDirectory)","code_tokens":"","url":611624} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"axes_grid.py","full_name":"Grid.set_aspect","func_name":"set_aspect","docstring":"Set the aspect of the SubplotDivider.","docstring_tokens":"","code":"def set_aspect(self, aspect):\n \"\"\"Set the aspect of the SubplotDivider.\"\"\"\n self._divider.set_aspect(aspect)","code_tokens":"","url":97476} +{"project_name":"lium-lst\/nmtpy","file_name":"basemodel.py","full_name":"BaseModel.init_shared_variables","func_name":"init_shared_variables","docstring":"Initialize the shared variables of the model.","docstring_tokens":"","code":"def init_shared_variables(self):\n \"\"\"Initialize the shared variables of the model.\"\"\"\n self.tparams = OrderedDict()\n for (kk, pp) in self.initial_params.items():\n self.tparams[kk] = theano.shared(pp, name=kk)","code_tokens":"","url":294476} +{"project_name":"Deci-AI\/super-gradients","file_name":"crash_tips_test.py","full_name":"CrashTipTest.test_found_exceptions","func_name":"test_found_exceptions","docstring":"Test all the exceptions that were documented, and make sure that they have an associated tip.","docstring_tokens":"","code":"def test_found_exceptions(self):\n \"\"\"Test all the exceptions that were documented, and make sure that they have an associated tip.\"\"\"\n for documented_exception in self.documented_exceptions:\n (exc_value, expected_crash_tip) = (documented_exception.exc_value, documented_exception.expected_crash_tip)\n try:\n raise exc_value\n except type(exc_value):\n (exc_type, exc_value, exc_traceback) = sys.exc_info()\n with self.subTest(msg='Making sure that the CrashTip is considered relevant for the exception...', expected_tip=expected_crash_tip.__name__, exception=exc_value):\n is_relevant = expected_crash_tip.is_relevant(exc_type, exc_value, exc_traceback)\n self.assertTrue(is_relevant, msg=f\"Crash tip '{expected_crash_tip.__name__}' should be relevant for exception '{exc_type.__name__}' but failed.\")\n with self.subTest(msg='Making sure that the CrashTip generates a message (None is returned if an error is raised internally, to avoid crashing atexit)...', crash_tip=expected_crash_tip.__name__):\n crash_tip_msg = expected_crash_tip.get_message(exc_type, exc_value, exc_traceback)\n self.assertIsNotNone(crash_tip_msg, msg=f\"The crash tip '{expected_crash_tip.__name__}' returned None, an exception was probably raised in '{expected_crash_tip.__name__}.get_message(...)'\")\n with self.subTest(msg=\"Making sure that we can find the relevant CrashTip and get it's summary for the exception...\", expected_tip=expected_crash_tip.__name__, exception=exc_value):\n crash_tip_message = get_relevant_crash_tip_message(exc_type, exc_value, exc_traceback)\n expected_crash_tip_message = expected_crash_tip.get_message(exc_type, exc_value, exc_traceback)\n self.assertEqual(crash_tip_message, expected_crash_tip_message, msg=f\"Crash tip message should be '{expected_crash_tip_message}' but got '{crash_tip_message}' instead.\")","code_tokens":"","url":880648} +{"project_name":"jhnwsk\/artificial","file_name":"base.py","full_name":"AgentBase.act","func_name":"act","docstring":"Decides which action should be performed over the world, and return its code.","docstring_tokens":"","code":"def act(self):\n \"\"\"Decides which action should be performed over the world,\n and return its code.\n\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":91690} +{"project_name":"gregdurrett\/nlp-qa-finalproj","file_name":"data.py","full_name":"Tokenizer.convert_tokens_to_ids","func_name":"convert_tokens_to_ids","docstring":"Converts words to corresponding indices.","docstring_tokens":"","code":"def convert_tokens_to_ids(self, tokens):\n \"\"\"\n Converts words to corresponding indices.\n\n Args:\n tokens: A list of words (string).\n\n Returns:\n A list of indices (int).\n \"\"\"\n return [self.vocabulary.encoding.get(token, self.unk_token_id) for token in tokens]","code_tokens":"","url":731112} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_loss.py","full_name":"test_graceful_squeezing","func_name":"test_graceful_squeezing","docstring":"Test that reshaped raw_prediction gives same results.","docstring_tokens":"","code":"@pytest.mark.parametrize('loss', LOSS_INSTANCES, ids=loss_instance_name)\ndef test_graceful_squeezing(loss):\n \"\"\"Test that reshaped raw_prediction gives same results.\"\"\"\n (y_true, raw_prediction) = random_y_true_raw_prediction(loss=loss, n_samples=20, y_bound=(-100, 100), raw_bound=(-10, 10), seed=42)\n if raw_prediction.ndim == 1:\n raw_prediction_2d = raw_prediction[:, None]\n assert_allclose(loss.loss(y_true=y_true, raw_prediction=raw_prediction_2d), loss.loss(y_true=y_true, raw_prediction=raw_prediction))\n assert_allclose(loss.loss_gradient(y_true=y_true, raw_prediction=raw_prediction_2d), loss.loss_gradient(y_true=y_true, raw_prediction=raw_prediction))\n assert_allclose(loss.gradient(y_true=y_true, raw_prediction=raw_prediction_2d), loss.gradient(y_true=y_true, raw_prediction=raw_prediction))\n assert_allclose(loss.gradient_hessian(y_true=y_true, raw_prediction=raw_prediction_2d), loss.gradient_hessian(y_true=y_true, raw_prediction=raw_prediction))","code_tokens":"","url":854456} +{"project_name":"palmettos\/neat-autoencoders","file_name":"statistics.py","full_name":"StatisticsReporter.get_fitness_median","func_name":"get_fitness_median","docstring":"Get the per-generation median fitness.","docstring_tokens":"","code":"def get_fitness_median(self):\n \"\"\"Get the per-generation median fitness.\"\"\"\n return self.get_fitness_stat(median2)","code_tokens":"","url":735204} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"structs.py","full_name":"_FactoryIterableView.excluding","func_name":"excluding","docstring":"Create a new instance excluding specified candidates.","docstring_tokens":"","code":"def excluding(self, candidates):\n \"\"\"Create a new instance excluding specified candidates.\"\"\"\n\n def factory():\n return (c for c in self._factory() if c not in candidates)\n return type(self)(factory)","code_tokens":"","url":434613} +{"project_name":"QData\/deepWordBug","file_name":"math2html.py","full_name":"MacroFunction.completemacro","func_name":"completemacro","docstring":"Complete the macro with the parameters read.","docstring_tokens":"","code":"def completemacro(self, macro):\n \"\"\"Complete the macro with the parameters read.\"\"\"\n self.contents = [macro.instantiate()]\n replaced = [False] * len(self.values)\n for parameter in self.searchall(MacroParameter):\n index = parameter.number - 1\n if index >= len(self.values):\n Trace.error('Macro parameter index out of bounds: ' + str(index))\n return\n replaced[index] = True\n parameter.contents = [self.values[index].clone()]\n for index in range(len(self.values)):\n if not replaced[index]:\n self.addfilter(index, self.values[index])","code_tokens":"","url":542669} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"compiler.py","full_name":"CodeGenerator.pull_dependencies","func_name":"pull_dependencies","docstring":"Pull all the dependencies.","docstring_tokens":"","code":"def pull_dependencies(self, nodes):\n \"\"\"Pull all the dependencies.\"\"\"\n visitor = DependencyFinderVisitor()\n for node in nodes:\n visitor.visit(node)\n for dependency in ('filters', 'tests'):\n mapping = getattr(self, dependency)\n for name in getattr(visitor, dependency):\n if name not in mapping:\n mapping[name] = self.temporary_identifier()\n self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name))","code_tokens":"","url":39178} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"httpclient.py","full_name":"HTTPClient.close","func_name":"close","docstring":"Closes the HTTPClient, freeing any resources used.","docstring_tokens":"","code":"def close(self) -> None:\n \"\"\"Closes the HTTPClient, freeing any resources used.\"\"\"\n if not self._closed:\n self._async_client.close()\n self._io_loop.close()\n self._closed = True","code_tokens":"","url":21243} +{"project_name":"mahossam\/OptiGAN","file_name":"utils_ace0.py","full_name":"get_velocity_vector","func_name":"get_velocity_vector","docstring":"Calculates the velocity vector for obj.","docstring_tokens":"","code":"def get_velocity_vector(obj):\n \"\"\" Calculates the velocity vector for obj. \"\"\"\n return np.matrix([obj.v * np.cos(np.radians(obj.psi)), obj.v * np.sin(np.radians(obj.psi)), obj.v * np.sin(np.radians(obj.theta))])","code_tokens":"","url":776308} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"augment_test.py","full_name":"AutoaugmentTest.test_invalid_custom_policy_key","func_name":"test_invalid_custom_policy_key","docstring":"Test autoaugment with invalid key in the custom policy.","docstring_tokens":"","code":"def test_invalid_custom_policy_key(self):\n \"\"\"Test autoaugment with invalid key in the custom policy.\"\"\"\n image = tf.zeros((224, 224, 3), dtype=tf.uint8)\n policy = [[('AAAAA', 0.8, 1), ('Shear', 0.8, 4)], [('TranslateY', 0.6, 3), ('Rotate', 0.9, 3)]]\n augmenter = augment.AutoAugment(policies=policy)\n with self.assertRaisesRegex(KeyError, \"'AAAAA'\"):\n augmenter.distort(image)","code_tokens":"","url":973248} +{"project_name":"Eric3911\/OpenAGI","file_name":"data_utils.py","full_name":"ais_binary","func_name":"ais_binary","docstring":"Return location of `ais` binary.","docstring_tokens":"","code":"def ais_binary() -> str:\n \"\"\"Return location of `ais` binary.\n \"\"\"\n path = shutil.which('ais')\n if path is not None:\n logging.debug('Found AIS binary at %s', path)\n return path\n logging.warning('AIS binary not found with `which ais`.')\n default_path = '\/usr\/local\/bin\/ais'\n if os.path.isfile(default_path):\n logging.info('ais available at the default path: %s', default_path)\n return default_path\n else:\n raise RuntimeError(f'AIS binary not found.')","code_tokens":"","url":274171} +{"project_name":"kumarkan\/Food_Detection","file_name":"config_util_test.py","full_name":"ConfigUtilTest.testNewMaskType","func_name":"testNewMaskType","docstring":"Tests that mask type can be overwritten in input readers.","docstring_tokens":"","code":"def testNewMaskType(self):\n \"\"\"Tests that mask type can be overwritten in input readers.\"\"\"\n original_mask_type = input_reader_pb2.NUMERICAL_MASKS\n new_mask_type = input_reader_pb2.PNG_MASKS\n pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')\n pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()\n train_input_reader = pipeline_config.train_input_reader\n train_input_reader.mask_type = original_mask_type\n eval_input_reader = pipeline_config.eval_input_reader\n eval_input_reader.mask_type = original_mask_type\n _write_config(pipeline_config, pipeline_config_path)\n configs = config_util.get_configs_from_pipeline_file(pipeline_config_path)\n configs = config_util.merge_external_params_with_configs(configs, mask_type=new_mask_type)\n self.assertEqual(new_mask_type, configs['train_input_config'].mask_type)\n self.assertEqual(new_mask_type, configs['eval_input_config'].mask_type)","code_tokens":"","url":608949} +{"project_name":"salesforce\/CodeRL","file_name":"test_tokenization_common.py","full_name":"TokenizerTesterMixin.test_padding_to_max_length","func_name":"test_padding_to_max_length","docstring":"We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated.","docstring_tokens":"","code":"def test_padding_to_max_length(self):\n \"\"\"We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated.\"\"\"\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f'{tokenizer.__class__.__name__}'):\n sequence = 'Sequence'\n padding_size = 10\n self._check_no_pad_token_padding(tokenizer, sequence)\n padding_idx = tokenizer.pad_token_id\n tokenizer.padding_side = 'right'\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(sequence, max_length=sequence_length + padding_size, pad_to_max_length=True)\n padded_sequence_length = len(padded_sequence)\n self.assertEqual(sequence_length + padding_size, padded_sequence_length)\n self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence)\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n tokenizer.padding_side = 'right'\n padded_sequence_right = tokenizer.encode(sequence, pad_to_max_length=True)\n padded_sequence_right_length = len(padded_sequence_right)\n self.assertEqual(sequence_length, padded_sequence_right_length)\n self.assertEqual(encoded_sequence, padded_sequence_right)","code_tokens":"","url":495691} +{"project_name":"tuananhbui89\/ASCL","file_name":"contrastive_losses_v2.py","full_name":"soft_lcscl","func_name":"soft_lcscl","docstring":"Compute Local Supervised Contrastive Loss.","docstring_tokens":"","code":"def soft_lcscl(hidden, labels, preds, dist, neg_type, hidden_norm=True, temperature=0.07):\n \"\"\"Compute Local Supervised Contrastive Loss.\n Args:\n hidden: hidden vector (`Tensor`) of shape (2 * bsz, dim).\n labels: labels of hidden vector of shape (2*bsz, classes)\n preds: current prediction \n hidden_norm: whether or not to use normalization on the hidden vector.\n temperature: a `floating` number for temperature scaling.\n dist: distance metric in latent space {'l1', 'l2', 'cosine', 'linf'}\n neg_type: \n 'hard': negative set when y_j ~= y_i, but tilde(y_j) == y_i \n 'soft': negative set when y_j ~= y_i, but tilde(y_j) == tilde(y_i)\n 'merge': negative set when y_i ~= y_i but tilde(y_j) in [y_i, tilde(y_i)]\n 'leaking': \n Returns:\n A loss scalar.\n\n the choice of temperature:\n temperature = 0.5 based on simCLR paper \n temperature = 0.07 based on SCL paper (they claim that smaller temperature \n benefit training more than higher ones)\n \"\"\"\n if dist in ['matmul', 'l1', 'l2']:\n assert hidden_norm is True\n elif dist in ['cosine']:\n assert hidden_norm is False\n if hidden_norm:\n hidden = F.normalize(hidden, p=2, dim=-1)\n batch_size = hidden.shape[0] \/\/ 2\n same_preds = get_positive_mask(preds)\n same_labels = get_positive_mask(labels)\n diff_labels = get_negative_mask(labels)\n same_preds_same_labels = torch.multiply(same_preds, same_labels)\n same_preds_diff_labels = torch.multiply(same_preds, diff_labels)\n pos_mask = get_positive_mask(labels)\n neg_mask = get_negative_mask(labels)\n hard_neg_mask = get_hard_negative_mask(labels, preds)\n soft_neg_mask = get_soft_negative_mask(labels, preds)\n merge_mask = torch.minimum(hard_neg_mask + soft_neg_mask, torch.ones_like(hard_neg_mask))\n if neg_type == 'all':\n illegal_mask = torch.zeros_like(neg_mask)\n nb_neg = torch.sum(neg_mask, dim=-1)\n elif neg_type == 'hard':\n illegal_mask = torch.maximum(neg_mask - hard_neg_mask, torch.zeros_like(neg_mask))\n nb_neg = torch.sum(hard_neg_mask, dim=-1)\n elif neg_type == 'soft':\n illegal_mask = torch.maximum(neg_mask - soft_neg_mask, torch.zeros_like(neg_mask))\n nb_neg = torch.sum(soft_neg_mask, dim=-1)\n elif neg_type == 'merge':\n illegal_mask = torch.maximum(neg_mask - merge_mask, torch.zeros_like(neg_mask))\n nb_neg = torch.sum(merge_mask, dim=-1)\n elif neg_type == 'leaking':\n illegal_mask = torch.maximum(torch.ones_like(same_preds_same_labels) - same_preds_same_labels - same_preds_diff_labels, torch.zeros_like(same_preds_same_labels))\n nb_neg = torch.sum(same_preds_diff_labels, dim=-1)\n masks = F.one_hot(torch.arange(2 * batch_size), num_classes=2 * batch_size).to(hidden.device)\n sim = -distance(hidden, hidden, dist, pairwise=True) \/ temperature\n logits_12 = sim - masks * LARGE_NUM\n logits_masked = logits_12 - LARGE_NUM * illegal_mask\n logprobs = F.log_softmax(logits_masked, dim=1)\n ' Convert labels to pairwise labels of shape [2b, 2b], diagonal(labels)=0\\n multiple hot label vectors \\n\\n '\n if neg_type == 'leaking':\n loss = -torch.sum(same_preds_same_labels * logprobs, dim=-1)\n nb_pos = torch.maximum(torch.sum(same_preds_same_labels, dim=-1), torch.ones_like(loss))\n else:\n loss = -torch.sum(pos_mask * logprobs, dim=-1)\n nb_pos = torch.maximum(torch.sum(pos_mask, dim=-1), torch.ones_like(loss))\n assert loss.shape == nb_pos.shape\n loss = torch.div(loss, nb_pos)\n loss = torch.mean(loss, dim=0)\n return loss","code_tokens":"","url":92283} +{"project_name":"chris-tng\/semi-supervised-nlp","file_name":"metric.py","full_name":"Collection.compute","func_name":"compute","docstring":"Computes metrics and returns them as Python numbers\/lists.","docstring_tokens":"","code":"def compute(self) -> Dict[str, torch.Tensor]:\n \"\"\"Computes metrics and returns them as Python numbers\/lists.\"\"\"\n ndim = self._reduction_counter.value.ndim\n if ndim != 0:\n raise ValueError(f'Collection is still replicated (ndim={ndim}). Maybe you forgot to call a flax.jax_utils.unreplicate() or a Collections.reduce()?')\n return {metric_name: metric.compute() for (metric_name, metric) in vars(self).items() if metric_name != '_reduction_counter'}","code_tokens":"","url":343457} +{"project_name":"thu-ml\/tianshou","file_name":"base.py","full_name":"BaseTrainer.reset","func_name":"reset","docstring":"Initialize or reset the instance to yield a new iterator from zero.","docstring_tokens":"","code":"def reset(self) -> None:\n \"\"\"Initialize or reset the instance to yield a new iterator from zero.\"\"\"\n self.is_run = False\n self.env_step = 0\n if self.resume_from_log:\n (self.start_epoch, self.env_step, self.gradient_step) = self.logger.restore_data()\n (self.last_rew, self.last_len) = (0.0, 0)\n self.start_time = time.time()\n if self.train_collector is not None:\n self.train_collector.reset_stat()\n if self.train_collector.policy != self.policy or self.test_collector is None:\n self.test_in_train = False\n if self.test_collector is not None:\n assert self.episode_per_test is not None\n assert not isinstance(self.test_collector, AsyncCollector)\n self.test_collector.reset_stat()\n test_result = test_episode(self.policy, self.test_collector, self.test_fn, self.start_epoch, self.episode_per_test, self.logger, self.env_step, self.reward_metric)\n self.best_epoch = self.start_epoch\n (self.best_reward, self.best_reward_std) = (test_result['rew'], test_result['rew_std'])\n if self.save_best_fn:\n self.save_best_fn(self.policy)\n self.epoch = self.start_epoch\n self.stop_fn_flag = False\n self.iter_num = 0","code_tokens":"","url":355289} +{"project_name":"ldkong1205\/LaserMix","file_name":"local_visualizer.py","full_name":"Det3DLocalVisualizer.draw_bev_bboxes","func_name":"draw_bev_bboxes","docstring":"Draw projected 3D boxes on the image.","docstring_tokens":"","code":"@master_only\ndef draw_bev_bboxes(self, bboxes_3d: BaseInstance3DBoxes, scale: int=15, edge_colors: Union[str, Tuple[int], List[Union[str, Tuple[int]]]]='o', line_styles: Union[str, List[str]]='-', line_widths: Union[int, float, List[Union[int, float]]]=1, face_colors: Union[str, Tuple[int], List[Union[str, Tuple[int]]]]='none', alpha: Union[int, float]=1) -> MMENGINE_Visualizer:\n \"\"\"Draw projected 3D boxes on the image.\n\n Args:\n bboxes_3d (:obj:`BaseInstance3DBoxes`): 3D bbox\n (x, y, z, x_size, y_size, z_size, yaw) to visualize.\n scale (dict): Value to scale the bev bboxes for better\n visualization. Defaults to 15.\n edge_colors (str or Tuple[int] or List[str or Tuple[int]]):\n The colors of bboxes. ``colors`` can have the same length with\n lines or just single value. If ``colors`` is single value, all\n the lines will have the same colors. Refer to `matplotlib.\n colors` for full list of formats that are accepted.\n Defaults to 'o'.\n line_styles (str or List[str]): The linestyle of lines.\n ``line_styles`` can have the same length with texts or just\n single value. If ``line_styles`` is single value, all the lines\n will have the same linestyle. Reference to\n https:\/\/matplotlib.org\/stable\/api\/collections_api.html?highlight=collection#matplotlib.collections.AsteriskPolygonCollection.set_linestyle\n for more details. Defaults to '-'.\n line_widths (int or float or List[int or float]): The linewidth of\n lines. ``line_widths`` can have the same length with lines or\n just single value. If ``line_widths`` is single value, all the\n lines will have the same linewidth. Defaults to 2.\n face_colors (str or Tuple[int] or List[str or Tuple[int]]):\n The face colors. Defaults to 'none'.\n alpha (int or float): The transparency of bboxes. Defaults to 1.\n \"\"\"\n check_type('bboxes', bboxes_3d, BaseInstance3DBoxes)\n bev_bboxes = tensor2ndarray(bboxes_3d.bev)\n bev_bboxes[:, :4] *= scale\n (ctr, w, h, theta) = np.split(bev_bboxes, [2, 3, 4], axis=-1)\n (cos_value, sin_value) = (np.cos(theta), np.sin(theta))\n vec1 = np.concatenate([w \/ 2 * cos_value, w \/ 2 * sin_value], axis=-1)\n vec2 = np.concatenate([-h \/ 2 * sin_value, h \/ 2 * cos_value], axis=-1)\n pt1 = ctr + vec1 + vec2\n pt2 = ctr + vec1 - vec2\n pt3 = ctr - vec1 - vec2\n pt4 = ctr - vec1 + vec2\n poly = np.stack([pt1, pt2, pt3, pt4], axis=-2)\n poly[:, :, 0] += self.width \/ 2\n poly = [p for p in poly]\n return self.draw_polygons(poly, alpha=alpha, edge_colors=edge_colors, line_styles=line_styles, line_widths=line_widths, face_colors=face_colors)","code_tokens":"","url":624470} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"parser_test.py","full_name":"test_function_with_args_kwargs","func_name":"test_function_with_args_kwargs","docstring":"Docstring for second test function.","docstring_tokens":"","code":"def test_function_with_args_kwargs(unused_arg, *unused_args, **unused_kwargs):\n \"\"\"Docstring for second test function.\"\"\"\n pass","code_tokens":"","url":606764} +{"project_name":"tonandr\/keras_unsupervised","file_name":"gan.py","full_name":"AbstractGAN.compose_gan","func_name":"compose_gan","docstring":"Compose the GAN model.","docstring_tokens":"","code":"def compose_gan(self):\n \"\"\"Compose the GAN model.\"\"\"\n raise NotImplementedError('compose_gan is not implemented.')","code_tokens":"","url":256131} +{"project_name":"open-mmlab\/mmsegmentation","file_name":"class_names.py","full_name":"mapillary_v1_classes","func_name":"mapillary_v1_classes","docstring":"mapillary_v1 class names for external use.","docstring_tokens":"","code":"def mapillary_v1_classes():\n \"\"\"mapillary_v1 class names for external use.\"\"\"\n return ['Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail', 'Barrier', 'Wall', 'Bike Lane', 'Crosswalk - Plain', 'Curb Cut', 'Parking', 'Pedestrian Area', 'Rail Track', 'Road', 'Service Lane', 'Sidewalk', 'Bridge', 'Building', 'Tunnel', 'Person', 'Bicyclist', 'Motorcyclist', 'Other Rider', 'Lane Marking - Crosswalk', 'Lane Marking - General', 'Mountain', 'Sand', 'Sky', 'Snow', 'Terrain', 'Vegetation', 'Water', 'Banner', 'Bench', 'Bike Rack', 'Billboard', 'Catch Basin', 'CCTV Camera', 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole', 'Phone Booth', 'Pothole', 'Street Light', 'Pole', 'Traffic Sign Frame', 'Utility Pole', 'Traffic Light', 'Traffic Sign (Back)', 'Traffic Sign (Front)', 'Trash Can', 'Bicycle', 'Boat', 'Bus', 'Car', 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle', 'Trailer', 'Truck', 'Wheeled Slow', 'Car Mount', 'Ego Vehicle', 'Unlabeled']","code_tokens":"","url":625501} +{"project_name":"deepmind\/dm_control","file_name":"mazes.py","full_name":"MazeWithTargets.spawn_positions","func_name":"spawn_positions","docstring":"The Cartesian position at which the agent should be spawned.","docstring_tokens":"","code":"@property\ndef spawn_positions(self):\n \"\"\"The Cartesian position at which the agent should be spawned.\"\"\"\n return self._spawn_positions","code_tokens":"","url":165045} +{"project_name":"LLNL\/Abmarl","file_name":"agent_based_simulation.py","full_name":"AgentBasedSimulation.get_all_done","func_name":"get_all_done","docstring":"Return the simulation's done status.","docstring_tokens":"","code":"@abstractmethod\ndef get_all_done(self, **kwargs):\n \"\"\"\n Return the simulation's done status.\n \"\"\"\n pass","code_tokens":"","url":405712} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_tifffile.py","full_name":"TiffPage.is_ome","func_name":"is_ome","docstring":"Page contains OME-XML in ImageDescription tag.","docstring_tokens":"","code":"@property\ndef is_ome(self):\n \"\"\"Page contains OME-XML in ImageDescription tag.\"\"\"\n if self.index > 1 or not self.description:\n return False\n d = self.description\n return d[:14] == ''","code_tokens":"","url":37624} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"network_units.py","full_name":"fixed_embeddings_name","func_name":"fixed_embeddings_name","docstring":"Returns the name of the fixed embedding matrix for some channel ID.","docstring_tokens":"","code":"def fixed_embeddings_name(channel_id):\n \"\"\"Returns the name of the fixed embedding matrix for some channel ID.\"\"\"\n return 'fixed_embedding_matrix_%d' % channel_id","code_tokens":"","url":28378} +{"project_name":"deepmind\/acme","file_name":"base.py","full_name":"Adder.reset","func_name":"reset","docstring":"Resets the adder's buffer.","docstring_tokens":"","code":"@abc.abstractmethod\ndef reset(self):\n \"\"\"Resets the adder's buffer.\"\"\"","code_tokens":"","url":7486} +{"project_name":"BishopFox\/eyeballer","file_name":"model.py","full_name":"EyeballModel.predict","func_name":"predict","docstring":"Predict the labels for a single file or directory of files Keyword arguments: path -- The path to the file(s) that we'll be evaluating.","docstring_tokens":"","code":"def predict(self, path, threshold=0.5):\n \"\"\"Predict the labels for a single file or directory of files\n\n Keyword arguments:\n path -- The path to the file(s) that we'll be evaluating.\n \"\"\"\n screenshots = []\n if os.path.isfile(path):\n screenshots = [path]\n elif os.path.isdir(path):\n screenshots = os.listdir(path)\n screenshots = [os.path.join(path, s) for s in screenshots]\n else:\n raise FileNotFoundError\n results = []\n bar = progressbar.ProgressBar()\n if self.quiet:\n bar = progressbar.NullBar()\n for screenshot in bar(screenshots):\n img = None\n try:\n img = tf.keras.preprocessing.image.load_img(screenshot, target_size=(self.image_width, self.image_height))\n img = tf.keras.preprocessing.image.img_to_array(img)\n img = np.expand_dims(img, axis=0)\n img = preprocess_input(img)\n except IsADirectoryError:\n print('\\nWARN: Skipping directory: ', screenshot)\n continue\n except OSError:\n print('\\nWARN: Skipping empty or corrupt file: ', screenshot)\n continue\n prediction = self.model.predict(img, batch_size=1)\n result = dict()\n result['filename'] = screenshot\n result['custom404'] = prediction[0][0]\n result['login'] = prediction[0][1]\n result['webapp'] = prediction[0][2]\n result['oldlooking'] = prediction[0][3]\n result['parked'] = prediction[0][4]\n results.append(result)\n return results","code_tokens":"","url":178766} +{"project_name":"voxel51\/fiftyone","file_name":"activitynet.py","full_name":"ActivityNetDetectionResults.plot_pr_curves","func_name":"plot_pr_curves","docstring":"Plots precision-recall (PR) curves for the results.","docstring_tokens":"","code":"def plot_pr_curves(self, classes=None, iou_thresh=None, backend='plotly', **kwargs):\n \"\"\"Plots precision-recall (PR) curves for the results.\n\n Args:\n classes (None): a list of classes to generate curves for. By\n default, the top 3 AP classes will be plotted\n iou_thresh (None): an optional IoU threshold or list of IoU\n thresholds for which to plot curves. If multiple thresholds are\n provided, precision data is averaged across these thresholds.\n By default, precision data is averaged over all IoU thresholds.\n Refer to :attr:`iou_threshs` to see the available thresholds\n backend (\"plotly\"): the plotting backend to use. Supported values\n are ``(\"plotly\", \"matplotlib\")``\n **kwargs: keyword arguments for the backend plotting method:\n\n - \"plotly\" backend: :meth:`fiftyone.core.plots.plotly.plot_pr_curves`\n - \"matplotlib\" backend: :meth:`fiftyone.core.plots.matplotlib.plot_pr_curves`\n\n Returns:\n one of the following:\n\n - a :class:`fiftyone.core.plots.plotly.PlotlyNotebookPlot`, if\n you are working in a notebook context and the plotly backend is\n used\n - a plotly or matplotlib figure, otherwise\n \"\"\"\n if classes is None:\n inds = np.argsort(self._classwise_AP)[::-1][:3]\n classes = self.classes[inds]\n thresh_inds = self._get_iou_thresh_inds(iou_thresh=iou_thresh)\n precisions = []\n has_thresholds = self.thresholds is not None\n thresholds = [] if has_thresholds else None\n for c in classes:\n class_ind = self._get_class_index(c)\n precisions.append(np.mean(self.precision[thresh_inds, class_ind], axis=0))\n if has_thresholds:\n thresholds.append(np.mean(self.thresholds[thresh_inds, class_ind], axis=0))\n return fop.plot_pr_curves(precisions, self.recall, classes, thresholds=thresholds, backend=backend, **kwargs)","code_tokens":"","url":584333} +{"project_name":"sktime\/sktime","file_name":"test_panel.py","full_name":"test_check_X_enforce_min_columns","func_name":"test_check_X_enforce_min_columns","docstring":"Test minimum columns enforced in check_X.","docstring_tokens":"","code":"def test_check_X_enforce_min_columns():\n \"\"\"Test minimum columns enforced in check_X.\"\"\"\n (X, y) = make_classification_problem(n_columns=2)\n msg = 'columns'\n with pytest.raises(ValueError, match=msg):\n check_X(X, enforce_min_columns=3)\n with pytest.raises(ValueError, match=msg):\n check_X_y(X, y, enforce_min_columns=3)","code_tokens":"","url":878136} +{"project_name":"user0407\/CLUDA","file_name":"class_names.py","full_name":"get_palette","func_name":"get_palette","docstring":"Get class palette (RGB) of a dataset.","docstring_tokens":"","code":"def get_palette(dataset):\n \"\"\"Get class palette (RGB) of a dataset.\"\"\"\n alias2name = {}\n for (name, aliases) in dataset_aliases.items():\n for alias in aliases:\n alias2name[alias] = name\n if mmcv.is_str(dataset):\n if dataset in alias2name:\n labels = eval(alias2name[dataset] + '_palette()')\n else:\n raise ValueError(f'Unrecognized dataset: {dataset}')\n else:\n raise TypeError(f'dataset must a str, but got {type(dataset)}')\n return labels","code_tokens":"","url":122617} +{"project_name":"aakashjhawar\/SolveSudoku","file_name":"SudokuExtractor.py","full_name":"find_corners_of_largest_polygon","func_name":"find_corners_of_largest_polygon","docstring":"Finds the 4 extreme corners of the largest contour in the image.","docstring_tokens":"","code":"def find_corners_of_largest_polygon(img):\n \"\"\"Finds the 4 extreme corners of the largest contour in the image.\"\"\"\n opencv_version = cv2.__version__.split('.')[0]\n if opencv_version == '3':\n (_, contours, h) = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n else:\n (contours, h) = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n polygon = contours[0]\n (bottom_right, _) = max(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))\n (top_left, _) = min(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))\n (bottom_left, _) = min(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))\n (top_right, _) = max(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))\n return [polygon[top_left][0], polygon[top_right][0], polygon[bottom_right][0], polygon[bottom_left][0]]","code_tokens":"","url":879480} +{"project_name":"vbhardwaj2000\/Recurrent_Neural_Network","file_name":"script.py","full_name":"rnn_cell_backward","func_name":"rnn_cell_backward","docstring":"Implements the backward pass for the RNN-cell (single time-step).","docstring_tokens":"","code":"def rnn_cell_backward(da_next, cache):\n \"\"\"\n Implements the backward pass for the RNN-cell (single time-step).\n\n \"\"\"\n (a_next, a_prev, xt, parameters) = cache\n Wax = parameters['Wax']\n Waa = parameters['Waa']\n Wya = parameters['Wya']\n ba = parameters['ba']\n by = parameters['by']\n dz = 1 - np.square(np.tanh(np.dot(Wax, xt) + np.dot(Waa, a_prev) + ba))\n dtanh = da_next * dz\n dxt = np.dot(Wax.T, dtanh)\n dWax = np.dot(dtanh, xt.T)\n da_prev = np.dot(Waa.T, dtanh)\n dWaa = np.dot(dtanh, a_prev.T)\n dba = np.sum(dtanh, axis=1, keepdims=True)\n gradients = {'dxt': dxt, 'da_prev': da_prev, 'dWax': dWax, 'dWaa': dWaa, 'dba': dba}\n return gradients","code_tokens":"","url":309513} +{"project_name":"eric-haibin-lin\/nlp-notebooks","file_name":"finetune_classifier.py","full_name":"test","func_name":"test","docstring":"Inference function on the test dataset.","docstring_tokens":"","code":"def test(loader_test, segment):\n \"\"\"Inference function on the test dataset.\"\"\"\n logging.info('Now we are doing testing on %s with %s.', segment, ctx)\n tic = time.time()\n results = []\n for (_, seqs) in enumerate(loader_test):\n (input_ids, valid_length, type_ids) = seqs\n out = model(input_ids.as_in_context(ctx), type_ids.as_in_context(ctx), valid_length.astype('float32').as_in_context(ctx))\n if not task.class_labels:\n for result in out.asnumpy().reshape(-1).tolist():\n results.append('{:.3f}'.format(result))\n else:\n indices = mx.nd.topk(out, k=1, ret_typ='indices', dtype='int32').asnumpy()\n for index in indices:\n results.append(task.class_labels[int(index)])\n mx.nd.waitall()\n toc = time.time()\n logging.info('Time cost=%.2fs, throughput=%.2f samples\/s', toc - tic, dev_batch_size * len(loader_test) \/ (toc - tic))\n filename = args.task_name + segment.replace('test', '') + '.csv'\n test_path = os.path.join(args.output_dir, filename)\n with io.open(test_path, 'w', encoding='utf-8') as f:\n f.write(u'index\\tprediction\\n')\n for (i, pred) in enumerate(results):\n f.write(u'%d\\t%s\\n' % (i, str(pred)))","code_tokens":"","url":730860} +{"project_name":"triaquae\/triaquae","file_name":"test_envelope.py","full_name":"EnvelopeTest.test06_expand_to_include_extent_4_tuple","func_name":"test06_expand_to_include_extent_4_tuple","docstring":"Testing Envelope expand_to_include -- extent as a single 4-tuple parameter.","docstring_tokens":"","code":"def test06_expand_to_include_extent_4_tuple(self):\n \"\"\"Testing Envelope expand_to_include -- extent as a single 4-tuple parameter.\"\"\"\n self.e.expand_to_include((-1, 1, 3, 7))\n self.assertEqual((-1, 0, 5, 7), self.e)","code_tokens":"","url":357701} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"event_accumulator.py","full_name":"EventAccumulator.CompressedHistograms","func_name":"CompressedHistograms","docstring":"Given a summary tag, return all associated compressed histograms.","docstring_tokens":"","code":"def CompressedHistograms(self, tag):\n \"\"\"Given a summary tag, return all associated compressed histograms.\n\n Args:\n tag: A string tag associated with the events.\n\n Raises:\n KeyError: If the tag is not found.\n\n Returns:\n An array of `CompressedHistogramEvent`s.\n \"\"\"\n return self._compressed_histograms.Items(tag)","code_tokens":"","url":183193} +{"project_name":"flow-project\/flow","file_name":"test_vehicles.py","full_name":"TestMultiLaneData.test_no_junctions_ring","func_name":"test_no_junctions_ring","docstring":"Test the above mentioned methods in the absence of junctions.","docstring_tokens":"","code":"def test_no_junctions_ring(self):\n \"\"\"\n Test the above mentioned methods in the absence of junctions.\n \"\"\"\n additional_net_params = {'length': 230, 'lanes': 3, 'speed_limit': 30, 'resolution': 40}\n net_params = NetParams(additional_params=additional_net_params)\n vehicles = VehicleParams()\n vehicles.add(veh_id='test', acceleration_controller=(RLController, {}), num_vehicles=21)\n initial_config = InitialConfig(lanes_distribution=float('inf'))\n (env, _, _) = ring_road_exp_setup(net_params=net_params, vehicles=vehicles, initial_config=initial_config)\n env.reset()\n actual_lane_leaders = env.k.vehicle.get_lane_leaders('test_0')\n expected_lane_leaders = ['test_3', 'test_1', 'test_2']\n self.assertCountEqual(actual_lane_leaders, expected_lane_leaders)\n actual_lane_head = env.k.vehicle.get_lane_headways('test_0')\n expected_lane_head = [27.85714285714286, -5, -5]\n self.assertCountEqual(actual_lane_head, expected_lane_head)\n actual_lane_followers = env.k.vehicle.get_lane_followers('test_0')\n expected_lane_followers = ['test_18', 'test_19', 'test_20']\n self.assertCountEqual(actual_lane_followers, expected_lane_followers)\n actual_lane_tail = env.k.vehicle.get_lane_tailways('test_0')\n expected_lane_tail = [28.577143] * 3\n np.testing.assert_array_almost_equal(actual_lane_tail, expected_lane_tail)","code_tokens":"","url":212547} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"gen_data_flow_ops.py","full_name":"random_shuffle_queue","func_name":"random_shuffle_queue","docstring":"A queue that randomizes the order of elements.","docstring_tokens":"","code":"def random_shuffle_queue(component_types, shapes=[], capacity=-1, min_after_dequeue=0, seed=0, seed2=0, container='', shared_name='', name=None):\n \"\"\"A queue that randomizes the order of elements.\n\n Args:\n component_types: A list of `tf.DTypes` that has length `>= 1`.\n The type of each component in a value.\n shapes: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[]`.\n The shape of each component in a value. The length of this attr must\n\n be either 0 or the same as the length of component_types. If the length of\n\n this attr is 0, the shapes of queue elements are not constrained, and\n\n only one element may be dequeued at a time.\n capacity: An optional `int`. Defaults to `-1`.\n The upper bound on the number of elements in this queue.\n\n Negative numbers mean no limit.\n min_after_dequeue: An optional `int`. Defaults to `0`.\n Dequeue will block unless there would be this\n\n many elements after the dequeue or the queue is closed. This\n\n ensures a minimum level of mixing of elements.\n seed: An optional `int`. Defaults to `0`.\n If either seed or seed2 is set to be non-zero, the random number\n\n generator is seeded by the given seed. Otherwise, a random seed is used.\n seed2: An optional `int`. Defaults to `0`.\n A second seed to avoid seed collision.\n container: An optional `string`. Defaults to `\"\"`.\n If non-empty, this queue is placed in the given container.\n\n Otherwise, a default container is used.\n shared_name: An optional `string`. Defaults to `\"\"`.\n If non-empty, this queue will be shared under the given name\n\n across multiple sessions.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type mutable `string`.\n \"\"\"\n _ctx = _context._context\n if _ctx is None or not _ctx._eager_context.is_eager:\n if not isinstance(component_types, (list, tuple)):\n raise TypeError(\"Expected list for 'component_types' argument to 'random_shuffle_queue' Op, not %r.\" % component_types)\n component_types = [_execute.make_type(_t, 'component_types') for _t in component_types]\n if shapes is None:\n shapes = []\n if not isinstance(shapes, (list, tuple)):\n raise TypeError(\"Expected list for 'shapes' argument to 'random_shuffle_queue' Op, not %r.\" % shapes)\n shapes = [_execute.make_shape(_s, 'shapes') for _s in shapes]\n if capacity is None:\n capacity = -1\n capacity = _execute.make_int(capacity, 'capacity')\n if min_after_dequeue is None:\n min_after_dequeue = 0\n min_after_dequeue = _execute.make_int(min_after_dequeue, 'min_after_dequeue')\n if seed is None:\n seed = 0\n seed = _execute.make_int(seed, 'seed')\n if seed2 is None:\n seed2 = 0\n seed2 = _execute.make_int(seed2, 'seed2')\n if container is None:\n container = ''\n container = _execute.make_str(container, 'container')\n if shared_name is None:\n shared_name = ''\n shared_name = _execute.make_str(shared_name, 'shared_name')\n (_, _, _op) = _op_def_lib._apply_op_helper('RandomShuffleQueue', component_types=component_types, shapes=shapes, capacity=capacity, min_after_dequeue=min_after_dequeue, seed=seed, seed2=seed2, container=container, shared_name=shared_name, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = ('component_types', _op.get_attr('component_types'), 'shapes', _op.get_attr('shapes'), 'capacity', _op.get_attr('capacity'), 'min_after_dequeue', _op.get_attr('min_after_dequeue'), 'seed', _op.get_attr('seed'), 'seed2', _op.get_attr('seed2'), 'container', _op.get_attr('container'), 'shared_name', _op.get_attr('shared_name'))\n _execute.record_gradient('RandomShuffleQueue', _inputs_flat, _attrs, _result, name)\n (_result,) = _result\n return _result\n else:\n raise RuntimeError(\"random_shuffle_queue op does not support eager execution. Arg 'handle' is a ref.\")\n raise RuntimeError(\"random_shuffle_queue op does not support eager execution. Arg 'handle' is a ref.\")","code_tokens":"","url":337755} +{"project_name":"lllingfa\/computer_vision_with_python","file_name":"ch9_seg1.py","full_name":"create_msr_labels","func_name":"create_msr_labels","docstring":"Create label matrix for training from user annotations.","docstring_tokens":"","code":"def create_msr_labels(m, lasso=False):\n \"\"\" Create label matrix for training from\n user annotations. \"\"\"\n labels = zeros(im.shape[:2])\n labels[m == 0] = -1\n labels[m == 20] = -1\n if lasso:\n labels[m == 255] = 1\n else:\n labels[m == 128] = 1\n return labels","code_tokens":"","url":514946} +{"project_name":"google-research\/scenic","file_name":"test_model_utils.py","full_name":"LossTest.test_weighted_l1_loss","func_name":"test_weighted_l1_loss","docstring":"Test weighted_l1_loss against a manually specified target.","docstring_tokens":"","code":"def test_weighted_l1_loss(self):\n \"\"\"Test weighted_l1_loss against a manually specified target.\"\"\"\n x = jnp.array([[0.1, 0.3], [-1.0, 0.2]], dtype=jnp.float32)\n y = jnp.array([[0.5, -1.3], [0.9, 1.2]], dtype=jnp.float32)\n out1 = model_utils.weighted_l1_loss(x, y, reduction=None)\n out1_target = jnp.array([[0.4, 1.6], [1.9, 1.0]], dtype=jnp.float32)\n self.assertSequenceAlmostEqual(out1.flatten(), out1_target.flatten(), places=5)\n out2 = model_utils.weighted_l1_loss(x, y, reduction='mean').item()\n out2_target = 4.9 \/ 4\n self.assertAlmostEqual(out2, out2_target, places=5)","code_tokens":"","url":846228} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_openml.py","full_name":"datasets_column_names","func_name":"datasets_column_names","docstring":"Returns the columns names for each dataset.","docstring_tokens":"","code":"@pytest.fixture(scope='module')\ndef datasets_column_names():\n \"\"\"Returns the columns names for each dataset.\"\"\"\n return {61: ['sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'class'], 2: ['family', 'product-type', 'steel', 'carbon', 'hardness', 'temper_rolling', 'condition', 'formability', 'strength', 'non-ageing', 'surface-finish', 'surface-quality', 'enamelability', 'bc', 'bf', 'bt', 'bw%2Fme', 'bl', 'm', 'chrom', 'phos', 'cbond', 'marvi', 'exptl', 'ferro', 'corr', 'blue%2Fbright%2Fvarn%2Fclean', 'lustre', 'jurofm', 's', 'p', 'shape', 'thick', 'width', 'len', 'oil', 'bore', 'packing', 'class'], 561: ['vendor', 'MYCT', 'MMIN', 'MMAX', 'CACH', 'CHMIN', 'CHMAX', 'class'], 40589: ['Mean_Acc1298_Mean_Mem40_Centroid', 'Mean_Acc1298_Mean_Mem40_Rolloff', 'Mean_Acc1298_Mean_Mem40_Flux', 'Mean_Acc1298_Mean_Mem40_MFCC_0', 'Mean_Acc1298_Mean_Mem40_MFCC_1', 'Mean_Acc1298_Mean_Mem40_MFCC_2', 'Mean_Acc1298_Mean_Mem40_MFCC_3', 'Mean_Acc1298_Mean_Mem40_MFCC_4', 'Mean_Acc1298_Mean_Mem40_MFCC_5', 'Mean_Acc1298_Mean_Mem40_MFCC_6', 'Mean_Acc1298_Mean_Mem40_MFCC_7', 'Mean_Acc1298_Mean_Mem40_MFCC_8', 'Mean_Acc1298_Mean_Mem40_MFCC_9', 'Mean_Acc1298_Mean_Mem40_MFCC_10', 'Mean_Acc1298_Mean_Mem40_MFCC_11', 'Mean_Acc1298_Mean_Mem40_MFCC_12', 'Mean_Acc1298_Std_Mem40_Centroid', 'Mean_Acc1298_Std_Mem40_Rolloff', 'Mean_Acc1298_Std_Mem40_Flux', 'Mean_Acc1298_Std_Mem40_MFCC_0', 'Mean_Acc1298_Std_Mem40_MFCC_1', 'Mean_Acc1298_Std_Mem40_MFCC_2', 'Mean_Acc1298_Std_Mem40_MFCC_3', 'Mean_Acc1298_Std_Mem40_MFCC_4', 'Mean_Acc1298_Std_Mem40_MFCC_5', 'Mean_Acc1298_Std_Mem40_MFCC_6', 'Mean_Acc1298_Std_Mem40_MFCC_7', 'Mean_Acc1298_Std_Mem40_MFCC_8', 'Mean_Acc1298_Std_Mem40_MFCC_9', 'Mean_Acc1298_Std_Mem40_MFCC_10', 'Mean_Acc1298_Std_Mem40_MFCC_11', 'Mean_Acc1298_Std_Mem40_MFCC_12', 'Std_Acc1298_Mean_Mem40_Centroid', 'Std_Acc1298_Mean_Mem40_Rolloff', 'Std_Acc1298_Mean_Mem40_Flux', 'Std_Acc1298_Mean_Mem40_MFCC_0', 'Std_Acc1298_Mean_Mem40_MFCC_1', 'Std_Acc1298_Mean_Mem40_MFCC_2', 'Std_Acc1298_Mean_Mem40_MFCC_3', 'Std_Acc1298_Mean_Mem40_MFCC_4', 'Std_Acc1298_Mean_Mem40_MFCC_5', 'Std_Acc1298_Mean_Mem40_MFCC_6', 'Std_Acc1298_Mean_Mem40_MFCC_7', 'Std_Acc1298_Mean_Mem40_MFCC_8', 'Std_Acc1298_Mean_Mem40_MFCC_9', 'Std_Acc1298_Mean_Mem40_MFCC_10', 'Std_Acc1298_Mean_Mem40_MFCC_11', 'Std_Acc1298_Mean_Mem40_MFCC_12', 'Std_Acc1298_Std_Mem40_Centroid', 'Std_Acc1298_Std_Mem40_Rolloff', 'Std_Acc1298_Std_Mem40_Flux', 'Std_Acc1298_Std_Mem40_MFCC_0', 'Std_Acc1298_Std_Mem40_MFCC_1', 'Std_Acc1298_Std_Mem40_MFCC_2', 'Std_Acc1298_Std_Mem40_MFCC_3', 'Std_Acc1298_Std_Mem40_MFCC_4', 'Std_Acc1298_Std_Mem40_MFCC_5', 'Std_Acc1298_Std_Mem40_MFCC_6', 'Std_Acc1298_Std_Mem40_MFCC_7', 'Std_Acc1298_Std_Mem40_MFCC_8', 'Std_Acc1298_Std_Mem40_MFCC_9', 'Std_Acc1298_Std_Mem40_MFCC_10', 'Std_Acc1298_Std_Mem40_MFCC_11', 'Std_Acc1298_Std_Mem40_MFCC_12', 'BH_LowPeakAmp', 'BH_LowPeakBPM', 'BH_HighPeakAmp', 'BH_HighPeakBPM', 'BH_HighLowRatio', 'BHSUM1', 'BHSUM2', 'BHSUM3', 'amazed.suprised', 'happy.pleased', 'relaxing.calm', 'quiet.still', 'sad.lonely', 'angry.aggresive'], 1119: ['age', 'workclass', 'fnlwgt:', 'education:', 'education-num:', 'marital-status:', 'occupation:', 'relationship:', 'race:', 'sex:', 'capital-gain:', 'capital-loss:', 'hours-per-week:', 'native-country:', 'class'], 40966: ['DYRK1A_N', 'ITSN1_N', 'BDNF_N', 'NR1_N', 'NR2A_N', 'pAKT_N', 'pBRAF_N', 'pCAMKII_N', 'pCREB_N', 'pELK_N', 'pERK_N', 'pJNK_N', 'PKCA_N', 'pMEK_N', 'pNR1_N', 'pNR2A_N', 'pNR2B_N', 'pPKCAB_N', 'pRSK_N', 'AKT_N', 'BRAF_N', 'CAMKII_N', 'CREB_N', 'ELK_N', 'ERK_N', 'GSK3B_N', 'JNK_N', 'MEK_N', 'TRKA_N', 'RSK_N', 'APP_N', 'Bcatenin_N', 'SOD1_N', 'MTOR_N', 'P38_N', 'pMTOR_N', 'DSCR1_N', 'AMPKA_N', 'NR2B_N', 'pNUMB_N', 'RAPTOR_N', 'TIAM1_N', 'pP70S6_N', 'NUMB_N', 'P70S6_N', 'pGSK3B_N', 'pPKCG_N', 'CDK5_N', 'S6_N', 'ADARB1_N', 'AcetylH3K9_N', 'RRP1_N', 'BAX_N', 'ARC_N', 'ERBB4_N', 'nNOS_N', 'Tau_N', 'GFAP_N', 'GluR3_N', 'GluR4_N', 'IL1B_N', 'P3525_N', 'pCASP9_N', 'PSD95_N', 'SNCA_N', 'Ubiquitin_N', 'pGSK3B_Tyr216_N', 'SHH_N', 'BAD_N', 'BCL2_N', 'pS6_N', 'pCFOS_N', 'SYP_N', 'H3AcK18_N', 'EGR1_N', 'H3MeK4_N', 'CaNA_N', 'class'], 40945: ['pclass', 'survived', 'name', 'sex', 'age', 'sibsp', 'parch', 'ticket', 'fare', 'cabin', 'embarked', 'boat', 'body', 'home.dest']}","code_tokens":"","url":363585} +{"project_name":"david-abel\/simple_rl","file_name":"ActionAbstractionClass.py","full_name":"ActionAbstraction.is_next_step_continuing_option","func_name":"is_next_step_continuing_option","docstring":"Returns: (bool): True iff an option was executing and should continue next step.","docstring_tokens":"","code":"def is_next_step_continuing_option(self, ground_state):\n \"\"\"\n Returns:\n (bool): True iff an option was executing and should continue next step.\n \"\"\"\n return self.is_cur_executing and (not self.cur_option.is_term_true(ground_state))","code_tokens":"","url":350702} +{"project_name":"instadeepai\/jumanji","file_name":"utils_shelf.py","full_name":"set_new_shelf_position_if_carrying","func_name":"set_new_shelf_position_if_carrying","docstring":"Set the new position of the shelf if the agent is carrying one.","docstring_tokens":"","code":"def set_new_shelf_position_if_carrying(grid: chex.Array, shelves: Shelf, cur_pos: chex.Array, new_pos: chex.Array) -> Tuple[chex.Array, chex.Array]:\n \"\"\"Set the new position of the shelf if the agent is carrying one.\n\n Args:\n grid: the warehouse floor grid array.\n shelves: a pytree of Shelf type containing shelf information.\n cur_pos: the current position of the shelf.\n new_pos: the new position of the shelf.\n\n Returns:\n updated grid array and shelves pytree.\n \"\"\"\n shelf_id = grid[_SHELVES, cur_pos.x, cur_pos.y]\n shelves = update_shelf(shelves, shelf_id - 1, 'position', new_pos)\n grid = grid.at[_SHELVES, cur_pos.x, cur_pos.y].set(0)\n grid = grid.at[_SHELVES, new_pos.x, new_pos.y].set(shelf_id)\n return (grid, shelves)","code_tokens":"","url":594491} +{"project_name":"binary-husky\/hmp2g","file_name":"localbo_utils.py","full_name":"onehot2ordinal","func_name":"onehot2ordinal","docstring":"Convert one-hot representation of strings back to ordinal representation.","docstring_tokens":"","code":"def onehot2ordinal(x, categorical_dims):\n \"\"\"Convert one-hot representation of strings back to ordinal representation.\"\"\"\n from itertools import chain\n if x.ndim == 1:\n x = x.reshape(1, -1)\n categorical_dims_flattned = list(chain(*categorical_dims))\n x = x[:, categorical_dims_flattned]\n if not isinstance(x, torch.Tensor):\n x = torch.tensor(x)\n res = torch.zeros(x.shape[0], len(categorical_dims), dtype=torch.float32)\n for (i, var_group) in enumerate(categorical_dims):\n res[:, i] = torch.argmax(x[:, var_group], dim=-1).float()\n return res","code_tokens":"","url":569123} +{"project_name":"zomux\/deepy","file_name":"network.py","full_name":"NeuralNetwork.testing_callback","func_name":"testing_callback","docstring":"Callback for each testing iteration.","docstring_tokens":"","code":"def testing_callback(self):\n \"\"\"\n Callback for each testing iteration.\n \"\"\"\n for cb in self.training_callbacks:\n cb()","code_tokens":"","url":180983} +{"project_name":"QData\/deepWordBug","file_name":"test_util.py","full_name":"IterTreeTest.test_2_3_sideways_links","func_name":"test_2_3_sideways_links","docstring":"Tests to make sure the same directory can be encountered multiple times via links.","docstring_tokens":"","code":"def test_2_3_sideways_links(self):\n \"\"\"\n\t\tTests to make sure the same directory can be encountered multiple\n\t\ttimes via links.\n\t\t\"\"\"\n self.require_symlink()\n self.make_dirs(['Dir', 'Dir\/Target'])\n self.make_files(['Dir\/Target\/file'])\n self.make_links([('Ax', 'Dir'), ('Bx', 'Dir'), ('Cx', 'Dir\/Target'), ('Dx', 'Dir\/Target'), ('Dir\/Ex', 'Dir\/Target'), ('Dir\/Fx', 'Dir\/Target')])\n results = set(iter_tree(self.temp_dir))\n self.assertEqual(results, set(map(self.ospath, ['Ax\/Ex\/file', 'Ax\/Fx\/file', 'Ax\/Target\/file', 'Bx\/Ex\/file', 'Bx\/Fx\/file', 'Bx\/Target\/file', 'Cx\/file', 'Dx\/file', 'Dir\/Ex\/file', 'Dir\/Fx\/file', 'Dir\/Target\/file'])))","code_tokens":"","url":543758} +{"project_name":"jordipons\/sklearn-audio-transfer-learning","file_name":"audio_transfer_learning.py","full_name":"define_classification_model","func_name":"define_classification_model","docstring":"Select and define the model you will use for the classifier.","docstring_tokens":"","code":"def define_classification_model():\n \"\"\" Select and define the model you will use for the classifier. \n \"\"\"\n if config['model_type'] == 'linearSVM':\n return LinearSVC(C=1)\n elif config['model_type'] == 'SVM':\n return SVC(C=1, kernel='rbf', gamma='scale')\n elif config['model_type'] == 'kNN':\n return KNeighborsClassifier(n_neighbors=1, metric='cosine')\n elif config['model_type'] == 'perceptron':\n return SGDClassifier(max_iter=600, verbose=0.5, loss='log', learning_rate='optimal')\n elif config['model_type'] == 'MLP':\n return MLPClassifier(hidden_layer_sizes=(20,), max_iter=600, verbose=10, solver='sgd', learning_rate='constant', learning_rate_init=0.001)","code_tokens":"","url":884744} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_all_estimators.py","full_name":"TestAllObjects.test_valid_estimator_class_tags","func_name":"test_valid_estimator_class_tags","docstring":"Check that Estimator class tags are in VALID_ESTIMATOR_TAGS.","docstring_tokens":"","code":"def test_valid_estimator_class_tags(self, estimator_class):\n \"\"\"Check that Estimator class tags are in VALID_ESTIMATOR_TAGS.\"\"\"\n for tag in estimator_class.get_class_tags().keys():\n assert tag in VALID_ESTIMATOR_TAGS","code_tokens":"","url":399860} +{"project_name":"usnistgov\/chemnlp","file_name":"__init__.py","full_name":"test","func_name":"test","docstring":"Run pytest in the base of chemnlp.","docstring_tokens":"","code":"def test(*args):\n \"\"\"Run pytest in the base of chemnlp.\"\"\"\n import pytest\n path = os.path.join(os.path.split(__file__)[0], 'tests')\n pytest.main(args=[path] + list(args))","code_tokens":"","url":486121} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"has_props.py","full_name":"HasProps.query_properties_with_values","func_name":"query_properties_with_values","docstring":"Query the properties values of |HasProps| instances with a predicate.","docstring_tokens":"","code":"def query_properties_with_values(self, query, include_defaults=True):\n \"\"\" Query the properties values of |HasProps| instances with a\n predicate.\n\n Args:\n query (callable) :\n A callable that accepts property descriptors and returns True\n or False\n\n include_defaults (bool, optional) :\n Whether to include properties that have not been explicitly\n set by a user (default: True)\n\n Returns:\n dict : mapping of property names and values for matching properties\n\n \"\"\"\n themed_keys = set()\n result = dict()\n if include_defaults:\n keys = self.properties()\n else:\n keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys())\n if self.themed_values():\n themed_keys = set(self.themed_values().keys())\n keys |= themed_keys\n for key in keys:\n descriptor = self.lookup(key)\n if not query(descriptor):\n continue\n value = descriptor.serializable_value(self)\n if not include_defaults and key not in themed_keys:\n if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values:\n continue\n result[key] = value\n return result","code_tokens":"","url":977231} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"utils.py","full_name":"check_and_get_run_experiment_config","func_name":"check_and_get_run_experiment_config","docstring":"Check user input experiment_config or get it from the current Run object if exists.","docstring_tokens":"","code":"def check_and_get_run_experiment_config(experiment_config: Optional[dict]=None) -> dict:\n \"\"\"Check user input experiment_config or get it from the current Run object if exists.\n\n Args:\n experiment_config (dict): The experiment_config supplied by the user.\n\n Returns:\n dict: Return the user supplied experiment_config if it is not None.\n Otherwise fetch the experiment_config from the current Run object if exists.\n \"\"\"\n from sagemaker.experiments._run_context import _RunContext\n run_obj = _RunContext.get_current_run()\n if experiment_config:\n if run_obj:\n logger.warning('The function is invoked within an Experiment Run context but another experiment_config (%s) was supplied, so ignoring the experiment_config fetched from the Run object.', experiment_config)\n return experiment_config\n return run_obj.experiment_config if run_obj else None","code_tokens":"","url":829736} +{"project_name":"microsoft\/maro","file_name":"ddpg.py","full_name":"DDPGOps.get_actor_grad","func_name":"get_actor_grad","docstring":"Compute the actor network's gradients of a batch.","docstring_tokens":"","code":"@remote\ndef get_actor_grad(self, batch: TransitionBatch) -> Tuple[Dict[str, torch.Tensor], bool]:\n \"\"\"Compute the actor network's gradients of a batch.\n\n Args:\n batch (TransitionBatch): Batch.\n\n Returns:\n grad_dict (Dict[str, torch.Tensor]): The actor gradient of the batch.\n early_stop (bool): Early stop indicator.\n \"\"\"\n (loss, early_stop) = self._get_actor_loss(batch)\n return (self._policy.get_gradients(loss), early_stop)","code_tokens":"","url":628541} +{"project_name":"opendilab\/DI-star","file_name":"renderer_human.py","full_name":"RendererHuman.draw_overlay","func_name":"draw_overlay","docstring":"Draw the overlay describing resources.","docstring_tokens":"","code":"@sw.decorate\ndef draw_overlay(self, surf):\n \"\"\"Draw the overlay describing resources.\"\"\"\n obs = self._obs.observation\n player = obs.player_common\n surf.write_screen(self._font_large, colors.green, (0.2, 0.2), 'Minerals: %s, Vespene: %s, Food: %s \/ %s' % (player.minerals, player.vespene, player.food_used, player.food_cap))\n (times, steps) = zip(*self._game_times)\n sec = obs.game_loop \/\/ 22.4\n surf.write_screen(self._font_large, colors.green, (-0.2, 0.2), 'Score: %s, Step: %s, %.1f\/s, Time: %d:%02d' % (obs.score.score, obs.game_loop, sum(steps) \/ (sum(times) or 1), sec \/\/ 60, sec % 60), align='right')\n surf.write_screen(self._font_large, colors.green * 0.8, (-0.2, 1.2), 'APM: %d, EPM: %d, FPS: O:%.1f, R:%.1f' % (obs.score.score_details.current_apm, obs.score.score_details.current_effective_apm, len(times) \/ (sum(times) or 1), len(self._render_times) \/ (sum(self._render_times) or 1)), align='right')\n line = 3\n for (alert, ts) in sorted(self._alerts.items(), key=lambda item: item[1]):\n if time.time() < ts + 3:\n surf.write_screen(self._font_large, colors.red, (20, line), alert)\n line += 1\n else:\n del self._alerts[alert]","code_tokens":"","url":184788} +{"project_name":"krrish94\/ENet-ScanNet","file_name":"args.py","full_name":"get_arguments","func_name":"get_arguments","docstring":"Defines command-line arguments, and parses them.","docstring_tokens":"","code":"def get_arguments():\n \"\"\"Defines command-line arguments, and parses them.\n\n\t\"\"\"\n parser = ArgumentParser()\n parser.add_argument('--mode', '-m', choices=['train', 'test', 'inference', 'full'], default='train', help='train: performs training and validation; test: tests the model; inference: similar to test, but has advanced functionality, eg. saving results, etc.found in \"--save_dir\" with name \"--name\" on \"--dataset\"; full: combines train and test modes. Default: train')\n parser.add_argument('--resume', action='store_true', help='The model found in \"--checkpoint_dir\/--name\/\" and filename \"--name.h5\" is loaded.')\n parser.add_argument('--generate-images', action='store_true', help='Used in inference mode. Generates segmentation images, for visualization.')\n parser.add_argument('--arch', choices=['rgb', 'rgbd'], default='rgb', help='Select network architecture. Using RGB, or RGB-D.')\n parser.add_argument('--seg-classes', choices=['nyu40', 'scannet20'], default='nyu40', help='Choose the palette of classes learnt by the network.')\n parser.add_argument('--batch-size', '-b', type=int, default=10, help='The batch size. Default: 10')\n parser.add_argument('--epochs', type=int, default=300, help='Number of training epochs. Default: 300')\n parser.add_argument('--learning-rate', '-lr', type=float, default=0.0005, help='The learning rate. Default: 5e-4')\n parser.add_argument('--beta0', type=float, default=0.9, help='betas[0] for Adam Optimizer. Default: 0.9')\n parser.add_argument('--beta1', type=float, default=0.999, help='betas[1] for Adam Optimizer. Default: 0.999')\n parser.add_argument('--lr-decay', type=float, default=0.1, help='The learning rate decay factor. Default: 0.5')\n parser.add_argument('--lr-decay-epochs', type=int, default=100, help='The number of epochs before adjusting the learning rate. Default: 100')\n parser.add_argument('--weight-decay', '-wd', type=float, default=0.0002, help='L2 regularization factor. Default: 2e-4')\n parser.add_argument('--dataset', choices=['scannet'], default='scannet', help='Dataset to use. Default: scannet')\n parser.add_argument('--dataset-dir', type=str, default='data\/ENet', help='Path to the root directory of the selected dataset. Default: data\/ENet')\n parser.add_argument('--trainFile', type=str, default='data\/ENet\/train.txt', help='Path to txt file containing a list of training scenes.Default: data\/ENet\/train.txt')\n parser.add_argument('--valFile', type=str, default='data\/ENet\/val.txt', help='Path to txt file containing a list of validation scenes.Default: data\/ENet\/val.txt')\n parser.add_argument('--testFile', type=str, default='data\/ENet\/test.txt', help='Path to txt file containing a list of testing scenes.Default: data\/ENet\/test.txt')\n parser.add_argument('--height', type=int, default=240, help='The image height. Default: 240')\n parser.add_argument('--width', type=int, default=320, help='The image width. Default: 320')\n parser.add_argument('--weighing', choices=['enet', 'mfb', 'none'], default='ENet', help='The class weighing technique to apply to the dataset. Default: enet')\n parser.add_argument('--class-weights-file', type=str, help='Path to class weights file. Will skip class weight computation if provided.')\n parser.add_argument('--with-unlabeled', dest='ignore_unlabeled', action='store_false', help='The unlabeled class is not ignored.')\n parser.add_argument('--workers', type=int, default=4, help='Number of subprocesses to use for data loading. Default: 4')\n parser.add_argument('--print-step', type=int, help='Print loss every step')\n parser.add_argument('--imshow-batch', action='store_true', help='Displays batch images when loading the dataset and making predictions.')\n parser.add_argument('--device', default='cuda', help='Device on which the network will be trained. Default: cuda')\n parser.add_argument('--name', type=str, default='ENet', help='Name given to the model when saving. Default: ENet')\n parser.add_argument('--save-dir', type=str, default='save', help='The directory where models are saved. Default: save')\n parser.add_argument('--validate-every', type=int, default=10, help='Number of epochs after which to validate')\n return parser.parse_args()","code_tokens":"","url":561773} +{"project_name":"AlibabaResearch\/efficientteacher","file_name":"nanodet_utils.py","full_name":"bbox_center","func_name":"bbox_center","docstring":"Get bbox centers from boxes.","docstring_tokens":"","code":"def bbox_center(boxes):\n \"\"\"Get bbox centers from boxes.\n Args:\n boxes (Tensor): boxes with shape (..., 4), \"xmin, ymin, xmax, ymax\" format.\n Returns:\n Tensor: boxes centers with shape (..., 2), \"cx, cy\" format.\n \"\"\"\n boxes_cx = (boxes[..., 0] + boxes[..., 2]) \/ 2\n boxes_cy = (boxes[..., 1] + boxes[..., 3]) \/ 2\n return torch.stack([boxes_cx, boxes_cy], axis=-1)","code_tokens":"","url":560993} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"buttons.py","full_name":"Dropdown.js_on_click","func_name":"js_on_click","docstring":"Set up a JavaScript handler for button or menu item clicks.","docstring_tokens":"","code":"def js_on_click(self, handler):\n \"\"\" Set up a JavaScript handler for button or menu item clicks. \"\"\"\n self.js_on_change('value', handler)","code_tokens":"","url":977408} +{"project_name":"hamza-murad\/AALU","file_name":"natural_language_understanding_v1.py","full_name":"TokenResult.from_dict","func_name":"from_dict","docstring":"Initialize a TokenResult object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'TokenResult':\n \"\"\"Initialize a TokenResult object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['text', 'part_of_speech', 'location', 'lemma']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class TokenResult: ' + ', '.join(bad_keys))\n if 'text' in _dict:\n args['text'] = _dict.get('text')\n if 'part_of_speech' in _dict:\n args['part_of_speech'] = _dict.get('part_of_speech')\n if 'location' in _dict:\n args['location'] = _dict.get('location')\n if 'lemma' in _dict:\n args['lemma'] = _dict.get('lemma')\n return cls(**args)","code_tokens":"","url":5989} +{"project_name":"darrellsilver\/norc","file_name":"parsing.py","full_name":"parse_class","func_name":"parse_class","docstring":"Attempts to import a class at the given path and return it.","docstring_tokens":"","code":"def parse_class(class_path):\n \"\"\"Attempts to import a class at the given path and return it.\"\"\"\n parts = class_path.split('.')\n module = '.'.join(parts[:-1])\n class_name = parts[-1]\n if len(parts) < 2:\n raise Exception('Invalid path \"%s\". Must be of the form \"x.Y\".' % class_path)\n try:\n imported = __import__(module, globals(), locals(), [class_name])\n return getattr(imported, class_name)\n except ImportError:\n return None","code_tokens":"","url":249500} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"ffmpeg_ops.py","full_name":"encode_audio","func_name":"encode_audio","docstring":"Creates an op that encodes an audio file using sampled audio from a tensor.","docstring_tokens":"","code":"def encode_audio(audio, file_format=None, samples_per_second=None):\n \"\"\"Creates an op that encodes an audio file using sampled audio from a tensor.\n\n Args:\n audio: A rank 2 tensor that has time along dimension 0 and channels along\n dimension 1. Dimension 0 is `samples_per_second * length` long in\n seconds.\n file_format: The type of file to encode. \"wav\" is the only supported format.\n samples_per_second: The number of samples in the audio tensor per second of\n audio.\n\n Returns:\n A scalar tensor that contains the encoded audio in the specified file\n format.\n \"\"\"\n return gen_encode_audio_op_py.encode_audio(audio, file_format=file_format, samples_per_second=samples_per_second)","code_tokens":"","url":181286} +{"project_name":"instadeepai\/jumanji","file_name":"env_test.py","full_name":"test_robot_warehouse__agent_observation","func_name":"test_robot_warehouse__agent_observation","docstring":"Validate the agent observation function.","docstring_tokens":"","code":"def test_robot_warehouse__agent_observation(deterministic_robot_warehouse_env: Tuple[RobotWarehouse, State, TimeStep]) -> None:\n \"\"\"Validate the agent observation function.\"\"\"\n (env, state, timestep) = deterministic_robot_warehouse_env\n (state, timestep) = env.step(state, jnp.array([0, 0]))\n agent1_own_view = jnp.array([3, 4, 0, 0, 0, 1, 0, 1])\n agent1_other_agents_view = jnp.array(8 * [0, 0, 0, 0, 0])\n agent1_shelf_view = jnp.array(9 * [0, 0])\n agent1_obs = jnp.hstack([agent1_own_view, agent1_other_agents_view, agent1_shelf_view])\n agent2_own_view = jnp.array([1, 7, 0, 0, 0, 0, 1, 0])\n agent2_other_agents_view = jnp.array(8 * [0, 0, 0, 0, 0])\n agent2_shelf_view = jnp.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1])\n agent2_obs = jnp.hstack([agent2_own_view, agent2_other_agents_view, agent2_shelf_view])\n assert jnp.all(timestep.observation.agents_view[0] == agent1_obs)\n assert jnp.all(timestep.observation.agents_view[1] == agent2_obs)","code_tokens":"","url":594462} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.ntupledata","func_name":"ntupledata","docstring":"number of objects in all tuple fields.","docstring_tokens":"","code":"@property\ndef ntupledata(self):\n \"\"\"number of objects in all tuple fields.\"\"\"\n return self._ptr.contents.ntupledata","code_tokens":"","url":440213} +{"project_name":"SurakshaRV\/AI-Lab1BM17CS108","file_name":"forawrd_reasoning.py","full_name":"dissociate","func_name":"dissociate","docstring":"Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args).","docstring_tokens":"","code":"def dissociate(op, args):\n \"\"\"Given an associative op, return a flattened list result such\n that Expr(op, *result) means the same as Expr(op, *args).\"\"\"\n result = []\n\n def collect(subargs):\n for arg in subargs:\n if arg.op == op:\n collect(arg.args)\n else:\n result.append(arg)\n collect(args)\n return result","code_tokens":"","url":24661} +{"project_name":"dstallmann\/transfer_learning_twinvae","file_name":"DeepView.py","full_name":"DeepView.update_matrix","func_name":"update_matrix","docstring":"When new distance values are calculated this merges old and new distances into the same matrix.","docstring_tokens":"","code":"def update_matrix(self, old_matrix, new_values, n_new, n_keep):\n \"\"\"\n\t\tWhen new distance values are calculated this merges old \n\t\tand new distances into the same matrix.\n\t\t\"\"\"\n to_triu = np.triu(old_matrix, k=1)\n new_mat = np.zeros([self.num_samples, self.num_samples])\n new_mat[n_new:, n_new:] = to_triu[:n_keep, :n_keep]\n new_mat[:n_new] = new_values\n return new_mat + new_mat.transpose()","code_tokens":"","url":964685} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"api.py","full_name":"CCGVar.can_unify","func_name":"can_unify","docstring":"If the variable can be replaced with other a substitution is returned.","docstring_tokens":"","code":"def can_unify(self, other):\n \"\"\" If the variable can be replaced with other\n a substitution is returned.\n \"\"\"\n if other.is_primitive() or not self._prim_only:\n return [(self, other)]\n return None","code_tokens":"","url":529933} +{"project_name":"deepset-ai\/FARM","file_name":"processor.py","full_name":"Processor.generate_config","func_name":"generate_config","docstring":"Generates config file from Class and instance attributes (only for sensible config parameters).","docstring_tokens":"","code":"def generate_config(self):\n \"\"\"\n Generates config file from Class and instance attributes (only for sensible config parameters).\n \"\"\"\n config = {}\n for (key, value) in inspect.getmembers(self):\n if is_json(value) and key[0] != '_':\n if issubclass(type(value), Path):\n value = str(value)\n config[key] = value\n return config","code_tokens":"","url":559331} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"logging.py","full_name":"IndentingFormatter.format","func_name":"format","docstring":"Calls the standard formatter, but will indent all of the log message lines by our current indentation level.","docstring_tokens":"","code":"def format(self, record):\n \"\"\"\n Calls the standard formatter, but will indent all of the log message\n lines by our current indentation level.\n \"\"\"\n formatted = super(IndentingFormatter, self).format(record)\n message_start = self.get_message_start(formatted, record.levelno)\n formatted = message_start + formatted\n prefix = ''\n if self.add_timestamp:\n t = self.formatTime(record, '%Y-%m-%dT%H:%M:%S')\n prefix = '%s,%03d ' % (t, record.msecs)\n prefix += ' ' * get_indentation()\n formatted = ''.join([prefix + line for line in formatted.splitlines(True)])\n return formatted","code_tokens":"","url":83796} +{"project_name":"xuannianz\/FSAF","file_name":"resnet.py","full_name":"ResNetBackbone.preprocess_image","func_name":"preprocess_image","docstring":"Takes as input an image and prepares it for being passed through the network.","docstring_tokens":"","code":"def preprocess_image(self, inputs):\n \"\"\"\n Takes as input an image and prepares it for being passed through the network.\n \"\"\"\n return preprocess_image(inputs, mode='caffe')","code_tokens":"","url":565122} +{"project_name":"mideind\/GreynirServer","file_name":"utility.py","full_name":"sanitize_filename","func_name":"sanitize_filename","docstring":"Sanitize a potential filename string by limiting allowed characters.","docstring_tokens":"","code":"def sanitize_filename(fn: str, maxlen: int=60) -> str:\n \"\"\"Sanitize a potential filename string by limiting allowed characters.\"\"\"\n assert maxlen >= 1, 'maxlen must be positive'\n ALLOWED_FILE_CHARS = string.ascii_letters + string.digits + '._-'\n fn = '_'.join([t for t in fn.lower().split()])\n fn = ''.join((c for c in icelandic_asciify(fn) if c in ALLOWED_FILE_CHARS))[:maxlen].rstrip('._')\n return fn","code_tokens":"","url":581036} +{"project_name":"som-shahlab\/femr","file_name":"__init__.py","full_name":"EventCollection.reader","func_name":"reader","docstring":"Return a contextmanager that allows iteration over all of the events.","docstring_tokens":"","code":"@contextlib.contextmanager\ndef reader(self) -> Iterator[Iterable[Tuple[int, RawEvent]]]:\n \"\"\"Return a contextmanager that allows iteration over all of the events.\"\"\"\n with contextlib.ExitStack() as stack:\n sub_readers = [stack.enter_context(reader()) for reader in self.sharded_readers()]\n yield itertools.chain.from_iterable(sub_readers)","code_tokens":"","url":179768} +{"project_name":"cts198859\/deeprl_network","file_name":"cacc_env.py","full_name":"OVMCarFollowing.get_accel","func_name":"get_accel","docstring":"Get target acceleration using OVM controller.","docstring_tokens":"","code":"def get_accel(self, v, v_lead, h, alpha, beta, h_go=-1):\n \"\"\"\n Get target acceleration using OVM controller.\n\n Args:\n v (float): current vehicle speed\n v_lead (float): leading vehicle speed\n h (float): current headway\n alpha, beta (float): human parameters\n Returns:\n accel (float): target acceleration\n \"\"\"\n vh = self.get_vh(h, h_go=h_go)\n return alpha * (vh - v) + beta * (v_lead - v)","code_tokens":"","url":180772} +{"project_name":"funkelab\/gunpowder","file_name":"batch_provider.py","full_name":"BatchProvider.request_batch","func_name":"request_batch","docstring":"Request a batch from this provider.","docstring_tokens":"","code":"def request_batch(self, request):\n \"\"\"Request a batch from this provider.\n\n Args:\n\n request (:class:`BatchRequest`):\n\n A request containing (possibly partial)\n :class:`ArraySpecs` and\n :class:`GraphSpecs`.\n \"\"\"\n batch = None\n try:\n self.set_seeds(request)\n logger.debug('%s got request %s', self.name(), request)\n self.check_request_consistency(request)\n upstream_request = request.copy()\n if self.remove_placeholders:\n upstream_request.remove_placeholders()\n batch = self.provide(upstream_request)\n request.remove_placeholders()\n self.check_batch_consistency(batch, request)\n self.remove_unneeded(batch, request)\n logger.debug('%s provides %s', self.name(), batch)\n except Exception as e:\n raise BatchRequestError(self, request, batch) from e\n return batch","code_tokens":"","url":572775} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"smtplib.py","full_name":"SMTP.send","func_name":"send","docstring":"Send `s' to the server.","docstring_tokens":"","code":"def send(self, s):\n \"\"\"Send `s' to the server.\"\"\"\n if self.debuglevel > 0:\n self._print_debug('send:', repr(s))\n if hasattr(self, 'sock') and self.sock:\n if isinstance(s, str):\n s = s.encode(self.command_encoding)\n try:\n self.sock.sendall(s)\n except OSError:\n self.close()\n raise SMTPServerDisconnected('Server not connected')\n else:\n raise SMTPServerDisconnected('please run connect() first')","code_tokens":"","url":429456} +{"project_name":"Yuting-Gao\/DisCo-pytorch","file_name":"selecsls.py","full_name":"selecsls60","func_name":"selecsls60","docstring":"Constructs a SelecSLS60 model.","docstring_tokens":"","code":"@register_model\ndef selecsls60(pretrained=False, **kwargs):\n \"\"\"Constructs a SelecSLS60 model.\n \"\"\"\n return _create_selecsls('selecsls60', pretrained, kwargs)","code_tokens":"","url":186603} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"skip_thoughts_model.py","full_name":"SkipThoughtsModel.build","func_name":"build","docstring":"Creates all ops for training, evaluation or encoding.","docstring_tokens":"","code":"def build(self):\n \"\"\"Creates all ops for training, evaluation or encoding.\"\"\"\n self.build_inputs()\n self.build_word_embeddings()\n self.build_encoder()\n self.build_decoders()\n self.build_loss()\n self.build_global_step()","code_tokens":"","url":586370} +{"project_name":"rudranil723\/mini-main","file_name":"simple.py","full_name":"SimpleFilter.GetFilterVersion","func_name":"GetFilterVersion","docstring":"Called by the ISAPI framework to get the extension version The default implementation uses the classes docstring to set the extension description, and uses the classes filter_flags attribute to set the ISAPI filter flags - you must specify filter_flags in your class.","docstring_tokens":"","code":"def GetFilterVersion(self, fv):\n \"\"\"Called by the ISAPI framework to get the extension version\n\n The default implementation uses the classes docstring to\n set the extension description, and uses the classes\n filter_flags attribute to set the ISAPI filter flags - you\n must specify filter_flags in your class.\n \"\"\"\n if self.filter_flags is None:\n raise RuntimeError('You must specify the filter flags')\n if fv is not None:\n fv.Flags = self.filter_flags\n fv.FilterDesc = self.__doc__","code_tokens":"","url":318784} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"inference_utils.py","full_name":"get_numeric_feature_names","func_name":"get_numeric_feature_names","docstring":"Returns a list of feature names for float and int64 type features.","docstring_tokens":"","code":"def get_numeric_feature_names(example):\n \"\"\"Returns a list of feature names for float and int64 type features.\n\n Args:\n example: A tf.train.Example.\n\n Returns:\n A list of string feature names.\n \"\"\"\n numeric_features = ('float_list', 'int64_list')\n features = example.features.feature\n return sorted([feature_name for feature_name in features if features[feature_name].WhichOneof('kind') in numeric_features])","code_tokens":"","url":312236} +{"project_name":"IceClear\/MW-GAN","file_name":"duf_arch.py","full_name":"DynamicUpsamplingFilter.forward","func_name":"forward","docstring":"Forward function for DynamicUpsamplingFilter.","docstring_tokens":"","code":"def forward(self, x, filters):\n \"\"\"Forward function for DynamicUpsamplingFilter.\n\n Args:\n x (Tensor): Input image with 3 channels. The shape is (n, 3, h, w).\n filters (Tensor): Generated dynamic filters.\n The shape is (n, filter_prod, upsampling_square, h, w).\n filter_prod: prod of filter kenrel size, e.g., 1*5*5=25.\n upsampling_square: similar to pixel shuffle,\n upsampling_square = upsampling * upsampling\n e.g., for x 4 upsampling, upsampling_square= 4*4 = 16\n\n Returns:\n Tensor: Filtered image with shape (n, 3*upsampling_square, h, w)\n \"\"\"\n (n, filter_prod, upsampling_square, h, w) = filters.size()\n (kh, kw) = self.filter_size\n expanded_input = F.conv2d(x, self.expansion_filter.to(x), padding=(kh \/\/ 2, kw \/\/ 2), groups=3)\n expanded_input = expanded_input.view(n, 3, filter_prod, h, w).permute(0, 3, 4, 1, 2)\n filters = filters.permute(0, 3, 4, 1, 2)\n out = torch.matmul(expanded_input, filters)\n return out.permute(0, 3, 4, 1, 2).view(n, 3 * upsampling_square, h, w)","code_tokens":"","url":651429} +{"project_name":"ameet-1997\/AttentionGuidance","file_name":"lm_seqs_dataset.py","full_name":"LmSeqsDataset.remove_long_sequences","func_name":"remove_long_sequences","docstring":"Sequences that are too long are splitted by chunk of max_model_input_size.","docstring_tokens":"","code":"def remove_long_sequences(self):\n \"\"\"\n Sequences that are too long are splitted by chunk of max_model_input_size.\n \"\"\"\n max_len = self.params.max_model_input_size\n indices = self.lengths > max_len\n logger.info(f'Splitting {sum(indices)} too long sequences.')\n\n def divide_chunks(l, n):\n return [l[i:i + n] for i in range(0, len(l), n)]\n new_tok_ids = []\n new_lengths = []\n if self.params.mlm:\n (cls_id, sep_id) = (self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'])\n else:\n (cls_id, sep_id) = (self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'])\n for (seq_, len_) in zip(self.token_ids, self.lengths):\n assert seq_[0] == cls_id and seq_[-1] == sep_id, seq_\n if len_ <= max_len:\n new_tok_ids.append(seq_)\n new_lengths.append(len_)\n else:\n sub_seqs = []\n for sub_s in divide_chunks(seq_, max_len - 2):\n if sub_s[0] != cls_id:\n sub_s = np.insert(sub_s, 0, cls_id)\n if sub_s[-1] != sep_id:\n sub_s = np.insert(sub_s, len(sub_s), sep_id)\n assert len(sub_s) <= max_len\n assert sub_s[0] == cls_id and sub_s[-1] == sep_id, sub_s\n sub_seqs.append(sub_s)\n new_tok_ids.extend(sub_seqs)\n new_lengths.extend([len(l) for l in sub_seqs])\n self.token_ids = np.array(new_tok_ids)\n self.lengths = np.array(new_lengths)","code_tokens":"","url":92792} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"f_measure.py","full_name":"FMeasure.f_measure","func_name":"f_measure","docstring":"Returns the f-measure as ScoreMetric.","docstring_tokens":"","code":"@property\ndef f_measure(self) -> ScoreMetric:\n \"\"\"Returns the f-measure as ScoreMetric.\"\"\"\n return self._f_measure","code_tokens":"","url":918760} +{"project_name":"tum-pbs\/PhiFlow","file_name":"_scene.py","full_name":"Scene.fieldnames","func_name":"fieldnames","docstring":"Determines all field names present in this `Scene`, independent of frame.","docstring_tokens":"","code":"@property\ndef fieldnames(self) -> tuple:\n \"\"\" Determines all field names present in this `Scene`, independent of frame. \"\"\"\n return get_fieldnames(self.path)","code_tokens":"","url":768836} +{"project_name":"intel\/neural-compressor","file_name":"calibrator.py","full_name":"calib_registry","func_name":"calib_registry","docstring":"The class decorator used to register all Calibrator subclasses.","docstring_tokens":"","code":"def calib_registry(calib_method):\n \"\"\"The class decorator used to register all Calibrator subclasses.\"\"\"\n\n def decorator_calib(cls):\n assert cls.__name__.endswith('Calibrator'), \"The name of subclass of Calibrator should end with 'Calibrator' substring.\"\n if cls.__name__[:-len('Calibrator')] in CALIBRATOR:\n raise ValueError('Cannot have two operators with the same name.')\n CALIBRATOR[calib_method.strip()] = cls\n return cls\n return decorator_calib","code_tokens":"","url":737450} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"schema.py","full_name":"Schemas.get","func_name":"get","docstring":"Get deserialized JSON schema from the schema name.","docstring_tokens":"","code":"def get(self, name, default=None):\n \"\"\"Get deserialized JSON schema from the schema name.\n\n Args:\n name: string, Schema name.\n default: object, return value if name not found.\n \"\"\"\n return self.schemas.get(name, default)","code_tokens":"","url":215528} +{"project_name":"erikdelange\/Reinforcement-Learning-Maze","file_name":"abstractmodel.py","full_name":"AbstractModel.q","func_name":"q","docstring":"Return q values for state.","docstring_tokens":"","code":"@abstractmethod\ndef q(self, state):\n \"\"\" Return q values for state. \"\"\"\n pass","code_tokens":"","url":286459} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"encoders.py","full_name":"encode_7or8bit","func_name":"encode_7or8bit","docstring":"Set the Content-Transfer-Encoding header to 7bit or 8bit.","docstring_tokens":"","code":"def encode_7or8bit(msg):\n \"\"\"Set the Content-Transfer-Encoding header to 7bit or 8bit.\"\"\"\n orig = msg.get_payload()\n if orig is None:\n msg['Content-Transfer-Encoding'] = '7bit'\n return\n try:\n if isinstance(orig, str):\n orig.encode('ascii')\n else:\n orig.decode('ascii')\n except UnicodeError:\n charset = msg.get_charset()\n output_cset = charset and charset.output_charset\n if output_cset and output_cset.lower().startswith('iso-2022-'):\n msg['Content-Transfer-Encoding'] = '7bit'\n else:\n msg['Content-Transfer-Encoding'] = '8bit'\n else:\n msg['Content-Transfer-Encoding'] = '7bit'\n if not isinstance(orig, str):\n msg.set_payload(orig.decode('ascii', 'surrogateescape'))","code_tokens":"","url":36741} +{"project_name":"matsu0228\/nlp-jp","file_name":"layer1_decisions.py","full_name":"Layer1Decisions.request_cancel_external_workflow_execution","func_name":"request_cancel_external_workflow_execution","docstring":"Requests that a request be made to cancel the specified external workflow execution and records a RequestCancelExternalWorkflowExecutionInitiated event in the history.","docstring_tokens":"","code":"def request_cancel_external_workflow_execution(self, workflow_id, control=None, run_id=None):\n \"\"\"\n Requests that a request be made to cancel the specified\n external workflow execution and records a\n RequestCancelExternalWorkflowExecutionInitiated event in the\n history.\n \"\"\"\n o = {}\n o['decisionType'] = 'RequestCancelExternalWorkflowExecution'\n attrs = o['requestCancelExternalWorkflowExecutionDecisionAttributes'] = {}\n attrs['workflowId'] = workflow_id\n if control is not None:\n attrs['control'] = control\n if run_id is not None:\n attrs['runId'] = run_id\n self._data.append(o)","code_tokens":"","url":785459} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"pathlib.py","full_name":"Path.is_socket","func_name":"is_socket","docstring":"Whether this path is a socket.","docstring_tokens":"","code":"def is_socket(self):\n \"\"\"\n Whether this path is a socket.\n \"\"\"\n try:\n return S_ISSOCK(self.stat().st_mode)\n except OSError as e:\n if e.errno not in (ENOENT, ENOTDIR):\n raise\n return False","code_tokens":"","url":429097} +{"project_name":"rudranil723\/mini-main","file_name":"diagnose.py","full_name":"rsentence","func_name":"rsentence","docstring":"Generate a random sentence-like string.","docstring_tokens":"","code":"def rsentence(length=4):\n \"\"\"Generate a random sentence-like string.\"\"\"\n return ' '.join((rword(random.randint(4, 9)) for i in range(length)))","code_tokens":"","url":314163} +{"project_name":"befelix\/safe_learning","file_name":"test_utilities.py","full_name":"test_unique_rows","func_name":"test_unique_rows","docstring":"Test the unique_rows function.","docstring_tokens":"","code":"def test_unique_rows():\n \"\"\"Test the unique_rows function.\"\"\"\n a = np.array([[1, 1], [1, 2], [1, 3], [1, 2], [1, 3], [1, 4], [2, 3]])\n uniques = np.array([[1, 1], [1, 2], [1, 3], [1, 4], [2, 3]])\n assert_allclose(unique_rows(a), uniques)","code_tokens":"","url":328257} +{"project_name":"tensorflow\/agents","file_name":"rnn_wrapper.py","full_name":"RNNWrapper.wrapped_layer","func_name":"wrapped_layer","docstring":"Return the wrapped RNN layer.","docstring_tokens":"","code":"@property\ndef wrapped_layer(self) -> tf.keras.layers.RNN:\n \"\"\"Return the wrapped RNN layer.\"\"\"\n return self._layer","code_tokens":"","url":22779} +{"project_name":"boris-kz\/CogAlg","file_name":"frame_blobs_sign_map_Khanh.py","full_name":"calc_sign","func_name":"calc_sign","docstring":"Compute ternary sign per rdert.","docstring_tokens":"","code":"def calc_sign(g__, g3__, ave=ave_2x2, ave3=ave_3x3):\n \"\"\"Compute ternary sign per rdert.\"\"\"\n vg__ = g__ - ave\n vg3__ = g3__ - ave3\n bs__ = vg__ > 0\n bs3__ = vg3__ > 0\n temp_s__ = bs__[1:, 1:] | bs__[1:, :-1] | bs__[:-1, 1:] | bs__[:-1, :-1]\n s__ = ~temp_s__ * 1 + (~temp_s__ & ~bs3__)\n return (s__, vg__, vg3__)","code_tokens":"","url":495966} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"reporters.py","full_name":"BaseReporter.ending","func_name":"ending","docstring":"Called before the resolution ends successfully.","docstring_tokens":"","code":"def ending(self, state):\n \"\"\"Called before the resolution ends successfully.\n \"\"\"","code_tokens":"","url":99129} +{"project_name":"Mephisto405\/WCMC","file_name":"metrics.py","full_name":"L1","func_name":"L1","docstring":"Absolute error between images.","docstring_tokens":"","code":"def L1(im, ref, reduce=True):\n \"\"\"Absolute error between images.\n Args:\n im(np.array): image to test.\n ref(np.array): reference for the comparison.\n Returns:\n (float) error value.\n \"\"\"\n return np.abs(im - ref).mean() if reduce else np.abs(im - ref)","code_tokens":"","url":373073} +{"project_name":"johnathanlouie\/cascaded-refinement-network","file_name":"models.py","full_name":"append_layer","func_name":"append_layer","docstring":"Each module has a 3x3 convolutional layer with LReLU for activation followed by batch normalization.","docstring_tokens":"","code":"def append_layer(x, fnum, conv, bn):\n \"\"\"Each module has a 3x3 convolutional layer with LReLU for activation followed by batch normalization.\"\"\"\n x = Conv2D(filters=fnum, kernel_size=3, padding='same', name=conv)(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = BatchNormalization(name=bn)(x)\n return x","code_tokens":"","url":456271} +{"project_name":"alexjc\/neural-doodle","file_name":"doodle.py","full_name":"NeuralGenerator.run","func_name":"run","docstring":"The main entry point for the application, runs through multiple phases at increasing resolutions.","docstring_tokens":"","code":"def run(self):\n \"\"\"The main entry point for the application, runs through multiple phases at increasing resolutions.\n \"\"\"\n (self.frame, Xn) = (0, None)\n for i in range(args.phases):\n self.error = 255.0\n scale = 1.0 \/ 2.0 ** (args.phases - 1 - i)\n shape = self.content_img_original.shape\n print('\\n{}Phase #{}: resolution {}x{} scale {}{}'.format(ansi.BLUE_B, i, int(shape[1] * scale), int(shape[0] * scale), scale, ansi.BLUE))\n self.model.setup(layers=['sem' + l for l in self.style_layers] + ['conv' + l for l in self.content_layers])\n self.prepare_content(scale)\n self.prepare_style(scale)\n self.model.setup(layers=['sem' + l for l in self.style_layers] + ['conv' + l for l in self.used_layers])\n self.prepare_optimization()\n print('{}'.format(ansi.ENDC))\n shape = self.content_img.shape[2:]\n if args.seed == 'content':\n Xn = self.content_img[0] + self.model.pixel_mean\n if args.seed == 'noise':\n bounds = [int(i) for i in args.seed_range.split(':')]\n Xn = np.random.uniform(bounds[0], bounds[1], shape + (3,)).astype(np.float32)\n if args.seed == 'previous':\n Xn = scipy.misc.imresize(Xn[0], shape, interp='bicubic')\n Xn = Xn.transpose((2, 0, 1))[np.newaxis]\n if os.path.exists(args.seed):\n seed_image = scipy.ndimage.imread(args.seed, mode='RGB')\n seed_image = scipy.misc.imresize(seed_image, shape, interp='bicubic')\n self.seed_image = self.model.prepare_image(seed_image)\n Xn = self.seed_image[0] + self.model.pixel_mean\n if Xn is None:\n error('Seed for optimization was not found. You can either...', ' - Set the `--seed` to `content` or `noise`.', ' - Specify `--seed` as a valid filename.')\n data_bounds = np.zeros((np.product(Xn.shape), 2), dtype=np.float64)\n data_bounds[:] = (0.0, 255.0)\n (self.iter_time, self.iteration, interrupt) = (time.time(), 0, False)\n try:\n (Xn, Vn, info) = scipy.optimize.fmin_l_bfgs_b(self.evaluate, Xn.astype(np.float64).flatten(), bounds=data_bounds, factr=0.0, pgtol=0.0, m=5, maxfun=args.iterations - 1, iprint=-1)\n except OverflowError:\n error('The optimization diverged and NaNs were encountered.', ' - Try using a different `--device` or change the parameters.', ' - Make sure libraries are updated to work around platform bugs.')\n except KeyboardInterrupt:\n interrupt = True\n args.seed = 'previous'\n resolution = self.content_img.shape\n Xn = Xn.reshape(resolution)\n output = self.model.finalize_image(Xn[0], self.content_img_original.shape)\n scipy.misc.toimage(output, cmin=0, cmax=255).save(args.output)\n if interrupt:\n break\n status = 'finished in' if not interrupt else 'interrupted at'\n print('\\n{}Optimization {} {:3.1f}s, average pixel error {:3.1f}!{}\\n'.format(ansi.CYAN, status, time.time() - self.start_time, self.error, ansi.ENDC))","code_tokens":"","url":721900} +{"project_name":"mcao516\/Autoregressive-VAE","file_name":"model.py","full_name":"Model.train_epoch","func_name":"train_epoch","docstring":"Train the model for one single epoch.","docstring_tokens":"","code":"def train_epoch(self, train_dataloader, optimizer, epoch):\n \"\"\"Train the model for one single epoch.\n \"\"\"\n self.model.train()\n epoch_iterator = tqdm(train_dataloader, desc='Iteration')\n train_loss = 0.0\n for (i, batch) in enumerate(epoch_iterator):\n batch = {k: v.to(self.args.device) for (k, v) in batch.items()}\n (batch_loss, _) = self.loss_batch(batch['target'], batch['target'], optimizer=optimizer, step=i)\n train_loss += batch_loss\n if self.writer:\n self.writer.add_scalar('batch_loss', batch_loss, epoch * len(train_dataloader) + i + 1)\n epoch_loss = train_loss \/ len(train_dataloader)\n self.scheduler.step()\n return epoch_loss","code_tokens":"","url":420372} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_stacking.py","full_name":"test_stacking_classifier_multilabel_auto_predict","func_name":"test_stacking_classifier_multilabel_auto_predict","docstring":"Check the behaviour for the multilabel classification case for stack methods supported for all estimators or automatically picked up.","docstring_tokens":"","code":"@pytest.mark.parametrize('stack_method', ['auto', 'predict'])\n@pytest.mark.parametrize('passthrough', [False, True])\ndef test_stacking_classifier_multilabel_auto_predict(stack_method, passthrough):\n \"\"\"Check the behaviour for the multilabel classification case for stack methods\n supported for all estimators or automatically picked up.\n \"\"\"\n (X_train, X_test, y_train, y_test) = train_test_split(X_multilabel, y_multilabel, stratify=y_multilabel, random_state=42)\n y_train_before_fit = y_train.copy()\n n_outputs = 3\n estimators = [('mlp', MLPClassifier(random_state=42)), ('rf', RandomForestClassifier(random_state=42)), ('ridge', RidgeClassifier())]\n final_estimator = KNeighborsClassifier()\n clf = StackingClassifier(estimators=estimators, final_estimator=final_estimator, passthrough=passthrough, stack_method=stack_method).fit(X_train, y_train)\n assert_array_equal(y_train_before_fit, y_train)\n y_pred = clf.predict(X_test)\n assert y_pred.shape == y_test.shape\n if stack_method == 'auto':\n expected_stack_methods = ['predict_proba', 'predict_proba', 'decision_function']\n else:\n expected_stack_methods = ['predict'] * len(estimators)\n assert clf.stack_method_ == expected_stack_methods\n n_features_X_trans = n_outputs * len(estimators)\n if passthrough:\n n_features_X_trans += X_train.shape[1]\n X_trans = clf.transform(X_test)\n assert X_trans.shape == (X_test.shape[0], n_features_X_trans)\n assert_array_equal(clf.classes_, [np.array([0, 1])] * n_outputs)","code_tokens":"","url":853197} +{"project_name":"ifwe\/digsby","file_name":"buddyliststore.py","full_name":"BuddyListStore.add_tofrom","func_name":"add_tofrom","docstring":"Add a new entry in the to\/from history list.","docstring_tokens":"","code":"def add_tofrom(self, history_type, to, from_):\n \"\"\"Add a new entry in the to\/from history list.\"\"\"\n self.dispatch.add_tofrom(history_type, to, from_)\n self._info_changed('tofrom_timer', TOFROM_UPDATE_FREQ_SECS)","code_tokens":"","url":185206} +{"project_name":"Eric3911\/OpenAGI","file_name":"data_preprocessing.py","full_name":"check_chinese_char","func_name":"check_chinese_char","docstring":"Check if a character is in Chinese.","docstring_tokens":"","code":"def check_chinese_char(ch):\n \"\"\"Check if a character is in Chinese.\"\"\"\n if '\u4e00' <= ch <= '\\u9fff' or ch in chinese_punctuation:\n return True\n else:\n return False","code_tokens":"","url":273166} +{"project_name":"google-research\/scenic","file_name":"vivit_multimodal.py","full_name":"ViViTMultiMaskedAutoencoder.apply_decoder_projection","func_name":"apply_decoder_projection","docstring":"Project the unmasked tokens to decoder latent space dimension.","docstring_tokens":"","code":"def apply_decoder_projection(self, x_unmasked_encoded_dict: ArrayDict) -> ArrayDict:\n \"\"\"Project the unmasked tokens to decoder latent space dimension.\"\"\"\n x_unmasked_proj_dict = {}\n for (key, x_unmasked_encoded) in x_unmasked_encoded_dict.items():\n x_unmasked_proj = nn.Dense(self.decoder_config.hidden_size, use_bias=self.decoder_config.get('use_projection_bias', True), kernel_init=nn.initializers.xavier_uniform(), name=f'decoder_projection_{key}')(x_unmasked_encoded)\n x_unmasked_proj_dict[key] = x_unmasked_proj\n return x_unmasked_proj_dict","code_tokens":"","url":846469} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"preprocessor_builder_test.py","full_name":"PreprocessorBuilderTest.assert_dictionary_close","func_name":"assert_dictionary_close","docstring":"Helper to check if two dicts with floatst or integers are close.","docstring_tokens":"","code":"def assert_dictionary_close(self, dict1, dict2):\n \"\"\"Helper to check if two dicts with floatst or integers are close.\"\"\"\n self.assertEqual(sorted(dict1.keys()), sorted(dict2.keys()))\n for key in dict1:\n value = dict1[key]\n if isinstance(value, float):\n self.assertAlmostEqual(value, dict2[key])\n else:\n self.assertEqual(value, dict2[key])","code_tokens":"","url":852086} +{"project_name":"ludwig-ai\/ludwig","file_name":"llm.py","full_name":"LLM.get_augmentation_pipelines","func_name":"get_augmentation_pipelines","docstring":"Returns the augmentation pipeline for this model.","docstring_tokens":"","code":"@staticmethod\ndef get_augmentation_pipelines() -> AugmentationPipelines:\n \"\"\"Returns the augmentation pipeline for this model.\"\"\"\n return AugmentationPipelines({})","code_tokens":"","url":616883} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"deprecations.py","full_name":"deprecated_function","func_name":"deprecated_function","docstring":"Wrap a function with a deprecation warning.","docstring_tokens":"","code":"def deprecated_function(func, name):\n \"\"\"Wrap a function with a deprecation warning.\n\n Args:\n func: Function to wrap in a deprecation warning.\n name: The name that has been deprecated.\n\n Returns:\n The modified function\n \"\"\"\n\n def deprecate(*args, **kwargs):\n renamed_warning(f'The {name}')\n return func(*args, **kwargs)\n return deprecate","code_tokens":"","url":829429} +{"project_name":"deepmind\/meltingpot","file_name":"predator_prey.py","full_name":"build","func_name":"build","docstring":"Build predator_and_prey substrate given player roles.","docstring_tokens":"","code":"def build(roles: Sequence[str], config: configdict.ConfigDict) -> Mapping[str, Any]:\n \"\"\"Build predator_and_prey substrate given player roles.\"\"\"\n num_players = len(roles)\n avatar_objects_and_helpers = []\n for (player_idx, role) in enumerate(roles):\n if role == 'prey':\n avatar_objects_and_helpers.extend(_build_prey_objects(player_idx))\n elif role == 'predator':\n avatar_objects_and_helpers.extend(_build_predator_objects(player_idx))\n else:\n raise ValueError(f'Unrecognized role: {role}')\n substrate_definition = dict(levelName='predator_prey', levelDirectory='meltingpot\/lua\/levels', numPlayers=num_players, maxEpisodeLengthFrames=1000, spriteSize=8, topology='BOUNDED', simulation=dict(map=config.layout.ascii_map, gameObjects=avatar_objects_and_helpers, scene=create_scene(), prefabs=create_prefabs(apple_reward=config.apple_reward), charPrefabMap=config.layout.char_prefab_map))\n return substrate_definition","code_tokens":"","url":285407} +{"project_name":"explosion\/spaCy","file_name":"test_matcher_api.py","full_name":"test_matcher_any_token_operator","func_name":"test_matcher_any_token_operator","docstring":"Test that patterns with \"any token\" {} work with operators.","docstring_tokens":"","code":"def test_matcher_any_token_operator(en_vocab):\n \"\"\"Test that patterns with \"any token\" {} work with operators.\"\"\"\n matcher = Matcher(en_vocab)\n matcher.add('TEST', [[{'ORTH': 'test'}, {'OP': '*'}]])\n doc = Doc(en_vocab, words=['test', 'hello', 'world'])\n matches = [doc[start:end].text for (_, start, end) in matcher(doc)]\n assert len(matches) == 3\n assert matches[0] == 'test'\n assert matches[1] == 'test hello'\n assert matches[2] == 'test hello world'","code_tokens":"","url":894197} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"mesh_tensorflow.py","full_name":"MeshImpl.slice_shape","func_name":"slice_shape","docstring":"Shape of each slice of the Tensor.","docstring_tokens":"","code":"def slice_shape(self, tensor_shape):\n \"\"\"Shape of each slice of the Tensor.\n\n Args:\n tensor_shape: Shape.\n\n Returns:\n list of integers with length tensor_shape.ndims.\n\n Raises:\n ValueError: If a Tensor dimension is not divisible by the corresponding\n Mesh dimension.\n \"\"\"\n tensor_layout = self.tensor_layout(tensor_shape)\n ret = []\n for (tensor_dim, mesh_axis) in zip(tensor_shape, tensor_layout.tensor_axis_to_mesh_axis):\n if mesh_axis is None:\n ret.append(tensor_dim.size)\n else:\n mesh_dim = self.shape[mesh_axis]\n if tensor_dim.size % mesh_dim.size != 0:\n raise ValueError('Tensor dimension size not divisible by mesh dimension size: tensor_shape=%s tensor_layout=%s' % (tensor_shape, tensor_layout))\n ret.append(tensor_dim.size \/\/ mesh_dim.size)\n return ret","code_tokens":"","url":965501} +{"project_name":"akandykeller\/NeuralWaveMachines","file_name":"eval_metric.py","full_name":"compute_jacobian_manual","func_name":"compute_jacobian_manual","docstring":"Computes the jacobian manually.","docstring_tokens":"","code":"def compute_jacobian_manual(x, polynomial_features, weight_matrix, tolerance):\n \"\"\"Computes the jacobian manually.\"\"\"\n weight_mask = np.abs(weight_matrix) > tolerance\n weight_matrix = weight_mask * weight_matrix\n jacobians = list()\n for i in range(weight_matrix.shape[0]):\n grad_accumulator = np.zeros_like(x)\n for (j, feature) in enumerate(polynomial_features):\n eval_monomial_grad(feature, x, weight_matrix[i, j], grad_accumulator)\n jacobians.append(grad_accumulator)\n return np.stack(jacobians)","code_tokens":"","url":293515} +{"project_name":"michiyasunaga\/BIFI","file_name":"trainer.py","full_name":"Trainer.get_model","func_name":"get_model","docstring":"Get the (non-wrapped) model instance.","docstring_tokens":"","code":"def get_model(self):\n \"\"\"Get the (non-wrapped) model instance.\"\"\"\n return self._model","code_tokens":"","url":107316} +{"project_name":"luispedro\/mahotas","file_name":"freeimage.py","full_name":"write","func_name":"write","docstring":"Write a (width, height) or (width, height, nchannels) array to a greyscale, RGB, or RGBA image, with file type deduced from the filename.","docstring_tokens":"","code":"def write(array, filename, flags=0):\n \"\"\"Write a (width, height) or (width, height, nchannels) array to\n a greyscale, RGB, or RGBA image, with file type deduced from the\n filename.\n\n \"\"\"\n filename = _bytestr(filename)\n ftype = _FI.FreeImage_GetFIFFromFilename(filename)\n if ftype == -1:\n raise ValueError('mahotas.freeimage: cannot determine type for %s' % filename)\n (bitmap, fi_type) = _array_to_bitmap(array)\n try:\n if fi_type == FI_TYPES.FIT_BITMAP:\n can_write = _FI.FreeImage_FIFSupportsExportBPP(ftype, _FI.FreeImage_GetBPP(bitmap))\n else:\n can_write = _FI.FreeImage_FIFSupportsExportType(ftype, fi_type)\n if not can_write:\n raise TypeError('mahotas.freeimage: cannot save image of this type (%s) to this file type' % array.dtype)\n res = _FI.FreeImage_Save(ftype, bitmap, filename, flags)\n if not res:\n raise RuntimeError('mahotas.freeimage: could not save image properly.')\n finally:\n _FI.FreeImage_Unload(bitmap)","code_tokens":"","url":627280} +{"project_name":"aahuja9\/decision-trees-CS3600-Project4","file_name":"DataInterface.py","full_name":"getCarDataset","func_name":"getCarDataset","docstring":"Reads in and parses through the Car dataset.","docstring_tokens":"","code":"def getCarDataset(start=None, end=None):\n \"\"\"\n Reads in and parses through the Car dataset.\n \n Args:\n start (int): optional line number to start dataset at\n end (int): optional line number to end dataset at\n Returns:\n tuple>,\n dictionary>,\n str,\n list>\n \n List of examples as dictionaries, a dictionary mapping each\n attribute to all of its possible values, the name of the label\n in the example dictionaries, and the list of possible label values.\n \"\"\"\n examples = []\n attrValues = {}\n data = open('datasets\/cars-data.txt')\n attrs = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety']\n attr_values = [['vhigh', 'high', 'med', 'low'], ['vhigh', 'high', 'med', 'low'], ['2', '3', '4', '5more'], ['2', '4', 'more'], ['small', 'med', 'big'], ['high', 'med', 'low']]\n labelValues = ['unacc', 'acc', 'good', 'vgood']\n for index in range(len(attrs)):\n attrValues[attrs[index]] = attr_values[index]\n for line in data:\n dict = {}\n examples.append(dict)\n count = 0\n for val in line.split(','):\n if count == 6:\n dict['label'] = val[:-1]\n else:\n dict[attrs[count]] = val\n count += 1\n if start is not None and end is None:\n examples = examples[start:]\n elif start is None and end is not None:\n examples = examples[:end]\n elif start is not None and end is not None:\n examples = examples[start:end]\n return (examples, attrValues, 'label', labelValues)","code_tokens":"","url":127122} +{"project_name":"georghess\/voxel-mae","file_name":"box_3d_mode.py","full_name":"Box3DMode.convert","func_name":"convert","docstring":"Convert boxes from `src` mode to `dst` mode.","docstring_tokens":"","code":"@staticmethod\ndef convert(box, src, dst, rt_mat=None):\n \"\"\"Convert boxes from `src` mode to `dst` mode.\n\n Args:\n box (tuple | list | np.ndarray |\n torch.Tensor | BaseInstance3DBoxes):\n Can be a k-tuple, k-list or an Nxk array\/tensor, where k = 7.\n src (:obj:`BoxMode`): The src Box mode.\n dst (:obj:`BoxMode`): The target Box mode.\n rt_mat (np.ndarray | torch.Tensor): The rotation and translation\n matrix between different coordinates. Defaults to None.\n The conversion from `src` coordinates to `dst` coordinates\n usually comes along the change of sensors, e.g., from camera\n to LiDAR. This requires a transformation matrix.\n\n Returns:\n (tuple | list | np.ndarray | torch.Tensor | BaseInstance3DBoxes): The converted box of the same type.\n \"\"\"\n if src == dst:\n return box\n is_numpy = isinstance(box, np.ndarray)\n is_Instance3DBoxes = isinstance(box, BaseInstance3DBoxes)\n single_box = isinstance(box, (list, tuple))\n if single_box:\n assert len(box) >= 7, 'BoxMode.convert takes either a k-tuple\/list or an Nxk array\/tensor, where k >= 7'\n arr = torch.tensor(box)[None, :]\n elif is_numpy:\n arr = torch.from_numpy(np.asarray(box)).clone()\n elif is_Instance3DBoxes:\n arr = box.tensor.clone()\n else:\n arr = box.clone()\n (x_size, y_size, z_size) = (arr[..., 3:4], arr[..., 4:5], arr[..., 5:6])\n if src == Box3DMode.LIDAR and dst == Box3DMode.CAM:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[0, -1, 0], [0, 0, -1], [1, 0, 0]])\n xyz_size = torch.cat([y_size, z_size, x_size], dim=-1)\n elif src == Box3DMode.CAM and dst == Box3DMode.LIDAR:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[0, 0, 1], [-1, 0, 0], [0, -1, 0]])\n xyz_size = torch.cat([z_size, x_size, y_size], dim=-1)\n elif src == Box3DMode.DEPTH and dst == Box3DMode.CAM:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[1, 0, 0], [0, 0, 1], [0, -1, 0]])\n xyz_size = torch.cat([x_size, z_size, y_size], dim=-1)\n elif src == Box3DMode.CAM and dst == Box3DMode.DEPTH:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[1, 0, 0], [0, 0, -1], [0, 1, 0]])\n xyz_size = torch.cat([x_size, z_size, y_size], dim=-1)\n elif src == Box3DMode.LIDAR and dst == Box3DMode.DEPTH:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n xyz_size = torch.cat([y_size, x_size, z_size], dim=-1)\n elif src == Box3DMode.DEPTH and dst == Box3DMode.LIDAR:\n if rt_mat is None:\n rt_mat = arr.new_tensor([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])\n xyz_size = torch.cat([y_size, x_size, z_size], dim=-1)\n else:\n raise NotImplementedError(f'Conversion from Box3DMode {src} to {dst} is not supported yet')\n if not isinstance(rt_mat, torch.Tensor):\n rt_mat = arr.new_tensor(rt_mat)\n if rt_mat.size(1) == 4:\n extended_xyz = torch.cat([arr[:, :3], arr.new_ones(arr.size(0), 1)], dim=-1)\n xyz = extended_xyz @ rt_mat.t()\n else:\n xyz = arr[:, :3] @ rt_mat.t()\n remains = arr[..., 6:]\n arr = torch.cat([xyz[:, :3], xyz_size, remains], dim=-1)\n original_type = type(box)\n if single_box:\n return original_type(arr.flatten().tolist())\n if is_numpy:\n return arr.numpy()\n elif is_Instance3DBoxes:\n if dst == Box3DMode.CAM:\n target_type = CameraInstance3DBoxes\n elif dst == Box3DMode.LIDAR:\n target_type = LiDARInstance3DBoxes\n elif dst == Box3DMode.DEPTH:\n target_type = DepthInstance3DBoxes\n else:\n raise NotImplementedError(f'Conversion to {dst} through {original_type} is not supported yet')\n return target_type(arr, box_dim=arr.size(-1), with_yaw=box.with_yaw)\n else:\n return arr","code_tokens":"","url":380387} +{"project_name":"zachgitt\/computer-vision-panorama","file_name":"uiutils.py","full_name":"ImageWidget.set_grayscale","func_name":"set_grayscale","docstring":"If the passet value is true, draws the given raw_image as grayscale otherwise defaults to its color scheme.","docstring_tokens":"","code":"def set_grayscale(self, value):\n \"\"\"If the passet value is true, draws the given raw_image as grayscale\n otherwise defaults to its color scheme.\"\"\"\n self.show_grayscale = value\n self.redraw()","code_tokens":"","url":470347} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"networkwrapper.py","full_name":"NetworkWrapper.getOutputConnection","func_name":"getOutputConnection","docstring":"Returns the input connection of the output layer.","docstring_tokens":"","code":"def getOutputConnection(self):\n \"\"\" Returns the input connection of the output layer. \"\"\"\n if self._output_connection is None:\n outlayer = self.getOutputLayer()\n lastlayer = self.getLastHiddenLayer()\n for c in self.getConnections():\n if c.outmod is outlayer:\n assert c.inmod is lastlayer\n self._output_connection = c\n return self._output_connection","code_tokens":"","url":722712} +{"project_name":"thaines\/helit","file_name":"corpus.py","full_name":"Corpus.getCalcPhi","func_name":"getCalcPhi","docstring":"Returns False if it is going to leave the phi prior as is, True to indicate that it will be optimised.","docstring_tokens":"","code":"def getCalcPhi(self):\n \"\"\"Returns False if it is going to leave the phi prior as is, True to indicate that it will be optimised.\"\"\"\n return self.calcPhi","code_tokens":"","url":590971} +{"project_name":"rouge8\/20questions","file_name":"test.py","full_name":"module_suite","func_name":"module_suite","docstring":"Makes a suite from a module.","docstring_tokens":"","code":"def module_suite(module, classnames=None):\n \"\"\"Makes a suite from a module.\"\"\"\n if classnames:\n return unittest.TestLoader().loadTestsFromNames(classnames, module)\n elif hasattr(module, 'suite'):\n return module.suite()\n else:\n return unittest.TestLoader().loadTestsFromModule(module)","code_tokens":"","url":4411} +{"project_name":"open-mmlab\/mmsegmentation","file_name":"class_names.py","full_name":"lip_palette","func_name":"lip_palette","docstring":"LIP palette for external use.","docstring_tokens":"","code":"def lip_palette():\n \"\"\"LIP palette for external use.\"\"\"\n return ['Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'UpperClothes', 'Dress', 'Coat', 'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', 'Face', 'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe', 'Right-shoe']","code_tokens":"","url":625517} +{"project_name":"lixingjian\/DELTA","file_name":"kaldi_dir.py","full_name":"KaldiMetaData.select_spks","func_name":"select_spks","docstring":"Select speakers and perform a shallow copy.","docstring_tokens":"","code":"def select_spks(self, spk_list):\n \"\"\" Select speakers and perform a shallow copy. \"\"\"\n new_meta = KaldiMetaData()\n for spk in spk_list:\n if spk in self.spks:\n for utt_key in self.spks[spk].utts:\n new_meta.utts[utt_key] = self.utts[utt_key]\n new_meta.collect_spks_from_utts()\n return new_meta","code_tokens":"","url":537613} +{"project_name":"guoguo12\/tensorflow-fcwta","file_name":"models.py","full_name":"FullyConnectedWTA.get_dictionary","func_name":"get_dictionary","docstring":"Fetch (approximately) the learned code dictionary.","docstring_tokens":"","code":"def get_dictionary(self, session):\n \"\"\"Fetch (approximately) the learned code dictionary.\n\n Args:\n session: TensorFlow session to use.\n\n Returns:\n The code dictionary, with shape (hidden_units, input_dim).\n \"\"\"\n fake_input = 1000000000000000.0 * tf.eye(self.hidden_units)\n return session.run(self._decode_layer(fake_input, reuse=True))","code_tokens":"","url":908619} +{"project_name":"nerdslab\/myow","file_name":"fast_classification.py","full_name":"compute_accuracy","func_name":"compute_accuracy","docstring":"Evaluates the classification accuracy with representations pre-computed.","docstring_tokens":"","code":"def compute_accuracy(classifier, data, batch_size=256, device='cpu'):\n \"\"\"Evaluates the classification accuracy with representations pre-computed.\n\n Args:\n classifier (torch.nn.Module): Linear layer.\n data (list of torch.nn.Tensor): Inputs, target class and target angles.\n batch_size (int, Optional): Batch size used during evaluation. It has no impact on final accuracy.\n (default: :obj:`256`)\n device (String, Optional): Device used. (default: :obj:`\"cpu\"`)\n\n Returns:\n float: Accuracy.\n \"\"\"\n classifier.eval()\n right = []\n total = []\n for (x, label) in utils.batch_iter(*data, batch_size=batch_size):\n x = x.to(device)\n label = label.to(device)\n with torch.no_grad():\n pred_logits = classifier(x)\n (_, pred_class) = torch.max(pred_logits, 1)\n right.append((pred_class == label).sum().item())\n total.append(label.size(0))\n classifier.train()\n return sum(right) \/ sum(total)","code_tokens":"","url":291048} +{"project_name":"YiSyuanChen\/MTL-ABS","file_name":"reporter.py","full_name":"Statistics.output_inner","func_name":"output_inner","docstring":"Write out statistics to stdout.","docstring_tokens":"","code":"def output_inner(self, step, num_steps, learning_rate, learning_rate_dec, start):\n \"\"\"Write out statistics to stdout.\n\n Args:\n step (int): current step\n n_batch (int): total batches\n start (int): start time of step.\n \"\"\"\n t = self.elapsed_time()\n logger.info(('Inner Step %2d\/%5d; acc: %6.2f; ppl: %5.2f; xent: %4.2f; ' + 'lr: %7.8f; lr_dec: %7.8f; %3.0f\/%3.0f tok\/s; %6.0f sec') % (step, num_steps, self.accuracy(), self.ppl(), self.xent(), learning_rate, learning_rate_dec, self.n_src_words \/ (t + 1e-05), self.n_words \/ (t + 1e-05), time.time() - start))\n sys.stdout.flush()","code_tokens":"","url":642827} +{"project_name":"Eric3911\/OpenAGI","file_name":"data_simulation_utils.py","full_name":"DataAnnotator.add_to_filename_lists","func_name":"add_to_filename_lists","docstring":"Add the current filename to the list of filenames for each file type.","docstring_tokens":"","code":"def add_to_filename_lists(self, basepath: str, filename: str):\n \"\"\"\n Add the current filename to the list of filenames for each file type.\n\n Args:\n basepath (str): Basepath for output files.\n filename (str): Base filename for all output files.\n \"\"\"\n full_base_filepath = os.path.join(basepath, filename)\n for file_type in self._file_types:\n self.annote_lists[f'{file_type}_list'].append(f'{full_base_filepath}.{file_type}')","code_tokens":"","url":272859} +{"project_name":"google-research\/rigl","file_name":"masked.py","full_name":"mask_layer_sparsity","func_name":"mask_layer_sparsity","docstring":"Calculates the sparsity of a single layer's mask.","docstring_tokens":"","code":"def mask_layer_sparsity(mask_layer):\n \"\"\"Calculates the sparsity of a single layer's mask.\n\n Args:\n mask_layer: mask layer to calculate the sparsity of.\n\n Returns:\n The sparsity of the mask.\n \"\"\"\n parameter_count = 0\n masked_count = 0\n for key in mask_layer:\n if mask_layer[key] is not None and key in WEIGHT_PARAM_NAMES:\n parameter_count += mask_layer[key].size\n masked_count += jnp.sum(mask_layer[key])\n if parameter_count == 0:\n return 0.0\n return 1.0 - masked_count \/ parameter_count","code_tokens":"","url":841464} +{"project_name":"NickNickGo\/fastseq","file_name":"file_utils.py","full_name":"wget","func_name":"wget","docstring":"Download the file from the url to the target file.","docstring_tokens":"","code":"def wget(url, target_file_handling):\n \"\"\"Download the file from the url to the target file.\n\n Args:\n url (str): the url to download the data.\n target_file_handling (file object): A file handling for writing the\n data.\n \"\"\"\n response = requests.get(url, stream=True)\n if response.status_code == 416:\n raise ValueError('Range not satisfiable when loading {}'.format(url))\n content_length = response.headers.get('Content-Length')\n total = int(content_length) if content_length is not None else None\n progress = tqdm(unit='B', unit_scale=True, total=total, initial=0, desc='Downloading')\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n progress.update(len(chunk))\n target_file_handling.write(chunk)\n progress.close()","code_tokens":"","url":559890} +{"project_name":"brain-research\/hyperbolictext","file_name":"tools.py","full_name":"load_skip_thought_embeddings","func_name":"load_skip_thought_embeddings","docstring":"Loads the embedding matrix from a skip thought model checkpoint.","docstring_tokens":"","code":"def load_skip_thought_embeddings(checkpoint_path, vocab_size, embedding_dim):\n \"\"\"Loads the embedding matrix from a skip thought model checkpoint.\n\n Args:\n checkpoint_path: Model checkpoint file or directory containing a checkpoint\n file.\n vocab_size: Number of words in the vocabulary.\n embedding_dim: Word embedding dimension.\n\n Returns:\n word_embedding: A numpy array of shape [vocab_size, embedding_dim].\n\n Raises:\n ValueError: If no checkpoint file matches checkpoint_path.\n \"\"\"\n if tf.gfile.IsDirectory(checkpoint_path):\n checkpoint_file = tf.train.latest_checkpoint(checkpoint_path)\n if not checkpoint_file:\n raise ValueError('No checkpoint file found in %s' % checkpoint_path)\n else:\n checkpoint_file = checkpoint_path\n g = tf.Graph()\n with g.as_default():\n word_embedding_tensor = tf.get_variable(name='word_embedding', shape=[vocab_size, embedding_dim])\n saver = tf.train.Saver()\n with tf.Session(graph=g) as sess:\n tf.logging.info('Loading skip thought embedding matrix from %s', checkpoint_file)\n saver.restore(sess, checkpoint_file)\n word_embedding = sess.run(word_embedding_tensor)\n tf.logging.info('Loaded skip thought embedding matrix of shape %s', word_embedding.shape)\n return word_embedding","code_tokens":"","url":228131} +{"project_name":"AndrewSpano\/BSc-Thesis","file_name":"data_prep_utils.py","full_name":"print_stats_and_save","func_name":"print_stats_and_save","docstring":"Prints statistics regarding the data and then saves it.","docstring_tokens":"","code":"def print_stats_and_save(train_sentences: List[List[str]], val_sentences: List[List[str]], test_sentences: List[List[str]], dest_dir: Path, name: str) -> None:\n \"\"\"Prints statistics regarding the data and then saves it.\"\"\"\n print(f'{name} - Number of train sentences: {sum(map(len, train_sentences))}')\n print(f'{name} - Number of val sentences: {sum(map(len, val_sentences))}')\n print(f'{name} - Number of test sentences: {sum(map(len, test_sentences))}')\n write_sentences(dest_dir \/ 'train' \/ f'{name}-train.txt', train_sentences)\n write_sentences(dest_dir \/ 'val' \/ f'{name}-val.txt', val_sentences)\n write_sentences(dest_dir \/ 'test' \/ f'{name}-test.txt', test_sentences)","code_tokens":"","url":410056} +{"project_name":"Alexander-Parker\/youtube_nlp","file_name":"firefox_profile.py","full_name":"FirefoxProfile.set_preference","func_name":"set_preference","docstring":"sets the preference that we want in the profile.","docstring_tokens":"","code":"def set_preference(self, key, value):\n \"\"\"\n sets the preference that we want in the profile.\n \"\"\"\n self.default_preferences[key] = value","code_tokens":"","url":970853} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"translate.py","full_name":"read_data","func_name":"read_data","docstring":"Read data from source and target files and put into buckets.","docstring_tokens":"","code":"def read_data(source_path, target_path, max_size=None):\n \"\"\"Read data from source and target files and put into buckets.\n\n Args:\n source_path: path to the files with token-ids for the source language.\n target_path: path to the file with token-ids for the target language;\n it must be aligned with the source file: n-th line contains the desired\n output for n-th line from the source_path.\n max_size: maximum number of lines to read, all other will be ignored;\n if 0 or None, data files will be read completely (no limit).\n\n Returns:\n data_set: a list of length len(_buckets); data_set[n] contains a list of\n (source, target) pairs read from the provided data files that fit\n into the n-th bucket, i.e., such that len(source) < _buckets[n][0] and\n len(target) < _buckets[n][1]; source and target are lists of token-ids.\n \"\"\"\n data_set = [[] for _ in _buckets]\n with tf.gfile.GFile(source_path, mode='r') as source_file:\n with tf.gfile.GFile(target_path, mode='r') as target_file:\n (source, target) = (source_file.readline(), target_file.readline())\n counter = 0\n while source and target and (not max_size or counter < max_size):\n counter += 1\n if counter % 100000 == 0:\n print(' reading data line %d' % counter)\n sys.stdout.flush()\n source_ids = [int(x) for x in source.split()]\n target_ids = [int(x) for x in target.split()]\n target_ids.append(data_utils.EOS_ID)\n for (bucket_id, (source_size, target_size)) in enumerate(_buckets):\n if len(source_ids) < source_size and len(target_ids) < target_size:\n data_set[bucket_id].append([source_ids, target_ids])\n break\n (source, target) = (source_file.readline(), target_file.readline())\n return data_set","code_tokens":"","url":30555} +{"project_name":"mj-will\/nessai","file_name":"conftest.py","full_name":"get_bilby_gw_model","func_name":"get_bilby_gw_model","docstring":"Return a function will provide a nessai model given parameters and an injection.","docstring_tokens":"","code":"@pytest.fixture()\ndef get_bilby_gw_model() -> Callable:\n \"\"\"Return a function will provide a nessai model given parameters\n and an injection.\n \"\"\"\n\n def get_model(parameters, injection_parameters) -> BaseModel:\n import bilby\n priors = bilby.gw.prior.BBHPriorDict()\n fixed_params = ['chirp_mass', 'mass_ratio', 'phi_12', 'phi_jl', 'a_1', 'a_2', 'tilt_1', 'tilt_2', 'ra', 'dec', 'luminosity_distance', 'geocent_time', 'theta_jn', 'psi', 'phase']\n try:\n fixed_params.remove(parameters)\n except ValueError:\n for p in parameters:\n fixed_params.remove(p)\n priors['geocent_time'] = bilby.core.prior.Uniform(minimum=injection_parameters['geocent_time'] - 0.1, maximum=injection_parameters['geocent_time'] + 0.1, name='geocent_time', latex_label='$t_c$', unit='$s$')\n for key in fixed_params:\n if key in injection_parameters:\n priors[key] = injection_parameters[key]\n waveform_generator = bilby.gw.WaveformGenerator(duration=1, sampling_frequency=256, frequency_domain_source_model=bilby.gw.source.lal_binary_black_hole)\n likelihood = bilby.gw.GravitationalWaveTransient(interferometers=['H1'], waveform_generator=waveform_generator, priors=priors, phase_marginalization='phase' not in fixed_params, distance_marginalization=False, time_marginalization=False, reference_frame='sky')\n likelihood = bilby.core.likelihood.ZeroLikelihood(likelihood)\n\n def log_prior(theta):\n return priors.ln_prob(theta, axis=0)\n search_parameter_keys = []\n for key in priors:\n if isinstance(priors[key], bilby.core.prior.Prior) and priors[key].is_fixed is False:\n search_parameter_keys.append(key)\n\n def log_likelihood(theta):\n params = {key: t for (key, t) in zip(search_parameter_keys, theta)}\n likelihood.parameters.update(params)\n return likelihood.log_likelihood_ratio()\n\n class Model(BaseModel):\n\n def __init__(self, names, priors):\n self.names = names\n self.priors = priors\n self._update_bounds()\n\n @staticmethod\n def log_likelihood(x, **kwargs):\n theta = [x[n].item() for n in search_parameter_keys]\n return log_likelihood(theta)\n\n @staticmethod\n def log_prior(x, names=None, **kwargs):\n if names is None:\n names = search_parameter_keys\n theta = {n: x[n] for n in names}\n return log_prior(theta)\n\n def _update_bounds(self):\n self.bounds = {key: [self.priors[key].minimum, self.priors[key].maximum] for key in self.names}\n\n def new_point(self, N=1):\n prior_samples = self.priors.sample(size=N)\n samples = {n: prior_samples[n] for n in self.names}\n self._update_bounds()\n return dict_to_live_points(samples)\n\n def new_point_log_prob(self, x):\n return self.log_prior(x)\n return Model(search_parameter_keys, priors)\n return get_model","code_tokens":"","url":292596} +{"project_name":"hchasestevens\/monkeys","file_name":"test_search.py","full_name":"test_max_score_not_set_by_assertions_as_score_on_for","func_name":"test_max_score_not_set_by_assertions_as_score_on_for","docstring":"Ensure that a max score attribute is left unset on scoring functions using for loops when using assertions_as_score.","docstring_tokens":"","code":"def test_max_score_not_set_by_assertions_as_score_on_for():\n \"\"\"\n Ensure that a max score attribute is left unset on scoring\n functions using for loops when using assertions_as_score.\n \"\"\"\n\n @search.assertions_as_score\n def score(x):\n for item in xrange(x):\n assert item\n with pytest.raises(AttributeError):\n score.__max_score","code_tokens":"","url":241123} +{"project_name":"tum-pbs\/PhiFlow","file_name":"test_poisson_solver.py","full_name":"FFT_solve_numpy","func_name":"FFT_solve_numpy","docstring":"Inverse operation to `fourier_laplace`.","docstring_tokens":"","code":"def FFT_solve_numpy(tensor, dx, times=1):\n \"\"\" Inverse operation to `fourier_laplace`. \"\"\"\n tensor = tensor.reshape(1, *tensor.shape, 1)\n frequencies = np.fft.fft2(to_complex(tensor), axes=[1, 2])\n k = fftfreq(np.shape(tensor)[1:-1], mode='square')\n fft_laplace = -(2 * np.pi) ** 2 * k\n fft_laplace[(0,) * len(k.shape)] = np.inf\n result = np.real(np.fft.ifft2(divide_no_nan(frequencies, fft_laplace ** times), axes=[1, 2])).astype(tensor.dtype)[0, ..., 0]\n return result * dx ** 2","code_tokens":"","url":768907} +{"project_name":"Caojunxu\/AC-FPN","file_name":"lr_policy.py","full_name":"get_step_index","func_name":"get_step_index","docstring":"Given an iteration, find which learning rate step we're at.","docstring_tokens":"","code":"def get_step_index(cur_iter):\n \"\"\"Given an iteration, find which learning rate step we're at.\"\"\"\n assert cfg.SOLVER.STEPS[0] == 0, 'The first step should always start at 0.'\n steps = cfg.SOLVER.STEPS + [cfg.SOLVER.MAX_ITER]\n for (ind, step) in enumerate(steps):\n if cur_iter < step:\n break\n return ind - 1","code_tokens":"","url":406577} +{"project_name":"deepmind\/meltingpot","file_name":"hidden_agenda.py","full_name":"create_action_set","func_name":"create_action_set","docstring":"Create the action set for the agents.","docstring_tokens":"","code":"def create_action_set(num_players):\n \"\"\"Create the action set for the agents.\"\"\"\n action_set = [NOOP, FORWARD, BACKWARD, STEP_LEFT, STEP_RIGHT, TURN_LEFT, TURN_RIGHT, TAG]\n for player in range(1, num_players + 2):\n vote = copy.deepcopy(NOOP)\n vote['vote'] = player\n action_set.append(vote)\n return action_set","code_tokens":"","url":285381} +{"project_name":"calico\/basenji","file_name":"test_data.py","full_name":"TestData.test_targets","func_name":"test_targets","docstring":"Test that the targets match.","docstring_tokens":"","code":"def test_targets(self, atol=0.001):\n \"\"\"Test that the targets match.\"\"\"\n seqs_bed_file = '%s\/sequences.bed' % self.out_dir\n seq_coords = read_seq_coords(seqs_bed_file)\n targets_df = pd.read_table(self.targets_file, index_col=0)\n train_tfrs_str = '%s\/tfrecords\/train-0.tfr' % self.out_dir\n (_, targets) = self.read_tfrecords(train_tfrs_str)\n seq_indexes = random.sample(range(targets.shape[0]), 8)\n target_indexes = random.sample(range(targets_df.shape[0]), 8)\n for si in seq_indexes:\n sc = seq_coords[si]\n for ti in target_indexes:\n cov_h5 = h5py.File(targets_df.file.iloc[ti], 'r')\n seq_cov_nt = cov_h5[sc.chr][sc.start:sc.end]\n seq_cov_nt = np.nan_to_num(seq_cov_nt)\n seq_cov = seq_cov_nt.reshape((-1, self.pool_width))\n seq_cov = seq_cov.sum(axis=1, dtype='float32').astype('float16')\n cov_targets_diff = np.abs(seq_cov - targets[si, :, ti])\n close_mask = cov_targets_diff < atol\n seq_cov_umap = seq_cov.copy()\n seq_cov_umap[~close_mask] = np.percentile(seq_cov, q=[25])[0]\n try:\n np.testing.assert_allclose(targets[si, :, ti], seq_cov_umap, rtol=1, atol=atol)\n except AssertionError:\n pdb.set_trace()","code_tokens":"","url":94903} +{"project_name":"mj-will\/nessai","file_name":"test_flow_proposal.py","full_name":"test_check_training_not_completed_training","func_name":"test_check_training_not_completed_training","docstring":"Assert the flow is forced to train if training did not complete when the sampler was checkpointed.","docstring_tokens":"","code":"def test_check_training_not_completed_training(sampler):\n \"\"\"\n Assert the flow is forced to train if training did not complete when\n the sampler was checkpointed.\n \"\"\"\n sampler.completed_training = False\n (train, force) = NestedSampler.check_training(sampler)\n assert train is True\n assert force is True","code_tokens":"","url":292961} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"neural_bandit_model.py","full_name":"NeuralBanditModel.build_layer","func_name":"build_layer","docstring":"Builds a layer with input x; dropout and layer norm if specified.","docstring_tokens":"","code":"def build_layer(self, x, num_units):\n \"\"\"Builds a layer with input x; dropout and layer norm if specified.\"\"\"\n init_s = self.hparams.init_scale\n layer_n = getattr(self.hparams, 'layer_norm', False)\n dropout = getattr(self.hparams, 'use_dropout', False)\n nn = tf.contrib.layers.fully_connected(x, num_units, activation_fn=self.hparams.activation, normalizer_fn=None if not layer_n else tf.contrib.layers.layer_norm, normalizer_params={}, weights_initializer=tf.random_uniform_initializer(-init_s, init_s))\n if dropout:\n nn = tf.nn.dropout(nn, self.hparams.keep_prob)\n return nn","code_tokens":"","url":762277} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"center_net_meta_arch.py","full_name":"prediction_tensors_to_single_instance_kpts","func_name":"prediction_tensors_to_single_instance_kpts","docstring":"Convert keypoint heatmap predictions and offsets to keypoint candidates.","docstring_tokens":"","code":"def prediction_tensors_to_single_instance_kpts(keypoint_heatmap_predictions, keypoint_heatmap_offsets, keypoint_score_heatmap=None):\n \"\"\"Convert keypoint heatmap predictions and offsets to keypoint candidates.\n\n Args:\n keypoint_heatmap_predictions: A float tensor of shape [batch_size, height,\n width, num_keypoints] representing the per-keypoint heatmaps which is\n used for finding the best keypoint candidate locations.\n keypoint_heatmap_offsets: A float tensor of shape [batch_size, height,\n width, 2] (or [batch_size, height, width, 2 * num_keypoints] if\n 'per_keypoint_offset' is set True) representing the per-keypoint offsets.\n keypoint_score_heatmap: (optional) A float tensor of shape [batch_size,\n height, width, num_keypoints] representing the heatmap which is used for\n reporting the confidence scores. If not provided, then the values in the\n keypoint_heatmap_predictions will be used.\n\n Returns:\n keypoint_candidates: A tensor of shape\n [batch_size, max_candidates, num_keypoints, 2] holding the\n location of keypoint candidates in [y, x] format (expressed in absolute\n coordinates in the output coordinate frame).\n keypoint_scores: A float tensor of shape\n [batch_size, max_candidates, num_keypoints] with the scores for each\n keypoint candidate. The scores come directly from the heatmap predictions.\n num_keypoint_candidates: An integer tensor of shape\n [batch_size, num_keypoints] with the number of candidates for each\n keypoint type, as it's possible to filter some candidates due to the score\n threshold.\n \"\"\"\n (batch_size, height, width, num_keypoints) = _get_shape(keypoint_heatmap_predictions, 4)\n (y_indices, x_indices, channel_indices) = argmax_feature_map_locations(keypoint_heatmap_predictions)\n (_, num_keypoints) = _get_shape(y_indices, 2)\n combined_indices = tf.stack([_multi_range(batch_size, value_repetitions=num_keypoints), tf.reshape(y_indices, [-1]), tf.reshape(x_indices, [-1]), tf.reshape(channel_indices, [-1])], axis=1)\n keypoint_heatmap_offsets = tf.reshape(keypoint_heatmap_offsets, [batch_size, height, width, num_keypoints, -1])\n selected_offsets_flat = tf.gather_nd(keypoint_heatmap_offsets, combined_indices)\n (y_offsets, x_offsets) = tf.unstack(selected_offsets_flat, axis=1)\n keypoint_candidates = tf.stack([tf.cast(y_indices, dtype=tf.float32) + tf.expand_dims(y_offsets, axis=0), tf.cast(x_indices, dtype=tf.float32) + tf.expand_dims(x_offsets, axis=0)], axis=2)\n keypoint_candidates = tf.expand_dims(keypoint_candidates, axis=0)\n if keypoint_score_heatmap is None:\n keypoint_scores = tf.gather_nd(keypoint_heatmap_predictions, combined_indices)\n else:\n keypoint_scores = tf.gather_nd(keypoint_score_heatmap, combined_indices)\n keypoint_scores = tf.expand_dims(tf.expand_dims(keypoint_scores, axis=0), axis=0)\n return (keypoint_candidates, keypoint_scores)","code_tokens":"","url":974996} +{"project_name":"lojzezust\/WaSR-T","file_name":"wasr_t.py","full_name":"WaSRTDecoder.sequential","func_name":"sequential","docstring":"Switch to sequential mode.","docstring_tokens":"","code":"def sequential(self):\n \"\"\"Switch to sequential mode.\"\"\"\n self.tcm.sequential()\n return self","code_tokens":"","url":942337} +{"project_name":"MycroftAI\/mycroft-core","file_name":"test_mycroft_skill_get_response.py","full_name":"TestMycroftSkillAskYesNo.test_ask_yesno_no","func_name":"test_ask_yesno_no","docstring":"Check that a negative response is interpreted as a no.","docstring_tokens":"","code":"def test_ask_yesno_no(self):\n \"\"\"Check that a negative response is interpreted as a no.\"\"\"\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'nope'\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'no')","code_tokens":"","url":290949} +{"project_name":"google-research\/scenic","file_name":"dataset_utils.py","full_name":"parse_example","func_name":"parse_example","docstring":"Parses feature dictionary from the `serialized_example` proto.","docstring_tokens":"","code":"def parse_example(serialized_example):\n \"\"\"Parses feature dictionary from the `serialized_example` proto.\n\n Args:\n serialized_example: The proto of the current example.\n\n Returns:\n A parsed example as dict with several elements.\n \"\"\"\n feature_description = {'chrm_img': tf.io.FixedLenFeature([], tf.string, default_value=''), 'meta_img': tf.io.FixedLenFeature([], tf.string, default_value=''), 'label': tf.io.FixedLenFeature([], tf.string, default_value=''), 'chrm_path': tf.io.FixedLenFeature([], tf.string, default_value='')}\n features = tf.io.parse_single_example(serialized_example, feature_description)\n return features","code_tokens":"","url":847377} +{"project_name":"illuri96\/NaturalLanguageProcessing","file_name":"create_pretraining_data.py","full_name":"create_masked_lm_predictions","func_name":"create_masked_lm_predictions","docstring":"Creates the predictions for the masked LM objective.","docstring_tokens":"","code":"def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng):\n \"\"\"Creates the predictions for the masked LM objective.\"\"\"\n cand_indexes = []\n for (i, token) in enumerate(tokens):\n if token == '[CLS]' or token == '[SEP]':\n continue\n if FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and token.startswith('##'):\n cand_indexes[-1].append(i)\n else:\n cand_indexes.append([i])\n rng.shuffle(cand_indexes)\n output_tokens = list(tokens)\n num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob))))\n masked_lms = []\n covered_indexes = set()\n for index_set in cand_indexes:\n if len(masked_lms) >= num_to_predict:\n break\n if len(masked_lms) + len(index_set) > num_to_predict:\n continue\n is_any_index_covered = False\n for index in index_set:\n if index in covered_indexes:\n is_any_index_covered = True\n break\n if is_any_index_covered:\n continue\n for index in index_set:\n covered_indexes.add(index)\n masked_token = None\n if rng.random() < 0.8:\n masked_token = '[MASK]'\n elif rng.random() < 0.5:\n masked_token = tokens[index]\n else:\n masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]\n output_tokens[index] = masked_token\n masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))\n assert len(masked_lms) <= num_to_predict\n masked_lms = sorted(masked_lms, key=lambda x: x.index)\n masked_lm_positions = []\n masked_lm_labels = []\n for p in masked_lms:\n masked_lm_positions.append(p.index)\n masked_lm_labels.append(p.label)\n return (output_tokens, masked_lm_positions, masked_lm_labels)","code_tokens":"","url":710314} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"descriptor_pool.py","full_name":"DescriptorPool.Add","func_name":"Add","docstring":"Adds the FileDescriptorProto and its types to this pool.","docstring_tokens":"","code":"def Add(self, file_desc_proto):\n \"\"\"Adds the FileDescriptorProto and its types to this pool.\n\n Args:\n file_desc_proto: The FileDescriptorProto to add.\n \"\"\"\n self._internal_db.Add(file_desc_proto)","code_tokens":"","url":215190} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"search.py","full_name":"reverse_incremental_search","func_name":"reverse_incremental_search","docstring":"Apply reverse incremental search, but keep search buffer focused.","docstring_tokens":"","code":"@key_binding(filter=is_searching)\ndef reverse_incremental_search(event):\n \"\"\"\n Apply reverse incremental search, but keep search buffer focused.\n \"\"\"\n search.do_incremental_search(search.SearchDirection.BACKWARD, count=event.arg)","code_tokens":"","url":75955} +{"project_name":"Deci-AI\/super-gradients","file_name":"zero_weight_decay_on_bias_bn_test.py","full_name":"ZeroWdForBnBiasTest.test_zero_wd_multiple_group","func_name":"test_zero_wd_multiple_group","docstring":"test that 2 groups of parameters are separated to 2 groups of weight_decay_params and 2 groups without.","docstring_tokens":"","code":"def test_zero_wd_multiple_group(self):\n \"\"\"\n test that 2 groups of parameters are separated to 2 groups of weight_decay_params and 2 groups without.\n \"\"\"\n for input_dim in self.input_dimensions:\n net = ToySgModule(input_dimension=input_dim, multiple_param_groups=True)\n train_params = HpmStruct(**self.train_params_zero_wd)\n optimizer_params_groups = separate_zero_wd_params_groups_for_optimizer(net, net.initialize_param_groups(self.lr, train_params), self.weight_decay)\n self._assert_optimizer_param_groups(optimizer_params_groups, excpected_num_groups=4, excpected_num_params_per_group=[net.base_params[0], net.base_params[1], net.head_params[0], net.head_params[1]], excpected_weight_decay_per_group=[0, self.weight_decay, 0, self.weight_decay])","code_tokens":"","url":880706} +{"project_name":"rudranil723\/mini-main","file_name":"timezone.py","full_name":"get_default_timezone_name","func_name":"get_default_timezone_name","docstring":"Return the name of the default time zone.","docstring_tokens":"","code":"def get_default_timezone_name():\n \"\"\"Return the name of the default time zone.\"\"\"\n return _get_timezone_name(get_default_timezone())","code_tokens":"","url":316807} +{"project_name":"imoscovitz\/wittgenstein","file_name":"base.py","full_name":"Ruleset.num_covered","func_name":"num_covered","docstring":"Return the number of covered examples.","docstring_tokens":"","code":"def num_covered(self, df):\n \"\"\"Return the number of covered examples.\"\"\"\n return len(self.covers(df))","code_tokens":"","url":959850} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"params_dict.py","full_name":"save_params_dict_to_yaml","func_name":"save_params_dict_to_yaml","docstring":"Saves the input ParamsDict to a YAML file.","docstring_tokens":"","code":"def save_params_dict_to_yaml(params, file_path):\n \"\"\"Saves the input ParamsDict to a YAML file.\"\"\"\n with tf.io.gfile.GFile(file_path, 'w') as f:\n\n def _my_list_rep(dumper, data):\n return dumper.represent_sequence(u'tag:yaml.org,2002:seq', data, flow_style=True)\n yaml.add_representer(list, _my_list_rep)\n yaml.dump(params.as_dict(), f, default_flow_style=False)","code_tokens":"","url":850229} +{"project_name":"zhiweichen0012\/E2Net","file_name":"symbolic_functions.py","full_name":"rms","func_name":"rms","docstring":"Returns: root mean square of tensor x.","docstring_tokens":"","code":"def rms(x, name=None):\n \"\"\"\n Returns:\n root mean square of tensor x.\n \"\"\"\n if name is None:\n name = x.op.name + '\/rms'\n with tfv1.name_scope(None):\n return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)\n return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)","code_tokens":"","url":174503} +{"project_name":"rishab-sharma\/object_detection","file_name":"nn.py","full_name":"weight","func_name":"weight","docstring":"Get a weight variable.","docstring_tokens":"","code":"def weight(name, shape, init='normal', range=0.1, stddev=0.001, init_val=None, group_id=0):\n \"\"\" Get a weight variable. \"\"\"\n if init_val != None:\n initializer = tf.constant_initializer(init_val)\n elif init == 'uniform':\n initializer = tf.random_uniform_initializer(-range, range)\n elif init == 'normal':\n initializer = tf.random_normal_initializer(stddev=stddev)\n elif init == 'he':\n (fan_in, _) = _get_dims(shape)\n std = math.sqrt(2.0 \/ fan_in)\n initializer = tf.random_normal_initializer(stddev=std)\n elif init == 'xavier':\n (fan_in, fan_out) = _get_dims(shape)\n range = math.sqrt(6.0 \/ (fan_in + fan_out))\n initializer = tf.random_uniform_initializer(-range, range)\n else:\n initializer = tf.truncated_normal_initializer(stddev=stddev)\n var = tf.get_variable(name, shape, initializer=initializer)\n tf.add_to_collection('l2_' + str(group_id), tf.nn.l2_loss(var))\n return var","code_tokens":"","url":793125} +{"project_name":"matsu0228\/nlp-jp","file_name":"pool.py","full_name":"PoolOptions.wait_queue_multiple","func_name":"wait_queue_multiple","docstring":"Multiplied by max_pool_size to give the number of threads allowed to wait for a socket at one time.","docstring_tokens":"","code":"@property\ndef wait_queue_multiple(self):\n \"\"\"Multiplied by max_pool_size to give the number of threads allowed\n to wait for a socket at one time.\n \"\"\"\n return self.__wait_queue_multiple","code_tokens":"","url":804977} +{"project_name":"jbwang1997\/CrossKD","file_name":"semi_base.py","full_name":"SemiBaseDetector.loss","func_name":"loss","docstring":"Calculate losses from multi-branch inputs and data samples.","docstring_tokens":"","code":"def loss(self, multi_batch_inputs: Dict[str, Tensor], multi_batch_data_samples: Dict[str, SampleList]) -> dict:\n \"\"\"Calculate losses from multi-branch inputs and data samples.\n\n Args:\n multi_batch_inputs (Dict[str, Tensor]): The dict of multi-branch\n input images, each value with shape (N, C, H, W).\n Each value should usually be mean centered and std scaled.\n multi_batch_data_samples (Dict[str, List[:obj:`DetDataSample`]]):\n The dict of multi-branch data samples.\n\n Returns:\n dict: A dictionary of loss components\n \"\"\"\n losses = dict()\n losses.update(**self.loss_by_gt_instances(multi_batch_inputs['sup'], multi_batch_data_samples['sup']))\n (origin_pseudo_data_samples, batch_info) = self.get_pseudo_instances(multi_batch_inputs['unsup_teacher'], multi_batch_data_samples['unsup_teacher'])\n multi_batch_data_samples['unsup_student'] = self.project_pseudo_instances(origin_pseudo_data_samples, multi_batch_data_samples['unsup_student'])\n losses.update(**self.loss_by_pseudo_instances(multi_batch_inputs['unsup_student'], multi_batch_data_samples['unsup_student'], batch_info))\n return losses","code_tokens":"","url":491263} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"mailbox.py","full_name":"Mailbox.itervalues","func_name":"itervalues","docstring":"Return an iterator over all messages.","docstring_tokens":"","code":"def itervalues(self):\n \"\"\"Return an iterator over all messages.\"\"\"\n for key in self.iterkeys():\n try:\n value = self[key]\n except KeyError:\n continue\n yield value","code_tokens":"","url":280713} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"train_utils.py","full_name":"train_step","func_name":"train_step","docstring":"Runs a single training step.","docstring_tokens":"","code":"def train_step(sess, train_op, loss, global_step):\n \"\"\"Runs a single training step.\"\"\"\n start_time = time.time()\n (_, loss_val, global_step_val) = sess.run([train_op, loss, global_step])\n duration = time.time() - start_time\n if global_step_val % 10 == 0:\n examples_per_sec = FLAGS.batch_size \/ duration\n sec_per_batch = float(duration)\n format_str = 'step %d, loss = %.2f (%.1f examples\/sec; %.3f sec\/batch)'\n tf.logging.info(format_str % (global_step_val, loss_val, examples_per_sec, sec_per_batch))\n if np.isnan(loss_val):\n raise OverflowError('Loss is nan')\n return global_step_val","code_tokens":"","url":585386} +{"project_name":"zackmcnulty\/CSE_446-Machine_Learning","file_name":"mathtext.py","full_name":"Parser.get_state","func_name":"get_state","docstring":"Get the current :class:`State` of the parser.","docstring_tokens":"","code":"def get_state(self):\n \"\"\"\n Get the current :class:`State` of the parser.\n \"\"\"\n return self._state_stack[-1]","code_tokens":"","url":194468} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"trainer_lib.py","full_name":"create_hparams","func_name":"create_hparams","docstring":"Create HParams with data_dir and problem hparams, if kwargs provided.","docstring_tokens":"","code":"def create_hparams(hparams_set, hparams_overrides_str='', data_dir=None, problem_name=None):\n \"\"\"Create HParams with data_dir and problem hparams, if kwargs provided.\"\"\"\n hparams = registry.hparams(hparams_set)\n if data_dir:\n hparams.add_hparam('data_dir', data_dir)\n if problem_name:\n add_problem_hparams(hparams, problem_name)\n if hparams_overrides_str:\n tf.logging.info('Overriding hparams in %s with %s', hparams_set, hparams_overrides_str)\n hparams = hparams.parse(hparams_overrides_str)\n return hparams","code_tokens":"","url":966220} +{"project_name":"Deci-AI\/super-gradients","file_name":"ddr_loss_test.py","full_name":"DDRLossTest.test_with_auxiliary_loss","func_name":"test_with_auxiliary_loss","docstring":"Auxiliary loss, 2 prediction maps, as DDRNet paper.","docstring_tokens":"","code":"def test_with_auxiliary_loss(self):\n \"\"\"\n Auxiliary loss, 2 prediction maps, as DDRNet paper.\n \"\"\"\n predictions = [self.predictions, self.predictions]\n weights = [1.0, 0.4]\n criterion = DDRNetLoss(1 \/ self.num_classes - self.eps, ohem_percentage=0.1, weights=weights)\n expected_loss = -torch.log(torch.tensor(1 \/ self.num_classes)) * weights[0] + -torch.log(torch.tensor(1 \/ self.num_classes)) * weights[1]\n (loss, _) = criterion(predictions, self.targets)\n self.assertAlmostEqual(expected_loss, loss, delta=1e-05)","code_tokens":"","url":880651} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"box_utils.py","full_name":"denormalize_boxes","func_name":"denormalize_boxes","docstring":"Converts boxes normalized by [height, width] to pixel coordinates.","docstring_tokens":"","code":"def denormalize_boxes(boxes, image_shape):\n \"\"\"Converts boxes normalized by [height, width] to pixel coordinates.\n\n Args:\n boxes: a tensor whose last dimension is 4 representing the coordinates of\n boxes in ymin, xmin, ymax, xmax order.\n image_shape: a list of two integers, a two-element vector or a tensor such\n that all but the last dimensions are `broadcastable` to `boxes`. The last\n dimension is 2, which represents [height, width].\n\n Returns:\n denormalized_boxes: a tensor whose shape is the same as `boxes` representing\n the denormalized boxes.\n\n Raises:\n ValueError: If the last dimension of boxes is not 4.\n \"\"\"\n with tf.name_scope('denormalize_boxes'):\n if isinstance(image_shape, list) or isinstance(image_shape, tuple):\n (height, width) = image_shape\n else:\n image_shape = tf.cast(image_shape, dtype=boxes.dtype)\n (height, width) = tf.split(image_shape, 2, axis=-1)\n (ymin, xmin, ymax, xmax) = tf.split(boxes, 4, axis=-1)\n ymin = ymin * height\n xmin = xmin * width\n ymax = ymax * height\n xmax = xmax * width\n denormalized_boxes = tf.concat([ymin, xmin, ymax, xmax], axis=-1)\n return denormalized_boxes","code_tokens":"","url":850992} +{"project_name":"google-research\/tensor2robot","file_name":"tec.py","full_name":"embed_condition_images","func_name":"embed_condition_images","docstring":"Independently embed a (meta)-batch of images.","docstring_tokens":"","code":"@gin.configurable\ndef embed_condition_images(condition_image, scope, reuse=tf.AUTO_REUSE, fc_layers=None, use_spatial_softmax=True):\n \"\"\"Independently embed a (meta)-batch of images.\n\n Args:\n condition_image: A rank 4 tensor of images: [N, H, W, C].\n scope: Name of the tf variable_scope.\n reuse: The variable_scope reuse setting.\n fc_layers: An optional tuple of ints describing the number of units in each\n fully-connected hidden layer, or 1x1 conv layer when excluding spatial\n softmax.\n use_spatial_softmax: Whether to use a spatial softmax or not.\n\n Returns:\n A rank 2 tensor of embeddings: [N, embedding size] if spatial_softmax is\n True. Otherwise, a rank 4 tensor of visual features [N, H, W, embedding\n size]\n Raises:\n ValueError if `condition_image` has incorrect rank.\n \"\"\"\n if len(condition_image.shape) != 4:\n raise ValueError('Image has unexpected shape {}.'.format(condition_image.shape))\n with tf.variable_scope(scope, reuse=reuse, use_resource=True):\n (image_embedding, _) = vision_layers.BuildImagesToFeaturesModel(condition_image, use_spatial_softmax=use_spatial_softmax)\n if fc_layers is not None:\n if len(image_embedding.shape) == 2:\n image_embedding = layers.stack(image_embedding, layers.fully_connected, fc_layers[:-1], activation_fn=tf.nn.relu, normalizer_fn=layers.layer_norm)\n image_embedding = layers.fully_connected(image_embedding, fc_layers[-1], activation_fn=None)\n else:\n image_embedding = layers.stack(image_embedding, layers.conv2d, fc_layers[:-1], kernel_size=[1, 1], activation_fn=tf.nn.relu, normalizer_fn=layers.layer_norm)\n image_embedding = layers.conv2d(image_embedding, fc_layers[-1], activation_fn=None)\n return image_embedding","code_tokens":"","url":908151} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"bf_variational_neural_bandit_model.py","full_name":"analytic_kl","func_name":"analytic_kl","docstring":"KL for two Gaussian distributions with diagonal covariance matrix.","docstring_tokens":"","code":"def analytic_kl(mu_1, sigma_1, mu_2, sigma_2):\n \"\"\"KL for two Gaussian distributions with diagonal covariance matrix.\"\"\"\n kl = tfd.kl_divergence(tfd.MVNDiag(mu_1, sigma_1), tfd.MVNDiag(mu_2, sigma_2))\n return kl","code_tokens":"","url":762230} +{"project_name":"ldkong1205\/LaserMix","file_name":"local_visualizer.py","full_name":"Det3DLocalVisualizer.set_points","func_name":"set_points","docstring":"Set the point cloud to draw.","docstring_tokens":"","code":"@master_only\ndef set_points(self, points: np.ndarray, pcd_mode: int=0, vis_mode: str='replace', frame_cfg: dict=dict(size=1, origin=[0, 0, 0]), points_color: Tuple[float]=(0.8, 0.8, 0.8), points_size: int=2, mode: str='xyz') -> None:\n \"\"\"Set the point cloud to draw.\n\n Args:\n points (np.ndarray): Points to visualize with shape (N, 3+C).\n pcd_mode (int): The point cloud mode (coordinates): 0 represents\n LiDAR, 1 represents CAMERA, 2 represents Depth. Defaults to 0.\n vis_mode (str): The visualization mode in Open3D:\n\n - 'replace': Replace the existing point cloud with input point\n cloud.\n - 'add': Add input point cloud into existing point cloud.\n\n Defaults to 'replace'.\n frame_cfg (dict): The coordinate frame config for Open3D\n visualization initialization.\n Defaults to dict(size=1, origin=[0, 0, 0]).\n points_color (Tuple[float]): The color of points.\n Defaults to (1, 1, 1).\n points_size (int): The size of points to show on visualizer.\n Defaults to 2.\n mode (str): Indicate type of the input points, available mode\n ['xyz', 'xyzrgb']. Defaults to 'xyz'.\n \"\"\"\n assert points is not None\n assert vis_mode in ('replace', 'add')\n check_type('points', points, np.ndarray)\n if not hasattr(self, 'o3d_vis'):\n self.o3d_vis = self._initialize_o3d_vis()\n if pcd_mode != Coord3DMode.DEPTH:\n points = Coord3DMode.convert(points, pcd_mode, Coord3DMode.DEPTH)\n if hasattr(self, 'pcd') and vis_mode != 'add':\n self.o3d_vis.remove_geometry(self.pcd)\n render_option = self.o3d_vis.get_render_option()\n if render_option is not None:\n render_option.point_size = points_size\n render_option.background_color = np.asarray([0, 0, 0])\n points = points.copy()\n pcd = geometry.PointCloud()\n if mode == 'xyz':\n pcd.points = o3d.utility.Vector3dVector(points[:, :3])\n points_colors = np.tile(np.array(points_color), (points.shape[0], 1))\n elif mode == 'xyzrgb':\n pcd.points = o3d.utility.Vector3dVector(points[:, :3])\n points_colors = points[:, 3:6]\n if not ((points_colors >= 0.0) & (points_colors <= 1.0)).all():\n points_colors \/= 255.0\n else:\n raise NotImplementedError\n mesh_frame = geometry.TriangleMesh.create_coordinate_frame(**frame_cfg)\n self.o3d_vis.add_geometry(mesh_frame)\n pcd.colors = o3d.utility.Vector3dVector(points_colors)\n self.o3d_vis.add_geometry(pcd)\n self.pcd = pcd\n self.points_colors = points_colors","code_tokens":"","url":624467} +{"project_name":"facebookresearch\/detectron2","file_name":"post_processing.py","full_name":"find_instance_center","func_name":"find_instance_center","docstring":"Find the center points from the center heatmap.","docstring_tokens":"","code":"def find_instance_center(center_heatmap, threshold=0.1, nms_kernel=3, top_k=None):\n \"\"\"\n Find the center points from the center heatmap.\n Args:\n center_heatmap: A Tensor of shape [1, H, W] of raw center heatmap output.\n threshold: A float, threshold applied to center heatmap score.\n nms_kernel: An integer, NMS max pooling kernel size.\n top_k: An integer, top k centers to keep.\n Returns:\n A Tensor of shape [K, 2] where K is the number of center points. The\n order of second dim is (y, x).\n \"\"\"\n center_heatmap = F.threshold(center_heatmap, threshold, -1)\n nms_padding = (nms_kernel - 1) \/\/ 2\n center_heatmap_max_pooled = F.max_pool2d(center_heatmap, kernel_size=nms_kernel, stride=1, padding=nms_padding)\n center_heatmap[center_heatmap != center_heatmap_max_pooled] = -1\n center_heatmap = center_heatmap.squeeze()\n assert len(center_heatmap.size()) == 2, 'Something is wrong with center heatmap dimension.'\n if top_k is None:\n return torch.nonzero(center_heatmap > 0)\n else:\n (top_k_scores, _) = torch.topk(torch.flatten(center_heatmap), top_k)\n return torch.nonzero(center_heatmap > top_k_scores[-1].clamp_(min=0))","code_tokens":"","url":549540} +{"project_name":"aramis-lab\/AD-DL","file_name":"cnn_utils.py","full_name":"evaluate_prediction","func_name":"evaluate_prediction","docstring":"Evaluates different metrics based on the list of true labels and predicted labels.","docstring_tokens":"","code":"def evaluate_prediction(y, y_pred):\n \"\"\"\n Evaluates different metrics based on the list of true labels and predicted labels.\n\n Args:\n y: (list) true labels\n y_pred: (list) corresponding predictions\n\n Returns:\n (dict) ensemble of metrics\n \"\"\"\n true_positive = np.sum((y_pred == 1) & (y == 1))\n true_negative = np.sum((y_pred == 0) & (y == 0))\n false_positive = np.sum((y_pred == 1) & (y == 0))\n false_negative = np.sum((y_pred == 0) & (y == 1))\n accuracy = (true_positive + true_negative) \/ (true_positive + true_negative + false_positive + false_negative)\n if true_positive + false_negative != 0:\n sensitivity = true_positive \/ (true_positive + false_negative)\n else:\n sensitivity = 0.0\n if false_positive + true_negative != 0:\n specificity = true_negative \/ (false_positive + true_negative)\n else:\n specificity = 0.0\n if true_positive + false_positive != 0:\n ppv = true_positive \/ (true_positive + false_positive)\n else:\n ppv = 0.0\n if true_negative + false_negative != 0:\n npv = true_negative \/ (true_negative + false_negative)\n else:\n npv = 0.0\n balanced_accuracy = (sensitivity + specificity) \/ 2\n results = {'accuracy': accuracy, 'balanced_accuracy': balanced_accuracy, 'sensitivity': sensitivity, 'specificity': specificity, 'ppv': ppv, 'npv': npv}\n return results","code_tokens":"","url":39802} +{"project_name":"shepnerd\/inpainting_gmcnn","file_name":"ops.py","full_name":"bbox2mask","func_name":"bbox2mask","docstring":"Generate mask tensor from bbox.","docstring_tokens":"","code":"def bbox2mask(bbox, config, name='mask'):\n \"\"\"Generate mask tensor from bbox.\n\n Args:\n bbox: configuration tuple, (top, left, height, width)\n config: Config should have configuration including IMG_SHAPES,\n MAX_DELTA_HEIGHT, MAX_DELTA_WIDTH.\n\n Returns:\n tf.Tensor: output with shape [1, H, W, 1]\n\n \"\"\"\n\n def npmask(bbox, height, width, delta_h, delta_w):\n mask = np.zeros((1, height, width, 1), np.float32)\n h = np.random.randint(delta_h \/\/ 2 + 1)\n w = np.random.randint(delta_w \/\/ 2 + 1)\n mask[:, bbox[0] + h:bbox[0] + bbox[2] - h, bbox[1] + w:bbox[1] + bbox[3] - w, :] = 1.0\n return mask\n with tf.variable_scope(name), tf.device('\/cpu:0'):\n img_shape = config.img_shapes\n height = img_shape[0]\n width = img_shape[1]\n mask = tf.py_func(npmask, [bbox, height, width, config.max_delta_shapes[0], config.max_delta_shapes[1]], tf.float32, stateful=False)\n mask.set_shape([1] + [height, width] + [1])\n return mask","code_tokens":"","url":229842} +{"project_name":"Trusted-AI\/AIF360","file_name":"gerryfair_classifier.py","full_name":"GerryFairClassifier.generate_heatmap","func_name":"generate_heatmap","docstring":"Helper Function to generate the heatmap at the current time.","docstring_tokens":"","code":"def generate_heatmap(self, dataset, predictions, vmin=None, vmax=None, cols_index=[0, 1], eta=0.1):\n \"\"\"Helper Function to generate the heatmap at the current time.\n\n Args:\n iteration:current iteration\n dataset: dataset object with its own class definition in datasets\n folder inherits from class StandardDataset.\n predictions: predictions of the model self on dataset.\n vmin: see documentation of heatmap.py heat_map function\n vmax: see documentation of heatmap.py heat_map function\n \"\"\"\n (X, X_prime, y) = clean.extract_df_from_ds(dataset)\n X_prime_heat = X_prime.iloc[:, cols_index]\n minmax = heatmap.heat_map(X, X_prime_heat, y, predictions, eta, self.heatmap_path, vmin, vmax)","code_tokens":"","url":412188} +{"project_name":"sktime\/sktime","file_name":"test_intervals.py","full_name":"test_supervised_intervals_on_basic_motions","func_name":"test_supervised_intervals_on_basic_motions","docstring":"Test of SupervisedIntervals on basic motions data.","docstring_tokens":"","code":"@pytest.mark.skipif(not run_test_for_class(SupervisedIntervals), reason='run test only if softdeps are present and incrementally (if requested)')\ndef test_supervised_intervals_on_basic_motions():\n \"\"\"Test of SupervisedIntervals on basic motions data.\"\"\"\n (X_train, y_train) = load_basic_motions(split='train')\n indices = np.random.RandomState(4).choice(len(y_train), 5, replace=False)\n si = SupervisedIntervals(random_state=0, n_intervals=1, randomised_split_point=True)\n data = si.fit_transform(X_train.iloc[indices], y_train[indices])\n testing.assert_array_almost_equal(data, supervised_intervals_basic_motions_data, decimal=4)","code_tokens":"","url":877750} +{"project_name":"ludwig-ai\/ludwig","file_name":"test_gbm.py","full_name":"test_hummingbird_conversion_regression","func_name":"test_hummingbird_conversion_regression","docstring":"Verify that Hummingbird conversion predictions match LightGBM predictions for numeric outputs.","docstring_tokens":"","code":"def test_hummingbird_conversion_regression(tmpdir, local_backend):\n \"\"\"Verify that Hummingbird conversion predictions match LightGBM predictions for numeric outputs.\"\"\"\n input_features = [number_feature(), category_feature(encoder={'reduce_output': 'sum'})]\n output_features = [number_feature()]\n (preds_lgbm, model) = _train_and_predict_gbm(input_features, output_features, tmpdir, local_backend)\n with model.model.compile():\n (preds_hb, _) = model.predict(dataset=os.path.join(tmpdir, 'training.csv'), split='test')\n assert np.allclose(preds_hb, preds_lgbm, rtol=1e-06, atol=1e-06)","code_tokens":"","url":617252} +{"project_name":"anuragranj\/coma","file_name":"utils.py","full_name":"TextRCV1.show_classes_per_doc","func_name":"show_classes_per_doc","docstring":"Number of classes per document.","docstring_tokens":"","code":"def show_classes_per_doc(self):\n \"\"\"Number of classes per document.\"\"\"\n classes_per_doc = np.array(self.target.sum(axis=1)).squeeze()\n plt.figure(figsize=(17, 5))\n plt.plot(sorted(classes_per_doc[::-1]), '.')","code_tokens":"","url":467138} +{"project_name":"zhyhan\/TransPar","file_name":"freihand.py","full_name":"projectPoints","func_name":"projectPoints","docstring":"Project 3D coordinates into image space.","docstring_tokens":"","code":"def projectPoints(xyz, K):\n \"\"\" Project 3D coordinates into image space. \"\"\"\n xyz = np.array(xyz)\n K = np.array(K)\n uv = np.matmul(K, xyz.T).T\n return uv[:, :2] \/ uv[:, -1:]","code_tokens":"","url":356052} +{"project_name":"apple\/ml-cvnets","file_name":"byteformer.py","full_name":"ByteFormer.dummy_input_and_label","func_name":"dummy_input_and_label","docstring":"Get a dummy input and label that could be passed to the model.","docstring_tokens":"","code":"def dummy_input_and_label(self, batch_size: int) -> Dict:\n \"\"\"\n Get a dummy input and label that could be passed to the model.\n\n Args:\n batch_size: The batch size to use for the generated inputs.\n\n Returns:\n A dict with\n {\n \"samples\": tensor of shape [batch_size, sequence_length],\n \"targets\": tensor of shape [batch_size],\n }\n \"\"\"\n n_labels = 10\n max_value = 257\n samples = torch.randint(0, max_value, [batch_size, self.dummy_input_token_length])\n targets = torch.randint(low=0, high=n_labels, size=(batch_size,)).long()\n return {'samples': samples, 'targets': targets}","code_tokens":"","url":671306} +{"project_name":"BMW-InnovationLab\/BMW-Semantic--Training-GUI","file_name":"base.py","full_name":"KeyPointDataset.joint_pairs","func_name":"joint_pairs","docstring":"Joint pairs which defines the pairs of joint to be swapped when the image is flipped horizontally.","docstring_tokens":"","code":"@property\ndef joint_pairs(self):\n \"\"\"Joint pairs which defines the pairs of joint to be swapped\n when the image is flipped horizontally.\"\"\"\n return []","code_tokens":"","url":463140} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_boundary_decision_display.py","full_name":"test_string_target","func_name":"test_string_target","docstring":"Check that decision boundary works with classifiers trained on string labels.","docstring_tokens":"","code":"def test_string_target(pyplot):\n \"\"\"Check that decision boundary works with classifiers trained on string labels.\"\"\"\n iris = load_iris()\n X = iris.data[:, [0, 1]]\n y = iris.target_names[iris.target]\n log_reg = LogisticRegression().fit(X, y)\n DecisionBoundaryDisplay.from_estimator(log_reg, X, grid_resolution=5, response_method='predict')","code_tokens":"","url":364049} +{"project_name":"dmpelt\/msdnet","file_name":"data.py","full_name":"DataPoint.getall","func_name":"getall","docstring":"Return input image, target image, and mask image (when given).","docstring_tokens":"","code":"def getall(self):\n \"\"\"Return input image, target image, and mask image (when given).\"\"\"\n return (self.input, self.target, self.mask)","code_tokens":"","url":265112} +{"project_name":"yehengchen\/Object-Detection-and-Tracking","file_name":"model.py","full_name":"DarknetConv2D","func_name":"DarknetConv2D","docstring":"Wrapper to set Darknet parameters for Convolution2D.","docstring_tokens":"","code":"@wraps(Conv2D)\ndef DarknetConv2D(*args, **kwargs):\n \"\"\"Wrapper to set Darknet parameters for Convolution2D.\"\"\"\n darknet_conv_kwargs = {'kernel_regularizer': l2(0.0005)}\n darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides') == (2, 2) else 'same'\n darknet_conv_kwargs.update(kwargs)\n return Conv2D(*args, **darknet_conv_kwargs)","code_tokens":"","url":725977} +{"project_name":"AboudyKreidieh\/h-baselines","file_name":"test_replay_buffer.py","full_name":"TestHierReplayBuffer.test_buffer_size","func_name":"test_buffer_size","docstring":"Validate the buffer_size output from the replay buffer.","docstring_tokens":"","code":"def test_buffer_size(self):\n \"\"\"Validate the buffer_size output from the replay buffer.\"\"\"\n self.assertEqual(self.replay_buffer.buffer_size, 2)","code_tokens":"","url":574124} +{"project_name":"Farama-Foundation\/D4RL","file_name":"module.py","full_name":"get_mujoco_py","func_name":"get_mujoco_py","docstring":"Returns the mujoco_py module.","docstring_tokens":"","code":"def get_mujoco_py():\n \"\"\"Returns the mujoco_py module.\"\"\"\n global _MUJOCO_PY_MODULE\n if _MUJOCO_PY_MODULE:\n return _MUJOCO_PY_MODULE\n try:\n import mujoco_py\n from mujoco_py.builder import cymj\n cymj.set_warning_callback(_mj_warning_fn)\n except ImportError:\n print('Failed to import mujoco_py. Ensure that mujoco_py (using MuJoCo v1.50) is installed.', file=sys.stderr)\n sys.exit(1)\n _MUJOCO_PY_MODULE = mujoco_py\n return mujoco_py","code_tokens":"","url":126308} +{"project_name":"akandykeller\/NeuralWaveMachines","file_name":"utils_test.py","full_name":"MakeAsyncTest.testNonBlocking","func_name":"testNonBlocking","docstring":"Tests async function doesn't block the main thread.","docstring_tokens":"","code":"def testNonBlocking(self):\n \"\"\"Tests async function doesn't block the main thread.\"\"\"\n r = []\n async_fn = utils.make_async()(lambda : r.append((time.sleep(5), 'a')))\n r.append((None, 'b'))\n async_fn().result()\n self.assertListEqual(r, [(None, 'b'), (None, 'a')])","code_tokens":"","url":293641} +{"project_name":"Zhenye-Na\/machine-learning-uiuc","file_name":"logistic_model.py","full_name":"LogisticModel.load_model","func_name":"load_model","docstring":"Load pretrained weghit from a binary file.","docstring_tokens":"","code":"def load_model(self, weight_file):\n \"\"\" Load pretrained weghit from a binary file.\n Args:\n weight_file(str): binary file to load from.\n \"\"\"\n self.W = np.fromfile(weight_file, dtype=np.float32)\n print('model loaded from', weight_file)","code_tokens":"","url":621027} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"versioncontrol.py","full_name":"VersionControl.get_requirement_revision","func_name":"get_requirement_revision","docstring":"Return the revision string that should be used in a requirement.","docstring_tokens":"","code":"@classmethod\ndef get_requirement_revision(cls, repo_dir):\n \"\"\"\n Return the revision string that should be used in a requirement.\n \"\"\"\n return cls.get_revision(repo_dir)","code_tokens":"","url":83876} +{"project_name":"thaines\/helit","file_name":"isotropic.py","full_name":"IsotropicGMM.getMix","func_name":"getMix","docstring":"Returns the mixing weight for the given cluster.","docstring_tokens":"","code":"def getMix(self, i):\n \"\"\"Returns the mixing weight for the given cluster.\"\"\"\n return self.mix[i]","code_tokens":"","url":591728} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"base.py","full_name":"Index.holds_integer","func_name":"holds_integer","docstring":"Whether the type is an integer type.","docstring_tokens":"","code":"def holds_integer(self):\n \"\"\"\n Whether the type is an integer type.\n \"\"\"\n return self.inferred_type in ['integer', 'mixed-integer']","code_tokens":"","url":82873} +{"project_name":"MycroftAI\/mycroft-core","file_name":"event_container.py","full_name":"EventContainer.add","func_name":"add","docstring":"Create event handler for executing intent or other event.","docstring_tokens":"","code":"def add(self, name, handler, once=False):\n \"\"\"Create event handler for executing intent or other event.\n\n Args:\n name (string): IntentParser name\n handler (func): Method to call\n once (bool, optional): Event handler will be removed after it has\n been run once.\n \"\"\"\n\n def once_wrapper(message):\n self.remove(name)\n handler(message)\n if handler:\n if once:\n self.bus.once(name, once_wrapper)\n self.events.append((name, once_wrapper))\n else:\n self.bus.on(name, handler)\n self.events.append((name, handler))\n LOG.debug('Added event: {}'.format(name))","code_tokens":"","url":290591} +{"project_name":"nosmokingbandit\/watcher","file_name":"caching.py","full_name":"Cache.delete","func_name":"delete","docstring":"Remove ALL cached variants of the current resource.","docstring_tokens":"","code":"def delete(self):\n \"\"\"Remove ALL cached variants of the current resource.\"\"\"\n raise NotImplemented","code_tokens":"","url":381384} +{"project_name":"rudranil723\/mini-main","file_name":"geometry.py","full_name":"GEOSGeometryBase.kml","func_name":"kml","docstring":"Return the KML representation of this Geometry.","docstring_tokens":"","code":"@property\ndef kml(self):\n \"\"\"Return the KML representation of this Geometry.\"\"\"\n gtype = self.geom_type\n return '<%s>%s<\/%s>' % (gtype, self.coord_seq.kml, gtype)","code_tokens":"","url":315310} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"function.py","full_name":"_DefinedFunction.add_to_graph","func_name":"add_to_graph","docstring":"Adds this function into the graph g.","docstring_tokens":"","code":"def add_to_graph(self, g):\n \"\"\"Adds this function into the graph g.\"\"\"\n self._create_definition_if_needed()\n prev = g._get_function(self.name)\n if prev and prev._hash_str == self._hash_str:\n return\n g._add_function(self)\n for f in self._sub_functions.values():\n f.add_to_graph(g)\n if self._grad_func:\n self._grad_func.add_to_graph(g)","code_tokens":"","url":605353} +{"project_name":"wandb\/wandb","file_name":"test_spec.py","full_name":"test_3_2_6_2_if","func_name":"test_3_2_6_2_if","docstring":"Promises returned by then must be rejected when any of their callbacks throw an exception.","docstring_tokens":"","code":"def test_3_2_6_2_if():\n \"\"\"\n Promises returned by then must be rejected when any of their\n callbacks throw an exception.\n \"\"\"\n\n def fail(v):\n raise AssertionError('Exception Message')\n p1 = Promise.resolve(5)\n pf = p1.then(fail)\n pf._wait()\n assert pf.is_rejected\n assert_exception(pf.reason, AssertionError, 'Exception Message')\n p2 = Promise.reject(Exception('Error'))\n pr = p2.then(None, fail)\n pr._wait()\n assert pr.is_rejected\n assert_exception(pr.reason, AssertionError, 'Exception Message')","code_tokens":"","url":941984} +{"project_name":"nhsx\/SynthVAE","file_name":"common.py","full_name":"DPModules_test.compare_gradients","func_name":"compare_gradients","docstring":"Runs forward and backward through both the standard nn_module and the dp_module and checks that all gradients are indeed the same.","docstring_tokens":"","code":"def compare_gradients(self, nn_module: nn.Module, dp_module: nn.Module, train_fn: Callable, *train_fn_args, atol: float=1e-05, rtol: float=0.0001, **train_fn_kwargs) -> None:\n \"\"\"\n Runs forward and backward through both the standard nn_module and the dp_module and\n checks that all gradients are indeed the same.\n\n Args:\n nn_module: The original nn.Module that will be our reference\n dp_module: Our dp_module reimplementation that we want to test against ``nn_module``\n train_fn: A function that we can run to train the model on a single input batch.\n It should run forward and backward and stop there.\n Refer to ``default_train_fn`` in this file for an example.\n *train_fn_args: args to pass to the train_fn (ie we'll call\n ``train_fn(*train_fn_args, **train_fn_kwargs))``.\n atol: Absolute tolerance.\n rtol: Relative tolerance.\n **train_fn_kwargs: kwargs to pass to the train_fn (ie we'll call\n ``module(*module_args, **module_kwargs))``.\n Returns:\n None\n\n Raises:\n AssertionError if either:\n - nn_module has a gradient for a parameter that dp_module doesn't have.\n - dp_module has a gradient for a parameter that nn_module doesn't have.\n - The shape of any parameter gradient doesn't match.\n - The values for any parameter gradient ``nn_grad`` differ by more than\n `atol + rtol * abs(nn_grad)`.\n \"\"\"\n train_fn(nn_module, *train_fn_args, **train_fn_kwargs)\n train_fn(dp_module, *train_fn_args, **train_fn_kwargs)\n nn_params = dict(nn_module.named_parameters())\n dp_params = dict(dp_module.named_parameters())\n nn_only_grads = [param_name for (param_name, param) in nn_params.items() if param.grad is not None and param_name not in dp_params]\n if nn_only_grads:\n failed_str = '\\n\\t'.join((f'{i}. {s}' for (i, s) in enumerate(nn_only_grads, 1)))\n raise AssertionError(f'A total of {len(nn_only_grads)} gradients are in nn_module but not in dp_module: \\n\\t{failed_str}')\n dp_only_grads = [param_name for (param_name, param) in dp_params.items() if param.grad is not None and param_name not in nn_params]\n if dp_only_grads:\n failed_str = '\\n\\t'.join((f'{i}. {s}' for (i, s) in enumerate(nn_only_grads, 1)))\n raise AssertionError(f'A total of {len(nn_only_grads)} gradients are in dp_module but not in nn_module: \\n\\t{failed_str}')\n for (param_name, nn_param) in nn_module.named_parameters():\n dp_param = dp_params[param_name]\n self._check_shapes(nn_param, dp_param, param_name)\n self._check_values(nn_param, dp_param, atol, rtol, param_name)","code_tokens":"","url":906231} +{"project_name":"nodefluxio\/vortex","file_name":"model.py","full_name":"ModelBase.output_format","func_name":"output_format","docstring":"Define the format ('indices' and 'axis' for each output) to extract the output for single batch.","docstring_tokens":"","code":"@property\n@abstractmethod\ndef output_format(self):\n \"\"\"Define the format ('indices' and 'axis' for each output) to\n extract the output for single batch.\n \"\"\"\n pass","code_tokens":"","url":946650} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"document.py","full_name":"Document.is_cursor_at_the_end_of_line","func_name":"is_cursor_at_the_end_of_line","docstring":"True when the cursor is at the end of this line.","docstring_tokens":"","code":"@property\ndef is_cursor_at_the_end_of_line(self) -> bool:\n \"\"\" True when the cursor is at the end of this line. \"\"\"\n return self.current_char in ('\\n', '')","code_tokens":"","url":434993} +{"project_name":"QinganZhao\/Deep-Learning-Based-Structural-Damage-Detection","file_name":"cpp_lint.py","full_name":"GetHeaderGuardCPPVariable","func_name":"GetHeaderGuardCPPVariable","docstring":"Returns the CPP variable that should be used as a header guard.","docstring_tokens":"","code":"def GetHeaderGuardCPPVariable(filename):\n \"\"\"Returns the CPP variable that should be used as a header guard.\n\n Args:\n filename: The name of a C++ header file.\n\n Returns:\n The CPP variable that should be used as a header guard in the\n named file.\n\n \"\"\"\n filename = re.sub('_flymake\\\\.h$', '.h', filename)\n filename = re.sub('\/\\\\.flymake\/([^\/]*)$', '\/\\\\1', filename)\n fileinfo = FileInfo(filename)\n file_path_from_root = fileinfo.RepositoryName()\n if _root:\n file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)\n return re.sub('[-.\/\\\\s]', '_', file_path_from_root).upper() + '_'","code_tokens":"","url":127538} +{"project_name":"instadeepai\/jumanji","file_name":"utils.py","full_name":"CanMoveCarry.target","func_name":"target","docstring":"Tile at target index of row.","docstring_tokens":"","code":"@property\ndef target(self) -> chex.Numeric:\n \"\"\"Tile at target index of row.\"\"\"\n return self.row[self.target_idx]","code_tokens":"","url":594024} +{"project_name":"SilenceDut\/nbaplus-server","file_name":"testing.py","full_name":"HTMLTreeBuilderSmokeTest.test_nested_inline_elements","func_name":"test_nested_inline_elements","docstring":"Inline elements can be nested indefinitely.","docstring_tokens":"","code":"def test_nested_inline_elements(self):\n \"\"\"Inline elements can be nested indefinitely.\"\"\"\n b_tag = 'Inside a B tag<\/b>'\n self.assertSoupEquals(b_tag)\n nested_b_tag = '

A nested tag<\/b><\/i><\/p>'\n self.assertSoupEquals(nested_b_tag)\n double_nested_b_tag = '

A doubly nested tag<\/b><\/i><\/a><\/p>'\n self.assertSoupEquals(nested_b_tag)","code_tokens":"","url":291929} +{"project_name":"arshpreetsingh\/quantopian-machinelearning","file_name":"__init__.py","full_name":"month_end","func_name":"month_end","docstring":"Get the end of the month for a given date.","docstring_tokens":"","code":"def month_end(dt):\n \"\"\"Get the end of the month for a given date.\"\"\"\n return month_start(dt) - timedelta(days=1)","code_tokens":"","url":816759} +{"project_name":"mpeychev\/disentangled-autoencoders","file_name":"util.py","full_name":"get_autoencoder_data_dir","func_name":"get_autoencoder_data_dir","docstring":"Returns the directory of the data to be used for training the autoencoder.","docstring_tokens":"","code":"def get_autoencoder_data_dir():\n \"\"\"Returns the directory of the data to be used for training the autoencoder.\"\"\"\n return os.path.join(get_data_dir(), 'autoencoder')","code_tokens":"","url":552041} +{"project_name":"kukuruza\/shuffler","file_name":"draw.py","full_name":"drawScoredRoi","func_name":"drawScoredRoi","docstring":"Draw a bounding box on top of image.","docstring_tokens":"","code":"def drawScoredRoi(img, roi, label=None, score=None, fill_opacity=0.0, colormap='inferno_r', **kwargs):\n \"\"\"\n Draw a bounding box on top of image.\n Args:\n img: Numpy color image.\n roi: List\/tuple [y1, x1, y2, x2].\n label: String to print near the bounding box or None.\n score: A float in range [0, 1] or None.\n fill_opacity: If > 0, fill in the bounding box with specified opacity.\n colormap: Name of the Matplotlib colormap.\n kwargs: Ignored.\n Return:\n Nothing, 'img' is changed in place.\n \"\"\"\n assert len(img.shape) == 3 and img.shape[2] == 3, 'Image must be color, but is grayscale: %s' % str(img.shape)\n assert score is None or (score >= 0 and score <= 1)\n if label is None:\n label = ''\n label = general_utils.maybeDecode(label)\n if score is None:\n score = 1\n color = tuple([int(x * 255) for x in plt.cm.get_cmap(colormap)(float(score))][0:3][::-1])\n roi = [int(a) for a in roi]\n text_coords = (roi[1], roi[0] - SCALE)\n cv2.putText(img, label, text_coords, FONT, FONT_SIZE, TEXT_COLOR, THICKNESS)\n cv2.putText(img, label, text_coords, FONT, FONT_SIZE, TEXT_BACKCOLOR, THICKNESS - 1)\n if fill_opacity > 0:\n _drawFilledRoi(img, roi, color, fill_opacity)\n cv2.rectangle(img, (roi[1], roi[0]), (roi[3], roi[2]), color, THICKNESS)","code_tokens":"","url":933880} +{"project_name":"agoragames\/haigha","file_name":"connection.py","full_name":"Connection.synchronous","func_name":"synchronous","docstring":"True if transport is synchronous or the connection has been forced into synchronous mode, False otherwise.","docstring_tokens":"","code":"@property\ndef synchronous(self):\n \"\"\"\n True if transport is synchronous or the connection has been forced\n into synchronous mode, False otherwise.\n \"\"\"\n if self._transport is None:\n if self._close_info and len(self._close_info['reply_text']) > 0:\n raise ConnectionClosed('connection is closed: %s : %s' % (self._close_info['reply_code'], self._close_info['reply_text']))\n raise ConnectionClosed('connection is closed')\n return self.transport.synchronous or self._synchronous","code_tokens":"","url":234550} +{"project_name":"RasaHQ\/rasa","file_name":"exceptions.py","full_name":"InvalidEntityFormatException.create_from","func_name":"create_from","docstring":"Creates `InvalidEntityFormatException` from `JSONDecodeError`.","docstring_tokens":"","code":"@classmethod\ndef create_from(cls, other: json.JSONDecodeError, msg: Text) -> 'InvalidEntityFormatException':\n \"\"\"Creates `InvalidEntityFormatException` from `JSONDecodeError`.\"\"\"\n return cls(msg, other.doc, other.pos)","code_tokens":"","url":837384} +{"project_name":"jimtin\/Stock_Comparison","file_name":"utils.py","full_name":"get_dasharray","func_name":"get_dasharray","docstring":"Get an SVG dash array for the given matplotlib linestyle Parameters ---------- obj : matplotlib object The matplotlib line or path object, which must have a get_linestyle() method which returns a valid matplotlib line code i : integer (optional) Returns ------- dasharray : string The HTML\/SVG dasharray code associated with the object.","docstring_tokens":"","code":"def get_dasharray(obj, i=None):\n \"\"\"Get an SVG dash array for the given matplotlib linestyle\n\n Parameters\n ----------\n obj : matplotlib object\n The matplotlib line or path object, which must have a get_linestyle()\n method which returns a valid matplotlib line code\n i : integer (optional)\n\n Returns\n -------\n dasharray : string\n The HTML\/SVG dasharray code associated with the object.\n \"\"\"\n if obj.__dict__.get('_dashSeq', None) is not None:\n return ','.join(map(str, obj._dashSeq))\n else:\n ls = obj.get_linestyle()\n if i is not None:\n ls = ls[i]\n dasharray = LINESTYLES.get(ls, None)\n if dasharray is None:\n warnings.warn(\"dash style '{0}' not understood: defaulting to solid.\".format(ls))\n dasharray = LINESTYLES['-']\n return dasharray","code_tokens":"","url":389263} +{"project_name":"ZumoLabs\/zpy","file_name":"files.py","full_name":"write_json","func_name":"write_json","docstring":"Save data to json file.","docstring_tokens":"","code":"def write_json(path: Union[Path, str], data: Union[Dict, List]) -> None:\n \"\"\"Save data to json file.\n\n Args:\n path (Union[Path, str]): Path to output json.\n data (Union[Dict, List]): Data to save.\n\n Raises:\n ValueError: Path is not a json file.\n \"\"\"\n path = to_pathlib_path(path)\n if not path.suffix == '.json':\n raise ValueError(f'{path} is not a JSON file.')\n log.info(f'Writing JSON to file {path}')\n with path.open('w') as f:\n json.dump(data, f, indent=4)","code_tokens":"","url":972021} +{"project_name":"hans\/pyccg","file_name":"lexicon.py","full_name":"get_candidate_categories","func_name":"get_candidate_categories","docstring":"Find candidate categories for the given tokens which appear in `sentence` such that `sentence` yields a parse.","docstring_tokens":"","code":"def get_candidate_categories(lex, tokens, sentence, smooth=0.001):\n \"\"\"\n Find candidate categories for the given tokens which appear in `sentence` such\n that `sentence` yields a parse.\n\n Args:\n lex:\n tokens:\n sentence:\n smooth: If not `None`, add-k smooth the prior distribution over syntactic\n categories (where the float value of `smooth` specifies `k`).\n\n Returns:\n cat_dists: Dictionary mapping each token to a `Distribution` over\n categories.\n \"\"\"\n assert set(tokens).issubset(set(sentence))\n lex = lex.clone(retain_semantics=False)\n for token in tokens:\n lex.set_entries(token, [])\n category_prior = lex.observed_category_distribution(exclude_tokens=set(tokens), soft_propagate_roots=True)\n if smooth is not None:\n for key in category_prior.keys():\n category_prior[key] += smooth\n category_prior = category_prior.normalize()\n L.debug('Smoothed category prior with soft root propagation: %s', category_prior)\n\n def score_cat_assignment(cat_assignment):\n \"\"\"\n Assign a log-probability to a joint assignment of categories to tokens.\n \"\"\"\n for (token, category) in zip(tokens, cat_assignment):\n lex.set_entries(token, [(category, None, 0.001)])\n results = chart.WeightedCCGChartParser(lex, chart.DefaultRuleSet).parse(sentence, return_aux=True)\n if results:\n score = 0\n for (token, category) in zip(tokens, cat_assignment):\n score += np.log(category_prior[category])\n score += np.log(sum((np.exp(weight) for (_, weight, _) in results)))\n return score\n return -np.inf\n cat_assignment_weights = {cat_assignment: score_cat_assignment(cat_assignment) for cat_assignment in itertools.product(category_prior.keys(), repeat=len(tokens))}\n cat_dists = defaultdict(Distribution)\n for (cat_assignment, logp) in cat_assignment_weights.items():\n for (token, token_cat_assignment) in zip(tokens, cat_assignment):\n cat_dists[token][token_cat_assignment] += np.exp(logp)\n cat_dists = {token: dist.normalize() for (token, dist) in cat_dists.items()}\n return cat_dists","code_tokens":"","url":295930} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"curses_ui_test.py","full_name":"CursesTest.testRunUIEmptyCommand","func_name":"testRunUIEmptyCommand","docstring":"Issue an empty command then exit.","docstring_tokens":"","code":"def testRunUIEmptyCommand(self):\n \"\"\"Issue an empty command then exit.\"\"\"\n ui = MockCursesUI(40, 80, command_sequence=[[], self._EXIT])\n ui.run_ui()\n self.assertEqual(0, len(ui.unwrapped_outputs))","code_tokens":"","url":182388} +{"project_name":"jimtin\/Stock_Comparison","file_name":"test_path.py","full_name":"TestBasics.test_explicit_module","func_name":"test_explicit_module","docstring":"The user may specify an explicit path module to use.","docstring_tokens":"","code":"def test_explicit_module(self):\n \"\"\"\n The user may specify an explicit path module to use.\n \"\"\"\n nt_ok = Path.using_module(ntpath)('foo\\\\bar\\\\baz')\n posix_ok = Path.using_module(posixpath)('foo\/bar\/baz')\n posix_wrong = Path.using_module(posixpath)('foo\\\\bar\\\\baz')\n assert nt_ok.dirname() == 'foo\\\\bar'\n assert posix_ok.dirname() == 'foo\/bar'\n assert posix_wrong.dirname() == ''\n assert nt_ok \/ 'quux' == 'foo\\\\bar\\\\baz\\\\quux'\n assert posix_ok \/ 'quux' == 'foo\/bar\/baz\/quux'","code_tokens":"","url":384363} +{"project_name":"shervinea\/enzynet","file_name":"generate_datasets.py","full_name":"create_pdb_to_class_mapping","func_name":"create_pdb_to_class_mapping","docstring":"Creates dictionary linking PDB IDs to their corresponding classes.","docstring_tokens":"","code":"def create_pdb_to_class_mapping(save: bool=False) -> None:\n \"\"\"Creates dictionary linking PDB IDs to their corresponding classes.\"\"\"\n labels_all = {}\n labels_single = {}\n labels_multi = {}\n for pdb_class in range(1, constants.N_CLASSES + 1):\n enzymes = pd.read_table(os.path.join(constants.MAKE_FILES_DIR, f'{pdb_class}.txt'), header=None)\n enzymes = enzymes[0].tolist()\n for pdb_id in enzymes:\n if pdb_id in labels_all:\n labels_all[pdb_id] += [pdb_class]\n else:\n labels_all[pdb_id] = [pdb_class]\n for (pdb_id, pdb_classes) in labels_all.items():\n if len(pdb_classes) == 1:\n labels_single[pdb_id] = more_itertools.one(pdb_classes)\n else:\n labels_multi[pdb_id] = pdb_classes\n if save:\n tools.dict_to_csv(labels_all, os.path.join(constants.DATASETS_DIR, 'dataset_all.csv'))\n tools.dict_to_csv(labels_single, os.path.join(constants.DATASETS_DIR, 'dataset_single.csv'))\n tools.dict_to_csv(labels_multi, os.path.join(constants.DATASETS_DIR, 'dataset_multi.csv'))","code_tokens":"","url":178205} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"trainer_lib.py","full_name":"get_summary_writer","func_name":"get_summary_writer","docstring":"Creates a directory for writing summaries and returns a writer.","docstring_tokens":"","code":"def get_summary_writer(tensorboard_dir):\n \"\"\"Creates a directory for writing summaries and returns a writer.\"\"\"\n tf.logging.info('TensorBoard directory: %s', tensorboard_dir)\n tf.logging.info('Deleting prior data if exists...')\n try:\n gfile.DeleteRecursively(tensorboard_dir)\n except errors.OpError as err:\n tf.logging.error('Directory did not exist? Error: %s', err)\n tf.logging.info('Deleted! Creating the directory again...')\n gfile.MakeDirs(tensorboard_dir)\n tf.logging.info('Created! Instatiating SummaryWriter...')\n summary_writer = tf.summary.FileWriter(tensorboard_dir)\n return summary_writer","code_tokens":"","url":28656} +{"project_name":"rudranil723\/mini-main","file_name":"loggingTools.py","full_name":"Timer.time","func_name":"time","docstring":"Return the overall time (in seconds) since the timer started.","docstring_tokens":"","code":"def time(self):\n \"\"\" Return the overall time (in seconds) since the timer started. \"\"\"\n return self._time() - self.start","code_tokens":"","url":317205} +{"project_name":"rudranil723\/mini-main","file_name":"syntax.py","full_name":"ANSISyntaxTheme.get_style_for_token","func_name":"get_style_for_token","docstring":"Look up style in the style map.","docstring_tokens":"","code":"def get_style_for_token(self, token_type: TokenType) -> Style:\n \"\"\"Look up style in the style map.\"\"\"\n try:\n return self._style_cache[token_type]\n except KeyError:\n get_style = self.style_map.get\n token = tuple(token_type)\n style = self._missing_style\n while token:\n _style = get_style(token)\n if _style is not None:\n style = _style\n break\n token = token[:-1]\n self._style_cache[token_type] = style\n return style","code_tokens":"","url":268953} +{"project_name":"chainer\/chainer","file_name":"fliplr.py","full_name":"fliplr","func_name":"fliplr","docstring":"Flip array in the left\/right direction.","docstring_tokens":"","code":"def fliplr(a):\n \"\"\"Flip array in the left\/right direction.\n\n Args:\n a (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.\n\n Returns:\n ~chainer.Variable: Output variable.\n\n \"\"\"\n return FlipLR().apply((a,))[0]","code_tokens":"","url":477232} +{"project_name":"FriedRonaldo\/EditableGAN","file_name":"compare_ops.py","full_name":"weight_norm_linear","func_name":"weight_norm_linear","docstring":"Linear layer with Weight Normalization (Salimans, Kingma '16).","docstring_tokens":"","code":"def weight_norm_linear(input_, output_size, init=False, init_scale=1.0, name='wn_linear', initializer=tf.truncated_normal_initializer, stddev=0.02):\n \"\"\"Linear layer with Weight Normalization (Salimans, Kingma '16).\"\"\"\n with tf.variable_scope(name):\n if init:\n v = tf.get_variable('V', [int(input_.get_shape()[1]), output_size], tf.float32, initializer(0, stddev), trainable=True)\n v_norm = tf.nn.l2_normalize(v.initialized_value(), [0])\n x_init = tf.matmul(input_, v_norm)\n (m_init, v_init) = tf.nn.moments(x_init, [0])\n scale_init = init_scale \/ tf.sqrt(v_init + 1e-10)\n g = tf.get_variable('g', dtype=tf.float32, initializer=scale_init, trainable=True)\n b = tf.get_variable('b', dtype=tf.float32, initializer=-m_init * scale_init, trainable=True)\n x_init = tf.reshape(scale_init, [1, output_size]) * (x_init - tf.reshape(m_init, [1, output_size]))\n return x_init\n else:\n v = tf.get_variable('V')\n g = tf.get_variable('g')\n b = tf.get_variable('b')\n tf.assert_variables_initialized([v, g, b])\n x = tf.matmul(input_, v)\n scaler = g \/ tf.sqrt(tf.reduce_sum(tf.square(v), [0]))\n x = tf.reshape(scaler, [1, output_size]) * x + tf.reshape(b, [1, output_size])\n return x","code_tokens":"","url":548283} +{"project_name":"ludwig-ai\/ludwig","file_name":"preprocessing.py","full_name":"build_data","func_name":"build_data","docstring":"Preprocesses the input dataframe columns, handles missing values, and potentially adds metadata to training_set_metadata.","docstring_tokens":"","code":"def build_data(input_cols: DataFrame, feature_configs: List[Dict], training_set_metadata: Dict, backend: Backend, skip_save_processed_input: bool) -> Dict[str, DataFrame]:\n \"\"\"Preprocesses the input dataframe columns, handles missing values, and potentially adds metadata to\n training_set_metadata.\n\n Args:\n input_cols: Input dataframe to be processed.\n feature_configs: List of feature configs.\n training_set_metadata: Training set metadata. Additional fields may be added.\n backend: Backend for data processing.\n skip_save_processed_input: (bool) Whether to skip saving the processed input.\n\n Returns:\n Dictionary of (feature name) -> (processed data).\n \"\"\"\n proc_cols = {}\n for feature_config in feature_configs:\n preprocessing_parameters = training_set_metadata[feature_config[NAME]][PREPROCESSING]\n handle_missing_values(input_cols, feature_config, preprocessing_parameters, backend)\n handle_outliers(input_cols, feature_config, preprocessing_parameters, training_set_metadata[feature_config[NAME]], backend)\n get_from_registry(feature_config[TYPE], get_base_type_registry()).add_feature_data(feature_config, input_cols, proc_cols, training_set_metadata, preprocessing_parameters, backend, skip_save_processed_input)\n return proc_cols","code_tokens":"","url":616629} +{"project_name":"RasaHQ\/rasa","file_name":"test_telemetry.py","full_name":"patch_global_config_path","func_name":"patch_global_config_path","docstring":"Ensure we use a unique config path for each test to avoid tests influencing each other.","docstring_tokens":"","code":"@pytest.fixture(autouse=True)\ndef patch_global_config_path(tmp_path: Path) -> Generator[None, None, None]:\n \"\"\"Ensure we use a unique config path for each test to avoid tests influencing\n each other.\"\"\"\n default_location = rasa.constants.GLOBAL_USER_CONFIG_PATH\n rasa.constants.GLOBAL_USER_CONFIG_PATH = str(tmp_path \/ 'global.yml')\n yield\n rasa.constants.GLOBAL_USER_CONFIG_PATH = default_location","code_tokens":"","url":838022} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"test_lr_scheduler.py","full_name":"test_cosine_decay_function","func_name":"test_cosine_decay_function","docstring":"Tests Cosine lr decay function at (pi\/2) and verifies if the value is correct.","docstring_tokens":"","code":"def test_cosine_decay_function() -> None:\n \"\"\"\n Tests Cosine lr decay function at (pi\/2) and verifies if the value is correct.\n \"\"\"\n config = DummyModel(l_rate_scheduler=LRSchedulerType.Cosine, num_epochs=10, min_l_rate=0.0)\n test_epoch = 5\n (lr_scheduler, _) = _create_lr_scheduler_and_optimizer(config)\n for _ in range(test_epoch):\n lr_scheduler.step()\n assert lr_scheduler.get_last_lr()[0] == 0.5 * config.l_rate","code_tokens":"","url":613813} +{"project_name":"enlite-ai\/maze","file_name":"rollout_runner.py","full_name":"RolloutRunner.run","func_name":"run","docstring":"Parse the supplied Hydra config and perform the run.","docstring_tokens":"","code":"@override(Runner)\ndef run(self) -> None:\n \"\"\"Parse the supplied Hydra config and perform the run.\"\"\"\n start_time = time.time()\n self.run_with(self._cfg.env, self._cfg.wrappers if 'wrappers' in self._cfg else {}, self._cfg.policy)\n print(f'Rollout took {time.time() - start_time:.3f} seconds')","code_tokens":"","url":646749} +{"project_name":"ForrestPi\/ObjectDetectionTricks","file_name":"wavelet.py","full_name":"construct","func_name":"construct","docstring":"num_levels a wavelet decomposition of an image.","docstring_tokens":"","code":"def construct(im, num_levels, wavelet_type):\n \"\"\"num_levels a wavelet decomposition of an image.\n\n Args:\n im: A numpy or TF tensor of single or double precision floats of size\n (batch_size, width, height)\n num_levels: The number of levels (or scales) of the wavelet decomposition to\n apply. A value of 0 returns a \"wavelet decomposition\" that is just the\n image.\n wavelet_type: The kind of wavelet to use, see generate_filters().\n\n Returns:\n A wavelet decomposition of `im` that has `num_levels` levels (not including\n the coarsest residual level) and is of type `wavelet_type`. This\n decomposition is represented as a tuple of 3-tuples, with the final element\n being a tensor:\n ((band00, band01, band02), (band10, band11, band12), ..., resid)\n Where band** and resid are TF tensors. Each element of these nested tuples\n is of shape [batch_size, width * 2^-(level+1), height * 2^-(level+1)],\n though the spatial dimensions may be off by 1 if width and height are not\n factors of 2. The residual image is of the same (rough) size as the last set\n of bands. The floating point precision of these tensors matches that of\n `im`.\n \"\"\"\n if len(im.shape) != 3:\n raise ValueError('Expected `im` to have a rank of 3, but is of size {}'.format(im.shape))\n im = torch.as_tensor(im)\n if num_levels == 0:\n return (im,)\n max_num_levels = get_max_num_levels(im.shape)\n assert max_num_levels >= num_levels\n filters = generate_filters(wavelet_type)\n pyr = []\n for _ in range(num_levels):\n hi = _downsample(im, filters.analysis_hi, 0, 1)\n lo = _downsample(im, filters.analysis_lo, 0, 0)\n pyr.append((_downsample(hi, filters.analysis_hi, 1, 1), _downsample(lo, filters.analysis_hi, 1, 1), _downsample(hi, filters.analysis_lo, 1, 0)))\n im = _downsample(lo, filters.analysis_lo, 1, 0)\n pyr.append(im)\n pyr = tuple(pyr)\n return pyr","code_tokens":"","url":744669} +{"project_name":"lixingjian\/DELTA","file_name":"test_sigproc.py","full_name":"test_case.test_frame_sig","func_name":"test_frame_sig","docstring":"Test frame signal processing.","docstring_tokens":"","code":"def test_frame_sig(self):\n \"\"\" Test frame signal processing. \"\"\"\n n = 10000124\n frame_len = 37\n frame_step = 13\n x = np.random.rand(n)\n t0 = time.time()\n y_old = sigproc.framesig(x, frame_len=frame_len, frame_step=frame_step, stride_trick=False)\n t1 = time.time()\n y_new = sigproc.framesig(x, frame_len=frame_len, frame_step=frame_step, stride_trick=True)\n t_new = time.time() - t1\n t_old = t1 - t0\n self.assertTupleEqual(y_old.shape, y_new.shape)\n np.testing.assert_array_equal(y_old, y_new)\n self.assertLess(t_new, t_old)\n print('new run time %3.2f < %3.2f sec' % (t_new, t_old))","code_tokens":"","url":537339} +{"project_name":"Cheng-Lin-Li\/AI","file_name":"analysis.py","full_name":"question2d","func_name":"question2d","docstring":"Prefer the distant exit (+10), avoiding the cliff (-10).","docstring_tokens":"","code":"def question2d():\n \"\"\"\n Prefer the distant exit (+10), avoiding the cliff (-10).\n \"\"\"\n answerDiscount = None\n answerNoise = None\n answerLivingReward = None\n return (answerDiscount, answerNoise, answerLivingReward)","code_tokens":"","url":64415} +{"project_name":"Farama-Foundation\/D4RL","file_name":"__init__.py","full_name":"qlearning_dataset","func_name":"qlearning_dataset","docstring":"Returns datasets formatted for use by standard Q-learning algorithms, with observations, actions, next_observations, rewards, and a terminal flag.","docstring_tokens":"","code":"def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs):\n \"\"\"\n Returns datasets formatted for use by standard Q-learning algorithms,\n with observations, actions, next_observations, rewards, and a terminal\n flag.\n\n Args:\n env: An OfflineEnv object.\n dataset: An optional dataset to pass in for processing. If None,\n the dataset will default to env.get_dataset()\n terminate_on_end (bool): Set done=True on the last timestep\n in a trajectory. Default is False, and will discard the\n last timestep in each trajectory.\n **kwargs: Arguments to pass to env.get_dataset().\n\n Returns:\n A dictionary containing keys:\n observations: An N x dim_obs array of observations.\n actions: An N x dim_action array of actions.\n next_observations: An N x dim_obs array of next observations.\n rewards: An N-dim float array of rewards.\n terminals: An N-dim boolean array of \"done\" or episode termination flags.\n \"\"\"\n if dataset is None:\n dataset = env.get_dataset(**kwargs)\n N = dataset['rewards'].shape[0]\n obs_ = []\n next_obs_ = []\n action_ = []\n reward_ = []\n done_ = []\n use_timeouts = False\n if 'timeouts' in dataset:\n use_timeouts = True\n episode_step = 0\n for i in range(N - 1):\n obs = dataset['observations'][i].astype(np.float32)\n new_obs = dataset['observations'][i + 1].astype(np.float32)\n action = dataset['actions'][i].astype(np.float32)\n reward = dataset['rewards'][i].astype(np.float32)\n done_bool = bool(dataset['terminals'][i])\n if use_timeouts:\n final_timestep = dataset['timeouts'][i]\n else:\n final_timestep = episode_step == env._max_episode_steps - 1\n if not terminate_on_end and final_timestep:\n episode_step = 0\n continue\n if done_bool or final_timestep:\n episode_step = 0\n obs_.append(obs)\n next_obs_.append(new_obs)\n action_.append(action)\n reward_.append(reward)\n done_.append(done_bool)\n episode_step += 1\n return {'observations': np.array(obs_), 'actions': np.array(action_), 'next_observations': np.array(next_obs_), 'rewards': np.array(reward_), 'terminals': np.array(done_)}","code_tokens":"","url":126378} +{"project_name":"QY1994-0919\/CFPNet","file_name":"setup_env.py","full_name":"configure_omp","func_name":"configure_omp","docstring":"If OMP_NUM_THREADS is not configured and world_size is greater than 1, Configure OMP_NUM_THREADS environment variables of NCCL to `num_thread`.","docstring_tokens":"","code":"def configure_omp(num_threads=1):\n \"\"\"\n If OMP_NUM_THREADS is not configured and world_size is greater than 1,\n Configure OMP_NUM_THREADS environment variables of NCCL to `num_thread`.\n\n Args:\n num_threads (int): value of `OMP_NUM_THREADS` to set.\n \"\"\"\n if 'OMP_NUM_THREADS' not in os.environ and get_world_size() > 1:\n os.environ['OMP_NUM_THREADS'] = str(num_threads)\n if is_main_process():\n logger.info('\\n***************************************************************\\nWe set `OMP_NUM_THREADS` for each process to {} to speed up.\\nplease further tune the variable for optimal performance.\\n***************************************************************'.format(os.environ['OMP_NUM_THREADS']))","code_tokens":"","url":476750} +{"project_name":"zhoroh\/ObjectDetection","file_name":"functionalCV.py","full_name":"pad","func_name":"pad","docstring":"Pad the given CV2 Image on all sides with speficified padding mode and fill value.","docstring_tokens":"","code":"def pad(img, padding, fill=0, padding_mode='constant'):\n \"\"\"Pad the given CV2 Image on all sides with speficified padding mode and fill value.\n\n Args:\n img (CV2 Image): Image to be padded.\n padding (int or tuple): Padding on each border. If a single int is provided this\n is used to pad all borders. If tuple of length 2 is provided this is the padding\n on left\/right and top\/bottom respectively. If a tuple of length 4 is provided\n this is the padding for the left, top, right and bottom borders\n respectively.\n fill: Pixel fill value for constant fill. Default is 0. If a tuple of\n length 3, it is used to fill R, G, B channels respectively.\n This value is only used when the padding_mode is constant\n padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.\n constant: pads with a constant value, this value is specified with fill\n edge: pads with the last value on the edge of the image\n reflect: pads with reflection of image (without repeating the last value on the edge)\n padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode\n will result in [3, 2, 1, 2, 3, 4, 3, 2]\n symmetric: pads with reflection of image (repeating the last value on the edge)\n padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode\n will result in [2, 1, 1, 2, 3, 4, 4, 3]\n\n Returns:\n CV2 Image: Padded image.\n \"\"\"\n if not _is_numpy_image(img):\n raise TypeError('img should be nparray Image. Got {}'.format(type(img)))\n if not isinstance(padding, (numbers.Number, tuple)):\n raise TypeError('Got inappropriate padding arg')\n if not isinstance(fill, (numbers.Number, str, tuple)):\n raise TypeError('Got inappropriate fill arg')\n if not isinstance(padding_mode, str):\n raise TypeError('Got inappropriate padding_mode arg')\n if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:\n raise ValueError('Padding must be an int or a 2, or 4 element tuple, not a ' + '{} element tuple'.format(len(padding)))\n assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], 'Padding mode should be either constant, edge, reflect or symmetric'\n if isinstance(padding, int):\n pad_left = pad_right = pad_top = pad_bottom = padding\n if isinstance(padding, collections.Sequence) and len(padding) == 2:\n pad_left = pad_right = padding[0]\n pad_top = pad_bottom = padding[1]\n if isinstance(padding, collections.Sequence) and len(padding) == 4:\n pad_left = padding[0]\n pad_top = padding[1]\n pad_right = padding[2]\n pad_bottom = padding[3]\n if padding_mode == 'constant':\n if isinstance(fill, int):\n fill_R = fill_G = fill_B = fill\n else:\n fill_R = fill[0]\n fill_G = fill[1]\n fill_B = fill[2]\n (img_b, img_g, img_r) = cv2.split(img)\n img_b = np.pad(img_b, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode, constant_values=((fill_B, fill_B), (fill_B, fill_B)))\n img_g = np.pad(img_g, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode, constant_values=((fill_G, fill_G), (fill_G, fill_G)))\n img_r = np.pad(img_r, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode, constant_values=((fill_R, fill_R), (fill_R, fill_R)))\n img = cv2.merge([img_b, img_g, img_r])\n elif len(img.shape) == 3:\n img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)\n return img","code_tokens":"","url":743333} +{"project_name":"ashwin-phadke\/cvplayground","file_name":"flask_server.py","full_name":"check_db_exists","func_name":"check_db_exists","docstring":"Checks to see if the dataase file required for the app to function exists in the current directory and if not then creates it with all the required tables.","docstring_tokens":"","code":"def check_db_exists():\n \"\"\"\n Checks to see if the dataase file required for the app to function exists in the current directory and if not then creates it with all the required tables.\n \"\"\"\n if not os.path.isfile('db\/cvplayground.db'):\n logging.info('Creating database, this might take a while')\n db()\n logging.info('Database created. Starting the app now')\n else:\n logging.info('Database already exists. Starting app now...')","code_tokens":"","url":510468} +{"project_name":"RasaHQ\/rasa_core","file_name":"callback.py","full_name":"nlg_request_format_spec","func_name":"nlg_request_format_spec","docstring":"Expected request schema for requests sent to an NLG endpoint.","docstring_tokens":"","code":"def nlg_request_format_spec():\n \"\"\"Expected request schema for requests sent to an NLG endpoint.\"\"\"\n return {'type': 'object', 'properties': {'template': {'type': 'string'}, 'arguments': {'type': 'object'}, 'tracker': {'type': 'object', 'properties': {'sender_id': {'type': 'string'}, 'slots': {'type': 'object'}, 'latest_message': {'type': 'object'}, 'latest_event_time': {'type': 'number'}, 'paused': {'type': 'boolean'}, 'events': {'type': 'array'}}}, 'channel': {'type': 'object', 'properties': {'name': {'type': 'string'}}}}}","code_tokens":"","url":838314} +{"project_name":"Farama-Foundation\/Minari","file_name":"cli.py","full_name":"list_remote","func_name":"list_remote","docstring":"List Minari datasets hosted in the Farama server.","docstring_tokens":"","code":"@list_app.command('remote')\ndef list_remote(all: Annotated[bool, typer.Option('--all', '-a', help='Show all dataset versions.')]=False):\n \"\"\"List Minari datasets hosted in the Farama server.\"\"\"\n if all:\n datasets = hosting.list_remote_datasets()\n else:\n datasets = hosting.list_remote_datasets(latest_version=True, compatible_minari_version=True)\n table_title = 'Minari datasets in Farama server'\n _show_dataset_table(datasets, table_title)","code_tokens":"","url":670481} +{"project_name":"kubeflow\/pipelines","file_name":"_container_op.py","full_name":"Container.set_memory_request","func_name":"set_memory_request","docstring":"Set memory request (minimum) for this operator.","docstring_tokens":"","code":"def set_memory_request(self, memory: Union[str, _pipeline_param.PipelineParam]) -> 'Container':\n \"\"\"Set memory request (minimum) for this operator.\n\n Args:\n memory(Union[str, PipelineParam]): a string which can be a number or a number followed by one of\n \"E\", \"P\", \"T\", \"G\", \"M\", \"K\".\n \"\"\"\n if not isinstance(memory, _pipeline_param.PipelineParam):\n self._validate_size_string(memory)\n return self.add_resource_request('memory', memory)","code_tokens":"","url":780112} +{"project_name":"RoundofThree\/AIMA-notes","file_name":"docs.py","full_name":"build_lang","func_name":"build_lang","docstring":"Build the docs for a language, filling missing pages with translation notifications.","docstring_tokens":"","code":"@app.command()\ndef build_lang(lang: str=typer.Argument(..., callback=lang_callback, autocompletion=complete_existing_lang)):\n \"\"\"\n Build the docs for a language, filling missing pages with translation notifications.\n \"\"\"\n lang_path: Path = docs_root_path \/ lang\n if not lang_path.is_dir():\n typer.echo(f\"The language translation doesn't seem to exist yet: {lang}\")\n raise typer.Abort()\n typer.echo(f'Building docs for: {lang}')\n build_dir_path = Path('docs_build')\n build_dir_path.mkdir(exist_ok=True)\n build_lang_path = build_dir_path \/ lang\n site_path = Path('site').absolute()\n if lang == default_lang:\n dist_path = site_path\n else:\n dist_path: Path = site_path \/ lang\n shutil.rmtree(build_lang_path, ignore_errors=True)\n shutil.copytree(lang_path, build_lang_path)\n overrides_src = default_docs_path \/ 'overrides'\n overrides_dest = build_lang_path \/ 'overrides'\n for path in overrides_src.iterdir():\n dest_path = overrides_dest \/ path.name\n if not dest_path.exists():\n shutil.copy(path, dest_path)\n default_lang_path = Path('docs\/en')\n default_config_path: Path = default_lang_path \/ mkdocs_name\n default_config: dict = mkdocs.utils.yaml_load(default_config_path.read_text(encoding='utf-8'))\n nav = default_config['nav']\n use_nav = nav\n file_to_nav = get_file_to_nav_map(use_nav)\n sections = get_sections(use_nav)\n lang_config_path: Path = lang_path \/ mkdocs_name\n lang_config: dict = mkdocs.utils.yaml_load(lang_config_path.read_text(encoding='utf-8'))\n lang_nav = lang_config['nav']\n lang_use_nav = lang_nav\n lang_file_to_nav = get_file_to_nav_map(lang_use_nav)\n use_lang_file_to_nav = get_file_to_nav_map(lang_use_nav)\n for file in file_to_nav:\n file_path = Path(file)\n build_lang_file_path: Path = build_lang_path \/ 'docs' \/ file_path\n default_lang_file_path: Path = default_lang_path \/ 'docs' \/ file_path\n build_lang_file_path.parent.mkdir(parents=True, exist_ok=True)\n if not build_lang_file_path.is_file():\n default_text = default_lang_file_path.read_text(encoding='utf-8')\n lang_text = get_text_with_translate_missing(default_text)\n build_lang_file_path.write_text(lang_text, encoding='utf-8')\n file_key = file_to_nav[file]\n use_lang_file_to_nav[file] = file_key\n if file_key:\n composite_key = ()\n new_key = ()\n for key_part in file_key:\n composite_key += (key_part,)\n key_first_file = sections[composite_key]\n if type(key_first_file) == dict:\n new_key += (key_part,)\n elif key_first_file in lang_file_to_nav:\n new_key = lang_file_to_nav[key_first_file]\n else:\n new_key += (key_part,)\n use_lang_file_to_nav[file] = new_key\n key_to_section = {(): []}\n for (file, orig_file_key) in file_to_nav.items():\n if file in use_lang_file_to_nav:\n file_key = use_lang_file_to_nav[file]\n else:\n file_key = orig_file_key\n section = get_key_section(key_to_section=key_to_section, key=file_key)\n section.append(file)\n for (path, dirs, files) in os.walk(default_lang_path):\n for dir in dirs:\n tmp_default_dir: Path = Path(path) \/ Path(dir)\n tmp_build_dir: Path = Path(str(tmp_default_dir).replace('docs\/en\/', 'docs_build\/en\/'))\n if str(tmp_build_dir).endswith('\/figure'):\n if not tmp_build_dir.exists():\n shutil.copytree(tmp_default_dir, tmp_build_dir)\n new_nav = key_to_section[()]\n export_lang_nav = new_nav\n lang_config['nav'] = export_lang_nav\n build_lang_config_path: Path = build_lang_path \/ mkdocs_name\n build_lang_config_path.write_text(yaml.dump(lang_config, sort_keys=False, width=200, allow_unicode=True), encoding='utf-8')\n current_dir = os.getcwd()\n os.chdir(build_lang_path)\n mkdocs.commands.build.build(mkdocs.config.load_config(site_dir=str(dist_path)))\n os.chdir(current_dir)\n typer.secho(f'Successfully built docs for: {lang}', color=typer.colors.GREEN)","code_tokens":"","url":86304} +{"project_name":"vturrisi\/solo-learn","file_name":"pretrain_dataloader.py","full_name":"dataset_with_index","func_name":"dataset_with_index","docstring":"Factory for datasets that also returns the data index.","docstring_tokens":"","code":"def dataset_with_index(DatasetClass: Type[Dataset]) -> Type[Dataset]:\n \"\"\"Factory for datasets that also returns the data index.\n\n Args:\n DatasetClass (Type[Dataset]): Dataset class to be wrapped.\n\n Returns:\n Type[Dataset]: dataset with index.\n \"\"\"\n\n class DatasetWithIndex(DatasetClass):\n\n def __getitem__(self, index):\n data = super().__getitem__(index)\n return (index, *data)\n return DatasetWithIndex","code_tokens":"","url":393551} +{"project_name":"JinliangLu96\/CL_UNMT","file_name":"embedder.py","full_name":"SentenceEmbedder.reload","func_name":"reload","docstring":"Create a sentence embedder from a pretrained model.","docstring_tokens":"","code":"@staticmethod\ndef reload(path, params):\n \"\"\"\n Create a sentence embedder from a pretrained model.\n \"\"\"\n reloaded = torch.load(path)\n state_dict = reloaded['model']\n if 'checkpoint' in path:\n state_dict = {k[7:] if k.startswith('module.') else k: v for (k, v) in state_dict.items()}\n dico = Dictionary(reloaded['dico_id2word'], reloaded['dico_word2id'], reloaded['dico_counts'])\n pretrain_params = AttrDict(reloaded['params'])\n pretrain_params.n_words = len(dico)\n pretrain_params.bos_index = dico.index(BOS_WORD)\n pretrain_params.eos_index = dico.index(EOS_WORD)\n pretrain_params.pad_index = dico.index(PAD_WORD)\n pretrain_params.unk_index = dico.index(UNK_WORD)\n pretrain_params.mask_index = dico.index(MASK_WORD)\n model = TransformerModel(pretrain_params, dico, True, True)\n model.load_state_dict(state_dict)\n model.eval()\n params.max_batch_size = 0\n return SentenceEmbedder(model, dico, pretrain_params)","code_tokens":"","url":123284} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"dates.py","full_name":"DateLocator.datalim_to_dt","func_name":"datalim_to_dt","docstring":"Convert axis data interval to datetime objects.","docstring_tokens":"","code":"def datalim_to_dt(self):\n \"\"\"\n Convert axis data interval to datetime objects.\n \"\"\"\n (dmin, dmax) = self.axis.get_data_interval()\n if dmin > dmax:\n (dmin, dmax) = (dmax, dmin)\n if dmin < 1:\n raise ValueError('datalim minimum {} is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units'.format(dmin))\n return (num2date(dmin, self.tz), num2date(dmax, self.tz))","code_tokens":"","url":459} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"install.py","full_name":"WheelFile.install","func_name":"install","docstring":"Install the wheel into site-packages.","docstring_tokens":"","code":"def install(self, force=False, overrides={}):\n \"\"\"\n Install the wheel into site-packages.\n \"\"\"\n\n def get_path(key):\n return overrides.get(key) or self.install_paths[key]\n if self.parsed_wheel_info['Root-Is-Purelib'] == 'true':\n root = get_path('purelib')\n else:\n root = get_path('platlib')\n name_trans = {}\n for info in self.zipfile.infolist():\n name = info.filename\n if name.endswith('\/'):\n continue\n if name.startswith('.\/'):\n name = name[2:]\n (basedir, sep, filename) = name.partition('\/')\n if sep and basedir == self.datadir_name:\n (key, sep, filename) = filename.partition('\/')\n if not sep:\n raise ValueError('Invalid filename in wheel: {0}'.format(name))\n target = get_path(key)\n else:\n key = ''\n target = root\n filename = name\n dest = os.path.normpath(os.path.join(target, filename))\n name_trans[info] = (key, target, filename, dest)\n if not force:\n for (info, v) in name_trans.items():\n k = info.filename\n (key, target, filename, dest) = v\n if os.path.exists(dest):\n raise ValueError('Wheel file {0} would overwrite {1}. Use force if this is intended'.format(k, dest))\n exename = sys.executable.encode(sys.getfilesystemencoding())\n record_data = []\n record_name = self.distinfo_name + '\/RECORD'\n for (info, (key, target, filename, dest)) in name_trans.items():\n name = info.filename\n source = self.zipfile.open(info)\n if name == record_name:\n continue\n ddir = os.path.dirname(dest)\n if not os.path.isdir(ddir):\n os.makedirs(ddir)\n destination = HashingFile(open(dest, 'wb'))\n if key == 'scripts':\n hashbang = source.readline()\n if hashbang.startswith(b'#!python'):\n hashbang = b'#!' + exename + binary(os.linesep)\n destination.write(hashbang)\n shutil.copyfileobj(source, destination)\n reldest = os.path.relpath(dest, root)\n reldest.replace(os.sep, '\/')\n record_data.append((reldest, destination.digest(), destination.length))\n destination.close()\n source.close()\n attrs = info.external_attr >> 16\n if attrs:\n os.chmod(dest, info.external_attr >> 16)\n record_name = os.path.join(root, self.record_name)\n writer = csv.writer(open_for_csv(record_name, 'w+'))\n for (reldest, digest, length) in sorted(record_data):\n writer.writerow((reldest, digest, length))\n writer.writerow((self.record_name, '', ''))","code_tokens":"","url":189381} +{"project_name":"rlgraph\/rlgraph","file_name":"pytorch_util.py","full_name":"pytorch_one_hot","func_name":"pytorch_one_hot","docstring":"One-hot utility function for PyTorch.","docstring_tokens":"","code":"def pytorch_one_hot(index_tensor, depth=0):\n \"\"\"\n One-hot utility function for PyTorch.\n\n Args:\n index_tensor (torch.Tensor): The input to be one-hot.\n depth (int): The max. number to be one-hot encoded (size of last rank).\n\n Returns:\n torch.Tensor: The one-hot encoded equivalent of the input array.\n \"\"\"\n if get_backend() == 'pytorch':\n if isinstance(index_tensor, torch.FloatTensor):\n index_tensor = index_tensor.long()\n if isinstance(index_tensor, torch.IntTensor):\n index_tensor = index_tensor.long()\n out = torch.zeros(index_tensor.size() + torch.Size([depth]))\n dim = len(index_tensor.size())\n index = index_tensor.unsqueeze(-1)\n return out.scatter_(dim, index, 1)","code_tokens":"","url":862859} +{"project_name":"deepmind\/spriteworld","file_name":"environment.py","full_name":"Environment.step","func_name":"step","docstring":"Step the environment with an action.","docstring_tokens":"","code":"def step(self, action):\n \"\"\"Step the environment with an action.\"\"\"\n if self._reset_next_step:\n return self.reset()\n self._step_count += 1\n reward = self._action_space.step(action, self._sprites, keep_in_frame=self._keep_in_frame)\n for sprite in self._sprites:\n sprite.update_position(keep_in_frame=self._keep_in_frame)\n reward += self._task.reward(self._sprites)\n observation = self.observation()\n if self.should_terminate():\n self._reset_next_step = True\n return dm_env.termination(reward=reward, observation=observation)\n else:\n return dm_env.transition(reward=reward, observation=observation)","code_tokens":"","url":897176} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_data.py","full_name":"test_kernelcenterer_non_linear_kernel","func_name":"test_kernelcenterer_non_linear_kernel","docstring":"Check kernel centering for non-linear kernel.","docstring_tokens":"","code":"def test_kernelcenterer_non_linear_kernel():\n \"\"\"Check kernel centering for non-linear kernel.\"\"\"\n rng = np.random.RandomState(0)\n (X, X_test) = (rng.randn(100, 50), rng.randn(20, 50))\n\n def phi(X):\n \"\"\"Our mapping function phi.\"\"\"\n return np.vstack([np.clip(X, a_min=0, a_max=None), -np.clip(X, a_min=None, a_max=0)])\n phi_X = phi(X)\n phi_X_test = phi(X_test)\n scaler = StandardScaler(with_std=False)\n phi_X_center = scaler.fit_transform(phi_X)\n phi_X_test_center = scaler.transform(phi_X_test)\n K = phi_X @ phi_X.T\n K_test = phi_X_test @ phi_X.T\n K_center = phi_X_center @ phi_X_center.T\n K_test_center = phi_X_test_center @ phi_X_center.T\n kernel_centerer = KernelCenterer()\n kernel_centerer.fit(K)\n assert_allclose(kernel_centerer.transform(K), K_center)\n assert_allclose(kernel_centerer.transform(K_test), K_test_center)\n ones_M = np.ones_like(K) \/ K.shape[0]\n K_centered = K - ones_M @ K - K @ ones_M + ones_M @ K @ ones_M\n assert_allclose(kernel_centerer.transform(K), K_centered)\n ones_prime_M = np.ones_like(K_test) \/ K.shape[0]\n K_test_centered = K_test - ones_prime_M @ K - K_test @ ones_M + ones_prime_M @ K @ ones_M\n assert_allclose(kernel_centerer.transform(K_test), K_test_centered)","code_tokens":"","url":364513} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"viewer.py","full_name":"ManipulationController.set_move_horizontal_mode","func_name":"set_move_horizontal_mode","docstring":"Begins\/ends an object translation action along the horizontal plane.","docstring_tokens":"","code":"def set_move_horizontal_mode(self, enable):\n \"\"\"Begins\/ends an object translation action along the horizontal plane.\n\n Args:\n enable: A boolean flag, True begins the action, False ends it.\n \"\"\"\n if enable:\n self._action.begin(enums.mjtMouse.mjMOUSE_MOVE_H)\n else:\n self._action.end(enums.mjtMouse.mjMOUSE_MOVE_H)","code_tokens":"","url":441124} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"misc.py","full_name":"redact_password_from_url","func_name":"redact_password_from_url","docstring":"Replace the password in a given url with ****.","docstring_tokens":"","code":"def redact_password_from_url(url):\n \"\"\"Replace the password in a given url with ****.\"\"\"\n return _transform_url(url, _redact_netloc)[0]","code_tokens":"","url":83835} +{"project_name":"cheind\/gcsl","file_name":"group_config_test.py","full_name":"RobotGroupConfigTest.test_qpos_out_of_range","func_name":"test_qpos_out_of_range","docstring":"Ensures error when qpos indices are out of bounds.","docstring_tokens":"","code":"def test_qpos_out_of_range(self):\n \"\"\"Ensures error when qpos indices are out of bounds.\"\"\"\n sim_scene = MockSimScene(nq=3)\n with self.assertRaises(AssertionError):\n RobotGroupConfig(sim_scene, qpos_indices=[3])\n with self.assertRaises(AssertionError):\n RobotGroupConfig(sim_scene, qpos_indices=[-4])","code_tokens":"","url":201744} +{"project_name":"QData\/deepWordBug","file_name":"containers.py","full_name":"Container.kill","func_name":"kill","docstring":"Kill or send a signal to the container.","docstring_tokens":"","code":"def kill(self, signal=None):\n \"\"\"\n Kill or send a signal to the container.\n\n Args:\n signal (str or int): The signal to send. Defaults to ``SIGKILL``\n\n Raises:\n :py:class:`docker.errors.APIError`\n If the server returns an error.\n \"\"\"\n return self.client.api.kill(self.id, signal=signal)","code_tokens":"","url":541870} +{"project_name":"sktime\/sktime","file_name":"njit.py","full_name":"jit","func_name":"jit","docstring":"Identity decorator for replacing njit by passthrough.","docstring_tokens":"","code":"def jit(*args, **kwargs):\n \"\"\"Identity decorator for replacing njit by passthrough.\"\"\"\n\n def decorator(func):\n return func\n return decorator","code_tokens":"","url":878015} +{"project_name":"RasaHQ\/rasa","file_name":"io.py","full_name":"random_string","func_name":"random_string","docstring":"Returns a random string of given length.","docstring_tokens":"","code":"def random_string(length: int) -> Text:\n \"\"\"Returns a random string of given length.\"\"\"\n return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))","code_tokens":"","url":837817} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_tifffile.py","full_name":"read_nih_image_header","func_name":"read_nih_image_header","docstring":"Read NIH_IMAGE_HEADER tag from file and return as dict.","docstring_tokens":"","code":"def read_nih_image_header(fh, byteorder, dtype, count, offsetsize):\n \"\"\"Read NIH_IMAGE_HEADER tag from file and return as dict.\"\"\"\n a = fh.read_record(TIFF.NIH_IMAGE_HEADER, byteorder=byteorder)\n a = a.newbyteorder(byteorder)\n a = recarray2dict(a)\n a['XUnit'] = a['XUnit'][:a['XUnitSize']]\n a['UM'] = a['UM'][:a['UMsize']]\n return a","code_tokens":"","url":37500} +{"project_name":"AgnostiqHQ\/covalent","file_name":"context_managers.py","full_name":"ActiveLatticeManager.get_active_lattice","func_name":"get_active_lattice","docstring":"Return the active lattice.","docstring_tokens":"","code":"def get_active_lattice(self) -> 'Lattice':\n \"\"\"\n Return the active lattice.\n\n Args:\n None\n\n Returns:\n active_lattice: The active lattice.\n \"\"\"\n return self._active_lattice","code_tokens":"","url":489503} +{"project_name":"RasaHQ\/rasa","file_name":"lm_featurizer.py","full_name":"LanguageModelFeaturizer.process_training_data","func_name":"process_training_data","docstring":"Computes tokens and dense features for each message in training data.","docstring_tokens":"","code":"def process_training_data(self, training_data: TrainingData) -> TrainingData:\n \"\"\"Computes tokens and dense features for each message in training data.\n\n Args:\n training_data: NLU training data to be tokenized and featurized\n config: NLU pipeline config consisting of all components.\n \"\"\"\n batch_size = 64\n for attribute in DENSE_FEATURIZABLE_ATTRIBUTES:\n non_empty_examples = list(filter(lambda x: x.get(attribute), training_data.training_examples))\n batch_start_index = 0\n while batch_start_index < len(non_empty_examples):\n batch_end_index = min(batch_start_index + batch_size, len(non_empty_examples))\n batch_messages = non_empty_examples[batch_start_index:batch_end_index]\n batch_docs = self._get_docs_for_batch(batch_messages, attribute)\n for (index, ex) in enumerate(batch_messages):\n self._set_lm_features(batch_docs[index], ex, attribute)\n batch_start_index += batch_size\n return training_data","code_tokens":"","url":837253} +{"project_name":"ifwe\/digsby","file_name":"imwin_ctrl.py","full_name":"ImWinCtrl.on_send_message_sms","func_name":"on_send_message_sms","docstring":"Invoked when enter is pressed in the message input box during SMS mode.","docstring_tokens":"","code":"def on_send_message_sms(self):\n \"\"\"Invoked when enter is pressed in the message input box during SMS mode.\"\"\"\n if not self.input_area.Value:\n return\n (to, frm) = (self.SMSControl.ToSMS, self.SMSControl.FromAccount)\n if to is None:\n MessageBox(_('Please add an SMS number first.'), _('Send SMS Message'))\n elif frm is None:\n MessageBox(_('You are not signed in to any accounts which can send SMS messages.'), _('Send SMS Message'))\n else:\n message = self.input_area.Value\n\n def on_success():\n self.show_message(Message(buddy=frm.self_buddy, message=message[:SMS_MAX_LENGTH], conversation=self.convo, type='outgoing'))\n self.ClearAndFocus()\n\n def on_error(errstr=None):\n if errstr is not None:\n more = '\\n' + _('The error message received was:') + '\\n\\t%s' % errstr\n else:\n more = ''\n MessageBox(_('There was an error in sending your SMS message.') + more, _('Send SMS Message Error'), style=wx.ICON_ERROR)\n if len(message) > SMS_MAX_LENGTH:\n sms_line1 = _('Only the first {max_length:d} characters of your message can be sent over SMS:').format(max_length=SMS_MAX_LENGTH)\n sms_line2 = _('Do you want to send this message now?')\n if wx.NO == wx.MessageBox(u'%s\\n\\n\"%s\"\\n\\n%s' % (sms_line1, message, sms_line2), _('Send SMS - Character Limit'), style=wx.YES_NO):\n return\n import hooks\n hooks.notify('digsby.statistics.sms.sent')\n frm.send_sms(to, message[:SMS_MAX_LENGTH], success=on_success, error=on_error)","code_tokens":"","url":185384} +{"project_name":"jimtin\/Stock_Comparison","file_name":"test_run.py","full_name":"TestMagicRunSimple.test_unicode","func_name":"test_unicode","docstring":"Check that files in odd encodings are accepted.","docstring_tokens":"","code":"def test_unicode(self):\n \"\"\"Check that files in odd encodings are accepted.\"\"\"\n mydir = os.path.dirname(__file__)\n na = os.path.join(mydir, 'nonascii.py')\n _ip.magic('run \"%s\"' % na)\n nt.assert_equal(_ip.user_ns['u'], u'\u00c3\\x90\u00c2\\x8e\u00c3\\x91\u00c2\\x82\u00c3\u00a2\u00c2\\x84\u00c2\\x96\u00c3\\x90\u00c2\u00a4')","code_tokens":"","url":385155} +{"project_name":"hankcs\/HanLP","file_name":"dictionary.py","full_name":"DictInterface.tokenize","func_name":"tokenize","docstring":"Implement this method to tokenize a piece of text into a list of non-intersect spans, each span is a tuple of ``(begin_offset, end_offset, label)``, where label is some properties related to this span and downstream tasks have the freedom to define what kind of labels they want.","docstring_tokens":"","code":"@abstractmethod\ndef tokenize(self, text: Union[str, Sequence[str]]) -> List[Tuple[int, int, Any]]:\n \"\"\"Implement this method to tokenize a piece of text into a list of non-intersect spans, each span is a tuple\n of ``(begin_offset, end_offset, label)``, where label is some properties related to this span and downstream\n tasks have the freedom to define what kind of labels they want.\n\n Args:\n text: The text to be tokenized.\n\n Returns:\n A list of tokens.\n\n \"\"\"\n pass","code_tokens":"","url":575950} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"option_builder.py","full_name":"ProfileOptionBuilder.with_timeline_output","func_name":"with_timeline_output","docstring":"Generate a timeline json file.","docstring_tokens":"","code":"def with_timeline_output(self, timeline_file):\n \"\"\"Generate a timeline json file.\"\"\"\n self._options['output'] = 'timeline:outfile=%s' % timeline_file\n return self","code_tokens":"","url":339395} +{"project_name":"yixindu1573\/Recursive-Image-Dehazing-via-Perceptually-Optimized---Network-POGAN","file_name":"recurrent.py","full_name":"BasicConvLSTMCell.output_size","func_name":"output_size","docstring":"Number of units in outputs.","docstring_tokens":"","code":"@property\ndef output_size(self):\n \"\"\"Number of units in outputs.\"\"\"\n return self._num_units","code_tokens":"","url":832337} +{"project_name":"matsu0228\/nlp-jp","file_name":"layer2.py","full_name":"TableGenerator.response","func_name":"response","docstring":"The current response to the call from DynamoDB.","docstring_tokens":"","code":"@property\ndef response(self):\n \"\"\"\n The current response to the call from DynamoDB.\n \"\"\"\n return self.next_response() if self._response is None else self._response","code_tokens":"","url":784260} +{"project_name":"RashadGarayev\/FireDetection","file_name":"autoaugment_utils.py","full_name":"solarize_only_bboxes","func_name":"solarize_only_bboxes","docstring":"Apply solarize to each bbox in the image with probability prob.","docstring_tokens":"","code":"def solarize_only_bboxes(image, bboxes, prob, threshold):\n \"\"\"Apply solarize to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, solarize, func_changes_bbox, threshold)","code_tokens":"","url":210724} +{"project_name":"ZhAnGToNG1\/transfer_learning_cspt","file_name":"dataset_wrappers.py","full_name":"ConcatDataset.get_ann_info","func_name":"get_ann_info","docstring":"Get annotation of concatenated dataset by index.","docstring_tokens":"","code":"def get_ann_info(self, idx):\n \"\"\"Get annotation of concatenated dataset by index.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Annotation info of specified index.\n \"\"\"\n if idx < 0:\n if -idx > len(self):\n raise ValueError('absolute value of index should not exceed dataset length')\n idx = len(self) + idx\n dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)\n if dataset_idx == 0:\n sample_idx = idx\n else:\n sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]\n return self.datasets[dataset_idx].get_ann_info(sample_idx)","code_tokens":"","url":963832} +{"project_name":"frgfm\/Holocron","file_name":"utils.py","full_name":"load_pretrained_params","func_name":"load_pretrained_params","docstring":"Loads a checkpoint on a model given its URL.","docstring_tokens":"","code":"def load_pretrained_params(model: nn.Module, url: Optional[str]=None, progress: bool=True, key_replacement: Optional[Tuple[str, str]]=None, key_filter: Optional[str]=None) -> None:\n \"\"\"Loads a checkpoint on a model given its URL.\n\n Args:\n model: PyTorch model\n url: the URL of the checkpoint to download\n progress: whether a progress br should be displayed when downloading the checkpoint\n key_replacement: a mapping to replace keys in the checkpoint before loading them\n key_filter: prefix of the checkpoint keys to be loaded\n \"\"\"\n if url is None:\n logging.warning('Invalid model URL, using default initialization.')\n else:\n state_dict = load_state_dict_from_url(url, progress=progress, map_location='cpu')\n if isinstance(key_filter, str):\n state_dict = {k: v for (k, v) in state_dict.items() if k.startswith(key_filter)}\n if isinstance(key_replacement, tuple):\n state_dict = {k.replace(*key_replacement): v for (k, v) in state_dict.items()}\n model.load_state_dict(state_dict)","code_tokens":"","url":569988} +{"project_name":"PaddlePaddle\/Paddle3D","file_name":"bevdet_reader.py","full_name":"LoadAnnotationsBEVDepth.sample_bda_augmentation","func_name":"sample_bda_augmentation","docstring":"Generate bda augmentation values based on bda_config.","docstring_tokens":"","code":"def sample_bda_augmentation(self):\n \"\"\"Generate bda augmentation values based on bda_config.\"\"\"\n if self.is_train:\n rotate_bda = np.random.uniform(*self.bda_aug_conf['rot_lim'])\n scale_bda = np.random.uniform(*self.bda_aug_conf['scale_lim'])\n flip_dx = np.random.uniform() < self.bda_aug_conf['flip_dx_ratio']\n flip_dy = np.random.uniform() < self.bda_aug_conf['flip_dy_ratio']\n else:\n rotate_bda = 0\n scale_bda = 1.0\n flip_dx = False\n flip_dy = False\n return (rotate_bda, scale_bda, flip_dx, flip_dy)","code_tokens":"","url":777984} +{"project_name":"tensorflow\/data-validation","file_name":"schema_util.py","full_name":"get_categorical_numeric_feature_types","func_name":"get_categorical_numeric_feature_types","docstring":"Get a mapping of numeric categorical features to their schema type.","docstring_tokens":"","code":"def get_categorical_numeric_feature_types(schema: schema_pb2.Schema) -> Mapping[types.FeaturePath, 'schema_pb2.FeatureType']:\n \"\"\"Get a mapping of numeric categorical features to their schema type.\n\n Args:\n schema: The schema for the data.\n\n Returns:\n A map from feature path of numeric features that should be considered\n categorical to their schema type.\n\n Raises:\n ValueError: If a feature path is duplicated within the schema and\n associated with more than one type.\n \"\"\"\n categorical_numeric_types = {}\n for (feature_path, feature) in get_all_leaf_features(schema):\n if feature_path in categorical_numeric_types and categorical_numeric_types[feature_path] != feature.type:\n raise ValueError('Schema contains inconsistently typed duplicates for %s' % feature_path)\n if feature.type in (schema_pb2.INT, schema_pb2.FLOAT) and is_categorical_feature(feature):\n categorical_numeric_types[feature_path] = feature.type\n return categorical_numeric_types","code_tokens":"","url":497633} +{"project_name":"UAVs-at-Berkeley\/flywave","file_name":"vlc.py","full_name":"MediaListPlayer.is_playing","func_name":"is_playing","docstring":"Is media list playing? @return: true for playing and false for not playing \\libvlc_return_bool.","docstring_tokens":"","code":"def is_playing(self):\n \"\"\"Is media list playing?\n @return: true for playing and false for not playing \\\\libvlc_return_bool.\n \"\"\"\n return libvlc_media_list_player_is_playing(self)","code_tokens":"","url":607801} +{"project_name":"jimtin\/Stock_Comparison","file_name":"utils.py","full_name":"PlotlyJSONEncoder.encode_as_datetime","func_name":"encode_as_datetime","docstring":"Attempt to convert to utc-iso time string using datetime methods.","docstring_tokens":"","code":"@staticmethod\ndef encode_as_datetime(obj):\n \"\"\"Attempt to convert to utc-iso time string using datetime methods.\"\"\"\n try:\n obj = obj.astimezone(pytz.utc)\n except ValueError:\n pass\n except TypeError:\n pass\n except AttributeError:\n raise NotEncodable\n try:\n time_string = obj.isoformat()\n except AttributeError:\n raise NotEncodable\n else:\n return iso_to_plotly_time_string(time_string)","code_tokens":"","url":389213} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"__init__.py","full_name":"make_weighted_tree","func_name":"make_weighted_tree","docstring":"Takes a function\/class that takes two positional arguments and a list of (weight, argument) tuples and returns a huffman-like weighted tree of results\/instances.","docstring_tokens":"","code":"def make_weighted_tree(fn, ls, **kwargs):\n \"\"\"Takes a function\/class that takes two positional arguments and a list of\n (weight, argument) tuples and returns a huffman-like weighted tree of\n results\/instances.\n \"\"\"\n if not ls:\n raise ValueError('Called make_weighted_tree with empty list')\n ls.sort()\n while len(ls) > 1:\n a = ls.pop(0)\n b = ls.pop(0)\n insort(ls, (a[0] + b[0], fn(a[1], b[1])))\n return ls[0][1]","code_tokens":"","url":133737} +{"project_name":"autonlab\/weasel","file_name":"LSTM.py","full_name":"LSTM.get_decision_thresh","func_name":"get_decision_thresh","docstring":"Get the model's decision threshold for hard predictions in binary classification.","docstring_tokens":"","code":"def get_decision_thresh(self) -> Optional[float]:\n \"\"\"\n Get the model's decision threshold for hard predictions in binary classification.\n \"\"\"\n return self.readout.get_decision_thresh()","code_tokens":"","url":373371} +{"project_name":"muhanzhang\/D-VAE","file_name":"test_rng_mrg.py","full_name":"test_consistency_cpu_serial","func_name":"test_consistency_cpu_serial","docstring":"Verify that the random numbers generated by mrg_uniform, serially, are the same as the reference (Java) implementation by L'Ecuyer et al.","docstring_tokens":"","code":"def test_consistency_cpu_serial():\n \"\"\"\n Verify that the random numbers generated by mrg_uniform, serially,\n are the same as the reference (Java) implementation by L'Ecuyer et al.\n\n \"\"\"\n seed = 12345\n n_samples = 5\n n_streams = 12\n n_substreams = 7\n samples = []\n curr_rstate = numpy.array([seed] * 6, dtype='int32')\n for i in range(n_streams):\n stream_rstate = curr_rstate.copy()\n for j in range(n_substreams):\n rstate = theano.shared(numpy.array([stream_rstate.copy()], dtype='int32'))\n (new_rstate, sample) = rng_mrg.mrg_uniform.new(rstate, ndim=None, dtype=config.floatX, size=(1,))\n sample.rstate = rstate\n sample.update = (rstate, new_rstate)\n rstate.default_update = new_rstate\n f = theano.function([], sample)\n for k in range(n_samples):\n s = f()\n samples.append(s)\n stream_rstate = rng_mrg.ff_2p72(stream_rstate)\n curr_rstate = rng_mrg.ff_2p134(curr_rstate)\n samples = numpy.array(samples).flatten()\n assert numpy.allclose(samples, java_samples)","code_tokens":"","url":525247} +{"project_name":"rudranil723\/mini-main","file_name":"_base.py","full_name":"_AxesBase.get_navigate_mode","func_name":"get_navigate_mode","docstring":"Get the navigation toolbar button status: 'PAN', 'ZOOM', or None.","docstring_tokens":"","code":"def get_navigate_mode(self):\n \"\"\"\n Get the navigation toolbar button status: 'PAN', 'ZOOM', or None.\n \"\"\"\n return self._navigate_mode","code_tokens":"","url":319996} +{"project_name":"drivendataorg\/concept-to-clinic","file_name":"visualization.py","full_name":"display_training_pair","func_name":"display_training_pair","docstring":"Display both given three-dimensional input images with a slider for the third dimension.","docstring_tokens":"","code":"def display_training_pair(input_cuboid, output_cuboid, axis=2, **kwargs):\n \"\"\"\n Display both given three-dimensional input images with a slider for the\n third dimension.\n\n Args:\n input_cuboid: three-dimensional array that contains the scan\n output_cuboid: three-dimensional array that contains the segmented mask\n axis: index of the axis that should be changeable using the slider\n \"\"\"\n if not input_cuboid.ndim == 3 or not output_cuboid.ndim == 3:\n raise ValueError('cube should be an ndarray with ndim == 3')\n fig = plt.figure()\n subplot_input = fig.add_subplot(221)\n subplot_output = fig.add_subplot(222)\n fig.subplots_adjust(left=0.25, bottom=0.25)\n im1 = subplot_output.imshow(output_cuboid[:, :, 0])\n fig.colorbar(im1)\n s = [slice(0, 1) if i == axis else slice(None) for i in range(3)]\n im = input_cuboid[s].squeeze()\n image_display = subplot_input.imshow(im, **kwargs)\n axcolor = 'lightgoldenrodyellow'\n ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)\n slider = Slider(ax, 'Axis {} index'.format(axis), 0, input_cuboid.shape[axis] - 1, valinit=0, valfmt='%i')\n\n def update(val):\n subplot_output.imshow(output_cuboid[:, :, int(val)])\n ind = int(slider.val)\n s = [slice(ind, ind + 1) if i == axis else slice(None) for i in range(3)]\n im = input_cuboid[s].squeeze()\n image_display.set_data(im, **kwargs)\n fig.canvas.draw()\n slider.on_changed(update)\n plt.show()","code_tokens":"","url":136203} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"stat.py","full_name":"S_IFMT","func_name":"S_IFMT","docstring":"Return the portion of the file's mode that describes the file type.","docstring_tokens":"","code":"def S_IFMT(mode):\n \"\"\"Return the portion of the file's mode that describes the\n file type.\n \"\"\"\n return mode & 61440","code_tokens":"","url":188039} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"factorization_ops.py","full_name":"WALSModel.initialize_col_update_op","func_name":"initialize_col_update_op","docstring":"Op to initialize worker state before starting column updates.","docstring_tokens":"","code":"@property\ndef initialize_col_update_op(self):\n \"\"\"Op to initialize worker state before starting column updates.\"\"\"\n return self._col_updates_init","code_tokens":"","url":313050} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"_helpers.py","full_name":"_LocalStack.top","func_name":"top","docstring":"Get the top-most resource :rtype: object :returns: the top-most item, or None if the stack is empty.","docstring_tokens":"","code":"@property\ndef top(self):\n \"\"\"Get the top-most resource\n\n :rtype: object\n :returns: the top-most item, or None if the stack is empty.\n \"\"\"\n if self._stack:\n return self._stack[-1]","code_tokens":"","url":214619} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"topn.py","full_name":"TopN.insert","func_name":"insert","docstring":"Insert the ids and scores into the TopN.","docstring_tokens":"","code":"def insert(self, ids, scores):\n \"\"\"Insert the ids and scores into the TopN.\"\"\"\n with tf.control_dependencies(self.last_ops):\n scatter_op = tf.scatter_update(self.id_to_score, ids, scores)\n larger_scores = tf.greater(scores, self.sl_scores[0])\n\n def shortlist_insert():\n larger_ids = tf.boolean_mask(tf.to_int64(ids), larger_scores)\n larger_score_values = tf.boolean_mask(scores, larger_scores)\n (shortlist_ids, new_ids, new_scores) = self.ops.top_n_insert(self.sl_ids, self.sl_scores, larger_ids, larger_score_values)\n u1 = tf.scatter_update(self.sl_ids, shortlist_ids, new_ids)\n u2 = tf.scatter_update(self.sl_scores, shortlist_ids, new_scores)\n return tf.group(u1, u2)\n cond_op = tf.cond(tf.reduce_any(larger_scores), shortlist_insert, tf.no_op)\n with tf.control_dependencies([cond_op]):\n self.last_ops = [scatter_op, cond_op]","code_tokens":"","url":182118} +{"project_name":"ShuvenduRoy\/Generative_adversarial_networks","file_name":"solver.py","full_name":"Solver.label2onehot","func_name":"label2onehot","docstring":"Convert label indices to one-hot vectors.","docstring_tokens":"","code":"def label2onehot(self, labels, dim):\n \"\"\"Convert label indices to one-hot vectors.\"\"\"\n batch_size = labels.size(0)\n out = torch.zeros(batch_size, dim)\n out[np.arange(batch_size), labels.long()] = 1\n return out","code_tokens":"","url":556667} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"rnn_cell.py","full_name":"NASCell.call","func_name":"call","docstring":"Run one step of NAS Cell.","docstring_tokens":"","code":"def call(self, inputs, state):\n \"\"\"Run one step of NAS Cell.\n\n Args:\n inputs: input Tensor, 2D, batch x num_units.\n state: This must be a tuple of state Tensors, both `2-D`, with column\n sizes `c_state` and `m_state`.\n\n Returns:\n A tuple containing:\n - A `2-D, [batch x output_dim]`, Tensor representing the output of the\n NAS Cell after reading `inputs` when previous state was `state`.\n Here output_dim is:\n num_proj if num_proj was set,\n num_units otherwise.\n - Tensor(s) representing the new state of NAS Cell after reading `inputs`\n when the previous state was `state`. Same type and shape(s) as `state`.\n\n Raises:\n ValueError: If input size cannot be inferred from inputs via\n static shape inference.\n \"\"\"\n sigmoid = math_ops.sigmoid\n tanh = math_ops.tanh\n relu = nn_ops.relu\n num_proj = self._num_units if self._num_proj is None else self._num_proj\n (c_prev, m_prev) = state\n dtype = inputs.dtype\n input_size = inputs.get_shape().with_rank(2)[1]\n if input_size.value is None:\n raise ValueError('Could not infer input size from inputs.get_shape()[-1]')\n concat_w_m = vs.get_variable('recurrent_kernel', [num_proj, 8 * self._num_units], dtype)\n concat_w_inputs = vs.get_variable('kernel', [input_size.value, 8 * self._num_units], dtype)\n m_matrix = math_ops.matmul(m_prev, concat_w_m)\n inputs_matrix = math_ops.matmul(inputs, concat_w_inputs)\n if self._use_biases:\n b = vs.get_variable('bias', shape=[8 * self._num_units], initializer=init_ops.zeros_initializer(), dtype=dtype)\n m_matrix = nn_ops.bias_add(m_matrix, b)\n m_matrix_splits = array_ops.split(axis=1, num_or_size_splits=8, value=m_matrix)\n inputs_matrix_splits = array_ops.split(axis=1, num_or_size_splits=8, value=inputs_matrix)\n layer1_0 = sigmoid(inputs_matrix_splits[0] + m_matrix_splits[0])\n layer1_1 = relu(inputs_matrix_splits[1] + m_matrix_splits[1])\n layer1_2 = sigmoid(inputs_matrix_splits[2] + m_matrix_splits[2])\n layer1_3 = relu(inputs_matrix_splits[3] * m_matrix_splits[3])\n layer1_4 = tanh(inputs_matrix_splits[4] + m_matrix_splits[4])\n layer1_5 = sigmoid(inputs_matrix_splits[5] + m_matrix_splits[5])\n layer1_6 = tanh(inputs_matrix_splits[6] + m_matrix_splits[6])\n layer1_7 = sigmoid(inputs_matrix_splits[7] + m_matrix_splits[7])\n l2_0 = tanh(layer1_0 * layer1_1)\n l2_1 = tanh(layer1_2 + layer1_3)\n l2_2 = tanh(layer1_4 * layer1_5)\n l2_3 = sigmoid(layer1_6 + layer1_7)\n l2_0 = tanh(l2_0 + c_prev)\n l3_0_pre = l2_0 * l2_1\n new_c = l3_0_pre\n l3_0 = l3_0_pre\n l3_1 = tanh(l2_2 + l2_3)\n new_m = tanh(l3_0 * l3_1)\n if self._num_proj is not None:\n concat_w_proj = vs.get_variable('projection_weights', [self._num_units, self._num_proj], dtype)\n new_m = math_ops.matmul(new_m, concat_w_proj)\n new_state = rnn_cell_impl.LSTMStateTuple(new_c, new_m)\n return (new_m, new_state)","code_tokens":"","url":335115} +{"project_name":"rootskar\/EEGMotorImagery","file_name":"split.py","full_name":"time_series_split","func_name":"time_series_split","docstring":"Split a dataset into n splits.","docstring_tokens":"","code":"def time_series_split(features, labels, n_splits):\n \"\"\"Split a dataset into n splits.\n\n \"\"\"\n xx = sklearn.model_selection.TimeSeriesSplit(n_splits)\n for (train_index, test_index) in xx.split(features):\n (X_train, X_test) = (features[train_index], features[test_index])\n (y_train, y_test) = (labels[train_index], labels[test_index])\n return (X_train, X_test, y_train, y_test)","code_tokens":"","url":175364} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"test_parallel.py","full_name":"test_dispatch_multiprocessing","func_name":"test_dispatch_multiprocessing","docstring":"Check that using pre_dispatch Parallel does indeed dispatch items lazily.","docstring_tokens":"","code":"@with_multiprocessing\n@parametrize('backend', PARALLEL_BACKENDS)\ndef test_dispatch_multiprocessing(backend):\n \"\"\" Check that using pre_dispatch Parallel does indeed dispatch items\n lazily.\n \"\"\"\n manager = mp.Manager()\n queue = manager.list()\n\n def producer():\n for i in range(6):\n queue.append('Produced %i' % i)\n yield i\n Parallel(n_jobs=2, batch_size=1, pre_dispatch=3, backend=backend)((delayed(consumer)(queue, 'any') for _ in producer()))\n queue_contents = list(queue)\n assert queue_contents[0] == 'Produced 0'\n first_consumption_index = queue_contents[:4].index('Consumed any')\n assert first_consumption_index > -1\n produced_3_index = queue_contents.index('Produced 3')\n assert produced_3_index > first_consumption_index\n assert len(queue) == 12","code_tokens":"","url":449708} +{"project_name":"mrubash1\/RNN-Tutorial","file_name":"char_rnn.py","full_name":"initialize_session","func_name":"initialize_session","docstring":"Create a session and saver initialized from a checkpoint if found.","docstring_tokens":"","code":"@contextlib.contextmanager\ndef initialize_session(logdir):\n \"\"\"Create a session and saver initialized from a checkpoint if found.\"\"\"\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n logdir = os.path.expanduser(logdir)\n checkpoint = tf.train.latest_checkpoint(logdir)\n saver = tf.train.Saver()\n with tf.Session(config=config) as sess:\n if checkpoint:\n print('Load checkpoint {}.'.format(checkpoint))\n saver.restore(sess, checkpoint)\n else:\n print('Initialize new model.')\n os.makedirs(logdir, exist_ok=True)\n sess.run(tf.global_variables_initializer())\n yield (sess, saver)","code_tokens":"","url":325389} +{"project_name":"s3prl\/s3prl","file_name":"model.py","full_name":"TransformerModel.get_multihead_outputs","func_name":"get_multihead_outputs","docstring":"Gather all multi-head outputs.","docstring_tokens":"","code":"def get_multihead_outputs(self):\n \"\"\"Gather all multi-head outputs.\n Return: list (layers) of multihead module outputs with gradients\n \"\"\"\n return [layer.attention.self.multihead_output for layer in self.encoder.layer]","code_tokens":"","url":327777} +{"project_name":"RyanWangZf\/PyTrial","file_name":"copula_gan.py","full_name":"CTGANSynthesizer.fit","func_name":"fit","docstring":"Fit the CTGAN Synthesizer models to the training data.","docstring_tokens":"","code":"def fit(self, train_data, discrete_columns=(), epochs=None):\n \"\"\"Fit the CTGAN Synthesizer models to the training data.\n\n Args:\n train_data (numpy.ndarray or pandas.DataFrame):\n Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.\n discrete_columns (list-like):\n List of discrete columns to be used to generate the Conditional\n Vector. If ``train_data`` is a Numpy array, this list should\n contain the integer indices of the columns. Otherwise, if it is\n a ``pandas.DataFrame``, this list should contain the column names.\n \"\"\"\n self._validate_discrete_columns(train_data, discrete_columns)\n if epochs is None:\n epochs = self._epochs\n else:\n warnings.warn('`epochs` argument in `fit` method has been deprecated and will be removed in a future version. Please pass `epochs` to the constructor instead', DeprecationWarning)\n self._transformer = DataTransformer()\n self._transformer.fit(train_data, discrete_columns)\n train_data = self._transformer.transform(train_data)\n self._data_sampler = DataSampler(train_data, self._transformer.output_info_list, self._log_frequency)\n data_dim = self._transformer.output_dimensions\n self._generator = Generator(self._embedding_dim + self._data_sampler.dim_cond_vec(), self._generator_dim, data_dim).to(self._device)\n discriminator = Discriminator(data_dim + self._data_sampler.dim_cond_vec(), self._discriminator_dim, pac=self.pac).to(self._device)\n optimizerG = optim.Adam(self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9), weight_decay=self._generator_decay)\n optimizerD = optim.Adam(discriminator.parameters(), lr=self._discriminator_lr, betas=(0.5, 0.9), weight_decay=self._discriminator_decay)\n mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device)\n std = mean + 1\n steps_per_epoch = max(len(train_data) \/\/ self._batch_size, 1)\n for i in range(epochs):\n for id_ in range(steps_per_epoch):\n for n in range(self._discriminator_steps):\n fakez = torch.normal(mean=mean, std=std)\n condvec = self._data_sampler.sample_condvec(self._batch_size)\n if condvec is None:\n (c1, m1, col, opt) = (None, None, None, None)\n real = self._data_sampler.sample_data(self._batch_size, col, opt)\n else:\n (c1, m1, col, opt) = condvec\n c1 = torch.from_numpy(c1).to(self._device)\n m1 = torch.from_numpy(m1).to(self._device)\n fakez = torch.cat([fakez, c1], dim=1)\n perm = np.arange(self._batch_size)\n np.random.shuffle(perm)\n real = self._data_sampler.sample_data(self._batch_size, col[perm], opt[perm])\n c2 = c1[perm]\n fake = self._generator(fakez)\n fakeact = self._apply_activate(fake)\n real = torch.from_numpy(real.astype('float32')).to(self._device)\n if c1 is not None:\n fake_cat = torch.cat([fakeact, c1], dim=1)\n real_cat = torch.cat([real, c2], dim=1)\n else:\n real_cat = real\n fake_cat = fakeact\n y_fake = discriminator(fake_cat)\n y_real = discriminator(real_cat)\n pen = discriminator.calc_gradient_penalty(real_cat, fake_cat, self._device, self.pac)\n loss_d = -(torch.mean(y_real) - torch.mean(y_fake))\n optimizerD.zero_grad()\n pen.backward(retain_graph=True)\n loss_d.backward()\n optimizerD.step()\n fakez = torch.normal(mean=mean, std=std)\n condvec = self._data_sampler.sample_condvec(self._batch_size)\n if condvec is None:\n (c1, m1, col, opt) = (None, None, None, None)\n else:\n (c1, m1, col, opt) = condvec\n c1 = torch.from_numpy(c1).to(self._device)\n m1 = torch.from_numpy(m1).to(self._device)\n fakez = torch.cat([fakez, c1], dim=1)\n fake = self._generator(fakez)\n fakeact = self._apply_activate(fake)\n if c1 is not None:\n y_fake = discriminator(torch.cat([fakeact, c1], dim=1))\n else:\n y_fake = discriminator(fakeact)\n if condvec is None:\n cross_entropy = 0\n else:\n cross_entropy = self._cond_loss(fake, c1, m1)\n loss_g = -torch.mean(y_fake) + cross_entropy\n optimizerG.zero_grad()\n loss_g.backward()\n optimizerG.step()\n if self._verbose:\n print(f'Epoch {i + 1}, Loss G: {loss_g.detach().cpu(): .4f},Loss D: {loss_d.detach().cpu(): .4f}', flush=True)","code_tokens":"","url":302539} +{"project_name":"wangck20\/OPERA","file_name":"resnet.py","full_name":"resnet26t","func_name":"resnet26t","docstring":"Constructs a ResNet-26-T model.","docstring_tokens":"","code":"@register_model\ndef resnet26t(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-26-T model.\n \"\"\"\n model_args = dict(block=Bottleneck, layers=[2, 2, 2, 2], stem_width=32, stem_type='deep_tiered', avg_down=True, **kwargs)\n return _create_resnet('resnet26t', pretrained, **model_args)","code_tokens":"","url":253036} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"config_util_test.py","full_name":"ConfigUtilTest.testMomentumOptimizerWithNewLearningRate","func_name":"testMomentumOptimizerWithNewLearningRate","docstring":"Tests new learning rates for Momentum Optimizer.","docstring_tokens":"","code":"def testMomentumOptimizerWithNewLearningRate(self):\n \"\"\"Tests new learning rates for Momentum Optimizer.\"\"\"\n self._assertOptimizerWithNewLearningRate('momentum_optimizer')","code_tokens":"","url":752142} +{"project_name":"gunthercox\/ChatterBot","file_name":"ma.py","full_name":"reshape","func_name":"reshape","docstring":"Copy of a with a new shape.","docstring_tokens":"","code":"def reshape(a, *newshape):\n \"\"\"Copy of a with a new shape.\"\"\"\n m = getmask(a)\n d = filled(a).reshape(*newshape)\n if m is nomask:\n return masked_array(d)\n else:\n return masked_array(d, mask=numeric.reshape(m, *newshape))","code_tokens":"","url":532413} +{"project_name":"ludwig-ai\/ludwig","file_name":"utils.py","full_name":"extract_generated_tokens","func_name":"extract_generated_tokens","docstring":"Extracts the generated tokens from the raw output sequences of the language model.","docstring_tokens":"","code":"def extract_generated_tokens(raw_generated_output_sequences: List[Tensor], input_lengths: List[int], max_new_tokens: int, pad_sequence: bool) -> List[Tensor]:\n \"\"\"Extracts the generated tokens from the raw output sequences of the language model.\n\n Args:\n raw_generated_output_sequences: The raw output sequences of the language model.\n Represented as a list to handle variable length sequences.\n input_lengths: The length of the inputs to the language model.\n max_new_tokens: The maximum number of new tokens that were generated. Used to\n pad the generated sequences to the max_new_tokens.\n pad_sequence: Whether to pad the generated sequences to the max_new_tokens.\n\n Returns:\n The generated tokens.\n \"\"\"\n if len(raw_generated_output_sequences) != len(input_lengths):\n raise ValueError(f'The number of raw_generated_output_sequences ({len(raw_generated_output_sequences)}) must be the same as the number of input_lengths ({len(input_lengths)}).')\n generated_outputs = []\n for (idx, input_length) in enumerate(input_lengths):\n generated_sequence = raw_generated_output_sequences[idx][input_length:]\n if pad_sequence and generated_sequence.size()[0] < max_new_tokens:\n generated_sequence = torch.nn.functional.pad(generated_sequence, (0, max_new_tokens - generated_sequence.size()[0]), 'constant', 0)\n generated_outputs.append(generated_sequence)\n return generated_outputs","code_tokens":"","url":616725} +{"project_name":"google-research\/bleurt","file_name":"score_files.py","full_name":"check_flags_and_score","func_name":"check_flags_and_score","docstring":"Creates a file reader and runs model.","docstring_tokens":"","code":"def check_flags_and_score():\n \"\"\"Creates a file reader and runs model.\"\"\"\n assert FLAGS.sentence_pairs_file or (FLAGS.reference_file and FLAGS.candidate_file), 'Reference and candidate files not found, please specify a JSONL file or two text files.'\n if FLAGS.sentence_pairs_file:\n sentence_pairs_generator = _json_generator(FLAGS.sentence_pairs_file)\n else:\n sentence_pairs_generator = _text_generator(FLAGS.reference_file, FLAGS.candidate_file)\n score_files(sentence_pairs_generator, FLAGS.bleurt_checkpoint)","code_tokens":"","url":461704} +{"project_name":"voxel51\/fiftyone","file_name":"stages.py","full_name":"SelectLabels.tags","func_name":"tags","docstring":"A list of tags of labels to select.","docstring_tokens":"","code":"@property\ndef tags(self):\n \"\"\"A list of tags of labels to select.\"\"\"\n return self._tags","code_tokens":"","url":583353} +{"project_name":"hamza-murad\/AALU","file_name":"assistant_v1.py","full_name":"EntityMention.from_dict","func_name":"from_dict","docstring":"Initialize a EntityMention object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'EntityMention':\n \"\"\"Initialize a EntityMention object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['text', 'intent', 'location']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class EntityMention: ' + ', '.join(bad_keys))\n if 'text' in _dict:\n args['text'] = _dict.get('text')\n else:\n raise ValueError(\"Required property 'text' not present in EntityMention JSON\")\n if 'intent' in _dict:\n args['intent'] = _dict.get('intent')\n else:\n raise ValueError(\"Required property 'intent' not present in EntityMention JSON\")\n if 'location' in _dict:\n args['location'] = _dict.get('location')\n else:\n raise ValueError(\"Required property 'location' not present in EntityMention JSON\")\n return cls(**args)","code_tokens":"","url":5220} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"compressor.py","full_name":"BinaryZlibFile.closed","func_name":"closed","docstring":"True if this file is closed.","docstring_tokens":"","code":"@property\ndef closed(self):\n \"\"\"True if this file is closed.\"\"\"\n return self._mode == _MODE_CLOSED","code_tokens":"","url":95827} +{"project_name":"rudranil723\/mini-main","file_name":"visitor.py","full_name":"Visitor.visitDict","func_name":"visitDict","docstring":"Called to visit any value that is a dictionary.","docstring_tokens":"","code":"def visitDict(self, obj, *args, **kwargs):\n \"\"\"Called to visit any value that is a dictionary.\"\"\"\n for value in obj.values():\n self.visit(value, *args, **kwargs)","code_tokens":"","url":317259} +{"project_name":"yaoyao-liu\/meta-transfer-learning","file_name":"misc.py","full_name":"mse","func_name":"mse","docstring":"The MSE loss function.","docstring_tokens":"","code":"def mse(pred, label):\n \"\"\"The MSE loss function.\n Args:\n pred: the predictions.\n label: the ground truth labels.\n Return:\n The Loss.\n \"\"\"\n pred = tf.reshape(pred, [-1])\n label = tf.reshape(label, [-1])\n return tf.reduce_mean(tf.square(pred - label))","code_tokens":"","url":633229} +{"project_name":"sondremb\/TDT4265-StarterCode","file_name":"task2.py","full_name":"Trainer.should_early_stop","func_name":"should_early_stop","docstring":"Checks if validation loss doesn't improve over early_stop_count epochs.","docstring_tokens":"","code":"def should_early_stop(self):\n \"\"\"\n Checks if validation loss doesn't improve over early_stop_count epochs.\n \"\"\"\n if len(self.VALIDATION_LOSS) < self.early_stop_count:\n return False\n relevant_loss = list(self.VALIDATION_LOSS.values())[-self.early_stop_count:]\n first_loss = relevant_loss[0]\n if first_loss == min(relevant_loss):\n print('Early stop criteria met')\n return True\n return False","code_tokens":"","url":908039} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"dnn_linear_combined_test.py","full_name":"DNNLinearCombinedRegressorTest.testRegression_MatrixData","func_name":"testRegression_MatrixData","docstring":"Tests regression using matrix data as input.","docstring_tokens":"","code":"def testRegression_MatrixData(self):\n \"\"\"Tests regression using matrix data as input.\"\"\"\n cont_features = [tf.contrib.layers.real_valued_column('feature', dimension=4)]\n regressor = tf.contrib.learn.DNNLinearCombinedRegressor(linear_feature_columns=cont_features, dnn_feature_columns=cont_features, dnn_hidden_units=[3, 3], config=tf.contrib.learn.RunConfig(tf_random_seed=1))\n regressor.fit(input_fn=_iris_input_logistic_fn, steps=10)\n scores = regressor.evaluate(input_fn=_iris_input_logistic_fn, steps=1)\n self.assertIn('loss', scores.keys())","code_tokens":"","url":181679} +{"project_name":"MycroftAI\/mycroft-core","file_name":"utterance_responses.py","full_name":"then_messagebus_message","func_name":"then_messagebus_message","docstring":"Verify a specific message is sent.","docstring_tokens":"","code":"@then('mycroft should send the message \"{message_type}\"')\ndef then_messagebus_message(context, message_type):\n \"\"\"Verify a specific message is sent.\"\"\"\n\n def check_dummy(message):\n \"\"\"We are just interested in the message data, just the type.\"\"\"\n return (True, '')\n (message_found, _) = then_wait(message_type, check_dummy, context)\n assert message_found, 'No matching message received.'","code_tokens":"","url":290859} +{"project_name":"google-research\/batch_rl","file_name":"atari_helpers.py","full_name":"QuantileNetwork.call","func_name":"call","docstring":"Calculates the distribution of Q-values using the input state tensor.","docstring_tokens":"","code":"def call(self, state):\n \"\"\"Calculates the distribution of Q-values using the input state tensor.\"\"\"\n net = tf.cast(state, tf.float32)\n net = tf.div(net, 255.0)\n net = self.conv1(net)\n net = self.conv2(net)\n net = self.conv3(net)\n net = self.flatten(net)\n net = self.dense1(net)\n net = self.dense2(net)\n logits = tf.reshape(net, [-1, self.num_actions, self.num_atoms])\n probabilities = tf.keras.activations.softmax(tf.zeros_like(logits))\n q_values = tf.reduce_mean(logits, axis=2)\n return QuantileNetworkType(q_values, logits, probabilities)","code_tokens":"","url":105915} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_text.py","full_name":"test_vectorizers_do_not_have_set_output","func_name":"test_vectorizers_do_not_have_set_output","docstring":"Check that vectorizers do not define set_output.","docstring_tokens":"","code":"@pytest.mark.parametrize('Estimator', [CountVectorizer, TfidfVectorizer, TfidfTransformer, HashingVectorizer])\ndef test_vectorizers_do_not_have_set_output(Estimator):\n \"\"\"Check that vectorizers do not define set_output.\"\"\"\n est = Estimator()\n assert not hasattr(est, 'set_output')","code_tokens":"","url":853304} +{"project_name":"proxypoke\/quickswitch-for-i3","file_name":"quickswitch.py","full_name":"find_window_by_regex","func_name":"find_window_by_regex","docstring":"Find the first window whose title matches regex and focus or move it.","docstring_tokens":"","code":"def find_window_by_regex(regex, move=False):\n \"\"\"Find the first window whose title matches regex and focus or move it.\"\"\"\n action = move_window_here if move else focus\n cr = re.compile(regex)\n for (title, id) in get_windows().items():\n if cr.match(title):\n action(id)\n return True\n return False","code_tokens":"","url":304086} +{"project_name":"google\/deepvariant","file_name":"test_utils.py","full_name":"iterable_len","func_name":"iterable_len","docstring":"Returns the length of a Python iterable, by advancing it.","docstring_tokens":"","code":"def iterable_len(iterable):\n \"\"\"Returns the length of a Python iterable, by advancing it.\"\"\"\n return sum((1 for _ in iterable))","code_tokens":"","url":540629} +{"project_name":"google-research\/bleurt","file_name":"downloaders.py","full_name":"WMTImporter.cleanup","func_name":"cleanup","docstring":"Housekeeping--we want to erase all the temp files created.","docstring_tokens":"","code":"def cleanup(self):\n \"\"\"Housekeeping--we want to erase all the temp files created.\"\"\"\n for file_type in self.location_info:\n (folder_name, archive_name, _) = self.location_info[file_type]\n folder_path = os.path.join(self.temp_directory, folder_name)\n logging.info('Removing', folder_path)\n try:\n shutil.rmtree(folder_path)\n except OSError:\n logging.info('OS Error--skipping')\n archive_path = os.path.join(self.temp_directory, archive_name)\n logging.info('Removing', archive_path)\n try:\n os.remove(archive_path)\n except OSError:\n logging.info('OS Error--skipping')","code_tokens":"","url":461747} +{"project_name":"mme\/vergeml","file_name":"cache.py","full_name":"Cache.read","func_name":"read","docstring":"Read n_samples at index from the cache.","docstring_tokens":"","code":"def read(self, index, n_samples):\n \"\"\"Read n_samples at index from the cache.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":931488} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"hparam.py","full_name":"HParams.get","func_name":"get","docstring":"Returns the value of `key` if it exists, else `default`.","docstring_tokens":"","code":"def get(self, key, default=None):\n \"\"\"Returns the value of `key` if it exists, else `default`.\"\"\"\n if key in self._hparam_types:\n if default is not None:\n (param_type, is_param_list) = self._hparam_types[key]\n type_str = 'list<%s>' % param_type if is_param_list else str(param_type)\n fail_msg = \"Hparam '%s' of type '%s' is incompatible with default=%s\" % (key, type_str, default)\n is_default_list = isinstance(default, list)\n if is_param_list != is_default_list:\n raise ValueError(fail_msg)\n try:\n if is_default_list:\n for value in default:\n _cast_to_type_if_compatible(key, param_type, value)\n else:\n _cast_to_type_if_compatible(key, param_type, default)\n except ValueError as e:\n raise ValueError('%s. %s' % (fail_msg, e))\n return getattr(self, key)\n return default","code_tokens":"","url":335684} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"image_classification.py","full_name":"image_classification_imagenet_mobilenet","func_name":"image_classification_imagenet_mobilenet","docstring":"Image classification on imagenet with mobilenet.","docstring_tokens":"","code":"@exp_factory.register_config_factory('mobilenet_imagenet')\ndef image_classification_imagenet_mobilenet() -> cfg.ExperimentConfig:\n \"\"\"Image classification on imagenet with mobilenet.\"\"\"\n train_batch_size = 4096\n eval_batch_size = 4096\n steps_per_epoch = IMAGENET_TRAIN_EXAMPLES \/\/ train_batch_size\n config = cfg.ExperimentConfig(task=ImageClassificationTask(model=ImageClassificationModel(num_classes=1001, dropout_rate=0.2, input_size=[224, 224, 3], backbone=backbones.Backbone(type='mobilenet', mobilenet=backbones.MobileNet(model_id='MobileNetV2', filter_size_scale=1.0)), norm_activation=common.NormActivation(norm_momentum=0.997, norm_epsilon=0.001)), losses=Losses(l2_weight_decay=1e-05, label_smoothing=0.1), train_data=DataConfig(input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'train*'), is_training=True, global_batch_size=train_batch_size), validation_data=DataConfig(input_path=os.path.join(IMAGENET_INPUT_PATH_BASE, 'valid*'), is_training=False, global_batch_size=eval_batch_size)), trainer=cfg.TrainerConfig(steps_per_loop=steps_per_epoch, summary_interval=steps_per_epoch, checkpoint_interval=steps_per_epoch, train_steps=500 * steps_per_epoch, validation_steps=IMAGENET_VAL_EXAMPLES \/\/ eval_batch_size, validation_interval=steps_per_epoch, optimizer_config=optimization.OptimizationConfig({'optimizer': {'type': 'rmsprop', 'rmsprop': {'rho': 0.9, 'momentum': 0.9, 'epsilon': 0.002}}, 'learning_rate': {'type': 'exponential', 'exponential': {'initial_learning_rate': 0.008 * (train_batch_size \/\/ 128), 'decay_steps': int(2.5 * steps_per_epoch), 'decay_rate': 0.98, 'staircase': True}}, 'warmup': {'type': 'linear', 'linear': {'warmup_steps': 5 * steps_per_epoch, 'warmup_learning_rate': 0}}})), restrictions=['task.train_data.is_training != None', 'task.validation_data.is_training != None'])\n return config","code_tokens":"","url":850739} +{"project_name":"pandeyankit83\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"streams.py","full_name":"CommonTokenStream.setTokenSource","func_name":"setTokenSource","docstring":"Reset this token stream by setting its token source.","docstring_tokens":"","code":"def setTokenSource(self, tokenSource):\n \"\"\"Reset this token stream by setting its token source.\"\"\"\n self.tokenSource = tokenSource\n self.tokens = []\n self.p = -1\n self.channel = DEFAULT_CHANNEL","code_tokens":"","url":9937} +{"project_name":"voxel51\/fiftyone","file_name":"runs.py","full_name":"RunResults.cls","func_name":"cls","docstring":"The fully-qualified name of this :class:`RunResults` class.","docstring_tokens":"","code":"@property\ndef cls(self):\n \"\"\"The fully-qualified name of this :class:`RunResults` class.\"\"\"\n return etau.get_class_name(self)","code_tokens":"","url":583247} +{"project_name":"aimclub\/FEDOT","file_name":"test_multimodal_data.py","full_name":"test_multimodal_data_from_csv","func_name":"test_multimodal_data_from_csv","docstring":"Checking correctness of MultiModalData import from csv file.","docstring_tokens":"","code":"def test_multimodal_data_from_csv():\n \"\"\"\n Checking correctness of MultiModalData import from csv file.\n \"\"\"\n file_path = 'test\/data\/simple_multimodal_classification.csv'\n path = Path(fedot_project_root(), file_path)\n df = pd.read_csv(path)\n text_data = np.array(df['description'])\n table_data = np.array(df.drop(columns=['id', 'description', 'variety']))\n target = np.array(df['variety']).reshape(-1, 1)\n actual_data = MultiModalData.from_csv(path)\n actual_text_features = actual_data['data_source_text\/description'].features\n actual_table_features = actual_data['data_source_table'].features\n actual_target = actual_data.target\n assert np.array_equal(actual_text_features, text_data)\n assert np.array_equal(actual_table_features, table_data)\n assert np.array_equal(actual_target, target)","code_tokens":"","url":546116} +{"project_name":"enlite-ai\/maze","file_name":"maze_env.py","full_name":"MazeEnv.observation_space","func_name":"observation_space","docstring":"Keep this env compatible with the gym interface by returning the observation space of the current policy.","docstring_tokens":"","code":"@property\ndef observation_space(self):\n \"\"\"Keep this env compatible with the gym interface by returning the\n observation space of the current policy.\"\"\"\n (policy_id, actor_id) = self.core_env.actor_id()\n return self.observation_spaces_dict[policy_id]","code_tokens":"","url":646629} +{"project_name":"explosion\/spaCy","file_name":"test_training.py","full_name":"test_issue7029","func_name":"test_issue7029","docstring":"Test that an empty document doesn't mess up an entire batch.","docstring_tokens":"","code":"@pytest.mark.issue(7029)\ndef test_issue7029():\n \"\"\"Test that an empty document doesn't mess up an entire batch.\"\"\"\n TRAIN_DATA = [('I like green eggs', {'tags': ['N', 'V', 'J', 'N']}), ('Eat blue ham', {'tags': ['V', 'J', 'N']})]\n nlp = English.from_config(load_config_from_str(CONFIG_7029))\n train_examples = []\n for t in TRAIN_DATA:\n train_examples.append(Example.from_dict(nlp.make_doc(t[0]), t[1]))\n optimizer = nlp.initialize(get_examples=lambda : train_examples)\n for i in range(50):\n losses = {}\n nlp.update(train_examples, sgd=optimizer, losses=losses)\n texts = ['first', 'second', 'third', 'fourth', 'and', 'then', 'some', '']\n docs1 = list(nlp.pipe(texts, batch_size=1))\n docs2 = list(nlp.pipe(texts, batch_size=4))\n assert [doc[0].tag_ for doc in docs1[:-1]] == [doc[0].tag_ for doc in docs2[:-1]]","code_tokens":"","url":894388} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"bccache.py","full_name":"BytecodeCache.set_bucket","func_name":"set_bucket","docstring":"Put the bucket into the cache.","docstring_tokens":"","code":"def set_bucket(self, bucket):\n \"\"\"Put the bucket into the cache.\"\"\"\n self.dump_bytecode(bucket)","code_tokens":"","url":39159} +{"project_name":"gunthercox\/ChatterBot","file_name":"events.py","full_name":"InstanceEvents.first_init","func_name":"first_init","docstring":"Called when the first instance of a particular mapping is called.","docstring_tokens":"","code":"def first_init(self, manager, cls):\n \"\"\"Called when the first instance of a particular mapping is called.\n\n \"\"\"","code_tokens":"","url":481325} +{"project_name":"JinliangLu96\/CL_UNMT","file_name":"evaluator.py","full_name":"Evaluator.create_reference_files","func_name":"create_reference_files","docstring":"Create reference files for BLEU evaluation.","docstring_tokens":"","code":"def create_reference_files(self):\n \"\"\"\n Create reference files for BLEU evaluation.\n \"\"\"\n params = self.params\n params.ref_paths = {}\n for ((lang1, lang2), v) in self.data['para'].items():\n assert lang1 < lang2\n for data_set in ['valid', 'test']:\n lang1_path = os.path.join(params.hyp_path, 'ref.{0}-{1}.{2}.txt'.format(lang2, lang1, data_set))\n lang2_path = os.path.join(params.hyp_path, 'ref.{0}-{1}.{2}.txt'.format(lang1, lang2, data_set))\n params.ref_paths[lang2, lang1, data_set] = lang1_path\n params.ref_paths[lang1, lang2, data_set] = lang2_path\n lang1_txt = []\n lang2_txt = []\n for ((sent1, len1), (sent2, len2)) in self.get_iterator(data_set, lang1, lang2):\n lang1_txt.extend(convert_to_text(sent1, len1, self.dico, params))\n lang2_txt.extend(convert_to_text(sent2, len2, self.dico, params))\n lang1_txt = [x.replace('', '<>') for x in lang1_txt]\n lang2_txt = [x.replace('', '<>') for x in lang2_txt]\n with open(lang1_path, 'w', encoding='utf-8') as f:\n f.write('\\n'.join(lang1_txt) + '\\n')\n with open(lang2_path, 'w', encoding='utf-8') as f:\n f.write('\\n'.join(lang2_txt) + '\\n')\n restore_segmentation(lang1_path)\n restore_segmentation(lang2_path)","code_tokens":"","url":123192} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"cbook.py","full_name":"restrict_dict","func_name":"restrict_dict","docstring":"Return a dictionary that contains those keys that appear in both d and keys, with values from d.","docstring_tokens":"","code":"def restrict_dict(d, keys):\n \"\"\"\n Return a dictionary that contains those keys that appear in both\n d and keys, with values from d.\n \"\"\"\n return dict([(k, v) for (k, v) in six.iteritems(d) if k in keys])","code_tokens":"","url":715260} +{"project_name":"ratschlab\/dpsom","file_name":"DPSOM_model.py","full_name":"DPSOM.z_q_neighbors","func_name":"z_q_neighbors","docstring":"Aggregates the respective neighbors in the SOM grid for every z_q.","docstring_tokens":"","code":"@lazy_scope\ndef z_q_neighbors(self):\n \"\"\"Aggregates the respective neighbors in the SOM grid for every z_q.\"\"\"\n k_1 = self.k \/\/ self.som_dim[0]\n k_2 = self.k % self.som_dim[1]\n k_stacked = tf.stack([k_1, k_2], axis=1)\n k1_not_top = tf.less(k_1, tf.constant(self.som_dim[0] - 1, dtype=tf.int64))\n k1_not_bottom = tf.greater(k_1, tf.constant(0, dtype=tf.int64))\n k2_not_right = tf.less(k_2, tf.constant(self.som_dim[1] - 1, dtype=tf.int64))\n k2_not_left = tf.greater(k_2, tf.constant(0, dtype=tf.int64))\n k1_up = tf.where(k1_not_top, tf.add(k_1, 1), tf.zeros(tf.shape(k_1), dtype=tf.dtypes.int64))\n k1_down = tf.where(k1_not_bottom, tf.subtract(k_1, 1), tf.ones(tf.shape(k_1), dtype=tf.dtypes.int64) * (self.som_dim[0] - 1))\n k2_right = tf.where(k2_not_right, tf.add(k_2, 1), tf.zeros(tf.shape(k_2), dtype=tf.dtypes.int64))\n k2_left = tf.where(k2_not_left, tf.subtract(k_2, 1), tf.ones(tf.shape(k_2), dtype=tf.dtypes.int64) * (self.som_dim[0] - 1))\n z_q_up = tf.gather_nd(self.embeddings, tf.stack([k1_up, k_2], axis=1))\n z_q_down = tf.gather_nd(self.embeddings, tf.stack([k1_down, k_2], axis=1))\n z_q_right = tf.gather_nd(self.embeddings, tf.stack([k_1, k2_right], axis=1))\n z_q_left = tf.gather_nd(self.embeddings, tf.stack([k_1, k2_left], axis=1))\n z_q_neighbors = tf.stack([self.z_q, z_q_up, z_q_down, z_q_right, z_q_left], axis=1)\n return z_q_neighbors","code_tokens":"","url":166946} +{"project_name":"mhagiwara\/realworldnlp","file_name":"word2vec.py","full_name":"get_synonyms","func_name":"get_synonyms","docstring":"Given a token, return a list of top N most similar words to the token.","docstring_tokens":"","code":"def get_synonyms(token: str, embedding: Model, vocab: Vocabulary, num_synonyms: int=10):\n \"\"\"Given a token, return a list of top N most similar words to the token.\"\"\"\n token_id = vocab.get_token_index(token, 'token_in')\n token_vec = embedding.weight[token_id]\n cosine = CosineSimilarity(dim=0)\n sims = Counter()\n for (index, token) in vocab.get_index_to_token_vocabulary('token_in').items():\n sim = cosine(token_vec, embedding.weight[index]).item()\n sims[token] = sim\n return sims.most_common(num_synonyms)","code_tokens":"","url":831423} +{"project_name":"deepmind\/dm_control","file_name":"finger.py","full_name":"Turn.get_observation","func_name":"get_observation","docstring":"Returns state, touch sensors, and target info.","docstring_tokens":"","code":"def get_observation(self, physics):\n \"\"\"Returns state, touch sensors, and target info.\"\"\"\n obs = collections.OrderedDict()\n obs['position'] = physics.bounded_position()\n obs['velocity'] = physics.velocity()\n obs['touch'] = physics.touch()\n obs['target_position'] = physics.target_position()\n obs['dist_to_target'] = physics.dist_to_target()\n return obs","code_tokens":"","url":166346} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"ast.py","full_name":"GlyphClass.extend","func_name":"extend","docstring":"Add a list of :class:`GlyphName` objects to the class.","docstring_tokens":"","code":"def extend(self, glyphs):\n \"\"\"Add a list of :class:`GlyphName` objects to the class.\"\"\"\n self.glyphs.extend(glyphs)","code_tokens":"","url":360840} +{"project_name":"triaquae\/triaquae","file_name":"fallback.py","full_name":"FallbackTest.test_session_fallback_only","func_name":"test_session_fallback_only","docstring":"Confirms that large messages, none of which fit in a cookie, are stored in the SessionBackend (and nothing is stored in the CookieBackend).","docstring_tokens":"","code":"def test_session_fallback_only(self):\n \"\"\"\n Confirms that large messages, none of which fit in a cookie, are stored\n in the SessionBackend (and nothing is stored in the CookieBackend).\n \"\"\"\n storage = self.get_storage()\n response = self.get_response()\n storage.add(constants.INFO, 'x' * 5000)\n storage.update(response)\n cookie_storing = self.stored_cookie_messages_count(storage, response)\n self.assertEqual(cookie_storing, 0)\n session_storing = self.stored_session_messages_count(storage, response)\n self.assertEqual(session_storing, 1)","code_tokens":"","url":358140} +{"project_name":"rudranil723\/mini-main","file_name":"client.py","full_name":"Client.delete","func_name":"delete","docstring":"Send a DELETE request to the server.","docstring_tokens":"","code":"def delete(self, path, data='', content_type='application\/octet-stream', follow=False, secure=False, **extra):\n \"\"\"Send a DELETE request to the server.\"\"\"\n response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)\n if follow:\n response = self._handle_redirects(response, data=data, content_type=content_type, **extra)\n return response","code_tokens":"","url":316544} +{"project_name":"rudranil723\/mini-main","file_name":"syntax.py","full_name":"SyntaxTheme.get_style_for_token","func_name":"get_style_for_token","docstring":"Get a style for a given Pygments token.","docstring_tokens":"","code":"@abstractmethod\ndef get_style_for_token(self, token_type: TokenType) -> Style:\n \"\"\"Get a style for a given Pygments token.\"\"\"\n raise NotImplementedError","code_tokens":"","url":268950} +{"project_name":"intel\/neural-compressor","file_name":"metric.py","full_name":"ONNXRTGLUE.result","func_name":"result","docstring":"Compute the GLUE score.","docstring_tokens":"","code":"def result(self):\n \"\"\"Compute the GLUE score.\"\"\"\n output_mode = transformers.glue_output_modes[self.task]\n if output_mode == 'classification':\n processed_preds = np.argmax(self.pred_list, axis=1)\n elif output_mode == 'regression':\n processed_preds = np.squeeze(self.pred_list)\n result = transformers.glue_compute_metrics(self.task, processed_preds, self.label_list)\n return result[self.return_key[self.task]]","code_tokens":"","url":738587} +{"project_name":"maxbrenner-ai\/GO-Bot-DRL","file_name":"test.py","full_name":"episode_reset","func_name":"episode_reset","docstring":"Resets the episode\/conversation in the testing loop.","docstring_tokens":"","code":"def episode_reset():\n \"\"\"Resets the episode\/conversation in the testing loop.\"\"\"\n state_tracker.reset()\n user_action = user.reset()\n emc.infuse_error(user_action)\n state_tracker.update_state_user(user_action)\n dqn_agent.reset()","code_tokens":"","url":578642} +{"project_name":"aonotas\/dynamic_cnn_for_nlp","file_name":"test_hinton_digram.py","full_name":"hinton","func_name":"hinton","docstring":"Draw Hinton diagram for visualizing a weight matrix.","docstring_tokens":"","code":"def hinton(matrix, max_weight=None, ax=None):\n \"\"\"Draw Hinton diagram for visualizing a weight matrix.\"\"\"\n ax = ax if ax is not None else plt.gca()\n if not max_weight:\n max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) \/ np.log(2))\n ax.patch.set_facecolor('gray')\n ax.set_aspect('equal', 'box')\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n for ((x, y), w) in np.ndenumerate(matrix):\n color = 'white' if w > 0 else 'black'\n size = np.sqrt(np.abs(w))\n rect = plt.Rectangle([x - size \/ 2, y - size \/ 2], size, size, facecolor=color, edgecolor=color)\n ax.add_patch(rect)\n ax.autoscale_view()\n ax.invert_yaxis()","code_tokens":"","url":174354} +{"project_name":"huawei-noah\/xingtian","file_name":"tensorflow_fn.py","full_name":"arange","func_name":"arange","docstring":"Rreange from left to right.","docstring_tokens":"","code":"def arange(left, right, dtype, device):\n \"\"\"Rreange from left to right.\"\"\"\n if dtype == 'long':\n dtype = tf.float32\n elif dtype == 'uint8':\n dtype = tf.int32\n else:\n dtype = None\n return tf.range(left, right, dtype=dtype)","code_tokens":"","url":962844} +{"project_name":"zcrwind\/PredNet_pytorch","file_name":"prednet.py","full_name":"PredNet.make_layers","func_name":"make_layers","docstring":"equal to the `build` method in original version.","docstring_tokens":"","code":"def make_layers(self):\n \"\"\"\n equal to the `build` method in original version.\n \"\"\"\n self.conv_layers = {item: [] for item in ['i', 'f', 'c', 'o', 'A', 'Ahat']}\n lstm_list = ['i', 'f', 'c', 'o']\n for item in sorted(self.conv_layers.keys()):\n for lay in range(self.num_layers):\n downSample_factor = 2 ** lay\n if item == 'Ahat':\n in_channels = self.R_stack_sizes[lay]\n self.conv_layers['Ahat'].append(nn.Conv2d(in_channels=in_channels, out_channels=self.stack_sizes[lay], kernel_size=self.Ahat_filter_sizes[lay], stride=(1, 1), padding=int((self.Ahat_filter_sizes[lay] - 1) \/ 2)))\n act = 'relu' if lay == 0 else self.A_activation\n self.conv_layers['Ahat'].append(get_activationFunc(act))\n elif item == 'A':\n if self.isNotTopestLayer(lay):\n in_channels = self.R_stack_sizes[lay] * 2\n self.conv_layers['A'].append(nn.Conv2d(in_channels=in_channels, out_channels=self.stack_sizes[lay + 1], kernel_size=self.A_filter_sizes[lay], stride=(1, 1), padding=int((self.A_filter_sizes[lay] - 1) \/ 2)))\n self.conv_layers['A'].append(get_activationFunc(self.A_activation))\n elif item in lstm_list:\n in_channels = self.stack_sizes[lay] * 2 + self.R_stack_sizes[lay]\n if self.isNotTopestLayer(lay):\n in_channels += self.R_stack_sizes[lay + 1]\n self.conv_layers[item].append(nn.Conv2d(in_channels=in_channels, out_channels=self.R_stack_sizes[lay], kernel_size=self.R_filter_sizes[lay], stride=(1, 1), padding=int((self.R_filter_sizes[lay] - 1) \/ 2)))\n for (name, layerList) in self.conv_layers.items():\n self.conv_layers[name] = nn.ModuleList(layerList)\n setattr(self, name, self.conv_layers[name])\n self.upSample = nn.Upsample(scale_factor=2, mode='nearest')\n self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)","code_tokens":"","url":305952} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"test_extras.py","full_name":"TestMedian.test_2d_waxis","func_name":"test_2d_waxis","docstring":"Tests median w\/ 2D arrays and different axis.","docstring_tokens":"","code":"def test_2d_waxis(self):\n \"\"\"Tests median w\/ 2D arrays and different axis.\"\"\"\n x = masked_array(np.arange(30).reshape(10, 3))\n x[:3] = x[-3:] = masked\n assert_equal(median(x), 14.5)\n assert_equal(median(x, axis=0), [13.5, 14.5, 15.5])\n assert_equal(median(x, axis=1), [0, 0, 0, 10, 13, 16, 19, 0, 0, 0])\n assert_equal(median(x, axis=1).mask, [1, 1, 1, 0, 0, 0, 0, 1, 1, 1])","code_tokens":"","url":532085} +{"project_name":"microsoft\/nni","file_name":"proxyless.py","full_name":"ProxylessMixedInput.forward","func_name":"forward","docstring":"Choose one single input.","docstring_tokens":"","code":"def forward(self, inputs):\n \"\"\"Choose one single input.\"\"\"\n if self._sampled is None:\n raise RuntimeError('resample() needs to be called before fprop.')\n result = self.forward_path(self._sampled[0], *inputs)\n return _ProxylessFunction.apply(self.forward_path, self._sampled[0], len(inputs), self._softmax, self._arch_alpha, *inputs, result)","code_tokens":"","url":728853} +{"project_name":"ipazc\/vrpwrp","file_name":"test_boundingbox.py","full_name":"TestBoundingBox.test_get_box_coord","func_name":"test_get_box_coord","docstring":"Tests that bounding box successfully returns the array of the box in coordinates version.","docstring_tokens":"","code":"def test_get_box_coord(self):\n \"\"\"\n Tests that bounding box successfully returns the array of the box in coordinates version.\n \"\"\"\n box = BoundingBox(15, 16, 17, 18)\n self.assertEqual(box.get_box_coord(), [[15, 16], [32, 16], [15, 34], [32, 34]])","code_tokens":"","url":940011} +{"project_name":"zhang614\/MicroGrid","file_name":"message.py","full_name":"Message.get_charset","func_name":"get_charset","docstring":"Return the Charset instance associated with the message's payload.","docstring_tokens":"","code":"def get_charset(self):\n \"\"\"Return the Charset instance associated with the message's payload.\n \"\"\"\n return self._charset","code_tokens":"","url":636102} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"test_logging.py","full_name":"SocketHandlerTest.setUp","func_name":"setUp","docstring":"Set up a TCP server to receive log messages, and a SocketHandler pointing to that server's address and port.","docstring_tokens":"","code":"def setUp(self):\n \"\"\"Set up a TCP server to receive log messages, and a SocketHandler\n pointing to that server's address and port.\"\"\"\n BaseTest.setUp(self)\n self.tcpserver = LogRecordSocketReceiver(port=0)\n self.port = self.tcpserver.socket.getsockname()[1]\n self.threads = [threading.Thread(target=self.tcpserver.serve_until_stopped)]\n for thread in self.threads:\n thread.start()\n self.sock_hdlr = logging.handlers.SocketHandler('localhost', self.port)\n self.sock_hdlr.setFormatter(self.root_formatter)\n self.root_logger.removeHandler(self.root_logger.handlers[0])\n self.root_logger.addHandler(self.sock_hdlr)","code_tokens":"","url":219624} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"configurer.py","full_name":"IncrSegmentationConfigurer.is_incremental","func_name":"is_incremental","docstring":"Return whether current model classes is increased from original model classes.","docstring_tokens":"","code":"def is_incremental(self) -> bool:\n \"\"\"Return whether current model classes is increased from original model classes.\"\"\"\n if len(set(self.org_model_classes) & set(self.model_classes)) == 1 or set(self.org_model_classes) == set(self.model_classes):\n is_cls_incr = False\n else:\n is_cls_incr = True\n return is_cls_incr","code_tokens":"","url":918256} +{"project_name":"georghess\/voxel-mae","file_name":"pillar_scatter.py","full_name":"PointPillarsScatter.forward","func_name":"forward","docstring":"Foraward function to scatter features.","docstring_tokens":"","code":"@auto_fp16(apply_to=('voxel_features',))\ndef forward(self, voxel_features, coors, batch_size=None):\n \"\"\"Foraward function to scatter features.\"\"\"\n if batch_size is not None:\n return self.forward_batch(voxel_features, coors, batch_size)\n else:\n return self.forward_single(voxel_features, coors)","code_tokens":"","url":380701} +{"project_name":"researchmm\/WSOD2","file_name":"base.py","full_name":"BaseDetector.extract_feats","func_name":"extract_feats","docstring":"Extract features from multiple images.","docstring_tokens":"","code":"def extract_feats(self, imgs):\n \"\"\"Extract features from multiple images.\n\n Args:\n imgs (list[torch.Tensor]): A list of images. The images are\n augmented from the same image but in different ways.\n\n Returns:\n list[torch.Tensor]: Features of different images\n \"\"\"\n assert isinstance(imgs, list)\n return [self.extract_feat(img) for img in imgs]","code_tokens":"","url":374293} +{"project_name":"rudranil723\/mini-main","file_name":"otConverters.py","full_name":"BaseConverter.readArray","func_name":"readArray","docstring":"Read an array of values from the reader.","docstring_tokens":"","code":"def readArray(self, reader, font, tableDict, count):\n \"\"\"Read an array of values from the reader.\"\"\"\n lazy = font.lazy and count > 8\n if lazy:\n recordSize = self.getRecordSize(reader)\n if recordSize is NotImplemented:\n lazy = False\n if not lazy:\n l = []\n for i in range(count):\n l.append(self.read(reader, font, tableDict))\n return l\n else:\n l = _LazyList()\n l.reader = reader.copy()\n l.pos = l.reader.pos\n l.font = font\n l.conv = self\n l.recordSize = recordSize\n l.extend((_MissingItem([i]) for i in range(count)))\n reader.advance(count * recordSize)\n return l","code_tokens":"","url":317450} +{"project_name":"zoltanbonus\/ai50","file_name":"logic.py","full_name":"Sentence.symbols","func_name":"symbols","docstring":"Returns a set of all symbols in the logical sentence.","docstring_tokens":"","code":"def symbols(self):\n \"\"\"Returns a set of all symbols in the logical sentence.\"\"\"\n return set()","code_tokens":"","url":85366} +{"project_name":"feast-dev\/feast","file_name":"feature_logging.py","full_name":"LoggingSource.get_log_timestamp_column","func_name":"get_log_timestamp_column","docstring":"Return timestamp column that must exist in generated schema.","docstring_tokens":"","code":"@abc.abstractmethod\ndef get_log_timestamp_column(self) -> str:\n \"\"\"Return timestamp column that must exist in generated schema.\"\"\"\n raise NotImplementedError","code_tokens":"","url":544222} +{"project_name":"sktime\/sktime","file_name":"test_panel_converters.py","full_name":"test_from_nested_to_long","func_name":"test_from_nested_to_long","docstring":"Test from_nested_to_long for correctness.","docstring_tokens":"","code":"@pytest.mark.parametrize('n_instances', N_INSTANCES)\n@pytest.mark.parametrize('n_columns', N_COLUMNS)\n@pytest.mark.parametrize('n_timepoints', N_TIMEPOINTS)\ndef test_from_nested_to_long(n_instances, n_columns, n_timepoints):\n \"\"\"Test from_nested_to_long for correctness.\"\"\"\n (nested, _) = make_classification_problem(n_instances, n_columns, n_timepoints)\n X_long = from_nested_to_long(nested, instance_column_name='case_id', time_column_name='reading_id', dimension_column_name='dim_id')\n assert isinstance(X_long, pd.DataFrame)\n assert X_long.shape == (n_instances * n_timepoints * n_columns, 4)\n assert (X_long.columns == ['case_id', 'reading_id', 'dim_id', 'value']).all()","code_tokens":"","url":886156} +{"project_name":"open-mmlab\/mmrotate","file_name":"gmm.py","full_name":"GaussianMixture.update_mu","func_name":"update_mu","docstring":"Updates mean to the provided value.","docstring_tokens":"","code":"def update_mu(self, mu):\n \"\"\"Updates mean to the provided value.\n\n Args:\n mu (torch.Tensor):\n \"\"\"\n assert mu.size() == (self.T, self.n_components, self.n_features), 'Input mu does not have required tensor dimensions (%i, %i, %i)' % (self.T, self.n_components, self.n_features)\n if mu.size() == (self.n_components, self.n_features):\n self.mu = mu.unsqueeze(0)\n elif mu.size() == (self.T, self.n_components, self.n_features):\n self.mu = mu.clone()","code_tokens":"","url":625062} +{"project_name":"deepmind\/trfl","file_name":"retrace_ops_test.py","full_name":"RetraceOpsTest.testRetraceCoreLossThreeTimeSteps","func_name":"testRetraceCoreLossThreeTimeSteps","docstring":"Tests whether retrace_core evaluates correct losses.","docstring_tokens":"","code":"def testRetraceCoreLossThreeTimeSteps(self):\n \"\"\"Tests whether retrace_core evaluates correct losses.\"\"\"\n (_, _, retrace) = self._get_retrace_core()\n with self.test_session() as sess:\n self.assertAllClose(sess.run(retrace.loss), self.expected_result)","code_tokens":"","url":356237} +{"project_name":"intelligent-environments-lab\/CityLearn","file_name":"building.py","full_name":"Building.carbon_intensity","func_name":"carbon_intensity","docstring":"Carbon dioxide emission rate time series.","docstring_tokens":"","code":"@property\ndef carbon_intensity(self) -> CarbonIntensity:\n \"\"\"Carbon dioxide emission rate time series.\"\"\"\n return self.__carbon_intensity","code_tokens":"","url":105280} +{"project_name":"ludwig-ai\/ludwig","file_name":"inference_utils.py","full_name":"to_inference_module_input_from_dataframe","func_name":"to_inference_module_input_from_dataframe","docstring":"Converts a pandas DataFrame to be compatible with a torchscripted InferenceModule forward pass.","docstring_tokens":"","code":"def to_inference_module_input_from_dataframe(dataset: pd.DataFrame, config: ModelConfigDict, load_paths: bool=False, device: Optional[torch.device]=None) -> Dict[str, TorchscriptPreprocessingInput]:\n \"\"\"Converts a pandas DataFrame to be compatible with a torchscripted InferenceModule forward pass.\"\"\"\n inputs = {}\n for if_config in config['input_features']:\n feature_inputs = to_inference_model_input_from_series(dataset[if_config[COLUMN]], if_config[TYPE], load_paths=load_paths, feature_config=if_config)\n feature_inputs = place_on_device(feature_inputs, device)\n inputs[if_config[NAME]] = feature_inputs\n return inputs","code_tokens":"","url":617108} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"db_import_multiplexer.py","full_name":"DbImportMultiplexer.Reload","func_name":"Reload","docstring":"Call `Import` on every run to import.","docstring_tokens":"","code":"def Reload(self):\n \"\"\"Call `Import` on every run to import.\"\"\"\n tf.logging.info('Beginning DbImportMultiplexer.Reload()')\n items_queue = queue.Queue()\n for item in six.iteritems(self._run_importers):\n items_queue.put(item)\n names_to_delete = set()\n names_to_delete_mutex = threading.Lock()\n\n def Worker():\n \"\"\"Keeps importing runs until none are left.\"\"\"\n while True:\n try:\n (name, importer) = items_queue.get(block=False)\n except queue.Empty:\n break\n try:\n start = time.time()\n importer.Import()\n elapsed = time.time() - start\n tf.logging.debug('importer.Import() took %0.3f sec', elapsed)\n except (OSError, IOError) as e:\n tf.logging.error('Unable to import run %r: %s', name, e)\n except directory_watcher.DirectoryDeletedError:\n with names_to_delete_mutex:\n names_to_delete.add(name)\n finally:\n items_queue.task_done()\n if self._max_reload_threads > 1:\n num_threads = min(self._max_reload_threads, len(self._run_importers))\n tf.logging.info('Starting %d threads to import runs', num_threads)\n for i in xrange(num_threads):\n thread = threading.Thread(target=Worker, name='Importer %d' % i)\n thread.daemon = True\n thread.start()\n items_queue.join()\n else:\n tf.logging.info('Importing runs serially on the main thread')\n Worker()\n for name in names_to_delete:\n tf.logging.warning('Deleting importer %r', name)\n del self._run_importers[name]\n tf.logging.info('Finished with DbImportMultiplexer.Reload()')\n return self","code_tokens":"","url":312032} +{"project_name":"vmware-labs\/research-and-development---lab","file_name":"llama_training.py","full_name":"preprocess","func_name":"preprocess","docstring":"Preprocess the data by tokenizing.","docstring_tokens":"","code":"def preprocess(sources: Sequence[str], targets: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:\n \"\"\"Preprocess the data by tokenizing.\"\"\"\n examples = [s + t for (s, t) in zip(sources, targets)]\n (examples_tokenized, sources_tokenized) = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]\n input_ids = examples_tokenized['input_ids']\n labels = copy.deepcopy(input_ids)\n for (label, source_len) in zip(labels, sources_tokenized['input_ids_lens']):\n label[:source_len] = IGNORE_INDEX\n return dict(input_ids=input_ids, labels=labels)","code_tokens":"","url":346090} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"test_config_helpers.py","full_name":"create_dataset_csv","func_name":"create_dataset_csv","docstring":"Create dummy dataset csv file for tests, deleting any pre-existing file.","docstring_tokens":"","code":"def create_dataset_csv(test_output_dirs: OutputFolderForTests) -> Path:\n \"\"\"Create dummy dataset csv file for tests,\n deleting any pre-existing file.\"\"\"\n test_csv = 'test_dataset.csv'\n root_dir = test_output_dirs.root_dir\n dataset_csv_path = root_dir \/ test_csv\n if dataset_csv_path.exists():\n dataset_csv_path.unlink()\n dataset_csv_path.write_text('subject,channel,filePath')\n return dataset_csv_path","code_tokens":"","url":613574} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"visualization.py","full_name":"draw_predictions","func_name":"draw_predictions","docstring":"Converts predictions to visual representations depending on task type and draws them on a frame.","docstring_tokens":"","code":"def draw_predictions(task_type: TaskType, predictions: List[Annotation], frame: Mat, fit_to_size: Tuple[int, int]):\n \"\"\"Converts predictions to visual representations depending on task type and draws them on a frame.\"\"\"\n (width, height) = (frame.shape[1], frame.shape[0])\n if fit_to_size:\n ratio_x = fit_to_size[0] \/ width\n ratio_y = fit_to_size[1] \/ height\n ratio = min(ratio_x, ratio_y)\n frame = cv2.resize(frame, None, fx=ratio, fy=ratio)\n if task_type in {TaskType.DETECTION, TaskType.ANOMALY_DETECTION}:\n frame = draw_bounding_boxes(frame, predictions, put_object_count=True)\n elif task_type in {TaskType.CLASSIFICATION, TaskType.ANOMALY_CLASSIFICATION}:\n frame = put_labels(frame, predictions)\n elif task_type in {TaskType.INSTANCE_SEGMENTATION, TaskType.ROTATED_DETECTION}:\n frame = draw_masks(frame, predictions, put_object_count=True)\n elif task_type in {TaskType.SEGMENTATION, TaskType.ANOMALY_SEGMENTATION}:\n frame = draw_masks(frame, predictions, put_object_count=False)\n else:\n raise ValueError(f'Unknown task type: {task_type}')\n return frame","code_tokens":"","url":918962} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_window_summarizer.py","full_name":"test_windowsummarizer","func_name":"test_windowsummarizer","docstring":"Test columns match kwargs arguments.","docstring_tokens":"","code":"@pytest.mark.parametrize('kwargs, column_names, y, target_cols, truncate', [(kwargs, ['y_lag_1', 'y_mean_1_3', 'y_mean_1_12', 'y_std_1_4'], y_train_named, None, None), (kwargs_alternames, Xtmvar, X_ll_train, ['POP', 'GNP'], None), (kwargs_alternames, Xtmvar_none, X_ll_train, None, None), (kwargs, ['y_lag_1', 'y_mean_1_3', 'y_mean_1_12', 'y_std_1_4'], y_group1, None, None), (kwargs, ['y_lag_1', 'y_mean_1_3', 'y_mean_1_12', 'y_std_1_4'], y_grouped, None, None), (kwargs, ['y_lag_1', 'y_mean_1_3', 'y_mean_1_12', 'y_std_1_4'], y_hierarchical, None, None), (None, ['var_0_lag_1', 'var_1'], y_multi, None, None), (None, None, y_train, None, None), (None, ['a_lag_1'], y_pd, None, None), (kwargs_custom, ['a_count_gt100_3_2'], y_pd, None, None), (kwargs_alternames, ['0_lag_3', '0_lag_6'], y_train, None, 'bfill'), (kwargs_variant, ['0_mean_1_7', '0_mean_8_7', '0_cov_1_28'], y_train, None, None)])\ndef test_windowsummarizer(kwargs, column_names, y, target_cols, truncate):\n \"\"\"Test columns match kwargs arguments.\"\"\"\n if kwargs is not None:\n transformer = WindowSummarizer(**kwargs, target_cols=target_cols, truncate=truncate)\n else:\n transformer = WindowSummarizer(target_cols=target_cols, truncate=truncate)\n Xt = transformer.fit_transform(y)\n if Xt is not None:\n if isinstance(Xt, pd.DataFrame):\n Xt_columns = Xt.columns.to_list()\n else:\n Xt_columns = Xt.name\n else:\n Xt_columns = None\n assert y.index.names == Xt.index.names\n check_eval(Xt_columns, column_names)","code_tokens":"","url":400092} +{"project_name":"sarnsdev\/social-alignment-data-mining","file_name":"utils.py","full_name":"flatten","func_name":"flatten","docstring":"Recursively flatten tuple, list and set in a list.","docstring_tokens":"","code":"def flatten(a):\n \"\"\"\n Recursively flatten tuple, list and set in a list.\n\n \"\"\"\n if isinstance(a, (tuple, list, set)):\n l = []\n for item in a:\n l.extend(flatten(item))\n return l\n else:\n return [a]","code_tokens":"","url":392765} +{"project_name":"ltbringer\/tic_tac_toe","file_name":"agent.py","full_name":"Agent.on_reward","func_name":"on_reward","docstring":"Assign rewards to actions performed on intermediate states.","docstring_tokens":"","code":"def on_reward(self, reward):\n \"\"\"\n Assign rewards to actions performed on intermediate states.\n \"\"\"\n if len(self.state_order) == 0:\n return None\n (new_state_key, new_action) = self.state_order.pop()\n self.states[new_state_key] = np.zeros((3, 3))\n self.states[new_state_key].itemset(new_action, reward)\n while self.state_order:\n (state_key, action) = self.state_order.pop()\n reward *= self.discount_factor\n if state_key in self.states:\n reward += self.learn_by_temporal_difference(reward, new_state_key, state_key).item(new_action)\n log('update learning', state_key, action, reward)\n log(self.states[state_key])\n self.states[state_key].itemset(action, reward)\n else:\n self.states[state_key] = np.zeros((3, 3))\n reward = self.learn_by_temporal_difference(reward, new_state_key, state_key).item(new_action)\n self.states[state_key].itemset(action, reward)\n new_state_key = state_key\n new_action = action","code_tokens":"","url":916630} +{"project_name":"voxel51\/fiftyone","file_name":"torch.py","full_name":"TorchImageModel.classes","func_name":"classes","docstring":"The list of class labels for the model, if known.","docstring_tokens":"","code":"@property\ndef classes(self):\n \"\"\"The list of class labels for the model, if known.\"\"\"\n return self._classes","code_tokens":"","url":584199} +{"project_name":"RonMen10\/Artificial-decision-making-of-autonomous-vehicles-AI","file_name":"road.py","full_name":"Road.act","func_name":"act","docstring":"Decide the actions of each entity on the road.","docstring_tokens":"","code":"def act(self):\n \"\"\"\n Decide the actions of each entity on the road.\n \"\"\"\n for vehicle in self.vehicles:\n vehicle.act()","code_tokens":"","url":34772} +{"project_name":"google-research\/rigl","file_name":"mobilenetv1_model.py","full_name":"mobilenet_v1_generator","func_name":"mobilenet_v1_generator","docstring":"Generator for mobilenet v2 models.","docstring_tokens":"","code":"def mobilenet_v1_generator(num_classes=1000, pruning_method='baseline', width=1.0, prune_last_layer=False, data_format='channels_first', weight_decay=0.0, name=None):\n \"\"\"Generator for mobilenet v2 models.\n\n Args:\n num_classes: Int number of possible classes for image classification.\n pruning_method: String that specifies the pruning method used to identify\n which weights to remove.\n width: Float that scales the number of filters in each layer.\n prune_last_layer: Whether or not to prune the last layer.\n data_format: String either \"channels_first\" for `[batch, channels, height,\n width]` or \"channels_last for `[batch, height, width, channels]`.\n weight_decay: Weight for the l2 regularization loss.\n name: String that specifies name for model layer.\n\n Returns:\n Model `function` that takes in `inputs` and `is_training` and returns the\n output `Tensor` of the ResNet model.\n \"\"\"\n\n def model(inputs, is_training):\n \"\"\"Creation of the model graph.\"\"\"\n with tf.variable_scope(name, 'resnet_model'):\n inputs = resnet_model.fixed_padding(inputs, kernel_size=3, data_format=data_format)\n padding = 'VALID'\n kernel_initializer = tf.variance_scaling_initializer()\n kernel_regularizer = contrib_layers.l2_regularizer(weight_decay)\n inputs = tf.layers.conv2d(inputs=inputs, filters=_make_divisible(32 * width), kernel_size=3, strides=2, padding=padding, use_bias=False, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, data_format=data_format, name='initial_conv')\n inputs = tf.identity(inputs, 'initial_conv')\n inputs = resnet_model.batch_norm_relu(inputs, is_training, data_format=data_format)\n mb_block = functools.partial(mbv1_block_, is_training=is_training, width=width, pruning_method=pruning_method, data_format=data_format, weight_decay=weight_decay)\n inputs = mb_block(inputs, filters=64, stride=1, block_id=0)\n inputs = mb_block(inputs, filters=128, stride=2, block_id=1)\n inputs = mb_block(inputs, filters=128, stride=1, block_id=2)\n inputs = mb_block(inputs, filters=256, stride=2, block_id=3)\n inputs = mb_block(inputs, filters=256, stride=1, block_id=4)\n inputs = mb_block(inputs, filters=512, stride=2, block_id=5)\n inputs = mb_block(inputs, filters=512, stride=1, block_id=6)\n inputs = mb_block(inputs, filters=512, stride=1, block_id=7)\n inputs = mb_block(inputs, filters=512, stride=1, block_id=8)\n inputs = mb_block(inputs, filters=512, stride=1, block_id=9)\n inputs = mb_block(inputs, filters=512, stride=1, block_id=10)\n inputs = mb_block(inputs, filters=1024, stride=2, block_id=11)\n inputs = mb_block(inputs, filters=1024, stride=1, block_id=12)\n last_block_filters = _make_divisible(int(1024 * width), 8)\n if data_format == 'channels_last':\n pool_size = (inputs.shape[1], inputs.shape[2])\n elif data_format == 'channels_first':\n pool_size = (inputs.shape[2], inputs.shape[3])\n inputs = tf.layers.average_pooling2d(inputs=inputs, pool_size=pool_size, strides=1, padding='VALID', data_format=data_format, name='final_avg_pool')\n inputs = tf.identity(inputs, 'final_avg_pool')\n inputs = tf.reshape(inputs, [-1, last_block_filters])\n kernel_initializer = tf.variance_scaling_initializer()\n kernel_regularizer = contrib_layers.l2_regularizer(weight_decay)\n if prune_last_layer:\n inputs = sparse_fully_connected(x=inputs, units=num_classes, sparsity_technique=pruning_method if prune_last_layer else 'baseline', kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, name='final_dense')\n else:\n inputs = tf.layers.dense(inputs=inputs, units=num_classes, activation=None, use_bias=True, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, name='final_dense')\n inputs = tf.identity(inputs, 'final_dense')\n return inputs\n model.default_image_size = 224\n return model","code_tokens":"","url":841581} +{"project_name":"intel\/neural-compressor","file_name":"distillation.py","full_name":"Distillation.train_distributed","func_name":"train_distributed","docstring":"Setter to know whether need distributed training dataloader.","docstring_tokens":"","code":"@train_distributed.setter\ndef train_distributed(self, distributed):\n \"\"\"Setter to know whether need distributed training dataloader.\"\"\"\n self._train_distributed = distributed","code_tokens":"","url":738351} +{"project_name":"zhang614\/MicroGrid","file_name":"_header_value_parser.py","full_name":"get_obs_route","func_name":"get_obs_route","docstring":"obs-route = obs-domain-list \":\" obs-domain-list = *(CFWS \/ \",\") \"@\" domain *(\",\" [CFWS] [\"@\" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree).","docstring_tokens":"","code":"def get_obs_route(value):\n \"\"\" obs-route = obs-domain-list \":\"\n obs-domain-list = *(CFWS \/ \",\") \"@\" domain *(\",\" [CFWS] [\"@\" domain])\n\n Returns an obs-route token with the appropriate sub-tokens (that is,\n there is no obs-domain-list in the parse tree).\n \"\"\"\n obs_route = ObsRoute()\n while value and (value[0] == ',' or value[0] in CFWS_LEADER):\n if value[0] in CFWS_LEADER:\n (token, value) = get_cfws(value)\n obs_route.append(token)\n elif value[0] == ',':\n obs_route.append(ListSeparator)\n value = value[1:]\n if not value or value[0] != '@':\n raise errors.HeaderParseError(\"expected obs-route domain but found '{}'\".format(value))\n obs_route.append(RouteComponentMarker)\n (token, value) = get_domain(value[1:])\n obs_route.append(token)\n while value and value[0] == ',':\n obs_route.append(ListSeparator)\n value = value[1:]\n if not value:\n break\n if value[0] in CFWS_LEADER:\n (token, value) = get_cfws(value)\n obs_route.append(token)\n if value[0] == '@':\n obs_route.append(RouteComponentMarker)\n (token, value) = get_domain(value[1:])\n obs_route.append(token)\n if not value:\n raise errors.HeaderParseError('end of header while parsing obs-route')\n if value[0] != ':':\n raise errors.HeaderParseError(\"expected ':' marking end of obs-route but found '{}'\".format(value))\n obs_route.append(ValueTerminal(':', 'end-of-obs-route-marker'))\n return (obs_route, value[1:])","code_tokens":"","url":636180} +{"project_name":"matsu0228\/nlp-jp","file_name":"interactiveshell.py","full_name":"InteractiveShell.ex","func_name":"ex","docstring":"Execute a normal python statement in user namespace.","docstring_tokens":"","code":"def ex(self, cmd):\n \"\"\"Execute a normal python statement in user namespace.\"\"\"\n with self.builtin_trap:\n exec(cmd, self.user_global_ns, self.user_ns)","code_tokens":"","url":786730} +{"project_name":"voxel51\/fiftyone","file_name":"utils.py","full_name":"validate_hex_color","func_name":"validate_hex_color","docstring":"Validates that the given value is a hex color string or css name.","docstring_tokens":"","code":"def validate_hex_color(value):\n \"\"\"Validates that the given value is a hex color string or css name.\n\n Args:\n value: a value\n\n Raises:\n ValueError: if ``value`` is not a hex color string\n \"\"\"\n if not etau.is_str(value) or not re.search('^#(?:[0-9a-fA-F]{3}){1,2}$', value):\n raise ValueError(\"%s is not a valid hex color string (eg: '#FF6D04')\" % value)","code_tokens":"","url":583465} +{"project_name":"liuyuemaicha\/Deep-Reinforcement-Learning-for-Dialogue-Generation-in-tensorflow","file_name":"gst_seq2seq.py","full_name":"sequence_loss_by_example","func_name":"sequence_loss_by_example","docstring":"Weighted cross-entropy loss for a sequence of logits (per example).","docstring_tokens":"","code":"def sequence_loss_by_example(logits, targets, weights, average_across_timesteps=True, softmax_loss_function=None, name=None):\n \"\"\"Weighted cross-entropy loss for a sequence of logits (per example).\n\n Args:\n logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols].\n targets: List of 1D batch-sized int32 Tensors of the same length as logits.\n weights: List of 1D batch-sized float-Tensors of the same length as logits.\n average_across_timesteps: If set, divide the returned cost by the total\n label weight.\n softmax_loss_function: Function (inputs-batch, labels-batch) -> loss-batch\n to be used instead of the standard softmax (the default if this is None).\n name: Optional name for this operation, default: \"sequence_loss_by_example\".\n\n Returns:\n 1D batch-sized float Tensor: The log-perplexity for each sequence.\n\n Raises:\n ValueError: If len(logits) is different from len(targets) or len(weights).\n \"\"\"\n if len(targets) != len(logits) or len(weights) != len(logits):\n raise ValueError('Lengths of logits, weights, and targets must be the same %d, %d, %d.' % (len(logits), len(weights), len(targets)))\n with ops.name_scope(name, 'sequence_loss_by_example', logits + targets + weights):\n log_perp_list = []\n for (logit, target, weight) in zip(logits, targets, weights):\n if softmax_loss_function is None:\n target = array_ops.reshape(target, [-1])\n crossent = nn_ops.sparse_softmax_cross_entropy_with_logits(logit, target)\n else:\n crossent = softmax_loss_function(logit, target)\n log_perp_list.append(crossent * weight)\n log_perps = math_ops.add_n(log_perp_list)\n if average_across_timesteps:\n total_size = math_ops.add_n(weights)\n total_size += 1e-12\n log_perps \/= total_size\n return log_perps","code_tokens":"","url":128062} +{"project_name":"replit-archive\/empythoned","file_name":"saxutils.py","full_name":"prepare_input_source","func_name":"prepare_input_source","docstring":"This function takes an InputSource and an optional base URL and returns a fully resolved InputSource object ready for reading.","docstring_tokens":"","code":"def prepare_input_source(source, base=''):\n \"\"\"This function takes an InputSource and an optional base URL and\n returns a fully resolved InputSource object ready for reading.\"\"\"\n if type(source) in _StringTypes:\n source = xmlreader.InputSource(source)\n elif hasattr(source, 'read'):\n f = source\n source = xmlreader.InputSource()\n source.setByteStream(f)\n if hasattr(f, 'name'):\n source.setSystemId(f.name)\n if source.getByteStream() is None:\n sysid = source.getSystemId()\n basehead = os.path.dirname(os.path.normpath(base))\n sysidfilename = os.path.join(basehead, sysid)\n if os.path.isfile(sysidfilename):\n source.setSystemId(sysidfilename)\n f = open(sysidfilename, 'rb')\n else:\n source.setSystemId(urlparse.urljoin(base, sysid))\n f = urllib.urlopen(source.getSystemId())\n source.setByteStream(f)\n return source","code_tokens":"","url":177071} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"inputtransformer2.py","full_name":"leading_empty_lines","func_name":"leading_empty_lines","docstring":"Remove leading empty lines If the leading lines are empty or contain only whitespace, they will be removed.","docstring_tokens":"","code":"def leading_empty_lines(lines):\n \"\"\"Remove leading empty lines\n\n If the leading lines are empty or contain only whitespace, they will be\n removed.\n \"\"\"\n if not lines:\n return lines\n for (i, line) in enumerate(lines):\n if line and (not line.isspace()):\n return lines[i:]\n return lines","code_tokens":"","url":448168} +{"project_name":"kornia\/kornia","file_name":"lightglue.py","full_name":"sigmoid_log_double_softmax","func_name":"sigmoid_log_double_softmax","docstring":"Create the log assignment matrix from logits and similarity.","docstring_tokens":"","code":"def sigmoid_log_double_softmax(sim: Tensor, z0: Tensor, z1: Tensor) -> Tensor:\n \"\"\"Create the log assignment matrix from logits and similarity.\"\"\"\n (b, m, n) = sim.shape\n certainties = F.logsigmoid(z0) + F.logsigmoid(z1).transpose(1, 2)\n scores0 = F.log_softmax(sim, 2)\n scores1 = F.log_softmax(sim.transpose(-1, -2).contiguous(), 2).transpose(-1, -2)\n scores = sim.new_full((b, m + 1, n + 1), 0)\n scores[:, :m, :n] = scores0 + scores1 + certainties\n scores[:, :-1, -1] = F.logsigmoid(-z0.squeeze(-1))\n scores[:, -1, :-1] = F.logsigmoid(-z1.squeeze(-1))\n return scores","code_tokens":"","url":621717} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"test_markdown.py","full_name":"TestMarkdown.test_markdown2html_math_mixed","func_name":"test_markdown2html_math_mixed","docstring":"ensure markdown between inline and inline-block math works and test multiple LaTeX markup syntaxes.","docstring_tokens":"","code":"def test_markdown2html_math_mixed(self):\n \"\"\"ensure markdown between inline and inline-block math works and\n test multiple LaTeX markup syntaxes.\n \"\"\"\n case = 'The entries of \\\\\\\\(C\\\\\\\\) are given by the exact formula:\\n$$\\nC_{ik} = \\\\sum_{j=1}^n A_{ij} B_{jk},\\n$$\\nbut you can _implement_ this computation in many ways.\\n$\\x07pprox 2mnp$ flops are needed for \\\\\\\\[ C_{ik} = \\\\sum_{j=1}^n A_{ij} B_{jk} \\\\\\\\].\\nAlso check empty math blocks work correctly:\\n$$$$\\n\\\\\\\\[\\\\\\\\]'\n output_check = case.replace('_implement_', 'implement<\/em>').replace('\\\\\\\\(', '$').replace('\\\\\\\\)', '$').replace('\\\\\\\\[', '$$').replace('\\\\\\\\]', '$$')\n self._try_markdown(markdown2html, case, output_check)","code_tokens":"","url":42753} +{"project_name":"alfredfrancis\/ai-chatbot-framework","file_name":"sklearn_intent_classifer.py","full_name":"SklearnIntentClassifier.process","func_name":"process","docstring":"Returns the most likely intent and its probability for the input text.","docstring_tokens":"","code":"def process(self, x, INTENT_RANKING_LENGTH=5):\n \"\"\"Returns the most likely intent and\n its probability for the input text.\"\"\"\n intent = {'name': None, 'confidence': 0.0}\n intent_ranking = []\n if self.model:\n (intents, probabilities) = self.predict_proba(x)\n intents = [self.model.classes_[intent] for intent in intents.flatten()]\n probabilities = probabilities.flatten()\n if len(intents) > 0 and len(probabilities) > 0:\n ranking = list(zip(list(intents), list(probabilities)))\n ranking = ranking[:INTENT_RANKING_LENGTH]\n intent = {'intent': intents[0], 'confidence': probabilities[0]}\n intent_ranking = [{'intent': intent_name, 'confidence': score} for (intent_name, score) in ranking]\n else:\n intent = {'name': None, 'confidence': 0.0}\n intent_ranking = []\n return (intent, intent_ranking)","code_tokens":"","url":24269} +{"project_name":"shellerbrand\/machine-learning-for-artistic-style","file_name":"image_utils.py","full_name":"load_evaluation_images","func_name":"load_evaluation_images","docstring":"Loads images for evaluation.","docstring_tokens":"","code":"def load_evaluation_images(image_size):\n \"\"\"Loads images for evaluation.\n\n Args:\n image_size: int. Image size.\n\n Returns:\n Tensor. A batch of evaluation images.\n\n Raises:\n IOError: If no evaluation images can be found.\n \"\"\"\n glob = os.path.join(tf.resource_loader.get_data_files_path(), _EVALUATION_IMAGES_GLOB)\n evaluation_images = tf.gfile.Glob(glob)\n if not evaluation_images:\n raise IOError('No evaluation images found')\n return tf.concat([load_image(path, image_size) for path in evaluation_images], 0)","code_tokens":"","url":620689} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"transformer_main.py","full_name":"get_global_step","func_name":"get_global_step","docstring":"Return estimator's last checkpoint.","docstring_tokens":"","code":"def get_global_step(estimator):\n \"\"\"Return estimator's last checkpoint.\"\"\"\n return int(estimator.latest_checkpoint().split('-')[-1])","code_tokens":"","url":748704} +{"project_name":"jboss-openshift\/application-templates","file_name":"gen_template_docs.py","full_name":"generate_readme","func_name":"generate_readme","docstring":"Generates a README page for the template documentation.","docstring_tokens":"","code":"def generate_readme():\n \"\"\"Generates a README page for the template documentation.\"\"\"\n with open('docs\/README.adoc', 'w') as fh:\n fh.write(autogen_warning)\n fh.write(open('.\/README.adoc.in').read())\n for directory in sorted(template_dirs):\n if not os.path.isdir(directory):\n continue\n fh.write('\\n== %s\\n\\n' % fullname.get(directory, directory))\n for template in [os.path.splitext(x)[0] for x in sorted(os.listdir(directory))]:\n if 'image-stream' not in template:\n fh.write('* link:.\/%s\/%s.adoc[%s]\\n' % (directory, template, template))\n fh.write(open('.\/release-notes.adoc.in').read())","code_tokens":"","url":34033} +{"project_name":"deepmind\/dm_control","file_name":"__init__.py","full_name":"MJCFVariator.apply_variations","func_name":"apply_variations","docstring":"Applies variations in-place to the specified MJCF element.","docstring_tokens":"","code":"def apply_variations(self, random_state):\n \"\"\"Applies variations in-place to the specified MJCF element.\n\n Args:\n random_state: A `numpy.random.RandomState` instance.\n \"\"\"\n for (element, attribute_variations) in self._variations.items():\n new_values = {}\n for (attribute_name, variation_info) in attribute_variations.items():\n current_value = getattr(element, attribute_name)\n if variation_info.initial_value is None:\n variation_info.initial_value = copy.copy(current_value)\n new_values[attribute_name] = evaluate(variation_info.variation, variation_info.initial_value, current_value, random_state)\n element.set_attributes(**new_values)","code_tokens":"","url":164998} +{"project_name":"boat-group\/fancy-nlp","file_name":"spm_preprocessor.py","full_name":"SPMPreprocessor.get_word_ids","func_name":"get_word_ids","docstring":"Given a word-level tokenized text, return the corresponding word ids.","docstring_tokens":"","code":"def get_word_ids(self, word_cut: List[str]) -> List[int]:\n \"\"\"Given a word-level tokenized text, return the corresponding word ids.\n\n Args:\n word_cut: list of str, like ['\u00c3\u00a6\u00c2\\x88\u00c2\\x91', '\u00c3\u00a6\u00c2\\x98\u00c2\u00af'. '\u00c3\u00a4\u00c2\u00b8\u00c2\\xad\u00c3\u00a5\u00c2\\x9b\u00c2\u00bd\u00c3\u00a4\u00c2\u00ba\u00c2\u00ba']\n unk_idx: the index of words that do not appear in vocabulary, we usually set it to 1\n\n Returns: list of int, id sequence\n\n \"\"\"\n word_ids = []\n for word in word_cut:\n word_ids.append(self.word_vocab.get(word, self.word_vocab[self.unk_token]))\n return word_ids","code_tokens":"","url":559253} +{"project_name":"bhavyamerchant\/Hyperspec-WGAN","file_name":"nodes.py","full_name":"plot_pca","func_name":"plot_pca","docstring":"Plot the PCA results.","docstring_tokens":"","code":"def plot_pca(x: np.ndarray, y: np.ndarray, variance: np.ndarray, metadata: Dict[str, Any], kwargs: Dict[str, Any]) -> sns.FacetGrid:\n \"\"\"Plot the PCA results.\"\"\"\n with sns.plotting_context(context='paper'):\n graph = sns.relplot(x=x[:, 0], y=x[:, 1], hue=y, palette=metadata['palette'], **kwargs['relplot_kwargs'])\n _plot_colorbar(figure=graph.fig, palette=[*metadata['palette'].values()][1:], labels=[*metadata['labels'].values()][1:])\n graph.set(title=f\"{metadata['name']} PCA Projection\", xlabel=f'Principal Component 1 - {variance[0] * 100:.1f}% Explained Variance', xticks=[], ylabel=f'Principal Component 2 - {variance[1] * 100:.1f}% Explained Variance', yticks=[])\n return graph","code_tokens":"","url":571795} +{"project_name":"scikit-learn-contrib\/imbalanced-learn","file_name":"test_testing.py","full_name":"test_custom_nearest_neighbors","func_name":"test_custom_nearest_neighbors","docstring":"Check that our custom nearest neighbors can be used for our internal duck-typing.","docstring_tokens":"","code":"def test_custom_nearest_neighbors():\n \"\"\"Check that our custom nearest neighbors can be used for our internal\n duck-typing.\"\"\"\n neareat_neighbors = _CustomNearestNeighbors(n_neighbors=3)\n assert not isinstance(neareat_neighbors, KNeighborsMixin)\n assert hasattr(neareat_neighbors, 'kneighbors')\n assert hasattr(neareat_neighbors, 'kneighbors_graph')\n rng = np.random.RandomState(42)\n X = rng.randn(150, 3)\n y = rng.randint(0, 2, 150)\n neareat_neighbors.fit(X, y)\n (distances, indices) = neareat_neighbors.kneighbors(X)\n assert distances.shape == (150, 3)\n assert indices.shape == (150, 3)\n np.testing.assert_allclose(distances[:, 0], 0.0)\n np.testing.assert_allclose(indices[:, 0], np.arange(150))","code_tokens":"","url":610735} +{"project_name":"kornia\/kornia","file_name":"base.py","full_name":"RigidAffineAugmentationBase2D.identity_matrix","func_name":"identity_matrix","docstring":"Return 3x3 identity matrix.","docstring_tokens":"","code":"def identity_matrix(self, input: Tensor) -> Tensor:\n \"\"\"Return 3x3 identity matrix.\"\"\"\n return eye_like(3, input)","code_tokens":"","url":621520} +{"project_name":"jariasf\/GMVAE","file_name":"gmvae.py","full_name":"GMVAE.reconstruct_images","func_name":"reconstruct_images","docstring":"Generate reconstructions of 'images' from the model.","docstring_tokens":"","code":"def reconstruct_images(self, images):\n \"\"\"Generate reconstructions of 'images' from the model.\"\"\"\n q_y = self.encoder_y(images)\n y = q_y.sample(seed=self.random_seed)\n q_z = self.encoder_gmm(images, y)\n z = q_z.sample(seed=self.random_seed)\n p_x_given_z = self.decoder(z)\n recon = p_x_given_z.mean(name='reconstructions')\n return recon","code_tokens":"","url":578493} +{"project_name":"alibaba-mmai-research\/HiCo","file_name":"lr_policy.py","full_name":"lr_func_steps_with_relative_lrs","func_name":"lr_func_steps_with_relative_lrs","docstring":"Retrieve the learning rate to specified values at specified epoch with the steps with relative learning rate schedule.","docstring_tokens":"","code":"def lr_func_steps_with_relative_lrs(cfg, cur_epoch):\n \"\"\"\n Retrieve the learning rate to specified values at specified epoch with the\n steps with relative learning rate schedule.\n Args:\n cfg (Config): global config object. \n cur_epoch (float): the number of epoch of the current training stage.\n \"\"\"\n ind = get_step_index(cfg, cur_epoch)\n return cfg.OPTIMIZER.LRS[ind] * cfg.OPTIMIZER.BASE_LR","code_tokens":"","url":206098} +{"project_name":"bm777\/object_detection","file_name":"nn.py","full_name":"fully_connected_no_bias","func_name":"fully_connected_no_bias","docstring":"Apply a fully-connected layer (without bias).","docstring_tokens":"","code":"def fully_connected_no_bias(x, output_size, name, init_w='normal', stddev=0.001, group_id=0):\n \"\"\" Apply a fully-connected layer (without bias). \"\"\"\n x_shape = _get_shape(x)\n input_dim = x_shape[-1]\n with tf.variable_scope(name) as scope:\n w = weight('weights', [input_dim, output_size], init=init_w, stddev=stddev, group_id=group_id)\n z = tf.matmul(x, w)\n return z","code_tokens":"","url":793197} +{"project_name":"GeekLiB\/keras","file_name":"tensorflow_backend.py","full_name":"sparse_categorical_crossentropy","func_name":"sparse_categorical_crossentropy","docstring":"Categorical crossentropy between an output tensor and a target tensor, where the target is an integer tensor.","docstring_tokens":"","code":"def sparse_categorical_crossentropy(output, target, from_logits=False):\n \"\"\"Categorical crossentropy between an output tensor\n and a target tensor, where the target is an integer tensor.\n \"\"\"\n if not from_logits:\n epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)\n output = tf.clip_by_value(output, epsilon, 1 - epsilon)\n output = tf.log(output)\n output_shape = output.get_shape()\n res = tf.nn.sparse_softmax_cross_entropy_with_logits(tf.reshape(output, [-1, int(output_shape[-1])]), cast(flatten(target), 'int64'))\n if len(output_shape) == 3:\n return tf.reshape(res, [-1, int(output_shape[-2])])\n else:\n return res","code_tokens":"","url":247816} +{"project_name":"rlworkgroup\/garage","file_name":"_functions.py","full_name":"pad_tensor","func_name":"pad_tensor","docstring":"Pad tensors with zeros.","docstring_tokens":"","code":"def pad_tensor(x, max_len):\n \"\"\"Pad tensors with zeros.\n\n Args:\n x (numpy.ndarray): Tensors to be padded.\n max_len (int): Maximum length.\n\n Returns:\n numpy.ndarray: Padded tensor.\n \"\"\"\n return np.concatenate([x, np.tile(np.zeros_like(x[0]), (max_len - len(x),) + (1,) * np.ndim(x[0]))])","code_tokens":"","url":200501} +{"project_name":"seltzerfish\/guardyn","file_name":"gtest_shuffle_test.py","full_name":"CalculateTestLists","func_name":"CalculateTestLists","docstring":"Calculates the list of tests run under different flags.","docstring_tokens":"","code":"def CalculateTestLists():\n \"\"\"Calculates the list of tests run under different flags.\"\"\"\n if not ALL_TESTS:\n ALL_TESTS.extend(GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])\n if not ACTIVE_TESTS:\n ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])\n if not FILTERED_TESTS:\n FILTERED_TESTS.extend(GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])\n if not SHARDED_TESTS:\n SHARDED_TESTS.extend(GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, [])[0])\n if not SHUFFLED_ALL_TESTS:\n SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])\n if not SHUFFLED_ACTIVE_TESTS:\n SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [ShuffleFlag(), RandomSeedFlag(1)])[0])\n if not SHUFFLED_FILTERED_TESTS:\n SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations({}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])\n if not SHUFFLED_SHARDED_TESTS:\n SHUFFLED_SHARDED_TESTS.extend(GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, [ShuffleFlag(), RandomSeedFlag(1)])[0])","code_tokens":"","url":572304} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_series_to_panel_converters.py","full_name":"test_convert_df_collection_to_series","func_name":"test_convert_df_collection_to_series","docstring":"Test output format of collection-to-series for dataframe type input.","docstring_tokens":"","code":"def test_convert_df_collection_to_series():\n \"\"\"Test output format of collection-to-series for dataframe type input.\"\"\"\n (X_collection, _) = make_3d_test_data(n_cases=1, n_channels=2, n_labels=1)\n X_collection = from_3d_numpy_to_multi_index(X_collection)\n X_series = convert_Panel_to_Series(X_collection)\n assert isinstance(X_series, pd.DataFrame)\n assert len(X_series) == len(X_collection)\n assert (X_series.values == X_collection.values).all()","code_tokens":"","url":399439} +{"project_name":"201608040228\/-Natural-Language-Processing","file_name":"dureader_eval.py","full_name":"normalize","func_name":"normalize","docstring":"Normalize strings to space joined chars.","docstring_tokens":"","code":"def normalize(s):\n \"\"\"\n Normalize strings to space joined chars.\n\n Args:\n s: a list of strings.\n\n Returns:\n A list of normalized strings.\n \"\"\"\n if not s:\n return s\n normalized = []\n for ss in s:\n tokens = [c for c in list(ss) if len(c.strip()) != 0]\n normalized.append(' '.join(tokens))\n return normalized","code_tokens":"","url":375184} +{"project_name":"ludwig-ai\/ludwig","file_name":"checks.py","full_name":"check_tagger_decoder_requirements","func_name":"check_tagger_decoder_requirements","docstring":"Checks that the tagger decoder has at least one sequence, text or timeseries input feature where the encoder's reduce_output will produce a 3D shaped output from the combiner.","docstring_tokens":"","code":"@register_config_check\ndef check_tagger_decoder_requirements(config: 'ModelConfig') -> None:\n \"\"\"Checks that the tagger decoder has at least one sequence, text or timeseries input feature where the\n encoder's reduce_output will produce a 3D shaped output from the combiner.\"\"\"\n output_feature_with_tagger_decoder = False\n for output_feature in config.output_features:\n if output_feature.type in {TEXT, SEQUENCE} and output_feature.decoder.type == 'tagger':\n output_feature_with_tagger_decoder = True\n if not output_feature_with_tagger_decoder:\n return\n has_sequence_feature = False\n for input_feature in config.input_features:\n if input_feature.type in {SEQUENCE, TEXT, TIMESERIES}:\n has_sequence_feature = True\n if input_feature.encoder.reduce_output is None:\n return\n if not has_sequence_feature:\n raise ConfigValidationError('Tagger decoder requires at least one text, sequence or timeseries input feature.')\n else:\n raise ConfigValidationError('Tagger decoder requires at least one of the text, sequence or timeseries input feature encoders to have `reduce_output` set to `None`.')","code_tokens":"","url":616585} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_naive.py","full_name":"test_strategy_last_seasonal","func_name":"test_strategy_last_seasonal","docstring":"Test last strategy on seasonal data.","docstring_tokens":"","code":"@pytest.mark.parametrize('fh', TEST_OOS_FHS)\n@pytest.mark.parametrize('sp', TEST_SPS)\ndef test_strategy_last_seasonal(fh, sp):\n \"\"\"Test last strategy on seasonal data.\"\"\"\n f = NaiveForecaster(strategy='last', sp=sp)\n f.fit(y_train)\n y_pred = f.predict(fh)\n cutoff = get_cutoff(y_train, return_index=True)\n _assert_correct_pred_time_index(y_pred.index, cutoff, fh)\n fh = check_fh(fh)\n reps = int(np.ceil(max(fh) \/ sp))\n expected = np.tile(y_train.iloc[-sp:], reps=reps)[fh - 1]\n np.testing.assert_array_equal(y_pred, expected)","code_tokens":"","url":399730} +{"project_name":"lebrice\/Sequoia","file_name":"procgen_example.py","full_name":"ProcGenConfig.make_env","func_name":"make_env","docstring":"Creates the environment using these options.","docstring_tokens":"","code":"def make_env(self) -> gym.Env:\n \"\"\"Creates the environment using these options.\"\"\"\n env_id = f'procgen:procgen-{self.env_name}'\n procgen_env = gym.make(id=env_id, num_levels=self.num_levels, start_level=self.start_level, paint_vel_info=self.paint_vel_info, use_generated_assets=self.use_generated_assets, debug=self.debug, center_agent=self.center_agent, use_sequential_levels=self.use_sequential_levels, distribution_mode=self.distribution_mode, use_backgrounds=self.use_backgrounds, restrict_themes=self.restrict_themes, use_monochrome_assets=self.use_monochrome_assets)\n wrapped_env = SequoiaProcGenAdapterWrapper(env=procgen_env)\n return wrapped_env","code_tokens":"","url":343975} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"waveform_generator.py","full_name":"WaveformGenerator.generate_and_save_waveforms","func_name":"generate_and_save_waveforms","docstring":"Generate and save all specified waveforms.","docstring_tokens":"","code":"def generate_and_save_waveforms(self):\n \"\"\"\n Generate and save all specified waveforms.\n \"\"\"\n n_samples = len(self.config['injections'])\n duration = self.config['meta']['duration']\n sample_rate = self.config['meta']['sample_rate']\n failed = []\n print('Generate the waveforms...', end=' ')\n if duration > 0:\n N = int(duration * sample_rate)\n waveforms = np.zeros((n_samples, N))\n for (i, conf) in enumerate(tqdm(self.config['injections'])):\n x = np.zeros(N)\n try:\n (hp, cp) = tuple(map(np.array, get_td_waveform(**conf)))\n inj_time = conf['injection_time']\n (Iembed, Isignal) = self._get_embedding_indices(hp, inj_time, N)\n x[Iembed] += hp[Isignal]\n except Exception as e:\n failed.append(i)\n err = type(e).__name__\n print('Failure {}\\n during waveform {}: {}'.format(err, i, conf))\n waveforms[i, :] = x\n else:\n waveforms_raw = []\n for (i, conf) in enumerate(tqdm(self.config['injections'])):\n try:\n (hp, cp) = tuple(map(np.array, get_td_waveform(**conf)))\n waveforms_raw.append(hp)\n inj_time = conf['injection_time']\n except Exception as e:\n waveforms_raw.append(np.zeros(1))\n failed.append(i)\n err = type(e).__name__\n print('Failure {}\\n during waveform {}: {}'.format(err, i, conf))\n N = max(map(len, waveforms_raw))\n waveforms = np.zeros((n_samples, N))\n for (i, x) in enumerate(waveforms_raw):\n waveforms[i, :len(x)] = x\n inj_time = np.argmax(x) \/ float(N)\n self.config['injections'][i]['injection_time'] = inj_time\n print('DONE')\n print('Save everything to file...', end=' ')\n with h5py.File(self.output_file, 'w') as f:\n f['waveforms'] = waveforms\n f['config'] = np.string_(json.dumps(self.config))\n f['failed'] = failed\n print('DONE')","code_tokens":"","url":12386} +{"project_name":"RasaHQ\/rasa","file_name":"features.py","full_name":"Features.combine_with_features","func_name":"combine_with_features","docstring":"Combine the incoming features with this instance's features.","docstring_tokens":"","code":"def combine_with_features(self, additional_features: Optional[Features]) -> None:\n \"\"\"Combine the incoming features with this instance's features.\n\n Args:\n additional_features: additional features to add\n\n Returns:\n Combined features.\n \"\"\"\n if additional_features is None:\n return\n if self.is_dense() and additional_features.is_dense():\n self._combine_dense_features(additional_features)\n elif self.is_sparse() and additional_features.is_sparse():\n self._combine_sparse_features(additional_features)\n else:\n raise ValueError('Cannot combine sparse and dense features.')","code_tokens":"","url":837671} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"render_spec_with_graphviz.py","full_name":"master_spec_graph","func_name":"master_spec_graph","docstring":"Constructs a master spec graph.","docstring_tokens":"","code":"def master_spec_graph(master_spec):\n \"\"\"Constructs a master spec graph.\n\n Args:\n master_spec: MasterSpec proto.\n\n Raises:\n TypeError, if master_spec is not the right type. N.B. that this may be\n raised if you import proto classes in non-standard ways (e.g. dynamically).\n\n Returns:\n SVG graph contents as a string.\n \"\"\"\n if not isinstance(master_spec, spec_pb2.MasterSpec):\n raise TypeError('master_spec_graph() expects a MasterSpec input.')\n graph = pygraphviz.AGraph(directed=True)\n graph.node_attr.update(shape='box', style='filled', fillcolor='white', fontname='roboto, helvetica, arial', fontsize=11)\n graph.edge_attr.update(fontname='roboto, helvetica, arial', fontsize=11)\n for component in master_spec.component:\n graph.add_node(component.name, label=_component_contents(component))\n for component in master_spec.component:\n for linked_feature in component.linked_feature:\n graph.add_edge(linked_feature.source_component, component.name, label=_linked_feature_label(linked_feature))\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n return graph.draw(format='svg', prog='dot')","code_tokens":"","url":28563} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"base_model.py","full_name":"Model.build_model","func_name":"build_model","docstring":"Build the model object.","docstring_tokens":"","code":"@abc.abstractmethod\ndef build_model(self, params, mode):\n \"\"\"Build the model object.\"\"\"\n pass","code_tokens":"","url":973504} +{"project_name":"mariacer\/cl_in_rnns","file_name":"self_attention_layer.py","full_name":"SelfAttnLayerV2.weight_shapes","func_name":"weight_shapes","docstring":"Getter for read-only attribute weight_shapes.","docstring_tokens":"","code":"@property\ndef weight_shapes(self):\n \"\"\"Getter for read-only attribute weight_shapes.\"\"\"\n return self._weight_shapes","code_tokens":"","url":123097} +{"project_name":"nasimrahaman\/antipasti-tf","file_name":"core.py","full_name":"getfw","func_name":"getfw","docstring":"Get framework or a submodule in the framework.","docstring_tokens":"","code":"def getfw(submodule=None):\n \"\"\"Get framework or a submodule in the framework.\"\"\"\n if submodule is None:\n return tf\n else:\n assert isinstance(submodule, str), 'Submodule name must be a string.'\n return getattr(tf, submodule)","code_tokens":"","url":33457} +{"project_name":"YannDubs\/Invariant-Self-Supervised-Learning","file_name":"img.py","full_name":"ISSLImgDataset.get_base_transform","func_name":"get_base_transform","docstring":"Return the base transform, ie train or test.","docstring_tokens":"","code":"def get_base_transform(self) -> Callable[..., Any]:\n \"\"\"Return the base transform, ie train or test.\"\"\"\n shape = self.shapes['input']\n trnsfs = []\n if self.base_resize == 'resize':\n trnsfs += [Resize((shape[1], shape[2]))]\n elif self.base_resize is None:\n pass\n else:\n raise ValueError(f'Unknown base_resize={self.base_resize}')\n trnsfs += [ToTensor()]\n if self.is_normalize and self.is_color:\n trnsfs += [Normalizer(self.normalization, is_raise=True)]\n return Compose(trnsfs)","code_tokens":"","url":245992} +{"project_name":"lalwanii26\/openscope-barcodingstim","file_name":"behavior.py","full_name":"BehaviorBase.add_encoder","func_name":"add_encoder","docstring":"Adds a behavior encoder.","docstring_tokens":"","code":"def add_encoder(self, encoder):\n \"\"\" Adds a behavior encoder.\n \"\"\"\n self.encoders.append(encoder)","code_tokens":"","url":757434} +{"project_name":"hamza-murad\/AALU","file_name":"discovery_v1.py","full_name":"SourceOptionsWebCrawl.from_dict","func_name":"from_dict","docstring":"Initialize a SourceOptionsWebCrawl object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl':\n \"\"\"Initialize a SourceOptionsWebCrawl object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['url', 'limit_to_starting_hosts', 'crawl_speed', 'allow_untrusted_certificate', 'maximum_hops', 'request_timeout', 'override_robots_txt', 'blacklist']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class SourceOptionsWebCrawl: ' + ', '.join(bad_keys))\n if 'url' in _dict:\n args['url'] = _dict.get('url')\n else:\n raise ValueError(\"Required property 'url' not present in SourceOptionsWebCrawl JSON\")\n if 'limit_to_starting_hosts' in _dict:\n args['limit_to_starting_hosts'] = _dict.get('limit_to_starting_hosts')\n if 'crawl_speed' in _dict:\n args['crawl_speed'] = _dict.get('crawl_speed')\n if 'allow_untrusted_certificate' in _dict:\n args['allow_untrusted_certificate'] = _dict.get('allow_untrusted_certificate')\n if 'maximum_hops' in _dict:\n args['maximum_hops'] = _dict.get('maximum_hops')\n if 'request_timeout' in _dict:\n args['request_timeout'] = _dict.get('request_timeout')\n if 'override_robots_txt' in _dict:\n args['override_robots_txt'] = _dict.get('override_robots_txt')\n if 'blacklist' in _dict:\n args['blacklist'] = _dict.get('blacklist')\n return cls(**args)","code_tokens":"","url":5676} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"series.py","full_name":"Series.dropna","func_name":"dropna","docstring":"Return Series without null values Returns ------- valid : Series inplace : boolean, default False Do operation in place.","docstring_tokens":"","code":"def dropna(self, axis=0, inplace=False, **kwargs):\n \"\"\"\n Return Series without null values\n\n Returns\n -------\n valid : Series\n inplace : boolean, default False\n Do operation in place.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n kwargs.pop('how', None)\n if kwargs:\n raise TypeError('dropna() got an unexpected keyword argument \"{0}\"'.format(list(kwargs.keys())[0]))\n axis = self._get_axis_number(axis or 0)\n if self._can_hold_na:\n result = remove_na_arraylike(self)\n if inplace:\n self._update_inplace(result)\n else:\n return result\n elif inplace:\n pass\n else:\n return self.copy()","code_tokens":"","url":981923} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"axis.py","full_name":"XAxis.get_text_heights","func_name":"get_text_heights","docstring":"Return how much space should be reserved for text above and below the Axes, as a pair of floats.","docstring_tokens":"","code":"@_api.deprecated('3.6')\ndef get_text_heights(self, renderer):\n \"\"\"\n Return how much space should be reserved for text above and below the\n Axes, as a pair of floats.\n \"\"\"\n (bbox, bbox2) = self.get_ticklabel_extents(renderer)\n pad_pixels = self.majorTicks[0].get_pad_pixels()\n above = 0.0\n if bbox2.height:\n above += bbox2.height + pad_pixels\n below = 0.0\n if bbox.height:\n below += bbox.height + pad_pixels\n if self.get_label_position() == 'top':\n above += self.label.get_window_extent(renderer).height + pad_pixels\n else:\n below += self.label.get_window_extent(renderer).height + pad_pixels\n return (above, below)","code_tokens":"","url":361668} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"credentials.py","full_name":"AnonymousCredentials.expired","func_name":"expired","docstring":"Returns `False`, anonymous credentials never expire.","docstring_tokens":"","code":"@property\ndef expired(self):\n \"\"\"Returns `False`, anonymous credentials never expire.\"\"\"\n return False","code_tokens":"","url":214537} +{"project_name":"bachiraoun\/fullrmc","file_name":"Engine.py","full_name":"Engine.numberOfAtoms","func_name":"numberOfAtoms","docstring":"Number of atoms in the pdb.","docstring_tokens":"","code":"@property\ndef numberOfAtoms(self):\n \"\"\" Number of atoms in the pdb.\"\"\"\n return self.__realCoordinates.shape[0]","code_tokens":"","url":213417} +{"project_name":"okfn-brasil\/serenata-de-amor","file_name":"fetch_receipts.py","full_name":"Receipt.path","func_name":"path","docstring":"Returns the absolute path to the receipt (the path to be used when saving the file).","docstring_tokens":"","code":"@property\ndef path(self):\n \"\"\"\n Returns the absolute path to the receipt (the path to be used when\n saving the file).\n \"\"\"\n return os.path.join(os.path.abspath(self.target), str(self.applicant_id), str(self.year), str(self.document_id) + '.pdf')","code_tokens":"","url":349802} +{"project_name":"rchurchley\/IMA-Deep-Learning","file_name":"flickr.py","full_name":"urls_tagged","func_name":"urls_tagged","docstring":"Return a generator over images with a given tag on Flickr.","docstring_tokens":"","code":"def urls_tagged(keywords, api_key):\n \"\"\"Return a generator over images with a given tag on Flickr.\n\n Args:\n keywords (str): A comma-separated list of Flickr tags.\n api_key (str): The path to a valid Flickr API key.\n\n Yields:\n Pairs photo_id, photo_url for each photo returned from the Flickr API.\n The photo_id is the unique ID assigned by Flickr to each photo, and\n the photo_url is the url to download the image file.\n\n \"\"\"\n flickr = session(api_key)\n url_template = 'https:\/\/farm{}.staticflickr.com\/{}\/{}_{}.jpg'\n for photo in flickr.walk(tag_mode='all', tags=keywords):\n photo_id = photo.get('id')\n secret = photo.get('secret')\n farm_id = photo.get('farm')\n server = photo.get('server')\n photo_url = url_template.format(farm_id, server, photo_id, secret)\n yield (photo_id, photo_url)","code_tokens":"","url":598845} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"figure.py","full_name":"Figure.get_facecolor","func_name":"get_facecolor","docstring":"Get the face color of the Figure rectangle.","docstring_tokens":"","code":"def get_facecolor(self):\n \"\"\"Get the face color of the Figure rectangle.\"\"\"\n return self.patch.get_facecolor()","code_tokens":"","url":500} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"space_utils.py","full_name":"iterate","func_name":"iterate","docstring":"Iterate over the elements of a (batched) space.","docstring_tokens":"","code":"@singledispatch\ndef iterate(space: Space[T_cov], items: Iterable[T_cov]) -> Iterator:\n \"\"\"Iterate over the elements of a (batched) space.\n\n Args:\n space: Observation space of a single environment in the vectorized environment.\n items: Samples to be concatenated.\n out: The output object. This object is a (possibly nested) numpy array.\n\n Returns:\n The output object. This object is a (possibly nested) numpy array.\n\n Raises:\n ValueError: Space is not an instance of :class:`gym.Space`\n\n Example:\n >>> from gymnasium.spaces import Box, Dict\n >>> import numpy as np\n >>> space = Dict({\n ... 'position': Box(low=0, high=1, shape=(2, 3), seed=42, dtype=np.float32),\n ... 'velocity': Box(low=0, high=1, shape=(2, 2), seed=42, dtype=np.float32)})\n >>> items = space.sample()\n >>> it = iterate(space, items)\n >>> next(it)\n OrderedDict([('position', array([0.77395606, 0.43887845, 0.85859793], dtype=float32)), ('velocity', array([0.77395606, 0.43887845], dtype=float32))])\n >>> next(it)\n OrderedDict([('position', array([0.697368 , 0.09417735, 0.97562236], dtype=float32)), ('velocity', array([0.85859793, 0.697368 ], dtype=float32))])\n >>> next(it)\n Traceback (most recent call last):\n ...\n StopIteration\n \"\"\"\n if isinstance(space, Space):\n raise CustomSpaceError(f\"Space of type `{type(space)}` doesn't have an registered `iterate` function. Register `{type(space)}` for `iterate` to support it.\")\n else:\n raise TypeError(f'The space provided to `iterate` is not a gymnasium Space instance, type: {type(space)}, {space}')","code_tokens":"","url":573144} +{"project_name":"LEAP-WS\/CG3","file_name":"coarsen.py","full_name":"jaccard_idx_preprocess","func_name":"jaccard_idx_preprocess","docstring":"Use hashmap to find out nodes with exactly same neighbors.","docstring_tokens":"","code":"def jaccard_idx_preprocess(graph, matched, groups):\n \"\"\"Use hashmap to find out nodes with exactly same neighbors.\"\"\"\n neighs2node = defaultdict(list)\n for i in range(graph.node_num):\n neighs = str(sorted(graph.get_neighs(i)))\n neighs2node[neighs].append(i)\n for key in neighs2node.keys():\n g = neighs2node[key]\n if len(g) > 1:\n for node in g:\n matched[node] = True\n groups.append(g)\n return","code_tokens":"","url":104271} +{"project_name":"facebookresearch\/CutLER","file_name":"build.py","full_name":"build_detection_train_loader","func_name":"build_detection_train_loader","docstring":"Build a dataloader for object detection with some default features.","docstring_tokens":"","code":"@configurable(from_config=_train_loader_from_config)\ndef build_detection_train_loader(dataset, *, mapper, sampler=None, total_batch_size, aspect_ratio_grouping=True, num_workers=0, collate_fn=None):\n \"\"\"\n Build a dataloader for object detection with some default features.\n\n Args:\n dataset (list or torch.utils.data.Dataset): a list of dataset dicts,\n or a pytorch dataset (either map-style or iterable). It can be obtained\n by using :func:`DatasetCatalog.get` or :func:`get_detection_dataset_dicts`.\n mapper (callable): a callable which takes a sample (dict) from dataset and\n returns the format to be consumed by the model.\n When using cfg, the default choice is ``DatasetMapper(cfg, is_train=True)``.\n sampler (torch.utils.data.sampler.Sampler or None): a sampler that produces\n indices to be applied on ``dataset``.\n If ``dataset`` is map-style, the default sampler is a :class:`TrainingSampler`,\n which coordinates an infinite random shuffle sequence across all workers.\n Sampler must be None if ``dataset`` is iterable.\n total_batch_size (int): total batch size across all workers.\n aspect_ratio_grouping (bool): whether to group images with similar\n aspect ratio for efficiency. When enabled, it requires each\n element in dataset be a dict with keys \"width\" and \"height\".\n num_workers (int): number of parallel data loading workers\n collate_fn: a function that determines how to do batching, same as the argument of\n `torch.utils.data.DataLoader`. Defaults to do no collation and return a list of\n data. No collation is OK for small batch size and simple data structures.\n If your batch size is large and each sample contains too many small tensors,\n it's more efficient to collate them in data loader.\n\n Returns:\n torch.utils.data.DataLoader:\n a dataloader. Each output from it is a ``list[mapped_element]`` of length\n ``total_batch_size \/ num_workers``, where ``mapped_element`` is produced\n by the ``mapper``.\n \"\"\"\n if isinstance(dataset, list):\n dataset = DatasetFromList(dataset, copy=False)\n if mapper is not None:\n dataset = MapDataset(dataset, mapper)\n if isinstance(dataset, torchdata.IterableDataset):\n assert sampler is None, 'sampler must be None if dataset is IterableDataset'\n else:\n if sampler is None:\n sampler = TrainingSampler(len(dataset))\n assert isinstance(sampler, torchdata.Sampler), f'Expect a Sampler but got {type(sampler)}'\n return build_batch_data_loader(dataset, sampler, total_batch_size, aspect_ratio_grouping=aspect_ratio_grouping, num_workers=num_workers, collate_fn=collate_fn)","code_tokens":"","url":509132} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"prediction_model.py","full_name":"cdna_transformation","func_name":"cdna_transformation","docstring":"Apply convolutional dynamic neural advection to previous image.","docstring_tokens":"","code":"def cdna_transformation(prev_image, cdna_input, num_masks, color_channels):\n \"\"\"Apply convolutional dynamic neural advection to previous image.\n\n Args:\n prev_image: previous image to be transformed.\n cdna_input: hidden lyaer to be used for computing CDNA kernels.\n num_masks: the number of masks and hence the number of CDNA transformations.\n color_channels: the number of color channels in the images.\n Returns:\n List of images transformed by the predicted CDNA kernels.\n \"\"\"\n batch_size = int(cdna_input.get_shape()[0])\n height = int(prev_image.get_shape()[1])\n width = int(prev_image.get_shape()[2])\n cdna_kerns = slim.layers.fully_connected(cdna_input, DNA_KERN_SIZE * DNA_KERN_SIZE * num_masks, scope='cdna_params', activation_fn=None)\n cdna_kerns = tf.reshape(cdna_kerns, [batch_size, DNA_KERN_SIZE, DNA_KERN_SIZE, 1, num_masks])\n cdna_kerns = tf.nn.relu(cdna_kerns - RELU_SHIFT) + RELU_SHIFT\n norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True)\n cdna_kerns \/= norm_factor\n cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4, 3])\n cdna_kerns = tf.reshape(cdna_kerns, [DNA_KERN_SIZE, DNA_KERN_SIZE, batch_size, num_masks])\n prev_image = tf.transpose(prev_image, [3, 1, 2, 0])\n transformed = tf.nn.depthwise_conv2d(prev_image, cdna_kerns, [1, 1, 1, 1], 'SAME')\n transformed = tf.reshape(transformed, [color_channels, height, width, batch_size, num_masks])\n transformed = tf.transpose(transformed, [3, 1, 2, 0, 4])\n transformed = tf.unstack(transformed, axis=-1)\n return transformed","code_tokens":"","url":29993} +{"project_name":"dibyaghosh\/gcsl","file_name":"dm_sim_scene.py","full_name":"DMSimScene.get_mjlib","func_name":"get_mjlib","docstring":"Returns an interface to the low-level MuJoCo API.","docstring_tokens":"","code":"def get_mjlib(self) -> Any:\n \"\"\"Returns an interface to the low-level MuJoCo API.\"\"\"\n return dm_mujoco.wrapper.mjbindings.mjlib","code_tokens":"","url":202010} +{"project_name":"apple\/ml-cvnets","file_name":"collate_functions.py","full_name":"default_collate_fn","func_name":"default_collate_fn","docstring":"Combines a list of dictionaries into a single dictionary by concatenating matching fields.","docstring_tokens":"","code":"@COLLATE_FN_REGISTRY.register(name='default_collate_fn')\ndef default_collate_fn(batch: List[Mapping[str, Tensor]], opts: argparse.Namespace) -> Mapping[str, Tensor]:\n \"\"\"Combines a list of dictionaries into a single dictionary by concatenating matching fields.\n\n Args:\n batch: A list of dictionaries\n opts: An argparse.Namespace instance.\n\n Returns:\n A dictionary with the same keys as batch[0].\n \"\"\"\n batch_size = len(batch)\n keys = list(batch[0].keys())\n new_batch = {k: [] for k in keys}\n for b in range(batch_size):\n for k in keys:\n new_batch[k].append(batch[b][k])\n for k in keys:\n batch_elements = new_batch.pop(k)\n if isinstance(batch_elements[0], (int, float)):\n batch_elements = torch.as_tensor(batch_elements)\n else:\n try:\n batch_elements = torch.stack(batch_elements, dim=0).contiguous()\n except Exception as e:\n logger.error('Unable to stack the tensors. Error: {}'.format(e))\n new_batch[k] = batch_elements\n return new_batch","code_tokens":"","url":671392} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"datastructures.py","full_name":"MIMEAccept.accept_html","func_name":"accept_html","docstring":"True if this object accepts HTML.","docstring_tokens":"","code":"@property\ndef accept_html(self):\n \"\"\"True if this object accepts HTML.\"\"\"\n return 'text\/html' in self or 'application\/xhtml+xml' in self or self.accept_xhtml","code_tokens":"","url":132028} +{"project_name":"alegonz\/kdsb17","file_name":"model.py","full_name":"NakedModel.summary","func_name":"summary","docstring":"Print summary of model to stdout.","docstring_tokens":"","code":"def summary(self):\n \"\"\"Print summary of model to stdout.\n \"\"\"\n self._model.summary()","code_tokens":"","url":594930} +{"project_name":"huawei-noah\/xingtian","file_name":"record.py","full_name":"ReportRecord.performance","func_name":"performance","docstring":"Set performance and parse value into dict.","docstring_tokens":"","code":"@performance.setter\ndef performance(self, value):\n \"\"\"Set performance and parse value into dict.\"\"\"\n if isinstance(value, str):\n value = ast.literal_eval(value)\n self._performance = value","code_tokens":"","url":968342} +{"project_name":"chenbinghui1\/DSL","file_name":"anchor_head.py","full_name":"AnchorHead.get_targets","func_name":"get_targets","docstring":"Compute regression and classification targets for anchors in multiple images.","docstring_tokens":"","code":"def get_targets(self, anchor_list, valid_flag_list, gt_bboxes_list, img_metas, gt_bboxes_ignore_list=None, gt_labels_list=None, label_channels=1, unmap_outputs=True, return_sampling_results=False):\n \"\"\"Compute regression and classification targets for anchors in\n multiple images.\n\n Args:\n anchor_list (list[list[Tensor]]): Multi level anchors of each\n image. The outer list indicates images, and the inner list\n corresponds to feature levels of the image. Each element of\n the inner list is a tensor of shape (num_anchors, 4).\n valid_flag_list (list[list[Tensor]]): Multi level valid flags of\n each image. The outer list indicates images, and the inner list\n corresponds to feature levels of the image. Each element of\n the inner list is a tensor of shape (num_anchors, )\n gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image.\n img_metas (list[dict]): Meta info of each image.\n gt_bboxes_ignore_list (list[Tensor]): Ground truth bboxes to be\n ignored.\n gt_labels_list (list[Tensor]): Ground truth labels of each box.\n label_channels (int): Channel of label.\n unmap_outputs (bool): Whether to map outputs back to the original\n set of anchors.\n\n Returns:\n tuple: Usually returns a tuple containing learning targets.\n\n - labels_list (list[Tensor]): Labels of each level.\n - label_weights_list (list[Tensor]): Label weights of each level.\n - bbox_targets_list (list[Tensor]): BBox targets of each level.\n - bbox_weights_list (list[Tensor]): BBox weights of each level.\n - num_total_pos (int): Number of positive samples in all images.\n - num_total_neg (int): Number of negative samples in all images.\n additional_returns: This function enables user-defined returns from\n `self._get_targets_single`. These returns are currently refined\n to properties at each feature map (i.e. having HxW dimension).\n The results will be concatenated after the end\n \"\"\"\n num_imgs = len(img_metas)\n assert len(anchor_list) == len(valid_flag_list) == num_imgs\n num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]\n concat_anchor_list = []\n concat_valid_flag_list = []\n for i in range(num_imgs):\n assert len(anchor_list[i]) == len(valid_flag_list[i])\n concat_anchor_list.append(torch.cat(anchor_list[i]))\n concat_valid_flag_list.append(torch.cat(valid_flag_list[i]))\n if gt_bboxes_ignore_list is None:\n gt_bboxes_ignore_list = [None for _ in range(num_imgs)]\n if gt_labels_list is None:\n gt_labels_list = [None for _ in range(num_imgs)]\n results = multi_apply(self._get_targets_single, concat_anchor_list, concat_valid_flag_list, gt_bboxes_list, gt_bboxes_ignore_list, gt_labels_list, img_metas, label_channels=label_channels, unmap_outputs=unmap_outputs)\n (all_labels, all_label_weights, all_bbox_targets, all_bbox_weights, pos_inds_list, neg_inds_list, sampling_results_list) = results[:7]\n rest_results = list(results[7:])\n if any([labels is None for labels in all_labels]):\n return None\n num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])\n num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])\n labels_list = images_to_levels(all_labels, num_level_anchors)\n label_weights_list = images_to_levels(all_label_weights, num_level_anchors)\n bbox_targets_list = images_to_levels(all_bbox_targets, num_level_anchors)\n bbox_weights_list = images_to_levels(all_bbox_weights, num_level_anchors)\n res = (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg)\n if return_sampling_results:\n res = res + (sampling_results_list,)\n for (i, r) in enumerate(rest_results):\n rest_results[i] = images_to_levels(r, num_level_anchors)\n return res + tuple(rest_results)","code_tokens":"","url":167651} +{"project_name":"lalwanii26\/openscope-barcodingstim","file_name":"sweepstim.py","full_name":"Stimulus.set_fps","func_name":"set_fps","docstring":"Have to rebuild the frame list every time we change fps.","docstring_tokens":"","code":"def set_fps(self, fps):\n \"\"\"\n Have to rebuild the frame list every time we change fps.\n \"\"\"\n self.fps = fps\n self._build_frame_list()","code_tokens":"","url":757523} +{"project_name":"Katja-M\/Python_NaturalLanguageProcessing","file_name":"prepare.py","full_name":"unpack_file_url","func_name":"unpack_file_url","docstring":"Unpack link into location.","docstring_tokens":"","code":"def unpack_file_url(link, location, download_dir=None, hashes=None):\n \"\"\"Unpack link into location.\n \"\"\"\n link_path = link.file_path\n if link.is_existing_dir():\n if os.path.isdir(location):\n rmtree(location)\n _copy_source_tree(link_path, location)\n return None\n already_downloaded_path = None\n if download_dir:\n already_downloaded_path = _check_download_dir(link, download_dir, hashes)\n if already_downloaded_path:\n from_path = already_downloaded_path\n else:\n from_path = link_path\n if hashes:\n hashes.check_against_path(from_path)\n content_type = mimetypes.guess_type(from_path)[0]\n unpack_file(from_path, location, content_type)\n return from_path","code_tokens":"","url":868133} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"named_commands.py","full_name":"capitalize_word","func_name":"capitalize_word","docstring":"Capitalize the current (or following) word.","docstring_tokens":"","code":"@register('capitalize-word')\ndef capitalize_word(event):\n \"\"\"\n Capitalize the current (or following) word.\n \"\"\"\n buff = event.current_buffer\n for i in range(event.arg):\n pos = buff.document.find_next_word_ending()\n words = buff.document.text_after_cursor[:pos]\n buff.insert_text(words.title(), overwrite=True)","code_tokens":"","url":45266} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"conf.py","full_name":"replace_in_file","func_name":"replace_in_file","docstring":"Replace all occurences of the original_str with replace_str in the file provided.","docstring_tokens":"","code":"def replace_in_file(filepath: Path, original_str: str, replace_str: str) -> None:\n \"\"\"\n Replace all occurences of the original_str with replace_str in the file provided.\n \"\"\"\n text = filepath.read_text()\n text = text.replace(original_str, replace_str)\n filepath.write_text(text)","code_tokens":"","url":612684} +{"project_name":"ZumoLabs\/zpy","file_name":"material.py","full_name":"save_mat_props","func_name":"save_mat_props","docstring":"Save a pose (rot and pos) to dict.","docstring_tokens":"","code":"def save_mat_props(mat: Union[bpy.types.Material, str]) -> None:\n \"\"\"Save a pose (rot and pos) to dict.\n\n Args:\n mat (Union[bpy.types.Material, str]): Material (or it's name)\n \"\"\"\n log.info(f'Saving material properties for {mat.name}')\n _SAVED_MATERIALS[mat.name] = get_mat_props(mat)","code_tokens":"","url":972056} +{"project_name":"iffiX\/machin","file_name":"assigner.py","full_name":"ModelSizeEstimator.estimate_size","func_name":"estimate_size","docstring":"Estimate model size in memory in megabytes.","docstring_tokens":"","code":"def estimate_size(self):\n \"\"\"Estimate model size in memory in megabytes.\"\"\"\n total = self.get_parameter_sizes() + self.get_buffer_sizes()\n return total * self.size_multiplier","code_tokens":"","url":620354} +{"project_name":"tryolabs\/luminoth","file_name":"image_test.py","full_name":"ImageTest.testRandomResizeImageBboxes","func_name":"testRandomResizeImageBboxes","docstring":"Tests the integrity of the return values of random_resize This tests the case when bboxes is not None.","docstring_tokens":"","code":"def testRandomResizeImageBboxes(self):\n \"\"\"Tests the integrity of the return values of random_resize\n\n This tests the case when bboxes is not None.\n \"\"\"\n im_shape = (600, 800, 3)\n config = self._random_resize_config\n total_boxes = 5\n label = 3\n (image, bboxes) = self._get_image_with_boxes(im_shape, total_boxes)\n bboxes_w_label = tf.concat([bboxes, tf.fill((bboxes.shape[0], 1), label)], axis=1)\n (ret_image, ret_bboxes) = self._random_resize(image, config, bboxes_w_label)\n self.assertEqual(ret_bboxes.shape[0], total_boxes)\n self.assertTrue(np.all(np.asarray(ret_image.shape[:2]) >= config.min_size))\n self.assertTrue(np.all(np.asarray(ret_image.shape[:2]) <= config.max_size))","code_tokens":"","url":617565} +{"project_name":"yhyu13\/AlphaGOZero-python-tensorflow","file_name":"sgf_wrapper.py","full_name":"handle_node","func_name":"handle_node","docstring":"A node can either add B+W stones, play as B, or play as W.","docstring_tokens":"","code":"def handle_node(pos, node):\n \"\"\"A node can either add B+W stones, play as B, or play as W.\"\"\"\n props = node.properties\n black_stones_added = [pc(coords) for coords in props.get('AB', [])]\n white_stones_added = [pc(coords) for coords in props.get('AW', [])]\n if black_stones_added or white_stones_added:\n return add_stones(pos, black_stones_added, white_stones_added)\n elif 'B' in props:\n black_move = pc(props.get('B', [''])[0])\n return pos.play_move(black_move, color=go.BLACK)\n elif 'W' in props:\n white_move = pc(props.get('W', [''])[0])\n return pos.play_move(white_move, color=go.WHITE)\n else:\n return pos","code_tokens":"","url":33008} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"session.py","full_name":"Session.package_model_for_edge","func_name":"package_model_for_edge","docstring":"Create an Amazon SageMaker Edge packaging job.","docstring_tokens":"","code":"def package_model_for_edge(self, output_model_config, role=None, job_name=None, compilation_job_name=None, model_name=None, model_version=None, resource_key=None, tags=None):\n \"\"\"Create an Amazon SageMaker Edge packaging job.\n\n Args:\n output_model_config (dict): Identifies the Amazon S3 location where you want Amazon\n SageMaker Edge to save the results of edge packaging job\n role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker Edge\n edge packaging jobs use this role to access model artifacts. You must grant\n sufficient permissions to this role.\n job_name (str): Name of the edge packaging job being created.\n compilation_job_name (str): Name of the compilation job being created.\n resource_key (str): KMS key to encrypt the disk used to package the job\n tags (list[dict]): List of tags for labeling a compile model job. For more, see\n https:\/\/docs.aws.amazon.com\/sagemaker\/latest\/dg\/API_Tag.html.\n \"\"\"\n role = resolve_value_from_config(role, EDGE_PACKAGING_ROLE_ARN_PATH, sagemaker_session=self)\n inferred_output_model_config = update_nested_dictionary_with_values_from_config(output_model_config, EDGE_PACKAGING_OUTPUT_CONFIG_PATH, sagemaker_session=self)\n edge_packaging_job_request = {'OutputConfig': inferred_output_model_config, 'RoleArn': role, 'ModelName': model_name, 'ModelVersion': model_version, 'EdgePackagingJobName': job_name, 'CompilationJobName': compilation_job_name}\n resource_key = resolve_value_from_config(resource_key, EDGE_PACKAGING_RESOURCE_KEY_PATH, sagemaker_session=self)\n tags = _append_project_tags(tags)\n tags = self._append_sagemaker_config_tags(tags, '{}.{}.{}'.format(SAGEMAKER, EDGE_PACKAGING_JOB, TAGS))\n if tags is not None:\n edge_packaging_job_request['Tags'] = tags\n if resource_key is not None:\n edge_packaging_job_request['ResourceKey'] = resource_key\n LOGGER.info('Creating edge-packaging-job with name: %s', job_name)\n self.sagemaker_client.create_edge_packaging_job(**edge_packaging_job_request)","code_tokens":"","url":829617} +{"project_name":"google\/deepvariant","file_name":"data_providers.py","full_name":"get_input_fn_from_dataset","func_name":"get_input_fn_from_dataset","docstring":"Creates an input_fn from the dataset config file.","docstring_tokens":"","code":"def get_input_fn_from_dataset(dataset_config_filename, mode, **kwargs):\n \"\"\"Creates an input_fn from the dataset config file.\n\n Args:\n dataset_config_filename: str. Path to the dataset config pbtxt file.\n mode: one of tf.estimator.ModeKeys.{TRAIN,EVAL,PREDICT}\n **kwargs: Additional keyword arguments for DeepVariantInput.\n\n Returns:\n An input_fn from the specified split in the dataset_config file.\n\n Raises:\n ValueError: if the dataset config doesn't have the necessary information.\n \"\"\"\n dataset_config = read_dataset_config(dataset_config_filename)\n return get_input_fn_from_filespec(input_file_spec=dataset_config.tfrecord_path, mode=mode, num_examples=dataset_config.num_examples, name=dataset_config.name, **kwargs)","code_tokens":"","url":540254} +{"project_name":"chenbinghui1\/DSL","file_name":"detectors_resnet.py","full_name":"DetectoRS_ResNet.make_res_layer","func_name":"make_res_layer","docstring":"Pack all blocks in a stage into a ``ResLayer`` for DetectoRS.","docstring_tokens":"","code":"def make_res_layer(self, **kwargs):\n \"\"\"Pack all blocks in a stage into a ``ResLayer`` for DetectoRS.\"\"\"\n return ResLayer(**kwargs)","code_tokens":"","url":167613} +{"project_name":"LucasAlegre\/sumo-rl","file_name":"ql_agent.py","full_name":"QLAgent.learn","func_name":"learn","docstring":"Update Q-table with new experience.","docstring_tokens":"","code":"def learn(self, next_state, reward, done=False):\n \"\"\"Update Q-table with new experience.\"\"\"\n if next_state not in self.q_table:\n self.q_table[next_state] = [0 for _ in range(self.action_space.n)]\n s = self.state\n s1 = next_state\n a = self.action\n self.q_table[s][a] = self.q_table[s][a] + self.alpha * (reward + self.gamma * max(self.q_table[s1]) - self.q_table[s][a])\n self.state = s1\n self.acc_reward += reward","code_tokens":"","url":910442} +{"project_name":"microsoft\/nni","file_name":"autoformer.py","full_name":"AutoFormer.preset","func_name":"preset","docstring":"Get the model space config proposed in paper.","docstring_tokens":"","code":"@classmethod\ndef preset(cls, name: str):\n \"\"\"Get the model space config proposed in paper.\"\"\"\n name = name.lower()\n assert name in ['tiny', 'small', 'base']\n if name == 'tiny':\n init_kwargs = {'search_embed_dim': (192, 216, 240), 'search_mlp_ratio': (3.0, 3.5, 4.0), 'search_num_heads': (3, 4), 'search_depth': (12, 13, 14)}\n elif name == 'small':\n init_kwargs = {'search_embed_dim': (320, 384, 448), 'search_mlp_ratio': (3.0, 3.5, 4.0), 'search_num_heads': (5, 6, 7), 'search_depth': (12, 13, 14)}\n elif name == 'base':\n init_kwargs = {'search_embed_dim': (528, 576, 624), 'search_mlp_ratio': (3.0, 3.5, 4.0), 'search_num_heads': (8, 9, 10), 'search_depth': (14, 15, 16)}\n else:\n raise ValueError(f'Unsupported architecture with name: {name}')\n return init_kwargs","code_tokens":"","url":728744} +{"project_name":"Megvii-BaseDetection\/cvpods","file_name":"file_io.py","full_name":"PathManager.ls","func_name":"ls","docstring":"List the contents of the directory at the provided URI.","docstring_tokens":"","code":"@staticmethod\n@deprecated_func('use megfile.smart_listdir instead')\ndef ls(path: str):\n \"\"\"\n List the contents of the directory at the provided URI.\n\n Args:\n path (str): A URI supported by this PathHandler\n\n Returns:\n List[str]: list of contents in given path\n \"\"\"\n return megfile.smart_listdir(path)","code_tokens":"","url":523212} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"apis.py","full_name":"MMdeployExporter.extract_partition","func_name":"extract_partition","docstring":"Function for extracting partition.","docstring_tokens":"","code":"@staticmethod\ndef extract_partition(output_dir: str, input_data: Any, cfg: mmcv.Config, deploy_cfg: mmcv.Config, export_type: str, *, model_name: str='model'):\n \"\"\"Function for extracting partition.\"\"\"\n reset_mark_function_count()\n model_onnx = MMdeployExporter.torch2onnx(output_dir, input_data, cfg, deploy_cfg, model_name=model_name)\n partition_cfgs = get_partition_config(deploy_cfg)\n partition_cfgs = partition_cfgs.get('partition_cfg', None)\n partition_onnx = MMdeployExporter.partition_onnx(output_dir, model_onnx, partition_cfgs)\n if 'ONNX' not in export_type:\n deploy_cfg_ = deepcopy(deploy_cfg)\n update_deploy_cfg(partition_onnx[0], deploy_cfg_)\n MMdeployExporter.onnx2openvino(output_dir, partition_onnx[0], deploy_cfg_)\n deploy_cfg['partition_config']['apply_marks'] = False\n reset_mark_function_count()","code_tokens":"","url":917954} +{"project_name":"emirhanai\/My-Artificial-Intelligence-Project-Tic-Tac-Toe-that-I-developed-and-made-at-Harvard-University","file_name":"tictactoe.py","full_name":"exam","func_name":"exam","docstring":"Returns the board that exams from making move (i, j) on the board.","docstring_tokens":"","code":"def exam(board, breaks):\n \"\"\"\n Returns the board that exams from making move (i, j) on the board.\n \"\"\"\n new_board = deepcopy(board)\n if breakss(new_board) != None and breaks not in breakss(new_board):\n raise ValueError('breaks not possible')\n player_current = player(new_board)\n if player_current == X:\n new_board[breaks[0]][breaks[1]] = X\n else:\n new_board[breaks[0]][breaks[1]] = O\n return new_board","code_tokens":"","url":289014} +{"project_name":"tensorflow\/data-validation","file_name":"display_util.py","full_name":"get_skew_result_dataframe","func_name":"get_skew_result_dataframe","docstring":"Formats FeatureSkew results as a pandas dataframe.","docstring_tokens":"","code":"def get_skew_result_dataframe(skew_results: Iterable[feature_skew_results_pb2.FeatureSkew]) -> pd.DataFrame:\n \"\"\"Formats FeatureSkew results as a pandas dataframe.\"\"\"\n result = []\n for feature_skew in skew_results:\n result.append((feature_skew.feature_name, feature_skew.base_count, feature_skew.test_count, feature_skew.match_count, feature_skew.base_only, feature_skew.test_only, feature_skew.mismatch_count, feature_skew.diff_count))\n columns = ['feature_name', 'base_count', 'test_count', 'match_count', 'base_only', 'test_only', 'mismatch_count', 'diff_count']\n return pd.DataFrame(result, columns=columns).sort_values('feature_name').reset_index(drop=True)","code_tokens":"","url":497608} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"train_cifar.py","full_name":"CifarModel.build","func_name":"build","docstring":"Construct the cifar model.","docstring_tokens":"","code":"def build(self, mode):\n \"\"\"Construct the cifar model.\"\"\"\n assert mode in ['train', 'eval']\n self.mode = mode\n self._setup_misc(mode)\n self._setup_images_and_labels()\n self._build_graph(self.images, self.labels, mode)\n self.init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())","code_tokens":"","url":851440} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"cluster.py","full_name":"Cluster.ListDevices","func_name":"ListDevices","docstring":"Returns the list of available hardware devices.","docstring_tokens":"","code":"def ListDevices(self):\n \"\"\"Returns the list of available hardware devices.\"\"\"\n devices = []\n if self._tf_cluster is not None:\n ret_from_swig = tf_cluster.TF_ListDevices(self._tf_cluster)\n devices = []\n for raw_dev in ret_from_swig:\n devices.append(device_properties_pb2.NamedDevice.FromString(raw_dev))\n return devices","code_tokens":"","url":336646} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"versioncontrol.py","full_name":"VcsSupport.get_backend_for_dir","func_name":"get_backend_for_dir","docstring":"Return a VersionControl object if a repository of that type is found at the given directory.","docstring_tokens":"","code":"def get_backend_for_dir(self, location):\n \"\"\"\n Return a VersionControl object if a repository of that type is found\n at the given directory.\n \"\"\"\n vcs_backends = {}\n for vcs_backend in self._registry.values():\n repo_path = vcs_backend.get_repository_root(location)\n if not repo_path:\n continue\n logger.debug('Determine that %s uses VCS: %s', location, vcs_backend.name)\n vcs_backends[repo_path] = vcs_backend\n if not vcs_backends:\n return None\n inner_most_repo_path = max(vcs_backends, key=len)\n return vcs_backends[inner_most_repo_path]","code_tokens":"","url":98619} +{"project_name":"google\/deepvariant","file_name":"postprocess_variants_test.py","full_name":"PostprocessVariantsTest.test_triallelic_genotype_in_add_call_to_variant","func_name":"test_triallelic_genotype_in_add_call_to_variant","docstring":"Ensures the order of GLs are interpreted correctly for triallelics.","docstring_tokens":"","code":"@parameterized.parameters((0, [0, 0]), (1, [0, 1]), (2, [1, 1]), (3, [0, 2]), (4, [1, 2]), (5, [2, 2]))\ndef test_triallelic_genotype_in_add_call_to_variant(self, highest_prob_position, expected_best_genotype):\n \"\"\"Ensures the order of GLs are interpreted correctly for triallelics.\"\"\"\n raw_variant = _create_variant_with_alleles(ref='CACA', alts=['C', 'A'])\n probs = [0.001] * 6\n assert 0 <= highest_prob_position <= len(probs)\n probs[highest_prob_position] = 0.995\n variantcall_utils.set_ad(raw_variant.calls[0], [1, 1, 1])\n variant = postprocess_variants.add_call_to_variant(variant=raw_variant, predictions=probs, sample_name=_DEFAULT_SAMPLE_NAME)\n self.assertEqual(variant.calls[0].genotype, expected_best_genotype)","code_tokens":"","url":540415} +{"project_name":"apeterswu\/RL4NMT","file_name":"transformer_vae.py","full_name":"bit_to_int","func_name":"bit_to_int","docstring":"Turn x_bit representing numbers bitwise (lower-endian) to int tensor.","docstring_tokens":"","code":"def bit_to_int(x_bit, nbits):\n \"\"\"Turn x_bit representing numbers bitwise (lower-endian) to int tensor.\"\"\"\n x_l = tf.stop_gradient(tf.reshape(x_bit, [-1, nbits]))\n x_labels = []\n for i in range(nbits):\n x_labels.append(x_l[:, i] * 2 ** i)\n res = sum(x_labels)\n return tf.to_int32(tf.reshape(res, tf.shape(x_bit)[:-1]))","code_tokens":"","url":331207} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"analyzer_cli_test.py","full_name":"AnalyzerCLIControlDepTest.testListInputsNonRecursiveWithControls","func_name":"testListInputsNonRecursiveWithControls","docstring":"List inputs non-recursively, with control inputs.","docstring_tokens":"","code":"def testListInputsNonRecursiveWithControls(self):\n \"\"\"List inputs non-recursively, with control inputs.\"\"\"\n out = self._registry.dispatch_command('li', ['-t', 'control_deps\/ctrl_dep_z', '-c'])\n self.assertEqual(['Inputs to node \"control_deps\/ctrl_dep_z\" (Depth limit = 1, control inputs included):', '|- (1) [Mul] control_deps\/z', '| |- ...', '|- (1) (Ctrl) [Identity] control_deps\/ctrl_dep_y', '| |- ...', '|- (1) (Ctrl) [Variable] control_deps\/x', '', 'Legend:', ' (d): recursion depth = d.', ' (Ctrl): Control input.', ' [Op]: Input node has op type Op.'], out.lines)","code_tokens":"","url":182374} +{"project_name":"jonathanking\/sidechainnet","file_name":"SCNDataset.py","full_name":"SCNProtein.seq3","func_name":"seq3","docstring":"Return 3-letter amino acid sequence for the protein.","docstring_tokens":"","code":"@property\ndef seq3(self):\n \"\"\"Return 3-letter amino acid sequence for the protein.\"\"\"\n return ' '.join([ONE_TO_THREE_LETTER_MAP[c] for c in self.seq])","code_tokens":"","url":934006} +{"project_name":"MANGA-UOFA\/NAUS","file_name":"trainer.py","full_name":"Trainer.get_criterion","func_name":"get_criterion","docstring":"Get the (non-wrapped) criterion instance.","docstring_tokens":"","code":"def get_criterion(self):\n \"\"\"Get the (non-wrapped) criterion instance.\"\"\"\n return self._criterion","code_tokens":"","url":291230} +{"project_name":"PaccMann\/fdsa","file_name":"mapper.py","full_name":"MapperSetsAE.forward","func_name":"forward","docstring":"Computes cost matrix and performs a matching between inputs and outputs.","docstring_tokens":"","code":"def forward(self, inputs: torch.Tensor, stacked_outputs: torch.Tensor, member_probabilities: torch.Tensor) -> Tuple:\n \"\"\"Computes cost matrix and performs a matching between inputs and outputs.\n\n Args:\n inputs (torch.Tensor): Input tensor of shape\n [batch_size x sequence_length x input_size].\n stacked_outputs (torch.Tensor): Reconstructed elements from the\n decoder with shape [batch_size, max_length, input_size].\n member_probabilities (torch.Tensor): Probabilities describing the\n likelihood of elements belonging to the set.\n\n Returns:\n Tuple: Tuple of the outputs and their membership probabilities\n reordered with respect to the input.\n \"\"\"\n (in_batch_size, input_length, input_size) = inputs.size()\n (out_batch_size, output_length, output_size) = stacked_outputs.size()\n mapped_outputs = []\n with torch.no_grad():\n cost_matrices = list(map(torch.cdist, inputs, stacked_outputs, [self.p] * in_batch_size))\n (match_matrices, cols) = map(list, zip(*map(self.method[self.matcher], cost_matrices)))\n mapped_outputs = list(map(self.output_mapping, stacked_outputs, match_matrices))\n mapped_prob = list(map(self.output_mapping, member_probabilities, match_matrices))\n return (torch.stack(mapped_outputs), torch.stack(mapped_prob), np.stack(cols))","code_tokens":"","url":560897} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_plot.py","full_name":"test_learning_curve_display_plot_kwargs","func_name":"test_learning_curve_display_plot_kwargs","docstring":"Check the behaviour of the different plotting keyword arguments: `line_kw`, `fill_between_kw`, and `errorbar_kw`.","docstring_tokens":"","code":"def test_learning_curve_display_plot_kwargs(pyplot, data):\n \"\"\"Check the behaviour of the different plotting keyword arguments: `line_kw`,\n `fill_between_kw`, and `errorbar_kw`.\"\"\"\n (X, y) = data\n estimator = DecisionTreeClassifier(random_state=0)\n train_sizes = [0.3, 0.6, 0.9]\n std_display_style = 'fill_between'\n line_kw = {'color': 'red'}\n fill_between_kw = {'color': 'red', 'alpha': 1.0}\n display = LearningCurveDisplay.from_estimator(estimator, X, y, train_sizes=train_sizes, std_display_style=std_display_style, line_kw=line_kw, fill_between_kw=fill_between_kw)\n assert display.lines_[0].get_color() == 'red'\n assert_allclose(display.fill_between_[0].get_facecolor(), [[1.0, 0.0, 0.0, 1.0]])\n std_display_style = 'errorbar'\n errorbar_kw = {'color': 'red'}\n display = LearningCurveDisplay.from_estimator(estimator, X, y, train_sizes=train_sizes, std_display_style=std_display_style, errorbar_kw=errorbar_kw)\n assert display.errorbar_[0].lines[0].get_color() == 'red'","code_tokens":"","url":364357} +{"project_name":"CAMeL-Lab\/camel_tools","file_name":"test_transliterate.py","full_name":"TestTransliteratorInit.test_init_none_mapper","func_name":"test_init_none_mapper","docstring":"Test that init raises a TypeError when given a mapper that is None.","docstring_tokens":"","code":"def test_init_none_mapper(self):\n \"\"\"Test that init raises a TypeError when given a mapper that is None.\n \"\"\"\n with pytest.raises(TypeError):\n Transliterator(None)","code_tokens":"","url":411237} +{"project_name":"ifwe\/digsby","file_name":"plugin_registry.py","full_name":"plugins_skinpaths","func_name":"plugins_skinpaths","docstring":"Returns paths images for plugins can be loaded from.","docstring_tokens":"","code":"def plugins_skinpaths():\n \"\"\"Returns paths images for plugins can be loaded from.\"\"\"\n return list(pkg_dirs)","code_tokens":"","url":186029} +{"project_name":"triaquae\/triaquae","file_name":"forms.py","full_name":"PasswordResetForm.save","func_name":"save","docstring":"Generates a one-use only link for resetting password and sends to the user.","docstring_tokens":"","code":"def save(self, domain_override=None, subject_template_name='registration\/password_reset_subject.txt', email_template_name='registration\/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None):\n \"\"\"\n Generates a one-use only link for resetting password and sends to the\n user.\n \"\"\"\n from django.core.mail import send_mail\n for user in self.users_cache:\n if not domain_override:\n current_site = get_current_site(request)\n site_name = current_site.name\n domain = current_site.domain\n else:\n site_name = domain = domain_override\n c = {'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': int_to_base36(user.pk), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http'}\n subject = loader.render_to_string(subject_template_name, c)\n subject = ''.join(subject.splitlines())\n email = loader.render_to_string(email_template_name, c)\n send_mail(subject, email, from_email, [user.email])","code_tokens":"","url":357069} +{"project_name":"ifwe\/digsby","file_name":"rendezvous.py","full_name":"map_intarg","func_name":"map_intarg","docstring":"Dictionary lookup with extra type checking.","docstring_tokens":"","code":"def map_intarg(arg, map):\n \"\"\"Dictionary lookup with extra type checking.\"\"\"\n if isinstance(arg, basestring):\n if not arg in map:\n raise ValueError('%s is not a valid argument' % arg)\n return map[arg]\n elif not isinstance(arg, int):\n raise ValueError('integer or string expected')\n return arg","code_tokens":"","url":185815} +{"project_name":"opendilab\/DI-star","file_name":"remote_controller.py","full_name":"RemoteController.debug","func_name":"debug","docstring":"Run a debug command.","docstring_tokens":"","code":"@valid_status(Status.in_game)\n@sw.decorate\ndef debug(self, debug_commands):\n \"\"\"Run a debug command.\"\"\"\n if isinstance(debug_commands, sc_debug.DebugCommand):\n debug_commands = [debug_commands]\n return self._client.send(debug=sc_pb.RequestDebug(debug=debug_commands))","code_tokens":"","url":184755} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"custom_export_strategy.py","full_name":"convert_to_universal_format","func_name":"convert_to_universal_format","docstring":"Convert GTFlow trees to universal format.","docstring_tokens":"","code":"def convert_to_universal_format(dtec, sorted_feature_names, num_dense, num_sparse_float, num_sparse_int, feature_name_to_proto=None):\n \"\"\"Convert GTFlow trees to universal format.\"\"\"\n del num_sparse_int\n model_and_features = generic_tree_model_pb2.ModelAndFeatures()\n for feature_name in sorted_feature_names:\n if not feature_name_to_proto:\n model_and_features.features[feature_name].SetInParent()\n else:\n model_and_features.features[feature_name].CopyFrom(feature_name_to_proto[feature_name])\n model = model_and_features.model\n model.ensemble.summation_combination_technique.SetInParent()\n for tree_idx in range(len(dtec.trees)):\n gtflow_tree = dtec.trees[tree_idx]\n tree_weight = dtec.tree_weights[tree_idx]\n member = model.ensemble.members.add()\n member.submodel_id.value = tree_idx\n tree = member.submodel.decision_tree\n for node_idx in range(len(gtflow_tree.nodes)):\n gtflow_node = gtflow_tree.nodes[node_idx]\n node = tree.nodes.add()\n node_type = gtflow_node.WhichOneof('node')\n node.node_id.value = node_idx\n if node_type == 'leaf':\n leaf = gtflow_node.leaf\n if leaf.HasField('vector'):\n for weight in leaf.vector.value:\n new_value = node.leaf.vector.value.add()\n new_value.float_value = weight * tree_weight\n else:\n for (index, weight) in zip(leaf.sparse_vector.index, leaf.sparse_vector.value):\n new_value = node.leaf.sparse_vector.sparse_value[index]\n new_value.float_value = weight * tree_weight\n else:\n node = node.binary_node\n if node_type == 'dense_float_binary_split':\n split = gtflow_node.dense_float_binary_split\n feature_id = split.feature_column\n inequality_test = node.inequality_left_child_test\n inequality_test.feature_id.id.value = sorted_feature_names[feature_id]\n inequality_test.type = generic_tree_model_pb2.InequalityTest.LESS_OR_EQUAL\n inequality_test.threshold.float_value = split.threshold\n elif node_type == 'sparse_float_binary_split_default_left':\n split = gtflow_node.sparse_float_binary_split_default_left.split\n node.default_direction = generic_tree_model_pb2.BinaryNode.LEFT\n feature_id = split.feature_column + num_dense\n inequality_test = node.inequality_left_child_test\n inequality_test.feature_id.id.value = _SPARSE_FLOAT_FEATURE_NAME_TEMPLATE % (sorted_feature_names[feature_id], split.dimension_id)\n model_and_features.features.pop(sorted_feature_names[feature_id])\n model_and_features.features[inequality_test.feature_id.id.value].SetInParent()\n inequality_test.type = generic_tree_model_pb2.InequalityTest.LESS_OR_EQUAL\n inequality_test.threshold.float_value = split.threshold\n elif node_type == 'sparse_float_binary_split_default_right':\n split = gtflow_node.sparse_float_binary_split_default_right.split\n node.default_direction = generic_tree_model_pb2.BinaryNode.RIGHT\n feature_id = split.feature_column + num_dense\n inequality_test = node.inequality_left_child_test\n inequality_test.feature_id.id.value = _SPARSE_FLOAT_FEATURE_NAME_TEMPLATE % (sorted_feature_names[feature_id], split.dimension_id)\n model_and_features.features.pop(sorted_feature_names[feature_id])\n model_and_features.features[inequality_test.feature_id.id.value].SetInParent()\n inequality_test.type = generic_tree_model_pb2.InequalityTest.LESS_OR_EQUAL\n inequality_test.threshold.float_value = split.threshold\n elif node_type == 'categorical_id_binary_split':\n split = gtflow_node.categorical_id_binary_split\n node.default_direction = generic_tree_model_pb2.BinaryNode.RIGHT\n feature_id = split.feature_column + num_dense + num_sparse_float\n categorical_test = generic_tree_model_extensions_pb2.MatchingValuesTest()\n categorical_test.feature_id.id.value = sorted_feature_names[feature_id]\n matching_id = categorical_test.value.add()\n matching_id.int64_value = split.feature_id\n node.custom_left_child_test.Pack(categorical_test)\n else:\n raise ValueError('Unexpected node type %s', node_type)\n node.left_child_id.value = split.left_id\n node.right_child_id.value = split.right_id\n return model_and_features","code_tokens":"","url":312468} +{"project_name":"georghess\/voxel-mae","file_name":"primitive_head.py","full_name":"PrimitiveHead.get_primitive_center","func_name":"get_primitive_center","docstring":"Generate primitive center from predictions.","docstring_tokens":"","code":"def get_primitive_center(self, pred_flag, center):\n \"\"\"Generate primitive center from predictions.\n\n Args:\n pred_flag (torch.Tensor): Scores of primitive center.\n center (torch.Tensor): Pridictions of primitive center.\n\n Returns:\n Tuple: Primitive center and the prediction indices.\n \"\"\"\n ind_normal = F.softmax(pred_flag, dim=1)\n pred_indices = (ind_normal[:, 1, :] > self.surface_thresh).detach().float()\n selected = (ind_normal[:, 1, :] <= self.surface_thresh).detach().float()\n offset = torch.ones_like(center) * self.upper_thresh\n center = center + offset * selected.unsqueeze(-1)\n return (center, pred_indices)","code_tokens":"","url":380751} +{"project_name":"jezdez\/django-staticfiles","file_name":"storage.py","full_name":"CachedFilesMixin.url_converter","func_name":"url_converter","docstring":"Returns the custom URL converter for the given file name.","docstring_tokens":"","code":"def url_converter(self, name):\n \"\"\"\n Returns the custom URL converter for the given file name.\n \"\"\"\n\n def converter(matchobj):\n \"\"\"\n Converts the matched URL depending on the parent level (`..`)\n and returns the normalized and hashed URL using the url method\n of the storage.\n \"\"\"\n (matched, url) = matchobj.groups()\n if url.startswith(('#', 'http:', 'https:', 'data:')):\n return matched\n name_parts = name.split(os.sep)\n url = posixpath.normpath(url)\n url_parts = url.split('\/')\n (parent_level, sub_level) = (url.count('..'), url.count('\/'))\n if url.startswith('\/'):\n sub_level -= 1\n url_parts = url_parts[1:]\n if parent_level or not url.startswith('\/'):\n (start, end) = (parent_level + 1, parent_level)\n elif sub_level:\n if sub_level == 1:\n parent_level -= 1\n (start, end) = (parent_level, sub_level - 1)\n else:\n (start, end) = (1, sub_level - 1)\n joined_result = '\/'.join(name_parts[:-start] + url_parts[end:])\n hashed_url = self.url(unquote(joined_result), force=True)\n return 'url(\"%s\")' % unquote(hashed_url)\n return converter","code_tokens":"","url":164849} +{"project_name":"dmcnamee\/FlexModEHC","file_name":"check_inputs.py","full_name":"is_scalar_0inc_1exc","func_name":"is_scalar_0inc_1exc","docstring":"Checks if scalar is scalar and 0<=scalar<1, else raises ValueError.","docstring_tokens":"","code":"def is_scalar_0inc_1exc(scalar, scalar_name):\n \"\"\"Checks if scalar is scalar and 0<=scalar<1, else raises ValueError.\"\"\"\n err_msg = '{} {} invalid: must be scalar such that 0 <= {} < 1.'.format(scalar_name, scalar, scalar_name)\n if not np.isscalar(scalar):\n raise ValueError(err_msg)\n if scalar < 0.0 or scalar >= 1.0:\n raise ValueError(err_msg)","code_tokens":"","url":585032} +{"project_name":"dmcnamee\/FlexModEHC","file_name":"generators.py","full_name":"symmetrize_weightmat","func_name":"symmetrize_weightmat","docstring":"FUNCTION: symmetrizes weight matrix.","docstring_tokens":"","code":"def symmetrize_weightmat(W):\n \"\"\"\n FUNCTION: symmetrizes weight matrix.\n \"\"\"\n print('todo')","code_tokens":"","url":585118} +{"project_name":"ldkong1205\/LaserMix","file_name":"monoflex_bbox_coder.py","full_name":"MonoFlexCoder.decode","func_name":"decode","docstring":"Decode bounding box regression into 3D predictions.","docstring_tokens":"","code":"def decode(self, bbox: Tensor, base_centers2d: Tensor, labels: Tensor, downsample_ratio: int, cam2imgs: Tensor) -> Dict[str, Tensor]:\n \"\"\"Decode bounding box regression into 3D predictions.\n\n Args:\n bbox (Tensor): Raw bounding box predictions for each\n predict center2d point.\n shape: (N, C)\n base_centers2d (torch.Tensor): Base centers2d for 3D bboxes.\n shape: (N, 2).\n labels (Tensor): Batch predict class label for each predict\n center2d point.\n shape: (N, )\n downsample_ratio (int): The stride of feature map.\n cam2imgs (Tensor): Batch images' camera intrinsic matrix.\n shape: kitti (N, 4, 4) nuscenes (N, 3, 3)\n\n Return:\n dict: The 3D prediction dict decoded from regression map.\n the dict has components below:\n - bboxes2d (torch.Tensor): Decoded [x1, y1, x2, y2] format\n 2D bboxes.\n - dimensions (torch.Tensor): Decoded dimensions for each\n object.\n - offsets2d (torch.Tenosr): Offsets between base centers2d\n and real centers2d.\n - direct_depth (torch.Tensor): Decoded directly regressed\n depth.\n - keypoints2d (torch.Tensor): Keypoints of each projected\n 3D box on image.\n - keypoints_depth (torch.Tensor): Decoded depth from keypoints.\n - combined_depth (torch.Tensor): Combined depth using direct\n depth and keypoints depth with depth uncertainty.\n - orientations (torch.Tensor): Multibin format orientations\n (local yaw) for each objects.\n \"\"\"\n pred_bboxes2d = bbox[:, 0:4]\n pred_bboxes2d = self.decode_bboxes2d(pred_bboxes2d, base_centers2d)\n pred_offsets2d = bbox[:, 4:6]\n pred_dimensions_offsets3d = bbox[:, 29:32]\n pred_orientations = torch.cat((bbox[:, 32:40], bbox[:, 40:48]), dim=1)\n pred_keypoints_depth_uncertainty = bbox[:, 26:29]\n pred_direct_depth_uncertainty = bbox[:, 49:50].squeeze(-1)\n pred_keypoints2d = bbox[:, 6:26].reshape(-1, 10, 2)\n pred_direct_depth_offsets = bbox[:, 48:49].squeeze(-1)\n pred_dimensions = self.decode_dims(labels, pred_dimensions_offsets3d)\n pred_direct_depth = self.decode_direct_depth(pred_direct_depth_offsets)\n pred_keypoints_depth = self.keypoints2depth(pred_keypoints2d, pred_dimensions, cam2imgs, downsample_ratio)\n pred_direct_depth_uncertainty = torch.clamp(pred_direct_depth_uncertainty, self.uncertainty_range[0], self.uncertainty_range[1])\n pred_keypoints_depth_uncertainty = torch.clamp(pred_keypoints_depth_uncertainty, self.uncertainty_range[0], self.uncertainty_range[1])\n if self.combine_depth:\n pred_depth_uncertainty = torch.cat((pred_direct_depth_uncertainty.unsqueeze(-1), pred_keypoints_depth_uncertainty), dim=1).exp()\n pred_depth = torch.cat((pred_direct_depth.unsqueeze(-1), pred_keypoints_depth), dim=1)\n pred_combined_depth = self.combine_depths(pred_depth, pred_depth_uncertainty)\n else:\n pred_combined_depth = None\n preds = dict(bboxes2d=pred_bboxes2d, dimensions=pred_dimensions, offsets2d=pred_offsets2d, keypoints2d=pred_keypoints2d, orientations=pred_orientations, direct_depth=pred_direct_depth, keypoints_depth=pred_keypoints_depth, combined_depth=pred_combined_depth, direct_depth_uncertainty=pred_direct_depth_uncertainty, keypoints_depth_uncertainty=pred_keypoints_depth_uncertainty)\n return preds","code_tokens":"","url":624285} +{"project_name":"srai-lab\/srai","file_name":"test_count_embedder.py","full_name":"test_empty","func_name":"test_empty","docstring":"Test CountEmbedder handling of empty input data frames.","docstring_tokens":"","code":"@pytest.mark.parametrize('regions_fixture,features_fixture,joint_fixture,expected_features_fixture,expectation', [('gdf_regions_empty', 'gdf_features', 'gdf_joint', None, does_not_raise()), ('gdf_regions', 'gdf_features_empty', 'gdf_joint', None, pytest.raises(ValueError)), ('gdf_regions', 'gdf_features_empty', 'gdf_joint', 'expected_feature_names', does_not_raise()), ('gdf_regions', 'gdf_features', 'gdf_joint_empty', None, does_not_raise())])\ndef test_empty(regions_fixture: str, features_fixture: str, joint_fixture: str, expected_features_fixture: Union[str, None], expectation: Any, request: Any) -> None:\n \"\"\"Test CountEmbedder handling of empty input data frames.\"\"\"\n expected_output_features = None if expected_features_fixture is None else request.getfixturevalue(expected_features_fixture)\n embedder = CountEmbedder(expected_output_features)\n gdf_regions: 'gpd.GeoDataFrame' = request.getfixturevalue(regions_fixture)\n gdf_features: 'gpd.GeoDataFrame' = request.getfixturevalue(features_fixture)\n gdf_joint: 'gpd.GeoDataFrame' = request.getfixturevalue(joint_fixture)\n with expectation:\n embedding = embedder.transform(gdf_regions, gdf_features, gdf_joint)\n assert len(embedding) == len(gdf_regions)\n assert embedding.index.name == gdf_regions.index.name\n if expected_output_features:\n assert embedding.columns.tolist() == expected_output_features\n assert (embedding == 0).all().all()","code_tokens":"","url":371961} +{"project_name":"yinyunie\/ScenePriors","file_name":"weight_mapper.py","full_name":"MappingRule.matches","func_name":"matches","docstring":"Check whether this mapping rule should be applied to this key.","docstring_tokens":"","code":"def matches(self, key):\n \"\"\"Check whether this mapping rule should be applied to this key.\"\"\"\n raise NotImplementedError()","code_tokens":"","url":329513} +{"project_name":"tudelft3d\/SUMS-Semantic-Urban-Mesh--public","file_name":"s3dis_dataset.py","full_name":"get_datasets","func_name":"get_datasets","docstring":"Gets training and test datasets.","docstring_tokens":"","code":"def get_datasets(args, test_seed_offset=0):\n \"\"\" Gets training and test datasets. \"\"\"\n (testlist, trainlist, validlist) = ([], [], [])\n valid_names = ['hallway_1.h5', 'hallway_6.h5', 'hallway_11.h5', 'office_1.h5', 'office_6.h5', 'office_11.h5', 'office_16.h5', 'office_21.h5', 'office_26.h5', 'office_31.h5', 'office_36.h5', 'WC_2.h5', 'storage_1.h5', 'storage_5.h5', 'conferenceRoom_2.h5', 'auditorium_1.h5']\n for n in range(1, 7):\n if n != args.cvfold:\n path = '{}\/superpoint_graphs\/Area_{:d}\/'.format(args.S3DIS_PATH, n)\n for fname in sorted(os.listdir(path)):\n if fname.endswith('.h5') and (not (args.use_val_set and fname in valid_names)):\n trainlist.append(spg.spg_reader(args, path + fname, True))\n if fname.endswith('.h5') and (args.use_val_set and fname in valid_names):\n validlist.append(spg.spg_reader(args, path + fname, True))\n path = '{}\/superpoint_graphs\/Area_{:d}\/'.format(args.S3DIS_PATH, args.cvfold)\n for fname in sorted(os.listdir(path)):\n if fname.endswith('.h5'):\n testlist.append(spg.spg_reader(args, path + fname, True))\n if args.spg_attribs01:\n (trainlist, testlist, validlist, scaler) = spg.scaler01(trainlist, testlist, validlist=validlist)\n return (tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in trainlist], functools.partial(spg.loader, train=True, args=args, db_path=args.S3DIS_PATH)), tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in testlist], functools.partial(spg.loader, train=False, args=args, db_path=args.S3DIS_PATH, test_seed_offset=test_seed_offset)), tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in validlist], functools.partial(spg.loader, train=False, args=args, db_path=args.S3DIS_PATH, test_seed_offset=test_seed_offset)), scaler)","code_tokens":"","url":911654} +{"project_name":"kubeflow\/pipelines","file_name":"_pipeline_param.py","full_name":"sanitize_k8s_name","func_name":"sanitize_k8s_name","docstring":"Cleans and converts the names in the workflow.","docstring_tokens":"","code":"def sanitize_k8s_name(name, allow_capital_underscore=False):\n \"\"\"Cleans and converts the names in the workflow.\n\n Args:\n name: original name,\n allow_capital_underscore: whether to allow capital letter and underscore in\n this name.\n\n Returns:\n A sanitized name.\n \"\"\"\n if allow_capital_underscore:\n return re.sub('-+', '-', re.sub('[^-_0-9A-Za-z]+', '-', name)).lstrip('-').rstrip('-')\n else:\n return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-', name.lower())).lstrip('-').rstrip('-')","code_tokens":"","url":780176} +{"project_name":"AlexGeControl\/Artificial-Intelligence-01-Graph-Search-02-Pacman","file_name":"pyparsing.py","full_name":"upcaseTokens","func_name":"upcaseTokens","docstring":"Helper parse action to convert tokens to upper case.","docstring_tokens":"","code":"def upcaseTokens(s, l, t):\n \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n return [tt.upper() for tt in map(_ustr, t)]","code_tokens":"","url":35784} +{"project_name":"thaines\/helit","file_name":"model.py","full_name":"DocModel.absorbModel","func_name":"absorbModel","docstring":"Absorbs samples from the given DocModel, leaving it baren.","docstring_tokens":"","code":"def absorbModel(self, dModel):\n \"\"\"Absorbs samples from the given DocModel, leaving it baren.\"\"\"\n self.sample += dModel.sample\n dModel.sample = []","code_tokens":"","url":591190} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"generate_samples.py","full_name":"write_unmasked_log","func_name":"write_unmasked_log","docstring":"Helper function for logging evaluated sequences without mask.","docstring_tokens":"","code":"def write_unmasked_log(log, id_to_word, sequence_eval):\n \"\"\"Helper function for logging evaluated sequences without mask.\"\"\"\n indices_arr = np.asarray(sequence_eval)\n samples = helper.convert_to_human_readable(id_to_word, indices_arr, FLAGS.batch_size)\n for sample in samples:\n log.write(sample + '\\n')\n log.flush()\n return samples","code_tokens":"","url":757885} +{"project_name":"mj-will\/nessai","file_name":"combined.py","full_name":"CombinedReparameterisation.update","func_name":"update","docstring":"Update the reparameterisations given a set of points.","docstring_tokens":"","code":"def update(self, x):\n \"\"\"Update the reparameterisations given a set of points.\"\"\"\n for r in self.values():\n r.update(x)","code_tokens":"","url":292138} +{"project_name":"voxel51\/fiftyone","file_name":"collections.py","full_name":"SampleCollection.has_evaluations","func_name":"has_evaluations","docstring":"Whether this colection has any evaluation results.","docstring_tokens":"","code":"@property\ndef has_evaluations(self):\n \"\"\"Whether this colection has any evaluation results.\"\"\"\n return bool(self.list_evaluations())","code_tokens":"","url":582771} +{"project_name":"triaquae\/triaquae","file_name":"geometries.py","full_name":"OGRGeometry.equals","func_name":"equals","docstring":"Returns True if this geometry is equivalent to the other.","docstring_tokens":"","code":"def equals(self, other):\n \"\"\"Returns True if this geometry is equivalent to the other.\"\"\"\n return self._topology(capi.ogr_equals, other)","code_tokens":"","url":357588} +{"project_name":"rudranil723\/mini-main","file_name":"wikipedia.py","full_name":"WikipediaPage.categories","func_name":"categories","docstring":"List of categories of a page.","docstring_tokens":"","code":"@property\ndef categories(self):\n \"\"\"\n List of categories of a page.\n \"\"\"\n if not getattr(self, '_categories', False):\n self._categories = [re.sub('^Category:', '', x) for x in [link['title'] for link in self.__continued_query({'prop': 'categories', 'cllimit': 'max'})]]\n return self._categories","code_tokens":"","url":271048} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"__init__.py","full_name":"Misc.winfo_depth","func_name":"winfo_depth","docstring":"Return the number of bits per pixel.","docstring_tokens":"","code":"def winfo_depth(self):\n \"\"\"Return the number of bits per pixel.\"\"\"\n return self.tk.getint(self.tk.call('winfo', 'depth', self._w))","code_tokens":"","url":284079} +{"project_name":"SamsungLabs\/fcaf3d","file_name":"h3d_roi_head.py","full_name":"H3DRoIHead.forward_train","func_name":"forward_train","docstring":"Training forward function of PartAggregationROIHead.","docstring_tokens":"","code":"def forward_train(self, feats_dict, img_metas, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask, pts_instance_mask, gt_bboxes_ignore=None):\n \"\"\"Training forward function of PartAggregationROIHead.\n\n Args:\n feats_dict (dict): Contains features from the first stage.\n img_metas (list[dict]): Contain pcd and img's meta info.\n points (list[torch.Tensor]): Input points.\n gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]): Ground truth bboxes of each sample.\n gt_labels_3d (list[torch.Tensor]): Labels of each sample.\n pts_semantic_mask (None | list[torch.Tensor]): Point-wise\n semantic mask.\n pts_instance_mask (None | list[torch.Tensor]): Point-wise\n instance mask.\n gt_bboxes_ignore (None | list[torch.Tensor]): Specify\n which bounding.\n\n Returns:\n dict: losses from each head.\n \"\"\"\n losses = dict()\n sample_mod = self.train_cfg.sample_mod\n assert sample_mod in ['vote', 'seed', 'random']\n result_z = self.primitive_z(feats_dict, sample_mod)\n feats_dict.update(result_z)\n result_xy = self.primitive_xy(feats_dict, sample_mod)\n feats_dict.update(result_xy)\n result_line = self.primitive_line(feats_dict, sample_mod)\n feats_dict.update(result_line)\n primitive_loss_inputs = (feats_dict, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask, pts_instance_mask, img_metas, gt_bboxes_ignore)\n loss_z = self.primitive_z.loss(*primitive_loss_inputs)\n losses.update(loss_z)\n loss_xy = self.primitive_xy.loss(*primitive_loss_inputs)\n losses.update(loss_xy)\n loss_line = self.primitive_line.loss(*primitive_loss_inputs)\n losses.update(loss_line)\n targets = feats_dict.pop('targets')\n bbox_results = self.bbox_head(feats_dict, sample_mod)\n feats_dict.update(bbox_results)\n bbox_loss = self.bbox_head.loss(feats_dict, points, gt_bboxes_3d, gt_labels_3d, pts_semantic_mask, pts_instance_mask, img_metas, targets, gt_bboxes_ignore)\n losses.update(bbox_loss)\n return losses","code_tokens":"","url":560513} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"firestore_pb2_grpc.py","full_name":"FirestoreServicer.Write","func_name":"Write","docstring":"Streams batches of document updates and deletes, in order.","docstring_tokens":"","code":"def Write(self, request_iterator, context):\n \"\"\"Streams batches of document updates and deletes, in order.\n \"\"\"\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')","code_tokens":"","url":214803} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"bounds.py","full_name":"never_resample_criterion","func_name":"never_resample_criterion","docstring":"A criterion that never resamples.","docstring_tokens":"","code":"def never_resample_criterion(unused_num_samples, log_ess, unused_t):\n \"\"\"A criterion that never resamples.\"\"\"\n return tf.cast(tf.zeros_like(log_ess), tf.bool)","code_tokens":"","url":48331} +{"project_name":"FedML-AI\/FedML","file_name":"checkpoint.py","full_name":"load_state_dict","func_name":"load_state_dict","docstring":"Load weights from checkpoint file, only assign weights those layers' name and shape are match.","docstring_tokens":"","code":"def load_state_dict(weights, model, map_location=None):\n \"\"\"Load weights from checkpoint file, only assign weights those layers' name and shape are match.\"\"\"\n ckpt = torch.load(weights, map_location=map_location)\n state_dict = ckpt['model'].float().state_dict()\n model_state_dict = model.state_dict()\n state_dict = {k: v for (k, v) in state_dict.items() if k in model_state_dict and v.shape == model_state_dict[k].shape}\n model.load_state_dict(state_dict, strict=False)\n del ckpt, state_dict, model_state_dict\n return model","code_tokens":"","url":545081} +{"project_name":"zehuichen123\/AutoAlignV2","file_name":"centerpoint_head.py","full_name":"CenterHead.forward_single","func_name":"forward_single","docstring":"Forward function for CenterPoint.","docstring_tokens":"","code":"def forward_single(self, x):\n \"\"\"Forward function for CenterPoint.\n\n Args:\n x (torch.Tensor): Input feature map with the shape of\n [B, 512, 128, 128].\n\n Returns:\n list[dict]: Output results for tasks.\n \"\"\"\n ret_dicts = []\n x = self.shared_conv(x)\n for task in self.task_heads:\n ret_dicts.append(task(x))\n return ret_dicts","code_tokens":"","url":416823} +{"project_name":"triaquae\/triaquae","file_name":"creation.py","full_name":"BaseDatabaseCreation.sql_indexes_for_field","func_name":"sql_indexes_for_field","docstring":"Return the CREATE INDEX SQL statements for a single model field.","docstring_tokens":"","code":"def sql_indexes_for_field(self, model, f, style):\n \"\"\"\n Return the CREATE INDEX SQL statements for a single model field.\n \"\"\"\n if f.db_index and (not f.unique):\n return self.sql_indexes_for_fields(model, [f], style)\n else:\n return []","code_tokens":"","url":423289} +{"project_name":"microsoft\/maro","file_name":"common.py","full_name":"DecisionEvent.action_scope","func_name":"action_scope","docstring":"ActionScope: Load and discharge scope for agent to generate decision.","docstring_tokens":"","code":"@property\ndef action_scope(self) -> ActionScope:\n \"\"\"ActionScope: Load and discharge scope for agent to generate decision.\"\"\"\n if self._action_scope is None:\n self._action_scope = self._action_scope_func(self.port_idx, self.vessel_idx)\n return self._action_scope","code_tokens":"","url":628634} +{"project_name":"anonymous-iclr-2019\/acai-iclr-2019","file_name":"discretization.py","full_name":"DiscreteBottleneck.slice_hidden","func_name":"slice_hidden","docstring":"Slice encoder hidden state into block_dim.","docstring_tokens":"","code":"def slice_hidden(self, x):\n \"\"\"Slice encoder hidden state into block_dim.\n\n Args:\n x: Encoder hidden state of shape [-1, hidden_size].\n\n Returns:\n Sliced states of shape [-1, num_blocks, block_dim].\n \"\"\"\n x_sliced = tf.reshape(x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim])\n return x_sliced","code_tokens":"","url":406631} +{"project_name":"yinyunie\/ScenePriors","file_name":"ply_io.py","full_name":"_PlyElementType.add_property","func_name":"add_property","docstring":"Adds a new property.","docstring_tokens":"","code":"def add_property(self, name: str, data_type: str, list_size_type: Optional[str]=None):\n \"\"\"Adds a new property.\n\n Args:\n name: (str) name of the property.\n data_type: (str) PLY data type.\n list_size_type: (str) PLY data type of the list size, or None if not\n a list.\n \"\"\"\n for property in self.properties:\n if property.name == name:\n msg = 'Cannot have two properties called %s in %s.'\n raise ValueError(msg % (name, self.name))\n self.properties.append(_Property(name, data_type, list_size_type))","code_tokens":"","url":329754} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"registry.py","full_name":"hparams","func_name":"hparams","docstring":"Retrieve registered hparams by name.","docstring_tokens":"","code":"def hparams(name):\n \"\"\"Retrieve registered hparams by name.\"\"\"\n if name not in _HPARAMS:\n error_msg = 'HParams set %s never registered. Sets registered:\\n%s'\n raise LookupError(error_msg % (name, display_list_by_prefix(list_hparams(), starting_spaces=4)))\n hp = _HPARAMS[name]()\n if hp is None:\n raise TypeError('HParams %s is None. Make sure the registered function returns the HParams object.' % name)\n return hp","code_tokens":"","url":966176} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"pty.py","full_name":"spawn","func_name":"spawn","docstring":"Create a spawned process.","docstring_tokens":"","code":"def spawn(argv, master_read=_read, stdin_read=_read):\n \"\"\"Create a spawned process.\"\"\"\n if type(argv) == type(''):\n argv = (argv,)\n (pid, master_fd) = fork()\n if pid == CHILD:\n os.execlp(argv[0], *argv)\n try:\n mode = tty.tcgetattr(STDIN_FILENO)\n tty.setraw(STDIN_FILENO)\n restore = 1\n except tty.error:\n restore = 0\n try:\n _copy(master_fd, master_read, stdin_read)\n except OSError:\n if restore:\n tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)\n os.close(master_fd)\n return os.waitpid(pid, 0)[1]","code_tokens":"","url":281175} +{"project_name":"bitprophet\/ssh","file_name":"test_util.py","full_name":"UtilTest.test_1_import","func_name":"test_1_import","docstring":"verify that all the classes can be imported from ssh.","docstring_tokens":"","code":"def test_1_import(self):\n \"\"\"\n verify that all the classes can be imported from ssh.\n \"\"\"\n symbols = globals().keys()\n self.assertTrue('Transport' in symbols)\n self.assertTrue('SSHClient' in symbols)\n self.assertTrue('MissingHostKeyPolicy' in symbols)\n self.assertTrue('AutoAddPolicy' in symbols)\n self.assertTrue('RejectPolicy' in symbols)\n self.assertTrue('WarningPolicy' in symbols)\n self.assertTrue('SecurityOptions' in symbols)\n self.assertTrue('SubsystemHandler' in symbols)\n self.assertTrue('Channel' in symbols)\n self.assertTrue('RSAKey' in symbols)\n self.assertTrue('DSSKey' in symbols)\n self.assertTrue('Message' in symbols)\n self.assertTrue('SSHException' in symbols)\n self.assertTrue('AuthenticationException' in symbols)\n self.assertTrue('PasswordRequiredException' in symbols)\n self.assertTrue('BadAuthenticationType' in symbols)\n self.assertTrue('ChannelException' in symbols)\n self.assertTrue('SFTP' in symbols)\n self.assertTrue('SFTPFile' in symbols)\n self.assertTrue('SFTPHandle' in symbols)\n self.assertTrue('SFTPClient' in symbols)\n self.assertTrue('SFTPServer' in symbols)\n self.assertTrue('SFTPError' in symbols)\n self.assertTrue('SFTPAttributes' in symbols)\n self.assertTrue('SFTPServerInterface' in symbols)\n self.assertTrue('ServerInterface' in symbols)\n self.assertTrue('BufferedFile' in symbols)\n self.assertTrue('Agent' in symbols)\n self.assertTrue('AgentKey' in symbols)\n self.assertTrue('HostKeys' in symbols)\n self.assertTrue('SSHConfig' in symbols)\n self.assertTrue('util' in symbols)","code_tokens":"","url":372507} +{"project_name":"replit-archive\/empythoned","file_name":"_pyio.py","full_name":"TextIOBase.truncate","func_name":"truncate","docstring":"Truncate size to pos.","docstring_tokens":"","code":"def truncate(self, pos=None):\n \"\"\"Truncate size to pos.\"\"\"\n self._unsupported('truncate')","code_tokens":"","url":177452} +{"project_name":"microsoft\/nlp-recipes","file_name":"msrpc.py","full_name":"download_msrpc","func_name":"download_msrpc","docstring":"Downloads Windows Installer for Microsoft Paraphrase Corpus.","docstring_tokens":"","code":"def download_msrpc(download_dir):\n \"\"\"Downloads Windows Installer for Microsoft Paraphrase Corpus.\n \n Args:\n download_dir (str): File path for the downloaded file\n\n Returns:\n str: file_path to the downloaded dataset.\n \"\"\"\n url = 'https:\/\/download.microsoft.com\/download\/D\/4\/6\/D46FF87A-F6B9-4252-AA8B-3604ED519838\/MSRParaphraseCorpus.msi'\n return maybe_download(url, work_directory=download_dir)","code_tokens":"","url":731182} +{"project_name":"enuguru\/artificial_intelligence_and_machine_","file_name":"plugin_base.py","full_name":"pre_begin","func_name":"pre_begin","docstring":"things to set up early, before coverage might be setup.","docstring_tokens":"","code":"def pre_begin(opt):\n \"\"\"things to set up early, before coverage might be setup.\"\"\"\n global options\n options = opt\n for fn in pre_configure:\n fn(options, file_config)","code_tokens":"","url":160969} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"environment.py","full_name":"Template.is_up_to_date","func_name":"is_up_to_date","docstring":"If this variable is `False` there is a newer version available.","docstring_tokens":"","code":"@property\ndef is_up_to_date(self):\n \"\"\"If this variable is `False` there is a newer version available.\"\"\"\n if self._uptodate is None:\n return True\n return self._uptodate()","code_tokens":"","url":39234} +{"project_name":"sony\/nnabla-rl","file_name":"test_categorical_dqn.py","full_name":"TestCategoricalDQN.test_run_online_rnn_training","func_name":"test_run_online_rnn_training","docstring":"Check that no error occurs when calling online training with RNN model.","docstring_tokens":"","code":"def test_run_online_rnn_training(self):\n \"\"\"Check that no error occurs when calling online training with RNN\n model.\"\"\"\n\n class RNNModelBuilder(ModelBuilder[ValueDistributionFunction]):\n\n def build_model(self, scope_name: str, env_info, algorithm_config, **kwargs):\n n_action = env_info.action_dim\n n_atom = algorithm_config.num_atoms\n v_min = algorithm_config.v_min\n v_max = algorithm_config.v_max\n return RNNValueDistributionFunction(scope_name, n_action, n_atom, v_min, v_max)\n dummy_env = E.DummyDiscreteImg()\n config = A.CategoricalDQNConfig()\n config.num_steps = 2\n config.unroll_steps = 2\n config.burn_in_steps = 2\n config.start_timesteps = 7\n config.batch_size = 2\n config.learner_update_frequency = 1\n config.target_update_frequency = 1\n categorical_dqn = A.CategoricalDQN(dummy_env, config=config, value_distribution_builder=RNNModelBuilder())\n categorical_dqn.train_online(dummy_env, total_iterations=10)","code_tokens":"","url":727331} +{"project_name":"ZurichNLP\/romanesco","file_name":"reader.py","full_name":"iterate","func_name":"iterate","docstring":"Yields sequences of length `num_step` for RNN training (or evaluation), in batches of size `batch_size`.","docstring_tokens":"","code":"def iterate(raw_data, batch_size: int=C.BATCH_SIZE, num_steps: int=C.NUM_STEPS):\n \"\"\"Yields sequences of length `num_step` for RNN training (or evaluation),\n in batches of size `batch_size`.\n\n Args:\n raw_data: the dataset (a list of numbers).\n batch_size: the batch size\n num_steps: number of time steps per example\n\n Yields:\n an (x, y) tuple, with x corresponding to inputs and y to expected\n outputs. y is x time shifted by one: y_0 = x_1, y_1 = x_2, etc. Both x\n and y are NumPy arrays of shape (num_steps, batch_size).\n\n Example:\n >>> raw_data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n >>> i = iterate(raw_data, batch_size=3, num_steps=2)\n >>> batches = list(i)\n >>> len(batches)\n 2\n >>> batches[0]\n ( [[ 0, 1], [[ 1, 2],\n [ 5, 6], [ 6, 7],\n [10, 11]], [11, 12]] )\n >>> batches[1]\n ( [[ 2, 3], [[ 3, 4],\n [ 7, 8], [ 8, 9],\n [12, 13]] [13, 14]] )\n \"\"\"\n data_len = len(raw_data)\n num_batches = data_len \/\/ batch_size\n data = raw_data[0:batch_size * num_batches]\n data = np.reshape(data, [batch_size, num_batches])\n num_batches_in_epoch = (num_batches - 1) \/\/ num_steps\n for i in range(num_batches_in_epoch):\n s = i * num_steps\n e = s + num_steps\n yield (data[:, s:e], data[:, s + 1:e + 1])","code_tokens":"","url":326760} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"test_shlex.py","full_name":"ShlexTest.testEmptyStringHandling","func_name":"testEmptyStringHandling","docstring":"Test that parsing of empty strings is correctly handled.","docstring_tokens":"","code":"def testEmptyStringHandling(self):\n \"\"\"Test that parsing of empty strings is correctly handled.\"\"\"\n expected = ['', ')', 'abc']\n for punct in (False, True):\n s = shlex.shlex(\"'')abc\", posix=True, punctuation_chars=punct)\n slist = list(s)\n self.assertEqual(slist, expected)\n expected = [\"''\", ')', 'abc']\n s = shlex.shlex(\"'')abc\", punctuation_chars=True)\n self.assertEqual(list(s), expected)","code_tokens":"","url":283570} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"compiler.py","full_name":"CodeGenerator.newline","func_name":"newline","docstring":"Add one or more newlines before the next write.","docstring_tokens":"","code":"def newline(self, node=None, extra=0):\n \"\"\"Add one or more newlines before the next write.\"\"\"\n self._new_lines = max(self._new_lines, 1 + extra)\n if node is not None and node.lineno != self._last_line:\n self._write_debug_info = node.lineno\n self._last_line = node.lineno","code_tokens":"","url":39176} +{"project_name":"usnistgov\/chemnlp","file_name":"make_wordcloud.py","full_name":"make_plot","func_name":"make_plot","docstring":"Generate a word-cloud given pandas dataframe.","docstring_tokens":"","code":"def make_plot(df=None, key='title'):\n \"\"\"Generate a word-cloud given pandas dataframe.\"\"\"\n all_text = ' '.join(df[key].values)\n f = open('sample.txt', 'w')\n f.write(all_text)\n f.close()\n d = path.dirname(__file__) if '__file__' in locals() else os.getcwd()\n text = open(path.join(d, 'sample.txt')).read()\n wordcloud = WordCloud().generate(text)\n wordcloud = WordCloud(max_font_size=40, background_color='white').generate(text)\n plt.figure()\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis('off')\n plt.savefig('wordc.png')\n plt.close()","code_tokens":"","url":486142} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjvFigureWrapper.xaxisdata","func_name":"xaxisdata","docstring":"range of x-axis in data units.","docstring_tokens":"","code":"@util.CachedProperty\ndef xaxisdata(self):\n \"\"\"range of x-axis in data units.\"\"\"\n return util.buf_to_npy(self._ptr.contents.xaxisdata, (2,))","code_tokens":"","url":440772} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"dataset_item.py","full_name":"DatasetItemEntity.annotation_scene","func_name":"annotation_scene","docstring":"Access to annotation scene.","docstring_tokens":"","code":"@property\ndef annotation_scene(self) -> AnnotationSceneEntity:\n \"\"\"Access to annotation scene.\"\"\"\n return self.__annotation_scene","code_tokens":"","url":918504} +{"project_name":"TheCurryMan\/MedicAI","file_name":"markers.py","full_name":"ASTWhitelist.visit","func_name":"visit","docstring":"Ensure statement only contains allowed nodes.","docstring_tokens":"","code":"def visit(self, node):\n \"\"\"Ensure statement only contains allowed nodes.\"\"\"\n if not isinstance(node, self.ALLOWED):\n raise SyntaxError('Not allowed in environment markers.\\n%s\\n%s' % (self.statement, ' ' * node.col_offset + '^'))\n return ast.NodeTransformer.visit(self, node)","code_tokens":"","url":649968} +{"project_name":"hamza-murad\/AALU","file_name":"visual_recognition_v4.py","full_name":"TrainingEvent.from_dict","func_name":"from_dict","docstring":"Initialize a TrainingEvent object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'TrainingEvent':\n \"\"\"Initialize a TrainingEvent object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['type', 'collection_id', 'completion_time', 'status', 'image_count']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class TrainingEvent: ' + ', '.join(bad_keys))\n if 'type' in _dict:\n args['type'] = _dict.get('type')\n if 'collection_id' in _dict:\n args['collection_id'] = _dict.get('collection_id')\n if 'completion_time' in _dict:\n args['completion_time'] = string_to_datetime(_dict.get('completion_time'))\n if 'status' in _dict:\n args['status'] = _dict.get('status')\n if 'image_count' in _dict:\n args['image_count'] = _dict.get('image_count')\n return cls(**args)","code_tokens":"","url":6206} +{"project_name":"xiaomengyc\/ACoL","file_name":"functional.py","full_name":"to_grayscale","func_name":"to_grayscale","docstring":"Convert image to grayscale version of image.","docstring_tokens":"","code":"def to_grayscale(img, num_output_channels=1):\n \"\"\"Convert image to grayscale version of image.\n\n Args:\n img (PIL Image): Image to be converted to grayscale.\n\n Returns:\n PIL Image: Grayscale version of the image.\n if num_output_channels == 1 : returned image is single channel\n if num_output_channels == 3 : returned image is 3 channel with r == g == b\n \"\"\"\n if not _is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n if num_output_channels == 1:\n img = img.convert('L')\n elif num_output_channels == 3:\n img = img.convert('L')\n np_img = np.array(img, dtype=np.uint8)\n np_img = np.dstack([np_img, np_img, np_img])\n img = Image.fromarray(np_img, 'RGB')\n else:\n raise ValueError('num_output_channels should be either 1 or 3')\n return img","code_tokens":"","url":8556} +{"project_name":"tensortrade-org\/tensortrade","file_name":"order.py","full_name":"Order.base_instrument","func_name":"base_instrument","docstring":"The base instrument of the pair being traded.","docstring_tokens":"","code":"@property\ndef base_instrument(self) -> 'Instrument':\n \"\"\"The base instrument of the pair being traded.\"\"\"\n return self.exchange_pair.pair.base","code_tokens":"","url":366567} +{"project_name":"jimtin\/Stock_Comparison","file_name":"__init__.py","full_name":"MarkerEvaluation.is_invalid_marker","func_name":"is_invalid_marker","docstring":"Validate text as a PEP 426 environment marker; return an exception if invalid or False otherwise.","docstring_tokens":"","code":"@classmethod\ndef is_invalid_marker(cls, text):\n \"\"\"\n Validate text as a PEP 426 environment marker; return an exception\n if invalid or False otherwise.\n \"\"\"\n try:\n cls.evaluate_marker(text)\n except SyntaxError as e:\n return cls.normalize_exception(e)\n return False","code_tokens":"","url":389135} +{"project_name":"CosmiQ\/solaris","file_name":"raster_tile.py","full_name":"RasterTiler.get_tile_bounds","func_name":"get_tile_bounds","docstring":"Get tile bounds for each tile to be created in the input CRS.","docstring_tokens":"","code":"def get_tile_bounds(self):\n \"\"\"Get tile bounds for each tile to be created in the input CRS.\"\"\"\n if not self.aoi_boundary:\n if not self.src:\n raise ValueError('aoi_boundary and\/or a source file must be provided.')\n else:\n self.aoi_boundary = list(self.src.bounds)\n self.tile_bounds = split_geom(geometry=self.aoi_boundary, tile_size=self.src_tile_size, resolution=(self.src.transform[0], -self.src.transform[4]), use_projection_units=self.use_src_metric_size, src_img=self.src)","code_tokens":"","url":879405} +{"project_name":"open-mmlab\/mmcv","file_name":"processing.py","full_name":"Normalize.transform","func_name":"transform","docstring":"Function to normalize images.","docstring_tokens":"","code":"def transform(self, results: dict) -> dict:\n \"\"\"Function to normalize images.\n\n Args:\n results (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Normalized results, key 'img_norm_cfg' key is added in to\n result dict.\n \"\"\"\n results['img'] = mmcv.imnormalize(results['img'], self.mean, self.std, self.to_rgb)\n results['img_norm_cfg'] = dict(mean=self.mean, std=self.std, to_rgb=self.to_rgb)\n return results","code_tokens":"","url":631580} +{"project_name":"rudranil723\/mini-main","file_name":"symbolic.py","full_name":"as_deref","func_name":"as_deref","docstring":"Return object as dereferencing expression.","docstring_tokens":"","code":"def as_deref(expr):\n \"\"\"Return object as dereferencing expression.\n \"\"\"\n return Expr(Op.DEREF, expr)","code_tokens":"","url":322684} +{"project_name":"ifwe\/digsby","file_name":"feed_trends.py","full_name":"reposition_existing_ads","func_name":"reposition_existing_ads","docstring":"Given old_ids (a list of ids and AdPlaceholder objects) attempts to insert those same AdPlaceholder objects into new_ids so that they are in the same position relative to the ids around them in old_ids.","docstring_tokens":"","code":"def reposition_existing_ads(old_ids, new_ids):\n \"\"\"Given old_ids (a list of ids and AdPlaceholder objects) attempts to insert those\n same AdPlaceholder objects into new_ids so that they are in the same position relative\n to the ids around them in old_ids.\"\"\"\n before = [(id, set(old_ids[:i])) for (i, id) in enumerate(old_ids) if isadspot(id)]\n for (ad, ids_before) in before:\n for i in range(len(new_ids) - 1, -1, -1):\n if new_ids[i] in ids_before:\n new_ids.insert(i + 1, ad)\n break","code_tokens":"","url":185982} +{"project_name":"nhsx\/SynthVAE","file_name":"performance.py","full_name":"evaluate_transformer_performance","func_name":"evaluate_transformer_performance","docstring":"Evaluate the given transformer's performance against the given dataset generator.","docstring_tokens":"","code":"def evaluate_transformer_performance(transformer, dataset_generator, verbose=False):\n \"\"\"Evaluate the given transformer's performance against the given dataset generator.\n\n Args:\n transformer (rdt.transformers.BaseTransformer):\n The transformer to evaluate.\n dataset_generator (rdt.tests.datasets.BaseDatasetGenerator):\n The dataset generator to performance test against.\n verbose (bool):\n Whether or not to add extra columns about the dataset and transformer,\n and return data for all dataset sizes. If false, it will only return\n the max performance values of all the dataset sizes used.\n\n Returns:\n pandas.DataFrame:\n The performance test results.\n \"\"\"\n transformer_instance = transformer()\n sizes = _get_dataset_sizes(dataset_generator.DATA_TYPE)\n out = []\n for (fit_size, transform_size) in sizes:\n performance = profile_transformer(transformer=transformer_instance, dataset_generator=dataset_generator, fit_size=fit_size, transform_size=transform_size)\n size = np.array([fit_size, transform_size, transform_size] * 2)\n performance = performance \/ size\n if verbose:\n performance = performance.rename(lambda x: x + ' (s)' if 'Time' in x else x + ' (B)')\n performance['Number of fit rows'] = fit_size\n performance['Number of transform rows'] = transform_size\n performance['Dataset'] = dataset_generator.__name__\n performance['Transformer'] = f'{transformer.__module__}.{transformer.__name__}'\n out.append(performance)\n summary = pd.DataFrame(out)\n if verbose:\n return summary\n return summary.max(axis=0)","code_tokens":"","url":906279} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"woff2.py","full_name":"decompress","func_name":"decompress","docstring":"Decompress WOFF2 font to OpenType font.","docstring_tokens":"","code":"def decompress(input_file, output_file):\n \"\"\"Decompress WOFF2 font to OpenType font.\n\n Args:\n input_file: a file path, file or file-like object (open in binary mode)\n containing a compressed WOFF2 font.\n output_file: a file path, file or file-like object where to save the\n decompressed OpenType font.\n \"\"\"\n log.info('Processing %s => %s' % (input_file, output_file))\n font = TTFont(input_file, recalcBBoxes=False, recalcTimestamp=False)\n font.flavor = None\n font.flavorData = None\n font.save(output_file, reorderTables=True)","code_tokens":"","url":361215} +{"project_name":"rudranil723\/mini-main","file_name":"models.py","full_name":"CharsetMatch.encoding_aliases","func_name":"encoding_aliases","docstring":"Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.","docstring_tokens":"","code":"@property\ndef encoding_aliases(self) -> List[str]:\n \"\"\"\n Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855.\n \"\"\"\n also_known_as: List[str] = []\n for (u, p) in aliases.items():\n if self.encoding == u:\n also_known_as.append(p)\n elif self.encoding == p:\n also_known_as.append(u)\n return also_known_as","code_tokens":"","url":314324} +{"project_name":"aws-deepracer\/aws-deepracer-follow-the-leader-sample-project","file_name":"utility.py","full_name":"is_network_inactive","func_name":"is_network_inactive","docstring":"Check if the supplied SSID is currently not connected, but previously connected.","docstring_tokens":"","code":"def is_network_inactive(ssid):\n \"\"\"Check if the supplied SSID is currently not connected, but previously connected.\n\n Args:\n ssid (str): SSID value.\n\n Returns:\n bool: True if the SSID is inactive else False.\n \"\"\"\n webserver_node = webserver_publisher_node.get_webserver_node()\n webserver_node.get_logger().info(f'Checking if ssid: {ssid} is inactive')\n is_present = False\n stdout = execute('\/usr\/bin\/nmcli -t -f name -e no con show', shlex_split=True)[1]\n for line in stdout.splitlines():\n if line == ssid:\n is_present = True\n break\n if is_present and (not is_network_connected(ssid)):\n return True\n return False","code_tokens":"","url":421230} +{"project_name":"Alexander-Parker\/youtube_nlp","file_name":"jwt.py","full_name":"Credentials.refresh","func_name":"refresh","docstring":"Refreshes the access token.","docstring_tokens":"","code":"def refresh(self, request):\n \"\"\"Refreshes the access token.\n\n Args:\n request (Any): Unused.\n \"\"\"\n (self.token, self.expiry) = self._make_jwt()","code_tokens":"","url":970015} +{"project_name":"thaines\/helit","file_name":"corpus.py","full_name":"Corpus.getBeta","func_name":"getBeta","docstring":"Returns the current beta value.","docstring_tokens":"","code":"def getBeta(self):\n \"\"\"Returns the current beta value.\"\"\"\n return self.beta","code_tokens":"","url":592050} +{"project_name":"thuml\/Transfer-Learning-Library","file_name":"freihand.py","full_name":"db_size","func_name":"db_size","docstring":"Hardcoded size of the datasets.","docstring_tokens":"","code":"def db_size(set_name):\n \"\"\" Hardcoded size of the datasets. \"\"\"\n if set_name == 'training':\n return 32560\n elif set_name == 'evaluation':\n return 3960\n else:\n assert 0, 'Invalid choice.'","code_tokens":"","url":921316} +{"project_name":"materialsvirtuallab\/mlearn","file_name":"nnp.py","full_name":"NNPotential.from_config","func_name":"from_config","docstring":"Initialize potentials with parameters file.","docstring_tokens":"","code":"@staticmethod\ndef from_config(input_filename, scaling_filename, weights_filename):\n \"\"\"\n Initialize potentials with parameters file.\n\n Args:\n input_filename (str): The file storing the input configuration of\n Neural Network Potential.\n scaling_filename (str): The file storing scaling info of\n Neural Network Potential.\n weights_filename (str): The file storing weights of\n Neural Network Potential.\n \"\"\"\n nnp = NNPotential()\n nnp.load_input(input_filename)\n nnp.load_scaler(scaling_filename)\n nnp.load_weights(weights_filename)\n nnp.fitted = True\n return nnp","code_tokens":"","url":630317} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"subprocess.py","full_name":"make_command","func_name":"make_command","docstring":"Create a CommandArgs object.","docstring_tokens":"","code":"def make_command(*args):\n \"\"\"\n Create a CommandArgs object.\n \"\"\"\n command_args = []\n for arg in args:\n if isinstance(arg, list):\n command_args.extend(arg)\n else:\n command_args.append(arg)\n return command_args","code_tokens":"","url":215979} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"offsetbox.py","full_name":"TextArea.get_window_extent","func_name":"get_window_extent","docstring":"get the bounding box in display space.","docstring_tokens":"","code":"def get_window_extent(self, renderer):\n \"\"\"\n get the bounding box in display space.\n \"\"\"\n (w, h, xd, yd) = self.get_extent(renderer)\n (ox, oy) = self.get_offset()\n return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)","code_tokens":"","url":750} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"export_tflite_graph_lib_tf2.py","full_name":"SSDModule.input_shape","func_name":"input_shape","docstring":"Returns shape of TFLite model input.","docstring_tokens":"","code":"def input_shape(self):\n \"\"\"Returns shape of TFLite model input.\"\"\"\n return [1, self._height, self._width, self._num_channels]","code_tokens":"","url":851943} +{"project_name":"jialeli1\/lidarseg3d","file_name":"semanticwaymo_common.py","full_name":"dummy_semseg_for_one_frame","func_name":"dummy_semseg_for_one_frame","docstring":"Assign all valid points to a single dummy class.","docstring_tokens":"","code":"def dummy_semseg_for_one_frame(frame, dummy_class=14):\n \"\"\"Assign all valid points to a single dummy class.\n\n Args:\n frame: An Open Dataset Frame proto.\n dummy_class: The class to assign to. Default is 14 (building).\n\n Returns:\n segmentation_frame: A SegmentationFrame proto.\n \"\"\"\n (range_images, camera_projections, segmentation_labels, range_image_top_pose) = frame_utils.parse_range_image_and_camera_projection(frame)\n points_indexing_top = get_range_image_point_indexing(range_images, ri_index=0)\n points_indexing_top_ri2 = get_range_image_point_indexing(range_images, ri_index=1)\n range_image_pred = np.zeros((TOP_LIDAR_ROW_NUM, TOP_LIDAR_COL_NUM, 2), dtype=np.int32)\n range_image_pred[points_indexing_top[:, 1], points_indexing_top[:, 0], 1] = dummy_class\n range_image_pred_ri2 = np.zeros((TOP_LIDAR_ROW_NUM, TOP_LIDAR_COL_NUM, 2), dtype=np.int32)\n range_image_pred_ri2[points_indexing_top_ri2[:, 1], points_indexing_top_ri2[:, 0], 1] = dummy_class\n segmentation_frame = segmentation_metrics_pb2.SegmentationFrame()\n segmentation_frame.context_name = frame.context.name\n segmentation_frame.frame_timestamp_micros = frame.timestamp_micros\n laser_semseg = open_dataset.Laser()\n laser_semseg.name = open_dataset.LaserName.TOP\n laser_semseg.ri_return1.segmentation_label_compressed = compress_array(range_image_pred, is_int32=True)\n laser_semseg.ri_return2.segmentation_label_compressed = compress_array(range_image_pred_ri2, is_int32=True)\n segmentation_frame.segmentation_labels.append(laser_semseg)\n return segmentation_frame","code_tokens":"","url":601471} +{"project_name":"shervinea\/enzynet","file_name":"tools.py","full_name":"dict_to_csv","func_name":"dict_to_csv","docstring":"Saves Python dictionary to a csv file.","docstring_tokens":"","code":"def dict_to_csv(dictionary: Dict[Any, Any], path: Text) -> None:\n \"\"\"Saves Python dictionary to a csv file.\"\"\"\n w = csv.writer(open(path, 'w'))\n for (key, val) in dictionary.items():\n w.writerow([key, val])","code_tokens":"","url":178220} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"inputs_test.py","full_name":"NegativeSizeTest.test_negative_size_error","func_name":"test_negative_size_error","docstring":"Test that error is raised for negative size boxes.","docstring_tokens":"","code":"def test_negative_size_error(self):\n \"\"\"Test that error is raised for negative size boxes.\"\"\"\n\n def graph_fn():\n tensors = {fields.InputDataFields.image: tf.zeros((128, 128, 3)), fields.InputDataFields.groundtruth_classes: tf.constant([1, 1], tf.int32), fields.InputDataFields.groundtruth_boxes: tf.constant([[0.5, 0.5, 0.4, 0.5]], tf.float32)}\n tensors = inputs.transform_input_data(tensors, _fake_model_preprocessor_fn, _fake_image_resizer_fn, num_classes=10)\n return tensors[fields.InputDataFields.groundtruth_boxes]\n with self.assertRaises(tf.errors.InvalidArgumentError):\n self.execute_cpu(graph_fn, [])","code_tokens":"","url":851976} +{"project_name":"matsu0228\/nlp-jp","file_name":"connection.py","full_name":"FPSConnection.fund_prepaid","func_name":"fund_prepaid","docstring":"Funds the prepaid balance on the given prepaid instrument.","docstring_tokens":"","code":"@needs_caller_reference\n@complex_amounts('FundingAmount')\n@requires(['PrepaidInstrumentId', 'FundingAmount.Value', 'SenderTokenId', 'FundingAmount.CurrencyCode'])\n@api_action()\ndef fund_prepaid(self, action, response, **kw):\n \"\"\"\n Funds the prepaid balance on the given prepaid instrument.\n \"\"\"\n return self.get_object(action, kw, response)","code_tokens":"","url":784637} +{"project_name":"ludwig-ai\/ludwig","file_name":"test_date_utils.py","full_name":"test_convert_number_to_datetime","func_name":"test_convert_number_to_datetime","docstring":"Ensure that numeric timestamps are correctly converted to datetime objects.","docstring_tokens":"","code":"@pytest.mark.parametrize('timestamp,raises', [pytest.param(1691600953.443032, does_not_raise(), id='float-s'), pytest.param(1691600953443.032, does_not_raise(), id='float-ms'), pytest.param(1691600953, does_not_raise(), id='int-s'), pytest.param(1691600953443, does_not_raise(), id='int-ms'), pytest.param('1691600953.443032', does_not_raise(), id='string[float]-s'), pytest.param('1691600953443.0032', does_not_raise(), id='string[float]-ms'), pytest.param('1691600953', does_not_raise(), id='string[int]-s'), pytest.param('1691600953443', does_not_raise(), id='string[int]-ms'), pytest.param('foo', pytest.raises(ValueError), id='string error'), pytest.param([1691600953.443032], pytest.raises(ValueError), id='list error'), pytest.param(datetime.datetime(2023, 8, 9, 13, 9, 13), pytest.raises(ValueError), id='datetime error'), pytest.param(None, pytest.raises(ValueError), id='NoneType error')])\ndef test_convert_number_to_datetime(reference_datetime: datetime.datetime, timestamp: Any, raises: ContextManager):\n \"\"\"Ensure that numeric timestamps are correctly converted to datetime objects.\n\n Args:\n reference_datetime: A datetime object with the expected date\/time\n timestamp: The timestamp to convert in s or ms\n raises: context manager to check for expected exceptions\n \"\"\"\n with raises:\n dt = convert_number_to_datetime(timestamp)\n assert dt.year == reference_datetime.year\n assert dt.month == reference_datetime.month\n assert dt.day == reference_datetime.day\n assert dt.hour == reference_datetime.hour\n assert dt.minute == reference_datetime.minute\n assert dt.second == reference_datetime.second","code_tokens":"","url":617411} +{"project_name":"zcablii\/LSKNet","file_name":"test_loss.py","full_name":"test_convex_regression_losses","func_name":"test_convex_regression_losses","docstring":"Tests convex regression losses.","docstring_tokens":"","code":"@pytest.mark.skipif(not torch.cuda.is_available(), reason='requires CUDA support')\n@pytest.mark.parametrize('loss_class', [BCConvexGIoULoss, ConvexGIoULoss, KLDRepPointsLoss])\ndef test_convex_regression_losses(loss_class):\n \"\"\"Tests convex regression losses.\n\n Args:\n loss_class (str): type of convex loss.\n \"\"\"\n pred = torch.rand((10, 18)).cuda()\n target = torch.rand((10, 8)).cuda()\n weight = torch.rand((10,)).cuda()\n loss = loss_class()(pred, target)\n assert isinstance(loss, torch.Tensor)\n loss = loss_class()(pred, target, weight)\n assert isinstance(loss, torch.Tensor)\n loss = loss_class()(pred, target, reduction_override='mean')\n assert isinstance(loss, torch.Tensor)\n loss = loss_class()(pred, target, avg_factor=10)\n assert isinstance(loss, torch.Tensor)","code_tokens":"","url":616264} +{"project_name":"jimtin\/Stock_Comparison","file_name":"graph_objs.py","full_name":"PlotlyList.append","func_name":"append","docstring":"Override to enforce validation.","docstring_tokens":"","code":"def append(self, value):\n \"\"\"Override to enforce validation.\"\"\"\n index = len(self)\n value = self._value_to_graph_object(index, value)\n super(PlotlyList, self).append(value)","code_tokens":"","url":389219} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"mlab.py","full_name":"eye","func_name":"eye","docstring":"eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros.","docstring_tokens":"","code":"def eye(N, M=None, k=0, typecode=None, dtype=None):\n \"\"\" eye returns a N-by-M 2-d array where the k-th diagonal is all ones,\n and everything else is zeros.\n \"\"\"\n dtype = convtypecode(typecode, dtype)\n if M is None:\n M = N\n m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)), -k)\n if m.dtype != dtype:\n return m.astype(dtype)","code_tokens":"","url":532465} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"structs.py","full_name":"DirectedGraph.copy","func_name":"copy","docstring":"Return a shallow copy of this graph.","docstring_tokens":"","code":"def copy(self):\n \"\"\"Return a shallow copy of this graph.\n \"\"\"\n other = DirectedGraph()\n other._vertices = set(self._vertices)\n other._forwards = {k: set(v) for (k, v) in self._forwards.items()}\n other._backwards = {k: set(v) for (k, v) in self._backwards.items()}\n return other","code_tokens":"","url":99136} +{"project_name":"HLTCHKUST\/CAiRE-COVID","file_name":"predictor_kaggle.py","full_name":"mrqa_predictor","func_name":"mrqa_predictor","docstring":"Get prediction with the data got fron mrqa official request.","docstring_tokens":"","code":"def mrqa_predictor(FLAGS, predict_fn, data):\n \"\"\"\n Get prediction with the data got fron mrqa official request.\n \"\"\"\n tf.logging.set_verbosity(tf.logging.INFO)\n sp_model = spm.SentencePieceProcessor()\n sp_model.Load(FLAGS.spiece_model_file)\n tf.logging.info('Got Data from IR system...')\n eval_data = arrange_kaggle_data(data, is_training=False)\n eval_writer = FeatureWriter(is_training=False)\n eval_features = []\n eval_features_inp = []\n\n def append_feature(feature):\n eval_features.append(feature)\n eval_features_inp.append(eval_writer.process_feature(feature))\n convert_examples_to_features(examples=eval_data, sp_model=sp_model, max_seq_length=FLAGS.max_seq_length, doc_stride=FLAGS.doc_stride, max_query_length=FLAGS.max_query_length, is_training=False, output_fn=append_feature, FLAGS=FLAGS)\n cur_results = []\n for (num, eval_feature) in enumerate(eval_features_inp):\n result = predict_fn({'examples': [eval_feature]})\n if len(cur_results) % 1000 == 0:\n tf.logging.info('Processing example: %d' % len(cur_results))\n unique_id = int(result['unique_ids'])\n start_top_log_probs = [float(x) for x in result['start_top_log_probs'].flat]\n start_top_index = [int(x) for x in result['start_top_index'].flat]\n end_top_log_probs = [float(x) for x in result['end_top_log_probs'].flat]\n end_top_index = [int(x) for x in result['end_top_index'].flat]\n cls_logits = float(result['cls_logits'].flat[0])\n cur_results.append(RawResult(unique_id=unique_id, start_top_log_probs=start_top_log_probs, start_top_index=start_top_index, end_top_log_probs=end_top_log_probs, end_top_index=end_top_index, cls_logits=cls_logits))\n ret = get_predictions(eval_data, eval_features, cur_results, FLAGS.n_best_size, FLAGS.max_answer_length, FLAGS)\n return dict(ret)","code_tokens":"","url":410990} +{"project_name":"facebookresearch\/rlmeta","file_name":"rescalers.py","full_name":"Rescaler.recover","func_name":"recover","docstring":"Undo rescale for the input tensor.","docstring_tokens":"","code":"@abc.abstractmethod\ndef recover(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Undo rescale for the input tensor.\n \"\"\"","code_tokens":"","url":862891} +{"project_name":"Khan\/guacamole","file_name":"engine.py","full_name":"ItemResponse.exercise","func_name":"exercise","docstring":"Getter for whether the slug of the exercise connected with the item Returns: a string.","docstring_tokens":"","code":"@property\ndef exercise(self):\n \"\"\"Getter for whether the slug of the exercise connected with the item\n\n Returns: a string.\"\"\"\n return self.data.get('exercise')","code_tokens":"","url":572166} +{"project_name":"OctoConsulting\/octobot","file_name":"describe_bot_status.py","full_name":"bot_name_from_url","func_name":"bot_name_from_url","docstring":"Makes a unique bot name from the base url from the base url and the path url.","docstring_tokens":"","code":"def bot_name_from_url(url: str) -> str:\n \"\"\"Makes a unique bot name from the base url from the base url and the\n path url.\n\n Args:\n url: A well-formed URL.\n\n Returns:\n The base url as a titlecased, no-space, no-puncutation string.\n \"\"\"\n base_url = urlparse(url).netloc\n path = urlparse(url).path\n path_parts = path.split('\/')[1:]\n path_hash = ''.join([pp[:2] for pp in path_parts])[:10]\n return convert_to_title(base_url + path_hash)","code_tokens":"","url":249992} +{"project_name":"kykiefer\/depression-detect","file_name":"segmentation.py","full_name":"concatenate_segments","func_name":"concatenate_segments","docstring":"A function that concatenates all the wave files in a participants directory in to single wav file (with silence and other speakers removed) and writes in to the participant's directory, then removes the individual segments (when remove_segment=True).","docstring_tokens":"","code":"def concatenate_segments(participant_dir, partic_id, remove_segment=True):\n \"\"\"\n A function that concatenates all the wave files in a participants\n directory in to single wav file (with silence and other speakers removed)\n and writes in to the participant's directory, then removes the individual\n segments (when remove_segment=True).\n \"\"\"\n infiles = os.listdir(participant_dir)\n outfile = '{}_no_silence.wav'.format(partic_id)\n data = []\n for infile in infiles:\n w = wave.open(infile, 'rb')\n data.append([w.getparams(), w.readframes(w.getnframes())])\n w.close()\n if remove_segment:\n os.remove(infile)\n output = wave.open(outfile, 'wb')\n output.setparams(data[0][0])\n for idx in range(len(data)):\n output.writeframes(data[idx][1])\n output.close()","code_tokens":"","url":183933} +{"project_name":"drckf\/paysage","file_name":"shuffle.py","full_name":"DataShuffler.reassemble_table","func_name":"reassemble_table","docstring":"Takes a set of chunked tables and rebuilds the shuffled table.","docstring_tokens":"","code":"def reassemble_table(self, key, num_chunks, chunk_keys, chunk_counts):\n \"\"\"\n Takes a set of chunked tables and rebuilds the shuffled table.\n\n Args:\n key (str): the key of the table to shuffle.\n num_chunks (int): the number of chunks the table was divided into.\n chunk_keys (List[str]): the keys of the chunks in the temporary file.\n chunk_counts (List[int]): the number of samples in each of the chunks.\n\n Returns:\n None\n\n \"\"\"\n stream_map = numpy.concatenate([[i for _ in range(chunk_counts[i])] for i in range(len(chunk_counts))])\n numpy.random.shuffle(stream_map)\n chunk_read_inds = [0 for _ in range(num_chunks)]\n num_streamed = 0\n for i_chunk in range(num_chunks):\n chunk_inds = stream_map[i_chunk * self.chunksize:(i_chunk + 1) * self.chunksize]\n chunk_read_counts = [numpy.sum(chunk_inds == j) for j in range(num_chunks)]\n chunk_pieces = [None for _ in range(num_chunks)]\n for j in range(num_chunks):\n num_read = chunk_read_counts[j]\n chunk_pieces[j] = self.chunk_store.select(chunk_keys[j], start=chunk_read_inds[j], stop=chunk_read_inds[j] + num_read)\n chunk_read_inds[j] += num_read\n df_chunk = pandas.concat(chunk_pieces)\n df_chunk = df_chunk.sample(frac=1)\n num_streamed += len(df_chunk)\n self.shuffled_store.append(key, df_chunk)","code_tokens":"","url":278669} +{"project_name":"openml-labs\/gama","file_name":"parser.py","full_name":"merge_configurations","func_name":"merge_configurations","docstring":"Takes two configurations and merges them together.","docstring_tokens":"","code":"def merge_configurations(c1: Dict, c2: Dict) -> Dict:\n \"\"\"Takes two configurations and merges them together.\"\"\"\n merged: Dict[Any, Any] = defaultdict(lambda : None, c1)\n for (algorithm, hparams2) in c2.items():\n if algorithm not in merged:\n merged[algorithm] = hparams2\n continue\n hparams = merged[algorithm]\n if isinstance(hparams, list) and isinstance(hparams2, list):\n merged[algorithm] = list(set(hparams + hparams2))\n continue\n for (hyperparameter, values) in hparams2.items():\n if hyperparameter not in hparams:\n hparams[hyperparameter] = values\n continue\n values1 = hparams[hyperparameter]\n if isinstance(values1, dict) and isinstance(values, dict):\n hparams[hyperparameter] = {**values1, **values}\n elif isinstance(values1, type(values)):\n hparams[hyperparameter] = list(set(list(values1) + list(values)))\n else:\n raise TypeError(f'Could not merge values of {algorithm}.{hyperparameter}:{hparams} vs. {hparams2}')\n return merged","code_tokens":"","url":566138} +{"project_name":"megvii-research\/MSCL","file_name":"ssn_loss.py","full_name":"SSNLoss.forward","func_name":"forward","docstring":"Calculate Boundary Matching Network Loss.","docstring_tokens":"","code":"def forward(self, activity_score, completeness_score, bbox_pred, proposal_type, labels, bbox_targets, train_cfg):\n \"\"\"Calculate Boundary Matching Network Loss.\n\n Args:\n activity_score (torch.Tensor): Predicted activity score.\n completeness_score (torch.Tensor): Predicted completeness score.\n bbox_pred (torch.Tensor): Predicted interval center and span\n of positive proposals.\n proposal_type (torch.Tensor): Type index slices of proposals.\n labels (torch.Tensor): Groundtruth class label.\n bbox_targets (torch.Tensor): Groundtruth center and span\n of positive proposals.\n train_cfg (dict): Config for training.\n\n Returns:\n dict([torch.Tensor, torch.Tensor, torch.Tensor]):\n (loss_activity, loss_completeness, loss_reg).\n Loss_activity is the activity loss, loss_completeness is\n the class-wise completeness loss,\n loss_reg is the class-wise regression loss.\n \"\"\"\n self.sampler = train_cfg.ssn.sampler\n self.loss_weight = train_cfg.ssn.loss_weight\n losses = dict()\n proposal_type = proposal_type.view(-1)\n labels = labels.view(-1)\n activity_indexer = ((proposal_type == 0) + (proposal_type == 2)).nonzero().squeeze(1)\n completeness_indexer = ((proposal_type == 0) + (proposal_type == 1)).nonzero().squeeze(1)\n total_ratio = self.sampler.positive_ratio + self.sampler.background_ratio + self.sampler.incomplete_ratio\n positive_per_video = int(self.sampler.num_per_video * (self.sampler.positive_ratio \/ total_ratio))\n background_per_video = int(self.sampler.num_per_video * (self.sampler.background_ratio \/ total_ratio))\n incomplete_per_video = self.sampler.num_per_video - positive_per_video - background_per_video\n losses['loss_activity'] = self.activity_loss(activity_score, labels, activity_indexer)\n losses['loss_completeness'] = self.completeness_loss(completeness_score, labels, completeness_indexer, positive_per_video, incomplete_per_video, ohem_ratio=positive_per_video \/ incomplete_per_video)\n losses['loss_completeness'] *= self.loss_weight.comp_loss_weight\n if bbox_pred is not None:\n regression_indexer = (proposal_type == 0).nonzero().squeeze(1)\n bbox_targets = bbox_targets.view(-1, 2)\n losses['loss_reg'] = self.classwise_regression_loss(bbox_pred, labels, bbox_targets, regression_indexer)\n losses['loss_reg'] *= self.loss_weight.reg_loss_weight\n return losses","code_tokens":"","url":264949} +{"project_name":"ashwin-phadke\/cvplayground","file_name":"flask_server.py","full_name":"show_segmentation_form","func_name":"show_segmentation_form","docstring":"Returns the template to upload image and choose model to perform semantic segmentation using Deeplab v3.","docstring_tokens":"","code":"@app.route('\/segmentation_upload_page', methods=['GET', 'POST'])\ndef show_segmentation_form():\n \"\"\"\n Returns the template to upload image and choose model\n to perform semantic segmentation using Deeplab v3.\n \"\"\"\n return render_template('modelselectsegmentationindex.html')","code_tokens":"","url":510474} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_axes.py","full_name":"test_stem_args","func_name":"test_stem_args","docstring":"Test that stem() correctly identifies x and y values.","docstring_tokens":"","code":"def test_stem_args():\n \"\"\"Test that stem() correctly identifies x and y values.\"\"\"\n\n def _assert_equal(stem_container, expected):\n (x, y) = map(list, stem_container.markerline.get_data())\n assert x == expected[0]\n assert y == expected[1]\n (fig, ax) = plt.subplots()\n x = [1, 3, 5]\n y = [9, 8, 7]\n _assert_equal(ax.stem(y), expected=([0, 1, 2], y))\n _assert_equal(ax.stem(x, y), expected=(x, y))\n _assert_equal(ax.stem(x, y, linefmt='r--'), expected=(x, y))\n _assert_equal(ax.stem(x, y, 'r--'), expected=(x, y))\n _assert_equal(ax.stem(x, y, linefmt='r--', basefmt='b--'), expected=(x, y))\n _assert_equal(ax.stem(y, linefmt='r--'), expected=([0, 1, 2], y))\n _assert_equal(ax.stem(y, 'r--'), expected=([0, 1, 2], y))","code_tokens":"","url":362769} +{"project_name":"rlpy\/rlpy","file_name":"IndependentDiscretizationCompactBinary.py","full_name":"IndependentDiscretizationCompactBinary.getDimNumber","func_name":"getDimNumber","docstring":"Returns the dimension number corresponding to feature ``f``.","docstring_tokens":"","code":"def getDimNumber(self, f):\n \"\"\" Returns the dimension number corresponding to feature ``f``. \"\"\"\n dim = np.searchsorted(self.maxFeatureIDperDimension, f)\n return dim","code_tokens":"","url":334236} +{"project_name":"heynemann\/pyvows","file_name":"common.py","full_name":"VowsReporter.indent_msg","func_name":"indent_msg","docstring":"Returns `msg` with the indentation specified by `indentation`.","docstring_tokens":"","code":"def indent_msg(self, msg, indentation=None):\n \"\"\"Returns `msg` with the indentation specified by `indentation`.\n\n \"\"\"\n if indentation is not None:\n indent = self.TAB * indentation\n else:\n indent = self.TAB * self.indent\n return '{indent}{msg}'.format(indent=indent, msg=msg)","code_tokens":"","url":302621} +{"project_name":"thaines\/helit","file_name":"student_t.py","full_name":"StudentT.getInvScale","func_name":"getInvScale","docstring":"Returns the inverse of the scale matrix.","docstring_tokens":"","code":"def getInvScale(self):\n \"\"\"Returns the inverse of the scale matrix.\"\"\"\n if self.invScale is None:\n self.invScale = numpy.linalg.inv(self.scale)\n return self.invScale","code_tokens":"","url":591689} +{"project_name":"MycroftAI\/mycroft-core","file_name":"intent_service_interface.py","full_name":"IntentServiceInterface.intent_is_detached","func_name":"intent_is_detached","docstring":"Determine if an intent is detached.","docstring_tokens":"","code":"def intent_is_detached(self, intent_name):\n \"\"\"Determine if an intent is detached.\n\n Args:\n intent_name(str): Intent reference\n\n Returns:\n (bool) True if intent is found, else False.\n \"\"\"\n for (name, _) in self.detached_intents:\n if name == intent_name:\n return True\n return False","code_tokens":"","url":290504} +{"project_name":"OliverKillane\/NuNet-Designer","file_name":"NuNetLibrary.py","full_name":"LossFunctions.logloss","func_name":"logloss","docstring":"Logloss (Log Loss) loss function, used for binary classifiers.","docstring_tokens":"","code":"@staticmethod\ndef logloss(label: float, predicted: float, constant: float=0) -> FuncReturn:\n \"\"\"Logloss (Log Loss) loss function, used for binary classifiers.\"\"\"\n if label == 1:\n return FuncReturn(result=-log1p(predicted), derivative=-1 \/ log1p(predicted))\n elif label == 0:\n return FuncReturn(result=-log1p(1 - predicted), derivative=-1 \/ (1 - predicted))","code_tokens":"","url":730498} +{"project_name":"AndrewSpano\/BSc-Thesis","file_name":"plot_utils.py","full_name":"plot_confusion_matrix","func_name":"plot_confusion_matrix","docstring":"Plots and saves the given confusion matrix as a heatmap.","docstring_tokens":"","code":"def plot_confusion_matrix(cm: torch.Tensor, classes: List[str], savepath: Path) -> None:\n \"\"\"Plots and saves the given confusion matrix as a heatmap.\"\"\"\n df_cm = pd.DataFrame(cm.cpu(), index=classes, columns=classes)\n plt.figure(figsize=(16, 11))\n sns.heatmap(df_cm, annot=True, fmt='d', cmap=sns.cm.rocket_r)\n if not savepath.parent.is_dir():\n os.makedirs(savepath.parent)\n plt.savefig(savepath, bbox_inches='tight')","code_tokens":"","url":410091} +{"project_name":"voxel51\/fiftyone","file_name":"fields.py","full_name":"EmbeddedDocumentField.get_field_schema","func_name":"get_field_schema","docstring":"Returns a schema dictionary describing the fields of the embedded document field.","docstring_tokens":"","code":"def get_field_schema(self, ftype=None, embedded_doc_type=None, include_private=False, flat=False):\n \"\"\"Returns a schema dictionary describing the fields of the embedded\n document field.\n\n Args:\n ftype (None): an optional field type or iterable of types to which\n to restrict the returned schema. Must be subclass(es) of\n :class:`Field`\n embedded_doc_type (None): an optional embedded document type or\n iterable of types to which to restrict the returned schema.\n Must be subclass(es) of\n :class:`fiftyone.core.odm.BaseEmbeddedDocument`\n include_private (False): whether to include fields that start with\n ``_`` in the returned schema\n flat (False): whether to return a flattened schema where all\n embedded document fields are included as top-level keys\n\n Returns:\n a dict mapping field names to field types\n \"\"\"\n validate_type_constraints(ftype=ftype, embedded_doc_type=embedded_doc_type)\n schema = {}\n for name in self._get_field_names(include_private=include_private):\n field = self._fields[name]\n if matches_type_constraints(field, ftype=ftype, embedded_doc_type=embedded_doc_type):\n schema[name] = field\n if flat:\n schema = flatten_schema(schema, ftype=ftype, embedded_doc_type=embedded_doc_type, include_private=include_private)\n return schema","code_tokens":"","url":583113} +{"project_name":"rudranil723\/mini-main","file_name":"common.py","full_name":"classes_and_not_datetimelike","func_name":"classes_and_not_datetimelike","docstring":"Evaluate if the tipo is a subclass of the klasses and not a datetimelike.","docstring_tokens":"","code":"def classes_and_not_datetimelike(*klasses) -> Callable:\n \"\"\"\n Evaluate if the tipo is a subclass of the klasses\n and not a datetimelike.\n \"\"\"\n return lambda tipo: issubclass(tipo, klasses) and (not issubclass(tipo, (np.datetime64, np.timedelta64)))","code_tokens":"","url":323671} +{"project_name":"triaquae\/triaquae","file_name":"field.py","full_name":"Field.precision","func_name":"precision","docstring":"Returns the precision of this Field.","docstring_tokens":"","code":"@property\ndef precision(self):\n \"\"\"Returns the precision of this Field.\"\"\"\n return capi.get_field_precision(self.ptr)","code_tokens":"","url":357554} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"doc.py","full_name":"set_curdoc","func_name":"set_curdoc","docstring":"Configure the current document (returned by curdoc()).","docstring_tokens":"","code":"@dev((1, 0, 0))\ndef set_curdoc(doc):\n \"\"\"Configure the current document (returned by curdoc()).\n\n Args:\n doc (Document) : Document we will output.\n\n Returns:\n None\n\n .. warning::\n Calling this function will replace any existing document.\n\n \"\"\"\n from .state import curstate\n curstate().document = doc","code_tokens":"","url":977348} +{"project_name":"Emory-HITI\/Niffler","file_name":"ColdDataRetriever.py","full_name":"retrieve","func_name":"retrieve","docstring":"The core DICOM on-demand retrieve process to retrieve the images or metadata.","docstring_tokens":"","code":"def retrieve():\n \"\"\"\n The core DICOM on-demand retrieve process to retrieve the images or metadata.\n \"\"\"\n if file_path == cfind_only or file_path == cfind_detailed:\n if not os.path.exists(temp_folder):\n os.makedirs(temp_folder)\n if number_of_query_attributes > 3 or number_of_query_attributes <= 1:\n if first_attr == 'PatientID':\n for pid in range(0, length):\n sleep_for_nightly_mode()\n patient = firsts[pid]\n if not resume or (resume and patient not in extracted_ones):\n if file_path == cfind_only or file_path == cfind_detailed:\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -M PatientRoot -m PatientID={3} -r AccessionNumber -r StudyInstanceUID {4} --out-cat --out-file {5} --out-dir {6}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, cfind_add, temp_file, out_folder), shell=True)\n else:\n subprocess.call('{0}\/movescu -c {1} -b {2} -M PatientRoot -m PatientID={3} --dest {4}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, DEST_AET), shell=True)\n extracted_ones.append(patient)\n merge_temp_files()\n else:\n for pid in range(0, length):\n sleep_for_nightly_mode()\n first = firsts[pid]\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -m {3}={4} -r PatientID -r StudyInstanceUID {5} --out-cat --out-file {6} --out-dir {7}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, first_attr, first, cfind_add, temp_file, out_folder), shell=True)\n if not (file_path == cfind_only or file_path == cfind_detailed):\n extract_empi_study()\n merge_temp_files()\n elif number_of_query_attributes == 2:\n empi_accession_mode = False\n empi_study_mode = False\n patients = []\n accessions = []\n studies = []\n if first_attr == 'PatientID' and second_attr == 'AccessionNumber':\n empi_accession_mode = True\n patients = firsts\n accessions = seconds\n elif first_attr == 'AccessionNumber' and second_attr == 'PatientID':\n empi_accession_mode = True\n patients = seconds\n accessions = firsts\n elif first_attr == 'PatientID' and second_attr == 'StudyInstanceUID':\n empi_study_mode = True\n patients = firsts\n studies = seconds\n elif first_attr == 'StudyInstanceUID' and second_attr == 'PatientID':\n empi_study_mode = True\n patients = seconds\n studies = firsts\n if empi_accession_mode:\n for pid in range(0, length):\n sleep_for_nightly_mode()\n accession = accessions[pid]\n patient = patients[pid]\n temp_id = patient + SEPARATOR + accession\n if not resume or (resume and temp_id not in extracted_ones):\n if file_path == cfind_only or file_path == cfind_detailed:\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -M PatientRoot -m PatientID={3} -m AccessionNumber={4} -r StudyInstanceUID {5} --out-cat --out-file {6} --out-dir {7}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, accession, cfind_add, temp_file, out_folder), shell=True)\n else:\n subprocess.call('{0}\/movescu -c {1} -b {2} -M PatientRoot -m PatientID={3} -m AccessionNumber={4} --dest {5}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, accession, DEST_AET), shell=True)\n extracted_ones.append(temp_id)\n merge_temp_files()\n elif empi_study_mode:\n for pid in range(0, length):\n sleep_for_nightly_mode()\n study = studies[pid]\n patient = patients[pid]\n temp_id = patient + SEPARATOR + study\n if not resume or (resume and temp_id not in extracted_ones):\n if file_path == cfind_only or file_path == cfind_detailed:\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -M PatientRoot -m PatientID={3} -m StudyInstanceUID={4} -r AccessionNumber {5} --out-cat --out-file {6} --out-dir {7}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, study, cfind_add, temp_file, out_folder), shell=True)\n else:\n subprocess.call('{0}\/movescu -c {1} -b {2} -m PatientID={3} -m StudyInstanceUID={4} --dest {5}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, patient, study, DEST_AET), shell=True)\n extracted_ones.append(temp_id)\n merge_temp_files()\n else:\n for pid in range(0, length):\n sleep_for_nightly_mode()\n first = firsts[pid]\n second = seconds[pid]\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -m {3}={4} -m {5}={6} -r PatientID -r StudyInstanceUID {7} --out-cat --out-file {8} --out-dir {9}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, first_attr, first, second_attr, second, cfind_add, temp_file, out_folder), shell=True)\n if not (file_path == cfind_only or file_path == cfind_detailed):\n extract_empi_study()\n merge_temp_files()\n elif number_of_query_attributes == 3:\n for pid in range(0, length):\n sleep_for_nightly_mode()\n first = firsts[pid]\n second = seconds[pid]\n third = thirds[pid]\n temp_file = generate_temp_file_name()\n subprocess.call('{0}\/findscu -c {1} -b {2} -m {3}={4} -m {5}={6} -m {7}={8} -r PatientID -r StudyInstanceUID {9} --out-cat --out-file {10} --out-dir {11}'.format(DCM4CHE_BIN, SRC_AET, QUERY_AET, first_attr, first, second_attr, second, third_attr, third, cfind_add, temp_file, out_folder), shell=True)\n if not (file_path == cfind_only or file_path == cfind_detailed):\n extract_empi_study()\n merge_temp_files()\n check_kill_process()\n if send_email:\n subprocess.call('echo \"Niffler has successfully completed the DICOM retrieval\" | mail -s \"The DICOM retrieval has been complete\" {0}'.format(email), shell=True)\n logging.info('Total run time: %s %s', time.time() - t_start, ' seconds!')\n os.kill(os.getpid(), signal.SIGINT)","code_tokens":"","url":723464} +{"project_name":"liang-hou\/slimgan","file_name":"sngan_32.py","full_name":"SNGANGenerator32.forward","func_name":"forward","docstring":"Feedforwards a batch of noise vectors into a batch of fake images.","docstring_tokens":"","code":"def forward(self, x):\n \"\"\"\n Feedforwards a batch of noise vectors into a batch of fake images.\n\n Args:\n x (Tensor): A batch of noise vectors of shape (N, nz).\n\n Returns:\n Tensor: A batch of fake images of shape (N, C, H, W).\n \"\"\"\n h = self.l1(x)\n h = h.view(x.shape[0], -1, self.bottom_width, self.bottom_width)\n h = self.block2(h)\n h = self.block3(h)\n h = self.block4(h)\n h = self.b5(h)\n h = self.activation(h)\n h = torch.tanh(self.c5(h))\n return h","code_tokens":"","url":878327} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"array.py","full_name":"SparseArray.sp_index","func_name":"sp_index","docstring":"The SparseIndex containing the location of non- ``fill_value`` points.","docstring_tokens":"","code":"@property\ndef sp_index(self) -> SparseIndex:\n \"\"\"\n The SparseIndex containing the location of non- ``fill_value`` points.\n \"\"\"\n return self._sparse_index","code_tokens":"","url":442592} +{"project_name":"Rock-100\/MonoDet","file_name":"cityscapes_evaluation.py","full_name":"CityscapesInstanceEvaluator.evaluate","func_name":"evaluate","docstring":"Returns: dict: has a key \"segm\", whose value is a dict of \"AP\" and \"AP50\".","docstring_tokens":"","code":"def evaluate(self):\n \"\"\"\n Returns:\n dict: has a key \"segm\", whose value is a dict of \"AP\" and \"AP50\".\n \"\"\"\n comm.synchronize()\n if comm.get_rank() > 0:\n return\n import cityscapesscripts.evaluation.evalInstanceLevelSemanticLabeling as cityscapes_eval\n self._logger.info('Evaluating results under {} ...'.format(self._temp_dir))\n cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir)\n cityscapes_eval.args.predictionWalk = None\n cityscapes_eval.args.JSONOutput = False\n cityscapes_eval.args.colorized = False\n cityscapes_eval.args.gtInstancesFile = os.path.join(self._temp_dir, 'gtInstances.json')\n gt_dir = PathManager.get_local_path(self._metadata.gt_dir)\n groundTruthImgList = glob.glob(os.path.join(gt_dir, '*', '*_gtFine_instanceIds.png'))\n assert len(groundTruthImgList), 'Cannot find any ground truth images to use for evaluation. Searched for: {}'.format(cityscapes_eval.args.groundTruthSearch)\n predictionImgList = []\n for gt in groundTruthImgList:\n predictionImgList.append(cityscapes_eval.getPrediction(gt, cityscapes_eval.args))\n results = cityscapes_eval.evaluateImgLists(predictionImgList, groundTruthImgList, cityscapes_eval.args)['averages']\n ret = OrderedDict()\n ret['segm'] = {'AP': results['allAp'] * 100, 'AP50': results['allAp50%'] * 100}\n self._working_dir.cleanup()\n return ret","code_tokens":"","url":654839} +{"project_name":"jchaykow\/AGN-pytorch","file_name":"imports.py","full_name":"to_gpu","func_name":"to_gpu","docstring":"puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true.","docstring_tokens":"","code":"def to_gpu(x, *args, **kwargs):\n \"\"\"puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. \"\"\"\n return x.cuda(*args, **kwargs) if USE_GPU else x","code_tokens":"","url":411974} +{"project_name":"neokarn\/computer_vision","file_name":"train_yolov3.py","full_name":"validate","func_name":"validate","docstring":"Test on validation dataset.","docstring_tokens":"","code":"def validate(net, val_data, ctx, eval_metric):\n \"\"\"Test on validation dataset.\"\"\"\n eval_metric.reset()\n net.set_nms(nms_thresh=0.45, nms_topk=400)\n mx.nd.waitall()\n net.hybridize()\n for batch in val_data:\n data = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0, even_split=False)\n label = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0, even_split=False)\n det_bboxes = []\n det_ids = []\n det_scores = []\n gt_bboxes = []\n gt_ids = []\n gt_difficults = []\n for (x, y) in zip(data, label):\n (ids, scores, bboxes) = net(x)\n det_ids.append(ids)\n det_scores.append(scores)\n det_bboxes.append(bboxes.clip(0, batch[0].shape[2]))\n gt_ids.append(y.slice_axis(axis=-1, begin=4, end=5))\n gt_bboxes.append(y.slice_axis(axis=-1, begin=0, end=4))\n gt_difficults.append(y.slice_axis(axis=-1, begin=5, end=6) if y.shape[-1] > 5 else None)\n eval_metric.update(det_bboxes, det_ids, det_scores, gt_bboxes, gt_ids, gt_difficults)\n return eval_metric.get()","code_tokens":"","url":475766} +{"project_name":"gunthercox\/ChatterBot","file_name":"numeric.py","full_name":"float_to_byte","func_name":"float_to_byte","docstring":"Encodes a floating point number in a single byte.","docstring_tokens":"","code":"def float_to_byte(value, mantissabits=5, zeroexp=2):\n \"\"\"Encodes a floating point number in a single byte.\n \"\"\"\n fzero = 63 - zeroexp << mantissabits\n bits = unpack('i', pack('f', value))[0]\n smallfloat = bits >> 24 - mantissabits\n if smallfloat < fzero:\n if bits <= 0:\n result = chr(0)\n else:\n result = chr(1)\n elif smallfloat >= fzero + 256:\n result = chr(255)\n else:\n result = chr(smallfloat - fzero)\n return b(result)","code_tokens":"","url":484771} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"grpc_tensorflow_server.py","full_name":"parse_cluster_spec","func_name":"parse_cluster_spec","docstring":"Parse content of cluster_spec string and inject info into cluster protobuf.","docstring_tokens":"","code":"def parse_cluster_spec(cluster_spec, cluster):\n \"\"\"Parse content of cluster_spec string and inject info into cluster protobuf.\n\n Args:\n cluster_spec: cluster specification string, e.g.,\n \"local|localhost:2222;localhost:2223\"\n cluster: cluster protobuf.\n\n Raises:\n ValueError: if the cluster_spec string is invalid.\n \"\"\"\n job_strings = cluster_spec.split(',')\n if not cluster_spec:\n raise ValueError('Empty cluster_spec string')\n for job_string in job_strings:\n job_def = cluster.job.add()\n if job_string.count('|') != 1:\n raise ValueError(\"Not exactly one instance of '|' in cluster_spec\")\n job_name = job_string.split('|')[0]\n if not job_name:\n raise ValueError('Empty job_name in cluster_spec')\n job_def.name = job_name\n if FLAGS.verbose:\n print('Added job named \"%s\"' % job_name)\n job_tasks = job_string.split('|')[1].split(';')\n for i in range(len(job_tasks)):\n if not job_tasks[i]:\n raise ValueError('Empty task string at position %d' % i)\n job_def.tasks[i] = job_tasks[i]\n if FLAGS.verbose:\n print(' Added task \"%s\" to job \"%s\"' % (job_tasks[i], job_name))","code_tokens":"","url":183505} +{"project_name":"huawei-noah\/xingtian","file_name":"evaluate_xt.py","full_name":"get_train_model_path_from_config","func_name":"get_train_model_path_from_config","docstring":"Get train model path from config.","docstring_tokens":"","code":"def get_train_model_path_from_config(config, task_postfix=None):\n \"\"\"Get train model path from config.\"\"\"\n bm_args = get_bm_args_from_config(config)\n workspace = __get_wp_from_bm_args(bm_args)\n if task_postfix:\n workspace += task_postfix\n return os.path.join(workspace, 'models')","code_tokens":"","url":962415} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"linear_operator_low_rank_update.py","full_name":"LinearOperatorLowRankUpdate.is_diag_update_positive","func_name":"is_diag_update_positive","docstring":"If this operator is `A = L + U D V^H`, this hints `D > 0` elementwise.","docstring_tokens":"","code":"@property\ndef is_diag_update_positive(self):\n \"\"\"If this operator is `A = L + U D V^H`, this hints `D > 0` elementwise.\"\"\"\n return self._is_diag_update_positive","code_tokens":"","url":339288} +{"project_name":"mseg-dataset\/mseg-semantic","file_name":"inference_task.py","full_name":"resize_by_scaled_short_side","func_name":"resize_by_scaled_short_side","docstring":"Equivalent to ResizeShort(), but functional, instead of OOP paradigm, and w\/ scale param.","docstring_tokens":"","code":"def resize_by_scaled_short_side(image: np.ndarray, base_size: int, scale: float) -> np.ndarray:\n \"\"\"Equivalent to ResizeShort(), but functional, instead of OOP paradigm, and w\/ scale param.\n\n Args:\n image: Numpy array of shape ()\n scale: scaling factor for image\n\n Returns:\n image_scaled:\n \"\"\"\n (h, w, _) = image.shape\n short_size = round(scale * base_size)\n new_h = short_size\n new_w = short_size\n if h > w:\n new_h = round(short_size \/ float(w) * h)\n else:\n new_w = round(short_size \/ float(h) * w)\n image_scaled = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)\n return image_scaled","code_tokens":"","url":642440} +{"project_name":"weiruXie\/Natural-Language-Processing","file_name":"test_expandrank.py","full_name":"test_expandrank_candidate_weighting","func_name":"test_expandrank_candidate_weighting","docstring":"Test ExtandRank candidate weighting method.","docstring_tokens":"","code":"def test_expandrank_candidate_weighting(tmp_path):\n \"\"\"Test ExtandRank candidate weighting method.\"\"\"\n input_file = 'a.txt'\n corpus = {input_file: 'lorem sit amet', 'b.txt': 'lorem ipsum'}\n corpus_dir = create_corpus(corpus, tmp_path)\n (corpus_df, _) = create_df(corpus_dir, tmp_path)\n pairw_file = tmp_path \/ 'pairwise.gz'\n pke.utils.compute_pairwise_similarity_matrix(str(corpus_dir), str(pairw_file), extension='txt', collection_dir=None, df=corpus_df)\n pairwise = pke.utils.load_pairwise_similarities(str(pairw_file))\n n_expanded = 1\n expanded_documents = [(v, u) for (u, v) in pairwise[os.path.basename(input_file)][-n_expanded:]]\n extractor = pke.unsupervised.ExpandRank()\n extractor.load_document(input=input_file)\n extractor.candidate_selection(pos=pos)\n extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, normalized=False)\n keyphrases = [k for (k, s) in extractor.get_n_best(n=10)]","code_tokens":"","url":662882} +{"project_name":"edas\/webperf-book","file_name":"odt2txt_py.py","full_name":"OpenDocumentTextFile.processFontDeclarations","func_name":"processFontDeclarations","docstring":"Extracts necessary font information from a font-declaration element.","docstring_tokens":"","code":"def processFontDeclarations(self, fontDecl):\n \"\"\" Extracts necessary font information from a font-declaration\n element.\n \"\"\"\n for fontFace in fontDecl.getElementsByTagName('style:font-face'):\n if fontFace.getAttribute('style:font-pitch') == 'fixed':\n self.fixedFonts.append(fontFace.getAttribute('style:name'))","code_tokens":"","url":373384} +{"project_name":"tensorflow\/agents","file_name":"common.py","full_name":"has_eager_been_enabled","func_name":"has_eager_been_enabled","docstring":"Returns true iff in TF2 or in TF1 with eager execution enabled.","docstring_tokens":"","code":"def has_eager_been_enabled():\n \"\"\"Returns true iff in TF2 or in TF1 with eager execution enabled.\"\"\"\n with tf.init_scope():\n return tf.executing_eagerly()","code_tokens":"","url":23048} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"tag.py","full_name":"TaggedJSONSerializer.loads","func_name":"loads","docstring":"Load data from a JSON string and deserialized any tagged objects.","docstring_tokens":"","code":"def loads(self, value):\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return loads(value, object_hook=self.untag)","code_tokens":"","url":102072} +{"project_name":"rudranil723\/mini-main","file_name":"client.py","full_name":"RequestFactory.generic","func_name":"generic","docstring":"Construct an arbitrary HTTP request.","docstring_tokens":"","code":"def generic(self, method, path, data='', content_type='application\/octet-stream', secure=False, **extra):\n \"\"\"Construct an arbitrary HTTP request.\"\"\"\n parsed = urlparse(str(path))\n data = force_bytes(data, settings.DEFAULT_CHARSET)\n r = {'PATH_INFO': self._get_path(parsed), 'REQUEST_METHOD': method, 'SERVER_PORT': '443' if secure else '80', 'wsgi.url_scheme': 'https' if secure else 'http'}\n if data:\n r.update({'CONTENT_LENGTH': len(data), 'CONTENT_TYPE': content_type, 'wsgi.input': FakePayload(data)})\n r.update(extra)\n if not r.get('QUERY_STRING'):\n query_string = parsed[4].encode().decode('iso-8859-1')\n r['QUERY_STRING'] = query_string\n return self.request(**r)","code_tokens":"","url":316534} +{"project_name":"thuml\/Transfer-Learning-Library","file_name":"ibn.py","full_name":"resnet50_ibn_a","func_name":"resnet50_ibn_a","docstring":"Constructs a ResNet-50-IBN-a model.","docstring_tokens":"","code":"def resnet50_ibn_a(pretrained=False):\n \"\"\"Constructs a ResNet-50-IBN-a model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = IBNNet(block=Bottleneck, layers=[3, 4, 6, 3], ibn_cfg=('a', 'a', 'a', None))\n if pretrained:\n model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet50_ibn_a']), strict=False)\n return model","code_tokens":"","url":921161} +{"project_name":"meidachen\/STPLS3D","file_name":"cindex.py","full_name":"Cursor.access_specifier","func_name":"access_specifier","docstring":"Retrieves the access specifier (if any) of the entity pointed at by the cursor.","docstring_tokens":"","code":"@property\ndef access_specifier(self):\n \"\"\"\n Retrieves the access specifier (if any) of the entity pointed at by the\n cursor.\n \"\"\"\n if not hasattr(self, '_access_specifier'):\n self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)\n return AccessSpecifier.from_id(self._access_specifier)","code_tokens":"","url":909142} +{"project_name":"sarnsdev\/social-alignment-data-mining","file_name":"test_peak_finding.py","full_name":"TestPeakProminences.test_basic","func_name":"test_basic","docstring":"Test if height of prominences is correctly calculated in signal with rising baseline (peak widths are 1 sample).","docstring_tokens":"","code":"def test_basic(self):\n \"\"\"\n Test if height of prominences is correctly calculated in signal with\n rising baseline (peak widths are 1 sample).\n \"\"\"\n x = np.array([-1, 1.2, 1.2, 1, 3.2, 1.3, 2.88, 2.1])\n peaks = np.array([1, 2, 4, 6])\n lbases = np.array([0, 0, 0, 5])\n rbases = np.array([3, 3, 5, 7])\n proms = x[peaks] - np.max([x[lbases], x[rbases]], axis=0)\n out = peak_prominences(x, peaks)\n assert_equal(out[0], proms)\n assert_equal(out[1], lbases)\n assert_equal(out[2], rbases)","code_tokens":"","url":391243} +{"project_name":"rudranil723\/mini-main","file_name":"operations.py","full_name":"BaseDatabaseOperations.datetime_extract_sql","func_name":"datetime_extract_sql","docstring":"Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or 'second', return the SQL that extracts a value from the given datetime field field_name.","docstring_tokens":"","code":"def datetime_extract_sql(self, lookup_type, field_name, tzname):\n \"\"\"\n Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute', or\n 'second', return the SQL that extracts a value from the given\n datetime field field_name.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')","code_tokens":"","url":315775} +{"project_name":"akandykeller\/NeuralWaveMachines","file_name":"datasets.py","full_name":"generate_sample","func_name":"generate_sample","docstring":"Simulates a single trajectory of the system.","docstring_tokens":"","code":"def generate_sample(index: int, system: n_body.hamiltonian.HamiltonianSystem, dt: float, num_steps: int, steps_per_dt: int) -> Mapping[str, jnp.ndarray]:\n \"\"\"Simulates a single trajectory of the system.\"\"\"\n seed = np.random.randint(0, 2 * 32 - 1)\n prng_key = jax.random.fold_in(jax.random.PRNGKey(seed), index)\n total_steps = num_steps * steps_per_dt\n total_dt = dt \/ steps_per_dt\n result = system.generate_and_render_dt(num_trajectories=1, rng_key=prng_key, t0=0.0, dt=total_dt, num_steps=total_steps)\n sub_sample_index = np.linspace(0.0, total_steps, num_steps + 1)\n sub_sample_index = sub_sample_index.astype('int64')\n\n def sub_sample(x):\n if x.ndim > 1 and x.shape[1] == total_steps + 1:\n return x[0, sub_sample_index]\n else:\n return x\n result = jax.tree_map(sub_sample, result)\n for k in result.keys():\n if 'image' in k:\n result[k] = (result[k] * 255.0).astype('uint8')\n return result","code_tokens":"","url":293554} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"sort.py","full_name":"merge","func_name":"merge","docstring":"Merge Sort: split the list in half, and sort each half, then combine the sorted halves.","docstring_tokens":"","code":"def merge(a):\n \"\"\"\n Merge Sort: split the list in half, and sort each half, then\n combine the sorted halves.\n \"\"\"\n count = 0\n if len(a) > 1:\n midpoint = len(a) \/\/ 2\n b = a[:midpoint]\n c = a[midpoint:]\n count_b = merge(b)\n count_c = merge(c)\n (result, count_a) = _merge_lists(b, c)\n a[:] = result\n count = count_a + count_b + count_c\n return count","code_tokens":"","url":218053} +{"project_name":"alibaba-mmai-research\/HiCo","file_name":"metrics.py","full_name":"joint_topks_correct","func_name":"joint_topks_correct","docstring":"Calculates number of correctly predicted samples for each top-k value respectively for separate verb\/noun, and joint action predictions.","docstring_tokens":"","code":"def joint_topks_correct(preds, labels, ks):\n \"\"\"\n Calculates number of correctly predicted samples for each top-k value\n respectively for separate verb\/noun, and joint action predictions.\n Args:\n preds (dict): dictionary of verb and noun predictions. can have \n two keys \"verb_class\" and \"noun_class\", or alternatively\n three keys, \"verb_class\", \"noun_class\" and \"action_class_ind_pred\".\n labels (dict): dictionray of verb and noun class labels. The rules for\n the keys are the same as the preds.\n ks (list): list of top-k values. For example, ks = [1, 5] correspods\n to top-1 and top-5.\n Returns:\n topks_correct_all (dict): number of top-k correctly predicted samples \n for \"verb_class\", \"noun_class\", \"action_class_ind_pred\", \n and \"joint_class\".\n The difference in the \"action_class_ind_pred\" and the \"join_class\" \n is the sequence of calculating action score and fusing different \n views. \n Details can be found in the tech report, \n Huang et al. \n Towards Training Stronger Video Vision Transformers for \n EPIC-KITCHENS-100 Action Recognition.\n https:\/\/arxiv.org\/pdf\/2106.05058.pdf\n b (int): batch size.\n \"\"\"\n assert len(preds.keys()) <= 3, 'Only a maximum of three joint topks are supported.'\n for k in preds.keys():\n assert k in labels.keys(), 'Predicted key not in labels.'\n topks_correct_all = {}\n idx = 0\n joint_label = [0, 0, 0]\n num_classes = [0, 0, 0]\n for (k, pred) in preds.items():\n b = pred.shape[0]\n label = labels[k]\n joint_label[idx] = label\n num_classes[idx] = pred.shape[1]\n if idx == 0:\n if pred[0].sum(-1) != 1:\n pred = pred.softmax(-1)\n joint_pred = pred.unsqueeze(-1)\n idx += 1\n elif idx == 1:\n if pred[0].sum(-1) != 1:\n pred = pred.softmax(-1)\n joint_pred = joint_pred * pred.unsqueeze(-2)\n idx += 1\n assert pred.size(0) == label.size(0), 'Batch dim of predictions and labels must match'\n (_top_max_k_vals, top_max_k_inds) = torch.topk(pred, max(ks), dim=1, largest=True, sorted=True)\n top_max_k_inds = top_max_k_inds.t()\n rep_max_k_labels = label.view(1, -1).expand_as(top_max_k_inds)\n top_max_k_correct = top_max_k_inds.eq(rep_max_k_labels)\n topks_correct = [top_max_k_correct[:k, :].view(-1).float().sum() for k in ks]\n topks_correct_all[k] = topks_correct\n joint_pred = joint_pred.reshape(joint_pred.shape[0], -1)\n joint_label = joint_label[0] * num_classes[1] + joint_label[1]\n (_top_max_k_vals, top_max_k_inds) = torch.topk(joint_pred, max(ks), dim=1, largest=True, sorted=True)\n top_max_k_inds = top_max_k_inds.t()\n rep_max_k_labels = joint_label.view(1, -1).expand_as(top_max_k_inds)\n top_max_k_correct = top_max_k_inds.eq(rep_max_k_labels)\n topks_correct = [top_max_k_correct[:k, :].view(-1).float().sum() for k in ks]\n topks_correct_all['joint_class'] = topks_correct\n return (topks_correct_all, b)","code_tokens":"","url":206260} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"base.py","full_name":"FBDDLCompiler.visit_drop_sequence","func_name":"visit_drop_sequence","docstring":"Generate a ``DROP GENERATOR`` statement for the sequence.","docstring_tokens":"","code":"def visit_drop_sequence(self, drop):\n \"\"\"Generate a ``DROP GENERATOR`` statement for the sequence.\"\"\"\n if self.dialect._version_two:\n return 'DROP SEQUENCE %s' % self.preparer.format_sequence(drop.element)\n else:\n return 'DROP GENERATOR %s' % self.preparer.format_sequence(drop.element)","code_tokens":"","url":131801} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"query.py","full_name":"CaseDataset.drivers","func_name":"drivers","docstring":"List of driver info dictionaries.","docstring_tokens":"","code":"@property\ndef drivers(self):\n \"\"\" List of driver info dictionaries. \"\"\"\n return self._reader.drivers()","code_tokens":"","url":275380} +{"project_name":"RyanWangZf\/PyTrial","file_name":"ft_transformer.py","full_name":"CategoricalFeatureTokenizer.d_token","func_name":"d_token","docstring":"The size of one token.","docstring_tokens":"","code":"@property\ndef d_token(self) -> int:\n \"\"\"The size of one token.\"\"\"\n return self.embeddings.embedding_dim","code_tokens":"","url":302355} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"data_flow_ops.py","full_name":"ConditionalAccumulatorBase.num_accumulated","func_name":"num_accumulated","docstring":"Number of gradients that have currently been aggregated in accumulator.","docstring_tokens":"","code":"def num_accumulated(self, name=None):\n \"\"\"Number of gradients that have currently been aggregated in accumulator.\n\n Args:\n name: Optional name for the operation.\n\n Returns:\n Number of accumulated gradients currently in accumulator.\n \"\"\"\n if name is None:\n name = '%s_NumAccumulated' % self._name\n return gen_data_flow_ops.accumulator_num_accumulated(self._accumulator_ref, name=name)","code_tokens":"","url":182880} +{"project_name":"wubinzzu\/NeuRec","file_name":"tool.py","full_name":"pad_sequences","func_name":"pad_sequences","docstring":"Pads sequences to the same length.","docstring_tokens":"","code":"def pad_sequences(sequences, value=0.0, max_len=None, padding='post', truncating='post', dtype=np.int32):\n \"\"\"Pads sequences to the same length.\n\n Args:\n sequences (list): A list of lists, where each element is a sequence.\n value (int or float): Padding value. Defaults to `0.`.\n max_len (int or None): Maximum length of all sequences.\n padding (str): `\"pre\"` or `\"post\"`: pad either before or after each\n sequence. Defaults to `post`.\n truncating (str): `\"pre\"` or `\"post\"`: remove values from sequences\n larger than `max_len`, either at the beginning or at the end of\n the sequences. Defaults to `post`.\n dtype (int or float): Type of the output sequences. Defaults to `np.int32`.\n\n Returns:\n np.ndarray: Numpy array with shape `(len(sequences), max_len)`.\n\n Raises:\n ValueError: If `padding` or `truncating` is not understood.\n \"\"\"\n if max_len is None:\n max_len = np.max([len(x) for x in sequences])\n x = np.full([len(sequences), max_len], value, dtype=dtype)\n for (idx, s) in enumerate(sequences):\n if not len(s):\n continue\n if truncating == 'pre':\n trunc = s[-max_len:]\n elif truncating == 'post':\n trunc = s[:max_len]\n else:\n raise ValueError('Truncating type \"%s\" not understood' % truncating)\n if padding == 'post':\n x[idx, :len(trunc)] = trunc\n elif padding == 'pre':\n x[idx, -len(trunc):] = trunc\n else:\n raise ValueError('Padding type \"%s\" not understood' % padding)\n return x","code_tokens":"","url":722426} +{"project_name":"jimtin\/Stock_Comparison","file_name":"skipdoctest.py","full_name":"skip_doctest_py3","func_name":"skip_doctest_py3","docstring":"Decorator - skip the doctest under Python 3.","docstring_tokens":"","code":"def skip_doctest_py3(f):\n \"\"\"Decorator - skip the doctest under Python 3.\"\"\"\n f.skip_doctest = sys.version_info[0] >= 3\n return f","code_tokens":"","url":385390} +{"project_name":"sktime\/sktime","file_name":"test_softdeps.py","full_name":"is_soft_dep_missing_message","func_name":"is_soft_dep_missing_message","docstring":"Check whether message is one of multiple missing softdep messages.","docstring_tokens":"","code":"def is_soft_dep_missing_message(msg):\n \"\"\"Check whether message is one of multiple missing softdep messages.\"\"\"\n missing_version_msg = 'to be present in the python environment, with version'\n cond1 = missing_version_msg in msg\n missing_dep_entirely_msg = 'is a soft dependency and not included in the base sktime installation'\n cond2 = missing_dep_entirely_msg in msg\n error_msg_dl = 'required for deep learning'\n cond3 = error_msg_dl in msg\n return cond1 or cond2 or cond3","code_tokens":"","url":877627} +{"project_name":"0xangelo\/raylab","file_name":"policy.py","full_name":"SVGTorchPolicy.importance_sampling_ratios","func_name":"importance_sampling_ratios","docstring":"Compute unrestricted importance sampling ratios.","docstring_tokens":"","code":"def importance_sampling_ratios(self, batch_tensors):\n \"\"\"Compute unrestricted importance sampling ratios.\"\"\"\n curr_logp = self.module.actor.log_prob(batch_tensors[SampleBatch.CUR_OBS], batch_tensors[SampleBatch.ACTIONS])\n is_ratio = torch.exp(curr_logp - batch_tensors[SampleBatch.ACTION_LOGP])\n return is_ratio","code_tokens":"","url":848255} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"datasets.py","full_name":"random_binary","func_name":"random_binary","docstring":"Returns a randomly generated dataset of binary values.","docstring_tokens":"","code":"def random_binary(n_features, n_samples, random_seed=None):\n \"\"\"Returns a randomly generated dataset of binary values.\n\n Args:\n n_features: number of features (dependent variables)\n n_samples: number of samples (data points)\n random_seed: seed used for drawing the random data (default: None)\n\n Returns:\n dataset: A Dataset namedtuple containing the generated data and labels\n \"\"\"\n random_seed = np.random.randint(MAX_SEED) if random_seed is None else random_seed\n np.random.seed(random_seed)\n x = np.random.randint(2, size=(n_samples, n_features))\n y = np.zeros((n_samples, 1))\n return Dataset(x.astype('float32'), y.astype('int32'))","code_tokens":"","url":49309} +{"project_name":"ludwig-ai\/ludwig","file_name":"test_sequence_decoders.py","full_name":"test_sequence_decoder_predictions","func_name":"test_sequence_decoder_predictions","docstring":"Test that sequence decoders return the correct successfully predict.","docstring_tokens":"","code":"@pytest.mark.slow\n@pytest.mark.parametrize('feature_type,feature_gen', [(TEXT, text_feature), (SEQUENCE, sequence_feature)])\n@pytest.mark.parametrize('decoder_type', ['generator', 'tagger'])\n@pytest.mark.distributed\ndef test_sequence_decoder_predictions(tmpdir, csv_filename, ray_cluster_2cpu, feature_type, feature_gen, decoder_type):\n \"\"\"Test that sequence decoders return the correct successfully predict.\"\"\"\n input_feature = feature_gen()\n output_feature = feature_gen(output_feature=True)\n input_feature[ENCODER] = {TYPE: 'embed', 'reduce_output': None}\n output_feature[DECODER] = {TYPE: decoder_type}\n dataset_path = generate_data(input_features=[input_feature], output_features=[output_feature], filename=os.path.join(tmpdir, csv_filename))\n dataset_path = create_data_set_to_use('csv', dataset_path)\n config = {INPUT_FEATURES: [input_feature], TRAINER: {EPOCHS: 1, BATCH_SIZE: 4}}\n config[OUTPUT_FEATURES] = [output_feature]\n train_with_backend(RAY_BACKEND_CONFIG, config=config, dataset=dataset_path)","code_tokens":"","url":617294} +{"project_name":"pipermerriam\/flex","file_name":"test_schema_validation.py","full_name":"test_response_body_schema_validation_with_items_as_reference","func_name":"test_response_body_schema_validation_with_items_as_reference","docstring":"Ensure that when the expected response type is an object, and some other type is provided, that schema validation does not break since internally it will try to pull keys off of the value.","docstring_tokens":"","code":"def test_response_body_schema_validation_with_items_as_reference():\n \"\"\"\n Ensure that when the expected response type is an object, and some other\n type is provided, that schema validation does not break since internally it\n will try to pull keys off of the value.\n \"\"\"\n schema = SchemaFactory(definitions={'User': {'required': ['id', 'name'], 'properties': {'id': {'type': INTEGER}, 'name': {'enum': ('bob', 'joe')}}}, 'UserList': {'type': OBJECT, 'required': ['results'], 'properties': {'results': {'type': ARRAY, 'items': {'$ref': '#\/definitions\/User'}}}}}, paths={'\/get': {'get': {'responses': {'200': {'description': 'Success', 'schema': {'$ref': '#\/definitions\/UserList'}}}}}})\n response = ResponseFactory(url='http:\/\/www.example.com\/get', status_code=200, content_type='application\/json', content=json.dumps({'results': [{'id': 3, 'name': 'billy'}]}))\n with pytest.raises(ValidationError) as err:\n validate_response(response=response, request_method='get', schema=schema)\n assert_message_in_errors(MESSAGES['enum']['invalid'], err.value.detail, 'body.schema.enum')","code_tokens":"","url":211394} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"pixelda_eval.py","full_name":"to_degrees","func_name":"to_degrees","docstring":"Converts a log quaternion distance to an angle.","docstring_tokens":"","code":"def to_degrees(log_quaternion_loss):\n \"\"\"Converts a log quaternion distance to an angle.\n\n Args:\n log_quaternion_loss: The log quaternion distance between two\n unit quaternions (or a batch of pairs of quaternions).\n\n Returns:\n The angle in degrees of the implied angle-axis representation.\n \"\"\"\n return tf.acos(-(tf.exp(log_quaternion_loss) - 1)) * 2 * 180 \/ math.pi","code_tokens":"","url":762698} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"textpad.py","full_name":"Textbox.do_command","func_name":"do_command","docstring":"Process a single editing command.","docstring_tokens":"","code":"def do_command(self, ch):\n \"\"\"Process a single editing command.\"\"\"\n (y, x) = self.win.getyx()\n self.lastcmd = ch\n if curses.ascii.isprint(ch):\n if y < self.maxy or x < self.maxx:\n self._insert_printable_char(ch)\n elif ch == curses.ascii.SOH:\n self.win.move(y, 0)\n elif ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY_BACKSPACE):\n if x > 0:\n self.win.move(y, x - 1)\n elif y == 0:\n pass\n elif self.stripspaces:\n self.win.move(y - 1, self._end_of_line(y - 1))\n else:\n self.win.move(y - 1, self.maxx)\n if ch in (curses.ascii.BS, curses.KEY_BACKSPACE):\n self.win.delch()\n elif ch == curses.ascii.EOT:\n self.win.delch()\n elif ch == curses.ascii.ENQ:\n if self.stripspaces:\n self.win.move(y, self._end_of_line(y))\n else:\n self.win.move(y, self.maxx)\n elif ch in (curses.ascii.ACK, curses.KEY_RIGHT):\n if x < self.maxx:\n self.win.move(y, x + 1)\n elif y == self.maxy:\n pass\n else:\n self.win.move(y + 1, 0)\n elif ch == curses.ascii.BEL:\n return 0\n elif ch == curses.ascii.NL:\n if self.maxy == 0:\n return 0\n elif y < self.maxy:\n self.win.move(y + 1, 0)\n elif ch == curses.ascii.VT:\n if x == 0 and self._end_of_line(y) == 0:\n self.win.deleteln()\n else:\n self.win.move(y, x)\n self.win.clrtoeol()\n elif ch == curses.ascii.FF:\n self.win.refresh()\n elif ch in (curses.ascii.SO, curses.KEY_DOWN):\n if y < self.maxy:\n self.win.move(y + 1, x)\n if x > self._end_of_line(y + 1):\n self.win.move(y + 1, self._end_of_line(y + 1))\n elif ch == curses.ascii.SI:\n self.win.insertln()\n elif ch in (curses.ascii.DLE, curses.KEY_UP):\n if y > 0:\n self.win.move(y - 1, x)\n if x > self._end_of_line(y - 1):\n self.win.move(y - 1, self._end_of_line(y - 1))\n return 1","code_tokens":"","url":282157} +{"project_name":"RingBDStack\/CurvGAN","file_name":"base.py","full_name":"Manifold.proj","func_name":"proj","docstring":"Projects point p on the manifold.","docstring_tokens":"","code":"def proj(self, p, c):\n \"\"\"Projects point p on the manifold.\"\"\"\n raise NotImplementedError","code_tokens":"","url":508975} +{"project_name":"paulorauber\/rl","file_name":"common.py","full_name":"LossModule.convert_to_functional","func_name":"convert_to_functional","docstring":"Converts a module to functional to be used in the loss.","docstring_tokens":"","code":"def convert_to_functional(self, module: TensorDictModule, module_name: str, expand_dim: Optional[int]=None, create_target_params: bool=False, compare_against: Optional[List[Parameter]]=None, funs_to_decorate=None) -> None:\n \"\"\"Converts a module to functional to be used in the loss.\n\n Args:\n module (TensorDictModule or compatible): a stateful tensordict module.\n This module will be made functional, yet still stateful, meaning\n that it will be callable with the following alternative signatures:\n\n >>> module(tensordict)\n >>> module(tensordict, params=params)\n\n ``params`` is a :class:`tensordict.TensorDict` instance with parameters\n stuctured as the output of :func:`tensordict.nn.make_functional`\n is.\n module_name (str): name where the module will be found.\n The parameters of the module will be found under ``loss_module._params``\n whereas the module will be found under ``loss_module.``.\n expand_dim (int, optional): if provided, the parameters of the module\n will be expanded ``N`` times, where ``N = expand_dim`` along the\n first dimension. This option is to be used whenever a target\n network with more than one configuration is to be used.\n\n .. note::\n If a ``compare_against`` list of values is provided, the\n resulting parameters will simply be a detached expansion\n of the original parameters. If ``compare_against`` is not\n provided, the value of the parameters will be resampled uniformly\n between the minimum and maximum value of the parameter content.\n\n create_target_params (bool, optional): if ``True``, a detached\n copy of the parameter will be available to feed a target network\n under the name ``loss_module._target_params``.\n If ``False`` (default), this attribute will still be available\n but it will be a detached instance of the parameters, not a copy.\n In other words, any modification of the parameter value\n will directly be reflected in the target parameters.\n compare_against (iterable of parameters, optional): if provided,\n this list of parameters will be used as a comparison set for\n the parameters of the module. If the parameters are expanded\n (``expand_dim > 0``), the resulting parameters for the module\n will be a simple expansion of the original parameter. Otherwise,\n the resulting parameters will be a detached version of the\n original parameters. If ``None``, the resulting parameters\n will carry gradients as expected.\n funs_to_decorate (list of str, optional): if provided, the list of\n methods of ``module`` to make functional, ie the list of\n methods that will accept the ``params`` keyword argument.\n\n \"\"\"\n if funs_to_decorate is None:\n funs_to_decorate = ['forward']\n sep = self.SEP\n params = make_functional(module, funs_to_decorate=funs_to_decorate)\n buffer_names = []\n for (key, value) in params.items(True, True):\n if not isinstance(value, nn.Parameter):\n key = sep.join(key) if not isinstance(key, str) else key\n buffer_names.append(key)\n functional_module = deepcopy(module)\n repopulate_module(module, params)\n params_and_buffers = params\n params_and_buffers = TensorDictParams(params_and_buffers, no_convert=True)\n for key in params_and_buffers.keys(True):\n if sep in key:\n raise KeyError(f\"The key {key} contains the '_sep_' pattern which is prohibited. Consider renaming the parameter \/ buffer.\")\n params_and_buffers_flat = params_and_buffers.flatten_keys(sep)\n buffers = params_and_buffers_flat.select(*buffer_names)\n params = params_and_buffers_flat.exclude(*buffer_names)\n if compare_against is not None:\n compare_against = set(compare_against)\n else:\n compare_against = set()\n if expand_dim:\n\n def _compare_and_expand(param):\n if param in compare_against:\n expanded_param = param.data.expand(expand_dim, *param.shape)\n return expanded_param\n else:\n p_out = param.repeat(expand_dim, *[1 for _ in param.shape])\n p_out = nn.Parameter(p_out.uniform_(p_out.min().item(), p_out.max().item()).requires_grad_())\n return p_out\n params = params.apply(_compare_and_expand, batch_size=[expand_dim, *params.shape])\n buffers = buffers.apply(lambda buffer: buffer.expand(expand_dim, *buffer.shape).clone(), batch_size=[expand_dim, *buffers.shape])\n params_and_buffers.update(params.unflatten_keys(sep))\n params_and_buffers.update(buffers.unflatten_keys(sep))\n params_and_buffers.batch_size = params.batch_size\n param_name = module_name + '_params'\n prev_set_params = set(self.parameters())\n for (key, parameter) in list(params_and_buffers.items(True, True)):\n if parameter not in prev_set_params:\n pass\n elif compare_against is not None and parameter in compare_against:\n params_and_buffers.set(key, parameter.data)\n setattr(self, param_name, params_and_buffers)\n setattr(self, module_name, functional_module)\n name_params_target = 'target_' + module_name\n if create_target_params:\n target_params = TensorDictParams(params_and_buffers.apply(_make_target_param(clone=create_target_params)), no_convert=True)\n setattr(self, name_params_target + '_params', target_params)\n self._has_update_associated[module_name] = not create_target_params","code_tokens":"","url":859322} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"visitor.py","full_name":"MethodContent.acceptReturn","func_name":"acceptReturn","docstring":"Creates a new return expression.","docstring_tokens":"","code":"def acceptReturn(self, node, memo):\n \"\"\" Creates a new return expression. \"\"\"\n if node.parentType:\n expr = self.factory.expr(left='return', parent=self)\n if node.children:\n (expr.fs, expr.right) = (FS.lsr, self.factory.expr(parent=expr))\n expr.right.walk(node, memo)\n return expr","code_tokens":"","url":10977} +{"project_name":"0xangelo\/raylab","file_name":"options.py","full_name":"with_rllib_info","func_name":"with_rllib_info","docstring":"Merge info with RLlib's common parameters' info.","docstring_tokens":"","code":"def with_rllib_info(info: Info) -> Info:\n \"\"\"Merge info with RLlib's common parameters' info.\"\"\"\n info = merge_dicts(COMMON_INFO, info)\n info = tree.map_structure(lambda x: inspect.cleandoc(x) if isinstance(x, str) else x, info)\n return info","code_tokens":"","url":848220} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"loggingTools.py","full_name":"Timer.split","func_name":"split","docstring":"Split and return the lap time (in seconds) in between splits.","docstring_tokens":"","code":"def split(self):\n \"\"\"Split and return the lap time (in seconds) in between splits.\"\"\"\n current = self._time()\n self.elapsed = current - self.last\n self.last = current\n return self.elapsed","code_tokens":"","url":360981} +{"project_name":"roboflow\/supervision","file_name":"image.py","full_name":"ImageSink.save_image","func_name":"save_image","docstring":"Save a given image in the target directory.","docstring_tokens":"","code":"def save_image(self, image: np.ndarray, image_name: Optional[str]=None):\n \"\"\"\n Save a given image in the target directory.\n\n Args:\n image (np.ndarray): The image to be saved.\n image_name (str, optional): The name to use for the saved image.\n If not provided, a name will be\n generated using the `image_name_pattern`.\n \"\"\"\n if image_name is None:\n image_name = self.image_name_pattern.format(self.image_count)\n image_path = os.path.join(self.target_dir_path, image_name)\n cv2.imwrite(image_path, image)\n self.image_count += 1","code_tokens":"","url":882109} +{"project_name":"OliverKillane\/NuNet-Designer","file_name":"NuNetLibrary.py","full_name":"Output.setlabel","func_name":"setlabel","docstring":"setlabel is used in training to set the label value associated with the neuron.","docstring_tokens":"","code":"def setlabel(self, label: str) -> None:\n \"\"\"setlabel is used in training to set the label value associated with the neuron.\"\"\"\n self._labelValue = label","code_tokens":"","url":730521} +{"project_name":"nilearn\/nilearn","file_name":"test_plot_glass_brain.py","full_name":"test_plot_noncurrent_axes","func_name":"test_plot_noncurrent_axes","docstring":"Regression test for Issue #450.","docstring_tokens":"","code":"def test_plot_noncurrent_axes():\n \"\"\"Regression test for Issue #450.\"\"\"\n rng = np.random.RandomState(42)\n maps_img = Nifti1Image(rng.random_sample((10, 10, 10)), np.eye(4))\n fh1 = plt.figure()\n fh2 = plt.figure()\n ax1 = fh1.add_subplot(1, 1, 1)\n assert plt.gcf() == fh2, 'fh2 was the last plot created.'\n slicer = plot_glass_brain(maps_img, axes=ax1, title='test')\n for (ax_name, niax) in slicer.axes.items():\n ax_fh = niax.ax.get_figure()\n assert ax_fh == fh1, f'New axis {ax_name} should be in fh1.'\n plt.close()","code_tokens":"","url":724181} +{"project_name":"google-coral\/pycoral","file_name":"backprop_last_layer.py","full_name":"get_image_paths","func_name":"get_image_paths","docstring":"Walks through data_dir and returns list of image paths and label map.","docstring_tokens":"","code":"def get_image_paths(data_dir):\n \"\"\"Walks through data_dir and returns list of image paths and label map.\n\n Args:\n data_dir: string, path to data directory. It assumes data directory is\n organized as, - [CLASS_NAME_0] -- image_class_0_a.jpg --\n image_class_0_b.jpg -- ... - [CLASS_NAME_1] -- image_class_1_a.jpg -- ...\n\n Returns:\n A tuple of (image_paths, labels, label_map)\n image_paths: list of string, represents image paths\n labels: list of int, represents labels\n label_map: a dictionary (int -> string), e.g., 0->class0, 1->class1, etc.\n \"\"\"\n classes = None\n image_paths = []\n labels = []\n class_idx = 0\n for (root, dirs, files) in os.walk(data_dir):\n if root == data_dir:\n classes = dirs\n else:\n assert classes[class_idx] in root\n print('Reading dir: %s, which has %d images' % (root, len(files)))\n for img_name in files:\n image_paths.append(os.path.join(root, img_name))\n labels.append(class_idx)\n class_idx += 1\n return (image_paths, labels, dict(zip(range(class_idx), classes)))","code_tokens":"","url":819349} +{"project_name":"hayd\/pep8radius","file_name":"radius.py","full_name":"fix_line_range","func_name":"fix_line_range","docstring":"Apply autopep8 (and docformatter) between the lines start and end of source.","docstring_tokens":"","code":"def fix_line_range(source_code, start, end, options):\n \"\"\"Apply autopep8 (and docformatter) between the lines start and end of\n source.\"\"\"\n start = max(start, 1)\n options.line_range = [start, end]\n from autopep8 import fix_code\n fixed = fix_code(source_code, options)\n try:\n if options.docformatter:\n from docformatter import format_code\n fixed = format_code(fixed, summary_wrap_length=options.max_line_length - 1, description_wrap_length=options.max_line_length - 2 * options.indent_size, pre_summary_newline=options.pre_summary_newline, post_description_blank=options.post_description_blank, force_wrap=options.force_wrap, line_range=[start, end])\n except AttributeError:\n pass\n return fixed","code_tokens":"","url":279745} +{"project_name":"Westlake-AI\/openmixup","file_name":"dist_utils.py","full_name":"is_distributed","func_name":"is_distributed","docstring":"Return True if distributed environment has been initialized.","docstring_tokens":"","code":"def is_distributed() -> bool:\n \"\"\"Return True if distributed environment has been initialized.\"\"\"\n return dist.is_available() and dist.is_initialized()","code_tokens":"","url":252577} +{"project_name":"triaquae\/triaquae","file_name":"formsets.py","full_name":"BaseFormSet.total_form_count","func_name":"total_form_count","docstring":"Returns the total number of forms in this FormSet.","docstring_tokens":"","code":"def total_form_count(self):\n \"\"\"Returns the total number of forms in this FormSet.\"\"\"\n if self.is_bound:\n return self.management_form.cleaned_data[TOTAL_FORM_COUNT]\n else:\n initial_forms = self.initial_form_count()\n total_forms = initial_forms + self.extra\n if initial_forms > self.max_num >= 0:\n total_forms = initial_forms\n elif total_forms > self.max_num >= 0:\n total_forms = self.max_num\n return total_forms","code_tokens":"","url":423684} +{"project_name":"HikariTJU\/LD","file_name":"transformer.py","full_name":"MultiheadAttention.forward","func_name":"forward","docstring":"Forward function for `MultiheadAttention`.","docstring_tokens":"","code":"def forward(self, x, key=None, value=None, residual=None, query_pos=None, key_pos=None, attn_mask=None, key_padding_mask=None):\n \"\"\"Forward function for `MultiheadAttention`.\n\n Args:\n x (Tensor): The input query with shape [num_query, bs,\n embed_dims]. Same in `nn.MultiheadAttention.forward`.\n key (Tensor): The key tensor with shape [num_key, bs,\n embed_dims]. Same in `nn.MultiheadAttention.forward`.\n Default None. If None, the `query` will be used.\n value (Tensor): The value tensor with same shape as `key`.\n Same in `nn.MultiheadAttention.forward`. Default None.\n If None, the `key` will be used.\n residual (Tensor): The tensor used for addition, with the\n same shape as `x`. Default None. If None, `x` will be used.\n query_pos (Tensor): The positional encoding for query, with\n the same shape as `x`. Default None. If not None, it will\n be added to `x` before forward function.\n key_pos (Tensor): The positional encoding for `key`, with the\n same shape as `key`. Default None. If not None, it will\n be added to `key` before forward function. If None, and\n `query_pos` has the same shape as `key`, then `query_pos`\n will be used for `key_pos`.\n attn_mask (Tensor): ByteTensor mask with shape [num_query,\n num_key]. Same in `nn.MultiheadAttention.forward`.\n Default None.\n key_padding_mask (Tensor): ByteTensor with shape [bs, num_key].\n Same in `nn.MultiheadAttention.forward`. Default None.\n\n Returns:\n Tensor: forwarded results with shape [num_query, bs, embed_dims].\n \"\"\"\n query = x\n if key is None:\n key = query\n if value is None:\n value = key\n if residual is None:\n residual = x\n if key_pos is None:\n if query_pos is not None and key is not None:\n if query_pos.shape == key.shape:\n key_pos = query_pos\n if query_pos is not None:\n query = query + query_pos\n if key_pos is not None:\n key = key + key_pos\n out = self.attn(query, key, value=value, attn_mask=attn_mask, key_padding_mask=key_padding_mask)[0]\n return residual + self.dropout(out)","code_tokens":"","url":587618} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"tensorflow_dataframe.py","full_name":"TensorFlowDataFrame.batch","func_name":"batch","docstring":"Resize the batches in the `DataFrame` to the given `batch_size`.","docstring_tokens":"","code":"def batch(self, batch_size, shuffle=False, num_threads=1, queue_capacity=None, min_after_dequeue=None, seed=None):\n \"\"\"Resize the batches in the `DataFrame` to the given `batch_size`.\n\n Args:\n batch_size: desired batch size.\n shuffle: whether records should be shuffled. Defaults to true.\n num_threads: the number of enqueueing threads.\n queue_capacity: capacity of the queue that will hold new batches.\n min_after_dequeue: minimum number of elements that can be left by a\n dequeue operation. Only used if `shuffle` is true.\n seed: passed to random shuffle operations. Only used if `shuffle` is true.\n\n Returns:\n A `DataFrame` with `batch_size` rows.\n \"\"\"\n column_names = list(self._columns.keys())\n if shuffle:\n batcher = batch.ShuffleBatch(batch_size, output_names=column_names, num_threads=num_threads, queue_capacity=queue_capacity, min_after_dequeue=min_after_dequeue, seed=seed)\n else:\n batcher = batch.Batch(batch_size, output_names=column_names, num_threads=num_threads, queue_capacity=queue_capacity)\n batched_series = batcher(list(self._columns.values()))\n dataframe = type(self)()\n dataframe.assign(**dict(zip(column_names, batched_series)))\n return dataframe","code_tokens":"","url":181603} +{"project_name":"rudranil723\/mini-main","file_name":"feeds.py","full_name":"GeoFeedMixin.add_georss_element","func_name":"add_georss_element","docstring":"Add a GeoRSS XML element using the given item and handler.","docstring_tokens":"","code":"def add_georss_element(self, handler, item, w3c_geo=False):\n \"\"\"Add a GeoRSS XML element using the given item and handler.\"\"\"\n geom = item.get('geometry')\n if geom is not None:\n if isinstance(geom, (list, tuple)):\n box_coords = None\n if isinstance(geom[0], (list, tuple)):\n if len(geom) == 2:\n box_coords = geom\n else:\n raise ValueError('Only should be two sets of coordinates.')\n elif len(geom) == 2:\n self.add_georss_point(handler, geom, w3c_geo=w3c_geo)\n elif len(geom) == 4:\n box_coords = (geom[:2], geom[2:])\n else:\n raise ValueError('Only should be 2 or 4 numeric elements.')\n if box_coords is not None:\n if w3c_geo:\n raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.')\n handler.addQuickElement('georss:box', self.georss_coords(box_coords))\n else:\n gtype = str(geom.geom_type).lower()\n if gtype == 'point':\n self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo)\n else:\n if w3c_geo:\n raise ValueError('W3C Geo only supports Point geometries.')\n if gtype in ('linestring', 'linearring'):\n handler.addQuickElement('georss:line', self.georss_coords(geom.coords))\n elif gtype in ('polygon',):\n handler.addQuickElement('georss:polygon', self.georss_coords(geom[0].coords))\n else:\n raise ValueError('Geometry type \"%s\" not supported.' % geom.geom_type)","code_tokens":"","url":314972} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_base.py","full_name":"_AxesBase.get_shared_y_axes","func_name":"get_shared_y_axes","docstring":"Return a reference to the shared axes Grouper object for y axes.","docstring_tokens":"","code":"def get_shared_y_axes(self):\n \"\"\"Return a reference to the shared axes Grouper object for y axes.\"\"\"\n return self._shared_y_axes","code_tokens":"","url":1123} +{"project_name":"pedromzadeh\/numpy-based-mnist-classifier","file_name":"network.py","full_name":"sigmoid","func_name":"sigmoid","docstring":"Returns the sigmoid of `z`.","docstring_tokens":"","code":"def sigmoid(z):\n \"\"\"Returns the sigmoid of `z`.\"\"\"\n return 1 \/ (1 + np.exp(-z))","code_tokens":"","url":730013} +{"project_name":"RasaHQ\/rasa","file_name":"single_state_featurizer.py","full_name":"IntentTokenizerSingleStateFeaturizer.encode_all_labels","func_name":"encode_all_labels","docstring":"Encodes all relevant labels from the domain using the given precomputations.","docstring_tokens":"","code":"def encode_all_labels(self, domain: Domain, precomputations: Optional[MessageContainerForCoreFeaturization]) -> List[Dict[Text, List[Features]]]:\n \"\"\"Encodes all relevant labels from the domain using the given precomputations.\n\n Args:\n domain: The domain that contains the labels.\n precomputations: Contains precomputed features and attributes.\n\n Returns:\n A list of encoded labels.\n \"\"\"\n return [self._encode_intent(intent, precomputations) for intent in domain.intents]","code_tokens":"","url":836902} +{"project_name":"twke18\/HSG","file_name":"base_dataset.py","full_name":"ListDataset.collate_fn","func_name":"collate_fn","docstring":"Customized collate function to group datas into batch.","docstring_tokens":"","code":"def collate_fn(self, batch):\n \"\"\"Customized collate function to group datas into batch.\n \"\"\"\n (images, labels, indices) = zip(*batch)\n images = self._collate_fn_dict_list(images)\n labels = self._collate_fn_dict_list(labels)\n indices = torch.LongTensor(indices)\n return (images, labels, indices)","code_tokens":"","url":570644} +{"project_name":"accel-brain\/accel-brain-code","file_name":"discriminative_model.py","full_name":"DiscriminativeModel.inference","func_name":"inference","docstring":"Draw samples from the fake distribution.","docstring_tokens":"","code":"def inference(self, observed_arr):\n \"\"\"\n Draw samples from the fake distribution.\n\n Args:\n observed_arr: `mxnet.ndarray` or `mxnet.symbol` of observed data points.\n\n Returns:\n `Tuple` of `mxnet.ndarray`s.\n \"\"\"\n return self(observed_arr)","code_tokens":"","url":6793} +{"project_name":"deepmind\/dm_control","file_name":"cartpole.py","full_name":"Physics.pole_angle_cosine","func_name":"pole_angle_cosine","docstring":"Returns the cosine of the pole angle.","docstring_tokens":"","code":"def pole_angle_cosine(self):\n \"\"\"Returns the cosine of the pole angle.\"\"\"\n return self.named.data.xmat[2:, 'zz']","code_tokens":"","url":165396} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"movielens_dataset.py","full_name":"load_data","func_name":"load_data","docstring":"Load data from a csv file which splits on tab key.","docstring_tokens":"","code":"def load_data(file_name):\n \"\"\"Load data from a csv file which splits on tab key.\"\"\"\n lines = tf.gfile.Open(file_name, 'r').readlines()\n\n def _process_line(line):\n return [int(col) for col in line.split('\\t')]\n data = [_process_line(line) for line in lines]\n return data","code_tokens":"","url":761075} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"pty.py","full_name":"fork","func_name":"fork","docstring":"fork() -> (pid, master_fd) Fork and make the child a session leader with a controlling terminal.","docstring_tokens":"","code":"def fork():\n \"\"\"fork() -> (pid, master_fd)\n Fork and make the child a session leader with a controlling terminal.\"\"\"\n try:\n (pid, fd) = os.forkpty()\n except (AttributeError, OSError):\n pass\n else:\n if pid == CHILD:\n try:\n os.setsid()\n except OSError:\n pass\n return (pid, fd)\n (master_fd, slave_fd) = openpty()\n pid = os.fork()\n if pid == CHILD:\n os.setsid()\n os.close(master_fd)\n os.dup2(slave_fd, STDIN_FILENO)\n os.dup2(slave_fd, STDOUT_FILENO)\n os.dup2(slave_fd, STDERR_FILENO)\n if slave_fd > STDERR_FILENO:\n os.close(slave_fd)\n tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)\n os.close(tmp_fd)\n else:\n os.close(slave_fd)\n return (pid, master_fd)","code_tokens":"","url":281174} +{"project_name":"fudan-zvg\/SeaFormer","file_name":"efficientnet.py","full_name":"gc_efficientnetv2_rw_t","func_name":"gc_efficientnetv2_rw_t","docstring":"EfficientNet-V2 Tiny w\/ Global Context Attn (Custom variant, tiny not in paper).","docstring_tokens":"","code":"@register_model\ndef gc_efficientnetv2_rw_t(pretrained=False, **kwargs):\n \"\"\" EfficientNet-V2 Tiny w\/ Global Context Attn (Custom variant, tiny not in paper). \"\"\"\n model = _gen_efficientnetv2_s('gc_efficientnetv2_rw_t', channel_multiplier=0.8, depth_multiplier=0.9, rw=False, se_layer='gc', pretrained=pretrained, **kwargs)\n return model","code_tokens":"","url":855392} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_dask_pd.py","full_name":"test_convert_dask_to_pd_multiindex","func_name":"test_convert_dask_to_pd_multiindex","docstring":"Tests back-conversion from dask to pandas is correct for MultiIndex.","docstring_tokens":"","code":"@pytest.mark.skipif(not _check_soft_dependencies('dask', severity='none'), reason='skip test if required soft dependency for dask not available')\ndef test_convert_dask_to_pd_multiindex():\n \"\"\"Tests back-conversion from dask to pandas is correct for MultiIndex.\"\"\"\n from dask.dataframe import from_pandas\n pd_fixture = pd.DataFrame({'__index__a': [1, 2, 3], '__index__1': [1, 2, 3], 'a': [2, 3, 4]})\n pd_fixture_orig = deepcopy(pd_fixture)\n dask_fixture = from_pandas(pd_fixture, npartitions=1)\n result = convert_dask_to_pandas(dask_fixture)\n assert pd_fixture.equals(pd_fixture_orig)\n assert result.index.names == ['a', None]\n assert result.columns == ['a']\n assert (result.values == pd_fixture[['a']].values).all()","code_tokens":"","url":399463} +{"project_name":"accel-brain\/accel-brain-code","file_name":"convolutional_neural_networks.py","full_name":"ConvolutionalNeuralNetworks.get_loss_arr","func_name":"get_loss_arr","docstring":"getter for for `list` of accuracies.","docstring_tokens":"","code":"def get_loss_arr(self):\n \"\"\" getter for for `list` of accuracies. \"\"\"\n return np.array(self.__loss_list)","code_tokens":"","url":6743} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"decoder_test.py","full_name":"DecoderTest.testStringFromCTC","func_name":"testStringFromCTC","docstring":"Tests that the decoder can decode sequences including multi-codes.","docstring_tokens":"","code":"def testStringFromCTC(self):\n \"\"\"Tests that the decoder can decode sequences including multi-codes.\n \"\"\"\n ctc_labels = [9, 6, 9, 1, 3, 9, 4, 9, 5, 5, 9, 5, 0, 2, 1, 3, 9, 4, 9]\n decode = decoder.Decoder(filename=_testdata('charset_size_10.txt'))\n text = decode.StringFromCTC(ctc_labels, merge_dups=True, null_label=9)\n self.assertEqual(text, 'farm barn')","code_tokens":"","url":27568} +{"project_name":"kiretd\/Unsupervised-MIseg","file_name":"kidney_workflow.py","full_name":"segmentation_performance","func_name":"segmentation_performance","docstring":"Gets the performance metrics for a list of predicted segmentations and true labels.","docstring_tokens":"","code":"def segmentation_performance(preds, true_masks):\n \"\"\"\n Gets the performance metrics for a list of predicted segmentations and true labels.\n \"\"\"\n scores = []\n for label in np.unique(preds):\n perf = []\n for (i, (ypred, path)) in enumerate(zip(preds, true_masks)):\n ytrue = img_as_float(io.imread(path))\n perf.append(compute_metrics(ytrue, ypred, label))\n scores.append(perf)\n return scores","code_tokens":"","url":353663} +{"project_name":"BradRuderman\/pyhs2","file_name":"cursor.py","full_name":"Cursor.next","func_name":"next","docstring":"iterator-protocol for fetch next row.","docstring_tokens":"","code":"def next(self):\n \"\"\" iterator-protocol for fetch next row. \"\"\"\n row = self.fetchone()\n if row is None:\n raise StopIteration\n return row","code_tokens":"","url":296684} +{"project_name":"unixpickle\/anyrl-py","file_name":"list.py","full_name":"mean_total_reward","func_name":"mean_total_reward","docstring":"Get the mean of the total rewards.","docstring_tokens":"","code":"def mean_total_reward(rollouts):\n \"\"\"\n Get the mean of the total rewards.\n \"\"\"\n return sum([r.total_reward for r in rollouts]) \/ len(rollouts)","code_tokens":"","url":33631} +{"project_name":"JosephKJ\/iOD","file_name":"keypoints.py","full_name":"heatmaps_to_keypoints","func_name":"heatmaps_to_keypoints","docstring":"Extract predicted keypoint locations from heatmaps.","docstring_tokens":"","code":"@torch.no_grad()\ndef heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Extract predicted keypoint locations from heatmaps.\n\n Args:\n maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for\n each ROI and each keypoint.\n rois (Tensor): (#ROIs, 4). The box of each ROI.\n\n Returns:\n Tensor of shape (#ROIs, #keypoints, 4) with the last dimension corresponding to\n (x, y, logit, score) for each keypoint.\n\n When converting discrete pixel indices in an NxN image to a continuous keypoint coordinate,\n we maintain consistency with :meth:`Keypoints.to_heatmap` by using the conversion from\n Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a continuous coordinate.\n \"\"\"\n offset_x = rois[:, 0]\n offset_y = rois[:, 1]\n widths = (rois[:, 2] - rois[:, 0]).clamp(min=1)\n heights = (rois[:, 3] - rois[:, 1]).clamp(min=1)\n widths_ceil = widths.ceil()\n heights_ceil = heights.ceil()\n (num_rois, num_keypoints) = maps.shape[:2]\n xy_preds = maps.new_zeros(rois.shape[0], num_keypoints, 4)\n width_corrections = widths \/ widths_ceil\n height_corrections = heights \/ heights_ceil\n keypoints_idx = torch.arange(num_keypoints, device=maps.device)\n for i in range(num_rois):\n outsize = (int(heights_ceil[i]), int(widths_ceil[i]))\n roi_map = interpolate(maps[[i]], size=outsize, mode='bicubic', align_corners=False).squeeze(0)\n (max_score, _) = roi_map.view(num_keypoints, -1).max(1)\n max_score = max_score.view(num_keypoints, 1, 1)\n tmp_full_resolution = (roi_map - max_score).exp_()\n tmp_pool_resolution = (maps[i] - max_score).exp_()\n roi_map_scores = tmp_full_resolution \/ tmp_pool_resolution.sum((1, 2), keepdim=True)\n w = roi_map.shape[2]\n pos = roi_map.view(num_keypoints, -1).argmax(1)\n x_int = pos % w\n y_int = (pos - x_int) \/\/ w\n assert (roi_map_scores[keypoints_idx, y_int, x_int] == roi_map_scores.view(num_keypoints, -1).max(1)[0]).all()\n x = (x_int.float() + 0.5) * width_corrections[i]\n y = (y_int.float() + 0.5) * height_corrections[i]\n xy_preds[i, :, 0] = x + offset_x[i]\n xy_preds[i, :, 1] = y + offset_y[i]\n xy_preds[i, :, 2] = roi_map[keypoints_idx, y_int, x_int]\n xy_preds[i, :, 3] = roi_map_scores[keypoints_idx, y_int, x_int]\n return xy_preds","code_tokens":"","url":576919} +{"project_name":"Zengyi-Qin\/TLNet","file_name":"grid_anchor_3d_generator.py","full_name":"tile_anchors_3d","func_name":"tile_anchors_3d","docstring":"Tiles anchors over the area extents by using meshgrids to generate combinations of (x, y, z), (l, w, h) and ry.","docstring_tokens":"","code":"def tile_anchors_3d(area_extents, anchor_3d_sizes, anchor_stride, ground_plane):\n \"\"\"\n Tiles anchors over the area extents by using meshgrids to\n generate combinations of (x, y, z), (l, w, h) and ry.\n\n Args:\n area_extents: [[min_x, max_x], [min_y, max_y], [min_z, max_z]]\n anchor_3d_sizes: list of 3d anchor sizes N x (l, w, h)\n anchor_stride: stride lengths (x_stride, z_stride)\n ground_plane: coefficients of the ground plane e.g. [0, -1, 0, 0]\n\n Returns:\n boxes: list of 3D anchors in box_3d format N x [x, y, z, l, w, h, ry]\n \"\"\"\n anchor_3d_sizes = np.asarray(anchor_3d_sizes)\n anchor_stride_x = anchor_stride[0]\n anchor_stride_z = anchor_stride[1]\n anchor_rotations = np.asarray([0, np.pi \/ 2.0])\n x_start = area_extents[0][0] + anchor_stride[0] \/ 2.0\n x_end = area_extents[0][1]\n x_centers = np.array(np.arange(x_start, x_end, step=anchor_stride_x), dtype=np.float32)\n z_start = area_extents[2][1] - anchor_stride[1] \/ 2.0\n z_end = area_extents[2][0]\n z_centers = np.array(np.arange(z_start, z_end, step=-anchor_stride_z), dtype=np.float32)\n size_indices = np.arange(0, len(anchor_3d_sizes))\n rotation_indices = np.arange(0, len(anchor_rotations))\n before_sub = np.stack(np.meshgrid(x_centers, z_centers, size_indices, rotation_indices), axis=4).reshape(-1, 4)\n (a, b, c, d) = ground_plane\n all_x = before_sub[:, 0]\n all_z = before_sub[:, 1]\n all_y = -(a * all_x + c * all_z + d) \/ b\n num_anchors = len(before_sub)\n all_anchor_boxes_3d = np.zeros((num_anchors, 7))\n all_anchor_boxes_3d[:, 0:3] = np.stack((all_x, all_y, all_z), axis=1)\n sizes = anchor_3d_sizes[np.asarray(before_sub[:, 2], np.int32)]\n all_anchor_boxes_3d[:, 3:6] = sizes\n rotations = anchor_rotations[np.asarray(before_sub[:, 3], np.int32)]\n all_anchor_boxes_3d[:, 6] = rotations\n return all_anchor_boxes_3d","code_tokens":"","url":917705} +{"project_name":"roxanahirean\/Pac-Man-Artificial-Intelligence","file_name":"searchAgents.py","full_name":"FoodSearchProblem.getSuccessors","func_name":"getSuccessors","docstring":"Returns successor states, the actions they require, and a cost of 1.","docstring_tokens":"","code":"def getSuccessors(self, state):\n \"\"\"Returns successor states, the actions they require, and a cost of 1.\"\"\"\n successors = []\n self._expanded += 1\n for direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:\n (x, y) = state[0]\n (dx, dy) = Actions.directionToVector(direction)\n (nextx, nexty) = (int(x + dx), int(y + dy))\n hitsWall = self.walls[nextx][nexty]\n if not hitsWall:\n nextFood = state[1].copy()\n nextFood[nextx][nexty] = False\n successors.append((((nextx, nexty), nextFood), direction, 1))\n return successors","code_tokens":"","url":253790} +{"project_name":"nilearn\/nilearn","file_name":"test_first_level.py","full_name":"test_scaling","func_name":"test_scaling","docstring":"Test the scaling function.","docstring_tokens":"","code":"def test_scaling():\n \"\"\"Test the scaling function.\"\"\"\n rng = np.random.RandomState(42)\n shape = (400, 10)\n u = rng.standard_normal(size=shape)\n mean = 100 * rng.uniform(size=shape[1]) + 1\n Y = u + mean\n (Y_, mean_) = mean_scaling(Y)\n assert_almost_equal(Y_.mean(0), 0, 5)\n assert_almost_equal(mean_, mean, 0)\n assert Y.std() > 1","code_tokens":"","url":723836} +{"project_name":"limdauto\/drf_openapi","file_name":"travis_pypi_setup.py","full_name":"prepend_line","func_name":"prepend_line","docstring":"Rewrite a file adding a line to its beginning.","docstring_tokens":"","code":"def prepend_line(filepath, line):\n \"\"\"Rewrite a file adding a line to its beginning.\"\"\"\n with open(filepath) as f:\n lines = f.readlines()\n lines.insert(0, line)\n with open(filepath, 'w') as f:\n f.writelines(lines)","code_tokens":"","url":167298} +{"project_name":"lululxvi\/deepxde","file_name":"backend.py","full_name":"sparse_tensor","func_name":"sparse_tensor","docstring":"Construct a sparse tensor based on given indices, values and shape.","docstring_tokens":"","code":"def sparse_tensor(indices, values, shape):\n \"\"\"Construct a sparse tensor based on given indices, values and shape.\n\n Args:\n indices (list of tuple). A 2-D int list of shape [N, ndims], which specifies\n the indices of the elements in the sparse tensor that contain nonzero values\n (elements are zero-indexed), such as [(x1, y1), (x2, y2), ..., (xN, yN)].\n values (Tensor). Values of non-zero elements, with shape of [N].\n shape (list or tuple). Dense shape of constructed tensor.\n\n Returns:\n SparseTensor: A sparse tensor.\n \"\"\"","code_tokens":"","url":536186} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"_threading_local.py","full_name":"_localimpl.create_dict","func_name":"create_dict","docstring":"Create a new dict for the current thread, and return it.","docstring_tokens":"","code":"def create_dict(self):\n \"\"\"Create a new dict for the current thread, and return it.\"\"\"\n localdict = {}\n key = self.key\n thread = current_thread()\n idt = id(thread)\n\n def local_deleted(_, key=key):\n thread = wrthread()\n if thread is not None:\n del thread.__dict__[key]\n\n def thread_deleted(_, idt=idt):\n local = wrlocal()\n if local is not None:\n dct = local.dicts.pop(idt)\n wrlocal = ref(self, local_deleted)\n wrthread = ref(thread, thread_deleted)\n thread.__dict__[key] = wrlocal\n self.dicts[idt] = (wrthread, localdict)\n return localdict","code_tokens":"","url":282046} +{"project_name":"rouge8\/20questions","file_name":"model.py","full_name":"get_question_by_text","func_name":"get_question_by_text","docstring":"Returns Storage object containing a question where text=text.","docstring_tokens":"","code":"def get_question_by_text(text):\n \"\"\"Returns Storage object containing a question where text=text.\"\"\"\n try:\n return db.select('questions', vars=locals(), where='text=$text')[0]\n except IndexError:\n return None","code_tokens":"","url":4384} +{"project_name":"ManifoldFR\/recvis-project","file_name":"refiner.py","full_name":"Refiner.predict","func_name":"predict","docstring":"images: num_batch, img_size, img_size, 3 kps: num_batch x 19 x 3 Preprocessed to range [-1, 1] scale_factors, offsets: used to preprocess the bbox Runs the model with images.","docstring_tokens":"","code":"def predict(self, images, kps, scale_factors, offsets):\n \"\"\"\n images: num_batch, img_size, img_size, 3\n kps: num_batch x 19 x 3\n Preprocessed to range [-1, 1]\n\n scale_factors, offsets: used to preprocess the bbox\n\n Runs the model with images.\n \"\"\"\n feed_dict = {self.images_pl: images}\n fetch_dict = {'img_feats': self.img_feat}\n img_feats = self.sess.run(self.img_feat, feed_dict)\n feed_dict = {self.img_feat_pl: img_feats, self.kps_pl: kps}\n self.sess.run(self.set_img_feat_var, feed_dict)\n if self.refine_inpose:\n use_res = -2\n else:\n use_res = -1\n fetch_dict = {'theta': self.final_thetas[use_res], 'joints': self.all_kps[use_res], 'verts': self.all_verts[use_res]}\n init_result = self.sess.run(fetch_dict, feed_dict)\n shapes = init_result['theta'][:, -10:]\n mean_shape = np.mean(shapes, axis=0)\n feed_dict[self.shape_pl] = mean_shape\n init_pose = init_result['theta'][:, 3:3 + 72]\n feed_dict[self.init_pose_pl] = init_pose\n if self.refine_inpose:\n print('Doing optimization in pose space!!')\n feed_dict[self.theta_pl] = init_result['theta']\n self.sess.run(self.set_theta_var, feed_dict)\n if self.config.use_weighted_init_pose:\n print('Using weighted init pose!')\n gt_kps = np.stack(kps)\n vis = gt_kps[:, :, 2, None]\n diff = vis * (gt_kps[:, :, :2] - init_result['joints'])\n error = np.linalg.norm(diff.reshape(diff.shape[0], -1), axis=1, ord=1)\n weights = np.expand_dims(np.exp(-(error \/ error.max()) ** 2), 1)\n feed_dict[self.init_pose_weight_pl] = weights\n feed_dict[self.scale_factors_pl] = scale_factors\n feed_dict[self.offsets_pl] = offsets\n fetch_dict = {'joints': self.all_kps[-1], 'verts': self.all_verts[-1], 'cams': self.all_cams[-1], 'joints3d': self.all_Js[-1], 'theta': self.final_thetas[-1], 'total_loss': self.total_loss, 'loss_kp': self.e_loss_kp, 'loss_shape': self.loss_shape, 'loss_joints': self.loss_joints, 'loss_camera': self.loss_camera, 'loss_init_pose': self.loss_init_pose, 'optim': self.e_opt}\n if self.viz:\n crops = [unprocess_image(image) for image in images[::self.viz_sub]]\n op_kps = [np.hstack((self.img_size * ((kp[:, :2] + 1) * 0.5), kp[:, 2, None])) for kp in kps[::self.viz_sub]]\n op_imgs = [draw_skeleton(crop, kp, vis=kp[:, 2] > 0.1) for (crop, kp) in zip(crops, op_kps)]\n op_img = np.hstack(op_imgs)\n (proj_img, rend_img) = self.visualize_seq(crops, init_result)\n import matplotlib.pyplot as plt\n plt.ion()\n plt.figure(1)\n plt.clf()\n plt.suptitle('init')\n plt.subplot(311)\n plt.imshow(op_img)\n plt.axis('off')\n plt.title('openpose joints')\n plt.subplot(312)\n plt.imshow(proj_img)\n plt.axis('off')\n plt.title('proj joints')\n plt.subplot(313)\n plt.imshow(rend_img)\n plt.axis('off')\n plt.title('rend verts')\n plt.pause(0.001)\n import ipdb\n ipdb.set_trace()\n all_loss_keys = ['loss_kp', 'loss_shape', 'loss_joints', 'loss_init_pose', 'loss_camera']\n tbegin = time.time()\n num_iter = self.config.num_refine\n loss_records = {}\n for step in range(num_iter):\n result = self.sess.run(fetch_dict, feed_dict)\n loss_keys = [key for key in all_loss_keys if key in result.keys()]\n total_loss = result['total_loss']\n msg_prefix = 'iter %d\/%d, total_loss %.2g' % (step, num_iter, total_loss)\n msg_raw = ['%s: %.2g' % (key, result[key]) for key in loss_keys]\n print(msg_prefix + ' ' + ' ,'.join(msg_raw))\n if step == 0:\n for key in loss_keys:\n loss_records[key] = [result[key]]\n else:\n for key in loss_keys:\n loss_records[key].append(result[key])\n if self.viz and step > 0 and (step % 50 == 0):\n (proj_img, rend_img) = self.visualize_seq(crops, result)\n import matplotlib.pyplot as plt\n plt.ion()\n plt.figure(2)\n plt.clf()\n plt.suptitle('iter %d' % step)\n plt.subplot(311)\n plt.imshow(op_img)\n plt.axis('off')\n plt.title('openpose joints')\n plt.subplot(312)\n plt.imshow(proj_img)\n plt.axis('off')\n plt.title('proj joints')\n plt.subplot(313)\n plt.imshow(rend_img)\n plt.axis('off')\n plt.title('rend verts')\n plt.pause(0.001)\n import ipdb\n ipdb.set_trace()\n total_time = time.time() - tbegin\n print('Total time %g' % total_time)\n del result['optim']\n del result['verts']\n result['loss_records'] = loss_records\n return result","code_tokens":"","url":832440} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"tensorrt.py","full_name":"print_predictions","func_name":"print_predictions","docstring":"Given an array of mode, graph_name, predicted_ID, print labels.","docstring_tokens":"","code":"def print_predictions(results, ids_are_one_indexed=False, preds_to_print=5):\n \"\"\"Given an array of mode, graph_name, predicted_ID, print labels.\"\"\"\n labels = get_labels()\n print('Predictions:')\n for (mode, result) in results:\n pred_ids = top_predictions(result, preds_to_print)\n pred_labels = get_labels_for_ids(labels, pred_ids, ids_are_one_indexed)\n print('Precision: ', mode, pred_labels)","code_tokens":"","url":760756} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"attributes.py","full_name":"History.non_deleted","func_name":"non_deleted","docstring":"Return a collection of added + unchanged.","docstring_tokens":"","code":"def non_deleted(self):\n \"\"\"Return a collection of added + unchanged.\"\"\"\n return (self.added or []) + (self.unchanged or [])","code_tokens":"","url":481140} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"video_classification.py","full_name":"video_classification_kinetics400","func_name":"video_classification_kinetics400","docstring":"Video classification on Kinectics 400 with resnet.","docstring_tokens":"","code":"@exp_factory.register_config_factory('video_classification_kinetics400')\ndef video_classification_kinetics400() -> cfg.ExperimentConfig:\n \"\"\"Video classification on Kinectics 400 with resnet.\"\"\"\n train_dataset = kinetics400(is_training=True)\n validation_dataset = kinetics400(is_training=False)\n task = VideoClassificationTask(model=VideoClassificationModel(backbone=backbones_3d.Backbone3D(type='resnet_3d', resnet_3d=backbones_3d.ResNet3D50()), norm_activation=common.NormActivation(norm_momentum=0.9, norm_epsilon=1e-05)), losses=Losses(l2_weight_decay=0.0001), train_data=train_dataset, validation_data=validation_dataset)\n config = cfg.ExperimentConfig(runtime=cfg.RuntimeConfig(mixed_precision_dtype='bfloat16'), task=task, restrictions=['task.train_data.is_training != None', 'task.validation_data.is_training != None', 'task.train_data.num_classes == task.validation_data.num_classes'])\n add_trainer(config, train_batch_size=1024, eval_batch_size=64)\n return config","code_tokens":"","url":850750} +{"project_name":"Trusted-AI\/adversarial-robustness-toolbox","file_name":"test_lowprofool.py","full_name":"test_general_cancer_lr","func_name":"test_general_cancer_lr","docstring":"Check whether the produced adversaries are correct, given Logistic Regression classifier and breast cancer wisconsin dataset.","docstring_tokens":"","code":"def test_general_cancer_lr(breast_cancer_dataset):\n \"\"\"\n Check whether the produced adversaries are correct,\n given Logistic Regression classifier and breast cancer wisconsin dataset.\n \"\"\"\n ((x_train, y_train, x_valid, y_valid), _, clip_values) = breast_cancer_dataset\n lr_clf = LogisticRegression(penalty='none')\n lr_clf.fit(x_train, y_train)\n clf_slr = ScikitlearnLogisticRegression(model=lr_clf, clip_values=clip_values)\n lpf_slr = LowProFool(classifier=clf_slr, n_steps=30, eta=0.02, lambd=1.5)\n lpf_slr.fit_importances(x_train, y_train)\n sample = x_valid\n target = np.eye(2)[np.array(y_valid.apply(lambda x: np.random.choice([i for i in [0, 1] if i != x])))]\n adversaries = lpf_slr.generate(x=sample, y=target)\n expected = np.argmax(target, axis=1)\n predicted = np.argmax(lr_clf.predict_proba(adversaries), axis=1)\n correct = expected == predicted\n success_rate = np.sum(correct) \/ correct.shape[0]\n expected = 0.6\n logger.info('[Breast cancer, Scikit-learn Logistic Regression] success rate of adversarial attack (expected >{:.2f}): {:.2f}%'.format(expected * 100, success_rate * 100))\n assert success_rate > expected","code_tokens":"","url":398518} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_openml.py","full_name":"test_fetch_openml_consistency_parser","func_name":"test_fetch_openml_consistency_parser","docstring":"Check the consistency of the LIAC-ARFF and pandas parsers.","docstring_tokens":"","code":"@fails_if_pypy\n@pytest.mark.parametrize('data_id', [61, 1119, 40945])\ndef test_fetch_openml_consistency_parser(monkeypatch, data_id):\n \"\"\"Check the consistency of the LIAC-ARFF and pandas parsers.\"\"\"\n pd = pytest.importorskip('pandas')\n _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)\n bunch_liac = fetch_openml(data_id=data_id, as_frame=True, cache=False, parser='liac-arff')\n bunch_pandas = fetch_openml(data_id=data_id, as_frame=True, cache=False, parser='pandas')\n (data_liac, data_pandas) = (bunch_liac.data, bunch_pandas.data)\n\n def convert_numerical_dtypes(series):\n pandas_series = data_pandas[series.name]\n if pd.api.types.is_numeric_dtype(pandas_series):\n return series.astype(pandas_series.dtype)\n else:\n return series\n data_liac_with_fixed_dtypes = data_liac.apply(convert_numerical_dtypes)\n pd.testing.assert_frame_equal(data_liac_with_fixed_dtypes, data_pandas)\n (frame_liac, frame_pandas) = (bunch_liac.frame, bunch_pandas.frame)\n pd.testing.assert_frame_equal(frame_pandas[bunch_pandas.feature_names], data_pandas)\n\n def convert_numerical_and_categorical_dtypes(series):\n pandas_series = frame_pandas[series.name]\n if pd.api.types.is_numeric_dtype(pandas_series):\n return series.astype(pandas_series.dtype)\n elif pd.api.types.is_categorical_dtype(pandas_series):\n return series.cat.rename_categories(pandas_series.cat.categories)\n else:\n return series\n frame_liac_with_fixed_dtypes = frame_liac.apply(convert_numerical_and_categorical_dtypes)\n pd.testing.assert_frame_equal(frame_liac_with_fixed_dtypes, frame_pandas)","code_tokens":"","url":363578} +{"project_name":"ludwig-ai\/ludwig","file_name":"optimizers.py","full_name":"BaseOptimizerConfig.is_paged","func_name":"is_paged","docstring":"Returns True if the optimizer is a Paged optimizer.","docstring_tokens":"","code":"@property\ndef is_paged(self) -> bool:\n \"\"\"Returns True if the optimizer is a Paged optimizer.\"\"\"\n return False","code_tokens":"","url":616919} +{"project_name":"sjtu-marl\/malib","file_name":"trainer.py","full_name":"Trainer.train","func_name":"train","docstring":"Run training, and return info dict.","docstring_tokens":"","code":"@abstractmethod\ndef train(self, batch: Batch) -> Dict[str, float]:\n \"\"\"Run training, and return info dict.\n\n Args:\n batch (Union[Dict[AgentID, Batch], Batch]): A dict of batch or batch\n\n Returns:\n Batch: A training batch of data.\n \"\"\"","code_tokens":"","url":627540} +{"project_name":"treigerm\/WaterNet","file_name":"evaluation.py","full_name":"visualise_predictions","func_name":"visualise_predictions","docstring":"Create a new GeoTIFF image which overlays the predictions of the model.","docstring_tokens":"","code":"def visualise_predictions(predictions, labels, false_positives, tile_size, out_path, out_format='GeoTIFF'):\n \"\"\"Create a new GeoTIFF image which overlays the predictions of the model.\"\"\"\n print('Create {} result files.'.format(out_format))\n predictions = np.reshape(predictions, (len(labels), tile_size, tile_size, 1))\n false_positives = np.reshape(false_positives, (len(labels), tile_size, tile_size, 1))\n results = []\n for (i, (_, position, path_to_geotiff)) in enumerate(labels):\n prediction_tile = predictions[i, :, :, :]\n false_positivle_tile = false_positives[i, :, :, :]\n label_tile = labels[i][0]\n results.append(((prediction_tile, label_tile, false_positivle_tile), position, path_to_geotiff))\n visualise_results(results, tile_size, out_path, out_format=out_format)","code_tokens":"","url":372914} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"factorization_ops_test_utils.py","full_name":"remove_empty_rows_columns","func_name":"remove_empty_rows_columns","docstring":"Simple util to remove empty rows and columns of a matrix.","docstring_tokens":"","code":"def remove_empty_rows_columns(np_matrix):\n \"\"\"Simple util to remove empty rows and columns of a matrix.\n\n Args:\n np_matrix: A numpy array.\n Returns:\n A tuple consisting of:\n mat: A numpy matrix obtained by removing empty rows and columns from\n np_matrix.\n nz_row_ids: A numpy array of the ids of non-empty rows, such that\n nz_row_ids[i] is the old row index corresponding to new index i.\n nz_col_ids: A numpy array of the ids of non-empty columns, such that\n nz_col_ids[j] is the old column index corresponding to new index j.\n \"\"\"\n nz_row_ids = np.where(np.sum(np_matrix, axis=1) != 0)[0]\n nz_col_ids = np.where(np.sum(np_matrix, axis=0) != 0)[0]\n mat = np_matrix[np.ix_(nz_row_ids, nz_col_ids)]\n return (mat, nz_row_ids, nz_col_ids)","code_tokens":"","url":313056} +{"project_name":"Eric3911\/OpenAGI","file_name":"test_utils.py","full_name":"TestPreprocessingUtils.test_get_full_path_ais","func_name":"test_get_full_path_ais","docstring":"Test with paths on AIStore.","docstring_tokens":"","code":"@pytest.mark.unit\ndef test_get_full_path_ais(self, tmpdir):\n \"\"\"Test with paths on AIStore.\n \"\"\"\n num_files = 10\n audio_files_relative_path = [f'file_{n}.test' for n in range(num_files)]\n audio_files_cache_path = [os.path.join(tmpdir, a_file_rel) for a_file_rel in audio_files_relative_path]\n ais_data_dir = 'ais:\/\/test'\n ais_manifest_file = os.path.join(ais_data_dir, 'manifest.json')\n\n @contextmanager\n def create_files(paths):\n for a_file in paths:\n Path(a_file).touch()\n yield\n for a_file in paths:\n Path(a_file).unlink()\n\n def datastore_path_to_cache_path_in_tmpdir(path):\n rel_path = os.path.relpath(path, start=os.path.dirname(ais_manifest_file))\n if rel_path in audio_files_relative_path:\n idx = audio_files_relative_path.index(rel_path)\n return audio_files_cache_path[idx]\n else:\n raise ValueError(f'Unexpected path {path}')\n with mock.patch('nemo.collections.common.parts.preprocessing.manifest.datastore_path_to_local_path', datastore_path_to_cache_path_in_tmpdir):\n with create_files(audio_files_cache_path):\n for n in range(num_files):\n assert get_full_path(audio_files_relative_path[n], manifest_file=ais_manifest_file) == audio_files_cache_path[n]\n assert get_full_path(audio_files_relative_path[n], data_dir=ais_data_dir) == audio_files_cache_path[n]\n assert get_full_path(audio_files_relative_path, manifest_file=ais_manifest_file) == audio_files_cache_path\n assert get_full_path(audio_files_relative_path, data_dir=ais_data_dir) == audio_files_cache_path","code_tokens":"","url":274410} +{"project_name":"f-dangel\/cockpit","file_name":"examples_utils.py","full_name":"CNN","func_name":"CNN","docstring":"Basic Conv-Net for MNIST.","docstring_tokens":"","code":"def CNN():\n \"\"\"Basic Conv-Net for MNIST.\"\"\"\n return nn.Sequential(nn.Conv2d(1, 11, 5), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Conv2d(11, 16, 5), nn.ReLU(), nn.MaxPool2d(2, 2), nn.Flatten(), nn.Linear(16 * 4 * 4, 80), nn.ReLU(), nn.Linear(80, 84), nn.ReLU(), nn.Linear(84, 10))","code_tokens":"","url":493149} +{"project_name":"opendilab\/DI-star","file_name":"actions.py","full_name":"ArgumentType.scalar","func_name":"scalar","docstring":"Create an ArgumentType with a single scalar in range(value).","docstring_tokens":"","code":"@classmethod\ndef scalar(cls, value):\n \"\"\"Create an ArgumentType with a single scalar in range(value).\"\"\"\n return lambda i, name: cls(i, name, (value,), lambda a: a[0], None, None)","code_tokens":"","url":184668} +{"project_name":"tensorlayer\/RLzoo","file_name":"dis_components.py","full_name":"Agent.new_queue_pair","func_name":"new_queue_pair","docstring":"create a pair of queues.","docstring_tokens":"","code":"def new_queue_pair(self, a, b):\n \"\"\"create a pair of queues.\"\"\"\n q1 = self.new_queue(a, b)\n q2 = self.new_queue(b, a)\n return (q1, q2)","code_tokens":"","url":324505} +{"project_name":"bytedance\/DeepSolid","file_name":"network.py","full_name":"construct_input_features","func_name":"construct_input_features","docstring":"Constructs inputs to Fermi Net from raw electron and atomic positions.","docstring_tokens":"","code":"def construct_input_features(x: jnp.ndarray, atoms: jnp.ndarray, ndim: int=3) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray, jnp.ndarray]:\n \"\"\"Constructs inputs to Fermi Net from raw electron and atomic positions.\n Args:\n x: electron positions. Shape (nelectrons*ndim,).\n atoms: atom positions. Shape (natoms, ndim).\n ndim: dimension of system. Change only with caution.\n Returns:\n ae, ee, r_ae, r_ee tuple, where:\n ae: atom-electron vector. Shape (nelectron, natom, 3).\n ee: atom-electron vector. Shape (nelectron, nelectron, 3).\n r_ae: atom-electron distance. Shape (nelectron, natom, 1).\n r_ee: electron-electron distance. Shape (nelectron, nelectron, 1).\n The diagonal terms in r_ee are masked out such that the gradients of these\n terms are also zero.\n \"\"\"\n assert atoms.shape[1] == ndim\n ae = jnp.reshape(x, [-1, 1, ndim]) - atoms[None, ...]\n ee = jnp.reshape(x, [1, -1, ndim]) - jnp.reshape(x, [-1, 1, ndim])\n r_ae = jnp.linalg.norm(ae, axis=2, keepdims=True)\n n = ee.shape[0]\n r_ee = jnp.linalg.norm(ee + jnp.eye(n)[..., None], axis=-1) * (1.0 - jnp.eye(n))\n return (ae, ee, r_ae, r_ee[..., None])","code_tokens":"","url":539864} +{"project_name":"google-research\/tensor2robot","file_name":"tpu_model_wrapper.py","full_name":"TPUT2RModelWrapper.get_feature_specification","func_name":"get_feature_specification","docstring":"Returns the feature specification with bfloat16 replacing float32.","docstring_tokens":"","code":"def get_feature_specification(self, mode):\n \"\"\"Returns the feature specification with bfloat16 replacing float32.\"\"\"\n return tensorspec_utils.replace_dtype(self._t2r_model.get_feature_specification(mode), from_dtype=tf.float32, to_dtype=tf.bfloat16)","code_tokens":"","url":908250} +{"project_name":"chainer\/chainerrl","file_name":"evaluator.py","full_name":"eval_performance","func_name":"eval_performance","docstring":"Run multiple evaluation episodes and return statistics.","docstring_tokens":"","code":"def eval_performance(env, agent, n_steps, n_episodes, max_episode_len=None, logger=None):\n \"\"\"Run multiple evaluation episodes and return statistics.\n\n Args:\n env (Environment): Environment used for evaluation\n agent (Agent): Agent to evaluate.\n n_steps (int): Number of timesteps to evaluate for.\n n_episodes (int): Number of evaluation episodes.\n max_episode_len (int or None): If specified, episodes longer than this\n value will be truncated.\n logger (Logger or None): If specified, the given Logger object will be\n used for logging results. If not specified, the default logger of\n this module will be used.\n Returns:\n Dict of statistics.\n \"\"\"\n assert (n_steps is None) != (n_episodes is None)\n if isinstance(env, chainerrl.env.VectorEnv):\n scores = batch_run_evaluation_episodes(env, agent, n_steps, n_episodes, max_episode_len=max_episode_len, logger=logger)\n else:\n scores = run_evaluation_episodes(env, agent, n_steps, n_episodes, max_episode_len=max_episode_len, logger=logger)\n stats = dict(episodes=len(scores), mean=statistics.mean(scores), median=statistics.median(scores), stdev=statistics.stdev(scores) if len(scores) >= 2 else 0.0, max=np.max(scores), min=np.min(scores))\n return stats","code_tokens":"","url":104445} +{"project_name":"zomux\/deepy","file_name":"initializers.py","full_name":"WeightInitializer.sample","func_name":"sample","docstring":"Sample parameters with given shape.","docstring_tokens":"","code":"def sample(self, shape):\n \"\"\"\n Sample parameters with given shape.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":181021} +{"project_name":"opendilab\/DI-star","file_name":"gen_actions.py","full_name":"get_data","func_name":"get_data","docstring":"Retrieve static data from the game.","docstring_tokens":"","code":"def get_data():\n \"\"\"Retrieve static data from the game.\"\"\"\n run_config = run_configs.get()\n with run_config.start(want_rgb=False) as controller:\n m = maps.get(FLAGS.map)\n create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(map_path=m.path, map_data=m.data(run_config)))\n create.player_setup.add(type=sc_pb.Participant)\n create.player_setup.add(type=sc_pb.Computer, race=sc_common.Random, difficulty=sc_pb.VeryEasy)\n join = sc_pb.RequestJoinGame(race=sc_common.Random, options=sc_pb.InterfaceOptions(raw=True))\n controller.create_game(create)\n controller.join_game(join)\n return controller.data()","code_tokens":"","url":184597} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"chart.py","full_name":"SteppingChartParser.current_chartrule","func_name":"current_chartrule","docstring":"Return the chart rule used to generate the most recent edge.","docstring_tokens":"","code":"def current_chartrule(self):\n \"\"\"Return the chart rule used to generate the most recent edge.\"\"\"\n return self._current_chartrule","code_tokens":"","url":218099} +{"project_name":"tensorflow\/agents","file_name":"sac_agent.py","full_name":"SacAgent.actor_loss","func_name":"actor_loss","docstring":"Computes the actor_loss for SAC training.","docstring_tokens":"","code":"def actor_loss(self, time_steps: ts.TimeStep, weights: Optional[types.Tensor]=None, training: Optional[bool]=True) -> types.Tensor:\n \"\"\"Computes the actor_loss for SAC training.\n\n Args:\n time_steps: A batch of timesteps.\n weights: Optional scalar or elementwise (per-batch-entry) importance\n weights.\n training: Whether training should be applied.\n\n Returns:\n actor_loss: A scalar actor loss.\n \"\"\"\n with tf.name_scope('actor_loss'):\n nest_utils.assert_same_structure(time_steps, self.time_step_spec)\n (actions, log_pi) = self._actions_and_log_probs(time_steps, training=training)\n target_input = (time_steps.observation, actions)\n (target_q_values1, _) = self._critic_network_1(target_input, step_type=time_steps.step_type, training=False)\n (target_q_values2, _) = self._critic_network_2(target_input, step_type=time_steps.step_type, training=False)\n target_q_values = tf.minimum(target_q_values1, target_q_values2)\n actor_loss = tf.exp(self._log_alpha) * log_pi - target_q_values\n if actor_loss.shape.rank > 1:\n actor_loss = tf.reduce_sum(actor_loss, axis=range(1, actor_loss.shape.rank))\n reg_loss = self._actor_network.losses if self._actor_network else None\n agg_loss = common.aggregate_losses(per_example_loss=actor_loss, sample_weight=weights, regularization_loss=reg_loss)\n actor_loss = agg_loss.total_loss\n self._actor_loss_debug_summaries(actor_loss, actions, log_pi, target_q_values, time_steps)\n return actor_loss","code_tokens":"","url":23234} +{"project_name":"tensorflow\/data-validation","file_name":"stats_generator.py","full_name":"CombinerStatsGenerator.add_input","func_name":"add_input","docstring":"Returns result of folding a batch of inputs into accumulator.","docstring_tokens":"","code":"def add_input(self, accumulator: ACCTYPE, input_record_batch: pa.RecordBatch) -> ACCTYPE:\n \"\"\"Returns result of folding a batch of inputs into accumulator.\n\n Args:\n accumulator: The current accumulator, which may be modified and returned\n for efficiency.\n input_record_batch: An Arrow RecordBatch whose columns are features and\n rows are examples. The columns are of type List or Null (If a\n feature's value is None across all the examples in the batch, its\n corresponding column is of Null type).\n\n Returns:\n The accumulator after updating the statistics for the batch of inputs.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":497531} +{"project_name":"Qualcomm-AI-research\/weakly-supervised-causal-representation-","file_name":"scm.py","full_name":"FixedOrderSCM.log_prob_weakly_supervised","func_name":"log_prob_weakly_supervised","docstring":"Given weakly supervised causal variables and the intervention mask, computes the corresponding noise variables and log likelihoods.","docstring_tokens":"","code":"def log_prob_weakly_supervised(self, z1, z2, intervention, adjacency_matrix):\n \"\"\"\n Given weakly supervised causal variables and the intervention mask, computes the\n corresponding noise variables\n and log likelihoods.\n \"\"\"\n intervention = self._sanitize_intervention(intervention, z1.shape[0])\n assert torch.all(torch.isfinite(z1))\n assert torch.all(torch.isfinite(z2))\n (observation_noise, logdet1) = self._inverse(z1, adjacency_matrix=adjacency_matrix)\n assert torch.all(torch.isfinite(observation_noise))\n logprob_observed = self.base_density.log_prob(observation_noise.reshape((-1, 1))).reshape((-1, self.dim_z))\n logprob_observed += logdet1\n logprob_observed = clean_and_clamp(logprob_observed)\n logprob_observed = torch.sum(logprob_observed, 1, keepdim=True)\n (intervention_noise, logdet2) = self._inverse(z2, intervention=intervention, adjacency_matrix=adjacency_matrix)\n assert torch.all(torch.isfinite(intervention_noise))\n logprob_intervened = self.base_density.log_prob(intervention_noise.reshape((-1, 1))).reshape((-1, self.dim_z))\n logprob_intervened += logdet2\n logprob_intervened = clean_and_clamp(logprob_intervened)\n logprob_intervened = intervention * logprob_intervened\n logprob_intervened = torch.sum(logprob_intervened, 1, keepdim=True)\n z_counterfactual = self._solve_counterfactual(z2, intervention=intervention, noise=observation_noise, adjacency_matrix=adjacency_matrix)\n assert torch.all(torch.isfinite(z_counterfactual))\n cf_noise = (z2 - z_counterfactual) \/ self.manifold_thickness\n assert torch.all(torch.isfinite(cf_noise))\n logdet_cf = -torch.log(self.manifold_thickness)\n logprob_nonintervened = self.base_density.log_prob(cf_noise.reshape((-1, 1))).reshape((-1, self.dim_z))\n logprob_nonintervened += logdet_cf\n logprob_nonintervened = clean_and_clamp(logprob_nonintervened)\n logprob_nonintervened = (1.0 - intervention) * logprob_nonintervened\n logprob_nonintervened = torch.sum(logprob_nonintervened, 1, keepdim=True)\n logprob = logprob_observed + logprob_intervened + logprob_nonintervened\n assert torch.all(torch.isfinite(logprob))\n outputs = dict(scm_log_prior=logprob, scm_log_prior_observed=logprob_observed, scm_log_prior_intervened=logprob_intervened, scm_log_prior_nonintervened=logprob_nonintervened)\n return (logprob, outputs)","code_tokens":"","url":373210} +{"project_name":"Eric3911\/OpenAGI","file_name":"optimizers.py","full_name":"get_optimizer","func_name":"get_optimizer","docstring":"Convenience method to obtain an Optimizer class and partially instantiate it with optimizer kwargs.","docstring_tokens":"","code":"def get_optimizer(name: str, **kwargs: Optional[Dict[str, Any]]) -> Optimizer:\n \"\"\"\n Convenience method to obtain an Optimizer class and partially instantiate it with optimizer kwargs.\n\n Args:\n name: Name of the Optimizer in the registry.\n kwargs: Optional kwargs of the optimizer used during instantiation.\n\n Returns:\n a partially instantiated Optimizer\n \"\"\"\n if name not in AVAILABLE_OPTIMIZERS:\n raise ValueError(f\"Cannot resolve optimizer '{name}'. Available optimizers are : {AVAILABLE_OPTIMIZERS.keys()}\")\n if name == 'fused_adam':\n if not torch.cuda.is_available():\n raise ValueError(f'CUDA must be available to use fused_adam.')\n optimizer = AVAILABLE_OPTIMIZERS[name]\n optimizer = partial(optimizer, **kwargs)\n return optimizer","code_tokens":"","url":274088} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"tree.py","full_name":"TreeItem.IsExpandable","func_name":"IsExpandable","docstring":"Return whether there are subitems.","docstring_tokens":"","code":"def IsExpandable(self):\n \"\"\"Return whether there are subitems.\"\"\"\n return 1","code_tokens":"","url":282894} +{"project_name":"hans\/pyccg","file_name":"lexicon.py","full_name":"Lexicon.start_categories","func_name":"start_categories","docstring":"Return primitive categories which are valid root nodes.","docstring_tokens":"","code":"@property\ndef start_categories(self):\n \"\"\"\n Return primitive categories which are valid root nodes.\n \"\"\"\n return self._starts + list(itertools.chain.from_iterable((self._derived_categories_by_base[start] for start in self._starts)))","code_tokens":"","url":295948} +{"project_name":"instadeepai\/jumanji","file_name":"specs.py","full_name":"Spec.name","func_name":"name","docstring":"Returns the name of the nested spec.","docstring_tokens":"","code":"@property\ndef name(self) -> str:\n \"\"\"Returns the name of the nested spec.\"\"\"\n return self._name","code_tokens":"","url":593844} +{"project_name":"Eric3911\/OpenAGI","file_name":"data_simulation.py","full_name":"RIRCorpusGenerator.generate_source_position","func_name":"generate_source_position","docstring":"Generate position for all sources in a room.","docstring_tokens":"","code":"def generate_source_position(self, room_dim: Iterable[float]) -> List[List[float]]:\n \"\"\"Generate position for all sources in a room.\n\n Args:\n room_dim: dimensions of a 3D shoebox room\n\n Returns:\n List of source positions, with each position characterized with a 3D coordinate\n \"\"\"\n source_cfg = self.cfg.source\n placement_range = convert_placement_to_range(placement=source_cfg.placement, room_dim=room_dim)\n source_position = []\n for n in range(source_cfg.num):\n s_pos = [None] * 3\n for idx in range(len(s_pos)):\n s_pos[idx] = self.random.uniform(low=placement_range[idx][0], high=placement_range[idx][1])\n source_position.append(s_pos)\n return source_position","code_tokens":"","url":272289} +{"project_name":"rudranil723\/mini-main","file_name":"contour.py","full_name":"ContourLabeler.print_label","func_name":"print_label","docstring":"Return whether a contour is long enough to hold a label.","docstring_tokens":"","code":"def print_label(self, linecontour, labelwidth):\n \"\"\"Return whether a contour is long enough to hold a label.\"\"\"\n return len(linecontour) > 10 * labelwidth or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()","code_tokens":"","url":319327} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"test_mujoco_v5.py","full_name":"test_reset_info","func_name":"test_reset_info","docstring":"Verify that the environment returns info with `reset()`.","docstring_tokens":"","code":"@pytest.mark.parametrize('env_name', ['Ant', 'HalfCheetah', 'Hopper', 'Humanoid', 'HumanoidStandup', 'Swimmer', 'Walker2d'])\n@pytest.mark.parametrize('version', ['v5'])\ndef test_reset_info(env_name: str, version: str):\n \"\"\"Verify that the environment returns info with `reset()`.\"\"\"\n env = gym.make(f'{env_name}-{version}')\n (_, reset_info) = env.reset()\n assert len(reset_info) > 0","code_tokens":"","url":573481} +{"project_name":"googleinterns\/ddsp-docker","file_name":"ddsp_ai_platform.py","full_name":"submit_job","func_name":"submit_job","docstring":"Submits the job on AI Platform.","docstring_tokens":"","code":"def submit_job(args):\n \"\"\"Submits the job on AI Platform.\"\"\"\n submitting_job = f\"gcloud ai-platform jobs submit training {args['job_name']} --region={args['region']} --master-image-uri={args['image_uri']} --config={args['config_path']} -- --save_dir={args['save_dir']} --restore_dir={args['restore_dir']} --file_pattern={args['data_path']}\/train.tfrecord* --batch_size={args['batch_size']} --learning_rate={args['learning_rate']} --num_steps={args['num_steps']} --steps_per_summary={args['steps_per_summary']} --steps_per_save={args['steps_per_save']} --early_stop_loss_value={args['early_stop_loss_value']}\"\n os.system(submitting_job)","code_tokens":"","url":516404} +{"project_name":"Vincent-Vercruyssen\/LocIT","file_name":"construct_benchmark.py","full_name":"predict_unsupervised","func_name":"predict_unsupervised","docstring":"Predict the class of the instances.","docstring_tokens":"","code":"def predict_unsupervised(method, features, labels):\n \"\"\" Predict the class of the instances. \"\"\"\n if method == 'kmeans':\n mean_dist = []\n for k in [5, 10, 15, 20, 25, 30]:\n kmeans = KMeans(n_clusters=k)\n kmeans.fit(features)\n mean_dist.append(kmeans.inertia_ \/ features.shape[0])\n explained_var = 0.95\n variance = np.diff(mean_dist) * -1\n distortion_percent = np.cumsum(variance) \/ (mean_dist[0] - mean_dist[-1])\n idx = np.where(distortion_percent > explained_var)[0]\n best_k = (idx[0] + 1) * 5\n kmeans = KMeans(n_clusters=best_k)\n kmeans.fit(features)\n y_pred = kmeans.predict(features)\n elif method == 'gmm':\n pass\n (l1, l2) = np.unique(labels)\n class_1 = np.zeros(best_k)\n class_2 = np.zeros(best_k)\n for (i, cl) in enumerate(y_pred):\n if labels[i] == l1:\n class_1[cl] += 1\n else:\n class_2[cl] += 1\n class_dict = dict()\n for i in range(best_k):\n if class_1[i] > class_2[i]:\n class_dict[i] = l1\n else:\n class_dict[i] = l2\n y_pred_final = np.zeros(len(labels))\n for (i, l) in enumerate(y_pred):\n y_pred_final[i] = class_dict[l]\n return y_pred_final","code_tokens":"","url":614780} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"_bootstrap.py","full_name":"FrozenImporter.create_module","func_name":"create_module","docstring":"Use default semantics for module creation.","docstring_tokens":"","code":"@classmethod\ndef create_module(cls, spec):\n \"\"\"Use default semantics for module creation.\"\"\"","code_tokens":"","url":282931} +{"project_name":"Deci-AI\/super-gradients","file_name":"early_stop_test.py","full_name":"EarlyStopTest.test_min_mode_threshold_metric","func_name":"test_min_mode_threshold_metric","docstring":"Test for mode=min metric, test that training stops after metric value reaches the `threshold` value.","docstring_tokens":"","code":"def test_min_mode_threshold_metric(self):\n \"\"\"\n Test for mode=min metric, test that training stops after metric value reaches the `threshold` value.\n \"\"\"\n trainer = Trainer('early_stop_test')\n early_stop_loss = EarlyStop(Phase.VALIDATION_EPOCH_END, monitor='LossTest', mode='min', threshold=0.1, verbose=True)\n phase_callbacks = [early_stop_loss]\n loss_values = torch.tensor([1.0, 0.8, 0.4, 0.2, 0.09, 0.11, 0.105, 0.3, 0.05, 0.02])\n fake_loss = LossTest(loss_values)\n train_params = self.train_params.copy()\n train_params.update({'loss': fake_loss, 'phase_callbacks': phase_callbacks})\n trainer.train(model=self.net, training_params=train_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader())\n excepted_end_epoch = 5\n self.assertEqual(excepted_end_epoch, fake_loss.count \/\/ 2)","code_tokens":"","url":880660} +{"project_name":"ethz-asl\/ai_for_robotics","file_name":"FCLayer.py","full_name":"FCLayer.affinePart","func_name":"affinePart","docstring":"Get the affine part of the layer, excluding the activation function.","docstring_tokens":"","code":"def affinePart(self, x):\n \"\"\"\n Get the affine part of the layer, excluding the activation function.\n \"\"\"\n return","code_tokens":"","url":87173} +{"project_name":"morpheus-project\/morpheus","file_name":"helpers.py","full_name":"LabelHelper.update_mean_var","func_name":"update_mean_var","docstring":"Updates the mean and variance outputs with the new model values.","docstring_tokens":"","code":"@staticmethod\ndef update_mean_var(data: dict, labels: np.ndarray, batch_idx: List[Tuple[int, int]]):\n \"\"\"Updates the mean and variance outputs with the new model values.\n\n Args:\n data (dict): a dict of numpy arrays containing the data\n labels (np.ndarray): the new output from the model\n batch_idx (List[Tuple[int, int]]): a list of indices to update\n\n Returns:\n None\n \"\"\"\n (window_y, window_x) = LabelHelper.UPDATE_MASK_N.shape\n total_shape = data['n'].shape\n for (i, l) in enumerate(labels):\n (y, x) = batch_idx[i]\n LabelHelper.update_ns(data, [(y, x)])\n ys = slice(y, y + window_y)\n xs = slice(x, x + window_x)\n final_map = LabelHelper.get_final_map(total_shape, y, x)\n n = data['n'][ys, xs]\n for (j, morph) in enumerate(LabelHelper.MORPHOLOGIES):\n k_mean = f'{morph}_mean'\n k_var = f'{morph}_var'\n x_n = l[:, :, j]\n prev_mean = data[k_mean][ys, xs]\n prev_var = data[k_var][ys, xs]\n mean = LabelHelper.iterative_mean(n, prev_mean, x_n, LabelHelper.UPDATE_MASK)\n var = LabelHelper.iterative_variance(prev_var, x_n, prev_mean, mean, LabelHelper.UPDATE_MASK)\n var = LabelHelper.finalize_variance(n, var, final_map)\n data[k_mean][ys, xs] = mean\n data[k_var][ys, xs] = var","code_tokens":"","url":655977} +{"project_name":"xwarfare\/GPT2-Telegram-Chatbot","file_name":"GPT2-Learning.py","full_name":"learnreset","func_name":"learnreset","docstring":"Send a message when the command \/learnreset is issued.","docstring_tokens":"","code":"def learnreset(bot, update):\n \"\"\"Send a message when the command \/learnreset is issued.\"\"\"\n global running\n global mode\n global learn\n global user\n global tim\n global learning\n global cache\n if user == '':\n user = update.message.from_user.id\n mode = True\n learn = True\n learning = ''\n cache = ''\n if mode == True and learn == True:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M. I am in the learning chatbot mode.')\n if mode == True and learn == False:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M I am in the chatbot mode.')\n if mode == False:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M I am in the finishsentence mode.')\n return\n if user == update.message.from_user.id:\n mode = True\n learn = True\n learning = ''\n cache = ''\n if mode == True and learn == True:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M. I am in the learning chatbot mode.')\n if mode == True and learn == False:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M I am in the chatbot mode.')\n if mode == False:\n update.message.reply_text('Send a message! Get it computed! 1558M Settings: Logic: ' + tpstring + ' Rate:' + temps + ' GPT-2 1558M I am in the finishsentence mode.')\n return\n else:\n left = str(tim)\n update.message.reply_text('Bot is currently in use, make sure to set your settings when their timer runs down. ' + left + ' seconds.')","code_tokens":"","url":202633} +{"project_name":"clips\/pattern","file_name":"__init__.py","full_name":"ellipse","func_name":"ellipse","docstring":"Draws an ellipse at (x, y) with given fill and stroke color and stroke width.","docstring_tokens":"","code":"def ellipse(x, y, width, height, fill=(0, 0, 0, 1), stroke=None, strokewidth=1):\n \"\"\" Draws an ellipse at (x, y) with given fill and stroke color and stroke width.\n \"\"\"\n pass","code_tokens":"","url":764623} +{"project_name":"Gradiant\/pyodi","file_name":"train_config_generation.py","full_name":"train_config_generation","func_name":"train_config_generation","docstring":"Computes optimal anchors for a given COCO dataset based on iou clustering.","docstring_tokens":"","code":"@logger.catch(reraise=True)\ndef train_config_generation(ground_truth_file: str, input_size: Tuple[int, int]=(1280, 720), n_ratios: int=3, n_scales: int=3, strides: Optional[List[int]]=None, base_sizes: Optional[List[int]]=None, show: bool=True, output: Optional[str]=None, output_size: Tuple[int, int]=(1600, 900), keep_ratio: bool=False, evaluate: bool=True) -> None:\n \"\"\"Computes optimal anchors for a given COCO dataset based on iou clustering.\n\n Args:\n ground_truth_file: Path to COCO ground truth file.\n input_size: Model image input size. Defaults to (1280, 720).\n n_ratios: Number of ratios. Defaults to 3.\n n_scales: Number of scales. Defaults to 3.\n strides: List of strides. Defatults to [4, 8, 16, 32, 64].\n base_sizes: The basic sizes of anchors in multiple levels.\n If None is given, strides will be used as base_sizes.\n show: Show results or not. Defaults to True.\n output: Output directory where results going to be saved. Defaults to None.\n output_size: Size of saved images. Defaults to (1600, 900).\n keep_ratio: Whether to keep the aspect ratio or not. Defaults to False.\n evaluate: Whether to evaluate or not the anchors. Check\n [`pyodi train-config evaluation`][pyodi.apps.train_config.train_config_evaluation.train_config_evaluation]\n for more information.\n\n Returns:\n Anchor generator instance.\n \"\"\"\n if output is not None:\n Path(output).mkdir(parents=True, exist_ok=True)\n df_annotations = coco_ground_truth_to_df(ground_truth_file)\n df_annotations = filter_zero_area_bboxes(df_annotations)\n df_annotations = scale_bbox_dimensions(df_annotations, input_size=input_size, keep_ratio=keep_ratio)\n df_annotations = get_scale_and_ratio(df_annotations, prefix='scaled')\n if strides is None:\n strides = [4, 8, 16, 32, 64]\n if base_sizes is None:\n base_sizes = strides\n df_annotations['fpn_level'] = find_pyramid_level(get_bbox_array(df_annotations, prefix='scaled')[:, 2:], base_sizes)\n df_annotations['fpn_level_scale'] = df_annotations['fpn_level'].replace({i: scale for (i, scale) in enumerate(base_sizes)})\n df_annotations['level_scale'] = df_annotations['scaled_scale'] \/ df_annotations['fpn_level_scale']\n df_annotations['log_ratio'] = np.log(df_annotations['scaled_ratio'])\n df_annotations['log_level_scale'] = np.log(df_annotations['level_scale'])\n clustering_results = [kmeans_euclidean(df_annotations[value].to_numpy(), n_clusters=n_clusters) for (i, (value, n_clusters)) in enumerate(zip(['log_level_scale', 'log_ratio'], [n_scales, n_ratios]))]\n scales = np.e ** clustering_results[0]['centroids']\n ratios = np.e ** clustering_results[1]['centroids']\n anchor_generator = AnchorGenerator(strides=strides, ratios=ratios, scales=scales, base_sizes=base_sizes)\n logger.info(f'Anchor configuration: \\n{anchor_generator.to_string()}')\n plot_clustering_results(df_annotations, anchor_generator, show=show, output=output, output_size=output_size, title='COCO_anchor_generation')\n if evaluate:\n anchor_config = dict(anchor_generator=anchor_generator.to_dict())\n train_config_evaluation(ground_truth_file=df_annotations, anchor_config=anchor_config, input_size=input_size, show=show, output=output, output_size=output_size)\n if output:\n output_file = Path(output) \/ 'anchor_config.py'\n with open(output_file, 'w') as f:\n f.write(anchor_generator.to_string())","code_tokens":"","url":820839} +{"project_name":"triaquae\/triaquae","file_name":"management.py","full_name":"CustomUserModelValidationTestCase.test_username_not_in_required_fields","func_name":"test_username_not_in_required_fields","docstring":"USERNAME_FIELD should not appear in REQUIRED_FIELDS.","docstring_tokens":"","code":"@override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields')\ndef test_username_not_in_required_fields(self):\n \"\"\"USERNAME_FIELD should not appear in REQUIRED_FIELDS.\"\"\"\n new_io = StringIO()\n get_validation_errors(new_io, get_app('auth'))\n self.assertIn('The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.', new_io.getvalue())","code_tokens":"","url":357145} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"credentials.py","full_name":"Credentials.from_authorized_user_file","func_name":"from_authorized_user_file","docstring":"Creates a Credentials instance from an authorized user json file.","docstring_tokens":"","code":"@classmethod\ndef from_authorized_user_file(cls, filename, scopes=None):\n \"\"\"Creates a Credentials instance from an authorized user json file.\n\n Args:\n filename (str): The path to the authorized user json file.\n scopes (Sequence[str]): Optional list of scopes to include in the\n credentials.\n\n Returns:\n google.oauth2.credentials.Credentials: The constructed\n credentials.\n\n Raises:\n ValueError: If the file is not in the expected format.\n \"\"\"\n with io.open(filename, 'r', encoding='utf-8') as json_file:\n data = json.load(json_file)\n return cls.from_authorized_user_info(data, scopes)","code_tokens":"","url":215158} +{"project_name":"keras-team\/keras-cv","file_name":"efficientnet_v1_backbone.py","full_name":"apply_efficientnet_block","func_name":"apply_efficientnet_block","docstring":"An inverted residual block.","docstring_tokens":"","code":"def apply_efficientnet_block(inputs, filters_in=32, filters_out=16, kernel_size=3, strides=1, activation='swish', expand_ratio=1, se_ratio=0.0, dropout_rate=0.0, name=''):\n \"\"\"An inverted residual block.\n\n Args:\n inputs: Tensor, The input tensor of the block\n filters_in: integer, the number of input filters.\n filters_out: integer, the number of output filters.\n kernel_size: integer, the dimension of the convolution window.\n strides: integer, the stride of the convolution.\n activation: activation function to use between each convolutional layer.\n expand_ratio: integer, scaling coefficient for the input filters.\n se_ratio: float between 0 and 1, fraction to squeeze the input filters.\n dropout_rate: float between 0 and 1, fraction of the input units to drop.\n name: string, block label.\n\n Returns:\n output tensor for the block.\n \"\"\"\n filters = filters_in * expand_ratio\n if expand_ratio != 1:\n x = keras.layers.Conv2D(filters=filters, kernel_size=1, strides=1, padding='same', use_bias=False, kernel_initializer=conv_kernel_initializer(), name=name + 'expand_conv')(inputs)\n x = keras.layers.BatchNormalization(axis=3, name=name + 'expand_bn')(x)\n x = keras.layers.Activation(activation, name=name + 'expand_activation')(x)\n else:\n x = inputs\n if strides == 2:\n x = keras.layers.ZeroPadding2D(padding=utils.correct_pad_downsample(x, kernel_size), name=name + 'dwconv_pad')(x)\n conv_pad = 'valid'\n else:\n conv_pad = 'same'\n x = keras.layers.DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding=conv_pad, use_bias=False, depthwise_initializer=conv_kernel_initializer(), name=name + 'dwconv')(x)\n x = keras.layers.BatchNormalization(axis=3, name=name + 'dwconv_bn')(x)\n x = keras.layers.Activation(activation, name=name + 'dwconv_activation')(x)\n if 0 < se_ratio <= 1:\n filters_se = max(1, int(filters_in * se_ratio))\n se = keras.layers.GlobalAveragePooling2D(name=name + 'se_squeeze')(x)\n se_shape = (1, 1, filters)\n se = keras.layers.Reshape(se_shape, name=name + 'se_reshape')(se)\n se = keras.layers.Conv2D(filters_se, 1, padding='same', activation=activation, kernel_initializer=conv_kernel_initializer(), name=name + 'se_reduce')(se)\n se = keras.layers.Conv2D(filters, 1, padding='same', activation='sigmoid', kernel_initializer=conv_kernel_initializer(), name=name + 'se_expand')(se)\n x = keras.layers.multiply([x, se], name=name + 'se_excite')\n x = keras.layers.Conv2D(filters=filters_out, kernel_size=1, strides=1, padding='same', use_bias=False, kernel_initializer=conv_kernel_initializer(), name=name + 'project')(x)\n x = keras.layers.BatchNormalization(axis=3, name=name + 'project_bn')(x)\n x = keras.layers.Activation(activation, name=name + 'project_activation')(x)\n if strides == 1 and filters_in == filters_out:\n if dropout_rate > 0:\n x = keras.layers.Dropout(dropout_rate, noise_shape=(None, 1, 1, 1), name=name + 'drop')(x)\n x = keras.layers.Add(name=name + 'add')([x, inputs])\n return x","code_tokens":"","url":595190} +{"project_name":"jbwang1997\/CrossKD","file_name":"soft_teacher.py","full_name":"SoftTeacher.aug_box","func_name":"aug_box","docstring":"Augment bboxes with jitter.","docstring_tokens":"","code":"@staticmethod\ndef aug_box(batch_data_samples, times, frac):\n \"\"\"Augment bboxes with jitter.\"\"\"\n\n def _aug_single(box):\n box_scale = box[:, 2:4] - box[:, :2]\n box_scale = box_scale.clamp(min=1)[:, None, :].expand(-1, 2, 2).reshape(-1, 4)\n aug_scale = box_scale * frac\n offset = torch.randn(times, box.shape[0], 4, device=box.device) * aug_scale[None, ...]\n new_box = box.clone()[None, ...].expand(times, box.shape[0], -1) + offset\n return new_box\n return [_aug_single(data_samples.gt_instances.bboxes) for data_samples in batch_data_samples]","code_tokens":"","url":491277} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"shape_drawer.py","full_name":"ShapeDrawer.EllipseDrawer.draw","func_name":"draw","docstring":"Draw the ellipse on the image.","docstring_tokens":"","code":"def draw(self, image: np.ndarray, entity: Ellipse, labels: List[ScoredLabel]) -> np.ndarray:\n \"\"\"Draw the ellipse on the image.\n\n Args:\n image (np.ndarray): Image to draw on.\n entity (Ellipse): Ellipse to draw.\n labels (List[ScoredLabel]): Labels to draw.\n\n Returns:\n np.ndarray: Image with the ellipse drawn on it.\n \"\"\"\n base_color = labels[0].color.bgr_tuple\n if entity.width > entity.height:\n axes = (int(entity.major_axis * image.shape[1]), int(entity.minor_axis * image.shape[0]))\n else:\n axes = (int(entity.major_axis * image.shape[0]), int(entity.minor_axis * image.shape[1]))\n center = (int(entity.x_center * image.shape[1]), int(entity.y_center * image.shape[0]))\n alpha = self.alpha_shape\n overlay = cv2.ellipse(img=image.copy(), center=center, axes=axes, angle=0, startAngle=0, endAngle=360, color=base_color, thickness=cv2.FILLED)\n result_without_border = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)\n result_with_border = cv2.ellipse(img=result_without_border, center=center, axes=axes, angle=0, startAngle=0, endAngle=360, color=base_color, lineType=cv2.LINE_AA)\n (draw_command, content_width, content_height) = self.generate_draw_command_for_labels(labels, image, self.show_labels, self.show_confidence)\n offset = self.label_offset_box_shape\n x_coord = entity.x1 * image.shape[1]\n y_coord = entity.y1 * image.shape[0] - offset - content_height\n flagpole_end_point = Coordinate(int(x_coord + 1), int(entity.y_center * image.shape[0]))\n if y_coord < self.top_margin * image.shape[0]:\n y_coord = entity.y1 * image.shape[0] + entity.y2 * image.shape[0] + offset\n flagpole_start_point = Coordinate(x_coord + 1, y_coord)\n else:\n flagpole_start_point = Coordinate(x_coord + 1, y_coord + content_height)\n if x_coord + content_width > result_with_border.shape[1]:\n x_coord = result_with_border.shape[1] - content_width\n self.set_cursor_pos(Coordinate(x_coord, y_coord))\n image = draw_command(result_with_border)\n image = self.draw_flagpole(image, flagpole_start_point, flagpole_end_point)\n return image","code_tokens":"","url":918897} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"test_tgrep.py","full_name":"TestSequenceFunctions.test_tokenize_examples","func_name":"test_tokenize_examples","docstring":"Test tokenization of the TGrep2 manual example patterns.","docstring_tokens":"","code":"def test_tokenize_examples(self):\n \"\"\"\n Test tokenization of the TGrep2 manual example patterns.\n \"\"\"\n self.assertEqual(tgrep.tgrep_tokenize('NP < PP'), ['NP', '<', 'PP'])\n self.assertEqual(tgrep.tgrep_tokenize('\/^NP\/'), ['\/^NP\/'])\n self.assertEqual(tgrep.tgrep_tokenize('NP << PP . VP'), ['NP', '<<', 'PP', '.', 'VP'])\n self.assertEqual(tgrep.tgrep_tokenize('NP << PP | . VP'), ['NP', '<<', 'PP', '|', '.', 'VP'])\n self.assertEqual(tgrep.tgrep_tokenize('NP !<< PP [> NP | >> VP]'), ['NP', '!', '<<', 'PP', '[', '>', 'NP', '|', '>>', 'VP', ']'])\n self.assertEqual(tgrep.tgrep_tokenize('NP << (PP . VP)'), ['NP', '<<', '(', 'PP', '.', 'VP', ')'])\n self.assertEqual(tgrep.tgrep_tokenize(\"NP <' (PP <, (IN < on))\"), ['NP', \"<'\", '(', 'PP', '<,', '(', 'IN', '<', 'on', ')', ')'])\n self.assertEqual(tgrep.tgrep_tokenize('S < (A < B) < C'), ['S', '<', '(', 'A', '<', 'B', ')', '<', 'C'])\n self.assertEqual(tgrep.tgrep_tokenize('S < ((A < B) < C)'), ['S', '<', '(', '(', 'A', '<', 'B', ')', '<', 'C', ')'])\n self.assertEqual(tgrep.tgrep_tokenize('S < (A < B < C)'), ['S', '<', '(', 'A', '<', 'B', '<', 'C', ')'])\n self.assertEqual(tgrep.tgrep_tokenize('A= 0.0 else 'S'\n ew = 'E' if lon >= 0.0 else 'W'\n return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew)","code_tokens":"","url":362694} +{"project_name":"Erfanafshar\/Principles-and-Applications-of---graph-coloring","file_name":"colors.py","full_name":"Normalize.autoscale","func_name":"autoscale","docstring":"Set *vmin*, *vmax* to min, max of *A*.","docstring_tokens":"","code":"def autoscale(self, A):\n \"\"\"Set *vmin*, *vmax* to min, max of *A*.\"\"\"\n A = np.asanyarray(A)\n self.vmin = A.min()\n self.vmax = A.max()","code_tokens":"","url":306599} +{"project_name":"RLE-Foundation\/rllte","file_name":"squashed_normal.py","full_name":"SquashedNormal.log_prob","func_name":"log_prob","docstring":"Scores the sample by inverting the transform(s) and computing the score using the score of the base distribution and the log abs det jacobian.","docstring_tokens":"","code":"def log_prob(self, actions: th.Tensor) -> th.Tensor:\n \"\"\"Scores the sample by inverting the transform(s) and computing the score using\n the score of the base distribution and the log abs det jacobian.\n Args:\n actions (th.Tensor): The actions to be evaluated.\n\n Returns:\n The log_prob value.\n \"\"\"\n return self.dist.log_prob(actions)","code_tokens":"","url":333405} +{"project_name":"tensorflow\/agents","file_name":"common.py","full_name":"safe_has_state","func_name":"safe_has_state","docstring":"Safely checks `state not in (None, (), [])`.","docstring_tokens":"","code":"def safe_has_state(state):\n \"\"\"Safely checks `state not in (None, (), [])`.\"\"\"\n return state is not None and state is not () and (state is not [])","code_tokens":"","url":23082} +{"project_name":"muhanzhang\/D-VAE","file_name":"test_opt.py","full_name":"test_constant_folding","func_name":"test_constant_folding","docstring":"Test that constant folding get registered at fast_compile An error removed that registration during the registration.","docstring_tokens":"","code":"def test_constant_folding():\n \"\"\" Test that constant folding get registered at fast_compile\n\n An error removed that registration during the registration.\n \"\"\"\n x = tensor.dvector()\n mode = theano.compile.get_mode('FAST_COMPILE').excluding('fusion')\n f = theano.function([x], [x * 2, x + x], mode=mode)\n topo = f.maker.fgraph.toposort()\n assert len(topo) == 2\n x = tensor.constant(3)\n assert x.ndim == 0\n mode = theano.compile.get_mode('FAST_COMPILE').excluding('fusion')\n f = theano.function([], [x * 2, x + x], mode=mode)\n topo = f.maker.fgraph.toposort()\n assert len(topo) == 2\n assert all([isinstance(n.op, DeepCopyOp) for n in topo])","code_tokens":"","url":525877} +{"project_name":"ermongroup\/MetaIRL","file_name":"instrument.py","full_name":"ensure_dir","func_name":"ensure_dir","docstring":"Ensure that a named directory exists; if it does not, attempt to create it.","docstring_tokens":"","code":"def ensure_dir(dirname):\n \"\"\"\n Ensure that a named directory exists; if it does not, attempt to create it.\n \"\"\"\n try:\n os.makedirs(dirname)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise","code_tokens":"","url":634663} +{"project_name":"StanfordVL\/taskonomy","file_name":"basic_feedforward.py","full_name":"StandardFeedforward.get_losses","func_name":"get_losses","docstring":"Returns the loss for a Siamese Network.","docstring_tokens":"","code":"def get_losses(self, final_output, target, is_softmax=True):\n \"\"\"Returns the loss for a Siamese Network.\n Args:\n final_output: tensor that represent the final output of the image bundle.\n target: Tensor of target to be output by the siamese network.\n \n Returns:\n losses: list of tensors representing each loss component\n \"\"\"\n print('setting up losses...')\n self.target = target\n self.final_output = final_output\n self.predicted = slim.softmax(final_output)\n with tf.variable_scope('losses'):\n if is_softmax:\n if len(target.shape) == len(final_output.shape):\n correct_prediction = tf.equal(tf.argmax(final_output, 1), tf.argmax(target, 1))\n if len(self.masks.shape) == 2:\n self.masks = tf.squeeze(self.masks)\n siamese_loss = tf.reduce_mean(losses_lib.get_softmax_loss(final_output, target, self.masks, scope='softmax_loss'))\n else:\n correct_prediction = tf.equal(tf.argmax(final_output, 1), target)\n siamese_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=final_output, labels=target, name='softmax_loss'))\n self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n self.siamese_loss = siamese_loss\n else:\n self.accuracy = 0\n target = tf.to_float(target)\n final_output = tf.to_float(final_output)\n if self.is_l1:\n self.l_loss = losses_lib.get_l1_loss(final_output, target, scope='d1')\n print('Using L1 loss.....')\n else:\n self.l_loss = losses_lib.get_l2_loss(final_output, target, scope='d1')\n self.siamese_loss = self.l_loss\n self.robust_l_loss = self.l_loss\n tf.add_to_collection(tf.GraphKeys.LOSSES, self.siamese_loss)\n losses = [self.siamese_loss]\n return losses","code_tokens":"","url":907510} +{"project_name":"deepmind\/acme","file_name":"networks.py","full_name":"get_default_behavior_policy","func_name":"get_default_behavior_policy","docstring":"Selects action according to the training policy.","docstring_tokens":"","code":"def get_default_behavior_policy(networks: D4PGNetworks, config: d4pg_config.D4PGConfig) -> actor_core_lib.FeedForwardPolicy:\n \"\"\"Selects action according to the training policy.\"\"\"\n\n def behavior_policy(params: networks_lib.Params, key: networks_lib.PRNGKey, observation: types.NestedArray):\n action = networks.policy_network.apply(params, observation)\n if config.sigma != 0:\n action = rlax.add_gaussian_noise(key, action, config.sigma)\n return action\n return behavior_policy","code_tokens":"","url":7553} +{"project_name":"jeromewang-github\/computer_vision","file_name":"object_detection_2d_data_generator.py","full_name":"DataGenerator.get_dataset_size","func_name":"get_dataset_size","docstring":"Returns: The number of images in the dataset.","docstring_tokens":"","code":"def get_dataset_size(self):\n \"\"\"\n Returns:\n The number of images in the dataset.\n \"\"\"\n return self.dataset_size","code_tokens":"","url":502849} +{"project_name":"openvinotoolkit\/datumaro","file_name":"image.py","full_name":"load_image","func_name":"load_image","docstring":"Reads an image in the HWC Grayscale\/BGR(A) [0; 255] format (default dtype is uint8).","docstring_tokens":"","code":"def load_image(path: str, dtype: DTypeLike=np.uint8, crypter: Crypter=NULL_CRYPTER):\n \"\"\"\n Reads an image in the HWC Grayscale\/BGR(A) [0; 255] format (default dtype is uint8).\n \"\"\"\n if _IMAGE_BACKEND == _IMAGE_BACKENDS.cv2:\n with open(path, 'rb') as f:\n image_bytes = crypter.decrypt(f.read())\n return decode_image(image_bytes, dtype=dtype)\n elif _IMAGE_BACKEND == _IMAGE_BACKENDS.PIL:\n from PIL import Image\n if not crypter.is_null_crypter:\n raise DatumaroError('PIL backend should have crypter=NullCrypter.')\n image = Image.open(path)\n image = np.asarray(image, dtype=dtype)\n if len(image.shape) == 3 and image.shape[2] in {3, 4}:\n image = np.array(image)\n image[:, :, :3] = image[:, :, 2::-1]\n else:\n raise NotImplementedError()\n assert len(image.shape) in {2, 3}\n if len(image.shape) == 3:\n assert image.shape[2] in {3, 4}\n return image","code_tokens":"","url":498214} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"pipeline.py","full_name":"_PipelineExecution.list_parameters","func_name":"list_parameters","docstring":"Gets a list of parameters for a pipeline execution.","docstring_tokens":"","code":"def list_parameters(self, max_results: int=None, next_token: str=None):\n \"\"\"Gets a list of parameters for a pipeline execution.\n\n Args:\n max_results (int): The maximum number of parameters to return in the response.\n next_token (str): If the result of the previous `ListPipelineParametersForExecution`\n request was truncated, the response includes a `NextToken`. To retrieve the next\n set of parameters, use the token in the next request.\n\n Returns:\n Information about the parameters of the pipeline execution. This function is also\n a wrapper for `list_pipeline_parameters_for_execution\n `_.\n \"\"\"\n kwargs = dict(PipelineExecutionArn=self.arn)\n update_args(kwargs, MaxResults=max_results, NextToken=next_token)\n return self.sagemaker_session.sagemaker_client.list_pipeline_parameters_for_execution(**kwargs)","code_tokens":"","url":830644} +{"project_name":"google\/deepvariant","file_name":"runtime_by_region_vis.py","full_name":"individual_region_bars","func_name":"individual_region_bars","docstring":"Makes a stacked bar chart with runtime of each stage for individual regions.","docstring_tokens":"","code":"def individual_region_bars(small_df: pd.DataFrame, title: Union[str, Dict[str, str]]='') -> alt.Chart:\n \"\"\"Makes a stacked bar chart with runtime of each stage for individual regions.\n\n Args:\n small_df: A dataframe of regions, each of which will be shown as a bar.\n title: A title for the plot. If a dict, it should contain 'title' and\/or\n 'subtitle'.\n\n Returns:\n An altair chart.\n \"\"\"\n columns_used = ['region', 'Runtime'] + RUNTIME_COLUMNS\n d = small_df[columns_used]\n return alt.Chart(d).transform_fold(RUNTIME_COLUMNS, as_=['Stage', 'runtime_by_stage']).mark_bar().encode(x=alt.X('region:N', sort=None), y=alt.Y('runtime_by_stage:Q', scale=alt.Scale(type='linear'), title='Runtime (seconds)'), fill=alt.Fill('Stage:N', sort=None), tooltip='Runtime:N').properties(title=title)","code_tokens":"","url":540430} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"fitness.py","full_name":"Tournament.set_tournament_size","func_name":"set_tournament_size","docstring":"This function accepts the tournament size, which is the number of members that will be selected per tournament.","docstring_tokens":"","code":"def set_tournament_size(self, tournament_size):\n \"\"\"\n This function accepts the tournament size, which is the number of\n members that will be selected per tournament.\n\n \"\"\"\n if tournament_size is not None:\n if not isinstance(tournament_size, int):\n raise ValueError('Tournament size, %s must be an int.' % tournament_size)\n if self._selection_list:\n if tournament_size > len(self._selection_list):\n raise ValueError('The tournament size, %s, cannot\\n be larger than the population, %s.' % (tournament_size, len(self._selection_list)))\n self._tournament_size = tournament_size","code_tokens":"","url":722875} +{"project_name":"srai-lab\/srai","file_name":"h3.py","full_name":"shapely_geometry_to_h3","func_name":"shapely_geometry_to_h3","docstring":"Convert Shapely geometry to H3 indexes.","docstring_tokens":"","code":"def shapely_geometry_to_h3(geometry: Union[BaseGeometry, Iterable[BaseGeometry], gpd.GeoSeries, gpd.GeoDataFrame], h3_resolution: int, buffer: bool=True) -> List[str]:\n \"\"\"\n Convert Shapely geometry to H3 indexes.\n\n Args:\n geometry (Union[BaseGeometry, Iterable[BaseGeometry], GeoSeries, GeoDataFrame]):\n Shapely geometry to be converted.\n h3_resolution (int): H3 resolution of the cells. See [1] for a full comparison.\n buffer (bool, optional): Whether to fully cover the geometries with\n H3 Cells (visible on the borders). Defaults to True.\n\n Returns:\n List[str]: List of H3 indexes that cover a given geometry.\n\n Raises:\n ValueError: If resolution is not between 0 and 15.\n\n References:\n 1. https:\/\/h3geo.org\/docs\/core-library\/restable\/\n \"\"\"\n if not 0 <= h3_resolution <= 15:\n raise ValueError(f'Resolution {h3_resolution} is not between 0 and 15.')\n if _is_macos():\n return _polygon_to_h3_index_raw(geometry, h3_resolution, buffer)\n wkb = []\n if isinstance(geometry, gpd.GeoSeries):\n wkb = geometry.to_wkb()\n elif isinstance(geometry, gpd.GeoDataFrame):\n wkb = geometry[GEOMETRY_COLUMN].to_wkb()\n elif isinstance(geometry, Iterable):\n wkb = [sub_geometry.wkb for sub_geometry in geometry]\n else:\n wkb = [geometry.wkb]\n h3_indexes = wkb_to_cells(wkb, resolution=h3_resolution, all_intersecting=buffer, flatten=True).unique()\n return [h3.int_to_str(h3_index) for h3_index in h3_indexes.tolist()]","code_tokens":"","url":371845} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"nav_env.py","full_name":"GridWorld.to_actual_xyt_vec","func_name":"to_actual_xyt_vec","docstring":"Converts from node array to location array on the map.","docstring_tokens":"","code":"def to_actual_xyt_vec(self, pqr):\n \"\"\"Converts from node array to location array on the map.\"\"\"\n p = pqr[:, 0][:, np.newaxis]\n q = pqr[:, 1][:, np.newaxis]\n r = pqr[:, 2][:, np.newaxis]\n if self.task.n_ori == 6:\n out = np.concatenate((p - q * 0.5 + self.task.origin_loc[0], q * np.sqrt(3.0) \/ 2.0 + self.task.origin_loc[1], r), axis=1)\n elif self.task.n_ori == 4:\n out = np.concatenate((p + self.task.origin_loc[0], q + self.task.origin_loc[1], r), axis=1)\n return out","code_tokens":"","url":47173} +{"project_name":"feast-dev\/feast","file_name":"file_source.py","full_name":"FileSource.file_format","func_name":"file_format","docstring":"Returns the file format of this file data source.","docstring_tokens":"","code":"@property\ndef file_format(self) -> Optional[FileFormat]:\n \"\"\"Returns the file format of this file data source.\"\"\"\n return self.file_options.file_format","code_tokens":"","url":544363} +{"project_name":"rudranil723\/mini-main","file_name":"uploadhandler.py","full_name":"MemoryFileUploadHandler.file_complete","func_name":"file_complete","docstring":"Return a file object if this handler is activated.","docstring_tokens":"","code":"def file_complete(self, file_size):\n \"\"\"Return a file object if this handler is activated.\"\"\"\n if not self.activated:\n return\n self.file.seek(0)\n return InMemoryUploadedFile(file=self.file, field_name=self.field_name, name=self.file_name, content_type=self.content_type, size=file_size, charset=self.charset, content_type_extra=self.content_type_extra)","code_tokens":"","url":315556} +{"project_name":"rlworkgroup\/garage","file_name":"benchmarks.py","full_name":"get_benchmark","func_name":"get_benchmark","docstring":"Get a benchmark by name.","docstring_tokens":"","code":"def get_benchmark(benchmark_name):\n \"\"\"Get a benchmark by name.\"\"\"\n for b in _BENCHMARKS:\n if b['name'] == benchmark_name:\n return b\n raise ValueError('%s not found! Known benchmarks: %s' % (benchmark_name, list_benchmarks()))","code_tokens":"","url":200065} +{"project_name":"markbirbeck\/sublime-text-shell-command","file_name":"SublimeHelper.py","full_name":"TextCommand.get_region","func_name":"get_region","docstring":"Get the value under the cursor, or cursors.","docstring_tokens":"","code":"def get_region(self, view=None, can_select_entire_buffer=False):\n \"\"\"Get the value under the cursor, or cursors.\"\"\"\n value = ''\n (view, window) = self.get_view_and_window(view)\n if view is not None:\n selection = view.sel()\n if can_select_entire_buffer is True:\n if len(selection) == 1 and selection[0].empty():\n selection = [sublime.Region(0, view.size())]\n if selection is not None:\n for region in selection:\n if region.empty():\n region = view.expand_by_class(region, sublime.CLASS_WORD_START | sublime.CLASS_WORD_END, ' ():')\n value = value + ' ' + view.substr(region)\n return value","code_tokens":"","url":360004} +{"project_name":"facebookresearch\/detectron2","file_name":"instances.py","full_name":"Instances.has","func_name":"has","docstring":"Returns: bool: whether the field called `name` exists.","docstring_tokens":"","code":"def has(self, name: str) -> bool:\n \"\"\"\n Returns:\n bool: whether the field called `name` exists.\n \"\"\"\n return name in self._fields","code_tokens":"","url":549312} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"factory_test.py","full_name":"FactoryTest.test_mobilenet_creation","func_name":"test_mobilenet_creation","docstring":"Test creation of Mobilenet models.","docstring_tokens":"","code":"@combinations.generate(combinations.combine(model_id=['MobileNetV1', 'MobileNetV2', 'MobileNetV3Large', 'MobileNetV3Small', 'MobileNetV3EdgeTPU'], filter_size_scale=[1.0, 0.75]))\ndef test_mobilenet_creation(self, model_id, filter_size_scale):\n \"\"\"Test creation of Mobilenet models.\"\"\"\n network = backbones.MobileNet(model_id=model_id, filter_size_scale=filter_size_scale, norm_momentum=0.99, norm_epsilon=1e-05)\n backbone_config = backbones_cfg.Backbone(type='mobilenet', mobilenet=backbones_cfg.MobileNet(model_id=model_id, filter_size_scale=filter_size_scale))\n norm_activation_config = common_cfg.NormActivation(norm_momentum=0.99, norm_epsilon=1e-05)\n model_config = retinanet_cfg.RetinaNet(backbone=backbone_config, norm_activation=norm_activation_config)\n factory_network = factory.build_backbone(input_specs=tf.keras.layers.InputSpec(shape=[None, None, None, 3]), model_config=model_config)\n network_config = network.get_config()\n factory_network_config = factory_network.get_config()\n self.assertEqual(network_config, factory_network_config)","code_tokens":"","url":850802} +{"project_name":"rudranil723\/mini-main","file_name":"descriptor_pool.py","full_name":"DescriptorPool.FindExtensionByName","func_name":"FindExtensionByName","docstring":"Loads the named extension descriptor from the pool.","docstring_tokens":"","code":"def FindExtensionByName(self, full_name):\n \"\"\"Loads the named extension descriptor from the pool.\n\n Args:\n full_name (str): The full name of the extension descriptor to load.\n\n Returns:\n FieldDescriptor: The field descriptor for the named extension.\n\n Raises:\n KeyError: if the extension cannot be found in the pool.\n \"\"\"\n full_name = _NormalizeFullyQualifiedName(full_name)\n try:\n return self._toplevel_extensions[full_name]\n except KeyError:\n pass\n (message_name, _, extension_name) = full_name.rpartition('.')\n try:\n scope = self.FindMessageTypeByName(message_name)\n except KeyError:\n scope = self._FindFileContainingSymbolInDb(full_name)\n return scope.extensions_by_name[extension_name]","code_tokens":"","url":318257} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"timeline.py","full_name":"_TensorTracker.object_id","func_name":"object_id","docstring":"Returns the object identifier of this tensor (integer).","docstring_tokens":"","code":"@property\ndef object_id(self):\n \"\"\"Returns the object identifier of this tensor (integer).\"\"\"\n return self._object_id","code_tokens":"","url":182304} +{"project_name":"Farama-Foundation\/D4RL","file_name":"renderer.py","full_name":"Renderer.close","func_name":"close","docstring":"Cleans up any resources being used by the renderer.","docstring_tokens":"","code":"@abc.abstractmethod\ndef close(self):\n \"\"\"Cleans up any resources being used by the renderer.\"\"\"","code_tokens":"","url":126313} +{"project_name":"intel\/neural-compressor","file_name":"server.py","full_name":"disable_cache","func_name":"disable_cache","docstring":"Disable cache on all requests.","docstring_tokens":"","code":"@app_blueprint.after_request\ndef disable_cache(response: WebResponse) -> WebResponse:\n \"\"\"Disable cache on all requests.\"\"\"\n response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'\n response.headers['Pragma'] = 'no-cache'\n response.headers['Expires'] = '0'\n response.headers['Cache-Control'] = 'public, max-age=0'\n return response","code_tokens":"","url":721761} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"revnet.py","full_name":"init","func_name":"init","docstring":"Standard ResNet initial block used as first RevNet block.","docstring_tokens":"","code":"def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'):\n \"\"\"Standard ResNet initial block used as first RevNet block.\n\n Args:\n images: [N, H, W, 3] tensor of input images to the model.\n num_channels: Output depth of convolutional layer in initial block.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n stride: stride for the convolution and pool layer.\n kernel_size: Size of the initial convolution filter\n maxpool: If true, apply a maxpool after the convolution\n training: True for train phase, False for eval phase.\n scope: Optional scope for the init block.\n\n Returns:\n Two [N, H, W, C] output activations from input images.\n \"\"\"\n conv = CONFIG[dim]['conv']\n pool = CONFIG[dim]['max_pool']\n with tf.variable_scope(scope):\n net = conv(images, num_channels, kernel_size, strides=stride, padding='SAME', activation=None)\n net = tf.layers.batch_normalization(net, training=training)\n net = tf.nn.relu(net)\n if maxpool:\n net = pool(net, pool_size=3, strides=stride)\n (x1, x2) = tf.split(net, 2, axis=CONFIG[dim]['split_axis'])\n return (x1, x2)","code_tokens":"","url":965661} +{"project_name":"hamza-murad\/AALU","file_name":"assistant_v2.py","full_name":"MessageResponse.from_dict","func_name":"from_dict","docstring":"Initialize a MessageResponse object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'MessageResponse':\n \"\"\"Initialize a MessageResponse object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['output', 'context']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class MessageResponse: ' + ', '.join(bad_keys))\n if 'output' in _dict:\n args['output'] = MessageOutput._from_dict(_dict.get('output'))\n else:\n raise ValueError(\"Required property 'output' not present in MessageResponse JSON\")\n if 'context' in _dict:\n args['context'] = MessageContext._from_dict(_dict.get('context'))\n return cls(**args)","code_tokens":"","url":5322} +{"project_name":"salesforce\/CodeRL","file_name":"logging.py","full_name":"set_verbosity","func_name":"set_verbosity","docstring":"Set the verbosity level for the \u00c3\u00b0\u00c2\u009f\u00c2\u00a4\u00c2\u0097 Transformers's root logger.","docstring_tokens":"","code":"def set_verbosity(verbosity: int) -> None:\n \"\"\"\n Set the verbosity level for the \u00c3\u00b0\u00c2\\x9f\u00c2\u00a4\u00c2\\x97 Transformers's root logger.\n\n Args:\n verbosity (`int`):\n Logging level, e.g., one of:\n\n - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`\n - `transformers.logging.ERROR`\n - `transformers.logging.WARNING` or `transformers.logging.WARN`\n - `transformers.logging.INFO`\n - `transformers.logging.DEBUG`\n \"\"\"\n _configure_library_root_logger()\n _get_library_root_logger().setLevel(verbosity)","code_tokens":"","url":495594} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_encoders.py","full_name":"test_ohe_infrequent_two_levels_drop_frequent","func_name":"test_ohe_infrequent_two_levels_drop_frequent","docstring":"Test two levels and dropping the frequent category.","docstring_tokens":"","code":"@pytest.mark.parametrize('drop', ['if_binary', 'first', ['b']])\ndef test_ohe_infrequent_two_levels_drop_frequent(drop):\n \"\"\"Test two levels and dropping the frequent category.\"\"\"\n X_train = np.array([['a'] * 5 + ['b'] * 20 + ['c'] * 10 + ['d'] * 3]).T\n ohe = OneHotEncoder(handle_unknown='infrequent_if_exist', sparse_output=False, max_categories=2, drop=drop).fit(X_train)\n assert ohe.categories_[0][ohe.drop_idx_[0]] == 'b'\n X_test = np.array([['b'], ['c']])\n X_trans = ohe.transform(X_test)\n assert_allclose([[0], [1]], X_trans)\n feature_names = ohe.get_feature_names_out()\n assert_array_equal(['x0_infrequent_sklearn'], feature_names)\n X_inverse = ohe.inverse_transform(X_trans)\n assert_array_equal([['b'], ['infrequent_sklearn']], X_inverse)","code_tokens":"","url":364522} +{"project_name":"matsu0228\/nlp-jp","file_name":"wordrank.py","full_name":"Wordrank.ensemble_embedding","func_name":"ensemble_embedding","docstring":"Replace syn0 with the sum of context and word embeddings.","docstring_tokens":"","code":"def ensemble_embedding(self, word_embedding, context_embedding):\n \"\"\"Replace syn0 with the sum of context and word embeddings.\"\"\"\n glove2word2vec(context_embedding, context_embedding + '.w2vformat')\n w_emb = KeyedVectors.load_word2vec_format('%s.w2vformat' % word_embedding)\n c_emb = KeyedVectors.load_word2vec_format('%s.w2vformat' % context_embedding)\n assert set(w_emb.vocab) == set(c_emb.vocab), 'Vocabs are not same for both embeddings'\n prev_c_emb = copy.deepcopy(c_emb.syn0)\n for (word_id, word) in enumerate(w_emb.index2word):\n c_emb.syn0[word_id] = prev_c_emb[c_emb.vocab[word].index]\n new_emb = w_emb.syn0 + c_emb.syn0\n self.syn0 = new_emb\n return new_emb","code_tokens":"","url":785972} +{"project_name":"Dsajeet\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"visitor.py","full_name":"Base.stripComment","func_name":"stripComment","docstring":"Regex substitutions for comments; removes comment characters.","docstring_tokens":"","code":"def stripComment(self, text):\n \"\"\" Regex substitutions for comments; removes comment characters. \"\"\"\n subText = lambda value, regex: resub(regex, '', value)\n for text in ifilter(unicode.strip, text.split('\\n')):\n yield reduce(subText, self.commentSubs, text)","code_tokens":"","url":17190} +{"project_name":"pytorch\/rl","file_name":"transforms.py","full_name":"Transform.transform_observation_spec","func_name":"transform_observation_spec","docstring":"Transforms the observation spec such that the resulting spec matches transform mapping.","docstring_tokens":"","code":"def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:\n \"\"\"Transforms the observation spec such that the resulting spec matches transform mapping.\n\n Args:\n observation_spec (TensorSpec): spec before the transform\n\n Returns:\n expected spec after the transform\n\n \"\"\"\n return observation_spec","code_tokens":"","url":859091} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"TestUtils.py","full_name":"CythonTest.fragment","func_name":"fragment","docstring":"Simply create a tree fragment using the name of the test-case in parse errors.","docstring_tokens":"","code":"def fragment(self, code, pxds=None, pipeline=None):\n \"\"\"Simply create a tree fragment using the name of the test-case in parse errors.\"\"\"\n if pxds is None:\n pxds = {}\n if pipeline is None:\n pipeline = []\n name = self.id()\n if name.startswith('__main__.'):\n name = name[len('__main__.'):]\n name = name.replace('.', '_')\n return TreeFragment(code, name, pxds, pipeline=pipeline)","code_tokens":"","url":36452} +{"project_name":"Alvin0629\/Code-for-DEEP-UNSUPERVISED-LEARNING-FOR-SIMULTANEOUS-VISUAL-ODOMETRY-AND-DEPTH-ESTIMATION-","file_name":"kitti_raw_loader.py","full_name":"rotz","func_name":"rotz","docstring":"Rotation about the z-axis.","docstring_tokens":"","code":"def rotz(t):\n \"\"\"Rotation about the z-axis.\"\"\"\n c = np.cos(t)\n s = np.sin(t)\n return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])","code_tokens":"","url":124746} +{"project_name":"yburda\/iwae","file_name":"nnet.py","full_name":"random_linear_then_tanh_chain","func_name":"random_linear_then_tanh_chain","docstring":"Returns a neural network consisting of alternating Linear and Tanh layers.","docstring_tokens":"","code":"def random_linear_then_tanh_chain(n_units):\n \"\"\"Returns a neural network consisting of alternating Linear and Tanh layers.\"\"\"\n model = NNet()\n for (n_in, n_out) in zip(n_units, n_units[1:]):\n model.add_layer(Linear.random(n_in, n_out))\n model.add_layer(Tanh())\n return model","code_tokens":"","url":577586} +{"project_name":"huggingface\/datasets-server","file_name":"parquet_metadata.py","full_name":"compute_parquet_metadata_response","func_name":"compute_parquet_metadata_response","docstring":"Store the config's parquet metadata on the disk and return the list of local metadata files.","docstring_tokens":"","code":"def compute_parquet_metadata_response(dataset: str, config: str, hf_token: Optional[str], parquet_metadata_directory: StrPath) -> ConfigParquetMetadataResponse:\n \"\"\"\n Store the config's parquet metadata on the disk and return the list of local metadata files.\n Args:\n dataset (`str`):\n A namespace (user or an organization) and a repo name separated\n by a `\/`.\n config (`str`):\n A configuration name.\n hf_token (`str`, *optional*):\n An authentication token (See https:\/\/huggingface.co\/settings\/token)\n parquet_metadata_directory (`str` or `pathlib.Path`):\n The directory where the parquet metadata files are stored.\n Returns:\n `ConfigParquetMetadataResponse`: An object with the list of parquet metadata files.\n \n Raises the following errors:\n - [`~libcommon.simple_cache.CachedArtifactError`]\n If the previous step gave an error.\n - [`~libcommon.exceptions.PreviousStepFormatError`]\n If the content of the previous step has not the expected format\n - [`~libcommon.exceptions.ParquetResponseEmptyError`]\n If the previous step provided an empty list of parquet files.\n - [`~libcommon.exceptions.FileSystemError`]\n If the HfFileSystem couldn't access the parquet files.\n <\/Tip>\n \"\"\"\n logging.info(f'get parquet files for dataset={dataset}, config={config}')\n config_parquet_best_response = get_previous_step_or_raise(kinds=['config-parquet'], dataset=dataset, config=config)\n try:\n parquet_files_content = config_parquet_best_response.response['content']['parquet_files']\n parquet_file_items: list[SplitHubFile] = [parquet_file_item for parquet_file_item in parquet_files_content if parquet_file_item['config'] == config]\n if not parquet_file_items:\n raise ParquetResponseEmptyError('No parquet files found.')\n content = config_parquet_best_response.response['content']\n if 'features' in content and isinstance(content['features'], dict):\n features = content['features']\n else:\n features = None\n partial = config_parquet_best_response.response['content']['partial']\n except Exception as e:\n raise PreviousStepFormatError('Previous step did not return the expected content.') from e\n fs = HTTPFileSystem()\n desc = f'{dataset}\/{config}'\n parquet_files_metadata: list[ParquetFileMetadataItem] = thread_map(functools.partial(create_parquet_metadata_file_from_remote_parquet, fs=fs, hf_token=hf_token, parquet_metadata_directory=parquet_metadata_directory), parquet_file_items, desc=desc, unit='pq', disable=True)\n return ConfigParquetMetadataResponse(parquet_files_metadata=parquet_files_metadata, features=features, partial=partial)","code_tokens":"","url":497940} +{"project_name":"tensorflow\/agents","file_name":"distribution_spec.py","full_name":"DistributionSpec.distribution_parameters","func_name":"distribution_parameters","docstring":"Returns the `distribution_parameters` of the spec.","docstring_tokens":"","code":"@property\ndef distribution_parameters(self):\n \"\"\"Returns the `distribution_parameters` of the spec.\"\"\"\n return self._distribution_parameters","code_tokens":"","url":23693} +{"project_name":"Media-Smart\/volkscv","file_name":"anchor_processor.py","full_name":"AnchorProcessor.areas","func_name":"areas","docstring":"List of box area.","docstring_tokens":"","code":"@property\ndef areas(self):\n \"\"\"List of box area.\"\"\"\n return self._areas","code_tokens":"","url":946391} +{"project_name":"rudranil723\/mini-main","file_name":"finders.py","full_name":"AppDirectoriesFinder.list","func_name":"list","docstring":"List all files in all app storages.","docstring_tokens":"","code":"def list(self, ignore_patterns):\n \"\"\"\n List all files in all app storages.\n \"\"\"\n for storage in self.storages.values():\n if storage.exists(''):\n for path in utils.get_files(storage, ignore_patterns):\n yield (path, storage)","code_tokens":"","url":315459} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"tix.py","full_name":"ButtonBox.add","func_name":"add","docstring":"Add a button with given name to box.","docstring_tokens":"","code":"def add(self, name, cnf={}, **kw):\n \"\"\"Add a button with given name to box.\"\"\"\n btn = self.tk.call(self._w, 'add', name, *self._options(cnf, kw))\n self.subwidget_list[name] = _dummyButton(self, name)\n return btn","code_tokens":"","url":283912} +{"project_name":"pykale\/pykale","file_name":"cross_validation.py","full_name":"leave_one_group_out","func_name":"leave_one_group_out","docstring":"Perform leave one group out cross validation for a given estimator.","docstring_tokens":"","code":"def leave_one_group_out(x, y, groups, estimator, use_domain_adaptation=False) -> dict:\n \"\"\"\n Perform leave one group out cross validation for a given estimator.\n\n Args:\n x (np.ndarray or torch.tensor): Input data [n_samples, n_features].\n y (np.ndarray or torch.tensor): Target labels [n_samples].\n groups (np.ndarray or torch.tensor): Group labels to be left out [n_samples].\n estimator (estimator object): Machine learning estimator to be evaluated from kale or scikit-learn.\n use_domain_adaptation (bool): Whether to use domain adaptation, i.e., leveraging test data, during training.\n\n Returns:\n dict: A dictionary containing results for each target group with 3 keys.\n - 'Target': A list of unique target groups or classes. The final entry is \"Average\".\n - 'Num_samples': A list where each entry indicates the number of samples in its corresponding target group.\n The final entry represents the total number of samples.\n - 'Accuracy': A list where each entry indicates the accuracy score for its corresponding target group.\n The final entry represents the overall mean accuracy.\n \"\"\"\n enc = OneHotEncoder(handle_unknown='ignore')\n group_mat = enc.fit_transform(groups.reshape(-1, 1)).toarray()\n (target, num_samples, accuracy) = (np.unique(groups).tolist(), [], [])\n y_pred = np.zeros(y.shape)\n for (train, test) in LeaveOneGroupOut().split(x, y, groups=groups):\n (x_src, x_tgt) = (x[train], x[test])\n (y_src, y_tgt) = (y[train], y[test])\n if use_domain_adaptation:\n estimator.fit(np.concatenate((x_src, x_tgt)), y_src, np.concatenate((group_mat[train], group_mat[test])))\n else:\n estimator.fit(x_src, y_src)\n y_pred[test] = estimator.predict(x_tgt)\n num_samples.append(x_tgt.shape[0])\n accuracy.append(accuracy_score(y_tgt, y_pred[test]))\n target.append('Average')\n num_samples.append(x.shape[0])\n accuracy.append(accuracy_score(y, y_pred))\n return {'Target': target, 'Num_samples': num_samples, 'Accuracy': accuracy}","code_tokens":"","url":819649} +{"project_name":"GUR9000\/Deep_MRI_brain_extraction","file_name":"NN_PerceptronLayer.py","full_name":"PerceptronLayer.negative_log_likelihood_array","func_name":"negative_log_likelihood_array","docstring":"Return the negative log-likelihood of the prediction of this model under a given target distribution for each element of the batch individually.","docstring_tokens":"","code":"def negative_log_likelihood_array(self, y):\n \"\"\"Return the negative log-likelihood of the prediction\n of this model under a given target distribution for each element of the batch individually.\n\n \"\"\"\n return -T.log(self.class_probabilities)[T.arange(y.shape[0]), y]","code_tokens":"","url":536708} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"config.py","full_name":"IdleUserConfParser.IsEmpty","func_name":"IsEmpty","docstring":"Return True if no sections after removing empty sections.","docstring_tokens":"","code":"def IsEmpty(self):\n \"\"\"Return True if no sections after removing empty sections.\"\"\"\n self.RemoveEmptySections()\n return not self.sections()","code_tokens":"","url":282699} +{"project_name":"cleanlab\/cleanlab","file_name":"label_issues_batched.py","full_name":"split_arr","func_name":"split_arr","docstring":"Helper function to split array into chunks for multiprocessing.","docstring_tokens":"","code":"def split_arr(arr: np.ndarray, chunksize: int) -> List[np.ndarray]:\n \"\"\"\n Helper function to split array into chunks for multiprocessing.\n \"\"\"\n return np.split(arr, np.arange(chunksize, arr.shape[0], chunksize), axis=0)","code_tokens":"","url":487986} +{"project_name":"chenbinghui1\/DSL","file_name":"coco.py","full_name":"CocoDataset.evaluate","func_name":"evaluate","docstring":"Evaluation in COCO protocol.","docstring_tokens":"","code":"def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None):\n \"\"\"Evaluation in COCO protocol.\n\n Args:\n results (list[list | tuple]): Testing results of the dataset.\n metric (str | list[str]): Metrics to be evaluated. Options are\n 'bbox', 'segm', 'proposal', 'proposal_fast'.\n logger (logging.Logger | str | None): Logger used for printing\n related information during evaluation. Default: None.\n jsonfile_prefix (str | None): The prefix of json files. It includes\n the file path and the prefix of filename, e.g., \"a\/b\/prefix\".\n If not specified, a temp file will be created. Default: None.\n classwise (bool): Whether to evaluating the AP for each class.\n proposal_nums (Sequence[int]): Proposal number used for evaluating\n recalls, such as recall@100, recall@1000.\n Default: (100, 300, 1000).\n iou_thrs (Sequence[float], optional): IoU threshold used for\n evaluating recalls\/mAPs. If set to a list, the average of all\n IoUs will also be computed. If not specified, [0.50, 0.55,\n 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] will be used.\n Default: None.\n metric_items (list[str] | str, optional): Metric items that will\n be returned. If not specified, ``['AR@100', 'AR@300',\n 'AR@1000', 'AR_s@1000', 'AR_m@1000', 'AR_l@1000' ]`` will be\n used when ``metric=='proposal'``, ``['mAP', 'mAP_50', 'mAP_75',\n 'mAP_s', 'mAP_m', 'mAP_l']`` will be used when\n ``metric=='bbox' or metric=='segm'``.\n\n Returns:\n dict[str, float]: COCO style evaluation metric.\n \"\"\"\n metrics = metric if isinstance(metric, list) else [metric]\n allowed_metrics = ['bbox', 'segm', 'proposal', 'proposal_fast']\n for metric in metrics:\n if metric not in allowed_metrics:\n raise KeyError(f'metric {metric} is not supported')\n if iou_thrs is None:\n iou_thrs = np.linspace(0.5, 0.95, int(np.round((0.95 - 0.5) \/ 0.05)) + 1, endpoint=True)\n if metric_items is not None:\n if not isinstance(metric_items, list):\n metric_items = [metric_items]\n (result_files, tmp_dir) = self.format_results(results, jsonfile_prefix)\n eval_results = OrderedDict()\n cocoGt = self.coco\n for metric in metrics:\n msg = f'Evaluating {metric}...'\n if logger is None:\n msg = '\\n' + msg\n print_log(msg, logger=logger)\n if metric == 'proposal_fast':\n ar = self.fast_eval_recall(results, proposal_nums, iou_thrs, logger='silent')\n log_msg = []\n for (i, num) in enumerate(proposal_nums):\n eval_results[f'AR@{num}'] = ar[i]\n log_msg.append(f'\\nAR@{num}\\t{ar[i]:.4f}')\n log_msg = ''.join(log_msg)\n print_log(log_msg, logger=logger)\n continue\n iou_type = 'bbox' if metric == 'proposal' else metric\n if metric not in result_files:\n raise KeyError(f'{metric} is not in results')\n try:\n predictions = mmcv.load(result_files[metric])\n if iou_type == 'segm':\n for x in predictions:\n x.pop('bbox')\n warnings.simplefilter('once')\n warnings.warn('The key \"bbox\" is deleted for more accurate mask AP of small\/medium\/large instances since v2.12.0. This does not change the overall mAP calculation.', UserWarning)\n cocoDt = cocoGt.loadRes(predictions)\n except IndexError:\n print_log('The testing results of the whole dataset is empty.', logger=logger, level=logging.ERROR)\n break\n cocoEval = COCOeval(cocoGt, cocoDt, iou_type)\n cocoEval.params.catIds = self.cat_ids\n cocoEval.params.imgIds = self.img_ids\n cocoEval.params.maxDets = list(proposal_nums)\n cocoEval.params.iouThrs = iou_thrs\n coco_metric_names = {'mAP': 0, 'mAP_50': 1, 'mAP_75': 2, 'mAP_s': 3, 'mAP_m': 4, 'mAP_l': 5, 'AR@100': 6, 'AR@300': 7, 'AR@1000': 8, 'AR_s@1000': 9, 'AR_m@1000': 10, 'AR_l@1000': 11}\n if metric_items is not None:\n for metric_item in metric_items:\n if metric_item not in coco_metric_names:\n raise KeyError(f'metric item {metric_item} is not supported')\n if metric == 'proposal':\n cocoEval.params.useCats = 0\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n if metric_items is None:\n metric_items = ['AR@100', 'AR@300', 'AR@1000', 'AR_s@1000', 'AR_m@1000', 'AR_l@1000']\n for item in metric_items:\n val = float(f'{cocoEval.stats[coco_metric_names[item]]:.3f}')\n eval_results[item] = val\n else:\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n if classwise:\n precisions = cocoEval.eval['precision']\n assert len(self.cat_ids) == precisions.shape[2]\n results_per_category = []\n for (idx, catId) in enumerate(self.cat_ids):\n nm = self.coco.loadCats(catId)[0]\n precision = precisions[:, :, idx, 0, -1]\n precision = precision[precision > -1]\n if precision.size:\n ap = np.mean(precision)\n else:\n ap = float('nan')\n results_per_category.append((f\"{nm['name']}\", f'{float(ap):0.3f}'))\n num_columns = min(6, len(results_per_category) * 2)\n results_flatten = list(itertools.chain(*results_per_category))\n headers = ['category', 'AP'] * (num_columns \/\/ 2)\n results_2d = itertools.zip_longest(*[results_flatten[i::num_columns] for i in range(num_columns)])\n table_data = [headers]\n table_data += [result for result in results_2d]\n table = AsciiTable(table_data)\n print_log('\\n' + table.table, logger=logger)\n if metric_items is None:\n metric_items = ['mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l']\n for metric_item in metric_items:\n key = f'{metric}_{metric_item}'\n val = float(f'{cocoEval.stats[coco_metric_names[metric_item]]:.3f}')\n eval_results[key] = val\n ap = cocoEval.stats[:6]\n eval_results[f'{metric}_mAP_copypaste'] = f'{ap[0]:.3f} {ap[1]:.3f} {ap[2]:.3f} {ap[3]:.3f} {ap[4]:.3f} {ap[5]:.3f}'\n if tmp_dir is not None:\n tmp_dir.cleanup()\n return eval_results","code_tokens":"","url":167534} +{"project_name":"aws\/sagemaker-training-toolkit","file_name":"encoders.py","full_name":"npy_to_numpy","func_name":"npy_to_numpy","docstring":"Convert an NPY array into numpy.","docstring_tokens":"","code":"def npy_to_numpy(npy_array):\n \"\"\"Convert an NPY array into numpy.\n\n Args:\n npy_array (npy array): NPY array to be converted.\n Returns:\n (np.array): Converted numpy array.\n \"\"\"\n stream = BytesIO(npy_array)\n return np.load(stream, allow_pickle=True)","code_tokens":"","url":844968} +{"project_name":"boris-kz\/CogAlg","file_name":"utils.py","full_name":"shrink","func_name":"shrink","docstring":"Return shape tuple that is shrunken by x units.","docstring_tokens":"","code":"def shrink(shape, x, axes=(0, 1)):\n \"\"\"Return shape tuple that is shrunken by x units.\"\"\"\n return tuple((X - x if axis in axes else X for (axis, X) in enumerate(shape)))","code_tokens":"","url":495901} +{"project_name":"jbwang1997\/CrossKD","file_name":"crowdhuman_metric.py","full_name":"CrowdHumanMetric.get_ignores","func_name":"get_ignores","docstring":"Get the number of ignore bboxes.","docstring_tokens":"","code":"def get_ignores(self, dt_boxes, gt_boxes):\n \"\"\"Get the number of ignore bboxes.\"\"\"\n if gt_boxes.size:\n ioas = bbox_overlaps(dt_boxes, gt_boxes, mode='iof')\n ioas = np.max(ioas, axis=1)\n rows = np.where(ioas > self.iou_thres)[0]\n return len(rows)\n else:\n return 0","code_tokens":"","url":490870} +{"project_name":"renfredxh\/compilebot","file_name":"compilebot.py","full_name":"CompiledReply.detect_spam","func_name":"detect_spam","docstring":"Scan a reply and return a list of potentially spammy attributes found in the comment's output.","docstring_tokens":"","code":"def detect_spam(self):\n \"\"\"Scan a reply and return a list of potentially spammy attributes\n found in the comment's output.\n \"\"\"\n output = self.compile_details['output']\n source = self.compile_details['source']\n errors = self.compile_details['stderr']\n spam_behaviors = {'Excessive line breaks': output.count('\\n') > config.LINE_LIMIT, 'Excessive character count': len(output) > config.CHAR_LIMIT, 'Spam phrase detected': any([word.encode('utf-8').lower() in (source + output).encode('utf-8').lower() for word in config.SPAM_PHRASES]), 'Illegal system call detected': 'Permission denied' in errors}\n if any(spam_behaviors.values()):\n spam_triggers = [k for (k, v) in spam_behaviors.iteritems() if v]\n return spam_triggers\n return []","code_tokens":"","url":125315} +{"project_name":"mj-will\/nessai","file_name":"test_analytic.py","full_name":"test_draw_out_of_samples","func_name":"test_draw_out_of_samples","docstring":"Assert populated is set to false when the last sample is used.","docstring_tokens":"","code":"def test_draw_out_of_samples(proposal):\n \"\"\"Assert populated is set to false when the last sample is used.\"\"\"\n N = 5\n proposal.populated = True\n proposal.indices = [0]\n proposal.samples = np.array([0, 1, 2, 3, 4])\n sample = AnalyticProposal.draw(proposal, 1, N=N)\n assert sample == 0\n assert proposal.indices == []\n assert proposal.populated is False","code_tokens":"","url":292639} +{"project_name":"google-research\/scenic","file_name":"dataset_utils.py","full_name":"tokenize_masked_words","func_name":"tokenize_masked_words","docstring":"Tokenize masked words and add them to the batch in `masked_targets` field.","docstring_tokens":"","code":"def tokenize_masked_words(batch, tokenizer, max_num_tokens, prepend_bos, append_eos):\n \"\"\"Tokenize masked words and add them to the batch in `masked_targets` field.\"\"\"\n caption_string = batch['mwp_caption_string'][0]\n word_mask = batch['mwp_word_mask']\n masked_word_strings = tf.boolean_mask(tf.strings.split(caption_string), word_mask)\n tokenized = tokenizer.string_tensor_to_indices(masked_word_strings, prepend_bos=prepend_bos, append_eos=append_eos, max_num_tokens=max_num_tokens)\n batch['masked_targets'] = tokenized\n del batch['mwp_word_mask'], batch['mwp_caption_string']\n return batch","code_tokens":"","url":846381} +{"project_name":"victordibia\/data2vis","file_name":"seq2seq_model.py","full_name":"Seq2SeqModel.batch_size","func_name":"batch_size","docstring":"Returns the batch size of the curren batch based on the passed features.","docstring_tokens":"","code":"def batch_size(self, features, labels):\n \"\"\"Returns the batch size of the curren batch based on the passed\n features.\n \"\"\"\n return tf.shape(features['source_ids'])[0]","code_tokens":"","url":126870} +{"project_name":"ishtiaq1495\/Generative_adversarial_networks","file_name":"solver.py","full_name":"Solver.train_multi","func_name":"train_multi","docstring":"Train StarGAN with multiple datasets.","docstring_tokens":"","code":"def train_multi(self):\n \"\"\"Train StarGAN with multiple datasets.\"\"\"\n celeba_iter = iter(self.celeba_loader)\n rafd_iter = iter(self.rafd_loader)\n (x_fixed, c_org) = next(celeba_iter)\n x_fixed = x_fixed.to(self.device)\n c_celeba_list = self.create_labels(c_org, self.c_dim, 'CelebA', self.selected_attrs)\n c_rafd_list = self.create_labels(c_org, self.c2_dim, 'RaFD')\n zero_celeba = torch.zeros(x_fixed.size(0), self.c_dim).to(self.device)\n zero_rafd = torch.zeros(x_fixed.size(0), self.c2_dim).to(self.device)\n mask_celeba = self.label2onehot(torch.zeros(x_fixed.size(0)), 2).to(self.device)\n mask_rafd = self.label2onehot(torch.ones(x_fixed.size(0)), 2).to(self.device)\n g_lr = self.g_lr\n d_lr = self.d_lr\n start_iters = 0\n if self.resume_iters:\n start_iters = self.resume_iters\n self.restore_model(self.resume_iters)\n print('Start training...')\n start_time = time.time()\n for i in range(start_iters, self.num_iters):\n for dataset in ['CelebA', 'RaFD']:\n data_iter = celeba_iter if dataset == 'CelebA' else rafd_iter\n try:\n (x_real, label_org) = next(data_iter)\n except:\n if dataset == 'CelebA':\n celeba_iter = iter(self.celeba_loader)\n (x_real, label_org) = next(celeba_iter)\n elif dataset == 'RaFD':\n rafd_iter = iter(self.rafd_loader)\n (x_real, label_org) = next(rafd_iter)\n rand_idx = torch.randperm(label_org.size(0))\n label_trg = label_org[rand_idx]\n if dataset == 'CelebA':\n c_org = label_org.clone()\n c_trg = label_trg.clone()\n zero = torch.zeros(x_real.size(0), self.c2_dim)\n mask = self.label2onehot(torch.zeros(x_real.size(0)), 2)\n c_org = torch.cat([c_org, zero, mask], dim=1)\n c_trg = torch.cat([c_trg, zero, mask], dim=1)\n elif dataset == 'RaFD':\n c_org = self.label2onehot(label_org, self.c2_dim)\n c_trg = self.label2onehot(label_trg, self.c2_dim)\n zero = torch.zeros(x_real.size(0), self.c_dim)\n mask = self.label2onehot(torch.ones(x_real.size(0)), 2)\n c_org = torch.cat([zero, c_org, mask], dim=1)\n c_trg = torch.cat([zero, c_trg, mask], dim=1)\n x_real = x_real.to(self.device)\n c_org = c_org.to(self.device)\n c_trg = c_trg.to(self.device)\n label_org = label_org.to(self.device)\n label_trg = label_trg.to(self.device)\n (out_src, out_cls) = self.D(x_real)\n out_cls = out_cls[:, :self.c_dim] if dataset == 'CelebA' else out_cls[:, self.c_dim:]\n d_loss_real = -torch.mean(out_src)\n d_loss_cls = self.classification_loss(out_cls, label_org, dataset)\n x_fake = self.G(x_real, c_trg)\n (out_src, _) = self.D(x_fake.detach())\n d_loss_fake = torch.mean(out_src)\n alpha = torch.rand(x_real.size(0), 1, 1, 1).to(self.device)\n x_hat = (alpha * x_real.data + (1 - alpha) * x_fake.data).requires_grad_(True)\n (out_src, _) = self.D(x_hat)\n d_loss_gp = self.gradient_penalty(out_src, x_hat)\n d_loss = d_loss_real + d_loss_fake + self.lambda_cls * d_loss_cls + self.lambda_gp * d_loss_gp\n self.reset_grad()\n d_loss.backward()\n self.d_optimizer.step()\n loss = {}\n loss['D\/loss_real'] = d_loss_real.item()\n loss['D\/loss_fake'] = d_loss_fake.item()\n loss['D\/loss_cls'] = d_loss_cls.item()\n loss['D\/loss_gp'] = d_loss_gp.item()\n if (i + 1) % self.n_critic == 0:\n x_fake = self.G(x_real, c_trg)\n (out_src, out_cls) = self.D(x_fake)\n out_cls = out_cls[:, :self.c_dim] if dataset == 'CelebA' else out_cls[:, self.c_dim:]\n g_loss_fake = -torch.mean(out_src)\n g_loss_cls = self.classification_loss(out_cls, label_trg, dataset)\n x_reconst = self.G(x_fake, c_org)\n g_loss_rec = torch.mean(torch.abs(x_real - x_reconst))\n g_loss = g_loss_fake + self.lambda_rec * g_loss_rec + self.lambda_cls * g_loss_cls\n self.reset_grad()\n g_loss.backward()\n self.g_optimizer.step()\n loss['G\/loss_fake'] = g_loss_fake.item()\n loss['G\/loss_rec'] = g_loss_rec.item()\n loss['G\/loss_cls'] = g_loss_cls.item()\n if (i + 1) % self.log_step == 0:\n et = time.time() - start_time\n et = str(datetime.timedelta(seconds=et))[:-7]\n log = 'Elapsed [{}], Iteration [{}\/{}], Dataset [{}]'.format(et, i + 1, self.num_iters, dataset)\n for (tag, value) in loss.items():\n log += ', {}: {:.4f}'.format(tag, value)\n print(log)\n if self.use_tensorboard:\n for (tag, value) in loss.items():\n self.logger.scalar_summary(tag, value, i + 1)\n if (i + 1) % self.sample_step == 0:\n with torch.no_grad():\n x_fake_list = [x_fixed]\n for c_fixed in c_celeba_list:\n c_trg = torch.cat([c_fixed, zero_rafd, mask_celeba], dim=1)\n x_fake_list.append(self.G(x_fixed, c_trg))\n for c_fixed in c_rafd_list:\n c_trg = torch.cat([zero_celeba, c_fixed, mask_rafd], dim=1)\n x_fake_list.append(self.G(x_fixed, c_trg))\n x_concat = torch.cat(x_fake_list, dim=3)\n sample_path = os.path.join(self.sample_dir, '{}-images.jpg'.format(i + 1))\n save_image(self.denorm(x_concat.data.cpu()), sample_path, nrow=1, padding=0)\n print('Saved real and fake images into {}...'.format(sample_path))\n if (i + 1) % self.model_save_step == 0:\n G_path = os.path.join(self.model_save_dir, '{}-G.ckpt'.format(i + 1))\n D_path = os.path.join(self.model_save_dir, '{}-D.ckpt'.format(i + 1))\n torch.save(self.G.state_dict(), G_path)\n torch.save(self.D.state_dict(), D_path)\n print('Saved model checkpoints into {}...'.format(self.model_save_dir))\n if (i + 1) % self.lr_update_step == 0 and i + 1 > self.num_iters - self.num_iters_decay:\n g_lr -= self.g_lr \/ float(self.num_iters_decay)\n d_lr -= self.d_lr \/ float(self.num_iters_decay)\n self.update_lr(g_lr, d_lr)\n print('Decayed learning rates, g_lr: {}, d_lr: {}.'.format(g_lr, d_lr))","code_tokens":"","url":556686} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"lightning_base.py","full_name":"InferenceDataLightning.setup","func_name":"setup","docstring":"Initializes the datasets stored in the present object, by calling the config object to prepare the torch Dataset objects for train\/val\/test.","docstring_tokens":"","code":"def setup(self, stage: Optional[str]=None) -> None:\n \"\"\"\n Initializes the datasets stored in the present object, by calling the config object to\n prepare the torch Dataset objects for train\/val\/test.\n \"\"\"\n self.train_data = self.config.get_torch_dataset_for_inference(ModelExecutionMode.TRAIN)\n self.val_data = self.config.get_torch_dataset_for_inference(ModelExecutionMode.VAL)\n self.test_data = self.config.get_torch_dataset_for_inference(ModelExecutionMode.TEST)","code_tokens":"","url":612879} +{"project_name":"intel\/neural-compressor","file_name":"benchmark.py","full_name":"run_instance","func_name":"run_instance","docstring":"Run the instance with the configuration.","docstring_tokens":"","code":"def run_instance(model, conf, b_dataloader=None, b_func=None):\n \"\"\"Run the instance with the configuration.\n\n Args:\n model (object): The model to be benchmarked.\n conf (BenchmarkConfig): The configuration for benchmark containing accuracy goal,\n tuning objective and preferred calibration & quantization\n tuning space etc.\n b_dataloader: The dataloader for frameworks.\n b_func: Customized benchmark function. If user passes the dataloader,\n then b_func is not needed.\n \"\"\"\n results = {}\n if b_func is None:\n GLOBAL_STATE.STATE = MODE.BENCHMARK\n framework_specific_info = {'device': conf.device, 'approach': None, 'random_seed': options.random_seed, 'backend': conf.backend if conf.backend is not None else 'default', 'format': 'default'}\n framework = conf.framework.lower()\n if 'tensorflow' in framework:\n framework_specific_info.update({'inputs': conf.inputs, 'outputs': conf.outputs, 'recipes': {}, 'workspace_path': options.workspace})\n if framework == 'keras':\n framework_specific_info.update({'workspace_path': options.workspace})\n if framework == 'mxnet':\n framework_specific_info.update({'b_dataloader': b_dataloader})\n if 'onnx' in framework:\n framework_specific_info.update({'workspace_path': options.workspace, 'graph_optimization': OPTIONS[framework].graph_optimization})\n if framework == 'pytorch_ipex' or framework == 'pytorch' or framework == 'pytorch_fx':\n framework_specific_info.update({'workspace_path': options.workspace, 'q_dataloader': None})\n assert isinstance(model, BaseModel), 'need set neural_compressor Model for quantization....'\n adaptor = FRAMEWORKS[framework](framework_specific_info)\n assert b_dataloader is not None, 'dataloader should not be None'\n from neural_compressor.utils.create_obj_from_config import create_eval_func\n b_func = create_eval_func(conf.framework, b_dataloader, adaptor, None, iteration=conf.iteration)\n objectives = MultiObjective(['performance'], {'relative': 0.1}, is_measure=True)\n val = objectives.evaluate(b_func, model)\n (acc, _) = val\n batch_size = b_dataloader.batch_size\n warmup = conf.warmup\n if len(objectives.objectives[0].result_list()) < warmup:\n if len(objectives.objectives[0].result_list()) > 1 and warmup != 0:\n warmup = 1\n else:\n warmup = 0\n result_list = objectives.objectives[0].result_list()[warmup:]\n latency = np.array(result_list).mean() \/ batch_size\n results['performance'] = (acc, batch_size, result_list)\n logger.info('\\nbenchmark result:')\n for (i, res) in enumerate(result_list):\n logger.debug('Iteration {} result {}:'.format(i, res))\n logger.info('Batch size = {}'.format(batch_size))\n logger.info('Latency: {:.3f} ms'.format(latency * 1000))\n logger.info('Throughput: {:.3f} images\/sec'.format(1.0 \/ latency))\n return results\n else:\n b_func(model.model)","code_tokens":"","url":737213} +{"project_name":"juliancervos\/stdp-nmnist","file_name":"topology.py","full_name":"Conv2dConnection.update","func_name":"update","docstring":"Compute connection's update rule.","docstring_tokens":"","code":"def update(self, **kwargs) -> None:\n \"\"\"\n Compute connection's update rule.\n \"\"\"\n super().update(**kwargs)","code_tokens":"","url":384071} +{"project_name":"georgetown-cset\/ai-relevant-papers","file_name":"cost.py","full_name":"filter_metrics","func_name":"filter_metrics","docstring":"Filter by metric name.","docstring_tokens":"","code":"def filter_metrics(output):\n \"\"\"Filter by metric name.\"\"\"\n for item in output:\n name = item.get('name', {}).get('name', '')\n for (k, v) in COST.items():\n if k in name:\n yield (name, item.get('scalar'))","code_tokens":"","url":95666} +{"project_name":"ZumoLabs\/zpy","file_name":"ml.py","full_name":"init","func_name":"init","docstring":"Initialize a experiment run.","docstring_tokens":"","code":"def init(name: str, sim: str=None, dataset: str=None, config: Dict=None, api_key: str=None) -> None:\n \"\"\"Initialize a experiment run.\n\n Args:\n name (str): identifier for experiment\n sim (str. optional): identifier for simulation associated with experiment\n dataset (str, optional): identifier for dataset associated with experiment\n config (dict, optional): configuration details about experiment\n api_key (str, required): api_key to auth with backend\n Returns:\n experiment object\n \"\"\"\n if api_key is None:\n raise PermissionError('please input zpy api_key')\n global logger\n logger = logging.getLogger(__name__)\n exp = Experiment(name=name, sim=sim, dataset=dataset, config=config, api_key=api_key)\n global experiment\n experiment = exp\n exp._create()","code_tokens":"","url":972068} +{"project_name":"PyRetri\/PyRetri","file_name":"helper.py","full_name":"ExtractHelper.do_extract","func_name":"do_extract","docstring":"Extract features for a whole dataset and save features in json files.","docstring_tokens":"","code":"def do_extract(self, dataloader: DataLoader, save_path: str, save_interval: int=5000) -> None:\n \"\"\"\n Extract features for a whole dataset and save features in json files.\n\n Args:\n dataloader (DataLoader): a DataLoader class for loading images for training.\n save_path (str): the save path for the extracted features.\n save_interval (int, optional): number of features saved in one part file.\n \"\"\"\n datainfo = dataloader.dataset.data_info\n pbar = tqdm(range(len(dataloader)))\n save_fea = list()\n part_cnt = 0\n ensure_dir(save_path)\n start = time.time()\n for (_, batch) in zip(pbar, dataloader):\n feature_dict = self.extract_one_batch(batch)\n for i in range(len(batch['img'])):\n idx = batch['idx'][i]\n save_fea.append(datainfo['info_dicts'][idx])\n single_fea_dict = dict()\n for key in feature_dict:\n single_fea_dict[key] = feature_dict[key][i].tolist()\n save_fea[-1]['feature'] = single_fea_dict\n save_fea[-1]['idx'] = int(idx)\n if len(save_fea) >= save_interval:\n self._save_part_fea(datainfo, save_fea, os.path.join(save_path, 'part_{}.json'.format(part_cnt)))\n part_cnt += 1\n del save_fea\n save_fea = list()\n end = time.time()\n print('time: ', end - start)\n if len(save_fea) >= 1:\n self._save_part_fea(datainfo, save_fea, os.path.join(save_path, 'part_{}.json'.format(part_cnt)))","code_tokens":"","url":297196} +{"project_name":"chribsen\/simple-machine-learning-examples","file_name":"emo.py","full_name":"identity","func_name":"identity","docstring":"Returns directly the argument *obj*.","docstring_tokens":"","code":"def identity(obj):\n \"\"\"Returns directly the argument *obj*.\n \"\"\"\n return obj","code_tokens":"","url":935031} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"app.py","full_name":"is_done","func_name":"is_done","docstring":"True when the CLI is returning, aborting or exiting.","docstring_tokens":"","code":"@Condition\ndef is_done() -> bool:\n \"\"\"\n True when the CLI is returning, aborting or exiting.\n \"\"\"\n return get_app().is_done","code_tokens":"","url":435137} +{"project_name":"clips\/pattern","file_name":"inflect.py","full_name":"indefinite_article","func_name":"indefinite_article","docstring":"Returns the indefinite article for a given word.","docstring_tokens":"","code":"def indefinite_article(word, gender=MALE):\n \"\"\" Returns the indefinite article for a given word.\n \"\"\"\n if MALE in gender and zs(word):\n return PLURAL in gender and 'degli' or 'uno'\n if MALE in gender:\n return PLURAL in gender and 'dei' or 'un'\n if FEMALE in gender and is_vowel(word[:1]):\n return PLURAL in gender and 'delle' or \"un'\"\n if FEMALE in gender:\n return PLURAL in gender and 'delle' or 'una'\n return 'un'","code_tokens":"","url":764954} +{"project_name":"ShengdingHu\/GraphPolicyNetworkActiveLearning","file_name":"create_data.py","full_name":"get_keras_data","func_name":"get_keras_data","docstring":"Get datasets using keras API and return as a Dataset object.","docstring_tokens":"","code":"def get_keras_data(dataname):\n \"\"\"Get datasets using keras API and return as a Dataset object.\"\"\"\n if dataname == 'cifar10_keras':\n (train, test) = cifar10.load_data()\n elif dataname == 'cifar100_coarse_keras':\n (train, test) = cifar100.load_data('coarse')\n elif dataname == 'cifar100_keras':\n (train, test) = cifar100.load_data()\n elif dataname == 'mnist_keras':\n (train, test) = mnist.load_data()\n else:\n raise NotImplementedError('dataset not supported')\n X = np.concatenate((train[0], test[0]))\n y = np.concatenate((train[1], test[1]))\n if dataname == 'mnist_keras':\n num_rows = X.shape[1]\n num_cols = X.shape[2]\n X = X.reshape(X.shape[0], 1, num_rows, num_cols)\n if K.image_data_format() == 'channels_last':\n X = X.transpose(0, 2, 3, 1)\n y = y.flatten()\n data = Dataset(X, y)\n return data","code_tokens":"","url":580739} +{"project_name":"alibaba-mmai-research\/HiCo","file_name":"tal_tools.py","full_name":"save_epic_props","func_name":"save_epic_props","docstring":"Save a video proposals for epic-kitchen.","docstring_tokens":"","code":"def save_epic_props(cfg, bucket, video_name, propos, heads, dir_prefix, epoch, to_oss=False):\n \"\"\"\n Save a video proposals for epic-kitchen.\n Args:\n cfg (Config): the global config object.\n bucket (Oss bucket): ignore it if you donot use oss\n video_name (str): video name\n propos (tensor): proposals for this video\n heads (list): proposals table head\n dir_prefix (str): path prefix\n epoch (int): epoch number of these proposals\n \"\"\"\n if bucket is not None and cfg.OSS.CHECKPOINT_OUTPUT_PATH[:3] == 'oss':\n dir_name = os.path.join(cfg.LOCALIZATION.TEST_OUTPUT_DIR, dir_prefix)\n else:\n dir_name = os.path.join(cfg.OUTPUT_DIR, _get_oss_path_prefix(dir_prefix, epoch, cfg.TEST.TEST_SET))\n to_oss = False\n if os.path.exists(dir_name) is False:\n try:\n os.makedirs(dir_name)\n except:\n pass\n local_file = os.path.join(dir_name, video_name + '.pkl')\n logger.info('saving: {}'.format(local_file))\n torch.save([propos, heads], local_file)\n logger.info('{} saved!!'.format(local_file))\n if to_oss:\n oss_dir_prefix = _get_oss_path_prefix(dir_prefix, epoch, cfg.TEST.TEST_SET)\n oss_file = os.path.join(cfg.OSS.CHECKPOINT_OUTPUT_PATH, oss_dir_prefix + '\/')\n bu.put_to_bucket(bucket, oss_file, local_file, bucket.bucket_name, retries=1, verbose=False)\n return None","code_tokens":"","url":206292} +{"project_name":"matsu0228\/nlp-jp","file_name":"topology_description.py","full_name":"TopologyDescription.reset","func_name":"reset","docstring":"A copy of this description, with all servers marked Unknown.","docstring_tokens":"","code":"def reset(self):\n \"\"\"A copy of this description, with all servers marked Unknown.\"\"\"\n if self._topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary:\n topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary\n else:\n topology_type = self._topology_type\n sds = dict(((address, ServerDescription(address)) for address in self._server_descriptions))\n return TopologyDescription(topology_type, sds, self._replica_set_name, self._max_set_version, self._max_election_id, self._topology_settings)","code_tokens":"","url":805086} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"socketserver.py","full_name":"ForkingMixIn.collect_children","func_name":"collect_children","docstring":"Internal routine to wait for children that have exited.","docstring_tokens":"","code":"def collect_children(self):\n \"\"\"Internal routine to wait for children that have exited.\"\"\"\n if self.active_children is None:\n return\n while len(self.active_children) >= self.max_children:\n try:\n (pid, status) = os.waitpid(0, 0)\n except os.error:\n pid = None\n if pid not in self.active_children:\n continue\n self.active_children.remove(pid)\n for child in self.active_children:\n try:\n (pid, status) = os.waitpid(child, os.WNOHANG)\n except os.error:\n pid = None\n if not pid:\n continue\n try:\n self.active_children.remove(pid)\n except ValueError as e:\n raise ValueError('%s. x=%d and list=%r' % (e.message, pid, self.active_children))","code_tokens":"","url":395563} +{"project_name":"ludwig-ai\/ludwig","file_name":"test_hyperopt_ray_horovod.py","full_name":"mock_storage_client","func_name":"mock_storage_client","docstring":"Mocks storage client that treats a local dir as durable storage.","docstring_tokens":"","code":"def mock_storage_client(path):\n \"\"\"Mocks storage client that treats a local dir as durable storage.\"\"\"\n os.makedirs(path, exist_ok=True)\n syncer = get_node_to_storage_syncer(SyncConfig(upload_dir=path))\n return syncer","code_tokens":"","url":617265} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"gmm_ops.py","full_name":"GmmAlgorithm.training_ops","func_name":"training_ops","docstring":"Returns the training operation.","docstring_tokens":"","code":"def training_ops(self):\n \"\"\"Returns the training operation.\"\"\"\n return control_flow_ops.group(*self._train_ops)","code_tokens":"","url":603007} +{"project_name":"jbwang1997\/CrossKD","file_name":"loading.py","full_name":"LoadMultiChannelImageFromFiles.transform","func_name":"transform","docstring":"Transform functions to load multiple images and get images meta information.","docstring_tokens":"","code":"def transform(self, results: dict) -> dict:\n \"\"\"Transform functions to load multiple images and get images meta\n information.\n\n Args:\n results (dict): Result dict from :obj:`mmdet.CustomDataset`.\n\n Returns:\n dict: The dict contains loaded images and meta information.\n \"\"\"\n assert isinstance(results['img_path'], list)\n img = []\n for name in results['img_path']:\n img_bytes = self.file_client.get(name)\n img.append(mmcv.imfrombytes(img_bytes, flag=self.color_type, backend=self.imdecode_backend))\n img = np.stack(img, axis=-1)\n if self.to_float32:\n img = img.astype(np.float32)\n results['img'] = img\n results['img_shape'] = img.shape[:2]\n results['ori_shape'] = img.shape[:2]\n return results","code_tokens":"","url":490768} +{"project_name":"LeeDongYeun\/keras-m2det","file_name":"keras_version.py","full_name":"keras_version_ok","func_name":"keras_version_ok","docstring":"Check if the current Keras version is higher than the minimum version.","docstring_tokens":"","code":"def keras_version_ok():\n \"\"\" Check if the current Keras version is higher than the minimum version.\n \"\"\"\n return keras_version() >= minimum_keras_version","code_tokens":"","url":595553} +{"project_name":"GMvandeVen\/brain-inspired-replay","file_name":"continual_learner.py","full_name":"ContinualLearner.reset_XdGmask","func_name":"reset_XdGmask","docstring":"Remove task-specific mask, by setting all \"excit-buffers\" to 1.","docstring_tokens":"","code":"def reset_XdGmask(self):\n \"\"\"Remove task-specific mask, by setting all \"excit-buffers\" to 1.\"\"\"\n torchType = next(self.parameters()).detach()\n for excit_buffer in self.excit_buffer_list:\n gating_mask = np.repeat(1.0, len(excit_buffer))\n excit_buffer.set_(torchType.new(gating_mask))","code_tokens":"","url":466050} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"__init__.py","full_name":"PythonHandler.close","func_name":"close","docstring":"Closes the stream to which we are writing.","docstring_tokens":"","code":"def close(self):\n \"\"\"Closes the stream to which we are writing.\"\"\"\n self.acquire()\n try:\n self.flush()\n try:\n if self.stream not in (sys.stderr, sys.stdout) and (not hasattr(self.stream, 'isatty') or not self.stream.isatty()):\n self.stream.close()\n except ValueError:\n pass\n super(PythonHandler, self).close()\n finally:\n self.release()","code_tokens":"","url":309707} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"package_index.py","full_name":"ContentChecker.feed","func_name":"feed","docstring":"Feed a block of data to the hash.","docstring_tokens":"","code":"def feed(self, block):\n \"\"\"\n Feed a block of data to the hash.\n \"\"\"\n return","code_tokens":"","url":189266} +{"project_name":"zgojcic\/Rigid3DSceneFlow","file_name":"config.py","full_name":"get_optimizer","func_name":"get_optimizer","docstring":"Returns an optimizer instance.","docstring_tokens":"","code":"def get_optimizer(cfg, model):\n \"\"\" \n Returns an optimizer instance.\n Args:\n cfg (dict): config dictionary\n model (nn.Module): the model used for training\n\n Returns:\n optimizer (optimizer instance): optimizer used to train the network\n \"\"\"\n method = cfg['optimizer']['alg']\n if method == 'SGD':\n optimizer = getattr(optim, method)(model.parameters(), lr=cfg['optimizer']['learning_rate'], momentum=cfg['optimizer']['momentum'], weight_decay=cfg['optimizer']['weight_decay'])\n elif method == 'Adam':\n optimizer = getattr(optim, method)(model.parameters(), lr=cfg['optimizer']['learning_rate'], weight_decay=cfg['optimizer']['weight_decay'])\n else:\n print('{} optimizer is not implemented, must be one of the [SGD, Adam]'.format(method))\n return optimizer","code_tokens":"","url":348982} +{"project_name":"victordibia\/data2vis","file_name":"decoder.py","full_name":"Decoder.batch_size","func_name":"batch_size","docstring":"The batch size of the inputs returned by `sample`.","docstring_tokens":"","code":"@property\ndef batch_size(self):\n \"\"\"The batch size of the inputs returned by `sample`.\"\"\"\n raise NotImplementedError","code_tokens":"","url":126818} +{"project_name":"intel\/neural-compressor","file_name":"configuration.py","full_name":"Configuration.determine_url_prefix","func_name":"determine_url_prefix","docstring":"Determine url prefix based on parameters given.","docstring_tokens":"","code":"@staticmethod\ndef determine_url_prefix(args: dict) -> str:\n \"\"\"Determine url prefix based on parameters given.\"\"\"\n url_prefix = args.get('url_prefix', '')\n if isinstance(url_prefix, str) and (not url_prefix.startswith('\/')):\n url_prefix = f'\/{url_prefix}'\n return url_prefix","code_tokens":"","url":721746} +{"project_name":"ludwig-ai\/ludwig","file_name":"deepspeed.py","full_name":"DeepSpeedStrategy.allow_clip_gradients","func_name":"allow_clip_gradients","docstring":"DeepSpeed handles gradient clipping internally.","docstring_tokens":"","code":"def allow_clip_gradients(self) -> bool:\n \"\"\"DeepSpeed handles gradient clipping internally.\"\"\"\n return False","code_tokens":"","url":616731} +{"project_name":"deepmind\/dm_control","file_name":"primitive.py","full_name":"Primitive.geom","func_name":"geom","docstring":"The geom belonging to this prop.","docstring_tokens":"","code":"@property\ndef geom(self):\n \"\"\"The geom belonging to this prop.\"\"\"\n return self._geom","code_tokens":"","url":165025} +{"project_name":"intra2net\/guibot","file_name":"test_imagelogger.py","full_name":"ImageLoggerTest.test_image_dumping","func_name":"test_image_dumping","docstring":"Check that images are dumped correctly.","docstring_tokens":"","code":"def test_image_dumping(self):\n \"\"\"Check that images are dumped correctly.\"\"\"\n ImageLogger.step = 18\n with patch('os.path.exists', side_effect=lambda _: False):\n self.imglog.dump_matched_images()\n self.mock_mkdir.assert_called_once_with(ImageLogger.logging_destination)\n self.imglog.needle.save.assert_called_once_with(os.path.join('imglog', 'imglog018-1needle-test_needle'))\n self.imglog.haystack.save.assert_called_once_with(os.path.join('imglog', 'imglog018-2haystack-test_haystack'))","code_tokens":"","url":572674} +{"project_name":"TJU-DRL-LAB\/AI-Optimizer","file_name":"drnn.py","full_name":"DRNN.dist_from_state","func_name":"dist_from_state","docstring":"Extract the latent distribution from a prior or posterior state.","docstring_tokens":"","code":"def dist_from_state(self, state, mask=None):\n \"\"\"Extract the latent distribution from a prior or posterior state.\"\"\"\n if mask is not None:\n stddev = tools.mask(state['stddev'], mask, value=1)\n else:\n stddev = state['stddev']\n dist = tfd.MultivariateNormalDiag(state['mean'], stddev)\n return dist","code_tokens":"","url":70323} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"base85.py","full_name":"to_base85","func_name":"to_base85","docstring":"Encodes the given integer using base 85.","docstring_tokens":"","code":"def to_base85(x, islong=False):\n \"\"\"Encodes the given integer using base 85.\"\"\"\n size = 10 if islong else 5\n rems = ''\n for i in xrange(size):\n rems = b85chars[x % 85] + rems\n x \/\/= 85\n return rems","code_tokens":"","url":133634} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"turtle.py","full_name":"ScrolledCanvas.adjustScrolls","func_name":"adjustScrolls","docstring":"Adjust scrollbars according to window- and canvas-size.","docstring_tokens":"","code":"def adjustScrolls(self):\n \"\"\" Adjust scrollbars according to window- and canvas-size.\n \"\"\"\n cwidth = self._canvas.winfo_width()\n cheight = self._canvas.winfo_height()\n self._canvas.xview_moveto(0.5 * (self.canvwidth - cwidth) \/ self.canvwidth)\n self._canvas.yview_moveto(0.5 * (self.canvheight - cheight) \/ self.canvheight)\n if cwidth < self.canvwidth or cheight < self.canvheight:\n self.hscroll.grid(padx=1, in_=self, pady=1, row=1, column=0, rowspan=1, columnspan=1, sticky='news')\n self.vscroll.grid(padx=1, in_=self, pady=1, row=0, column=1, rowspan=1, columnspan=1, sticky='news')\n else:\n self.hscroll.grid_forget()\n self.vscroll.grid_forget()","code_tokens":"","url":281691} +{"project_name":"paulorauber\/rl","file_name":"ray.py","full_name":"print_remote_collector_info","func_name":"print_remote_collector_info","docstring":"Prints some information about the remote collector.","docstring_tokens":"","code":"def print_remote_collector_info(self):\n \"\"\"Prints some information about the remote collector.\"\"\"\n s = f'Created remote collector with in machine {get_node_ip_address()} using gpus {ray.get_gpu_ids()}'\n print(s)","code_tokens":"","url":858630} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"routing.py","full_name":"RuleFactory.get_rules","func_name":"get_rules","docstring":"Subclasses of `RuleFactory` have to override this method and return an iterable of rules.","docstring_tokens":"","code":"def get_rules(self, map):\n \"\"\"Subclasses of `RuleFactory` have to override this method and return\n an iterable of rules.\"\"\"\n raise NotImplementedError()","code_tokens":"","url":84887} +{"project_name":"google\/deepvariant","file_name":"vcf.py","full_name":"NativeVcfReader.iterate","func_name":"iterate","docstring":"Returns an iterable of Variant protos in the file.","docstring_tokens":"","code":"def iterate(self):\n \"\"\"Returns an iterable of Variant protos in the file.\"\"\"\n return self._reader.iterate()","code_tokens":"","url":540604} +{"project_name":"xuwei95\/transfer-learning","file_name":"pytorch_image_anomaly_detection_model.py","full_name":"PyTorchImageAnomalyDetectionModel.predict","func_name":"predict","docstring":"Perform inference and predict the class of the input_samples.","docstring_tokens":"","code":"def predict(self, input_samples, pca_mats, return_type='scores', threshold=None):\n \"\"\"\n Perform inference and predict the class of the input_samples.\n\n Args:\n input_samples (tensor): Input tensor with one or more samples to perform inference on\n pca_mats (PCA components): Components responsible for the top (threshold)% of the\n features' variability\n return_type (str): Using 'scores' will return the raw output of the PCA model and using 'class' will return\n the highest scoring class based on a user-provided threshold (default: 'scores')\n threshold (numerical): Optional; When using return_type \"class\" this is the threshold for determining\n whether a score counts as an anomaly or not\n\n Returns:\n List of predictions ('good' or 'bad') or raw score vector\n \"\"\"\n if return_type == 'class' and (not isinstance(threshold, Number)):\n raise ValueError('For class prediction, please give a numeric threshold.')\n model = get_feature_extraction_model(self._model, self._layer_name)\n with torch.no_grad():\n scores = np.empty(len(input_samples))\n count = 0\n input_samples = input_samples.to(memory_format=torch.channels_last)\n num_im = input_samples.shape[0]\n outputs = extract_features(model, input_samples, self._layer_name, pooling=[self._pooling, self._kernel_size])\n feature_shapes = outputs.shape\n oi = outputs\n oi_or = oi\n oi_j = pca_mats.transform(oi)\n oi_reconstructed = pca_mats.inverse_transform(oi_j)\n fre = torch.square(oi_or - oi_reconstructed).reshape(feature_shapes)\n fre_score = torch.sum(fre, dim=1)\n scores[count:count + num_im] = -fre_score\n count += num_im\n if return_type == 'scores':\n return scores\n else:\n return ['good' if s >= threshold else 'bad' for s in scores]","code_tokens":"","url":928244} +{"project_name":"Eric3911\/OpenAGI","file_name":"transformer_generators.py","full_name":"GreedySequenceGenerator.unfreeze","func_name":"unfreeze","docstring":"Unfreeze weights of embedding, decoder, and classification layers.","docstring_tokens":"","code":"def unfreeze(self) -> None:\n \"\"\"Unfreeze weights of embedding, decoder, and classification layers.\n \"\"\"\n for param in self.embedding.parameters():\n param.requires_grad = True\n self.embedding.train()\n for param in self.decoder.parameters():\n param.requires_grad = True\n self.decoder.train()\n for param in self.log_softmax.parameters():\n param.require_grad = True\n self.log_softmax.train()","code_tokens":"","url":272646} +{"project_name":"RasaHQ\/rasa","file_name":"test.py","full_name":"write_response_successes","func_name":"write_response_successes","docstring":"Write successful response selection predictions to a file.","docstring_tokens":"","code":"def write_response_successes(response_results: List[ResponseSelectionEvaluationResult], successes_filename: Text) -> None:\n \"\"\"Write successful response selection predictions to a file.\n\n Args:\n response_results: response selection evaluation result\n successes_filename: filename of file to save successful predictions to\n \"\"\"\n successes = [{'text': r.message, 'intent_response_key_target': r.intent_response_key_target, 'intent_response_key_prediction': {'name': r.intent_response_key_prediction, 'confidence': r.confidence}} for r in response_results if r.intent_response_key_prediction == r.intent_response_key_target]\n if successes:\n rasa.shared.utils.io.dump_obj_as_json_to_file(successes_filename, successes)\n logger.info(f'Successful response predictions saved to {successes_filename}.')\n structlogger.debug('test.write.response', successes=copy.deepcopy(successes))\n else:\n logger.info('No successful response predictions found.')","code_tokens":"","url":837104} +{"project_name":"rishab-sharma\/object_detection","file_name":"model.py","full_name":"ObjectDetector.get_feed_dict_for_all","func_name":"get_feed_dict_for_all","docstring":"Get the feed dictionary for both RPN and RCN.","docstring_tokens":"","code":"def get_feed_dict_for_all(self, batch, is_train, feats=None):\n \"\"\" Get the feed dictionary for both RPN and RCN. \"\"\"\n if is_train:\n (_, anchor_files) = batch\n (gt_anchor_labels, gt_anchor_regs, anchor_masks, anchor_weights, anchor_reg_masks) = self.process_anchor_data(anchor_files)\n (rois, gt_roi_classes, gt_roi_regs, roi_masks, roi_weights, roi_reg_masks) = self.process_roi_data(anchor_files)\n rois = rois.reshape((-1, 4))\n rois = convert_bbox(rois, self.img_shape[:2], self.conv_feat_shape[:2])\n rois = rois.reshape((self.batch_size, self.num_roi, 4))\n roi_warped_feats = self.get_roi_feats(feats, rois)\n return {self.feats: feats, self.gt_anchor_labels: gt_anchor_labels, self.gt_anchor_regs: gt_anchor_regs, self.anchor_masks: anchor_masks, self.anchor_weights: anchor_weights, self.anchor_reg_masks: anchor_reg_masks, self.roi_warped_feats: roi_warped_feats, self.gt_roi_classes: gt_roi_classes, self.gt_roi_regs: gt_roi_regs, self.roi_masks: roi_masks, self.roi_weights: roi_weights, self.roi_reg_masks: roi_reg_masks, self.is_train: is_train}\n else:\n img_files = batch\n imgs = self.img_loader.load_imgs(img_files)\n return {self.imgs: imgs, self.is_train: is_train}","code_tokens":"","url":745101} +{"project_name":"deepmind\/dm_control","file_name":"lqr.py","full_name":"LQRLevel.get_evaluation","func_name":"get_evaluation","docstring":"Returns a sparse evaluation reward that is not used for learning.","docstring_tokens":"","code":"def get_evaluation(self, physics):\n \"\"\"Returns a sparse evaluation reward that is not used for learning.\"\"\"\n return float(physics.state_norm() <= 0.01)","code_tokens":"","url":165509} +{"project_name":"heyingge-1560733\/cse415","file_name":"heyingge_Farmer_Fox_etc.py","full_name":"State.move","func_name":"move","docstring":"Assuming it's legal to make the move, this computes the new state resulting from moving the boat carrying farmer (and one passenger).","docstring_tokens":"","code":"def move(self, passenger):\n \"\"\"Assuming it's legal to make the move, this computes\n the new state resulting from moving the boat carrying\n farmer (and one passenger).\"\"\"\n news = self.copy()\n news.d['farmer'] = not self.d['farmer']\n if passenger == 'fox':\n news.d['fox'] = not self.d['fox']\n elif passenger == 'chicken':\n news.d['chicken'] = not self.d['chicken']\n elif passenger == 'grain':\n news.d['grain'] = not self.d['grain']\n return news","code_tokens":"","url":193066} +{"project_name":"google-research\/scenic","file_name":"bert_glue_dataset.py","full_name":"get_dataset_fn","func_name":"get_dataset_fn","docstring":"Gets a closure to create a dataset.","docstring_tokens":"","code":"def get_dataset_fn(input_file_pattern, max_seq_length, batch_size, is_training, repeats=None, label_type=tf.int64, include_sample_weights=False, num_samples=None):\n \"\"\"Gets a closure to create a dataset.\"\"\"\n\n def _dataset_fn(ctx=None):\n \"\"\"Returns tf.data.Dataset for distributed BERT pretraining.\"\"\"\n dataset = create_classifier_dataset(tf.io.gfile.glob(input_file_pattern), max_seq_length, batch_size, is_training=is_training, repeats=repeats, input_pipeline_context=ctx, label_type=label_type, include_sample_weights=include_sample_weights, num_samples=num_samples)\n return dataset\n return _dataset_fn","code_tokens":"","url":846560} +{"project_name":"alexandra-chron\/ntua-slp-wassa-iest2018","file_name":"spellcorrect.py","full_name":"SpellCorrector.edits2","func_name":"edits2","docstring":"All edits that are two edits away from `word`.","docstring_tokens":"","code":"def edits2(self, word):\n \"\"\"\n All edits that are two edits away from `word`.\n \"\"\"\n return (e2 for e1 in self.edit_step(word) for e2 in self.edit_step(e1))","code_tokens":"","url":729965} +{"project_name":"yinyunie\/ScenePriors","file_name":"masking.py","full_name":"BaseMask.float_matrix","func_name":"float_matrix","docstring":"Return the bool matrix as a float to be used as a multiplicative mask for non softmax attentions.","docstring_tokens":"","code":"@property\ndef float_matrix(self):\n \"\"\"Return the bool matrix as a float to be used as a multiplicative\n mask for non softmax attentions.\"\"\"\n if not hasattr(self, '_float_matrix'):\n with torch.no_grad():\n self._float_matrix = self.bool_matrix.float()\n return self._float_matrix","code_tokens":"","url":329503} +{"project_name":"dillondaudert\/pssp_lstm","file_name":"entropy_estimators.py","full_name":"centropy","func_name":"centropy","docstring":"The classic K-L k-nearest neighbor continuous entropy estimator for the entropy of X conditioned on Y.","docstring_tokens":"","code":"def centropy(x, y, k=3, base=2):\n \"\"\" The classic K-L k-nearest neighbor continuous entropy estimator for the\n entropy of X conditioned on Y.\n \"\"\"\n hxy = entropy([xi + yi for (xi, yi) in zip(x, y)], k, base)\n hy = entropy(y, k, base)\n return hxy - hy","code_tokens":"","url":295785} +{"project_name":"FitSNAP\/FitSNAP","file_name":"libmod_optimize.py","full_name":"fit_and_cost","func_name":"fit_and_cost","docstring":"Perform FitSNAP fit and evaluate errors (cost or score).","docstring_tokens":"","code":"def fit_and_cost(fs, fitobjects, costweights):\n \"\"\"\n Perform FitSNAP fit and evaluate errors (cost or score).\n\n Args:\n fs: instance of FitSNAP class\n costweights: tuple with user-specified weights on energies, forces, stresses, default is (1.,1.,1.) (no special weighting)\n\n Returns:\n cost: a value representing the fit's performance (currently uses RMSE on training only)\n\n Objective function note: fit_and_cost will likely need to be modified to print current fit if other objective functions are to be added. See commented-out examples below.\n \"\"\"\n (etot_weight, ftot_weight, stot_weight) = tuple(costweights)\n (a, b, w, fs_dict) = tuple(fitobjects)\n fs.solver.fit = None\n fs.solver.perform_fit(a, b, w, fs_dict)\n fittst = fs.solver.fit\n fs.solver.error_analysis(a, b, w, fs_dict)\n errstst = fs.solver.errors\n rmse_tst = errstst.iloc[:, 2].to_numpy()\n (rmse_eattst, rmse_fattst, rmse_sattst) = rmse_tst[0:3]\n CO = CostObject()\n CO.add_contribution(rmse_eattst, etot_weight)\n CO.add_contribution(rmse_fattst, ftot_weight)\n CO.add_contribution(rmse_sattst, stot_weight)\n cost = CO.evaluate_cost()\n del CO\n return cost","code_tokens":"","url":584578} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"logging.py","full_name":"LoggingAgent.integrateObservation","func_name":"integrateObservation","docstring":"Step 1: store the observation received in a temporary variable until action is called and reward is given.","docstring_tokens":"","code":"def integrateObservation(self, obs):\n \"\"\"Step 1: store the observation received in a temporary variable until action is called and\n reward is given. \"\"\"\n self.lastobs = obs\n self.lastaction = None\n self.lastreward = None","code_tokens":"","url":722519} +{"project_name":"Erfanafshar\/Principles-and-Applications-of---graph-coloring","file_name":"textpath.py","full_name":"TextPath.vertices","func_name":"vertices","docstring":"Return the cached path after updating it if necessary.","docstring_tokens":"","code":"@property\ndef vertices(self):\n \"\"\"\n Return the cached path after updating it if necessary.\n \"\"\"\n self._revalidate_path()\n return self._cached_vertices","code_tokens":"","url":307033} +{"project_name":"sktime\/sktime","file_name":"test_PlateauFinder.py","full_name":"test_PlateauFinder","func_name":"test_PlateauFinder","docstring":"Test PlateauFinder on test data against expected output plateau features.","docstring_tokens":"","code":"@pytest.mark.parametrize('value', [np.nan, -10, 10, -0.5, 0.5])\ndef test_PlateauFinder(value):\n \"\"\"Test PlateauFinder on test data against expected output plateau features.\"\"\"\n value = np.nan\n X = pd.DataFrame(pd.Series([pd.Series([value, 1, 2, 3, value, 2, 2, 3]), pd.Series([value, value, 3, 3, value, 2, 2, 3]), pd.Series([0, value, value, value, value, value, 2, value]), pd.Series([0, value, value, 3, 4, 5, value, value]), pd.Series([2, value, value, value, 2, value, 3, 1]), pd.Series([0, value, value, 3, value, value, 2, 0])]))\n n_samples = X.shape[0]\n t = PlateauFinder(value=value, min_length=2)\n Xt = t.fit_transform(X)\n actual_starts = Xt.iloc[:, 0]\n actual_lengths = Xt.iloc[:, 1]\n expected_starts = [np.array([]), np.array([0]), np.array([1]), np.array([1, 6]), np.array([1]), np.array([1, 4])]\n expected_lengths = [np.array([]), np.array([2]), np.array([5]), np.array([2, 2]), np.array([3]), np.array([2, 2])]\n for i in range(n_samples):\n np.testing.assert_array_equal(actual_starts[i], expected_starts[i])\n np.testing.assert_array_equal(actual_lengths[i], expected_lengths[i])","code_tokens":"","url":877722} +{"project_name":"rlpy\/rlpy","file_name":"MDPSolver.py","full_name":"MDPSolver.performanceRun","func_name":"performanceRun","docstring":"Set Exploration to zero and sample one episode from the domain.","docstring_tokens":"","code":"def performanceRun(self):\n \"\"\"Set Exploration to zero and sample one episode from the domain.\"\"\"\n eps_length = 0\n eps_return = 0\n eps_term = False\n eps_discounted_return = 0\n (s, eps_term, p_actions) = self.domain.s0()\n while not eps_term and eps_length < self.domain.episodeCap:\n a = self.representation.bestAction(s, eps_term, p_actions)\n (r, ns, eps_term, p_actions) = self.domain.step(a)\n s = ns\n eps_discounted_return += self.domain.discount_factor ** eps_length * r\n eps_return += r\n eps_length += 1\n return (eps_return, eps_length, eps_term, eps_discounted_return)","code_tokens":"","url":333851} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"first.py","full_name":"Summarize","func_name":"Summarize","docstring":"Print various summary statistics.","docstring_tokens":"","code":"def Summarize(live, firsts, others):\n \"\"\"Print various summary statistics.\"\"\"\n mean = live.prglngth.mean()\n var = live.prglngth.var()\n std = live.prglngth.std()\n print('Live mean', mean)\n print('Live variance', var)\n print('Live std', std)\n mean1 = firsts.prglngth.mean()\n mean2 = others.prglngth.mean()\n var1 = firsts.prglngth.var()\n var2 = others.prglngth.var()\n print('Mean')\n print('First babies', mean1)\n print('Others', mean2)\n print('Variance')\n print('First babies', var1)\n print('Others', var2)\n print('Difference in weeks', mean1 - mean2)\n print('Difference in hours', (mean1 - mean2) * 7 * 24)\n print('Difference relative to 39 weeks', (mean1 - mean2) \/ 39 * 100)\n d = thinkstats2.CohenEffectSize(firsts.prglngth, others.prglngth)\n print('Cohen d', d)","code_tokens":"","url":12595} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"dataset_item.py","full_name":"DatasetItemEntity.append_annotations","func_name":"append_annotations","docstring":"Adds a list of shapes to the annotation.","docstring_tokens":"","code":"def append_annotations(self, annotations: Sequence[Annotation]):\n \"\"\"Adds a list of shapes to the annotation.\"\"\"\n roi_as_box = ShapeFactory.shape_as_rectangle(self.roi.shape)\n validated_annotations = [Annotation(shape=annotation.shape.normalize_wrt_roi_shape(roi_as_box), labels=annotation.get_labels()) for annotation in annotations if ShapeFactory().shape_produces_valid_crop(shape=annotation.shape, media_width=self.media.width, media_height=self.media.height)]\n n_invalid_shapes = len(annotations) - len(validated_annotations)\n if n_invalid_shapes > 0:\n logger.info('%d shapes will not be added to the dataset item as they would produce invalid crops (this is expected for some tasks, such as segmentation).', n_invalid_shapes)\n self.annotation_scene.append_annotations(validated_annotations)","code_tokens":"","url":918506} +{"project_name":"rudranil723\/mini-main","file_name":"base.py","full_name":"BaseDatabaseWrapper.timezone_name","func_name":"timezone_name","docstring":"Name of the time zone of the database connection.","docstring_tokens":"","code":"@cached_property\ndef timezone_name(self):\n \"\"\"\n Name of the time zone of the database connection.\n \"\"\"\n if not settings.USE_TZ:\n return settings.TIME_ZONE\n elif self.settings_dict['TIME_ZONE'] is None:\n return 'UTC'\n else:\n return self.settings_dict['TIME_ZONE']","code_tokens":"","url":315706} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_gpr.py","full_name":"test_gpr_lml_error","func_name":"test_gpr_lml_error","docstring":"Check that we raise the proper error in the LML method.","docstring_tokens":"","code":"def test_gpr_lml_error():\n \"\"\"Check that we raise the proper error in the LML method.\"\"\"\n gpr = GaussianProcessRegressor(kernel=RBF()).fit(X, y)\n err_msg = 'Gradient can only be evaluated for theta!=None'\n with pytest.raises(ValueError, match=err_msg):\n gpr.log_marginal_likelihood(eval_gradient=True)","code_tokens":"","url":364004} +{"project_name":"vturrisi\/solo-learn","file_name":"auto_resumer.py","full_name":"AutoResumer.add_and_assert_specific_cfg","func_name":"add_and_assert_specific_cfg","docstring":"Adds specific default values\/checks for config.","docstring_tokens":"","code":"@staticmethod\ndef add_and_assert_specific_cfg(cfg: DictConfig) -> DictConfig:\n \"\"\"Adds specific default values\/checks for config.\n\n Args:\n cfg (omegaconf.DictConfig): DictConfig object.\n\n Returns:\n omegaconf.DictConfig: same as the argument, used to avoid errors.\n \"\"\"\n cfg.auto_resume = omegaconf_select(cfg, 'auto_resume', default={})\n cfg.auto_resume.enabled = omegaconf_select(cfg, 'auto_resume.enabled', default=False)\n cfg.auto_resume.max_hours = omegaconf_select(cfg, 'auto_resume.max_hours', default=36)\n return cfg","code_tokens":"","url":393710} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"label_schema.py","full_name":"LabelTree.add_child","func_name":"add_child","docstring":"Add a `child` Label to `parent`.","docstring_tokens":"","code":"def add_child(self, parent: LabelEntity, child: LabelEntity):\n \"\"\"Add a `child` Label to `parent`.\"\"\"\n self.add_edge(child, parent)\n self.clear_topological_cache()","code_tokens":"","url":918556} +{"project_name":"AboudyKreidieh\/h-baselines","file_name":"utils.py","full_name":"is_ppo_policy","func_name":"is_ppo_policy","docstring":"Check whether a policy is for designed to support PPO.","docstring_tokens":"","code":"def is_ppo_policy(policy):\n \"\"\"Check whether a policy is for designed to support PPO.\"\"\"\n return policy in [PPOFeedForwardPolicy, PPOMultiFeedForwardPolicy]","code_tokens":"","url":573804} +{"project_name":"YangRui2015\/2048_env","file_name":"gym_2048.py","full_name":"Game2048Env.get_board","func_name":"get_board","docstring":"Retrieve the whole board, useful for testing.","docstring_tokens":"","code":"def get_board(self):\n \"\"\"Retrieve the whole board, useful for testing.\"\"\"\n return self.Matrix","code_tokens":"","url":375624} +{"project_name":"google\/deepvariant","file_name":"utils.py","full_name":"read_end","func_name":"read_end","docstring":"Returns the read start + alignment length for Read read.","docstring_tokens":"","code":"def read_end(read):\n \"\"\"Returns the read start + alignment length for Read read.\"\"\"\n return read_range(read).end","code_tokens":"","url":540687} +{"project_name":"QData\/deepWordBug","file_name":"types.py","full_name":"VolumeSpec.parse","func_name":"parse","docstring":"Parse a volume_config path and split it into external:internal[:mode] parts to be returned as a valid VolumeSpec.","docstring_tokens":"","code":"@classmethod\ndef parse(cls, volume_config, normalize=False, win_host=False):\n \"\"\"Parse a volume_config path and split it into external:internal[:mode]\n parts to be returned as a valid VolumeSpec.\n \"\"\"\n if IS_WINDOWS_PLATFORM or win_host:\n return cls._parse_win32(volume_config, normalize)\n else:\n return cls._parse_unix(volume_config)","code_tokens":"","url":541792} +{"project_name":"brain-research\/realistic-ssl-evaluation","file_name":"evaluate_checkpoints.py","full_name":"make_images_and_labels_tensors","func_name":"make_images_and_labels_tensors","docstring":"Make tensors for loading images and labels from dataset.","docstring_tokens":"","code":"def make_images_and_labels_tensors():\n \"\"\"Make tensors for loading images and labels from dataset.\"\"\"\n with tf.name_scope('input'):\n dataset = dataset_utils.get_dataset(FLAGS.primary_dataset_name, FLAGS.split)\n dataset = dataset.shuffle(FLAGS.shuffle_buffer_size, seed=0)\n dataset = dataset.batch(FLAGS.examples_to_take)\n iterator = dataset.make_initializable_iterator()\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, iterator.initializer)\n (images, labels, _) = iterator.get_next()\n images = tf.cast(images, tf.float32)\n return (images, labels)","code_tokens":"","url":308975} +{"project_name":"RLE-Foundation\/rllte","file_name":"natural_imgsource.py","full_name":"ImageSource.reset","func_name":"reset","docstring":"Called when an episode ends.","docstring_tokens":"","code":"def reset(self):\n \"\"\"Called when an episode ends.\"\"\"\n pass","code_tokens":"","url":333277} +{"project_name":"chenbinghui1\/DSL","file_name":"anchor_head.py","full_name":"AnchorHead.loss","func_name":"loss","docstring":"Compute losses of the head.","docstring_tokens":"","code":"@force_fp32(apply_to=('cls_scores', 'bbox_preds'))\ndef loss(self, cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None):\n \"\"\"Compute losses of the head.\n\n Args:\n cls_scores (list[Tensor]): Box scores for each scale level\n Has shape (N, num_anchors * num_classes, H, W)\n bbox_preds (list[Tensor]): Box energies \/ deltas for each scale\n level with shape (N, num_anchors * 4, H, W)\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss. Default: None\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == self.anchor_generator.num_levels\n device = cls_scores[0].device\n (anchor_list, valid_flag_list) = self.get_anchors(featmap_sizes, img_metas, device=device)\n label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1\n cls_reg_targets = self.get_targets(anchor_list, valid_flag_list, gt_bboxes, img_metas, gt_bboxes_ignore_list=gt_bboxes_ignore, gt_labels_list=gt_labels, label_channels=label_channels)\n if cls_reg_targets is None:\n return None\n (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets\n num_total_samples = num_total_pos + num_total_neg if self.sampling else num_total_pos\n num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]\n concat_anchor_list = []\n for i in range(len(anchor_list)):\n concat_anchor_list.append(torch.cat(anchor_list[i]))\n all_anchor_list = images_to_levels(concat_anchor_list, num_level_anchors)\n (losses_cls, losses_bbox) = multi_apply(self.loss_single, cls_scores, bbox_preds, all_anchor_list, labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_samples=num_total_samples)\n return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)","code_tokens":"","url":167653} +{"project_name":"salesforce\/CodeRL","file_name":"retrieval_rag.py","full_name":"Index.get_top_docs","func_name":"get_top_docs","docstring":"For each query in the batch, retrieves `n_docs` documents.","docstring_tokens":"","code":"def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n For each query in the batch, retrieves `n_docs` documents.\n\n Args:\n question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`):\n An array of query vectors.\n n_docs (`int`):\n The number of docs retrieved per query.\n\n Returns:\n `np.ndarray` of shape `(batch_size, n_docs)`: A tensor of indices of retrieved documents. `np.ndarray` of\n shape `(batch_size, vector_size)`: A tensor of vector representations of retrieved documents.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":495031} +{"project_name":"hamza-murad\/AALU","file_name":"assistant_v1.py","full_name":"MessageRequest.from_dict","func_name":"from_dict","docstring":"Initialize a MessageRequest object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'MessageRequest':\n \"\"\"Initialize a MessageRequest object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['input', 'intents', 'entities', 'alternate_intents', 'context', 'output', 'actions']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class MessageRequest: ' + ', '.join(bad_keys))\n if 'input' in _dict:\n args['input'] = MessageInput._from_dict(_dict.get('input'))\n if 'intents' in _dict:\n args['intents'] = [RuntimeIntent._from_dict(x) for x in _dict.get('intents')]\n if 'entities' in _dict:\n args['entities'] = [RuntimeEntity._from_dict(x) for x in _dict.get('entities')]\n if 'alternate_intents' in _dict:\n args['alternate_intents'] = _dict.get('alternate_intents')\n if 'context' in _dict:\n args['context'] = Context._from_dict(_dict.get('context'))\n if 'output' in _dict:\n args['output'] = OutputData._from_dict(_dict.get('output'))\n if 'actions' in _dict:\n args['actions'] = [DialogNodeAction._from_dict(x) for x in _dict.get('actions')]\n return cls(**args)","code_tokens":"","url":5246} +{"project_name":"google-research\/scenic","file_name":"test_model.py","full_name":"OmniNetModelTest.test_omnimixer_output_shape","func_name":"test_omnimixer_output_shape","docstring":"Tests validity of output's shape of OmniMixerEncoder module.","docstring_tokens":"","code":"@parameterized.parameters(itertools.product([True, False], [1, 2, 4], ['max', 'last']))\ndef test_omnimixer_output_shape(self, skip_standard, partition, pool):\n \"\"\"Tests validity of output's shape of OmniMixerEncoder module.\"\"\"\n rng = random.PRNGKey(0)\n x = jnp.ones((4, 16, 32))\n omnimixer_configs = ml_collections.ConfigDict({'skip_standard': skip_standard, 'partition': partition, 'pool': pool, 'depth_mlp_dim': 16})\n omnimixer_encoder_def = functools.partial(model.OmniMixerEncoder, num_layers=4, channels_mlp_dim=32, sequence_mlp_dim=8, omnimixer=omnimixer_configs)\n omnimixer_encoder_vars = omnimixer_encoder_def().init(rng, x, train=False)\n y = omnimixer_encoder_def().apply(omnimixer_encoder_vars, x, train=False)\n self.assertEqual(y.shape, x.shape)","code_tokens":"","url":847153} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"common_layers.py","full_name":"mean_with_attention","func_name":"mean_with_attention","docstring":"Mean and attention to reduce spatial dimensions.","docstring_tokens":"","code":"def mean_with_attention(x, name, num_heads=4):\n \"\"\"Mean and attention to reduce spatial dimensions.\"\"\"\n with tf.variable_scope(name):\n shape = shape_list(x)\n m = tf.reduce_mean(x, [1, 2])\n a = tf.layers.dense(x, num_heads, name='mean_attn')\n s = tf.reshape(a, [shape[0], -1, num_heads])\n s = tf.nn.softmax(s, axis=1)\n s = tf.reshape(s, shape[:-1] + [1, num_heads])\n am = tf.reduce_mean(tf.expand_dims(x, axis=-1) * s, [1, 2])\n l = tf.concat([am, tf.expand_dims(m, axis=-1)], axis=-1)\n return tf.layers.dense(tf.reshape(l, [shape[0], (num_heads + 1) * shape[-1]]), 2 * shape[-1], name='mean_attn_final')","code_tokens":"","url":965347} +{"project_name":"jonathanventura\/cylindricalsfmlearner","file_name":"headcam_loader.py","full_name":"headcam_loader.load_image_raw","func_name":"load_image_raw","docstring":"Returns a raw image given a drive and frame id.","docstring_tokens":"","code":"def load_image_raw(self, drive, frame_id):\n \"\"\"Returns a raw image given a drive and frame id.\"\"\"\n date = drive[-10:]\n img_file = os.path.join(self.dataset_dir, date, drive, frame_id + '.png')\n img = cv2.imread(img_file)\n return img","code_tokens":"","url":197746} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"ast_util.py","full_name":"CleanCopier.copy","func_name":"copy","docstring":"Returns a deep copy of node (excluding some fields, see copy_clean).","docstring_tokens":"","code":"def copy(self, node):\n \"\"\"Returns a deep copy of node (excluding some fields, see copy_clean).\"\"\"\n if isinstance(node, list):\n return [self.copy(n) for n in node]\n elif isinstance(node, tuple):\n return tuple((self.copy(n) for n in node))\n elif not isinstance(node, (gast.AST, ast.AST)):\n return node\n assert isinstance(node, (gast.AST, ast.AST))\n new_fields = {}\n for f in node._fields:\n if not f.startswith('__') and hasattr(node, f):\n new_fields[f] = self.copy(getattr(node, f))\n new_node = type(node)(**new_fields)\n if self.preserve_annos:\n for k in self.preserve_annos:\n anno.copyanno(node, new_node, k)\n return new_node","code_tokens":"","url":312382} +{"project_name":"Megvii-BaseDetection\/cvpods","file_name":"dynamic_backbone.py","full_name":"build_dynamic_backbone","func_name":"build_dynamic_backbone","docstring":"Create a Dynamic Backbone from config.","docstring_tokens":"","code":"def build_dynamic_backbone(cfg, input_shape: ShapeSpec):\n \"\"\"\n Create a Dynamic Backbone from config.\n\n Args:\n cfg: a config dict\n\n Returns:\n backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.\n \"\"\"\n if input_shape is None:\n input_shape = ShapeSpec(channels=len(cfg.MODEL.PIXEL_MEAN))\n backbone = DynamicNetwork(init_channel=cfg.MODEL.BACKBONE.INIT_CHANNEL, input_shape=input_shape, cell_num_list=cfg.MODEL.BACKBONE.CELL_NUM_LIST, layer_num=cfg.MODEL.BACKBONE.LAYER_NUM, norm=cfg.MODEL.BACKBONE.NORM, cal_flops=cfg.MODEL.CAL_FLOPS, cell_type=cfg.MODEL.BACKBONE.CELL_TYPE, max_stride=cfg.MODEL.BACKBONE.MAX_STRIDE, sep_stem=cfg.MODEL.BACKBONE.SEPT_STEM, using_gate=cfg.MODEL.GATE.GATE_ON, small_gate=cfg.MODEL.GATE.SMALL_GATE, gate_bias=cfg.MODEL.GATE.GATE_INIT_BIAS, drop_prob=cfg.MODEL.BACKBONE.DROP_PROB)\n return backbone","code_tokens":"","url":522954} +{"project_name":"deepmind\/acme","file_name":"helpers.py","full_name":"make_dqn_atari_network","func_name":"make_dqn_atari_network","docstring":"Creates networks for training DQN on Atari.","docstring_tokens":"","code":"def make_dqn_atari_network(environment_spec: specs.EnvironmentSpec) -> dqn.DQNNetworks:\n \"\"\"Creates networks for training DQN on Atari.\"\"\"\n\n def network(inputs):\n model = hk.Sequential([networks_lib.AtariTorso(), hk.nets.MLP([512, environment_spec.actions.num_values])])\n return model(inputs)\n network_hk = hk.without_apply_rng(hk.transform(network))\n obs = utils.add_batch_dim(utils.zeros_like(environment_spec.observations))\n network = networks_lib.FeedForwardNetwork(init=lambda rng: network_hk.init(rng, obs), apply=network_hk.apply)\n typed_network = networks_lib.non_stochastic_network_to_typed(network)\n return dqn.DQNNetworks(policy_network=typed_network)","code_tokens":"","url":7976} +{"project_name":"nilearn\/nilearn","file_name":"test_img_plotting.py","full_name":"test_plotting_functions_with_nans_in_bg_img","func_name":"test_plotting_functions_with_nans_in_bg_img","docstring":"Smoke test for plotting functions with nans in background image.","docstring_tokens":"","code":"@pytest.mark.parametrize('plot_func', [plot_anat, plot_roi, plot_stat_map])\ndef test_plotting_functions_with_nans_in_bg_img(plot_func, img_3d_mni):\n \"\"\"Smoke test for plotting functions with nans in background image.\"\"\"\n bg_img = _add_nans_to_img(img_3d_mni)\n if plot_func == plot_anat:\n plot_func(bg_img)\n else:\n plot_func(img_3d_mni, bg_img=bg_img)\n plt.close()","code_tokens":"","url":724146} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"cwise_ops_test.py","full_name":"SelectOpTest.testNan","func_name":"testNan","docstring":"Verify that nans don't propagate where they shouldn't.","docstring_tokens":"","code":"def testNan(self):\n \"\"\"Verify that nans don't propagate where they shouldn't.\"\"\"\n with self.test_session():\n for c in (False, True):\n for a in (7.0, np.nan):\n for b in (5.0, np.nan):\n x = array_ops.where(c, a, b).eval()\n y = a if c else b\n self.assertEqual(np.isnan(x), np.isnan(y))","code_tokens":"","url":605600} +{"project_name":"thallada\/nlp","file_name":"rc_model.py","full_name":"RCModel.decode","func_name":"decode","docstring":"Implements the answer pointer part of the model.","docstring_tokens":"","code":"def decode(self, name, input):\n \"\"\"\n Implements the answer pointer part of the model.\n\n Args:\n name: name prefix of the layers defined in this method.\n input: the encoding of the paragraph.\n\n Returns:\n A probability distribution over temporal axis.\n \"\"\"\n latent = layer.fc(size=input.size \/ 2, input=input, act=Act.Tanh(), bias_attr=False)\n probs = layer.fc(name=name, size=1, input=latent, act=Act.SequenceSoftmax())\n return probs","code_tokens":"","url":808496} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"getpass.py","full_name":"unix_getpass","func_name":"unix_getpass","docstring":"Prompt for a password, with echo turned off.","docstring_tokens":"","code":"def unix_getpass(prompt='Password: ', stream=None):\n \"\"\"Prompt for a password, with echo turned off.\n\n Args:\n prompt: Written on stream to ask for the input. Default: 'Password: '\n stream: A writable file object to display the prompt. Defaults to\n the tty. If no tty is available defaults to sys.stderr.\n Returns:\n The seKr3t input.\n Raises:\n EOFError: If our input tty or stdin was closed.\n GetPassWarning: When we were unable to turn echo off on the input.\n\n Always restores terminal settings before returning.\n \"\"\"\n passwd = None\n with contextlib.ExitStack() as stack:\n try:\n fd = os.open('\/dev\/tty', os.O_RDWR | os.O_NOCTTY)\n tty = io.FileIO(fd, 'w+')\n stack.enter_context(tty)\n input = io.TextIOWrapper(tty)\n stack.enter_context(input)\n if not stream:\n stream = input\n except OSError as e:\n stack.close()\n try:\n fd = sys.stdin.fileno()\n except (AttributeError, ValueError):\n fd = None\n passwd = fallback_getpass(prompt, stream)\n input = sys.stdin\n if not stream:\n stream = sys.stderr\n if fd is not None:\n try:\n old = termios.tcgetattr(fd)\n new = old[:]\n new[3] &= ~termios.ECHO\n tcsetattr_flags = termios.TCSAFLUSH\n if hasattr(termios, 'TCSASOFT'):\n tcsetattr_flags |= termios.TCSASOFT\n try:\n termios.tcsetattr(fd, tcsetattr_flags, new)\n passwd = _raw_input(prompt, stream, input=input)\n finally:\n termios.tcsetattr(fd, tcsetattr_flags, old)\n stream.flush()\n except termios.error:\n if passwd is not None:\n raise\n if stream is not input:\n stack.close()\n passwd = fallback_getpass(prompt, stream)\n stream.write('\\n')\n return passwd","code_tokens":"","url":280441} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"cache.py","full_name":"Cache.getsizeof","func_name":"getsizeof","docstring":"Return the size of a cache element's value.","docstring_tokens":"","code":"@staticmethod\ndef getsizeof(value):\n \"\"\"Return the size of a cache element's value.\"\"\"\n return 1","code_tokens":"","url":214215} +{"project_name":"vanderschaarlab\/mlforhealthlabpub","file_name":"add_noise.py","full_name":"add_noise","func_name":"add_noise","docstring":"Add Gaussian noise on the original data and use as the synthetic data.","docstring_tokens":"","code":"def add_noise(ori_data, noise_size):\n \"\"\"Add Gaussian noise on the original data and use as the synthetic data.\n\n Args:\n - ori_data: original time-series data\n - noise_size: amplitude of the added noise\n\n Returns:\n - generated_data: generated synthetic data\n \"\"\"\n (no, seq_len, dim) = ori_data.shape\n prep_data = np.reshape(ori_data.copy(), [no * seq_len, dim])\n for i in range(dim):\n noise_amplitude = np.std(prep_data[:, i]) * noise_size\n noise_vector = np.random.normal(0, noise_amplitude, size=[no * seq_len])\n prep_data[:, i] = prep_data[:, i] + noise_vector\n generated_data = np.reshape(prep_data, [no, seq_len, dim])\n return generated_data","code_tokens":"","url":240174} +{"project_name":"RasaHQ\/rasa","file_name":"importer.py","full_name":"E2EImporter.get_domain","func_name":"get_domain","docstring":"Retrieves model domain (see parent class for full docstring).","docstring_tokens":"","code":"@rasa.shared.utils.common.cached_method\ndef get_domain(self) -> Domain:\n \"\"\"Retrieves model domain (see parent class for full docstring).\"\"\"\n original = self.importer.get_domain()\n e2e_domain = self._get_domain_with_e2e_actions()\n return original.merge(e2e_domain)","code_tokens":"","url":837642} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"data.py","full_name":"OTXAnomalyDataModule.summary","func_name":"summary","docstring":"Print size of the dataset, number of anomalous images and number of normal images.","docstring_tokens":"","code":"def summary(self):\n \"\"\"Print size of the dataset, number of anomalous images and number of normal images.\"\"\"\n for subset in [Subset.TRAINING, Subset.VALIDATION, Subset.TESTING]:\n dataset = self.dataset.get_subset(subset)\n num_items = len(dataset)\n num_normal = len([item for item in dataset if not item.get_shapes_labels()[0].is_anomalous])\n num_anomalous = len([item for item in dataset if item.get_shapes_labels()[0].is_anomalous])\n logger.info(\"'%s' subset size: Total '%d' images. Normal: '%d', images. Anomalous: '%d' images\", subset, num_items, num_normal, num_anomalous)","code_tokens":"","url":903926} +{"project_name":"qm19\/A-Weakly-Supervised-Learning-based-Oversampling-Framework-for-Imbalanced-Classification","file_name":"utils.py","full_name":"imbalance_train_test_split","func_name":"imbalance_train_test_split","docstring":"Train\/Test split that guarantee same class distribution between split datasets.","docstring_tokens":"","code":"def imbalance_train_test_split(X, y, test_size, random_state=None):\n \"\"\"Train\/Test split that guarantee same class distribution between split datasets.\"\"\"\n X_maj = X[y == 0]\n y_maj = y[y == 0]\n X_min = X[y == 1]\n y_min = y[y == 1]\n (X_train_maj, X_test_maj, y_train_maj, y_test_maj) = train_test_split(X_maj, y_maj, test_size=test_size, random_state=random_state)\n (X_train_min, X_test_min, y_train_min, y_test_min) = train_test_split(X_min, y_min, test_size=test_size, random_state=random_state)\n X_train = np.concatenate([X_train_maj, X_train_min])\n X_test = np.concatenate([X_test_maj, X_test_min])\n y_train = np.concatenate([y_train_maj, y_train_min])\n y_test = np.concatenate([y_test_maj, y_test_min])\n return (X_train, X_test, y_train, y_test)","code_tokens":"","url":5100} +{"project_name":"KalleHallden\/InstaAutomator","file_name":"config.py","full_name":"change_settings","func_name":"change_settings","docstring":"Changes the value of configuration variables.","docstring_tokens":"","code":"def change_settings(new_settings={}, file=None):\n \"\"\" Changes the value of configuration variables.\"\"\"\n gl = globals()\n if file is not None:\n execfile(file)\n gl.update(locals())\n gl.update(new_settings)","code_tokens":"","url":230332} +{"project_name":"RasaHQ\/rasa","file_name":"domain.py","full_name":"SessionConfig.default","func_name":"default","docstring":"Returns the SessionConfig with the default values.","docstring_tokens":"","code":"@staticmethod\ndef default() -> 'SessionConfig':\n \"\"\"Returns the SessionConfig with the default values.\"\"\"\n return SessionConfig(DEFAULT_SESSION_EXPIRATION_TIME_IN_MINUTES, DEFAULT_CARRY_OVER_SLOTS_TO_NEW_SESSION)","code_tokens":"","url":837389} +{"project_name":"cnr-isti-vclab\/TagLab","file_name":"Annotation.py","full_name":"Annotation.clickedBlob","func_name":"clickedBlob","docstring":"It returns the blob clicked with the smallest area (to avoid problems with overlapping blobs).","docstring_tokens":"","code":"def clickedBlob(self, x, y):\n \"\"\"\n It returns the blob clicked with the smallest area (to avoid problems with overlapping blobs).\n \"\"\"\n blobs_clicked = []\n for blob in self.seg_blobs:\n point = np.array([[x, y]])\n out = measure.points_in_poly(point, blob.contour)\n if out[0] == True:\n blobs_clicked.append(blob)\n area_min = 100000000.0\n selected_blob = None\n for i in range(len(blobs_clicked)):\n blob = blobs_clicked[i]\n if blob.area < area_min:\n area_min = blob.area\n selected_blob = blob\n return selected_blob","code_tokens":"","url":906682} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"__init__.py","full_name":"get_reader_class","func_name":"get_reader_class","docstring":"Return the Reader class from the `reader_name` module.","docstring_tokens":"","code":"def get_reader_class(reader_name):\n \"\"\"Return the Reader class from the `reader_name` module.\"\"\"\n reader_name = reader_name.lower()\n if reader_name in _reader_aliases:\n reader_name = _reader_aliases[reader_name]\n try:\n module = __import__(reader_name, globals(), locals(), level=1)\n except ImportError:\n module = __import__(reader_name, globals(), locals(), level=0)\n return module.Reader","code_tokens":"","url":394960} +{"project_name":"microsoft\/MASS","file_name":"glue.py","full_name":"GLUE.train","func_name":"train","docstring":"Finetune for one epoch on the training set.","docstring_tokens":"","code":"def train(self):\n \"\"\"\n Finetune for one epoch on the training set.\n \"\"\"\n params = self.params\n self.embedder.train()\n self.proj.train()\n losses = []\n ns = 0\n nw = 0\n t = time.time()\n iterator = self.get_iterator('train')\n lang_id = params.lang2id['en']\n while True:\n try:\n batch = next(iterator)\n except StopIteration:\n break\n if self.n_sent == 1:\n ((x, lengths), idx) = batch\n (x, lengths) = truncate(x, lengths, params.max_len, params.eos_index)\n else:\n ((sent1, len1), (sent2, len2), idx) = batch\n (sent1, len1) = truncate(sent1, len1, params.max_len, params.eos_index)\n (sent2, len2) = truncate(sent2, len2, params.max_len, params.eos_index)\n (x, lengths, _, _) = concat_batches(sent1, len1, lang_id, sent2, len2, lang_id, params.pad_index, params.eos_index, reset_positions=False)\n y = self.data['train']['y'][idx]\n bs = len(lengths)\n (x, y, lengths) = to_cuda(x, y, lengths)\n output = self.proj(self.embedder.get_embeddings(x, lengths, positions=None, langs=None))\n if self.is_classif:\n loss = F.cross_entropy(output, y, weight=self.weights)\n else:\n loss = F.mse_loss(output.squeeze(1), y.float())\n self.optimizer.zero_grad()\n if params.fp16:\n self.optimizer.backward(loss)\n else:\n loss.backward()\n self.optimizer.step()\n ns += bs\n nw += lengths.sum().item()\n losses.append(loss.item())\n if ns != 0 and ns % (10 * bs) < bs:\n logger.info('GLUE - %s - Epoch %s - Train iter %7i - %.1f words\/s - %s Loss: %.4f' % (self.task, self.epoch, ns, nw \/ (time.time() - t), 'XE' if self.is_classif else 'MSE', sum(losses) \/ len(losses)))\n (nw, t) = (0, time.time())\n losses = []\n if params.epoch_size != -1 and ns >= params.epoch_size:\n break","code_tokens":"","url":646070} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"event_file_inspector.py","full_name":"get_dict_to_print","func_name":"get_dict_to_print","docstring":"Transform the field-to-obs mapping into a printable dictionary.","docstring_tokens":"","code":"def get_dict_to_print(field_to_obs):\n \"\"\"Transform the field-to-obs mapping into a printable dictionary.\n\n Args:\n field_to_obs: Dict that maps string field to `Observation` list.\n\n Returns:\n A dict with the keys and values to print to console.\n \"\"\"\n\n def compressed_steps(steps):\n return {'num_steps': len(set(steps)), 'min_step': min(steps), 'max_step': max(steps), 'last_step': steps[-1], 'first_step': steps[0], 'outoforder_steps': get_out_of_order(steps)}\n\n def full_steps(steps):\n return {'steps': steps, 'outoforder_steps': get_out_of_order(steps)}\n output = {}\n for (field, observations) in field_to_obs.items():\n if not observations:\n output[field] = None\n continue\n steps = [x['step'] for x in observations]\n if field in SHORT_FIELDS:\n output[field] = compressed_steps(steps)\n if field in LONG_FIELDS:\n output[field] = full_steps(steps)\n return output","code_tokens":"","url":183213} +{"project_name":"pramodiperera\/virtual-keyboard","file_name":"show.py","full_name":"print_results","func_name":"print_results","docstring":"Print the information from installed distributions found.","docstring_tokens":"","code":"def print_results(distributions: Iterator[_PackageInfo], list_files: bool, verbose: bool) -> bool:\n \"\"\"\n Print the information from installed distributions found.\n \"\"\"\n results_printed = False\n for (i, dist) in enumerate(distributions):\n results_printed = True\n if i > 0:\n write_output('---')\n write_output('Name: %s', dist.name)\n write_output('Version: %s', dist.version)\n write_output('Summary: %s', dist.summary)\n write_output('Home-page: %s', dist.homepage)\n write_output('Author: %s', dist.author)\n write_output('Author-email: %s', dist.author_email)\n write_output('License: %s', dist.license)\n write_output('Location: %s', dist.location)\n write_output('Requires: %s', ', '.join(dist.requires))\n write_output('Required-by: %s', ', '.join(dist.required_by))\n if verbose:\n write_output('Metadata-Version: %s', dist.metadata_version)\n write_output('Installer: %s', dist.installer)\n write_output('Classifiers:')\n for classifier in dist.classifiers:\n write_output(' %s', classifier)\n write_output('Entry-points:')\n for entry in dist.entry_points:\n write_output(' %s', entry.strip())\n if list_files:\n write_output('Files:')\n if dist.files is None:\n write_output('Cannot locate RECORD or installed-files.txt')\n else:\n for line in dist.files:\n write_output(' %s', line.strip())\n return results_printed","code_tokens":"","url":931911} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"has_props.py","full_name":"HasProps.lookup","func_name":"lookup","docstring":"Find the ``PropertyDescriptor`` for a Bokeh property on a class, given the property name.","docstring_tokens":"","code":"@classmethod\ndef lookup(cls, name):\n \"\"\" Find the ``PropertyDescriptor`` for a Bokeh property on a class,\n given the property name.\n\n Args:\n name (str) : name of the property to search for\n\n Returns:\n PropertyDescriptor : descriptor for property named ``name``\n\n \"\"\"\n return getattr(cls, name)","code_tokens":"","url":977224} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"qcore.py","full_name":"token_lists","func_name":"token_lists","docstring":"Returns the terms in the query tree, with the query hierarchy represented as nested lists.","docstring_tokens":"","code":"def token_lists(q, phrases=True):\n \"\"\"Returns the terms in the query tree, with the query hierarchy\n represented as nested lists.\n \"\"\"\n if q.is_leaf():\n from whoosh.query import Phrase\n if phrases or not isinstance(q, Phrase):\n return list(q.tokens())\n else:\n ls = []\n for qq in q.children():\n t = token_lists(qq, phrases=phrases)\n if len(t) == 1:\n t = t[0]\n if t:\n ls.append(t)\n return ls","code_tokens":"","url":484672} +{"project_name":"rlgraph\/rlgraph","file_name":"test_dqfd_agent_functionality.py","full_name":"TestDQFDAgentFunctionality.test_update_from_demos","func_name":"test_update_from_demos","docstring":"Tests the separate API method to update from demos.","docstring_tokens":"","code":"def test_update_from_demos(self):\n \"\"\"\n Tests the separate API method to update from demos.\n \"\"\"\n env = OpenAIGymEnv.from_spec(self.env_spec)\n agent_config = config_from_path('configs\/dqfd_agent_for_cartpole.json')\n agent = DQFDAgent.from_spec(agent_config, state_space=env.state_space, action_space=env.action_space)\n terminals = BoolBox(add_batch_rank=True)\n rewards = FloatBox(add_batch_rank=True)\n state_1 = agent.preprocessed_state_space.with_batch_rank().sample(1)\n action_1 = [1]\n state_2 = agent.preprocessed_state_space.with_batch_rank().sample(1)\n action_2 = [0]\n for _ in range(10):\n agent.observe_demos(preprocessed_states=state_1, actions=action_1, rewards=rewards.sample(1), next_states=agent.preprocessed_state_space.with_batch_rank().sample(1), terminals=terminals.sample(1))\n agent.observe_demos(preprocessed_states=state_2, actions=action_2, rewards=rewards.sample(1), next_states=agent.preprocessed_state_space.with_batch_rank().sample(1), terminals=terminals.sample(1))\n agent.update_from_demos(batch_size=8, num_updates=1000)\n action = agent.get_action(states=state_1, apply_preprocessing=False, use_exploration=False)\n self.assertEqual(action, action_1)\n action = agent.get_action(states=state_2, apply_preprocessing=False, use_exploration=False)\n self.assertEqual(action, action_2)","code_tokens":"","url":862678} +{"project_name":"lozuwa\/impy","file_name":"ObjectDetectionDataset.py","full_name":"ObjectDetectionDataset.applyDataAugmentation","func_name":"applyDataAugmentation","docstring":"Applies one or multiple data augmentation methods to the dataset.","docstring_tokens":"","code":"def applyDataAugmentation(self, configurationFile=None, outputImageDirectory=None, outputAnnotationDirectory=None, threshold=None):\n \"\"\"\n\t\tApplies one or multiple data augmentation methods to the dataset.\n\t\tArgs:\n\t\t\tconfigurationFile: A string with a path to a json file that contains the \n\t\t\t\t\t\t\t\tconfiguration of the data augmentation methods.\n\t\t\toutputImageDirectory: A string that contains the path to the directory where\n\t\t\t\t\t\t\t\t\t\t\t\t\t\timages will be saved.\n\t\t\toutputAnnotationDirectory: A string that contains the path the directory where\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tannotations will be saved.\n\t\t\tthreshold: A float that contains a number between 0 and 1.\n\t\tReturns:\n\t\t\tNone\n\t\t\"\"\"\n if configurationFile == None:\n raise ValueError('ERROR: Augmenter parameter cannot be empty.')\n elif not os.path.isfile(configurationFile):\n raise Exception('ERROR: Path to json file ({}) does not exist.'.format(configurationFile))\n jsonConf = AugmentationConfigurationFile(file=configurationFile)\n typeAugmentation = jsonConf.runAllAssertions()\n if outputImageDirectory == None:\n outputImageDirectory = os.getcwd()\n Util.create_folder(os.path.join(outputImageDirectory, 'images'))\n outputImageDirectory = os.path.join(os.getcwd(), 'images')\n if not os.path.isdir(outputImageDirectory):\n raise Exception('ERROR: Path to output directory does not exist. {}'.format(outputImageDirectory))\n if outputAnnotationDirectory == None:\n outputAnnotationDirectory = os.getcwd()\n Util.create_folder(os.path.join(outputAnnotationDirectory, 'annotations'))\n Util.create_folder(os.path.join(outputAnnotationDirectory, 'annotations', 'xmls'))\n outputAnnotationDirectory = os.path.join(os.getcwd(), 'annotations', 'xmls')\n if not os.path.isdir(outputAnnotationDirectory):\n raise Exception('ERROR: Path to output annotation directory does not exist. {}'.format(outputAnnotationDirectory))\n if threshold == None:\n threshold = 0.5\n if type(threshold) != float:\n raise TyperError('ERROR: threshold parameter must be of type float.')\n if threshold > 1 or threshold < 0:\n raise ValueError('ERROR: threshold paramater should be a number between' + ' 0-1.')\n f = open(configurationFile)\n data = json.load(f)\n f.close()\n for img in tqdm(os.listdir(self.imagesDirectory)):\n extension = Util.detect_file_extension(filename=img)\n if extension == None:\n raise Exception('ERROR: Your image extension is not valid.' + 'Only jpgs and pngs are allowed.')\n filename = os.path.split(img)[1].split(extension)[0]\n imgFullPath = os.path.join(self.imagesDirectory, filename + extension)\n xmlFullPath = os.path.join(self.annotationsDirectory, filename + '.xml')\n imgAnt = ImageAnnotation(path=xmlFullPath)\n boundingBoxes = imgAnt.propertyBoundingBoxes\n names = imgAnt.propertyNames\n if typeAugmentation == 0:\n for i in data['bounding_box_augmenters']:\n if i == 'Sequential':\n frame = cv2.imread(imgFullPath)\n bndboxes = boundingBoxes\n assert type(data['bounding_box_augmenters'][i]) == list, 'Not list'\n for k in range(len(data['bounding_box_augmenters'][i])):\n augmentationType = list(data['bounding_box_augmenters'][i][k].keys())[0]\n if not jsonConf.isValidBoundingBoxAugmentation(augmentation=augmentationType):\n raise Exception('ERROR: {} is not valid.'.format(augmentationType))\n parameters = data['bounding_box_augmenters'][i][k][augmentationType]\n saveParameter = jsonConf.extractSavingParameter(parameters=parameters)\n (frame, bndboxes) = applyBoundingBoxAugmentation(frame=frame, boundingBoxes=bndboxes, augmentationType=augmentationType, parameters=parameters)\n if saveParameter == True:\n newName = Util.create_random_name(name=self.databaseName, length=4)\n imgName = newName + extension\n xmlName = newName + '.xml'\n Util.save_img(frame=frame, img_name=imgName, output_image_directory=outputImageDirectory)\n Util.save_annotation(filename=imgName, path=os.path.join(outputImageDirectory, imgName), database_name=self.databaseName, frame_size=frame.shape, data_augmentation_type=augmentationType, bounding_boxes=bndboxes, names=names, origin=imgFullPath, output_directory=os.path.join(outputAnnotationDirectory, xmlName))\n else:\n parameters = data['bounding_box_augmenters'][i]\n saveParameter = jsonConf.extractSavingParameter(parameters=parameters)\n (frame, bndboxes) = applyBoundingBoxAugmentation(frame=cv2.imread(imgFullPath), boundingBoxes=boundingBoxes, augmentationType=i, parameters=parameters)\n if saveParameter == True:\n newName = Util.create_random_name(name=self.databaseName, length=4)\n imgName = newName + extension\n xmlName = newName + '.xml'\n Util.save_img(frame=frame, img_name=imgName, output_image_directory=outputImageDirectory)\n Util.save_annotation(filename=imgName, path=os.path.join(outputImageDirectory, imgName), database_name=self.databaseName, frame_size=frame.shape, data_augmentation_type=augmentationType, bounding_boxes=bndboxes, names=names, origin=imgFullPath, output_directory=os.path.join(outputAnnotationDirectory, xmlName))\n elif typeAugmentation == 1:\n raise ValueError('Image geometric data augmentations are not ' + 'supported for bounding boxes. Use bounding box ' + 'augmentation types.')\n elif typeAugmentation == 2:\n for i in data['image_color_augmenters']:\n if i == 'Sequential':\n frame = cv2.imread(imgFullPath)\n assert type(data['image_color_augmenters'][i]) == list, 'Not list'\n for k in range(len(data['image_color_augmenters'][i])):\n augmentationType = list(data['image_color_augmenters'][i][k].keys())[0]\n if not jsonConf.isValidColorAugmentation(augmentation=augmentationType):\n raise Exception('ERROR: {} is not valid.'.format(augmentationType))\n parameters = data['image_color_augmenters'][i][k][augmentationType]\n saveParameter = jsonConf.extractSavingParameter(parameters=parameters)\n frame = applyColorAugmentation(frame=frame, augmentationType=augmentationType, parameters=parameters)\n if saveParameter == True:\n newName = Util.create_random_name(name=self.databaseName, length=4)\n imgName = newName + extension\n xmlName = newName + '.xml'\n Util.save_img(frame=frame, img_name=imgName, output_image_directory=outputImageDirectory)\n Util.save_annotation(filename=imgName, path=os.path.join(outputImageDirectory, imgName), database_name=self.databaseName, frame_size=frame.shape, data_augmentation_type=augmentationType, bounding_boxes=bndboxes, names=names, origin=imgFullPath, output_directory=os.path.join(outputAnnotationDirectory, xmlName))\n else:\n parameters = data['image_color_augmenters'][i]\n saveParameter = jsonConf.extractSavingParameter(parameters=parameters)\n frame = applyColorAugmentation(frame=cv2.imread(imgFullPath), augmentationType=i, parameters=parameters)\n if saveParameter == True:\n newName = Util.create_random_name(name=self.databaseName, length=4)\n imgName = newName + extension\n xmlName = newName + '.xml'\n Util.save_img(frame=frame, img_name=imgName, output_image_directory=outputImageDirectory)\n Util.save_annotation(filename=imgName, path=os.path.join(outputImageDirectory, imgName), database_name=self.databaseName, frame_size=frame.shape, data_augmentation_type=augmentationType, bounding_boxes=bndboxes, names=names, origin=imgFullPath, output_directory=os.path.join(outputAnnotationDirectory, xmlName))\n elif typeAugmentation == 3:\n if not 'Sequential' in data['multiple_image_augmentations']:\n raise Exception('ERROR: Data after multiple_image_augmentations is not recognized.')\n list_of_augmenters_confs = data['multiple_image_augmentations']['Sequential']\n if not type(list_of_augmenters_confs) == list:\n raise TypeError('ERROR: Data inside [multiple_image_augmentations][Sequential] must be a list.')\n frame = cv2.imread(imgFullPath)\n bndboxes = boundingBoxes\n for k in range(len(list_of_augmenters_confs)):\n augmentationConf = list(list_of_augmenters_confs[k].keys())[0]\n if not (jsonConf.isBndBxAugConfFile(keys=[augmentationConf]) or jsonConf.isColorConfFile(keys=[augmentationConf])):\n raise Exception('{} is not a valid configuration.'.format(augmentationConf))\n list_of_augmenters_confs_types = list_of_augmenters_confs[k][augmentationConf]['Sequential']\n if not type(list_of_augmenters_confs_types) == list:\n raise TypeError('Data inside [multiple_image_augmentations][Sequential][{}][Sequential] must be a list.'.format(augmentationConf))\n for l in range(len(list_of_augmenters_confs_types)):\n augmentationType = list(list_of_augmenters_confs_types[l].keys())[0]\n if not (jsonConf.isValidBoundingBoxAugmentation(augmentation=augmentationType) or jsonConf.isValidColorAugmentation(augmentation=augmentationType)):\n raise Exception('ERROR: {} is not valid.'.format(augmentationType))\n parameters = list_of_augmenters_confs_types[l][augmentationType]\n saveParameter = jsonConf.extractSavingParameter(parameters=parameters)\n restartFrameParameter = jsonConf.extractRestartFrameParameter(parameters=parameters)\n randomEvent = jsonConf.randomEvent(parameters=parameters, threshold=threshold)\n if augmentationConf == 'image_color_augmenters':\n if randomEvent == True:\n frame = applyColorAugmentation(frame=frame, augmentationType=augmentationType, parameters=parameters)\n elif augmentationConf == 'bounding_box_augmenters':\n if randomEvent == True:\n (frame, bndboxes) = applyBoundingBoxAugmentation(frame=frame, boundingBoxes=bndboxes, augmentationType=augmentationType, parameters=parameters)\n if saveParameter == True and randomEvent == True:\n newName = Util.create_random_name(name=self.databaseName, length=4)\n imgName = newName + extension\n xmlName = newName + '.xml'\n Util.save_img(frame=frame, img_name=imgName, output_image_directory=outputImageDirectory)\n Util.save_annotation(filename=imgName, path=os.path.join(outputImageDirectory, imgName), database_name=self.databaseName, frame_size=frame.shape, data_augmentation_type=augmentationType, bounding_boxes=bndboxes, names=names, origin=imgFullPath, output_directory=os.path.join(outputAnnotationDirectory, xmlName))\n if restartFrameParameter == True:\n frame = cv2.imread(imgFullPath)\n bndboxes = boundingBoxes\n else:\n raise Exception('Type augmentation {} not valid.'.format(typeAugmentation))","code_tokens":"","url":611626} +{"project_name":"rudranil723\/mini-main","file_name":"column.py","full_name":"PandasColumn.metadata","func_name":"metadata","docstring":"Store specific metadata of the column.","docstring_tokens":"","code":"@property\ndef metadata(self) -> dict[str, pd.Index]:\n \"\"\"\n Store specific metadata of the column.\n \"\"\"\n return {'pandas.index': self._col.index}","code_tokens":"","url":323944} +{"project_name":"voxel51\/fiftyone","file_name":"github.py","full_name":"GitHubRepository.user","func_name":"user","docstring":"The username of the repo.","docstring_tokens":"","code":"@property\ndef user(self):\n \"\"\"The username of the repo.\"\"\"\n return self._user","code_tokens":"","url":584055} +{"project_name":"mhoogen\/ML4QS","file_name":"crowdsignals_ch3_outliers.py","full_name":"print_flags","func_name":"print_flags","docstring":"Prints all entries in FLAGS variable.","docstring_tokens":"","code":"def print_flags():\n \"\"\"\n Prints all entries in FLAGS variable.\n \"\"\"\n for (key, value) in vars(FLAGS).items():\n print(key + ' : ' + str(value))","code_tokens":"","url":629936} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"thinkstats2.py","full_name":"MakePmfFromHist","func_name":"MakePmfFromHist","docstring":"Makes a normalized PMF from a Hist object.","docstring_tokens":"","code":"def MakePmfFromHist(hist, label=None):\n \"\"\"Makes a normalized PMF from a Hist object.\n\n Args:\n hist: Hist object\n label: string label\n\n Returns:\n Pmf object\n \"\"\"\n if label is None:\n label = hist.label\n return Pmf(hist, label=label)","code_tokens":"","url":12820} +{"project_name":"tryolabs\/luminoth","file_name":"image_test.py","full_name":"ImageTest.testRandomDistort","func_name":"testRandomDistort","docstring":"Tests the integrity of the return values of random_distortion.","docstring_tokens":"","code":"def testRandomDistort(self):\n \"\"\"Tests the integrity of the return values of random_distortion.\n \"\"\"\n im_shape = (600, 900, 3)\n config = self._random_distort_config\n total_boxes = 5\n label = 3\n (image, bboxes) = self._get_image_with_boxes(im_shape, total_boxes)\n bboxes_w_label = tf.concat([bboxes, tf.fill((bboxes.shape[0], 1), label)], axis=1)\n (ret_image, ret_bboxes) = self._random_distort(image, config, bboxes_w_label)\n self.assertEqual(im_shape, ret_image.shape)\n self.assertAllEqual(bboxes, ret_bboxes[:, :4])","code_tokens":"","url":617567} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"well_known_types.py","full_name":"_FieldMaskTree.ToFieldMask","func_name":"ToFieldMask","docstring":"Converts the tree to a FieldMask.","docstring_tokens":"","code":"def ToFieldMask(self, field_mask):\n \"\"\"Converts the tree to a FieldMask.\"\"\"\n field_mask.Clear()\n _AddFieldPaths(self._root, '', field_mask)","code_tokens":"","url":310031} +{"project_name":"imoscovitz\/wittgenstein","file_name":"base_functions.py","full_name":"argmin","func_name":"argmin","docstring":"Return index of minimum value.","docstring_tokens":"","code":"def argmin(iterable):\n \"\"\"Return index of minimum value.\"\"\"\n lowest_val = iterable[0]\n lowest_i = 0\n for (i, val) in enumerate(iterable):\n if val < lowest_val:\n lowest_val = val\n lowest_i = i\n return lowest_i","code_tokens":"","url":959881} +{"project_name":"rajansh87\/ChatBot-Artificial-Intelligence","file_name":"ChatBot 1.0.py","full_name":"XYEnvironment.object_percept","func_name":"object_percept","docstring":"Return the percept for this object.","docstring_tokens":"","code":"def object_percept(self, obj, agent):\n \"\"\"Return the percept for this object.\"\"\"\n return obj.__class__.__name__","code_tokens":"","url":104751} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"mesh_tensorflow.py","full_name":"MeshImpl.allreduce","func_name":"allreduce","docstring":"Grouped allreduce, (summed across the given dimensions).","docstring_tokens":"","code":"def allreduce(self, x, mesh_axes, reduction_fn_string):\n \"\"\"Grouped allreduce, (summed across the given dimensions).\n\n Args:\n x: LaidOutTensor.\n mesh_axes: list of integers, the mesh dimensions to be reduced.\n reduction_fn_string: \"SUM\" or \"MAX\".\n\n Returns:\n LaidOutTensor.\n \"\"\"\n raise NotImplementedError('Allreduce not implemented')","code_tokens":"","url":965505} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_channel_selection.py","full_name":"test_channel_selection","func_name":"test_channel_selection","docstring":"Test channel selection on random nested data frame.","docstring_tokens":"","code":"def test_channel_selection():\n \"\"\"Test channel selection on random nested data frame.\"\"\"\n (X, y) = make_3d_test_data(n_cases=10, n_channels=4, n_timepoints=20)\n ecp = ElbowClassPairwise()\n ecp.fit(X, y)\n Xt = ecp.transform(X, y)\n assert Xt.shape == (X.shape[0], len(ecp.channels_selected_idx), X.shape[2])","code_tokens":"","url":399949} +{"project_name":"Eric3911\/OpenAGI","file_name":"test_ema.py","full_name":"TestEMATrain.test_ema_run_with_save_best_model","func_name":"test_ema_run_with_save_best_model","docstring":"Test to ensure that we save the model correctly when save best model is set to True.","docstring_tokens":"","code":"@pytest.mark.unit\ndef test_ema_run_with_save_best_model(self, tmpdir):\n \"\"\"Test to ensure that we save the model correctly when save best model is set to True.\"\"\"\n tmp_path = tmpdir \/ 'exp_manager_test'\n model = ExampleModel()\n trainer = Trainer(max_epochs=1, enable_checkpointing=False, logger=False, devices=1, limit_train_batches=1)\n exp_manager(trainer, {'ema': {'enable': True}, 'explicit_log_dir': str(tmp_path), 'checkpoint_callback_params': {'save_best_model': True}})\n trainer.fit(model)","code_tokens":"","url":274407} +{"project_name":"google-research\/crest","file_name":"resnet.py","full_name":"ResNetV1","func_name":"ResNetV1","docstring":"Instantiates the ResNet architecture.","docstring_tokens":"","code":"def ResNetV1(arch='ResNet18', input_shape=None, num_class=1000, pooling=None, normalization='bn', activation='relu', width=1.0, **kwargs):\n \"\"\"Instantiates the ResNet architecture.\"\"\"\n del kwargs\n\n def stack_fn(x, arch, width=1.0):\n (block, stack, expansion) = (BLOCK[arch], STACK[arch], EXPANSION[arch])\n x = stack(x, int(64 * width), block[0], expansion=expansion, stride1=1, normalization=normalization, activation=activation, name='conv2')\n x = stack(x, int(128 * width), block[1], expansion=expansion, normalization=normalization, activation=activation, name='conv3')\n x = stack(x, int(256 * width), block[2], expansion=expansion, normalization=normalization, activation=activation, name='conv4')\n return stack(x, int(512 * width), block[3], expansion=expansion, normalization=normalization, activation=activation, name='conv5')\n return ResNet(stack_fn=functools.partial(stack_fn, arch=arch, width=width), preact=False, model_name='{}_w{:g}_{}_{}'.format(arch, width, normalization, activation), input_shape=input_shape, pooling=pooling, normalization=normalization, activation=activation, num_class=num_class)","code_tokens":"","url":138520} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"tornado.py","full_name":"BokehTornado.get_sessions","func_name":"get_sessions","docstring":"Gets all currently active sessions for an application.","docstring_tokens":"","code":"def get_sessions(self, app_path):\n \"\"\" Gets all currently active sessions for an application.\n\n Args:\n app_path (str) :\n The configured application path for the application to return\n sessions for.\n\n Returns:\n list[ServerSession]\n\n \"\"\"\n if app_path not in self._applications:\n raise ValueError('Application %s does not exist on this server' % app_path)\n return list(self._applications[app_path].sessions)","code_tokens":"","url":977462} +{"project_name":"GregorKobsik\/Octree-Transformer","file_name":"shape_sampler.py","full_name":"ShapeSampler.sample_preconditioned","func_name":"sample_preconditioned","docstring":"Samples a single array of elements from the model.","docstring_tokens":"","code":"def sample_preconditioned(self, precondition, precondition_resolution=1, target_resolution=32, temperature=1.0, cls=None):\n \"\"\" Samples a single array of elements from the model.\n\n Args:\n precondition: Use a precondition for sampling up to a resolution in 'start_resolution' given as a numpy\n element array.\n precondition_resolution: Initial resolution used for the precondition. The precondition should have at\n least the `precondition_resolution` side length. Resolution values can be only power of 2.\n target_resolution: The target resolution for the up-sampling process. The resolution should be not bigger,\n than the trained model resolution. Resolution values can be only power of 2.\n temperature: Defines the randomness of the samples. Lower temperatures make the model increasingly\n confident in its top choices, while temperatures greater than 1 decrease confidence. 0 temperature is\n equivalent to argmax\/max likelihood, while infinite temperature corresponds to a uniform sampling.\n cls: if the transformer has been trained class conditional, we can add a class label\n from which to draw samples, otherwise this argument will be ignored.\n\n Return:\n A sampled array of elements (pixels\/voxels) with the size of `target_resolution` as a numpy array.\n\n TODO: If `input` is None, than a single random sample will be drawn from the dataset used in the model.\n TODO: Extend with `batch_size` to allow parallel sampling.\n \"\"\"\n if input is None:\n raise ValueError('ERROR: `input` cannot be `None`.')\n precon_res = min(self.trained_resolution, precondition_resolution)\n return self.sampler(precondition, precon_res, target_resolution, temperature, cls)","code_tokens":"","url":755092} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.body_iquat","func_name":"body_iquat","docstring":"local orientation of inertia ellipsoid (nbody x 4).","docstring_tokens":"","code":"@util.CachedProperty\ndef body_iquat(self):\n \"\"\"local orientation of inertia ellipsoid (nbody x 4).\"\"\"\n return util.buf_to_npy(self._ptr.contents.body_iquat, (self.nbody, 4))","code_tokens":"","url":440250} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.dof_armature","func_name":"dof_armature","docstring":"dof armature inertia\/mass (nv x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef dof_armature(self):\n \"\"\"dof armature inertia\/mass (nv x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.dof_armature, (self.nv,))","code_tokens":"","url":440278} +{"project_name":"deepmind\/dm_control","file_name":"finger.py","full_name":"Physics.touch","func_name":"touch","docstring":"Returns logarithmically scaled signals from the two touch sensors.","docstring_tokens":"","code":"def touch(self):\n \"\"\"Returns logarithmically scaled signals from the two touch sensors.\"\"\"\n return np.log1p(self.named.data.sensordata[['touchtop', 'touchbottom']])","code_tokens":"","url":165439} +{"project_name":"bnpy\/bnpy","file_name":"TestHDPHMM_ParallelBenchmark.py","full_name":"Test.run_baseline","func_name":"run_baseline","docstring":"Execute on entire matrix (no slices) in master process.","docstring_tokens":"","code":"def run_baseline(self):\n \"\"\" Execute on entire matrix (no slices) in master process.\n \"\"\"\n SSall = calcLocalParamsAndSummarize(self.Data, self.hmodel)\n return SSall","code_tokens":"","url":465513} +{"project_name":"p-lambda\/wilds","file_name":"process.py","full_name":"compute_pcba_fingerprint","func_name":"compute_pcba_fingerprint","docstring":"Compute the fingerprint features for molpcba molecules.","docstring_tokens":"","code":"def compute_pcba_fingerprint():\n \"\"\"\n Compute the fingerprint features for molpcba molecules.\n \"\"\"\n os.makedirs('processed_fp', exist_ok=True)\n pcba_dataset = get_dataset(dataset='ogb-molpcba')\n smiles_list = pd.read_csv('data\/ogbg_molpcba\/mapping\/mol.csv.gz')['smiles'].tolist()\n x_list = []\n for smiles in tqdm(smiles_list):\n mol = Chem.MolFromSmiles(smiles)\n x = np.array(list(AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=1024)), dtype=np.int8)\n x_list.append(x)\n x = np.stack(x_list)\n np.save('processed_fp\/molpcba.npy', x)","code_tokens":"","url":959615} +{"project_name":"bioinform\/neusomatic","file_name":"utils.py","full_name":"prob2phred","func_name":"prob2phred","docstring":"Convert prob to Phred-scale quality score.","docstring_tokens":"","code":"def prob2phred(p, max_phred=100):\n \"\"\"Convert prob to Phred-scale quality score.\"\"\"\n assert 0 <= p <= 1\n if p == 1:\n Q = max_phred\n elif p == 0:\n Q = 0\n else:\n Q = -10 * np.log10(1 - p)\n if Q > max_phred:\n Q = max_phred\n return Q","code_tokens":"","url":293754} +{"project_name":"matsu0228\/nlp-jp","file_name":"cmdshell.py","full_name":"LocalClient.get_file","func_name":"get_file","docstring":"Copy a file from one directory to another.","docstring_tokens":"","code":"def get_file(self, src, dst):\n \"\"\"\n Copy a file from one directory to another.\n \"\"\"\n shutil.copyfile(src, dst)","code_tokens":"","url":784883} +{"project_name":"intel\/neural-compressor","file_name":"util.py","full_name":"parse_tune_config","func_name":"parse_tune_config","docstring":"Convert the strategy config to MXNet quantization config.","docstring_tokens":"","code":"def parse_tune_config(tune_cfg, quantizable_nodes):\n \"\"\"Convert the strategy config to MXNet quantization config.\n\n Args:\n tune_cfg (dict): tune config from neural_compressor strategy.\n quantizable_nodes (list): quantizable nodes in the model.\n\n Returns:\n dict: quantization configuration.\n dict: calibration configuration.\n \"\"\"\n excluded_symbols = []\n calib_minmax_nodes = set()\n calib_kl_nodes = set()\n amp_excluded_nodes = set()\n for op in quantizable_nodes:\n cfg = tune_cfg['op'][op['name'], op['type']]['activation']\n if cfg['dtype'] not in ['bf16']:\n amp_excluded_nodes.add(op['name'])\n if cfg['dtype'] not in ['int8']:\n excluded_symbols.append(op['name'])\n cfg['algorithm'] = QUANTIZE_DEFAULT_ALGORITHM\n if cfg['algorithm'] == 'kl':\n calib_kl_nodes.add(op['name'])\n else:\n calib_minmax_nodes.add(op['name'])\n assert len(calib_kl_nodes & calib_minmax_nodes) == 0\n quant_cfg = {'excluded_symbols': excluded_symbols, 'quantized_dtype': 'auto', 'quantize_mode': 'smart'}\n if check_mx_version('1.7.0'):\n quant_cfg['quantize_granularity'] = 'tensor-wise'\n calib_cfg = {'quantized_dtype': quant_cfg['quantized_dtype'], 'batches': tune_cfg['calib_iteration'], 'calib_mode': 'naive', 'calib_kl_nodes': calib_kl_nodes, 'calib_minmax_nodes': calib_minmax_nodes}\n amp_cfg = {'target_dtype': 'bfloat16', 'excluded_sym_names': amp_excluded_nodes}\n return (quant_cfg, calib_cfg, amp_cfg)","code_tokens":"","url":737430} +{"project_name":"SeldonIO\/MLServer","file_name":"utils.py","full_name":"train_explainer","func_name":"train_explainer","docstring":"Train and save an explainer.","docstring_tokens":"","code":"def train_explainer(explainer_tag: str, save_dir: Optional[Path], init_args: tuple, init_kwargs: dict, fit: Union[np.ndarray, Literal[False, 'no-data']]=False) -> Explainer:\n \"\"\"\n Train and save an explainer.\n \"\"\"\n klass = import_and_get_class(get_alibi_class_as_str(explainer_tag))\n explainer = klass(*init_args, **init_kwargs)\n if fit:\n explainer.fit() if fit == 'no-data' else explainer.fit(fit)\n if save_dir:\n explainer.save(save_dir)\n return explainer","code_tokens":"","url":630932} +{"project_name":"ace19-dev\/gvcnn-tf","file_name":"_train_helper.py","full_name":"get_post_init_ops","func_name":"get_post_init_ops","docstring":"Copy values of variables on GPU 0 to other GPUs.","docstring_tokens":"","code":"def get_post_init_ops():\n \"\"\"\n Copy values of variables on GPU 0 to other GPUs.\n \"\"\"\n all_vars = tf.compat.v1.global_variables() + tf.compat.v1.local_variables()\n var_by_name = dict([(v.name, v) for v in all_vars])\n post_init_ops = []\n for v in all_vars:\n if not v.name.startswith('tower'):\n continue\n if v.name.startswith('tower0'):\n continue\n split_name = v.name.split('\/')\n prefix = split_name[0]\n realname = '\/'.join(split_name[1:])\n if prefix in realname:\n pass\n copy_from = var_by_name.get(v.name.replace(prefix, 'tower0'))\n if copy_from is not None:\n post_init_ops.append(v.assign(copy_from.read_value()))\n else:\n print('Cannot find {} in the graph!'.format(realname))\n print(\"'sync_variables_from_main_tower' includes {} operations.\".format(len(post_init_ops)))\n return tf.group(*post_init_ops, name='sync_variables_from_main_tower')","code_tokens":"","url":234101} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"afm.py","full_name":"AFM.get_vertical_stem_width","func_name":"get_vertical_stem_width","docstring":"Return the standard vertical stem width as float, or *None* if not specified in AFM file.","docstring_tokens":"","code":"def get_vertical_stem_width(self):\n \"\"\"\n Return the standard vertical stem width as float, or *None* if\n not specified in AFM file.\n \"\"\"\n return self._header.get(b'StdVW', None)","code_tokens":"","url":44} +{"project_name":"enuguru\/artificial_intelligence_and_machine_","file_name":"exthook.py","full_name":"ExtensionImporter.is_important_frame","func_name":"is_important_frame","docstring":"Checks a single frame if it's important.","docstring_tokens":"","code":"def is_important_frame(self, important_module, tb):\n \"\"\"Checks a single frame if it's important.\"\"\"\n g = tb.tb_frame.f_globals\n if '__name__' not in g:\n return False\n module_name = g['__name__']\n if module_name == important_module:\n return True\n filename = os.path.abspath(tb.tb_frame.f_code.co_filename)\n test_string = os.path.sep + important_module.replace('.', os.path.sep)\n return test_string + '.py' in filename or test_string + os.path.sep + '__init__.py' in filename","code_tokens":"","url":157778} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.name_bodyadr","func_name":"name_bodyadr","docstring":"body name pointers (nbody x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef name_bodyadr(self):\n \"\"\"body name pointers (nbody x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.name_bodyadr, (self.nbody,))","code_tokens":"","url":440475} +{"project_name":"neokarn\/computer_vision","file_name":"text_detection.py","full_name":"TextDetection.find_best_size","func_name":"find_best_size","docstring":"Compute best scale for test.","docstring_tokens":"","code":"def find_best_size(self, boxes, probs, threshold=0.9):\n \"\"\"\n Compute best scale for test.\n\n Args:\n boxes: predicted boxes.\n probs: probs corresponding to boxes.\n Returns:\n shortest_edge for test.\n \"\"\"\n thre_masks = probs > threshold\n length = np.sum(thre_masks)\n if length > 0:\n sqrt_areas = []\n levels = []\n shortest_edges = []\n boxes = boxes[thre_masks]\n for box in boxes:\n (x0, y0, x1, y1) = box\n w = x1 - x0\n h = y1 - y0\n sqrtarea = np.sqrt(w * h)\n level = np.floor(4 + np.log((sqrtarea * (1.0 \/ 224) + 1e-06) * (1.0 \/ np.log(2))))\n sqrt_areas.append(sqrtarea)\n levels.append(level)\n shortest_edges.append(min(w, h))\n counts = np.bincount(levels)\n most_level = np.argmax(counts)\n max_level = np.amax(levels)\n min_level = np.amin(levels)\n print('levels: {}'.format(levels))\n print('fpn level max: {}, min: {}, most: {}'.format(np.amax(levels), np.amin(levels), most_level))\n if most_level == 1:\n max_size = 2240\n elif most_level == 2:\n max_size = 1920\n elif most_level == 5:\n max_size = 1280\n return max_size","code_tokens":"","url":501631} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"event_accumulator.py","full_name":"EventAccumulator.Audio","func_name":"Audio","docstring":"Given a summary tag, return all associated audio.","docstring_tokens":"","code":"def Audio(self, tag):\n \"\"\"Given a summary tag, return all associated audio.\n\n Args:\n tag: A string tag associated with the events.\n\n Raises:\n KeyError: If the tag is not found.\n\n Returns:\n An array of `AudioEvent`s.\n \"\"\"\n return self._audio.Items(tag)","code_tokens":"","url":183195} +{"project_name":"hsd1503\/resnet1d","file_name":"util.py","full_name":"read_data_generated","func_name":"read_data_generated","docstring":"Generated data This generated data contains one noise channel class, plus unlimited number of sine channel classes which are different on frequency.","docstring_tokens":"","code":"def read_data_generated(n_samples, n_length, n_channel, n_classes, verbose=False):\n \"\"\"\n Generated data\n \n This generated data contains one noise channel class, plus unlimited number of sine channel classes which are different on frequency. \n \n \"\"\"\n all_X = []\n all_Y = []\n X_noise = np.random.rand(n_samples, n_channel, n_length)\n Y_noise = np.array([0] * n_samples)\n all_X.append(X_noise)\n all_Y.append(Y_noise)\n x = np.arange(n_length)\n for i_class in range(n_classes - 1):\n scale = 2 ** i_class\n offset_list = 2 * np.pi * np.random.rand(n_samples)\n X_sin = []\n for i_sample in range(n_samples):\n tmp_x = []\n for i_channel in range(n_channel):\n tmp_x.append(np.sin(x \/ scale + 2 * np.pi * np.random.rand()))\n X_sin.append(tmp_x)\n X_sin = np.array(X_sin)\n Y_sin = np.array([i_class + 1] * n_samples)\n all_X.append(X_sin)\n all_Y.append(Y_sin)\n all_X = np.concatenate(all_X)\n all_Y = np.concatenate(all_Y)\n shuffle_idx = np.random.permutation(all_Y.shape[0])\n all_X = all_X[shuffle_idx]\n all_Y = all_Y[shuffle_idx]\n if verbose:\n for _ in np.random.permutation(all_Y.shape[0])[:10]:\n fig = plt.figure()\n plt.plot(all_X[_, 0, :])\n plt.title('Label: {0}'.format(all_Y[_]))\n return (all_X, all_Y)","code_tokens":"","url":840537} +{"project_name":"instadeepai\/Mava","file_name":"logger_tools.py","full_name":"should_log","func_name":"should_log","docstring":"Check if the logger should log.","docstring_tokens":"","code":"def should_log(config: Dict) -> bool:\n \"\"\"Check if the logger should log.\"\"\"\n return bool(config['use_sacred'] or config['use_tf'] or config['use_neptune'])","code_tokens":"","url":209887} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"ops.py","full_name":"Output.device","func_name":"device","docstring":"The name of the device on which this tensor will be produced, or None.","docstring_tokens":"","code":"@property\ndef device(self):\n \"\"\"The name of the device on which this tensor will be produced, or None.\"\"\"\n return self._op.device","code_tokens":"","url":182556} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"augments.py","full_name":"Augments.translate_x_rel","func_name":"translate_x_rel","docstring":"Apply translate_x_rel for an given image.","docstring_tokens":"","code":"@staticmethod\ndef translate_x_rel(img: PILImage, pct: float, *args, **kwargs) -> PILImage:\n \"\"\"Apply translate_x_rel for an given image.\"\"\"\n kwargs = Augments._check_args_tf(kwargs)\n pixels = pct * img.size[0]\n return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)","code_tokens":"","url":917900} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"app.py","full_name":"buffer_has_focus","func_name":"buffer_has_focus","docstring":"Enabled when the currently focused control is a `BufferControl`.","docstring_tokens":"","code":"@Condition\ndef buffer_has_focus():\n \"\"\"\n Enabled when the currently focused control is a `BufferControl`.\n \"\"\"\n return get_app().layout.buffer_has_focus","code_tokens":"","url":45152} +{"project_name":"bytedance\/DeepSolid","file_name":"layers_and_loss_tags.py","full_name":"dense_tagging","func_name":"dense_tagging","docstring":"Correctly registers a dense layer pattern.","docstring_tokens":"","code":"def dense_tagging(jaxpr, inverse_map, values_map):\n \"\"\"Correctly registers a dense layer pattern.\"\"\"\n del inverse_map\n in_values = [values_map[v] for v in jaxpr.invars]\n out_values = [values_map[v] for v in jaxpr.outvars]\n return register_dense(out_values[0], *in_values)","code_tokens":"","url":539916} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"backend_bases.py","full_name":"_Backend.new_figure_manager_given_figure","func_name":"new_figure_manager_given_figure","docstring":"Create a new figure manager instance for the given figure.","docstring_tokens":"","code":"@classmethod\ndef new_figure_manager_given_figure(cls, num, figure):\n \"\"\"Create a new figure manager instance for the given figure.\n \"\"\"\n canvas = cls.FigureCanvas(figure)\n manager = cls.FigureManager(canvas, num)\n return manager","code_tokens":"","url":282} +{"project_name":"AlexGeControl\/Artificial-Intelligence-01-Graph-Search-02-Pacman","file_name":"dictconfig.py","full_name":"DictConfigurator.configure_handler","func_name":"configure_handler","docstring":"Configure a handler from a dictionary.","docstring_tokens":"","code":"def configure_handler(self, config):\n \"\"\"Configure a handler from a dictionary.\"\"\"\n formatter = config.pop('formatter', None)\n if formatter:\n try:\n formatter = self.config['formatters'][formatter]\n except StandardError as e:\n raise ValueError('Unable to set formatter %r: %s' % (formatter, e))\n level = config.pop('level', None)\n filters = config.pop('filters', None)\n if '()' in config:\n c = config.pop('()')\n if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and (type(c) != types.ClassType):\n c = self.resolve(c)\n factory = c\n else:\n klass = self.resolve(config.pop('class'))\n if issubclass(klass, logging.handlers.MemoryHandler) and 'target' in config:\n try:\n config['target'] = self.config['handlers'][config['target']]\n except StandardError as e:\n raise ValueError('Unable to set target handler %r: %s' % (config['target'], e))\n elif issubclass(klass, logging.handlers.SMTPHandler) and 'mailhost' in config:\n config['mailhost'] = self.as_tuple(config['mailhost'])\n elif issubclass(klass, logging.handlers.SysLogHandler) and 'address' in config:\n config['address'] = self.as_tuple(config['address'])\n factory = klass\n kwargs = dict(((k, config[k]) for k in config if valid_ident(k)))\n try:\n result = factory(**kwargs)\n except TypeError as te:\n if \"'stream'\" not in str(te):\n raise\n kwargs['strm'] = kwargs.pop('stream')\n result = factory(**kwargs)\n if formatter:\n result.setFormatter(formatter)\n if level is not None:\n result.setLevel(_checkLevel(level))\n if filters:\n self.add_filters(result, filters)\n return result","code_tokens":"","url":35007} +{"project_name":"aisingapore\/PeekingDuck","file_name":"darknet.py","full_name":"CSPDarknet.make_group_layer","func_name":"make_group_layer","docstring":"Starts with BaseConv layer, followed by a CSPLayer.","docstring_tokens":"","code":"@staticmethod\ndef make_group_layer(in_channels: int, depth: int) -> Tuple[BaseConv, CSPLayer]:\n \"\"\"Starts with BaseConv layer, followed by a CSPLayer.\n\n Args:\n in_channels (int): Number of channels in the input image.\n depth (int): Number of Bottlenecks.\n\n Returns:\n (Tuple[BaseConv, CSPLayer]): A group layer consisting of a BaseConv\n CSPLayer.\n \"\"\"\n return (BaseConv(in_channels, in_channels * 2, 3, 2), CSPLayer(in_channels * 2, in_channels * 2, depth))","code_tokens":"","url":767089} +{"project_name":"deepmind\/acme","file_name":"builder.py","full_name":"IMPALABuilder.make_replay_tables","func_name":"make_replay_tables","docstring":"The queue; use XData or INFO log.","docstring_tokens":"","code":"def make_replay_tables(self, environment_spec: specs.EnvironmentSpec, policy: acting.ImpalaPolicy) -> List[reverb.Table]:\n \"\"\"The queue; use XData or INFO log.\"\"\"\n dummy_actor_state = policy.init(jax.random.PRNGKey(0))\n signature = reverb_adders.SequenceAdder.signature(environment_spec, policy.get_extras(dummy_actor_state), sequence_length=self._config.sequence_length)\n samples_per_insert = self._config.samples_per_insert\n if samples_per_insert:\n if samples_per_insert > 1.0 or samples_per_insert <= 0.0:\n raise ValueError(f'Impala requires a samples_per_insert ratio in the range (0, 1], but received {samples_per_insert}.')\n limiter = reverb.rate_limiters.SampleToInsertRatio(samples_per_insert=samples_per_insert, min_size_to_sample=1, error_buffer=self._config.batch_size)\n else:\n limiter = reverb.rate_limiters.MinSize(1)\n table_extensions = []\n if self._table_extension is not None:\n table_extensions = [self._table_extension()]\n queue = reverb.Table(name=self._config.replay_table_name, sampler=reverb.selectors.Uniform(), remover=reverb.selectors.Fifo(), max_size=self._config.max_queue_size, max_times_sampled=1, rate_limiter=limiter, extensions=table_extensions, signature=signature)\n return [queue]","code_tokens":"","url":7570} +{"project_name":"autonomousvision\/differentiable_volumetric_rendering","file_name":"fields.py","full_name":"IndexField.check_complete","func_name":"check_complete","docstring":"Check if field is complete.","docstring_tokens":"","code":"def check_complete(self, files):\n \"\"\" Check if field is complete.\n\n Args:\n files: files\n \"\"\"\n return True","code_tokens":"","url":185013} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"__init__.py","full_name":"Entry.index","func_name":"index","docstring":"Return position of cursor.","docstring_tokens":"","code":"def index(self, index):\n \"\"\"Return position of cursor.\"\"\"\n return self.tk.getint(self.tk.call(self._w, 'index', index))","code_tokens":"","url":284257} +{"project_name":"chenbinghui1\/DSL","file_name":"test_assigner.py","full_name":"test_random_assign_result","func_name":"test_random_assign_result","docstring":"Test random instantiation of assign result to catch corner cases.","docstring_tokens":"","code":"def test_random_assign_result():\n \"\"\"Test random instantiation of assign result to catch corner cases.\"\"\"\n from mmdet.core.bbox.assigners.assign_result import AssignResult\n AssignResult.random()\n AssignResult.random(num_gts=0, num_preds=0)\n AssignResult.random(num_gts=0, num_preds=3)\n AssignResult.random(num_gts=3, num_preds=3)\n AssignResult.random(num_gts=0, num_preds=3)\n AssignResult.random(num_gts=7, num_preds=7)\n AssignResult.random(num_gts=7, num_preds=64)\n AssignResult.random(num_gts=24, num_preds=3)","code_tokens":"","url":168041} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"lightning_models.py","full_name":"ScalarLightning.logits_to_posterior","func_name":"logits_to_posterior","docstring":"Apply the model-specific normalization to go from logits (model outputs) to posteriors.","docstring_tokens":"","code":"def logits_to_posterior(self, logits: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Apply the model-specific normalization to go from logits (model outputs) to posteriors.\n \"\"\"\n return self.logits_to_posterior_fn(logits)","code_tokens":"","url":612944} +{"project_name":"tensorly\/quantum","file_name":"op_deserializer_test.py","full_name":"OpDeserializerTest.test_from_proto_required_missing","func_name":"test_from_proto_required_missing","docstring":"Test error raised when required is missing.","docstring_tokens":"","code":"def test_from_proto_required_missing(self):\n \"\"\"Test error raised when required is missing.\"\"\"\n deserializer = op_deserializer.GateOpDeserializer(serialized_gate_id='my_gate', gate_constructor=GateWithAttribute, args=[op_deserializer.DeserializingArg(serialized_name='my_val', constructor_arg_name='val')])\n serialized = op_proto({'gate': {'id': 'my_gate'}, 'args': {'not_my_val': {'arg_value': {'float_value': 0.125}}}, 'qubits': [{'id': '1_2'}]})\n with self.assertRaisesRegex(Exception, expected_regex='my_val'):\n deserializer.from_proto(serialized)","code_tokens":"","url":834881} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"compiler.py","full_name":"CodeGenerator.temporary_identifier","func_name":"temporary_identifier","docstring":"Get a new unique identifier.","docstring_tokens":"","code":"def temporary_identifier(self):\n \"\"\"Get a new unique identifier.\"\"\"\n self._last_identifier += 1\n return 't_%d' % self._last_identifier","code_tokens":"","url":39167} +{"project_name":"BerkeleyLearnVerify\/VerifAI","file_name":"util.py","full_name":"sparse_to_dense","func_name":"sparse_to_dense","docstring":"Build a dense matrix from sparse representations.","docstring_tokens":"","code":"def sparse_to_dense(sp_indices, output_shape, values, default_value=0):\n \"\"\"Build a dense matrix from sparse representations.\n\n Args:\n sp_indices: A [0-2]-D array that contains the index to place values.\n shape: shape of the dense matrix.\n values: A {0,1}-D array where values corresponds to the index in each row of\n sp_indices.\n default_value: values to set for indices not specified in sp_indices.\n Return:\n A dense numpy N-D array with shape output_shape.\n \"\"\"\n assert len(sp_indices) == len(values), 'Length of sp_indices is not equal to length of values'\n array = np.ones(output_shape) * default_value\n for (idx, value) in zip(sp_indices, values):\n array[tuple(idx)] = value\n return array","code_tokens":"","url":379360} +{"project_name":"google\/deepvariant","file_name":"tf_test_utils.py","full_name":"check_equals_checkpoint_top_scopes","func_name":"check_equals_checkpoint_top_scopes","docstring":"Returns true if list_of_scopes equals the top scopes in checkpoint.","docstring_tokens":"","code":"def check_equals_checkpoint_top_scopes(checkpoint, list_of_scopes):\n \"\"\"Returns true if list_of_scopes equals the top scopes in checkpoint.\"\"\"\n reader = tf.compat.v1.train.NewCheckpointReader(checkpoint)\n var_to_shape_map = reader.get_variable_to_shape_map()\n top_scopes_in_ckpt = set([x.split('\/')[0] for x in var_to_shape_map.keys()])\n return top_scopes_in_ckpt == set(list_of_scopes)","code_tokens":"","url":540509} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"pfor.py","full_name":"PFor.loop_var","func_name":"loop_var","docstring":"Returns placeholder loop variable.","docstring_tokens":"","code":"@property\ndef loop_var(self):\n \"\"\"Returns placeholder loop variable.\"\"\"\n return self._loop_var","code_tokens":"","url":339338} +{"project_name":"sentinel-hub\/eo-learn","file_name":"graph.py","full_name":"DirectedGraph.get_vertices","func_name":"get_vertices","docstring":"Returns the set of vertices of the graph.","docstring_tokens":"","code":"def get_vertices(self) -> set[T]:\n \"\"\"Returns the set of vertices of the graph.\"\"\"\n return set(self._vertices)","code_tokens":"","url":562583} +{"project_name":"lektor\/lektor-archive","file_name":"datamodel.py","full_name":"PaginationConfig.match_pagination","func_name":"match_pagination","docstring":"Matches the pagination from the URL path.","docstring_tokens":"","code":"def match_pagination(self, record, url_path):\n \"\"\"Matches the pagination from the URL path.\"\"\"\n if not self.enabled:\n return\n suffixes = self.url_suffix.strip('\/').split('\/')\n if url_path[:len(suffixes)] != suffixes:\n return\n try:\n page_num = int(url_path[len(suffixes)])\n except (ValueError, IndexError):\n return\n if page_num == 1 or len(url_path) != len(suffixes) + 1:\n return\n rv = self.get_record_for_page(record, page_num)\n if rv.pagination.items.first() is not None:\n return rv","code_tokens":"","url":216364} +{"project_name":"open-mmlab\/mmsegmentation","file_name":"set_env.py","full_name":"register_all_modules","func_name":"register_all_modules","docstring":"Register all modules in mmseg into the registries.","docstring_tokens":"","code":"def register_all_modules(init_default_scope: bool=True) -> None:\n \"\"\"Register all modules in mmseg into the registries.\n\n Args:\n init_default_scope (bool): Whether initialize the mmseg default scope.\n When `init_default_scope=True`, the global default scope will be\n set to `mmseg`, and all registries will build modules from mmseg's\n registry node. To understand more about the registry, please refer\n to https:\/\/github.com\/open-mmlab\/mmengine\/blob\/main\/docs\/en\/tutorials\/registry.md\n Defaults to True.\n \"\"\"\n import mmseg.datasets\n import mmseg.engine\n import mmseg.evaluation\n import mmseg.models\n import mmseg.structures\n if init_default_scope:\n never_created = DefaultScope.get_current_instance() is None or not DefaultScope.check_instance_created('mmseg')\n if never_created:\n DefaultScope.get_instance('mmseg', scope_name='mmseg')\n return\n current_scope = DefaultScope.get_current_instance()\n if current_scope.scope_name != 'mmseg':\n warnings.warn(f'The current default scope \"{current_scope.scope_name}\" is not \"mmseg\", `register_all_modules` will force the currentdefault scope to be \"mmseg\". If this is not expected, please set `init_default_scope=False`.')\n new_instance_name = f'mmseg-{datetime.datetime.now()}'\n DefaultScope.get_instance(new_instance_name, scope_name='mmseg')","code_tokens":"","url":625526} +{"project_name":"muhanzhang\/D-VAE","file_name":"test_scan_opt.py","full_name":"TestPushOutScanOutputDot.test_dot_not_output","func_name":"test_dot_not_output","docstring":"Test the case where the vector input to the dot is not already an output of the inner function.","docstring_tokens":"","code":"def test_dot_not_output(self):\n \"\"\"\n Test the case where the vector input to the dot is not already an\n output of the inner function.\n \"\"\"\n v = T.vector()\n m = T.matrix()\n output = T.dot(v, m)\n opt_mode = mode.including('scan')\n f_opt = theano.function([v, m], T.jacobian(output, v), mode=opt_mode)\n no_opt_mode = mode.excluding('scanOp_pushout_output')\n f_no_opt = theano.function([v, m], T.jacobian(output, v), mode=no_opt_mode)\n scan_node = [node for node in f_opt.maker.fgraph.toposort() if isinstance(node.op, Scan)][0]\n assert len(scan_node.op.outputs) == 1\n assert not isinstance(scan_node.op.outputs[0], T.Dot)\n v_value = numpy.random.random(4).astype(config.floatX)\n m_value = numpy.random.random((4, 5)).astype(config.floatX)\n output_opt = f_opt(v_value, m_value)\n output_no_opt = f_no_opt(v_value, m_value)\n utt.assert_allclose(output_opt, output_no_opt)","code_tokens":"","url":525306} +{"project_name":"google-research\/scenic","file_name":"test_box_utils.py","full_name":"IoUTest.test_box_iou","func_name":"test_box_iou","docstring":"Test box_iou using hand designed targets.","docstring_tokens":"","code":"def test_box_iou(self):\n \"\"\"Test box_iou using hand designed targets.\"\"\"\n in1 = jnp.array([[[0.1, 0.2, 0.3, 0.4], [0.1, 0.2, 0.5, 1.0], [0.1, 0.2, 0.5, 0.8]], [[0.6, 0.2, 1.0, 1.0], [0.6, 0.2, 1.0, 0.8], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.2, 0.1, 0.2, 0.1], [0.1, 0.1, 0.2, 0.2]]], dtype=jnp.float32)\n in2 = jnp.array([[[0.4, 0.4, 0.5, 0.8], [0.4, 0.4, 0.5, 0.8], [0.4, 0.4, 0.7, 0.8]], [[0.7, 0.4, 0.8, 0.6], [0.8, 0.6, 0.7, 0.4], [0.1, 0.1, 0.2, 0.2]], [[0.0, 0.0, 0.0, 0.0], [0.2, 0.1, 0.2, 0.1], [0.1, 0.1, 0.2, 0.2]]], dtype=jnp.float32)\n target = jnp.array([[0.0, 0.125, 0.125], [0.0625, 0.0, 0.0], [0.0, 0.0, 1.0]], dtype=jnp.float32)\n (output, _) = box_utils.box_iou(in1, in2, all_pairs=False)\n self.assertSequenceAlmostEqual(output.flatten(), target.flatten(), places=3)","code_tokens":"","url":846215} +{"project_name":"MushroomRL\/mushroom-rl","file_name":"core.py","full_name":"Core.reset","func_name":"reset","docstring":"Reset the state of the agent.","docstring_tokens":"","code":"def reset(self, initial_states=None):\n \"\"\"\n Reset the state of the agent.\n\n \"\"\"\n if initial_states is None or self._total_episodes_counter == self._n_episodes:\n initial_state = None\n else:\n initial_state = initial_states[self._total_episodes_counter]\n self.agent.episode_start()\n self._state = self._preprocess(self.mdp.reset(initial_state).copy())\n self.agent.next_action = None\n self._episode_steps = 0","code_tokens":"","url":265996} +{"project_name":"PacktPublishing\/Hands-On-Artificial--for-Banking","file_name":"testing.py","full_name":"clean_warning_registry","func_name":"clean_warning_registry","docstring":"Safe way to reset warnings.","docstring_tokens":"","code":"def clean_warning_registry():\n \"\"\"Safe way to reset warnings.\"\"\"\n warnings.resetwarnings()\n reg = '__warningregistry__'\n for (mod_name, mod) in list(sys.modules.items()):\n if 'six.moves' in mod_name:\n continue\n if hasattr(mod, reg):\n getattr(mod, reg).clear()","code_tokens":"","url":204708} +{"project_name":"cpnota\/autonomous-learning-library","file_name":"_vector_environment.py","full_name":"VectorEnvironment.state_array","func_name":"state_array","docstring":"A StateArray of the Environments at the current timestep.","docstring_tokens":"","code":"@property\n@abstractmethod\ndef state_array(self):\n \"\"\"\n A StateArray of the Environments at the current timestep.\n \"\"\"","code_tokens":"","url":93602} +{"project_name":"lbkchen\/deep-learning","file_name":"sdautoencoder.py","full_name":"NNLayer.set_wb","func_name":"set_wb","docstring":"Used during pre-training for convenience.","docstring_tokens":"","code":"def set_wb(self, weights, biases):\n \"\"\"Used during pre-training for convenience.\"\"\"\n self.weights = weights\n self.biases = biases\n print('Set weights of layer with shape', weights.shape)\n print('Set biases of layer with shape', biases.shape)","code_tokens":"","url":518691} +{"project_name":"TalLinzen\/rnn_agreement","file_name":"inflect.py","full_name":"engine.defadj","func_name":"defadj","docstring":"Set the adjective plural of singular to plural.","docstring_tokens":"","code":"def defadj(self, singular, plural):\n \"\"\"\n Set the adjective plural of singular to plural.\n\n \"\"\"\n self.checkpat(singular)\n self.checkpatplural(plural)\n self.pl_adj_user_defined.extend((singular, plural))\n return 1","code_tokens":"","url":325455} +{"project_name":"qobilidop\/srcnn","file_name":"metrics.py","full_name":"psnr","func_name":"psnr","docstring":"Peak signal-to-noise ratio averaged over samples and channels.","docstring_tokens":"","code":"def psnr(y_true, y_pred):\n \"\"\"Peak signal-to-noise ratio averaged over samples and channels.\"\"\"\n mse = K.mean(K.square(y_true - y_pred), axis=(-3, -2))\n return K.mean(20 * K.log(255 \/ K.sqrt(mse)) \/ np.log(10))","code_tokens":"","url":372140} +{"project_name":"jingjingli01\/TGLS","file_name":"hf_api_test.py","full_name":"HfFolderTest.test_token_workflow","func_name":"test_token_workflow","docstring":"Test the whole token save\/get\/delete workflow, with the desired behavior with respect to non-existent tokens.","docstring_tokens":"","code":"def test_token_workflow(self):\n \"\"\"\n Test the whole token save\/get\/delete workflow,\n with the desired behavior with respect to non-existent tokens.\n \"\"\"\n token = 'token-{}'.format(int(time.time()))\n HfFolder.save_token(token)\n self.assertEqual(HfFolder.get_token(), token)\n HfFolder.delete_token()\n HfFolder.delete_token()\n self.assertEqual(HfFolder.get_token(), None)","code_tokens":"","url":354326} +{"project_name":"yzcjtr\/GeoNet","file_name":"png.py","full_name":"Writer.convert_ppm_and_pgm","func_name":"convert_ppm_and_pgm","docstring":"Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object.","docstring_tokens":"","code":"def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile):\n \"\"\"\n Convert a PPM and PGM file containing raw pixel data into a\n PNG outfile with the parameters set in the writer object.\n \"\"\"\n pixels = array('B')\n pixels.fromfile(ppmfile, self.bitdepth \/ 8 * self.color_planes * self.width * self.height)\n apixels = array('B')\n apixels.fromfile(pgmfile, self.bitdepth \/ 8 * self.width * self.height)\n pixels = interleave_planes(pixels, apixels, self.bitdepth \/ 8 * self.color_planes, self.bitdepth \/ 8)\n if self.interlace:\n self.write_passes(outfile, self.array_scanlines_interlace(pixels))\n else:\n self.write_passes(outfile, self.array_scanlines(pixels))","code_tokens":"","url":202388} +{"project_name":"google\/deepvariant","file_name":"ranges.py","full_name":"RangeSet.from_bed","func_name":"from_bed","docstring":"Creates a RangeSet containing the intervals from source.","docstring_tokens":"","code":"@classmethod\ndef from_bed(cls, source, contigs=None):\n \"\"\"Creates a RangeSet containing the intervals from source.\n\n Args:\n source: A path to a BED (or equivalent) file of intervals.\n contigs: An optional list of ContigInfo proto, used by RangeSet\n constructor.\n\n Returns:\n A RangeSet.\n \"\"\"\n return cls(bed_parser(source), contigs)","code_tokens":"","url":540663} +{"project_name":"openai\/gym","file_name":"vector_list_info.py","full_name":"VectorListInfo.reset","func_name":"reset","docstring":"Resets the environment using kwargs.","docstring_tokens":"","code":"def reset(self, **kwargs):\n \"\"\"Resets the environment using kwargs.\"\"\"\n (obs, infos) = self.env.reset(**kwargs)\n list_info = self._convert_info_to_list(infos)\n return (obs, list_info)","code_tokens":"","url":234339} +{"project_name":"tencent-ailab\/TriNet","file_name":"data_cfg.py","full_name":"S2TDataConfig.use_sample_rate","func_name":"use_sample_rate","docstring":"Needed by the dataset loader to see if the model requires raw audio with specific sample rate as inputs.","docstring_tokens":"","code":"@property\ndef use_sample_rate(self):\n \"\"\"Needed by the dataset loader to see if the model requires\n raw audio with specific sample rate as inputs.\"\"\"\n return self.config.get('use_sample_rate', 16000)","code_tokens":"","url":425191} +{"project_name":"jialeli1\/lidarseg3d","file_name":"semanticwaymo_decoder.py","full_name":"extract_points_and_seglabels","func_name":"extract_points_and_seglabels","docstring":"Extract point clouds from ALL_LIDAR and seglabels from the annotated TOP_LIDAR.","docstring_tokens":"","code":"def extract_points_and_seglabels(lasers, laser_calibrations, frame_pose, return_camera_proj=False):\n \"\"\"Extract point clouds from ALL_LIDAR and seglabels from the annotated TOP_LIDAR.\"\"\"\n sort_lambda = lambda x: x.name\n lasers_with_calibration = zip(sorted(lasers, key=sort_lambda), sorted(laser_calibrations, key=sort_lambda))\n points_xyz = []\n points_feature = []\n points_nlz = []\n points_seglabel = []\n if return_camera_proj:\n points_cp = []\n for (laser, calibration) in lasers_with_calibration:\n (points_list, points_seglabel_list, points_cp_list) = extract_points_and_seglabels_from_range_image(laser, calibration, frame_pose, return_camera_proj)\n if laser.name == dataset_pb2.LaserName.TOP:\n num_points_of_top_lidar = {'ri_return1': points_list[0].shape[0], 'ri_return2': points_list[1].shape[0]}\n points = np.concatenate(points_list, axis=0)\n points_xyz.extend(points[..., :3].astype(np.float32))\n points_feature.extend(points[..., 3:5].astype(np.float32))\n points_nlz.extend(points[..., 5].astype(np.float32))\n seglabel = np.concatenate(points_seglabel_list, axis=0)\n points_seglabel.extend(seglabel.astype(np.int32))\n if laser.name == dataset_pb2.LaserName.TOP and seglabel.shape[0] > 0:\n assert points.shape[0] == seglabel.shape[0], 'for TOP lidar, points: {} and seglabel: {} do not match'.format(points.shape, seglabel.shape)\n if return_camera_proj:\n cp = np.concatenate(points_cp_list, axis=0)\n points_cp.extend(cp.astype(np.int32))\n lidar_dict = {'points_xyz': np.asarray(points_xyz), 'points_feature': np.asarray(points_feature), 'num_points_of_top_lidar': num_points_of_top_lidar}\n if return_camera_proj:\n lidar_dict['points_cp'] = np.asarray(points_cp)\n seglabel_dict = {'points_seglabel': np.asarray(points_seglabel).reshape(-1, 2)}\n return (lidar_dict, seglabel_dict)","code_tokens":"","url":601477} +{"project_name":"EPFL-VILAB\/MultiMAE","file_name":"multimae.py","full_name":"MultiMAE.make_mask","func_name":"make_mask","docstring":"Creates masks for each task, given lists of un-masked x,y coordinates.","docstring_tokens":"","code":"@staticmethod\ndef make_mask(N_H, N_W, xy_idxs, full_tasks=[], indicate_visible=True, flatten=True, device='cuda'):\n \"\"\"\n Creates masks for each task, given lists of un-masked x,y coordinates.\n \"\"\"\n xy_idxs = {k: torch.LongTensor(v) for (k, v) in xy_idxs.items()}\n task_masks = {k: torch.ones(N_H, N_W).to(device) for k in xy_idxs.keys()}\n for k in xy_idxs.keys():\n if len(xy_idxs[k]) > 0:\n task_masks[k][xy_idxs[k][:, 1], xy_idxs[k][:, 0]] = 0\n for task in full_tasks:\n task_masks[task][:] = 0\n if not indicate_visible:\n task_masks = {k: 1 - v for (k, v) in task_masks.items()}\n if flatten:\n task_masks = {k: v.flatten().unsqueeze(0) for (k, v) in task_masks.items()}\n return task_masks","code_tokens":"","url":643646} +{"project_name":"meowoodie\/Reinforcement-Learning-of-Spatio-Temporal-Point-Processes","file_name":"ppgmle.py","full_name":"MLE_Hawkes_Generator.train","func_name":"train","docstring":"train the point process generator given expert sequences.","docstring_tokens":"","code":"def train(self, sess, epoches, expert_seqs, pretrained=False):\n \"\"\"train the point process generator given expert sequences.\"\"\"\n if not pretrained:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n print('[%s] parameters are initialized.' % arrow.now(), file=sys.stderr)\n n_data = expert_seqs.shape[0]\n n_batches = int(n_data \/ batch_size)\n all_train_cost = []\n for epoch in range(epoches):\n shuffled_ids = np.arange(n_data)\n np.random.shuffle(shuffled_ids)\n avg_train_cost = []\n for b in range(n_batches):\n idx = np.arange(batch_size * b, batch_size * (b + 1))\n batch_train_ids = shuffled_ids[idx]\n batch_train_seqs = expert_seqs[batch_train_ids, :, :]\n sess.run(self.optimizer, feed_dict={self.input_seqs: batch_train_seqs})\n train_cost = sess.run(self.cost, feed_dict={self.input_seqs: batch_train_seqs})\n print('[%s] batch training cost: %.2f.' % (arrow.now(), train_cost), file=sys.stderr)\n avg_train_cost.append(train_cost)\n all_train_cost.append(train_cost)\n avg_train_cost = np.mean(avg_train_cost)\n print('[%s] Epoch %d (n_train_batches=%d, batch_size=%d)' % (arrow.now(), epoch, n_batches, batch_size), file=sys.stderr)\n print('[%s] Training cost:\\t%f' % (arrow.now(), avg_train_cost), file=sys.stderr)\n np.savetxt('results\/robbery_mle_train_cost.txt', all_train_cost, delimiter=',')","code_tokens":"","url":833491} +{"project_name":"rudranil723\/mini-main","file_name":"ogrinfo.py","full_name":"ogrinfo","func_name":"ogrinfo","docstring":"Walk the available layers in the supplied `data_source`, displaying the fields for the first `num_features` features.","docstring_tokens":"","code":"def ogrinfo(data_source, num_features=10):\n \"\"\"\n Walk the available layers in the supplied `data_source`, displaying\n the fields for the first `num_features` features.\n \"\"\"\n if isinstance(data_source, str):\n data_source = DataSource(data_source)\n elif isinstance(data_source, DataSource):\n pass\n else:\n raise Exception('Data source parameter must be a string or a DataSource object.')\n for (i, layer) in enumerate(data_source):\n print('data source : %s' % data_source.name)\n print('==== layer %s' % i)\n print(' shape type: %s' % GEO_CLASSES[layer.geom_type.num].__name__)\n print(' # features: %s' % len(layer))\n print(' srs: %s' % layer.srs)\n extent_tup = layer.extent.tuple\n print(' extent: %s - %s' % (extent_tup[0:2], extent_tup[2:4]))\n print('Displaying the first %s features ====' % num_features)\n width = max(*map(len, layer.fields))\n fmt = ' %%%ss: %%s' % width\n for (j, feature) in enumerate(layer[:num_features]):\n print('=== Feature %s' % j)\n for fld_name in layer.fields:\n type_name = feature[fld_name].type_name\n output = fmt % (fld_name, type_name)\n val = feature.get(fld_name)\n if val:\n if isinstance(val, str):\n val_fmt = ' (\"%s\")'\n else:\n val_fmt = ' (%s)'\n output += val_fmt % val\n else:\n output += ' (None)'\n print(output)","code_tokens":"","url":315394} +{"project_name":"facebookresearch\/deep_bisim4control","file_name":"quadruped.py","full_name":"Physics.origin_distance","func_name":"origin_distance","docstring":"Returns the distance from the origin to the workspace.","docstring_tokens":"","code":"def origin_distance(self):\n \"\"\"Returns the distance from the origin to the workspace.\"\"\"\n return np.asarray(np.linalg.norm(self.named.data.site_xpos['workspace']))","code_tokens":"","url":536441} +{"project_name":"david8862\/tf-keras-deeplabv3p-model-set","file_name":"layers.py","full_name":"DeeplabConv2D","func_name":"DeeplabConv2D","docstring":"Wrapper to set Deeplab parameters for Conv2D.","docstring_tokens":"","code":"@wraps(Conv2D)\ndef DeeplabConv2D(*args, **kwargs):\n \"\"\"Wrapper to set Deeplab parameters for Conv2D.\"\"\"\n deeplab_conv_kwargs = {'kernel_regularizer': l2(L2_FACTOR)}\n deeplab_conv_kwargs['bias_regularizer'] = l2(L2_FACTOR)\n deeplab_conv_kwargs.update(kwargs)\n return Conv2D(*args, **deeplab_conv_kwargs)","code_tokens":"","url":914164} +{"project_name":"david-abel\/simple_rl","file_name":"QLearningAgentClass.py","full_name":"QLearningAgent.print_v_func","func_name":"print_v_func","docstring":"Summary: Prints the V function.","docstring_tokens":"","code":"def print_v_func(self):\n \"\"\"\n Summary:\n Prints the V function.\n \"\"\"\n for state in self.q_func.keys():\n print(state, self.get_value(state))","code_tokens":"","url":350714} +{"project_name":"intel\/neural-compressor","file_name":"post_hostconst_converter.py","full_name":"PostHostConstConverter.do_transformation","func_name":"do_transformation","docstring":"Convert Const to HostConst as default.","docstring_tokens":"","code":"@dump_elapsed_time('Pass PostHostConstConverter')\ndef do_transformation(self):\n \"\"\"Convert Const to HostConst as default.\"\"\"\n if os.environ.get('DISABLE_HOSTCONST') == '1':\n return self.model\n output_graph_def = graph_pb2.GraphDef()\n for node in self.model.node:\n new_node = node_def_pb2.NodeDef()\n new_node.CopyFrom(node)\n new_node.device = ''\n if node.op == 'Const' and node.attr['dtype'].type in [1, 3] and (node.name.endswith('_min') or node.name.endswith('_max') or node.name.endswith('_max_only') or node.name.endswith('_min_only')):\n new_node.op = 'HostConst'\n output_graph_def.node.extend([new_node])\n return output_graph_def","code_tokens":"","url":737731} +{"project_name":"aisingapore\/PeekingDuck","file_name":"utils.py","full_name":"Stats.prepare_data","func_name":"prepare_data","docstring":"Does the necessary data preparation during node initialisation.","docstring_tokens":"","code":"def prepare_data(self, all_funcs: Dict[str, Union[str, None]]) -> Tuple[str, List[str]]:\n \"\"\"\n Does the necessary data preparation during node initialisation.\n\n Args:\n - all_funcs (Dict[str, Union[str, None]]): Dictionary of : .\n\n Returns:\n - self.data_type (str): PeekingDuck in-built data type or custom data type from custom\n nodes.\n - self.keys (List[str]): List of selected keys if self.data_type is a dictionary.\n If not, returns an empty list.\n \"\"\"\n (self.func, self.expr) = _get_func_expr(all_funcs)\n self._update_data_type_keys_condition()\n return (self.data_type, self.keys)","code_tokens":"","url":766833} +{"project_name":"pyRiemann\/pyRiemann","file_name":"test_embedding.py","full_name":"test_barycenter_weights","func_name":"test_barycenter_weights","docstring":"Test barycenter_weights helper function.","docstring_tokens":"","code":"def test_barycenter_weights(get_covmats):\n \"\"\"Test barycenter_weights helper function.\"\"\"\n (n_matrices, n_channels) = (4, 3)\n covmats = get_covmats(n_matrices, n_channels)\n weights = barycenter_weights(covmats, covmats, np.array([[1, 2], [2, 3], [3, 0], [0, 1]]))\n assert weights.shape == (n_matrices, 2)","code_tokens":"","url":809325} +{"project_name":"thu-ml\/tianshou","file_name":"random.py","full_name":"RandomPolicy.learn","func_name":"learn","docstring":"Since a random agent learns nothing, it returns an empty dict.","docstring_tokens":"","code":"def learn(self, batch: RolloutBatchProtocol, *args: Any, **kwargs: Any) -> dict[str, float]:\n \"\"\"Since a random agent learns nothing, it returns an empty dict.\"\"\"\n return {}","code_tokens":"","url":355255} +{"project_name":"caiostringari\/deepwaves","file_name":"interpret.py","full_name":"GradCAM.compute_heatmap","func_name":"compute_heatmap","docstring":"Compute a heatmap with the class activation.","docstring_tokens":"","code":"def compute_heatmap(self, image, classIdx, eps=1e-08):\n \"\"\"Compute a heatmap with the class activation.\"\"\"\n with tf.GradientTape() as tape:\n tape.watch(self.gradModel.get_layer(self.layerName).output)\n inputs = tf.cast(image, tf.float32)\n (convOutputs, predictions) = self.gradModel(inputs)\n if len(predictions) == 1:\n loss = predictions[0]\n else:\n loss = predictions[:, classIdx]\n grads = tape.gradient(loss, convOutputs)\n castConvOutputs = tf.cast(convOutputs > 0, 'float32')\n castGrads = tf.cast(grads > 0, 'float32')\n guidedGrads = castConvOutputs * castGrads * grads\n convOutputs = convOutputs[0]\n guidedGrads = guidedGrads[0]\n weights = tf.reduce_mean(guidedGrads, axis=(0, 1))\n cam = tf.reduce_sum(tf.multiply(weights, convOutputs), axis=-1)\n (w, h) = (image.shape[2], image.shape[1])\n heatmap = cv2.resize(cam.numpy(), (w, h))\n numer = heatmap - np.min(heatmap)\n denom = heatmap.max() - heatmap.min() + eps\n heatmap = numer \/ denom\n heatmap = (heatmap * 255).astype('uint8')\n return heatmap","code_tokens":"","url":540962} +{"project_name":"triaquae\/triaquae","file_name":"testcases.py","full_name":"LiveServerThread.run","func_name":"run","docstring":"Sets up the live server and databases, and then loops over handling http requests.","docstring_tokens":"","code":"def run(self):\n \"\"\"\n Sets up the live server and databases, and then loops over handling\n http requests.\n \"\"\"\n if self.connections_override:\n from django.db import connections\n for (alias, conn) in self.connections_override.items():\n connections[alias] = conn\n try:\n handler = StaticFilesHandler(_MediaFilesHandler(WSGIHandler()))\n for (index, port) in enumerate(self.possible_ports):\n try:\n self.httpd = StoppableWSGIServer((self.host, port), QuietWSGIRequestHandler)\n except WSGIServerException as e:\n if index + 1 < len(self.possible_ports) and hasattr(e.args[0], 'errno') and (e.args[0].errno == errno.EADDRINUSE):\n continue\n else:\n raise\n else:\n self.port = port\n break\n self.httpd.set_app(handler)\n self.is_ready.set()\n self.httpd.serve_forever()\n except Exception as e:\n self.error = e\n self.is_ready.set()","code_tokens":"","url":423970} +{"project_name":"PKU-Alignment\/safe-rlhf","file_name":"utils.py","full_name":"to_device","func_name":"to_device","docstring":"Move a batch of tensors to a device.","docstring_tokens":"","code":"def to_device(batch: TensorTree, device: torch.device | str | int | None) -> TensorTree:\n \"\"\"Move a batch of tensors to a device.\"\"\"\n if not __PYTREE_INITIALIZED:\n __initialize_pytree_registry_once()\n if device is None:\n return batch\n return optree.tree_map(lambda x: x.to(device), batch, namespace='safe_rlhf')","code_tokens":"","url":829122} +{"project_name":"sktime\/sktime","file_name":"test_all_transformers.py","full_name":"TestAllTransformers.test_fit_transform_output","func_name":"test_fit_transform_output","docstring":"Test that transform output is of expected scitype.","docstring_tokens":"","code":"def test_fit_transform_output(self, estimator_instance, scenario):\n \"\"\"Test that transform output is of expected scitype.\"\"\"\n X = scenario.args['transform']['X']\n Xt = scenario.run(estimator_instance, method_sequence=['fit', 'transform'])\n X_scitype = scenario.get_tag('X_scitype')\n trafo_input = estimator_instance.get_tag('scitype:transform-input')\n trafo_output = estimator_instance.get_tag('scitype:transform-output')\n (valid_X_scitype, _, X_metadata) = check_is_scitype(X, scitype=X_scitype, return_metadata=True)\n msg = f'error with scenario {type(scenario).__name__}, X_scitype tag was \"{X_scitype}\", but check_is_scitype does not confirm this'\n assert valid_X_scitype, msg\n Xt_expected_scitype = self._expected_trafo_output_scitype(X_scitype, trafo_input, trafo_output)\n (valid_scitype, _, Xt_metadata) = check_is_scitype(Xt, scitype=Xt_expected_scitype, return_metadata=True)\n msg = f'{type(estimator_instance).__name__}.transform should return an object of scitype {Xt_expected_scitype} when given an input of scitype {X_scitype}, but found the following return: {Xt}'\n assert valid_scitype, msg\n Xt_scitype = Xt_expected_scitype\n if type(estimator_instance).__name__ in ['Aggregator', 'Reconciler']:\n return None\n if hasattr(Xt, 'columns'):\n msg = f'{type(estimator_instance).__name__}.transform return should have unique column indices, but found {Xt.columns}'\n assert Xt.columns.is_unique, msg\n if trafo_input == 'Series' and trafo_output == 'Series':\n if X_scitype == 'Series' and Xt_scitype == 'Series':\n if estimator_instance.get_tag('transform-returns-same-time-index'):\n assert X.shape[0] == Xt.shape[0]\n if X_scitype == 'Panel' and Xt_scitype == 'Panel':\n assert X_metadata['n_instances'] == Xt_metadata['n_instances']\n if X_scitype == 'Hierarchical' and Xt_scitype == 'Hierarchical':\n assert X_metadata['n_instances'] == Xt_metadata['n_instances']\n if trafo_input == 'Panel' and trafo_output == 'Panel':\n if X_scitype == 'Hierarchical' and Xt_scitype == 'Hierarchical':\n assert X_metadata['n_panels'] == Xt_metadata['n_panels']\n if trafo_input == 'Series' and trafo_output == 'Primitives':\n if X_scitype == 'Series':\n assert Xt_metadata['n_instances'] == 1\n if X_scitype == 'Panel':\n assert X_metadata['n_instances'] == Xt_metadata['n_instances']","code_tokens":"","url":877932} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"mailbox.py","full_name":"_mboxMMDFMessage.set_from","func_name":"set_from","docstring":"Set \"From \" line, formatting and appending time_ if specified.","docstring_tokens":"","code":"def set_from(self, from_, time_=None):\n \"\"\"Set \"From \" line, formatting and appending time_ if specified.\"\"\"\n if time_ is not None:\n if time_ is True:\n time_ = time.gmtime()\n from_ += ' ' + time.asctime(time_)\n self._from = from_","code_tokens":"","url":280782} +{"project_name":"cometsong\/MA-GenTA","file_name":"targeted_probe_design.py","full_name":"export_final_sets","func_name":"export_final_sets","docstring":"Export final sets of (possibly random) probe sequences into fasta format; one file for 'musicc', one for non.","docstring_tokens":"","code":"def export_final_sets(dbname, cluster_id, final_probe_amount=1, randomly=True):\n \"\"\"Export final sets of (possibly random) probe sequences into fasta format;\n one file for 'musicc', one for non.\n \"\"\"\n log.info(f'Exporting probes for {cluster_id}')\n working_dir = APath(CONFIG.get('paths').get('working_dir'))\n final_amount = int(final_probe_amount) or int(CONFIG.get('general').get('final_probe_amount'))\n random_picks = randomly or CONFIG.get('general').get('final_probe_random')\n filter_view = DB_CFG.get('probes_view').get('name')\n 'final_fields taken from config\/database\/probes_view_cols last words (post-space)'\n final_fields = [col.split(' ')[-1] for col in DB_CFG.get('probes_view').get('cols').copy()]\n for (which, where) in (('normal', '0'), ('musicc', '1')):\n export_bits = '.'.join([cluster_id, 'probes', 'final', which, 'fasta'])\n export_file = working_dir \/ export_bits\n whim = 'is_musicc=' + where\n record_count = Sdb.iter_select(dbname, filter_view, where=whim, fields='count(*) as recs')\n record_count = next(record_count).pop('recs')\n log.debug(f' ... record_count: {record_count}')\n if record_count == 0:\n log.notice(f'No filtered \"{which}\" probes for cluster \"{cluster_id}\".')\n write_out_file('', export_file, mode='a')\n next\n if random_picks:\n final_amount = final_amount if record_count >= final_amount else record_count\n row_nums = random.sample(range(record_count), k=final_amount)\n else:\n row_nums = [r for r in range(final_amount)]\n log.debug(f' ... row_nums: {row_nums}')\n probes_selector = Sdb.iter_select(dbname, filter_view, where=whim, fields=final_fields)\n log.info(f'Exporting to file {export_file}')\n for row in [row for (num, row) in enumerate(probes_selector) if num in row_nums]:\n seq = row.pop('probe_seq')\n head = '>' + '|'.join([str(v) for v in row.values()])\n probe_fasta = os.linesep.join([head, seq, ''])\n log.debug(f' ... writing to file {export_file}: \"{probe_fasta}\"')\n write_out_file(probe_fasta, export_file, mode='a')","code_tokens":"","url":620115} +{"project_name":"nlp-uoregon\/trankit","file_name":"seq2seq_vocabs.py","full_name":"BaseMultiVocab.state_dict","func_name":"state_dict","docstring":"Build a state dict by iteratively calling state_dict() of all vocabs.","docstring_tokens":"","code":"def state_dict(self):\n \"\"\" Build a state dict by iteratively calling state_dict() of all vocabs. \"\"\"\n state = OrderedDict()\n for (k, v) in self._vocabs.items():\n state[k] = v.state_dict()\n return state","code_tokens":"","url":920491} +{"project_name":"facebookresearch\/CompilerGym","file_name":"minimize_trajectory_test.py","full_name":"make_hypothesis","func_name":"make_hypothesis","docstring":"Create a hypothesis that checks if `val` is in actions.","docstring_tokens":"","code":"def make_hypothesis(val: int):\n \"\"\"Create a hypothesis that checks if `val` is in actions.\"\"\"\n\n def hypothesis(env):\n print('hypothesis?()', env.actions, val in env.actions, file=sys.stderr)\n return val in env.actions\n return hypothesis","code_tokens":"","url":125999} +{"project_name":"accel-brain\/accel-brain-code","file_name":"adaptive_simulated_annealing.py","full_name":"AdaptiveSimulatedAnnealing.adaptive_set","func_name":"adaptive_set","docstring":"Init for Adaptive Simulated Annealing.","docstring_tokens":"","code":"def adaptive_set(self, reannealing_per=50, thermostat=0.9, t_min=0.001, t_default=1.0):\n \"\"\"\n Init for Adaptive Simulated Annealing.\n \n Args:\n reannealing_per: How often will this model reanneals there per cycles.\n thermostat: Thermostat.\n t_min: The minimum temperature.\n t_default: The default temperature.\n \"\"\"\n self.__reannealing_per = reannealing_per\n self.__thermostat = thermostat\n self.__t_min = t_min\n self.__t_default = t_default","code_tokens":"","url":7258} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"cloud_mlengine.py","full_name":"launch","func_name":"launch","docstring":"Launch t2t_trainer on Cloud ML Engine.","docstring_tokens":"","code":"def launch():\n \"\"\"Launch t2t_trainer on Cloud ML Engine.\"\"\"\n validate_flags()\n job_spec = configure_job()\n job_name = job_spec['jobId']\n tf.logging.info('Launching job %s with ML Engine spec:\\n%s', job_name, job_spec)\n assert confirm()\n train_dir = FLAGS.output_dir\n t2t_tar = tar_and_copy_t2t(train_dir)\n configure_trainer_package(job_spec, t2t_tar)\n if FLAGS.t2t_usr_dir:\n usr_tar = tar_and_copy_usr_dir(FLAGS.t2t_usr_dir, train_dir)\n configure_usr_dir(job_spec, usr_tar)\n launch_job(job_spec)\n tf.logging.info('Launched %s. See console to track: %s.', job_name, CONSOLE_URL)","code_tokens":"","url":966065} +{"project_name":"RasaHQ\/rasa_core","file_name":"utils.py","full_name":"read_lines","func_name":"read_lines","docstring":"Read messages from the command line and print bot responses.","docstring_tokens":"","code":"def read_lines(filename, max_line_limit=None, line_pattern='.*'):\n \"\"\"Read messages from the command line and print bot responses.\"\"\"\n line_filter = re.compile(line_pattern)\n with open(filename, 'r', encoding='utf-8') as f:\n num_messages = 0\n for line in f:\n m = line_filter.match(line)\n if m is not None:\n yield m.group(1 if m.lastindex else 0)\n num_messages += 1\n if is_limit_reached(num_messages, max_line_limit):\n break","code_tokens":"","url":838282} +{"project_name":"MycroftAI\/mycroft-core","file_name":"api.py","full_name":"EnclosureAPI.system_mute","func_name":"system_mute","docstring":"Mute (turn off) the system speaker.","docstring_tokens":"","code":"def system_mute(self):\n \"\"\"Mute (turn off) the system speaker.\"\"\"\n self.bus.emit(Message('enclosure.system.mute', context={'destination': ['enclosure']}))","code_tokens":"","url":290347} +{"project_name":"deepmind\/acme","file_name":"delayed_reward.py","full_name":"DelayedRewardWrapper.step","func_name":"step","docstring":"Performs one step and maybe returns a reward.","docstring_tokens":"","code":"def step(self, action: types.NestedArray) -> dm_env.TimeStep:\n \"\"\"Performs one step and maybe returns a reward.\"\"\"\n timestep = self.environment.step(action)\n self._delayed_reward = tree.map_structure(operator.iadd, self._delayed_reward, timestep.reward)\n self._accumulation_counter += 1\n if self._accumuation_period is not None and self._accumulation_counter == self._accumuation_period or timestep.last():\n timestep = timestep._replace(reward=self._delayed_reward)\n self._accumulation_counter = 0\n self._delayed_reward = self._zero_reward\n else:\n timestep = timestep._replace(reward=self._zero_reward)\n return timestep","code_tokens":"","url":7943} +{"project_name":"Trusted-AI\/adversarial-robustness-toolbox","file_name":"conftest.py","full_name":"image_batch","func_name":"image_batch","docstring":"Image fixtures of shape NHWC and NCHW and a sample object detection label.","docstring_tokens":"","code":"@pytest.fixture()\ndef image_batch(channels_first):\n \"\"\"\n Image fixtures of shape NHWC and NCHW and a sample object detection label.\n \"\"\"\n channels = 3\n height = 20\n width = 16\n if channels_first:\n data_shape = (2, channels, height, width)\n else:\n data_shape = (2, height, width, channels)\n x = (0.5 * np.ones(data_shape)).astype(ART_NUMPY_DTYPE)\n y = []\n for _ in range(len(x)):\n (y_1, x_1) = np.random.uniform(0, (height \/ 2, width \/ 2))\n (y_2, x_2) = np.random.uniform((y_1 + 3, x_1 + 3), (height, width))\n target_dict = {'boxes': np.array([[x_1, y_1, x_2, y_2]]), 'labels': np.array([0])}\n y.append(target_dict)\n return (x, y)","code_tokens":"","url":398532} +{"project_name":"huawei-noah\/xingtian","file_name":"evaluate_adapter.py","full_name":"EvalResultSummary.append","func_name":"append","docstring":"Append eval results to buf.","docstring_tokens":"","code":"def append(self, eval_results):\n \"\"\"Append eval results to buf.\"\"\"\n if not eval_results:\n return\n for _result in eval_results:\n self._buf[_result['eval_name']] = _result\n (train_id, eval_id) = str(_result['eval_name']).split('@')\n self._info[train_id].add(eval_id)","code_tokens":"","url":962203} +{"project_name":"greydanus\/mr_london","file_name":"pildriver.py","full_name":"PILDriver.do_sharpness","func_name":"do_sharpness","docstring":"usage: sharpness Enhance sharpness in the top image.","docstring_tokens":"","code":"def do_sharpness(self):\n \"\"\"usage: sharpness \n\n Enhance sharpness in the top image.\n \"\"\"\n from PIL import ImageEnhance\n factor = float(self.do_pop())\n image = self.do_pop()\n enhancer = ImageEnhance.Sharpness(image)\n self.push(enhancer.enhance(factor))","code_tokens":"","url":241771} +{"project_name":"PytLab\/simpleflow","file_name":"operations.py","full_name":"Constant.compute_output","func_name":"compute_output","docstring":"Compute and return the constant value.","docstring_tokens":"","code":"def compute_output(self):\n \"\"\" Compute and return the constant value.\n \"\"\"\n if self.output_value is None:\n self.output_value = self.value\n return self.output_value","code_tokens":"","url":350694} +{"project_name":"IntelAI\/transfer-learning","file_name":"list.py","full_name":"list_models","func_name":"list_models","docstring":"List the supported models and the information that we have about each model from the config files.","docstring_tokens":"","code":"@list_group.command('models', help='List the available models')\n@click.option('--framework', '-f', required=False, help='Filter the list of models by framework.')\n@click.option('--use-case', '--use_case', required=False, help='Filter the list of models to a single use case')\n@click.option('--verbose', 'verbose', flag_value=True, default=False, help='Verbose output with extra information about each model')\n@click.option('--markdown', flag_value=True, default=False, hidden=True, help='Display the results as markdown. Not compatible with --verbose.')\ndef list_models(framework, use_case, verbose, markdown):\n \"\"\"\n List the supported models and the information that we have about each model from the config files.\n \"\"\"\n from tlt.models.model_factory import print_supported_models\n try:\n print_supported_models(framework, use_case, verbose, markdown)\n except Exception as e:\n sys.exit('Error while listing the supported models for framework: {}, use case: {}\\n {}'.format(str(framework), str(use_case), str(e)))","code_tokens":"","url":928615} +{"project_name":"georghess\/voxel-mae","file_name":"waymo_converter.py","full_name":"Waymo2KITTI.create_folder","func_name":"create_folder","docstring":"Create folder for data preprocessing.","docstring_tokens":"","code":"def create_folder(self):\n \"\"\"Create folder for data preprocessing.\"\"\"\n if not self.test_mode:\n dir_list1 = [self.label_all_save_dir, self.calib_save_dir, self.point_cloud_save_dir, self.pose_save_dir]\n dir_list2 = [self.label_save_dir, self.image_save_dir]\n else:\n dir_list1 = [self.calib_save_dir, self.point_cloud_save_dir, self.pose_save_dir]\n dir_list2 = [self.image_save_dir]\n for d in dir_list1:\n mmcv.mkdir_or_exist(d)\n for d in dir_list2:\n for i in range(5):\n mmcv.mkdir_or_exist(f'{d}{str(i)}')","code_tokens":"","url":380838} +{"project_name":"mideind\/GreynirServer","file_name":"geo.py","full_name":"parse_address_string","func_name":"parse_address_string","docstring":"Break Icelandic address string down to its components.","docstring_tokens":"","code":"def parse_address_string(addrstr: str) -> Dict[str, Any]:\n \"\"\"Break Icelandic address string down to its components.\"\"\"\n addr: Dict[str, Any] = {'street': addrstr}\n comp = addrstr.split()\n if len(comp) == 1:\n return addr\n last = comp[-1]\n r = re.search('^(\\\\d+)([a-zA-Z]?)$', last)\n if r:\n addr['number'] = int(r.group(1))\n addr['letter'] = r.group(2) or ''\n addr['street'] = ' '.join(comp[:-1])\n return addr","code_tokens":"","url":580957} +{"project_name":"edwardlib\/observations","file_name":"psid.py","full_name":"psid","func_name":"psid","docstring":"Panel Survey of Income Dynamics a cross-section from 1993 *number of observations* : 4856 *observation* : individuals *country* : United States A dataframe containing : intnum 1968 interview number persnum person number age age of individual educatn highest grade completed earnings total labor income hours annual work hours kids live births to this individual married last known marital status (married, never married, windowed, divorced, separated, NA\/DF, no histories) Panel Survey of Income Dynamics.","docstring_tokens":"","code":"def psid(path):\n \"\"\"Panel Survey of Income Dynamics\n\n a cross-section from 1993\n\n *number of observations* : 4856\n\n *observation* : individuals\n\n *country* : United States\n\n A dataframe containing :\n\n intnum\n 1968 interview number\n\n persnum\n person number\n\n age\n age of individual\n\n educatn\n highest grade completed\n\n earnings\n total labor income\n\n hours\n annual work hours\n\n kids\n live births to this individual\n\n married\n last known marital status (married, never married, windowed,\n divorced, separated, NA\/DF, no histories)\n\n Panel Survey of Income Dynamics.\n\n Args:\n\n path: str.\n Path to directory which either stores file or otherwise file will\n be downloaded and extracted there.\n Filename is `psid.csv`.\n\n Returns:\n\n Tuple of np.ndarray `x_train` with 4856 rows and 8 columns and\n dictionary `metadata` of column headers (feature names).\n \"\"\"\n import pandas as pd\n path = os.path.expanduser(path)\n filename = 'psid.csv'\n if not os.path.exists(os.path.join(path, filename)):\n url = 'http:\/\/dustintran.com\/data\/r\/Ecdat\/PSID.csv'\n maybe_download_and_extract(path, url, save_file_name='psid.csv', resume=False)\n data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True)\n x_train = data.values\n metadata = {'columns': data.columns}\n return (x_train, metadata)","code_tokens":"","url":740567} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"face.py","full_name":"ResponseReceiver.complete","func_name":"complete","docstring":"Receives the completion values emitted from the service-side of the RPC.","docstring_tokens":"","code":"@abc.abstractmethod\ndef complete(self, terminal_metadata, code, details):\n \"\"\"Receives the completion values emitted from the service-side of the RPC.\n\n Args:\n terminal_metadata: The terminal metadata object emitted from the\n service-side of the RPC.\n code: The code object emitted from the service-side of the RPC.\n details: The details object emitted from the service-side of the RPC.\n \"\"\"\n raise NotImplementedError()","code_tokens":"","url":215693} +{"project_name":"onnx\/onnx","file_name":"op_col2im.py","full_name":"col2im_naive_implementation","func_name":"col2im_naive_implementation","docstring":"Naive implementation for `col2im`.","docstring_tokens":"","code":"def col2im_naive_implementation(data, image_shape, kernel_shape, dilations, pads, strides):\n \"\"\"\n Naive implementation for `col2im`.\n \"\"\"\n n_dims = len(pads) \/\/ 2\n new_pads = np.array([(pads[i], pads[i + n_dims]) for i in range(n_dims)])\n _col2im_shape_check(data, image_shape, kernel_shape, dilations, new_pads, strides)\n data_col = data\n data_im = np.zeros(image_shape, dtype=data.dtype)\n dim_col = []\n for i in range(n_dims):\n col = (image_shape[i] + new_pads[i, :].sum() - (dilations[i] * (kernel_shape[i] - 1) + 1)) \/\/ strides[i] + 1\n dim_col.append(col)\n kernel_size = np.prod(kernel_shape)\n col_size = np.prod(dim_col)\n for c_col in range(kernel_size):\n offset = _get_indices(c_col, kernel_shape)\n for col in range(col_size):\n ind_col = _get_indices(col, dim_col)\n ind_im = []\n for i in range(n_dims):\n ind = ind_col[i] * strides[i] - new_pads[i, 0] + offset[i] * dilations[i]\n ind_im.append(ind)\n if not _is_out(ind_im, data_im.shape):\n data_im[tuple(ind_im)] += data_col[c_col, col]\n return data_im","code_tokens":"","url":756526} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"ttFont.py","full_name":"newTable","func_name":"newTable","docstring":"Return a new instance of a table.","docstring_tokens":"","code":"def newTable(tag):\n \"\"\"Return a new instance of a table.\"\"\"\n tableClass = getTableClass(tag)\n return tableClass(tag)","code_tokens":"","url":361174} +{"project_name":"pytorch\/rl","file_name":"wandb.py","full_name":"WandbLogger.log_hparams","func_name":"log_hparams","docstring":"Logs the hyperparameters of the experiment.","docstring_tokens":"","code":"def log_hparams(self, cfg: Union['DictConfig', Dict]) -> None:\n \"\"\"Logs the hyperparameters of the experiment.\n\n Args:\n cfg (DictConfig or dict): The configuration of the experiment.\n\n \"\"\"\n if type(cfg) is not dict and _has_omegaconf:\n if not _has_omegaconf:\n raise ImportError('OmegaConf could not be imported. Cannot log hydra configs without OmegaConf.')\n from omegaconf import OmegaConf\n cfg = OmegaConf.to_container(cfg, resolve=True)\n self.experiment.config.update(cfg, allow_val_change=True)","code_tokens":"","url":859488} +{"project_name":"anuragranj\/cc","file_name":"inverse_warp.py","full_name":"flow_warp","func_name":"flow_warp","docstring":"Inverse warp a source image to the target image plane.","docstring_tokens":"","code":"def flow_warp(img, flow, padding_mode='zeros'):\n \"\"\"\n Inverse warp a source image to the target image plane.\n\n Args:\n img: the source image (where to sample pixels) -- [B, 3, H, W]\n flow: flow map of the target image -- [B, 2, H, W]\n Returns:\n Source image warped to the target image plane\n \"\"\"\n check_sizes(img, 'img', 'BCHW')\n check_sizes(flow, 'flow', 'B2HW')\n (bs, _, h, w) = flow.size()\n u = flow[:, 0, :, :]\n v = flow[:, 1, :, :]\n grid_x = Variable(torch.arange(0, w).view(1, 1, w).expand(1, h, w), requires_grad=False).type_as(u).expand_as(u)\n grid_y = Variable(torch.arange(0, h).view(1, h, 1).expand(1, h, w), requires_grad=False).type_as(v).expand_as(v)\n X = grid_x + u\n Y = grid_y + v\n X = 2 * (X \/ (w - 1.0) - 0.5)\n Y = 2 * (Y \/ (h - 1.0) - 0.5)\n grid_tf = torch.stack((X, Y), dim=3)\n img_tf = torch.nn.functional.grid_sample(img, grid_tf, padding_mode=padding_mode)\n return img_tf","code_tokens":"","url":103302} +{"project_name":"zhaocq-nlp\/NJUNMT-tf","file_name":"model_builder.py","full_name":"model_fn","func_name":"model_fn","docstring":"Creates NMT model for training, evaluation or inference.","docstring_tokens":"","code":"def model_fn(model_configs, mode, vocab_source, vocab_target, name=None, reuse=None, distributed_mode=False, is_chief=True, verbose=True):\n \"\"\" Creates NMT model for training, evaluation or inference.\n\n Args:\n model_configs: A dictionary of all configurations.\n mode: A mode.\n vocab_source: A `Vocab` for source side.\n vocab_target: A `Vocab` for target side.\n name: A string, the name of top-level of the variable scope.\n reuse: Whether to reuse all variables, the parameter passed\n to `tf.variable_scope()`.\n verbose: Print model parameters if set True.\n distributed_mode: Whether training is on distributed mode.\n is_chief: Whether is the chief worker.\n\n Returns: A `EstimatorSpec` object.\n \"\"\"\n model_str = model_configs['model']\n if model_str is None or model_str == '':\n model_str = 'SequenceToSequence'\n model_name = get_model_top_scope_name(model_str, name)\n if verbose:\n tf.logging.info('Create model: {} for {}'.format(model_str, mode))\n model = eval(model_str)(params=model_configs['model_params'], mode=mode, vocab_source=vocab_source, vocab_target=vocab_target, name=model_name, verbose=verbose)\n parallelism = Parallelism(mode, reuse=reuse)\n if mode == ModeKeys.TRAIN:\n opt = OptimizerWrapper(model_configs['optimizer_params'])\n\n def _build_model():\n if verbose:\n tf.logging.info('Building Model.......')\n _input_fields = eval(model_str).create_input_fields(mode)\n _model_output = model.build(_input_fields)\n if verbose:\n tf.logging.info('Finish Building Model.......')\n if mode == ModeKeys.INFER:\n return (_input_fields, _model_output)\n elif mode == ModeKeys.EVAL:\n return (_input_fields, _model_output[0], _model_output[1])\n elif mode == ModeKeys.TRAIN:\n _loss = _model_output[0] \/ _model_output[1]\n grads = opt.optimizer.compute_gradients(_loss, var_list=tf.trainable_variables(), colocate_gradients_with_ops=True)\n return (_input_fields, _loss, grads)\n else:\n raise NotImplementedError('TODO reranking')\n model_returns = parallelism(_build_model)\n input_fields = model_returns[0]\n if mode == ModeKeys.INFER:\n predictions = model_returns[1]\n return EstimatorSpec(model_name, mode, input_fields=input_fields, predictions=predictions)\n if mode == ModeKeys.EVAL:\n (loss_op, attention) = model_returns[1:]\n return EstimatorSpec(model_name, mode, input_fields=input_fields, loss=loss_op, predictions=attention)\n assert mode == ModeKeys.TRAIN\n (loss_per_dp, grads) = model_returns[1:]\n _add_to_display_collection(input_fields)\n (train_loss, train_ops) = opt.optimize(loss_per_dp, grads, update_cycle=model_configs['train']['update_cycle'])\n tf.add_to_collection(Constants.DISPLAY_KEY_COLLECTION_NAME, Constants.TRAIN_LOSS_KEY_NAME)\n tf.add_to_collection(Constants.DISPLAY_VALUE_COLLECTION_NAME, train_loss)\n hooks = build_hooks(model_configs, distributed_mode=distributed_mode, is_chief=is_chief)\n return EstimatorSpec(name, mode, input_fields=input_fields, loss=train_loss, train_ops=train_ops, training_hooks=hooks, training_chief_hooks=None)","code_tokens":"","url":782886} +{"project_name":"cpnota\/autonomous-learning-library","file_name":"experiment.py","full_name":"Experiment.frame","func_name":"frame","docstring":"The index of the current training frame.","docstring_tokens":"","code":"@property\n@abstractmethod\ndef frame(self):\n \"\"\"The index of the current training frame.\"\"\"","code_tokens":"","url":93610} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjDataWrapper.xmat","func_name":"xmat","docstring":"Cartesian orientation of body frame (nbody x 9).","docstring_tokens":"","code":"@util.CachedProperty\ndef xmat(self):\n \"\"\"Cartesian orientation of body frame (nbody x 9).\"\"\"\n return util.buf_to_npy(self._ptr.contents.xmat, (self._model.nbody, 9))","code_tokens":"","url":440546} +{"project_name":"rudranil723\/mini-main","file_name":"well_known_types.py","full_name":"Timestamp.FromDatetime","func_name":"FromDatetime","docstring":"Converts datetime to Timestamp.","docstring_tokens":"","code":"def FromDatetime(self, dt):\n \"\"\"Converts datetime to Timestamp.\n\n Args:\n dt: A datetime. If it's timezone-naive, it's assumed to be in UTC.\n \"\"\"\n self.seconds = calendar.timegm(dt.utctimetuple())\n self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND","code_tokens":"","url":318466} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"common_shapes.py","full_name":"broadcast_shape","func_name":"broadcast_shape","docstring":"Returns the broadcasted shape between `shape_x` and `shape_y`.","docstring_tokens":"","code":"def broadcast_shape(shape_x, shape_y):\n \"\"\"Returns the broadcasted shape between `shape_x` and `shape_y`.\n\n Args:\n shape_x: A `TensorShape`\n shape_y: A `TensorShape`\n\n Returns:\n A `TensorShape` representing the broadcasted shape.\n\n Raises:\n ValueError: If the two shapes can not be broadcasted.\n \"\"\"\n if shape_x.ndims is None or shape_y.ndims is None:\n return tensor_shape.unknown_shape()\n return_dims = _broadcast_shape_helper(shape_x, shape_y)\n if return_dims is None:\n raise ValueError('Incompatible shapes for broadcasting: %s and %s' % (shape_x, shape_y))\n return tensor_shape.TensorShape(return_dims)","code_tokens":"","url":336256} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"base_model.py","full_name":"Model.eval_metrics","func_name":"eval_metrics","docstring":"Returns tuple of metric function and its inputs for evaluation.","docstring_tokens":"","code":"def eval_metrics(self):\n \"\"\"Returns tuple of metric function and its inputs for evaluation.\"\"\"\n raise NotImplementedError('Unimplemented eval_metrics')","code_tokens":"","url":850950} +{"project_name":"rudranil723\/mini-main","file_name":"chart.py","full_name":"SteppingChartParser.strategy","func_name":"strategy","docstring":"Return the strategy used by this parser.","docstring_tokens":"","code":"def strategy(self):\n \"\"\"Return the strategy used by this parser.\"\"\"\n return self._strategy","code_tokens":"","url":321427} +{"project_name":"googleapis\/python-aiplatform","file_name":"helpers.py","full_name":"wait_for_job_state","func_name":"wait_for_job_state","docstring":"Waits until the Job state of provided resource name is a particular state.","docstring_tokens":"","code":"def wait_for_job_state(get_job_method: Callable[[str], 'proto.Message'], name: str, expected_state: str='CANCELLED', timeout: int=90, freq: float=1.5) -> None:\n \"\"\"Waits until the Job state of provided resource name is a particular state.\n\n Args:\n get_job_method: Callable[[str], \"proto.Message\"]\n Required. The GAPIC getter method to poll. Takes 'name' parameter\n and has a 'state' attribute in its response.\n name (str):\n Required. Complete uCAIP resource name to pass to get_job_method\n expected_state (str):\n The state at which this method will stop waiting.\n Default is \"CANCELLED\".\n timeout (int):\n Maximum number of seconds to wait for expected_state. If the job\n state is not expected_state within timeout, a TimeoutError will be raised.\n Default is 90 seconds.\n freq (float):\n Number of seconds between calls to get_job_method.\n Default is 1.5 seconds.\n \"\"\"\n for _ in range(int(timeout \/ freq)):\n response = get_job_method(name=name)\n if expected_state in str(response.state):\n return None\n time.sleep(freq)\n raise TimeoutError(f'Job state did not become {expected_state} within {timeout} seconds\\nTry increasing the timeout in sample test\\nLast recorded state: {response.state}')","code_tokens":"","url":862923} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_metaestimators_metadata_routing.py","full_name":"test_metadata_is_routed_correctly_to_scorer","func_name":"test_metadata_is_routed_correctly_to_scorer","docstring":"Test that any requested metadata is correctly routed to the underlying scorers in CV estimators.","docstring_tokens":"","code":"@pytest.mark.parametrize('metaestimator', METAESTIMATORS, ids=METAESTIMATOR_IDS)\ndef test_metadata_is_routed_correctly_to_scorer(metaestimator):\n \"\"\"Test that any requested metadata is correctly routed to the underlying\n scorers in CV estimators.\n \"\"\"\n if 'scorer_name' not in metaestimator:\n return\n cls = metaestimator['metaestimator']\n routing_methods = metaestimator['scorer_routing_methods']\n for method_name in routing_methods:\n (kwargs, (estimator, _), (scorer, registry), (cv, _)) = get_init_args(metaestimator)\n if estimator:\n estimator.set_fit_request(sample_weight=True, metadata=True)\n scorer.set_score_request(sample_weight=True)\n if cv:\n cv.set_split_request(groups=True, metadata=True)\n instance = cls(**kwargs)\n method = getattr(instance, method_name)\n method_kwargs = {'sample_weight': sample_weight}\n if 'fit' not in method_name:\n instance.fit(X, y)\n method(X, y, **method_kwargs)\n assert registry\n for _scorer in registry:\n check_recorded_metadata(obj=_scorer, method='score', split_params=('sample_weight',), **method_kwargs)","code_tokens":"","url":854179} +{"project_name":"ifwe\/digsby","file_name":"imwin_ctrl.py","full_name":"ImWinCtrl.on_message_area_shown","func_name":"on_message_area_shown","docstring":"Sets up the MessageStyle for the IM area.","docstring_tokens":"","code":"def on_message_area_shown(self):\n \"\"\"Sets up the MessageStyle for the IM area.\"\"\"\n if hasattr(self, 'message_area') and (not self.message_area.inited):\n if hasattr(self, 'convo'):\n self.init_message_area(self.convo.name, self.convo.buddy, show_history=not self.convo.ischat)\n else:\n self.init_message_area('', None)\n self.input_area.tc.Bind(wx.EVT_TEXT, self.on_text_changed)\n from gui.imwin.imwindnd import ImWinDropTarget\n self.SetDropTarget(ImWinDropTarget(self))","code_tokens":"","url":185394} +{"project_name":"PaddlePaddle\/PARL","file_name":"train.py","full_name":"Learner.run_remote_sample","func_name":"run_remote_sample","docstring":"Sample data from remote actor and update parameters of remote actor.","docstring_tokens":"","code":"def run_remote_sample(self, params_queue):\n \"\"\" Sample data from remote actor and update parameters of remote actor.\n \"\"\"\n remote_actor = Actor(self.config)\n cnt = 0\n while True:\n latest_params = params_queue.get()\n remote_actor.set_weights(latest_params)\n batch = remote_actor.sample()\n self.sample_data_queue.put(batch)\n cnt += 1\n if cnt % self.config['get_remote_metrics_interval'] == 0:\n metrics = remote_actor.get_metrics()\n if metrics:\n self.remote_metrics_queue.put(metrics)","code_tokens":"","url":277581} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"path_model.py","full_name":"PathBasedModel.load_labels","func_name":"load_labels","docstring":"Loads the labels of the current instances.","docstring_tokens":"","code":"def load_labels(self, session, batch_instances):\n \"\"\"Loads the labels of the current instances.\n\n Args:\n session: the current TensorFlow session.\n batch_instances: the dataset instances.\n\n Returns:\n the labels.\n \"\"\"\n return session.run(self.labels_to_load, feed_dict={self.instances_to_load: batch_instances})","code_tokens":"","url":757758} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"test_io_util.py","full_name":"test_load_dicom_image_random","func_name":"test_load_dicom_image_random","docstring":"Test loading of 2D Dicom images of type (uint16) and (int16).","docstring_tokens":"","code":"@pytest.mark.parametrize('is_signed', [True, False])\n@pytest.mark.parametrize('is_monochrome2', [True, False])\n@pytest.mark.parametrize('bits_stored', [14, 16])\ndef test_load_dicom_image_random(test_output_dirs: OutputFolderForTests, is_signed: bool, is_monochrome2: bool, bits_stored: int) -> None:\n \"\"\"\n Test loading of 2D Dicom images of type (uint16) and (int16).\n \"\"\"\n array_size = (20, 30)\n if not is_signed:\n array = np.random.randint(0, 200, size=array_size, dtype='uint16')\n else:\n array = np.random.randint(-200, 200, size=array_size, dtype='int16')\n assert array.shape == array_size\n if is_monochrome2:\n to_write = array\n elif not is_signed:\n to_write = 2 ** bits_stored - 1 - array\n else:\n to_write = -1 * array - 1\n dcm_file = test_output_dirs.root_dir \/ 'file.dcm'\n assert is_dicom_file_path(dcm_file)\n write_test_dicom(array=to_write, path=dcm_file, is_monochrome2=is_monochrome2, bits_stored=bits_stored)\n image = load_dicom_image(dcm_file)\n assert image.ndim == 2 and image.shape == array_size\n assert np.array_equal(image, array)\n image_and_segmentation = load_image_in_known_formats(dcm_file, load_segmentation=False)\n assert image_and_segmentation.images.ndim == 2 and image_and_segmentation.images.shape == array_size\n assert np.array_equal(image_and_segmentation.images, array)","code_tokens":"","url":613795} +{"project_name":"voxel51\/fiftyone","file_name":"collections.py","full_name":"SampleCollection.app_config","func_name":"app_config","docstring":"Dataset-specific settings that customize how this collection is visualized in the :ref:`FiftyOne App `.","docstring_tokens":"","code":"@property\ndef app_config(self):\n \"\"\"Dataset-specific settings that customize how this collection is\n visualized in the :ref:`FiftyOne App `.\n \"\"\"\n raise NotImplementedError('Subclass must implement app_config')","code_tokens":"","url":582722} +{"project_name":"iffiX\/machin","file_name":"conf.py","full_name":"merge_config","func_name":"merge_config","docstring":"Merge config object with a dictionary, or a Config object, same keys in the ``conf`` will be overwritten by keys in ``merge``.","docstring_tokens":"","code":"def merge_config(conf: Config, merge: Union[dict, Config]) -> Config:\n \"\"\"\n Merge config object with a dictionary, or a Config object,\n same keys in the ``conf`` will be overwritten by keys\n in ``merge``.\n \"\"\"\n new_conf = copy.deepcopy(conf)\n if isinstance(merge, dict):\n for (k, v) in merge.items():\n new_conf[k] = v\n else:\n for (k, v) in merge.data.items():\n if k not in new_conf.const_attrs:\n new_conf[k] = v\n return new_conf","code_tokens":"","url":620449} +{"project_name":"rlworkgroup\/garage","file_name":"reps_gym_cartpole.py","full_name":"reps_gym_cartpole","func_name":"reps_gym_cartpole","docstring":"Train REPS with CartPole-v0 environment.","docstring_tokens":"","code":"@wrap_experiment\ndef reps_gym_cartpole(ctxt=None, seed=1):\n \"\"\"Train REPS with CartPole-v0 environment.\n\n Args:\n ctxt (garage.experiment.ExperimentContext): The experiment\n configuration used by Trainer to create the snapshotter.\n seed (int): Used to seed the random number generator to produce\n determinism.\n\n \"\"\"\n set_seed(seed)\n with TFTrainer(snapshot_config=ctxt) as trainer:\n env = GymEnv('CartPole-v0')\n policy = CategoricalMLPPolicy(env_spec=env.spec, hidden_sizes=[32, 32])\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n sampler = RaySampler(agents=policy, envs=env, max_episode_length=env.spec.max_episode_length, is_tf_worker=True)\n algo = REPS(env_spec=env.spec, policy=policy, baseline=baseline, sampler=sampler, discount=0.99)\n trainer.setup(algo, env)\n trainer.train(n_epochs=100, batch_size=4000, plot=False)","code_tokens":"","url":200277} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_encoders.py","full_name":"test_ordinal_encoder_all_frequent","func_name":"test_ordinal_encoder_all_frequent","docstring":"All categories are considered frequent have same encoding as default encoder.","docstring_tokens":"","code":"@pytest.mark.parametrize('kwargs', [{'max_categories': 6}, {'min_frequency': 2}])\ndef test_ordinal_encoder_all_frequent(kwargs):\n \"\"\"All categories are considered frequent have same encoding as default encoder.\"\"\"\n X_train = np.array([['a'] * 5 + ['b'] * 20 + ['c'] * 10 + ['d'] * 3], dtype=object).T\n adjusted_encoder = OrdinalEncoder(**kwargs, handle_unknown='use_encoded_value', unknown_value=-1).fit(X_train)\n default_encoder = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1).fit(X_train)\n X_test = [['a'], ['b'], ['c'], ['d'], ['e']]\n assert_allclose(adjusted_encoder.transform(X_test), default_encoder.transform(X_test))","code_tokens":"","url":854037} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"parser.py","full_name":"_Errors.log_all","func_name":"log_all","docstring":"Log all the collected errors to the standard error.","docstring_tokens":"","code":"def log_all(self):\n \"\"\"Log all the collected errors to the standard error.\"\"\"\n template = 'ERROR:\\n output file name: %s\\n %s\\n\\n'\n for (full_name, message) in self._errors:\n print(template % (full_name, message), file=sys.stderr)","code_tokens":"","url":606733} +{"project_name":"tum-pbs\/PhiFlow","file_name":"fluid.py","full_name":"masked_laplace","func_name":"masked_laplace","docstring":"Computes the laplace of `pressure` in the presence of obstacles.","docstring_tokens":"","code":"@math.jit_compile_linear(auxiliary_args='hard_bcs,active,order,implicit', forget_traces=True)\ndef masked_laplace(pressure: CenteredGrid, hard_bcs: Grid, active: CenteredGrid, order=2, implicit: Solve=None) -> CenteredGrid:\n \"\"\"\n Computes the laplace of `pressure` in the presence of obstacles.\n\n Args:\n pressure: Pressure field.\n hard_bcs: Mask encoding which cells are connected to each other.\n One between fluid cells, zero inside and at the boundary of obstacles.\n This should be of the same type as the velocity, i.e. `StaggeredGrid` or `CenteredGrid`.\n active: Mask indicating for which cells the pressure value is valid.\n Linear solves will only determine the pressure for these cells.\n This is generally zero inside obstacles and in non-simulated regions.\n order: Spatial order of accuracy.\n Higher orders entail larger stencils and more computation time but result in more accurate results assuming a large enough resolution.\n Supported: 2 explicit, 4 explicit, 6 implicit (inherited from `phi.field.laplace()`).\n implicit: When a `Solve` object is passed, performs an implicit operation with the specified solver and tolerances.\n Otherwise, an explicit stencil is used.\n\n Returns:\n `CenteredGrid`\n \"\"\"\n if order == 2 and (not implicit):\n grad = spatial_gradient(pressure, hard_bcs.extrapolation, type=type(hard_bcs))\n valid_grad = grad * hard_bcs\n valid_grad = valid_grad.with_extrapolation(extrapolation.remove_constant_offset(valid_grad.extrapolation))\n div = divergence(valid_grad)\n laplace = where(active, div, pressure)\n else:\n laplace = field.laplace(pressure, order=order, implicit=implicit)\n return laplace","code_tokens":"","url":768879} +{"project_name":"asyml\/texar","file_name":"tfrecord_data_test.py","full_name":"TFRecordDataTest.test_default_setting","func_name":"test_default_setting","docstring":"Tests the logics of TFRecordData.","docstring_tokens":"","code":"def test_default_setting(self):\n \"\"\"Tests the logics of TFRecordData.\n \"\"\"\n self._run_and_test(self._hparams)","code_tokens":"","url":924339} +{"project_name":"kubeflow\/pipelines","file_name":"types.py","full_name":"verify_type_compatibility","func_name":"verify_type_compatibility","docstring":"verify_type_compatibility verifies that the given argument type is compatible with the expected input type.","docstring_tokens":"","code":"def verify_type_compatibility(given_type: TypeSpecType, expected_type: TypeSpecType, error_message_prefix: str=''):\n \"\"\"verify_type_compatibility verifies that the given argument type is\n compatible with the expected input type.\n\n Args:\n given_type (str\/dict): The type of the argument passed to the\n input\n expected_type (str\/dict): The declared type of the input\n \"\"\"\n if given_type is None or expected_type is None:\n return True\n if not type_utils.is_parameter_type(str(expected_type)) and str(given_type).lower() == 'artifact':\n return True\n if not type_utils.is_parameter_type(str(given_type)) and str(expected_type).lower() == 'artifact':\n return True\n types_are_compatible = check_types(given_type, expected_type)\n if not types_are_compatible:\n error_text = error_message_prefix + 'Argument type \"{}\" is incompatible with the input type \"{}\"'.format(str(given_type), str(expected_type))\n import kfp.deprecated as kfp\n if kfp.TYPE_CHECK:\n raise InconsistentTypeException(error_text)\n else:\n warnings.warn(InconsistentTypeWarning(error_text))\n return types_are_compatible","code_tokens":"","url":780098} +{"project_name":"enuguru\/artificial_intelligence_and_machine_","file_name":"server.py","full_name":"AssociateRequest.answerUnsupported","func_name":"answerUnsupported","docstring":"Respond to this request indicating that the association type or association session type is not supported.","docstring_tokens":"","code":"def answerUnsupported(self, message, preferred_association_type=None, preferred_session_type=None):\n \"\"\"Respond to this request indicating that the association\n type or association session type is not supported.\"\"\"\n if self.message.isOpenID1():\n raise ProtocolError(self.message)\n response = OpenIDResponse(self)\n response.fields.setArg(OPENID_NS, 'error_code', 'unsupported-type')\n response.fields.setArg(OPENID_NS, 'error', message)\n if preferred_association_type:\n response.fields.setArg(OPENID_NS, 'assoc_type', preferred_association_type)\n if preferred_session_type:\n response.fields.setArg(OPENID_NS, 'session_type', preferred_session_type)\n return response","code_tokens":"","url":130301} +{"project_name":"shubhomoydas\/ad_examples","file_name":"iso_gan.py","full_name":"GAN.init_ano_gan","func_name":"init_ano_gan","docstring":"Prepare variables required for AnoGAN functionality # Note: AnoGAN functionality will come in use only *after* the # GAN (simple|conditional|InfoGAN) has been fully trained.","docstring_tokens":"","code":"def init_ano_gan(self):\n \"\"\" Prepare variables required for AnoGAN functionality\n\n # Note: AnoGAN functionality will come in use only *after* the\n # GAN (simple|conditional|InfoGAN) has been fully trained.\n \"\"\"\n self.ano_gan_lambda = tf.placeholder(tf.float32, shape=(), name='ano_gan_lambda')\n self.ano_z = tf.Variable(initial_value=tf.zeros([1, self.gen_input_dim]), trainable=True, name='ano_z')\n with tf.variable_scope('GAN', reuse=True):\n (self.ano_gan_net_G, self.ano_gan_net_D) = self.init_ano_gan_network(x=self.x, y=self.y, z=self.ano_z)\n (ano_gan_G, ano_gan_D, ano_gan_D_features) = self.ano_gan_outputs()\n self.ano_gan_loss_R = tf.reduce_sum(tf.abs(tf.subtract(self.x, ano_gan_G)))\n self.ano_gan_loss_D = tf.reduce_sum(-tf.log(tf.nn.sigmoid(ano_gan_D)))\n self.ano_gan_info_loss = tf.constant(0.0)\n if self.info_gan:\n with tf.variable_scope('InfoGAN'):\n self.ano_gan_q_network = self.init_info_gan_network(ano_gan_D_features, reuse=True)\n self.ano_gan_info_loss = self.marginal_mutual_info(get_nn_layer(self.ano_gan_q_network, layer_from_top=1), self.pvals)\n self.ano_gan_loss = (1 - self.ano_gan_lambda) * self.ano_gan_loss_R + self.ano_gan_lambda * (self.ano_gan_loss_D + self.ano_gan_info_loss)\n self.ano_gan_training_op = self.training_op(self.ano_gan_loss, var_list=[self.ano_z], use_adam=self.use_adam)","code_tokens":"","url":398858} +{"project_name":"scikit-multiflow\/scikit-multiflow","file_name":"data_structures.py","full_name":"ConfusionMatrix.shape","func_name":"shape","docstring":"shape Returns ------- tuple The confusion matrix's shape.","docstring_tokens":"","code":"def shape(self):\n \"\"\" shape\n\n Returns\n -------\n tuple\n The confusion matrix's shape.\n\n \"\"\"\n return self.confusion_matrix.shape","code_tokens":"","url":854965} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"utils.py","full_name":"ids_to_strings","func_name":"ids_to_strings","docstring":"Converts ID's in the `config_dict` to their string representation.","docstring_tokens":"","code":"def ids_to_strings(config_dict: dict) -> dict:\n \"\"\"Converts ID's in the `config_dict` to their string representation.\n\n Args:\n config_dict: Dictionary in which to replace the ID's by strings\n\n Returns:\n Updated config_dict dictionary\n \"\"\"\n for (key, value) in config_dict.items():\n if isinstance(value, ID):\n config_dict[key] = str(value)\n return config_dict","code_tokens":"","url":918448} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"state_space_model.py","full_name":"StateSpaceModel.get_start_state","func_name":"get_start_state","docstring":"Defines and returns a non-batched prior state and covariance.","docstring_tokens":"","code":"def get_start_state(self):\n \"\"\"Defines and returns a non-batched prior state and covariance.\"\"\"\n if self._input_statistics is not None:\n start_time = self._input_statistics.start_time\n else:\n start_time = array_ops.zeros([], dtype=dtypes.int64)\n return (self.prior_state_mean, self.prior_state_var, start_time - 1)","code_tokens":"","url":335476} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"figure.py","full_name":"Figure.get_frameon","func_name":"get_frameon","docstring":"Return whether the figure frame will be drawn.","docstring_tokens":"","code":"def get_frameon(self):\n \"\"\"Return whether the figure frame will be drawn.\"\"\"\n return self.frameon","code_tokens":"","url":504} +{"project_name":"RasaHQ\/rasa_core","file_name":"keras_policy.py","full_name":"KerasPolicy.continue_training","func_name":"continue_training","docstring":"Continues training an already trained policy.","docstring_tokens":"","code":"def continue_training(self, training_trackers: List[DialogueStateTracker], domain: Domain, **kwargs: Any) -> None:\n \"\"\"Continues training an already trained policy.\"\"\"\n batch_size = kwargs.get('batch_size', 5)\n epochs = kwargs.get('epochs', 50)\n with self.graph.as_default(), self.session.as_default():\n for _ in range(epochs):\n training_data = self._training_data_for_continue_training(batch_size, training_trackers, domain)\n self.model.fit(training_data.X, training_data.y, epochs=self.current_epoch + 1, batch_size=len(training_data.y), verbose=0, initial_epoch=self.current_epoch)\n self.current_epoch += 1","code_tokens":"","url":838335} +{"project_name":"irdanish11\/Seq2Seq-UrduChatBot","file_name":"vocabulary_importer_factory.py","full_name":"get_vocabulary_importer","func_name":"get_vocabulary_importer","docstring":"Gets the appropriate importer implementation for the specified vocabulary name.","docstring_tokens":"","code":"def get_vocabulary_importer(vocabulary_dir):\n \"\"\"Gets the appropriate importer implementation for the specified vocabulary name.\n\n Args:\n vocabulary_dir: The directory of the vocabulary to get a importer implementation for.\n \"\"\"\n vocabulary_name = path.basename(vocabulary_dir)\n importers = [Word2vecWikipediaVocabularyImporter(), NnlmEnVocabularyImporter(), DependencyBasedVocabularyImporter()]\n for importer in importers:\n if importer.vocabulary_name == vocabulary_name:\n return importer\n raise ValueError(\"There is no vocabulary importer implementation for '{0}'. If this is a new vocabulary, please add one!\".format(vocabulary_name))","code_tokens":"","url":876490} +{"project_name":"catlab-team\/latentclr","file_name":"util.py","full_name":"Logger.flush","func_name":"flush","docstring":"Flush written text to both stdout and a file, if open.","docstring_tokens":"","code":"def flush(self) -> None:\n \"\"\"Flush written text to both stdout and a file, if open.\"\"\"\n if self.file is not None:\n self.file.flush()\n self.stdout.flush()","code_tokens":"","url":261952} +{"project_name":"RasaHQ\/rasa","file_name":"memoization.py","full_name":"MemoizationPolicy.load","func_name":"load","docstring":"Loads a trained policy (see parent class for full docstring).","docstring_tokens":"","code":"@classmethod\ndef load(cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, **kwargs: Any) -> MemoizationPolicy:\n \"\"\"Loads a trained policy (see parent class for full docstring).\"\"\"\n featurizer = None\n lookup = None\n try:\n with model_storage.read_from(resource) as path:\n metadata_file = Path(path) \/ cls._metadata_filename()\n metadata = rasa.shared.utils.io.read_json_file(metadata_file)\n lookup = metadata['lookup']\n if (Path(path) \/ FEATURIZER_FILE).is_file():\n featurizer = TrackerFeaturizer.load(path)\n except (ValueError, FileNotFoundError, FileIOException):\n logger.warning(f\"Couldn't load metadata for policy '{cls.__name__}' as the persisted metadata couldn't be loaded.\")\n return cls(config, model_storage, resource, execution_context, featurizer=featurizer, lookup=lookup)","code_tokens":"","url":836937} +{"project_name":"facebookresearch\/CompilerGym","file_name":"llvm_commandline_opt_equivalence_fuzz_test.py","full_name":"test_fuzz","func_name":"test_fuzz","docstring":"This test produces a random trajectory and then uses the commandline generated with opt to check that the states are equivalent.","docstring_tokens":"","code":"@pytest.mark.timeout(600)\ndef test_fuzz(env: LlvmEnv, tmpwd: Path, llvm_opt: Path, llvm_diff: Path):\n \"\"\"This test produces a random trajectory and then uses the commandline\n generated with opt to check that the states are equivalent.\n \"\"\"\n del tmpwd\n env.reset()\n env.write_ir('input.ll')\n assert Path('input.ll').is_file()\n apply_random_trajectory(env, random_trajectory_length_range=RANDOM_TRAJECTORY_LENGTH_RANGE, timeout=30)\n commandline = env.action_space.to_string(env.actions)\n print(env.state)\n env.write_ir('env.ll')\n assert Path('env.ll').is_file()\n subprocess.check_call(commandline, env={'PATH': str(llvm_opt.parent)}, shell=True, timeout=60)\n assert Path('output.ll').is_file()\n os.rename('output.ll', 'opt.ll')\n with Popen([llvm_diff, 'opt.ll', 'env.ll'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) as diff:\n (stdout, stderr) = diff.communicate(timeout=300)\n if diff.returncode:\n pytest.fail(f'Opt produced different output to CompilerGym (returncode: {diff.returncode}):\\n{stdout}\\n{stderr}')","code_tokens":"","url":125870} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"calendar.py","full_name":"HTMLCalendar.formatweek","func_name":"formatweek","docstring":"Return a complete week as a table row.","docstring_tokens":"","code":"def formatweek(self, theweek):\n \"\"\"\n Return a complete week as a table row.\n \"\"\"\n s = ''.join((self.formatday(d, wd) for (d, wd) in theweek))\n return '%s<\/tr>' % s","code_tokens":"","url":280152} +{"project_name":"deepmind\/dm_control","file_name":"walkers.py","full_name":"WalkerInfo.add_marker_sites","func_name":"add_marker_sites","docstring":"Adds sites corresponding to mocap tracking markers.","docstring_tokens":"","code":"def add_marker_sites(self, walker, size=0.01, rgba=(0.0, 0.0, 1.0, 0.3), default_to_random_position=True, random_state=None):\n \"\"\"Adds sites corresponding to mocap tracking markers.\"\"\"\n self.check_walker_is_compatible(walker)\n random_state = random_state or np.random\n sites = []\n if self._proto.markers:\n mocap_class = walker.mjcf_model.default.add('default', dclass='mocap')\n mocap_class.site.set_attributes(type='sphere', size=(size,), rgba=rgba, group=composer.SENSOR_SITES_GROUP)\n for marker_info in self._proto.markers.marker:\n body = walker.mjcf_model.find('body', marker_info.parent)\n if not body:\n raise ValueError('Walker model does not contain a body named {!r}'.format(str(marker_info.parent)))\n pos = marker_info.position\n if not pos:\n if default_to_random_position:\n pos = random_state.uniform(-0.005, 0.005, size=3)\n else:\n pos = np.zeros(3)\n sites.append(body.add('site', name=str(marker_info.name), pos=pos, dclass=mocap_class))\n walker.list_of_site_names = [site.name for site in sites]\n return sites","code_tokens":"","url":165069} +{"project_name":"astooke\/rlpyt","file_name":"cppo_pid.py","full_name":"CppoPID.compute_beta_kl","func_name":"compute_beta_kl","docstring":"Ratio of KL divergences from reward-only vs cost-only updates.","docstring_tokens":"","code":"def compute_beta_kl(self, loss_inputs, init_rnn_state, batch_size, mb_size, T):\n \"\"\"Ratio of KL divergences from reward-only vs cost-only updates.\"\"\"\n self.agent.beta_r_model.load_state_dict(strip_ddp_state_dict(self.agent.model.state_dict()))\n self.agent.beta_c_model.load_state_dict(strip_ddp_state_dict(self.agent.model.state_dict()))\n self.beta_r_optimizer.load_state_dict(self.optimizer.state_dict())\n self.beta_c_optimizer.load_state_dict(self.optimizer.state_dict())\n recurrent = self.agent.recurrent\n for _ in range(self.beta_kl_epochs):\n for idxs in iterate_mb_idxs(batch_size, mb_size, shuffle=batch_size > mb_size):\n T_idxs = slice(None) if recurrent else idxs % T\n B_idxs = idxs if recurrent else idxs \/\/ T\n rnn_state = init_rnn_state[B_idxs] if recurrent else None\n self.beta_r_optimizer.zero_grad()\n self.beta_c_optimizer.zero_grad()\n (beta_r_loss, beta_c_loss) = self.beta_kl_losses(*loss_inputs[T_idxs, B_idxs], rnn_state)\n beta_r_loss.backward()\n _ = torch.nn.utils.clip_grad_norm_(self.agent.beta_r_model.parameters(), self.clip_grad_norm)\n self.beta_r_optimizer.step()\n beta_c_loss.backward()\n _ = torch.nn.utils.clip_grad_norm_(self.agent.beta_c_model.parameters(), self.clip_grad_norm)\n self.beta_c_optimizer.step()\n if init_rnn_state is not None:\n init_rnn_state = buffer_method(init_rnn_state, 'transpose', 0, 1)\n init_rnn_state = buffer_method(init_rnn_state, 'contiguous')\n with torch.no_grad():\n (r_dist_info, c_dist_info) = self.agent.beta_dist_infos(*loss_inputs.agent_inputs, init_rnn_state)\n else:\n with torch.no_grad():\n (r_dist_info, c_dist_info) = self.agent.beta_dist_infos(*loss_inputs.agent_inputs, init_rnn_state)\n dist = self.agent.distribution\n beta_r_KL = dist.mean_kl(new_dist_info=r_dist_info, old_dist_info=loss_inputs.old_dist_info, valid=loss_inputs.valid)\n beta_c_KL = dist.mean_kl(new_dist_info=c_dist_info, old_dist_info=loss_inputs.old_dist_info, valid=loss_inputs.valid)\n if self._ddp:\n beta_KLs = torch.stack([beta_r_KL, beta_c_KL])\n beta_KLs = beta_KLs.to(self.agent.device)\n torch.distributed.all_reduce(beta_KLs)\n beta_KLs = beta_KLs.to('cpu')\n beta_KLs \/= torch.distributed.get_world_size()\n (beta_r_KL, beta_c_KL) = (beta_KLs[0], beta_KLs[1])\n raw_beta_KL = float(beta_r_KL \/ max(beta_c_KL, 1e-08))\n return (raw_beta_KL, float(beta_r_KL), float(beta_c_KL))","code_tokens":"","url":334591} +{"project_name":"chuyangliu\/snake","file_name":"pos.py","full_name":"Pos.direc_to","func_name":"direc_to","docstring":"Return the direction of an adjacent Pos relative to self.","docstring_tokens":"","code":"def direc_to(self, adj_pos):\n \"\"\"Return the direction of an adjacent Pos relative to self.\"\"\"\n if self._x == adj_pos.x:\n diff = self._y - adj_pos.y\n if diff == 1:\n return Direc.LEFT\n if diff == -1:\n return Direc.RIGHT\n elif self._y == adj_pos.y:\n diff = self._x - adj_pos.x\n if diff == 1:\n return Direc.UP\n if diff == -1:\n return Direc.DOWN\n return Direc.NONE","code_tokens":"","url":352198} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"gen_nn_ops.py","full_name":"max_pool3d","func_name":"max_pool3d","docstring":"Performs 3D max pooling on the input.","docstring_tokens":"","code":"@tf_export('nn.max_pool3d')\ndef max_pool3d(input, ksize, strides, padding, data_format='NDHWC', name=None):\n \"\"\"Performs 3D max pooling on the input.\n\n Args:\n input: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`.\n Shape `[batch, depth, rows, cols, channels]` tensor to pool over.\n ksize: A list of `ints` that has length `>= 5`.\n 1-D tensor of length 5. The size of the window for each dimension of\n\n the input tensor. Must have `ksize[0] = ksize[4] = 1`.\n strides: A list of `ints` that has length `>= 5`.\n 1-D tensor of length 5. The stride of the sliding window for each\n\n dimension of `input`. Must have `strides[0] = strides[4] = 1`.\n padding: A `string` from: `\"SAME\", \"VALID\"`.\n The type of padding algorithm to use.\n data_format: An optional `string` from: `\"NDHWC\", \"NCDHW\"`. Defaults to `\"NDHWC\"`.\n The data format of the input and output data. With the\n\n default format \"NDHWC\", the data is stored in the order of:\n\n [batch, in_depth, in_height, in_width, in_channels].\n\n Alternatively, the format could be \"NCDHW\", the data storage order is:\n\n [batch, in_channels, in_depth, in_height, in_width].\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n _ctx = _context._context\n if _ctx is None or not _ctx._eager_context.is_eager:\n if not isinstance(ksize, (list, tuple)):\n raise TypeError(\"Expected list for 'ksize' argument to 'max_pool3d' Op, not %r.\" % ksize)\n ksize = [_execute.make_int(_i, 'ksize') for _i in ksize]\n if not isinstance(strides, (list, tuple)):\n raise TypeError(\"Expected list for 'strides' argument to 'max_pool3d' Op, not %r.\" % strides)\n strides = [_execute.make_int(_i, 'strides') for _i in strides]\n padding = _execute.make_str(padding, 'padding')\n if data_format is None:\n data_format = 'NDHWC'\n data_format = _execute.make_str(data_format, 'data_format')\n (_, _, _op) = _op_def_lib._apply_op_helper('MaxPool3D', input=input, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = ('ksize', _op.get_attr('ksize'), 'strides', _op.get_attr('strides'), 'padding', _op.get_attr('padding'), 'data_format', _op.get_attr('data_format'), 'T', _op.get_attr('T'))\n _execute.record_gradient('MaxPool3D', _inputs_flat, _attrs, _result, name)\n (_result,) = _result\n return _result\n else:\n try:\n _result = _pywrap_tensorflow.TFE_Py_FastPathExecute(_ctx._context_handle, _ctx._eager_context.device_name, 'MaxPool3D', name, _ctx._post_execution_callbacks, input, 'ksize', ksize, 'strides', strides, 'padding', padding, 'data_format', data_format)\n return _result\n except _core._FallbackException:\n return max_pool3d_eager_fallback(input, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name, ctx=_ctx)\n except _core._NotOkStatusException as e:\n if name is not None:\n message = e.message + ' name: ' + name\n else:\n message = e.message\n _six.raise_from(_core._status_to_exception(e.code, message), None)","code_tokens":"","url":338373} +{"project_name":"akshitsarin\/Udacity-AI-Nanodegree","file_name":"isolation.py","full_name":"DebugState.ind2xy","func_name":"ind2xy","docstring":"Convert from board index value to xy coordinates The coordinate frame is 0 in the bottom right corner, with x increasing along the columns progressing towards the left, and y increasing along the rows progressing towards teh top.","docstring_tokens":"","code":"@classmethod\ndef ind2xy(cls, ind):\n \"\"\" Convert from board index value to xy coordinates\n\n The coordinate frame is 0 in the bottom right corner, with x increasing\n along the columns progressing towards the left, and y increasing along\n the rows progressing towards teh top.\n \"\"\"\n return (ind % (_WIDTH + 2), ind \/\/ (_WIDTH + 2))","code_tokens":"","url":427459} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"types.py","full_name":"JumpStartModelSpecs.to_json","func_name":"to_json","docstring":"Returns json representation of JumpStartModelSpecs object.","docstring_tokens":"","code":"def to_json(self) -> Dict[str, Any]:\n \"\"\"Returns json representation of JumpStartModelSpecs object.\"\"\"\n json_obj = {}\n for att in self.__slots__:\n if hasattr(self, att):\n cur_val = getattr(self, att)\n if issubclass(type(cur_val), JumpStartDataHolderType):\n json_obj[att] = cur_val.to_json()\n elif isinstance(cur_val, list):\n json_obj[att] = []\n for obj in cur_val:\n if issubclass(type(obj), JumpStartDataHolderType):\n json_obj[att].append(obj.to_json())\n else:\n json_obj[att].append(obj)\n else:\n json_obj[att] = cur_val\n return json_obj","code_tokens":"","url":830195} +{"project_name":"ldkong1205\/LaserMix","file_name":"nuscenes_converter.py","full_name":"generate_record","func_name":"generate_record","docstring":"Generate one 2D annotation record given various information on top of the 2D bounding box coordinates.","docstring_tokens":"","code":"def generate_record(ann_rec: dict, x1: float, y1: float, x2: float, y2: float, sample_data_token: str, filename: str) -> OrderedDict:\n \"\"\"Generate one 2D annotation record given various information on top of\n the 2D bounding box coordinates.\n\n Args:\n ann_rec (dict): Original 3d annotation record.\n x1 (float): Minimum value of the x coordinate.\n y1 (float): Minimum value of the y coordinate.\n x2 (float): Maximum value of the x coordinate.\n y2 (float): Maximum value of the y coordinate.\n sample_data_token (str): Sample data token.\n filename (str):The corresponding image file where the annotation\n is present.\n\n Returns:\n dict: A sample 2D annotation record.\n - file_name (str): file name\n - image_id (str): sample data token\n - area (float): 2d box area\n - category_name (str): category name\n - category_id (int): category id\n - bbox (list[float]): left x, top y, dx, dy of 2d box\n - iscrowd (int): whether the area is crowd\n \"\"\"\n repro_rec = OrderedDict()\n repro_rec['sample_data_token'] = sample_data_token\n coco_rec = dict()\n relevant_keys = ['attribute_tokens', 'category_name', 'instance_token', 'next', 'num_lidar_pts', 'num_radar_pts', 'prev', 'sample_annotation_token', 'sample_data_token', 'visibility_token']\n for (key, value) in ann_rec.items():\n if key in relevant_keys:\n repro_rec[key] = value\n repro_rec['bbox_corners'] = [x1, y1, x2, y2]\n repro_rec['filename'] = filename\n coco_rec['file_name'] = filename\n coco_rec['image_id'] = sample_data_token\n coco_rec['area'] = (y2 - y1) * (x2 - x1)\n if repro_rec['category_name'] not in NuScenesNameMapping:\n return None\n cat_name = NuScenesNameMapping[repro_rec['category_name']]\n coco_rec['category_name'] = cat_name\n coco_rec['category_id'] = nus_categories.index(cat_name)\n coco_rec['bbox'] = [x1, y1, x2 - x1, y2 - y1]\n coco_rec['iscrowd'] = 0\n return coco_rec","code_tokens":"","url":624638} +{"project_name":"intel\/neural-compressor","file_name":"criteria.py","full_name":"SnipMomentumCriterion.on_before_optimizer_step","func_name":"on_before_optimizer_step","docstring":"Calculate and store the pruning scores based on snip_momentum criterion.","docstring_tokens":"","code":"def on_before_optimizer_step(self):\n \"\"\"Calculate and store the pruning scores based on snip_momentum criterion.\"\"\"\n with torch.no_grad():\n for key in self.modules.keys():\n p = self.modules[key].weight\n self.scores[key] *= self.alpha\n tmp = torch.abs(p * p.grad)\n if hasattr(self.pattern, 'reduce_score'):\n tmp = self.pattern.reduce_score(tmp, key, force=True)\n if self.low_memory_usage:\n tmp = tmp.bfloat16() if p.device.type == 'cpu' else tmp.half()\n self.scores[key] += self.beta * tmp","code_tokens":"","url":738044} +{"project_name":"jbwang1997\/CrossKD","file_name":"test_ddod_head.py","full_name":"TestDDODHead.test_ddod_head_loss","func_name":"test_ddod_head_loss","docstring":"Tests ddod head loss when truth is empty and non-empty.","docstring_tokens":"","code":"def test_ddod_head_loss(self):\n \"\"\"Tests ddod head loss when truth is empty and non-empty.\"\"\"\n s = 256\n img_metas = [{'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1}]\n cfg = Config(dict(assigner=dict(type='ATSSAssigner', topk=9, alpha=0.8), reg_assigner=dict(type='ATSSAssigner', topk=9, alpha=0.5), allowed_border=-1, pos_weight=-1, debug=False))\n atss_head = DDODHead(num_classes=4, in_channels=1, stacked_convs=1, feat_channels=1, use_dcn=False, norm_cfg=None, train_cfg=cfg, anchor_generator=dict(type='AnchorGenerator', ratios=[1.0], octave_base_scale=8, scales_per_octave=1, strides=[8, 16, 32, 64, 128]), loss_cls=dict(type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=2.0), loss_iou=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))\n feat = [torch.rand(1, 1, s \/\/ feat_size, s \/\/ feat_size) for feat_size in [8, 16, 32, 64, 128]]\n (cls_scores, bbox_preds, centernesses) = atss_head.forward(feat)\n gt_instances = InstanceData()\n gt_instances.bboxes = torch.empty((0, 4))\n gt_instances.labels = torch.LongTensor([])\n empty_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, centernesses, [gt_instances], img_metas)\n empty_cls_loss = sum(empty_gt_losses['loss_cls'])\n empty_box_loss = sum(empty_gt_losses['loss_bbox'])\n empty_centerness_loss = sum(empty_gt_losses['loss_iou'])\n self.assertGreater(empty_cls_loss.item(), 0, 'cls loss should be non-zero')\n self.assertEqual(empty_box_loss.item(), 0, 'there should be no box loss when there are no true boxes')\n self.assertEqual(empty_centerness_loss.item(), 0, 'there should be no centerness loss when there are no true boxes')\n gt_instances = InstanceData()\n gt_instances.bboxes = torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]])\n gt_instances.labels = torch.LongTensor([2])\n one_gt_losses = atss_head.loss_by_feat(cls_scores, bbox_preds, centernesses, [gt_instances], img_metas)\n onegt_cls_loss = sum(one_gt_losses['loss_cls'])\n onegt_box_loss = sum(one_gt_losses['loss_bbox'])\n onegt_centerness_loss = sum(one_gt_losses['loss_iou'])\n self.assertGreater(onegt_cls_loss.item(), 0, 'cls loss should be non-zero')\n self.assertGreater(onegt_box_loss.item(), 0, 'box loss should be non-zero')\n self.assertGreater(onegt_centerness_loss.item(), 0, 'centerness loss should be non-zero')","code_tokens":"","url":491893} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"benchmark_uploader.py","full_name":"BigQueryUploader.upload_benchmark_metric_json","func_name":"upload_benchmark_metric_json","docstring":"Upload metric information to Bigquery.","docstring_tokens":"","code":"def upload_benchmark_metric_json(self, dataset_name, table_name, run_id, metric_json_list):\n \"\"\"Upload metric information to Bigquery.\n\n Args:\n dataset_name: string, the name of bigquery dataset where the data will be\n uploaded.\n table_name: string, the name of bigquery table under the dataset where\n the metric data will be uploaded. This is different from the\n benchmark_run table.\n run_id: string, a unique ID that will be attached to the data, usually\n this is a UUID4 format. This should be the same as the benchmark run_id.\n metric_json_list: list, a list of JSON object that record the metric info.\n \"\"\"\n for m in metric_json_list:\n m['run_id'] = run_id\n self._upload_json(dataset_name, table_name, metric_json_list)","code_tokens":"","url":760992} +{"project_name":"yinyunie\/ScenePriors","file_name":"utils.py","full_name":"TensorProperties.clone","func_name":"clone","docstring":"Update the tensor properties of other with the cloned properties of self.","docstring_tokens":"","code":"def clone(self, other) -> 'TensorProperties':\n \"\"\"\n Update the tensor properties of other with the cloned properties of self.\n \"\"\"\n for k in dir(self):\n v = getattr(self, k)\n if inspect.ismethod(v) or k.startswith('__'):\n continue\n if torch.is_tensor(v):\n v_clone = v.clone()\n else:\n v_clone = copy.deepcopy(v)\n setattr(other, k, v_clone)\n return other","code_tokens":"","url":329851} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"pefile.py","full_name":"PE.get_rva_from_offset","func_name":"get_rva_from_offset","docstring":"Get the RVA corresponding to this file offset.","docstring_tokens":"","code":"def get_rva_from_offset(self, offset):\n \"\"\"Get the RVA corresponding to this file offset. \"\"\"\n s = self.get_section_by_offset(offset)\n if not s:\n if self.sections:\n lowest_rva = min([self.adjust_SectionAlignment(s.VirtualAddress, self.OPTIONAL_HEADER.SectionAlignment, self.OPTIONAL_HEADER.FileAlignment) for s in self.sections])\n if offset < lowest_rva:\n return offset\n return None\n else:\n return offset\n return s.get_rva_from_offset(offset)","code_tokens":"","url":976771} +{"project_name":"alegonz\/kdsb17","file_name":"model.py","full_name":"NakedModel.build_model","func_name":"build_model","docstring":"Builds and compiles the model.","docstring_tokens":"","code":"def build_model(self, freeze=None):\n \"\"\"Builds and compiles the model.\n\n Args:\n freeze (list): Name of layers to freeze in training.\n \"\"\"\n self._build_layers()\n self._model = Model(self._input_layer, self._output_layer)\n if freeze is not None:\n for layer_name in freeze:\n layer = self._model.get_layer(name=layer_name)\n layer.trainable = False\n print('%s is set to %d' % (layer_name, layer.trainable))\n self._compile_model()","code_tokens":"","url":594929} +{"project_name":"google-research\/tensor2robot","file_name":"model_interface.py","full_name":"ModelInterface.is_device_gpu","func_name":"is_device_gpu","docstring":"Returns True if the device is GPU otherwise False.","docstring_tokens":"","code":"@abc.abstractproperty\ndef is_device_gpu(self):\n \"\"\"Returns True if the device is GPU otherwise False.\"\"\"","code_tokens":"","url":908235} +{"project_name":"google\/ml-compiler-opt","file_name":"worker.py","full_name":"wait_for","func_name":"wait_for","docstring":"Dask futures don't support more than result() and done().","docstring_tokens":"","code":"def wait_for(futures: Iterable[WorkerFuture]):\n \"\"\"Dask futures don't support more than result() and done().\"\"\"\n for f in futures:\n try:\n _ = f.result()\n except:\n pass","code_tokens":"","url":671140} +{"project_name":"apeterswu\/RL4NMT","file_name":"common_layers.py","full_name":"shakeshake2","func_name":"shakeshake2","docstring":"The shake-shake function with a different alpha for forward\/backward.","docstring_tokens":"","code":"@function.Defun(grad_func=shakeshake2_grad)\ndef shakeshake2(x1, x2):\n \"\"\"The shake-shake function with a different alpha for forward\/backward.\"\"\"\n return shakeshake2_py(x1, x2)","code_tokens":"","url":331017} +{"project_name":"dwf\/convolupy","file_name":"base.py","full_name":"BaseBPropComponent.grad","func_name":"grad","docstring":"Backpropagate derivatives through this module to get derivatives with respect to this module's input.","docstring_tokens":"","code":"def grad(self, dout, inputs):\n \"\"\"\n Backpropagate derivatives through this module to get derivatives\n with respect to this module's input.\n \"\"\"\n dshp = 'x'.join((str(x) for x in dout.shape))\n ishp = 'x'.join((str(x) for x in inputs.shape))\n raise NotImplementedError('grad(dout@%s, input@%s): %s' % (dshp, ishp, str(self.__class__)))","code_tokens":"","url":136998} +{"project_name":"triaquae\/triaquae","file_name":"views.py","full_name":"sitemap","func_name":"sitemap","docstring":"This view generates a sitemap with additional geographic elements defined by Google.","docstring_tokens":"","code":"def sitemap(request, sitemaps, section=None):\n \"\"\"\n This view generates a sitemap with additional geographic\n elements defined by Google.\n \"\"\"\n (maps, urls) = ([], [])\n if section is not None:\n if section not in sitemaps:\n raise Http404(_('No sitemap available for section: %r') % section)\n maps.append(sitemaps[section])\n else:\n maps = list(six.itervalues(sitemaps))\n page = request.GET.get('p', 1)\n current_site = get_current_site(request)\n for site in maps:\n try:\n if callable(site):\n urls.extend(site().get_urls(page=page, site=current_site))\n else:\n urls.extend(site.get_urls(page=page, site=current_site))\n except EmptyPage:\n raise Http404(_('Page %s empty') % page)\n except PageNotAnInteger:\n raise Http404(_(\"No page '%s'\") % page)\n xml = loader.render_to_string('gis\/sitemaps\/geo_sitemap.xml', {'urlset': urls})\n return HttpResponse(xml, content_type='application\/xml')","code_tokens":"","url":357928} +{"project_name":"imoscovitz\/wittgenstein","file_name":"base.py","full_name":"Timer.stop","func_name":"stop","docstring":"Freeze the clock at the amount of time elapsed since Timer was created or reset.","docstring_tokens":"","code":"def stop(self):\n \"\"\" Freeze the clock at the amount of time elapsed since Timer was created or reset. \"\"\"\n self.elapsed = time.time() - self.start","code_tokens":"","url":959832} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"ops.py","full_name":"convert_to_eager_tensor","func_name":"convert_to_eager_tensor","docstring":"Converts the given `value` to an `EagerTensor`.","docstring_tokens":"","code":"def convert_to_eager_tensor(t, dtype=None):\n \"\"\"Converts the given `value` to an `EagerTensor`.\"\"\"\n if isinstance(ag_core.getval(t), EagerTensor):\n if dtype is not None and t.dtype != dtype:\n raise TypeError('Expected tensor with type %r not %r' % (dtype, t.dtype))\n return t\n try:\n return t._dense_var_to_tensor(dtype=dtype, as_ref=False)\n except AttributeError:\n pass\n return EagerTensor(t, dtype=dtype)","code_tokens":"","url":605380} +{"project_name":"jsn5\/dancenet","file_name":"mdn.py","full_name":"get_mixture_loss_func","func_name":"get_mixture_loss_func","docstring":"Construct a loss functions for the MDN layer parametrised by number of mixtures.","docstring_tokens":"","code":"def get_mixture_loss_func(output_dim, num_mixes):\n \"\"\"Construct a loss functions for the MDN layer parametrised by number of mixtures.\"\"\"\n\n def loss_func(y_true, y_pred):\n (out_mu, out_sigma, out_pi) = tf.split(y_pred, num_or_size_splits=[num_mixes * output_dim, num_mixes * output_dim, num_mixes], axis=1, name='mdn_coef_split')\n cat = Categorical(logits=out_pi)\n component_splits = [output_dim] * num_mixes\n mus = tf.split(out_mu, num_or_size_splits=component_splits, axis=1)\n sigs = tf.split(out_sigma, num_or_size_splits=component_splits, axis=1)\n coll = [MultivariateNormalDiag(loc=loc, scale_diag=scale) for (loc, scale) in zip(mus, sigs)]\n mixture = Mixture(cat=cat, components=coll)\n loss = mixture.log_prob(y_true)\n loss = tf.negative(loss)\n loss = tf.reduce_mean(loss)\n return loss\n with tf.name_scope('MDN'):\n return loss_func","code_tokens":"","url":497025} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"fileio.py","full_name":"FileManagerMixin.perm_to_403","func_name":"perm_to_403","docstring":"context manager for turning permission errors into 403.","docstring_tokens":"","code":"@contextmanager\ndef perm_to_403(self, os_path=''):\n \"\"\"context manager for turning permission errors into 403.\"\"\"\n try:\n yield\n except (OSError, IOError) as e:\n if e.errno in {errno.EPERM, errno.EACCES}:\n if not os_path:\n os_path = str_to_unicode(e.filename or 'unknown file')\n path = to_api_path(os_path, root=self.root_dir)\n raise HTTPError(403, u'Permission denied: %s' % path)\n else:\n raise","code_tokens":"","url":43223} +{"project_name":"huiminren\/RobustVAE","file_name":"projSVDToDist.py","full_name":"projSVDToDist","func_name":"projSVDToDist","docstring":"A projection of an SVD onto a index set with a conversion to a distance matrix.","docstring_tokens":"","code":"def projSVDToDist(U, E, VT, u, v, returnVec=False):\n \"\"\"A projection of an SVD onto a index set with a conversion to\n a distance matrix.\n\n Args:\n U,E,VT: The SVD of a matrix.\n\n u,v: The indices at which to evaluate the SVD.\n\n returnVec: If True return a vector, otherwise return a\n sparse matrix.\n\n Returns:\n A sparse matrix with the evalutions of the matrix and\n then converted to a distance matrix. Note, the undefined\n entries are not necessarily 0! They are merely unobserved.\n\n \"\"\"\n assert U.shape[1] == len(E), 'shape mismatch'\n assert VT.shape[0] == len(E), 'shape mismatch'\n assert len(U.shape) == 2, 'U needs to be a matrix'\n assert len(VT.shape) == 2, 'VT need to be a matrix'\n assert len(E.shape) == 1, 'E need to be an array'\n m = U.shape[0]\n n = VT.shape[1]\n l = len(u)\n tmp = np.array(np.zeros([l]))\n Sigma = np.diag(E)\n _worker(U, Sigma, VT, tmp, u, v, l)\n if returnVec:\n return tmp\n else:\n return sp.csc_matrix(sp.coo_matrix((tmp, (u, v)), shape=[m, n]))","code_tokens":"","url":826404} +{"project_name":"QinganZhao\/Deep-Learning-Based-Structural-Damage-Detection","file_name":"cpp_lint.py","full_name":"_CppLintState.SetCountingStyle","func_name":"SetCountingStyle","docstring":"Sets the module's counting options.","docstring_tokens":"","code":"def SetCountingStyle(self, counting_style):\n \"\"\"Sets the module's counting options.\"\"\"\n self.counting = counting_style","code_tokens":"","url":127584} +{"project_name":"accel-brain\/accel-brain-code","file_name":"generative_model.py","full_name":"GenerativeModel.get_condition_sampler","func_name":"get_condition_sampler","docstring":"getter for `ConditionSampler` of sampler to draw conditons from user-defined distributions.","docstring_tokens":"","code":"def get_condition_sampler(self):\n \"\"\" getter for `ConditionSampler` of sampler to draw conditons from user-defined distributions.\"\"\"\n return self.__conditon_sampler","code_tokens":"","url":6946} +{"project_name":"AgnostiqHQ\/covalent","file_name":"transport_test.py","full_name":"test_reset_node","func_name":"test_reset_node","docstring":"Test the node reset method.","docstring_tokens":"","code":"def test_reset_node(workflow_transport_graph, mocker):\n \"\"\"Test the node reset method.\"\"\"\n set_node_value_mock = mocker.patch('covalent._workflow.transport._TransportGraph.set_node_value')\n node_id = 0\n workflow_transport_graph.reset_node(node_id)\n actual_mock_calls = set_node_value_mock.mock_calls\n expected_mock_calls = [call(node_id, node_attr, default_val) for (node_attr, default_val) in workflow_transport_graph._default_node_attrs.items()]\n for mock_call in expected_mock_calls:\n assert mock_call in actual_mock_calls","code_tokens":"","url":489955} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"test_editmenu.py","full_name":"PasteTest.test_paste_spin_no_selection","func_name":"test_paste_spin_no_selection","docstring":"Test pasting into a spinbox without a selection.","docstring_tokens":"","code":"def test_paste_spin_no_selection(self):\n \"\"\"Test pasting into a spinbox without a selection.\"\"\"\n spin = self.spin\n (end, ans) = (0, 'onetwo')\n spin.delete(0, 'end')\n spin.insert(0, 'one')\n spin.selection('range', 0, end)\n spin.event_generate('<>')\n self.assertEqual(spin.get(), ans)","code_tokens":"","url":219304} +{"project_name":"NVIDIA-Omniverse\/OmniIsaacGymEnvs","file_name":"factory_control.py","full_name":"translate_along_local_z","func_name":"translate_along_local_z","docstring":"Translate global body position along local Z-axis and express in global coordinates.","docstring_tokens":"","code":"def translate_along_local_z(pos, quat, offset, device):\n \"\"\"Translate global body position along local Z-axis and express in global coordinates.\"\"\"\n num_vecs = pos.shape[0]\n offset_vec = offset * torch.tensor([0.0, 0.0, 1.0], device=device).repeat((num_vecs, 1))\n (_, translated_pos) = torch_utils.tf_combine(q1=quat, t1=pos, q2=torch.tensor([1.0, 0.0, 0.0, 0.0], device=device).repeat((num_vecs, 1)), t2=offset_vec)\n return translated_pos","code_tokens":"","url":250385} +{"project_name":"lhotse-speech\/lhotse","file_name":"qa.py","full_name":"register_validator","func_name":"register_validator","docstring":"Decorator registers the function to be invoked inside ``validate()`` when the first argument's type is matching.","docstring_tokens":"","code":"def register_validator(fn):\n \"\"\"\n Decorator registers the function to be invoked inside ``validate()``\n when the first argument's type is matching.\n \"\"\"\n first_arg_type = next(iter(fn.__annotations__.values()))\n _VALIDATORS[first_arg_type] = fn\n return fn","code_tokens":"","url":600398} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"completer.py","full_name":"compress_user","func_name":"compress_user","docstring":"Does the opposite of expand_user, with its outputs.","docstring_tokens":"","code":"def compress_user(path: str, tilde_expand: bool, tilde_val: str) -> str:\n \"\"\"Does the opposite of expand_user, with its outputs.\n \"\"\"\n if tilde_expand:\n return path.replace(tilde_val, '~')\n else:\n return path","code_tokens":"","url":37882} +{"project_name":"dlshriver\/dnnv","file_name":"test_esip.py","full_name":"TestNNBounds.test_prop_error_matrix_trough_relaxation","func_name":"test_prop_error_matrix_trough_relaxation","docstring":"Tests the output from the _prop_error_matrix_trough_relaxation() method against ground truth.","docstring_tokens":"","code":"def test_prop_error_matrix_trough_relaxation(self):\n \"\"\"\n Tests the output from the _prop_error_matrix_trough_relaxation() method against ground truth.\n \"\"\"\n error_matrix = np.array([[-3, 1]])\n relax = np.array([[[0.5, 1]], [[0.5, 2]]])\n bounds_concrete = np.array([[-1, 1]])\n error_matrix_to_node_indices = np.array([[1, 0], [1, 1]])\n layer_num = 2\n (new_error_matrix, error_matrix_to_node_indices) = self.bounds_relu._prop_error_matrix_trough_relaxation(error_matrix, relax, bounds_concrete, error_matrix_to_node_indices, layer_num)\n gt_error_matrix = np.array([[-1.5, 0.5, 1]])\n gt_error_matrix_to_node_indices = np.array([[1, 0], [1, 1], [2, 0]])\n for i in range(gt_error_matrix.shape[0]):\n for j in range(gt_error_matrix.shape[1]):\n self.assertAlmostEqual(new_error_matrix[i, j], gt_error_matrix[i, j])\n for i in range(gt_error_matrix_to_node_indices.shape[0]):\n for j in range(gt_error_matrix_to_node_indices.shape[1]):\n self.assertAlmostEqual(error_matrix_to_node_indices[i, j], gt_error_matrix_to_node_indices[i, j])","code_tokens":"","url":522669} +{"project_name":"PUTvision\/qgis-plugin-deepness","file_name":"deepness.py","full_name":"Deepness.unload","func_name":"unload","docstring":"Removes the plugin menu item and icon from QGIS GUI.","docstring_tokens":"","code":"def unload(self):\n \"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"\n for action in self.actions:\n self.iface.removePluginMenu(self.tr(u'&Deepness'), action)\n self.iface.removeToolBarIcon(action)\n del self.toolbar","code_tokens":"","url":816089} +{"project_name":"IGNF\/myria3d","file_name":"run.py","full_name":"launch_predict","func_name":"launch_predict","docstring":"Infer probabilities and automate semantic segmentation decisions on unseen data.","docstring_tokens":"","code":"@hydra.main(config_path=DEFAULT_DIRECTORY, config_name=DEFAULT_CONFIG_FILE)\ndef launch_predict(config: DictConfig):\n \"\"\"Infer probabilities and automate semantic segmentation decisions on unseen data.\"\"\"\n from myria3d.predict import predict\n if not os.path.isabs(config.predict.ckpt_path):\n config.predict.ckpt_path = os.path.join(os.path.dirname(__file__), config.predict.ckpt_path)\n if config.get('print_config'):\n utils.print_config(config, resolve=False)\n src_las_iterable = glob(config.predict.src_las)\n for config.predict.src_las in tqdm(src_las_iterable):\n predict(config)","code_tokens":"","url":651612} +{"project_name":"lebrice\/Sequoia","file_name":"setting_test.py","full_name":"test_methods_applicable_to_iid_setting","func_name":"test_methods_applicable_to_iid_setting","docstring":"Test to make sure that Methods that are applicable to the Domain-Incremental are applicable to the IID Setting, same for those targetting the Task-Incremental setting.","docstring_tokens":"","code":"def test_methods_applicable_to_iid_setting():\n \"\"\"Test to make sure that Methods that are applicable to the Domain-Incremental\n are applicable to the IID Setting, same for those targetting the Task-Incremental\n setting.\n \"\"\"\n assert ContinualSLMethod.is_applicable(ContinualSLSetting)\n assert ContinualSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert ContinualSLMethod.is_applicable(IncrementalSLSetting)\n assert ContinualSLMethod.is_applicable(ClassIncrementalSetting)\n assert ContinualSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert ContinualSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert ContinualSLMethod.is_applicable(TraditionalSLSetting)\n assert ContinualSLMethod.is_applicable(MultiTaskSLSetting)\n assert not DiscreteTaskAgnosticSLMethod.is_applicable(ContinualSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(IncrementalSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(ClassIncrementalSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(TraditionalSLSetting)\n assert DiscreteTaskAgnosticSLMethod.is_applicable(MultiTaskSLSetting)\n assert not IncrementalSLMethod.is_applicable(ContinualSLSetting)\n assert not IncrementalSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert IncrementalSLMethod.is_applicable(IncrementalSLSetting)\n assert IncrementalSLMethod.is_applicable(ClassIncrementalSetting)\n assert IncrementalSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert IncrementalSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert IncrementalSLMethod.is_applicable(TraditionalSLSetting)\n assert IncrementalSLMethod.is_applicable(MultiTaskSLSetting)\n assert not ClassIncrementalSLMethod.is_applicable(ContinualSLSetting)\n assert not ClassIncrementalSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert ClassIncrementalSLMethod.is_applicable(IncrementalSLSetting)\n assert ClassIncrementalSLMethod.is_applicable(ClassIncrementalSetting)\n assert ClassIncrementalSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert ClassIncrementalSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert ClassIncrementalSLMethod.is_applicable(TraditionalSLSetting)\n assert ClassIncrementalSLMethod.is_applicable(MultiTaskSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(ContinualSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(IncrementalSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(ClassIncrementalSetting)\n assert TaskIncrementalSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert not TaskIncrementalSLMethod.is_applicable(TraditionalSLSetting)\n assert TaskIncrementalSLMethod.is_applicable(MultiTaskSLSetting)\n assert not DomainIncrementalSLMethod.is_applicable(ContinualSLSetting)\n assert not DomainIncrementalSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert not DomainIncrementalSLMethod.is_applicable(IncrementalSLSetting)\n assert not DomainIncrementalSLMethod.is_applicable(ClassIncrementalSetting)\n assert not DomainIncrementalSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert DomainIncrementalSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert not DomainIncrementalSLMethod.is_applicable(TraditionalSLSetting)\n assert not TraditionalSLMethod.is_applicable(ContinualSLSetting)\n assert not TraditionalSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert not TraditionalSLMethod.is_applicable(IncrementalSLSetting)\n assert not TraditionalSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert not TraditionalSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert not TraditionalSLMethod.is_applicable(ClassIncrementalSetting)\n assert TraditionalSLMethod.is_applicable(TraditionalSLSetting)\n assert TraditionalSLMethod.is_applicable(MultiTaskSLSetting)\n assert not MultiTaskSLMethod.is_applicable(ContinualSLSetting)\n assert not MultiTaskSLMethod.is_applicable(DiscreteTaskAgnosticSLSetting)\n assert not MultiTaskSLMethod.is_applicable(IncrementalSLSetting)\n assert not MultiTaskSLMethod.is_applicable(TaskIncrementalSLSetting)\n assert not MultiTaskSLMethod.is_applicable(DomainIncrementalSLSetting)\n assert not MultiTaskSLMethod.is_applicable(ClassIncrementalSetting)\n assert not MultiTaskSLMethod.is_applicable(TraditionalSLSetting)\n assert MultiTaskSLMethod.is_applicable(MultiTaskSLSetting)","code_tokens":"","url":349697} +{"project_name":"brain-research\/hyperbolictext","file_name":"tools.py","full_name":"create_embedding_map","func_name":"create_embedding_map","docstring":"Returns a dictionary mapping word to word embedding.","docstring_tokens":"","code":"def create_embedding_map(reverse_vocab, embedding_matrix):\n \"\"\"Returns a dictionary mapping word to word embedding.\"\"\"\n return collections.OrderedDict(zip(reverse_vocab, embedding_matrix))","code_tokens":"","url":228136} +{"project_name":"noambassat\/SpeechTrainer","file_name":"compat.py","full_name":"ChainMap.fromkeys","func_name":"fromkeys","docstring":"Create a ChainMap with a single dict created from the iterable.","docstring_tokens":"","code":"@classmethod\ndef fromkeys(cls, iterable, *args):\n \"\"\"Create a ChainMap with a single dict created from the iterable.\"\"\"\n return cls(dict.fromkeys(iterable, *args))","code_tokens":"","url":895391} +{"project_name":"vin-nag\/GANs-n-reels","file_name":"Audio_Converter.py","full_name":"Converter.parse_out_type","func_name":"parse_out_type","docstring":"Helper function to ensure the file type is valid\/manageable.","docstring_tokens":"","code":"def parse_out_type(self, out_type):\n \"\"\"\n Helper function to ensure the file type is valid\/manageable.\n \"\"\"\n default = 'mid'\n out_types = ['mid', 'wav', 'flac', 'mp3', 'ogg', 'flv', 'mp4', 'wma', 'aac']\n if type(out_type) == int:\n if out_type >= len(out_types):\n print('Index out of range. Defaulting to MIDI')\n return default\n else:\n return out_types[out_type]\n if type(out_type) != str:\n print(\"Invalid input type. Expected 'str' or 'int', got '{}' instead.\".format(type(out_type)))\n print('Defaulting to MIDI')\n return default\n elif out_type.lower() not in out_types:\n if not out_type.lower() == 'midi':\n print('Unsupported file type. Defaulting to MIDI')\n return default\n else:\n return out_type","code_tokens":"","url":566855} +{"project_name":"yaserkl\/RLSeq2Seq","file_name":"model.py","full_name":"SummarizationModel.reward","func_name":"reward","docstring":"A wrapper for calculating the reward.","docstring_tokens":"","code":"def reward(self, t, _ss, _gts, vsize_extended):\n \"\"\" A wrapper for calculating the reward. \"\"\"\n first_case = np.append(_ss[0:t], [0])\n special_reward = self.calc_reward(first_case, _gts)\n reward = [special_reward for _ in range(vsize_extended)]\n second_case = np.append(_ss[0:t], [_gts[t - 1]])\n reward[_gts[t - 1]] = self.calc_reward(second_case, _gts)\n return reward","code_tokens":"","url":324262} +{"project_name":"MushroomRL\/mushroom-rl","file_name":"viewer.py","full_name":"Viewer.function","func_name":"function","docstring":"Draw the graph of a function in the image.","docstring_tokens":"","code":"def function(self, x_s, x_e, f, n_points=100, width=1, color=(255, 255, 255)):\n \"\"\"\n Draw the graph of a function in the image.\n\n Args:\n x_s (float): starting x coordinate;\n x_e (float): final x coordinate;\n f (function): the function that maps x coorinates into y\n coordinates;\n n_points (int, 100): the number of segments used to approximate the\n function to draw;\n width (int, 1): thw width of the line drawn;\n color (tuple, (255,255,255)): the color of the line.\n\n \"\"\"\n x = np.linspace(x_s, x_e, n_points)\n y = f(x)\n points = [self._transform([a, b]) for (a, b) in zip(x, y)]\n pygame.draw.lines(self.screen, color, False, points, width)","code_tokens":"","url":266190} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"calendar.py","full_name":"HTMLCalendar.formatyear","func_name":"formatyear","docstring":"Return a formatted year as a table of tables.","docstring_tokens":"","code":"def formatyear(self, theyear, width=3):\n \"\"\"\n Return a formatted year as a table of tables.\n \"\"\"\n v = []\n a = v.append\n width = max(width, 1)\n a('')\n a('\\n')\n a('')\n for m in months:\n a('
%s<\/th><\/tr>' % (width, theyear))\n for i in range(January, January + 12, width):\n months = range(i, min(i + width, 13))\n a('
')\n a(self.formatmonth(theyear, m, withyear=False))\n a('<\/td>')\n a('<\/tr>')\n a('<\/table>')\n return ''.join(v)","code_tokens":"","url":428253} +{"project_name":"guenthermi\/table-embeddings","file_name":"classifier.py","full_name":"DECOClassifier.train","func_name":"train","docstring":"Trains the GNN network previously created with the _create_gcn_net() function.","docstring_tokens":"","code":"def train(self, train_ids, train_labels, valid_ids, valid_labels, max_epochs=150):\n \"\"\"Trains the GNN network previously created with the _create_gcn_net()\n function.\n \"\"\"\n epoch = 0\n loss_stagnation = 0\n duration = []\n while epoch < max_epochs:\n t0 = time.time()\n (pred, train_loss) = self._perform_training_step(train_ids, train_labels)\n valid_loss = self.loss_fcn(mx.nd.log_softmax(mx.nd.array(pred[valid_ids])), valid_labels)\n valid_loss = valid_loss.sum() \/ len(valid_ids)\n mx.nd.waitall()\n duration.append(time.time() - t0)\n valid_acc = gcn.evaluate(pred[valid_ids], valid_labels)\n epoch += 1\n print(('Epoch {:03d} | Train Loss {:.4f} | ' + 'Valid Loss {:.4f} | Valid Acc {:.4f} | Time(s) {:.4f}').format(epoch, train_loss.asscalar(), valid_loss.asscalar(), valid_acc, duration[-1]))","code_tokens":"","url":365111} +{"project_name":"src-d\/ml","file_name":"content2ids.py","full_name":"IdentifiersToDataset.process","func_name":"process","docstring":"Process rows to gather identifier without frequencies.","docstring_tokens":"","code":"def process(self, rows: RDD):\n \"\"\"\n Process rows to gather identifier without frequencies.\n \"\"\"\n return rows.keys().distinct().map(lambda x: Row(token=x, token_split=' '.join(TokenParser(min_split_length=1).split(x))))","code_tokens":"","url":239750} +{"project_name":"opendilab\/DI-star","file_name":"renderer_human.py","full_name":"RendererHuman.draw_panel","func_name":"draw_panel","docstring":"Draw the unit selection or build queue.","docstring_tokens":"","code":"@sw.decorate\ndef draw_panel(self, surf):\n \"\"\"Draw the unit selection or build queue.\"\"\"\n left = -14\n line = itertools.count(3)\n\n def unit_name(unit_type):\n return self._static_data.units.get(unit_type, '')\n\n def write(loc, text, color=colors.yellow):\n surf.write_screen(self._font_large, color, loc, text)\n\n def write_line(x, *args, **kwargs):\n write((left + x, next(line)), *args, **kwargs)\n\n def write_single(unit):\n \"\"\"Write a description of a single selected unit.\"\"\"\n write_line(1, unit_name(unit.unit_type), colors.cyan)\n write_line(1, 'Health: %s \/ %s' % (unit.health, unit.max_health))\n if unit.max_shields:\n write_line(1, 'Shields: %s \/ %s' % (unit.shields, unit.max_shields))\n if unit.max_energy:\n write_line(1, 'Energy: %s \/ %s' % (unit.energy, unit.max_energy))\n if unit.build_progress > 0:\n write_line(1, 'Progress: %d%%' % (unit.build_progress * 100))\n if unit.transport_slots_taken > 0:\n write_line(1, 'Slots: %s' % unit.transport_slots_taken)\n\n def write_multi(units):\n \"\"\"Write a description of multiple selected units.\"\"\"\n counts = collections.defaultdict(int)\n for unit in units:\n counts[unit_name(unit.unit_type)] += 1\n for (name, count) in sorted(counts.items()):\n y = next(line)\n write((left + 1, y), count)\n write((left + 3, y), name)\n ui = self._obs.observation.ui_data\n if ui.groups:\n write_line(0, 'Control Groups:', colors.green)\n for group in ui.groups:\n y = next(line)\n write((left + 1, y), '%s:' % group.control_group_index, colors.green)\n write((left + 3, y), '%s %s' % (group.count, unit_name(group.leader_unit_type)))\n next(line)\n if ui.HasField('single'):\n write_line(0, 'Selection:', colors.green)\n write_single(ui.single.unit)\n if ui.single.attack_upgrade_level or ui.single.armor_upgrade_level or ui.single.shield_upgrade_level:\n write_line(1, 'Upgrades:')\n if ui.single.attack_upgrade_level:\n write_line(2, 'Attack: %s' % ui.single.attack_upgrade_level)\n if ui.single.armor_upgrade_level:\n write_line(2, 'Armor: %s' % ui.single.armor_upgrade_level)\n if ui.single.shield_upgrade_level:\n write_line(2, 'Shield: %s' % ui.single.shield_upgrade_level)\n if ui.single.buffs:\n write_line(1, 'Buffs:')\n for b in ui.single.buffs:\n write_line(2, buffs.Buffs(b).name)\n elif ui.HasField('multi'):\n write_line(0, 'Selection:', colors.green)\n write_multi(ui.multi.units)\n elif ui.HasField('cargo'):\n write_line(0, 'Selection:', colors.green)\n write_single(ui.cargo.unit)\n next(line)\n write_line(0, 'Cargo:', colors.green)\n write_line(1, 'Empty slots: %s' % ui.cargo.slots_available)\n write_multi(ui.cargo.passengers)\n elif ui.HasField('production'):\n write_line(0, 'Selection:', colors.green)\n write_single(ui.production.unit)\n next(line)\n if ui.production.production_queue:\n write_line(0, 'Production:', colors.green)\n for item in ui.production.production_queue:\n specific_data = self._static_data.abilities[item.ability_id]\n if specific_data.remaps_to_ability_id:\n general_data = self._static_data.abilities[specific_data.remaps_to_ability_id]\n else:\n general_data = specific_data\n s = general_data.friendly_name or general_data.button_name or general_data.link_name\n s = s.replace('Research ', '').replace('Train ', '')\n if item.build_progress > 0:\n s += ': %d%%' % (item.build_progress * 100)\n write_line(1, s)\n elif ui.production.build_queue:\n write_line(0, 'Build Queue:', colors.green)\n for unit in ui.production.build_queue:\n s = unit_name(unit.unit_type)\n if unit.build_progress > 0:\n s += ': %d%%' % (unit.build_progress * 100)\n write_line(1, s)","code_tokens":"","url":184791} +{"project_name":"shenyunhang\/PDSL","file_name":"defaults.py","full_name":"add_wsl_config","func_name":"add_wsl_config","docstring":"Add config for mrrpnet.","docstring_tokens":"","code":"def add_wsl_config(cfg):\n \"\"\"\n Add config for mrrpnet.\n \"\"\"\n _C = cfg\n _C.MODEL.VGG = CN()\n _C.MODEL.VGG.DEPTH = 16\n _C.MODEL.VGG.OUT_FEATURES = ['plain5']\n _C.MODEL.VGG.CONV5_DILATION = 1\n _C.WSL = CN()\n _C.WSL.VIS_TEST = False\n _C.WSL.ITER_SIZE = 1\n _C.WSL.MEAN_LOSS = True\n _C.WSL.AE_BURNIN_ITERS = 100000\n _C.WSL.SIZE_EPOCH = 5000\n _C.WSL.CMIL = False\n _C.MODEL.ROI_BOX_HEAD.DAN_DIM = [4096, 4096]\n _C.WSL.USE_OBN = True\n _C.WSL.CSC_MAX_ITER = 35000\n _C.WSL.REFINE_NUM = 3\n _C.WSL.REFINE_REG = [False, False, False]\n _C.WSL.HAS_GAM = False\n _C.WSL.REFINE_MIST = False\n _C.DATASETS.VAL = ()\n _C.DATASETS.PROPOSAL_FILES_VAL = ()\n _C.MODEL.SEM_SEG_HEAD.ASSP_CONVS_DIM = [1024, 1024]\n _C.MODEL.SEM_SEG_HEAD.MASK_SOFTMAX = False\n _C.MODEL.SEM_SEG_HEAD.CONSTRAINT = False\n _C.TEST.EVAL_TRAIN = True\n _C.WSL.CLS_AGNOSTIC_BBOX_KNOWN = False\n _C.WSL.SAMPLING = CN()\n _C.WSL.SAMPLING.SAMPLING_ON = False\n _C.WSL.SAMPLING.IOU_THRESHOLDS = [[0.5], [0.5], [0.5], [0.5]]\n _C.WSL.SAMPLING.IOU_LABELS = [[0, 1], [0, 1], [0, 1], [0, 1]]\n _C.WSL.SAMPLING.BATCH_SIZE_PER_IMAGE = [4096, 4096, 4096, 4096]\n _C.WSL.SAMPLING.POSITIVE_FRACTION = [1.0, 1.0, 1.0, 1.0]\n _C.WSL.CASCADE_ON = False\n _C.WSL.PS_ON = False\n _C.WSL.SP_ON = False\n _C.WSL.MASK_MINED_TOP_K = 10\n _C.MODEL.MRRP = CN()\n _C.MODEL.MRRP.MRRP_ON = False\n _C.MODEL.MRRP.NUM_BRANCH = 3\n _C.MODEL.MRRP.BRANCH_DILATIONS = [1, 2, 3]\n _C.MODEL.MRRP.MRRP_STAGE = 'res4'\n _C.MODEL.MRRP.TEST_BRANCH_IDX = 1","code_tokens":"","url":279444} +{"project_name":"jhultman\/vision3d","file_name":"sparse_cnn.py","full_name":"SparseCNNBase.pad_batch","func_name":"pad_batch","docstring":"Pad sparse tensor with subsamples to form dense minibatch.","docstring_tokens":"","code":"def pad_batch(self, x, batch_index, batch_size):\n \"\"\"Pad sparse tensor with subsamples to form dense minibatch.\"\"\"\n if batch_size == 1:\n return x.unsqueeze(0)\n (batch_count, pad) = self.compute_pad_amounts(batch_index, batch_size)\n chunks = x.split(batch_count)\n pad_values = [random_choice(c, n) for (c, n) in zip(chunks, pad)]\n chunks = [torch.cat((c, p)) for (c, p) in zip(chunks, pad_values)]\n return torch.stack(chunks)","code_tokens":"","url":944839} +{"project_name":"zhyhan\/TransPar","file_name":"_util.py","full_name":"check_exits","func_name":"check_exits","docstring":"Check whether `file_name` exists under directory `root`.","docstring_tokens":"","code":"def check_exits(root: str, file_name: str):\n \"\"\"Check whether `file_name` exists under directory `root`. \"\"\"\n if not os.path.exists(os.path.join(root, file_name)):\n print('Dataset directory {} not found under {}'.format(file_name, root))\n exit(-1)","code_tokens":"","url":356050} +{"project_name":"oarriaga\/luvina","file_name":"nltk_backend.py","full_name":"calculate_levenshtein_distance","func_name":"calculate_levenshtein_distance","docstring":"get number of characters that need to be substituted, inserted or deleted to go from token_1 to token_2.","docstring_tokens":"","code":"def calculate_levenshtein_distance(token_1, token_2):\n \"\"\" get number of characters that need to be substituted,\n inserted or deleted to go from token_1 to token_2.\n args:\n token_1: string\n token_2: string\n returns:\n int\n \"\"\"\n return edit_distance(token_1, token_2)","code_tokens":"","url":619839} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"mid_fidelity.py","full_name":"MidFidelity.execute","func_name":"execute","docstring":"Compute results based on mid-fidelity approximation.","docstring_tokens":"","code":"def execute(self):\n \"\"\" Compute results based on mid-fidelity approximation. \"\"\"\n if self.lofi_model is None:\n self.raise_exception('No lofi model plugin', ValueError)\n if self.hifi_model is None:\n self.raise_exception('No hifi model plugin', ValueError)\n if self._lofi_m4model is None:\n inputs = []\n for (mid, low, high) in self.input_mappings:\n inputs.append(low)\n outputs = []\n for (mid, low, high) in self.output_mappings:\n outputs.append(low)\n self._lofi_m4model = wrapper.M4Model(self.lofi_model, inputs, outputs)\n if self._hifi_m4model is None:\n inputs = []\n for (mid, low, high) in self.input_mappings:\n inputs.append(high)\n outputs = []\n for (mid, low, high) in self.output_mappings:\n outputs.append(high)\n self._hifi_m4model = wrapper.M4Model(self.hifi_model, inputs, outputs)\n if self.need_updated_corrections:\n nvars = len(self.input_mappings)\n if self.doe_type == 'ccd':\n if nvars == 1:\n min_samples = 3\n else:\n min_samples = 2 ** nvars + 2 * nvars + 1\n if self.n_samples != min_samples:\n self._logger.warning('Setting n_samples to CCD required value: %d', min_samples)\n self.n_samples = min_samples\n elif self.doe_type == 'lhs':\n min_samples = nvars\n elif self.doe_type == 'rand_lhs':\n min_samples = nvars\n elif self.doe_type == 'oa2':\n min_samples = (nvars - 1) ** 2\n elif self.doe_type == 'oa3':\n min_samples = (nvars - 1) ** 3\n else:\n msg = \"Unknown DOE type '%s'\" % self.doe_type\n self.raise_exception(msg, ValueError)\n if self.n_samples < min_samples:\n self._logger.warning('Updating n_samples to minimum for DOE: %d', min_samples)\n self.n_samples = min_samples\n if self.rs_type == 'linear':\n min_samples = nvars + 1\n elif self.rs_type == 'quadratic':\n min_samples = (nvars ** 2 + 3 * nvars + 2) \/ 2\n elif self.rs_type == 'cubic':\n min_samples = (nvars ** 3 + 6 * nvars ** 2 + 11 * nvars + 6) \/ 6\n elif self.rs_type == 'rbf':\n min_samples = self.n_samples\n elif self.rs_type == 'kriging':\n min_samples = nvars\n else:\n msg = \"Unknown RS type '%s'\" % self.rs_type\n self.raise_exception(msg, ValueError)\n if self.n_samples < min_samples:\n self._logger.warning('Updating n_samples to minimum for RS: %d', min_samples)\n self.n_samples = min_samples\n xlb = []\n xub = []\n for (i, mapping) in enumerate(self.input_mappings):\n trait = self.get_trait(mapping[0]).trait_type\n if isinstance(trait, (Int, Float)):\n low = trait.low\n high = trait.high\n else:\n msg = 'Unexpected input %d trait type %r' % (i, trait)\n self.raise_exception(msg, ValueError)\n xlb.append(low)\n xub.append(high)\n self._midfi_model.Set(hifi=self._hifi_m4model, lofi=self._lofi_m4model, xlb=xlb, xub=xub, nd=nvars, nsamples=self.n_samples, nsamples_test=self.n_samples_test, nf=len(self.output_mappings), n_th_func=None, accu_test_type=self.accuracy_test_type, rs_type=self.rs_type, correct_func_type=self.correction_function, w_h=self.w_h, doe_type=self.doe_type, tolerance=self.tolerance, ntheta=self.ntheta)\n self._midfi_model.Construct_set_run_type(run_type=('doe', 'rs_fast'), iflag_doe=3, iflag_accu=1)\n self.need_updated_corrections = False\n vec = []\n for mapping in self.input_mappings:\n vec.append(self.get(mapping[0]))\n for (i, mapping) in enumerate(self.output_mappings):\n self._logger.debug('Running mid-fidelity model %s %d %s', str(vec), i, str(mapping[0]))\n result = self._midfi_model.RunModel(vec, i)\n self._logger.debug(' result %s', str(result))\n setattr(self, mapping[0], result)","code_tokens":"","url":275287} +{"project_name":"thuml\/Transfer-Learning-Library","file_name":"roi_heads.py","full_name":"fast_rcnn_sample_background","func_name":"fast_rcnn_sample_background","docstring":"Call `fast_rcnn_sample_background_single_image` for all images.","docstring_tokens":"","code":"def fast_rcnn_sample_background(boxes: List[torch.Tensor], scores: List[torch.Tensor], image_shapes: List[Tuple[int, int]], score_thresh: float, nms_thresh: float, topk_per_image: int):\n \"\"\"\n Call `fast_rcnn_sample_background_single_image` for all images.\n\n Args:\n boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic\n boxes for each image. Element i has shape (Ri, K * 4) if doing\n class-specific regression, or (Ri, 4) if doing class-agnostic\n regression, where Ri is the number of predicted objects for image i.\n This is compatible with the output of :meth:`FastRCNNOutputLayers.predict_boxes`.\n scores (list[Tensor]): A list of Tensors of predicted class scores for each image.\n Element i has shape (Ri, K + 1), where Ri is the number of predicted objects\n for image i. Compatible with the output of :meth:`FastRCNNOutputLayers.predict_probs`.\n image_shapes (list[tuple]): A list of (width, height) tuples for each image in the batch.\n score_thresh (float): Only return detections with a confidence score exceeding this\n threshold.\n nms_thresh (float): The threshold to use for box non-maximum suppression. Value in [0, 1].\n topk_per_image (int): The number of top scoring detections to return. Set < 0 to return\n all detections.\n\n Returns:\n instances: (list[Instances]): A list of N instances, one for each image in the batch,\n that stores the background proposals.\n kept_indices: (list[Tensor]): A list of 1D tensor of length of N, each element indicates\n the corresponding boxes\/scores index in [0, Ri) from the input, for image i.\n \"\"\"\n result_per_image = [fast_rcnn_sample_background_single_image(boxes_per_image, scores_per_image, image_shape, score_thresh, nms_thresh, topk_per_image) for (scores_per_image, boxes_per_image, image_shape) in zip(scores, boxes, image_shapes)]\n return ([x[0] for x in result_per_image], [x[1] for x in result_per_image])","code_tokens":"","url":921131} +{"project_name":"gunthercox\/ChatterBot","file_name":"test_api.py","full_name":"ApiTestCase.test_post_unicode","func_name":"test_post_unicode","docstring":"Test that a response is returned.","docstring_tokens":"","code":"def test_post_unicode(self):\n \"\"\"\n Test that a response is returned.\n \"\"\"\n response = self.client.post(self.api_url, data=json.dumps({'text': u'\u00c3\\x98\u00c2\u00b3\u00c3\\x99\u00c2\\x84\u00c3\\x98\u00c2\u00a7\u00c3\\x99\u00c2\\x85'}), content_type='application\/json', format='json')\n self.assertEqual(response.status_code, 200)\n self.assertIn('text', response.json())\n self.assertGreater(len(response.json()['text']), 1)\n self.assertIn('in_response_to', response.json())","code_tokens":"","url":478199} +{"project_name":"meganlsmith\/phyloGAN","file_name":"utils.py","full_name":"sequencetonparrayChunk","func_name":"sequencetonparrayChunk","docstring":"Convert a fasta chunk to a numpy array for downstream operations.","docstring_tokens":"","code":"def sequencetonparrayChunk(empirical_alignments, numTaxa, maxSNPs, Length, Chunks, sampled, Input_Order, Input_Match_dict):\n \"\"\"Convert a fasta chunk to a numpy array for downstream operations.\"\"\"\n all_empirical_regions = []\n all_empirical_pinv = []\n for i in range(len(sampled)):\n current_length = 0\n for j in range(len(sampled[i])):\n charmatrix = empirical_alignments[sampled[i][j]]\n current_length += charmatrix.max_sequence_size\n if current_length > Length:\n to_sample = charmatrix.max_sequence_size - (current_length - Length)\n extracted = charmatrix.export_character_indices([*range(to_sample)])\n charmatrix = extracted\n if j == 0:\n this_charmatrix = charmatrix\n else:\n this_charmatrix = dendropy.DnaCharacterMatrix.concatenate([this_charmatrix, charmatrix])\n tempsim = simulators.Simulator(IQ_Tree=None, Model=None, Chunks=Chunks, Length=Length, Input_Alignments=empirical_alignments, Input_Lengths=None, Input_Order=Input_Order, Input_Match_dict=Input_Match_dict, Temp=None)\n (this_prop_inv, this_matrix_full) = tempsim.sequencetonparray_dendropy(this_charmatrix, Input_Order, maxSNPs, True)\n all_empirical_regions.append(this_matrix_full)\n all_empirical_pinv.append(this_prop_inv)\n all_empirical_regions = np.array(all_empirical_regions)\n all_empirical_pinv = np.array(all_empirical_pinv)\n return (all_empirical_regions, all_empirical_pinv)","code_tokens":"","url":769319} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_encoders.py","full_name":"test_ordinal_encoder_unknown_missing_interaction","func_name":"test_ordinal_encoder_unknown_missing_interaction","docstring":"Check interactions between encode_unknown and missing value encoding.","docstring_tokens":"","code":"def test_ordinal_encoder_unknown_missing_interaction():\n \"\"\"Check interactions between encode_unknown and missing value encoding.\"\"\"\n X = np.array([['a'], ['b'], [np.nan]], dtype=object)\n oe = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=np.nan, encoded_missing_value=-3).fit(X)\n X_trans = oe.transform(X)\n assert_allclose(X_trans, [[0], [1], [-3]])\n X_test = np.array([['c'], [np.nan]], dtype=object)\n X_test_trans = oe.transform(X_test)\n assert_allclose(X_test_trans, [[np.nan], [-3]])\n X_roundtrip = oe.inverse_transform(X_test_trans)\n assert X_roundtrip[0][0] is None\n assert np.isnan(X_roundtrip[1][0])","code_tokens":"","url":364551} +{"project_name":"RingBDStack\/CurvGAN","file_name":"curvgan.py","full_name":"Model.eval_node_classification","func_name":"eval_node_classification","docstring":"Micro- and Macro- F1 Score using LinearRegression.","docstring_tokens":"","code":"def eval_node_classification(self, embs):\n \"\"\"\n Micro- and Macro- F1 Score using LinearRegression.\n \"\"\"\n embs = self.discriminator.manifold.logmap0(embs, self.discriminator.c)\n embeddings = embs.cpu().data.numpy().tolist()\n X = []\n Y = []\n for (idx, key) in enumerate(self.data['labels']):\n X.append(embeddings[idx] + embeddings[idx])\n Y.append(key)\n (X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, test_size=0.2, random_state=123)\n lr = LinearClassifier(self.config)\n lr.train(torch.tensor(X_train), torch.LongTensor(Y_train))\n Y_pred = lr.test(torch.tensor(X_test))\n micro_f1 = f1_score(Y_test, Y_pred, average='micro')\n macro_f1 = f1_score(Y_test, Y_pred, average='macro')\n return (micro_f1, macro_f1)","code_tokens":"","url":508972} +{"project_name":"Farama-Foundation\/Shimmy","file_name":"test_bsuite.py","full_name":"test_bsuite_suite_envs","func_name":"test_bsuite_suite_envs","docstring":"Tests that all BSUITE_ENVS are equal to the known bsuite tasks.","docstring_tokens":"","code":"def test_bsuite_suite_envs():\n \"\"\"Tests that all BSUITE_ENVS are equal to the known bsuite tasks.\"\"\"\n env_ids = [env_id.split('\/')[-1].split('-')[0] for env_id in BSUITE_ENV_IDS]\n assert list(bsuite._bsuite.EXPERIMENT_NAME_TO_ENVIRONMENT.keys()) == env_ids","code_tokens":"","url":901046} +{"project_name":"boslbi92\/dialogue-generation","file_name":"evaluator.py","full_name":"Evaluator.evaluate","func_name":"evaluate","docstring":"Evaluate a model on given dataset and return performance.","docstring_tokens":"","code":"def evaluate(self, model, data):\n \"\"\" Evaluate a model on given dataset and return performance.\n\n Args:\n model (seq2seq.models): model to evaluate\n data (seq2seq.dataset.dataset.Dataset): dataset to evaluate against\n\n Returns:\n loss (float): loss of the given model on the given dataset\n \"\"\"\n model.eval()\n loss = self.loss\n loss.reset()\n match = 0\n total = 0\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n batch_iterator = torchtext.data.BucketIterator(dataset=data, batch_size=self.batch_size, sort=True, sort_key=lambda x: len(x.src), device=device, train=False)\n tgt_vocab = data.fields[seq2seq.tgt_field_name].vocab\n pad = tgt_vocab.stoi[data.fields[seq2seq.tgt_field_name].pad_token]\n with torch.no_grad():\n for batch in batch_iterator:\n (input_variables, input_lengths) = getattr(batch, seq2seq.src_field_name)\n target_variables = getattr(batch, seq2seq.tgt_field_name)\n (decoder_outputs, decoder_hidden, other) = model(input_variables, input_lengths.tolist(), target_variables)\n seqlist = other['sequence']\n for (step, step_output) in enumerate(decoder_outputs):\n target = target_variables[:, step + 1]\n loss.eval_batch(step_output.view(target_variables.size(0), -1), target)\n non_padding = target.ne(pad)\n correct = seqlist[step].view(-1).eq(target).masked_select(non_padding).sum().item()\n match += correct\n total += non_padding.sum().item()\n if total == 0:\n accuracy = float('nan')\n else:\n accuracy = match \/ total\n return (loss.get_loss(), accuracy)","code_tokens":"","url":550144} +{"project_name":"flavioschneider\/rl-transfer-","file_name":"mtsac_metaworld_mt1_pick_place.py","full_name":"mtsac_metaworld_mt1_pick_place","func_name":"mtsac_metaworld_mt1_pick_place","docstring":"Train MTSAC with the MT1 pick-place-v1 environment.","docstring_tokens":"","code":"@click.command()\n@click.option('--seed', 'seed', type=int, default=1)\n@click.option('--timesteps', default=10000000)\n@click.option('--gpu', '_gpu', type=int, default=None)\n@wrap_experiment(snapshot_mode='none')\ndef mtsac_metaworld_mt1_pick_place(ctxt=None, *, seed, timesteps, _gpu):\n \"\"\"Train MTSAC with the MT1 pick-place-v1 environment.\n\n Args:\n ctxt (garage.experiment.ExperimentContext): The experiment\n configuration used by Trainer to create the snapshotter.\n seed (int): Used to seed the random number generator to produce\n determinism.\n _gpu (int): The ID of the gpu to be used (used on multi-gpu machines).\n timesteps (int): Number of timesteps to run.\n\n \"\"\"\n deterministic.set_seed(seed)\n mt1 = metaworld.MT1('pick-place-v1')\n mt1_test = metaworld.MT1('pick-place-v1')\n train_task_sampler = MetaWorldTaskSampler(mt1, 'train', lambda env, _: normalize(env))\n test_task_sampler = MetaWorldTaskSampler(mt1_test, 'train', lambda env, _: normalize(env))\n n_tasks = 50\n train_envs = train_task_sampler.sample(n_tasks)\n env = train_envs[0]()\n test_envs = [env_up() for env_up in test_task_sampler.sample(n_tasks)]\n trainer = Trainer(ctxt)\n policy = TanhGaussianMLPPolicy(env_spec=env.spec, hidden_sizes=[400, 400, 400], hidden_nonlinearity=nn.ReLU, output_nonlinearity=None, min_std=np.exp(-20.0), max_std=np.exp(2.0))\n qf1 = ContinuousMLPQFunction(env_spec=env.spec, hidden_sizes=[400, 400, 400], hidden_nonlinearity=F.relu)\n qf2 = ContinuousMLPQFunction(env_spec=env.spec, hidden_sizes=[400, 400, 400], hidden_nonlinearity=F.relu)\n replay_buffer = PathBuffer(capacity_in_transitions=int(1000000.0))\n sampler = LocalSampler(agents=policy, envs=train_envs, max_episode_length=env.spec.max_episode_length, n_workers=n_tasks, worker_class=FragmentWorker)\n batch_size = int(env.spec.max_episode_length * n_tasks)\n num_evaluation_points = 500\n epochs = timesteps \/\/ batch_size\n epoch_cycles = epochs \/\/ num_evaluation_points\n epochs = epochs \/\/ epoch_cycles\n mtsac = MTSAC(policy=policy, qf1=qf1, qf2=qf2, sampler=sampler, gradient_steps_per_itr=150, eval_env=test_envs, env_spec=env.spec, num_tasks=1, steps_per_epoch=epoch_cycles, replay_buffer=replay_buffer, min_buffer_size=1500, target_update_tau=0.005, discount=0.99, buffer_batch_size=1280)\n if _gpu is not None:\n set_gpu_mode(True, _gpu)\n mtsac.to()\n trainer.setup(algo=mtsac, env=train_envs)\n trainer.train(n_epochs=epochs, batch_size=batch_size)","code_tokens":"","url":861133} +{"project_name":"junshengzhou\/3D-OAE","file_name":"registry.py","full_name":"build_from_cfg","func_name":"build_from_cfg","docstring":"Build a module from config dict.","docstring_tokens":"","code":"def build_from_cfg(cfg, registry, default_args=None):\n \"\"\"Build a module from config dict.\n Args:\n cfg (edict): Config dict. It should at least contain the key \"NAME\".\n registry (:obj:`Registry`): The registry to search the type from.\n Returns:\n object: The constructed object.\n \"\"\"\n if not isinstance(cfg, dict):\n raise TypeError(f'cfg must be a dict, but got {type(cfg)}')\n if 'NAME' not in cfg:\n if default_args is None or 'NAME' not in default_args:\n raise KeyError(f'`cfg` or `default_args` must contain the key \"NAME\", but got {cfg}\\n{default_args}')\n if not isinstance(registry, Registry):\n raise TypeError(f'registry must be an mmcv.Registry object, but got {type(registry)}')\n if not (isinstance(default_args, dict) or default_args is None):\n raise TypeError(f'default_args must be a dict or None, but got {type(default_args)}')\n if default_args is not None:\n cfg = config.merge_new_config(cfg, default_args)\n obj_type = cfg.get('NAME')\n if isinstance(obj_type, str):\n obj_cls = registry.get(obj_type)\n if obj_cls is None:\n raise KeyError(f'{obj_type} is not in the {registry.name} registry')\n elif inspect.isclass(obj_type):\n obj_cls = obj_type\n else:\n raise TypeError(f'type must be a str or valid type, but got {type(obj_type)}')\n try:\n return obj_cls(cfg)\n except Exception as e:\n raise type(e)(f'{obj_cls.__name__}: {e}')","code_tokens":"","url":4472} +{"project_name":"yinyunie\/ScenePriors","file_name":"test_packed_to_padded.py","full_name":"TestPackedToPadded.padded_to_packed_python","func_name":"padded_to_packed_python","docstring":"PyTorch implementation of padded_to_packed function.","docstring_tokens":"","code":"@staticmethod\ndef padded_to_packed_python(inputs, first_idxs, num_inputs, device):\n \"\"\"\n PyTorch implementation of padded_to_packed function.\n \"\"\"\n num_meshes = inputs.size(0)\n D = inputs.shape[2] if inputs.dim() == 3 else 0\n if D == 0:\n inputs_packed = torch.zeros((num_inputs,), device=device)\n else:\n inputs_packed = torch.zeros((num_inputs, D), device=device)\n for m in range(num_meshes):\n s = first_idxs[m]\n if m == num_meshes - 1:\n f = num_inputs\n else:\n f = first_idxs[m + 1]\n inputs_packed[s:f] = inputs[m, :f]\n return inputs_packed","code_tokens":"","url":330059} +{"project_name":"dibyaghosh\/gcsl","file_name":"device.py","full_name":"VrDevice.get_model_name","func_name":"get_model_name","docstring":"Returns the model name of the device.","docstring_tokens":"","code":"def get_model_name(self) -> str:\n \"\"\"Returns the model name of the device.\"\"\"\n return self._get_string(openvr.Prop_RenderModelName_String)","code_tokens":"","url":201841} +{"project_name":"oegedijk\/explainerdashboard","file_name":"explainers.py","full_name":"ClassifierExplainer.plot_cumulative_precision","func_name":"plot_cumulative_precision","docstring":"plot cumulative precision returns a cumulative precision plot, which is a slightly different representation of a lift curve.","docstring_tokens":"","code":"@insert_pos_label\ndef plot_cumulative_precision(self, percentile=None, pos_label=None):\n \"\"\"plot cumulative precision\n\n returns a cumulative precision plot, which is a slightly different\n representation of a lift curve.\n\n Args:\n pos_label: positive label to display, defaults to self.pos_label\n\n Returns:\n plotly fig\n\n \"\"\"\n return plotly_cumulative_precision_plot(self.get_liftcurve_df(pos_label=pos_label), labels=self.labels, percentile=percentile, pos_label=pos_label)","code_tokens":"","url":563737} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"base_case.py","full_name":"ChatBotTestCase.assertIsLength","func_name":"assertIsLength","docstring":"Assert that an iterable has the given length.","docstring_tokens":"","code":"def assertIsLength(self, item, length):\n \"\"\"\n Assert that an iterable has the given length.\n \"\"\"\n if len(item) != length:\n raise AssertionError('Length {} is not equal to {}'.format(len(item), length))","code_tokens":"","url":485816} +{"project_name":"Liusifei\/UVC","file_name":"vis_utils.py","full_name":"aff2flow","func_name":"aff2flow","docstring":"INPUT: - A: a (H*W)*(H*W) affinity matrix - F_size: image feature size OUTPUT: - U: a (2*H*W) flow tensor, U_ij indicates the coordinates of pixel ij in target image.","docstring_tokens":"","code":"def aff2flow(A, F_size, GPU=True):\n \"\"\"\n INPUT:\n - A: a (H*W)*(H*W) affinity matrix\n - F_size: image feature size\n OUTPUT:\n - U: a (2*H*W) flow tensor, U_ij indicates the coordinates of pixel ij in target image.\n \"\"\"\n (b, c, h, w) = F_size\n theta = torch.tensor([[1, 0, 0], [0, 1, 0]])\n theta = theta.unsqueeze(0).repeat(b, 1, 1)\n theta = theta.float()\n grid = torch.nn.functional.affine_grid(theta, F_size)\n if GPU:\n grid = grid.cuda()\n grid = grid.permute(0, 3, 1, 2)\n U = transform(A, grid)\n return (U - grid).permute(0, 2, 3, 1)","code_tokens":"","url":439198} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"open_in_editor.py","full_name":"load_emacs_open_in_editor_bindings","func_name":"load_emacs_open_in_editor_bindings","docstring":"Pressing C-X C-E will open the buffer in an external editor.","docstring_tokens":"","code":"def load_emacs_open_in_editor_bindings():\n \"\"\"\n Pressing C-X C-E will open the buffer in an external editor.\n \"\"\"\n key_bindings = KeyBindings()\n key_bindings.add('c-x', 'c-e', filter=emacs_mode & ~has_selection)(get_by_name('edit-and-execute-command'))\n return key_bindings","code_tokens":"","url":45291} +{"project_name":"hsim13372\/QCompress","file_name":"qae_engine_test.py","full_name":"test_full_no_reset_attributes","func_name":"test_full_no_reset_attributes","docstring":"Test for attributes of full, no reset instance.","docstring_tokens":"","code":"def test_full_no_reset_attributes(full_no_reset_inst):\n \"\"\"Test for attributes of full, no reset instance.\"\"\"\n assert full_no_reset_inst.trash_training == False\n assert full_no_reset_inst.reset == False\n assert full_no_reset_inst.n_in == 2\n assert full_no_reset_inst.n_latent == 1\n assert full_no_reset_inst.n_refresh == 1\n assert full_no_reset_inst.data_size == 5\n test_str = 'QCompress Setting\\n=================\\nQAE type: 2-1-2\\nData size: 5\\nTraining set size: 0\\nTraining mode: full cost function\\n Reset qubits: False\\nCompile program: False\\nForest connection: None\\n Connection type: None'\n assert str(full_no_reset_inst) == test_str","code_tokens":"","url":816016} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"text.py","full_name":"Text.cell_len","func_name":"cell_len","docstring":"Get the number of cells required to render this text.","docstring_tokens":"","code":"@property\ndef cell_len(self) -> int:\n \"\"\"Get the number of cells required to render this text.\"\"\"\n return cell_len(self.plain)","code_tokens":"","url":445100} +{"project_name":"rudranil723\/mini-main","file_name":"crypto.py","full_name":"pbkdf2","func_name":"pbkdf2","docstring":"Return the hash of password using pbkdf2.","docstring_tokens":"","code":"def pbkdf2(password, salt, iterations, dklen=0, digest=None):\n \"\"\"Return the hash of password using pbkdf2.\"\"\"\n if digest is None:\n digest = hashlib.sha256\n dklen = dklen or None\n password = force_bytes(password)\n salt = force_bytes(salt)\n return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)","code_tokens":"","url":316628} +{"project_name":"rfeinman\/tictactoe-reinforcement-learning","file_name":"teacher.py","full_name":"Teacher.corner","func_name":"corner","docstring":"Pick a corner move.","docstring_tokens":"","code":"def corner(self, board):\n \"\"\" Pick a corner move. \"\"\"\n if board[0][0] == 'O' and board[2][2] == '-':\n return (2, 2)\n elif board[2][0] == 'O' and board[0][2] == '-':\n return (0, 2)\n elif board[0][2] == 'O' and board[2][0] == '-':\n return (2, 0)\n elif board[2][2] == 'O' and board[0][0] == '-':\n return (0, 0)\n elif board[0][0] == '-':\n return (0, 0)\n elif board[2][0] == '-':\n return (2, 0)\n elif board[0][2] == '-':\n return (0, 2)\n elif board[2][2] == '-':\n return (2, 2)\n return None","code_tokens":"","url":916622} +{"project_name":"vertical-knowledge\/ripozo","file_name":"tests_utilities.py","full_name":"UtilitiesTestCase.test_make_json_safe","func_name":"test_make_json_safe","docstring":"Tests whether the make_json_safe method correctly returns values.","docstring_tokens":"","code":"def test_make_json_safe(self):\n \"\"\"\n Tests whether the make_json_safe method correctly\n returns values.\n \"\"\"\n resp = make_json_safe(datetime.datetime.now())\n self.assertIsInstance(resp, six.text_type)\n resp = make_json_safe(datetime.date.today())\n self.assertIsInstance(resp, six.text_type)\n resp = make_json_safe(datetime.time())\n self.assertIsInstance(resp, six.text_type)\n resp = make_json_safe(datetime.timedelta(days=1))\n self.assertIsInstance(resp, six.text_type)\n resp = make_json_safe(decimal.Decimal('1.02'))\n self.assertEqual(resp, 1.02)\n self.assertIsInstance(resp, float)\n l = [datetime.time(), datetime.date.today(), datetime.datetime.now()]\n resp = make_json_safe(l)\n self.assertIsInstance(resp, list)\n for item in resp:\n self.assertIsInstance(item, six.text_type)\n d = dict(a=datetime.datetime.now(), b=datetime.time(), c=datetime.date.today())\n resp = make_json_safe(d)\n self.assertIsInstance(resp, dict)\n for (key, value) in six.iteritems(resp):\n self.assertIsInstance(value, six.text_type)","code_tokens":"","url":349168} +{"project_name":"deepmind\/spriteworld","file_name":"demo_ui.py","full_name":"HumanDragAndDropAgent.register_callbacks","func_name":"register_callbacks","docstring":"Register the matplotlib callbacks required by the agent.","docstring_tokens":"","code":"def register_callbacks(self, ui):\n \"\"\"Register the matplotlib callbacks required by the agent.\"\"\"\n\n def _onclick(event):\n if event.inaxes and event.inaxes == ui.ax_image:\n self._click = event.inaxes.transAxes.inverted().transform((event.x, event.y))\n else:\n self._click = None\n return\n ui.register_callback('button_press_event', _onclick)","code_tokens":"","url":897174} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"conftest.py","full_name":"not_daily","func_name":"not_daily","docstring":"Several timedelta-like and DateOffset instances that are _not_ compatible with Daily frequencies.","docstring_tokens":"","code":"@pytest.fixture(params=[np.timedelta64(4, 'h'), pd.Timedelta(hours=23).to_pytimedelta(), pd.Timedelta('23:00:00')] + _common_mismatch)\ndef not_daily(request):\n \"\"\"\n Several timedelta-like and DateOffset instances that are _not_\n compatible with Daily frequencies.\n \"\"\"\n return request.param","code_tokens":"","url":83348} +{"project_name":"instadeepai\/jumanji","file_name":"parametric_distribution.py","full_name":"ParametricDistribution.create_dist","func_name":"create_dist","docstring":"Creates distribution from parameters.","docstring_tokens":"","code":"@abc.abstractmethod\ndef create_dist(self, parameters: chex.Array) -> Distribution:\n \"\"\"Creates distribution from parameters.\"\"\"","code_tokens":"","url":594593} +{"project_name":"deepmind\/dm_control","file_name":"fish.py","full_name":"Swim.get_observation","func_name":"get_observation","docstring":"Returns an observation of joints, target direction and velocities.","docstring_tokens":"","code":"def get_observation(self, physics):\n \"\"\"Returns an observation of joints, target direction and velocities.\"\"\"\n obs = collections.OrderedDict()\n obs['joint_angles'] = physics.joint_angles()\n obs['upright'] = physics.upright()\n obs['target'] = physics.mouth_to_target()\n obs['velocity'] = physics.velocity()\n return obs","code_tokens":"","url":166359} +{"project_name":"matsu0228\/nlp-jp","file_name":"connection.py","full_name":"MWSConnection.get_my_price_for_sku","func_name":"get_my_price_for_sku","docstring":"Returns pricing information for your own offer listings, based on SellerSKU.","docstring_tokens":"","code":"@requires(['MarketplaceId', 'SellerSKUList'])\n@structured_lists('SellerSKUList.SellerSKU')\n@api_action('Products', 20, 10, 'GetMyPriceForSKU')\ndef get_my_price_for_sku(self, request, response, **kw):\n \"\"\"Returns pricing information for your own offer listings, based on SellerSKU.\n \"\"\"\n return self._post_request(request, kw, response)","code_tokens":"","url":784980} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"neural_gpu.py","full_name":"make_dense","func_name":"make_dense","docstring":"Move a batch of targets to a dense 1-hot representation.","docstring_tokens":"","code":"def make_dense(targets, noclass, low_param):\n \"\"\"Move a batch of targets to a dense 1-hot representation.\"\"\"\n low = low_param \/ float(noclass - 1)\n high = 1.0 - low * (noclass - 1)\n targets = tf.cast(targets, tf.int64)\n return tf.one_hot(targets, depth=noclass, on_value=high, off_value=low)","code_tokens":"","url":751366} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"utils.py","full_name":"add_single_jumpstart_tag","func_name":"add_single_jumpstart_tag","docstring":"Adds ``tag_key`` to ``curr_tags`` if ``uri`` corresponds to a JumpStart model.","docstring_tokens":"","code":"def add_single_jumpstart_tag(uri: str, tag_key: enums.JumpStartTag, curr_tags: Optional[List[Dict[str, str]]]) -> Optional[List]:\n \"\"\"Adds ``tag_key`` to ``curr_tags`` if ``uri`` corresponds to a JumpStart model.\n\n Args:\n uri (str): URI which may correspond to a JumpStart model.\n tag_key (enums.JumpStartTag): Custom tag to apply to current tags if the URI\n corresponds to a JumpStart model.\n curr_tags (Optional[List]): Current tags associated with ``Estimator`` or ``Model``.\n \"\"\"\n if is_jumpstart_model_uri(uri):\n if curr_tags is None:\n curr_tags = []\n if not tag_key_in_array(tag_key, curr_tags):\n curr_tags.append({'Key': tag_key, 'Value': uri})\n return curr_tags","code_tokens":"","url":830210} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"dates.py","full_name":"DateLocator.set_tzinfo","func_name":"set_tzinfo","docstring":"Set time zone info.","docstring_tokens":"","code":"def set_tzinfo(self, tz):\n \"\"\"\n Set time zone info.\n \"\"\"\n self.tz = tz","code_tokens":"","url":458} +{"project_name":"cog-imperial\/OMLT","file_name":"formulation.py","full_name":"_PyomoFormulationInterface.block","func_name":"block","docstring":"Return the block associated with this formulation.","docstring_tokens":"","code":"@property\n@abc.abstractmethod\ndef block(self):\n \"\"\"Return the block associated with this formulation.\"\"\"\n pass","code_tokens":"","url":755630} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"box_ops.py","full_name":"jitter_boxes","func_name":"jitter_boxes","docstring":"Jitter the box coordinates by some noise distribution.","docstring_tokens":"","code":"def jitter_boxes(boxes, noise_scale=0.025):\n \"\"\"Jitter the box coordinates by some noise distribution.\n\n Args:\n boxes: a tensor whose last dimension is 4 representing the coordinates of\n boxes in ymin, xmin, ymax, xmax order.\n noise_scale: a python float which specifies the magnitude of noise. The rule\n of thumb is to set this between (0, 0.1]. The default value is found to\n mimic the noisy detections best empirically.\n\n Returns:\n jittered_boxes: a tensor whose shape is the same as `boxes` representing\n the jittered boxes.\n\n Raises:\n ValueError: If the last dimension of boxes is not 4.\n \"\"\"\n if boxes.shape[-1] != 4:\n raise ValueError('boxes.shape[-1] is {:d}, but must be 4.'.format(boxes.shape[-1]))\n with tf.name_scope('jitter_boxes'):\n bbox_jitters = tf.random.normal(tf.shape(boxes), stddev=noise_scale)\n ymin = boxes[..., 0:1]\n xmin = boxes[..., 1:2]\n ymax = boxes[..., 2:3]\n xmax = boxes[..., 3:4]\n width = xmax - xmin\n height = ymax - ymin\n new_center_x = (xmin + xmax) \/ 2.0 + bbox_jitters[..., 0:1] * width\n new_center_y = (ymin + ymax) \/ 2.0 + bbox_jitters[..., 1:2] * height\n new_width = width * tf.math.exp(bbox_jitters[..., 2:3])\n new_height = height * tf.math.exp(bbox_jitters[..., 3:4])\n jittered_boxes = tf.concat([new_center_y - new_height * 0.5, new_center_x - new_width * 0.5, new_center_y + new_height * 0.5, new_center_x + new_width * 0.5], axis=-1)\n return jittered_boxes","code_tokens":"","url":850864} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"state_space_model_test.py","full_name":"TimeDependentTests.test_loop_unrolling","func_name":"test_loop_unrolling","docstring":"Tests running\/restoring from a checkpoint with static unrolling.","docstring_tokens":"","code":"def test_loop_unrolling(self):\n \"\"\"Tests running\/restoring from a checkpoint with static unrolling.\"\"\"\n model = TimeDependentStateSpaceModel(static_unrolling_window_size_threshold=2)\n estimator = estimators.StateSpaceRegressor(model=model)\n times = numpy.arange(100)\n values = numpy.arange(100)\n dataset = {feature_keys.TrainEvalFeatures.TIMES: times, feature_keys.TrainEvalFeatures.VALUES: values}\n train_input_fn = input_pipeline.RandomWindowInputFn(input_pipeline.NumpyReader(dataset), batch_size=16, window_size=2)\n eval_input_fn = input_pipeline.WholeDatasetInputFn(input_pipeline.NumpyReader(dataset))\n estimator.train(input_fn=train_input_fn, max_steps=1)\n estimator.evaluate(input_fn=eval_input_fn, steps=1)","code_tokens":"","url":604724} +{"project_name":"pyelasticsearch\/pyelasticsearch","file_name":"utils_tests.py","full_name":"BulkChunksTests.test_over","func_name":"test_over","docstring":"Make sure action iterators longer than 1 chunk work.","docstring_tokens":"","code":"def test_over(self):\n \"\"\"Make sure action iterators longer than 1 chunk work.\"\"\"\n actions = self.str_xrange(7)\n chunks = bulk_chunks(actions, docs_per_chunk=3)\n self.assertEqual(list(chunks), [['0', '1', '2'], ['3', '4', '5'], ['6']])","code_tokens":"","url":296284} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"movinet_test.py","full_name":"MoViNetTest.test_network_creation","func_name":"test_network_creation","docstring":"Test creation of MoViNet family models.","docstring_tokens":"","code":"def test_network_creation(self):\n \"\"\"Test creation of MoViNet family models.\"\"\"\n tf.keras.backend.set_image_data_format('channels_last')\n network = movinet.Movinet(model_id='a0', causal=True)\n inputs = tf.keras.Input(shape=(8, 128, 128, 3), batch_size=1)\n (endpoints, states) = network(inputs)\n self.assertAllEqual(endpoints['stem'].shape, [1, 8, 64, 64, 8])\n self.assertAllEqual(endpoints['b0\/l0'].shape, [1, 8, 32, 32, 8])\n self.assertAllEqual(endpoints['b1\/l0'].shape, [1, 8, 16, 16, 32])\n self.assertAllEqual(endpoints['b2\/l0'].shape, [1, 8, 8, 8, 56])\n self.assertAllEqual(endpoints['b3\/l0'].shape, [1, 8, 8, 8, 56])\n self.assertAllEqual(endpoints['b4\/l0'].shape, [1, 8, 4, 4, 104])\n self.assertAllEqual(endpoints['head'].shape, [1, 1, 1, 1, 480])\n self.assertNotEmpty(states)","code_tokens":"","url":973364} +{"project_name":"jbwang1997\/CrossKD","file_name":"bbox_head.py","full_name":"BBoxHead.loss_and_target","func_name":"loss_and_target","docstring":"Calculate the loss based on the features extracted by the bbox head.","docstring_tokens":"","code":"def loss_and_target(self, cls_score: Tensor, bbox_pred: Tensor, rois: Tensor, sampling_results: List[SamplingResult], rcnn_train_cfg: ConfigDict, concat: bool=True, reduction_override: Optional[str]=None) -> dict:\n \"\"\"Calculate the loss based on the features extracted by the bbox head.\n\n Args:\n cls_score (Tensor): Classification prediction\n results of all class, has shape\n (batch_size * num_proposals_single_image, num_classes)\n bbox_pred (Tensor): Regression prediction results,\n has shape\n (batch_size * num_proposals_single_image, 4), the last\n dimension 4 represents [tl_x, tl_y, br_x, br_y].\n rois (Tensor): RoIs with the shape\n (batch_size * num_proposals_single_image, 5) where the first\n column indicates batch id of each RoI.\n sampling_results (List[obj:SamplingResult]): Assign results of\n all images in a batch after sampling.\n rcnn_train_cfg (obj:ConfigDict): `train_cfg` of RCNN.\n concat (bool): Whether to concatenate the results of all\n the images in a single batch. Defaults to True.\n reduction_override (str, optional): The reduction\n method used to override the original reduction\n method of the loss. Options are \"none\",\n \"mean\" and \"sum\". Defaults to None,\n\n Returns:\n dict: A dictionary of loss and targets components.\n The targets are only used for cascade rcnn.\n \"\"\"\n cls_reg_targets = self.get_targets(sampling_results, rcnn_train_cfg, concat=concat)\n losses = self.loss(cls_score, bbox_pred, rois, *cls_reg_targets, reduction_override=reduction_override)\n return dict(loss_bbox=losses, bbox_targets=cls_reg_targets)","code_tokens":"","url":491436} +{"project_name":"octree-nn\/ocnn-pytorch","file_name":"octree.py","full_name":"Octree.to_points","func_name":"to_points","docstring":"Converts averaged points in the octree to a point cloud.","docstring_tokens":"","code":"def to_points(self, rescale: bool=True):\n \"\"\" Converts averaged points in the octree to a point cloud.\n\n Args:\n rescale (bool): rescale the xyz coordinates to [-1, 1] if True.\n \"\"\"\n depth = self.depth\n batch_size = self.batch_size\n xyz = self.points[depth]\n batch_id = self.batch_id(depth, nempty=True)\n if xyz is None:\n (x, y, z, batch_id) = self.xyzb(depth, nempty=True)\n xyz = torch.stack([x, y, z], dim=1) + 0.5\n if rescale:\n scale = 2 ** (1 - depth)\n xyz = self.points[depth] * scale - 1.0\n out = Points(xyz, self.normals[depth], self.features[depth], batch_id=batch_id, batch_size=batch_size)\n return out","code_tokens":"","url":249941} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"dataset_manager.py","full_name":"DatasetManager.auto_split","func_name":"auto_split","docstring":"Automatically split the dataset: train --> train\/val.","docstring_tokens":"","code":"@staticmethod\ndef auto_split(task: str, dataset: Dataset, split_ratio: List[Tuple[str, float]]) -> dict:\n \"\"\"Automatically split the dataset: train --> train\/val.\"\"\"\n splitter = Split(dataset, task.lower(), split_ratio)\n return splitter.subsets()","code_tokens":"","url":919059} +{"project_name":"intel\/neural-compressor","file_name":"base.py","full_name":"ProgressivePatternUtils.update_progressive_masks_linear_order","func_name":"update_progressive_masks_linear_order","docstring":"Generate the progressive masks.","docstring_tokens":"","code":"@staticmethod\ndef update_progressive_masks_linear_order(pre_masks, cur_masks, scores, progressive_step, progressive_configs: dict, block_sizes: dict):\n \"\"\"Generate the progressive masks.\n\n Args:\n pre_masks: Dict{\"layer_name\": Tensor} that stores the masks generated after the last pruning step.\n cur_masks: Dict{\"layer_name\": Tensor} that stores the current masks.\n scores: A dict{\"layer_name\": Tensor} that stores the pruning scores of weights.\n progressive_step: An integer representing the number of current step in progressive pruning.\n progressive_configs: A dict that stores configurations of progressive pruning.\n block_size: Dict{\"layer_name\": List or Tuple} that stores the block sizes, only for NxM patterns.\n\n Returns:\n A dict{\"layer_name\": Tensor} that stores the masks generated in progressive pruning.\n \"\"\"\n progressive_steps = progressive_configs['progressive_steps']\n progressive_masks = {}\n new_added_masks = ProgressivePatternUtils.update_new_added_masks(pre_masks, cur_masks)\n for key in pre_masks.keys():\n block_size = block_sizes[key]\n new_added_mask = new_added_masks[key]\n new_added_mask = ProgressivePatternUtils._reshape_orig_to_2dims(new_added_mask)\n shape = new_added_mask.shape\n if block_size[0] >= block_size[1]:\n new_shape = [shape[0] \/\/ block_size[0], progressive_steps, block_size[0] \/\/ progressive_steps, shape[1] \/\/ block_size[1], block_size[1]]\n new_added_mask_reshape = new_added_mask.reshape(new_shape)\n new_added_mask_reshape[:, progressive_step:, :, :, :] = 1.0\n else:\n new_shape = [shape[0] \/\/ block_size[0], block_size[0], shape[1] \/\/ block_size[1], progressive_steps, block_size[1] \/\/ progressive_steps]\n new_added_mask_reshape = new_added_mask.reshape(new_shape)\n new_added_mask_reshape[:, :, :, progressive_step:, :] = 1.0\n new_added_mask = new_added_mask_reshape.reshape(shape)\n new_added_mask = ProgressivePatternUtils._reshape_2dims_to_orig(new_added_mask, pre_masks[key].shape)\n progressive_masks[key] = pre_masks[key] * new_added_mask\n return progressive_masks","code_tokens":"","url":738133} +{"project_name":"LLNL\/Abmarl","file_name":"turn_based_manager.py","full_name":"TurnBasedManager.reset","func_name":"reset","docstring":"Reset the simulation and return the observation of the first agent.","docstring_tokens":"","code":"def reset(self, **kwargs):\n \"\"\"\n Reset the simulation and return the observation of the first agent.\n \"\"\"\n self.done_agents = set((agent.id for agent in self.agents.values() if not isinstance(agent, Agent)))\n self.sim.reset(**kwargs)\n next_agent = next(self.agent_order)\n return {next_agent: self.sim.get_obs(next_agent)}","code_tokens":"","url":405676} +{"project_name":"RasaHQ\/rasa","file_name":"processor.py","full_name":"MessageProcessor.predict_next_with_tracker","func_name":"predict_next_with_tracker","docstring":"Predict the next action for a given conversation state.","docstring_tokens":"","code":"def predict_next_with_tracker(self, tracker: DialogueStateTracker, verbosity: EventVerbosity=EventVerbosity.AFTER_RESTART) -> Optional[Dict[Text, Any]]:\n \"\"\"Predict the next action for a given conversation state.\n\n Args:\n tracker: A tracker representing a conversation state.\n verbosity: Verbosity for the returned conversation state.\n\n Returns:\n The prediction for the next action. `None` if no domain or policies loaded.\n \"\"\"\n if self.model_metadata.training_type == TrainingType.NLU:\n rasa.shared.utils.io.raise_warning('No core model. Skipping action prediction and execution.', docs=DOCS_URL_POLICIES)\n return None\n prediction = self._predict_next_with_tracker(tracker)\n scores = [{'action': a, 'score': p} for (a, p) in zip(self.domain.action_names_or_texts, prediction.probabilities)]\n return {'scores': scores, 'policy': prediction.policy_name, 'confidence': prediction.max_confidence, 'tracker': tracker.current_state(verbosity)}","code_tokens":"","url":836707} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_axes.py","full_name":"test_axline_args","func_name":"test_axline_args","docstring":"Exactly one of *xy2* and *slope* must be specified.","docstring_tokens":"","code":"def test_axline_args():\n \"\"\"Exactly one of *xy2* and *slope* must be specified.\"\"\"\n (fig, ax) = plt.subplots()\n with pytest.raises(TypeError):\n ax.axline((0, 0))\n with pytest.raises(TypeError):\n ax.axline((0, 0), (1, 1), slope=1)\n ax.set_xscale('log')\n with pytest.raises(TypeError):\n ax.axline((0, 0), slope=1)\n ax.set_xscale('linear')\n ax.set_yscale('log')\n with pytest.raises(TypeError):\n ax.axline((0, 0), slope=1)\n ax.set_yscale('linear')\n with pytest.raises(ValueError):\n ax.axline((0, 0), (0, 0))\n plt.draw()","code_tokens":"","url":362775} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"base.py","full_name":"LocalTree.selectComments","func_name":"selectComments","docstring":"Returns the comment tokens for this tree up to the given index.","docstring_tokens":"","code":"def selectComments(self, stop, memo):\n \"\"\" Returns the comment tokens for this tree up to the given index. \"\"\"\n pred = lambda k: k.type in tokens.commentTypes and k.index not in memo\n ctoks = [t for t in self.parser.input.tokens[0:stop] if pred(t)]\n memo.update((t.index for t in ctoks))\n return ctoks","code_tokens":"","url":11354} +{"project_name":"jbwang1997\/CrossKD","file_name":"grid_roi_head.py","full_name":"GridRoIHead.bbox_loss","func_name":"bbox_loss","docstring":"Perform forward propagation and loss calculation of the bbox head on the features of the upstream network.","docstring_tokens":"","code":"def bbox_loss(self, x: Tuple[Tensor], sampling_results: List[SamplingResult], batch_img_metas: Optional[List[dict]]=None) -> dict:\n \"\"\"Perform forward propagation and loss calculation of the bbox head on\n the features of the upstream network.\n\n Args:\n x (tuple[Tensor]): List of multi-level img features.\n sampling_results (list[:obj:`SamplingResult`]): Sampling results.\n batch_img_metas (list[dict], optional): Meta information of each\n image, e.g., image size, scaling factor, etc.\n\n Returns:\n dict[str, Tensor]: Usually returns a dictionary with keys:\n\n - `cls_score` (Tensor): Classification scores.\n - `bbox_pred` (Tensor): Box energies \/ deltas.\n - `bbox_feats` (Tensor): Extract bbox RoI features.\n - `loss_bbox` (dict): A dictionary of bbox loss components.\n \"\"\"\n assert batch_img_metas is not None\n bbox_results = super().bbox_loss(x, sampling_results)\n sampling_results = self._random_jitter(sampling_results, batch_img_metas)\n pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])\n if pos_rois.shape[0] == 0:\n return bbox_results\n grid_feats = self.grid_roi_extractor(x[:self.grid_roi_extractor.num_inputs], pos_rois)\n if self.with_shared_head:\n grid_feats = self.shared_head(grid_feats)\n max_sample_num_grid = self.train_cfg.get('max_num_grid', 192)\n sample_idx = torch.randperm(grid_feats.shape[0])[:min(grid_feats.shape[0], max_sample_num_grid)]\n grid_feats = grid_feats[sample_idx]\n grid_pred = self.grid_head(grid_feats)\n loss_grid = self.grid_head.loss(grid_pred, sample_idx, sampling_results, self.train_cfg)\n bbox_results['loss_bbox'].update(loss_grid)\n return bbox_results","code_tokens":"","url":491383} +{"project_name":"viko-3\/DiffSeqMol","file_name":"distributed_c10d.py","full_name":"recv","func_name":"recv","docstring":"Receives a tensor synchronously.","docstring_tokens":"","code":"def recv(tensor, src=None, group=None, tag=0):\n \"\"\"\n Receives a tensor synchronously.\n\n Args:\n tensor (Tensor): Tensor to fill with received data.\n src (int, optional): Source rank. Will receive from any\n process if unspecified.\n group (ProcessGroup, optional): The process group to work on. If None,\n the default process group will be used.\n tag (int, optional): Tag to match recv with remote send\n\n Returns:\n Sender rank\n -1, if not part of the group\n\n \"\"\"\n _check_single_tensor(tensor, 'tensor')\n if _rank_not_in_group(group):\n return -1\n if group is None:\n pg = _get_default_group()\n else:\n pg = group\n if src is None:\n work = pg.recv_anysource([tensor], tag)\n work.wait()\n src_rank = work._source_rank()\n if group is None or group is GroupMember.WORLD:\n return src_rank\n else:\n return _get_global_rank(pg, src_rank)\n else:\n if group is None or group is GroupMember.WORLD:\n pg.recv([tensor], src, tag).wait()\n else:\n group_src_rank = _get_group_rank(pg, src)\n pg.recv([tensor], group_src_rank, tag).wait()\n return src","code_tokens":"","url":551334} +{"project_name":"yzou2\/CBST","file_name":"mxutil.py","full_name":"load_params_from_file","func_name":"load_params_from_file","docstring":"Load model checkpoint from file.","docstring_tokens":"","code":"def load_params_from_file(path):\n \"\"\"Load model checkpoint from file.\"\"\"\n save_dict = mx.nd.load(path)\n arg_params = {}\n aux_params = {}\n for (k, v) in save_dict.items():\n (tp, name) = k.split(':', 1)\n if tp == 'arg':\n arg_params[name] = v\n if tp == 'aux':\n aux_params[name] = v\n return (arg_params, aux_params)","code_tokens":"","url":457005} +{"project_name":"deepmind\/dm_control","file_name":"control.py","full_name":"Physics.step","func_name":"step","docstring":"Updates the simulation state.","docstring_tokens":"","code":"@abc.abstractmethod\ndef step(self, n_sub_steps=1):\n \"\"\"Updates the simulation state.\n\n Args:\n n_sub_steps: Optional number of times to repeatedly update the simulation\n state. Defaults to 1.\n \"\"\"","code_tokens":"","url":165350} +{"project_name":"gundoganalperen\/DIRAL","file_name":"drl_drqn.py","full_name":"DRQN.get_next_states_user","func_name":"get_next_states_user","docstring":"Receives a batch and returns the the next states of each user :param batch: (batch_size, step_size, (states_step, actions_step, rewards_step, next_state_step)) :return: collected next states.","docstring_tokens":"","code":"def get_next_states_user(self, batch):\n \"\"\"\n Receives a batch and returns the the next states of each user\n :param batch: (batch_size, step_size, (states_step, actions_step, rewards_step, next_state_step))\n :return: collected next states.\n \"\"\"\n next_states = []\n for user in range(self.num_users):\n next_states_per_user = []\n for each in batch:\n next_states_per_batch = []\n for step_i in each:\n next_states_per_step = step_i[3][user]\n next_states_per_batch.append(next_states_per_step)\n next_states_per_user.append(next_states_per_batch)\n next_states.append(next_states_per_user)\n return np.array(next_states)","code_tokens":"","url":551862} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"tix.py","full_name":"Grid.edit_set","func_name":"edit_set","docstring":"Highlights the cell at (x, y) for editing, if the -editnotify command returns True for this cell.","docstring_tokens":"","code":"def edit_set(self, x, y):\n \"\"\"Highlights the cell at (x, y) for editing, if the -editnotify\n command returns True for this cell.\"\"\"\n self.tk.call(self, 'edit', 'set', x, y)","code_tokens":"","url":376658} +{"project_name":"rlberry-py\/rlberry","file_name":"old_finite_mdp.py","full_name":"Old_FiniteMDP.sample","func_name":"sample","docstring":"Sample a transition s' from P(s'|state, action).","docstring_tokens":"","code":"def sample(self, state, action):\n \"\"\"\n Sample a transition s' from P(s'|state, action).\n \"\"\"\n prob = self.P[state, action, :]\n next_state = self.rng.choice(self._states, p=prob)\n reward = self.reward_fn(state, action, next_state)\n done = self.is_terminal(state)\n info = {}\n return (next_state, reward, done, info)","code_tokens":"","url":862262} +{"project_name":"Eric3911\/OpenAGI","file_name":"prompt_base.py","full_name":"Template.from_config","func_name":"from_config","docstring":"load a template from template's configuration node.","docstring_tokens":"","code":"@classmethod\ndef from_config(cls, config: CfgNode, **kwargs):\n \"\"\"load a template from template's configuration node.\n\n Args:\n config (:obj:`CfgNode`): the sub-configuration of template, i.e. config[config.template]\n if config is a global config node.\n kwargs: Other kwargs that might be used in initialize the verbalizer.\n The actual value should match the arguments of __init__ functions.\n \"\"\"\n init_args = signature(cls.__init__).args\n _init_dict = {**convert_cfg_to_dict(config), **kwargs}\n init_dict = {key: _init_dict[key] for key in _init_dict if key in init_args}\n template = cls(**init_dict)\n if hasattr(template, 'from_file'):\n if not hasattr(config, 'file_path'):\n pass\n elif (not hasattr(config, 'text') or config.text is None) and config.file_path is not None:\n if config.choice is None:\n config.choice = 0\n template.from_file(config.file_path, config.choice)\n elif (hasattr(config, 'text') and config.text is not None) and config.file_path is not None:\n raise RuntimeError(\"The text can't be both set from `text` and `file_path`.\")\n return template","code_tokens":"","url":274529} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"test_ticker.py","full_name":"TestLogitFormatter.test_invalid","func_name":"test_invalid","docstring":"Test that invalid value are formatted with empty string without raising exception.","docstring_tokens":"","code":"@pytest.mark.parametrize('x', (-1, -0.5, -0.1, 1.1, 1.5, 2))\ndef test_invalid(self, x):\n \"\"\"\n Test that invalid value are formatted with empty string without\n raising exception.\n \"\"\"\n formatter = mticker.LogitFormatter(use_overline=False)\n formatter.set_locs(self.decade_test)\n s = formatter(x)\n assert s == ''","code_tokens":"","url":451468} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"lenet.py","full_name":"lenet_arg_scope","func_name":"lenet_arg_scope","docstring":"Defines the default lenet argument scope.","docstring_tokens":"","code":"def lenet_arg_scope(weight_decay=0.0):\n \"\"\"Defines the default lenet argument scope.\n\n Args:\n weight_decay: The weight decay to use for regularizing the model.\n\n Returns:\n An `arg_scope` to use for the inception v3 model.\n \"\"\"\n with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), weights_initializer=tf.truncated_normal_initializer(stddev=0.1), activation_fn=tf.nn.relu) as sc:\n return sc","code_tokens":"","url":752893} +{"project_name":"alugupta\/ares","file_name":"utils.py","full_name":"all_reduce","func_name":"all_reduce","docstring":"Gather all tensor results across all GPUs if ddp.","docstring_tokens":"","code":"def all_reduce(tensor, reduction='sum'):\n \"\"\"Gather all tensor results across all GPUs if ddp.\"\"\"\n if not is_distributed():\n return\n op_factory = {'sum': dist.ReduceOp.SUM, 'avg': dist.ReduceOp.AVG}\n assert reduction in op_factory, f'Expected reductions are none, sum and mean, but got {reduction} instead!'\n op = op_factory[reduction.lower()]\n dist.all_reduce(tensor, op)","code_tokens":"","url":402095} +{"project_name":"FedML-AI\/FedML","file_name":"utils.py","full_name":"cifar100_transform","func_name":"cifar100_transform","docstring":"cropping, flipping, and normalizing.","docstring_tokens":"","code":"def cifar100_transform(img_mean, img_std, train=True, crop_size=32):\n \"\"\"cropping, flipping, and normalizing.\"\"\"\n if train:\n return transforms.Compose([transforms.ToPILImage(), transforms.RandomCrop(crop_size), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=img_mean, std=img_std), Cutout(16)])\n else:\n return transforms.Compose([transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize(mean=img_mean, std=img_std)])","code_tokens":"","url":545267} +{"project_name":"ancasag\/ensembleObjectDetection","file_name":"transform.py","full_name":"colvec","func_name":"colvec","docstring":"Create a numpy array representing a column vector.","docstring_tokens":"","code":"def colvec(*args):\n \"\"\"\n Create a numpy array representing a column vector.\n \"\"\"\n return np.array([args]).T","code_tokens":"","url":561952} +{"project_name":"sktime\/sktime","file_name":"test_dropna.py","full_name":"test_dropna_conflicting_arguments","func_name":"test_dropna_conflicting_arguments","docstring":"Test that how and thresh arguments cannot be both set.","docstring_tokens":"","code":"@pytest.mark.parametrize('axis', DropNA.VALID_AXIS_VALUES)\n@pytest.mark.parametrize('how', ['any', 'all'])\n@pytest.mark.parametrize('thresh', [10, 0.5])\n@pytest.mark.parametrize('remember', [None, True, False])\ndef test_dropna_conflicting_arguments(axis, how, thresh, remember):\n \"\"\"Test that how and thresh arguments cannot be both set.\"\"\"\n with pytest.raises(TypeError, match='thresh cannot be set together with how'):\n DropNA(axis=axis, how=str(how), thresh=thresh, remember=remember)","code_tokens":"","url":877867} +{"project_name":"okfn-brasil\/serenata-de-amor","file_name":"fetch_receipts.py","full_name":"Receipt.url","func_name":"url","docstring":"Returns the URL of this receipt at the Lower House server.","docstring_tokens":"","code":"@property\ndef url(self):\n \"\"\"\n Returns the URL of this receipt at the Lower House server.\n \"\"\"\n base = 'http:\/\/www.camara.gov.br\/cota-parlamentar\/documentos\/publ\/'\n recipe = '{base}{applicant_id}\/{year}\/{document_id}.pdf'\n return recipe.format(base=base, applicant_id=self.applicant_id, year=self.year, document_id=self.document_id)","code_tokens":"","url":349803} +{"project_name":"interpretml\/DiCE","file_name":"data.py","full_name":"Data.decide_implementation_type","func_name":"decide_implementation_type","docstring":"Decides if the Data class is for public or private data.","docstring_tokens":"","code":"def decide_implementation_type(self, params):\n \"\"\"Decides if the Data class is for public or private data.\"\"\"\n self.__class__ = decide(params)\n self.__init__(params)","code_tokens":"","url":550166} +{"project_name":"fcjian\/LOCE","file_name":"builder.py","full_name":"build_bbox_coder","func_name":"build_bbox_coder","docstring":"Builder of box coder.","docstring_tokens":"","code":"def build_bbox_coder(cfg, **default_args):\n \"\"\"Builder of box coder.\"\"\"\n return build_from_cfg(cfg, BBOX_CODERS, default_args)","code_tokens":"","url":614219} +{"project_name":"tensorflow\/agents","file_name":"suite_atari.py","full_name":"load","func_name":"load","docstring":"Loads the selected environment and wraps it with the specified wrappers.","docstring_tokens":"","code":"@gin.configurable\ndef load(environment_name: Text, discount: types.Int=1.0, max_episode_steps: Optional[types.Int]=None, gym_env_wrappers: Sequence[types.GymEnvWrapper]=DEFAULT_ATARI_GYM_WRAPPERS, env_wrappers: Sequence[types.PyEnvWrapper]=(), spec_dtype_map: Optional[Dict[gym.Space, np.dtype]]=None) -> py_environment.PyEnvironment:\n \"\"\"Loads the selected environment and wraps it with the specified wrappers.\"\"\"\n if spec_dtype_map is None:\n spec_dtype_map = {gym.spaces.Box: np.uint8}\n gym_spec = gym.spec(environment_name)\n gym_env = gym_spec.make()\n if max_episode_steps is None and gym_spec.max_episode_steps is not None:\n max_episode_steps = gym_spec.max_episode_steps\n return suite_gym.wrap_env(gym_env, discount=discount, max_episode_steps=max_episode_steps, gym_env_wrappers=gym_env_wrappers, time_limit_wrapper=atari_wrappers.AtariTimeLimit, env_wrappers=env_wrappers, spec_dtype_map=spec_dtype_map, auto_reset=False)","code_tokens":"","url":22710} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"cm.py","full_name":"ScalarMappable.changed","func_name":"changed","docstring":"Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal.","docstring_tokens":"","code":"def changed(self):\n \"\"\"\n Call this whenever the mappable is changed to notify all the\n callbackSM listeners to the 'changed' signal.\n \"\"\"\n self.callbacksSM.process('changed', self)\n for key in self._update_dict:\n self._update_dict[key] = True\n self.stale = True","code_tokens":"","url":96344} +{"project_name":"surafelml\/adapt-mnmt","file_name":"config.py","full_name":"load_model_from_file","func_name":"load_model_from_file","docstring":"Loads a model from a configuration file.","docstring_tokens":"","code":"def load_model_from_file(path):\n \"\"\"Loads a model from a configuration file.\n\n Args:\n path: The relative path to the configuration file.\n\n Returns:\n A :class:`opennmt.models.model.Model` instance.\n \"\"\"\n module = load_model_module(path)\n model = module.model()\n del sys.path_importer_cache[os.path.dirname(module.__file__)]\n del sys.modules[module.__name__]\n return model","code_tokens":"","url":407745} +{"project_name":"deep-learning-indaba\/Baobab","file_name":"tests.py","full_name":"ResponseApiTest.test_post_without_nomination","func_name":"test_post_without_nomination","docstring":"Test a typical POST flow.","docstring_tokens":"","code":"def test_post_without_nomination(self):\n \"\"\"Test a typical POST flow.\"\"\"\n self._seed_data()\n response_data = {'application_form_id': self.form.id, 'is_submitted': True, 'answers': [{'question_id': self.question.id, 'value': 'Answer 1'}, {'question_id': self.question2.id, 'value': 'Hello world, this is the 2nd answer.'}]}\n response = self.app.post('\/api\/v1\/response', data=json.dumps(response_data), content_type='application\/json', headers={'Authorization': self.user_data['token']}, query_string={'language': 'en'})\n self.assertEqual(response.status_code, 201)\n data = json.loads(response.data)\n self.assertEqual(data['application_form_id'], self.form.id)\n self.assertEqual(data['user_id'], self.user_data['id'])\n self.assertIsNotNone(data['submitted_timestamp'])\n self.assertTrue(data['is_submitted'])\n self.assertFalse(data['is_withdrawn'])\n self.assertIsNone(data['withdrawn_timestamp'])\n self.assertEqual(len(data['answers']), 2)\n self.assertEqual(data['language'], 'en')\n answer = data['answers'][0]\n self.assertEqual(answer['value'], 'Answer 1')\n self.assertEqual(answer['question_id'], self.question.id)\n answer = data['answers'][1]\n self.assertEqual(answer['value'], 'Hello world, this is the 2nd answer.')\n self.assertEqual(answer['question_id'], self.question2.id)","code_tokens":"","url":94199} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"sentiment_main.py","full_name":"run_model","func_name":"run_model","docstring":"Run training loop and an evaluation at the end.","docstring_tokens":"","code":"def run_model(dataset_name, emb_dim, voc_size, sen_len, hid_dim, batch_size, epochs):\n \"\"\"Run training loop and an evaluation at the end.\n\n Args:\n dataset_name: Dataset name to be trained and evaluated.\n emb_dim: The dimension of the Embedding layer.\n voc_size: The number of the most frequent tokens\n to be used from the corpus.\n sen_len: The number of words in each sentence.\n Longer sentences get cut, shorter ones padded.\n hid_dim: The dimension of the Embedding layer.\n batch_size: The size of each batch during training.\n epochs: The number of the iteration over the training set for training.\n \"\"\"\n model = sentiment_model.CNN(emb_dim, voc_size, sen_len, hid_dim, dataset.get_num_class(dataset_name), _DROPOUT_RATE)\n model.summary()\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n tf.logging.info('Loading the data')\n (x_train, y_train, x_test, y_test) = dataset.load(dataset_name, voc_size, sen_len)\n model.fit(x_train, y_train, batch_size=batch_size, validation_split=0.4, epochs=epochs)\n score = model.evaluate(x_test, y_test, batch_size=batch_size)\n tf.logging.info('Score: {}'.format(score))","code_tokens":"","url":752696} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"pydoc.py","full_name":"HTMLDoc.index","func_name":"index","docstring":"Generate an HTML index for a directory of modules.","docstring_tokens":"","code":"def index(self, dir, shadowed=None):\n \"\"\"Generate an HTML index for a directory of modules.\"\"\"\n modpkgs = []\n if shadowed is None:\n shadowed = {}\n for (importer, name, ispkg) in pkgutil.iter_modules([dir]):\n if any((55296 <= ord(ch) <= 57343 for ch in name)):\n continue\n modpkgs.append((name, '', ispkg, name in shadowed))\n shadowed[name] = 1\n modpkgs.sort()\n contents = self.multicolumn(modpkgs, self.modpkglink)\n return self.bigsection(dir, '#ffffff', '#ee77aa', contents)","code_tokens":"","url":281233} +{"project_name":"facebookresearch\/CompilerGym","file_name":"minimize_trajectory_test.py","full_name":"test_random_minimization_no_effect","func_name":"test_random_minimization_no_effect","docstring":"Test random minimization when there's no improvement to be had.","docstring_tokens":"","code":"def test_random_minimization_no_effect():\n \"\"\"Test random minimization when there's no improvement to be had.\"\"\"\n env = MockEnv(actions=list(range(10)))\n minimized = list(range(10))\n\n def hypothesis(env):\n return env.actions == minimized\n list(mt.random_minimization(env, hypothesis))\n assert env.actions == minimized","code_tokens":"","url":126006} +{"project_name":"BMIRDS\/deepslide","file_name":"utils_processing.py","full_name":"gen_val_patches","func_name":"gen_val_patches","docstring":"Generates all patches for subfolders in the validation set.","docstring_tokens":"","code":"def gen_val_patches(input_folder: Path, output_folder: Path, overlap_factor: float, num_workers: int, patch_size: int, purple_threshold: int, purple_scale_size: int, image_ext: str, type_histopath: bool) -> None:\n \"\"\"\n Generates all patches for subfolders in the validation set.\n\n Args:\n input_folder: Folder containing the subfolders containing WSI.\n output_folder: Folder to save the patches to.\n overlap_factor: The amount of overlap between patches.\n num_workers: Number of workers to use for IO.\n patch_size: Size of the patches extracted from the WSI.\n purple_threshold: Number of purple points for region to be considered purple.\n purple_scale_size: Scalar to use for reducing image to check for purple.\n image_ext: Image extension for saving patches.\n type_histopath: Only look for purple histopathology images and filter whitespace.\n \"\"\"\n subfolders = get_subfolder_paths(folder=input_folder)\n print(f'{len(subfolders)} subfolders found from {input_folder}')\n for input_subfolder in subfolders:\n produce_patches(input_folder=input_subfolder, output_folder=output_folder.joinpath(input_subfolder.name), inverse_overlap_factor=overlap_factor, by_folder=False, num_workers=num_workers, patch_size=patch_size, purple_threshold=purple_threshold, purple_scale_size=purple_scale_size, image_ext=image_ext, type_histopath=type_histopath)\n print('\\nfinished all folders\\n')","code_tokens":"","url":539821} +{"project_name":"voxel51\/fiftyone","file_name":"runs.py","full_name":"Run.list_runs","func_name":"list_runs","docstring":"Returns the list of run keys on the given collection.","docstring_tokens":"","code":"@classmethod\ndef list_runs(cls, samples, type=None, **kwargs):\n \"\"\"Returns the list of run keys on the given collection.\n\n Args:\n samples: a :class:`fiftyone.core.collections.SampleCollection`\n type (None): a :class:`fiftyone.core.runs.Run` type. If provided,\n only runs that are a subclass of this type are included\n **kwargs: optional config parameters to match\n\n Returns:\n a list of run keys\n \"\"\"\n run_docs = cls._get_run_docs(samples)\n if etau.is_str(type):\n type = etau.get_class(type)\n if type is not None or kwargs:\n keys = []\n for key in run_docs.keys():\n try:\n run_info = cls.get_run_info(samples, key)\n config = run_info.config\n except:\n logger.warning(\"Failed to load info for %s with key '%s'\", cls._run_str(), key)\n continue\n if type is not None and (not issubclass(config.run_cls, type)):\n continue\n if kwargs and any((getattr(config, key, None) != value for (key, value) in kwargs.items())):\n continue\n keys.append(key)\n else:\n keys = run_docs.keys()\n return sorted(keys)","code_tokens":"","url":583236} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"structural_ensemble_test.py","full_name":"StructuralEnsembleEstimatorTests.test_exogenous_input","func_name":"test_exogenous_input","docstring":"Test that no errors are raised when using exogenous features.","docstring_tokens":"","code":"def test_exogenous_input(self):\n \"\"\"Test that no errors are raised when using exogenous features.\"\"\"\n dtype = dtypes.float64\n times = [1, 2, 3, 4, 5, 6]\n values = [[0.01], [5.1], [5.21], [0.3], [5.41], [0.5]]\n feature_a = [['off'], ['on'], ['on'], ['off'], ['on'], ['off']]\n sparse_column_a = feature_column.sparse_column_with_keys(column_name='feature_a', keys=['on', 'off'])\n one_hot_a = layers.one_hot_column(sparse_id_column=sparse_column_a)\n regressor = estimators.StructuralEnsembleRegressor(periodicities=[], num_features=1, moving_average_order=0, exogenous_feature_columns=[one_hot_a], dtype=dtype)\n features = {TrainEvalFeatures.TIMES: times, TrainEvalFeatures.VALUES: values, 'feature_a': feature_a}\n train_input_fn = input_pipeline.RandomWindowInputFn(input_pipeline.NumpyReader(features), window_size=6, batch_size=1)\n regressor.train(input_fn=train_input_fn, steps=1)\n eval_input_fn = input_pipeline.WholeDatasetInputFn(input_pipeline.NumpyReader(features))\n evaluation = regressor.evaluate(input_fn=eval_input_fn, steps=1)\n predict_input_fn = input_pipeline.predict_continuation_input_fn(evaluation, times=[[7, 8, 9]], exogenous_features={'feature_a': [[['on'], ['off'], ['on']]]})\n regressor.predict(input_fn=predict_input_fn)","code_tokens":"","url":604725} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"math2html.py","full_name":"LimitCommand.parsebit","func_name":"parsebit","docstring":"Parse a limit command.","docstring_tokens":"","code":"def parsebit(self, pos):\n \"\"\"Parse a limit command.\"\"\"\n pieces = BigSymbol(self.translated).getpieces()\n self.output = TaggedOutput().settag('span class=\"limits\"')\n for piece in pieces:\n self.contents.append(TaggedBit().constant(piece, 'span class=\"limit\"'))","code_tokens":"","url":395331} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"pdf.py","full_name":"PDFExporter.clean_temp_files","func_name":"clean_temp_files","docstring":"Remove temporary files created by xelatex\/bibtex.","docstring_tokens":"","code":"def clean_temp_files(self, filename):\n \"\"\"Remove temporary files created by xelatex\/bibtex.\"\"\"\n self.log.info('Removing temporary LaTeX files')\n filename = os.path.splitext(filename)[0]\n for ext in self.temp_file_exts:\n try:\n os.remove(filename + ext)\n except OSError:\n pass","code_tokens":"","url":980199} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"control_flow_ops.py","full_name":"ControlFlowContext.Enter","func_name":"Enter","docstring":"Enter this control flow context.","docstring_tokens":"","code":"def Enter(self):\n \"\"\"Enter this control flow context.\"\"\"\n graph = ops.get_default_graph()\n self._context_stack.append(graph._get_control_flow_context())\n graph._set_control_flow_context(self)","code_tokens":"","url":337160} +{"project_name":"loicmarie\/hands-detection","file_name":"ptn_rotator.py","full_name":"model","func_name":"model","docstring":"Model for performing rotation.","docstring_tokens":"","code":"def model(poses, actions, params, is_training):\n \"\"\"Model for performing rotation.\"\"\"\n del is_training\n return bilinear(poses, actions, params.z_dim)","code_tokens":"","url":575168} +{"project_name":"google\/deepvariant","file_name":"runtime_by_region_vis.py","full_name":"make_report","func_name":"make_report","docstring":"Reads data, creates charts, and composes the charts into an HTML report.","docstring_tokens":"","code":"def make_report(input_path: str, title: str, html_output: tf.io.gfile.GFile) -> None:\n \"\"\"Reads data, creates charts, and composes the charts into an HTML report.\n\n Args:\n input_path: Path of the input TSV file (or sharded files).\n title: Title to put at the top of the report.\n html_output: Writable file object where output will be written.\n \"\"\"\n (df, by_task) = read_data_and_make_dataframes(input_path)\n charts = make_all_charts(df, by_task)\n subtitle = f\"Runtime profiling for make_examples on {len(df)} regions across {len(by_task)} task{('(s)' if len(by_task) > 1 else '')}\"\n dashboard_utils.create_html_report(specs=charts, html_output=html_output, title=title, subtitle=subtitle)","code_tokens":"","url":540435} +{"project_name":"huawei-noah\/xingtian","file_name":"loss.py","full_name":"LossConfig.from_json","func_name":"from_json","docstring":"Restore config from a dictionary or a file.","docstring_tokens":"","code":"@classmethod\ndef from_json(cls, data, skip_check=True):\n \"\"\"Restore config from a dictionary or a file.\"\"\"\n cls = super(LossConfig, cls).from_json(data, skip_check)\n if 'params' not in data:\n cls.params = {}\n return cls","code_tokens":"","url":968499} +{"project_name":"ajMIT95\/MIT_Artificial_Intelligence_Labs","file_name":"lab0.py","full_name":"remove_from_string","func_name":"remove_from_string","docstring":"Given a string and a list of individual letters, returns a new string which is the same as the old one except all occurrences of those letters have been removed from it.","docstring_tokens":"","code":"def remove_from_string(string, letters):\n \"\"\"Given a string and a list of individual letters, returns a new string\n which is the same as the old one except all occurrences of those letters\n have been removed from it.\"\"\"\n string_copy = string\n for letter in letters:\n string_copy = string_copy.replace(letter, '')\n return string_copy","code_tokens":"","url":239181} +{"project_name":"thaines\/helit","file_name":"lda.py","full_name":"VLDA.lockDoc","func_name":"lockDoc","docstring":"Given a document identifier this locks it, or unlocks it if lock==False - can be used for repeated calls to solve to reduce computation if desired.","docstring_tokens":"","code":"def lockDoc(self, doc, lock=True):\n \"\"\"Given a document identifier this locks it, or unlocks it if lock==False - can be used for repeated calls to solve to reduce computation if desired.\"\"\"\n if lock:\n self.docLock.add(doc)\n elif doc in self.docLock:\n self.docLoc.remove(doc)","code_tokens":"","url":592189} +{"project_name":"ivan-alles\/localizer","file_name":"train.py","full_name":"MultiProcessBatchGenerator.stop_generation","func_name":"stop_generation","docstring":"Wait for completion of all running jobs.","docstring_tokens":"","code":"def stop_generation(self):\n \"\"\"\n Wait for completion of all running jobs.\n \"\"\"\n if self._process_count == 0:\n return\n while len(self._jobs) > 0:\n self._wait_for_ready_job()","code_tokens":"","url":602865} +{"project_name":"RasaHQ\/rasa","file_name":"events.py","full_name":"LegacyFormValidation.fingerprint","func_name":"fingerprint","docstring":"Returns hash of the event.","docstring_tokens":"","code":"def fingerprint(self) -> Text:\n \"\"\"Returns hash of the event.\"\"\"\n d = self.as_dict()\n d['event'] = self.type_name\n del d['timestamp']\n return rasa.shared.utils.io.get_dictionary_fingerprint(d)","code_tokens":"","url":837486} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"generic.py","full_name":"NDFrame.get_dtype_counts","func_name":"get_dtype_counts","docstring":"Return the counts of dtypes in this object.","docstring_tokens":"","code":"def get_dtype_counts(self):\n \"\"\"Return the counts of dtypes in this object.\"\"\"\n from pandas import Series\n return Series(self._data.get_dtype_counts())","code_tokens":"","url":717648} +{"project_name":"KaiyangZhou\/Dassl.pytorch","file_name":"trainer.py","full_name":"SimpleTrainer.test","func_name":"test","docstring":"A generic testing pipeline.","docstring_tokens":"","code":"@torch.no_grad()\ndef test(self, split=None):\n \"\"\"A generic testing pipeline.\"\"\"\n self.set_model_mode('eval')\n self.evaluator.reset()\n if split is None:\n split = self.cfg.TEST.SPLIT\n if split == 'val' and self.val_loader is not None:\n data_loader = self.val_loader\n else:\n split = 'test'\n data_loader = self.test_loader\n print(f'Evaluate on the *{split}* set')\n for (batch_idx, batch) in enumerate(tqdm(data_loader)):\n (input, label) = self.parse_batch_test(batch)\n output = self.model_inference(input)\n self.evaluator.process(output, label)\n results = self.evaluator.evaluate()\n for (k, v) in results.items():\n tag = f'{split}\/{k}'\n self.write_scalar(tag, v, self.epoch)\n return list(results.values())[0]","code_tokens":"","url":126721} +{"project_name":"MushroomRL\/mushroom-rl","file_name":"dataset.py","full_name":"select_random_samples","func_name":"select_random_samples","docstring":"Return the randomly picked desired number of samples in the provided dataset.","docstring_tokens":"","code":"def select_random_samples(dataset, n_samples, parse=False):\n \"\"\"\n Return the randomly picked desired number of samples in the provided\n dataset.\n\n Args:\n dataset (list): the dataset to consider;\n n_samples (int): the number of samples to pick from the dataset;\n parse (bool, False): whether to parse the dataset to return.\n\n Returns:\n A subset of the dataset containing randomly picked ``n_samples``\n samples.\n\n \"\"\"\n assert n_samples >= 0, 'Number of samples must be greater than or equalto zero.'\n if n_samples == 0:\n return np.array([[]])\n dataset = np.array(dataset, dtype=object)\n idxs = np.random.randint(dataset.shape[0], size=n_samples)\n sub_dataset = dataset[idxs, ...]\n return sub_dataset if not parse else parse_dataset(sub_dataset)","code_tokens":"","url":266114} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"single_task_trainer.py","full_name":"SingleTaskTrainer.train_loop_begin","func_name":"train_loop_begin","docstring":"Actions to take once, at the beginning of each train loop.","docstring_tokens":"","code":"def train_loop_begin(self):\n \"\"\"Actions to take once, at the beginning of each train loop.\"\"\"\n self.train_loss.reset_states()\n for metric in self.metrics:\n metric.reset_states()","code_tokens":"","url":973855} +{"project_name":"Dsajeet\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"nb_007a.py","full_name":"data_from_texttokens","func_name":"data_from_texttokens","docstring":"Creates a `DataBunch` from tokens and labels.","docstring_tokens":"","code":"def data_from_texttokens(path: PathOrStr, train: str='train', valid: str='valid', test: Optional[str]=None, data_func: DataFunc=standard_data, vocab: Vocab=None, **kwargs) -> DataBunch:\n \"\"\"Creates a `DataBunch` from tokens and labels.\"\"\"\n path = Path(path)\n (txt_kwargs, kwargs) = extract_kwargs(['max_vocab', 'chunksize', 'min_freq', 'n_labels', 'tok_suff', 'lbl_suff'], kwargs)\n train_ds = TextDataset.from_tokens(path, train, vocab=vocab, **txt_kwargs)\n datasets = [train_ds, TextDataset.from_tokens(path, valid, vocab=train_ds.vocab, **txt_kwargs)]\n if test:\n datasets.append(TextDataset.from_tokens(path, test, vocab=train_ds.vocab, **txt_kwargs))\n return data_func(datasets, path, **kwargs)","code_tokens":"","url":81608} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"server_lib.py","full_name":"ClusterSpec.num_tasks","func_name":"num_tasks","docstring":"Returns the number of tasks defined in the given job.","docstring_tokens":"","code":"def num_tasks(self, job_name):\n \"\"\"Returns the number of tasks defined in the given job.\n\n Args:\n job_name: The string name of a job in this cluster.\n\n Returns:\n The number of tasks defined in the given job.\n\n Raises:\n ValueError: If `job_name` does not name a job in this cluster.\n \"\"\"\n try:\n job = self._cluster_spec[job_name]\n except KeyError:\n raise ValueError('No such job in cluster: %r' % job_name)\n return len(job)","code_tokens":"","url":339729} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"update_version.py","full_name":"Version.parse_from_string","func_name":"parse_from_string","docstring":"Returns version object from Semver string.","docstring_tokens":"","code":"@staticmethod\ndef parse_from_string(string, version_type):\n \"\"\"Returns version object from Semver string.\n\n Args:\n string: version string\n version_type: version parameter\n\n Raises:\n RuntimeError: If the version string is not valid.\n \"\"\"\n if not re.search('[0-9]+\\\\.[0-9]+\\\\.[a-zA-Z0-9]+', string):\n raise RuntimeError('Invalid version string: %s' % string)\n (major, minor, extension) = string.split('.', 2)\n extension_split = extension.split('-', 1)\n patch = extension_split[0]\n if len(extension_split) == 2:\n identifier_string = '-' + extension_split[1]\n else:\n identifier_string = ''\n return Version(major, minor, patch, identifier_string, version_type)","code_tokens":"","url":606700} +{"project_name":"voxel51\/fiftyone","file_name":"dataset.py","full_name":"Dataset.slug","func_name":"slug","docstring":"The slug of the dataset.","docstring_tokens":"","code":"@property\ndef slug(self):\n \"\"\"The slug of the dataset.\"\"\"\n return self._doc.slug","code_tokens":"","url":582865} +{"project_name":"intel\/neural-compressor","file_name":"mse.py","full_name":"MSETuneStrategy.mse_impact_lst","func_name":"mse_impact_lst","docstring":"Calculate and generate the MSE impact list.","docstring_tokens":"","code":"def mse_impact_lst(self, op_list: List, fp32_model, best_qmodel):\n \"\"\"Calculate and generate the MSE impact list.\n\n Args:\n op_list (List[Tuple(str, str)]): List of ops in format of [(op_name, op_type), ...].\n fp32_model (Model): The original FP32 model before quantization.\n current_best_model (Model): The currently best quantized model.\n\n Returns:\n ordered_op_name_types (List[Tuple(str, str)]): The sorted list of ops by its MSE\n impaction, in the same format of 'op_list'.\n \"\"\"\n op_name_lst = [element[0] for element in op_list]\n op_mapping = {}\n for (op_name, op_type) in list(op_list):\n op_mapping[op_name] = (op_name, op_type)\n current_best_tune_cfg = self._tune_cfg_converter(self.cur_best_tuning_cfg)\n fp32_dump_content = self.adaptor.inspect_tensor(fp32_model, self.calib_dataloader, op_name_lst, [1], inspect_type='activation', save_to_disk=True, save_path='.\/nc_workspace\/', quantization_cfg=current_best_tune_cfg)\n fp32_tensor_dict = fp32_dump_content['activation'][0]\n best_qmodel = self.adaptor.quantize(current_best_tune_cfg, self.model, self.calib_dataloader, self.q_func)\n quant_dump_content = self.adaptor.inspect_tensor(best_qmodel, self.calib_dataloader, op_name_lst, [1], inspect_type='activation', save_to_disk=True, save_path='.\/nc_workspace\/', quantization_cfg=current_best_tune_cfg)\n dequantize_tensor_dict = quant_dump_content['activation'][0]\n ops_mse = {op: self._mse_metric_gap(list(fp32_tensor_dict[op].values())[0], list(dequantize_tensor_dict[op].values())[0]) for op in fp32_tensor_dict}\n ordered_op_names = sorted(ops_mse.keys(), key=lambda key: ops_mse[key], reverse=self.higher_is_better)\n ordered_op_name_types = [op_mapping[name] for name in ordered_op_names]\n return ordered_op_name_types","code_tokens":"","url":738739} +{"project_name":"jxhe\/struct-learning-with-flow","file_name":"graph.py","full_name":"Graph.get_node","func_name":"get_node","docstring":"Return any node of the graph.","docstring_tokens":"","code":"def get_node(self):\n \"\"\"Return any node of the graph.\n \"\"\"\n return self.nodes[0]","code_tokens":"","url":359938} +{"project_name":"nbsnyder\/OldEnglishNLP","file_name":"Utils.py","full_name":"removePunctuationFromWord","func_name":"removePunctuationFromWord","docstring":"Removes punctuation characters from a word.","docstring_tokens":"","code":"def removePunctuationFromWord(word: str):\n \"\"\"Removes punctuation characters from a word.\"\"\"\n return ''.join((char for char in word if char not in removePunctuationFromWord.unwantedChars))","code_tokens":"","url":755575} +{"project_name":"muhanzhang\/D-VAE","file_name":"test_opt.py","full_name":"test_opt_gpujoin_joinvectors_negativeaxes","func_name":"test_opt_gpujoin_joinvectors_negativeaxes","docstring":"Test that negative axis concatenation works as expected.","docstring_tokens":"","code":"def test_opt_gpujoin_joinvectors_negativeaxes():\n \"\"\"\n Test that negative axis concatenation works as expected.\n \"\"\"\n rng = numpy.random.RandomState(22)\n x1 = rng.rand(5)\n x2 = rng.rand(10)\n t1 = cuda.shared_constructor(numpy.asarray(x1, 'float32'))\n t2 = cuda.shared_constructor(numpy.asarray(x2, 'float32'))\n t = tensor.concatenate([t1, t2], axis=-1)\n f = theano.function(inputs=[], outputs=t)\n assert numpy.allclose(f(), numpy.concatenate([x1, x2], axis=-1))\n x1 = rng.rand(5, 10)\n x2 = rng.rand(10, 10)\n t1 = cuda.shared_constructor(numpy.asarray(x1, 'float32'))\n t2 = cuda.shared_constructor(numpy.asarray(x2, 'float32'))\n t = tensor.concatenate([t1, t2], axis=-2)\n f = theano.function(inputs=[], outputs=t)\n assert numpy.allclose(f(), numpy.concatenate([x1, x2], axis=-2))\n try:\n t = tensor.concatenate([t1, t2], axis=-1)\n f = theano.function(inputs=[], outputs=t)\n f()\n assert False\n except ValueError:\n assert True\n try:\n t = tensor.concatenate([t1, t2], axis=-3)\n f = theano.function(inputs=[], outputs=t)\n f()\n assert False\n except IndexError:\n assert True","code_tokens":"","url":525184} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"bulk_component.py","full_name":"extract_fixed_feature_ids","func_name":"extract_fixed_feature_ids","docstring":"Extracts fixed feature IDs.","docstring_tokens":"","code":"def extract_fixed_feature_ids(comp, state, stride):\n \"\"\"Extracts fixed feature IDs.\n\n Args:\n comp: Component whose fixed feature IDs we wish to extract.\n state: Live MasterState object for the component.\n stride: Tensor containing current batch * beam size.\n\n Returns:\n state handle: Updated state handle to be used after this call.\n ids: List of [stride * num_steps, 1] feature IDs per channel. Missing IDs\n (e.g., due to batch padding) are set to -1.\n \"\"\"\n num_channels = len(comp.spec.fixed_feature)\n if not num_channels:\n return (state.handle, [])\n for feature_spec in comp.spec.fixed_feature:\n check.Eq(feature_spec.size, 1, 'All features must have size=1')\n check.Lt(feature_spec.embedding_dim, 0, 'All features must be non-embedded')\n (state.handle, indices, ids, _, num_steps) = dragnn_ops.bulk_fixed_features(state.handle, component=comp.name, num_channels=num_channels)\n size = stride * num_steps\n fixed_ids = []\n for (channel, feature_spec) in enumerate(comp.spec.fixed_feature):\n tf.logging.info('[%s] Adding fixed feature IDs \"%s\"', comp.name, feature_spec.name)\n sums = tf.unsorted_segment_sum(ids[channel] + 1, indices[channel], size) - 1\n sums = tf.expand_dims(sums, axis=1)\n fixed_ids.append(network_units.NamedTensor(sums, feature_spec.name, dim=1))\n return (state.handle, fixed_ids)","code_tokens":"","url":27996} +{"project_name":"AndrejOrsula\/drl_grasping","file_name":"gazebo.py","full_name":"get_model_orientation","func_name":"get_model_orientation","docstring":"Return orientation of model's link that is represented as wxyz quaternion or xyzw based on the passed argument `xyzw`.","docstring_tokens":"","code":"def get_model_orientation(world: World, model: Union[ModelWrapper, str], link: Union[Link, str, None]=None, xyzw: bool=False) -> Tuple[float, float, float, float]:\n \"\"\"\n Return orientation of model's link that is represented as wxyz quaternion or xyzw based on the passed argument `xyzw`.\n \"\"\"\n if isinstance(model, str):\n model = world.to_gazebo().get_model(model).to_gazebo()\n if link is None:\n link = model.get_link(link_name=model.link_names()[0])\n elif isinstance(link, str):\n link = model.get_link(link_name=link)\n quat = link.orientation()\n if xyzw:\n quat = quat_to_xyzw(quat)\n return quat","code_tokens":"","url":553084} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"feature_aggregation_similarity.py","full_name":"SimilarityAggregatedRepresentation.ComputeSimilarity","func_name":"ComputeSimilarity","docstring":"Computes similarity between aggregated descriptors.","docstring_tokens":"","code":"def ComputeSimilarity(self, aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1=None, feature_visual_words_2=None):\n \"\"\"Computes similarity between aggregated descriptors.\n\n Args:\n aggregated_descriptors_1: 1-D NumPy array.\n aggregated_descriptors_2: 1-D NumPy array.\n feature_visual_words_1: Used only for ASMK\/ASMK* aggregation type. 1-D\n sorted NumPy integer array denoting visual words corresponding to\n `aggregated_descriptors_1`.\n feature_visual_words_2: Used only for ASMK\/ASMK* aggregation type. 1-D\n sorted NumPy integer array denoting visual words corresponding to\n `aggregated_descriptors_2`.\n\n Returns:\n similarity: Float. The larger, the more similar.\n\n Raises:\n ValueError: If aggregation type is invalid.\n \"\"\"\n if self._aggregation_type == _VLAD:\n similarity = np.dot(aggregated_descriptors_1, aggregated_descriptors_2)\n elif self._aggregation_type == _ASMK:\n similarity = self._AsmkSimilarity(aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1, feature_visual_words_2, binarized=False)\n elif self._aggregation_type == _ASMK_STAR:\n similarity = self._AsmkSimilarity(aggregated_descriptors_1, aggregated_descriptors_2, feature_visual_words_1, feature_visual_words_2, binarized=True)\n else:\n raise ValueError('Invalid aggregation type: %d' % self._aggregation_type)\n return similarity","code_tokens":"","url":974233} +{"project_name":"facebookresearch\/minihack","file_name":"test_envs.py","full_name":"TestGymEnv.make_cwd_tmp","func_name":"make_cwd_tmp","docstring":"Makes cwd point to the test's tmpdir.","docstring_tokens":"","code":"@pytest.fixture(autouse=True)\ndef make_cwd_tmp(self, tmpdir):\n \"\"\"Makes cwd point to the test's tmpdir.\"\"\"\n with tmpdir.as_cwd():\n yield","code_tokens":"","url":670768} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"png.py","full_name":"Test.testRGBtoRGBA","func_name":"testRGBtoRGBA","docstring":"asRGBA8() on colour type 2 source.","docstring_tokens":"","code":"def testRGBtoRGBA(self):\n \"\"\"asRGBA8() on colour type 2 source.\"\"\"\n r = Reader(bytes=_pngsuite['basn2c08'])\n (x, y, pixels, meta) = r.asRGBA8()\n row9 = list(pixels)[9]\n self.assertEqual(row9[0:8], [255, 223, 255, 255, 255, 222, 255, 255])","code_tokens":"","url":76534} +{"project_name":"openkinome\/kinoml","file_name":"test_oemodeling.py","full_name":"test_write_molecules","func_name":"test_write_molecules","docstring":"Compare results to expected number of molecules and atoms in the written file.","docstring_tokens":"","code":"@pytest.mark.parametrize('molecules, suffix, n_atoms_list', [([read_smiles('CCC')], '.sdf', [11]), ([read_smiles('CCC')], '.pdb', [11]), ([read_smiles('COCC'), read_smiles('cccccc')], '.sdf', [12, 14]), ([read_smiles('CCC'), read_smiles('cccccc')], '.pdb', [11, 14])])\ndef test_write_molecules(molecules, suffix, n_atoms_list):\n \"\"\"Compare results to expected number of molecules and atoms in the written file.\"\"\"\n import tempfile\n\n def _count_molecules(path):\n with open(path) as rf:\n if path.split('.')[-1] == 'sdf':\n return rf.read().count('\\n$$$$\\n')\n elif path.split('.')[-1] == 'pdb':\n return rf.read().count('\\nEND\\n')\n else:\n raise NotImplementedError\n\n def _count_atoms(path, index):\n with open(path) as rf:\n if path.split('.')[-1] == 'sdf':\n molecule_text = rf.read().split('\\n$$$$\\n')[index]\n return int(molecule_text.split('\\n')[3].split()[0])\n elif path.split('.')[-1] == 'pdb':\n molecule_text = rf.read().split('\\nEND\\n')[index]\n return len([line for line in molecule_text.split('\\n') if line.startswith(('ATOM', 'HETATM'))])\n else:\n raise NotImplementedError\n with tempfile.NamedTemporaryFile(suffix=suffix) as temp_file:\n write_molecules(molecules, temp_file.name)\n assert _count_molecules(temp_file.name) == len(n_atoms_list)\n for (i, (molecule, n_atoms)) in enumerate(zip(molecules, n_atoms_list)):\n assert _count_atoms(temp_file.name, i) == n_atoms","code_tokens":"","url":596284} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"test_segmentation_configs.py","full_name":"test_head_and_neck_paper_with_mismatched_display_names_raises","func_name":"test_head_and_neck_paper_with_mismatched_display_names_raises","docstring":"Check that passing too many colours raises ValueError exception.","docstring_tokens":"","code":"def test_head_and_neck_paper_with_mismatched_display_names_raises() -> None:\n \"\"\"\n Check that passing too many colours raises ValueError exception.\n \"\"\"\n ground_truth_count = len(DEFAULT_HEAD_AND_NECK_GROUND_TRUTH_IDS) - 2\n ground_truth_ids_display_names = generate_random_display_ids(ground_truth_count - 1)\n with pytest.raises(ValueError) as e:\n assert HeadAndNeckPaper(local_dataset=Path('foo'), num_structures=ground_truth_count, ground_truth_ids_display_names=ground_truth_ids_display_names)\n assert str(e.value) == 'len(ground_truth_ids_display_names)!=len(ground_truth_ids)'","code_tokens":"","url":613554} +{"project_name":"instadeepai\/jumanji","file_name":"env_not_smoke.py","full_name":"check_env_does_not_smoke","func_name":"check_env_does_not_smoke","docstring":"Run an episode of the environment, with a jitted step function to check no errors occur.","docstring_tokens":"","code":"def check_env_does_not_smoke(env: Environment, select_action: Optional[SelectActionFn]=None, assert_finite_check: bool=True) -> None:\n \"\"\"Run an episode of the environment, with a jitted step function to check no errors occur.\"\"\"\n action_spec = env.action_spec()\n if select_action is None:\n if isinstance(action_spec, specs.BoundedArray) or isinstance(action_spec, specs.DiscreteArray):\n select_action = make_random_select_action_fn(action_spec)\n else:\n raise NotImplementedError(f'Currently the `make_random_select_action_fn` only works for environments with either discrete actions or bounded continuous actions. The input environment to this test has an action spec of type {action_spec}, and therefore requires a custom `SelectActionFn` to be provided to this test.')\n key = jax.random.PRNGKey(0)\n (key, reset_key) = jax.random.split(key)\n (state, timestep) = env.reset(reset_key)\n step_fn = jax.jit(env.step)\n while not timestep.last():\n (key, action_key) = jax.random.split(key)\n action = select_action(action_key, timestep.observation)\n env.action_spec().validate(action)\n (state, timestep) = step_fn(state, action)\n env.observation_spec().validate(timestep.observation)\n if assert_finite_check:\n chex.assert_tree_all_finite((state, timestep))","code_tokens":"","url":594554} +{"project_name":"pathak22\/noreward-rl","file_name":"demo.py","full_name":"inference","func_name":"inference","docstring":"It restore policy weights, and does inference.","docstring_tokens":"","code":"def inference(args):\n \"\"\"\n It restore policy weights, and does inference.\n \"\"\"\n env = create_env(args.env_id, client_id='0', remotes=None, envWrap=True, acRepeat=1, record=args.record, outdir=args.outdir)\n numaction = env.action_space.n\n with tf.device('\/cpu:0'):\n config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n with tf.Session(config=config) as sess:\n logger.info('Restoring trainable global parameters.')\n saver = tf.train.import_meta_graph(args.ckpt + '.meta')\n saver.restore(sess, args.ckpt)\n probs = tf.get_collection('probs')[0]\n sample = tf.get_collection('sample')[0]\n vf = tf.get_collection('vf')[0]\n state_out_0 = tf.get_collection('state_out_0')[0]\n state_out_1 = tf.get_collection('state_out_1')[0]\n last_state = env.reset()\n if args.render or args.record:\n env.render()\n last_features = np.zeros((1, 256), np.float32)\n last_features = [last_features, last_features]\n length = 0\n rewards = 0\n mario_distances = np.zeros((args.num_episodes,))\n for i in range(args.num_episodes):\n print('Starting episode %d' % (i + 1))\n if args.random:\n print('I am a random policy!')\n elif args.greedy:\n print('I am a greedy policy!')\n else:\n print('I am a sampled policy!')\n while True:\n fetched = sess.run([probs, sample, vf, state_out_0, state_out_1], {'global\/x:0': [last_state], 'global\/c_in:0': last_features[0], 'global\/h_in:0': last_features[1]})\n (prob_action, action, value_, features) = (fetched[0], fetched[1], fetched[2], fetched[3:])\n if args.random:\n stepAct = np.random.randint(0, numaction)\n elif args.greedy:\n stepAct = prob_action.argmax()\n else:\n stepAct = action.argmax()\n (state, reward, terminal, info) = env.step(stepAct)\n length += 1\n rewards += reward\n last_state = state\n last_features = features\n if args.render or args.record:\n env.render()\n timestep_limit = env.spec.tags.get('wrapper_config.TimeLimit.max_episode_steps')\n if timestep_limit is None:\n timestep_limit = env.spec.timestep_limit\n if terminal or length >= timestep_limit:\n if length >= timestep_limit or not env.metadata.get('semantics.autoreset'):\n last_state = env.reset()\n last_features = np.zeros((1, 256), np.float32)\n last_features = [last_features, last_features]\n print('Episode finished. Sum of rewards: %.2f. Length: %d.' % (rewards, length))\n length = 0\n rewards = 0\n if args.render or args.record:\n env.render()\n break\n logger.info('Finished %d true episodes.', args.num_episodes)\n env.close()","code_tokens":"","url":249526} +{"project_name":"MycroftAI\/mycroft-core","file_name":"mycroft_skill.py","full_name":"MycroftSkill.load_vocab_files","func_name":"load_vocab_files","docstring":"Load vocab files found under root_directory.","docstring_tokens":"","code":"def load_vocab_files(self, root_directory):\n \"\"\" Load vocab files found under root_directory.\n\n Args:\n root_directory (str): root folder to use when loading files\n \"\"\"\n keywords = []\n vocab_dir = join(root_directory, 'vocab', self.lang)\n locale_dir = join(root_directory, 'locale', self.lang)\n if exists(vocab_dir):\n keywords = load_vocabulary(vocab_dir, self.skill_id)\n elif exists(locale_dir):\n keywords = load_vocabulary(locale_dir, self.skill_id)\n else:\n LOG.debug('No vocab loaded')\n for vocab_type in keywords:\n for line in keywords[vocab_type]:\n entity = line[0]\n aliases = line[1:]\n with self.intent_service_lock:\n self.intent_service.register_adapt_keyword(vocab_type, entity, aliases)","code_tokens":"","url":290638} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"utils.py","full_name":"wrap_nncf_model","func_name":"wrap_nncf_model","docstring":"The function wraps mmcv model by NNCF.","docstring_tokens":"","code":"def wrap_nncf_model(config: Config, model: nn.Module, *, model_eval_fn: Optional[Callable]=None, dummy_forward_fn: Optional[Callable]=None, get_fake_input_fn: Optional[Callable]=None, wrap_inputs_fn: Optional[Callable]=None, dataloader_for_init: Optional[DataLoader]=None, init_state_dict: Optional[Dict[Any, Any]]=None, is_accuracy_aware: bool=False):\n \"\"\"The function wraps mmcv model by NNCF.\"\"\"\n check_nncf_is_enabled()\n from nncf import NNCFConfig\n from nncf.config.utils import is_accuracy_aware_training\n from nncf.torch import create_compressed_model, load_state, register_default_init_args\n from nncf.torch.dynamic_graph.io_handling import nncf_model_input\n from nncf.torch.initialization import PTInitializingDataLoader\n\n class _MMInitializeDataLoader(PTInitializingDataLoader):\n\n def get_inputs(self, dataloader_output):\n kwargs = {k: v.data[0] if isinstance(v, DataContainer) else v for (k, v) in dataloader_output.items()}\n kwargs['return_loss'] = False\n kwargs['img_metas'] = [kwargs['img_metas']]\n kwargs['img'] = [kwargs['img']]\n new_kwargs = dict()\n for (key, val) in kwargs.items():\n if not key.startswith('gt_'):\n new_kwargs[key] = val\n return ((), new_kwargs)\n nncf_config = NNCFConfig(config.nncf_config)\n resuming_state_dict = None\n if dataloader_for_init:\n wrapped_loader = _MMInitializeDataLoader(dataloader_for_init)\n eval_fn = model_eval_fn if is_accuracy_aware else None\n nncf_config = register_default_init_args(nncf_config, wrapped_loader, model_eval_fn=eval_fn, device=next(model.parameters()).device)\n if config.get('resume_from'):\n checkpoint_path = config.get('resume_from')\n assert is_checkpoint_nncf(checkpoint_path), 'It is possible to resume training with NNCF compression from NNCF checkpoints only. Use \"load_from\" with non-compressed model for further compression by NNCF.'\n elif config.get('load_from'):\n checkpoint_path = config.get('load_from')\n if not is_checkpoint_nncf(checkpoint_path):\n logger.info('Received non-NNCF checkpoint to start training -- initialization of NNCF fields will be done')\n else:\n checkpoint_path = None\n if not dataloader_for_init and (not checkpoint_path) and (not init_state_dict):\n logger.warning('Either dataloader_for_init or NNCF pre-trained model checkpoint should be set. Without this, quantizers will not be initialized')\n if init_state_dict:\n assert is_state_nncf(init_state_dict)\n meta_state = init_state_dict['meta'][NNCF_META_KEY]\n resuming_state_dict = init_state_dict['state_dict']\n compression_state = meta_state.compression_ctrl\n elif checkpoint_path:\n logger.info(f'Loading NNCF checkpoint from {checkpoint_path}')\n logger.info('Please, note that this first loading is made before addition of NNCF FakeQuantize nodes to the model, so there may be some warnings on unexpected keys')\n (compression_state, resuming_state_dict) = load_checkpoint(model, checkpoint_path)\n logger.info(f'Loaded NNCF checkpoint from {checkpoint_path}')\n else:\n compression_state = None\n if dummy_forward_fn is None:\n assert get_fake_input_fn is not None\n\n def _get_fake_data_for_forward(nncf_config):\n device = next(model.parameters()).device\n if nncf_config.get('input_info', None) and nncf_config.get('input_info').get('sample_size', None):\n input_size = nncf_config.get('input_info').get('sample_size')\n assert len(input_size) == 4 and input_size[0] == 1\n (H, W, C) = (input_size[2], input_size[3], input_size[1])\n shape = tuple([H, W, C])\n else:\n shape = (128, 128, 3)\n with no_nncf_trace():\n return get_fake_input_fn(shape=shape, device=device)\n\n def dummy_forward_fn(model):\n fake_data = _get_fake_data_for_forward(nncf_config)\n (img, img_metas) = (fake_data['img'], fake_data['img_metas'])\n ctx = model.nncf_trace_context(img_metas)\n with ctx:\n img = [i.to(next(model.parameters()).device) for i in img]\n img = [nncf_model_input(i) for i in img]\n model(img)\n if wrap_inputs_fn is None:\n\n def wrap_inputs_fn(args, kwargs):\n img = kwargs.get('img') if 'img' in kwargs else args[0]\n if isinstance(img, list):\n assert len(img) == 1, 'Input list must have a length 1'\n assert torch.is_tensor(img[0]), 'Input for a model must be a tensor'\n img[0] = nncf_model_input(img[0])\n else:\n assert torch.is_tensor(img), 'Input for a model must be a tensor'\n img = nncf_model_input(img)\n if 'img' in kwargs:\n kwargs['img'] = img\n else:\n args = (img, *args[1:])\n return (args, kwargs)\n if 'log_dir' in nncf_config:\n os.makedirs(nncf_config['log_dir'], exist_ok=True)\n uncompressed_model_accuracy = None\n if is_accuracy_aware_training(nncf_config) and model_eval_fn is not None:\n uncompressed_model_accuracy = model_eval_fn(model)\n model._register_state_dict_hook(nncf_state_dict_hook)\n model._register_load_state_dict_pre_hook(nncf_state_dict_pre_hook)\n (compression_ctrl, model) = create_compressed_model(model, nncf_config, dummy_forward_fn=dummy_forward_fn, wrap_inputs_fn=wrap_inputs_fn, compression_state=compression_state)\n if uncompressed_model_accuracy is not None:\n model.nncf._uncompressed_model_accuracy = uncompressed_model_accuracy\n model.__class__.forward.__signature__ = inspect.Signature([inspect.Parameter('args', inspect.Parameter.VAR_POSITIONAL), inspect.Parameter('kwargs', inspect.Parameter.VAR_KEYWORD)])\n if resuming_state_dict:\n load_state(model, resuming_state_dict, is_resume=True)\n return (compression_ctrl, model)","code_tokens":"","url":917887} +{"project_name":"salesforce\/CodeRL","file_name":"check_repo.py","full_name":"check_models_are_auto_configured","func_name":"check_models_are_auto_configured","docstring":"Check models defined in module are each in an auto class.","docstring_tokens":"","code":"def check_models_are_auto_configured(module, all_auto_models):\n \"\"\"Check models defined in module are each in an auto class.\"\"\"\n defined_models = get_models(module)\n failures = []\n for (model_name, _) in defined_models:\n if model_name not in all_auto_models and (not ignore_unautoclassed(model_name)):\n failures.append(f'{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file `utils\/check_repo.py`.')\n return failures","code_tokens":"","url":495748} +{"project_name":"AgileRL\/AgileRL","file_name":"evolvable_bert.py","full_name":"EvolvableBERT.recreate_shrunk_nets","func_name":"recreate_shrunk_nets","docstring":"Recreates shrunk neural networks.","docstring_tokens":"","code":"def recreate_shrunk_nets(self):\n \"\"\"Recreates shrunk neural networks.\n \"\"\"\n (new_encoder, new_decoder) = self.create_nets()\n new_encoder = self.shrink_preserve_parameters(old_net=self.encoder, new_net=new_encoder)\n new_decoder = self.shrink_preserve_parameters(old_net=self.decoder, new_net=new_decoder)\n (self.encoder, self.decoder) = (new_encoder, new_decoder)","code_tokens":"","url":23964} +{"project_name":"matsu0228\/nlp-jp","file_name":"connection.py","full_name":"MWSConnection.create_inbound_shipment","func_name":"create_inbound_shipment","docstring":"Creates an inbound shipment.","docstring_tokens":"","code":"@requires(['ShipmentId', 'InboundShipmentHeader', 'InboundShipmentItems'])\n@structured_objects('InboundShipmentHeader', 'InboundShipmentItems')\n@api_action('Inbound', 30, 0.5)\ndef create_inbound_shipment(self, request, response, **kw):\n \"\"\"Creates an inbound shipment.\n \"\"\"\n return self._post_request(request, kw, response)","code_tokens":"","url":784946} +{"project_name":"clementchadebec\/benchmark_VAE","file_name":"training_callbacks.py","full_name":"TrainingCallback.on_epoch_end","func_name":"on_epoch_end","docstring":"Event called at the end of an epoch.","docstring_tokens":"","code":"def on_epoch_end(self, training_config: BaseTrainerConfig, **kwargs):\n \"\"\"\n Event called at the end of an epoch.\n \"\"\"","code_tokens":"","url":434046} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"manager.py","full_name":"ConfigManager.update","func_name":"update","docstring":"Update the config only to the user's config.","docstring_tokens":"","code":"def update(self, section_name, new_data):\n \"\"\"Update the config only to the user's config.\"\"\"\n return self.write_config_manager.update(section_name, new_data)","code_tokens":"","url":43197} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"png.py","full_name":"Reader.serialtoflat","func_name":"serialtoflat","docstring":"Convert serial format (byte stream) pixel data to flat row flat pixel.","docstring_tokens":"","code":"def serialtoflat(self, bytes, width=None):\n \"\"\"Convert serial format (byte stream) pixel data to flat row\n flat pixel.\n \"\"\"\n if self.bitdepth == 8:\n return bytes\n if self.bitdepth == 16:\n bytes = tostring(bytes)\n return array('H', struct.unpack('!%dH' % (len(bytes) \/\/ 2), bytes))\n assert self.bitdepth < 8\n if width is None:\n width = self.width\n spb = 8 \/\/ self.bitdepth\n out = array('B')\n mask = 2 ** self.bitdepth - 1\n shifts = map(self.bitdepth.__mul__, reversed(range(spb)))\n l = width\n for o in bytes:\n out.extend([mask & o >> s for s in shifts][:l])\n l -= spb\n if l <= 0:\n l = width\n return out","code_tokens":"","url":76519} +{"project_name":"apeterswu\/RL4NMT","file_name":"common_layers.py","full_name":"conv1d_block","func_name":"conv1d_block","docstring":"A block of standard 1d convolutions.","docstring_tokens":"","code":"def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\n \"\"\"A block of standard 1d convolutions.\"\"\"\n return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)","code_tokens":"","url":331041} +{"project_name":"ripl-org\/sockit","file_name":"__init__.py","full_name":"get_soc4_title","func_name":"get_soc4_title","docstring":"Lazy-load SOC titles and lookup the title for a 4-digit SOC code.","docstring_tokens":"","code":"def get_soc4_title(soc4):\n \"\"\"\n Lazy-load SOC titles and lookup the title for a 4-digit SOC code.\n \"\"\"\n return get_lookup('soc4_titles')[str(soc4)]","code_tokens":"","url":879233} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"task.py","full_name":"OTXActionTask.export","func_name":"export","docstring":"Export function of OTX Task.","docstring_tokens":"","code":"def export(self, export_type: ExportType, output_model: ModelEntity, precision: ModelPrecision=ModelPrecision.FP32, dump_features: bool=True):\n \"\"\"Export function of OTX Task.\"\"\"\n if dump_features:\n raise NotImplementedError('Feature dumping is not implemented for the action task.The saliency maps and representation vector outputs will not be dumped in the exported model.')\n self._update_model_export_metadata(output_model, export_type, precision, dump_features)\n results = self._export_model(precision, export_type, dump_features)\n outputs = results.get('outputs')\n logger.debug(f'results of run_task = {outputs}')\n if outputs is None:\n raise RuntimeError(results.get('msg'))\n if export_type == ExportType.ONNX:\n onnx_file = outputs.get('onnx')\n with open(onnx_file, 'rb') as f:\n output_model.set_data('model.onnx', f.read())\n else:\n bin_file = outputs.get('bin')\n xml_file = outputs.get('xml')\n with open(bin_file, 'rb') as f:\n output_model.set_data('openvino.bin', f.read())\n with open(xml_file, 'rb') as f:\n output_model.set_data('openvino.xml', f.read())\n output_model.set_data('confidence_threshold', np.array([self.confidence_threshold], dtype=np.float32).tobytes())\n output_model.set_data('config.json', config_to_bytes(self._hyperparams))\n output_model.set_data('label_schema.json', label_schema_to_bytes(self._task_environment.label_schema))\n logger.info('Exporting completed')","code_tokens":"","url":903843} +{"project_name":"facebookresearch\/fvcore","file_name":"test_focal_loss.py","full_name":"TestFocalLossStar.test_focal_loss_star_equals_ce_loss","func_name":"test_focal_loss_star_equals_ce_loss","docstring":"No weighting of easy\/hard (gamma = 1) or positive\/negative (alpha = -1).","docstring_tokens":"","code":"def test_focal_loss_star_equals_ce_loss(self) -> None:\n \"\"\"\n No weighting of easy\/hard (gamma = 1) or positive\/negative (alpha = -1).\n \"\"\"\n inputs = logit(torch.tensor([[[0.95], [0.9], [0.98], [0.99]]], dtype=torch.float32))\n targets = torch.tensor([[[1], [1], [1], [1]]], dtype=torch.float32)\n inputs_fl = inputs.clone().requires_grad_()\n targets_fl = targets.clone()\n inputs_ce = inputs.clone().requires_grad_()\n targets_ce = targets.clone()\n focal_loss_star = sigmoid_focal_loss_star(inputs_fl, targets_fl, gamma=1, alpha=-1, reduction='mean')\n ce_loss = F.binary_cross_entropy_with_logits(inputs_ce, targets_ce, reduction='mean')\n self.assertEqual(ce_loss, focal_loss_star.data)\n focal_loss_star.backward()\n ce_loss.backward()\n self.assertTrue(torch.allclose(inputs_fl.grad.data, inputs_ce.grad.data))","code_tokens":"","url":565984} +{"project_name":"RonMen10\/Artificial-decision-making-of-autonomous-vehicles-AI","file_name":"control.py","full_name":"AgentVehicle.mutate_threshold","func_name":"mutate_threshold","docstring":"Change the agent risk threshold by mutation.","docstring_tokens":"","code":"def mutate_threshold(self, sigma, mutation_probability):\n \"\"\"Change the agent risk threshold by mutation.\"\"\"\n if random.random() <= mutation_probability:\n mutated_threshold = self.risk_threshold - random.gauss(0, sigma)\n if mutated_threshold < variables.lower_risk_bound:\n mutated_threshold = variables.lower_risk_bound\n elif mutated_threshold > variables.upper_risk_bound:\n mutated_threshold = variables.upper_risk_bound\n self.risk_threshold = mutated_threshold","code_tokens":"","url":34805} +{"project_name":"lonePatient\/TorchBlocks","file_name":"layer_norm.py","full_name":"replace_with_fused_layernorm","func_name":"replace_with_fused_layernorm","docstring":"Replace the normal (PyTorch-vanilla) layer-norms to apex fused layer-norms.","docstring_tokens":"","code":"def replace_with_fused_layernorm(module):\n \"\"\"Replace the normal (PyTorch-vanilla) layer-norms to apex fused layer-norms.\n Args:\n module: The target module to be replaced.\n \"\"\"\n for submodule in module.modules():\n for (name, layer) in submodule.named_children():\n if not isinstance(layer, nn.LayerNorm):\n continue\n new_layer = FusedLayerNorm(layer.normalized_shape, layer.eps)\n new_layer.weight = layer.weight\n new_layer.bias = layer.bias\n setattr(submodule, name, new_layer)","code_tokens":"","url":902551} +{"project_name":"neurospin\/pylearn-parsimony","file_name":"penalties.py","full_name":"L2Squared.L","func_name":"L","docstring":"Lipschitz constant of the gradient.","docstring_tokens":"","code":"def L(self):\n \"\"\"Lipschitz constant of the gradient.\n \"\"\"\n return self.l","code_tokens":"","url":820113} +{"project_name":"PacktPublishing\/Learning-Generative-Adversarial-Networks-V-","file_name":"kerasModel.py","full_name":"predict","func_name":"predict","docstring":"Predict the top 3 categories for the given image file.","docstring_tokens":"","code":"def predict(image_file):\n \"\"\"\n Predict the top 3 categories for the given image file.\n\n \"\"\"\n img = image.load_img(image_file, target_size=(299, 299))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n results = model.predict(x)\n top3 = decode_predictions(results, top=3)[0]\n return [{'label': label, 'description': description, 'probability': probability * 100.0} for (label, description, probability) in top3]","code_tokens":"","url":587910} +{"project_name":"deepmind\/dm_alchemy","file_name":"ideal_observer.py","full_name":"get_possible_stone_maps","func_name":"get_possible_stone_maps","docstring":"Gets possible stone maps (and their indices) consistent with stones passed.","docstring_tokens":"","code":"def get_possible_stone_maps(stone_map_indices: Sequence[StoneMapIndex], aligned_stones: Sequence[AlignedStone]) -> Tuple[List[int], List[StoneMapIndex]]:\n \"\"\"Gets possible stone maps (and their indices) consistent with stones passed.\"\"\"\n still_in_s = []\n poss_sms = []\n for (i, sm) in enumerate(stone_map_indices):\n stone_map = stones_and_potions.stone_map_from_index(sm)\n if stone_map.consistent_with_stones(aligned_stones):\n still_in_s.append(i)\n poss_sms.append(sm)\n return (still_in_s, poss_sms)","code_tokens":"","url":522197} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"box_list_ops.py","full_name":"scale_height_width","func_name":"scale_height_width","docstring":"Scale the height and width of boxes, leaving centers unchanged.","docstring_tokens":"","code":"def scale_height_width(boxlist, y_scale, x_scale, scope=None):\n \"\"\"Scale the height and width of boxes, leaving centers unchanged.\n\n Args:\n boxlist: BoxList holding N boxes\n y_scale: (float) scalar tensor\n x_scale: (float) scalar tensor\n scope: name scope.\n\n Returns:\n boxlist: BoxList holding N boxes\n \"\"\"\n with tf.name_scope(scope, 'ScaleHeightWidth'):\n y_scale = tf.cast(y_scale, tf.float32)\n x_scale = tf.cast(x_scale, tf.float32)\n (yc, xc, height_orig, width_orig) = boxlist.get_center_coordinates_and_sizes()\n y_min = yc - 0.5 * y_scale * height_orig\n y_max = yc + 0.5 * y_scale * height_orig\n x_min = xc - 0.5 * x_scale * width_orig\n x_max = xc + 0.5 * x_scale * width_orig\n scaled_boxlist = box_list.BoxList(tf.stack([y_min, x_min, y_max, x_max], 1))\n return _copy_extra_fields(scaled_boxlist, boxlist)","code_tokens":"","url":852113} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"data.py","full_name":"get_dataset","func_name":"get_dataset","docstring":"Get dataset from datasetentity.","docstring_tokens":"","code":"def get_dataset(dataset: DatasetEntity, subset: Subset):\n \"\"\"Get dataset from datasetentity.\"\"\"\n data = dataset.get_subset(subset)\n return data if len(data) > 0 else None","code_tokens":"","url":918005} +{"project_name":"kengz\/SLM-Lab","file_name":"util.py","full_name":"self_desc","func_name":"self_desc","docstring":"Method to get self description, used at init.","docstring_tokens":"","code":"def self_desc(cls, omit=None):\n \"\"\"Method to get self description, used at init.\"\"\"\n desc_list = [f'{get_class_name(cls)}:']\n omit_list = ps.compact(cast_list(omit))\n for (k, v) in get_class_attr(cls).items():\n if k in omit_list:\n continue\n if k == 'spec':\n desc_v = pformat(v['meta'])\n elif ps.is_dict(v) or ps.is_dict(ps.head(v)):\n desc_v = pformat(v)\n else:\n desc_v = v\n desc_list.append(f'- {k} = {desc_v}')\n desc = '\\n'.join(desc_list)\n return desc","code_tokens":"","url":351594} +{"project_name":"matsu0228\/nlp-jp","file_name":"ldamallet.py","full_name":"LdaMallet.convert_input","func_name":"convert_input","docstring":"Serialize documents (lists of unicode tokens) to a temporary text file, then convert that text file to MALLET format `outfile`.","docstring_tokens":"","code":"def convert_input(self, corpus, infer=False, serialize_corpus=True):\n \"\"\"\n Serialize documents (lists of unicode tokens) to a temporary text file,\n then convert that text file to MALLET format `outfile`.\n\n \"\"\"\n if serialize_corpus:\n logger.info('serializing temporary corpus to %s', self.fcorpustxt())\n with smart_open(self.fcorpustxt(), 'wb') as fout:\n self.corpus2mallet(corpus, fout)\n cmd = self.mallet_path + ' import-file --preserve-case --keep-sequence --remove-stopwords --token-regex \"\\\\S+\" --input %s --output %s'\n if infer:\n cmd += ' --use-pipe-from ' + self.fcorpusmallet()\n cmd = cmd % (self.fcorpustxt(), self.fcorpusmallet() + '.infer')\n else:\n cmd = cmd % (self.fcorpustxt(), self.fcorpusmallet())\n logger.info('converting temporary corpus to MALLET format with %s', cmd)\n check_output(args=cmd, shell=True)","code_tokens":"","url":785953} +{"project_name":"intelligent-environments-lab\/CityLearn","file_name":"building.py","full_name":"Building.electrical_storage","func_name":"electrical_storage","docstring":"Electric storage object for meeting electric loads.","docstring_tokens":"","code":"@property\ndef electrical_storage(self) -> Battery:\n \"\"\"Electric storage object for meeting electric loads.\"\"\"\n return self.__electrical_storage","code_tokens":"","url":105552} +{"project_name":"voxel51\/fiftyone","file_name":"patches.py","full_name":"EvaluationPatchesView.gt_field","func_name":"gt_field","docstring":"The ground truth field for the evaluation patches in this view.","docstring_tokens":"","code":"@property\ndef gt_field(self):\n \"\"\"The ground truth field for the evaluation patches in this view.\"\"\"\n return self._gt_field","code_tokens":"","url":583218} +{"project_name":"googleapis\/python-aiplatform","file_name":"client.py","full_name":"FeaturestoreOnlineServingServiceClient.parse_entity_type_path","func_name":"parse_entity_type_path","docstring":"Parses a entity_type path into its component segments.","docstring_tokens":"","code":"@staticmethod\ndef parse_entity_type_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a entity_type path into its component segments.\"\"\"\n m = re.match('^projects\/(?P.+?)\/locations\/(?P.+?)\/featurestores\/(?P.+?)\/entityTypes\/(?P.+?)$', path)\n return m.groupdict() if m else {}","code_tokens":"","url":812436} +{"project_name":"Trusted-AI\/AIF360","file_name":"transformer.py","full_name":"Transformer.predict","func_name":"predict","docstring":"Return a new dataset with labels predicted by running this Transformer on the input.","docstring_tokens":"","code":"def predict(self, dataset):\n \"\"\"Return a new dataset with labels predicted by running this\n Transformer on the input.\n\n Args:\n dataset (Dataset): Input dataset.\n\n Returns:\n Dataset: Output dataset. `metadata` should reflect the details of\n this transformation.\n \"\"\"\n raise NotImplementedError(\"'predict' is not supported for this class. Perhaps you meant 'transform' or 'fit_predict' instead?\")","code_tokens":"","url":412174} +{"project_name":"MycroftAI\/mycroft-core","file_name":"test_skill_api.py","full_name":"create_skill_api_from_skill","func_name":"create_skill_api_from_skill","docstring":"Helper creating an api from a skill.","docstring_tokens":"","code":"def create_skill_api_from_skill(skill):\n \"\"\"Helper creating an api from a skill.\n\n Args:\n skill (MycroftSkill): Skill to create api from.\n\n Returns:\n (SkillApi): API for the skill.\n \"\"\"\n SkillApi.connect_bus(skill.bus)\n return SkillApi(skill.public_api)","code_tokens":"","url":290959} +{"project_name":"jonathanking\/sidechainnet","file_name":"errors.py","full_name":"ProteinErrors.get_error_names","func_name":"get_error_names","docstring":"Returns a list of error names.","docstring_tokens":"","code":"def get_error_names(self):\n \"\"\"Returns a list of error names.\"\"\"\n return self.name_to_code.keys()","code_tokens":"","url":934109} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"vector_diffeomixture.py","full_name":"maybe_check_quadrature_param","func_name":"maybe_check_quadrature_param","docstring":"Helper which checks validity of `loc` and `scale` init args.","docstring_tokens":"","code":"@deprecation.deprecated('2018-10-01', 'The TensorFlow Distributions library has moved to TensorFlow Probability (https:\/\/github.com\/tensorflow\/probability). You should update all references to use `tfp.distributions` instead of `tf.contrib.distributions`.', warn_once=True)\ndef maybe_check_quadrature_param(param, name, validate_args):\n \"\"\"Helper which checks validity of `loc` and `scale` init args.\"\"\"\n with ops.name_scope(name='check_' + name, values=[param]):\n assertions = []\n if param.shape.ndims is not None:\n if param.shape.ndims == 0:\n raise ValueError('Mixing params must be a (batch of) vector; {}.rank={} is not at least one.'.format(name, param.shape.ndims))\n elif validate_args:\n assertions.append(check_ops.assert_rank_at_least(param, 1, message='Mixing params must be a (batch of) vector; {}.rank is not at least one.'.format(name)))\n if param.shape.with_rank_at_least(1)[-1] is not None:\n if param.shape[-1].value != 1:\n raise NotImplementedError('Currently only bimixtures are supported; {}.shape[-1]={} is not 1.'.format(name, param.shape[-1].value))\n elif validate_args:\n assertions.append(check_ops.assert_equal(array_ops.shape(param)[-1], 1, message='Currently only bimixtures are supported; {}.shape[-1] is not 1.'.format(name)))\n if assertions:\n return control_flow_ops.with_dependencies(assertions, param)\n return param","code_tokens":"","url":312887} +{"project_name":"open-mmlab\/mmdetection3d","file_name":"transforms_3d.py","full_name":"RandomFlip3D.transform","func_name":"transform","docstring":"Call function to flip points, values in the ``bbox3d_fields`` and also flip 2D image and its annotations.","docstring_tokens":"","code":"def transform(self, input_dict: dict) -> dict:\n \"\"\"Call function to flip points, values in the ``bbox3d_fields`` and\n also flip 2D image and its annotations.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Flipped results, 'flip', 'flip_direction',\n 'pcd_horizontal_flip' and 'pcd_vertical_flip' keys are added\n into result dict.\n \"\"\"\n if 'img' in input_dict:\n super(RandomFlip3D, self).transform(input_dict)\n if self.sync_2d and 'img' in input_dict:\n input_dict['pcd_horizontal_flip'] = input_dict['flip']\n input_dict['pcd_vertical_flip'] = False\n else:\n if 'pcd_horizontal_flip' not in input_dict:\n flip_horizontal = True if np.random.rand() < self.flip_ratio_bev_horizontal else False\n input_dict['pcd_horizontal_flip'] = flip_horizontal\n if 'pcd_vertical_flip' not in input_dict:\n flip_vertical = True if np.random.rand() < self.flip_ratio_bev_vertical else False\n input_dict['pcd_vertical_flip'] = flip_vertical\n if 'transformation_3d_flow' not in input_dict:\n input_dict['transformation_3d_flow'] = []\n if input_dict['pcd_horizontal_flip']:\n self.random_flip_data_3d(input_dict, 'horizontal')\n input_dict['transformation_3d_flow'].extend(['HF'])\n if input_dict['pcd_vertical_flip']:\n self.random_flip_data_3d(input_dict, 'vertical')\n input_dict['transformation_3d_flow'].extend(['VF'])\n return input_dict","code_tokens":"","url":631725} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"tree.py","full_name":"tree","func_name":"tree","docstring":"plist is list of pens l is length of branch a is half of the angle between 2 branches f is factor by which branch is shortened from level to level.","docstring_tokens":"","code":"def tree(plist, l, a, f):\n \"\"\" plist is list of pens\n l is length of branch\n a is half of the angle between 2 branches\n f is factor by which branch is shortened\n from level to level.\"\"\"\n if l > 3:\n lst = []\n for p in plist:\n p.forward(l)\n q = p.clone()\n p.left(a)\n q.right(a)\n lst.append(p)\n lst.append(q)\n for x in tree(lst, l * f, a, f):\n yield None","code_tokens":"","url":377133} +{"project_name":"kornia\/kornia","file_name":"patch.py","full_name":"PatchSequential.forward","func_name":"forward","docstring":"Input transformation will be returned if input is a tuple.","docstring_tokens":"","code":"def forward(self, input: Tensor, params: Optional[List[PatchParamItem]]=None) -> Tensor:\n \"\"\"Input transformation will be returned if input is a tuple.\"\"\"\n if isinstance(input, (tuple,)):\n raise ValueError('tuple input is not currently supported.')\n if params is None:\n params = self.forward_parameters(input.shape)\n output = self.transform_inputs(input, params=params)\n self._params = params\n return output","code_tokens":"","url":621507} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"thinkstats2.py","full_name":"Suite.Print","func_name":"Print","docstring":"Prints the hypotheses and their probabilities.","docstring_tokens":"","code":"def Print(self):\n \"\"\"Prints the hypotheses and their probabilities.\"\"\"\n for (hypo, prob) in sorted(self.Items()):\n print(hypo, prob)","code_tokens":"","url":12957} +{"project_name":"adiyoss\/DeepWDM","file_name":"textgrid.py","full_name":"TextGrid.getList","func_name":"getList","docstring":"Return a list of all tiers with the given name.","docstring_tokens":"","code":"def getList(self, tierName):\n \"\"\"\n Return a list of all tiers with the given name.\n \"\"\"\n tiers = []\n for t in self.tiers:\n if t.name == tierName:\n tiers.append(t)\n return tiers","code_tokens":"","url":180915} +{"project_name":"MaxHalford\/xam","file_name":"utils.py","full_name":"get_next_weekday","func_name":"get_next_weekday","docstring":"Find the first weekday after a given date.","docstring_tokens":"","code":"def get_next_weekday(date, weekday):\n \"\"\"Find the first weekday after a given date.\n\n Args:\n date (datetime)\n weekday (int)\n\n Returns:\n datetime: The next day of the week that has index `weekday`.\n \"\"\"\n return date + dt.timedelta(days=(weekday - date.weekday() + 7) % 7)","code_tokens":"","url":961842} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"test_vector_env_wrapper.py","full_name":"test_vector_env_wrapper_attributes","func_name":"test_vector_env_wrapper_attributes","docstring":"Test if `set_attr`, `call` methods for VecEnvWrapper get correctly forwarded to the vector env it is wrapping.","docstring_tokens":"","code":"def test_vector_env_wrapper_attributes():\n \"\"\"Test if `set_attr`, `call` methods for VecEnvWrapper get correctly forwarded to the vector env it is wrapping.\"\"\"\n env = make('CartPole-v1', num_envs=3)\n wrapped = DummyWrapper(make('CartPole-v1', num_envs=3))\n assert np.allclose(wrapped.call('gravity'), env.call('gravity'))\n env.set_attr('gravity', [20.0, 20.0, 20.0])\n wrapped.set_attr('gravity', [20.0, 20.0, 20.0])\n assert np.allclose(wrapped.get_attr('gravity'), env.get_attr('gravity'))","code_tokens":"","url":573665} +{"project_name":"FreshAirTonight\/af2complex","file_name":"data_transforms.py","full_name":"random_crop_to_size","func_name":"random_crop_to_size","docstring":"Crop randomly to `crop_size`, or keep as is if shorter than that.","docstring_tokens":"","code":"@curry1\ndef random_crop_to_size(protein, crop_size, max_templates, shape_schema, subsample_templates=False):\n \"\"\"Crop randomly to `crop_size`, or keep as is if shorter than that.\"\"\"\n seq_length = protein['seq_length']\n if 'template_mask' in protein:\n num_templates = tf.cast(shape_helpers.shape_list(protein['template_mask'])[0], tf.int32)\n else:\n num_templates = tf.constant(0, dtype=tf.int32)\n num_res_crop_size = tf.math.minimum(seq_length, crop_size)\n seed_maker = utils.SeedMaker(initial_seed=protein['random_crop_to_size_seed'])\n if subsample_templates:\n templates_crop_start = tf.random.stateless_uniform(shape=(), minval=0, maxval=num_templates + 1, dtype=tf.int32, seed=seed_maker())\n else:\n templates_crop_start = 0\n num_templates_crop_size = tf.math.minimum(num_templates - templates_crop_start, max_templates)\n num_res_crop_start = tf.random.stateless_uniform(shape=(), minval=0, maxval=seq_length - num_res_crop_size + 1, dtype=tf.int32, seed=seed_maker())\n templates_select_indices = tf.argsort(tf.random.stateless_uniform([num_templates], seed=seed_maker()))\n for (k, v) in protein.items():\n if k not in shape_schema or ('template' not in k and NUM_RES not in shape_schema[k]):\n continue\n if k.startswith('template') and subsample_templates:\n v = tf.gather(v, templates_select_indices)\n crop_sizes = []\n crop_starts = []\n for (i, (dim_size, dim)) in enumerate(zip(shape_schema[k], shape_helpers.shape_list(v))):\n is_num_res = dim_size == NUM_RES\n if i == 0 and k.startswith('template'):\n crop_size = num_templates_crop_size\n crop_start = templates_crop_start\n else:\n crop_start = num_res_crop_start if is_num_res else 0\n crop_size = num_res_crop_size if is_num_res else -1 if dim is None else dim\n crop_sizes.append(crop_size)\n crop_starts.append(crop_start)\n protein[k] = tf.slice(v, crop_starts, crop_sizes)\n protein['seq_length'] = num_res_crop_size\n return protein","code_tokens":"","url":400786} +{"project_name":"changh95\/cpp-cv-project-template","file_name":"optional.py","full_name":"install_packages_mac","func_name":"install_packages_mac","docstring":"Installs optional packages for Mac.","docstring_tokens":"","code":"def install_packages_mac(cfg):\n \"\"\"Installs optional packages for Mac.\n\n Args:\n cfg (Config): Config object for the current build\n \"\"\"\n print('Unimplemented on Mac')\n import sys\n sys.exit()","code_tokens":"","url":490179} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"tree_walk.py","full_name":"TreeWalk.replace","func_name":"replace","docstring":"Replace a node after first checking integrity of node stack.","docstring_tokens":"","code":"def replace(self, new_node):\n \"\"\"Replace a node after first checking integrity of node stack.\"\"\"\n cur_node = self.cur_node\n nodestack = self.nodestack\n cur = nodestack.pop()\n prev = nodestack[-1]\n index = prev[-1] - 1\n (oldnode, name) = prev[-2][index]\n assert cur[0] is cur_node is oldnode, (cur[0], cur_node, prev[-2], index)\n parent = prev[0]\n if isinstance(parent, list):\n parent[index] = new_node\n else:\n setattr(parent, name, new_node)","code_tokens":"","url":309792} +{"project_name":"kubeflow\/pipelines","file_name":"dataflow_python_job_remote_runner.py","full_name":"create_python_job","func_name":"create_python_job","docstring":"Creates a Dataflow python job.","docstring_tokens":"","code":"def create_python_job(python_module_path: str, project: str, gcp_resources: str, location: str, temp_location: str, requirements_file_path: str='', args: Optional[str]='[]'):\n \"\"\"Creates a Dataflow python job.\n\n Args:\n python_module_path: The gcs path to the python file to run.\n project: Required. The project of which the resource will be launched.\n gcp_resources: A placeholder output for returning the gcp_resouces proto.\n location: Required. The region of which the resource will be launched.\n temp_location: A GCS path for Dataflow to stage temporary job files created\n during the execution of the pipeline.\n requirements_file_path: Optional, the gcs path to the pip requirements file.\n args: The JsonArray list of args to pass to the python file. It can include\n '--requirements_file' or '--setup_file' to configure the workers however\n the path provided needs to be a GCS path.\n\n Returns:\n And instance of GCPResouces proto with the dataflow Job ID which is stored\n in gcp_resources path.\n Raises:\n RuntimeError: If the execution does not return a job ID.\n \"\"\"\n job_id = None\n if requirements_file_path:\n install_requirements(requirements_file_path)\n args_list = get_system_label_args_list()\n if args:\n args_list += json.loads(args)\n python_file_path = stage_file(python_module_path)\n for (idx, param) in enumerate(args_list):\n if param in _ARGS_FILES_TO_STAGE:\n args_list[idx + 1] = stage_file(args_list[idx + 1])\n logging.info('Staging %s at %s locally.', param, args_list[idx + 1])\n cmd = prepare_cmd(project, location, python_file_path, args_list, temp_location)\n sub_process = Process(cmd)\n for line in sub_process.read_lines():\n logging.info('DataflowRunner output: %s', line)\n (job_id, location) = extract_job_id_and_location(line)\n if job_id:\n logging.info('Found job id %s and location %s.', job_id, location)\n job_resources = gcp_resources_pb2.GcpResources()\n job_resource = job_resources.resources.add()\n job_resource.resource_type = 'DataflowJob'\n job_resource.resource_uri = f'https:\/\/dataflow.googleapis.com\/v1b3\/projects\/{project}\/locations\/{location}\/jobs\/{job_id}'\n with open(gcp_resources, 'w') as f:\n f.write(json_format.MessageToJson(job_resources))\n break\n if not job_id:\n raise RuntimeError('No dataflow job was found when running the python file.')","code_tokens":"","url":770789} +{"project_name":"chenbinghui1\/DSL","file_name":"test_paa_head.py","full_name":"test_paa_head_loss","func_name":"test_paa_head_loss","docstring":"Tests paa head loss when truth is empty and non-empty.","docstring_tokens":"","code":"def test_paa_head_loss():\n \"\"\"Tests paa head loss when truth is empty and non-empty.\"\"\"\n\n class mock_skm:\n\n def GaussianMixture(self, *args, **kwargs):\n return self\n\n def fit(self, loss):\n pass\n\n def predict(self, loss):\n components = np.zeros_like(loss, dtype=np.long)\n return components.reshape(-1)\n\n def score_samples(self, loss):\n scores = np.random.random(len(loss))\n return scores\n paa_head.skm = mock_skm()\n s = 256\n img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]\n train_cfg = mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.1, neg_iou_thr=0.1, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False))\n self = PAAHead(num_classes=4, in_channels=1, train_cfg=train_cfg, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='GIoULoss', loss_weight=1.3), loss_centerness=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=0.5))\n feat = [torch.rand(1, 1, s \/\/ feat_size, s \/\/ feat_size) for feat_size in [4, 8, 16, 32, 64]]\n self.init_weights()\n (cls_scores, bbox_preds, iou_preds) = self(feat)\n gt_bboxes = [torch.empty((0, 4))]\n gt_labels = [torch.LongTensor([])]\n gt_bboxes_ignore = None\n empty_gt_losses = self.loss(cls_scores, bbox_preds, iou_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore)\n empty_cls_loss = empty_gt_losses['loss_cls']\n empty_box_loss = empty_gt_losses['loss_bbox']\n empty_iou_loss = empty_gt_losses['loss_iou']\n assert empty_cls_loss.item() > 0, 'cls loss should be non-zero'\n assert empty_box_loss.item() == 0, 'there should be no box loss when there are no true boxes'\n assert empty_iou_loss.item() == 0, 'there should be no box loss when there are no true boxes'\n gt_bboxes = [torch.Tensor([[23.6667, 23.8757, 238.6326, 151.8874]])]\n gt_labels = [torch.LongTensor([2])]\n one_gt_losses = self.loss(cls_scores, bbox_preds, iou_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore)\n onegt_cls_loss = one_gt_losses['loss_cls']\n onegt_box_loss = one_gt_losses['loss_bbox']\n onegt_iou_loss = one_gt_losses['loss_iou']\n assert onegt_cls_loss.item() > 0, 'cls loss should be non-zero'\n assert onegt_box_loss.item() > 0, 'box loss should be non-zero'\n assert onegt_iou_loss.item() > 0, 'box loss should be non-zero'\n (n, c, h, w) = (10, 4, 20, 20)\n mlvl_tensor = [torch.ones(n, c, h, w) for i in range(5)]\n results = levels_to_images(mlvl_tensor)\n assert len(results) == n\n assert results[0].size() == (h * w * 5, c)\n assert self.with_score_voting\n cls_scores = [torch.ones(2, 4, 5, 5)]\n bbox_preds = [torch.ones(2, 4, 5, 5)]\n iou_preds = [torch.ones(2, 1, 5, 5)]\n mlvl_anchors = [torch.ones(2, 5 * 5, 4)]\n img_shape = None\n scale_factor = [0.5, 0.5]\n cfg = mmcv.Config(dict(nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.6), max_per_img=100))\n rescale = False\n self._get_bboxes(cls_scores, bbox_preds, iou_preds, mlvl_anchors, img_shape, scale_factor, cfg, rescale=rescale)","code_tokens":"","url":168001} +{"project_name":"hsouri\/BayesianTransferLearning","file_name":"classification_dataloader.py","full_name":"prepare_dataloaders","func_name":"prepare_dataloaders","docstring":"Wraps a train and a validation dataset with a DataLoader.","docstring_tokens":"","code":"def prepare_dataloaders(train_dataset: Dataset, val_dataset: Dataset, batch_size: int=64, num_workers: int=4) -> Tuple[DataLoader, DataLoader]:\n \"\"\"Wraps a train and a validation dataset with a DataLoader.\n\n Args:\n train_dataset (Dataset): object containing training data.\n val_dataset (Dataset): object containing validation data.\n batch_size (int): batch size.\n num_workers (int): number of parallel workers.\n Returns:\n Tuple[DataLoader, DataLoader]: training dataloader and validation dataloader.\n \"\"\"\n train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True, drop_last=True)\n val_loader = DataLoader(val_dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, drop_last=False)\n return (train_loader, val_loader)","code_tokens":"","url":423030} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"summary_ops_v2.py","full_name":"eval_dir","func_name":"eval_dir","docstring":"Construct a logdir for an eval summary writer.","docstring_tokens":"","code":"def eval_dir(model_dir, name=None):\n \"\"\"Construct a logdir for an eval summary writer.\"\"\"\n return os.path.join(model_dir, 'eval' if not name else 'eval_' + name)","code_tokens":"","url":339017} +{"project_name":"microsoft\/maro","file_name":"base.py","full_name":"DataTopology.download","func_name":"download","docstring":"Download the original data files of all data pipelines.","docstring_tokens":"","code":"def download(self, is_force: bool=False):\n \"\"\"Download the original data files of all data pipelines.\n\n Args:\n is_force(bool): If forced re-download the data file.\n \"\"\"\n for pipeline in self._data_pipeline:\n self._data_pipeline[pipeline].download(is_force)","code_tokens":"","url":628134} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"batch_ops_test.py","full_name":"BatchOpsTest.testBatchWithPadding","func_name":"testBatchWithPadding","docstring":"Test that batching with padding up to an allowed batch size works.","docstring_tokens":"","code":"def testBatchWithPadding(self):\n \"\"\"Test that batching with padding up to an allowed batch size works.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[2])\n (batched, index, _) = batch_ops.batch([inp], num_batch_threads=1, max_batch_size=10, batch_timeout_micros=100000, allowed_batch_sizes=[5, 10], grad_timeout_micros=0, batching_queue='')\n thread_results = []\n\n def worker():\n thread_results.extend(sess.run([batched, index], feed_dict={inp: [1, 3]}))\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([batched, index], feed_dict={inp: [2, 4]})\n worker_thread.join()\n if list(thread_results[0][0]):\n batch_t = thread_results[0][0]\n else:\n batch_t = main_results[0][0]\n self.assertEqual(len(batch_t), 5)","code_tokens":"","url":312452} +{"project_name":"awslabs\/predictive-maintenance-using--","file_name":"groupby.py","full_name":"GroupBy.cummax","func_name":"cummax","docstring":"Cumulative max for each group.","docstring_tokens":"","code":"@Substitution(name='groupby')\n@Appender(_common_see_also)\ndef cummax(self, axis=0, **kwargs):\n \"\"\"\n Cumulative max for each group.\n \"\"\"\n if axis != 0:\n return self.apply(lambda x: np.maximum.accumulate(x, axis))\n return self._cython_transform('cummax', numeric_only=False)","code_tokens":"","url":823532} +{"project_name":"dibyaghosh\/gcsl","file_name":"robot_env.py","full_name":"RobotEnv.close","func_name":"close","docstring":"Cleans up any resources used by the environment.","docstring_tokens":"","code":"def close(self):\n \"\"\"Cleans up any resources used by the environment.\"\"\"\n for component in self._components:\n component.close()\n self._components.clear()\n self.sim_scene.close()","code_tokens":"","url":201597} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"learning_rate.py","full_name":"learning_rate_factor","func_name":"learning_rate_factor","docstring":"Compute the designated learning rate factor from hparams.","docstring_tokens":"","code":"def learning_rate_factor(name, step_num, hparams):\n \"\"\"Compute the designated learning rate factor from hparams.\"\"\"\n if name == 'constant':\n tf.logging.info('Base learning rate: %f', hparams.learning_rate_constant)\n return hparams.learning_rate_constant\n elif name == 'linear_warmup':\n return tf.minimum(1.0, step_num \/ hparams.learning_rate_warmup_steps)\n elif name == 'linear_decay':\n ret = (hparams.train_steps - step_num) \/ hparams.learning_rate_decay_steps\n return tf.minimum(1.0, tf.maximum(0.0, ret))\n elif name == 'rsqrt_decay':\n return tf.rsqrt(tf.maximum(step_num, hparams.learning_rate_warmup_steps))\n elif name == 'rsqrt_normalized_decay':\n scale = tf.sqrt(tf.to_float(hparams.learning_rate_warmup_steps))\n return scale * tf.rsqrt(tf.maximum(step_num, hparams.learning_rate_warmup_steps))\n elif name == 'exp_decay':\n decay_steps = hparams.learning_rate_decay_steps\n warmup_steps = hparams.learning_rate_warmup_steps\n p = (step_num - warmup_steps) \/ decay_steps\n p = tf.maximum(p, 0.0)\n if hparams.learning_rate_decay_staircase:\n p = tf.floor(p)\n return tf.pow(hparams.learning_rate_decay_rate, p)\n elif name == 'rsqrt_hidden_size':\n return hparams.hidden_size ** (-0.5)\n elif name == 'legacy':\n return legacy_learning_rate_schedule(hparams)\n else:\n raise ValueError('unknown learning rate factor %s' % name)","code_tokens":"","url":966107} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjDataWrapper.efc_pos","func_name":"efc_pos","docstring":"constraint position (equality, contact) (njmax x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef efc_pos(self):\n \"\"\"constraint position (equality, contact) (njmax x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.efc_pos, (self._model.njmax,))","code_tokens":"","url":440591} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"trainable_optimizer.py","full_name":"TrainableOptimizer.train","func_name":"train","docstring":"Creates graph operations to train the optimizer.","docstring_tokens":"","code":"def train(self, problem, dataset):\n \"\"\"Creates graph operations to train the optimizer.\n\n Args:\n problem: A problem_generator.Problem instance to train on.\n dataset: A datasets.Dataset tuple to use when training.\n\n Returns:\n meta_objective: A tensorflow operation for computing the meta-objective\n obj_weights: A tensor placeholder for feeding in the objective weights\n obj_values: The subproblem objective values during optimization\n batches: The batch indexes tensor for overriding with feed_dict\n first_unroll: A placeholder signifying if this is a first unroll\n (this will propagate the gradients slightly differently).\n reset_state: A placeholder signifying that the rnn state should be reset.\n output_state: The final state of the optimizer\n init_loop_vars_to_override: Local variables that can be assigned to\n propagate the optimizer and problem state for unrolling\n final_loop_vals: Final values of the loop variables that can be\n assigned to init_loop_vars_to_override.\n \"\"\"\n obj_weights = tf.placeholder(tf.float32)\n num_iter = tf.shape(obj_weights)[0]\n (data, labels) = dataset\n data = tf.constant(data)\n labels = tf.constant(labels)\n batches = tf.placeholder(tf.int32)\n first_unroll = tf.placeholder_with_default(False, [])\n reset_state = tf.placeholder_with_default(False, [])\n training_output = collections.namedtuple('TrainingOutput', ['metaobj', 'obj_weights', 'problem_objectives', 'initial_obj', 'batches', 'first_unroll', 'reset_state', 'output_state', 'init_loop_vars', 'output_loop_vars'])\n\n def loop_body(itr, obj_accum, params, attend_params, flattened_states, global_state, all_obj, unused_init_obj, data, labels, batches):\n \"\"\"Body of the meta-training while loop for optimizing a sub-problem.\n\n Args:\n itr: The current meta-training iteration.\n obj_accum: The accumulated objective over all training steps so far.\n params: The parameters of the sub-problem.\n attend_params: The parameters of the sub-problems at the attended\n location.\n flattened_states: The states of the trainable optimizer, sorted and\n flattened into a list (since a while loop can't handle nested lists\n or dictionaries).\n global_state: The global state of the optimizer.\n all_obj: The list of all objective values in the training process.\n unused_init_obj: The initial objective (unused here, but needed in the\n variable list because it's used in a stopping condition in the\n loop_cond.)\n data: The data for this problem.\n labels: The labels corresponding to the data.\n batches: The batch indexes needed for shuffled minibatch creation.\n\n Returns:\n itr: The updated meta-training iteration.\n obj_accum: The updated accumulated objective.\n params: The new parameters of the sub-problem.\n attend_params: The new parameters of the sub-problems at the attended\n location.\n flattened_states: The new states of the trainable optimizer.\n global_state: The updated global state.\n all_obj: The updates list of all objective values.\n unused_init_obj: The initial objective.\n data: The data for this problem.\n labels: The labels corresponding to the data.\n batches: The batch indexes needed for shuffled minibatch creation.\n \"\"\"\n batch_indices = tf.gather(batches, itr)\n batch_data = tf.gather(data, batch_indices)\n batch_labels = tf.gather(labels, batch_indices)\n obj = problem.objective(params, data, labels)\n if self.use_attention:\n current_obj = problem.objective(attend_params, batch_data, batch_labels)\n grads = problem.gradients(current_obj, attend_params)\n else:\n current_obj = problem.objective(params, batch_data, batch_labels)\n grads = problem.gradients(current_obj, params)\n if not self.use_second_derivatives:\n new_grads = []\n for grad in grads:\n if isinstance(grad, tf.IndexedSlices):\n new_grads.append(tf.IndexedSlices(tf.stop_gradient(grad.values), grad.indices))\n else:\n new_grads.append(tf.stop_gradient(grad))\n grads = new_grads\n all_obj = tf.concat([all_obj, tf.reshape(obj, (1,))], 0)\n acc = tf.gather(obj_weights, itr) * obj\n obj_accum = tf.add(obj_accum, acc)\n obj_accum.set_shape([])\n dict_states = [dict(zip(self.state_keys, flat_state)) for flat_state in flattened_states]\n args = (params, grads, dict_states, global_state)\n updates = self._compute_updates(*args)\n (new_params, new_states, new_global_state, new_attend_params) = updates\n new_flattened_states = map(flatten_and_sort, new_states)\n return [itr + 1, obj_accum, new_params, new_attend_params, new_flattened_states, new_global_state, all_obj, unused_init_obj, data, labels, batches]\n\n def loop_cond(itr, obj_accum, unused_params, unused_attend_params, unused_flattened_states, unused_global_state, all_obj, init_obj, *args):\n \"\"\"Termination conditions of the sub-problem optimization loop.\"\"\"\n del args\n cond1 = tf.less(itr, num_iter)\n cond2 = tf.is_finite(obj_accum)\n if self.obj_train_max_multiplier > 0:\n current_obj = tf.gather(all_obj, itr)\n max_diff = (self.obj_train_max_multiplier - 1) * tf.abs(init_obj)\n max_obj = init_obj + max_diff\n cond3 = tf.less(current_obj, max_obj)\n return tf.logical_and(tf.logical_and(cond1, cond2), cond3, name='training_loop_cond')\n else:\n return tf.logical_and(cond1, cond2, name='training_loop_cond')\n init = self._initialize_training_loop_parameters(problem, data, labels, batches, first_unroll, reset_state)\n (loop_vars, invariants, initial_obj, init_loop_vars_to_override) = init\n loop_output = tf.while_loop(loop_cond, loop_body, loop_vars, swap_memory=True, shape_invariants=invariants)\n (meta_obj, problem_objectives) = (loop_output[1], loop_output[6])\n scaled_meta_objective = self.scale_objective(meta_obj, problem_objectives, initial_obj)\n final_loop_vals = [initial_obj] + loop_output[2] + loop_output[3] + loop_output[5]\n final_loop_vals.extend(itertools.chain(*loop_output[4]))\n return training_output(scaled_meta_objective, obj_weights, problem_objectives, initial_obj, batches, first_unroll, reset_state, loop_output[4], init_loop_vars_to_override, final_loop_vals)","code_tokens":"","url":49221} +{"project_name":"thaines\/helit","file_name":"model.py","full_name":"Sample.getTopicConc","func_name":"getTopicConc","docstring":"Returns the sampled concentration parameter for drawing topic instances from the global DP.","docstring_tokens":"","code":"def getTopicConc(self):\n \"\"\"Returns the sampled concentration parameter for drawing topic instances from the global DP.\"\"\"\n return self.topicConc","code_tokens":"","url":591148} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"distribution_util.py","full_name":"get_broadcast_shape","func_name":"get_broadcast_shape","docstring":"Get broadcast shape as a Python list of integers (preferred) or `Tensor`.","docstring_tokens":"","code":"def get_broadcast_shape(*tensors):\n \"\"\"Get broadcast shape as a Python list of integers (preferred) or `Tensor`.\n\n Args:\n *tensors: One or more `Tensor` objects (already converted!).\n\n Returns:\n broadcast shape: Python list (if shapes determined statically), otherwise\n an `int32` `Tensor`.\n \"\"\"\n s_shape = tensors[0].shape\n for t in tensors[1:]:\n s_shape = array_ops.broadcast_static_shape(s_shape, t.shape)\n if s_shape.is_fully_defined():\n return s_shape.as_list()\n d_shape = array_ops.shape(tensors[0])\n for t in tensors[1:]:\n d_shape = array_ops.broadcast_dynamic_shape(d_shape, array_ops.shape(t))\n return d_shape","code_tokens":"","url":312817} +{"project_name":"lixingjian\/DELTA","file_name":"keras_solver.py","full_name":"KerasSolver.export_model","func_name":"export_model","docstring":"Export a model to tensorflow SavedModel.","docstring_tokens":"","code":"def export_model(self):\n \"\"\"Export a model to tensorflow SavedModel.\"\"\"\n inputs = self.build_inputs(utils.INFER)\n self.build()\n logits = self.model(inputs.input_x_dict)\n score = tf.nn.softmax(logits)\n self.session.run(tf.global_variables_initializer())\n self.session.run(tf.tables_initializer())\n self.session.run(inputs.iterator.initializer)\n weights_ckpt_dir = tf.train.latest_checkpoint(self.checkpoint_dir)\n self.model.load_weights(weights_ckpt_dir)\n output_dict = {'score': score}\n to_saved_model(self.config, self.session, inputs.input_x_dict, output_dict)","code_tokens":"","url":537681} +{"project_name":"voxel51\/fiftyone","file_name":"base.py","full_name":"ResponsivePlot.reset","func_name":"reset","docstring":"Resets the plot to its default state.","docstring_tokens":"","code":"def reset(self):\n \"\"\"Resets the plot to its default state.\"\"\"\n raise NotImplementedError('Subclass must implement reset()')","code_tokens":"","url":583604} +{"project_name":"google-research\/scenic","file_name":"mnist_dataset.py","full_name":"get_dataset","func_name":"get_dataset","docstring":"Returns generators for the MNIST train, validation, and test set.","docstring_tokens":"","code":"@datasets.add_dataset('mnist')\ndef get_dataset(*, batch_size, eval_batch_size, num_shards, dtype_str='float32', shuffle_seed=0, rng=None, dataset_configs=None, dataset_service_address: Optional[str]=None):\n \"\"\"Returns generators for the MNIST train, validation, and test set.\n\n Args:\n batch_size: int; Determines the train batch size.\n eval_batch_size: int; Determines the evaluation batch size.\n num_shards: int; Number of shards --> batch shape: [num_shards, bs, ...].\n dtype_str: Data type of the image (e.g. 'float32').\n shuffle_seed: int; Seed for shuffling the training data.\n rng: JAX rng key, which can be used for augmentation, shuffling, etc.\n dataset_configs: dict; Dataset specific configurations.\n dataset_service_address: If set, will distribute the training dataset using\n the given tf.data service at the given address.\n\n Returns:\n A dataset_utils.Dataset() which includes a train_iter, a valid_iter,\n a test_iter, and a dict of meta_data.\n \"\"\"\n del rng\n del dataset_configs\n dtype = getattr(tf, dtype_str)\n preprocess_ex = functools.partial(preprocess_example, dtype=dtype)\n logging.info('Loading train split of the MNIST dataset.')\n (train_ds, train_ds_info) = dataset_utils.load_split_from_tfds('mnist', batch_size, split='train', preprocess_example=preprocess_ex, shuffle_seed=shuffle_seed)\n if dataset_service_address:\n if shuffle_seed is not None:\n raise ValueError('Using dataset service with a random seed causes each worker to produce exactly the same data. Add config.shuffle_seed = None to your config if you want to run with dataset service.')\n logging.info('Using the tf.data service at %s', dataset_service_address)\n train_ds = dataset_utils.distribute(train_ds, dataset_service_address)\n logging.info('Loading test split of the MNIST dataset.')\n (eval_ds, _) = dataset_utils.load_split_from_tfds('mnist', eval_batch_size, split='test', preprocess_example=preprocess_ex)\n maybe_pad_batches_train = functools.partial(dataset_utils.maybe_pad_batch, train=True, batch_size=batch_size)\n maybe_pad_batches_eval = functools.partial(dataset_utils.maybe_pad_batch, train=False, batch_size=eval_batch_size)\n shard_batches = functools.partial(dataset_utils.shard, n_devices=num_shards)\n train_iter = iter(train_ds)\n train_iter = map(dataset_utils.tf_to_numpy, train_iter)\n train_iter = map(maybe_pad_batches_train, train_iter)\n train_iter = map(shard_batches, train_iter)\n eval_iter = iter(eval_ds)\n eval_iter = map(dataset_utils.tf_to_numpy, eval_iter)\n eval_iter = map(maybe_pad_batches_eval, eval_iter)\n eval_iter = map(shard_batches, eval_iter)\n input_shape = (-1, 28, 28, 1)\n meta_data = {'num_classes': train_ds_info.features['label'].num_classes, 'input_shape': input_shape, 'num_train_examples': dataset_utils.get_num_examples('mnist', 'train'), 'num_eval_examples': dataset_utils.get_num_examples('mnist', 'test'), 'input_dtype': getattr(jnp, dtype_str), 'target_is_onehot': False}\n return dataset_utils.Dataset(train_iter, eval_iter, None, meta_data)","code_tokens":"","url":846048} +{"project_name":"instadeepai\/jumanji","file_name":"wrappers_test.py","full_name":"TestJumanjiToGymObservation.test_jumanji_to_gym_obs__correct_observation","func_name":"test_jumanji_to_gym_obs__correct_observation","docstring":"Check that a NamedTuple containing a JAX array and a chex dataclass of two JAX arrays is converted correctly into a nested dictionary of numpy arrays.","docstring_tokens":"","code":"def test_jumanji_to_gym_obs__correct_observation(self) -> None:\n \"\"\"Check that a NamedTuple containing a JAX array and a chex dataclass of two\n JAX arrays is converted correctly into a nested dictionary of numpy arrays.\n \"\"\"\n NestedObservation = namedtuple('NestedObservation', ['jax_array', 'chex_dataclass'])\n array = jnp.zeros((2, 2))\n data_class = self.DummyChexDataclass(x=array, y=array)\n nested_obs = NestedObservation(array, data_class)\n converted_obs = jumanji_to_gym_obs(nested_obs)\n correct_obs = {'jax_array': np.zeros((2, 2)), 'chex_dataclass': {'x': np.zeros((2, 2)), 'y': np.zeros((2, 2))}}\n chex.assert_trees_all_equal(converted_obs, correct_obs)\n assert isinstance(converted_obs, dict)\n assert isinstance(converted_obs['jax_array'], chex.ArrayNumpy)\n assert isinstance(converted_obs['chex_dataclass'], dict)\n assert isinstance(converted_obs['chex_dataclass']['x'], chex.ArrayNumpy)\n assert isinstance(converted_obs['chex_dataclass']['y'], chex.ArrayNumpy)","code_tokens":"","url":593965} +{"project_name":"yinyunie\/ScenePriors","file_name":"common.py","full_name":"BaseDataset.n_object_types","func_name":"n_object_types","docstring":"The number of distinct objects contained in the rooms.","docstring_tokens":"","code":"@property\ndef n_object_types(self):\n \"\"\"The number of distinct objects contained in the rooms.\"\"\"\n return len(self.object_types)","code_tokens":"","url":341360} +{"project_name":"andreimuntean\/A3C","file_name":"environment.py","full_name":"AtariWrapper.sample_action","func_name":"sample_action","docstring":"Samples a random action.","docstring_tokens":"","code":"def sample_action(self):\n \"\"\"Samples a random action.\"\"\"\n return np.random.choice(self.action_space)","code_tokens":"","url":405478} +{"project_name":"mpeychev\/disentangled-autoencoders","file_name":"linear_classifier.py","full_name":"LinearClassifier.accuracy","func_name":"accuracy","docstring":"Evaluate the accuracy of the classifier on the test data.","docstring_tokens":"","code":"def accuracy(self, test_inputs, test_targets):\n \"\"\"Evaluate the accuracy of the classifier on the test data.\"\"\"\n correct_predictions = np.equal(self.predict_batch(test_inputs), np.argmax(test_targets, 1))\n return np.mean(correct_predictions)","code_tokens":"","url":552036} +{"project_name":"asyml\/texar-pytorch","file_name":"xlnet_regressor.py","full_name":"XLNetRegressor.forward","func_name":"forward","docstring":"Feeds the inputs through the network and makes regression.","docstring_tokens":"","code":"def forward(self, inputs: Union[torch.Tensor, torch.LongTensor], segment_ids: Optional[torch.LongTensor]=None, input_mask: Optional[torch.Tensor]=None) -> torch.Tensor:\n \"\"\"Feeds the inputs through the network and makes regression.\n\n Args:\n inputs: Either a **2D Tensor** of shape `[batch_size, max_time]`,\n containing the ids of tokens in input sequences, or\n a **3D Tensor** of shape `[batch_size, max_time, vocab_size]`,\n containing soft token ids (i.e., weights or probabilities)\n used to mix the embedding vectors.\n segment_ids: Shape `[batch_size, max_time]`.\n input_mask: Float tensor of shape `[batch_size, max_time]`. Note\n that positions with value 1 are masked out.\n\n Returns:\n Regression predictions.\n\n - If ``regr_strategy`` is ``cls_time`` or ``all_time``, predictions\n have shape `[batch_size]`.\n\n - If ``clas_strategy`` is ``time_wise``, predictions have shape\n `[batch_size, max_time]`.\n \"\"\"\n (output, _) = self._encoder(inputs=inputs, segment_ids=segment_ids, input_mask=input_mask)\n strategy = self._hparams.regr_strategy\n if strategy == 'time_wise':\n summary = output\n elif strategy == 'cls_time':\n summary = output[:, -1]\n elif strategy == 'all_time':\n length_diff = self._hparams.max_seq_length - inputs.shape[1]\n summary_input = F.pad(output, [0, 0, 0, length_diff, 0, 0])\n summary_input_dim = self._encoder.output_size * self._hparams.max_seq_length\n summary = summary_input.contiguous().view(-1, summary_input_dim)\n else:\n raise ValueError('Unknown regression strategy: {}'.format(strategy))\n if self._hparams.use_projection:\n summary = torch.tanh(self.projection(summary))\n summary = self.dropout(summary)\n preds = self.hidden_to_logits(summary).squeeze(-1)\n return preds","code_tokens":"","url":925269} +{"project_name":"famura\/SimuRLacra","file_name":"normal_noise.py","full_name":"FullNormalNoise.std","func_name":"std","docstring":"Get the standard deviations from the internal covariance matrix.","docstring_tokens":"","code":"@property\n@to.no_grad()\ndef std(self) -> to.Tensor:\n \"\"\"Get the standard deviations from the internal covariance matrix.\"\"\"\n return to.sqrt(self.cov.diag())","code_tokens":"","url":883746} +{"project_name":"kubeflow\/pipelines","file_name":"artifact_types.py","full_name":"ClassificationMetrics.log_confusion_matrix","func_name":"log_confusion_matrix","docstring":"Logs a confusion matrix to metadata.","docstring_tokens":"","code":"def log_confusion_matrix(self, categories: List[str], matrix: List[List[int]]) -> None:\n \"\"\"Logs a confusion matrix to metadata.\n\n Args:\n categories: List of the category names.\n matrix: Complete confusion matrix.\n\n Raises:\n ValueError: If the length of ``categories`` does not match number of rows or columns of ``matrix``.\n \"\"\"\n self.set_confusion_matrix_categories(categories)\n if len(matrix) != len(categories):\n raise ValueError(f'Invalid matrix: {matrix} passed for categories: {categories}')\n for index in range(len(categories)):\n if len(matrix[index]) != len(categories):\n raise ValueError(f'Invalid matrix: {matrix} passed for categories: {categories}')\n self.log_confusion_matrix_row(categories[index], matrix[index])\n self.metadata['confusionMatrix'] = self._confusion_matrix","code_tokens":"","url":780270} +{"project_name":"intel\/neural-compressor","file_name":"quantize_graph_matmul.py","full_name":"FuseNodeStartWithMatmul.apply_the_transform","func_name":"apply_the_transform","docstring":"Quantize MatMul and apply the fusion pattern.","docstring_tokens":"","code":"def apply_the_transform(self):\n \"\"\"Quantize MatMul and apply the fusion pattern.\"\"\"\n self._get_op_list()\n (matched_rule, matched_node_name) = self._is_match(self.sorted_patterns)\n if matched_node_name:\n self.output_graph = graph_pb2.GraphDef()\n fusion_name = ''.join(matched_rule)\n if fusion_name in self.fusion_mapping:\n matched_nodes = self.fusion_mapping[fusion_name](matched_node_name)\n else:\n self.logger.debug('Unknown fusion pattern {}.'.format(fusion_name))\n if self.remove_redundant_quant_flag:\n self.input_graph = self.remove_redundant_quantization(self.input_graph)\n return (self.input_graph, [])\n self.input_graph = self.output_graph\n self._reset_output_node_maps()\n if self.remove_redundant_quant_flag:\n self.output_graph = self.remove_redundant_quantization(self.output_graph)\n return (self.output_graph, matched_nodes, self.exclude_matmul_name)\n return (self.input_graph, [], [])","code_tokens":"","url":737783} +{"project_name":"pandeyankit83\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"neural_gpu_trainer.py","full_name":"assign_vectors","func_name":"assign_vectors","docstring":"Assign the embedding_key variable from the given word vectors file.","docstring_tokens":"","code":"def assign_vectors(word_vector_file, embedding_key, vocab_path, sess):\n \"\"\"Assign the embedding_key variable from the given word vectors file.\"\"\"\n if not tf.gfile.Exists(word_vector_file):\n data.print_out('Word vector file does not exist: %s' % word_vector_file)\n sys.exit(1)\n (vocab, _) = wmt.initialize_vocabulary(vocab_path)\n vectors_variable = [v for v in tf.trainable_variables() if embedding_key == v.name]\n if len(vectors_variable) != 1:\n data.print_out('Word vector variable not found or too many.')\n sys.exit(1)\n vectors_variable = vectors_variable[0]\n vectors = vectors_variable.eval()\n data.print_out('Pre-setting word vectors from %s' % word_vector_file)\n with tf.gfile.GFile(word_vector_file, mode='r') as f:\n for line in f:\n line_parts = line.split()\n word = line_parts[0]\n if word in vocab:\n word_vector = np.array(map(float, line_parts[1:]))\n if len(word_vector) != FLAGS.vec_size:\n data.print_out(\"Warn: Word '%s', Expecting vector size %d, found %d\" % (word, FLAGS.vec_size, len(word_vector)))\n else:\n vectors[vocab[word]] = word_vector\n sess.run([vectors_variable.initializer], {vectors_variable.initializer.inputs[1]: vectors})","code_tokens":"","url":50198} +{"project_name":"takuseno\/d3rlpy","file_name":"replay_buffer.py","full_name":"ReplayBuffer.sample_trajectory","func_name":"sample_trajectory","docstring":"Samples a partial trajectory.","docstring_tokens":"","code":"def sample_trajectory(self, length: int) -> PartialTrajectory:\n \"\"\"Samples a partial trajectory.\n\n Args:\n length: Length of partial trajectory.\n\n Returns:\n Partial trajectory.\n \"\"\"\n index = np.random.randint(self._buffer.transition_count)\n (episode, transition_index) = self._buffer[index]\n return self._trajectory_slicer(episode, transition_index, length)","code_tokens":"","url":197838} +{"project_name":"Sentdex\/Carla-RL","file_name":"experiment_suite.py","full_name":"ExperimentSuite.build_experiments","func_name":"build_experiments","docstring":"Returns a set of experiments to be evaluated Must be redefined in an inherited class.","docstring_tokens":"","code":"@abc.abstractmethod\ndef build_experiments(self):\n \"\"\"\n Returns a set of experiments to be evaluated\n Must be redefined in an inherited class.\n\n \"\"\"","code_tokens":"","url":103040} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"vertexdomain.py","full_name":"VertexList.vertices","func_name":"vertices","docstring":"Array of vertex coordinate data.","docstring_tokens":"","code":"@property\ndef vertices(self):\n \"\"\"Array of vertex coordinate data.\"\"\"\n if self._vertices_cache_version != self.domain._version:\n domain = self.domain\n attribute = domain.attribute_names['vertices']\n self._vertices_cache = attribute.get_region(attribute.buffer, self.start, self.count)\n self._vertices_cache_version = domain._version\n region = self._vertices_cache\n region.invalidate()\n return region.array","code_tokens":"","url":369548} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"nb_102a.py","full_name":"create_anchors","func_name":"create_anchors","docstring":"Create anchor of `sizes`, `ratios` and `scales`.","docstring_tokens":"","code":"def create_anchors(sizes, ratios, scales, flatten=True):\n \"\"\"Create anchor of `sizes`, `ratios` and `scales`.\"\"\"\n aspects = [[[s * math.sqrt(r), s * math.sqrt(1 \/ r)] for s in scales] for r in ratios]\n aspects = torch.tensor(aspects).view(-1, 2)\n anchors = []\n for (h, w) in sizes:\n sized_aspects = 4 * (aspects * torch.tensor([2 \/ h, 2 \/ w])).unsqueeze(0)\n base_grid = create_grid((h, w)).unsqueeze(1)\n (n, a) = (base_grid.size(0), aspects.size(0))\n ancs = torch.cat([base_grid.expand(n, a, 2), sized_aspects.expand(n, a, 2)], 2)\n anchors.append(ancs.view(h, w, a, 4))\n return torch.cat([anc.view(-1, 4) for anc in anchors], 0) if flatten else anchors","code_tokens":"","url":32585} +{"project_name":"qinliuliuqin\/Medical-Segmentation3d-Toolkit","file_name":"image_tools.py","full_name":"get_mean_std_from_image","func_name":"get_mean_std_from_image","docstring":"Get mean and standard deviation from the input image.","docstring_tokens":"","code":"def get_mean_std_from_image(image):\n \"\"\" Get mean and standard deviation from the input image.\n \"\"\"\n assert isinstance(image, sitk.Image)\n image_npy = sitk.GetArrayFromImage(image)\n return (np.mean(image_npy), np.std(image_npy))","code_tokens":"","url":650034} +{"project_name":"matsu0228\/nlp-jp","file_name":"topology.py","full_name":"Topology.get_primary","func_name":"get_primary","docstring":"Return primary's address or None.","docstring_tokens":"","code":"def get_primary(self):\n \"\"\"Return primary's address or None.\"\"\"\n with self._lock:\n topology_type = self._description.topology_type\n if topology_type != TOPOLOGY_TYPE.ReplicaSetWithPrimary:\n return None\n return writable_server_selector(self._new_selection())[0].address","code_tokens":"","url":805076} +{"project_name":"nqanh\/video2command","file_name":"utils.py","full_name":"text_to_sequence","func_name":"text_to_sequence","docstring":"Convert a text to numerical sequence.","docstring_tokens":"","code":"def text_to_sequence(text, vocab, filters='!\"#$%&()*+.,-\/:;=?@[\\\\]^_`{|}~ ', lower=True, split=' '):\n \"\"\"Convert a text to numerical sequence.\n \"\"\"\n tokens = word_tokenize(text, filters, lower, split)\n seq = []\n for token in tokens:\n word_index = vocab(token)\n if word_index is not None:\n seq.extend([word_index])\n return seq","code_tokens":"","url":379884} +{"project_name":"Trusted-AI\/AIF360","file_name":"metrics.py","full_name":"smoothed_base_rate","func_name":"smoothed_base_rate","docstring":"Compute the smoothed base rate, :math:`\\frac{P + \\alpha}{P + N + |R_Y|\\alpha}`.","docstring_tokens":"","code":"def smoothed_base_rate(y_true, y_pred=None, *, concentration=1.0, pos_label=1, sample_weight=None):\n \"\"\"Compute the smoothed base rate,\n :math:`\\\\frac{P + \\\\alpha}{P + N + |R_Y|\\\\alpha}`.\n\n Args:\n y_true (array-like): Ground truth (correct) target values.\n y_pred (array-like, optional): Estimated targets. Ignored.\n concentration (scalar): Dirichlet smoothing concentration parameter\n :math:`|R_Y|\\\\alpha` (must be non-negative).\n pos_label (scalar, optional): The label of the positive class.\n sample_weight (array-like, optional): Sample weights.\n\n Returns:\n float: Smoothed base rate.\n \"\"\"\n if concentration < 0:\n raise ValueError('Concentration parameter must be non-negative.')\n num_classes = len(np.unique(y_true))\n idx = y_true == pos_label\n (avg, tot) = np.average(idx, weights=sample_weight, returned=True)\n return (avg * tot + concentration \/ num_classes) \/ (tot + concentration)","code_tokens":"","url":412421} +{"project_name":"deepmind\/dm_control","file_name":"renderer.py","full_name":"SceneCamera.render","func_name":"render","docstring":"Renders the scene form this camera's perspective.","docstring_tokens":"","code":"def render(self, perturbation=None):\n \"\"\"Renders the scene form this camera's perspective.\n\n Args:\n perturbation: (Optional), instance of Perturbation.\n Returns:\n Rendered scene, instance of MjvScene.\n \"\"\"\n perturb_to_render = perturbation.ptr if perturbation else None\n mujoco.mjv_updateScene(self._model.ptr, self._data.ptr, self._options.visualization.ptr, perturb_to_render, self._camera.ptr, mujoco.mjtCatBit.mjCAT_ALL, self._scene.ptr)\n if self._scene_callback is not None:\n self._scene_callback(self._model, self._data, self._scene)\n return self._scene","code_tokens":"","url":165678} +{"project_name":"syuoni\/eznlp","file_name":"eznlp.py","full_name":"subjects","func_name":"subjects","docstring":"Determine whether [string] is about the given subjects in [string_list].","docstring_tokens":"","code":"def subjects(string, string_list):\n \"\"\"\n\tDetermine whether [string] is about the given subjects in [string_list].\n\t\"\"\"\n zsl = text.ZeroShotClassifier()\n res = zsl.predict(string, labels=string_list, include_labels=True, nli_template='The article is about {}.')\n return res","code_tokens":"","url":558102} +{"project_name":"triaquae\/triaquae","file_name":"text.py","full_name":"recapitalize","func_name":"recapitalize","docstring":"Recapitalizes text, placing caps after end-of-sentence punctuation.","docstring_tokens":"","code":"def recapitalize(text):\n \"\"\"Recapitalizes text, placing caps after end-of-sentence punctuation.\"\"\"\n text = force_text(text).lower()\n capsRE = re.compile('(?:^|(?<=[\\\\.\\\\?\\\\!] ))([a-z])')\n text = capsRE.sub(lambda x: x.group(1).upper(), text)\n return text","code_tokens":"","url":424181} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"compressor.py","full_name":"CompressorWrapper.decompressor_file","func_name":"decompressor_file","docstring":"Returns an instance of a decompressor file object.","docstring_tokens":"","code":"def decompressor_file(self, fileobj):\n \"\"\"Returns an instance of a decompressor file object.\"\"\"\n return self.fileobj_factory(fileobj, 'rb')","code_tokens":"","url":95819} +{"project_name":"replit-archive\/empythoned","file_name":"_exceptions.py","full_name":"SAXException.getException","func_name":"getException","docstring":"Return the embedded exception, or None if there was none.","docstring_tokens":"","code":"def getException(self):\n \"\"\"Return the embedded exception, or None if there was none.\"\"\"\n return self._exception","code_tokens":"","url":177073} +{"project_name":"enuguru\/artificial_intelligence_and_machine_","file_name":"blocks.py","full_name":"unicodeBlock","func_name":"unicodeBlock","docstring":"Returns the name of the unicode block containing c c must be a single character.","docstring_tokens":"","code":"def unicodeBlock(c):\n \"\"\" Returns the name of the unicode block containing c\n c must be a single character. \"\"\"\n ix = bisect_left(_endpoints, ord(c))\n return _names[ix]","code_tokens":"","url":128861} +{"project_name":"triaquae\/triaquae","file_name":"forms.py","full_name":"CommentForm.clean_honeypot","func_name":"clean_honeypot","docstring":"Check that nothing's been entered into the honeypot.","docstring_tokens":"","code":"def clean_honeypot(self):\n \"\"\"Check that nothing's been entered into the honeypot.\"\"\"\n value = self.cleaned_data['honeypot']\n if value:\n raise forms.ValidationError(self.fields['honeypot'].label)\n return value","code_tokens":"","url":357190} +{"project_name":"otoofim\/ObjLocalisation","file_name":"DNN.py","full_name":"make_epsilon_greedy_policy","func_name":"make_epsilon_greedy_policy","docstring":"Creates an epsilon-greedy policy based on a given Q-function approximator and epsilon.","docstring_tokens":"","code":"def make_epsilon_greedy_policy(estimator, nA):\n \"\"\"\n Creates an epsilon-greedy policy based on a given Q-function approximator and epsilon.\n\n Args:\n estimator: An estimator that returns q values for a given state\n nA: Number of actions in the environment.\n Returns:\n A policy for a given estimator\n\n \"\"\"\n\n def policy_fn(sess, observation, epsilon):\n \"\"\"\n Predicts Q values and gives probability distribution over actions\n \n Args:\n sess: Tensorflow session object\n observation: State input of shape [84, 84, 4]\n epsilon: Probability of taking actions rendomly\n\n Returns:\n the probabilities for every action in the form of a numpy array of length nA.\n\n \"\"\"\n A = np.ones(nA, dtype=float) * epsilon \/ nA\n q_values = estimator.predict(sess, np.expand_dims(observation, 0))[0]\n best_action = np.argmax(q_values)\n A[best_action] += 1.0 - epsilon\n return (A, q_values)\n return policy_fn","code_tokens":"","url":739900} +{"project_name":"fidelity\/seq2pat","file_name":"seq2pat.py","full_name":"Seq2Pat.sequences","func_name":"sequences","docstring":"Sequence The sequences of Seq2Pat.","docstring_tokens":"","code":"@property\ndef sequences(self) -> List[List]:\n \"\"\"Sequence\n The sequences of Seq2Pat.\n \"\"\"\n return self._sequences","code_tokens":"","url":876390} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"tokenization.py","full_name":"FullSentencePieceTokenizer.tokenize","func_name":"tokenize","docstring":"Tokenizes text into pieces.","docstring_tokens":"","code":"def tokenize(self, text):\n \"\"\"Tokenizes text into pieces.\"\"\"\n return encode_pieces(self.sp_model, text)","code_tokens":"","url":850332} +{"project_name":"thaines\/helit","file_name":"pruners.py","full_name":"PruneCap.setMinTrain","func_name":"setMinTrain","docstring":"Sets the minimum number of nodes allowed to be split.","docstring_tokens":"","code":"def setMinTrain(self, minTrain):\n \"\"\"Sets the minimum number of nodes allowed to be split.\"\"\"\n self.minTrain = minTrain","code_tokens":"","url":591340} +{"project_name":"BerkeleyLearnVerify\/VerifAI","file_name":"util.py","full_name":"bgr_to_rgb","func_name":"bgr_to_rgb","docstring":"Convert a list of images from BGR format to RGB format.","docstring_tokens":"","code":"def bgr_to_rgb(ims):\n \"\"\"Convert a list of images from BGR format to RGB format.\"\"\"\n out = []\n for im in ims:\n out.append(im[:, :, ::-1])\n return out","code_tokens":"","url":379361} +{"project_name":"deepmind\/bsuite","file_name":"plotting.py","full_name":"score_by_scaling","func_name":"score_by_scaling","docstring":"Apply scoring function based on mean and std.","docstring_tokens":"","code":"def score_by_scaling(df: pd.DataFrame, score_fn: Callable[[pd.DataFrame], float], scaling_var: str) -> float:\n \"\"\"Apply scoring function based on mean and std.\"\"\"\n scores = []\n for (_, sub_df) in df.groupby(scaling_var):\n scores.append(score_fn(sub_df))\n mean_score = np.clip(np.mean(scores), 0, 1)\n lcb_score = np.clip(np.mean(scores) - np.std(scores), 0, 1)\n return 0.5 * (mean_score + lcb_score)","code_tokens":"","url":410268} +{"project_name":"MycroftAI\/mycroft-core","file_name":"audioservice.py","full_name":"AudioService.prev","func_name":"prev","docstring":"Change to previous track.","docstring_tokens":"","code":"def prev(self):\n \"\"\"Change to previous track.\"\"\"\n self.bus.emit(Message('mycroft.audio.service.prev'))","code_tokens":"","url":290425} +{"project_name":"SPOClab-ca\/dn3","file_name":"dataset.py","full_name":"DN3ataset.clear_transforms","func_name":"clear_transforms","docstring":"Remove all added transforms from dataset.","docstring_tokens":"","code":"def clear_transforms(self):\n \"\"\"\n Remove all added transforms from dataset.\n \"\"\"\n self._transforms = list()","code_tokens":"","url":522320} +{"project_name":"tensorflow\/hub","file_name":"tf_utils.py","full_name":"composite_tensor_info_to_type_spec","func_name":"composite_tensor_info_to_type_spec","docstring":"Converts a `TensorInfo` for a composite tensor to a `TypeSpec` object.","docstring_tokens":"","code":"def composite_tensor_info_to_type_spec(tensor_info):\n \"\"\"Converts a `TensorInfo` for a composite tensor to a `TypeSpec` object.\"\"\"\n if nested_structure_coder is None or struct_pb2 is None:\n raise ValueError('This version of TensorFlow does not support composite tensors.')\n if tensor_info.WhichOneof('encoding') != 'composite_tensor':\n raise ValueError('Expected a TensorInfo with encoding=composite_tensor')\n spec_proto = struct_pb2.StructuredValue(type_spec_value=tensor_info.composite_tensor.type_spec)\n try:\n return nested_structure_coder.decode_proto(spec_proto)\n except AttributeError:\n struct_coder = nested_structure_coder.StructureCoder()\n return struct_coder.decode_proto(spec_proto)","code_tokens":"","url":571053} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"__init__.py","full_name":"register","func_name":"register","docstring":"Register the unit conversion classes with matplotlib.","docstring_tokens":"","code":"def register():\n \"\"\"Register the unit conversion classes with matplotlib.\"\"\"\n import matplotlib.units as mplU\n mplU.registry[str] = StrConverter()\n mplU.registry[Epoch] = EpochConverter()\n mplU.registry[Duration] = EpochConverter()\n mplU.registry[UnitDbl] = UnitDblConverter()","code_tokens":"","url":1379} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning---Tutorials","file_name":"visualization_utils.py","full_name":"draw_bounding_boxes_on_image_tensors","func_name":"draw_bounding_boxes_on_image_tensors","docstring":"Draws bounding boxes on batch of image tensors.","docstring_tokens":"","code":"def draw_bounding_boxes_on_image_tensors(images, boxes, classes, scores, category_index, max_boxes_to_draw=20, min_score_thresh=0.2):\n \"\"\"Draws bounding boxes on batch of image tensors.\n\n Args:\n images: A 4D uint8 image tensor of shape [N, H, W, C].\n boxes: [N, max_detections, 4] float32 tensor of detection boxes.\n classes: [N, max_detections] int tensor of detection classes. Note that\n classes are 1-indexed.\n scores: [N, max_detections] float32 tensor of detection scores.\n category_index: a dict that maps integer ids to category dicts. e.g.\n {1: {1: 'dog'}, 2: {2: 'cat'}, ...}\n max_boxes_to_draw: Maximum number of boxes to draw on an image. Default 20.\n min_score_thresh: Minimum score threshold for visualization. Default 0.2.\n\n Returns:\n 4D image tensor of type uint8, with boxes drawn on top.\n \"\"\"\n visualize_boxes_fn = functools.partial(visualize_boxes_and_labels_on_image_array, category_index=category_index, instance_masks=None, keypoints=None, use_normalized_coordinates=True, max_boxes_to_draw=max_boxes_to_draw, min_score_thresh=min_score_thresh, agnostic_mode=False, line_thickness=4)\n\n def draw_boxes(image_boxes_classes_scores):\n \"\"\"Draws boxes on image.\"\"\"\n (image, boxes, classes, scores) = image_boxes_classes_scores\n image_with_boxes = tf.py_func(visualize_boxes_fn, [image, boxes, classes, scores], tf.uint8)\n return image_with_boxes\n images = tf.map_fn(draw_boxes, (images, boxes, classes, scores), dtype=tf.uint8, back_prop=False)\n return images","code_tokens":"","url":58685} +{"project_name":"kingofspace0wzz\/wae-rnf-lm","file_name":"loss.py","full_name":"total_kld","func_name":"total_kld","docstring":"Use pytorch built-in distributions to calculate kl divergence.","docstring_tokens":"","code":"def total_kld(posterior, prior):\n \"\"\"\n Use pytorch built-in distributions to calculate kl divergence.\n\n \"\"\"\n return torch.sum(kl_divergence(posterior, prior))","code_tokens":"","url":941008} +{"project_name":"renmengye\/few-shot-ssl-public","file_name":"prototypical.py","full_name":"update_gmm_cluster","func_name":"update_gmm_cluster","docstring":"Updates cluster center based on assignment, GMM.","docstring_tokens":"","code":"def update_gmm_cluster(data, prob):\n \"\"\"Updates cluster center based on assignment, GMM.\n Args:\n data: [N, D] Data representation.\n prob: [N, K] Cluster assignment soft probability.\n Returns:\n cluster_centers: [K, D].\n \"\"\"\n print('prob', prob.get_shape())\n prob2 = prob \/ tf.reduce_sum(prob, [0], keep_dims=True)\n mean = tf.reduce_sum(tf.expand_dims(data, 1) * tf.expand_dims(prob2, 2), [0])\n d1 = tf.expand_dims(data, 1)\n var = tf.expand_dims(d1, 2) * tf.expand_dims(d1, 3)\n print('haha', var.get_shape())\n prob2 = tf.expand_dims(tf.expand_dims(prob2, 2), 3)\n print('kk', prob2.get_shape())\n var = tf.reduce_sum(var * prob2, [0])\n print('udpate covar', var.get_shape())\n return (mean, var)","code_tokens":"","url":179996} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"feedparser.py","full_name":"BufferedSubFile.push","func_name":"push","docstring":"Push some new data into this object.","docstring_tokens":"","code":"def push(self, data):\n \"\"\"Push some new data into this object.\"\"\"\n parts = data.splitlines(True)\n if not parts or not parts[0].endswith(('\\n', '\\r')):\n self._partial += parts\n return\n if self._partial:\n self._partial.append(parts[0])\n parts[0:1] = ''.join(self._partial).splitlines(True)\n del self._partial[:]\n if not parts[-1].endswith('\\n'):\n self._partial = [parts.pop()]\n self.pushlines(parts)","code_tokens":"","url":140133} +{"project_name":"FreshAirTonight\/af2complex","file_name":"complex.py","full_name":"extract_template_domain_mult","func_name":"extract_template_domain_mult","docstring":"Extracts the template features (in the format of AF-Multimer) of a domain specified by a list of domain ranges from a larger chain.","docstring_tokens":"","code":"def extract_template_domain_mult(mono_entry: Dict):\n \"\"\"Extracts the template features (in the format of AF-Multimer) of a domain specified\n by a list of domain ranges from a larger chain.\n\n Args:\n mono_entry: dictionary containing the features of a monomer in the multimer\n \"\"\"\n features = mono_entry['feature_dict']\n copy_num = mono_entry['copy_number']\n dom_range = mono_entry['domain_range']\n mono_sequence = features['sequence'][0].decode()\n if dom_range is not None:\n mono_seq = ''\n for (idx, boundary) in enumerate(dom_range):\n (sta, end) = boundary.split('-')\n sta = int(sta) - 1\n end = int(end)\n mono_seq += mono_sequence[sta:end]\n if idx == 0:\n temp_aatype = features['template_aatype'][:, sta:end]\n temp_all_atom_masks = features['template_all_atom_mask'][:, sta:end, :]\n temp_asym_ids = features['asym_id'][sta:end]\n temp_sym_ids = features['sym_id'][sta:end]\n temp_entity_ids = features['entity_id'][sta:end]\n temp_all_atom_positions = features['template_all_atom_positions'][:, sta:end, ...]\n else:\n temp_aatype = np.concatenate((temp_aatype, features['template_aatype'][:, sta:end]), axis=1)\n temp_all_atom_masks = np.concatenate((temp_all_atom_masks, features['template_all_atom_mask'][:, sta:end, :]), axis=1)\n temp_asym_ids = np.concatenate((temp_asym_ids, features['asym_id'][sta:end]), axis=0)\n temp_sym_ids = np.concatenate((temp_sym_ids, features['sym_id'][sta:end]), axis=0)\n temp_entity_ids = np.concatenate((temp_entity_ids, features['entity_id'][sta:end]), axis=0)\n temp_all_atom_positions = np.concatenate((temp_all_atom_positions, features['template_all_atom_positions'][:, sta:end, ...]), axis=1)\n features['template_aatype'] = temp_aatype\n features['template_all_atom_mask'] = temp_all_atom_masks\n features['asym_id'] = temp_asym_ids\n features['sym_id'] = temp_sym_ids\n features['entity_id'] = temp_entity_ids\n features['template_all_atom_positions'] = temp_all_atom_positions\n return features","code_tokens":"","url":400530} +{"project_name":"yinyunie\/ScenePriors","file_name":"so3.py","full_name":"so3_log_map","func_name":"so3_log_map","docstring":"Convert a batch of 3x3 rotation matrices `R` to a batch of 3-dimensional matrix logarithms of rotation matrices The conversion has a singularity around `(R=I)` which is handled by clamping controlled with the `eps` and `cos_bound` arguments.","docstring_tokens":"","code":"def so3_log_map(R: torch.Tensor, eps: float=0.0001, cos_bound: float=0.0001) -> torch.Tensor:\n \"\"\"\n Convert a batch of 3x3 rotation matrices `R`\n to a batch of 3-dimensional matrix logarithms of rotation matrices\n The conversion has a singularity around `(R=I)` which is handled\n by clamping controlled with the `eps` and `cos_bound` arguments.\n\n Args:\n R: batch of rotation matrices of shape `(minibatch, 3, 3)`.\n eps: A float constant handling the conversion singularity.\n cos_bound: Clamps the cosine of the rotation angle to\n [-1 + cos_bound, 1 - cos_bound] to avoid non-finite outputs\/gradients\n of the `acos` call when computing `so3_rotation_angle`.\n Note that the non-finite outputs\/gradients are returned when\n the rotation angle is close to 0 or \u00c3\\x8f\u00c2\\x80.\n\n Returns:\n Batch of logarithms of input rotation matrices\n of shape `(minibatch, 3)`.\n\n Raises:\n ValueError if `R` is of incorrect shape.\n ValueError if `R` has an unexpected trace.\n \"\"\"\n (N, dim1, dim2) = R.shape\n if dim1 != 3 or dim2 != 3:\n raise ValueError('Input has to be a batch of 3x3 Tensors.')\n phi = so3_rotation_angle(R, cos_bound=cos_bound, eps=eps)\n phi_sin = torch.sin(phi)\n phi_factor = torch.empty_like(phi)\n ok_denom = phi_sin.abs() > 0.5 * eps\n phi_factor[~ok_denom] = 0.5 + phi[~ok_denom] ** 2 * (1.0 \/ 12)\n phi_factor[ok_denom] = phi[ok_denom] \/ (2.0 * phi_sin[ok_denom])\n log_rot_hat = phi_factor[:, None, None] * (R - R.permute(0, 2, 1))\n log_rot = hat_inv(log_rot_hat)\n return log_rot","code_tokens":"","url":329937} +{"project_name":"Davide-sd\/GIMP-style-transfer","file_name":"module.py","full_name":"discriminator","func_name":"discriminator","docstring":"Discriminator agent, that provides us with information about image plausibility at different scales.","docstring_tokens":"","code":"def discriminator(image, options, reuse=True, name='discriminator'):\n \"\"\"\n Discriminator agent, that provides us with information about image plausibility at\n different scales.\n Args:\n image: input tensor\n options: options defining number of kernels in conv layers\n reuse: to create new discriminator or use existing\n name: name of the discriminator\n\n Returns:\n Image estimates at different scales.\n \"\"\"\n with tf.variable_scope(name):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n else:\n assert tf.get_variable_scope().reuse is False\n h0 = lrelu(instance_norm(conv2d(image, options.df_dim * 2, ks=5, name='d_h0_conv'), name='d_bn0'))\n h0_pred = conv2d(h0, 1, ks=5, s=1, name='d_h0_pred', activation_fn=None)\n h1 = lrelu(instance_norm(conv2d(h0, options.df_dim * 2, ks=5, name='d_h1_conv'), name='d_bn1'))\n h1_pred = conv2d(h1, 1, ks=10, s=1, name='d_h1_pred', activation_fn=None)\n h2 = lrelu(instance_norm(conv2d(h1, options.df_dim * 4, ks=5, name='d_h2_conv'), name='d_bn2'))\n h3 = lrelu(instance_norm(conv2d(h2, options.df_dim * 8, ks=5, name='d_h3_conv'), name='d_bn3'))\n h3_pred = conv2d(h3, 1, ks=10, s=1, name='d_h3_pred', activation_fn=None)\n h4 = lrelu(instance_norm(conv2d(h3, options.df_dim * 8, ks=5, name='d_h4_conv'), name='d_bn4'))\n h5 = lrelu(instance_norm(conv2d(h4, options.df_dim * 16, ks=5, name='d_h5_conv'), name='d_bn5'))\n h5_pred = conv2d(h5, 1, ks=6, s=1, name='d_h5_pred', activation_fn=None)\n h6 = lrelu(instance_norm(conv2d(h5, options.df_dim * 16, ks=5, name='d_h6_conv'), name='d_bn6'))\n h6_pred = conv2d(h6, 1, ks=3, s=1, name='d_h6_pred', activation_fn=None)\n return {'scale_0': h0_pred, 'scale_1': h1_pred, 'scale_3': h3_pred, 'scale_5': h5_pred, 'scale_6': h6_pred}","code_tokens":"","url":202423} +{"project_name":"hayd\/pep8radius","file_name":"vcs.py","full_name":"using_git","func_name":"using_git","docstring":"Test whether the directory cwd is contained in a git repository.","docstring_tokens":"","code":"def using_git(cwd):\n \"\"\"Test whether the directory cwd is contained in a git repository.\"\"\"\n try:\n git_log = shell_out(['git', 'log'], cwd=cwd)\n return True\n except (CalledProcessError, OSError):\n return False","code_tokens":"","url":279752} +{"project_name":"thu-ml\/tianshou","file_name":"bcq.py","full_name":"BCQPolicy.sync_weight","func_name":"sync_weight","docstring":"Soft-update the weight for the target network.","docstring_tokens":"","code":"def sync_weight(self) -> None:\n \"\"\"Soft-update the weight for the target network.\"\"\"\n self.soft_update(self.critic1_target, self.critic1, self.tau)\n self.soft_update(self.critic2_target, self.critic2, self.tau)\n self.soft_update(self.actor_target, self.actor, self.tau)","code_tokens":"","url":355258} +{"project_name":"instadeepai\/jumanji","file_name":"parametric_distribution.py","full_name":"ParametricDistribution.sample","func_name":"sample","docstring":"Returns a sample from the postprocessed distribution.","docstring_tokens":"","code":"def sample(self, parameters: chex.Array, seed: chex.PRNGKey) -> chex.Array:\n \"\"\"Returns a sample from the postprocessed distribution.\"\"\"\n return self.postprocess(self.sample_no_postprocessing(parameters, seed))","code_tokens":"","url":594595} +{"project_name":"rudranil723\/mini-main","file_name":"_regex_core.py","full_name":"parse_octal_escape","func_name":"parse_octal_escape","docstring":"Parses an octal escape sequence.","docstring_tokens":"","code":"def parse_octal_escape(source, info, digits, in_set):\n \"\"\"Parses an octal escape sequence.\"\"\"\n saved_pos = source.pos\n ch = source.get()\n while len(digits) < 3 and ch in OCT_DIGITS:\n digits.append(ch)\n saved_pos = source.pos\n ch = source.get()\n source.pos = saved_pos\n try:\n value = int(''.join(digits), 8)\n return make_character(info, value, in_set)\n except ValueError:\n if digits[0] in OCT_DIGITS:\n raise error('incomplete escape \\\\%s' % ''.join(digits), source.string, source.pos)\n else:\n raise error('bad escape \\\\%s' % digits[0], source.string, source.pos)","code_tokens":"","url":269810} +{"project_name":"palmettos\/neat-autoencoders","file_name":"evolve.py","full_name":"CircuitGenome.configure_crossover","func_name":"configure_crossover","docstring":"Configure a new genome by crossover from two parent genomes.","docstring_tokens":"","code":"def configure_crossover(self, genome1, genome2, config):\n \"\"\" Configure a new genome by crossover from two parent genomes. \"\"\"\n if genome1.fitness > genome2.fitness:\n (parent1, parent2) = (genome1, genome2)\n else:\n (parent1, parent2) = (genome2, genome1)\n for (key, cg1) in iteritems(parent1.connections):\n cg2 = parent2.connections.get(key)\n if cg2 is None:\n self.connections[key] = cg1.copy()\n else:\n self.connections[key] = cg1.crossover(cg2)\n parent1_set = parent1.nodes\n parent2_set = parent2.nodes\n for (key, ng1) in iteritems(parent1_set):\n ng2 = parent2_set.get(key)\n assert key not in self.nodes\n if ng2 is None:\n self.nodes[key] = ng1.copy()\n else:\n self.nodes[key] = ng1.crossover(ng2)","code_tokens":"","url":735131} +{"project_name":"keras-team\/keras-cv","file_name":"efficientnet_v2_backbone.py","full_name":"round_repeats","func_name":"round_repeats","docstring":"Round number of repeats based on depth multiplier.","docstring_tokens":"","code":"def round_repeats(repeats, depth_coefficient):\n \"\"\"Round number of repeats based on depth multiplier.\"\"\"\n return int(math.ceil(depth_coefficient * repeats))","code_tokens":"","url":595207} +{"project_name":"Alexander-Parker\/youtube_nlp","file_name":"common.py","full_name":"validate_integer","func_name":"validate_integer","docstring":"Validates that 'value' is an integer (or basestring representation).","docstring_tokens":"","code":"def validate_integer(option, value):\n \"\"\"Validates that 'value' is an integer (or basestring representation).\n \"\"\"\n if isinstance(value, integer_types):\n return value\n elif isinstance(value, string_type):\n try:\n return int(value)\n except ValueError:\n raise ValueError('The value of %s must be an integer' % (option,))\n raise TypeError('Wrong type for %s, value must be an integer' % (option,))","code_tokens":"","url":970353} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"data_quality_monitoring_config.py","full_name":"DataQualityDistributionConstraints.valid_categorical_drift_method","func_name":"valid_categorical_drift_method","docstring":"Checks whether categorical_drift_method is valid or not.","docstring_tokens":"","code":"@staticmethod\ndef valid_categorical_drift_method(categorical_drift_method):\n \"\"\"Checks whether categorical_drift_method is valid or not.\"\"\"\n if not categorical_drift_method:\n return True\n return categorical_drift_method in [CHI_SQUARED_METHOD, L_INFINITY_METHOD]","code_tokens":"","url":830434} +{"project_name":"ANazaret\/unbounded-depth-neural-","file_name":"models.py","full_name":"TruncatedPoisson.nu_L","func_name":"nu_L","docstring":"Returns the variational parameter nu_L, which is reparametrized to be positive.","docstring_tokens":"","code":"@property\ndef nu_L(self):\n \"\"\"Returns the variational parameter nu_L, which is reparametrized to be positive.\"\"\"\n return nn.Softplus()(self._nu_L)","code_tokens":"","url":947624} +{"project_name":"wandb\/wandb","file_name":"artifact.py","full_name":"Artifact.source_entity","func_name":"source_entity","docstring":"The name of the entity of the primary (sequence) artifact collection.","docstring_tokens":"","code":"@property\ndef source_entity(self) -> str:\n \"\"\"The name of the entity of the primary (sequence) artifact collection.\"\"\"\n self._ensure_logged('source_entity')\n assert self._source_entity is not None\n return self._source_entity","code_tokens":"","url":941615} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"model.py","full_name":"Model.train_step","func_name":"train_step","docstring":"Train network using standard gradient descent.","docstring_tokens":"","code":"def train_step(self, sess, observations, internal_state, actions, rewards, terminated, pads, avg_episode_reward=0, greedy_episode_reward=0):\n \"\"\"Train network using standard gradient descent.\"\"\"\n outputs = [self.raw_loss, self.gradient_ops, self.summary]\n feed_dict = {self.internal_state: internal_state, self.rewards: rewards, self.terminated: terminated, self.pads: pads, self.avg_episode_reward: avg_episode_reward, self.greedy_episode_reward: greedy_episode_reward}\n time_len = None\n for (action_place, action) in zip(self.actions, actions):\n if time_len is None:\n time_len = len(action)\n assert time_len == len(action)\n feed_dict[action_place] = action\n for (obs_place, obs) in zip(self.observations, observations):\n assert time_len == len(obs)\n feed_dict[obs_place] = obs\n assert len(rewards) == time_len - 1\n return sess.run(outputs, feed_dict=feed_dict)","code_tokens":"","url":26093} +{"project_name":"mrahtz\/learning-from-human-preferences","file_name":"pref_db_test.py","full_name":"TestPrefDB.test_append_delete","func_name":"test_append_delete","docstring":"Do a number of appends\/deletes and check that the number of preferences and segments is as expected at all times.","docstring_tokens":"","code":"def test_append_delete(self):\n \"\"\"\n Do a number of appends\/deletes and check that the number of\n preferences and segments is as expected at all times.\n \"\"\"\n p = PrefDB(maxlen=10)\n s1 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n s2 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n p.append(s1, s2, [1.0, 0.0])\n self.assertEqual(len(p.segments), 2)\n self.assertEqual(len(p.prefs), 1)\n p.append(s1, s2, [0.0, 1.0])\n self.assertEqual(len(p.segments), 2)\n self.assertEqual(len(p.prefs), 2)\n s1 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n p.append(s1, s2, [1.0, 0.0])\n self.assertEqual(len(p.segments), 3)\n self.assertEqual(len(p.prefs), 3)\n s2 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n p.append(s1, s2, [1.0, 0.0])\n self.assertEqual(len(p.segments), 4)\n self.assertEqual(len(p.prefs), 4)\n s1 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n s2 = np.random.randint(low=-10, high=10, size=(25, 84, 84, 4))\n p.append(s1, s2, [1.0, 0.0])\n self.assertEqual(len(p.segments), 6)\n self.assertEqual(len(p.prefs), 5)\n prefs_pre = list(p.prefs)\n p.del_first()\n self.assertEqual(len(p.prefs), 4)\n self.assertEqual(p.prefs, prefs_pre[1:])\n self.assertEqual(len(p.segments), 6)\n p.del_first()\n self.assertEqual(len(p.prefs), 3)\n self.assertEqual(len(p.segments), 5)\n p.del_first()\n self.assertEqual(len(p.prefs), 2)\n self.assertEqual(len(p.segments), 4)\n p.del_first()\n self.assertEqual(len(p.prefs), 1)\n self.assertEqual(len(p.segments), 2)\n p.del_first()\n self.assertEqual(len(p.prefs), 0)\n self.assertEqual(len(p.segments), 0)","code_tokens":"","url":262127} +{"project_name":"AgnostiqHQ\/covalent","file_name":"init_test.py","full_name":"test_get_executor","func_name":"test_get_executor","docstring":"Test get executor method in executor manager.","docstring_tokens":"","code":"def test_get_executor(mocker):\n \"\"\"Test get executor method in executor manager.\"\"\"\n\n class MockExecutor(BaseExecutor):\n\n def run(self):\n pass\n\n def plugin_mock(**kwargs):\n return 'plugin map func called'\n mocker.patch('covalent.executor._ExecutorManager.__init__', return_value=None)\n em = _ExecutorManager()\n resp = em.get_executor(MockExecutor())\n assert isinstance(resp, MockExecutor)\n get_config_mock = mocker.patch('covalent.executor.get_config', return_value={'test_arg': 1})\n update_config_mock = mocker.patch('covalent.executor.update_config')\n em.executor_plugins_map = {'mock_name': plugin_mock}\n resp = em.get_executor(name='mock_name')\n update_config_mock.assert_called_once_with()\n get_config_mock.assert_called_once_with('executors.mock_name')\n assert resp == 'plugin map func called'\n with pytest.raises(ValueError):\n em.get_executor(name='non-existent')\n with pytest.raises(TypeError):\n em.get_executor(name=3)","code_tokens":"","url":489799} +{"project_name":"ForrestPi\/ObjectDetectionTricks","file_name":"distribution_test.py","full_name":"TestDistribution.testSamplingPreservesDtype","func_name":"testSamplingPreservesDtype","docstring":"Checks that sampling's output has the same precision as its input.","docstring_tokens":"","code":"@parameterized.named_parameters(('Single', np.float32), ('Double', np.float64))\ndef testSamplingPreservesDtype(self, float_dtype):\n \"\"\"Checks that sampling's output has the same precision as its input.\"\"\"\n n = 16\n alpha = float_dtype(np.exp(np.random.normal(size=n)))\n scale = float_dtype(np.exp(np.random.normal(size=n)))\n y = self._distribution.draw_samples(alpha, scale).detach().numpy()\n np.testing.assert_(y.dtype, float_dtype)","code_tokens":"","url":744699} +{"project_name":"zjut-jianhuazhang\/CalibRCNN","file_name":"utils.py","full_name":"projective_inverse_warp","func_name":"projective_inverse_warp","docstring":"Inverse warp a source image to the target image plane based on projection.","docstring_tokens":"","code":"def projective_inverse_warp(img, depth, pose, intrinsics):\n \"\"\"Inverse warp a source image to the target image plane based on projection.\n\n Args:\n img: the source image [batch, height_s, width_s, 3]\n depth: depth map of the target image [batch, height_t, width_t]\n pose: target to source camera transformation matrix [batch, 4, 4], in the\n order of tx, ty, tz, rx, ry, rz\n intrinsics: camera intrinsics [batch, 3, 3]\n Returns:\n Source image inverse warped to the target image plane [batch, height_t,\n width_t, 3]\n \"\"\"\n (batch, height, width, _) = img.get_shape().as_list()\n batch = tf.shape(img)[0]\n pixel_coords = meshgrid(batch, height, width)\n cam_coords = pixel2cam(depth, pixel_coords, intrinsics)\n filler = tf.constant([0.0, 0.0, 0.0, 1.0], shape=[1, 1, 4])\n filler = tf.tile(filler, [batch, 1, 1])\n intrinsics = tf.concat([intrinsics, tf.zeros([batch, 3, 1])], axis=2)\n intrinsics = tf.concat([intrinsics, filler], axis=1)\n proj_tgt_cam_to_src_pixel = tf.matmul(intrinsics, pose)\n src_pixel_coords = cam2pixel(cam_coords, proj_tgt_cam_to_src_pixel)\n output_img = bilinear_sampler(img, src_pixel_coords, depth)\n return (output_img, cam_coords)","code_tokens":"","url":108886} +{"project_name":"secretflow\/secretflow","file_name":"cli.py","full_name":"component","func_name":"component","docstring":"Get information of components in SecretFlow package.","docstring_tokens":"","code":"@cli.group()\ndef component():\n \"\"\"Get information of components in SecretFlow package.\"\"\"\n pass","code_tokens":"","url":856239} +{"project_name":"google\/mentornet","file_name":"models.py","full_name":"vstar_spcl_linear","func_name":"vstar_spcl_linear","docstring":"Variable v_star function for self-paced curriculum learning (linear).","docstring_tokens":"","code":"def vstar_spcl_linear(inbatch, **kwargs):\n \"\"\"Variable v_star function for self-paced curriculum learning (linear).\n\n Args:\n inbatch: a numpy array with the following\n Index 0: Loss\n Index 1: Loss difference from moving average\n Index 3: Label\n Index 4: Epoch\n **kwargs: hyper-parameter specified in vtsar_gamma\n\n Returns:\n v: [batch_size, 1] weight vector.\n \"\"\"\n if 'vstar_gamma' in kwargs:\n gamma = kwargs['vstar_gamma']\n else:\n gamma = 1\n assert gamma != 0\n loss_diff = inbatch[:, 1]\n v = -1.0 \/ gamma * loss_diff + 1\n v = np.maximum(np.minimum(v, 1), 0)\n return v","code_tokens":"","url":632548} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"prediction_to_annotation_converter.py","full_name":"DetectionToAnnotationConverter.convert_to_annotation","func_name":"convert_to_annotation","docstring":"Convert predictions to annotation format.","docstring_tokens":"","code":"def convert_to_annotation(self, predictions: Union[DetectionResult, np.ndarray], metadata: Optional[Dict[str, np.ndarray]]=None) -> AnnotationSceneEntity:\n \"\"\"Convert predictions to annotation format.\n\n Args:\n predictions (DetectionResult|np.ndarray): detection represented in ModelAPI format or\n array with shape [num_predictions, 6] or\n [num_predictions, 7]\n Supported detection formats are\n\n * [label, confidence, x1, y1, x2, y2]\n * [_, label, confidence, x1, y1, x2, y2]\n .. note::\n `label` can be any integer that can be mapped to `self.labels`\n `confidence` should be a value between 0 and 1\n `x1`, `x2`, `y1` and `y2` are expected to be normalized.\n metadata (Optional[Dict]): Additional information\n\n Returns:\n AnnotationScene: AnnotationScene Object containing the boxes obtained from the prediction.\n \"\"\"\n if isinstance(predictions, DetectionResult):\n detections = detection2array(predictions.objects)\n else:\n detections = predictions\n if metadata:\n detections[:, 2:] \/= np.tile(metadata['original_shape'][1::-1], 2)\n annotations = self.__convert_to_annotations(detections)\n annotation_scene = AnnotationSceneEntity(id=ID(), kind=AnnotationSceneKind.PREDICTION, editor='otx', creation_date=now(), annotations=annotations)\n return annotation_scene","code_tokens":"","url":918776} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"utils.py","full_name":"cov","func_name":"cov","docstring":"Compute the sample covariance between two vectors.","docstring_tokens":"","code":"def cov(a, b):\n \"\"\"Compute the sample covariance between two vectors.\"\"\"\n mu_a = tf.reduce_mean(a)\n mu_b = tf.reduce_mean(b)\n n = tf.to_float(tf.shape(a)[0])\n return tf.reduce_sum((a - mu_a) * (b - mu_b)) \/ (n - 1.0)","code_tokens":"","url":752690} +{"project_name":"aalgirdas\/Artificial-Intelligence-Course","file_name":"utils.py","full_name":"matrix_multiplication","func_name":"matrix_multiplication","docstring":"Return a matrix as a matrix-multiplication of x and arbitrary number of matrices *y.","docstring_tokens":"","code":"def matrix_multiplication(x, *y):\n \"\"\"Return a matrix as a matrix-multiplication of x and arbitrary number of matrices *y.\"\"\"\n result = x\n for _y in y:\n result = np.matmul(result, _y)\n return result","code_tokens":"","url":79707} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"test_regexremove.py","full_name":"TestRegexRemove.test_nosource_with_output","func_name":"test_nosource_with_output","docstring":"Test that the check_conditions returns true when given a code-cell that has non-empty outputs but no source.","docstring_tokens":"","code":"def test_nosource_with_output(self):\n \"\"\"\n Test that the check_conditions returns true when given a code-cell\n that has non-empty outputs but no source.\n \"\"\"\n cell = {'cell_type': 'code', 'execution_count': 2, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': 'I exist.\\n'}], 'source': ''}\n preprocessor = self.build_preprocessor()\n node = from_dict(cell)\n assert preprocessor.check_conditions(node)","code_tokens":"","url":1847} +{"project_name":"AgnostiqHQ\/covalent","file_name":"qbase.py","full_name":"QCResult.expand","func_name":"expand","docstring":"Expand result object into a list of result objects, one for each execution.","docstring_tokens":"","code":"def expand(self) -> List['QCResult']:\n \"\"\"\n Expand result object into a list of result objects, one for each execution.\n \"\"\"\n result_objs = []\n for (i, result) in enumerate(self.results):\n _result_obj = QCResult(results=[result], execution_time=self.execution_time, metadata={})\n execution_metadata = self.metadata['execution_metadata']\n if len(self.metadata['execution_metadata']) > 0:\n execution_metadata = execution_metadata[i]\n _result_obj.metadata.update(execution_metadata=[execution_metadata], device_name=self.metadata['device_name'], executor_name=self.metadata['executor_name'], executor_backend_name=self.metadata['executor_backend_name'])\n result_objs.append(_result_obj)\n return result_objs","code_tokens":"","url":489389} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"debug.py","full_name":"DebugControl.write_formatted_info","func_name":"write_formatted_info","docstring":"Write a sequence of (label,data) pairs nicely.","docstring_tokens":"","code":"def write_formatted_info(self, header, info):\n \"\"\"Write a sequence of (label,data) pairs nicely.\"\"\"\n self.write(info_header(header))\n for line in info_formatter(info):\n self.write(' %s' % line)","code_tokens":"","url":147689} +{"project_name":"cesium-ml\/cesium","file_name":"util.py","full_name":"regular_periodic","func_name":"regular_periodic","docstring":"Generate periodic test data sampled at regular intervals: superposition of multiple sine waves, each with multiple harmonics.","docstring_tokens":"","code":"def regular_periodic(freqs, amplitudes, phase, size=501):\n \"\"\"Generate periodic test data sampled at regular intervals: superposition\n of multiple sine waves, each with multiple harmonics.\n \"\"\"\n times = np.linspace(0, 2, size)\n values = np.zeros(size)\n for ((i, j), amplitude) in np.ndenumerate(amplitudes):\n values += amplitude * np.sin(2 * np.pi * times * freqs[i] * (j + 1) + phase)\n errors = 0.0001 * np.ones(size)\n return (times, values, errors)","code_tokens":"","url":476683} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"core.py","full_name":"shape","func_name":"shape","docstring":"maskedarray version of the numpy function.","docstring_tokens":"","code":"def shape(obj):\n \"\"\"maskedarray version of the numpy function.\"\"\"\n return np.shape(getdata(obj))","code_tokens":"","url":2854} +{"project_name":"0xangelo\/raylab","file_name":"off_policy.py","full_name":"OffPolicyMixin.add_options","func_name":"add_options","docstring":"Decorator to add default off-policy options used by OffPolicyMixin.","docstring_tokens":"","code":"@staticmethod\ndef add_options(policy_cls: type) -> type:\n \"\"\"Decorator to add default off-policy options used by OffPolicyMixin.\"\"\"\n return off_policy_options(policy_cls)","code_tokens":"","url":848312} +{"project_name":"fpthink\/3D-WSIS","file_name":"GraphConvInfo.py","full_name":"GraphConvInfo.get_buffers","func_name":"get_buffers","docstring":"Provides data to `GraphConvModule`.","docstring_tokens":"","code":"def get_buffers(self):\n \"\"\" Provides data to `GraphConvModule`.\n \"\"\"\n return (self._idxn, self._idxe, self._degrees, self._degrees_gpu, self._edgefeats)","code_tokens":"","url":4607} +{"project_name":"tensorflow\/privacy","file_name":"epsilon_lower_bound.py","full_name":"EpsilonLowerBound.compute_epsilon_lower_bound","func_name":"compute_epsilon_lower_bound","docstring":"Computes lower bound w\/ a specified method and returns top-k epsilons.","docstring_tokens":"","code":"def compute_epsilon_lower_bound(self, method: BoundMethod, k: Optional[int]=None) -> npt.NDArray[float]:\n \"\"\"Computes lower bound w\/ a specified method and returns top-k epsilons.\n\n Args:\n method: the method to use for ratio bound.\n k: if specified, will return top-k values.\n\n Returns:\n An array of bounds.\n \"\"\"\n if method not in self._rbs[0].available_methods:\n raise ValueError(f'Method {method} not recognized.')\n ratio_bound = np.concatenate([rb.compute_bound(method) for rb in self._rbs])\n bounds = np.log(ratio_bound[ratio_bound > 0])\n bounds = np.sort(bounds)[::-1]\n if k is None or k >= bounds.size:\n return bounds\n return bounds[:k]","code_tokens":"","url":824846} +{"project_name":"IDEA-Research\/detrex","file_name":"position_embedding.py","full_name":"PositionEmbeddingSine.forward","func_name":"forward","docstring":"Forward function for `PositionEmbeddingSine`.","docstring_tokens":"","code":"def forward(self, mask: torch.Tensor, **kwargs) -> torch.Tensor:\n \"\"\"Forward function for `PositionEmbeddingSine`.\n\n Args:\n mask (torch.Tensor): ByteTensor mask. Non-zero values representing\n ignored positions, while zero values means valid positions\n for the input tensor. Shape as `(bs, h, w)`.\n\n Returns:\n torch.Tensor: Returned position embedding with\n shape `(bs, num_pos_feats * 2, h, w)`\n \"\"\"\n assert mask is not None\n not_mask = ~mask\n y_embed = not_mask.cumsum(1, dtype=torch.float32)\n x_embed = not_mask.cumsum(2, dtype=torch.float32)\n if self.normalize:\n y_embed = (y_embed + self.offset) \/ (y_embed[:, -1:, :] + self.eps) * self.scale\n x_embed = (x_embed + self.offset) \/ (x_embed[:, :, -1:] + self.eps) * self.scale\n dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=mask.device)\n dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode='floor') \/ self.num_pos_feats)\n pos_x = x_embed[:, :, :, None] \/ dim_t\n pos_y = y_embed[:, :, :, None] \/ dim_t\n (B, H, W) = mask.size()\n pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).view(B, H, W, -1)\n pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).view(B, H, W, -1)\n pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)\n return pos","code_tokens":"","url":549788} +{"project_name":"arxyzan\/data2vec-pytorch","file_name":"trainer.py","full_name":"AudioTrainer.train_step","func_name":"train_step","docstring":"Train one batch of data and return loss.","docstring_tokens":"","code":"def train_step(self, batch):\n \"\"\"\n Train one batch of data and return loss.\n\n Args:\n batch: A batch of data, inputs, labels and mask with shape [batch_size, seq_len]\n\n Returns:\n Loss value\n \"\"\"\n (src, mask) = batch\n (src, mask) = (src.to(self.device), mask.to(self.device))\n (x, y) = self.model(src, src, mask)\n loss = self.criterion(x.float(), y.float()).sum(dim=-1).div(x.size(0))\n loss.backward()\n self.optimizer.step()\n self.optimizer.zero_grad()\n return loss.item()","code_tokens":"","url":126776} +{"project_name":"algoterranean\/3dgan","file_name":"summaries.py","full_name":"summarize_gradients","func_name":"summarize_gradients","docstring":"Adds histogram summaries for input list.","docstring_tokens":"","code":"def summarize_gradients(grads_and_vars, name=None):\n \"\"\"Adds histogram summaries for input list.\n\n Args:\n grads_and_vars: List, a list of tuples in form (grad, var).e\n name: String, name to use for var scope.\n \"\"\"\n with tf.name_scope(name, 'gradients', grads_and_vars):\n for (g, v) in grads_and_vars:\n n = hem.tensor_name(v) + '\/gradient'\n tf.summary.histogram(n, g)\n tf.summary.scalar(n, tf.reduce_mean(g))","code_tokens":"","url":404892} +{"project_name":"cwlinkem\/linkuce","file_name":"fasta_to_nexus.py","full_name":"parse_sequence_fasta","func_name":"parse_sequence_fasta","docstring":"Takes a fasta file, pulls out GI and TI numbers and sequence.","docstring_tokens":"","code":"def parse_sequence_fasta(inp):\n \"\"\"Takes a fasta file, pulls out GI and TI numbers and sequence.\"\"\"\n identifiers = []\n sequences = []\n current_seq = []\n x = {}\n for line in inp:\n stripped = line.strip()\n if line.startswith('>'):\n if current_seq:\n sequences.append(''.join(current_seq))\n identifiers.append(stripped[1:])\n current_seq = []\n elif stripped:\n current_seq.append(stripped)\n if current_seq:\n sequences.append(''.join(current_seq))\n assert len(identifiers) == len(sequences)\n return (identifiers, sequences)","code_tokens":"","url":602742} +{"project_name":"SSQ\/Coursera-Ng-Convolutional-Neural-","file_name":"Art+Generation+with+Neural+Style+Transfer+-+v2.py","full_name":"compute_content_cost","func_name":"compute_content_cost","docstring":"Computes the content cost Arguments: a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G Returns: J_content -- scalar that you compute using equation 1 above.","docstring_tokens":"","code":"def compute_content_cost(a_C, a_G):\n \"\"\"\n Computes the content cost\n \n Arguments:\n a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C \n a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G\n \n Returns: \n J_content -- scalar that you compute using equation 1 above.\n \"\"\"\n (m, n_H, n_W, n_C) = a_G.get_shape().as_list()\n a_C_unrolled = tf.reshape(a_C, [m, n_H * n_W, n_C])\n a_G_unrolled = tf.reshape(a_G, [m, n_H * n_W, n_C])\n J_content = tf.reduce_sum(tf.square(tf.subtract(a_C_unrolled, a_G_unrolled))) \/ (4 * n_H * n_W * n_C)\n return J_content","code_tokens":"","url":137654} +{"project_name":"kornia\/kornia","file_name":"helpers.py","full_name":"safe_inverse_with_mask","func_name":"safe_inverse_with_mask","docstring":"Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.","docstring_tokens":"","code":"def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:\n \"\"\"Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid\n solution.\"\"\"\n if not isinstance(A, Tensor):\n raise AssertionError(f'A must be Tensor. Got: {type(A)}.')\n dtype_original = A.dtype\n if dtype_original not in (torch.float32, torch.float64):\n dtype = torch.float32\n else:\n dtype = dtype_original\n (inverse, info) = inv_ex(A.to(dtype))\n mask = info == 0\n return (inverse.to(dtype_original), mask)","code_tokens":"","url":622305} +{"project_name":"facebookresearch\/dmae_st","file_name":"epoch_trainer.py","full_name":"EpochTrainer.reg_rank","func_name":"reg_rank","docstring":"Register rank for process in distributed training.","docstring_tokens":"","code":"def reg_rank(self, rank: int):\n \"\"\"\n Register rank for process in distributed training.\n\n Args:\n rank (int): Rank, int >= 0\n \"\"\"\n self.distributed = True\n self.rank = rank","code_tokens":"","url":522048} +{"project_name":"s3prl\/s3prl","file_name":"expert.py","full_name":"match","func_name":"match","docstring":"Match between a query and a doc.","docstring_tokens":"","code":"def match(query, doc, query_name, doc_name, dist_fn, minmax_norm, dtwrc):\n \"\"\"Match between a query and a doc.\"\"\"\n dist = dist_fn(query, doc)\n if minmax_norm:\n dist_min = dist.min(1)[:, np.newaxis]\n dist_max = dist.max(1)[:, np.newaxis]\n dist = (dist - dist_min) \/ np.clip(dist_max - dist_min, 1e-09, np.inf)\n dtw_result = dtw(x=dist, **dtwrc)\n cost = dtw_result.normalizedDistance\n return (query_name, doc_name, -1 * cost)","code_tokens":"","url":327452} +{"project_name":"JosephKJ\/iOD","file_name":"poolers.py","full_name":"convert_boxes_to_pooler_format","func_name":"convert_boxes_to_pooler_format","docstring":"Convert all boxes in `box_lists` to the low-level format used by ROI pooling ops (see description under Returns).","docstring_tokens":"","code":"def convert_boxes_to_pooler_format(box_lists):\n \"\"\"\n Convert all boxes in `box_lists` to the low-level format used by ROI pooling ops\n (see description under Returns).\n\n Args:\n box_lists (list[Boxes] | list[RotatedBoxes]):\n A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch.\n\n Returns:\n When input is list[Boxes]:\n A tensor of shape (M, 5), where M is the total number of boxes aggregated over all\n N batch images.\n The 5 columns are (batch index, x0, y0, x1, y1), where batch index\n is the index in [0, N) identifying which batch image the box with corners at\n (x0, y0, x1, y1) comes from.\n When input is list[RotatedBoxes]:\n A tensor of shape (M, 6), where M is the total number of boxes aggregated over all\n N batch images.\n The 6 columns are (batch index, x_ctr, y_ctr, width, height, angle_degrees),\n where batch index is the index in [0, N) identifying which batch image the\n rotated box (x_ctr, y_ctr, width, height, angle_degrees) comes from.\n \"\"\"\n\n def fmt_box_list(box_tensor, batch_index):\n repeated_index = torch.full((len(box_tensor), 1), batch_index, dtype=box_tensor.dtype, device=box_tensor.device)\n return cat((repeated_index, box_tensor), dim=1)\n pooler_fmt_boxes = cat([fmt_box_list(box_list.tensor, i) for (i, box_list) in enumerate(box_lists)], dim=0)\n return pooler_fmt_boxes","code_tokens":"","url":576845} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"deccheck.py","full_name":"test_quantize_api","func_name":"test_quantize_api","docstring":"Iterate the 'quantize' method through many test cases, using the optional arguments.","docstring_tokens":"","code":"def test_quantize_api(method, prec, exprange, restricted_range, itr, stat):\n \"\"\"Iterate the 'quantize' method through many test cases, using\n the optional arguments.\"\"\"\n for op in all_binary(prec, restricted_range, itr):\n for rounding in RoundModes:\n c = randcontext(exprange)\n quantizeop = (op[0], op[1], rounding, c)\n t = TestSet(method, quantizeop)\n try:\n if not convert(t):\n continue\n callfuncs(t)\n verify(t, stat)\n except VerifyError as err:\n log(err)","code_tokens":"","url":284670} +{"project_name":"zcablii\/LSKNet","file_name":"oriented_reppoints_head.py","full_name":"OrientedRepPointsHead.loss","func_name":"loss","docstring":"Loss function of OrientedRepPoints head.","docstring_tokens":"","code":"def loss(self, cls_scores, pts_preds_init, pts_preds_refine, base_features, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None):\n \"\"\"Loss function of OrientedRepPoints head.\"\"\"\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == self.prior_generator.num_levels\n label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1\n device = cls_scores[0].device\n (center_list, valid_flag_list) = self.get_points(featmap_sizes, img_metas, device=device)\n pts_coordinate_preds_init = self.offset_to_pts(center_list, pts_preds_init)\n num_proposals_each_level = [featmap.size(-1) * featmap.size(-2) for featmap in cls_scores]\n num_level = len(featmap_sizes)\n assert num_level == len(pts_coordinate_preds_init)\n candidate_list = center_list\n cls_reg_targets_init = self.get_targets(candidate_list, valid_flag_list, gt_bboxes, img_metas, gt_bboxes_ignore_list=gt_bboxes_ignore, gt_labels_list=gt_labels, stage='init', label_channels=label_channels)\n (*_, bbox_gt_list_init, candidate_list_init, bbox_weights_list_init, num_total_pos_init, num_total_neg_init, _) = cls_reg_targets_init\n (center_list, valid_flag_list) = self.get_points(featmap_sizes, img_metas, device=device)\n pts_coordinate_preds_refine = self.offset_to_pts(center_list, pts_preds_refine)\n (refine_points_features,) = multi_apply(self.get_adaptive_points_feature, base_features, pts_coordinate_preds_refine, self.point_strides)\n features_pts_refine = levels_to_images(refine_points_features)\n features_pts_refine = [item.reshape(-1, self.num_points, item.shape[-1]) for item in features_pts_refine]\n points_list = []\n for (i_img, center) in enumerate(center_list):\n points = []\n for i_lvl in range(len(pts_preds_refine)):\n points_preds_init_ = pts_preds_init[i_lvl].detach()\n points_preds_init_ = points_preds_init_.view(points_preds_init_.shape[0], -1, *points_preds_init_.shape[2:])\n points_shift = points_preds_init_.permute(0, 2, 3, 1) * self.point_strides[i_lvl]\n points_center = center[i_lvl][:, :2].repeat(1, self.num_points)\n points.append(points_center + points_shift[i_img].reshape(-1, 2 * self.num_points))\n points_list.append(points)\n cls_reg_targets_refine = self.get_targets(points_list, valid_flag_list, gt_bboxes, img_metas, gt_bboxes_ignore_list=gt_bboxes_ignore, gt_labels_list=gt_labels, stage='refine', label_channels=label_channels)\n (labels_list, label_weights_list, bbox_gt_list_refine, _, bbox_weights_list_refine, pos_inds_list_refine, pos_gt_index_list_refine) = cls_reg_targets_refine\n cls_scores = levels_to_images(cls_scores)\n cls_scores = [item.reshape(-1, self.cls_out_channels) for item in cls_scores]\n pts_coordinate_preds_init_img = levels_to_images(pts_coordinate_preds_init, flatten=True)\n pts_coordinate_preds_init_img = [item.reshape(-1, 2 * self.num_points) for item in pts_coordinate_preds_init_img]\n pts_coordinate_preds_refine_img = levels_to_images(pts_coordinate_preds_refine, flatten=True)\n pts_coordinate_preds_refine_img = [item.reshape(-1, 2 * self.num_points) for item in pts_coordinate_preds_refine_img]\n with torch.no_grad():\n (quality_assess_list,) = multi_apply(self.pointsets_quality_assessment, features_pts_refine, cls_scores, pts_coordinate_preds_init_img, pts_coordinate_preds_refine_img, labels_list, bbox_gt_list_refine, label_weights_list, bbox_weights_list_refine, pos_inds_list_refine)\n (labels_list, label_weights_list, bbox_weights_list_refine, num_pos, pos_normalize_term) = multi_apply(self.dynamic_pointset_samples_selection, quality_assess_list, labels_list, label_weights_list, bbox_weights_list_refine, pos_inds_list_refine, pos_gt_index_list_refine, num_proposals_each_level=num_proposals_each_level, num_level=num_level)\n num_pos = sum(num_pos)\n cls_scores = torch.cat(cls_scores, 0).view(-1, cls_scores[0].size(-1))\n pts_preds_refine = torch.cat(pts_coordinate_preds_refine_img, 0).view(-1, pts_coordinate_preds_refine_img[0].size(-1))\n labels = torch.cat(labels_list, 0).view(-1)\n labels_weight = torch.cat(label_weights_list, 0).view(-1)\n bbox_gt_refine = torch.cat(bbox_gt_list_refine, 0).view(-1, bbox_gt_list_refine[0].size(-1))\n bbox_weights_refine = torch.cat(bbox_weights_list_refine, 0).view(-1)\n pos_normalize_term = torch.cat(pos_normalize_term, 0).reshape(-1)\n pos_inds_flatten = ((0 <= labels) & (labels < self.num_classes)).nonzero(as_tuple=False).reshape(-1)\n assert len(pos_normalize_term) == len(pos_inds_flatten)\n if num_pos:\n losses_cls = self.loss_cls(cls_scores, labels, labels_weight, avg_factor=num_pos)\n pos_pts_pred_refine = pts_preds_refine[pos_inds_flatten]\n pos_bbox_gt_refine = bbox_gt_refine[pos_inds_flatten]\n pos_bbox_weights_refine = bbox_weights_refine[pos_inds_flatten]\n losses_pts_refine = self.loss_bbox_refine(pos_pts_pred_refine \/ pos_normalize_term.reshape(-1, 1), pos_bbox_gt_refine \/ pos_normalize_term.reshape(-1, 1), pos_bbox_weights_refine)\n loss_border_refine = self.loss_spatial_refine(pos_pts_pred_refine.reshape(-1, 2 * self.num_points) \/ pos_normalize_term.reshape(-1, 1), pos_bbox_gt_refine \/ pos_normalize_term.reshape(-1, 1), pos_bbox_weights_refine, avg_factor=None)\n else:\n losses_cls = cls_scores.sum() * 0\n losses_pts_refine = pts_preds_refine.sum() * 0\n loss_border_refine = pts_preds_refine.sum() * 0\n (losses_pts_init, loss_border_init) = multi_apply(self.init_loss_single, pts_coordinate_preds_init, bbox_gt_list_init, bbox_weights_list_init, self.point_strides)\n loss_dict_all = {'loss_cls': losses_cls, 'loss_pts_init': losses_pts_init, 'loss_pts_refine': losses_pts_refine, 'loss_spatial_init': loss_border_init, 'loss_spatial_refine': loss_border_refine}\n return loss_dict_all","code_tokens":"","url":616135} +{"project_name":"morpheus-project\/morpheus","file_name":"test_cli.py","full_name":"TestCLI.test_parse_args_raises_cpus_gpus","func_name":"test_parse_args_raises_cpus_gpus","docstring":"test _parse_args raise ValueError for passing cpus and gpus.","docstring_tokens":"","code":"@staticmethod\ndef test_parse_args_raises_cpus_gpus():\n \"\"\"test _parse_args raise ValueError for passing cpus and gpus.\"\"\"\n local = os.path.dirname(os.path.abspath(__file__))\n f_name = 'test.fits'\n open(os.path.join(local, f_name), 'w').close()\n test_file = os.path.join(local, f_name)\n cli_args = f'{test_file} {test_file} {test_file} {test_file} '\n cli_args += '--cpus 3 --gpus 1,2,3'\n print(cli_args)\n with pytest.raises(ValueError):\n cli._parse_args(cli_args.split())\n os.remove(test_file)","code_tokens":"","url":656014} +{"project_name":"RasaHQ\/rasa","file_name":"structures.py","full_name":"StoryGraph.is_empty","func_name":"is_empty","docstring":"Checks if `StoryGraph` is empty.","docstring_tokens":"","code":"def is_empty(self) -> bool:\n \"\"\"Checks if `StoryGraph` is empty.\"\"\"\n return not self.story_steps","code_tokens":"","url":837582} +{"project_name":"lwabala\/RNN4MNIST","file_name":"read_mnist.py","full_name":"img_subset","func_name":"img_subset","docstring":"Transform a whole img to a set of patches.","docstring_tokens":"","code":"def img_subset(img):\n \"\"\"Transform a whole img to a set of patches.\"\"\"\n local_img = img\n img_set = []\n subnum = np.array([3, 3])\n subsize = np.array([14, 14])\n subdist = (local_img.shape - subsize) \/ (subnum - 1)\n for srow in range(subnum[0]):\n for scol in range(subnum[1]):\n (row, col) = subdist * (srow, scol)\n sub_img = local_img[row:row + subsize[0], col:col + subsize[1]]\n img_set.append(sub_img.reshape(1, -1))\n return np.array(img_set)","code_tokens":"","url":325440} +{"project_name":"bm777\/object_detection","file_name":"model.py","full_name":"ObjectDetector.build_basic_resnet50","func_name":"build_basic_resnet50","docstring":"Build the basic ResNet50 net.","docstring_tokens":"","code":"def build_basic_resnet50(self):\n \"\"\" Build the basic ResNet50 net. \"\"\"\n print('Building the basic ResNet50 net...')\n bn = self.batch_norm\n imgs = tf.placeholder(tf.float32, [self.batch_size] + self.img_shape)\n is_train = tf.placeholder(tf.bool)\n conv1_feats = convolution(imgs, 7, 7, 64, 2, 2, 'conv1')\n conv1_feats = batch_norm(conv1_feats, 'bn_conv1', is_train, bn, 'relu')\n pool1_feats = max_pool(conv1_feats, 3, 3, 2, 2, 'pool1')\n res2a_feats = self.basic_block(pool1_feats, 'res2a', 'bn2a', is_train, bn, 64, 1)\n res2b_feats = self.basic_block2(res2a_feats, 'res2b', 'bn2b', is_train, bn, 64)\n res2c_feats = self.basic_block2(res2b_feats, 'res2c', 'bn2c', is_train, bn, 64)\n res3a_feats = self.basic_block(res2c_feats, 'res3a', 'bn3a', is_train, bn, 128)\n res3b_feats = self.basic_block2(res3a_feats, 'res3b', 'bn3b', is_train, bn, 128)\n res3c_feats = self.basic_block2(res3b_feats, 'res3c', 'bn3c', is_train, bn, 128)\n res3d_feats = self.basic_block2(res3c_feats, 'res3d', 'bn3d', is_train, bn, 128)\n res4a_feats = self.basic_block(res3d_feats, 'res4a', 'bn4a', is_train, bn, 256)\n res4b_feats = self.basic_block2(res4a_feats, 'res4b', 'bn4b', is_train, bn, 256)\n res4c_feats = self.basic_block2(res4b_feats, 'res4c', 'bn4c', is_train, bn, 256)\n res4d_feats = self.basic_block2(res4c_feats, 'res4d', 'bn4d', is_train, bn, 256)\n res4e_feats = self.basic_block2(res4d_feats, 'res4e', 'bn4e', is_train, bn, 256)\n res4f_feats = self.basic_block2(res4e_feats, 'res4f', 'bn4f', is_train, bn, 256)\n res5a_feats = self.basic_block(res4f_feats, 'res5a', 'bn5a', is_train, bn, 512)\n res5b_feats = self.basic_block2(res5a_feats, 'res5b', 'bn5b', is_train, bn, 512)\n res5c_feats = self.basic_block2(res5b_feats, 'res5c', 'bn5c', is_train, bn, 512)\n self.conv_feats = res5c_feats\n self.conv_feat_shape = [20, 20, 2048]\n self.roi_warped_feat_shape = [10, 10, 2048]\n self.roi_pooled_feat_shape = [5, 5, 2048]\n self.imgs = imgs\n self.is_train = is_train\n print('Basic ResNet50 net built.')","code_tokens":"","url":745205} +{"project_name":"NJU-LHRS\/official-CMID","file_name":"mim_utils.py","full_name":"cast_tensor_type","func_name":"cast_tensor_type","docstring":"Recursively convert Tensor in inputs from src_type to dst_type.","docstring_tokens":"","code":"def cast_tensor_type(inputs, src_type, dst_type):\n \"\"\"Recursively convert Tensor in inputs from src_type to dst_type.\n\n Args:\n inputs: Inputs that to be casted.\n src_type (torch.dtype): Source type..\n dst_type (torch.dtype): Destination type.\n\n Returns:\n The same type with inputs, but all contained Tensors have been cast.\n \"\"\"\n if isinstance(inputs, torch.Tensor):\n return inputs.to(dst_type)\n elif isinstance(inputs, str):\n return inputs\n elif isinstance(inputs, np.ndarray):\n return inputs\n elif isinstance(inputs, abc.Mapping):\n return type(inputs)({k: cast_tensor_type(v, src_type, dst_type) for (k, v) in inputs.items()})\n elif isinstance(inputs, abc.Iterable):\n return type(inputs)((cast_tensor_type(item, src_type, dst_type) for item in inputs))\n else:\n return inputs","code_tokens":"","url":250197} +{"project_name":"QData\/deepWordBug","file_name":"test_core.py","full_name":"test_time_left_infinite_None","func_name":"test_time_left_infinite_None","docstring":"keyboard '_time_left' routine returns None when given None.","docstring_tokens":"","code":"def test_time_left_infinite_None():\n \"\"\"keyboard '_time_left' routine returns None when given None.\"\"\"\n from blessed.keyboard import _time_left\n assert _time_left(stime=time.time(), timeout=None) is None","code_tokens":"","url":541132} +{"project_name":"voxel51\/fiftyone","file_name":"runs.py","full_name":"RunResults.key","func_name":"key","docstring":"The run key for these results.","docstring_tokens":"","code":"@property\ndef key(self):\n \"\"\"The run key for these results.\"\"\"\n return self._key","code_tokens":"","url":583251} +{"project_name":"Huixxi\/TensorFlow2.0-for-Deep-Reinforcement-Learning","file_name":"05_multistep_td.py","full_name":"MSTDAgent.get_n_step_info","func_name":"get_n_step_info","docstring":"Return n step reward, next state, and done.","docstring_tokens":"","code":"def get_n_step_info(self, n_step_buffer, gamma):\n \"\"\"Return n step reward, next state, and done.\"\"\"\n (reward, next_state, done) = n_step_buffer[-1][-3:]\n for transition in reversed(list(n_step_buffer)[:-1]):\n (r, n_s, d) = transition[-3:]\n reward = r + gamma * reward * (1 - d)\n (next_state, done) = (n_s, d) if d else (next_state, done)\n return (reward, next_state, done)","code_tokens":"","url":922428} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"ColorDB.py","full_name":"rrggbb_to_triplet","func_name":"rrggbb_to_triplet","docstring":"Converts a #rrggbb color to the tuple (red, green, blue).","docstring_tokens":"","code":"def rrggbb_to_triplet(color):\n \"\"\"Converts a #rrggbb color to the tuple (red, green, blue).\"\"\"\n rgbtuple = _namedict.get(color)\n if rgbtuple is None:\n if color[0] != '#':\n raise BadColor(color)\n red = color[1:3]\n green = color[3:5]\n blue = color[5:7]\n rgbtuple = (int(red, 16), int(green, 16), int(blue, 16))\n _namedict[color] = rgbtuple\n return rgbtuple","code_tokens":"","url":284830} +{"project_name":"NLPCodebase\/PTSGM","file_name":"utils_metrics.py","full_name":"f1_score","func_name":"f1_score","docstring":"Compute the F1 score.","docstring_tokens":"","code":"def f1_score(true_entities, pred_entities):\n \"\"\"Compute the F1 score.\"\"\"\n nb_correct = len(true_entities & pred_entities)\n nb_pred = len(pred_entities)\n nb_true = len(true_entities)\n p = nb_correct \/ nb_pred if nb_pred > 0 else 0\n r = nb_correct \/ nb_true if nb_true > 0 else 0\n score = 2 * p * r \/ (p + r) if p + r > 0 else 0\n return score","code_tokens":"","url":818554} +{"project_name":"QinganZhao\/Deep-Learning-Based-Structural-Damage-Detection","file_name":"test_coord_map.py","full_name":"TestCoordMap.test_catch_unconnected","func_name":"test_catch_unconnected","docstring":"Catch mapping spatially unconnected tops.","docstring_tokens":"","code":"def test_catch_unconnected(self):\n \"\"\"\n Catch mapping spatially unconnected tops.\n \"\"\"\n n = coord_net_spec()\n n.ip = L.InnerProduct(n.deconv, num_output=10)\n with self.assertRaises(RuntimeError):\n coord_map_from_to(n.ip, n.data)","code_tokens":"","url":127508} +{"project_name":"PIYUSH0812\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"bounds.py","full_name":"ess_criterion","func_name":"ess_criterion","docstring":"A criterion that resamples based on effective sample size.","docstring_tokens":"","code":"def ess_criterion(num_samples, log_ess, unused_t):\n \"\"\"A criterion that resamples based on effective sample size.\"\"\"\n return log_ess <= tf.log(num_samples \/ 2.0)","code_tokens":"","url":48345} +{"project_name":"georghess\/voxel-mae","file_name":"primitive_head.py","full_name":"PrimitiveHead.match_point2plane","func_name":"match_point2plane","docstring":"Match points to plane.","docstring_tokens":"","code":"def match_point2plane(self, plane, points):\n \"\"\"Match points to plane.\n\n Args:\n plane (torch.Tensor): Equation of the plane.\n points (torch.Tensor): Points of input.\n\n Returns:\n Tuple: Distance of each point to the plane and\n flag of matching correspondence.\n \"\"\"\n point2plane_dist = torch.abs((points * plane[:3]).sum(dim=1) + plane[-1])\n min_dist = point2plane_dist.min()\n selected = torch.abs(point2plane_dist - min_dist) < self.train_cfg['dist_thresh']\n return (point2plane_dist, selected)","code_tokens":"","url":380749} +{"project_name":"Westlake-AI\/openmixup","file_name":"ema_hook.py","full_name":"EMAHook.after_val_epoch","func_name":"after_val_epoch","docstring":"We recover source model's parameter from ema model after validation.","docstring_tokens":"","code":"def after_val_epoch(self, runner):\n \"\"\"We recover source model's parameter from ema model after validation.\"\"\"\n if self.evaluate_on_ema:\n self._swap_ema_parameters()","code_tokens":"","url":252303} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"force_train_hook.py","full_name":"ForceTrainModeHook.before_train_epoch","func_name":"before_train_epoch","docstring":"Make sure to put a model in a training mode before train epoch.","docstring_tokens":"","code":"def before_train_epoch(self, runner):\n \"\"\"Make sure to put a model in a training mode before train epoch.\"\"\"\n runner.model.train()","code_tokens":"","url":917823} +{"project_name":"scottemmons\/rvs","file_name":"visualize.py","full_name":"plot_average_hit_times","func_name":"plot_average_hit_times","docstring":"Create a barplot of the average hitting times.","docstring_tokens":"","code":"def plot_average_hit_times(hitting_time_vecs: Union[np.ndarray, List[np.ndarray]], attribute_dicts: List[Dict[str, Union[int, float, str]]], env_name: str, out_directory: str, x: str='Checkpoint', y: str='Hitting Time', hue: str='Checkpoint', title: Optional[str]=None, wandb_run: Optional[Run]=None) -> None:\n \"\"\"Create a barplot of the average hitting times.\"\"\"\n df = aggregate_performance(hitting_time_vecs, attribute_dicts, y)\n sns.barplot(x=x, y=y, hue=hue, data=df)\n plt.grid()\n if title:\n plt.title(title)\n plt_filename_root = f'{env_name.lower()}_avg_hit_times'\n plt_filename = os.path.join(out_directory, plt_filename_root + '.png')\n plt.savefig(plt_filename)\n log_plt_as_image(f'{env_name.lower()}_avg_hit_times', wandb_run=wandb_run)\n plt.close()\n save_df_with_plot(df, plt_filename, wandb_run=wandb_run, wandb_table_key=plt_filename_root + '_table')","code_tokens":"","url":327047} +{"project_name":"CarperAI\/trlx","file_name":"logging.py","full_name":"is_progress_bar_enabled","func_name":"is_progress_bar_enabled","docstring":"Return a boolean indicating whether tqdm progress bars are enabled.","docstring_tokens":"","code":"def is_progress_bar_enabled() -> bool:\n \"\"\"Return a boolean indicating whether tqdm progress bars are enabled.\"\"\"\n global _tqdm_active\n return bool(_tqdm_active)","code_tokens":"","url":426036} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"_bisect_k_means.py","full_name":"_BisectingTree.split","func_name":"split","docstring":"Split the cluster node into two subclusters.","docstring_tokens":"","code":"def split(self, labels, centers, scores):\n \"\"\"Split the cluster node into two subclusters.\"\"\"\n self.left = _BisectingTree(indices=self.indices[labels == 0], center=centers[0], score=scores[0])\n self.right = _BisectingTree(indices=self.indices[labels == 1], center=centers[1], score=scores[1])\n self.indices = None","code_tokens":"","url":363464} +{"project_name":"danaugrs\/huskarl","file_name":"core.py","full_name":"Agent.train","func_name":"train","docstring":"Trains the agent for one step.","docstring_tokens":"","code":"def train(self, step):\n \"\"\"Trains the agent for one step.\"\"\"\n raise NotImplementedError()","code_tokens":"","url":206789} +{"project_name":"jimtin\/Stock_Comparison","file_name":"web.py","full_name":"UIModule.html_body","func_name":"html_body","docstring":"Override to return an HTML string that will be put at the end of the element.","docstring_tokens":"","code":"def html_body(self):\n \"\"\"Override to return an HTML string that will be put at the end of\n the element.\n \"\"\"\n return None","code_tokens":"","url":359300} +{"project_name":"95616ARG\/PRDNN","file_name":"test_ddnn.py","full_name":"test_compute_representatives","func_name":"test_compute_representatives","docstring":"Tests that the linear-region endpoints work.","docstring_tokens":"","code":"def test_compute_representatives():\n \"\"\"Tests that the linear-region endpoints work.\"\"\"\n activation_layers = [FullyConnectedLayer(np.eye(1), np.zeros(shape=(1,))), ReluLayer()]\n value_layers = [FullyConnectedLayer(np.eye(1), np.ones(shape=(1,))), ReluLayer()]\n network = DDNN(activation_layers, value_layers)\n assert network.differ_index == 0\n points = np.array([[0.0], [0.0]])\n representatives = np.array([[1.0], [-1.0]])\n output = network.compute(points, representatives=representatives)\n assert np.array_equal(output, [[1.0], [0.0]])","code_tokens":"","url":822212} +{"project_name":"marlbenchmark\/off-policy","file_name":"base_runner.py","full_name":"RecRunner.collect_rollout","func_name":"collect_rollout","docstring":"Collect a rollout and store it in the buffer.","docstring_tokens":"","code":"def collect_rollout(self):\n \"\"\"Collect a rollout and store it in the buffer.\"\"\"\n raise NotImplementedError","code_tokens":"","url":755528} +{"project_name":"instadeepai\/jumanji","file_name":"env_test.py","full_name":"test_graph_coloring_get_action_mask","func_name":"test_graph_coloring_get_action_mask","docstring":"Verify that the action mask generated by `_get_valid_actions` is correct.","docstring_tokens":"","code":"def test_graph_coloring_get_action_mask(graph_coloring: GraphColoring) -> None:\n \"\"\"Verify that the action mask generated by `_get_valid_actions` is correct.\"\"\"\n key = jax.random.PRNGKey(0)\n (state, _) = graph_coloring.reset(key)\n num_nodes = graph_coloring.generator.num_nodes\n get_valid_actions_fn = jax.jit(graph_coloring._get_valid_actions)\n action_mask = get_valid_actions_fn(state.current_node_index, state.adj_matrix, state.colors)\n assert action_mask.dtype == jnp.bool_\n assert action_mask.shape == (num_nodes,)","code_tokens":"","url":594056} +{"project_name":"LongPham7\/Distributionally-Robust-Optimization","file_name":"util_analysis.py","full_name":"Analysis.testAccuracy","func_name":"testAccuracy","docstring":"Evaluate the accuracy of a neural network on the MNIST test data.","docstring_tokens":"","code":"def testAccuracy(self):\n \"\"\"\n Evaluate the accuracy of a neural network on the MNIST test data.\n \"\"\"\n return evaluateModelAccuracy(self.model)","code_tokens":"","url":552154} +{"project_name":"intel\/neural-compressor","file_name":"benchmark.py","full_name":"Benchmark.results","func_name":"results","docstring":"Get the results of benchmarking.","docstring_tokens":"","code":"@property\ndef results(self):\n \"\"\"Get the results of benchmarking.\"\"\"\n return self._results","code_tokens":"","url":738291} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"offsetbox.py","full_name":"AnnotationBbox.draw","func_name":"draw","docstring":"Draw the :class:`Annotation` object to the given *renderer*.","docstring_tokens":"","code":"def draw(self, renderer):\n \"\"\"\n Draw the :class:`Annotation` object to the given *renderer*.\n \"\"\"\n if renderer is not None:\n self._renderer = renderer\n if not self.get_visible():\n return\n xy_pixel = self._get_position_xy(renderer)\n if not self._check_xy(renderer, xy_pixel):\n return\n self.update_positions(renderer)\n if self.arrow_patch is not None:\n if self.arrow_patch.figure is None and self.figure is not None:\n self.arrow_patch.figure = self.figure\n self.arrow_patch.draw(renderer)\n if self._drawFrame:\n self.patch.draw(renderer)\n self.offsetbox.draw(renderer)\n self.stale = False","code_tokens":"","url":767} +{"project_name":"open-mmlab\/mmtracking","file_name":"eval_sot_vot.py","full_name":"eval_sot_eao","func_name":"eval_sot_eao","docstring":"Calculate EAO socre over all tracking sequences.","docstring_tokens":"","code":"def eval_sot_eao(results, annotations, interval=[100, 356], videos_wh=None):\n \"\"\"Calculate EAO socre over all tracking sequences.\n\n Args:\n results (list[list[ndarray]]): The first list contains the\n tracking results of each video. The second list contains the\n tracking results of each frame in one video. The ndarray have two\n cases:\n - bbox: denotes the normal tracking box in [x1, y1, w, h]\n format.\n - special tracking state: [0] denotes the unknown state,\n namely the skipping frame after failure, [1] denotes the\n initialized state, and [2] denotes the failed state.\n annotations (list[ndarray]): The list contains the gt_bboxes of each\n video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape.\n Each bbox is in (x1, y1, w, h) format.\n interval: an specified interval in EAO curve used to calculate the EAO\n score. There are different settings in different VOT challenge.\n Default is VOT2018 setting: [100, 356].\n videos_wh (list[tuple(width, height), ...]): The list contains the\n width and height of each video. Default is None.\n\n Return:\n dict[str, float]: EAO score in EAO evaluation metric.\n \"\"\"\n if vot is None:\n raise ImportError('Please runpip install git+https:\/\/github.com\/votchallenge\/toolkit.gitto manually install vot-toolkit')\n if videos_wh is None:\n videos_wh = [None] * len(annotations)\n all_overlaps = []\n all_successes = []\n for (i, (gt_traj, pred_traj)) in enumerate(zip(annotations, results)):\n assert len(gt_traj) == len(pred_traj), f'{len(gt_traj)} == {len(pred_traj)}'\n assert len(pred_traj[0]) == 1 and pred_traj[0][0] == 1, f'{len(pred_traj[0])} == 1 and {pred_traj[0][0]} == 1'\n (fail_inds, init_inds) = locate_failures_inits(pred_traj)\n pred_traj = trajectory2region(pred_traj)\n gt_traj = trajectory2region(gt_traj)\n overlaps = calculate_region_overlaps(pred_traj, gt_traj, videos_wh[i])\n if len(fail_inds) > 0:\n for i in range(len(fail_inds)):\n all_overlaps.append(overlaps[init_inds[i]:fail_inds[i]])\n all_successes.append(False)\n if len(init_inds) > len(fail_inds):\n all_overlaps.append(overlaps[init_inds[-1]:])\n all_successes.append(True)\n else:\n all_overlaps.append(overlaps)\n all_successes.append(True)\n eao_curve = calc_eao_curve(all_overlaps, all_successes)\n eao_score = np.mean(eao_curve[interval[0]:interval[1] + 1])\n eao = dict(eao=eao_score)\n return eao","code_tokens":"","url":625679} +{"project_name":"zackmcnulty\/CSE_446-Machine_Learning","file_name":"figure.py","full_name":"AxesStack.as_list","func_name":"as_list","docstring":"Return a list of the Axes instances that have been added to the figure.","docstring_tokens":"","code":"def as_list(self):\n \"\"\"\n Return a list of the Axes instances that have been added to the figure.\n \"\"\"\n ia_list = [a for (k, a) in self._elements]\n ia_list.sort()\n return [a for (i, a) in ia_list]","code_tokens":"","url":194302} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_kalman_filter.py","full_name":"rand_list","func_name":"rand_list","docstring":"Return list with `length` random ndarrays of shape `shape`.","docstring_tokens":"","code":"def rand_list(shape, length=ts, mult=10):\n \"\"\"Return list with `length` random ndarrays of shape `shape`.\"\"\"\n return [create_data(shape, mult=mult) for _ in range(length)]","code_tokens":"","url":400058} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"wals_test.py","full_name":"WALSMatrixFactorizationTest.calculate_loss","func_name":"calculate_loss","docstring":"Calculates the loss of the current (trained) model.","docstring_tokens":"","code":"def calculate_loss(self):\n \"\"\"Calculates the loss of the current (trained) model.\"\"\"\n current_rows = embedding_ops.embedding_lookup(self._model.get_row_factors(), math_ops.range(self._num_rows), partition_strategy='div')\n current_cols = embedding_ops.embedding_lookup(self._model.get_col_factors(), math_ops.range(self._num_cols), partition_strategy='div')\n row_wts = embedding_ops.embedding_lookup(self._row_weights, math_ops.range(self._num_rows), partition_strategy='div')\n col_wts = embedding_ops.embedding_lookup(self._col_weights, math_ops.range(self._num_cols), partition_strategy='div')\n sp_inputs = self.np_array_to_sparse(self.INPUT_MATRIX)\n return factorization_ops_test_utils.calculate_loss(sp_inputs, current_rows, current_cols, self._regularization_coeff, self._unobserved_weight, row_wts, col_wts)","code_tokens":"","url":603024} +{"project_name":"guxm2021\/ALT_SpeechBrain","file_name":"data_pipeline.py","full_name":"DynamicItem.next_takes","func_name":"next_takes","docstring":"The next argkeys to provide to this, when called.","docstring_tokens":"","code":"def next_takes(self):\n \"\"\"The next argkeys to provide to this, when called.\"\"\"\n return self.takes","code_tokens":"","url":415884} +{"project_name":"sjtu-marl\/malib","file_name":"rolloutworker.py","full_name":"parse_rollout_info","func_name":"parse_rollout_info","docstring":"Merge a list of rollout information here.","docstring_tokens":"","code":"def parse_rollout_info(raw_statistics: List[Dict[str, Any]]) -> Dict[str, Any]:\n \"\"\"Merge a list of rollout information here.\n\n Args:\n raw_statistics (List[Dict[str, Any]]): A list of dict, each element is a result dict. Keys include\n - total_timesteps\n - FPS\n - evaluation\n\n Returns:\n Dict[str, Any]: A merged dict.\n \"\"\"\n results = {'total_timesteps': 0, 'FPS': 0.0}\n evaluation = []\n for e in raw_statistics:\n if 'evaluation' in e:\n evaluation.extend(e['evaluation'])\n for (k, v) in e.items():\n if k == 'total_timesteps':\n results[k] += v\n elif k == 'FPS':\n results[k] += v\n if len(evaluation) > 0:\n raw_eval_results = defaultdict(lambda : [])\n for e in evaluation:\n for (k, v) in e.items():\n if isinstance(v, (Tuple, List)):\n v = sum(v)\n raw_eval_results[k].append(v)\n eval_results = {}\n for (k, v) in raw_eval_results.items():\n eval_results.update({f'{k}_max': np.max(v), f'{k}_min': np.min(v), f'{k}_mean': np.mean(v)})\n results['evaluation'] = eval_results\n return results","code_tokens":"","url":627554} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"variables.py","full_name":"Variable.SaveSliceInfo.to_proto","func_name":"to_proto","docstring":"Returns a SaveSliceInfoDef() proto.","docstring_tokens":"","code":"def to_proto(self, export_scope=None):\n \"\"\"Returns a SaveSliceInfoDef() proto.\n\n Args:\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n A `SaveSliceInfoDef` protocol buffer, or None if the `Variable` is not\n in the specified name scope.\n \"\"\"\n if export_scope is None or self.full_name.startswith(export_scope):\n save_slice_info_def = variable_pb2.SaveSliceInfoDef()\n save_slice_info_def.full_name = ops.strip_name_scope(self.full_name, export_scope)\n for i in self.full_shape:\n save_slice_info_def.full_shape.append(i)\n for i in self.var_offset:\n save_slice_info_def.var_offset.append(i)\n for i in self.var_shape:\n save_slice_info_def.var_shape.append(i)\n return save_slice_info_def\n else:\n return None","code_tokens":"","url":183115} +{"project_name":"NickNickGo\/fastseq","file_name":"test_api_decorator.py","full_name":"APIDecoratorTest.test_replace_baseclass","func_name":"test_replace_baseclass","docstring":"Test replace() decorator for the base class.","docstring_tokens":"","code":"def test_replace_baseclass(self):\n \"\"\"Test replace() decorator for the base class.\"\"\"\n preloaded_classes = {}\n preloaded_classes['grandchild'] = Grandchild\n child = Child()\n grandchild = Grandchild()\n preloaded_grandchild = preloaded_classes['grandchild']()\n self.assertEqual(child.name(), 'Base')\n self.assertEqual(grandchild.name(), 'Base')\n self.assertEqual(preloaded_grandchild.name(), 'Base')\n CachedBase = Base\n\n @replace(Base)\n class BaseV2(Base):\n\n def name(self):\n return 'BaseV2'\n self.assertEqual(BaseV2.__replaced_class__, CachedBase)\n self.assertEqual(Base.__replaced_class__, CachedBase)\n child = Child()\n grandchild = Grandchild()\n preloaded_grandchild = preloaded_classes['grandchild']()\n self.assertEqual(child.name(), 'BaseV2')\n self.assertEqual(grandchild.name(), 'BaseV2')\n self.assertEqual(preloaded_grandchild.name(), 'BaseV2')\n CachedGrandchild = Grandchild\n\n @replace(Grandchild)\n class GrandchildV2(Grandchild):\n\n def name(self):\n return 'GrandChildV2'\n self.assertEqual(GrandchildV2.__replaced_class__, CachedGrandchild)\n self.assertEqual(Grandchild.__replaced_class__, CachedGrandchild)\n child = Child()\n grandchild = Grandchild()\n preloaded_grandchild = preloaded_classes['grandchild']()\n self.assertEqual(child.name(), 'BaseV2')\n self.assertEqual(grandchild.name(), 'GrandChildV2')\n self.assertEqual(preloaded_grandchild.name(), 'BaseV2')\n self.assertEqual(preloaded_classes['grandchild'], Grandchild.__replaced_class__)","code_tokens":"","url":559951} +{"project_name":"scottemmons\/rvs","file_name":"step.py","full_name":"sample_episode_performance","func_name":"sample_episode_performance","docstring":"Helper function to sample episode performance correctly, depending on the env.","docstring_tokens":"","code":"def sample_episode_performance(policy, env: Union[GCSLToGym, offline_env.OfflineEnv], env_name: str, max_episode_steps: int, traj_samples: int=2000, kitchen_subtask: str='all') -> np.ndarray:\n \"\"\"Helper function to sample episode performance correctly, depending on the env.\"\"\"\n if env_name[:7] == 'kitchen':\n if kitchen_subtask == 'dynamic':\n return sample_cumulative_reward(policy, env, trajectory_samples=traj_samples, dynamic_kitchen_goal=True)\n else:\n (goal, _) = get_kitchen_goal(env, subtask=kitchen_subtask)\n goals = np.repeat(goal[np.newaxis], traj_samples, axis=0)\n return sample_cumulative_reward(policy, env, goals=goals, trajectory_samples=traj_samples)\n elif env_name in d4rl_env_names:\n return sample_cumulative_reward(policy, env, trajectory_samples=traj_samples)\n else:\n return sample_hitting_times(policy, env, max_episode_steps, hitting_time_samples=traj_samples)","code_tokens":"","url":327010} +{"project_name":"sunsmarterjie\/SDL-Skeleton","file_name":"utils.py","full_name":"load_pretrained_weights","func_name":"load_pretrained_weights","docstring":"Loads pretrained weights from weights path or download using url.","docstring_tokens":"","code":"def load_pretrained_weights(model, model_name, weights_path=None, load_fc=True, advprop=False):\n \"\"\"Loads pretrained weights from weights path or download using url.\n\n Args:\n model (Module): The whole model of efficientnet.\n model_name (str): Model name of efficientnet.\n weights_path (None or str):\n str: path to pretrained weights file on the local disk.\n None: use pretrained weights downloaded from the Internet.\n load_fc (bool): Whether to load pretrained weights for fc layer at the end of the model.\n advprop (bool): Whether to load pretrained weights\n trained with advprop (valid when weights_path is None).\n \"\"\"\n if isinstance(weights_path, str):\n state_dict = torch.load(weights_path)\n else:\n url_map_ = url_map_advprop if advprop else url_map\n state_dict = model_zoo.load_url(url_map_[model_name])\n if load_fc:\n ret = model.load_state_dict(state_dict, strict=False)\n assert not ret.missing_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys)\n else:\n state_dict.pop('_fc.weight')\n state_dict.pop('_fc.bias')\n ret = model.load_state_dict(state_dict, strict=False)\n assert set(ret.missing_keys) == set(['_fc.weight', '_fc.bias']), 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys)\n assert not ret.unexpected_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.unexpected_keys)\n print('Loaded pretrained weights for {}'.format(model_name))","code_tokens":"","url":855236} +{"project_name":"explosion\/spaCy","file_name":"test_displacy.py","full_name":"test_displacy_spans","func_name":"test_displacy_spans","docstring":"Test that displaCy can render Spans.","docstring_tokens":"","code":"def test_displacy_spans(en_vocab):\n \"\"\"Test that displaCy can render Spans.\"\"\"\n doc = Doc(en_vocab, words=['But', 'Google', 'is', 'starting', 'from', 'behind'])\n doc.ents = [Span(doc, 1, 2, label=doc.vocab.strings['ORG'])]\n html = displacy.render(doc[1:4], style='ent')\n assert html.startswith(' Any:\n \"\"\"Calling :meth:`get` and execute the evaluator.\"\"\"\n return self.get().evaluate(model)","code_tokens":"","url":728707} +{"project_name":"kornia\/kornia","file_name":"divergence.py","full_name":"kl_div_loss_2d","func_name":"kl_div_loss_2d","docstring":"Calculate the Kullback-Leibler divergence loss between heatmaps.","docstring_tokens":"","code":"def kl_div_loss_2d(input: Tensor, target: Tensor, reduction: str='mean') -> Tensor:\n \"\"\"Calculate the Kullback-Leibler divergence loss between heatmaps.\n\n Args:\n input: the input tensor with shape :math:`(B, N, H, W)`.\n target: the target tensor with shape :math:`(B, N, H, W)`.\n reduction: Specifies the reduction to apply to the\n output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction\n will be applied, ``'mean'``: the sum of the output will be divided by\n the number of elements in the output, ``'sum'``: the output will be\n summed.\n\n Examples:\n >>> input = torch.full((1, 1, 2, 4), 0.125)\n >>> loss = kl_div_loss_2d(input, input)\n >>> loss.item()\n 0.0\n \"\"\"\n return _reduce_loss(_kl_div_2d(target, input), reduction)","code_tokens":"","url":622216} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_public_functions.py","full_name":"test_function_param_validation","func_name":"test_function_param_validation","docstring":"Check param validation for public functions that are not wrappers around estimators.","docstring_tokens":"","code":"@pytest.mark.parametrize('func_module', PARAM_VALIDATION_FUNCTION_LIST)\ndef test_function_param_validation(func_module):\n \"\"\"Check param validation for public functions that are not wrappers around\n estimators.\n \"\"\"\n (func, func_name, func_params, required_params) = _get_func_info(func_module)\n parameter_constraints = getattr(func, '_skl_parameter_constraints')\n _check_function_param_validation(func, func_name, func_params, required_params, parameter_constraints)","code_tokens":"","url":854215} +{"project_name":"deepmind\/pycolab","file_name":"hello_world.py","full_name":"make_game","func_name":"make_game","docstring":"Builds and returns a Hello World game.","docstring_tokens":"","code":"def make_game():\n \"\"\"Builds and returns a Hello World game.\"\"\"\n return ascii_art.ascii_art_to_game(HELLO_ART, what_lies_beneath=' ', sprites={'1': ascii_art.Partial(SlidingSprite, 0), '2': ascii_art.Partial(SlidingSprite, 1), '3': ascii_art.Partial(SlidingSprite, 2), '4': ascii_art.Partial(SlidingSprite, 3)}, drapes={'@': RollingDrape}, z_order='12@34')","code_tokens":"","url":819256} +{"project_name":"MLBazaar\/MLPrimitives","file_name":"test_timeseries_preprocessing.py","full_name":"CutoffWindowSequencesTest.test_not_enough_data","func_name":"test_not_enough_data","docstring":"If there is not enough data for the given window_size, shape changes.","docstring_tokens":"","code":"def test_not_enough_data(self):\n \"\"\"If there is not enough data for the given window_size, shape changes.\"\"\"\n X = self.X\n timeseries = self.timeseries\n array = cutoff_window_sequences(X, timeseries, window_size=5)\n assert len(array) == 2\n expected_array = np.array([np.array([[1, 21], [2, 22], [3, 23], [4, 24]]), np.array([[12, 32], [13, 33], [14, 34], [15, 35], [16, 36]])])\n assert_allclose(array[0], expected_array[0])\n assert_allclose(array[1], expected_array[1])","code_tokens":"","url":630675} +{"project_name":"rlgraph\/rlgraph","file_name":"layer.py","full_name":"Layer.get_preprocessed_space","func_name":"get_preprocessed_space","docstring":"Returns the Space obtained after pushing the space input through this layer.","docstring_tokens":"","code":"def get_preprocessed_space(self, space):\n \"\"\"\n Returns the Space obtained after pushing the space input through this layer.\n\n Args:\n space (Space): The incoming Space object.\n\n Returns:\n Space: The Space after preprocessing.\n \"\"\"\n return space","code_tokens":"","url":862486} +{"project_name":"hitchtest\/hitch","file_name":"commandline.py","full_name":"clean","func_name":"clean","docstring":"Remove the hitch directory entirely.","docstring_tokens":"","code":"@command()\ndef clean():\n \"\"\"Remove the hitch directory entirely.\"\"\"\n if hitchdir.hitch_exists():\n hitchdir.remove_hitch_directory_if_exists()\n else:\n stderr.write('No hitch directory found. Doing nothing.\\n')\n stderr.flush()","code_tokens":"","url":206546} +{"project_name":"mariacer\/cl_in_rnns","file_name":"train_args_st.py","full_name":"check_invalid_args","func_name":"check_invalid_args","docstring":"Sanity check for some command-line arguments specific to training in the student-teacher setting.","docstring_tokens":"","code":"def check_invalid_args(config):\n \"\"\"Sanity check for some command-line arguments specific to training in\n the student-teacher setting.\n\n Args:\n config (argparse.Namespace): Parsed command-line arguments.\n \"\"\"\n if config.orth_teacher_hid_mat:\n if config.rank_teacher_hid_mat != -1:\n raise ValueError('Options \"orth_teacher_hid_mat\" and ' + '\"rank_teacher_hid_mat\" are not compatible.')\n if config.max_sv_teacher_hid_mat != -1:\n raise ValueError('Options \"orth_teacher_hid_mat\" and ' + '\"max_sv_teacher_hid_mat\" are not compatible.')\n if config.num_timesteps_out != -1:\n if config.num_timesteps_out < config.num_timesteps_in:\n raise ValueError('Option \"num_timesteps_out\" has to be greater ' + 'or equal to \"num_timesteps_in\".')","code_tokens":"","url":123017} +{"project_name":"janluke\/cs188","file_name":"autograder.py","full_name":"GameState.getGhostTeamIndices","func_name":"getGhostTeamIndices","docstring":"Returns a list of the agent index numbers for the agents on the ghost team.","docstring_tokens":"","code":"def getGhostTeamIndices(self):\n \"\"\"\n Returns a list of the agent index numbers for the agents on the ghost team.\n \"\"\"\n return self.ghostTeam[:]","code_tokens":"","url":223942} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"overrides.py","full_name":"get_overridable_numpy_array_functions","func_name":"get_overridable_numpy_array_functions","docstring":"List all numpy functions overridable via `__array_function__` Parameters ---------- None Returns ------- set A set containing all functions in the public numpy API that are overridable via `__array_function__`.","docstring_tokens":"","code":"def get_overridable_numpy_array_functions():\n \"\"\"List all numpy functions overridable via `__array_function__`\n\n Parameters\n ----------\n None\n\n Returns\n -------\n set\n A set containing all functions in the public numpy API that are\n overridable via `__array_function__`.\n\n \"\"\"\n from numpy.lib import recfunctions\n return _array_functions.copy()","code_tokens":"","url":442051} +{"project_name":"sarnsdev\/social-alignment-data-mining","file_name":"IpythonMagic.py","full_name":"CythonMagics.so_ext","func_name":"so_ext","docstring":"The extension suffix for compiled modules.","docstring_tokens":"","code":"@property\ndef so_ext(self):\n \"\"\"The extension suffix for compiled modules.\"\"\"\n try:\n return self._so_ext\n except AttributeError:\n self._so_ext = self._get_build_extension().get_ext_filename('')\n return self._so_ext","code_tokens":"","url":352278} +{"project_name":"IntelLabs\/nlp-architect","file_name":"np2vec.py","full_name":"NP2vec.load","func_name":"load","docstring":"Load the np2vec model.","docstring_tokens":"","code":"@classmethod\ndef load(cls, np2vec_model_file, binary=False, word_ngrams=0, word2vec_format=True):\n \"\"\"\n Load the np2vec model.\n\n Args:\n np2vec_model_file (str): the file containing the np2vec model to load\n binary (bool): boolean indicating whether the np2vec model to load is in binary format\n word_ngrams (int {1,0}): If 1, np2vec model to load uses word vectors with subword (\n ngrams) information.\n word2vec_format(bool): boolean indicating whether the model to load has been stored in\n original word2vec format.\n\n Returns:\n np2vec model to load\n \"\"\"\n if word_ngrams == 0:\n if word2vec_format:\n return KeyedVectors.load_word2vec_format(np2vec_model_file, binary=binary)\n return KeyedVectors.load(np2vec_model_file, mmap='r')\n if word_ngrams == 1:\n return FastText.load(np2vec_model_file)\n logger.error(\"invalid value for 'word_ngrams'\")\n return None","code_tokens":"","url":783319} +{"project_name":"deepmind\/acme","file_name":"agent_distributed.py","full_name":"DistributedMPO.learner","func_name":"learner","docstring":"The Learning part of the agent.","docstring_tokens":"","code":"def learner(self, replay: reverb.Client, counter: counting.Counter):\n \"\"\"The Learning part of the agent.\"\"\"\n act_spec = self._environment_spec.actions\n obs_spec = self._environment_spec.observations\n online_networks = self._network_factory(act_spec)\n target_networks = self._network_factory(act_spec)\n observation_network = online_networks.get('observation', tf.identity)\n observation_network = tf2_utils.to_sonnet_module(observation_network)\n online_networks['observation'] = observation_network\n target_observation_network = target_networks.get('observation', tf.identity)\n target_observation_network = tf2_utils.to_sonnet_module(target_observation_network)\n target_networks['observation'] = target_observation_network\n emb_spec = tf2_utils.create_variables(observation_network, [obs_spec])\n tf2_utils.create_variables(online_networks['policy'], [emb_spec])\n tf2_utils.create_variables(online_networks['critic'], [emb_spec, act_spec])\n tf2_utils.create_variables(target_networks['observation'], [obs_spec])\n tf2_utils.create_variables(target_networks['policy'], [emb_spec])\n tf2_utils.create_variables(target_networks['critic'], [emb_spec, act_spec])\n dataset = datasets.make_reverb_dataset(server_address=replay.server_address)\n dataset = dataset.batch(self._batch_size, drop_remainder=True)\n dataset = dataset.prefetch(self._prefetch_size)\n counter = counting.Counter(counter, 'learner')\n logger = loggers.make_default_logger('learner', time_delta=self._log_every, steps_key='learner_steps')\n if self._policy_loss_factory:\n policy_loss_module = self._policy_loss_factory()\n else:\n policy_loss_module = None\n return learning.MPOLearner(policy_network=online_networks['policy'], critic_network=online_networks['critic'], observation_network=observation_network, target_policy_network=target_networks['policy'], target_critic_network=target_networks['critic'], target_observation_network=target_observation_network, discount=self._additional_discount, num_samples=self._num_samples, target_policy_update_period=self._target_policy_update_period, target_critic_update_period=self._target_critic_update_period, policy_loss_module=policy_loss_module, dataset=dataset, counter=counter, logger=logger)","code_tokens":"","url":7747} +{"project_name":"thaines\/helit","file_name":"tile_image.py","full_name":"TileImage.from_array","func_name":"from_array","docstring":"Replaces the current image, after being given an array of uint8, [y, x, c], where alpha is c=3, blue is c=0, green is c=1 and red is c=2.","docstring_tokens":"","code":"def from_array(self, image):\n \"\"\"Replaces the current image, after being given an array of uint8, [y, x, c], where alpha is c=3, blue is c=0, green is c=1 and red is c=2.\"\"\"\n stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, image.shape[1])\n if stride != image.strides[0]:\n image = numpy.concatenate((image, numpy.zeros((image.shape[0], (stride - image.strides[0]) \/ 4, 4), dtype=numpy.uint8)), axis=1).copy('C')\n temp = cairo.ImageSurface.create_for_data(image, cairo.FORMAT_ARGB32, image.shape[1], image.shape[0], stride)\n self.original = cairo.ImageSurface(cairo.FORMAT_ARGB32, image.shape[1], image.shape[0])\n ctx = cairo.Context(self.original)\n ctx.set_operator(cairo.OPERATOR_SOURCE)\n ctx.set_source_surface(temp, 0, 0)\n ctx.paint()\n self.cache = OrderedDict()","code_tokens":"","url":592680} +{"project_name":"chenyuntc\/dsod.pytorch","file_name":"box.py","full_name":"box_select","func_name":"box_select","docstring":"Select boxes in range (xmin,ymin,xmax,ymax).","docstring_tokens":"","code":"def box_select(boxes, xmin, ymin, xmax, ymax):\n \"\"\"Select boxes in range (xmin,ymin,xmax,ymax).\n\n Args:\n boxes: (tensor) bounding boxes of (xmin,ymin,xmax,ymax), sized [N,4].\n xmin: (number) min value of x.\n ymin: (number) min value of y.\n xmax: (number) max value of x.\n ymax: (number) max value of y.\n\n Returns:\n (tensor) selected boxes, sized [M,4].\n (tensor) selected mask, sized [N,].\n \"\"\"\n mask = (boxes[:, 0] >= xmin) & (boxes[:, 1] >= ymin) & (boxes[:, 2] <= xmax) & (boxes[:, 3] <= ymax)\n boxes = boxes[mask.nonzero().squeeze(), :]\n return (boxes, mask)","code_tokens":"","url":173931} +{"project_name":"google-research\/tensor2robot","file_name":"t2r_models.py","full_name":"LegacyGraspingModelWrapper.create_legacy_input_specification","func_name":"create_legacy_input_specification","docstring":"Compatibility method needed by cem policies.","docstring_tokens":"","code":"def create_legacy_input_specification(self):\n \"\"\"Compatibility method needed by cem policies.\"\"\"\n return self.legacy_model_class.create_input_specifications()","code_tokens":"","url":908404} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"test_util.py","full_name":"GoldenFile","func_name":"GoldenFile","docstring":"Finds the given golden file and returns a file object representing it.","docstring_tokens":"","code":"def GoldenFile(filename):\n \"\"\"Finds the given golden file and returns a file object representing it.\"\"\"\n path = '.'\n while os.path.exists(path):\n if os.path.exists(os.path.join(path, 'src\/google\/protobuf')):\n full_path = os.path.join(path, 'src\/google\/protobuf\/testdata', filename)\n return open(full_path, 'rb')\n path = os.path.join(path, '..')\n path = '.'\n full_path = os.path.join(path, 'third_party\/py\/google\/protobuf\/testdata', filename)\n if os.path.exists(full_path):\n return open(full_path, 'rb')\n raise RuntimeError('Could not find golden files. This test must be run from within the protobuf source package so that it can read test data files from the C++ source tree.')","code_tokens":"","url":309985} +{"project_name":"fruittree\/CSC5892017Fall","file_name":"CannyEdge_V1.py","full_name":"canny_edges","func_name":"canny_edges","docstring":"Compute Canny edge detection on an image.","docstring_tokens":"","code":"def canny_edges(image, sigma=1.0, low_thresh=50, high_thresh=100):\n \"\"\"Compute Canny edge detection on an image.\"\"\"\n image = ndi.filters.gaussian_filter(image, sigma)\n dx = ndi.filters.sobel(image, 0)\n dy = ndi.filters.sobel(image, 1)\n mag = np.hypot(dx, dy)\n ort = np.arctan2(dy, dx)\n edge_map = non_maximal_edge_suppresion(mag, ort)\n edge_map = np.logical_and(edge_map, mag > low_thresh)\n (labels, num_labels) = ndi.measurements.label(edge_map, np.ones((3, 3)))\n for i in range(num_labels):\n if max(mag[labels == i]) < high_thresh:\n edge_map[labels == i] = False\n return edge_map","code_tokens":"","url":508449} +{"project_name":"shery322\/Lunar-Lander-ANN","file_name":"mask_test.py","full_name":"MaskTypeTest.test_zero_mask_set_at","func_name":"test_zero_mask_set_at","docstring":"Ensures set_at correctly handles zero sized masks.","docstring_tokens":"","code":"def test_zero_mask_set_at(self):\n \"\"\"Ensures set_at correctly handles zero sized masks.\"\"\"\n for size in ((31, 0), (0, 30), (0, 0)):\n mask = pygame.mask.Mask(size)\n with self.assertRaises(IndexError):\n mask.set_at((0, 0))","code_tokens":"","url":619063} +{"project_name":"awslabs\/predictive-maintenance-using--","file_name":"base.py","full_name":"IndexOpsMixin.item","func_name":"item","docstring":"Return the first element of the underlying data as a python scalar.","docstring_tokens":"","code":"def item(self):\n \"\"\"\n Return the first element of the underlying data as a python scalar.\n \"\"\"\n try:\n return self.values.item()\n except IndexError:\n raise ValueError('can only convert an array of size 1 to a Python scalar')","code_tokens":"","url":823031} +{"project_name":"rlworkgroup\/garage","file_name":"gaussian_mlp_module.py","full_name":"GaussianMLPBaseModule.to","func_name":"to","docstring":"Move the module to the specified device.","docstring_tokens":"","code":"def to(self, *args, **kwargs):\n \"\"\"Move the module to the specified device.\n\n Args:\n *args: args to pytorch to function.\n **kwargs: keyword args to pytorch to function.\n\n \"\"\"\n super().to(*args, **kwargs)\n buffers = dict(self.named_buffers())\n if not isinstance(self._log_std, torch.nn.Parameter):\n self._log_std = buffers['log_std']\n self._min_std_param = buffers['min_std_param']\n self._max_std_param = buffers['max_std_param']","code_tokens":"","url":200796} +{"project_name":"tejaskhot\/unsup_mvs","file_name":"model.py","full_name":"depth_smoothness","func_name":"depth_smoothness","docstring":"Computes image-aware depth smoothness loss.","docstring_tokens":"","code":"def depth_smoothness(depth, img, lambda_wt=1):\n \"\"\"Computes image-aware depth smoothness loss.\"\"\"\n depth_dx = gradient_x(depth)\n depth_dy = gradient_y(depth)\n image_dx = gradient_x(img)\n image_dy = gradient_y(img)\n weights_x = tf.exp(-(lambda_wt * tf.reduce_mean(tf.abs(image_dx), 3, keepdims=True)))\n weights_y = tf.exp(-(lambda_wt * tf.reduce_mean(tf.abs(image_dy), 3, keepdims=True)))\n smoothness_x = depth_dx * weights_x\n smoothness_y = depth_dy * weights_y\n return tf.reduce_mean(abs(smoothness_x)) + tf.reduce_mean(abs(smoothness_y))","code_tokens":"","url":438346} +{"project_name":"rlgraph\/rlgraph","file_name":"test_all_compile.py","full_name":"TestAllCompile.test_impala_single_agent_compilation","func_name":"test_impala_single_agent_compilation","docstring":"Tests IMPALA agent compilation (single-node mode).","docstring_tokens":"","code":"def test_impala_single_agent_compilation(self):\n \"\"\"\n Tests IMPALA agent compilation (single-node mode).\n \"\"\"\n return\n if get_backend() == 'pytorch':\n return\n env = GridWorld('2x2')\n agent = IMPALAAgent.from_spec(config_from_path('configs\/impala_agent_for_2x2_gridworld.json'), state_space=env.state_space, action_space=env.action_space, update_spec=dict(batch_size=16), optimizer_spec=dict(type='adam', learning_rate=0.05), execution_spec=dict(disable_monitoring=True))\n agent.terminate()\n print('Compiled {}'.format(agent))","code_tokens":"","url":862671} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"sequence_layers.py","full_name":"get_layer_class","func_name":"get_layer_class","docstring":"A convenience function to get a layer class based on requirements.","docstring_tokens":"","code":"def get_layer_class(use_attention, use_autoregression):\n \"\"\"A convenience function to get a layer class based on requirements.\n\n Args:\n use_attention: if True a returned class will use attention.\n use_autoregression: if True a returned class will use auto regression.\n\n Returns:\n One of available sequence layers (child classes for SequenceLayerBase).\n \"\"\"\n if use_attention and use_autoregression:\n layer_class = AttentionWithAutoregression\n elif use_attention and (not use_autoregression):\n layer_class = Attention\n elif not use_attention and (not use_autoregression):\n layer_class = NetSlice\n elif not use_attention and use_autoregression:\n layer_class = NetSliceWithAutoregression\n else:\n raise AssertionError('Unsupported sequence layer class')\n logging.debug('Use %s as a layer class', layer_class.__name__)\n return layer_class","code_tokens":"","url":14635} +{"project_name":"atang020\/reinforcement","file_name":"agent.py","full_name":"Agent.choose_action","func_name":"choose_action","docstring":"Return an action and the learned reward by maximizing reward.","docstring_tokens":"","code":"def choose_action(self, env, state):\n \"\"\"\n Return an action and the learned reward by maximizing reward.\n \"\"\"\n return argmax(ACTIONS, lambda action: self.q_value(state, action))","code_tokens":"","url":286686} +{"project_name":"PIYUSH0812\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"scan_ex2_solution.py","full_name":"sample_from_pvect","func_name":"sample_from_pvect","docstring":"Provided utility function: given a symbolic vector of probabilities (which MUST sum to 1), sample one element and return its index.","docstring_tokens":"","code":"def sample_from_pvect(pvect):\n \"\"\" Provided utility function: given a symbolic vector of\n probabilities (which MUST sum to 1), sample one element\n and return its index.\n \"\"\"\n onehot_sample = rng.multinomial(n=1, pvals=pvect)\n sample = onehot_sample.argmax()\n return sample","code_tokens":"","url":9102} +{"project_name":"RasaHQ\/rasa_core","file_name":"interpreter.py","full_name":"RegexInterpreter.extract_intent_and_entities","func_name":"extract_intent_and_entities","docstring":"Parse the user input using regexes to extract intent & entities.","docstring_tokens":"","code":"@staticmethod\ndef extract_intent_and_entities(user_input: Text) -> object:\n \"\"\"Parse the user input using regexes to extract intent & entities.\"\"\"\n prefixes = re.escape(RegexInterpreter.allowed_prefixes())\n m = re.search('^[' + prefixes + ']?([^{@]+)(@[0-9.]+)?([{].+)?', user_input)\n if m is not None:\n event_name = m.group(1).strip()\n confidence = RegexInterpreter._parse_confidence(m.group(2))\n entities = RegexInterpreter._parse_parameters(m.group(3), m.start(3), m.end(3), user_input)\n return (event_name, confidence, entities)\n else:\n logger.warning(\"Failed to parse intent end entities from '{}'. \".format(user_input))\n return (None, 0.0, [])","code_tokens":"","url":838196} +{"project_name":"MushroomRL\/mushroom-rl","file_name":"plot_dataset.py","full_name":"PlotDataset.load_state","func_name":"load_state","docstring":"Load the data to the plots given a path.","docstring_tokens":"","code":"def load_state(self, path):\n \"\"\"\n Load the data to the plots given a path.\n\n Args:\n path (str): path to load the data.\n\n \"\"\"\n with open(path, 'rb') as f:\n data = pickle.load(f)\n self.set_state(data)","code_tokens":"","url":266199} +{"project_name":"grayhong\/self-diagnosing-gan","file_name":"image_loader_with_attr.py","full_name":"get_celeba_images_with_attr","func_name":"get_celeba_images_with_attr","docstring":"Loads sampled CelebA images with index.","docstring_tokens":"","code":"def get_celeba_images_with_attr(attr, root='.\/dataset', size=128, num_samples=None, **kwargs):\n \"\"\"\n Loads sampled CelebA images with index.\n\n Args:\n index (ndarray): The index of images.\n root (str): The root directory where all datasets are stored.\n size (int): Size of image to resize to.\n\n Returns:\n ndarray: Batch of len(index) images in np array form.\n \"\"\"\n dataset = data_utils.load_celeba_dataset(root=root, size=size, transform_data=True, convert_tensor=False, **kwargs)\n dataset_dir = os.path.join(root, 'celeba')\n (attr_index, not_attr_index) = get_celeba_index_with_attr(dataset_dir, attr)\n print(f'Number of images with attribute {len(attr_index)}')\n print(f'Number of images without attribute {len(not_attr_index)}')\n if num_samples:\n if len(attr_index) > num_samples:\n attr_index = np.random.choice(attr_index, size=num_samples, replace=False)\n if len(not_attr_index) > num_samples:\n not_attr_index = np.random.choice(not_attr_index, size=num_samples, replace=False)\n attr_images = get_index_images(dataset, attr_index)\n not_attr_images = get_index_images(dataset, not_attr_index)\n print(f'Number of images with attribute {attr}: {len(attr_images)}')\n print(f'Number of images without attribute {attr}: {len(not_attr_images)}')\n return (attr_images, not_attr_images)","code_tokens":"","url":843172} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"axis.py","full_name":"Tick.get_view_interval","func_name":"get_view_interval","docstring":"Return the view limits ``(min, max)`` of the axis the tick belongs to.","docstring_tokens":"","code":"def get_view_interval(self):\n \"\"\"\n Return the view limits ``(min, max)`` of the axis the tick belongs to.\n \"\"\"\n raise NotImplementedError('Derived must override')","code_tokens":"","url":96056} +{"project_name":"nosmokingbandit\/watcher","file_name":"wspbus.py","full_name":"ChannelFailures.handle_exception","func_name":"handle_exception","docstring":"Append the current exception to self.","docstring_tokens":"","code":"def handle_exception(self):\n \"\"\"Append the current exception to self.\"\"\"\n self._exceptions.append(sys.exc_info()[1])","code_tokens":"","url":381535} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"pdb.py","full_name":"Pdb.do_next","func_name":"do_next","docstring":"n(ext) Continue execution until the next line in the current function is reached or it returns.","docstring_tokens":"","code":"def do_next(self, arg):\n \"\"\"n(ext)\n Continue execution until the next line in the current function\n is reached or it returns.\n \"\"\"\n self.set_next(self.curframe)\n return 1","code_tokens":"","url":281026} +{"project_name":"Div99\/LISA","file_name":"eval.py","full_name":"eval_episode","func_name":"eval_episode","docstring":"Evaluate a single episode.","docstring_tokens":"","code":"def eval_episode(env, no_lang, tokenizer, model, max_ep_len, K, words_dict, render, device, **kwargs):\n \"\"\"Evaluate a single episode.\"\"\"\n images = []\n method = model.method\n horizon = model.horizon\n if method != 'vanilla':\n option_dim = model.option_selector.option_dim\n else:\n option_dim = None\n if render and kwargs['i'] % kwargs['render_freq'] == 0:\n observation = env.reset(render=True, render_path=kwargs['render_path'], iter_num=kwargs['iter_num'], i=kwargs['i'])\n (cur_state, lang) = (observation['state'], observation['lang'])\n images.append(env.get_image())\n else:\n observation = env.reset(render=False)\n (cur_state, lang) = (observation['state'], observation['lang'])\n if no_lang:\n lang = ''\n state_dim = env.state_dim\n act_dim = env.act_dim\n cur_state = torch.from_numpy(cur_state)\n lm_input = tokenizer(text=[lang], add_special_tokens=True, return_tensors='pt', padding=True).to(device=device)\n with torch.no_grad():\n lm_embeddings = model.lm(lm_input['input_ids'], lm_input['attention_mask']).last_hidden_state\n cls_embeddings = lm_embeddings[:, 0, :]\n word_embeddings = lm_embeddings[:, 1:, :]\n if isinstance(state_dim, tuple):\n states = cur_state.reshape(1, *state_dim).to(device=device, dtype=torch.float32)\n else:\n states = cur_state.reshape(1, state_dim).to(device=device, dtype=torch.float32)\n actions = torch.zeros((0, act_dim), device=device, dtype=torch.float32)\n timesteps = torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)\n if method != 'vanilla':\n options = torch.zeros((0, option_dim), device=device, dtype=torch.float32)\n (episode_return, episode_length, success) = (0, 0, 0)\n options_list = []\n option = None\n for t in range(max_ep_len):\n actions = torch.cat([actions, torch.zeros((1, act_dim), device=device)], dim=0)\n if method != 'vanilla':\n options = torch.cat([options, torch.zeros((1, option_dim), device=device)], dim=0)\n else:\n options = None\n (action, option, states, actions, timesteps, options) = get_action(model, states, actions, options, timesteps, cls_embeddings, word_embeddings, options_list, cur_state, option, t, horizon, K, method, state_dim, act_dim, option_dim, device, **kwargs)\n if model.decision_transformer.discrete:\n actions[-1] = torch.nn.functional.one_hot(action, num_classes=act_dim)\n else:\n action = torch.clamp(action, torch.from_numpy(env.action_space.low).to(device), torch.from_numpy(env.action_space.high).to(device))\n actions[-1] = action\n action = action.detach().cpu().numpy()\n assert action in env.action_space, 'Transformer predicted action outside env action space'\n (obs, reward, done, info) = env.step(action)\n if render and kwargs['i'] % kwargs['render_freq'] == 0:\n images.append(env.get_image())\n (state, lang) = (obs['state'], obs['lang'])\n if no_lang:\n lang = ''\n if isinstance(state_dim, tuple):\n cur_state = torch.from_numpy(state).to(device=device).reshape(1, *state_dim)\n else:\n cur_state = torch.from_numpy(state).to(device=device).reshape(1, state_dim)\n states = torch.cat([states, cur_state], dim=0).float()\n timesteps = torch.cat([timesteps, torch.ones((1, 1), device=device, dtype=torch.long) * (t + 1)], dim=1)\n episode_return += reward\n episode_length += 1\n if done:\n success = info.get('success', -1)\n break\n if method != 'vanilla' and model.option_selector.use_vq:\n tokens = get_tokens(lm_input, tokenizer)\n for o in options_list:\n for w in tokens:\n words_dict[o].append(w)\n return (episode_return, episode_length, success, options_list, lang, images, words_dict)","code_tokens":"","url":216969} +{"project_name":"savinienb\/Matwo-CapsNet","file_name":"summary_handler.py","full_name":"SummaryHandler.reset_current_losses","func_name":"reset_current_losses","docstring":"Resets the current calculated running mean of the losses.","docstring_tokens":"","code":"def reset_current_losses(self):\n \"\"\"\n Resets the current calculated running mean of the losses.\n \"\"\"\n reset_op_list = list(zip(*self.loss_metrics.values()))[2]\n self.session.run(reset_op_list)","code_tokens":"","url":646305} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.skin_boneadr","func_name":"skin_boneadr","docstring":"first bone in skin (nskin x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef skin_boneadr(self):\n \"\"\"first bone in skin (nskin x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.skin_boneadr, (self.nskin,))","code_tokens":"","url":440361} +{"project_name":"filerock\/FileRock-Client","file_name":"IntegrityManager.py","full_name":"IntegrityManager.setCurrentBasis","func_name":"setCurrentBasis","docstring":"Sets currently stored trusted basis.","docstring_tokens":"","code":"def setCurrentBasis(self, basis):\n \"\"\"Sets currently stored trusted basis.\n \"\"\"\n self.trusted_basis = basis","code_tokens":"","url":180161} +{"project_name":"napratin\/lumos","file_name":"blobtracking.py","full_name":"Blob.diff","func_name":"diff","docstring":"Return the difference between this blob and other as a single numeric value.","docstring_tokens":"","code":"def diff(self, other):\n \"\"\"Return the difference between this blob and other as a single numeric value.\"\"\"\n selfBigger = self.hypot >= other.hypot\n areaDiff = abs(other.area - self.area) \/ (self.area if selfBigger else other.area)\n hypotDiff = abs(other.hypot - self.hypot) \/ (self.hypot if selfBigger else other.hypot)\n centerDiff = hypot(other.center[0] - self.center[0], other.center[1] - self.center[1]) \/ (self.hypot if selfBigger else other.hypot)\n return self.areaWeight * areaDiff + self.hypotWeight * hypotDiff + self.centerWeight * centerDiff","code_tokens":"","url":617605} +{"project_name":"feast-dev\/feast","file_name":"offline_utils.py","full_name":"get_pyarrow_schema_from_batch_source","func_name":"get_pyarrow_schema_from_batch_source","docstring":"Returns the pyarrow schema and column names for the given batch source.","docstring_tokens":"","code":"def get_pyarrow_schema_from_batch_source(config: RepoConfig, batch_source: DataSource, timestamp_unit: str='us') -> Tuple[pa.Schema, List[str]]:\n \"\"\"Returns the pyarrow schema and column names for the given batch source.\"\"\"\n column_names_and_types = batch_source.get_table_column_names_and_types(config)\n pa_schema = []\n column_names = []\n for (column_name, column_type) in column_names_and_types:\n pa_schema.append((column_name, feast_value_type_to_pa(batch_source.source_datatype_to_feast_value_type()(column_type), timestamp_unit=timestamp_unit)))\n column_names.append(column_name)\n return (pa.schema(pa_schema), column_names)","code_tokens":"","url":544385} +{"project_name":"rudranil723\/mini-main","file_name":"geometries.py","full_name":"OGRGeometry.point_count","func_name":"point_count","docstring":"Return the number of Points in this Geometry.","docstring_tokens":"","code":"@property\ndef point_count(self):\n \"\"\"Return the number of Points in this Geometry.\"\"\"\n return capi.get_point_count(self.ptr)","code_tokens":"","url":315096} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"timer_comparison.py","full_name":"ModuleTester.assert_array_equal","func_name":"assert_array_equal","docstring":"Checks the elementwise equality of two masked arrays.","docstring_tokens":"","code":"def assert_array_equal(self, x, y, err_msg=''):\n \"\"\"\n Checks the elementwise equality of two masked arrays.\n\n \"\"\"\n self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal')","code_tokens":"","url":2931} +{"project_name":"rudranil723\/mini-main","file_name":"layout.py","full_name":"Splitter.divide","func_name":"divide","docstring":"Divide a region amongst several child layouts.","docstring_tokens":"","code":"@abstractmethod\ndef divide(self, children: Sequence['Layout'], region: Region) -> Iterable[Tuple['Layout', Region]]:\n \"\"\"Divide a region amongst several child layouts.\n\n Args:\n children (Sequence(Layout)): A number of child layouts.\n region (Region): A rectangular region to divide.\n \"\"\"","code_tokens":"","url":268898} +{"project_name":"keras-team\/keras-nlp","file_name":"tokenizer.py","full_name":"Tokenizer.tokenize","func_name":"tokenize","docstring":"Transform input tensors of strings into output tokens.","docstring_tokens":"","code":"def tokenize(self, inputs, *args, **kwargs):\n \"\"\"Transform input tensors of strings into output tokens.\n\n Args:\n inputs: Input tensor, or dict\/list\/tuple of input tensors.\n *args: Additional positional arguments.\n **kwargs: Additional keyword arguments.\n \"\"\"\n raise NotImplementedError(f'No implementation of `tokenize()` was found for {self.__class__.__name__}. All tokenizers should implement `tokenize()`.')","code_tokens":"","url":595692} +{"project_name":"benedekrozemberczki\/karateclub","file_name":"graph_embedding_test.py","full_name":"test_netlsd","func_name":"test_netlsd","docstring":"Test the NetLSD embedding.","docstring_tokens":"","code":"def test_netlsd():\n \"\"\"\n Test the NetLSD embedding.\n \"\"\"\n graphs = [nx.newman_watts_strogatz_graph(50, 5, 0.3) for _ in range(100)]\n model = NetLSD()\n model.fit(graphs)\n embedding = model.get_embedding()\n assert embedding.shape[0] == len(graphs)\n assert embedding.shape[1] == model.scale_steps\n assert type(embedding) == np.ndarray\n graphs = [nx.newman_watts_strogatz_graph(500, 5, 0.3) for _ in range(100)]\n new_graphs = [nx.newman_watts_strogatz_graph(500, 5, 0.3) for _ in range(100)]\n model = NetLSD()\n model.fit(graphs)\n embedding = model.get_embedding()\n assert embedding.shape[0] == len(graphs)\n assert embedding.shape[1] == model.scale_steps\n assert type(embedding) == np.ndarray\n new_embedding = model.infer(new_graphs)\n assert new_embedding.shape[0] == len(new_graphs)\n assert new_embedding.shape[1] == model.scale_steps\n assert type(new_embedding) == np.ndarray","code_tokens":"","url":247414} +{"project_name":"srai-lab\/srai","file_name":"_optional.py","full_name":"import_optional_dependency","func_name":"import_optional_dependency","docstring":"Import a module or a element from the module.","docstring_tokens":"","code":"def import_optional_dependency(dependency_group: str, module: str, name: Optional[str]=None, error: ImportErrorHandle=ImportErrorHandle.RAISE) -> Optional[ModuleType]:\n \"\"\"\n Import a module or a element from the module.\n\n Args:\n dependency_group (str): Name of dependency group where dependency is defined.\n Helps communicate a proper error message to the end user.\n module (str): Name of a module.\n name (str, optional): Name of element from the module. If none, returns whole module.\n Otherwise returns a submodule found using a given name. Defaults to None.\n error (ErrorHandle, {'raise', 'warn', 'ignore'}): Information what to do when module hasn't\n been found. Can `raise` an error, write a warning (`warn`) or `ignore` missing module.\n Defaults to ErrorHandle.RAISE.\n\n Raises:\n ImportError: When required dependency is not installed.\n\n Returns:\n Optional[ModuleType]: Module or submodule imported using a name. None if not found.\n \"\"\"\n assert error in ImportErrorHandle.__members__.values()\n import importlib\n try:\n imported_module = importlib.import_module(module)\n return imported_module if name is None else getattr(imported_module, name)\n except ImportError as exc:\n error_msg = f'Missing optional dependency \"{module}\". Please install required packages using `pip install srai[{dependency_group}]`.'\n if error == ImportErrorHandle.RAISE:\n raise ImportError(error_msg) from exc\n if error == ImportErrorHandle.WARN:\n import warnings\n warnings.warn(f'{error_msg} Skipping import.', ImportWarning, stacklevel=2)\n return None","code_tokens":"","url":371849} +{"project_name":"ifwe\/digsby","file_name":"merge.py","full_name":"tolower","func_name":"tolower","docstring":"Returns a copy of a mapping tree with all string keys lowercased.","docstring_tokens":"","code":"def tolower(mapping, maptype=Storage):\n \"\"\"Returns a copy of a mapping tree with all string keys lowercased.\"\"\"\n return maptype(((getattr(k, 'lower', lambda k: k)(), tolower(v, maptype) if isMappingType(v) else v) for (k, v) in mapping.iteritems()))","code_tokens":"","url":186060} +{"project_name":"huawei-noah\/xingtian","file_name":"record.py","full_name":"ReportRecord.rewards","func_name":"rewards","docstring":"Get rewards, ReadOnly property.","docstring_tokens":"","code":"@rewards.setter\ndef rewards(self, value):\n \"\"\"Get rewards, ReadOnly property.\"\"\"\n self._rewards = value","code_tokens":"","url":968346} +{"project_name":"rishab-sharma\/object_detection","file_name":"base_model.py","full_name":"BaseModel.val_pascal","func_name":"val_pascal","docstring":"Validate the model on PASCAL dataset.","docstring_tokens":"","code":"def val_pascal(self, sess, val_pascal, val_dataset):\n \"\"\" Validate the model on PASCAL dataset. \"\"\"\n print('Validating the model...')\n num_roi = self.num_roi\n det_scores = []\n det_classes = []\n det_bboxes = []\n for k in tqdm(list(range(val_dataset.count))):\n batch = val_dataset.next_batch()\n img_files = batch\n img_file = img_files[0]\n (H, W) = (val_dataset.img_heights[k], val_dataset.img_widths[k])\n imgs = self.img_loader.load_imgs(img_files)\n feats = sess.run(self.conv_feats, feed_dict={self.imgs: imgs, self.is_train: False})\n feed_dict = self.get_feed_dict_for_rpn(batch, is_train=False, feats=feats)\n (scores, regs) = sess.run([self.rpn_scores, self.rpn_regs], feed_dict=feed_dict)\n rois = unparam_bbox(regs.squeeze(), self.anchors, self.img_shape[:2])\n (num_real_roi, real_rois) = self.process_rpn_result(scores.squeeze(), rois)\n rois = np.ones((num_roi, 4), np.int32) * 3\n rois[:num_real_roi] = real_rois\n expanded_rois = expand_bbox(rois, self.img_shape[:2])\n expanded_rois = np.expand_dims(expanded_rois, 0)\n masks = np.zeros(num_roi, np.float32)\n masks[:num_real_roi] = 1.0\n masks = np.expand_dims(masks, 0)\n feed_dict = self.get_feed_dict_for_rcn(batch, is_train=False, feats=feats, rois=expanded_rois, masks=masks)\n (scores, classes, regs) = sess.run([self.res_scores, self.res_classes, self.res_regs], feed_dict=feed_dict)\n bboxes = unparam_bbox(regs.squeeze(), rois)\n (num_det, scores, classes, bboxes) = self.process_rcn_result(scores.squeeze(), classes.squeeze(), bboxes, H, W)\n det_scores.append(scores)\n det_classes.append(classes)\n det_bboxes.append(bboxes)\n val_dataset.reset()\n results = {}\n for i in range(val_dataset.count):\n file_name = val_dataset.img_files[i].split(os.sep)[-1]\n results[file_name] = []\n for (s, c, b) in zip(det_scores[i], det_classes[i], det_bboxes[i]):\n results[file_name].append({'class_id': c, 'bbox': [b[1], b[0], b[1] + b[3] - 1, b[0] + b[2] - 1], 'score': s})\n eval_pascal(val_pascal, results)\n print('Validation complete.')","code_tokens":"","url":744833} +{"project_name":"myuon\/AI","file_name":"graphicsDisplay.py","full_name":"InfoPane.toScreen","func_name":"toScreen","docstring":"Translates a point relative from the bottom left of the info pane.","docstring_tokens":"","code":"def toScreen(self, pos, y=None):\n \"\"\"\n Translates a point relative from the bottom left of the info pane.\n \"\"\"\n if y == None:\n (x, y) = pos\n else:\n x = pos\n x = self.gridSize + x\n y = self.base + y\n return (x, y)","code_tokens":"","url":25505} +{"project_name":"deepmind\/dm_control","file_name":"cartpole.py","full_name":"swingup_sparse","func_name":"swingup_sparse","docstring":"Returns the sparse reward variant of the Cartpole Swing-Up task.","docstring_tokens":"","code":"@SUITE.add('benchmarking')\ndef swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):\n \"\"\"Returns the sparse reward variant of the Cartpole Swing-Up task.\"\"\"\n physics = Physics.from_xml_string(*get_model_and_assets())\n task = Balance(swing_up=True, sparse=True, random=random)\n environment_kwargs = environment_kwargs or {}\n return control.Environment(physics, task, time_limit=time_limit, **environment_kwargs)","code_tokens":"","url":165391} +{"project_name":"srai-lab\/srai","file_name":"test_with_regions.py","full_name":"test_get_neighbours_up_to_distance_with_regions_gdf","func_name":"test_get_neighbours_up_to_distance_with_regions_gdf","docstring":"Test get_neighbours_up_to_distance of H3Neighbourhood with a specified regions.","docstring_tokens":"","code":"@pytest.mark.parametrize('distance,expected,expected_with_include_center', [(0, set(), {'862bac507ffffff'}), (1, {'862bac50fffffff', '862bac517ffffff', '862bac51fffffff', '862bac527ffffff'}, {'862bac50fffffff', '862bac517ffffff', '862bac51fffffff', '862bac527ffffff', '862bac507ffffff'}), (2, {'862bac50fffffff', '862bac517ffffff', '862bac51fffffff', '862bac527ffffff', '862ba124fffffff', '862ba126fffffff', '862bac427ffffff', '862bac437ffffff', '862bac557ffffff', '862bac577ffffff', '862bac5a7ffffff', '862bac5afffffff', '862bacc8fffffff'}, {'862bac50fffffff', '862bac517ffffff', '862bac51fffffff', '862bac527ffffff', '862ba124fffffff', '862ba126fffffff', '862bac427ffffff', '862bac437ffffff', '862bac557ffffff', '862bac577ffffff', '862bac5a7ffffff', '862bac5afffffff', '862bacc8fffffff', '862bac507ffffff'})])\ndef test_get_neighbours_up_to_distance_with_regions_gdf(distance: int, expected: Set[str], expected_with_include_center: Set[str], request: Any) -> None:\n \"\"\"Test get_neighbours_up_to_distance of H3Neighbourhood with a specified regions.\"\"\"\n center_region = '862bac507ffffff'\n regions_gdf = request.getfixturevalue('two_rings_regions_some_missing')\n neighbourhood = H3Neighbourhood(regions_gdf)\n assert neighbourhood.get_neighbours_up_to_distance(center_region, distance) == expected\n assert neighbourhood.get_neighbours_up_to_distance(center_region, distance, include_center=True) == expected_with_include_center\n neighbourhood_with_include_center = H3Neighbourhood(regions_gdf, include_center=True)\n assert neighbourhood_with_include_center.get_neighbours_up_to_distance(center_region, distance) == expected_with_include_center\n assert neighbourhood_with_include_center.get_neighbours_up_to_distance(center_region, distance, include_center=False) == expected","code_tokens":"","url":372099} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"bases.py","full_name":"Property.serialize_value","func_name":"serialize_value","docstring":"Change the value into a JSON serializable format.","docstring_tokens":"","code":"def serialize_value(self, value):\n \"\"\" Change the value into a JSON serializable format.\n\n \"\"\"\n return value","code_tokens":"","url":977248} +{"project_name":"AgnostiqHQ\/covalent","file_name":"dir_trigger.py","full_name":"DirTrigger.attach_methods_to_handler","func_name":"attach_methods_to_handler","docstring":"Dynamically attaches and overrides the \"on_*\" methods to the handler depending on which ones are requested by the user.","docstring_tokens":"","code":"def attach_methods_to_handler(self) -> None:\n \"\"\"\n Dynamically attaches and overrides the \"on_*\" methods to the handler\n depending on which ones are requested by the user.\n\n Args:\n event_names: List of event names upon which to perform a trigger action\n \"\"\"\n app_log.warning('Attaching methods to dir handler')\n self.n_changes = 0\n\n def proxy_trigger(_, event_object):\n self.n_changes += 1\n if self.n_changes == self.batch_size:\n self.trigger()\n self.n_changes = 0\n for en in self.event_names:\n func_name = self.event_handler.supported_event_to_func_names[en]\n proxy_trigger.__name__ = func_name\n setattr(self.event_handler, func_name, MethodType(proxy_trigger, self.event_handler))","code_tokens":"","url":489454} +{"project_name":"Deci-AI\/super-gradients","file_name":"distributed_training_utils.py","full_name":"get_gpu_mem_utilization","func_name":"get_gpu_mem_utilization","docstring":"GPU memory managed by the caching allocator in bytes for a given device.","docstring_tokens":"","code":"def get_gpu_mem_utilization():\n \"\"\"GPU memory managed by the caching allocator in bytes for a given device.\"\"\"\n if hasattr(torch.cuda, 'memory_reserved'):\n return torch.cuda.memory_reserved()\n else:\n return torch.cuda.memory_cached()","code_tokens":"","url":880472} +{"project_name":"gletarte\/dichotomize-and-generalize","file_name":"networks.py","full_name":"BaselineNet.init_weights","func_name":"init_weights","docstring":"Network parameters random initialization.","docstring_tokens":"","code":"def init_weights(self):\n \"\"\"Network parameters random initialization.\"\"\"\n for layer in self.layers:\n if isinstance(layer, nn.Linear):\n torch.nn.init.xavier_normal_(layer.weight)\n layer.bias.data.zero_()","code_tokens":"","url":550310} +{"project_name":"rudranil723\/mini-main","file_name":"lexer.py","full_name":"bygroups","func_name":"bygroups","docstring":"Callback that yields multiple actions for each group in the match.","docstring_tokens":"","code":"def bygroups(*args):\n \"\"\"\n Callback that yields multiple actions for each group in the match.\n \"\"\"\n\n def callback(lexer, match, ctx=None):\n for (i, action) in enumerate(args):\n if action is None:\n continue\n elif type(action) is _TokenType:\n data = match.group(i + 1)\n if data:\n yield (match.start(i + 1), action, data)\n else:\n data = match.group(i + 1)\n if data is not None:\n if ctx:\n ctx.pos = match.start(i + 1)\n for item in action(lexer, _PseudoMatch(match.start(i + 1), data), ctx):\n if item:\n yield item\n if ctx:\n ctx.pos = match.end()\n return callback","code_tokens":"","url":268582} +{"project_name":"saghul\/evergreen","file_name":"locks.py","full_name":"Barrier.broken","func_name":"broken","docstring":"Return True if the barrier is in a broken state.","docstring_tokens":"","code":"@property\ndef broken(self):\n \"\"\"Return True if the barrier is in a broken state.\"\"\"\n return self._state == -2","code_tokens":"","url":178439} +{"project_name":"HDI-Project\/ATM","file_name":"database.py","full_name":"Database.mark_datarun_complete","func_name":"mark_datarun_complete","docstring":"Set the status of the Datarun to COMPLETE and set the 'end_time' field to the current datetime.","docstring_tokens":"","code":"@try_with_session(commit=True)\ndef mark_datarun_complete(self, datarun_id):\n \"\"\"\n Set the status of the Datarun to COMPLETE and set the 'end_time' field\n to the current datetime.\n \"\"\"\n datarun = self.get_datarun(datarun_id)\n datarun.status = RunStatus.COMPLETE\n datarun.end_time = datetime.now()","code_tokens":"","url":402696} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"operator.py","full_name":"imatmul","func_name":"imatmul","docstring":"Same as a @= b.","docstring_tokens":"","code":"def imatmul(a, b):\n \"\"\"Same as a @= b.\"\"\"\n a @= b\n return a","code_tokens":"","url":187919} +{"project_name":"rudranil723\/mini-main","file_name":"protobuf_helpers.py","full_name":"get","func_name":"get","docstring":"Retrieve a key's value from a protobuf Message or dictionary.","docstring_tokens":"","code":"def get(msg_or_dict, key, default=_SENTINEL):\n \"\"\"Retrieve a key's value from a protobuf Message or dictionary.\n\n Args:\n mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the\n object.\n key (str): The key to retrieve from the object.\n default (Any): If the key is not present on the object, and a default\n is set, returns that default instead. A type-appropriate falsy\n default is generally recommended, as protobuf messages almost\n always have default values for unset values and it is not always\n possible to tell the difference between a falsy value and an\n unset one. If no default is set then :class:`KeyError` will be\n raised if the key is not present in the object.\n\n Returns:\n Any: The return value from the underlying Message or dict.\n\n Raises:\n KeyError: If the key is not found. Note that, for unset values,\n messages and dictionaries may not have consistent behavior.\n TypeError: If ``msg_or_dict`` is not a Message or Mapping.\n \"\"\"\n (key, subkey) = _resolve_subkeys(key)\n if isinstance(msg_or_dict, message.Message):\n answer = getattr(msg_or_dict, key, default)\n elif isinstance(msg_or_dict, collections.abc.Mapping):\n answer = msg_or_dict.get(key, default)\n else:\n raise TypeError('get() expected a dict or protobuf message, got {!r}.'.format(type(msg_or_dict)))\n if answer is _SENTINEL:\n raise KeyError(key)\n if subkey is not None and answer is not default:\n return get(answer, subkey, default=default)\n return answer","code_tokens":"","url":317674} +{"project_name":"huiminren\/RobustVAE","file_name":"sparseFrobeniusNorm.py","full_name":"sparseFrobeniusNorm","func_name":"sparseFrobeniusNorm","docstring":"Compute a the Frobenius norm of the observed entries of a sparse matrix.","docstring_tokens":"","code":"def sparseFrobeniusNorm(X):\n \"\"\" Compute a the Frobenius norm of the observed entries of a sparse matrix.\n\n Args:\n X: a sparse matrix\n\n Returns:\n The square root of the sum of the squares of the observed entries.\n \"\"\"\n tmp = X.multiply(X)\n return np.sqrt(tmp.sum())","code_tokens":"","url":826408} +{"project_name":"BYU-PCCL\/holodeck","file_name":"command.py","full_name":"CommandsGroup.clear","func_name":"clear","docstring":"Clear the list of commands.","docstring_tokens":"","code":"def clear(self):\n \"\"\"Clear the list of commands.\"\"\"\n self._commands.clear()","code_tokens":"","url":570115} +{"project_name":"schulter\/crbm","file_name":"testcrbm.py","full_name":"TestCRBM.test_topdown_singlestranded_randomhidden","func_name":"test_topdown_singlestranded_randomhidden","docstring":"Test topdown with random hidden states.","docstring_tokens":"","code":"def test_topdown_singlestranded_randomhidden(self):\n \"\"\"Test topdown with random hidden states.\"\"\"\n nseq = 11\n seqlen = 200\n nmot = 10\n mlen = 5\n data = np.random.binomial(1, p=[[[[0.1] * (seqlen - mlen + 1)] * 1] * nmot] * nseq).astype('float32')\n model = CRBM(num_motifs=nmot, motif_length=mlen)\n (oa, op, op2) = self.topdownActivitySS(model, data)\n w = model.motifs.get_value()\n c = model.c.get_value()\n output_control = self.controlTopDownActivity(w, c, data)\n np.testing.assert_equal(oa.shape, (nseq, 1, 4, seqlen))\n np.testing.assert_equal(op.shape, (nseq, 1, 4, seqlen))\n np.testing.assert_allclose(oa, output_control, rtol=1e-05, atol=1e-05)\n output_control = np.exp(output_control) \/ np.exp(output_control).sum(axis=2, keepdims=True)\n np.testing.assert_allclose(output_control, op, rtol=1e-05, atol=1e-05)\n np.testing.assert_allclose(output_control, op2, rtol=1e-05, atol=1e-05)","code_tokens":"","url":138467} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"__init__.py","full_name":"Text.tag_ranges","func_name":"tag_ranges","docstring":"Return a list of ranges of text which have tag TAGNAME.","docstring_tokens":"","code":"def tag_ranges(self, tagName):\n \"\"\"Return a list of ranges of text which have tag TAGNAME.\"\"\"\n return self.tk.splitlist(self.tk.call(self._w, 'tag', 'ranges', tagName))","code_tokens":"","url":284362} +{"project_name":"Cocoxili\/CMPC","file_name":"dataloader.py","full_name":"load_data","func_name":"load_data","docstring":"Load data from pickle file Parameters ---------- filename: str Path to file Returns ------- data: list or dict Loaded file.","docstring_tokens":"","code":"def load_data(filename):\n \"\"\"Load data from pickle file\n\n Parameters\n ----------\n filename: str\n Path to file\n\n Returns\n -------\n data: list or dict\n Loaded file.\n\n \"\"\"\n return pickle.load(open(filename, 'rb'), encoding='latin1')","code_tokens":"","url":123446} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"configurer.py","full_name":"BaseConfigurer.get_subset_data_cfg","func_name":"get_subset_data_cfg","docstring":"Get subset's data cfg.","docstring_tokens":"","code":"@staticmethod\ndef get_subset_data_cfg(cfg, subset):\n \"\"\"Get subset's data cfg.\"\"\"\n assert subset in ['train', 'val', 'test', 'unlabeled'], f'Unknown subset:{subset}'\n if 'dataset' in cfg.data[subset]:\n dataset = cfg.data[subset].dataset\n while hasattr(dataset, 'dataset'):\n dataset = dataset.dataset\n return dataset\n return cfg.data[subset]","code_tokens":"","url":917786} +{"project_name":"alex-petrenko\/sample-factory","file_name":"utils.py","full_name":"numpy_all_the_way","func_name":"numpy_all_the_way","docstring":"Turn a list of numpy arrays into a 2D numpy array.","docstring_tokens":"","code":"def numpy_all_the_way(list_of_arrays):\n \"\"\"Turn a list of numpy arrays into a 2D numpy array.\"\"\"\n shape = list(list_of_arrays[0].shape)\n shape[:0] = [len(list_of_arrays)]\n arr = np.concatenate(list_of_arrays).reshape(shape)\n return arr","code_tokens":"","url":329056} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"test_sync_vector_env.py","full_name":"test_sync_vector_determinism","func_name":"test_sync_vector_determinism","docstring":"Check that for all environments, the sync vector envs produce the same action samples using the same seeds.","docstring_tokens":"","code":"@pytest.mark.parametrize('spec', all_testing_env_specs, ids=[spec.id for spec in all_testing_env_specs])\ndef test_sync_vector_determinism(spec: EnvSpec, seed: int=123, n: int=3):\n \"\"\"Check that for all environments, the sync vector envs produce the same action samples using the same seeds.\"\"\"\n env_1 = SyncVectorEnv([make_env(spec.id, seed=seed) for _ in range(n)])\n env_2 = SyncVectorEnv([make_env(spec.id, seed=seed) for _ in range(n)])\n assert_rng_equal(env_1.action_space.np_random, env_2.action_space.np_random)\n for _ in range(100):\n env_1_samples = env_1.action_space.sample()\n env_2_samples = env_2.action_space.sample()\n assert np.all(env_1_samples == env_2_samples)","code_tokens":"","url":573543} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"imaplib.py","full_name":"IMAP4_stream.readline","func_name":"readline","docstring":"Read line from remote.","docstring_tokens":"","code":"def readline(self):\n \"\"\"Read line from remote.\"\"\"\n return self.readfile.readline()","code_tokens":"","url":280524} +{"project_name":"Megvii-BaseDetection\/DynamicRouting","file_name":"jit_handles.py","full_name":"addmm_flop_jit","func_name":"addmm_flop_jit","docstring":"This method counts the flops for fully connected layers with torch script.","docstring_tokens":"","code":"def addmm_flop_jit(inputs: typing.List[object], outputs: typing.List[object]) -> typing.Counter[str]:\n \"\"\"\n This method counts the flops for fully connected layers with torch script.\n Args:\n inputs (list(torch._C.Value)): The input shape in the form of a list of\n jit object.\n outputs (list(torch._C.Value)): The output shape in the form of a list\n of jit object.\n Returns:\n Counter: A Counter dictionary that records the number of flops for each\n operation.\n \"\"\"\n input_shapes = [get_shape(v) for v in inputs[1:3]]\n assert len(input_shapes[0]) == 2\n assert len(input_shapes[1]) == 2\n (batch_size, input_dim) = input_shapes[0]\n output_dim = input_shapes[1][1]\n flop = batch_size * input_dim * output_dim\n flop_counter = Counter({'addmm': flop})\n return flop_counter","code_tokens":"","url":555224} +{"project_name":"Dsajeet\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"visitor.py","full_name":"MethodContent.acceptReturn","func_name":"acceptReturn","docstring":"Creates a new return expression.","docstring_tokens":"","code":"def acceptReturn(self, node, memo):\n \"\"\" Creates a new return expression. \"\"\"\n if node.parentType:\n expr = self.factory.expr(left='return', parent=self)\n if node.children:\n (expr.fs, expr.right) = (FS.lsr, self.factory.expr(parent=expr))\n expr.right.walk(node, memo)\n return expr","code_tokens":"","url":17221} +{"project_name":"intel\/neural-compressor","file_name":"utility.py","full_name":"version1_lte_version2","func_name":"version1_lte_version2","docstring":"Check whether version1 is less than version2 or is equal to it.","docstring_tokens":"","code":"def version1_lte_version2(version1, version2):\n \"\"\"Check whether version1 is less than version2 or is equal to it.\"\"\"\n return parse_version(version1) < parse_version(version2) or parse_version(version1) == parse_version(version2)","code_tokens":"","url":721485} +{"project_name":"instadeepai\/jumanji","file_name":"env_not_smoke_test.py","full_name":"fake_env","func_name":"fake_env","docstring":"Instantiate the FakeEnvironment for testing.","docstring_tokens":"","code":"@pytest.fixture\ndef fake_env() -> FakeEnvironment:\n \"\"\"Instantiate the FakeEnvironment for testing.\"\"\"\n return FakeEnvironment()","code_tokens":"","url":594555} +{"project_name":"tensorflow\/data-validation","file_name":"artifacts_io_impl.py","full_name":"default_record_reader","func_name":"default_record_reader","docstring":"TFRecord based record iterator.","docstring_tokens":"","code":"def default_record_reader(input_pattern: str, message_factory: Callable[[], _MESSAGE_TYPE]) -> Iterator[_MESSAGE_TYPE]:\n \"\"\"TFRecord based record iterator.\"\"\"\n for path in tf.io.gfile.glob(input_pattern):\n for record in tf.compat.v1.io.tf_record_iterator(path):\n m = message_factory()\n m.ParseFromString(record)\n yield m","code_tokens":"","url":497585} +{"project_name":"thaines\/helit","file_name":"model.py","full_name":"Model.sampleCount","func_name":"sampleCount","docstring":"Returns the number of samples.","docstring_tokens":"","code":"def sampleCount(self):\n \"\"\"Returns the number of samples.\"\"\"\n return len(self.sample)","code_tokens":"","url":591180} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"minigo.py","full_name":"run_selfplay","func_name":"run_selfplay","docstring":"Run selfplay to generate training data.","docstring_tokens":"","code":"def run_selfplay(selfplay_model, selfplay_games, dirs, params):\n \"\"\"Run selfplay to generate training data.\n\n Args:\n selfplay_model: The model name for selfplay.\n selfplay_games: The number of selfplay games.\n dirs: A MiniGoDirectory instance of directories used in each step.\n params: A MiniGoParams instance of hyperparameters for the model.\n \"\"\"\n (selfplay_dirs, network) = _prepare_selfplay(selfplay_model, dirs.trained_models_dir, dirs.selfplay_dir, dirs.holdout_dir, dirs.sgf_dir, params)\n print('Self-play with model: {}'.format(selfplay_model))\n for _ in range(selfplay_games):\n selfplay(selfplay_dirs, network, params)","code_tokens":"","url":763887} +{"project_name":"AIChallenger\/AI_Challenger_2018","file_name":"inference.py","full_name":"DeepLabModel.run","func_name":"run","docstring":"Runs inference on a single image.","docstring_tokens":"","code":"def run(self, image):\n \"\"\"Runs inference on a single image.\n Args:\n image: A PIL.Image object, raw input image.\n Returns:\n seg_map: Segmentation map of the input image.\n \"\"\"\n batch_seg_map = self.sess.run(self.OUTPUT_TENSOR_NAME, feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(image)]})\n seg_map = batch_seg_map[0]\n return seg_map","code_tokens":"","url":87102} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"base_trainer.py","full_name":"Trainer.validation_metrics","func_name":"validation_metrics","docstring":"Accesses all validation metric metric objects.","docstring_tokens":"","code":"@property\ndef validation_metrics(self):\n \"\"\"Accesses all validation metric metric objects.\"\"\"\n return self._validation_metrics","code_tokens":"","url":972311} +{"project_name":"keiohta\/tf2rl","file_name":"apex.py","full_name":"learner","func_name":"learner","docstring":"Update network weights using samples collected by explorers.","docstring_tokens":"","code":"def learner(global_rb, trained_steps, is_training_done, lock, env, policy_fn, get_weights_fn, n_training, update_freq, evaluation_freq, gpu, queues):\n \"\"\"Update network weights using samples collected by explorers.\n\n Args:\n global_rb: multiprocessing.managers.AutoProxy[PrioritizedReplayBuffer]\n Prioritized replay buffer sharing with multiple explorers and only one learner.\n This object is shared over processes, so it must be locked when trying to\n operate something with `lock` object.\n trained_steps: multiprocessing.Value\n Number of steps to apply gradients.\n is_training_done: multiprocessing.Event\n multiprocessing.Event object to share the status of training.\n lock: multiprocessing.Lock\n multiprocessing.Lock to lock other processes.\n env: OpenAI-gym compatible environment object\n policy_fn: function\n Method object to generate an explorer.\n get_weights_fn: function\n Method object to get network weights and put them to queue.\n n_training: int\n Maximum number of times to apply gradients. If number of applying gradients\n is over this value, training will be done by setting `is_training_done` to `True`\n update_freq: int\n Frequency to update parameters, i.e., put network parameters to `queues`\n evaluation_freq: int\n Frequency to call `evaluator`.\n gpu: int\n GPU id. If this is set to -1, then this process uses only CPU.\n queues: List\n List of Queues shared with explorers to send latest network parameters.\n\n Returns:\n None\n \"\"\"\n tf = import_tf()\n logger = logging.getLogger('tf2rl')\n policy = policy_fn(env, 'Learner', global_rb.get_buffer_size(), gpu=gpu)\n output_dir = prepare_output_dir(args=None, user_specified_dir='.\/results', suffix='learner')\n writer = tf.summary.create_file_writer(output_dir)\n writer.set_as_default()\n while not is_training_done.is_set() and global_rb.get_stored_size() < policy.n_warmup:\n continue\n start_time = time.time()\n while not is_training_done.is_set():\n trained_steps.value += 1\n tf.summary.experimental.set_step(trained_steps.value)\n lock.acquire()\n samples = global_rb.sample(policy.batch_size)\n lock.release()\n td_errors = policy.train(samples['obs'], samples['act'], samples['next_obs'], samples['rew'], samples['done'], samples['weights'])\n writer.flush()\n lock.acquire()\n global_rb.update_priorities(samples['indexes'], np.abs(td_errors) + 1e-06)\n lock.release()\n if trained_steps.value % update_freq == 0:\n weights = get_weights_fn(policy)\n for i in range(len(queues) - 1):\n queues[i].put(weights)\n fps = update_freq \/ (time.time() - start_time)\n tf.summary.scalar(name='apex\/fps', data=fps)\n logger.info('Update weights. {0:.2f} FPS for GRAD. Learned {1:.2f} steps'.format(fps, trained_steps.value))\n start_time = time.time()\n if trained_steps.value % evaluation_freq == 0:\n queues[-1].put(get_weights_fn(policy))\n queues[-1].put(trained_steps.value)\n if trained_steps.value >= n_training:\n is_training_done.set()","code_tokens":"","url":367057} +{"project_name":"RasaHQ\/rasa_core","file_name":"domain.py","full_name":"Domain.prev_action_states","func_name":"prev_action_states","docstring":"Returns all available previous action state strings.","docstring_tokens":"","code":"@utils.lazyproperty\ndef prev_action_states(self):\n \"\"\"Returns all available previous action state strings.\"\"\"\n return [PREV_PREFIX + a for a in self.action_names]","code_tokens":"","url":838170} +{"project_name":"CAMeL-Lab\/camel_tools","file_name":"stringutils.py","full_name":"force_encoding","func_name":"force_encoding","docstring":"Convert a given string into an encoded string if it isn't already.","docstring_tokens":"","code":"def force_encoding(s, encoding='utf-8'):\n \"\"\"Convert a given string into an encoded string if it isn't already.\n\n Args:\n s (:obj:`str`): String object to convert.\n\n encoding (:obj:`str`): The encoding **s** should be encoded into.\n Note that if **s** is already encoded, it is returned as is,\n even though it is in a differnet encoding than what is passed to\n this parameter. Defaults to 'utf-8'.\n\n Returns:\n :obj:`str`: An encoded version of **s**.\n \"\"\"\n if s is None or isinstance(s, six.binary_type):\n return s\n return s.encode(encoding)","code_tokens":"","url":411181} +{"project_name":"mlcommons\/medperf","file_name":"utils.py","full_name":"LabelsParser.time_str_to_sec","func_name":"time_str_to_sec","docstring":"A util function to convert a timestamp to seconds.","docstring_tokens":"","code":"def time_str_to_sec(time_str):\n \"\"\"A util function to convert a timestamp to seconds.\n\n Args:\n time_str (str): A timestamp of form 'hh:mm:ss.ss'.\n\n Returns:\n float: The corresponding number of seconds.\n \n \"\"\"\n (hrs, min, sec) = time_str.split(':')\n hrs = int(hrs)\n min = int(min)\n sec = float(sec)\n return hrs * 3600 + min * 60 + sec","code_tokens":"","url":285167} +{"project_name":"pokaxpoka\/sunrise","file_name":"fisher_blocks.py","full_name":"ConvDiagonalFB.register_additional_minibatch","func_name":"register_additional_minibatch","docstring":"Registers an additional minibatch to the FisherBlock.","docstring_tokens":"","code":"def register_additional_minibatch(self, inputs, outputs):\n \"\"\"Registers an additional minibatch to the FisherBlock.\n Args:\n inputs: Tensor of shape [batch_size, height, width, input_size]. Inputs to\n the convolution.\n outputs: Tensor of shape [batch_size, height, width, output_size]. Layer\n preactivations.\n \"\"\"\n self._inputs.append(inputs)\n self._outputs.append(outputs)","code_tokens":"","url":911804} +{"project_name":"SvenGronauer\/phoenix-drone-simulation","file_name":"loggers.py","full_name":"Logger.save_env_config","func_name":"save_env_config","docstring":"Save configuration of environment to disk.","docstring_tokens":"","code":"def save_env_config(self, env: gym.Env, file_name='env_config.json'):\n \"\"\"Save configuration of environment to disk.\"\"\"\n assert isinstance(env, gym.Env)\n all_env_locals = env.unwrapped.__dict__.copy()\n self.save_dict_to_disk(all_env_locals, file_name, console_print=False)","code_tokens":"","url":769191} +{"project_name":"rudranil723\/mini-main","file_name":"__init__.py","full_name":"get_flac_converter","func_name":"get_flac_converter","docstring":"Returns the absolute path of a FLAC converter executable, or raises an OSError if none can be found.","docstring_tokens":"","code":"def get_flac_converter():\n \"\"\"Returns the absolute path of a FLAC converter executable, or raises an OSError if none can be found.\"\"\"\n flac_converter = shutil_which('flac')\n if flac_converter is None:\n base_path = os.path.dirname(os.path.abspath(__file__))\n (system, machine) = (platform.system(), platform.machine())\n if system == 'Windows' and machine in {'i686', 'i786', 'x86', 'x86_64', 'AMD64'}:\n flac_converter = os.path.join(base_path, 'flac-win32.exe')\n elif system == 'Darwin' and machine in {'i686', 'i786', 'x86', 'x86_64', 'AMD64'}:\n flac_converter = os.path.join(base_path, 'flac-mac')\n elif system == 'Linux' and machine in {'i686', 'i786', 'x86'}:\n flac_converter = os.path.join(base_path, 'flac-linux-x86')\n elif system == 'Linux' and machine in {'x86_64', 'AMD64'}:\n flac_converter = os.path.join(base_path, 'flac-linux-x86_64')\n else:\n raise OSError(\"FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent\")\n try:\n if not os.access(flac_converter, os.X_OK):\n stat_info = os.stat(flac_converter)\n os.chmod(flac_converter, stat_info.st_mode | stat.S_IEXEC)\n if 'Linux' in platform.system():\n os.sync() if sys.version_info >= (3, 3) else os.system('sync')\n except OSError:\n pass\n return flac_converter","code_tokens":"","url":270625} +{"project_name":"tmadl\/semisup-learn","file_name":"qns3vm.py","full_name":"QN_S3VM.getPredictions","func_name":"getPredictions","docstring":"Computes the predicted labels for a given set of patterns Keyword arguments: X -- The set of patterns real_valued -- If True, then the real prediction values are returned Returns: The predictions for the list X of patterns.","docstring_tokens":"","code":"def getPredictions(self, X, real_valued=False):\n \"\"\"\n Computes the predicted labels for a given set of patterns\n\n Keyword arguments:\n X -- The set of patterns\n real_valued -- If True, then the real prediction values are returned\n\n Returns:\n The predictions for the list X of patterns.\n \"\"\"\n return self.__model.getPredictions(X, real_valued=False)","code_tokens":"","url":343605} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"default.py","full_name":"QueryParser.remove_plugin","func_name":"remove_plugin","docstring":"Removes the given plugin object from the list of plugins in this parser.","docstring_tokens":"","code":"def remove_plugin(self, pi):\n \"\"\"Removes the given plugin object from the list of plugins in this\n parser.\n \"\"\"\n self.plugins.remove(pi)","code_tokens":"","url":133510} +{"project_name":"surafelml\/adapt-mnmt","file_name":"compat.py","full_name":"tf_supports","func_name":"tf_supports","docstring":"Returns ``True`` if TensorFlow defines :obj:`symbol`.","docstring_tokens":"","code":"def tf_supports(symbol):\n \"\"\"Returns ``True`` if TensorFlow defines :obj:`symbol`.\"\"\"\n return _string_to_tf_symbol(symbol) is not None","code_tokens":"","url":407843} +{"project_name":"deepmind\/dm_control","file_name":"util.py","full_name":"TimeMultiplier.decrease","func_name":"decrease","docstring":"Halves the current time factor value.","docstring_tokens":"","code":"def decrease(self):\n \"\"\"Halves the current time factor value.\"\"\"\n self.set(self._real_time_multiplier \/ 2.0)","code_tokens":"","url":165708} +{"project_name":"rlgraph\/rlgraph","file_name":"decorators.py","full_name":"define_api_method","func_name":"define_api_method","docstring":"Registers an API-method with a Component instance.","docstring_tokens":"","code":"def define_api_method(component, api_method_record, copy_record=True):\n \"\"\"\n Registers an API-method with a Component instance.\n\n Args:\n component (Component): The Component object to register the API method with.\n api_method_record (APIMethodRecord): The APIMethodRecord describing the to-be-registered API-method.\n copy_record (bool): Whether to deepcopy the APIMethodRecord prior to handing it to the Component for storing.\n \"\"\"\n if copy_record:\n api_method_record = copy.deepcopy(api_method_record)\n api_method_record.component = component\n if not api_method_record.ok_to_overwrite:\n if api_method_record.name in component.api_methods:\n raise RLGraphError(\"API-method with name '{}' already defined!\".format(api_method_record.name))\n elif not api_method_record.is_class_method and getattr(component, api_method_record.name, None) is not None:\n raise RLGraphError(\"Component '{}' already has a property called '{}'. Cannot define an API-method with the same name!\".format(component.name, api_method_record.name))\n if api_method_record.name in component.switched_off_apis:\n return\n component.synthetic_methods.add(api_method_record.name)\n setattr(component, api_method_record.name, api_method_record.wrapper_func.__get__(component, component.__class__))\n setattr(api_method_record.wrapper_func, '__name__', api_method_record.name)\n component.api_methods[api_method_record.name] = api_method_record\n component.api_fn_by_name[api_method_record.name] = api_method_record.wrapper_func\n skip_args = 1\n skip_args += api_method_record.is_graph_fn_wrapper and api_method_record.add_auto_key_as_first_param\n param_list = list(inspect.signature(api_method_record.func).parameters.values())[skip_args:]\n for param in param_list:\n component.api_methods[api_method_record.name].input_names.append(param.name)\n if param.name not in component.api_method_inputs:\n if param.default != inspect.Parameter.empty:\n if param.default is None:\n component.api_method_inputs[param.name] = 'flex'\n else:\n space = get_space_from_op(param.default)\n component.api_method_inputs[param.name] = space\n elif param.kind == inspect.Parameter.VAR_POSITIONAL:\n component.api_method_inputs[param.name] = '*flex'\n elif param.kind == inspect.Parameter.VAR_KEYWORD:\n component.api_method_inputs[param.name] = '**flex'\n else:\n component.api_method_inputs[param.name] = None","code_tokens":"","url":862825} +{"project_name":"triaquae\/triaquae","file_name":"base.py","full_name":"NoArgsCommand.handle_noargs","func_name":"handle_noargs","docstring":"Perform this command's actions.","docstring_tokens":"","code":"def handle_noargs(self, **options):\n \"\"\"\n Perform this command's actions.\n\n \"\"\"\n raise NotImplementedError()","code_tokens":"","url":358343} +{"project_name":"intel\/neural-compressor","file_name":"base_model.py","full_name":"BaseModel.graph_info","func_name":"graph_info","docstring":"Return a dict with content 'Node: Node_type'.","docstring_tokens":"","code":"@property\ndef graph_info(self):\n \"\"\"Return a dict with content 'Node: Node_type'.\"\"\"\n raise NotImplementedError","code_tokens":"","url":738859} +{"project_name":"jason718\/semi-sup","file_name":"custom_ops.py","full_name":"zero_pad","func_name":"zero_pad","docstring":"Zero pads `input` tensor to have `out_filter` number of filters.","docstring_tokens":"","code":"def zero_pad(inputs, in_filter, out_filter):\n \"\"\"Zero pads `input` tensor to have `out_filter` number of filters.\"\"\"\n outputs = tf.pad(inputs, [[0, 0], [0, 0], [0, 0], [(out_filter - in_filter) \/\/ 2, (out_filter - in_filter) \/\/ 2]])\n return outputs","code_tokens":"","url":343238} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"op_hint.py","full_name":"_LiteOperand.aggregate_and_return_name_for_input","func_name":"aggregate_and_return_name_for_input","docstring":"This adds the node(s) to out_graphdef and returns the input node name.","docstring_tokens":"","code":"def aggregate_and_return_name_for_input(self, out_graphdef):\n \"\"\"This adds the node(s) to out_graphdef and returns the input node name.\n\n Args:\n out_graphdef: A graphdef that is ready to have this input added.\n\n Returns:\n The the output that the stub should use as an input for this operand.\n\n Raises:\n RuntimeError: if the method is not implemented.\n \"\"\"\n del out_graphdef\n raise RuntimeError('Unimplemented abstract method.')","code_tokens":"","url":313800} +{"project_name":"hamza-murad\/AALU","file_name":"discovery_v1.py","full_name":"EnrichmentOptions.from_dict","func_name":"from_dict","docstring":"Initialize a EnrichmentOptions object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'EnrichmentOptions':\n \"\"\"Initialize a EnrichmentOptions object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['features', 'language', 'model']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class EnrichmentOptions: ' + ', '.join(bad_keys))\n if 'features' in _dict:\n args['features'] = NluEnrichmentFeatures._from_dict(_dict.get('features'))\n if 'language' in _dict:\n args['language'] = _dict.get('language')\n if 'model' in _dict:\n args['model'] = _dict.get('model')\n return cls(**args)","code_tokens":"","url":5560} +{"project_name":"xiongfengyan\/gcnn","file_name":"graph.py","full_name":"rescale_L","func_name":"rescale_L","docstring":"Rescale the Laplacian eigenvalues in [-1,1].","docstring_tokens":"","code":"def rescale_L(L, lmax=2):\n \"\"\"Rescale the Laplacian eigenvalues in [-1,1].\"\"\"\n (M, M) = L.shape\n I = scipy.sparse.identity(M, format='csr', dtype=L.dtype)\n L \/= lmax \/ 2\n L -= I\n return L","code_tokens":"","url":201355} +{"project_name":"voxel51\/fiftyone","file_name":"manager.py","full_name":"PlotManager.pop","func_name":"pop","docstring":"Removes the plot from this manager and returns it.","docstring_tokens":"","code":"def pop(self, name):\n \"\"\"Removes the plot from this manager and returns it.\n\n Args:\n name: the name of a plot\n\n Returns:\n the :class:`fiftyone.core.plots.base.ResponsivePlot`\n \"\"\"\n if name not in self._plots:\n raise ValueError(\"No plot with name '%s'\" % name)\n plot = self._plots.pop(name)\n self._aggs.pop(name, None)\n plot.disconnect()\n if not self._plots:\n self.disconnect()\n return plot","code_tokens":"","url":583630} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"image_test.py","full_name":"ImageModuleTest.test_fromstring__and_tostring","func_name":"test_fromstring__and_tostring","docstring":"Ensure methods tostring() and fromstring() are symmetric.","docstring_tokens":"","code":"def test_fromstring__and_tostring(self):\n \"\"\"Ensure methods tostring() and fromstring() are symmetric.\"\"\"\n\n def RotateRGBAtoARGB(str_buf):\n byte_buf = array.array('B', str_buf)\n num_quads = len(byte_buf) \/\/ 4\n for i in xrange_(num_quads):\n alpha = byte_buf[i * 4 + 3]\n byte_buf[i * 4 + 3] = byte_buf[i * 4 + 2]\n byte_buf[i * 4 + 2] = byte_buf[i * 4 + 1]\n byte_buf[i * 4 + 1] = byte_buf[i * 4 + 0]\n byte_buf[i * 4 + 0] = alpha\n return byte_buf.tostring()\n\n def RotateARGBtoRGBA(str_buf):\n byte_buf = array.array('B', str_buf)\n num_quads = len(byte_buf) \/\/ 4\n for i in xrange_(num_quads):\n alpha = byte_buf[i * 4 + 0]\n byte_buf[i * 4 + 0] = byte_buf[i * 4 + 1]\n byte_buf[i * 4 + 1] = byte_buf[i * 4 + 2]\n byte_buf[i * 4 + 2] = byte_buf[i * 4 + 3]\n byte_buf[i * 4 + 3] = alpha\n return byte_buf.tostring()\n test_surface = pygame.Surface((64, 256), flags=pygame.SRCALPHA, depth=32)\n for i in xrange_(256):\n for j in xrange_(16):\n intensity = j * 16 + 15\n test_surface.set_at((j + 0, i), (intensity, i, i, i))\n test_surface.set_at((j + 16, i), (i, intensity, i, i))\n test_surface.set_at((j + 32, i), (i, i, intensity, i))\n test_surface.set_at((j + 32, i), (i, i, i, intensity))\n self._assertSurfaceEqual(test_surface, test_surface, 'failing with identical surfaces')\n rgba_buf = pygame.image.tostring(test_surface, 'RGBA')\n rgba_buf = RotateARGBtoRGBA(RotateRGBAtoARGB(rgba_buf))\n test_rotate_functions = pygame.image.fromstring(rgba_buf, test_surface.get_size(), 'RGBA')\n self._assertSurfaceEqual(test_surface, test_rotate_functions, 'rotate functions are not symmetric')\n rgba_buf = pygame.image.tostring(test_surface, 'RGBA')\n argb_buf = RotateRGBAtoARGB(rgba_buf)\n test_from_argb_string = pygame.image.fromstring(argb_buf, test_surface.get_size(), 'ARGB')\n self._assertSurfaceEqual(test_surface, test_from_argb_string, '\"RGBA\" rotated to \"ARGB\" failed')\n argb_buf = pygame.image.tostring(test_surface, 'ARGB')\n rgba_buf = RotateARGBtoRGBA(argb_buf)\n test_to_argb_string = pygame.image.fromstring(rgba_buf, test_surface.get_size(), 'RGBA')\n self._assertSurfaceEqual(test_surface, test_to_argb_string, '\"ARGB\" rotated to \"RGBA\" failed')\n for fmt in ('ARGB', 'RGBA'):\n fmt_buf = pygame.image.tostring(test_surface, fmt)\n test_to_from_fmt_string = pygame.image.fromstring(fmt_buf, test_surface.get_size(), fmt)\n self._assertSurfaceEqual(test_surface, test_to_from_fmt_string, 'tostring\/fromstring functions are not symmetric with \"{}\" format'.format(fmt))","code_tokens":"","url":368997} +{"project_name":"RonMcKay\/OODRetrieval","file_name":"discover.py","full_name":"Discovery.color_pred","func_name":"color_pred","docstring":"When called colors the scatter in the main plot according to the predicted class color.","docstring_tokens":"","code":"def color_pred(self):\n \"\"\"When called colors the scatter in the main plot according to the predicted\n class color.\"\"\"\n self.basecolors = np.stack([tuple((i \/ 255.0 for i in self.pred_mapping[self.pred[ind]][1])) + (1.0,) for ind in range(self.basecolors.shape[0])])\n legend_elements = [Patch(color=tuple((i \/ 255.0 for i in self.pred_mapping[cl][1])) + (1.0,), label=self.pred_mapping[cl][0]) for cl in np.unique(self.pred).flatten()]\n self.fig_main.axes[0].legend(loc='upper left', handles=legend_elements, ncol=8, bbox_to_anchor=(0, 1.1))\n self.flush_colors()","code_tokens":"","url":756670} +{"project_name":"pandeyankit83\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"thinkstats2.py","full_name":"Beta.Mean","func_name":"Mean","docstring":"Computes the mean of this distribution.","docstring_tokens":"","code":"def Mean(self):\n \"\"\"Computes the mean of this distribution.\"\"\"\n return self.alpha \/ (self.alpha + self.beta)","code_tokens":"","url":19822} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"docs.py","full_name":"Library.exclude_symbols","func_name":"exclude_symbols","docstring":"Set of excluded symbols.","docstring_tokens":"","code":"@property\ndef exclude_symbols(self):\n \"\"\"Set of excluded symbols.\"\"\"\n return self._exclude_symbols","code_tokens":"","url":182465} +{"project_name":"guenthermi\/table-embeddings","file_name":"feature_preparation.py","full_name":"FeaturePreparation.create_mx_arrays","func_name":"create_mx_arrays","docstring":"Gets dgl_graph_node_ids for node_ids in train_sheets, valid_sheets, and test_sheets and construct vectors for ids and labels.","docstring_tokens":"","code":"def create_mx_arrays(self, dgl_graph, label_lookup, train_sheets, valid_sheets, test_sheets, downsampling=False):\n \"\"\"Gets dgl_graph_node_ids for node_ids in train_sheets, valid_sheets,\n and test_sheets and construct vectors for ids and labels.\n \"\"\"\n train_ids = []\n train_labels = []\n valid_ids = []\n valid_labels = []\n test_ids = []\n test_labels = []\n for (dgl_node_id, node_id) in enumerate(dgl_graph.ndata['node_id'].asnumpy()):\n attributes = self.node_attributes[node_id]\n if (attributes['filename'], attributes['sheetname']) in train_sheets:\n train_ids.append(dgl_node_id)\n train_labels.append(label_lookup[node_id])\n if (attributes['filename'], attributes['sheetname']) in valid_sheets:\n valid_ids.append(dgl_node_id)\n valid_labels.append(label_lookup[node_id])\n if (attributes['filename'], attributes['sheetname']) in test_sheets:\n test_ids.append(dgl_node_id)\n test_labels.append(label_lookup[node_id])\n if downsampling:\n (train_ids, train_labels) = self._downsampling(train_ids, train_labels, strategy='soft')\n weight_vector = self._get_class_weights(train_labels, method='equal')\n train_ids = nd.array(train_ids).astype(np.int64)\n valid_ids = nd.array(valid_ids).astype(np.int64)\n test_ids = nd.array(test_ids).astype(np.int64)\n train_labels = nd.array(train_labels)\n valid_labels = nd.array(valid_labels)\n test_labels = nd.array(test_labels)\n return (train_ids, train_labels, valid_ids, valid_labels, test_ids, test_labels, weight_vector)","code_tokens":"","url":365125} +{"project_name":"flavioschneider\/rl-transfer-","file_name":"epsilon_greedy_policy.py","full_name":"EpsilonGreedyPolicy.get_actions","func_name":"get_actions","docstring":"Get actions from this policy for the input observations.","docstring_tokens":"","code":"def get_actions(self, observations):\n \"\"\"Get actions from this policy for the input observations.\n\n Args:\n observations (numpy.ndarray): Observation from the environment.\n\n Returns:\n np.ndarray: Actions with noise.\n List[dict]: Arbitrary policy state information (agent_info).\n\n \"\"\"\n (opt_actions, _) = self.policy.get_actions(observations)\n for (itr, _) in enumerate(opt_actions):\n if np.random.random() < self._epsilon():\n opt_actions[itr] = self._action_space.sample()\n self._total_env_steps += 1\n return (opt_actions, dict())","code_tokens":"","url":861214} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"test_scalar_inference.py","full_name":"test_inference_required_crossval_runs","func_name":"test_inference_required_crossval_runs","docstring":"Test the flags for running full inference on the test set, for models that are trained in crossval mode.","docstring_tokens":"","code":"def test_inference_required_crossval_runs() -> None:\n \"\"\"\n Test the flags for running full inference on the test set, for models that are trained in crossval mode.\n \"\"\"\n classification_model = GlaucomaPublic()\n classification_model.number_of_cross_validation_splits = 2\n segmentation_model = SegmentationModelBase(should_validate=False)\n segmentation_model.number_of_cross_validation_splits = 2\n assert classification_model.perform_cross_validation\n assert segmentation_model.perform_cross_validation\n assert classification_model.is_inference_required(model_proc=ModelProcessing.DEFAULT, data_split=ModelExecutionMode.TEST)\n assert not segmentation_model.is_inference_required(model_proc=ModelProcessing.DEFAULT, data_split=ModelExecutionMode.TEST)\n classification_model.inference_on_test_set = False\n assert not classification_model.is_inference_required(model_proc=ModelProcessing.DEFAULT, data_split=ModelExecutionMode.TEST)","code_tokens":"","url":613740} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"gbdt_batch.py","full_name":"GradientBoostedDecisionTreeModel.predict","func_name":"predict","docstring":"Returns predictions given the features and mode.","docstring_tokens":"","code":"def predict(self, mode):\n \"\"\"Returns predictions given the features and mode.\n\n Args:\n mode: Mode the graph is running in (train|predict|eval).\n\n Returns:\n A dict of predictions tensors.\n\n Raises:\n ValueError: if features is not valid.\n \"\"\"\n input_deps = self._dense_floats + self._sparse_float_indices + self._sparse_int_indices\n if not input_deps:\n raise ValueError('No input tensors for prediction.')\n ensemble_stamp = model_ops.tree_ensemble_stamp_token(self._ensemble_handle)\n if self._ensemble_handle.device != input_deps[0].device:\n with ops.name_scope('local_ensemble', 'TreeEnsembleVariable') as name:\n local_ensemble_handle = gen_model_ops.decision_tree_ensemble_resource_handle_op(name=name)\n create_op = gen_model_ops.create_tree_ensemble_variable(local_ensemble_handle, stamp_token=-1, tree_ensemble_config='')\n with ops.control_dependencies([create_op]):\n local_stamp = model_ops.tree_ensemble_stamp_token(local_ensemble_handle)\n\n def _refresh_local_ensemble_fn():\n with ops.control_dependencies([input_deps[0]]):\n (ensemble_stamp, serialized_model) = model_ops.tree_ensemble_serialize(self._ensemble_handle)\n with ops.control_dependencies([create_op]):\n return (model_ops.tree_ensemble_deserialize(local_ensemble_handle, stamp_token=ensemble_stamp, tree_ensemble_config=serialized_model), ensemble_stamp)\n (refresh_local_ensemble, ensemble_stamp) = control_flow_ops.cond(math_ops.not_equal(ensemble_stamp, local_stamp), _refresh_local_ensemble_fn, lambda : (control_flow_ops.no_op(), ensemble_stamp))\n with ops.control_dependencies([refresh_local_ensemble]):\n return self._predict_and_return_dict(local_ensemble_handle, ensemble_stamp, mode)\n else:\n with ops.device(self._ensemble_handle.device):\n return self._predict_and_return_dict(self._ensemble_handle, ensemble_stamp, mode)","code_tokens":"","url":312592} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"expression.py","full_name":"Select.having","func_name":"having","docstring":"return a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any.","docstring_tokens":"","code":"@_generative\ndef having(self, having):\n \"\"\"return a new select() construct with the given expression added to\n its HAVING clause, joined to the existing clause via AND, if any.\n\n \"\"\"\n self.append_having(having)","code_tokens":"","url":481669} +{"project_name":"rneilson\/rngru","file_name":"rn_rnn_model.py","full_name":"ModelParams.traintime","func_name":"traintime","docstring":"Prints time for batch training step (default size 16).","docstring_tokens":"","code":"def traintime(self, dataset, batchsize=16, pos=0, init_state=None):\n \"\"\"Prints time for batch training step (default size 16).\"\"\"\n if not self._built_t:\n self._build_t()\n start_state = init_state if isinstance(init_state, np.ndarray) else self.freshstate(batchsize)\n (xbatch, ybatch) = dataset.batch(pos, batchsize)\n time1 = time.time()\n self.train_step_bat(xbatch, ybatch, start_state, self.hyper.learnrate, self.hyper.decay, self.hyper.regcost)\n time2 = time.time()\n stdout.write('Time for SGD\/RMS learning batch of {0:d} sequences, {1:d} chars each: {2:.4f} ms\\n'.format(xbatch.shape[1], xbatch.shape[0], (time2 - time1) * 1000.0))\n time1 = time.time()\n self.err_bat(xbatch, ybatch, start_state, self.hyper.regcost)\n time2 = time.time()\n stdout.write('Time for loss calculation step of {0:d} chars: {1:.4f} ms\\n'.format(xbatch.shape[0], (time2 - time1) * 1000.0))","code_tokens":"","url":324937} +{"project_name":"rudranil723\/mini-main","file_name":"_regex_core.py","full_name":"compile_repl_group","func_name":"compile_repl_group","docstring":"Compiles a replacement template group reference.","docstring_tokens":"","code":"def compile_repl_group(source, pattern):\n \"\"\"Compiles a replacement template group reference.\"\"\"\n source.expect('<')\n name = parse_name(source, True, True)\n source.expect('>')\n if name.isdigit():\n index = int(name)\n if not 0 <= index <= pattern.groups:\n raise error('invalid group reference', source.string, source.pos)\n return index\n try:\n return pattern.groupindex[name]\n except KeyError:\n raise IndexError('unknown group')","code_tokens":"","url":269832} +{"project_name":"QData\/deepWordBug","file_name":"cache.py","full_name":"ICache.purge","func_name":"purge","docstring":"Clears all data from the cache.","docstring_tokens":"","code":"def purge():\n \"\"\"\n Clears all data from the cache.\n\n \"\"\"","code_tokens":"","url":541605} +{"project_name":"shellerbrand\/machine-learning-for-artistic-style","file_name":"learning.py","full_name":"precompute_gram_matrices","func_name":"precompute_gram_matrices","docstring":"Pre-computes the Gram matrices on a given image.","docstring_tokens":"","code":"def precompute_gram_matrices(image, final_endpoint='fc8'):\n \"\"\"Pre-computes the Gram matrices on a given image.\n\n Args:\n image: 4-D tensor. Input (batch of) image(s).\n final_endpoint: str, name of the final layer to compute Gram matrices for.\n Defaults to 'fc8'.\n\n Returns:\n dict mapping layer names to their corresponding Gram matrices.\n \"\"\"\n with tf.Session() as session:\n end_points = vgg.vgg_16(image, final_endpoint=final_endpoint)\n tf.train.Saver(slim.get_variables('vgg_16')).restore(session, vgg.checkpoint_file())\n return dict([(key, gram_matrix(value).eval()) for (key, value) in end_points.iteritems()])","code_tokens":"","url":620693} +{"project_name":"rudranil723\/mini-main","file_name":"pgraster.py","full_name":"to_pgraster","func_name":"to_pgraster","docstring":"Convert a GDALRaster into PostGIS Raster format.","docstring_tokens":"","code":"def to_pgraster(rast):\n \"\"\"\n Convert a GDALRaster into PostGIS Raster format.\n \"\"\"\n rasterheader = (1, 0, len(rast.bands), rast.scale.x, rast.scale.y, rast.origin.x, rast.origin.y, rast.skew.x, rast.skew.y, rast.srs.srid, rast.width, rast.height)\n result = pack(POSTGIS_HEADER_STRUCTURE, rasterheader)\n for band in rast.bands:\n structure = 'B' + GDAL_TO_STRUCT[band.datatype()]\n pixeltype = GDAL_TO_POSTGIS[band.datatype()]\n if band.nodata_value is not None:\n pixeltype += 64\n bandheader = pack(structure, (pixeltype, band.nodata_value or 0))\n result += bandheader + band.data(as_memoryview=True)\n return result.hex()","code_tokens":"","url":315031} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"handlers.py","full_name":"BaseHandler.log_exception","func_name":"log_exception","docstring":"Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format.","docstring_tokens":"","code":"def log_exception(self, exc_info):\n \"\"\"Log the 'exc_info' tuple in the server log\n\n Subclasses may override to retarget the output or change its format.\n \"\"\"\n try:\n from traceback import print_exception\n stderr = self.get_stderr()\n print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr)\n stderr.flush()\n finally:\n exc_info = None","code_tokens":"","url":284540} +{"project_name":"RasaHQ\/rasa_core","file_name":"domain.py","full_name":"Domain.input_state_map","func_name":"input_state_map","docstring":"Provides a mapping from state names to indices.","docstring_tokens":"","code":"@utils.lazyproperty\ndef input_state_map(self):\n \"\"\"Provides a mapping from state names to indices.\"\"\"\n return {f: i for (i, f) in enumerate(self.input_states)}","code_tokens":"","url":838174} +{"project_name":"2arian3\/Artificial-Intelligence","file_name":"search.py","full_name":"UndirectedGraph","func_name":"UndirectedGraph","docstring":"Build a Graph where every edge (including future ones) goes both ways.","docstring_tokens":"","code":"def UndirectedGraph(graph_dict=None):\n \"\"\"Build a Graph where every edge (including future ones) goes both ways.\"\"\"\n return Graph(graph_dict=graph_dict, directed=False)","code_tokens":"","url":117762} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"plugins.py","full_name":"BoostPlugin.do_boost","func_name":"do_boost","docstring":"This filter finds BoostNodes and applies the boost to the previous node.","docstring_tokens":"","code":"def do_boost(self, parser, group):\n \"\"\"This filter finds BoostNodes and applies the boost to the previous\n node.\n \"\"\"\n newgroup = group.empty_copy()\n for node in group:\n if isinstance(node, syntax.GroupNode):\n node = self.do_boost(parser, node)\n elif isinstance(node, self.BoostNode):\n if newgroup and newgroup[-1].has_boost:\n newgroup[-1].set_boost(node.boost)\n continue\n else:\n node = syntax.to_word(node)\n newgroup.append(node)\n return newgroup","code_tokens":"","url":526918} +{"project_name":"cycraig\/MP-DQN","file_name":"qpamdp.py","full_name":"QPAMDPAgent.log_gradient","func_name":"log_gradient","docstring":"Returns the log gradient for the entire policy.","docstring_tokens":"","code":"def log_gradient(self, state, action, param):\n \"\"\" Returns the log gradient for the entire policy. \"\"\"\n grad = np.zeros((0,))\n for i in range(self.num_actions):\n elems = self.parameter_weights[i].size\n if i == action:\n parameter_grad = self._log_parameter_gradient(state, i, param)\n grad = np.append(grad, parameter_grad)\n else:\n grad = np.append(grad, np.zeros((elems,)))\n return grad","code_tokens":"","url":656316} +{"project_name":"aisingapore\/PeekingDuck","file_name":"track.py","full_name":"STrack.multi_predict","func_name":"multi_predict","docstring":"Runs the vectorized version of Kalman filter prediction step.","docstring_tokens":"","code":"@staticmethod\ndef multi_predict(stracks: List['STrack']) -> None:\n \"\"\"Runs the vectorized version of Kalman filter prediction step.\n\n Args:\n stracks (List[STrack]): List of STrack.\n \"\"\"\n if not stracks:\n return\n multi_mean = np.asarray([st.mean.copy() for st in stracks])\n multi_covariance = np.asarray([st.covariance for st in stracks])\n for (i, strack) in enumerate(stracks):\n if strack.state != TrackState.TRACKED:\n multi_mean[i][7] = 0\n (multi_mean, multi_covariance) = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)\n for (i, (mean, cov)) in enumerate(zip(multi_mean, multi_covariance)):\n stracks[i].mean = mean\n stracks[i].covariance = cov","code_tokens":"","url":766937} +{"project_name":"flairNLP\/flair","file_name":"data.py","full_name":"Dictionary.get_idx_for_item","func_name":"get_idx_for_item","docstring":"Returns the ID of the string, otherwise 0.","docstring_tokens":"","code":"def get_idx_for_item(self, item: str) -> int:\n \"\"\"Returns the ID of the string, otherwise 0.\n\n Args:\n item: string for which ID is requested\n\n Returns: ID of string, otherwise 0\n \"\"\"\n item_encoded = item.encode('utf-8')\n if item_encoded in self.item2idx:\n return self.item2idx[item_encoded]\n elif self.add_unk:\n return 0\n else:\n log.error(f\"The string '{item}' is not in dictionary! Dictionary contains only: {self.get_items()}\")\n log.error('You can create a Dictionary that handles unknown items with an -key by setting add_unk = True in the construction.')\n raise IndexError","code_tokens":"","url":584734} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"calendar.py","full_name":"HTMLCalendar.formatweekday","func_name":"formatweekday","docstring":"Return a weekday name as a table header.","docstring_tokens":"","code":"def formatweekday(self, day):\n \"\"\"\n Return a weekday name as a table header.\n \"\"\"\n return '%s<\/th>' % (self.cssclasses[day], day_abbr[day])","code_tokens":"","url":280153} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"math2html.py","full_name":"MacroFunction.parsemandatory","func_name":"parsemandatory","docstring":"Parse a number of mandatory parameters.","docstring_tokens":"","code":"def parsemandatory(self, pos, number):\n \"\"\"Parse a number of mandatory parameters.\"\"\"\n for index in range(number):\n parameter = self.parsemacroparameter(pos, number - index)\n if not parameter:\n return\n self.values.append(parameter)","code_tokens":"","url":395385} +{"project_name":"tensorflow\/quantum","file_name":"op_serializer_test.py","full_name":"OpSerializerTest.test_to_proto_unsupported_type","func_name":"test_to_proto_unsupported_type","docstring":"Test proto unsupported types errors.","docstring_tokens":"","code":"@parameterized.parameters([cirq.GridQubit(1, 2), cirq.LineQubit(4)])\ndef test_to_proto_unsupported_type(self, q):\n \"\"\"Test proto unsupported types errors.\"\"\"\n serializer = op_serializer.GateOpSerializer(gate_type=GateWithProperty, serialized_gate_id='my_gate', args=[op_serializer.SerializingArg(serialized_name='my_val', serialized_type=bytes, op_getter='val')])\n with self.assertRaisesRegex(ValueError, expected_regex='bytes'):\n serializer.to_proto(GateWithProperty(b's')(q))","code_tokens":"","url":834925} +{"project_name":"kamal-rahimi\/SentenceCorrection","file_name":"process_sentence.py","full_name":"process_sentence","func_name":"process_sentence","docstring":"analyzes the inout sentnces and reorders the word to form a senetnces which has the highest liklihood in the longuage model.","docstring_tokens":"","code":"def process_sentence(model_name, input_sentence, window_size, max_sentence_words=12):\n \"\"\" analyzes the inout sentnces and reorders the word to form a senetnces which\n has the highest liklihood in the longuage model.\n\n Args:\n model: trained longuage model object\n word2id: dictionary to convert from word to id\n id2word: dictionary to convert from id to word\n window_size: word reordering search window size\n input_sentnce (text): input sentnce\n max_sentence_words: maximum number of words in a senetnce\n Returns:\n most_likely_sentence: the word reordred senetnce that has highes liklihood in the longuage model\n most_likely_word_order_prob: liklihood of the reordred sentence\n \"\"\"\n model_path = '.\/models\/' + model_name + '_model.h5'\n meta_data_path = '.\/models\/' + model_name + '_metadata.pickle'\n if os.path.isfile(model_path) == True and os.path.isfile(model_path) == True:\n model = load_model(model_path)\n with open(meta_data_path, 'rb') as f:\n (word2id, id2word) = pickle.load(f)\n else:\n print('No model with name \"%s\" is trained yet' % model_name)\n return\n input_sentence = strip_punctuations(input_sentence)\n input_sentence = input_sentence.lower()\n sentence_words = input_sentence.split()\n sentence_words_id = [word2id[word] if word in word2id else word2id[''] for word in sentence_words]\n full_sentence_words_id = [word2id['']] + sentence_words_id + [word2id['']]\n (inout_word_order_prob, _) = analyze_sequence(model, full_sentence_words_id, max_sentence_words)\n sentence_words_id_permutations = []\n num_iterations = max(1, len(sentence_words_id) - window_size + 1)\n for i in range(0, num_iterations):\n words_id_permutations = [sentence_words_id[0:i] + list(l) for l in permutations(sentence_words_id[i:window_size + i])]\n num_permutations = len(words_id_permutations)\n sentence_size = len(words_id_permutations[0])\n words_id_permutations_prob = []\n for words_id_order_index in range(0, num_permutations):\n words_id_order = list(words_id_permutations[words_id_order_index])\n words_id_order = [word2id['']] + words_id_order\n if i == num_iterations - 1:\n words_id_order = words_id_order + [word2id['']]\n (p_sentence, p_words) = analyze_sequence(model, words_id_order, max_sentence_words)\n words_id_permutations_prob.append(p_sentence)\n most_likely_word_order_index = np.argmax(words_id_permutations_prob)\n most_likely_word_order_prob = words_id_permutations_prob[most_likely_word_order_index]\n most_likely_words_id_order = words_id_permutations[most_likely_word_order_index]\n sentence_words_id = most_likely_words_id_order + sentence_words_id[window_size + i:]\n k.clear_session()\n most_likely_words_order = [id2word[id] for id in sentence_words_id]\n most_likely_sentence = ' '.join(most_likely_words_order)\n return (inout_word_order_prob, most_likely_sentence, most_likely_word_order_prob)","code_tokens":"","url":343867} +{"project_name":"Eric3911\/OpenAGI","file_name":"audio_to_text_dataset.py","full_name":"get_concat_bpe_dataset","func_name":"get_concat_bpe_dataset","docstring":"Instantiates a ContactDataset based on several Byte Pair Encoding \/ Word Piece Encoding based AudioToBPEDatasets.","docstring_tokens":"","code":"def get_concat_bpe_dataset(config: dict, tokenizer: 'TokenizerSpec', global_rank: int, world_size: int, augmentor: Optional['AudioAugmentor']=None) -> ConcatDataset:\n \"\"\"\n Instantiates a ContactDataset based on several Byte Pair Encoding \/ Word Piece Encoding based AudioToBPEDatasets.\n\n Args:\n config: Config of the AudioToBPEDataset.\n tokenizer: An instance of a TokenizerSpec object.\n global_rank: Global rank of this device.\n world_size: Global world size in the training method.\n augmentor: Optional AudioAugmentor object for augmentations on audio data.\n\n Returns:\n An instance of ConcatDataset containing several instances of AudioToBPEDataset.\n \"\"\"\n manifest_filepaths = config['manifest_filepath']\n datasets = []\n if len(manifest_filepaths) == 1 and (not isinstance(manifest_filepaths[0], str)):\n logging.info(f'removing an extra nesting level from {manifest_filepaths}')\n manifest_filepaths = config['manifest_filepath'][0]\n for manifest_filepath in manifest_filepaths:\n conf = copy.deepcopy(config)\n conf['manifest_filepath'] = manifest_filepath\n dataset = get_bpe_dataset(config=conf, tokenizer=tokenizer, augmentor=augmentor)\n datasets.append(dataset)\n dataset = ConcatDataset(datasets, sampling_technique=config.get('concat_sampling_technique', 'temperature'), sampling_temperature=config.get('concat_sampling_temperature', 5), sampling_scale=config.get('concat_sampling_scale', 1), sampling_probabilities=config.get('concat_sampling_probabilities', None), shuffle=config.get('concat_shuffle', True), seed=config.get('concat_sampling_seed', None), global_rank=global_rank, world_size=world_size)\n return dataset","code_tokens":"","url":272247} +{"project_name":"rudranil723\/mini-main","file_name":"__init__.py","full_name":"VendorImporter.find_spec","func_name":"find_spec","docstring":"Return a module spec for vendored names.","docstring_tokens":"","code":"def find_spec(self, fullname, path=None, target=None):\n \"\"\"Return a module spec for vendored names.\"\"\"\n return importlib.util.spec_from_loader(fullname, self) if self._module_matches_namespace(fullname) else None","code_tokens":"","url":269246} +{"project_name":"TJU-DRL-LAB\/AI-Optimizer","file_name":"self_play.py","full_name":"MCTS.ucb_score","func_name":"ucb_score","docstring":"The score for a node is based on its value, plus an exploration bonus based on the prior.","docstring_tokens":"","code":"def ucb_score(self, parent, child, min_max_stats):\n \"\"\"\n The score for a node is based on its value, plus an exploration bonus based on the prior.\n \"\"\"\n pb_c = math.log((parent.visit_count + self.config.pb_c_base + 1) \/ self.config.pb_c_base) + self.config.pb_c_init\n pb_c *= math.sqrt(parent.visit_count) \/ (child.visit_count + 1)\n prior_score = pb_c * child.prior\n if child.visit_count > 0:\n value_score = min_max_stats.normalize(child.reward + self.config.discount * (child.value() if len(self.config.players) == 1 else -child.value()))\n else:\n value_score = 0\n return prior_score + value_score","code_tokens":"","url":70378} +{"project_name":"intel\/neural-compressor","file_name":"criterion.py","full_name":"KnowledgeDistillationLoss.loss_cal_sloss","func_name":"loss_cal_sloss","docstring":"Calculate all losses between student model and teacher model.","docstring_tokens":"","code":"def loss_cal_sloss(self, student_outputs, teacher_outputs, student_loss):\n \"\"\"Calculate all losses between student model and teacher model.\n\n Args:\n student_outputs (tensor): student outputs\n teacher_outputs (tensor): teacher outputs\n student_loss (tensor): student loss\n\n Returns:\n tensor: loss\n \"\"\"\n if self.loss_weights[0] > 0:\n origin_loss = student_loss\n else:\n origin_loss = 0\n if self.loss_weights[1] > 0:\n student_out_ = student_outputs \/ self.temperature\n teacher_out_ = teacher_outputs \/ self.temperature\n distillation_loss = self.teacher_student_loss_cal(student_out_, teacher_out_)\n distillation_loss *= self.temperature ** 2\n else:\n distillation_loss = 0\n self.loss = origin_loss * self.loss_weights[0] + distillation_loss * self.loss_weights[1]\n return self.loss","code_tokens":"","url":738436} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"_bootstrap_external.py","full_name":"SourceFileLoader.path_stats","func_name":"path_stats","docstring":"Return the metadata for the path.","docstring_tokens":"","code":"def path_stats(self, path):\n \"\"\"Return the metadata for the path.\"\"\"\n st = _path_stat(path)\n return {'mtime': st.st_mtime, 'size': st.st_size}","code_tokens":"","url":282952} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"task.py","full_name":"Task.getObservation","func_name":"getObservation","docstring":"A filtered mapping to getSample of the underlying environment.","docstring_tokens":"","code":"def getObservation(self):\n \"\"\" A filtered mapping to getSample of the underlying environment. \"\"\"\n sensors = self.env.getSensors()\n if self.sensor_limits:\n sensors = self.normalize(sensors)\n return sensors","code_tokens":"","url":722544} +{"project_name":"sankalpapharande\/Artificial-Intelligence-Programming-Assignments","file_name":"sudoku.py","full_name":"board_to_string","func_name":"board_to_string","docstring":"Helper function to convert board dictionary to string for writing.","docstring_tokens":"","code":"def board_to_string(board):\n \"\"\"Helper function to convert board dictionary to string for writing.\"\"\"\n ordered_vals = []\n for r in ROW:\n for c in COL:\n ordered_vals.append(str(board[r + c]))\n return ''.join(ordered_vals)","code_tokens":"","url":91380} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"lazy_wheel.py","full_name":"LazyZipOverHTTP.tell","func_name":"tell","docstring":"Return the current possition.","docstring_tokens":"","code":"def tell(self):\n \"\"\"Return the current possition.\"\"\"\n return self._file.tell()","code_tokens":"","url":454255} +{"project_name":"georghess\/voxel-mae","file_name":"create_data.py","full_name":"waymo_data_prep","func_name":"waymo_data_prep","docstring":"Prepare the info file for waymo dataset.","docstring_tokens":"","code":"def waymo_data_prep(root_path, info_prefix, version, out_dir, workers, max_sweeps=5):\n \"\"\"Prepare the info file for waymo dataset.\n\n Args:\n root_path (str): Path of dataset root.\n info_prefix (str): The prefix of info filenames.\n out_dir (str): Output directory of the generated info file.\n workers (int): Number of threads to be used.\n max_sweeps (int): Number of input consecutive frames. Default: 5 Here we store pose information of these frames for later use.\n \"\"\"\n from tools.data_converter import waymo_converter as waymo\n splits = ['training', 'validation', 'testing']\n for (i, split) in enumerate(splits):\n load_dir = osp.join(root_path, 'waymo_format', split)\n if split == 'validation':\n save_dir = osp.join(out_dir, 'kitti_format', 'training')\n else:\n save_dir = osp.join(out_dir, 'kitti_format', split)\n converter = waymo.Waymo2KITTI(load_dir, save_dir, prefix=str(i), workers=workers, test_mode=split == 'test')\n out_dir = osp.join(out_dir, 'kitti_format')\n kitti.create_waymo_info_file(out_dir, info_prefix, max_sweeps=max_sweeps)\n create_groundtruth_database('WaymoDataset', out_dir, info_prefix, f'{out_dir}\/{info_prefix}_infos_train.pkl', relative_path=False, with_mask=False)","code_tokens":"","url":380804} +{"project_name":"enlite-ai\/maze","file_name":"external_core_env.py","full_name":"ExternalCoreEnv.set_actor_id","func_name":"set_actor_id","docstring":"Hook for the agent deployment to set actor_id before querying execution.","docstring_tokens":"","code":"def set_actor_id(self, new_value: ActorID):\n \"\"\"Hook for the agent deployment to set actor_id before querying execution.\"\"\"\n self._actor_id = new_value","code_tokens":"","url":646566} +{"project_name":"Ashwin-Ravi\/Deep-Learning-A-Z-Udemy","file_name":"minisom.py","full_name":"MiniSom.activation_response","func_name":"activation_response","docstring":"Returns a matrix where the element i,j is the number of times that the neuron i,j have been winner.","docstring_tokens":"","code":"def activation_response(self, data):\n \"\"\"\n Returns a matrix where the element i,j is the number of times\n that the neuron i,j have been winner.\n \"\"\"\n a = zeros((self.weights.shape[0], self.weights.shape[1]))\n for x in data:\n a[self.winner(x)] += 1\n return a","code_tokens":"","url":127443} +{"project_name":"dojoteef\/dvae","file_name":"util.py","full_name":"create_reconstruction_image","func_name":"create_reconstruction_image","docstring":"Given the current batch and the reconstructed p(x|z), this function creates an image tensor containing tiled input and reconstructed instances.","docstring_tokens":"","code":"def create_reconstruction_image(input, reconstruction, batch_size):\n \"\"\" Given the current batch and the reconstructed p(x|z), this function creates an image tensor containing\n tiled input and reconstructed instances.\n\n Args:\n input: a tensor containing vectorized instances (x) in each row.\n reconstruction: a tensor containing vectorized reconstructed instances using p(x|z) in each row.\n batch_size: the number of rows in input or reconstruction tensors.\n\n Returns:\n image: containing tiled input and reconstruction images.\n \"\"\"\n assert input.get_shape().ndims == 2, 'input should be 2D vectorized images.'\n assert reconstruction.get_shape().ndims == 2, 'reconstruction should be 2D vectorized images.'\n num_input = input.get_shape().as_list()[1]\n image_size = int(np.sqrt(num_input))\n shape = [batch_size, image_size, image_size]\n original = tf.cast(255 * tf.reshape(input, shape), tf.uint8)\n recon = tf.cast(255 * tf.reshape(reconstruction, shape), tf.uint8)\n n = int(np.floor(np.sqrt(batch_size)))\n original = tf.slice(original, [0, 0, 0], [n * n, -1, -1])\n recon = tf.slice(recon, [0, 0, 0], [n * n, -1, -1])\n original = tile_image_tf(original, n, n, image_size, image_size)\n recon = tile_image_tf(recon, n, n, image_size, image_size)\n image = tf.concat(axis=1, values=[original, recon])\n return image","code_tokens":"","url":554890} +{"project_name":"quantumiracle\/Benchmark-Efficient-Reinforcement--with-Demonstrations","file_name":"box2d_viewer.py","full_name":"PygameDraw.DrawSolidCircle","func_name":"DrawSolidCircle","docstring":"Draw a solid circle given the center, radius, axis of orientation and color.","docstring_tokens":"","code":"def DrawSolidCircle(self, center, radius, axis, color):\n \"\"\"\n Draw a solid circle given the center, radius, axis of orientation and\n color.\n \"\"\"\n radius *= self.zoom\n if radius < 1:\n radius = 1\n else:\n radius = int(radius)\n pygame.draw.circle(self.surface, (color \/ 2).bytes + [127], center, radius, 0)\n pygame.draw.circle(self.surface, color.bytes, center, radius, 1)\n pygame.draw.aaline(self.surface, (255, 0, 0), center, (center[0] - radius * axis[0], center[1] + radius * axis[1]))","code_tokens":"","url":433594} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"sequence_layers.py","full_name":"SequenceLayerBase.is_training","func_name":"is_training","docstring":"Returns True if the layer is created for training stage.","docstring_tokens":"","code":"def is_training(self):\n \"\"\"Returns True if the layer is created for training stage.\"\"\"\n return self._labels_one_hot is not None","code_tokens":"","url":14639} +{"project_name":"chainer\/chainer","file_name":"model.py","full_name":"VGG16FeatureExtractor.forward","func_name":"forward","docstring":"Batch of images to image features.","docstring_tokens":"","code":"def forward(self, imgs):\n \"\"\"Batch of images to image features.\"\"\"\n img_feats = self.cnn(imgs, [self.cnn_layer_name])[self.cnn_layer_name]\n return img_feats","code_tokens":"","url":477665} +{"project_name":"deepmind\/acme","file_name":"mpo.py","full_name":"compute_nonparametric_kl_from_normalized_weights","func_name":"compute_nonparametric_kl_from_normalized_weights","docstring":"Estimate the actualized KL between the non-parametric and target policies.","docstring_tokens":"","code":"def compute_nonparametric_kl_from_normalized_weights(normalized_weights: tf.Tensor) -> tf.Tensor:\n \"\"\"Estimate the actualized KL between the non-parametric and target policies.\"\"\"\n num_action_samples = tf.cast(normalized_weights.shape[0], tf.float32)\n integrand = tf.math.log(num_action_samples * normalized_weights + 1e-08)\n return tf.reduce_sum(normalized_weights * integrand, axis=0)","code_tokens":"","url":7882} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"attention_utils.py","full_name":"prepare_attention","func_name":"prepare_attention","docstring":"Prepare keys\/values\/functions for attention.","docstring_tokens":"","code":"def prepare_attention(attention_states, attention_option, num_units, reuse=None):\n \"\"\"Prepare keys\/values\/functions for attention.\n\n Args:\n attention_states: hidden states to attend over.\n attention_option: how to compute attention, either \"luong\" or \"bahdanau\".\n num_units: hidden state dimension.\n reuse: whether to reuse variable scope.\n\n Returns:\n attention_keys: to be compared with target states.\n attention_values: to be used to construct context vectors.\n attention_score_fn: to compute similarity between key and target states.\n attention_construct_fn: to build attention states.\n \"\"\"\n with tf.variable_scope('attention_keys', reuse=reuse) as scope:\n attention_keys = tf.contrib.layers.linear(attention_states, num_units, biases_initializer=None, scope=scope)\n attention_values = attention_states\n attention_score_fn = _create_attention_score_fn('attention_score', num_units, attention_option, reuse)\n attention_construct_fn = _create_attention_construct_fn('attention_construct', num_units, attention_score_fn, reuse)\n return (attention_keys, attention_values, attention_score_fn, attention_construct_fn)","code_tokens":"","url":757925} +{"project_name":"rishab-sharma\/object_detection","file_name":"base_model.py","full_name":"BaseModel.save","func_name":"save","docstring":"Save the trained model.","docstring_tokens":"","code":"def save(self, sess):\n \"\"\" Save the trained model. \"\"\"\n print('Saving model to %s' % self.save_dir)\n self.saver.save(sess, self.save_dir, self.global_step)","code_tokens":"","url":744835} +{"project_name":"QData\/deepWordBug","file_name":"math2html.py","full_name":"LabelFunction.process","func_name":"process","docstring":"Add an anchor with the label contents.","docstring_tokens":"","code":"def process(self):\n \"\"\"Add an anchor with the label contents.\"\"\"\n self.type = 'font'\n self.label = Label().create(' ', self.key, type='eqnumber')\n self.contents = [self.label]\n Label.names[self.key] = self.label","code_tokens":"","url":542587} +{"project_name":"matsu0228\/nlp-jp","file_name":"events.py","full_name":"EventManager.unregister","func_name":"unregister","docstring":"Remove a callback from the given event.","docstring_tokens":"","code":"def unregister(self, event, function):\n \"\"\"Remove a callback from the given event.\"\"\"\n self.callbacks[event].remove(function)","code_tokens":"","url":786606} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"depth_utils.py","full_name":"get_camera_matrix","func_name":"get_camera_matrix","docstring":"Returns a camera matrix from image size and fov.","docstring_tokens":"","code":"def get_camera_matrix(width, height, fov):\n \"\"\"Returns a camera matrix from image size and fov.\"\"\"\n xc = (width - 1.0) \/ 2.0\n zc = (height - 1.0) \/ 2.0\n f = width \/ 2.0 \/ np.tan(np.deg2rad(fov \/ 2.0))\n camera_matrix = utils.Foo(xc=xc, zc=zc, f=f)\n return camera_matrix","code_tokens":"","url":749470} +{"project_name":"AlperHuseyn\/artificial-intelligence-and-machine-learning-with-python","file_name":"covid-nlp-sentiment.py","full_name":"train_evaluate_save_model","func_name":"train_evaluate_save_model","docstring":"Train, evaluate, and save the covid-nlp prediction model.","docstring_tokens":"","code":"def train_evaluate_save_model(X_train, y_train, X_test, y_test, X_to_predict, name='model', epochs=5):\n \"\"\"\nTrain, evaluate, and save the covid-nlp prediction model.\n\nArgs:\n X_train (pandas.DataFrame): Input features for training.\n y_train (pandas.Series): Output values for training.\n X_test (pandas.DataFrame): Input features for testing.\n y_test (pandas.Series): Output values for testing.\n X_to_predict (numpy.ndarray): Input features for predictions.\n name (str): Name for saving the model.\n epochs (int): Number of training epochs.\n\nReturns:\n float: categorical accuracy of the model on the test dataset.\n numpy.ndarray: Predicted covid-nlp-sentiment.\n\"\"\"\n model = create_covid_model(input_dim=X_train.shape[1], name='Covid-nlp')\n hist = model.fit(X_train, y_train, epochs=epochs, validation_split=0.2)\n (loss, category_accuracy) = model.evaluate(X_test, y_test, verbose=0)\n predictions = model.predict(X_to_predict)\n model.save(f'{name}.h5')\n return (hist, loss, category_accuracy, predictions)","code_tokens":"","url":36161} +{"project_name":"keras-team\/keras-cv","file_name":"backbone.py","full_name":"Backbone.presets_with_weights","func_name":"presets_with_weights","docstring":"Dictionary of preset names and configs that include weights.","docstring_tokens":"","code":"@classproperty\ndef presets_with_weights(cls):\n \"\"\"Dictionary of preset names and configs that include weights.\"\"\"\n return {}","code_tokens":"","url":595126} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"search_space.py","full_name":"SingleSearchSpace.use_quantized_step","func_name":"use_quantized_step","docstring":"Check current instance is one of type to use `step`.","docstring_tokens":"","code":"def use_quantized_step(self):\n \"\"\"Check current instance is one of type to use `step`.\"\"\"\n return self._type in ('quniform', 'qloguniform')","code_tokens":"","url":919151} +{"project_name":"palVikram\/Machine-Learning-using-Python","file_name":"cmodule.py","full_name":"get_module_cache","func_name":"get_module_cache","docstring":"Create a new module_cache with the (k, v) pairs in this dictionary Parameters ---------- init_args If not None, the (k, v) pairs in this dictionary will be forwarded to the ModuleCache constructor as keyword arguments.","docstring_tokens":"","code":"def get_module_cache(dirname, init_args=None):\n \"\"\"\n Create a new module_cache with the (k, v) pairs in this dictionary\n\n Parameters\n ----------\n init_args\n If not None, the (k, v) pairs in this dictionary will be forwarded to\n the ModuleCache constructor as keyword arguments.\n\n \"\"\"\n global _module_cache\n if init_args is None:\n init_args = {}\n if _module_cache is None:\n _module_cache = ModuleCache(dirname, **init_args)\n atexit.register(_module_cache._on_atexit)\n elif init_args:\n _logger.warning('Ignoring init arguments for module cache because it was created prior to this call')\n if _module_cache.dirname != dirname:\n _logger.warning('Returning module cache instance with different dirname (%s) than you requested (%s)', _module_cache.dirname, dirname)\n return _module_cache","code_tokens":"","url":621287} +{"project_name":"SvenGronauer\/phoenix-drone-simulation","file_name":"model.py","full_name":"Model.summary","func_name":"summary","docstring":"print nice outputs to console.","docstring_tokens":"","code":"def summary(self):\n \"\"\" print nice outputs to console.\"\"\"\n raise NotImplementedError","code_tokens":"","url":769070} +{"project_name":"google-research\/crest","file_name":"train.py","full_name":"BaseTrain.eval_step","func_name":"eval_step","docstring":"Evaluates a model for one step.","docstring_tokens":"","code":"@tf.function\ndef eval_step(self, iterator, inference, use_logit_adjustment=False, accuracy_metric=None, per_class_accuracy_metric=None):\n \"\"\"Evaluates a model for one step.\"\"\"\n\n def step_fn(data):\n (x, y) = (data[0], data[1])\n logits = inference(x, training=False)['logits']\n if use_logit_adjustment:\n logits = logits - tf.expand_dims(tf.math.log(self.p_data()), axis=0)\n scores = tf.nn.softmax(logits, axis=1)\n if accuracy_metric:\n accuracy_metric.update_state(y, tf.argmax(logits, axis=1))\n if per_class_accuracy_metric:\n per_class_accuracy_metric.update_state(y, tf.argmax(logits, axis=1))\n return (scores, y)\n return self.strategy.run(step_fn, args=(next(iterator),))","code_tokens":"","url":138590} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"widgets.py","full_name":"Widget.set_active","func_name":"set_active","docstring":"Set whether the widget is active.","docstring_tokens":"","code":"def set_active(self, active):\n \"\"\"Set whether the widget is active.\n \"\"\"\n self._active = active","code_tokens":"","url":716154} +{"project_name":"fundamentalvision\/Auto-Seg-Loss","file_name":"enc_head.py","full_name":"EncHead.losses","func_name":"losses","docstring":"Compute segmentation and semantic encoding loss.","docstring_tokens":"","code":"def losses(self, seg_logit, seg_label):\n \"\"\"Compute segmentation and semantic encoding loss.\"\"\"\n (seg_logit, se_seg_logit) = seg_logit\n loss = dict()\n loss.update(super(EncHead, self).losses(seg_logit, seg_label))\n se_loss = self.loss_se_decode(se_seg_logit, self._convert_to_onehot_labels(seg_label, self.num_classes))\n loss['loss_se'] = se_loss\n return loss","code_tokens":"","url":416418} +{"project_name":"deepmind\/acme","file_name":"fakes.py","full_name":"rlds_dataset_from_env_spec","func_name":"rlds_dataset_from_env_spec","docstring":"Constructs a fake RLDS dataset with the given spec.","docstring_tokens":"","code":"def rlds_dataset_from_env_spec(spec: specs.EnvironmentSpec, *, episode_count: int=10, episode_length: int=25) -> tf.data.Dataset:\n \"\"\"Constructs a fake RLDS dataset with the given spec.\n\n Args:\n spec: specification to use for generation of fake steps.\n episode_count: number of episodes in the dataset.\n episode_length: length of the episode in the dataset.\n\n Returns:\n a fake RLDS dataset.\n \"\"\"\n fake_steps = {rlds_types.OBSERVATION: [_generate_from_spec(spec.observations)] * episode_length, rlds_types.ACTION: [_generate_from_spec(spec.actions)] * episode_length, rlds_types.REWARD: [_generate_from_spec(spec.rewards)] * episode_length, rlds_types.DISCOUNT: [_generate_from_spec(spec.discounts)] * episode_length, rlds_types.IS_TERMINAL: [False] * (episode_length - 1) + [True], rlds_types.IS_FIRST: [True] + [False] * (episode_length - 1), rlds_types.IS_LAST: [False] * (episode_length - 1) + [True]}\n steps_dataset = tf.data.Dataset.from_tensor_slices(fake_steps)\n return tf.data.Dataset.from_tensor_slices({rlds_types.STEPS: [steps_dataset] * episode_count})","code_tokens":"","url":7845} +{"project_name":"NVIDIA-Omniverse\/IsaacGymEnvs","file_name":"trifinger.py","full_name":"default_orientation","func_name":"default_orientation","docstring":"Returns identity rotation transform.","docstring_tokens":"","code":"@torch.jit.script\ndef default_orientation(num: int, device: str) -> torch.Tensor:\n \"\"\"Returns identity rotation transform.\"\"\"\n quat = torch.zeros((num, 4), dtype=torch.float, device=device)\n quat[..., -1] = 1.0\n return quat","code_tokens":"","url":246500} +{"project_name":"tensorflow\/agents","file_name":"spec_utils.py","full_name":"get_collect_data_spec_from_policy_and_env","func_name":"get_collect_data_spec_from_policy_and_env","docstring":"Returns collect data spec from policy and environment.","docstring_tokens":"","code":"def get_collect_data_spec_from_policy_and_env(env, policy):\n \"\"\"Returns collect data spec from policy and environment.\n\n Args:\n env: instance of the environment used for collection\n policy: policy for collection to get policy spec\n\n Meant to be used for collection jobs (i.e. Actors) without having to\n construct an agent instance but directly from a policy (which can be loaded\n from a saved model).\n \"\"\"\n observation_tensor_spec = tensor_spec.from_spec(env.observation_spec())\n time_step_tensor_spec = ts.time_step_spec(observation_tensor_spec)\n policy_step_tensor_spec = tensor_spec.from_spec(policy.policy_step_spec)\n collect_data_spec = trajectory.from_transition(time_step_tensor_spec, policy_step_tensor_spec, time_step_tensor_spec)\n return collect_data_spec","code_tokens":"","url":23007} +{"project_name":"cvalenzuela\/scenescoop","file_name":"server.py","full_name":"create_output","func_name":"create_output","docstring":"Create a new video given the input video and a user selected film in the database.","docstring_tokens":"","code":"@app.route('\/make', methods=['POST'])\ndef create_output():\n \"\"\"\n Create a new video given the input video and a user selected film in the database.\n \"\"\"\n input_data = '{}\/{}.json'.format(TRANSCRIPTS_VIDEOS_PATH, request.form['name'])\n duration = '0,{}'.format(int(float(request.form['duration'])))\n movie = '{}\/{}'.format(VIDEOS_PATH, request.form['movie'])\n movie_data = '{}\/{}.json'.format(TRANSCRIPTS_VIDEOS_PATH, request.form['movie'])\n scene = make_scene(OUTPUT_VIDEOS_PATH, input_data, duration, movie, movie_data, True)\n return jsonify(status='200', scene=scene)","code_tokens":"","url":845986} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"dnn.py","full_name":"DNNRegressor.predict_scores","func_name":"predict_scores","docstring":"Returns predicted scores for given features.","docstring_tokens":"","code":"@deprecated_arg_values(estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False)\ndef predict_scores(self, x=None, input_fn=None, batch_size=None, as_iterable=True):\n \"\"\"Returns predicted scores for given features.\n\n Args:\n x: features.\n input_fn: Input function. If set, x must be None.\n batch_size: Override default batch size.\n as_iterable: If True, return an iterable which keeps yielding predictions\n for each example until inputs are exhausted. Note: The inputs must\n terminate if you want the iterable to terminate (e.g. be sure to pass\n num_epochs=1 if you are using something like read_batch_features).\n\n Returns:\n Numpy array of predicted scores (or an iterable of predicted scores if\n as_iterable is True). If `label_dimension == 1`, the shape of the output\n is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`.\n \"\"\"\n key = prediction_key.PredictionKey.SCORES\n preds = super(DNNRegressor, self).predict(x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable)\n if as_iterable:\n return (pred[key] for pred in preds)\n return preds[key]","code_tokens":"","url":313597} +{"project_name":"mme\/vergeml","file_name":"io.py","full_name":"SourcePlugin.scan_and_split_files","func_name":"scan_and_split_files","docstring":"Return a dictionary of train, val and test files.","docstring_tokens":"","code":"def scan_and_split_files(self, files=None):\n \"\"\"Return a dictionary of train, val and test files.\n \"\"\"\n (train_files, val_files, test_files) = files or self.scan_dirs()\n\n def fromidx(idx):\n return [train_files[i] for i in idx]\n (strain, sval, stest) = self.split(len(train_files))\n\n def makemeta(split):\n return lambda filename: dict(split=split, filename=self.normalize_filename(split, filename))\n train = fromidx(strain)\n train_meta = map(makemeta('train'), train)\n val = val_files or fromidx(sval)\n val_meta = map(makemeta('val'), val)\n test = test_files or fromidx(stest)\n test_meta = map(makemeta('test'), test)\n return dict(train=list(zip(train, train_meta)), val=list(zip(val, val_meta)), test=list(zip(test, test_meta)))","code_tokens":"","url":931547} +{"project_name":"UWARG\/computer-vision-python","file_name":"camera_properties.py","full_name":"is_matrix_r3x3","func_name":"is_matrix_r3x3","docstring":"Checks if the numpy array is a matrix in R^{3x3} .","docstring_tokens":"","code":"def is_matrix_r3x3(matrix: np.ndarray) -> bool:\n \"\"\"\n Checks if the numpy array is a matrix in R^{3x3} .\n \"\"\"\n return matrix.shape == (3, 3)","code_tokens":"","url":470457} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"evaluation.py","full_name":"evaluation_loop","func_name":"evaluation_loop","docstring":"Runs TF-Slim's Evaluation Loop.","docstring_tokens":"","code":"def evaluation_loop(master, checkpoint_dir, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, eval_interval_secs=60, max_number_of_evaluations=None, session_config=None, timeout=None):\n \"\"\"Runs TF-Slim's Evaluation Loop.\n\n Args:\n master: The BNS address of the TensorFlow master.\n checkpoint_dir: The directory where checkpoints are stored.\n logdir: The directory where the TensorFlow summaries are written to.\n num_evals: The number of times to run `eval_op`.\n initial_op: An operation run at the beginning of evaluation.\n initial_op_feed_dict: A feed dictionary to use when executing `initial_op`.\n eval_op: A operation run `num_evals` times.\n eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`.\n final_op: An operation to execute after all of the `eval_op` executions. The\n value of `final_op` is returned.\n final_op_feed_dict: A feed dictionary to use when executing `final_op`.\n summary_op: The summary_op to evaluate after running TF-Slims metric ops. By\n default the summary_op is set to tf.summary.merge_all().\n summary_op_feed_dict: An optional feed dictionary to use when running the\n `summary_op`.\n variables_to_restore: A list of TensorFlow variables to restore during\n evaluation. If the argument is left as `None` then\n slim.variables.GetVariablesToRestore() is used.\n eval_interval_secs: The minimum number of seconds between evaluations.\n max_number_of_evaluations: the max number of iterations of the evaluation.\n If the value is left as 'None', the evaluation continues indefinitely.\n session_config: An instance of `tf.ConfigProto` that will be used to\n configure the `Session`. If left as `None`, the default will be used.\n timeout: The maximum amount of time to wait between checkpoints. If left as\n `None`, then the process will wait indefinitely.\n\n Returns:\n The value of `final_op` or `None` if `final_op` is `None`.\n \"\"\"\n if summary_op == _USE_DEFAULT:\n summary_op = summary.merge_all()\n global_step = variables.get_or_create_global_step()\n saver = tf_saver.Saver(variables_to_restore or variables.get_variables_to_restore())\n summary_writer = summary_io.SummaryWriter(logdir)\n sv = supervisor.Supervisor(graph=ops.get_default_graph(), logdir=logdir, summary_op=None, summary_writer=None, global_step=None, saver=saver)\n number_of_evaluations = 0\n for checkpoint_path in checkpoints_iterator(checkpoint_dir, eval_interval_secs, timeout):\n logging.info('Starting evaluation at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime()))\n with sv.managed_session(master, start_standard_services=False, config=session_config) as sess:\n sv.saver.restore(sess, checkpoint_path)\n sv.start_queue_runners(sess)\n final_op_value = evaluation(sess, num_evals=num_evals, initial_op=initial_op, initial_op_feed_dict=initial_op_feed_dict, eval_op=eval_op, eval_op_feed_dict=eval_op_feed_dict, final_op=final_op, final_op_feed_dict=final_op_feed_dict, summary_op=summary_op, summary_op_feed_dict=summary_op_feed_dict, summary_writer=summary_writer, global_step=global_step)\n logging.info('Finished evaluation at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime()))\n number_of_evaluations += 1\n if max_number_of_evaluations and number_of_evaluations >= max_number_of_evaluations:\n logging.info('Reached max_number_of_evaluations=%s. Exit', max_number_of_evaluations)\n return final_op_value\n logging.info('Timed-out waiting for new checkpoint file. Exiting evaluation loop.')\n return final_op_value","code_tokens":"","url":182004} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"re.py","full_name":"fullmatch","func_name":"fullmatch","docstring":"Try to apply the pattern to all of the string, returning a match object, or None if no match was found.","docstring_tokens":"","code":"def fullmatch(pattern, string, flags=0):\n \"\"\"Try to apply the pattern to all of the string, returning\n a match object, or None if no match was found.\"\"\"\n return _compile(pattern, flags).fullmatch(string)","code_tokens":"","url":187986} +{"project_name":"zcablii\/LSKNet","file_name":"mmrotate_handler.py","full_name":"MMRotateHandler.inference","func_name":"inference","docstring":"Predict the results given input request.","docstring_tokens":"","code":"def inference(self, data, *args, **kwargs):\n \"\"\"Predict the results given input request.\n\n Args:\n data (list[ndarray]): The list of a ndarray which are ready to\n process.\n\n Returns:\n list[Tensor] : The list of results from the inference.\n \"\"\"\n results = inference_detector(self.model, data)\n return results","code_tokens":"","url":616291} +{"project_name":"qiwenjjin\/TANet","file_name":"geometry.py","full_name":"points_in_convex_polygon_3d_jit","func_name":"points_in_convex_polygon_3d_jit","docstring":"check points is in 3d convex polygons.","docstring_tokens":"","code":"@numba.jit(nopython=False)\ndef points_in_convex_polygon_3d_jit(points, polygon_surfaces, num_surfaces=None):\n \"\"\"check points is in 3d convex polygons.\n Args:\n points: [num_points, 3] array.\n polygon_surfaces: [num_polygon, max_num_surfaces, \n max_num_points_of_surface, 3] \n array. all surfaces' normal vector must direct to internal.\n max_num_points_of_surface must at least 3.\n num_surfaces: [num_polygon] array. indicate how many surfaces \n a polygon contain\n Returns:\n [num_points, num_polygon] bool array.\n \"\"\"\n (max_num_surfaces, max_num_points_of_surface) = polygon_surfaces.shape[1:3]\n num_points = points.shape[0]\n num_polygons = polygon_surfaces.shape[0]\n if num_surfaces is None:\n num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64)\n (normal_vec, d) = surface_equ_3d_jit(polygon_surfaces[:, :, :3, :])\n ret = np.ones((num_points, num_polygons), dtype=np.bool_)\n sign = 0.0\n for i in range(num_points):\n for j in range(num_polygons):\n for k in range(max_num_surfaces):\n if k > num_surfaces[j]:\n break\n sign = points[i, 0] * normal_vec[j, k, 0] + points[i, 1] * normal_vec[j, k, 1] + points[i, 2] * normal_vec[j, k, 2] + d[j, k]\n if sign >= 0:\n ret[i, j] = False\n break\n return ret","code_tokens":"","url":906895} +{"project_name":"clips\/pattern","file_name":"liblinearutil.py","full_name":"evaluations","func_name":"evaluations","docstring":"evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC) ty, pv: list, tuple or ndarray useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv).","docstring_tokens":"","code":"def evaluations(ty, pv, useScipy=True):\n \"\"\"\n evaluations(ty, pv, useScipy) -> (ACC, MSE, SCC)\n ty, pv: list, tuple or ndarray\n useScipy: convert ty, pv to ndarray, and use scipy functions for the evaluation\n\n Calculate accuracy, mean squared error and squared correlation coefficient\n using the true values (ty) and predicted values (pv).\n \"\"\"\n if scipy is not None and useScipy:\n return evaluations_scipy(scipy.asarray(ty), scipy.asarray(pv))\n if len(ty) != len(pv):\n raise ValueError('len(ty) must be equal to len(pv)')\n total_correct = total_error = 0\n sumv = sumy = sumvv = sumyy = sumvy = 0\n for (v, y) in zip(pv, ty):\n if y == v:\n total_correct += 1\n total_error += (v - y) * (v - y)\n sumv += v\n sumy += y\n sumvv += v * v\n sumyy += y * y\n sumvy += v * y\n l = len(ty)\n ACC = 100.0 * total_correct \/ l\n MSE = total_error \/ l\n try:\n SCC = (l * sumvy - sumv * sumy) * (l * sumvy - sumv * sumy) \/ ((l * sumvv - sumv * sumv) * (l * sumyy - sumy * sumy))\n except:\n SCC = float('nan')\n return (float(ACC), float(MSE), float(SCC))","code_tokens":"","url":765041} +{"project_name":"marysia\/thesis","file_name":"model_building.py","full_name":"hyperparameter_randomiser_svm","func_name":"hyperparameter_randomiser_svm","docstring":"Returns the best hyperparameters from given ranges using a random search algorithm: c_range: Upper and lower bounds of the c distribution range as a list gamma_range: Upper and lower bounds of the gamma distribution range as a list c_dist: An argument specifying whether the distribution is drawn from a uniform or log uniform distribution arguments: \"log_uniform\", \"uniform\" gamma_dist: An argument specifying whether the distribution is drawn from a uniform or log uniform distribution arguments: \"log_uniform\", \"uniform\" prints: An option to facilitate the printing of the randomly selected hyperparameters at each search.","docstring_tokens":"","code":"def hyperparameter_randomiser_svm(c_range, gamma_range, c_dist='log_uniform', gamma_dist='log_uniform', prints=False):\n \"\"\"\n Returns the best hyperparameters from given ranges using a random search algorithm:\n c_range: Upper and lower bounds of the c distribution range as a list\n gamma_range: Upper and lower bounds of the gamma distribution range as a list\n c_dist: An argument specifying whether the distribution is drawn from a uniform or log uniform distribution\n arguments: \"log_uniform\", \"uniform\"\n gamma_dist: An argument specifying whether the distribution is drawn from a uniform or log uniform distribution\n arguments: \"log_uniform\", \"uniform\"\n prints: An option to facilitate the printing of the randomly selected hyperparameters at each search.\n \"\"\"\n if c_dist == 'log_uniform':\n c = loguniform(c_range[0], c_range[1]).rvs(1).item()\n elif c_dist == 'uniform':\n c = uniform(c_range[0], c_range[1]).rvs(1).item()\n else:\n raise Exception('Please provide a valid c distribution.')\n if gamma_dist == 'log_uniform':\n gamma = loguniform(gamma_range[0], gamma_range[1]).rvs(1).item()\n elif gamma_dist == 'uniform':\n gamma = uniform(gamma_range[0], gamma_range[1]).rvs(1).item()\n else:\n raise Exception('Please provide a valid gamma distribution.')\n if prints == True:\n print('c:', c)\n print('gamma:', gamma)\n return (c, gamma)","code_tokens":"","url":354916} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"html.py","full_name":"HtmlReporter.write_html","func_name":"write_html","docstring":"Write `html` to `fname`, properly encoded.","docstring_tokens":"","code":"def write_html(self, fname, html):\n \"\"\"Write `html` to `fname`, properly encoded.\"\"\"\n with open(fname, 'wb') as fout:\n fout.write(html.encode('ascii', 'xmlcharrefreplace'))","code_tokens":"","url":157434} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"factorization_ops.py","full_name":"WALSModel.row_factors","func_name":"row_factors","docstring":"Returns a list of tensors corresponding to row factor shards.","docstring_tokens":"","code":"@property\ndef row_factors(self):\n \"\"\"Returns a list of tensors corresponding to row factor shards.\"\"\"\n return self._row_factors","code_tokens":"","url":181250} +{"project_name":"jamie0725\/DLNLP-Project","file_name":"utils.py","full_name":"create_vocabulary","func_name":"create_vocabulary","docstring":"Create the vocabulary according to the train and val datasets.","docstring_tokens":"","code":"def create_vocabulary(embedding_model, data_path=data_path, train_file=train_file, val_file=val_file):\n \"\"\"Create the vocabulary according to the train and val datasets.\n\n Args:\n embedding_model (gensim model): model attribute of the Embeddings class.\n data_path (str, optional): path to the dataset folder. Defaults to data_path.\n train_file (str, optional): path to train.json. Defaults to train_file.\n val_file (str, optional): path to val.json. Defaults to val_file.\n\n Returns:\n OrderedDict, OrderedDict: vocabularies to look up the index of the tokens and to look up the tokens according to the index.\n \"\"\"\n stemmer = PorterStemmer()\n files = [train_file, val_file]\n data_dicts = []\n for file_ in files:\n with open(data_path + file_) as json_file:\n data_dicts.append(json.load(json_file))\n tokens = set()\n for data_dict in data_dicts:\n for sentences in data_dict.values():\n for sentence in sentences:\n tokens.update(map(stemmer.stem, sentence))\n token2ind = OrderedDict()\n ind2token = OrderedDict()\n token2ind[''] = 0\n token2ind[''] = 1\n ind2token[0] = ''\n ind2token[1] = ''\n i = 2\n for token in sorted(list(tokens)):\n if token not in embedding_model.vocab:\n token2ind[token] = 0\n continue\n token2ind[token] = i\n ind2token[i] = token\n i += 1\n return (token2ind, ind2token)","code_tokens":"","url":521860} +{"project_name":"RashadGarayev\/FireDetection","file_name":"convolutional_keras_box_predictor.py","full_name":"ConvolutionalBoxPredictor.build","func_name":"build","docstring":"Creates the variables of the layer.","docstring_tokens":"","code":"def build(self, input_shapes):\n \"\"\"Creates the variables of the layer.\"\"\"\n if len(input_shapes) != len(self._prediction_heads[BOX_ENCODINGS]):\n raise ValueError('This box predictor was constructed with %d heads,but there are %d inputs.' % (len(self._prediction_heads[BOX_ENCODINGS]), len(input_shapes)))\n for (stack_index, input_shape) in enumerate(input_shapes):\n net = []\n features_depth = static_shape.get_depth(input_shape)\n depth = max(min(features_depth, self._max_depth), self._min_depth)\n tf.logging.info('depth of additional conv before box predictor: {}'.format(depth))\n if depth > 0 and self._num_layers_before_predictor > 0:\n for i in range(self._num_layers_before_predictor):\n net.append(keras.Conv2D(depth, [1, 1], name='SharedConvolutions_%d\/Conv2d_%d_1x1_%d' % (stack_index, i, depth), padding='SAME', **self._conv_hyperparams.params()))\n net.append(self._conv_hyperparams.build_batch_norm(training=self._is_training and (not self._freeze_batchnorm), name='SharedConvolutions_%d\/Conv2d_%d_1x1_%d_norm' % (stack_index, i, depth)))\n net.append(self._conv_hyperparams.build_activation_layer(name='SharedConvolutions_%d\/Conv2d_%d_1x1_%d_activation' % (stack_index, i, depth)))\n self._shared_nets.append(net)\n self.built = True","code_tokens":"","url":210700} +{"project_name":"matsu0228\/nlp-jp","file_name":"test_doc2vec.py","full_name":"TestDoc2VecModel.test_parallel","func_name":"test_parallel","docstring":"Test doc2vec parallel training.","docstring_tokens":"","code":"def test_parallel(self):\n \"\"\"Test doc2vec parallel training.\"\"\"\n if doc2vec.FAST_VERSION < 0:\n return\n corpus = utils.RepeatCorpus(DocsLeeCorpus(), 10000)\n for workers in [2, 4]:\n model = doc2vec.Doc2Vec(corpus, workers=workers)\n self.model_sanity(model)","code_tokens":"","url":786087} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"buffer.py","full_name":"Buffer.cancel_completion","func_name":"cancel_completion","docstring":"Cancel completion, go back to the original text.","docstring_tokens":"","code":"def cancel_completion(self):\n \"\"\"\n Cancel completion, go back to the original text.\n \"\"\"\n if self.complete_state:\n self.go_to_completion(None)\n self.complete_state = None","code_tokens":"","url":44915} +{"project_name":"PRMorgan\/State-of-the-Artificial-Intelligence","file_name":"Player.py","full_name":"Player.jump","func_name":"jump","docstring":"Called when user hits 'jump' button.","docstring_tokens":"","code":"def jump(self):\n \"\"\" Called when user hits 'jump' button. \"\"\"\n self.rect.y += 4\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n self.rect.y -= 4\n if (self.rect.left == 0 or self.rect.right == SCREEN_WIDTH) and self.sideJumpCount == 0:\n self.change_y = -10\n self.sideJumpCount = 1\n if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:\n self.change_y = -10","code_tokens":"","url":383834} +{"project_name":"muneebshahid\/Learning-to-Optimize---","file_name":"util.py","full_name":"run_epoch","func_name":"run_epoch","docstring":"Runs one optimization epoch.","docstring_tokens":"","code":"def run_epoch(sess, loss, ops, reset, num_unrolls):\n \"\"\"Runs one optimization epoch.\"\"\"\n cost = 0\n final_ops = list()\n final_ops.append(loss)\n if ops is not None:\n final_ops = final_ops + ops\n start = timer()\n if reset is not None:\n sess.run(reset)\n for _ in range(num_unrolls):\n cost += sess.run(final_ops)[0]\n return (timer() - start, cost \/ num_unrolls)","code_tokens":"","url":588212} +{"project_name":"adamshamsudeen\/vision.ai","file_name":"datastructures.py","full_name":"Range.to_header","func_name":"to_header","docstring":"Converts the object back into an HTTP header.","docstring_tokens":"","code":"def to_header(self):\n \"\"\"Converts the object back into an HTTP header.\"\"\"\n ranges = []\n for (begin, end) in self.ranges:\n if end is None:\n ranges.append(begin >= 0 and '%s-' % begin or str(begin))\n else:\n ranges.append('%s-%s' % (begin, end - 1))\n return '%s=%s' % (self.units, ','.join(ranges))","code_tokens":"","url":944425} +{"project_name":"ago109\/predictive-forward-forward","file_name":"pff_rnn.py","full_name":"PFF_RNN.save_model","func_name":"save_model","docstring":"Save current model configuration and synaptic parameters (of both representation & generative circuits) to disk.","docstring_tokens":"","code":"def save_model(self, model_dir):\n \"\"\"\n Save current model configuration and synaptic parameters (of both\n representation & generative circuits) to disk.\n\n Args:\n model_dir: directory to save model config\n \"\"\"\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n serialize('{}config.args'.format(model_dir), self.args)\n serialize('{}rep_params.theta'.format(model_dir), self.theta)\n serialize('{}gen_params.theta'.format(model_dir), self.theta_g)","code_tokens":"","url":305920} +{"project_name":"Djaizz\/Djaizz","file_name":"__init__.py","full_name":"djaizz_aws_eb","func_name":"djaizz_aws_eb","docstring":"Trigger Djaizz AWS Elastic Beanstalk from CLI.","docstring_tokens":"","code":"@click.group(name='aws-eb', cls=click.Group, commands={'init': init, 'deploy': deploy}, invoke_without_command=False, no_args_is_help=True, subcommand_metavar='DJAI_AWS_EB_SUB_COMMAND', chain=False, help='Djaizz AWS Elastic Beanstalk CLI >>>', epilog='^^^ Djaizz AWS Elastic Beanstalk CLI', short_help='Djaizz AWS-EB CLI', options_metavar='[OPTIONS]', add_help_option=True, hidden=False, deprecated=False)\ndef djaizz_aws_eb():\n \"\"\"Trigger Djaizz AWS Elastic Beanstalk from CLI.\"\"\"","code_tokens":"","url":189472} +{"project_name":"jxhe\/unify-parameter-efficient-tuning","file_name":"check_copies.py","full_name":"convert_to_rst","func_name":"convert_to_rst","docstring":"Convert `model_list` to rst format.","docstring_tokens":"","code":"def convert_to_rst(model_list, max_per_line=None):\n \"\"\"Convert `model_list` to rst format.\"\"\"\n\n def _rep_link(match):\n (title, link) = match.groups()\n if 'master' in link or not link.startswith('https:\/\/huggingface.co\/transformers'):\n return f'`{title} <{link}>`__'\n else:\n link = link[len('https:\/\/huggingface.co\/transformers\/'):-len('.html')]\n return f':doc:`{title} <{link}>`'\n model_list = re.sub('\\\\*\\\\*\\\\[([^\\\\]]*)\\\\]\\\\(([^\\\\)]*)\\\\)\\\\*\\\\*', _rep_link, model_list)\n model_list = re.sub('\\\\[([^\\\\]]*)\\\\]\\\\(([^\\\\)]*)\\\\)', '`\\\\1 <\\\\2>`__', model_list)\n lines = model_list.split('\\n')\n result = []\n for (i, line) in enumerate(lines):\n line = re.sub('^\\\\s*(\\\\d+)\\\\.', f'{i + 1}.', line)\n if max_per_line is not None and len(line) > max_per_line:\n prompt = re.search('^(\\\\s*\\\\d+\\\\.\\\\s+)\\\\S', line)\n indent = len(prompt.groups()[0]) if prompt is not None else 0\n line = split_long_line_with_indent(line, max_per_line, indent)\n result.append(line)\n return '\\n'.join(result)","code_tokens":"","url":949556} +{"project_name":"facebookresearch\/CompilerGym","file_name":"random_search.py","full_name":"RandomAgentWorker.run","func_name":"run","docstring":"Run episodes in an infinite loop.","docstring_tokens":"","code":"def run(self) -> None:\n \"\"\"Run episodes in an infinite loop.\"\"\"\n while self.should_run_one_episode:\n self.total_environment_count += 1\n with self._make_env() as env:\n self._patience = self._patience or env.action_space.n\n self.run_one_environment(env)","code_tokens":"","url":125339} +{"project_name":"RasaHQ\/rasa_core","file_name":"data.py","full_name":"get_core_directory","func_name":"get_core_directory","docstring":"Recursively collects all Core training files from a list of directories.","docstring_tokens":"","code":"def get_core_directory(directories: Union[Text, List[Text]]) -> Text:\n \"\"\"Recursively collects all Core training files from a list of directories.\n\n Args:\n directories: List of paths to directories containing training files.\n\n Returns:\n Path to temporary directory containing all found Core training files.\n \"\"\"\n (core_files, _) = _get_core_nlu_files(directories)\n return _copy_files_to_new_dir(core_files)","code_tokens":"","url":838123} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_bisect_k_means.py","full_name":"test_float32_float64_equivalence","func_name":"test_float32_float64_equivalence","docstring":"Check that the results are the same between float32 and float64.","docstring_tokens":"","code":"@pytest.mark.parametrize('is_sparse', [True, False])\ndef test_float32_float64_equivalence(is_sparse):\n \"\"\"Check that the results are the same between float32 and float64.\"\"\"\n rng = np.random.RandomState(0)\n X = rng.rand(10, 2)\n if is_sparse:\n X[X < 0.8] = 0\n X = sp.csr_matrix(X)\n km64 = BisectingKMeans(n_clusters=3, random_state=0).fit(X)\n km32 = BisectingKMeans(n_clusters=3, random_state=0).fit(X.astype(np.float32))\n assert_allclose(km32.cluster_centers_, km64.cluster_centers_)\n assert_array_equal(km32.labels_, km64.labels_)","code_tokens":"","url":363501} +{"project_name":"gfjiangly\/cvtools","file_name":"file.py","full_name":"get_files_list","func_name":"get_files_list","docstring":"file_type is a str or list.","docstring_tokens":"","code":"def get_files_list(root, file_type=None, basename=False):\n \"\"\"file_type is a str or list.\"\"\"\n root = osp.abspath(root)\n files_list = _get_files_list(root)\n if file_type is not None:\n if isinstance(file_type, str):\n file_type = [file_type]\n files_list = [file for type in file_type for file in files_list if type == osp.splitext(file)[1]]\n if basename:\n files_list = [file.replace(root + os.sep, '') for file in files_list]\n return files_list","code_tokens":"","url":523881} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"flagsaver.py","full_name":"save_flag_values","func_name":"save_flag_values","docstring":"Returns copy of flag values as a dict.","docstring_tokens":"","code":"def save_flag_values(flag_values=FLAGS):\n \"\"\"Returns copy of flag values as a dict.\n\n Args:\n flag_values: FlagValues, the FlagValues instance with which the flag will\n be saved. This should almost never need to be overridden.\n Returns:\n Dictionary mapping keys to values. Keys are flag names, values are\n corresponding __dict__ members. E.g. {'key': value_dict, ...}.\n \"\"\"\n return {name: _copy_flag_dict(flag_values[name]) for name in flag_values}","code_tokens":"","url":309757} +{"project_name":"tanjeffreyz\/auto-maple","file_name":"gui.py","full_name":"GUI.start","func_name":"start","docstring":"Starts the GUI as well as any scheduled functions.","docstring_tokens":"","code":"def start(self):\n \"\"\"Starts the GUI as well as any scheduled functions.\"\"\"\n display_thread = threading.Thread(target=self._display_minimap)\n display_thread.daemon = True\n display_thread.start()\n layout_thread = threading.Thread(target=self._save_layout)\n layout_thread.daemon = True\n layout_thread.start()\n self.root.mainloop()","code_tokens":"","url":93405} +{"project_name":"DamianValle\/KTH-Artificial-Intelligence","file_name":"player.py","full_name":"PlayerControllerHMM.init_parameters","func_name":"init_parameters","docstring":"In this function you should initialize the parameters you will need, such as the initialization of models, or fishes, among others.","docstring_tokens":"","code":"def init_parameters(self):\n \"\"\"\n In this function you should initialize the parameters you will need,\n such as the initialization of models, or fishes, among others.\n \"\"\"\n self.models_fish = [Model(1, N_EMISSIONS) for _ in range(N_SPECIES)]\n self.fishes = [(i, []) for i in range(N_FISH)]","code_tokens":"","url":261448} +{"project_name":"yinyunie\/ScenePriors","file_name":"test_volumes.py","full_name":"TestVolumes.test_feature_density_setters","func_name":"test_feature_density_setters","docstring":"Tests getters and setters for padded\/list representations.","docstring_tokens":"","code":"def test_feature_density_setters(self):\n \"\"\"\n Tests getters and setters for padded\/list representations.\n \"\"\"\n device = torch.device('cuda:0')\n diff_device = torch.device('cpu')\n num_volumes = 30\n num_channels = 4\n K = 20\n densities = []\n features = []\n grid_sizes = []\n diff_grid_sizes = []\n for _ in range(num_volumes):\n grid_size = torch.randint(K - 1, size=(3,)).long() + 1\n densities.append(torch.rand((1, *grid_size), device=device, dtype=torch.float32))\n features.append(torch.rand((num_channels, *grid_size), device=device, dtype=torch.float32))\n grid_sizes.append(grid_size)\n diff_grid_size = copy.deepcopy(grid_size) + torch.randint(2, size=(3,)).long() + 1\n diff_grid_sizes.append(diff_grid_size)\n grid_sizes = torch.stack(grid_sizes).to(device)\n diff_grid_sizes = torch.stack(diff_grid_sizes).to(device)\n volumes = Volumes(densities=densities, features=features)\n self.assertClose(volumes.get_grid_sizes(), grid_sizes)\n features_padded = volumes.features()\n densities_padded = volumes.densities()\n features_list = volumes.features_list()\n densities_list = volumes.densities_list()\n for (x_pad, x_list) in zip((densities_padded, features_padded, densities_padded, features_padded), (densities_list, features_list, densities, features)):\n self._check_padded(x_pad, x_list, grid_sizes)\n features_new = [torch.rand((num_channels, *grid_size), device=device, dtype=torch.float32) for grid_size in grid_sizes]\n volumes._set_features(features_new)\n features_new_list = volumes.features_list()\n features_new_padded = volumes.features()\n for (x_pad, x_list) in zip((features_new_padded, features_new_padded), (features_new, features_new_list)):\n self._check_padded(x_pad, x_list, grid_sizes)\n bad_features_new = [[torch.rand((num_channels, *grid_size), device=diff_device, dtype=torch.float32) for grid_size in diff_grid_sizes], torch.rand((num_volumes, num_channels, K + 1, K, K), device=device, dtype=torch.float32), None]\n for bad_features_new_ in bad_features_new:\n with self.assertRaises(ValueError):\n volumes._set_densities(bad_features_new_)\n densities_new = [torch.rand((1, *grid_size), device=device, dtype=torch.float32) for grid_size in grid_sizes]\n volumes._set_densities(densities_new)\n densities_new_list = volumes.densities_list()\n densities_new_padded = volumes.densities()\n for (x_pad, x_list) in zip((densities_new_padded, densities_new_padded), (densities_new, densities_new_list)):\n self._check_padded(x_pad, x_list, grid_sizes)\n bad_densities_new = [[torch.rand((1, *grid_size), device=diff_device, dtype=torch.float32) for grid_size in diff_grid_sizes], torch.rand((num_volumes, 1, K + 1, K, K), device=device, dtype=torch.float32), None]\n for bad_densities_new_ in bad_densities_new:\n with self.assertRaises(ValueError):\n volumes._set_densities(bad_densities_new_)\n volumes = Volumes(densities=densities, features=features)\n volumes_updated = volumes.update_padded(densities_new, new_features=features_new)\n densities_new_list = volumes_updated.densities_list()\n densities_new_padded = volumes_updated.densities()\n features_new_list = volumes_updated.features_list()\n features_new_padded = volumes_updated.features()\n for (x_pad, x_list) in zip((densities_new_padded, densities_new_padded, features_new_padded, features_new_padded), (densities_new, densities_new_list, features_new, features_new_list)):\n self._check_padded(x_pad, x_list, grid_sizes)\n self.assertIs(volumes.get_grid_sizes(), volumes_updated.get_grid_sizes())\n self.assertIs(volumes.get_local_to_world_coords_transform(), volumes_updated.get_local_to_world_coords_transform())\n self.assertIs(volumes.device, volumes_updated.device)","code_tokens":"","url":330207} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"test_sync_vector_env.py","full_name":"test_custom_space_sync_vector_env","func_name":"test_custom_space_sync_vector_env","docstring":"Test the use of custom spaces with sync vector environment.","docstring_tokens":"","code":"def test_custom_space_sync_vector_env():\n \"\"\"Test the use of custom spaces with sync vector environment.\"\"\"\n env_fns = [make_custom_space_env(i) for i in range(4)]\n env = SyncVectorEnv(env_fns)\n (reset_observations, infos) = env.reset()\n assert isinstance(env.single_action_space, CustomSpace)\n assert isinstance(env.action_space, Tuple)\n actions = ('action-2', 'action-3', 'action-5', 'action-7')\n (step_observations, rewards, terminateds, truncateds, _) = env.step(actions)\n env.close()\n assert isinstance(env.single_observation_space, CustomSpace)\n assert isinstance(env.observation_space, Tuple)\n assert isinstance(reset_observations, tuple)\n assert reset_observations == ('reset', 'reset', 'reset', 'reset')\n assert isinstance(step_observations, tuple)\n assert step_observations == ('step(action-2)', 'step(action-3)', 'step(action-5)', 'step(action-7)')","code_tokens":"","url":573541} +{"project_name":"zackmcnulty\/CSE_446-Machine_Learning","file_name":"UnitDbl.py","full_name":"UnitDbl.type","func_name":"type","docstring":"Return the type of UnitDbl data.","docstring_tokens":"","code":"def type(self):\n \"\"\"Return the type of UnitDbl data.\"\"\"\n return self._types[self._units]","code_tokens":"","url":195194} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"bezier.py","full_name":"make_wedged_bezier2","func_name":"make_wedged_bezier2","docstring":"Being similar to get_parallels, returns control points of two quadrativ bezier lines having a width roughly parallel to given one separated by *width*.","docstring_tokens":"","code":"def make_wedged_bezier2(bezier2, width, w1=1.0, wm=0.5, w2=0.0):\n \"\"\"\n Being similar to get_parallels, returns control points of two quadrativ\n bezier lines having a width roughly parallel to given one separated by\n *width*.\n \"\"\"\n (c1x, c1y) = bezier2[0]\n (cmx, cmy) = bezier2[1]\n (c3x, c3y) = bezier2[2]\n (cos_t1, sin_t1) = get_cos_sin(c1x, c1y, cmx, cmy)\n (cos_t2, sin_t2) = get_cos_sin(cmx, cmy, c3x, c3y)\n (c1x_left, c1y_left, c1x_right, c1y_right) = get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)\n (c3x_left, c3y_left, c3x_right, c3y_right) = get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)\n (c12x, c12y) = ((c1x + cmx) * 0.5, (c1y + cmy) * 0.5)\n (c23x, c23y) = ((cmx + c3x) * 0.5, (cmy + c3y) * 0.5)\n (c123x, c123y) = ((c12x + c23x) * 0.5, (c12y + c23y) * 0.5)\n (cos_t123, sin_t123) = get_cos_sin(c12x, c12y, c23x, c23y)\n (c123x_left, c123y_left, c123x_right, c123y_right) = get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)\n path_left = find_control_points(c1x_left, c1y_left, c123x_left, c123y_left, c3x_left, c3y_left)\n path_right = find_control_points(c1x_right, c1y_right, c123x_right, c123y_right, c3x_right, c3y_right)\n return (path_left, path_right)","code_tokens":"","url":331} +{"project_name":"facebookresearch\/av_hubert","file_name":"hubert_asr.py","full_name":"HubertEncoder.set_num_updates","func_name":"set_num_updates","docstring":"Set the number of parameters updates.","docstring_tokens":"","code":"def set_num_updates(self, num_updates):\n \"\"\"Set the number of parameters updates.\"\"\"\n super().set_num_updates(num_updates)\n self.num_updates = num_updates","code_tokens":"","url":93804} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"vt100_output.py","full_name":"Vt100_Output.encoding","func_name":"encoding","docstring":"Return encoding used for stdout.","docstring_tokens":"","code":"def encoding(self):\n \"\"\" Return encoding used for stdout. \"\"\"\n return self.stdout.encoding","code_tokens":"","url":984055} +{"project_name":"rudranil723\/mini-main","file_name":"schema.py","full_name":"BaseDatabaseSchemaEditor.alter_db_table","func_name":"alter_db_table","docstring":"Rename the table a model points to.","docstring_tokens":"","code":"def alter_db_table(self, model, old_db_table, new_db_table):\n \"\"\"Rename the table a model points to.\"\"\"\n if old_db_table == new_db_table or (self.connection.features.ignores_table_name_case and old_db_table.lower() == new_db_table.lower()):\n return\n self.execute(self.sql_rename_table % {'old_table': self.quote_name(old_db_table), 'new_table': self.quote_name(new_db_table)})\n for sql in self.deferred_sql:\n if isinstance(sql, Statement):\n sql.rename_table_references(old_db_table, new_db_table)","code_tokens":"","url":315840} +{"project_name":"aalgirdas\/Artificial-Intelligence-Course","file_name":"tic-tac-toe.py","full_name":"reset_game","func_name":"reset_game","docstring":"This function will reset all the tiles to the initial null value.","docstring_tokens":"","code":"def reset_game():\n \"\"\"\n This function will reset all the tiles to the initial null value.\n \"\"\"\n global x_pos, o_pos, frames, count\n count = 0\n x_pos = []\n o_pos = []\n result.set('Your Turn!')\n for x in frames:\n for y in x.winfo_children():\n y.config(text=' ', state='normal')","code_tokens":"","url":79764} +{"project_name":"fmassa\/vision","file_name":"setup.py","full_name":"BuildExtension.with_options","func_name":"with_options","docstring":"Returns an alternative constructor that extends any original keyword arguments to the original constructor with the given options.","docstring_tokens":"","code":"@classmethod\ndef with_options(cls, **options):\n \"\"\"\n Returns an alternative constructor that extends any original keyword\n arguments to the original constructor with the given options.\n \"\"\"\n\n def init_with_options(*args, **kwargs):\n kwargs = kwargs.copy()\n kwargs.update(options)\n return cls(*args, **kwargs)\n return init_with_options","code_tokens":"","url":955780} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"interactive_debugger_server_lib.py","full_name":"SourceManager.get_paths","func_name":"get_paths","docstring":"Get the paths to all available source files.","docstring_tokens":"","code":"def get_paths(self):\n \"\"\"Get the paths to all available source files.\"\"\"\n return list(self._source_file_content.keys())","code_tokens":"","url":312178} +{"project_name":"meidachen\/STPLS3D","file_name":"cindex.py","full_name":"Type.get_declaration","func_name":"get_declaration","docstring":"Return the cursor for the declaration of the given type.","docstring_tokens":"","code":"def get_declaration(self):\n \"\"\"\n Return the cursor for the declaration of the given type.\n \"\"\"\n return conf.lib.clang_getTypeDeclaration(self)","code_tokens":"","url":909184} +{"project_name":"Sabrinas-workspace\/nlp-project-similar-lyrics","file_name":"lyrics_topics.py","full_name":"nouns_sorted","func_name":"nouns_sorted","docstring":"Creates a Counter of all nouns from the lyrics.","docstring_tokens":"","code":"def nouns_sorted(lyrics):\n \"\"\"Creates a Counter of all nouns from the lyrics.\n\n Args:\n lyrics: A string containing the lyrics of a song.\n\n Returns:\n A Counter of all nouns found in the lyrics.\n \"\"\"\n nouns = get_nouns(lyrics)\n sorted_nouns = Counter(nouns)\n return sorted_nouns","code_tokens":"","url":731097} +{"project_name":"microsoft\/InnerEye-DeepLearning","file_name":"checkpoint_handling.py","full_name":"CheckpointHandler.download_weights","func_name":"download_weights","docstring":"Download a checkpoint from weights_url to the modelweights directory.","docstring_tokens":"","code":"@staticmethod\ndef download_weights(urls: List[str], download_folder: Path) -> List[Path]:\n \"\"\"\n Download a checkpoint from weights_url to the modelweights directory.\n \"\"\"\n checkpoint_paths = []\n for url in urls:\n file_name = os.path.basename(urlparse(url).path) or str(uuid.uuid4().hex)\n result_file = download_folder \/ file_name\n checkpoint_paths.append(result_file)\n if result_file.exists():\n logging.info(f'File already exists, skipping download: {result_file}')\n else:\n logging.info(f'Downloading weights from URL {url}')\n response = requests.get(url, stream=True)\n response.raise_for_status()\n with open(result_file, 'wb') as file:\n for chunk in response.iter_content(chunk_size=1024):\n file.write(chunk)\n return checkpoint_paths","code_tokens":"","url":613265} +{"project_name":"explosion\/spaCy","file_name":"test_pipe_factories.py","full_name":"test_pipe_factories_from_source","func_name":"test_pipe_factories_from_source","docstring":"Test adding components from a source model.","docstring_tokens":"","code":"def test_pipe_factories_from_source():\n \"\"\"Test adding components from a source model.\"\"\"\n source_nlp = English()\n source_nlp.add_pipe('tagger', name='my_tagger')\n nlp = English()\n with pytest.raises(ValueError):\n nlp.add_pipe('my_tagger', source='en_core_web_sm')\n nlp.add_pipe('my_tagger', source=source_nlp)\n assert 'my_tagger' in nlp.pipe_names\n with pytest.raises(KeyError):\n nlp.add_pipe('custom', source=source_nlp)","code_tokens":"","url":894299} +{"project_name":"google-research\/scenic","file_name":"dvc_eval.py","full_name":"evaluate_caption_scores","func_name":"evaluate_caption_scores","docstring":"Compute the mean NLP metrics over the given IOU thresholds.","docstring_tokens":"","code":"def evaluate_caption_scores(ground_truths_filtered, predictions_filtered, iou_thresholds=(0.3, 0.5, 0.7, 0.9), scorers=None):\n \"\"\"Compute the mean NLP metrics over the given IOU thresholds.\n\n Args:\n ground_truths_filtered: Filtered list of ground truth captions for each\n threshold.\n predictions_filtered: Matching list of predicted captions for each threshold.\n iou_thresholds: A list of thresholds for IOU to average over.\n scorers: A dictionary of scorers.\n\n Returns:\n metrics: dictionary with mean captioning score across the threshold set.\n \"\"\"\n if scorers is None:\n scorers = {}\n metrics = collections.defaultdict(list)\n for (scorer_name, scorer) in scorers.items():\n for threshold in iou_thresholds:\n if not ground_truths_filtered[str(threshold)]:\n metrics[scorer_name].append(0.0)\n elif not predictions_filtered[str(threshold)]:\n metrics[scorer_name].append(0.0)\n else:\n score = scorer.compute_score(ground_truths_filtered[str(threshold)], predictions_filtered[str(threshold)])\n score = np.nan_to_num(score[0])\n metrics[scorer_name].append(score)\n for (key, value) in metrics.items():\n metrics[key] = np.mean(value)\n return metrics","code_tokens":"","url":847510} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"fields.py","full_name":"Schema.has_vectored_fields","func_name":"has_vectored_fields","docstring":"Returns True if any of the fields in this schema store term vectors.","docstring_tokens":"","code":"def has_vectored_fields(self):\n \"\"\"Returns True if any of the fields in this schema store term vectors.\n \"\"\"\n return any((ftype.vector for ftype in self))","code_tokens":"","url":483883} +{"project_name":"palmettos\/neat-autoencoders","file_name":"test_distributed.py","full_name":"test_DistributedEvaluator_state_error2","func_name":"test_DistributedEvaluator_state_error2","docstring":"Tests that attempts to use an unstarted manager for get_inqueue cause an error.","docstring_tokens":"","code":"def test_DistributedEvaluator_state_error2():\n \"\"\"Tests that attempts to use an unstarted manager for get_inqueue cause an error.\"\"\"\n primary = neat.DistributedEvaluator(('localhost', 8022), authkey=b'abcd1234', eval_function=eval_dummy_genome_nn, mode=MODE_PRIMARY)\n try:\n ignored = primary.em.get_inqueue()\n except RuntimeError:\n pass\n else:\n raise Exception('primary.em.get_inqueue() with unstarted manager did not raise a RuntimeError!')","code_tokens":"","url":735237} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"reading.py","full_name":"IndexReader.has_deletions","func_name":"has_deletions","docstring":"Returns True if the underlying index\/segment has deleted documents.","docstring_tokens":"","code":"@abstractmethod\ndef has_deletions(self):\n \"\"\"Returns True if the underlying index\/segment has deleted\n documents.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":132996} +{"project_name":"huawei-noah\/xingtian","file_name":"__init__.py","full_name":"register_evaluator","func_name":"register_evaluator","docstring":"Import and register evaluator automatically.","docstring_tokens":"","code":"def register_evaluator():\n \"\"\"Import and register evaluator automatically.\"\"\"\n from .evaluator import Evaluator\n from .host_evaluator import HostEvaluator\n from .device_evaluator import DeviceEvaluator","code_tokens":"","url":962613} +{"project_name":"alfrunesiq\/SemanticSegmentationActiveLearning","file_name":"extra_ops.py","full_name":"batch_normalization","func_name":"batch_normalization","docstring":"In good Tensorflow spirit this function is DEPRECATED.","docstring_tokens":"","code":"def batch_normalization(inputs, training=True, decay=0.9):\n \"\"\"\n In good Tensorflow spirit this function is DEPRECATED.\n \"\"\"\n params = {}\n with tf.variable_scope('BatchNorm'):\n with tf.name_scope('ShapeOps'):\n input_ch = inputs.shape[-1]\n params['Mean'] = tf.get_variable(shape=[input_ch], initializer=tf.zeros_initializer(), trainable=False, dtype=tf.float32, name='Mean')\n params['Variance'] = tf.get_variable(shape=[input_ch], initializer=tf.ones_initializer(), dtype=tf.float32, trainable=False, name='Variance')\n params['Beta'] = tf.get_variable(shape=[input_ch], initializer=tf.zeros_initializer(), trainable=True, dtype=tf.float32, name='Beta')\n params['Gamma'] = tf.get_variable(shape=[input_ch], initializer=tf.ones_initializer(), trainable=True, dtype=tf.float32, name='Gamma')\n if training:\n (out, batch_mean, batch_var) = tf.nn.fused_batch_norm(inputs, scale=params['Gamma'], offset=params['Beta'], is_training=training)\n update_mean = tf.assign_sub(params['Mean'], (1 - decay) * (params['Mean'] - batch_mean))\n update_var = tf.assign_sub(params['Variance'], (1 - decay) * (params['Variance'] - batch_var))\n with tf.control_dependencies([update_mean, update_var]):\n out = tf.identity(out)\n else:\n (out, _, _) = tf.nn.fused_batch_norm(inputs, scale=params['Gamma'], offset=params['Beta'], mean=params['Mean'], variance=params['Variance'], is_training=training)\n return (out, params)","code_tokens":"","url":870914} +{"project_name":"nilearn\/nilearn","file_name":"test_plot_carpet.py","full_name":"test_plot_carpet","func_name":"test_plot_carpet","docstring":"Check contents of plot_carpet figure against data in image.","docstring_tokens":"","code":"def test_plot_carpet(testdata_4d_for_plotting):\n \"\"\"Check contents of plot_carpet figure against data in image.\"\"\"\n img_4d = testdata_4d_for_plotting['img_4d']\n img_4d_long = testdata_4d_for_plotting['img_4d_long']\n mask_img = testdata_4d_for_plotting['img_mask']\n display = plot_carpet(img_4d, mask_img, detrend=False, title='TEST')\n ax = display.axes[0]\n plotted_array = ax.images[0].get_array()\n assert plotted_array.shape == (np.prod(img_4d.shape[:-1]), img_4d.shape[-1])\n np.testing.assert_almost_equal(plotted_array.sum(), img_4d.get_fdata().sum(), decimal=3)\n plt.close(display)\n (fig, ax) = plt.subplots()\n display = plot_carpet(img_4d_long, mask_img, t_r=None, detrend=True, title='TEST', figure=fig, axes=ax)\n ax = display.axes[0]\n plotted_array = ax.images[0].get_array()\n n_items = np.prod(img_4d_long.shape[:-1]) * np.ceil(img_4d_long.shape[-1] \/ 4)\n assert plotted_array.size == n_items\n plt.close(display)","code_tokens":"","url":724153} +{"project_name":"kubeflow\/pipelines","file_name":"client.py","full_name":"Client.delete_recurring_run","func_name":"delete_recurring_run","docstring":"Deletes a recurring run.","docstring_tokens":"","code":"def delete_recurring_run(self, recurring_run_id: str) -> dict:\n \"\"\"Deletes a recurring run.\n\n Args:\n recurring_run_id: ID of the recurring_run.\n\n Returns:\n Empty dictionary.\n \"\"\"\n return self._recurring_run_api.delete_recurring_run(recurring_run_id=recurring_run_id)","code_tokens":"","url":779902} +{"project_name":"ludwig-ai\/ludwig","file_name":"test_preprocessing.py","full_name":"test_number_feature_wrong_dtype","func_name":"test_number_feature_wrong_dtype","docstring":"Tests that a number feature with all string values is treated as having missing values by default.","docstring_tokens":"","code":"def test_number_feature_wrong_dtype(csv_filename, tmpdir):\n \"\"\"Tests that a number feature with all string values is treated as having missing values by default.\"\"\"\n data_csv_path = os.path.join(tmpdir, csv_filename)\n num_feat = number_feature()\n input_features = [num_feat]\n output_features = [binary_feature()]\n config = {INPUT_FEATURES: input_features, OUTPUT_FEATURES: output_features}\n training_data_csv_path = generate_data(input_features, output_features, data_csv_path)\n df = pd.read_csv(training_data_csv_path)\n\n def random_string():\n letters = string.ascii_lowercase\n return ''.join((random.choice(letters) for _ in range(10)))\n df[num_feat[COLUMN]] = df[num_feat[COLUMN]].apply(lambda _: random_string())\n backend = LocalTestBackend()\n ludwig_model = LudwigModel(config, backend=backend)\n (train_ds, val_ds, test_ds, _) = ludwig_model.preprocess(dataset=df)\n concatenated_df = concatenate_df(train_ds.to_df(), val_ds.to_df(), test_ds.to_df(), backend)\n assert len(concatenated_df) == len(df)\n assert np.all(concatenated_df[num_feat[PROC_COLUMN]] == 0.0)","code_tokens":"","url":617272} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"convolutional.py","full_name":"extract_labels","func_name":"extract_labels","docstring":"Extract the labels into a vector of int64 label IDs.","docstring_tokens":"","code":"def extract_labels(filename, num_images):\n \"\"\"Extract the labels into a vector of int64 label IDs.\"\"\"\n print('Extracting', filename)\n with gzip.open(filename) as bytestream:\n bytestream.read(8)\n buf = bytestream.read(1 * num_images)\n labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64)\n return labels","code_tokens":"","url":30378} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.eq_type","func_name":"eq_type","docstring":"constraint type (mjtEq) (neq x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef eq_type(self):\n \"\"\"constraint type (mjtEq) (neq x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.eq_type, (self.neq,))","code_tokens":"","url":440401} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"editor.py","full_name":"EditorWindow.RemoveKeybindings","func_name":"RemoveKeybindings","docstring":"Remove the keybindings before they are changed.","docstring_tokens":"","code":"def RemoveKeybindings(self):\n \"\"\"Remove the keybindings before they are changed.\"\"\"\n self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()\n for (event, keylist) in keydefs.items():\n self.text.event_delete(event, *keylist)\n for extensionName in self.get_standard_extension_names():\n xkeydefs = idleConf.GetExtensionBindings(extensionName)\n if xkeydefs:\n for (event, keylist) in xkeydefs.items():\n self.text.event_delete(event, *keylist)","code_tokens":"","url":282760} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"test_wrkpool.py","full_name":"TestCase.add","func_name":"add","docstring":"Dummy task for a worker to do.","docstring_tokens":"","code":"def add(self, value):\n \"\"\" Dummy task for a worker to do. \"\"\"\n self.total += value\n return -value","code_tokens":"","url":276331} +{"project_name":"ShuvenduRoy\/Generative_adversarial_networks","file_name":"solver.py","full_name":"Solver.test_multi","func_name":"test_multi","docstring":"Translate images using StarGAN trained on multiple datasets.","docstring_tokens":"","code":"def test_multi(self):\n \"\"\"Translate images using StarGAN trained on multiple datasets.\"\"\"\n self.restore_model(self.test_iters)\n with torch.no_grad():\n for (i, (x_real, c_org)) in enumerate(self.celeba_loader):\n x_real = x_real.to(self.device)\n c_celeba_list = self.create_labels(c_org, self.c_dim, 'CelebA', self.selected_attrs)\n c_rafd_list = self.create_labels(c_org, self.c2_dim, 'RaFD')\n zero_celeba = torch.zeros(x_real.size(0), self.c_dim).to(self.device)\n zero_rafd = torch.zeros(x_real.size(0), self.c2_dim).to(self.device)\n mask_celeba = self.label2onehot(torch.zeros(x_real.size(0)), 2).to(self.device)\n mask_rafd = self.label2onehot(torch.ones(x_real.size(0)), 2).to(self.device)\n x_fake_list = [x_real]\n for c_celeba in c_celeba_list:\n c_trg = torch.cat([c_celeba, zero_rafd, mask_celeba], dim=1)\n x_fake_list.append(self.G(x_real, c_trg))\n for c_rafd in c_rafd_list:\n c_trg = torch.cat([zero_celeba, c_rafd, mask_rafd], dim=1)\n x_fake_list.append(self.G(x_real, c_trg))\n x_concat = torch.cat(x_fake_list, dim=3)\n result_path = os.path.join(self.result_dir, '{}-images.jpg'.format(i + 1))\n save_image(self.denorm(x_concat.data.cpu()), result_path, nrow=1, padding=0)\n print('Saved real and fake images into {}...'.format(result_path))","code_tokens":"","url":556673} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"cls_head.py","full_name":"GaussianProcessClassificationHead.reset_covariance_matrix","func_name":"reset_covariance_matrix","docstring":"Resets covariance matrix of the Gaussian process layer.","docstring_tokens":"","code":"def reset_covariance_matrix(self):\n \"\"\"Resets covariance matrix of the Gaussian process layer.\"\"\"\n if hasattr(self.out_proj, 'reset_covariance_matrix'):\n self.out_proj.reset_covariance_matrix()","code_tokens":"","url":972559} +{"project_name":"intel\/neural-compressor","file_name":"nxm.py","full_name":"PytorchPatternNxM.get_block_size_dict","func_name":"get_block_size_dict","docstring":"Calculate the zero elements' ration in pre_masks.","docstring_tokens":"","code":"def get_block_size_dict(self):\n \"\"\"Calculate the zero elements' ration in pre_masks.\n\n Args:\n data: Dict{\"layer_name\": Tensor} that stores weights or scores.\n\n Returns:\n A dict. Dict{\"layer_name\": [block_size_1, block_size_2]} containing block shapes of each layer.\n In channel-wise pruning different layers can have different pruning patterns.\n \"\"\"\n datas = self.modules\n block_sizes_dict = {}\n for key in datas.keys():\n block_sizes_dict[key] = self.block_size\n if not (self.N == 'channel' or self.M == 'channel'):\n continue\n if isinstance(datas[key], torch.nn.Module):\n shape = datas[key].weight.shape\n else:\n shape = datas[key].shape\n if self.N == 'channel':\n block_sizes_dict[key] = [shape[0], self.block_size[1]]\n if self.M == 'channel':\n block_sizes_dict[key] = [self.block_size[0], shape[1]]\n return block_sizes_dict","code_tokens":"","url":738163} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"text_format.py","full_name":"Tokenizer.TryConsume","func_name":"TryConsume","docstring":"Tries to consume a given piece of text.","docstring_tokens":"","code":"def TryConsume(self, token):\n \"\"\"Tries to consume a given piece of text.\n\n Args:\n token: Text to consume.\n\n Returns:\n True iff the text was consumed.\n \"\"\"\n if self.token == token:\n self.NextToken()\n return True\n return False","code_tokens":"","url":215268} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"messaging.py","full_name":"_MessagingService.send_all","func_name":"send_all","docstring":"Sends the given messages to FCM via the batch API.","docstring_tokens":"","code":"def send_all(self, messages, dry_run=False):\n \"\"\"Sends the given messages to FCM via the batch API.\"\"\"\n if not isinstance(messages, list):\n raise ValueError('messages must be a list of messaging.Message instances.')\n if len(messages) > 500:\n raise ValueError('messages must not contain more than 500 elements.')\n responses = []\n\n def batch_callback(_, response, error):\n exception = None\n if error:\n exception = self._handle_batch_error(error)\n send_response = SendResponse(response, exception)\n responses.append(send_response)\n batch = http.BatchHttpRequest(batch_callback, _MessagingService.FCM_BATCH_URL)\n for message in messages:\n body = json.dumps(self._message_data(message, dry_run))\n req = http.HttpRequest(http=self._transport, postproc=self._postproc, uri=self._fcm_url, method='POST', body=body, headers=self._fcm_headers)\n batch.add(req)\n try:\n batch.execute()\n except googleapiclient.http.HttpError as error:\n raise self._handle_batch_error(error)\n else:\n return BatchResponse(responses)","code_tokens":"","url":214304} +{"project_name":"DLR-RM\/stable-baselines3","file_name":"test_vec_envs.py","full_name":"check_vecenv_obs","func_name":"check_vecenv_obs","docstring":"Helper method to check observations from multiple environments each belong to the appropriate observation space.","docstring_tokens":"","code":"def check_vecenv_obs(obs, space):\n \"\"\"Helper method to check observations from multiple environments each belong to\n the appropriate observation space.\"\"\"\n assert obs.shape[0] == N_ENVS\n for value in obs:\n assert space.contains(value)","code_tokens":"","url":383600} +{"project_name":"rail-berkeley\/softlearning","file_name":"serialization.py","full_name":"serialize_softlearning_class_and_config","func_name":"serialize_softlearning_class_and_config","docstring":"Returns the serialization of the class with the given config.","docstring_tokens":"","code":"def serialize_softlearning_class_and_config(cls_name, cls_config):\n \"\"\"Returns the serialization of the class with the given config.\"\"\"\n return {'class_name': cls_name, 'config': cls_config}","code_tokens":"","url":879323} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"agents.py","full_name":"XYEnvironment.turn_heading","func_name":"turn_heading","docstring":"Return the heading to the left (inc=+1) or right (inc=-1) of heading.","docstring_tokens":"","code":"def turn_heading(self, heading, inc):\n \"\"\"Return the heading to the left (inc=+1) or right (inc=-1) of heading.\"\"\"\n return turn_heading(heading, inc)","code_tokens":"","url":22053} +{"project_name":"deepmind\/dm_control","file_name":"mazes.py","full_name":"MazeWithTargets.text_maze_regenerated_hook","func_name":"text_maze_regenerated_hook","docstring":"A callback that is executed after the LabMaze object is regenerated.","docstring_tokens":"","code":"@property\ndef text_maze_regenerated_hook(self):\n \"\"\"A callback that is executed after the LabMaze object is regenerated.\"\"\"\n return self._text_maze_modifier","code_tokens":"","url":165043} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"channels.py","full_name":"HBChannel.stop","func_name":"stop","docstring":"Stop the channel's event loop and join its thread.","docstring_tokens":"","code":"def stop(self):\n \"\"\"Stop the channel's event loop and join its thread.\"\"\"\n self._running = False\n self.join()\n self.close()","code_tokens":"","url":39456} +{"project_name":"drprojects\/superpoint_transformer","file_name":"base.py","full_name":"BaseDataset.pre_transform_hash","func_name":"pre_transform_hash","docstring":"Produce a unique but stable hash based on the dataset's `pre_transform` attributes (as exposed by `_repr`).","docstring_tokens":"","code":"@property\ndef pre_transform_hash(self):\n \"\"\"Produce a unique but stable hash based on the dataset's\n `pre_transform` attributes (as exposed by `_repr`).\n \"\"\"\n if self.custom_hash is not None:\n return self.custom_hash\n if self.pre_transform is None:\n return 'no_pre_transform'\n return hashlib.md5(_repr(self.pre_transform).encode()).hexdigest()","code_tokens":"","url":880824} +{"project_name":"triaquae\/triaquae","file_name":"case.py","full_name":"TestCase.assertFalse","func_name":"assertFalse","docstring":"Fail the test if the expression is true.","docstring_tokens":"","code":"def assertFalse(self, expr, msg=None):\n \"\"\"Fail the test if the expression is true.\"\"\"\n if expr:\n msg = self._formatMessage(msg, '%s is not False' % safe_repr(expr))\n raise self.failureException(msg)","code_tokens":"","url":424247} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"dtypes.py","full_name":"DType.real_dtype","func_name":"real_dtype","docstring":"Returns the dtype correspond to this dtype's real part.","docstring_tokens":"","code":"@property\ndef real_dtype(self):\n \"\"\"Returns the dtype correspond to this dtype's real part.\"\"\"\n base = self.base_dtype\n if base == complex64:\n return float32\n elif base == complex128:\n return float64\n else:\n return self","code_tokens":"","url":182477} +{"project_name":"avalonstrel\/SketchBERT","file_name":"utils.py","full_name":"clean_strokes","func_name":"clean_strokes","docstring":"Cut irrelevant end points, scale to pixel space and store as integer.","docstring_tokens":"","code":"def clean_strokes(sample_strokes, factor=100):\n \"\"\"Cut irrelevant end points, scale to pixel space and store as integer.\"\"\"\n copy_stroke = []\n added_final = False\n for j in range(len(sample_strokes)):\n finish_flag = int(sample_strokes[j][4])\n if finish_flag == 0:\n copy_stroke.append([int(round(sample_strokes[j][0] * factor)), int(round(sample_strokes[j][1] * factor)), int(sample_strokes[j][2]), int(sample_strokes[j][3]), finish_flag])\n else:\n copy_stroke.append([0, 0, 0, 0, 1])\n added_final = True\n break\n if not added_final:\n copy_stroke.append([0, 0, 0, 0, 1])\n return copy_stroke","code_tokens":"","url":350970} +{"project_name":"Erfanafshar\/Principles-and-Applications-of---graph-coloring","file_name":"test_arraypad.py","full_name":"TestAsPairs.test_single_value","func_name":"test_single_value","docstring":"Test casting for a single value.","docstring_tokens":"","code":"def test_single_value(self):\n \"\"\"Test casting for a single value.\"\"\"\n expected = np.array([[3, 3]] * 10)\n for x in (3, [3], [[3]]):\n result = _as_pairs(x, 10)\n assert_equal(result, expected)\n obj = object()\n assert_equal(_as_pairs(obj, 10), np.array([[obj, obj]] * 10))","code_tokens":"","url":308109} +{"project_name":"google\/deepvariant","file_name":"genomics_reader.py","full_name":"GenomicsReader.query","func_name":"query","docstring":"Returns an iterator for going through the records in the region.","docstring_tokens":"","code":"@abc.abstractmethod\ndef query(self, region):\n \"\"\"Returns an iterator for going through the records in the region.\n\n Args:\n region: A nucleus.genomics.v1.Range.\n\n Returns:\n An iterator containing all and only records within the specified region.\n \"\"\"","code_tokens":"","url":540568} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"device_assignment.py","full_name":"DeviceAssignment.lookup_replicas","func_name":"lookup_replicas","docstring":"Lookup replica ids by task number and logical core.","docstring_tokens":"","code":"def lookup_replicas(self, task_id, logical_core):\n \"\"\"Lookup replica ids by task number and logical core.\n\n Args:\n task_id: TensorFlow task number.\n logical_core: A tuple of three integers which represents a logical core.\n Returns:\n A sorted list of the replicas that are attached to that task and\n logical_core.\n Raises:\n ValueError: If no replica exists in the task which contains the logical\n core.\n \"\"\"\n try:\n return self._task_and_cores_to_replicas[task_id][logical_core]\n except KeyError:\n raise ValueError('Can not find any replica in task: {} contains logical_core: {} '.format(task_id, logical_core))","code_tokens":"","url":335550} +{"project_name":"alibaba\/EasyCV","file_name":"mvx_two_stage.py","full_name":"MVXTwoStageDetector.with_pts_neck","func_name":"with_pts_neck","docstring":"bool: Whether the detector has a neck in 3D detector branch.","docstring_tokens":"","code":"@property\ndef with_pts_neck(self):\n \"\"\"bool: Whether the detector has a neck in 3D detector branch.\"\"\"\n return hasattr(self, 'pts_neck') and self.pts_neck is not None","code_tokens":"","url":546616} +{"project_name":"amzn\/xfer","file_name":"metalogger.py","full_name":"MetaLogger.plot_params","func_name":"plot_params","docstring":"Plot the logged parameters.","docstring_tokens":"","code":"def plot_params(self, param, W, loss_fn, figsize=(20, 6), gridsize=(100, 100), a=0.2, loss_samples=100):\n \"\"\"\n Plot the logged parameters.\n \"\"\"\n if self._parameters == {}:\n raise ValueError('No parameters logged.')\n (fig, axes) = plt.subplots(ncols=self.num_tasks, figsize=figsize)\n for surface in range(self.num_tasks):\n for ms in sorted(self._parameters.keys()):\n for task in range(self.num_tasks):\n if task in self._parameters[ms].keys() or ms == max(self._parameters.keys()):\n temp_ms = ms\n while task not in self._parameters[temp_ms].keys():\n temp_ms -= 1\n x = np.concatenate([p[param] for p in self._parameters[temp_ms][task]])\n x = np.concatenate([self._parameters[temp_ms]['all'][0][param], x]).T\n initial_point = self._parameters[temp_ms]['all'][0][param].T\n assert x.shape[0] == 2, 'Dimension of parameter must be 2.'\n label = task if ms == max(self._parameters.keys()) else None\n alpha = 1 if ms == max(self._parameters.keys()) else self.alpha_plot\n color = 'r' if surface == task else 'k'\n axes[surface].plot(x[0], x[1], 'o-', color=color, label=label, alpha=alpha)\n axes[surface].plot(initial_point[0], initial_point[1], 'o-', color='tab:pink', alpha=alpha)\n axes[surface].legend()\n axes[surface].set_title('Loss surface for Task {}'.format(surface))\n extent = axes[surface].get_xlim() + axes[surface].get_ylim()\n grid = np.zeros(gridsize)\n for (i, w1) in enumerate(np.linspace(extent[0], extent[1], gridsize[0])):\n for (j, w2) in enumerate(np.linspace(extent[2], extent[3], gridsize[1])):\n grid[j][i] = loss_fn(mx.nd.array([w1, w2]), W[surface], loss_samples)\n axes[surface].imshow(grid, extent=extent, origin='lower')\n axes[surface].set_xlabel(param + ' 1')\n axes[surface].set_ylabel(param + ' 2')\n fig.suptitle('Parameters', fontsize=30, y=0.9)","code_tokens":"","url":961931} +{"project_name":"megvii-research\/MSCL","file_name":"decorators.py","full_name":"import_module_error_class","func_name":"import_module_error_class","docstring":"When a class is imported incorrectly due to a missing module, raise an import error when the class is instantiated.","docstring_tokens":"","code":"def import_module_error_class(module_name):\n \"\"\"When a class is imported incorrectly due to a missing module, raise an\n import error when the class is instantiated.\"\"\"\n\n def decorate(cls):\n\n def import_error_init(*args, **kwargs):\n raise ImportError(f'Please install {module_name} to use {cls.__name__}.')\n cls.__init__ = MethodType(import_error_init, cls)\n return cls\n return decorate","code_tokens":"","url":264969} +{"project_name":"MycroftAI\/mycroft-core","file_name":"intent_service.py","full_name":"IntentService.remove_active_skill","func_name":"remove_active_skill","docstring":"Remove a skill from being targetable by converse.","docstring_tokens":"","code":"def remove_active_skill(self, skill_id):\n \"\"\"Remove a skill from being targetable by converse.\n\n Args:\n skill_id (str): skill to remove\n \"\"\"\n for skill in self.active_skills:\n if skill[0] == skill_id:\n self.active_skills.remove(skill)","code_tokens":"","url":290483} +{"project_name":"facebookresearch\/CompilerGym","file_name":"observation_spaces_test.py","full_name":"test_runtime_observation_space_different_observation_count","func_name":"test_runtime_observation_space_different_observation_count","docstring":"Test setting a custom observation count for LLVM runtimes.","docstring_tokens":"","code":"@flaky\ndef test_runtime_observation_space_different_observation_count(env: LlvmEnv):\n \"\"\"Test setting a custom observation count for LLVM runtimes.\"\"\"\n env.reset('cbench-v1\/crc32')\n env.runtime_observation_count = 3\n value: np.ndarray = env.observation['Runtime']\n print(value.tolist())\n assert value.shape == (3,)\n env.reset()\n value: np.ndarray = env.observation['Runtime']\n print(value.tolist())\n assert value.shape == (3,)\n env.runtime_observation_count = 5\n value: np.ndarray = env.observation['Runtime']\n print(value.tolist())\n assert value.shape == (5,)","code_tokens":"","url":125937} +{"project_name":"yufeiwang63\/ROLL","file_name":"instrument2.py","full_name":"ensure_dir","func_name":"ensure_dir","docstring":"Ensure that a named directory exists; if it does not, attempt to create it.","docstring_tokens":"","code":"def ensure_dir(dirname):\n \"\"\"\n Ensure that a named directory exists; if it does not, attempt to create it.\n \"\"\"\n try:\n os.makedirs(dirname)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise","code_tokens":"","url":326635} +{"project_name":"NetManAIOps\/OmniAnomaly","file_name":"vae.py","full_name":"VAE.variational","func_name":"variational","docstring":"Derive an instance of :math:`q(z|h(x))`, the variational net.","docstring_tokens":"","code":"@instance_reuse\ndef variational(self, x, z=None, n_z=None, posterior_flow=None):\n \"\"\"\n Derive an instance of :math:`q(z|h(x))`, the variational net.\n\n Args:\n x: The observation `x` for the variational net.\n z: If specified, observe `z` in the variational net.\n (default :obj:`None`)\n n_z: The number of `z` samples to take for each `x`, if `z`\n is not observed. (default :obj:`None`, one sample for\n each `x`, without dedicated sampling dimension)\n\n It is recommended to specify this argument even if `z`\n is observed, to make explicit how many samples are there\n in the observation.\n\n Returns:\n BayesianNet: The variational net.\n \"\"\"\n observed = {}\n if z is not None:\n observed['z'] = z\n net = BayesianNet(observed=observed)\n with tf.variable_scope('h_for_q_z'):\n z_params = self.h_for_q_z(x)\n with tf.variable_scope('q_z_given_x'):\n q_z_given_x = self.q_z_given_x(**z_params)\n assert isinstance(q_z_given_x, Distribution)\n with tf.name_scope('z'):\n z = net.add('z', q_z_given_x, n_samples=n_z, group_ndims=self.z_group_ndims, is_reparameterized=self.is_reparameterized, flow=posterior_flow)\n return net","code_tokens":"","url":250276} +{"project_name":"nilearn\/nilearn","file_name":"test_html_report.py","full_name":"test_nifti_maps_masker_report_integer_and_all_displayed_maps","func_name":"test_nifti_maps_masker_report_integer_and_all_displayed_maps","docstring":"Tests NiftiMapsMasker reporting with no image provided to fit and displayed_maps provided as an integer or as 'all'.","docstring_tokens":"","code":"@pytest.mark.parametrize('displayed_maps', [1, 6, 9, 12, 'all'])\ndef test_nifti_maps_masker_report_integer_and_all_displayed_maps(niftimapsmasker_inputs, displayed_maps):\n \"\"\"Tests NiftiMapsMasker reporting with no image provided to fit\n and displayed_maps provided as an integer or as 'all'.\n \"\"\"\n masker = NiftiMapsMasker(**niftimapsmasker_inputs)\n masker.fit()\n expected_n_maps = 9 if displayed_maps == 'all' else min(9, displayed_maps)\n if displayed_maps != 'all' and displayed_maps > 9:\n with pytest.warns(UserWarning, match='masker only has 9 maps.'):\n html = masker.generate_report(displayed_maps)\n else:\n html = masker.generate_report(displayed_maps)\n assert masker._report_content['report_id'] == 0\n assert masker._report_content['number_of_maps'] == 9\n assert masker._report_content['displayed_maps'] == list(range(expected_n_maps))\n msg = 'No image provided to fit in NiftiMapsMasker. Plotting only spatial maps for reporting.'\n assert masker._report_content['warning_message'] == msg\n assert html.body.count(' None:\n \"\"\"Validates observation_spec property of the multi agent to single\n agent wrapped environment.\n \"\"\"\n obs_spec: specs.Array = fake_multi_to_single_env.observation_spec()\n assert isinstance(obs_spec, specs.Array)\n assert obs_spec.shape == fake_multi_environment.observation_spec().shape","code_tokens":"","url":593946} +{"project_name":"kornia\/kornia","file_name":"hybrid_encoder.py","full_name":"AIFI.build_2d_sincos_pos_emb","func_name":"build_2d_sincos_pos_emb","docstring":"Construct 2D sin-cos positional embeddings.","docstring_tokens":"","code":"@staticmethod\ndef build_2d_sincos_pos_emb(w: int, h: int, embed_dim: int, temp: float=10000.0, device: Optional[torch.device]=None, dtype: Optional[torch.dtype]=None) -> Tensor:\n \"\"\"Construct 2D sin-cos positional embeddings.\n\n Args:\n w: width of the image or feature map\n h: height of the image or feature map\n embed_dim: embedding dimension\n temp: temperature coefficient\n device: device to place the positional embeddings\n dtype: data type of the positional embeddings\n\n Returns:\n positional embeddings, shape :math:`(H * W, 1, C)`\n \"\"\"\n xs = torch.arange(w, device=device, dtype=dtype)\n ys = torch.arange(h, device=device, dtype=dtype)\n (grid_x, grid_y) = torch.meshgrid(xs, ys, indexing='ij')\n pos_dim = embed_dim \/\/ 4\n omega = torch.arange(pos_dim, device=device, dtype=dtype) \/ pos_dim\n omega = 1.0 \/ temp ** omega\n out_x = grid_x.reshape(-1, 1) * omega.view(1, -1)\n out_y = grid_y.reshape(-1, 1) * omega.view(1, -1)\n pos_emb = concatenate([out_x.sin(), out_x.cos(), out_y.sin(), out_y.cos()], 1)\n return pos_emb.unsqueeze(1)","code_tokens":"","url":621629} +{"project_name":"rudranil723\/mini-main","file_name":"credentials.py","full_name":"ReadOnlyScoped.scopes","func_name":"scopes","docstring":"Sequence[str]: the credentials' current set of scopes.","docstring_tokens":"","code":"@property\ndef scopes(self):\n \"\"\"Sequence[str]: the credentials' current set of scopes.\"\"\"\n return self._scopes","code_tokens":"","url":317750} +{"project_name":"microsoft\/maro","file_name":"request_port.py","full_name":"get_acc_port_data","func_name":"get_acc_port_data","docstring":"Get the port data within a range.","docstring_tokens":"","code":"def get_acc_port_data(experiment_name: str, episode: str, start_tick: str, end_tick: str) -> json:\n \"\"\"Get the port data within a range.\n\n Args:\n experiment_name (str): Name of the experiment expected to be displayed.\n episode (str) : Number of the episode of expected data.\n start_tick (str): Number of tick to the start point of port data.\n end_tick(str): Number of tick to the end point of port data.\n\n Returns:\n json: Jsonified formatted port value through a selected range.\n\n \"\"\"\n input_range = get_input_range(start_tick, end_tick)\n query = f\"select {request_column.port_header.value} from {experiment_name}.port_details where episode='{episode}'\"\n if input_range != '()':\n query += f' and tick in {input_range}'\n params = {'query': query, 'count': 'true'}\n db_port_data = requests.get(url=request_settings.request_url.value, headers=request_settings.request_header.value, params=params).json()\n return process_port_data(db_port_data)","code_tokens":"","url":628314} +{"project_name":"deephyper\/deephyper","file_name":"_memory_storage.py","full_name":"MemoryStorage.store_job","func_name":"store_job","docstring":"Stores the value corresponding to key for job_id.","docstring_tokens":"","code":"def store_job(self, job_id: Hashable, key: Hashable, value: Any) -> None:\n \"\"\"Stores the value corresponding to key for job_id.\n\n Args:\n job_id (Hashable): The identifier of the job.\n key (Hashable): A key to use to store the value.\n value (Any): The value to store.\n \"\"\"\n (search_id, partial_id) = job_id.split('.')\n self._data[search_id]['data'][partial_id][key] = value","code_tokens":"","url":520818} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"decoder.py","full_name":"get_attention_bias","func_name":"get_attention_bias","docstring":"A helper function to get various attention bias tensors.","docstring_tokens":"","code":"def get_attention_bias(input_tensor, bias_type, padding_value=0, max_length=None):\n \"\"\"A helper function to get various attention bias tensors.\"\"\"\n if bias_type not in ('single_cross', 'multi_cross', 'decoder_self'):\n raise ValueError('Invalid attention bias type: %s' % bias_type)\n if bias_type == 'single_cross':\n length = tf_utils.get_shape_list(input_tensor, expected_rank=2)[1]\n bias = transformer_utils.get_padding_bias(input_tensor, padding_value=padding_value)\n elif bias_type == 'multi_cross':\n length = tf_utils.get_shape_list(input_tensor, expected_rank=3)[2]\n padding = transformer_utils.get_padding(input_tensor, padding_value=padding_value)\n bias = padding * -1000000000.0\n else:\n if max_length is not None:\n length = max_length\n else:\n length = tf_utils.get_shape_list(input_tensor, expected_rank=2)[1]\n bias = transformer_utils.get_decoder_self_attention_bias(length)\n return tf.where(bias < 0, tf.zeros_like(bias), tf.ones_like(bias))","code_tokens":"","url":850481} +{"project_name":"PaddlePaddle\/Paddle3D","file_name":"bbox.py","full_name":"rbbox2d_to_near_bbox","func_name":"rbbox2d_to_near_bbox","docstring":"convert rotated 2D bbox to nearest 'standing' or 'lying' bbox.","docstring_tokens":"","code":"def rbbox2d_to_near_bbox(rbboxes):\n \"\"\"convert rotated 2D bbox to nearest 'standing' or 'lying' bbox.\n Args:\n rbboxes: [N, 5(x, y, xdim, ydim, rad)] rotated bboxes\n Returns:\n bboxes: [N, 4(xmin, ymin, xmax, ymax)] bboxes\n \"\"\"\n rots = rbboxes[..., -1]\n rots = np.abs(BBoxes3D.limit_period(rots, 0.5, np.pi))\n cond = (rots > np.pi \/ 4)[..., np.newaxis]\n bboxes_center_dim = np.where(cond, rbboxes[:, [0, 1, 3, 2]], rbboxes[:, :4])\n (centers, dims) = (bboxes_center_dim[:, :2], bboxes_center_dim[:, 2:])\n bboxes = np.concatenate([centers - dims \/ 2, centers + dims \/ 2], axis=-1)\n return bboxes","code_tokens":"","url":777300} +{"project_name":"lixingjian\/DELTA","file_name":"utils.py","full_name":"prepare_vocab_from_config","func_name":"prepare_vocab_from_config","docstring":"Prepare vocab from config.","docstring_tokens":"","code":"def prepare_vocab_from_config(vocab_file_path, config, output_index=None):\n \"\"\"Prepare vocab from config.\"\"\"\n if output_index is None:\n label_config = config['data']['task']['classes']['vocab']\n else:\n label_config = config['data']['task']['classes'][output_index]['vocab']\n save_vocabs(label_config, vocab_file_path)","code_tokens":"","url":537394} +{"project_name":"Bismarrck\/kcon","file_name":"transformer.py","full_name":"Transformer.is_lj","func_name":"is_lj","docstring":"Return True if this transformer shall be used for LJ systems.","docstring_tokens":"","code":"@property\ndef is_lj(self):\n \"\"\"\n Return True if this transformer shall be used for LJ systems.\n \"\"\"\n return self._lj","code_tokens":"","url":247586} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"generic_regularizers.py","full_name":"NetworkRegularizer.get_regularization_term","func_name":"get_regularization_term","docstring":"Compute the regularization term.","docstring_tokens":"","code":"@abc.abstractmethod\ndef get_regularization_term(self, ops=None):\n \"\"\"Compute the regularization term.\n\n Args:\n ops: A list of tf.Operation objects. If specified, only the regularization\n term associated with the ops in `ops` will be returned. Otherwise, all\n relevant ops in the default TensorFlow graph will be included.\n\n Returns:\n A tf.Tensor scalar of floating point type that evaluates to the\n regularization term (that should be added to the total loss, with a\n suitable coefficient)\n \"\"\"\n pass","code_tokens":"","url":758222} +{"project_name":"ldkong1205\/LaserMix","file_name":"dfm.py","full_name":"DfM.with_neck_2d","func_name":"with_neck_2d","docstring":"Whether the detector has a 2D neck.","docstring_tokens":"","code":"@property\ndef with_neck_2d(self):\n \"\"\"Whether the detector has a 2D neck.\"\"\"\n return hasattr(self, 'neck_2d') and self.neck_2d is not None","code_tokens":"","url":624055} +{"project_name":"angsten\/pianonet","file_name":"custom_multitrack.py","full_name":"CustomMultitrack.pad_to_same","func_name":"pad_to_same","docstring":"Pad shorter pianorolls with zeros at the end along the time axis to make the resulting pianoroll lengths the same as the maximum pianoroll length among all the tracks.","docstring_tokens":"","code":"def pad_to_same(self):\n \"\"\"Pad shorter pianorolls with zeros at the end along the time axis to\n make the resulting pianoroll lengths the same as the maximum pianoroll\n length among all the tracks.\"\"\"\n max_length = self.get_max_length()\n for track in self.tracks:\n if track.pianoroll.shape[0] < max_length:\n track.pad(max_length - track.pianoroll.shape[0])","code_tokens":"","url":769391} +{"project_name":"ludwig-ai\/ludwig","file_name":"utils.py","full_name":"create_default_config","func_name":"create_default_config","docstring":"Create a Ludwig config that only contains input and output features.","docstring_tokens":"","code":"def create_default_config(experiment: Dict[str, Any]) -> str:\n \"\"\"Create a Ludwig config that only contains input and output features.\n\n Args:\n experiment: experiment dictionary.\n\n Returns:\n path where the default config is saved.\n \"\"\"\n model_config = model_configs_for_dataset(experiment['dataset_name'])['default']\n main_config_keys = list(model_config.keys())\n for key in main_config_keys:\n if key not in ['input_features', 'output_features']:\n del model_config[key]\n config_path = f\"{experiment['dataset_name']}-{uuid.uuid4().hex}.yaml\"\n save_yaml(config_path, model_config)\n return config_path","code_tokens":"","url":616543} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"estimator.py","full_name":"Estimator.train","func_name":"train","docstring":"Trains a model given training data `input_fn`.","docstring_tokens":"","code":"def train(self, input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None):\n \"\"\"Trains a model given training data `input_fn`.\n\n Args:\n input_fn: A function that provides input data for training as minibatches.\n See [Premade Estimators](\n https:\/\/tensorflow.org\/guide\/premade_estimators#create_input_functions)\n for more information. The function should construct and return one of\n the following: * A\n `tf.data.Dataset` object: Outputs of `Dataset` object must be a tuple\n `(features, labels)` with same constraints as below. * A tuple\n `(features, labels)`: Where `features` is a `tf.Tensor` or a dictionary\n of string feature name to `Tensor` and `labels` is a `Tensor` or a\n dictionary of string label name to `Tensor`. Both `features` and\n `labels` are consumed by `model_fn`. They should satisfy the expectation\n of `model_fn` from inputs.\n hooks: List of `tf.train.SessionRunHook` subclass instances. Used for\n callbacks inside the training loop.\n steps: Number of steps for which to train the model. If `None`, train\n forever or train until `input_fn` generates the `tf.errors.OutOfRange`\n error or `StopIteration` exception. `steps` works incrementally. If you\n call two times `train(steps=10)` then training occurs in total 20 steps.\n If `OutOfRange` or `StopIteration` occurs in the middle, training stops\n before 20 steps. If you don't want to have incremental behavior please\n set `max_steps` instead. If set, `max_steps` must be `None`.\n max_steps: Number of total steps for which to train model. If `None`,\n train forever or train until `input_fn` generates the\n `tf.errors.OutOfRange` error or `StopIteration` exception. If set,\n `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the\n middle, training stops before `max_steps` steps. Two calls to\n `train(steps=100)` means 200 training iterations. On the other hand, two\n calls to `train(max_steps=100)` means that the second call will not do\n any iteration since first call did all 100 steps.\n saving_listeners: list of `CheckpointSaverListener` objects. Used for\n callbacks that run immediately before or after checkpoint savings.\n\n Returns:\n `self`, for chaining.\n\n Raises:\n ValueError: If both `steps` and `max_steps` are not `None`.\n ValueError: If either `steps` or `max_steps <= 0`.\n \"\"\"\n if self.config.task_type in (run_config.TaskType.EVALUATOR, run_config.TaskType.PS):\n raise ValueError('Train has been called wrong configuration. Please use tf.estimator.train_and_evaluate which calls propper API according to given configuration. Current configuration: {}.'.format(self.config))\n with context.graph_mode():\n if steps is not None and max_steps is not None:\n raise ValueError('Can not provide both steps and max_steps.')\n if steps is not None and steps <= 0:\n raise ValueError('Must specify steps > 0, given: {}'.format(steps))\n if max_steps is not None and max_steps <= 0:\n raise ValueError('Must specify max_steps > 0, given: {}'.format(max_steps))\n if max_steps is not None:\n start_step = _load_global_step_from_checkpoint_dir(self._model_dir)\n if max_steps <= start_step:\n logging.info('Skipping training since max_steps has already saved.')\n return self\n hooks = _check_hooks_type(hooks)\n hooks.extend(self._convert_train_steps_to_hooks(steps, max_steps))\n saving_listeners = _check_listeners_type(saving_listeners)\n loss = self._train_model(input_fn, hooks, saving_listeners)\n logging.info('Loss for final step: %s.', loss)\n return self","code_tokens":"","url":336179} +{"project_name":"ZhangAoCanada\/RADDet","file_name":"batch_data_generator.py","full_name":"DataGenerator.readSequences","func_name":"readSequences","docstring":"Read sequences from train\/test directories.","docstring_tokens":"","code":"def readSequences(self, mode):\n \"\"\" Read sequences from train\/test directories. \"\"\"\n assert mode in ['train', 'test']\n if mode == 'train':\n sequences = glob.glob(os.path.join(self.config_data['train_set_dir'], 'RAD\/*\/*.npy'))\n else:\n sequences = glob.glob(os.path.join(self.config_data['test_set_dir'], 'RAD\/*\/*.npy'))\n if len(sequences) == 0:\n raise ValueError('Cannot read data from either train or test directory, Please double-check the data path or the data format.')\n return sequences","code_tokens":"","url":835728} +{"project_name":"pfnet\/pfrl","file_name":"empirical_normalization.py","full_name":"EmpiricalNormalization.forward","func_name":"forward","docstring":"Normalize mean and variance of values based on emprical values.","docstring_tokens":"","code":"def forward(self, x, update=True):\n \"\"\"Normalize mean and variance of values based on emprical values.\n\n Args:\n x (ndarray or Variable): Input values\n update (bool): Flag to learn the input values\n\n Returns:\n ndarray or Variable: Normalized output values\n \"\"\"\n if update:\n self.experience(x)\n normalized = (x - self._mean) * self._std_inverse\n if self.clip_threshold is not None:\n normalized = torch.clamp(normalized, -self.clip_threshold, self.clip_threshold)\n return normalized","code_tokens":"","url":304691} +{"project_name":"gunthercox\/ChatterBot","file_name":"fst.py","full_name":"BaseCursor.find_path","func_name":"find_path","docstring":"Follows the labels in the given path, starting at the current position.","docstring_tokens":"","code":"def find_path(self, path):\n \"\"\"Follows the labels in the given path, starting at the current\n position.\n \"\"\"\n path = to_labels(path)\n _switch_to = self.switch_to\n _follow = self.follow\n _stopped = self.stopped\n first = True\n for (i, label) in enumerate(path):\n if not first:\n _follow()\n if not _switch_to(label):\n return False\n if _stopped():\n if i < len(path) - 1:\n return False\n first = False\n return True","code_tokens":"","url":526636} +{"project_name":"aisingapore\/PeekingDuck","file_name":"node_template.py","full_name":"Node.run","func_name":"run","docstring":"This node does ___.","docstring_tokens":"","code":"def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"This node does ___.\n\n Args:\n inputs (dict): Dictionary with keys \"__\", \"__\".\n\n Returns:\n outputs (dict): Dictionary with keys \"__\".\n \"\"\"","code_tokens":"","url":766817} +{"project_name":"Farama-Foundation\/D4RL","file_name":"renderer.py","full_name":"DMRenderWindow.load_model","func_name":"load_model","docstring":"Loads the given Physics object to render.","docstring_tokens":"","code":"def load_model(self, physics):\n \"\"\"Loads the given Physics object to render.\"\"\"\n self._viewer.deinitialize()\n self._draw_surface = module.get_dm_render().Renderer(max_width=_MAX_RENDERBUFFER_SIZE, max_height=_MAX_RENDERBUFFER_SIZE)\n self._renderer = module.get_dm_viewer().renderer.OffScreenRenderer(physics.model, self._draw_surface)\n self._viewer.initialize(physics, self._renderer, touchpad=False)","code_tokens":"","url":126321} +{"project_name":"haruiz\/CvStudio","file_name":"async_utilities.py","full_name":"Worker.run","func_name":"run","docstring":"Initialise the runner function with passed args, kwargs.","docstring_tokens":"","code":"@pyqtSlot()\ndef run(self):\n \"\"\"\n Initialise the runner function with passed args, kwargs.\n \"\"\"\n try:\n result = self.fn(*self.args, **self.kwargs)\n except:\n traceback.print_exc()\n (exctype, value) = sys.exc_info()[:2]\n self.signals.error.emit((exctype, value, traceback.format_exc()))\n else:\n self.signals.result.emit(result)\n finally:\n self.signals.finished.emit()","code_tokens":"","url":523726} +{"project_name":"PaddlePaddle\/PARL","file_name":"cql.py","full_name":"CQL.learn","func_name":"learn","docstring":"Define the loss function and create an optimizer to minize the loss.","docstring_tokens":"","code":"def learn(self, obs, action, reward, next_obs, terminal):\n \"\"\" Define the loss function and create an optimizer to minize the loss.\n \"\"\"\n self._current_steps += 1\n (critic_loss, mse) = self._critic_learn(obs, action, reward, next_obs, terminal)\n (actor_loss, min_q) = self._actor_learn(obs, action)\n self.sync_target()\n return (critic_loss, mse, actor_loss, min_q)","code_tokens":"","url":277889} +{"project_name":"abrarrhine\/Artificial-Intelligence-PacmanGames","file_name":"capture.py","full_name":"GameState.getInitialAgentPosition","func_name":"getInitialAgentPosition","docstring":"Returns the initial position of an agent.","docstring_tokens":"","code":"def getInitialAgentPosition(self, agentIndex):\n \"\"\"Returns the initial position of an agent.\"\"\"\n return self.data.layout.agentPositions[agentIndex][1]","code_tokens":"","url":90921} +{"project_name":"deepmind\/dm_control","file_name":"dog.py","full_name":"Physics.torso_pelvis_height","func_name":"torso_pelvis_height","docstring":"Returns the height of the torso.","docstring_tokens":"","code":"def torso_pelvis_height(self):\n \"\"\"Returns the height of the torso.\"\"\"\n return self.named.data.xpos[['torso', 'pelvis'], 'z']","code_tokens":"","url":165414} +{"project_name":"synsense\/sinabs","file_name":"test_from_model.py","full_name":"test_network_conversion_complicated_model","func_name":"test_network_conversion_complicated_model","docstring":"Try converting rather complicated network model with nested structures, which used to fail before.","docstring_tokens":"","code":"def test_network_conversion_complicated_model():\n \"\"\"Try converting rather complicated network model with nested structures, which used to fail\n before.\"\"\"\n ann = nn.Sequential(nn.Conv2d(1, 1, 1), nn.Sequential(nn.AvgPool2d(2), nn.ReLU(), nn.Conv2d(1, 1, 1)), nn.ReLU(), nn.AvgPool2d(3), nn.Sequential(nn.Conv2d(1, 1, 2), nn.Sequential(nn.Flatten(), nn.Linear(400, 12))))\n snn = from_model(ann, batch_size=1)","code_tokens":"","url":884385} +{"project_name":"BerkeleyLearnVerify\/VerifAI","file_name":"utils.py","full_name":"random_translate","func_name":"random_translate","docstring":"Randomly shift the image virtially and horizontally (translation).","docstring_tokens":"","code":"def random_translate(image, steering_angle, range_x, range_y):\n \"\"\"\n Randomly shift the image virtially and horizontally (translation).\n \"\"\"\n trans_x = range_x * (np.random.rand() - 0.5)\n trans_y = range_y * (np.random.rand() - 0.5)\n steering_angle += trans_x * 0.002\n trans_m = np.float32([[1, 0, trans_x], [0, 1, trans_y]])\n (height, width) = image.shape[:2]\n image = cv2.warpAffine(image, trans_m, (width, height))\n return (image, steering_angle)","code_tokens":"","url":379294} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"ncf_input_pipeline.py","full_name":"create_dataset_from_data_producer","func_name":"create_dataset_from_data_producer","docstring":"Return dataset online-generating data.","docstring_tokens":"","code":"def create_dataset_from_data_producer(producer, params):\n \"\"\"Return dataset online-generating data.\"\"\"\n\n def preprocess_train_input(features, labels):\n \"\"\"Pre-process the training data.\n\n This is needed because\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for DUPLICATE_MASK in training data.\n\n Args:\n features: Dictionary of features for training.\n labels: Training labels.\n\n Returns:\n Processed training features.\n \"\"\"\n fake_dup_mask = tf.zeros_like(features[movielens.USER_COLUMN])\n features[rconst.DUPLICATE_MASK] = fake_dup_mask\n features[rconst.TRAIN_LABEL_KEY] = labels\n return features\n train_input_fn = producer.make_input_fn(is_training=True)\n train_input_dataset = train_input_fn(params).map(preprocess_train_input)\n\n def preprocess_eval_input(features):\n \"\"\"Pre-process the eval data.\n\n This is needed because:\n - The label needs to be extended to be used in the loss fn\n - We need the same inputs for training and eval so adding fake inputs\n for VALID_PT_MASK in eval data.\n\n Args:\n features: Dictionary of features for evaluation.\n\n Returns:\n Processed evaluation features.\n \"\"\"\n labels = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)\n fake_valid_pt_mask = tf.cast(tf.zeros_like(features[movielens.USER_COLUMN]), tf.bool)\n features[rconst.VALID_POINT_MASK] = fake_valid_pt_mask\n features[rconst.TRAIN_LABEL_KEY] = labels\n return features\n eval_input_fn = producer.make_input_fn(is_training=False)\n eval_input_dataset = eval_input_fn(params).map(preprocess_eval_input)\n return (train_input_dataset, eval_input_dataset)","code_tokens":"","url":850697} +{"project_name":"IntelAI\/transfer-learning","file_name":"pytorch_image_anomaly_detection_model.py","full_name":"PyTorchImageAnomalyDetectionModel.train_cutpaste","func_name":"train_cutpaste","docstring":"Trains a CutPaste model using the specified dataset.","docstring_tokens":"","code":"def train_cutpaste(self, dataset, output_dir, optim, epochs, freeze_resnet, head_layer, cutpaste_type, initial_checkpoints=None, generate_checkpoints=False, precision='float32'):\n \"\"\"\n Trains a CutPaste model using the specified dataset.\n\n Args:\n dataset (str): Dataset to use when training the model\n output_dir (str): Path to a writeable directory for output files\n optim (str): Choice of optimizer to use for training\n epochs (int): Number of epochs to train the model\n freeze_resnet (int): Epochs upto which we freeze ResNet layers\n and only train the new header with FC layers\n head_layer (int): number of layers in the projection head\n cutpaste-type (str): cutpaste variant to use\n initial_checkpoints (str): path for feature extractor model\n generate_checkpoints (bool): Whether to save\/preserve the best weights during\n SimSiam or CutPaste training, default is False.\n precision (str): precision in which model to be trained, default is float32.\n\n Returns:\n Model object\n\n \"\"\"\n self.variant_map = {'normal': CutPasteNormal, 'scar': CutPasteScar, '3way': CutPaste3Way, 'union': CutPasteUnion}\n variant = self.variant_map[cutpaste_type]\n self.cutpaste = True\n dataset._dataset.transform = dataset._cutpaste_transform\n dataloader = dataset._train_loader\n valid_model_name = validate_model_name(self.model_name)\n checkpoint_dir = os.path.join(output_dir, '{}_checkpoints'.format(valid_model_name))\n verify_directory(checkpoint_dir)\n if initial_checkpoints is None:\n print(\"=> creating CUT-PASTE feature extractor with the backbone of'{}'\".format(self.model_name))\n head_layers = [512] * head_layer + [128]\n num_classes = 2 if variant is not CutPaste3Way else 3\n self._model = ProjectionNet(model_name=self.model_name, pretrained=True, head_layers=head_layers, num_classes=num_classes)\n self._model.to(self._device)\n if freeze_resnet > 0:\n self._model.freeze_resnet()\n criterion = torch.nn.CrossEntropyLoss()\n weight_decay = 3e-05\n momentum = 0.9\n if optim == 'sgd':\n optimizer = torch.optim.SGD(self._model.parameters(), lr=0.03, momentum=momentum, weight_decay=weight_decay)\n scheduler = lr_scheduler.CosineAnnealingWarmRestarts(optimizer, epochs)\n elif optim == 'adam':\n optimizer = torch.optim.Adam(self._model.parameters(), lr=0.03, weight_decay=weight_decay)\n scheduler = None\n else:\n print(f'ERROR unkown optimizer: {optim}')\n num_images = len(dataset.train_subset)\n best_least_Loss = float('inf')\n is_best_ans = False\n file_name_least_loss = ''\n print('Fine-tuning CUT-PASTE Model on ', epochs, 'epochs using ', num_images, ' training images')\n self._model.train()\n (model, optimizer) = ipex.optimize(self._model, optimizer=optimizer, dtype=torch.bfloat16 if precision == 'bfloat16' else torch.float32)\n for step in range(epochs):\n epoch = int(step \/ 1)\n curr_loss = utils._fit_cutpaste(dataloader, model, criterion, optimizer, epoch, freeze_resnet, scheduler, precision)\n if generate_checkpoints:\n if curr_loss < best_least_Loss:\n best_least_Loss = curr_loss\n is_best_ans = True\n file_name_least_loss = 'cutpaste_checkpoint_{:04d}.pth.tar'.format(step)\n utils.save_checkpoint({'epoch': step + 1, 'arch': self.model_name, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}, is_best=is_best_ans, filename=file_name_least_loss, loss=best_least_Loss, checkpoint_dir=checkpoint_dir)\n is_best_ans = False\n elif epoch == epochs - 1:\n file_name_least_loss = 'cutpaste_checkpoint_{:04d}.pth.tar'.format(step)\n utils.save_checkpoint({'epoch': step + 1, 'arch': self.model_name, 'state_dict': model.state_dict()}, is_best=True, filename=file_name_least_loss, loss=curr_loss, checkpoint_dir=checkpoint_dir)\n self._model = self.load_checkpoint_weights(self.model_name, checkpoint_dir, file_name_least_loss, feature_extractor='cutpaste')\n else:\n models = []\n for filename in os.listdir(initial_checkpoints):\n f = os.path.join(initial_checkpoints, filename)\n if os.path.isfile(f) and self.cutpaste:\n models.append(f)\n model_path = os.path.basename(max(models, key=os.path.getctime))\n self._model = self.load_checkpoint_weights(self.model_name, checkpoint_dir, model_path, feature_extractor='cutpaste')\n return self._model","code_tokens":"","url":928201} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"models.py","full_name":"create_model","func_name":"create_model","docstring":"A factory function to create different types of models.","docstring_tokens":"","code":"@gin.configurable\ndef create_model(model_type: Text, params, init_checkpoint: Optional[Text]=None):\n \"\"\"A factory function to create different types of models.\"\"\"\n if model_type == 'bert2bert':\n return create_bert2bert_model(params, init_checkpoint=init_checkpoint)\n elif model_type == 'nhnet':\n return create_nhnet_model(params, init_checkpoint=init_checkpoint)\n elif 'transformer' in model_type:\n return create_transformer_model(params, init_checkpoint=init_checkpoint)\n else:\n raise KeyError('The model type is not defined: %s' % model_type)","code_tokens":"","url":850508} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"screen.py","full_name":"screen.scroll_up","func_name":"scroll_up","docstring":"Scroll display up one line.","docstring_tokens":"","code":"def scroll_up(self):\n \"\"\"Scroll display up one line.\"\"\"\n s = self.scroll_row_start - 1\n e = self.scroll_row_end - 1\n self.w[s:e] = copy.deepcopy(self.w[s + 1:e + 1])","code_tokens":"","url":74608} +{"project_name":"netket\/netket","file_name":"_utils_tree.py","full_name":"tree_ishomogeneous","func_name":"tree_ishomogeneous","docstring":"Returns true if all leaves have real dtype or all leaves have complex dtype.","docstring_tokens":"","code":"def tree_ishomogeneous(pars: PyTree) -> bool:\n \"\"\"\n Returns true if all leaves have real dtype or all leaves have complex dtype.\n \"\"\"\n return not (tree_leaf_isreal(pars) and tree_leaf_iscomplex(pars))","code_tokens":"","url":736105} +{"project_name":"RasaHQ\/rasa","file_name":"test.py","full_name":"EvaluationStore.add_to_store","func_name":"add_to_store","docstring":"Add items or lists of items to the store.","docstring_tokens":"","code":"def add_to_store(self, action_predictions: Optional[PredictionList]=None, action_targets: Optional[PredictionList]=None, intent_predictions: Optional[PredictionList]=None, intent_targets: Optional[PredictionList]=None, entity_predictions: Optional[List['EntityPrediction']]=None, entity_targets: Optional[List['EntityPrediction']]=None) -> None:\n \"\"\"Add items or lists of items to the store.\"\"\"\n self.action_predictions.extend(action_predictions or [])\n self.action_targets.extend(action_targets or [])\n self.intent_targets.extend(intent_targets or [])\n self.intent_predictions.extend(intent_predictions or [])\n self.entity_predictions.extend(entity_predictions or [])\n self.entity_targets.extend(entity_targets or [])","code_tokens":"","url":836719} +{"project_name":"OctoConsulting\/octobot","file_name":"create_azure_knowledge_base.py","full_name":"convert_to_title","func_name":"convert_to_title","docstring":"Formats string as a title, such that the input string has no punctuation, is titlecased, and has no whitespace.","docstring_tokens":"","code":"def convert_to_title(s: str) -> str:\n \"\"\"Formats string as a title, such that the input string has no punctuation,\n is titlecased, and has no whitespace.\n\n Args:\n s: any string.\n\n Returns:\n The input string as a title.\n \"\"\"\n s = s.translate(s.maketrans('', '', string.punctuation))\n s = s.title()\n s = s.translate(s.maketrans('', '', string.whitespace))\n return s","code_tokens":"","url":249976} +{"project_name":"robustness-gym\/robustness-gym","file_name":"mandoline.py","full_name":"log_density_ratio","func_name":"log_density_ratio","docstring":"Calculate the log density ratio for a solved Mandoline run.","docstring_tokens":"","code":"def log_density_ratio(D, solved):\n \"\"\"Calculate the log density ratio for a solved Mandoline run.\"\"\"\n Phi_D = Phi(D, None)\n return Phi_D.dot(solved.opt.x) + log_partition_ratio(solved.opt.x, solved.Phi_D_src, solved.n_src)","code_tokens":"","url":826234} +{"project_name":"Katja-M\/Python_NaturalLanguageProcessing","file_name":"afm.py","full_name":"AFM.get_str_bbox_and_descent","func_name":"get_str_bbox_and_descent","docstring":"Return the string bounding box and the maximal descent.","docstring_tokens":"","code":"def get_str_bbox_and_descent(self, s):\n \"\"\"Return the string bounding box and the maximal descent.\"\"\"\n if not len(s):\n return (0, 0, 0, 0, 0)\n total_width = 0\n namelast = None\n miny = 1000000000.0\n maxy = 0\n left = 0\n if not isinstance(s, str):\n s = _to_str(s)\n for c in s:\n if c == '\\n':\n continue\n name = uni2type1.get(ord(c), 'question')\n try:\n (wx, _, bbox) = self._metrics_by_name[name]\n except KeyError:\n name = 'question'\n (wx, _, bbox) = self._metrics_by_name[name]\n total_width += wx + self._kern.get((namelast, name), 0)\n (l, b, w, h) = bbox\n left = min(left, l)\n miny = min(miny, b)\n maxy = max(maxy, b + h)\n namelast = name\n return (left, miny, total_width, maxy - miny, -miny)","code_tokens":"","url":864078} +{"project_name":"triaquae\/triaquae","file_name":"loader.py","full_name":"BaseLoader.load_template_source","func_name":"load_template_source","docstring":"Returns a tuple containing the source and origin for the given template name.","docstring_tokens":"","code":"def load_template_source(self, template_name, template_dirs=None):\n \"\"\"\n Returns a tuple containing the source and origin for the given template\n name.\n\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":423876} +{"project_name":"rudranil723\/mini-main","file_name":"_regex_core.py","full_name":"parse_fuzzy_compare","func_name":"parse_fuzzy_compare","docstring":"Parses a cost comparator.","docstring_tokens":"","code":"def parse_fuzzy_compare(source):\n \"\"\"Parses a cost comparator.\"\"\"\n if source.match('<='):\n return True\n elif source.match('<'):\n return False\n else:\n return None","code_tokens":"","url":269790} +{"project_name":"rudranil723\/mini-main","file_name":"interface.py","full_name":"InterfaceClass.names","func_name":"names","docstring":"Return the attribute names defined by the interface.","docstring_tokens":"","code":"def names(self, all=False):\n \"\"\"Return the attribute names defined by the interface.\"\"\"\n if not all:\n return self.__attrs.keys()\n r = self.__attrs.copy()\n for base in self.__bases__:\n r.update(dict.fromkeys(base.names(all)))\n return r.keys()","code_tokens":"","url":271330} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"test_bundler_tools.py","full_name":"TestBundlerTools.test_get_cell_reference_patterns_precode","func_name":"test_get_cell_reference_patterns_precode","docstring":"Should find no references in a fenced code block in a *code* cell.","docstring_tokens":"","code":"def test_get_cell_reference_patterns_precode(self):\n \"\"\"Should find no references in a fenced code block in a *code* cell.\"\"\"\n self.assertTrue(tools.get_cell_reference_patterns)\n no_references = tools.get_cell_reference_patterns({'source': '```\\nfoo\\nbar\\nbaz\\n```\\n', 'cell_type': 'code'})\n self.assertEqual(len(no_references), 0)","code_tokens":"","url":2194} +{"project_name":"RasaHQ\/rasa","file_name":"processor.py","full_name":"MessageProcessor.should_predict_another_action","func_name":"should_predict_another_action","docstring":"Determine whether the processor should predict another action.","docstring_tokens":"","code":"@staticmethod\ndef should_predict_another_action(action_name: Text) -> bool:\n \"\"\"Determine whether the processor should predict another action.\n\n Args:\n action_name: Name of the latest executed action.\n\n Returns:\n `False` if `action_name` is `ACTION_LISTEN_NAME` or\n `ACTION_SESSION_START_NAME`, otherwise `True`.\n \"\"\"\n return action_name not in (ACTION_LISTEN_NAME, ACTION_SESSION_START_NAME)","code_tokens":"","url":836710} +{"project_name":"AIZOOTech\/object-detection-anchors","file_name":"example.py","full_name":"show_width_height","func_name":"show_width_height","docstring":"Display bouding box distribution with histgram.","docstring_tokens":"","code":"def show_width_height(data, cluster, bins=50):\n \"\"\"\n\tDisplay bouding box distribution with histgram.\n\t\"\"\"\n if data.dtype != np.float32:\n data = data.astype(np.float32)\n width = data[:, 0]\n height = data[:, 1]\n ratio = height \/ width\n plt.figure(1, figsize=(20, 6))\n plt.subplot(131)\n plt.hist(width, bins=bins, color='green')\n plt.xlabel('width')\n plt.ylabel('number')\n plt.title('Distribution of Width')\n plt.subplot(132)\n plt.hist(height, bins=bins, color='blue')\n plt.xlabel('Height')\n plt.ylabel('Number')\n plt.title('Distribution of Height')\n plt.subplot(133)\n plt.hist(ratio, bins=bins, color='magenta')\n plt.xlabel('Height \/ Width')\n plt.ylabel('number')\n plt.title('Distribution of aspect ratio(Height \/ Width)')\n plt.savefig('shape-distribution.png')\n plt.show()","code_tokens":"","url":725745} +{"project_name":"DeepLearnXMU\/ABDNMT-RNMT","file_name":"__init__.py","full_name":"register_lr_scheduler","func_name":"register_lr_scheduler","docstring":"Decorator to register a new LR scheduler.","docstring_tokens":"","code":"def register_lr_scheduler(name):\n \"\"\"Decorator to register a new LR scheduler.\"\"\"\n\n def register_lr_scheduler_cls(cls):\n if name in LR_SCHEDULER_REGISTRY:\n raise ValueError('Cannot register duplicate LR scheduler ({})'.format(name))\n if not issubclass(cls, FairseqLRScheduler):\n raise ValueError('LR Scheduler ({}: {}) must extend FairseqLRScheduler'.format(name, cls.__name__))\n LR_SCHEDULER_REGISTRY[name] = cls\n return cls\n return register_lr_scheduler_cls","code_tokens":"","url":6392} +{"project_name":"EducationalTestingService\/skll","file_name":"test_classification.py","full_name":"TestClassification.test_test_file_and_test_directory","func_name":"test_test_file_and_test_directory","docstring":"Test that test_file + test_directory = ValueError.","docstring_tokens":"","code":"def test_test_file_and_test_directory(self):\n \"\"\"Test that test_file + test_directory = ValueError.\"\"\"\n config_path = fill_in_config_paths_for_single_file(config_dir \/ 'test_single_file.template.cfg', train_dir \/ 'train_single_file.jsonlines', test_dir \/ 'test_single_file.jsonlines', test_directory='foo')\n with self.assertRaises(ValueError):\n parse_config_file(config_path)","code_tokens":"","url":885031} +{"project_name":"rudranil723\/mini-main","file_name":"layout_engine.py","full_name":"LayoutEngine.execute","func_name":"execute","docstring":"Execute the layout on the figure given by *fig*.","docstring_tokens":"","code":"def execute(self, fig):\n \"\"\"\n Execute the layout on the figure given by *fig*.\n \"\"\"\n raise NotImplementedError","code_tokens":"","url":319518} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"utils.py","full_name":"RouletteWheel.is_empty","func_name":"is_empty","docstring":"Returns whether there is anything in the roulette wheel.","docstring_tokens":"","code":"def is_empty(self):\n \"\"\"Returns whether there is anything in the roulette wheel.\"\"\"\n return not self.partial_sums","code_tokens":"","url":46315} +{"project_name":"akandykeller\/NeuralWaveMachines","file_name":"hamiltonian.py","full_name":"HamiltonianSystem.sample_y","func_name":"sample_y","docstring":"Samples randomly initial states.","docstring_tokens":"","code":"@abc.abstractmethod\ndef sample_y(self, num_samples: int, params: utils.Params, rng_key: jnp.ndarray, **kwargs: Any) -> phase_space.PhaseSpace:\n \"\"\"Samples randomly initial states.\"\"\"","code_tokens":"","url":293562} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_k_means.py","full_name":"test_kmeans_dba","func_name":"test_kmeans_dba","docstring":"Test implementation of Kmeans using dba.","docstring_tokens":"","code":"@pytest.mark.skipif(not _check_estimator_deps(TimeSeriesKMeans, severity='none'), reason='skip test if required soft dependencies not available')\ndef test_kmeans_dba():\n \"\"\"Test implementation of Kmeans using dba.\"\"\"\n (X_train, y_train) = load_basic_motions(split='train')\n (X_test, y_test) = load_basic_motions(split='test')\n num_test_values = 5\n kmeans = TimeSeriesKMeans(averaging_method='ba', random_state=1, n_init=2, n_clusters=2, init_algorithm='kmeans++', distance='dtw')\n train_predict = kmeans.fit_predict(X_train[0:num_test_values])\n train_mean_score = metrics.rand_score(y_train[0:num_test_values], train_predict)\n test_mean_result = kmeans.predict(X_test[0:num_test_values])\n mean_score = metrics.rand_score(y_test[0:num_test_values], test_mean_result)\n proba = kmeans.predict_proba(X_test[0:num_test_values])\n assert np.array_equal(test_mean_result, expected_results['dba'])\n assert mean_score == expected_score['dba']\n assert train_mean_score == expected_train_result['dba']\n assert kmeans.n_iter_ == expected_iters['dba']\n assert np.array_equal(kmeans.labels_, expected_labels['dba'])\n assert isinstance(kmeans.cluster_centers_, np.ndarray)\n assert proba.shape == (5, 2)\n for val in proba:\n assert np.count_nonzero(val == 1.0) == 1","code_tokens":"","url":399337} +{"project_name":"aqeelanwar\/PEDRA","file_name":"transformations.py","full_name":"is_same_quaternion","func_name":"is_same_quaternion","docstring":"Return True if two quaternions are equal.","docstring_tokens":"","code":"def is_same_quaternion(q0, q1):\n \"\"\"Return True if two quaternions are equal.\"\"\"\n q0 = numpy.array(q0)\n q1 = numpy.array(q1)\n return numpy.allclose(q0, q1) or numpy.allclose(q0, -q1)","code_tokens":"","url":279633} +{"project_name":"nancheng58\/Self-supervised-learning-for-Sequential-Recommender-Systems","file_name":"dataset.py","full_name":"Dataset.set_field_property","func_name":"set_field_property","docstring":"Set a new field's properties.","docstring_tokens":"","code":"def set_field_property(self, field, field_type, field_source, field_seqlen):\n \"\"\"Set a new field's properties.\n\n Args:\n field (str): Name of the new field.\n field_type (FeatureType): Type of the new field.\n field_source (FeatureSource): Source of the new field.\n field_seqlen (int): max length of the sequence in ``field``.\n ``1`` if ``field``'s type is not sequence-like.\n \"\"\"\n self.field2type[field] = field_type\n self.field2source[field] = field_source\n self.field2seqlen[field] = field_seqlen","code_tokens":"","url":341796} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"scripting.py","full_name":"RexxLexer.analyse_text","func_name":"analyse_text","docstring":"Check for inital comment and patterns that distinguish Rexx from other C-like languages.","docstring_tokens":"","code":"def analyse_text(text):\n \"\"\"\n Check for inital comment and patterns that distinguish Rexx from other\n C-like languages.\n \"\"\"\n if re.search('\/\\\\*\\\\**\\\\s*rexx', text, re.IGNORECASE):\n return 1.0\n elif text.startswith('\/*'):\n lowerText = text.lower()\n result = sum((weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText))) + 0.01\n return min(result, 1.0)","code_tokens":"","url":20977} +{"project_name":"famura\/SimuRLacra","file_name":"base.py","full_name":"EnvWrapper.wrapped_env","func_name":"wrapped_env","docstring":"Get the wrapped environment of this wrapper.","docstring_tokens":"","code":"@property\ndef wrapped_env(self) -> Env:\n \"\"\"Get the wrapped environment of this wrapper.\"\"\"\n return self._wrapped_env","code_tokens":"","url":883705} +{"project_name":"thaines\/helit","file_name":"corpus.py","full_name":"Corpus.setCalcPhi","func_name":"setCalcPhi","docstring":"Set False to have phi constant as the algorithm runs, leave True if you want it recalculated based on the cluster multinomials over behaviour drawn from it.","docstring_tokens":"","code":"def setCalcPhi(self, val):\n \"\"\"Set False to have phi constant as the algorithm runs, leave True if you want it recalculated based on the cluster multinomials over behaviour drawn from it.\"\"\"\n self.calcPhi = val","code_tokens":"","url":590970} +{"project_name":"yihui-he\/KL-Loss","file_name":"dummy_datasets.py","full_name":"get_coco_dataset","func_name":"get_coco_dataset","docstring":"A dummy COCO dataset that includes only the 'classes' field.","docstring_tokens":"","code":"def get_coco_dataset():\n \"\"\"A dummy COCO dataset that includes only the 'classes' field.\"\"\"\n ds = AttrDict()\n classes = ['__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']\n ds.classes = {i: name for (i, name) in enumerate(classes)}\n return ds","code_tokens":"","url":596484} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"_base.py","full_name":"_AxesBase.minorticks_on","func_name":"minorticks_on","docstring":"Add autoscaling minor ticks to the axes.","docstring_tokens":"","code":"def minorticks_on(self):\n \"\"\"Add autoscaling minor ticks to the axes.\"\"\"\n for ax in (self.xaxis, self.yaxis):\n scale = ax.get_scale()\n if scale == 'log':\n s = ax._scale\n ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))\n elif scale == 'symlog':\n s = ax._scale\n ax.set_minor_locator(mticker.SymmetricalLogLocator(s._transform, s.subs))\n else:\n ax.set_minor_locator(mticker.AutoMinorLocator())","code_tokens":"","url":716334} +{"project_name":"replit-archive\/empythoned","file_name":"AutoComplete.py","full_name":"AutoComplete.force_open_completions_event","func_name":"force_open_completions_event","docstring":"Happens when the user really wants to open a completion list, even if a function call is needed.","docstring_tokens":"","code":"def force_open_completions_event(self, event):\n \"\"\"Happens when the user really wants to open a completion list, even\n if a function call is needed.\n \"\"\"\n self.open_completions(True, False, True)","code_tokens":"","url":176679} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"ops.py","full_name":"decode_image","func_name":"decode_image","docstring":"Decodes images in a tensor dict.","docstring_tokens":"","code":"def decode_image(tensor_dict):\n \"\"\"Decodes images in a tensor dict.\"\"\"\n tensor_dict[fields.InputDataFields.image] = tf.io.decode_image(tensor_dict[fields.InputDataFields.image], channels=3)\n tensor_dict[fields.InputDataFields.image].set_shape([None, None, 3])\n return tensor_dict","code_tokens":"","url":831000} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"hasresponses.py","full_name":"Response.deactivate","func_name":"deactivate","docstring":"Remove this response from the dependency graph and remove its pseudocomp from the scoping object.","docstring_tokens":"","code":"def deactivate(self):\n \"\"\"Remove this response from the dependency graph and remove\n its pseudocomp from the scoping object.\n \"\"\"\n if self._pseudo is not None:\n scope = self.scope\n try:\n getattr(scope, self._pseudo.name)\n except AttributeError:\n pass\n else:\n scope.remove(self._pseudo.name)","code_tokens":"","url":275838} +{"project_name":"gunthercox\/ChatterBot","file_name":"ma.py","full_name":"maximum_fill_value","func_name":"maximum_fill_value","docstring":"Function to calculate default fill value suitable for taking maxima.","docstring_tokens":"","code":"def maximum_fill_value(obj):\n \"\"\"Function to calculate default fill value suitable for taking maxima.\"\"\"\n if isinstance(obj, float):\n return -inf\n elif isinstance(obj, int) or isinstance(obj, long):\n return -_MAXINT\n elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):\n x = obj.dtype.char\n if x in typecodes['Float']:\n return -inf\n if x in typecodes['Integer']:\n return -_MAXINT\n if x in typecodes['UnsignedInteger']:\n return 0\n else:\n raise TypeError('Unsuitable type for calculating maximum.')","code_tokens":"","url":532372} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"seq2seq_transformer.py","full_name":"TransformerEncoder.call","func_name":"call","docstring":"Return the output of the encoder.","docstring_tokens":"","code":"def call(self, encoder_inputs, attention_mask=None):\n \"\"\"Return the output of the encoder.\n\n Args:\n encoder_inputs: tensor with shape [batch_size, input_length, hidden_size]\n attention_mask: mask for the encoder self-attention layer. [batch_size,\n input_length, input_length]\n\n Returns:\n Output of encoder.\n float32 tensor with shape [batch_size, input_length, hidden_size]\n \"\"\"\n for layer_idx in range(self.num_layers):\n encoder_inputs = self.encoder_layers[layer_idx]([encoder_inputs, attention_mask])\n output_tensor = encoder_inputs\n output_tensor = self.output_normalization(output_tensor)\n return output_tensor","code_tokens":"","url":850431} +{"project_name":"marysia\/thesis","file_name":"visualize.py","full_name":"array_to_png_folder","func_name":"array_to_png_folder","docstring":"Saves each slice as a png in a folder.","docstring_tokens":"","code":"def array_to_png_folder(array, folder_name):\n \"\"\"\n Saves each slice as a png in a folder.\n\n Args:\n array: np.array of lung nodule\n folder_name: str, where the pngs will be saved.\n \"\"\"\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n for i in xrange(array.shape[0]):\n img = array[i]\n fname = str(i) + '.png' if i > 9 else '0' + str(i) + '.png'\n fname = os.path.join(folder_name, fname)\n cv2.imwrite(fname, img)","code_tokens":"","url":354750} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"seq_example_util.py","full_name":"context_bytes_feature","func_name":"context_bytes_feature","docstring":"Converts a numpy bytes array to a context bytes feature.","docstring_tokens":"","code":"def context_bytes_feature(ndarray):\n \"\"\"Converts a numpy bytes array to a context bytes feature.\n\n Args:\n ndarray: A numpy bytes array.\n\n Returns:\n A context bytes feature.\n \"\"\"\n feature = tf.train.Feature()\n for val in ndarray:\n if isinstance(val, np.ndarray):\n val = val.tolist()\n feature.bytes_list.value.append(tf.compat.as_bytes(val))\n return feature","code_tokens":"","url":974958} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"test_buffer.py","full_name":"iter_format","func_name":"iter_format","docstring":"Yield (format, items, item) for all possible modes and format characters plus one random compound format string.","docstring_tokens":"","code":"def iter_format(nitems, testobj='ndarray'):\n \"\"\"Yield (format, items, item) for all possible modes and format\n characters plus one random compound format string.\"\"\"\n for t in iter_mode(nitems, testobj):\n yield t\n if testobj != 'ndarray':\n return\n yield struct_items(nitems, testobj)","code_tokens":"","url":283224} +{"project_name":"unixpickle\/anyrl-py","file_name":"test_dists.py","full_name":"test_box_beta_log_prob","func_name":"test_box_beta_log_prob","docstring":"Test log probs for known situations of BoxBeta.","docstring_tokens":"","code":"def test_box_beta_log_prob():\n \"\"\"\n Test log probs for known situations of BoxBeta.\n \"\"\"\n with tf.Graph().as_default():\n with tf.Session() as sess:\n dist = BoxBeta(np.array([[0], [-2]]), np.array([[1], [3]]), softplus=False)\n actual = sess.run(dist.log_prob(np.array([[[0.1, 0.5]], [[0.3, 0.7]]]), np.array([[0.4], [-0.5]])))\n expected = np.array([_beta_log_prob(0.1, 0.5, 0.4), _beta_log_prob(0.3, 0.7, 0.3) - np.log(5)])\n assert np.allclose(actual, expected, atol=0.0001)","code_tokens":"","url":33699} +{"project_name":"CEA-LIST\/SCE","file_name":"gather.py","full_name":"concat_all_gather_without_backprop","func_name":"concat_all_gather_without_backprop","docstring":"Gather tensor across devices without grad.","docstring_tokens":"","code":"@torch.no_grad()\ndef concat_all_gather_without_backprop(x: Tensor, dim: int=0) -> Tensor:\n \"\"\"Gather tensor across devices without grad.\n\n Args:\n x (Tensor): Tensor to gather.\n dim (int): Dimension to concat. Defaults to 0.\n\n Returns:\n Tensor: Gathered tensor.\n \"\"\"\n if dist.is_available() and dist.is_initialized():\n tensors_gather = [torch.ones_like(x) for _ in range(torch.distributed.get_world_size())]\n torch.distributed.all_gather(tensors_gather, x, async_op=False)\n output = torch.cat(tensors_gather, dim=dim)\n else:\n output = x\n return output","code_tokens":"","url":329461} +{"project_name":"eth-sri\/debin","file_name":"segments.py","full_name":"Segment.data","func_name":"data","docstring":"The segment data from the file.","docstring_tokens":"","code":"def data(self):\n \"\"\" The segment data from the file.\n \"\"\"\n self.stream.seek(self['p_offset'])\n return self.stream.read(self['p_filesz'])","code_tokens":"","url":516628} +{"project_name":"devashish-patel\/webcam-motion-detector","file_name":"ioloop.py","full_name":"install","func_name":"install","docstring":"DEPRECATED pyzmq 17 no longer needs any special integration for tornado.","docstring_tokens":"","code":"def install():\n \"\"\"DEPRECATED\n\n pyzmq 17 no longer needs any special integration for tornado.\n \"\"\"\n _deprecated()\n ioloop.IOLoop.configure(ZMQIOLoop)","code_tokens":"","url":985478} +{"project_name":"ludwig-ai\/ludwig","file_name":"preprocessing.py","full_name":"build_dataset","func_name":"build_dataset","docstring":"Builds a dataset from a dataframe and a list of features.","docstring_tokens":"","code":"def build_dataset(config, dataset_df, features, global_preprocessing_parameters, mode, metadata=None, backend=LOCAL_BACKEND, random_seed=default_random_seed, skip_save_processed_input=False, callbacks=None):\n \"\"\"Builds a dataset from a dataframe and a list of features.\n\n Args:\n config: A dictionary containing the Ludwig model configuration\n dataset_df: Pandas or Dask dataframe\n features: List of features\n global_preprocessing_parameters: Global preprocessing parameters\n mode: One of ['training', 'prediction']\n metadata: Training set metadata if available\n backend: Backend\n random_seed: Random seed\n skip_save_processed_input: Whether to skip saving the processed input\n callbacks: List of callbacks\n\n Returns:\n A tuple of (dataset, metadata)\n \"\"\"\n df_engine = backend.df_engine\n if df_engine.partitioned:\n if any((f['type'] in REPARTITIONING_FEATURE_TYPES for f in features)) and dataset_df.npartitions > 1:\n logger.warning(f'Dataset has {dataset_df.npartitions} partitions and feature types that cause repartitioning. Resetting index to ensure globally unique indices.')\n dataset_df = df_engine.reset_index(dataset_df)\n dataset_df = df_engine.parallelize(dataset_df)\n dataset_df = sanitize_column_names(dataset_df)\n if mode == 'training':\n sample_ratio = global_preprocessing_parameters['sample_ratio']\n if sample_ratio < 1.0:\n if not df_engine.partitioned and len(dataset_df) * sample_ratio < 1:\n raise ValueError(f'sample_ratio {sample_ratio} is too small for dataset of length {len(dataset_df)}. Please increase sample_ratio or use a larger dataset.')\n logger.debug(f'sample {sample_ratio} of data')\n dataset_df = dataset_df.sample(frac=sample_ratio, random_state=random_seed)\n dataset_df = df_engine.persist(dataset_df)\n if mode == 'training':\n default_preprocessing_parameters = default_training_preprocessing_parameters\n elif mode == 'prediction':\n default_preprocessing_parameters = default_prediction_preprocessing_parameters\n else:\n raise ValueError(f'Invalid mode {mode}')\n global_preprocessing_parameters = merge_dict(default_preprocessing_parameters, global_preprocessing_parameters)\n split_col = None\n if global_preprocessing_parameters['split']['type'] == 'fixed':\n if global_preprocessing_parameters['split']['column'] in dataset_df.columns:\n split_col = dataset_df[global_preprocessing_parameters['split']['column']]\n else:\n logger.warning(f\"Specified split column {global_preprocessing_parameters['split']['column']} for fixed split strategy was not found in dataset.\")\n logger.debug('handle text features with prompt parameters')\n synthesized_dataset_cols = handle_features_with_prompt_config(config, dataset_df, features, split_col=split_col, backend=backend)\n feature_configs = []\n feature_hashes = set()\n for feature in features:\n if feature[PROC_COLUMN] not in feature_hashes:\n feature_configs.append(feature)\n feature_hashes.add(feature[PROC_COLUMN])\n dataset_cols = {}\n for feature_config in feature_configs:\n col_name = feature_config[COLUMN]\n dataset_cols[col_name] = synthesized_dataset_cols[col_name] if col_name in synthesized_dataset_cols else dataset_df[col_name]\n logger.debug('build preprocessing parameters')\n feature_name_to_preprocessing_parameters = build_preprocessing_parameters(dataset_cols, feature_configs, global_preprocessing_parameters, backend, metadata=metadata)\n logger.debug('handle missing values')\n for col_key in dataset_cols:\n dataset_cols[col_key] = dataset_cols[col_key].astype(object)\n for feature_config in feature_configs:\n preprocessing_parameters = feature_name_to_preprocessing_parameters[feature_config[NAME]]\n handle_missing_values(dataset_cols, feature_config, preprocessing_parameters, backend)\n logger.debug('cast columns')\n cast_columns(dataset_cols, feature_configs, backend)\n for callback in callbacks or []:\n callback.on_build_metadata_start(dataset_df, mode)\n logger.debug('build metadata')\n metadata = build_metadata(metadata, feature_name_to_preprocessing_parameters, dataset_cols, feature_configs, backend)\n for callback in callbacks or []:\n callback.on_build_metadata_end(dataset_df, mode)\n for callback in callbacks or []:\n callback.on_build_data_start(dataset_df, mode)\n logger.debug('build data')\n proc_cols = build_data(dataset_cols, feature_configs, metadata, backend, skip_save_processed_input)\n for callback in callbacks or []:\n callback.on_build_data_end(dataset_df, mode)\n split_params = global_preprocessing_parameters.get(SPLIT, {})\n if 'type' not in split_params and SPLIT in dataset_df:\n warnings.warn('Detected \"split\" column in the data, but using default split type \"random\". Did you mean to set split type to \"fixed\"?')\n splitter = get_splitter(**split_params)\n for column in splitter.required_columns:\n if column not in dataset_df:\n warnings.warn(f\"column: '{column}' is required by the dataset splitter with params: {split_params}, but '{column}' is not present in the `dataset_df` with columns: {dataset_df.columns}. This is acceptable during serving setting where dataset splitting is irrelevant. You may see this warning if, for example, the model was trained with a configuration that used a stratified split on the target column, but for live predictions, a value for the target column is not to be provided.\")\n continue\n proc_cols[column] = dataset_df[column]\n if not skip_save_processed_input and backend.cache.data_format == 'parquet':\n for feature in features:\n name = feature[NAME]\n proc_column = feature[PROC_COLUMN]\n reshape = metadata[name].get('reshape')\n if reshape is not None:\n proc_cols[proc_column] = backend.df_engine.map_objects(proc_cols[proc_column], lambda x: x.reshape(-1))\n dataset = backend.df_engine.df_like(dataset_df, proc_cols)\n len_dataset_before_drop_rows = len(dataset)\n dataset = dataset.dropna()\n len_dataset_after_drop_rows = len(dataset)\n if len_dataset_before_drop_rows != len_dataset_after_drop_rows:\n logger.warning(f'Dropped a total of {len_dataset_before_drop_rows - len_dataset_after_drop_rows} rows out of {len_dataset_before_drop_rows} due to missing values')\n col_name_to_dtype = {}\n for (col_name, col) in proc_cols.items():\n if type(col) == list and type(col[0]) in {list, np.ndarray, torch.Tensor}:\n continue\n col_name_to_dtype[col_name] = col.dtype\n dataset = dataset.astype(col_name_to_dtype)\n dataset = backend.df_engine.persist(dataset)\n dataset = backend.df_engine.remove_empty_partitions(dataset)\n dataset = embed_fixed_features(dataset, feature_configs, metadata, backend)\n return (dataset, metadata)","code_tokens":"","url":616624} +{"project_name":"googleapis\/python-aiplatform","file_name":"client.py","full_name":"ModelServiceClient.pipeline_job_path","func_name":"pipeline_job_path","docstring":"Returns a fully-qualified pipeline_job string.","docstring_tokens":"","code":"@staticmethod\ndef pipeline_job_path(project: str, location: str, pipeline_job: str) -> str:\n \"\"\"Returns a fully-qualified pipeline_job string.\"\"\"\n return 'projects\/{project}\/locations\/{location}\/pipelineJobs\/{pipeline_job}'.format(project=project, location=location, pipeline_job=pipeline_job)","code_tokens":"","url":811437} +{"project_name":"feidieufo\/Carla-Reinforcement-Learning","file_name":"sensor.py","full_name":"LidarMeasurement.save_to_disk","func_name":"save_to_disk","docstring":"Save point-cloud to disk as PLY format.","docstring_tokens":"","code":"def save_to_disk(self, filename):\n \"\"\"Save point-cloud to disk as PLY format.\"\"\"\n self.point_cloud.save_to_disk(filename)","code_tokens":"","url":455866} +{"project_name":"rootskar\/EEGMotorImagery","file_name":"khushaba.py","full_name":"Khushaba.getClassTrials","func_name":"getClassTrials","docstring":"Return all class trials and labels.","docstring_tokens":"","code":"def getClassTrials(self, class_name):\n \"\"\"Return all class trials and labels.\n\n Args:\n class_name (str): The class name for which the trials should be returned\n\n Returns:\n A 2-tuple containing\n\n - **trials**: A list of all trials of `class_name`\n - **labels**: A list of corresponding labels for the trials\n\n \"\"\"\n Results = []\n label_list = []\n for force_level in self._force_levels:\n path = base_dir + '{}_Force Exp\/{}_{}\/'.format(self.data_id, class_name, force_level)\n for i in range(1, 6):\n file = path + '{}_{}_{}_t{}.mat'.format(self.data_id, class_name, force_level, str(i))\n trial = scipy.io.loadmat(file)['t{}'.format(i)]\n Results.append(trial)\n label_list.append(self._class_labels.index(class_name))\n return (Results, label_list)","code_tokens":"","url":175378} +{"project_name":"aleju\/computer-vision-algorithms","file_name":"sift.py","full_name":"draw_keypoints","func_name":"draw_keypoints","docstring":"Draws for each keypoint a circle (roughly matching the sigma of the scale) with a line for the orientation.","docstring_tokens":"","code":"def draw_keypoints(img, keypoints, draw_prob):\n \"\"\"Draws for each keypoint a circle (roughly matching the sigma of the scale)\n with a line for the orientation.\n Args:\n img The image to which to add the keypoints (gets copied)\n keypoints The keypoints to draw\n draw_prob Probability of drawing a keypoint (the lower the less keypoints are drawn)\n Returns:\n Image with keypoints\"\"\"\n (height, width) = img.shape\n img = np.copy(img)\n img = img[:, :, np.newaxis]\n img = np.repeat(img, 3, axis=2)\n for ((y, x), orientation, scale_idx, scale_size, kp_type) in keypoints:\n if draw_prob < 1.0 and random.random() <= draw_prob:\n radius = int(scale_size)\n (rr, cc) = draw.circle_perimeter(y, x, radius, shape=img.shape)\n img[rr, cc, 0] = 1.0\n img[rr, cc, 1:] = 0\n orientation = util.quantize(orientation, [-135, -90, -45, 0, 45, 90, 135, 180])\n x_start = x\n y_start = y\n if orientation == 0:\n x_end = x + radius\n y_end = y\n elif orientation == 45:\n x_end = x + radius * (1 \/ math.sqrt(2))\n y_end = y + radius * (1 \/ math.sqrt(2))\n elif orientation == 90:\n x_end = x\n y_end = y + radius\n elif orientation == 135:\n x_end = x - radius * (1 \/ math.sqrt(2))\n y_end = y - radius * (1 \/ math.sqrt(2))\n elif orientation == 180:\n x_end = x - radius\n y_end = y\n elif orientation == -135:\n x_end = x - radius * (1 \/ math.sqrt(2))\n y_end = y - radius * (1 \/ math.sqrt(2))\n elif orientation == -90:\n x_end = x\n y_end = y - radius\n elif orientation == -45:\n x_end = x + radius * (1 \/ math.sqrt(2))\n y_end = y - radius * (1 \/ math.sqrt(2))\n x_end = np.clip(x_end, 0, width - 1)\n y_end = np.clip(y_end, 0, height - 1)\n (rr, cc) = draw.line(int(y_start), int(x_start), int(y_end), int(x_end))\n img[rr, cc, 0] = 1.0\n img[rr, cc, 1:] = 0\n img = np.clip(img, 0, 1.0)\n return img","code_tokens":"","url":467572} +{"project_name":"vishalprabha\/Image-Classification-Transfer-Learning-with-Inception-v3","file_name":"predict-request.py","full_name":"predict_json","func_name":"predict_json","docstring":"Send json data to a deployed model for prediction.","docstring_tokens":"","code":"def predict_json(project, model, instances, version=None):\n \"\"\"Send json data to a deployed model for prediction.\n\n Args:\n project (str): project where the Cloud ML Engine Model is deployed.\n model (str): model name.\n instances ([Mapping[str: Any]]): Keys should be the names of Tensors\n your deployed model expects as inputs. Values should be datatypes\n convertible to Tensors, or (potentially nested) lists of datatypes\n convertible to tensors.\n version: str, version of the model to target.\n Returns:\n Mapping[str: any]: dictionary of prediction results defined by the\n model.\n \"\"\"\n service = googleapiclient.discovery.build('ml', 'v1')\n name = 'projects\/{}\/models\/{}'.format(project, model)\n if version is not None:\n name += '\/versions\/{}'.format(version)\n response = service.projects().predict(name=name, body={'instances': instances}).execute()\n if 'error' in response:\n raise RuntimeError(response['error'])\n return response['predictions']","code_tokens":"","url":599079} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"control_flow.py","full_name":"if_stmt","func_name":"if_stmt","docstring":"Functional form of an if statement.","docstring_tokens":"","code":"def if_stmt(cond, body, orelse):\n \"\"\"Functional form of an if statement.\n\n Args:\n cond: Boolean.\n body: Callable with no arguments, and outputs of the positive (if) branch\n as return type.\n orelse: Callable with no arguments, and outputs of the negative (else)\n branch as return type.\n\n Returns:\n Tuple containing the statement outputs.\n \"\"\"\n if tensor_util.is_tensor(cond):\n return tf_if_stmt(cond, body, orelse)\n else:\n return _py_if_stmt(cond, body, orelse)","code_tokens":"","url":312366} +{"project_name":"salu133445\/bmusegan","file_name":"metrics.py","full_name":"to_chroma","func_name":"to_chroma","docstring":"Return the chroma features (not normalized).","docstring_tokens":"","code":"def to_chroma(pianoroll):\n \"\"\"Return the chroma features (not normalized).\"\"\"\n padded = np.pad(pianoroll, ((0, 0), (0, 12 - pianoroll.shape[1] % 12)), 'constant')\n return np.sum(np.reshape(padded, (pianoroll.shape[0], 12, -1)), 2)","code_tokens":"","url":461875} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning---Tutorials","file_name":"pixelda_train.py","full_name":"run_training","func_name":"run_training","docstring":"Runs the training loop.","docstring_tokens":"","code":"def run_training(run_dir, checkpoint_dir, hparams):\n \"\"\"Runs the training loop.\n\n Args:\n run_dir: The directory where training specific logs are placed\n checkpoint_dir: The directory where the checkpoints and log files are\n stored.\n hparams: The hyperparameters struct.\n\n Raises:\n ValueError: if hparams.arch is not recognized.\n \"\"\"\n for path in [run_dir, checkpoint_dir]:\n if not tf.gfile.Exists(path):\n tf.gfile.MakeDirs(path)\n hparams_filename = os.path.join(checkpoint_dir, 'hparams.json')\n with tf.gfile.FastGFile(hparams_filename, 'w') as f:\n f.write(hparams.to_json())\n with tf.Graph().as_default():\n with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks)):\n global_step = slim.get_or_create_global_step()\n target_dataset = dataset_factory.get_dataset(FLAGS.target_dataset, split_name='train', dataset_dir=FLAGS.dataset_dir)\n (target_images, _) = dataset_factory.provide_batch(FLAGS.target_dataset, 'train', FLAGS.dataset_dir, FLAGS.num_readers, hparams.batch_size, FLAGS.num_preprocessing_threads)\n num_target_classes = target_dataset.num_classes\n if hparams.arch not in ['dcgan']:\n source_dataset = dataset_factory.get_dataset(FLAGS.source_dataset, split_name='train', dataset_dir=FLAGS.dataset_dir)\n num_source_classes = source_dataset.num_classes\n (source_images, source_labels) = dataset_factory.provide_batch(FLAGS.source_dataset, 'train', FLAGS.dataset_dir, FLAGS.num_readers, hparams.batch_size, FLAGS.num_preprocessing_threads)\n source_labels['class'] = tf.argmax(source_labels['classes'], 1)\n del source_labels['classes']\n if num_source_classes != num_target_classes:\n raise ValueError('Source and Target datasets must have same number of classes. Are %d and %d' % (num_source_classes, num_target_classes))\n else:\n source_images = None\n source_labels = None\n end_points = pixelda_model.create_model(hparams, target_images, source_images=source_images, source_labels=source_labels, is_training=True, num_classes=num_target_classes)\n (generator_vars, generator_update_ops) = _get_vars_and_update_ops(hparams, 'generator')\n (discriminator_vars, discriminator_update_ops) = _get_vars_and_update_ops(hparams, 'discriminator')\n generator_loss = pixelda_losses.g_step_loss(source_images, source_labels, end_points, hparams, num_classes=num_target_classes)\n discriminator_loss = pixelda_losses.d_step_loss(end_points, source_labels, num_target_classes, hparams)\n learning_rate = hparams.learning_rate\n if hparams.lr_decay_steps:\n learning_rate = tf.train.exponential_decay(learning_rate, slim.get_or_create_global_step(), decay_steps=hparams.lr_decay_steps, decay_rate=hparams.lr_decay_rate, staircase=True)\n tf.summary.scalar('Learning_rate', learning_rate)\n if hparams.discriminator_steps == 0:\n discriminator_train_op = tf.no_op()\n else:\n discriminator_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=hparams.adam_beta1)\n discriminator_train_op = slim.learning.create_train_op(discriminator_loss, discriminator_optimizer, update_ops=discriminator_update_ops, variables_to_train=discriminator_vars, clip_gradient_norm=hparams.clip_gradient_norm, summarize_gradients=FLAGS.summarize_gradients)\n if hparams.generator_steps == 0:\n generator_train_op = tf.no_op()\n else:\n generator_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=hparams.adam_beta1)\n generator_train_op = slim.learning.create_train_op(generator_loss, generator_optimizer, update_ops=generator_update_ops, variables_to_train=generator_vars, clip_gradient_norm=hparams.clip_gradient_norm, summarize_gradients=FLAGS.summarize_gradients)\n pixelda_utils.summarize_model(end_points)\n pixelda_utils.summarize_transferred_grid(end_points['transferred_images'], source_images, name='Transferred')\n if 'source_images_recon' in end_points:\n pixelda_utils.summarize_transferred_grid(end_points['source_images_recon'], source_images, name='Source Reconstruction')\n pixelda_utils.summaries_color_distributions(end_points['transferred_images'], 'Transferred')\n pixelda_utils.summaries_color_distributions(target_images, 'Target')\n if source_images is not None:\n pixelda_utils.summarize_transferred(source_images, end_points['transferred_images'])\n pixelda_utils.summaries_color_distributions(source_images, 'Source')\n pixelda_utils.summaries_color_distributions(tf.abs(source_images - end_points['transferred_images']), 'Abs(Source_minus_Transferred)')\n number_of_steps = None\n if hparams.num_training_examples:\n number_of_steps = hparams.num_training_examples \/ hparams.batch_size\n hooks = [tf.train.StepCounterHook()]\n chief_only_hooks = [tf.train.CheckpointSaverHook(saver=tf.train.Saver(), checkpoint_dir=run_dir, save_secs=FLAGS.save_interval_secs)]\n if number_of_steps:\n hooks.append(tf.train.StopAtStepHook(last_step=number_of_steps))\n _train(discriminator_train_op, generator_train_op, logdir=run_dir, master=FLAGS.master, is_chief=FLAGS.task == 0, hooks=hooks, chief_only_hooks=chief_only_hooks, save_checkpoint_secs=None, save_summaries_steps=FLAGS.save_summaries_steps, hparams=hparams)","code_tokens":"","url":48280} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_estimator_checks.py","full_name":"test_check_outlier_contamination","func_name":"test_check_outlier_contamination","docstring":"Check the test for the contamination parameter in the outlier detectors.","docstring_tokens":"","code":"def test_check_outlier_contamination():\n \"\"\"Check the test for the contamination parameter in the outlier detectors.\"\"\"\n\n class OutlierDetectorWithoutConstraint(OutlierMixin, BaseEstimator):\n \"\"\"Outlier detector without parameter validation.\"\"\"\n\n def __init__(self, contamination=0.1):\n self.contamination = contamination\n\n def fit(self, X, y=None, sample_weight=None):\n return self\n\n def predict(self, X, y=None):\n return np.ones(X.shape[0])\n detector = OutlierDetectorWithoutConstraint()\n assert check_outlier_contamination(detector.__class__.__name__, detector) is None\n\n class OutlierDetectorWithConstraint(OutlierDetectorWithoutConstraint):\n _parameter_constraints = {'contamination': [StrOptions({'auto'})]}\n detector = OutlierDetectorWithConstraint()\n err_msg = 'contamination constraints should contain a Real Interval constraint.'\n with raises(AssertionError, match=err_msg):\n check_outlier_contamination(detector.__class__.__name__, detector)\n OutlierDetectorWithConstraint._parameter_constraints['contamination'] = [Interval(Real, 0, 0.5, closed='right')]\n detector = OutlierDetectorWithConstraint()\n check_outlier_contamination(detector.__class__.__name__, detector)\n incorrect_intervals = [Interval(Integral, 0, 1, closed='right'), Interval(Real, -1, 1, closed='right'), Interval(Real, 0, 2, closed='right'), Interval(Real, 0, 0.5, closed='left')]\n err_msg = 'contamination constraint should be an interval in \\\\(0, 0.5\\\\]'\n for interval in incorrect_intervals:\n OutlierDetectorWithConstraint._parameter_constraints['contamination'] = [interval]\n detector = OutlierDetectorWithConstraint()\n with raises(AssertionError, match=err_msg):\n check_outlier_contamination(detector.__class__.__name__, detector)","code_tokens":"","url":854299} +{"project_name":"Rizo-R\/chess-cv","file_name":"geometry.py","full_name":"EventQueue.offer","func_name":"offer","docstring":"Offer a new event ``s`` at point ``p`` in this queue.","docstring_tokens":"","code":"def offer(self, p, e: Event):\n \"\"\"\n Offer a new event ``s`` at point ``p`` in this queue.\n \"\"\"\n existing = self.events_scan.setdefault(p, ([], [], [], []) if USE_VERTICAL else ([], [], []))\n '\\n if e.type == Event.Type.END:\\n existing.insert(0, e)\\n else:\\n existing.append(e)\\n '\n existing[e.type].append(e)","code_tokens":"","url":486202} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"texmanager.py","full_name":"TexManager.get_custom_preamble","func_name":"get_custom_preamble","docstring":"Return a string containing user additions to the tex preamble.","docstring_tokens":"","code":"def get_custom_preamble(self):\n \"\"\"Return a string containing user additions to the tex preamble.\"\"\"\n return '\\n'.join(rcParams['text.latex.preamble'])","code_tokens":"","url":882} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"transports.py","full_name":"WriteTransport.can_write_eof","func_name":"can_write_eof","docstring":"Return True if this transport supports write_eof(), False if not.","docstring_tokens":"","code":"def can_write_eof(self):\n \"\"\"Return True if this transport supports write_eof(), False if not.\"\"\"\n raise NotImplementedError","code_tokens":"","url":282096} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"well_known_types.py","full_name":"FieldMask.ToJsonString","func_name":"ToJsonString","docstring":"Converts FieldMask to string according to proto3 JSON spec.","docstring_tokens":"","code":"def ToJsonString(self):\n \"\"\"Converts FieldMask to string according to proto3 JSON spec.\"\"\"\n camelcase_paths = []\n for path in self.paths:\n camelcase_paths.append(_SnakeCaseToCamelCase(path))\n return ','.join(camelcase_paths)","code_tokens":"","url":215405} +{"project_name":"surafelml\/adapt-mnmt","file_name":"data.py","full_name":"inference_pipeline","func_name":"inference_pipeline","docstring":"Defines a complete inference data pipeline.","docstring_tokens":"","code":"def inference_pipeline(dataset, batch_size, process_fn=None, num_threads=None, prefetch_buffer_size=None, bucket_width=None, length_fn=None):\n \"\"\"Defines a complete inference data pipeline.\n\n Args:\n dataset: The base dataset.\n batch_size: The batch size to use.\n process_fn: The processing function to apply on each element.\n num_threads: The number of elements processed in parallel.\n prefetch_buffer_size: The number of batches to prefetch asynchronously. If\n ``None``, use an automatically tuned value on TensorFlow 1.8+ and 1 on\n older versions.\n bucket_width: The width of the length buckets to select batch candidates\n from. If set, this means the inference pipeline will be reordered based on\n the examples length, the application is then responsible to restore the\n predictions in order. An \"index\" key will be inserted in the examples\n dict.\n length_fn: A callable mapping features to a sequence length.\n\n Returns:\n A ``tf.data.Dataset``.\n \"\"\"\n\n def _inject_index(index, x):\n x['index'] = index\n return x\n\n def _key_func(x):\n length = length_fn(x)\n bucket_id = tf.constant(0, dtype=tf.int64)\n if not isinstance(length, list):\n bucket_id = tf.maximum(bucket_id, tf.cast(length, bucket_id.dtype) \/\/ bucket_width)\n return bucket_id\n\n def _reduce_func(unused_key, dataset):\n return dataset.apply(batch_dataset(batch_size))\n if process_fn is not None:\n dataset = dataset.map(process_fn, num_parallel_calls=num_threads)\n if bucket_width is not None and bucket_width > 0:\n if length_fn is None:\n raise ValueError('length_fn is required when reordering by length')\n if not isinstance(dataset.output_shapes, dict):\n raise ValueError('Reordering by length expects dataset elements to be Python dicts')\n dataset = dataset.apply(_experimental_data_namespace().enumerate_dataset())\n dataset = dataset.map(_inject_index)\n dataset = dataset.apply(_experimental_data_namespace().group_by_window(_key_func, _reduce_func, window_size=batch_size))\n else:\n dataset = dataset.apply(batch_dataset(batch_size))\n dataset = dataset.apply(prefetch_element(buffer_size=prefetch_buffer_size))\n return dataset","code_tokens":"","url":407854} +{"project_name":"Farama-Foundation\/Shimmy","file_name":"test_dm_control.py","full_name":"test_rendering_camera_id","func_name":"test_rendering_camera_id","docstring":"Test that dm-control rendering works.","docstring_tokens":"","code":"@pytest.mark.parametrize('camera_id', [-1, 0, 1])\ndef test_rendering_camera_id(camera_id):\n \"\"\"Test that dm-control rendering works.\"\"\"\n env = gym.make(DM_CONTROL_ENV_IDS[0], render_mode='rgb_array', render_kwargs=dict(camera_id=camera_id))\n env.reset()\n frames = []\n for _ in range(10):\n frames.append(env.render())\n env.step(env.action_space.sample())\n env.close()","code_tokens":"","url":901054} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"rstlint.py","full_name":"check_leaked_markup","func_name":"check_leaked_markup","docstring":"Check HTML files for leaked reST markup; this only works if the HTML files have been built.","docstring_tokens":"","code":"@checker('.html', severity=2, falsepositives=True)\ndef check_leaked_markup(fn, lines):\n \"\"\"Check HTML files for leaked reST markup; this only works if\n the HTML files have been built.\n \"\"\"\n for (lno, line) in enumerate(lines):\n if leaked_markup_re.search(line):\n yield (lno + 1, 'possibly leaked markup: %r' % line)","code_tokens":"","url":280040} +{"project_name":"thaines\/helit","file_name":"model.py","full_name":"Sample.getClusterDrawConc","func_name":"getClusterDrawConc","docstring":"Returns the sampled concentration parameter for drawing cluster instances for documents.","docstring_tokens":"","code":"def getClusterDrawConc(self):\n \"\"\"Returns the sampled concentration parameter for drawing cluster instances for documents.\"\"\"\n return self.clusterConc","code_tokens":"","url":591092} +{"project_name":"brightmart\/albert_zh","file_name":"modeling_google_fast.py","full_name":"create_initializer","func_name":"create_initializer","docstring":"Creates a `truncated_normal_initializer` with the given range.","docstring_tokens":"","code":"def create_initializer(initializer_range=0.02):\n \"\"\"Creates a `truncated_normal_initializer` with the given range.\"\"\"\n return tf.truncated_normal_initializer(stddev=initializer_range)","code_tokens":"","url":32744} +{"project_name":"csuhan\/ReDet","file_name":"counting_ReDet_model_size.py","full_name":"convert","func_name":"convert","docstring":"This script is used to count ReDet's model size As ReResNet contains some unnecessary keys, so we remove them for counting the real model size.","docstring_tokens":"","code":"def convert(in_file, out_file, with_det_head=True):\n \"\"\"This script is used to count ReDet's model size\n As ReResNet contains some unnecessary keys, so we remove them for counting the real model size.\n \"\"\"\n remove_keys = ['_basisexpansion', 'filter', 'expanded_bias', 'indices', 'bias_expansion']\n if not with_det_head:\n remove_keys.extend(['rpn_head', 'bbox_head', 'rbbox_head'])\n checkpoint = torch.load(in_file)\n if 'optimizer' in checkpoint.keys():\n checkpoint.pop('optimizer')\n in_state_dict = checkpoint.pop('state_dict')\n out_state_dict = OrderedDict()\n for (key, val) in in_state_dict.items():\n flag = 0\n for item in remove_keys:\n if item in key:\n flag = 1\n if flag == 0:\n out_state_dict[key] = val\n checkpoint['state_dict'] = out_state_dict\n torch.save(checkpoint, out_file)","code_tokens":"","url":832685} +{"project_name":"jonathanking\/sidechainnet","file_name":"losses.py","full_name":"compute_batch_drmsd","func_name":"compute_batch_drmsd","docstring":"Compute batch-averaged DRMSD between two sets of coordinates.","docstring_tokens":"","code":"def compute_batch_drmsd(true_coordinates, pred_coordinates, seq, verbose=False):\n \"\"\"Compute batch-averaged DRMSD between two sets of coordinates.\n\n Args:\n true_coordinates (torch.Tensor): Tensor of true atomic coordinates\n (batch_size * length * NUM_COORDS_PER_RES).\n pred_coordinates (torch.Tensor): Tensor of predicted atomic coordinates\n (batch_size * length * NUM_COORDS_PER_RES).\n seq (torch.Tensor): Tensor of protein sequences represented as integers\n (batch_size * length).\n verbose (bool, optional): If True, print DRMSD\/lnDRMSD values as they are\n computed. Defaults to False.\n\n Returns:\n torch.Tensor: Geometric mean of DRMSD values for each protein in the batch.\n Lower is better.\n \"\"\"\n drmsds = torch.tensor(0.0)\n raw_drmsds = torch.tensor(0.0)\n for (pc, tc, s) in zip(pred_coordinates, true_coordinates, seq):\n batch_padding = _tile(s != 20, 0, NUM_COORDS_PER_RES)\n tc = tc[batch_padding]\n missing_atoms = (tc == 0).all(axis=-1)\n tc = tc[~missing_atoms]\n pc = pc[~missing_atoms]\n d = drmsd(tc, pc)\n drmsds += d \/ (len(tc) \/\/ NUM_COORDS_PER_RES)\n raw_drmsds += d\n if verbose:\n print(f'DRMSD = {raw_drmsds.mean():.2f}, lnDRMSD = {drmsds.mean():.2f}')\n return drmsds.mean()","code_tokens":"","url":934008} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"c_declarations.py","full_name":"StaticStringArray.ctypes_var_decl","func_name":"ctypes_var_decl","docstring":"Generates a ctypes export statement.","docstring_tokens":"","code":"def ctypes_var_decl(self, cdll_name=''):\n \"\"\"Generates a ctypes export statement.\"\"\"\n ptr_str = 'ctypes.c_char_p'\n for dim in self.shape[::-1]:\n ptr_str = '({0} * {1!s})'.format(ptr_str, dim)\n return '{0} = {1}.in_dll({2}, {3!r})\\n'.format(self.name, ptr_str, cdll_name, self.symbol_name)","code_tokens":"","url":439837} +{"project_name":"matsu0228\/nlp-jp","file_name":"parse.py","full_name":"PgenParser.add_token","func_name":"add_token","docstring":"Add a token; return True if this is the end of the program.","docstring_tokens":"","code":"def add_token(self, type_, value, start_pos, prefix):\n \"\"\"Add a token; return True if this is the end of the program.\"\"\"\n ilabel = token_to_ilabel(self.grammar, type_, value)\n _gram = self.grammar\n _labels = _gram.labels\n _push = self._push\n _pop = self._pop\n _shift = self._shift\n while True:\n (dfa, state, node) = self.stack[-1]\n (states, first) = dfa\n arcs = states[state]\n for (i, newstate) in arcs:\n (t, v) = _labels[i]\n if ilabel == i:\n assert t < 256\n _shift(type_, value, newstate, prefix, start_pos)\n state = newstate\n while states[state] == [(0, state)]:\n _pop()\n if not self.stack:\n return True\n (dfa, state, node) = self.stack[-1]\n (states, first) = dfa\n return False\n elif t >= 256:\n itsdfa = _gram.dfas[t]\n (itsstates, itsfirst) = itsdfa\n if ilabel in itsfirst:\n _push(t, itsdfa, newstate)\n break\n else:\n if (0, state) in arcs:\n _pop()\n if not self.stack:\n raise InternalParseError('too much input', type_, value, start_pos)\n else:\n self.error_recovery(self.grammar, self.stack, arcs, type_, value, start_pos, prefix, self.add_token)\n break","code_tokens":"","url":803122} +{"project_name":"sisl\/MADRL","file_name":"pursuit_evade.py","full_name":"PursuitEvade.animate","func_name":"animate","docstring":"Save an animation to an mp4 file.","docstring_tokens":"","code":"def animate(self, act_fn, nsteps, file_name, rate=1.5, verbose=False):\n \"\"\"\n Save an animation to an mp4 file.\n \"\"\"\n plt.figure(0)\n o = self.reset()\n file_path = '\/'.join(file_name.split('\/')[0:-1])\n temp_name = join(file_path, 'temp_0.png')\n self.save_image(temp_name)\n removed = 0\n for i in range(nsteps):\n a = act_fn(o)\n (o, r, done, info) = self.step(a)\n temp_name = join(file_path, 'temp_' + str(i + 1) + '.png')\n self.save_image(temp_name)\n removed += info['removed']\n if verbose:\n print(r, info)\n if done:\n break\n if verbose:\n print('Total removed:', removed)\n ffmpeg_cmd = 'ffmpeg -framerate ' + str(rate) + ' -i ' + join(file_path, 'temp_%d.png') + ' -c:v libx264 -pix_fmt yuv420p ' + file_name\n call(ffmpeg_cmd.split())\n map(os.remove, glob.glob(join(file_path, 'temp_*.png')))","code_tokens":"","url":209132} +{"project_name":"zhang614\/MicroGrid","file_name":"cookiejar.py","full_name":"deepvalues","func_name":"deepvalues","docstring":"Iterates over nested mapping, depth-first, in sorted order by key.","docstring_tokens":"","code":"def deepvalues(mapping):\n \"\"\"Iterates over nested mapping, depth-first, in sorted order by key.\"\"\"\n values = vals_sorted_by_key(mapping)\n for obj in values:\n mapping = False\n try:\n obj.items\n except AttributeError:\n pass\n else:\n mapping = True\n for subobj in deepvalues(obj):\n yield subobj\n if not mapping:\n yield obj","code_tokens":"","url":636272} +{"project_name":"MycroftAI\/mycroft-core","file_name":"event_scheduler.py","full_name":"EventScheduler.remove_event","func_name":"remove_event","docstring":"Remove an event from the list of scheduled events.","docstring_tokens":"","code":"def remove_event(self, event):\n \"\"\"Remove an event from the list of scheduled events.\n\n Args:\n event (str): event identifier\n \"\"\"\n with self.event_lock:\n if event in self.events:\n self.events.pop(event)","code_tokens":"","url":290457} +{"project_name":"weiruXie\/Natural-Language-Processing","file_name":"configuration.py","full_name":"Configuration.add_arc","func_name":"add_arc","docstring":"Add an arc with the label l from the head node h to the dependent node t.","docstring_tokens":"","code":"def add_arc(self, h, t, l):\n \"\"\"\n Add an arc with the label l from the head node h to the dependent node t.\n \"\"\"\n self.tree.set(t, h, l)","code_tokens":"","url":686844} +{"project_name":"enuguru\/artificial_intelligence_and_machine_","file_name":"flask_mail.py","full_name":"Message.send","func_name":"send","docstring":"Verifies and sends the message.","docstring_tokens":"","code":"def send(self, connection):\n \"\"\"Verifies and sends the message.\"\"\"\n connection.send(self)","code_tokens":"","url":156541} +{"project_name":"interpretml\/DiCE","file_name":"dice_pytorch.py","full_name":"DicePyTorch.do_optimizer_initializations","func_name":"do_optimizer_initializations","docstring":"Initializes gradient-based PyTorch optimizers.","docstring_tokens":"","code":"def do_optimizer_initializations(self, optimizer, learning_rate):\n \"\"\"Initializes gradient-based PyTorch optimizers.\"\"\"\n opt_method = optimizer.split(':')[1]\n if opt_method == 'adam':\n self.optimizer = torch.optim.Adam(self.cfs, lr=learning_rate)\n elif opt_method == 'rmsprop':\n self.optimizer = torch.optim.RMSprop(self.cfs, lr=learning_rate)","code_tokens":"","url":550226} +{"project_name":"openai\/gym","file_name":"test_utils.py","full_name":"test_flat_space_contains_flat_points","func_name":"test_flat_space_contains_flat_points","docstring":"Test that the flattened samples are contained within the flattened space.","docstring_tokens":"","code":"@pytest.mark.parametrize('space', TESTING_SPACES, ids=TESTING_SPACES_IDS)\ndef test_flat_space_contains_flat_points(space):\n \"\"\"Test that the flattened samples are contained within the flattened space.\"\"\"\n flattened_samples = [utils.flatten(space, space.sample()) for _ in range(10)]\n flat_space = utils.flatten_space(space)\n for flat_sample in flattened_samples:\n assert flat_sample in flat_space","code_tokens":"","url":234391} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"mlab.py","full_name":"rec_drop_fields","func_name":"rec_drop_fields","docstring":"Return a new numpy record array with fields in *names* dropped.","docstring_tokens":"","code":"@cbook.deprecated('2.2')\ndef rec_drop_fields(rec, names):\n \"\"\"\n Return a new numpy record array with fields in *names* dropped.\n \"\"\"\n names = set(names)\n newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names if name not in names])\n newrec = np.recarray(rec.shape, dtype=newdtype)\n for field in newdtype.names:\n newrec[field] = rec[field]\n return newrec","code_tokens":"","url":698} +{"project_name":"voxel51\/fiftyone","file_name":"cvat.py","full_name":"CVATTaskLabels.merge_task_labels","func_name":"merge_task_labels","docstring":"Merges the given :class:`CVATTaskLabels` into this instance.","docstring_tokens":"","code":"def merge_task_labels(self, task_labels):\n \"\"\"Merges the given :class:`CVATTaskLabels` into this instance.\n\n Args:\n task_labels: a :class:`CVATTaskLabels`\n \"\"\"\n schema = self.to_schema()\n schema.merge_schema(task_labels.to_schema())\n new_task_labels = CVATTaskLabels.from_schema(schema)\n self.labels = new_task_labels.labels","code_tokens":"","url":583933} +{"project_name":"viko-3\/DiffSeqMol","file_name":"stream.py","full_name":"is_cuda","func_name":"is_cuda","docstring":"Returns ``True`` if the given stream is a valid CUDA stream.","docstring_tokens":"","code":"def is_cuda(stream: AbstractStream) -> bool:\n \"\"\"Returns ``True`` if the given stream is a valid CUDA stream.\"\"\"\n return stream is not CPUStream","code_tokens":"","url":551528} +{"project_name":"ishtiaq1495\/Generative_adversarial_networks","file_name":"CycleGAN.py","full_name":"load_checkpoint","func_name":"load_checkpoint","docstring":"Loads the generator and discriminator models from checkpoints.","docstring_tokens":"","code":"def load_checkpoint(opts):\n \"\"\"\n Loads the generator and discriminator models from checkpoints.\n \"\"\"\n G_XtoY_path = os.path.join(opts.load, 'G_XtoY.pkl')\n G_YtoX_path = os.path.join(opts.load, 'G_YtoX.pkl')\n D_X_path = os.path.join(opts.load, 'D_X.pkl')\n D_Y_path = os.path.join(opts.load, 'D_Y.pkl')\n G_XtoY = CycleGenerator(conv_dim=opts.g_conv_dim, init_zero_weights=opts.init_zero_weights)\n G_YtoX = CycleGenerator(conv_dim=opts.g_conv_dim, init_zero_weights=opts.init_zero_weights)\n D_X = DCDiscriminator(conv_dim=opts.d_conv_dim)\n D_Y = DCDiscriminator(conv_dim=opts.d_conv_dim)\n G_XtoY.load_state_dict(torch.load(G_XtoY_path, map_location=lambda storage, loc: storage))\n G_YtoX.load_state_dict(torch.load(G_YtoX_path, map_location=lambda storage, loc: storage))\n D_X.load_state_dict(torch.load(D_X_path, map_location=lambda storage, loc: storage))\n D_Y.load_state_dict(torch.load(D_Y_path, map_location=lambda storage, loc: storage))\n if torch.cuda.is_available():\n G_XtoY.cuda()\n G_YtoX.cuda()\n D_X.cuda()\n D_Y.cuda()\n print('Models moved to GPU.')\n return (G_XtoY, G_YtoX, D_X, D_Y)","code_tokens":"","url":556607} +{"project_name":"fengyoung\/video_embedding","file_name":"video_decode.py","full_name":"frames_extract","func_name":"frames_extract","docstring":"Extracts frames input video.","docstring_tokens":"","code":"def frames_extract(video_file, start_off=0, sampling_fps=1, max_frame_cnt=60):\n \"\"\"Extracts frames input video.\n\t\n\tArgs: \n\t\tvideo_file: A String. Video file path.\n\t\tstart_off: A Integer`. Start offset in second. \n\t\tsampling_fps: A Integer. Frames per second in sampling. \n\t\tmax_frame_cnt: A Integer. How many frames should be extracted.\n\t\tpadding: A Boolean. If 0 should be padded when the video was too short.\n\n\tReturns:\n\t\tA 4-D array of uint8 in shape [frames, heigt, width, channels]. If failed, return None \n\t\"\"\"\n if not os.path.exists(video_file):\n return None\n vcap = cv2.VideoCapture(video_file)\n fps = vcap.get(cv2.CAP_PROP_FPS)\n height = int(vcap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n width = int(vcap.get(cv2.CAP_PROP_FRAME_WIDTH))\n frame_interval = 1\n if sampling_fps > 0 and sampling_fps < fps:\n frame_interval = int(fps \/ sampling_fps)\n frame_list = []\n off = 0\n cnt = 0\n (success, im) = vcap.read()\n while success and cnt < max_frame_cnt:\n if off == start_off * fps + cnt * frame_interval:\n frame_list.append(im)\n cnt += 1\n off += 1\n (success, im) = vcap.read()\n return np.array(frame_list)","code_tokens":"","url":379965} +{"project_name":"BYU-PCCL\/holodeck","file_name":"environments.py","full_name":"HolodeckEnvironment.clean_up_resources","func_name":"clean_up_resources","docstring":"Frees up references to mapped memory files.","docstring_tokens":"","code":"def clean_up_resources(self):\n \"\"\"Frees up references to mapped memory files.\"\"\"\n self._command_center.clean_up_resources()\n if hasattr(self, '_reset_ptr'):\n del self._reset_ptr\n for key in list(self.agents.keys()):\n self.agents[key].clean_up_resources()\n del self.agents[key]","code_tokens":"","url":570127} +{"project_name":"santhoshkolloju\/Abstractive-Summarization-With-Transfer-","file_name":"context.py","full_name":"valid_modes","func_name":"valid_modes","docstring":"Returns a set of possible values of mode.","docstring_tokens":"","code":"def valid_modes():\n \"\"\"Returns a set of possible values of mode.\n \"\"\"\n return {tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, tf.estimator.ModeKeys.PREDICT}","code_tokens":"","url":405929} +{"project_name":"klb3713\/cw_word_embedding","file_name":"model.py","full_name":"Model.embed","func_name":"embed","docstring":"Embed one sequence of vocabulary IDs.","docstring_tokens":"","code":"def embed(self, sequence):\n \"\"\"\n Embed one sequence of vocabulary IDs.\n \"\"\"\n embs = numpy.concatenate([self.parameters.embeddings[s] for s in sequence]).reshape((1, self.parameters.input_size))\n return embs","code_tokens":"","url":524398} +{"project_name":"octree-nn\/ocnn-pytorch","file_name":"points.py","full_name":"Points.bbox","func_name":"bbox","docstring":"Returns the bounding box.","docstring_tokens":"","code":"def bbox(self):\n \"\"\" Returns the bounding box.\n \"\"\"\n bbmin = self.points.min(dim=0)\n bbmax = self.points.max(dim=0)\n return (bbmin[0], bbmax[0])","code_tokens":"","url":249954} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"gmm_ops.py","full_name":"GmmAlgorithm.clusters","func_name":"clusters","docstring":"Returns the clusters with dimensions num_classes X 1 X num_dimensions.","docstring_tokens":"","code":"def clusters(self):\n \"\"\"Returns the clusters with dimensions num_classes X 1 X num_dimensions.\"\"\"\n return self._means","code_tokens":"","url":181271} +{"project_name":"voxel51\/fiftyone","file_name":"stages.py","full_name":"GeoWithin.strict","func_name":"strict","docstring":"Whether matches must be strictly contained in the boundary.","docstring_tokens":"","code":"@property\ndef strict(self):\n \"\"\"Whether matches must be strictly contained in the boundary.\"\"\"\n return self._strict","code_tokens":"","url":583311} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_tifffile.py","full_name":"FileHandle.read","func_name":"read","docstring":"Read 'size' bytes from file, or until EOF is reached.","docstring_tokens":"","code":"def read(self, size=-1):\n \"\"\"Read 'size' bytes from file, or until EOF is reached.\"\"\"\n if size < 0 and self._offset:\n size = self._size\n return self._fh.read(size)","code_tokens":"","url":37647} +{"project_name":"open-mmlab\/mmtracking","file_name":"processing.py","full_name":"TridentSampling.prepare_cls_data","func_name":"prepare_cls_data","docstring":"Prepare the sampled classification training data according to the sampled index.","docstring_tokens":"","code":"def prepare_cls_data(self, video_info, video_info_another, sampled_inds):\n \"\"\"Prepare the sampled classification training data according to the\n sampled index.\n\n Args:\n video_info (dict): the video information. It contains the keys:\n ['bboxes','bboxes_isvalid','filename','frame_ids',\n 'video_id','visible'].\n video_info_another (dict): the another video information. It's only\n used to get negative samples in classification train. It\n contains the keys: ['bboxes','bboxes_isvalid','filename',\n 'frame_ids','video_id','visible'].\n sampled_inds (list[int]): the sampled frame indexes.\n\n Returns:\n List[dict]: contains the information of sampled data.\n \"\"\"\n results = self.prepare_data(video_info, sampled_inds[:self.num_template_frames], with_label=True)\n if random.random() < self.cls_pos_prob:\n pos_search_samples = self.prepare_data(video_info, sampled_inds[-self.num_search_frames:])\n for sample in pos_search_samples:\n sample['ann_info']['labels'] = np.array([1], dtype=np.float32)\n results.extend(pos_search_samples)\n else:\n if self.is_video_data:\n neg_search_ind = self.random_sample_inds(video_info_another['bboxes_isvalid'], num_samples=1)\n if neg_search_ind[0] is None:\n return None\n neg_search_samples = self.prepare_data(video_info_another, neg_search_ind)\n else:\n neg_search_samples = self.prepare_data(video_info_another, [0])\n for sample in neg_search_samples:\n sample['ann_info']['labels'] = np.array([0], dtype=np.float32)\n results.extend(neg_search_samples)\n return results","code_tokens":"","url":625786} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"data.py","full_name":"SeekableUnicodeStreamReader.mode","func_name":"mode","docstring":"The mode of the underlying stream.","docstring_tokens":"","code":"@property\ndef mode(self):\n \"\"\"The mode of the underlying stream.\"\"\"\n return self.stream.mode","code_tokens":"","url":217224} +{"project_name":"google-research\/scenic","file_name":"losses.py","full_name":"get_labels","func_name":"get_labels","docstring":"Labels the inner products compute dfrom `compute_inners`.","docstring_tokens":"","code":"def get_labels(inners: jnp.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Labels the inner products compute dfrom `compute_inners`.\"\"\"\n bs = inners.shape[0]\n labels = np.zeros(inners.reshape((bs, bs, -1)).shape, dtype=inners.dtype)\n labels_all = np.zeros_like(labels)\n for i in range(inners.shape[0]):\n labels[i, i, 0] = 1\n labels_all[i, i, :] = 1\n return (labels.reshape(inners.shape), labels_all.reshape(inners.shape))","code_tokens":"","url":847475} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"backend_bases.py","full_name":"GraphicsContextBase.get_url","func_name":"get_url","docstring":"Return a url if one is set, None otherwise.","docstring_tokens":"","code":"def get_url(self):\n \"\"\"Return a url if one is set, None otherwise.\"\"\"\n return self._url","code_tokens":"","url":96165} +{"project_name":"rudranil723\/mini-main","file_name":"backend_tools.py","full_name":"ToolViewsPositions.forward","func_name":"forward","docstring":"Forward one step in the stack of views and positions.","docstring_tokens":"","code":"def forward(self):\n \"\"\"Forward one step in the stack of views and positions.\"\"\"\n self.views[self.figure].forward()\n self.positions[self.figure].forward()","code_tokens":"","url":319215} +{"project_name":"facebookresearch\/CompilerGym","file_name":"env_without_bazel_test.py","full_name":"test_reward_before_reset","func_name":"test_reward_before_reset","docstring":"Taking a reward before reset() is illegal.","docstring_tokens":"","code":"def test_reward_before_reset(env: CompilerEnv):\n \"\"\"Taking a reward before reset() is illegal.\"\"\"\n with pytest.raises(SessionNotFound, match='Must call reset\\\\(\\\\) before step\\\\(\\\\)'):\n _ = env.reward['runtime']","code_tokens":"","url":135727} +{"project_name":"rishab-sharma\/object_detection","file_name":"preprocessor_cache.py","full_name":"PreprocessorCache.update","func_name":"update","docstring":"Adds a value to the dictionary.","docstring_tokens":"","code":"def update(self, function_id, key, value):\n \"\"\"Adds a value to the dictionary.\n\n Args:\n function_id: identifier for the preprocessing function used.\n key: identifier for the variable stored.\n value: the value to store, expected to be a tensor or nested structure\n of tensors.\n Raises:\n ValueError: if function_id is not one of the 23 valid function ids.\n \"\"\"\n if function_id not in self._VALID_FNS:\n raise ValueError('Function id not recognized: %s.' % str(function_id))\n self._history[function_id][key] = value","code_tokens":"","url":771872} +{"project_name":"IIT-PAVIS\/acoustic-images-self-supervision","file_name":"shared.py","full_name":"shared_net_legacy","func_name":"shared_net_legacy","docstring":"Builds a three-layer fully-connected modality agnostic network using legacy functions.","docstring_tokens":"","code":"def shared_net_legacy(inputs, num_classes=None, spatial_squeeze=True, scope='shared_net'):\n \"\"\"\n Builds a three-layer fully-connected modality agnostic network using legacy functions.\n \"\"\"\n with tf.variable_scope(scope, [inputs]):\n conv1 = base.build2DConvolution(inputs, 1024, 1024, 1, 1, 1, 1, 0, 0, 'fc1')\n relu1 = base.buildReLU(conv1, 'fc1')\n conv2 = base.build2DConvolution(relu1, 1024, 1000, 1, 1, 1, 1, 0, 0, 'fc2')\n relu2 = base.buildReLU(conv2, 'fc2')\n conv3 = base.build2DConvolution(relu2, 1000, num_classes, 1, 1, 1, 1, 0, 0, 'fc3')\n if spatial_squeeze:\n output = tf.squeeze(conv3, [1, 2], name='fc3\/squeezed')\n else:\n output = conv3\n return (output, {scope + '\/fc1': relu1, scope + '\/fc2': output})","code_tokens":"","url":8622} +{"project_name":"hans\/pyccg","file_name":"test_model.py","full_name":"test_nested_lambda","func_name":"test_nested_lambda","docstring":"Test evaluation of nested lambda expressions.","docstring_tokens":"","code":"def test_nested_lambda():\n \"\"\"\n Test evaluation of nested lambda expressions.\n \"\"\"\n ontology = _make_mock_ontology()\n scene = {'objects': [frozendict(x=3, shape='sphere'), frozendict(x=4, shape='cube')]}\n model = Model(scene, ontology)\n eq_(model.evaluate(Expression.fromstring('unique(\\\\x.left_of(x,unique(\\\\y.cube(y))))')), scene['objects'][0])\n eq_(model.evaluate(Expression.fromstring('sphere(unique(\\\\x.left_of(x,unique(\\\\y.cube(y)))))')), True)","code_tokens":"","url":296054} +{"project_name":"eddylau328\/fyp-artificial-intelligence-ac-control-device","file_name":"encoder.py","full_name":"MessageEncoder","func_name":"MessageEncoder","docstring":"Returns an encoder for a message field.","docstring_tokens":"","code":"def MessageEncoder(field_number, is_repeated, is_packed):\n \"\"\"Returns an encoder for a message field.\"\"\"\n tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)\n local_EncodeVarint = _EncodeVarint\n assert not is_packed\n if is_repeated:\n\n def EncodeRepeatedField(write, value, deterministic):\n for element in value:\n write(tag)\n local_EncodeVarint(write, element.ByteSize(), deterministic)\n element._InternalSerialize(write, deterministic)\n return EncodeRepeatedField\n else:\n\n def EncodeField(write, value, deterministic):\n write(tag)\n local_EncodeVarint(write, value.ByteSize(), deterministic)\n return value._InternalSerialize(write, deterministic)\n return EncodeField","code_tokens":"","url":215315} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"mnist.py","full_name":"mnist_common_generator","func_name":"mnist_common_generator","docstring":"Image generator for MNIST.","docstring_tokens":"","code":"def mnist_common_generator(tmp_dir, training, how_many, data_filename, label_filename, start_from=0):\n \"\"\"Image generator for MNIST.\n\n Args:\n tmp_dir: path to temporary storage directory.\n training: a Boolean; if true, we use the train set, otherwise the test set.\n how_many: how many images and labels to generate.\n data_filename: file that contains features data.\n label_filename: file that contains labels.\n start_from: from which image to start.\n\n Returns:\n An instance of image_generator that produces MNIST images.\n \"\"\"\n data_path = os.path.join(tmp_dir, data_filename)\n labels_path = os.path.join(tmp_dir, label_filename)\n images = _extract_mnist_images(data_path, 60000 if training else 10000)\n labels = _extract_mnist_labels(labels_path, 60000 if training else 10000)\n data = list(zip(images, labels))\n random.shuffle(data)\n (images, labels) = list(zip(*data))\n return image_utils.image_generator(images[start_from:start_from + how_many], labels[start_from:start_from + how_many])","code_tokens":"","url":964923} +{"project_name":"MushroomRL\/mushroom-rl","file_name":"polynomial.py","full_name":"PolynomialBasis.generate","func_name":"generate","docstring":"Factory method to build a polynomial of order ``max_degree`` based on the first ``input_size`` dimensions of the input.","docstring_tokens":"","code":"@staticmethod\ndef generate(max_degree, input_size, low=None, high=None):\n \"\"\"\n Factory method to build a polynomial of order ``max_degree`` based on\n the first ``input_size`` dimensions of the input.\n\n Args:\n max_degree (int): maximum degree of the polynomial;\n input_size (int): size of the input;\n low (np.ndarray, None): array specifying the lower bound of the action space, used to normalize the\n state between -1 and 1;\n high (np.ndarray, None): array specifying the lower bound of the action space, used to normalize the\n state between -1 and 1;\n\n Returns:\n The list of the generated polynomial basis functions.\n\n \"\"\"\n assert max_degree >= 0\n assert input_size > 0\n basis_list = [PolynomialBasis()]\n for e in PolynomialBasis._compute_exponents(max_degree, input_size):\n dims = np.reshape(np.argwhere(e != 0), -1)\n degs = e[e != 0]\n basis_list.append(PolynomialBasis(dims, degs, low, high))\n return basis_list","code_tokens":"","url":266062} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"migrate_repository.py","full_name":"move_file","func_name":"move_file","docstring":"Moves a file and prints a message.","docstring_tokens":"","code":"def move_file(src, tgt):\n \"\"\"Moves a file and prints a message.\"\"\"\n log.info('Moving file %s to %s' % (src, tgt))\n if os.path.exists(tgt):\n raise Exception('Cannot move file %s because target %s already exists' % (src, tgt))\n os.rename(src, tgt)","code_tokens":"","url":129857} +{"project_name":"HazyResearch\/thanos-code","file_name":"scheduler.py","full_name":"SequentialScheduler.get_batches","func_name":"get_batches","docstring":"Generate batch generator from all dataloaders for one epoch.","docstring_tokens":"","code":"def get_batches(self, dataloaders: List[torch.utils.data.DataLoader], model: UnagiModel=None) -> Iterator[Union[Tuple, List[Tuple]]]:\n \"\"\"Generate batch generator from all dataloaders for one epoch.\n\n Args:\n dataloaders: List of dataloaders.\n model: The training model, defaults to None.\n\n Returns:\n A generator of all batches.\n \"\"\"\n data_loaders = [iter(dataloader) for dataloader in dataloaders]\n batch_counts = [len(dataloader) for dataloader in dataloaders]\n if self.fillup:\n batch_counts = [max(batch_counts)] * len(dataloaders)\n 'for idx in range(len(dataloaders)):\\n if dataloaders[idx].n_batches:\\n batch_counts[idx] = dataloaders[idx].n_batches'\n for (data_loader_idx, batch_count) in enumerate(batch_counts):\n for batch_idx in range(batch_count):\n try:\n batch = next(data_loaders[data_loader_idx])\n except StopIteration:\n data_loaders[data_loader_idx] = iter(dataloaders[data_loader_idx])\n batch = next(data_loaders[data_loader_idx])\n if not isinstance(batch, dict):\n (X_dict, Y_dict) = batch\n else:\n X_dict = batch\n Y_dict = None\n yield (X_dict, Y_dict)","code_tokens":"","url":354402} +{"project_name":"meganlsmith\/phyloGAN","file_name":"simulators.py","full_name":"Simulator.countPinvIQTree","func_name":"countPinvIQTree","docstring":"Convert a simulated alignment into a proportion of invariant sites.","docstring_tokens":"","code":"def countPinvIQTree(self, align):\n \"\"\"Convert a simulated alignment into a proportion of invariant sites.\"\"\"\n chunklength = align.get_alignment_length()\n countvarsites = 0\n for i in range(0, chunklength):\n sequence = list(align[:, i])\n if len(set(sequence)) > 1:\n countvarsites += 1\n prop_inv = [1 - countvarsites \/ chunklength]\n return prop_inv","code_tokens":"","url":769303} +{"project_name":"openkinome\/kinoml","file_name":"test_oemodeling.py","full_name":"test_delete_residue","func_name":"test_delete_residue","docstring":"Compare results to number of expected atoms.","docstring_tokens":"","code":"@pytest.mark.parametrize('package, resource, chain_id, residue_name, residue_id, expectation, n_atoms', [('kinoml.data.proteins', '4f8o.pdb', 'A', 'GLY', 22, does_not_raise(), 2468), ('kinoml.data.proteins', '4f8o.pdb', 'A', 'ASP', 22, pytest.raises(ValueError), 2468)])\ndef test_delete_residue(package, resource, chain_id, residue_name, residue_id, expectation, n_atoms):\n \"\"\"Compare results to number of expected atoms.\"\"\"\n with resources.path(package, resource) as path:\n with expectation:\n molecule = read_molecules(str(path))[0]\n selection = delete_residue(molecule, chain_id, residue_name, residue_id)\n assert selection.NumAtoms() == n_atoms","code_tokens":"","url":596288} +{"project_name":"romanorac\/discomll","file_name":"kmeans.py","full_name":"random_init_map","func_name":"random_init_map","docstring":"Assign datapoint `e` randomly to one of the `k` clusters.","docstring_tokens":"","code":"def random_init_map(interface, state, label, inp):\n \"\"\"Assign datapoint `e` randomly to one of the `k` clusters.\"\"\"\n import random\n out = interface.output(0)\n centers = {}\n for row in inp:\n row = row.strip().split(state['delimiter'])\n if len(row) > 1:\n x = [0 if row[i] in state['missing_vals'] else float(row[i]) for i in state['X_indices']]\n cluster = random.randint(0, state['k'] - 1)\n vertex = state['create'](x, 1.0)\n centers[cluster] = vertex if cluster not in centers else state['update'](centers[cluster], vertex)\n for (cluster, values) in centers.iteritems():\n out.add(cluster, values)","code_tokens":"","url":551987} +{"project_name":"google\/mentornet","file_name":"models.py","full_name":"logistic","func_name":"logistic","docstring":"A baseline logistic model.","docstring_tokens":"","code":"def logistic(inputs):\n \"\"\"A baseline logistic model.\"\"\"\n feat_dim = int(inputs.get_shape()[1])\n with tf.variable_scope('logistic'):\n layer_1 = tf.add(tf.matmul(inputs, tf.get_variable('W1', [feat_dim, 1])), tf.get_variable('b1', [1]))\n return layer_1","code_tokens":"","url":632542} +{"project_name":"mj-will\/nessai","file_name":"test_plot.py","full_name":"test_plot_live_points_hue","func_name":"test_plot_live_points_hue","docstring":"Test generating a plot for a set of live points with a hue.","docstring_tokens":"","code":"@pytest.mark.parametrize('c', [None, 'x'])\ndef test_plot_live_points_hue(live_points, c, model):\n \"\"\"Test generating a plot for a set of live points with a hue.\"\"\"\n fig = plot.plot_live_points(live_points, c=c)\n assert fig is not None\n plt.close()","code_tokens":"","url":292362} +{"project_name":"open-mmlab\/mmselfsup","file_name":"batch_shuffle.py","full_name":"batch_shuffle_ddp","func_name":"batch_shuffle_ddp","docstring":"Batch shuffle, for making use of BatchNorm.","docstring_tokens":"","code":"@torch.no_grad()\ndef batch_shuffle_ddp(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Batch shuffle, for making use of BatchNorm.\n\n Args:\n x (torch.Tensor): Data in each GPU.\n\n Returns:\n Tuple[torch.Tensor, torch.Tensor]: Output of shuffle operation.\n - x_gather[idx_this]: Shuffled data.\n - idx_unshuffle: Index for restoring.\n \"\"\"\n batch_size_this = x.shape[0]\n x_gather = concat_all_gather(x)\n batch_size_all = x_gather.shape[0]\n num_gpus = batch_size_all \/\/ batch_size_this\n idx_shuffle = torch.randperm(batch_size_all)\n broadcast(idx_shuffle, src=0)\n idx_unshuffle = torch.argsort(idx_shuffle)\n gpu_idx = get_rank()\n idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]\n return (x_gather[idx_this], idx_unshuffle)","code_tokens":"","url":240475} +{"project_name":"mj-will\/nessai","file_name":"test_stats_utils.py","full_name":"test_weighted_quantile_value_error_neff","func_name":"test_weighted_quantile_value_error_neff","docstring":"Assert an error is raised if the ESS is not finite.","docstring_tokens":"","code":"def test_weighted_quantile_value_error_neff():\n \"\"\"Assert an error is raised if the ESS is not finite.\"\"\"\n with pytest.raises(ValueError, match='Effective sample size is not finite.*'):\n weighted_quantile([1, 2], 0.5, log_weights=np.array([np.NINF, np.NINF]))","code_tokens":"","url":293147} +{"project_name":"salesforce\/CodeRL","file_name":"modeling_tapas.py","full_name":"range_index_map","func_name":"range_index_map","docstring":"Constructs an index map equal to range(num_segments).","docstring_tokens":"","code":"def range_index_map(batch_shape, num_segments, name='range_index_map'):\n \"\"\"\n Constructs an index map equal to range(num_segments).\n\n Args:\n batch_shape (`torch.Size`):\n Batch shape\n num_segments (`int`):\n Number of segments\n name (`str`, *optional*, defaults to 'range_index_map'):\n Name for the operation. Currently not used\n\n Returns:\n (`IndexMap`): IndexMap of shape batch_shape with elements equal to range(num_segments).\n \"\"\"\n batch_shape = torch.as_tensor(batch_shape, dtype=torch.long)\n assert len(batch_shape.size()) == 1\n num_segments = torch.as_tensor(num_segments)\n assert len(num_segments.size()) == 0\n indices = torch.arange(start=0, end=num_segments, device=num_segments.device)\n new_tensor = torch.cat([torch.ones_like(batch_shape, dtype=torch.long, device=num_segments.device), num_segments.unsqueeze(dim=0)], dim=0)\n new_shape = [int(x) for x in new_tensor.tolist()]\n indices = indices.view(new_shape)\n multiples = torch.cat([batch_shape, torch.as_tensor([1])], dim=0)\n indices = indices.repeat(multiples.tolist())\n return IndexMap(indices=indices, num_segments=num_segments, batch_dims=list(batch_shape.size())[0])","code_tokens":"","url":495231} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"tracemalloc.py","full_name":"take_snapshot","func_name":"take_snapshot","docstring":"Take a snapshot of traces of memory blocks allocated by Python.","docstring_tokens":"","code":"def take_snapshot():\n \"\"\"\n Take a snapshot of traces of memory blocks allocated by Python.\n \"\"\"\n if not is_tracing():\n raise RuntimeError('the tracemalloc module must be tracing memory allocations to take a snapshot')\n traces = _get_traces()\n traceback_limit = get_traceback_limit()\n return Snapshot(traces, traceback_limit)","code_tokens":"","url":429757} +{"project_name":"googleapis\/python-aiplatform","file_name":"_language_models.py","full_name":"CodeChatModel.start_chat","func_name":"start_chat","docstring":"Starts a chat session with the code chat model.","docstring_tokens":"","code":"def start_chat(self, *, context: Optional[str]=None, max_output_tokens: Optional[int]=None, temperature: Optional[float]=None, message_history: Optional[List[ChatMessage]]=None, stop_sequences: Optional[List[str]]=None) -> 'CodeChatSession':\n \"\"\"Starts a chat session with the code chat model.\n\n Args:\n context: Context shapes how the model responds throughout the conversation.\n For example, you can use context to specify words the model can or\n cannot use, topics to focus on or avoid, or the response format or style.\n max_output_tokens: Max length of the output text in tokens. Range: [1, 1000].\n temperature: Controls the randomness of predictions. Range: [0, 1].\n stop_sequences: Customized stop sequences to stop the decoding process.\n\n Returns:\n A `ChatSession` object.\n \"\"\"\n return CodeChatSession(model=self, context=context, max_output_tokens=max_output_tokens, temperature=temperature, message_history=message_history, stop_sequences=stop_sequences)","code_tokens":"","url":863141} +{"project_name":"deepmind\/meltingpot","file_name":"substrate_factory.py","full_name":"SubstrateFactory.timestep_spec","func_name":"timestep_spec","docstring":"Returns spec of timestep sent to a single player.","docstring_tokens":"","code":"def timestep_spec(self) -> dm_env.TimeStep:\n \"\"\"Returns spec of timestep sent to a single player.\"\"\"\n return self._timestep_spec","code_tokens":"","url":285589} +{"project_name":"surafelml\/adapt-mnmt","file_name":"inputter.py","full_name":"Inputter.set_data_field","func_name":"set_data_field","docstring":"Sets a data field.","docstring_tokens":"","code":"def set_data_field(self, data, key, value, volatile=False):\n \"\"\"Sets a data field.\n\n Args:\n data: The data dictionary.\n key: The value key.\n value: The value to assign.\n volatile: If ``True``, the key\/value pair will be removed once the\n processing done.\n\n Returns:\n The updated data dictionary.\n \"\"\"\n data[key] = value\n if volatile:\n self.volatile.add(key)\n return data","code_tokens":"","url":407773} +{"project_name":"huawei-noah\/xingtian","file_name":"atari_wrappers.py","full_name":"AtariFireRest.reset","func_name":"reset","docstring":"Take action after reset.","docstring_tokens":"","code":"def reset(self):\n \"\"\"Take action after reset.\"\"\"\n state = self.env.reset()\n (state, _, done, _) = self.env.step(1)\n if done:\n self.env.reset()\n (state, _, done, _) = self.env.step(2)\n if done:\n self.env.reset()\n return state","code_tokens":"","url":962155} +{"project_name":"michaelhush\/M-LOOP","file_name":"learners.py","full_name":"GaussianProcessLearner.create_gaussian_process","func_name":"create_gaussian_process","docstring":"Create a Gaussian process.","docstring_tokens":"","code":"def create_gaussian_process(self):\n \"\"\"\n Create a Gaussian process.\n \"\"\"\n gp_kernel = skk.RBF(length_scale=self.scaled_length_scale, length_scale_bounds=self.scaled_length_scale_bounds)\n if self.cost_has_noise:\n white_kernel = skk.WhiteKernel(noise_level=self.scaled_noise_level, noise_level_bounds=self.scaled_noise_level_bounds)\n gp_kernel = gp_kernel + white_kernel\n alpha = self.scaled_uncers ** 2\n if self.update_hyperparameters:\n self.gaussian_process = skg.GaussianProcessRegressor(alpha=alpha, kernel=gp_kernel, n_restarts_optimizer=self.hyperparameter_searches)\n else:\n self.gaussian_process = skg.GaussianProcessRegressor(alpha=alpha, kernel=gp_kernel, optimizer=None)","code_tokens":"","url":619893} +{"project_name":"explosion\/spaCy","file_name":"test_serialize_tokenizer.py","full_name":"test_issue2833","func_name":"test_issue2833","docstring":"Test that a custom error is raised if a token or span is pickled.","docstring_tokens":"","code":"@pytest.mark.issue(2833)\ndef test_issue2833(en_vocab):\n \"\"\"Test that a custom error is raised if a token or span is pickled.\"\"\"\n doc = Doc(en_vocab, words=['Hello', 'world'])\n with pytest.raises(NotImplementedError):\n pickle.dumps(doc[0])\n with pytest.raises(NotImplementedError):\n pickle.dumps(doc[0:2])","code_tokens":"","url":894359} +{"project_name":"huawei-noah\/xingtian","file_name":"impala_cnn_opt.py","full_name":"calc_pi_loss","func_name":"calc_pi_loss","docstring":"Calculate policy gradient loss.","docstring_tokens":"","code":"def calc_pi_loss(logic_outs, actions, advantages):\n \"\"\"Calculate policy gradient loss.\"\"\"\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=actions, logits=logic_outs)\n advantages = tf.stop_gradient(advantages)\n pg_loss_per_step = cross_entropy * advantages\n return tf.reduce_sum(pg_loss_per_step)","code_tokens":"","url":962258} +{"project_name":"srai-lab\/srai","file_name":"test_osm_way_loader.py","full_name":"valid_and_empty_polygons_area_gdf","func_name":"valid_and_empty_polygons_area_gdf","docstring":"Get an example area gdf with one valid polygon and one without road infrastructure.","docstring_tokens":"","code":"@pytest.fixture\ndef valid_and_empty_polygons_area_gdf(first_polygon_area_gdf: gpd.GeoDataFrame, empty_polygon_area_gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:\n \"\"\"Get an example area gdf with one valid polygon and one without road infrastructure.\"\"\"\n return pd.concat([first_polygon_area_gdf, empty_polygon_area_gdf], axis=0)","code_tokens":"","url":372064} +{"project_name":"RasaHQ\/rasa","file_name":"plugin.py","full_name":"prefixing_custom_actions_response","func_name":"prefixing_custom_actions_response","docstring":"Add namespacing to the response from custom actions.","docstring_tokens":"","code":"@hookspec\ndef prefixing_custom_actions_response(json_body: Dict[Text, Any], response: Dict[Text, Any]) -> None:\n \"\"\"Add namespacing to the response from custom actions.\"\"\"","code_tokens":"","url":836533} +{"project_name":"lxtGH\/CAE","file_name":"ema_head.py","full_name":"reduce_mean","func_name":"reduce_mean","docstring":"Reduce mean when distributed training.","docstring_tokens":"","code":"def reduce_mean(tensor):\n \"\"\"Reduce mean when distributed training.\"\"\"\n if not (dist.is_available() and dist.is_initialized()):\n return tensor\n tensor = tensor.clone()\n dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM)\n return tensor","code_tokens":"","url":108806} +{"project_name":"bachiraoun\/fullrmc","file_name":"GroupSelector.py","full_name":"RecursiveGroupSelector.willSelect","func_name":"willSelect","docstring":"Get whether next step a new selection is occur or still the same group is going to be selected again.","docstring_tokens":"","code":"@property\ndef willSelect(self):\n \"\"\" Get whether next step a new selection is occur or still the same\n group is going to be selected again. \"\"\"\n return self.__position >= self.__recur","code_tokens":"","url":213851} +{"project_name":"mradaideh\/neorl","file_name":"classic.py","full_name":"ackley","func_name":"ackley","docstring":"Ackley test objective function.","docstring_tokens":"","code":"def ackley(individual):\n \"\"\"Ackley test objective function.\n \"\"\"\n N = len(individual)\n return 20 - 20 * exp(-0.2 * sqrt(1.0 \/ N * sum((x ** 2 for x in individual)))) + e - exp(1.0 \/ N * sum((cos(2 * pi * x) for x in individual)))","code_tokens":"","url":735404} +{"project_name":"wandb\/wandb","file_name":"test_kubernetes.py","full_name":"mock_event_streams","func_name":"mock_event_streams","docstring":"Patches the kubernetes event stream with a mock and returns it.","docstring_tokens":"","code":"@pytest.fixture\ndef mock_event_streams(monkeypatch):\n \"\"\"Patches the kubernetes event stream with a mock and returns it.\"\"\"\n job_stream = MockEventStream()\n pod_stream = MockEventStream()\n\n def _select_stream(_, api_call, *args, **kwargs):\n if api_call.__name__ == 'list_namespaced_pod':\n return pod_stream\n elif api_call.__name__ == 'list_namespaced_job':\n return job_stream\n elif api_call.__name__ == 'list_namespaced_custom_object':\n return job_stream\n raise Exception(f'Event stream requested for unsupported API call: {api_call.__name__} ')\n monkeypatch.setattr('wandb.sdk.launch.runner.kubernetes_monitor.SafeWatch.stream', _select_stream)\n return (job_stream, pod_stream)","code_tokens":"","url":941285} +{"project_name":"copenlu\/X-MAML","file_name":"optimization.py","full_name":"get_constant_schedule","func_name":"get_constant_schedule","docstring":"Create a schedule with a constant learning rate.","docstring_tokens":"","code":"def get_constant_schedule(optimizer, last_epoch=-1):\n \"\"\" Create a schedule with a constant learning rate.\n \"\"\"\n return LambdaLR(optimizer, lambda _: 1, last_epoch=last_epoch)","code_tokens":"","url":961663} +{"project_name":"SeldonIO\/MLServer","file_name":"utils.py","full_name":"to_status_code","func_name":"to_status_code","docstring":"Convert a boolean flag into a HTTP status code.","docstring_tokens":"","code":"def to_status_code(flag: bool, error_code: int=status.HTTP_400_BAD_REQUEST) -> int:\n \"\"\"\n Convert a boolean flag into a HTTP status code.\n \"\"\"\n if flag:\n return status.HTTP_200_OK\n return error_code","code_tokens":"","url":630921} +{"project_name":"BMIRDS\/deepslide","file_name":"compute_stats.py","full_name":"load_stats","func_name":"load_stats","docstring":"Load a stats file in json and return mean and std in lists.","docstring_tokens":"","code":"def load_stats(jsonfile: str):\n \"\"\" Load a stats file in json and return mean and std in lists.\n \"\"\"\n with open(jsonfile, 'r') as infile:\n data = json.load(infile)\n print(f\"Stats of '{data['datapath']}' are loaded from {jsonfile}.\")\n return (data['mean'], data['std'])","code_tokens":"","url":539788} +{"project_name":"ZhAnGToNG1\/transfer_learning_cspt","file_name":"accuracy.py","full_name":"accuracy","func_name":"accuracy","docstring":"Calculate accuracy according to the prediction and target.","docstring_tokens":"","code":"@mmcv.jit(coderize=True)\ndef accuracy(pred, target, topk=1, thresh=None):\n \"\"\"Calculate accuracy according to the prediction and target.\n\n Args:\n pred (torch.Tensor): The model prediction, shape (N, num_class)\n target (torch.Tensor): The target of each prediction, shape (N, )\n topk (int | tuple[int], optional): If the predictions in ``topk``\n matches the target, the predictions will be regarded as\n correct ones. Defaults to 1.\n thresh (float, optional): If not None, predictions with scores under\n this threshold are considered incorrect. Default to None.\n\n Returns:\n float | tuple[float]: If the input ``topk`` is a single integer,\n the function will return a single float as accuracy. If\n ``topk`` is a tuple containing multiple integers, the\n function will return a tuple containing accuracies of\n each ``topk`` number.\n \"\"\"\n assert isinstance(topk, (int, tuple))\n if isinstance(topk, int):\n topk = (topk,)\n return_single = True\n else:\n return_single = False\n maxk = max(topk)\n if pred.size(0) == 0:\n accu = [pred.new_tensor(0.0) for i in range(len(topk))]\n return accu[0] if return_single else accu\n assert pred.ndim == 2 and target.ndim == 1\n assert pred.size(0) == target.size(0)\n assert maxk <= pred.size(1), f'maxk {maxk} exceeds pred dimension {pred.size(1)}'\n (pred_value, pred_label) = pred.topk(maxk, dim=1)\n pred_label = pred_label.t()\n correct = pred_label.eq(target.view(1, -1).expand_as(pred_label))\n if thresh is not None:\n correct = correct & (pred_value > thresh).t()\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 \/ pred.size(0)))\n return res[0] if return_single else res","code_tokens":"","url":964173} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"well_known_types.py","full_name":"_FieldMaskTree.AddLeafNodes","func_name":"AddLeafNodes","docstring":"Adds leaf nodes begin with prefix to this tree.","docstring_tokens":"","code":"def AddLeafNodes(self, prefix, node):\n \"\"\"Adds leaf nodes begin with prefix to this tree.\"\"\"\n if not node:\n self.AddPath(prefix)\n for name in node:\n child_path = prefix + '.' + name\n self.AddLeafNodes(child_path, node[name])","code_tokens":"","url":310033} +{"project_name":"opendilab\/DI-star","file_name":"remote_controller.py","full_name":"RemoteController.save_replay","func_name":"save_replay","docstring":"Save a replay, returning the data.","docstring_tokens":"","code":"@valid_status(Status.in_game, Status.in_replay, Status.ended)\n@sw.decorate\ndef save_replay(self):\n \"\"\"Save a replay, returning the data.\"\"\"\n res = self._client.send(save_replay=sc_pb.RequestSaveReplay())\n return res.data","code_tokens":"","url":184754} +{"project_name":"kubeflow\/pipelines","file_name":"artifact_utils.py","full_name":"update_output_artifact","func_name":"update_output_artifact","docstring":"Updates the output artifact with the new uri and metadata.","docstring_tokens":"","code":"def update_output_artifact(executor_input: str, target_artifact_name: str, uri: str, metadata: dict={}) -> None:\n \"\"\"Updates the output artifact with the new uri and metadata.\"\"\"\n executor_input_json = json.loads(executor_input)\n executor_output = {'artifacts': {}}\n for (name, artifacts) in executor_input_json.get('outputs', {}).get('artifacts', {}).items():\n artifacts_list = artifacts.get('artifacts')\n if name == target_artifact_name and artifacts_list:\n updated_runtime_artifact = artifacts_list[0]\n updated_runtime_artifact['uri'] = uri\n updated_runtime_artifact['metadata'] = metadata\n artifacts_list = {'artifacts': [updated_runtime_artifact]}\n executor_output['artifacts'][name] = artifacts_list\n os.makedirs(os.path.dirname(executor_input_json['outputs']['outputFile']), exist_ok=True)\n with open(executor_input_json['outputs']['outputFile'], 'w') as f:\n f.write(json.dumps(executor_output))","code_tokens":"","url":770735} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"_mock_backport.py","full_name":"NonCallableMock.assert_called_once_with","func_name":"assert_called_once_with","docstring":"assert that the mock was called exactly once and with the specified arguments.","docstring_tokens":"","code":"def assert_called_once_with(_mock_self, *args, **kwargs):\n \"\"\"assert that the mock was called exactly once and with the specified\n arguments.\"\"\"\n self = _mock_self\n if not self.call_count == 1:\n msg = \"Expected '%s' to be called once. Called %s times.\" % (self._mock_name or 'mock', self.call_count)\n raise AssertionError(msg)\n return self.assert_called_with(*args, **kwargs)","code_tokens":"","url":219686} +{"project_name":"matsu0228\/nlp-jp","file_name":"connection.py","full_name":"MWSConnection.list_all_fulfillment_orders","func_name":"list_all_fulfillment_orders","docstring":"Returns a list of fulfillment orders fulfilled after (or at) a specified date or by fulfillment method.","docstring_tokens":"","code":"@api_action('Outbound', 30, 0.5)\ndef list_all_fulfillment_orders(self, request, response, **kw):\n \"\"\"Returns a list of fulfillment orders fulfilled after (or\n at) a specified date or by fulfillment method.\n \"\"\"\n return self._post_request(request, kw, response)","code_tokens":"","url":784960} +{"project_name":"dongliangcao\/Self-Supervised-Multimodal-Shape-Matching","file_name":"options.py","full_name":"dict2str","func_name":"dict2str","docstring":"dict to string for printing options.","docstring_tokens":"","code":"def dict2str(opt, indent_level=1):\n \"\"\"dict to string for printing options.\n\n Args:\n opt (dict): Option dict.\n indent_level (int): Indent level. Default 1.\n\n Return:\n (str): Option string for printing.\n \"\"\"\n msg = '\\n'\n for (k, v) in opt.items():\n if isinstance(v, dict):\n msg += ' ' * (indent_level * 2) + str(k) + ':['\n msg += dict2str(v, indent_level + 1)\n msg += ' ' * (indent_level * 2) + ']\\n'\n elif isinstance(v, list):\n msg = ''\n for iv in v:\n if isinstance(iv, dict):\n msg += dict2str(iv, indent_level)\n else:\n msg += '\\n' + ' ' * (indent_level * 2) + str(iv)\n else:\n msg += ' ' * (indent_level * 2) + str(k) + ': ' + str(v) + '\\n'\n return msg","code_tokens":"","url":342158} +{"project_name":"explosion\/spaCy","file_name":"initialize.py","full_name":"load_vectors_into_model","func_name":"load_vectors_into_model","docstring":"Load word vectors from an installed model or path into a model instance.","docstring_tokens":"","code":"def load_vectors_into_model(nlp: 'Language', name: Union[str, Path], *, add_strings: bool=True) -> None:\n \"\"\"Load word vectors from an installed model or path into a model instance.\"\"\"\n try:\n exclude = ['lookups']\n if not add_strings:\n exclude.append('strings')\n vectors_nlp = load_model(name, vocab=nlp.vocab, exclude=exclude)\n except ConfigValidationError as e:\n title = f'Config validation error for vectors {name}'\n desc = \"This typically means that there's a problem in the config.cfg included with the packaged vectors. Make sure that the vectors package you're loading is compatible with the current version of spaCy.\"\n err = ConfigValidationError.from_error(e, title=title, desc=desc)\n raise err from None\n if len(vectors_nlp.vocab.vectors.keys()) == 0 and vectors_nlp.vocab.vectors.mode != VectorsMode.floret or (vectors_nlp.vocab.vectors.shape[0] == 0 and vectors_nlp.vocab.vectors.mode == VectorsMode.floret):\n logger.warning(Warnings.W112.format(name=name))\n for lex in nlp.vocab:\n lex.rank = nlp.vocab.vectors.key2row.get(lex.orth, OOV_RANK)","code_tokens":"","url":894420} +{"project_name":"rlgraph\/rlgraph","file_name":"ray_util.py","full_name":"RayTaskPool.add_task","func_name":"add_task","docstring":"Adds a task to the task pool.","docstring_tokens":"","code":"def add_task(self, worker, ray_object_ids):\n \"\"\"\n Adds a task to the task pool.\n Args:\n worker (any): Worker completing the task, must use the @ray.remote decorator.\n ray_object_ids (Union[str, list]): Ray object id. See ray documentation for how these are used.\n \"\"\"\n if isinstance(ray_object_ids, list):\n ray_object_id = ray_object_ids[0]\n else:\n ray_object_id = ray_object_ids\n self.ray_tasks[ray_object_id] = worker\n self.ray_objects[ray_object_id] = ray_object_ids","code_tokens":"","url":862575} +{"project_name":"deepmind\/dm_alchemy","file_name":"graphs.py","full_name":"graph_distr","func_name":"graph_distr","docstring":"Returns prior over all valid graphs.","docstring_tokens":"","code":"def graph_distr(constraints: Sequence[Constraint]) -> Dict[Graph, float]:\n \"\"\"Returns prior over all valid graphs.\"\"\"\n num_constraints = get_num_constraints(constraints)\n valid_graphs = [(create_graph_from_constraint(constraint), constraint_count) for (constraint, constraint_count) in zip(constraints, num_constraints)]\n graphs_per_constraint = collections.Counter([g[1] for g in valid_graphs])\n prior = [1.0 \/ (len(graphs_per_constraint) * graphs_per_constraint[g[1]]) for g in valid_graphs]\n valid_graphs = [g[0] for g in valid_graphs]\n return {g: p for (g, p) in zip(valid_graphs, prior)}","code_tokens":"","url":522247} +{"project_name":"JunweiLiang\/Object_Detection_Tracking","file_name":"tf_example_decoder.py","full_name":"TfExampleDecoder.decode","func_name":"decode","docstring":"Decode the serialized example.","docstring_tokens":"","code":"def decode(self, serialized_example):\n \"\"\"Decode the serialized example.\n\n Args:\n serialized_example: a single serialized tf.Example string.\n\n Returns:\n decoded_tensors: a dictionary of tensors with the following fields:\n - image: a uint8 tensor of shape [None, None, 3].\n - source_id: a string scalar tensor.\n - height: an integer scalar tensor.\n - width: an integer scalar tensor.\n - groundtruth_classes: a int64 tensor of shape [None].\n - groundtruth_is_crowd: a bool tensor of shape [None].\n - groundtruth_area: a float32 tensor of shape [None].\n - groundtruth_boxes: a float32 tensor of shape [None, 4].\n - groundtruth_instance_masks: a float32 tensor of shape\n [None, None, None].\n - groundtruth_instance_masks_png: a string tensor of shape [None].\n \"\"\"\n parsed_tensors = tf.io.parse_single_example(serialized_example, self._keys_to_features)\n for k in parsed_tensors:\n if isinstance(parsed_tensors[k], tf.SparseTensor):\n if parsed_tensors[k].dtype == tf.string:\n parsed_tensors[k] = tf.sparse_tensor_to_dense(parsed_tensors[k], default_value='')\n else:\n parsed_tensors[k] = tf.sparse_tensor_to_dense(parsed_tensors[k], default_value=0)\n image = self._decode_image(parsed_tensors)\n boxes = self._decode_boxes(parsed_tensors)\n areas = self._decode_areas(parsed_tensors)\n decode_image_shape = tf.logical_or(tf.equal(parsed_tensors['image\/height'], -1), tf.equal(parsed_tensors['image\/width'], -1))\n image_shape = tf.cast(tf.shape(image), dtype=tf.int64)\n parsed_tensors['image\/height'] = tf.where(decode_image_shape, image_shape[0], parsed_tensors['image\/height'])\n parsed_tensors['image\/width'] = tf.where(decode_image_shape, image_shape[1], parsed_tensors['image\/width'])\n is_crowds = tf.cond(tf.greater(tf.shape(parsed_tensors['image\/object\/is_crowd'])[0], 0), lambda : tf.cast(parsed_tensors['image\/object\/is_crowd'], dtype=tf.bool), lambda : tf.zeros_like(parsed_tensors['image\/object\/class\/label'], dtype=tf.bool))\n if self._regenerate_source_id:\n source_id = _get_source_id_from_encoded_image(parsed_tensors)\n else:\n source_id = tf.cond(tf.greater(tf.strings.length(parsed_tensors['image\/source_id']), 0), lambda : parsed_tensors['image\/source_id'], lambda : _get_source_id_from_encoded_image(parsed_tensors))\n if self._include_mask:\n masks = self._decode_masks(parsed_tensors)\n decoded_tensors = {'image': image, 'source_id': source_id, 'height': parsed_tensors['image\/height'], 'width': parsed_tensors['image\/width'], 'groundtruth_classes': parsed_tensors['image\/object\/class\/label'], 'groundtruth_is_crowd': is_crowds, 'groundtruth_area': areas, 'groundtruth_boxes': boxes}\n if self._include_mask:\n decoded_tensors.update({'groundtruth_instance_masks': masks, 'groundtruth_instance_masks_png': parsed_tensors['image\/object\/mask']})\n return decoded_tensors","code_tokens":"","url":796279} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjDataWrapper.site_xpos","func_name":"site_xpos","docstring":"Cartesian site position (nsite x 3).","docstring_tokens":"","code":"@util.CachedProperty\ndef site_xpos(self):\n \"\"\"Cartesian site position (nsite x 3).\"\"\"\n return util.buf_to_npy(self._ptr.contents.site_xpos, (self._model.nsite, 3))","code_tokens":"","url":440553} +{"project_name":"clvrai\/spirl","file_name":"dist_utils.py","full_name":"safe_entropy","func_name":"safe_entropy","docstring":"Computes entropy even if some entries are 0.","docstring_tokens":"","code":"def safe_entropy(dist, dim=None, eps=1e-12):\n \"\"\"Computes entropy even if some entries are 0.\"\"\"\n return -torch.sum(dist * safe_log_prob(dist, eps), dim=dim)","code_tokens":"","url":897036} +{"project_name":"thograce\/C2FNet","file_name":"Res2Net_v1b.py","full_name":"res2net101_v1b","func_name":"res2net101_v1b","docstring":"Constructs a Res2Net-50_v1b_26w_4s lib.","docstring_tokens":"","code":"def res2net101_v1b(pretrained=False, **kwargs):\n \"\"\"Constructs a Res2Net-50_v1b_26w_4s lib.\n Args:\n pretrained (bool): If True, returns a lib pre-trained on ImageNet\n \"\"\"\n model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth=26, scale=4, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s']))\n return model","code_tokens":"","url":410736} +{"project_name":"deepmind\/acme","file_name":"structured.py","full_name":"StructuredAdder.add_first","func_name":"add_first","docstring":"Record the first observation of an episode.","docstring_tokens":"","code":"def add_first(self, timestep: dm_env.TimeStep):\n \"\"\"Record the first observation of an episode.\"\"\"\n if not timestep.first():\n raise ValueError('adder.add_first called with a timestep that was not the first of itsepisode (i.e. one for which timestep.first() is not True)')\n if self._writer is None:\n self._writer = self._client.structured_writer(self._configs)\n self._writer_created_at = time.time()\n self._writer.append(data=self._make_step(observation=timestep.observation, start_of_episode=timestep.first()), partial_step=True)\n self._writer.flush(self._max_in_flight_items)","code_tokens":"","url":8029} +{"project_name":"AndrewSpano\/BSc-Thesis","file_name":"cmd_args.py","full_name":"parse_hf_pos_input","func_name":"parse_hf_pos_input","docstring":"Parses the input for the Hugging Face PoS Tagging training script.","docstring_tokens":"","code":"def parse_hf_pos_input(arg: Optional[List[str]]=None) -> argparse.Namespace:\n \"\"\"Parses the input for the Hugging Face PoS Tagging training script.\"\"\"\n default_logdir = Path(__file__).parent.parent \/ 'logs' \/ 'hf-pos'\n default_loaddir = Path(__file__).parent.parent \/ 'objects' \/ 'HF-AG-RoBERTa'\n default_savedir = Path(__file__).parent.parent \/ 'objects' \/ 'HF-PoS-AG-RoBERTa'\n default_seed = 'random'\n desc = 'HF PoS Tagging Training script.'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('-l', '--logdir', type=Path, action='store', metavar='logs-directory', default=default_logdir, help='Path to the tensorboard logs directory.')\n parser.add_argument('-c', '--config-path', type=Path, action='store', metavar='configuration-file', help='Path to the configuration file that will be used to set the hyperparameters of the model.')\n parser.add_argument('-t', '--pre-trained-model', type=Path, action='store', metavar='pre-trained-mlm', default=default_loaddir, help='The path to the pre-trained MLM Ancient Greek RoBERTa model.')\n parser.add_argument('-s', '--savedir', type=Path, action='store', default=default_savedir, metavar='model-save-directory', help='Path to the directory where the PoS tagging fine-tuned model will be saved.')\n parser.add_argument('-p', '--plot-savepath', type=Path, action='store', metavar='path-to-save-learning-curves-plot', help='Path to the a .png filename where the learning curves for the current experiment will be saved.')\n parser.add_argument('-m', '--confusion-matrix', type=Path, action='store', metavar='path-to-confusion-matrix-heatmap', help='Path to the .png filename where the confusion matrix of the test set will be saved.')\n parser.add_argument('-n', '--no-cuda', action='store_true', help='If toggled, then no GPUs will be used for training. Else, all available GPUs will be used.')\n parser.add_argument('--seed', type=str, action='store', default=default_seed, metavar='seed', help='Random seed to be set. Used for reproducibility purposes. If not specified, then a random seed will be set.')\n return parser.parse_args(arg)","code_tokens":"","url":410079} +{"project_name":"nosyndicate\/pytorchrl","file_name":"parameterized.py","full_name":"Parameterized.ordered_params","func_name":"ordered_params","docstring":"Return the named parameters in a list.","docstring_tokens":"","code":"def ordered_params(self):\n \"\"\"\n Return the named parameters in a list.\n \"\"\"\n namedparams = sorted(self.get_internal_named_params(), key=lambda x: x[0])\n return [param[1] for param in namedparams]","code_tokens":"","url":815397} +{"project_name":"Stable-Baselines-Team\/stable-baselines","file_name":"test_save.py","full_name":"test_model_manipulation","func_name":"test_model_manipulation","docstring":"Test if the algorithm (with a given policy) can be loaded and saved without any issues, the environment switching works and that the action prediction works :param model_class: (BaseRLModel) A RL model :param storage_method: (str) Should file be saved to a file (\"path\") or to a buffer (\"file-like\") :param store_format: (str) Save format, either \"zip\" or \"cloudpickle\".","docstring_tokens":"","code":"@pytest.mark.slow\n@pytest.mark.parametrize('model_class', MODEL_LIST)\n@pytest.mark.parametrize('storage_method', STORE_METHODS)\n@pytest.mark.parametrize('store_format', STORE_FORMAT)\ndef test_model_manipulation(request, model_class, storage_method, store_format):\n \"\"\"\n Test if the algorithm (with a given policy) can be loaded and saved without any issues, the environment switching\n works and that the action prediction works\n\n :param model_class: (BaseRLModel) A RL model\n :param storage_method: (str) Should file be saved to a file (\"path\") or to a buffer\n (\"file-like\")\n :param store_format: (str) Save format, either \"zip\" or \"cloudpickle\".\n \"\"\"\n model_fname = '.\/test_model_{}.model'.format(request.node.name)\n store_as_cloudpickle = store_format == 'cloudpickle'\n kwargs = dict(seed=0, gamma=0.4)\n if model_class in [DQN]:\n kwargs['learning_starts'] = 0\n kwargs['exploration_final_eps'] = 0.05\n if model_class == PPO1:\n kwargs['entcoeff'] = 0.0\n kwargs['optim_batchsize'] = 4\n kwargs['timesteps_per_actorbatch'] = 4\n if model_class in [A2C, ACKTR, PPO2]:\n kwargs['n_steps'] = 4\n kwargs['ent_coef'] = 0.0\n if model_class in [TRPO]:\n kwargs['timesteps_per_batch'] = 4\n try:\n env = DummyVecEnv([lambda : IdentityEnv(10)])\n model = model_class(policy='MlpPolicy', env=env, **kwargs)\n model.learn(total_timesteps=15)\n env.envs[0].action_space.seed(0)\n (mean_reward, _) = evaluate_policy(model, env, deterministic=True, n_eval_episodes=N_EVAL_EPISODES)\n env = model.get_env()\n obs = env.reset()\n observations = np.array([env.step([env.action_space.sample()])[0] for _ in range(10)])\n observations = np.squeeze(observations)\n (selected_actions, _) = model.predict(observations, deterministic=True)\n actions = np.array([env.action_space.sample() for _ in range(10)])\n actions_probas = model.action_probability(observations, actions=actions)\n assert actions_probas.shape == (len(actions), 1), actions_probas.shape\n assert actions_probas.min() >= 0, actions_probas.min()\n assert actions_probas.max() <= 1, actions_probas.max()\n if storage_method == 'path':\n model.save(model_fname, cloudpickle=store_as_cloudpickle)\n else:\n b_io = BytesIO()\n model.save(b_io, cloudpickle=store_as_cloudpickle)\n model_bytes = b_io.getvalue()\n b_io.close()\n del model, env\n if storage_method == 'path':\n model = model_class.load(model_fname)\n else:\n b_io = BytesIO(model_bytes)\n model = model_class.load(b_io)\n b_io.close()\n env = DummyVecEnv([lambda : IdentityEnv(10)])\n model.set_env(env)\n (new_selected_actions, _) = model.predict(observations, deterministic=True)\n assert np.allclose(selected_actions, new_selected_actions, 0.0001)\n model.learn(total_timesteps=15)\n evaluate_policy(model, env, n_eval_episodes=N_EVAL_EPISODES)\n del model, env\n finally:\n if os.path.exists(model_fname):\n os.remove(model_fname)","code_tokens":"","url":873270} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"GlobalWrapper.glow","func_name":"glow","docstring":"glow coefficient for selected body.","docstring_tokens":"","code":"@property\ndef glow(self):\n \"\"\"glow coefficient for selected body.\"\"\"\n return self._ptr.contents.glow","code_tokens":"","url":440165} +{"project_name":"UWARG\/computer-vision-python","file_name":"test_camera_properties.py","full_name":"TestRotationMatrix.test_yaw_quarter","func_name":"test_yaw_quarter","docstring":"Quarter turn towards east from north.","docstring_tokens":"","code":"def test_yaw_quarter(self):\n \"\"\"\n Quarter turn towards east from north.\n \"\"\"\n yaw = np.pi \/ 2\n pitch = 0.0\n roll = 0.0\n expected = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], dtype=np.float32)\n (result, actual) = camera_properties.create_rotation_matrix_from_orientation(yaw, pitch, roll)\n assert result\n assert actual is not None\n np.testing.assert_almost_equal(actual, expected)","code_tokens":"","url":470463} +{"project_name":"salesforce\/CodeRL","file_name":"test_feature_extraction_detr.py","full_name":"DetrFeatureExtractionTester.get_expected_values","func_name":"get_expected_values","docstring":"This function computes the expected height and width when providing images to DetrFeatureExtractor, assuming do_resize is set to True with a scalar size.","docstring_tokens":"","code":"def get_expected_values(self, image_inputs, batched=False):\n \"\"\"\n This function computes the expected height and width when providing images to DetrFeatureExtractor,\n assuming do_resize is set to True with a scalar size.\n \"\"\"\n if not batched:\n image = image_inputs[0]\n if isinstance(image, Image.Image):\n (w, h) = image.size\n else:\n (h, w) = (image.shape[1], image.shape[2])\n if w < h:\n expected_height = int(self.size * h \/ w)\n expected_width = self.size\n elif w > h:\n expected_height = self.size\n expected_width = int(self.size * w \/ h)\n else:\n expected_height = self.size\n expected_width = self.size\n else:\n expected_values = []\n for image in image_inputs:\n (expected_height, expected_width) = self.get_expected_values([image])\n expected_values.append((expected_height, expected_width))\n expected_height = max(expected_values, key=lambda item: item[0])[0]\n expected_width = max(expected_values, key=lambda item: item[1])[1]\n return (expected_height, expected_width)","code_tokens":"","url":495625} +{"project_name":"ilya16\/MultINN","file_name":"rnn_nade.py","full_name":"RnnNade.sample_single","func_name":"sample_single","docstring":"Computes a sample and its probability from a batch of states.","docstring_tokens":"","code":"def sample_single(self, inputs, state):\n \"\"\"Computes a sample and its probability from a batch of states.\n\n Args:\n inputs: (Unused) A batch of inputs from which sampling may start.\n state: An RnnEstimatorStateTuple containing the RNN-NADE state\n for each sample in the batch\n\n Returns:\n eval: A sample for each input state, sized `[batch_size, num_dims]`.\n log_prob: The log probability of each sample, sized `[batch_size, 1]`.\n \"\"\"\n (sample, log_prob) = self._nade.sample(state.b_enc, state.b_dec, temperature=1.0)\n return (sample, log_prob)","code_tokens":"","url":644270} +{"project_name":"apeterswu\/RL4NMT","file_name":"translate.py","full_name":"compile_data","func_name":"compile_data","docstring":"Concatenate all `datasets` and save to `filename`.","docstring_tokens":"","code":"def compile_data(tmp_dir, datasets, filename):\n \"\"\"Concatenate all `datasets` and save to `filename`.\"\"\"\n filename = os.path.join(tmp_dir, filename)\n with tf.gfile.GFile(filename + '.lang1', mode='w') as lang1_resfile:\n with tf.gfile.GFile(filename + '.lang2', mode='w') as lang2_resfile:\n for dataset in datasets:\n url = dataset[0]\n compressed_filename = os.path.basename(url)\n compressed_filepath = os.path.join(tmp_dir, compressed_filename)\n generator_utils.maybe_download(tmp_dir, compressed_filename, url)\n if dataset[1][0] == 'tsv':\n (_, src_column, trg_column, glob_pattern) = dataset[1]\n filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))\n if not filenames:\n mode = 'r:gz' if compressed_filepath.endswith('gz') else 'r'\n with tarfile.open(compressed_filepath, mode) as corpus_tar:\n corpus_tar.extractall(tmp_dir)\n filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))\n for tsv_filename in filenames:\n if tsv_filename.endswith('.gz'):\n new_filename = tsv_filename.strip('.gz')\n generator_utils.gunzip_file(tsv_filename, new_filename)\n tsv_filename = new_filename\n with tf.gfile.GFile(tsv_filename, mode='r') as tsv_file:\n for line in tsv_file:\n if line and '\\t' in line:\n parts = line.split('\\t')\n (source, target) = (parts[src_column], parts[trg_column])\n lang1_resfile.write(source.strip() + '\\n')\n lang2_resfile.write(target.strip() + '\\n')\n else:\n (lang1_filename, lang2_filename) = dataset[1]\n lang1_filepath = os.path.join(tmp_dir, lang1_filename)\n lang2_filepath = os.path.join(tmp_dir, lang2_filename)\n is_sgm = lang1_filename.endswith('sgm') and lang2_filename.endswith('sgm')\n if not (os.path.exists(lang1_filepath) and os.path.exists(lang2_filepath)):\n mode = 'r:gz' if compressed_filepath.endswith('gz') else 'r'\n with tarfile.open(compressed_filepath, mode) as corpus_tar:\n corpus_tar.extractall(tmp_dir)\n if lang1_filepath.endswith('.gz'):\n new_filepath = lang1_filepath.strip('.gz')\n generator_utils.gunzip_file(lang1_filepath, new_filepath)\n lang1_filepath = new_filepath\n if lang2_filepath.endswith('.gz'):\n new_filepath = lang2_filepath.strip('.gz')\n generator_utils.gunzip_file(lang2_filepath, new_filepath)\n lang2_filepath = new_filepath\n with tf.gfile.GFile(lang1_filepath, mode='r') as lang1_file:\n with tf.gfile.GFile(lang2_filepath, mode='r') as lang2_file:\n (line1, line2) = (lang1_file.readline(), lang2_file.readline())\n while line1 or line2:\n line1res = _preprocess_sgm(line1, is_sgm)\n line2res = _preprocess_sgm(line2, is_sgm)\n if line1res or line2res:\n lang1_resfile.write(line1res.strip() + '\\n')\n lang2_resfile.write(line2res.strip() + '\\n')\n (line1, line2) = (lang1_file.readline(), lang2_file.readline())\n return filename","code_tokens":"","url":330941} +{"project_name":"sek788432\/Waymo-2D-Object-Detection","file_name":"global_features_utils.py","full_name":"debug_and_log","func_name":"debug_and_log","docstring":"Outputs `msg` to both stdout (if in the debug mode) and the log file.","docstring_tokens":"","code":"def debug_and_log(msg, debug=True, log=True, debug_on_the_same_line=False):\n \"\"\"Outputs `msg` to both stdout (if in the debug mode) and the log file.\n\n Args:\n msg: String, message to be logged.\n debug: Bool, if True, will print `msg` to stdout.\n log: Bool, if True, will redirect `msg` to the logfile.\n debug_on_the_same_line: Bool, if True, will print `msg` to stdout without a\n new line. When using this mode, logging to a logfile is disabled.\n \"\"\"\n if debug_on_the_same_line:\n print(msg, end='')\n return\n if debug:\n print(msg)\n if log:\n logging.info(msg)","code_tokens":"","url":974287} +{"project_name":"MarvinBertin\/Stanford-NLP-Course","file_name":"Datum.py","full_name":"Datum.isValidTest","func_name":"isValidTest","docstring":"Returns true if the error is within edit distance one and contains no numerics\/punctuation.","docstring_tokens":"","code":"def isValidTest(self):\n \"\"\"Returns true if the error is within edit distance one and contains no numerics\/punctuation.\"\"\"\n if not self.hasError():\n return False\n distance = dameraulevenshtein(self.word, self.error)\n if distance > 1:\n return False\n regex = '.*[^a-zA-Z].*'\n if re.match(regex, self.word) or re.match(regex, self.error):\n return False\n return True","code_tokens":"","url":873424} +{"project_name":"pokaxpoka\/sunrise","file_name":"fisher_factors.py","full_name":"FisherFactor.make_covariance_update_op","func_name":"make_covariance_update_op","docstring":"Constructs and returns the covariance update Op.","docstring_tokens":"","code":"def make_covariance_update_op(self, ema_decay, update_type='online'):\n \"\"\"Constructs and returns the covariance update Op.\n Args:\n ema_decay: The exponential moving average decay (float or Tensor).\n Returns:\n An Op for updating the covariance Variable referenced by _cov.\n \"\"\"\n new_cov = math_ops.add_n(tuple((self._compute_new_cov(idx) for idx in range(self._num_sources))))\n if update_type == 'online':\n return moving_averages.assign_moving_average(self._cov, new_cov, ema_decay, zero_debias=ZERO_DEBIAS)\n elif update_type == 'accumulate':\n return self._cov.assign_add(new_cov)\n elif update_type == 'minibatch':\n return self._cov.assign(new_cov)","code_tokens":"","url":911812} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"compiler.py","full_name":"CodeGenerator.macro_def","func_name":"macro_def","docstring":"Dump the macro definition for the def created by macro_body.","docstring_tokens":"","code":"def macro_def(self, macro_ref, frame):\n \"\"\"Dump the macro definition for the def created by macro_body.\"\"\"\n arg_tuple = ', '.join((repr(x.name) for x in macro_ref.node.args))\n name = getattr(macro_ref.node, 'name', None)\n if len(macro_ref.node.args) == 1:\n arg_tuple += ','\n self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, context.eval_ctx.autoescape)' % (name, arg_tuple, macro_ref.accesses_kwargs, macro_ref.accesses_varargs, macro_ref.accesses_caller))","code_tokens":"","url":39180} +{"project_name":"deepmind\/pycolab","file_name":"ordeal.py","full_name":"make_game","func_name":"make_game","docstring":"Builds and returns an Ordeal game.","docstring_tokens":"","code":"def make_game():\n \"\"\"Builds and returns an Ordeal game.\"\"\"\n\n def make_castle():\n return ascii_art.ascii_art_to_game(GAME_ART_CASTLE, what_lies_beneath=' ', sprites=dict(P=PlayerSprite, D=DragonduckSprite), update_schedule=['P', 'D'], z_order=['D', 'P'])\n\n def make_cavern():\n return ascii_art.ascii_art_to_game(GAME_ART_CAVERN, what_lies_beneath=' ', sprites=dict(P=PlayerSprite), drapes=dict(S=SwordDrape), update_schedule=['P', 'S'])\n\n def make_kansas():\n return ascii_art.ascii_art_to_game(GAME_ART_KANSAS, what_lies_beneath='~', sprites=dict(P=PlayerSprite))\n crop_kansas = cropping.ScrollingCropper(rows=8, cols=15, to_track='P', scroll_margins=(2, 3))\n return storytelling.Story(chapters=dict(castle=make_castle, cavern=make_cavern, kansas=make_kansas), croppers=dict(castle=None, cavern=None, kansas=crop_kansas), first_chapter='kansas')","code_tokens":"","url":819257} +{"project_name":"gaurav0535\/NaturalLanguageProcessing","file_name":"models.py","full_name":"Batch.make_mask","func_name":"make_mask","docstring":"Create a mask to hide future words.","docstring_tokens":"","code":"@staticmethod\ndef make_mask(data, pad):\n \"\"\"Create a mask to hide future words.\"\"\"\n mask = (data != pad).unsqueeze(-2)\n mask = mask & Variable(subsequent_mask(data.size(-1)).type_as(mask.data))\n return mask","code_tokens":"","url":672941} +{"project_name":"ifwe\/digsby","file_name":"imwin_native.py","full_name":"DigsbyFlatNotebook.ActiveTab","func_name":"ActiveTab","docstring":"Property that returns the selected NoteBook page, or None if there isn't one.","docstring_tokens":"","code":"@property\ndef ActiveTab(self):\n \"\"\"\n Property that returns the selected NoteBook page, or None if there isn't one.\n \"\"\"\n sel = self.GetSelection()\n if sel != -1:\n return self.GetPage(sel)\n elif self.GetPageCount() > 0:\n return self.GetPage(0)\n return None","code_tokens":"","url":185424} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_hdbscan.py","full_name":"test_hdbscan_allow_single_cluster_with_epsilon","func_name":"test_hdbscan_allow_single_cluster_with_epsilon","docstring":"Tests that HDBSCAN single-cluster selection with epsilon works correctly.","docstring_tokens":"","code":"def test_hdbscan_allow_single_cluster_with_epsilon():\n \"\"\"\n Tests that HDBSCAN single-cluster selection with epsilon works correctly.\n \"\"\"\n rng = np.random.RandomState(0)\n no_structure = rng.rand(150, 2)\n labels = HDBSCAN(min_cluster_size=5, cluster_selection_epsilon=0.0, cluster_selection_method='eom', allow_single_cluster=True).fit_predict(no_structure)\n (unique_labels, counts) = np.unique(labels, return_counts=True)\n assert len(unique_labels) == 2\n assert counts[unique_labels == -1] > 30\n labels = HDBSCAN(min_cluster_size=5, cluster_selection_epsilon=0.18, cluster_selection_method='eom', allow_single_cluster=True, algorithm='kd_tree').fit_predict(no_structure)\n (unique_labels, counts) = np.unique(labels, return_counts=True)\n assert len(unique_labels) == 2\n assert counts[unique_labels == -1] == 2","code_tokens":"","url":852849} +{"project_name":"matsu0228\/nlp-jp","file_name":"read_preferences.py","full_name":"_ServerMode.mode","func_name":"mode","docstring":"The mode of this read preference instance.","docstring_tokens":"","code":"@property\ndef mode(self):\n \"\"\"The mode of this read preference instance.\n \"\"\"\n return self.__mode","code_tokens":"","url":805001} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"thinkstats2.py","full_name":"Cdf.Values","func_name":"Values","docstring":"Returns a sorted list of values.","docstring_tokens":"","code":"def Values(self):\n \"\"\"Returns a sorted list of values.\n \"\"\"\n return self.xs","code_tokens":"","url":12935} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"context.py","full_name":"in_graph_mode","func_name":"in_graph_mode","docstring":"Returns True if current thread is in GRAPH mode for default context.","docstring_tokens":"","code":"def in_graph_mode():\n \"\"\"Returns True if current thread is in GRAPH mode for default context.\"\"\"\n return context().in_graph_mode()","code_tokens":"","url":605133} +{"project_name":"accel-brain\/accel-brain-code","file_name":"data_visualizer.py","full_name":"DataVisualizer.plot_portfolio","func_name":"plot_portfolio","docstring":"Plot potrfolio optimized by DQN.","docstring_tokens":"","code":"def plot_portfolio(self, rebalance_policy='min_vol', rebalance_sub_policy=None, timing_policy=None, bad_end_flag=False):\n \"\"\"\n Plot potrfolio optimized by DQN.\n\n Args:\n rebalance_policy: `str` value.\n - `min_vol`: Visualize portfolios generated in a mode where portfolio optimization is based on volatility minimization.\n - `max_sharpe_ratio`: Visualize portfolios generated in a mode where portfolio optimization is based on sharpe ratio maximization.\n\n rebalance_sub_policy: `str` value.\n - `buy_and_sell`: Outputs the results of agents performing normal trading.\n - `dollar_cost_averaging`: By referring to the dollar cost averaging method, the agent outputs the results when making an investment strategy decision (although it does not necessarily follow the dollar cost averaging method completely).\n\n timing_policy: `str` value.\n - `only_drl`: The agent makes decisions on the timing of rebalancing and rotation by purely following the Q-value of deep reinforcement learning.\n - `multi_trade_observer`: The following agent results are output. By observing the technical indicator measuring instruments implemented in the interface of `MultiTradeObserver`, the agent can refer not only to the Q value of deep reinforcement learning but also to the\" buy sign \"and\" sell sign \"of various technical indicators. By doing so, you can make investment strategy decisions.\n\n bad_end_flag: `bool` value. The default value is `False`.\n If `False`, this method outputs the result when the yield is the highest.\n If `True`, this method outputs the result when the yield is the lowest.\n \"\"\"\n key = self.__key\n ticker_n = self.__master_df.ticker.drop_duplicates().shape[0]\n col = cm.Spectral(np.arange(ticker_n) \/ ticker_n)\n result_agent_master_df = pd.read_csv('result\/result_agent_master_' + str(key) + '.csv')\n result_agent_master_df = result_agent_master_df[result_agent_master_df.rebalance_policy == rebalance_policy]\n if rebalance_sub_policy is not None:\n result_agent_master_df = result_agent_master_df[result_agent_master_df.rebalance_sub_policy == rebalance_sub_policy]\n if timing_policy is not None:\n result_agent_master_df = result_agent_master_df[result_agent_master_df.timing_policy == timing_policy]\n try:\n if bad_end_flag is False:\n batch_n = result_agent_master_df[result_agent_master_df.yeild == result_agent_master_df.yeild.max()].batch_n.values[0]\n else:\n batch_n = result_agent_master_df[result_agent_master_df.yeild == result_agent_master_df.yeild.min()].batch_n.values[0]\n except IndexError:\n print('Data is not found.')\n return None\n agent_master_key = result_agent_master_df[result_agent_master_df.yeild == result_agent_master_df.yeild.max()].agent_master_key.values[0]\n talkative_num_list_arr = np.load('result\/talkative_num_list_' + str(key) + '.npy')\n talkative_num_list_arr = talkative_num_list_arr.transpose((0, 2, 1, 3))\n talkative_num_arr = talkative_num_list_arr[int(batch_n), int(agent_master_key)]\n pie_df = pd.read_csv('result\/pie_' + str(key) + '.csv')\n _pie_df = pie_df[pie_df.batch_n == batch_n]\n _pie_df = _pie_df[_pie_df.agent_master_key == agent_master_key]\n iter_n_arr = _pie_df.iter_n.drop_duplicates().values\n viz_pie_df = None\n for iter_n in iter_n_arr:\n try:\n df = _pie_df[_pie_df.iter_n == iter_n]\n date_n = df.date_n.values[0]\n date_str = result_agent_master_df[result_agent_master_df.days == date_n]['date'].values[0]\n label_list = [col for col in df.columns if col not in ['agent_master_key', 'batch_n', 'iter_n', 'date_n']]\n except:\n continue\n try:\n company_name_list = [self.__master_df[self.__master_df.ticker == ticker].company_name.values[0] for ticker in label_list]\n except:\n company_name_list = label_list\n pie_arr = df[label_list].values.reshape(-1)\n pie_arr = pie_arr \/ pie_arr.sum()\n plt.figure(figsize=(8, 8))\n (patches, texts, autotexts) = plt.pie(pie_arr, colors=col, labels=company_name_list, counterclock=False, startangle=90, autopct=lambda p: '{:.1f}%'.format(p) if p >= 0.1 else '', pctdistance=0.7)\n plt.legend(company_name_list, loc=(0.62, 0.05), bbox_to_anchor=(1, 0, 0.5, 1))\n plt.title('date: ' + date_str)\n plt.show()\n if viz_pie_df is None:\n viz_pie_df = df[[col for col in df.columns if col not in ['iter_n', 'date_n', 'batch_n']]]\n else:\n _viz_pie_df = df[[col for col in df.columns if col not in ['iter_n', 'date_n', 'batch_n']]]\n viz_pie_df = pd.concat([viz_pie_df, _viz_pie_df])\n talkative_num_df = pd.DataFrame(talkative_num_arr)\n talkative_num_df.columns = [col + '_n' for col in viz_pie_df.columns if col != 'agent_master_key']\n df = result_agent_master_df[result_agent_master_df.batch_n == batch_n]\n df = df[df.agent_master_key == agent_master_key]\n df.money = df.money.astype(int)\n df.cost = df.cost.astype(int)\n df = df.sort_values(by=['agent_master_key', 'date'])\n df = df.reset_index()\n viz_pie_df = viz_pie_df.reset_index()\n result_df = pd.concat([df[['date', 'money', 'assessment', 'rebalancing_prob', 'buy', 'cum_buy', 'sell', 'cum_sell', 'cost', 'cum_cost', 'income_gain', 'trading_profit', 'cum_trading_profit_and_loss', 'yeild', 'timing_policy']], viz_pie_df, talkative_num_df], axis=1)\n return result_df","code_tokens":"","url":7066} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"cookies.py","full_name":"get_cookie_header","func_name":"get_cookie_header","docstring":"Produce an appropriate Cookie header string to be sent with `request`, or None.","docstring_tokens":"","code":"def get_cookie_header(jar, request):\n \"\"\"Produce an appropriate Cookie header string to be sent with `request`, or None.\"\"\"\n r = MockRequest(request)\n jar.add_cookie_header(r)\n return r.get_new_headers().get('Cookie')","code_tokens":"","url":131123} +{"project_name":"deepmind\/dm_control","file_name":"viewer.py","full_name":"CameraSelector.select_next","func_name":"select_next","docstring":"Cycles to the next scene camera.","docstring_tokens":"","code":"def select_next(self):\n \"\"\"Cycles to the next scene camera.\"\"\"\n self._camera_idx += 1\n if not self._model.ncam or self._camera_idx >= self._model.ncam:\n self._camera_idx = -1\n self._commit_selection()","code_tokens":"","url":166624} +{"project_name":"dibyaghosh\/gcsl","file_name":"resources_test.py","full_name":"TestAssetBundle.test_add_mujoco","func_name":"test_add_mujoco","docstring":"Tests adding a MuJoCo file.","docstring_tokens":"","code":"def test_add_mujoco(self):\n \"\"\"Tests adding a MuJoCo file.\"\"\"\n resources = DummyResources({'a\/b\/main.xml': '<\/mujoco>', 'a\/child1.xml': '\\n \\n \\n \\n \\n \\n <\/asset>\\n <\/mujoco>\\n ', 'a\/c\/hello.stl': 'Hello!', 'a\/c\/world.stl': 'World!'})\n bundle = AssetBundle(dest_path='test', dry_run=True, resource_fn=resources.get_resource)\n transformed_path = bundle.add_mujoco('a\/b\/main.xml')\n self.assertEqual(transformed_path, 'test\/a\/b\/main.xml')\n self.assertDictEqual(bundle.copied_paths, {'a\/b\/main.xml': 'test\/a\/b\/main.xml', 'a\/child1.xml': 'test\/a\/child1.xml', 'a\/c\/hello.stl': 'test\/a\/c\/hello.stl', 'a\/c\/world.stl': 'test\/a\/c\/world.stl'})","code_tokens":"","url":202133} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"seq2seq_attention_model.py","full_name":"Seq2SeqAttentionModel.decode_topk","func_name":"decode_topk","docstring":"Return the topK results and new decoder states.","docstring_tokens":"","code":"def decode_topk(self, sess, latest_tokens, enc_top_states, dec_init_states):\n \"\"\"Return the topK results and new decoder states.\"\"\"\n feed = {self._enc_top_states: enc_top_states, self._dec_in_state: np.squeeze(np.array(dec_init_states)), self._abstracts: np.transpose(np.array([latest_tokens])), self._abstract_lens: np.ones([len(dec_init_states)], np.int32)}\n results = sess.run([self._topk_ids, self._topk_log_probs, self._dec_out_state], feed_dict=feed)\n (ids, probs, states) = (results[0], results[1], results[2])\n new_states = [s for s in states]\n return (ids, probs, new_states)","code_tokens":"","url":753959} +{"project_name":"vt257\/allnews-am","file_name":"WikiExtractor.py","full_name":"Extractor.clean","func_name":"clean","docstring":"Removes irrelevant parts from :param: text.","docstring_tokens":"","code":"def clean(self, text):\n \"\"\"\n Removes irrelevant parts from :param: text.\n \"\"\"\n spans = []\n for m in comment.finditer(text):\n spans.append((m.start(), m.end()))\n for pattern in selfClosing_tag_patterns:\n for m in pattern.finditer(text):\n spans.append((m.start(), m.end()))\n for (left, right) in options.ignored_tag_patterns:\n for m in left.finditer(text):\n spans.append((m.start(), m.end()))\n for m in right.finditer(text):\n spans.append((m.start(), m.end()))\n text = dropSpans(spans, text)\n for tag in options.discardElements:\n text = dropNested(text, '<\\\\s*%s\\\\b[^>\/]*>' % tag, '<\\\\s*\/\\\\s*%s>' % tag)\n if not options.toHTML:\n text = unescape(text)\n for (pattern, placeholder) in placeholder_tag_patterns:\n index = 1\n for match in pattern.finditer(text):\n text = text.replace(match.group(), '%s_%d' % (placeholder, index))\n index += 1\n text = text.replace('<<', '\u00c3\\x82\u00c2\u00ab').replace('>>', '\u00c3\\x82\u00c2\u00bb')\n text = text.replace('\\t', ' ')\n text = spaces.sub(' ', text)\n text = dots.sub('...', text)\n text = re.sub(' (,:\\\\.\\\\)\\\\]\u00c3\\x82\u00c2\u00bb)', '\\\\1', text)\n text = re.sub('(\\\\[\\\\(\u00c3\\x82\u00c2\u00ab) ', '\\\\1', text)\n text = re.sub('\\\\n\\\\W+?\\\\n', '\\n', text, flags=re.U)\n text = text.replace(',,', ',').replace(',.', '.')\n if options.keep_tables:\n text = re.sub('!(?:\\\\s)?style=\\\\\"[a-z]+:(?:\\\\d+)%;\\\\\"', '', text)\n text = re.sub('!(?:\\\\s)?style=\"[a-z]+:(?:\\\\d+)%;[a-z]+:(?:#)?(?:[0-9a-z]+)?\"', '', text)\n text = text.replace('|-', '')\n text = text.replace('|', '')\n if options.toHTML:\n text = cgi.escape(text)\n return text","code_tokens":"","url":414708} +{"project_name":"dlshriver\/dnnv","file_name":"piecewise_linear.py","full_name":"Relu.linear_relaxation","func_name":"linear_relaxation","docstring":"Calculates the linear relaxation The linear relaxation is a Nx2 array, where each row represents a and b of the linear equation: l(x) = ax + b The relaxations are described in detail in the paper.","docstring_tokens":"","code":"def linear_relaxation(self, lower_bounds_concrete_in: np.array, upper_bounds_concrete_in: np.array, upper: bool) -> np.array:\n \"\"\"\n Calculates the linear relaxation\n\n The linear relaxation is a Nx2 array, where each row represents a and b of the linear equation:\n l(x) = ax + b\n\n The relaxations are described in detail in the paper.\n\n Args:\n lower_bounds_concrete_in : The concrete lower bounds of the input to the nodes\n upper_bounds_concrete_in : The concrete upper bounds of the input to the nodes\n upper : If true, the upper relaxation is calculated, else the lower\n Returns:\n The relaxations as a Nx2 array\n \"\"\"\n layer_size = lower_bounds_concrete_in.shape[0]\n relaxations = np.zeros((layer_size, 2))\n fixed_upper_idx = np.argwhere(lower_bounds_concrete_in >= 0)\n relaxations[fixed_upper_idx, 0] = 1\n relaxations[fixed_upper_idx, 1] = 0\n fixed_lower_idx = np.argwhere(upper_bounds_concrete_in <= 0)\n relaxations[fixed_lower_idx, :] = 0\n mixed_idx = np.argwhere((upper_bounds_concrete_in > 0) * (lower_bounds_concrete_in < 0))\n if len(mixed_idx) == 0:\n return relaxations\n xl = lower_bounds_concrete_in[mixed_idx]\n xu = upper_bounds_concrete_in[mixed_idx]\n if upper:\n a = xu \/ (xu - xl)\n b = -a * xl\n relaxations[:, 0][mixed_idx] = a\n relaxations[:, 1][mixed_idx] = b\n else:\n relaxations[:, 0][mixed_idx] = xu \/ (xu - xl)\n relaxations[:, 1][mixed_idx] = 0\n num_ops = 2\n max_edge_dist = np.hstack((np.abs(xl), np.abs(xu))).max(axis=1)[:, np.newaxis]\n max_err = np.spacing(np.abs(relaxations[:, 0][mixed_idx])) * max_edge_dist + np.spacing(np.abs(relaxations[:, 1][mixed_idx]))\n outward_round = max_err * num_ops if upper else -max_err * num_ops\n relaxations[:, 1][mixed_idx] += outward_round\n return relaxations","code_tokens":"","url":522614} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"base.py","full_name":"Output.enable_autowrap","func_name":"enable_autowrap","docstring":"Enable auto line wrapping.","docstring_tokens":"","code":"@abstractmethod\ndef enable_autowrap(self):\n \"\"\" Enable auto line wrapping. \"\"\"","code_tokens":"","url":45433} +{"project_name":"uber\/causalml","file_name":"regression.py","full_name":"regression_metrics","func_name":"regression_metrics","docstring":"Log metrics for regressors.","docstring_tokens":"","code":"def regression_metrics(y, p, w=None, metrics={'RMSE': rmse, 'sMAPE': smape, 'Gini': gini}):\n \"\"\"Log metrics for regressors.\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n w (numpy.array, optional): a treatment vector (1 or True: treatment, 0 or False: control). If given, log\n metrics for the treatment and control group separately\n metrics (dict, optional): a dictionary of the metric names and functions\n \"\"\"\n assert metrics\n assert y.shape[0] == p.shape[0]\n for (name, func) in metrics.items():\n if w is not None:\n assert y.shape[0] == w.shape[0]\n if w.dtype != bool:\n w = w == 1\n logger.info('{:>8s} (Control): {:10.4f}'.format(name, func(y[~w], p[~w])))\n logger.info('{:>8s} (Treatment): {:10.4f}'.format(name, func(y[w], p[w])))\n else:\n logger.info('{:>8s}: {:10.4f}'.format(name, func(y, p)))","code_tokens":"","url":456496} +{"project_name":"shenyunhang\/PDSL","file_name":"config.py","full_name":"add_hrnet_config","func_name":"add_hrnet_config","docstring":"Add config for HRNet backbone.","docstring_tokens":"","code":"def add_hrnet_config(cfg: CN):\n \"\"\"\n Add config for HRNet backbone.\n \"\"\"\n _C = cfg\n _C.MODEL.HRNET = CN()\n _C.MODEL.HRNET.STEM_INPLANES = 64\n _C.MODEL.HRNET.STAGE2 = CN()\n _C.MODEL.HRNET.STAGE2.NUM_MODULES = 1\n _C.MODEL.HRNET.STAGE2.NUM_BRANCHES = 2\n _C.MODEL.HRNET.STAGE2.BLOCK = 'BASIC'\n _C.MODEL.HRNET.STAGE2.NUM_BLOCKS = [4, 4]\n _C.MODEL.HRNET.STAGE2.NUM_CHANNELS = [32, 64]\n _C.MODEL.HRNET.STAGE2.FUSE_METHOD = 'SUM'\n _C.MODEL.HRNET.STAGE3 = CN()\n _C.MODEL.HRNET.STAGE3.NUM_MODULES = 4\n _C.MODEL.HRNET.STAGE3.NUM_BRANCHES = 3\n _C.MODEL.HRNET.STAGE3.BLOCK = 'BASIC'\n _C.MODEL.HRNET.STAGE3.NUM_BLOCKS = [4, 4, 4]\n _C.MODEL.HRNET.STAGE3.NUM_CHANNELS = [32, 64, 128]\n _C.MODEL.HRNET.STAGE3.FUSE_METHOD = 'SUM'\n _C.MODEL.HRNET.STAGE4 = CN()\n _C.MODEL.HRNET.STAGE4.NUM_MODULES = 3\n _C.MODEL.HRNET.STAGE4.NUM_BRANCHES = 4\n _C.MODEL.HRNET.STAGE4.BLOCK = 'BASIC'\n _C.MODEL.HRNET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4]\n _C.MODEL.HRNET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256]\n _C.MODEL.HRNET.STAGE4.FUSE_METHOD = 'SUM'\n _C.MODEL.HRNET.HRFPN = CN()\n _C.MODEL.HRNET.HRFPN.OUT_CHANNELS = 256","code_tokens":"","url":279280} +{"project_name":"intelligent-environments-lab\/CityLearn","file_name":"building.py","full_name":"Building.energy_simulation","func_name":"energy_simulation","docstring":"Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series.","docstring_tokens":"","code":"@property\ndef energy_simulation(self) -> EnergySimulation:\n \"\"\"Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series.\"\"\"\n return self.__energy_simulation","code_tokens":"","url":105543} +{"project_name":"intel\/neural-compressor","file_name":"utility.py","full_name":"build_local_cluster","func_name":"build_local_cluster","docstring":"Build a local cluster.","docstring_tokens":"","code":"def build_local_cluster(db_path):\n \"\"\"Build a local cluster.\n\n Args:\n db_path (str): database path\n\n Returns:\n (Cluster, int): cluster and num threads per process\n \"\"\"\n from neural_solution.backend.cluster import Cluster, Node\n hostname = 'localhost'\n node1 = Node(name=hostname, num_sockets=2, num_cores_per_socket=5)\n node2 = Node(name=hostname, num_sockets=2, num_cores_per_socket=5)\n node3 = Node(name=hostname, num_sockets=2, num_cores_per_socket=5)\n node_lst = [node1, node2, node3]\n cluster = Cluster(node_lst=node_lst, db_path=db_path)\n return (cluster, 5)","code_tokens":"","url":721810} +{"project_name":"Ashwin-Ravi\/Deep-Learning-A-Z-Udemy","file_name":"minisom.py","full_name":"MiniSom.quantization","func_name":"quantization","docstring":"Assigns a code book (weights vector of the winning neuron) to each sample in data.","docstring_tokens":"","code":"def quantization(self, data):\n \"\"\" Assigns a code book (weights vector of the winning neuron) to each sample in data. \"\"\"\n q = zeros(data.shape)\n for (i, x) in enumerate(data):\n q[i] = self.weights[self.winner(x)]\n return q","code_tokens":"","url":127438} +{"project_name":"KalleHallden\/InstaAutomator","file_name":"wheel.py","full_name":"Wheel.install_as_egg","func_name":"install_as_egg","docstring":"Install wheel as an egg directory.","docstring_tokens":"","code":"def install_as_egg(self, destination_eggdir):\n \"\"\"Install wheel as an egg directory.\"\"\"\n with zipfile.ZipFile(self.filename) as zf:\n dist_basename = '%s-%s' % (self.project_name, self.version)\n dist_info = '%s.dist-info' % dist_basename\n dist_data = '%s.data' % dist_basename\n\n def get_metadata(name):\n with zf.open('%s\/%s' % (dist_info, name)) as fp:\n value = fp.read().decode('utf-8') if PY3 else fp.read()\n return email.parser.Parser().parsestr(value)\n wheel_metadata = get_metadata('WHEEL')\n dist_metadata = get_metadata('METADATA')\n wheel_version = parse_version(wheel_metadata.get('Wheel-Version'))\n if not parse_version('1.0') <= wheel_version < parse_version('2.0dev0'):\n raise ValueError('unsupported wheel format version: %s' % wheel_version)\n os.mkdir(destination_eggdir)\n zf.extractall(destination_eggdir)\n dist_info = os.path.join(destination_eggdir, dist_info)\n dist = Distribution.from_location(destination_eggdir, dist_info, metadata=PathMetadata(destination_eggdir, dist_info))\n\n def raw_req(req):\n req.marker = None\n return str(req)\n install_requires = list(sorted(map(raw_req, dist.requires())))\n extras_require = {extra: list(sorted((req for req in map(raw_req, dist.requires((extra,))) if req not in install_requires))) for extra in dist.extras}\n egg_info = os.path.join(destination_eggdir, 'EGG-INFO')\n os.rename(dist_info, egg_info)\n os.rename(os.path.join(egg_info, 'METADATA'), os.path.join(egg_info, 'PKG-INFO'))\n setup_dist = SetuptoolsDistribution(attrs=dict(install_requires=install_requires, extras_require=extras_require))\n write_requirements(setup_dist.get_command_obj('egg_info'), None, os.path.join(egg_info, 'requires.txt'))\n dist_data = os.path.join(destination_eggdir, dist_data)\n dist_data_scripts = os.path.join(dist_data, 'scripts')\n if os.path.exists(dist_data_scripts):\n egg_info_scripts = os.path.join(destination_eggdir, 'EGG-INFO', 'scripts')\n os.mkdir(egg_info_scripts)\n for entry in os.listdir(dist_data_scripts):\n if entry.endswith('.pyc'):\n os.unlink(os.path.join(dist_data_scripts, entry))\n else:\n os.rename(os.path.join(dist_data_scripts, entry), os.path.join(egg_info_scripts, entry))\n os.rmdir(dist_data_scripts)\n for subdir in filter(os.path.exists, (os.path.join(dist_data, d) for d in ('data', 'headers', 'purelib', 'platlib'))):\n unpack(subdir, destination_eggdir)\n if os.path.exists(dist_data):\n os.rmdir(dist_data)\n namespace_packages = os.path.join(egg_info, 'namespace_packages.txt')\n if os.path.exists(namespace_packages):\n with open(namespace_packages) as fp:\n namespace_packages = fp.read().split()\n for mod in namespace_packages:\n mod_dir = os.path.join(destination_eggdir, *mod.split('.'))\n mod_init = os.path.join(mod_dir, '__init__.py')\n if os.path.exists(mod_dir) and (not os.path.exists(mod_init)):\n with open(mod_init, 'w') as fp:\n fp.write(NAMESPACE_PACKAGE_INIT)","code_tokens":"","url":233698} +{"project_name":"fengju514\/Face-Pose-Net","file_name":"transformers.py","full_name":"SubNodeFuser.is_eligible_pair","func_name":"is_eligible_pair","docstring":"Returns true if this parent\/child pair is eligible for fusion.","docstring_tokens":"","code":"def is_eligible_pair(self, parent, child):\n \"\"\"Returns true if this parent\/child pair is eligible for fusion.\"\"\"\n raise NotImplementedError('Must be implemented by subclass.')","code_tokens":"","url":178867} +{"project_name":"ArdaGunay99\/Key_Detection_Unsupervised_Learning","file_name":"test_memory.py","full_name":"test_memory_integration","func_name":"test_memory_integration","docstring":"Simple test of memory lazy evaluation.","docstring_tokens":"","code":"def test_memory_integration(tmpdir):\n \"\"\" Simple test of memory lazy evaluation.\n \"\"\"\n accumulator = list()\n\n def f(l):\n accumulator.append(1)\n return l\n check_identity_lazy(f, accumulator, tmpdir.strpath)\n for compress in (False, True):\n for mmap_mode in ('r', None):\n memory = Memory(location=tmpdir.strpath, verbose=10, mmap_mode=mmap_mode, compress=compress)\n shutil.rmtree(tmpdir.strpath, ignore_errors=True)\n g = memory.cache(f)\n g(1)\n g.clear(warn=False)\n current_accumulator = len(accumulator)\n out = g(1)\n assert len(accumulator) == current_accumulator + 1\n assert memory.eval(f, 1) == out\n assert len(accumulator) == current_accumulator + 1\n f.__module__ = '__main__'\n memory = Memory(location=tmpdir.strpath, verbose=0)\n memory.cache(f)(1)","code_tokens":"","url":256481} +{"project_name":"AlperHuseyn\/artificial-intelligence-and-machine-learning-with-python","file_name":"gallonomics.py","full_name":"train_evaluate_save_model","func_name":"train_evaluate_save_model","docstring":"Train, evaluate, and save the auto-mpg prediction model.","docstring_tokens":"","code":"def train_evaluate_save_model(X_train, y_train, X_test, y_test, X_to_predict, name='model', epochs=100):\n \"\"\"\nTrain, evaluate, and save the auto-mpg prediction model.\n\nArgs:\n X_train (pandas.DataFrame): Input features for training.\n y_train (pandas.Series): Output values for training.\n X_test (pandas.DataFrame): Input features for testing.\n y_test (pandas.Series): Output values for testing.\n X_to_predict (numpy.ndarray): Input features for predictions.\n name (str): Name for saving the model.\n epochs (int): Number of training epochs.\n\nReturns:\n float: Mean Absolute Error (MAE) of the model on the test dataset.\n numpy.ndarray: Predicted auto-mpg.\n\"\"\"\n model = create_auto_mpg_model(input_dim=X_train.shape[1], name='auto-mpg')\n hist = model.fit(X_train, y_train, epochs=epochs, validation_split=0.1)\n (loss, mae) = model.evaluate(X_test, y_test, verbose=0)\n predictions = model.predict(X_to_predict)\n model.save(f'{name}.h5')\n return (hist, loss, mae, predictions)","code_tokens":"","url":36122} +{"project_name":"eth-ait\/motion-infilling","file_name":"data_loader.py","full_name":"Databases.from_str","func_name":"from_str","docstring":"Retrieves the name of the DB file for a given string.","docstring_tokens":"","code":"@classmethod\ndef from_str(cls, name):\n \"\"\"Retrieves the name of the DB file for a given string.\"\"\"\n n = name.lower()\n return cls.MAPPING[n]","code_tokens":"","url":656152} +{"project_name":"DYCI2\/Dicy2-python","file_name":"factor_oracle_navigator.py","full_name":"FactorOracleNavigator.feedback","func_name":"feedback","docstring":"Updates the current temporal position (it's execution trace) of the FactorOracleNavigator based on the last generated event.","docstring_tokens":"","code":"def feedback(self, output_event: Optional[Candidate]) -> None:\n \"\"\" Updates the current temporal position (it's execution trace) of the FactorOracleNavigator\n based on the last generated event.\n \"\"\"\n self.increment_generation_index()\n if output_event is not None:\n self.set_position_in_sequence(output_event.event.index + 1)\n else:\n self.set_position_in_sequence(0)","code_tokens":"","url":550346} +{"project_name":"lixingjian\/DELTA","file_name":"model.py","full_name":"print_ops","func_name":"print_ops","docstring":"Print tensorflow operations in a graph.","docstring_tokens":"","code":"def print_ops(graph, prefix=''):\n \"\"\"Print tensorflow operations in a graph.\"\"\"\n for operator in graph.get_operations():\n logging.info('{} : op name: {}'.format(prefix, operator.name))","code_tokens":"","url":537586} +{"project_name":"tonybeltramelli\/Graphics-And-Vision","file_name":"CamerasParameters.py","full_name":"CamerasParameters.F","func_name":"F","docstring":"Get the fundamental matrix.","docstring_tokens":"","code":"@F.setter\ndef F(self, value):\n \"\"\"Get the fundamental matrix.\"\"\"\n self.__f = value","code_tokens":"","url":580607} +{"project_name":"openvinotoolkit\/training_extensions","file_name":"custom_image_classifier.py","full_name":"CustomImageClassifier.load_state_dict_pre_hook","func_name":"load_state_dict_pre_hook","docstring":"Redirect input state_dict to model for OTX model compatibility.","docstring_tokens":"","code":"@staticmethod\ndef load_state_dict_pre_hook(module, state_dict, prefix, *args, **kwargs):\n \"\"\"Redirect input state_dict to model for OTX model compatibility.\"\"\"\n backbone_type = type(module.backbone).__name__\n if backbone_type not in ['OTXMobileNetV3', 'OTXEfficientNet', 'OTXEfficientNetV2']:\n return\n if backbone_type == 'OTXMobileNetV3':\n for key in list(state_dict.keys()):\n val = state_dict.pop(key)\n if not prefix or key.startswith(prefix):\n key = key.replace(prefix, '', 1)\n if key.startswith('classifier.'):\n if '4' in key:\n key = 'head.' + key.replace('4', '3')\n if module.multilabel:\n val = val.t()\n else:\n key = 'head.' + key\n elif key.startswith('act'):\n key = 'head.' + key\n elif not key.startswith('backbone.'):\n key = 'backbone.' + key\n key = prefix + key\n state_dict[key] = val\n elif backbone_type == 'OTXEfficientNet':\n for key in list(state_dict.keys()):\n val = state_dict.pop(key)\n if not prefix or key.startswith(prefix):\n key = key.replace(prefix, '', 1)\n if key.startswith('features.') and 'activ' not in key:\n key = 'backbone.' + key\n elif key.startswith('output.'):\n key = key.replace('output', 'head')\n if not module.hierarchical:\n key = key.replace('asl', 'fc')\n val = val.t()\n key = prefix + key\n state_dict[key] = val\n elif backbone_type == 'OTXEfficientNetV2':\n for key in list(state_dict.keys()):\n val = state_dict.pop(key)\n if not prefix or key.startswith(prefix):\n key = key.replace(prefix, '', 1)\n if key.startswith('model.classifier'):\n key = key.replace('model.classifier', 'head.fc')\n if not module.hierarchical:\n val = val.t()\n elif key.startswith('model'):\n key = 'backbone.' + key\n key = prefix + key\n state_dict[key] = val\n else:\n logger.info('conversion is not required.')","code_tokens":"","url":904015} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"pydoc.py","full_name":"HTMLDoc.docother","func_name":"docother","docstring":"Produce HTML documentation for a data object.","docstring_tokens":"","code":"def docother(self, object, name=None, mod=None, *ignored):\n \"\"\"Produce HTML documentation for a data object.\"\"\"\n lhs = name and '%s<\/strong> = ' % name or ''\n return lhs + self.repr(object)","code_tokens":"","url":281231} +{"project_name":"ZumoLabs\/zpy","file_name":"files.py","full_name":"filecopy","func_name":"filecopy","docstring":"Copy file from source (src) to destination (dst).","docstring_tokens":"","code":"def filecopy(src_path: Union[Path, str], dst_path: Union[Path, str]) -> None:\n \"\"\"Copy file from source (src) to destination (dst).\n\n Args:\n src_path (Union[Path, str]): Source filesystem path.\n dst_path (Union[Path, str]): Destination filesystem path.\n \"\"\"\n src_path = verify_path(src_path)\n dst_path = verify_path(dst_path)\n log.debug(f'Copying over file from {src_path} to {dst_path}')\n shutil.copy(src_path, dst_path)","code_tokens":"","url":972027} +{"project_name":"AirbusCyber\/grap","file_name":"grap-match.py","full_name":"parse_arguments","func_name":"parse_arguments","docstring":"Parse the arguments of the program.","docstring_tokens":"","code":"def parse_arguments():\n \"\"\"\n Parse the arguments of the program.\n \"\"\"\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group()\n group.add_argument('-v', '--verbosity', action='count', default=0, help='increase output verbosity')\n group.add_argument('-q', '--quiet', action='store_true', default=False)\n parser.add_argument('-ncl', '--no-check-labels', dest='checklabels', action='store_false', default=True, help='do not check the labels of sites')\n parser.add_argument('-st', '--single-traversal', dest='singletraversal', action='store_true', default=False, help='use the single traversal algorithm (default: tree)')\n parser.add_argument('-m', '--print-all-matches', dest='allmatches', action='store_true', default=False, help='always print matched nodes (overrides getid fields)')\n parser.add_argument('-nm', '--print-no-matches', dest='nomatches', action='store_true', default=False, help='never print matched nodes (overrides getid fields)')\n parser.add_argument('patternFile', help='The pattern to search')\n parser.add_argument('testFile', nargs='+', help='The file in which we will lookfor the pattern')\n return parser.parse_args()","code_tokens":"","url":202778} +{"project_name":"bnpy\/bnpy","file_name":"HDPTopicUtil.py","full_name":"calcELBO_NonlinearTerms","func_name":"calcELBO_NonlinearTerms","docstring":"Calculate ELBO objective terms non-linear in suff stats.","docstring_tokens":"","code":"def calcELBO_NonlinearTerms(Data=None, SS=None, LP=None, todict=0, rho=None, Ebeta=None, alpha=None, resp=None, nDoc=None, DocTopicCount=None, theta=None, thetaRem=None, ElogPi=None, ElogPiRem=None, sumLogPi=None, sumLogPiRem=None, sumLogPiRemVec=None, Hresp=None, slackTheta=None, slackThetaRem=None, gammalnTheta=None, gammalnSumTheta=None, gammalnThetaRem=None, thetaEmptyComp=None, ElogPiEmptyComp=None, ElogPiOrigComp=None, gammalnThetaOrigComp=None, slackThetaOrigComp=None, returnMemoizedDict=0, **kwargs):\n \"\"\" Calculate ELBO objective terms non-linear in suff stats.\n \"\"\"\n if resp is not None:\n (N, K) = resp.shape\n elif LP is not None:\n if 'resp' in LP:\n (N, K) = LP['resp'].shape\n else:\n (N, K) = LP['spR'].shape\n if Ebeta is None:\n Ebeta = rho2beta(rho, returnSize='K+1')\n if LP is not None:\n DocTopicCount = LP['DocTopicCount']\n nDoc = DocTopicCount.shape[0]\n theta = LP['theta']\n thetaRem = LP['thetaRem']\n ElogPi = LP['ElogPi']\n ElogPiRem = LP['ElogPiRem']\n sumLogPi = np.sum(ElogPi, axis=0)\n sumLogPiRem = np.sum(ElogPiRem)\n if 'thetaEmptyComp' in LP:\n thetaEmptyComp = LP['thetaEmptyComp']\n ElogPiEmptyComp = LP['ElogPiEmptyComp']\n ElogPiOrigComp = LP['ElogPiOrigComp']\n gammalnThetaOrigComp = LP['gammalnThetaOrigComp']\n slackThetaOrigComp = LP['slackThetaOrigComp']\n HrespOrigComp = LP['HrespOrigComp']\n elif SS is not None:\n sumLogPi = SS.sumLogPi\n nDoc = SS.nDoc\n if hasattr(SS, 'sumLogPiRemVec'):\n sumLogPiRemVec = SS.sumLogPiRemVec\n else:\n sumLogPiRem = SS.sumLogPiRem\n if DocTopicCount is not None and theta is None:\n theta = DocTopicCount + alpha * Ebeta[:-1]\n thetaRem = alpha * Ebeta[-1]\n if theta is not None and ElogPi is None:\n digammasumtheta = digamma(theta.sum(axis=1) + thetaRem)\n ElogPi = digamma(theta) - digammasumtheta[:, np.newaxis]\n ElogPiRem = digamma(thetaRem) - digammasumtheta[:, np.newaxis]\n if sumLogPi is None and ElogPi is not None:\n sumLogPi = np.sum(ElogPi, axis=0)\n sumLogPiRem = np.sum(ElogPiRem)\n if Hresp is None:\n if SS is not None and SS.hasELBOTerm('Hresp'):\n Hresp = SS.getELBOTerm('Hresp')\n elif hasattr(Data, 'word_count') and N == Data.word_count.size:\n if resp is not None:\n Hresp = -1 * NumericUtil.calcRlogRdotv(resp, Data.word_count)\n elif 'resp' in LP:\n Hresp = -1 * NumericUtil.calcRlogRdotv(LP['resp'], Data.word_count)\n elif 'spR' in LP:\n Hresp = calcSparseRlogRdotv(v=Data.word_count, **LP)\n else:\n raise ValueError('Missing resp assignments!')\n elif resp is not None:\n Hresp = -1 * NumericUtil.calcRlogR(resp)\n elif 'resp' in LP:\n Hresp = -1 * NumericUtil.calcRlogR(LP['resp'])\n elif 'spR' in LP:\n assert 'nnzPerRow' in LP\n Hresp = calcSparseRlogR(**LP)\n else:\n raise ValueError('Missing resp assignments!')\n if slackTheta is None:\n if SS is not None and SS.hasELBOTerm('slackTheta'):\n slackTheta = SS.getELBOTerm('slackTheta')\n slackThetaRem = SS.getELBOTerm('slackThetaRem')\n else:\n slackTheta = DocTopicCount - theta\n slackTheta *= ElogPi\n slackTheta = np.sum(slackTheta, axis=0)\n slackThetaRem = -1 * np.sum(thetaRem * ElogPiRem)\n if gammalnTheta is None:\n if SS is not None and SS.hasELBOTerm('gammalnTheta'):\n gammalnSumTheta = SS.getELBOTerm('gammalnSumTheta')\n gammalnTheta = SS.getELBOTerm('gammalnTheta')\n gammalnThetaRem = SS.getELBOTerm('gammalnThetaRem')\n else:\n sumTheta = np.sum(theta, axis=1) + thetaRem\n gammalnSumTheta = np.sum(gammaln(sumTheta))\n gammalnTheta = np.sum(gammaln(theta), axis=0)\n gammalnThetaRem = theta.shape[0] * gammaln(thetaRem)\n if thetaEmptyComp is not None:\n gammalnThetaEmptyComp = nDoc * gammaln(thetaEmptyComp) - gammalnThetaOrigComp\n slackThetaEmptyComp = -np.sum(thetaEmptyComp * ElogPiEmptyComp) - slackThetaOrigComp\n if returnMemoizedDict:\n Mdict = dict(Hresp=Hresp, slackTheta=slackTheta, slackThetaRem=slackThetaRem, gammalnTheta=gammalnTheta, gammalnThetaRem=gammalnThetaRem, gammalnSumTheta=gammalnSumTheta)\n if thetaEmptyComp is not None:\n Mdict['HrespEmptyComp'] = -1 * HrespOrigComp\n Mdict['gammalnThetaEmptyComp'] = gammalnThetaEmptyComp\n Mdict['slackThetaEmptyComp'] = slackThetaEmptyComp\n return Mdict\n Lentropy = np.sum(Hresp)\n Lslack = slackTheta.sum() + slackThetaRem\n LcDtheta = -1 * (gammalnSumTheta - gammalnTheta.sum() - gammalnThetaRem)\n if SS is not None and SS.hasAmpFactor():\n Lentropy *= SS.ampF\n Lslack *= SS.ampF\n LcDtheta *= SS.ampF\n alphaEbeta = alpha * Ebeta\n Lslack_alphaEbeta = np.sum(alphaEbeta[:-1] * sumLogPi)\n if sumLogPiRemVec is not None:\n Ebeta_gt = 1 - np.cumsum(Ebeta[:-1])\n Lslack_alphaEbeta += alpha * np.inner(Ebeta_gt, sumLogPiRemVec)\n else:\n Lslack_alphaEbeta += alphaEbeta[-1] * sumLogPiRem\n Lslack += Lslack_alphaEbeta\n if todict:\n return dict(Lslack=Lslack, Lentropy=Lentropy, LcDtheta=LcDtheta, Lslack_alphaEbeta=Lslack_alphaEbeta)\n return LcDtheta + Lslack + Lentropy","code_tokens":"","url":464347} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"vanilla_gan.py","full_name":"SlicedGan.losses","func_name":"losses","docstring":"Losses in the sliced case.","docstring_tokens":"","code":"def losses(self, inputs, generated):\n \"\"\"Losses in the sliced case.\"\"\"\n is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n\n def discriminate(x):\n return self.discriminator(x, is_training=is_training, reuse=False)\n generator_loss = common_layers.sliced_gan_loss(inputs, reverse_gradient(generated), discriminate, self.hparams.num_sliced_vecs)\n return {'training': -generator_loss}","code_tokens":"","url":965735} +{"project_name":"rmkemker\/EarthMapper","file_name":"mlp.py","full_name":"MLP.act","func_name":"act","docstring":"Applies PELU activation function.","docstring_tokens":"","code":"def act(self, z, a, b):\n \"\"\"Applies PELU activation function.\n\n Args:\n z (tensor): data to apply activation function on.\n a (float): `a` parameter.\n b (float): `b` parameter.\n \"\"\"\n if self.activation == 'relu':\n return tf.nn.relu(z)\n elif self.activation == 'tanh':\n return tf.nn.tanh(z)\n elif self.activation == 'leakyrelu':\n return tf.nn.relu(z) - 0.1 * tf.nn.relu(-z)\n elif self.activation == 'pelu':\n positive = tf.nn.relu(z) * a \/ (b + 1e-09)\n negative = a * (tf.exp(-tf.nn.relu(-z) \/ (b + 1e-09)) - 1)\n return negative + positive\n elif self.activation == 'elu':\n return tf.nn.elu(z)\n else:\n raise NotImplementedError('Only RELU, ELU, TANH, and PELU activations are supported')","code_tokens":"","url":556282} +{"project_name":"ming71\/Rotated-RetinaNet","file_name":"rrc_evaluation_funcs_1_1.py","full_name":"validate_clockwise_points","func_name":"validate_clockwise_points","docstring":"Validates that the points are in clockwise order.","docstring_tokens":"","code":"def validate_clockwise_points(points):\n \"\"\"\n Validates that the points are in clockwise order.\n \"\"\"\n edge = []\n for i in range(len(points) \/\/ 2):\n edge.append((int(points[(i + 1) * 2 % len(points)]) - int(points[i * 2])) * (int(points[((i + 1) * 2 + 1) % len(points)]) + int(points[i * 2 + 1])))\n if sum(edge) > 0:\n raise Exception(\"Points are not clockwise. The coordinates of bounding points have to be given in clockwise order. Regarding the correct interpretation of 'clockwise' remember that the image coordinate system used is the standard one, with the image origin at the upper left, the X axis extending to the right and Y axis extending downwards.\")","code_tokens":"","url":827840} +{"project_name":"yinyunie\/ScenePriors","file_name":"stats.py","full_name":"Stats.print","func_name":"print","docstring":"Print the current values of all stored stats.","docstring_tokens":"","code":"def print(self, max_it: Optional[int]=None, stat_set: str='train') -> None:\n \"\"\"\n Print the current values of all stored stats.\n\n Args:\n max_it: Maximum iteration number to be displayed.\n If None, the maximum iteration number is not displayed.\n stat_set: The set of statistics to be printed.\n \"\"\"\n epoch = self.epoch\n stats = self.stats\n str_out = ''\n it = self.it[stat_set]\n stat_str = ''\n stats_print = sorted(stats[stat_set].keys())\n for stat in stats_print:\n if stats[stat_set][stat].count == 0:\n continue\n stat_str += ' {0:.12}: {1:1.3f} |'.format(stat, stats[stat_set][stat].avg)\n head_str = f'[{stat_set}] | epoch {epoch} | it {it}'\n if max_it:\n head_str += f'\/ {max_it}'\n str_out = f'{head_str} | {stat_str}'\n print(str_out)","code_tokens":"","url":329601} +{"project_name":"heynemann\/pyvows","file_name":"common.py","full_name":"VowsReporter.humanized_print","func_name":"humanized_print","docstring":"Passes `msg` through multiple text filters to make the output appear more like normal text, then prints it (indented by `indentation`).","docstring_tokens":"","code":"def humanized_print(self, msg, indentation=None, file=sys.stdout):\n \"\"\"Passes `msg` through multiple text filters to make the output\n appear more like normal text, then prints it (indented by\n `indentation`).\n\n \"\"\"\n msg = self.under_split(msg)\n msg = self.camel_split(msg)\n msg = msg.replace(' ', ' ')\n msg = msg.capitalize()\n msg = self.format_python_constants(msg)\n print(self.indent_msg(msg, indentation), file=file)","code_tokens":"","url":302622} +{"project_name":"rudranil723\/mini-main","file_name":"ccompiler_opt.py","full_name":"_Config.conf_features_partial","func_name":"conf_features_partial","docstring":"Return a dictionary of supported CPU features by the platform, and accumulate the rest of undefined options in `conf_features`, the returned dict has same rules and notes in class attribute `conf_features`, also its override any options that been set in 'conf_features'.","docstring_tokens":"","code":"def conf_features_partial(self):\n \"\"\"Return a dictionary of supported CPU features by the platform,\n and accumulate the rest of undefined options in `conf_features`,\n the returned dict has same rules and notes in\n class attribute `conf_features`, also its override\n any options that been set in 'conf_features'.\n \"\"\"\n if self.cc_noopt:\n return {}\n on_x86 = self.cc_on_x86 or self.cc_on_x64\n is_unix = self.cc_is_gcc or self.cc_is_clang\n if on_x86 and is_unix:\n return dict(SSE=dict(flags='-msse'), SSE2=dict(flags='-msse2'), SSE3=dict(flags='-msse3'), SSSE3=dict(flags='-mssse3'), SSE41=dict(flags='-msse4.1'), POPCNT=dict(flags='-mpopcnt'), SSE42=dict(flags='-msse4.2'), AVX=dict(flags='-mavx'), F16C=dict(flags='-mf16c'), XOP=dict(flags='-mxop'), FMA4=dict(flags='-mfma4'), FMA3=dict(flags='-mfma'), AVX2=dict(flags='-mavx2'), AVX512F=dict(flags='-mavx512f -mno-mmx'), AVX512CD=dict(flags='-mavx512cd'), AVX512_KNL=dict(flags='-mavx512er -mavx512pf'), AVX512_KNM=dict(flags='-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq'), AVX512_SKX=dict(flags='-mavx512vl -mavx512bw -mavx512dq'), AVX512_CLX=dict(flags='-mavx512vnni'), AVX512_CNL=dict(flags='-mavx512ifma -mavx512vbmi'), AVX512_ICL=dict(flags='-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq'))\n if on_x86 and self.cc_is_icc:\n return dict(SSE=dict(flags='-msse'), SSE2=dict(flags='-msse2'), SSE3=dict(flags='-msse3'), SSSE3=dict(flags='-mssse3'), SSE41=dict(flags='-msse4.1'), POPCNT={}, SSE42=dict(flags='-msse4.2'), AVX=dict(flags='-mavx'), F16C={}, XOP=dict(disable=\"Intel Compiler doesn't support it\"), FMA4=dict(disable=\"Intel Compiler doesn't support it\"), FMA3=dict(implies='F16C AVX2', flags='-march=core-avx2'), AVX2=dict(implies='FMA3', flags='-march=core-avx2'), AVX512F=dict(implies='AVX2 AVX512CD', flags='-march=common-avx512'), AVX512CD=dict(implies='AVX2 AVX512F', flags='-march=common-avx512'), AVX512_KNL=dict(flags='-xKNL'), AVX512_KNM=dict(flags='-xKNM'), AVX512_SKX=dict(flags='-xSKYLAKE-AVX512'), AVX512_CLX=dict(flags='-xCASCADELAKE'), AVX512_CNL=dict(flags='-xCANNONLAKE'), AVX512_ICL=dict(flags='-xICELAKE-CLIENT'))\n if on_x86 and self.cc_is_iccw:\n return dict(SSE=dict(flags='\/arch:SSE'), SSE2=dict(flags='\/arch:SSE2'), SSE3=dict(flags='\/arch:SSE3'), SSSE3=dict(flags='\/arch:SSSE3'), SSE41=dict(flags='\/arch:SSE4.1'), POPCNT={}, SSE42=dict(flags='\/arch:SSE4.2'), AVX=dict(flags='\/arch:AVX'), F16C={}, XOP=dict(disable=\"Intel Compiler doesn't support it\"), FMA4=dict(disable=\"Intel Compiler doesn't support it\"), FMA3=dict(implies='F16C AVX2', flags='\/arch:CORE-AVX2'), AVX2=dict(implies='FMA3', flags='\/arch:CORE-AVX2'), AVX512F=dict(implies='AVX2 AVX512CD', flags='\/Qx:COMMON-AVX512'), AVX512CD=dict(implies='AVX2 AVX512F', flags='\/Qx:COMMON-AVX512'), AVX512_KNL=dict(flags='\/Qx:KNL'), AVX512_KNM=dict(flags='\/Qx:KNM'), AVX512_SKX=dict(flags='\/Qx:SKYLAKE-AVX512'), AVX512_CLX=dict(flags='\/Qx:CASCADELAKE'), AVX512_CNL=dict(flags='\/Qx:CANNONLAKE'), AVX512_ICL=dict(flags='\/Qx:ICELAKE-CLIENT'))\n if on_x86 and self.cc_is_msvc:\n return dict(SSE=dict(flags='\/arch:SSE') if self.cc_on_x86 else {}, SSE2=dict(flags='\/arch:SSE2') if self.cc_on_x86 else {}, SSE3={}, SSSE3={}, SSE41={}, POPCNT=dict(headers='nmmintrin.h'), SSE42={}, AVX=dict(flags='\/arch:AVX'), F16C={}, XOP=dict(headers='ammintrin.h'), FMA4=dict(headers='ammintrin.h'), FMA3=dict(implies='F16C AVX2', flags='\/arch:AVX2'), AVX2=dict(implies='F16C FMA3', flags='\/arch:AVX2'), AVX512F=dict(implies='AVX2 AVX512CD AVX512_SKX', flags='\/arch:AVX512'), AVX512CD=dict(implies='AVX512F AVX512_SKX', flags='\/arch:AVX512'), AVX512_KNL=dict(disable=\"MSVC compiler doesn't support it\"), AVX512_KNM=dict(disable=\"MSVC compiler doesn't support it\"), AVX512_SKX=dict(flags='\/arch:AVX512'), AVX512_CLX={}, AVX512_CNL={}, AVX512_ICL={})\n on_power = self.cc_on_ppc64le or self.cc_on_ppc64\n if on_power:\n partial = dict(VSX=dict(implies='VSX2' if self.cc_on_ppc64le else '', flags='-mvsx'), VSX2=dict(flags='-mcpu=power8', implies_detect=False), VSX3=dict(flags='-mcpu=power9 -mtune=power9', implies_detect=False), VSX4=dict(flags='-mcpu=power10 -mtune=power10', implies_detect=False))\n if self.cc_is_clang:\n partial['VSX']['flags'] = '-maltivec -mvsx'\n partial['VSX2']['flags'] = '-mpower8-vector'\n partial['VSX3']['flags'] = '-mpower9-vector'\n partial['VSX4']['flags'] = '-mpower10-vector'\n return partial\n on_zarch = self.cc_on_s390x\n if on_zarch:\n partial = dict(VX=dict(flags='-march=arch11 -mzvector'), VXE=dict(flags='-march=arch12', implies_detect=False), VXE2=dict(flags='-march=arch13', implies_detect=False))\n return partial\n if self.cc_on_aarch64 and is_unix:\n return dict(NEON=dict(implies='NEON_FP16 NEON_VFPV4 ASIMD', autovec=True), NEON_FP16=dict(implies='NEON NEON_VFPV4 ASIMD', autovec=True), NEON_VFPV4=dict(implies='NEON NEON_FP16 ASIMD', autovec=True), ASIMD=dict(implies='NEON NEON_FP16 NEON_VFPV4', autovec=True), ASIMDHP=dict(flags='-march=armv8.2-a+fp16'), ASIMDDP=dict(flags='-march=armv8.2-a+dotprod'), ASIMDFHM=dict(flags='-march=armv8.2-a+fp16fml'))\n if self.cc_on_armhf and is_unix:\n return dict(NEON=dict(flags='-mfpu=neon'), NEON_FP16=dict(flags='-mfpu=neon-fp16 -mfp16-format=ieee'), NEON_VFPV4=dict(flags='-mfpu=neon-vfpv4'), ASIMD=dict(flags='-mfpu=neon-fp-armv8 -march=armv8-a+simd'), ASIMDHP=dict(flags='-march=armv8.2-a+fp16'), ASIMDDP=dict(flags='-march=armv8.2-a+dotprod'), ASIMDFHM=dict(flags='-march=armv8.2-a+fp16fml'))\n return {}","code_tokens":"","url":322488} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"humanoid.py","full_name":"Physics.extremities","func_name":"extremities","docstring":"Returns end effector positions in egocentric frame.","docstring_tokens":"","code":"def extremities(self):\n \"\"\"Returns end effector positions in egocentric frame.\"\"\"\n torso_frame = self.named.data.xmat['torso'].reshape(3, 3)\n torso_pos = self.named.data.xpos['torso']\n positions = []\n for side in ('left_', 'right_'):\n for limb in ('hand', 'foot'):\n torso_to_limb = self.named.data.xpos[side + limb] - torso_pos\n positions.append(torso_to_limb.dot(torso_frame))\n return np.hstack(positions)","code_tokens":"","url":440888} +{"project_name":"switchablenorms\/SwitchNorm_Segmentation","file_name":"resnet_v1_sn.py","full_name":"resnetv1sn50","func_name":"resnetv1sn50","docstring":"Constructs a ResNetV1SN-50 model using switchable normalization.","docstring_tokens":"","code":"def resnetv1sn50(pretrained=True, **kwargs):\n \"\"\"Constructs a ResNetV1SN-50 model using switchable normalization.\n \"\"\"\n model = ResNetV1SN(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(load_weight(model_name['resnetv1sn50']), strict=True)\n return model","code_tokens":"","url":905791} +{"project_name":"worldbank\/wb-nlp-tools","file_name":"scripts.py","full_name":"create_dask_cluster","func_name":"create_dask_cluster","docstring":"This function creates a local dask cluster.","docstring_tokens":"","code":"def create_dask_cluster(logger=None, n_workers=None, return_cluster=False):\n \"\"\"\n This function creates a local dask cluster.\n \"\"\"\n if n_workers is not None:\n n_workers = int(n_workers)\n if logger:\n logger.info('Creating dask client...')\n cpu_count = os.cpu_count()\n n_workers = max(1, cpu_count - 4) if n_workers is None else n_workers\n n_workers = max(1, cpu_count - 4) if n_workers > cpu_count else n_workers\n cluster = LocalCluster(n_workers=n_workers, dashboard_address=':8887', threads_per_worker=1, processes=True, memory_limit=0)\n client = Client(cluster)\n if logger:\n logger.info(client)\n logger.info(client.dashboard_link)\n if not return_cluster:\n return client\n else:\n return (cluster, client)","code_tokens":"","url":975972} +{"project_name":"Dsajeet\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"network_units.py","full_name":"NetworkUnitInterface.create","func_name":"create","docstring":"Constructs a feed-forward unit based on the features and context tensors.","docstring_tokens":"","code":"@abc.abstractmethod\ndef create(self, fixed_embeddings, linked_embeddings, context_tensor_arrays, attention_tensor, during_training, stride=None):\n \"\"\"Constructs a feed-forward unit based on the features and context tensors.\n\n Args:\n fixed_embeddings: list of NamedTensor objects\n linked_embeddings: list of NamedTensor objects\n context_tensor_arrays: optional list of TensorArray objects used for\n implicit recurrence.\n attention_tensor: optional Tensor used for attention.\n during_training: whether to create a network for training (vs inference).\n stride: int scalar tensor containing the stride required for\n bulk computation.\n\n Returns:\n A list of tensors corresponding to the list of layers.\n \"\"\"\n pass","code_tokens":"","url":28448} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"webcam.py","full_name":"launch_images_to_videos","func_name":"launch_images_to_videos","docstring":"Launch job in separate process to convert images to videos.","docstring_tokens":"","code":"def launch_images_to_videos(view_dirs, vid_paths, debug_path):\n \"\"\"Launch job in separate process to convert images to videos.\"\"\"\n f = 'learning\/brain\/research\/tcn\/dataset\/images_to_videos.py'\n cmd = ['python %s ' % f]\n cmd += ['--view_dirs %s ' % ','.join((i for i in view_dirs))]\n cmd += ['--vid_paths %s ' % ','.join((i for i in vid_paths))]\n cmd += ['--debug_path %s ' % debug_path]\n cmd += ['--debug_lhs_view %s ' % FLAGS.debug_lhs_view]\n cmd += ['--debug_rhs_view %s ' % FLAGS.debug_rhs_view]\n cmd += [' & ']\n cmd = ''.join((i for i in cmd))\n fnull = open(os.devnull, 'w')\n subprocess.Popen([cmd], stdout=fnull, stderr=subprocess.STDOUT, shell=True)\n for p in vid_paths:\n tf.logging.info('Writing final video to: %s' % p)\n if debug_path:\n tf.logging.info('Writing debug video to: %s' % debug_path)","code_tokens":"","url":29605} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"replicate_model_fn.py","full_name":"TowerOptimizer.apply_gradients","func_name":"apply_gradients","docstring":"Collect gradients updates to apply them with the last tower.","docstring_tokens":"","code":"def apply_gradients(self, grads_and_vars, global_step=None, **kwargs):\n \"\"\"Collect gradients updates to apply them with the last tower.\"\"\"\n if self._graph_state().number_of_towers == 1:\n return self._get_optimizer().apply_gradients(grads_and_vars, global_step, **kwargs)\n self._graph_state().collect_gradients(grads_and_vars)\n if not self._graph_state().is_the_last_tower:\n with ops_lib.control_dependencies(_extract_tensors(grads_and_vars)):\n return self._construct_no_op_train_op()\n else:\n (var_scope, name_scope) = self._graph_state().scopes_of_the_first_tower\n with variable_scope.variable_scope(var_scope):\n with ops_lib.name_scope(name_scope):\n return self._apply_gathered_gradients(global_step, **kwargs)","code_tokens":"","url":313039} +{"project_name":"TrellixVulnTeam\/Unsupervised_Learning_HFI7","file_name":"compressor.py","full_name":"BinaryZlibFile.closed","func_name":"closed","docstring":"True if this file is closed.","docstring_tokens":"","code":"@property\ndef closed(self):\n \"\"\"True if this file is closed.\"\"\"\n return self._mode == _MODE_CLOSED","code_tokens":"","url":449534} +{"project_name":"TarrySingh\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"graph_builder.py","full_name":"MasterBuilder.add_saver","func_name":"add_saver","docstring":"Adds a Saver for all variables in the graph.","docstring_tokens":"","code":"def add_saver(self):\n \"\"\"Adds a Saver for all variables in the graph.\"\"\"\n logging.info('Saving variables:\\n\\t%s', '\\n\\t'.join([x.name for x in tf.global_variables()]))\n self.saver = tf.train.Saver(var_list=[x for x in tf.global_variables()], write_version=saver_pb2.SaverDef.V1)","code_tokens":"","url":28234} +{"project_name":"voxel51\/fiftyone","file_name":"annotations.py","full_name":"draw_labeled_video","func_name":"draw_labeled_video","docstring":"Renders an annotated version of the sample's video with the specified label data overlaid to disk.","docstring_tokens":"","code":"def draw_labeled_video(sample, outpath, support=None, label_fields=None, config=None, **kwargs):\n \"\"\"Renders an annotated version of the sample's video with the specified\n label data overlaid to disk.\n\n Args:\n sample: a :class:`fiftyone.core.sample.Sample`\n outpath: the path to write the annotated image\n support (None): an optional ``[first, last]`` range of frames to\n render\n label_fields (None): a label field or list of label fields to render.\n If omitted, all compatiable fields are rendered\n config (None): an optional :class:`DrawConfig` configuring how to draw\n the labels\n **kwargs: optional keyword arguments specifying parameters of the\n default :class:`DrawConfig` to override\n \"\"\"\n config = _parse_draw_config(config, kwargs)\n video_path = sample.filepath\n video_labels = _to_video_labels(sample, label_fields=label_fields)\n if support is None and isinstance(sample, foc.ClipView):\n support = sample.support\n etaa.annotate_video(video_path, video_labels, outpath, support=support, annotation_config=config)","code_tokens":"","url":583894} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"_shgo.py","full_name":"SHGO.sampling_custom","func_name":"sampling_custom","docstring":"Generates uniform sampling points in a hypercube and scales the points to the bound limits.","docstring_tokens":"","code":"def sampling_custom(self, n, dim):\n \"\"\"\n Generates uniform sampling points in a hypercube and scales the points\n to the bound limits.\n \"\"\"\n if self.n_sampled == 0:\n self.C = self.sampling_function(n, dim)\n else:\n self.C = self.sampling_function(n, dim)\n for i in range(len(self.bounds)):\n self.C[:, i] = self.C[:, i] * (self.bounds[i][1] - self.bounds[i][0]) + self.bounds[i][0]\n return self.C","code_tokens":"","url":445931} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"axis.py","full_name":"Axis.get_tick_space","func_name":"get_tick_space","docstring":"Return the estimated number of ticks that can fit on the axis.","docstring_tokens":"","code":"def get_tick_space(self):\n \"\"\"\n Return the estimated number of ticks that can fit on the axis.\n \"\"\"\n raise NotImplementedError()","code_tokens":"","url":715010} +{"project_name":"tensorflow\/agents","file_name":"train_utils_test.py","full_name":"TrainUtilsTest.test_wait_for_predicate_timeout","func_name":"test_wait_for_predicate_timeout","docstring":"Tests predicate returning True forever and then timing out.","docstring_tokens":"","code":"def test_wait_for_predicate_timeout(self):\n \"\"\"Tests predicate returning True forever and then timing out.\"\"\"\n predicate_mock = mock.MagicMock(side_effect=[True, True, True])\n with self.assertRaises(TimeoutError):\n train_utils.wait_for_predicate(predicate_mock, num_retries=3)","code_tokens":"","url":23748} +{"project_name":"Eric3911\/OpenAGI","file_name":"base_ir_model.py","full_name":"BaseIRModel.calculate_mean_reciprocal_rank","func_name":"calculate_mean_reciprocal_rank","docstring":"Helper function which calculates mean reciprocal rank.","docstring_tokens":"","code":"@staticmethod\ndef calculate_mean_reciprocal_rank(query2passages, query2rel):\n \"\"\"\n Helper function which calculates mean reciprocal rank.\n Args:\n query2passages: dict which contains passage ids and corresponding\n scores for each query\n query2rel: dict which contains ids of relevant passages for each query\n \"\"\"\n reciprocal_ranks = []\n for query in query2passages:\n indices = np.argsort(query2passages[query]['scores'])[::-1]\n sorted_psgs = query2passages[query]['psg_ids'][indices]\n reciprocal_ranks.append(0)\n for (i, psg_id) in enumerate(sorted_psgs):\n if psg_id in query2rel[query]:\n reciprocal_ranks[-1] = 1 \/ (i + 1)\n break\n return np.mean(reciprocal_ranks)","code_tokens":"","url":273515} +{"project_name":"Annusha\/unsup_temp_embed","file_name":"training_embed.py","full_name":"training","func_name":"training","docstring":"Training pipeline for embedding.","docstring_tokens":"","code":"def training(train_loader, epochs, save, **kwargs):\n \"\"\"Training pipeline for embedding.\n\n Args:\n train_loader: iterator within dataset\n epochs: how much training epochs to perform\n n_subact: number of subactions in current complex activity\n mnist: if training with mnist dataset (just to test everything how well\n it works)\n Returns:\n trained pytorch model\n \"\"\"\n logger.debug('create model')\n torch.manual_seed(opt.seed)\n torch.cuda.manual_seed(opt.seed)\n np.random.seed(opt.seed)\n random.seed(opt.seed)\n torch.backends.cudnn.deterministic = True\n model = kwargs['model']\n loss = kwargs['loss']\n optimizer = kwargs['optimizer']\n cudnn.benchmark = True\n batch_time = Averaging()\n data_time = Averaging()\n losses = Averaging()\n adjustable_lr = opt.lr\n logger.debug('epochs: %s', epochs)\n for epoch in range(epochs):\n model.to(opt.device)\n model.train()\n logger.debug('Epoch # %d' % epoch)\n if opt.lr_adj:\n if epoch % 30 == 0 and epoch > 0:\n adjustable_lr = adjust_lr(optimizer, adjustable_lr)\n logger.debug('lr: %f' % adjustable_lr)\n end = time.time()\n for (i, (features, labels)) in enumerate(train_loader):\n data_time.update(time.time() - end)\n features = features.float()\n labels = labels.float().to(opt.device)\n if opt.device == 'cuda':\n features = features.cuda(non_blocking=True)\n output = model(features)\n loss_values = loss(output.squeeze(), labels.squeeze())\n losses.update(loss_values.item(), features.size(0))\n optimizer.zero_grad()\n loss_values.backward()\n optimizer.step()\n batch_time.update(time.time() - end)\n end = time.time()\n if i % 100 == 0 and i:\n logger.debug('Epoch: [{0}][{1}\/{2}]\\tTime {batch_time.val:.3f} ({batch_time.avg:.3f})\\tData {data_time.val:.3f} ({data_time.avg:.3f})\\tLoss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses))\n logger.debug('loss: %f' % losses.avg)\n losses.reset()\n opt.resume_str = join(opt.dataset_root, 'models', '%s.pth.tar' % opt.log_str)\n if save:\n save_dict = {'epoch': epoch, 'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}\n if opt.global_pipe:\n dir_check(join(opt.dataset_root, 'models', 'global'))\n opt.resume_str = join(opt.dataset_root, 'models', 'global', '%s.pth.tar' % opt.log_str)\n else:\n dir_check(join(opt.dataset_root, 'models'))\n torch.save(save_dict, opt.resume_str)\n return model","code_tokens":"","url":438369} +{"project_name":"deepmind\/bsuite","file_name":"analysis.py","full_name":"find_solution","func_name":"find_solution","docstring":"Find first episode that gets below thresh regret by sweep_vars.","docstring_tokens":"","code":"def find_solution(df_in: pd.DataFrame, sweep_vars: Optional[Sequence[str]]=None, merge: bool=True, thresh: float=0.8, num_episodes: int=NUM_EPISODES) -> pd.DataFrame:\n \"\"\"Find first episode that gets below thresh regret by sweep_vars.\"\"\"\n df = df_in.copy()\n _check_data(df)\n df = df[df.episode <= num_episodes]\n if sweep_vars is None:\n sweep_vars = ['size']\n elif 'size' not in sweep_vars:\n sweep_vars = list(sweep_vars) + ['size']\n df['avg_bad_episodes'] = df.total_bad_episodes \/ df.episode\n plt_df = df[df.avg_bad_episodes < thresh].groupby(sweep_vars)['episode']\n plt_df = plt_df.min().reset_index()\n solved = plt_df.set_index(sweep_vars).episode\n unsolved_ids = set(df.set_index(sweep_vars).index) - set(solved.index)\n unsolved = df.groupby(sweep_vars)['episode'].max()[list(unsolved_ids)]\n plt_df = solved.append(unsolved).to_frame()\n plt_df.rename(columns={0: 'episode'}, inplace=True)\n plt_df.loc[solved.index, 'solved'] = True\n plt_df.loc[unsolved.index, 'solved'] = False\n plt_df.rename(columns={0: 'episode'}, inplace=True)\n plt_df.reset_index(inplace=True)\n finish_df = (df.groupby(sweep_vars)['episode'].max() >= num_episodes).reset_index()\n finish_df.rename(columns={'episode': 'finished'}, inplace=True)\n plt_df = plt_df.merge(finish_df, on=sweep_vars)\n plt_df.loc[plt_df.solved, 'finished'] = True\n if merge:\n join_vars = sweep_vars + ['episode']\n plt_df = plt_df.merge(df, on=join_vars)\n return plt_df","code_tokens":"","url":410199} +{"project_name":"clovaai\/assembled-cnn","file_name":"autoaugment.py","full_name":"sharpness","func_name":"sharpness","docstring":"Implements Sharpness function from PIL using TF ops.","docstring_tokens":"","code":"def sharpness(image, factor):\n \"\"\"Implements Sharpness function from PIL using TF ops.\"\"\"\n orig_image = image\n image = tf.cast(image, tf.float32)\n image = tf.expand_dims(image, 0)\n kernel = tf.constant([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32, shape=[3, 3, 1, 1]) \/ 13.0\n kernel = tf.tile(kernel, [1, 1, 3, 1])\n strides = [1, 1, 1, 1]\n degenerate = tf.nn.depthwise_conv2d(image, kernel, strides, padding='VALID', rate=[1, 1])\n degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)\n degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])\n mask = tf.ones_like(degenerate)\n padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])\n padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])\n result = tf.where(tf.equal(padded_mask, 1), padded_degenerate, orig_image)\n return blend(result, orig_image, factor)","code_tokens":"","url":92489} +{"project_name":"RasaHQ\/rasa","file_name":"socketio.py","full_name":"SocketIOInput.blueprint","func_name":"blueprint","docstring":"Defines a Sanic blueprint.","docstring_tokens":"","code":"def blueprint(self, on_new_message: Callable[[UserMessage], Awaitable[Any]]) -> Blueprint:\n \"\"\"Defines a Sanic blueprint.\"\"\"\n sio = AsyncServer(async_mode='sanic', cors_allowed_origins=[])\n socketio_webhook = SocketBlueprint(sio, self.socketio_path, 'socketio_webhook', __name__)\n self.sio = sio\n\n @socketio_webhook.route('\/', methods=['GET'])\n async def health(_: Request) -> HTTPResponse:\n return response.json({'status': 'ok'})\n\n @sio.on('connect', namespace=self.namespace)\n async def connect(sid: Text, environ: Dict, auth: Optional[Dict]) -> bool:\n if self.jwt_key:\n jwt_payload = None\n if auth and auth.get('token'):\n jwt_payload = rasa.core.channels.channel.decode_bearer_token(auth.get('token'), self.jwt_key, self.jwt_algorithm)\n if jwt_payload:\n logger.debug(f'User {sid} connected to socketIO endpoint.')\n return True\n else:\n return False\n else:\n logger.debug(f'User {sid} connected to socketIO endpoint.')\n return True\n\n @sio.on('disconnect', namespace=self.namespace)\n async def disconnect(sid: Text) -> None:\n logger.debug(f'User {sid} disconnected from socketIO endpoint.')\n\n @sio.on('session_request', namespace=self.namespace)\n async def session_request(sid: Text, data: Optional[Dict]) -> None:\n if data is None:\n data = {}\n if 'session_id' not in data or data['session_id'] is None:\n data['session_id'] = uuid.uuid4().hex\n if self.session_persistence:\n sio.enter_room(sid, data['session_id'])\n await sio.emit('session_confirm', data['session_id'], room=sid)\n logger.debug(f'User {sid} connected to socketIO endpoint.')\n\n @sio.on(self.user_message_evt, namespace=self.namespace)\n async def handle_message(sid: Text, data: Dict) -> None:\n output_channel = SocketIOOutput(sio, self.bot_message_evt)\n if self.session_persistence:\n if not data.get('session_id'):\n rasa.shared.utils.io.raise_warning('A message without a valid session_id was received. This message will be ignored. Make sure to set a proper session id using the `session_request` socketIO event.')\n return\n sender_id = data['session_id']\n else:\n sender_id = sid\n metadata = data.get(self.metadata_key, {})\n if isinstance(metadata, Text):\n metadata = json.loads(metadata)\n message = UserMessage(data.get('message', ''), output_channel, sender_id, input_channel=self.name(), metadata=metadata)\n await on_new_message(message)\n return socketio_webhook","code_tokens":"","url":836829} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"all_reduce.py","full_name":"build_ring_all_reduce","func_name":"build_ring_all_reduce","docstring":"Construct a subgraph performing a ring-style all-reduce of input_tensors.","docstring_tokens":"","code":"def build_ring_all_reduce(input_tensors, num_workers, num_subchunks, gpu_perm, red_op, un_op=None):\n \"\"\"Construct a subgraph performing a ring-style all-reduce of input_tensors.\n\n Args:\n input_tensors: a list of T `tf.Tensor` objects, which must all\n have the same shape and type.\n num_workers: number of worker tasks spanned by input_tensors.\n num_subchunks: number of subchunks each device should process in one tick.\n gpu_perm: a list of ints giving a ring-wise rank ordering of GPUs at\n each worker. All workers must have the same number of\n GPUs with the same rank ordering. If NVLINK is available, this should\n be a ring order supported by NVLINK edges.\n red_op: a binary operator for elementwise reduction.\n un_op: an optional unary operator to apply to fully reduced values.\n\n Raises:\n ValueError: empty input_tensors or they don't all have same\n size.\n\n Returns:\n a list of T `tf.Tensor` identical sum-reductions of input_tensors.\n \"\"\"\n if len(input_tensors) < 2:\n raise ValueError('input_tensors must be length 2 or longer')\n (input_tensors, shape) = _flatten_tensors(input_tensors)\n devices = [t.device for t in input_tensors]\n (pred_by_s_d, rank_by_s_d) = _ring_permutations(num_workers, num_subchunks, gpu_perm)\n (chunks_by_dev, pad_len) = _build_ring_gather(input_tensors, devices, num_subchunks, pred_by_s_d, rank_by_s_d, red_op)\n if un_op:\n chunks_by_dev = _apply_unary_to_chunks(un_op, chunks_by_dev)\n output_tensors = _build_ring_scatter(pred_by_s_d, rank_by_s_d, chunks_by_dev)\n if pad_len > 0:\n output_tensors = _strip_padding(output_tensors, pad_len)\n if len(shape) != 1:\n output_tensors = _reshape_tensors(output_tensors, shape)\n return output_tensors","code_tokens":"","url":312328} +{"project_name":"intel\/neural-compressor","file_name":"utility.py","full_name":"print_table","func_name":"print_table","docstring":"Print table with prettytable.","docstring_tokens":"","code":"def print_table(column_mapping: Dict[str, str], table_entries: List[Any], output_handler=logger.info, title: Optional[str]=None, insert_newlines=False, precision: Optional[int]=None) -> None:\n \"\"\"Print table with prettytable.\n\n Args:\n :\n column_mapping (dict): Dictionary where key is a column header and value corresponds\n to object's attribute.\n table_entries (list): List of objects to be included in the table.\n output_handler (func, optional): Output handler function.\n title (str): Title for the table\n insert_newlines (bool): Add newlines to each row\n precision (int): Number of digits after the decimal point\n\n Returns:\n None\n \"\"\"\n from functools import reduce\n import numpy as np\n table = pt.PrettyTable(min_table_width=40)\n if title is not None:\n table.title = title\n table.field_names = list(column_mapping.keys())\n for entry in table_entries:\n table_row = []\n for (_, attribute) in column_mapping.items():\n if isinstance(entry, dict):\n table_row.append(entry.get(attribute))\n else:\n value = reduce(getattr, [entry] + attribute.split('.'))\n if (isinstance(value, np.floating) or isinstance(value, float)) and isinstance(precision, int):\n if 'e' in str(value):\n value = f'{value:.{precision}e}'\n else:\n value = round(value, precision)\n table_row.append(value)\n table.add_row(table_row)\n lines = table.get_string().split('\\n')\n for i in lines:\n if insert_newlines:\n i += '\\n'\n output_handler(i)","code_tokens":"","url":721509} +{"project_name":"MolecularAI\/Siamese-RNN-Self-Attention","file_name":"hyperopt.py","full_name":"HyperOpt.instantiate_model","func_name":"instantiate_model","docstring":"Instantiates the model, so that it can be fitted thereafter.","docstring_tokens":"","code":"def instantiate_model(self):\n \"\"\"\n Instantiates the model, so that it can be fitted thereafter.\n \n \"\"\"\n if self.hidden_states_processing is None:\n self_hidden_state_processor = None\n elif self.hidden_states_processing == 'self-attention':\n self.hidden_states_processor = SelfAttention(self.expansion_size, self.attention_layers, activation_fn=self.activation_function)\n elif self.hidden_states_processing == 'internal processing':\n self.hidden_states_processor = InternalProcessing(self.hidden_size, self.expansion_size, activation_fn=self.activation_fn)\n else:\n raise ValueError('\"hidden_states_processing\" input is not correct.')\n self.model = SNN(self.hidden_size, self.num_layers, self.dist_fn, self.similarity_fn, self.cell_type, self.loss_fn, self.learning_rate, self.weight_decay, self.embedding_dropout, self.dropout, hidden_states_processor=self.hidden_states_processor, embedding_dimensions=self.embedding_dimensions, initialisation_process=self.weight_initialisation, normalisation=self.normalisation)","code_tokens":"","url":350360} +{"project_name":"JosephKJ\/iOD","file_name":"retinanet.py","full_name":"RetinaNet.preprocess_image","func_name":"preprocess_image","docstring":"Normalize, pad and batch the input images.","docstring_tokens":"","code":"def preprocess_image(self, batched_inputs):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [x['image'].to(self.device) for x in batched_inputs]\n images = [self.normalizer(x) for x in images]\n images = ImageList.from_tensors(images, self.backbone.size_divisibility)\n return images","code_tokens":"","url":576864} +{"project_name":"neuroailab\/unsup_vvs","file_name":"objective.py","full_name":"add_supervised_loss","func_name":"add_supervised_loss","docstring":"Compute loss for model and add it to loss collection.","docstring_tokens":"","code":"def add_supervised_loss(labels, logits, weights, **kwargs):\n \"\"\"Compute loss for model and add it to loss collection.\"\"\"\n return tf.losses.softmax_cross_entropy(labels, logits, weights, **kwargs)","code_tokens":"","url":438457} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"dataset_factory.py","full_name":"DatasetBuilder.load_synthetic","func_name":"load_synthetic","docstring":"Return a dataset generating dummy synthetic data.","docstring_tokens":"","code":"def load_synthetic(self) -> tf.data.Dataset:\n \"\"\"Return a dataset generating dummy synthetic data.\"\"\"\n logging.info('Generating a synthetic dataset.')\n\n def generate_data(_):\n image = tf.zeros([self.image_size, self.image_size, self.num_channels], dtype=self.dtype)\n label = tf.zeros([1], dtype=tf.int32)\n return (image, label)\n dataset = tf.data.Dataset.range(1)\n dataset = dataset.repeat()\n dataset = dataset.map(generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n return dataset","code_tokens":"","url":851181} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"coords.py","full_name":"to_kgs","func_name":"to_kgs","docstring":"Converts from a MiniGo coordinate to a KGS coordinate.","docstring_tokens":"","code":"def to_kgs(board_size, coord):\n \"\"\"Converts from a MiniGo coordinate to a KGS coordinate.\"\"\"\n if coord is None:\n return 'pass'\n (y, x) = coord\n return '{}{}'.format(_KGS_COLUMNS[x], board_size - y)","code_tokens":"","url":758104} +{"project_name":"shazow\/workerpool","file_name":"blockingworker.py","full_name":"BlockingWorkerPool.put","func_name":"put","docstring":"Perform a job by a member in the pool and return the result.","docstring_tokens":"","code":"def put(self, job, result):\n \"\"\"Perform a job by a member in the pool and return the result.\"\"\"\n self.job.put(job)\n r = result.get()\n return r","code_tokens":"","url":373673} +{"project_name":"facebookresearch\/CompilerGym","file_name":"benchmark_cache_test.py","full_name":"test_oversized_benchmark_emits_warning","func_name":"test_oversized_benchmark_emits_warning","docstring":"Test that a warning is emitted when a single item is larger than the entire target cache size.","docstring_tokens":"","code":"def test_oversized_benchmark_emits_warning(mocker):\n \"\"\"Test that a warning is emitted when a single item is larger than the\n entire target cache size.\n \"\"\"\n cache = BenchmarkCache(max_size_in_bytes=10)\n mocker.spy(logger, 'warning')\n cache['test'] = make_benchmark_of_size(50)\n logger.warning.assert_called_once_with('Adding new benchmark with size %d bytes exceeds total target cache size of %d bytes', 50, 10)","code_tokens":"","url":125987} +{"project_name":"CentML\/DeepView.Profile","file_name":"utils.py","full_name":"sync_workers","func_name":"sync_workers","docstring":"Yields distributed rank and synchronizes all workers on exit.","docstring_tokens":"","code":"@contextmanager\ndef sync_workers():\n \"\"\"\n Yields distributed rank and synchronizes all workers on exit.\n \"\"\"\n rank = get_rank()\n yield rank\n barrier()","code_tokens":"","url":540825} +{"project_name":"secretflow\/secretflow","file_name":"transformer.py","full_name":"_FunctionTransformer.fit_transform","func_name":"fit_transform","docstring":"Fit function transformer and return transformed DataFrame.","docstring_tokens":"","code":"def fit_transform(self, df: Union[HDataFrame, VDataFrame]) -> Union[HDataFrame, VDataFrame, MixDataFrame]:\n \"\"\"Fit function transformer and return transformed DataFrame.\"\"\"\n self.fit(df)\n return self.transform(df)","code_tokens":"","url":856602} +{"project_name":"nasimrahaman\/antipasti-tf","file_name":"graph.py","full_name":"LayerGraph.all_node_layers","func_name":"all_node_layers","docstring":"Get the associated layers of all nodes in graph.","docstring_tokens":"","code":"@property\ndef all_node_layers(self):\n \"\"\"Get the associated layers of all nodes in graph.\"\"\"\n return [node_attributes['layer'] for node_attributes in self.graph.node.values()]","code_tokens":"","url":33529} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"test_subprocess.py","full_name":"POSIXProcessTestCase.test_exception_bad_args_0","func_name":"test_exception_bad_args_0","docstring":"Test error in the child raised in the parent for a bad args[0].","docstring_tokens":"","code":"def test_exception_bad_args_0(self):\n \"\"\"Test error in the child raised in the parent for a bad args[0].\"\"\"\n desired_exception = self._get_chdir_exception()\n try:\n p = subprocess.Popen([self._nonexistent_dir, '-c', ''])\n except OSError as e:\n self.assertEqual(desired_exception.errno, e.errno)\n self.assertEqual(desired_exception.strerror, e.strerror)\n else:\n self.fail('Expected OSError: %s' % desired_exception)","code_tokens":"","url":376407} +{"project_name":"santhoshkolloju\/Abstractive-Summarization-With-Transfer-","file_name":"seq_pg_agent.py","full_name":"SeqPGAgent.get_samples","func_name":"get_samples","docstring":"Returns sequence samples and extra results.","docstring_tokens":"","code":"def get_samples(self, extra_fetches=None, feed_dict=None):\n \"\"\"Returns sequence samples and extra results.\n\n Args:\n extra_fetches (dict, optional): Extra tensors to fetch values,\n besides `samples` and `sequence_length`. Same as the\n `fetches` argument of\n :tf_main:`tf.Session.run ` and\n tf_main:`partial_run `.\n feed_dict (dict, optional): A `dict` that maps tensor to\n values. Note that all placeholder values used in\n :meth:`get_samples` and subsequent :meth:`observe` calls\n should be fed here.\n\n Returns:\n A `dict` with keys **\"samples\"** and **\"sequence_length\"**\n containing the fetched values of :attr:`samples` and\n :attr:`sequence_length`, as well as other fetched values\n as specified in :attr:`extra_fetches`.\n\n Example:\n\n .. code-block:: python\n\n extra_fetches = {'truth_ids': data_batch['text_ids']}\n vals = agent.get_samples()\n sample_text = tx.utils.map_ids_to_strs(vals['samples'], vocab)\n truth_text = tx.utils.map_ids_to_strs(vals['truth_ids'], vocab)\n reward = reward_fn_in_python(truth_text, sample_text)\n \"\"\"\n if self._sess is None:\n raise ValueError('`sess` must be specified before sampling.')\n self._check_extra_fetches(extra_fetches)\n fetch_values = None\n if extra_fetches is not None:\n fetch_values = list(extra_fetches.values())\n feeds = None\n if feed_dict is not None:\n feeds = list(feed_dict.keys())\n self._setup_partial_run(fetches=fetch_values, feeds=feeds)\n fetches = {'samples': self._samples, 'sequence_length': self._sequence_length}\n if extra_fetches is not None:\n fetches.update(extra_fetches)\n feed_dict_ = feed_dict\n vals = self._sess.partial_run(self._partial_run_handle, fetches, feed_dict=feed_dict_)\n self._samples_py = vals['samples']\n self._sequence_length_py = vals['sequence_length']\n return vals","code_tokens":"","url":405959} +{"project_name":"Newbeeer\/TRM","file_name":"grad_fun.py","full_name":"jacobian","func_name":"jacobian","docstring":"Function that computes the Jacobian of a given function.","docstring_tokens":"","code":"def jacobian(func, inputs, create_graph=False, strict=False):\n \"\"\"Function that computes the Jacobian of a given function.\n\n Args:\n func (function): a Python function that takes Tensor inputs and returns\n a tuple of Tensors or a Tensor.\n inputs (tuple of Tensors or Tensor): inputs to the function ``func``.\n create_graph (bool, optional): If ``True``, the Jacobian will be\n computed in a differentiable manner. Note that when ``strict`` is\n ``False``, the result can not require gradients or be disconnected\n from the inputs. Defaults to ``False``.\n strict (bool, optional): If ``True``, an error will be raised when we\n detect that there exists an input such that all the outputs are\n independent of it. If ``False``, we return a Tensor of zeros as the\n jacobian for said inputs, which is the expected mathematical value.\n Defaults to ``False``.\n\n Returns:\n Jacobian (Tensor or nested tuple of Tensors): if there are a single\n input and output, this will be a single Tensor containing the\n Jacobian for the linearized inputs and output. If one of the two is\n a tuple, then the Jacobian will be a tuple of Tensors. If both of\n them are tuples, then the Jacobian will be a tuple of tuple of\n Tensors where ``Jacobian[i][j]`` will contain the Jacobian of the\n ``i``\\\\th output and ``j``\\\\th input and will have as size the\n concatenation of the sizes of the corresponding output and the\n corresponding input.\n\n Example:\n\n >>> def exp_reducer(x):\n ... return x.exp().sum(dim=1)\n >>> inputs = torch.rand(2, 2)\n >>> jacobian(exp_reducer, inputs)\n tensor([[[1.4917, 2.4352],\n [0.0000, 0.0000]],\n [[0.0000, 0.0000],\n [2.4369, 2.3799]]])\n\n >>> jacobian(exp_reducer, inputs, create_graph=True)\n tensor([[[1.4917, 2.4352],\n [0.0000, 0.0000]],\n [[0.0000, 0.0000],\n [2.4369, 2.3799]]], grad_fn=)\n\n >>> def exp_adder(x, y):\n ... return 2 * x.exp() + 3 * y\n >>> inputs = (torch.rand(2), torch.rand(2))\n >>> jacobian(exp_adder, inputs)\n (tensor([[2.8052, 0.0000],\n [0.0000, 3.3963]]),\n tensor([[3., 0.],\n [0., 3.]]))\n \"\"\"\n (is_inputs_tuple, inputs) = _as_tuple(inputs, 'inputs', 'jacobian')\n inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)\n outputs = func(*inputs)\n (is_outputs_tuple, outputs) = _as_tuple(outputs, 'outputs of the user-provided function', 'jacobian')\n _check_requires_grad(outputs, 'outputs', strict=strict)\n jacobian: Tuple[torch.Tensor, ...] = tuple()\n for (i, out) in enumerate(outputs):\n jac_i: Tuple[List[torch.Tensor]] = tuple(([] for _ in range(len(inputs))))\n for j in range(out.nelement()):\n vj = _autograd_grad((out.reshape(-1)[j],), inputs, retain_graph=True, create_graph=create_graph)\n for (el_idx, (jac_i_el, vj_el, inp_el)) in enumerate(zip(jac_i, vj, inputs)):\n if vj_el is not None:\n if strict and create_graph and (not vj_el.requires_grad):\n msg = 'The jacobian of the user-provided function is independent of input {}. This is not allowed in strict mode when create_graph=True.'.format(i)\n raise RuntimeError(msg)\n jac_i_el.append(vj_el)\n else:\n if strict:\n msg = 'Output {} of the user-provided function is independent of input {}. This is not allowed in strict mode.'.format(i, el_idx)\n raise RuntimeError(msg)\n jac_i_el.append(torch.zeros_like(inp_el))\n jacobian += (tuple((torch.stack(jac_i_el, dim=0).view(out.size() + inputs[el_idx].size()) for (el_idx, jac_i_el) in enumerate(jac_i))),)\n jacobian = _grad_postprocess(jacobian, create_graph)\n return _tuple_postprocess(jacobian, (is_outputs_tuple, is_inputs_tuple))","code_tokens":"","url":951618} +{"project_name":"rudranil723\/mini-main","file_name":"options.py","full_name":"ModelAdmin.get_formsets_with_inlines","func_name":"get_formsets_with_inlines","docstring":"Yield formsets and the corresponding inlines.","docstring_tokens":"","code":"def get_formsets_with_inlines(self, request, obj=None):\n \"\"\"\n Yield formsets and the corresponding inlines.\n \"\"\"\n for inline in self.get_inline_instances(request, obj):\n yield (inline.get_formset(request, obj), inline)","code_tokens":"","url":314756} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"surface_test.py","full_name":"SurfaceTypeTest.test_fill_keyword_args","func_name":"test_fill_keyword_args","docstring":"Ensure fill() accepts keyword arguments.","docstring_tokens":"","code":"def test_fill_keyword_args(self):\n \"\"\"Ensure fill() accepts keyword arguments.\"\"\"\n color = (1, 2, 3, 255)\n area = (1, 1, 2, 2)\n s1 = pygame.Surface((4, 4), 0, 32)\n s1.fill(special_flags=pygame.BLEND_ADD, color=color, rect=area)\n self.assertEqual(s1.get_at((0, 0)), (0, 0, 0, 255))\n self.assertEqual(s1.get_at((1, 1)), color)","code_tokens":"","url":45970} +{"project_name":"huawei-noah\/xingtian","file_name":"pytorch_fn.py","full_name":"arange","func_name":"arange","docstring":"Rearange from left to right.","docstring_tokens":"","code":"def arange(*inputs, dtype='long', device=None):\n \"\"\"Rearange from left to right.\"\"\"\n if dtype == 'long':\n dtype = torch.long\n elif dtype == 'uint8':\n dtype = torch.uint8\n else:\n dtype = None\n return torch.arange(*inputs, dtype=dtype, device=device)","code_tokens":"","url":962786} +{"project_name":"Trusted-AI\/AIF360","file_name":"lfr.py","full_name":"LFR.fit","func_name":"fit","docstring":"Compute the transformation parameters that leads to fair representations.","docstring_tokens":"","code":"def fit(self, dataset, maxiter=5000, maxfun=5000):\n \"\"\"Compute the transformation parameters that leads to fair representations.\n Args:\n dataset (BinaryLabelDataset): Dataset containing true labels.\n maxiter (int): Maximum number of iterations.\n maxfun (int): Maxinum number of function evaluations.\n Returns:\n LFR: Returns self.\n \"\"\"\n if self.seed is not None:\n np.random.seed(self.seed)\n (num_train_samples, self.features_dim) = np.shape(dataset.features)\n protected_attributes = np.reshape(dataset.protected_attributes[:, dataset.protected_attribute_names.index(self.protected_attribute_name)], [-1, 1])\n unprivileged_sample_ids = np.array(np.where(protected_attributes == self.unprivileged_group_protected_attribute_value))[0].flatten()\n privileged_sample_ids = np.array(np.where(protected_attributes == self.privileged_group_protected_attribute_value))[0].flatten()\n features_unprivileged = dataset.features[unprivileged_sample_ids]\n features_privileged = dataset.features[privileged_sample_ids]\n labels_unprivileged = dataset.labels[unprivileged_sample_ids]\n labels_privileged = dataset.labels[privileged_sample_ids]\n parameters_initialization = np.random.uniform(size=self.k + self.features_dim * self.k)\n bnd = [(0, 1)] * self.k + [(None, None)] * self.features_dim * self.k\n lfr_helpers.LFR_optim_objective.steps = 0\n self.learned_model = optim.fmin_l_bfgs_b(lfr_helpers.LFR_optim_objective, x0=parameters_initialization, epsilon=1e-05, args=(features_unprivileged, features_privileged, labels_unprivileged[:, 0], labels_privileged[:, 0], self.k, self.Ax, self.Ay, self.Az, self.print_interval, self.verbose), bounds=bnd, approx_grad=True, maxfun=maxfun, maxiter=maxiter, disp=self.verbose)[0]\n self.w = self.learned_model[:self.k]\n self.prototypes = self.learned_model[self.k:].reshape((self.k, self.features_dim))\n return self","code_tokens":"","url":412239} +{"project_name":"tejas-trivedi\/Natural-Language-Processing","file_name":"base.py","full_name":"LoadFile.load_document","func_name":"load_document","docstring":"Loads the content of a document\/string\/stream in a given language.","docstring_tokens":"","code":"def load_document(self, input, **kwargs):\n \"\"\"Loads the content of a document\/string\/stream in a given language.\n\n Args:\n input (str): input.\n language (str): language of the input, defaults to 'en'.\n encoding (str): encoding of the raw file.\n normalization (str): word normalization method, defaults to\n 'stemming'. Other possible values are 'lemmatization' or 'None'\n for using word surface forms instead of stems\/lemmas.\n \"\"\"\n language = kwargs.get('language', 'en')\n doc = Document()\n if is_corenlp(input):\n path = input\n parser = MinimalCoreNLPReader()\n doc = parser.read(path=input, **kwargs)\n doc.is_corenlp_file = True\n elif is_file_path(input):\n path = input\n with open(path, encoding=kwargs.get('encoding', 'utf-8')) as f:\n input = f.read()\n parser = RawTextReader(language=language)\n doc = parser.read(text=input, path=path, **kwargs)\n elif isinstance(input, str):\n parser = RawTextReader(language=language)\n doc = parser.read(text=input, **kwargs)\n else:\n logging.error('Cannot process input. It is neither a file path or a string: {}'.format(type(input)))\n return\n self.input_file = doc.input_file\n self.language = language\n self.sentences = doc.sentences\n self.stoplist = get_stopwords(self.language)\n self.normalization = kwargs.get('normalization', 'stemming')\n if self.normalization == 'stemming':\n stem = get_stemmer_func(self.language)\n get_stem = lambda s: [stem(w).lower() for w in s.words]\n else:\n get_stem = lambda s: [w.lower() for w in s.words]\n for (i, sentence) in enumerate(self.sentences):\n self.sentences[i].stems = get_stem(sentence)\n if getattr(doc, 'is_corenlp_file', False):\n self.normalize_pos_tags()\n self.unescape_punctuation_marks()","code_tokens":"","url":636959} +{"project_name":"Qsingle\/LearnablePromptSAM","file_name":"amg.py","full_name":"build_point_grid","func_name":"build_point_grid","docstring":"Generates a 2D grid of points evenly spaced in [0,1]x[0,1].","docstring_tokens":"","code":"def build_point_grid(n_per_side: int) -> np.ndarray:\n \"\"\"Generates a 2D grid of points evenly spaced in [0,1]x[0,1].\"\"\"\n offset = 1 \/ (2 * n_per_side)\n points_one_side = np.linspace(offset, 1 - offset, n_per_side)\n points_x = np.tile(points_one_side[None, :], (n_per_side, 1))\n points_y = np.tile(points_one_side[:, None], (1, n_per_side))\n points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)\n return points","code_tokens":"","url":587871} +{"project_name":"kubeflow\/pipelines","file_name":"test_visualization.py","full_name":"test_markdown_storage_invalid_datatype","func_name":"test_markdown_storage_invalid_datatype","docstring":"Test for passing invalid markdown storage datatype.","docstring_tokens":"","code":"def test_markdown_storage_invalid_datatype(viz_params):\n \"\"\"Test for passing invalid markdown storage datatype.\"\"\"\n viz_params['markdown']['storage'] = ['test']\n expected_exception_msg = \"storage must be of type but received as {}\".format(type(viz_params['markdown']['storage']))\n with pytest.raises(TypeError, match=expected_exception_msg):\n generate_visualization(viz_params)","code_tokens":"","url":779681} +{"project_name":"calico\/basenji","file_name":"seqnn_util.py","full_name":"SeqNNModel.test_tfr","func_name":"test_tfr","docstring":"Compute model accuracy on a test set, where data is loaded from a queue.","docstring_tokens":"","code":"def test_tfr(self, sess, dataset, handle_ph=None, test_batches=None, sample=1.0):\n \"\"\" Compute model accuracy on a test set, where data is loaded from a queue.\n\n Args:\n sess: TensorFlow session\n dataset: Dataset\n handle_ph: Dataset handle placeholder\n test_batches: Number of test batches to use.\n sample: Sample sequence positions to save predictions\/targets.\n\n Returns:\n acc: Accuracy object\n \"\"\"\n fd = self.set_mode('test')\n if handle_ph is not None:\n fd[handle_ph] = dataset.handle\n if test_batches is None:\n num_seqs = dataset.num_seqs\n else:\n num_seqs = min(dataset.num_seqs, test_batches * self.hp.batch_size)\n sample_length = int(np.round(sample * self.preds_length))\n preds = None\n targets = None\n targets_na = np.zeros((num_seqs, sample_length), dtype='bool')\n batch_losses = []\n batch_target_losses = []\n batch_sizes = []\n data_available = True\n batch_num = 0\n si = 0\n while data_available and (test_batches is None or batch_num < test_batches):\n try:\n run_ops = [self.targets_train, self.preds_train_loss, self.loss_train, self.loss_train_targets]\n run_returns = sess.run(run_ops, feed_dict=fd)\n (targets_batch, preds_batch, loss_batch, target_losses_batch) = run_returns\n (batch_size, _, num_targets) = preds_batch.shape\n if preds is None:\n preds = np.zeros((num_seqs, sample_length, num_targets), dtype='float16')\n targets = np.zeros((num_seqs, sample_length, num_targets), dtype='float16')\n if sample_length < self.preds_length:\n sampled_indexes = np.random.choice(np.arange(self.preds_length), size=sample_length, replace=False)\n sampled_indexes.sort()\n preds[si:si + batch_size] = preds_batch[:, sampled_indexes, :]\n targets[si:si + batch_size] = targets_batch[:, sampled_indexes, :]\n else:\n preds[si:si + batch_size] = preds_batch\n targets[si:si + batch_size] = targets_batch\n batch_losses.append(loss_batch)\n batch_target_losses.append(target_losses_batch)\n batch_sizes.append(preds_batch.shape[0])\n batch_num += 1\n si += batch_size\n except tf.errors.OutOfRangeError:\n data_available = False\n batch_losses = np.array(batch_losses, dtype='float64')\n batch_losses = np.average(batch_losses, weights=batch_sizes)\n batch_target_losses = np.array(batch_target_losses, dtype='float64')\n batch_target_losses = np.average(batch_target_losses, axis=0, weights=batch_sizes)\n acc = accuracy.Accuracy(targets, preds, targets_na, batch_losses, batch_target_losses)\n return acc","code_tokens":"","url":94661} +{"project_name":"viko-3\/DiffSeqMol","file_name":"fp16_util.py","full_name":"make_master_params","func_name":"make_master_params","docstring":"Copy model parameters into a (differently-shaped) list of full-precision parameters.","docstring_tokens":"","code":"def make_master_params(model_params):\n \"\"\"\n Copy model parameters into a (differently-shaped) list of full-precision\n parameters.\n \"\"\"\n master_params = _flatten_dense_tensors([param.detach().float() for param in model_params])\n master_params = nn.Parameter(master_params)\n master_params.requires_grad = True\n return [master_params]","code_tokens":"","url":551295} +{"project_name":"PIYUSH0812\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"resnet_model.py","full_name":"conv2d_fixed_padding","func_name":"conv2d_fixed_padding","docstring":"Strided 2-D convolution with explicit padding.","docstring_tokens":"","code":"def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):\n \"\"\"Strided 2-D convolution with explicit padding.\"\"\"\n if strides > 1:\n inputs = fixed_padding(inputs, kernel_size, data_format)\n return tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding='SAME' if strides == 1 else 'VALID', use_bias=False, kernel_initializer=tf.variance_scaling_initializer(), data_format=data_format)","code_tokens":"","url":14051} +{"project_name":"lifuguan\/ObjectDetection","file_name":"yolov3_mobilev2.py","full_name":"YOLOv3.forward","func_name":"forward","docstring":"Forward path of YOLOv3.","docstring_tokens":"","code":"def forward(self, x, targets=None, epoch=0):\n \"\"\"\n Forward path of YOLOv3.\n Args:\n x (torch.Tensor) : input data whose shape is :math:`(N, C, H, W)`, where N, C are batchsize and num. of channels.\n targets (torch.Tensor) : label array whose shape is :math:`(N, 50, 5)`\n\n Returns:\n training:\n output (torch.Tensor): loss tensor for backpropagation.\n test:\n output (torch.Tensor): concatenated detection results.\n \"\"\"\n train = targets is not None\n output = []\n anchor_losses = []\n iou_losses = []\n l1_losses = []\n conf_losses = []\n cls_losses = []\n route_layers = []\n for (i, module) in enumerate(self.module_list):\n x = module(x)\n if i in [6, 13, 25, 32, 39]:\n route_layers.append(x)\n if i == 27:\n x = torch.cat((x, route_layers[1]), 1)\n if i == 34:\n x = torch.cat((x, route_layers[0]), 1)\n for l in range(3):\n conver = getattr(self, 'level_{}_conv'.format(l))\n header = getattr(self, 'level_{}_header'.format(l))\n if self.asff:\n f_conv = conver(route_layers[2], route_layers[3], route_layers[4])\n else:\n f_conv = conver(route_layers[l + 2])\n if train:\n (x, anchor_loss, iou_loss, l1_loss, conf_loss, cls_loss) = header(f_conv, targets)\n anchor_losses.append(anchor_loss)\n iou_losses.append(iou_loss)\n l1_losses.append(l1_loss)\n conf_losses.append(conf_loss)\n cls_losses.append(cls_loss)\n else:\n x = header(f_conv)\n output.append(x)\n if train:\n losses = torch.stack(output, 0).unsqueeze(0).sum(1, keepdim=True)\n anchor_losses = torch.stack(anchor_losses, 0).unsqueeze(0).sum(1, keepdim=True)\n iou_losses = torch.stack(iou_losses, 0).unsqueeze(0).sum(1, keepdim=True)\n l1_losses = torch.stack(l1_losses, 0).unsqueeze(0).sum(1, keepdim=True)\n conf_losses = torch.stack(conf_losses, 0).unsqueeze(0).sum(1, keepdim=True)\n cls_losses = torch.stack(cls_losses, 0).unsqueeze(0).sum(1, keepdim=True)\n loss_dict = dict(losses=losses, anchor_losses=anchor_losses, iou_losses=iou_losses, l1_losses=l1_losses, conf_losses=conf_losses, cls_losses=cls_losses)\n return loss_dict\n else:\n return torch.cat(output, 1)","code_tokens":"","url":744321} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_scaledlogit.py","full_name":"test_scaledlogit_transform","func_name":"test_scaledlogit_transform","docstring":"Test that we get the right output.","docstring_tokens":"","code":"@pytest.mark.parametrize('lower, upper, output', [(10, 70, np.log((TEST_SERIES - 10) \/ (70 - TEST_SERIES))), (None, 70, -np.log(70 - TEST_SERIES)), (10, None, np.log(TEST_SERIES - 10)), (None, None, TEST_SERIES)])\ndef test_scaledlogit_transform(lower, upper, output):\n \"\"\"Test that we get the right output.\"\"\"\n transformer = ScaledLogitTransformer(lower, upper)\n y_transformed = transformer.fit_transform(TEST_SERIES)\n assert np.all(output == y_transformed)","code_tokens":"","url":400065} +{"project_name":"sarnsdev\/social-alignment-data-mining","file_name":"opt.py","full_name":"local_inplace_incsubtensor1","func_name":"local_inplace_incsubtensor1","docstring":"Also work for GpuAdvancedIncSubtensor1.","docstring_tokens":"","code":"@gof.local_optimizer([AdvancedIncSubtensor1], inplace=True)\ndef local_inplace_incsubtensor1(node):\n \"\"\"\n Also work for GpuAdvancedIncSubtensor1.\n\n \"\"\"\n if isinstance(node.op, AdvancedIncSubtensor1) and (not node.op.inplace):\n new_op = node.op.clone_inplace()\n new_node = new_op(*node.inputs)\n copy_stack_trace(node.outputs, new_node)\n return [new_node]\n return False","code_tokens":"","url":393135} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"internals.py","full_name":"BlockManager.reindex_axis","func_name":"reindex_axis","docstring":"Conform block manager to new index.","docstring_tokens":"","code":"def reindex_axis(self, new_index, axis, method=None, limit=None, fill_value=None, copy=True):\n \"\"\"\n Conform block manager to new index.\n \"\"\"\n new_index = _ensure_index(new_index)\n (new_index, indexer) = self.axes[axis].reindex(new_index, method=method, limit=limit)\n return self.reindex_indexer(new_index, indexer, axis=axis, fill_value=fill_value, copy=copy)","code_tokens":"","url":717785} +{"project_name":"voxel51\/fiftyone","file_name":"delegated_operation.py","full_name":"DelegatedOperationRepo.update_run_state","func_name":"update_run_state","docstring":"Update the run state of an operation.","docstring_tokens":"","code":"def update_run_state(self, _id: ObjectId, run_state: ExecutionRunState, result: ExecutionResult=None) -> DelegatedOperationDocument:\n \"\"\"Update the run state of an operation.\"\"\"\n raise NotImplementedError('subclass must implement update_run_state()')","code_tokens":"","url":583708} +{"project_name":"TheUpshot\/4thdownbot-model","file_name":"plays.py","full_name":"missed_field_goal","func_name":"missed_field_goal","docstring":"Opponent takes over from the spot of the kick.","docstring_tokens":"","code":"def missed_field_goal(situation, new_situation, **kwargs):\n \"\"\"Opponent takes over from the spot of the kick.\"\"\"\n new_situation['yfog'] = 100 - (situation['yfog'] - 8)\n return new_situation","code_tokens":"","url":4781} +{"project_name":"dbetm\/handwritten-flowchart-with-cnn","file_name":"history.py","full_name":"History.append_epoch_info","func_name":"append_epoch_info","docstring":"Open existing log cvs file and append a new row epoch info.","docstring_tokens":"","code":"def append_epoch_info(self, row):\n \"\"\"Open existing log cvs file and append a new row epoch info.\"\"\"\n self.csv_log = open(self.base_path + '\/history.csv', 'a')\n string = ','.join((str(s) for s in row))\n self.csv_log.write('\\n' + string)\n self.csv_log.close()","code_tokens":"","url":205491} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"offsets.py","full_name":"BusinessHourMixin.rollback","func_name":"rollback","docstring":"Roll provided date backward to next offset only if not on offset.","docstring_tokens":"","code":"@apply_wraps\ndef rollback(self, dt):\n \"\"\"\n Roll provided date backward to next offset only if not on offset.\n \"\"\"\n if not self.is_on_offset(dt):\n if self.n >= 0:\n dt = self._prev_opening_time(dt)\n else:\n dt = self._next_opening_time(dt)\n return self._get_closing_time(dt)\n return dt","code_tokens":"","url":83597} +{"project_name":"RasaHQ\/rasa","file_name":"domain.py","full_name":"Domain.index_for_action","func_name":"index_for_action","docstring":"Looks up which action index corresponds to this action name.","docstring_tokens":"","code":"def index_for_action(self, action_name: Text) -> int:\n \"\"\"Looks up which action index corresponds to this action name.\"\"\"\n try:\n return self.action_names_or_texts.index(action_name)\n except ValueError:\n self.raise_action_not_found_exception(action_name)","code_tokens":"","url":837410} +{"project_name":"deephyper\/deephyper","file_name":"_job.py","full_name":"Job.objective","func_name":"objective","docstring":"Objective returned by the run-function.","docstring_tokens":"","code":"@property\ndef objective(self):\n \"\"\"Objective returned by the run-function.\"\"\"\n return self.output['objective']","code_tokens":"","url":520807} +{"project_name":"rlgraph\/rlgraph","file_name":"test_sequence_helper.py","full_name":"TestSequenceHelper.test_reverse_apply_decays_to_sequence","func_name":"test_reverse_apply_decays_to_sequence","docstring":"Tests reverse decaying a sequence of 1-step TD errors for GAE.","docstring_tokens":"","code":"def test_reverse_apply_decays_to_sequence(self):\n \"\"\"\n Tests reverse decaying a sequence of 1-step TD errors for GAE.\n \"\"\"\n sequence_helper = SequenceHelper()\n decay_value = 0.5\n test = ComponentTest(component=sequence_helper, input_spaces=self.input_spaces)\n td_errors = np.asarray([0.1, 0.2, 0.3, 0.4])\n indices = np.array([0, 0, 0, 1])\n expected_output_sequence_manual = np.asarray([0.1 + 0.5 * 0.2 + 0.25 * 0.3 + 0.125 * 0.4, 0.2 + 0.5 * 0.3 + 0.25 * 0.4, 0.3 + 0.5 * 0.4, 0.4])\n expected_output_sequence_numpy = self.decay_td_sequence(td_errors, decay=decay_value)\n recursive_assert_almost_equal(expected_output_sequence_manual, expected_output_sequence_numpy)\n test.test(('reverse_apply_decays_to_sequence', [td_errors, indices, decay_value]), expected_outputs=expected_output_sequence_manual)","code_tokens":"","url":862748} +{"project_name":"Juniper\/OpenClos","file_name":"writer.py","full_name":"L3ReportWriter.getThreeStageL3ReportJson","func_name":"getThreeStageL3ReportJson","docstring":"This method will be called by REST layer :returns str: l3Report in json format.","docstring_tokens":"","code":"def getThreeStageL3ReportJson(self):\n \"\"\"\n This method will be called by REST layer\n :returns str: l3Report in json format.\n \"\"\"\n data = self.getDataFor3StageL3Report()\n l3ReportJson = self.l3ReportTemplate.render(devices=data['devices'], links=data['links'])\n return l3ReportJson","code_tokens":"","url":274985} +{"project_name":"mnot\/thor","file_name":"tcp.py","full_name":"TcpConnection.pause","func_name":"pause","docstring":"Temporarily stop\/start reading from the connection and pushing it to the app.","docstring_tokens":"","code":"def pause(self, paused: bool) -> None:\n \"\"\"\n Temporarily stop\/start reading from the connection and pushing\n it to the app.\n \"\"\"\n if paused:\n self.event_del('fd_readable')\n else:\n self.event_add('fd_readable')\n self._input_paused = paused","code_tokens":"","url":355118} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"quantized_distribution.py","full_name":"QuantizedDistribution.high","func_name":"high","docstring":"Highest value that quantization returns.","docstring_tokens":"","code":"@property\ndef high(self):\n \"\"\"Highest value that quantization returns.\"\"\"\n return self._high","code_tokens":"","url":312853} +{"project_name":"intel\/neural-compressor","file_name":"weight_only.py","full_name":"quant_weight","func_name":"quant_weight","docstring":"Quant and dequant tensor with group size.","docstring_tokens":"","code":"def quant_weight(weight, num_bits=4, group_size=-1, scheme='asym', quantile=1.0, data_type='int', return_int=False, full_range=False):\n \"\"\"Quant and dequant tensor with group size.\n\n Args:\n weight: input weight\n num_bits (int, optional): num_bits. Defaults to 4.\n group_size (int, optional): how many elements share one scale\/zp. Defaults to -1.\n scheme (str, optional): sym or asym. Defaults to \"asym\".\n quantile (float, optional): percentile of clip. Defaults to 1.0.\n data_type (str, optional): select from int, nf4, fp4. Defaults to int.\n return_int (bool, optional): Choose return fp32 or int8\/uint8 data.\n Defaults to False.\n full_range (bool, optional): Choose sym range whether use -2**(bits-1).\n\n Returns:\n output: qdq weight.\n \"\"\"\n if num_bits <= 0:\n return weight\n if group_size == -1 or weight.shape[1] < group_size:\n return qdq_weight_actor(weight, num_bits, scheme=scheme, quantile=quantile, return_int=return_int, full_range=full_range, data_type=data_type)\n orig_shape = weight.shape\n if weight.shape[1] % group_size == 0:\n weight = weight.reshape(-1, group_size)\n if return_int:\n (weight, scale, zp) = qdq_weight_actor(weight, num_bits, scheme=scheme, quantile=quantile, return_int=True, full_range=full_range, data_type=data_type)\n weight = weight.reshape(orig_shape)\n scale = scale.reshape(orig_shape[0], -1)\n if zp is not None:\n zp = zp.reshape(orig_shape[0], -1)\n return (weight, scale, zp)\n else:\n weight = qdq_weight_actor(weight, num_bits, scheme=scheme, data_type=data_type, quantile=quantile, full_range=full_range)\n return weight.reshape(orig_shape)\n else:\n split_index = weight.shape[1] \/\/ group_size * group_size\n weight1 = weight[:, :split_index]\n weight1 = weight1.reshape(-1, group_size)\n if return_int:\n (weight1, scale1, zp1) = qdq_weight_actor(weight1, num_bits, scheme=scheme, data_type=data_type, quantile=quantile, return_int=True, full_range=full_range)\n scale1 = scale1.reshape(orig_shape[0], -1)\n if zp1 is not None:\n zp1 = zp1.reshape(orig_shape[0], -1)\n else:\n weight1 = qdq_weight_actor(weight1, num_bits, scheme=scheme, quantile=quantile, data_type=data_type, full_range=full_range)\n weight1 = weight1.reshape(orig_shape[0], split_index)\n weight2 = weight[:, split_index:]\n if return_int:\n (weight2, scale2, zp2) = qdq_weight_actor(weight2, num_bits, scheme=scheme, data_type=data_type, quantile=quantile, return_int=True, full_range=full_range)\n weight = torch.cat([weight1, weight2], dim=1)\n scale = torch.cat([scale1, scale2], dim=1)\n if zp2 is not None:\n zp = torch.cat([zp1, zp2], dim=1)\n else:\n zp = None\n return (weight, scale, zp)\n else:\n weight2 = qdq_weight_actor(weight2, num_bits, scheme=scheme, data_type=data_type, quantile=quantile, full_range=full_range)\n weight = torch.cat([weight1, weight2], dim=1)\n return weight","code_tokens":"","url":737926} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"searching.py","full_name":"Results.docnum","func_name":"docnum","docstring":"Returns the document number of the result at position n in the list of ranked documents.","docstring_tokens":"","code":"def docnum(self, n):\n \"\"\"Returns the document number of the result at position n in the list\n of ranked documents.\n \"\"\"\n return self.top_n[n][1]","code_tokens":"","url":133113} +{"project_name":"tensorlayer\/TensorLayer","file_name":"tutorial_generate_text.py","full_name":"basic_clean_str","func_name":"basic_clean_str","docstring":"Tokenization\/string cleaning for a datasets.","docstring_tokens":"","code":"def basic_clean_str(string):\n \"\"\"Tokenization\/string cleaning for a datasets.\"\"\"\n string = re.sub('\\\\n', ' ', string)\n string = re.sub(\"\\\\'s\", \" 's\", string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99s', \" 's\", string)\n string = re.sub(\"\\\\'ve\", ' have', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99ve', ' have', string)\n string = re.sub(\"\\\\'t\", ' not', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99t', ' not', string)\n string = re.sub(\"\\\\'re\", ' are', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99re', ' are', string)\n string = re.sub(\"\\\\'d\", '', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99d', '', string)\n string = re.sub(\"\\\\'ll\", ' will', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99ll', ' will', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x9c', ' ', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x9d', ' ', string)\n string = re.sub('\\\\\"', ' ', string)\n string = re.sub(\"\\\\'\", ' ', string)\n string = re.sub('\\\\\u00c3\u00a2\u00c2\\x80\u00c2\\x99', ' ', string)\n string = re.sub('\\\\.', ' . ', string)\n string = re.sub('\\\\,', ' , ', string)\n string = re.sub('\\\\!', ' ! ', string)\n string = re.sub('\\\\-', ' ', string)\n string = re.sub('\\\\(', ' ', string)\n string = re.sub('\\\\)', ' ', string)\n string = re.sub('\\\\]', ' ', string)\n string = re.sub('\\\\[', ' ', string)\n string = re.sub('\\\\?', ' ', string)\n string = re.sub('\\\\>', ' ', string)\n string = re.sub('\\\\<', ' ', string)\n string = re.sub('\\\\=', ' ', string)\n string = re.sub('\\\\;', ' ', string)\n string = re.sub('\\\\;', ' ', string)\n string = re.sub('\\\\:', ' ', string)\n string = re.sub('\\\\\"', ' ', string)\n string = re.sub('\\\\$', ' ', string)\n string = re.sub('\\\\_', ' ', string)\n string = re.sub('\\\\s{2,}', ' ', string)\n return string.strip().lower()","code_tokens":"","url":366102} +{"project_name":"Eric3911\/OpenAGI","file_name":"information_retrieval_dataset.py","full_name":"BertInformationRetrievalDataset.parse_query_to_passages","func_name":"parse_query_to_passages","docstring":"Function which parses query to passages correspondence file.","docstring_tokens":"","code":"def parse_query_to_passages(self, file):\n \"\"\"\n Function which parses query to passages correspondence file.\n \"\"\"\n idx2psgs = {}\n idx = 0\n for line in open(file, 'r').readlines():\n if '\\t' not in line:\n raise ValueError(f'Provided dataset does not have a form of tsv file')\n query_and_psgs = line.split('\\t')\n query_and_psgs_ids = [int(id_) for id_ in query_and_psgs]\n (query_and_rel_psg_ids, irrel_psgs_ids) = (query_and_psgs_ids[:2], query_and_psgs_ids[2:])\n random.shuffle(irrel_psgs_ids)\n num_samples = len(irrel_psgs_ids) \/\/ self.num_negatives\n for j in range(num_samples):\n left = self.num_negatives * j\n right = self.num_negatives * (j + 1)\n idx2psgs[idx] = query_and_rel_psg_ids + irrel_psgs_ids[left:right]\n idx += 1\n return idx2psgs","code_tokens":"","url":273263} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"cookiejar.py","full_name":"escape_path","func_name":"escape_path","docstring":"Escape any invalid characters in HTTP URL, and uppercase all escapes.","docstring_tokens":"","code":"def escape_path(path):\n \"\"\"Escape any invalid characters in HTTP URL, and uppercase all escapes.\"\"\"\n path = urllib.parse.quote(path, HTTP_PATH_SAFE)\n path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)\n return path","code_tokens":"","url":282607} +{"project_name":"sunishsheth2009\/ChatterBot","file_name":"fst.py","full_name":"BaseCursor.peek_key_string","func_name":"peek_key_string","docstring":"Returns the next closest key in the graph as a decoded unicode string.","docstring_tokens":"","code":"def peek_key_string(self):\n \"\"\"Returns the next closest key in the graph as a decoded unicode\n string.\n \"\"\"\n return utf8decode(self.peek_key_bytes())[0]","code_tokens":"","url":484310} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"conftest.py","full_name":"read_ext","func_name":"read_ext","docstring":"Valid extensions for reading Excel files.","docstring_tokens":"","code":"@pytest.fixture(params=['.xls', '.xlsx', '.xlsm', '.ods', '.xlsb'])\ndef read_ext(request):\n \"\"\"\n Valid extensions for reading Excel files.\n \"\"\"\n return request.param","code_tokens":"","url":83493} +{"project_name":"deepmind\/acme","file_name":"models.py","full_name":"make_ensemble_world_model","func_name":"make_ensemble_world_model","docstring":"Creates an ensemble world model from its network.","docstring_tokens":"","code":"def make_ensemble_world_model(world_model_network: mbop_networks.WorldModelNetwork) -> WorldModel:\n \"\"\"Creates an ensemble world model from its network.\"\"\"\n return functools.partial(ensemble.apply_round_robin, world_model_network.apply)","code_tokens":"","url":7593} +{"project_name":"fpthink\/3D-WSIS","file_name":"log_buffer.py","full_name":"HistoryBuffer.summation","func_name":"summation","docstring":"Return the summation of the latest `window_size` values in the buffer.","docstring_tokens":"","code":"def summation(self, window_size: int) -> float:\n \"\"\"\n Return the summation of the latest `window_size` values in the buffer.\n \"\"\"\n _sum = sum(map(lambda x: x[0] * x[1], zip(self._values[-window_size:], self._nums[-window_size:])))\n return _sum","code_tokens":"","url":4658} +{"project_name":"CAMeL-Lab\/camel_tools","file_name":"test_charmap.py","full_name":"TestCharMapperInit.test_init_none","func_name":"test_init_none","docstring":"Test that init with None raises a TypeError.","docstring_tokens":"","code":"def test_init_none(self):\n \"\"\"Test that init with None raises a TypeError.\n \"\"\"\n with pytest.raises(TypeError):\n CharMapper(None)","code_tokens":"","url":411183} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"backend_bases.py","full_name":"NavigationToolbar2.press","func_name":"press","docstring":"Called whenever a mouse button is pressed.","docstring_tokens":"","code":"@cbook.deprecated('3.3')\ndef press(self, event):\n \"\"\"Called whenever a mouse button is pressed.\"\"\"","code_tokens":"","url":96233} +{"project_name":"rudranil723\/mini-main","file_name":"ccompiler_opt.py","full_name":"_Feature.feature_flags","func_name":"feature_flags","docstring":"Return a list of CPU features flags sorted from the lowest to highest interest.","docstring_tokens":"","code":"@_Cache.me\ndef feature_flags(self, names):\n \"\"\"\n Return a list of CPU features flags sorted from the lowest\n to highest interest.\n \"\"\"\n names = self.feature_sorted(self.feature_implies_c(names))\n flags = []\n for n in names:\n d = self.feature_supported[n]\n f = d.get('flags', [])\n if not f or not self.cc_test_flags(f):\n continue\n flags += f\n return self.cc_normalize_flags(flags)","code_tokens":"","url":322509} +{"project_name":"google-research\/scenic","file_name":"cifar10_dataset.py","full_name":"get_dataset","func_name":"get_dataset","docstring":"Returns generators for the CIFAR10 train, validation, and test set.","docstring_tokens":"","code":"@datasets.add_dataset('cifar10')\ndef get_dataset(*, batch_size, eval_batch_size, num_shards, dtype_str='float32', shuffle_seed=0, rng=None, dataset_configs=None, dataset_service_address: Optional[str]=None):\n \"\"\"Returns generators for the CIFAR10 train, validation, and test set.\n\n Args:\n batch_size: int; Determines the train batch size.\n eval_batch_size: int; Determines the evaluation batch size.\n num_shards: int; Number of shards --> batch shape: [num_shards, bs, ...].\n dtype_str: Data type of the image (e.g. 'float32').\n shuffle_seed: int; Seed for shuffling the training data.\n rng: JAX rng key, which can be used for augmentation, shuffling, etc.\n dataset_configs: dict; Dataset specific configurations.\n dataset_service_address: If set, will distribute the training dataset using\n the given tf.data service at the given address.\n\n Returns:\n A dataset_utils.Dataset() which includes a train_iter, a valid_iter,\n a test_iter, and a dict of meta_data.\n \"\"\"\n del rng\n dataset_configs = dataset_configs or {}\n data_augmentations = dataset_configs.get('data_augmentations', [])\n data_augmentations.append('cifar_default')\n for da in data_augmentations:\n if da not in ['mixup', 'cifar_default']:\n raise ValueError(f'Data augmentation type {da} is not yet supported in the CIFAR dataset.')\n dtype = getattr(tf, dtype_str)\n target_is_onehot = False\n preprocess_ex = functools.partial(preprocess_example, dtype=dtype)\n logging.info('Loading train split of the CIFAR10 dataset.')\n augment_ex = functools.partial(augment_example, dtype=dtype, data_augmentations=data_augmentations)\n (train_ds, train_ds_info) = dataset_utils.load_split_from_tfds('cifar10', batch_size, split='train', preprocess_example=preprocess_ex, augment_train_example=augment_ex, shuffle_seed=shuffle_seed)\n if dataset_service_address:\n if shuffle_seed is not None:\n raise ValueError('Using dataset service with a random seed causes each worker to produce exactly the same data. Add config.shuffle_seed = None to your config if you want to run with dataset service.')\n logging.info('Using the tf.data service at %s', dataset_service_address)\n train_ds = dataset_utils.distribute(train_ds, dataset_service_address)\n logging.info('Loading test split of the CIFAR10 dataset.')\n (eval_ds, _) = dataset_utils.load_split_from_tfds('cifar10', eval_batch_size, split='test', preprocess_example=preprocess_ex)\n maybe_pad_batches_train = functools.partial(dataset_utils.maybe_pad_batch, train=True, batch_size=batch_size)\n maybe_pad_batches_eval = functools.partial(dataset_utils.maybe_pad_batch, train=False, batch_size=eval_batch_size)\n num_classes = train_ds_info.features['label'].num_classes\n target_to_one_hot_batches = functools.partial(dataset_utils.target_to_one_hot, num_classes=num_classes)\n shard_batches = functools.partial(dataset_utils.shard, n_devices=num_shards)\n mixup_batches = functools.partial(dataset_utils.mixup, alpha=1.0)\n train_iter = iter(train_ds)\n train_iter = map(dataset_utils.tf_to_numpy, train_iter)\n train_iter = map(maybe_pad_batches_train, train_iter)\n if 'mixup' in data_augmentations:\n train_iter = map(target_to_one_hot_batches, train_iter)\n train_iter = map(mixup_batches, train_iter)\n target_is_onehot = True\n train_iter = map(shard_batches, train_iter)\n eval_iter = iter(eval_ds)\n eval_iter = map(dataset_utils.tf_to_numpy, eval_iter)\n eval_iter = map(maybe_pad_batches_eval, eval_iter)\n if target_is_onehot:\n eval_iter = map(target_to_one_hot_batches, eval_iter)\n eval_iter = map(shard_batches, eval_iter)\n input_shape = (-1, HEIGHT, WIDTH, NUM_CHANNELS)\n meta_data = {'num_classes': num_classes, 'input_shape': input_shape, 'num_train_examples': dataset_utils.get_num_examples('cifar10', 'train'), 'num_eval_examples': dataset_utils.get_num_examples('cifar10', 'test'), 'input_dtype': getattr(jnp, dtype_str), 'target_is_onehot': target_is_onehot}\n return dataset_utils.Dataset(train_iter, eval_iter, None, meta_data)","code_tokens":"","url":846014} +{"project_name":"yinyunie\/ScenePriors","file_name":"transformer_builders.py","full_name":"BaseTransformerBuilder.value_dimensions","func_name":"value_dimensions","docstring":"The dimensions of the values in each attention layer.","docstring_tokens":"","code":"@property\ndef value_dimensions(self):\n \"\"\"The dimensions of the values in each attention layer.\"\"\"\n return self._d_value","code_tokens":"","url":329528} +{"project_name":"AxeldeRomblay\/MLBox","file_name":"test_na_encoder.py","full_name":"test_transform_NA_encoder","func_name":"test_transform_NA_encoder","docstring":"Test transform method of NA_encoder class.","docstring_tokens":"","code":"def test_transform_NA_encoder():\n \"\"\"Test transform method of NA_encoder class.\"\"\"\n df = pd.read_csv('data_for_tests\/train.csv')\n encoder = NA_encoder()\n with pytest.raises(ValueError):\n encoder.transform(df)\n encoder.fit(df, df['Survived'])\n df_encoded = encoder.transform(df)\n assert (df.columns == df_encoded.columns).all()","code_tokens":"","url":630039} +{"project_name":"wenyudu\/Natural-Language-Processing-A-Machine-Learning-Perspective","file_name":"features.py","full_name":"FeatureMapper.sentence_sequences","func_name":"sentence_sequences","docstring":"Array of indices for words and tags.","docstring_tokens":"","code":"def sentence_sequences(self, sentence):\n \"\"\"\n Array of indices for words and tags.\n \"\"\"\n sentence = [(FeatureMapper.START, FeatureMapper.START)] + sentence + [(FeatureMapper.STOP, FeatureMapper.STOP)]\n words = [self.wdict[w] if w in self.wdict else self.wdict[FeatureMapper.UNK] for (w, t) in sentence]\n tags = [self.tdict[t] if t in self.tdict else self.tdict[FeatureMapper.UNK] for (w, t) in sentence]\n w = np.array(words).astype('int32')\n t = np.array(tags).astype('int32')\n return (w, t)","code_tokens":"","url":652191} +{"project_name":"rlworkgroup\/garage","file_name":"vpg_garage_pytorch.py","full_name":"vpg_garage_pytorch","func_name":"vpg_garage_pytorch","docstring":"Create garage PyTorch VPG model and training.","docstring_tokens":"","code":"@wrap_experiment\ndef vpg_garage_pytorch(ctxt, env_id, seed):\n \"\"\"Create garage PyTorch VPG model and training.\n\n Args:\n ctxt (garage.experiment.ExperimentContext): The experiment\n configuration used by Trainer to create the\n snapshotter.\n env_id (str): Environment id of the task.\n seed (int): Random positive integer for the trial.\n\n \"\"\"\n deterministic.set_seed(seed)\n trainer = Trainer(ctxt)\n env = normalize(GymEnv(env_id))\n policy = PyTorch_GMP(env.spec, hidden_sizes=hyper_parameters['hidden_sizes'], hidden_nonlinearity=torch.tanh, output_nonlinearity=None)\n value_function = GaussianMLPValueFunction(env_spec=env.spec, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, output_nonlinearity=None)\n policy_optimizer = OptimizerWrapper((torch.optim.Adam, dict(lr=0.00025)), policy, max_optimization_epochs=10, minibatch_size=64)\n vf_optimizer = OptimizerWrapper((torch.optim.Adam, dict(lr=0.00025)), value_function, max_optimization_epochs=10, minibatch_size=64)\n sampler = RaySampler(agents=policy, envs=env, max_episode_length=env.spec.max_episode_length)\n algo = PyTorch_VPG(env_spec=env.spec, policy=policy, value_function=value_function, sampler=sampler, policy_optimizer=policy_optimizer, vf_optimizer=vf_optimizer, discount=hyper_parameters['discount'], center_adv=hyper_parameters['center_adv'])\n trainer.setup(algo, env)\n trainer.train(n_epochs=hyper_parameters['n_epochs'], batch_size=hyper_parameters['batch_size'])","code_tokens":"","url":200102} +{"project_name":"deepmind\/pycolab","file_name":"story_test.py","full_name":"StoryTest.testStandIns","func_name":"testStandIns","docstring":"The \"abstraction breakers\" in `Story` are suitably simulated.","docstring_tokens":"","code":"def testStandIns(self):\n \"\"\"The \"abstraction breakers\" in `Story` are suitably simulated.\"\"\"\n arts = list(zip(['P~~', '..S'], ['~~~', '..D'], ['www', '###']))\n story = storytelling.Story([lambda : ascii_art.ascii_art_to_game(arts[0], what_lies_beneath='~', sprites={'P': self._DieRightward}, drapes={'w': self._IdleDrape}), lambda : ascii_art.ascii_art_to_game(arts[1], what_lies_beneath='.', sprites={'S': self._DieRightward}, drapes={'D': self._IdleDrape})])\n self.assertEqual(sorted(story.backdrop.palette), ['#', '.', '~'])\n self.assertEqual(sorted(story.things), ['D', 'P', 'S', 'w'])\n self.assertTrue(storytelling.is_fictional(story.things['D']))\n self.assertFalse(storytelling.is_fictional(story.things['P']))\n self.assertTrue(storytelling.is_fictional(story.things['S']))\n self.assertFalse(storytelling.is_fictional(story.things['w']))","code_tokens":"","url":819314} +{"project_name":"hamza-murad\/AALU","file_name":"discovery_v1.py","full_name":"Enrichment.from_dict","func_name":"from_dict","docstring":"Initialize a Enrichment object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'Enrichment':\n \"\"\"Initialize a Enrichment object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['description', 'destination_field', 'source_field', 'overwrite', 'enrichment', 'ignore_downstream_errors', 'options']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class Enrichment: ' + ', '.join(bad_keys))\n if 'description' in _dict:\n args['description'] = _dict.get('description')\n if 'destination_field' in _dict:\n args['destination_field'] = _dict.get('destination_field')\n else:\n raise ValueError(\"Required property 'destination_field' not present in Enrichment JSON\")\n if 'source_field' in _dict:\n args['source_field'] = _dict.get('source_field')\n else:\n raise ValueError(\"Required property 'source_field' not present in Enrichment JSON\")\n if 'overwrite' in _dict:\n args['overwrite'] = _dict.get('overwrite')\n if 'enrichment' in _dict:\n args['enrichment'] = _dict.get('enrichment')\n else:\n raise ValueError(\"Required property 'enrichment' not present in Enrichment JSON\")\n if 'ignore_downstream_errors' in _dict:\n args['ignore_downstream_errors'] = _dict.get('ignore_downstream_errors')\n if 'options' in _dict:\n args['options'] = EnrichmentOptions._from_dict(_dict.get('options'))\n return cls(**args)","code_tokens":"","url":5558} +{"project_name":"santhoshkolloju\/Abstractive-Summarization-With-Transfer-","file_name":"preprocess.py","full_name":"read_file","func_name":"read_file","docstring":"a generator to generate each line of file.","docstring_tokens":"","code":"def read_file(path, tok=False):\n \"\"\"a generator to generate each line of file.\"\"\"\n with open_file(path) as f:\n for line in f.readlines():\n words = split_sentence(line.strip(), tok)\n yield words","code_tokens":"","url":405920} +{"project_name":"materialsvirtuallab\/mlearn","file_name":"models.py","full_name":"LinearModel.predict","func_name":"predict","docstring":"Predict outputs with fitted model.","docstring_tokens":"","code":"def predict(self, inputs, override=False):\n \"\"\"\n Predict outputs with fitted model.\n\n Args:\n inputs (list\/Array): List\/Array of input testing objects.\n override (bool): Whether to calculate the feature\n vectors from given inputs. Default to False. Set to True\n if you want to test the model with a different set of\n testing inputs.\n\n Returns:\n Predicted output array from inputs.\n \"\"\"\n if self._xtest is None or override:\n xtest = self.describer.describe_all(inputs)\n else:\n warnings.warn('Feature vectors retrieved from cache and input testing objects ignored. To override the old cache with feature vectors of new testing objects, set override=True.')\n xtest = self._xtest\n self._xtest = xtest\n return self.model.predict(xtest)","code_tokens":"","url":630281} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"_minimize.py","full_name":"standardize_constraints","func_name":"standardize_constraints","docstring":"Converts constraints to the form required by the solver.","docstring_tokens":"","code":"def standardize_constraints(constraints, x0, meth):\n \"\"\"Converts constraints to the form required by the solver.\"\"\"\n all_constraint_types = (NonlinearConstraint, LinearConstraint, dict)\n new_constraint_types = all_constraint_types[:-1]\n if isinstance(constraints, all_constraint_types):\n constraints = [constraints]\n constraints = list(constraints)\n if meth == 'trust-constr':\n for (i, con) in enumerate(constraints):\n if not isinstance(con, new_constraint_types):\n constraints[i] = old_constraint_to_new(i, con)\n else:\n for (i, con) in enumerate(list(constraints)):\n if isinstance(con, new_constraint_types):\n old_constraints = new_constraint_to_old(con, x0)\n constraints[i] = old_constraints[0]\n constraints.extend(old_constraints[1:])\n return constraints","code_tokens":"","url":99747} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"pathlib.py","full_name":"Path.rglob","func_name":"rglob","docstring":"Recursively yield all existing files (of any kind, including directories) matching the given pattern, anywhere in this subtree.","docstring_tokens":"","code":"def rglob(self, pattern):\n \"\"\"Recursively yield all existing files (of any kind, including\n directories) matching the given pattern, anywhere in this subtree.\n \"\"\"\n pattern = self._flavour.casefold(pattern)\n (drv, root, pattern_parts) = self._flavour.parse_parts((pattern,))\n if drv or root:\n raise NotImplementedError('Non-relative patterns are unsupported')\n selector = _make_selector(('**',) + tuple(pattern_parts))\n for p in selector.select_from(self):\n yield p","code_tokens":"","url":429070} +{"project_name":"irdanish11\/Seq2Seq-UrduChatBot","file_name":"chatbot_model.py","full_name":"ChatbotModel.validate_batch","func_name":"validate_batch","docstring":"Evaluate the metric on one batch and return.","docstring_tokens":"","code":"def validate_batch(self, inputs, targets, input_sequence_length, target_sequence_length, metric='loss'):\n \"\"\"Evaluate the metric on one batch and return.\n\n Args:\n inputs: The input matrix of shape (batch_size, sequence_length)\n where each value in the sequences are words encoded as integer indexes of the input vocabulary.\n \n targets: The target matrix of shape (batch_size, sequence_length)\n where each value in the sequences are words encoded as integer indexes of the output vocabulary.\n\n input_sequence_length: A vector of sequence lengths of shape (batch_size)\n containing the lengths of every input sequence in the batch. This allows for dynamic sequence lengths.\n\n target_sequence_length: A vector of sequence lengths of shape (batch_size)\n containing the lengths of every target sequence in the batch. This allows for dynamic sequence lengths.\n\n metric: The desired validation metric. Currently only \"loss\" is supported. This will eventually support\n \"accuracy\", \"bleu\", and other common validation metrics.\n \"\"\"\n if self.mode != tf.contrib.learn.ModeKeys.TRAIN:\n raise ValueError('validate_batch can only be called when the model is initialized in train mode.')\n if metric == 'loss':\n metric_op = self.loss\n else:\n raise ValueError(\"Unsupported validation metric: '{0}'\".format(metric))\n metric_value = self.session.run(metric_op, {self.inputs: inputs, self.targets: targets, self.input_sequence_length: input_sequence_length, self.target_sequence_length: target_sequence_length, self.keep_prob: 1})\n return metric_value","code_tokens":"","url":876457} +{"project_name":"pipermerriam\/flex","file_name":"parameter.py","full_name":"construct_parameter_validators","func_name":"construct_parameter_validators","docstring":"Constructs a dictionary of validator functions for the provided parameter definition.","docstring_tokens":"","code":"def construct_parameter_validators(parameter, context):\n \"\"\"\n Constructs a dictionary of validator functions for the provided parameter\n definition.\n \"\"\"\n validators = ValidationDict()\n if '$ref' in parameter:\n validators.add_validator('$ref', ParameterReferenceValidator(parameter['$ref'], context))\n for key in parameter:\n if key in validator_mapping:\n validators.add_validator(key, validator_mapping[key](context=context, **parameter))\n if 'schema' in parameter:\n schema_validators = construct_schema_validators(parameter['schema'], context=context)\n for (key, value) in schema_validators.items():\n validators.setdefault(key, value)\n return validators","code_tokens":"","url":211317} +{"project_name":"Katja-M\/Python_NaturalLanguageProcessing","file_name":"versioncontrol.py","full_name":"VersionControl.compare_urls","func_name":"compare_urls","docstring":"Compare two repo URLs for identity, ignoring incidental differences.","docstring_tokens":"","code":"@classmethod\ndef compare_urls(cls, url1, url2):\n \"\"\"\n Compare two repo URLs for identity, ignoring incidental differences.\n \"\"\"\n return cls.normalize_url(url1) == cls.normalize_url(url2)","code_tokens":"","url":868329} +{"project_name":"rlworkgroup\/garage","file_name":"test_maml.py","full_name":"TestMAML.test_get_exploration_policy","func_name":"test_get_exploration_policy","docstring":"Test if an independent copy of policy is returned.","docstring_tokens":"","code":"def test_get_exploration_policy(self):\n \"\"\"Test if an independent copy of policy is returned.\"\"\"\n self.policy.apply(partial(self._set_params, 0.1))\n adapt_policy = self.algo.get_exploration_policy()\n adapt_policy.apply(partial(self._set_params, 0.2))\n self.policy.apply(partial(self._test_params, 0.1))\n adapt_policy.apply(partial(self._test_params, 0.2))","code_tokens":"","url":200981} +{"project_name":"kakaobrain\/pororo","file_name":"audio.py","full_name":"ms_to_frames","func_name":"ms_to_frames","docstring":"Convert milliseconds into number of frames.","docstring_tokens":"","code":"def ms_to_frames(ms):\n \"\"\"Convert milliseconds into number of frames.\"\"\"\n return int(hp.sample_rate * ms \/ 1000)","code_tokens":"","url":782482} +{"project_name":"interpretml\/DiCE","file_name":"dice_tensorflow1.py","full_name":"DiceTensorFlow1.do_cf_initializations","func_name":"do_cf_initializations","docstring":"Intializes TF variables required for CF generation.","docstring_tokens":"","code":"def do_cf_initializations(self, total_CFs, algorithm, features_to_vary):\n \"\"\"Intializes TF variables required for CF generation.\"\"\"\n self.cf_init_weights = [total_CFs, algorithm, features_to_vary]\n if algorithm == 'RandomInitCF':\n self.total_random_inits = total_CFs\n self.total_CFs = 1\n else:\n self.total_random_inits = 0\n self.total_CFs = total_CFs\n self.x1 = tf.placeholder(tf.float32, shape=(1, self.minx.shape[1]))\n self.target_cf = tf.placeholder(tf.float32, (1, 1))\n self.learning_rate = tf.placeholder(tf.float32, ())\n self.cfs = []\n self.cf_init = tf.placeholder(tf.float32, shape=(1, self.minx.shape[1]))\n self.cf_assign = []\n for i in range(self.total_CFs):\n self.cfs.append(tf.Variable(self.minx, dtype=tf.float32))\n self.cf_assign.append(tf.assign(self.cfs[i], self.cf_init))\n self.feat_to_vary_idxs = self.data_interface.get_indexes_of_features_to_vary(features_to_vary=features_to_vary)\n frozen_dims = np.array([[1.0 if ix in self.feat_to_vary_idxs else 0.0 for ix in range(self.minx.shape[1])]])\n self.cfs_frozen = []\n for i in range(self.total_CFs):\n frozen = tf.multiply(self.cfs[i], tf.constant(frozen_dims, dtype=tf.float32))\n self.cfs_frozen.append(frozen + tf.stop_gradient(-frozen + self.cfs[i]))\n self.optimizers_options = {'tensorflow': self.tensorflow_optimizers, 'scipy': self.scipy_optimizers}","code_tokens":"","url":550237} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"ioloop_test.py","full_name":"TestIOLoop.test_exception_logging_future","func_name":"test_exception_logging_future","docstring":"The IOLoop examines exceptions from Futures and logs them.","docstring_tokens":"","code":"def test_exception_logging_future(self):\n \"\"\"The IOLoop examines exceptions from Futures and logs them.\"\"\"\n\n @gen.coroutine\n def callback():\n self.io_loop.add_callback(self.stop)\n 1 \/ 0\n self.io_loop.add_callback(callback)\n with ExpectLog(app_log, 'Exception in callback'):\n self.wait()","code_tokens":"","url":21544} +{"project_name":"meidachen\/STPLS3D","file_name":"cindex.py","full_name":"Type.get_align","func_name":"get_align","docstring":"Retrieve the alignment of the record.","docstring_tokens":"","code":"def get_align(self):\n \"\"\"\n Retrieve the alignment of the record.\n \"\"\"\n return conf.lib.clang_Type_getAlignOf(self)","code_tokens":"","url":909190} +{"project_name":"aws\/sagemaker-python-sdk","file_name":"modifier.py","full_name":"Modifier.node_should_be_modified","func_name":"node_should_be_modified","docstring":"Check if an AST node should be modified.","docstring_tokens":"","code":"@abstractmethod\ndef node_should_be_modified(self, node):\n \"\"\"Check if an AST node should be modified.\"\"\"","code_tokens":"","url":829845} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.dof_solimp","func_name":"dof_solimp","docstring":"constraint solver impedance:frictionloss (nv x mjNIMP).","docstring_tokens":"","code":"@util.CachedProperty\ndef dof_solimp(self):\n \"\"\"constraint solver impedance:frictionloss (nv x mjNIMP).\"\"\"\n return util.buf_to_npy(self._ptr.contents.dof_solimp, (self.nv, 5))","code_tokens":"","url":440276} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"ltisys.py","full_name":"ZerosPolesGain.gain","func_name":"gain","docstring":"Gain of the `ZerosPolesGain` system.","docstring_tokens":"","code":"@property\ndef gain(self):\n \"\"\"Gain of the `ZerosPolesGain` system.\"\"\"\n return self._gain","code_tokens":"","url":370889} +{"project_name":"SforAiDl\/genrl","file_name":"offpolicy.py","full_name":"OffPolicyTrainer.get_action","func_name":"get_action","docstring":"Gets the action to be performed on the environment For the first few timesteps (Warmup steps) it selects an action randomly to introduce stochasticity to the environment start position.","docstring_tokens":"","code":"def get_action(self, state: np.ndarray, timestep: int) -> np.ndarray:\n \"\"\"Gets the action to be performed on the environment\n\n For the first few timesteps (Warmup steps) it selects an action randomly to introduce\n stochasticity to the environment start position.\n\n Args:\n state (:obj:`np.ndarray`): Current state of the environment\n timestep (int): Current timestep of training\n\n Returns:\n action (:obj:`np.ndarray`): Action to be taken on the env\n \"\"\"\n if timestep < self.warmup_steps:\n action = self.env.sample()\n else:\n action = self.agent.select_action(state)\n return action","code_tokens":"","url":557033} +{"project_name":"voxel51\/fiftyone","file_name":"exporters.py","full_name":"build_dataset_exporter","func_name":"build_dataset_exporter","docstring":"Builds the :class:`DatasetExporter` instance for the given parameters.","docstring_tokens":"","code":"def build_dataset_exporter(dataset_type, strip_none=True, warn_unused=True, **kwargs):\n \"\"\"Builds the :class:`DatasetExporter` instance for the given parameters.\n\n Args:\n dataset_type: the :class:`fiftyone.types.Dataset` type\n strip_none (True): whether to exclude None-valued items from ``kwargs``\n warn_unused (True): whether to issue warnings for any non-None unused\n parameters encountered\n **kwargs: keyword arguments to pass to the dataset exporter's\n constructor via ``DatasetExporter(**kwargs)``\n\n Returns:\n a tuple of:\n\n - the :class:`DatasetExporter` instance\n - a dict of unused keyword arguments\n \"\"\"\n if dataset_type is None:\n raise ValueError('You must provide a `dataset_type` in order to build a dataset exporter')\n if inspect.isclass(dataset_type):\n dataset_type = dataset_type()\n dataset_exporter_cls = dataset_type.get_dataset_exporter_cls()\n if strip_none:\n kwargs = {k: v for (k, v) in kwargs.items() if v is not None}\n (kwargs, unused_kwargs) = fou.extract_kwargs_for_class(dataset_exporter_cls, kwargs)\n try:\n dataset_exporter = dataset_exporter_cls(**kwargs)\n except Exception as e:\n raise ValueError('Failed to construct exporter of type %s using the provided parameters. See above for the error. You may need to supply additional mandatory arguments. Please consult the documentation of %s to learn more' % (dataset_exporter_cls, dataset_exporter_cls)) from e\n if warn_unused:\n for (key, value) in unused_kwargs.items():\n if value is not None:\n logger.warning(\"Ignoring unsupported parameter '%s' for exporter type %s\", key, dataset_exporter_cls)\n return (dataset_exporter, unused_kwargs)","code_tokens":"","url":584253} +{"project_name":"chenbinghui1\/DSL","file_name":"test_assigner.py","full_name":"test_max_iou_assigner_with_empty_gt","func_name":"test_max_iou_assigner_with_empty_gt","docstring":"Test corner case where an image might have no true detections.","docstring_tokens":"","code":"def test_max_iou_assigner_with_empty_gt():\n \"\"\"Test corner case where an image might have no true detections.\"\"\"\n self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)\n bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [5, 5, 15, 15], [32, 32, 38, 42]])\n gt_bboxes = torch.empty(0, 4)\n assign_result = self.assign(bboxes, gt_bboxes)\n expected_gt_inds = torch.LongTensor([0, 0, 0, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)","code_tokens":"","url":168032} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"maxContextCalc.py","full_name":"maxCtxFont","func_name":"maxCtxFont","docstring":"Calculate the usMaxContext value for an entire font.","docstring_tokens":"","code":"def maxCtxFont(font):\n \"\"\"Calculate the usMaxContext value for an entire font.\"\"\"\n maxCtx = 0\n for tag in ('GSUB', 'GPOS'):\n if tag not in font:\n continue\n table = font[tag].table\n if not table.LookupList:\n continue\n for lookup in table.LookupList.Lookup:\n for st in lookup.SubTable:\n maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st)\n return maxCtx","code_tokens":"","url":361098} +{"project_name":"triaquae\/triaquae","file_name":"test_ds.py","full_name":"DataSourceTest.test03c_layer_references","func_name":"test03c_layer_references","docstring":"Ensure OGR objects keep references to the objects they belong to.","docstring_tokens":"","code":"def test03c_layer_references(self):\n \"\"\"\n Ensure OGR objects keep references to the objects they belong to.\n \"\"\"\n source = ds_list[0]\n\n def get_layer():\n ds = DataSource(source.ds)\n return ds[0]\n lyr = get_layer()\n self.assertEqual(source.nfeat, len(lyr))\n self.assertEqual(source.gtype, lyr.geom_type.num)\n self.assertEqual(str(lyr[0]['str']), '1')","code_tokens":"","url":357693} +{"project_name":"google-research\/tensor2robot","file_name":"image_transformations_test.py","full_name":"ImageTransformationsTest.testWrongRandomCropImages","func_name":"testWrongRandomCropImages","docstring":"Tests that all ValueErrors are triggered for RandomCropImages.","docstring_tokens":"","code":"def testWrongRandomCropImages(self):\n \"\"\"Tests that all ValueErrors are triggered for RandomCropImages.\"\"\"\n with tf.Graph().as_default():\n input_shape = [32, 32, 3]\n batch_size = 4\n images = self._CreateRampTestImages(batch_size, input_shape[0], input_shape[1])\n with self.assertRaises(ValueError):\n image_transformations.RandomCropImages([images], [32, 32], [20, 64])\n with self.assertRaises(ValueError):\n image_transformations.RandomCropImages([images], [32, 32, 3, 4], [20, 64])\n with self.assertRaises(ValueError):\n image_transformations.RandomCropImages([images], [32, 32, 3], [20])\n with self.assertRaises(ValueError):\n image_transformations.RandomCropImages([images], [32, 32, 3], [20, 32, 64])","code_tokens":"","url":908325} +{"project_name":"nosmokingbandit\/watcher","file_name":"torrent.py","full_name":"Torrent.ratio","func_name":"ratio","docstring":"Get the upload\/download ratio.","docstring_tokens":"","code":"@property\ndef ratio(self):\n \"\"\"Get the upload\/download ratio.\"\"\"\n return float(self._fields['uploadRatio'].value)","code_tokens":"","url":381986} +{"project_name":"oskopek\/mvae","file_name":"ars.py","full_name":"ARS.recalculate_hull","func_name":"recalculate_hull","docstring":"Recalculate hull from existing x, h, hprime.","docstring_tokens":"","code":"def recalculate_hull(self, nbnew: int=0, xnew: Optional[Tensor]=None, hnew: Optional[Tensor]=None, hprimenew: Optional[Tensor]=None) -> None:\n \"\"\"Recalculate hull from existing x, h, hprime.\"\"\"\n if xnew is not None:\n self.x[:, self.K:self.K + nbnew] = xnew\n (self.x, idx) = self.x.sort()\n self.h[:, self.K:self.K + nbnew] = hnew\n self.h = self.h.gather(1, idx)\n self.hprime[:, self.K:self.K + nbnew] = hprimenew\n self.hprime = self.hprime.gather(1, idx)\n self.K += xnew.size(-1)\n self.z = torch.zeros(self.B, self.K + 1).to(self.device)\n self.z[:, 0] = self.lb\n self.z[:, self.K] = self.ub\n self.z[:, 1:self.K] = (diff(self.h[:, :self.K]) - diff(self.x[:, :self.K] * self.hprime[:, :self.K])) \/ -diff(self.hprime[:, :self.K])\n idx = [0] + list(range(self.K))\n self.u = self.h[:, idx] + self.hprime[:, idx] * (self.z - self.x[:, idx])\n exp_u = torch.exp(self.u)\n self.s = diff(exp_u) \/ self.hprime[:, :self.K]\n self.s[self.hprime[:, :self.K] == 0.0] = 0.0\n assert torch.isfinite(self.s).all()\n self.cs = torch.cat((torch.zeros(self.B, 1).to(self.device), torch.cumsum(self.s, dim=-1)), dim=-1)\n self.cu = self.cs[:, -1]\n assert torch.isfinite(self.cu).all()","code_tokens":"","url":651267} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"grammatical_evolution.py","full_name":"GrammaticalEvolution.set_crossover_rate","func_name":"set_crossover_rate","docstring":"This function sets the probablity that will be applied to members selected into the fitness pool.","docstring_tokens":"","code":"def set_crossover_rate(self, crossover_rate):\n \"\"\"\n This function sets the probablity that will be\n applied to members selected into the fitness pool.\n\n \"\"\"\n errmsg = 'The crossover rate, %s must be a float value\\n from 0.0 to 1.0' % crossover_rate\n if not isinstance(crossover_rate, float):\n raise ValueError(errmsg)\n if not 0.0 <= crossover_rate <= 1.0:\n raise ValueError(errmsg)\n self._crossover_rate = crossover_rate","code_tokens":"","url":722921} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"text_classification.py","full_name":"rnn_model","func_name":"rnn_model","docstring":"RNN model to predict from sequence of words to a class.","docstring_tokens":"","code":"def rnn_model(features, labels, mode):\n \"\"\"RNN model to predict from sequence of words to a class.\"\"\"\n word_vectors = tf.contrib.layers.embed_sequence(features[WORDS_FEATURE], vocab_size=n_words, embed_dim=EMBEDDING_SIZE)\n word_list = tf.unstack(word_vectors, axis=1)\n cell = tf.contrib.rnn.GRUCell(EMBEDDING_SIZE)\n (_, encoding) = tf.contrib.rnn.static_rnn(cell, word_list, dtype=tf.float32)\n logits = tf.layers.dense(encoding, MAX_LABEL, activation=None)\n return estimator_spec_for_softmax_classification(logits=logits, labels=labels, mode=mode)","code_tokens":"","url":604884} +{"project_name":"benanne\/morb","file_name":"factors.py","full_name":"Factor.factor_product","func_name":"factor_product","docstring":"The factor product needed to compute the activation of the other units tied by Parameters params.","docstring_tokens":"","code":"def factor_product(self, params, vmap):\n \"\"\"\n The factor product needed to compute the activation of the other units\n tied by Parameters params.\n \"\"\"\n fp_params_list = list(self.params_list)\n fp_params_list.remove(params)\n activations = [fp_params.terms[self](vmap) for fp_params in fp_params_list]\n return reduce(mul, activations)","code_tokens":"","url":241164} +{"project_name":"cvjena\/PartDetectorDisovery","file_name":"visualize.py","full_name":"draw_net_to_file","func_name":"draw_net_to_file","docstring":"Draws a decaf net, and saves it to file using the format given as the file extension.","docstring_tokens":"","code":"def draw_net_to_file(decaf_net, filename):\n \"\"\"Draws a decaf net, and saves it to file using the format given as the\n file extension.\n \"\"\"\n ext = os.path.splitext(filename)[-1][1:]\n with open(filename, 'w') as fid:\n fid.write(draw_net(decaf_net, ext))","code_tokens":"","url":278436} +{"project_name":"google-research\/rigl","file_name":"dataset_base_test.py","full_name":"DummyDatasetTest.test_create_dataset","func_name":"test_create_dataset","docstring":"Tests creation of dataset.","docstring_tokens":"","code":"def test_create_dataset(self):\n \"\"\"Tests creation of dataset.\"\"\"\n self.assertIsInstance(self._dataset, DummyDataset)","code_tokens":"","url":841421} +{"project_name":"deepmind\/grid-cells","file_name":"scores.py","full_name":"GridScorer.get_grid_scores_for_mask","func_name":"get_grid_scores_for_mask","docstring":"Calculate Pearson correlations of area inside mask at corr_angles.","docstring_tokens":"","code":"def get_grid_scores_for_mask(self, sac, rotated_sacs, mask):\n \"\"\"Calculate Pearson correlations of area inside mask at corr_angles.\"\"\"\n masked_sac = sac * mask\n ring_area = np.sum(mask)\n masked_sac_mean = np.sum(masked_sac) \/ ring_area\n masked_sac_centered = (masked_sac - masked_sac_mean) * mask\n variance = np.sum(masked_sac_centered ** 2) \/ ring_area + 1e-05\n corrs = dict()\n for (angle, rotated_sac) in zip(self._corr_angles, rotated_sacs):\n masked_rotated_sac = (rotated_sac - masked_sac_mean) * mask\n cross_prod = np.sum(masked_sac_centered * masked_rotated_sac) \/ ring_area\n corrs[angle] = cross_prod \/ variance\n return (self.grid_score_60(corrs), self.grid_score_90(corrs), variance)","code_tokens":"","url":233997} +{"project_name":"AirbusCyber\/grap","file_name":"CryptoIdentificationWidget.py","full_name":"CryptoIdentificationWidget.populateSignatureTree","func_name":"populateSignatureTree","docstring":"populate the TreeWidget for display of the signature scanning results.","docstring_tokens":"","code":"def populateSignatureTree(self):\n \"\"\"\n populate the TreeWidget for display of the signature scanning results.\n \"\"\"\n self.signature_tree.clear()\n self.signature_tree.setSortingEnabled(True)\n self.qtreewidgetitems_to_addresses = dict()\n shown_patterns = set()\n for ana in self.cc.CryptoIdentifier.get_analyzed_patterns():\n tree_matches = ana._patterns._matches\n found_patterns = ana.get_found_patterns()\n algo = ana.get_algo()\n patterns = ana.get_patterns()\n colors = self.cc.CryptoColor.get_patterns_colors()\n if len(found_patterns) > 0:\n if patterns._perform_analysis:\n algo_info = self.cc.QTreeWidgetItem(self.signature_tree)\n algo_info.setText(0, algo.get_name())\n patterns_info = self.cc.QTreeWidgetItem(algo_info)\n else:\n patterns_info = self.cc.QTreeWidgetItem(self.signature_tree)\n pattern_name = patterns.get_name()\n txt = '%s (%d matches)' % (pattern_name, len(found_patterns))\n patterns_info.setText(0, txt)\n shown_patterns.add(pattern_name)\n for match_dict_list in found_patterns:\n if patterns._perform_analysis:\n matches_info = self.cc.QTreeWidgetItem(patterns_info)\n for (pattern_id, match_dicts) in match_dict_list.items():\n if patterns._perform_analysis:\n pattern_info = self.cc.QTreeWidgetItem(matches_info)\n pattern_info.setText(0, '%s (%d matches)' % (patterns.get_pattern_name(pattern_id), len(match_dicts.values())))\n if pattern_id in colors:\n pattern_info.setForeground(0, self.cc.QBrush(self.cc.QColor(colors[pattern_id])))\n for match in iter(match_dicts.values()):\n if match.get_start_address() is not None:\n if patterns._perform_analysis:\n match_info = self.cc.QTreeWidgetItem(pattern_info)\n match_info.setText(0, '0x%x (%d instructions)' % (match.get_start_address(), match.get_num_insts()))\n else:\n match_info = self.cc.QTreeWidgetItem(patterns_info)\n if pattern_id in colors and (not patterns._perform_analysis):\n patterns_info.setForeground(0, self.cc.QBrush(self.cc.QColor(colors[pattern_id])))\n if patterns._perform_analysis:\n matches_info.setText(0, '%s' % idc.GetFunctionName(match.get_start_address()))\n else:\n try:\n func_name = idc.get_func_name(match.get_start_address())\n except:\n func_name = idc.GetFunctionName(match.get_start_address())\n match_info.setText(0, '0x%x in %s (%d instructions)' % (match.get_start_address(), func_name, match.get_num_insts()))\n match_info.setData(1, 0, True)\n match_info.setData(2, 0, hex(match.get_start_address()))\n self.signature_tree.expandItem(match_info)\n else:\n match_info = self.cc.QTreeWidgetItem(patterns_info)\n match_info.setText(0, 'One pattern matched with no extracted node (no getid option)')\n self.signature_tree.collapseItem(match_info)\n if patterns._perform_analysis:\n self.signature_tree.expandItem(pattern_info)\n if patterns._perform_analysis:\n self.signature_tree.expandItem(matches_info)\n if len(found_patterns) <= 5:\n self.signature_tree.expandItem(patterns_info)\n if patterns._perform_analysis:\n self.signature_tree.expandItem(algo_info)\n self.signature_tree.sortByColumn(0, 0)\n if self.show_all:\n for pattern_name in self.cc.CryptoIdentifier.pattern_to_path:\n if pattern_name not in shown_patterns:\n patterns_info = self.cc.QTreeWidgetItem(self.signature_tree)\n txt = '%s (unmatched)' % pattern_name\n patterns_info.setText(0, txt)","code_tokens":"","url":202777} +{"project_name":"kornia\/kornia","file_name":"homography.py","full_name":"symmetric_transfer_error","func_name":"symmetric_transfer_error","docstring":"Return Symmetric transfer error for correspondences given the homography matrix.","docstring_tokens":"","code":"def symmetric_transfer_error(pts1: Tensor, pts2: Tensor, H: Tensor, squared: bool=True, eps: float=1e-08) -> Tensor:\n \"\"\"Return Symmetric transfer error for correspondences given the homography matrix.\n\n Args:\n pts1: correspondences from the left images with shape\n (B, N, 2 or 3). If they are homogeneous, converted automatically.\n pts2: correspondences from the right images with shape\n (B, N, 2 or 3). If they are homogeneous, converted automatically.\n H: Homographies with shape :math:`(B, 3, 3)`.\n squared: if True (default), the squared distance is returned.\n eps: Small constant for safe sqrt.\n\n Returns:\n the computed distance with shape :math:`(B, N)`.\n \"\"\"\n KORNIA_CHECK_SHAPE(H, ['B', '3', '3'])\n if pts1.size(-1) == 3:\n pts1 = convert_points_from_homogeneous(pts1)\n if pts2.size(-1) == 3:\n pts2 = convert_points_from_homogeneous(pts2)\n max_num = torch.finfo(pts1.dtype).max\n (H_inv, good_H) = safe_inverse_with_mask(H)\n there: Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)\n back: Tensor = oneway_transfer_error(pts2, pts1, H_inv, True, eps)\n good_H_reshape: Tensor = good_H.view(-1, 1).expand_as(there)\n out = (there + back) * good_H_reshape.to(there.dtype) + max_num * (~good_H_reshape).to(there.dtype)\n if squared:\n return out\n return (out + eps).sqrt()","code_tokens":"","url":621908} +{"project_name":"nilearn\/nilearn","file_name":"test_img_plotting.py","full_name":"test_plotting_functions_with_display_mode_tiled","func_name":"test_plotting_functions_with_display_mode_tiled","docstring":"Smoke test for plotting functions with tiled display mode.","docstring_tokens":"","code":"@pytest.mark.parametrize('plot_func', [plot_stat_map, plot_anat, plot_img])\ndef test_plotting_functions_with_display_mode_tiled(plot_func, img_3d_mni):\n \"\"\"Smoke test for plotting functions with tiled display mode.\"\"\"\n if plot_func == plot_anat:\n plot_func(display_mode='tiled')\n else:\n plot_func(img_3d_mni, display_mode='tiled')\n plt.close()","code_tokens":"","url":724147} +{"project_name":"SvenGronauer\/phoenix-drone-simulation","file_name":"control.py","full_name":"Attitude.reset","func_name":"reset","docstring":"Resets the internal variables of the PIDs.","docstring_tokens":"","code":"def reset(self):\n \"\"\"Resets the internal variables of the PIDs. \"\"\"\n super().reset()\n self.attitude_rate_controller.reset()\n self.integral = np.zeros(3)\n self.last_error = np.zeros(3)","code_tokens":"","url":769137} +{"project_name":"Dsajeet\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"nb_007a.py","full_name":"TextDataset.from_csv","func_name":"from_csv","docstring":"Creates a dataset from texts in a csv file.","docstring_tokens":"","code":"@classmethod\ndef from_csv(cls, folder: PathOrStr, tokenizer: Tokenizer, name: str, **kwargs) -> 'TextDataset':\n \"\"\"Creates a dataset from texts in a csv file.\"\"\"\n orig = [Path(folder) \/ f'{name}.csv']\n dest = [Path(folder) \/ 'tmp' \/ f'{name}.csv']\n maybe_copy(orig, dest)\n return cls(folder, tokenizer, name=name, **kwargs)","code_tokens":"","url":32345} +{"project_name":"flavioschneider\/rl-transfer-","file_name":"context_conditioned_policy.py","full_name":"ContextConditionedPolicy.forward","func_name":"forward","docstring":"Given observations and context, get actions and probs from policy.","docstring_tokens":"","code":"def forward(self, obs, context):\n \"\"\"Given observations and context, get actions and probs from policy.\n\n Args:\n obs (torch.Tensor): Observation values, with shape\n :math:`(X, N, O)`. X is the number of tasks. N is batch size. O\n is the size of the flattened observation space.\n context (torch.Tensor): Context values, with shape\n :math:`(X, N, C)`. X is the number of tasks. N is batch size. C\n is the combined size of observation, action, reward, and next\n observation if next observation is used in context. Otherwise,\n C is the combined size of observation, action, and reward.\n\n Returns:\n tuple:\n * torch.Tensor: Predicted action values.\n * np.ndarray: Mean of distribution.\n * np.ndarray: Log std of distribution.\n * torch.Tensor: Log likelihood of distribution.\n * torch.Tensor: Sampled values from distribution before\n applying tanh transformation.\n torch.Tensor: z values, with shape :math:`(N, L)`. N is batch size.\n L is the latent dimension.\n\n \"\"\"\n self.infer_posterior(context)\n self.sample_from_belief()\n task_z = self.z\n (t, b, _) = obs.size()\n obs = obs.view(t * b, -1)\n task_z = [z.repeat(b, 1) for z in task_z]\n task_z = torch.cat(task_z, dim=0)\n obs_z = torch.cat([obs, task_z.detach()], dim=1)\n dist = self._policy(obs_z)[0]\n (pre_tanh, actions) = dist.rsample_with_pre_tanh_value()\n log_pi = dist.log_prob(value=actions, pre_tanh_value=pre_tanh)\n log_pi = log_pi.unsqueeze(1)\n mean = dist.mean.to('cpu').detach().numpy()\n log_std = (dist.variance ** 0.5).log().to('cpu').detach().numpy()\n return ((actions, mean, log_std, log_pi, pre_tanh), task_z)","code_tokens":"","url":861624} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"fitness.py","full_name":"FitnessList.stddev","func_name":"stddev","docstring":"This function returns the standard deviation of fitness values.","docstring_tokens":"","code":"def stddev(self):\n \"\"\"\n This function returns the standard deviation of fitness values.\n\n \"\"\"\n total = 0.0\n mean = self.mean()\n for item in self:\n total += pow(item[0] - mean, 2.0)\n return pow(total \/ (float(len(self)) - 1.0), 0.5)","code_tokens":"","url":722871} +{"project_name":"Djaizz\/Djaizz","file_name":"base.py","full_name":"_AIModelWithArtifactFilesABC.load","func_name":"load","docstring":"Load the Model's native object from its artifact file(s).","docstring_tokens":"","code":"@abstractmethod\ndef load(self) -> None:\n \"\"\"Load the Model's native object from its artifact file(s).\"\"\"\n raise NotImplementedError","code_tokens":"","url":189448} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"gen_nn_ops.py","full_name":"softplus_grad","func_name":"softplus_grad","docstring":"Computes softplus gradients for a softplus operation.","docstring_tokens":"","code":"def softplus_grad(gradients, features, name=None):\n \"\"\"Computes softplus gradients for a softplus operation.\n\n Args:\n gradients: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`.\n The backpropagated gradients to the corresponding softplus operation.\n features: A `Tensor`. Must have the same type as `gradients`.\n The features passed as input to the corresponding softplus operation.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `gradients`.\n \"\"\"\n _ctx = _context._context\n if _ctx is None or not _ctx._eager_context.is_eager:\n (_, _, _op) = _op_def_lib._apply_op_helper('SoftplusGrad', gradients=gradients, features=features, name=name)\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = ('T', _op.get_attr('T'))\n _execute.record_gradient('SoftplusGrad', _inputs_flat, _attrs, _result, name)\n (_result,) = _result\n return _result\n else:\n try:\n _result = _pywrap_tensorflow.TFE_Py_FastPathExecute(_ctx._context_handle, _ctx._eager_context.device_name, 'SoftplusGrad', name, _ctx._post_execution_callbacks, gradients, features)\n return _result\n except _core._FallbackException:\n return softplus_grad_eager_fallback(gradients, features, name=name, ctx=_ctx)\n except _core._NotOkStatusException as e:\n if name is not None:\n message = e.message + ' name: ' + name\n else:\n message = e.message\n _six.raise_from(_core._status_to_exception(e.code, message), None)","code_tokens":"","url":338431} +{"project_name":"janluke\/cs188","file_name":"autograder.py","full_name":"GameState.getAgentDistances","func_name":"getAgentDistances","docstring":"Returns a noisy distance to each agent.","docstring_tokens":"","code":"def getAgentDistances(self):\n \"\"\"\n Returns a noisy distance to each agent.\n \"\"\"\n if 'agentDistances' in dir(self):\n return self.agentDistances\n else:\n return None","code_tokens":"","url":223944} +{"project_name":"lalwanii26\/openscope-barcodingstim","file_name":"experiment.py","full_name":"Experiment.add_item","func_name":"add_item","docstring":"Adds an item to the experiment.","docstring_tokens":"","code":"def add_item(self, item, name=''):\n \"\"\"\n Adds an item to the experiment.\n \"\"\"\n if not name:\n length = len(self.items.keys())\n name = 'unnamed_item_%s' % length\n item._parent = self\n self.items[name] = item","code_tokens":"","url":757503} +{"project_name":"intel\/neural-compressor","file_name":"utility.py","full_name":"calculate_mse","func_name":"calculate_mse","docstring":"Calculate MSE for specified OP.","docstring_tokens":"","code":"def calculate_mse(op_name: str, input_model_tensors: dict, optimized_model_tensors: dict) -> Optional[float]:\n \"\"\"Calculate MSE for specified OP.\n\n Args:\n op_name: name of the OP\n input_model_tensors: dict with input tensors details\n optimized_model_tensors: dict with optimized tensors details\n\n Returns:\n MSE value for specified op_name\n \"\"\"\n input_model_op_data = input_model_tensors.get(op_name, None)\n optimized_model_op_data = optimized_model_tensors.get(op_name, None)\n if input_model_op_data is None or optimized_model_op_data is None:\n return None\n mse: float = mse_metric_gap(next(iter(input_model_op_data.values()))[0], next(iter(optimized_model_op_data.values()))[0])\n return mse","code_tokens":"","url":721517} +{"project_name":"AlexGeControl\/Artificial-Intelligence-01-Graph-Search-02-Pacman","file_name":"ipaddress.py","full_name":"_BaseNetwork.num_addresses","func_name":"num_addresses","docstring":"Number of hosts in the current subnet.","docstring_tokens":"","code":"@property\ndef num_addresses(self):\n \"\"\"Number of hosts in the current subnet.\"\"\"\n return int(self.broadcast_address) - int(self.network_address) + 1","code_tokens":"","url":35162} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_tifffile.py","full_name":"TiffFile.micromanager_metadata","func_name":"micromanager_metadata","docstring":"Return consolidated MicroManager metadata as dict.","docstring_tokens":"","code":"@lazyattr\ndef micromanager_metadata(self):\n \"\"\"Return consolidated MicroManager metadata as dict.\"\"\"\n if not self.is_micromanager:\n return\n result = read_micromanager_metadata(self._fh)\n result.update(self.pages[0].tags['MicroManagerMetadata'].value)\n return result","code_tokens":"","url":37589} +{"project_name":"EducationalTestingService\/skll","file_name":"test_input.py","full_name":"TestInput.test_learning_curve_bad_folds_specifications","func_name":"test_learning_curve_bad_folds_specifications","docstring":"Test that config parsing raises error for bad learning curve folds.","docstring_tokens":"","code":"def test_learning_curve_bad_folds_specifications(self):\n \"\"\"Test that config parsing raises error for bad learning curve folds.\"\"\"\n values_to_fill_dict = {'experiment_name': 'config_parsing', 'task': 'learning_curve', 'train_directory': train_dir, 'featuresets': \"[['f1', 'f2', 'f3']]\", 'learning_curve_cv_folds_list': '[10]', 'learners': \"['LogisticRegression', 'MultinomialNB']\", 'metrics': \"['accuracy', 'f1_score_macro']\", 'logs': output_dir, 'results': output_dir}\n config_template_path = config_dir \/ 'test_config_parsing.template.cfg'\n config_path = fill_in_config_options(config_template_path, values_to_fill_dict, 'learning_curve_bad_folds_specifications')\n with self.assertRaises(ValueError):\n parse_config_file(config_path)","code_tokens":"","url":885204} +{"project_name":"mfbx9da4\/neuron-astrocyte-networks","file_name":"gfilter.py","full_name":"Filter.apply","func_name":"apply","docstring":"Applies an operation on a population.","docstring_tokens":"","code":"def apply(self, population):\n \"\"\" Applies an operation on a population. \"\"\"\n raise NotImplementedError()","code_tokens":"","url":723229} +{"project_name":"nilearn\/nilearn","file_name":"_maskers.py","full_name":"check_same_n_vertices","func_name":"check_same_n_vertices","docstring":"Check that 2 meshes have the same keys and that n vertices match.","docstring_tokens":"","code":"def check_same_n_vertices(mesh_1: PolyMesh, mesh_2: PolyMesh) -> None:\n \"\"\"Check that 2 meshes have the same keys and that n vertices match.\"\"\"\n (keys_1, keys_2) = (set(mesh_1.keys()), set(mesh_2.keys()))\n if keys_1 != keys_2:\n diff = keys_1.symmetric_difference(keys_2)\n raise ValueError(f'Meshes do not have the same keys. Offending keys: {diff}')\n for key in keys_1:\n if mesh_1[key].n_vertices != mesh_2[key].n_vertices:\n raise ValueError(f\"Number of vertices do not match for '{key}'.number of vertices in mesh_1: {mesh_1[key].n_vertices}; in mesh_2: {mesh_2[key].n_vertices}\")","code_tokens":"","url":723762} +{"project_name":"kevinddchen\/Keras-FCN","file_name":"augment.py","full_name":"resize_with_pad","func_name":"resize_with_pad","docstring":"Resize a square while keeping the original aspect ratio, padding with black for the image and boundary for the label.","docstring_tokens":"","code":"def resize_with_pad(image, label, size=512):\n \"\"\"Resize a square while keeping the original aspect ratio, padding with black for the image and boundary \n for the label.\n \n Args:\n image (array): RGB values for each pixel. Shape=(height, width, 3)\n label (array): Class labels for each pixel. Shape=(height, width, 1)\n size (int): length of square\n \n Returns:\n (array): Resized image. Shape=(size, size, 3)\n (array): Resized label. Shape=(size, size, 1)\n \"\"\"\n image = tf.image.resize_with_pad(image, size, size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n label = tf.image.resize_with_pad(label + 1, size, size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) - 1\n return (image, label)","code_tokens":"","url":595429} +{"project_name":"NVIDIA-Omniverse\/IsaacGymEnvs","file_name":"vec_task.py","full_name":"VecTask.pre_physics_step","func_name":"pre_physics_step","docstring":"Apply the actions to the environment (eg by setting torques, position targets).","docstring_tokens":"","code":"@abc.abstractmethod\ndef pre_physics_step(self, actions: torch.Tensor):\n \"\"\"Apply the actions to the environment (eg by setting torques, position targets).\n\n Args:\n actions: the actions to apply\n \"\"\"","code_tokens":"","url":246609} +{"project_name":"okfn-brasil\/serenata-de-amor","file_name":"receipts_text.py","full_name":"Command.receipts","func_name":"receipts","docstring":"Returns a Generator with batches of receipts text.","docstring_tokens":"","code":"def receipts(self):\n \"\"\"Returns a Generator with batches of receipts text.\"\"\"\n print('Loading receipts text dataset\u00c3\u00a2\u00c2\\x80\u00c2\u00a6', end='\\r')\n with lzma.open(self.path, mode='rt') as file_handler:\n batch = []\n for row in csv.DictReader(file_handler):\n batch.append(self.serialize(row))\n if len(batch) >= self.batch_size:\n yield batch\n batch = []\n yield batch","code_tokens":"","url":349753} +{"project_name":"chainer\/chainer","file_name":"device_resident.py","full_name":"DeviceResident.from_chx","func_name":"from_chx","docstring":"Converts parameter variables and persistent values from ChainerX to NumPy\/CuPy devices without any copy.","docstring_tokens":"","code":"@utils.final\ndef from_chx(self):\n \"\"\"Converts parameter variables and persistent values from ChainerX to NumPy\/CuPy devices without any copy.\"\"\"\n if self._device.xp is chainerx:\n self._device = self._device.fallback_device\n self.device_resident_accept(_FromChxVisitor())\n return self","code_tokens":"","url":476910} +{"project_name":"google-research\/crest","file_name":"resnet.py","full_name":"ResNetV2","func_name":"ResNetV2","docstring":"Instantiates the ResNet V2 architecture.","docstring_tokens":"","code":"def ResNetV2(arch='ResNet18', input_shape=None, num_class=1000, pooling=None, normalization='bn', activation='relu', width=1.0, **kwargs):\n \"\"\"Instantiates the ResNet V2 architecture.\"\"\"\n del kwargs\n\n def stack_fn(x, arch, width=1.0):\n (block, stack, expansion) = (BLOCK[arch], STACK[arch], EXPANSION[arch])\n x = stack(x, int(64 * width), block[0], expansion=expansion, normalization=normalization, activation=activation, name='conv2')\n x = stack(x, int(128 * width), block[1], expansion=expansion, normalization=normalization, activation=activation, name='conv3')\n x = stack(x, int(256 * width), block[2], expansion=expansion, normalization=normalization, activation=activation, name='conv4')\n return stack(x, int(512 * width), block[3], expansion=expansion, stride1=1, normalization=normalization, activation=activation, name='conv5')\n return ResNet(stack_fn=functools.partial(stack_fn, arch=arch, width=width), preact=True, model_name='{}_w{:g}_{}_{}'.format(arch, width, normalization, activation), input_shape=input_shape, pooling=pooling, normalization=normalization, activation=activation, num_class=num_class)","code_tokens":"","url":138521} +{"project_name":"muhanzhang\/D-VAE","file_name":"opt.py","full_name":"local_cast_cast","func_name":"local_cast_cast","docstring":"cast(cast(x, dtype1), dtype2) when those contrain: dtype1 == dtype2 TODO: the base dtype is the same (int, uint, float, complex) and the first cast cause an upcast.","docstring_tokens":"","code":"@register_canonicalize\n@register_specialize\n@gof.local_optimizer([T.Elemwise])\ndef local_cast_cast(node):\n \"\"\"cast(cast(x, dtype1), dtype2)\n\n when those contrain:\n dtype1 == dtype2\n TODO: the base dtype is the same (int, uint, float, complex)\n and the first cast cause an upcast.\n\n \"\"\"\n if not isinstance(node.op, T.Elemwise) or not isinstance(node.op.scalar_op, scalar.Cast):\n return\n x = node.inputs[0]\n if not x.owner or not isinstance(x.owner.op, T.Elemwise) or (not isinstance(x.owner.op.scalar_op, scalar.Cast)):\n return\n if node.op.scalar_op.o_type == x.owner.op.scalar_op.o_type:\n return [x]","code_tokens":"","url":525525} +{"project_name":"veseln\/Neat-EO.pink","file_name":"tiles.py","full_name":"tiles_from_csv","func_name":"tiles_from_csv","docstring":"Retrieve tiles from a line-delimited csv file.","docstring_tokens":"","code":"def tiles_from_csv(path, xyz=True, extra_columns=False):\n \"\"\"Retrieve tiles from a line-delimited csv file.\"\"\"\n assert os.path.isfile(os.path.expanduser(path)), \"'{}' seems not a valid CSV file\".format(path)\n with open(os.path.expanduser(path)) as fp:\n for row in fp:\n row = row.replace('\\n', '')\n if not row:\n continue\n row = re.split(',|\\t', row)\n if xyz:\n assert len(row) >= 3, 'Invalid Cover'\n if not extra_columns or len(row) == 3:\n yield mercantile.Tile(int(row[0]), int(row[1]), int(row[2]))\n else:\n yield [mercantile.Tile(int(row[0]), int(row[1]), int(row[2])), *map(float, row[3:])]\n if not xyz:\n assert len(row) >= 1, 'Invalid Cover'\n if not extra_columns:\n yield row[0]\n else:\n yield [row[0], *map(float, row[1:])]","code_tokens":"","url":735290} +{"project_name":"microsoft\/maro","file_name":"abs_business_engine.py","full_name":"AbsBusinessEngine.dump","func_name":"dump","docstring":"Dump something from business engine.","docstring_tokens":"","code":"def dump(self, folder: str) -> None:\n \"\"\"Dump something from business engine.\n\n Args:\n folder (str): Folder to place dumped files.\n \"\"\"","code_tokens":"","url":628618} +{"project_name":"hamza-murad\/AALU","file_name":"discovery_v1.py","full_name":"Expansion.from_dict","func_name":"from_dict","docstring":"Initialize a Expansion object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'Expansion':\n \"\"\"Initialize a Expansion object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['input_terms', 'expanded_terms']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class Expansion: ' + ', '.join(bad_keys))\n if 'input_terms' in _dict:\n args['input_terms'] = _dict.get('input_terms')\n if 'expanded_terms' in _dict:\n args['expanded_terms'] = _dict.get('expanded_terms')\n else:\n raise ValueError(\"Required property 'expanded_terms' not present in Expansion JSON\")\n return cls(**args)","code_tokens":"","url":5568} +{"project_name":"voxel51\/fiftyone","file_name":"storage.py","full_name":"ensure_empty_dir","func_name":"ensure_empty_dir","docstring":"Ensures that the given directory exists and is empty.","docstring_tokens":"","code":"def ensure_empty_dir(dirpath, cleanup=False):\n \"\"\"Ensures that the given directory exists and is empty.\n\n Args:\n dirpath: the directory path\n cleanup (False): whether to delete any existing directory contents\n\n Raises:\n ValueError: if the directory is not empty and ``cleanup`` is False\n \"\"\"\n etau.ensure_empty_dir(dirpath, cleanup=cleanup)","code_tokens":"","url":583395} +{"project_name":"Center-of-Diagnostics-and-Telemedicine\/ai-testing-platform","file_name":"conftest.py","full_name":"compression_only","func_name":"compression_only","docstring":"Fixture for trying common compression types in compression tests excluding uncompressed case.","docstring_tokens":"","code":"@pytest.fixture(params=['gzip', 'bz2', 'zip', 'xz'])\ndef compression_only(request):\n \"\"\"\n Fixture for trying common compression types in compression tests excluding\n uncompressed case.\n \"\"\"\n return request.param","code_tokens":"","url":82261} +{"project_name":"openai\/gym","file_name":"test_passive_env_checker.py","full_name":"test_passive_render_checker","func_name":"test_passive_render_checker","docstring":"Tests the passive render checker.","docstring_tokens":"","code":"@pytest.mark.parametrize('test,env,message', [[UserWarning, GenericTestEnv(metadata={'render_modes': None}), \"No render modes was declared in the environment (env.metadata['render_modes'] is None or not defined), you may have trouble when calling `.render()`.\"], [UserWarning, GenericTestEnv(metadata={'render_modes': 'Testing mode'}), \"Expects the render_modes to be a sequence (i.e. list, tuple), actual type: \"], [UserWarning, GenericTestEnv(metadata={'render_modes': ['Testing mode', 1], 'render_fps': 1}), \"Expects all render modes to be strings, actual types: [, ]\"], [UserWarning, GenericTestEnv(metadata={'render_modes': ['Testing mode'], 'render_fps': None}, render_mode='Testing mode', render_fn=lambda self: 0), \"No render fps was declared in the environment (env.metadata['render_fps'] is None or not defined), rendering may occur at inconsistent fps.\"], [UserWarning, GenericTestEnv(metadata={'render_modes': ['Testing mode'], 'render_fps': 'fps'}), \"Expects the `env.metadata['render_fps']` to be an integer or a float, actual type: \"], [AssertionError, GenericTestEnv(metadata={'render_modes': [], 'render_fps': 30}, render_mode='Test'), 'With no render_modes, expects the Env.render_mode to be None, actual value: Test'], [AssertionError, GenericTestEnv(metadata={'render_modes': ['Testing mode'], 'render_fps': 30}, render_mode='Non mode'), \"The environment was initialized successfully however with an unsupported render mode. Render mode: Non mode, modes: ['Testing mode']\"]])\ndef test_passive_render_checker(test, env: GenericTestEnv, message: str):\n \"\"\"Tests the passive render checker.\"\"\"\n if test is UserWarning:\n with pytest.warns(UserWarning, match=f'^\\\\x1b\\\\[33mWARN: {re.escape(message)}\\\\x1b\\\\[0m$'):\n env_render_passive_checker(env)\n else:\n with warnings.catch_warnings(record=True) as caught_warnings:\n with pytest.raises(test, match=f'^{re.escape(message)}$'):\n env_render_passive_checker(env)\n assert len(caught_warnings) == 0","code_tokens":"","url":234405} +{"project_name":"AndrewYinLi\/lstm-neural-network-spam-filter","file_name":"test_tgrep.py","full_name":"TestSequenceFunctions.test_rel_sister_nodes","func_name":"test_rel_sister_nodes","docstring":"Test matching sister nodes in a tree.","docstring_tokens":"","code":"def test_rel_sister_nodes(self):\n \"\"\"\n Test matching sister nodes in a tree.\n \"\"\"\n tree = ParentedTree.fromstring('(S (A x) (B x) (C x))')\n self.assertEqual(list(tgrep.tgrep_positions('* $. B', [tree])), [[(0,)]])\n self.assertEqual(list(tgrep.tgrep_positions('* $.. B', [tree])), [[(0,)]])\n self.assertEqual(list(tgrep.tgrep_positions('* $, B', [tree])), [[(2,)]])\n self.assertEqual(list(tgrep.tgrep_positions('* $,, B', [tree])), [[(2,)]])\n self.assertEqual(list(tgrep.tgrep_positions('* $ B', [tree])), [[(0,), (2,)]])","code_tokens":"","url":218509} +{"project_name":"GatorEducator\/GatorMiner","file_name":"streamlit_web.py","full_name":"import_data","func_name":"import_data","docstring":"Pipeline to import data from local or aws.","docstring_tokens":"","code":"@st.cache(allow_output_mutation=True, suppress_st_warning=True)\ndef import_data(data_retreive_method, paths):\n \"\"\"Pipeline to import data from local or aws.\"\"\"\n global main_md_dict\n if data_retreive_method == 'Path input':\n json_lst = path_import(paths)\n elif data_retreive_method == 'AWS':\n json_lst = aws_import(paths)\n else:\n json_lst = file_uploader_import(paths)\n if json_lst:\n raw_df = pd.DataFrame()\n for item in json_lst:\n single_df = pd.DataFrame(item)\n raw_df = pd.concat([raw_df, single_df], ignore_index=True)\n processed_df = raw_df.fillna('')\n df_preprocess(processed_df)\n return (raw_df, processed_df)","code_tokens":"","url":567411} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"__init__.py","full_name":"YAMLObject.to_yaml","func_name":"to_yaml","docstring":"Convert a Python object to a representation node.","docstring_tokens":"","code":"@classmethod\ndef to_yaml(cls, dumper, data):\n \"\"\"\n Convert a Python object to a representation node.\n \"\"\"\n return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)","code_tokens":"","url":101737} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"configHandler.py","full_name":"IdleUserConfParser.RemoveEmptySections","func_name":"RemoveEmptySections","docstring":"Remove any sections that have no options.","docstring_tokens":"","code":"def RemoveEmptySections(self):\n \"\"\"Remove any sections that have no options.\"\"\"\n for section in self.sections():\n if not self.GetOptionList(section):\n self.remove_section(section)","code_tokens":"","url":219191} +{"project_name":"rudranil723\/mini-main","file_name":"base.py","full_name":"BaseDatabaseWrapper.get_connection_params","func_name":"get_connection_params","docstring":"Return a dict of parameters suitable for get_new_connection.","docstring_tokens":"","code":"def get_connection_params(self):\n \"\"\"Return a dict of parameters suitable for get_new_connection.\"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_connection_params() method')","code_tokens":"","url":315707} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"math2html.py","full_name":"CommandBit.parsesquareliteral","func_name":"parsesquareliteral","docstring":"Parse a square bracket literally.","docstring_tokens":"","code":"def parsesquareliteral(self, pos):\n \"\"\"Parse a square bracket literally.\"\"\"\n self.factory.clearskipped(pos)\n if not self.factory.detecttype(SquareBracket, pos):\n return None\n bracket = SquareBracket().setfactory(self.factory)\n self.add(bracket.parseliteral(pos))\n return bracket.literal","code_tokens":"","url":395296} +{"project_name":"hamza-murad\/AALU","file_name":"assistant_v1.py","full_name":"CounterexampleCollection.from_dict","func_name":"from_dict","docstring":"Initialize a CounterexampleCollection object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'CounterexampleCollection':\n \"\"\"Initialize a CounterexampleCollection object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['counterexamples', 'pagination']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class CounterexampleCollection: ' + ', '.join(bad_keys))\n if 'counterexamples' in _dict:\n args['counterexamples'] = [Counterexample._from_dict(x) for x in _dict.get('counterexamples')]\n else:\n raise ValueError(\"Required property 'counterexamples' not present in CounterexampleCollection JSON\")\n if 'pagination' in _dict:\n args['pagination'] = Pagination._from_dict(_dict.get('pagination'))\n else:\n raise ValueError(\"Required property 'pagination' not present in CounterexampleCollection JSON\")\n return cls(**args)","code_tokens":"","url":5178} +{"project_name":"bayer-science-for-a-better-life\/contrastive-reconstruction","file_name":"contrastive.py","full_name":"preprocess_for_train","func_name":"preprocess_for_train","docstring":"Preprocesses the given image for training.","docstring_tokens":"","code":"def preprocess_for_train(image, height, width, color_distort=True, crop=True, flip=True, impl='simclrv2', color_jitter_strength=0.5):\n \"\"\"Preprocesses the given image for training.\n\n Args:\n image: `Tensor` representing an image of arbitrary size.\n height: Height of output image.\n width: Width of output image.\n color_distort: Whether to apply the color distortion.\n crop: Whether to crop the image.\n flip: Whether or not to flip left and right of an image.\n impl: 'simclrv1' or 'simclrv2'. Whether to use simclrv1 or simclrv2's\n version of random brightness.\n\n Returns:\n A preprocessed image `Tensor`.\n \"\"\"\n if crop:\n image = random_crop_with_resize(image, height, width)\n if flip:\n image = tf.image.random_flip_left_right(image)\n if color_distort:\n image = random_color_jitter(image, impl=impl, color_jitter_strength=color_jitter_strength)\n image = tf.reshape(image, [height, width, 3])\n image = tf.clip_by_value(image, 0.0, 1.0)\n return image","code_tokens":"","url":136607} +{"project_name":"divelab\/AIRS","file_name":"train.py","full_name":"make_standard_scalar_and_pca","func_name":"make_standard_scalar_and_pca","docstring":"Use standard scalar and PCS for multi-output data.","docstring_tokens":"","code":"def make_standard_scalar_and_pca(output):\n \"\"\"Use standard scalar and PCS for multi-output data.\"\"\"\n sc = pk.load(open(os.path.join(tmp_output_dir, 'sc.pkl'), 'rb'))\n (y_pred, y) = output\n y_pred = torch.tensor(sc.transform(y_pred.cpu().numpy()), device=device)\n y = torch.tensor(sc.transform(y.cpu().numpy()), device=device)\n return (y_pred, y)","code_tokens":"","url":86530} +{"project_name":"frapa\/tbcnn","file_name":"sampling.py","full_name":"gen_samples","func_name":"gen_samples","docstring":"Creates a generator that returns a tree in BFS order with each node replaced by its vector embedding, and a child lookup table.","docstring_tokens":"","code":"def gen_samples(trees, labels, vectors, vector_lookup):\n \"\"\"Creates a generator that returns a tree in BFS order with each node\n replaced by its vector embedding, and a child lookup table.\"\"\"\n label_lookup = {label: _onehot(i, len(labels)) for (i, label) in enumerate(labels)}\n for tree in trees:\n nodes = []\n children = []\n label = label_lookup[tree['label']]\n queue = [(tree['tree'], -1)]\n while queue:\n (node, parent_ind) = queue.pop(0)\n node_ind = len(nodes)\n queue.extend([(child, node_ind) for child in node['children']])\n children.append([])\n if parent_ind > -1:\n children[parent_ind].append(node_ind)\n nodes.append(vectors[vector_lookup[node['node']]])\n yield (nodes, children, label)","code_tokens":"","url":365559} +{"project_name":"deepmind\/bsuite","file_name":"catch_scale.py","full_name":"load","func_name":"load","docstring":"Load a catch experiment with the prescribed settings.","docstring_tokens":"","code":"def load(reward_scale, seed):\n \"\"\"Load a catch experiment with the prescribed settings.\"\"\"\n env = wrappers.RewardScale(env=catch.Catch(seed=seed), reward_scale=reward_scale, seed=seed)\n env.bsuite_num_episodes = sweep.NUM_EPISODES\n return env","code_tokens":"","url":410198} +{"project_name":"Eric3911\/OpenAGI","file_name":"rnnt_wer.py","full_name":"AbstractRNNTDecoding.decode_hypothesis","func_name":"decode_hypothesis","docstring":"Decode a list of hypotheses into a list of strings.","docstring_tokens":"","code":"def decode_hypothesis(self, hypotheses_list: List[Hypothesis]) -> List[Union[Hypothesis, NBestHypotheses]]:\n \"\"\"\n Decode a list of hypotheses into a list of strings.\n\n Args:\n hypotheses_list: List of Hypothesis.\n\n Returns:\n A list of strings.\n \"\"\"\n for ind in range(len(hypotheses_list)):\n prediction = hypotheses_list[ind].y_sequence\n if type(prediction) != list:\n prediction = prediction.tolist()\n if self.blank_id != 0:\n num_extra_outputs = 0\n if self.big_blank_durations is not None:\n num_extra_outputs += len(self.big_blank_durations)\n prediction = [p for p in prediction if p < self.blank_id - num_extra_outputs]\n else:\n prediction = [p for p in prediction if p != self.blank_id]\n if self.compute_timestamps is True:\n alignments = copy.deepcopy(hypotheses_list[ind].alignments)\n token_repetitions = [1] * len(alignments)\n hypothesis = (prediction, alignments, token_repetitions)\n else:\n hypothesis = self.decode_tokens_to_str(prediction)\n if self.compute_hypothesis_token_set:\n hypotheses_list[ind].tokens = self.decode_ids_to_tokens(prediction)\n hypotheses_list[ind].text = hypothesis\n return hypotheses_list","code_tokens":"","url":272352} +{"project_name":"gunthercox\/ChatterBot","file_name":"mapper.py","full_name":"Mapper.primary_mapper","func_name":"primary_mapper","docstring":"Return the primary mapper corresponding to this mapper's class key (class).","docstring_tokens":"","code":"def primary_mapper(self):\n \"\"\"Return the primary mapper corresponding to this mapper's class key\n (class).\"\"\"\n return self.class_manager.mapper","code_tokens":"","url":481411} +{"project_name":"suarez12138\/AI-Reversi_IMP_TextDichotomy","file_name":"test_hashing.py","full_name":"test_bound_cached_methods_hash","func_name":"test_bound_cached_methods_hash","docstring":"Make sure that calling the same _cached_ method on two different instances of the same class does resolve to the same hashes.","docstring_tokens":"","code":"def test_bound_cached_methods_hash(tmpdir):\n \"\"\" Make sure that calling the same _cached_ method on two different\n instances of the same class does resolve to the same hashes.\n \"\"\"\n a = KlassWithCachedMethod(tmpdir.strpath)\n b = KlassWithCachedMethod(tmpdir.strpath)\n assert hash(filter_args(a.f.func, [], (1,))) == hash(filter_args(b.f.func, [], (1,)))","code_tokens":"","url":95961} +{"project_name":"Eric3911\/OpenAGI","file_name":"mlm_scorer.py","full_name":"MLMScorer.score_sentence","func_name":"score_sentence","docstring":"returns MLM score for sentence.","docstring_tokens":"","code":"def score_sentence(self, sentence: str):\n \"\"\"\n returns MLM score for sentence.\n \"\"\"\n assert type(sentence) == str\n tokens = self.tokenizer.tokenize(sentence)\n mask_idx = []\n token_type = []\n attn_mask = []\n ids = []\n for (m_idx, _) in enumerate(tokens):\n masked = self.__mask_text__(m_idx, tokens)\n mask_idx.append(m_idx)\n ids.append(self.tokenizer.encode(masked))\n id_len = len(ids[-1])\n token_type.append([0] * id_len)\n attn_mask.append([1] * id_len)\n data = {'input_ids': torch.tensor(ids, device=self.device), 'attention_mask': torch.tensor(attn_mask, device=self.device), 'token_type_ids': torch.tensor(token_type, device=self.device)}\n with torch.no_grad():\n outputs = self.model(**data)\n logits = outputs.logits\n scores = []\n scores_log_prob = 0.0\n for (i, m_idx) in enumerate(mask_idx):\n preds = logits[i].squeeze(0)\n probs = softmax(preds, dim=1)\n token_id = self.tokenizer.convert_tokens_to_ids([tokens[m_idx]])[0]\n log_prob = np.log(probs[m_idx + 1, token_id].cpu().numpy()).item()\n scores.append(log_prob)\n scores_log_prob += log_prob\n return scores_log_prob","code_tokens":"","url":273121} +{"project_name":"aalgirdas\/Artificial-Intelligence-Course","file_name":"games.py","full_name":"random_player","func_name":"random_player","docstring":"A player that chooses a legal move at random.","docstring_tokens":"","code":"def random_player(game, state):\n \"\"\"A player that chooses a legal move at random.\"\"\"\n return random.choice(game.actions(state)) if game.actions(state) else None","code_tokens":"","url":79636} +{"project_name":"feast-dev\/feast","file_name":"test_dynamodb_online_store.py","full_name":"test_dynamodb_table_default_params","func_name":"test_dynamodb_table_default_params","docstring":"Test DynamoDBTable default parameters.","docstring_tokens":"","code":"def test_dynamodb_table_default_params():\n \"\"\"Test DynamoDBTable default parameters.\"\"\"\n tbl_name = 'dynamodb-test'\n aws_region = 'us-west-2'\n dynamodb_table = DynamoDBTable(tbl_name, aws_region)\n assert dynamodb_table.name == tbl_name\n assert dynamodb_table.region == aws_region\n assert dynamodb_table.endpoint_url is None\n assert dynamodb_table._dynamodb_client is None\n assert dynamodb_table._dynamodb_resource is None","code_tokens":"","url":544627} +{"project_name":"googleapis\/python-aiplatform","file_name":"client.py","full_name":"JobServiceClient.parse_data_labeling_job_path","func_name":"parse_data_labeling_job_path","docstring":"Parses a data_labeling_job path into its component segments.","docstring_tokens":"","code":"@staticmethod\ndef parse_data_labeling_job_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a data_labeling_job path into its component segments.\"\"\"\n m = re.match('^projects\/(?P.+?)\/locations\/(?P.+?)\/dataLabelingJobs\/(?P.+?)$', path)\n return m.groupdict() if m else {}","code_tokens":"","url":813046} +{"project_name":"LucasAlegre\/morl-baselines","file_name":"capql.py","full_name":"CAPQL.update","func_name":"update","docstring":"Update the policy and the Q-nets.","docstring_tokens":"","code":"def update(self):\n \"\"\"Update the policy and the Q-nets.\"\"\"\n for _ in range(self.gradient_updates):\n (s_obs, s_actions, w, s_rewards, s_next_obs, s_dones) = self._sample_batch_experiences()\n with th.no_grad():\n (next_actions, log_pi, _) = self.policy.sample(s_next_obs, w)\n q_targets = th.stack([q_target(s_next_obs, next_actions, w) for q_target in self.target_q_nets])\n min_target_q = th.min(q_targets, dim=0)[0] - self.alpha * log_pi.reshape(-1, 1)\n target_q = (s_rewards + (1 - s_dones.reshape(-1, 1)) * self.gamma * min_target_q).detach()\n q_values = [q_net(s_obs, s_actions, w) for q_net in self.q_nets]\n critic_loss = 1 \/ self.num_q_nets * sum([F.mse_loss(q_value, target_q) for q_value in q_values])\n self.q_optim.zero_grad()\n critic_loss.backward()\n self.q_optim.step()\n (pi, log_pi, _) = self.policy.sample(s_obs, w)\n q_values = th.stack([q_target(s_obs, pi, w) for q_target in self.q_nets])\n min_q = th.min(q_values, dim=0)[0]\n min_q = (min_q * w).sum(dim=-1, keepdim=True)\n policy_loss = (self.alpha * log_pi - min_q).mean()\n self.policy_optim.zero_grad()\n policy_loss.backward()\n self.policy_optim.step()\n for (q_net, target_q_net) in zip(self.q_nets, self.target_q_nets):\n polyak_update(q_net.parameters(), target_q_net.parameters(), self.tau)\n if self.log and self.global_step % 100 == 0:\n wandb.log({'losses\/critic_loss': critic_loss.item(), 'losses\/policy_loss': policy_loss.item(), 'global_step': self.global_step})","code_tokens":"","url":655872} +{"project_name":"rudranil723\/mini-main","file_name":"text.py","full_name":"Text.highlight_regex","func_name":"highlight_regex","docstring":"Highlight text with a regular expression, where group names are translated to styles.","docstring_tokens":"","code":"def highlight_regex(self, re_highlight: str, style: Optional[Union[GetStyleCallable, StyleType]]=None, *, style_prefix: str='') -> int:\n \"\"\"Highlight text with a regular expression, where group names are\n translated to styles.\n\n Args:\n re_highlight (str): A regular expression.\n style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable\n which accepts the matched text and returns a style. Defaults to None.\n style_prefix (str, optional): Optional prefix to add to style group names.\n\n Returns:\n int: Number of regex matches\n \"\"\"\n count = 0\n append_span = self._spans.append\n _Span = Span\n plain = self.plain\n for match in re.finditer(re_highlight, plain):\n get_span = match.span\n if style:\n (start, end) = get_span()\n match_style = style(plain[start:end]) if callable(style) else style\n if match_style is not None and end > start:\n append_span(_Span(start, end, match_style))\n count += 1\n for name in match.groupdict().keys():\n (start, end) = get_span(name)\n if start != -1 and end > start:\n append_span(_Span(start, end, f'{style_prefix}{name}'))\n return count","code_tokens":"","url":268980} +{"project_name":"accel-brain\/accel-brain-code","file_name":"volatility_gan_controller.py","full_name":"VolatilityGANController.train_by_feature_matching","func_name":"train_by_feature_matching","docstring":"Train by feature matching.","docstring_tokens":"","code":"def train_by_feature_matching(self, k_step):\n \"\"\"\n Train by feature matching.\n\n Args:\n k_step: `int` of the number of iterations.\n \n Returns:\n feature matching loss.\n \"\"\"\n feature_matching_loss = 0.0\n if self.feature_matching_loss is None:\n return feature_matching_loss\n try_limit = 10\n for k in range(k_step):\n for try_n in range(try_limit):\n try:\n true_arr = self.true_sampler.draw()\n break\n except:\n if try_n + 1 >= try_limit:\n raise\n continue\n for try_n in range(try_limit):\n try:\n (generated_arr, _, _) = self.generative_model.draw()\n break\n except:\n if try_n + 1 >= try_limit:\n raise\n continue\n with autograd.record():\n true_posterior_arr = self.discriminative_model.inference(true_arr)\n generated_posterior_arr = self.discriminative_model.inference(generated_arr)\n loss = self.feature_matching_loss(true_posterior_arr, generated_posterior_arr)\n loss.backward()\n self.discriminator_trainer.step(true_arr.shape[0])\n feature_matching_loss += loss.mean().asnumpy()[0]\n feature_matching_loss = feature_matching_loss \/ k_step\n return feature_matching_loss","code_tokens":"","url":7081} +{"project_name":"YuriyGuts\/snake-ai-reinforcement","file_name":"dqn.py","full_name":"DeepQNetworkAgent.act","func_name":"act","docstring":"Choose the next action to take.","docstring_tokens":"","code":"def act(self, observation, reward):\n \"\"\"\n Choose the next action to take.\n \n Args:\n observation: observable state for the current timestep. \n reward: reward received at the beginning of the current timestep.\n\n Returns:\n The index of the action to take next.\n \"\"\"\n state = self.get_last_frames(observation)\n q = self.model.predict(state)[0]\n return np.argmax(q)","code_tokens":"","url":352090} +{"project_name":"georghess\/voxel-mae","file_name":"kitti_converter.py","full_name":"generate_record","func_name":"generate_record","docstring":"Generate one 2D annotation record given various informations on top of the 2D bounding box coordinates.","docstring_tokens":"","code":"def generate_record(ann_rec, x1, y1, x2, y2, sample_data_token, filename):\n \"\"\"Generate one 2D annotation record given various informations on top of\n the 2D bounding box coordinates.\n\n Args:\n ann_rec (dict): Original 3d annotation record.\n x1 (float): Minimum value of the x coordinate.\n y1 (float): Minimum value of the y coordinate.\n x2 (float): Maximum value of the x coordinate.\n y2 (float): Maximum value of the y coordinate.\n sample_data_token (str): Sample data token.\n filename (str):The corresponding image file where the annotation\n is present.\n\n Returns:\n dict: A sample 2D annotation record.\n - file_name (str): flie name\n - image_id (str): sample data token\n - area (float): 2d box area\n - category_name (str): category name\n - category_id (int): category id\n - bbox (list[float]): left x, top y, dx, dy of 2d box\n - iscrowd (int): whether the area is crowd\n \"\"\"\n repro_rec = OrderedDict()\n repro_rec['sample_data_token'] = sample_data_token\n coco_rec = dict()\n key_mapping = {'name': 'category_name', 'num_points_in_gt': 'num_lidar_pts', 'sample_annotation_token': 'sample_annotation_token', 'sample_data_token': 'sample_data_token'}\n for (key, value) in ann_rec.items():\n if key in key_mapping.keys():\n repro_rec[key_mapping[key]] = value\n repro_rec['bbox_corners'] = [x1, y1, x2, y2]\n repro_rec['filename'] = filename\n coco_rec['file_name'] = filename\n coco_rec['image_id'] = sample_data_token\n coco_rec['area'] = (y2 - y1) * (x2 - x1)\n if repro_rec['category_name'] not in kitti_categories:\n return None\n cat_name = repro_rec['category_name']\n coco_rec['category_name'] = cat_name\n coco_rec['category_id'] = kitti_categories.index(cat_name)\n coco_rec['bbox'] = [x1, y1, x2 - x1, y2 - y1]\n coco_rec['iscrowd'] = 0\n return coco_rec","code_tokens":"","url":380813} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"future.py","full_name":"Future.from_asyncio_future","func_name":"from_asyncio_future","docstring":"Return a prompt_toolkit `Future` from the given asyncio Future.","docstring_tokens":"","code":"@classmethod\ndef from_asyncio_future(cls, asyncio_f, loop=None):\n \"\"\"\n Return a prompt_toolkit `Future` from the given asyncio Future.\n \"\"\"\n f = cls(loop=loop)\n\n @asyncio_f.add_done_callback\n def _(asyncio_f):\n if asyncio_f.exception():\n f.set_exception(asyncio_f.exception())\n else:\n f.set_result(asyncio_f.result())\n return f","code_tokens":"","url":45129} +{"project_name":"LLNL\/Abmarl","file_name":"train.py","full_name":"run","func_name":"run","docstring":"Train MARL policies using the config_file.","docstring_tokens":"","code":"def run(full_config_path):\n \"\"\"Train MARL policies using the config_file.\"\"\"\n experiment_mod = adu.custom_import_module(full_config_path)\n title = experiment_mod.params['experiment']['title']\n import os\n import shutil\n import time\n base = experiment_mod.params['ray_tune'].get('local_dir', os.path.expanduser('~'))\n output_dir = os.path.join(base, 'abmarl_results\/{}_{}'.format(title, time.strftime('%Y-%m-%d_%H-%M')))\n experiment_mod.params['ray_tune']['local_dir'] = output_dir\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n shutil.copy(full_config_path, output_dir)\n import ray\n from ray import tune\n ray.init()\n tune.run(**experiment_mod.params['ray_tune'])\n ray.shutdown()","code_tokens":"","url":405642} +{"project_name":"Eric3911\/OpenAGI","file_name":"pipeline_base.py","full_name":"PromptForGeneration.post_processing","func_name":"post_processing","docstring":"Post-process the sequences generated by the generation model.","docstring_tokens":"","code":"def post_processing(self, output_sequences, input_lengths):\n \"\"\"\n Post-process the sequences generated by the generation model.\n\n Args:\n output_sequences (:obj:`torch.Tensor`): The raw sequences generated by the generation model.\n input_lengths (:obj:`int` or `list`): The length(s) of the input sequence.\n\n Returns:\n :obj:`List`: The generated sentences that have been post-processed.\n \"\"\"\n generated_sentences = []\n if type(input_lengths) == int:\n input_lengths = [input_lengths] * len(output_sequences)\n for (sent_id, seq) in enumerate(output_sequences):\n seq = seq[input_lengths[sent_id]:]\n if hasattr(self.tokenizer, 'eos_token') and self.tokenizer.eos_token is not None:\n text_output = self.tokenizer.decode(seq, clean_up_tokenization_spaces=True, skip_special_tokens=False)\n idx = text_output.find(self.tokenizer.eos_token)\n if idx >= 0:\n text_output = text_output[:idx]\n else:\n text_output = self.tokenizer.decode(seq, clean_up_tokenization_spaces=True, skip_special_tokens=True)\n text_output = text_output.strip()\n generated_sentences.append(text_output)\n return generated_sentences","code_tokens":"","url":274515} +{"project_name":"cvhciKIT\/sloth","file_name":"utils.py","full_name":"import_callable","func_name":"import_callable","docstring":"Import the callable given by ``module_path_name``.","docstring_tokens":"","code":"def import_callable(module_path_name):\n \"\"\"\n Import the callable given by ``module_path_name``.\n \"\"\"\n try:\n (module_path, name) = module_path_name.rsplit('.', 1)\n except ValueError:\n raise exceptions.ImproperlyConfigured('%s is not a valid module path' % module_path_name)\n try:\n mod = importlib.import_module(module_path)\n except ImportError as e:\n raise exceptions.ImproperlyConfigured('Error importing module %s: \"%s\"' % (module_path, e))\n try:\n item_callable = getattr(mod, name)\n except AttributeError:\n raise exceptions.ImproperlyConfigured('Module \"%s\" does not define a \"%s\" callable' % (module_path, name))\n return item_callable","code_tokens":"","url":878381} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"fish.py","full_name":"Swim.get_reward","func_name":"get_reward","docstring":"Returns a smooth reward.","docstring_tokens":"","code":"def get_reward(self, physics):\n \"\"\"Returns a smooth reward.\"\"\"\n radii = physics.named.model.geom_size[['mouth', 'target'], 0].sum()\n in_target = rewards.tolerance(np.linalg.norm(physics.mouth_to_target()), bounds=(0, radii), margin=2 * radii)\n is_upright = 0.5 * (physics.upright() + 1)\n return (7 * in_target + is_upright) \/ 8","code_tokens":"","url":440867} +{"project_name":"Bismarrck\/kcon","file_name":"transformer.py","full_name":"Transformer.binary_weights","func_name":"binary_weights","docstring":"Return the binary weights for the all k-body contribs.","docstring_tokens":"","code":"@property\ndef binary_weights(self):\n \"\"\"\n Return the binary weights for the all k-body contribs.\n \"\"\"\n return self._binary_weights","code_tokens":"","url":247579} +{"project_name":"scikit-learn\/scikit-learn","file_name":"test_kernel_pca.py","full_name":"test_kernel_pca_n_components","func_name":"test_kernel_pca_n_components","docstring":"Test that `n_components` is correctly taken into account for projections For all solvers this tests that the output has the correct shape depending on the selected number of components.","docstring_tokens":"","code":"def test_kernel_pca_n_components():\n \"\"\"Test that `n_components` is correctly taken into account for projections\n\n For all solvers this tests that the output has the correct shape depending\n on the selected number of components.\n \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n for eigen_solver in ('dense', 'arpack', 'randomized'):\n for c in [1, 2, 4]:\n kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver)\n shape = kpca.fit(X_fit).transform(X_pred).shape\n assert shape == (2, c)","code_tokens":"","url":853051} +{"project_name":"atulkum\/object_detection","file_name":"bbox.py","full_name":"convert_bbox","func_name":"convert_bbox","docstring":"Map bounding boxes in old image shape to their counterparts in new image shape.","docstring_tokens":"","code":"def convert_bbox(bboxes, old_shape, new_shape):\n \"\"\" Map bounding boxes in old image shape to their counterparts in new image shape. \"\"\"\n bboxes = np.array(bboxes, np.float32)\n if bboxes.shape[0] == 0:\n return bboxes\n (oh, ow) = old_shape\n (nh, nw) = new_shape\n bboxes[:, 0] = bboxes[:, 0] * nh \/ oh\n bboxes[:, 1] = bboxes[:, 1] * nw \/ ow\n bboxes[:, 2] = bboxes[:, 2] * nh \/ oh\n bboxes[:, 3] = bboxes[:, 3] * nw \/ ow\n bboxes = rectify_bbox(bboxes, new_shape)\n return bboxes","code_tokens":"","url":744923} +{"project_name":"AndrewSpano\/BSc-Thesis","file_name":"plot_utils.py","full_name":"get_hf_pos_metrics","func_name":"get_hf_pos_metrics","docstring":"Reads the train\/val loss\/accuracy\/f1 metrics from tensorboard files and returns them.","docstring_tokens":"","code":"def get_hf_pos_metrics(logdir: Path) -> Tuple[Tuple[List[float], List[float], List[float]], Tuple[List[float], List[float], List[float]]]:\n \"\"\"Reads the train\/val loss\/accuracy\/f1 metrics from tensorboard files\n and returns them.\"\"\"\n (train_losses, val_losses) = ([], [])\n (train_acc, val_acc) = ([], [])\n (train_f1, val_f1) = ([], [])\n tb_files = glob.glob(f'{logdir}\/events.out.tfevents.*') + glob.glob(f'{logdir}\/*\/events.out.tfevents.*')\n for tb_out in tb_files:\n for e in EventFileLoader(tb_out).Load():\n if len(e.summary.value) > 0:\n if e.summary.value[0].tag == 'train\/loss':\n train_losses.append(e.summary.value[0].tensor.float_val[0])\n elif e.summary.value[0].tag == 'eval\/loss':\n val_losses.append(e.summary.value[0].tensor.float_val[0])\n if e.summary.value[0].tag == 'train\/accuracy':\n train_acc.append(e.summary.value[0].tensor.float_val[0])\n elif e.summary.value[0].tag == 'eval\/accuracy':\n val_acc.append(e.summary.value[0].tensor.float_val[0])\n if e.summary.value[0].tag == 'train\/f1':\n train_f1.append(e.summary.value[0].tensor.float_val[0])\n elif e.summary.value[0].tag == 'eval\/f1':\n val_f1.append(e.summary.value[0].tensor.float_val[0])\n train_metrics = (train_losses, train_acc, train_f1)\n val_metrics = (val_losses, val_acc, val_f1)\n return (train_metrics, val_metrics)","code_tokens":"","url":410089} +{"project_name":"Alexander-Parker\/youtube_nlp","file_name":"extension_connection.py","full_name":"ExtensionConnection.connect_and_quit","func_name":"connect_and_quit","docstring":"Connects to an running browser and quit immediately.","docstring_tokens":"","code":"@classmethod\ndef connect_and_quit(self):\n \"\"\"Connects to an running browser and quit immediately.\"\"\"\n self._request('%s\/extensions\/firefox\/quit' % _URL)","code_tokens":"","url":970848} +{"project_name":"rudranil723\/mini-main","file_name":"dask.py","full_name":"TqdmCallback.display","func_name":"display","docstring":"Displays in the current cell in Notebooks.","docstring_tokens":"","code":"def display(self):\n \"\"\"Displays in the current cell in Notebooks.\"\"\"\n container = getattr(self.bar, 'container', None)\n if container is None:\n return\n from .notebook import display\n display(container)","code_tokens":"","url":270697} +{"project_name":"intel\/neural-compressor","file_name":"criteria.py","full_name":"PruningCriterion.on_after_optimizer_step","func_name":"on_after_optimizer_step","docstring":"Calculate and store the pruning scores of pruning modules after the optimizer step.","docstring_tokens":"","code":"def on_after_optimizer_step(self):\n \"\"\"Calculate and store the pruning scores of pruning modules after the optimizer step.\"\"\"\n pass","code_tokens":"","url":738040} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"misc.py","full_name":"make_vcs_requirement_url","func_name":"make_vcs_requirement_url","docstring":"Return the URL for a VCS requirement.","docstring_tokens":"","code":"def make_vcs_requirement_url(repo_url, rev, egg_project_name, subdir=None):\n \"\"\"\n Return the URL for a VCS requirement.\n\n Args:\n repo_url: the remote VCS url, with any needed VCS prefix (e.g. \"git+\").\n \"\"\"\n req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)\n if subdir:\n req += '&subdirectory={}'.format(subdir)\n return req","code_tokens":"","url":74816} +{"project_name":"rudranil723\/mini-main","file_name":"query.py","full_name":"QuerySet.exclude","func_name":"exclude","docstring":"Return a new QuerySet instance with NOT (args) ANDed to the existing set.","docstring_tokens":"","code":"def exclude(self, *args, **kwargs):\n \"\"\"\n Return a new QuerySet instance with NOT (args) ANDed to the existing\n set.\n \"\"\"\n return self._filter_or_exclude(True, *args, **kwargs)","code_tokens":"","url":316045} +{"project_name":"triaquae\/triaquae","file_name":"srs.py","full_name":"SpatialReference.local","func_name":"local","docstring":"Returns True if this SpatialReference is local (root node is LOCAL_CS).","docstring_tokens":"","code":"@property\ndef local(self):\n \"\"\"Returns True if this SpatialReference is local (root node is LOCAL_CS).\"\"\"\n return bool(capi.islocal(self.ptr))","code_tokens":"","url":357654} +{"project_name":"awalsh128\/nlp","file_name":"rc_model.py","full_name":"RCModel.get_loss","func_name":"get_loss","docstring":"Compute the loss: $l_{ heta} = -logP(start)\\cdotP(end|start)$ Returns: A LayerOutput object containing loss.","docstring_tokens":"","code":"def get_loss(self, start_prob, end_prob, start_label, end_label):\n \"\"\"\n Compute the loss: $l_{\theta} = -logP(start)\\\\cdotP(end|start)$\n\n Returns:\n A LayerOutput object containing loss.\n \"\"\"\n probs = layer.seq_concat(a=start_prob, b=end_prob)\n labels = layer.seq_concat(a=start_label, b=end_label)\n log_probs = layer.mixed(size=probs.size, act=Act.Log(), bias_attr=False, input=paddle.layer.identity_projection(probs))\n neg_log_probs = layer.slope_intercept(input=log_probs, slope=-1, intercept=0)\n loss = paddle.layer.mixed(size=1, input=paddle.layer.dotmul_operator(a=neg_log_probs, b=labels))\n sum_val = paddle.layer.pooling(input=loss, pooling_type=paddle.pooling.Sum())\n cost = paddle.layer.sum_cost(input=sum_val)\n return cost","code_tokens":"","url":808563} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"vertexbuffer.py","full_name":"AbstractBuffer.unmap","func_name":"unmap","docstring":"Unmap a previously mapped memory block.","docstring_tokens":"","code":"def unmap(self):\n \"\"\"Unmap a previously mapped memory block.\"\"\"\n raise NotImplementedError('abstract')","code_tokens":"","url":76807} +{"project_name":"jason718\/game-feature-learning","file_name":"tools.py","full_name":"SimpleTransformer.set_scale","func_name":"set_scale","docstring":"Set the data scaling.","docstring_tokens":"","code":"def set_scale(self, scale):\n \"\"\"\n Set the data scaling.\n \"\"\"\n self.scale = scale","code_tokens":"","url":199446} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"session_ops.py","full_name":"TensorHandle.eval","func_name":"eval","docstring":"Return the value of the tensor represented by this handle.","docstring_tokens":"","code":"def eval(self):\n \"\"\"Return the value of the tensor represented by this handle.\"\"\"\n if not self._auto_gc_enabled:\n raise TypeError('Persistent tensor %s may have already been deleted.' % self.handle)\n (holder, reader) = _get_handle_reader(self._session.graph, self._handle, self._dtype)\n return self._session.run(reader, feed_dict={holder: self._handle})","code_tokens":"","url":338958} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"test_filter_design.py","full_name":"TestNormalize.test_errors","func_name":"test_errors","docstring":"Test the error cases.","docstring_tokens":"","code":"def test_errors(self):\n \"\"\"Test the error cases.\"\"\"\n assert_raises(ValueError, normalize, [1, 2], 0)\n assert_raises(ValueError, normalize, [1, 2], [[1]])\n assert_raises(ValueError, normalize, [[[1, 2]]], 1)","code_tokens":"","url":77899} +{"project_name":"inovex\/multi2convai","file_name":"vocab.py","full_name":"Vocab.to_dict","func_name":"to_dict","docstring":"Returns vocab as dictionary mapping from texts to ids.","docstring_tokens":"","code":"def to_dict(self) -> Dict[str, int]:\n \"\"\"Returns vocab as dictionary mapping from texts to ids.\"\"\"\n return self._text2id","code_tokens":"","url":643467} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"mailbox.py","full_name":"Mailbox.pop","func_name":"pop","docstring":"Delete the keyed message and return it, or default.","docstring_tokens":"","code":"def pop(self, key, default=None):\n \"\"\"Delete the keyed message and return it, or default.\"\"\"\n try:\n result = self[key]\n except KeyError:\n return default\n self.discard(key)\n return result","code_tokens":"","url":280717} +{"project_name":"aws\/sagemaker-rl-container","file_name":"firehose_producer.py","full_name":"FirehoseProducer.flush_queue","func_name":"flush_queue","docstring":"Grab all the current records in the queue and send them.","docstring_tokens":"","code":"def flush_queue(self):\n \"\"\"Grab all the current records in the queue and send them.\"\"\"\n records = []\n while not self.queue.empty() and len(records) < self.batch_size:\n records.append(self.queue.get())\n if records:\n self.send_records(records)\n self.last_flush = time.time()","code_tokens":"","url":844885} +{"project_name":"CVI-SZU\/CCAM","file_name":"evaluate_utils.py","full_name":"calculate_mIoU","func_name":"calculate_mIoU","docstring":"This function is to calculate precision, recall, and f1-score using tags.","docstring_tokens":"","code":"def calculate_mIoU(pred_mask, gt_mask):\n \"\"\"This function is to calculate precision, recall, and f1-score using tags.\n\n Args:\n pred_mask: \n The type of variable is numpy array.\n\n gt_mask:\n The type of variable is numpy array.\n\n Returns:\n miou:\n miou is meanIU.\n \"\"\"\n inter = np.logical_and(pred_mask, gt_mask)\n union = np.logical_or(pred_mask, gt_mask)\n epsilon = 1e-05\n miou = (np.sum(inter) + epsilon) \/ (np.sum(union) + epsilon)\n return miou * 100","code_tokens":"","url":103354} +{"project_name":"vturrisi\/solo-learn","file_name":"nnbyol.py","full_name":"NNBYOL.find_nn","func_name":"find_nn","docstring":"Finds the nearest neighbor of a sample.","docstring_tokens":"","code":"@torch.no_grad()\ndef find_nn(self, z: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Finds the nearest neighbor of a sample.\n\n Args:\n z (torch.Tensor): a batch of projected features.\n\n Returns:\n Tuple[torch.Tensor, torch.Tensor]:\n indices and projected features of the nearest neighbors.\n \"\"\"\n idx = (z @ self.queue.T).max(dim=1)[1]\n nn = self.queue[idx]\n return (idx, nn)","code_tokens":"","url":393653} +{"project_name":"DYCI2\/Dicy2-python","file_name":"factor_oracle_model.py","full_name":"FactorOracle.learn_sequence","func_name":"learn_sequence","docstring":"Learns (appends) a new sequence in the model.","docstring_tokens":"","code":"def learn_sequence(self, sequence: List[Optional[T]], labels: List[Optional[Dicy2Label]], equiv: Optional[Equiv]=None) -> None:\n \"\"\"\n Learns (appends) a new sequence in the model.\n\n \"\"\"\n if equiv is None:\n equiv = self.equiv\n for (event, label) in zip(sequence, labels):\n self.learn_event(event, label, equiv)","code_tokens":"","url":550320} +{"project_name":"Eric3911\/OpenAGI","file_name":"u2_st.py","full_name":"U2STModel.from_pretrained","func_name":"from_pretrained","docstring":"Build a DeepSpeech2Model model from a pretrained model.","docstring_tokens":"","code":"@classmethod\ndef from_pretrained(cls, dataloader, config, checkpoint_path):\n \"\"\"Build a DeepSpeech2Model model from a pretrained model.\n\n Args:\n dataloader (paddle.io.DataLoader): not used.\n config (yacs.config.CfgNode): model configs\n checkpoint_path (Path or str): the path of pretrained model checkpoint, without extension name\n\n Returns:\n DeepSpeech2Model: The model built from pretrained result.\n \"\"\"\n with UpdateConfig(config):\n config.input_dim = dataloader.collate_fn.feature_size\n config.output_dim = dataloader.collate_fn.vocab_size\n model = cls.from_config(config)\n if checkpoint_path:\n infos = checkpoint.load_parameters(model, checkpoint_path=checkpoint_path)\n logger.info(f'checkpoint info: {infos}')\n layer_tools.summary(model)\n return model","code_tokens":"","url":251423} +{"project_name":"rudranil723\/mini-main","file_name":"register.py","full_name":"Registrar.debug","func_name":"debug","docstring":"Write entries in the registry to setup logging for this clsid.","docstring_tokens":"","code":"def debug(self, cls, levels, format):\n \"\"\"Write entries in the registry to setup logging for this clsid.\"\"\"\n clsid = cls._reg_clsid_\n _debug('CreateKey( %s\\\\CLSID\\\\%s\\\\Logging\"' % (_explain(winreg.HKEY_CLASSES_ROOT), clsid))\n hkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, 'CLSID\\\\%s\\\\Logging' % clsid)\n for item in levels:\n (name, value) = item.split('=')\n v = getattr(logging, value)\n assert isinstance(v, int)\n _debug('SetValueEx(levels, %s)' % levels)\n winreg.SetValueEx(hkey, 'levels', None, winreg.REG_MULTI_SZ, levels)\n if format:\n _debug('SetValueEx(format, %s)' % format)\n winreg.SetValueEx(hkey, 'format', None, winreg.REG_SZ, format)\n else:\n _debug('DeleteValue(format)')\n try:\n winreg.DeleteValue(hkey, 'format')\n except WindowsError as detail:\n if get_winerror(detail) != 2:\n raise","code_tokens":"","url":314477} +{"project_name":"google-research\/scenic","file_name":"optax.py","full_name":"make_schedule","func_name":"make_schedule","docstring":"Creates a schedule dictionary compatible with the `make` function.","docstring_tokens":"","code":"def make_schedule(schedule: Optional[ml_collections.ConfigDict]=None, get_learning_rate_fn: Callable[[ml_collections.ConfigDict], optax.ScalarOrSchedule]=lr_schedules.get_learning_rate_fn) -> List[Tuple[str, str, Tuple[optax.ScalarOrSchedule, float]]]:\n \"\"\"Creates a schedule dictionary compatible with the `make` function.\"\"\"\n if schedule is None:\n schedule = ml_collections.ConfigDict({'all': ml_collections.ConfigDict({'re': '(.*)', 'lr_configs': None})})\n schedule = [(cfg.re, name, cfg.lr_configs) for (name, cfg) in schedule.items()]\n\n def create_schedule(lr_configs):\n if lr_configs is None:\n return (None, None)\n fn = get_learning_rate_fn(ml_collections.ConfigDict({'lr_configs': lr_configs}))\n base_lr = lr_configs.get('base_learning_rate', 1.0)\n return (fn, base_lr)\n schedule = [(re, name, create_schedule(lr_configs)) for (re, name, lr_configs) in schedule]\n return schedule","code_tokens":"","url":847614} +{"project_name":"rudranil723\/mini-main","file_name":"builder.py","full_name":"LookupBuilder.inferGlyphClasses","func_name":"inferGlyphClasses","docstring":"Infers glyph glasses for the GDEF table, such as {\"cedilla\":3}.","docstring_tokens":"","code":"def inferGlyphClasses(self):\n \"\"\"Infers glyph glasses for the GDEF table, such as {\"cedilla\":3}.\"\"\"\n return {}","code_tokens":"","url":317298} +{"project_name":"Speech-Lab-IITM\/CCC-wav2vec-2.0","file_name":"dictionary.py","full_name":"Dictionary.pad_to_multiple_","func_name":"pad_to_multiple_","docstring":"Pad Dictionary size to be a multiple of *padding_factor*.","docstring_tokens":"","code":"def pad_to_multiple_(self, padding_factor):\n \"\"\"Pad Dictionary size to be a multiple of *padding_factor*.\"\"\"\n if padding_factor > 1:\n i = 0\n while len(self) % padding_factor != 0:\n symbol = 'madeupword{:04d}'.format(i)\n self.add_symbol(symbol, n=0)\n i += 1","code_tokens":"","url":103607} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"datastructures.py","full_name":"MultiDict.popitem","func_name":"popitem","docstring":"Pop an item from the dict.","docstring_tokens":"","code":"def popitem(self):\n \"\"\"Pop an item from the dict.\"\"\"\n try:\n item = dict.popitem(self)\n return (item[0], item[1][0])\n except KeyError as e:\n raise exceptions.BadRequestKeyError(str(e))","code_tokens":"","url":161113} +{"project_name":"Edward-CNRG-NTU\/ADLxMLDS2017","file_name":"atari_wrapper.py","full_name":"wrap_deepmind","func_name":"wrap_deepmind","docstring":"Configure environment for DeepMind-style Atari.","docstring_tokens":"","code":"def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):\n \"\"\"Configure environment for DeepMind-style Atari.\n \"\"\"\n if episode_life:\n env = EpisodicLifeEnv(env)\n if 'FIRE' in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env = WarpFrame(env)\n if scale:\n env = ScaledFloatFrame(env)\n if clip_rewards:\n env = ClipRewardEnv(env)\n if frame_stack:\n env = FrameStack(env, 4)\n return env","code_tokens":"","url":396628} +{"project_name":"caiiiac\/Machine-Learning-with-Python","file_name":"animation.py","full_name":"Animation.new_frame_seq","func_name":"new_frame_seq","docstring":"Creates a new sequence of frame information.","docstring_tokens":"","code":"def new_frame_seq(self):\n \"\"\"Creates a new sequence of frame information.\"\"\"\n return iter(self._framedata)","code_tokens":"","url":714870} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_affinity_propagation.py","full_name":"test_affinity_propagation_precomputed","func_name":"test_affinity_propagation_precomputed","docstring":"Check equality of precomputed affinity matrix to internally computed affinity matrix.","docstring_tokens":"","code":"def test_affinity_propagation_precomputed():\n \"\"\"Check equality of precomputed affinity matrix to internally computed affinity\n matrix.\n \"\"\"\n S = -euclidean_distances(X, squared=True)\n preference = np.median(S) * 10\n af = AffinityPropagation(preference=preference, affinity='precomputed', random_state=28)\n labels_precomputed = af.fit(S).labels_\n af = AffinityPropagation(preference=preference, verbose=True, random_state=37)\n labels = af.fit(X).labels_\n assert_array_equal(labels, labels_precomputed)\n cluster_centers_indices = af.cluster_centers_indices_\n n_clusters_ = len(cluster_centers_indices)\n assert np.unique(labels).size == n_clusters_\n assert n_clusters == n_clusters_","code_tokens":"","url":363487} +{"project_name":"AboudyKreidieh\/h-baselines","file_name":"ant_maze_env.py","full_name":"AntMazeEnv.action_space","func_name":"action_space","docstring":"Return the properties of the action space.","docstring_tokens":"","code":"@property\ndef action_space(self):\n \"\"\"Return the properties of the action space.\"\"\"\n return self.wrapped_env.action_space","code_tokens":"","url":573841} +{"project_name":"famura\/SimuRLacra","file_name":"svpg.py","full_name":"OptimizerHook.step","func_name":"step","docstring":"Store the args of the mocked call in the queue.","docstring_tokens":"","code":"def step(self, *args, **kwargs):\n \"\"\"Store the args of the mocked call in the queue.\"\"\"\n self.buffer.append((args, kwargs, to.clone(self.particle.policy.param_values).detach(), to.clone(self.particle.policy.param_grad).detach()))","code_tokens":"","url":883573} +{"project_name":"MaZhiyuanBUAA\/Seq2BFforDialogue","file_name":"data_utils.py","full_name":"prepare_dialog_data","func_name":"prepare_dialog_data","docstring":"Get dialog data into data_dir, create vocabularies and tokenize data.","docstring_tokens":"","code":"def prepare_dialog_data(data_dir, vocabulary_size):\n \"\"\"Get dialog data into data_dir, create vocabularies and tokenize data.\n\n Args:\n data_dir: directory in which the data sets will be stored.\n vocabulary_size: size of the English vocabulary to create and use.\n\n Returns:\n A tuple of 3 elements:\n (1) path to the token-ids for chat training data-set,\n (2) path to the token-ids for chat development data-set,\n (3) path to the chat vocabulary file\n \"\"\"\n train_path = get_dialog_train_set_path(data_dir)\n dev_path = get_dialog_dev_set_path(data_dir)\n vocab_path = os.path.join(data_dir, 'vocab%d.in' % vocabulary_size)\n create_vocabulary(vocab_path, train_path + '.in', vocabulary_size)\n train_ids_path = train_path + '.ids%d.in' % vocabulary_size\n data_to_token_ids(train_path + '.in', train_ids_path, vocab_path)\n dev_ids_path = dev_path + '.ids%d.in' % vocabulary_size\n data_to_token_ids(dev_path + '.in', dev_ids_path, vocab_path)\n return (train_ids_path, dev_ids_path, vocab_path)","code_tokens":"","url":876364} +{"project_name":"yinyunie\/ScenePriors","file_name":"rotation_conversions.py","full_name":"random_rotations","func_name":"random_rotations","docstring":"Generate random rotations as 3x3 rotation matrices.","docstring_tokens":"","code":"def random_rotations(n: int, dtype: Optional[torch.dtype]=None, device: Optional[Device]=None) -> torch.Tensor:\n \"\"\"\n Generate random rotations as 3x3 rotation matrices.\n\n Args:\n n: Number of rotation matrices in a batch to return.\n dtype: Type to return.\n device: Device of returned tensor. Default: if None,\n uses the current device for the default tensor type.\n\n Returns:\n Rotation matrices as tensor of shape (n, 3, 3).\n \"\"\"\n quaternions = random_quaternions(n, dtype=dtype, device=device)\n return quaternion_to_matrix(quaternions)","code_tokens":"","url":329921} +{"project_name":"tomcatmanager\/tomcatmanager","file_name":"interactive_tomcat_manager.py","full_name":"InteractiveTomcatManager.help_undeploy","func_name":"help_undeploy","docstring":"Help for the 'undeploy' command.","docstring_tokens":"","code":"def help_undeploy(self):\n \"\"\"Help for the 'undeploy' command.\"\"\"\n self.show_help_from(self.undeploy_parser)","code_tokens":"","url":355553} +{"project_name":"juliancervos\/stdp-nmnist","file_name":"davis.py","full_name":"Davis.progress","func_name":"progress","docstring":"Simple progress indicator for the download of the dataset.","docstring_tokens":"","code":"@staticmethod\ndef progress(count, block_size, total_size):\n \"\"\"\n Simple progress indicator for the download of the dataset.\n \"\"\"\n global start_time\n if count == 0:\n start_time = time.time()\n return\n duration = time.time() - start_time\n progress_size = int(count * block_size)\n speed = int(progress_size \/ (1024 * duration))\n percent = min(int(count * block_size * 100 \/ total_size), 100)\n sys.stdout.write('\\r...%d%%, %d MB, %d KB\/s, %d seconds passed' % (percent, progress_size \/ (1024 * 1024), speed, duration))\n sys.stdout.flush()","code_tokens":"","url":383963} +{"project_name":"Ikomia-dev\/IkomiaApi","file_name":"datadictIO.py","full_name":"DataDictIO.clear_data","func_name":"clear_data","docstring":"Clear whole data dict.","docstring_tokens":"","code":"def clear_data(self):\n \"\"\"\n Clear whole data dict.\n \"\"\"\n self.data.clear()","code_tokens":"","url":598666} +{"project_name":"lorenlugosch\/end-to-end-SLU","file_name":"data.py","full_name":"one_hot","func_name":"one_hot","docstring":"letters : LongTensor of shape (batch size, sequence length) S : integer Convert batch of integer letter indices to one-hot vectors of dimension S (# of possible letters).","docstring_tokens":"","code":"def one_hot(letters, S):\n \"\"\"\n\tletters : LongTensor of shape (batch size, sequence length)\n\tS : integer\n\tConvert batch of integer letter indices to one-hot vectors of dimension S (# of possible letters).\n\t\"\"\"\n out = torch.zeros(letters.shape[0], letters.shape[1], S)\n for i in range(0, letters.shape[0]):\n for t in range(0, letters.shape[1]):\n out[i, t, letters[i, t]] = 1\n return out","code_tokens":"","url":561755} +{"project_name":"guskarls\/dfl-pens","file_name":"train_utils.py","full_name":"save_checkpoints","func_name":"save_checkpoints","docstring":"Saves checkpoints corresponding to the models that reach a higher-than-previous accuracy.","docstring_tokens":"","code":"def save_checkpoints(args, clients, histories, comround, plot_title, moving_average_window_size, start_date):\n \"\"\"\n Saves checkpoints corresponding to the models that reach a higher-than-previous accuracy.\n \"\"\"\n checkpoints = [torch.load(f'data\/output\/{start_date}\/checkpoints\/checkpoint{args.pid}\/{plot_title}\/client_{c}.tar') for c in range(len(clients))]\n for (c, client) in enumerate(clients):\n checkpoint = checkpoints[c]\n current_moving_average = moving_average(histories[c]['val_accs'], moving_average_window_size)[-1]\n current_accuracy = np.average(histories[c]['val_accs'][-moving_average_window_size:])\n if current_accuracy > checkpoint['val_acc'] and checkpoint['stopped_early'] == False:\n torch.save({'communication_round': comround, 'stopped_early': False, 'model_state_dict': client.model.state_dict(), 'val_acc': current_accuracy}, f'data\/output\/{start_date}\/checkpoints\/checkpoint{args.pid}\/{plot_title}\/client_{c}.tar')\n return checkpoints","code_tokens":"","url":550053} +{"project_name":"googleapis\/python-aiplatform","file_name":"client.py","full_name":"FeaturestoreOnlineServingServiceClient.parse_entity_type_path","func_name":"parse_entity_type_path","docstring":"Parses a entity_type path into its component segments.","docstring_tokens":"","code":"@staticmethod\ndef parse_entity_type_path(path: str) -> Dict[str, str]:\n \"\"\"Parses a entity_type path into its component segments.\"\"\"\n m = re.match('^projects\/(?P.+?)\/locations\/(?P.+?)\/featurestores\/(?P.+?)\/entityTypes\/(?P.+?)$', path)\n return m.groupdict() if m else {}","code_tokens":"","url":810536} +{"project_name":"facebookresearch\/fvcore","file_name":"test_transform.py","full_name":"TestTransforms.VFlipTransform_img_gt","func_name":"VFlipTransform_img_gt","docstring":"Given the input array, return the expected output array and shape after applying the vertical flip transformation.","docstring_tokens":"","code":"@staticmethod\ndef VFlipTransform_img_gt(imgs, *args) -> Tuple[np.ndarray, list]:\n \"\"\"\n Given the input array, return the expected output array and shape after\n applying the vertical flip transformation.\n Args:\n imgs (array): image(s) array before the transform.\n args (list): list of arguments. Details can be found in test case.\n Returns:\n img (array): expected output array after apply the transformation.\n (list): expected shape of the output array.\n \"\"\"\n if len(imgs.shape) <= 3:\n return (imgs[::-1, :], imgs.shape)\n else:\n return (imgs[:, ::-1, :], imgs.shape)","code_tokens":"","url":566020} +{"project_name":"eric-erki\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"visitor.py","full_name":"MethodContent.acceptIf","func_name":"acceptIf","docstring":"Accept and process an if statement.","docstring_tokens":"","code":"def acceptIf(self, node, memo):\n \"\"\" Accept and process an if statement. \"\"\"\n children = node.children\n ifStat = self.factory.statement('if', fs=FS.lsrc, parent=self)\n ifStat.expr.walk(children[0], memo)\n if node.children[1].type == tokens.EXPR:\n ifBlock = self.factory.expr(parent=ifStat)\n ifBlock.walk(node.children[1], memo)\n else:\n ifBlock = self.factory.methodContent(parent=self)\n ifBlock.walk(node.children[1], memo)\n if len(children) == 3:\n nextNode = children[2]\n nextType = nextNode.type\n while nextType == tokens.IF:\n nextStat = self.factory.statement('elif', fs=FS.lsrc, parent=self)\n nextStat.expr.walk(nextNode.children[0], memo)\n if nextNode.children[1].type == tokens.EXPR:\n nextBlock = self.factory.expr(parent=nextStat)\n else:\n nextBlock = self.factory.methodContent(parent=self)\n nextBlock.walk(nextNode.children[1], memo)\n try:\n nextNode = nextNode.children[2]\n except (IndexError,):\n nextType = None\n else:\n nextType = nextNode.type\n if nextType == tokens.EXPR:\n elseStat = self.factory.statement('else', fs=FS.lc, parent=self)\n elseBlock = self.factory.expr(parent=elseStat)\n elseBlock.walk(nextNode, memo)\n elif nextType:\n elseStat = self.factory.statement('else', fs=FS.lc, parent=self)\n if nextNode.children:\n self.factory.methodContent(parent=self).walk(nextNode, memo)\n else:\n self.factory.expr(left='pass', parent=elseStat)","code_tokens":"","url":11031} +{"project_name":"hamza-murad\/AALU","file_name":"speech_to_text_v1.py","full_name":"RecognitionJobs.from_dict","func_name":"from_dict","docstring":"Initialize a RecognitionJobs object from a json dictionary.","docstring_tokens":"","code":"@classmethod\ndef from_dict(cls, _dict: Dict) -> 'RecognitionJobs':\n \"\"\"Initialize a RecognitionJobs object from a json dictionary.\"\"\"\n args = {}\n valid_keys = ['recognitions']\n bad_keys = set(_dict.keys()) - set(valid_keys)\n if bad_keys:\n raise ValueError('Unrecognized keys detected in dictionary for class RecognitionJobs: ' + ', '.join(bad_keys))\n if 'recognitions' in _dict:\n args['recognitions'] = [RecognitionJob._from_dict(x) for x in _dict.get('recognitions')]\n else:\n raise ValueError(\"Required property 'recognitions' not present in RecognitionJobs JSON\")\n return cls(**args)","code_tokens":"","url":6057} +{"project_name":"flavioschneider\/rl-transfer-","file_name":"wrappers.py","full_name":"AutoStopEnv.reset","func_name":"reset","docstring":"Reset the wrapped environment.","docstring_tokens":"","code":"def reset(self, **kwargs):\n \"\"\"Reset the wrapped environment.\n\n Args:\n **kwargs: Keyword arguments.\n\n Returns:\n np.ndarray: Initial observation.\n \"\"\"\n return self.env.reset(**kwargs)","code_tokens":"","url":861654} +{"project_name":"ArdaGunay99\/Key_Detection_Unsupervised_Learning","file_name":"backend_bases.py","full_name":"GraphicsContextBase.restore","func_name":"restore","docstring":"Restore the graphics context from the stack - needed only for backends that save graphics contexts on a stack.","docstring_tokens":"","code":"def restore(self):\n \"\"\"\n Restore the graphics context from the stack - needed only\n for backends that save graphics contexts on a stack.\n \"\"\"","code_tokens":"","url":256663} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"mst_ops_test.py","full_name":"MstOpsTest.testLogPartitionFunctionOneTreeScaled","func_name":"testLogPartitionFunctionOneTreeScaled","docstring":"Tests the log partition function with one feasible tree.","docstring_tokens":"","code":"def testLogPartitionFunctionOneTreeScaled(self):\n \"\"\"Tests the log partition function with one feasible tree.\"\"\"\n with self.test_session():\n for forest in [False, True]:\n pad = 12345.6\n scores = tf.constant([[[2, pad, pad], [pad, pad, pad], [pad, pad, pad]], [[3, 0, pad], [5, 0, pad], [pad, pad, pad]], [[7, 0, 0], [11, 0, 0], [0, 13, 0]]], tf.float64)\n scores = tf.log(scores)\n num_nodes = tf.constant([1, 2, 3], tf.int32)\n log_partition_functions = mst_ops.log_partition_function(num_nodes, scores, forest=forest)\n self.assertAlmostEqual(tf.exp(log_partition_functions[0]).eval(), 2.0)\n self.assertAlmostEqual(tf.exp(log_partition_functions[1]).eval(), 3.0 * 5.0)\n self.assertAlmostEqual(tf.exp(log_partition_functions[2]).eval(), 7.0 * 11.0 * 13.0)","code_tokens":"","url":760187} +{"project_name":"sentinel-hub\/eo-learn","file_name":"core_tasks.py","full_name":"MapFeatureTask.map_method","func_name":"map_method","docstring":"A function that will be applied to the input features.","docstring_tokens":"","code":"def map_method(self, feature: Any) -> Any:\n \"\"\"A function that will be applied to the input features.\"\"\"\n raise NotImplementedError('map_method should be overridden.')","code_tokens":"","url":562533} +{"project_name":"voxel51\/fiftyone","file_name":"stages.py","full_name":"SortBy.field_or_expr","func_name":"field_or_expr","docstring":"The field or expression to sort by.","docstring_tokens":"","code":"@property\ndef field_or_expr(self):\n \"\"\"The field or expression to sort by.\"\"\"\n return self._field_or_expr","code_tokens":"","url":583358} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"_base.py","full_name":"as_completed","func_name":"as_completed","docstring":"An iterator over the given futures that yields each as it completes.","docstring_tokens":"","code":"def as_completed(fs, timeout=None):\n \"\"\"An iterator over the given futures that yields each as it completes.\n\n Args:\n fs: The sequence of Futures (possibly created by different Executors) to\n iterate over.\n timeout: The maximum number of seconds to wait. If None, then there\n is no limit on the wait time.\n\n Returns:\n An iterator that yields the given Futures as they complete (finished or\n cancelled). If any given Futures are duplicated, they will be returned\n once.\n\n Raises:\n TimeoutError: If the entire result iterator could not be generated\n before the given timeout.\n \"\"\"\n if timeout is not None:\n end_time = timeout + time.time()\n fs = set(fs)\n with _AcquireFutures(fs):\n finished = set((f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]))\n pending = fs - finished\n waiter = _create_and_install_waiters(fs, _AS_COMPLETED)\n try:\n yield from finished\n while pending:\n if timeout is None:\n wait_timeout = None\n else:\n wait_timeout = end_time - time.time()\n if wait_timeout < 0:\n raise TimeoutError('%d (of %d) futures unfinished' % (len(pending), len(fs)))\n waiter.event.wait(wait_timeout)\n with waiter.lock:\n finished = waiter.finished_futures\n waiter.finished_futures = []\n waiter.event.clear()\n for future in finished:\n yield future\n pending.remove(future)\n finally:\n for f in fs:\n with f._condition:\n f._waiters.remove(waiter)","code_tokens":"","url":282129} +{"project_name":"drprojects\/superpoint_transformer","file_name":"sparse.py","full_name":"indices_to_pointers","func_name":"indices_to_pointers","docstring":"Convert pre-sorted dense indices to CSR format.","docstring_tokens":"","code":"def indices_to_pointers(indices: torch.LongTensor):\n \"\"\"Convert pre-sorted dense indices to CSR format.\"\"\"\n device = indices.device\n assert len(indices.shape) == 1, 'Only 1D indices are accepted.'\n assert indices.shape[0] >= 1, 'At least one group index is required.'\n assert is_dense(indices), 'Indices must be dense'\n order = torch.arange(indices.shape[0], device=device)\n if not is_sorted(indices):\n (indices, order) = indices.sort()\n pointers = torch.cat([torch.LongTensor([0]).to(device), torch.where(indices[1:] > indices[:-1])[0] + 1, torch.LongTensor([indices.shape[0]]).to(device)])\n return (pointers, order)","code_tokens":"","url":880937} +{"project_name":"ml-tooling\/opyrator","file_name":"core.py","full_name":"get_input_type","func_name":"get_input_type","docstring":"Returns the input type of a given function (callable).","docstring_tokens":"","code":"def get_input_type(func: Callable) -> Type:\n \"\"\"Returns the input type of a given function (callable).\n\n Args:\n func: The function for which to get the input type.\n\n Raises:\n ValueError: If the function does not have a valid input type annotation.\n \"\"\"\n type_hints = get_type_hints(func)\n if 'input' not in type_hints:\n raise ValueError('The callable MUST have a parameter with the name `input` with typing annotation. For example: `def my_opyrator(input: InputModel) -> OutputModel:`.')\n input_type = type_hints['input']\n if not is_compatible_type(input_type):\n raise ValueError('The `input` parameter MUST be a subclass of the Pydantic BaseModel or a list of Pydantic models.')\n return input_type","code_tokens":"","url":776357} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"cgi.py","full_name":"FieldStorage.getvalue","func_name":"getvalue","docstring":"Dictionary style get() method, including 'value' lookup.","docstring_tokens":"","code":"def getvalue(self, key, default=None):\n \"\"\"Dictionary style get() method, including 'value' lookup.\"\"\"\n if key in self:\n value = self[key]\n if isinstance(value, list):\n return [x.value for x in value]\n else:\n return value.value\n else:\n return default","code_tokens":"","url":280171} +{"project_name":"tensorflow\/data-validation","file_name":"feature_skew_detector.py","full_name":"match_stats_iterator","func_name":"match_stats_iterator","docstring":"Reads records written by match_stats_sink.","docstring_tokens":"","code":"def match_stats_iterator(input_pattern_prefix) -> Iterator[feature_skew_results_pb2.MatchStats]:\n \"\"\"Reads records written by match_stats_sink.\"\"\"\n return artifacts_io_impl.default_record_reader(input_pattern_prefix + '*-of-*', feature_skew_results_pb2.MatchStats)","code_tokens":"","url":497447} +{"project_name":"ilya16\/MultINN","file_name":"training.py","full_name":"LossAccumulator.num_bad","func_name":"num_bad","docstring":"Returns the number of bad losses.","docstring_tokens":"","code":"def num_bad(self):\n \"\"\"Returns the number of bad losses.\"\"\"\n return self._num_nan + self._num_posinf + self._num_neginf","code_tokens":"","url":644394} +{"project_name":"voxel51\/fiftyone","file_name":"document.py","full_name":"DocumentView.save","func_name":"save","docstring":"Saves the document view to the database.","docstring_tokens":"","code":"def save(self):\n \"\"\"Saves the document view to the database.\"\"\"\n self._save()\n self._reload_parents()","code_tokens":"","url":582993} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"primitive.py","full_name":"Primitive.geom","func_name":"geom","docstring":"The geom belonging to this prop.","docstring_tokens":"","code":"@property\ndef geom(self):\n \"\"\"The geom belonging to this prop.\"\"\"\n return self._geom","code_tokens":"","url":439926} +{"project_name":"eora-ai\/torchok","file_name":"classification_head.py","full_name":"ClassificationHead.forward","func_name":"forward","docstring":"Forward single input ``x``.","docstring_tokens":"","code":"def forward(self, x: Tensor, target: Optional[Tensor]=None) -> Tensor:\n \"\"\"Forward single input ``x``.\n\n Args:\n x: Input tensor.\n \"\"\"\n x = super(ClassificationHead, self).forward(x, target)\n if self.out_channels == 1:\n x = x[..., 0]\n return x","code_tokens":"","url":903301} +{"project_name":"akshitsarin\/Udacity-AI-Nanodegree","file_name":"logic.py","full_name":"PropKB.tell","func_name":"tell","docstring":"Add the sentence's clauses to the KB.","docstring_tokens":"","code":"def tell(self, sentence):\n \"\"\"Add the sentence's clauses to the KB.\"\"\"\n self.clauses.extend(conjuncts(to_cnf(sentence)))","code_tokens":"","url":427404} +{"project_name":"feast-dev\/feast","file_name":"field.py","full_name":"Field.from_proto","func_name":"from_proto","docstring":"Creates a Field object from a protobuf representation.","docstring_tokens":"","code":"@classmethod\ndef from_proto(cls, field_proto: FieldProto):\n \"\"\"\n Creates a Field object from a protobuf representation.\n\n Args:\n field_proto: FieldProto protobuf object\n \"\"\"\n value_type = ValueType(field_proto.value_type)\n return cls(name=field_proto.name, dtype=from_value_type(value_type=value_type), tags=dict(field_proto.tags), description=field_proto.description)","code_tokens":"","url":544269} +{"project_name":"liber145\/rlpack","file_name":"utils.py","full_name":"EnvironmentWrapper.put_srd","func_name":"put_srd","docstring":"Put state, reward, done to agent, non-blocking.","docstring_tokens":"","code":"def put_srd(self, state, reward, done):\n \"\"\"Put state, reward, done to agent, non-blocking.\"\"\"\n self.srd_queue.put((state, reward, done))","code_tokens":"","url":825056} +{"project_name":"jwyang\/fpn.pytorch","file_name":"net_utils.py","full_name":"apply_mask","func_name":"apply_mask","docstring":"Apply the given mask to the image.","docstring_tokens":"","code":"def apply_mask(image, mask, nomask, color, alpha=0.5):\n \"\"\"Apply the given mask to the image.\n \"\"\"\n mask[nomask != 0] = 0\n for c in range(3):\n image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - alpha) + alpha * color[c] * 255, image[:, :, c])\n return image","code_tokens":"","url":564300} +{"project_name":"alteia-ai\/ICSS","file_name":"metrics.py","full_name":"rectangle_union","func_name":"rectangle_union","docstring":"Computes union between two recangles.","docstring_tokens":"","code":"def rectangle_union(a, b):\n \"\"\"Computes union between two recangles.\"\"\"\n x = min(a[0], b[0])\n y = min(a[1], b[1])\n w = max(a[0] + a[2], b[0] + b[2]) - x\n h = max(a[1] + a[3], b[1] + b[3]) - y\n return (x, y, w, h)","code_tokens":"","url":597023} +{"project_name":"farazBhatti\/Human-Body-Measurements-using--","file_name":"RunModel.py","full_name":"RunModel.predict_dict","func_name":"predict_dict","docstring":"images: num_batch, img_size, img_size, 3 Preprocessed to range [-1, 1] Runs the model with images.","docstring_tokens":"","code":"def predict_dict(self, images):\n \"\"\"\n images: num_batch, img_size, img_size, 3\n Preprocessed to range [-1, 1]\n Runs the model with images.\n \"\"\"\n feed_dict = {self.images_pl: images}\n fetch_dict = {'joints': self.all_kps[-1], 'verts': self.all_verts[-1], 'cams': self.all_cams[-1], 'joints3d': self.all_Js[-1], 'theta': self.final_thetas[-1]}\n results = self.sess.run(fetch_dict, feed_dict)\n joints = results['joints']\n results['joints'] = (joints + 1) * 0.5 * self.img_size\n return results","code_tokens":"","url":571078} +{"project_name":"LLNL\/Abmarl","file_name":"multi_corridor.py","full_name":"MultiCorridor.get_obs","func_name":"get_obs","docstring":"Agents observe their own position and if the squares to the left and right are occupied by other agents.","docstring_tokens":"","code":"def get_obs(self, agent_id, **kwargs):\n \"\"\"\n Agents observe their own position and if the squares to the left and right\n are occupied by other agents.\n \"\"\"\n agent_position = self.agents[agent_id].position\n if agent_position == 0 or self.corridor[agent_position - 1] is None:\n left = False\n else:\n left = True\n if agent_position == self.end - 1 or self.corridor[agent_position + 1] is None:\n right = False\n else:\n right = True\n return {'position': np.array([agent_position]), 'left': np.array([int(left)]), 'right': np.array([int(right)])}","code_tokens":"","url":405650} +{"project_name":"intel\/neural-compressor","file_name":"weight_only.py","full_name":"check_op_support_status","func_name":"check_op_support_status","docstring":"Check whether weight-only op is supported.","docstring_tokens":"","code":"def check_op_support_status():\n \"\"\"Check whether weight-only op is supported.\"\"\"\n input_tensor = helper.make_tensor_value_info('input', 1, [1, 32])\n output_tensor = helper.make_tensor_value_info('output', 1, [1, 64])\n initializers = []\n packed_weight = np.random.randint(0, high=16, size=(64, 1, 16), dtype='uint8')\n initializers.append(onnx.helper.make_tensor('weight', 2, packed_weight.shape, packed_weight.flatten().tolist()))\n scale = np.random.random((64, 1)).astype('float32')\n initializers.append(onnx.helper.make_tensor('scale', 1, scale.shape, scale.flatten().tolist()))\n kwargs = {}\n kwargs['K'] = 32\n kwargs['N'] = 64\n kwargs['bits'] = 4\n kwargs['block_size'] = 32\n node = onnx.helper.make_node('MatMulWithQuantWeight', inputs=['input', 'weight', 'scale'], outputs=['output'], name='test', domain='com.microsoft', **kwargs)\n global WEIGHT_ONLY_OP_SUPPORTED\n graph = helper.make_graph([node], 'test', [input_tensor], [output_tensor], initializer=initializers)\n model = helper.make_model(graph)\n try:\n ort.InferenceSession(model.SerializeToString(), providers=['CPUExecutionProvider'])\n WEIGHT_ONLY_OP_SUPPORTED = True\n except:\n WEIGHT_ONLY_OP_SUPPORTED = False","code_tokens":"","url":737492} +{"project_name":"ifwe\/digsby","file_name":"emailpanels.py","full_name":"EmailList.OnMouseMotion","func_name":"OnMouseMotion","docstring":"Select the email and show links when mouse passes over an item.","docstring_tokens":"","code":"def OnMouseMotion(self, event):\n \"\"\"Select the email and show links when mouse passes over an item.\"\"\"\n i = self.HitTest(event.Position)\n if self.Selection != i:\n oldSelection = self.Selection\n self.Selection = i\n if self.Selection == -1:\n self.linkage.Show(False)\n else:\n self.linkage.Show(True)\n if oldSelection >= 0:\n self.RefreshLine(oldSelection)\n if self.Selection >= 0:\n self.RefreshLine(self.Selection)","code_tokens":"","url":185451} +{"project_name":"microsoft\/maro","file_name":"cim_data_container.py","full_name":"CimBaseDataContainer.port_number","func_name":"port_number","docstring":"int: Number of ports.","docstring_tokens":"","code":"@property\ndef port_number(self) -> int:\n \"\"\"int: Number of ports.\"\"\"\n return len(self._data_collection.port_settings)","code_tokens":"","url":628409} +{"project_name":"datature\/portal","file_name":"file.py","full_name":"generate_thumbnail","func_name":"generate_thumbnail","docstring":"Create small thumbnail to be used by Portal frontend.","docstring_tokens":"","code":"def generate_thumbnail(path, filename):\n \"\"\"Create small thumbnail to be used by Portal frontend.\"\"\"\n if not allowed_file(filename):\n raise PortalError(Errors.INVALIDFILETYPE, filename)\n thumb_bytes = None\n if allowed_video(filename):\n threshold = 1\n vcap = cv2.VideoCapture(path)\n width = vcap.get(cv2.CAP_PROP_FRAME_WIDTH)\n height = vcap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n aspect_ratio = width \/ height\n if width > height:\n height = int(500 \/ aspect_ratio)\n width = 500\n else:\n height = 500\n width = int(aspect_ratio * 500)\n (res, image_ar) = vcap.read()\n while image_ar.mean() < threshold and res:\n (res, image_ar) = vcap.read()\n image_ar = cv2.resize(image_ar, (width, height), 0, 0, cv2.INTER_LINEAR)\n (res, image_buf) = cv2.imencode('.jpeg', image_ar)\n thumb_bytes = image_buf.tobytes()\n else:\n image = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n width = image.shape[1]\n height = image.shape[0]\n aspect_ratio = width \/ height\n dsize = (int(aspect_ratio * 500), 500)\n if width > height:\n dsize = (500, int(500 \/ aspect_ratio))\n image_resize = cv2.resize(image, dsize)\n (is_success, image_buf) = cv2.imencode('.jpeg', image_resize)\n thumb_bytes = image_buf.tobytes()\n image_buffer = BytesIO()\n if thumb_bytes:\n image_buffer.write(thumb_bytes)\n image_buffer.seek(0)\n return image_buffer","code_tokens":"","url":820996} +{"project_name":"thaines\/helit","file_name":"corpus.py","full_name":"Corpus.getAlpha","func_name":"getAlpha","docstring":"Returns the current alpha value.","docstring_tokens":"","code":"def getAlpha(self):\n \"\"\"Returns the current alpha value.\"\"\"\n return self.alpha","code_tokens":"","url":592332} +{"project_name":"phausamann\/sklearn-xarray","file_name":"_numpy_groupies_np.py","full_name":"fill_untouched","func_name":"fill_untouched","docstring":"any elements of ret not indexed by idx are set to fill_value.","docstring_tokens":"","code":"def fill_untouched(idx, ret, fill_value):\n \"\"\"any elements of ret not indexed by idx are set to fill_value.\"\"\"\n untouched = np.ones_like(ret, dtype=bool)\n untouched[idx] = False\n ret[untouched] = fill_value","code_tokens":"","url":884944} +{"project_name":"tum-pbs\/PhiFlow","file_name":"_field_math.py","full_name":"curl","func_name":"curl","docstring":"Computes the finite-difference curl of the give 2D `StaggeredGrid`.","docstring_tokens":"","code":"def curl(field: Grid, type: type=CenteredGrid):\n \"\"\" Computes the finite-difference curl of the give 2D `StaggeredGrid`. \"\"\"\n assert field.spatial_rank in (2, 3), 'curl is only defined in 2 and 3 spatial dimensions.'\n if isinstance(field, CenteredGrid) and field.spatial_rank == 2:\n if 'vector' not in field.shape and type == StaggeredGrid:\n grad = math.spatial_gradient(field.values, dx=field.dx, difference='forward', padding=None, stack_dim=channel('vector'))\n result = grad.vector[::-1] * (1, -1)\n bounds = Box(field.bounds.lower + 0.5 * field.dx, field.bounds.upper - 0.5 * field.dx)\n return StaggeredGrid(result, bounds=bounds, extrapolation=field.extrapolation.spatial_gradient())\n if 'vector' in field.shape and type == CenteredGrid:\n (x, y) = field.shape.spatial.names\n vy_dx = math.spatial_gradient(field.values.vector[1], dx=field.dx.vector[0], padding=field.extrapolation, dims=x, stack_dim=None)\n vx_dy = math.spatial_gradient(field.values.vector[0], dx=field.dx.vector[1], padding=field.extrapolation, dims=y, stack_dim=None)\n c = vy_dx - vx_dy\n return field.with_values(c)\n elif isinstance(field, StaggeredGrid) and field.spatial_rank == 2:\n if type == CenteredGrid:\n values = bake_extrapolation(field).values\n x_padded = math.pad(values.vector['x'], {'y': (1, 1)}, field.extrapolation)\n y_padded = math.pad(values.vector['y'], {'x': (1, 1)}, field.extrapolation)\n vx_dy = math.spatial_gradient(x_padded, field.dx, 'forward', None, dims='y', stack_dim=None)\n vy_dx = math.spatial_gradient(y_padded, field.dx, 'forward', None, dims='x', stack_dim=None)\n result = vy_dx - vx_dy\n return CenteredGrid(result, field.extrapolation.spatial_gradient(), bounds=field.bounds)\n raise NotImplementedError()","code_tokens":"","url":768795} +{"project_name":"MolecularAI\/Siamese-RNN-Self-Attention","file_name":"cluster.py","full_name":"Cluster.make_clusters","func_name":"make_clusters","docstring":"The DataFrame is handled so that clusters can be prepared.","docstring_tokens":"","code":"def make_clusters(self):\n \"\"\"\n The DataFrame is handled so that clusters can be prepared.\n \n \"\"\"\n self.clusters = self.cluster_fps(self.fps)\n self.filtered_clusters = self._remove_clusters(self.clusters)\n return self.filtered_clusters","code_tokens":"","url":350311} +{"project_name":"triaquae\/triaquae","file_name":"uploadhandler.py","full_name":"MemoryFileUploadHandler.handle_raw_input","func_name":"handle_raw_input","docstring":"Use the content_length to signal whether or not this handler should be in use.","docstring_tokens":"","code":"def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):\n \"\"\"\n Use the content_length to signal whether or not this handler should be in use.\n \"\"\"\n if content_length > settings.FILE_UPLOAD_MAX_MEMORY_SIZE:\n self.activated = False\n else:\n self.activated = True","code_tokens":"","url":358301} +{"project_name":"TengXiaoDai\/DistributedCrawling","file_name":"random.py","full_name":"Random.getstate","func_name":"getstate","docstring":"Return internal state; can be passed to setstate() later.","docstring_tokens":"","code":"def getstate(self):\n \"\"\"Return internal state; can be passed to setstate() later.\"\"\"\n return (self.VERSION, super().getstate(), self.gauss_next)","code_tokens":"","url":187964} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"train.py","full_name":"make_resolution_schedule","func_name":"make_resolution_schedule","docstring":"Returns an object of `ResolutionSchedule`.","docstring_tokens":"","code":"def make_resolution_schedule(**kwargs):\n \"\"\"Returns an object of `ResolutionSchedule`.\"\"\"\n return networks.ResolutionSchedule(start_resolutions=(kwargs['start_height'], kwargs['start_width']), scale_base=kwargs['scale_base'], num_resolutions=kwargs['num_resolutions'])","code_tokens":"","url":762938} +{"project_name":"gilis-rnd\/openNMT-arabic-transfer-learning","file_name":"vid_feature_extractor.py","full_name":"batch","func_name":"batch","docstring":"Collate frames into batches of equal length.","docstring_tokens":"","code":"def batch(dset, batch_size):\n \"\"\"Collate frames into batches of equal length.\"\"\"\n batch = [[], [], []]\n batch_ct = 0\n for seq in dset:\n for (path, idx, img) in seq:\n if batch_ct == batch_size:\n collate_tensor(batch)\n yield batch\n batch = [[], [], []]\n batch_ct = 0\n batch[0].append(path)\n batch[1].append(idx)\n batch[2].append(img)\n batch_ct += 1\n if batch_ct != 0:\n collate_tensor(batch)\n yield batch","code_tokens":"","url":757311} +{"project_name":"Alexander-Parker\/youtube_nlp","file_name":"mobile.py","full_name":"Mobile.context","func_name":"context","docstring":"returns the current context (Native or WebView).","docstring_tokens":"","code":"@property\ndef context(self):\n \"\"\"\n returns the current context (Native or WebView).\n \"\"\"\n return self._driver.execute(Command.CURRENT_CONTEXT_HANDLE)","code_tokens":"","url":970925} +{"project_name":"apeterswu\/RL4NMT","file_name":"resnet.py","full_name":"conv2d_fixed_padding","func_name":"conv2d_fixed_padding","docstring":"conv2d with fixed_padding, based only on kernel_size.","docstring_tokens":"","code":"def conv2d_fixed_padding(**kwargs):\n \"\"\"conv2d with fixed_padding, based only on kernel_size.\"\"\"\n strides = kwargs['strides']\n if strides > 1:\n kwargs['inputs'] = fixed_padding(kwargs['inputs'], kwargs['kernel_size'], kwargs['data_format'])\n defaults = {'padding': 'SAME' if strides == 1 else 'VALID', 'use_bias': False, 'kernel_initializer': tf.variance_scaling_initializer()}\n defaults.update(kwargs)\n return tf.layers.conv2d(**defaults)","code_tokens":"","url":331161} +{"project_name":"google\/deepvariant","file_name":"postprocess_variants.py","full_name":"merge_predictions","func_name":"merge_predictions","docstring":"Merges the predictions from the multi-allelic calls.","docstring_tokens":"","code":"def merge_predictions(call_variants_outputs, qual_filter=None, multiallelic_model=None, debug_output_all_candidates=None):\n \"\"\"Merges the predictions from the multi-allelic calls.\"\"\"\n if not call_variants_outputs:\n raise ValueError('Expected 1 or more call_variants_outputs.')\n if not is_valid_call_variants_outputs(call_variants_outputs):\n raise ValueError('`call_variants_outputs` did not pass sanity check.')\n (first_call, other_calls) = (call_variants_outputs[0], call_variants_outputs[1:])\n canonical_variant = first_call.variant\n if not other_calls:\n canonical_variant = variant_utils.simplify_variant_alleles(canonical_variant)\n return (canonical_variant, first_call.genotype_probabilities)\n alt_alleles_to_remove = get_alt_alleles_to_remove(call_variants_outputs, qual_filter)\n flattened_probs_dict = convert_call_variants_outputs_to_probs_dict(canonical_variant, call_variants_outputs, alt_alleles_to_remove, debug_output_all_candidates)\n if debug_output_all_candidates == 'INFO':\n add_string_field(canonical_variant.info, 'CANDIDATES', '|'.join(canonical_variant.alternate_bases))\n if debug_output_all_candidates != 'ALT':\n canonical_variant = prune_alleles(canonical_variant, alt_alleles_to_remove)\n num_alts = len(canonical_variant.alternate_bases)\n if num_alts == 2 and multiallelic_model is not None:\n cvo_probs = get_multiallelic_distributions(call_variants_outputs, alt_alleles_to_remove)\n normalized_predictions = multiallelic_model(cvo_probs).numpy().tolist()[0]\n else:\n\n def min_alt_filter(probs):\n return min([x for x in probs if x != _FILTERED_ALT_PROB] or [0])\n predictions = [min_alt_filter(flattened_probs_dict[m, n]) for (_, _, m, n) in variant_utils.genotype_ordering_in_likelihoods(canonical_variant)]\n if sum(predictions) == 0:\n predictions = [1.0] * len(predictions)\n normalized_predictions = normalize_predictions(predictions)\n canonical_variant = variant_utils.simplify_variant_alleles(canonical_variant)\n return (canonical_variant, normalized_predictions)","code_tokens":"","url":540409} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.sensor_dim","func_name":"sensor_dim","docstring":"number of scalar outputs (nsensor x 1).","docstring_tokens":"","code":"@util.CachedProperty\ndef sensor_dim(self):\n \"\"\"number of scalar outputs (nsensor x 1).\"\"\"\n return util.buf_to_npy(self._ptr.contents.sensor_dim, (self.nsensor,))","code_tokens":"","url":440455} +{"project_name":"PacktPublishing\/Hands-On-Artificial--for-Banking","file_name":"conftest.py","full_name":"resample_method","func_name":"resample_method","docstring":"Fixture for parametrization of Grouper resample methods.","docstring_tokens":"","code":"@pytest.fixture(params=resample_methods)\ndef resample_method(request):\n \"\"\"Fixture for parametrization of Grouper resample methods.\"\"\"\n return request.param","code_tokens":"","url":237294} +{"project_name":"Speedwagon13\/CS-3600-Introduction-to--","file_name":"_abcoll.py","full_name":"MutableSet.clear","func_name":"clear","docstring":"This is slow (creates N new iterators!) but effective.","docstring_tokens":"","code":"def clear(self):\n \"\"\"This is slow (creates N new iterators!) but effective.\"\"\"\n try:\n while True:\n self.pop()\n except KeyError:\n pass","code_tokens":"","url":139993} +{"project_name":"IceClear\/MW-GAN","file_name":"base_model.py","full_name":"BaseModel.save","func_name":"save","docstring":"Save networks and training state.","docstring_tokens":"","code":"def save(self, epoch, current_iter):\n \"\"\"Save networks and training state.\"\"\"\n pass","code_tokens":"","url":651493} +{"project_name":"Deci-AI\/super-gradients","file_name":"post_prediction_callback_test.py","full_name":"TestPostPredictionCallback.test_yolo_post_prediction_callback_yolox_output","func_name":"test_yolo_post_prediction_callback_yolox_output","docstring":"Sanity check for yolox usage with YoloPostPredictionCallback.","docstring_tokens":"","code":"def test_yolo_post_prediction_callback_yolox_output(self):\n \"\"\"\n Sanity check for yolox usage with YoloPostPredictionCallback.\n \"\"\"\n callback = self._default_yolo_post_prediction_callback()\n model = models.get(model_name='yolox_s', num_classes=80).eval()\n x = torch.randn(1, 3, 320, 320)\n output = model(x)\n _ = callback(output)","code_tokens":"","url":880679} +{"project_name":"enuguru\/artificial_intelligence_and_machine_learning","file_name":"python.py","full_name":"get_python_source","func_name":"get_python_source","docstring":"Return the source code, as unicode.","docstring_tokens":"","code":"@contract(returns='unicode')\ndef get_python_source(filename):\n \"\"\"Return the source code, as unicode.\"\"\"\n (base, ext) = os.path.splitext(filename)\n if ext == '.py' and env.WINDOWS:\n exts = ['.py', '.pyw']\n else:\n exts = [ext]\n for ext in exts:\n try_filename = base + ext\n if os.path.exists(try_filename):\n source = read_python_source(try_filename)\n break\n source = get_zip_bytes(try_filename)\n if source is not None:\n break\n else:\n raise NoSource(\"No source for code: '%s'.\" % filename)\n source = source.decode(source_encoding(source), 'replace')\n if source and source[-1] != '\\n':\n source += '\\n'\n return source","code_tokens":"","url":147892} +{"project_name":"JetBrains\/python-skeletons","file_name":"__init__.py","full_name":"assert_not_equal","func_name":"assert_not_equal","docstring":"Fail if the two objects are equal as determined by the '==' operator.","docstring_tokens":"","code":"def assert_not_equal(first, second, msg=None):\n \"\"\"Fail if the two objects are equal as determined by the '==' operator.\n \"\"\"\n pass","code_tokens":"","url":298211} +{"project_name":"Deci-AI\/super-gradients","file_name":"image.py","full_name":"load_pil_image_from_str","func_name":"load_pil_image_from_str","docstring":"Load an image based on a string (local file path or URL).","docstring_tokens":"","code":"def load_pil_image_from_str(image_str: str) -> PIL.Image.Image:\n \"\"\"Load an image based on a string (local file path or URL).\"\"\"\n if is_url(image_str):\n response = requests.get(image_str, stream=True)\n response.raise_for_status()\n return PIL.Image.open(io.BytesIO(response.content))\n else:\n return PIL.Image.open(image_str)","code_tokens":"","url":880574} +{"project_name":"AxeldeRomblay\/MLBox","file_name":"test_optimiser.py","full_name":"test_evaluate_regression_optimiser","func_name":"test_evaluate_regression_optimiser","docstring":"Test evaluate method of Optimiser class for regression.","docstring_tokens":"","code":"def test_evaluate_regression_optimiser():\n \"\"\"Test evaluate method of Optimiser class for regression.\"\"\"\n reader = Reader(sep=',')\n dict = reader.train_test_split(Lpath=['data_for_tests\/train_regression.csv', 'data_for_tests\/test_regression.csv'], target_name='SalePrice')\n drift_thresholder = Drift_thresholder()\n drift_thresholder = drift_thresholder.fit_transform(dict)\n mape = make_scorer(lambda y_true, y_pred: 100 * np.sum(np.abs(y_true - y_pred) \/ y_true) \/ len(y_true), greater_is_better=False, needs_proba=False)\n with pytest.warns(UserWarning) as record:\n opt = Optimiser(scoring=mape, n_folds=3)\n assert len(record) == 1\n score = opt.evaluate(None, dict)\n assert -np.Inf <= score\n with pytest.warns(UserWarning) as record:\n opt = Optimiser(scoring=None, n_folds=3)\n assert len(record) == 1\n score = opt.evaluate(None, dict)\n assert -np.Inf <= score\n with pytest.warns(UserWarning) as record:\n opt = Optimiser(scoring='wrong_scoring', n_folds=3)\n assert len(record) == 1\n with pytest.warns(UserWarning) as record:\n score = opt.evaluate(None, dict)\n assert -np.Inf <= score","code_tokens":"","url":630044} +{"project_name":"Firas-Ben-Hassan\/Evaluation_Framework_For_Graph_Embedding","file_name":"setup.py","full_name":"set_gcc","func_name":"set_gcc","docstring":"Try to find and use GCC on OSX for OpenMP support.","docstring_tokens":"","code":"def set_gcc():\n \"\"\"\n Try to find and use GCC on OSX for OpenMP support.\n \"\"\"\n patterns = ['\/opt\/local\/bin\/gcc-mp-[0-9].[0-9]', '\/opt\/local\/bin\/gcc-mp-[0-9]', '\/usr\/local\/bin\/gcc-[0-9].[0-9]', '\/usr\/local\/bin\/gcc-[0-9]']\n if 'darwin' in platform.platform().lower():\n gcc_binaries = []\n for pattern in patterns:\n gcc_binaries += glob.glob(pattern)\n gcc_binaries.sort()\n if gcc_binaries:\n (_, gcc) = os.path.split(gcc_binaries[-1])\n os.environ['CC'] = gcc\n else:\n raise Exception('No GCC available. Install gcc from Homebrew using brew install gcc.')","code_tokens":"","url":563514} +{"project_name":"lakraj\/Udacity-Artificial-Intelligence-Nanodegree-Projects","file_name":"test_strptime.py","full_name":"StrptimeTests.setUp","func_name":"setUp","docstring":"Create testing time tuple.","docstring_tokens":"","code":"def setUp(self):\n \"\"\"Create testing time tuple.\"\"\"\n self.time_tuple = time.gmtime()","code_tokens":"","url":376398} +{"project_name":"TonyLianLong\/VAI-ReinforcementLearning","file_name":"wrappers.py","full_name":"MjModelWrapper.nu","func_name":"nu","docstring":"number of actuators\/controls = dim(ctrl).","docstring_tokens":"","code":"@property\ndef nu(self):\n \"\"\"number of actuators\/controls = dim(ctrl).\"\"\"\n return self._ptr.contents.nu","code_tokens":"","url":440191} +{"project_name":"sentinel-hub\/eo-learn","file_name":"eotask.py","full_name":"EOTask.execute","func_name":"execute","docstring":"Override to specify action performed by task.","docstring_tokens":"","code":"@abstractmethod\ndef execute(self, *eopatches, **kwargs):\n \"\"\"Override to specify action performed by task.\"\"\"","code_tokens":"","url":562566} +{"project_name":"marlbenchmark\/off-policy","file_name":"base_runner.py","full_name":"MlpRunner.collect_rollout","func_name":"collect_rollout","docstring":"Collect a rollout and store the transitions in the buffer.","docstring_tokens":"","code":"def collect_rollout(self):\n \"\"\"Collect a rollout and store the transitions in the buffer.\"\"\"\n raise NotImplementedError","code_tokens":"","url":755510} +{"project_name":"myothida\/Supervised-Machine-Learning","file_name":"test_calibration.py","full_name":"test_calibrated_classifier_cv_double_sample_weights_equivalence","func_name":"test_calibrated_classifier_cv_double_sample_weights_equivalence","docstring":"Check that passing repeating twice the dataset `X` is equivalent to passing a `sample_weight` with a factor 2.","docstring_tokens":"","code":"@pytest.mark.parametrize('method', ['sigmoid', 'isotonic'])\n@pytest.mark.parametrize('ensemble', [True, False])\ndef test_calibrated_classifier_cv_double_sample_weights_equivalence(method, ensemble):\n \"\"\"Check that passing repeating twice the dataset `X` is equivalent to\n passing a `sample_weight` with a factor 2.\"\"\"\n (X, y) = load_iris(return_X_y=True)\n X = StandardScaler().fit_transform(X)\n (X, y) = (X[:100], y[:100])\n sample_weight = np.ones_like(y) * 2\n X_twice = np.zeros((X.shape[0] * 2, X.shape[1]), dtype=X.dtype)\n X_twice[::2, :] = X\n X_twice[1::2, :] = X\n y_twice = np.zeros(y.shape[0] * 2, dtype=y.dtype)\n y_twice[::2] = y\n y_twice[1::2] = y\n estimator = LogisticRegression()\n calibrated_clf_without_weights = CalibratedClassifierCV(estimator, method=method, ensemble=ensemble, cv=2)\n calibrated_clf_with_weights = clone(calibrated_clf_without_weights)\n calibrated_clf_with_weights.fit(X, y, sample_weight=sample_weight)\n calibrated_clf_without_weights.fit(X_twice, y_twice)\n for (est_with_weights, est_without_weights) in zip(calibrated_clf_with_weights.calibrated_classifiers_, calibrated_clf_without_weights.calibrated_classifiers_):\n assert_allclose(est_with_weights.estimator.coef_, est_without_weights.estimator.coef_)\n y_pred_with_weights = calibrated_clf_with_weights.predict_proba(X)\n y_pred_without_weights = calibrated_clf_without_weights.predict_proba(X)\n assert_allclose(y_pred_with_weights, y_pred_without_weights)","code_tokens":"","url":364624} +{"project_name":"nicknochnack\/RealTimeSignLanguageTFJS","file_name":"efficientnet_model.py","full_name":"round_repeats","func_name":"round_repeats","docstring":"Round number of repeats based on depth coefficient.","docstring_tokens":"","code":"def round_repeats(repeats: int, depth_coefficient: float) -> int:\n \"\"\"Round number of repeats based on depth coefficient.\"\"\"\n return int(math.ceil(depth_coefficient * repeats))","code_tokens":"","url":851214} +{"project_name":"SergiosKar\/Deep-Learning-models","file_name":"darknet.py","full_name":"conv_unit","func_name":"conv_unit","docstring":"A single convolutional unit that consists of Conv2D layer, BatchNorm, and LeakyReLU activation.","docstring_tokens":"","code":"def conv_unit(x, filters, kernel, strides, weight_decay=0.0001, last=False):\n \"\"\" A single convolutional unit that consists of \n Conv2D layer, BatchNorm, and LeakyReLU activation.\n \"\"\"\n x = tf.keras.layers.Conv2D(filters=filters, kernel_size=kernel, use_bias=False, kernel_initializer='he_normal', kernel_regularizer=tf.keras.regularizers.l2(weight_decay), strides=strides, padding='same')(x)\n if not last:\n x = tf.keras.layers.BatchNormalization(axis=3, epsilon=1e-05, momentum=0.9)(x)\n else:\n x = tf.keras.layers.BatchNormalization(axis=3, epsilon=1e-05, momentum=0.9, gamma_initializer='zeros')(x)\n x = tf.keras.layers.LeakyReLU(alpha=0.1)(x)\n return x","code_tokens":"","url":518821} +{"project_name":"rudranil723\/mini-main","file_name":"text.py","full_name":"Text.spans","func_name":"spans","docstring":"Get a reference to the internal list of spans.","docstring_tokens":"","code":"@property\ndef spans(self) -> List[Span]:\n \"\"\"Get a reference to the internal list of spans.\"\"\"\n return self._spans","code_tokens":"","url":268971} +{"project_name":"famura\/SimuRLacra","file_name":"sequential.py","full_name":"SequentialTasks.idx_curr","func_name":"idx_curr","docstring":"Get the index of the currently active task.","docstring_tokens":"","code":"@property\ndef idx_curr(self) -> int:\n \"\"\"Get the index of the currently active task.\"\"\"\n return self._idx_curr","code_tokens":"","url":884036} +{"project_name":"UWARG\/computer-vision-python","file_name":"test_cluster_detection.py","full_name":"TestModelExecutionCondition.test_under_min_bucket_size","func_name":"test_under_min_bucket_size","docstring":"New data under threshold should not run.","docstring_tokens":"","code":"def test_under_min_bucket_size(self, cluster_model: cluster_estimation.ClusterEstimation):\n \"\"\"\n New data under threshold should not run.\n \"\"\"\n NUM_DATA_POINTS = MIN_TOTAL_POINTS_THRESHOLD + 10\n NEW_DATA_POINTS = MIN_NEW_POINTS_TO_RUN - 1\n (generated_detections, _) = generate_cluster_data([NUM_DATA_POINTS], self.STD_DEV_REG)\n (generated_detections_2, _) = generate_cluster_data([NEW_DATA_POINTS], self.STD_DEV_REG)\n (model_ran, detections_in_world) = cluster_model.run(generated_detections, False)\n (model_ran_2, detections_in_world_2) = cluster_model.run(generated_detections_2, False)\n assert model_ran\n assert detections_in_world is not None\n assert not model_ran_2\n assert detections_in_world_2 is None","code_tokens":"","url":470475} +{"project_name":"lobocv\/pyperform","file_name":"benchmark.py","full_name":"Benchmark.run_timeit","func_name":"run_timeit","docstring":"Create the function call statement as a string used for timeit.","docstring_tokens":"","code":"def run_timeit(self, stmt, setup):\n \"\"\" Create the function call statement as a string used for timeit. \"\"\"\n _timer = timeit.Timer(stmt=stmt, setup=setup)\n trials = _timer.repeat(self.timeit_repeat, self.timeit_number)\n self.time_average_seconds = sum(trials) \/ len(trials) \/ self.timeit_number\n time_avg = convert_time_units(self.time_average_seconds)\n return time_avg","code_tokens":"","url":296834} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"mesh_tensorflow.py","full_name":"rename_dimension","func_name":"rename_dimension","docstring":"Reshape a Tensor, renaming one dimension.","docstring_tokens":"","code":"def rename_dimension(x, old_name, new_name):\n \"\"\"Reshape a Tensor, renaming one dimension.\n\n Args:\n x: a Tensor\n old_name: a string\n new_name: a string\n\n Returns:\n a Tensor\n \"\"\"\n return reshape(x, x.shape.rename_dimension(old_name, new_name))","code_tokens":"","url":965461} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"screen.py","full_name":"screen.lf","func_name":"lf","docstring":"This moves the cursor down with scrolling.","docstring_tokens":"","code":"def lf(self):\n \"\"\"This moves the cursor down with scrolling.\n \"\"\"\n old_r = self.cur_r\n self.cursor_down()\n if old_r == self.cur_r:\n self.scroll_up()\n self.erase_line()","code_tokens":"","url":74591} +{"project_name":"IntelLabs\/coach","file_name":"coach.py","full_name":"CoachLauncher.get_argument_parser","func_name":"get_argument_parser","docstring":"This returns an ArgumentParser object which defines the set of options that customers are expected to supply in order to launch a coach job.","docstring_tokens":"","code":"def get_argument_parser(self) -> argparse.ArgumentParser:\n \"\"\"\n This returns an ArgumentParser object which defines the set of options that customers are expected to supply in order\n to launch a coach job.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--preset', help=\"(string) Name of a preset to run (class name from the 'presets' directory.)\", default=None, type=str)\n parser.add_argument('-l', '--list', help='(flag) List all available presets', action='store_true')\n parser.add_argument('-e', '--experiment_name', help='(string) Experiment name to be used to store the results.', default=None, type=str)\n parser.add_argument('-ep', '--experiment_path', help='(string) Path to experiments folder.', default=None, type=str)\n parser.add_argument('-r', '--render', help='(flag) Render environment', action='store_true')\n parser.add_argument('-f', '--framework', help='(string) Neural network framework. Available values: tensorflow, mxnet', default='tensorflow', type=str)\n parser.add_argument('-n', '--num_workers', help='(int) Number of workers for multi-process based agents, e.g. A3C', default=1, type=int)\n parser.add_argument('-c', '--use_cpu', help='(flag) Use only the cpu for training. If a GPU is not available, this flag will have no effect and the CPU will be used either way.', action='store_true')\n parser.add_argument('-ew', '--evaluation_worker', help=\"(flag) If multiple workers are used, add an evaluation worker as well which will evaluate asynchronously and independently during the training. NOTE: this worker will ignore the evaluation settings in the preset's ScheduleParams.\", action='store_true')\n parser.add_argument('--play', help='(flag) Play as a human by controlling the game with the keyboard. This option will save a replay buffer with the game play.', action='store_true')\n parser.add_argument('--evaluate', help='(int) Run evaluation only, for at least the given number of steps (note that complete episodes are evaluated). This is a convenient way to disable training in order to evaluate an existing checkpoint. If value is 0, or no value is provided, evaluation will run for an infinite number of steps.', nargs='?', const=0, type=int)\n parser.add_argument('-v', '--verbosity', help='(flag) Sets the verbosity level of Coach print outs. Can be either low or high.', default='low', type=str)\n parser.add_argument('-tfv', '--tf_verbosity', help='(flag) TensorFlow verbosity level', default=3, type=int)\n parser.add_argument('--nocolor', help='(flag) Turn off color-codes in screen logging. Ascii text only', action='store_true')\n parser.add_argument('-s', '--checkpoint_save_secs', help='(int) Time in seconds between saving checkpoints of the model.', default=None, type=int)\n parser.add_argument('-crd', '--checkpoint_restore_dir', help='(string) Path to a folder containing a checkpoint to restore the model from.', type=str)\n parser.add_argument('-crf', '--checkpoint_restore_file', help='(string) Path to a checkpoint file to restore the model from.', type=str)\n parser.add_argument('-dg', '--dump_gifs', help='(flag) Enable the gif saving functionality.', action='store_true')\n parser.add_argument('-dm', '--dump_mp4', help='(flag) Enable the mp4 saving functionality.', action='store_true')\n parser.add_argument('-et', '--environment_type', help='(string) Choose an environment type class to override on top of the selected preset.', default=None, type=str)\n parser.add_argument('-lvl', '--level', help='(string) Choose the level that will be played in the environment that was selected.This value will override the level parameter in the environment class.', default=None, type=str)\n parser.add_argument('-cp', '--custom_parameter', help='(string) Semicolon separated parameters used to override specific parameters on top of the selected preset (or on top of the command-line assembled one). Whenever a parameter value is a string, it should be inputted as \\'\\\\\"string\\\\\"\\'. For ex.: \"visualization_parameters.render=False; heatup_steps=EnvironmentSteps(1000);improve_steps=TrainingSteps(100000); optimizer=\\'rmsprop\\'\"', default=None, type=str)\n parser.add_argument('--print_networks_summary', help='(flag) Print network summary to stdout', action='store_true')\n parser.add_argument('-tb', '--tensorboard', help='(flag) When using the TensorFlow backend, enable TensorBoard log dumps. ', action='store_true')\n parser.add_argument('-ns', '--no_summary', help='(flag) Prevent Coach from printing a summary and asking questions at the end of runs', action='store_true')\n parser.add_argument('-d', '--open_dashboard', help='(flag) Open dashboard with the experiment when the run starts', action='store_true')\n parser.add_argument('--seed', help='(int) A seed to use for running the experiment', default=None, type=int)\n parser.add_argument('-onnx', '--export_onnx_graph', help='(flag) Export the ONNX graph to the experiment directory. This will have effect only if the --checkpoint_save_secs flag is used in order to store checkpoints, since the weights checkpoint are needed for the ONNX graph. Keep in mind that this can cause major overhead on the experiment. Exporting ONNX graphs requires manually installing the tf2onnx package (https:\/\/github.com\/onnx\/tensorflow-onnx).', action='store_true')\n parser.add_argument('-dc', '--distributed_coach', help='(flag) Use distributed Coach.', action='store_true')\n parser.add_argument('-dcp', '--distributed_coach_config_path', help='(string) Path to config file when using distributed rollout workers.Only distributed Coach parameters should be provided through this config file.Rest of the parameters are provided using Coach command line options.Used only with --distributed_coach flag.Ignored if --distributed_coach flag is not used.', type=str)\n parser.add_argument('--memory_backend_params', help=argparse.SUPPRESS, type=str)\n parser.add_argument('--data_store_params', help=argparse.SUPPRESS, type=str)\n parser.add_argument('--distributed_coach_run_type', help=argparse.SUPPRESS, type=RunType, default=RunType.ORCHESTRATOR, choices=list(RunType))\n parser.add_argument('-asc', '--apply_stop_condition', help='(flag) If set, this will apply a stop condition on the run, defined by reaching atarget success rate as set by the environment or a custom success rate as defined in the preset. ', action='store_true')\n parser.add_argument('--dump_worker_logs', help='(flag) Only used in distributed coach. If set, the worker logs are saved in the experiment dir', action='store_true')\n parser.add_argument('--is_multi_node_test', help=argparse.SUPPRESS, action='store_true')\n return parser","code_tokens":"","url":124144} +{"project_name":"neviim\/Applying_EANNs_using_Python","file_name":"geometry.py","full_name":"Vector.angle","func_name":"angle","docstring":"Angle between vector and x-axis.","docstring_tokens":"","code":"@angle.getter\ndef angle(self):\n \"\"\" Angle between vector and x-axis.\n \"\"\"\n return 360 - int(self.as_polar()[1])","code_tokens":"","url":401800} +{"project_name":"thaines\/helit","file_name":"video_node.py","full_name":"VideoNode.inputMode","func_name":"inputMode","docstring":"Returns the required mode for the given input.","docstring_tokens":"","code":"def inputMode(self, channel=0):\n \"\"\"Returns the required mode for the given input.\"\"\"\n raise Exception('inputMode not implimented')","code_tokens":"","url":592803} +{"project_name":"mideind\/GreynirServer","file_name":"play.py","full_name":"find_youtube_playlists","func_name":"find_youtube_playlists","docstring":"Find URLs for playlists given a search string via the YouTube API.","docstring_tokens":"","code":"def find_youtube_playlists(q: str, limit: int=3) -> List[str]:\n \"\"\"Find URLs for playlists given a search string via the YouTube API.\"\"\"\n vids: List[str] = []\n try:\n r = search_youtube(q, types=['playlist'], limit=limit)\n if r is None or r.items is None:\n return vids\n for i in r.items:\n item = i.to_dict()\n if 'id' not in item or 'playlistId' not in item['id']:\n continue\n playlist_id = item['id']['playlistId']\n pl_vids = yt_api().get_playlist_items(playlist_id=playlist_id, count=1)\n if not pl_vids.items:\n continue\n first_vid_id = pl_vids.items[0].snippet.resourceId.videoId\n vids.append(_YOUTUBE_PLAYLIST_URL.format(first_vid_id, playlist_id))\n except Exception as e:\n logging.error(f'Error communicating with YouTube API: {e}')\n return vids","code_tokens":"","url":581114} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"linear_test.py","full_name":"LinearClassifierTest.testSdcaOptimizerWeightedSparseFeatures","func_name":"testSdcaOptimizerWeightedSparseFeatures","docstring":"LinearClassifier with SDCAOptimizer and weighted sparse features.","docstring_tokens":"","code":"def testSdcaOptimizerWeightedSparseFeatures(self):\n \"\"\"LinearClassifier with SDCAOptimizer and weighted sparse features.\"\"\"\n\n def input_fn():\n return ({'example_id': constant_op.constant(['1', '2', '3']), 'price': sparse_tensor.SparseTensor(values=[2.0, 3.0, 1.0], indices=[[0, 0], [1, 0], [2, 0]], dense_shape=[3, 5]), 'country': sparse_tensor.SparseTensor(values=['IT', 'US', 'GB'], indices=[[0, 0], [1, 0], [2, 0]], dense_shape=[3, 5])}, constant_op.constant([[1], [0], [1]]))\n country = feature_column_lib.sparse_column_with_hash_bucket('country', hash_bucket_size=5)\n country_weighted_by_price = feature_column_lib.weighted_sparse_column(country, 'price')\n sdca_optimizer = sdca_optimizer_lib.SDCAOptimizer(example_id_column='example_id')\n classifier = linear.LinearClassifier(feature_columns=[country_weighted_by_price], optimizer=sdca_optimizer)\n classifier.fit(input_fn=input_fn, steps=50)\n scores = classifier.evaluate(input_fn=input_fn, steps=1)\n self.assertGreater(scores['accuracy'], 0.9)","code_tokens":"","url":604039} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"base.py","full_name":"DummyOutput.fileno","func_name":"fileno","docstring":"There is no sensible default for fileno().","docstring_tokens":"","code":"def fileno(self):\n \"\"\" There is no sensible default for fileno(). \"\"\"\n raise NotImplementedError","code_tokens":"","url":45439} +{"project_name":"CLARIN-PL\/embeddings","file_name":"embedding.py","full_name":"Embedding.download_file","func_name":"download_file","docstring":"Downloads a file from an url to a local file.","docstring_tokens":"","code":"@staticmethod\ndef download_file(url, local_filename):\n \"\"\"\n Downloads a file from an url to a local file.\n\n Args:\n url (str): url to download from.\n local_filename (str): local file to download to.\n\n Returns:\n str: file name of the downloaded file.\n\n \"\"\"\n r = requests.get(url, stream=True, verify=False)\n if path.dirname(local_filename) and (not path.isdir(path.dirname(local_filename))):\n raise Exception(local_filename)\n makedirs(path.dirname(local_filename))\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n return local_filename","code_tokens":"","url":561539} +{"project_name":"EducationalTestingService\/skll","file_name":"test_voting_learners_expts_1.py","full_name":"TestVotingLearnersExptsOne.check_train_task","func_name":"check_train_task","docstring":"Check given combination of training configuration options.","docstring_tokens":"","code":"def check_train_task(self, learner_type, options_dict):\n \"\"\"Check given combination of training configuration options.\"\"\"\n (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, 'train', options_dict)\n patcher = patch.object(VotingLearner, '__init__', return_value=None)\n mock_vl_init = patcher.start()\n with patch.multiple(VotingLearner, train=DEFAULT, save=DEFAULT, model=DEFAULT, create=True) as mocks:\n run_configuration(config_path, quiet=True, local=True)\n num_expected_calls = len(objectives) if options_dict['with_grid_search'] else 1\n self.assertEqual(mock_vl_init.call_count, num_expected_calls)\n expected_init_args = (estimator_names,)\n expected_init_kwargs = {'voting': 'soft' if options_dict['with_soft_voting'] else 'hard', 'custom_learner_path': custom_learner, 'feature_scaling': 'with_mean' if options_dict['with_centering'] else 'none', 'pos_label': 'dog' if options_dict['with_pos_label'] else None, 'min_feature_count': 2 if options_dict['with_min_feature_count'] else 1, 'model_kwargs_list': model_kwargs_list, 'sampler_list': sampler_list, 'sampler_kwargs_list': None}\n for actual_call in mock_vl_init.call_args_list:\n self.assertEqual(actual_call[0], expected_init_args)\n for (key, expected_value) in expected_init_kwargs.items():\n actual_value = actual_call[1][key]\n self.assertEqual(actual_value, expected_value)\n self.assertEqual(mocks['train'].call_count, num_expected_calls)\n expected_train_kwargs = {'param_grid_list': param_grid_list, 'grid_search_folds': 4 if options_dict['with_gs_folds'] else 5, 'grid_search': options_dict['with_grid_search'], 'grid_jobs': None, 'shuffle': options_dict['with_shuffle']}\n for (idx, actual_call) in enumerate(mocks['train'].call_args_list):\n actual_arg = actual_call[0][0]\n self.assertTrue(isinstance(actual_arg, FeatureSet))\n self.assertEqual(set(actual_arg.labels), {'cat', 'dog'})\n for (key, expected_value) in expected_train_kwargs.items():\n actual_value = actual_call[1][key]\n self.assertEqual(actual_value, expected_value)\n self.assertEqual(actual_call[1]['grid_objective'], objectives[idx] if options_dict['with_grid_search'] else None)\n self.assertEqual(mocks['save'].call_count, num_expected_calls)\n for (idx, actual_call) in enumerate(mocks['save'].call_args_list):\n if not options_dict['with_grid_search'] or (options_dict['with_grid_search'] and (not options_dict['with_multiple_objectives'])):\n expected_save_args = (output_dir \/ f'{job_name}.model',)\n else:\n expected_save_args = (output_dir \/ f'{job_name}_{objectives[idx]}.model',)\n self.assertEqual(actual_call[0], expected_save_args)\n _ = patcher.stop()","code_tokens":"","url":885258} +{"project_name":"rifqind\/Agent-Programs-3KS1","file_name":"git.py","full_name":"Git.is_commit_id_equal","func_name":"is_commit_id_equal","docstring":"Return whether the current commit hash equals the given name.","docstring_tokens":"","code":"def is_commit_id_equal(self, dest, name):\n \"\"\"\n Return whether the current commit hash equals the given name.\n\n Args:\n dest: the repository directory.\n name: a string name.\n \"\"\"\n if not name:\n return False\n return self.get_revision(dest) == name","code_tokens":"","url":44277} +{"project_name":"DeepGraphLearning\/torchdrug","file_name":"draw.py","full_name":"MolToMPL","func_name":"MolToMPL","docstring":"Generates a drawing of a molecule on a matplotlib canvas.","docstring_tokens":"","code":"def MolToMPL(mol, ax=None, kekulize=True, wedgeBonds=True, imageType=None, fitImage=False, options=None, **kwargs):\n \"\"\"Generates a drawing of a molecule on a matplotlib canvas.\"\"\"\n if not mol:\n raise ValueError('Null molecule provided')\n canvas = Canvas(ax)\n if options is None:\n options = DrawingOptions()\n options.bgColor = None\n if fitImage:\n options.dotsPerAngstrom = int(min(canvas.size) \/ 10)\n options.wedgeDashedBonds = wedgeBonds\n drawer = MolDrawing(canvas=canvas, drawingOptions=options)\n omol = mol\n if kekulize:\n mol = Chem.Mol(mol.ToBinary())\n Chem.Kekulize(mol)\n if not mol.GetNumConformers():\n AllChem.Compute2DCoords(mol)\n drawer.AddMol(mol, **kwargs)\n omol._atomPs = drawer.atomPs[mol]\n for (k, v) in omol._atomPs.items():\n omol._atomPs[k] = canvas.rescalePt(v)\n return canvas._figure","code_tokens":"","url":902781} +{"project_name":"Farama-Foundation\/Gymnasium","file_name":"spaces.py","full_name":"batch_space","func_name":"batch_space","docstring":"Create a (batched) space, containing multiple copies of a single space.","docstring_tokens":"","code":"@singledispatch\ndef batch_space(space: Space, n: int=1) -> Space:\n \"\"\"Create a (batched) space, containing multiple copies of a single space.\n\n Args:\n space: Space (e.g. the observation space) for a single environment in the vectorized environment.\n n: Number of environments in the vectorized environment.\n\n Returns:\n Space (e.g. the observation space) for a batch of environments in the vectorized environment.\n\n Raises:\n ValueError: Cannot batch space that is not a valid :class:`gym.Space` instance\n\n Example:\n >>> from gymnasium.spaces import Box, Dict\n >>> import numpy as np\n >>> space = Dict({\n ... 'position': Box(low=0, high=1, shape=(3,), dtype=np.float32),\n ... 'velocity': Box(low=0, high=1, shape=(2,), dtype=np.float32)\n ... })\n >>> batch_space(space, n=5)\n Dict('position': Box(0.0, 1.0, (5, 3), float32), 'velocity': Box(0.0, 1.0, (5, 2), float32))\n \"\"\"\n raise ValueError(f'Cannot batch space with type `{type(space)}`. The space must be a valid `gymnasium.Space` instance.')","code_tokens":"","url":573357} +{"project_name":"43Carrig\/recurrent_neural_networks_practice","file_name":"rnn_colorbot.py","full_name":"train_one_epoch","func_name":"train_one_epoch","docstring":"Trains model on train_data using optimizer.","docstring_tokens":"","code":"def train_one_epoch(model, optimizer, train_data, log_interval=10):\n \"\"\"Trains model on train_data using optimizer.\"\"\"\n tf.train.get_or_create_global_step()\n\n def model_loss(labels, chars, sequence_length):\n predictions = model((chars, sequence_length), training=True)\n loss_value = loss(labels, predictions)\n tf.contrib.summary.scalar('loss', loss_value)\n return loss_value\n for (batch, (labels, chars, sequence_length)) in enumerate(tfe.Iterator(train_data)):\n with tf.contrib.summary.record_summaries_every_n_global_steps(log_interval):\n batch_model_loss = functools.partial(model_loss, labels, chars, sequence_length)\n optimizer.minimize(batch_model_loss, global_step=tf.train.get_global_step())\n if log_interval and batch % log_interval == 0:\n print('train\/batch #%d\\tloss: %.6f' % (batch, batch_model_loss()))","code_tokens":"","url":313001} +{"project_name":"llSourcell\/AI_Artist","file_name":"util.py","full_name":"from_json","func_name":"from_json","docstring":"Decode a JSON payload.","docstring_tokens":"","code":"def from_json(j):\n \"\"\"Decode a JSON payload.\"\"\"\n return json.loads(j)","code_tokens":"","url":414483} +{"project_name":"google-research\/bleurt","file_name":"downloaders.py","full_name":"Importer19.list_lang_pairs","func_name":"list_lang_pairs","docstring":"List all language pairs included in the WMT files for 2019.","docstring_tokens":"","code":"def list_lang_pairs(self):\n \"\"\"List all language pairs included in the WMT files for 2019.\"\"\"\n (folder_name, _, _) = self.location_info['eval_data']\n folder = os.path.join(self.temp_directory, folder_name, '*', 'analysis', 'ad-seg-scores-*.csv')\n all_full_paths = glob.glob(folder)\n all_files = [os.path.basename(f) for f in all_full_paths]\n cand_lang_pairs = [self.parse_eval_file_name(fname) for fname in all_files]\n lang_pairs = [lang_pair for lang_pair in cand_lang_pairs if lang_pair]\n return list(set(lang_pairs))","code_tokens":"","url":461768} +{"project_name":"Speech-Lab-IITM\/CCC-wav2vec-2.0","file_name":"token_generation_constraints.py","full_name":"ConstraintNode.tokens","func_name":"tokens","docstring":"Returns the set of tokens in constraints.","docstring_tokens":"","code":"def tokens(self) -> Set[int]:\n \"\"\"Returns the set of tokens in constraints.\"\"\"\n return set(self.token_counts().keys())","code_tokens":"","url":103495} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"curses_ui_test.py","full_name":"CursesTest.testRegexSearchNoMatchContinuation","func_name":"testRegexSearchNoMatchContinuation","docstring":"Test continuing scrolling when there is no regex match.","docstring_tokens":"","code":"def testRegexSearchNoMatchContinuation(self):\n \"\"\"Test continuing scrolling when there is no regex match.\"\"\"\n ui = MockCursesUI(40, 80, command_sequence=[string_to_codes('babble -n 3\\n'), string_to_codes('\/foo\\n'), string_to_codes('\/\\n'), self._EXIT])\n ui.register_command_handler('babble', self._babble, 'babble some', prefix_aliases=['b'])\n ui.run_ui()\n self.assertEqual(1, len(ui.unwrapped_outputs))\n self.assertEqual([0], ui.output_pad_rows)","code_tokens":"","url":182395} +{"project_name":"dbetm\/handwritten-flowchart-with-cnn","file_name":"cnn.py","full_name":"CNN.build_nn_base","func_name":"build_nn_base","docstring":"Build the VGG16 convolutional layers.","docstring_tokens":"","code":"def build_nn_base(self, input_tensor=None):\n \"\"\"Build the VGG16 convolutional layers.\"\"\"\n input_shape = (None, None, 3)\n if input_tensor is None:\n img_input = Input(shape=input_shape)\n elif not K.is_keras_tensor(input_tensor):\n img_input = Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n bn_axis = 3\n x = self.__get_conv_blocks(img_input)\n return x","code_tokens":"","url":205461} +{"project_name":"huawei-noah\/xingtian","file_name":"logger.py","full_name":"Logger.get_new_info","func_name":"get_new_info","docstring":"To assemble newest records for display.","docstring_tokens":"","code":"def get_new_info(self):\n \"\"\"To assemble newest records for display.\"\"\"\n _info = {'train_count': np.nan, 'step': np.nan, 'mean_train_time_ms': self.train_timer.average('enter'), 'mean_loop_time_ms': self.train_timer.average('loop'), 'elapsed_time': self.elapsed_time}\n for _key in ('train_loss', 'train_count'):\n if self.records[_key]:\n _info.update({_key: self.records[_key][-1]})\n if getattr(self, 'wait_sample_timer'):\n _info.update({'mean_wait_sample_ms': self.wait_sample_timer.average()})\n if getattr(self, 'prepare_data_timer'):\n _info.update({'mean_prepare_data_ms': self.prepare_data_timer.average()})\n if self.records['step']:\n _cur_step = self.records['step'][-1]\n _info.update({'step': _cur_step, 'step_per_second': int(_cur_step \/ (time() - self.abs_start))})\n if self.records['train_reward']:\n _info.update({'train_reward_avg': np.mean(self.records['train_reward'][-100:])})\n _extend_item = ('explore_won_rate',)\n for _item in _extend_item:\n if _item not in self.records.keys():\n continue\n _info.update({_item: self.records[_item]})\n return _info","code_tokens":"","url":962433} +{"project_name":"pasus\/Reinforcement-Learning-Book","file_name":"gmm.py","full_name":"GMM.estep","func_name":"estep","docstring":"Compute log observation probabilities under GMM.","docstring_tokens":"","code":"def estep(self, data):\n \"\"\"\n Compute log observation probabilities under GMM.\n Args:\n data: A N x D array of points.\n Returns:\n logobs: A N x K array of log probabilities (for each point\n on each cluster).\n \"\"\"\n (N, D) = data.shape\n K = self.sigma.shape[0]\n logobs = -0.5 * np.ones((N, K)) * D * np.log(2 * np.pi)\n for i in range(K):\n (mu, sigma) = (self.mu[i], self.sigma[i])\n L = scipy.linalg.cholesky(sigma, lower=True)\n logobs[:, i] -= np.sum(np.log(np.diag(L)))\n diff = (data - mu).T\n soln = scipy.linalg.solve_triangular(L, diff, lower=True)\n logobs[:, i] -= 0.5 * np.sum(soln ** 2, axis=0)\n logobs += self.logmass.T\n return logobs","code_tokens":"","url":340721} +{"project_name":"flow-project\/flow","file_name":"test_scenario_base_class.py","full_name":"TestRandomStartPos.test_lanes_distribution","func_name":"test_lanes_distribution","docstring":"Tests that vehicles are only placed in the requested number of lanes.","docstring_tokens":"","code":"def test_lanes_distribution(self):\n \"\"\"\n Tests that vehicles are only placed in the requested number of lanes.\n \"\"\"\n initial_config = InitialConfig(spacing='random', lanes_distribution=2)\n self.setUp_gen_start_pos(initial_config)\n for veh_id in self.env.k.vehicle.get_ids():\n self.assertLess(self.env.k.vehicle.get_lane(veh_id), initial_config.lanes_distribution)","code_tokens":"","url":212524} +{"project_name":"google\/balloon-learning-environment","file_name":"balloon_arena.py","full_name":"BalloonArenaInterface.set_balloon_state","func_name":"set_balloon_state","docstring":"Sets the baloon state.","docstring_tokens":"","code":"@abc.abstractmethod\ndef set_balloon_state(self, new_state: balloon.BalloonState) -> None:\n \"\"\"Sets the baloon state.\n\n Args:\n new_state: The state to set the baloon to.\n \"\"\"","code_tokens":"","url":422348} +{"project_name":"triaquae\/triaquae","file_name":"admin_list.py","full_name":"result_headers","func_name":"result_headers","docstring":"Generates the list column headers.","docstring_tokens":"","code":"def result_headers(cl):\n \"\"\"\n Generates the list column headers.\n \"\"\"\n ordering_field_columns = cl.get_ordering_field_columns()\n for (i, field_name) in enumerate(cl.list_display):\n (text, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)\n if attr:\n if field_name == 'action_checkbox':\n yield {'text': text, 'class_attrib': mark_safe(' class=\"action-checkbox-column\"'), 'sortable': False}\n continue\n admin_order_field = getattr(attr, 'admin_order_field', None)\n if not admin_order_field:\n yield {'text': text, 'sortable': False}\n continue\n th_classes = ['sortable']\n order_type = ''\n new_order_type = 'asc'\n sort_priority = 0\n sorted = False\n if i in ordering_field_columns:\n sorted = True\n order_type = ordering_field_columns.get(i).lower()\n sort_priority = list(ordering_field_columns).index(i) + 1\n th_classes.append('sorted %sending' % order_type)\n new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]\n o_list_primary = []\n o_list_remove = []\n o_list_toggle = []\n make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)\n for (j, ot) in ordering_field_columns.items():\n if j == i:\n param = make_qs_param(new_order_type, j)\n o_list_primary.insert(0, param)\n o_list_toggle.append(param)\n else:\n param = make_qs_param(ot, j)\n o_list_primary.append(param)\n o_list_toggle.append(param)\n o_list_remove.append(param)\n if i not in ordering_field_columns:\n o_list_primary.insert(0, make_qs_param(new_order_type, i))\n yield {'text': text, 'sortable': True, 'sorted': sorted, 'ascending': order_type == 'asc', 'sort_priority': sort_priority, 'url_primary': cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}), 'url_remove': cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}), 'url_toggle': cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}), 'class_attrib': format_html(' class=\"{0}\"', ' '.join(th_classes)) if th_classes else ''}","code_tokens":"","url":357035} +{"project_name":"hongliangduan\/Transformer-model-for-prediction-in-low-chemical-data-regimes","file_name":"t2t_datagen.py","full_name":"generate_data_for_registered_problem","func_name":"generate_data_for_registered_problem","docstring":"Generate data for a registered problem.","docstring_tokens":"","code":"def generate_data_for_registered_problem(problem_name):\n \"\"\"Generate data for a registered problem.\"\"\"\n tf.logging.info('Generating data for %s.', problem_name)\n if FLAGS.num_shards:\n raise ValueError('--num_shards should not be set for registered Problem.')\n problem = registry.problem(problem_name)\n task_id = None if FLAGS.task_id < 0 else FLAGS.task_id\n data_dir = os.path.expanduser(FLAGS.data_dir)\n tmp_dir = os.path.expanduser(FLAGS.tmp_dir)\n if task_id is None and problem.multiprocess_generate:\n if FLAGS.task_id_start != -1:\n assert FLAGS.task_id_end != -1\n task_id_start = FLAGS.task_id_start\n task_id_end = FLAGS.task_id_end\n else:\n task_id_start = 0\n task_id_end = problem.num_generate_tasks\n pool = multiprocessing.Pool(processes=FLAGS.num_concurrent_processes)\n problem.prepare_to_generate(data_dir, tmp_dir)\n args = [(problem_name, data_dir, tmp_dir, task_id) for task_id in range(task_id_start, task_id_end)]\n pool.map(generate_data_in_process, args)\n else:\n problem.generate_data(data_dir, tmp_dir, task_id)","code_tokens":"","url":964781} +{"project_name":"aeon-toolkit\/aeon","file_name":"test_evaluate.py","full_name":"test_evaluate_hierarchical","func_name":"test_evaluate_hierarchical","docstring":"Check that adding exogenous data produces different results.","docstring_tokens":"","code":"@pytest.mark.parametrize('backend', BACKENDS)\ndef test_evaluate_hierarchical(backend):\n \"\"\"Check that adding exogenous data produces different results.\"\"\"\n if backend == 'dask' and (not _check_soft_dependencies('dask', severity='none')):\n return None\n y = _make_hierarchical(random_state=0, hierarchy_levels=(2, 2), min_timepoints=20, max_timepoints=20)\n X = _make_hierarchical(random_state=42, hierarchy_levels=(2, 2), min_timepoints=20, max_timepoints=20)\n y = y.sort_index()\n X = X.sort_index()\n forecaster = DirectReductionForecaster(LinearRegression())\n cv = SlidingWindowSplitter()\n scoring = MeanAbsolutePercentageError(symmetric=True)\n out_exog = evaluate(forecaster, cv, y, X=X, scoring=scoring, error_score='raise', backend=backend)\n out_no_exog = evaluate(forecaster, cv, y, X=None, scoring=scoring, error_score='raise', backend=backend)\n scoring_name = f'test_{scoring.name}'\n assert np.all(out_exog[scoring_name] != out_no_exog[scoring_name])","code_tokens":"","url":399672} +{"project_name":"matsu0228\/nlp-jp","file_name":"layer2.py","full_name":"Layer2.dynamize_scan_filter","func_name":"dynamize_scan_filter","docstring":"Convert a layer2 scan_filter parameter into the structure required by Layer1.","docstring_tokens":"","code":"def dynamize_scan_filter(self, scan_filter):\n \"\"\"\n Convert a layer2 scan_filter parameter into the\n structure required by Layer1.\n \"\"\"\n d = None\n if scan_filter:\n d = {}\n for attr_name in scan_filter:\n condition = scan_filter[attr_name]\n d[attr_name] = condition.to_dict()\n return d","code_tokens":"","url":784265} +{"project_name":"pytorch\/rl","file_name":"tensor_specs.py","full_name":"TensorSpec.type_check","func_name":"type_check","docstring":"Checks the input value dtype against the TensorSpec dtype and raises an exception if they don't match.","docstring_tokens":"","code":"def type_check(self, value: torch.Tensor, key: str=None) -> None:\n \"\"\"Checks the input value dtype against the TensorSpec dtype and raises an exception if they don't match.\n\n Args:\n value (torch.Tensor): tensor whose dtype has to be checked\n key (str, optional): if the TensorSpec has keys, the value\n dtype will be checked against the spec pointed by the\n indicated key.\n\n \"\"\"\n if value.dtype is not self.dtype:\n raise TypeError(f'value.dtype={value.dtype} but {self.__class__.__name__}.dtype={self.dtype}')","code_tokens":"","url":858659} +{"project_name":"ashwin-phadke\/cvplayground","file_name":"inputs_test.py","full_name":"InputsTest.test_ssd_inceptionV2_eval_input_with_additional_channels","func_name":"test_ssd_inceptionV2_eval_input_with_additional_channels","docstring":"Tests the eval input function for SSDInceptionV2 with additional channels.","docstring_tokens":"","code":"def test_ssd_inceptionV2_eval_input_with_additional_channels(self, eval_batch_size=1):\n \"\"\"Tests the eval input function for SSDInceptionV2 with additional channels.\n\n Args:\n eval_batch_size: Batch size for eval set.\n \"\"\"\n configs = _get_configs_for_model('ssd_inception_v2_pets')\n model_config = configs['model']\n model_config.ssd.num_classes = 37\n configs['eval_input_configs'][0].num_additional_channels = 1\n eval_config = configs['eval_config']\n eval_config.batch_size = eval_batch_size\n eval_config.retain_original_image_additional_channels = True\n eval_input_fn = inputs.create_eval_input_fn(eval_config, configs['eval_input_configs'][0], model_config)\n (features, labels) = _make_initializable_iterator(eval_input_fn()).get_next()\n self.assertAllEqual([eval_batch_size, 300, 300, 4], features[fields.InputDataFields.image].shape.as_list())\n self.assertEqual(tf.float32, features[fields.InputDataFields.image].dtype)\n self.assertAllEqual([eval_batch_size, 300, 300, 3], features[fields.InputDataFields.original_image].shape.as_list())\n self.assertEqual(tf.uint8, features[fields.InputDataFields.original_image].dtype)\n self.assertAllEqual([eval_batch_size, 300, 300, 1], features[fields.InputDataFields.image_additional_channels].shape.as_list())\n self.assertEqual(tf.uint8, features[fields.InputDataFields.image_additional_channels].dtype)\n self.assertAllEqual([eval_batch_size], features[inputs.HASH_KEY].shape.as_list())\n self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)\n self.assertAllEqual([eval_batch_size, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())\n self.assertEqual(tf.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype)\n self.assertAllEqual([eval_batch_size, 100, model_config.ssd.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list())\n self.assertEqual(tf.float32, labels[fields.InputDataFields.groundtruth_classes].dtype)\n self.assertAllEqual([eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_weights].shape.as_list())\n self.assertEqual(tf.float32, labels[fields.InputDataFields.groundtruth_weights].dtype)\n self.assertAllEqual([eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_area].shape.as_list())\n self.assertEqual(tf.float32, labels[fields.InputDataFields.groundtruth_area].dtype)\n self.assertAllEqual([eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())\n self.assertEqual(tf.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype)\n self.assertAllEqual([eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())\n self.assertEqual(tf.int32, labels[fields.InputDataFields.groundtruth_difficult].dtype)","code_tokens":"","url":509720} +{"project_name":"tianpeiyang\/PTF_code","file_name":"reacher.py","full_name":"Physics.finger_to_target_dist","func_name":"finger_to_target_dist","docstring":"Returns the signed distance between the finger and target surface.","docstring_tokens":"","code":"def finger_to_target_dist(self):\n \"\"\"Returns the signed distance between the finger and target surface.\"\"\"\n return np.linalg.norm(self.finger_to_target())","code_tokens":"","url":818466} +{"project_name":"Westlake-AI\/OpenBioSeq","file_name":"precise_bn_hook.py","full_name":"update_bn_stats","func_name":"update_bn_stats","docstring":"Computes precise BN stats on training data.","docstring_tokens":"","code":"@torch.no_grad()\ndef update_bn_stats(model: nn.Module, loader: DataLoader, num_samples: int=8192, update_all_stats: bool=False, logger: Optional[logging.Logger]=None) -> None:\n \"\"\"Computes precise BN stats on training data.\n\n Args:\n model (nn.module): The model whose bn stats will be recomputed.\n loader (DataLoader): PyTorch dataloader._dataloader\n num_samples (int): The number of samples to update the bn stats.\n Defaults to 8192.\n update_all_stats (bool): Whether to update all BN stats in the model, i.e.,\n both BN.train() and BN.eval(). Defaults to False (only BN.train()).\n logger (:obj:`logging.Logger` | None): Logger for logging.\n Default: None.\n \"\"\"\n (rank, world_size) = get_dist_info()\n num_iter = num_samples \/\/ (loader.batch_size * world_size)\n num_iter = min(num_iter, len(loader))\n bn_layers = [m for m in model.modules() if (m.training or update_all_stats) and isinstance(m, _BatchNorm)]\n if len(bn_layers) == 0:\n print_log('No BN found in model', logger=logger, level=logging.WARNING)\n return\n print_log(f'{len(bn_layers)} BN found, run {num_iter} iters...', logger=logger)\n other_norm_layers = [m for m in model.modules() if m.training and isinstance(m, (_InstanceNorm, GroupNorm))]\n if len(other_norm_layers) > 0:\n print_log('IN\/GN stats will not be updated in PreciseHook.', logger=logger, level=logging.INFO)\n running_means = [torch.zeros_like(bn.running_mean) for bn in bn_layers]\n running_vars = [torch.zeros_like(bn.running_var) for bn in bn_layers]\n momentums = [bn.momentum for bn in bn_layers]\n for bn in bn_layers:\n bn.momentum = 1.0\n if rank == 0:\n prog_bar = mmcv.ProgressBar(num_iter)\n for data in itertools.islice(loader, num_iter):\n model(**data)\n for (i, bn) in enumerate(bn_layers):\n running_means[i] += bn.running_mean \/ num_iter\n running_vars[i] += bn.running_var \/ num_iter\n if rank == 0:\n prog_bar.update()\n running_means = scaled_all_reduce(running_means, world_size)\n running_vars = scaled_all_reduce(running_vars, world_size)\n for (i, bn) in enumerate(bn_layers):\n bn.running_mean = running_means[i]\n bn.running_var = running_vars[i]\n bn.momentum = momentums[i]","code_tokens":"","url":274751} +{"project_name":"ludwig-ai\/ludwig","file_name":"utils.py","full_name":"PositiveInteger","func_name":"PositiveInteger","docstring":"Returns a dataclass field with marshmallow metadata strictly enforcing (non-float) inputs must be positive.","docstring_tokens":"","code":"@DeveloperAPI\ndef PositiveInteger(description: str, default: Union[None, int], allow_none: bool=False, parameter_metadata: ParameterMetadata=None):\n \"\"\"Returns a dataclass field with marshmallow metadata strictly enforcing (non-float) inputs must be\n positive.\"\"\"\n val = validate.Range(min=1)\n if default is not None:\n try:\n assert isinstance(default, int)\n val(default)\n except Exception:\n raise ValidationError(f'Invalid default: `{default}`')\n return field(metadata={'marshmallow_field': fields.Integer(strict=True, validate=val, allow_none=allow_none, load_default=default, dump_default=default, metadata={'description': description, 'parameter_metadata': convert_metadata_to_json(parameter_metadata)})}, default=default)","code_tokens":"","url":616942} +{"project_name":"deepmind\/dm_control","file_name":"dog.py","full_name":"Stand.get_reward","func_name":"get_reward","docstring":"Returns the reward, product of reward factors.","docstring_tokens":"","code":"def get_reward(self, physics):\n \"\"\"Returns the reward, product of reward factors.\"\"\"\n return np.prod(self.get_reward_factors(physics))","code_tokens":"","url":165431} +{"project_name":"feast-dev\/feast","file_name":"test_offline_write.py","full_name":"test_writing_incorrect_schema_fails","func_name":"test_writing_incorrect_schema_fails","docstring":"Tests that writing a dataframe with an incorrect schema fails.","docstring_tokens":"","code":"@pytest.mark.integration\n@pytest.mark.universal_offline_stores\ndef test_writing_incorrect_schema_fails(environment, universal_data_sources):\n \"\"\"Tests that writing a dataframe with an incorrect schema fails.\"\"\"\n store = environment.feature_store\n (_, _, data_sources) = universal_data_sources\n feature_views = construct_universal_feature_views(data_sources)\n driver_fv = feature_views.driver\n store.apply([driver(), driver_fv])\n now = datetime.utcnow()\n ts = pd.Timestamp(now).round('ms')\n expected_df = pd.DataFrame.from_dict({'event_timestamp': [ts - timedelta(hours=3), ts], 'driver_id': [1001, 1002], 'conv_rate': [random.random(), random.random()], 'incorrect_schema': [random.randint(0, 10), random.randint(0, 10)], 'created': [ts, ts]})\n with pytest.raises(ValueError):\n store.write_to_offline_store(driver_fv.name, expected_df, allow_registry_cache=False)","code_tokens":"","url":544601} +{"project_name":"SamuelScheit\/carcassonne-ai","file_name":"muzero.py","full_name":"MuZero.test","func_name":"test","docstring":"Test the model in a dedicated thread.","docstring_tokens":"","code":"def test(self, render=True, opponent=None, muzero_player=None, num_tests=1, num_gpus=0):\n \"\"\"\n Test the model in a dedicated thread.\n\n Args:\n render (bool): To display or not the environment. Defaults to True.\n\n opponent (str): \"self\" for self-play, \"human\" for playing against MuZero and \"random\"\n for a random agent, None will use the opponent in the config. Defaults to None.\n\n muzero_player (int): Player number of MuZero in case of multiplayer\n games, None let MuZero play all players turn by turn, None will use muzero_player in\n the config. Defaults to None.\n\n num_tests (int): Number of games to average. Defaults to 1.\n\n num_gpus (int): Number of GPUs to use, 0 forces to use the CPU. Defaults to 0.\n \"\"\"\n opponent = opponent if opponent else self.config.opponent\n muzero_player = muzero_player if muzero_player else self.config.muzero_player\n self_play_worker = self_play.SelfPlay.options(num_cpus=0, num_gpus=num_gpus).remote(self.checkpoint, self.Game, self.config, numpy.random.randint(10000))\n results = []\n for i in range(num_tests):\n print(f'Testing {i + 1}\/{num_tests}')\n results.append(ray.get(self_play_worker.play_game.remote(0, 0, render, opponent, muzero_player)))\n self_play_worker.close_game.remote()\n if len(self.config.players) == 1:\n result = numpy.mean([sum(history.reward_history) for history in results])\n else:\n result = numpy.mean([sum((reward for (i, reward) in enumerate(history.reward_history) if history.to_play_history[i - 1] == muzero_player)) for history in results])\n return result","code_tokens":"","url":109095} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"ops.py","full_name":"Output.value_index","func_name":"value_index","docstring":"The index of this tensor in the outputs of its `Operation`.","docstring_tokens":"","code":"@property\ndef value_index(self):\n \"\"\"The index of this tensor in the outputs of its `Operation`.\"\"\"\n return self._value_index","code_tokens":"","url":182558} +{"project_name":"alexandra-chron\/ntua-slp-wassa-iest2018","file_name":"spellcorrect.py","full_name":"SpellCorrector.correct_text","func_name":"correct_text","docstring":"Correct all the words within a text, returning the corrected text.","docstring_tokens":"","code":"def correct_text(self, text):\n \"\"\"\n Correct all the words within a text, returning the corrected text.\"\"\"\n return re.sub('[a-zA-Z]+', self.correct_match, text)","code_tokens":"","url":729969} +{"project_name":"sentinel-hub\/eo-learn","file_name":"core_tasks.py","full_name":"ZipFeatureTask.zip_method","func_name":"zip_method","docstring":"A function that will be applied to the input features if overridden.","docstring_tokens":"","code":"def zip_method(self, *features: Any) -> Any:\n \"\"\"A function that will be applied to the input features if overridden.\"\"\"\n raise NotImplementedError('zip_method should be overridden.')","code_tokens":"","url":562535} +{"project_name":"tobegit3hub\/deep_image_model","file_name":"tensor_shape.py","full_name":"as_shape","func_name":"as_shape","docstring":"Converts the given object to a TensorShape.","docstring_tokens":"","code":"def as_shape(shape):\n \"\"\"Converts the given object to a TensorShape.\"\"\"\n if isinstance(shape, TensorShape):\n return shape\n else:\n return TensorShape(shape)","code_tokens":"","url":182630} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"macosx.py","full_name":"isCocoaTk","func_name":"isCocoaTk","docstring":"Returns True if IDLE is using a Cocoa Aqua Tk.","docstring_tokens":"","code":"def isCocoaTk():\n \"\"\"\n Returns True if IDLE is using a Cocoa Aqua Tk.\n \"\"\"\n if not _tk_type:\n _init_tk_type()\n return _tk_type == 'cocoa'","code_tokens":"","url":282786} +{"project_name":"weimin17\/Object-Detection_HelmetDetection","file_name":"generate_samples.py","full_name":"generate_logs","func_name":"generate_logs","docstring":"Impute Sequences using the model for a particular feed and send it to logs.","docstring_tokens":"","code":"def generate_logs(sess, model, log, id_to_word, feed):\n \"\"\"Impute Sequences using the model for a particular feed and send it to\n logs.\n \"\"\"\n [p, inputs_eval, sequence_eval] = sess.run([model.present, model.inputs, model.fake_sequence], feed_dict=feed)\n first_token = np.expand_dims(inputs_eval[:, 0], axis=1)\n sequence_eval = np.concatenate((first_token, sequence_eval), axis=1)\n p = np.concatenate((np.ones((FLAGS.batch_size, 1)), p), axis=1)\n if FLAGS.output_masked_logs:\n samples = write_masked_log(log, id_to_word, sequence_eval, p)\n else:\n samples = write_unmasked_log(log, id_to_word, sequence_eval)\n return samples","code_tokens":"","url":757882} +{"project_name":"Ruturaj123\/Flowchart-Detection","file_name":"xla_test.py","full_name":"Benchmark","func_name":"Benchmark","docstring":"Build a graph and run benchmarks against it, with or without XLA.","docstring_tokens":"","code":"def Benchmark(tf_bench, builder_fn, use_xla_jit, device, separate_compiled_gradients=False):\n \"\"\"Build a graph and run benchmarks against it, with or without XLA.\n\n Args:\n tf_bench: An instance of tf.test.Benchmark, used to run the benchmark.\n builder_fn: A function that builds a graph when invoked, and returns\n (name, fetches), where name is the name of the test, and fetches\n is a list of tensors to fetch as output.\n use_xla_jit: If true compile with the XLA JIT, otherwise use regular TF.\n device: The tensorflow device to run on, e.g. \"cpu\", \"gpu\".\n separate_compiled_gradients: If true put each gradient subgraph into a\n separate compilation scope. This gives fine-grained control over which\n portions of the graph will be compiled as a single unit. Compiling\n gradients separately may yield better performance for some graphs.\n The scope is named based on the scope of the forward computation as well\n as the name of the gradients. As a result, the gradients will be compiled\n in a scope that is separate from both the forward computation, and from\n other gradients.\n \"\"\"\n with ops.Graph().as_default():\n name = None\n targets = []\n with ops.device(device):\n fetches = []\n jit_scope = jit.experimental_jit_scope\n with jit_scope(compile_ops=use_xla_jit, separate_compiled_gradients=separate_compiled_gradients):\n (name, fetches) = builder_fn()\n for fetch in fetches:\n targets.append(array_ops.identity(fetch).op)\n config = config_pb2.ConfigProto(allow_soft_placement=True)\n with session.Session(config=config) as sess:\n sess.run(variables.global_variables_initializer())\n xla = 'xla_' if use_xla_jit else ''\n tf_bench.run_op_benchmark(sess, targets, name='%s_%s%s' % (name, xla, device))","code_tokens":"","url":586797} +{"project_name":"google-research\/ssl_detection","file_name":"viz.py","full_name":"dump_dataflow_images","func_name":"dump_dataflow_images","docstring":"Dump or visualize images of a :class:`DataFlow`.","docstring_tokens":"","code":"def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False):\n \"\"\"\n Dump or visualize images of a :class:`DataFlow`.\n\n Args:\n df (DataFlow): the DataFlow.\n index (int): the index of the image component.\n batched (bool): whether the component contains batched images (NHW or\n NHWC) or not (HW or HWC).\n number (int): how many datapoint to take from the DataFlow.\n output_dir (str): output directory to save images, default to not save.\n scale (float): scale the value, usually either 1 or 255.\n resize (tuple or None): tuple of (h, w) to resize the images to.\n viz (tuple or None): tuple of (h, w) determining the grid size to use\n with :func:`gen_stack_patches` for visualization. No visualization will happen by\n default.\n flipRGB (bool): apply a RGB<->BGR conversion or not.\n \"\"\"\n if output_dir:\n mkdir_p(output_dir)\n if viz is not None:\n viz = shape2d(viz)\n vizsize = viz[0] * viz[1]\n if resize is not None:\n resize = tuple(shape2d(resize))\n vizlist = []\n df.reset_state()\n cnt = 0\n while True:\n for dp in df:\n if not batched:\n imgbatch = [dp[index]]\n else:\n imgbatch = dp[index]\n for img in imgbatch:\n cnt += 1\n if cnt == number:\n return\n if scale != 1:\n img = img * scale\n if resize is not None:\n img = cv2.resize(img, resize)\n if flipRGB:\n img = img[:, :, ::-1]\n if output_dir:\n fname = os.path.join(output_dir, '{:03d}.jpg'.format(cnt))\n cv2.imwrite(fname, img)\n if viz is not None:\n vizlist.append(img)\n if viz is not None and len(vizlist) >= vizsize:\n stack_patches(vizlist[:vizsize], nr_row=viz[0], nr_col=viz[1], viz=True)\n vizlist = vizlist[vizsize:]","code_tokens":"","url":382363} +{"project_name":"deepmind\/dm_control","file_name":"core.py","full_name":"MjData.contact","func_name":"contact","docstring":"Variable-length recarray containing all current contacts.","docstring_tokens":"","code":"@property\ndef contact(self):\n \"\"\"Variable-length recarray containing all current contacts.\"\"\"\n return self._data.contact[:self.ncon]","code_tokens":"","url":165334} +{"project_name":"enlite-ai\/maze","file_name":"core_env.py","full_name":"CoreEnv.get_serializable_components","func_name":"get_serializable_components","docstring":"List components that should be serialized as part of trajectory data.","docstring_tokens":"","code":"@abstractmethod\n@override(SerializableEnvMixin)\ndef get_serializable_components(self) -> Dict[str, Any]:\n \"\"\"List components that should be serialized as part of trajectory data.\"\"\"","code_tokens":"","url":646597} +{"project_name":"deepmind\/dm_control","file_name":"pendulum.py","full_name":"Physics.pole_vertical","func_name":"pole_vertical","docstring":"Returns vertical (z) component of pole frame.","docstring_tokens":"","code":"def pole_vertical(self):\n \"\"\"Returns vertical (z) component of pole frame.\"\"\"\n return self.named.data.xmat['pole', 'zz']","code_tokens":"","url":165524} +{"project_name":"ArtificialIntelligenceToolkit\/aitk.robots","file_name":"cameras.py","full_name":"Camera.set_max","func_name":"set_max","docstring":"Set the maximum distance the camera can see.","docstring_tokens":"","code":"def set_max(self, max_range):\n \"\"\"\n Set the maximum distance the camera can see.\n\n Args:\n max_range (float): distance (in CM) the camera can see\n \"\"\"\n self.max_range = max_range","code_tokens":"","url":86730} +{"project_name":"Kvatsx\/Artificial-Intelligence-Assignments","file_name":"_base.py","full_name":"_AxesBase.get_facecolor","func_name":"get_facecolor","docstring":"Get the facecolor of the Axes.","docstring_tokens":"","code":"def get_facecolor(self):\n \"\"\"Get the facecolor of the Axes.\"\"\"\n return self.patch.get_facecolor()","code_tokens":"","url":1023} +{"project_name":"PIYUSH0812\/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials","file_name":"cyclegan.py","full_name":"cyclegan_arg_scope","func_name":"cyclegan_arg_scope","docstring":"Returns a default argument scope for all generators and discriminators.","docstring_tokens":"","code":"def cyclegan_arg_scope(instance_norm_center=True, instance_norm_scale=True, instance_norm_epsilon=0.001, weights_init_stddev=0.02, weight_decay=0.0):\n \"\"\"Returns a default argument scope for all generators and discriminators.\n\n Args:\n instance_norm_center: Whether instance normalization applies centering.\n instance_norm_scale: Whether instance normalization applies scaling.\n instance_norm_epsilon: Small float added to the variance in the instance\n normalization to avoid dividing by zero.\n weights_init_stddev: Standard deviation of the random values to initialize\n the convolution kernels with.\n weight_decay: Magnitude of weight decay applied to all convolution kernel\n variables of the generator.\n\n Returns:\n An arg-scope.\n \"\"\"\n instance_norm_params = {'center': instance_norm_center, 'scale': instance_norm_scale, 'epsilon': instance_norm_epsilon}\n weights_regularizer = None\n if weight_decay and weight_decay > 0.0:\n weights_regularizer = layers.l2_regularizer(weight_decay)\n with tf.contrib.framework.arg_scope([layers.conv2d], normalizer_fn=layers.instance_norm, normalizer_params=instance_norm_params, weights_initializer=tf.random_normal_initializer(0, weights_init_stddev), weights_regularizer=weights_regularizer) as sc:\n return sc","code_tokens":"","url":109872} +{"project_name":"deepmind\/acme","file_name":"simulator_test.py","full_name":"SimulatorTest.test_checkpointing","func_name":"test_checkpointing","docstring":"Tests whether checkpointing restores the state correctly.","docstring_tokens":"","code":"def test_checkpointing(self):\n \"\"\"Tests whether checkpointing restores the state correctly.\"\"\"\n model = simulator.Simulator(catch.Catch())\n num_actions = model.action_spec().num_values\n model.reset()\n model.save_checkpoint()\n ts = model.step(1)\n timestep = model.step(np.random.randint(num_actions))\n model.load_checkpoint()\n self._check_equal(ts, model.step(1))\n while not timestep.last():\n timestep = model.step(np.random.randint(num_actions))\n self.assertTrue(model.needs_reset)\n model.load_checkpoint()\n self.assertFalse(model.needs_reset)\n self._check_equal(ts, model.step(1))","code_tokens":"","url":7735} +{"project_name":"deepmind\/bsuite","file_name":"deep_sea_stochastic.py","full_name":"load","func_name":"load","docstring":"Load a deep sea experiment with the prescribed settings.","docstring_tokens":"","code":"def load(size: int, mapping_seed=0):\n \"\"\"Load a deep sea experiment with the prescribed settings.\"\"\"\n env = deep_sea.DeepSea(size=size, deterministic=False, mapping_seed=mapping_seed)\n env.bsuite_num_episodes = sweep.NUM_EPISODES\n return env","code_tokens":"","url":410208} +{"project_name":"ppengtang\/pcl.pytorch","file_name":"io.py","full_name":"assert_cache_file_is_ok","func_name":"assert_cache_file_is_ok","docstring":"Check that cache file has the correct hash.","docstring_tokens":"","code":"def assert_cache_file_is_ok(url, file_path):\n \"\"\"Check that cache file has the correct hash.\"\"\"\n cache_file_md5sum = _get_file_md5sum(file_path)\n ref_md5sum = _get_reference_md5sum(url)\n assert cache_file_md5sum == ref_md5sum, 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 hash of the local file does not match the reference (actual: {} vs. expected: {}). You may wish to delete the cached file and try again to trigger automatic download.'.format(url, file_path, cache_file_md5sum, ref_md5sum)","code_tokens":"","url":278818} +{"project_name":"zihuitang\/medical_AI_platform","file_name":"test_tokenize.py","full_name":"TestRoundtrip.test_indentation_semantics_retained","func_name":"test_indentation_semantics_retained","docstring":"Ensure that although whitespace might be mutated in a roundtrip, the semantic meaning of the indentation remains consistent.","docstring_tokens":"","code":"def test_indentation_semantics_retained(self):\n \"\"\"\n Ensure that although whitespace might be mutated in a roundtrip,\n the semantic meaning of the indentation remains consistent.\n \"\"\"\n code = 'if False:\\n\\tx=3\\n\\tx=3\\n'\n codelines = self.roundtrip(code).split('\\n')\n self.assertEqual(codelines[1], codelines[2])\n self.check_roundtrip(code)","code_tokens":"","url":283677} +{"project_name":"deepmind\/acme","file_name":"utils.py","full_name":"create_variables","func_name":"create_variables","docstring":"Builds the network with dummy inputs to create the necessary variables.","docstring_tokens":"","code":"def create_variables(network: snt.Module, input_spec: List[Union[types.NestedSpec, tf.TensorSpec]]) -> Optional[tf.TensorSpec]:\n \"\"\"Builds the network with dummy inputs to create the necessary variables.\n\n Args:\n network: Sonnet Module whose variables are to be created.\n input_spec: list of input specs to the network. The length of this list\n should match the number of arguments expected by `network`.\n\n Returns:\n output_spec: only returns an output spec if the output is a tf.Tensor, else\n it doesn't return anything (None); e.g. if the output is a\n tfp.distributions.Distribution.\n \"\"\"\n dummy_input = zeros_like(input_spec)\n if isinstance(network, snt.RNNCore):\n initial_state = squeeze_batch_dim(network.initial_state(1))\n dummy_input += [initial_state]\n dummy_output = network(*add_batch_dim(dummy_input))\n input_signature = tree.map_structure(lambda t: tf.TensorSpec((None,) + t.shape, t.dtype), dummy_input)\n network._input_signature = input_signature\n\n def spec(output):\n if not isinstance(output, tf.Tensor):\n return None\n if tf.rank(output) > 0:\n output = squeeze_batch_dim(output)\n return tf.TensorSpec(output.shape, output.dtype)\n return tree.map_structure(spec, dummy_output)","code_tokens":"","url":7865} +{"project_name":"ryu-ed\/SpaceInvaders_Ros","file_name":"ttf.py","full_name":"TruetypeInfo.is_bold","func_name":"is_bold","docstring":"Returns True iff the font describes itself as bold.","docstring_tokens":"","code":"def is_bold(self):\n \"\"\"Returns True iff the font describes itself as bold.\"\"\"\n return bool(self.get_font_selection_flags() & 32)","code_tokens":"","url":369462} +{"project_name":"wandb\/wandb","file_name":"file_stream.py","full_name":"FileStreamApi.set_default_file_policy","func_name":"set_default_file_policy","docstring":"Set an upload policy for a file unless one has already been set.","docstring_tokens":"","code":"def set_default_file_policy(self, filename: str, file_policy: 'DefaultFilePolicy') -> None:\n \"\"\"Set an upload policy for a file unless one has already been set.\"\"\"\n if filename not in self._file_policies:\n self._file_policies[filename] = file_policy","code_tokens":"","url":941714} +{"project_name":"OpenMDAO\/OpenMDAO-Framework","file_name":"eggsrv.py","full_name":"EggServer.dist_dir_response","func_name":"dist_dir_response","docstring":"When the server gets a request for a directory, return a page listing each distribution file in the directory, along with its md5 digest.","docstring_tokens":"","code":"def dist_dir_response(self, environ, start_response, abspath):\n \"\"\"When the server gets a request for a directory, return a page\n listing each distribution file in the directory, along with its md5 digest.\n \"\"\"\n dpath = environ['PATH_INFO'].strip('\/')\n start_response('200 OK', [('Content-Type', 'text\/html')])\n out = StringIO()\n out.write('\\n\\n

%s Distributions<\/h1>\\n