content
stringlengths
42
6.51k
def get_LJ_params(components, LJ_data): """Get LJ params from csv file :param components: :return: LJ params sigma and epsilon """ sigma = [] epsilon = [] for key in components: assert key in LJ_data['Substance'], 'No parameters found for {} in LJparams.csv'.format(key) inde...
def coco2pascal(box): """Convert bounding box coordinates from Coco format to Pascal VOC. Go from [x, y, width, height] to [x1, y1, x2, y2]. """ x, y, width, height = box return [x, y, x + width, y + height]
def mod_inverse_iterative(a, b): """ Helps mod_inverse work """ x, y, u, v = 0, 1, 1, 0 while a != 0: q, r = b // a, b % a m, n = x - u * q, y - v * q b, a, x, y, u, v = a, r, u, v, m, n return b, x, y
def jpeg_header_length(byte_array): """Finds the length of a jpeg header, given the jpeg data in byte array format""" result = 417 for i in range(len(byte_array) - 3): if byte_array[i] == 0xFF and byte_array[i + 1] == 0xDA: result = i + 2 break return result
def find_max_len(text): """ A linear search of the maximum length of a particular string Every string in the array is looked up by its length and consequently compared The string with the biggest length is then returned Args: text (arr[str]): array of strings that are compared Returns: str: Word with the bigg...
def check_empty_dict(GET_dict): """ Returns True if the GET querstring contains on values, but it can contain empty keys. This is better than doing not bool(request.GET) as an empty key will return True """ empty = True for k, v in GET_dict.items(): # Don't disable on p(age) or '...
def checkColor(r, g, b): """Returns color ID string for given bit.""" if r == 1: if b == 1: if g == 0: return "magenta" else: return False else: if g == 0: return "red" else: return "y...
def build_profile_name(account: int, role: str) -> str: """ Builds a profile name from an account ID and role name :param account: the account ID :param role: the role name :return: a profile name """ return f"gatech_{account:12}_{role}"
def reverse_list(head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return prev
def b2i(bstr, s = 'h'): """convert byte string to numerical array""" import struct return 'not even' if len(bstr)%2!=0 else [struct.unpack(s, bstr[2*i:2*i+2])[0] for i in range(len(bstr)//2)]
def wrap_text(text, char_limit, separator=" "): """ Split a string into a list of strings no longer than char_limit without splitting individual words. """ words = text.split(separator) lines = [] current_line = [] current_length = 0 for word in words: if len(word) + current_...
def kaldi_id_to_parts(example_id): """ ToDo: start and end >>> kaldi_id_to_parts('P28_S09_LIVING.R-0714562-0714764') {'speaker_id': 'P28', 'session_id': 'S09', 'array_id': 'P28', 'location': 'LIVING', 'channel': 'R'} >>> kaldi_id_to_parts('P28_S09_LIVING.L-0714562-0714764') {'speaker_id': 'P28'...
def default_init_params(output_min, output_max): """Returns default initialization bounds depending on layer output bounds. Args: output_min: None or minimum layer output. output_max: None or maximum layer output. """ if output_min is None and output_max is None: return 0.5, 1.5 else: return ...
def slice(seq, start, stop=None, step=None): """ Returns the start:stop:step slice of the sequence `seq`. """ return seq[start:stop:step]
def get_single_user(user_id): """add new user""" return 'get single user', 200
def ToResourceFileName(name): """Returns the resource-compatible file name for the given file.""" # Resources file names must consist of [a-z0-9_.]. # Changes extension to .lpak so that compression can be toggled separately for # locale pak files vs other pak files. return name.replace('-', '_').replace('.pak...
def binarySearchSortedArray(nums, s): """ Args: {List<int>} nums {int} s Returns: {boolean} Whether s is in nums. """ # Write your code here. beginning = 0 end = len(nums) - 1 found = False while beginning <= end and not found: mid = (beginning + end) // 2 ...
def make_tags_in_aws_format(tags): """Take a dictionary of tags and convert them into the AWS Tags format. Args: tags (dict): The tags you want applied. Basic Usage: >>> tags = {'env': 'development', 'service': 'web'} >>> make_tags_in_proper_format(tags) [ { ...
def clip_norm(g, c, n): """Ref: https://github.com/keras-team/keras/blob/7a39b6c62d43c25472b2c2476bd2a8983ae4f682/keras/optimizers.py#L21 Clip the gradient `g` if the L2 norm `n` exceeds `c`. ===================================================== @param g: (ndarray) Gradient. @param c: (float) Gr...
def clean_line(line): """ Cleans a single line of text """ ret = '' for ch in line.lower(): if ch.isalpha(): ret += ch elif ch == ' ': ret += ch elif ch in ('.', '?', '!'): ret += ch return ret.strip()
def formatConcert(day,date,venue,cost): """Pack concert information into a dictionary""" date = date.split('-') m, d, y = range(3) # MM-DD-YYYY formatted day details = ["venue", "year", "month", "date", "day", "cost"] concert = [venue, date[y], date[m], date[d], day, cost] return dict(zip(detai...
def recursive_levenshtein(string_1, string_2, len_1=None, len_2=None, offset_1=0, offset_2=0, memo=None): """ Calculates the Levenshtein distance between two strings. Usage:: >>> recursive_levenshtein('kitten', 'sitting') 3 >>> recursive_levenshtein('kitten', 'kitten') 0 ...
def ext_from_url(url): """ Get the file extension from the given URL. Looks at the last part of the URL path, and returns the string after the last dot. :param url: the URL to the file whose extension is being determined :returns: the file extension or ``None`` """ file_name = url.split("/"...
def dns_label_count(rows, args): """Returns the number of labels in a given domain (eg: www.example.com = 3)""" label = rows[args[0]] parts = label.split(".") # deal with www.exmaple.com. with a trailing dot if parts[-1] == "": return (str(len(parts)-1),'') return (str(len(parts)),'')
def _import_class(cls, minv=None): """Take a string FQP and return the imported class or identifier clas is of the form "package.module.klass" or "package.module:subobject.klass" """ import importlib if ":" in cls: mod, name = cls.rsplit(":", 1) mod = importlib.import_module(mod) f...
def is_dictable(obj): """Returns ``True`` if `obj` has a ``to_dict()`` method.""" return hasattr(obj, "to_dict")
def subtract(a: float, b: float) -> float: """ Subtract two floats. This is a very nice function that performs the following operation .. math:: c = a - b Parameters ---------- a : float First parameter b : float Second parameter Returns ------- float ...
def get_xy_from_waypoints(waypoints): """ Given a list of waypoints, returns a list of [x,y] coordinates associated with those waypoints """ return list(map(lambda waypoint: [waypoint.pose.pose.position.x, waypoint.pose.pose.position.y], waypoints))
def revert_model_name(name): """Translating display model name to model name""" if name == 'service': return 'clusterobject' elif name == 'component': return 'servicecomponent' elif name == 'provider': return 'hostprovider' else: return name
def _ports_match(protocol, module_min, module_max, rule_min, rule_max): """ Capture the complex port matching logic. The port values coming in for the module might be -1 (for ICMP), which will work only for Nova, but this is handled by sdk. Likewise, they might be None, which works for Neutron, but...
def prepare_bearer_headers(token, headers=None): """Add a `Bearer Token`_ to the request URI. Recommended method of passing bearer tokens. Authorization: Bearer h480djs93hd8 .. _`Bearer Token`: http://tools.ietf.org/html/rfc6750 """ headers = headers or {} headers['Authorization'] = 'Beare...
def filter_hostnames(hostnames, domain_filter): """ This function removes hostnames that don't match the domain_filter from the input map of hostnames=>address """ for hostname in hostnames.copy(): if domain_filter not in hostname: hostnames.pop(hostname) return hostnames
def ratio(rels, nonrels): """ expect two floats """ dem = rels + nonrels if dem > 0.0: return round((rels * rels) / dem, 2) else: return 0.0
def _normalize_names(names): """Recursively normalize, inferring upper level names for unadorned tuples. Generally, we want the field names to be organized like dtypes, as in ``(['pv', ('p', 'v')], 't')``. But we automatically infer upper field names if the list is absent from items like ``(('p', 'v')...
def map_cat_to_real_names(classes, cat_to_name): """ Maps class categories to real names Parameters: - classes: the classes (list of ids) - cat_to_name: dictionary mapping the integer encoded categories to the actual names of the flowers Returns: - labels: the class...
def merge(d1, d2): """ Merges two dictionaries, nested values are overwitten by d1 >>> d = merge({'a': 1}, {'b': 2}) >>> assert d == {'a': 1, 'b': 2} >>> d = merge({'a': {'b': 2}}, {'b': 2, 'a': {'c': 3}}) >>> assert d == {'a': {'c': 3}, 'b': 2} """ return dict(d1, **d2)
def attr_visitor_name(attr_name: str) -> str: """ Returns the visitor_method name for `attr_name`, e.g.:: >>> attr_visitor_name('class') 'attr_class' """ # assert re.match(r'\w+$', node_name) return 'attr_' + attr_name
def _get_seq(string): """ Return the input string or an empty string with np.nan. >>> _get_seq('QVQQ') 'QVQQ' >>> import numpy as np >>> _get_seq(np.nan) '' """ if isinstance(string, str): return string return ""
def _has_related_artifacts(groupId, artifactId): """ >>> _has_related_artifacts('org.mygovscot.publishing', 'publishing-deb') True >>> _has_related_artifacts('org.mygovscot.beta', 'authentication-deb') True >>> _has_related_artifacts('org.mygovscot.beta', 'web-site') False """ Beta =...
def escape_backticks(text: str) -> str: """ Replace backticks with a homoglyph to prevent codeblock and inline code breakout. Parameters ---------- text : str The text to escape. Returns ------- str The escaped text. """ return text.replace('\N{GRAVE ACCENT}', '\N...
def removeArticle(s): """Remove the article in the beginning of the given phrase""" if s.startswith("a "): return s[2:] elif s.startswith("an "): return s[3:] elif s.startswith("the "): return s[4:] return s
def bound(x, m, M): """ Bound x between m and M. Parameters ---------- x : float Value. m : float Lower bound. M : float Upper bound. """ return min(max(x, m), M)
def remove_whitespace(markdown): """Remove extra whitespace (3 line breaks).""" if '\n\n\n' in markdown: markdown = markdown.replace('\n\n\n', '\n') markdown = remove_whitespace(markdown) return markdown
def bubble_sort(numbers): """ This is the description of the function ~ Loves it2 Parameters ---------- numbers : array array to sort Returns ------- array printed array """ n = [] for x in numbers: ...
def scale_axis(axis_data, factor): """ Scale axis data by factor X (string) = factor * X Arguments: axis_data = axis to scale factor = scale factor (float) """ scaled_axis = str(float(axis_data)*factor) return scaled_axis
def dict_or_string(x): """ Property: Model.Schema """ if isinstance(x, (dict, str)): return x raise TypeError(f"Value {x} of type {type(x)} must be either dict or str")
def update_user(username, event) -> str: """ Placeholder to handle updating the given user based on the event type """ event_type = event["event"]["type"] if event_type == "escalate": message = f"Escalating user: {username}" elif event_type == "deescalate": message = f"Deescalati...
def get_dsa_constants(constants=None): """Returns (p, q, g) if constants is None, and constants otherwise. This allows you to write: ``` def function(constants=None): p, q, g = get_dsa_constants(constants) ``` instead of: ``` def function(constants=None): if constants is...
def all_true_p (seq, pred) : """Returns True if `pred` returns true for all elements of `seq`, otherwise returns first non-true element. """ for e in seq : if not pred (e) : return e else : return True
def Sphere(individual): """Sphere test objective function. F(x) = sum_{i=1}^d xi^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ return sum(x**2 for x in individual)
def find_sol(c, ws, vs, memo): """ Finds an optimal solution for the given instance of the knapsack problem with weight capacity c, item weights ws, and item values vs, provided maximum total value for subproblems are memoized in memo. """ sol = [] for n in reversed(range(len(ws))): ...
def exact_nev_noise(d=10, b=3): """ Computes the exact expectation of the similarity of t and the white noise For more details, see Proposition 1 of the paper. Args: d (int): dimensionality of the window b (int): number of bins Returns: float: the expectation "...
def maybe_unsorted(start, end): """Tells if a range is big enough to potentially be unsorted.""" return end - start > 1
def export_to_file(file_name, payload): """! Simple file dump used to store reports on disk @param file_name Report file name (with path if needed) @param payload Data to store inside file @return True if report save was successful """ result = True try: with open(file_name, 'w') as ...
def zeros(n): """Mimic np.zeros() by returning a list of zero floats of length n. """ if isinstance(n, int): if n > 0: return [0.]*n msg = "zeros() should be called with positive integer, got: %s" % n raise ValueError(msg)
def require(*modules): """Check if the given modules are already available; if not add them to the dependency list.""" deplist = [] for module in modules: try: __import__(module) except ImportError: deplist.append(module) return deplist
def calc_exposure_time(num_integrations, ramp_time): """Calculates exposure time (or photon collection duration as told by APT.) Parameters ---------- num_integrations : int Integrations per exposure. ramp_time : float Ramp time (in seconds). Returns ------- exposur...
def seqid_to_filename(seqid): """ Makes a sequence id filename friendly. (eg, replaces '|' with '_') """ return seqid.replace("|", "_")
def validate_int(number): """This function validates the numbers we get from the user before we can add them to our database""" try: int(number) except ValueError: return False else: # we will not pass a number greater than zero anywhere # in our app, so we reject zer...
def marker_source(session, Type='Int32', RepCap='', AttrID=1150065, buffsize=0, action=['Get', '']): """[Get/Set Marker Source] """ return session, Type, RepCap, AttrID, buffsize, action
def false_positive_rate(tn, fp): """Calculate the detection rate. :param tn: Number of true negatives. :param fp: Number of false positives. :return: The detection rate. """ if (fp+tn) == 0: return 0 return fp/float(fp+tn)
def convert_results_geojson(data): """ Convert results to geojson format, for writing to shapefile. Parameters ---------- data : list of dicts Contains all results ready to be written. Outputs ------- output : list of dicts A list of geojson dictionaries ready for writ...
def partition(ls, size): """ Returns a new list with elements of which is a list of certain size. >>> partition([1, 2, 3, 4], 3) [[1, 2, 3], [4]] """ return [ls[i:i + size] for i in range(0, len(ls), size)]
def strip_comment(line): """Strip from line everything after the first '#' character. If no such character is present, return line unchanged. """ i = line.find('#') return line if (i == -1) else line[:i]
def _translate_attachment_summary_view(_context, vol): """Maps keys for attachment summary view.""" d = {} storage_pool_id = vol['id'] # NOTE(justinsb): We use the storage_pool id as the id of the attachment object d['id'] = storage_pool_id d['storage_pool_id'] = storage_pool_id d['server_id'...
def version_contains_field(version, field): """ Checks if the given dictionary contains the given field. Args: version: A dictionary containing version details. field: A string representing a key path. Returns: A boolean indicating whether or not the version contains the field. """ version_fragme...
def cleaning(sentence): """ Data cleansing using the stopwords list : https://github.com/Yoast/YoastSEO.js/blob/develop/src/config/stopwords.js """ stopwords = ["a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "as", "at", "be", "because", "been", "befor...
def default_value(desc): """ Parse default out of description. :param desc: str :return: str """ subs = { 'true': True, 'false': False } if '(default' in desc: _, result = desc.split('(default ') result = result.rstrip(')') result = subs.get(result...
def _(value: bytes) -> str: """Convert ``bytes`` to ``str``""" return value.decode('utf-8')
def ftime_ns(nanoseconds, precision=2, spaced=None): """ Convert nanoseconds into a human-readable format (small units). """ # shorten the variable name to keep line length under 100 lol ns = nanoseconds if ns < 1000: if spaced is True or spaced is None: return "{ns:.{precis...
def rodframe_parameters(illusion_strength=0, difference=0): """ Compute Parameters for the Rod and Frame Illusion Parameters ---------- illusion_strength : float The strength of the frame tilt in biasing the perception of a congruently tilted rod. Specifically, the orientation of th...
def get_input_from_kvp(datainputs): """Get execute DataInputs from URL (key-value-pairs) encoding """ inputs = {} if datainputs: for inpt in datainputs.split(";"): (identifier, val) = inpt.split("=") # add input to Inputs inputs[identifier] = val retur...
def get_nested_value(json_result, keys): """Returns JSON value retrieved by following *known* keys. This function makes it easy to plumb the depths of a nested dict with using an iterable of keys and integers. It will go as deep as keys/indices exist and return None if it doesn't find one or if it...
def clean_output(text): """ Remove whitespace and newline characters from input text.""" return text.replace('\n', '')
def get_daily_rate(target_count, cycle_minutes): """Get daily rate of emails sent.""" cycle_days = cycle_minutes / (60 * 24) return target_count / cycle_days
def fibonacci_no_branch(n, value = 1, previous = 0): """ @ref https://stackoverflow.com/questions/47871051/big-o-time-complexity-for-this-recursive-fibonacci """ if (n == 0 or n == 1): return previous if (n == 2): return value return fibonacci_no_branch(n - 1, value + previous,...
def track_nformants(track): """Gets the number of formants used to arrive at a given track. Parameters ---------- track : dict The measured track. Returns ------- int The number of formants used to measure that track """ numbers = set(int(x[1]) for x in track.keys()...
def decode_slice(slc): """decode a slice object as sent to __getitem__. takes into account the 2.5 __index__() method, basically. """ ret = [] for x in slc.start, slc.stop, slc.step: if hasattr(x, '__index__'): x = x.__index__() ret.append(x) return tuple(ret)
def normal_to_snake_case(text: str) -> str: """Convert from normal to snake_case.""" return text.lower().replace(" ", "_")
def grade(value): """ Returns a string based grade from a number. 1: Good 2: Fair 3: Fair 4: Poor """ if value == 1: return 'good' if value == 2 or value == 3: return 'fair' if value == 4: return 'poor'
def dict_list_to_str(dict_list): """ parses a list of dictionaries into a string representation """ if not dict_list: return '' string_list = [] for dict in dict_list: key_values = ["{}: {}".format(k, v) for k, v in dict.items()] string_list.append(', '.join(key_values)...
def permutations(nums): """Given a list, return all the possible orderings in an array. 3 ingredients to Backtracking: 1. Goal - fill up a permutation 2. choices - unused values of nums 3. constraint - values that are already used """ def find_permutations(current, remaining, fo...
def returnstringpacket(pkt): """Returns a packet as hex string""" myString = "" for c in pkt: myString += "%02x" % c return myString
def energy_value(h, J, sol): """ Obtain energy of an Ising solution for a given Ising problem (h,J). :param h: (dict) External magnetic term of the Ising problem. :param J: (dict) Interaction terms of the Ising problem (may be k-local). :param sol: (list) Ising solution. :return: Energy of the ...
def channels_first_to_last(shape): """Given a shape with channels first, returns a shape with channels last. Assumes we're dealing with the standard shapes as used by [TF's convolution operators][1]. [1]: https://www.tensorflow.org/api_docs/python/tf/nn/convolution Args: shape: A sequence with each ele...
def newtonraphson(f, f_, x0, TOL=0.001, NMAX=100): """ Takes a function f, its derivative f_, initial value x0, tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the newton-raphson method. """ n=1 while n<=NMAX: x1 = ...
def parseopts(opts): """ parses the command-line flags and options passed to the script """ params = { 'format': 'bed' } for opt, arg in opts: if opt in ["--input"]: params['inputfile'] = arg elif opt in ["--format"]: params['format'] = arg elif o...
def dec2gon(dec): """ Converts Decimal Degrees to Gradians :param dec: Decimal Degrees :type dec: float :return: Gradians :rtype: float """ return 10/9 * dec
def reduce(function, iterable, **attr): """ Args: function: iterable: **attr: """ if iterable: it = iter(iterable) value = next(it) for element in it: value = function(value, element, **attr) return value else: return None
def align_position2doc_spans(positions, doc_spans_indices, offset=0, default_value=-1, all_in_span=True): """Align original positions to the corresponding document span positions Parameters ---------- positions: list or int A single or a list of positions to be alig...
def merge_breakpoint_records(records_l, records_r): """ Merge records found on both the left and the right breakpoints. If a read or its paired end overlaps both breakpoints, then choose the lesser of the two alignments to represent the read (lesser by furthest distance from the reference or contig it b...
def intersects(line_seg_a, line_seg_b): """ Checks whether two line segments intersect. Parameters ---------- line_seg_a: [x1, y1], [x2, y2] details of first line segment. line_seg_b: [x1, y1], [x2, y2] details of second line segment. Returns ---------- boolean ...
def lower_utf8(phrase): """Receive string and return utf-8 string lowered""" return phrase.lower().encode('utf-8')
def diff2(arr): """Luisho5 on CodeWars solutions.""" r = 0 c = '' for i in arr: y = i.split('-') s = abs(int(y[0]) - int(y[1])) if s > r: r = s c = i if r == 0: return False return c
def flatten(lst): """ Return a list where all elemts are items. Any encountered iterable will be expanded. Method is recursive. """ result = [] for x in lst: if isinstance(x, (tuple, list)): for y in flatten(x): result.append(y) else: if x is ...
def _parse_text(value): """Default coercion function which assumes text is UTF-8 encoded""" return value.decode('utf-8')
def hamming_distance(seq1, seq2): """Return the Hamming distance between equal-length sequences """ if len(seq1) != len(seq2): raise ValueError("Undefined for sequences of unequal length.") return sum(bp1 != bp2 for bp1, bp2 in zip(seq1, seq2))
def dropSpans(matches, text): """Drop from text the blocks identified in matches""" matches.sort() res = '' start = 0 for s, e in matches: res += text[start:s] start = e res += text[start:] return res
def extractIdFromUrl(url): """Parse |url| hoping to get a spreadsheet id.""" if not url: return 0 return url.split('?key=')[1].split('&')[0].split('#')[0]
def numerize_key(key: str) -> int: """ Blackbox function for generating some big number from str. Examples: * ``numerize_key('LoremIpsum')`` -> ``7406395466880`` * ``numerize_key('LoremIpsumDolorSitAmet')`` -> ``69127628581563401652806784`` Notes: In case you are really wonderi...