content
stringlengths
42
6.51k
def Catch(X,Tolerance=0): """Forces continuous values into bins at 0, .5, and 1""" if X < (.5-(Tolerance/2)): return(0) elif X > (.5+(Tolerance/2)): return(1) else: return(.5)
def add_slim_to_term(term, slim_terms): """Checks the list of ancestor terms to see if any are slim_terms and if so adds the slim_term to the term in slim_term slot for now checking both closure and closure_with_develops_from but consider having only single 'ancestor' list """ slimt...
def firstMissingPositive(nums): """ :type nums: List[int] :rtype: int """ # Method 1: Changing array values # mark those elements who aren't in the range of [1, n] n = len(nums) for i in range(n): if nums[i] <= 0 or nums[i] > n: nums[i] = n + 1 # mark vi...
def uvicorn_options_custom(logging_conf_dict: dict) -> dict: """Return custom options used by `uvicorn.run()` for use in test assertions.""" return dict( host="0.0.0.0", port=80, log_config=logging_conf_dict, log_level="debug", reload=True, reload_delay=0.5, ...
def predict(score): """El score es continuo, pero la prediccion es 1 o -1. Ponemos +-0.9 como threshold ya que usamos tanh como activacion""" if score >= 0.9: return 1 elif score <= -0.9: return -1 else: return score
def decode_val(val_text, hexnum): """ Decode tile value text to its numerical equvalent. @param val_text: Value text to decode. @type val_text: C{str} @param hexnum: Value is a hexadecimal number. @type hexnum: C{bool} @return: Its numeric value if it can be decoded, C{None} if it canno...
def get_pyramid_index(row, col): """Get a cell index from the pyramid array row 0 = top row col 0 = left-most column """ row_offset = (row * (row + 1)) / 2 index = row_offset + col return index
def radtodeg(rad): """ Function that converts radians to degrees """ return rad * (180/3.14159)
def filter_techniques_by_platform(tech_list, platforms): """Given a technique lsit and a platforms list, filter out techniques that are not part of the platforms """ if not platforms: return tech_list filtered_list = [] # Map to easily find objs and avoid duplicates ids_for_dupl...
def part1(data): """ >>> part1([16,1,2,0,4,2,7,1,2,14]) 37 >>> part1(read_input()) 352997 """ options = range(min(data), max(data) + 1) return min(sum(abs(option - crab) for crab in data) for option in options)
def invert_injective(d): """ invert a one-to-one map d """ inv = {} for k in d: if d[k] in inv: raise RuntimeError('not an injective map') inv[d[k]] = k return inv
def split(s, d=None): """Splits a string. :Parameters: s : str or unicode String to split. d : str or unicode Optional delimiter. Any white-char by default. :return: A list of words or ``[]`` if the string was empty. :rtype: list of str or unicode :note: This function ...
def _SitecustomizeRemovalEntry(is_prebuilt_image): """Returns a Dockerfile entry that removes `sitecustomize` if it's Vertex AI Training pre-built container images.""" return "RUN rm -rf /var/sitecustomize" if is_prebuilt_image else ""
def choices_to_list(choices): """Helper function that transforms choices dict to an ordered string list. Numeric values are sorted and placed after string values. :param dict choices: The dict containing available choices. :rtype: list[str] >>> choices_to_list({0: 0, 1: 1, 2: 2, "foo": 2}) ['f...
def get_last_data_idx(productions): """ Find index of the last production :param productions: list of 24 production dict objects :return: (int) index of the newest data or -1 if no data (empty day) """ for i in range(len(productions)): if productions[i]['total'] < 1000: retur...
def RetrieveValue(Dictionary, IndexPath): """ WARNING: This function is for internal use. Enter dictionary recursively using IndexPath and return leaf value. """ if IndexPath == []: return Dictionary else: return RetrieveValue(Dictionary[IndexPath[0]], IndexPath[1:])
def convert_units(props, conversion_dict): """Converts dictionary of properties to the desired units. Args: props (dict): dictionary containing the properties of interest. conversion_dict (dict): constants to convert. Returns: props (dict): dictionary with properties converted. ...
def main(argv): """ Get argument from command line. :param argv: :return: """ inputfile = "coincidences.txt" if argv: inputfile=argv[0] return inputfile
def octetsToHex(octets): """ convert a string of octets to a string of hex digits """ result = '' while octets: byte = octets[0] octets = octets[1:] result += "%.2x" % byte return result
def binarySearch(alist, item): """ to use this function you must have a sorted array/list. """ firstIndex = 0 lastIndex = len(alist)-1 found = False while firstIndex<=lastIndex: midIndex = (firstIndex+lastIndex)//2 if alist[midIndex] == item: found = True ...
def _parse_booktitle(booktitle): """ :param booktitle: entry book title """ if booktitle: if "," in booktitle: bt = booktitle.split(",") booktitle = bt[1].strip() + " " + bt[0].strip() return booktitle return None
def _set_params_noise( actor, states, noise_delta=0.2, tol=1e-3, max_steps=1000 ): """ Perturbs parameters of the policy represented by the actor network. Binary search is employed to find the appropriate magnitude of the noise corresponding to the desired distance measure (noise_delta) between ...
def partial_difference_quotient(f, points, v, i, h): """compute the ith partial difference quotient of function f w.r.t to ith position of v""" #add h to just the ith element of v w = [v_j + (h if j == i else 0) for j, v_j in enumerate(v)] return (f(points, w[0], w[1]) - f(points, v[0]...
def set_to_delete(set_list): """ Return the set to delete given a list of sets. It keeps the first element of the set. >>> set_to_delete([{1, 2, 3}, {4, 5}]) # it keeps 1 and 4 {2, 3, 5} """ return {element for group in set_list for element in list(group)[1:]}
def remove_prefix(text: str, prefix: str) -> str: """ Removes a prefix if one is present in the input text Args: text (str): The input text to remove the prefix from prefix (str): The prefix that has to be removed Returns: str: The original string if no prefix is found, or the ...
def wave(methodcnt): # NOTE - INSTANTIATE WITH SPECIAL CASE """global setup_bool # initial bootup if (setup_bool == False or methodcnt == False): setup_bool = True else:""" print ("waving") # react_with_sound(confirmation_final) return 0
def _cross_correlations(n_states): """Returns list of crosscorrelations Args: n_states: number of local states Returns: list of tuples for crosscorrelations >>> l = _cross_correlations(3) >>> assert l == [(0, 1), (0, 2), (1, 2)] """ l = range(n_states) cross_corr = [[(...
def ordinal(n): """Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc. :param int n: the index to be translated. :return: (*str*) -- Ordinal. """ ord_dict = {1: "st", 2: "nd", 3: "rd"} return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, "th")
def all_bases_valid(seq): """Confirm that the sequence contains only bases""" valid_bases = ['a', 'A', 'c', 'C', 'g', 'G', 't', 'T', 'N'] for base in seq: if base not in valid_bases: return False return True
def is_valid_format_url(format_url): """ Ensure that the given URL has the required format keys for use as a format URL. Parameters ---------- format_url : str Returns ------- bool """ components = [ "image_base", "{depth}", "{zoom_level}", "{row...
def count_single_level(num_container, num_children): """ Helper function to calculate the number of children bags for a single layer deep, i.e. ignoring the descendents of the children bags. Example -------- A single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it...
def GPMtoLPS(Vgpm): """ Convertie le debit volumique en gpm vers l/sec Conversion: 3.7854118 l = 1 gallon :param Vgpm: Debit volumique [gpm] :return Vlps: Debit volumique [l/sec] """ Vlps = Vgpm * 3.7854118 / 60 return Vlps
def length_scale(name): """Get length scale associated with units. Args: name (str): Units of length, e.g., "m", "meter", "km", "kilometer", "ft", "feet". Returns: Length of unit in meters. """ value = 1.0 if name in ["m", "meter", "meters"]: value = 1.0 ...
def show_graph(ticker): """ Displays the graph based on ticker :param ticker: the ticker :return: two dicts setting visibility of graph and sentiment information """ if not ticker: return { 'display':'none' },{'display':'none'} else: return { ...
def ComplementIntervalls(intervalls, first=None, last=None): """complement a list of intervalls with intervalls not in list. """ if not intervalls: if first and last: return [(first, last)] else: return [] new_intervalls = [] intervalls.sort() last_...
def piece_size_ratio(treatment_type, cover_type, piece_size_ratios): """ Returns piece size ratio. Assume Action.is_harvest in [0, 1, 2, 3] Assume cover_type in ['r', 'm', 'f'] Return vr/vp ratio, where vr is mean piece size of harvested stems, and vp is mean piece size of stand before h...
def soma_elementos(lista): """ Recebe inteiros e devolve um inteiro correspondente a soma dos elementos da lista. >>> soma_elementos([1, 2, 4]) 7 :param lista: :return: """ soma = 0 for i in lista: soma += i return soma
def buildEdgeDict(faces): """ Arguments: faces ([[vIdx, ...], ...]): A face representation Returns: {vIdx: [vIdx, ...]}: A dictionary keyed from a vert index whose values are adjacent edges """ edgeDict = {} for face in faces: for f in range(len(face)): ff = edgeDict.setdefault(face[f-1],...
def create_indices(dims): """Create lists of indices""" return [range(1,dim+1) for dim in dims]
def find_unique_lengths(inputs: dict) -> set: """ Given a dictionary, return a set of integers representing the unique lengths of the input strings """ return set([len(str(s)) for s in inputs])
def parse_session_list(session_str: str) -> list: """ Moderate = Old World, Colony01 = New World :param session_str: :return: """ session_list = [session.strip() for session in session_str.split(';')] return session_list
def sum_digits(y): """Sum all the digits of y. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ total = 0 while y: ...
def prepend(name, prefix): """ @brief Prepends prefix to file name. @param name The full path to the file @param prefix The prefix to prepend to the file name @return Path to file with new name. """ new_name = name.split("/") new_name[-1] = prefix + new_name[-1] ...
def FormatClassToJava(input): """ Transoform a typical xml format class into java format :param input: the input class name :rtype: string """ return "L" + input.replace(".", "/") + ";"
def dictget(dictionary, key): """ Gets the value from the given dictionary for the given key and returns an empty string if the key is not found. """ return dictionary.get(key, '')
def check_answer(guess, answer, turns): """Checks answer against guess. Returns the number of turns remaining.""" if guess > answer: print("Too high.") return turns - 1 elif guess < answer: print("Too low.") return turns - 1 else: print(f"You got it! The answer wa...
def contains_matches(to_search): """There are better ways to do this, but this will work for now.""" match1 = 'Python' match2 = 'python' if (match1 in to_search) or (match2 in to_search): return True else: return False
def _clean_input(id): """Cleans the char id""" if type(id) is int: id = abs(id) return id
def extract_xml_tags(xml_tag_name, node, allow_none=True): """Helper to extract xml tags from xmltodict. Parameters ---------- xml_tag_name : str Name of the xml tag to extract from the node. node : object Node object returned by ``xmltodict`` from which ``xml_tag_name`` sh...
def split_cfe_idx(idx): """ split cfe index into tem/ccc/rc/fe tuple """ return (idx/(12*4*4), (idx/(12*4))%4, (idx/12)%4, idx%12)
def typematch(variable, expectedtype): """ Check if a variable is a specific type :type variable: variable :param variable: The variable to check the type of :type expectedtype: type :param expectedtype: The type to check against >>> typematch(True, bool) True >>> typematch("foo"...
def create_message(scraped_data): """ A simple function that creates the message to be sent in an email if the conditions are met.""" message = "" for dic in scraped_data: if dic["in_stock"] and dic["deal"]: line = f"The item sold by {dic['seller']} is on sale for {dic['price']} eur...
def get_final_api_endpoint(start_endpoint, is_foldersync_format): """ Take an endpoint and convert to the right endpoint depending file format :param start_endpoint: :return: """ new_endpoint = False if (start_endpoint.__contains__("/api/v1/apps/import")): new_endpoint = True els...
def make_sortkey(full_name, searchkey=False): """ Algorythm inspired by W. Sage J. Chem. Inf: Comput. Sci. 1983, 23, 186-197 """ keylist = [] full_name = ''.join(e for e in full_name if e not in ('{}()[],')) full_name = full_name.split(' ') rest = " " + ' '.join(full_name[1:]) full_name ...
def wkhtmltopdf_args_mapping(data): """ fix our names to wkhtmltopdf's args """ mapping = { 'cookies': 'cookie', 'custom-headers': 'custom-header', 'run-scripts': 'run-script' } return {mapping.get(k, k): v for k, v in data.items()}
def _fuel_remaining_percentage_supported(data): """Determine if fuel remaining percentage is supported.""" return (not data["isElectric"]) and ( data["status"]["fuelRemainingPercent"] is not None )
def snrconv( snr0: float, r0: float, rcs0: float, r: float, rcs: float ): """ Signal-to-noise ratio (SNR) from reference. Inputs: - snr0 [float]: Reference SNR - r0 [float]: Reference range (m) - rcs0 [float]: Reference radar cross section (m^2) - r [float]: ...
def split_array(csv_data): """ Split array by empty lines """ data_blocks = [] offsets = [] current_block = None for ofset, line in enumerate(csv_data): if sum(map(len, line)) > 0: if current_block is None: offsets.append(ofset) data_blocks.append([]) current_block = len(data...
def _extended_gcd(a, b): """Returns (g, x, y) such that a*x + b*y = g = gcd(a, b)""" x, x_old, y, y_old = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y, y_old = y_old, y - q * y_old x, x_old = x_old, x - q * x_old return b, x, y
def _human_size(size_bytes): """ format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB Note that bytes will be reported in whole numbers but KB and above will have greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc """ UNIT_SIZE = 1000.0 suffixes_table = [('B'...
def item_sum(seq, name): """Return the sum of an iterable by attribute or key""" if seq and isinstance(seq[0], dict): return sum(i[name] for i in seq) return sum(getattr(i, name) for i in seq)
def most_common_v1(lst): """Great way to find return the most common item in a list. Unfortunately, the result is unpredictable in case of a tie. This can be avoided by using the Counter function in the collections module. Args: lst (list): The list to seach in for the most common item. Returns: The most co...
def convert(number): """Convert a number into a string that contains raindrop sounds corresponding to certain potential factors""" if number % 3 == 0: if number % 5 == 0: if number % 7 == 0: return "PlingPlangPlong" else: return "PlingPlang" ...
def get_dataset_location(bq): """Parse payload for dataset location""" # Default BQ location to EU, as that's where we prefer our datasets location = "EU" # ... but the payload knows best if "location" in bq: location = bq["location"] return location
def is_iterable(v): """Tells whether the thing is an iterable. NB: strings do not count even on Py3. """ return hasattr(v, '__iter__') and not isinstance(v, str)
def max_raw_frequency(terms): """ terms = [['a', 5], ['b', 7], ['c', 3]] maximum_raw_frequency(terms) => returns 7 """ max = 0 for term, frequency in terms: if frequency > max: max = frequency return max
def populate_songs_table(db_session, album_id, l): """Save the list of songs in the songs table.""" if not l: # list is empty return False c = db_session.cursor() c.execute("""DELETE FROM songs WHERE album_id = ?""", [album_id]) for song_list in l: c.execute("""INSERT INTO songs (alb...
def _abc_classify_customer(percentage): """Apply an ABC classification to each customer based on its ranked percentage revenue contribution. Args: percentage (float): Cumulative percentage of ranked revenue Returns: segments: Pandas DataFrame """ if 0 < percentage <= 80: r...
def get_commit_id(results): """ gets the commitId :param result: :return: """ #print("Here's the commitId"+ str(results["element"][0].get('commitId'))) return results["elements"][0].get('_commitId')
def strip_backslashes(input_string: str) -> str: """ >>> strip_backslashes(r'\\test\\\\') 'test' """ input_string = input_string.strip("\\") return input_string
def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ...
def isnonnumeric(x): """ Return True if x looks to be non-numeric """ try: x = float(x) except ValueError: return True return False
def url_path_join(*pieces): """ Duplicated from Jupyter Server """ initial = pieces[0].startswith('/') final = pieces[-1].endswith('/') stripped = [s.strip('/') for s in pieces] result = '/'.join(s for s in stripped if s) if initial: result = '/' + result if final: result = result + ...
def make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if...
def _remove_namespace_prefix(value: str) -> str: """Returns the string without the 'namespace:' prefix.""" delim = value.find(':') return value[delim + 1:]
def _create_index_cql(key_space: str, index_name: str, table_name: str, index_on: str ) -> str: """ This is general function to create Index CQL Query """ cql_index = "CREATE INDEX " + index_name + " ON " ...
def average_pair(array, target): """ Time: O(n) Space: O(n) Returns true if there is a pair of numbers in the array that when averaged are equal to the target. False otherwise :param array: positive or negative int or floats :param target: positive or negative int or float :return: Bool ...
def tuple_setitem(data, item, value): """Implement `tuple_setitem`.""" return tuple(value if i == item else x for i, x in enumerate(data))
def special_methods_callback(app, what, name, obj, skip, options): """ Enable documenting 'special methods' using the autodoc_ extension. Refer to :func:`enable_special_methods()` to enable the use of this function (you probably don't want to call :func:`special_methods_callback()` directly). Th...
def adjust_score(raw_score, komi, handicap_compensation='no', handicap=0): """Adjust an area score for komi and handicap. raw_score -- int (black points minus white points) komi -- int or float handicap_compensation -- 'no' (default), 'short', or 'full'. handicap ...
def argmax(list, score_func=None): """ If a score function is provided, the element with the highest score AND the score is returned. If not, the index of highest element in the list is returned. If the list is empty, None is returned. """ if len(list) == 0: return None scores = list...
def _box_weighting_function(x: float) -> float: """Box filter's weighting function. For more information about the Box filter, see `Box <https://legacy.imagemagick.org/Usage/filter/#box>`_. Args: x (float): distance to source pixel. Returns: float: weight on the source pixel. ...
def isNestedDict(dictionary): """ Checks if a dictionary contains subdictionaries. Args: dictionary (`dict`): dictionary to check Returns: `bool` """ if not isinstance(dictionary, dict): raise ValueError('isNestedDict: No dict given') for key in dictionary.keys():...
def params(method, nonce, **kwargs): """Represent a set of parameters for a Trade request. Keyword arguments: method -- TAPI method name Other arguments are optional. """ parameters = kwargs # Random (but incremental) number for request. nonce = str(nonce) # Dict with params ...
def comma_separated_positions(text): """ Start and end positions of comma separated text items. Commas and trailing spaces should not be included. >>> comma_separated_positions("ABC, 2,3") [(0, 3), (5, 6), (7, 8)] """ chunks = [] start = 0 end = 0 for item in text.split(","): ...
def map_genders(wikidata_gender): """ Maps those genders from Wikidata to succinct versions. """ if wikidata_gender in ["masculine", "Q499327"]: return "M" elif wikidata_gender in ["feminine", "Q1775415"]: return "F" else: return ""
def swap(state): """ swap: Perform the swap action. :param state: 1D array (list) of the current players hand. :return: new 1D array after performing the swap """ state.sort() return [int(state[1] / 2), int(state[1] / 2)]
def significant(n): """Check if value is significantly greater than 0.""" return (n < -1e-10 or n > 1e-10)
def is_palindrome(num: int) -> bool: """Checks if a number is a palindrome.""" return str(num) == str(num)[::-1]
def _write_surx(parameters): """Write surface complexes.""" out = [] if not ("surface_complexes" in parameters and parameters["surface_complexes"]): return out for complex_ in parameters["surface_complexes"]: out += [f"{complex_:<20}"] return out
def filter_paths(paths, filters): """Filters a list of paths so it only contains paths containing all of the given filters. Used by get_paths_to_images. ## Example ```python import medpicpy as med paths = ["data/ID-001/PRONE/1.dcm", "data/ID-001/SUPINE/1.dcm", "data/ID-002/PRONE/1.dcm", "da...
def _default_model(klass): """ Default model for unhandled classes. :param klass: A class. :return: Tuple of (model dictionary, further classes to process). """ return (None, set())
def parse_info_field(field): """ Parses a vcf info field in to a dictionary Args: field (str): info field from vcf Returns: Dict: {name:[val1, val2]} """ d = {} for entry in field.split(";"): try: key, value = entry.split("=") d[key] = value.split(...
def count_csv_files(files_string): """Count number of DataStream CSV files in census tract Parses a string of CSV file paths to determine how many individual files there are. Args: files_string (string): single string of file paths separated by commas Returns: counts (int)...
def convert_str_list(my_string): """ Function to convert from string to list. The create_set() function requires a specific input. Parameters ---------- my_string : str Input string. Returns ------- list The input string converted to list. """ return my_str...
def convert_uint16_to_array(value): """ Convert a number into an array of 2 bytes (LSB). """ return [ (value >> 0 & 0xFF), (value >> 8 & 0xFF) ]
def group_by_pred(pred, iterable): """Splits items in a sequence into two lists, one containing items matching the predicate, and another containing those that do not.""" is_true, is_false = [], [] for item in iterable: if pred(item): is_true.append(item) else: ...
def _unite_first_with_all_intersecting_elements(indices): """Helper function to bundle overlapping indices. Args: indices (list): A list lists with indices. """ first = set(indices[0]) new_first = first new_others = [] for idx in indices[1:]: if len(first.intersection(idx))...
def merge_dicts(*dict_args): """Merge two dictionnary. Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def M_to_D(M): """Parabolic anomaly from mean anomaly. Parameters ---------- M : float Mean anomaly in radians. Returns ------- D : float Parabolic anomaly. Notes ----- This uses the analytical solution of Barker's equation from [5]_. """ B = 3.0 * M / 2.0...