query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
The organizations.networks.show endpoint should be correct.
def test_organization_networks_show(self): self.assertEqual( "https://dashboard.meraki.com/api/v0/organizations/" + ORGANIZATION_ID + "/networks/" + NETWORK_ID , MerakiAPI(KEY) .organizations(ORGANIZATION_ID) .networks(NETWORK_I...
[ "def test_organization_networks_index(self):\n self.assertEqual(\n \"https://dashboard.meraki.com/api/v0/organizations/\"\n + ORGANIZATION_ID\n + \"/networks\"\n , MerakiAPI(KEY)\n .organizations(ORGANIZATION_ID)\n .networks()\n .la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The organizations.networks.create endpoint should be correct.
def test_organization_networks_create(self): self.assertEqual( "https://dashboard.meraki.com/api/v0/organizations/" + ORGANIZATION_ID + "/networks" , MerakiAPI(KEY) .organizations(ORGANIZATION_ID) .networks() .lazy() ...
[ "def create_network(request):\n cloud_id = request.matchdict['cloud']\n\n params = params_from_request(request)\n network_params = params.get('network')\n subnet_params = params.get('subnet')\n\n auth_context = auth_context_from_request(request)\n\n if not network_params:\n raise RequiredPa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The organizations.networks.update endpoint should be correct.
def test_organization_networks_update(self): self.assertEqual( "https://dashboard.meraki.com/api/v0/organizations/" + ORGANIZATION_ID + "/networks/" + NETWORK_ID , MerakiAPI(KEY) .organizations(ORGANIZATION_ID) .networks(NETWORK...
[ "def update_network(req):\n db = YamlDB()\n err, msg = db.update_network_group(Const.KUBAM_CFG, req)\n if err == 1:\n return {\"error\": msg}, Const.HTTP_BAD_REQUEST\n return {\"status\": \"ok\"}, Const.HTTP_CREATED", "def update_subnet(self, request):", "def update_networ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The organizations.networks.delete endpoint should be correct.
def test_organization_networks_delete(self): self.assertEqual( "https://dashboard.meraki.com/api/v0/organizations/" + ORGANIZATION_ID + "/networks/" + NETWORK_ID , MerakiAPI(KEY) .organizations(ORGANIZATION_ID) .networks(NETWORK...
[ "def delete_network(request):\n cloud_id = request.matchdict['cloud']\n network_id = request.matchdict['network']\n\n auth_context = auth_context_from_request(request)\n\n # TODO\n if not auth_context.is_owner():\n raise PolicyUnauthorizedError()\n\n try:\n cloud = Cloud.objects.get(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The organizations.networks.traffic endpoint should be correct.
def test_organization_networks_traffic(self): req = MerakiAPI(KEY).organizations(ORGANIZATION_ID).networks(NETWORK_ID).lazy().traffic({ "timespan": 7200, "deviceType": "wireless" }) self.assertEqual( "https://dashboard.meraki.com/api/v0/organizati...
[ "def test_azure_service_api_networks_get(self):\n pass", "def test_organization_networks_index(self):\n self.assertEqual(\n \"https://dashboard.meraki.com/api/v0/organizations/\"\n + ORGANIZATION_ID\n + \"/networks\"\n , MerakiAPI(KEY)\n .organi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test_setup_is_valid. Make sure setup is valid
def test_setup_is_valid(self):
[ "def input_valid(self, settings_to_test):\n return (True, \"ok\")\n #return (False, \"All arguments are assumed invalid until verified\")", "async def test_requires_validation_state(hass: HomeAssistant) -> None:\n\n config_entry = MockConfigEntry(\n domain=DOMAIN,\n data=_mock_get_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pone el pipe de Gst en Gst.State.PLAYING
def __play(self): self.player.set_state(Gst.State.PLAYING)
[ "def pause_play(self):\n \n if self.estado == Gst.State.PAUSED \\\n or self.estado == Gst.State.NULL \\\n or self.estado == Gst.State.READY:\n self.__play()\n \n elif self.estado == Gst.State.PLAYING:\n self.__pause()", "def switchPlaySta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pone el pipe de Gst en Gst.State.NULL
def stop(self): self.player.set_state(Gst.State.NULL)
[ "def reset():\n Game.FRAMES = 0 # resets number of frames to zero\n pipes = [] # removes all the pipes on the screen\n return pipes", "def constructPipeline(self):\r\n self.pipeline = gst.Pipeline(\"pipeline\")\r\n\r\n self.audiosrc = gst.element_fac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Llama a play() o pause() segun el estado actual del pipe de Gst.
def pause_play(self): if self.estado == Gst.State.PAUSED \ or self.estado == Gst.State.NULL \ or self.estado == Gst.State.READY: self.__play() elif self.estado == Gst.State.PLAYING: self.__pause()
[ "def __play(self):\n \n self.player.set_state(Gst.State.PLAYING)", "def pause_play():", "def start_play():", "def stop_play():", "def switchPlayStatus(self):\n if self.signalPlayer.playStatus == AudioSignalPlayer.PLAYING or \\\n self.signalPlayer.playStatus == AudioSignalPlaye...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates x_grid and y_grid from even n_1, n_2
def gen_grids(n_1, n_2): x_grid = 1.0*np.arange(-int(n_2/2), int(n_2/2)+1) y_grid = 1.0*np.arange(-int(n_1/2), int(n_1/2)+1) return x_grid, y_grid
[ "def _possible_grids(self, num_windows):\r\n if num_windows < 2:\r\n end = 2\r\n else:\r\n end = num_windows / 2 + 1\r\n for rows in range(1, end):\r\n cols = int(math.ceil(float(num_windows) / rows))\r\n yield (rows, cols, ROWCOL)\r\n if r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assuming token is in bottom up format Also, certificate is in raw form
def get_root_from_token(certificate, token): t = get_hash_md5(certificate) for hash in token: if hash[0] == "before": tmp = hash[1]+t t = tmp else: tmp = t+hash[1] t = tmp return t
[ "def tbs_certificate_bytes(self):", "def decode_auth_token(token):\n try:\n payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms='HS256')\n return payload['sub']\n except jwt.ExpiredSignatureError:\n return 'Signature expired, Please sign in again'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads UTF8 encoded SQL from a file
def read_sql(path): with codecs.open(path, mode='r', encoding='utf-8', buffering=-1) as sql_file: return sql_file.read()
[ "def get_sql_from_file(self, path):\n with open(self.make_sql_file_path(path), 'rb') as f:\n sql = f.read().decode('utf-8')\n return sql", "def getSqls(file):\n if isinstance(file, io.IOBase):\n sqls = file.read().split(\"\\n\")\n file.close()\n return sqls", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a TableReference from project, dataset and table
def tableref(project, dataset_id, table_id): dataset_ref = bigquery.dataset.DatasetReference(project=project, dataset_id=dataset_id) return bigquery.table.TableReference(dataset_ref=dataset_ref, table_id=table_id)
[ "def createAzureTable(self):\n self.table_service = TableService(self.account_name, self.account_key)\n self.table_service.create_table(self.table_name)", "def _get_table(self, dataset_name, table_name, schema):\n dataset_ref = client.dataset(dataset_name)\n try:\n client.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a TableReference from TableSpec
def to_tableref(tablespec_str): parts = tablespec_str.split('.') return tableref(parts[0], parts[1], parts[2])
[ "def create_link_spec_table_builder(**kwargs):\n spec_table_builder = DMSpecTableBuilder(**kwargs)\n return spec_table_builder", "def make_table_stub():\n return TABLE_STUB_FACTORY(\n TABLE_ADMIN_HOST, PORT,\n metadata_transformer=custom_metadata_transformer,\n secure=True,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A decorator to wait on export job
def gcs_export_job_poller(func): @functools.wraps(func) def wrapper(*args, **kwargs): logger = logging.getLogger(__name__) job = func(*args, **kwargs) job.result(timeout=kwargs.get('timeout')) # wait for job to complete logger.info('Finished Extract to GCS. jobId: %s', ...
[ "def wait_for_completion(job, headers={}):\n while is_running(job, headers):\n time.sleep(3)", "def run_job():", "def finish_exporting(self):\n pass", "def test_post_job_log_export(self):\n pass", "def test_export_csv_in_job(self):\n pass", "def test_export_json_in_job(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Infers project based on client's credentials.
def infer_project(self): return self.get_client().project
[ "def project(self):\n\t\treturn self._client.project", "def project_steps(keystone_client):\n return ProjectSteps(keystone_client.projects)", "def projects(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n\t\t\trequest.sessi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolves a full TableSpec from a partial TableSpec by adding default project and dataset.
def resolve_table_spec(self, dest): if type(dest) == bigquery.table.TableReference: return dest table_id = dest if table_id is not None: parts = table_id.split('.') if len(parts) == 2 and self.default_project is not None: table_id = self.defaul...
[ "def get_table_definition_template(template_type = 'csv', **kwargs):\n base_io = pkg_resources.resource_stream(__name__, \"specs/base.json\")\n base = json.load(base_io)\n\n conversion = {\n \"avro\": pkg_resources.resource_stream(__name__, \"specs/avro_specific.json\"),\n \"csv\": pkg_resour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resolves a full DatasetSpec from a partial DatasetSpec by adding default project.
def resolve_dataset_spec(self, dataset): dataset_id = dataset if dataset_id is not None: parts = dataset_id.split('.') if len(parts) == 1 and \ self.default_project is not None: dataset_id = self.default_project + '.' + dataset return datas...
[ "def get_dataset_resolver(dataset: Dataset) -> Resolver[Entity]:\n if not dataset.resolve:\n return Resolver()\n return get_resolver()", "def _create_data_spec(self):\n if self.has_superclasses:\n self.dataset_spec = ds_spec.BiLevelDatasetSpecification(\n self.name, self.superclasses...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export a table to GCS as CSV.
def export_csv_to_gcs(self, table, gcs_path, delimiter=',', header=True, wait=True, timeout=None): src = self.resolve_table_spec(table) extract_job_config = bigquery.job.ExtractJobConfig( compression='NONE', destination_format='CSV', field_de...
[ "def export_table(service, project_id, dataset_id, table_id, gcs_path):\n # [START extract_job_data]\n job_data = {\n 'configuration': {\n 'extract': {\n 'sourceTable': {\n 'projectId': project_id,\n 'datasetId': dataset_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export a table to GCS as a Newline Delimited JSON file.
def export_json_to_gcs(self, table, gcs_path, wait=True, timeout=None): src = self.resolve_table_spec(table) extract_job_config = bigquery.job.ExtractJobConfig( compression='NONE', destination_format='NEWLINE_DELIMITED_JSON', ) gcs_path = os.path.join(gcs_path, s...
[ "def export_table(service, project_id, dataset_id, table_id, gcs_path):\n # [START extract_job_data]\n job_data = {\n 'configuration': {\n 'extract': {\n 'sourceTable': {\n 'projectId': project_id,\n 'datasetId': dataset_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles CLI invocations of bqpipelines.
def main(): print_handler = logging.StreamHandler(sys.stdout) print_handler.setLevel(logging.DEBUG) fmt = '%(asctime)-15s %(levelname)s %(message)s' print_handler.setFormatter(logging.Formatter(fmt)) job_name = getpass.getuser() + '-cli-job' log = logging.getLogger(job_name) log.setLevel(lo...
[ "def run(argv=None):\n # type: (List[str]) -> None\n logging.info('Command: %s', ' '.join(argv or sys.argv))\n known_args, pipeline_args = vcf_to_bq_common.parse_args(argv,\n _COMMAND_LINE_OPTIONS)\n # Note VepRunner creates new input files, so it should ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to perform a POST request on the webhook view with an invalid hubspot signature header.
def test_invalid_signature(self): # We first try to perform the request without the `X-HubSpot-Signature` header ... request = self.request_factory.post('/hooks/hubspot/') response = MockWebhookView.as_view()(request) self.assertEqual(response.status_code, 401) # ... then, we p...
[ "def test_valid_signature(self):\n request = self.request_factory.post(\n '/hooks/hubspot/',\n data=REQUEST_BODY,\n content_type='application/json',\n )\n request.META[constants.HUBSPOT_SIGNATURE_HEADER_NAME] = HUBSPOT_SIGNATURE\n response = MockWebhookVi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a POST to the webhook view with a valid hubspot signature.
def test_valid_signature(self): request = self.request_factory.post( '/hooks/hubspot/', data=REQUEST_BODY, content_type='application/json', ) request.META[constants.HUBSPOT_SIGNATURE_HEADER_NAME] = HUBSPOT_SIGNATURE response = MockWebhookView.as_view()...
[ "def test_invalid_signature(self):\n # We first try to perform the request without the `X-HubSpot-Signature` header ...\n request = self.request_factory.post('/hooks/hubspot/')\n response = MockWebhookView.as_view()(request)\n\n self.assertEqual(response.status_code, 401)\n\n # .....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a dependency list for the given package, assuming the given package has already been installed. The dependency list is provided in the order in which it needs to be installed.
def build_dep_list(package_name, local_only=True): ## Dealing with pip 10.* api chagnes ## The solution is from: ## https://github.com/naiquevin/pipdeptree/blob/master/pipdeptree.py try: from pip._internal.utils.misc import get_installed_distributions except ImportError: from pip imp...
[ "def get_installedpackages_fulfilling(dep_list):\n # check params\n arizonageneral.check_type_stringlist(dep_list, \"dep_list\", \"storktar.get_installedpackages_fulfilling\")\n\n if len(dep_list) < 1:\n return []\n\n # TODO need to find file dependencies\n retlist = []\n for package in dep_list:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds new group to the database. notifies stats_tab of changes.
def create_group(self): group_name = self.line_grp.text().strip() # removes whitespaces from left and right if group_name == '': display_msg(MsgIcon.WARNING, "Warning", "Please choose a group name") return self.line_grp.setText("") if self.db.insert_group(group...
[ "def AddGroup(self, group):\n # Try to avoid grabbing the lock in the common case that a group already\n # exists.\n if self.GroupExists(group.group):\n logging.info('Not installing group \"%s\" because it already existed.',\n group.group)\n return\n\n # Clear the group cache...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if selected word exists in the database. if not, adds it to the db. later adds it to word_in_group with an appropriate id. called after clicking on '>>' button.
def insert_word_to_group(self): self.db.clear_cache() word_txt = self.line_wrd_to_grp.text().strip().lower() # remove spaces from the rear and the front self.line_wrd_to_grp.setText("") index = self.list_grp.selectionModel().currentIndex() group_txt = index.sibling(index.row(), ...
[ "async def addword(self, ctx, word: str):\n wcheck = await self.bot.pool.fetch(\"SELECT * FROM cursewords WHERE guildid = $1 AND word = $2\", ctx.guild.id, word)\n\n if wcheck != []:\n await ctx.send(\"That word is already blocked in this server!\")\n return\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fills group words (right) list with words of the group the user clicked.
def display_grp_words(self): index = self.list_grp.selectionModel().currentIndex() group_txt = index.sibling(index.row(), 0).data() self.list_wrd_in_grp.clear() # clears group words list (right list). for word in self.db.get_group_words(group_txt): self.list_wrd_in_grp.addIt...
[ "def insert_word_to_group(self):\n self.db.clear_cache()\n word_txt = self.line_wrd_to_grp.text().strip().lower() # remove spaces from the rear and the front\n self.line_wrd_to_grp.setText(\"\")\n index = self.list_grp.selectionModel().currentIndex()\n group_txt = index.sibling(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates group (left) list from DB. Used when user either adds a new book or imports to the DB.
def update_groups(self): self.list_grp.clear() self.list_wrd_in_grp.clear() # resets (left) groups list for group_name in self.db.get_groups(): # populates groups list from DB. self.list_grp.addItem(group_name[0])
[ "def update_all_group(self, side):\n self.lock.acquire()\n allied_users = memory.get_players_with(self.db,\n side=side,\n recruited=True)\n memory.update_list(side, 'all', allied_users)\n self.loc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the word the user selected in the list from the previously selected group
def del_wrd_in_grp(self): index = self.list_grp.selectionModel().currentIndex() group = index.sibling(index.row(), 0).data() wrd_index = self.list_wrd_in_grp.selectionModel().currentIndex() wrd = wrd_index.sibling(wrd_index.row(), 0).data() if not (wrd and group): dis...
[ "def UnCategorizedClickHndlr(self):\r\n some = self.listUnCategorized.selectedItems()\r\n if len(some) == 1:\r\n self.edtSelectTrigger.setText(some[0].text())", "def remove_selected(self):\n idx = 0\n for i in list(self.selection):\n idx = self.index(i)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes the selected group from the database, including all words unique to said group
def del_group(self): index = self.list_grp.selectionModel().currentIndex() group = index.sibling(index.row(), 0).data() if not group: display_msg(MsgIcon.WARNING, "Warning", "Please choose a group to remove.") return self.db.del_group(group) self.update_gr...
[ "def del_wrd_in_grp(self):\n index = self.list_grp.selectionModel().currentIndex()\n group = index.sibling(index.row(), 0).data()\n wrd_index = self.list_wrd_in_grp.selectionModel().currentIndex()\n wrd = wrd_index.sibling(wrd_index.row(), 0).data()\n if not (wrd and group):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fuction takes 6 arguments and initiates deep neural network, takes the downloaded torchvision model, freeze parameters, initiates new classifier with the required output units, criterion loss is defined as nn.NLLLoss(), and adam optimizer is defined.
def initiate_DNN(model, arch, hidden_units_1, hidden_units_2, learning_rate, device): for param in model.parameters(): param.requires_grad = False if arch[:3] in ["vgg", "den", "ale", "squ", "mob"]: input_features = model.classifier[0].in_features else: input_featur...
[ "def buildModel(arch = 'vgg16', hidden_units=500, lr=0.001, n_output=102):\n \n # Load the specifc model from torchvision.models\n # We only provide vgg and mnasnet_05 as altenatives.\n # More models can be found at: https://pytorch.org/docs/stable/torchvision/models.html\n if arch == 'vgg11':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an app, run detect script on it to determine whether it can be built with this pack. Return True/False.
def detect(self, app): script = os.path.join(self.folder, 'bin', 'detect') cmd = '%s %s' % (script, app.folder) result = run(cmd) return result.status_code == 0
[ "def verify_app(cmd):\n try:\n subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n except OSError as e:\n if e.errno == errno.ENOENT:\n return False\n return True", "def appNeedsSetup(self, app):\n return app.getLink('setup') and app['configured'] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path.
def tar(self, appname, appversion): name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2' time = utc.now() name = name_tmpl % {'app': appname, 'version': appversion, 'time': time.strftime('%Y-%m-%dT%H-%M')} if not os.path.exists(TARBA...
[ "def do_pack():\n current_time = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n local(\"mkdir -p versions\")\n name = \"versions/web_static_{}.tgz\".format(current_time)\n tgz_file = local(\"tar -cvzf {} web_static\".format(name))\n return tgz_file", "def make_package(name='a', version='b', path='path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checkout/update a buildpack, given its URL. Buildpacks are checked out into folders whose names start with something nicely readable, followed by an MD5 hash of the full URL (thus distinguishing two buildpacks with the same 'name' but different URLs).
def update_buildpack(url, packs_dir=PACKS_HOME, vcs_type=None): defrag = _defrag(urllib.parse.urldefrag(url)) bpfolder = repo.basename(url) + '-' + hash_text(defrag.url) dest = os.path.join(packs_dir, bpfolder) # TODO: check for whether the buildpack in the folder is really the same as # the one we'...
[ "def update_git_repo(scm_url, scm_url_location):\n if not scm_url and scm_url_location:\n print 'Error. Not all parameters defined in check_scm_url_aliveness.'\n return\n if not check_scm_url_aliveness(scm_url, scm_url_location):\n print 'Update failed as URL did not return error code 200...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a repository URL, return a folder name that's humanreadable, filesystemfriendly, and guaranteed unique to that repo.
def get_unique_repo_folder(repo_url): return '%s-%s' % (repo.basename(repo_url), hash_text(repo_url))
[ "def _repo_name_from_url(url_decode: str):\n github_project_name = os.path.split(url_decode.path)[-1]\n return github_project_name.replace('.git', '')", "def _url_folder_format(self):\n return self.__url_root + self.__url_suffix_repo", "def _get_repo_name_from_url(url: str) -> str:\n\n last_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This takes a guess letter from the user.
def take_a_letter(): letter = input("Please guess a letter: ") return letter
[ "def guess():\n return letter", "def input_letter_from_user(letters_guessed):\r\n\r\n while True:\r\n user_input = input(\"\\nGuess a letter: \")\r\n\r\n if len(user_input) == 1 and user_input.isalpha():\r\n if user_input in letters_guessed:\r\n print(\"Letter\", user...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This checks whether the letter is in the secret word.
def letter_checker(letter, secret): if letter in secret: return True elif letter not in secret: return False
[ "def is_guess_in_word(guess, secret_word):\n return (guess in secret_word)", "def is_word_guessed(secret_word, letters_guessed):\n for i in range(len(secret_word)):\n if not secret_word[i] in letters_guessed:\n return False\n return True", "def is_letter_in_word(self):\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will add to the list of wrong guesses.
def wrong_guess_appender(letter, guesses): guesses.append(letter)
[ "def addGuess(self, guess):\n self.guesses.append(guess)", "def add_guess(self, guess, level):\n if guess >= 1 and guess <= 4 and len(self.guess) < level and not self.dead:\n print \"Player %s guess: %s\" % (self.name, guess)\n self.guess.append(guess)\n return True\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The message for if a user already guessed a letter.
def already_guessed_message(): print("You already guessed that letter.") print("Try again.")
[ "def check_error_notification(letter_guessed, old_letters_guessed):\r\n # Check if guess is more than single char, and alphabet letters.\r\n if len(letter_guessed) > 1 and letter_guessed.isalpha():\r\n error_notification = \"X\\nOnly one letter is allowed\"\r\n # Check if guess is more than single c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Analysis algorithm sequence constructor Nothing special, it just initialises the base class, and taking the name of the input container of the sequence.
def __init__( self, name = "AnalysisSequence" ): # Initialise the base class: super( AnaAlgSequence, self ).__init__( name ) # Set up the sequence's member variables: self._algorithmMeta = [] self._outputAffectingSystematics = None self._metaConfigDefault = {} ...
[ "def __init__(self, sequences, name=\"zip\", fields=[]):\n # shall be changed to this:\n # def __init__(self, seqs, construct=tuple, with_context=False):\n # *Construct* is a callable which accepts a\n if not sequences:\n raise exceptions.LenaTypeError(\n \"at least one ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a postconfiguration on the analysis algorithm sequence This function needs to be called once the sequence is configured to hold the right algorithms, in the right order, with the right settings. It sets the I/O properties of the algorithms to make sure that they receive the input object(s) specified, and produc...
def configure( self, inputName, outputName, affectingSystematics = None, hiddenLayerPrefix = "" ): # Make sure that all internal variables are of the same size: nAlgs = len( self ) if len( self._algorithmMeta ) != nAlgs: raise RuntimeError( 'Analysis algorithm seq...
[ "def runAlgorithm(self):\n addAlgorithme(self.configFile,\"preprocessing\",self.algo)\n #parse(self.configFile)", "def Process(config, logger=None):\n # First thing to do is deep copy the input config to make sure we don't modify the original.\n import copy\n config = copy.deepcopy(config)\n\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a public tool to the job This function is here to provide a uniform interface with which analysis algorithm sequences can declare the public tools that they need. In Athena mode the function doesn't do anything. But in EventLoop
def addPublicTool( self, tool, stageName = 'undefined' ): try: # Try to access the ToolSvc, to see whethet we're in Athena mode: from AthenaCommon.AppMgr import ToolSvc except ImportError: # We're not, so let's remember this as a "normal" algorithm: self...
[ "def add_tool(*args, **kw):\n\n try:\n\n # get additional keys and delete them before calling the method, did this to respect the legacy method signature\n TOOLS = kw['TOOLS']\n del kw['TOOLS']\n\n query.add_tool(kw, TOOLS)\n return {\"success\": True, \"content\": [{\"name\": ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove one algorithm/sequence from this sequence, by name This is to allow removing algorithms (or even sequences) from this sequence in case that would be needed.
def __delattr__( self, name ): # Figure out the algorithm's index: algIndex = -1 index = 0 for alg in self: if alg.name() == name: algIndex = index break index += 1 pass # Check if we were successful: i...
[ "def removeStage( self, stageName ):\n\n if not stageName in self.allowedStageNames() :\n raise ValueError ('unknown stage name ' + stageName + ' allowed stage names are ' + ', '.join(self.allowedStageNames()))\n\n # safety check that we actually know the stages of all\n # algorithms...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all algorithms for the given stage
def removeStage( self, stageName ): if not stageName in self.allowedStageNames() : raise ValueError ('unknown stage name ' + stageName + ' allowed stage names are ' + ', '.join(self.allowedStageNames())) # safety check that we actually know the stages of all # algorithms if...
[ "def resolve_intersections(stage):\n actions_to_remove = set()\n for a in stage:\n if self.action[a].get('next', None):\n intersection = self.action[a]['next'].intersection(stage)\n if intersection:\n for i in intersec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a default value for the given metaconfiguration entry This will both register name as a valid metaconfiguration value and set its default value, or add to its default value, if that name is already known.
def addMetaConfigDefault (self, name, value) : if name in self._metaConfigDefault : self._metaConfigDefault[name] += value pass else : self._metaConfigDefault[name] = value pass pass
[ "def register_default_option(self, nsobj: ConfigNamespace, opt: ConfigOption):\n item = ConfigItem.get(nsobj.namespace_prefix, opt.name)\n if not item:\n self.log.info('Adding {} ({}) = {} to {}'.format(\n opt.name,\n opt.type,\n opt.default_valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test cases where low and high don't cover the whole list
def test_bin_search_diff_highs_and_lows(self): list_val = [0, 1, 2, 3, 4] self.assertEqual(bin_search(4, 0, 2, list_val), None ) self.assertEqual(bin_search(0, 2, 3, list_val), None )
[ "def mark_overlaps_low_res(low_list,high_list):\n marker=np.zeros(len(high_list))\n for index, row in low_list.iterrows():\n c1=row[0],row[1],row[2],row[4],row[5]\n for index2, row2 in high_list.iterrows():\n c2=row2[0],row2[1],row2[2],row2[4\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compute measurement uncertainty from points in 3D
def computeMeasurementUncertainty(points3D, m_measurementError): sigmas = [] for point1 in points3D: m_T_C1C2 = np.asarray([BASELINE, 0, 0]) # Compute angle (alpha) between ray in the first camera and translation between cameras T_C1C2Norm = np.linalg.norm(m_T_C1C2) point1N...
[ "def dev_var_3D(dvar,z,mean_z,var_z,dz_norm,epsilon,Clim):\n nc = cuda.threadIdx.x + cuda.blockDim.x * cuda.blockIdx.x\n \n if (nc < Clim):\n\n m,n_H,n_W,_ = dz_norm.shape\n std_z = math.pow(var_z[nc]+epsilon,1.5)\n\n for i in range(m):\n\n for nh in range(n_H):\n\n for nw in range(n_W):\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The pipeline to compute depth with associated uncertainty from SGBM
def computeDepthSGBM(imR, imL): imgL = cv2.cvtColor(imL,cv2.COLOR_RGB2GRAY) imgR = cv2.cvtColor(imR,cv2.COLOR_RGB2GRAY) win_size = 5 min_disp = 1 max_disp = 16 * 7 -1 #min_disp * 9 num_disp = max_disp - min_disp # Needs to be divisible by 16 #Create Block matching object. stereo = cv2...
[ "def depth(self) -> float:", "def get_depth(self):\r\n check_is_fitted(self)\r\n return self.tree_.max_depth", "def compute_depths(ps_volume, inv_depths):\n\n inv_depth_image = np.zeros(ps_volume.shape[1:], dtype=np.float64)\n\n \"\"\" YOUR CODE STARTS HERE \"\"\"\n for x in range(ps_volu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the URL for a specific anime or manga from the Anilist API.
async def get_anime_manga(bot: UtilityBot, *, query: str, _type: ContentType) -> dict: query_string = _QUERY(_type=_type.value.upper()) async with bot.http_session.post( API_URL, json={"query": query_string, "variables": {"search": query}} ) as resp: logger.info(f"Searching Anilist for {quer...
[ "def get_anime(self, anime):\n if isinstance(anime, int):\n log.debug(f\"Attempting to fetch anime with id {anime}\")\n data = self.fetcher.get_item(anime, category=\"anime\")\n else:\n log.debug(f\"Attempting to find anime matching search {anime}\")\n # thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of urls matching supplied size and hashes.
def get_urls(self, size=None, hashes=None, ids=None, start=0, limit=100): raise NotImplementedError("TODO")
[ "def get_hashes(self, url, hash_types):\n raise NotImplementedError", "def sortUrlsBySize(urls):\n sortedUrls = []\n unknownSizeUrls = []\n totalSize = 0\n for url in urls:\n try:\n response = urllib2.urlopen(url)\n byteSize = response.info().get('content-length', N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a record version given did
def add_version( self, current_did, form, new_did=None, size=None, file_name=None, metadata=None, urls_metadata=None, version=None, urls=None, acl=None, authz=None, hashes=None, description=None, cont...
[ "def add_version(self, version):\n model = self.model()\n model.add_version(version)", "def add(self, record):\n return self._append_record(record, 'additions')", "def add_record(self, **kw):\n return self.connection.add_record(self, **kw)", "def GetRecordFromVersionRecord(request, version...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all record versions given did
def get_all_versions(self, did): raise NotImplementedError("TODO")
[ "def get_versions(self) -> List[dict]:\n versions = list()\n while True:\n payload = dict(\n DatabaseName=self.db.name,\n TableName=self.table,\n MaxResults=100\n )\n response = self.db.glue.get_table_versions(**payload)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the lattest record version given did
def get_latest_version(self, did, has_version=None): raise NotImplementedError("TODO")
[ "def parse_version(record):\n annotations = record.annotations\n accession = annotations.get('accessions', [''])[0]\n if accession:\n if 'sequence_version' in annotations:\n version_num = str(annotations.get('sequence_version'))\n elif record.id.startswith(accession + '.'):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the total bytes of the data represented in the index.
def totalbytes(self): raise NotImplementedError("TODO")
[ "def total_index_size():\n query_total_index_size(current_app.extensions['sqlalchemy'].db)", "def size_bytes(self) -> int:\n return sum(\n v.nbytes if isinstance(v, np.ndarray) else sys.getsizeof(v)\n for v in tree.flatten(self)\n )", "def __len__(self):\n with self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs a program through psutil.Popen, disabling Windows error dialogs
def startSubprocess(processArgs, env=None, shell=False): if env: env = dict(os.environ.items() + env.items()) else: env = os.environ if sys.platform.startswith('win'): # Don't display the Windows GPF dialog if the invoked program dies. # See comp.os.ms-windows.programmer.win32 # How to suppress crash not...
[ "def poll_error(process):\n output, error = process.communicate()\n if process.returncode != 0:\n showwarning(\"Error\", \"Error encountered:\\n\" + str(error))", "def shellit(cmd, shell=True):\n debug = False\n if mg.EXPORT_IMAGES_DIAGNOSTIC: debug = False\n verbose = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test function application across values.
def testApplication(self): self.assertEqual( repeated.repeated(2, 4), repeated.value_apply( repeated.repeated(1, 2), lambda x: x * 2)) # As everything working on values, this should also work on scalars. applied = repeated.value_apply(5, l...
[ "def test_basic_evaluation(self):\r\n # test for no model\r\n result = evaluate_functions(self.session, None, [])\r\n assert result == {}\r\n\r\n # test for no functions\r\n result = evaluate_functions(self.session, self.Person, [])\r\n assert result == {}\r\n\r\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the acriss_code of this VehicleInfo.
def acriss_code(self): return self._acriss_code
[ "def getAuthorityCode(self):\r\n return self.__authorityCode", "def customer_code(self) -> str:\n return self._customer_code", "def acriss_code(self, acriss_code):\n if acriss_code is None:\n raise ValueError(\"Invalid value for `acriss_code`, must not be `None`\")\n\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the acriss_code of this VehicleInfo.
def acriss_code(self, acriss_code): if acriss_code is None: raise ValueError("Invalid value for `acriss_code`, must not be `None`") self._acriss_code = acriss_code
[ "def sso_code(self, sso_code):\n\n self._sso_code = sso_code", "def set_code(self, code):\n self._code = code", "def setCode(self, c):\n\t\t\n\t\tself.code = c", "def setCode(self, code):\n if not utils.is_valid_code(code)[0]:\n raise ValueError, utils.mapping(_(\"Invalid code:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the transmission of this VehicleInfo. The decoded ACRISS transmission type, to let you know if this vehicle is Automatic or Manual Transmission (stickshift).
def transmission(self): return self._transmission
[ "def get_transmit_power(self):\n (status, power) = self.__device.get_transmit_power()\n self.__device.decode_error_status(status, cmd='get_transmit_power', print_on_error=True)\n return \"%d dBm\" % (power)", "def GetSerialString(self):\n return self._send_string", "def transmission(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the transmission of this VehicleInfo. The decoded ACRISS transmission type, to let you know if this vehicle is Automatic or Manual Transmission (stickshift).
def transmission(self, transmission): self._transmission = transmission
[ "def transport_type(self, transport_type: str):\n allowed_values = [\"aircraft\", \"train\", \"bus\"] # noqa: E501\n if transport_type not in allowed_values:\n raise ValueError(\n \"Invalid value for `transport_type` ({0}), must be one of {1}\"\n .format(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the air_conditioning of this VehicleInfo. The decoded ACRISS air_conditioning information, to let you know if this vehicle has air conditioning
def air_conditioning(self): return self._air_conditioning
[ "def get_aircraft(self):\n return self.aircraft", "async def getAirConditioning(self, vin):\n try:\n await self.set_token('connect')\n airconStatus = self.get(f'https://api.connect.skoda-auto.cz/api/v1/air-conditioning/{vin}/status')\n airconSettings = self.get(f'htt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the air_conditioning of this VehicleInfo. The decoded ACRISS air_conditioning information, to let you know if this vehicle has air conditioning
def air_conditioning(self, air_conditioning): self._air_conditioning = air_conditioning
[ "def set_air_pollution(self, air_pollution_level):\n if air_pollution_level < 0:\n raise ValueError(\"Air pollution level must be positive number\")\n self.air_pollution_level = air_pollution_level", "def setAirMass(self, airmass):\n schema = {'airmass': {'type': 'cFloat', 'coerce'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the fuel of this VehicleInfo. The decoded ACRISS fuel type, to let you know if this vehicle is hybrid, electric, etc.
def fuel(self): return self._fuel
[ "def HeatingFuelType(self):\n return self._heating_fuel_type", "def CoolingFuelType(self):\n return self._cooling_fuel_type", "def getFuel(self):\n return \"FUEL LEVEL %s\"%self.fuel_level", "def get_odometer_fuel(self):\n fresh = False\n odometer_path = Pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the fuel of this VehicleInfo. The decoded ACRISS fuel type, to let you know if this vehicle is hybrid, electric, etc.
def fuel(self, fuel): self._fuel = fuel
[ "def set_fuel(self, fuel):\n self.fuel = fuel\n return self.fuel", "def fuel_technology(self, fuel_technology):\n\n self._fuel_technology = fuel_technology", "def set_battery(self, init_batt, min_batt, fuel_rate):\n rospy.loginfo('%s is setting up fuel requirements...' % self.namespa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`Loss` constructor. It considers the inverse depth map and the corresponding 2D normal map.
def __init__(self, image: np.array, idepth: np.array, idepth_range: Tuple[float], loss_param: Dict[str, float], idepth_confidence: np.array = None, inormal: np.array = None, idepth_init: np.array = None, inormal_init: ...
[ "def _CreateWeightLoss(self):\n self.AssertInitialized()\n with self._BlockScope():\n return [tf.nn.l2_loss(v) for v in self._variables]", "def __init__(self, level, scale, pos, **kwargs):\n super(LevelMap, self).__init__(**kwargs)\n self.level = level\n self.scale = scale\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the averged persite expectation value of the operator parameter.
def expectation_per_site(self, operator): expectation = 0 for tensor_idx, _ in enumerate(self.tensors): expectation += self.tensor_expectation(tensor_idx, operator) return np.real(expectation) / len(self.tensors)
[ "def mean(self):\n\t\treturn 0.8", "def get_avg(self):\n\t\treturn self.sum / max(len(self.window), 1)", "def get_average_xp(xp, operators):", "def avg_Ao(self):\n ...", "def estimated_mean(self):\n estimands=scipy.array(list(itertools.chain(*self.estimands)))\n return sum(estimands)/fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
absorb the Tensor Network all lambda weights into their neighboring tensors.
def absorb_all_weights(self): n, m = self.structure_matrix.shape for tensor_idx in range(n): tensor = self.tensors[tensor_idx] edges_dims = self.get_edges(tensor_idx=tensor_idx) tensor = self.absorb_sqrt_weights(tensor=tensor, edges_dims=edges_dims) self.t...
[ "def avgpoolflatten(): #%t\n return nn.Sequential(Reduce(\"b c h w -> b c\", \"mean\")) # combine avg pool + view", "def update_weights(self) -> None:\n for neuron in self.__neurons__:\n neuron.update_weight(self.__inputs__)", "def __apply_weight_mask(self):\n with torch.no_grad():...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate a player move and return the new gamestate. curl X POST data \
def move(): data = request.get_json(force=True) try: state = fixInputData(data['gamestate']) move = int(data['move']) except (KeyError, TypeError, ValueError): raise JsonError(description='Invalid value.') resp = {"gamestate": game_state.doMove(state, move)} return checkWin(r...
[ "def aimove():\n data = request.get_json(force=True)\n try:\n state = fixInputData(data['gamestate'])\n ai = str(data['ai-name'])\n except (KeyError, TypeError, ValueError):\n raise JsonError(description='Invalid value.')\n move = aiMove(ai, state)\n resp = {\n \"pre-state...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the ai move for the current gamestate, as well as the resulting gamestate. curl X POST data \
def aimove(): data = request.get_json(force=True) try: state = fixInputData(data['gamestate']) ai = str(data['ai-name']) except (KeyError, TypeError, ValueError): raise JsonError(description='Invalid value.') move = aiMove(ai, state) resp = { "pre-state": state, ...
[ "def move():\n data = request.get_json(force=True)\n try:\n state = fixInputData(data['gamestate'])\n move = int(data['move'])\n except (KeyError, TypeError, ValueError):\n raise JsonError(description='Invalid value.')\n resp = {\"gamestate\": game_state.doMove(state, move)}\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When you won, it shows you how long it takes you to save a city and how many letters you needded to guess. It gives you chance to save other capitals
def you_won(): print("\nThis is it!") end = Decimal(time.time() - start) end = str(round(end, 1)) global lettercount print("\nSaving " + capital + " took thou " + str(end) + " seconds and " + repr(lettercount) + " letters.") replay = input('Enter any number if you want to save another city, if n...
[ "def display_status(self):\n print('\\n')\n for line in stages[self.guesses]: print(line)\n for c in self.word.get_word_guessed(self.guessed_letters): \n print(c, end=\" \")\n print(\"\\nLetters Used:\")\n for letter in self.guessed_letters: \n print(letter, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates linear interpolation indices and weights for ND coordinates.
def _make_linear_interpolation_indices_nd( coordinates: jnp.ndarray, shape: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: lower = jnp.floor(coordinates).astype(jnp.int32) upper = jnp.ceil(coordinates).astype(jnp.int32) weights = coordinates - lower # Expand dimensions for `shape` to all...
[ "def _make_linear_interpolation_indices_flat_nd(\n coordinates: jnp.ndarray,\n shape: Sequence[int]) -> Tuple[jnp.ndarray, jnp.ndarray]:\n coordinates = jnp.asarray(coordinates)\n shape = jnp.asarray(shape)\n\n if shape.shape[0] != coordinates.shape[0]:\n raise ValueError(\n (f'{coordinates.shape...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates flat linear interpolation indices and weights for ND coordinates.
def _make_linear_interpolation_indices_flat_nd( coordinates: jnp.ndarray, shape: Sequence[int]) -> Tuple[jnp.ndarray, jnp.ndarray]: coordinates = jnp.asarray(coordinates) shape = jnp.asarray(shape) if shape.shape[0] != coordinates.shape[0]: raise ValueError( (f'{coordinates.shape[0]}-dimensio...
[ "def _make_linear_interpolation_indices_nd(\n coordinates: jnp.ndarray,\n shape: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:\n lower = jnp.floor(coordinates).astype(jnp.int32)\n upper = jnp.ceil(coordinates).astype(jnp.int32)\n weights = coordinates - lower\n\n # Expand dimensions for `s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interpolates linearly on `volume` using `indices` and `weights`.
def _linear_interpolate_using_indices_nd( volume: jnp.ndarray, indices: jnp.ndarray, weights: jnp.ndarray, ) -> jnp.ndarray: target = jnp.sum(weights * volume[indices], axis=0) if jnp.issubdtype(volume.dtype, jnp.integer): target = _round_half_away_from_zero(target) return target.astype(volume.dty...
[ "def _compute_interpolation_weights(self,x):\n\n sz = x.size()\n dim = sz[1]\n\n index = MyLongTensor(*([self.n+1]+list(x.size())))\n weight = MyTensor(*([self.n+1]+list(x.size()))).zero_()\n\n # compute the interpolation indexes\n # todo: can likely be simplified (without ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps the input ND volume to coordinates by linear interpolation.
def flat_nd_linear_interpolate( volume: jnp.ndarray, coordinates: jnp.ndarray, *, unflattened_vol_shape: Optional[Sequence[int]] = None) -> jnp.ndarray: if unflattened_vol_shape is None: unflattened_vol_shape = volume.shape volume = volume.flatten() indices, weights = _make_linear_interpola...
[ "def cube2latlon_preprocess(x, y, xi, yi):", "def linear_interpolation(self, source_adata, dest_adata, n_steps):\n if sparse.issparse(source_adata.X):\n source_average = source_adata.X.A.mean(axis=0).reshape((1, source_adata.shape[1]))\n else:\n source_average = source_adata.X....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of files, return the files that have an extension listed in TESTABLE_FILE_EXTENSIONS
def testable_files(files): return [f for f in files if f.endswith(TESTABLE_FILE_EXTENSIONS)]
[ "def CheckFilebyExt(tgt_ext, file_list):\n\tmatch_list = [file for file in file_list\n\t\t\t\t\t\tif file.endswith(tgt_ext)]\n\treturn match_list", "def GetFileExtensions():", "def get_files_by_ext(dirname, *exts):\n fnames = [f for f in os.listdir(dirname) if os.path.splitext(f)[-1] in exts]\n return [os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run tests for Agentbased checks. If no checks are specified, this will only test checks that were changed compared to the master branch.
def test(checks, bench, coverage, cov_missing, cov_keep, changed, verbose): root = get_root() if checks: checks_to_test = get_testable_checks() & set(checks) if changed: checks_to_test = checks_to_test & get_changed_checks() # Retain order final_checks = [] f...
[ "def run_checks():\n\n log.info('Running checks')\n checks = [\n esync_file_limits(),\n ]\n if all(checks):\n log.info('All checks successful')", "def perform_checks(self) -> None:", "async def _perform_checks(self, member: discord.Member, checks):\n for check in ALL_CHECKS:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate total and average song length
def getSongLength(self, en_artist, song_list): total_song_length = 0 for song in song_list: total_song_length += song.get_audio_summary()['duration'] total_song_length = total_song_length / 60 avg_song_length = total_song_length / NUM_SONGS data = { 'total_songs': NUM_SONGS, 'total_song_length': t...
[ "def get_avg_word_length(lyrics):\n\n\tlyrics = lyrics.translate(str.maketrans('','',string.punctuation))\n\treturn round(sum([len(word) for word in lyrics.split()]) / len(lyrics.split()),2)", "def average_len(records):\n count = 0\n total_Length = 0\n for i in records:\n count = count + 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an intent to the bot
def add_intent(self, intent): self.intents.append(intent)
[ "def __add_new_intent(question, response):\n # type: (str, str) -> None\n\n # The json data to be posted to the DialogFlow\n data = {'auto': True,\n 'contexts': [],\n 'events': [],\n 'fallbackIntent': False,\n 'name': 'sem:'+ question,\n 'priority': 50...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use user input to find the relevant intent
def detect_intent(self, user_input): for intent in self.intents: if intent.matches(user_input): return intent return None
[ "def do_action_for_input(self, user_input):\n try:\n if user_input == CommandLineProgram.ACTION.HELP:\n self.print_help()\n elif user_input == CommandLineProgram.ACTION.ADD_USER:\n self.input_and_create_user()\n elif user_input == CommandLineProg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop to get the revelant intent and run the bound story
def run(self): while True: user_input = self.interface.read() intent = self.detect_intent(user_input) if intent: story = intent.story story.reset() story.run(self.interface) else: self.fallback()
[ "def run_policy(self):\n env = make_imitation_env()\n obs_dict = env.reset()\n while True:\n action = self.get_action(self.gymobs_to_inputdict(obs_dict))\n next_obs_dict, reward, done, info = env.step(action)\n if info.get(\"record\"):\n self.reco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the classification accuracy from IDs; accuracy = correct/all
def compute_classification_accuracy(labels: List[int], predictions: List[int], num_classes: int = -1) -> float: assert len(labels) == len(predictions) correct = 0 for a, b in zip(labels, predictions): if a == b: correct += 1 return correct / len(labels)
[ "def accuracy(labels, labels_true):\r\n # YOUR CODE HERE\r\n\r\n total_label = len(labels)\r\n correct_label = 0\r\n\r\n for i in range(total_label):\r\n if labels[i] == labels_true[i]:\r\n correct_label += 1\r\n\r\n return correct_label/total_label\r\n pass", "def accuracy(data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert list of tensors to list of their argmaxes
def argmax_list_list_tensors(tensors: List[List[torch.Tensor]]) -> List[List[int]]: result = [] for phase in tensors: ids_in_phase = [] for tensor in phase: ids_in_phase.append(argmax_tensor(tensor)) result.append(ids_in_phase) return result
[ "def _tensor_max(*args):\n maximum, *rest = args\n for arg in rest:\n maximum = maximum.max(arg)\n return maximum", "def max2d(a: torch.Tensor) -> (torch.Tensor, torch.Tensor):\n\n max_val_row, argmax_row = torch.max(a, dim=-2)\n max_val, argmax_col = torch.max(max_val_row, dim=-1)\n argm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the MSE between labels and given outputs. Computed for lists of testing phases.
def compute_mse_values(labels: List[List[torch.Tensor]], outputs: List[List[torch.Tensor]]) -> List[float]: mse_values = [] for labels_per_phase, outputs_per_phase in zip(labels, outputs): mse_values.append(compute_mse_from(labels_per_phase, outputs_per_phase).item()) return mse_values
[ "def compute_mse(x_train,x_test,y_train,y_test,theta_hat,max_order):\n\n mse_train = np.zeros((max_order+1))\n for order in range(0, max_order+1):\n X_design_train = make_design_matrix(x_train, order)\n y_hat = np.dot(X_design_train, theta_hat[order])\n residuals = y_train - y_hat\n mse_train[order] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the List (for testing phase) of Lists of scalars (measurements) to List of LongTensors.
def list_int_to_long_tensors(model_outputs: List[List[int]]) -> List[torch.Tensor]: result = [] # TODO shorten with list comprehension here ideally for single_phase_outputs in model_outputs: result.append(torch.tensor(single_phase_outputs, dtype=torch.long)) return result
[ "def list_2dimension_convert(self, lst):\r\n self.matrix_value = []\r\n for sub_list in lst:\r\n self.matrix_value.append(sub_list)", "def get_long_tensor(self, tokens_list, batch_size, mask=None):\r\n token_len = max(len(x) for x in tokens_list)\r\n tokens = torch.LongTenso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition the torch tensor into tensor.numel()//flock_size parts, find argmax of each part
def _partition_tensor_to_ids(tensor: torch.Tensor, flock_size: int) -> List[int]: assert tensor.numel() % flock_size == 0 argmaxes = [] for expert_id in range(flock_size): items = tensor[expert_id].tolist() max_id = items.index(max(items)) # python argmax argmaxes.append(max_id) ...
[ "def n_argmax(a,size):\n if type(a) == torch.FloatTensor:\n a = a.numpy()\n else:\n a = np.array(a)\n\n if len(a.shape)!=1:\n raise ValueError('Only 1D input supported.')\n\n return a.argsort()[-size:][::-1]", "def _tensor_max(*args):\n maximum, *rest = args\n for arg in res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Partition the output tensor of the flock with flock_size>1 into List of ids for each expert For an example see the \tests\templates\test_template_helpers.py\test_partition_to_list_of_ids()
def partition_to_list_of_ids(tensors: List[List[torch.Tensor]], flock_size: int) -> List[List[List[int]]]: # list of experts results = [] # for each phase, for each measurement, split the tensor to list of ids for phase_id, phase in enumerate(tensors): results.append([]) # append the next pha...
[ "def _partition_tensor_to_ids(tensor: torch.Tensor, flock_size: int) -> List[int]:\n assert tensor.numel() % flock_size == 0\n\n argmaxes = []\n\n for expert_id in range(flock_size):\n items = tensor[expert_id].tolist()\n max_id = items.index(max(items)) # python argmax\n argmaxes.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A function factory for building the ColemanReffett operator. Here og is an instance of OptimalGrowthModel.
def time_operator_factory(og, parallel_flag=True): β = og.β f, u = og.f, og.u f_prime, u_prime = og.f_prime, og.u_prime grid, shocks = og.grid, og.shocks @njit def objective(c, σ, y): """ The right hand side of the operator """ # First turn w into a function via ...
[ "def _build_gan_trainer(self, input, model):\n # Build the graph\n self.tower_func = TowerFunc(model.build_graph, model.inputs())\n with TowerContext('', is_training=True):\n self.tower_func(*input.get_input_tensors())\n opt = model.get_optimizer()\n\n # Define the trai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the given matrix in vector form. As per NumPy shape conventions, this is done by stacking rows one after another. The convention chosen is irrelevant, though, as long as it is used consistently.
def mat2vec(matrix): return matrix.reshape(-1)
[ "def mat2vec(M, column=0):\n return [m[column] for m in M]", "def column_vector(v):\n return numpy.reshape(numpy.ravel(v), (-1, 1))", "def matrix_to_vector(self, mat):\n # TODO(nina): why factor np.sqrt(2)\n mat = vectorization.expand_dims(mat, to_ndim=3)\n assert np.all(is_symmetric(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a superoperator in Choi representation to Liouville representation. With our normalisation convention, this is almost an involution up to the different normalisation factors.
def choi2liou(choi): dim = _sqrt_dim(choi) return dim * np.reshape(choi, (dim, dim, dim, dim)).swapaxes(0, 3).reshape( (dim**2, dim**2))
[ "def liou2choi(liou):\n return choi2liou(liou) / liou.shape[0]", "def convert_to_cln(data):\n return cln_converter.convert(data)", "def _Raw_To_Lux(self, gain, ch0, ch1):\n\t\tWINFAC =self._WinFac\n\t\tALS_INT = 10*(self._IntTime)\n\t\tALS_GAIN= 1.0 *gain\n\t\tresult = 0\n\t\tif ch0+ch1 != 0:\n\t\t\tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a superoperator in Liouville representation to Choi representation.
def liou2choi(liou): return choi2liou(liou) / liou.shape[0]
[ "def CalculateChi10p(mol):\r\n return _CalculateChinp(mol, NumPath=10)", "def CalculateChi9p(mol):\r\n return _CalculateChinp(mol, NumPath=9)", "def test_choi_conjugate(self):\n mats = self.unitaries\n chans = [Choi(mat) for mat in self.chois]\n self._compare_conjugate_to_operator(cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Compute the average gate fidelity of the given superoperator to the target unitary.
def avg_gate_fidelity(liou, target_unitary): target_liou = np.kron(np.conj(target_unitary), target_unitary) dim = _sqrt_dim(liou) return (np.real(np.trace(liou @ np.conjugate(target_liou).T)) + dim) / (dim**2 + dim)
[ "def average_gate_fidelity(oper, target=None):\n dims_out, dims_in = _hilbert_space_dims(oper)\n if not (target is None or target.type == 'oper'):\n raise TypeError(\n 'target must be None or a Qobj representing a unitary.')\n\n d = np.prod(dims_in)\n return (d * process_fidelity(oper,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new post. Method 'GET' Format request /post/add?title=&description= Function has a check for the length of the text (title and description)
def add_post(): title = request.args.get("title") description = request.args.get("description") date = datetime.today().strftime("%d-%m-%Y %H:%M") if not title or not description: return redirect('/') data = () if len(title) > 5 and len(description) > 10: data = (title, descr...
[ "def post(self):\r\n title = self.request.get(\"subject\")\r\n content = self.request.get(\"content\")\r\n if title and content:\r\n add_to_store = BlogPosts(title = title, blogpost = content)\r\n newpost = add_to_store.put()\r\n self.redirect(\"/blog/\" + str(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This func edit post with id from request New text title and description get from request Format request /post/edit?id=&title=&description=
def edit_post(): id = request.args.get('id') title = request.args.get('title') description = request.args.get('description') if not id: return redirect('/') try: db = connect_db() if title and description: db.cursor().execute("UPDATE posts SET title=?, descrip...
[ "def handle_post_edit(post_id):\n\n edit_title = request.form.get('edit-title')\n edit_content = request.form.get('edit-content')\n\n current_post = Post.query.get(post_id)\n\n current_post.title = edit_title\n current_post.content = edit_content\n\n db.session.add(current_post)\n db.session.co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This func delete post with id from request Format request /post/delete?id=
def del_post(): id = request.args.get('id') if id: try: db = connect_db() db.cursor().execute("DELETE FROM posts WHERE id = ?", (id, )) db.commit() db.close() except sqlite3.Error as e: db.close() return f"Ошибка доступа к...
[ "def delete(self, id): \n post = delete(id)\n return post", "def delete_post():\n post = mongo.db.Posts\n _id = request.json['_id']\n post.delete_one({'_id': ObjectId(_id)})\n\n return jsonify({'result': \"Post deleted!\"})", "def delete_post(list_id):\n data = request.get_json()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test split path utility.
def test_split_path(self): zope_root = self.root.getPhysicalRoot() self.assertEqual( split_path('publication/document', self.root), (['root', 'publication', 'document'], zope_root)) self.assertEqual( split_path('/publication/document', self.root), ...
[ "def testSplitPath(self):\n path_spec = fake_path_spec.FakePathSpec(location='/')\n\n test_file_system = TestFileSystem(self._resolver_context, path_spec)\n\n expected_path_segments = ['test1', 'test2', 'test3']\n\n path_segments = test_file_system.SplitPath('/test1/test2/test3')\n self.assertEqual(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test upgrade of a simple link.
def test_upgrade_link(self): document = self.root.document editable = document.get_editable() editable.content = ParsedXML( 'content', """<?xml version="1.0" encoding="utf-8"?> <doc> <p type="normal"> <link target="_blank" url="./publication">Publication link</link>...
[ "def test_upgrade_link_external(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <link target=\"_blank\" url=\"http...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test upgrade of a link that does not point to a Silva object, like for instance to the edit interface.
def test_upgrade_link_not_silva_object(self): document = self.root.document editable = document.get_editable() editable.content = ParsedXML( 'content', """<?xml version="1.0" encoding="utf-8"?> <doc> <p type="normal"> <link target="_blank" url="./edit">SMI</link> ...
[ "def test_upgrade_link(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <link target=\"_blank\" url=\"./publication...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test upgrade of a link that is only to an anchor on the same page
def test_upgrade_link_only_anchor(self): document = self.root.document editable = document.get_editable() editable.content = ParsedXML( 'content', """<?xml version="1.0" encoding="utf-8"?> <doc> <p type="normal"> <link target="_blank" url="#on_me">On me link</link> ...
[ "def test_upgrade_link_with_anchor(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <link target=\"_blank\" url=\"....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test upgrade of a simple link to a content with an anchor
def test_upgrade_link_with_anchor(self): document = self.root.document editable = document.get_editable() editable.content = ParsedXML( 'content', """<?xml version="1.0" encoding="utf-8"?> <doc> <p type="normal"> <link target="_blank" url="./publication#on_me">On me...
[ "def test_upgrade_link_only_anchor(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <link target=\"_blank\" url=\"#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test upgrade of a simple link with a completely invalid URL as a link.
def test_upgrade_link_invalid(self): document = self.root.document editable = document.get_editable() editable.content = ParsedXML( 'content', u"""<?xml version="1.0" encoding="utf-8"?> <doc> <p type="normal"> <link target="_blank" url="Aléatoire">On me link</link> </p> </doc...
[ "def validate_link(link):\n\tpass", "def test_nonexistent_link(self):\n url = reverse('links:index')\n response = self.client.get(url)\n orig_link = \"https://byrbalyalya/\"\n self.assertNotContains(response, orig_link)", "def test_upgrade_link_external(self):\n document = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }