query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels.
def load_data_and_labels_without_shuffled(): # Load data from files with codecs.open('./data/train_pos.txt', 'r+', 'utf-8') as f: train_pos = f.readlines() with codecs.open('./data/dev_pos.txt', 'r+', 'utf-8') as f: dev_pos = f.readlines() with codecs.open('./data/train_neg.txt', 'r+', 'utf-8') as f: train_neg = f.readlines() with codecs.open('./data/dev_neg.txt', 'r+', 'utf-8') as f: dev_neg = f.readlines() positive_examples1 = [] positive_examples2 = [] negative_examples1 = [] negative_examples2 = [] for i in train_pos: item1, item2 = i.split('\t') item1 = remove_stop_word(item1) item2 = remove_stop_word(item2) positive_examples1.append(item1) positive_examples2.append(item2) for i in train_neg: item1, item2 = i.split('\t') item1 = remove_stop_word(item1) item2 = remove_stop_word(item2) negative_examples1.append(item1) negative_examples2.append(item2) # Split by words x_text_train1 = positive_examples1 + negative_examples1 x_text_train2 = positive_examples2 + negative_examples2 positive_dev1 = [] positive_dev2 = [] negative_dev1 = [] negative_dev2 = [] for i in dev_pos: item1, item2 = i.split('\t') item1 = remove_stop_word(item1) item2 = remove_stop_word(item2) positive_dev1.append(item1) positive_dev2.append(item2) for i in dev_neg: item1, item2 = i.split('\t') item1 = remove_stop_word(item1) item2 = remove_stop_word(item2) negative_dev1.append(item1) negative_dev2.append(item2) x_text_dev1 = positive_dev1 + negative_dev1 x_text_dev2 = positive_dev2 + negative_dev2 # Generate labels train_positive_labels = [[0, 1] for _ in train_pos] dev_positive_labels = [[0, 1] for _ in dev_pos] train_negative_labels = [[1, 0] for _ in train_neg] dev_negative_labels = [[1, 0] for _ in dev_neg] y_train = np.concatenate([train_positive_labels, train_negative_labels], 0) y_dev = np.concatenate([dev_positive_labels, dev_negative_labels], 0) return [x_text_train1, x_text_train2, x_text_dev1, x_text_dev2, y_train, y_dev]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_data_and_labels():\n # Load data from files\n positive_examples = list(\n open(\"./data/rt-polarity.pos\", \"r\", encoding='latin-1').readlines())\n positive_examples = [s.strip() for s in positive_examples]\n negative_examples = list(\n open(\"./data/rt-polarity.neg\", \"r\", en...
[ "0.7615511", "0.7190876", "0.68102527", "0.67267877", "0.6636343", "0.65735227", "0.6539939", "0.6465734", "0.64292496", "0.6304949", "0.6301084", "0.6295304", "0.6271314", "0.6269045", "0.61948806", "0.6137916", "0.6116728", "0.6078847", "0.6076159", "0.6075476", "0.605736",...
0.66374993
4
Builds a vocabulary mapping from word to index based on the sentences. Returns vocabulary mapping and inverse vocabulary mapping.
def build_vocab(sentences): # Build vocabulary word_counts = Counter(itertools.chain(*sentences)) # 实际没用到 # Mapping from index to word vocabulary_inv = [x[0] for x in word_counts.most_common()] vocabulary_inv = list(sorted(vocabulary_inv)) # 加入 <UNK> vocabulary_inv.insert(0, '</s>') # Mapping from word to index vocabulary = {x: i for i, x in enumerate(vocabulary_inv)} return [vocabulary, vocabulary_inv]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_vocab(self, sentences):\n\t\t# Build the vocab\n\t\tword_counts = collections.Counter(sentences)\n\n\t\t# Mapping from index to word (get the indices of most common words)\n\t\tvocab_inv = [x[0] for x in word_counts.most_common()] # Do we need this?\n\t\tvocab_inv = list(sorted(vocab_inv))\n\n\t\t# Mapp...
[ "0.79638803", "0.7715133", "0.7715133", "0.7715133", "0.76599747", "0.7653059", "0.7552094", "0.74614453", "0.69518715", "0.6917704", "0.68646234", "0.68494624", "0.67772037", "0.6662719", "0.6608852", "0.65526927", "0.65498227", "0.6457259", "0.6451463", "0.6442439", "0.6440...
0.7844205
1
Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences.
def pad_sentences(sentences, padding_word="<PAD/>"): # !!! 一定要注意这里会影响数据的形状,要与代码内的 sequence length 保持一致 !!! sequence_length = 30 # sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i in range(len(sentences)): sentence = sentences[i][:sequence_length] num_padding = sequence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding padded_sentences.append(new_sentence) return padded_sentences
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pad_sentences(sentences, padding_word=\"<PAD/>\"):\n sequence_length = max(len(x) for x in sentences)\n padded_sentences = []\n for i in range(len(sentences)):\n sentence = sentences[i]\n num_padding = sequence_length - len(sentence)\n new_sentence = sentence + [padding_word] * nu...
[ "0.8116531", "0.8083582", "0.8041561", "0.7986152", "0.79414433", "0.7637198", "0.75545436", "0.7517852", "0.7492193", "0.7338666", "0.7041751", "0.7004114", "0.69546854", "0.6900307", "0.68227386", "0.6682252", "0.6641073", "0.6603725", "0.6601419", "0.6599529", "0.65984535"...
0.8030784
3
Maps sentencs and labels to vectors based on a vocabulary.
def build_input_data(sentences, vocabulary): count = 0 seq2seq_sentences = [] for sentence in sentences: seq2seq_sentence = [] for word in sentence: try: seq2seq_sentence.append(vocabulary[word]) except KeyError: seq2seq_sentence.append(vocabulary['</s>']) count += 1 seq2seq_sentences.append(seq2seq_sentence) print count return np.array(seq2seq_sentences)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_vocab(sentences):\n # Build vocabulary\n word_counts = Counter(itertools.chain(*sentences)) # 实际没用到\n # Mapping from index to word\n vocabulary_inv = [x[0] for x in word_counts.most_common()]\n vocabulary_inv = list(sorted(vocabulary_inv))\n # 加入 <UNK>\n vocabulary_inv.insert(0, '</...
[ "0.7294365", "0.70796233", "0.70616835", "0.700586", "0.700586", "0.700586", "0.69982046", "0.69713277", "0.68781686", "0.6814168", "0.679631", "0.6701771", "0.6628131", "0.66187143", "0.6590109", "0.65756196", "0.6565486", "0.65587103", "0.6492771", "0.6482376", "0.6426598",...
0.6217245
42
Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary.
def load_data(): # Load and preprocess data x_text_train1, x_text_train2, x_text_dev1, x_text_dev2, y_train, y_dev = load_data_and_labels_without_shuffled() x_text_train1 = split_sentence(x_text_train1) x_text_train2 = split_sentence(x_text_train2) x_text_dev1 = split_sentence(x_text_dev1) x_text_dev2 = split_sentence(x_text_dev2) x_text_train1 = pad_sentences(x_text_train1) x_text_train2 = pad_sentences(x_text_train2) x_text_dev1 = pad_sentences(x_text_dev1) x_text_dev2 = pad_sentences(x_text_dev2) # sentences = x_text_train1 + x_text_train2 + x_text_dev1 + x_text_dev2 # vocabulary, vocabulary_inv = build_vocab(sentences) # x_text_train1 = build_input_data(x_text_train1, vocabulary) # x_text_train2 = build_input_data(x_text_train2, vocabulary) # x_text_dev1 = build_input_data(x_text_dev1, vocabulary) # x_text_dev2 = build_input_data(x_text_dev2, vocabulary) x_train1 = sentence_word2vec(x_text_train1) x_train2 = sentence_word2vec(x_text_train2) x_dev1 = sentence_word2vec(x_text_dev1) x_dev2 = sentence_word2vec(x_text_dev2) y_train = np.array(y_train) y_dev = np.array(y_dev) # return [x_text_train1, x_text_train2, x_text_dev1, x_text_dev2, y_train, y_dev, vocabulary, vocabulary_inv] return [x_train1, x_train2, x_dev1, x_dev2, y_train, y_dev]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_data():\n # Load and preprocess data\n sentences, labels = load_data_and_labels()\n sentences_padded = pad_sentences(sentences)\n vocabulary, vocabulary_inv = build_vocab(sentences_padded)\n x, y = build_input_data(sentences_padded, labels, vocabulary)\n return [x, y, vocabulary, vocabul...
[ "0.7270907", "0.6811596", "0.6781514", "0.663366", "0.6511913", "0.64549154", "0.6454384", "0.6444618", "0.6405498", "0.6399058", "0.6371277", "0.6303841", "0.63015515", "0.62549603", "0.61739635", "0.6170799", "0.61557263", "0.6155556", "0.6148963", "0.60986376", "0.6094318"...
0.6727568
3
Estimate the true signal mean and interpolate bad channels. This function implements the functionality of the `performReference` function as part of the PREP pipeline on mne raw object. Notes This function calls robust_reference first Currently this function only implements the functionality of default settings, i.e., doRobustPost
def perform_reference(self): # Phase 1: Estimate the true signal mean with robust referencing self.robust_reference() if self.noisy_channels["bad_all"]: self.raw.info["bads"] = self.noisy_channels["bad_all"] self.raw.interpolate_bads() self.reference_signal = ( np.nanmean(self.raw.get_data(picks=self.reference_channels), axis=0) * 1e6 ) rereferenced_index = [ self.ch_names_eeg.index(ch) for ch in self.rereferenced_channels ] self.EEG = self.remove_reference( self.EEG, self.reference_signal, rereferenced_index ) # Phase 2: Find the bad channels and interpolate self.raw._data = self.EEG * 1e-6 noisy_detector = NoisyChannels(self.raw) noisy_detector.find_all_bads(ransac=self.ransac) # Record Noisy channels and EEG before interpolation self.bad_before_interpolation = noisy_detector.get_bads(verbose=True) self.EEG_before_interpolation = self.EEG.copy() bad_channels = _union(self.bad_before_interpolation, self.unusable_channels) self.raw.info["bads"] = bad_channels self.raw.interpolate_bads() reference_correct = ( np.nanmean(self.raw.get_data(picks=self.reference_channels), axis=0) * 1e6 ) self.EEG = self.raw.get_data() * 1e6 self.EEG = self.remove_reference( self.EEG, reference_correct, rereferenced_index ) # reference signal after interpolation self.reference_signal_new = self.reference_signal + reference_correct # MNE Raw object after interpolation self.raw._data = self.EEG * 1e-6 # Still noisy channels after interpolation self.interpolated_channels = bad_channels noisy_detector = NoisyChannels(self.raw) noisy_detector.find_all_bads(ransac=self.ransac) self.still_noisy_channels = noisy_detector.get_bads() self.raw.info["bads"] = self.still_noisy_channels return self
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def robust_reference(self):\n raw = self.raw.copy()\n raw._data = removeTrend(raw.get_data(), sample_rate=self.sfreq)\n\n # Determine unusable channels and remove them from the reference channels\n noisy_detector = NoisyChannels(raw, do_detrend=False)\n noisy_detector.find_all_ba...
[ "0.72033346", "0.51534164", "0.51021534", "0.5064311", "0.50264406", "0.50084466", "0.49690974", "0.49434143", "0.4942057", "0.4890532", "0.4875339", "0.4820547", "0.4813191", "0.47748223", "0.47736692", "0.47729418", "0.47667706", "0.4733884", "0.47221825", "0.47158694", "0....
0.80031914
0
Detect bad channels and estimate the robust reference signal. This function implements the functionality of the `robustReference` function as part of the PREP pipeline on mne raw object.
def robust_reference(self): raw = self.raw.copy() raw._data = removeTrend(raw.get_data(), sample_rate=self.sfreq) # Determine unusable channels and remove them from the reference channels noisy_detector = NoisyChannels(raw, do_detrend=False) noisy_detector.find_all_bads(ransac=self.ransac) self.noisy_channels_original = { "bad_by_nan": noisy_detector.bad_by_nan, "bad_by_flat": noisy_detector.bad_by_flat, "bad_by_deviation": noisy_detector.bad_by_deviation, "bad_by_hf_noise": noisy_detector.bad_by_hf_noise, "bad_by_correlation": noisy_detector.bad_by_correlation, "bad_by_ransac": noisy_detector.bad_by_ransac, "bad_all": noisy_detector.get_bads(), } self.noisy_channels = self.noisy_channels_original.copy() logger.info("Bad channels: {}".format(self.noisy_channels)) self.unusable_channels = _union( noisy_detector.bad_by_nan, noisy_detector.bad_by_flat ) # unusable_channels = _union(unusable_channels, noisy_detector.bad_by_SNR) self.reference_channels = _set_diff( self.reference_channels, self.unusable_channels ) # Get initial estimate of the reference by the specified method signal = raw.get_data() * 1e6 self.reference_signal = ( np.nanmedian(raw.get_data(picks=self.reference_channels), axis=0) * 1e6 ) reference_index = [ self.ch_names_eeg.index(ch) for ch in self.reference_channels ] signal_tmp = self.remove_reference( signal, self.reference_signal, reference_index ) # Remove reference from signal, iteratively interpolating bad channels raw_tmp = raw.copy() iterations = 0 noisy_channels_old = [] max_iteration_num = 4 while True: raw_tmp._data = signal_tmp * 1e-6 noisy_detector = NoisyChannels(raw_tmp) noisy_detector.find_all_bads(ransac=self.ransac) self.noisy_channels["bad_by_nan"] = _union( self.noisy_channels["bad_by_nan"], noisy_detector.bad_by_nan ) self.noisy_channels["bad_by_flat"] = _union( self.noisy_channels["bad_by_flat"], noisy_detector.bad_by_flat ) self.noisy_channels["bad_by_deviation"] = _union( self.noisy_channels["bad_by_deviation"], noisy_detector.bad_by_deviation ) self.noisy_channels["bad_by_hf_noise"] = _union( self.noisy_channels["bad_by_hf_noise"], noisy_detector.bad_by_hf_noise ) self.noisy_channels["bad_by_correlation"] = _union( self.noisy_channels["bad_by_correlation"], noisy_detector.bad_by_correlation, ) self.noisy_channels["bad_by_ransac"] = _union( self.noisy_channels["bad_by_ransac"], noisy_detector.bad_by_ransac ) self.noisy_channels["bad_all"] = _union( self.noisy_channels["bad_all"], noisy_detector.get_bads() ) logger.info("Bad channels: {}".format(self.noisy_channels)) if ( iterations > 1 and ( not self.noisy_channels["bad_all"] or set(self.noisy_channels["bad_all"]) == set(noisy_channels_old) ) or iterations > max_iteration_num ): break noisy_channels_old = self.noisy_channels["bad_all"].copy() if raw_tmp.info["nchan"] - len(self.noisy_channels["bad_all"]) < 2: raise ValueError( "RobustReference:TooManyBad " "Could not perform a robust reference -- not enough good channels" ) if self.noisy_channels["bad_all"]: raw_tmp._data = signal * 1e-6 raw_tmp.info["bads"] = self.noisy_channels["bad_all"] raw_tmp.interpolate_bads() signal_tmp = raw_tmp.get_data() * 1e6 else: signal_tmp = signal self.reference_signal = ( np.nanmean(raw_tmp.get_data(picks=self.reference_channels), axis=0) * 1e6 ) signal_tmp = self.remove_reference( signal, self.reference_signal, reference_index ) iterations = iterations + 1 logger.info("Iterations: {}".format(iterations)) logger.info("Robust reference done") return self.noisy_channels, self.reference_signal
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def perform_reference(self):\n # Phase 1: Estimate the true signal mean with robust referencing\n self.robust_reference()\n if self.noisy_channels[\"bad_all\"]:\n self.raw.info[\"bads\"] = self.noisy_channels[\"bad_all\"]\n self.raw.interpolate_bads()\n self.refere...
[ "0.7477632", "0.6277125", "0.59613264", "0.58670795", "0.55491996", "0.53819615", "0.5299285", "0.5188852", "0.51496625", "0.5102384", "0.50921977", "0.5008404", "0.49466848", "0.4929399", "0.49203682", "0.49124527", "0.48961046", "0.48734668", "0.48694846", "0.48172373", "0....
0.79005593
0
Remove the reference signal from the original EEG signal. This function implements the functionality of the `removeReference` function as part of the PREP pipeline on mne raw object.
def remove_reference(signal, reference, index=None): if np.ndim(signal) != 2: raise ValueError( "RemoveReference: EEG signal must be 2D array (channels * times)" ) if np.ndim(reference) != 1: raise ValueError("RemoveReference: Reference signal must be 1D array") if np.shape(signal)[1] != np.shape(reference)[0]: raise ValueError( "RemoveReference: The second dimension of EEG signal must be " "the same with the length of reference signal" ) if index is None: signal_referenced = signal - reference else: if not isinstance(index, list): raise TypeError( "RemoveReference: Expected type list, got {} instead".format( type(index) ) ) signal_referenced = signal.copy() signal_referenced[np.asarray(index), :] = ( signal[np.asarray(index), :] - reference ) return signal_referenced
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def removeReference(self, reference: ghidra.program.model.symbol.Reference) -> None:\n ...", "def removeReferenceGlyph(self, *args):\n return _libsbml.GeneralGlyph_removeReferenceGlyph(self, *args)", "def _remove_reference(self, target):\n assert target in self._referenced_nodes\n ...
[ "0.7395361", "0.618159", "0.6136284", "0.6101331", "0.59427154", "0.58940864", "0.58332074", "0.57739156", "0.5770895", "0.5762816", "0.5671317", "0.56659806", "0.5665375", "0.5660799", "0.5658297", "0.5644026", "0.5601565", "0.5555541", "0.5552319", "0.5550075", "0.5489779",...
0.7985783
0
Sets the buy list for the board
def setBuyList(self, buyList): parsedBuyList = [] for bought in buyList: if hasattr(bought, "unitType"): parsedBuyList.append(bought) elif isinstance(bought, dict) and u'unitType' in bought and u'territory' in bought: parsedBuyList.append(createBoughtUnitFromDict(bought, self.board.territories)) else: raise Exception("Invalid buy list", buyList) sumCost = self.costOfUnits(parsedBuyList) if sumCost <= self.board.currentCountry.money: self.board.buyList = parsedBuyList[:] # copy in buyList return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def buys(self, buys):\n\n self._buys = buys", "def set_buy_sell_deal_account(self, account_list):\n self.multiple_items_selection_from_kendo_dropdown(self.buy_sell_deal_account_dropdown_locator, account_list)\n self.wait_for_ajax_spinner_load()", "def set_target_buy_list(self, item_name, i...
[ "0.6422962", "0.6265", "0.5775737", "0.5630926", "0.5596823", "0.5562822", "0.55483556", "0.5545518", "0.5418781", "0.53955275", "0.535245", "0.5310174", "0.5309824", "0.53068644", "0.5252064", "0.52498454", "0.5239531", "0.5211751", "0.5184596", "0.51813936", "0.5175984", ...
0.6954832
0
Converts an object into a json string
def SerializeObject(self, data): if isinstance(data,dict): serializad_data = json.dumps(data) else: serializad_data = json.dumps(data.__dict__) return serializad_data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def toJSON(object):\n\treturn json.dumps(object, ensure_ascii=False)", "def toJSON(cls, obj):\n return json.dumps(obj)", "def to_json_string(my_obj):\n return json.dumps(my_obj)", "def to_json_string(my_obj):\n return json.dumps(my_obj)", "def to_json_string(my_obj):\n return json.dumps(my_...
[ "0.83760744", "0.83283734", "0.81909037", "0.81909037", "0.81909037", "0.81909037", "0.81712186", "0.81712186", "0.81665546", "0.81609154", "0.8029213", "0.7942642", "0.79287285", "0.79166585", "0.78885394", "0.77051455", "0.7690964", "0.76449054", "0.76258", "0.755187", "0.7...
0.7041254
42
Converts json string in related object object_to_serialize have to be an instace of the desired to convert object
def DeserializeJson(self, json_string, object_to_serialize): object_to_serialize.__dict__ = json.loads(str(json_string)) return object_to_serialize
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_serializable(o: Any) -> Any:\n if isinstance(o, UUID):\n return str(o)\n if isinstance(o, datetime):\n return isoformat(o)\n if is_dataclass(o):\n return asdict(o)\n if hasattr(o, \"__json__\"):\n return o.__json__()\n if hasattr(o, \"to_dict\"):\n # api_cli...
[ "0.68756694", "0.6863126", "0.68572044", "0.68323946", "0.68267304", "0.6792545", "0.67513794", "0.6714095", "0.6697272", "0.66942084", "0.6680018", "0.6673534", "0.6665409", "0.6663698", "0.6646167", "0.6644696", "0.6639211", "0.6623753", "0.66212523", "0.66212523", "0.66212...
0.7826462
0
Constructs a DVR object
def DVR( domain=None, divs=None, classes=None, potential_function=None, g=None, g_deriv=None, scf=False, potential_optimize=False, **base_opts ): return DVRConstructor.construct( domain=domain, divs=divs, classes=classes, potential_function=potential_function, g=g, g_deriv=g_deriv, scf=scf, potential_optimize=potential_optimize, **base_opts )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, dzdt, v, e, D):\n self.V = dzdt\n self.v = v\n self.e = e\n self.D = D\n self.laminar_label = \"Laminar\"\n self.critical_label = \"Critical\"\n self.turbulent_label = \"Turbulent\"", "def __init__(self, dr_ds: DatasetReader) -> None:\n s...
[ "0.61528945", "0.60658884", "0.599728", "0.59843045", "0.59223074", "0.5918787", "0.5913648", "0.5847089", "0.5769131", "0.5743365", "0.57272416", "0.57149744", "0.57125163", "0.5688939", "0.56877244", "0.5670665", "0.56602484", "0.56357646", "0.5623393", "0.5620744", "0.5612...
0.7178919
0
Run the entire NBA_bet project.
def run_all(): db = DBInterface() year = Config.get_property("league_year") session = Session(bind=db.engine) scraper.scrape_all(db, session, year) session.commit() bets.predict_all(db, session) session.commit() session.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n boba_blast_game.main()", "def run():\n\n # Set up environment and agent\n e = Environment() # create environment (also adds some dummy traffic)\n a = e.create_agent(LearningAgent) # create agent\n e.set_primary_agent(a, enforce_deadline=False) # set agent to track\n\n # Now sim...
[ "0.66027266", "0.6353985", "0.6346927", "0.6313131", "0.62619185", "0.62193763", "0.62180185", "0.6216404", "0.6215654", "0.61611444", "0.6076099", "0.6034337", "0.602182", "0.59690386", "0.5968432", "0.59557575", "0.59223056", "0.5915671", "0.5899744", "0.58864325", "0.58760...
0.5997161
13
the function takes an images and try to quantify the roundness of the photo generated plasma
def round_score(file_name, target_file_name, save_calibration = False, target_directory = "ScreenCaps_contour"): try: img = Image.open(file_name).convert('L') except: raise NameError("The script failed to open the image") # (width, height) = img.size img_arr = np.asarray(img).copy() # copy to avoid working on the original data img_arrN = img_arr/255 # finding the maximum value of the array max_value_of_array = 0 for i in img_arrN: if max(i) > max_value_of_array: max_value_of_array = max(i) # renormalization with the maximum value for i in range(len(img_arrN)): for j in range(len(img_arrN[0])): img_arrN[i, j] = img_arrN[i, j] / max_value_of_array # we applied some filters img_arrN = filters.gaussian(img_arrN, 2) img_arrN = abs(sig.convolve(img_arrN, kernel_test)) # contrast img_arrN = np.int8(img_arrN) # countour detecting crit = 0.02 ct = np.zeros(shape=img_arrN.shape) for i in range(len(img_arrN) - 1): for j in range(len(img_arrN[0]) - 1): if abs(img_arrN[i+1, j] - img_arrN[i, j]) > crit: ct[i, j] = 1 if abs(img_arrN[i, j+1] - img_arrN[i, j]) > crit: ct[i, j] = 1 #find the true center idx_h = np.sum(ct,axis=0) idx_v = np.sum(ct,axis=1) count = 0 total_h = 0 for x in idx_h: count += 1 if x != 0: total_h += count if (np.count_nonzero(idx_h) == 0) or (np.count_nonzero(idx_v) == 0): return 1 center_x = total_h/np.count_nonzero(idx_h) total_v = 0 count = 0 for x in idx_v: count += 1 if x != 0: total_v += count center_y = total_v/np.count_nonzero(idx_v) center = [center_y, center_x] # calculate the mean radius and the score radius = [] for i in range(len(ct)): for j in range(len(ct[0])): if ct[i, j] == 1: radius.append(np.sqrt((i - center[0])**2 + (j - center[1])**2)) radius_mean = np.mean(radius) # radius /= radius_mean score = 0 if radius_mean < 0.1: return 1 for i in radius: score += abs(i - radius_mean)/radius_mean #print(score/len(radius)) # getting the cercle with the radius_mean as the radius # for i in range(len(ct)): # for j in range(len(ct[0])): # if ct[i, j] != 1: # if np.sqrt((i-center[0])**2 + (j-center[1])**2) <= radius_mean: # ct[i, j] = 1 img_gs = Image.fromarray(np.uint8(ct)*255) img_gs.save("{}/{}".format(target_directory, target_file_name)) if save_calibration: calibration_visualisation(radius_mean, center, img_arrN.shape, ct, target_file_name, target_directory) return score/len(radius)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def quantize(image_patch, gray_levels=12, n_stddev=2):\n # compute gray level gaussian stats\n mean = np.mean(image_patch)\n stddev = np.std(image_patch)\n # logger.debug('mean: {!s}\\nstd dev: {!s}'.format(mean, stddev))\n bin_width = 2*n_stddev*stddev / (gray_levels-2)\n # logger.debug('bin_...
[ "0.60352147", "0.5991346", "0.59536624", "0.59423345", "0.5887183", "0.58796984", "0.5852654", "0.5849112", "0.58206713", "0.5803636", "0.5785182", "0.57806164", "0.57765096", "0.576138", "0.57505316", "0.5739448", "0.5710007", "0.5701599", "0.5683255", "0.5672449", "0.565078...
0.0
-1
Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method.
def format(self, response): res = self._prepare_response(response) res.content = self._format_data(res.content, self.charset) return self._finalize_response(res)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def format_data(self, data):", "def format(self, data):", "def formatted_data(self):\n return self._formatted_data", "def _formatData(self):\r\n assert self._runData is not None\r\n\r\n # Getting Axes data into separate lists\r\n x=[]; y=[]; z=[]\r\n for i in range(len(self...
[ "0.8710108", "0.8226497", "0.73157656", "0.69565845", "0.6939006", "0.69311357", "0.69138837", "0.6854443", "0.67923564", "0.6714074", "0.6688871", "0.66315264", "0.6579256", "0.65059084", "0.64873344", "0.6434863", "0.6407318", "0.6352616", "0.6308234", "0.6295145", "0.62939...
0.0
-1
Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes.
def parse(self, data, charset=None): charset = charset or self.charset return self._parse_data(data, charset)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse(self, data):\n raise NotImplementedError", "def parse(cls, data):\n raise NotImplementedError", "def parse_data(self):\n\t\traise NotImplementedError('%s: No parse function implemented!' % self.name)", "def parse_dataset(self, data):\n pass", "def parse(self, data):\n ...
[ "0.83383363", "0.8124831", "0.8103867", "0.7813138", "0.7209145", "0.71461093", "0.71073484", "0.70829093", "0.70819396", "0.7063399", "0.7004795", "0.6928474", "0.6914489", "0.69009197", "0.68570995", "0.6790236", "0.6790236", "0.6790236", "0.6790236", "0.67341244", "0.67255...
0.669551
21
Format the data data the data (may be None)
def _format_data(self, data, charset): return self._encode_data(data) if data else u''
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def format_data(self, data):", "def format(self, data):", "def format_data(self)->float: \n try:\n formatted = chr(self.data[0])\n for i in range(1, len(self.data)): \n formatted = formatted + (chr(self.data[i])) \n return str(formatted)\n...
[ "0.8829935", "0.8364288", "0.71631086", "0.6922519", "0.67930263", "0.6727314", "0.6676519", "0.6615989", "0.6539193", "0.64204735", "0.6417292", "0.640719", "0.63545674", "0.6275988", "0.6255942", "0.6243175", "0.6212364", "0.6212364", "0.62109625", "0.61957896", "0.6140141"...
0.747908
2
Coerce response to devil's Response
def _prepare_response(self, response): if not isinstance(response, Response): return Response(0, response) return response
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def adapt_response(self, response):\n return response", "def adapt_response(self, response):\n return response", "def parse_response(self, response: Any) -> Any:\n return response", "def _parse_response(self, response):\n if response is not None:\n return response.string\n ...
[ "0.773039", "0.773039", "0.72027785", "0.69940764", "0.6856815", "0.68360895", "0.67848694", "0.6754801", "0.6601165", "0.6534803", "0.6463667", "0.6463667", "0.64454454", "0.6439771", "0.6422133", "0.6422133", "0.6421432", "0.6416055", "0.64027804", "0.6400647", "0.639998", ...
0.6973536
4
Convert the ``Response`` object into django's ``HttpResponse``
def _finalize_response(self, response): res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set separately to allow zero res.status_code = response.code return res
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def to_http_response(self) -> HttpResponse:\n response = (\n JsonResponse(self.body)\n if (self.headers or {}).get(\"Content-Type\") == \"application/json\"\n else HttpResponse(self.body)\n )\n response.headers = self.headers\n return response", "def m...
[ "0.7379816", "0.7109294", "0.69839066", "0.6952941", "0.6952941", "0.6925957", "0.6925957", "0.69120204", "0.68229306", "0.6809943", "0.6809943", "0.6740994", "0.6736841", "0.6683467", "0.66039944", "0.65061057", "0.64141685", "0.640344", "0.6377596", "0.634833", "0.6296918",...
0.759568
0
Return ContentType header with charset info.
def _get_content_type(self): return '%s; charset=%s' % (self.content_type, self.charset)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def charset(self) -> Optional[str]:\n raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]\n if self._stored_content_type != raw:\n self._parse_content_type(raw)\n return self._content_dict.get(\"charset\") # type: ignore[union-attr]", "def content_type_header...
[ "0.7331894", "0.71138537", "0.6978401", "0.6755701", "0.6664483", "0.6629774", "0.6557151", "0.65387005", "0.65190446", "0.64697444", "0.64657295", "0.6446364", "0.642422", "0.6410978", "0.63235193", "0.6279511", "0.6264188", "0.623511", "0.6197167", "0.61729234", "0.6166692"...
0.74809164
0
Initialize the manager. The ``_datamappers`` dictionary is initialized here to make testing easier.
def __init__(self): self._datamappers = { '*/*': DataMapper() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self):\n self.data_set_loc = conf.config_section_mapper(\"filePath\").get(\"data_set_loc\")\n self.data_extractor = DataExtractor(self.data_set_loc)", "def do_init(self):\n\n pass", "def init(self, **kwargs):\n self._d = {}\n self._th = None\n self._run = ...
[ "0.6461124", "0.6418458", "0.6413563", "0.6375085", "0.6290806", "0.6228817", "0.6185347", "0.6185347", "0.6185347", "0.61723155", "0.61663306", "0.6159628", "0.6139021", "0.6131483", "0.61117107", "0.6094118", "0.6062833", "0.6062833", "0.6062833", "0.6062833", "0.6062833", ...
0.7486393
0
Select appropriate formatter based on the request.
def select_formatter(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from accept header mapper_name = self._get_name_from_accept(request) if mapper_name: return self._get_mapper(mapper_name) # 4. use resource's default if resource.default_mapper: return resource.default_mapper # 5. use manager's default return self._get_default_mapper()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _determine_format(self, request):\n return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)", "def determine_format(request, serializer, default_format='application/json'):\r\n # First, check if they forced the format.\r\n if request.GET.get('format'):\r...
[ "0.70516115", "0.68860674", "0.67620766", "0.6718547", "0.641668", "0.62356836", "0.6230665", "0.61402184", "0.61402184", "0.6086643", "0.6054365", "0.59921783", "0.59283495", "0.5847288", "0.58354276", "0.5824539", "0.57529914", "0.5744481", "0.5692539", "0.569212", "0.56478...
0.7539723
0
Select appropriate parser based on the request.
def select_parser(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from content type mapper_name = self._get_name_from_content_type(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 4. use resource's default if resource.default_mapper: return resource.default_mapper # 5. use manager's default return self._get_default_mapper()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_parser():\n\n try:\n select_texttools_parser()\n except ImportError:\n select_python_parser()", "def get_parser(self):\n if self.vendor and self.platform and self.version:\n cls = self.profile.get_profile().get_parser(\n self.vendor.code, self.platform.name, se...
[ "0.67126334", "0.6521535", "0.6489922", "0.640149", "0.6139885", "0.61379045", "0.613299", "0.61198676", "0.6049748", "0.602667", "0.5946609", "0.58708733", "0.58408815", "0.5837304", "0.58118755", "0.5710313", "0.5667457", "0.5613246", "0.5606975", "0.5493934", "0.5479771", ...
0.73894787
0
Returs mapper based on the content type.
def get_mapper_by_content_type(self, content_type): content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mapper(self, structure):\n type_ = structure['type']\n mapper = self.mappers[type_]\n return mapper", "def mapper_for_type(self, type_):\n mapper = self.mappers[type_]\n return mapper", "def get_mapping_type(cls):\n ...", "def _get_mapper(obj):\n its_a_model =...
[ "0.6787792", "0.6768891", "0.62163997", "0.5705611", "0.56396294", "0.55432177", "0.5536067", "0.5350777", "0.53324276", "0.53072", "0.529081", "0.5220667", "0.5189422", "0.5182988", "0.51817083", "0.50861496", "0.50557506", "0.5036861", "0.50153947", "0.49689895", "0.4966391...
0.77844703
0
Set the default mapper to be used, when no format is defined. This is the same as calling ``register_mapper`` with ``/`` with the exception of giving ``None`` as parameter.
def set_default_mapper(self, mapper): mapper = mapper or DataMapper() self._datamappers['*/*'] = mapper
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_default_mapper(self):\n\n return self._datamappers['*/*']", "def set_mapper(obj, mapper):\n setattr(obj, MAPPER, mapper)\n return mapper", "def _get_mapper(self, mapper_name):\n\n if mapper_name in self._datamappers:\n # mapper found\n return self._datamappers...
[ "0.7185841", "0.5845222", "0.5408889", "0.5322639", "0.5239758", "0.5030067", "0.4899394", "0.48726788", "0.4867522", "0.48561874", "0.48168156", "0.4815694", "0.48097968", "0.48017895", "0.47900453", "0.4782826", "0.47522974", "0.47464633", "0.4713747", "0.46979213", "0.4691...
0.7901851
0
Return the default mapper.
def _get_default_mapper(self): return self._datamappers['*/*']
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_default_mapper(self, mapper):\n\n mapper = mapper or DataMapper()\n self._datamappers['*/*'] = mapper", "def mapper(self):\n if not self._fitted:\n raise ValueError(\"Cannot get mapper if object has not been fitted.\")\n return self._mapper.copy()", "def _get_mapp...
[ "0.6871667", "0.6705098", "0.66739136", "0.65977365", "0.6307456", "0.62351674", "0.6097825", "0.5983813", "0.59388465", "0.57689005", "0.5738587", "0.57277805", "0.57277805", "0.5723523", "0.56839365", "0.562199", "0.5607039", "0.5599599", "0.5549087", "0.553436", "0.5475148...
0.8958518
0
Return the mapper based on the given name.
def _get_mapper(self, mapper_name): if mapper_name in self._datamappers: # mapper found return self._datamappers[mapper_name] else: # unsupported format return self._unknown_format(mapper_name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lookup(self, name):\n try:\n return self._baseLookup(name)\n except ImportError:\n raise ImportError(\"No module named %r in mapper %r\" % (name, self))", "def get(cls, name):\n cls.initialize()\n if isinstance(name, cls):\n return name\n el...
[ "0.69885236", "0.6523901", "0.64461076", "0.63601327", "0.6340254", "0.6093008", "0.60604954", "0.60452425", "0.59643584", "0.5960165", "0.59453994", "0.589722", "0.5801919", "0.567288", "0.5612674", "0.5609351", "0.55997974", "0.559257", "0.55712503", "0.5496303", "0.5479467...
0.7992836
0
Get name from ContentType header
def _get_name_from_content_type(self, request): content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def content_type_header(request: Request) -> str:\n return request.content_type", "def gettype(self, failobj=None):\n missing = []\n value = self.get('content-type', missing)\n if value is missing:\n return failobj\n return re.split(r';\\s*', value.strip())[0].lower()", ...
[ "0.6892327", "0.6575444", "0.65093666", "0.6481238", "0.6447588", "0.63857204", "0.6333128", "0.63329685", "0.6310448", "0.6281364", "0.6262302", "0.62129503", "0.6198477", "0.61856425", "0.608376", "0.60403216", "0.5957448", "0.5953572", "0.59456986", "0.5944716", "0.5935226...
0.78704923
0
Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support.
def _get_name_from_accept(self, request): accepts = util.parse_accept_header(request.META.get("HTTP_ACCEPT", "")) if not accepts: return None for accept in accepts: if accept[0] in self._datamappers: return accept[0] raise errors.NotAcceptable()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _accept_strategy(self, host, port, environ, supported_content_types):\n accept = Accept(environ.get('HTTP_ACCEPT', ''))\n\n app = None\n\n # Find the best match in the Accept header\n mime_type, params = accept.best_match(supported_content_types)\n if 'version' in params:\n ...
[ "0.7370754", "0.6847089", "0.6750999", "0.6682592", "0.6649257", "0.65085864", "0.6476922", "0.6448833", "0.6262016", "0.61876094", "0.6172913", "0.6024761", "0.5840581", "0.5723091", "0.56867343", "0.5537604", "0.5529102", "0.55037165", "0.5392582", "0.5388047", "0.5382728",...
0.6449594
7
Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json).
def _get_name_from_url(self, request): format = request.GET.get('format', None) if not format: match = self._format_query_pattern.match(request.path) if match and match.group('format'): format = match.group('format') return format
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def url_name(request):\n url_name = False\n if request.resolver_match:\n url_name = request.resolver_match.url_name\n return {\"url_name\": url_name}", "def shorten_url():\n return rh.shorten_url(request)", "def _shortenUrl(self, url):\n posturi = \"https://www.googleapis.com/urlshort...
[ "0.6074111", "0.6005944", "0.5902819", "0.58046716", "0.5792287", "0.5767634", "0.57404774", "0.57221323", "0.57147455", "0.5575753", "0.5546919", "0.5540886", "0.553158", "0.55257696", "0.5518946", "0.5516314", "0.54784685", "0.5469388", "0.544259", "0.54098177", "0.5381609"...
0.66325134
0
Deal with the situation when we don't support the requested format.
def _unknown_format(self, format): raise errors.NotAcceptable('unknown data format: ' + format)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_format(self):\n raise NotImplementedError()", "def _determine_format(self, request):\n return determine_format(request, self._meta.serializer, default_format=self._meta.default_format)", "def validateWorkFormat(format):\n\n if not(format):\n return \"You must select a work ...
[ "0.7758894", "0.6573002", "0.6391546", "0.6325112", "0.62708557", "0.6243621", "0.6233522", "0.6175671", "0.6166886", "0.61477107", "0.61403495", "0.60342926", "0.60149646", "0.6010532", "0.5987411", "0.5959781", "0.5955787", "0.5895473", "0.58931667", "0.58854645", "0.588295...
0.76091594
1
Check that the mapper has valid signature.
def _check_mapper(self, mapper): if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise ValueError('mapper must implement format()')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def verify_signature(self, inputs, signature):\n pass", "def verify_signature(self, inputs, signature):\n pass", "def signature_check(dummy, *args, **kwargs):\n try:\n dummy(*args, **kwargs)\n return True\n\n except TypeError:\n return False", "def _check_type(self):\...
[ "0.6831698", "0.6831698", "0.6462788", "0.6245771", "0.62307477", "0.6047557", "0.601151", "0.5921455", "0.59146875", "0.5847448", "0.58155686", "0.57982296", "0.577483", "0.5725613", "0.57252246", "0.5719018", "0.5713518", "0.57050633", "0.56824374", "0.5622677", "0.561941",...
0.73222697
0
Set up the Zigbee Home Automation device tracker from config entry.
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: entities_to_create = hass.data[DATA_ZHA][Platform.DEVICE_TRACKER] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create ), ) config_entry.async_on_unload(unsub)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setup_platform(\n hass: HomeAssistant,\n config: ConfigType,\n add_entities: AddEntitiesCallback,\n discovery_info: DiscoveryInfoType | None = None,\n) -> None:\n name = config.get(CONF_NAME)\n mac = config.get(CONF_MAC)\n _LOGGER.debug(\"Setting up\")\n\n mon = Monitor(hass, mac, name)...
[ "0.645116", "0.6365515", "0.6173198", "0.6137033", "0.6097791", "0.60210615", "0.5982656", "0.5962991", "0.5919882", "0.5888324", "0.5879143", "0.5873886", "0.58680475", "0.5860574", "0.5820853", "0.58103406", "0.5783399", "0.57670003", "0.5749506", "0.57469505", "0.5705554",...
0.0
-1
Initialize the ZHA device tracker.
def __init__(self, unique_id, zha_device, cluster_handlers, **kwargs): super().__init__(unique_id, zha_device, cluster_handlers, **kwargs) self._battery_cluster_handler = self.cluster_handlers.get( CLUSTER_HANDLER_POWER_CONFIGURATION ) self._connected = False self._keepalive_interval = 60 self._battery_level = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def init(self):\n logger.info(\"Init device: %s\", self._serial)\n self._callback(STATUS_INIT)\n\n self._init_binaries()\n self._init_apks()\n await self._init_forwards()\n\n await adb.shell(self._serial, \"/data/local/tmp/atx-agent server --stop\")\n await ad...
[ "0.65205735", "0.6469632", "0.6374689", "0.6327194", "0.6239735", "0.62235254", "0.62131935", "0.61628926", "0.61628926", "0.61628926", "0.6160946", "0.61380124", "0.61321", "0.610218", "0.60903937", "0.6049556", "0.60407215", "0.6000517", "0.59815305", "0.596642", "0.5956365...
0.59739983
19
Run when about to be added to hass.
async def async_added_to_hass(self) -> None: await super().async_added_to_hass() if self._battery_cluster_handler: self.async_accept_signal( self._battery_cluster_handler, SIGNAL_ATTR_UPDATED, self.async_battery_percentage_remaining_updated, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def async_added_to_hass(self):\n\n def gpio_edge_listener(port):\n \"\"\"Update GPIO when edge change is detected.\"\"\"\n self.schedule_update_ha_state(True)\n\n def setup_entity():\n setup_input(self._port)\n edge_detect(self._port, gpio_edge_listen...
[ "0.68537086", "0.6834448", "0.6687171", "0.6658029", "0.6650727", "0.657596", "0.65477496", "0.65373653", "0.6497973", "0.64905834", "0.64446324", "0.64446324", "0.64271516", "0.64118624", "0.64040715", "0.64040715", "0.64040715", "0.6399848", "0.6393785", "0.6379698", "0.637...
0.6008163
65
Return true if the device is connected to the network.
def is_connected(self): return self._connected
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_connected():\n sta_if = network.WLAN(network.STA_IF)\n return sta_if.isconnected()", "def is_connected(self):\n return self._port.is_connected()", "def isconnected(self):\n return self._wlan.isconnected()", "def is_connected(self):\n return self.hw_connected", "def is_connecte...
[ "0.7903595", "0.78890985", "0.7884118", "0.78780943", "0.7753229", "0.7727309", "0.7695511", "0.76544905", "0.76394", "0.7609661", "0.75915796", "0.7570455", "0.7563875", "0.75160927", "0.75101984", "0.749174", "0.7488076", "0.7486625", "0.74687254", "0.7448089", "0.74446356"...
0.73389804
43
Return the source type, eg gps or router, of the device.
def source_type(self) -> SourceType: return SourceType.ROUTER
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def source_type(self):\n return SOURCE_TYPE_GPS", "def source_type(self):\n return SOURCE_TYPE_GPS", "def source_type(self):\n return SOURCE_TYPE_ROUTER", "def source_type(self):\n return SOURCE_TYPE_ROUTER", "def source_type(self) -> Optional[str]:\n return pulumi.get(se...
[ "0.79885626", "0.79885626", "0.7760277", "0.7760277", "0.7449024", "0.72812986", "0.71759343", "0.66198623", "0.6579725", "0.64343446", "0.6371079", "0.62237245", "0.6218695", "0.6187604", "0.6182113", "0.61786586", "0.61733663", "0.61695445", "0.6154849", "0.6086145", "0.608...
0.7750512
5
Return the battery level of the device. Percentage from 0100.
def battery_level(self): return self._battery_level
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def battery_level(self):\n return self.battery", "def get_battery_level(self) -> int:\n\n try:\n self._serial.transmit(b'\\x51\\x00')\n response = self._get_reply(0x51, 1, 0.25)\n finally:\n self._gpio.sleep()\n\n return response[2]", "def battery_le...
[ "0.85965866", "0.8490694", "0.8206418", "0.8130491", "0.8092713", "0.80214363", "0.79328454", "0.7850373", "0.7657598", "0.760602", "0.7397481", "0.7355417", "0.723275", "0.7155458", "0.70573586", "0.70248145", "0.69043136", "0.6902873", "0.68718886", "0.68614537", "0.6757102...
0.84553003
2
Return an airport code input after validating it
def airportCodeInput(self, prompt): while True: code = input(prompt).upper() if code not in self.travel_db.airports: print("Invalid airport code") else: return code
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validateAirport(self, code):\n print(code)\n if code in self.travel_db.airports:\n return True\n else:\n return False", "def iata(code):\r\n if len(code) == 3:\r\n return code.upper()\r\n else:\r\n raise argparse.ArgumentTypeError(\"%s is not val...
[ "0.7340205", "0.6232221", "0.6139465", "0.6118442", "0.6065149", "0.60150987", "0.5987312", "0.58300376", "0.57871574", "0.57339126", "0.5719007", "0.5665261", "0.5665261", "0.5665261", "0.5651849", "0.56237924", "0.5594974", "0.5574781", "0.55745834", "0.556082", "0.55538803...
0.81940216
0
Return a country name input after validating it
def countryInput(self, prompt): while True: name = input(prompt) if name not in self.travel_db.countries: print("Invalid country name. Please make sure name is capitalized.") else: return name
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def country() -> str:", "def valid_country(value: Any) -> str:\n value = cv.string(value)\n all_supported_countries = holidays.list_supported_countries()\n\n try:\n raw_value = value.encode(\"utf-8\")\n except UnicodeError as err:\n raise vol.Invalid(\n \"The country name or ...
[ "0.6980752", "0.69086546", "0.6828054", "0.669586", "0.66514415", "0.66304183", "0.6440515", "0.64396936", "0.6435864", "0.6435098", "0.6365185", "0.63565147", "0.6318801", "0.6305565", "0.62800944", "0.6262626", "0.6246364", "0.6230827", "0.62267274", "0.62176657", "0.607218...
0.79892355
0
Return a currency code input after validaing it
def currencyInput(self, prompt): while True: code = input(prompt).upper() if code not in self.travel_db.currencies: print("Invalid currency code") else: return code
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_currency(currency_code):\n try:\n rate = rates.get_rates(currency_code)\n return 0\n except:\n flash(f'Error: {currency_code} is not a valid currency')\n return 1", "def get_currency(test_loop_count=None) -> str:\n loop_count = 0\n while True:\n try:\n ...
[ "0.6704559", "0.6646507", "0.6486832", "0.62412405", "0.6107163", "0.60303926", "0.600023", "0.59911394", "0.5982588", "0.59745014", "0.5958056", "0.5924218", "0.587548", "0.58722013", "0.5858742", "0.5832311", "0.5812267", "0.5781818", "0.5777066", "0.5729549", "0.5705858", ...
0.7700206
0
Return True if airport code valid, False otherwise.
def validateAirport(self, code): print(code) if code in self.travel_db.airports: return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _is_valid_code(self, code):\r\n return code in COUNTRY_CODES", "def is_valid(postal_code):\n return bool(re.match(UK_POST_CODE_REGEX, postal_code, re.VERBOSE)) if postal_code else False", "def check_code(item_code):\r\n # RA matches\r\n if re.match(r'^MCRNC[0-9]{4}\\.T$', item_code):\r\n ...
[ "0.70381415", "0.6726082", "0.64569366", "0.6375067", "0.630065", "0.6263566", "0.6250235", "0.62470305", "0.6238505", "0.62053096", "0.6156845", "0.61343706", "0.61318254", "0.6113142", "0.6089113", "0.6086316", "0.6080452", "0.6008818", "0.5969722", "0.59552896", "0.5907283...
0.8865747
0
Return True if country_name valid, False otherwise.
def validateCountry(self, country_name): if country_name in self.travel_db.countries: return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_valid_country():\n assert valid_country(\"Democratic Republic of Lungary\") is True\n assert valid_country(\"Kraznoviklandstan\") is True\n assert valid_country(\"kraznoviklandstan\") is True\n assert valid_country(\"KRAZNOVIKLANDSTAN\") is True\n\n assert valid_country(\"Democratic_Republi...
[ "0.7013575", "0.700049", "0.6939837", "0.68034947", "0.67918384", "0.6622717", "0.6601707", "0.6583337", "0.6476302", "0.64751047", "0.6429186", "0.64257467", "0.64110726", "0.6369207", "0.63588893", "0.62856215", "0.6275524", "0.62537944", "0.62458146", "0.6229923", "0.62293...
0.8314883
0
Return True if currency_code valid, False otherwise.
def validateCurrency(self, currency_code): if currency_code in self.travel_db.currencies: return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def validate_currency(currency_code):\n try:\n rate = rates.get_rates(currency_code)\n return 0\n except:\n flash(f'Error: {currency_code} is not a valid currency')\n return 1", "def _is_valid_code(self, code):\r\n return code in COUNTRY_CODES", "def is_valid(postal_cod...
[ "0.759342", "0.70800674", "0.6537341", "0.62727094", "0.62223756", "0.619591", "0.6130835", "0.60933155", "0.6079185", "0.6059149", "0.6046414", "0.60261106", "0.5977034", "0.59302557", "0.5910405", "0.5875142", "0.5865183", "0.5845647", "0.5834872", "0.57638985", "0.57544607...
0.85613906
0
Return a dictionary of Currency objects, with key = currency code. Created from info stored in filename
def buildCurrencyDict(filename): currencies = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: currencies[line[1]] = Currency(line[1], line[0], float(line[2])) return currencies
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def buildCountryDict(filename, currencies_dict):\n # This function requires the currency dictionary to be built already.\n countries = {}\n with open(os.path.join(\"input\", filename), \"rt\", encoding=\"utf8\") as f:\n reader = csv.reader(f)\n for line in reader:\n ...
[ "0.70550233", "0.6869403", "0.6178886", "0.61106163", "0.59804064", "0.59100264", "0.5908569", "0.59003896", "0.58851796", "0.58286935", "0.58016914", "0.57944894", "0.57516325", "0.5689539", "0.5687478", "0.56543136", "0.56246847", "0.56089044", "0.56031054", "0.5590987", "0...
0.84670454
0
Return a dictionary of Country objects, with key = country name. Created from info stored in filename
def buildCountryDict(filename, currencies_dict): # This function requires the currency dictionary to be built already. countries = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: try: countries[line[0]] = Country(line[0], line[14], currencies_dict) except KeyError: # If currency isn't found, country won't be added to the dictionary continue return countries
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def buildAirportDict(filename, countries_dict): \n # This function requires the country dictionary to be built already.\n airports = {}\n with open(os.path.join(\"input\", filename), \"rt\", encoding=\"utf8\") as f:\n reader = csv.reader(f)\n for line in reader:\n ...
[ "0.65897286", "0.64826685", "0.6389784", "0.6383171", "0.6335359", "0.62931234", "0.6252615", "0.62445325", "0.6109666", "0.6080601", "0.6028311", "0.60078806", "0.5918966", "0.588614", "0.5876146", "0.5860082", "0.5792945", "0.576631", "0.57317054", "0.5713805", "0.5710851",...
0.74422234
0
Return a dictionary of Airport objects, with key = airport code. Created from info stored in filename
def buildAirportDict(filename, countries_dict): # This function requires the country dictionary to be built already. airports = {} with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: try: airports[line[4]] = Airport(line[4], line[1], line[3], line[2], float(line[6]), float(line[7]), countries_dict) except KeyError: # If country isn't found, the airport won't be added to the dictionary continue return airports
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def triplify(self):\n airports = {}\n with open(self.source_file_path, 'r') as csvfile:\n reader = csv.reader(csvfile, delimiter=\",\")\n for i, row in enumerate(reader):\n if i != 0:\n # even if it says that data is encoded to latin-1, it actua...
[ "0.70951945", "0.7048426", "0.68105704", "0.67958844", "0.67303306", "0.660992", "0.6241538", "0.6214554", "0.60528135", "0.5989924", "0.59378284", "0.5857952", "0.58015823", "0.55762887", "0.55647373", "0.554717", "0.5545705", "0.5532614", "0.551982", "0.5506063", "0.5496964...
0.7226677
0
Return a list of routes from a file, in the format [name, [airport code list]]. Return None if file not found.
def getRouteInputFile(filename): if filename[-4:] != ".csv": # Make sure the filename is a .csv return None routes = [] try: with open(os.path.join("input", filename), "rt", encoding="utf8") as f: reader = csv.reader(f) for line in reader: try: routes.append([line[0], line[1:]]) except (UnicodeDecodeError, IndexError): # skip blank lines and lines with invalid characters continue except (FileNotFoundError, OSError): return None return routes
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_routes_file(route_filename):\n\n list_route_descriptions = []\n tree = ET.parse(route_filename)\n for route in tree.iter(\"route\"):\n route_town = route.attrib['map']\n route_id = route.attrib['id']\n waypoint_list = [] # the list of waypoints that can be found on this rou...
[ "0.6682189", "0.61099017", "0.60007584", "0.59836805", "0.59614146", "0.585794", "0.58239037", "0.57957166", "0.5757466", "0.5705301", "0.5684137", "0.5619704", "0.5542456", "0.55303", "0.5512766", "0.5511307", "0.5509003", "0.54854715", "0.5457731", "0.54531974", "0.54459774...
0.6995897
0
Create a csv input file, given a list of routes. Routes are lists of names and airport codes.
def writeRoutesCSV(filename, routes): if filename[-4:] != ".csv": # Make sure the filename is a .csv filename += ".csv" try: with open(os.path.join("input", filename), "w", newline='') as f: writer = csv.writer(f, delimiter=",") writer.writerows(routes) except (OSError, FileNotFoundError): return False else: return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def route_data(route):\n os.chdir(\"../Data/test\") #change to whatever directory your data files are stored in\n with open(\"../Sorted Data/\"+str(route)+\"_data.csv\",\"w\",newline=\"\") as result_file: #storing resulting data in csv file in different directory\n wr=csv.writer(result_file, dialect='...
[ "0.6899799", "0.66672605", "0.6458159", "0.63670135", "0.634914", "0.63457423", "0.63208055", "0.6306807", "0.6239996", "0.62074065", "0.6170774", "0.60570943", "0.6028385", "0.6027313", "0.60171574", "0.60073507", "0.59914494", "0.59842396", "0.5965804", "0.59501034", "0.591...
0.7744267
0
Write output .csv file for list of itineraries. Output file shows cheapest route and its cost.
def writeItineraryOutput(filename, itins): if filename[-4:] != ".csv": # Make sure the filename is a .csv filename += ".csv" try: with open(os.path.join("output", filename), "w", newline='') as f: writer = csv.writer(f, delimiter=",") firstline = ["Name", "Cost", "Home", "Dest 1", "Dest 2", "Dest 3", "Dest 4", "Dest 5", "Dest 6"] writer.writerow(firstline) for itinerary in itins: line = [] line.append(itinerary.name) line.append(itinerary.cheapest_cost) line = line + itinerary.cheapest_route.getCodeList() writer.writerow(line) except (FileNotFoundError, OSError): return False else: return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_csv(net, wires, net_id, chip_id, chip):\n with open('output/output.csv', 'w') as file:\n # Write first line\n output = csv.writer(file)\n output.writerow([\"net\", \"wires\"])\n\n # Index and fill the body\n for step in range(len(wires)):\n output.writerow(...
[ "0.654631", "0.64892834", "0.6398828", "0.6333328", "0.6306452", "0.62436354", "0.6238039", "0.6226846", "0.6123271", "0.6066527", "0.6055366", "0.6047722", "0.6046962", "0.6041532", "0.6025302", "0.60197496", "0.6000928", "0.5996336", "0.59933907", "0.5990987", "0.5989872", ...
0.7681153
0
Create an input file with randomly generated routes for num_people.
def generateRandomInput(filename, num_people, travel_db): import random routes = [] for i in range(num_people): route = travel_db.randomRoute() route.insert(0,"Person " + str(i)) # Add a name for each route. routes.append(route) if FileHandler.writeRoutesCSV(filename,routes): # If it's successful writing the file print("File {0} created successfully with {1} people.".format(filename, num_people)) else: print("File {0} could not be created.".format(filename))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _prepare_input_file(self, filename, numlines, maxvalue):\n with open(filename, 'a') as f:\n for _ in range(numlines):\n f.write(str(randrange(maxvalue)) + '\\n')\n self.filepath = f.name", "def routes_gen(num) -> Generator[Route, None, None]:\n with open(f'data/route-...
[ "0.587769", "0.5856231", "0.56174666", "0.55805063", "0.55153143", "0.5446747", "0.54272777", "0.54071355", "0.5406519", "0.5362641", "0.5354671", "0.53122556", "0.5305677", "0.5279175", "0.5232032", "0.5200919", "0.51978534", "0.518729", "0.51755005", "0.5140269", "0.5115986...
0.84894335
0
get access token for ohub API
def get_access_token(self): payload = { 'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret, 'resource': self.resource } res = requests.post(self.auth_url, data=payload) data = res.json() if res.status_code == 200: return data['access_token'], res return False, res
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_token(): \n \n # Token url\n token_endpoint = \"https://api.signicat.io/oauth/connect/token\"\n # Setting the grant type to client_credentials\n data = {'grant_type':'client_credentials', 'scope':'identify'}\n # Posting to token url with HTTP basic authentication\n token = requests.pos...
[ "0.752597", "0.736419", "0.72990793", "0.7212395", "0.7182696", "0.7124292", "0.70727074", "0.7070482", "0.70286155", "0.7016784", "0.7008737", "0.6973223", "0.69727576", "0.69727576", "0.69727325", "0.6971487", "0.6961795", "0.6953318", "0.69116116", "0.6904606", "0.6902688"...
0.6742485
40
Tests API call to onboard NS descriptor resources
def test_post_ns_descriptors(post_ns_descriptors_keys): sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL) sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) Helpers._delete_test_nsd(_token=_token["token"]["access_token"]) sonata_vnfpkgm.post_vnf_packages(token=_token["token"]["access_token"], package_path="tests/samples/vnfd_example.yml") response = json.loads(sonata_nsd.post_ns_descriptors( token=_token["token"]["access_token"], package_path="tests/samples/nsd_example.yml")) assert response['error'] == False assert response['data'] != ''
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_get_ns_descriptors_nsdinfoid():\r\n sonata_nsd = SONATAClient.Nsd(HOST_URL)\r\n sonata_auth = SONATAClient.Auth(HOST_URL)\r\n _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD))\r\n _token = json.loads(_token[\"data\"])\r\n _nsd_list = json.loads(sonata_nsd.get_ns_de...
[ "0.66410756", "0.63118935", "0.6108497", "0.5946216", "0.5842967", "0.58171374", "0.5727807", "0.5709085", "0.56833494", "0.56741107", "0.56662744", "0.56547874", "0.56290054", "0.5608064", "0.55975276", "0.55833757", "0.55814964", "0.5580672", "0.5555872", "0.5532858", "0.55...
0.52910966
63
Tests API call to fetch multiple NS descriptor resources
def test_get_ns_descriptors(get_ns_descriptors_keys): sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) response = json.loads(sonata_nsd.get_ns_descriptors( token=_token["token"]["access_token"], limit=1000)) response = json.loads(response["data"]) assert isinstance(response, list) if len(response) > 0: assert set(get_ns_descriptors_keys).issubset( response[0].keys()), "All keys should be in the response"
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_many_descriptors(self, uuids):", "def test_multiple_gets(uris):\n\n for uri in uris:\n print('='*10 + ' Try uri : {uri} '.format(uri=uri) + '='*10)\n resp = get_api_url(uri)\n print(resp)\n try:\n pprint(resp.json())\n except Exception as e:\n p...
[ "0.6480714", "0.64030355", "0.63878626", "0.633152", "0.61416095", "0.6027618", "0.59268606", "0.5893378", "0.5883436", "0.5867936", "0.5860991", "0.58218473", "0.58013874", "0.5790113", "0.5780573", "0.5772255", "0.57513046", "0.5746608", "0.5731543", "0.5729499", "0.5722015...
0.65850234
0
Tests API call to read information about an NS descriptor resources
def test_get_ns_descriptors_nsdinfoid(): sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) _nsd_list = json.loads(sonata_nsd.get_ns_descriptors( token=_token["token"]["access_token"])) _nsd_list = json.loads(_nsd_list["data"]) Helpers._upload_test_nsd(_token=_token["token"]["access_token"]) for _n in _nsd_list: if "sonata-demo" == _n['nsd']['name']: _nsd = _n['uuid'] response = json.loads(sonata_nsd.get_ns_descriptors_nsdinfoid( token=_token["token"]["access_token"], nsdinfoid=_nsd)) Helpers._delete_test_nsd(_token=_token["token"]["access_token"]) if response["error"]: return True else: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_get_ns_descriptors(get_ns_descriptors_keys):\r\n sonata_nsd = SONATAClient.Nsd(HOST_URL)\r\n sonata_auth = SONATAClient.Auth(HOST_URL)\r\n _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD))\r\n _token = json.loads(_token[\"data\"])\r\n\r\n response = json.loads(sona...
[ "0.64663666", "0.608117", "0.5999047", "0.5969652", "0.59466934", "0.59190524", "0.5892444", "0.5845748", "0.5732233", "0.5668746", "0.5648303", "0.5639067", "0.56217575", "0.56203", "0.56144845", "0.5610858", "0.5607481", "0.560151", "0.5600352", "0.55998194", "0.5585602", ...
0.70114577
0
Tests API call to delete NS descriptor resources
def test_delete_ns_descriptors_nsdinfoid(delete_ns_descriptors_nsdinfoid_keys): sonata_vnfpkgm = SONATAClient.VnfPkgm(HOST_URL) sonata_nsd = SONATAClient.Nsd(HOST_URL) sonata_auth = SONATAClient.Auth(HOST_URL) _token = json.loads(sonata_auth.auth(username=USERNAME, password=PASSWORD)) _token = json.loads(_token["data"]) _nsd_list = json.loads(sonata_nsd.get_ns_descriptors( token=_token["token"]["access_token"])) _nsd_list = json.loads(_nsd_list["data"]) _nsd = None for _n in _nsd_list: if "sonata-demo" == _n['nsd']['name']: _nsd = _n['uuid'] time.sleep(10) # Wait for NSD onboarding response = json.loads(sonata_nsd.delete_ns_descriptors_nsdinfoid( token=_token["token"]["access_token"], nsdinfoid=_nsd)) assert isinstance(response, dict) assert response["data"] == "{\"error\":\"The NSD ID None does not exist\"}" time.sleep(2) #Wait for NSD onboarding _vnfd_list = json.loads(sonata_vnfpkgm.get_vnf_packages( token=_token["token"]["access_token"])) _vnfd_list = json.loads(_vnfd_list["data"]) _vnfd = None for _v in _vnfd_list: if "vnfd_example" == _v['uuid']: _vnfd = _v['uuid'] response = None if _vnfd: response = json.loads(sonata_vnfpkgm.delete_vnf_packages_vnfpkgid( token=_token["token"]["access_token"], vnfPkgId=_vnfd)) assert isinstance(response, dict) assert response["data"] == ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_delete_on_background_response_descriptor_projects_release_release_resource_spaces(self):\n pass", "def test_delete_on_background_response_descriptor_projects_release_release_resource(self):\n pass", "def test_delete_on_background_response_descriptor_subscriptions_subscription_subscriptio...
[ "0.70575756", "0.68376297", "0.67838246", "0.66237175", "0.64669347", "0.64376366", "0.64376366", "0.6399817", "0.6381159", "0.63791645", "0.63716006", "0.6369237", "0.6348905", "0.6325135", "0.6323571", "0.62920225", "0.62577426", "0.62550163", "0.6228073", "0.62071025", "0....
0.70335805
1
palindrome should fail when first input is not string
def teststring(self): self.assertRaises(palindrome.NotStringError,palindrome.palin, 4)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_palindrome():", "def check_palindrome(inp_string):\n if len(inp_string) <= 2:\n return False\n elif inp_string == inp_string[::-1]:\n return True\n else:\n return False", "def is_palindrome(string):\n return", "def ispalindrome(string):\n if isinstance(string, (s...
[ "0.8580645", "0.7966129", "0.79021037", "0.7837178", "0.77251107", "0.7704955", "0.76943594", "0.7679945", "0.7677962", "0.76570374", "0.7632073", "0.7594772", "0.7590463", "0.7588587", "0.7567943", "0.7513122", "0.7498341", "0.7479257", "0.7478958", "0.74631226", "0.7449308"...
0.6526004
90
Reads DHalo data into memory
def read(self, simtype): if simtype == 'original': if self.filename.endswith(".pkl"): logging.debug("Loading pickle file %s", self.filename) data = pd.read_pickle(self.filename) elif self.filename.endswith(".hdf5"): logging.debug("Loading HDF5 file %s", self.filename) with h5py.File(self.filename, "r") as data_file: #print('treeIndex', data_file["treeIndex"].keys()) #print('haloTrees', data_file["haloTrees"].keys()) # Find dimensionality of keys columns_1dim = [] columns_2dim = [] for column in self.columns: if len(data_file["/haloTrees/%s" % column].shape) == 1: columns_1dim.append(column) else: columns_2dim.append(column) # 1D keys data = pd.DataFrame( { column: data_file["/haloTrees/%s" % column].value for column in columns_1dim }, columns=columns_1dim ).set_index("nodeIndex") del columns_1dim # 2D keys for column in columns_2dim: if column == 'position': pos = data_file["/haloTrees/%s" % column].value data['X'] = pd.Series(pos[:, 0], index=data.index) data['Y'] = pd.Series(pos[:, 1], index=data.index) data['Z'] = pd.Series(pos[:, 2], index=data.index) del columns_2dim data.rename(index=str, columns={"snapshotNumber": "snapnum"}) ## eliminate fake elements with isIntegrated=1 #data = data[data.isInterpolated != 1] else: raise TypeError("Unknown filetype %s" % self.filename) if simtype == 'EAGLE': if self.filename.endswith(".pkl"): logging.debug("Loading pickle file %s", self.filename) data = pd.read_pickle(self.filename) elif self.filename.endswith(".hdf5"): logging.debug("Loading HDF5 file %s", self.filename) data_file = h5py.File(self.filename, 'r') column_mt = [] column_sh = [] for column in self.columns: if column in data_file['MergerTree']: column_mt.append(column) else: column_sh.append(column) data = pd.DataFrame( { column: data_file["/MergerTree/%s" % column].value for column in column_mt }, columns=column_mt ).set_index("HaloID") #.set_index(data_file["/Merger/HaloID"].value) for column in column_sh: data[column] = pd.Series(data_file["/Subhalo/%s" % column].value, index=data.index) data = data.rename(index=str, columns={"SnapNum": "snapnum", #"HaloID": "nodeIndex", "DescendantID" : "descendantIndex"}) else: raise TypeError("Unknown filetype %s" % self.filename) return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _read_data(self):", "def read_drt(self):\n data = Array('B')\n data = self.read(0, 0, 8)\n num_of_devices = drt_controller.get_number_of_devices(data)\n len_to_read = num_of_devices * 8\n\n data = self.read(0, 0, len_to_read + 8)\n self.drt_manager.set_drt(data)", "def _read_data(self) -...
[ "0.67620295", "0.6609676", "0.6301889", "0.62566316", "0.6254608", "0.62242556", "0.61881506", "0.6081291", "0.6077486", "0.6040958", "0.6022732", "0.5944303", "0.5917045", "0.588852", "0.588852", "0.588852", "0.5851131", "0.58243155", "0.5814752", "0.5798164", "0.57805437", ...
0.0
-1
Returns halo (row of data) given a ``nodeIndex``
def get_halo(self, index): try: halo = self.data.loc[index] except KeyError: raise IndexError( "Halo id %d not found in %s" % (index, self.filename) ) return halo
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_node(self, index):\r\n\t\tself._validate_index(index)\r\n\t\treturn self._traverse(lambda i, list: i < index)[\"node\"]", "def halo_host(self, index):\n halo = self.get_halo(index)\n return (\n halo\n if halo.name == halo[\"hostIndex\"]\n else self.halo_hos...
[ "0.5902977", "0.5608498", "0.5608498", "0.5394057", "0.5361975", "0.53427607", "0.5313705", "0.52938735", "0.526928", "0.5263665", "0.5258102", "0.5251677", "0.5238716", "0.52234507", "0.52188444", "0.52096754", "0.51846796", "0.51694787", "0.51663357", "0.516497", "0.5148196...
0.6535571
1
Finds indices of all progenitors of a halo, recursively.
def halo_progenitor_ids(self, index): _progenitors = [] def rec(i): _progenitor_ids = self.data[self.data["descendantHost"] == i][ "hostIndex" ].unique() logging.debug("Progenitors recursion: %d > %d (%d progenitors)", index, i, len(_progenitor_ids)) if len(_progenitor_ids) == 0: return for _progenitor_id in _progenitor_ids: # if _progenitor_id not in _progenitors: # TODO: this only eliminates fly-byes _progenitors.append(_progenitor_id) rec(_progenitor_id) rec(index) logging.info( "%d progenitors found for halo %d", len(_progenitors), index ) return _progenitors
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def halo_progenitor_ids(self, index):\n _progenitors = []\n\n def rec(i):\n _progenitor_ids = self.data[self.data[\"descendantHost\"] == i][\n \"hostIndex\"\n ].unique()\n logging.debug(\n \"Progenitors recursion: %d > %d (%d progenitors)...
[ "0.6863077", "0.5833046", "0.5638713", "0.5561099", "0.5542297", "0.5519623", "0.54976434", "0.54312", "0.537776", "0.53390366", "0.53045774", "0.5278391", "0.5255487", "0.52501196", "0.5239766", "0.522312", "0.52182275", "0.5186579", "0.5170028", "0.51365596", "0.5129794", ...
0.6898143
0
Finds host of halo. Recursively continues until hits the main halo, in case of multiply embedded subhaloes.
def halo_host(self, index): halo = self.get_halo(index) return ( halo if halo.name == halo["hostIndex"] else self.halo_host(self.get_halo(halo["hostIndex"]).name) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def updateSubhalos(host,file, host2sub):\n if not (host.ID in host2sub):\n return\n g = open(file,'r')\n for posn in host2sub[host.ID]:\n g.seek(posn)\n line = g.readline()\n sub = MTH.MTHalo(line)\n if sub.pid != host.ID:\n print 'WARNING: ERROR: halo not sub...
[ "0.56107956", "0.54044807", "0.53122574", "0.52616286", "0.524105", "0.51986015", "0.5194676", "0.5027002", "0.49752408", "0.49468756", "0.49244332", "0.49071574", "0.48990795", "0.4883024", "0.48149812", "0.47726056", "0.47632203", "0.47600392", "0.47526672", "0.47278097", "...
0.63591355
1
Finds mass of central halo and all subhaloes.
def halo_mass(self, index): return self.data[self.data["hostIndex"] == index][ "particleNumber" ].sum()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_center_of_mass_allies(self,obs):", "def center_of_mass(self, entity, geometric=False):\n\n # Structure, Model, Chain, Residue\n if isinstance(entity, Entity.Entity):\n atom_list = entity.get_atoms()\n # List of Atoms\n elif hasattr(entity, \"__iter__\") and [x for x...
[ "0.62661475", "0.61996317", "0.618251", "0.6090707", "0.60871905", "0.5922938", "0.5916971", "0.5912088", "0.59059227", "0.5891885", "0.5858639", "0.5802172", "0.5787271", "0.578331", "0.57702184", "0.5754956", "0.5754098", "0.57494813", "0.5742618", "0.5713476", "0.5711955",...
0.6344772
1
Calculates mass assembly history for a given halo. Treebased approach has been abandoned for performace reasons.
def collapsed_mass_history(self, index, nfw_f): logging.debug("Looking for halo %d", index) halo = self.get_halo(index) if halo["hostIndex"] != halo.name: raise ValueError("Not a host halo!") m_0 = self.halo_mass(index) progenitors = pd.concat( [ self.data.loc[index], self.data.loc[self.halo_progenitor_ids(index)], ] ) logging.debug( "Built progenitor sub-table for halo %d of mass %d with %d members", index, m_0, progenitors.size, ) progenitors = progenitors[progenitors["particleNumber"] > nfw_f * m_0] cmh = progenitors.groupby("snapshotNumber", as_index=False)[ "particleNumber" ].sum() cmh["nodeIndex"] = index logging.info( "Aggregated masses of %d valid progenitors of halo %d", progenitors.size, index, ) return cmh
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def collapsed_mass_history(self, index, nfw_f):\n\n logging.debug(\"Looking for halo %d\", index)\n halo = self.get_halo(index)\n if halo[\"hostIndex\"] != halo.name:\n raise ValueError(\"Not a host halo!\")\n m_0 = self.halo_mass(index)\n\n progenitors = pd.concat(\n ...
[ "0.5746956", "0.53531224", "0.51111126", "0.5078", "0.5021775", "0.49615657", "0.4913952", "0.48098966", "0.4727419", "0.4717308", "0.46857807", "0.4666251", "0.46613628", "0.46605286", "0.46548498", "0.46313113", "0.4621329", "0.45925197", "0.45755017", "0.4556348", "0.45549...
0.565708
1
Find the all topnodes mtree(z1) (across different snapshots) of mergertrees with basenode in SH(z2)
def tot_num_of_progenitors_at_z(self, SH, mtree, z1, z2): for ss in range(z1, z2+1): print('redshift:', ss) # nodes at redshift ss ss_indx = np.where(mtree.data.snapshotNumber.values == ss) nodeID = mtree.data.index.values[ss_indx] nodeID_desc = mtree.data.descendantIndex.values[ss_indx] # find number of progenitors for nodes at redshift ss if ss != z1: progcounts = np.zeros(len(nodeID), dtype=int) for ii in range(len(nodeID_past_desc)): if nodeID_past_desc[ii] in nodeID: indx = np.where(nodeID == nodeID_past_desc[ii]) progcounts[indx] = count[ii] nodeID_desc_unique, count = np.unique(nodeID_desc, return_counts=True) nodeID_desc_unique=nodeID_desc_unique[1:]; count=count[1:] # add progenitors of progenitors if ss != z1: for ii in range(len(nodeID)): if progcounts[ii] > 1: indx = np.where(nodeID_desc_unique == nodeID_desc[ii]) count[indx] += progcounts[ii] - 1 nodeID_past = nodeID nodeID_past_desc = nodeID_desc_unique return nodeID, progcounts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_progenitors_until_z_EAGLE(self, mtree, nodeID, z1, z2):\n snapcount = 0\n print(':Read MergerTree from %d until %d' % (z2, z1))\n for ss in range(z2, z1, -1):\n if ss == z2:\n df_target = pd.DataFrame({'nodeID':nodeID})\n _indx = np.where(mtree...
[ "0.6213814", "0.59098613", "0.57479274", "0.55864424", "0.55541563", "0.55429643", "0.55378467", "0.5518064", "0.5507714", "0.54895484", "0.54585093", "0.5443105", "0.5417853", "0.53423256", "0.53349715", "0.53140324", "0.53065985", "0.530484", "0.5277614", "0.52477187", "0.5...
0.51368386
32
Number of progenitors at one given snapshot z1
def find_progenitors_at_z(self, SH, mtree, z1, z2): for ss in range(z1, z2): # nodes at redshift ss ss_indx = np.where(mtree.data.snapshotNumber.values == ss) nodeID = mtree.data.index.values[ss_indx] nodeID_desc = mtree.data.descendantIndex.values[ss_indx] # find number of progenitors for nodes at redshift ss if ss != z1: _progcounts = np.zeros(len(nodeID)) for ii in range(len(nodeID_past_desc)): if nodeID_past_desc[ii] in nodeID: indx = np.where(nodeID == nodeID_past_desc[ii]) _progcounts[indx] = count[ii] nodeID_desc_unique, count = np.unique(nodeID_desc, return_counts=True) nodeID_desc_unique=nodeID_desc_unique[1:]; count=count[1:] nodeID_past = nodeID nodeID_past_desc = nodeID_desc_unique if ss != z1: _progcounts_past = _progcounts print('_progcounts', _progcounts)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tot_num_of_progenitors_at_z(self, SH, mtree, z1, z2):\n \n for ss in range(z1, z2+1):\n print('redshift:', ss)\n # nodes at redshift ss\n ss_indx = np.where(mtree.data.snapshotNumber.values == ss)\n nodeID = mtree.data.index.values[ss_indx]\n ...
[ "0.7110273", "0.6287449", "0.5909766", "0.57706916", "0.57402396", "0.5601302", "0.55882317", "0.5510065", "0.5481831", "0.54731274", "0.54057765", "0.5389035", "0.53697664", "0.53530174", "0.5347362", "0.53414553", "0.5321019", "0.53112924", "0.53112924", "0.53112924", "0.53...
0.6796147
1
Number of progenitors att all redshift between z1 and z2.
def find_progenitors_until_z(self, mtree, nodeID, z1, z2): snapcount = 0 print('from %d until %d' % (z2, z1)) for ss in range(z2, z1, -1): if ss == z2: df_target = pd.DataFrame({'nodeID':nodeID}) _indx = np.where(mtree.data.snapshotNumber.values == ss-1) nodeID_prog = mtree.data.index.values[_indx] nodeID_prog_desc = mtree.data.descendantIndex.values[_indx] _indx = np.where((nodeID_prog_desc < 1e15) & (nodeID_prog_desc > 1e11)) nodeID_prog = nodeID_prog[_indx] nodeID_prog_desc = nodeID_prog_desc[_indx] df_prog = pd.DataFrame({'nodeID' : nodeID_prog, 'nodeID_target' : nodeID_prog_desc}) # Initiliaze Output Array progcounts = np.zeros((df_target['nodeID'].size, z2-z1)) # nodeID_prog_desc_unic is sorted nodeID_prog_desc_unic, count = np.unique(nodeID_prog_desc, return_counts=True) # remove -1's nodeID_prog_desc_unic=nodeID_prog_desc_unic[1:]; count=count[1:] # Nr. of progenitors for sub-&halos at snapshot z2 s = pd.Index(df_target['nodeID'].tolist()) _indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) now_sort_indx = np.argsort(df_target['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(nodeID_prog_desc_unic) progcounts[_indx_now[now_sort_indx], snapcount] = count[pro_sort_indx] else: df_now = df_prog _indx = np.where(mtree.data.snapshotNumber.values == ss-1) nodeID_prog = mtree.data.index.values[_indx] nodeID_prog_desc = mtree.data.descendantIndex.values[_indx] #_indx = np.where((nodeID_prog_desc < 1e15) & # (nodeID_prog_desc > 1e10)) #nodeID_prog = nodeID_prog[_indx] #nodeID_prog_desc = nodeID_prog_desc[_indx] df_prog = pd.DataFrame({'nodeID' : nodeID_prog}) progcounts_local = np.zeros(df_now['nodeID'].size) nodeID_prog_desc_unic, count = np.unique(nodeID_prog_desc, return_counts=True) # remove -1's nodeID_prog_desc_unic=nodeID_prog_desc_unic[1:]; count=count[1:] # progenitors for snapshot ss s = pd.Index(df_now['nodeID'].tolist()) _indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) now_sort_indx = np.argsort(df_now['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(nodeID_prog_desc_unic) progcounts_local[_indx_now[now_sort_indx]] = count[pro_sort_indx] df_now['progcount'] = pd.Series(progcounts_local, index=df_now.index, dtype=int) # Nr. of progenitors for sub-&halos at snapshot z2 df_inter = df_now.groupby(['nodeID_target'], as_index=False)['progcount'].sum() # only real progeniteurs df_inter = df_inter[(df_inter['nodeID_target'] > 1e10) & (df_inter['nodeID_target'] < 1e15)] df_inter = df_inter.drop_duplicates(subset=['nodeID_target'], keep='first') s = pd.Index(df_target['nodeID'].tolist()) _indx_now = s.get_indexer(df_inter['nodeID_target'].tolist()) now_sort_indx = np.argsort(df_target['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(df_inter['nodeID_target'].values) progcounts[_indx_now[now_sort_indx], snapcount] = df_inter['progcount'].values[pro_sort_indx] # sort nodeID_prog to nodeID #s = pd.Index(df_now['nodeID'].tolist()) #_indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) #df_now['nodeID_target'].values[_indx_now] obs_ref_local = np.zeros(df_prog['nodeID'].size) for ii in range(len(nodeID_prog_desc_unic)): tarID = df_now.loc[ df_now['nodeID'] == nodeID_prog_desc_unic[ii], 'nodeID_target'].values.astype(int) if tarID: _indx = np.where( nodeID_prog_desc == nodeID_prog_desc_unic[ii]) obs_ref_local[_indx] = tarID df_prog['nodeID_target'] = pd.Series(obs_ref_local, index=df_prog.index) snapcount += 1 del nodeID_prog_desc del df_now, df_inter, df_prog return np.asarray(df_target['nodeID'].tolist()), progcounts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tot_num_of_progenitors_at_z(self, SH, mtree, z1, z2):\n \n for ss in range(z1, z2+1):\n print('redshift:', ss)\n # nodes at redshift ss\n ss_indx = np.where(mtree.data.snapshotNumber.values == ss)\n nodeID = mtree.data.index.values[ss_indx]\n ...
[ "0.77634203", "0.72745174", "0.564701", "0.5616065", "0.552504", "0.549008", "0.5469204", "0.53005636", "0.5266585", "0.52409446", "0.5221631", "0.5201175", "0.5187531", "0.5157279", "0.5154978", "0.51176065", "0.510265", "0.5062432", "0.5053735", "0.5025109", "0.50141466", ...
0.5992864
2
Number of progenitors att all redshift between z1 and z2.
def find_progenitors_until_z_EAGLE(self, mtree, nodeID, z1, z2): snapcount = 0 print(':Read MergerTree from %d until %d' % (z2, z1)) for ss in range(z2, z1, -1): if ss == z2: df_target = pd.DataFrame({'nodeID':nodeID}) _indx = np.where(mtree.data.snapnum.values == ss-1) nodeID_prog = mtree.data.index.values[_indx] nodeID_prog_desc = mtree.data.descendantIndex.values[_indx] _indx = np.where((nodeID_prog_desc < 1e15) & (nodeID_prog_desc > 1e11)) nodeID_prog = nodeID_prog[_indx] nodeID_prog_desc = nodeID_prog_desc[_indx] df_prog = pd.DataFrame({'nodeID' : nodeID_prog, 'nodeID_target' : nodeID_prog_desc}) # Initiliaze Output Array progcounts = np.zeros((df_target['nodeID'].size, z2-z1)) # nodeID_prog_desc_unic is sorted nodeID_prog_desc_unic, count = np.unique(nodeID_prog_desc, return_counts=True) # remove -1's nodeID_prog_desc_unic=nodeID_prog_desc_unic[1:]; count=count[1:] # Nr. of progenitors for sub-&halos at snapshot z2 s = pd.Index(df_target['nodeID'].tolist()) _indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) now_sort_indx = np.argsort(df_target['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(nodeID_prog_desc_unic) progcounts[_indx_now[now_sort_indx], snapcount] = count[pro_sort_indx] else: df_now = df_prog _indx = np.where(mtree.data.snapnum.values == ss-1) nodeID_prog = mtree.data.index.values[_indx] nodeID_prog_desc = mtree.data.descendantIndex.values[_indx] #_indx = np.where((nodeID_prog_desc < 1e15) & # (nodeID_prog_desc > 1e10)) #nodeID_prog = nodeID_prog[_indx] #nodeID_prog_desc = nodeID_prog_desc[_indx] df_prog = pd.DataFrame({'nodeID' : nodeID_prog}) progcounts_local = np.zeros(df_now['nodeID'].size) nodeID_prog_desc_unic, count = np.unique(nodeID_prog_desc, return_counts=True) # remove -1's nodeID_prog_desc_unic=nodeID_prog_desc_unic[1:]; count=count[1:] # progenitors for snapshot ss s = pd.Index(df_now['nodeID'].tolist()) _indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) now_sort_indx = np.argsort(df_now['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(nodeID_prog_desc_unic) progcounts_local[_indx_now[now_sort_indx]] = count[pro_sort_indx] df_now['progcount'] = pd.Series(progcounts_local, index=df_now.index, dtype=int) # Nr. of progenitors for sub-&halos at snapshot z2 df_inter = df_now.groupby(['nodeID_target'], as_index=False)['progcount'].sum() # only real progeniteurs df_inter = df_inter[(df_inter['nodeID_target'] > 1e10) & (df_inter['nodeID_target'] < 1e15)] df_inter = df_inter.drop_duplicates(subset=['nodeID_target'], keep='first') s = pd.Index(df_target['nodeID'].tolist()) _indx_now = s.get_indexer(df_inter['nodeID_target'].tolist()) now_sort_indx = np.argsort(df_target['nodeID'].values[_indx_now]) pro_sort_indx = np.argsort(df_inter['nodeID_target'].values) progcounts[_indx_now[now_sort_indx], snapcount] = df_inter['progcount'].values[pro_sort_indx] # sort nodeID_prog to nodeID #s = pd.Index(df_now['nodeID'].tolist()) #_indx_now = s.get_indexer(list(nodeID_prog_desc_unic)) #df_now['nodeID_target'].values[_indx_now] obs_ref_local = np.zeros(df_prog['nodeID'].size) for ii in range(len(nodeID_prog_desc_unic)): tarID = df_now.loc[ df_now['nodeID'] == nodeID_prog_desc_unic[ii], 'nodeID_target'].values.astype(int) if tarID: _indx = np.where( nodeID_prog_desc == nodeID_prog_desc_unic[ii]) obs_ref_local[_indx] = tarID df_prog['nodeID_target'] = pd.Series(obs_ref_local, index=df_prog.index) snapcount += 1 del nodeID_prog_desc del df_now, df_inter, df_prog return np.asarray(df_target['nodeID'].tolist()), progcounts
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tot_num_of_progenitors_at_z(self, SH, mtree, z1, z2):\n \n for ss in range(z1, z2+1):\n print('redshift:', ss)\n # nodes at redshift ss\n ss_indx = np.where(mtree.data.snapshotNumber.values == ss)\n nodeID = mtree.data.index.values[ss_indx]\n ...
[ "0.7762394", "0.72740203", "0.59918725", "0.564635", "0.56158906", "0.5524609", "0.5490007", "0.5470048", "0.53012586", "0.52668864", "0.5241456", "0.5201391", "0.5188126", "0.51561224", "0.51548773", "0.5116847", "0.510104", "0.5062283", "0.5053708", "0.50249565", "0.5013674...
0.522115
11
Schedule WB category export on Scrapinghub.
def category_export(url: str, chat_id: int, spider='wb', priority=2) -> str: logger.info(f'Export {url} for chat #{chat_id}') client, project = init_scrapinghub() scheduled_jobs = scheduled_jobs_count(project, spider) max_scheduled_jobs = env('SCHEDULED_JOBS_THRESHOLD', cast=int, default=1) if priority < 3 and scheduled_jobs > max_scheduled_jobs: raise Exception('Spider wb has more than SCHEDULED_JOBS_THRESHOLD queued jobs') job = project.jobs.run(spider, priority=priority, job_args={ 'category_url': url, 'callback_url': env('WILDSEARCH_JOB_FINISHED_CALLBACK') + f'/{spider}_category_export', 'callback_params': f'chat_id={chat_id}', }) logger.info(f'Export for category {url} will have job key {job.key}') return 'https://app.scrapinghub.com/p/' + job.key
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def daily_task():\n global CATEGORIES_PAGES\n global BROWSER\n global DATE\n global OBSERVATION\n log.info('Scraper started')\n # Refresh date\n DATE = str(datetime.date.today())\n OBSERVATION = 0\n # Initiate headless web browser\n log.info('Initializing browser')\n BROWSER = webd...
[ "0.62322336", "0.5496554", "0.5323388", "0.5212413", "0.51680547", "0.5047314", "0.50356627", "0.5001191", "0.4996804", "0.4940439", "0.49359438", "0.48962823", "0.48792583", "0.48306614", "0.47664198", "0.47485566", "0.4733813", "0.47102794", "0.46897477", "0.4680858", "0.46...
0.5811483
1
Train a simple conv net img_h = sentence length (padded where necessary) img_w = word vector length (300 for word2vec) filter_hs = filter window sizes hidden_units = [x,y] x is the number of feature maps (per filter window), and y is the penultimate layer sqr_norm_lim = s^2 in the paper lr_decay = adadelta decay parameter
def train_conv_net(datasets,datasets_weights, U, U_Topical, img_w=300, filter_hs=[3,4,5], hidden_units=[100,2], dropout_rate=[0.5], shuffle_batch=True, n_epochs=25, batch_size=50, lr_decay = 0.95, conv_non_linear="relu", use_valid_set=True, show_states=False, activations=[Iden], sqr_norm_lim=9, non_static=True): rng = np.random.RandomState(3435) img_h = len(datasets[0][0])-1 U_Topical.dtype = "float32" (num_topics,topic_dim) = U_Topical.shape word_w = img_w img_w = int(img_w + num_topics*topic_dim) filter_w = img_w feature_maps = hidden_units[0] filter_shapes = [] pool_sizes = [] for filter_h in filter_hs: filter_shapes.append((feature_maps, 1, filter_h, filter_w)) # 100 1 3 300 pool_sizes.append((img_h-filter_h+1, img_w-filter_w+1)) # size of words samples one parameters = [("image shape",img_h,img_w),("filter shape",filter_shapes), ("hidden_units",hidden_units), ("dropout", dropout_rate), ("batch_size",batch_size),("non_static", non_static), ("learn_decay",lr_decay), ("conv_non_linear", conv_non_linear), ("non_static", non_static) ,("sqr_norm_lim",sqr_norm_lim),("shuffle_batch",shuffle_batch)] #print parameters #define model architecture index = T.lscalar() x = T.matrix('x') y = T.ivector('y') x_topic = T.tensor3('x_topic') Words = theano.shared(value = U, name = "Words") Topics = theano.shared(value=U_Topical,name="Topics") zero_vec_tensor = T.vector() zero_vec = np.zeros(word_w, dtype='float32') set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0,:], zero_vec_tensor))]) layer0_input_words = Words[T.cast(x.flatten(),dtype="int32")].reshape((x.shape[0],1,x.shape[1],Words.shape[1])) layer0_inputs_topics = [] for i in range(num_topics): sin_topic = x_topic[:,:,i] Topic = Topics[i].reshape((1,Topics[i].shape[0])) weights = sin_topic.flatten() weights = weights.reshape((weights.shape[0],1)) layer0_inputs_topics.append(T.dot(weights, Topic)) layer0_input_topics = T.concatenate(layer0_inputs_topics,1) layer0_input_topics = layer0_input_topics.reshape((x_topic.shape[0],1,x_topic.shape[1],num_topics*topic_dim)) layer0_input = T.concatenate([layer0_input_words,layer0_input_topics],3) conv_layers = [] layer1_inputs = [] for i in xrange(len(filter_hs)): filter_shape = filter_shapes[i] pool_size = pool_sizes[i] conv_layer = LeNetConvPoolLayer(rng, input=layer0_input,image_shape=(batch_size, 1, img_h, img_w), filter_shape=filter_shape, poolsize=pool_size, non_linear=conv_non_linear) layer1_input = conv_layer.output.flatten(2) conv_layers.append(conv_layer) layer1_inputs.append(layer1_input) layer1_input = T.concatenate(layer1_inputs,1) hidden_units[0] = feature_maps*len(filter_hs) classifier = MLPDropout(rng, input=layer1_input, layer_sizes=hidden_units, activations=activations, dropout_rates=dropout_rate) #define parameters of the model and update functions using adadelta params = classifier.params for conv_layer in conv_layers: params += conv_layer.params if non_static: #if word vectors are allowed to change, add them as model parameters params += [Words] #params are model parameters params += [Topics] #Topics embedding are adjusted cost = classifier.negative_log_likelihood(y) dropout_cost = classifier.dropout_negative_log_likelihood(y) grad_updates = sgd_updates_adadelta(params, dropout_cost, lr_decay, 1e-6, sqr_norm_lim) #shuffle dataset and assign to mini batches. if dataset size is not a multiple of mini batches, replicate #extra data (at random) np.random.seed(3435) if datasets[0].shape[0] % batch_size > 0: extra_data_num = batch_size - datasets[0].shape[0] % batch_size random_index = np.random.permutation(np.arange(datasets[0].shape[0])) random_index.astype('int32') train_set = datasets[0][random_index,:] train_set_weights = datasets_weights[0][random_index,:,:] extra_data = train_set[:extra_data_num] extra_data_weights = train_set_weights[:extra_data_num] new_data=np.append(datasets[0],extra_data,axis=0) new_data_weights = np.append(datasets_weights[0],extra_data_weights,axis = 0) else: new_data = datasets[0] new_data_weights = datasets_weights[0] random_index = np.random.permutation(np.arange(new_data.shape[0])) random_index.astype('int32') new_data = new_data[random_index] new_data_weights = new_data_weights[random_index] n_batches = new_data.shape[0]/batch_size n_train_batches = int(np.round(n_batches*0.9)) test_set_x = np.asarray(datasets[1][:,:img_h] ,"float32") test_set_x_topic = np.asarray(datasets_weights[1][:,:img_h,:] ,"float32") test_set_y = np.asarray(datasets[1][:,-1],"int32") if use_valid_set: train_set = new_data[:n_train_batches*batch_size,:] train_set_weights = new_data_weights[:n_train_batches*batch_size,:,:] val_set = new_data[n_train_batches*batch_size:,:] val_set_weights = new_data_weights[n_train_batches*batch_size:,:,:] train_set_x, train_set_x_topic, train_set_y = shared_dataset((train_set[:,:img_h],train_set_weights,train_set[:,-1])) val_set_x, val_set_x_topic, val_set_y = shared_dataset((val_set[:,:img_h],val_set_weights,val_set[:,-1])) n_val_batches = n_batches - n_train_batches val_model = theano.function([index], classifier.errors(y), givens={ x: val_set_x[index * batch_size: (index + 1) * batch_size], x_topic: val_set_x_topic[index * batch_size: (index + 1) * batch_size], y: val_set_y[index * batch_size: (index + 1) * batch_size]}) else: train_set = new_data[:,:] train_set_x, train_set_x_topic, train_set_y = shared_dataset((train_set[:,:img_h],train_set_weights,train_set[:,-1])) #make theano functions to get train/val/test errors test_model = theano.function([index], classifier.errors(y), givens={ x: train_set_x[index * batch_size: (index + 1) * batch_size], x_topic: train_set_x_topic[index * batch_size: (index + 1) * batch_size], y: train_set_y[index * batch_size: (index + 1) * batch_size]}) train_model = theano.function([index], cost, updates=grad_updates, givens={ x: train_set_x[index*batch_size:(index+1)*batch_size], x_topic: train_set_x_topic[index * batch_size: (index + 1) * batch_size], y: train_set_y[index*batch_size:(index+1)*batch_size]}) test_pred_layers = [] test_size = test_set_x.shape[0] test_layer0_input_words = Words[T.cast(x.flatten(),dtype="int32")].reshape((test_size,1,img_h,Words.shape[1])) test_layer0_inputs_topics = [] for i in range(num_topics): sin_topic = x_topic[:,:,i] Topic = Topics[i].reshape((1,Topics[i].shape[0])) weights = sin_topic.flatten() weights = weights.reshape((weights.shape[0],1)) test_layer0_inputs_topics.append(T.dot(weights, Topic)) test_layer0_input_topics = T.concatenate(test_layer0_inputs_topics,1) test_layer0_input_topics = test_layer0_input_topics.reshape((test_size,1,img_h,num_topics*topic_dim)) test_layer0_input = T.concatenate([test_layer0_input_words,test_layer0_input_topics],3) for conv_layer in conv_layers: test_layer0_output = conv_layer.predict(test_layer0_input, test_size) test_pred_layers.append(test_layer0_output.flatten(2)) test_layer1_input = T.concatenate(test_pred_layers, 1) test_y_pred = classifier.predict(test_layer1_input) test_error = T.mean(T.neq(test_y_pred, y)) test_model_all = theano.function([x,x_topic,y], test_error) #start training over mini-batches print '... training' epoch = 0 best_val_perf = 0 val_perf = 0 test_perf = 0 cost_epoch = 0 while (epoch < n_epochs): epoch = epoch + 1 if shuffle_batch: for minibatch_index in np.random.permutation(range(n_train_batches)): cost_epoch = train_model(minibatch_index) set_zero(zero_vec) else: for minibatch_index in xrange(n_train_batches): cost_epoch = train_model(minibatch_index) set_zero(zero_vec) train_losses = [test_model(i) for i in xrange(n_train_batches)] train_perf = 1 - np.mean(train_losses) if use_valid_set: val_losses = [val_model(i) for i in xrange(n_val_batches)] val_perf = 1- np.mean(val_losses) if val_perf >= best_val_perf: params_conv = [] params_output = {} test_loss = test_model_all(test_set_x,test_set_x_topic, test_set_y) test_perf = 1- test_loss best_val_perf = val_perf for conv_layer in conv_layers: params_conv.append(conv_layer.get_params()) params_output = classifier.get_params() word_vec = Words.get_value() Topic_vec = Topics.get_value() else : val_perf = 0 if show_states: print('epoch %i, train perf %f %%, val perf %f' % (epoch, train_perf * 100., val_perf*100.)) if not use_valid_set: params_conv = [] params_output = {} test_loss = test_model_all(test_set_x,test_set_x_topic, test_set_y) test_perf = 1- test_loss for conv_layer in conv_layers: params_conv.append(conv_layer.get_params()) params_output = classifier.get_params() word_vec = Words.get_value() Topic_vec = Topics.get_value() return test_perf, [params_conv, params_output, word_vec,Topic_vec]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_cnn_for_text(input_data, conv_window, filter_num, pooling_window, activation_fn=tf.nn.relu,\n padding_vec=None, use_batch_norm=False, bias_initializer=tf.zeros_initializer,\n keep_prob=1, is_training=False):\n # Do padding\n input_shape = tf.shape(input_data)\n...
[ "0.6291026", "0.61072165", "0.6082616", "0.59387344", "0.59314805", "0.5919466", "0.5789336", "0.5736913", "0.5708138", "0.5659221", "0.5653504", "0.5638298", "0.5631338", "0.5591712", "0.55789256", "0.55471337", "0.5543536", "0.5524808", "0.550148", "0.54923403", "0.5481331"...
0.6283863
1
Function that loads the dataset into shared variables The reason we store our dataset in shared variables is to allow Theano to copy it into the GPU memory (when code is run on GPU). Since copying data into the GPU is slow, copying a minibatch everytime is needed (the default behaviour if the data is not in a shared variable) would lead to a large decrease in performance.
def shared_dataset(data_xy, borrow=True): data_x, data_x_topic, data_y = data_xy shared_x = theano.shared(np.asarray(data_x, dtype=theano.config.floatX), borrow=borrow) shared_x_topic = theano.shared(np.asarray(data_x_topic, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(np.asarray(data_y, dtype=theano.config.floatX), borrow=borrow) return shared_x, shared_x_topic, T.cast(shared_y, 'int32')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shared_dataset(data_x, data_y, borrow=True):\n shared_x = theano.shared(np.asarray(data_x,\n dtype=theano.config.floatX),\n borrow=borrow)\n shared_y = theano.shared(np.asarray(data_y, dtype=np.int32),\n ...
[ "0.66170514", "0.65900344", "0.6475917", "0.61465776", "0.61301583", "0.61217743", "0.60805804", "0.59559256", "0.59458435", "0.59417135", "0.5921487", "0.58830863", "0.5878444", "0.58709127", "0.58622324", "0.58391243", "0.58236265", "0.58061445", "0.5792834", "0.5765671", "...
0.60709625
7
adadelta update rule, mostly from
def sgd_updates_adadelta(params,cost,rho=0.95,epsilon=1e-6,norm_lim=9,word_vec_name='Words'): updates = OrderedDict({}) exp_sqr_grads = OrderedDict({}) exp_sqr_ups = OrderedDict({}) gparams = [] for param in params: empty = np.zeros_like(param.get_value()) exp_sqr_grads[param] = theano.shared(value=as_floatX(empty),name="exp_grad_%s" % param.name) gp = T.grad(cost, param) exp_sqr_ups[param] = theano.shared(value=as_floatX(empty), name="exp_grad_%s" % param.name) gparams.append(gp) for param, gp in zip(params, gparams): exp_sg = exp_sqr_grads[param] exp_su = exp_sqr_ups[param] up_exp_sg = rho * exp_sg + (1 - rho) * T.sqr(gp) updates[exp_sg] = up_exp_sg step = -(T.sqrt(exp_su + epsilon) / T.sqrt(up_exp_sg + epsilon)) * gp updates[exp_su] = rho * exp_su + (1 - rho) * T.sqr(step) stepped_param = param + step if (param.get_value(borrow=True).ndim == 2) and (param.name != 'Words') and (param.name != 'Topics'): col_norms = T.sqrt(T.sum(T.sqr(stepped_param), axis=0)) desired_norms = T.clip(col_norms, 0, T.sqrt(norm_lim)) scale = desired_norms / (1e-7 + col_norms) updates[param] = stepped_param * scale else: updates[param] = stepped_param return updates
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_update_rule(self):\n pass", "def update_rules():\n update_all_rules()\n return \"OK\"", "def acUpdate(deltaT):#-------------------------------- AC UPDATE\n pass # -> Delete this line if you do something here !", "def _UpdateAclRule(self, entry):\n\n print 'Update Acl rule: %s' % (...
[ "0.72158897", "0.61915874", "0.59953177", "0.56383234", "0.5619746", "0.5614491", "0.5574052", "0.55433077", "0.55414903", "0.54987466", "0.5419936", "0.54156685", "0.5361411", "0.5350453", "0.53490156", "0.5341854", "0.53329635", "0.52209646", "0.5166257", "0.5149093", "0.51...
0.5070786
33
remake update dictionary for safe updating
def safe_update(dict_to, dict_from): for key, val in dict(dict_from).iteritems(): if key in dict_to: raise KeyError(key) dict_to[key] = val return dict_to
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_dict(new,old):", "def _update_loose (self, dict):\n self.__dict__.update(dict)", "def update(self, *args, **kwargs):\n super(ReadOnlyDict, self).update(*args, **kwargs) # pragma: no cover", "def _update(value: Dict[str, Any], update: Dict[str, Any]):\n for key, val in update.item...
[ "0.8283676", "0.7269931", "0.6905765", "0.6654361", "0.66300076", "0.6628225", "0.6574362", "0.65601563", "0.6495813", "0.6480724", "0.64378697", "0.64134395", "0.6387203", "0.6384412", "0.6380623", "0.63678986", "0.62931854", "0.6287735", "0.62773114", "0.6266723", "0.623645...
0.5890382
55
Transforms sentence into a list of indices. Pad with zeroes.
def get_idx_from_sent(sent, topic_weights, word_idx_map, max_l=51, k=300, filter_h=5): x = [] t = [] num_topics = len(topic_weights[0]) pad = filter_h - 1 zero_weights = [0.0]*num_topics for i in xrange(pad): x.append(0) t.append(zero_weights) words = sent.split() for index, word in enumerate(words): if word in word_idx_map: x.append(word_idx_map[word]) t.append(topic_weights[index]) while len(x) < max_l+2*pad: x.append(0) t.append(zero_weights) return x,t
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sentence_to_indices(self, sentence):\n token_list = self.tokenize(sentence)\n indices = self.tokenizer.convert_tokens_to_ids(token_list)\n\n return indices", "def sentence_to_indices(sentence, word_dict):\n return [word_dict.to_index(word) for word in word_tokenize(sentence)]", "def...
[ "0.6450914", "0.64385843", "0.6401967", "0.6338094", "0.6316792", "0.61736226", "0.61721224", "0.61721224", "0.61499345", "0.6140153", "0.61389184", "0.61104566", "0.6093466", "0.606643", "0.60410887", "0.5994239", "0.5958273", "0.5941653", "0.5936649", "0.5908101", "0.590779...
0.5256634
73
Transforms sentences into a 2d matrix.
def make_idx_data_cv(revs, lda_weights, word_idx_map, cv, max_l=56, k=300, filter_h=5): train, test = [], [] train_weight, test_weight = [], [] for index, rev in enumerate(revs): sent,sent_weight = get_idx_from_sent(rev["text"], lda_weights[index], word_idx_map, max_l, k, filter_h) sent.append(rev["y"]) if rev["split"] == cv: test.append(sent) test_weight.append(sent_weight) else: train.append(sent) train_weight.append(sent_weight) train = np.array(train, dtype="int") train_weight = np.array(train_weight, dtype="float32") test_weight = np.array(test_weight, dtype="float32") test = np.array(test, dtype="int") return [train, test], [train_weight,test_weight]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def lines_to_matrix(lines):\n\n for index, line in enumerate(lines):\n lines[index] = [char for char in line]\n\n return lines", "def text_to_matrix(text):\n matrix = []\n for i in range(0, 8, 2):\n matrix.append([int(text[i] + text[i+1], 16), int(text[i+8] + text[i+9], 16),\n ...
[ "0.6663844", "0.66369677", "0.6621791", "0.617014", "0.61520714", "0.61395663", "0.6071079", "0.6000583", "0.5962202", "0.5890576", "0.58884305", "0.58818334", "0.58665574", "0.5851002", "0.5772027", "0.56664914", "0.5654367", "0.5645098", "0.5634978", "0.56204677", "0.560234...
0.0
-1
Get word matrix. W[i] is the vector for word indexed by i
def rand_TE(num_topics=5, k=20): W = np.random.uniform(-0.25,0.25,(num_topics,k)) return W
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_matrix_of_vectors(wv_from_bin, required_words=['softball', 'technology','street','project','fellow','maps','view','fuel','summer','clubhouse','ball','steal','soccer','driving','motor','comedy']):\n import random\n words = list(wv_from_bin.vocab.keys())\n print(\"Shuffling words ...\")\n random....
[ "0.7206552", "0.70206374", "0.6722377", "0.6556378", "0.6531552", "0.6528248", "0.6501242", "0.64862776", "0.64330167", "0.6422995", "0.64024043", "0.63945264", "0.6394137", "0.6350247", "0.6325137", "0.63241976", "0.6304245", "0.6274398", "0.6263698", "0.62422335", "0.623854...
0.0
-1
checks for equality beetwen two MyInts return False o True
def __eq__(self, number): return int(self) != number
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __eq__(self, oth):\n return int(self) != oth", "def __ne__(self, oth):\n return int(self) == oth", "def __eq__(self, other):\n return int(self) != int(other)", "def __eq__(self, other):\n return int.__ne__(self, other)", "def __ne__(self, other):\n return int(self) ==...
[ "0.76982534", "0.7489979", "0.7380747", "0.7375535", "0.7313602", "0.7142088", "0.6908504", "0.68830556", "0.68567646", "0.6777183", "0.6627412", "0.6612154", "0.66104484", "0.65805703", "0.65621144", "0.6551062", "0.6542485", "0.65216887", "0.65202266", "0.65168554", "0.6506...
0.69736755
6
checks for equality beetwen two MyInts
def __ne__(self, number): return int(self) == number
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __eq__(self, oth):\n return int(self) != oth", "def __eq__(self, other):\n return int(self) != int(other)", "def __eq__(self, other):\n return int.__ne__(self, other)", "def __ne__(self, oth):\n return int(self) == oth", "def same(self, x: int, y: int):\n\n return sel...
[ "0.7517991", "0.7299583", "0.7024994", "0.69548833", "0.68217367", "0.6819955", "0.67301023", "0.67204297", "0.66224813", "0.659244", "0.6561572", "0.65176463", "0.6499448", "0.6496064", "0.64380145", "0.64290977", "0.6324286", "0.6321902", "0.62818635", "0.6244796", "0.62301...
0.58893675
87
Return the absolute path to a valid plugins.cfg file. Copied from sf_OIS.py
def getPluginPath(): import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugins.cfg')] for path in paths: if os.path.exists(path): return path sys.stderr.write("\n" "** Warning: Unable to locate a suitable plugins.cfg file.\n" "** Warning: Please check your ogre installation and copy a\n" "** Warning: working plugins.cfg file to the current directory.\n\n") raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_config_file_location():\n\n return './' + CONFIG_FILE_NAME", "def config_file_and_path():\n return str(rmfriend_dir() / 'config.cfg')", "def config_path(self):\n if os.path.exists(self._config_path):\n if pyhocon.ConfigFactory.parse_file(self._config_path):\n retu...
[ "0.7101111", "0.7079233", "0.70316", "0.691988", "0.6856361", "0.6809086", "0.67529494", "0.6713169", "0.6694192", "0.6685862", "0.6680839", "0.6547461", "0.64858216", "0.6481523", "0.6454455", "0.64139074", "0.6406523", "0.64045656", "0.6398177", "0.63761204", "0.635552", ...
0.82794327
0
This shows the config dialog and returns the renderWindow.
def configure(ogre_root): user_confirmation = ogre_root.showConfigDialog() if user_confirmation: return ogre_root.initialise(True, "OGRE Render Window") else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def openRocConfig(self):\n self.rocConfig_Window = QtWidgets.QDialog()\n self.rocConfig_ui = Ui_rocConfigure()\n self.rocConfig_ui.setupUi(self.rocConfig_Window)\n self.rocConfig_Window.show()", "def display_window(self):\n frame = tk.Frame(master=self.param_window)\n fr...
[ "0.6363973", "0.6353406", "0.62993693", "0.6273288", "0.62459344", "0.62194985", "0.6168433", "0.61429256", "0.6130523", "0.6106466", "0.60738796", "0.6022143", "0.59356743", "0.5909631", "0.58671", "0.5833457", "0.58322257", "0.57948744", "0.5749032", "0.5740846", "0.570118"...
0.6725343
0
Read a DICOM file, raising an exception if the 'DICM' marker is not present at byte 128. dicom.read_file() does this as of pydicom 0.9.5.
def read_dicom_file(fname): fo = open(fname) try: preamble = fo.read(128) magic = fo.read(4) if len(preamble) != 128 or magic != 'DICM': raise InvalidDicomError fo.seek(0) do = dicom.read_file(fo) finally: fo.close() return do
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _read(path, desired_size):\n \n dcm = pydicom.dcmread(path)\n\n slope, intercept = dcm.RescaleSlope, dcm.RescaleIntercept\n \n try:\n img = (dcm.pixel_array * slope + intercept)\n except:\n img = np.zeros(desired_size[:2])-1\n \n if img.shape != desired_size[:2]:\n ...
[ "0.5621899", "0.54997045", "0.54964674", "0.5454611", "0.53653544", "0.5280224", "0.52707344", "0.5212712", "0.52099603", "0.5170325", "0.516826", "0.51599985", "0.51240665", "0.51210904", "0.5107606", "0.51000935", "0.50604916", "0.5044146", "0.5007753", "0.5000708", "0.4984...
0.7051324
0
given our dicom_files and studies records and a patient ID, return a list of (datetime, study instance UID) ordered by date+time
def patient_studies(dicom_files, studies, patient_id): ps = [] for uid in dicom_files[patient_id]: datetime = '%s%s' % studies[uid] ps.append([datetime, uid]) ps.sort(lambda a, b: cmp(a[0], b[0])) for el in ps: date_time_parts = (el[0][0:4], el[0][4:6], el[0][6:8], el[0][8:10], el[0][10:12], el[0][12:14]) el[0] = '%s-%s-%s %s:%s:%s' % date_time_parts return ps
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_all_dicom_images(self, verbose=True):\n if verbose: print(\"Loading dicom files ... This may take a moment.\")\n\n path = self.get_path_to_dicom_files()\n fnames = [fname for fname in os.listdir(path)\n if fname.endswith('.dcm') and not fname.startswith(\".\...
[ "0.60390854", "0.5873085", "0.5861059", "0.5460806", "0.5381554", "0.53764325", "0.5292173", "0.52161545", "0.5200111", "0.51963425", "0.5172361", "0.516292", "0.5146686", "0.5142398", "0.51141894", "0.511357", "0.5112972", "0.510411", "0.5102937", "0.5091951", "0.5091913", ...
0.82577133
0
Create a new DICOM UID. Return an alreadycreated UID if the old UID has already been replaced.
def new_uid(old_uid): if old_uid not in uids: uids[old_uid] = '2.25.%d' % uuid.uuid1().int return uids[old_uid]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def new_uid():\n return str(uuid.uuid1())[:30]", "def create_uid():\n return random_string(5, string.hexdigits.lower())\n # return (\"%x\" % (int(time.time()) * 0x10 % 0x1000000000)\n # + random_string(7, string.hexdigits.lower()))", "def generate_uid(prefix=PYDICOM_ROOT_UID, entropy_srcs=N...
[ "0.69686115", "0.68575305", "0.6833389", "0.66276854", "0.6467969", "0.62508255", "0.61379224", "0.6119005", "0.6028553", "0.6014281", "0.59217644", "0.58923423", "0.58923423", "0.5885048", "0.5780032", "0.5770298", "0.5749628", "0.57420045", "0.57420045", "0.57278305", "0.57...
0.67064506
3
Check if a project/subject/session identifier is valid. Identifiers can only contain alphanumeric characters and underscores.
def _validate_identifier(self, identifier): for c in identifier: if c not in string.letters + string.digits + '_': return False return True
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def IsProjectIDValid(project):\n if len(project) < 6 or len(project) > 30:\n return False\n return bool(re.match('^[a-z][a-z0-9\\\\-]*[a-z0-9]$', project))", "def IsValidIdentifier(string):\n counter = 0\n if string in keyword.kwlist:\n feedback = (False, \"Invalid: can't use a keyword as your ...
[ "0.7817043", "0.7263203", "0.71657807", "0.6915533", "0.6915533", "0.6901704", "0.68005633", "0.6792642", "0.67050254", "0.6685971", "0.6454717", "0.64318484", "0.6427234", "0.64037365", "0.6375381", "0.6367689", "0.6350279", "0.6343211", "0.6312446", "0.63092995", "0.6287927...
0.7744844
1
Scrapes for requested number of items and search word(s) as category.
def extract_etsy_items(number_of_items: int, category: str) -> pd.DataFrame: print(f"Scrapping category \"{category}\"") result = [] page_number = 1 headers = {"User-Agent": "Mozilla/5.0"} while len(result) < number_of_items: time.sleep(2) url = f"https://www.etsy.com/search?q={make_url_compatible(category)}" \ f"&ref=pagination&page={page_number} " source = requests.get(url, headers=headers) soup = BeautifulSoup(source.content, "html.parser") items = soup.select("li.wt-list-unstyled") if len(items) == 0: print(f'Total items of {category} was found less than requested: ' f'{len(result)}') break for item in items: if len(result) >= number_of_items: break record = extract_item_data(item) if record: result.append(record) page_number += 1 return pd.DataFrame(result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_item_list(client, word=''):\n\titem_group = client.search_metadata('collection_name:cooee')\n\titems = item_group.get_all()\n\titem_list_name = word + '_list'\n\titem_urls = []\n\tfor item in items:\n\t\tprimary_text = item.get_primary_text()\n\t\tif word in primary_text:\n\t\t\tprint item.url()\n\t\t\t...
[ "0.5936122", "0.5875122", "0.58417684", "0.58384866", "0.5813017", "0.5788929", "0.5743952", "0.574124", "0.5724943", "0.5716384", "0.57140964", "0.5701603", "0.5691337", "0.56734043", "0.5648546", "0.5612714", "0.5611656", "0.55976135", "0.55937296", "0.55912596", "0.5578013...
0.58419687
2
Converts string to URL compatible.
def make_url_compatible(category: str) -> str: return urllib.parse.quote(category)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def text_to_url(self, text):\r\n return QUrl(text)", "def url(value: Any) -> str:\n url_in = str(value)\n\n if urlparse(url_in).scheme in [\"http\", \"https\"]:\n return cast(str, vol.Schema(vol.Url())(url_in))\n\n raise vol.Invalid(\"Invalid URL\")", "def url_fix(s, charset='utf-8'):\n ...
[ "0.6706412", "0.6616591", "0.6346535", "0.63381904", "0.6220913", "0.6202903", "0.6197797", "0.6176937", "0.6167852", "0.6164724", "0.61420554", "0.61230433", "0.6118814", "0.61146235", "0.6109616", "0.60942715", "0.60720885", "0.6057571", "0.6017928", "0.59949386", "0.595964...
0.5838849
35
Normalizes USD price with thousand separator into float value
def normalize_price(price: str) -> float: return float(price.strip().replace(',', ''))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_price(str_val):\n return float(str_val.replace('.', '').replace(',', '.'))", "def clean_dollar_to_float(value):\n return (value.replace('$', '').replace(',', ''))", "def convert_currency(val):\n new_val = val.replace(',','').replace('$', '')\n return float(new_val)", "def clean_value(self...
[ "0.72919416", "0.7071461", "0.6978202", "0.6896954", "0.68778527", "0.6861502", "0.668687", "0.66791004", "0.6679073", "0.6679073", "0.6679073", "0.6679073", "0.6679073", "0.6636291", "0.6459509", "0.64089173", "0.64083546", "0.63997513", "0.6395582", "0.6393109", "0.6388328"...
0.80026025
0
Take a list of categories from categories table in database. Scrapes website for all of them. Prepare data for inserting to the database.
def get_all_categories_items(number_of_items: int) -> pd.DataFrame: all_items = pd.DataFrame() for (category_id, category_name) in get_categories(): items = extract_etsy_items(number_of_items, category_name) items['categoryId'] = category_id items = items[['categoryId', 'title', 'price', 'itemURL', 'imgURL']] items.set_index('categoryId', inplace=True) all_items = all_items.append(items) return all_items
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scrapeCategories():\n page = requests.get(\"http://books.toscrape.com/index.html\")\n soup = BeautifulSoup(page.content, 'html.parser')\n content = soup.find(\"div\", {\"class\": \"side_categories\"}).findChild().find(\"ul\")\n categories = content.find_all(\"a\")\n for category in categories:\n...
[ "0.69870496", "0.68652314", "0.65082896", "0.6431102", "0.63733405", "0.63554925", "0.633605", "0.632757", "0.6321157", "0.62610203", "0.6253101", "0.6226809", "0.6174908", "0.61444", "0.6128838", "0.6115741", "0.6043684", "0.6017082", "0.5986148", "0.5977991", "0.5969803", ...
0.5311808
82
Insert all items into the database.
def save_items_to_database(items: pd.DataFrame) -> None: for item in items.itertuples(): insert_item(item)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def insert(self, items=''):\n cur = self.conn.cursor()\n\n format_args = {'table': self.__name__,\n 'items': ', '.join(items.keys()),\n 'values': ', '.join([':'+key for key in items.keys()])}\n \n insert_query = \"\"\"\n INSERT INTO...
[ "0.738048", "0.728863", "0.7119373", "0.69322", "0.69140184", "0.6894494", "0.6738854", "0.6694093", "0.66766566", "0.6634999", "0.65382606", "0.653699", "0.6525922", "0.6473785", "0.6451338", "0.6418449", "0.63942665", "0.63700026", "0.63535374", "0.6332911", "0.62997335", ...
0.7253259
2
Exports given file to csv.
def save_items_to_csv(items_data: pd.DataFrame): with open('etsy_items.csv', 'w') as f: writer = csv.writer(f) writer.writerows(items_data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def export_csv(self):\n outputfile = tkinter.filedialog.asksaveasfilename(\n defaultextension=\".csv\",\n filetypes=((\"comma seperated values\", \"*.csv\"),\n (\"All Files\", \"*.*\")))\n if outputfile:\n tabledata = self.tabs.window.aistracker....
[ "0.7477921", "0.74023473", "0.72890913", "0.7163044", "0.7147001", "0.7147001", "0.7116825", "0.7090414", "0.70343846", "0.7002203", "0.6979948", "0.695002", "0.6947416", "0.69094193", "0.6906419", "0.68957627", "0.686277", "0.68464404", "0.6839928", "0.6741557", "0.67377245"...
0.0
-1
Retrieve, update or delete a person instance.
def PrintVisitante(request, pk): try: visitante = Visitante.objects.get(pk=pk) except Visitante.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = VisitanteSerializer(visitante) return Response(serializer.data) elif request.method == 'PUT': serializer = VisitanteSerializer(visitante, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def person(self, person_id):\r\n return persons.Person(self, person_id)", "def edit_person():\n # get person name from user\n responses = accept_inputs([\"Person's name\"])\n person_name = responses[\"Person's name\"]\n # check for existence\n results = query_with_results(\"select * from person where...
[ "0.6274317", "0.6184409", "0.6044379", "0.60121447", "0.60050964", "0.5923112", "0.59186417", "0.5886551", "0.58603877", "0.5851857", "0.58510053", "0.58013856", "0.5764969", "0.57433015", "0.5636165", "0.5635824", "0.5605609", "0.5604004", "0.55662686", "0.5558843", "0.55301...
0.0
-1
Does a country like Mexico or United States get a code assigned?
def test_country_code(self): country_name = 'United States' # population = int(float(pop_dict['Value'])) code = get_country_code(country_name) #Assert methods verifies result received matches expected one self.assertEqual(code, 'usa')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def country(alpha_2_code: str) -> None:", "def get_country_code(self):\n #method on the class InternationalMelonOrder\n\n return self.country_code\n # international has country code; domestic does not\n # WAI???", "def get_country_code(country_name):\n for code, name in COUNTRIES...
[ "0.78264016", "0.74500364", "0.7422215", "0.7363206", "0.7362113", "0.7261186", "0.7252336", "0.7212905", "0.7122891", "0.709406", "0.7093551", "0.7011302", "0.6986172", "0.69353557", "0.69182456", "0.68706924", "0.6821515", "0.6747886", "0.6657928", "0.6657928", "0.6580908",...
0.73427856
5
Reads the csv file CSV file should contain ['Question', 'Answer'] columns Remove NaN values Throw error if format is bad or file does not exist
def parse_csv_file(self, csv_file: str): try: df = pd.read_csv(csv_file) if not set(['Question', 'Answer']).issubset(df.columns): raise BadCSVFile( "CSV file does not contain ['Question', 'Answer'] columns.") df.dropna(inplace=True) except Exception as e: raise BadCSVFile( "Error while reading the csv file. Please check the path of the file or the file might be curropted.") return df
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_csv():", "def read_csv_file(self):\n pass", "def test_csv(self, input_file_path: str, answer_file_path: List[Dict]):\n with open(attach_path(answer_file_path), 'r') as answer_file:\n csv_file = open(attach_path(input_file_path))\n assert str(read_csv(csv_file)) == a...
[ "0.7320947", "0.6934107", "0.6727932", "0.6726128", "0.6720706", "0.6720139", "0.67085135", "0.66700244", "0.65878505", "0.6561937", "0.64199805", "0.64198834", "0.6413396", "0.6406278", "0.64025426", "0.63658756", "0.63533485", "0.63505536", "0.63503546", "0.63334334", "0.63...
0.77133363
0
Create a mechanism to vectorize the data Create vector for our current dataset
def build_model(self, documents): self.vectorizer = TfidfVectorizer( stop_words='english', lowercase=True).fit(documents) self.vectors = self.vectorizer.transform(documents)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def vectorize(self):\n return vectorize(self)", "def _vectorize_data(self, docs: []):\n print('Vectorizing data...')\n tfidf = TfidfVectorizer()\n encoded_data = tfidf.fit_transform(docs)\n return encoded_data", "def get_data_vector(self) -> DataVector:\n raise NotImpl...
[ "0.7192277", "0.66099465", "0.6579369", "0.65683573", "0.6435415", "0.6372212", "0.63627356", "0.636164", "0.63602024", "0.6243461", "0.6200177", "0.61812717", "0.617205", "0.6124774", "0.60975635", "0.60963786", "0.6080632", "0.6075216", "0.6062782", "0.6045074", "0.60133845...
0.0
-1
Returns a vector for a given query
def get_vector(self, query: list): if len(query) == 0: raise BadQueryParameter("Query (list) can not be empty.") return self.vectorizer.transform(query)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _to_full_vector(self, query_vector: List[Tuple[str, float]]) -> np.array:\n terms = list(self.index.get_terms())\n terms.sort()\n vector = np.zeros(len(terms))\n\n for (term, weight) in query_vector:\n index = terms.index(term)\n vector[index] = weight\n\n ...
[ "0.710231", "0.6852143", "0.6806123", "0.6790017", "0.65516216", "0.6484472", "0.6346682", "0.62224436", "0.62009585", "0.61882883", "0.6144658", "0.6134512", "0.61188674", "0.6103813", "0.6086374", "0.6070219", "0.60688305", "0.5987167", "0.59024227", "0.5888981", "0.5858321...
0.7983144
0
Returns cosine similarity between the input question and our dataset questions
def get_cosine_similarity(self, query: list): question_vector = self.get_vector(query) return cosine_similarity(question_vector, self.vectors).flatten()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cosine_similarity(self, source_doc, input_doc):\n vectorizer = self.vectorizer or TfidfVectorizer(tokenizer=PlagiarismDetector.tokenize_and_stem, stop_words='english')\n tfidf = vectorizer.fit_transform([source_doc, input_doc])\n return ((tfidf * tfidf.T).A)[0, 1]", "def calculate_cosine...
[ "0.77647394", "0.77439165", "0.7479039", "0.7361782", "0.72787845", "0.7188363", "0.7178258", "0.7110796", "0.7093376", "0.7010269", "0.6990073", "0.6989606", "0.6962196", "0.6950967", "0.6913966", "0.6902417", "0.68863827", "0.6876185", "0.68280274", "0.67813444", "0.6764831...
0.7567193
2
API function that can be used by other codebase It takes query (string) and n top similar questions along with thier answers
def perform_query(self, query: str, n: int = 5): query = [query] cosine_similarities = self.get_cosine_similarity(query) indices = cosine_similarities.argsort()[:-n-1:-1] return self.data[ self.data.index.isin(indices) ].reset_index(drop=True).to_dict(orient='records')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def top_n_satisfy2(content, n):\n #print(n)\n sum_satisfy = 0.0\n query_num = 0.0\n for qid in content:\n label_sort = []\n score = []\n all_info = content[qid]\n num_label1 = 0\n for info in all_info:\n if info[0] > 0:\n num_label1 += 1\n ...
[ "0.6818519", "0.6672054", "0.66686153", "0.6436746", "0.6367996", "0.63375914", "0.63115406", "0.6299758", "0.6281875", "0.6159052", "0.61510074", "0.61417896", "0.6108233", "0.61047775", "0.6080384", "0.60795337", "0.60682553", "0.60677445", "0.60321194", "0.60313493", "0.60...
0.54849684
63
Get most likely categorical variables (onehot)
def get_most_likely(self): c_cat = self.theta.argmax(axis=1) T = np.zeros((self.d, self.max)) for i, c in enumerate(c_cat): T[i, c] = 1 return T
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unhot(one_hot_labels):\n return np.argmax(one_hot_labels, axis=1)", "def infer_categorical_variables_in_place(df: pd.DataFrame):\n # infer which variables are categorical\n MAX_UNIQUE_VALUES = 10\n for column in df.columns:\n if df[column].nunique() <= MAX_UNIQUE_VALUES:\n df[co...
[ "0.7186164", "0.71264297", "0.700594", "0.6770333", "0.66180325", "0.6554686", "0.65422523", "0.6527132", "0.6494277", "0.6475236", "0.64435905", "0.64244854", "0.64193946", "0.64063036", "0.6401098", "0.63921547", "0.63824326", "0.63524544", "0.63380814", "0.6334604", "0.632...
0.0
-1
Ranking Based Utility Transformation. w(f(x)) / lambda = 1/mu if rank(x) <= mu 0 if mu < rank(x) < lambda mu 1/mu if lambda mu <= rank(x) where rank(x) is the number of at least equally good points, including it self. The number of good and bad points, mu, is ceil(lambda/4). That is, mu = 1 if lambda = 2 mu = 1 if lambda = 4 mu = 2 if lambda = 6, etc. If there exist tie points, the utility values are equally distributed for these points.
def ranking_based_utility_transformation(losses, lam, rho=0.25, negative=True): eps = 1e-14 idx = np.argsort(losses) mu = int(np.ceil(lam * rho)) _w = np.zeros(lam) _w[:mu] = 1 / mu _w[lam - mu:] = -1 / mu if negative else 0 w = np.zeros(lam) istart = 0 for i in range(losses.shape[0] - 1): if losses[idx[i + 1]] - losses[idx[i]] < eps * losses[idx[i]]: pass elif istart < i: w[istart:i + 1] = np.mean(_w[istart:i + 1]) istart = i + 1 else: w[i] = _w[i] istart = i + 1 w[istart:] = np.mean(_w[istart:]) return w, idx
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_good(self, m, n, rank, mu=2, ka=2):\n sr = random.random()\n s = []\n s.append(sr)\n for r in range(rank-1):\n newele = s[-1] * (1 + ka * random.random() / (rank-1))\n s.append(newele)\n s.reverse()\n \n # best_u = None\n # ...
[ "0.60227036", "0.59967417", "0.5658467", "0.5579704", "0.55585", "0.55581784", "0.55484015", "0.5513262", "0.5466028", "0.54607856", "0.54588825", "0.5439738", "0.5396137", "0.5386086", "0.5380749", "0.53742325", "0.5363156", "0.53529656", "0.5346669", "0.5311985", "0.5311851...
0.51569587
42
Groups data in SimulationReport's by the value of alpha or gamma2
def group_data(simulation_reports: List[SimulationReport]) -> Dict[float, SimulationTable]: heat_maps: OrderedDict[float, SimulationTable] = OrderedDict() for report in simulation_reports: if report.param not in heat_maps: param_name = "alpha" if report.growth_type == GrowthType.Polynomial else "gamma2" simulation_table = heat_maps.setdefault( report.param, SimulationTable(report.growth_type, param_name, report.param, OrderedDict()), ) else: simulation_table = heat_maps[report.param] errors_by_prefix = simulation_table.errors.setdefault(report.prefix_length, []) errors_by_prefix.append((report.b0, report.error)) return heat_maps
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compute_data_gamma_(idx2_daid, wx2_rvecs, wx2_aids, wx2_idf,\n alpha=3, thresh=0):\n if utool.DEBUG2:\n from ibeis.model.hots.smk import smk_debug\n smk_debug.rrr()\n smk_debug.check_wx2(wx2_rvecs=wx2_rvecs, wx2_aids=wx2_aids)\n wx_sublist = pdh.ensure_values(p...
[ "0.5615865", "0.5525419", "0.5523908", "0.54661447", "0.536697", "0.53608376", "0.5330283", "0.52438", "0.5227983", "0.5227983", "0.5154076", "0.5146968", "0.51379746", "0.51017696", "0.5098285", "0.50540596", "0.5026247", "0.5020847", "0.50154185", "0.49952942", "0.4989816",...
0.6480124
0
Abstract method which provides a set of hyperparameters. This method will get called when the framework is about to launch a new trial,
def generate_parameters(self, parameter_id, **kwargs): # FIXME: some tuners raise NoMoreTrialError when they are waiting for more trial results # we need to design a new exception for this purpose raise NotImplementedError('Tuner: generate_parameters not implemented')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_hyperparams(self):", "def _get_current_hyperparameters(self):", "def get_hyper_params():\n #################################\n ##### INSERT YOUR CODE HERE #####\n layers_size = [10]\n activation = 'relu'\n lr = 5e-4\n epochs = 30\n dropout_rate = 0.2\n init_kind = 'xavier'\n ...
[ "0.7449988", "0.73030883", "0.6955949", "0.6952735", "0.69313055", "0.6916811", "0.6915098", "0.6915098", "0.6910595", "0.6755054", "0.66564333", "0.6618931", "0.6612997", "0.6604273", "0.6575251", "0.6572437", "0.64946365", "0.64934057", "0.6481356", "0.6410235", "0.64025366...
0.6258678
30