query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Click the ``Confirm`` button and cancel the dialog.
def cancel(self): with self.handle_alert(confirm=False): self.q(css='button#confirm').first.click()
[ "def confirm(self):\n with self.handle_alert(confirm=True):\n self.q(css='button#confirm').first.click()", "def confirm_cancel(self, button):\n if not self.confirm_window_open:\n raise Exception('confirmation window is not open')\n self.confirm_buttons.find_buttons()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of div.test elements.
def num_divs(self): return len(self.q(css='div.test').results)
[ "def count_tests(self):\n return sum(1 for test in test_list_repr(self.context[0].testlist) if test.get('test_type') == 'test')", "def test_number_of_testcase_elements(self):\n testcases = self.root.findall('testcase')\n self.assertEqual(len(testcases), 4)", "def test_count(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of text for each div.test element.
def div_text_list(self): return self.q(css='div.test').text
[ "def div_html_list(self):\n return self.q(css='div.test').html", "def _get_text(self, element):\n # for text in element.itertext():\n for text in self.iter_main_text(element):\n yield text.strip()", "def list():\n tests = getTestList()\n print \"Available tests:\"\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of values for each div.test element.
def div_value_list(self): return self.q(css='div.test').attrs('value')
[ "def div_text_list(self):\n return self.q(css='div.test').text", "def div_html_list(self):\n return self.q(css='div.test').html", "def get_elements(self):\n\t\treturn self._testing_cache", "def list():\n tests = getTestList()\n print \"Available tests:\"\n for test in tests:\n pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of html for each div.test element.
def div_html_list(self): return self.q(css='div.test').html
[ "def div_text_list(self):\n return self.q(css='div.test').text", "def div_value_list(self):\n return self.q(css='div.test').attrs('value')", "def list():\n tests = getTestList()\n print \"Available tests:\"\n for test in tests:\n print test", "def _build_tests_list_helper(self, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of the ids of outer divs with the specified text in a child element.
def ids_of_outer_divs_with_inner_text(self, child_text): return self.q(css='div.outer').filter( lambda el: child_text in [inner.text for inner in el.find_elements_by_css_selector('div.inner')] ).attrs('id')
[ "def find_elements_by_text(self, text):\n # XPATH have to be string in Python 2 and unicode in Python 3.\n text = force_text(text)\n if not six.PY3:\n text = text.encode('utf8')\n elms = self.find_elements_by_xpath(\n './/*/text()[contains(., \"{}\") and not(ancesto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait for click handlers to be installed, then click a button and retrieve the output that appears after a delay.
def trigger_output(self): EmptyPromise(self.q(css='div#ready').is_present, "Click ready").fulfill() self.q(css='div#fixture button').first.click() EmptyPromise(self.q(css='div#output').is_present, "Output available").fulfill()
[ "def background_and_wait(self):\n return self.wait_for_click()", "def wait_until_insurance_displayed(self):", "def wait_for_click():\r\n global _canvas\r\n global _cue\r\n if _canvas == None:\r\n raise RuntimeError(\"Canvas is not open yet.\")\r\n else:\r\n while True:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a promise that will not be fulfilled. Should raise a `BrokenPromise` exception.
def make_broken_promise(self): return EmptyPromise( self.q(css='div#not_present').is_present, "Invalid div appeared", try_limit=3, try_interval=0.01 ).fulfill()
[ "def rejected(reason):\n p = Promise()\n p._state = \"rejected\"\n p.reason = reason\n return p", "def test_willNotAllowNonDeferredOrCoroutine(self):\n with self.assertRaises(ValueError):\n defer.ensureDeferred(\"something\")", "def reject(self, reason):\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the page named `page_name` after waiting for `delay_sec`.
def load_next(self, page, delay_sec): time.sleep(delay_sec) page.visit()
[ "def load_page(self, url: str):\n self.__driver.get(url)\n sleep(SLEEP_LONG_TIME)", "def wait(self, url):\r\n domain = urlsplit(url).netloc\r\n last_accessed = self.domains.get(domain)\r\n if self.delay > 0 and last_accessed is not None:\r\n sleep_secs = self.delay - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Give focus to the element with the ``maincontent`` ID.
def focus_on_main_content(self): self.browser.execute_script("$('#main-content').focus()")
[ "def onMnemoToMain(self):\n self.second_main_text.SetFocus()", "def _focus(self, element):\n actions = ActionChains(self.selenium.driver)\n actions.move_to_element(element).click().perform()\n self.selenium.set_focus_to_element(element)", "def giveFocus(self):\r\n self.focus =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reload the page, wait for JS, then trigger the output.
def reload_and_trigger_output(self): self.browser.refresh() self.wait_for_js() # pylint: disable=no-member self.q(css='div#fixture button').first.click()
[ "def reload_webpage(browser):\n browser.execute_script(\"location.reload()\")\n update_activity()\n sleep(2)\n\n return True", "def refresh_page(self):\n self.m_driver.refresh()\n time.sleep(30)", "def reload_content(self):\n pass", "def reloadContent(self):\n\n self._s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click button and wait until playing class disappeared from DOM
def is_class_absent(self): self.q(css='#spinner').first.click() self.wait_for_element_absence('.playing', 'Animation Stopped')
[ "def poll(self):\n\tself.met = self.button.poll()", "def wait_for_button(self, button, message=True):\n if message:\n rospy.loginfo(\"Waiting for xbox button: \" + button)\n \n wait_for(lambda: not self.get_button(button) == 0)", "def _check_play_button(self, mouse_pos):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click button and wait until spinner is disappeared.
def is_spinner_invisible(self): self.q(css='#spinner').first.click() self.wait_for_element_invisibility('#anim', 'Button Output is Visible')
[ "def wait_until_insurance_displayed(self):", "def wait_for_button(self, button, message=True):\n if message:\n rospy.loginfo(\"Waiting for xbox button: \" + button)\n \n wait_for(lambda: not self.get_button(button) == 0)", "def poll(self):\n\tself.met = self.button.poll()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if value is prime
def is_prime(value: int) -> bool: if value == 1: return False if value <= 0: raise ValueError("Value must be greater than zero") for i in range(2, int(value**(1/2)) + 1): if value % i == 0: return False return True
[ "def is_prime(num: int) -> bool:\n pass", "def is_prime(self):\n\n vroot = int(self.value ** 0.5) + 1\n for i in range(3, vroot, 2):\n if self.value % i == 0:\n return False\n return True", "def is_prime(val):\n if val == 2:\n return True\n if val %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all prime factors of the given value
def factors(value: int) -> list: prime_factors: list = [] for i in range(2, value + 1): if i > 2 and i % 2 == 0 or not is_prime(i): continue while value % i == 0: value = int(value / i) prime_factors.append(i) if value == 1: break ...
[ "def prime_factors(value):\n\n checkutils.check_instance(int, value, 'positive ')\n checkutils.check_nonnegative(value)\n\n if value < 4:\n return [value]\n\n ret = list()\n for prime in primes:\n if value == 1:\n assert len(ret) > 0\n return ret\n while val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets up the connection. Will optionally accept a size or else will use a chunked TransferEncoding.
def setup(self, size=None): if size: self.size = size if not self.size: self.size = UNKNOWN_LENGTH self.body.length = self.size req = self.conn.make_request('PUT', self.url, headers=self.headers, ...
[ "def enable_chunked_encoding(self, chunk_size: Optional[int] = ...) -> None:\n ...", "def setup_connection(self):\n if self.conn:\n self.conn.close()\n self.buffer = ''\n self.conn = pycurl.Curl()\n self.conn.setopt(pycurl.URL, API_ENDPOINT_URL)\n self.conn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a chunk of data.
def send_chunk(self, chunk): print "ChunkedTwistedConnection: send chunk" return self.body.send(chunk)
[ "def send_chunk(chunk, send_socket):\n length = len(chunk)\n data = str(length).zfill(MAX_CHUNK_SIZE).encode() + chunk\n send_socket.send(data)", "def send_byte_data(self, data):\n data_len = len(data)\n print(\"Data is of length \",)\n n_blocks = int(data_len//1024 if da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the distance and rotation to the edge of the desk
def getDistanceAndRotationToEdge(l, f, r): if DEBUG: print "lfr:", l,",",f,",",r # Maths help from: http://xaktly.com/MathNonRightTrig.html # - Specfically the law of cosines, but at least one of their # examples is wrong, but methods are correct... sigh. # # For triangle with forwar...
[ "def calculate_distance_edge(self):\n if self.mu > 0:\n # right interface is intersected next\n dx = self.cell_xr - self.x\n self.next_cell_index = self.cell_index + 1\n else:\n # left interface is intersected next\n dx = self.cell_xl - self.x\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a value break it down by the ilk of node (usb or pci), the vendor, and the device or product.
def parse_value(value: str) -> Tuple[str, str, str]: value_pattern = r'^(usb|pci)\(([^:]{4}):([^:]{4})\)$' matches = re.match(value_pattern, value) assert matches, value ilk, vendor, device = matches.group(1), matches.group(2), matches.group(3) return ilk, vendor, device
[ "def device_get_vendor(udev_info):\n return udev_info.get(\"ID_VENDOR_FROM_DATABASE\", udev_info.get(\"ID_VENDOR\"))", "def findVendor(self):\n if self.model in ['nokia39','nokia56','chkp40','chkp20','chkp120','chkp13']:\n return 'nokia'\n elif self.model in ['asa10','asa25','asa50','a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update_cmdb_item('sys', 'name', u'ATM 容灾', 'tkt78f0ad3d7dcf', 'ci549abda9', 'ci467b8875', cfg='TimeZone=Asia/Shanghai')
def update_cmdb_item(cfg_type, pk_name, pk_value, ticket_id, applicant, approve, **item): cfg_model = get_cfg_model_by_type(cfg_type) if cfg_model: kwargs = {pk_name: pk_value} instance = cfg_model.objects.get(**kwargs) if instance: ins, err = cfg_model.objects.update(instanc...
[ "def bala(update, context):\n update.message.reply_text(\"\"\"BALAKUMAR-191MC110\n MOBILE-8903220635\"\"\")", "def catalog_update_request(table_name: str, stac_item_key: str):\n\n get_client(\"dynamodb\").put_item(\n TableName=table_name,\n Item={\n \"stacitem\": {\"S\": stac_ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
I have some docs
def docs():
[ "def show_doc(self):\n pass", "def docs():\n return render_template(\"docs.html\")", "def apiDocs():\n\treturn render_template('apiDocs.html')", "def documento():\r\n\tpass", "def printdoc():", "def print_docs(self, docs: DocList) -> None:\n for doc in docs:\n print(f\"----...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LÊ arquivo de INDICES arquivoIndices.txt.
def lerArquivoIndices(indices): arq = open("arquivoIndices.txt", "r") linha = arq.readline() gravaIndices(indices, linha) while linha: linha = arq.readline() registro = gravaDados(indices, linha) arq.close() return
[ "def gravarArquivoIndices(indices):\n arq = open(\"arquivoIndices.txt\", \"w\")\n for i in indices.indices:\n linha = i.codigo + \",\" + str(i.indice) + \",\" + str(i.excluido) + \"\\n\"\n arq.write(linha)\n arq.close()\n return", "def _load_split_indices(self):\n split_file = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grava objetos em formato texto no arquivo de Indices.
def gravarArquivoIndices(indices): arq = open("arquivoIndices.txt", "w") for i in indices.indices: linha = i.codigo + "," + str(i.indice) + "," + str(i.excluido) + "\n" arq.write(linha) arq.close() return
[ "def __bert_text_to_index(self, file_path: str):\r\n data_ids = []\r\n data_types = []\r\n label_ids = []\r\n data_masks = []\r\n with open(file_path, 'r',encoding='UTF-8') as f:\r\n line_data_ids = []\r\n line_data_types = []\r\n line_label = []\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all row and column groups.
def get_regular_groups(self, grid, min=3): row_groups = self._get_row_groups(grid.grid, models.patterns.RowPattern, min) col_groups = self._get_row_groups(grid.grid.T, models.patterns.ColumnPattern, min) return row_groups + col_groups
[ "def genBlockGroups(self):\n \n try:\n \n byRow = byColumn = int(math.sqrt(self.groupSize))\n groupByRow = [] \n \n for row in range (self.rows):\n list = []\n for aux in range(self.columns/byColumn):\n list.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete acl in a secret.
def delete_acls_for_secret(cls, secret, session=None): session = cls.get_session(session=session) for entity in secret.secret_acls: entity.delete(session=session)
[ "def delete_secret(self, secret_id: str, project_id: Optional[str] = None):", "def delete_acl(self, sg):\n self.security_group_driver.delete_acl(sg)", "def delete(self, secret_name):\n with self.__client as client:\n return self.__exec_cmd(client, Command.DELETE, secret_name)", "def d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates a torch model so that input minibatches are parallelized across the batch dimension to utilise multiple gpus. If model parallel is set to True and execution is in test mode, then model is partitioned to perform full volume inference. This assumes the model has been created, that the optimizer has not yet been c...
def _adjust_for_gpus(cls, model: DeviceAwareModule, config: ModelConfigBase, model_execution_mode: ModelExecutionMode) -> DeviceAwareModule: if config.use_gpu: model = model.cuda() logging.info("Adjusting the model to use mixed precision training.") #...
[ "def initialize_model_parallel(model_parallel_size_):\n if torch.distributed.get_rank() == 0:\n print('> initializing model parallel with size {}'.format(\n model_parallel_size_))\n # Get world size and rank. Ensure some consistencies.\n assert torch.distributed.is_initialized()\n worl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a model (with temperature scaling) according to the config given.
def create_model(self) -> None: self._model = create_model_with_temperature_scaling(self.config)
[ "def create_model_with_temperature_scaling(config: ModelConfigBase) -> Any:\n # wrap the model around a temperature scaling model if required\n model = config.create_model()\n if isinstance(config, SequenceModelBase) and config.temperature_scaling_config:\n model = ModelWithTemperature(model, config...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the model summary, which is required for model partitioning across GPUs, and then moves the model to GPU with data parallel/model parallel by calling adjust_model_for_gpus.
def create_summary_and_adjust_model_for_gpus(self) -> None: if self._model is None: raise ValueError("Model must be created before it can be adjusted.") if self.config.is_segmentation_model: summary_for_segmentation_models(self.config, self._model) # Prepare for mixed pr...
[ "def _distribute_model(self):\n self.feature_extractor.cuda(1)\n self.feature_adapter.cuda(1)", "def model_to_gpu(self):\n # Multi-GPU\n if torch.cuda.device_count() >= 1:\n gpu_count = torch.cuda.device_count()\n for mname in self.model:\n self.mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an optimizer and loads its state from a checkpoint.
def try_create_optimizer_and_load_from_checkpoint(self) -> bool: self.create_optimizer() if self.checkpoint_path: return self.try_load_checkpoint_for_optimizer() return True
[ "def _load_optimizer(optimizer_config):\n logger.info(\"\\t Loading optimizer ...\")\n return create_tf_optimizer(optimizer_config)", "def create_optimizer(self) -> None:\n # Make sure model is created before we create optimizer\n if self._model is None:\n raise ValueError(\"Model c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a human readable summary of the present segmentation model, writes it to logging.info, and stores the ModelSummary object inside the argument `model`.
def summary_for_segmentation_models(config: ModelConfigBase, model: DeviceAwareModule) -> None: assert isinstance(model, BaseModel) crop_size = config.crop_size if isinstance(crop_size, int): crop_size = (crop_size, crop_size, crop_size) try: model.generate_model_summary(crop_size, log_s...
[ "def model_summary(model):\n summary = model.summary()\n return summary", "def print_model_summary():\n global model\n global model_name\n if validModel():\n \"\"\"textBrowser.append(\"\\nModel summary:\\n\")\n # print model summary to textbrowser\n stringlist = []\n mod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a model with temperature scaling by wrapping the result of config.create_model with ModelWithTemperature, if temperature scaling config has been provided, otherwise return the result of config.create_model
def create_model_with_temperature_scaling(config: ModelConfigBase) -> Any: # wrap the model around a temperature scaling model if required model = config.create_model() if isinstance(config, SequenceModelBase) and config.temperature_scaling_config: model = ModelWithTemperature(model, config.temperat...
[ "def create_model(self) -> None:\n self._model = create_model_with_temperature_scaling(self.config)", "def infer_temperature_model(self):\n temperature_model_parameters = tuple(\n array.temperature_model_parameters for array in self.system.arrays)\n params = _common_keys(temperatur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load twine from a .json filename, filelike or a json string and validates twine contents.
def _load_twine(self, source=None): if source is None: # If loading an unspecified twine, return an empty one rather than raising error (like in _load_data()) raw_twine = {} logger.warning("No twine source specified. Loading empty twine.") else: raw_twine ...
[ "def loadTweets(self, fileName):\n\t\tself.rawTweets = loadJSON(fileName)", "def load_json_fixture(filename: str) -> Any:\n return json.loads(load_fixture(f\"jellyfin/{filename}\"))", "def load_tweets(file):\n with open(file) as f:\n data = json.load(f)\n return data", "def test_load_json_str(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the schema for the given strand.
def _get_schema(self, strand): if strand == "twine": # The data is a twine. A twine *contains* schema, but we also need to verify that it matches a certain # schema itself. The twine schema is distributed with this packaged to ensure version consistency... schema_path = "sche...
[ "def getschema(self, indir='', schemaname=''):\n if schemaname not in self.registry:\n try:\n self.convert_schema(indir=indir, schemaname=schemaname)\n except IOError:\n pass\n outschema = self.registry.get(schemaname)\n return outschema", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that the installed version is consistent with an optional version specification in the twine file.
def _validate_twine_version(self, twine_file_twined_version): installed_twined_version = pkg_resources.get_distribution("twined").version logger.debug( "Twine versions... %s installed, %s specified in twine", installed_twined_version, twine_file_twined_version ) if (twine_fil...
[ "def require_version(self, version):", "def validate_configurator_version():\n if settings.CONFIGURATOR_MODULE == \"bootmachine.contrib.configurators.salt\":\n pkgver = settings.SALT_AUR_PKGVER\n pkgrel = settings.SALT_AUR_PKGREL\n response = urllib2.urlopen(\"https://aur.archlinux.org/pac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that all nonoptional datasets specified in the corresponding manifest strand in the twine are present in the given manifest.
def _validate_all_expected_datasets_are_present_in_manifest(self, manifest_kind, manifest): # This is the manifest schema included in the `twine.json` file, not the schema for `manifest.json` files. manifest_schema = getattr(self, manifest_kind) for expected_dataset_name, expected_dataset_schem...
[ "def check_manifest(manifest):\n if not manifest:\n raise Exception('manifest is null')\n\n for key in ['dublin_core', 'checking', 'projects']:\n if key not in manifest:\n raise Exception('manifest missing key \"{0}\"'.format(key))\n\n # check checking\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the names of strands that are found in this twine.
def available_strands(self): return self._available_strands
[ "def iter_strands(self):\n return iter(self.strand_list)", "def station_names(self):\n return self.stations.keys()", "def names(self):\n for wool in self.wools.items():\n yield wool.name", "def stations_names_list(self):\n return [station[\"station_name\"] for station in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the names of the manifest strands that are found in this twine.
def available_manifest_strands(self): return self._available_manifest_strands
[ "def available_strands(self):\n return self._available_strands", "def manifest(self):\n return self._client[\"manifests\"]", "def list_manifests():\n import enaml\n with enaml.imports():\n from .pulses.manifest import PulsesManagerManifest\n from .tasks.manifest import PulsesTa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that the children values, passed as either a file or a json string, are correct.
def validate_children(self, source, **kwargs): # TODO cache this loaded data keyed on a hashed version of kwargs children = self._load_json("children", source, **kwargs) self._validate_against_schema("children", children) strand = getattr(self, "children", []) # Loop the childr...
[ "def check_dict_child(_json_data):\n nb_child = 0\n for test_dict in _json_data:\n if type(_json_data[test_dict]) is dict:\n nb_child += 1\n return nb_child", "def check_children_attributes(self, branch):\n attributes = branch.get_attributes()\n for attr in attributes:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that all credentials required by the twine are present. Credentials must be set as environment variables, or defined in a '.env' file. If stored remotely in a secrets manager (e.g. Google Cloud Secrets), they must be loaded into the environment before validating the credentials strand. If not present in the en...
def validate_credentials(self, *args, dotenv_path=None, **kwargs): if not hasattr(self, "credentials"): return set() # Load any variables from the .env file into the environment. dotenv_path = dotenv_path or os.path.join(".", ".env") load_dotenv(dotenv_path) for cre...
[ "def validate_credentials(self, credentials_to_validate):\n\n #TO-DO\n pass", "def load_credentials():\n\n # Get the config file path\n path = os.path.expanduser('~/.stirplate/config')\n\n # Default the credentials to NoneType\n user_id = None\n key = None\n secret = None\n loca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate monitor message against the monitor message schema strand.
def validate_monitor_message(self, source, **kwargs): return self._validate_values(kind="monitor_message", source=source, **kwargs)
[ "def validate(self):\n\n # Check if motherboard record exists\n motherboard_record_exists = False\n board_info_records = self.groups[constants.RecordType.BASEBOARD_RECORD]\n for handle_id in board_info_records:\n record = self.records[handle_id]\n if 'Type' in record.props and record.props['Ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the output manifest, passed as either a file or a json string.
def validate_output_manifest(self, source, **kwargs): return self._validate_manifest("output_manifest", source, **kwargs)
[ "def validate_manifest(manifest_json):\n manifest_json = copy.deepcopy(manifest_json)\n for field in [\"schemes\", \"host\", \"basePath\", \"info\"]:\n if field not in manifest_json:\n raise exceptions.ValidationError(\n click.style(\"Field '{}' is missing from the manifest fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter that will return cls[name] if cls is a dict or cls otherwise
def _get_cls(name, cls): return cls.get(name, None) if isinstance(cls, dict) else cls
[ "def getInstacefromcls(cls, clsname, valuedict=None):\n for i in range(len(clslist)):\n if clsname == clslist[i]:\n return clslist[i](valuedict)\n return None", "def lookup_by_class(dict_,class_):\n v = None\n for c in classlist(class_)[::-1]:\n if c in dict_:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate a single strand by name.
def validate_strand(self, name, source, **kwargs): return self.validate({name: source}, **kwargs)[name]
[ "def _validate_from_name(self, name):\n return name[:15]", "def testValidName(self, name: unicode, isPath: bool) -> None:\n ...", "def validate_name(self, name):\n\n lesson = Lessons.query.filter_by(id=self.lesson.data).first()\n academy = Academy.query.filter_by(name=self.academy.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the nonce is correct, less than one hour old, and not more than two minutes in the future Callers should also store used nonces and reject messages with previouslyused ones.
def verify_and_burn_nonce(nonce): ret = re.match(r'^001[2-9][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])' r'T([01][0-9]|2[0-3])(:[0-5][0-9]){2}Z[A-Za-z0-9]{6}$', nonce) if ret: date = parser.parse(nonce[3:-6]) now = datetime.utcnow().replace(tzinfo=tz.tzutc()) ret...
[ "def is_valid_nonce(prev_nonce, nonce):\n guess = '{0}{1}'.format(prev_nonce, nonce).encode()\n guess_hash = sha256(guess).hexdigest()\n\n return guess_hash[:5] == '00000'", "def check_and_redeem_nonce(cls, actor_id, nonce_id, level):\n def _transaction(nonces):\n \"\"\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map Juniper SRX Policy Object into xml config element
def to_xml(self): policy_element = create_element('policy') create_element('name', text=self.name, parent=policy_element) match_element = create_element('match', parent=policy_element) for s in self.src_addresses: create_element('source-address', text=s.name, parent=match_el...
[ "def policy_settings():\n liquid_header = \"{% if jwt.typ== \\'Bearer\\' %}{{ jwt.exp }};{{ jwt.iat }};{{ jwt.iss }};\" \\\n \"{{ jwt.aud }};{{ jwt.typ }};{{ jwt.azp }}{% else %}invalid{% endif %}\"\n\n return rawobj.PolicyConfig(\"headers\", {\n \"response\": [{\"op\": \"set\", \"he...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new ColumnInfo and update the size
def update(self, size) -> 'ColumnInfo': return ColumnInfo( size, self.directive, self.period )
[ "def SetColumn(self, column, info):\r\n \r\n if column < 0 or column >= self.GetColumnCount():\r\n raise Exception(\"Invalid column\")\r\n \r\n w = self._columns[column].GetWidth()\r\n self._columns[column] = info\r\n \r\n if w != info.GetWidth():\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply copy metadata from source to target
def copy_stock_metas( meta_source, target, copy_columns_info=True, ) -> None: set_attr( target, KEY_ALIAS_MAP, copy(getattr(meta_source, KEY_ALIAS_MAP)) ) if copy_columns_info: set_attr( target, KEY_COLUMNS_INFO_MAP, deepcopy(...
[ "def _copy_metadata(from_dir, to_dir):\n if not FLAGS.dry_run:\n tf.io.gfile.makedirs(to_dir)\n for fname in tfds.core.utils.list_info_files(from_dir):\n from_path = os.path.join(from_dir, fname)\n to_path = os.path.join(to_dir, fname)\n logging.info('cp %s %s', from_path, to_path)\n if not FLAGS.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of all public modules relative to a path.
def get_public_modules(path, base_package=None): result = [] for subdir, _, files in os.walk(path): # Skip folders that start with _. if any([part.startswith('_') for part in subdir.split(os.path.sep)]): continue _, rel_dir = subdir.split(path) rel_dir...
[ "def module_list(path):\n\n if os.path.isdir(path):\n folder_list = os.listdir(path)\n elif path.endswith('.egg'):\n from zipimport import zipimporter\n try:\n folder_list = [f for f in zipimporter(path)._files]\n except:\n folder_list = []\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get losses of last computation if existing
def get_losses(self): if self.loss is not None: return [self.loss] else: return []
[ "def last_loss(self):\n return self._internal.get_last_loss()", "def losses(self):\n pass", "def loss(self) -> Optional[float]:\n return self._last_loss_value", "def build_losses(self):\n self.batch_losses = tf.squared_difference(self.predicted_rv, self.label)\n self.total_loss ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute any branch of the stable or unstable submanifolds of a saddle. Accepts fixed point instances of class fixedpoint_2D.
def find_saddle_manifolds(fp, xname, ds=None, ds_gamma=None, ds_perp=None, tmax=None, max_arclen=None, ic=None, eps=None, ev_dirn=1, ic_ds=None, max_pts=1000, directions=(1,-1), which=('s', 'u'), other_pts=None, rel_scale=None, ...
[ "def exact_saddle(V,X,Y,Z,dim,Z0=None):\n #from all_functions import find_saddle,sum_of_e_field\n if dim==3:\n print \"here\"\n print find_saddle(V,X,Y,Z,3)\n [I,J,K]=find_saddle(V,X,Y,Z,3) # guess saddle point; Z0 not needed\n print I,J,K\n r0=[X[I],Y[J],Z[K]]\n if I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returned data frame should have trading_pair as index and include usd volume, baseAsset and quoteAsset
async def get_active_exchange_markets(cls) -> pd.DataFrame: async with aiohttp.ClientSession() as client: trading_pairs_response = await client.get(ASSET_PAIRS_URL) trading_pairs_response: aiohttp.ClientResponse = trading_pairs_response if trading_pairs_response.status != 2...
[ "def calculate_asset_delta_from_trades(current_strategy_name: str,\n market_trading_pair_tuples: List[MarketTradingPairTuple],\n raw_queried_trades: List[TradeFill],\n ) -> Dict[MarketTradingPairTuple, Dic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a string from standard input, but prompt to standard error. The trailing newline is stripped.
def stderr_input(prompt: str = '', file: IO = sys.stdout) -> str: # pragma: no cover if file is sys.stdout: return input(prompt) try: stdin = sys.stdin except AttributeError: raise RuntimeError("stderr_input: lost sys.stdin") file.write(prompt) try: flush = file.flush except AttributeError: pass e...
[ "def safeRawInput(in_string = None):\r\n \r\n try:\r\n if in_string == None:\r\n return raw_input()\r\n \r\n return raw_input(in_string)\r\n \r\n except (EOFError, KeyboardInterrupt):\r\n print\r\n print \"User Interrupt: Quitting script...\"\r\n sys....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return canonical form for control state.
def canonical_ctrl_state(ctrl_state, num_qubits): if not num_qubits: return '' if isinstance(ctrl_state, CtrlAll): if ctrl_state == CtrlAll.One: return '1' * num_qubits return '0' * num_qubits if isinstance(ctrl_state, int): # If the user inputs an integer, conv...
[ "def state_raw(self):\n return self._state_raw", "def normalize_state(self):\n self.state = 2 * (self.state - 0.5)", "def inverse(self):\n return CZGate(ctrl_state=self.ctrl_state) # self-inverse", "def get_state_s(self, lower = True):\r\n\r\n state_s = STATE_STRINGS[self._state -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if command cmd has a compute/uncompute tag.
def _has_compute_uncompute_tag(cmd): for tag in cmd.tags: if tag in [UncomputeTag(), ComputeTag()]: return True return False
[ "def _has_compute_uncompute_tag(self, cmd):\n for t in cmd.tags:\n if t in [UncomputeTag(), ComputeTag()]:\n return True\n return False", "def on_compute_node(self):\n return self.args.subparser_name == 'run'", "def has_extra(cmd):\n if cmd.instr == CQC_CMD_SEND...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive a list of commands.
def receive(self, command_list): for cmd in command_list: self._handle_command(cmd)
[ "def receive(self, command_list):\n if self.save_commands:\n self.received_commands.extend(command_list)\n if not self.is_last_engine:\n self.send(command_list)", "def receive(self, command_list):\n for cmd in command_list:\n if not cmd.gate == FlushGate():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of control qubits of the command object cmd.
def get_control_count(cmd): return len(cmd.control_qubits)
[ "def num_ctrl_qubits(self):\n return self._num_ctrl_qubits", "def command_count(self):\n return len(self.commands)", "def count(self):\n return len(self.commands)", "def num_commands(self):\n return len(self.commands)", "def count(self):\n return len(self._commands)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether a command has negatively controlled qubits.
def has_negative_control(cmd): return get_control_count(cmd) > 0 and '0' in cmd.control_state
[ "def is_use_qps(self) -> bool:\n if self.qps > 0 and self.second > 0:\n return True\n else:\n return False", "def has_non_cat_verb(self):\n return self.non_cat_verbs.all().count() > 0", "def is_qword(self):\n return ida_bytes.is_qword(self.flags)", "def has_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a starboard. A starboard is a channel which has messages with some stars. To configure this starboard (such as max age and threshold, which are 7 days and 5 stars by default), use starconfig's subcommands. See the help for details.
async def starboard(self, ctx): if self.bot.db.execute("SELECT * FROM starboards WHERE guild_id = ?",(ctx.guild.id,)).fetchone(): return await ctx.say("star.already") async with ctx.typing(): await ctx.channel.edit( topic=TOPIC.format(mention=self.bot.user.mention...
[ "def create_star(ai_settings, screen, stars, star_x, star_y):\n star = Star(ai_settings, screen)\n star.rect.x = star_x\n star.rect.y = star_y\n stars.add(star)", "async def stars(self, ctx: commands.Context, stars: int):\n self.stars = stars\n await self._update_db()\n\n await ct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables a disabled starboard.
async def enable(self, ctx): self.bot.db.execute("UPDATE starboards SET enabled = 1 WHERE channel_id = ?", (ctx.channel.id,)) await ctx.say("star.enabled")
[ "def enable(self):\n self.enabled = True", "async def starboard_toggle(self, ctx, value: bool):\n await queries.update_setting(ctx, \"starboard_settings\", \"is_enabled\", value)\n if value:\n await util.send_success(ctx, \"Starboard is now **enabled**\")\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets "max age" for the starboard messages. If a message is older than the specified days, the message is ignored. Note that existing messages are not affected. Defaults to 7 (one week).
async def maxage(self, ctx, age: int): if age > 0: self.bot.db.execute("UPDATE starboards SET age = ? WHERE channel_id = ?", (age,ctx.channel.id)) await ctx.say("star.age", age) await self.set_topic(ctx.channel.id) else: await ctx.say("star.unsigned", age)
[ "def max_age(self, max_age):\n self._max_age = max_age", "def max_age(self, max_age):\n\n self._max_age = max_age", "def set_maxdays(name, maxdays):\n pre_info = info(name)\n if maxdays == pre_info[\"max\"]:\n return True\n cmd = \"passwd -x {} {}\".format(maxdays, name)\n __sal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets "threshold" for the starboard messages. The specified number of stars are required to put the message on the starboard. Note that existing messages are not affected. Defaults to 5.
async def threshold(self, ctx, threshold: int): if threshold > 0: self.bot.db.execute("UPDATE starboards SET threshold = ? WHERE channel_id = ?", (threshold, ctx.channel.id)) await ctx.say("star.threshold", threshold) await self.set_topic(ctx.channel.id) else: ...
[ "async def set_reaction_threshold(ctx: MessageContext, threshold: int) -> None:\n ctx.guild.reaction_threshold = threshold\n await ctx.session.commit()\n await ctx.channel.send(f\"Set the reaction threshold to {threshold}\")", "def setThreshold(self, newThreshold, frame):\n self.threshold = newThr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a starboard item. The argument can be either original message ID or starboard item ID.
async def star_show(self, ctx, item: Star): board = self.bot.db.execute("SELECT * FROM starboards WHERE guild_id = ?", (ctx.guild.id,)).fetchone() try: board_msg = await self.bot.get_channel(board["channel_id"]).fetch_message(item["item_id"]) except discord.NotFound: retu...
[ "def show_message(message, col=c.r, update=False):\n g.content = generate_songlist_display()\n g.message = col + message + c.w\n\n if update:\n screen_update()", "def show_item(self):\n code = input(\"\\nEnter the items code: \")\n index = StockTracker.get_index(self, code)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables/disables DM when your message was stared. If the parameter is not given, this returns current status. Can be used anywhere including DM.
async def star_dm(self, ctx, enable: bool = None): if enable is None: result = self.bot.db.execute("SELECT starboard_dm FROM users WHERE user_id = ?", (ctx.author.id,)).fetchone() enabled = result["starboard_dm"] if result else 0 status_str = ctx._(f"star.dm{['Disabled', 'Ena...
[ "async def moderation(self, ctx):\n\n new_value = await self.toggle_dm_setting(ctx.author.id, \"ban_kick_mute\")\n\n if new_value:\n message = \":white_check_mark: You will now receive DMs when you get muted, kicked or banned by me.\"\n else:\n message = \":white_check_mar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the postion that a value of weight "weight" would fall in the weight_list, where weight_list is sorted by smallest to largest. Newer inputs win in ties.
def find_pos(weight, weight_list): bool_list = [weight >= x for x in weight_list] pos = bool_list.count(True) - 1 return pos
[ "def getByWeight(list, w):\n itemId = 0\n partialWeight = list[0][1]\n while partialWeight < w:\n itemId += 1\n partialWeight += list[itemId][1]\n return list[itemId]", "def getByWeight(list, w):\n itemId = 0\n partialWeight = list[0][3]\n while partialWeight < w:\n itemI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adjusts top10 list in ascending order, by inserting a new item in appropriate place and adjusting others appropriately
def adjust_top10(value, pos, weight, top10, top10weights): # Create new top10 to be adjusted newtop10 = top10 newtop10weights = top10weights # Keep higher ones, shift lower ones left one newtop10[0:pos] = top10[1:pos + 1] newtop10weights[0:pos] = top10weights[1:pos + 1] # add new ones ...
[ "def top10(self, top10: List[Word]):\n\n self._top10 = top10", "def sort_list_10(li):\n new_list = []\n\n li.sort()\n\n for item in li:\n new_list.append(item * 10)\n \n return new_list", "def move_top ( self ):\n list, index = self.get_info()\n self.value = [ list[in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the correction factor for ambient air temperature and relative humidity Based on the linearization of the temperature dependency curve under and above 20 degrees Celsius, asuming a linear dependency on humidity,
def get_correction_factor(self, temperature, humidity): if temperature < 20: return self.CORA * temperature * temperature - self.CORB * temperature + self.CORC - (humidity - 33.) * self.CORD return self.CORE * temperature + self.CORF * humidity + self.CORG
[ "def get_corrected_resistance(self, temperature, humidity):\n return self.get_resistance()/ self.get_correction_factor(temperature, humidity)", "def linear_scaling_correction(str_path_calibration_forcing, str_path_input_hist_forcing, str_path_input_forcing):\n \n calibration_forcing = nc.Dataset(str_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the resistance of the sensor in kOhms // 1 if not value got in pin
def get_resistance(self): adc = ADC(self.pin) value = adc.read() if value == 0: return -1 return (4095./value - 1.) * self.RLOAD
[ "def get_resistance(self):\n adc = ADC(self.pin)\n value = adc.read()\n if value == 0:\n return -1\n\n return (4095./value - 1.) * self.RLOAD # ESP32 maksimi, ESP8266:lle arvo on 1023", "def get_distance():\n \n GPIO.output(pinTrigger, False) # pulse off\n time.sle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the resistance of the sensor corrected for temperature/humidity
def get_corrected_resistance(self, temperature, humidity): return self.get_resistance()/ self.get_correction_factor(temperature, humidity)
[ "def get_resistance(self):\n adc = ADC(self.pin)\n value = adc.read()\n if value == 0:\n return -1\n\n return (4095./value - 1.) * self.RLOAD # ESP32 maksimi, ESP8266:lle arvo on 1023", "def get_resistance(self):\n adc = ADC(self.pin)\n value = adc.read()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the resistance RZero of the sensor (in kOhms) for calibratioin purposes
def get_rzero(self): return self.get_resistance() * math.pow((self.ATMOCO2/self.PARA), (1./self.PARB))
[ "def get_corrected_rzero(self, temperature, humidity):\n return self.get_corrected_resistance(temperature, humidity) * math.pow((self.ATMOCO2/self.PARA), (1./self.PARB))", "def get_resistance(self):\n adc = ADC(self.pin)\n value = adc.read()\n if value == 0:\n return -1\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the resistance RZero of the sensor (in kOhms) for calibration purposes corrected for temperature/humidity
def get_corrected_rzero(self, temperature, humidity): return self.get_corrected_resistance(temperature, humidity) * math.pow((self.ATMOCO2/self.PARA), (1./self.PARB))
[ "def get_rzero(self):\n return self.get_resistance() * math.pow((self.ATMOCO2/self.PARA), (1./self.PARB))", "def get_resistance(self):\n adc = ADC(self.pin)\n value = adc.read()\n if value == 0:\n return -1\n\n return (4095./value - 1.) * self.RLOAD # ESP32 maksimi, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find and create a configuration for Boost. prefix Where to find sofiasip, should sofiasip/sip.h.
def __init__(self, prefix = None): # Compute the search path. if prefix is None: test = [Path('/usr'), Path('/usr/local')] else: test = [Path(prefix)] self.__prefix = self._search_all('include/sofia-sip-1.12/sofia-sip/sip.h', test)[0] self.__config = drake...
[ "def setup():\n\tglobal config_parser, config_file\n\tglobal prefix\n\n\tif os.path.islink(sys.argv[0]):\n\t\tlink = os.readlink(sys.argv[0])\n\n\t\tif not os.path.isabs(link):\n\t\t\tlink = os.path.join(os.path.dirname(sys.argv[0]), link)\n\n\t\tprefix = os.path.dirname(os.path.abspath(link))\n\telse:\n\t\tprefix ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transliterate and clean username by removing any unsupported character
def clean_username(value): if NO_ASCII_REGEX.search(value): value = unidecode(value) value = NO_ASCII_REGEX.sub('', value) value = NO_SPECIAL_REGEX.sub('', value) return value
[ "def clean_username(username):\n bad_characters = \" !#$%^&*()[]'\\\"\"\n\n for char in bad_characters:\n if char in username:\n username = username.replace(char, '')\n\n return username", "def sanitizeUserName(username):\n if username.startswith(\"@\"):\n username = username[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replacement of ore.alchemist.container.stringKey The difference is that here the primary_key is not determined by sqlalchemy.orm.mapper.primary_key_from_instance(obj) but by doing the logically equivalent (but a little more laborious) [ getattr(instance, c.name) for c in mapper.primary_key ]. This is because, in some h...
def stringKey(obj): unproxied = proxy.removeSecurityProxy(obj) mapper = orm.object_mapper(unproxied) #primary_key = mapper.primary_key_from_instance(unproxied) identity_values = [ getattr(unproxied, c.name) for c in mapper.primary_key ] identity_key = "-".join(map(str, identity_values)) return "...
[ "def _to_primary_key(self, value):\n if value is None:\n return None\n if isinstance(value, self.base_class):\n if not value._is_loaded:\n raise Exception('Record must be loaded.')\n return value._primary_key\n\n return self.base_class._to_primary...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the puzzle state based on the provided move string
def update_puzzle(self, move_string): zero_row, zero_col = self.current_position(0, 0) for direction in move_string: if direction == "l": assert zero_col > 0, "move off grid: " + direction self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1] ...
[ "def update_puzzle(self, move_string):\n zero_row, zero_col = self.current_position(0, 0)\n for direction in move_string:\n if direction == \"l\":\n assert zero_col > 0, \"move off grid: \" + direction\n self._grid[zero_row][zero_col] = self._grid[zero_row][zer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the puzzle satisfies the row zero invariant at the given column (col > 1) Returns a boolean
def row0_invariant(self, target_col): result = True if self._grid[0][target_col] != 0: result = False if self._grid[1][target_col] != (target_col + self._width * 1): result = False for row in range(2, self._height): for col in range(self._width): ...
[ "def row0_invariant(self, target_col):\n # replace with your code\n boolean = True\n \n if self.get_number(0, target_col) != 0:\n boolean = False\n \n for row in range(2, self._height):\n for col in range(self._width):\n if self.current_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the puzzle satisfies the row one invariant at the given column (col > 1) Returns a boolean
def row1_invariant(self, target_col): result = True if self._grid[1][target_col] != 0: result = False for row in range(2, self._height): for col in range(self._width): solved_value = (col + self._width * row) if solved_value != self._grid[r...
[ "def row1_invariant(self, target_col):\r\n # assert that row 1 is solved\r\n if not self.lower_row_invariant(1, target_col):\r\n return False\r\n # asserts that tile proceeded to (1,j), the grid below (1,j) and to the right is solved\r\n for dummy_j in range(0, self.get_width(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a solution string for a puzzle Updates the puzzle and returns a move string
def solve_puzzle(self): cur0_row, cur0_col = self.current_position(0, 0) move_str = 'd' * (self._height - cur0_row - 1) + 'r' * (self._width - cur0_col - 1) self.update_puzzle(move_str) for row in range(self._height-1, 1, -1): for col in range(self._width-1, -1, -1): ...
[ "def solve_puzzle(self):\r\n move_str = \"\"\r\n \r\n puzzle_copy = self.clone()\r\n height = puzzle_copy.get_height()\r\n width = puzzle_copy.get_width()\r\n \r\n # move 0 tile to bottom right\r\n zero_pos = puzzle_copy.current_position(0, 0)\r\n row_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a reaction and combine the products in a single string. Makes errors readable ish
def _reactAndSummarize(rxn_smarts, *smiles): rxn = rdChemReactions.ReactionFromSmarts(rxn_smarts) mols = [Chem.MolFromSmiles(s) for s in smiles] products = [] for prods in rxn.RunReactants(mols): products.append(' + '.join(map(_getProductCXSMILES, prods))) products = ' OR '.join(products) return product...
[ "def reaction():\n return gr.Reaction({1, 2}, {3, 4})", "def reaction_str(self):\n\n def format(number):\n return str(number).rstrip(\".0\") + \" \"\n\n reactant_bits = []\n product_bits = []\n for met in sorted(self._metabolites, key=attrgetter(\"id\")):\n coe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
StereoGroup atoms are in the reaction, and the reaction destroys the specified chirality at the stereo centers > invalidate stereo center, preserve the rest of the stereo group.
def test_reaction_destroys_stereo(self): reaction = '[C@:1]>>[C:1]' products = _reactAndSummarize(reaction, 'F[C@H](Cl)Br |o1:1|') self.assertEqual(products, 'FC(Cl)Br') products = _reactAndSummarize(reaction, 'F[C@@H](Cl)Br |&1:1|') self.assertEqual(products, 'FC(Cl)Br') products = _reactAndSum...
[ "def test_reaction_defines_stereo(self):\n products = _reactAndSummarize('[C:1]>>[C@@:1]', 'F[C@H](Cl)Br |o1:1|')\n self.assertEqual(products, 'F[C@@H](Cl)Br')\n products = _reactAndSummarize('[C:1]>>[C@@:1]', 'F[C@@H](Cl)Br |&1:1|')\n self.assertEqual(products, 'F[C@@H](Cl)Br')\n products = _reactAn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
StereoGroup atoms are in the reaction, and the reaction creates the specified chirality at the stereo centers > remove the stereo center from > invalidate stereo group
def test_reaction_defines_stereo(self): products = _reactAndSummarize('[C:1]>>[C@@:1]', 'F[C@H](Cl)Br |o1:1|') self.assertEqual(products, 'F[C@@H](Cl)Br') products = _reactAndSummarize('[C:1]>>[C@@:1]', 'F[C@@H](Cl)Br |&1:1|') self.assertEqual(products, 'F[C@@H](Cl)Br') products = _reactAndSummarize...
[ "def test_reaction_destroys_stereo(self):\n reaction = '[C@:1]>>[C:1]'\n products = _reactAndSummarize(reaction, 'F[C@H](Cl)Br |o1:1|')\n self.assertEqual(products, 'FC(Cl)Br')\n products = _reactAndSummarize(reaction, 'F[C@@H](Cl)Br |&1:1|')\n self.assertEqual(products, 'FC(Cl)Br')\n products = _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If multiple copies of an atom in StereoGroup show up in the product, they should all be part of the same product StereoGroup.
def test_reaction_copies_stereogroup(self): # Stereogroup atoms are in the reaction with multiple copies in the product products = _reactAndSummarize('[O:1].[C:2]=O>>[O:1][C:2][O:1]', 'Cl[C@@H](Br)C[C@H](Br)CCO |&1:1,4|', 'CC(=O)C') # stere...
[ "def test_grouping_of_components_of_same_protein(self):\n same = [set(self.model.components[2:5])]\n self.assertEqual(self.model.group_accessions(), same)", "def test_grouping_of_components_of_same_protein(self):\n same = [set(self.model.components[2:5]), set(self.model.components[5:7])]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the versions from GitHub tags
def get_versions(self): # They randomly use and don't use 'r' prefix so we have to sort # versions manually versions = list(self._get_github_tags()) versions.sort( key=operator.attrgetter('base_version'), reverse=True, ) return versions
[ "def get_versions(self):\n return self._get_github_tags(normalize_func=self._normalize_tag_name)", "def remote_tags():\n url = \"%s/git/refs/tags\" % get_github_api_url()\n for result in requests.get(url).json():\n ref = result[\"ref\"]\n version = ref.split(\"/\")[-1]\n if versi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill the packets data properties.
def fill_data(self, data): self._data = data self._data_length = data[1:3] self._frame_id = data[4] self._address = XbeeAddress(data[5:9], data[9:13], data[13:15]) self._at_command = data[15:17] self._command_status = data[17] try: self._command_data ...
[ "def set_data(self):\n self.data_init = copy.deepcopy(self.tuun.data)\n self.data = copy.deepcopy(self.data_init)", "def set_properties(self):\n\n # assign feed entries from the root of the parsed data\n if hasattr(self.parsed_data, \"entries\"):\n self.items = self.parsed_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test if the stations are sorted correctly by distance
def test_stations_by_distance(): station_list = build_station_list() #test for stations closest to cambridge city coordinates station_list_sort = stations_by_distance(station_list, (52.2053, 0.1218)) output = [(station.name, distance) for (station, distance) in station_list_sort] for n in range(1, l...
[ "def test_nearest_filter(self):\n for airport, reports, count in (\n (True, True, 6),\n (True, False, 16),\n (False, True, 6),\n (False, False, 30),\n ):\n stations = station.nearest(30, -80, 30, airport, reports, 1.5)\n self.assertEqua...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
size 层汉诺塔搬移,从 left 到 right,借助 mid
def move(self, size: int, left: str, right: str, mid: str): if size == 1: print(f'Move 1 from {left} to {right} ') return # 把n-1个数移动到mid上 self.move(size - 1, left, mid, right) # 把最后一个移动到right print(f'Move {size} from {left} to {right} ') # 把mid的n-1...
[ "def _int_sift_down(self, arr, pos, size):\n #if 2*pos + 1 > size:\n # return\n min_pos = pos\n l_child = 2*pos + 1\n r_child = 2*pos + 2\n if (l_child <= size) and (arr[min_pos] > arr[l_child]):\n min_pos = l_child\n if (r_child <= size) and (arr[min_pos] > arr[r_child]):\n min_pos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
arr 都是整数,从 arr 选择任意个数,可以累加出 aim 的方法数
def sum_aim(self, arr: List[int], aim: int): if not arr or aim < 0: return 0 return self.sum_aim_process(arr, 0, aim)
[ "def sum_array(arr):\n sum = 0\n for num in arr:\n sum += num\n return sum", "def sum(numbers):", "def ArrayAdditionI(arr):\n\n nums = sorted(arr)\n\n #Get highest num\n highestNum = max(arr)\n currentSum = 0 - highestNum\n\n for num in nums:\n currentSum += num\n\n if c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
地上有一个m行和n列的方格。 一个机器人从坐标 0,0 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格, 但是不能进入行坐标和列坐标的数位之和大于 k 的格子.
def robot_move(m: int, n: int, k: int): # x1 = min(n % 10 + (n // 10) % 10, k+1) # x2 = min(m % 10 + (m // 10) % 10, k+1) # print(f'x1={x1}, x2={x2}') # 其他 return _robot_move(m, n, k)
[ "def matrix_left_move_column(k, matrix):\n pass", "def compute_new_pos(m,n,row,col,R,edge_row,edge_col,location):\n new_col = 0\n new_row = 0\n col1= col\n row1 = row\n while R > 0:\n if location == \"top\":\n #new_col = R - col\n if R > col - edge_col:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
位数之和 123 => 1+2+3 345 => 3+4+5
def bit_sum(n): res = 0 while n > 0: res += n % 10 n //= 10 return res
[ "def __digit(cls, s_code: str) -> str:\n i = 1\n tmp_sum = 0\n for num in s_code: # number 为0-9\n if 0 == i % 2:\n tmp = int(ord(num)) * 2 % 10 # tmp 这种\n else:\n tmp = int(ord(num)) * 3 % 10\n tmp_sum += tmp\n i += 2\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Arabic character set ranges from 0600–06FF in unicode.
def see_arabic_chars_unicode(): import unicodedata absent = 0 present = 0 for i in range(0x0600, 0x06FF + 1): try: print('{:04X} \t{} --> {}'.format(i, unicodedata.name(chr(i)), chr(i))) present += 1 except ValueError: absent += 1 else: pri...
[ "def iupac_standard_characters(cls):\n return set(\"ACGUacgu\")", "def normalize_alef_maksura_ar(s):\n\n return s.replace(u'\\u0649', u'\\u064a')", "def clean_arabic(word: str):\n diacritics = [chr(1614),chr(1615),chr(1616),chr(1617),chr(1618),chr(1761),chr(1619),chr(1648),chr(1649),chr(1611),chr(1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to reset instrument commands.
def reset_instrument(self): return self.inst.write('*RST')
[ "def __reset():\n\n global _COMMANDS\n\n _COMMANDS = {}\n\n arguments.reset_parser()", "def reset(self):\n self.query_lines(\"ri\", 3) # Resets the device\n self.query_lines(\"rfsm 1\", 2) # Turns comms on", "def reset(self):\r\n try:\r\n self.write(\"*RST\") ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
queries the database for a specific character takes a name returns a json with the lines
def lines_from_char(character): query = f""" SELECT script_l FROM script JOIN characters ON characters.char_id = script.characters_char_id WHERE name = '{character}' """ data = pd.read_sql_query(query,engine) return data.to_json(orient="records")
[ "def lines_from_char_ep(character,ep):\n query = f\"\"\"\nSELECT script_l FROM script\nJOIN characters \nON characters.char_id = script.characters_char_id\nINNER JOIN episodes\nON episodes.ep_id = script.episodes_ep_id\nWHERE name = '{character}' and episode = '{ep}'\n\"\"\"\n data = pd.read_sql_query(query,e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
queries the database for a specific character and episode takes a name and episode returns a json with the filtered lines
def lines_from_char_ep(character,ep): query = f""" SELECT script_l FROM script JOIN characters ON characters.char_id = script.characters_char_id INNER JOIN episodes ON episodes.ep_id = script.episodes_ep_id WHERE name = '{character}' and episode = '{ep}' """ data = pd.read_sql_query(query,engine) return da...
[ "def lines_from_char(character):\n query = f\"\"\"\nSELECT script_l FROM script\nJOIN characters \nON characters.char_id = script.characters_char_id\nWHERE name = '{character}'\n\"\"\"\n data = pd.read_sql_query(query,engine)\n return data.to_json(orient=\"records\")", "def stream_char(episode, user_path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
queries the database to insert a line from a character takes a name , character and episode returns a confirmation message
def new_line(script_l, character, episode): if up.check("characters", character): char_id = up.giveId("characters", character) else: up.insertCharacter(character) char_id = up.giveId("characters", character) if up.check("episodes", episode): ep_id = up.giveId("episodes", epis...
[ "def insertCharacter(string):\n if check(\"character\", string):\n return \"character exists\"\n else:\n engine.execute(f\"INSERT INTO characters (name) VALUES ('{string}');\")", "def insertEpisode(ep):\n if check(\"episodes\", ep):\n return \"episode exists\"\n else:\n eng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a string representation of SnakemakeRule instance
def __repr__(self): template = """ SnakemakeRule ({}) - parent_id : {} - input : {} - output : {} - local : {} - template : {} - params : {} """ return template.format( self.rule_id, ...
[ "def __str__(self):\n return \"[ %s ]\" % str(self.__rule)", "def __str__(self):\n return \"{ %s }\" % str(self.__rule)", "def format_rule(stats: Stats, rule: Rule) -> str:\n text = __print_body(rule.body)\n text += ' -> '\n text += __print_head(stats, rule.head)\n return text", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a string representation of DataIntegrationRule instance
def __repr__(self): template = """ DataIntegrationRule ({}) - inputs : {} - output : {} - local : {} - template : {} - params : {} """ return template.format( self.rule_id, self.inputs, ...
[ "def __str__(self):\n return \"[ %s ]\" % str(self.__rule)", "def __str__(self):\n return \"{ %s }\" % str(self.__rule)", "def format_rule(stats: Stats, rule: Rule) -> str:\n text = __print_body(rule.body)\n text += ' -> '\n text += __print_head(stats, rule.head)\n return text", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the jacobian of a finger at configuration q0.
def compute_jacobian(self, finger_id, q0): frame_id = self.tip_link_ids[finger_id] return pinocchio.computeFrameJacobian( self.robot_model, self.data, q0, frame_id, pinocchio.ReferenceFrame.LOCAL_WORLD_ALIGNED, )
[ "def jacobianF(self):\n\n jacob = np.eye(len(self.x))\n jacob[0][1] = 1\n jacob[2][0] = self.x[4] + self.x[6] * self.x[0] + self.x[8] * (self.x[0] ** 2) / 2\n jacob[2][4] = self.x[0]\n jacob[2][6] = (self.x[0] ** 2) / 2\n jacob[2][8] = (self.x[0] ** 3) / 6\n jacob[3]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the initial search space using latin hypercube sampling.
def lhs_start(hyperbounds, n_samples, rng=None): low_bounds = [] high_bounds = [] for bound in hyperbounds: low_bounds.append(bound[0]) high_bounds.append(bound[1]) low_bounds = np.array(low_bounds, dtype=object) high_bounds = np.array(high_bounds, dtype=object) samples = sampl...
[ "def generate_latin_hypercube(samples, param_dict, class_root, seed=10):\n # Set random seed\n random.seed(seed)\n\n # Create dictionary to hold sampled parameter values\n sample_points = {}\n for key in param_dict.keys():\n sample_points[key] = np.zeros(samples)\n Ndim = len(param_dict.key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts time to gmt, appends to list
def gmt(time): gmt = [0]*time.size for i in range(time.size): gmt[i]=datetime.utcfromtimestamp(time[i]).strftime('%Y-%m-%d %H:%M:%S') return gmt
[ "def _add_time_field(self) -> None:\n self.data[\"time\"] = [datetime(int(yyyy), int(mm), int(dd)) + timedelta(hours=hh) for yyyy, mm, dd, hh in zip(self.data[\"year\"], self.data[\"month\"], self.data[\"day\"], self.data[\"hour\"])]\n for key in [\"year\", \"doy\", \"month\", \"day\", \"hour\"]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds stations that don't have predictand data and appends them to a list
def miss_station(all_stations,stations): diff = len(all_stations)-len(stations) k=0 i=0 miss_stations = ['']*diff a = all_stations[:] a.sort() s = stations[:] s.sort() while i < len(stations): while a[i] != s[i]: mi...
[ "def stations():\n\n return station_list", "def _get_stations_data(self):\n return [station for network in self.__networks_objects_list for station in network[\"Stations\"]]", "def list_stations(self):\n for i in range(len(self.data)):\n self.stnlist.append(Station(self.data[i][0]))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hexlify raw text, return hexlified text.
def hexlify(text): if six.PY3: text = text.encode('utf-8') hexlified = binascii.hexlify(text) if six.PY3: hexlified = hexlified.decode('utf-8') return hexlified
[ "def unhexlify(text):\n unhexlified = binascii.unhexlify(text)\n\n if six.PY3:\n unhexlified = unhexlified.decode('utf-8')\n\n return unhexlified", "def hexify(text):\r\n return ' '.join([hexify_word(word) for word in text.split()])", "def preprocess_hex_chars(self, text) :\n preprocesse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }