query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Collection of transition metals (TMs) of a defined row. e.g. row = 1 > [Sc, Ti .. Zn]
def transition_metals(cls, row: int): if row < 1 or row > 3: raise ValueError('Not a valid row of TMs. Must be 1-3') tms = [elem for elem in cls.period(row+3) if elem in metals] return np.array(tms, dtype=str)
[ "def transition_matrix(self):\n self._assert_estimated()\n return self._T", "def get_transitions(self):\n transitions = []\n for row in self.states:\n t_row = []\n for column in self.states:\n t_row.append([row, column])\n transitions.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute gammaln(x + n) gammaln(x) parametrized with sparse weights.
def sparse_gammaln_ratio(x, weights, deriv=0): if deriv == 0: func = gammaln elif deriv == 1: func = digamma else: raise NotImplementedError('Only derivatives up to first order supported') res = weights.tocoo(copy=True) x_row = x[res.row] res.data = func(x_row + res.col) ...
[ "def gammaln(F):\n def compute(value):\n \"\"\"Return log(gamma(value))\n \"\"\"\n if isinstance(value, Number):\n if sc is not None:\n return sc.gammaln(value, dtype='float32')\n else:\n raise ValueError('Numbers are not supported as input...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute gammaln(x + n) gammaln(x) parametrized with dense weights.
def dense_gammaln_ratio(x, weights, deriv=0): if deriv == 0: func = gammaln elif deriv == 1: func = digamma else: raise NotImplementedError('Only derivatives up to first order supported') counts = np.where(weights)[0] weights = weights[counts] return func(x[:, None] + cou...
[ "def gammaln(F):\n def compute(value):\n \"\"\"Return log(gamma(value))\n \"\"\"\n if isinstance(value, Number):\n if sc is not None:\n return sc.gammaln(value, dtype='float32')\n else:\n raise ValueError('Numbers are not supported as input...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gradient of BetaBinomial likelihood
def beta_binomial_log_likelihood_grad( alpha, beta, positive_weights, negative_weights, total_weights ): res = np.empty((2, alpha.size)) res[0] = sparse_gammaln_ratio(alpha, positive_weights, deriv=1) res[1] = sparse_gammaln_ratio(beta, negative_weights, deriv=1) res -= dense_gammaln_rat...
[ "def _lbeta_fwd(x, y):\n return _lbeta_naive_gradient(x, y), (x, y)", "def b_gradient_descent(self, LB,UB,eta, tol,iter):\n bgd=[]\n bgd_x=[LB]\n iteration=0\n # current_pt=X\n first_derivative=sym.diff(self.gdfunc)\n #print(first_derivative)\n x=sym.Symbol('x')\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess Isophonics dataset. Divide spectrogram features geenrated from self.DATA audio waveforms to n_frames frames long sequences and do the same with targets from self.CHORDS.
def get_preprocessed_dataset(self, hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500, from_song_ind = 0, to_song_ind = 225, separately = False) -> tuple: FEATURESs = [] CHORDs = self.CHORDS TIME_BINSs = [] KEYs = [] i = 0 separate_da...
[ "def get_preprocessed_dataset(self, hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500, separately = True) -> tuple:\n FEATURESs = []\n CHORDs = self.CHORDS\n TIME_BINSs = []\n KEYs = []\n k = 0\n separate_data, separate_targets = [], [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess audio waveform, shift pitches to C major key (and its modes ... dorian, phrygian, aiolian, lydian, ...) and generate mel and log spectrograms.
def preprocess_audio(waveform, sample_rate, spectrogram_generator, nfft, hop_length, norm_to_C=False, key='C') -> list: # Get number of half tones to transpose if norm_to_C: splited_key = key.split(":") if len(splited_key) == 1: mode_shift = 0 elif len...
[ "def preprocess_sound(data, sample_rate):\n # Convert to mono.\n\n if len(data.shape) > 1:\n data = np.mean(data, axis=1)\n # Resample to the rate assumed by VGGish.\n if sample_rate != params.SAMPLE_RATE:\n data = resampy.resample(data, sample_rate, params.SAMPLE_RATE)\n\n # Compute log mel spectrogram ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save preprocessed data from this dataset to destination path 'dest' by default as a .ds file.
def save_preprocessed_dataset(self, dest = "./Datasets/preprocessed_IsophonicsDataset.ds", hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500): # Serialize the dataset. with lzma.open(dest, "wb") as dataset_file: pickle.dump((self.get_preprocessed_datase...
[ "def save_preprocessed_dataset(self, dest = \"./Datasets/preprocessed_BillboardDataset.ds\", hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500):\n\n # Serialize the dataset.\n with lzma.open(dest, \"wb\") as dataset_file:\n pickle.dump((self.get_prepro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load preprocessed data from this dataset from destination path 'dest'. Targets and preprocessed Data are stored by default as a .ds file.
def load_preprocessed_dataset(dest = "./Datasets/preprocessed_IsophonicsDataset.ds") -> tuple: with lzma.open(dest, "rb") as dataset_file: dataset = pickle.load(dataset_file) print("[INFO] The Preprocessed Isophonics Dataset was loaded successfully.") return dataset
[ "def load_preprocessed_dataset(dest = \"./Datasets/preprocessed_BillboardDataset.ds\") -> tuple:\n with lzma.open(dest, \"rb\") as dataset_file:\n dataset = pickle.load(dataset_file)\n\n print(\"[INFO] The Preprocessed Billboard Dataset was loaded successfully.\")\n return dataset", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save data from this dataset to destination path 'dest' by default as a .ds file.
def save_dataset(self, dest = "./Datasets/IsophonicsDataset.ds"): # Serialize the dataset. with lzma.open(dest, "wb") as dataset_file: pickle.dump((self.DATA, self.CHORDS, self.KEYS, self.SAMPLE_RATE, self.NFFT), dataset_file) print("[INFO] The Isophonics Dataset was saved successfu...
[ "def save(self, dest):\n\t\tif isinstance(dest, FileAccessor):\n\t\t\treturn core.BNSaveToFile(self.handle, dest._cb)\n\t\treturn core.BNSaveToFilename(self.handle, str(dest))", "def savetofile(self, savedir):\n # Create directory if necessary (won't throw exception if dir already exists)\n #os.make...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load data from this dataset from destination path 'dest'. Targets and Data are stored by default as a .ds file.
def load_dataset(dest = "./Datasets/IsophonicsDataset.ds") -> 'IsophonicsDataset': with lzma.open(dest, "rb") as dataset_file: loaded_dataset = pickle.load(dataset_file) data, chords, keys, sample_rate, nfft = loaded_dataset dataset = IsophonicsDataset() dataset.DATA = da...
[ "def set_data_dest(self, destination_id):\n self.data_dest = destination_id", "def load_preprocessed_dataset(dest = \"./Datasets/preprocessed_BillboardDataset.ds\") -> tuple:\n with lzma.open(dest, \"rb\") as dataset_file:\n dataset = pickle.load(dataset_file)\n\n print(\"[INFO] Th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save preprocessed data from this dataset with its target and chord changes to destination path 'dest' by default as a .seg file.
def save_segmentation_samples(self, dest="./Datasets/IsophonicsSegmentation.seg", song_indices=[0, 10, 20, 30, 40, 50, 60, 70], hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500): data = [] chords = [] gold_targets = [] # Iterate over all song indic...
[ "def save_segmentation_samples(self, dest=\"./Datasets/BillboardSegmentation.seg\", song_indices=[0, 10, 20, 30, 40, 50, 60, 70], n_frames=500):\n data = []\n chords = []\n gold_targets = []\n # Iterate over all song indices on the input\n for song_ind in song_indices:\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load preprocessed data and targets with its chord changes points from destination path 'dest'. This kind of data are stored by default as a .seg file.
def load_segmentation_samples(dest = "./Datasets/IsophonicsSegmentation.seg") -> tuple: with lzma.open(dest, "rb") as segmentation_samles: loaded_samples = pickle.load(segmentation_samles) print("[INFO] The Isophonics segmentation samples was loaded successfully.") return loaded_sam...
[ "def save_segmentation_samples(self, dest=\"./Datasets/IsophonicsSegmentation.seg\", song_indices=[0, 10, 20, 30, 40, 50, 60, 70], hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500):\n data = []\n chords = []\n gold_targets = []\n # Iterate over all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess Billboard dataset. Divide spectrogram features generated from self.DATA audio waveforms to n_frames frames long sequences and do the same with targets from self.CHORDS.
def get_preprocessed_dataset(self, hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500, separately = True) -> tuple: FEATURESs = [] CHORDs = self.CHORDS TIME_BINSs = [] KEYs = [] k = 0 separate_data, separate_targets = [], [] f...
[ "def _process_data(self) -> None:\n if self.processed:\n print('Dataset has already been processed!')\n return\n self.processed = True\n \n # Run through all audio and labels\n audio, labels = [], []\n pbar = tqdm(zip(self.audio, self.labels))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save preprocessed data from this dataset to destination path 'dest' by default as a .ds file.
def save_preprocessed_dataset(self, dest = "./Datasets/preprocessed_BillboardDataset.ds", hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500): # Serialize the dataset. with lzma.open(dest, "wb") as dataset_file: pickle.dump((self.get_preprocessed_datase...
[ "def save_preprocessed_dataset(self, dest = \"./Datasets/preprocessed_IsophonicsDataset.ds\", hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500):\n # Serialize the dataset.\n with lzma.open(dest, \"wb\") as dataset_file:\n pickle.dump((self.get_preproc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load preprocessed data from this dataset from destination path 'dest'. Targets and preprocessed Data are stored by default as a .ds file.
def load_preprocessed_dataset(dest = "./Datasets/preprocessed_BillboardDataset.ds") -> tuple: with lzma.open(dest, "rb") as dataset_file: dataset = pickle.load(dataset_file) print("[INFO] The Preprocessed Billboard Dataset was loaded successfully.") return dataset
[ "def load_preprocessed_dataset(dest = \"./Datasets/preprocessed_IsophonicsDataset.ds\") -> tuple:\n with lzma.open(dest, \"rb\") as dataset_file:\n dataset = pickle.load(dataset_file)\n\n print(\"[INFO] The Preprocessed Isophonics Dataset was loaded successfully.\")\n return dataset"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save preprocessed data from this dataset with its target and chord changes to destination path 'dest' by default as a .seg file.
def save_segmentation_samples(self, dest="./Datasets/BillboardSegmentation.seg", song_indices=[0, 10, 20, 30, 40, 50, 60, 70], n_frames=500): data = [] chords = [] gold_targets = [] # Iterate over all song indices on the input for song_ind in song_indices: # Convert ...
[ "def save_segmentation_samples(self, dest=\"./Datasets/IsophonicsSegmentation.seg\", song_indices=[0, 10, 20, 30, 40, 50, 60, 70], hop_length=512, norm_to_C=False, spectrogram_generator=log_mel_spectrogram, n_frames=500):\n data = []\n chords = []\n gold_targets = []\n # Iterate over all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This command will output a hello message.
async def hello(self): # << This is the actual command, or input # << Info await self.bot.say("Hi there!") # << This is the output
[ "def say_hello():\n return \"Hello\"", "def helloCmd(self, flags, args):\n if flags or len(args) > 1:\n raise InvalidArguments\n if args:\n target = args[0]\n else:\n target = self.default_target\n if target not in self.ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalizes html to remove expected differences between AsciiDoc's output and Asciidoctor's output.
def normalize_html(html): # Replace many whitespace characters with a single space in some elements # kind of like a browser does. soup = BeautifulSoup(html, 'lxml') for e in soup.select(':not(script,pre,code,style)'): for part in e: if isinstance(part, NavigableString): ...
[ "def norm_html_from_html(html):\n if not isinstance(html, unicode):\n html = html.decode('utf-8')\n html = _markdown_email_link_re.sub(\n _markdown_email_link_sub, html)\n if sys.platform == \"win32\":\n html = html.replace('\\r\\n', '\\n')\n return html", "def html(input):\n o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two html files, ignoring expected differences between AsciiDoc and Asciidoctor. The result is a generator for lines in the diff report. If it is entirely empty then there is no diff.
def html_file_diff(lhs, rhs): with open(lhs, encoding='utf-8') as lhs_file: lhs_text = lhs_file.read() with open(rhs, encoding='utf-8') as rhs_file: rhs_text = rhs_file.read() return html_diff(lhs, lhs_text, rhs, rhs_text)
[ "def diff(old, new):\n #_ = request.getText\n #t_line = _(\"Line\") + \" \"\n t_line = \"Line \"\n\n seq1 = old.splitlines()\n seq2 = new.splitlines()\n \n seqobj = difflib.SequenceMatcher(None, seq1, seq2)\n linematch = seqobj.get_matching_blocks()\n\n if len(seq1) == len(seq2) and linem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on a list of fields to fill, run inputs. Loop while the user has said they're not happy.
def accept_inputs(fields): user_is_not_happy = True while user_is_not_happy: # store the response provisionally until we know the user wants to keep it provisional_response_dict = {} for field in fields: provisional_response_dict[field] = str(raw_input("%s: " % field)) response = str(raw_input...
[ "def fill_inputs(email_input, password_input, name, password):\n time.sleep(1)\n email_input.send_keys(name)\n time.sleep(1)\n password_input.send_keys(password)\n time.sleep(1)\n password_input.send_keys(Keys.ENTER)\n time.sleep(5)", "def generate_inputs():\n yes = prompt_user_yes_no('Do ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the tree of tasks top level function
def show_tasks(): top_level_tasks = query_with_results("select label, description from task where parent = ''", []) for task in top_level_tasks: _show_task(task)
[ "def _show_task(task, depth=0):\n indent = \" \"*depth\n # get people associated with this task\n people = query_with_results(\"select person.name from (person inner join task_person_pair on person.id = task_person_pair.person) where task_person_pair.task = ?\", [task[0]])\n people_string = \", \".join(map(lam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the tree of tasks recursive part
def _show_task(task, depth=0): indent = " "*depth # get people associated with this task people = query_with_results("select person.name from (person inner join task_person_pair on person.id = task_person_pair.person) where task_person_pair.task = ?", [task[0]]) people_string = ", ".join(map(lambda person : pe...
[ "def show_tasks():\n top_level_tasks = query_with_results(\"select label, description from task where parent = ''\", [])\n for task in top_level_tasks:\n _show_task(task)", "def print_tree(self):\n\t\tprint(self.__print_tree('', True, ''))", "def recursion_print(path, parent_proj):", "def tree(ctx):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for adding a new task.
def add_task(): # get values from user responses = accept_inputs(["Task label", "Short task description", "Parent task label"]) # insert into db query_no_results("insert into task values(?, ?, ?)", [responses["Task label"], responses["Short task description"], responses["Parent task label"]]) print("New t...
[ "def __add_task():\n os.system('clear')\n os.system('cls')\n title = input('Enter tasks name: ')\n deadline = input('Enter tasks deadline(mm/dd/yy): ')\n text = input('Enter tasks text: ')\n created_on = time.strftime('%x')\n Application.diary.add_note(title, created...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for adding a new person.
def add_person(): # get values from user responses = accept_inputs(["Name"]) # insert into db query_no_results("insert into person (name) values(?)", [responses["Name"]]) print("New person created")
[ "def __ui_add_new_person(self):\n person_id = int(input(\"ID: \"))\n person_name = input(\"Name: \").strip()\n person_phone_number = input(\"Phone number: \").strip()\n self.__person_service.service_add_person(person_id, person_name, person_phone_number)\n print(\"Person successfu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for associating a person with a task.
def add_person_to_task(): # get values from user responses = accept_inputs(["Person", "Task label"]) # get the person's ID id = query_with_results("select id from person where name = ?", [responses["Person"]])[0][0] # insert into db query_no_results("insert into task_person_pair (person, task) values(?, ?)"...
[ "def add_task():\n # get values from user\n responses = accept_inputs([\"Task label\", \"Short task description\", \"Parent task label\"])\n # insert into db\n query_no_results(\"insert into task values(?, ?, ?)\",\n [responses[\"Task label\"], responses[\"Short task description\"], responses[\"Parent task l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for adding a task to a new parent task.
def add_task_to_task(): # get task label from user responses = accept_inputs(["Task label"]) child_label = responses["Task label"] # check for existence of task results = query_with_results("select * from task where label = ?", [child_label]) if len(results) == 0: print("No task found with label '%s' th...
[ "def add_task():\n # get values from user\n responses = accept_inputs([\"Task label\", \"Short task description\", \"Parent task label\"])\n # insert into db\n query_no_results(\"insert into task values(?, ?, ?)\",\n [responses[\"Task label\"], responses[\"Short task description\"], responses[\"Parent task l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for editing an existing task.
def edit_task(): # get task label from user responses = accept_inputs(["Task label"]) label = responses["Task label"] # check for existence of task results = query_with_results("select * from task where label = ?", [label]) if len(results) == 0: print("No task found with label '%s'." % label) return...
[ "def __edit_current_task():\n os.system('clear')\n os.system('cls')\n title = input('Do you want to edit the title of the task? (Y/n)? ')\n if title.lower() == 'y':\n new_title = input('Enter new title: ')\n else:\n new_title = None\n\n body = input('D...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for editing an existing person.
def edit_person(): # get person name from user responses = accept_inputs(["Person's name"]) person_name = responses["Person's name"] # check for existence results = query_with_results("select * from person where name = ?", [person_name]) if len(results) == 0: print("No person found with name '%s'." % pe...
[ "def __modifyPerson(self):\n id = input('Give ID: ')\n name = input('Give a new name: ')\n adress = input('Give a new adress: ')\n self.__servicePpl.modPerson(id, name, adress)", "def __ui_update_person(self):\n to_update_person_id = int(input(\"Introduce the ID of the person yo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for removing a person.
def rm_person(): # get person name from user responses = accept_inputs(["Person name"]) person_name = responses["Person name"] # check for existence of person results = query_with_results("select id from person where name = ?", [person_name]) if len(results) == 0: print("No person found with name '%s' t...
[ "def __ui_remove_person(self):\n remove_person_id = int(input(\"Introduce the ID of the person you want to remove: \"))\n self.__person_service.service_remove_person(remove_person_id)\n print(\"Person successfully removed from your agenda!\\n\")", "def remove_person(self, document):\n del ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for removing a person from a task.
def rm_person_from_task(): # get person name from user responses = accept_inputs(["Person name", "Task label"]) person_name = responses["Person name"] task_label = responses["Task label"] # check for existence of person person_results = query_with_results("select id from person where name = ?", [person_name...
[ "def rm_person():\n # get person name from user\n responses = accept_inputs([\"Person name\"])\n person_name = responses[\"Person name\"]\n # check for existence of person\n results = query_with_results(\"select id from person where name = ?\", [person_name])\n if len(results) == 0:\n print(\"No person fou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take the user through the procedure for removing a task from a parent task.
def rm_task_from_parent(): # get task label from user responses = accept_inputs(["Task label"]) label = responses["Task label"] # check for existence of task results = query_with_results("select * from task where label = ?", [label]) if len(results) == 0: print("No task found with label '%s' that we cou...
[ "def remove_task(tasks, id):\n pass", "def add_task_to_task():\n # get task label from user\n responses = accept_inputs([\"Task label\"])\n child_label = responses[\"Task label\"]\n # check for existence of task\n results = query_with_results(\"select * from task where label = ?\", [child_label])\n if le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that fills in the missing learning parameters with default values, or with values that can be inferred from the variable `params`.
def fill_learner_params(params, inputs, targets, num_question_features=None, num_word_features=None): params_learn = params.learning if params_learn['model'] == RidgeWithLearnedAttention: params_learn['model_params']['num_outputs'] = [targets.shape[-1]] params_learn['mode...
[ "def _sets_default_params(self):\n pass", "def override_default_params_without_nones(params: Dict, default_params: Mapping) -> Dict:\n for key, val in default_params.items():\n if key not in params.keys() or params[key] is None:\n params[key] = val\n return params", "def fillDefau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the crossvalidation data iterators. This takes into account if we are considering zeroshot setting for the words, questions or both, as specified by the experimental configuration in `params_learn`.
def create_iterators(params_learn, groups): word_ids = [w_q // 100 for w_q in groups] question_ids = [w_q % 100 for w_q in groups] num_words = len(set(word_ids)) num_questions = len(set(question_ids)) max_test_folds = params_learn.max_folds_test max_val_folds = params_learn.max_folds_param_valid...
[ "def _do_training_cross_validation(self) -> None:\n\n cfg = self.cfg_\n fit_kwargs = {'classes': list(self.data_.classes)}\n\n # Store all of the samples used during cross-validation\n self.y_training_set_all_ = list(self._generate_samples(self.train_ids_, 'y'))\n\n # Initialize l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the name of the regularization parameters that we can tune.
def get_reg_params_name(params_learn): if params_learn['model'] == RidgeWithLearnedAttention: return 'reg_weights' elif params_learn['model'] in [regression.RidgeRegression, regression.LassoRegression]: return 'alpha' else: raise ValueError('Need to add here the regularization parame...
[ "def regularizer(self):\n \n # L2 regularization for the fully connected parameters.\n regularizers = (tf.nn.l2_loss(self.weights.wd1) + tf.nn.l2_loss(self.weights.bd1) + \n tf.nn.l2_loss(self.weights.wout) + tf.nn.l2_loss(self.weights.bout))\n return regularizers", "def regularisat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the results stored in the callbacks and make plots.
def save_results_and_plot(params, callback_results, outputs_folder, callback_idx_dist_per_time, callback_idx_save_attention, callback_idx_predictions, callback_idx_save_weights): suffix = '-' + params.data.subject_id + '-' + get_hypothesis(params) # Save resu...
[ "def test_plot_results(self):\n\n res = get_results()\n\n res.plot_results()\n matplotlib.pyplot.close('all')", "def plot_results(results_filename):\n #######################\n # PUT YOUR CODE HERE #\n #######################\n pass\n #######################\n # END OF YOUR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a set, giving the names of all leaves dominated by the given node.
def leaves(self): if self.keys(): return set().union(*[child.leaves() for child in self.itervalues()]) else: return set(self.name)
[ "def leafNames(self, node = None):\n return map(lambda x: x.name, self.leaves(node))", "def get_node_names(self):\n return set({node.get_name() for node in self.get_nodeset()}) # return the set of names", "def get_leaves(self, node=None):\n node = node or self.root\n return self.__s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
REQUIRES INTERNET CONNECTION !!!! (takes ~3mins with 1.8 MB/s) Downloads the language families and its children from and return it as a defaultdict(list).
def get_language_families(): from bs4 import BeautifulSoup as bs # If ethnologue language family html doesn't exist yet, download it. if not os.path.exists(ETHNO_DIR+'ethnologue-family.html'): fin = urllib2.urlopen(ETHNOLOGUE_DOMAIN+'browse/families')\ .read().decode('utf8') with codecs.open(ETH...
[ "def load_language_families():\n # If languagefamilies.pk is not available, create it. \n if not os.path.exists(ETHNO_DIR+'languagefamilies.pk'):\n lfs = get_language_families()\n with codecs.open(ETHNO_DIR+'languagefamilies.pk','wb') as fout:\n pickle.dump(lfs, fout)\n # Loads the pickled file.\n wi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads languagefamilies.pk and return it as a defaultdict(list).
def load_language_families(): # If languagefamilies.pk is not available, create it. if not os.path.exists(ETHNO_DIR+'languagefamilies.pk'): lfs = get_language_families() with codecs.open(ETHNO_DIR+'languagefamilies.pk','wb') as fout: pickle.dump(lfs, fout) # Loads the pickled file. with codecs.op...
[ "def get_language_families():\n from bs4 import BeautifulSoup as bs\n # If ethnologue language family html doesn't exist yet, download it.\n if not os.path.exists(ETHNO_DIR+'ethnologue-family.html'):\n fin = urllib2.urlopen(ETHNOLOGUE_DOMAIN+'browse/families')\\\n .read().decode('utf8')\n with cod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test name exists in amenity instance
def test_name(self): inst = Amenity() self.assertTrue(hasattr(inst, "name")) self.assertEqual(inst.name, "")
[ "def test_attribute(self):\n\n new_jawn = Amenity()\n self.assertTrue(\"name\" in new_jawn.__dir__())", "def test_teams_name_name_exists_get(self):\n pass", "def test_get_by_name1(self):\n pass", "def exists(unit_name):", "def test_get_by_name2(self):\n pass", "def test_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aquest metode retorna la matricula del cotxe
def getMatricula(self): return self._l[0]
[ "def ia_matrice ():\n\t# Il est pratique d'avoir l'univers sous la main \n\t# (l'ensemble des couleurs disponibles dans l'ordre)\n\tunivers = couleurs.liste_couleurs (moteur.get_nombre_couleurs ())\n\t\n\t# On crée la matrice pondérée des coefs case/couleur (affichée en sortie !)\n\tm = matrice.make (4, len (univer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
store user's input in a list, by entering order, until the user logs a string that matches the stopper string.
def create_list(): input_list = [] input_from_user = input() while input_from_user != STOPPER_STRING: input_list.append(input_from_user) input_from_user = input() return input_list
[ "def readIn():\r\n word = input(\"Enter strings (end with DONE):\\n\")\r\n count = 0\r\n while word != \"DONE\":\r\n check = True\r\n for i in words: \r\n if i == word:\r\n check = False\r\n #If the word has not been entered before, it is added to the lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
concatenate the string's in the given list, and returns the outcome.
def concat_list(str_lst): concatenation = '' if len(str_lst) != 0: for string in str_lst: concatenation = concatenation + string return concatenation
[ "def concat_list_of_strings(my_list):", "def concat_strings_by_list(str1, str2=''):\n if str2:\n return ''.join([str1, str2])\n else:\n return str1", "def concat_strings(l_strings):\n if l_strings == []:\n return \"\"\n else: \n return l_strings[0] + \" \" + concat_string...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sums all nums in the given list and returns their average in floating point (automatic on python 3), or None if the list is empty.
def average(num_list): nums_average = None nums_sum = 0 if len(num_list) != 0: for num in num_list: nums_sum = nums_sum + num nums_average = nums_sum / len(num_list) # average formula return nums_average
[ "def average(list):\n return float(sum(list) / len(list))", "def get_average(num_list):\n\n sum = 0\n for i in num_list:\n sum += i \n return sum / len(num_list)", "def get_avg(list):\n return sum(list) / len(list)", "def avg(list):\n return sum(list) / len(list)", "def average(l):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a url page in Splash, by sending a post request to your local running Splash service. If you are using Crawlera, you can reuse the current session, by setting the reuse_session flag to True. This method is intended to provide flexibility in link following, after the initial http_connection has been made with start...
def open(self, url, splash_args:dict=None, reuse_session=False, *args, **kwargs): timeout = kwargs.pop('timeout', self.http_session_timeout) if reuse_session: self._reuse_crawlera_session() if splash_args: self.splash_args = splash_args return self._stateful_po...
[ "def _stateful_post(self, url, *args, **kwargs):\n timeout = kwargs.pop('timeout', self.http_session_timeout)\n keyword = kwargs.pop('keyword', None)\n splash_args = kwargs.pop('splash_args', self.splash_args)\n\n if not splash_args:\n self.splash_args = {\n 'lu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute sending the post request to the local running Splash service with our self.browser object.
def _stateful_post(self, url, *args, **kwargs): timeout = kwargs.pop('timeout', self.http_session_timeout) keyword = kwargs.pop('keyword', None) splash_args = kwargs.pop('splash_args', self.splash_args) if not splash_args: self.splash_args = { 'lua_source': s...
[ "def do_POST(self):\r\n self.do_GET()", "def submit(self):\r\n if self.form is None:\r\n raise BrowserError(\"No form selected.\")\r\n req = self.form.click()\r\n return self.do_request(req)", "def do_POST(self):\r\n self._send_handler_response('POST')", "def run(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the crawlera session id which is returned by XCrawleraSession. Reusing the same crawlera session during the lifetime of this object may be useful, depending on your need.
def session_id(self): return self.browser.crawlera_session
[ "def session_id(self):\n return self._session_id", "def session_id(self):\n try:\n return self.session['Id']\n except KeyError:\n return None", "def get_session_id(self):\n if not self.session_id:\n return uuid.uuid4()\n else:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the self.splash_json['session_id'] to the current session_id so that the current session will be extended with an self.open() request.
def _reuse_crawlera_session(self): self.splash_args['session_id'] = self.session_id
[ "def update_session_id(self):\n self.__session_id = self.api_base.get_session_id(\n self.__user_id, self.__company_id, self.__user_password, self.__entity_id)\n self.api_base.set_session_id(self.__session_id)\n self.contacts.set_session_id(self.__session_id)\n self.locations.set_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample nonIID client data from EMNIST dataset > FEMNIST
def femnist_star(dataset, num_users): print("Sampling dataset: FEMNIST*") dict_users = {i: [] for i in range(num_users)} total_len = len(dataset) labels = dataset.targets.numpy() idxs = np.argsort(labels) num_shards, num_imgs = 26 * num_users, total_len // (num_users * 26) label_selected ...
[ "def cifar_noniid_2(dataset, num_users):\n print(\"Sampling dataset: CIFAR-10 non-IID\")\n dict_users = {i: np.array([], dtype='int64') for i in range(num_users)}\n total_len = len(dataset)\n num_shards, num_imgs = 2 * num_users, 25000 // num_users\n idx_shard = [i for i in range(num_shards)]\n id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample IID client data from CIFAR10 dataset
def cifar_iid(dataset, num_users): print("Sampling dataset: CIFAR-10 IID") num_items = int(len(dataset)/num_users) dict_users, all_idxs = {}, [i for i in range(len(dataset))] for i in range(num_users): dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False)) all_idxs = l...
[ "def cifar_100_iid(dataset, num_users):\n print(\"Sampling dataset: CIFAR-100 IID\")\n num_items = int(len(dataset) / num_users)\n dict_users, all_idxs = {}, [i for i in range(len(dataset))]\n for i in range(num_users):\n dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False))\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample nonIID client data from CIFAR10 dataset
def cifar_noniid_2(dataset, num_users): print("Sampling dataset: CIFAR-10 non-IID") dict_users = {i: np.array([], dtype='int64') for i in range(num_users)} total_len = len(dataset) num_shards, num_imgs = 2 * num_users, 25000 // num_users idx_shard = [i for i in range(num_shards)] idxs = np.arang...
[ "def cifar_100_noniid(dataset, num_users):\n print(\"Sampling dataset: CIFAR-100 non-IID\")\n dict_users = {i: np.array([], dtype='int64') for i in range(num_users)}\n total_len = len(dataset)\n num_shards, num_imgs = 20 * num_users, total_len // (num_users * 20)\n\n labels = np.array(dataset.targets...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample nonIID client data from CIFAR100 dataset
def cifar_100_noniid(dataset, num_users): print("Sampling dataset: CIFAR-100 non-IID") dict_users = {i: np.array([], dtype='int64') for i in range(num_users)} total_len = len(dataset) num_shards, num_imgs = 20 * num_users, total_len // (num_users * 20) labels = np.array(dataset.targets) idxs = ...
[ "def cifar_noniid_2(dataset, num_users):\n print(\"Sampling dataset: CIFAR-10 non-IID\")\n dict_users = {i: np.array([], dtype='int64') for i in range(num_users)}\n total_len = len(dataset)\n num_shards, num_imgs = 2 * num_users, 25000 // num_users\n idx_shard = [i for i in range(num_shards)]\n id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample IID client data from CIFAR100 dataset
def cifar_100_iid(dataset, num_users): print("Sampling dataset: CIFAR-100 IID") num_items = int(len(dataset) / num_users) dict_users, all_idxs = {}, [i for i in range(len(dataset))] for i in range(num_users): dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False)) all_i...
[ "def cifar_iid(dataset, num_users):\n print(\"Sampling dataset: CIFAR-10 IID\")\n num_items = int(len(dataset)/num_users)\n dict_users, all_idxs = {}, [i for i in range(len(dataset))]\n for i in range(num_users):\n dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pred_classif and gt_classif must be aligned
def validate(pred_classif, gt_classif, pred_nan=-1, gt_nan=-1, add_to_gtr=10000): gt_valid = np.logical_not(gt_classif == gt_nan) pred_valid = np.logical_not(pred_classif == pred_nan) valids = np.where(np.logical_and(gt_valid, pred_valid)) # make sure the labels of gt_classif and pred_classif are diffe...
[ "def __call__(self, pred_texture, gt_texture):\n pred_class = self.classifier.predict(pred_texture)\n gt_class = self.classifier.predict(gt_texture)\n if pred_class == gt_class:\n return 0\n else:\n return 1", "def predict(V, W, classId, XlT, XuT, patClassIdTest, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the GUI into the offscreen texture
def draw_offscreen(context): offscreen = SprytileGui.offscreen target_img = SprytileGui.texture_grid tex_size = SprytileGui.tex_size offscreen.bind() glClear(GL_COLOR_BUFFER_BIT) glDisable(GL_DEPTH_TEST) glEnable(GL_BLEND) glMatrixMode(GL_PROJECTION) ...
[ "def draw_gui(self):\n # TODO: get the gui stuff going.\n pass", "def draw(self) -> None:\n # [WHITE] Outline\n out = (self.coord[0] - 3, self.coord[1] - 3, self.coord[2] + 6, \n self.coord[3] + 6)\n light_bg = (BACKGROUND[0] + 30, BACKGROUND[1] + 30, BACKGROUND[2]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raise a ValidationError if both read and seen aren't present in the data on load.
def validate_read_and_seen(self, data, **kwargs): if "_read" not in data and "_seen" not in data: raise ValidationError( "Please provide at least one field to update. Valid fields to update are: read, seen" ) return data
[ "def _validate(self):\n self.validator.validate(self.valid_dataloader)", "def validate_data(self, data):\n pass", "def check_read_create(self, bundle):\r\n\r\n obj = self.get_via_uri(bundle.request.path)\r\n for fk in self.read_create_fields:\r\n\r\n if fk not in bundle.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove unwanted fields from the input data before deserialization.
def strip_unwanted_fields(self, data, many, **kwargs): unwanted_fields = ["resource_type"] for field in unwanted_fields: if field in data: data.pop(field) return data
[ "def clean_data(self, raw_json):\n pass", "def reset_field_data(self, exclude=[]):\n if self.name not in exclude:\n self.data = self.object_data", "def data_without(self, fields):\n without = {}\n data = json.loads(self.data())\n for field, value in data.items():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default handler for the 'upgradecharm' hook. This calls the charm.singleton.upgrade_charm() function as a default.
def default_upgrade_charm(): reactive.set_state('upgraded')
[ "def custom_upgrade_charm():\n with charm.provide_charm_instance() as instance:\n if reactive.is_flag_set('leadership.is_leader'):\n # Change leadership cluster flags with dots in their names\n instance.update_dotted_flags()\n if (reactive.is_flag_set(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Ad...
def register_serializer(format, serializer_module, serializers=None): module = importlib.import_module(serializer_module) if serializers is None: _test_serializers[format] = module else: serializers[format] = module
[ "def register_serializer(self, format, serializer_module, serializers=None):\n if serializers is None and not _serializers:\n _load_serializers() # noqa\n module = importlib.import_module(serializer_module)\n if serializers is None:\n _serializers[format] = module\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register builtin and settingsdefined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order.
def _load_test_serializers(): global _test_serializers serializers = {} for format in TEST_SERIALIZERS: register_serializer(format, TEST_SERIALIZERS[format], serializers) if hasattr(settings, "TEST_SERIALIZATION_MODULES"): for format in settings.TEST_SERIALIZATION_MODULES: re...
[ "def _load_serializers(self):\n global _serializers\n serializers = {}\n for format in BUILTIN_SERIALIZERS:\n self.register_serializer(format, BUILTIN_SERIALIZERS[format], serializers)\n if hasattr(settings, \"SERIALIZATION_MODULES\"):\n for format in settings.SERIA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a segment and upload it to the database
def storeSegment ( baseurl, fields, token ): # Create the segment and initialize it's fields ann = annotation.Annotation() ann.annid = int(fields[0]) # Exceptional cases if ann.annid in EXCEPTIONS: print "Skipping id ", ann.annid return descriptorstr = fields[40].split("\"") descriptor = desc...
[ "def _parse_segments(self):\n reader = csv.reader(open(self._segment_file, 'rU'),\n delimiter='\\t')\n for row in reader:\n if reader.line_num == 1: #skip header\n continue\n sql = '''INSERT INTO segments\n (id, multip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update histogram axis labels
def update_histogram_axis(self, param_z): if not isinstance(param_z, (Parameter, ArrayParameter)): raise TypeError("param_z must be a qcodes parameter") self.histogram.axis.label = param_z.label self.histogram.axis.units = param_z.unit
[ "def set_histogram(histogram, x_title, y_title):\n histogram.SetLineWidth(2)\n histogram.GetXaxis().SetTitle(x_title)\n histogram.GetYaxis().SetTitle(y_title)\n histogram.GetXaxis().SetDecimals()\n histogram.GetYaxis().SetDecimals()\n histogram.GetXaxis().SetTitleSize(size)\n histogram.GetYaxis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the next file to be readed open it and parse de file header
def setNextFile(self): if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): self.nReadFiles=self.nReadFiles+1 if self.nReadFiles > self.nTotalReadFiles: self.flagNoMoreFiles=1 raise schainpy.admin.SchainWarning('No more files to read') ...
[ "def next_file(self):\n raise NotImplementedError()", "def _parseFileHeader(self):\n self.fileheader = FileHeader()\n self.fileheader.parse(self.f)\n #print('Parsed fileheader')", "def next(self):\n return self.__file.next()", "def _load_next_file(self):\n\n if self._file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for retrieving a MongoClient according to the environment we are running on
def get_client(): return MongoClientManager().client
[ "def get_client():\n return pymongo.MongoClient('163.118.78.22', 27017)", "def get_mongo_db_instance(self):\n\t\tself.mongo_client = MongoClient()\n\n\t\treturn self.mongo_client[DFSConstants.MONGO_NBA_TEST_DB_NAME]", "def _generate_client(self):\n mongoConf = self._config.get('Connectivity', 'MongoDB...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get start times of each window, rather than midpoint times
def window_start_times(self): window_length = self.window_length if window_length is not None: return np.array(self.times) - window_length / 2
[ "def get_window_start_times(profileDict):\n assert isinstance(profileDict, dict) and \"samples\" in profileDict\n\n return profileDict[\"samples\"][\"window_start_offsets\"]", "def get_stamp_windows(self):\n early_window = self.get_earliest_stamp_window()\n late_window = self.get_latest_stamp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limit the decibel values of the spectrogram to range from min_db to max_db values less than min_db are set to min_db values greater than max_db are set to max_db similar to Audacity's gain and range parameters
def limit_db_range(self, min_db=-100, max_db=-20): if max_db <= min_db: raise ValueError( f"max_db must be greater than min_db (got max_db={max_db} and min_db={min_db})" ) _spec = self.spectrogram.copy() _spec[_spec > max_db] = max_db _spec[_spec...
[ "def test_amplitude_to_DB_top_db_clamp(self, shape):\n amplitude_mult = 20.0\n amin = 1e-10\n ref = 1.0\n db_mult = math.log10(max(amin, ref))\n top_db = 40.0\n\n # A random tensor is used for increased entropy, but the max and min for\n # each spectrogram still need...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create amplitude signal in signal_band and subtract amplitude from reject_bands rescale the signal and reject bands by dividing by their bandwidths in Hz (amplitude of each reject_band is divided by the total bandwidth of all reject_bands. amplitude of signal_band is divided by badwidth of signal_band. )
def net_amplitude( self, signal_band, reject_bands=None ): # used to be called "net_power_signal" which is misleading (not power) # find the amplitude signal for the desired frequency band signal_band_amplitude = self.amplitude(signal_band) signal_band_bandwidth = signal_band[1] -...
[ "def bandreject(self, wllow, wlhigh):\n new_phase = bandreject_filter(self.phase, self.sample_spacing, wllow, wlhigh)\n new_phase[~m.isfinite(self.phase)] = m.nan\n self.phase = new_phase\n return self", "def _excitation_mixing(fpulse, fnoise, fbndaps, fperiod, srate, bands):\n puls...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an image from spectrogram (array, tensor, or PIL.Image) Linearly rescales values in the spectrogram from self.decibel_limits to [0,255] (PIL.Image) or [0,1] (array/tensor) Default of self.decibel_limits on load is [100, 20], so, e.g., 20 db is loudest > black, 100 db is quietest > white
def to_image( self, shape=None, channels=1, colormap=None, invert=False, return_type="pil" ): assert return_type in [ "pil", "np", "torch", ], f"Arg `return_type` must be one of 'pil', 'np', 'torch'. Got {return_type}." if colormap is not None: ...
[ "def createScale(instance, scale, width, height, data=None):", "def __init__(self, data, pixscale = 7.77/43):\n self.data = data\n self.pixscale = pixscale", "def make_spectrogram_image(spectrogram: torch.Tensor,\n filename: str = 'spectrogram',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a MelSpectrogram object from an Audio object First creates a spectrogram and a melfrequency filter bank, then computes the dot product of the filter bank with the spectrogram. A Mel spectgrogram is a spectrogram with a quasilogarithmic frequency axis that has often been used in langauge processing and other doma...
def from_audio( cls, audio, window_type="hann", window_samples=None, window_length_sec=None, overlap_samples=None, overlap_fraction=None, fft_size=None, decibel_limits=(-100, -20), dB_scale=True, scaling="spectrum", n_mels=6...
[ "def get_spectrogram(self, audio, label):\n # Normalize\n audio = tf.cast(audio, tf.float32) / 32768.0\n # Padding for files with less than 16000 samples\n zero_padding = tf.zeros([16000] - tf.shape(audio), dtype=tf.float32)\n # Pad to same length\n audio = tf.cast(audio, t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the mel spectrogram with matplotlib.pyplot We can't use pcolormesh because it will smash pixels to achieve a linear yaxis, rather than preserving the mel scale.
def plot(self, inline=True, fname=None, show_colorbar=False): color_norm = matplotlib.colors.Normalize( vmin=self.decibel_limits[0], vmax=self.decibel_limits[1] ) plt.imshow(self.spectrogram[::-1], cmap="Greys", norm=color_norm) # pick values to show on time and frequency a...
[ "def plot_melspectrogram(melspectrogram: Tensor, hp: HParams) -> None:\n assert len(melspectrogram.size()) == 3, \\\n \"Dimensions of melspectogram should be 3, found {}\".format(len(melspectrogram.size()))\n\n n_melspectrograms = melspectrogram.shape[0]\n # In case the spectrogram tensor is in the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary with gidvaluedictionary mappings. Each valuedictionary contains a "data" entry, which references a single satic value. {
def get_static_data(name): varinfo = get_varinfo(name) if varinfo["type"] == "static": data = get_data(varinfo["id"]) giddict = dict([ (valuedict["gid"],{"data":valuedict["value"]}) for valuedict in data["cells"] ]) return giddict els...
[ "def get_d_bindingdata(data_bd):\n dic = {}\n for data in data_bd:\n (species, mhc, length, cv, peptide, inequality, meas) = data\n dic[peptide] = data\n return dic", "def get_data_dict(self):\n return self.build_data_dict(self.get_flatten_values())", "def _get_gedi1b_main_data_dict(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a BagIt file is valid.
def validate_bagit_file(bagit_path): _assert_zip_file(bagit_path) bagit_zip = zipfile.ZipFile(bagit_path) manifest_info_list = _get_manifest_info_list(bagit_zip) _validate_checksums(bagit_zip, manifest_info_list) return True
[ "def is_valid_file(self, file_path):\n return True", "def __checkFile(self, filename):\n \n try:\n with open(filename, 'r') as f:\n first_line = f.readline()\n \n if not len(first_line.split(\"\\t\")) == 19:\n raise BadProteom...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a stream containing a BagIt zip archive.
def create_bagit_stream(dir_name, payload_info_list): zip_file = zipstream.ZipFile(mode="w", compression=zipstream.ZIP_DEFLATED) _add_path(dir_name, payload_info_list) payload_byte_count, payload_file_count = _add_payload_files( zip_file, payload_info_list ) tag_info_list = _add_tag_files( ...
[ "def _open_zip(self):\n self.buffer = io.BytesIO()\n self.zf = zipfile.ZipFile(self.buffer, \"w\", zipfile.ZIP_DEFLATED)", "def make_empty_zip(self):\n buffer = BytesIO()\n file = ZipFile(buffer, 'w')\n file.close()\n return buffer", "def _create_zip(self, files):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a key to each payload_info_dict with the path under which the file will be stored in the ZIP file and which will be used for the file when the ZIP is uncompressed. Since there is no unique restriction on the `fileName` element in SysMeta, this method checks for duplicated files and adds a count to filenames as need...
def _add_path(dir_name, payload_info_list): path_count_dict = {} for payload_info_dict in payload_info_list: file_name = payload_info_dict["filename"] or payload_info_dict["pid"] path = d1_common.utils.filesystem.gen_safe_path(dir_name, "data", file_name) path_count_dict.setdefault(path,...
[ "def _add_payload_files(zip_file, payload_info_list):\n payload_byte_count = 0\n payload_file_count = 0\n for payload_info_dict in payload_info_list:\n zip_file.write_iter(payload_info_dict[\"path\"], payload_info_dict[\"iter\"])\n payload_byte_count += payload_info_dict[\"iter\"].size\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the payload files to the zip.
def _add_payload_files(zip_file, payload_info_list): payload_byte_count = 0 payload_file_count = 0 for payload_info_dict in payload_info_list: zip_file.write_iter(payload_info_dict["path"], payload_info_dict["iter"]) payload_byte_count += payload_info_dict["iter"].size payload_file_c...
[ "def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list):\n for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list):\n _add_tag_file(\n zip_file,\n dir_name,\n tag_info_list,\n _gen_manifest_file_tup(payload_info_list, chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the tag files and add them to the zip.
def _add_tag_files( zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count ): tag_info_list = [] _add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup()) _add_tag_file( zip_file, dir_name, tag_info_list, _gen_bag_info_file_tup(pa...
[ "def _zip_files(self):\n\n zip_file = Path(self.build_directory.parent).joinpath(\n self.package_name + '.zip'\n )\n logger.info('Creating zip file: %s', zip_file)\n\n shutil.make_archive(zip_file.with_suffix(''), 'zip', self.build_directory)\n shutil.move(str(zip_file)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the manifest files and add them to the zip.
def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list): for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list): _add_tag_file( zip_file, dir_name, tag_info_list, _gen_manifest_file_tup(payload_info_list, checksum_algori...
[ "def _zip_files(self):\n\n zip_file = Path(self.build_directory.parent).joinpath(\n self.package_name + '.zip'\n )\n logger.info('Creating zip file: %s', zip_file)\n\n shutil.make_archive(zip_file.with_suffix(''), 'zip', self.build_directory)\n shutil.move(str(zip_file)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the tag manifest file and add it to the zip.
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list): _add_tag_file( zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list) )
[ "def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list):\n for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list):\n _add_tag_file(\n zip_file,\n dir_name,\n tag_info_list,\n _gen_manifest_file_tup(payload_info_list, chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a tag file to zip_file and record info for the tag manifest file.
def _add_tag_file(zip_file, dir_name, tag_info_list, tag_tup): tag_name, tag_str = tag_tup tag_path = d1_common.utils.filesystem.gen_safe_path(dir_name, tag_name) tag_iter = _create_and_add_tag_iter(zip_file, tag_path, tag_str) tag_info_list.append( { "path": tag_path, "c...
[ "def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):\n _add_tag_file(\n zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)\n )", "def _add_file_to_zip(zip_file, path, arcname):\n with open(path, \"rb\") as input_file:\n zinfo = zipfile.ZipInfo(filename=a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get set of checksum algorithms in use.
def _get_checksum_algorithm_set(payload_info_list): return {d["checksum_algorithm"] for d in payload_info_list}
[ "def __get_algorithms():\n return hashlib.algorithms_available", "def _available_algorithms(**_: str) -> Set[str]:\n avail = set()\n pass2 = set()\n for algo in hashlib.algorithms_available:\n lalgo = algo.lower()\n if \"with\" in lalgo:\n continue # skip apparently redun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode a dictionary made with encode() into a Game object.
def decode_game(obj): try: players = obj['players'] jacks = obj['jacks'] library = obj['library'] pool = obj['pool'] stack = obj['stack'] _current_frame = obj['_current_frame'] except KeyError as e: raise GTREncodingError(e.message) game_dict = copy.d...
[ "def decode_player(obj):\n player_dict = copy.deepcopy(obj)\n\n zones = ('hand', 'stockpile', 'clientele', 'vault', 'camp',\n 'revealed', 'prev_revealed', 'clients_given')\n\n for k in zones:\n try:\n zone_list = player_dict[k]\n except KeyError as e:\n # With...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode a dictionary made with encode() into a Player object.
def decode_player(obj): player_dict = copy.deepcopy(obj) zones = ('hand', 'stockpile', 'clientele', 'vault', 'camp', 'revealed', 'prev_revealed', 'clients_given') for k in zones: try: zone_list = player_dict[k] except KeyError as e: # Without a marker fo...
[ "def player_from_raw(data: Dict[str, Any]) -> andesite.Player:\n return build_from_raw(andesite.Player, data)", "def player_to_raw(player: andesite.Player) -> Dict[str, Any]:\n return convert_to_raw(player)", "def decode_game(obj):\n try:\n players = obj['players']\n jacks = obj['jacks']\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a Game object into JSON.
def game_to_json(game): return json.dumps(encode(game), sort_keys=True, indent=None)
[ "def to_json(self):\r\n\r\n object_json = dict()\r\n object_json[\"Type\"] = self.__class__.__name__\r\n game_json = dict()\r\n game_json[\"x_dist\"] = self.x_dist\r\n game_json[\"y_dist\"] = self.y_dist\r\n game_json[\"turn_number\"] = self.turn_number\r\n game_json[\"max_turns\"] = self.max_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform JSON into game object.
def json_to_game(game_json): try: game_dict = json.loads(game_json) except ValueError as e: raise GTREncodingError(e.message) return decode_game(game_dict)
[ "def json_to_player(cls, json_player):\n gdict = globals()\n if len(json_player) == PLAYER_LENGTH:\n [[gdict[ID], player_id], [gdict[SPECIES], json_los], [gdict[BAG], food_bag]] = json_player\n cards = []\n else:\n [[gdict[ID], player_id], [gdict[SPECIES], json_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the getEditor method. It checks if every property type has a corresponding editor.
def testGetEditorForPropTypes(self): propTypes = PROPERTY_TYPE_NAMES[:] propTypes.remove(u'Any') for propType in propTypes: self._editorFactory.createEditor(None, propType)
[ "def testGetCorrectEditor(self):\r\n \r\n self.assertTrue(type(self._editorFactory.createEditor(None, 'Number')) == QtGui.QDoubleSpinBox)\r\n self.assertTrue(type(self._editorFactory.createEditor(None, 'Boolean')) == QtGui.QCheckBox)\r\n self.assertTrue(type(self._editorFactory.createEdi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the correct editor type is returned corresponding to the input type.
def testGetCorrectEditor(self): self.assertTrue(type(self._editorFactory.createEditor(None, 'Number')) == QtGui.QDoubleSpinBox) self.assertTrue(type(self._editorFactory.createEditor(None, 'Boolean')) == QtGui.QCheckBox) self.assertTrue(type(self._editorFactory.createEditor(None, 'Da...
[ "def editorForTyp(typ):\n\n if typ == \"quint32\":\n return (\"QSpinBox\", \"setValue\", \"value\")\n elif typ == \"QString\":\n return (\"QLineEdit\", \"setText\", \"text\")\n elif typ == \"bool\":\n return (\"QCheckBox\", \"setChecked\", \"isChecked\")\n return (None, None, None)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests restrictions for integer and string editors
def testEditorRestrictionsStringInt(self): restrictions = {constants.MAXIMUM_LENGTH: 12, constants.MAXIMUM_VALUE: 500, constants.MINIMUM_VALUE: 10, constants.MAXIMUM_NUMBER_OF_DECIMAL_PLACES: 5, consta...
[ "def check_for_int(check):", "def test_non_numberic_validation(self):", "def test_validate_input_value_integer_string(integer_space):\n namespace = \"x\"\n\n is_valid, casted_value = _validate_input_value(\"string\", integer_space, namespace)\n assert not is_valid", "def test_not_int_input(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests restrictions for the date time editor
def testEditorRestrictionsDateTime(self): restrictions = { constants.MINIMUM_VALUE: datetime.datetime(1950, 1, 1, 0, 15), constants.MAXIMUM_VALUE: datetime.datetime(2010, 1, 1, 0, 15), } dateTimeEdit = self._e...
[ "def verify_date_or_time(css, date_or_time):\r\n # We need to wait for JavaScript to fill in the field, so we use\r\n # css_has_value(), which first checks that the field is not blank\r\n assert_true(world.css_has_value(css, date_or_time))", "def date_temporal_paradox_free(self):\n valid_date = Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the setEditorValue method
def testSetEditorValue(self): lineEdit = QtGui.QLineEdit() self._editorFactory.setEditorValue(lineEdit, u"Test") self.assertTrue(lineEdit.text() == u"Test" ) spinBox = QtGui.QDoubleSpinBox() self._editorFactory.setEditorValue(spinBox, 2.05) self....
[ "def SetValue(self, value):\n\t\tsuper(ACTextControl, self).ChangeValue(value)", "def test_set_value_valid(self):\r\n name = 'option2'\r\n option = self.config.options[name]\r\n value = 'hello'\r\n\r\n self.config.set_value(name, option, value)\r\n self.assertEqual(self.config.v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the /gauges Slack command and invoke the corresponding function.
def gauges_app(params): user = params['user_name'][0] command = params['command'][0] channel = params['channel_name'][0] command_text = params['text'][0] if 'text' in params else '' commands = { r'\s*check\s+(.+)': check_gauge, r'\s*add\s+(\d+)\s+(.+)': add_favorite_gauge, ...
[ "def handle(self, *args, **options):\n if len(args) != 2:\n self.stderr.write(\"Usage: 'python manage.py award_badge <badge-slug> <user>\\n\")\n return\n\n slug = args[0]\n username = args[1]\n\n award_badge(slug, username)", "def main():\n from argparse import...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display usage information for the /gauges Slack command.
def display_help_message(): return lambda_response(None, { "text": """ /gauges list - list favorite gauges /gauges add USGS_SITE_NUMBER RIVER_DESCRIPTION - add gauge to list of favorite gauges /gauges check USGS_SITE_NUMBER - display current flow readings for gauge """.strip(), })
[ "def gauges_app(params):\n user = params['user_name'][0]\n command = params['command'][0]\n channel = params['channel_name'][0]\n command_text = params['text'][0] if 'text' in params else ''\n\n commands = {\n r'\\s*check\\s+(.+)': check_gauge,\n r'\\s*add\\s+(\\d+)\\s+(.+)': add_favor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure the Slack token given in request matches token provided by Slack.
def verify_slack_token(request_token): encrypted_token = os.environ['kmsEncryptedToken'] if encrypted_token == 'local': return True kms = boto3.client('kms') expected_token = kms.decrypt(CiphertextBlob=b64decode(encrypted_token))['Plaintext'] return request_token == expected_token
[ "def validate_token(request_slack_token):\n if request_slack_token == os.environ['SLACK_TOKEN']:\n return\n else:\n raise ValueError", "def verify_token(token):\n if token != os.getenv('SLACK_VERIFICATION_TOKEN'):\n raise SlackException('Invalid verification token')", "def is_reque...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests for successful fetch of user details
def test_fetch_user(self): self.register_user() self.assertEqual(self.fetch_user_details().status_code, 200) self.assertTrue(self.fetch_user_details( ).json["data"][0]["username"] == 'Bjorn')
[ "def test_api_auth_retrieve_user_details_success(self):\n self.client.credentials(HTTP_AUTHORIZATION=\"Token \" + self.token.key)\n response = self.client.get(self.user_details_url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.user.nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test pure strategy deviation gains
def test_pure_strategy_deviation_gains(): profiles = [ [2, 0, 2, 0], [2, 0, 1, 1], [2, 0, 0, 2], [1, 1, 2, 0], [1, 1, 1, 1], [1, 1, 0, 2], [0, 2, 2, 0], [0, 2, 1, 1], [0, 2, 0, 2], ] payoffs = [ [1, 0, 2, 0], [3, 0, 4, 5...
[ "def test_pooled_sd(self):\r\n exp = pooled_standard_deviation(self.pooled_sd_input_1)\r\n self.assertEqual(self.pooled_sd_result, exp)", "def test_stddev(self):\n self.assertEqual(stddev(list1, sample=False), np.std(list1))\n self.assertEqual(stddev(list1), np.std(list1, ddof=1))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test empty pure strategy deviation gains
def test_empty_pure_strategy_deviation_gains(): game = rsgame.empty(2, [2, 2]) gains = regret.pure_strategy_deviation_gains(game, [2, 0, 2, 0]) expected = [np.nan, np.nan, 0, 0, np.nan, np.nan, 0, 0] assert np.allclose(gains, expected, equal_nan=True)
[ "def test_pure_strategy_deviation_gains():\n profiles = [\n [2, 0, 2, 0],\n [2, 0, 1, 1],\n [2, 0, 0, 2],\n [1, 1, 2, 0],\n [1, 1, 1, 1],\n [1, 1, 0, 2],\n [0, 2, 2, 0],\n [0, 2, 1, 1],\n [0, 2, 0, 2],\n ]\n payoffs = [\n [1, 0, 2, 0],\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test mixed prisoners dilemma
def test_mixed_prisoners_dilemma(_): game = gamegen.sym_2p2s_game(2, 0, 3, 1) # prisoners dilemma eqm = [0, 1] assert ( regret.mixture_regret(game, eqm) == 0 ), "Known symmetric mixed was not zero regret"
[ "def test_mixed():\n # assert the distribution of the samples is close to the distribution of the data\n # using a kstest for continuous + a cstest for categorical.", "def test_mixed_NE():\n #payoff = np.array([[1,-1],[-1,1]]) # Matching Pennies\n payoff = np.array([[0,-1,1],[1,0,-1],[-1,1,0]]) # Rock...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test pure regret with incomplete data
def test_pure_incomplete_data(): profiles = [[2, 0]] payoffs = [[1.0, 0.0]] game = paygame.game(2, 2, profiles, payoffs) reg = regret.pure_strategy_regret(game, [2, 0]) assert np.isnan(reg), "regret of missing profile not nan"
[ "def testRegex(regex, example):", "def test_check_iod_line_regex_none():\n check_iod_line_regex()", "def ReTest(re_str, data, flags):\n len_re_str = len(re_str)\n for index in range(len_re_str, 0, -1):\n try:\n m = re.search(re_str[:index], data, flags)\n except: # many sre_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test pure welfare in zero sum games
def test_two_player_zero_sum_pure_wellfare(strategies): game = gamegen.two_player_zero_sum_game(strategies) for prof in game.profiles(): assert np.isclose( regret.pure_social_welfare(game, prof), 0 ), "zero sum profile wasn't zero sum"
[ "def test_non_zero_sum_profile_welfare():\n game = matgame.matgame([[[3.5, 2.5]]])\n assert np.isclose(\n regret.pure_social_welfare(game, [1, 1]), 6\n ), \"didn't properly sum welfare\"", "def test_non_zero_sum_mixture_welfare():\n game = matgame.matgame([[[3.5, 2.5]]])\n assert np.isclose(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test nonzero profile welfare
def test_non_zero_sum_profile_welfare(): game = matgame.matgame([[[3.5, 2.5]]]) assert np.isclose( regret.pure_social_welfare(game, [1, 1]), 6 ), "didn't properly sum welfare"
[ "def is_zero_profile(in_file):\n profile = restore_profile_from_csv(in_file)\n for i in range(0, profile.shape[0]):\n for j in range(0, profile.shape[1]):\n if profile[i, j] != 0:\n return False\n return True", "def test_positive_electrode_potential_profile(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test nonzero mixed welfare
def test_non_zero_sum_mixture_welfare(): game = matgame.matgame([[[3.5, 2.5]]]) assert np.isclose( regret.mixed_social_welfare(game, [1, 1]), 6 ), "Didn't properly sum welfare"
[ "def test_00_01_mask(self):\n np.random.seed(0)\n result = F.vprewitt(np.random.uniform(size=(10, 10)),\n np.zeros((10, 10), bool))\n assert (np.all(result == 0))", "def sanity_checker(self, w):\n sum_pos = numpy.sum(numpy.array([w1 for w1 in w if w1>=0]))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to write data frame to output path in csv format
def write_df_to_csv(output_df,file_path): output_df\ .coalesce(1)\ .write\ .format("csv")\ .option("header","true")\ .mode("overwrite")\ .save(file_path)
[ "def output_csv(df: pd.DataFrame, output_data_path: str):\n os.makedirs(os.path.dirname(output_data_path), exist_ok=True)\n df.to_csv(output_data_path)", "def write_dataframe_to_file(dataframe, output_filename):\n\n dataframe.to_csv(output_filename, sep=\"\\t\", index=False)\n print(f\"Success: Output...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }