content
stringlengths
42
6.51k
def dump_tuple(tup): """ Dump a tuple to a string of fg,bg,attr (optional) """ return ','.join(str(i) for i in tup)
def cleaner_results(string): """ Objective : This method is used to replace the html tags with plain text. So that the browser does not render the html ,but should display it. """ try: result = string.replace('<P>', '').replace('<UL>', ''). \ replace('<LI>', '').replace('<BR>', '...
def calculateRevenue(orders): """Calculate revenue from a number of orders""" totalRevenue = 0 for order in orders: totalRevenue += order.shippingPrice if order.status == 3 else 0 return totalRevenue
def check_error(data): """Check if there is error in response""" if 'error' in data: if data['error'] is None: print(data['message']) return False else: print(data['error'],'-> ',data['message']) return True return False
def format_size(num_bytes): """Pretty print a file size.""" num_bytes = float(num_bytes) KiB = 1024 MiB = KiB * KiB GiB = KiB * MiB TiB = KiB * GiB PiB = KiB * TiB EiB = KiB * PiB ZiB = KiB * EiB YiB = KiB * ZiB if num_bytes > YiB: output = '%.3g YB' % (num_bytes / Yi...
def check_max_ids(max_id, mapping_max_id): """ Checks that the maximum ID of the mapping table is sufficient. :type long :param max_id: The maximum id :type long :param mapping_max_id: The maximum id of the mapping table :rtype bool :return Failure """ return mapping_max_id is ...
def copy_attribute(name, src, dst): """ Given a name copy attribute from source object to destination object @param name: field name @param src: source object @param dst: destination object @return: destination object """ if src and name in src: dst[name] = src[name] ret...
def reference_products_as_string(dataset): """Get all reference products as a string separated by ``'|'``. Return ``'None found'`` if no reference products were found.""" exchanges = sorted([exc['name'] for exc in dataset['exchanges'] if exc['type'] == 'refer...
def octagonal_n(n): """Returns the nth octagonal number""" return int(n * (3 * n - 2))
def is_prime(x): """Finding prime numbers""" if x in [0, 1]: return False elif x < 0: return False elif x == 2: return True elif x > 2: for i in range(2, x): if x % i == 0: return False return True
def stringify_value(v): """Converts a value to string in a way that's meaningful for values read from Excel.""" return str(v) if v else ""
def get_cell_from_label(label: str) -> str: """get cell name from the label (cell_name is in parenthesis)""" cell_name = label.split("(")[1].split(")")[0] if cell_name.startswith("loopback"): cell_name = "_".join(cell_name.split("_")[1:]) return cell_name
def get_file_text(path): """ Returns file text by path""" file_io = open(path, "r") text = file_io.read() file_io.close() return text
def countby(seq, key): """ Description ---------- Create a dictionary with keys composed of the return value of the funcion/key\n applied to each item in the sequence. The value for each key is the number of times\n each key was returned. Parameters ---------- seq : (list or tuple o...
def find_blocks_of_sus_substr(blocks, sus_start, h): """ Inputs: blocks - list of tups (text, cum_txt_len, bbox, page_num) sus_start - int index of occurrence of substring h - length of sus substr Returns (page number int, bbox tup) """ blocks_covered = [] for ...
def null_list(pages, size): """ Split a section (divided by pages) on 0-bytes. @param pages: a list of pages @param size: total size of the section @return: a list of strings """ res = [] for page in pages: if size > 4096: size -= 4096 else: page ...
def _get_first_matching_key(search_dictionary, search_key): """ Bullshit way to get around unordered dicts in JSON responses. Again, only exists because I suck and haven't found a better way. """ desired_key = [s for s in search_dictionary if search_key in s][0] desired_value = search_dictionary...
def stochastic_string(reactant_name, number): """ This function returns the stochastic string expression for mass action kinetics For instance the reaction 2A -> 3A would imply A*(A-1)/2 It only does so for one reactant, so it must be called for all reactants in the reaction Paramet...
def subsample_array(arr, max_values, can_modify_incoming_array=True, rand=None): """Shuffles the array and returns `max_values` number of elements.""" import random if not can_modify_incoming_array: arr = arr[:] if rand is not None: rand.shuffle(arr) else: random.shuffle(arr...
def insertion_sort_counting(A): """ Instrumented Insertion Sort to return #swaps, #compares. """ N = len(A) num_swap = num_compare = 0 for i in range(N): for j in range(i, 0, -1): num_compare += 1 if A[j - 1] <= A[j]: break num_swap += ...
def nonlin_softsign(x): """Softsign activation function.""" return x / (1.0+abs(x))
def _get_default_settings(settings): """adds the default settings to a dictinary with settings. If settings is None all the settings are default. If there are already settings given only the non-existing settings are added with their default value. The default settings are: fill_missing_obs = True ...
def convertKm(KM): """Convert Km to Meters""" METERS = float(KM) * 1000 METERS = round(METERS) return METERS
def tzcleanup(data): """Removes timezone from a postgres datetime field for upload to socrata. Socrata data type is a floating timestamp which does not include timezone. Args: Data (list of dicts): Data response from postgres. Returns: Data (list of dicts): The response wit...
def _gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a, b = b, (a % b) return a
def dict_keys_to_str(dictionary: dict): """ Returns a single string of all the keys of the dictionary passed :param dictionary: dict :return str """ key_list = [key for key in dictionary.keys()] return " | ".join(key_list)
def pairs_to_dict(lst_of_pairs): """ Convert a list/tuple of lists/tuples to a dictionary. Parameters ---------- lst_of_pairs: iteterable object of iterable objects an iterable containing iterables, each of these contained iterables is a key/value pair. Exam...
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ # your code here max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res
def numTrees(n): """ :type n: int :rtype: int >>> Solution().numTrees(1) 1 >>> Solution().numTrees(2) 2 >>> Solution().numTrees(3) 5 >>> Solution().numTrees(4) 14 """ if n <= 1: return 1 vec = [1, 1] for i in range(2, n + 1): total = 0 ...
def deserialize_date(string): """Deserializes string to date. :param string: str. :type string: str :return: date. :rtype: date """ try: # pylint: disable=import-outside-toplevel from dateutil.parser import parse return parse(string).date() except ImportError: ...
def sum_swap(a, b): """Return values to swap, None otherwise. Solve: sumA - a + b = sumB + a - b a - b = (sumA - sumB) / 2 Since the inputs are integers only, the difference must also be an even number in order to get a valid pair. Go through the smaller array and add all complements to a ...
def construct_pandoc_command( input_file=None, lua_filter=None, ): """ Construct the Pandoc command. # Parameters input_file:pathlib.Path - The file that we want to apply the lua filter too. lua_filter:pathlib.Path - The path to the lua filter to use for the word counts. ...
def compute_scores(score_instances): """ Given a list of scored instances [(stuff, label, score)], this method computes Average Precision, Reciprocal Rank, and Accuracy. AP is none if no positive instance is in scored instances. :param score_instances: :return: """ # sort score instance...
def is_any_empty(in_list): """A convinient function to check if all the entry in a list is not None. """ if in_list == []: return True else: return any((isinstance(sli, list) and is_any_empty(sli)) for sli in in_list)
def get_version(opts, app): """Get version of a specific app Args: opts (dict): Nephos options dict. app (str): Helm application name. Returns: str: Desired version of Helm app, if specified. Defaults to None. """ if "versions" in opts and app in opts["versions"]: r...
def calc_Ti(Te, Tg, n): """Calcuate the infectious period.""" return (Tg - Te) * 2.0 * n / (n + 1.0)
def min_len_string_encoded(d_rev): """ Calculate minimum length of huffman encodings Args: d_rev: dict encoded --> element Returns: minimum number of characters """ min = 1e10 for x in d_rev: len_bit = len(x) if(len_bit < min): min = len_bit re...
def extract_vuln_id(input_string): """ Function to extract a vulnerability ID from a message """ if 'fp' in input_string.lower(): wordlist = input_string.split() vuln_id = wordlist[-1] return vuln_id else: return None
def some_method(a1, a2, a3): """ some_method returns the larger of 1 or 2 :param a1: First item to compare :param a2: Second item to compare :param a3: Should reverse :return: 1 or 2 """ x = 1 if x > 2: return 1 else: return 2
def start(input): """starts the game, if the input is equal to 'y' pre: uses an input from the user post: returns true if the user input is 'y'""" if input == 'y': return True else: return False
def binary_search_recursive(input_list, item, first=0, last=None): """Recursive search for item index.""" if last is None: last = len(input_list) - 1 if first > last: return None mid_ix = (first + last) // 2 if input_list[mid_ix] == item: return mid_ix elif input_list[mid...
def pad(string: str, length: int) -> str: """ pads string with spaces at end so that it will use length characters """ diff = length - len(string) if diff > 0: return string + ' ' * diff else: return string
def serialize_items(items): """ Returns a list of dicts with all the entries """ final_list = [] for item in items: final_list.append(item.__dict__) return final_list
def convert_names_to_highlevel(names, low_level_names, high_level_names): """ Converts group names from a low level to high level API This is useful for example when you want to return ``db.groups()`` for the :py:mod:`bob.bio.base`. Your instance of the database should already ...
def exponential_moving_average(time_secs, utils, start_time_sec, step_sec, decay=0.99): """ :param time_secs: Epoch_sec of samples. :param utils: Device utilization samples. :param start_time_sec: Start time of the heat-scale. :param step_sec: How much a square in the...
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wi...
def get_indices_located_within_range(start, end, indices): """ start: 3, end: 10, indices: [1, 5, 9, 12], return [5, 9] """ within = list() for i in range(start, end + 1): if i in indices: within.append(i) return within
def get_config(context): """ return the formatted javascript for any disqus config variables """ conf_vars = ['disqus_developer', 'disqus_identifier', 'disqus_url', 'disqus_title'] output = [] for item in conf_vars: if item in context: output.append('\tvar %s = "%s";' % ...
def decode_bert(text): """Decodes text that uses https://github.com/google/sentencepiece encoding. Assumes that pieces are separated by a space""" # return "".join(text.split()).replace("##", " ").strip() return text.replace(" ##", "").strip()
def merge_wv_t1_eng(where_str_tokens, NLq): """ Almost copied of SQLNet. The main purpose is pad blank line while combining tokens. """ nlq = NLq.lower() where_str_tokens = [tok.lower() for tok in where_str_tokens] alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$' special = {'-L...
def get_color(r, g, b): """Bitshift the red, green and blue components around to get the proper bits that represent that color""" return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
def process_device_config_settings(results): """Process Device Config Settings Args: results (Element): XML results from firewall Returns: device_settings_list (list): A list of config setting string values from the firewall """ try: hostname = results.find('./result/system...
def power_of_two(n: int) -> int: """ BIG-O = O(log n) :param n: :return: """ if n < 1: return 0 elif n == 1: return 1 else: prev = power_of_two(n // 2) return prev * 2
def convertbits(data, frombits, tobits, pad=True): """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << (frombits + tobits - 1)) - 1 for value in data: if value < 0 or (value >> frombits): return None acc = ((acc << frombits) | value) & max_acc bit...
def create_box_marker_msg(id, pose, dims=(0.7,0.7,2.0), color=(0,0,1,0.1), duration=0.4): """ Creates a box marker message to be passed to the simulator. Args: id (int): Identifier for the box marker. pose (list): Pose of the box [x, y, z, roll, pitch, yaw] dims (l...
def _chi_LT_fi(phi_LT_theta_com, lambda_LT_theta_com): """ [Eq. 5.62] :param phi_LT_theta_com: Refer to [5.63] :param lambda_LT_theta_com: Non-dimensional slenderness at elevated temperature :return chi_LT_fi: Reduction factor for lateral-torsion buckling in the fire design situation """ ch...
def f(x, a, b): """Fitting function""" return b*(x**a)
def problem_8_5(n): """ Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3 (e.g., 3 pairs of parentheses) output: ['()()()', '()(())', '(())()', '((()))'] """ def parantheses(n): """ Composes n pairs...
def faceBlobSalientBasedOnAverageValue(value, salientLabelValue): """Deprecated""" # the face is considered salient if 50% of pixels or more are marked salient if value > (0.5 * salientLabelValue): return True # bright green # if the face is not salient: else: return False
def is_number(s): """ Given an arbitrary object, checks if it can be cast to a number. """ try: int(s) return True except ValueError: return False
def num_in_base(num, base): """Converts an integer to its representation in base in big-endian. e.g., num_in_base(14, 2) = [1, 1, 1, 0]. Args: num: the number to convert. base: the base of the representation. Returns: The list of digits in big-endian. """ if num == 0: return [0] digits...
def dedup(seq): """Remove duplicates while retaining order""" seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) < 1: return idx_dict = {} for i in range(len(nums)): if nums[i] in idx_dict: return [idx_dict[nums[i]], i] else: idx_dict[target - num...
def assign_tensor_placeholders(placeholder_dict, data_dict): """ Builds feed dictionary for Tensorflow from the placeholder dictionary, which holds placeholders of all gates in the circuit, and a global data dictionary. Parameters ---------- placeholder_dict : dict Dictionary of ...
def _get_commands(controller, config): """ Provides commands recognized by tor. """ commands = config.get('autocomplete', []) if controller is None: return commands # GETINFO commands. Lines are of the form '[option] -- [description]'. This # strips '*' from options that accept values. results =...
def traverse(it, tree): """ return False, when it has no more elements, or the leave node resulting from traversing the tree """ try: subtree = tree[next(it)] except StopIteration: return False if isinstance(subtree, list) and len(subtree)==2: return traverse(it, sub...
def get_diff(t1, t2): """Compute the difference between two lists of the same size. :param list t1: the first list to compare. :param list t2: the second list to compare. :returns: -1 if the list have different size, a list of False/True values in the other case, every True value corresponds to a diff...
def truncate_smart(value, limit=80, truncate='...'): """ Truncates a string after a given number of chars keeping whole words. From: https://djangosnippets.org/snippets/1259/ Usage: {{ string|truncate_smart }} {{ string|truncate_smart:50 }} """ try: limit = int(limit) ...
def carbonblack_ingress_event_filemod(rec): """CarbonBlack Ingress Event Filemod Matched MD5""" return rec['md5'] == '7A2870C2A8283B3630BF7670D0362B94'
def func_x_a_args_p(x, a=2, *args, p="p"): """func. Parameters ---------- x: float a: int args: tuple p: str Returns ------- x: float a: int args: tuple p: str """ return x, None, a, None, args, p, None, None
def read_dices(string): """Read a tuple of dice values from string. From a given string, values sepaated by ',', are extracted and returned as tuple. Arguments: string: (str) string with comma separated integer values Returns: tuple: (tuple) containing read dice values ...
def bubble_sort(arr): """Sort the array using bubble sort. Runtime is O(n^2). Arguments: arr: The array to sort. Returns: arr, but sorted. """ # I would normally comment, but it's bubble # sort. for i in range(len(arr)): # The only thing of note is that we ...
def isFloat(x): """ Returns True, if x is an float. >>> isFloat(3) False >>> isFloat(3.14) True >>> isFloat('3.14') False """ return isinstance(x, float)
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id and the version """ # strip off ?rss=1 if it exists url = url[:url.rfind('?') if '?' in url else None] ix = url.rfind('/') idversion = url[ix+1:] # extract just the id (and the vers...
def expand_vardict(vardict): """ Expand Variable Dictionary >>> expand_vardict({ \ 'v': ['0', '1', '2'], \ 'M': [['00', '01', '02'], ['10', '11', '12'], ['20', '21', '22']] \ }) # doctest: +ELLIPSIS {'v[0]': '0', 'v[1]': '1', ... 'M[2][1]': '21', 'M[2][2]...
def list_strip_all_blank(list_item: list) -> list: """ Strip all items from a list which are '' or empty. :param list_item: The list object to be stripped of all empty values. :return list: A cleaned list object. """ _output = [] for _item in list_item: if _item and _item != '': ...
def real_attenuation(original_extract, real_extract): """ Real Attenuation :param float original_extract: Original degrees Plato :param float real_extract: Real degrees Plato of finished beer :return: The percent of real attenuation :rtype: float """ return (original_extract - real_extr...
def get_max_stack(ant_list): """Get size of largest possible ant stack.""" stacks = [0,] # 0/1 Knapsack Problem for ant in ant_list: temp_stacks = stacks[:] for i in range(len(stacks)): if stacks[i] <= 6 * ant: if i == len(stacks) - 1: te...
def VD_5123(delta_P, a, Ssym, li, Ei, IBersi): """ 5.1.2.3 Resilience for eccentric application of an axial working load """ # try: Summ = sum(li[i] / (Ei[i] * IBersi[i]) for i in range(len(li))) except: Summ = li / (Ei * IBersi) # 5.1/52) delta_Ppp = de...
def plural(s, number, suffix="s"): """ Insert the number into the string, and make plural where marked, if needed. The string should use `{number}` to mark the place(s) where the number is inserted and `{s}` where an "s" needs to be added if the number is not 1. For instance, a string could be "I ...
def allinstance(collection, legal_type): """ Checks the type of all items in a collection match a specified type Parameters ---------- collection: list, tuple, or set legal_type: type Returns ------- bool """ if not isinstance(collection, (list, tuple, set)): illegal = type(collection).__name__ raise(T...
def overwrite_task_config(config, specific_config): """Overwrite config for specific task.""" # add specific task config for key, value in specific_config.items(): if key in config: config[key] = value return config
def __aidx__(a): """Converts Excel column index from alphabetical to numerical""" """ie: __aidx__('AA') = 27""" a = a.upper() try: return int(''.join([__aidx__.d[c] for c in a]), 26) except AttributeError: x = dict(zip(map(chr,range(ord('A'), ord('A')+9)),map(str,range(1,10+1))))...
def ReadBinaryFile(name): """Read a binary file and return the content, return None if error occured """ try: fBinary = open(name, 'rb') except: return None try: content = fBinary.read() except: return None finally: fBinary.close() return cont...
def is_quantity(val) -> bool: """Is ``val`` a quantity (int, float, datetime, etc) (not str, bool)? Relies on presence of __sub__. """ return hasattr(val, "__sub__")
def isMultiLine(line): """Returns true iff line ends with '\'.""" if (len(line) == 0): return False return line[len(line)-1] == '\\'
def scalar(value): """ Take return a value[0] if `value` is a list of length 1 """ if isinstance(value, (list, tuple)) and len(value) == 1: return value[0] return value
def with_file(filename, callback): """Call `callback` with the opened file `filename`. Return result of call. See http://softwareengineering.stackexchange.com/questions/262346/should-i-pass-in-filenames-to-be-opened-or-open-files """ with open(filename, 'r') as f: return callback(f)
def check_gameid(gid): """ Validate the game id to make sure it is not empty. Args: gid: The game id to check Returns: The game id. Raises: ValueError if the game id is the empty string or None. """ if gid == "" or gid is None: raise ValueError('Bad Game Id: %s' % gid) return gid
def vec_div (v,s): """scalar vector division""" return [ v[0]/s, v[1]/s, v[2]/s ]
def scale_signal(audio): """ Returns an audio signal scaled so that the max/min values are +1/-1. """ return audio['signal'] / 2**(audio['sample_width'] - 1)
def determine_projects(warnings): """ Get the list of projects. :rtype: list """ projects = warnings["Report"]["Issues"]["Project"] if not isinstance(projects, list): return [projects] return projects
def remove_first3(alist,k): """Removes the first occurrence of k from alist.""" retval = [] for x in range(0,len(alist)): # Here we use range instead of iterating the list itself # We need the current index, to get the rest of the list # once one occurrence of k is removed. if alist[x] == k: retval.exte...
def calculate_viscosity_Sutherland(T): """Calculates the viscosity of the air Parameters ----------- T : float Temperature (K) Returns ----------- visc : float viscosity of the air (kg/(m s)) Notes ----------- AcCording to [1] the limits for this function are: ...
def isEntity(obj): """Returns whether or not the opject passed is an Phobos entity. Args: obj(bpy.types.Object): The object for which entity status is tested. Returns: """ return obj is not None and 'entity/type' in obj and 'entity/name' in obj
def fisher_exact_test(a, b, c, d, **kwargs): """ Fast implementation of Fisher's exact test (two-tailed). Returns the significance p for the given 2 x 2 contingency table: p < 0.05: significant p < 0.01: very significant The following test shows a very significant correlation between...
def _format_config(config): """ Jesse's required format for user_config is different from what this function accepts (so it would be easier to write for the researcher). Hence we need to reformat the config_dict: """ return { 'exchanges': { config['exchange']: { '...
def to_list(x): """Normalizes a list/tuple to a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list. """ if isinstance(x, (list, tuple)): return list(x) return [x]
def create_keyword_string(command_string): """Creates the keyword string. The keyword string is everything before the first space character.""" cmd_str = command_string.split(" ")[0] return cmd_str
def _raw_ptr_ops(in_params): """Generate pointers to an array to use in place of CArray indexing. The ptr will have a name matching the input variable, but will have _data appended to the name. As a concrete example, `_raw_ptr_ops('raw X x, raw W w')` would return: ['X x_data = (X*)&(x[0]);',...