query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get the player document associated with `player`. This will assume user ID (field _id) and then username, in that order. If both fail, returns `None`.
async def get_player_document(player): db = client['players_and_teams'] player_collection = db['players'] player_document = await player_collection.find_one({'_id': player}) if not player_document: #mongodb queries are case-sensitive #i think it is marginally faster for a collectio...
[ "async def get_name_from_user(discord_id, *, return_player):\r\n user_doc = await get_user_document(discord_id)\r\n if not user_doc[\"osu_id\"]:\r\n return None\r\n else:\r\n if return_player:\r\n return user_doc[\"osu_id\"]\r\n else:\r\n return user_doc[\"team_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the osu! ID or team associated with `discord_id`. If `return_player` is True, returns the osu! ID. Otherwise, returns the team name (same as _id of associated Team document). If no osu! ID is associated, returns `None`. (Because we generate the team name and osu! ID, there is no need to have additional validation f...
async def get_name_from_user(discord_id, *, return_player): user_doc = await get_user_document(discord_id) if not user_doc["osu_id"]: return None else: if return_player: return user_doc["osu_id"] else: return user_doc["team_name"]
[ "def getId(wp_page='', player_name=''):\n\n\tif player_name:\n\t\ttext = ''\n\t\ttext = searchPlayer(wp_page=wp_page, player_name=player_name)\n\n\t\tif text:\n\t\t\tsoccerway_id = re.findall(r'<td class=\"player\"><a href=\"/players/([\\/\\-\\w]*)\" class=\"[\\_\\s\\/\\-\\w]*\">.*</a></td>', text, re.IGNORECASE)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the document associated with `id`. If `pool=None`, then `id` is treated as a beatmap ID first. If conversion to `int` fails (i.e. letters have been passed) or a database loookup fails, `id` is treated as shorthand notation ``, as in "NM1" or "HR2". The pool currently set as active in the Meta document will be used....
async def get_map_document(id, pool=None): db = client['mappools'] try: int(id) #id is only numbers, and is probably a /b id if not pool: pool = await determine_pool(id) pool_collection = db[pool] return await pool_collection.find_one({'_id': id}) ...
[ "async def determine_pool(map_id):\r\n db = client[\"mappools\"]\r\n collection = db[\"meta\"]\r\n cursor = collection.find()\r\n #well i'd hope we never end up with 100 pools\r\n for meta_document in await cursor.to_list(length=100):\r\n if map_id in meta_document[\"diff_ids\"]:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the match document associated with `match_id`. `match_id` must be an exact match of an _id in the matches collection. Lobby names are not acceptable. If the match cannot be found, `None` is returned.
async def get_match_document(match_id): #lobby names aren't acceptable because we don't store them lol db = client['matches_and_scores'] matches_collection = db['matches'] return await matches_collection.find_one({'_id': match_id})
[ "def get_match(id):\n match = Match.get(id)\n if match is None:\n return jsonify({'message': 'Match instance could not be found.'}), 404\n\n response = match.to_dict()\n return jsonify(response), 200", "def get_match_details(self, match_id, **kwargs):\n\n if 'match_id' not in kwargs:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the top n scores (as documents) of a player, filtered by mod if defined, and the max page. Returns the tuple `([], max_page)`.
async def get_top_player_scores(player_id, page=1, mod=None): db = client['players_and_teams'] player_collection = db['players'] player_document = await get_player_document(player_id) if player_document is None: return (None, None, None) scores = player_document["scores"] #t...
[ "async def get_top_team_scores(team_name, page=1, mod=None):\r\n db = client['players_and_teams']\r\n team_collection = db['teams']\r\n team_document = await get_team_document(team_name)\r\n if team_document is None:\r\n return (None, None, None)\r\n scores = team_document[\"scores\"]\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the top n scores (as documents) of a team, filtered by mod if defined, and the max page. Returns the tuple `([], page, max_page)`.
async def get_top_team_scores(team_name, page=1, mod=None): db = client['players_and_teams'] team_collection = db['teams'] team_document = await get_team_document(team_name) if team_document is None: return (None, None, None) scores = team_document["scores"] #the number of score...
[ "async def get_top_player_scores(player_id, page=1, mod=None):\r\n db = client['players_and_teams']\r\n player_collection = db['players']\r\n player_document = await get_player_document(player_id)\r\n if player_document is None:\r\n return (None, None, None)\r\n scores = player_document[\"scor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the top n scores (as documents) of a map. Returns `([], page, max_page)`. `map_id` can be either the shorthand name of the map in the pool ("NM1") or the full diff ID. `page` determines the top scores to be returned. Pagination is done on a 10 score per page basis; if `page10` exceeds the total number of scores of ...
async def get_top_map_scores(map_id, page=1, pool=None): map_document = await get_map_document(map_id) if not map_document: return (None, None, None) scores = map_document["scores"] max_page = math.ceil(len(scores)/10) if page < 0: page = 1 if page > max_page: ...
[ "async def get_top_player_scores(player_id, page=1, mod=None):\r\n db = client['players_and_teams']\r\n player_collection = db['players']\r\n player_document = await get_player_document(player_id)\r\n if player_document is None:\r\n return (None, None, None)\r\n scores = player_document[\"scor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the best players (as documents) in a certain average category. Returns the tuple `(, page, max_pages)`. `leaderboard` is any of `"acc"`, `"score"`, or `"contrib"`. `"score"` by default. `page` determines the top scores to be returned. Pagination is done on a 10 score per page basis; if `page10` exceeds the total nu...
async def get_top_tournament_players(leaderboard_field="score", page=1): db = client['players_and_teams'] player_collection = db['players'] player_count = await player_collection.estimated_document_count() max_page = math.ceil(player_count/10) if page < 0: page = 1 if page > m...
[ "async def get_top_tournament_teams(leaderboard_field=\"score\", page=1):\r\n db = client['players_and_teams']\r\n team_collection = db['teams']\r\n\r\n team_count = await team_collection.estimated_document_count()\r\n\r\n max_page = math.ceil(team_count/10)\r\n if page < 0:\r\n page = 1\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the best teams (as documents) in a certain average category. Returns the tuple (, page, max_pages). `leaderboard` is either `"acc"` or `"score"`. `"score"` by default. `page` determines the top scores to be returned. Pagination is done on a 10 score per page basis; if `page10` exceeds the total number of scores of ...
async def get_top_tournament_teams(leaderboard_field="score", page=1): db = client['players_and_teams'] team_collection = db['teams'] team_count = await team_collection.estimated_document_count() max_page = math.ceil(team_count/10) if page < 0: page = 1 if page > max_page: ...
[ "async def get_top_team_scores(team_name, page=1, mod=None):\r\n db = client['players_and_teams']\r\n team_collection = db['teams']\r\n team_document = await get_team_document(team_name)\r\n if team_document is None:\r\n return (None, None, None)\r\n scores = team_document[\"scores\"]\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the pool meta documents.
async def get_pool_metas(): db = client['mappools'] collection = db['meta'] cursor = collection.find() return (await cursor.to_list(length=100))
[ "def get_meta (self) :\n return self._meta", "def fetch_collection_meta(self, collection):\n url = self._url_for_collection(collection)\n res = self._make_request('get', url)\n return res.json()['data']", "async def get_meta_document():\r\n db = client[\"tournament_data\"]\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the player's best score on the specified map_id.
async def get_best_user_score(map_id, player): map_document = await get_map_document(map_id) if not map_document: return (None, None, None) player_document = await get_player_document(player) if not player_document: return (None, None, None) score_collection = client['ma...
[ "async def get_top_map_scores(map_id, page=1, pool=None):\r\n map_document = await get_map_document(map_id)\r\n if not map_document:\r\n return (None, None, None)\r\n scores = map_document[\"scores\"]\r\n\r\n max_page = math.ceil(len(scores)/10)\r\n if page < 0:\r\n page = 1\r\n if p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In order to clean up unused permissions, connect this handler to django's `pre_delete()
def remove_obj_permissions(sender, instance, **kwargs): # Do not listen to UserObjectPermission and GroupObjectPermission # instances. They should not have content type relations to itself. if not isinstance(instance, (UserObjectPermission, GroupObjectPermission)): lookup = Q(content_type=ContentTy...
[ "def organizer_pre_delete(sender, instance, **kwargs):\n for permission_code in Competition.get_organizer_permissions():\n remove_perm(permission_code, instance.user, instance.competition)", "def delete(self, request, *args, **kwargs):\n if request.user.is_superuser:\n return self.dest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enumerate the array to find those entries that satisfy Goldilocks' weight/temperature requirements.
def solve(weight, temperature, array): goodIdxs = [] for idx, val in enumerate(array): if val[0] >= weight and val[1] <= temperature: goodIdxs.append("{}".format(idx + 1)) return goodIdxs
[ "def known_mines(self):\n return {cell for cell in self.cells if len(self.cells)==self.count}", "def test_find_weight_changes():\n\n for f in fuels:\n weight_changes = x._find_weight_changes(f)\n weight = x.df_stoves[f][0]\n for i in (weight_changes[1:]):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new feed.
def add_feed(self, feed: Union[str, Feed]): url = feed_argument(feed) now = self._now() return self._storage.add_feed(url, now)
[ "def add_feed(self, feed: FeedInput) -> None:\n url = _feed_argument(feed)\n now = self._now()\n self._storage.add_feed(url, now)", "def create_feed(self, feed):\n path = \"api/feeds/\"\n return Feed.from_dict(self._post(path, feed._asdict()))", "def create_feed(self, feed, co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a feed. Also removes all of the feed's entries.
def remove_feed(self, feed: Union[str, Feed]): url = feed_argument(feed) return self._storage.remove_feed(url)
[ "def remove(self, feed):\n if isinstance(feed, dict):\n feed = feed.get('id')\n return kaa.feedmanager.remove_feed(feed)", "def delete_feed(self, feed: FeedInput) -> None:\n url = _feed_argument(feed)\n self._storage.delete_feed(url)", "def delete_feed(self, feed):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a userdefined title for a feed.
def set_feed_user_title(self, feed: Union[str, Feed], title: Optional[str]): url = feed_argument(feed) return self._storage.set_feed_user_title(url, title)
[ "def set_feed_user_title(self, feed: FeedInput, title: Optional[str]) -> None:\n url = _feed_argument(feed)\n return self._storage.set_feed_user_title(url, title)", "def change_feed_title(self, feed_url, title):\n return self._change_feed(feed_url, 'edit', title = title)", "def set_title(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a single feed.
def update_feed(self, feed: Union[str, Feed]): url = feed_argument(feed) rows = list(self._storage.get_feeds_for_update(url)) if len(rows) == 0: raise FeedNotFoundError(url) elif len(rows) == 1: self._update_feed(rows[0]) else: assert False, "s...
[ "def update(self, feed):\n if isinstance(feed, dict):\n feed = feed.get('id')\n return kaa.feedmanager.update_feed(feed)", "def _update_feed(self):\n # Update the last update field\n feed = feedparser.parse(self.url)\n self.last_update = datetime.date.today()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark an entry as read.
def mark_as_read(self, entry: Union[Tuple[str, str], Entry]): feed_url, entry_id = entry_argument(entry) self._storage.mark_as_read_unread(feed_url, entry_id, True)
[ "def mark_entry_as_read(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry)\n self._storage.mark_as_read_unread(feed_url, entry_id, True)", "def mark_as_read(self):\r\n self.hasBeenRead = True", "def mark_as_read(self):\n self.has_been_read = True", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark an entry as unread.
def mark_as_unread(self, entry: Union[Tuple[str, str], Entry]): feed_url, entry_id = entry_argument(entry) self._storage.mark_as_read_unread(feed_url, entry_id, False)
[ "def mark_entry_as_unread(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry)\n self._storage.mark_as_read_unread(feed_url, entry_id, False)", "def mark_unread(self, user, message_id):\n pass", "def mark_as_read(self, entry: Union[Tuple[str, str], Entry]):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark an entry as important.
def mark_as_important(self, entry: Union[Tuple[str, str], Entry]): feed_url, entry_id = entry_argument(entry) self._storage.mark_as_important_unimportant(feed_url, entry_id, True)
[ "def mark_entry_as_important(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry)\n self._storage.mark_as_important_unimportant(feed_url, entry_id, True)", "def mark_entry_as_unimportant(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark an entry as unimportant.
def mark_as_unimportant(self, entry: Union[Tuple[str, str], Entry]): feed_url, entry_id = entry_argument(entry) self._storage.mark_as_important_unimportant(feed_url, entry_id, False)
[ "def mark_entry_as_unimportant(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry)\n self._storage.mark_as_important_unimportant(feed_url, entry_id, False)", "def mark_entry_as_important(self, entry: EntryInput) -> None:\n feed_url, entry_id = _entry_argument(entry...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all the metadata values for a feed.
def iter_feed_metadata( self, feed: Union[str, Feed] ) -> Iterable[Tuple[str, JSONType]]: feed_url = feed_argument(feed) return self._storage.iter_feed_metadata(feed_url)
[ "def get_feed_metadata(\n self,\n feed: FeedInput,\n key: Optional[str] = None,\n ) -> Iterable[Tuple[str, JSONType]]:\n\n # get_feed_metadata(feed, *, key=None) -> (key, value), ...\n feed_url = _feed_argument(feed)\n return self._storage.iter_metadata((feed_url,), key)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set metadata for a feed.
def set_feed_metadata(self, feed: Union[str, Feed], key: str, value: JSONType): feed_url = feed_argument(feed) self._storage.set_feed_metadata(feed_url, key, value)
[ "def set_feed_metadata_item(\n self, feed: FeedInput, key: str, value: JSONType\n ) -> None:\n feed_url = _feed_argument(feed)\n self._storage.set_metadata((feed_url,), key, value)", "def set_metadata(self, metadata, clear=False):\n self.client.set_object_metadata(self.container, se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete metadata for a feed.
def delete_feed_metadata(self, feed: Union[str, Feed], key: str): feed_url = feed_argument(feed) self._storage.delete_feed_metadata(feed_url, key)
[ "def delete_feed_metadata_item(self, feed: FeedInput, key: str) -> None:\n feed_url = _feed_argument(feed)\n self._storage.delete_metadata((feed_url,), key)", "def delete_feed(self, feed):\n path = \"api/feeds/{0}\".format(feed)\n self._delete(path)", "def delete_feed(self, feed: Fee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper for getting profiles path from module installation location
def get_profiles_path(): module_path = get_module_path() profiles_path = os.path.join(module_path, PROFILES) return profiles_path
[ "def get_user_profile_path():\n config_path = Path.home() / \".bbs_build_profiles\"\n\n if config_path.exists() and os.access(config_path, os.R_OK):\n print(f\"Using user configuration: {config_path}\", file=sys.stderr)\n return config_path\n\n return None", "def get_system_profile_path():\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper for getting templates path from module installation location
def get_templates_path(): module_path = get_module_path() templates_path = os.path.join(module_path, TEMPLATES) return templates_path
[ "def get_template_dir(self) -> str:", "def template_path(self):\n\n return super().template_path+[os.path.join(os.path.dirname(__file__), \"templates\")]", "def get_template_dir():\n return os.path.join(get_base_dir(), TEMPLATE_DIR)", "def templates_repo() -> str:\n repo_path = os.path.abspath(\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select profile path and filename (user defined or from package)
def select_profile_file(profile_name): profiles_path = get_profiles_path() selected_template_path = profiles_path selected_template_name = profile_name user_extra_path = os.path.join(PROFILES, profile_name) if os.path.isfile(user_extra_path): # user path omitting 'profile' dir profile_tmp_...
[ "def find_profile_path(filename):\n try:\n out = subprocess.check_output(\n [\"colormgr\", \"find-profile-by-filename\", filename]\n )\n except subprocess.CalledProcessError:\n return None\n\n object_path = None\n for line in out.decode(\"utf8\").split(\"\\n\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select template dir path (user defined or packaged)
def select_template_dir(template_name): templates_path = get_templates_path() selected_template_path = os.path.join(templates_path, template_name) user_extra_path = os.path.join(TEMPLATES, template_name) if os.path.isdir(user_extra_path): selected_template_path = user_extra_path LOG.debu...
[ "def get_template_dir(self) -> str:", "def template_path(self):\n\n return super().template_path+[os.path.join(os.path.dirname(__file__), \"templates\")]", "def get_template_dir():\n return os.path.join(get_base_dir(), TEMPLATE_DIR)", "def template():\n template_dir = os.path.join(googkit_root(),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that output path is actually existing directory
def ensure_output_path(output_path): if not os.path.isdir(output_path): if os.path.isfile(output_path): raise IOError( 'Output path "%s" already exists and it is not a directory!' % output_path ) os.makedirs(output_path, exist_ok=True) ...
[ "def check_or_create_output_dir(self):\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)", "def verifyOutputDir(self, dirname):\n print \"Verifing output dir %s\" % dirname\n if (not path.exists(dirname)):\n print \"Path doesn't exist\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a template filename and get output file name
def get_output_filename(template_name): match = REX_TEMPLATE_TO_OUTPUT.match(template_name) output_filename = template_name if match: output_filename = match.group(1) return output_filename
[ "def get_template_name(target_file):\n return '{}.j2'.format(os.path.basename(target_file))", "def parse_template(self, template_name):\n assert template_name.endswith(\".in\")\n\n with open(template_name) as inp:\n template = jinja2.Template(inp.read())\n with open(template_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the total amount of created coins is equal to the total amount of consumed coins.
def verify_balance(self): total_created = 0 total_consumed = 0 for consumed_coin in self.consumed_coins: total_consumed += consumed_coin.value for created_coin in self.created_coins: total_created += created_coin.value return total_consumed == total_crea...
[ "def test_wallet_length(self):\n coins = [\"Quarter\", \"Dime\", \"Nickel\"]\n self.customer.add_coins_to_wallet(coins)\n length = len(self.customer.wallet.money)\n self.assertEqual(length,91)", "def validateMint(self, maxCoinsToCreate):\n if len(self.inputs) != 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new rank object
def __init__(self, rank_name, rank_strenght): self.rank_name = rank_name self.rank_strenght = rank_strenght
[ "def new_with(self,*args,**kwargs):\n newspec=dict(self.__spec)\n newspec.update(*args,**kwargs)\n return JobRankSpec(**newspec)", "def setRank(self,rank):\n self.rank = rank", "def set_rank(self, vert, newrank):\n \n pass", "def rank(self, rank):\n if rank not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the strenght of the rank
def get_rank_strenght(self): return self.rank_strenght
[ "def get_strenght(self):\n return 10 - self.get_agility()", "def get_estimated_rank(self):\n # At the moment the rank returned by this function is normally too high for either\n # my machine or the tensorly library to handle, therefore I have made it just return 1 for right now\n if fl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the name of the rank
def get_rank_name(self): return self.rank_name
[ "def name(self) -> str:\n return Card.__rank_names.get(self._rank, str(self._rank))", "def rank_display(self) -> str:\n _rank: str = dict(RANKS)[str(self.rank)]\n return _rank", "def __str__(self):\n\n return self.rank_name.capitalize()", "def get_rank_value(rank):\n if rank < 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the name of the rank capitalized
def __str__(self): return self.rank_name.capitalize()
[ "def rank_display(self) -> str:\n _rank: str = dict(RANKS)[str(self.rank)]\n return _rank", "def rank_print(text: str):\n rank = dist.get_rank()\n # Keep the print statement as a one-liner to guarantee that\n # one single process prints all the lines\n print(f\"Rank: {rank}, {text}.\")",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function generates the texts to be added to each participant for each round.
def generate_text_lists(self): for p in self.get_players(): p.task_text = Constants.text_list[self.round_number - 1] print("[[ APP_1_TRANSCRIPTION ]] - SUBSESSION - generate_text_lists().............round_number: ", self.round_number) print("[[ APP_1_TRANSCR...
[ "def text(game_num, textp2, last_person):\n\n textpart1 = (\"Game #{}. Play sequence: \".format(game_num + 1))\n # textpart2 joins all the tries from the list textp2 to convert it in \n # the required format = 1-1-2-2-3-3-2-2-1\n textpart2 = \"-\".join(textp2)\n if last_person == 'player 1':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function assigns treatment values to the participants using itertools.cycle
def generate_treatments(self): treatment = itertools.cycle(Constants.treatments) for p in self.get_players(): p.treatment = next(treatment) print("[[ APP_1_TRANSCRIPTION ]] - SUBSESSION - generate_treatments().............round_number: ", self.round_number) ...
[ "def __permutate_assignemnts(self, src, trucks, locations):\n\n # Following the intuition behind the best answer in:\n # https://stackoverflow.com/questions/22939260/every-way-to-organize-n-objects-in-m-list-slots\n # The \"slots\" are the places available on each destination. i.e. The shovel ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function counts the number of correct answers and the accumulated payoff. It depends on the round number. Check the self.in_all_rounds() and self.in_previous_rounds()
def accumulated_variables(self): if self.round_number == 1: self.accumulated_is_correct = 0 self.accumulated_payoff = 0 elif 1 < self.round_number < Constants.num_rounds: self.accumulated_is_correct = sum(filter(None, [p.is_correct for p in self.in_previous_rounds()])...
[ "def calculate_results() -> int:\r\n all_answers: list = []\r\n for question in Question.objects.all():\r\n question_accuracy: int = all([a.is_answered_correct() for a in question.answer_set.all()])\r\n all_answers.append(question_accuracy)\r\n\r\n percent: float = len([a for a in all_answers...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function affects accumulated_payoff from the very last round depending on treatment and on Constants.shock. Besides, it converts UME into pesos.
def final_payoff_calculator(self): if self.treatment == 1: self.final_payoff = self.accumulated_payoff * Constants.shock self.final_payoff_cop = int(self.accumulated_payoff * Constants.shock * Constants.cop_per_ume) elif self.treatment == 0: self.final_payoff = self.a...
[ "def get_Adjust(self):\n if \"AdjustPrb\" in self.time_vary:\n self.shocks[\"Adjust\"] = self.AdjustDstn.draw(\n np.maximum(self.t_cycle - 1, 0) if self.cycles == 1 else self.t_cycle\n )\n else:\n self.shocks[\"Adjust\"] = self.AdjustDstn.draw(self.Agent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the files the datastores.
def _retrieve_files(self): if self._search_tasks is None: if self._datacenter is not None: datastores = self._datacenter.datastore else: datastores = self._driver.ex_list_datastores() filter_query_flags = vim.FileQueryFlags( fil...
[ "def get_data_files ():\n installpath = os.path.join (\"share\", \"ocempgui\")\n path = \"data\"\n dirs = get_directory_list (path)\n filedict = {}\n for path in dirs:\n files = glob.glob (os.path.join (path, \"*.*\"))\n if files:\n filedict[path] = files\n return get_inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterate available volumes (on all datastores).
def iterate_volumes(self, node=None, ex_datacenter=None): if node is not None: if ex_datacenter: raise ValueError( "Cannot list the volumes for the datacenter and the " "virtual machine at the same time") virtual_machine = self.ex_g...
[ "def _iter_volumes(self):\n if self.volumes:\n for volume_name, container_path in self.volumes.iteritems():\n if \"/\" in volume_name:\n # if a / is found in the name, assume it's a full path specified on the host\n host_path = volume_name\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the VMWare datacenter for a given ID.
def _get_datacenter_by_id(self, datacenter_id): if isinstance(datacenter_id, vim.Datacenter): return datacenter_id datacenter_ids = self._get_datacenter_ids_map() if datacenter_id not in datacenter_ids: raise ValueError(( "Unknown datacenter ID '{}', avail...
[ "def get_datacenter(self, name):\n root_folder = self._get_root_folder()\n for mor in root_folder.childEntity:\n if name == mor.name:\n return Datacenter(self.si, mor)", "def get_data_center(datacenter, key='name'):\n logger.info(\"Get datacenter %s by %s\", datacenter, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the datastore info to datacenter map.
def _get_datastores_info_map(self): if 'datastores_info_map' not in self._cache: self._cache['datastores_info_map'] = { datastore.info: datacenter for datacenter in self.ex_list_datacenters() for datastore in datacenter.datastore} return self._...
[ "def _get_dsmap(self):\n return self.__dsmap", "def _get_datacenter_ids_map(self):\n if 'datacenter_ids_map' not in self._cache:\n # pylint: disable=protected-access\n self._cache['datacenter_ids_map'] = {\n datacenter._moId: datacenter\n for datacente...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the datacenter ID to datacenter object map.
def _get_datacenter_ids_map(self): if 'datacenter_ids_map' not in self._cache: # pylint: disable=protected-access self._cache['datacenter_ids_map'] = { datacenter._moId: datacenter for datacenter in self.ex_list_datacenters()} return self._cache['d...
[ "def _get_datastores_info_map(self):\n if 'datastores_info_map' not in self._cache:\n self._cache['datastores_info_map'] = {\n datastore.info: datacenter\n for datacenter in self.ex_list_datacenters()\n for datastore in datacenter.datastore}\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the datacenter ID for a given datastore URL.
def _get_datacenter_id_by_url(self, url): if url and isinstance(url, list): url = url[0] if isinstance(url, vim.vm.ConfigInfo.DatastoreUrlPair): url = str(url.url) if not url: return try: url = url.split('/') volume_id = url[ur...
[ "def get_domain_id(self, url):\n return self.get_domain_ids([url])[0]", "def get_id(self, url):\n return self.get_ids([url])[0]", "def get_category_id(url):\n return base.get_structure_id(url)", "def get_cluster_id():\n resolver = dns.resolver.Resolver()\n cluster_id = resolver.query('d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the creation timestamps of the VMs from the event history.
def _query_node_creation_times(self, virtual_machine=None): if not self._created_at_limit: return {} if self._has_cache('node_creation_times'): return self._get_cache('node_creation_times') created_events = self._query_events( event_type_id=[ ...
[ "def _query_volume_creation_times(self, virtual_machine=None):\n if not self._created_at_limit:\n return {}\n\n if self._has_cache('volume_creation_times'):\n return self._get_cache('volume_creation_times')\n\n reconfigure_events = self._query_events(\n event_ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the creation timestamps of the extra volumes from the event history.
def _query_volume_creation_times(self, virtual_machine=None): if not self._created_at_limit: return {} if self._has_cache('volume_creation_times'): return self._get_cache('volume_creation_times') reconfigure_events = self._query_events( event_type_id='VmReco...
[ "def get_volumes(instance):\n volumes = []\n for tag in instance['Tags']:\n if tag['Key'] == 'Name':\n volume_tag_reference = \"%s_data\" % tag['Value']\n\n for volume in instance['volumes']:\n if volume['volume_tags'] != None:\n for volume_tag in volume['volume_tags']:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches VMs for a given instance_uuid or Node object.
def ex_get_vm(self, node_or_uuid): if isinstance(node_or_uuid, Node): node_or_uuid = node_or_uuid.extra['instance_uuid'] vm = self.connection.content.searchIndex.FindByUuid( None, node_or_uuid, True, True) if not vm: raise LibcloudError("Unable to locate Virtu...
[ "def get_vm_mor_for_uuid(session, vm_uuid):\n\n vm_mor = cache.VCCache.get_vm_mor_for_uuid(vm_uuid)\n if vm_mor:\n return vm_mor\n # TODO(romilg) : use config.uuid instead of\n # config.extraConfig[\"nvp.vm-uuid\"] once fixed in nova.\n vm_mors = session._call_method(vim_util, \"get_objects\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of datacenters.
def ex_list_datacenters(self): return list(VSpherePropertyCollector(self, vim.Datacenter))
[ "def get_datacenters_list():\n return util.get(abs_link=False)", "def get_datacenters_names_list():\n return [cl.get_name() for cl in get_datacenters_list()]", "def get_cluster_centers(self):\n pass", "def get_cluster_centers(self):\n return None", "def get_datacenters(service_instance):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches Node for a given ``uuid``.
def ex_get_node_by_uuid(self, uuid): return self._to_node(vm_entity=self.ex_get_vm(uuid))
[ "def getNodeById(self, uuid):\n nodes = [i for i in self.scene.items() if isinstance(i, Node)]\n for node in nodes:\n if node.uuid == uuid:\n return node\n return None", "def find_node(nodes, string_id):\n\n for node in nodes:\n current_id = node.getAttribu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
memoize decorator that applies the function key to the arguments in order to retrieve the key to use in the cache dictionary.
def keymemo(key): def _memo(fn): """the memoize decorator itself.""" cache = {} @_functools.wraps(fn) def _fn(*args): if key: args = key(*args) try: ret = cache[args] except KeyError: ret = cache[args] = fn(*args) return ret ...
[ "def memoize(*args, **kwargs):\n if args:\n assert len(args) == 1\n assert not kwargs\n return memoize()(args[0])\n key_func = kwargs.pop('key_func', None)\n if kwargs:\n raise TypeError('memoize() got unexpected keyword arguments: %s', ', '.join(kwargs))\n\n return _memory_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the memoize decorator itself.
def _memo(fn): cache = {} @_functools.wraps(fn) def _fn(*args): if key: args = key(*args) try: ret = cache[args] except KeyError: ret = cache[args] = fn(*args) return ret _fn._cache = cache return _fn
[ "def memoize(function):\n cache = {}\n @functools.wraps(function)\n def _memoize(*args):\n if args in cache:\n return cache[args]\n result = function(*args)\n cache[args] = result\n return result\n return function", "def memoize(*args, **kwargs):\n if args:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the instancememoize decorator itself.
def _instancememo(fn): cache_name = '_cache_' + fn.__name__ def _get_cache(self, fn): """cache is stored in the self namespace, retrieved at runtime.""" try: return getattr(self, cache_name) except AttributeError: setattr(self, cache_...
[ "def memoize_instance(instance: T) -> None:\n for name, fn in inspect.getmembers(instance, inspect.ismethod):\n setattr(instance, name, memoize(fn))", "def _memo(fn):\n\n cache = {}\n\n @_functools.wraps(fn)\n def _fn(*args):\n if key: args = key(*args)\n try: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This operator generates a onehot Tensor from input Tensor. If input Tensor's rank is `N`, the corresponding onehot Tensor's rank is `N+1`. Flow.one_hot is aligned with tf.one_hot operator. If you want to use torch version, you can turn on_value is set to 1, off_value is set to 0.
def one_hot( input, num_classes: int = -1, on_value: Union[int, float] = 1, off_value: Union[int, float] = 0, ): if input.is_consistent: raise ValueError( "A consistent tensor can not be applied to onehot, and use tensor.to_local() to convert it to local tensor first." ) ...
[ "def one_hot(indices, on_value, off_value, depth, axis, dtype):\n return cpp.one_hot(indices, on_value, off_value, depth, axis, dtype)", "def to_one_hot(y, n_dims=None):\n y_tensor = y.view(-1, 1)\n n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1\n y_one_hot = torch.zeros(y_ten...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function which will yield all documents as dicts with `id` (must be unique) and `content` which will contain the data you want to display. The `content` field can be a list to have mulitple columns in the UI.
def dataGenerator(): for current in data: author = current["author"] text = current["text"] yield {"id": author, "content": {"title": author, "text": text}}
[ "def get_documents():\n\n DB_USER = app.config.get('DB_USER', 'postgres')\n DB_PASSWORD = app.config.get('DB_PASSWORD', 'dbpass')\n DB_NAME = app.config.get('DB_NAME', 'envirolens')\n\n DB.connect(\n database=DB_NAME,\n user=DB_USER,\n password=DB_PASSWORD\n )\n\n if DB.cursor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a ServicePrincipalCredentials object using values from environment variables
def __create_service_principal_credentials(): # service principal's app id; `<your-app-id>` app_id = os.environ.get("AZURE_CLIENT_ID", None) # one of the service principal's client secrets; `<your-password>` client_secret = os.environ.get("AZURE_CLIENT_SECRET", None) # id of the principal's Azure A...
[ "def patch_using_env(self):\n if self.cred_properties:\n credentials_config = self.cred_properties\n\n user = getenv(\"HERE_USER_ID\") or credentials_config[\"user\"]\n client = getenv(\"HERE_CLIENT_ID\") or credentials_config[\"client\"]\n key = (\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a ResourceManagementClient object using the subscription ID from environment variables
def __create_resource_management_client(): subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", None) if subscription_id is None: return None return ResourceManagementClient( credential=__create_service_principal_credentials(), subscription_id=subscription_id )
[ "def _create_resource_agent_client(self, sub_id, sub_resource_id):\n log.debug(\"%r: _create_resource_agent_client: sub_id=%r, sub_resource_id=%r\",\n self._platform_id, sub_id, sub_resource_id)\n\n a_client = ResourceAgentClient(sub_resource_id, process=self)\n\n log.debug(\"%...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a CommunicationServiceManagementClient object using a Subscription ID in an environment variable
def __create_communication_management_client(credentials): subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", None) if subscription_id is None: return None return CommunicationServiceManagementClient(credentials, subscription_id)
[ "def __create_resource_management_client():\n\n subscription_id = os.environ.get(\"AZURE_SUBSCRIPTION_ID\", None)\n if subscription_id is None:\n return None\n\n return ResourceManagementClient(\n credential=__create_service_principal_credentials(),\n subscription_id=subscription_id\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Communication Service
def __create_communication_service(args): print("\nCreate...") acs_client = __get_communication_management_client() resource = CommunicationServiceResource(location="global", data_location = "UnitedStates") operation = acs_client.communication_service.begin_create_or_update(args.resource_group_name, ar...
[ "def service_constructor(self):\n raise NotImplementedError", "def create_service():\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n store = file.Storage('token.json')\n cred...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch a Communication Service
def __get_communication_service(args): print("\nGet...") acs_client = __get_communication_management_client() try: resource = acs_client.communication_service.get(args.resource_group_name, args.resource_name) __print_resource(resource) except HttpResponseError: print("Resource ...
[ "def _get_service(self):\n\n service = self._selector.get_service(0) # Don't wait\n if service is None:\n raise err.OctpServiceAllFault('Not one service is available!')\n\n return service", "def get_service(self, id):\n return self._request('get', path='/services/{}'.format...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a Communication Service
def __update_communication_service(args): print("\nUpdate...") acs_client = __get_communication_management_client() tags = {} if args.keyvalues is not None: tags = {"tags": dict(args.keyvalues)} resource = acs_client.communication_service.update(args.resource_group_name, args.resource_nam...
[ "def update_service(events, context):\n config = Config(retries={'max_attempts': 20, 'mode': 'standard'})\n ecs_client = boto3.client('ecs', config=config)\n\n service_definition = {\n \"service\": events['ServiceName'],\n \"cluster\": events['ClusterName'],\n \"taskDefinition\": event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a Communication Service
def __delete_communication_service(args): print("\nDelete...") acs_client = __get_communication_management_client() acs_client.communication_service.begin_delete(args.resource_group_name, args.resource_name) print("Resource Deleted")
[ "def advapi32_DeleteService(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"hService\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)", "def delete_mgmt_service(self):\n return self._delete(\"service\", ApiService, api_version=6)", "def delete_servic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all Communication Services in the subscription
def __list_communication_service_by_subscription(args): print("\nList by subscription...") acs_client = __get_communication_management_client() resources = acs_client.communication_service.list_by_subscription() print("Found resources: ") for resource in resources: print("") __print...
[ "def getServicesList( self ):\n\n res = self.rsS.getServicesList()\n if not res[ 'OK' ]:\n raise RSSException, where( self, self.getServicesList ) + \" \" + res[ 'Message' ]\n\n return res", "def __list_communication_service_by_resource_group(args):\n print(\"\\nList by resource group...\")\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all Communication Services in the resource group
def __list_communication_service_by_resource_group(args): print("\nList by resource group...") acs_client = __get_communication_management_client() resources = acs_client.communication_service.list_by_resource_group(args.resource_group_name) print("Found resources: ") for resource in resources: ...
[ "def __list_communication_service_by_subscription(args):\n print(\"\\nList by subscription...\")\n\n acs_client = __get_communication_management_client()\n resources = acs_client.communication_service.list_by_subscription()\n print(\"Found resources: \")\n for resource in resources:\n print(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Regenerate the Primary or Secondary key pair
def __regenerate_key(args): print("\nRegeneration key...") acs_client = __get_communication_management_client() key_type = {"key_type": args.type} key = acs_client.communication_service.regenerate_key(args.resource_group_name, args.resource_name, RegenerateKeyParameters(**key_type)) print(key)
[ "def reset_key(self):\n self.key = self._default_manager.generate_key()\n self.reset_at = now()\n self.save(update_fields=['key', 'reset_at'])", "def __generate_inv_key(self):\n \n self.__inv_key = self.__key\n return self.__inv_key", "def generateKeyPair(cls):", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link a Notification Hub to the Communication Service
def __link_notification_hub(args): print("\nLink Notification Hub...") # Resource ID of the Notification Hub you want to link; `<your-tenant-id>` notification_hub_resource_id = os.environ.get("AZURE_NOTIFICATION_HUB_ID", None) # Connection String of the Notification Hub you want to link; `<your-tenan...
[ "def link_notification_hub(\n self,\n resource_group_name: str,\n communication_service_name: str,\n link_notification_hub_parameters: Optional[\"_models.LinkNotificationHubParameters\"] = None,\n **kwargs: Any\n ) -> \"_models.LinkedNotificationHub\":\n cls = kwargs.pop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Resource Group for the given name
def __create_resource_group(args): resource_client = __create_resource_management_client() resource_client.resource_groups.create_or_update( args.resource_group_name, {"location": "westus"} ).result()
[ "def Create(iam,groupname: str,tag='/'):\n\t\t\t\treturn iam.resource.Group(groupname).create(Path=AWS.preptag(tag))", "def resource_group_set(name: str, location: str) -> ResourceGroup:\n command: List[str] = ['az', 'group', 'create', f'--name={name}', f'--location={location}']\n sh.print_command(command)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the given Resource Group Exists
def __resource_group_exists(args): resource_client = __create_resource_management_client() try: resource_client.resource_groups.get(args.resource_group_name) except ResourceNotFoundError: return False return True
[ "def group_exists(self, group_name):\n try:\n self.rmc.resource_groups.get(group_name)\n return True\n except CloudError:\n return False", "def GroupExists(self, groupname):\n return groupname in self._groups", "def _check_group_exists(group_id):\n group = _s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define the parser for the list keys command.
def __setup_list_keys(subparsers, parent_parser): parser = subparsers.add_parser('list-keys', help='List the Primary and Secondary key pairs') parser.add_argument('resource_group_name', type=str) parser.add_argument('resource_name', type=str) parser.set_defaults(func=__list_keys)
[ "def read_list_cmd(self, liste_cmd):\r\n return dict([(cmd, self.__getattribute__(cmd)) for cmd in liste_cmd])", "def keys(self):\n return _NamelistKeysView(self)", "def keys(self, section):\n return self.parser.options(section)", "def list_key_pairs(self):\r\n raise NotImplemented...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define the parser for the regenerate key command.
def __setup_regenerate_key(subparsers, parent_parser): parser = subparsers.add_parser('regenerate-key', help='Regenerate the Primary or Secondary key pair') parser.add_argument('resource_group_name', type=str) parser.add_argument('resource_name', type=str) parser.add_argument('type', type=str, choices=...
[ "def _ParseKey(self, mediator, registry_key, value_name):", "def __regenerate_key(args):\n print(\"\\nRegeneration key...\")\n\n acs_client = __get_communication_management_client()\n\n key_type = {\"key_type\": args.type}\n key = acs_client.communication_service.regenerate_key(args.resource_group_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define the parser for the link notification hub command.
def __setup_link_notification_hub(subparsers, parent_parser): parser = subparsers.add_parser('link-notification-hub', help='Link a Notification Hub to the Communication Service') parser.add_argument('resource_group_name', type=str) parser.add_argument('resource_name', type=str) parser.set_defaults(func...
[ "def parse_link(self, link):\n # Split source and destination node descriptions\n source, dest = link.split(\"->\")\n\n # Parse the source and destination parameters\n source_node_name, source_plug_name, source_node, source_plug = \\\n self.parse_parameter(source)\n des...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Truncate context_tokens first, from the left, then question_tokens and choice_tokens
def _truncate_tokens(context_tokens, question_tokens, choice_tokens, max_length): max_context_len = max_length - len(question_tokens) - len(choice_tokens) if max_context_len > 0: if len(context_tokens) > max_context_len: context_tokens = context_tokens[-max_context_len:] ...
[ "def left_truncations (tokens):\n while tokens:\n yield tokens\n tokens = tokens [: -1]", "def right_truncations (tokens):\n while tokens:\n yield tokens\n tokens = tokens [1 :]", "def _truncate(self, tokens):\n\t\tif len(tokens) > self._max_sequence_length:\n\t\t\ttokens = tok...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns definitions of common audio features.
def AudioFeatures(mfcc_shape=None, cpc8k_shape=None): features = {'audio/id': _Feature([], tf.int64)} if mfcc_shape is not None: features['audio/mfccs'] = _Feature(mfcc_shape) if cpc8k_shape is not None: features['audio/cpc8k/features'] = _Feature(cpc8k_shape) return features
[ "def extract_features(sounds: List[Tuple[Any, Any]], feature_names: Iterable[str]) -> np.ndarray:\n all_features = []\n for index, (audio, sample_rate) in enumerate(sounds):\n print(\"##### Processing features for audio sample \" + str(index))\n stft = np.abs(librosa.stft(audio))\n if isi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the filesystem path of the blaze catalog path
def get_fsdir(self, dir): if is_abs_bpath(dir): return path.join(self.root, dir[1:]) else: raise ValueError('Expected absolute blaze catalog path: %r' % dir)
[ "def default_catalog_path(self) -> Path:\n\n try:\n return self._default_catalog_path\n except AttributeError:\n pass\n with ir.path(\"pulsaroftheday.catalogs.atnf.data\", \"psrcat.db\") as db:\n self._default_catalog_path = db\n return self._default_cata...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a blaze catalog path points to an existing array
def isarray(self, dir): if is_abs_bpath(dir): return path.isfile(path.join(self.root, dir[1:]) + '.array') else: raise ValueError('Expected absolute blaze catalog path: %r' % dir)
[ "def contains_array(store, path=None):\n path = normalize_storage_path(path)\n prefix = _path_to_prefix(path)\n key = prefix + array_meta_key\n return key in store", "def hasNonPortablePaths(self): #$NON-NLS-1$\r\n return len(self.elems) > 0", "def containsPath(self, *args):\n return _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a blaze catalog path points to an existing directory
def isdir(self, dir): if is_abs_bpath(dir): return path.isdir(path.join(self.root, dir[1:])) else: raise ValueError('Expected absolute blaze catalog path: %r' % dir)
[ "def dir_exists(self, path=''):\n if path == '':\n return True\n else:\n return False", "def is_checkout_dir(self, path):\n\t\treturn os.path.exists(os.path.join(path, Checkout.PIPELINE_FILENAME))", "def directory_exists(path):\n return os.path.isdir(path) and os.path.exis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all the arrays in the provided blaze catalog dir
def ls_arrs(self, dir): if is_abs_bpath(dir): fsdir = path.join(self.root, dir[1:]) listing = os.listdir(fsdir) return sorted([path.splitext(x)[0] for x in listing if x.endswith('.array')]) else: raise ValueError('Expected absolute blaz...
[ "def ls(self, dir):\n if is_abs_bpath(dir):\n fsdir = path.join(self.root, dir[1:])\n listing = os.listdir(fsdir)\n res = [path.splitext(x)[0] for x in listing\n if x.endswith('.array')]\n res += [x for x in listing\n if path.is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all the directories in the provided blaze catalog dir
def ls_dirs(self, dir): if is_abs_bpath(dir): fsdir = path.join(self.root, dir[1:]) listing = os.listdir(fsdir) return sorted([x for x in listing if path.isdir(path.join(fsdir, x))]) else: raise ValueError('Expected absolute blaze catal...
[ "def ls(self, dir):\n if is_abs_bpath(dir):\n fsdir = path.join(self.root, dir[1:])\n listing = os.listdir(fsdir)\n res = [path.splitext(x)[0] for x in listing\n if x.endswith('.array')]\n res += [x for x in listing\n if path.is...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of all the arrays and directories in the provided blaze catalog dir
def ls(self, dir): if is_abs_bpath(dir): fsdir = path.join(self.root, dir[1:]) listing = os.listdir(fsdir) res = [path.splitext(x)[0] for x in listing if x.endswith('.array')] res += [x for x in listing if path.isdir(path.joi...
[ "def ls_arrs(self, dir):\n if is_abs_bpath(dir):\n fsdir = path.join(self.root, dir[1:])\n listing = os.listdir(fsdir)\n return sorted([path.splitext(x)[0] for x in listing\n if x.endswith('.array')])\n else:\n raise ValueError('Expected a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The purpose of this function is to check whether CUDA is available and whether we should run on single or multi gpu mode.
def get_cuda_info(): use_cuda = False multi_gpu = False if torch.cuda.is_available() and os.environ['CUDA_VISIBLE_DEVICES'] != "": gpu_ids = os.environ['CUDA_VISIBLE_DEVICES'].split() use_cuda = True logging.info('CUDA support is active') if len(gpu_ids) > 1: lo...
[ "def _is_cuda_available():\n dev = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n assert dev == torch.device(\"cuda\")", "def check_cuda(self):\n if self.cfg.use_cuda:\n return True\n return False", "def check_cuda():\n is_available = cuda.is_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the Qvalue of action in state from the value function stored in self.values.
def computeQValueFromValues(self, state, action): "*** YOUR CODE HERE ***" #Just to note: #Q(s,a) = \sum_{s'} T(s,a,s')[R(s,a,s') + \gammaV(s')] # T is list of (nextState, probability) T = self.mdp.getTransitionStatesAndProbs(state, action) gamma = self.discount ...
[ "def calcQValue(self, state, action):\n return self.q_values[(state, action)]", "def getQValue(self, state, action):\n qValue = 0\n for action, probability in self.mdp.getTransitionStatesAndProbs\\\n (state,action):\n qValue += probability * self.getValue(action)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
crop an image along with the given axis
def crop(img, start, end, axis='x'): assert axis.lower() in ['z', 'y', 'x', 'd', 'h', 'w'], str(axis) + 'is not (D, H, W) or (z, y, x) !' if axis.lower() in ['z', 'd']: img = img[:, start:end, :, :] elif axis.lower() in ['h', 'y']: img = img[:, :, start:end, :] else: img = img[:...
[ "def cropImage():", "def crop(img, side):\n side = side // 2\n y = img.shape[0] // 2\n x = img.shape[1] // 2\n print(y, x)\n print(img.shape)\n return img[y - side:y +side, x - side : x+side]", "def crop_image(img, box):\n return img.crop(box)", "def _image_crop(self, crop_limits):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an sitk interpolator object for the given string.
def get_sitk_interpolator(interpolator): if interpolator == 'nearest': return sitk.sitkNearestNeighbor elif interpolator == 'linear': return sitk.sitkLinear elif interpolator == 'cubic': return sitk.sitkBSpline elif interpolator == 'label_gaussian': return sitk.sitkLabelG...
[ "def interpolate(self, string, stacklevel=1, name=None):\n return self.project.interpolate_ns(\n string, self.create_namespace(), stacklevel=stacklevel+1, name=name)", "def resolve_interpolates(self, s, context):\n interps = interpolate.findall(s)\n\n for i in interps:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This decorator registers functions to be used as extractors. Only functions decorated with this are considered metadata extractors, and will be called when the file extension matches the configured one.
def file_extractor(extension): def deco(f): assert extension not in file_extractors, f"extension {extension} already registered" file_extractors[extension] = f return f return deco
[ "def metadata(func):\n # bit of a hack to get class variables\n class_attrs = sys._getframe(1).f_locals\n suff = class_attrs.get('extractor_suffix')\n exs = class_attrs.get('metadata_extractors')\n\n # check name\n name = func.__name__\n if not name.endswith(suff):\n raise NameError(name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the similarity between two sentences a, b
def text_similar_score(a: list, b: list) -> float: from difflib import SequenceMatcher assert type(a) is str assert type(b) is str a = "".join(a).lower().replace(" ", "") b = "".join(b).lower().replace(" ", "") return SequenceMatcher(None, a, b).ratio()
[ "def get_sentences_similarity(words_in_sentence_1, words_in_sentence_2):\n matches = map(lambda w: 1 if w in words_in_sentence_1 else 0,\n words_in_sentence_2)\n\n if len(matches) <= 0:\n return 0\n\n return 2.0 * sum(matches) / (len(words_in_sentence_1) +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Just try producing a PhoSim InstanceCatalog from a fake ObservationMetaData, using protoDC2 (to make sure we don't break the whole interface)
def test_disk_phosim_catalog(self): db = diskDESCQAObject_protoDC2(yaml_file_name='protoDC2') db.field_ra = self.field_ra db.field_dec = self.field_dec obs = ObservationMetaData(pointingRA=self.field_ra+0.2, pointingDec=self.field_dec-0.2, ...
[ "def initCatalog(parametro):\n catalog = model.newCatalog(parametro) \n return catalog", "def __init__(self, catalog=None):\n self.catalog = catalog or util.GetIosCatalog()\n models = self.catalog.models\n versions = self.catalog.versions\n locales = self.catalog.runtimeConfiguration.locales\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that DESCQAObjects now return varParamStr='None' by default
def test_default_varParamStr(self): db = diskDESCQAObject_protoDC2(yaml_file_name='protoDC2') db.field_ra = self.field_ra db.field_dec = self.field_dec obs = ObservationMetaData(pointingRA=self.field_ra-0.7, pointingDec=self.field_dec+1.0) clas...
[ "def test_get_agent_parameters(self):\n pass", "def set_default_qa_param_desc_selection(self):\n qa_def = self.cmbQADef.currentText()\n index = self.cmbQADef.findText(qa_def, QtCore.Qt.MatchFixedString)\n qa_params = self.qa_analytics.qa_defs[index].Name.unique().tolist()\n\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CTC Beam search decoder. It utilizes beam search to approximately select top best decoding labels and returning results in the descending order. The implementation is based on Prefix Beam Search
def ctc_beam_search_decoder(probs_seq, beam_size, vocabulary, cutoff_prob=1.0, cutoff_top_n=40, ext_scoring_func=None, nproc=False): # dimension che...
[ "def _generate_beam_search(\n self,\n input_ids,\n cur_len,\n max_length,\n min_length,\n do_sample,\n early_stopping,\n temperature,\n top_k,\n top_p,\n repetition_penalty,\n no_repeat_ngram_size,\n bad_words_ids,\n pad_token_id,\n eos_token_id,\n batch_size,\n nu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CTC beam search decoder using multiple processes.
def ctc_beam_search_decoder_batch(probs_split, beam_size, vocabulary, num_processes, cutoff_prob=1.0, cutoff_top_n=40, ...
[ "def _decode_batch_beam_search_offline(\n self, probs_split, beam_alpha, beam_beta, beam_size, cutoff_prob,\n cutoff_top_n, vocab_list, num_processes):\n if self._ext_scorer is not None:\n self._ext_scorer.reset_params(beam_alpha, beam_beta)\n\n # beam search decode\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that a given file path is valid.
def validate_file_path(path): if not path or not isinstance(path, basestring) or path == '/': raise ValueError('Path is invalid: ' + repr(path)) if path.endswith('/'): raise ValueError('Path cannot end with a trailing "/": %s' % path) _validate_common_path(path)
[ "def _validate_file_path(self):\n ends_in_slash = self.file_path[-1] == '/'\n _, file_name = self._split_file_from_path(self.file_path)\n if not ends_in_slash:\n raise ValueError('Invalid file path: should end in \"/\".')\n if len(file_name) > 0:\n raise ValueError(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates that a given directory path is valid.
def validate_dir_path(path): if not path or not isinstance(path, basestring): raise ValueError('Path is invalid: %r' % path) _validate_common_path(path)
[ "def checkPath(self, path):\n if path and not os.path.isdir(path):\n raise ValueError(\"Path %r is not an existing directory\" % (path,))", "def is_valid_dir(arg):\n if not(os.path.isdir(arg)):\n error('No such directory %s' % arg)", "def fl_is_valid_dir(dirname):\n _fl_is_valid_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A safe version of os.path.join. The os.path.join() method opens a directory traversal vulnerability when a usersupplied input begins with a slash. With this method, any intermediary path that starts with slash will raise an error.
def safe_join(base, *paths): result = base for path in paths: # Prevent directory traversal attacks by preventing intermediate paths that # start with a slash. if path.startswith('/'): raise ValueError('Intermediate path cannot start with \'/\': %s' % path) if result == '' or result.endswith(...
[ "def pathjoin(p1, p2):\n if p2.startswith(\"/\"):\n return os.path.join(p1, p2[1:])\n else:\n return os.path.join(p1, p2)", "def _pathjoin( *args ):\n return os.path.join( \n args[0],\n *[ x.lstrip( os.sep ) for x in args[1:] ]\n )", "def path_join(fragment, *path):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a mapping of source paths to destination paths.
def make_destination_paths_map(source_paths, destination_dir_path, strip_prefix=None): # Assume that source_paths and destination_dir_path have already been # validated to avoid re-processing (and since they'd fail at lower layers). if not hasattr(source_paths, '__iter__'): rais...
[ "def map_paths(self):\n for path in self.paths:\n if not path.valid:\n continue\n if path.name == self.car.name:\n self.car.path = path\n elif path.name == self.pedestrian.name:\n self.pedestrian.path = path", "def _make_mappings...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates strings of of ASCII sequence permutations for naming shards.
def generate_shard_names(num_shards): # Find a number of permutations that is larger than the number of shards # requested. The number of ordered permutations is just a factorial. permutation_length = None for i in range(1, 10): # Support num_shards from 1 to 362880. if math.factorial(i) > num_shards: ...
[ "def gen_name(length):\n seed()\n return ''.join(choice(ascii_lowercase) for _ in xrange(length))", "def _generate_shortname(cls):\n return ''.join([cls.letters[random.randrange(0, cls.num_letters)] for idx in range(0, cls.SHORTNAME_LEN)])", "def _alphabet_generator():\n for i in itertools.count...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert camel case to snake case
def convert_camel_to_snake(name): ss1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', ss1).lower()
[ "def camel_to_snake(name: str) -> str:\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "def camel_to_snake_case(text: str) -> str:\n return re.sub(r\"([A-Z]+)\", r\"_\\1\", text).lower()", "def snake_case(string):\n return st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle GET requests to a ShortURL. Recover the group id and random key components and use them to redeem the ShortURL if it exists and is not expired. Fetch the named parameters that were associated with the ShortURL and pass them to the _HandleGet method.
def get(self, url_path): # Check that the ShortURL is valid. short_url = yield self._CheckShortURL(url_path) # Invoke the derived class to handle the request. self._HandleGet(short_url, **short_url.json)
[ "def _HandleGet(self, short_url):\n raise web.HTTPError(405)", "def get_shortened_url():\n url = request.args.get(\"url\")\n if not is_valid_url(url):\n return make_response(\"The url was not valid! Make sure to start the url with http:// or https://\", 404)\n key = url_key_dict.get(url)\n if key:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle POST requests to a ShortURL. Recover the group id and random key components and use them to redeem the ShortURL if it exists and is not expired. Fetch the named parameters that were associated with the ShortURL and pass them to the _HandlePost method.
def post(self, url_path): # Check that the ShortURL is valid. short_url = yield self._CheckShortURL(url_path) # Invoke the derived class to handle the request. self._HandlePost(short_url, **short_url.json)
[ "def testShortURLPost(self):\n response = self._RunAsync(self.http_client.fetch,\n self._url,\n method='POST',\n headers={'Cookie': '_xsrf=\"fake_xsrf\";', 'X-Xsrftoken': 'fake_xsrf'},\n body='{}')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract the ShortURL components from the URL path and check that the ShortURL exists and is valid.
def _CheckShortURL(self, url_path): # Split key to get the group_id and random key components. group_id = url_path[:-ShortURL.KEY_LEN_IN_BASE64] random_key = url_path[-ShortURL.KEY_LEN_IN_BASE64:] if len(group_id) == 0 or len(random_key) != ShortURL.KEY_LEN_IN_BASE64: raise web.HTTPError(400, 'Th...
[ "def _is_valid_short(url):\n global our_short_url_regex\n if not our_short_url_regex:\n our_short_url_regex = re.compile(url_for('main.index', _external=True) + \"[a-zA-Z0-9]+$\") #matches our URLs\n return not (not our_short_url_regex.match(url))", "def validateURL(url):", "def test_get_invalid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Any derived class should override this method in order to handle HTTP GET requests to the ShortURL. This method is called with the redeemed ShortURL db object. In addition, any named parameters passed to ShortURL.Create are passed to the derived _HandleGet.
def _HandleGet(self, short_url): raise web.HTTPError(405)
[ "def get(self, url_path):\n # Check that the ShortURL is valid.\n short_url = yield self._CheckShortURL(url_path)\n\n # Invoke the derived class to handle the request.\n self._HandleGet(short_url, **short_url.json)", "def post(self, url_path):\n # Check that the ShortURL is valid.\n short_url = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Any derived class should override this method in order to handle HTTP POST requests to the ShortURL. This method is called with the redeemed ShortURL db object. In addition, any named parameters passed to ShortURL.Create are passed to the derived _HandlePost.
def _HandlePost(self, short_url): raise web.HTTPError(405)
[ "def post(self, url_path):\n # Check that the ShortURL is valid.\n short_url = yield self._CheckShortURL(url_path)\n\n # Invoke the derived class to handle the request.\n self._HandlePost(short_url, **short_url.json)", "def POST(self):\n\t\tpass", "def url_shortner_page(request):\n if request.met...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }