content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from re import search def _find_cover_image(body): """Attempts to find a cover image to use for a summarized blog post. The cover image will be the first image found in the specified body. Because the body is written in markdown format, the algorithm works by looking for the pattern "![<label>](<URL>...
fed9f6806cd7cf94016b7142e77ae738b43fd234
603,422
import re def get_remote_info(remote): """ Extract the GitHub user/organization and repo name from the remote url. """ owner = None repository = None match = re.search('^(http[s]?\:\/\/|git@)github.com(\/|\:)([^/]+)\/([^/]+)(?:.git)', remote.url) if match and len(match.groups()) == 4: ...
a05aecac2835b3b35716e32633a0c7911ad8fce4
603,423
import math def cos_degre(angle): """ Renvoie le cosinus de l'angle (type``float``). Arguments: angle (float): La mesure d'un angle en degré """ return math.cos(math.radians(angle))
0ec36ee53ae1a90533999e5e7f42260d1909a96c
603,426
import math def combinations_n_k(n, k): """Returns the number of combinations n choose k""" return int(math.factorial(n) / (math.factorial(k) * math.factorial(n - k)))
0d77d041d3fa148c50cbe798dbb4955cd8e991b5
603,428
def in_real_grid(pos): """ Checks if the given position is on the game field. """ if 40 <= pos[0] <= 840 and 40 <= pos[1] <= 840: return True return False
fcf37f043f563de7da68c74bf149a39d62961fb7
603,430
from pathlib import Path def _log_filename(name: str) -> Path: """ Returns a name of the file with `.log` extension. """ return Path(name).with_suffix('.log')
f32466a41404e8aed4090774e6d709245a7cc3a5
603,431
def not_2018(holidays): """ Exclude the year 2018 from the holiday list. """ return holidays[holidays.year != 2018]
8364f6b86d200dc16f9680846ad561d8172a9dd1
603,432
def isListSorted(array:list): """ Check if the List is sorted using recursion """ l = len(array) if l == 0 or l == 1: return True if array[0] > array[1]: return False return isListSorted(array[1:])
bf5c9b72da43f8d36bfd19b93fdbd2f01c433444
603,434
def get_deviation(number: int, circle: int) -> int: """Get distance to horizontal or vertical line from 1.""" # Special case for memory storage center if number == 1: return 0 # Side length derived from progression n'th child formula side = circle * 2 + 1 # Normalize number - bottom le...
ba682a7b849037f6a3d2a2658bb4cc369f15deeb
603,436
def PRIMITIVE_OR_TENSOR_FILTER(arg_value): """Only keeps primitives and tensors.""" return arg_value.is_primitive or arg_value.is_tensor
bcc05202f5ed12d000160f4d2baf44cd166743df
603,437
import math def process_split_ratio(ratio): """Generate split ratio lists. Args: ratio (float or list): a float number that indicates split ratio or a list of float numbers that indicate split ratios (if it is a multi-split). Returns: tuple: - bool: A boolean variable mul...
a118eefb17bc228b4a639036e16f2c241114b8fd
603,441
def filter_user(user_ref): """Filter out private items in a user dict. 'password', 'tenants' and 'groups' are never returned. :returns: user_ref """ if user_ref: user_ref = user_ref.copy() user_ref.pop('password', None) user_ref.pop('projects', None) user_ref.pop('...
95ce22a7c3a050823938ec12da943f3358aa4d0a
603,445
def get_overlapping_adjectives_raw_results(merged_results): """ Looks through the male adjectives and female adjectives across the corpus and extracts adjective that overlap across both and their occurrences. FORMAT - {'adjective': [male, female]} :param merged_results: :return: """ overlap_...
25d3949866dc7a6c31b80c07a3b57494a824a27c
603,449
def compute_string_properties(string): """Given a string of lowercase letters, returns a tuple containing the following three elements: 0. The length of the string 1. A list of all the characters in the string (including duplicates, if any), sorted in REVERSE alphabetical order ...
ce02578741bc42d0e0030328904ae1e9ec28ee4e
603,452
def merge_dict(dict1, dict2): """ Merges dict2 into dict1.""" if dict1 is None: dict1 = {} if dict2 is None: dict2 = {} result = dict1.copy() for key in dict2: result[key] = dict2[key] return result
301dd0ae5f28bc63844e3401283278857b23c38d
603,455
def load_module(state, mod_list=[]): """Dynamically load modules for states USAGE mod = load_module(state, ['datasource', 'loader']) mod.datasource.Datasource() """ return __import__('openelex.us.%s' % state.lower(), fromlist=mod_list)
d9204ee9a274a9375ad7078e29dc7480cb4c1105
603,459
def find_range(iterable, predicate): """Find the indices of the first range of consecutive items which satisfy the given predicate. Returns (-1, -1) if it there is no such ranges. find_range([0, 0, 1, 1, 0], lambda e: e > 0) => (2, 4) """ iterator = enumerate(iterable) start_index = next((i for...
24f899a8a0dd7f4397d76aeecaf41c0199778e01
603,460
def assay_transpose(assay_df): """ assay_t_df = assay_transpose(assay_df) Parameters ---------------- assay_df: dataframe of assay data with genes as rows and patients as columns Returns ---------------- dataframe transposed with patients as rows and genes as columns """ assay...
29e7ebb1c9a62a9f008acfbcd3318be23dc2bfec
603,468
import math def word_index_ctc(true_txt, ctcout, target, step): """ Exploit relationship between True_ctc_len/True_num_words and Target_ctc_len/Target_num_words. Assume the True_ctc_len/True_num_words ~ Target_ctc_len/Target_num_words: if True_num_words <= Target_num_words, ...
15157915d3b646f70d16e419fcac1af5b9c34d9b
603,477
def grid_indices(qubit_id, n_dimensions, grid_length, spinless): """This function is the inverse of orbital_id. Args: qubit_id: The tensor factor to map to grid indices. n_dimensions: An int giving the number of dimensions for the model. grid_length (int): The number of points in one di...
212a58629306433c4405dcf491b438ad9d98e650
603,478
def canSignDefensivePact(fromTeam, toTeam): """ Returns True if the two CyTeams can sign a Defensive Pact. """ if fromTeam.isDefensivePact(toTeam.getID()) or toTeam.isDefensivePact(fromTeam.getID()): return False return fromTeam.isDefensivePactTrading() or toTeam.isDefensivePactTrading()
d0b32e8b56a2bb19df221d175308182b88c48a5a
603,479
def get_model_string(model): """ Returns a string that can be used to identify the specified model. The format is: `app_label.ModelName` This an be reversed with the `resolve_model_string` function """ return model._meta.app_label + "." + model.__name__
880c0f4248f46f3a2bb3a897802685e116396b37
603,483
def average(trials, group_by="order", key="best", return_var=False): """Compute the average of some trial attribute. By default it will compute the average objective at each time step across multiple experiments. Parameters ---------- trials: DataFrame A dataframe of trials containing,...
7035aec8f888296786d9e3cc42859b28b2d1516f
603,487
def shorten_fqdn(name): """ Shorten any system account FQDN for readability. """ if '.' in name: (name, _) = name.split('.', 1) return name
06ae9ed61a2cb2313b86102dc1a80d3dae9771c0
603,488
import logging def infer_header(input_path, expected_lines, method_name=None): """ Method that infers the length of the header of a given file from the number of lines and of expected lines. Parameters ---------- input_path : file or string File or filename to read. expected_lines : i...
b3c590f9d55b0e3f80e06fa2a3d1541a195c6a5c
603,501
import click def create_instance(config): """Create (and start) a new EC2 instance using the default AMI. """ if not config.ami_default: raise click.UsageError( 'No default AMI specified. Cannot create instances.' ) res = config.ec2.run_instances( ImageId=config.ami...
f0f133563c60da15e097eec14898c69c9f490417
603,505
def edition_check(current_edition, allowed_editions=None): """ Is this patch/extension allowed in the current edition? current_edition is what is currently installed and active. allowed_editions is the list of editions the patch/extension is suitable for. If allowed_editions is None, then the patch ...
c8bdfb391b4fee79ac61524489a550506178eb26
603,507
def subsets(self, nums): """Power set algorithm 1) set size is n, power set size is 2**n; 2) loop through power set i:0 -> 2**n-1, loop through set j:0 -> n-1 set = [a,b,c] 000 [] 001 [a] 010 [b] 011 [a,b] 100 [c] 101 [a, c] 110 [a, b] 111 [a, b,...
20db2d8e7d2e05b2c4e33acf3922468cd5e2afee
603,508
def is_empty(line): """Returns True empty lines and lines consisting only of whitespace.""" return (not line) or line.isspace()
275ad3ac8f048e7bfd0ed757d58427c8a7a9b60b
603,509
def experiment_rank_by_average_rank(experiment_pivot_df): """Creates experiment level ranking of fuzzers. Takes a pivot table representing per benchmark ranking scores. Ranks fuzzers per benchmark, then takes the average rank across benchmarks (smaller is better). """ # Rank fuzzers in each ben...
4b0976f393f0942e9ea6b2343c74470ceb539483
603,510
def ModifyCreateJobRequest(job_ref, args, create_job_req): """Change the job.name field to a relative name.""" del args # Unused in ModifyCreateJobRequest create_job_req.job.name = job_ref.RelativeName() return create_job_req
133005376c85a0c8aa05a7e3d112f6896518632a
603,512
import math def rowcol(x, y, affine, op=math.floor): """ Get row/col for a x/y """ r = int(op((y - affine.f) / affine.e)) c = int(op((x - affine.c) / affine.a)) return r, c
400d4b90179b329f7285b056a2fbf5685b6da82b
603,514
def voting(winners, author, text): """ Every author gets to vote once with their vote being text. The text is a numberic string indicating a voting choice. Each vote is added to a dict of all other votes. """ if author not in winners.keys(): if text.isnumeric(): winners[autho...
02e4177bc9cc64a2e7b9e80015c9eae20acf7fb4
603,518
from typing import Any import importlib def load_obj(obj_path: str, default_obj_path: str = "") -> Any: """Extract an object from a given path. Args: obj_path: Path to an object to be extracted, including the object name. default_obj_path: Default object path. ...
19775566288f2b5ae463875960c9d5b3ce7b8c18
603,519
def jaccard(sample1, sample2): """Jaccard similarity between two sets""" intersection = len(sample1.intersection(sample2)) union = len(sample1.union(sample2)) return intersection / union
03e907cb7e660380b425456471f869b2a55ad7f4
603,520
import string import logging def printable(s, func=None): """ Return string of ASCII string which is considered printable. Args: s(str): string func: function to convert non-ASCII characters """ out = '' for c in s: if c in string.printable: out += c ...
848669b7e2fc17699eb7fce0452f693061f36b03
603,524
def flatten(lst): """Flattens a list by removing all sublists within it.""" return [item for sublist in lst for item in sublist]
42d324f9c5be39479cb6b7692da9b6f29792f221
603,525
def scale_tensor_to_0_1(tensor): """Scales a tensor to values between 0 and 1. Args: tensor (torch.tensor): Input tensor. Returns: Tensor: Scaled input tensor. """ tensor = tensor.add(abs(tensor.min())) tensor = tensor.div(tensor.max()) return tensor
f255adf9e2313f27dfb5a843d1aa9c95cbf5b142
603,531
from operator import mod def generate_other(probe:int, limit:int, flags:list, *, inverse:bool=True, forward:bool=True) -> list: """ Generate indices of other locations for given probe location, limit range and flags. Parameters ---------- probe: int probe index limit: int max...
fdb0fc9ff3d5cb3fe71c7bce76ddee9ab8b61880
603,532
import json def parseJson(val): """Parse JSON string and returns a python dictionary""" return json.loads(val)
c845f282860b500a615dab8d2bf4939d0c727894
603,535
def docs_from_json(path, model, n=5000, update_kws=None, **kwds): """Create/update documents from json(lines) file. Parameters ---------- path : str Path to a file with document per line as a single valid JSON. model : interfaced mongoengine collection :py:class:`mongoengine.Documen...
8e959e8f4762c20e917de5f478d85f39d810208d
603,537
import math def hav(angle): """Return the haversine of an angle (input in radians)""" return math.sin(angle/2)**2
f61c5753393f3c447cfbca01012e8ddafebaca71
603,547
import itertools def gen_cartesian_product(*args): """ generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 1...
751fbf9af63e6eb0fe35b1174845380cd9d1d23b
603,549
import random def random_string(length=8): """ Generate a random string of a-z A-Z 0-9 (Without vowels to stop bad words from being generated!) >>> len(random_string()) 8 >>> len(random_string(10)) 10 If random, it should compress pretty badly: >>> import zlib >>> len(zlib.c...
6bed9ccc82054415fd8d47018ac4e9d8e99306e0
603,551
def get_color_index(color,palette): """Returns the index of color in palette. Parameters: color: List with 3 int values (RGB) palette: List with colors each represented by 3 int values (RGB) Returns: Index of color in palette. -1 if not found. """ for x in rang...
6131fdaa9fb0db7727a5e8ad6c30bd0b61e12031
603,555
import re def split_into_chunks(code): """ Split code into chunks, each chunk being a function definition """ # Create an empty list to store chunks chunks = [] # Create a string to store the current chunk chunk = '' # For each line in the code for line in code.splitlines(): ...
bc1d44060c14237893c522c04b3a04445dd5ea60
603,558
import re def smi_tokenizer(smi): """Tokenize a SMILES sequence or reaction""" pattern = "(\[[^\]]+]|Bi|Br?|Ge|Te|Mo|K|Ti|Zr|Y|Na|125I|Al|Ce|Cr|Cl?|Ni?|O|S|Pd?|Fe?|I|b|c|Mn|n|o|s|<unk>|>>|Li|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])" regex = re.compile(pattern) tokens = [token for t...
7cd5c7366c4897c8398cce19d36f5681863355a9
603,559
def from_ternary(ternary: str) -> int: """Converts a ternary number to its decimal (base 10) equivalent. Args: ternary (str): The ternary score. Returns: int: The decimal score. """ value = 0 digits = (int(digit) for digit in reversed(list(ternary))) for i, num in enumerate...
00ba5ce8a22acb6bd8c7eb448a8837e78821bd53
603,560
def get_center(res): """Computes center point of a resolution rectangle.""" return (round(res[0] / 2), round(res[1] / 2))
42a4bdab4ed19d0d3b0ba546c7762084e35e1812
603,561
import json async def insert(ctx, *, data: str): """Insert a document.""" try: j = json.loads(data) except: return await ctx.send('Failed to parse JSON') res = await ctx.bot.storcord.insert_one(j) await ctx.send(res)
2884eab22476fe7ac33646ccc651cf016ea69bab
603,562
import torch def process_box(box, score, image_shape, min_size): """ Clip boxes in the image size and remove boxes which are too small. """ box[:, [0, 2]] = box[:, [0, 2]].clamp(0, image_shape[0]) box[:, [1, 3]] = box[:, [1, 3]].clamp(0, image_shape[1]) w, h = box[:, 2] - box[:, 0], box[:, 3...
8abfcf589d90a87cdd4401097a2bb1bb141fce9a
603,563
def is_zip_archive(file_name): """test for zip file archive extension""" if file_name.lower().endswith('.zip'): return True else: return False
7e8f6b3304e05bb771d0fcce0677a4d89700829d
603,564
def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single ...
04b84a9e1e82426a2bc19fac5f75d0eb7a219b4a
603,568
import dill def load(fName): """ De-serialises object from pickle file, given `fName` """ with open(fName,'rb') as fobj: print("\nLoading serialised object from `{0}`".format(fName)) obj = dill.load(fobj) print("De-serialisation successful!\n") return obj
2f18fc6430c01dafd8a2325c6f18d9e9b8545dca
603,570
def model_to_dict(model): """Turns a Keras model into a Python dictionary :param model: Keras model instance :return: dictionary with model information """ return dict(model=model.to_json(), weights=model.get_weights())
95526d72427362bcc10a80fb13ff888bf0b55d8b
603,572
def find_neighbor(used_letters): """ This function help find the current position's neighbors that have not been used previously. :param used_letters: list, list of the indexes of used letters :return: list, list of indexes that are current position's neighbors and not have been used """ neighbo...
5058665c1e1c659192587c26e4348f7bfe2f2326
603,576
def compare_unhashable_list(s, t): """ Compare list of unhashable objects (e.g. dictionaries). From SO by Steven Rumbalski. """ t = list(t) # make a mutable copy try: for elem in s: t.remove(elem) except ValueError: return False return not t
a337ccda06bb8ec5aff3c7f139cba3b3b57f258a
603,579
def get_chrom(refseq): """Get the chromosome from a RefSeq entry. Parameters ---------- refseq : Bio.Seq.Seq A RefSeq entry Returns ------- str The chromosome extracted from the sequence id """ chrom = refseq.id # in case of scaffold genome if "|" in chrom: ...
fe08a0ba7900474eabf75da3d2bfe41e2c55e6f4
603,580
import socket def IsHostPortAvailable(host_port): """Checks whether the specified host port is available. Args: host_port: Port on host to check. Returns: True if the port on host is available, otherwise returns False. """ s = socket.socket() try: s.setsockopt(socket.SOL_SOCKET, socket.SO_RE...
6bd15452adeebb276666e8d0883490f6885de224
603,582
def make_list(obj): """Convert an object to a list if it is not already""" if isinstance(obj, list): return obj return [obj]
2757005b9d59e678986a5d66173c237be297672b
603,584
def RGQ_header_defined(vcf): """ Determine whether the RGQ annotation is defined in the FORMAT header of the vcf. """ try: vcf.get_header_type('RGQ') except KeyError: return False else: return True
0a899593dc4dcbae0df7e90fb6d1aeae6229d35d
603,585
def duration_from_seconds(seconds): """Converts a number of seconds to a time like format string.""" minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) timelapsed = "{:d}:{:02d}:{:02d}".format(int(hours), int(minutes), ...
981feb7a4ba7aeb6d4d6deb708d5cb51b53ff029
603,586
def bitcoinaddress2hash160(addr): """ Convert a Base58 Bitcoin address to its Hash-160 ASCII hex string. Args: addr (string): Base58 Bitcoin address Returns: string: Hash-160 ASCII hex string """ table = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" hash160...
85b35d5b14a79bd22831be718963f8176a6bc152
603,590
import pickle def load_plot(filename): """load a plot from a file""" return pickle.load(open(filename, "rb"))
17c18129b35c4ef05def45629032da3704024ae3
603,592
def seconds_to_timestamps(seconds): """Return a dict of timestamp strings for the given numnber of seconds""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) hms_parts = [] if h: hms_parts.append('{}h'.format(h)) if m: hms_parts.append('{}m'.format(m)) if s: hms_parts...
7263190c66db20baaa815894fa164672d5c7eb3d
603,593
def get_sizes_purities(clusters): """Return two lists containing the sizes and purities of `clusters`.""" sizes = [] purities = [] for cluster in clusters: sizes.append(cluster["size"]) purities.append(cluster["purity"]) return sizes, purities
91075470d54ef285c49be470eee26b321266e66c
603,595
def checkInAttributes(element,convertDict): """ Check if the there is something that needs to be converted in the attrib dictionary of xmlnode "element" @ In, element, the element to check in @ In, convertDict, the dictionary where the keywords to be converted are contained """ for key in convertDict....
1ceaeae78d99a25fe6eb75bf0bc0109cf441034f
603,597
from functools import reduce import operator def getFromDict(dataDict, mapList): """ Basic helper function which given a mapList (list) as a path gets the value from dataDict (nested dictionary structure) """ return reduce(operator.getitem, mapList, dataDict)
b046e842a1a9f69d9d404f1e3640c8ec7198e62e
603,601
def isomorphic_decode(s): """Decodes a binary string into a text string using iso-8859-1. Returns `str`. The function is a no-op if the argument already has a text type. iso-8859-1 is chosen because it is an 8-bit encoding whose code points range from 0x0 to 0xFF and the values are the same as the bina...
6ed8b2cf75fadb230bede7ab90f45f2f20e1a4bf
603,602
import re def humansort_key(strng): """Human/natural sort key-gathering function for sorted() Source: http://stackoverflow.com/a/1940105 """ if isinstance(strng, tuple): strng = strng[0] return [w.isdigit() and int(w) or w.lower() for w in re.split(r'(\d+)', strng)]
f633a05d9a599a0ec8e85782118dca47c06bba41
603,603
def lstrip_list(s): """ Return list with empty items from start of list removed. """ for i in range(len(s)): if s[i]: break else: return [] return s[i:]
f23dcbd5d8185fabccc68198a1685afa98b56eba
603,604
import base64 import binascii def IsValidBase64String(string_to_validate): """Verifies if a string is a valid Base64 encoded string, after replacing '-' with '/' :param string string_to_validate: String to validate. :return: Whether given string is a valid base64 string or not. :rtype: str ""...
c5d1c8e32f8d8e98171277baace3bc45b9f9e2da
603,607
def construct_captions(d, ids): """ Construct captions for entries in ids """ X = [] for x in ids: captions = d[x] for s in captions[:5]: X.append(s) return X
bbda31bc22582a45a05aa325c218c18a1c64d5e6
603,608
def mock_msg(cmd, body): """Wrap body in a dummy message header for cmd.""" return { 'head': { 'seq': 0, 'cmd' : cmd}, 'body': body, 'reply': None}
559c253402d6ffb3fe8cbf9fe5610626b28dfb75
603,609
from datetime import datetime def __make_data_point(measurement: str, tags: dict, fields: dict, time: datetime): """ Create a list with a single point to be saved to influxdb. :param measurement: The measurement where to save this point. :param tags: Dictionary of tags to be saved in the measurement....
43520c78a99feca4b3387eb0a09b459671098a7a
603,613
from typing import Any def get_identifier(request: Any, identifier: str, template: str, range_id=None) -> str: """ Takes a request object, parses it out, and returns a templated identifier suitable for use in an "id" field, including the incoming request information on host and scheme (http/https). :...
1693eca8832f145484b729fe69fcdf11e79d7999
603,615
def commutator(A, B, kind="normal"): """ Return the commutator of kind `kind` (normal, anti) of the two operators A and B. """ if kind == 'normal': return A * B - B * A elif kind == 'anti': return A * B + B * A else: raise TypeError("Unknown commutator kind '%s'" % ...
42dc27b9207056294ca88ec882943551da792e9f
603,619
def shorten_to(string: str, length: int, extension: bool = False): """ When a user uploaded a plugin with a pretty long file/URL name, it is useful to crop this file name to avoid weird UI behavior. This method takes a string (in this example the file name) and shortens it to the given length. ...
c3060630e277d944affdcbd82bd61bf3861a9285
603,620
def irange(*args): """ Similar to range but stop is an inclusive upper bound. """ if len(args) == 0: raise TypeError("irange expected at least 1 arguments, got 0") elif len(args) == 1: stop = args[0] start = 0 step = 1 elif len(args) == 2: start, stop = args step = 1 elif len(args)...
c25e8b7ab07a645199233f033a1417dac5355ca2
603,623
def single(iterable): """Returns a single item if the iterable has only one item""" return iterable[0] if len(iterable) == 1 else iterable
a16c198697233f1783dca720aa503bdd3a52d1f8
603,629
def flight_time_movies_3_utilize_set(movie_lengths, flight_length): """ Solution: As we iterate through our movie lengths, store the matching movie length needed in a set for a constant time lookup on all subsequent iterations. Complexity: Time: O(n) Space: O(n) """ if len(movie_lengths) < 2: raise ValueEr...
002d29b5dd8bbf9242a2a4e2fe3630a41297e8ff
603,635
def factorial(num): """Compute factorial of a number.""" result = 1 if num < 0: raise Exception('ValueError: factorial() not defined for negative values') elif num == 0: return result else: for i in range(1, num + 1): result = result * i return result
1bda6ca5e56c1e13db203928a5fa456fd50ceae1
603,642
def get_tts_type(cfg): """Get TTS type from the configuration.""" return cfg['TTS']['type']
490c4f6970badc074a6ee6f71818a532a714dfef
603,644
def parse_ID_from_query_comment(comment): """ Parses the NCBI-specific ID from the comment reported by the Mash match. The comment will look something like: [1870 seqs] NC_004354.4 Drosophila melanogaster chromosome X [...] and this function will return the "NC_004354.4" part of the comment. This func...
0a43130d1e1cf6f7c1c89b13413867b1c40e4caa
603,645
import torch def ctr_giou_loss_1d( input_offsets, target_offsets, reduction = 'none', eps = 1e-8 ): """ Generalized Intersection over Union Loss (Hamid Rezatofighi et. al) https://arxiv.org/abs/1902.09630 This is an implementation that assumes a 1D event is represented using the s...
5f676d8c4738fee6f9efb0575af982607d8fc27d
603,646
def get_fp_grad(v, g, x): """Returns the gradient of an fp-neuron at position x with the filter vectors v and g In the paper, Equation 8 corresponds to this function. Parameters ---------- v : np.array filter vector 1 g : np.array filter vector 2 x : np.array p...
535801e45522a87917c91c843983668d3a4eeec9
603,647
def truncate(text, length=100, suffix="..."): """ Truncates the given text to be no longer than the given length """ if len(text) > length: return text[: length - len(suffix)] + suffix else: return text
f81767d5ccc308d7c1449b68ed030723f1a1193b
603,653
def cellular_automaton(n, r=1, boundary="periodic"): """ Creates the adjacency matrix for a 1D cellular automaton, with the given number of cells and neighbourhood radius. :param n: the number of cells in this automaton :param r: the neighbourhood radius :param boundary: the boundary conditio...
9fd577282d56707985948409c14348ec196eca90
603,654
import random def roll(genome, random=random): """Randomly produce a set of genes based on the given genome.""" genes = {} for (geneName, gene) in genome.items(): if hasattr(gene,"roll"): genes[geneName] = gene.roll() else: genes[geneName] = random.choice(gene) return genes
47117386ca8deed9695272a620bed7bda74a50f8
603,660
def set_template(prefix, name, ext=".html"): """ This will return a safe template file path based on given params :param prefix: template root for module :param name: template name :param ext: template extension :return: formatted for flask """ return prefix + "/" + name + ext
d5c9007d05d287e23ed33f1b29219d2541ad1a51
603,665
def get_average_metric(metric_dict: dict, metric_name: str = 'Top1_Acc_Stream'): """ Compute the average of a metric based on the provided metric name. The average is computed across the instance of the metrics containing the given metric name in the input dictionary. :param metric_dict: dictionary ...
5033f52854e0f75d1652505000a3c5920cadc95f
603,669
def as_list(x): """A function to convert an item to a list if it is not, or pass it through otherwise Parameters ---------- x : any object anything that can be entered into a list that you want to be converted into a list Returns ------- list a list containing x ...
68415bfe9aeee8b69d5e03d0c7af3c9459803f7e
603,670
def _match_hash(x, y, no_match=None): """Returns an array of the positions of (first) matches of y in x This is similar to R's `match` or Matlab's `[Lia, Locb] = ismember` As in R's `match`, a hash (i.e. dictionary) is built to do the mapping. """ x_val2ind = {v: i for i, v in enumera...
9c339d45622d0b15316887bd61aab434463477f6
603,677
import random import math def get_distance(odd): """Advances a horse during one step of the racing simulation. The amount travelled is random, but scaled by the odds of the horse""" d = random.randrange(1, 100) s = math.ceil(odd) if d < 10: return 1 elif d < s + 17: return 2 ...
c0d63d579d38a4fbab69e2b5b143f1eefdcb6d6b
603,678
def highestMax(requestContext, seriesList, n): """Returns upto n seriesList members where the respective series has a max member is in the top-n.""" result_list = sorted( seriesList, key=lambda s: max(s) )[-n:] return sorted(result_list, key=lambda s: max(s), reverse=True)
0d2e8d82e9376b5fa36b6be9e07e5d2c07f54a2f
603,679
def _prepend_append_replace(word, prepend='', append='', replace='', replacement=''): """Prepends, appends and replaces text in a word. Args: word: A string literal to prepend, append or repla...
1a2370b5b8e0f245b6f929f0dbfe3b2be2690cf4
603,687
def get_timer_ids_from_group(view_timer_group): """Get the id's of every timer in a timer group """ timer_ids = [] for t in view_timer_group.get_timers(): timer_ids.append(t.id()) return timer_ids
93834e6bc1619dea91386bc35129b27e1ce324e2
603,689
def _clone_and_drop(data, drop_cols): """Returns a copy of a dataframe that doesn't have certain columns.""" clone = data.copy() for col in drop_cols: if col in clone.columns: del clone[col] return clone
2280c847d1403e807926569b031b3ff40fc013c4
603,694
from typing import Callable import click def verbosity_option(command: Callable[..., None]) -> Callable[..., None]: """ A decorator for setting the verbosity of logging. """ function = click.option( '-v', '--verbose', help=( 'Use verbose output. ' 'Use t...
92bf1bfed9ea138c6d0c301b6bcc19f89a6f18f0
603,701
def chunk_sentences(sentences, chunk_size): """ For a list of sentences, chunk sentences. Input: - sentences: list of single sentences - chunk_size: n sentences to be in one chunk Returns: - list of chunks, each containing n sentences """ # Create empty target list for chunks ...
e8cd58a5b6f8cd8896971057e7e48726241f70cc
603,702