content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import math def moments_get_orientation(m): """Returns the orientation in radians from moments. Theta is the angle of the principal axis nearest to the X axis and is in the range -pi/4 <= theta <= pi/4. [1] 1. Simon Xinmeng Liao. Image analysis by moments. (1993). """ theta = 0.5 * math.atan...
0b75e86e324dccd5fe2c4332dfeb15d63a417b9b
7,525
def get_article_case(article, word): """Determines the correct article casing based on the word casing""" return article.capitalize() if word[0].istitle() else article
603810cb60c3719c102afe024cdc0ce474d37bfa
7,526
import collections def deep_convert_to_plain_dict(an_odict): """ Recursively convert `an_odict` and any of its dictionary subelements from `collections.OrderedDict`:py:class: to plain `dict`:py:class: .. note:: This is naive, in that it will not properly handle dictionaries with recursive obj...
0a463981909153d4beee64fbbf5fad489adf78ac
7,527
def _members_geom_lists(relation_val, footprints): """ Add relation members' geoms to lists. Parameters ---------- relation_val : dict members and tags of the relation footprints : dict dictionary of all footprints (including open and closed ways) Returns ------- tu...
a0ccf10ef75c381b5839cf8e17ba304a7488ecda
7,529
import math def fuzzifier_determ(D: int, N: int) -> float: """The function to determ the fuzzifier paramter of fuzzy c-means """ return 1 + (1418 / N + 22.05) * D**(-2) + (12.33 / N + 0.243) * D**(-0.0406 * math.log(N) - 0.1134)
3bf0f85a74400c19fae74349ea651eba8b600697
7,531
from typing import List def _is_paired(ordered_list: List[int]) -> bool: """Check whether values are paired in ordered_list.""" consecutive_comparison = [ t == s for s, t in zip(ordered_list, ordered_list[1:]) ] return (all(consecutive_comparison[0::2]) & (not any(consecutive_comparison[1::2])...
ba7052de513bcc7bf274e38005c459715e9f60b8
7,532
def steps(number): """ Count steps needed to get to 1 from provided number. :param number int - the number provided. :return int - the number of steps taken to reach 1. """ if number < 1: raise ValueError("Provided number is less than 1.") steps = 0 while number != 1: s...
8681691946b5ba2d261a1ae753d2a04c46ac1719
7,533
import numpy def _get_sr_pod_grid(success_ratio_spacing=0.01, pod_spacing=0.01): """Creates grid in SR-POD space SR = success ratio POD = probability of detection M = number of rows (unique POD values) in grid N = number of columns (unique success ratios) in grid :param success_ratio_spacin...
6349afbecc8994c1078f2fa019a5a721862b0d15
7,534
import re def replace_space(string): """Replace all spaces in a word with `%20`.""" return re.sub(' ', '%20', string)
9b9b400f913efb7ee1e86a87335955744c9b1a3a
7,536
import re def port_to_string(port): """ Returns clear number string containing port number. :param port: port in integer (1234) or string ("1234/tcp") representation. :return: port number as number string ("1234") """ port_type = type(port) if port_type is int: return str(port) ...
5d526406566c7c37af223ed8e5744ba13771f55f
7,537
from typing import Optional def code_block(text: str, language: Optional[str] = None) -> str: """Creates a code block using HTML syntax. If language is given, then the code block will be created using Markdown syntax, but it cannot be used inside a table. :param text: The text inside the code block :...
5d8b272d2a93463171e5a51beaccd8293db280dc
7,538
def merge(line): """ Helper function that merges a single row or column in 2048 """ result = list(line) head = 0 i = 1 while (i < len(result)): if (result[i] != 0): if (result[head] == result[i]): result[head] += result[i] result[i] = 0 ...
1a843ef4dc9c1b6cf20036f24288cb6166ae207b
7,539
def get_transcripts_from_tree(chrom, start, stop, cds_tree): """Uses cds tree to btain transcript IDs from genomic coordinates chrom: (String) Specify chrom to use for transcript search. start: (Int) Specify start position to use for transcript search. stop: (Int) Specify ending position to use for tra...
51aa6f1aa97d2f977840376ea2c4bf422ff8e7a6
7,540
def parse_flattened_result_only_intent(to_parse): """ Parse out the belief state from the raw text. Return an empty list if the belief state can't be parsed Input: - A single <str> of flattened result e.g. 'User: Show me something else => Belief State : DA:REQUEST ...' ...
05c7346197fa3f98f1c4194ea7d92622483d0f51
7,541
import argparse def process_command_line(): """ returns a 1-tuple of cli args """ parser = argparse.ArgumentParser(description='usage') parser.add_argument('--config', dest='config', type=str, default='config.yaml', help='config file for this experiment') parser.add_argume...
573ec38b1b57538ebb97b082f71343a49081dfc7
7,542
import re def strip_outer_dollars(value): """Strip surrounding dollars signs from TeX string, ignoring leading and trailing whitespace""" if value is None: return '{}' value = value.strip() m = re.match(r'^\$(.*)\$$', value) if m is not None: value = m.groups()[0] return va...
3ad283af2835ba2bcf2c57705f2faa9495ea4e7a
7,543
import os def menu_select(title='~ Untitled Menu ~', main_entries=[], action_entries=[], prompt='Please make a selection', secret_exit=False): """Display options in a menu for user selection""" # Bail early if (len(main_entries) + len(action_entries) == 0): raise Exception("MenuError: No items gi...
2495d79218e03430642eb4d099223fa2e2f3b357
7,545
def estimate_price(mileage, theta0, theta1): """ Estimate price function: """ return theta0 + theta1 * mileage
43ba05aacc3cb94f9bf3223f6ea8f74a569c2537
7,546
def similar_date(anon, obj, field, val): """ Returns a date that is within plus/minus two years of the original date """ return anon.faker.date(field=field, val=val)
d9a723d3c22954797895b43d57f297330272c8cb
7,547
def structure_sampling_values(graph, centrality, function): """ helper function to compute the centrality values for an edge""" cent = centrality.get_values(graph) edges = graph.get_edges() left_values =cent[edges[:,0]] right_values=cent[edges[:,1]] values = function(left_values, right_values) ...
a0608646867704dea6b1e27e4cfee8b3062ab0da
7,548
def dummy_wrapper(fn): """Simple wrapper used for testing""" def _run_callable(*args, **kwargs): return fn(*args, **kwargs) return _run_callable
60d92942fd1d87b835ea05dd00baea8a71117fac
7,549
def get_backlinks(dictionary): """ Returns a reversed self-mapped dictionary @param dictionary: the forwardlinks """ o = dict() for key, values in dictionary.items(): try: for v in values: try: o[v].add(key) except KeyE...
43b28e4f177a7813ba8d8c0960d04e71ad28f83b
7,550
import zipfile def unzip(zip_address, file_name, encoding='UTF-8'): """解压zip数据包 :param zip_address: 压缩包的地址 :param file_name: 压缩包里面文件的名字 :param encoding: 文件的编码 :return: 压缩包里面的数据:默认编码的UTF-8 """ f = zipfile.ZipFile(zip_address) fp = f.read(file_name) lines = fp.decode(encoding) r...
ba71fd6f923c2c410b0461796da513583c15b9aa
7,551
def has_name_keywords(ustring): """是否含有名称的标识字符""" if (u'店名' in ustring) or \ (u'店家' in ustring) or \ (u'名字' in ustring): return True return False
e009e567ecf060b0b225802de523dea60ab8a02e
7,552
def bbox_flip(bbox, width, flip_x=False): """ invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2 also note need to save before assignment :param bbox: [n][x1, y1, x2, y2] :param width: cv2 (height, width, channel) :param flip_x: will flip x1 and x2 :return: flippe...
485496752c83e0e8424b9f67a56a861373db5fc5
7,553
def greeting(): # OK """Beschreibung: Dient zum besonderen aussehen :return: gibt die eingegebenen Zeichen decodiert aus Details: print(b'\xe2\x95\x94'.decode('utf-8')) ergibt ╔ die linke obere Ecke print(b'\xe2\x95\x91'.decode('utf-8')) ergibt ║ somit lassen sich "Rahmen bau...
4800675329568bda9015782bb2f30513fb842931
7,554
import logging import json def read_json_file_into_memory(json_file): """ Purpose: Read properly formatted JSON file into memory. Args: json_file (String): Filename for JSON file to load (including path) Returns: json_object (Dictonary): Dictonary representation JSON Object ...
70c2e6ab6180700ce77469b8afa0d0df8e0eee95
7,555
def to_base_10(num: str, from_base: int, key="0123456789abcdefghijklmnopqrstuvwxyz", digits=100, minus_sign="-") -> int: """Convert a num in from_base to base 10.""" if len(key) < from_base: raise ValueError("Must have key length > base") if num == key[0]: return 0 if num[0] == minus_s...
128127fe1f55250f46e057fa92f72d25966be626
7,557
import torch def dist(batch_reprs, eps = 1e-16, squared=False): """ Efficient function to compute the distance matrix for a matrix A. Args: batch_reprs: vector representations eps: float, minimal distance/clampling value to ensure no zero values. Returns: distance_matrix, clamped to ensure no zero values ...
be4d50e35ed11255eef2dc1acb4645de1453964c
7,559
def unquote(s): """Strip single quotes from the string. :param s: string to remove quotes from :return: string with quotes removed """ return s.strip("'")
15d29698e6a3db53243fc4d1f277184958092bc6
7,561
import string def normalize(text): """ Remove all punctuation for now """ return ''.join('' if c in string.punctuation else c for c in text)
9332583adb0ff3bfbe37170b2acdd58f09b3fe5e
7,562
def p_AB(A, b, L): """ Numerator of function f. """ a11, a12, a13, a21, a22, a23, a31, a32, a33 = \ A[0, 0], A[0, 1], A[0, 2], \ A[1, 0], A[1, 1], A[1, 2], \ A[2, 0], A[2, 1], A[2, 2] b1, b2, b3 = b[0, 0], b[1, 0], b[2, 0] return L**4*(-a11*a22*b3**2 + a11*a23*b2*b3 + a11*a32...
530655f0e6e56ef6aca4ad82d5076543caec0ddb
7,563
def binary_to_decimal(binary): """ Converts a binary number into a decimal number. """ decimal = 0 index = 0 while binary > 0: last = binary % 10 binary = binary / 10 decimal += (last * (2 ** index)) index += 1 return decimal
f1efdf19c802345e6badfed430dd82e3f067a419
7,564
def namelist(names: list) -> str: """ Format a string of names like 'Bart, Lisa & Maggie' :param names: an array containing hashes of names :return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersa...
b0b931f3f9365824931173c2aec3ac213342e0c3
7,565
def loadIUPACcompatibilities(IUPAC, useGU): """ Generating a hash containing all compatibilities of all IUPAC RNA NUCLEOTIDES """ compatible = {} for nuc1 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE sn1 = list(IUPAC[nuc1]) for nuc2 in IUPAC: # ITERATING OVER THE D...
931f2a765ec9499b8553d13d7de93c6b261622de
7,567
def to_fullspec(rs, es, hds): """ Rotationally symmetric dump of a list of each to fullspec """ output = [] for idx in range(0, len(rs)): row = {"r": [rs[idx]], "e": [es[idx]], "d": hds[idx] * 2} output.append(row) return output
98cac8ba938249d6af0decfeffedf594ab1d6660
7,568
def get_uniq_list(data): """ 列表去重并保持顺序(数据量大时效率不高) :param data: list :return: list """ ret = list(set(data)) ret.sort(key=data.index) return ret
d4a43acd42608210c022317999673bd281e5e247
7,569
import re def normalize_newlines(text): """Normalizes CRLF and CR newlines to just LF.""" # text = force_text(text) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines return re_newlines.sub('\n', text)
835f038f0873546db96d8e9d2a0d622b4e974f7d
7,570
def check_families(trace_events, families, event_definitions): """ Looks for event types found in the trace that are not specified in the event definitions. :param trace_events: Events found in the trace (filtered by family). :param families: Families to look for. :param event_definitions: Even...
2533835283d388ad2fe37d79f6e87f14103a5bee
7,571
import re def convertSQL_LIKE2REGEXP(sql_like_pattern): """Convert a standard SQL LIKE pattern to a REGEXP pattern. Function that transforms a SQL LIKE pattern to a supported python regexp. Returns a python regular expression (i.e. regexp). sql_like_pattern[in] pattern in the SQL LIKE form to be con...
16589a99327885dc034fb33af1e69a42a453ccbd
7,573
import argparse def parse_arguments(solving_methods): """ Main CLI for interfacing with Monte Carlo Sudoku Solver. Arguments: solving_methods: tuple(str) Methods for solving sudoku puzzles. Returns: argparse.Namespace Argparse namespace containg CLI inputs. ...
33c5419f4cd3944ee2fe39adbb2cd9776bb5a566
7,575
def make_enumeration(entries, divider=', '): """ :param entries: :param divider: :return: """ enumeration = { 'type': 'enumeration', 'entries': entries, 'divider': divider } return enumeration
0fee40bf69613944b57f2d1967ee0cdb87e7493b
7,576
def get_module_name(): """ モジュール名取得 Return: モジュール名 """ return __name__
45836eb290ff628baf9082829b9e95d9d4e45d78
7,578
def get_base_folder(image_file): """The base folder""" return '/'.join(image_file.split('/')[:-6])
14f212e80d57b71d2b379d2f5024c8f89ea438f3
7,579
import math def calc_distance(x1, y1, x2, y2): """ Calculate the distance between 2 point given the coordinates :param x1: Point 1 X coordinate :param y1: Point 1 Y coordinate :param x2: Point 2 X coordinate :param y2: Point 2 Y coordinate :return: Double. Distance between point 1 and poi...
dd143ed5dd088c8a4d205c47363cd463798796d9
7,581
def uniform_pdf(x): """ Uniform Distribution(균등 분포) 확률 밀도 함수 """ return 1 if 0 <= x < 1 else 0
8aa049fc5ce2524edbfed892e4c0de1ce439ff58
7,583
def unit(value, unit, parenthesis=True): """Formats the numeric value of a unit into a string in a consistent way.""" formatted = f"{value:,g} {unit}" if parenthesis: formatted = f"({formatted})" return formatted
fe039ec681a16e4a317f1a500c29ab44615addd1
7,584
def normalize_val_list(val_list): """Returns a list of numeric values by the size of their maximum value.""" max_val = float(max(val_list)) return [ val/max_val if max_val != 0 else 0 for val in val_list ]
f594a6c281253bc181e436d1e1e3e1a83d07b56c
7,587
def sieve(iterable, indicator): """Split an iterable into two lists by a boolean indicator function. Unlike `partition()` in iters.py, this does not clone the iterable twice. Instead, it run the iterable once and return two lists. Args: iterable: iterable of finite items. This function will sca...
55f64a2aea55af05bd2139328157e3a877b8f339
7,589
import re def property_to_snake_case(property_type): """Converts a property type to a snake case name. Parameters ---------- property_type: type of PhysicalProperty of str The property type to convert. Returns ------- str The property type as a snake case string. """ ...
fc0aa1c811a2de0bbd77f146a1816e8d7a31e08a
7,590
def read_binary(filepath): """return bytes read from filepath""" with open(filepath, "rb") as file: return file.read()
98587f79b5a2d8b8ff82909cb03957c0b3e2db7d
7,592
def sra_valid_accession(accession): """ Test whether a string is an SRA accession """ if accession.startswith('SRR') and len(accession) == 10: return True return False
3a4c5f40490f68490620ddacb430a0fcc8dfdd89
7,593
def alaska_transform(xy): """Transform Alaska's geographical placement so fits on US map""" x, y = xy return (0.3*x + 1000000, 0.3*y-1100000)
3f86caeee7b34295ce0680017dd70d6babea2a62
7,594
import requests import json def get_user_simple_list(access_token, dept_id): """ 获取部门用户信息 :return: { "errcode": 0, # 返回码 "errmsg": "ok", # 对返回码的文本描述内容 "hasMore": false, # 在分页查询时返回,代表是否还有下一页更多数据 "userlist": [ { "userid": "zhangsan", # 员工id "name": "张三" #...
4fe63f8a8554015e02193005023181aa22ec23a5
7,595
def increase_by_1_list_comp(dummy_list): """ Increase the value by 1 using list comprehension Return ------ A new list containing the new values Parameters ---------- dummy_list: A list containing integers """ return [x+1 for x in dummy_list]
9ad24064a7cf808cba86523e5b84fe675c6c128b
7,597
import os def save_config(config, path): """ Write the configuration file to ``path``. """ os.umask(0o77) f = open(path, "w") try: return config.write(f) finally: f.close()
8174cc17b97664a6253d906618cf1a45896c08b9
7,599
import unicodedata def is_hw(unichr): """unichrが半角文字であればTrueを返す。""" return not unicodedata.east_asian_width(unichr) in ('F', 'W', 'A')
260d79199c8551b635fb343a72ffeb30e7707958
7,600
def deletedup(xs): """Delete duplicates in a playlist.""" result = [] for x in xs: if x not in result: result.append(x) return result
0f36899c9ce2710564d5d5938b54edbdd64afd81
7,602
from typing import Any def prettyStringRepr(s: Any, initialIndentationLevel=0, indentationString=" "): """ Creates a pretty string representation (using indentations) from the given object/string representation (as generated, for example, via ToStringMixin). An indentation level is added for every open...
0c25810f5bd559a8dda09a2ec07bf6ea18956716
7,603
import os def replace_tail(path: str, search: str, replace: str) -> str: """ >>> replace_tail('/dir1/dir2/path.ext', '/dir1', '/dir2') 'dir2/dir2/path.ext' >>> replace_tail('/dir1/dir2/path.ext', '/dir1/', '/dir2/') 'dir2/dir2/path.ext' >>> replace_tail('/dir1/dir2/path.ext', '/dir3', '/dir2...
cc9cc5d808a2befa1427543b3a1f3f71d48d4d87
7,604
def get_mapping(d): """ Reports fields and types of a dictionary recursively :param object: dictionary to search :type object:dict """ mapp=dict() for x in d: if type(d[x])==list: mapp[x]=str(type(d[x][0]).__name__) elif type(d[x])==dict: mapp[x]=get_m...
87722f1429a93a934af08cb68519576cfc2cd7b0
7,606
def help(event): """Returns some documentation for a given command. Examples: !help help """ def prepare_doc(doc): return doc.split('\n')[0] plugin_manager = event.source_bot.plugin_manager prendex = 'Available commands: ' if len(event.args) < 1: return prendex +...
dbc2baed887df46e0d101d48a1a338760329679e
7,607
def remplace_mot_entre_parentheses(texte: str): """ Les mots entre parenthèse représente le petite texte dans Animal Crossing. Cela n'est pas prononcées. """ while '(' in texte and ')' in texte: debut = texte.index("(") fin = texte.index(")") texte = texte[:debut] + "*" * ...
30b2e86f56be6a4faee2f8c827c58d85ad62eb88
7,610
def knapsack(v, w, n, W): """ Function solves 0/1 Knapsack problem Function to calculate frequency of items to be added to knapsack to maximise value such that total weight is less than or equal to W :param v: set of values of n objects, :param w: set of weights of n objects, first eleme...
07537ab374f006a943a6ab19d90ee4cd580f9abf
7,611
def __normalize_request_parameters(post_body, query): """ Return a normalized string representing request parameters. This includes POST parameters as well as query string parameters. "oauth_signature" is not included. :param post_body: The body of an HTTP POST request. :type post_body: strin...
2cd7e72530a461629dd5034665c09dd240734313
7,612
import os def test_repo_dir(dir, name): """ Test an entered GitHub repository directory name. """ subdir = os.path.basename(dir) return subdir != name
b8fdbcb82e53fd1079b611617b3acf534af25fe5
7,613
import re def remove_punctuation(line): """ 去除所有半角全角符号,只留字母、数字、中文 :param line: :return: """ rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]") line = rule.sub('', line) return line
d63f355c5d48ec31db0412dd7b12474bf9d6dd6b
7,615
import time def CurrentTimeInSec(): """Returns current time in fractional seconds.""" return time.time()
3dc3bda89622ffdf0067d489c10f539cb6274e21
7,616
def euler2(f2p, b, t, h, p): """ tuple b = boundary condition (x0, y0, y'0) float h = step int t = number of steps lambda f2p = dy/dx int p = significant digits after x values """ x = b[0] y = b[1] yp = b[2] y2p = f2p(x, y, yp) ret = [(x, y)] #list of tuples to be returned with x and ...
67e390f0c21ba87d8aeec97920403c2d62678dc9
7,619
def parse_int(text: str) -> int: """ Takes in a number in string form and returns that string in integer form and handles zeroes represented as dashes """ text = text.strip() if text == '-': return 0 else: return int(text.replace(',', ''))
1f49a2d75c2fadc4796456640e9999796fddfa93
7,620
def _get_object_url_for_region(region, uri): """Internal function used to get the full URL to the passed PAR URI for the specified region. This has the format; https://objectstorage.{region}.oraclecloud.com/{uri} Args: region (str): Region for cloud service uri (str): ...
72b069e1657b94c7800ba7e5fd2269909e83c856
7,621
def sequence_delta(previous_sequence, next_sequence): """ Check the number of items between two sequence numbers. """ if previous_sequence is None: return 0 delta = next_sequence - (previous_sequence + 1) return delta & 0xFFFFFFFF
8580c26d583c0a816de2d3dfc470274f010c347f
7,623
def get_transitions(data_vals, threshold, hysteresis): """ Find the high-to-low and low-to-high state transistions """ pend_len, time_vals, sens_vals = data_vals # Get initial state if sens_vals[0] > threshold: state = 'high' else: state = 'low' # Find state changes ...
144a6463178820ef1cc6a6943cda5fe2e7117274
7,624
def single_number_generalized(nums, k, l): """ Given an array of integers, every element appears k times except for one. Find that single one which appears l times. We need a array x[i] with size k for saving the bits appears i times. For every input number a, generate the new counter by x[j] =...
90e28c2023622f23e808b89bb255d67aefe7bda8
7,626
import os def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "mnist": 900, } parts = fname.split...
46586b0ca13793fadb199b197cb22ac8be180557
7,627
import re def find_matched_pos(str, pattern): """ Find all positions (start,end) of matched characters >>> find_matched_pos('ss12as34cdf', '\d') [(2, 3), (3, 4), (6, 7), (7, 8)] """ match_objs = re.finditer(pattern ,str) match_pos = [match_obj.span() for match_obj in match_objs] return ma...
17e352299d7874bdfb66a4a181d04e90fba0af7e
7,628
def box_area(box): """ Calculates the area of a bounding box. Source code mainly taken from: https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ `box`: the bounding box to calculate the area for with the format ((x_min, x_max), (y_min, y_max)) return: the b...
3a52a41e8dc92d3a3a2e85a33a4ebcbbb7131091
7,629
def dsigmoid(sigmoid_x): """ dSigmoid(x) = Sigmoid(x) * (1-Sigmoid(x)) = Sigmoid(x) - Sigmoid(x)^2 """ return sigmoid_x - sigmoid_x**2
37e163e6baab1a2b584e9eef726895c919c80406
7,630
def progress_bar(iteration, total): """ entertain the user with a simple yet exquisitely designed progress bar and % :param iteration: :param total: :return: """ try: perc = round((iteration/total)*100, 2) bar = ('░'*19).replace('░','█',int(round(perc/5,0))) + '░' ret...
a32bd5edd108142583f0ea1573848c91c6d61c33
7,631
def par_auteur(name): """ Add 'par' to the author names """ author_phrase = '' if name: author_phrase = " par {},".format(name) return author_phrase
a09bbc79cb152239bc178d74ebd11cc0f74c1d30
7,632
from typing import Dict from typing import List def remove_items(item_capacities:Dict[str,int], items_to_remove:List[str])->Dict[str,int]: """ Remove the given items from the given dict. >>> stringify(remove_items({"x":3, "y":2, "z":1, "w":0}, ["x","y"])) '{x:2, y:1, z:1}' >>> stringify(remove_it...
c17b972050b4054121fffd478dd3252f90959b8a
7,633
import os def load_environment_auth_vars() -> tuple: """Attempts to load authentication information from environment variables if none is given, looks for a username under "FHIR_USER", password under "FHIR_PW" and the token under "FHIR_TOKEN" Returns: Tuple containing username, password and token...
b3f629524f1f74bb7b3c44ec0c2d8b2cff2ff3a5
7,634
def get_min_freeboard(fjord): """ Get a required minimum median freeboard for filtering out icebergs """ minfree = {"JI": 15, "KB":5} try: return minfree.pop(fjord) except KeyError: print("The current fjord does not have a minimum freeboard median entry - using a default value!...
b80fec4224dcf8ce0d24a19ca28e88e66db52150
7,636
from typing import Optional from typing import Callable import functools import click def server_add_and_update_opts(f: Optional[Callable] = None, *, add=False): """ shared collection of options for `globus transfer endpoint server add` and `globus transfer endpoint server update`. Accepts a toggle to...
bc2427a7a0996528dc1411186c51b11c7b4db339
7,637
def build_tag_regex(plugin_dict): """Given a plugin dict (probably from tagplugins) build an 'or' regex group. Something like: (?:latex|ref) """ func_name_list = [] for func_tuple in plugin_dict: for func_name in func_tuple: func_name_list.append(func_name) regex = '|'.joi...
367b95067cabd4dcdfd8981f6a14b650da3601c5
7,638
def is_html_like(text): """ Checks whether text is html or not :param text: string :return: bool """ if isinstance(text, str): text = text.strip() if text.startswith("<"): return True return False return False
a499e14c243fcd9485f3925b68a0cef75fa069cb
7,639
def relu_prime(x): """ ReLU derivative. """ return (0 <= x)
8908af6f6748291477e3379443fe7714fed289ad
7,641
import importlib def import_optional_dependency(name, message): """ Import an optional dependecy. Parameters ---------- name : str The module name. message : str Additional text to include in the ImportError message. Returns ------- module : ModuleType The...
22d638e86b8d979b746507790532273d161323c8
7,642
def curate_url(url): """ Put the url into a somewhat standard manner. Removes ".txt" extension that sometimes has, special characters and http:// Args: url: String with the url to curate Returns: curated_url """ curated_url = url curated_url = curated_url.replace(".txt",...
42ea836e84dfb2329dd35f6874b73ac18bde48d1
7,643
import requests def get_news(): """ Returns two dictionnary object containing news articles informations. The first one is a short version, with little informations and the second one contains all the informations. """ API_KEY = 'd913f4f1287a42819abc66f428e0fad4' sources = 'b...
4145ddfd669c54f8bfe285ccde67b7a08b724a85
7,644
def get_enzyme_train_set(traindata): """[获取酶训练的数据集] Args: traindata ([DataFrame]): [description] Returns: [DataFrame]: [trianX, trainY] """ train_X = traindata.iloc[:,7:] train_Y = traindata['isemzyme'].astype('int') return train_X, train_Y
8a3f6e29aca5737396c0e4007c5ff512592e51b9
7,646
def patch_utils_path(endpoint: str) -> str: """Returns the utils module to be patched for the given endpoint""" return f"bluebird.api.resources.{endpoint}.utils"
31ae02bd0bee7c51ea5780d297427fdac63295b3
7,647
def rgbToGray(r, g, b): """ Converts RGB to GrayScale using luminosity method :param r: red value (from 0.0 to 1.0) :param g: green value (from 0.0 to 1.0) :param b: blue value (from 0.0 to 1.0) :return GreyScale value (from 0.0 to 1.0) """ g = 0.21*r + 0.72*g + 0.07*b return g
59a874d1458ae35e196e1ca0874b16eadfd1a434
7,650
def choose_reads(hole, rng, n, predicate): """Select reads from the hole metadata.""" reads = [] required_reads = set(v for v in hole.metadata.required_reads if predicate(v)) allowed_reads = set(v for v in hole.metadata.allowed_reads if predicate(v)) while len(reads) < n and (required_reads or allowed_reads):...
cae99bcd36b6d7169da0682a5f54d168538766d5
7,651
def maximum(x, y): """Returns the larger one between real number x and y.""" return x if x > y else y
e98a4e720936a0bb271ee47c389811111fd65b00
7,652
def is_acceptable_multiplier(m): """A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1. """ return 1 < m < (2 ** 61 - 1)
d099dd53296138b94ca5c1d54df39b9cf7ad2b5d
7,653
def extractRSS_VSIZE(line1, line2, record_number): """ >>> extractRSS_VSIZE("%MSG-w MemoryCheck: PostModule 19-Jun-2009 13:06:08 CEST Run: 1 Event: 1", \ "MemoryCheck: event : VSIZE 923.07 0 RSS 760.25 0") (('1', '760.25'), ('1', '923.07')) """ if ("Run" in line1) and ("Event" in line1): # the first li...
89c14bbb3a2238ec9570daf54248b4bd913eecca
7,654
import pkg_resources def show_template_list(): """Show available HTML templates.""" filenames = pkg_resources.resource_listdir(__name__, "data") filenames = [f for f in filenames if f.endswith(".html")] if not filenames: print("No templates") else: for f in filenames: p...
f86d5ec772127be6183bfe14ebda324a05e43cd3
7,655
import hashlib def ripemd160(msg): """one-line rmd160(msg) -> bytes""" return hashlib.new('ripemd160', msg).digest()
a8484404fc3418fcca20bebfd66f36c3a33c9be3
7,656
from typing import Optional import re def extraer_numero_iniciativa(numero_evento: str) -> Optional[int]: """Algunos numeros de evento traen la iniciativa a la que pertenecen, esta función intenta extraer el ID Returns ------- int or None ID de iniciative o None si no existe un numero con...
3c1abffca75a66bfad5c9556a194b904b39422c0
7,657