content
stringlengths
42
6.51k
def coups_legaux(grille): """Renvoie la liste des colonnes dans lesquelles il est possible de jouer un jeton """ coups = [] for i in range(0, 6): if grille[i][0] == 0: coups += [str(i + 1)] return coups
def mag(mag_star, mag_ref=0): """Calculates the brightness difference based on magnitudes Parameters ---------- mag_star : float Magnitude of input star mag_ref : float magnitude of reference star""" return 10**(0.4*((mag_ref)-(mag_star)))
def compute_markdown_rendering(rendertype, text): """Generate special markdown rendering.""" rendered = "" if text: if rendertype == 1: for key, value in text.items(): rendered += "* " + key + " ### " + value + "\n" elif rendertype == 2: for i in text: rendered += "* " + i + "\n" elif rendertype == 3: for key, value in text.items(): rendered += "* " + key + ": " + str(value) + "\n" elif rendertype == 4: rendered = "[![](" + text + ")](" + text + ")" else: rendered = text else: text = "Something weird happened :(" return rendered
def get_file_name(file): """ As explained in clone_online_repo method test_dataset_* file name must be branch's name """ return file.split("/")[-1].split(".")[0]
def compareDicts(dict1, dict2): """ Compare two dictionaries, returning sets containing keys from dict1 difference dict2, dict2 difference dict1, and shared keys with non-equivalent values, respectively. Parameters ---------- dict1 : dict dict2 : dict Returns ------- set, set, set """ d1_keys = set(dict1.keys()) d2_keys = set(dict2.keys()) new = d1_keys - d2_keys missing = d2_keys - d1_keys modified = {k for k in d1_keys & d2_keys if dict1[k] != dict2[k]} return new, missing, modified
def trans_shape(trans_index, tensor_shape): """trans_shape""" s = list(tensor_shape) s[trans_index[0]], s[trans_index[1]] = s[trans_index[1]], s[trans_index[0]] return tuple(s)
def day_to_num(day): """ Converts day of week to numerical value. """ converter = { 'mon' : 0, 'tue' : 1, 'wed' : 2, 'thu' : 3, 'fri' : 4, 'sat' : 5, 'sun' : 6 } return converter[day]
def is_valid_ip(ip: str) -> bool: """Checks if ip address is valid Examples: >>> assert is_valid_ip('12.255.56.1') >>> assert not is_valid_ip('1.1.1') """ octets = ip.split(".") if not octets or len(octets) != 4: return False return all(map(lambda octet: octet in map(str, range(256)), octets))
def getKeyPath(parent, keyPath): """ Allows the getting of arbitrary nested dictionary keys via a single dot-separated string. For example, getKeyPath(parent, "foo.bar.baz") would fetch parent["foo"]["bar"]["baz"]. If any of the keys don't exist, None is returned instead. @param parent: the object to traverse @type parent: any dict-like object @param keyPath: a dot-delimited string specifying the path of keys to traverse @type keyPath: C{str} @return: the value at keyPath """ parts = keyPath.split(".") for part in parts[:-1]: child = parent.get(part, None) if child is None: return None parent = child return parent.get(parts[-1], None)
def is_create(line): """ Returns true if the line begins a SQL insert statement. """ return line.startswith('CREATE TABLE') or False
def _in_target(h, key): """ This function checks whether the target exist and key present in target config. :param h: target config. :param key: attribute name. :return: True/False. """ return True if h and key in h else False
def factorial(n): """ This function returns the factorial of n. factorial(5) => 120 """ #base case if n == 0: return 1 #recursive case else: fact = n * factorial(n-1) return fact
def leja_growth_rule(level): """ The number of samples in the 1D Leja quadrature rule of a given level. Most leja rules produce two point quadrature rules which have zero weight assigned to one point. Avoid this by skipping from one point rule to 3 point rule and then increment by 1. Parameters ---------- level : integer The level of the quadrature rule Return ------ num_samples_1d : integer The number of samples in the quadrature rule """ if level == 0: return 1 return level+2
def get_test_config(config, test): """Get a single test module's config""" return config["modules"].get(test)
def is_prime(n): """Determine if input number is prime number Args: n(int): input number Return: true or false(bool): """ for curr_num in range(2, n): # if input is evenly divisible by the current number if n % curr_num == 0: # print("current num:", curr_num) return False return True
def show_bit_mask(bit_mask): """ """ return '{:012b}'.format(bit_mask)
def html_close(tag): """</tag>""" return "</{}>".format(tag)
def decode_txpower(t): """ convert the data in info['txpower'] which is, for example, '15.00 dBm' into 15.0 @return: the value of the tx power @rtype: float """ r = float(t.split()[0].strip()) return r
def userstatus(data): """ Returns a dictionary id : status with info about latest status of every user in data. status - dict """ return {u['id']: u["status"] for u in data['users']}
def extract_groups_cores(grouped_jobs, max_cores=None): """Processes the list of task names to group, extracting the max number of cores per task. The grouped task name can have the format: task_name:num_cores or just task_name. If num_cores is set, the max_cores is used instead. Args: - grouped_jobs: list of strings of the format task_name or task_name:num_cores. Task_name refers to the name field of tasks to be grouped. num_cores to the maximum number of cores assigned to that tasks group. - max_cores: maximum number of cores used to group tasks in no specific value is set. Returns - new_groups: list of names of grouped tasks. - max_cores_dic: dictionary of integers with the maximum number of cores per grouped tasks indexed by the name of grouped tasks. """ new_groups = [] max_cores_dic = {} for gr in grouped_jobs: if ":" in gr: tokens = gr.split(":") new_groups.append(tokens[0]) max_cores_dic[tokens[0]]=(int(tokens[1])) else: new_groups.append(gr) max_cores_dic[gr]=max_cores return new_groups, max_cores_dic
def leniter(iterator): """leniter(iterator): return the length of an iterator, consuming it.""" if hasattr(iterator, "__len__"): return len(iterator) nelements = 0 for _ in iterator: nelements += 1 return nelements
def word_fits_in_line(pagewidth, x_pos, wordsize_w): """ Return True if a word can fit into a line. """ return (pagewidth - x_pos - wordsize_w) > 0
def safe2f(x): """converts to float if possible, otherwise is a string""" try: return float(x) except: return x
def get_resource_and_action(action): """ Extract resource and action (write, read) from api operation """ data = action.split(':', 1)[0].split('_', 1) return ("%ss" % data[-1], data[0] != 'get')
def get_acceleration_of_gravity(_): """ Get the acceleration of gravity for a carla vehicle (for the moment constant at 9.81 m/s^2) :param vehicle_info: the vehicle info :type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo :return: acceleration of gravity [m/s^2] :rtype: float64 """ acceleration = 9.81 return acceleration
def make_list(obj): """ Turn an object into a list if it isn't already """ if isinstance(obj, list): return obj else: return list(obj)
def ValueErrorOnNull(result, error): """Raises ValueError(error) if result is None, otherwise returns result.""" if result is None: raise ValueError(error) return result
def sin_recursive(x, N=100): """Calculate sin(x) for N iterations. Arguments --------- x : float argument of sin(x) N : int number of iterations Returns ------- func_value """ # special case 0 if x == 0: return 0.0 sumN = an = x # n=1 for n in range(2, N+1): qn = -x*x/((2*n - 1) * (2*n - 2)) an *= qn sumN += an return sumN
def find_prime(x): """ Usage: Find largest prime numbers within a list of integer. Argument: x : a list of integer. Return: an integer Examples: find_prime([0,1,2,3,4,5]) >>>5 find_prime([0,1]) >>> "No prime number in list" find_prime(["hello", 1, 5]) >>> "Exception error: input list must contains only integers" """ #set list of predefined list of prime numbers less than 1000 prime = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997] # Raise error if input not a list if type(x) != list: raise TypeError("Input must be a list") # Raise error if input is not integer (eg. float, string...) for i in x: if type(i) != int: raise TypeError("Input must be list of intergers") # Raise error if input values less than 1000 if max(x) >= 1000: raise ValueError("Input values exceed 1000. Please limit range of input values to less than 1000.") #return list of prime numbers max_prime = list(set(x).intersection(prime)) #return the largest prime numbers if len(max_prime) >=1: return max(max_prime) else: return "No prime number in list"
def numstr(number, decimalpoints: int) -> str: """ Print big numbers nicely. Add commas, and restrict decimal places Parameters ---------- number : numeric decimalpoints : int Number of decimal points to which the output string is restricted Returns ------- str nicely formatted number """ fmtstr = '{:,.%sf}' % str(decimalpoints) return fmtstr.format(number)
def remap(value, from_min_value, from_max_value, to_min_value, to_max_value): """Remap value from from_min_value:from_max_value range to to_min_value:to_max_value range""" # Check reversed input range reverse_input = False from_min = min(from_min_value, from_max_value) from_max = max(from_min_value, from_max_value) if from_min != from_min_value: reverse_input = True # Check reversed output range reverse_output = False to_min = min(to_min_value, to_max_value) to_max = max(to_min_value, to_max_value) if to_min != to_min_value : reverse_output = True portion = (value - from_min) * (to_max - to_min) / (from_max - from_min) if not reverse_input \ else (from_max - value) * (to_max - to_min) / (from_max - from_min) new_value = portion + to_min if not reverse_output else to_max - portion return new_value
def get_remote_host(dns_prefix, location): """ Provides a remote host according to the passed dns_prefix and location. """ return '{}.{}.cloudapp.azure.com'.format(dns_prefix, location)
def build_response(session_attributes, speechlet_response): """ Build the full response JSON from the speechlet response """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
def _value(ch, charset): """Decodes an individual digit of a base62 encoded string.""" try: return charset.index(ch) except ValueError: raise ValueError('base62: Invalid character (%s)' % ch)
def getMatchingLFN(_lfn, lfns): """ Return the proper LFN knowing only the preliminary LFN """ # Note: the preliminary LFN may contain substrings added to the actual LFN actual_lfn = "" for lfn in lfns: if lfn in _lfn: actual_lfn = lfn break return actual_lfn
def derivative(func, x, h): """ Evaluate the derivative of a function at point x, with step size h Uses the symmetric derivative Parameters ---------- func : function Function to evaluate x : float Point to evaluate derivative h : float Step size Returns ------- retval : float Derivative """ return (func(x+h) - func(x-h))/(2*h)
def zigzag(seq): """ returns odd values, even values """ return seq[::2], seq[1::2]
def lines_cross(begin1, end1, begin2, end2, inclusive=False): """ Returns true if the line segments intersect """ A1 = end1[1] - begin1[1] B1 = -end1[0] + begin1[0] C1 = - (begin1[1] * B1 + begin1[0] * A1) A2 = end2[1] - begin2[1] B2 = -end2[0] + begin2[0] C2 = - (begin2[1] * B2 + begin2[0] * A2) if A1 * B2 == A2 * B1: return False if inclusive: return ((A1 * begin2[0] + B1 * begin2[1] + C1) * (A1 * end2[0] + B1 * end2[1] + C1) <= 0 and (A2 * begin1[0] + B2 * begin1[1] + C2) * (A2 * end1[0] + B2 * end1[1] + C2) <= 0) else: return ((A1 * begin2[0] + B1 * begin2[1] + C1) * (A1 * end2[0] + B1 * end2[1] + C1) < 0 and (A2 * begin1[0] + B2 * begin1[1] + C2) * (A2 * end1[0] + B2 * end1[1] + C2) < 0)
def fibonacci(n): """ This is the original function, it will be used to compare execution times. """ if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2)
def knight(x,y): """Knight distance heuristic.""" return max((x//2+x%2),(y//2+y%2))
def isIONO(filename): """ Checks whether a file is IM806 format. """ try: temp = open(filename, 'rt').readline() except: return False try: if not temp.startswith('Messdaten IM806'): if not temp.startswith('Date;Time;NegMin;'): return False except: return False return True
def port_bound(port): """Returns true if the port is bound.""" return port['binding:vif_type'] != 'unbound'
def Generate_windows_and_count_tags(taglist, chrom, chrom_length, window_size, file): """ taglist: sorted list of positions that includes every tag on a chromosome window_size: the artificial bin size for binning the tags bed_vals: a dictionary keyed by the start of tag_containing windows, with value being the tag count in the window. In this function, the bins are set up using an absolute coordinate system. Namely [0, window_size-1),[window_size, 2*window_size-1). If the last window goes beyond the limit of the chromosome, that window is ignored. The result writen into the file is guaranteed to be already sorted within a chromosome. """ bed_vals = {}; outfile = open(file, 'w'); if (len(taglist) > 0): current_window_start = (taglist[0] / window_size) * window_size; tag_count_in_current_window = 1; for i in range(1, len(taglist)): start = (taglist[i] / window_size) * window_size; if start == current_window_start: tag_count_in_current_window += 1; elif start > current_window_start: # All the tags in the previous window have been counted current_window_end = current_window_start + window_size - 1; # if the window goes beyond the chromsome limit, it is discarded. if current_window_end < chrom_length: bed_vals[current_window_start] = tag_count_in_current_window; # write the window to file outline = chrom + "\t" + str(current_window_start) + \ "\t" + str(current_window_end) + "\t" + \ str(tag_count_in_current_window) + "\n"; outfile.write(outline); current_window_start = start; tag_count_in_current_window = 1; else: print 'Something is wrong!!!!!!!'; current_window_end = current_window_start + window_size - 1; # if the window goes beyond the chromsome limit, it is discarded. if current_window_end < chrom_length: bed_vals[current_window_start] = tag_count_in_current_window; outline = chrom + "\t" + str(current_window_start) + \ "\t" + str(current_window_end) + "\t" + \ str(tag_count_in_current_window) + "\n"; outfile.write(outline); outfile.close(); return bed_vals;
def digital_sum(n): """returns the sum of the digits of an integer""" assert isinstance(n, int), "Digital sum is defined for integers only." return sum([int(digit) for digit in str(n)])
def mixing_dict(xy, normalized=False): """Returns a dictionary representation of mixing matrix. Parameters ---------- xy : list or container of two-tuples Pairs of (x,y) items. attribute : string Node attribute key normalized : bool (default=False) Return counts if False or probabilities if True. Returns ------- d: dictionary Counts or Joint probability of occurrence of values in xy. """ d = {} psum = 0.0 for x, y in xy: if x not in d: d[x] = {} if y not in d: d[y] = {} v = d[x].get(y, 0) d[x][y] = v + 1 psum += 1 if normalized: for _, jdict in d.items(): for j in jdict: jdict[j] /= psum return d
def sizeToTeam(size): """Given a size in kilobytes, returns the 512kb.club team (green/orange/blue), or "N/A" if size is too big for 512kb.club""" if size<100: return "green" elif size<250: return "orange" elif size<=512: return "blue" else: return "N/A"
def count_data(data, code = None): """Helper function that counts the number of data points in an arbitrary list of lists""" if isinstance(data,list): sum = 0 for d in data: sum += count_data(d, code=code) return sum if data != '' and data != 'NA': if code == None or data == code: return 1 return 0
def greaterD( ef, gh): """ Return True if pair ef has greater margin than pair gh. A pair is a pair of the form: (pref[e,f],pref[f,e]) Schulze says (page 154): "(N[e,f],N[f,e]) >_win (N[g,h],N[h,g]) if and only if at least one of the following conditions is satisfied: 1. N[e,f] > N[f,e] and N[g,h] <= N[h,g]. 2. N[e,f] >= N[f,e] and N[g,h] < N[h,g]. 3. N[e,f] > N[f,e] and N[g,h] > N[h,g] and N[e,f] > N[g,h]. 4. N[e,f] > N[f,e] and N[g,h] > N[h,g] and N[e,f] = N[g,h] and N[f,e] < N[h,g]." """ nef,nfe = ef ngh,nhg = gh if nef > nfe and ngh <= nhg: return True if nef >= nfe and ngh < nhg: return True if nef > nfe and ngh > nhg and nef > ngh: return True if nef > nfe and ngh > nhg and nef==ngh and nfe < nhg: return True return False
def sort_databases(dbs: list, chids: tuple) -> tuple: """Ensures that the databases match the cubes.""" if len(dbs) != len(chids): raise IndexError( f"The number of databases {len(dbs)} does not " "match the number of Product IDs {chids}" ) chid_db_map = dict() for p in chids: for d in dbs: if str(p) == d["PRODUCT_ID"]: chid_db_map[p] = d break if len(chid_db_map) != len(chids): raise LookupError( "The Product IDs in the databases " f"do not match {chids}" ) return tuple(map(chid_db_map.get, chids))
def find_new(vglist1,vglist2,key): """ Return list of elements of vglist2 that are not in vglist1. Uses specified key to determine new elements of list. """ # Get all the values for the specified key values = [] for row in vglist1: values.append(row[key]) # Check through the new list for new values new_rows = [] for row in vglist2: if row[key] in values: # already exists in vglist1 continue else: new_rows.append(row) return new_rows
def make_car( manufacturer, model_name, **car_info): """Build a dictionary containing everything we know about a car.""" car = {} car['manufacturer'] = manufacturer car['model'] = model_name for key, value in car_info.items(): car[key] = value return car
def page_not_found(e): """ Handler for page not found 404 """ # pylint: disable=no-member # pylint: disable=unused-argument # pylint: disable=undefined-variable return "Flask 404 here, but not the page you requested."
def user_login(r): """ Because dict nesting, this is a special function to return the user_login out of a dict """ if "user" in r: if "login" in r["user"]: return r["user"]["login"] return None
def clean_description(incoming: str) -> str: """Format behavior description strings for output.""" description = [] for desc in incoming.split("\n"): part = "" for piece in desc.split(): delim = "" if len(part) > 60: description.append(part) part = "" if part: delim = " " part = f"{part}{delim}{piece}" description.append(part) return "\n".join(description)
def slim_aggregates(aggregates): """"slim version of the region aggregates, minimizing NoData and verbose naming""" slimmed_aggregates = [] for aggregate in aggregates: verbose_keys = list(aggregate.keys()) for verbose_key in verbose_keys: slim_key = verbose_key.split("_")[0] aggregate[slim_key] = aggregate.pop(verbose_key) datetime = aggregate["datetime"] aggregate["Date"] = datetime.split("T")[0] + "Z" aggregate.pop("datetime", None) slimmed_aggregates.append(aggregate) return slimmed_aggregates
def get_nth_digit(N, n): """ return the nth digit from an N digit number >>> get_nth_digit(12345, 3) 4 >>> get_nth_digit(12345, 7) Traceback (most recent call last): ... IndexError: string index out of range """ return int(str(N)[n])
def caminho_asset(nome: str, png_min: bool = False) -> str: """Retorna o caminho para o asset da peca com o identificador passado""" return f'assets/{nome}.png' + ('.min' if png_min else '')
def uppercase_underscore(a_string): """ Internally some strings that are Title Cased With Spaces should be UPPER_CASED_WITH_UNDERSCORES. """ a_string = a_string.replace(' ','_') return a_string.upper()
def query_newer_than(timestamp): """ Return a query string for later than "timestamp" :param timestamp: CloudGenix timestamp :return: Dictionary of the query """ return { "query_params": { "_updated_on_utc": { "gt": timestamp } }, "sort_params": { "id": "desc" } }
def lines_from_file(path): """Return a list of strings, one for each line in a file.""" with open(path, "r") as f: return [line.strip() for line in f.readlines()]
def XMLescape(txt): """Returns provided string with symbols & < > " replaced by their respective XML entities.""" return txt.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
def get_repo_name_from_url(url): """ :param url: :return: user/repo (or None if invalid) """ url = url.replace(' ', '') url = url.lower().strip() if url[:19] == "https://github.com/": name = url[19:] else: name = url print("name: "+name) if name[-1] == "/": name = name[:-1] print(len(name.split('/'))) if len(name.split('/')) == 2: return name return None
def parse_spec(spec, default_module): """Parse a spec of the form module.class:kw1=val,kw2=val. Returns a triple of module, classname, arguments list and keyword dict. """ name, args = (spec.split(':', 1) + [''])[:2] if '.' not in name: if default_module: module, klass = default_module, name else: module, klass = name, None else: module, klass = name.rsplit('.', 1) al = [a for a in args.split(',') if a and '=' not in a] kw = dict(a.split('=', 1) for a in args.split(',') if '=' in a) return module, klass, al, kw
def divide_grid(grid): """Divides the length of a grid into 4 and returns a list of slice indices.""" chunksize = int(len(grid)/4) chunk1 = (0, chunksize) chunk2 = (chunksize, chunksize*2) chunk3 = (chunksize*2, chunksize*3) chunk4 = (chunksize*3, len(grid)) return [chunk1, chunk2, chunk3, chunk4]
def factorial_recursive(num): """returns the factorial of num using a recursive method.""" return 1 if num == 0 else num * factorial_recursive(num - 1)
def select_top_relsent_cred(relsent): """Select the top available credibility source for a relsent This will be either the domain_credibility or a normalised claimReview_credibility_rating. :param relsent: a SimilarSent dict :returns: either the domain_credibility, or the claimReview_credibility_rating whichever has the highest confidence (although claimReview has precedence). If neither is available, returns an empty dict. :rtype: dict """ domcred = relsent.get('domain_credibility', {}).get('credibility', {}) domcred['source'] = 'domain' domcred['domainReviewed'] = relsent.get( 'domain_credibility', {}).get('itemReviewed', "??") cr_cred = relsent.get('claimReview_credibility_rating', {}) cr_cred['source'] = 'claimReview' if 'confidence' in cr_cred and cr_cred.get('confidence', -1.0) > 0.2: # avoid domcred, it could point to trustworthy factchecker domain!! src_creds = [cr_cred] else: src_creds = [domcred, cr_cred] src_creds = sorted(src_creds, key=lambda cred: cred.get('confidence', -1.0), reverse=True) return src_creds[0]
def unify_stringlist(L: list): """ Adds asterisks to strings that appear multiple times, so the resulting list has only unique strings but still the same length, order, and meaning. For example: unify_stringlist(['a','a','b','a','c']) -> ['a','a*','b','a**','c'] """ assert(all([isinstance(l,str) for l in L])) return [L[i]+"*"*L[:i].count(L[i]) for i in range(len(L))]
def removestringparts(matchers, listt): """returns cleaned list of input listt (list) and to-be-removed matchers (list) >>> removestringparts("QQ",["QQasdf","asdfQQasdf"]) ['asdf', 'asdfasdf'] >>> removestringparts(["QQ","s"],["QQasdf","asdfQQasdf"]) ['adf', 'adfadf'] """ #print("hi") if type(matchers)==str: matchers=[matchers]#assume if a string given to only replace the whole thing for matcher in matchers: listt = [line.replace(matcher,"") for line in listt] # replace with nothing #print(line) return listt
def repeat(s, exclaim): """ Returns the string 's' repeated 3 times. If exclaim is true, add exclamation marks. """ result = s + s + s # can also use "s * 3" which is faster (Why?) #faster because * calculates len of object once, + does it each time + is called #+ and * are called "overloaded" operators because they mean different things for numbers vs strings if exclaim: result = result + '!!!' return result
def dxR_calc(u,Ki_GCC): """Calculate derivative of current controller integral state - real component""" dxR = Ki_GCC*u.real return dxR
def _property_method(class_dict, name): """ Returns the method associated with a particular class property getter/setter. """ return class_dict.get(name)
def file_cadence(granularity): """Set the resolution of the file""" if granularity < 60*60*24: return '1D' else: return '1M'
def find_local_maxima(etas, es): """ input: a real array es energies(eta) output: all local maxima """ n = len(es) out = [] for i in range(1,n-1): if es[i] > es[i-1] and es[i] > es[i+1]: out.append((etas[i],es[i])) return out
def exclude_tags(tag_list, *args): """ - Filters a tag set by Exclusion - variable tag keys given as parameters, tag keys corresponding to args are excluded RETURNS TYPE: list """ clean = tag_list.copy() for tag in tag_list: for arg in args: if arg == tag['Key']: clean.remove(tag) return clean
def extrapolDiff(f, x, h): """return Ableitung der Funktion f an Stelle x nach '1/3h *( 8*(f(x + h/4)-f(x - h/4)) - (f(x + h/2) - f(x - h/2)))' """ return 1/(3*h) * (8*(f(x+h/4) - f(x-h/4)) - (f(x+h/2) - f(x-h/2)))
def ordinal(value): """ Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except (TypeError, ValueError): return value t = ('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th') if value % 100 in (11, 12, 13): # special case return u"%d%s" % (value, t[0]) return u'%d%s' % (value, t[value % 10])
def any(iter): """ For < Python2.5 compatibility. """ for elem in iter: if elem: return True return False
def unique_sorted_list(nums): """ Returns a unique numbers in the list in a sorted order. List items should contain only the integers """ unique_list = [] for number in nums: if number not in unique_list: unique_list.append(number) unique_list.sort() return unique_list
def decimal_from_str(src): """Decodes a decimal from a string returning a python float value. If string is not a valid lexical representation of a decimal value then ValueError is raised.""" sign = False point = False digit = False for c in src: v = ord(c) if v == 0x2B or v == 0x2D: if sign: raise ValueError( "Invalid lexical representation of decimal: %s" % src) else: sign = True elif v == 0x2E: if point: raise ValueError( "Invalid lexical representation of decimal: %s" % src) else: point = True elif v < 0x30 or v > 0x39: raise ValueError( "Invalid lexical representation of integer: %s" % src) else: # a digit means we've got an empty sign sign = True digit = True if not digit: # we must have at least one digit raise ValueError("Invalid lexical representation of integer: %s" % src) return float(src)
def tags_since_dt(sentence, i): """Creates a string describing the set of all part-of-speech tags\ that have been encountered since the most recent determiner. :param sentence: Array of word and part of speech tag :param i: Index of the actual word """ tags = set() for word, pos in sentence[:i]: if pos == 'DA': tags = set() else: tags.add(pos) return '+'.join(sorted(tags))
def user_dict(user, base64_file=None): """Convert the user object to a result dict""" if user: return { 'username': user.id, 'accesskey': user.access, 'secretkey': user.secret, 'file': base64_file, } else: return {}
def calc_image_weighted_average_accuracy(dict): """Calculate SOA-I""" accuracy = 0 total_images = 0 for label in dict.keys(): num_images = dict[label]["images_total"] accuracy += num_images * dict[label]["accuracy"] total_images += num_images overall_accuracy = accuracy / total_images return overall_accuracy
def get_worktime(hour_in, hour_out, check_in, check_out): """menghitung jam kerja minus telat dan pulang awal""" if check_in > hour_in: result = hour_out - check_in elif check_out > hour_out: result = check_out - hour_in else: result = hour_out - hour_in return result
def is_quantity_range(val: str) -> bool: """Checks if [] are present in val. """ if '[' in val and ']' in val: return True return False
def hide_password(url, start=6): """Returns the http url with password part replaced with '*'. :param url: URL to upload the plugin to. :type url: str :param start: Position of start of password. :type start: int """ start_position = url.find(':', start) + 1 end_position = url.find('@') return "%s%s%s" % ( url[:start_position], '*' * (end_position - start_position), url[end_position:])
def tags_as_str(tags): """Convert list of tags to string.""" return " ".join(tags) if tags else "all tests"
def _make_parameters(signature): """Return actual parameters (that can be passed to a call) corresponding to signature (the formal parameters). Copes with bare `*` (see PEP 3102) e.g. shutil.copyfile's signature is now "src, dst, *, follow_symlinks=True": return "src, dst, *, follow_symlinks=follow_symlinks" """ params = [] star = False for param in signature.split(','): if param.strip() == '*': star = True elif star: # a bare star means everything afterwards must be passed as named name, _ = param.split('=') params.append('%s=%s' % (name, name)) else: params.append(param) return ','.join(params)
def categorical(responses): """Analyses categorical responses Args: responses(list/tuple): List/tuple of the responses For example: ["Yes","No","Yes"] or ("Yes","No","Yes") Returns: A dictionary containing the sorted percentages of each response. For example: {"Percentages": {"No": 0.3333333333333333, "Yes": 0.6666666666666666}} """ categories = {} for i in responses: if i not in categories.keys(): categories[i] = 1 else: categories[i] += 1 for category, freq in categories.items(): categories[category] = freq / len(responses) sorting = sorted(categories.items(), key=lambda x: x[1]) return {"Percentages": dict(sorting)}
def extract_hyperparameter(file_path, name, delimiter='/'): """Extract hyperparameter value from the file path. Example 1: path: '/../learning_rate=420,momentum=101/Seed45' name: 'learning_rate=' delimiter: ',' return: '420' Example 2: path: '/../learning_rate420/momentum101/Seed45' name: 'learning_rate' delimiter: '/' return: '420' Args: file_path: A string file path to extract information from. name: The name of the hyperparameter as it appears in the path. delimiter: The separation between hyperparameters. Returns: The extracted hyperparameter value. """ return file_path.split(name)[1].split(delimiter)[0]
def levenshtein_1d_blocks(string, transpositions=False, flag='\x00'): """ Function returning the minimal set of longest Levenshtein distance <= 1 blocking keys of target string. Under the hood, this splits the given string into an average of 3 blocks (2 when string length is even, 4 when odd). When supporting transpositions, the function will always return 4 blocks to handle the case when middle letters are transposed. Note that this method therefore yields a constant number of keys, as opposed to ngrams which yield a number of keys proportional to the size of the given strings. The intuition of this technique can be found in Knuth. Similar concepts can be found in Doster. This is also reminiscent of q-samples. This method works quite well because it's independent of the string's length and therefore implicitly incorporates the string's length into the generated keys. Indeed, this method minimizes the number of produced keys (the number is constant, contrary to n-grams, for instance) and minimizes the probability of two strings colliding. What's more, this method is exact and won't generate false negatives like n-grams would. Args: string (str): Target string. transpositions (bool, optional): Whether to support transpositions like with the Damerau-Levenshtein distance. Defaults to False. Returns: tuple: Resulting blocks. """ n = len(string) if n == 1: return (flag + string, string + flag, flag) h = n // 2 # String has even length, we just split in half if n % 2 == 0: first_half = flag + string[:h] second_half = string[h:] + flag # For transpositions, we swap once the middle characters if transpositions: first_transposed_half = flag + string[:h - 1] + second_half[0] second_transposed_half = first_half[-1] + string[h + 1:] + flag return (first_half, second_half, first_transposed_half, second_transposed_half) else: return (first_half, second_half) # String has odd length, we split twice h1 = h + 1 first_half = flag + string[:h] second_half = string[h:] + flag first_half1 = flag + string[:h1] second_half1 = string[h1:] + flag return (first_half, second_half, first_half1, second_half1)
def bagdiff(xs, ys): """ merge sorted lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 while True: if xi >= len(xs): result.extend(ys[yi:]) return result if yi >= len(ys): result.extend(xs[xi:]) return result if xs[xi] < ys[yi]: result.append(xs[xi]) xi += 1 elif xs[xi] > ys[yi]: yi += 1 else: xi += 1 yi += 1
def laplace(x): """ Product of Laplace distributions, mu=3, b=0.1. """ return sum(abs(xi-3.)/0.1 for xi in x)
def str_to_bool(value): """Convert a string into a boolean""" if value.lower() in ("yes", "true", "t", "1"): return True if value.lower() in ("no", "false", "f", "0"): return False return None
def _to_lists(x): """ Returns lists of lists when given tuples of tuples """ if isinstance(x, tuple): return [_to_lists(el) for el in x] return x
def preprocess_cl_line(line): """Process one line in the category label database file.""" name, forms = line.strip().split("\t") forms = [form.strip() for form in forms.split(';')] return name, forms
def remove_empty_entries(dicts): """Drop keys from dicts in a list of dicts if key is falsey""" reduced = [] for d in dicts: new_d = {} for key in d: if d[key]: new_d[key] = d[key] reduced.append(new_d) return reduced
def meric_hit(h_rank, t_rank, N=50): """evaluate the vector result by hit-N method N: the rate of the true entities in the topN rank return the mean rate """ print('start evaluating by Hit') num = 0 for r1 in h_rank: if r1 <= N: num += 1 rate_h = num / len(h_rank) * 100 num = 0 for r2 in t_rank: if r2 <= N: num += 1 rate_t = num / len(t_rank) * 100 return (rate_h + rate_t) / 2
def _StringQuote(s, quote='"', escape='\\'): """Returns <quote>s<quote> with <escape> and <quote> in s escaped. s.encode('string-escape') does not work with type(s) == unicode. Args: s: The string to quote. quote: The outer quote character. escape: The enclosed escape character. Returns: <quote>s<quote> with <escape> and <quote> in s escaped. """ entity = {'\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'} chars = [] if quote: chars.append(quote) for c in s: if c in (escape, quote): chars.append(escape) elif c in entity: c = entity[c] chars.append(c) if quote: chars.append(quote) return ''.join(chars)
def helper_concatenation(var_pre, var_post): """ Simple helper method for concatenationg fields (Module and app/func name) """ return_val = None if var_pre is None: var_pre = "Not Specified" if var_post is None: var_post = "Not Specified" if var_pre != "Not Specified" or var_post != "Not Specified": return_val = var_pre + "/" + var_post return return_val
def quad2list2(quad): """ convert to list of list """ return [ [quad[0]["x"], quad[0]["y"]], [quad[1]["x"], quad[1]["y"]], [quad[2]["x"], quad[2]["y"]], [quad[3]["x"], quad[3]["y"]], ]