content
stringlengths
42
6.51k
def get_car_info_api(car_name: str, car_year: str) -> str: """Return the car info as gotten by an API""" return f"The {car_name} was manufactured in {car_year}"
def shout(word): """Return a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + '!!!' # Replace print with return return(shout_word)
def CSVformat(str_in): """ removes certain characters from fields returned by Jira requests, in order to facilitate insertion into SQL tables would need to be written differently for a production application, to handle escape characters etc. more intelligently parameters: str_in (string): the string from Jira that needs characters removed returns: string: the string with characters removed """ str_out = str(str_in).strip().replace(",", "\\,") return str_out
def to_padded_string(number, padding=None, decimals=None): """ Given a number object, converts that to a string. For non-natural numbers, we can optionally set the number of decimals to round to and print out. If a padding value is given, prefixes with enough spaces to make the final string at least as long as padding. """ if decimals is not None: number = round(float(number), decimals) if decimals is 0: number = int(number) string = str(number) if decimals: if '.' not in string: string += '.' decimals_length = len(string[string.index('.') + 1:]) zero_length = decimals - decimals_length string += '0' * zero_length if padding is not None and len(string) < padding: pad_length = padding - len(string) string = (' ' * pad_length) + string return string
def indent_string(string, indent=' ', include_first=True, include_last=False): """ Indent a string by adding indent after each newline. :param string: The string to indent :param indent: The string to use as indentation :param include_first: Also indent the first line of the string (before the first newline) :param include_last: If the string ends on a newline, also add an indent after that. :return: A new string. """ base = string.replace('\n', '\n' + indent) if include_first: base = indent + base if not include_last and base.endswith('\n' + indent): base = base[:-len(indent)] return base
def symbols(el): """Map words of operators to symbols of operators. Arguments: el {str} -- word of operator Returns: str -- symbol of operator """ el_lower = el.lower() if el_lower == "and": return "&" elif el_lower == "or": return "|" elif el_lower == "xor": return "^" elif el_lower == "possible": return "<>" elif el_lower == "necessary": return "[]" elif el_lower == "not": return "~" elif el_lower == "if": return "->" elif el_lower == "iff": return "<->" else: return el
def myfuncPrimeFactors(n): """ This function finds and returns the prime factorization of a whole number (excluding zero) via the reiterative division method. Example of usage: getPrimeFactors = myfuncPrimeFactors( 716 ) print(getPrimeFactors) """ i = 2 factors = [] while n != 1: if (n % i == 0): factors = factors + [i] n = n//i else: i = i+1 return factors
def instancesNaked(unit,values): """Find all the instances of naked twins in a unit Args: unit: a unit defining a set of boxes in the model values(dict): a dictionary of the form {'box_name': '123456789', ...} Returns: an array of tuples with all the naked twin instances in the unit in format [((box1,box2),value),...] """ # Store boxes with two digits in array twoDigits = [(box, values[box]) for box in unit if len(values[box]) == 2] toRemove = [] for i in range(0, len(twoDigits) - 1): for j in range(i + 1, len(twoDigits)): if twoDigits[i][1] == twoDigits[j][1]: # Store couples of boxes with the same value and the value in format [((box1,box2),value)] toRemove += [((twoDigits[i][0], twoDigits[j][0]), twoDigits[i][1])] return toRemove
def extract(string: str, start: int, len_: int) -> str: """Extract a section of a certain length from a string. Args: string (str): The string to extract from. start (int): How many chars to move forward. len_ (int): The amount of chars to extract. Returns: str: The extracted string. """ start -= 1 return string[start : start + len_].strip()
def factorial(n, show=False): """ -> Executa um calculo de fatorial :param n: Recebe o numero do fatorial a ser calculado. :param show=False: Por padrao false mas se for True mostra o processo de calculo. :param return: Retorna o valor calculado """ print(30 * '-') f = 1 for c in range(n, 0, -1): if show: print(c, end='') if c > 1: print(' x ', end='') else: print(' = ', end='') f *= c return f
def full_frame(flag=True): """When this flag is True, the related constraint should be applied if is_full_frame(SUBARRAY) is True. Returns "F" or False. >>> full_frame(True) 'F' >>> full_frame(False) False """ return "F" if flag else False
def debom(string): """Strip BOM from strings.""" return string.encode("utf-8").decode("utf-8-sig")
def codons(rna): """ Splits rna into codons. Args: rna (str): RNA string. Returns: list: codons. """ return [rna[index:index+3] for index in range(0, len(rna), 3) if len(rna[index:index+3]) == 3]
def to_list(x): """ Return x if it is already a list, or return a list containing x if x is a scalar. """ if isinstance(x, (list, tuple)): return x # Already a list, so just return it. return [x]
def check_agents_are_known(configuration): """ Checks if all keys of the configuration "structure" are defined in the "agents" section :param configuration: the object group to look at :return: if all agents are well defined """ known_agents = configuration["agents"] known_agents_id = [agent["id"] for agent in known_agents] agents_list = configuration["structure"].keys() for agent in agents_list: if agent not in known_agents_id: return False return True
def string_mappings(mapping_list): """Make a string out of the mapping list""" details = '' if mapping_list: details = '"' + str(mapping_list) + '"' return details
def genericTypeValidator(value, typ): """ Generic. (Added at version 2.) """ return isinstance(value, typ)
def _convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import") line = line.replace("QtWidgets.QApplication.translate", "Qt.QtCompat.translate") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
def _write_categories(categories_list): """ Parameters ---------- categories_list : list of str the list of category's names Returns ------- the categories' dictionary """ # create an empty categories' dictionary categories_dict = {"categories": []} for id, category in enumerate(categories_list): category_dict = {"id": id + 1, "name": category, "supercategory": category} categories_dict["categories"].append(category_dict) return categories_dict
def selection_sort(lst): """Perform an in-place selection sort on a list. params: lst: list to sort returns: lst: passed in sequence in sorted order """ if not isinstance(lst, list): raise TypeError('Sequence to be sorted must be list type.') for i in range(len(lst) - 1): min_idx = i + 1 for j in range(min_idx, len(lst)): if lst[j] < lst[min_idx]: min_idx = j if lst[min_idx] < lst[i]: lst[i], lst[min_idx] = lst[min_idx], lst[i] return lst
def get_iname_tag(image_name): """ return tuple with image name and tag """ if ":" in image_name: iname, tag = image_name.split(":") else: iname, tag = image_name, "latest" return iname, tag
def label_blockstructures(blockstructures): """Conversion between long-hand and short-hand for MTL block structures. """ conversion = { 'trueshare' : 'I', 'mhushare' : 'Y', 'split' : 'V', 'attenshare' : 'W', } labels = [] for blockstructure in blockstructures: labels.append(conversion[blockstructure]) return ''.join(labels)
def as_list(list_data): """Prints a list as html. """ return { 'list': list_data, }
def bind_question_text_alternatives(question): """Bind question text with each alternative in one single string variable. :param question: :return [string] merged_question_text: """ s = question["question_text"] for alternative in question["options"]: s = s + " " + alternative["text"] return s
def returnMaxAcreage(fire_data): """ return maximum acreage """ fire_max = 0 for fire in fire_data: if fire["properties"]["ACRES"] >= fire_max: fire_max = fire["properties"]["ACRES"] return fire_max
def color_contrast_ratio(fore_color, back_color): """Calculated the contrast ratio between a foreground color (with optional alpha) and a background color. Args: fore_color: Color in the form of rgb [r,g,b] or rgba [r,g,b,a] back_color: Color in the form of rgb [r,g,b] or rgba [r,g,b,a] Returns: Contrast ratio between the two colors """ def _calculate_luminance(color_code): """Helper function to calculate luminance for one channel of rgb""" index = float(color_code) / 255 if index < 0.03928: return index / 12.92 else: return ((index + 0.055) / 1.055) ** 2.4 def _calculate_relative_luminance(rgb): """Helper function to calculate luminance for all channels of rgb""" return 0.2126 * _calculate_luminance(rgb[0]) + \ 0.7152 * _calculate_luminance(rgb[1]) + \ 0.0722 * _calculate_luminance(rgb[2]) # find which color is lighter/darker light = back_color if sum(back_color[0:3]) >= sum( fore_color[0:3]) else fore_color dark = back_color if sum(back_color[0:3]) < sum( fore_color[0:3]) else fore_color # compute contrast ratio contrast_ratio = (_calculate_relative_luminance(light) + 0.05) / \ (_calculate_relative_luminance(dark) + 0.05) # Scale by the transparency of the el # contrast_ratio - 1 brings the color contrast range to [0, 20] so # that multiplying the contrast ratio by a decimal alpha won't result # in a contrast ratio < 1 (which is impossible) if len(fore_color) == 4: contrast_ratio = float(fore_color[3]) * (contrast_ratio - 1) + 1 return contrast_ratio
def bisect(f, lo=0, hi=None, eps=1e-9): """ Returns a value x such that f(x) is true. Based on the values of f at lo and hi. Assert that f(lo) != f(hi). """ lo_bool = f(lo) if hi is None: offset = 1 while f(lo+offset) == lo_bool: offset *= 2 hi = lo + offset else: assert f(hi) != lo_bool while hi - lo > eps: mid = (hi + lo) / 2 if f(mid) == lo_bool: lo = mid else: hi = mid if lo_bool: return lo else: return hi
def ss_label(ss_code): """ Get the frequency based subsystem code. :param ss_code: Subsystem code. :return: Frequency """ if ss_code == "2": # 1200 khz return "1200 kHz" elif ss_code == "3": # 600 khz return "600 kHz" elif ss_code == "4": # 300 khz return "300 kHz" elif ss_code == "6": # 1200 khz, 45 degree offset return "1200 kHz, 45 degree offset" elif ss_code == "7": # 600 khz, 45 degree offset return "600 kHz, 45 degree offset" elif ss_code == "8": # 300 khz, 45 degree offset return "300 kHz, 45 degree offset" elif ss_code == "A": # 1200 khz vertical beam return "1200 kHz vertical beam" elif ss_code == "B": # 600 khz vertical beam return "600 kHz vertical beam" elif ss_code == "C": # 300 khz vertical beam return "300 kHz vertical beam" elif ss_code == "D": # 150 khz vertical beam return "150 kHz vertical beam" elif ss_code == "E": # 78 khz vertical beam return "75 kHz vertical beam" else: return "1200 kHz" # Default is 1200 khz
def _jupyter_nbextension_paths(): """ Set up the notebook extension for displaying metrics """ return [{ "section": "notebook", "dest": "nbclearafter", "src": "static", "require": "nbclearafter/main" }]
def helm_sequences(): """Returns prefixes of files with raw HELM sequences""" return ['example_', 'for_alignment1_', 'for_alignment2_', 'for_alignment3_', 'for_alignment_without_nh2_', 'helmtest_', 'input_data_', 'multi_chain_peps_', 'multi_chem_pep_', "test_data_"]
def invert_atomlist_coordinates(atomst): """ Inverts atom coordinates :param atoms: list of atom list >>> c1 = [['c1', '1', '1', '-2', '3'], ['c1', 2, 1, -2, 3]] >>> invert_atomlist_coordinates(c1) [['c1', '1', -1.0, 2.0, -3.0], ['c1', 2, -1.0, 2.0, -3.0]] """ atoms = [] for line in atomst: line = list(line) try: inv_coord = [-float(i) for i in line[2:]] except: print('Unable to invert fragment coordinates.') return False line[2:] = inv_coord atoms.append(line) return atoms
def get_header_dict(value): """function to convert string header to dictionary""" values = value.rstrip("\n").split("\n") header_dict = {} for value in values: key, value = value.split(":", 1) header_dict[key.rstrip().lstrip()] = value.lstrip().rstrip() return header_dict
def is_iterable(obj): """ Check for the `__iter__` attribute so that this can cover types that don't have to be known by this module, such as NumPy arrays. """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
def json_int_key_encode(rename_dict): """ Recursively rename integer value keys if they are casted to strings via JSON encoding returns: dict with new keys """ if isinstance(rename_dict, dict): for k in list(rename_dict.keys()): if hasattr(k, 'isdigit') and k.isdigit(): new_label = int(k) else: new_label = k rename_dict[new_label] = json_int_key_encode(rename_dict.pop(k)) return rename_dict
def bisect_left(arr, x): """ x = 5 L R 1 3 4 10 10 arr[i] <5 | 5 <= arr[i] x = 2 L R 1 3 4 10 10 arr[0..L] < 2 | 2 <= arr[R..N] """ N = len(arr) l = -1 # arr[l] < x r = N # arr[r] >= x while r > l + 1: m = (l + r) // 2 if arr[m] < x: l = m else: r = m return l
def mutated_schema(schema, mutator): """Apply a change to all levels of a schema. Returns a new schema rather than modifying the original. """ schema = mutator(schema.copy()) if 'items' in schema: schema['items'] = mutated_schema(schema['items'], mutator) if 'properties' in schema: schema['properties'] = schema['properties'].copy() for k, v in schema['properties'].items(): schema['properties'][k] = mutated_schema(v, mutator) return schema
def prefix_suffix_prep(string1, string2): """Calculates starting position and lengths of two strings such that common prefix and suffix substrings are excluded. Expects len(string1) <= len(string2) """ # this is also the minimun length of the two strings len1 = len(string1) len2 = len(string2) # suffix common to both strings can be ignored while len1 != 0 and string1[len1 - 1] == string2[len2 - 1]: len1 -= 1 len2 -= 1 # prefix common to both strings can be ignored start = 0 while start != len1 and string1[start] == string2[start]: start += 1 if start != 0: len1 -= start # length of the part excluding common prefix and suffix len2 -= start return len1, len2, start
def percentage_string(val): """ Returns a percentage-formatted string for a value, e.g. 0.9234 becomes 92.34% """ return '{:,.2%}'.format(val)
def map_labels(label): """ Purpose: a function used for the pandas library's ".apply()" method to convert all the specific labels in the dataframe into general labels Params: label(string) -> the label from every single row of the dataframe column Returns: a general label (string) """ others = ['ads', 'unique_questions', 'starting_clubs', 'contact_management'] program_info = ['course_schedule', 'content', 'reschedule'] registration = ['course_availability', 'application_deadlines', 'payment_confirmation', 'website_navigation', 'account_edits', 'progress_or_spots'] program_logistics = ['zoom_links', 'zoom_recordings', 'cancel', 'other_urls'] monetary_issues = ['taxes', 'payment', 'refund'] scholarship = ['apply_scholarship', 'info_about_scholarship'] if label in others: label = "others" elif label in program_info: label = "program_info" elif label in registration: label = "registration" elif label in program_logistics: label = "program_logistics" elif label in monetary_issues: label = "monetary_issues" elif label in scholarship: label = "scholarship" elif label == 'unactionable': label = 'unactionable' return label
def require(obj, key, required_type=None): """Return the value with the specified key in obj if it exists, otherwise raise a KeyError. If required_type is not None, a TypeError will be raised if the corresponding value is not an instance of required_type. """ if key not in obj: raise KeyError(f'{key} not found') if required_type is not None and not isinstance(obj[key], required_type): raise TypeError(f'{key} is not a {required_type}') return obj[key]
def set_architecture(architecture_id): """Set architecture-specific parameters. Supported architectures: * 'default'/'intel': a conventional multi-core CPU, such as an Intel Haswell """ # All sizes are in Bytes # The /cache_size/ is the size of the private memory closest to a core if architecture_id in ['default', 'intel']: return { 'cache_size': 256 * 10**3, 'double': 8 } return {}
def binary_search(list: list, target: str): """binary search Args: list (list): sorted list target (str): search target """ low = 0 high = len(list) - 1 while low <= high: mid = (low + high) // 2 pick = list[mid] if pick == target: return mid if pick > target: high = mid -1 else: low = mid + 1 return None
def remove_last_slash(path): """ Remove the last slash in the given path [if any] """ if path.endswith('/'): path = path[:-1] return path
def fair_split(i, n, p): """ Split n requests amongst p proxies Returns how many requests go to the i-th proxy """ n1 = int(n) i1 = int(i) p1 = int(p) return int((n1 * i1) / p1) - int((n1 * (i1 - 1)) / p1)
def remove_whitespace(string): """ This function remove space Parameters : string: the string Returns : return string witout space """ return string.replace(' ','')
def oauth_generator(function, *args, **kwargs): """Set the _use_oauth keyword argument to True when appropriate. This is needed because generator functions may be called at anytime, and PRAW relies on the Reddit._use_oauth value at original call time to know when to make OAuth requests. Returned data is not modified. """ if getattr(args[0], '_use_oauth', False): kwargs['_use_oauth'] = True return function(*args, **kwargs)
def get_status_string(record): """Get the status label given a record of either data format or component""" if "when_revoked" not in record or "when_published" not in record or \ "when_added" not in record: return None if record["when_revoked"] is not None: return "revoked" elif record["when_published"] is not None: return "published" else: return "staged"
def h1(text: str): """ :param h1: string with text for HTML header :return: string containing HTML header 1 """ if not isinstance(text, str): raise TypeError("input must be a string") local_text = ("""<h1>""" + text + """</h1> """) return local_text
def inventory_alias_to_official_habitica_name(inventory_name: str): """Take an inventory_name argument and return the canonical Habitica item name""" # pylint: disable=too-many-return-statements if inventory_name in ["hatchingpotions", "hatchingPotion"]: return "hatchingPotions" if inventory_name in ["pet"]: return "pets" if inventory_name in ["mount"]: return "mounts" if inventory_name in ["currentpet"]: return "currentPet" if inventory_name in ["currentmount"]: return "currentMount" if inventory_name in ["lastdrop"]: return "lastDrop" return inventory_name
def reverse_and_add(x): """ Returns the sum of x and y, where y is formed by reversing the digits of x """ return(x + int(str(x)[::-1]))
def indent_all_but_first(string, indent): """Indent all but the first line of a string.""" return "\n".join(" " * indent * (i > 0) + l for i, l in enumerate(string.split("\n")))
def iter_algorithm(d, n, p, corpus, pr): """ PR(p) = ( (1-d) / n ) + ( d * sum( PR(i) / NumLinks(i) ) ) i d = dampening number; n = # of possible pages; p = page; i = incoming pages """ page_sum = 0 # This for loop will calculate the sum portion of the equation for i in corpus: # Find all incoming pages. p = pg and i = i if p in corpus[i]: # Update the sum to include each instance for the probablity of page i divided by NumLinks on page i page_sum += pr[i] / len(corpus[i]) # Insert sum into rest of iterative algorithm return ((1 - d) / n) + (d * page_sum)
def subjfn(prop): """ Function to retrieve the subject of prop (obtained from the intensional representation produced by SpatialParser). E.g. prop[1] = ['[]'], prop[1][0] = '[] """ return prop[1][0]
def dictadd(dict_a, dict_b): """ Returns a dictionary consisting of the keys in `a` and `b`. If they share a key, the value from b is used. >>> dictadd({1: 0, 2: 0}, {2: 1, 3: 1}) {1: 0, 2: 1, 3: 1} """ result = dict(dict_a) result.update(dict_b) return result
def find_c(side1, side2, side3): """ Takes three side lengths an returns the largest :param side1: int or float :param side2: int or float :param side3: int or float :return: int or float """ if side1 > side2 and side1 > side3: return side1 elif side2 > side1 and side2 > side3: return side2 elif side3 > side2 and side3 > side1: return side3
def maybe_fix_unary_chain(tgt_toks): """Fix unary chain IN:GET_LOCATION-SL:LOCATION_MODIFIER-IN:GET_LOCATION.""" if (not "[SL:LOCATION_MODIFIER" in tgt_toks or not "[IN:GET_LOCATION" in tgt_toks): return tgt_toks for i in range(len(tgt_toks) - 3): if (tgt_toks[i:i + 3] == [ "[IN:GET_LOCATION", "[SL:LOCATION_MODIFIER", "[IN:GET_LOCATION" ]): break else: return tgt_toks print( "--- Unary chain IN:GET_LOCATION-SL:LOCATION_MODIFIER-IN:GET_LOCATION" + " detected in", tgt_toks) new_tgt_toks = tgt_toks[:i] + ["[IN:GET_LOCATION_MODIFIER_LOCATION"] balance_check = 0 for j in range(i + 3, len(tgt_toks)): if "[" in tgt_toks[j]: balance_check += 1 new_tgt_toks.append(tgt_toks[j]) elif "]" in tgt_toks[j]: if balance_check > 0: balance_check -= 1 new_tgt_toks.append(tgt_toks[j]) else: assert tgt_toks[j + 1] == "]" new_tgt_toks += tgt_toks[j + 2:] print("after fix", new_tgt_toks) return new_tgt_toks else: new_tgt_toks.append(tgt_toks[j]) assert False return []
def captcha_halfway(numbers): """Sum the digits that match the one half way around a cyclic string.""" total = 0 for i in range(int(len(numbers) / 2)): if numbers[i] == numbers[i + int(len(numbers) / 2)]: total += int(numbers[i]) return total * 2
def stringToByteArray(string: str) -> list: """ A port of javascript string to Bytearray function :param string: a string """ result = [] i = 0 print(len(string)) while i < len(string): a = ord(string[i]) result.append((65280 & a) >> 8) result.append(255 & a) i += 1 return result
def make_args(args_dict, required, options): """ Make command line argument list, for testing argument parsers Args: args_dict (:obj:`dict`): argument names and their values required (:obj:`list`): required command line arguments options (:obj:`list`): optional command line arguments Returns: :obj:`list`: list of strings in command line arguements, as would appear in `sys.argv[1:]` """ args = [] for opt in options: if opt in args_dict: args.append('--' + opt) args.append(str(args_dict[opt])) for arg in required: args.extend([str(args_dict[arg])]) return args
def is_palindrome(value): """Check if a string is a palindrome.""" return value == value[::-1]
def levenshteinDistance(s1: str, s2: str) -> int: """ https://stackoverflow.com/questions/2460177/edit-distance-in-python """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) distances = distances_ return distances[-1]
def point_check(point,start,end): """ This function checks if the coordinates of a point lies at the edge of a grid. It returns a list of boolean values. """ check=0 for i in point: if i == start or i == end: check+=1 return check
def is_hit(x, y): """Return wheter given coords hit a circular target of r=1.""" return x*x + y*y <= 1
def screen_position(tam_win, tam_scr): """ Windows Position """ dato_scr = (tam_scr-tam_win) / 2 return dato_scr
def __calculate_coefficient_of_variation(profile_jsons, feature_name): """ Calculates coefficient of variation for single feature Parameters ---------- profile_jsons: Profile summary serialized json feature_name: Name of feature Returns ------- coefficient_of_variation : Calculated coefficient of variation for feature """ feature = profile_jsons.get("columns").get(feature_name) coefficient_of_variation = ( feature.get("numberSummary").get("stddev") / feature.get("numberSummary").get("mean") if feature.get("numberSummary") is not None else 0 ) return coefficient_of_variation
def trangle_area(a, b, c): """triangle_area""" return ((a[0] - c[0]) * (b[1] - c[1]) - (a[1] - c[1]) * (b[0] - c[0])) / 2.0
def is_genetic_effect(effect): """ Is this effect a genetic effect? :rtype: bool """ return effect in set(['additive', 'dominance', 'mitochondrial'])
def xgcd(a: int, b: int) -> tuple: """ Extended Euclidean algorithm. Returns (g, x, y) such that a*x + b*y = g = gcd(a, b). """ x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
def break_chocolate(n, m): """ Split the chocolate bar of given dimension n x m into small squares. :param n: integer value. :param m: integer value. :return: number of splits for n x m square. """ return n * m - 1 if n * m > 0 else 0
def replace_ref(tokens): """ syntax """ size = len(tokens) new_list = [] i = 0 while i < size: if i < size - 2 and tokens[i + 2] == b'R': new_list.append({'_REF': tokens[i]}) i += 3 else: new_list.append(tokens[i]) i += 1 return new_list
def process_response_code(info): """Check the VirusTotal response code to ensure hash exists in its database Args: info: the full VirusTotal report in json format. Returns: True if the hash was found in the VirusTotal database. False if not. """ if info["response_code"] == 1: #return true for further processing of results print("Item found in VT database, standby for results..") return True elif info["response_code"] == 0: print("Item not found in VT database, exiting..") return False elif info["response_code"] == -2: print("Item currently queued for analysis, check back later..") return False else: print("Unknown VT response code. Response code: ", info["response_code"]) return False
def dailyLow (lowTemps, date): """Finds the low temperature for date in question. .. warning: Assumes date has been validated using dateValidation and that data exists for date in question using dataAvailable. :param list lowTemps: Low temperatures for given month :param date: Date (Month, day, year) to check for low temperatures :type date: list[str, str, str] :except IndexError: No data available for date in question :return: The low temperature for date :rtype: int or None """ if date is not None: try: return lowTemps[int(date[1]) - 1] except IndexError: return None
def convertString(x): """ Converts textual description of number of likes to integer i.e. - '16.5k' -> 16,500 """ string = str(x) if 'k' in string: number = float( ''.join(string.split('k')[0].split(',')) ) * 1000 elif 'm' in string: number = float( ''.join(string.split('m')[0].split(',')) ) * 1000000 else: number = float( ''.join(string.split(',')) ) return number
def find_total_denials(overall_paths): """return total denial of paths""" cnt = 0 for path in overall_paths: if not path: cnt+=1 return cnt
def list_get(l, index, default): """ >>> list_get([], 0, None) >>> list_get([], -1, 7) 7 >>> list_get(None, 0, None) Traceback (most recent call last): ... TypeError: 'NoneType' object is not subscriptable >>> list_get([1], 1, 9) 9 >>> list_get([1, 2, 3, 4], 2, 8) 3 """ try: return l[index] except IndexError: return default
def trans_nums_to_strs(nums): """ :param nums: number :return: number of translations """ nums = str(nums) cache = [1, 1] # sol(n-2), sol(n-1) for i in range(1, len(nums)): if 9 < int(nums[i-1:i+1]) < 26: cache[1], cache[0] = cache[0] + cache[1], cache[1] else: cache[0] = cache[1] return cache[1]
def limit_to_safe_range(value: float) -> float: """ Controls like throttle, steer, pitch, yaw, and roll need to be in the range of -1 to 1. This will ensure your number is in that range. Something like 0.45 will stay as it is, but a value of -5.6 would be changed to -1. """ if value < -1: return -1 if value > 1: return 1 return value
def listToTensorString(array): """turn python list into java tensor string representation""" assert isinstance(array, list) a = [listToTensorString(element) if isinstance(element, list) else element for element in array] return '{%s}' % ', '.join(list(map(str, a)))
def compute_cumulants(moments): """ Compute the cumulants from the moments up to order 4 """ assert len(moments) >= 4, "You must have moments at least up to order 4." kappas = [0] * 4 kappas[0] = moments[0] kappas[1] = moments[1] - moments[0] ** 2 kappas[2] = moments[2] - 3 * moments[1] * moments[0] + 2 * moments[0] ** 3 kappas[3] = ( moments[3] - 4 * moments[2] * moments[0] - 3 * moments[1] ** 2 + 12 * moments[1] * moments[0] ** 2 - 6 * moments[0] ** 4 ) return kappas
def bolt_min_dist(d_0): """ Minimum bolt spacing. :param d_0: :return: """ e_1 = 1.2 * d_0 e_2 = 1.2 * d_0 e_3 = 1.5 * d_0 p_1 = 2.2 * d_0 p_2 = 2.4 * d_0 return e_1, e_2, e_3, p_1, p_2
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except (AttributeError, TypeError): try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or not isinstance(hint, int) or hint < 0: return None return hint
def single(collection): """:yaql:single Checks that collection has only one element and returns it. If the collection is empty or has more than one element, raises StopIteration. :signature: collection.single() :receiverArg collection: input collection :argType collection: iterable :returnType: type of collection's elements .. code:: yaql> ["abc"].single() "abc" yaql> [1, 2].single() Execution exception: Collection contains more than one item """ it = iter(collection) result = next(it) try: next(it) except StopIteration: return result raise StopIteration('Collection contains more than one item')
def is_hex_str(value, chars=40): # type: (str, int) -> bool """Check if a string is a hex-only string of exactly :param:`chars` characters length. This is useful to verify that a string contains a valid SHA, MD5 or UUID-like value. >>> is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c4ad932f10a', 64) True >>> is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c4ad932f10a', 32) False >>> is_hex_str('0f1128046248f83dc9b9ab187e1xfad0ff596128f1524d05a9a77c4ad932f10a', 64) False >>> is_hex_str('ef42bab1191da272f13935f78c401e3de0c11afb') True >>> is_hex_str('ef42bab1191da272f13935f78c401e3de0c11afb'.upper()) True >>> is_hex_str('ef42bab1191da272f13935f78c401e3de0c11afb', 64) False >>> is_hex_str('ef42bab1191da272f13935.78c401e3de0c11afb') False """ if len(value) != chars: return False try: int(value, 16) except ValueError: return False return True
def flatten_json(json_dict, delim): """Flattens a JSON dictionary so it can be stored in a single table row Parameters: json_dict (dict): Holds the json data delim (string): The delimiter to be used to create flattened keys Returns: flattened_dict (dict): Holds the flattened dictionary """ flattened_dict = {} for i in json_dict.keys(): if isinstance(json_dict[i], dict): get = flatten_json(json_dict[i], delim) for j in get.keys(): flattened_dict[i + delim + j] = get[j] else: flattened_dict[i] = json_dict[i] return flattened_dict
def _pack_uvarint(n: int) -> bytes: """Pack an unsigned variable-length integer into bytes. """ result = b"" while True: chunk = n & 0x7F n >>= 7 if n: result += bytes((chunk | 0x80,)) else: result += bytes((chunk,)) break return result
def get_fx(x, linear): """ Return the y value of function x """ a,b,offset = linear y = ((a * x) + b)//offset return y
def toggle_active_links(pathname): """Toggles active menu links based on url pathname Args: pathname (str): Url pathname Returns: bool: Active state for each page """ if pathname in ["/datyy/", "/datyy/summary"]: return True, False, False, False, False if pathname == "/datyy/orders": return False, True, False, False, False if pathname == "/datyy/products": return False, False, True, False, False if pathname == "/datyy/projects": return False, False, False, True, False if pathname == "/datyy/support": return False, False, False, False, True return False, True, False, False, False
def _get_wikiconv_year_info(year: str) -> str: """completes the download link for wikiconv""" # base directory of wikicon corpuses wikiconv_base = "http://zissou.infosci.cornell.edu/convokit/datasets/wikiconv-corpus/" data_dir = wikiconv_base + "corpus-zipped/" return data_dir + year + "/full.corpus.zip"
def int_32_lsb(x: int): """ Get the 32 least significant bits. :param x: A number. :return: The 32 LSBits of x. """ return int(0xFFFFFFFF & x)
def csv_to_list(x): """Converts a comma separated string to a list of strings.""" return x.split(',')
def gens_by_bus(buses, gens): """ Return a dictionary of the generators attached to each bus """ gens_by_bus = {k: list() for k in buses.keys()} for gen_name, gen in gens.items(): gens_by_bus[gen['bus']].append(gen_name) return gens_by_bus
def check_required_data(dati: tuple) -> bool: """ Ritorna True se tutti i dati passati non sono None o stringa vuota """ result = True for elem in dati: if elem is None: result = False break tmp = elem.strip(' \n\r') if tmp == '': result = False break return result
def is_commit(s): """Return true if `s` looks like a git commit. >>> is_commit("a3bcD445") True >>> is_commit("xyzzy123") False """ if len(s) >= 6: try: int(s, 16) return True except ValueError: pass return False
def texsafe(value): """ Returns a string with LaTeX special characters stripped/escaped out """ special = [ [ "\\xc5", 'A'], #'\\AA' [ "\\xf6", 'o'], [ "&", 'and'], #'\\"{o}' ] for char in ['\\', '^', '~', '%', "'", '"']: # these mess up things value = value.replace(char, '') for char in ['#','$','_', '{', '}', '<', '>']: # these can be escaped properly value = value.replace(char, '\\' + char) for char, new_char in special: value = eval(repr(value).replace(char, new_char)) return value
def tag_and(*tag_ands): """Select a (list of) tag_and(s).""" vtag_and = [t for t in tag_ands] return {"tag_and": vtag_and}
def convertValueToOSCRange(midiValue, oscRange, midiRange): """ value : OSC value OscRange: midiRange """ minOSC = oscRange[0] maxOSC = oscRange[1] minMidi = midiRange[0] maxMidi = midiRange[1] percent = (midiValue - minMidi ) / (maxMidi-minMidi) * 100.0 oscVal = (maxOSC - minOSC) * percent / 100 + minOSC return oscVal
def check_if_factor(guess, value): """Check if the guess is a factor of the value""" if value % guess == 0: return True else: return False
def rstrip_str(user, str): """ Replace strings with spaces (tabs, etc..) only with newlines Remove blank line at the end """ return '\n'.join([s.rstrip() for s in str.splitlines()])
def make_new(data, name): """Make a copy of a dictionary with defaults.""" if name not in data: return None out = data['_defaults'].copy() out.update(data[name]) return out
def _zerofix(x, string, precision=6): """ Try to fix non-zero tick labels formatted as ``'0'``. """ if string.rstrip('0').rstrip('.') == '0' and x != 0: string = ('{:.%df}' % precision).format(x) return string