content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def error(msg): """ Standard error result - for internal errors """ return dict(result='error', message=msg)
6c913c8ceeb151ed84ed21d834718030837dcf3b
577,837
import math def euc_dist(coords_1, coords_2): """Calculate the euclidian distance between two y,x tuples Args coords_1: tuple of row, col values coords_2: tuple of row, col values Returns dist: distance between two points""" y = coords_1[0] - coords_2[0] ...
b511405441eeb5f7a87368d896703c9605f71799
577,838
def _convert_trace_id_uint64(otel_id): """Convert 128-bit int used for trace_id to 64-bit unsigned int""" return otel_id & 0xFFFFFFFFFFFFFFFF
8b15411797bb1e7035d1b14fe21d47e5ac4b0f6a
577,839
def distance_one(possible, word): """Checks if the number of characters changed between two words is one. Args: possible: str, possibly the next word word: str, real path word to test against Returns: bool, True if one letter distance """ difference = 0 for i, _ in enumer...
a65b3f412bde6def06125a9238ec30aae12817bd
577,840
def get_audio_url(json_content: list) -> str: """ Generate an http compliant audio url :params: json_content: :returns: audio_url - https version of the audion url """ audio_url = json_content[0]['phonetics'][0]['audio'] audio_url = f"https:{audio_url}" return audio_url
1543a07f865b789929e7e005e6d9eb46acf4c34f
577,841
def knapsack_unbounded(w, wt, vt, n): """ It's an unbounded knapsack problem as we can use 1 or more instances of any resource. A simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which can achieved using all items and i capacity of knapsack. Note that we use 1D array...
703f73cb7632c050c98b659618a257862a4bbe6e
577,844
from typing import Union from typing import List from typing import Callable from typing import Optional from typing import Match import re def create_validator( valid_characters: Union[str, List[str]], case_sensitive: bool = True ) -> Callable[[str], Optional[Match[str]]]: """Function that generates a callab...
bf63a92ead72e21a43d5f74b92698175454b3fe8
577,845
def solves_simple_problem(X, y, nn_instance): """Checks if a given network is able to solve a simple problem""" nn_instance.compile(optimizer='adam', loss='mse') nn_instance.fit(X, y, epochs=800) results = nn_instance.evaluate(X, y) print("FINAL RESULT ", results) return result...
cb71845f706a1b80afa15869aa6af8910f25d2fa
577,848
def _extract_items(json_dict: dict): """Return the items key if it exists, otherwise the top level.""" return json_dict.get("items", json_dict)
76dd6bb209905cd2384dd3a88329e3e66f19ec18
577,849
def _rv(match): """ Given a regexp match for a color, return the reverse-video version of that color. @param match: A regular expression match. @type match: C{Match} @return: The reverse-video color. @rtype: C{string} """ str = '#' for color in match.groups(): str += '%0...
ad55068e47b713c2d43d7e4cfa209b92be64bdf1
577,851
def countGlideinsCondorStatus(status_dict): """Return the number of glideins in the dictionary :param status_dict: the output of getCondorStatus :return: number of glideins in the dictionary (integer) A Glidein is an execution of the glidein_startup.sh script - may be different from job submitted...
5fc95506b7ace853ec36a2a38e54342da96e0bc7
577,852
def _sabr_implied_vol_hagan_A4_fprime_by_strike( underlying, strike, maturity, alpha, beta, rho, nu): """_sabr_implied_vol_hagan_A4_fprime_by_strike See :py:func:`_sabr_implied_vol_hagan_A4`. :param float underlying: :param float strike: :param float maturity: :param float alpha: must b...
c3350ba834c06234817db8beaab4bfc2cf3c9adf
577,853
def coding_problem_38(n): """ You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal. From this Wikipedia artic...
38cfafff3220dbf20532c6e12ff04c6c0fbe8b67
577,854
def buildFactorialTable(n): """ Build the factorials of all the numbers 1,2,3,...,n We will need them all. So, lets compute them also bottom up, as in Dynamic Programming. """ result = [1] for i in range(n-1): result.append(result[-1]*(i+2)) return result
e52f1a217841a3e5246865ecd44fe9ae9395783f
577,855
def removeRepeat(arr, keyFunction=""): """ 去除掉[]中相同的元素,根据方法keyFunction。 e.g.:a=[{'name':1},{'name':3},{'name':2},{'name':1},{'name':1}] 假设要去除name为1的元素 c=removeRepeat(a,keyFunction=lambda x:x['name']) print(c) =>[{'name': 1}, {'name': 2}, {'name': 3}] @param:arr |[] 需要去重的数组 @param:keyFun...
1fa8128fe088df097099068b33bcaf60ba29ee40
577,862
def __get_taxa(rank): """ Return set of taxids with abundance > 0 >>> __get_taxa(query_rank) {123} :param rank: Set of taxids of specific rank :return: list of taxids """ return set(k for k, v in rank.items() if v > 0)
00e78d262007bcf529dded7209091e050f08d0aa
577,864
def t_RBRACKET(t): """] token""" return t
80ade789fdbf6ee5d9b8a5c8208135df3ae42d88
577,865
def get_root_node(ad_group_criterions): """ Returns the root node of a tree. This operation assumes that a complete product partition tree is provided for one ad group. The node that has null ParentCriterionId is the root node. :param ad_group_criterions: The ad group criterions that contain the p...
488780497ed057549af9ba1ed6ce8d098ea3831d
577,871
def _select_hooks(hook, hooks): """Returns list of callable hooks of given name""" if not hooks: return () return [getattr(i, hook) for i in hooks if hasattr(i, hook)]
1f20809fc3880c4585a394713811e4c2b10c8978
577,874
def email_ec(item): """ Create entry context for an email :param item: exchangelib.Item :return: entry context dict """ return { "CC": None if not item.cc_recipients else [mailbox.email_address for mailbox in item.cc_recipients], "BCC": None if not item.bc...
c485ac24da4dc9e282d1193fc16be7f04d477072
577,875
def add(dq1, dq2): """Adds two dual quaternions.""" return dq1 + dq2
e393b6f919f36b37eb2b2ead18076f0bccf6f793
577,877
def head(args, premise): """Return head (ID of token current token depends on).""" return args[0].head
8b519dc26b71c4ffb0aef66c5fdc262f0e368b5c
577,879
def to_list(x): """ Wraps x in a list if it is not already a list. :param object x: Any object. :return: x wrapped in list :rtype: list """ return x if isinstance(x, list) else [x]
a81834ee147d0dfde09674abbb8df14664a34429
577,882
def hex_str_to_bytes(h): """ Converts a hex-encoded string to bytes. Args: h (str): hex-encoded string to convert. Returns: b (bytes): bytes corresponding to h. """ return bytes.fromhex(h)
8be89de5699843c5acf49f1215bfce0697f9b73c
577,885
def ppv_from_df(merged_df, number_to_test, length_cutoff=8): """ Pretty straightforward calculation of positive predictive value given the merged_df input, n to test, and what to define as a contact (in units of angstroms) """ temp_df = merged_df[:number_to_test] tps = temp_df[temp_df['dista...
1c0b3a7fa0c16d6ac49a989b31dc9fea05084d26
577,888
def nested_update(defaults, updates): """ Recursively updates nested config dicts. """ if not isinstance(defaults, dict) or not isinstance(updates, dict): return updates for key, value in updates.items(): defaults[key] = nested_update(defaults.get(key, {}), value) return default...
3269deaf48a355841ac681c9c8a67282f9cd4a30
577,897
def pluralize(value: int, noun: str) -> str: """Pluralize a noun.""" nouns = {"success": "successes", "die": "dice"} pluralized = f"{value} {noun}" if value != 1: if noun in nouns: pluralized = f"{value} {nouns[noun]}" else: pluralized += "s" return pluraliz...
3909ac390d5f0c92c11a43e49bfa1830d34f8482
577,904
def _var(i=0): """ Return a distinct variable name for each given value of i """ alphabet = "XYZABCDEFGHIJKLMNOPQRSTUVW" return alphabet[i] if i < len(alphabet) else "X{}".format(i)
8026442a230d7c0b230a0c6ab9480676c0a6d45b
577,905
import math def print_from_ms(msec) -> str: """Result time in human readable format from milliseconds. Args: ms: time in millisecond Returns: str: Time in human readable format """ ms_per_sec = 1000 ms_per_min = ms_per_sec * 60 minutes = math.floor((msec / ms_per_min)) ...
d5bb691508a1c38ec873dd7d0ac4b4e7f52bb895
577,913
def lharmonicmean (inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0/item return len(inlist) / sum
1b9551de11834618e27e5eda78c5d36edd6c84ff
577,915
def fix_trailing_slashes(s): """ remove abritrary number of trailing slashes""" s = s.strip() # first remove spaces while s[-1] == '/': s = s.strip('/') return(s)
d3c213d079df29762ab5eeb9896d8375137612f9
577,918
def right_replace(string, old, new, count=1): """ Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``. For example:: right_replace('one_two_two', 'two', 'three') -> 'one_two_three' """ if not string: return string return new.join(string.rsplit(old, count))
5ddf369ef3efdfcb881656d2a8c18ce064581a8f
577,919
def int_to_bytes(value: int) -> bytes: """ Return the bytes for a given integer. """ return value.to_bytes((value.bit_length() + 7) // 8, byteorder='big')
c4c5c02d437964e006acef6292ffffdf48c20c88
577,920
def _num_type(x): """ Is x a number type? """ if type(x) == int: return True if type(x) == float: return True if type(x) == ord: return True return False
3e0114ac2774ae0a9a420f2f486e5c9c255d8af8
577,921
def _get_column_val(column): """ Parameters ---------- column : float or tuple gives the column or (column, unc) or (column, punc, munc) Returns ------- column: float column value """ if isinstance(column, tuple): return float(column[0]) else: re...
a6d1ed4101bfc20b71bd1b232e72d22d29f5a140
577,923
def remove_self_loops(edge_index, edge_sqdist, edge_weight=None): """ Removes all self-loop in the graph. Args: edge_index (`torch.LongTensor`): indices of graph's edges. edge_attr (`torch.FloatTensor`): attributes of graph's edges. Returns: (`torch.LongTensor`): indices of gra...
97efd8489a95669eb10f7f7b03fc7e9e22861a18
577,926
import re from datetime import datetime def get_instruments_ramp_messages(current_driver): """ Listen to the mock instruments and parse the messages to extract the ramping targets. This is useful in determining if the set targets arrive at the individual instruments correctly. The time stamps are useful t...
73fcb7aebd6eff94cf511bcd32e44feb8b998363
577,929
from typing import Set import re def compile_graphemes(graphemes: Set[str]) -> re.Pattern: """ Compiles the list of graphemes into a regular expression pattern. Parameters ---------- graphemes: Set[str] Set of characters to treat as orthographic text Returns ------- re.Patter...
b4714c34a16fab1af8babf3542aab20bb59c9ac9
577,930
def create_action(type_: str, value: str): """Create an action for clients to use.""" return {"type": type_, "value": value}
08c922d054dad8594ad4df77c432a29305ce60d1
577,933
def break_apl_singleton(apl: str) -> str: """ Pull APL entry apart, returning IPv4 or IPv6 nugget without mask """ if apl == "": return "" (ipver, remainder) = apl.split(":", 1) (ipaddr, mask) = remainder.split("/", 1) return ipaddr
639fdd3847255aa8ff8f248c7f591a6853e13a83
577,934
def make_printable(text): """ Strips out all non-printable characters from the text, including: - 0x00 - 0x20, excluding CR, LF and tab - 0x7F """ buffer = [] for ch in text: if ch in '\r\n': buffer.append(ch) else: ord_ch = ord(ch) if ord...
7b602734d613a912dd5a321f64bd0a0216072744
577,938
def get_dim(y): """Return the number of dimensions of a torch tensor or numpy array-like object. """ try: return y.ndim except AttributeError: return y.dim()
a5d8c6f1d6e16ad680dfab87255099f5a1aedf8c
577,939
def split_list(a_list): """Split a python list into two paths""" half = len(a_list)//2 return a_list[:half], a_list[half:]
cf851dcd77b5883f7f81cb513896682a412b8a0d
577,942
def reformat_resource_groups_outputs(text: str) -> str: """rg_*text -> ResourceGroupText Args: text: the text to transform Returns: A Camel Cased string. """ suffix = text[3:] if suffix == 'id': suffix = 'ID' elif suffix == 'resourcetypeid': suffix = 'TypeID' ...
722b8f3b361bd93368b36c1e506d7b47a796118e
577,943
def get_remote_field_model(rel): """Return the model a relation is pointing to. This is equivalent to ``rel.to`` prior to Django 1.9 and ``remote_field.model`` in 1.9 onward. Args: rel (object): The relation object. Returns: type: The model the relation points ...
ebe8462aac2fc99588f67af87c69129cd19ceea0
577,953
def get_all_image_index(self): """ Retrieves all image ids """ return list(self.image_infos.keys())
482524d6214d89ec348b7814535574c9f591f7ee
577,954
def is_job_array(job): """ Check if the given job is an array. :param job: the job dictionary returned by AWS Batch api :return: true if the job is an array, false otherwise """ return "arrayProperties" in job and "size" in job["arrayProperties"]
02753600e8c0842a8b6867af885819c9ee6bcc82
577,959
def vectorDistance(v1, v2): """ this function calculates de euclidean distance between two vectors. """ sum = 0 for i in range(len(v1)): sum += (v1[i] - v2[i]) ** 2 return sum ** 0.5
637f237e4620058aaaca0b0a93fd2ba70e173cad
577,961
import hashlib def hash_password(raw_pass): """Hashing raw password and split hash to prefix and suffix :param raw_pass: password in raw format :return: tuple (prefix of hash, suffix of hash) """ hash_pass = hashlib.sha1(raw_pass.encode("utf8")).hexdigest().upper() hash_pass_prefix = hash_pas...
bc88dbe768cb4ee62b75ab1979ff1ffb52bb0376
577,962
def filter_by_length(corpus, text_var, min_length=300): """Remove very short documents from a corpus""" filtered = corpus.loc[[len(doc) > min_length for doc in corpus[text_var]]] filtered = filtered.reset_index(drop=True) return filtered
e6bb2738080b3ba17e51f0cd33dbd31253e405cd
577,963
def prime_factors_ver1(num): """ 分解质因数: 试除法 遍历num所有可能的因子,返回所有实际的因子 """ result = [] for i in range(2, num + 1): s = 0 while num % i == 0: # 判断是否可以继续整除 num = num / i s += 1 if s > 0: # 即可以整除i for k in range(s): result....
de3ebaeb98778269eed2f24f44fd6bb10dc11dd0
577,964
def __open_osm(osm_file): """Read an OSM file and save contents in a list Parameters: ----------- osm_file -- File with OSM format Returns: -------- osm -- list with lines of the read file """ archivo = open(osm_file,"r") osm = archivo.readlines() archivo.close() ...
7bdd6b7087e404d253185ee0ccd96b1721c61703
577,968
def parse_target_composition_row(r): """parse target composition row data in numerical values Args: r (str): input row string, like H 1 061.54 010.60 Returns: tuple of ( Symbol, Atomic number, Atomic Percent, Mass...
edb1cf408058b0cfc9ea6c375510d5438a7243b4
577,969
def peek(file, n=1): """ Reads n lines ahead in a file without changing the file object's current position in the file Args: - file: a text file - n (int): how many lines ahead should be read, defaults to 1 Return: - line: last line read """ pos = ...
56d42cbebe63c63ebf9daabbac933a901d368a75
577,971
def extract_salient_features(dict1, dict2, alpha=1.0): """ Score salient features given to dictionaries. Args: dict1: First set of feature coutns dict2: Second set of feature counts alpha: The amount of smoothing (default 1 to Laplace smoothed probabilities) Returns: Laplace smoothed differenc...
952c975d7d2d831099388d2808f67f83d3528c19
577,974
def clean_m3u_from_extended_tag(content: str) -> str: """Remove #EXTM3U and empty lines.""" clean_content = content.strip() if clean_content[:8] == "#EXTM3U\n": clean_content = clean_content[len("#EXTM3U\n"):] return clean_content.strip()
b1fc84ec26980d29b5c4bca69083719e95182997
577,975
def getLimOrderValue(odds, volume): """ Calculate max price matched (to lay) and min (to back) in order to place a limit order """ if volume>0: #BACK odds_back = odds[odds[:,1]>0] odds_back = odds_back[odds_back[:,0].argsort()] odds_back = odds_back[::-1] ...
e1d0c08d47d692a563572afa49dc829638c32de1
577,976
import hashlib def md5sum(file: str) -> str: """ Create a strings with the md5 of a given file :param file: filename of the file whose md5 is computed for :return: md5 string """ md5_hash = hashlib.md5() a_file = open(file, "rb") content = a_file.read() md5_hash.update(content) ...
b2284ccb0779c06648ae87299c688c478f7119ca
577,980
from typing import Callable def save_func_and_its_meta(func: Callable) -> Callable: """Decorator for a wrapper function. Updates a wrapper function to look like the wrapped function (func). To use: add decorator @save_func_and_its_meta(func) before the wrapper function declatation. ...
85107e6dcd79ec576906d4e5390cf54ef11a5309
577,981
import requests def getDataFromAPI(endpoint = "https://jsonplaceholder.typicode.com/users/"): """ This function will call a GET request on the provided API endpoint """ try: dataFetchedFromAPI = requests.get(endpoint) dataFetchedFromAPI.raise_for_status() except requests.excep...
bc6009f5746d345fabc2e8be6d45a2e44849363c
577,982
import typing def set_if_exists(d: dict, k: str, v: typing.Any) -> dict: """ Given a dict ``d`` sets the key ``k`` with value of config ``v``, if the config value ``v`` is set and return the updated dictionary. .. note:: The input dictionary ``d`` will be mutated. """ if v: d...
04b9a425ef1a592f0c4306946206f23598e82f8c
577,983
def any(sequence, test_func = None): """ Returns 1 if for any member of a sequence, test_func returns a non-zero result. If test_func is not supplied, returns 1 if any member of the sequence is nonzero (e.g., not one of (), [], None, 0). """ for item in sequence: if test_func: ...
744f7d85bdc3df1acb9b92bff7881686f9d20ac1
577,987
def lsscale(self, nl1="", nl2="", ninc="", rx="", ry="", rz="", kinc="", noelem="", imove="", **kwargs): """Generates a scaled set of lines from a pattern of lines. APDL Command: LSSCALE Parameters ---------- nl1, nl2, ninc Set of lines (NL1 to NL2 in steps of NINC) that define...
b29ce5361c0d0cf746c1d8dfa80f69eecb65bcb3
577,988
def pascal_triangle(n_rows): """ Compute Pascal triangle. Taken from https://stackoverflow.com/questions/24093387/pascals-triangle-for-python. Parameters ---------- n_rows : int Number of rows in the Pascal triangle, i.e. maximum number of elements :math:`n`. Returns ------- ...
c9b2c867a690775aacd9fb47bdc9b953f02ac2e6
577,998
def extract_frequency(word, dictionary, return_as_binary_vector=False): """ This function extracts frequencies for a given word from a dictionary of frequencies Args: word (str): Word dictionary (dict): Dictionary with frequencies return_as_binary_vector (bool): Returns ...
94e771d693a40efe3eb7d1c43406d2cee4287f9e
577,999
from typing import Dict from typing import Tuple def get_dendogram_bounds(dg: Dict, data_range: int) -> Tuple[int, int]: """ function to calculate bounds and reduction factor for plotting dendograms :param dg: dictionary output from scipy dendogram calculation :param data_range: length of data in d...
21a7196e4ae29c9b3e82e82cc9877a5b14b71643
578,001
import math def npow(base: float, exp: float) -> float: """Perform `pow` with a negative number.""" return math.copysign(abs(base) ** exp, base)
d0d5e42316e35be44ce510a02dcbc2e6921cbe8e
578,002
def get_vocabulary_info(feature_info, file_io): """ Extract the vocabulary (encoding and values) from the stated vocabulary_file inside feature_info. Parameters ---------- feature_info : dict Dictionary representing the configuration parameters for the specific feature from the FeatureConfi...
4e336995c8364b23da325c17e1a63fe2ea69dc27
578,004
def lerp(p0, p1, t): """Linear interpolation.""" return (1.0 - t) * p0 + t * p1
d3e2c8417ac78ecf99549a32aae9787b00f4cd10
578,008
def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:]
78060386767df8742c235041091561a2255cb89d
578,013
def remove_first_last_sec(wav, sr): """ Removes the first and last second of an audio clip. :param wav: The audio time series data points :param sr: The sampling rate of the audio :return: np.array """ return wav[sr:-sr]
67803c1f037e8e50a0f0c85c5ff1f01a47be1b1d
578,015
import functools def filter_for(function): """ A decorator for slicing data from a list of dictionaries. If the wrapped function is called with:: field=<some key> extract data from a list of dicts if field is specified given a structure like:: [{'bw': 2029.6, 'io': 458152.0, 'io...
64ed780b6e7190a26b469c43cda2e7ec08c8ba6b
578,017
def rivers_with_station(stations): """Build and return a set of all rivers with at least one station.""" rivers = set() for station in stations: rivers.add(station.river) return rivers
a3460a83e49546a548310605c32407c984f48293
578,018
from io import StringIO import pprint def _get_pretty_string(obj) -> str: """ Return a prettier version of obj. Parameters ---------- obj : object Object to pretty print Returns ------- str Pretty print object repr """ sio = StringIO() pprint.pprint(obj, s...
828fc5fd2404ba99392529a87522157847008eb1
578,021
def inheritdoc(cls, gap="\n"): """ Decorator to automatize the inheritance of documentation from a class method. Example ------- >>> from skhep.utils.decorators import inheritdoc >>> class ADerivedClass(ABaseClass): # doctest: +SKIP ... @inheritdoc(ABaseClass) ...
df2a3878c1ef77700e77a35d5d4eb0e21b32691f
578,025
def is_weekday(d_or_dt): """Check if a datetime is weekday. """ return d_or_dt.isoweekday() not in [6, 7]
3ceb48dd22f3c6736f133cdf6a6635b7363422ec
578,027
import itertools def test_permutation_combinator(container_, pairs_): """ r-length tuples, all possible orderings, no repeated elements permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC """ return list( itertools.permutations( container_, pairs_ ...
bc0f6c96dd0aa7352376545562020d306d203335
578,032
def assess_gene_knockout_viability(model, gene_name): """Assesses viability of model when `gene_name` is knocked out. Returns True if viable, False if lethal.""" with model: model.genes.query(gene_name).pop().knock_out() if model.optimize().objective_value == 0: return False ...
509adf6474a9105c675d09cc7d299ca25bec125a
578,036
import itertools def peek(seq): """ Retrieve the next element of a sequence Returns the first element and an iterable equivalent to the original sequence, still having the element retrieved. >>> seq = [0, 1, 2, 3, 4] >>> first, seq = peek(seq) >>> first 0 >>> list(seq) [0, 1, 2, ...
808aa91b92ddcb2976289b4162b865aa35af0ebe
578,037
def square_n(n): """Returns the square of a number""" return int(n * n)
7d6e647b4e06758deec474b4355151f79afc15b3
578,039
def linear(iteration: int, frequency: int = 10) -> bool: """Optimize hyperparameters at equally spaced intervals Args: iteration (int): current iteration frequency (int, optional): Spacing between the True outputs. Defaults to 10. Returns: bool: True if iteration can be divided by ...
c99a5b70c3ad2418565cfd7bc8b8fabf163e2f5b
578,043
def fact(num): """ Factorial of positive integers """ if num < 0: raise ValueError("Cannot compute factorial of negative numbers") if num == 0: return 1 prod = 1 for i in range(2, num + 1): prod *= i return prod
3466c24961a8fbfc6ce5054441f826cb19e5148d
578,053
def get_floorplan_images(states, floorplan, map_range_x, map_range_y, scale_factor=1): """ Get floorplan images from floorplan class """ size_x = int(map_range_x * scale_factor) size_y = int(map_range_y * scale_factor) ims = floorplan.rgb(states, (size_x, size_y)) return ims
cceb4d058ea9bb047f1a9d13d5ffe2d35c48581c
578,055
import json def find_dtoverlay_config(variable_list): """ Find value and id of BALENA_HOST_CONFIG_dtoverlay or RESIN_HOST_CONFIG_dtoverlay. Return None if it doesn't exist. """ current_dt_overlay = None dt_overlay_var_id = None for variable in variable_list: if variable["name"] in...
9c9b5c9b2c77e1088eb99ea75d895fddce12500c
578,060
import logging def remove_rn(reference_node_name): """ Removes the RN from the end of a reference node's name :param reference_node_name: node with a reference prefix :return: Node with reference prefix removed """ flg = logging.getLogger("lettuce.xgenSetup.remove_rn") last_r = reference...
51763bd9cb99d0172a10741e1604dff6c6baac4a
578,061
def get_attrib_if_exists(xml_elem, key): """ Checks if the attrib key exists and returns either the val or none. :param xml_elem: xml element to check :param key: key of the attribute :return: vale | none """ return xml_elem.attrib[key] if key in xml_elem.attrib else None
1f15bedb29bb3f991977fd6fcbcdb324332f17b4
578,068
import re def is_valid_id(id): """checks if an id is valid Args: id (str): The id of a note Returns: bool: True if the id is valid """ if re.match(r'^[0-9a-f]{9}$', id): return True else: return False
449868ff3198b39d69721a336a451ed64d9d1c20
578,069
def cell_content(cell): """Return cell's content ready to be used in SPARQL requests. """ # Remove references for sup in cell.findAll('sup'): sup.decompose() # Remove breaks for br in cell.findAll('br'): br.decompose() # Try find a a = cell.find('a', href=True) if ...
90172fd2372855219bb70218e7764e42835adf6b
578,070
import configparser def load_status(status_file): """ Load pipeline status Args: status_file (string): name of configparser file Returns: configparser.RawConfigParser """ config = configparser.RawConfigParser() gl = config.read(status_file) return config
bd118146e10f632c1edfed7c362eb5a39fa61069
578,072
def read_data_from(file_: str) -> dict: """Get ingredients and allergens from file.""" foods = {} fio = open(file_, "r") for idx, food in enumerate(fio): foods[idx] = { "ingredients": food.split(" (")[0].split(" "), "allergens": food[:-2].split("(contains ")[1].split(", "...
a83b5f63bf987f5ff523821a33c9c397e93e7f9b
578,073
def get_key_by_value(dict_, value): """Return key by value.""" for key, val in dict_.items(): if value == val: return key return None
5239268839759b567ba122ab5dacc5c7c9fdc7d0
578,075
import time def elapsed_time(t1, verb=False): """ Returns the time between t1 and the current time now I can can also print the formatted elapsed time. ---------- t1: float The initial time (in seconds) verb: bool, optional Optionally print the formatted elapsed time return...
47df24ca9391283c894dd18733c60139f718ce83
578,076
def get_hosts(leases): """ get list of host in leases leases is a dict from parse_dhcpd_config return hosts as list """ return leases.keys()
4e3f11901bb8634a7b4efc42c4d3ebe4945151ac
578,079
def search_url(url, table, conn): """Attempts to find a row in the table in the database conn with the given url. Returns its id value if it is present, returns False otherwise.""" query = 'select * from %s where original="%s"' % (table, url) result = conn.execute(query).fetchall() if not result: #u...
883c133ac805ff00e58cee097797164ded158f87
578,083
def cleanup_ocr_text(txt): """Do some basic cleanup to make OCR text better. Err on the side of safety. Don't make fixes that could cause other issues. :param txt: The txt output from the OCR engine. :return: Txt output, cleaned up. """ simple_replacements = ( (u"Fi|ed", u"Filed"), ...
058dd6a951dcf8c302a1ae6b01ed103987c67015
578,085
def line_contains_all(the_line, items): """ Determine if all of the members of items are present in the string, if so, return True :param the_line: The input line to check against :param items: The (list of) check items :return: True if all items found, False otherwise """ for the_item in it...
20302f70d92e16bd3d4479d438999d0a777195ed
578,095
def expand_gtf_attributes(df): """Extracts metadata from attributes and saves in new dataframe columns The following fields are parsed and provided as new columns: - gene_id - transcript_id - gene_name - appris_principal_score (float). Features without a principal score are assigned a scor...
cff416ac9c90d8af3c910bec4457f1731d4ee4ca
578,099
from typing import Callable import random def rand_compute_name() -> Callable[[], str]: """return a random compute name string, e.g. testxxx""" return lambda: f"test{str(random.randint(1, 10000000000))}"
10154e31a7996257b9f8fcf451e10f3f57be3e9b
578,100
def minimums(some_dict): """ Returns a list of all keys with the minimum value within a dictionary :param some_dict: dictionary with values as ints :return: list with all keys that had the minimum value """ positions = {} min_value = float("inf") for k, v in some_dict.items(): if v...
413d1ee9de67a47e1ca680fd083def786b9c89fd
578,101
def pretty_duration(seconds): """ Returns a user-friendly representation of the provided duration in seconds. For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s" """ if seconds is None: return "" ret = "" if seconds >= 86400: ret += "{:.0f}d".format(int(seconds / 86400))...
2f18bddfcf15bc1f71f28c8853e1fc51d8a4c559
578,103