content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_new_id(identifier, width): """ Given an identifier, gets the next identifier. :param identifier: the last identifier known. :param width: the width of the identifier. :return: the next identifier. """ if identifier.lstrip('0') == "": identifier = str(1) else: identifier = str(int(identifier.lstrip('0')) + 1) identifier = (width - len(identifier.lstrip('0'))) * "0" + identifier return identifier
339eeb1032fe69e27428601e8f10df367276e5a0
35,532
def point_interval(ref_features, sec_features, disp): """ Computes the range of points over which the similarity measure will be applied :param ref_features: reference features :type ref_features: Tensor of shape (64, row, col) :param sec_features: secondary features :type sec_features: Tensor of shape (64, row, col) :param disp: current disparity :type disp: float :return: the range of the reference and secondary image over which the similarity measure will be applied :rtype: tuple """ _, _, nx_ref = ref_features.shape _, _, nx_sec = sec_features.shape # range in the reference image left = (max(0 - disp, 0), min(nx_ref - disp, nx_ref)) # range in the secondary image right = (max(0 + disp, 0), min(nx_sec + disp, nx_sec)) return left, right
22f1477ec4ef86f343969f6316771f3ebb21d085
35,533
def quadratic_fit_search(f, a, b, tol=1e-6): """ Impelements the Quadratic Fit Search method to find the minimum for a single variable function. Args: f: Objective function a: Lower bound of the search interval b: Upper bound of the search interval tol: Tolerance for the minimum point Returns: The minimum point (with tolerance tol) of f in the interval [a,b] """ c = b b = (c-a)/2 fa = f(a) fb = f(b) fc = f(c) while abs(c-a) < tol: x = 0.5*(fa*(b**2-c**2)+fb*(c**2-a**2)+fc*(a**2-b**2)) / \ (fa*(b-c) + fb*(c-a) + fc*(a-b)) fx = f(x) print(x) if x > b: if fx > fb: c = x fc = fx else: a = b fa = fb b = x fb = fx else: if fx > fb: a = x fa = fx else: c = b fc = fb b = x fb = fx return (a+c)/2
691c76bdad0e0f2da14962180fd8ad568729903f
35,534
def _remove_pageoutline(text: str): """ Remove any TracWiki PageOutline directives """ return text.replace('[[PageOutline]]', '')
72642413d11b5251c4f981a48ce7eb582cc9baf7
35,535
from typing import Union def factor_in_new_try(number: Union[int, float], try_count: int) -> Union[int, float]: """Increase the given number with 10% with each try.""" factor = float(f"1.{try_count}") return int(number * factor)
7cf66263b9e05be3ae51b55ef35a9a131433484f
35,536
import tempfile def get_temp_dir(prefix='tmp-cegr-', dir=None): """ Return a temporary directory. """ return tempfile.mkdtemp(prefix=prefix, dir=dir)
3abd323f97e72edb66d6bc00c6d08459a37f962a
35,537
def _cafec_coeff_ufunc(actual, potential): """ Vectorized function for computing a CAFEC coefficient. :param actual: average value for a month from water balance accounting :param potential: average potential value from water balance accounting :return CAFEC coefficient """ # calculate alpha if potential == 0: if actual == 0: coefficient = 1 else: coefficient = 0 else: coefficient = actual / potential return coefficient
9e0b4201dff2acb6170b9719558da494f15ad6e7
35,538
from typing import List import random def sample_floats(low: float, high: float, k: int = 1) -> List[float]: """Return a k-length list of unique random floats in the range of low <= x <= high.""" seen = set() for _ in range(k): x = random.uniform(low, high) while x in seen: x = random.uniform(low, high) seen.add(x) return list(seen)
9dcbef61809e1cfc3cc3748338137e4d48a95059
35,539
import os def get_biocode_script_dict(base): """ Returns a dict where each key is a script category 'fasta', 'blast', etc. and the values are the names of the scripts within that directory """ d = dict() for directory in os.listdir(base): if directory in ['build', '.git', 'sandbox', 'tests']: continue dir_path = "{0}/{1}".format(base, directory) if os.path.isdir(dir_path): d[directory] = list() for thing in os.listdir(dir_path): if thing == '__init__.py': continue if thing.endswith('.py'): d[directory].append(thing) return d
d53bfe35bc0d9f489b30817cb787ba1892ffa333
35,540
def make_list(value): """ Takes a value and turns it into a list if it is not one !!!!! This is important becouse list(value) if perfomed on an dictionary will return the keys of the dictionary in a list and not the dictionay as an element in the list. i.e. x = {"first":1, "second":2} list(x) = ["first", "second"] or use this [x,] make_list(x) =[{"first":1, "second":2}] :param value: :return: """ if not isinstance(value, list): value = [value] return value
9616ef3c265c308ec667aaee43a68b70f5f4138f
35,541
import collections def _defaultdict_of_lists(): """Returns a defaultdict of lists. This is used to avoid issues with Windows (if this function is anonymous, the Echo dataset cannot be used in a dataloader). """ return collections.defaultdict(list)
d1931c5a264a005202b744c42c90b22da9fbda8f
35,542
import functools import sys import traceback def system_exit(object): """ Handles proper system exit in case of critical exception. Parameters ---------- object : object Object to decorate. Return ------ object """ @functools.wraps(object) def system_exit_wrapper(*args, **kwargs): """ Handles proper system exit in case of critical exception. Other Parameters ---------------- \\*args : list, optional Arguments. \\**kwargs : dict, optional Keywords arguments. """ try: if object(*args, **kwargs): sys.exit() except Exception: traceback.print_exc() sys.exit(1) return system_exit_wrapper
1d2c4f907650cdb2f17590171c20ab0404efeeee
35,544
def escape_invalid_characters(name, invalid_char_list, replace_with='_'): """ Remove invalid characters from a variable and replace it with given character. Few chars are not allowed in asset displayname, during import/export Escape those chars with `replace_with` and return clean name Args: name (str): variable to escape chars from. invalid_char_list (list): Must be a list, and it should contain list of chars to be removed from name replace_with (str): Char used to replace invalid_char with. Returns: name (str): name without `invalid_char_list`. """ for char in invalid_char_list: if char in name: name = name.replace(char, replace_with) return name
47359202f0cee82426d35ec5a85d315d96ece1d7
35,545
def _estimate_step_number(n_points: int, batch_size: int) -> int: """Estimates which step this is (or rather how many steps were collected previously, basing on the ratio of number of points collected and the batch size). Note that this method is provisional and may be replaced with a parameter in the config. Raises: ValueError if ``n_points`` or ``batch_size`` is less than 1 """ if min(n_points, batch_size) < 1: raise ValueError( f"Both n_points={n_points} and batch_size={batch_size} must be at least 1." ) # pragma: no cover return n_points // batch_size
c097140107c458f0517d9f616b20d88ef0268e15
35,547
def normalize_ordinal(ordinal): """ Given a string like "first" or "1st" or "1", return the canonical version ('1'). """ return ordinal[0] if ordinal[0].isdigit() else str('ieho'.index(ordinal[1].lower()) + 1)
eceb5e26c54ce987eb65ce40c711000cc3164086
35,548
def chrange(start, end): """Generates a range of characters from start to end :param start: a character, eg. 'b' :type start: character (1 element string) :param end: a character, eg. 'b' :type end: character (1 element string) :example: >>> chrange('d','f') ['d','e','f'] >>> """ return [chr(i) for i in range(ord(start), ord(end) + 1)]
5cc18eec2aa33f6f27436a60eb01a04f2a974f04
35,549
import logging def _makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func) if extra is not None: for key in extra: if (key in ["message", "asctime"]): # or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv
dd12f3b8d7e0e342770f8e14cadfa5e1e8f47c64
35,551
def _is_valid_perm(perm): """Check string to be valid permission spec.""" for char in perm: if char not in 'rwcda': return False return True
357330ee32c2ed0c4ae537f5a9a8b7d08fb1918a
35,552
import os def file_path(filepath: str) -> str: """Special type for argparse, a filepath.""" if os.path.isfile(filepath): return filepath else: raise FileNotFoundError(filepath)
10936130f299252b56e68e6840503f332455ff28
35,553
def comp_height(self): """Compute the height of the Hole (Rmax-Rmin) Parameters ---------- self : Hole A Hole object Returns ------- H : float Height of the hole """ (Rmin, Rmax) = self.comp_radius() return Rmax - Rmin
4dbab93edbe3d7f277480e96b4a5e885e6e9161e
35,554
import random def GenerateRandomChoice(choices, prev=None): """Generates a random choice from a sequence. Args: choices: sequence. Returns: A value. """ return random.choice(choices)
1d38dd313b19f235d4ea367e841ce7e74ee8f69b
35,555
def list2pairs(l): """ Turns any list with N items into a list of (N-1) pairs of consecutive items. """ res = [] for i in range(len(l)-1): res.append((l[i], l[i+1])) return res
b1c3770e66354862d2dd96eedd473582549aae96
35,556
def normalize_br_tags(s): """ I like 'em this way. >>> normalize_br_tags('Hi there') 'Hi there' >>> normalize_br_tags('Hi <br>there') 'Hi <br />there' >>> normalize_br_tags('Hi there<br/>') 'Hi there<br />' """ return s.replace("<br>", "<br />").replace("<br/>", "<br />")
21df28ca4a8bfc03375d2e07e8a1b3840d840557
35,557
def filter_none_values(kwargs: dict) -> dict: """Returns a new dictionary excluding items where value was None""" return {k: v for k, v in kwargs.items() if v is not None}
f5a1f767291a72ebeac7b92c0bbe78b890330916
35,558
def radix_sort(array, base=10): """ Fuction to sort using radix sort algorithm <https://en.wikipedia.org/wiki/Radix_sort>. :param array: A list of elements to sort. :param base: Integer number to represent base number """ maxLen = len(str(max(array))) for i in range(maxLen): digit_ref = [[] for _ in range(base)] for num in array: digit_ref[(num // base ** i) % base].append(num) array=[] for section in digit_ref: array.extend(section) return array
3d88977389a86360e48813d9c01ae00bf5a18a0b
35,559
def mapContactsToLDAP(contact_list): """Create a payload for ldap_updater module calls. Generate a list of dictionaries mapping Insightly properties to LDAP attributes. Args: contact_list (List): A list of contacts as JSON from Insightly to be converted into LDAP-like dictionaries. Returns: List: The contact list converted into dictionaries with the relevant LDAP attributes. """ return map(lambda c: {'employeeNumber': str(c['CONTACT_ID']), 'givenName': c['FIRST_NAME'].encode('utf-8') if c['FIRST_NAME'] else '', 'sn': c['LAST_NAME'].encode('utf-8') if c['LAST_NAME'] else '', 'displayName': ('%s %s' % (c['FIRST_NAME'], c['LAST_NAME'])).strip().encode('utf-8'), 'mail': map(lambda m: m['DETAIL'].encode('utf-8'), filter(lambda e: e['TYPE'] == 'EMAIL', c['CONTACTINFOS'])), 'mobile': map(lambda m: m['DETAIL'].encode('utf-8'), filter(lambda e: e['TYPE'] == 'PHONE', c['CONTACTINFOS'])), 'isHidden': map(lambda t: t['FIELD_VALUE'], filter(lambda f: f['CUSTOM_FIELD_ID'] == 'CONTACT_FIELD_1', c['CUSTOMFIELDS'])), }, contact_list) if contact_list else []
d05cb72fa6039929e8aa65b5fab91f1e865c1691
35,560
import os def getConfig(ir, memconfig_file_path): """ Gets the arrays to be partitioned from the memconfig file """ if not os.path.isfile(memconfig_file_path): print("\tUser did not specify any arrays to partition") return [] configFile = open(memconfig_file_path,'r') partitions=[] while True: # Read line by line and exit when done line = configFile.readline() if not line: break partition = line.split()[0] dimention_to_partition= line.split()[1] settings = line.split()[2:] partitions.append([partition,dimention_to_partition,settings]) return partitions
3c5c85c8d1c337211a1d1070970555c293026070
35,562
from typing import List import yaml def get_training_class_names(training_config_file: str) -> List[str]: """get class names from training config file Args: training_config_file (str): path to training config file, NOT YOUR MINING OR INFER CONFIG FILE! Raises: ValueError: when class_names key not in training config file Returns: List[str]: list of class names """ with open(training_config_file, 'r') as f: training_config = yaml.safe_load(f.read()) if 'class_names' not in training_config or len(training_config['class_names']) == 0: raise ValueError(f"can not find class_names in {training_config_file}") return training_config['class_names']
4caba056481c653f97d5bb0b0f007cea20494412
35,563
def anticom(A,B): """ Compute the anticommutator between matrices A and B. Arguments: A,B -- square matrices Return: antcom -- square matrix of the anticommutator {A,B} """ antcom = A.dot(B) + B.dot(A) return antcom
734f435228fe3c69b52f3c5e8cc09e7f79bd01ce
35,564
def html_attrs_tuple_to_string(attrs): """Converts a set of HTML attributes tuple to an HTML string. Converts all HTML attributes returned by :py:meth:`html.parser.HTMLParser.handle_starttag` ``attrs`` value into their original HTML representation. Args: attrs (list): List of attributes, each item being a tuple with two values, the attribute name as the first and the value as the second. Returns: str: HTML attributes string ready to be used inside a HTML tag. """ response = '' for i, (name, value) in enumerate(attrs): response += '%s' % name if value is not None: response += '="%s"' % value if i < len(attrs) - 1: response += ' ' return response
71d31439f1a18a90483097c70aa09c3f9448ac5d
35,565
import json def json_file_to_dict(file_path): """load a dict from file containing JSON Args: file_path (str): path to JSON file Returns: json_dict (dict): object representation of JSON contained in file """ return json.loads(open(file_path, "r").read())
bf95cdf3ba049718caf2a5ca38ba3293c2eb308e
35,568
import re def restore_dash(arg: str) -> str: """Convert leading tildes back to dashes.""" return re.sub(r"^~", "-", arg)
63313a006ed934eff1ca83486a3dde4f6ea9ef74
35,569
import hashlib def __mysql_password_hash(passwd): """ Hash string twice with SHA1 and return uppercase hex digest, prepended with an asterisk. This function is identical to the MySQL PASSWORD() function. """ pass1 = hashlib.sha1(passwd.encode('utf-8')).digest() pass2 = hashlib.sha1(pass1).hexdigest() return "*" + pass2.upper()
f505025ea0459d42f118698c476fa83afb63f382
35,572
def extract_version_fields(version, at_least=0): """ For a specified version, return a list with major, minor, patch.. isolated as integers. :param version: A version to parse :param at_least: The minimum number of fields to find (else raise an error) """ fields = [int(f) for f in version.strip().split('-')[0].lstrip('v').split('.')] # v1.17.1 => [ '1', '17', '1' ] if len(fields) < at_least: raise IOError(f'Unable to find required {at_least} fields in {version}') return fields
04209b0029160b19bbdb80d45f560c696214f90a
35,573
import argparse import sys def get_cmdline_args(): """Parse cmdline and return Namespace.""" parser = argparse.ArgumentParser( description="Multi QR code generator: reads data from file " "(or stdin), writes HTML for printing to stdout.", ) parser.add_argument('--title', help="title for page footer") parser.add_argument( '--version', type=int, default=16, metavar='[1-40]', choices=range(1,41), help="QR code version to use (default %(default)s)", ) parser.add_argument( '--ecc', choices=['L', 'M', 'Q', 'H'], default='M', help="error correction level (default %(default)s)", ) parser.add_argument('input', metavar='FILE', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="input file (stdin if none)") return parser.parse_args()
f41acdc9d3ccff3301224bef3e7cc41a40cadd2d
35,574
def change_rate_extractor(change_rates, initial_currency, final_currency): """ Function which tests directions of exchange factors and returns the appropriate conversion factor. Example ------- >>> change_rate_extractor( ... change_rates = {'EUR/USD': .8771929824561404}, ... initial_currency = 'EUR', ... final_currency = 'USD', ... ) 1.14 >>> change_rate_extractor( ... change_rates = {'USD/EUR': 1.14}, ... initial_currency = 'EUR', ... final_currency = 'USD', ... ) 1.14 """ ACR_1 = '%s/%s'%( initial_currency, final_currency ) ACR_2 = '%s/%s'%( final_currency, initial_currency ) if ACR_1 in change_rates: return pow(change_rates[ACR_1], -1.) if ACR_2 in change_rates: return change_rates[ACR_2]
3ada3badcfa16c06c2a50ba943d67711e48b62a0
35,575
def get_codebook(ad_bits, codebook): """Returns the exhaustive codebooks for a given codeword length :param ad_bits: codewor length :type ad_bits: int :return: Codebook :rtype: list(str) """ return codebook[ad_bits-2]
331c33e54abe5fd0d71edbc32d5f76d2ec6f03a9
35,576
def _shiftedWord(value, index, width=1): """ Slices a width-word from an integer Parameters ---------- value: int input word index : int start bit index in the output word width: int number of bits of the output word Returns ------- An integer with the sliced word """ if not isinstance(value, int): raise ValueError("value must be integer.") if not isinstance(index, int): raise ValueError("index must be integer.") if not isinstance(width, int): raise ValueError("width must be integer.") elif width < 0: raise ValueError("width cannot be negative.") return (value >> index) & ((2 ** width) - 1)
d3c3ab1e1f34684607fb9f55f807053fd7052be0
35,577
import copy def merge(dest, src): """Merge two config dicts. Merging can't happen if the dictionaries are incompatible. This happens when the same path in `src` exists in `dest` and one points to a `dict` while another points to a non-`dict`. Returns: A new `dict` with the contents of `src` merged into `dest`. Raises: ValueError: If the two dicts are incompatible. """ dest = copy.deepcopy(dest) for src_name, src_val in src.items(): if isinstance(src_val, dict): dest_val = dest.get(src_name, {}) if not isinstance(dest_val, dict): raise ValueError('Incompatible config structures') dest[src_name] = merge(dest_val, src_val) else: try: if isinstance(dest[src_name], dict): raise ValueError('Incompatible config structures') except KeyError: pass dest[src_name] = src_val return dest
e03bd548294ee8df71dc802672d22085ac85ee83
35,578
import random def slow_reversible_propose(partition): """Proposes a random boundary flip from the partition in a reversible fasion by selecting uniformly from the (node, flip) pairs. Temporary version until we make an updater for this set. :param partition: The current partition to propose a flip from. :return: a proposed next `~gerrychain.Partition` """ b_nodes = {(x[0], partition.assignment[x[1]]) for x in partition["cut_edges"] }.union({(x[1], partition.assignment[x[0]]) for x in partition["cut_edges"]}) flip = random.choice(list(b_nodes)) return partition.flip({flip[0]: flip[1]})
8ccf4a1ba23815d9073ff7879380d095e9f0cf2c
35,579
def list_to_number(column): """ Turns a columns of 0s and 1s to an integer Args: column: List of 0s and 1s to turn into a number """ # Cast column integers to strings column = [str(cell) for cell in column] # Turn to an integer with base2 return int(''.join(column), 2)
b6176726517133711d12e47ed47d55ef5bc8ab82
35,581
def update_url_pattern(pattern): """ Falls die URL, die für eine Request übergeben wird, schon eine Query enthält, wird diese aufgelöst, damit die Paramter dem Request-Objekt als Dictionary übergeben werden können :param pattern: URL mit Query (http...?...) :type pattern: str :return: Die Basis-URL ohne Query-Teil und Paramter als Dictionary """ params = {} pattern = pattern.split("?") url = pattern[0] if len(pattern) > 1: param_list = pattern[1].split("&") for param in param_list: values = param.split("=") params.update({ values[0]: values[1] }) return url, params
c5c12de221296ed0d029f83d496fddf90129743b
35,583
def matrix_to_string(matrix, header=None): """ Returns a pretty and aligned string representation of a NxM matrix. This representation can be used to print any tabular data, such as database results. It works by scanning the lengths of each element in each column and determining the format string dynamically. :param matrix: Matrix representation (list with N rows and M elements). :param header: Optional tuple or list with header elements to be displayed. """ if type(header) is list: header = tuple(header) lengths = [] if header: for column in header: lengths.append(len(column)) for row in matrix: for column in row: i = row.index(column) column = str(column) cl = len(column) try: ml = lengths[i] if cl > ml: lengths[i] = cl except IndexError: lengths.append(cl) lengths = tuple(lengths) format_string = "" for length in lengths: format_string += "%-" + str(length) + "s " format_string += "\n" matrix_str = "" if header: matrix_str += format_string % header for row in matrix: matrix_str += format_string % tuple(row) return matrix_str
7eb430356357de9d6a6b51c196df4aba29decada
35,584
def SNR_kelly(spiketrain): """ returns the SNR of the waveforms of spiketrains, as computed in Kelly et al (2007): * compute the mean waveform * define the signal as the peak-to-through of such mean waveform * define the noise as double the std.dev. of the values of all waveforms, each normalised by subtracting the mean waveform Parameters: ----------- spiketrain : SpikeTrain spike train loaded with rgio (has attribute "vaweforms") Returns: -------- snr: float The SNR of the input spike train """ mean_waveform = spiketrain.waveforms.mean(axis=0) signal = mean_waveform.max() - mean_waveform.min() SD = (spiketrain.waveforms - mean_waveform).std() return signal / (2. * SD)
f827008138e9b02625db02ee6755da3451256d2d
35,585
import math def my_func(x): """ simple function that computes : sin(x) + 2x Inputs: 1.x: input value (in radians) Output: returns y = sin(x) + 2x """ y = math.sin(x) + 2.0*x return y
15c14af682051d972d16ca3bf14a4f50f54cd79c
35,586
import json from datetime import datetime import time def iso_to_unix_secs(s): """ convert an json str like {'time': '2022-02-05T15:20:09.429963Z'} to microsecs since unix epoch as a json str {'usecs': 1644927167429963} """ dt_str = json.loads(s)["time"] dt = datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%S.%fZ") usecs = int(time.mktime(dt.timetuple()) * 1000000 + dt.microsecond) return json.dumps({"usecs": usecs})
7421e6b1781b712ebc3b8bafd1d96f49c5f1d10c
35,587
import time import math def time_str() -> str: """ Create a time string in format YYYYMMDD-HHMMSSsssTTTT :return: """ time_s = time.strftime("%Y%m%d-%H%M%S{}%z") ms = math.floor(math.modf(time.time())[0]*1000) return time_s.format(ms)
dcdabd00015b53dc10c15d5f58eda8452d06e915
35,589
import os def get_filename_not_ext(filename) -> str: """去除文件扩展名""" return os.path.splitext(filename)[0]
e94dc20eaa26d45e93e907d31eddc0ba21a7cfae
35,591
def add_view(func, **kw): """Method to store view arguments when defining a resource with the add_resource class method :param func: The func to hook to :param kw: Keyword arguments configuring the view. Example: .. code-block:: python class User(object): def __init__(self, request): self.request = request def collection_get(self): return {'users': _USERS.keys()} def get(self): return _USERS.get(int(self.request.matchdict['id'])) add_view(User.get, renderer='json') add_resource(User, collection_path='/users', path='/users/{id}') """ # XXX needed in py2 to set on instancemethod if hasattr(func, '__func__'): # pragma: no cover func = func.__func__ # store view argument to use them later in @resource views = getattr(func, '__views__', None) if views is None: views = [] setattr(func, '__views__', views) views.append(kw) return func
6e662b9544ca013dda2a18e372e28e00cd625718
35,592
def ned_enu_conversion(eta, nu): """Rotates from north-east-down to east-north-up Args: eta (array) : Drone position and rotation nu (array) : Twitch of the drone - angular and linear velocities Returns: Array: Rotated eta and nu """ # yaw velocity is wrong -> ask aksel why! return [eta[0], eta[1], eta[2], eta[3], eta[4], eta[5]], [ nu[0], nu[1], nu[2], nu[3], nu[4], -nu[5], ]
5660dead6909cc29df8775bf4d70569484d640d1
35,594
import requests def check_time_response(domain): """Return the response time in seconds.""" try: latency = requests.get(domain, headers={'Cache-Control': 'no-cache'}).elapsed.total_seconds() return latency except Exception: return '?'
be208715ceae98122f7012a2982833e46b6979c7
35,595
def _safe_delay(delay): """Checks that `delay` is a positive float number else raises a ValueError.""" try: delay = float(delay) except ValueError: raise ValueError("{} is not a valid delay (not a number)".format(delay)) if delay < 0: raise ValueError("{} is not a valid delay (not positive)".format(delay)) return delay
ff3014047c5f4bcd7d4054f8af11ccd722401546
35,598
def simple_solution(numbers, sum): """Complexity : O(N²)""" for first in numbers: for second in numbers: if sum == first + second: return True return False
bebc90b9818dc8528dcaed2bbc8b1e9093e1f83c
35,599
def attrChain(obj, *attrs): """if attrs is ["a1", "a2", ..., "an"], then this returns obj.a1.a2.a3...an. If any .ak for k<n returns a scalar, stop and return None""" r = obj complete = False started = False for attr in attrs: try: r = getattr(r, attr) started = True except (ValueError, AttributeError) as e: return None complete = True if started and complete: return r else: raise SyntaxError("Must have some attrs")
e6df4cb2339da520a360da3fdee7ccadfab6d3f3
35,600
from typing import Dict from typing import Any def bundle_json_get_next_link(bundle_json: Dict[str, Any]) -> str: """get the 'next' link from a bundle, if it exists Args: bundle_json (Dict[str, Any]): the bundle to examine Returns: str: the url of the 'next' bundle or None """ filtered_link = [link for link in bundle_json["link"] if link["relation"] == "next"] if len(filtered_link) > 0: return filtered_link[0]["url"] return ""
db311eba00952b7d00bf5c9187cc52fb210c5560
35,601
import sys def get_response_encoding(): """Encoding to use to decode HTTP response from Google APIs.""" return None if sys.version_info[0] < 3 else 'utf8'
a6021f8f1769b530ccc10c360d63a0b5c64813e8
35,602
def strip_headers(post): """Find the first blank line and drop the headers to keep the body""" if '\n\n' in post: headers, body = post.split('\n\n', 1) return body.lower() else: # Unexpected post inner-structure, be conservative # and keep everything return post.lower()
ac5b5a7b06f700a42698b3a65fd4c9017a001f30
35,603
def check_continuity(array): """ Check whether the array contains continous values or not like 1, 2, 3, 4, .. """ max_v = max(array) min_v = min(array) n = len(array) # print(n, min_v, max_v) if max_v - min_v + 1 == n: # print("Given array has continous values") return True else: # print("Given array is not continous") return False
6b279cce3b332d5c593afe9590800fe3c8472710
35,604
import os def in_console(): """ Return True if current environment is the flask console """ # See $UMBER_ROOT/bin/umber_console return 'UMBER_CONSOLE' in os.environ
88572e7ede96188dd84395bd1b2fdf28e55f53fc
35,607
def get_node_type(conn, graph_node_pkey): """ Returns the node type of a given graph node""" c = conn.cursor() c.execute( """ SELECT graph_node_type FROM graph_node WHERE pkey = ?""", (graph_node_pkey, ) ) return c.fetchone()[0]
f68f29e45127854781c8fe5422ab754014df1d6b
35,608
def _to_gin_params(parameters): """A helper function that convert key-value parameters to gin parameters""" return ['--gin_param=%s' % e for e in parameters]
8b8e0a9ee7fe162fa317d364da88e6bc02e99adb
35,609
def getPixelFromLabel(label): """ Function to get the pizel from the class label. This reverse mapping is use to generate an image file fom available class labels. :param label: class label :type label: int :return: (r,g,b) equivalent of class label color. :rtype: tuple """ if label == 0: return (0, 255, 0) if label == 1: return (255, 0, 0) else: return (255, 255, 153)
746ae72f4adff1615f399ff5b591b7013ebdce46
35,611
def get_tadvs(words_li, pos_li, j): """ 获取时间状语 """ d = '' while pos_li[j] != 'p' and j > 0: d = words_li[j]+d j -= 1 d = words_li[j]+d return d
04ab2a39eea784f3aa42cd5eca313ceaf8cf819d
35,613
import argparse def make_parser(): """Create parser for grasp file and mesh file.""" parser = argparse.ArgumentParser(description='Visualize grasp file.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('input', type=str, help='Input file name.') parser.add_argument('--mesh_root_dir', type=str, default='.', help='Root folder for mesh file names.') return parser
69f3261df3befe03d82a5a43ed25b00e0cd3157c
35,614
from typing import OrderedDict def flatten(tree_dict): """Flatten tree_dict to a shallow OrderedDict with all unique exact pins.""" out = OrderedDict() for key0, val0 in tree_dict.items(): out[key0[0]] = key0[1] if not val0: continue for key1, subdict in val0.items(): out[key1[0]] = key1[1] deeper = flatten(subdict).items() for key2, val2 in deeper: if key2 in out and out[key2] != val2: raise RuntimeError( "{} has not been solved: both {} and {} found... Please file an issue on GitHub.", key2, val0, val2, ) else: out[key2] = val2 return out
d07271ac7c844fe8e56df20f1308aac777cb1acc
35,615
import time def ms_time_to_srt_time_format(d: int) -> str: """Convert decimal durations into proper srt format. ms_time_to_srt_time_format(3890) -> '00:00:03,890' """ sec, ms = d // 1000, d % 1000 time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec)) # if ms < 100 we get ...,00 or ...,0 when expected ...,000 ms = "0" * (3 - len(str(ms))) + str(ms) return f"{time_fmt},{ms}"
3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1
35,616
def format_float(value: float, precision: int = 4) -> str: """ Formats a float value to a specific precision. :param value: The float value to format. :param precision: The number of decimal places to use. :return: A string containing the formatted float. """ return f'{value:.{precision}f}'
41ec3acf02f3400fd484c8e6f7a72509d3f20cd9
35,618
def get_settings(data): """ Load needed settings from an issue report Arguments: data -- the parsed issue report dictionary Output: Dictionary of settings """ settings = {} model = data.get("insulin_model") if not model: raise RuntimeError("No insulin model information found") if model.lower() == "humalognovologchild": settings["model"] = [ data.get("insulin_action_duration") / 60, 65 ] elif model.lower() == "humalognovologadult": settings["model"] = [ data.get("insulin_action_duration") / 60, 75 ] elif model.lower() == "fiasp": settings["model"] = [ data.get("insulin_action_duration") / 60, 55 ] else: # Walsh model settings["model"] = [ data.get("insulin_action_duration") / 60 / 60 ] momentum_interval = data.get("glucose_store").get("momentumDataInterval") if momentum_interval is not None: settings["momentum_data_interval"] = float(momentum_interval) / 60 else: settings["momentum_data_interval"] = 15 suspend_threshold = data.get("suspend_threshold") if suspend_threshold is not None: settings["suspend_threshold"] = float(suspend_threshold) else: settings["suspend_threshold"] = None settings["dynamic_carb_absorption_enabled"] = True settings["retrospective_correction_integration_interval"] = 30 settings["recency_interval"] = 15 settings["retrospective_correction_grouping_interval"] = 30 settings["rate_rounder"] = 0.05 settings["insulin_delay"] = 10 settings["carb_delay"] = 10 settings["default_absorption_times"] = [ float(data.get("carb_default_absorption_times_fast")) / 60, float(data.get("carb_default_absorption_times_medium")) / 60, float(data.get("carb_default_absorption_times_slow")) / 60 ] settings["max_basal_rate"] = data.get("maximum_basal_rate") settings["max_bolus"] = data.get("maximum_bolus") settings["retrospective_correction_enabled"] = data.get( "retrospective_correction_enabled" ) and data.get( "retrospective_correction_enabled" ).lower() == "true" return settings
08f411a3256589f2fff3d5ec56c9756b23dbb7bd
35,620
def calcula_probabilidade(numero_jogadas_restantes, distancia_atual): """ Recebe um número de jogadas restantes e a distância altual para calcular a probalidade de se conseguir percorrer exatamente essa distância com 'n' jogadas de dados """ if(distancia_atual == 0): return 1 if(numero_jogadas_restantes == 0): return 0 soma = 0 for i in range(1,7): if(distancia_atual - i >= 0): soma += calcula_probabilidade(numero_jogadas_restantes - 1, distancia_atual - i)/6 return soma
77d85cab051b9b620388fb5a79af6413f5452c0a
35,621
import logging def TruncateStr(text, max_len=500): """Truncates strings to the specified maximum length or 500. Args: text: Text to truncate if longer than max_len. max_len: Maximum length of the string returned by the function. Returns: A string with max_len or less letters on it. """ if len(text) > max_len: logging.warning( 'Text length of %d is greater than the max length allowed. ' 'Truncating to a length of %d. Text: %s', len(text), max_len, text) return text[:max_len]
2401d6d56c6f99bd64cfd825aca0ab5badca1964
35,622
def timedelta_to_hour(delta): """ 换算时间 :param delta: """ seconds = int(round(delta.total_seconds())) hour = seconds / 3600 minute = (seconds % 3600) / 60 second = (seconds % 3600) % 60 return hour, minute, second
a99948e6b6cb9b39494568f6f2d78f7df39f35b4
35,623
def get_parameters(params, t, verbose=True): """ Convenience method for the numeric testing/validation system. Params is a dictionary, each key being a parameter name, and each value a list of values of length T (the number of trials). The method returns a list of the argument values for test number `t` < T. """ def print_v(str): if verbose: print(str) num_params = len(params) print_v('') print_v('-----------------------------------------------') print_v(' t='+str(t)) p = [] for p_idx in range(num_params): dict_tuple = list(params.items())[p_idx] key = dict_tuple[0] value = dict_tuple[1] p.append(value[t]) if verbose: print(key, value[t]) print_v('-----------------------------------------------') return p
70b624b465022efd9ef29e59b875881387f28935
35,625
def map_element(element): """Convert an XML element to a map""" # if sys.version_info >= (2, 7): # return {e.tag: e.text.strip() for e in list(element)} # return dict((e.tag, e.text and e.text.strip() or "") # for e in list(element)) return dict((e.tag, e.text) for e in list(element))
b8a84be91f28757f28622a5909a569d35e38282f
35,627
def _zone_group_topology_location_to_ip(location): """Takes a <ZoneGroupMember Location=> attribute and returns the IP of the player.""" # Assume it is of the form http://ip:port/blah/, rather than supporting # any type of URL and needing `urllib.parse`. (It is available for MicroPython # but it requires a million dependencies). scheme_prefix = 'http://' assert location.startswith(scheme_prefix) location = location[len(scheme_prefix):] port_idx = location.find(':') return location[:port_idx]
e3b038b92d4fcb24650dd6905847c9ca3f1fa13e
35,628
from typing import Union def transfrom_operand(operand: str) -> Union[str, int, bool]: """Transforms operand.""" result = operand.strip() if result.isdigit(): result = int(result) elif result in ['True', 'true', 'Yes', 'yes', 'T', 't', 'N', 'n']: result = True elif result in ['False', 'false', 'No', 'no', 'F', 'f', 'N', 'n']: result = False elif result.startswith('"') and result.endswith('"'): result = result[1:-1] return result
64bd30316d7176b01e66cd40d8852806b4da0e7b
35,629
def get_or_create(session, model, **kwargs): """ Determines if a given record already exists in the database. Args: session: The database session. model: The model for the record. **kwargs: The properties to set on the model. The first specified property will be used to determine if the model already exists. Returns: Two values. The first value is a boolean indicating if this item is a new record. The second value will be the created/retrieved model. """ instance = session.query(model).filter_by(**kwargs).first() if instance: return False, instance else: instance = model(**kwargs) return True, instance
74c77cfcbee09313b96284c34e59eb0ff1440f0c
35,630
def get_state_salue(view, option): """Get selected values stored at the state element""" element_value = "" for element in view["state"]["values"]: element_value = view["state"]["values"][element].get(option, None) if element_value is not None: if element_value.get("selected_option", None) is not None: return element_value["selected_option"]["value"] return element_value.get("value", None)
f45b18ee16ad1b2885dbcd7465cf707d8dbfce8b
35,631
import inspect def resolve_msg_filter(filt): """If the filter provided is a message type, then create a filter which returns any message of that type. Otherwise, assume the filter is a lambda method. """ if inspect.isclass(filt): # and issubclass(filt, PurpleDropMessage): return lambda x: isinstance(x, filt) else: return filt
5b97492c264cb8175b6de51f30ff952644312c5f
35,632
def n_distinct(series): """ Returns the number of distinct values in a series. Args: series (pandas.Series): column to summarize. """ n_distinct_s = series.unique().size return n_distinct_s
5f262c376e844cff324b5e0376be91ead8e20c0d
35,633
def get_index_offset_contents(result, source): """Return (line_index, column_offset, line_contents).""" line_index = result['line'] - 1 return (line_index, result['column'] - 1, source[line_index])
5ee12a8c991ab50c71426cacf8db255f4f938de9
35,635
import argparse def parse_options(): """Parses command line options""" parser = argparse.ArgumentParser(description='Process input files') # parser.add_argument('-r', '--reference', type=str, nargs='?', default=None, # help='reference genome input.') parser.add_argument("-s","--seqin", help = "Combined watson and crick file") parser.add_argument("-c","--crickin",dest = "crick", help = "Crick fasta for CRICK_MAX") parser.add_argument("--clusters",dest = "clusters", help = "uc input file to make sam output") parser.add_argument("--samout",dest = "samout", help = "Sam output file") args = parser.parse_args() return args
85a0aa14dd9f9b1706713eba61dc74d5fdd2351d
35,636
def avg_eval_metrics(metrics): """Average evaluation metrics (divide values by sample count). Args: metrics: evaluation metrics Returns: averaged metrics as a dict """ n = metrics['sample_count'] metrics['loss'] = metrics['loss_sum'] / n metrics['error_rate'] = metrics['error_count'] / n if 'top5_error_count' in metrics: metrics['top5_error_rate'] = metrics['top5_error_count'] / n return metrics
cfa3461c94b320a44438483f1d037c0b545cf02a
35,637
def gather(m): """ Helper function to gather constraint Jacobians. Adapated from fenics. """ if isinstance(m, list): return list(map(gather, m)) elif hasattr(m, "_ad_to_list"): return m._ad_to_list(m) else: return m
7821285d1dbce5e11b5452d906ad5333b0424b39
35,639
import os def make_template_paths(template_file, paths=None): """ Make up a list of template search paths from given `template_file` (absolute or relative path to the template file) and/or `paths` (a list of template search paths given by user). NOTE: User-given `paths` will take higher priority over a dir of template_file. :param template_file: Absolute or relative path to the template file :param paths: A list of template search paths :return: List of template paths ([str]) >>> make_template_paths("/path/to/a/template") ['/path/to/a'] >>> make_template_paths("/path/to/a/template", ["/tmp"]) ['/tmp', '/path/to/a'] >>> os.chdir("/tmp") >>> make_template_paths("./path/to/a/template") ['/tmp/path/to/a'] >>> make_template_paths("./path/to/a/template", ["/tmp"]) ['/tmp', '/tmp/path/to/a'] """ tmpldir = os.path.abspath(os.path.dirname(template_file)) return [tmpldir] if paths is None else paths + [tmpldir]
98f0a3e8aebec4e97a9ec91046e8bdf195f36c8f
35,640
def epoch_s_to_ns(epoch_seconds): """ Converts epoch seconds to nanoseconds """ if type(epoch_seconds) is not str: epoch_seconds = str(epoch_seconds) return epoch_seconds + '000000000'
7812fb76183caffdfc7851a06701d87a76d34c69
35,641
import copy def dreplace(d, fv=None, rv='None', new=False): """replace dict value Parameters ---------- d : dict the dict fv : any, optional to be replaced, by default None rv : any, optional replaced with, by default 'None' new : bool, optional if true, deep copy dict, will not change input, by default False Returns ------- dict dict with replaced value """ fvtype = type(fv) if new: d = copy.deepcopy(d) for k, v in d.items(): if type(v) is dict: dreplace(v, fv=fv, rv=rv) else: if type(v) == fvtype: if v == fv: d[k] = rv return d
86e29b6b3b8839ccf1de26483b71e8cd2e0fd6b8
35,642
from datetime import datetime def now(): """ Simple function to return the current time formatted as used here in bfa logging. :return: String containing the current time stamp. note:: Author(s): Mitch """ return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
da985e41032fccd07928602bd48fb7201f58132f
35,643
def _snapshot_readable_date(specified_date): """ A function that transforms the specified date into a more human friendly string formatted date :param specified_date: string formatted date :return: Human readable string formatted date """ return specified_date.strftime('%B %d, %Y')
84064e27e0e5ac289fe7e1f4c149bcd202c1cd3a
35,646
import os import argparse def _validate_directory(path): """an argparse validator to confirm user input is a valid directory""" if os.path.isdir(path): return path else: raise argparse.ArgumentTypeError(f'cannot find directory {path}')
d6334a3285b79062a2558251a0d198aaf115eb40
35,648
from typing import List from typing import Any from typing import Callable from typing import Optional def extract_self_if_method_call(args: List[Any], func: Callable) -> Optional[object]: """Check if this is a method rather than a function. Does this by checking to see if `func` is the attribute of the first (`self`) argument under `func.__name__`. Unfortunately, this is the most robust solution to this I was able to find. It would also be preferable to do this check when the decorator runs, rather than when the method is. Returns the `self` object if it's a method call, else None. Arguments: args (List[Any]): arguments to the function/method call. func (Callable): the unbound function that was called. """ if len(args) > 0: method = getattr(args[0], func.__name__, False) if method: wrapped = getattr(method, "__wrapped__", False) if wrapped and wrapped == func: return args.pop(0) return None
e93850cdad0bbe8fccfa1e508d14acd92f980b35
35,649
def encode_string(s, index): """ Transform a string in a list of integers. The ints correspond to indices in an embeddings matrix. """ return [index[symbol] for symbol in s]
bba25330f6d40b6211d11dda74fed8caa3dcfc16
35,650
def _is_instance(type_to_check, element, condition="any", deep=False): """ ----- Brief ----- Function that verifies when "all" or "any" elements of the list "element" have the type specified in "type_to_check" input. ----------- Description ----------- In some biosignalsnotebooks functions their implementation is extremely dependent on a specific criterion, i.e., 'all' list entries should be of a specific data type. In order to ensure this functionality _is_instance function was implemented. For example, when plotting data through 'plot' function of 'visualise' module, 'all' entries of time axis and data samples lists need to be 'Numeric'. In order to this condition be checked _is_instance should be called with the following input values: _is_instance(Number, [1, 2, 3, True, ...], 'all') Sometimes is also relevant to check if at least one of list entries belongs to a data type, for cases like this, the argument "condition" should have value equal to "any". -------- Examples -------- >>> _is_instance(Number, [1, 2, 3, True], 'all') False >>> _is_instance(Number, [1, 1.2, 3, 5], 'all') True ---------- Parameters ---------- type_to_check : type element Data type (all or any elements of 'element' list must be of the type specified in the current input). element : list List where condition specified in "condition" will be checked. condition : str String with values "any" or "all" verifying when "any" or "all" element entries have the specified type. deep : bool Flag that identifies when element is in a matrix format and each of its elements should be verified iteratively. Returns ------- out : boolean Returns True when the "condition" is verified for the entries of "element" list. """ out = None # Direct check of "condition" in "element". if deep is False: if condition == "any": out = any(isinstance(el, type_to_check) for el in element) elif condition == "all": out = all(isinstance(el, type_to_check) for el in element) # Since "element" is in a matrix format, then it will be necessary to check each dimension. else: for row in range(0, len(element)): for column in range(0, len(element[row])): flag = _is_instance(type_to_check, element[column][row], "all", deep=False) if flag is False: out = flag else: out = True return out
2b3f9e27e6a70fb9e665c237135eeb8c9d5e618b
35,652
def as_linker_lib_path(p): """Return as an ld library path argument""" if p: return '-L' + p return ''
567509c01a4d24978b22834aeaded4f33762d6fe
35,653
def remove_empty_arrays(movies_names_wl): """ This function takes movies_names_wl and removes empty arrays. """ for movie in movies_names_wl: if(movie == []): movies_names_wl.remove(movie) return movies_names_wl
6cac18c3f6c9fd23d05c9f1b969a027366d995a5
35,656
import random def generate_project_name(): """Generates a random project name.""" adjectives = [ 'aged', 'ancient', 'autumn', 'billowing', 'bitter', 'black', 'blue', 'bold', 'broad', 'broken', 'calm', 'cold', 'cool', 'crimson', 'curly', 'damp', 'dark', 'dawn', 'delicate', 'divine', 'dry', 'empty', 'falling', 'fancy', 'flat', 'floral', 'fragrant', 'frosty', 'gentle', 'green', 'hidden', 'holy', 'icy', 'jolly', 'late', 'lingering', 'little', 'lively', 'long', 'lucky', 'misty', 'morning', 'muddy', 'mute', 'nameless', 'noisy', 'odd', 'old', 'orange', 'patient', 'plain', 'polished', 'proud', 'purple', 'quiet', 'rapid', 'raspy', 'red', 'restless', 'rough', 'round', 'royal', 'shiny', 'shrill', 'shy', 'silent', 'small', 'snowy', 'soft', 'solitary', 'sparkling', 'spring', 'square', 'steep', 'still', 'summer', 'super', 'sweet', 'throbbing', 'tight', 'tiny', 'twilight', 'wandering', 'weathered', 'white', 'wild', 'winter', 'wispy', 'withered', 'yellow', 'young' ] nouns = [ 'art', 'band', 'bar', 'base', 'bird', 'block', 'boat', 'bonus', 'bread', 'breeze', 'brook', 'bush', 'butterfly', 'cake', 'cell', 'cherry', 'cloud', 'credit', 'darkness', 'dawn', 'dew', 'disk', 'dream', 'dust', 'feather', 'field', 'fire', 'firefly', 'flower', 'fog', 'forest', 'frog', 'frost', 'glade', 'glitter', 'grass', 'hall', 'hat', 'haze', 'heart', 'hill', 'king', 'lab', 'lake', 'leaf', 'limit', 'math', 'meadow', 'mode', 'moon', 'morning', 'mountain', 'mouse', 'mud', 'night', 'paper', 'pine', 'poetry', 'pond', 'queen', 'rain', 'recipe', 'resonance', 'rice', 'river', 'salad', 'scene', 'sea', 'shadow', 'shape', 'silence', 'sky', 'smoke', 'snow', 'snowflake', 'sound', 'star', 'sun', 'sun', 'sunset', 'surf', 'term', 'thunder', 'tooth', 'tree', 'truth', 'union', 'unit', 'violet', 'voice', 'water', 'waterfall', 'wave', 'wildflower', 'wind', 'wood' ] numbers = [str(x) for x in range(10)] return ' '.join([ random.choice(adjectives).capitalize(), random.choice(nouns).capitalize(), random.choice(numbers) + random.choice(numbers), ])
27ae42b20ab9d15add1cc162d3d4f2ab539447ff
35,657
def split_backlink_section_from_markdown(string): """Split the backlinks section from the markdown file, which should be the last, but doesn't have to be :) """ # Find the section with Backlinks; if there are multiple for some reason, pick the last one markdown_parts = string.rsplit("# Backlinks") print(markdown_parts) backlinks_removed = markdown_parts[1].split('#') print(backlinks_removed) return markdown_parts
6ea6a070e0c6553ee01031b7175667d25c0236bd
35,660
def get_frame(video_camera): """ Checks if the camera is open and takes a frame if so. :param video_camera: A cv2.VideoCapture object representing the camera. :return: Last frame taken by the camera. """ if video_camera.isOpened(): _, frame = video_camera.read() else: raise Exception("Camera is not opened") return frame
2c36b77b9f7e907276b397a1225cfa60f027d847
35,663
def detection_fruit(classe, prediction): """ This function analyses the list of prediction and return a consolidation of the predictions done Args: ----- - classe : list of classes - prediction : list of predictions Returns: -------- - fruit """ nb_predicted_images = len(prediction) nb_fruit = len(classe) list_nb_indexes = [prediction.count(x) for x in range(-1, nb_fruit)] list_nb_fruit = list_nb_indexes[1:nb_fruit+1] fruit = list_nb_fruit.index(max(list_nb_fruit)) nb_max = list_nb_fruit[fruit] if nb_max > (nb_predicted_images / 10): result = fruit else: result = -1 return result
ea2202b5774401ae53b7faded82577237aa85800
35,664
def get_pwsh_script(path: str) -> str: """ Get the contents of a script stored in pypsrp/pwsh_scripts. Will also strip out any empty lines and comments to reduce the data we send across as much as possible. Source: https://github.com/jborean93/pypsrp :param path: The filename of the script in pypsrp/pwsh_scripts to get. :return: The script contents. """ with open(path, "rt") as f: script = f.readlines() block_comment = False new_lines = [] for line in script: line = line.strip() if block_comment: block_comment = not line.endswith('#>') elif line.startswith('<#'): block_comment = True elif line and not line.startswith('#'): new_lines.append(line) return '\n'.join(new_lines)
43d1f0e526b9807ab729cb7b2b85ea1340699770
35,665
def is_numeric(obj): """Check whether object is a number or not, include numpy number, etc.""" try: float(obj) return True except (TypeError, ValueError): # TypeError: obj is not a string or a number # ValueError: invalid literal return False
3cce07df54d6d83410cbd79580cdfdfd29f3edb1
35,666