content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def domain_str_to_labels(domain_name): """Return a list of domain name labels, in reverse-DNS order.""" labels = domain_name.rstrip(".").split(".") labels.reverse() return labels
63743ac059f20d0bdda7a5ada54605cdeb50bc98
63,082
def check_match(list1, list2): """ Check whether two lists of sites contain the same sites between the two lists Args: :param list1: (List) list of sites :param list2: (List) list of sites :return: (boolean) whether list1 and list2 have the same sites within them """ if set(list1) == set(list2): return True else: return False
7d8b8533ff96ec50cf3c14be3535d8ce01fb8371
63,083
def format_rest_framework_validation_errors(errors): """Format error messages for response. Args: errors (dict): Dictionary of rest framework validation errors. Returns: dict: {field: error message} """ if isinstance(errors, list): return ". ".join(str(e) for e in errors) elif isinstance(errors, dict): error = "" for key, value in errors.items(): if key != "non_field_errors": error += f"{key}: " if isinstance(value, list): error += ". ".join(str(v) for v in value) else: error += str(value) error += "\n" return error.rstrip("\n") else: return str(errors)
6ce2439428e6a8198bc8cd6806d395507fb66514
63,084
from typing import Union def median(nums: list) -> Union[int, float]: """ Find median of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Median >>> median([0]) 0 >>> median([4, 1, 3, 2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] )
4f289718103f39e69257b3185d7f72242a47d928
63,089
def filter_dictionary(function, dictionary, by="keys"): """Filter a dictionary by conditions on keys or values. Args: function (callable): Function that takes one argument and returns True or False. dictionary (dict): Dictionary to be filtered. Returns: dict: Filtered dictionary Examples: >>> filter_dictionary(lambda x: "bla" in x, {"bla": 1, "blubb": 2}) {'bla': 1} >>> filter_dictionary(lambda x: x <= 1, {"bla": 1, "blubb": 2}, by="values") {'bla': 1} """ if by == "keys": keys_to_keep = set(filter(function, dictionary)) out = {key: val for key, val in dictionary.items() if key in keys_to_keep} elif by == "values": out = {} for key, val in dictionary.items(): if function(val): out[key] = val else: raise ValueError(f"by must be 'keys' or 'values', not {by}") return out
90677661923f6c2a4ed5ad5e0b119c700ef42282
63,098
def _remove_trailing_hr_tag(*, markdown: str) -> str: """ Remove a trailing `<hr>` tag from a specified markdown string. Parameters ---------- markdown : str Target markdown string. Returns ------- markdown : str Result markdown string. """ markdown = markdown.strip() hr_tag: str = '<hr>' if markdown.endswith(hr_tag): markdown = markdown[:-len(hr_tag)] markdown = markdown.strip() return markdown
9698c8fc98710e106008164879726ae37db13f88
63,100
def sort_unique(alist): """ Sorts and de-dupes a list Args: list: a list Returns: list: a sorted de-duped list """ return sorted(list(set(alist)))
32685421cd1b7a708447b173bb03ee6bbcad32f0
63,104
def _Backward2b_P_hs(h, s): """Backward equation for region 2b, P=f(h,s) Parameters ---------- h : float Specific enthalpy [kJ/kg] s : float Specific entropy [kJ/kgK] Returns ------- P : float Pressure [MPa] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for Pressure as a Function of Enthalpy and Entropy p(h,s) for Regions 1 and 2 of the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam, http://www.iapws.org/relguide/Supp-PHS12-2014.pdf, Eq 4 Examples -------- >>> _Backward2b_P_hs(2800,6) 4.793911442 >>> _Backward2b_P_hs(3600,6) 83.95519209 >>> _Backward2b_P_hs(3600,7) 7.527161441 """ I = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 12, 14] J = [0, 1, 2, 4, 8, 0, 1, 2, 3, 5, 12, 1, 6, 18, 0, 1, 7, 12, 1, 16, 1, 12, 1, 8, 18, 1, 16, 1, 3, 14, 18, 10, 16] n = [0.801496989929495e-1, -0.543862807146111, 0.337455597421283, 0.890555451157450e1, 0.313840736431485e3, 0.797367065977789, -0.121616973556240e1, 0.872803386937477e1, -0.169769781757602e2, -0.186552827328416e3, 0.951159274344237e5, -0.189168510120494e2, -0.433407037194840e4, 0.543212633012715e9, 0.144793408386013, 0.128024559637516e3, -0.672309534071268e5, 0.336972380095287e8, -0.586634196762720e3, -0.221403224769889e11, 0.171606668708389e4, -0.570817595806302e9, -0.312109693178482e4, -0.207841384633010e7, 0.305605946157786e13, 0.322157004314333e4, 0.326810259797295e12, -0.144104158934487e4, 0.410694867802691e3, 0.109077066873024e12, -0.247964654258893e14, 0.188801906865134e10, -0.123651009018773e15] nu = h/4100 sigma = s/7.9 suma = 0 for i, j, ni in zip(I, J, n): suma += ni * (nu-0.6)**i * (sigma-1.01)**j return 100*suma**4
66f5fab41d001dc5e47671ec8731d3a383eafaaf
63,106
from typing import Dict from typing import Any def build_config(config : Dict[str, Any]) -> Dict[str, str]: """Will build the actual config for Jinja2, based on SDK config. """ result = config.copy() # Manage the classifier stable/beta is_stable = result.pop("is_stable", False) if is_stable: result["classifier"] = "Development Status :: 5 - Production/Stable" else: result["classifier"] = "Development Status :: 4 - Beta" # Manage the nspkg package_name = result["package_name"] result["package_nspkg"] = result.pop( "package_nspkg", package_name[:package_name.rindex('-')]+"-nspkg" ) # ARM? result['is_arm'] = result.pop("is_arm", True) # Do I need msrestazure for this package? result['need_msrestazure'] = result.pop("need_msrestazure", True) # Pre-compute some Jinja variable that are complicated to do inside the templates package_parts = result["package_nspkg"][:-len('-nspkg')].split('-') result['nspkg_names'] = [ ".".join(package_parts[:i+1]) for i in range(len(package_parts)) ] result['init_names'] = [ "/".join(package_parts[:i+1])+"/__init__.py" for i in range(len(package_parts)) ] # Return result return result
4e3189443d7638a1b290666d52675f6874c19ab6
63,110
import unicodedata def character_categories(text, normalize=None): """Return the list of unicode categories for each character in text If normalize is not None, apply the specified normalization before extracting the categories. """ if normalize is not None: text = unicodedata.normalize(normalize, text) return [unicodedata.category(c) for c in text]
b5d85425bc65951bccf9fe578918905b522c6801
63,114
def getDepthError(depth): """ Return the absolute error in a depth value from a TrueDepth sensor, which varies depending on the depth value. These are OBSERVED values from my experimentation in phase 2 data collection. Parameters ---------- depth : number The depth value reported by the TrueDepth sensor, in cm Returns ------- error : float Error n, in the format n +/- cm """ if depth <= 45: return 0.115470054 elif 45 < depth <= 55: return 0.081649658 elif 55 < depth <= 65: return 0.141421356 elif 65 < depth <= 75: return 0.203442594 elif 75 < depth <= 85: return 0.324893145 elif 85 < depth <= 95: return 0.37155828 else: return 0.37859389
7d84cd7eff740efc98d53f01cca71782c1a89d91
63,115
def get_camera_info_from_image_topic(topic): """ Returns the camera info topic given an image topic from that camera """ topic_split = topic.split('/') info_topic = topic_split[:-1] info_topic.append('camera_info') info_topic = '/'.join(info_topic) return info_topic
3f3cce68dc8fa467ad2bb740f3dbc937d3825c5d
63,117
def charLimit(min: int, max: int, char, string): """Ensure that the count of occurrences of char in string lies between min and max""" if max < min: raise(ValueError('max less than min.')) total = string.count(char) return total <= max and total >= min
8dd0e91673f2b3bd587a86df7aac7fa0abc22148
63,118
def solution(resources, args): """Problem 1 - Version 3 Use a formula to determine the additional sum 15 integers at a time, then use the iterative approach for any remaining integers in the range. Parameters: args.number The upper limit of the range of numbers over which the sum will be taken Return: Sum of all numbers in range [1, args.number) that are divisible by 3 or 5. """ retval = 0 repeats = [3, 5, 6, 9, 10, 12, 15] i = 0 n = args.number - 1 while n > 15: retval += sum(repeats) retval += 15*len(repeats)*i n -= 15 i += 1 while n >= 3: if n % 3 == 0 or n % 5 == 0: retval += 15*i + n n -= 1 return retval
94a3b457d68e010c235a43e6e287821f5831d8ce
63,120
import itertools def ranges_overlap(ranges): """Test if ranges overlap Args: ranges (list): Iterable of pairs (min, max) Returns: bool: True if ranges overlap each other, False otherwise """ for r1, r2 in itertools.combinations(ranges, 2): if r1[1] > r2[0] and r1[0] < r2[1]: return True return False
742825a4abd53a14d9eb5a62375620aa335aee50
63,121
def grad_rescale(grads, k): """scale the gradient by a factor of k""" y = grads.deepcopy() for item in y: item[:] = item * k return y
a69570888e5924de87714f6c355e4c854b8b647f
63,122
def seq(start, stop, step=1): """Generate a list of values between start and stop every step :param start: The starting value :param stop: The ending values :param step: The step size :return: List of steps """ n = int(round((stop - start) / float(step))) if n > 1: return [start + step * i for i in range(n + 1)] else: return []
9471500a1dc13cde41beaad31092f7b00c771cca
63,125
import re def preprocess(text, to_lower=True, remove_tags=True, digits=True, special_chars=True): """ Takes a text object as input and performs a sequence of processing operations: lowercases , removes html tags and special characters Parameters ---------- text: str Text to be cleaned. to_lower: bool (default=True) Whether to convert text to lower case. remove_tags: bool (default=True) Whether to remove content form within html <> tags. digits: bool (default=True) Whether to remove numbers. special_chars: bool (default=True) Whether to remove special characters. Returns ------- text: str cleaned text """ if to_lower: text = text.lower() if remove_tags: text = re.sub("</?.*?>", " <> ", text) if digits: text = re.sub('\\d+', '', text) if special_chars: text = re.sub('\\W+', ' ', text) text = text.strip() return text
086d6bc4918e9ad39d9eed3f512ed661b90da6c8
63,126
def get_the_number_of_pages(total_data, limit_size): """根据数据总数和每页显示数据数计算分页数 Args: total_data 数据总数 limit_size 每页显示数据条数 """ quotient, remainder = divmod(total_data, limit_size) if remainder > 0: quotient = quotient + 1 return quotient
0d3ff3de0c6355e623d091d71a3ab9dc3c085d01
63,135
def s3_download(s3_bucket, file_key, output_path): """Download a file from S3.""" print(f"downloading [{file_key}] from [{s3_bucket.name}] to [{output_path.resolve().as_posix()}]") s3_bucket.download_file(file_key, output_path.resolve().as_posix()) return output_path
8a966b6f0230ffe037d054d798e05ff462036dbd
63,139
def x2cx(x, e): """Transform from *x* value to column *x* index value, using the *e.css('cw')* (column width) as column measure.""" # Gutter gw = e.gw cw = e.css('cw', 0) # Check on division by 0 if cw + gw: return (x - e.parent.pl) / (cw + gw) return 0
f2ac3a87589ded75e22c5aadfd5a95767c1d038e
63,140
import re def get_iter_num(fname): """Extracts the iteration number from the filename""" matches = re.match(r"^iter_(\d+).csv$", fname) if matches is None: return None return matches.group(1)
a150aad1333bb61fd6bb01e37aee00df6d28b542
63,141
import re from datetime import datetime def format_date(row): """ Extracts the unix timestamp from the string and converts it to a datetime object, best if used with map :param row: row from a dataframe """ row=str(row) unix = [int(s) for s in re.findall(r'-?\d+\.?\d*', row)] dt_object = datetime.fromtimestamp(unix[0]/1000) return(dt_object)
b9c3fc5445e7e9985b62ace145faece86576dd25
63,144
def adapt_dbm_reset_ast(dbm_reset_ast): """Transforms the expression ast of a reset into a clock reset ast. Args: dbm_reset_ast: The reset expression ast. Returns: The clock reset ast. """ clock = dbm_reset_ast["expr"]["left"] val = dbm_reset_ast["expr"]["right"] return {"clock": clock, "val": val, "astType": "ClockReset"}
7614c2a4edfa3c6c4b7b728de1604f8ca6e81553
63,148
def convert_words_to_string(paragraph_words): """ Convert the resulting list of words aka a paragraph into a string """ word_texts = [] for paragraph_word in paragraph_words: word_texts.append(''.join([ symbol.text for symbol in paragraph_word.symbols ])) return ' '.join(word_texts)
59e2485a7c03027d697a91928a67a079cba26f18
63,150
def is_palindrome(s): """Returns boolean test of whether s is a palindrome.""" for i in range(len(s)): if s[i] == s[len(s) - 1 - i]: continue else: return False return True
1371e62988a9e1d5754d40e5a2e85e48ff9d9a2d
63,152
def check_format(path): """Check if a file is an Tripos MOL2. Check for "@<TRIPOS>" Parameters ---------- path : str or Path """ result = True with open(path, "r") as fd: for line in fd: line = line.strip() if "@<TRIPOS>" in line: result = True break return result
1fc8ab1f5669bf0a9d6a38063bd2ddf03a5bdcef
63,158
import time def get_timestamp() -> int: """ Return the current millisecond timestamp. Return ------ ts : number milliseconds since the epoc """ ts = int(time.time() * 1000) return ts
663945a97a418bb54850ad913a72b7955f5dbff0
63,160
def nonNullIntersection(dataList): """ Takes a list of dataframes and returns the list of dataframes with rows that contain a null value in any dataframe removed. This is so that the row can be used for training ML Powerflow Input: dataList: a list of pandas dataframes of the same number of rows Output: dataListIntersection: a list of pandas dataframes with the rows that contain a null values in any row missing. """ masks = [] for data in dataList: mask = data.isna().any(axis=1) masks.append(~mask) finalMask = masks[0] for mask in masks[1:]: finalMask = finalMask & mask dataListIntersection = [] for x in range(len(dataList)): dataListIntersection.append(dataList[x][finalMask]) return dataListIntersection
845d153a0f3df1bd3e00a1c61c12b66eef3f3cfa
63,163
def sum_multiples(num1,num2,limit): """take two numbers and find the sum of their multiples from 1 to some upper limit. this DOES NOT double-count numbers which are multiples of BOTH num1 and num2.""" sum = 0 if num1 > limit and num2 > limit: return sum for i in range(1,(limit+1)): if i % num1 == 0 or i % num2 == 0: sum += i return sum
0966730d3ac650bf46914b6a5b76df62edd93a24
63,164
import binascii def unhexlify(text): """Unhexlify raw text, return unhexlified text.""" return binascii.unhexlify(text).decode('utf-8')
81927f86c07e77894a9f47bb9e444caad0ef75b5
63,165
def find_duplicates(iterable): """Find duplicate elements in an iterable. Parameters ---------- iterable : iterable Iterable to be searched for duplicates (i.e., elements that are repeated). Returns ------- set Repeated elements in `iterable`. """ # modified from qiita.qiita_db.util.find_repeated # https://github.com/biocore/qiita # see licenses/qiita.txt seen, repeated = set(), set() for e in iterable: if e in seen: repeated.add(e) else: seen.add(e) return repeated
b5d5bc6b85cd2cfafe3bd0f88ef2daa0e28e538e
63,166
import re def find_substring(substring, string): """ Find a substring inside a string and return it. If there is no match, return 0. Args: substring (str): Substring to find (supports regex) string (str): String to search Returns: match (str): The first occurence of the substring inside the string, or 0 if there is no match """ try: match = re.findall(substring, string)[0] except IndexError: match = '0' return match
dd3e8d2187454aa69e9c4d59404a5a87b6d813f8
63,167
def isPrime(n: int)->bool: """ Give an Integer 'n'. Check if 'n' is Prime or Not :param n: :return: bool - True or False A no. is prime if it is divisible only by 1 & itself. 1- is neither Prime nor Composite We will use Naive approach. . Check Divisibity of n with all numbers smaller than n. within range 2 to sqrt(n). All divisors of n comes as pairs. Thus if n is not divisible by any no. within range 2 to sqrt(n), then it is Prime. WE reduce range from 2 to n to 2 to sqrt(n) """ if n==1 : return False i = 2 while (i * i <= n ): if ( n % i ==0): return False i = i+1 return True
57eddd0aba0d53faa6ee1f4f5ff566a1c3b3ef85
63,172
def overlaps(tupl1, tupl2): """ Takes two ranges as tuples and returns a boolean determining if they overlap inclusively Parameters: r1, r2 - a tuple range """ return (tupl1[0] <= tupl2[0] <= tupl1[1]) or (tupl1[0] <= tupl2[1] <= tupl1[0])
145cbf7a75ae619e848427169377752532735861
63,174
def cols_to_drop(statistic, threshold, greater): """ Compiles a list of columns to be dropped by drop_cols(), using the given summary statistics. Parameters: _________________ statisic: Statistic to use for feature evaluation; should have <lr_model>.summary.<statistic> threshold: (float) Number used as the threshold for feature evaluation greater: (bool) If true, dop columns which are greater than the given threshold; otherwise, drop columns which are less than the given threshold Returns: _________________ cols_list: (list) list of columns to be dropped by drop_cols() """ cols_list = [] if greater: for val in range(len(statistic)): if statistic[val] >= threshold: cols_list.append("X{}".format(val+1)) else: for val in range(len(statistic)): if statistic[val] <= threshold: cols_list.append("X{}".format(val+1)) return cols_list
70f6b225950affbc5156d4d25f531d62e60cb8e0
63,177
def mix_string (str): """Convert all string to lowercase letters, and replaces spaces with '_' char""" return str.replace(' ', '_').lower()
5e07f99b0222cd9d31b692aadb638878a9b502a6
63,178
def precision_at(k): """Returns a function operating on a data frame, which calculates P@k""" return lambda s: s[:k].sum() / s[:k].count()
089bbb9e10a1025faa195ae8411ad5fb0f3f1eb4
63,186
from textwrap import dedent def skip_comment(line): """Return True if a comment line should be skipped based on contents.""" line = dedent(line) return not line or "to_remove" in line or "uncomment" in line.lower()
beda4e72faee0b062ddf6a12b3d449c884554127
63,191
def device_settings(string): """Convert string with SoapySDR device settings to dict""" if not string: return {} settings = {} for setting in string.split(','): setting_name, value = setting.split('=') settings[setting_name.strip()] = value.strip() return settings
ef16df671bea6247be35b1256b13951cda91290a
63,192
def v_equil(alpha, cli, cdi): """Calculate the equilibrium glide velocity. Parameters ---------- alpha : float Angle of attack in rad cli : function Returns Cl given angle of attack cdi : function Returns Cd given angle of attack Returns ------- vbar : float Equilibrium glide velocity """ den = cli(alpha)**2 + cdi(alpha)**2 return 1 / den**(.25)
16bd758f7349dd7c79a8441118191155730b1644
63,194
def gcd(a, b): """ Find greatest common divisior using euclid algorithm.""" assert a >= 0 and b >= 0 and a + b > 0 while a > 0 and b > 0: if a >= b: a = a % b else: b = b % a return max(a, b)
33be26cdb143df526ade519a0f0e3a216e9d3529
63,195
import math def dwpf(tmpf, relh): """ Compute the dewpoint in F given a temperature and relative humidity """ if tmpf is None or relh is None: return None tmpk = 273.15 + (5.00 / 9.00 * (tmpf - 32.00)) dwpk = tmpk / (1 + 0.000425 * tmpk * -(math.log10(relh / 100.0))) return int(float((dwpk - 273.15) * 9.00 / 5.00 + 32))
49031b6fb76f0311ec2554aae01671b2b935eaf7
63,198
def normalize_TPU_addr(addr): """ Ensure that a TPU addr always has the form grpc://.*:8470 :param addr: :return: """ if not addr.startswith("grpc://"): addr = "grpc://" + addr if not addr.endswith(":8470"): addr = addr + ":8470" return addr
a3b7dfb0fd603b7fd4a7f665f66c7465f5738e53
63,210
from typing import Union def convert_indent(text: str, old_indent: Union[int, str], new_indent: Union[int, str]) -> str: """ Changes the indent of the lines in a text. Note: empty lines will be unaffected. Args: text: The text to be processed. old_indent: The indent to remove, given either as a number of columns, or a specific string new_indent: The indent to add, given either as a number of columns, or a specific string Returns: The text with the indent replaced. """ if isinstance(old_indent, int): old_indent = ' ' * old_indent if isinstance(new_indent, int): new_indent = ' ' * new_indent def _convert_line(line): if line == '' or line == '\n': return line assert line.startswith(old_indent), "All text should start with the same indent sequence" return new_indent + line[len(old_indent):] return ''.join(_convert_line(line) for line in text.splitlines(True))
9829c96447daf99b2d7ac458ed64ef28b4c5a07f
63,217
def load_urls(username: str, location: str = "./Resources/url_blueprints.txt") -> list: """ Loads the urls from the specified blueprint file and sets the username as well :param username :param location :return: lisitfied urls with added usernames """ final_list = [] with open(location) as file: for line in file.readlines(): if "{}" in line: line = line.format(username) final_list.append(line.strip("\n")) file.close() return final_list
40ad91207cfaa19f18f74cf1a61f6c68603658c3
63,221
def get_filename(path): """ a helper function to get the filename of an image. This function splits a path provided by the argument by '/' and returns the last element of the result """ return path.split('/')[-1]
8a1a600216f45035dcd5b249df9511a303da634d
63,222
def args_to_tuple(*args): """Combine args into a tuple.""" return tuple(args)
571367c75f0a77d8a40c7383bb075c05acc6307c
63,226
def is_hex_digits(entry, count): """ Checks if a string is the given number of hex digits. Digits represented by letters are case insensitive. :param str entry: string to be checked :param int count: number of hex digits to be checked for :returns: **True** if the given number of hex digits, **False** otherwise """ try: if len(entry) != count: return False int(entry, 16) # attempt to convert it as hex return True except (ValueError, TypeError): return False
78df1fb5fca790967de9a94c7cd76143f7ecc23b
63,228
def weight(edge, modifiers): """ Gets the modified weight of the edge. Args: edge (DirectedEdge): Edge to get weight from. modifiers (list): A list of objects that modify the edge weight. These objects must support get_multiplier(edge). """ weight = edge.weight for modifier in modifiers: weight *= modifier.get_multiplier(edge) return weight
6ec9bc1fff3ea74cfcea5401c6f33376180f8830
63,232
import time def wait_for_victim_pg(manager): """Return a PG with some data and its acting set""" # wait for some PG to have data that we can mess with victim = None while victim is None: stats = manager.get_pg_stats() for pg in stats: size = pg['stat_sum']['num_bytes'] if size > 0: victim = pg['pgid'] acting = pg['acting'] return victim, acting time.sleep(3)
49b1977f6032ce883fffa8402760e7eb83e90b4a
63,233
def bfs_shortest_path_print(graph, x, y): """Return shortest path between nodes x and y.""" visited = [] q = [[x]] while q: path = q.pop(0) node = path[-1] if node not in visited: for adjacent in graph[node]: new_path = list(path) new_path.append(adjacent) if adjacent == y: return new_path q.append(new_path) visited.append(node) return f'No path from {x} to {y}.'
65c6b276cf09b6d37de69c317a8c012eb82ffe89
63,236
def fedoralink_streams(obj): """ Return an iterator of tuples (field, instance of TypedStream or UploadedFile) that were registered (via setting an instance of these classes to any property) with the object. :param obj: an instance of FedoraObject :return: iterator of tuples """ return getattr(obj, '__streams', {}).items()
98442702798d1f152e98f165104890d5329078c3
63,241
def sumTuple(tList, index): """This function takes in the list of tuples, and the index of the tuple It then returns the sum of all of this numbers in that specific tuple index""" _allNums = [x[index] for x in tList] return sum(_allNums)
b680c7cd43226a01dd19608a346fecbeed31baac
63,243
def get_key_to_hash(prefix, *args, **kwargs): """Return key to hash for *args and **kwargs.""" key_to_hash = prefix # First args for i in args: key_to_hash += ":%s" % i # Attach any kwargs for key in sorted(kwargs.keys()): key_to_hash += ":%s" % kwargs[key] return key_to_hash
08577a67e377e2ed5fdb067e54ca4ec56ec3c0b9
63,247
def check_tr_id_full_coverage(tr_id, trid2exc_dic, regid2nc_dic, pseudo_counts=False): """ Check if each exon of a given transcript ID is covered by > 0 reads. If so return True, else False. >>> trid2exc_dic = {"t1" : 2, "t2" : 2, "t3" : 1} >>> regid2nc_dic = {"t1_e1": 0.4, "t1_e2": 1.2, "t2_e1": 0.4, "t2_e2": 0.0, "t3_e1": 1.6} >>> check_tr_id_full_coverage("t1", trid2exc_dic, regid2nc_dic) True >>> check_tr_id_full_coverage("t2", trid2exc_dic, regid2nc_dic) False >>> check_tr_id_full_coverage("t3", trid2exc_dic, regid2nc_dic) True """ min_ex_cov = 0 if pseudo_counts: min_ex_cov = 1 for i in range(trid2exc_dic[tr_id]): ex_nr = i + 1 ex_id = tr_id + "_e" + str(ex_nr) ex_cov = regid2nc_dic[ex_id] if ex_cov == min_ex_cov: return False return True
7f8ec307a6faf09b6d22c9d0d1c63b1d0a181c8e
63,248
def _range_exhausted(i, values, steps, stops): """ Check if a range at i is exhausted. """ return steps[i] * (values[i] - stops[i]) >= 0
e5d6f781f5f005c248ece87dff3c26c7e10cbd22
63,249
def send_email(service, user_id, message): """ Send an email via Gmail API :service: (googleapiclient.discovery.Resource) authorized Gmail API service instance :user_id: (str) sender's email address, used for special "me" value (authenticated Gmail account) :message: (base64) message to be sent """ try: message = (service.users().messages().send(userId=user_id, body=message).execute()) return message except Exception as e: print("err: problem sending email") print(e)
e80aeb05d0d5a43b54a892a49b496ffb007f6879
63,260
def convert_to_type(value, value_type, default_value=None): """ Try to convert 'value' to type :param value: The value to convert :param value_type: The type to convert to eg: int, float, bool :param default_value: The default returned value if the conversion fails :return: """ try: return value_type(value) except ValueError: return default_value
828ed0d60dcdfd4f134a1e9c2377c921424bacce
63,262
from typing import Sequence from typing import Union import re def _parse_problem_sizes(argument: str) -> Sequence[Union[int, Sequence[int]]]: """Parse a problem size argument into a possibly nested integer sequence. Examples: 64,128 -> [64, 128] 32,32,[1,1] -> [32, 32, [1, 1]] """ problem_sizes = [] while argument: # Match size. match = re.match(r"""[,]?\d+""", argument) if match: problem_sizes.append(int(match.group().lstrip(','))) argument = argument[match.end():] continue # Match nested sizes. match = re.match(r"""[,]?\[[0-9,]+\]""", argument) if match: nested = match.group().lstrip(',')[1:-1] problem_sizes.append([int(elem) for elem in nested.split(',')]) argument = argument[match.end():] continue raise ValueError() return problem_sizes
9ac8055a4cfb26d11d19cba2de58d1b797fc2125
63,263
def extract_eyeid_diameters(pupil_datum): """Extract data for a given pupil datum Returns: tuple(eye_id, confidence, diameter_2d, and diameter_3d) """ return ( pupil_datum["id"], pupil_datum["confidence"], pupil_datum["diameter"], pupil_datum.get("diameter_3d", 0.0), )
bb935b2c7280e3f30a274d4cd7ba22f5a5f80c2c
63,264
def property_initialization(property_type, name): """Generate the property initialization for __init__().""" return f' self._{name} = {property_type}()\n'
44ed1ae42f153890a0ab8559b279fea700ab462c
63,267
import re def sanitize_file_path(file): """ Replaces backslashes with forward slashes and removes leading / or drive:/. :param file: Relative or absolute filepath :return: Relative or absolute filepath with leading / or drive:/ removed """ # Sanitize all backslashes (\) with forward slashes (/) file_key = file.replace('\\', '/').replace('//', '/') # If Mac/Linux full path if re.search(r'^/.+$', file): file_key = file.split('/', 1)[1] # If Windows full path elif re.search(r'^\D:/.+$', file_key): file_key = file_key.split(':/', 1)[1] return file_key
73694f4365c7cdf12b13d3b4841438562fa0bd40
63,268
def index_bisect(inlist, el): """ Return the index where to insert item el in inlist. inlist is assumed to be sorted and a comparison function (lt or cmp) must exist for el and the other elements of the list. If el already appears in the list, inlist.insert(el) will insert just before the leftmost el already there. """ lo = 0 hi = len(inlist) while lo < hi: mid = (lo+hi)//2 if inlist[mid] < el: lo = mid+1 else: hi = mid return lo
e3db6d444706dcd6f7bd5002479dbfe9cfe6bffc
63,269
def plane_edge_point_of_intersection(plane, n, p0, p1): """ Finds the point of intersection between a box plane and a line segment connecting (p0, p1). The plane is assumed to be infinite long. Args: plane: tensor of shape (4, 3) of the coordinates of the vertices defining the plane n: tensor of shape (3,) of the unit direction perpendicular on the plane (Note that we could compute n but since it's computed in the main body of the function, we save time by feeding it in. For the purpose of this function, it's not important that n points "inside" the shape.) p0, p1: tensors of shape (3,), (3,) Returns: p: tensor of shape (3,) of the coordinates of the point of intersection a: scalar such that p = p0 + a*(p1-p0) """ # The point of intersection can be parametrized # p = p0 + a (p1 - p0) where a in [0, 1] # We want to find a such that p is on plane # <p - v0, n> = 0 v0, v1, v2, v3 = plane a = -(p0 - v0).dot(n) / (p1 - p0).dot(n) p = p0 + a * (p1 - p0) return p, a
8737be3bde6fd81299b869d3dd12406b6382230f
63,270
import functools def keep_tc_pos(func): """ Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function """ @functools.wraps(func) def wrapper(editor, *args, **kwds): """ Decorator """ sb = editor.verticalScrollBar() spos = sb.sliderPosition() pos = editor.textCursor().position() retval = func(editor, *args, **kwds) text_cursor = editor.textCursor() text_cursor.setPosition(pos) editor.setTextCursor(text_cursor) sb.setSliderPosition(spos) return retval return wrapper
446ef8a684925c8dd209085ed91315a62d6462f1
63,273
def _rng_zero(x): """Return zero scalar, according to sensitivity_transform.""" return 0
6c8c805b37391b4577349cf1d9aaceacbba06b11
63,284
import re def remove_version(code): """ Remove any version directive """ pattern = r'\#\s*version[^\r\n]*\n' regex = re.compile(pattern, re.MULTILINE | re.DOTALL) return regex.sub('\n', code)
0072e85aaa8787db0728131b3038d62d899d2e38
63,287
import random def ShuffleList(feature, label): """ Shuffle list :param feature: the feature to train model, which is a list :param label: the label of the feature, which is a list :return: the shuffled feature and label """ randIndex = [a for a in range(len(feature))] random.shuffle(randIndex) featureShuffle = [feature[ind] for ind in randIndex] labelShuffle = [label[ind] for ind in randIndex] return featureShuffle, labelShuffle
291b5e5741f1a837c9777feba1622ef332818abb
63,288
def replace_repeated_characters(text): """Replaces every 3+ repetition of a character with a 2-repetition.""" if not text: return text res = text[0] c_prev = text[0] n_reps = 0 for c in text[1:]: if c == c_prev: n_reps += 1 if n_reps < 2: res += c else: n_reps = 0 res += c c_prev = c return res
15d11aa94d6da43f1d3f17c7077cda883b788780
63,291
def whatis(seizure): """ Détermine si une entrée est un montant, une date ou un mode de paiement. """ seizure = seizure.replace(" ", "") # pour reconnaître le montant si il contient un espace try: seizure = float(seizure) return "amount" except ValueError: try: seizure.index("/") return "date" except ValueError: return "mode"
ccbb5a3feda0b4d8542fdca7cadce2e9240e485b
63,292
def metabase_metadata_db_alias() -> str: """The db alias of the Metabase metadata database""" return 'metabase-metadata'
b7ec73635633b1294b6548fec21bafa787869510
63,293
def wrap_filter(hook, filter_fn): """ takes in a hook and only applies it when the given filter function returns a truthy value """ def wrap_filter_inner(hs): if filter_fn(hs): return hook(hs) else: return hs() return wrap_filter_inner
63048037dd1dc865de2cb98eda972191d6c14ff5
63,299
from typing import List from typing import Dict def gen_header(head: List[str]) -> Dict: """ This is a helper function meant to generate a dictionary that contains parsing information for csvs. I.e. it stores how to manage datetimes, integers and floats. Strings are pretty much ignored. >>> gen_header(["date~%m/%d/%Y","sentiment_value~float"]) {'date': "datetime.strptime(row[0],'%m/%d/%Y')", 'sentiment_value': 'float(row[1])'} """ final = {} for val in head: val = val.split('~') final[val[0]] = val[1] return final
314bf2e2b7451ab7a83352fb4edb947bf5bf2c21
63,301
def pivot_bulk_data(data, values='log2_rpkm'): """ take long format expression data and pivot to a wider (subject x region) x gene dataframe data: long format dataframe (gene x region x subject) x rpkm values: metric of interest to create a (region x subject) x gene matrix of metrics returns: table_data: wide format dataframe """ # select data selected_data = data.loc[:,['symbol', 'sample', 'region', 'age', values]] # pivot table_data = selected_data.pivot_table(index=['sample', 'region', 'age'], columns='symbol', values=values) table_data = table_data.reset_index() return table_data
7c72d1ad87649d3a541f2559266964581662c7e3
63,312
def get_cal_name(cal_id, service, http): """ Retrieve the name (summary) for a calendar. @param cal_id: str, calendar id @return: str, calendar name """ response = service.calendars().get(calendarId=cal_id).execute(http=http) return response['summary']
a57a0ea045914abcf3840bf82f0ecccf2ff540fb
63,314
def _text(e): """ Try to get the text content of this element """ try: text = e.text_content() except AttributeError: text = e return text.strip()
f447c9e189a587aab61ec1ae1d6437d0a607e381
63,315
def diff_identifiers(a, b): """Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets differ """ a_ids = set(a.identifiers) b_ids = set(b.identifiers) difference = [] for i in a_ids.difference(b_ids): difference.append((i, True, False)) for i in b_ids.difference(a_ids): difference.append((i, False, True)) return difference
5e08802654ed6da8bfb4f2850a8733c5548f9d75
63,317
def GetLiteral(parser, name): """Returns the literal with the given name, removing any single quotes if they exist""" value = parser.literalNames[name] if value.startswith("'"): value = value[1:] if value.endswith("'"): value = value[:-1] return value
2299d22db9cfd4f2734ca3e8890c2748c288c7fe
63,319
import math def _radians_to_angle(rad): """ Convert radians into angle :param rad: :return: angle """ return rad * 180 / math.pi
f88aa0a2da9f0dd31a0576afcd1ffd80ba9eafc8
63,320
import re def clean_whitespace(text: str) -> str: """ Replace all contiguous whitespace with single space character, strip leading and trailing whitespace. """ text = str(text or '') stripped = text.strip() sub = re.sub(r'\s+', ' ', stripped, ) return sub
1744f4ea82dfc538b2e095e66a2260368c5c09ac
63,322
def min_approx(x1, x2, x3, y1, y2, y3): """ Get the x-value of the minimum of the parabola through the points (x1,y1), ... :param x1: x-coordinate point 1 :param x2: x-coordinate point 2 :param x3: x-coordinate point 3 :param y1: y-coordinate point 1 :param y2: y-coordinate point 2 :param y3: y-coordinate point 3 :return: x-location of the minimum """ # div = (2.*(x3*(y1 - y2) + x1*(y2 - y3) + x2*(-y1 + y3))) return (x3**2*(y1 - y2) + x1**2*(y2 - y3) + x2**2*(-y1 + y3))/div
c557478554df7143b2fe193927bf9b8933ba30e7
63,324
def generate_transition_trigram_probabilities(transition_bigram_counts, transition_trigram_counts): """Takes in the bigram and trigram count matrices. Creates dictionary containing the transition trigram probabilities in the following format: {(tag[i-2], tag[i-1], tag[i]) : probability} where the probability is calculated by the following formula: probability((tag[i-2], tag[i-1], tag[i])) = count((tag[-2], tag[i-1], tag[i]))/count((tag[i-2], tag[i-1])) """ transition_trigram_probabilities = dict() for tag_trigram in transition_trigram_counts: transition_trigram_probabilities[tag_trigram] = float(transition_trigram_counts[tag_trigram])/transition_bigram_counts[(tag_trigram[0], tag_trigram[1])] return transition_trigram_probabilities
38790b31a4f15f0efaadee87e7ba6badc4249820
63,325
def get_result_from_input_values(input, result): """Check test conditions in scenario results input. Check whether the input parameters of a behave scenario results record from testapi match the input parameters of the latest test. In other words, check that the test results from testapi come from a test done under the same conditions (frame size, flow count, rate, ...) Args: input: input dict of a results dict of a behave scenario from testapi result: dict of nfvbench params used during the last test Returns: True if test conditions match, else False. """ # Select required keys (other keys can be not set or unconsistent between scenarios) required_keys = ['duration_sec', 'frame_sizes', 'flow_count', 'rate'] if 'user_label' in result: required_keys.append('user_label') if 'flavor_type' in result: required_keys.append('flavor_type') subset_input = dict((k, input[k]) for k in required_keys if k in input) subset_result = dict((k, result[k]) for k in required_keys if k in result) return subset_input == subset_result
421fac0d76bf0ec9a861b137db7ea6ceaf3cc92a
63,332
def convert_dm_ref_zp_flux_to_nanoJansky(flux, dm_ref_zp=27): """Convert the listed DM coadd-reported flux values to nanoJansky. Eventually this function should be a no-op. But presently The processing of Run 1.1, 1.2 to date (2019-02-17) have calibrated flux values with respect to a reference ZP=27 mag The reference catalog is on an AB system. Re-check dm_ref_zp if calibration is updated. Eventually we will get nJy from the final calibrated DRP processing. """ AB_mag_zp_wrt_Jansky = 8.90 # Definition of AB AB_mag_zp_wrt_nanoJansky = 2.5 * 9 + AB_mag_zp_wrt_Jansky # 9 is from nano=10**(-9) calibrated_flux_to_nanoJansky = 10**((AB_mag_zp_wrt_nanoJansky - dm_ref_zp)/2.5) return calibrated_flux_to_nanoJansky * flux
b3eb1828a1f8621bc76bf6d8a4da2ede58b5cf2b
63,333
def compress(nparray, newMax=1, newMin=0): """compress an numpy array, default is from range 0 to 1""" minimum = min(nparray) maximum = max(nparray) if(maximum - minimum) == 0: return nparray return (((nparray - minimum)/ ( max(nparray) - minimum)) * newMax + newMin)
99c67c099ee4ffc3399731674a0c376a2a8b5af2
63,342
def create_tsv(df, filename=None): """Convert pandas DataFrame to text-based table for SISSO. Args: df (pandas DataFrame): Dataframe of samples and features. filename: Path for writing file (optional). Returns (if filename==None): table (string) """ table = df.to_string() lines = table.splitlines() index_name = lines.pop(1).strip() lines[0] = index_name + lines[0][len(index_name):] table = '\n'.join(lines) if filename is not None: with open(filename, 'w') as f: f.write(table) else: return table
c43372835837922f21fd5131f421d295eb7298c6
63,343
from typing import Tuple def _ingresar_coordenadas() -> Tuple[int, int]: """Ingreso de coordenadas. :return: Coordenadas x e y :rtype: Tuple[int, int] """ x = int(input("x: ")) y = int(input("y: ")) return x, y
2e1f3d122ac68a6ed7f8785291f2d2310af198c9
63,345
import importlib def _object_from_name(object_name): """Creates an object from its name as a python string. Args: object_name: the name of the object to be created as a string. Returns: the object that the string refers to, dynamically imported. """ module_name, top_name = object_name.rsplit('.', 1) the_module = importlib.import_module(module_name) return getattr(the_module, top_name)
8d5b88487c0cdac7ec6797030cdb0667e0399f97
63,349
def dist_to_conc(dist, r_min, r_max, rule="trapezoid"): """ Converts a swath of a size distribution function to an actual number concentration. Aerosol size distributions are typically reported by normalizing the number density by the size of the aerosol. However, it's sometimes more convenient to simply have a histogram of representing several aerosol size ranges (bins) and the actual number concentration one should expect in those bins. To accomplish this, one only needs to integrate the size distribution function over the range spanned by the bin. Parameters ---------- dist : object implementing a ``pdf()`` method the representation of the size distribution r_min, r_max : float the lower and upper bounds of the size bin, in the native units of ``dist`` rule : {'trapezoid', 'simpson', 'other'} (default='trapezoid') rule used to integrate the size distribution Returns ------- float The number concentration of aerosol particles the given bin. Examples -------- >>> dist = Lognorm(mu=0.015, sigma=1.6, N=850.0) >>> r_min, r_max = 0.00326456461236 0.00335634401598 >>> dist_to_conc(dist, r_min, r_max) 0.114256210943 """ pdf = dist.pdf width = r_max - r_min if rule == "trapezoid": return width*0.5*(pdf(r_max) + pdf(r_min)) elif rule == "simpson": return (width/6.)*(pdf(r_max) + pdf(r_min) + 4.*pdf(0.5*(r_max + r_min))) else: return width*pdf(0.5*(r_max + r_min))
5c6dedfa49842e32dcb246bdc1e9dfc445b304ec
63,350
def fmt_option_val(option): """Format a single option (just a value , no key).""" if option is None: return "" return str(option)
410269228c0feb0a763edef8c0c7595ed4b22946
63,353
import json def prepareJSONstring(message_type, data, signature=None, verification=None): """ Prepares the JSON message format to be sent to the Buyer :param message_type: MENU/SESSION_KEY/DATA/DATA_INVOICE :param data: Corresponding data :param signature: Signed Data :param verification: Address or the transaction ID in Tangle/Blockchain :return: JSON dictionary """ json_data = {} json_data['message_type'] = message_type json_data['data'] = data if signature: json_data['signature'] = signature else: json_data['signature'] = "" if verification: json_data['verification'] = verification else: json_data['verification'] = "" return json.dumps(json_data)
c0db35ccb80fa1c13457358c5889cb66bd90ac76
63,354
import math def nCr(n: int, r: int) -> float: """Computes nCr Args: n: Total number r: Number to sample Returns: nCr """ if r > n or n < 0 or r < 0: return 0 f = math.factorial return f(n) // f(r) // f(n - r)
fcdaa2db1a71644faa881e18c080e655ecbfd5c2
63,357
def climbStairs(n): """ LeetCode 70:爬楼梯 建模为斐波那契数列问题:f(n) = f(n-1) + f(n-2) """ dp = [1, 2] if n < 3: return dp[n-1] for i in range(3, n+1): tmp = sum(dp) dp = [dp[1], tmp] return dp[1]
1f9b039a2996480cb0a6ca28d79d0076ab08eed7
63,358
def particao(a, b, N): """ Dados os pontos inicial $a$ e final $b$, e o número $N$ de subintervalos da partição regular desejada, esta função retorna a partição regular com tais características, sob a forma de uma lista """ lista = [a] delta = (b - a)/N for j in range(1, N+1): lista += [a + j * delta] return lista
e167870ffea5f45581d5f683e0d77b226ab53997
63,363
def get_compat_files( file_paths, compat_api_version): """Prepends compat/v<compat_api_version> to file_paths.""" return ["compat/v%d/%s" % (compat_api_version, f) for f in file_paths]
1974762e850e24d0ba1a00abefebe625a3243c84
63,364
def transformed_potential_energy(potential_energy, inv_transform, z): """ Given a potential energy `p(x)`, compute potential energy of `p(z)` with `z = transform(x)` (i.e. `x = inv_transform(z)`). :param potential_energy: a callable to compute potential energy of original variable `x`. :param ~numpyro.distributions.constraints.Transform inv_transform: a transform from the new variable `z` to `x`. :param z: new variable to compute potential energy :return: potential energy of `z`. """ x, intermediates = inv_transform.call_with_intermediates(z) logdet = inv_transform.log_abs_det_jacobian(z, x, intermediates=intermediates) return potential_energy(x) - logdet
ec8f27658cd573bd28c77eebf34b68800f1962b4
63,365
def _hex_to_rgb(_hex): """ Convert hex color code to RGB tuple Args: hex (str): Hex color string, e.g '#ff12ff' or 'ff12ff' Returns: (rgb): tuple i.e (123, 200, 155) or None """ try: if '#' in _hex: _hex = _hex.replace('#', "").strip() if len(_hex) != 6: return None (r, g, b) = int(_hex[0:2], 16), int(_hex[2:4], 16), int(_hex[4:6], 16) return (r, g, b) except Exception: return None
ff268246dd20aa50e2fdad711811784f5c1f5de5
63,370
from datetime import datetime def generate_report_name(report_instance): """ Generate a filename for a report based on the current time and attributes of an individual :model:`reporting.Report`. All periods and commas are removed to keep the filename browser-friendly. """ def replace_chars(report_name): return report_name.replace(".", "").replace(",", "") timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") client_name = report_instance.project.client assessment_type = report_instance.project.project_type report_name = replace_chars(f"{timestamp}_{client_name}_{assessment_type}") return report_name
f92d54d3bb14068526b292ce36061ede001c2e97
63,373
import math def UTM_EPSG(longitude, latitude): """Find UTM EPSG code of a longitude, latitude point.""" zone = str((math.floor((longitude + 180) / 6) % 60) + 1) epsg_code = 32600 epsg_code += int(zone) if latitude < 0: epsg_code += 100 return epsg_code
dfdfd1df086a400cece576a54a55f20ee72d494a
63,375