content
stringlengths
42
6.51k
def extract_name_and_id(user_input): """Determines if the string user_input is a name or an id. :param user_input: (str): input string from user :return: (name, id) pair """ name = id = None if user_input.lower().startswith('id:'): id = user_input[3:] else: name = user_input return name, id
def find_median(quantiles): """Find median from the quantile boundaries. Args: quantiles: A numpy array containing the quantile boundaries. Returns: The median. """ num_quantiles = len(quantiles) # We assume that we have at least one quantile boundary. assert num_quantiles > 0 median_index = int(num_quantiles / 2) if num_quantiles % 2 == 0: # If we have an even number of quantile boundaries, take the mean of the # middle boundaries to be the median. return (quantiles[median_index - 1] + quantiles[median_index])/2.0 else: # If we have an odd number of quantile boundaries, the middle boundary is # the median. return quantiles[median_index]
def parse_http_list(s): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Neither commas nor quotes count if they are escaped. Only double-quotes count, not single-quotes. """ res = [] part = '' escape = quote = False for cur in s: if escape: part += cur escape = False continue if quote: if cur == '\\': escape = True continue elif cur == '"': quote = False part += cur continue if cur == ',': res.append(part) part = '' continue if cur == '"': quote = True part += cur if part: res.append(part) return [ part.strip() for part in res ]
def percentage(n, total): """If `total`=100 and `n`=50 => 50%""" if n is None: return 0 else: return (n*100)/total
def verbose_formatter(verbose: int) -> str: """formatter factory""" if verbose is True: return 'verbose' return 'simple'
def _naics_level(code: str) -> int: """_naics_level is a helper that allows us to determine what level the employment sector is talking about Parameters ---------- code : str NAICS Sector as a string in the format xx-xxxxxx Returns ------- int: The number corresponding to the level of the NAICS sector """ codestr = code.split("-")[-1] # Get the part of the string we care about return ( len(codestr) - (codestr.count("0")) + 2 )
def ordinal_suffix(i): """Get 'st', 'nd', 'rd' or 'th' as appropriate for an integer.""" if i < 0: raise Exception("Can't handle negative numbers.") if i % 100 in [11, 12, 13]: return 'th' elif i % 10 is 1: return 'st' elif i % 10 is 2: return 'nd' elif i % 10 is 3: return 'rd' else: return 'th'
def get_activation_function(function_name): """ Transform keras activation function name into full activation function name :param function_name: Keras activation function name :return: Full activation function name """ translation_dict = { 'relu': 'Rectified Linear Unit', 'linear': 'Linear', 'elu': 'Exponential Linear Unit', 'exponential': 'Exponential', 'selu': 'Scaled Exponential Linear Unit', 'tanh': 'Hyperbolic Tangent', 'sigmoid': 'Sigmoid', 'hard_sigmoid': 'Hard Sigmoid', 'softmax': 'Softmax', 'softplus': 'Softplus', 'softsign': 'Softsign', } return_name = translation_dict.get(function_name, function_name.capitalize()) return return_name
def int2baseTwo(x): """x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.""" assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
def remove_bools(kwargs): """ Remove booleans from arguments. If ``True``, replace it with an empty string. If ``False``, completely remove the entry from the argument list. Parameters ---------- kwargs : dict Dictionary with the keyword arguments. Returns ------- new_kwargs : dict A copy of `kwargs` with the booleans parsed. """ new_kwargs = {} for arg, value in kwargs.items(): if isinstance(value, bool): if value: new_kwargs[arg] = "" else: new_kwargs[arg] = value return new_kwargs
def make_auth_header(auth_token): """Make the authorization headers to communicate with endpoints which implement Auth0 authentication API. Args: auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT (JSON Web Token), its expiry, the scopes granted, and the token type. Returns: headers (dict): A dict representing the headers with necessary token information to talk to Auth0 authentication required endpoints. """ token_type = auth_token['token_type'] access_token = auth_token['access_token'] headers = { "Content-type": "application/json", "Authorization": "{token_type} {access_token}".format( token_type=token_type, access_token=access_token ), } return headers
def sort_names_numerically(filename_list): """Named after the checkbox in ImageJ's "Import --> Image Sequence" dialog box Sorts the given filename list the same way ImageJ does if that checkbox is checked (and if the file is either not DICOM or the (0020, 0018) Instance Number tag is blank): hierarchically, by sequence component (e.g. 7.55.8 < 7.123.2) rather than lexicographically (individual string components are, however, sorted lexicographically). :param filename_list: List of filenames that are .-delimited strings or numbrers with a .dcm extension. """ def int_or_str(s): try: return int(s) except ValueError: return s filename_list.sort(key=lambda filename: [int_or_str(x) for x in filename.split('.')[:-1]])
def find_substring(string, substring): """Funkce hleda podretezec (substring) v retezci (string). Pokud se podretezec v retezci nachazi, vrati index prvniho vyskytu. Jinak vraci -1. """ if len(substring) > len(string): return -1 j = 1 i = 1 while i < len(string): if string[i] == substring[j]: if j == (len(substring) - 1): return i - j j += 1 i += 1 return -1
def to_median_redshift(wavelength, median_z): """Converts wavelength array to the median redshift of the sample Parameters: wavelength (array): wavelength values to convert median_z (int): redshift to change the wavelength by Returns: wavelength_red (array): redshifted wavelength """ wavelength_red = wavelength * (1 + median_z) return wavelength_red
def bisect_left(a, x, lo=0, hi=None): """bisection search (left)""" if hi is None: hi = len(a) while lo < hi: mid = (lo + hi)//2 if a[mid] < x: lo = mid + 1 else: hi = mid return lo
def rowdict(columns, row): """Convert given row list into dict with column keys""" robj = {} for k,v in zip(columns, row): robj.setdefault(k,v) return robj
def meanreturn(rates): """ Calculates the average rate of return given a list of returns. [ r1, r2, r3, r4, r5 ... rn ] r = [(1+r1)*(1+r2)*(1+r2) .... * (1+rn)]^(1/n) - 1 :param rates: List of interest rate :return: Geometric mean return Example: Suppose you have invested your savings in the stock market for five years. If your returns each year were 90%, 10%, 20%, 30% and -90%, what would your average return be during this period? Ans. -20% >>> import m2py.finance.finance as fin >>> # Return in percent >>> 100*fin.meanreturn([0.9, 0.10, 0.20, 0.30, -0.90]) -20.080238920753235 Reference: http://www.investopedia.com/ask/answers/06/geometricmean.asp """ prod = 1 for r in rates: prod = prod * (1 + r) return prod ** (1.0 / len(rates)) - 1
def vect_mult(_V, _a): """ Multiplies vector _V (in place) by number _a """ for i in range(len(_V)): _V[i] *= _a return _V
def paramsDictPhysical2Normalized(params, params_range): """Converts a dictionary of physical parameters into a dictionary of normalized parameters.""" # create copy of dictionary params = dict(params) for key, val in params.items(): params[key] = (val - params_range[key][0]) / (params_range[key][1] - params_range[key][0]) return params
def zero_column(d, j, i): """Return True if ``d[k,j] = 0`` for ``0 <= k < i`` Here ``d`` is a bit matrix implemented as an array of integers. """ s = 0 for k in range(i): s |= d[k] return (s & (1 << j)) == 0
def find_common_directory(directory_x, directory_y): """Given two strings containing paths to directories, find the lowest level parent directory that they share and return it's path. If none are found, return False""" x_path = directory_x.split("\\") y_path = directory_y.split("\\") result_path = "" ticker = len(x_path) if ticker > len(y_path): ticker = len(y_path) for i in range(ticker): if x_path[i] == y_path[i]: result_path += x_path[i] + "\\" else: break if result_path == "": return None return result_path
def tokenization(sequence_list): """ input : sequence_list -> [[s1],[s2],[s3],[s4] ....,[sn]] where sn is prediction vector output: tokenized sequence_list -> [1,2,3,2,3,....,678] and a look_up table -> {[s1]:0,[s2]:1,[s3]:2,[s4]:3 ....,[sn]:n-1} """ lookup_table={} tokenized_sequence_list=[] index=0 for predicton_vector in sequence_list: if predicton_vector not in lookup_table.values(): lookup_table[index]=predicton_vector tokenized_sequence_list.append(index) index+=1 else: # each key must have a unique value tokenized_sequence_list.append(list(lookup_table.keys())[list(lookup_table.values()).index(predicton_vector)]) return tokenized_sequence_list,lookup_table
def _transform_kwargs(kwargs): """ Replace underscores in the given dictionary's keys with dashes. Used to convert keyword argument names (which cannot contain dashes) to HTML attribute names, e.g. data-*. """ return {key.replace('_', '-'): kwargs[key] for key in kwargs.keys()}
def formatTitle(title): """ It formats titles extracted from the scraped HTML code. """ if(len(title) > 40): return title[:40] + "..." return title
def minimumBribes_iterative(q): """ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1, 2, 3, """ length = len(q) moves = [0 for i in range(length)] moves_made = 0 arr = q.copy() last_pos = length-1 def get_pos_indices(arr): nonlocal last_pos while last_pos >= 0 and arr[last_pos] <= last_pos + 1: last_pos -= 1 if last_pos == -1: return None last_pos += 1 # keep on searching from the one above return last_pos - 1 return last_pos if last_pos >= 0 else None while True: pos = get_pos_indices(arr) if pos is None: break else: thing = arr[pos] moves[thing - 1] += 1 moves_made += 1 # print(moves_made) # print(moves) if moves[thing - 1] == 3: return -1 arr = arr[:pos] + [arr[pos + 1]] + [thing] + arr[pos + 2:] return moves_made
def index_words(text): """ index_words :param text: :return: """ result = [] if text: result.append(0) for index, letter in enumerate(text): if letter == ' ': result.append(index + 1) return result
def has(i): """Returns the form of the verb 'avoir' based on the number i.""" # Note: this function is used only for the third person if i == 1: return 'a' else: return 'ont'
def f2p_worlds(worlds: list): """ Filters a list of worlds to a list only containing f2p worlds """ return [world for world in worlds if world['f2p'] and not world['vip']]
def returnRainfall(dd): """Returns rainfall data in units kg/m2/s""" rho_fresh = 1000 # freshwater density rain = [] if 'LIQUID_PRECIPITATION_VOLUME' in dd: period = dd['LIQUID_PRECIPITATION_DURATION'] # hours volume = dd['LIQUID_PRECIPITATION_VOLUME'] # mm rain = volume/(1000*period*3600)*rho_fresh elif 'PRECIP_VOLUME' in dd: period = dd['PRECIP_PERIOD'] # minutes volume = dd['PRECIP_VOLUME'] # mm rain = volume/(1000*period*60)*rho_fresh return rain
def replace_in_str(rstring, repres): """Replace keys by values of repres in rstring.""" for k in sorted(repres.keys(), key=len, reverse=True): rstring = rstring.replace(k, repres[k]) return rstring
def print_tree(ifaces): """ Prints a list of iface trees """ return " ".join(i.get_tree() for i in ifaces)
def _construct_param(arg_name): """Converts argument name into a command line parameter.""" return f'--{arg_name.replace("_", "-")}'
def add_whitespaces(file_contents, symbols): """Adds whitespaces around symbols""" for symbol in symbols: if symbol in file_contents: file_contents = file_contents.replace(symbol, " " + symbol + " ") return file_contents
def pattern_count(text, pattern): """[finds all occurences of a pattern in a text of bases] Args: text ([string]): [input string] pattern ([string]): [pattern to search for in string] Returns: [int]: [running tally of how many occurrences of pattern were found in text] """ Count = 0 PatternLength = len(pattern) TextLength = len(text) for i in range((TextLength - PatternLength)+1): # i represents a kmer if text[i:i+PatternLength] == pattern: Count += 1 return Count
def remove_assc_goids(assoc, broad_goids): """Remove GO IDs from the association, return a reduced association""" actuall_removed_goids = set() actuall_removed_genes = set() assc_rm = {} for geneid, goid_set in assoc.items(): rm_gos = goid_set.intersection(broad_goids) if rm_gos: actuall_removed_goids.update(rm_gos) reduced_goids = goid_set.difference(rm_gos) if reduced_goids: assc_rm[geneid] = reduced_goids else: actuall_removed_genes.add(geneid) else: assc_rm[geneid] = goid_set return {'assoc_reduced':assc_rm, 'goids_removed':actuall_removed_goids, 'genes_removed':actuall_removed_genes}
def link_easy(sid): """ Creates an html link to a dataset page in Easy. :param sid: a dataset id :return: link to the page for that dataset """ prefix = 'https://easy.dans.knaw.nl/ui/datasets/id/' return '<a target="_blank" href="{}{}">{}</a>'.format(prefix, sid, sid)
def is_valid(sequence, number): """ Returns True if the number is a sum of two discrete numbers in the preceding sequence. """ success = False for i,num in enumerate(sequence): if (number - num) in sequence[i:]: success = True break return success
def octet_str_to_int(octet_str: str) -> int: """ Convert octet string to integer. :param octet_str: Octet string to convert. :returns: Converted integer. """ return int(octet_str.replace(" ", ""), 16)
def get_href_attribute(xml_elem): """ Helping function which returns None or the href attribute. Since some xml documents use https for the w3.org reference, it is nicer to encapsulate the logic inside this separate function. Args: xml_elem: The xml element Returns: None | the attribute """ xlink = None if xml_elem is not None: possible_tags = [ "{http://www.w3.org/1999/xlink}href", "{https://www.w3.org/1999/xlink}href", ] for tag in possible_tags: xlink = xml_elem.get(tag) if xlink is not None: break return xlink
def modular_range(value, values): """ Provides a validator function that returns the value if it is in the range. Otherwise it returns the value, modulo the max of the range. :param value: a value to test :param values: A set of values that are valid """ return value % max(values)
def convert_float(s): """ Convert the string data field *s* to a float. If the value is 99999 (missing data) or 88888 (not observed), return not a number. """ f = float(s) if int(f) in [99999, 88888]: return float('nan') return f
def parse_sas_token(sas_token): """Parse a SAS token into its components. :param sas_token: The SAS token. :type sas_token: str :rtype: dict[str, str] """ sas_data = {} token = sas_token.partition(' ')[2] fields = token.split('&') for field in fields: key, value = field.split('=', 1) sas_data[key.lower()] = value return sas_data
def reindent(s, numSpaces=4, no_empty_lines=False): """ Return string s reindented by `numSpaces` spaces Args: s (string): string to reindent numSpaces (int): number of spaces to shift to the right no_empty_lines (bool): if True remove empty lines Returns: reindented string """ if no_empty_lines: lines = [numSpaces * " " + line if line else line for line in s.splitlines()] else: lines = [numSpaces * " " + line for line in s.splitlines()] return "\n".join(lines)
def basic_sequence(piece_dict): """ Create a basic sequence with the given pieces. Keyword arguments: piece_dict -- The pieces dictionary with the quantity of each piece. """ sequence = [] # Iterate over the pieces original dict for piece, number in piece_dict.items(): if number < 1: continue times = (("%s " % piece)*number) sequence.extend(times.split()) return sequence
def counting_sort(arr): """ Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr Complexity: 0(n) """ m = min(arr) #in case there are negative elements, change the array to all positive element different = 0 if m < 0: #save the change, so that we can convert the array back to all positive number different = -m for i in range (len(arr)): arr[i]+= -m k = max(arr) temp_arr = [0]*(k+1) for i in range(0,len(arr)): temp_arr[arr[i]] = temp_arr[arr[i]]+1 #temp_array[i] contain the times the number i appear in arr for i in range(1, k+1): temp_arr[i] = temp_arr[i] + temp_arr[i-1] #temp_array[i] contain the number of element less than or equal i in arr result_arr = [0]*len(arr) #creating a result_arr an put the element in a correct positon for i in range(len(arr)-1,-1,-1): result_arr[temp_arr[arr[i]]-1] = arr[i]-different temp_arr[arr[i]] = temp_arr[arr[i]]-1 return result_arr
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequence between the two strings Note: my_lcs only gives length of the longest common subsequence, not the actual LCS """ if len(string) < len(sub): sub, string = string, sub lengths = [[0 for _ in range(0,len(sub)+1)] for _ in range(0,len(string)+1)] for j in range(1,len(sub)+1): for i in range(1, len(string) + 1): if string[i - 1] == sub[j - 1]: lengths[i][j] = lengths[i-1][j-1] + 1 else: lengths[i][j] = max(lengths[i-1][j] , lengths[i][j-1]) return lengths[len(string)][len(sub)]
def get_cursor_ratio(image_size: tuple, screen_size: tuple): """ Used to calculate the ratio of the x and y axis of the image to the screen size. :param image_size: (x, y,) of image size. :param screen_size: (x, y,) of screen size. :return: (x, y,) as the ratio of the image size to the screen size. """ x_ratio = screen_size[0] / image_size[0] y_ratio = screen_size[1] / image_size[1] return x_ratio, y_ratio
def ij_tag_50838(nchannels): """ImageJ uses tag 50838 to indicate size of metadata elements (e.g., 768 bytes per ROI) :param nchannels: :return: """ info_block = (20,) # summary of metadata fields display_block = (16 * nchannels,) # display range block luts_block = (256 * 3,) * nchannels # return info_block + display_block + luts_block
def get_link_root(link): """ Gets the root of a url Inputs: link - the url of the page Output: Returns the root of the link if it can fint it. Otherwise, returns -1. """ websites = ["com", "org", "net", "int", "edu", "gov", "mil"] for extension in websites: index = link.find(extension) if(index!=-1): return link[0:index+3] + "/" return "-1"
def htseq_quant(curr_sample, out_dir, ERCC_gtf, strand): """ Use htseq-count for quantification """ cmd = "" cmd=cmd+"mkdir "+out_dir+"htseq_out/\n" if strand=="nonstrand": # non-strand-specific assay: capture coding transcriptome without strand information cmd=cmd+"samtools view "+curr_sample+"_accepted_hits.sorted.bam | htseq-count -r pos --stranded=no - "+ERCC_gtf+" > "+out_dir+"htseq_out/"+curr_sample+"_counts.txt\n" elif strand=="reverse": # strand-specific assay: sequence first strand (reverse) cmd=cmd+"samtools view "+curr_sample+"_accepted_hits.sorted.bam | htseq-count -r pos --stranded=reverse - "+ERCC_gtf+" > "+out_dir+"htseq_out/"+curr_sample+"_counts.txt\n" elif strand=="forward": # strand-specific assay: sequence second strand (forward) cmd=cmd+"samtools view "+curr_sample+"_accepted_hits.sorted.bam | htseq-count -r pos --stranded=yes - "+ERCC_gtf+" > "+out_dir+"htseq_out/"+curr_sample+"_counts.txt\n" return cmd
def parse_categorised_lists( data, header_formatter, formatter, list_parser, sorted_keys=None ): """Parses each element in data using a formatter function. Data is a dict, each key is a category and each value is a list of dicts. Adds a header for each category. """ if sorted_keys is None: sorted_keys = sorted(data.keys(), reverse=True) output = "".join( [ header_formatter(key) + list_parser(data[key], formatter) for key in sorted_keys ] ) return output
def three_point_derivative(f,x,h): """#3-point function to calaculate 1st derivative""" h = float(h) return (1/(2*h))*(f(x-2*h) - 4*f(x-h) + 3*f(x))
def marshal_error(error): """Gather/Marshal error details. Args: error (Object): Instance of NetworkLicensingError or OnlineLicensingError or MatlabError Returns: Dict: Containing information about the error. """ if error is None: return None return { "message": error.message, "logs": error.logs, "type": error.__class__.__name__, }
def convert_pH_temp(pH, original_temperature, desired_temperature): """Convert pH between temperatures. Parameters ---------- pH : float pH as measured. original_temperature : float Measurement temperature, in degrees Fahrenheit. desired_temperature : float Temperature relative to which to express the pH. Returns ------- pH : float The pH that would be measured at the desired temperature. Notes ----- The pH measured by a probe will vary based on the temperature of the sample for two reasons. The first is that the probe itself works according to electrochemical principles that vary according to the temperature. This is specific to the probe and has nothing to do with what is being measured. Many probes are branded as having "Automatic Temperature Correction" or "ATC", and those probes correct for this first phenomenon automatically. The second reason for variation is due to the intrinsic pH dependency on the temperature of the sample. Basically, the same substance at different temperatures really does have different pH levels. The variation depends on the substance and thus cannot automatically be corrected for by the probe, since the probe would have to know the details of the substance. For beer, a rough linear relationship holds over a range of desirable temperatures. This function permits the brewer to measure the sample at any temperature (provided it is reasonably close to room temperature; to do otherwise risks damage to the probe), and convert the measurement to a reference temperature for assessment. """ return pH - 0.003 * (desired_temperature - original_temperature)
def sharedLangCost(criterion, frRow, exRow): """Returns 1 if the two do not share a language, else 0""" fluentQ = criterion['fluentQ'] learningQ = criterion['learningQ'] frLangs = [set(frRow[fluentQ].split(',')), set(frRow[learningQ].split(','))] exLangs = [set(exRow[fluentQ].split(',')), set(exRow[learningQ].split(','))] # Do they share no language ? return int(len(frLangs[0].union(frLangs[1])\ .intersection(exLangs[0].union(exLangs[1]))) == 0)
def geojson_to_features_list(json_data: dict) -> list: """ Converts a decoded output GeoJSON to a list of feature objects The purpose of this formatting utility is to obtain a list of individual features for decoded tiles that can be later extended to the output GeoJSON From:: >>> {'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'geometry': ... {'type': 'Point','coordinates': [30.98594605922699, 30.003757307208872]}, ... 'properties': {}}]} To:: >>> [{'type': 'Feature', 'geometry': {'type': 'Point', ... 'coordinates': [30.98594605922699, 30.003757307208872]}, 'properties': {}}] :param json_data: The given json data :type json_data: dict :return: The feature list :rtype: list """ return json_data["features"]
def check_memory_burst(msgs): # type: (str) -> bool """ Check if memory burst is inferred as expected FIXME: Now we only check if Merlin failed to infer burst for any array instead of further checking the burst length """ #tracking = False for msg in msgs: # pylint: disable=no-else-return if msg.find('\"burst": \"off') != -1: return False elif msg.find('Memory burst NOT inferred') != -1: return False #elif msg.find('\"burst": \"on') != -1: # tracking = True #elif tracking and msg.find('critical_warning') != -1: # tracking = False # if msg.find('due to small external memory') == -1: # return False return True
def insert_sub_reqs(reqs, levels, req_info): """Recursively build all requirements in correct order.""" all_reqs = [] for _, req in enumerate(reqs): # Coefficients are referenced as 'c.<name>'... areq = req[2:] if req.startswith('c.') else req try: rargs = req_info[areq] except KeyError: raise ValueError('requirement "%s" is not defined!' % req) sub_reqs = rargs.get('requires', []) if req in levels: raise ValueError('circular requirement "%s"!' % (req)) if sub_reqs: levels.append(req) sreqs = insert_sub_reqs(sub_reqs, levels, req_info) all_reqs += [ii for ii in sreqs if ii not in all_reqs] levels.pop() if req in all_reqs: raise ValueError('circular requirement "%s"!' % (req)) else: all_reqs.append(req) return all_reqs
def _hr_time(seconds): """Convert time in seconds to a human readable string""" minutes = seconds // 60 if not minutes: return '{}s'.format(seconds) hours = minutes // 60 if not hours: seconds -= minutes * 60 return '{}m {}s'.format(minutes, seconds) days = hours // 24 if not days: minutes -= hours * 60 return '{}h {}m'.format(hours, minutes) years = days // 365 if not years: hours -= days * 24 return '{}d {}h'.format(days, hours) else: days -= years * 365 return '{}y {}d'.format(years, days)
def get_weights(w = 1.7, length = 20): """Returns a list of weights, based on quadratic function""" return [w**i for i in range(length, 0, -1)]
def scale(x, range, drange): """ From real coordinates get rendered coordinates. :param x: source value :param range: (min,max) of x :param drange: (min,max) of sx :return: scaled x (sx) """ (rx1, rx2) = float(range[0]), float(range[1]) (sx1, sx2) = float(drange[0]), float(drange[1]) return (sx2 - sx1) * (x - rx1) / (rx2 - rx1) + sx1
def _softint(intstr, base=10): """ Try to convert intstr to an int; if it fails, return None instead of ValueError like int() """ try: return int(intstr, base) except ValueError: return None
def _get_any_bad_args(badargs, dictionary): """Returns the intersection of 'badargs' and the non-Null keys of 'dictionary'.""" return list(illegal for illegal in badargs \ if illegal in dictionary and dictionary[illegal] is not None)
def get_key_presses(songs, data, replay): """This function returns the number of keys pressed during a run, because why not""" if songs < 0: return 0 keys = 0 for i in range(0, songs): keys += int(data[(i+1)*11]) return keys
def ip_bytes_to_int(ip_bytes: list)->int: """ :param ip_bytes: :return: """ return (ip_bytes[0] << 24) | (ip_bytes[1] << 16) | (ip_bytes[2] << 8) | \ ip_bytes[3]
def get_return_types_as_tuple(arg_id_to_dtype): """Returns the types of arguments in a tuple format. :arg arg_id_to_dtype: An instance of :class:`dict` which denotes a mapping from the arguments to their inferred types. """ return_arg_id_to_dtype = {id: dtype for id, dtype in arg_id_to_dtype.items() if (isinstance(id, int) and id < 0)} return_arg_pos = sorted(return_arg_id_to_dtype.keys(), reverse=True) return tuple(return_arg_id_to_dtype[id] for id in return_arg_pos)
def fuzzy_substring(needle, haystack): """Calculates the fuzzy match of needle in haystack, using a modified version of the Levenshtein distance algorithm. The function is modified from the levenshtein function in the bktree module by Adam Hupp. Taken and modified from: http://ginstrom.com/scribbles/2007/12/01/fuzzy-substring-matching-with-levenshtein-distance-in-python/ Returns: index of first most likely match (first match with minimal edit distance) """ m, n = len(needle), len(haystack) # base cases if m == 1: return not needle in haystack if not n: return m row1 = [0] * (n+1) for i in range(0,m): row2 = [i+1] for j in range(0,n): cost = ( needle[i] != haystack[j] ) row2.append( min(row1[j+1]+1, # deletion row2[j]+1, #insertion row1[j]+cost) #substitution ) # we don't need the original row1 in the future. # In the end, we only want the last row. row1 = row2 # the index of the lowest number in this row will tell us the location of # the best match. return row1.index(min(row1)) - len(needle), min(row1)
def compare(sample_list, first, last): """ This function aims to find tuples with each unique first element.For equal first element tuples, find the one with largest last element. Parameters ---------- sample_list : list, This parameter represents the a list of several tuples. first : integer, This parameter represents the first index of each tuple last : integer, This parameter represents the last index of each tuple Returns ------- res : list, A list of finding tuples """ op = [] for m in range(len(sample_list)): li = [sample_list[m]] # source code here has 4 indents, I asjust it myself. for n in range(len(sample_list)): if (sample_list[m][first] == sample_list[n][first] and # here index should be 2 rather than 3 sample_list[m][last] != sample_list[n][last]): li.append(sample_list[n]) op.append(sorted(li, key = lambda dd : dd[2], reverse = True)[0]) res = list(set(op)) return res
def bigger_price(limit, data): """ TOP most expensive goods """ res = sorted(data, key=lambda k: k['price'], reverse=True) return res[:limit]
def filter_planes(feature_dict, removeDirection, percentile): """filter planes by the criteria specified by removeDirection and percentile Args: feature_dict (dictionary): planes and respective feature value removeDirection (string): remove above or below percentile percentile (int): cutoff percentile Returns: set: planes that fit the criteria """ planes = list(feature_dict.keys()) feat_value = [feature_dict[i] for i in planes] thresh = min(feat_value) + percentile * (max(feat_value) - min(feat_value)) # filter planes if removeDirection == 'Below': keep_planes = [z for z in planes if feature_dict[z] >= thresh] else: keep_planes = [z for z in planes if feature_dict[z] <= thresh] return set(keep_planes)
def boolean(value): """ Converts string into boolean Returns: bool: converted boolean value """ if value in ["false", "0"]: return False else: return bool(value)
def arch_sampling_str_to_dict(sampling_str): """ Converts string representations of architecutre sampling methodology to the dictionary format that nas_searchmanager.SearchManager uses. Example: \"1:4,2:4,3:4,4:4\" is converted to {1.0 : 4, 2.0 : 4, 3.0 : 4, 4.0 : 4}. """ # Remove any spaces that the user may have # entered into the string representation. sampling_str = sampling_str.replace(" ", "") # Split by comma to get the architectures sampled # at each number of architecture parameters epochs # completed. archs_sampled_list = sampling_str.split(",") # Convert the list of epoch:num_archs_to_sample # strings to the correct dictionary format. arch_sampling_dict = {} for curr_arch_sampling in archs_sampled_list: # Split by colon. [num_epochs_elapsed, num_archs_to_sample] = curr_arch_sampling.split(":") # Add to dictionary. arch_sampling_dict[float(num_epochs_elapsed)] = int(num_archs_to_sample) # Return the dictionary. return arch_sampling_dict
def msgEpoch(inp): """ Taken (with permission) from https://github.com/TheElementalOfCreation/creatorUtils """ return (inp - 116444736000000000) / 10000000.0
def brook(x): """Brook 2014 CLUES inverted subhalo mass function. Keyword arguments: x -- array of peak halo masses """ tr = 38.1*1.e10/(x**(1./0.89)) return tr
def remove_Es(a_string): """Implement the code required to make this function work. Write a function `remove_Es` that receives a string and removes all the characters `'e'` or `'E'`. Example: remove_Es('remoter') # 'rmotr' remove_Es('eEe') # '' remove_Es('abc') # 'abc' """ b_string = '' for i in a_string: if i != 'e' and i != 'E': b_string += i return b_string
def gender_aware(line, genders): """ :param line: string line :param genders: map from "name" to "name[gender]" """ for old_name, new_name in genders.items(): line = line.replace(old_name, new_name) return line
def get_change_record(hostname: str, addr: str, rrtype: str): """Return a Route 53 request to UPSERT a resource record. As documented in https://boto3.amazonaws.com/v1/documentation/api/latest/reference/ \ services/route53.html#Route53.Client.change_resource_record_sets """ assert rrtype in ('A', 'AAAA') return { 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': hostname, 'Type': rrtype, 'TTL': 60, 'ResourceRecords': [{'Value': addr}] } }
def get_recall(mx): """Gets sensitivity, recall, hit rate, or true positive rate (TPR) Same as sensitivity """ [tp, fp], [fn, tn] = mx return tp / (tp + fn)
def azure_securityzone(azure_nic={"ipAddress": "", "tags": []}): """ Returns security zone from azure nic ipaddress """ prefix = 'azure_SecurityZone' security_zone = [t for t in azure_nic['tags'] if '_SecurityZone_' in t] if security_zone: if '_High' in security_zone[0]: return f'{prefix}_High' elif '_Medium' in security_zone[0]: return f'{prefix}_Medium' elif '_Low' in security_zone[0]: return f'{prefix}_Low' return f'{prefix}_None'
def _time_to_seconds_past_midnight(time_expr): """ Parse a time expression to seconds after midnight. :param time_expr: Time expression string (H:M or H:M:S) :rtype: int """ if time_expr is None: return None if time_expr.count(":") == 1: time_expr += ":00" hour, minute, second = [int(p, 10) for p in time_expr.split(":")] return hour * 60 * 60 + minute * 60 + second
def complex_multiply(x, y): """ Element wise multiplication for complex numbers represented as pairs """ x_re, x_im = x y_re, y_im = y z_re = (x_re * y_re) - (x_im * y_im) z_im = (x_re * y_im) + (x_im * y_re) return z_re, z_im
def relu_activation(x): """ Returns x if positive, 0 otherwise. """ return x if x > 0.0 else 0.0
def _split_svg_style(style): """Return `dict` from parsing `style`.""" parts = [x.strip() for x in style.split(';')] parts = [x.partition(':') for x in parts if x != ''] st = dict() for p in parts: st[p[0].strip()] = p[2].strip() return st
def getType(string: str): """getType Gives type of a type string (right hand side) :param string: :type string: str """ if '#' in string: string = string.rsplit('#', 1)[1] return string.rsplit('.', 1)[-1]
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) dict[string[i]] = i + 1 max_length = max(max_length, i - j + 1) return max_length
def find_nearest_locus(start, end, loci): """ Finds nearest locus (object with method `distance_to_interval`) to the interval defined by the given `start` and `end` positions. Returns the distance to that locus, along with the locus object itself. """ best_distance = float("inf") best_locus = None for locus in loci: distance = locus.distance_to_interval(start, end) if best_distance > distance: best_distance = distance best_locus = locus return best_distance, best_locus
def decode_payload(encoding, payload): """Decode the payload according to the given encoding Supported encodings: base64, quoted-printable. :param encoding: the encoding's name :param payload: the value to decode :return: a string """ encoding = encoding.lower() if encoding == "base64": import base64 return base64.b64decode(payload) elif encoding == "quoted-printable": import quopri return quopri.decodestring(payload) return payload
def get_base_layout(figs): """ Generates a layout with the union of all properties of multiple figures' layouts Parameters: ----------- fig : list(Figures) List of Plotly Figures """ layout = {} for fig in figs: if not isinstance(fig, dict): fig = fig.to_dict() for k, v in list(fig['layout'].items()): layout[k] = v return layout
def gt_support(A,x): """ Return set of support for probability vector x. Here A and x have the same length. A is the list of candidates. x is a list of their probabilities. Probability is `non-zero' if it is greater than epsilon = 1e-6. """ epsilon = 1e-6 support = [ ] for (xi,a) in zip(x,A): if xi >= epsilon: support.append(a) return support
def to_pecha_id_link(pecha_id): """Return pecha_id_link for `pecha_id`.""" return f"[{pecha_id}](https://github.com/OpenPecha/{pecha_id})"
def quadratic_inverse_distortion_scale(distortion_coefficient, distorted_r_squared, newton_iterations=4): """Calculates the inverse quadratic distortion function given squared radii. The distortion factor is 1.0 + `distortion_coefficient` * `r_squared`. When `distortion_coefficient` is negative (barrel distortion), the distorted radius is monotonically increasing only when r < r_max = sqrt(-1 / (3 * distortion_coefficient)). max_distorted_r_squared is obtained by calculating the distorted_r_squared corresponding to r = r_max, and the result is max_distorted_r_squared = - 4 / (27.0 * distortion_coefficient) Args: distortion_coefficient: A tf.Tensor of a floating point type. The rank can be from zero (scalar) to r_squared's rank. The shape of distortion_coefficient will be appended by ones until the rank equals that of r_squared. distorted_r_squared: A tf.Tensor of a floating point type, containing (x/z)^2 + (y/z)^2. We use distorted_r_squared rather than distorted_r to avoid an unnecessary sqrt, which may introduce gradient singularities. The non-negativity of distorted_r_squared is only enforced in debug mode. newton_iterations: Number of Newton-Raphson iterations to calculate the inverse distprtion function. Defaults to 5, which is on the high-accuracy side. Returns: A tf.Tensor of distorted_r_squared's shape, containing the correction factor that should multiply the distorted the projective coordinates (x/z) and (y/z) to obtain the undistorted ones. """ c = 1.0 # c for Correction # Newton-Raphson iterations for solving the inverse function of the # distortion. for _ in range(newton_iterations): c = (1.0 - (2.0 / 3.0) * c) / (1.0 + 3 * distortion_coefficient * distorted_r_squared * c * c) + (2.0 / 3.0) * c return c
def flatten(x): """Build a flat list out of any iter-able at infinite depth""" result = [] for el in x: # Iteratively call itself until a non-iterable is found if hasattr(el, "__len__") and not isinstance(el, str): flt = flatten(el) result.extend(flt) else: result.append(el) return result
def sidak_inv(alpha, m): """ Inverse transformation of sidak_alpha function. Used to compute final p-value of M independent tests if while preserving the same significance level for the resulting p-value. """ return 1 - (1 - alpha)**m
def run_and_read_all(run_lambda, command): """Runs command using run_lambda; reads and returns entire output if rc is 0""" rc, out, _ = run_lambda(command) if rc != 0: return None return out
def remove_underscore(text): """ Call this on variable names and api endpoints, so that BERT tokenizes names like 'find_place' as 'find place'. """ return text.replace("_", " ")
def disable_current_user_run(on=0): """Desabilitar Execucao de Comandos Especificados no Registro DESCRIPTION Esta restricao e usada para desabilitar a habilidade de executar programas de inicializacao especificados no registro quando o Windows e carregado. COMPATIBILITY Windows 98/Me/2000/XP MODIFIED VALUES DisableCurrentUserRun : dword : 00000000 = Habilita Execucao; 00000001 = Desabilita Execucao. DisableCurrentUserRunOnce : dword : 00000000 = Habilita Execucao; 00000001 = Desabilita Execucao. """ if on : return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\ CurrentVersion\\Policies\\Explorer] "DisableCurrentUserRun"=dword:00000001 "DisableCurrentUserRunOnce"=dword:00000001''' else : return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\ CurrentVersion\\Policies\\Explorer] "DisableCurrentUserRun"=dword:00000000 "DisableCurrentUserRunOnce"=dword:00000000'''
def pad(fingering, width): """Return fingering as a string, each note padded to the given width.""" return ''.join(str(f).ljust(width) for f in str(fingering))
def get_new_keys(values: dict, idx): """ :param values: Werte aus der JSON-Datei :param idx: Index des Arrays, welches gerade betrachtet wird. :return: """ return values["new_keys"][idx] if values.get("new_keys", None) else values["keys"][idx]
def calc_faculty(c_cid, cid_s, bad): """ c_cid : Given a class, map it to it's clump ID cid_s : Given a clump ID, map it to its slot bad: Given a CRN, tell me a set of slots that the CRN shouldn't go in. Returns: Number of courses scheduled into slots that the professor has said will not work for this course. """ total_bad=0 for clas in c_cid: if clas in bad: if cid_s[c_cid[clas]] in bad[ clas ] : total_bad+=1 return total_bad
def bytes_to_human_readable(bytes_in, suffix='B'): """ Convert number of bytes to a "human-readable" format. i.e. 1024 -> 1KB Shamelessly copied from: https://stackoverflow.com/a/1094933/2307994 :param int bytes_in: Number of bytes to convert :param str suffix: Suffix to convert to - i.e. B/KB/MB :return: str human-readable string """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(bytes_in) < 1024.0: return "%3.1f%s%s" % (bytes_in, unit, suffix) bytes_in /= 1024.0 return "%.1f%s%s" % (bytes_in, 'Yi', suffix)