content
stringlengths
42
6.51k
def get_job_name(cmd): """ Gets the name of the submitted job to set when submitting :param cmd: string or sequence with the command :return: descriptive name """ if isinstance(cmd, str): cmd = cmd.split() if cmd[0] == 'python': for part in cmd[1:]: if part[0] !=...
def normalize_variant(variant: str) -> str: """ Normalize variant. Reformat variant replace colons as separators to underscore. chromosome:position:reference:alternative to chromosome_position_reference_alternative :param variant: string representation of variant :return: reformat...
def get_even_numbers(array: list) -> list: """Returns the row sums. Args: array (list): input array of numbers. Returns: array (list): sorted array of numbers. Examples: >>> assert get_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6] """ return list(filter(lambda number: ...
def ec2_res_is_vpc(res): """ Is this EC2 reservation for a VPC instance? """ return ('VPC' in res['ProductDescription'])
def one_hot_encoding(x, allowable_set): """One-hot encoding. Parameters ---------- x : str, int or Chem.rdchem.HybridizationType allowable_set : list The elements of the allowable_set should be of the same type as x. Returns ------- list List of boolean values w...
def getFile(fileName): """ Returns the file based on the fileName param. Exit from script if something goes wrong. """ try: file = open(fileName, "r") except IOError: print("Unable to open the file: " + fileName) exit() else: return file
def is_num(text): """Check if text can be parsed as a number.""" try: float(text) except: return False else: return True
def _get_frame_op_default_axis(name): """ Only DataFrame cares about default_axis, specifically: special methods have default_axis=None and flex methods have default_axis='columns'. Parameters ---------- name : str Returns ------- default_axis: str or None """ if name.r...
def _to_camelcase(text): """ Converts underscore_delimited_text to CamelCase. Example: "tool_name" becomes "ToolName" """ return ''.join(word.title() for word in text.split('_'))
def format_song(song:dict)->str: """ song to formatted string 'naslov pesmi' by 'ime banda' """ return song['title'] + ' by ' + song['band']
def custom_cycle_time_columns(minimal_fields): """A columns list for the results of CycleTimeCalculator with the three custom fields from `custom_settings`. """ return [ "key", "url", "issue_type", "summary", "status", "resolution", "Estimate", ...
def model_string_from_id(id): """This function converts an AFINO model ID integer to a string descriptor""" allowed_models = { 0 : 'pow_const', 1 : 'pow_const_gauss', 2 : 'bpow_const', 3 : 'pow_const_2gauss' } model_string = allowed_models.get(id) if not model_strin...
def nested_import(name): """ Using ``__import__`` retrieve nested object/namespace. Solution_ couresty of stack overflow user dwestbook_. .. _Solution: http://stackoverflow.com/questions/ 211100/pythons-import-doesnt-work-as-expected .. _dwestbrook: http://stackoverflow.com...
def _flatten_json(y): """ Method to convert the multilayer JSON to 1 dimension row vector :return: flatten json dictionary """ out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') else: out[name[:...
def convert_taxonomy_bool(s): """ Returns true/false given a string loaded from the Taxonomy. Values to check are based on observed values from within the Taxonomy. If the input is not valid this will always return false. """ if s is None: return False elif s.strip().lower() in [...
def get_quoted_name_for_wlst(name): """ Return a wlst required string for a name value in format ('<name>') :param name: to represent in the formatted string :return: formatted string """ result = name if name is not None and '/' in name: result = '(' + name + ')' return result
def valid(board, pos, num): """ Returns is the attempted move is valid :param board: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # Check Row for i in range(0, len(board)): if board[pos[0]][i] == num and pos[1] != i: return False #...
def unpack_batch(batch, use_cuda): """ Unpack a batch from the data loader. """ if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:6]] else: inputs = [b if b is not None else None for b in batch[:6]] orig_idx = batch[6] return inputs, orig_idx
def convert_bbox_xywh_to_yminxmin(cv2_rects): """Convert cv2_rects (x, y, w, h) to bbox_coord (ymin, xmin, ymax, xman) Args: cv2_rects: Returns: bbox_coord """ x, y, w, h = cv2_rects ymin, xmin, ymax, xmax = y, x, y + h, x + w tf_bbox_coord = (ymin, xmin, ymax, xmax) re...
def functions_equal(fn1, fn2): """Check equality of the code in ``fn1`` and ``fn2``. """ try: code1 = fn1.__code__.co_code except AttributeError: code1 = fn1.__func__.__code__.co_code try: code2 = fn2.__code__.co_code except AttributeError: code2 = fn2.__func__....
def get_parameter_list_from_request(req,parameter): """Extracts a parameter from the request. Parameters ---------- req : HttpRequest The HTTP request. parameter : str The parameter being extracted. Returns ------- List List of comma separated parameters. "...
def build_html_string(html_string, page_title): """ This function builds the HTML document inside of it is placed the HTML components that have been built by other functions. :param html_string: :return: """ html = """ <html> <head> <title>{0}</title> <link r...
def partition_at_level(dendrogram, level) : """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher the level...
def format_channel(channel): """ Returns string representation of <channel>. """ if channel is None or channel == '': return None elif type(channel) == int: return 'ch{:d}'.format(channel) elif type(channel) != str: raise ValueError('Channel must be specified in string format....
def r_shift(bin_str, new_val): """ Function performs a right shift of a binary string. Placing the new value into the MSB position. """ offset = bin_str.find('b') + 1 new_val = str(new_val) + bin_str[offset:-1] if (offset != -1): new_val = '0b' + new_val return new_val
def assign_constant_points(projects, default_task_value=10): """ Takes in parsed project tree, with one level of tasks Outputs project tree with constant points assigned """ for goal in projects: for task in goal["ch"]: task["val"] = default_task_value return projects
def memoize(f): """ Memoization decorator for functions taking one or more arguments.""" class MemoDict(dict): def __init__(self, f_): self.f = f_ def __call__(self, *args): return self[args] def __missing__(self, key): ret = self[key] = self.f(*key...
def reaction_splitter(reaction): """ Args: reaction (str) - reaction with correct spacing and correct reaction arrow `=>` Returns (list): List of compounds in the reaction Example: >>>reaction_splitter("c6h12o6 + 6o2 => 6h2o + 6co2") ['c6h12o6', '6o2', '6h2o...
def pad(depth): """ Takes a recursion depth and returns an appropriate amount of indentation to try to be able to read what is going on. >>> takes: An integer, 0 or more >>> returns: Some spaces or whatever padding we want for something at this depth """ return "> "*depth
def pdomainname(labels): """given a sequence of domainname labels, return a quoted printable text representation of the domain name""" printables = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-*+' result_list = [] for label in labels: result = '' for c in label...
def convert_name_to_full_type_name(context, name, types_dict): # pylint: disable=unused-argument """ Converts a type name to its full type name, or else returns it unchanged. Works by checking for ``shorthand_name`` and ``type_qualified_name`` in the types' ``_exten...
def make_unique(arr): """Choose only the unique elements in the array""" return list(set(list(arr)))
def get_compliance_and_severity(new_status): """Return compliance status.""" status = ['FAILED', 3.0, 30] if new_status == 'COMPLIANT': status = ['PASSED', 0, 0] return status
def _remove_long_seq(maxlen, seq): """Removes sequences that exceed the maximum length. # Arguments maxlen: Int, maximum length of the output sequences. seq: List of lists, where each sublist is a sequence. label: List where each element is an integer. # Returns new_seq, ne...
def update_trackers(frame,trackers,penalties=0,mark_new=True): """Update all the trackers using the new frame Args: frame ([type]): new frame trackers (List[TrackerObj]): List of trackers to update penalties (int, optional): Amount of penaltie. Defaults to 0. mark_new (bool, opt...
def guess_lon_lat_columns(colnames): """ Given column names in a table, return the columns to use for lon/lat, or None/None if no high confidence possibilities. """ # Do all the checks in lowercase colnames_lower = [colname.lower() for colname in colnames] for lon, lat in [('ra', 'dec'), (...
def make_tuple(obj): """ Create a tuple from an object, or return the object itself. :param obj: object to convert to a tuple :return: converted tuple or the object itself :rtype: tuple """ if hasattr(obj, "__iter__"): return tuple(obj) else: return (obj,)
def parse_altmetric_id(file_object, paper_id): """ Parse the altmetric_id from the file object using hte paper id and return the id after processing the object Parameters ---------- arg1 | file_object: list The list that contains the altmetric information of all articles arg2 | p...
def equivalence_partition( iterable, relation ): """Partitions a set of objects into equivalence classes Args: iterable: collection of objects to be partitioned relation: equivalence relation. I.e. relation(o1,o2) evaluates to True if and only if o1 and o2 are equivalent Returns: classes, partitions c...
def smh(depth: int = 1) -> str: """Expands smh as many times as the depth argument.""" if depth == 0: return "smh" else: return smh(depth-1) + " my head"
def var_parameter_f(x, *args): """ var_parameter_f """ z = x + args[0] + args[1] + args[2] return z
def block(*_): """Returns the last element of a list.""" return _[-1]
def add_fibonacci(lst): """ Adding fibonacci number """ next_fibonacci_number = lst[-2] + lst[-1] lst.append(next_fibonacci_number) return lst
def construct_parameter_pattern(parameter): """ Given a parameter definition returns a regex pattern that will match that part of the path. """ name = parameter['name'] type = parameter['type'] repeated = '[^/]' if type == 'integer': repeated = '\d' return "(?P<{name}>{rep...
def convert_polvar_name(convention, polvar): """ Finds the correct variable name for a given convention (MXPOL, MCH) and a given variable name which was spelled with a different case or according to a different convention. For example, MXPOL convention uses 'Z' for the reflectivity variable, but if ...
def message2codepayload(message): """ Convert a message in a (code,payload) tuple message must be: [code][payload] """ if not message.startswith("["): raise ValueError("message2codepayload : invalid start char : {}".format(message)) if not message.endswith("]"): raise ValueE...
def created_by(date, user=None, prefix="updated"): """ Renders a created by link """ return dict(date=date, user=user, prefix=prefix)
def vdiv_scalar(vector, scalar): """ div vectors """ return (vector[0] / scalar, vector[1] / scalar)
def armstrong_number(number): """ Check if number is Armstrong number """ calc = number sum_ = 0 while calc > 0: dig = calc % 10 sum_ += dig ** 3 calc //= 10 if number == sum_: return True else: return False
def _get_number_of_column_label(label): """ This function returns a number which corresponds to the label. Example : 'A' -> 1 , 'Z' -> 26 , 'AA' -> 27 , 'BA' -> 53 Args : label : Type-str Denotes the label given to the column by sheets Returns : num : Type-int ...
def get_split(partition_rank, training=0.7, dev=0.2, test=0.1): """ This function partitions the data into training, dev, and test sets The partitioning algorithm is as follows: 1. anything less than 0.7 goes into training and receives an appropiate label 2. If not less than 0.7 subtract 0.7...
def null_odd_digits(n): """ Returns the number that cancels out the effect of the weight of the odd digits Examples: >>> null_odd_digits(6354) 6004 >>> null_odd_digits(3250) 200 >>> null_odd_digits(3050) 0 >>> null_odd_digits(10**20) ...
def _descendants(node): """ Returns the list of all nodes which are descended from the given tree node in some way. """ try: treepos = node.treepositions() except AttributeError: return [] return [node[x] for x in treepos[1:]]
def get_memory_from_string(mem_str): """ Converts a string of a memory or file size (i.e. "10G") into a number. Parameters ---------- mem_str : int or float Returns ------- int or float Examples -------- >>> libtbx.utils.get_memory_from_string("10G") 10737418240.0 >>> libtbx.utils.get_memor...
def replace_non_ascii(text, replace_with=' '): """Replaces all non-ASCII chars in strinng.""" return ''.join([i if ord(i) < 128 else replace_with for i in text])
def times(values): """ Reads the stdout logs, calculates the various cpu times and creates a dictionary of idle time and the total time Parameters ---------- values : list output of the command from the std out logs Returns ------- tuple idle and total time of the c...
def tof2evpoly(a, E0, t): """ Polynomial approximation of the time-of-flight to electron volt conversion formula. **Parameters**\n a: 1D array Polynomial coefficients. E0: float Energy offset. t: numeric array Drift time of electron. **Return**\n E: numeric ...
def get_gaps(int_list): """ Returns the gaps in a list of intervals: inverts the interval using its bottom and top values ad universe boundaries """ int_list = sorted(int_list, key=lambda x: x[0]) gaps = [] for i in range(len(int_list)-1): a, b = int_list[i] c, d = int_list[i+1]...
def parse_parameters(config, log=None): """Fills the configuration with default values. Writes a warning to logs, if unknown keys are detected.""" defaults = {"priority": "False", "bed": "no_peaks.bed", "gtf": "no_annotation.gtf"} # , "bigwig": "none.bw" keys = defaults.keys() values = ...
def sports_validation(sports): """ Decide if the sport input is valid. Parameters: sports(str): A user's input to the sport factor. Return: (str): A single valid string, such as "1", "0" or "-5" and so on. """ while sports != "5" and sports != "4" and sports != "3"...
def calc_damped_vs_kramer_1996(vs, xi): """ Calculates the damped shear wave velocity Ref: Eq 7.9 from Kramer (1996) :param vs: :param xi: :return: """ return vs * (1.0 + 1j * xi)
def capital_weights(preferred_stock, total_debt, common_stock): """ Summary: Given a firm's capital structure, calculate the weights of each group. PARA total_capital: The company's total capital. PARA type: float PARA preferred_stock: The comapny's preferred stock outstanding. PARA ty...
def asciilower(s): """convert a string to lowercase if ASCII Raises UnicodeDecodeError if non-ASCII characters are found.""" s.decode('ascii') return s.lower()
def construct_org_str(genomes): """Constructs the organism string for the hal snakes. format is genome=genome space separated""" return ' '.join(['{0}={0}'.format(genome) for genome in genomes])
def mean_(list): """Used for finding the mean of a list Usage: mean_(list) list = any list of decimal numbers which are non text""" list_sum = 0 try: for i in list: list_sum += int(i) return list_sum / len(list) except (TypeError, ValueError, ZeroDivisionError): ...
def _format_results(name, internal_score, scores, metrics, use_elbo=False): """Format results.""" result_str = "" internal_score_name = "elbo" if use_elbo else "ppl" if internal_score: result_str = "%s %s %.2f" % (name, internal_score_name, internal_score) if scores: for metric in metrics: if re...
def _convert_precision_to_zoom(precision): """Converts precision to zoom level based on the minimum zoom Parameters ---------- precision: string precision level Returns ------- zoom level """ if precision == "10m": return 6 elif precision == "1m": r...
def check_completeness(ISM): """ Check if an ISM is fully corrected (no ambiguous bases) Parameters ---------- ISM: str an ISM of interest Returns ------- FLAG: boolean if fully corrected """ for item in ISM: if item not in ['A', 'T', 'C', 'G', '-']: ...
def int_tokenize(itr, lexicographic_order=False): """ int tokenize iterable return dict mapping symbol to int token Args: * itr - iterable * lexicographic_order - (bool) iff True sort integer labels lexicographically according to itr Returns: * tokenized - (int list...
def operation_consumes_ref_bases(operation): """ Returns true if this is a cigar operation that consumes reference bases """ return operation == 0 or operation == 2 or operation == 3 or operation == 7
def _merge_group(group, companions, cnode): """Merge group with the previously known companions of cnode, return the group (which should now be the companion list for everything in group) """ # precondition: if group then forall x in group companions[x]==group if group is not None and cnode in ...
def _convert_to_string(data): """Converts extracted string data from bytes to string, as strings are handled as bytes since h5py >= 3.0. The function has been introduced as part of an `issue <https://github.com/rundherum/pymia/issues/40>`_. Args: data: The data to be converted; either :obj:`bytes`...
def cumulative_distribution(distribution): """Returns normalized cumulative distribution from discrete distribution.""" cdf = [0.0] psum = float(sum(distribution)) for i in range(0, len(distribution)): cdf.append(cdf[i] + distribution[i] / psum) return cdf
def order_suffix(index): """ Return the suffix order string. """ if index == 1: return "st" elif index == 2: return "nd" elif index == 3: return "rd" return "th"
def get_interface_type(interface): """Gets the type of interface Args: interface (str): full name of interface, i.e. Ethernet1/1, loopback10, port-channel20, vlan20 Returns: type of interface: ethernet, svi, loopback, management, portchannel, or unknown """ if in...
def RGBToLumaCCIR601(rgb): """ RGB -> Luma conversion Digital CCIR601 (gives less weight to the R and B components) :param: rgb - The elements of the array rgb are unsigned chars (0..255). :return: The luminance. """ Y = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2] return Y
def _check_categories(cat): """ Check if the keys of a dictionary are in ascending order. Parameters ---------- cat : disct the dictionary to be checked. Returns ------- correct : bool True if dict keys are in ascending order False otherwise. """ correct = True...
def getDictMax(a): """Get key of max element in a dict of ints or floats""" b = dict(map(lambda item: (item[1],item[0]),a.items())) max_key = b[max(b.keys())] return max_key
def color(red: int, green: int, blue: int, white: int = 0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. Note the sequencing has been changed from RGB (most signific...
def linear(x: float, target: float, span: float, symmetric = False) -> float: """Create a linearly sloped reward space. Args: x (float): Value to evaluate the reward space at. target (float): The value s.t. when x == target, this function returns 1. span (float): The value s.t. when x >= target ...
def get_packing_strategies(start_length, minimum_increment, target_length, depth): """Recursively build a list of unique packing "strategies". These strategies represent the ways that up to "depth" many sequences can be packed together to produce a packed sequence of exactly "target_length" tokens in t...
def read_file(filepath): """ Read file content :param filepath: :return: """ with open(filepath, "r", encoding="utf-8") as file: data = file.read() return data
def frohner_cor(sig1,sig2,n1,n2): """ Takes cross-sections [barns] and atom densities [atoms/barn] for two thicknesses of the same sample, and returns extrapolated cross section according to Frohner. Parameters ---------- sig1 : array_like Cross section of the thinner of the two sa...
def factR(n): """Assumes that n is an int > 0 Returns n!""" if n == 1: return n else: return n*factR(n - 1)
def get_ports_by_protocol(protocol, ports): """ Get tcp or udp ports from the list of POST data. """ result_ports = {} if not ports: return result_ports for port in ports: if port['protocol'] == protocol: result_ports[port['name']] = port['port'] return result_po...
def decode_hex(string): """ Decode hexdump string *string* must be an ASCII string describing binary data as hexadecimal bytes, ie. each line must have this form: BYTE [BYTE].. where each BYTE is a two-digit hexadecimal number. Lines are joined before decoding. For example: ...
def checkTestCaseSuccess(output): """ Searches the output of the GDB script for incentives of failure """ incentives = ["error", "fail", "unexpected", "cannot"] for word in incentives: if output.lower().find(word) != -1: return False return True
def fizz_buzz(n): """ return fizz when n divisible by 3 return buzz when n is divisible by 5 return fizzbuzz when n divisible by both 3 and 5 """ if n % 3 == 0 and n % 5 ==0: return 'fizzbuzz' elif n % 3 ==0: return 'Fizz' elif n % 5 ==0: return 'buzz'
def get_lock_name(file_path): """ Returns lock file of the given file :param file_path: str :return: str """ return '{}.lock'.format(file_path)
def _should_allow_unhandled(class_reference, key_name): """Check if a property is allowed to be unhandled.""" if not hasattr(class_reference, "__deserialize_allow_unhandled_map__"): return False return class_reference.__deserialize_allow_unhandled_map__.get(key_name, False)
def endot(text): """Terminate string with a period. """ if text and text[-1] not in '.,:;?!': text += '.' return text
def create_column_definition_single(d: dict) -> str: """Create the column definition for a single column. Args: d: A `dict` of values to compose a single column definition, defaults:: { "data_type": "varchar(256)", # str "default": None, # Any ...
def get_just_code(text): """Just the facts ma'am""" if text == "": return "" return text.split()[0]
def normalize_url(url): """Return a normalized url with trailing and without leading slash. >>> normalize_url(None) '/' >>> normalize_url('/') '/' >>> normalize_url('/foo/bar') '/foo/bar' >>> normalize_url('foo/bar') '/foo/bar' >>> normalize_url('/foo/bar/') '/foo/...
def cal_acc(golden_label, pred_label): """ The function actually calculate the accuracy. """ acc = 0.0 for ids in pred_label: if ids not in golden_label: continue if pred_label[ids] == golden_label[ids]: acc += 1 if len(golden_label): acc /= len(go...
def ms_to_minutes(time: float) -> float: """ Convert milliseconds to minutes. Parameters ---------- time : float A ``float`` of time in milliseconds. Returns ------- float Returns a ``float`` of the converted time in minutes. """ return round(time / 1000 / 60, 3...
def _joinNamePath(prefix=None, name=None, index=None): """ Utility function for generating nested configuration names """ if not prefix and not name: raise ValueError("Invalid name: cannot be None") elif not name: name = prefix elif prefix and name: name = prefix + "." + ...
def merge(dct1, dct2): """Merges two dictionaries""" return {**dct1, **dct2}
def _bitsize(count, chars): """helper for bitsize() methods""" if chars and count: import math return int(count * math.log(len(chars), 2)) else: return 0
def modo_api_instance_update(url, request): """Simulate successful update.""" return {"status_code": 200}