content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def adjust_asymp_with_chronic(asymp_column, chronic_column): """ Remove asymptomatic flag for people with chronic disease Parameters ---------- asymp_column : A boolean array storing people with asymptomatic infection chronic_column : A boolean array storing people with chronic diseas...
7848b09c36ee183e6a884647326822ab6f254ac5
634,021
def modulus(angka1: float, angka2: float) -> float: """ hasil dari modulus antara angka1 dan angka2 >>> modulus(3.0, 2.0) 1.0 """ return angka1 % angka2
13442aabaecff54ebd036f48d5c27af002584354
634,022
from typing import NamedTuple def create_template_struct(target: NamedTuple) -> dict: """ вспомогательная функция, создает шаблон словаря заданной в коде структуры :return: """ result = {'data': {'ssh': {'status': 'ssh', 'result': ...
ab02af81bf66a09844228f6cf39e34c3c9f896cd
634,023
def flip_dict_of_lists(dict_of_lists, dict_type=None, key_func=lambda k: k): """ Returns a "flipped" dictionary of lists from the given dictionnary of lists. What I mean by "flipped" is this: >>> d = {'a': [1, 2], 'b': [3, 1], 'c': [2]} >>> flip_dict_of_lists(d) {1: ['a', 'b'], 2: ['a', 'c'], ...
041b50f8bb3855145e6867eea30db61dc333235e
634,025
def wrap_text (text, font, base_width): """Wraps given text into multiple lines to fit into the given width Breaks the given text into a list of lines, so that the text when rendered with font won't horizontally overflow beyond base_width. If possible, lines are broken after complete words. Args: ...
f79eca00a8e1f10e540313e13a9bf2feeea1b83e
634,026
import argparse def parse_cli_args(): """ Command line parser for subnet of interest. Args: --ip 0.0.0.0 Returns: String, e.g. 0.0.0.0 """ parser = argparse.ArgumentParser(description="IPv4 address of interest.") parser.add_argument("--ip", action="store", type=str,\ ...
665199f5add409e73bf6d0ce7b19a9be190bfc52
634,028
from typing import Callable import inspect import asyncio def is_awaitable(call: Callable) -> bool: """Check if function returns awaitable object. Arguments: call: function that should be checked. Returns: Result of check. """ if inspect.isfunction(call) or inspect.ismethod(call)...
14015d0dd30cc3e35e0c5b0508aff7d401f7d5ac
634,029
import hashlib def HashFile(file_path): """Calculate the sha256 hash of a file. Args: file_path: (str) path to the file. Returns: [str]: The sha256 hash of the file. """ sha256 = hashlib.sha256() with open(file_path, 'rb') as f: for b in iter(lambda: f.read(2048), b''): sha256.update(b...
709125489af5596a241f9f888c5068f51b38c74e
634,030
def prettify_reference(ref, verbosity=2): """ Returns the parsed string version of the reference (dict) and strip down based on verbosity Keyword arguments: ref -- reference parsed by refextract as a dict verbosity -- the level of verbostiy for the reference composition (default 2) """ if verbo...
301ad1c4c0c959af5dd30f93ac0c011d3a9d5315
634,031
import torch def cxcy_to_xy(box): """ :param box: input boxes. Should be in center sized coordinates and size of (N,4) where N=number of priors :return: center coordinate boxes converted to (x_min,y_min,x_max,y_max) coordinates """ start = box[:, :2] - (box[:, 2:] / 2) end = box[:, :2] + (box[...
0e347073292ad27c029669e7a12bd7e8928ec2d1
634,032
def get_array_sizes(list, name): """ Expand the elements of an array for 1, 2, and 3D arrays """ t_list = [] if len(list) == 1: for t in range(0, list[0]): t_list.append(name + "[%s]" % t) elif len(list) == 2: for t1 in range(0, list[0]): for t2 in range(...
4cb6848e911fd8835d2fd69ab06c4b552766ac0b
634,033
import re def do_slugify(inp): """Convert an arbitrary string into a url-safe slug.""" inp = re.sub(r'[^\w\s-]+', '', inp) return re.sub(r'\s+', '-', inp).lower()
1d42419169e3fcc323a39bdcd636507d500acd8f
634,034
def find_count(substring, string): """finds the number of occurences of substring in string""" counter = 0 index = string.find(substring) while index >= 0: counter += 1 index = string.find(substring, index + 1) return counter
4cf562045c20d8acbfe372bc315c50f089925663
634,035
def HSVtoRGB(h, s, v): """ Convert Hue-Saturation-Value into Red-Green-Blue equivalent. Parameters: h - Hue between [0.0, 360.0) degrees. red(0.0) to violet(360.0-). s - Staturation [0.0, 1.0] v - Value [0.0, 1.0] Return Value: (r, g, b) 3-tuple with each color betw...
a160c3c38b56f335f32e6b8080dcc12fca2b2829
634,036
import torch def squared_distance(x1, x2=None): """ Given points x1 [n1 x d1] and x2 [n2 x d2], return a [n1 x n2] matrix with the pairwise squared distances between the points. Entry (i, j) is sum_{j=1}^d (x_1[i, j] - x_2[i, j]) ^ 2 """ if x2 is None: return squared_distance(x1, x1) ...
ed6662ea36b0c95b89b01c6ca1b6b9ccdd3c4e9e
634,037
import sys def extract_vars(*names,**kw): """Extract a set of variables by name from another frame. :Parameters: - `*names`: strings One or more variable names which will be extracted from the caller's frame. :Keywords: - `depth`: integer (0) How many frames in the stack ...
484125a939131caf1c262b0dfbc59a4799aef741
634,038
def colorGrad(value, colorMin, colorMax, minValue, maxValue): """ returns a middle rgb color value based on the distance between max and min """ c_range = abs(maxValue - minValue) v = value - min(maxValue,minValue) v_pct = v/c_range #v_pct *= v_pct #print value, v_pct, colorMin, ...
62997ae071880c28a1d65fe852afa46c5eae38b7
634,039
import math def straightness_imperfection(z, length, delta_global, oos_axis, **kwargs): """ Returns the out-of-straightness imperfection of the node. :param float z: z coordinate of node :param float length: total length of the component :param float delta_global: maximum amplitude of the out-of-stra...
6148eb8d9f24b55a5ee1efa5eb43f23f4476b02a
634,041
def filter_hsv_to_h(hsv, output_type="int", display_np_info=True): """ Obtain hue values from HSV NumPy array as a 1-dimensional array. If output as an int array, the original float values are multiplied by 360 for their degree equivalents for simplicity. For more information, see https://en.wikipedia.o...
0ae0940442cd9dfa7aeb7728d3b596d88362f312
634,042
def get_viewstate_value(page): """ Find for content of the viewState param in source code :param page: The code of the page for search in it :return: The content of the viewstate param or None """ page = str(page).replace("\\n", "\n") full_param = "name=\"javax.faces.ViewState\"" for i ...
47aad086f761ed7bec91bb318bbe31a5c1db47d5
634,043
def count(seq): """Count the number of items in sequence that are interpreted as true.""" return sum(map(bool, seq))
7ab0b238f8f5110f06e35876bd76431df69c559c
634,044
def prepare_data(df): """It is used to seperate dependent variables and independent variables Args: df (pd.DataFrame): its the pandas DataFrame Returns: tuple: it returns the tuples of dependent variables and independent variables """ X = df.drop("y",axis=1) y=df["y"] return X, y
e38a1d2511c8eed6eb72ba5ed51035ab267e72dd
634,045
def convert_inf(x): """ The tqdm doesn't support inf values. We have to convert it to None. """ if x == float('inf'): return None return x
8c20588ed1905a8d8df8f4be78a3f8e0f9a2c36f
634,046
import argparse def parse_args(): """ Parse arguments for this function """ parser = argparse.ArgumentParser() parser.add_argument("--output_location","-o",help="location to store output",default='sample_images') parser.add_argument("--catalog","-c",help='SEVIR catalog',default='CATALOG....
da7a46d53e536d4632ec9681825ae180494c3222
634,047
def number_to_digits(num): """Return sorted list of digits in number.""" return sorted(int(ch) for ch in str(num))
cc09154db0f587da5042bc06236e793411a0c5ab
634,048
import typing import os def file_paths_in_folder(folder_path: str) -> typing.List[str]: """Return sorted list of paths of files at a directory (and its subdirectories)""" file_paths = [] for root, _, file_names in os.walk(folder_path): for name in file_names: file_paths.append(os.path....
552205e39bc7cea4489bbb340dfbed07179273fa
634,049
from bs4 import BeautifulSoup def parseCategoryHTML(HTML_Source): """ カテゴリページを解析し、ランキングページのURLを取得する。 Parameters ---------- HTML_Source : str カテゴリページHTMLソース。 Returns ------- ranking_pg_list : str[] ランキングページリスト。 """ soup = BeautifulSoup(HTML_Source, 'html.parse...
91456fac09cf5f57fbf06acb1984735b3d59446e
634,050
import argparse import random import string import sys def parse_args(path): """ Parse input arguments """ parser = argparse.ArgumentParser('Convert_Image.py') parser.add_argument('--AudioFile', dest='AudioFile', type=str, help='(require)Please enter audio file for predicti...
9a3cdddc52b46ce725723c60d1c851411403f33c
634,051
def dont_scale(array, *_, **__): """identity function plus a black hole for args and kwargs""" return array
369c0e1037501e7fa60fd67700f8e65fd642c3dc
634,052
import re def match_swi(fname, json_data): """ Match SWI images """ folder, suffix, attrs, md = "swi", None, {}, {} desc = json_data["SeriesDescription"].lower() if "swi" in desc: if "sbref" in desc: suffix = "sbref" else: suffix = "swi" if "Ech...
c980c28e1bcd383c1784aa5d1e8a8b25db66fdab
634,053
import os import json def get_synced_folders(): """ Reads the appropriate file to get the synced_folder information so filepaths can be converted. Will look for the file 'synced_folder' in '/.vagrant_info'. Vagrantfile setup example: config.vm.synced_folder \ ".vagrant/machines/d...
d9e4a642d7d7d9d6aeab32cd41d9d0bb7933dd43
634,054
def strescape(txt): """ Convert bytes or text to a c-style escaped string. """ if type(txt) == bytes: txt = txt.decode("cp1251") txt = txt.replace("\\", "\\\\") txt = txt.replace("\n", "\\n") txt = txt.replace("\r", "\\r") txt = txt.replace("\t", "\\t") txt = txt.replace('"',...
63dedacbcf355016fba153ed4565053d02b3459f
634,055
def get_counts_and_averages(ID_and_ratings_tuple): """Given a tuple (bookID, ratings_iterable) returns (bookID, (ratings_count, ratings_avg)) """ nratings = len(ID_and_ratings_tuple[1]) return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings)
537cda9c9dab8cdf73a85ebff0d788b8af2b1d19
634,056
def bindigits(n:int, bits:int)->str: """Convierte a binario un numero de complemento A2 en caso de negativo, normal en caso de ser positivo Args: n (int): E.g 7 bits (int): eg 3 Returns: str: E.g '001' """ s = bin(n & int("1"*bits, 2))[2:] return ("{0:0>%s}" % (bits)).f...
57f5a0ce686953e75f29d53d8e943fc9923a747d
634,057
def get_edge_label_dict(graph, attr_type="label"): """ Return a dict with edge tuple as key and edge attr/label as value. If both are required, the label will be the first entry in the list, and the remaining attributes will come after""" d = {} if len(graph.es.attributes()) > 0: if len(att...
5a9c7901781f16e39c01ba2dfe6c116f3d399f91
634,058
def get_parameters(function, **kwargs): """ Return a list of parameters from a SSM function, like describe_parameters or get_parameters_by_path. """ next_token = "" response = function(**kwargs) parameter_list = response["Parameters"] while "NextToken" in response: next_token = r...
ca9fe2f942399040d78e6a2ed9e49a11ceed4c6a
634,059
from typing import Union def _decode(str_like: Union[str, bytes]) -> str: """Convert to string from bytes/str/... """ if isinstance(str_like, bytes): return str(str_like, 'utf-8') return str(str_like)
827f6ca4915eae992992504968808d1f773007c1
634,060
def format_time(start, end): """ Format length of time between start and end. :param start: the start time :param end: the end time :return: a formatted string of hours, minutes, and seconds """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{...
5e6879251c6f253c0260dd31fc455f0c87901ab9
634,061
import os def _files_from_dir(path): """ Recursive helper function for extracting a list of files within a directory, in a platform-independent order. """ assert os.path.isdir(path), "Not a directory: {}".format(path) filepaths = [] # Explicitly sort contents to get a platform-independen...
356a49ca8c5e3d201d122020e48c1a61415c8da1
634,062
from typing import List def _ternary_search(array: List[int], value, low: int, high: int) -> int: """ The implementation detail of the recursive implementation of ternary search. :param array: is the array to search. :param value: is the value to search for. :param low: is the lower bound of the p...
f07a81c640ef9bafe31f01c72bf7ce5af6d30604
634,063
def encode_dict_in_bash(dictionary: dict) -> str: """ Make dict into a series of key value pairs readable on command line. """ pairs = [] for key, value in dictionary.items(): pairs.append(f"{key}={value}") return " ".join(pairs)
363557734487d3ac6f7e209d76df1f780d553b47
634,064
import os def identify_inputs(args, logger): """Return True if input directory exists and contains files""" if not os.path.isdir(args.indir): logger.error("Input directory %s does not exist", args.indir) return False infiles = [ fname for fname in os.listdir(args.indir) ...
810a9b2ae46525e8326be59f615ec60a422d2664
634,065
def create_address(house_number, post_code): """ Creates immutable address data structure :param house_number: user's house number (string) :param post_code: user's post code (string) :return: (tuple) """ return (house_number, post_code)
f24ba0bcbfe396fd120d07748f31fab006ee21b7
634,066
def smooth_interval(interval): """Takes only the first item merged, everything else is tossed""" for item in range(3,8): interval[item] = interval[item].split(",")[0] return interval
b341d079b0b7c79be6ac841386b724cd04ae3017
634,067
import random import string def random_string(size: int) -> str: """Get a random string""" return "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(size) )
d30faee16486c4ad7e7fcb717789a5ce8c9921b7
634,068
def chunks(items, size): """ Split list into chunks of the given size. Original order is preserved. Example: > chunks([1,2,3,4,5,6,7,8,9], 2) [[1, 2], [3, 4], [5, 6], [7, 8], [9]] """ return [items[i:i+size] for i in range(0, len(items), size)]
960bc6ba7775ce66c3deb6c07966a9157b3e3e2c
634,069
def get_sector_narrative_and_single_from_multi(sector_to_match, switches): """Get all switches of a sector if the switches are defined specifically for a sector. If the switches are not specifically for a sector, return all switches Arguments ---------- sector_to_match : int Sector to f...
97f2482c252fb437ca405743b012f11ec3f24d11
634,071
def gcloud_path(): """Returns the path to the gcloud command. Requires gcloud to be on system PATH""" return 'gcloud'
67058a7c97b625311d068bf1f3096ebad7c2939e
634,072
def strpar(cfg, section, key): """String representation of a section/key combination""" return "[{}] {} = {}".format(section, key, cfg[section][key])
3c1137e3e8b539e3bb1b9e621d916bc1d70b30bd
634,073
def start(osi): """Start the timer""" return osi.to_process('start', [])
69dd272cc9a8802f60c5e3fe2b617063645c6bde
634,074
def prepare_test(func): """ :param func: :return: """ def wrapper(): """ :return: function called """ print("\n" + str(func) + " ----------------\n") return func() return wrapper
fda7d654af509db6aa3834f22e0035a60c72a52c
634,075
from typing import List def rob(numbers: List[int]) -> int: """https://leetcode.com/problems/house-robber/""" # f(k) = max(f(k – 2) + numbers[k], f(k – 1)) previous_max, current_max = 0, 0 for value in numbers: current_max, previous_max = max( previous_max + value, current_max), c...
bd0155a177d774dae6af402fc68816b4f7009456
634,076
def are_version_compatible(ver_a, ver_b): """ Expects a 2 part version like a.b with a and b both integers """ (a_1, a_2) = ver_a.split('.') (b_1, b_2) = ver_b.split('.') (a_1, a_2) = (int(a_1), int(a_2)) (b_1, b_2) = (int(b_1), int(b_2)) if a_1 < b_1: return False if (b_2 > ...
628f814d6936485426632f0ad9b01081e4960401
634,077
def check_mutually_exclusive(options, *opts) -> bool: """ Checks if there are mutually exclusive options >>> obj = lambda: None >>> obj.attrib1 = 1 >>> obj.attrib2 = 2 >>> check_mutually_exclusive(obj, *["attrib1"]) False >>> obj = lambda: None >>> obj.attrib1 = 1 >>> obj.attrib...
ea5caf4eb237fef795ef10ec65d1e1442ef951a0
634,078
def fmttimeshort(n): """ fmttimeshort """ if n == 0: return 'complete!' try: n = int(n) assert n >= 0 and n < 5184000 # 60 days except: return '<unknown>' m, s = divmod(n, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) if d >= 7: return '-' eli...
044a9e31cdcd2fbc7ed1a32fca0df084d267cbfe
634,079
import subprocess def is_git_ancestor(workdir, parent_check, child_check): """ Figures out if the second is a child of the first. See git merge-base --is-ancestor """ if parent_check == child_check: return False proc = subprocess.Popen( ['git', 'merge-base', '--is-ancestor', ...
1bdb46b8a6cb8c0bdbe67c14ad36f93dee555b77
634,080
def add_commas(n): """ Receives integer n, returns string representation of n with commas in thousands place. I'm sure there's easier ways of doing this... but meh. """ strn = str(n) lenn = len(strn) i = 0 result = '' while i < lenn: if (lenn - i) % 3 == 0 and i != 0:...
5f064d4bf4f5bf8330fe68e69bd29178d7d857f4
634,081
def split_args(args): """ Split a list of argument strings into a dictionary where each key is an argument name. An argument looks like ``crop``, ``crop="some option"`` or ``crop=my_var``. Arguments which provide no value get a value of ``True``. """ args_dict = {} for arg in args: ...
ae51f09da1c40395c4edc24f9528285f0e48d136
634,083
def phi_psi_omega_to_abego(phi: float, psi: float, omega: float) -> str: """ :param: phi: The phi angle. :param: psi: The psi angle. :param: omega: The omega angle. :return: The abego string. From Buwei https://wiki.ipd.uw.edu/protocols/dry_lab/rosetta/scaffold_generation_with_piecewise_blue...
0fb849b0f9600e6bb9fdc721718aa564dd6639f0
634,085
import cmath def _amp_phase_ ( self, x , *a ) : """Get the phase of amplitude >>> f = ... >>> r = f.amp_phase ( x ) """ return cmath.phase ( complex ( self.amp ( x , *a ) ) )
1be033fb7921c46e3c29558e18738109ca3e7026
634,086
def get_feature_3(token1: str, token2: str) -> str: """Conjunction of features 1 and 2.""" if token1 == "": token1 = "..." if token2 == "": token2 = "..." return token1 + "^" + token2
4e6298da19cf9c1172c8df1c77bc42ac131fb596
634,087
def disqus_id_for(obj): """ Returns a unique identifier for the object to be used in DISQUS JavaScript. """ return "%s-%s" % (obj._meta.object_name, obj.id)
f610a18d3567be669b202e1897ec50fef1c8405e
634,088
import codecs def complete_vocabulary(filename, initial_words, wordlength, vocsize, encoding="utf-8"): """ Reads words of length <wordlength>, from <filename>, until the number_of_words_read+len(initial_words)=vocsize. Returns a dictionary of words and their frequency. :param filename: text file, without...
e2b6ba39ce82a0147064d3a33781cda3d63d3112
634,090
def get_missing_elements(match, dmrs): """ Returns a list of elements of dmrs for which no match was found.: :param match A Match object. :param dmrs A DMRS object for which the match was searched. :return A list of nodeids and links. """ matched_nodeids = list(zip(*match.nodeid_pair...
3707188596cd235adc472f25203f990ff98e1dd1
634,091
def embedding_by_subnet(dependences_matrix): """ 获取词语依赖特征的embedding :param dependences_matrix: :return: """ print('embedding_by_subnet') res = [] return res
fa4fcf30195384aaece9e47979e5225e01a85a1d
634,092
def arxiv_url_sanitizer(url): """ as of now, just converts arxiv.org/pdf/ to arxiv.org/abs """ # if its an arxiv pdf url then if url.find("pdf") != -1: url = url.replace("/pdf","/abs") url = url.replace(".pdf","") return url
32302c33b1065030ab62c7b166d77216f439acf0
634,093
def misalign(data): """Just misalign.""" new_data = {k: v.replace("-", "") for k, v in data.items()} return new_data
451d83e6cc1e37211e9e7e27c5277a5498431787
634,094
def __calculate_metrics_merged(results): """ calculate the matrics for the merged results updates the dataframe in place """ results["HitMiss"] = results['HitMissStack'] / (results['Trades'] / 2) results["DoubleHit"] = results['Profit'] / (results['Trades'] / 2) / 200 return results
50e167846bf61a5da8d9e7f285b767f17d14d4c3
634,095
import statistics def average_validation_error_has_not_decreased_enough(histories, tolerance=0.01): """ Function that returns true if the average validation error of the penultimate iteration has not dropped by a significant amount """ # get the corresponding histories last_history = histories[...
6bcb8085f363bae2c5aae9d1327505c2ea41d64b
634,096
from typing import Union from typing import Optional import re def get_error_code(error_field: Union[str, None]) -> Optional[int]: """Get the error code part of the `error\ <https://docs.cometd.org/current/reference/#_code_error_code>`_, message \ field :param error_field: `Error\ <https://docs.c...
45c8b9cce27650652c126e5840f4fb610a08796d
634,097
def hill_equation(val, diss_cf, hill_cf): """ Hill equation :param val: input value :param diss_cf: dissociation coefficient :param hill_cf: Hill coefficient :return: Hill equation for input *val* """ if val == 0: return 0 else: return 1 / (1 + (diss_cf / val) ** hill...
96ee40c173a160ee4f557bd7ee125869927a3cd4
634,098
import re def _check_error(req, parser): """Checks for errors on the document.""" # HACK: Using regex to find list, tbgclient.parsers cannot parse document correctly error = re.findall(r'<div class="inbox error-info">(.+?)</div>', req.text, re.DOTALL) if not error: return None error = re.f...
04b7516a8ef9ae83823c8ee04a876195be895ad3
634,099
def get_words_prob(test_words_list:list, normal_words_freq:dict, spam_words_freq:dict, normal_file_number:int, spam_file_number:int, max_prob_num:int): """ Calculate the probability of spam for every words, p(s|wi) Args: test_words_list: the words list to test normal_words...
87fa23b721a26a526f3f5a80b4bb74aa45606199
634,100
def text_encoding(encoding, stacklevel=2): """ Stubbed version of io.text_encoding as found in Python 3.10 """ return encoding
b025d6d71cc1a1d06005a53dffc86b2166387070
634,101
def _update_with_calls(result_file, cnv_file): """Update bounds with calls from CNVkit, inferred copy numbers and p-values from THetA. """ results = {} with open(result_file) as in_handle: in_handle.readline() # header _, _, cs, ps = in_handle.readline().strip().split() for i, (...
65237d15a3bdcc2281a9bf7954d205172e5be182
634,103
def list_materials(client, file_=None, material=None): """List materials on a part. Args: client (obj): creopyson Client. `file_` (str, optional): File name. Defaults is currently active model. material (str, optional): Material name pattern. ...
bcd70f4003f4b7499bf939f1d3f9810558f6c719
634,104
import logging import os def get_logger(logger_name, logging_format, file_name, level=logging.INFO): """ Get logger with path 'file name'. If permission error, create log in /tmp :param logger_name: logger name :type logger_name: str :param logging_format: log format :type logging_format: st...
687b9879f60af9a0060278407dafef7f5cf1b4b5
634,105
def compute_accuracy(true_labels, labels_pred): """Print and save the accuracy of the model on the dataset""" correct = (true_labels == labels_pred) correct_sum = correct.sum() return (float(correct_sum)/len(true_labels))
7dca11fcb11f4fdde559d423f0eb7112436cf852
634,106
def heading(title, fgcol, bgcol,extras='',add='&nbsp;<br>'): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>%s <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td a...
ff4b11710812aaab28e96e02f8f7777471a226a0
634,107
from typing import Callable def contains(substring: str, false_prob: float = 0.0, true_prob: float = 1.0) -> Callable: """Generate a function that checks whether a substring is present.""" def call(value: object) -> float: if not isinstance(value, str): return 0.0 retu...
be91f8db341f51e44de45aec296c1e1c6804ff18
634,108
import requests def perform_query(query): """Performs a SPARQL query to the wikidata endpoint Args: query: A string containing a functional sparql query Returns: A json with the response content. """ endpoint_url = "https://query.wikidata.org/sparql" try: response =...
d429c3c2291557ab2d1b3ecee126e63f6f89ed99
634,109
def orderedSet(iterable): """ Remove all duplicates from the input iterable """ res = [] for el in iterable: if el not in res: res.append(el) return res
a67cda1f64dfebe22914e1d76d51d990fd967900
634,110
import six def first_where(pred, iterable, default=None): """Returns the first element in an iterable that meets the given predicate. :param default: is the default value to use if the predicate matches none of the elements. """ return next(six.moves.filter(pred, iterable), default)
508e67feeb9c190f67297495e242e67e0b05cce0
634,111
def size_mb(size): """ Helper function when creating database :param size: interger (size in Mb) :return: integer (bytes) """ return int(1024*1024*size)
0da4523a3ddb86a3212a729ad078751a28eef4ae
634,112
def digits_count(value): """Count the number of digits in the string representation of a scalar value. Parameters ---------- value: scalar Scalar value in a data stream. Returns ------- int """ return sum(c.isdigit() for c in str(value))
bcc020f9d159318c505c278de5796b089cccd7e0
634,113
def flatten(lists): """ Return a new (shallow) flattened list. :param lists: list: a list of lists :return list """ return [item for sublist in lists for item in sublist]
3dc11ae9c41cfae0abe88d5b905fb06e30658826
634,114
import binascii def read_data(hex_data): """read hex string and convert to binary""" data = binascii.unhexlify(hex_data[2:]) return data
0ddf20b108a07bf6bfd169542b5cd52c77a67845
634,115
def parse_meteorologia(f_element): """ helper function to the constructor, parses xml entries @param f_element: element to parse """ # inicia o dicionário de dados ldct_tmp = {} # handle altitude de transição if "alttrans" == f_element.tagName(): ldct_tmp["alttrans"] = f_elemen...
892d4c0ac103d87c9a514a4d3a4aaf05ebd587c4
634,116
def easing(current_time, begin, change, total_time): """ current_time = how much time has passed since start begin = starting value change = final value - starting value total_time = how long ease should take """ return change * current_time / float(total_time) + begin
1b9f66722ed6799b9de2dddcf2d995067d051aa9
634,117
def parse_report_section(config_obj, section): """ parse the [REPORT] section of a config file to extract various reporting options to be passed to the Report object :param: config_obj : configparser object for the config file passed in to naarad :param: section: name of the section. 'REPORT' should be passed i...
7737180164fc36f11ab1ab81a26d40760a9e84be
634,118
def createExportString(clip, delimiter=" ", badValue="nan"): """Create a line of text for the exporter Inputs: ------------ clip A clipboard object Optional Inputs: ----------------- delimiter: (string) The character, or set of characters to separate elements ...
c84253e848b418fe4f92d4de1910793c6c607a25
634,119
def _default_predict_fn(loaded_model, x): """Default predict function (callable) for running inference.""" predictions_dict = loaded_model.signatures['serving_default'](x) keys = list(predictions_dict.keys()) if len(keys) == 1: return predictions_dict[keys[0]] if 'scores' in predictions_dict: return p...
26943ceb14528bb99d01e912c04fd8dbe6a42089
634,120
def run_ckin_header(pf_info, ref_info, spc_model): """ prepare chemkin header info and convert pac 99 format to chemkin format """ tors_model, vib_model, _ = spc_model har_info, tors_info, vpt2_info, _, sp_str, = pf_info har_ref_info, tors_ref_info, vpt2_ref_info, _ = ref_info # Convert the pac...
caff0d67c7f1db352cfbeceb7f8210328c994b66
634,121
def air_flux(air_flow: float, co2_source: float, co2_target: float) -> float: """ Equation 8.46 Args: co2_source, co2_target: CO2-concentration at location (mg m^-3) air_flow: the air flux from location 1 to location 2 (m^3 m^-2 s^-1) return: CO2 flux accompanying an air flux from locat...
891ec9dedfa9a4ecfa496acd29d0afcf9e7aed98
634,122
import os import logging import time def enable_logging(log_name, log_file): """Enable logging.""" try: os.remove(log_file) except FileNotFoundError: print('No logging file present, creating new one.') logger = logging.getLogger(log_name) logger.setLevel(logging.INFO) handler...
043af044f4068935f54d619ed6991c49cdd487df
634,123
def is_service_hiting_start_limit(duthost, container_name): """ @summary: Determine whether the container can not be restarted is due to start-limit-hit or not """ service_status = duthost.shell("sudo systemctl status {}.service | grep 'Active'".format(container_name)) for line in serv...
0ea523543a82a21fb2b6f4e8f391bb539cfe382f
634,124
def add_newline_chars_to_list(list_of_filelines): """ adds a newline character to each string in a list :param list_of_filelines: list of strings :return: list of strings """ new_filelines = [] for i in range(len(list_of_filelines)): new_filelines.append(list_of_filelines[i] + "...
24447eafe730efdda0ec28dac54f76de43ec3034
634,125
import uuid def uuid4(short: bool = False) -> str: """ Create custom version of uuid4. :param short: If ``True`` only returns the first 8 chars of the uuid, else, 18 :return: UUID of 18 chars """ return str(uuid.uuid4())[:18 if not short else 8]
2e08d8b8772cc40efdac24b382eaa11d49247c21
634,126
import os import glob def download_media_by_msg(client, channel, msg): """Given a message ID, finds the media this message contained and downloads it. """ try: os.makedirs('tg_media', exist_ok=True) file_name = 'tg_media/' + channel + '-' + str(msg.id) file_name_check = fil...
e558b1facca03ed6d02b35d19ac8fe2986b7decb
634,127
def read_ascii_data_cols(_file_path, _str_sep, _i_col_start=0, _i_col_end=-1, _n_line_skip=0, _float=True): #OC24112019 #def read_ascii_data_cols(_file_path, _str_sep, _i_col_start=0, _i_col_end=-1, _n_line_skip=0): """ Auxiliary function to read-in data comumns from ASCII file (2D table) :param _file_path:...
da932c7d3a99b6c4c302918e795ccd802829c2b8
634,128