query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Updates the document from the index. This should be called via a signal whenever the obj gets saved.
def update_document(obj): index = obj.get_index_name() doc_type = obj.get_document_type() body = dict(doc=obj.get_document_body()) try: ES.update(index=index, doc_type=doc_type, body=body, id=obj.pk) except NotFoundError: raise DocumentNotFound(obj.get_index_name(), obj.pk)
[ "def update_document(self):\n pass", "def update_index(self, document):\n\t\tix = self.get_index()\n\n\t\twith ix.searcher():\n\t\t\twriter = AsyncWriter(ix)\n\t\t\twriter.delete_by_term(self.id, document[self.id])\n\t\t\twriter.add_document(**document)\n\t\t\twriter.commit(optimize=True)", "def update_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a document from the index. This should be called via a signal when the obj gets deleted.
def delete_document(obj): index = obj.get_index_name() doc_type = obj.get_document_type() try: ES.delete(index=index, doc_type=doc_type, id=obj.pk) except NotFoundError: raise DocumentNotFound(obj.get_index_name(), obj.pk)
[ "def delete_document(self, index: str, doc_id: str):\n self.__client__.delete(index=index, id=doc_id, refresh=True)", "def delete_document(self):\n pass", "def delete(self, id):\n if self._index is None:\n raise errors.IndexerError(\"IndexerConnection has been closed\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize all models with statistics about cases. It can either receive an explicit data frame with cases/deaths statistics, a callable object that receives a model and return the desired cases. If none of these are passed, it assumes that the cases should be initialized from the region.
def init_cases(self: T, data=None, regions=None, raises=True, **kwargs) -> T: kwargs["regions"] = {} if regions is None else regions kwargs.setdefault("real", True) for i, report in enumerate(self._reports): print(i, report.model.region.id, report.model.region.name) call...
[ "def initialize_case_metrics(self) -> None:\n for case in self.cases:\n graph_distance, time_distance = extract_case_distances(self.process_model_graph, case)\n case.graph_distance = graph_distance\n case.time_distance = time_distance", "def build_case_statistics(country_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize R0 from cases data.
def init_R0(self: T, *args, raises=False, **kwargs) -> T: for report in self._reports: call_safe_if(raises, report, report.init_R0, *args, **kwargs) return self
[ "def _initialize_data(self):\n self.OUT_values = None\n self.truncated_output = False\n self.auto_send = False\n self.input_mode = \"R0\"\n\n pass", "def __init__(self):\n\n # Dictionnaire de cases.\n # La clé est une position (ligne, colonne), et la valeur est une...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a data frame from simulations by extracting all columns in the given list at the selected times.
def report_time_columns_data( self, columns, times=(7, 15, 30, 60), info=None, dtype=None ) -> pd.DataFrame: locs = [t - self._niter - 1 for t in times] col_names = [*map(col_name, columns)] columns = [*map(to_column, columns)] rows = [] n_times = len(times) n...
[ "def setup_table(interval, start, end, column_list, multi_dim):\n time_array = []\n dataframe = pd.DataFrame(columns=column_list)\n\n for i in range(start, end, interval):\n time_array.append(i)\n\n dataframe['Time'] = time_array\n\n if multi_dim is True:\n out = [dataframe]\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert column identifier into a function with signature ``(model, dates) > data`` used to retrieve data from models.
def to_column(col): if callable(col): return col def fn(model, dates): return model[col + ":dates"].loc[dates] return fn
[ "def transform_func(self, data):\n if self.columns is None:\n return data\n\n columns = self._check_columns(data)\n columns = self._columns_to_select(columns, data)\n\n return data[:,columns]", "def column_expression(self, col):\n return getattr(func, self.impl.as_bin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a column name from its representation.
def col_name(col): if isinstance(col, str): return col return col.__name__
[ "def getColName(self, col):\n try:\n return chr(ord('a') + col)\n except:\n return col", "def columnName(self, column):\n return self.gCustomColumnList[column]['name']", "def get_name(self):\n return self.col_name", "def _valid_column(column_name):\n return str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Safely call function that involves a report. If function raises an error, log the error with report.log_error() method.
def call_safe(*args, **kwargs): report, func, *args = args if not callable(func): func = getattr(report, func) try: return func(*args, **kwargs) except Exception as ex: msg = f"{type(ex).__name__}: {ex}" report.log_error(msg, code=ex) return None
[ "def report(self, report):\n if report in self.reports:\n r = self.reports[report]()\n r.run(self.outfile)", "def _safely_call(self, thing_to_call, *args, **kwargs):\n try:\n return thing_to_call(*args, **kwargs)\n except Exception:\n log.exception(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load calibrations into the database
def load(db): r = db.truncate_table('calibrations') print "Truncated calibrations table" # Allowed columns columns = ['class','asset_uid','start_date','serial','name','value','notes'] # Read in calibration data file_mask = "repos/asset-management/calibration/*" directory_list = glob.glob(file_mask) fo...
[ "async def load_calibrations(self):\n self.p.load_calibration_json()\n self.p.load_preset_json()\n self.p.load_tunings_json()\n self.z.load_calibration_json()\n self.z.load_preset_json()\n self.z.load_tunings_json()\n self.y.load_calibration_json()\n self.y.lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize blockchain + open transfers data from a file
def load_data(self): try: with open("blockchain.txt", mode="r") as f: file_content = f.readlines() blockchain = json.loads(file_content[0][:-1]) # OrderedDict updated_blockchain = [] for block in blockchain: ...
[ "def load_data(self):\n try:\n with open(\"blockchain.txt\", mode=\"r\") as f:\n file_content = f.readlines()\n blockchain = json.loads(file_content[0][:-1])\n updated_blockchain = []\n for block in blockchain:\n update...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save blockchain + open transactions snapshot to a file
def save_data(self): try: with open("blockchain.txt", mode="w") as f: dict_chain = [] for block in self.__chain: temp = Block( block.index, block.previous_hash, [tx.__dict__ fo...
[ "def write_to_disk(self):\n text_file = open(self.file_path, \"w\")\n text_file.write(str(self))\n text_file.close()\n # dump to pickle\n pickle.dump(self.blockchain, open(self.pickle_path, \"wb\"))", "def save_data(self):\n try:\n with open('blockchain-{}.txt'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a proof of work for the open transfers, the hash of the previous block and a random number (which is guessed until it fits).
def proof_of_work(self): last_block = self.__chain[-1] last_hash = hash_block(last_block) proof = 0 # Try different PoW numbers and return the first valid one while not Verification.valid_proof(self.__open_transfers, last_hash, proof): proof += 1 print(proof) ...
[ "def _calc_proof_of_work(self):\n\n while True:\n guess = f'{self._calc_block_hash(self.previous_hash)}{self.nonce}'\n guess_hash = sha256(guess.encode('utf-8')).hexdigest()\n if guess_hash[:Block.NONCE_LEVEL] == '0' * Block.NONCE_LEVEL:\n return guess_hash\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Credit points to user. No checks required
def credit_points(self, user, signature, amount=0.0): if self.hosting_node == None: return False transfer = Transfer(user, signature, amount) if not Wallet.verify_transfer(transfer): return False self.__open_transfers.append(transfer) # participants.add(us...
[ "def test_points_to_credits(self):\n u, m = self._create_user_with_membership()\n m.add_points(100)\n self.assertEqual(Member.points_needed_for(10), 100)\n m.convert_points_to_these_credits(10)\n self.assertEqual(m.points, 0)\n self.assertEqual(m.credits, 10)\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debit points from user. Need to verify sufficient points.
def debit_points(self, user, signature, amount=0.0): if self.hosting_node == None: return False transfer = Transfer(user, signature, amount) if Verification.verify_single_transfer(transfer, self.get_balance): self.__open_transfers.append(transfer) # participan...
[ "def purchase_points():\n form = PurchasePointsForm()\n if request.method == \"POST\" and form.validate():\n points = int(form.points.data)\n current_user.purchased_points += points\n try:\n current_user.save()\n flash(\"Richie !!! Let's spend some money\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all connected peer nodes.
def get_peer_nodes(self): return list(self.__peer_nodes)
[ "def get_set_peer_nodes(self):\n return self.__peer_nodes", "def get_connected_peers(self):\n \n p = \"\"\n \n if self.connected_peers:\n p = self.connected_peers[0][0] + \":\" + str(self.connected_peers[0][1])\n\n for peer in self.connected_peers[1:]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PWM signal generator with direction signal for DC motors. The generated PWM frequency is approximately 25 KHz (25 MHz / 1024). The duty cycle can be fully controlled via a 11bit speed input. pwm Output PWM signal dir Output direction signal en_n Active low output enable signal clk25 25 MHz clock input speed 11bit signe...
def MotorDriver(pwm, dir, en_n, clk25, speed, rst_n, optocoupled): assert speed.min >= -2**10 and speed.max <= 2**10, 'wrong speed constraints' # account for optocouplers LOW_OPTO = LOW if not optocoupled else HIGH HIGH_OPTO = HIGH if not optocoupled else LOW CNT_MAX = 2**10 - 1; @instance ...
[ "def DriveMotor():\n\n # cnt overflows at 25KHz (approximately)\n cnt = intbv(0, min = 0, max = CNT_MAX + 1)\n\n # 10-bit duty cycle\n duty_cycle = intbv(0)[10:]\n\n while True:\n yield clk25.posedge, rst_n.negedge\n if rst_n == LOW:\n cnt[:] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate PWM, dir and brake signals for motor
def DriveMotor(): # cnt overflows at 25KHz (approximately) cnt = intbv(0, min = 0, max = CNT_MAX + 1) # 10-bit duty cycle duty_cycle = intbv(0)[10:] while True: yield clk25.posedge, rst_n.negedge if rst_n == LOW: cnt[:] = 0 ...
[ "def _set_pwm(self, raw_values):\n for i in range(len(self._pins)):\n self._pi.set_PWM_dutycycle(self._pins[i], raw_values[i])", "def start(self):\n \n if not self._sysfsWriter:\n self._sysfsWriter = SysfsWriter()\n \n \n if not exists(\"/sys/class/p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the train files of the `fold`
def train_files(self, fold: int) -> List[str]: all_files = [] for fold_id, inputs in enumerate(self.folds): if fold_id != fold: all_files += inputs return all_files
[ "def test_files(self, fold: int) -> List[str]:\n for fold_id, inputs in enumerate(self.folds):\n if fold_id == fold:\n return inputs\n\n return []", "def training_directory(trial_index, fold):\n return os.path.join(FLAGS.log_dir, 'train{0}-fold{1}'.format(trial_index, fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the test files of the `fold`
def test_files(self, fold: int) -> List[str]: for fold_id, inputs in enumerate(self.folds): if fold_id == fold: return inputs return []
[ "def train_files(self, fold: int) -> List[str]:\n all_files = []\n for fold_id, inputs in enumerate(self.folds):\n if fold_id != fold:\n all_files += inputs\n\n return all_files", "def get_test_files():\n test_files = os.listdir('./test')\n return [\n cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the fold split to the `filepath` as json.
def write_folds_to_json(self, filepath: str): with open(filepath, "w") as f: json.dump( { "isH5": self.is_h5_dataset, "folds": self.folds, }, f, indent=4, )
[ "def writeOut(self, filename):\r\n\t\twith open(filename, 'w') as f:\r\n\t\t\tf.writelines(json.dumps(self.board, indent=4))\r\n\t\t\tf.close()", "def write_json(self, data, fichier):", "def write_json(filepath, data):\r\n with open(filepath, 'w') as f:\r\n json.dump(data, f, indent=2)", "def write(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return environment variables starting with prefix
def env_vars(prefix): return {k: v for k, v in os.environ.items() if k.startswith(prefix)}
[ "def get_environ_vars(self, prefix='PIP_'):\r\n for key, val in os.environ.items():\r\n if key.startswith(prefix):\r\n yield (key.replace(prefix, '').lower(), val)", "def get_environ_vars(self, prefix='VIRTUALENV_'):\r\n for key, val in os.environ.items():\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an object from cache, return `None` if not found.
def cache_get(item: str) -> object: item = str(item) cache = cache_find(item) # cache_find() will return none if the cache does not exist # the returned location is guaranteed to exist, so no point checking again. if cache is not None: try: cached = pickle.load(open(cache, "rb")) except EOFError as ex: ...
[ "def get(self, name):\n with self.lock:\n if name not in self._cache:\n return None\n\n item = self._cache[name]\n if self._has_expired(item):\n return None\n\n item.hits += 1\n print(\"Returning object from cache %s\", self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save an item to cache, using a hashed ID.
def cache_save_hashed(item: str, obj: object) -> None: cache_save(md5(item), obj)
[ "def put(self, key, item):\n if key is None or item is None:\n return\n self.cache_data[key] = item", "def put(self, id, obj):\n if self.doCache:\n self.cache[id] = obj\n else:\n self.expiredCache[id] = ref(obj)", "def set(id, model):\n key = build...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an item from the cache, using a hashed ID.
def cache_remove_hashed(item: str) -> None: cache_remove(md5(item))
[ "def delete(self, item):\r\n self.fetch()\r\n t = self.make_item_tuple(item)\r\n changed = False\r\n while t in self.data:\r\n self.data.remove(t)\r\n changed = True\r\n \r\n if changed:\r\n query_cache.set(self.iden, self.data)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download the file from the provided url to the location. Uses the cache.
def download_file_cached(file_url: str, location: str) -> None: item = os.path.basename(location) local = cache_find(item) if local is None: # Cached item doesn't exist cache_create() download_file(file_url, "Cached/" + item) copy_file("Cached/" + item, location) return # Copy file from cache to locati...
[ "def _download_file(url):\n return requests.get(url, stream=True)", "def get_file(url, file_name=None):\n cache_dir = os.path.join(os.path.expanduser(\"~\"), \".jhML\")\n\n if file_name is None:\n file_name = url[url.rfind('/') + 1:]\n file_path = os.path.join(cache_dir, file_name)\n\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if a folder at the provided path exists.
def folder_exists(path: str) -> bool: return os.path.isdir(path)
[ "def folderExists(self, folderPath: unicode) -> bool:\n ...", "def exists(path: str) -> bool:\r\n if _is_local_path(path):\r\n return os.path.exists(path)\r\n elif _is_google_path(path):\r\n isfile, _ = _google_isfile(path)\r\n if isfile:\r\n return True\r\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Relabel array with consecutive values.
def relabel_consecutive(lab, start_from=0): new_lab = np.empty_like(lab) new_lab[:] = np.unique(lab, return_inverse=True)[1] new_lab += start_from return new_lab
[ "def relabel_sequential(label_field, offset=1):\n m = label_field.max()\n if not np.issubdtype(label_field.dtype, np.int):\n new_type = np.min_scalar_type(int(m))\n label_field = label_field.astype(new_type)\n m = m.astype(new_type) # Ensures m is an integer\n labels = np.unique(label...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Relabel according to overlap with reference.
def relabel_by_overlap(lab, ref_lab): u1 = np.unique(lab) u2 = np.unique(ref_lab) if u1.size > u2.size: thresh = lab.max() + 1 lab_shifted = lab + thresh lab_corr = find_label_correspondence(lab_shifted, ref_lab) lab_shifted = relabel(lab_shifted, new_labels=lab_corr) ...
[ "def update_labels(mask1, mask2):\n # Find the object in mask2 that has maximum overlap with an object in max1,\n # (as a fraction of the objects pixels in mask1)\n def get_max_overlap(mask1, mask2, label1):\n # Count overlapping pixels.\n labels, counts = np.unique(mask2[mask1 == label1], re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map data in source to target according to their labels. Target labels are sorted in ascending order, such that the smallest label indexes the value at position 0 in `source_val`. If `source_lab` is specified, any label in `target_lab` must be in `source_lab`.
def map_to_labels(source_val, target_lab, mask=None, fill=0, axis=0, source_lab=None): if mask is not None: if not isinstance(mask, np.ndarray): mask = target_lab != mask target_lab = target_lab[mask] mapped = map_to_labels(source_val, target_lab, axis=axis, ...
[ "def convert_labels(Y, source, target):\n if Y is None:\n return Y\n if isinstance(Y, np.ndarray):\n Y = Y.copy()\n assert Y.dtype == np.int64\n elif isinstance(Y, torch.Tensor):\n Y = Y.clone()\n assert isinstance(Y, torch.LongTensor)\n else:\n raise ValueError...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a string of verify statement.
def gen_v_stmt(q1n, q2n): return "verify {} {};\n".format(q1n, q2n)
[ "def format_verification(verification: Optional[str]) -> str:\n if not verification:\n return \"null\"\n return verification.replace('\"', \"`\")", "def run_verification(self, write=True, query_args=None):\n if not query_args:\n query_args = {}\n \n procedu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints text to the screen, using the currently active alignment.
def msg(text): for line in text.splitlines(): if JS.alignment == "left": print(demarkup(line)) elif JS.alignment == "center": print(demarkup(line).center(get_terminal_size()[0] - 1)) else: print(demarkup(line).rjust(get_terminal_size()[0] - 1))
[ "def print_at(x=1, y=1, text: str = \" \", fore=\"none\", style=\"none\", back=\"none\"):\n Cursor.set_position(x, y)\n print(style_text(text, fore=fore, back=back, style=style))", "def PrintAt(self,x=0,y=0,text=''):\n self.SetCursor(x,y)\n self.Print(text)", "def print_text_line():\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert Tags to Entities
def get_entities(tags): pass
[ "def _entity_tagger(self):\n\n # If this is a custom model, set the path to the directory\n if self.custom:\n self.model = self.path + self.model + \"/\"\n\n # Load the spaCy model\n try:\n nlp = spacy.load(self.model)\n except OSError:\n self.mode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add words to the hook, the freq can be zero
def add_word(self, word, freq=None): pass
[ "def add_word(word, freq=None, tag=None):\n global total\n word = strdecode(word)\n if freq is None:\n freq = suggest_freq(word)\n else:\n freq = int(freq)\n FREQ[word] = freq\n total += freq\n if tag:\n user_word_tag_tab[word] = tag\n for ch in xrange(len(word) - 1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hook to the new words
def hook(self, sentence, words): pass
[ "def _onWord(self, name, location, length):\n logging.debug(\"onWord...\")", "def new_match(self, new_word): \n self.rhyming_words.append(new_word)", "def replace_words_fun(self):\n\n cleaned_doc = []\n for word in str(self.doc).split():\n if word.lower() in sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of the bracket_as_entity option.
def bracket_as_entity(self): pass
[ "def entity_reference(self):\n if self.entity_kind == ContextEntityKind.anonymous:\n return None\n\n return getattr(self, self.entity_kind.value)", "def tag_value(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"tag_value\")", "def value_expression(self) -> Optio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of the en_quote_as_entity option.
def en_quote_as_entity(self): pass
[ "def zh_quote_as_entity(self):\n pass", "def quote_for(self):\n return self._quote_for", "def get_quotes(self):\n # However ignore the 'true' autodetection setting.\n jscs_quotes = self.jscs_options.get('validateQuoteMarks')\n if isinstance(jscs_quotes, dict):\n jsc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of the use_en option.
def use_en(self): pass
[ "def get_locale():\n return request.accept_languages.best_match(current_app.config['LANGUAGES'])\n # return 'es'", "def get_locale():\n setting = Setting.query.filter(Setting.name == 'default_language').first()\n\n if setting is not None:\n return setting.value\n\n # Return default language ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of the use_zh option.
def use_zh(self): pass
[ "def t(eng, chinese):\n return chinese if 'zh' in get_info().user_language else eng", "def include_chinese(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"include_chinese\")", "def get_translation_flag(self, country):\n country = country.strip().lower()\n if country ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the value of the zh_quote_as_entity option.
def zh_quote_as_entity(self): pass
[ "def en_quote_as_entity(self):\n pass", "def quote_for(self):\n return self._quote_for", "def quote_id(self) -> Optional[str]:\n return pulumi.get(self, \"quote_id\")", "def include_quote(self) -> Optional[bool]:\n return pulumi.get(self, \"include_quote\")", "def get_quotes(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the email addresses collected between startdate and enddate.
def get_email_addresses(startdate, enddate, user, password): emails = [] page = 1 more_pages = True while more_pages: response = requests.get( 'https://restapi.surveygizmo.com/v2/survey/{survey}' '/surveyresponse?' 'filter[field][0]=datesubmitted' ...
[ "def get_email_addresses(survey, startdatetime, enddatetime):\n token = settings.SURVEYGIZMO_API_TOKEN\n secret = settings.SURVEYGIZMO_API_TOKEN_SECRET\n emails = []\n page = 1\n more_pages = True\n survey_id = SURVEYS[survey][\"email_collection_survey_id\"]\n dtfmt = \"%Y-%m-%d+%H:%M:%S\"\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that the default parameters of an ExtrudeCircleShape are correct.
def test_default_parameters(self): assert self.test_shape.rotation_angle == 360 assert self.test_shape.extrude_both
[ "def test_default_parameters(self):\n\n assert self.test_shape.center_coordinate == (0.0, 0.0, 0.0)", "def test_default_parameters(self):\n\n assert self.test_shape.rotation_angle == 360\n assert self.test_shape.stp_filename == \"PoloidalFieldCoilCaseFC.stp\"\n assert self.test_shape.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an ExtrudeCircleShape with another ExtrudeCircleShape cut out and checks that the volume is correct.
def test_cut_volume(self): shape_with_cut = ExtrudeCircleShape(points=[(30, 0)], radius=20, distance=40, cut=self.test_shape) assert shape_with_cut.volume() == pytest.approx((math.pi * (20**2) * 40) - (math.pi * (10**2) * 30))
[ "def test_intersect_volume(self):\n\n intersect_shape = ExtrudeCircleShape(points=[(30, 0)], radius=5, distance=50)\n\n intersected_shape = ExtrudeCircleShape(\n points=[(30, 0)],\n radius=10,\n distance=50,\n intersect=[self.test_shape, intersect_shape],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates ExtrudeCircleShapes with other ExtrudeCircleShapes intersected and checks that their volumes are correct.
def test_intersect_volume(self): intersect_shape = ExtrudeCircleShape(points=[(30, 0)], radius=5, distance=50) intersected_shape = ExtrudeCircleShape( points=[(30, 0)], radius=10, distance=50, intersect=[self.test_shape, intersect_shape], ) ...
[ "def intersect_surfaces(guids):\n sc.doc.Views.Redraw()\n rs.UnselectAllObjects()\n layer('INTS_BOX')\n rs.SelectObjects(guids.boxes)\n rs.Command('_Intersect', echo=False)\n rs.UnselectAllObjects()\n layer('INTS')\n rs.SelectObjects(guids.fractures)\n rs.Command('_Intersect', echo=False)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an ExtrudeCircleShape with extrude_both = True and False and checks that the volumes are correct.
def test_extrude_both(self): test_volume_extrude_both = self.test_shape.volume() self.test_shape.extrude_both = False assert self.test_shape.volume() == pytest.approx(test_volume_extrude_both)
[ "def test_intersect_volume(self):\n\n intersect_shape = ExtrudeCircleShape(points=[(30, 0)], radius=5, distance=50)\n\n intersected_shape = ExtrudeCircleShape(\n points=[(30, 0)],\n radius=10,\n distance=50,\n intersect=[self.test_shape, intersect_shape],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exports and stp file with mode = solid and wire and checks that the outputs exist and relative file sizes are correct.
def test_export_stp(self): os.system("rm test_solid.stp test_solid2.stp test_wire.stp") self.test_shape.export_stp("test_solid.stp", mode="solid") self.test_shape.export_stp("test_solid2.stp") self.test_shape.export_stp("test_wire.stp", mode="wire") assert Path("test_solid.stp...
[ "def testFilledExporter(self):\n filename_a = os.path.join(FLAGS.test_tmpdir, 'test_a.far')\n filename_b = os.path.join(FLAGS.test_tmpdir, 'test_b.far')\n FLAGS.outputs = 'a=' + filename_a + ',b=' + filename_b\n with self.assertRaises(SystemExit):\n multi_grm.run(generator_method)\n\n stored_fst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matches if all of the given matchers are satisfied by any elements of the sequence.
def has_items(*items): matchers = [] for item in items: matchers.append(wrap_matcher(item)) return IsSequenceContainingEvery(*matchers)
[ "def any_of(*args):\n class AnyOfMatcher:\n def __init__(self, values):\n self.values = values\n\n def __eq__(self, other):\n return any(map(lambda v: v == other, self.values))\n\n def __ne__(self, other):\n return all(map(lambda v: v != other, self.values))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the access_window of this PopSettings. The range of messages which are accessible via POP.
def access_window(self): return self._access_window
[ "def access_window(self, access_window):\n allowed_values = [\"accessWindowUnspecified\", \"allMail\", \"disabled\", \"fromNowOn\"]\n if access_window not in allowed_values:\n raise ValueError(\n \"Invalid value for `access_window` ({0}), must be one of {1}\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the access_window of this PopSettings. The range of messages which are accessible via POP.
def access_window(self, access_window): allowed_values = ["accessWindowUnspecified", "allMail", "disabled", "fromNowOn"] if access_window not in allowed_values: raise ValueError( "Invalid value for `access_window` ({0}), must be one of {1}" .format(access_wind...
[ "def access_settings(self, access_settings):\n\n self._access_settings = access_settings", "def set_window(window):\n LimitQueue.set_window(window)\n CooccurrenceLimiter.set_window(window)", "def set_window(self, window):\n self._window = window", "def access(self, access):\n\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the disposition of this PopSettings. The action that will be executed on a message after it has been fetched via POP.
def disposition(self): return self._disposition
[ "def disposition(self, disposition):\n allowed_values = [\"archive\", \"dispositionUnspecified\", \"leaveInInbox\", \"markRead\", \"trash\"]\n if disposition not in allowed_values:\n raise ValueError(\n \"Invalid value for `disposition` ({0}), must be one of {1}\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the disposition of this PopSettings. The action that will be executed on a message after it has been fetched via POP.
def disposition(self, disposition): allowed_values = ["archive", "dispositionUnspecified", "leaveInInbox", "markRead", "trash"] if disposition not in allowed_values: raise ValueError( "Invalid value for `disposition` ({0}), must be one of {1}" .format(disposit...
[ "def disposition(self):\n return self._disposition", "def set_Disposition(self, value):\n super(WriteLocationDataInputSet, self)._set_input('Disposition', value)", "def body_disposition(self, msg):\n # If we have a content-disposition\n #\n if 'content-disposition' in msg:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the urls already in the correct order, downloads each image into the given directory. Gives the images local filenames img0, img1, and so on. Creates an index.html in the directory with an img tag to show each local image file. Creates the directory if necessary.
def download_images(img_urls, dest_dir): # Creating the directory if the directory does not already exist if not os.path.exists(str(dest_dir)): os.mkdir(dest_dir) print ('Retrieving...') with open(str(dest_dir) + '/index.html', 'w') as f: f.write("<html>\n<body>\n") for index, ur...
[ "def download_images(img_urls, dest_dir):\n index_content_start = \"<verbatim><html><body>\"\n index_content_end = \"</body></html>\"\n index_img_content = ''\n if not (os.path.exists(dest_dir)):\n os.mkdir(dest_dir)\n else:\n print 'dir exists already'\n i = 0\n for url in img_urls:\n print url\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse args, scan for urls, get images from urls
def main(args): parser = create_parser() if not args: parser.print_usage() sys.exit(1) parsed_args = parser.parse_args(args) img_urls = read_urls(parsed_args.logfile) if parsed_args.todir: download_images(img_urls, parsed_args.todir) else: print('\n'.join(img_...
[ "def main(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value\n parser = argparse.ArgumentParser()\n image = argparse.ArgumentParser()\n parser.add_argument(\"action\", choices=[\"image\", \"sources\"])\n\n image.add_argument('-d', '--download',\n help='Download the resu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a yaml file and adds line numbers to the objects
def load_yaml_with_lines(config): try: # Source: https://stackoverflow.com/a/13319530 loader = yaml.Loader(config) def compose_node(parent, index): # the line number where the previous token has ended (plus empty lines) line = loader.line node = Composer....
[ "def parse_yaml_linenumbers(data):\n loader = yaml.Loader(data)\n\n def compose_node(parent, index):\n # the line number where the previous token has ended (plus empty lines)\n line = loader.line\n node = Composer.compose_node(loader, parent, index)\n node.__line__ = line + 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare the sequences used by the Neural Network
def prepare_sequences(notes, n_vocab): sequence_length = 50 # get all pitch names pitchnames = sorted(set(item for item in notes)) # create a dictionary to map pitches to integers note_to_int = dict((note, number) for number, note in enumerate(pitchnames)) network_input = [] network_outp...
[ "def prepare_sequences(notes, sequence_len, translator):\n\n network_input = []\n network_labels = []\n\n # create input sequences and the corresponding outputs\n for i in range(0, len(notes) - sequence_len - 1, 1):\n X = notes[i:i + sequence_len]\n y = notes[i+1: i+1 + sequence_len]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add last layer to the convnet
def add_new_last_layer(base_model, nb_classes): x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(FC_SIZE, activation='relu')(x) #new FC layer, random init predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer model = Model(inputs=base_model.input, outputs=predi...
[ "def add_new_last_layer(base_model, nb_classes):\r\n x = base_model.output\r\n x = GlobalAveragePooling2D()(x)\r\n x = Dense(fc_size, activation='relu')(x) #new FC layer, random init\r\n predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer\r\n model = Model(inputs=base_model.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes an item from a multidict key.
def remove_from_multidict(d: MultiDict, key: str, item: typing.Any): # works by popping all, removing, then re-adding into i = d.popall(key, []) if item in i: i.remove(item) for n in i: d.add(key, n) return d
[ "def _RemoveKeys(self, item, key_set):\r\n if isinstance(item, dict):\r\n for key, value in item.items():\r\n if key in key_set:\r\n del item[key]\r\n else:\r\n self._RemoveKeys(value, key_set)\r\n elif isinstance(item, list):\r\n for value in item:\r\n self._R...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Base64ifys an image to send to discord.
def base64ify(image_data: bytes): # Convert the avatar to base64. mimetype = imghdr.what(None, image_data) if not mimetype: raise ValueError("Invalid image type") b64_data = base64.b64encode(image_data).decode() return "data:{};base64,{}".format(mimetype, b64_data)
[ "def b64_image(self) -> bytes:\n buffer = BytesIO()\n self.image.save(buffer, \"PNG\") \n im_b64 = base64.b64encode(buffer.getvalue())\n im_b64 = b\"data:image/png;base64,\" + im_b64\n return im_b64", "def encode_image(raw):\n return base64.b64encode(raw).decode('utf-8'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a Discordformatted timestamp to a datetime object.
def to_datetime(timestamp: str) -> datetime.datetime: if timestamp is None: return if timestamp.endswith("+00:00"): timestamp = timestamp[:-6] try: return datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f") except ValueError: # wonky datetimes return d...
[ "def _pb_timestamp_to_datetime(timestamp):\n return (\n EPOCH +\n datetime.timedelta(\n seconds=timestamp.seconds,\n microseconds=(timestamp.nanos / 1000.0),\n )\n )", "def timestamp_to_datetime(timestamp):\n return datetime.datetime.fromtimestamp(timestamp /100...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverses the stack for an object of type ``t``.
def _traverse_stack_for(t: type): for fr in inspect.stack(): frame = fr.frame try: locals = frame.locals except AttributeError: # idk continue else: for object in locals.values(): if type(object) is t: ...
[ "def __call__(self, request, obj, stack):\n unconsumed = stack[:]\n while unconsumed:\n for consumer in self.lookup(obj):\n any_consumed, obj, unconsumed = consumer(\n request, obj, unconsumed)\n if any_consumed:\n notify(B...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subclasses an immutable builtin, providing method wrappers that return the subclass instead of the original.
def subclass_builtin(original: type): def get_wrapper(subclass, func): @functools.wraps(func) def __inner_wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) new = subclass(result) # copy the parent dataclass if we need to if 'paren...
[ "def __copy__(self):\n return type(self)(self.value)", "def __copy__(self, *arguments) -> 'Wrapper':\n new = type(self)(\n alternate=self.alternate,\n annotation=self.annotation,\n component=None,\n context=self.context,\n deactivate=self.deacti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract FASTQ filename and read header from Waden Sea FASTA headers.
def transform_fasta_header(fastaheader): fastq_source, read_header = fastaheader.split(" ", 1)[0].rsplit("_", 1) fastq_base = fastq_source.rsplit("_", 1)[0] return fastq_base, read_header
[ "def fasta_headers(file_name):\n with open(file_name, 'r') as infile:\n text = infile.read()\n seqs = text.split('>')[1:]\n header = []\n for seq in seqs:\n try:\n x = seq.split('\\n', 1)\n header.append(x[0])\n except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a pair of complete fastq filenames for fastq_base.
def fastq_filename(fastq_base): return fastq_base+"_1.fastq", fastq_base+"_2.fastq"
[ "def fastqc_output(fastq):\n base_name = \"%s_fastqc\" % strip_ngs_extensions(os.path.basename(fastq))\n return (base_name,base_name+'.html',base_name+'.zip')", "def sample_name_from_fastq_paths(fastqs: List[str]) -> str:\n grouped_fastqs = group_fastqs(fastqs)\n for fastq_paths, sample_name in groupe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a query to find all summary entries for the given PDB.
def query(self, session, pdb): return session.query(mod.UnitInteractionSummary).\ filter_by(pdb_id=pdb)
[ "def query_summary(self):\n return self.details[KEY_QUERY_SUMMARY]", "def summary(self):\n for k,v in self.interactions.items():\n print(\"Found %s interactions within %s database\" % (len(v), k))\n\n counter = {}\n for k in self.interactions.keys():\n # scan each...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increment the count of the current bp. If the base pair is in `Loader.ignore_bp` we return the current counts.
def increment_bp(self, current, bp, crossing): if bp in self.ignore_bp: return current return self.increment(current, 'bps', bp, crossing)
[ "def get_num_calls(self):\n\t\treturn self.aa_count + self.ab_count + self.bb_count", "def inc_label(self):\n self.label_count += 1\n return self.label_count", "def increment_scan_point_count(self):\n self._scan_point_count += 1", "def base_count(self, base):\n cnt = {'N': 0, 'G': ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert the node n beginning at index position pos.
def insert(self, n, pos): if pos == 0: self.cons(n) else: prev = self.index(pos-1) next = prev.next prev.next = n n.next = next self.len += 1
[ "def insert(self, value, pos):\r\n\r\n if self.head is None:\r\n self.head = Node(value)\r\n return\r\n\r\n if pos == 0:\r\n self.prepend(value)\r\n return\r\n\r\n index = 0\r\n node = self.head\r\n while node.next and index <= pos:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append the node n to the end of the list.
def append(self, n): last = self.last() if last: last.next = n self.len += 1 else: self.cons(n)
[ "def append_at_postition(self, data, n):\n lenght = self.lenght()\n if n > lenght:\n return\n node = Node(data)\n ''' head-> node1 -> node2 -> node3 -> node4 -> node5\n '''\n # store the head\n temp = self.head\n\n # if the postion is the start\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start a cluster which should be in stopped status currently.
def cluster_start(r): cluster_id = request_get(r, "cluster_id") if not cluster_id: logger.warning("No cluster_id is given") return make_fail_response("No cluster_id is given") if cluster_handler.start(cluster_id): return jsonify(response_ok), CODE_OK return make_fail_response("c...
[ "async def start_cluster(self):\n raise NotImplementedError", "def test_stop_start_cc(self):\n self.createContainerCluster()\n \n self.assertEqual(True, self.stopCluster())\n \n self.assertEqual(True, self.startCluster())", "def start_cluster(self):\n \n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop a cluster which should be in running status currently.
def cluster_stop(r): cluster_id = request_get(r, "cluster_id") if not cluster_id: logger.warning("No cluster_id is given") return make_fail_response("No cluster_id is given") if cluster_handler.stop(cluster_id): return jsonify(response_ok), CODE_OK return make_fail_response("clu...
[ "async def stop(self):\n self.log.info(f'Stopping cluster with name {self.clustername()}')\n if await self.exists(self.clustername()):\n result = self.dataproc_client.delete_cluster(\n project_id=self.project,\n region=self.region,\n cluster_name=self.clustername())\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply a cluster. Return a Cluster json body.
def cluster_apply(r): request_debug(r, logger) user_id = request_get(r, "user_id") if not user_id: logger.warning("cluster_apply without user_id") return make_fail_response("cluster_apply without user_id") allow_multiple, condition = request_get(r, "allow_multiple"), {} consensus_...
[ "def cluster(self, text):\n body = {'text': text}\n body = json.dumps(body)\n url = self.base_url + '/ml-service/phoenix-ml/cluster'\n headers = {\"ApiKey\": self.api_key, \"Content-type\": \"application/json\"}\n response = requests.post(url=url, data=body, headers=headers)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Release a cluster which should be in used status currently.
def cluster_release(r): cluster_id = request_get(r, "cluster_id") if not cluster_id: logger.warning("No cluster_id is given") return make_fail_response("No cluster_id is given") if cluster_handler.release_cluster(cluster_id): return jsonify(response_ok), CODE_OK return make_fail...
[ "def delete_cluster(self):", "def assignToCluster(self, cluster):\n self.cluster = cluster", "def destroy(self, log_level=\"DEBUG\"):\n try:\n cluster_details = ocm.get_cluster_details(self.cluster_name)\n cluster_id = cluster_details.get(\"id\")\n delete_status = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Issue some operations on the cluster. e.g., /cluster_op?action=apply&user_id=xxx will apply a cluster for user
def cluster_actions(): request_debug(r, logger) action = request_get(r, "action") logger.info("cluster_op with action={}".format(action)) if action == "apply": return cluster_apply(r) elif action == "release": return cluster_release(r) elif action == "start": return clust...
[ "def cluster_apply(r):\n request_debug(r, logger)\n\n user_id = request_get(r, \"user_id\")\n if not user_id:\n logger.warning(\"cluster_apply without user_id\")\n return make_fail_response(\"cluster_apply without user_id\")\n\n allow_multiple, condition = request_get(r, \"allow_multiple\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse and return number of incidents by day of the week
def fetch_incident_by_days(parsed_data): incident_counter = dict() for incident in parsed_data: day_of_week = incident['DayOfWeek'] if day_of_week in incident_counter: incident_counter[day_of_week] += 1 else: incident_counter[day_of_week] = 1 return incident...
[ "def weekdays(frame):\n\n data = pd.DataFrame()\n data['weekday'] = pd.DatetimeIndex(frame.inserted).weekday\n counts = pd.DataFrame(np.arange(7)*0)\n return (counts[0]+data.weekday.value_counts()).fillna(0)", "def compute_heatsum_per_week(heatsum_day, day=5):\n heatsum_week = {}\n for k in heat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse and return count of total incidents and unresolved incidents by category
def fetch_incident_by_category_and_resolution(parsed_data): incident_counter = dict() for incident in parsed_data: category = incident['Category'] resolution = incident['Resolution'] if category in incident_counter: incident_counter[category][0] += 1 if resolutio...
[ "def count_risk_categories(data):\n results = Counter([row['risk_category'] for row in data])\n if '' in results:\n results['No Violations'] = results['']\n del results['']\n return results", "def fetch_incident_by_days(parsed_data):\n incident_counter = dict()\n\n for incident in par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the given metadata has correct types for all its members.
def check_metadata(metadata): message = 'The given metadata contains unsupported types.' assert all([item['type'] in ['category', 'value'] for item in metadata['details']]), message
[ "def check_members(self):\r\n\r\n if self.members.__len__() < self.require_member:\r\n raise TypeError(f\"Need at least {self.require_member} members\")\r\n\r\n for x in self.members:\r\n if not (isinstance(x, int) or isinstance(x, float)):\r\n raise TypeError(\"On...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate inputs for functions whose first argument is a numpy.ndarray with shape (n,1).
def check_inputs(function): def decorated(self, data, *args, **kwargs): if not (isinstance(data, np.ndarray) and len(data.shape) == 2 and data.shape[1] == 1): raise ValueError('The argument `data` must be a numpy.ndarray with shape (n, 1).') return function(self, data, *args, **kwargs) ...
[ "def check_input_shapes(*args):\n\n # Collect the shapes of the inputs\n shapes = set()\n\n # DESIGN NOTES - currently allow:\n # - scalars,\n # - 0 dim ndarrays (also scalars but packaged differently)\n # - 1 dim ndarrays with only a single value\n\n for val in args:\n if isinstan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Listener will be called every second with the number of seconds passed since cog load
async def on_timer_update(self, secs: int): pass
[ "def on_tick(self):\n pass", "def realtime(self):", "def onTimer(self, id, userArg):", "def timer_handler():\r\n \r\n global elapsed_time\r\n elapsed_time += 1", "def time_automation_listener(now):\n action()", "def every100ms():\r\n pass", "def stats_timer(self):\n\n LC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inject the edition tools into the html content and return a BeautifulSoup object of the resulting content + tools.
def inject_edition_tools(response, request=None, context=None, body_top_template_name="pages/_body_top.html", body_bottom_template_name="pages/_body_bottom.html", edit_frame_template_name=None): #pylint:disable=too-many-arguments content...
[ "def add_edition_tools(self, content, context=None):\n if context is None:\n context = {}\n context.update(csrf(self.request))\n template = loader.get_template(self.edition_tools_template_name)\n soup = BeautifulSoup(content)\n if soup and soup.body:\n soup.b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that model= is optional for abstract=True.
def test_factory_for_optional(self): class TestObjectFactory(base.Factory): class Meta: abstract = True self.assertTrue(TestObjectFactory._meta.abstract) self.assertIsNone(TestObjectFactory._meta.model)
[ "def is_abstract_model(model):\n has_meta_attribute = hasattr(model, '_meta')\n is_abstract = hasattr(model._meta, 'abstract') and model._meta.abstract\n return has_meta_attribute and is_abstract", "def test_abstract_attribute_is_not_inherited(self):\r\n assert not ConcreteModel.__abstract__\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the sequence of a 'slave' factory cannot be reset.
def test_reset_sequence_subclass_fails(self): class SubTestObjectFactory(self.TestObjectFactory): pass with self.assertRaises(ValueError): SubTestObjectFactory.reset_sequence()
[ "def test_slaveof(self):\n self.assertEqual(redismod.slaveof(\"master_host\", \"master_port\"), \"A\")", "def reset_slave():\n\n # Confirm slave status in case we need to refer to the values later\n slave_status()\n run_mysql_command(\"STOP SLAVE;\")\n\n with hide('everything'):\n # Stor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that reset_sequence(force=True) works.
def test_reset_sequence_subclass_force(self): class SubTestObjectFactory(self.TestObjectFactory): pass o1 = SubTestObjectFactory() self.assertEqual(0, o1.one) o2 = SubTestObjectFactory() self.assertEqual(1, o2.one) SubTestObjectFactory.reset_sequence(force=...
[ "def reset_sequence(self):\n self.sequence = []", "def soft_reset() -> NoReturn:", "def test_reset(self):\n ran = []\n def foo():\n ran.append(None)\n\n c = task.Clock()\n lc = TestableLoopingCall(c, foo)\n lc.start(2, now=False)\n c.advance(1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`.
def queryset(self, request, queryset): # Compare the requested value (either '80s' or 'other') # to decide how to filter the queryset. if self.value() is None: return queryset.all() return queryset.filter(firm__pk=self.value())
[ "def queryset(self, request, queryset):\n # Compare the requested value (either '80s' or '90s')\n # to decide how to filter the queryset.\n if self.value():\n queryset = queryset.filter(data_path__contains=self.value())\n return queryset", "def queryset(self, request, querys...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
inserts player name and score to top5 db
def insert_player(self, name, score): command = "UPDATE %s " % self.table_name_players command += "SET name_player = '%s', score = %d " % (name, score) command += "WHERE name_player = ( " command += "SELECT name_player " command += "FROM %s " % self.table_name_players ...
[ "async def input_solo_game(self, score : int):\r\n async with self.db.acquire() as conn:\r\n psql = \"\"\"\r\n INSERT INTO solo_wins (player, score)\r\n VALUES ($1, $2)\r\n \"\"\"\r\n await conn.execute(psql, self.host.id, score)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a delta between the initial statistics and the final one
def _deltas(self): istat = self.init lstat = self.stats uptime = self._uptime() delta = float(uptime) - float(self.uptime) self.uptime = uptime for dev in lstat.keys(): if not istat.has_key(dev): del lstat[dev] ...
[ "def testDelta(self):\r\n delta = counters._DeltaCounter('mydelta', 'Description')\r\n sampler = delta.get_sampler()\r\n sampler2 = delta.get_sampler()\r\n\r\n self.assertEqual(0, sampler())\r\n\r\n delta.increment()\r\n self.assertEqual(1, sampler())\r\n\r\n delta.increment(4)\r\n self.asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search text for [[link_me]], replace with link_me
def wiki_link(text): return wiki_link_pattern.sub(get_link, text)
[ "def convert_simple_links(text):\n for m in re.finditer(r\"\\[(.*?)]\\(\\)\", text):\n text = text.replace(m.group(0), \"[{link}]({link})\".format(link=m.group(1)))\n return text", "def extractLinks(text: str) -> LinkedText: \n formattedText = LinkedText(text)\n contador = 1\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Función desencripta, lee cada caracter línea por línea y lo reemplaza según el desplazamiento indicado.
def desencripta(linea, desplaza): linea_encriptada = "" letras = string.ascii_letters + "áéíóúñÁÉÍÓÚÑ" for c in linea: if c in letras: pos_donde_esta = letras.index(c) pos_c_desencriptado = (pos_donde_esta - desplaza) % len(letras) if pos_c_desencriptado < 0: ...
[ "def intercambiar_mayusculas_minusculas(cad):\n\n nueva_cad = \"\"\n\n for i in cad:\n if ord(i) < 64 or ord(i) > 122:\n nueva_cad = nueva_cad + i\n elif ord(i) < 97:\n nueva_cad = nueva_cad + chr(ord(i) + 32)\n else:\n nueva_cad = nueva_cad + chr(ord(i) -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle updating an object by its ID
def update(self, request, pk=None): #update a specific object return Response({'http_method': 'PUT'})
[ "def update_item(id: str, obj: endpoint_model):\n # should this error if exists?\n if obj.id:\n if obj.id != id:\n raise HTTPException(status_code=400, detail=\"id in body does not match id in path\")\n else:\n obj.id = id\n new_obj = db.save(obj)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle updating part of an object by its ID
def partial_update(self, request, pk=None): #partial update a specific object return Response({'http_method': 'PATCH'})
[ "def update_item(id: str, obj: endpoint_model):\n # should this error if exists?\n if obj.id:\n if obj.id != id:\n raise HTTPException(status_code=400, detail=\"id in body does not match id in path\")\n else:\n obj.id = id\n new_obj = db.save(obj)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Purge all completed exports from the backing IHS remote account
def exports(): from celery_queue.tasks import cleanup_remote_exports cleanup_remote_exports.run()
[ "def cleanup(self):\n files = self.nlst()\n latest = self.latest_filename\n for filename in files:\n if filename != latest:\n result = self.delete(filename)\n logger.info(f\"Deleted old export from FTP: {result}\")", "def clear_all_jobs(self):\n pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the faller to the left Won't move left if there are jewels in the way check piece to left if it is zero, if it is then you can move left
def move_left(self): counter = 0 for y in range(1, self._col): for x in reversed(range(self._row)): if '[' in self._board[x][y] and self._board[x][y-1] == ' ': counter += 1 elif '|' in self._board[x][y] and self._board[x][y-1] == ...
[ "def moveLeft(self):\n self._piece.move(-(WINDOW_WIDTH) / 16, 0)", "def move_left(self):\n if self.grid_pos_x == 0:\n self.grid_pos_x = self.grid_column_len - 1\n self.x_pos = self.grid_column_len\n\n self.grid[self.grid_pos_y][0] = self.tile_symbol\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loading directory with no courses gives only an empty "lessons" course
def test_no_courses(): model = models.Root() model.load_local_courses(fixture_path / 'empty-lessons-dir') assert sorted(model.courses) == ['lessons'] assert not model.courses['lessons'].sessions assert not model.courses['lessons'].lessons
[ "def load_online_courses():\n br.open('http://moodle.iitb.ac.in/')\n\n for link in br.links(url_regex='http://moodle.iitb.ac.in/course/view.php'):\n online_courses.append(CourseObject(link.url, link.text))", "def test_course_index_view_with_no_courses(self):\r\n # Create a course s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all methods inside the Pizza class.
def test_pizza_class(): # __init__() small = MenuItem("Small", "Pizza size", False, 0.0, 1) medium = MenuItem("Medium", "Pizza size", False, 4.0, 1) topping1 = MenuItem("Extra cheese", "Topping", False, 2.0, 1) topping2 = MenuItem("Special sauce", "Topping", False, 3.0, 1) pizza_menu_item1 = Men...
[ "def test_get_food(self):\n pass", "def test_required_methods(self):", "def run_test_pour():\n\n print()\n print('-----------------------------------------------------------')\n print('Testing the pour method of the CoffeePot class.')\n print('---------------------------------------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all methods inside the Drink class.
def test_drink_class(): # __init__() default_size = MenuItem("Small size", "Drink size", False, 0.0, 1) size_upgrade = MenuItem("Medium size", "Drink size", False, 1.0, 1) drink_menu_item1 = MenuItem("Coca Cola", "Drinks", True, 1.0, 1) drink_menu_item2 = MenuItem("Fanta", "Drinks", True, 1.5, 1) ...
[ "def test_get_food(self):\n pass", "def test_required_methods(self):", "def test_post_foods(self):\n pass", "def setUp(self) -> None:\n print(\"testing Deaths Class...\")\n self.data_handler_1 = self._init_mocked_data_handler(json_file_path=\"json_files/deaths_mocked_data.json\",\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all methods inside the Side class.
def test_side_class(): # __init__() side_menu_item1 = MenuItem("Fries", "Sides", True, 4.0, 1) side_menu_item2 = MenuItem("Salad", "Sides", True, 3.0, 1) side1 = Side(side_menu_item1) side2 = Side(side_menu_item2) side3 = Side(side_menu_item1) # Getter methods assert side1.get_sauces() =...
[ "def test_required_methods(self):", "def testing(self):", "def test_methods(self):\n\n methods = filter(lambda m: m[0] != '_', dir(Cassandra.Iface))\n\n real_client = Generic()\n\n @contextmanager\n def get_client():\n yield real_client\n\n client = self._client(['1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all methods inside the ItemFactory class.
def test_item_factory_class(): # __init__() factory = ItemFactory() pizza_menuitem = MenuItem("cheese", "Pizzas", True, 10.0, 1) drink_menuitem = MenuItem("fanta", "Drinks", True, 10.0, 1) side_menuitem = MenuItem("fries", "Sides", True, 10.0, 1) none_menuitem = MenuItem("oreo", "oreo", True, 10...
[ "def test_create_item(self):\n item = self.item\n\n self.assertTrue(isinstance(item, Item))\n self.assertEqual(item.name, \"Test Item\")", "def test_get_items_peas_get(self):\n pass", "def test_get_items(self):\n user = UserFactory.get_user()\n client = self.get_auth_cl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests methods of all Delivery subclasses.
def test_delivery_subclasses(): # Start with UberEatsDelivery class # __init__() order = Order(1) fries = MenuItem("fries", "Sides", True, 5.00, 1) order.add_to_cart(fries) uber_eats = UberEatsDelivery(order, "Test1.json") deliver_error = UberEatsDelivery(order, "FileDoesNotExist.jsdson") ...
[ "def test_delivery_factory_class():\n # __init__()\n factory = DeliveryFactory()\n order = Order(1)\n file = \"This is a file.\"\n\n expected_uber = UberEatsDelivery(order, file)\n expected_foodora = FoodoraDelivery(order, file)\n expected_delivery = Delivery(order, \"not uber or foodora\")\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all methods in DeliveryFactory class.
def test_delivery_factory_class(): # __init__() factory = DeliveryFactory() order = Order(1) file = "This is a file." expected_uber = UberEatsDelivery(order, file) expected_foodora = FoodoraDelivery(order, file) expected_delivery = Delivery(order, "not uber or foodora") assert factory....
[ "def test_delivery_subclasses():\n # Start with UberEatsDelivery class\n # __init__()\n order = Order(1)\n fries = MenuItem(\"fries\", \"Sides\", True, 5.00, 1)\n order.add_to_cart(fries)\n uber_eats = UberEatsDelivery(order, \"Test1.json\")\n deliver_error = UberEatsDelivery(order, \"FileDoesN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test pizza parlour's read from file.
def test_parlour_one(): menu = 'Here is our menu:\nPizzas:\n\tMargherita: $10.99\n\t' \ 'Pepperoni: $12.99\nDrinks:\n\tSprite: $2.99\n\tPepsi: $3.99\n' \ 'PizzaSizes:\n\tSmall: $0.00\n\tMedium: $3.99\n\tLarge: $6.99\n' \ 'DrinkSizes:\n\tSmall: $0.00\n\tMedium: $2.99\n\tLarge: $4.99\...
[ "def read_input_pizza(filename):\n lines = open(filename).readlines()\n R, C, L, H = [int(val) for val in lines[0].split()]\n pizza = np.array([list(map(lambda item: 1 if item == 'T' else 0, row.strip())) for row in lines[1:]])\n return R, C, L, H, pizza", "def ReadInputFile(file:int)->EvenMorePizza:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given t, returns BWT(t) by way of the BWM
def bwtViaBwm(t): BWT= ''.join(map(lambda x:x[-1], bwm(t))) return BWT
[ "def m2_weight(t):\n return integrate.quad(lambda x: x*x * bethe_dos(x, t), -2*t, 2*t)[0]", "def calc_wetbulb_temperature(t, td, p=P0_, eps=1e-8, n=10):\n\n \"\"\"\n Options:\n * A Start with the 1/3-rule for wet-bulb.\n * B Start with wet-bulb = dry-bulb\n B has better overall convergence\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans up the current state of the GUI by closing any open models and motion files.
def cleanUp(self): # Close any open models openModels = getAllModels() if len(openModels): for model in openModels: setCurrentModel(model) performAction("FileClose") # Wait time.sleep(1)
[ "def cleanup(self):\n if self.options != None:\n self.options.Free()\n ida_kernwin.hide_wait_box()\n self.close_xmlfile()", "def clean_gui():\n pass", "def destructor(self):\n print(\"[INFO] closing...\")\n self.window.destroy()\n self.vs.release() # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the adjusted COM model for the chosen trial into the GUI.
def loadAdjustedModel(self): # Load model in GUI addModel(self.trcFilePath.replace('.trc','.osim'))
[ "def autopilot(self, model, graph):\n self.model = model\n self.graph = graph\n self.model_loaded = True\n print('Vehicle ready.')", "def _load_model(self):\n pass", "def load_model(self):\n\n # First we eliminate the existing elements of the solar cell list\n self.clear_solar_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }