content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict def _create_block(block_type: str, body: Dict) -> Dict: """ Creates a Dict that represents a Notion block with the given type and body (https://developers.notion.com/reference/block) """ return { "object": "block", "type": block_type, block_type:...
e258e57cdb6df227f8e7aea12fe676429c46c8bf
614,522
def recursive_tuplify(x): """Recursively convert a nested list to a tuple""" def _tuplify(y): if isinstance(y, list) or isinstance(y, tuple): return tuple(_tuplify(i) if isinstance(i, (list, tuple)) else i for i in y) else: return y return tuple(map(_tuplify, x))
0dba777f2aab63a6fed9b4c22d2ab5f1e44955cc
614,524
from typing import Dict def default_markers() -> Dict[str, int]: """ Default markers for the mesh boundaries """ return dict(base=10, rv=20, lv=30, epi=40)
bfef4345987eb7f51bc148dca4f08538533c811c
614,525
def get_shard_name(shard, num_shards): """Returns an appropriate shard name, as a string. A single shard name is simply 0; otherwise it will attempt to split up 0x100 into multiple shards. For example, in a two sharded keyspace, shard 0 is -80, shard 1 is 80-. This function currently only applies to sharding...
6b24c97b96104f8fce7817e56a6f1a95050e180d
614,529
def get_div_children(element): """Helper function to get children div elements given a requests-html.Element object""" return element.find(':root > div > div')
bac218484da80f4d513f21cef891038b4e55ec8f
614,530
import base64 def urlsafe_b64decode(s: bytes) -> bytes: """ Base 64 URL safe decoding with no padding. :param s: input bytes to be decoded :return: decoded bytes """ try: s += b"=" * (-len(s) % 4) return base64.urlsafe_b64decode(s) except Exception as e: raise Value...
19b186a18c808ee4c210cf68111c345c7e055ace
614,531
def _get_prediction_method(clf): """Return prediction method. `decision_function` method of `clf` returned, if it exists, otherwise `predict_proba` method returned. Parameters ---------- clf : Estimator instance Fitted classifier to obtain the prediction method from. Returns -...
d4c84c9e7d4c3a0d407dce6df7cbac8961119d4f
614,532
from typing import Tuple def is_winning_combo(combo) -> Tuple[bool, int]: """ Проверка на выигрышную комбинацию :param combo: массив значений дайса (см. перем. casino) :return: пара ("есть_выигрыш?", "изменение счёта игрока") """ # Все комбинации из трёх одинаковых оцениваем в 10 или 7 очков...
5b94b77dcacb9a072b5623f4035ea126d46fc2f3
614,534
def format_fasta_record(name, seq, wrap=100): """Fasta __str__ method. Convert fasta name and sequence into wrapped fasta format. Args: name (str): name of the record seq (str): sequence of the record wrap (int): length of sequence per line Yields: tuple: name, sequenc...
b25cf99a70600a092c15565683c2787b15b1fd64
614,536
def in_any_seq(item, seq_seq): """Returns: true if item is present in any sequence of the sequence of sequences. >>> in_any_seq(1, [(2,3,4),(3,2,1)]) True >>> in_any_seq(1, [[2,3,4],[3,2,3]]) False """ for seq in seq_seq: if item in seq: return True return False
2a1005813f3bd2682c47aab81946f4ad5541c427
614,537
def serialize_proto(proto): """Serialize the protocol buffer object.""" if proto is None: return b'' elif isinstance(proto, bytes): return proto elif (hasattr(proto, 'SerializeToString') and callable(proto.SerializeToString)): result = proto.SerializeToString() ...
dc241367daf5699a6a176e6672aa2bff122e1997
614,539
import logging def _lookup_embedding(embedding_table, word_token, word_lemma, verbose=False): """ Helper function used to lookup word embeddings in the embedding table; incorporates back-off strategies if the exact token is not found in embedding table keys. """ # Map None to None if not word_token: ...
ada1f1fc5d30c7de3d880b45563c130c9845476e
614,540
import textwrap def wrap_elem(s, width): """Take a string, and attempt to wrap into a list of strings all less than <width>.""" return textwrap.wrap(s, width=width)
68f60a8898046552a95d5d5477a03ac1d0f6ac43
614,542
def _undo_op(arg, string, strict=False): """ Undo symbolic op if string is in str(op). Returns <arg> untouched if there was no symbolic op. Parameters ---------- arg : any symbolic variable. string : str String that specifies op. strict : bool Whether to force op undo o...
c2cd121ae2ebce49c921fff0f63e0dfd844565d9
614,543
def add_dict_value(dict1, dict2): """ add dict2 value to dict1""" for key, value in dict2.items(): dict1[key] = dict1.get(key, 0) + value return dict1
15449a33b849d5fe0795369a3c8da11520787dc6
614,544
import posixpath def make_relative_url(base, target): """Returns a relative URL from base to target.""" if base == '/': depth = 0 prefix = './' else: depth = ('/' + base.strip('/')).count('/') prefix = '' ends_in_slash = target[-1:] == '/' target = posixpath.normpa...
0f340a38dc06f10c4e22a2fe1b05d3b6a54b5a34
614,547
def _save_state(view): """ Save ths current size, selection and viewport position for the provided view. """ return (view.size(), list(view.sel()), view.viewport_position())
7574284f5f8d441ac8d8c7dc0bad82b906629e8c
614,549
def limit_data(data_dict: dict, limit: int = -1) -> dict: """apply limitation to data set Args: data_dict (dict): set with source and target limit (int, optional): limit of data to process. Defaults to -1. Returns: [dict]: dict with limited source and target """ if ...
7ec0990659092ae98882dca90d5a288e5b23d2dc
614,550
def seconds_to_frames(frame_rate, number_of_seconds): """Converts number_of_seconds to the equivalent number of frames.""" return int(number_of_seconds * frame_rate)
90c1cc552df39766c45ffc117c557a650177e260
614,552
def searchPFAMmatch(list_pfamId_orga_A:list, list_pfamId_orga_B:list, dict_ddi_sources:dict): """ Combine all the pfam ids and check if they exist in the dictionary of ddi, if yes the tuple was add to an array and returned. This method check the id_pfam_A - id_pfam_B AND id_fam_B - id_pfam_A :param lis...
2825607c2f270be30c6f5bc9c97af112d7b7f4d7
614,553
def get_pronouns(gender: str): """Gets a list of pronouns based on the gender given. Only binary genders supported, sorry.""" gender = gender.lower() if gender == "female": pronoun = ["she", "her", "her"] elif gender == "male": pronoun = ["he", "his", "him"] else: pronoun = [...
c97bc0a6c783320f951650ed4f92d2f06cce8172
614,555
def uint8_to_bool(np_img): """ Convert NumPy array of uint8 (255,0) values to bool (True,False) values Args: np_img: Binary image as NumPy array of uint8 (255,0) values. Returns: NumPy array of bool (True,False) values. """ result = (np_img / 255).astype(bool) return result
55b0b5f1376a7619f2691a05890e5840717f9716
614,560
import math def cdf(x): """Calculate approximation of Cumulative Distribution Function by using Hart Algorithms y = |x| if y < 7.07106781186547 N(x) = exp(- y*y / 2) * (A / B) where A = (((((a1*y + a2)*y + a3)*y + a4)*y + a...
ba51bb81251d568b11ea0c21ea380d81b89794af
614,562
import asyncio def wait(aws): """Waits for all of the awaitable objects (e.g. coroutines) in aws to finish. All the awaitable objects are waited for, even if one of them raises an exception. When one or more awaitable raises an exception, the exception from the awaitable with the lowest index in the aws list...
b6b4009ca59ba04ac56fa594f3379cad581c9a38
614,563
def yes_no_to_bool(string, empty_string_means=None): """Convert 'yes' or 'no' inputs to True or False boolean. Optionally, set an emtpy string to mean either True or False. Throw an error at other inputs.""" if string.lower() in ["yes", "y"]: return True elif string.lower() in ["no", ...
166ae8b549382a79e111de72bad33aef15451300
614,564
from typing import Iterable import hashlib def _hash(items: Iterable[str]): """Calculate hash of items.""" m = hashlib.sha256() for item in items: m.update(item.encode()) m.update(b"\xc0") return m.hexdigest()
be5e8a95cab76cf9503136149eddad1ee4f05430
614,567
import platform import json def sanity(event, _): """ Basic test, using the Epsagon lambda-wrapper :param event: events args :param _: context, unused :return: Success indication """ body = { 'message': 'Epsagon: General Acceptance Test (py {})'.format( platform.python_...
c88533b7dc8954319f1d49ca4c3133d8e1304d9f
614,569
def accuracy_metric(actual, predicted): """ Computes the accuracy percentage of a predicted classification when compared to the actual truth """ correct = 0 for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / float(len(actual)) * 100.0
29932800889b42c992bf219d9c1c0c7a8283a2f3
614,571
def mail_status(detection): """Write the status text for the mailbox.""" if detection == 0: return"Full!" elif detection == 1: return "Empty"
5bf219da7cf82ae2f916f56bd5a8e8813f29b1a6
614,572
def get_feature_class(row, quantile_list): """ Helper method for stratification. Returns class label based on quantile boundaries. Parameters: -------------- row: int, data point or series entry quantile_list: list with quantile measures Returns: --------------...
55fd1cb27375da3147dda092cbe65fbfc1f13f18
614,578
def removeprefix(string, prefix): """ Returns <string> without the <prefix> prefix. Copied from https://www.python.org/dev/peps/pep-0616/#specification to support python versions < 3.9 :param str string: string from which to remove prefix :param str prefix: prefix to remove from string :re...
9be0b72e525b688001fcb1d1068c69e0c7eafee2
614,586
def _normalize(min_, max_, val): """ Natural map from [min_, max_] -> [0, 1] """ assert min_ < max_, '{} !< {}'.format(min_, max_) return (val - min_) / (max_ - min_)
ecefea4bbe8c0936021a544070d0975046c58d36
614,591
def _to_generic_pyver(pyver_tags): """Convert from CPython implementation to generic python version tags Convert each CPython version tag to the equivalent generic tag. For example:: cp35 -> py3 cp27 -> py2 See https://www.python.org/dev/peps/pep-0425/#python-tag """ return [...
d784da44a5982ca243031d0cccb8146e44d82fcf
614,595
def __compute_num_layers(bpp, extra_bits, layer_bits=64): """ Computes the number of 'layers' required to store the original image with bpp bits-per-pixel along with the results of len(extra_bits) filtered versions of the image, each requiring bpp + extra_bits[i] bits. The filters are done in that order...
3c2d1365c56a4523d37054425cb6af95de77e66a
614,596
from typing import List def get_available_metrics() -> List[str]: """Get list of available metrics. Returns ------- List[str] List of implemented metric names. """ metrics = ["NSE", "MSE", "RMSE", "KGE", "Alpha-NSE", "Pearson-r", "Beta-NSE", "FHV", "FMS", "FLV", "Peak-Timing"] ret...
88779f45fc6bcf6363f69c030830683e371083c0
614,598
def is_file(node): """Check is node a file.""" return node.get('type') == 'file'
9fd506b778dc5f4a6360d19f5825057681bee2ef
614,603
import hashlib, mmap def md5_file(filename): """ Return the hex string representation of the MD5 checksum of filename. """ with open(filename, "rb") as f: m = hashlib.md5() try: with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm: for chunk in iter...
b6d03dbb34201c14b947695521f3278ed07bc59e
614,607
def nova_conf(host, ansible_vars): """ Get OpenStack Nova conf file and return a list with each item in the list representing a line in the Nova conf file """ nova_path = ansible_vars.get("nova_conf_path", None) if not nova_path: raise KeyError("Could not get nova_conf_path Ansible var") ...
9cf75d17fce3e7aa05d5250d5798748c9938b470
614,612
import random def make_weighted_choice(weights): """ Utility function to make weighted random choices. Pass a list of floats representing the weights of a series of options. Get back the index of the option that was selected. :param weights: list of floats, representing the weights of the options...
594948cf795ab80e982c438102eac0a4410143d2
614,615
def get_kegg_section(k_record, sname, whole_section=False): """Get the section with name `sname` from a kegg compound record. Returns a str, possibly empty.""" in_section = False section = [] for line in k_record.splitlines(): if line.startswith(sname): in_section = True ...
bf12ac9cfa24a6f33805be86ddfe669a3b3908e1
614,618
def readFileIntoList(fileName): """ Reads a single file into a single list, returns that list, strips newline character """ inFile = open(fileName) items = list() for line in inFile: items.append(line.rstrip('\n')) inFile.close() return items
4ce28d3c70555d6ca31edf2562874eeaf0bc4a60
614,621
def split_by_whitespace(text): """Runs basic whitespace cleaning and splitting on a piece of text. Examples: >>> _text = '我爱python,我爱编程;I love python, I like programming.' >>> split_by_whitespace(_text) ['我爱python,我爱编程;I', 'love', 'python,', 'I', 'like', 'programming.'] """ text...
4ede92215545aab7a55eac5b0733b91497340c60
614,624
def get_double_period(time1, time2): """ This method concatenates two different time strings and returns a single time interval string The order of the paramters does not matter. Example: get_double_period("08am-09am", "09am-10am") returns "08am-10am" get_double_period("09am-10am", "08am-09am") returns "08a...
7488ce57c34e6d154c24f041e38e988a33500123
614,626
def Confirm(text, default='N'): """Asks the user to confirm something. Args: text(str): the text of the question. default(str): set the accepted value if user just hits Enter. Possible values: 'Y' or 'N' (the default). Returns: bool: True if the user confirms, False otherwise. """ print(tex...
57e55ad780b9a442d245b2e12863d52650a7aa56
614,628
import time def convert_epoch_to_human_readable(input_epoch): """takes epoch value and converts to human readable time.strftime("%m-%d-%Y_%H-%M-%S", time.localtime(1442530758)) '09-17-2015_15-59-18' """ converted_epoch_value = time.strftime("%m-%d-%Y_%H-%M-%S", time.localtime(input_epoch)) return converted_epoc...
adbf0f8435baa5eabc0986b562a6c6022bdac5e7
614,629
def selection_sort(alist): """ Sorts a list using the selection sort algorithm. alist - The unsorted list. Examples selection_sort([4,7,8,3,2,9,1]) # => [1,2,3,4,7,8,9] a selection sort looks for the smallest value as it makes a pass and, after completing the pass, places it in ...
f986addfdfd402403d57524a9f8b0d46751367a9
614,631
import socket def is_local_port_open(port): """ Args: port (int): Returns: bool: References: http://stackoverflow.com/questions/7436801/identifying-listening-ports-using-python CommandLine: python -m utool.util_web is_local_port_open --show Example: ...
4091af0eb160b89d0fdfdea6cf894c2927772287
614,633
def getAnswer (answer): """ Function to get YES or NO answer from the user usage: x = getAnswer('mensage to display ') """ while True: user_input = input(answer).lower() if user_input != "y" and user_input != "n": print('Use Y for yes and N for no') else: ...
22fb1192cb771e91c75bb1cd331e9d4f643a1ed1
614,634
def remove_multiPV(opt): """delete MultiPV from the options""" del opt["MultiPV"] return opt
c9bb7559455b20eb2d84965ea2b4e34c1d420249
614,638
def quoteStringArgument(argument): """ Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string li...
ce43bfc7d6ead887fe8c520154bbe829939dcda3
614,642
from typing import Any import json def is_jsonable(x: Any) -> bool: """ Verify if object is JSON-serializable. Arguments: x : Literally any Python object. Returns: True : If json.dumps(x) succeeds. False : I...
92756db835da15f03eaf60f85616492752f1193f
614,643
def cpm(total_cost, total_recipients): """Return the CPM (or Cost per Mille) based on the marketing cost per 1000 customers. Args: total_cost (float): Total cost of marketing. total_recipients (int): Total number of marketing recipients. Returns: cpm (float) as total cost of market...
d7517b64814a0a7e2fa0845f6de9d0e78d05a220
614,647
def design_symmetric_compound_lens(f, w): """Design a compound lens with a given focal length and working distance. Args: f: Desired focal length. w: Desired working distance, defined here as distance from focal planes to the outer principal planes of the singlets. Returns: fl: Focal...
56cf9eed16700a7c01d044ef2ae3318e670b7890
614,650
def parse_definition_ref(ref: str) -> str: """Parse a reference to a definition and return the definition name.""" prefix = '#/definitions/' if not ref.startswith(prefix): raise ValueError("Expected a ref with prefix {!r}, but got: {!r}".format(prefix, ref)) return ref[len(prefix):]
2960b8eecf223fa727d924bf38ebbe3bb52ee61d
614,651
def citations_versus_references(obj, citations_from_descr): """Given an object an a list of citations found in the description, return the difference between the amount of citations and external references """ citations_len = len(citations_from_descr) ext_references_len = 0 if obj.get('exter...
83f9b1ef3a0bd1c000e4c8a6b70f89f7ffdd6c44
614,652
def get_port(parsed_url): """ Get port from parsed URL """ if parsed_url.port: return parsed_url.port if parsed_url.protocol == "https": return "443" return "80"
97a4f6886b5023054b3adfcc02abe5368d417b51
614,654
def get_reddit_posts(subreddits, limit, score, num_comments): """Collect submissions related data, including title, link, current score, the number of comments, etc. Params: ------- subreddits: list a list of praw.Reddit.subreddit instances limit: int maximum number of submissio...
664720609116cdd4512cec225b18fbb51a1e7369
614,656
def deltas(numbers): """ Returns the changes between consecutive numbers in a list of numbers. Example: deltas([1,5,3]) -> [4, -2] Parameters ---------- numbers : list The list of numbers to process. Returns ------- A list containing the differences between a series of n...
155073e249141643f169fc2684042914356171f1
614,657
import torch def _angle_from_tan( axis: str, other_axis: str, data, horizontal: bool, tait_bryan: bool ): """ Extract the first or third Euler angle from the two members of the matrix which are positive constant times its sine and cosine. Args: axis: Axis label "X" or "Y or "Z" for the an...
4f9999f3621d18b2a3f1a93495f84e1eb11d0ce2
614,660
import string def replace_punctuations(text, replacement=' '): """Replace the punctuations (``string.punctuation``) in a string.""" for punctuation in string.punctuation: text = text.replace(punctuation, replacement) return text
81edde3e84a533396ddfa1ce740a26760c665794
614,662
def scan_tags(tags): """ Input bam tags Return UMI and cell barcode sequences """ cell_barcode = None umi = None for tag in tags: if tag[0] == "CB": cell_barcode = tag[1] elif tag[0] == "UB": umi = tag[1] else: pass return cell_...
13f0397f4aa311ce29442b9d6b007e84e5f12beb
614,664
def extract_cert_check(key, device, not_secret): """ Check function for extracting PTCRB info. :param key: Device entry. :type key: dict :param device: HWID, FCCID or name of device. :type device: str :param not_secret: If device is not market as secret. :type not_secret: bool """...
f364a95654e1b9b1251e757ba23e6481c837a621
614,665
def sort_model_preds(dataset, model_preds): """ Sorts the model predictions in the order that the input dataset is in. """ # Dictionaries are insertion ordered since Python 3.6+, ordered_preds = {} for sentence_id in dataset: ordered_preds[sentence_id] = model_preds[sentence_id] re...
8047c008c7def7ff8a2326c7091ba35d4f829e93
614,670
def get_day_name(weekday): """ This function gets the number of the day considering the week and returns a String. The string corresponds to the name of the weekday in Portuguese. :param weekday: int The weekday is generated by a funct...
0ecbfad6887f6dd254b12255301c052e423593c6
614,671
import json def load_test_data(test_dir: str, test_name: str) -> dict: """ Returns the contents of a json file at location of: test_dir/test_name.json This is meant to keep large amounts of json needed for testing outside of the tests themselves and as the actual json responses from the API "...
d67bddb651f6eea2783f9d7a5f3a5806f2186264
614,672
import base64 def b64encode(content: bytes) -> str: """ Syntactic sugar for: >>> import base64 >>> y = base64.b64encode(content).decode('utf-8') Since `base64.b64decode(str)` returns bytes, the reverse is not provided. :param content: content to encode :return: content encoded as a stri...
c5ab554d93eac06c2e9179dca112499e87888fc7
614,673
def int_formatter(i): """ Int formatter (%d) :param i: The integer to format :return: The string representation of i to be saved to file with a newline appended """ return '%d\n' % i
0717dc53ba80115a2147fad858841b77331876ce
614,677
def find_prefix_match(prefix, choices, start_index=0): """Return index of element in 'choices' that starts with 'prefix'. prefix the prefix string to search for choices list of choces strings start_index the index to start searching 'choices' at Returns an index into 'choices' of uniqu...
53f50752127350eda41b3b84d5527114f2b9ee73
614,678
def open_bytes_file(path: str) -> bytes: """Opens file to bytes object""" f = open(path, "rb") return f.read()
652be50ab1da09852535401bf90fd446a84f17be
614,681
def resolved(issue): """Is the issue resolved?""" return issue.fields.status.name in ['Done', 'Resolved', 'Fertig', 'Closed']
b4de64097e8f0280d0c3250d1013ff312b87e4b9
614,683
import requests def _raw_fetch(url, logger): """ Fetch remote data and return the text output. :param url: The URL to fetch the data from :param logger: A logger instance to use. :return: Raw text data, None otherwise """ ret_data = None try: req = requests.get(url) if...
36ec9a9ec2c0b4e5f0bfdff4af817c6ff6f79e4b
614,687
def number_group(number): """ The number_group function should return "Positive" if the number received is positive, "Negative" if it's negative, and "Zero" if it's 0. """ if number > 0: return "Positive" elif number < 0: return "Negative" else: return "Zero"
4a1d6db5e7ad280172833fb5059a964c21d8c8b9
614,690
def parse_happy_summary(summary_path): """ Turn the happy summary into a dictionary we can easily get F1 scores etc. from """ results = {} # make something like: results[INDEL][METRIC.F1_Score] = 0.9x with open(summary_path) as sum_file: header = sum_file.readline().split(',') for line in s...
96eb2016b0183c8c247ca25256ab6aee32b97021
614,698
def parse_series(list): """ Parse series from a MangaUpdate's search results page. Parameters ---------- list : BeautifulSoup BeautifulSoup object of the series section of the search results page. Returns ------- series : list of dicts List of manga found by the search....
930e2b8fe0dde4d4adcc3be69c1183e7b4db4e6e
614,702
def get_log_level(client): """Get log level Returns: Current log level """ return client.call('get_log_level')
5ffb3c32a076aa72bbeab273211a6951dcb8d44a
614,707
from typing import Union from typing import List def nested_count(obj: Union[object, List]) -> int: """Return the number of integers in obj. >>> nested_count(27) 1 >>> nested_count([4, 1, 8]) 3 >>> nested_count([4]) 1 >>> nested_count([]) 0 >>> nested_count([4, [1, 2, 3], 8]) ...
b2d8c057ffb57ea4884633d2d3584be45af8d866
614,708
import torch def get_scheduler(optimizer, config): """ Creates the scheduler from the config """ if config["name"] == "cosine": scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=config["T_max"]) return scheduler else: raise NotImplementedError
c8eaf3ad70536b01d11317d3f1dc6f15543f9713
614,715
def boost_overlap(group_overlap, overlap): """ Return a fraction of boost based on the number of overlap events in the IAR. :param int group_overlap: The number of overla events in the IAR. :param overlap: The total boost amount allotted to this criterion :returns: The percent of boost provided by ...
caefa6bbfeceabd78f2f03457e29da41501e04c0
614,724
def floatValidator(text): """ TextEdit validator for floats. """ return not text or (text.replace('.', '').isdigit() and text.count('.') <= 1) or (text[0] == '-' and (len(text) == 1 or text[1:].replace('.', '').isdigit()) and text.count('.') <= 1)
e4898bbf827b95fe4899b2d71d491698b344a612
614,726
from typing import List def _index_within_range(query: List[int], source: List[int]) -> bool: """Check if query is within range of source index. :param query: List of query int :param source: List of soure int """ dim_num = len(query) for i in range(dim_num): if query[i] > source[i]: ...
b2798d6fb2c6aa9398f229af1d6f34c03479712d
614,729
def add(*args): """Add a list of numbers""" sum = 0.0 for arg in args: sum += arg return sum
51d3c55af584bafe7248e93011342fbb636a8028
614,730
def get_predecessors(blocks, blacklist=set()): """ Get set of predecessor blocks of a given set of blocks. Optionally, it can be filtered with set of blacklisted blocks. """ preds = set() for block in blocks: preds |= set(block.preds()) preds = preds.difference(blacklist) return ...
acaea26042de9125a9e2be810d324eb08cdf9c4b
614,731
from typing import Union from typing import List from typing import Tuple def first(data: Union[List, Tuple]): """ Returns first element from list or tuple. """ if isinstance(data, (list, tuple)) and data: return data[0] return None
736664c0a9142c6507ee7de45c8e4986036ca194
614,736
import glob def find_genomes(path): """ Takes a path to a directory of genomes, Returns a list of genome paths """ paths = [] for fasta in glob.glob("{}/*.fasta".format(path)): paths.append(fasta) return paths
941a05690234c2deb981b37dedb1843263ce04d1
614,737
from typing import Union from pathlib import Path def remove_suffix(path: Union[str, Path], suf: str) -> str: """Remove a suffix from a string, if it exists.""" # modified from https://stackoverflow.com/a/18723694 if isinstance(path, Path): path = str(path) if suf and path.endswith(suf): ...
8e48152e4add2a8f3c4497ab0f3a083776799e5c
614,740
def pluralize(number, singular='', plural='s'): """ Pluralize filter for Jinja. Source: http://stackoverflow.com/a/22336061/411514 """ if number == 1: return singular return plural
3027f71dfb1ed1b19d5eb3e5f05f754e34dc8e43
614,741
def format_cwt(x): """ format cwts as 63-03-99 """ x = str(x) cwt = "-".join([x[:2], x[2:4], x[4:6]]) return cwt
db62202ec9f7eda585b963f7803b0c14c9c540f8
614,744
def _false_test(x): """Finds where not False (where is True). Parameters ---------- x : array_like Array to search. Returns ------- array : array of bool Whether corresponding index is True. (Is not False.) Notes ----- Converts to bool dtype as integer could ha...
877b3ee801cefc1575784dc720c8c60024781aac
614,745
def validate_results(results): """ Fill in any missing values. Args: results (dict): Output of the calculate_matchups() Returns: Updated results dictionary with all class combinations represented. """ names = results.keys() for p1_type in names: for p2_type in name...
f6712835ab4638bd7a63f151d04e017a8c38fe47
614,746
def unique_name(name, all_names): """Make the name unique by appending "#n" at the end.""" if not isinstance(all_names, set): all_names = set(all_names) if name not in all_names: return name i = 1 head, sep, tail = name.rpartition('#') if sep: try: i = int(...
c32d1570b4eb4097e45be0f1cf53856492382ae6
614,754
def ids_as_lists(filename): """ Return the IDs in FILENAME as lists of characters, assuming one ID per line. """ ids = [] with open(filename,"r") as f: for line in f: ids.append(list(line.rstrip())) return ids
c471c3e44e7133aca60413151b4069177b1ce3b5
614,758
def _check_ddl_statements(value): """Validate DDL Statements used to define database schema. See https://cloud.google.com/spanner/docs/data-definition-language :type value: list of string :param value: DDL statements, excluding the 'CREATE DATABASE' statement :rtype: tuple :returns: tuple...
f5d08f98c8c5ab7089b0058eb1a5ceaf0f94ad34
614,763
from typing import Dict def create_damping_dryfriction_domain_param_map_wamjsc() -> Dict[int, str]: """ Create a mapping from indices to domain parameters (as used in the `LFI` algorithm). :return: dict where the key is the index and the value is the domain parameter name """ return { 0: ...
2a7bc0f63cc05e91cadd7e104c13c7c75a108aa9
614,764
def get_clk_hrow_and_rebuf_tiles_sorted(cur): """ Finds all CLK_HROW_TOP_R, CLK_HROW_BOT_T and REBUF tiles. returns them in a list sorted according to their Y coordinates. """ cur.execute( """ SELECT name FROM phy_tile WHERE name LIKE "CLK_HROW_BOT_R_%" OR name LIKE "CLK_HROW_TOP_R_%" O...
7cfd6005dc8b8d7830386cd7c6d4dab600a8a0d2
614,771
def _has_levels(section): """ Check if a given configuration section has levels or not. """ # Bit of a hack... num_dicts = [x for x in section.values() if type(x) == dict] return len(num_dicts) == len(section)
f291101fe11216cb29ec846fa8ac5abd8ab75137
614,774
def _interpolate(elem, invstep, trans, scale): """Interpolate SVG path element so on average we have ~invstep points per unit distance""" dist = abs(elem.start - elem.end) * scale steps = max(1, int(dist * invstep)) return [scale * (elem.point(i/steps)+trans) for i in range(steps)]
b1c211e9e719fc239bd0f74f69a93cdcd4923d2b
614,775
from typing import Dict from typing import Any from typing import List def handle_ruling_rows( card_data: Dict[str, Any], card_uuid: str ) -> List[Dict[str, Any]]: """ This method will take the card data and convert it, preparing for SQLite insertion :param card_data: Data to process :param ca...
d8d020caa223bb6f9be9f72f4711f72752601bb7
614,778
def count_bits(string: int, bitval: str = '1') -> int: """Count the bit value in a bistring Args: string (bitstring) - a bitstring to count the bits of bitval (string) - include the option to count unset bits Returns: int - the number of bits equal to bitval """ return bin...
5e67e6fd836f967d7098d1f913e5b79a602ffb26
614,780
def equip_sensors(worldmap, sensors): """ Args: worldmap (str): a string that describes the initial state of the world. sensors (dict) a map from robot character representation (e.g. 'r') to a string that describes its sensor (e.g. 'laser fov=90 min_range=1 max_range=5 angle_increment=5'...
32ebc1fe92d5d571b1b823867ef1ffaf0374f380
614,781
def GetUpdateTimestep(algorithm): """Returns the requested time value, or None if not present""" executive = algorithm.GetExecutive() outInfo = executive.GetOutputInformation(0) if not outInfo.Has(executive.UPDATE_TIME_STEP()): return None return outInfo.Get(executive.UPDATE_TIME...
2ef507aa6d75c59afdfd25455855f96d9dc7ff8c
614,782