content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import requests from bs4 import BeautifulSoup def getBuses(stopCode: str): """ www.oxontime.com provides live bus times, but not in a neat format. This function queries the real data source (www.buscms.com), cleans up the html table and outputs as JSON To find your stopcode, use this page: http://www...
b99dc75a71fe24a5c847092848452fa05b30c20c
641,174
def avoid_snakes(possible_moves: dict, snakes: dict): """ Removes the moves that will collide with other snakes """ moves_to_remove = [] for snake in snakes: for move in possible_moves: if possible_moves[move] in snake["body"]: moves_to_remove.append(move) for move i...
59c6422a31234a7fb0dcf5612bfbc70c418f33d3
641,175
def has_english_char(string): """ , 44 - 45 . 46 - 47 : - ; 58 - 60 A - Z 65 - 91 a - z 97 - 123 """ string = str(string) for char in string: for start, end in ( (44, 45), (46, 47), (58, 60), (65, 91), (97, 123), ...
1d62a6627ad3c32516edce32473bd9677f76d430
641,176
from typing import Any def format_with_optional_units(value: Any, units: str) -> str: """ Ex: > format_with_optional_units(25.0, "cm") # returns "25.0 cm" > format_with_optional_units(25.0, None) # returns "25.0" """ if units is None: return f"{value}" if units == "%": ret...
3e763bbfdaa35dfd5c4ab294a2a1e3d4ae8d6a4e
641,177
def get_variables(interface1, interface2, interface3): """Create and return a dictionary of test variables. :param interface1: Name of an interface. :param interface2: Name of an interface. :param interface3: Name of an interface. :type interface1: string :type interface2: string :type inte...
3910b1d4454409fcdb2f30d6bf6e7ca2210d3b65
641,178
def add_host(data, host): """Make the image path absolute for those served by the server.""" for i in range(len(data)): data[i]['image'] = f'http://{host}/{data[i]["image"]}' return data
dbf5ced19a545a84ee6f0e85a072f18a31d19cf3
641,179
from typing import List def find_length(a_list: List[int], b_list: List[int]) -> int: """https://leetcode.com/problems/maximum-length-of-repeated-subarray/""" m = len(a_list) n = len(b_list) memo = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m - 1, -1, -1): for j in range(n - 1...
4f3bf4bc48632597e4fbea84aa698fd98929743c
641,180
def bytes2integers(data): """Converts bytes into bytes/bytearray, so indexing/iterating yields integers.""" return data
93cf2c0a412d255fcc91fbc552d3386c37cd59df
641,181
def format_content(article): """ This function takes an Intercom article and formats its content as the HTML we'll use for the Guru card. Because Intercom has some extra fields on its articles, like the # of views, conversations, and counts of user reactions and we don't have these fields in Guru, we displa...
78274dca56bc1657c0af5ddee1c6967bc5c233a5
641,182
def remove_duplicates(n): """ Removes duplicates in a given list (referenced list) Returns a list of all duplicates. """ seen = [] duplicates = [] # determine duplicates for x in n: if x in seen: duplicates.append(x) else: seen.append(x) # m...
3c275f08056c8c7e369a0490c71384adaee2107a
641,183
from pathlib import Path def save_binary_file(path: str, data: bytes): """ Save binary data to given path :param path: file path :param data: binary data """ return Path(path).write_bytes(data)
b911ceb147360117d4753cacfb0eed9a276d1d63
641,186
def mkmdict(seq, *, container=None): """Make multi-dict {key: [val, val]...}.""" if container is None: container = {} for key, val in seq: container.setdefault(key, []).append(val) return container
6597d53d90d72dba67b23b172d714b3ebc8a4020
641,188
import argparse def parse_args(): """ Parse commandline arguments. """ parser = argparse.ArgumentParser(description='GNMT Translate', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # data dataset = parser.add_argument_group('data setup') datase...
054df65f42bc23a571f25a12462b6d87b6237c3f
641,189
def get_center(x_min: int,y_min: int,x_max:int,y_max:int): """Get center of bounding box. Args: x_min (int): Minimum x value in pixels. y_min (int): Minimum y value in pixels. x_max (int): Maximum x value in pixels. y_max (int): Maximum y value in pixels. Returns: t...
5b1095703cd3131fc02270e6cf8679826ca88ac2
641,190
from typing import Dict from typing import List import random def generate_chain(model: Dict[str, List[str]], length: int, order: int) -> str: """Build a Markov chain from the given model. Args: model: A dictionary mapping ngrams to possible following words. length: The length of the markov c...
aaa2e2f1b586e7c17c88dad504d83918259e85d7
641,192
def calc_prime_numbers(n): """Sieve of Eratosthenes""" if n == 1: return [] is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(n ** 0.5) + 1): for j in range(2 * i, n + 1, i): is_prime[j] = False prime_number_list = [] for i in r...
5729e357a6cf2edfe5af3d1f964bbe4bd5922aec
641,193
def parse_squad_label(label): """ :param label: :return: answer_start, answer_end, answer, is_impossible """ answer_start, answer_end, is_impossible, answer = label.split(":::") answer_start = int(answer_start) answer_end = int(answer_end) is_impossible = int(is_impossible) return an...
94ec4a14a2eb6c60693d9fc15ab06bf0511cf032
641,194
import argparse def parse_args(): """Parse the arguments """ parser = argparse.ArgumentParser(description='train an image classifier on mnist') parser.add_argument('--network', type=str, default='lenet', help='the cnn to use (mlp | lenet | <path to network json file>') pars...
e3f1ce6f0a9e5f5f86c0769b7d78f1d947a0d87a
641,195
def dataset_metadata_fixture() -> dict: """Test fixture returning an example dataset metadata response dict Returns: dict: Example Dataset metadata response dict """ data = { "@context": ["metadata-v1"], "@type": "dcat:Dataset", "dct:title": "An example workflow definiti...
f56245e13748f9971df5aa1d67d27be95c3d1485
641,196
def mask(length, offset=0): """ Generate a bitmask with the given parameter. :param length: The bit length of the mask. :param offset: The offset of the mask from the LSB bit. [default: 0] :return: An integer representing the bit mask. """ return ((1 << length) - 1) << offset
a1d3fa22ae1344904257e606b6d90346d1f5a9ed
641,197
def stat_parity_diff(fav_rate_unpriv, fav_rate_priv): """ Gets statistical parity difference between the unprivileged and privileged groups. :param fav_rate_unpriv: rate of favorable outcome for unprivileged group :type fav_rate_unpriv: `float` :param fav_rate_priv: rate of favorable outcome for pr...
1cfe67638de55c28d62c763f2e4099e40f1a9ae6
641,198
from typing import OrderedDict import json def load_watermark(wm_file, wm_size, name_feat_map=None): """ Load watermark mapping data from file. :param wm_file: (str) json file containing the watermark mappings :param wm_size: (int) sixe of the trigger :param name_feat_map: (dict) mapping of feature n...
e819846320da1d097f439f343cbb382688743a8a
641,199
def url_from_key(key): """Given an OSF project key, retrieve the URL of the project metadata. """ return ('https://files.osf.io/v1/resources/{}' '/providers/osfstorage/'.format(key))
be2ba050e739e903b7c58286d63e6e27070fbff1
641,200
def T(*args): """A function that always returns true. Any passed in parameters are ignored""" return True
c12005ec896968318bf84dfd04005a4344327cc5
641,201
import os import platform def get_qotd_file(): """ Get location of Quote of the Day file. """ home = os.path.expanduser("~") file = "_qotd" if platform.system() == 'Windows' else ".qotd" return os.path.join(home, file)
904510e4f062fb702a25a319b22762f4dfa6610e
641,202
def flip(matrix): """ Flip a matrix vertically. Returns an immutable matrix. Example: 1 2 --> 2 1 3 4 4 3 """ return tuple([row[::-1] for row in matrix])
0af446ef680af0272ee8c19e477fa44caea0e82a
641,203
import time def is_valid_date(str_date): """判断是否是一个有效的日期字符串""" try: time.strptime(str_date, "%Y-%m-%d") return True except Exception: try: time.strptime(str_date, "%Y/%m/%d") return True except Exception: return False
b6ef807ba1712dcc15ad0d9615cfce238214ab90
641,204
import argparse import os def parse_args() -> argparse.Namespace: """Parse arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", default=None, help="source directory or file, if a directory is " "given, the script will produce a vis...
ee332ea0d93931160eb2803ecf9859e2c99f38dc
641,205
import base64 def encode_images_from_file(image_paths): """ Encodes the processed image(s). Args: image_paths: List of input image filepath Strings ex).jpg , .png, .tiff Returns: A list of encoded image(s) as ByteStrings """ ret = [] for path in image_paths: with open(pat...
848cbef53d9d676d9efdf7231d21798722bfed8f
641,206
def is_yes(indicator): """ Check if `indicator`represents positive state :param indicator: the bool literal like 'y', 'yes', 'true' and 'True' :type indicator: str :return: bool value to indicate positive or not :rtype: bool """ assert(type(indicator) == str) value_list = ('y', 'y...
e5cf9c011418f1ca8c3d850b7a6af35e33ea9ab3
641,207
def check_and_remove_file_extension(filename): """ Remove file extension from filename. :param filename: :return: """ dot = '.' if dot in filename: filename = filename.split(dot)[0] return filename
0306da4da35fb555d6de380aa677efd598b0a83d
641,208
def invcdf_uniform(val: float, lb: float, ub: float) -> float: """Returns the inverse CDF lookup of a uniform distribution. Is constant time to call. Args: val: Value between 0 and 1 to calculate the inverse cdf of. lb: lower bound of the uniform distribution ub: upper bound of ...
a113171c9d4ced58d06e41c1289e5e30200b8d09
641,209
def deprecate(func): """This decorator stops a function from running and prints a message""" def nothing(*args, **kwargs): print(f"{func.__name__} has been deprecated") return nothing
9c337a51af5bf6a019ec8dc14a41378fad993c23
641,211
import json def verify_output_json(output_str, key=None, value=None): """ Given the stdout of summarize_job.py --json, ensure that it is valid json, and ensure that a given key is present """ for parsed_data in json.loads(output_str): if key is not None: print("Checking if %s i...
995fca272cffd6db960ecdd56ec69a22e7659e37
641,212
from typing import Sequence def entity_dict_has_primary_key(pk_names: Sequence[str], entity_dict: dict) -> bool: """ Check whether the given dict contains all primary key fields """ return set(pk_names) <= set(entity_dict)
aefc0ff6bfb10bedaaa180977f4da5075e4a478b
641,213
def sequence_index_word(sequence, index_word_dict, pad_value=' ', join=False): """Sequence index transfer to sequence word. Args: sequence: pd.Series or np.array or List of lists, sample sequence. index_word_dict: dict, {index: word}. pad_value: fillna value, if word not in index_wo...
a585cfd854e7c62290041b4afdae296bda0dc1a3
641,216
def allclose(a, b, tol=1e-7): """Are all elements of a vector close to one another""" return all([abs(ai - bi) < tol for ai, bi in zip(a,b)])
20b5e6c7cb0f8afbc2623d5a32dc752a70d9d6f7
641,218
def valid_alleles(alleles): """Return if alleles are valid (i.e. at least one non-symbolic alt).""" return len(alleles) > 1 and not any('<' in a or '[' in a or ']' in a for a in alleles)
a91c103f3fb68ebc62e07a95e3dc155727da8cb2
641,219
import re def refine_localization_probabilities(modified_seq, threshold = 0.05): """ returns the AAs that were possibly modified (with p > threshold). Input: modified sequence (a string of AA with p of each to contain modification: APKV(.7)ML(.3)L means that V was modified with p = .7 and L with p = .3) ...
e908f9cb19423711941d57e77883df78102c05db
641,220
from typing import List import math def fizzbuzz(n: int) -> List[str]: """Conunts and reterns N FizzBuzz numbers. The first number is "1", and the players then count upwards in turn. However, any number divisible by three is replaced by the word fizz and any number divisible by five by the word buzz. Numb...
7b921c000662eefa30d4d808ea755f6fbcd4e38f
641,221
def strip_trailing_zeroes(num) -> str: """Remove trailing zeroes, e.g. 0.500 --> 0.5 and 1.000 -> 1""" s = "{:.3f}".format(num) return s.rstrip("0").rstrip(".") if "." in s else s
99d76bfc769dde5f4c40686426e0a7a5c246ff82
641,223
import time import sys def print_time(s, start_time): """Take a start time, print elapsed duration, and return a new time.""" print("%s, time %ds, %s." % (s, (time.time() - start_time), time.ctime())) sys.stdout.flush() return time.time()
9449c62786ab337e333c62e17283acebfbfe40a5
641,224
import os import logging def activate_git_repository() -> bool: """ Activate Git Remote Repository Parameter Return Example >>> activate_git_repository() True """ try: os.system('git init') os.system('git remote add -f -t {{cookiecutter.repositorio_branc...
72f7d8d2b4b794346d472030d26cdec7af358bd2
641,226
def chordfinisher(*args, **kwargs): """. It turns out that chain(group,group) in celery does not execute one group after another, but executes the groups as if they were independent from one another. To get a sync point between groups, we use this method as a callback to enforce sync points for chor...
910b76d7632f8d51d9070ca67e2c804535c7e58d
641,227
def rotate(string_one, string_two): """Determines if one string is a rotation of the other. Args: string_one: any string of characters. string_two: any string of characters. Returns: True: if string_one is a rotation of string_two False: if string_one is not a rotation ...
6a35df127be54b66f0749766218e1b9884c64f7b
641,228
import argparse def get_arguments(): """Gets arguments from the command line. Returns: A parser with the input arguments. """ # Creates the ArgumentParser parser = argparse.ArgumentParser( usage='Process the saved metrics file into real results.') # Adds a dataset argument ...
a6eb863a33d439bd78ed71eff06051f5eddc7ad9
641,229
def estimate_shots_per_opp(turnover_rate, ft_attempt_rate): """ Estimates shot attempts per potential shot opportunity, i.e. possessions plus offensive rebounds. Coefficients are rounded from a simple least-squared regression from regular-season data. """ return 1 - 0.85 * turnover_rate - 0.4 * ...
127ea618a6970e4f4cb9734860fbbf251e2cfbe4
641,230
def strip_end_sections(text): """Strip useless parts at end (refs, see also, etc)""" References_start = text.rfind("References") See_also_start = text.rfind("See also") External_links_start = text.rfind("External links") Further_reading_start = text.rfind("Further reading") end_of_document = Re...
11b7ce02a39bdf7e0b6a1e58aeab790b00358a4a
641,231
def kelvin_to_farenheit(temp: float): """ Converts kelvin to farenheit """ far = (temp - 273.15) * (9 / 5) + 32 return int(far)
afbe3f29f8f99dd2287b5f9b666a55096672cb79
641,232
def welcome(): """displays 'welcome' on the screen""" return "welcome"
13f1e5daa4db6dc7adf65751cd5b22bba977d856
641,236
def _inline_to_standalone_script(calc): """ Create executable Python script for execution of inline script. .. note:: the output bash script may not always be correct, since it is simply formed from: * contents of the file, which contains the original ``\*_inline`` func...
721092d688dbc5feb1a558ce0e84ba7f71a376c0
641,238
import random def troll_salty_comments(): """ Generate a number of total salty comments """ return random.randint(100, 500)
a7407e7f2c700d6413165b0f989868d016bcf3cb
641,239
import numpy def _integer_to_edge_condition( k ): """Given a pattern id k, return left, middle, and right conditions Args: k (int): pattern id Returns: (Lcond, Mcond, Rcond) a tuple of three functions. """ assert k < 64, "Input k = {} must be < 64.".format(k) bdigs = [ int(b...
56656b3bba8766c23a68633726148762acefea15
641,240
def first(iterable): """Returns the first value of the given iterable.""" return next(iter(iterable))
f72bba1c1c97da2f1b3dbb3c7f74af7ae9e44e09
641,241
from typing import Optional def get_url_filename(metadata: dict, default: Optional[str] = None) -> str: """Method responsible to get the filename and right extension to add to the pypi url :param metadata: Dictionary with the all package metadata filled :param default: default value for the package f...
2bdeb9c8dadc7ceadfaa1ad4f851b496f4bc147c
641,242
def _format_pep_8(camel_case_name: str) -> str: """ Helper that creates a pep8_compliant_method_name from a given camelCaseMethodName. """ return camel_case_name[0].lower() + "".join( f"_{letter.lower()}" if letter.isupper() else letter.lower() for letter in camel_case_name[1:] )
f0b051aca791b2e775887a553c2cc230dfbaf62b
641,243
def linalg_vector_set_elem(a, n, v): """ Set vector element n to v. Returns copy of matrix with change. Parameters: a (array): The vector n (int): The index v (number): The new value """ a1 = a.copy() a1[n] = v return a1
9afa885999a381ba4209217636984ac8457f502d
641,244
import torch def threshold_resize_torch(preds, shape, threshold=0.5): """ Thresholds and resizes predictions as a tensor. Args: preds (torch tensor): Predictions. shape (tuple [2]): Shape to resize to threshold (float, optional): Threshold. Defaults to 0.5. Returns: n...
6c8e74df4c74df74501ddf04eaa3b4afd807ab08
641,245
def read_requirements(): """parses requirements from requirements.txt""" with open('requirements.txt') as f: req = f.readlines() return req
39907dd4687f23f5521356d8e3193baf79c33127
641,246
def filter_list_sorter(feed_filter): """ Provide a key to sort a list of feed filters. """ return feed_filter['class']
02536ac7a01e0e3e8e6e2f00d25244c5f9e90e74
641,248
import torch def vec_interpolate(v1, v2, alphas, repeat_row=0, repeat_col=0): """interpolate two vectors""" if repeat_row == repeat_col == 0: return torch.cat([(1 - alpha) * v1 + alpha * v2 for alpha in alphas], dim=0) elif repeat_row > 0: assert repeat_col == 0 return torch.cat([(...
11862e84124550e3794cf6f5ece9b493a6d04da6
641,249
def gc_content_percent(sequence): """ Calculates the GC-content percentage of the input sequence Returns the percentage as an integer out of 100 """ gc = sequence.count('G') + sequence.count('C') atcg = len(sequence) percent_gc = (gc * 100) / atcg return percent_gc
3e2344096df626556f1f0947d7a13dcd8e9ff600
641,250
def deriv_graphing_method(): """ This function determines how the user desires to graph the derivatives if they want to """ deriv_method = 0 try: #Loop until get desired value while (deriv_method != 1 or deriv_method != 2 or deriv_method != 3): #Obtain the desired input ...
5e78ac2f8eb178a825ebb3f8f2c9c8ed6eec8daf
641,251
def nucleotide_frequency(seq): """Count nucleotides in a given sequence. Return a dictionary""" tmpFreqDict = {"A": 0, "C": 0, "G": 0, "T": 0} for nuc in seq: tmpFreqDict[nuc] += 1 return tmpFreqDict # More Pythonic, using Counter # return dict(Counter(seq))
756456a77e25bca3d38fcc170c1fc5491f11dd04
641,252
def firstPositiveNumber(A): """ A: list[int] return: int """ if len(A) > 0 and A[0] > 0: return 0 if len(A) > 0 and A[-1] < 0: return len(A) l = 0 h = len(A)-1 while l <= h: mid = l + (h-l) // 2 if A[mid] > 0 and A[mid-1] < 0: return mid ...
577725c39bcb897e58741530a6aa8b16dc02ca44
641,253
def rules(state, alive): """ 1. Any live cell with two or three live neighbours survives. 2. Any dead cell with three live neighbours becomes a live cell. 3. All other live cells die in the next generation. Similarly, all other dead cells stay dead. """ if state == 1: # c...
65538704c29eb651fd6ca7d693d24b06476e5858
641,254
from queue import Queue def queue_no_nodes(): """Create empty queue.""" new_queue = Queue() return new_queue
a8ce70539af555de380de6e2212c491e285b97f7
641,255
from typing import Any import importlib def import_object(name: str) -> Any: """Dynamically import a Python object (e.g. class, function, ...). .. note:: To dynamically import a module, use :func:`importlib.import_module`. Args: name (str): The path to the Python object to import. ...
e6d414bdf871f53dd0a61824fbda46a31d3e3c7b
641,256
import torch def bbox2delta(proposals, gt, means=[0, 0, 0, 0], stds=[1, 1, 1, 1]): """Convert box to delta. :param proposals: proposals :param gt: ground truth :param means: means :param stds: stds :return: deltas """ proposals = proposals.float() gt = gt.float() px = (proposa...
64ef0b79ccfd09126f2eb3a723326885cd4879ea
641,257
def _IsSourceExtension(s): """File extension (excluding dot) matches a source file extension.""" return s in ('c', 'cc', 'cpp', 'cxx')
821741f630a5ca38377ab12207c39d8b943daf97
641,258
import sqlite3 async def db_check(bot, msg, cursor, table: str): """ This function is coroutine. Checks if table exists. :param bot: Bot instance :param msg: Message :param cursor: Database cursor :param table: Table name :return: Bool """ try: cursor.execute('SELECT...
6f032f2ac0f2d9f1d0e49890cd8db51e24c85c72
641,259
def element_times(left, right): """ The output of this operation is the element-wise product of the two input tensors. It supports broadcasting. Args: right: right side tensor left: left side tensor Returns: :the element-wise product of the two input Examples: >>...
c27ec46088a1a04640d4d81e9ae23f3e8865a5cd
641,260
from typing import Any def replace(source: str, search: Any, replace: str) -> str: """Replace for QSA where detects if "search" is a Regexp.""" if isinstance(search, str): return source.replace(search, str(replace)) else: return search.replace(source, replace)
0550596b44bcc75a34afbf1d0b18dc90ae8f702f
641,261
def readme(): """Get README.md content.""" with open('README.md') as in_file: return in_file.read()
c0d12570106cc7ac4346eb8a6f452a7f51fa8ac6
641,262
import logging def pad_sentences(sentences, padding_word="<PAD/>", forced_sequence_length=None): """Pad setences during training or prediction""" if forced_sequence_length is None: # Train sequence_length = max(len(x) for x in sentences) else: # Prediction logging.critical("This is predi...
7347ebf976b99c32087fc117610bd8920a1aab2c
641,264
import re def get_las_filenames(mjob_data, db_prefix): """Given result of get_mjob_data(), return {int: final_las_filename} """ # This is our best guess. # (We might not even need this, since we know the output filename of each merge-task by convention.) # Eventually, we need to re-write HPC.d...
e830e101ea5dc3838fb00e3efd2403091eebdd7c
641,266
def gradient(color_one, color_two, blend_weight): """ Blend between two colors with a given ratio. :param color_one: first color, as an (r,g,b) tuple :param color_two: second color, as an (r,g,b) tuple :param blend_weight: Blend weight (ratio) of second color, 0.0 to 1.0 """ if blend_weig...
7a3645acf3a83b093e96b706f8d118e47ef85c87
641,267
def strip(stringarr): """ Strip whitespace from the start of each string. """ # From https://en.wikipedia.org/wiki/Whitespace_character. is_whitespace = "((lookup(e, p) == 32c) || (lookup(e, p) >= 9c && lookup(e, p) <= 13c))" # +3L = +1 compensate start_i already +1'ed, +1 compensate end_i alr...
7c699d635d421d0184ae465cd282338513f4032a
641,268
def no_signature(run_command, disk_path): """Return true if no known signatures exist on the disk.""" signatures = run_command(['blkid', '-p', disk_path]) return not 'UUID' in signatures[1]
591adaf89461742c5eea7b7124dd37f3cc899e4c
641,269
def plot(lines, geom_type='xyz'): """Plots the geometries from the optimization steps""" start = ' COORDINATES OF ALL ATOMS ARE (ANGS)\n' end = '\n' geoms = [] i = 0 step = 0 while i < len(lines): if lines[i] == start: i += 3 start_num = i while li...
b4ab2f8b2d217abe19bb4494223dac29a481940e
641,270
def date_check(year, day): """Returns a boolean if it is after the year 2000, and the day is 'Friday'""" # example: a Tuesday in 1980 is False, a Friday in 2021 is True if year > 2000 and day.lower() == "friday": return True else: return False
f18a6bc706798470b6d4a2045a45394ffab64062
641,271
def _validate_prefix(prefix, avoid): """ Validate an install prefix. """ if prefix.startswith(avoid): rest = prefix[0:len(avoid)] return rest != "/" and rest != "" return True
6be541f65334a28ea09d6237f9e54cbfce9347f0
641,272
def _get_QComboBox(self): """ Get value QCombobox via re-mapping filter """ return self._get_map(self.currentText())
26330ce16c9147301e11ac46e5c9310bf0959606
641,273
def compare_webapps(list1, list2): """ Return list of matching dictionaries from two lists of dictionaries. """ check = set([(d['name'], d['id']) for d in list2]) return [d for d in list1 if (d['name'], d['id']) in check]
d02bac02e6dea5bbf7188b7e3afa6c6cbb64e054
641,274
def createNewICM(): """ Create a new ICM""" return "", 415
cb66396ccfa7240a95e9e0f286412012613c093c
641,275
def kafka_broker(kafka_broker_factory): """Return a Kafka broker fixture""" return kafka_broker_factory()[0]
88dca7bf53a12af9cc05a94127d6f382ca3f2419
641,276
import torch def node_covering_index(cover_index:torch.LongTensor, distribution=False, num_nodes=None): """Compute the node covering index of a given cover matrix, i.e., the number of occurrences of each node in the cover matrix. Args: cover_index (torch.LongTensor): Cover assignment matrix i...
e8626c502ada67fc19806d83e911263c3ff9bc95
641,277
from typing import get_args def is_optional(kls): """Returns `True` if the type is `type(None)`, has a Union to none, like Optional[], Nested `Union` arguments are inspected `TypeVar` Edge case: TypeVar` definitions are not inspected. If only the bound/constraint of a typevar is Optional is_op...
6b490306744a86f3cc4e5eb859fec222c437da51
641,278
import torch def prune(spectrum: torch.Tensor) -> torch.Tensor: """Prunes the spectrum and its associated matrices.""" condition_thresh = 1e16 spectrum_thresh = torch.max(torch.abs(spectrum ** 2)) / condition_thresh mask = torch.nonzero( (torch.abs(spectrum ** 2) <= spectrum_thresh) & ...
5dbcff9aaaeb3256c33e7ed133d0941bd705cc61
641,280
import base64 def parse_signature(value: bytes) -> str: """ Return a base64 encoded signature. Since the signatures dont really have any representation apart from bytes, encode the bytes to a b64 string similar to stellar's xdr viewer. """ return base64.b64encode(value).decode()
1456c34ff099a234c9ba77c264721326fa889e94
641,281
def test_model(clients_to_test, set_to_use='test'): """Tests self.model on given clients. Tests model on self.selected_clients if clients_to_test=None. Args: clients_to_test: list of Client objects. set_to_use: dataset to test on. Should be in ['train', 'test']. """ metrics = {} ...
aa1235328fd4e82a3dee1e60bb96de6115610bbf
641,283
def train_test_split(df,filter_condition,train_condition, test_condition,features,targets): """ Separate df into a train and test set. Returns training and testing dfs as well as split into inputs/outputs """ #Filter dataset if filter_condition is not None: df_filtered = ...
a4bf5a9ea5f9f63ef3a70ea5c1ef3295758e19ba
641,284
def split_image_name ( image_name ): """ Splits a specified **image_name** into its constituent volume and file names and returns a tuple of the form: ( volume_name, file_name ). """ col = image_name.find( ':' ) volume_name = image_name[ 1: col ] file_name = image_name[ col + 1: ] ...
151c73e5066607f230a115987eb1717cc77e97c6
641,285
def connect_db(client, db_name, username, password): """ Connect to a Arango database. :param db_name: Database name. :type db_name: str :param username: Username for basic authentication. :type username: str :param password: Password for basic authentication. :type password: str :r...
5665fa394285b8614ed5746a6a12b8391370a95a
641,286
def f_bound(f, key, first, last, value, which, *args, **kwargs): """ :param f: the MONOTONIC function :param key: keyword arguments or position of argument to be searched :param first: [first, last) :param last: [first, last) :param value: value to be searched :param which: lower bound or u...
47f722c4ab23ec3b0bb74390659cf7e268c3fccb
641,287
import torch def extend_batch_tuple(batch, dataloader, batch_size): """ The same as extend_batch, but here the batch is a list of tensors to be extended. All tensors are assumed to have the same first dimension. Returns the extended batch (i. e. list of extended tensors). """ while batch[0].sh...
fcd937edc6f550766868bb7a663ead90b83938e7
641,288
def partion_commits(commits, partitions): """ Function that divides commits into evenly partitions. """ quote, remainder = divmod(len(commits), partitions) chunk_commits = [(i * quote + min(i, remainder), (i + 1) * quote + min(i + 1, remainder) - 1) for i in range(partitions)] ...
1a54b1d80f0376b97dbf9b0952e7b56984dbddd7
641,289
def available_formats(): """Returns a list of all supported file-types""" return ["fasta-dna", "fasta-aa", "fastq"]
a879f0b87ae8da2acdb188891b104336c671afbb
641,291
def process_target(target_str): """ Extract target architecture from a string of verbose compiler invocation output. """ target_label = "Target:" target_clean = "" for line in target_str.splitlines(True): line = line.strip().split() if len(line) > 1 and line[0] == target_lab...
9fab762e1f01363339e02b925b30a97c9ec45f4c
641,292
import os def prepare_potcar(poscar,potcar_dir,potcar_postfix=''): """ Create a POTCAR if there is not in the directory. The directory that contains pseudo-potential files should be specified. Potentials without `_h`, `_s`, or `_GW` are to be used. """ if not potcar_dir: return None ...
de43caa51dd4f29cf8947410dbd2bd07df23d40a
641,293