content
stringlengths
42
6.51k
def adjust_displacement(n_trials, n_accept, max_displacement): """Change the acceptance criteria to get the desired rate. When the acceptance rate is too high, the maximum displacement is adjusted \ to be higher. When the acceptance rate is too low, the maximum displacement is \ adjusted lower. ...
def split_list(list_to_split: list, num_chunks: int): """Splits a list into num_chunks""" chunks = [] err_msg = "You have more users than you have buckets" assert len(list_to_split) >= num_chunks, err_msg size_of_chunk = len(list_to_split) // num_chunks size_of_uneven_chunk = size_of_chunk + 1...
def count_change(amount): """Return the number of ways to make change for amount. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 >>> from construct_check import check >>> # ban iteration >>> check(HW_SOURCE_FILE, 'count_c...
def center_value(obj, stat_or_name): """Add spaces in order to center a text within an entry.""" obj_length = len(str(obj)) amount_of_maxium_spaces = 21 if stat_or_name != 'stat' else 4 amount_of_avaliable_spaces = amount_of_maxium_spaces - obj_length centered_obj = f"{amount_of_avaliable_spaces * ...
def hello(target: str) -> str: """ sample function """ return f"Hello {target}"
def copy_files(src_filepaths, dest_filepaths): """ Accepts two parallel lists of pathlib Path objects - full filepaths Copies the files Creates the destination directory if it does not already exist Returns the number of files copied - integer """ n_copied = 0 for src_filepath, dest_file...
def _feh_from_str(feh_str): """Converts a metallicity value to MIST string Example Usage: _feh_from_str("m0.53") -> -0.53 _feh_from_str("p1.326") -> 1.326 Arguments: feh_str -- metallicity (as a string) Output: float value of metallicity """ value = float(feh_str[1:]) if f...
def check_sender_line(line): """Return a boolean Check if line contains specific words to validate if that's the line we want. """ return 'cleanup' in line and 'from=' in line and 'Subject' in line
def bin2state(bin, num_bins, limits): """ :param bin: index in the discretization :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit of each discrete dimension, and row[1] are corresponding upper l...
def es_document(idx, typ, id, field): """Returns a handle on a field in a document living in the ES store. This does not fetch the document, or even check that it exists. """ # Returns a dict instead of a custom object to ensure JSON serialization # works. return {'index': idx, 'type': typ, 'id...
def first(inp_data): """ Return first element from `inp_data`, or raise StopIteration. Note: This function was created because it works for generators, lists, iterators, tuples and so on same way, which indexing doesn't. Also it have smaller cost than list(generator)[0], because it...
def get_positional(args, kw, kw_overrides=False): """Interpolates keyword arguments into argument lists. If `kw` contains keywords of the form "_0", "_1", etc., these are positionally interpolated into the argument list. Args: args: argument list kw: keyword dictionary kw_overrides: key/valu...
def dG_to_flux_bounds(dG_min, dG_max, infinity=1000, abstol=1e-6): """ Convert standard Gibbs energy range to reaction flux bounds. Args: dG_min (float): minimum standard Gibbs energy dG_max (float): maximum standard Gibbs energy infinity (float): value to represent infinity (default: 1...
def fibonacci2_aux(current, target, before_previous, previous): """ Tail recursive ascendant version - auxiliar function. """ if current == target: return before_previous + previous return fibonacci2_aux( current + 1, target, previous, before_previous + previous )
def cost_deriv(y, t): """ gradient. dcost / dy """ return 2 * (y - t)
def power_optimized(x, n): """Compute x to the power_optimized of n (with n>=0)""" #1- base case if n == 0: return 1 #2- solve sub-problems squared_power = power_optimized(x, n//2) #3- combine sub-solutions if n %2 == 0: res = squared_power * squared_power else: ...
def find_index_of_subset(large_list, small_list): """ Returns the index after the small_list within the large list, Returns None if not present. Adapted from https://stackoverflow.com/a/45819222 which shows that it is performant for input lengths < 1000, which is the common case for this function. ...
def list_files(locales, filename_func): """Returns the names of the files generated by filename_func for a list of locales. :param filename_func: function that generates a filename for a given locale """ files = [] for locale in locales: files.append(filename_func(locale)) return " ".join(['"%s"' % x...
def _extract_version_number(bazel_version): """Extracts the semantic version number from a version string Args: bazel_version: the version string that begins with the semantic version e.g. "1.2.3rc1 abc1234" where "abc1234" is a commit hash. Returns: The semantic version string...
def get_rotation(row): """Generate a rotation matrix from elements in dictionary ``row``. Examples --------- >>> sdict = { \ '_pdbx_struct_oper_list.matrix[{}][{}]'.format(i // 3 + 1, i % 3 + 1): i \ for i in range(9) \ } >>> get_rotation(sdict) [[0.0, 1.0, 2.0], [3.0, 4.0, ...
def get_bot_in_location(location, game): """Returns the bot in the given location.""" bots = game.get('robots') if location in bots.keys(): return bots[location] else: return None
def divergent(x:int, y:int, iteration_count:int): """Given the data point x y where c_pair= x + iy is in the complex plane. x and y values are from -2 to 2 exclusive. Return a list of ones and zeros corresponding to whether a z value diverges or converges at that point c.""" z = complex(0...
def get_top(cards, colour): """ Get the top card played of the given colour string. """ iter = [card.rank for card in cards if card.colour.lower() == colour.lower()] if not iter: return 0 return max(iter)
def rgb_to_hex(rgb_tuple): """Converts RGB values to HEX values """ return '#%02x%02x%02x' % rgb_tuple
def _dol_to_lod(dol): """Convert a dict of lists to a list of dicts.""" return [{key: dol[key][ii] for key in dol.keys()} for ii in range(len(dol[list(dol.keys())[0]]))]
def _calculate_ts(tp, fp, fn): """Calculate ts.""" return tp, (tp + fn + fp)
def func_x_a_args_p_kwargs(x, a=2, *args, p="p", **kwargs): """func. Parameters ---------- x: float a: int args: tuple p: str kwargs: dict Returns ------- x: float a: int args: tuple p: str kwargs: dict """ return x, None, a, None, args, p, None, kw...
def serializeData(data: bytes, padding: int = 1) -> list: """ This function packs data into groups of 2bits and returns that list """ serializedData = list() for datum in data: serializedData.append((datum >> 6) & 0b11) serializedData.append((datum >> 4) & 0b11) seria...
def add_location_postfix(token_seq, tag_seq, phrase, i_tag_index, i_tag): """ Create token sequence and tag sequence for postfix perturbation """ word_list = phrase.strip().split(" ") if len(word_list) == 1: token_seq.insert(i_tag_index + 1, phrase) tag_seq.insert(i_tag_index + 1, i_...
def extract_username(msg): """ Helper functions should not have trace turned on because the logger is triggered per dataframe row >>> """ # logger.info('[trace]') if msg.startswith('Failed password for invalid user '): return msg.replace('Failed password for invalid user ',''...
def create_all_possible_moves(m, n): """Create all moves on a (m,n) board.""" moves = [] for i in range(m): for j in range(n): moves.append((i, j)) return list(set(moves))
def is_tag(obj): """Determines if `obj` is a tuple of two strings. Examples: >>> is_tag(('hello', 'yes')) True >>> is_tag(('hi', 22)) False """ try: return ( isinstance(obj, tuple) and len(obj) == 2 and all((isinstance(x, str) or x == None) ...
def get_lsb(number): """Extracts the Least Significant Bit of a number. Arguments: number (int) -- the number from which the LSB is to be extracted Returns: int type -- the LSB of the number """ binary = str(bin(number))[2:] return int(binary[-1], 2)
def ndependencies(dependencies, dependents): """ Number of total data elements on which this key depends For each key we return the number of tasks that must be run for us to run this task. Examples -------- >>> dsk = {'a': 1, 'b': (inc, 'a'), 'c': (inc, 'b')} >>> dependencies, dependents ...
def dec2bin(num, width=0): """ >>> dec2bin(0, 8) '00000000' >>> dec2bin(57, 8) '00111001' >>> dec2bin(3, 10) '0000000011' >>> dec2bin(-23, 8) '11101001' >>> dec2bin(23, 8) '00010111' >>> dec2bin(256) '100000000' """ if num < 0: if not width: ...
def format_column_header(string): """ Cleanup column header. :param string: :return: """ _name = str(string).lower() _name = f'{_name[0].upper()}{_name[1:]}' _name = _name.replace('_', ' ').replace('-', ' ') return _name
def solution1(inp): """Solves the first part of the challenge""" inp = list(map(int, inp.strip())) N_MOVES = 100 i = 0 cur_cup = 0 while i < N_MOVES: print(i+1,inp) if cur_cup + 4 >= len(inp): tmp_hold = inp[cur_cup + 1:] + inp[:(cur_cup+4) % len(inp)] dc...
def pop_kwarg_nones(kwargs): """ Pops off any kwargs that are none. Yeah I know this is verbose as hell. Also, I used a separate list (pop keys) cause it's scary manipulating a list while going over it. :param kwargs: :return: """ pop_keys = [] for k in kwargs.keys(): if ...
def split_by_commas(string): """Split a string by unenclosed commas. Splits a string by commas that are not inside of: - quotes - brackets Arguments: string {String} -- String to be split. Usuall a function parameter string Examples: >>> split_by_commas('foo, bar(ba...
def catmull_rom_spline(x, y0, y1, y2, y3): """The third order polynomial p(x) with p(0)=y1, p'(0)=y2-y0, p(1)=y2, p'(1)=y3-y1.""" a3 = y3 - y2 - y0 + y1 a2 = y0 - y1 - a3 return y1 + x * (y2 - y0 + x * (a2 + x * a3))
def nce_correct_prob(y_pred, y_noise): """ p(correct| x, y) used in NCE. :param y_pred: Model distribution (p_m(y|x; \theta)) :param y_noise: Noisy distribution (p_n(y|x)) :return: Probability that a given example is predicted to be a correct training (p(correct|x, y)) """ return y_pred / (y...
def decode_dbkey( dbkey ): """ Decodes dbkey and returns tuple ( username, dbkey )""" if ':' in dbkey: return dbkey.split( ':' ) else: return None, dbkey
def iso_date2(adate): """Returns int tuple (yyyy,mm,dd) if adate is in form of 'yyyy-dd-mm' else (0,0,0)""" if type(adate) != str or len(str(adate)) !=10 : return (0,0,0) alist = adate.split('-') if len(alist) != 3: return (0,0,0) y,m,d = alist return (int(y), int(m), int(d)) if ( \ y....
def dedup(seq): """ Drop duplicate while keeping the order. ref: http://www.peterbe.com/plog/uniqifiers-benchmark """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def parse_filesystems(f_systems, tag_key, tag_val): """Parse filesystems by tag.""" tmp_fsystems = [] for f_system in f_systems: if f_system['Lifecycle'] == 'AVAILABLE': for tag in f_system['Tags']: if ((tag['Key'] == tag_key) and (tag['Value'] == tag_val)): ...
def pos_pow(z,k): """z^k if k is positive, else 0.0""" if k>=0: return z**k else: return 0.0
def get_indir_outdir(dir): """returns default output directory""" tokens = dir.split('/') dir1 = '' dir2 = '' if len(tokens[-1]) == 0: dir1 = '/'.join(tokens[:-2]) dir2 = tokens[-2] else: dir1 = '/'.join(tokens[:-1]) dir2 = tokens[-1] prefix1 = dir1 + '/' + d...
def _dic_inclusion(a, b): """checks if a is included in a (dictionnary) b (dictionnary) Returns: (bool): True if a included in b """ return all([item in b.items() for item in a.items()])
def to_bytes_literal(seq): """Prints a byte sequence as a Python bytes literal that only uses hex encoding.""" return 'b"' + "".join("\\x{:02x}".format(v) for v in seq) + '"'
def dependencies(cls): """Returns dict of dependencies of a class declared with ``@has_dependencies`` """ return getattr(cls, '__zorro_depends__', {})
def flatten(nl): """Flattens a nested list/tuple/set, returns list""" if isinstance(nl, (tuple, set)): nl = list(nl) # noinspection PySimplifyBooleanCheck if nl == []: # don't change this return nl if isinstance(nl[0], (list, tuple, set)): return flatten(list(nl)...
def filter_without_boolfilt(files, criterion, critargs): """ Return everything that doesn't match criterion. :param files: Files to work on. :type files: list(str) :param criterion: Function to use for evaluation. :type criterion: func :param critargs: Arguments for function, other than f...
def slack_link(url, text=""): """ Return a slack-formatted URL of <path|text>. """ if text: return "<%s|%s>" % (url, text) else: return "<%s>" % url
def optimal_bin_size(n): """ Is this empricially the best? """ return int(2*n**(1/3))
def _make_message_set(messages): """ Unfortunately `django.core.checks.CheckMessage` doesn't implement `__hash__()`, so sets containing them cannot be compared directly. As a workaround this makes a set containing tuples of the level and message, which are the only two attributes the tests care abou...
def hybrid_gridconnection(input_dict): """ Function to calculate total costs for transmission and distribution. Parameters ---------- <None> Returns ------- tuple First element of tuple contains a 0 or 1. 0 means no errors happened and 1 means an error happened and the ...
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) ...
def yes_or_no(input): """Convert True or False in Yes or No. Args: input (bool): True or False Returns: str: Yes for True, No for False """ if input: return 'Yes' else: return 'No'
def affine_transformation(x, y, a, b, c, d, e, f): """ perform an affine 2d transformation using the given matrix coefficients""" return x * a + y * b + e, x * c + y * d + f
def to_boto3_tags(tagdict): """ Converts tag dict to list format that can feed to boto3 functions """ return [{'Key': k, 'Value': v} for k, v in tagdict.items() if 'aws:' not in k]
def mapSqr(L): """returns the map of sqr and L""" power = 2 lst = [] # have to make a new list so old is not mutated # cannot do better for x in L: #lst += [x ** power] # faster lst.append(x ** power) return lst
def colored(fmt, fg=None, bg=None, style=None): """ Return colored string. List of colours (for fg and bg): - k: black - r: red - g: green - y: yellow - b: blue - m: magenta - c: cyan - w: white List of styles: - b...
def get_sequence_length(n_stages, n_layers_per_stage): """Summary Parameters ---------- n_stages : TYPE Description n_layers_per_stage : TYPE Description Returns ------- TYPE Description """ sequence_length = 2**n_layers_per_stage * 2 * n_stages retu...
def colname(colx): """Utility function: ``7`` => ``'H'``, ``27`` => ``'AB'``""" alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if colx <= 25: return alphabet[colx] else: xdiv26, xmod26 = divmod(colx, 26) return alphabet[xdiv26 - 1] + alphabet[xmod26]
def url_path_join(*pieces): """Join components of url into a relative url Use to prevent double slash when joining subpath. This will leave the initial and final / in place """ initial = pieces[0].startswith('/') final = pieces[-1].endswith('/') stripped = [s.strip('/') for s in pieces] ...
def resolver(schema): """Default implementation of a schema name resolver function """ name = schema.__name__ if name.endswith('Schema'): return name[:-6] or name return name
def clean_link(link_text): """ Remove leading and trailing whitespace and punctuation """ return link_text.strip("\t\r\n '\"")
def show_keys(objectt: dict) -> list: """ Returns list of keys on object. >>> show_keys(get_json('d', '1.1/friends/ids.json', '@ITreskot', '2')) ['errors'] """ return list(objectt.keys())
def binary_search(target, source): """ Binary search the position of target in the source set. """ N = len(source) start = 0 end = N-1 while (end - start) != 1: mid = start + (end - start)//2 if target <= source[mid]: end = mid else: start = mid ...
def Chebyshev( x, n ): """ Function used to compute the Chebyshev polynomials. Args: x (any): variable. n (int): polynomials order Returns: any: returns the value of the polynomials at a given order for a given variable value. Testing: Already t...
def convert_sequence_list_to_dictionary(sequence_list): """ Convert a list of sequences into a dictionary of sequences, where key is the sequence ID. """ dictionary = {} for record in sequence_list: dictionary[record.id] = record.seq return(dictionary)
def calc_sc_carter(slr, ecc, x): """ Compute carter constant for the SC case (a = 0). Parameters: slr (float): semi-latus rectum [6, inf) ecc (float): eccentricity [0, 1) x (float): inclination value given by cos(theta_inc) (0, 1] negative x -> retrograde ...
def merge_dict(d1, d2): """Merge two dictionaries maintaining values in nested dicts WARNING: This is recursive, use it wisely. """ # pylint: disable=invalid-name if isinstance(d2, dict): # pragma: NO COVER for k in d2.keys(): if d1.get(k, None) and isinstance(d1[k], dict): ...
def filterTheDict(dictObj, callback): # DGTEMP - Not useful anymore """ Function copied from https://thispointer.com/python-filter-a-dictionary-by-conditions-on-keys-or-values/ Iterate over all the key value pairs in dictionary and call the given callback function() on each pair. Items for which callback()...
def bracket(f, lower, upper, accuracy=1e-10, max_iteration=1<<10): """Find root of function within bracket limits. @param f callable (function of form f(x) = 0) @param lower float (initial lower bound) @parma upper float (initial upper bound) @param accuracy float (d...
def interval_to_errors(value, low_bound, hi_bound): """ Convert error intervals to errors :param value: central value :param low_bound: interval low bound :param hi_bound: interval high bound :return: (error minus, error plus) """ error_plus = hi_bound - value error_minus = value ...
def flatten_rf(flow): """ Flattens the Risky Flow objects into a flat dict to write to CSV. """ return { "id": flow.get("id"), "businessUnit": flow.get("businessUnit", {}).get("name"), "riskRule": flow.get("riskRule", {}).get("name"), "internalAddress": flow.get("internal...
def get_iou(bb1, bb2): """ Calculate the Intersection over Union (IoU) of two 2D bounding boxes. Parameters ---------- bb1 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : dic...
def dismember(string, markers, names=None): """Decompose string into size-limited fragments and returns them separately string: string to separate into substrings """ if markers is None: return string else: pass
def extract_domain_from_url(url): """ Removes protocol, subdomain and url path. It does not perform any validation on input parameter url :param url Full onion url as str :return domain name as str """ if '.onion' not in url: return None no_path_no_tld = url.split('.onion')[0] ...
def count_needed_for_presents(presents, counter): """Calculate needed resource needed for presents using counter function.""" return sum( counter(present) for present in presents )
def clean_state(state): """ Upper cases the state and fixes a few weird issues. """ new_state = state.upper() if state else None # NF -> NL for Newfoundland and Labrador. if new_state == "NF": new_state = "NL" # PQ -> QC for Quebec. if new_state == "PQ": new_state = "QC" ...
def select_tx_port(tx_port_id_list, rx_port_id): """ Select an IXIA port to send traffic Args: tx_port_id_list (list): IDs of ports that can send traffic rx_port_id (int): ID of the port that should receive traffic Returns: ID of the port to send traffic (int) or None (if we fa...
def fibonacci(k): """Calculate Fibonacci number Args: k (int): Which Fibonacci number Returns: int: The kth Fibonacci number """ if type(k) != int: raise TypeError("k needs to be an integer") if k < 0: raise ValueError("k needs to be positive") if k == 0: ...
def lineup_group_id_parser(lineups): """Parse GROUP_ID str into list of IDs.""" for lineup in lineups: sorted_lineup = sorted(lineup['GROUP_ID'].split(' - ')) lineup['GROUP_ID'] = sorted_lineup return lineups
def offset_component_name(component_name): """ Many components can also have an offset, as in: position/x positionOffset/c Return the appropriate name. """ x = component_name.split('/') if len(x) == 1: return x[0]+'Offset' else: return x[0]+'Offset/'+x[1...
def parts(a, b): """https://stackoverflow.com/a/52698110""" q, r = divmod(a, b) return [q + 1] * r + [q] * (b - r)
def get_device_name(device): """ Find the name of a device fetched from the project device list. Returns the device identifier if no name is explicitly given. Parameters ---------- device : dict Dictionary of device information fetched by the API. Returns ------- name : str...
def get_average(lst): """ This function is used to calculate the average of a list of float. :param lst: a list :return: a float """ sum = 0 if len(lst) != 0: for i in lst: if i is float or int: sum = sum + i average = sum / len(lst) average = round(average, 2) return average else: return None
def contextwin(l, win): """ win :: int corresponding to the size of the window given a list of indexes composing a sentence l :: array containing the word indexes it will return a list of list of indexes corresponding to context windows surrounding each word in the sentence """ assert ...
def floatRgb100(mag, cmin, cmax): """ Return a tuple of floats between 0 and 1 for the red, green and blue amplitudes. """ if mag >1 and mag <=10: mag = mag*3 elif mag >10 and mag <=50: mag = mag*3/10 + 40 elif mag >10 and mag <=50: mag =...
def buildTypeTree(cls:type) -> dict: """ Return a tree of subclasses of a class Arguments: cls (type): Class from which to return descendants Returns: dict: Dict of all subclasses Example: buildTypeTree(MainClass) returns: { MainClass.SubClass1: { MainClass.SubClass1.SubClass11: {}, MainC...
def Softsign(v): """ Softsign activation function. """ return v/(1+abs(v))
def ishl7(line): """Determines whether a *line* looks like an HL7 message. This method only does a cursory check and does not fully validate the message. :rtype: bool """ # Prevent issues if the line is empty return line and (line.strip()[:3] in ["MSH"]) or False
def hamming(text1,text2): """calculates hamming distance between 2 texts of equal length, if not equal it throws an error""" distance=0 if len(text1)!=len(text2): return "Error" else: for i in range(len(text1)): if text1[i]!=text2[i]: distance+=1 ...
def platenum_as_str(platenum): """String representation of platenumber with leading zeros if necessary. Parameters ---------- platenum : int Number of plate Returns ------- str String representation of plate number. """ return '{:06d}'.format(platenum)
def _is_s3(string): """ Checks if the given string is a s3 path. Returns a boolean. """ return string.startswith("s3://")
def is_float_or_int(value): """ Returns True if the value is a float or an int, False otherwise. :param value: :return: """ if type(value) is float: return True elif type(value) is int: return True else: return False
def determine_winner(first_throw, second_throw): """ input parameters are each a list with contents: ["throw", "phone_number"] returns a string of format "phone_number wins." """ t1 = first_throw[0] t2 = second_throw[0] if t1 == t2: response = "Tie! No winner" elif t1 == "paper"...
def assignClasses(agentSchedule, masks, classes, indexMatrix): """ assign classes to a schedule""" durr = 2 base = 10 for index in range(len(masks)): # odd vs even chair = classes[index] maskRow = indexMatrix[index] for i, val in enumerate(masks[index]): if val: ...