content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def choose_height(new_width, width, height): """Return the height corresponding to 'new_width' that's proportional to the original size. """ proportion = float(height) / float(width) return int(new_width * proportion)
99f410c08092169a982abfb9bbdbeb8af8b8a9f5
622,013
import torch def test(model, test_loader, criteria, device): """ Function to perform model validation Args: model (Net): Model instance to run validation test_loader (Dataset): Dataset used in validation device (string, cuda/cpu): Device type Values Allowed - cuda/cpu Returns: ...
d623c7e67963949a005fd64f2973196f0f35ef24
622,014
def valid_base(base): """Checks if cloud base is valid""" if base <= 30: return True elif base <= 50: return base % 5 == 0 else: return base % 10 == 0
b6063fe8de0fee10490af9f11394f25d624f79cb
622,015
def isinstanceinh(obj, parent_class): """ Returns True if 'obj' is is an instance of class 'parent_class', or of a subclass of 'parent_class'. :param obj: object to be tested :type obj: Any :param parent_class: class to be checked against :type parent_class: type (e.g. list, tuple, int, bool) ...
ab3dfa08a594d0a4f3be35f43898abe17d785a43
622,016
def distance_mean_elements(K, T1, T2): """ Compute the squared distance between mean elements of two time series Parameters ---------- K: (T1+T2) x (T1+T2) array, between frames kernel matrix T1: int, duration of time series 1 T2: int, duration of time series 2 Re...
3183666caf4b11992dae20b7d2bd625380871db9
622,019
def _name_orf(tfam, gcoord, AAlen): """Assign a usually unique identifier for each ORF. If not unique, a number should be appended to the end.""" return '%s_%d_%daa' % (tfam, gcoord, AAlen)
950d574cfabb87f90a8686f25638a0793f416a09
622,020
def getWindChill(temp, windSpeed): """ A utility function to get the human-apparent temperature in an oxygen-nitrogen atmosphere given an actual temperature and a wind speed. Wind chill is only valid for temperatures at or lower than 10C (50F) and wind speeds higher than 4.8 km/h (3 m/h). @para...
ffca6f645e1a78bf5152577f6b278914a604460a
622,023
def check_stratification(age, stratification): """ Function check_stratification Returns 1 if all ages are consistent with stratification constraints Returns 0 if not. """ age_check = [age[i] for i in range(len(age)) if stratification[i] == 1] sorted_ages = age_check.copy() sort...
c86ab17331abccf909a3fb13a854881244c7b953
622,026
def PacketType(byte): """ Retrieve the message type from the first byte of the fixed header. """ if byte != None: rc = byte[0] >> 4 else: rc = None return rc
2481d26a0d1f1bd501403f08bd65c8821707f9da
622,027
import re def FormatTimestamp(timestamp): """Formats a timestamp which will be presented to a user. Args: timestamp: Raw timestamp string in RFC3339 UTC "Zulu" format. Returns: Formatted timestamp string. """ return re.sub(r'(\.\d{3})\d*Z$', r'\1', timestamp.replace('T', ' '))
e9d626c036240bfb9724b79ac87e4dcf8c392c9a
622,028
def multiple_bbox(bbox, img_height, img_width): """normalize bbox to be betwween 0, 1 Args: bbox (list): original labeled bounding box; img_width(int): image width; img_height(int): image height; Returns: norm_bbox: normolized bbox """ ...
bd6345d0a2163e2aabfc1104c6b42549e3627f39
622,039
import re def trim_space(s: str) -> str: """Remove leading and trailing whitespace but not newlines""" # leading and trailing whitespace causes "\n"'s in the resulting string ret = re.sub(r"(?m)[ \t]+$", "", s) ret = re.sub(r"(?m)^[ \t]+", "", ret) return ret
832cf9fd46d34e82a5c3dcc518d6462a08923d78
622,041
def get_lineage(taxon, tree): """Get lineage of given taxon in taxonomy tree. Parameters ---------- taxon : str Query taxon. tree : dict Taxonomy tree. Returns ------- list of str Lineage from root to query taxon. """ # if taxon is not in tree, return No...
9e99f3c59e0cc75c6ec3ac1b18a04acfb0b95e4f
622,045
def get_user_param(text: dict, machine_name_in_chat: str) -> str: """Maps text by 1/0 for it to be the person or the machine in the dialogue Parameters ---------- text: Dict[..., 'from', ...] Dict containing field 'from' with the name of the user who sent the message machine_name_in_chat: ...
a4adffd01e5ec49106c42b46afed72eeb670772b
622,046
import math def compute_distance(point1, point2): """ Computes distance between 2 points in a 2D space :param point1: :param point2: :return: distance """ return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
207cff73d10d0a3c9ca268130d330a15e462e2c5
622,047
import math def monobit_frequency(bit_str: str): """Frequency (Monobit) Test Determine whether the number of ones and zeros in a sequence are approximately the same as would be expected for a truly random sequence. See section 2.1 in this NIST publication: https://tsapps.nist.gov/publication/get...
d213b3685455fd3dea2878b31e842483430796dc
622,049
def state_root_hash(LIB) -> str: """Returns current state root hash @ NCTL Node 1. """ return LIB.get_state_root_hash()
d5a47e33910fa541086176de252b825ac0bb3bbb
622,051
def args_and_keywords(function): """ Return the information about the function's argument signature. Return a list of the function's positional argument names and a dictionary containing the function's keyword arguments. Example: >>> import random >>> args, kw = arg...
eccf4927cab9db590bf15de1840c26ef1aad8f46
622,055
def select_line(editor): """ Select line under cursor @param editor: Editor instance @type editor: ZenEditor """ start, end = editor.get_current_line_range(); editor.create_selection(start, end) return True
09b62b5bacea24c74d21a6a8262d7e6bba7a3376
622,058
def commonprefix(m): """Given a list of pathnames, returns the longest common leading component""" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
9b840cb20af17e08b707db6e0973998038f7b093
622,059
import re def normalize_reference(s): """Normalize reference label. Collapse internal whitespace to single space, remove leading/trailing whitespace, case fold. """ return re.sub(r'\s+', ' ', s.strip()).upper()
e90ec91cb0d50da8e871a0e5026952367143f803
622,060
import re def filterBlankChar(sourceStr): """filter whitespace characters in a string""" newStr = re.sub(r'[\f\n\r\t\v]+', '', sourceStr) return newStr.strip()
a19eb3fd7617c084e14fa7888401e9308ed72a5e
622,061
import sqlite3 def connect_to_db(dbfile): """Create connection to sqlite DB. Args: dbfile (str): path to sqlite DB. Returns: Connection object. """ conn = sqlite3.connect(dbfile) return conn
baa25cac1395950bf588ec84f97d65eeeee6539b
622,062
def get_safe_seaborn_labels(dfr, labels): """Returns labels guaranteed to correspond to the dataframe.""" if labels is not None: return [labels.get(i, i) for i in dfr.index] return [i for i in dfr.index]
ef6992b940cc65a3683857e2f50273a2a8d1b7f3
622,063
import codecs import json from typing import OrderedDict def load_scan(json_input): """ Return a list of scan results loaded from a json_input, either in ScanCode standard JSON format or the data.json html-app format. """ with codecs.open(json_input, 'rb', encoding='utf-8') as jsonf: scan ...
cbc8f8265e9e1b51a8ffd5bccf03cc49f6bb1e6b
622,066
from typing import List def int_list_greater_than_zero(l: List[int]) -> bool: """ Return True if every element in list is >= 0, else False """ for i in l: if i < 0: return False return True
6c4e382966fd8dc8c14b7a0d27fcdb5a59ce1794
622,069
def has_permission_logged_in(app, identity, model, permission): """ This permission rule matches all logged in identities. It requires the identity to have a 'role' attribute. Said role attribute is used to determine if the given permission is part of the given role. """ assert hasattr(identity, '...
806cf2842597c2ef9937f343cbf73b94e158de22
622,070
import math def dist(p1, p2): """Finds distance between two Points""" return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
6a7f8f928406f20a7de596d18192e8e364107197
622,075
from typing import Tuple from typing import Optional import types from typing import List import importlib def load_module_with_name(name: str) -> Tuple[Optional[types.ModuleType], List[str]]: """ Load the module given its name. Example identifier: some.module """ try: mod = importlib.imp...
134fe718bc2c2dcd59150ec5ba97b8e65b140e51
622,077
from typing import Literal def sh_bool(boolean: bool) -> Literal["yes", "no"]: """ Formats a boolean to be passed to a bash script environment (eg run_job.sh) :param boolean: A boolean flag (True or False) :type boolean: bool :return: 'yes' or 'no' :rtype: str """ if boolean: ...
a9ab0629d99ce5dfd9dfa2bf734d6b682dcffa91
622,089
def generateListLocation(username, list_name): """ generates file placement in S3 based on standardized storage """ return username + '/' + list_name + '.txt'
2d5e34aa0dd4129f3ea45f838318bd0a24e0333c
622,090
import click def format_line_diff(base: str, other: str) -> str: """ Formats the line identifier of a change. :param base: The base line number(s). :param other: The other line number(s). :return: The formatted line numbers. """ buffer = [] if base: buffer.append(f"<{base}") ...
df36c06f1e0ca3a0ddbf759ae490b05c427d3e18
622,092
def create_points_from_polygons(gdf, method='midpoint'): """ Converts the geometry of a polygon layer to a point layer. Parameters ---------- gdf : geopandas.GeoDataFrame method : str Method to create a point from a polygon. Returns ------- geopandas.GeoDataFrame : GeoDataF...
d6f302eee957d5475884c4f43e85d3f56bbdfe1e
622,093
def db(request): """ Returns an ODB connection (one of multiple kinds). """ connection = request.param return connection
4857c3d0e63c248e0a7d7c92a5f271ea6b0b0793
622,096
from typing import List def sort_mode_autocomplete(ctx, args: List[str], incomplete: str): """ Auto-complete choices for --sort-by / -s argument """ entries = [ ('seeders', 'Sort by number of torrent seeders (default)'), ('date', 'Sort by upload date'), ('size', 'Sort by file ...
bdc54d05880be917fccf6a8cdcb0bbc5d158151c
622,097
import re def _camel_to_snake(camel_string: str) -> str: """ Use regex to change camelCased string to snake_case Args: camel_string(str) Returns: A snake_cased string """ result = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_string) result = re.sub("(.)([0-9]+)", r"\1_\2",...
b29dc3a9b1177b01ba8b10461d2ac7be68ba84d6
622,098
def gen_types(tally): """Selects the field type with the highest count. Also intelligently merges compatible types, e.g., 4 ints and 1 floats --> float. Args: tally (dict): Rows of data whose keys are the field names and whose data is a dict of types and counts. Yields: dic...
112c30ee886ea9949b7ab1f4f78b5f6646b08c77
622,099
def _get_next_n_scores_from_prediction_reader(predictions, num_to_read): """ helper script to read a specific number of predictions from the predictions file :param RaasPredictionReader predictions: reader for raas prediction file :param num_to_read: number of answers to read :return: list of rank ...
44e307b20701218a807a351c80cdda1ec2e6d2aa
622,100
from typing import Dict import json def load_config(app_environment) -> Dict: """Load configuration file from config.json""" with open('config.json', 'r') as config_file: config_dict = json.load(config_file) return config_dict
c1ab8c4dda12593d6c67e573b9d1a07041c743db
622,101
import string def int2base(int_x, base): """ Convert an integer value (base 10) to another base :param int_x: a base 10 integer :param base: the base to convert to :returns: the number in a different base """ character_set = string.digits + string.ascii_lowercase + \ string.asc...
c4cec39fcb5c81f606e73f0353ceec71ec06b93e
622,102
import unicodedata import re def slugify(value, replace={}, keepSpace=True): """ Adapted from django.utils.text.slugify https://docs.djangoproject.com/en/3.0/_modules/django/utils/text/#slugify """ replace.update({"[": "(", "]": ")", ":": "_", "()": ""}) value = str(value) value = ( ...
6a25e86e955385a7c4bf0271ec459b217dbfaaa7
622,106
from datetime import datetime def convert_times_to_second_diff(time1, time2): """ Takes 2 time strings in the format "hh:mm:ss P" and calculates the difference in seconds :param time1: :param time2: :return int: seconds """ start = datetime.strptime(time1, "%I:%M:%S %p") end = datetime...
36582fb4cc1169159dac17abf8e75898ab8c60a8
622,111
def FormatDiffHunks(hunks): """Re-serialize a list of DiffHunks.""" r = [] last_header = None for hunk in hunks: this_header = hunk.header[0:2] if last_header != this_header: r.extend(hunk.header) last_header = this_header else: r.extend(hunk.h...
b3baa2ccc1784301a7ebf45746864f1a9bbabaa4
622,114
def split_by_descending_edge(bin_str): """ Split binary string representation by descending edges, i.e. '0101' -> '01 | 01' e.g. '01001101' -> ['01', '0011', '01'] """ prev = '0' split_idx = [0] # generate a list of indices where split needs to happen for idx, i in enumerate(bin_str...
2bed3d7876da669d742bed99ab3f3431976dcb5e
622,121
def _row_name(index): """ Converts a row index to a row name. >>> _row_name(0) '1' >>> _row_name(10) '11' """ return '%d' % (index + 1)
7317ab45a19cf1736451b6d475c810c5b13717de
622,125
def circle_overlaps_circle(circle, other): """ Tells if two circles overlap. The circles must have members 'center', 'r', where the latest is the radius. """ return (circle.center - other.center).magnitude_squared() < (circle.r + other.r) ** 2
8349738e93896b6c275714ba165aa06ce06ba142
622,126
def mode(v): """ Return the mode of `v`. The mode is the list of the most frequently occuring elements in `v`. If `n` is the most times that any element occurs in `v`, then the mode is the list of elements of `v` that occur `n` times. The list is sorted if possible. .. NOTE:: The ...
acf711cd91fbc46768b56661a10c5655c51409a4
622,128
def sort_dict_by_value(dict1: dict, reverse=False): """For a given dictionary, returns a sorted list of tuples for each item based on the value. Examples: >>> employees = {'Alice' : 100000, ... 'Bob' : 99817, ... 'Carol' : 122908, ... 'Fran...
949eb44fc037faea096308cbbce989ebaacd266b
622,129
from typing import Mapping from typing import Any from typing import Tuple def get_retrohunt_info( retrohunt: Mapping[str, Any]) -> Tuple[str, str, str, float]: """Helper function to extract versionId, retrohuntId, state, and progressPercentage from retrohunt. Args: retrohunt: Retrohunt in a Mapping form...
53e1e709e22f6b76129f79e8b05c0215252098b5
622,131
import math def get_col_row(length: int) -> tuple: """ The size of the rectangle (r x c) should be decided by the length of the message, such that c >= r and c - r <= 1, where c is the number of columns and r is the number of rows. :param length: :return: """ r = int(math.sqrt(leng...
f6615c3781706ddd73f78f072c9f7b3669a6460a
622,133
import struct def string_from_buffer(buffer, string_size: int, offset: int = 0): """ :param buffer: bytes returned from e.g. file.read(), which needs to be at least length of string_size+offset :param string_size: the length of the expected string to extract from the buffer :param offset: where in buf...
13254e4376662d00682a36ca427eecacdda8d1ed
622,135
def str_count(string, target, start=0, end=None): """ Description ---------- Count the number of times a target string appears in a string. Parameters ---------- string : str - string to iterate\n target : str - string to search for\n start : int, optional - start index (default is ...
c9b5684b608e57b0df7347b6f3b323ee0101f10e
622,139
def chunk_up(base64str, num_chunks): """ Breaks a base64 encoded string into n equal size parts (the final chunk might be smaller than the others). """ chunk_size = int(len(base64str)/num_chunks) chunks = [] for i in range(num_chunks-1): low = i*chunk_size upper = (i+1)*chun...
062a23f543825fb57a0b1f1b1705096ab8e07224
622,143
def percentile(arr, threshold): """Finds the number at threshold^th percentile of `arr`.""" assert threshold >= 0 idx = int(threshold * len(arr)) return sorted(arr)[idx]
696e98b53a4220b7277b0c92b697574723ac1ee5
622,144
def mean_parallel_B(rm=0.0, dm=100.0): """ Accepts a rotation measure (in rad/m^2) and dispersion measure (in pc/cm^3) and returns the approximate mean value for the paralelle magnetic field compoent along the line of sight, in Gauss. Conversion to Tesla is: 1 T = 10^4 G """ b_los = 1.23 * (rm / dm) return...
f699a9b30016df77a08715bf60fe703388706c45
622,145
import random def calculate_Private_Key(bit_length: int, p: int): """ Provided a byte length, find a random exponent (integer value) of that bit size -1 to use as a private key for Diffie-Hellman (Code from cocalc examples provided by Kevin) """ upper_limit = (p - 2) lower_limit = ((p - 2...
0f4c0bbada20b07b31c55cdc66dba4a8d33892c2
622,146
def test_warn(assertion, func='function', message='False assertion', verbose=True): """Tests if assertion can be interpreted as False. If this is the case, print a warning message, but continue the execution of the program. Returns True if problem found. This can be used in an if clause to perform additional ...
7239827782187d1b68742947039bb691f7a86e30
622,148
import logging def _log(a): """Log data to 'logging' module at INFO level.""" logging.getLogger(__name__).info(a) return a
b61ae588cdad23e831e1fc4b787a7808a9962a56
622,151
def is_serializable(obj: object) -> bool: """ Checks if object is serializable. Args: obj: object to test Returns (bool): serializable indicator """ return hasattr(obj, '__serialize__')
0d03c67ea18d3af245cc9d627e0bf735d467a7a9
622,153
def getStepsFromValues(values, prevValue=0.0): """Convert list of floats to list of steps between each float.""" steps = [] for val in values: currentVal = float(val) steps.append(currentVal - prevValue) prevValue = currentVal return steps
3ac9d419ce97cfeb871221be2e6bc9afe48e1904
622,160
import requests def get_url(url): """ Makes a request to a URL. Returns a JSON of the results :param str url: :return dict: """ response = requests.get(url) if response.status_code == 200: return response.json() else: print("[No data retrieved - %s] %s" % (response.sta...
26ec605759e98d97d68fc4a22ceb59deb8047deb
622,163
import string def preprocess_caption(caption): """Performs caption preprocessing""" punct_table = str.maketrans("", "", string.punctuation) # Extract separate tokens caption = caption.split() # Make tokens lowercase caption = [word.lower() for word in caption] # Remove punctuation capt...
830ec6d6e84d6ff0820cf16a74f7f82ce3beb4be
622,164
def lookup_continuum_range(continuum_ranges, longitude): """ Lookup the velocity range that shouild be used for measuring the continuum levels at a particular longitude. :param continuum_ranges: The list of continuum ranges. :param longitude: The integer longitude to be checked. :return: The mi...
5e525c8a7becc01f0dd70112b5837b49b7596a22
622,165
import pprint def dict_to_string(dict_): """Converts a dictionary into a pretty string """ return pprint.pformat(dict_)
d6dec89db37ae9e1c2f32d97595ff9e02146c326
622,167
def non_strict_neq(a, b): """Disequality between non-strict values Arguments: - `a`: a value or None - `b`: a value of a type comparable to a or None """ if a == None or b == None: return None else: return a != b
368df026668b1f8c8cf3d2f0045e08a1376deb83
622,172
def msvcrt_rand(s=0, size=1): """ Emulate interplay of srand() and rand() :param int s: The seed. :param int size: Desired length of returned data. :return: A sequence of bytes computed using the supplied arguments. :rtype: bytearray """ result = bytearray() for i in range(0, size...
0de2527a86aefd6dfb5a40e07e294844cf2d111f
622,175
def read_file(file_path): """Reads in a Python requirements file. :param str file_path: path to requirements file :returns: list of entries in the file :rtype: list """ with open(file_path) as file_h: return file_h.readlines()
15eae17587a692f14210aa40542aad1cd86191a7
622,176
def _binop_precision(l_dtype, r_dtype, op): """ Returns the result precision when performing the binary operation `op` for the given dtypes. See: https://docs.microsoft.com/en-us/sql/t-sql/data-types/precision-scale-and-length-transact-sql """ # noqa: E501 p1, p2 = l_dtype.precision, r_dtype.p...
a172b4aece2d062a23b1cbbcda0ab9586d9c1b90
622,178
def PNT2TidalOcto_Pv16(XA,beta0PNT=0,beta1PNT=0): """ TaylorT2 1PN Octopolar Tidal Coefficient, v^16 Phasing Term. XA = mass fraction of object beta0PNT = 0PN Octopole Tidal Flux coefficient beta1PNT = 1PN Octopole Tidal Flux coefficient """ XATo2nd = XA*XA XATo3rd = XATo2nd*XA XATo4th = XATo3rd*XA ...
d9692ed1935d1fd451f4d867f171b949ddddccca
622,180
async def edit_message(message, new_content): """ Modify a message. Most tests and ``send_message`` return the ``discord.Message`` they sent, which can be used here. **Helper Function** :param discord.Message message: The target message. Must be a ``discord.Message`` :param str new_content: The text to...
6c962c67562140ee9410504caec366bec845dbe8
622,184
def ens_to_indx(ens_num, max_start=1000000): """ Get the index related to the ensemble number : e.g 101 => 0 :param ens_num: ensemble number, int :param max_start: max number of ensembles, int :return: index, int """ start = 100 while start < max_start: ind = ens_num % start ...
a0af56431df994d1c01207aa2c8a9cf9fd76e258
622,185
def getitem(base, index): """Get an item from the base value""" return base[index]
8ad3cf9923ab49b1277143f1ba8eb17d9b5fd50e
622,186
def merge_dictionaries(base_dictionary, dict_to_be_merged): """Merge two dictionaries into one. Args: base_dictionary (dict): First Dictionary dict_to_be_merged (dict): Seconde Dictionary. Returns: (dict): Merged dictionaries. """ for key in dict_to_be_merged.keys(): ...
b1dee4978e2276520587cc58c2552b2ae7b10fa4
622,192
import math def Urms_calc_1phase(ua): """Function to calculate rms value of scalar phasor quantities for single phase.""" return abs(ua)/math.sqrt(2)
4d774af15c5ba3d61d2ffb9388cc54b56cc267fb
622,193
import importlib def import_mod(pkg): """Helper function for simple frontends. This will return a callable that will load a module. """ def loader(): importlib.import_module(pkg) return loader
a64517e79e8cc6b91b7a9b13b9492edc6c3b0991
622,197
def denormalize(img, mean, std): """ Denormalize the image with mean and standard deviation. This inverts the normalization. Parameters ---------- img : array(float) The image to denormalize. mean : float The mean which was used for normalization. std : float ...
b2fd8315ef4d282409f648ceb3e6a35652bea6e4
622,201
def get_height(root): """ Get height of a node We're going to be skeptical of the height stored in the node and verify it for ourselves. Returns the height. 0 if non-existent node """ if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1
f439f3f63ca1b8d85354c72619c3ac0d454e6ec1
622,204
from typing import Counter def count_exists(id,count): """ Return True if the ID contains exactly COUNT instances of any letter. """ exists = False counts = Counter(list(id)) for c in counts.values(): if c == count: exists = True break return exists
f06dcabf51b3341f4128a01265d1a96067d952a5
622,206
def add_text_generate_args(parser): """Text generate arguments.""" group = parser.add_argument_group('Text generation', 'configurations') group.add_argument("--temperature", type=float, default=1.0) group.add_argument("--top_p", type=float, default=0.0) group.add_argument("--top_k", type=int, defau...
7231b207248418e237c9974c1479a34c542af13a
622,208
def add_FDI(data): """ Forest Discrimination Index (FDI) = (NIR - (Red + Blue)), for 6 bands images, (FDI) = (B8 - (B6 + B2)), for 8 bands images """ return ((data[7,:,:] - (data[5,:,:] + data[1,:,:]))).expand_dims(dim="band", axis=0)
9ed4b1b7d635320d764fcbe5fe8970e3c06f40e9
622,210
from pathlib import Path from bs4 import BeautifulSoup def _unused_html(outdir: Path) -> BeautifulSoup: """Read and parse generated test unused.html.""" text = (outdir / "unused.html").read_text(encoding="utf8") return BeautifulSoup(text, "html.parser")
e71ef0dff51e38c807f39487089a8c4a752ffa46
622,214
def _render_template(template, destination, **kwargs): """Render a template into a file destination. :param template: A text template to be rendered :param destination: Destination file name. :param kwargs: Arguments for the template render.""" content = template.format(**kwargs) with open(desti...
38056c6123a557bdc0c045c3398291304375a867
622,215
def fhir_version_name(fhir_version): """ Get the name of a particular FHIR version number :param: fhir_version :type: str :returns: str """ major_version = int(fhir_version.split(".")[0]) if major_version < 3: return "dstu2" elif (major_version >= 3) and (major_version < 4...
22d2429e25dfec035fadf022151c25ef017492f5
622,216
import importlib def get_func_by_name(fn_name): """Automatically import function by its name Args: fn_name (str): import path of a function Returns: Callable: a python function """ module, fn = fn_name.rsplit(".", 1) try: module = importlib.import_module(module) e...
f368a5716e4eef7d73823aaf87e7c6da64a564af
622,218
import re def top_level_separator_regex(separator): """Returns a regex that matches separators in only the top level of a string (i.e. no separators found within parenthetical statements).""" sep_pattern = re.escape(separator) return sep_pattern + r'(?![^\(]*\))'
bca22dc2b0dabae2c9efeb9fd1ce01dc20c58df2
622,224
import math def readable_size(sbytes): """Converts bytes into a human readable size. Size is reported in units based on powers of 2 (where one KiB is 1024 bytes). @param sbytes <int>: Size in bytes @return size <str>: Returns human readable size """ units = ("B", "KiB", "MiB", ...
272603750a08c5e9f733aa5b5a8fdc1dc4cee1fd
622,227
import torch def get_device(option: str = "auto"): """helper function for getting pytorch device Paramaters ---------- option: - if "auto" it tries to get the GPU and returns CPU if unavailable - if "cpu" just use CPU """ if option == "auto": return torch.device("cuda:0" i...
5fb38ae213ac356a76b7026304e87ca7d5131896
622,228
def as_bool(val): """ Convert a value to a boolean. `val` is `True` if it is a boolean that contains True, is a string of 'true' or 't' (case-insensitive), or is a non-zero numeric (or string of non-zero numeric). False in all other cases including if `val` is `None`. :param val: Value to test. ...
771c306bd63c1199df0bbac5ee9e34f4bcdc62a3
622,236
def isprefix(path1, path2): """Return true is path1 is a prefix of path2. :param path1: An FS path :param path2: An FS path >>> isprefix("foo/bar", "foo/bar/spam.txt") True >>> isprefix("foo/bar/", "foo/bar") True >>> isprefix("foo/barry", "foo/baz/bar") False >>> ispre...
fad5eed531ed7fb3ed4e982d3fd7649dbf08ecac
622,237
def get_pars(ts, coors, mode=None, region=None, ig=None): """ We can define the coefficient `load.val` as a function of space. For scalar parameters, the shape has to be set to `(coors.shape[0], 1, 1)`. """ if mode == 'qp': x = coors[:,0] val = 55.0 * (x - 0.05) ...
00ea9705a9f59388d1d3ab1c97796da687da6686
622,238
def _GetTracingRerunOptions(point): """Gets the trace rerun options, if available. Args: point: A Row entity. Returns: A dict of {description: params} strings, or None. """ if not hasattr(point, 'a_trace_rerun_options'): return None return point.a_trace_rerun_options.to_dict()
85f3b7aaacec5595f766a64d3b5cfb236c597efd
622,241
import math def cosd(v): """Return the cosine of x (measured in in degrees).""" return math.cos(math.radians(v))
80efb607b3ee362d31913a626f0d301c23ab4639
622,242
import hashlib import random def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: ...
7b3df283e595395985c228413626f97c9d0ceba0
622,245
def controller(msg): """Returns the controller number of a control change message.""" return msg[1]
634c00be507087721a7faca04f3b4cea9be2861a
622,247
def normalize_querydict(querydict): """ Converts a `QueryDict` to a normal, mutable dictionary, preserving list values. QueryDict('foo=1&bar=2&bar=3&baz=') becomes: {'foo': '1', 'bar': ['2', '3'], 'baz': ''} This function is necessary because `QueryDict` does not provide any built-in ...
656c4dcb03f0a592deda7a466cd656808b616d2a
622,248
def get_itim_length(memories): """Get the length of the itim, if it exists""" if "itim" in memories and "length" in memories["itim"]: return memories["itim"]["length"] return 0
9aade79e6be8f259914fe2f57b6de60641c17f4e
622,252
def register_account(client, user, pword, rem=True, captcha=None): """ Create a new Reddit account: log in with user_login() once logged in, you can register new accounts every five minutes without entering captcha. user: the username of the new account you wish to create pword: a password for t...
2aa01ef1a17baf1b4fcfa1c864d3adbba1426b0f
622,254
def oneline(value): """ Replace each line break with a single space """ return value.replace('\n', ' ')
131416fe6b312d95ec29990bd0dab0e12ee2af4c
622,255
def check_numeric_type_instance(value) -> bool: """Method checks if value is int or float Parameters ---------- value : Expected Numeric type Returns ------- : bool True - value is numeric, False - value is other than the number """ if isinstance(value, str): return...
5d05c0a205014d2f411a8de829d65ba6ba8b6f11
622,256
def getOrthographyReferenced(crappyReferenceString, row, orthographies): """Return the id of the orthography model referenced in ``crappyReferenceString``. ``crappyReferenceString`` is something like "Orthography 1" or "Object Language Orthography 3" and ``row`` is a row in the applicationsettings table. `...
122c3826d59f981a7c44e97d0a5f2792175f115d
622,258