content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def str_to_fancyc_comment(text): """ Return a string as a C formatted comment. """ l_lines = text.splitlines() outstr = "/* " + l_lines[0] + "\n" for line in l_lines[1:]: outstr += " * " + line + "\n" outstr += " */\n" return outstr
3ee7fd146c8390346dfa9580870aef0551124339
539,025
def _code_range_to_set(code_range): """Converts a code range output by _parse_code_ranges to a set.""" characters = set() for first, last, _ in code_range: characters.update(range(first, last+1)) return characters
3cb7c2771bec698241ae4d2ae103e4827493e40d
617,676
def easy_product(a, b): """Takes two numbers and returns their product""" return a * b
8a455a81a8a6b4a3219874d52b50bb84d2587b89
302,801
import textwrap def get_notifiers_provider_config(message, subtitle, title) -> dict: """ Return kwargs that will be passed to `notifiers.notify` method. """ # different providers have different requirements for the `notify` method # most seem to take a `message` parameter, but they also have diffe...
45d78bdd37925d85eab91aaad430696f23cb4c70
691,896
import random import string def get_random_string(n): """ Create random string with len `n` """ return ''.join(random.choices(string.ascii_letters + string.digits, k=n))
b1d354d8a7f1a4c3520e865fd87e2f2ca048699e
619,359
def generate_question_with_choices(choices: list[str], message: str) -> list[dict]: """Generate a multiple choice single select question with <choices> and <message> and return it in py-inquirer format :param choices: choices of the question :param message: message of the question """ return [ ...
1379d4c1ca6dca2e9bae786a9b2937de6cf95ec3
118,696
def top_hat_width(subband_df, subband_f0, DM): """top_hat_width(subband_df, subband_f0, DM) Returns width of a top-hat pulse to convolve with pulses for dipsersion broadening. Following Lorimer and Kramer, 2005 (sec 4.1.1 and A2.4) subband_df : subband bandwidth (MHz) subband_f0 : subband center fre...
5e6d399a3d78952ef6ea7f30101ebc5bddd2bc8a
57,705
def ReadFile(filename): """Utility function reads a file and returns its content. Args: filename: the file to read. Returns: The file content. """ with open(filename, "r") as data_file: return data_file.read()
7487e5c2e238f8890cdb1582ace984278346434e
585,396
import logging def exists_handler_with_name(name: str) -> bool: """ >>> discard = set_stream_handler() >>> assert exists_handler_with_name('stream_handler') >>> discard2 = set_stream_handler_color() >>> assert exists_handler_with_name('stream_handler_color') >>> assert not exists_handler_with_...
ab2fc4f6b1a7ae02c74164c7054ad0e4fe24312a
107,918
import re def _unescape_value(value): """Unescape a value.""" def unescape(c): return { "\\\\": "\\", "\\\"": "\"", "\\n": "\n", "\\t": "\t", "\\b": "\b", }[c.group(0)] return re.sub(r"(\\.)", unescape, value)
84a2c4cd39e90b219be3ec68e5e88e1e68def56b
539,975
def repeat(string, n): """ Description ---------- Repeat a string 'n' number of times. Parameters ---------- string : str - string to repeat n : int - number of times to repeat Returns ---------- str - string consisting of param string repeated 'n' times Example --...
7edef4df6df14fd7b9087771b000c026e1715689
88,675
from datetime import datetime def roundTime(dt=None, roundTo=1): """Round a datetime object to any time lapse in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 15 seconds. """ if dt == None : dt = datetime.now() seconds = dt.replace(second=0,microsec...
1c383917fb4b0aab130f1ecd8e5f05b069f454b9
398,579
import zipfile def extract_zipfile(source_zip): """ unzips your new zip file into a temporary directory to work in :param source_zip: a .zip file :return: None. should create a temp dir in the PWD then put the .zip contents in it """ # unzip the .zip zip_ref = zipfile.ZipFile(source_zip, '...
13a9426771bb7209cda5344b36ce49cbe66590c2
68,626
import ipaddress def getResourceManagerIpv4(args): """Retrieve the IPv4 address of the cloudFPGA Resource Manager. :param args The options passed as arguments to the script. :return The IP address as an 'ipaddress.IPv4Address'.""" ipResMngrStr = args.mngr_ipv4 while True: if args.mngr_...
5f5baecad256bcfde2e555d229448c68da3580a8
514,497
import sqlite3 def get_tile(dbfile, z, x, y): """Get a specific image tile from an sqlite db.""" con = sqlite3.connect(dbfile) with con: cur = con.cursor() cur.execute('SELECT image FROM tiles where z=? AND x=? AND y=?', (z, x, y)) image = cur.fetchone()[0] return str(image)
709e1577ada327c802a34311e193cc19fde1b8e0
440,356
import requests from bs4 import BeautifulSoup def _scraper(url): """ Scraper function :Param url: url to be scraped :Return: BeautifulSoup object """ response = requests.get(url) assert response.status_code == 200, "url could not be reached" soup = BeautifulSoup(response.content, "ht...
77fb20d7f3519587195226ccbf71635021350d29
285,165
def test_case_is_success(test): """Determine if the the test expects a successful parse""" if "results" not in test: return True for result in test["results"]: if "error" in result: return False return True
fee43364a8a11ed42564b07533a2500b69c60894
635,677
def get_recipients(msg, recipients): """Given a parsed message, extract and return recipient list""" msg_fields = ['From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Sender', 'Subject', 'In-Reply-To', 'Message-ID','References'] for f in msg_fields: if msg[f] is None: continue if f == 'Subje...
e76868e3427e4c578c79b9ac897047a11aaab129
224,876
import posixpath import ntpath def _is_abs(path): """ Check if path is absolute on any platform. :param str path: Path to validate. :returns bool: True is absolute on any platform, False otherwise. """ return posixpath.isabs(path) or ntpath.isabs(path)
08d13e51c42da51196c1e92d90783ab24b6e9382
531,321
def match_any(matcher, values): """Check if the matcher matches *any* of the supplied values. :param matcher(regex pattern): compiled regular expression. :param values(list): list of ``str`` values to match. :returns: ``True`` if *any* of the ``str`` values matches (fullmatch) the matcher; oth...
cd7c8d9cb0e2adf85a665be22acefc34d8058735
304,131
def is_valid_scheme(scheme: str) -> bool: """Validate a scheme. Arguments: scheme: scheme to validate. Returns: True if is valid else False. """ return scheme.lower() in ("http", "https")
9fccb1eb57e5fe3b36551cb2f84a10b9db7181b1
191,220
def stop_server(proc): """ Stop server process. proc: ShellProc Process of server to stop. """ return proc.terminate(timeout=10)
c126ca840b56407f1eea8af943f4602532df13df
16,318
def dget(d, dkey, default=None): """Dictionary get: gets the field from nested key Args: d (dict, list): Dictionary/list to retrieve field from dkey (str): Nested key to retrive field from dictionary/list separated by periods. Example: key1.3.key2, this will be the equivalent of ...
813aaad713f2167fac3b479903b021bc409d0d6c
97,611
def NW(N, tp='U'): """function to compute number of edges or number of feasible vertex-pair Args: N (int): number of nodes tp (str, optional): Can be either 'U' for undirected and 'D' for directed graphs. Defaults to 'U'. Returns: int: number of edges or number of feasible vertex-p...
5b13eaf1c2d1b50e9ddd7e9e8dec3b999722dd4f
379,572
def interpolate(x1, y1, x2, y2, current_step, total_steps): """Interpolates between two 2d points. Args: x1, y1, x2, y2: coords representing the two 2d points current_step, total_steps: ints representing the current progress (example 2, 10 represents 20%) Returns: 2-float tuple repr...
b61c493b86815c5373c414abc4da3fe78c14ca1d
561,975
import torch def move_bdim_to_front(x, result_ndim=None): """ Returns a tensor with a batch dimension at the front. If a batch dimension already exists, move it. Otherwise, create a new batch dimension at the front. If `result_ndim` is not None, ensure that the resulting tensor has rank equal to `...
313a1837b6c3b451cebacaa7815f2631dfa387e5
24
import unicodedata def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, f...
ac4eeeeceba447f85cb61d792237c930d9c131f9
691,361
def recursive_linear_search(array:list,target:int,index:int =0)-> int: """ This a python implementation of recursive linear search algorithm. Where we are applying linear search algorithm with recursion. Parameters : 1>array : First parameter to the function is the array(searching space) (accepts both sort...
e2cb7331813aa11bef8fd19247ff3667b3f1e9ae
77,249
from typing import Dict from typing import List def update_enrollments( tracked_entity: Dict, enrollments_with_new_events: List, ) -> List: """ Adds new events to current program enrollments and adds new enrollments. Returns a complete list of enrollments. """ current_enrollments = tracked...
1d364cc843026e44d4680d0e55e1275ff2433737
525,845
from datetime import datetime def timestamp2datetime(unixtime : float): """ Convert unix timestamp to datetime :param unixtime: Unix timestamp to be converted in a datetime :type unixtime: int :return: datetime :rtype: datetime """ if unixtime and unixtime > 0: result = da...
3ddca644bf05babbba88cf0cf027930a3fb49ba5
254,784
def ReadIgnoreFile(infile): """Parses a file indicating which communities should be skipped by RemoveLowComplexityRepeats. The numbers of communities to skip should be separated by commas Lines beginning with # will be treated as comments and skipped (eg providing justification for skipping these c...
98b25c8b26c0d4a8c320e66a55628c8e62c996c0
533,690
def _to_int(x): """Converts a completion and error code as it is listed in 32-bit notation in the VPP-4.3.2 specification to the actual integer value. """ if x > 0x7FFFFFFF: return int(x - 0x100000000) else: return int(x)
de155dce733dc93c3112d5bbc10f0dbc20110978
77,536
import uuid def _replace_substrings(code, first_char, last_char): """Replace the substrings between first_char and last_char with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ substrings = [] level = 0 start = -1 for i...
4a4b877df5aa6ce889a62f6e3ed9b784e37ad41c
688,805
from typing import Optional def res_to_q(res: float) -> Optional[float]: """ :param res: resonance value :return: Q factor, or None if res out of range [0, 1) """ if not 0.0 <= res < 1.0: return None return 1.25 / (1 - res) - 1
92e8ee2d0d8636d8d516701e57a5fb8d507765e2
526,773
def transpose(matlist, K): """ Returns the transpose of a matrix Examples ======== >>> from sympy.matrices.densetools import transpose >>> from sympy import ZZ >>> a = [ ... [ZZ(3), ZZ(7), ZZ(4)], ... [ZZ(2), ZZ(4), ZZ(5)], ... [ZZ(6), ZZ(2), ZZ(3)]] >>> transpose(a, ZZ) ...
2f3909e6c7bd0d554520c8d240d7630e0620f3f5
646,412
def split_number(number, multiplier): """Decodes a number into two. The number = high * multiplier + low, and This method returns the tuple (high, low). """ low = int(number % multiplier) high = int(number / multiplier) return (high, low)
48381531bd177055056641cec5eaee9b2af7a28d
165,162
import re import string def clean_string(text): """ Performs basic string cleaning: - Clear pdf conversion md strings - Remove weird symbols - Reduce redundant white spaces Parameters ---------- text : list list of strings to clean Returns ------- text : list ...
afa2fea6dbed2a2fc11b8c71203dbdd6188f4c81
610,999
from typing import List def add_bcc(cmd: List[int]): """Compute BCC (= Block Checking Charactor) and append to command sequence. Returns: list of binary data with BCC code. """ check: int = 0x00 for b in cmd: check = check ^ b cmd.append(check) return cmd
6fac48e348cdb2c6fd63f1545a09fa5ea6ddba61
666,279
def extract_one_string_in_section(section, str_ptr): """Extract one string in an ELF section""" data = section['data'] max_offset = section['size'] offset = str_ptr - section['start'] if offset < 0 or offset >= max_offset: return None ret_str = "" while (offset < max_offset) and (...
7f3e95961d1febd0c5edb2a18e0f6f0e3098a539
490,849
def mean(mylist): """ function to take the mean of a list Parameters ---------- mylist : list list of numbers to take a mean Returns ------- mean_list : float The mean of the list. Examples -------- >>> mean([1,2,3,4,5,6,7]) 4.0 """ ...
5b3c0796e752c2ac384ea00f97ff14ab7d3e7f2d
673,052
def glob_to_sql(string: str) -> str: """Convert glob-like wildcards to SQL wildcards * becomes % ? becomes _ % becomes \% \\ remains \\ \* remains \* \? remains \? This also adds a leading and trailing %, unless the pattern begins with ^ or ends with $ """ # What's with th...
bf3ca7bf522292c17c418ccdf75aca21e4f2bc69
70,654
from typing import Dict from typing import Any from pathlib import Path import yaml def load_config(fpath: str) -> Dict[str, Any]: """Loads a configuration from a path to a YAML file, allows for inheritance between files using the ``base_config`` key. Parameters ---------- path : str Path...
8b3d708f4ec441dc5be661efb5fc243d7d4d57fd
84,505
def colnames_to_yeo_7(colnames: list, order: bool = True) -> list: """ takes a list of colnames in the brainnetome format/naming and converts them to yeo_7 regions Examples: >>> print(colnames_to_yeo_7(["108_110", "1_2", "200_218", "148_140"])) >>> print(colnames_to_yeo_7(["108_110", "1_2", "200_218", "148_140"],...
eeac8f08c8ff2f9308c9c608fb1c74d5f5bb0387
110,693
def register(func): """Method decorator to register CLI commands.""" func._registered = True return func
6cc016eaf99c2cb585fafb0c641e16b145dc8871
360,367
def add_argument_group (parser, title): """Add group only is it doesn't exist yet""" for group in parser._action_groups: if group.title == title: return group return parser.add_argument_group(title)
e6d5a794004b9478e06b42f4108044e70c7d8e0d
134,745
def change_one(pair, index, new_value): """Return new tuple with one element modified.""" new_pair = list(pair) new_pair[index] = new_value return tuple(new_pair)
82f3f29639044bdfdf861cc0c7917cf521ac74aa
111,375
def _off_faces(faces): """ Return a string representing the faces in OFF format. Parameters ---------- faces: numpy array of integers A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces. Returns ------- string The OFF format string for the f...
5488ed221fabe329be876bf5914591a2fd18f2fc
582,142
import torch def pad_batch(items, pad_value=0): """Pad tensors in list to equal length (in the first dim) :param items: :param pad_value: :return: padded_items, orig_lens """ max_len = len(max(items, key=lambda x: len(x))) zeros = (2*torch.as_tensor(items[0]).ndim -1) * [pad_value] pa...
481c3c8dcbc3dfa63cfbe7b71d04d0d897980f5a
289,441
def get_sea_attribute_cmd(seaname): """ Get pvid, pvid_adapter, and virt_adapters from the configured SEA device. Also get the state of the SEA. :param seaname: sea device name :returns: A VIOS command to get the sea adapter's attributes. """ return ("ioscli lsdev -dev %(sea)s -attr pvid,pv...
18224e14e45b73ff716f4282aaff3e06c4584866
18,867
def get_text_ls(filename): """Returns text of file as a list of strings""" with open(filename, 'r') as f_in: return f_in.readlines()
5b788f38e683c82648224b7cc1b5875a0f602dce
11,083
def get_commerce_url(root_url: str) -> str: """Get the Kamereon base commerce url.""" return f"{root_url}/commerce/v1"
3e56bfcb13d476a2668d756673bf7c0425404baa
576,517
def get_kernel_rpm_release(rpm): """ Get the release of a kernel RPM as an integer. :param rpm: An instance of an RPM derived model. """ return int(rpm.release.split('.')[0])
c81e78457e70da29a2b2a4e8d13eb65ef4a16a10
594,794
def _module_name_to_class_name(module_name): """Converts the given name of a module containing a tool test settings class into a class name. """ # Settings for some of our tools have to be treated specially because the # generic conversion below is inadequate. if module_name == 'idaplugin_test_s...
f68309c565d9454b9fa1c64cb1ffee102a4a97a3
227,042
import struct import binascii def hex2double(s): """Convert Ephemeris Time hex string into double.""" return struct.unpack('d', binascii.unhexlify(s))[0]
2320ba8352cf880ec61e8d867ac7d648f818ae45
670,963
def path_to_key(datastore, path): """ Translates a file system path to a datastore key. The basename becomes the key name and the extension becomes the kind. Examples: /file.ext -> key(ext, file) /parent.ext/file.ext -> key(ext, parent, ext, file) """ key_parts = [] path_par...
53b52478f5c451f17498020b2ec316bbb4e8a822
253,581
import random def simulate_ip() -> str: """ Simulates a random IP address Returns: A random IP address (str) """ return "{}.{}.{}.{}".format( random.randint(1, 1000), random.randint(1, 1000), random.randint(1, 1000), random.randint(1, 1000) )
faf424a9025244220f2b4c0b9bffad95243a152b
117,390
import re def get_offer_total_floors(html_parser, default_value=''): """ This method returns the maximal number of floors in the building. :param html_parser: a BeautifulSoup object :rtype: string :return: The maximal floor number """ # searching dom for floor data floor_raw_data = ht...
170e75a04104f6fa1c544788c3d25324edd6b2e8
17,185
def gcd(first_number: int, second_number: int) -> int: """ gcd: Function which finds the GCD of two numbers. The GCD (Greatest Common Divisor) of two numbers is found by the Steins GCD Algorithm. Args: first_number (int): First number second_number (int): Second number Returns: ...
5475dba0153a9d73e6f339350afe7c811c6e7140
340,624
def transform(token, operations=None): """ Apply transformations to token. """ for operation in operations if operations else []: token = operation(token) if token is None: break return token
a77ee0470c7073162f56d0318043b5901183542c
282,678
def _skip_nop_operations(task, pre=None, post=None): """If `task` is a NOP, then skip pre and post Useful for skipping the 'creating node instance' message in case no creating is actually going to happen. """ if not task or task.is_nop(): return [] if pre is None: pre = [] i...
9a6f0e27a46c6df22bcc518ff444cf185da4030b
504,131
def as_digits(number, min_digits): """ break a positive number into an array of digits 1244 -> [1, 2, 4, 4] 0 -> [0] -222999 -> [-222999] """ n = number arr = [] while n >= 10: arr.append(n % 10) n = round(n) // 10 arr.append(round(n)) if len(arr) < min_d...
da5848506d06da3f10ea5497c7b16c07f72bce5c
187,408
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices, the inner list is over indi...
2e182650be07b1ce2bfe6cc3ee4b34c9915160f7
660,477
def is_prime(p): """ Returns True if p is a prime This function uses Fermat's little theorem to quickly remove most candidates. https://en.wikipedia.org/wiki/Fermat%27s_little_theorem """ if p == 2: return True elif p <= 1 or p % 2 == 0 or 2**(p-1) % p != 1: return Fals...
463de539dcc346cf35ad78a1a020782d13acdf93
98,578
import requests def get_pypi_package_data(package_name, version=None): """ Get package data from pypi by the package name https://wiki.python.org/moin/PyPIJSON :param package_name: string :param version: string :return: dict """ pypi_url = 'https://pypi.org/pypi' if version: ...
955c805b679b6656b5d1b8aead09860723a2a9d3
483,703
def checkbytes_lt128(file): """ Check if all bytes of a file are less than decimal 128. Returns : True for an ASCII encoded text file else False. """ with open(file, 'rb') as f: content = f.read() return all(b<128 for b in content)
d492dce226a55e12fe34cbac8f32b16267062b42
125,027
def annotation_as_image_size(label): """Convert a VOC detection label to the image size. Args: label (dict): an image label in the VOC detection format. Returns: tuple: width, height of image. """ width = int(label['annotation']['size']['width']) height = int(label['annotation'...
68bc99b67a40ffdd8ca3772189c5be45bd0f775f
295,291
import functools import warnings def deprecated(_func=None, *, print_msg=None): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. Args: print_msg: Information to point user to newest version. """...
1d2849a95702f470fb8933b695712839fc71a90f
587,112
def smaller_root(a, b, c): """ Returns the smaller root of a quadratic equation with the given coefficients. """ dis = (b **2) - (4 * a * c) if dis < 0: return "Error: No real solutions" else: s = (-b - (dis ** 0.5)) / (2 * a) return s
085905ea3081cb33db98c092a7c7db9589190012
164,773
from typing import Optional from typing import Any def safe_min(*values) -> Optional[Any]: """ Find the min value in a list. Ignore None values. Args: *values: all values to be compared Returns: min value in the list or None Examples: >>> safe_min(None, 5, 2, 1, None, 5) ...
2c38380df97eb84f04bb751df1725d953806220d
372,806
def all_same(items): """Returns bool for checking if all items in a list are the same.""" return all(x == items[0] for x in items)
e89945fd1c6151fd50db1ce92c7269642dc5eac6
477,577
def solucion_a(texto: str) -> str: """Devuelve el texto ingresado sin mayúsculas. :param texto: Texto :type texto: str :return: Texto ingresado sin mayúsculas :rtype: str """ resultado = "" for letra in texto: if not letra.isupper(): resultado += letra return res...
637c663f00a4cb58a8e061d61e72eba54f48ace5
259,653
def row_hasindel(r): """ Return True if the row has an indel. Parameters ---------- r : pandas.Series VCF row. Returns ------- bool True if the row has an indel. Examples -------- >>> from fuc import pyvcf >>> data = { ... 'CHROM': ['chr1', 'ch...
b79053ae0df480662848b05e146452d29375cdea
428,516
def clip_box(box, shape): """ Clip box for given image shape. Args: box (array_like[int]): Box for clipping in the next format: [y_min, x_min, y_max, x_max]. shape (tuple[int]): Shape of image. Returns: array_like[int]: Clipped box. """ ymin, xmin, ymax, xm...
7cb329c630dc5eef47e87a8e32dab4d5a97739ae
670,044
from typing import List def check_padding(padding: List[int], bounds: List[int]): """This function checks whether padding is within the limits supported by the NPU""" if len(padding) != 4 or len(bounds) != 4: return False top, left, bottom, right = padding topb, leftb, bottomb, rightb = bounds...
c9f2f2e14ddacc0697c905c7d3cc871c4e7cacb2
547,075
def uniq(l): """Return list without duplication.""" return list(set(l))
c1fecd07f5e2c1d0ff7f19a2f4356be15b430a7e
409,212
def filter_interval_tensor(sample, interval, data_frequency, apply_indices=[0]): """Cut out a specific interval from a sample of EEG-Data. :param sample: sample consisitng of channel_number * data_points :type sample: tensor :param interval: two values specifying the starting and end point in ...
d1221680d32d07bcfe7f47af8797f895b58d030a
223,031
import re def format_row(row): """Formats the row Args: row (string): The row of the file. Returns: dict: The dictionary containing the following attributes: - query (string): The query. - document (string): The document. - relevance (integer): The rel...
da779f84f79e2b9feb8cdb47213525605a8d14cc
124,038
def pkg_as_json(pkg): """Return a dictionary of information for the package.""" result = { 'name': pkg.name, 'ensure': pkg.evr, 'platform': pkg.arch} return result
db43d2eadf57f3a27d88d650f562c805fbadb2a2
119,979
from typing import Mapping def replace_name_in_key(key, rename: Mapping[str, str]): """Given a dask collection's key, replace the collection name with a new one. Parameters ---------- key: string or tuple Dask collection's key, which must be either a single string or a tuple whose fir...
71f04aa9b6fdca4aa1569cd9d31af5c0126ca90d
152,422
def __sbox_single_byte(byte, sbox): """S-Box substitution of a single byte""" row = byte // 16 col = byte % 16 return sbox[row][col]
3091bf7da9d6365713f11f8659c56d0c815965ec
59,717
def append_lesson_content(from_lesson, to_lesson): """Append lesson properties from the send lesson to the receiving lesson """ to_lesson.objectives = from_lesson.objectives to_lesson.activity_title = from_lesson.activity to_lesson.title = from_lesson.title to_lesson.notes = from_lesson.notes to...
c0fbb8c2f649bf5de2e346ab589ce7080caef60f
361,200
def euclidean(p1: tuple[int, int], p2: tuple[int, int]) -> int: """Calculate the distance between two points. Args: p1: First point. p2: Second point. Returns: The distance between the two points. """ diff_x = p1[0] - p2[0] diff_y = p1[1] - p2[1] return (diff_x ** 2...
cd78ac92ff6792401a724247739ef6d0db825bb9
617,627
import math def Diameter(volume, factor=3/math.pi/4, exp=1/3.0): """Converts a volume to a diameter. d = 2r = 2 * (3/4/pi V)^1/3 """ return 2 * (factor * volume) ** exp
9b2d49568e0f2494647152f7e29006d4a770e1ca
217,422
def get_relative_freqs(type2freq): """ Calculates the relative frequency (proportion) of each type in a system Parameters ---------- type2freq: dict Keys are types of a system and values are frequencies of those types Returns ------- type2p: dict Keys are types and valu...
15c33e0ed235543430e9c1925593916135d96615
72,084
def format_direction(direction): """ Examples -------- >>> format_direction('ra') 'ra' >>> format_direction('el') 'alat' >>> format_direction('az') 'alon' """ lowerdir = direction.lower() if lowerdir == 'el': return 'alat' elif lowerdir == 'az': return...
d961ff38fd68b19a8a5975cb2fe1a80af09d8c56
632,661
import warnings def data_order(iaf, ibf, order, multite=False): """ Determine the data format and ordering from ``iaf`` and ``ibf`` options If ``iaf`` is not specified (None or empty string), TC pairs are specified if the ``order`` parameter is given and contains the ``l`` character. Otherwise differ...
fff663af2c0092271c62ae74e0fe97a5d7e243a3
214,371
def groupIntersections(intersections: list, key: int) -> dict: """ Function to group horizontal or vertical intersections Groups horizontal or vertical intersections as a list into a dict by the given key Parameters: intersections (list): List of tuples representing intersection points key (int): Tu...
45f33715dc9917eb224376c2bedede1a8c49c48f
636,256
from typing import Tuple from typing import Dict from typing import Union from typing import List def parse_stan_vars( names: Tuple[str, ...] ) -> Tuple[Dict[str, Tuple[int, ...]], Dict[str, Tuple[int, ...]]]: """ Parses out Stan variable names (i.e., names not ending in `__`) from list of CSV file co...
ba334eb66990d58640d9d978786e89e5555b5d71
623,853
def split_phylogeny(p, level="s"): """ Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p...
b61d5cafa1ca7f56c37195c619e8f02f9b925dab
578,669
import random def split_dataFrames(df, trimmedRUL, splittingRatio): """Split the dataframes according to the indicated splitting ratio""" num_engines = df['Unit Number'].max() shuffledEngines = list(range(1,num_engines+1)) random.shuffle(shuffledEngines) i = int(splittingRatio*num_engines) ...
1190d9bb55c307daa753956eae88eb4806c52eb8
614,136
def validate_input(user_input, input_map): """ Checks user_input for validity and appends any validation errors to return data. Input: - user_input: Dictionary containing the following input keys: values - amount: float - prefix: string - type: string ...
ddeed40bc2cf8294c4fcb86251411290989030c2
422,539
import cgi def check_content_type(content_type, mime_type): """Return True if the content type contains the MIME type""" mt, _ = cgi.parse_header(content_type) return mime_type == mt
faf22b8c546b6846a690d33fbaa4df5525cfc255
589,367
def has_tag(filename, tag): """Check if a filename has a given tag.""" return f':{tag}' in filename
c6ae18c687a5bfeacfae635af3d858ec8bca0820
579,377
import re def find_and_replace(items, updates): """ aka find_and_replace apply all updates in updates list to all items in items list updates consist of a list of lists where the sub lists contain: (search_string, replace_string) """ for u in updates: search_string = u[0]...
57f6f9ed15feb306584fd217d5b062307f2e6aac
616,783
def concat_attrs(*attrs, separator=' '): """ Helper function to join string attributes using separator. """ return separator.join([attr for attr in attrs if attr])
9cd81916c34fc0a04b65c5676bcea4a3eaa06c19
404,682
from datetime import datetime def is_date_format_correct(date_string): """ Check if date is in format YYYY-MM-DD Return: - True if format correct - False if format wrong """ if len(date_string) != 10: return False try: date = datetime.strptime(date_string, "%Y-%m-%d") except ValueError: return Fal...
414093f4c109b8dda35b310acef50ad2d67ad601
518,210
def rekey(x, key_map=None): """Replace the feature keys according to the mapping in `key_map`. For example, if the dataset returns examples of the format: {'foo': 'something', 'bar': 'something else'} and key_map = {'boo': 'foo', 'spar': 'bar'} then this function will return examples with the format {'boo'...
b036a3f28eed2a1226dd4ca78de378cc93022a4f
538,670
def read_from_txt(file_path): """read data from txt file signal content: % ... % ... float; float ... border content: int \t int int \t int ... Args: file_path (str): txt file path Returns: data (li...
ac8aeebdbc62ef7fe90dddb4a5b500dbec3de698
430,624
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float: """ Calculate the area of a rhombus. >>> area_rhombus(10, 20) 100.0 >>> area_rhombus(-1, -2) Traceback (most recent call last): ... ValueError: area_rhombus() only accepts non-negative values >>> area_rhombus(1, -2...
5ed8737df583cda7fe976aa66b92f5d0ef568edd
417,977
def getFirstValid(opts, default): """Returns the first valid entry from `opts`, or `default` if none found. Valid is defined as ``if o`` returns true.""" for o in opts: if o: return o return default
799a6ea4a993f0a112fa38b882566d72a0d223e0
6,320