content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_interaction_id(question_id):
"""Returns the interaction_id from input question_id."""
rindex = question_id.rfind("_")
if rindex == -1:
return question_id
return question_id[:rindex] | d1e0bf238de9db0185b6db4828a1adc238d8025d | 630,245 |
def merge_config(c1, c2):
"""
Merge 2 configs c1 and c2 (where c1 is the default config and c2 the user defined config).
A config is a python dictionary. The result config takes key:value from c1 if key
is not present in c2, and key:value from c2 otherwise (key is either present both in
in c1 and c... | 32d0315002ac9448b19634652a300960d2e65567 | 630,249 |
from pathlib import Path
def read_file(loc: str | Path) -> str:
"""Read test from a file.
:param loc: The file system location of the file.
:return: A :class:str object.
:rtype: str
"""
path = Path(loc)
with open(path) as fh:
contents = fh.read()
return contents | 41ef8e225e2a30ea4df4d90303b089c749607cc7 | 630,251 |
import re
def _normalise_id(raw_id):
"""Reddit IDs start with t1_, t2_, etc. which need to be stripped."""
return re.sub("^t[0-9]_", "", raw_id) | 6d9def895e6aeb60a606849387810050b09f2cd7 | 630,254 |
def dist(spectrum, A, B):
"""
Minimum number of steps along ring to get from one pitch to the next
Parameters:
-----------
spectrum: list
user-defined spectrum
A: int
first pitch
B: int
second pitch
"""
length = len(spectrum)
forwa... | 3ecda36a9912f3088949b406f93ccf0654d505c1 | 630,257 |
def get_planet_product_type(img_path):
"""
return if file is scene or OrthoTile"""
split = img_path.stem.split('_')
# check if 4th last imagename segment is BGRN
if split[-4] == 'BGRN':
pl_type = 'OrthoTile'
else:
pl_type = 'Scene'
return pl_type | 70aac7930fb95c0270f4b74a51a09e5d72ea8aeb | 630,258 |
import requests
def shrink(url):
"""
Shrinks the given URL.
"""
return requests.post('http://tinyurl.com/api-create.php', data={'url': url}).text | facf0c6fa34e8663648c177d99895f90a436b0e9 | 630,259 |
def get_license(j):
"""
By default, the license info can be achieved from json["info"]["license"]
In rare cases it doesn't work.
We fall back to json["info"]["classifiers"], it looks like License :: OSI Approved :: BSD Clause
"""
if j["info"]["license"] != "":
return j["info"]["license"]... | c736967189b170155fe9948ab83c9e54c4ca2719 | 630,262 |
def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_liter... | 14bb312074b06d3b8d5e9e66652050d9247700af | 630,263 |
def decode_params(filename):
"""
Decode the tlusty filenames for the model parameters
"""
model_params = {}
slashpos = filename.rfind("/")
periodpos = filename.rfind(".flux")
# translation of metallicity code
met_code = {"C": 2.0, "G": 1.0, "L": 0.5, "S": 0.2, "T": 0.1}
met_char = ... | c08a13f1aa3bc9d24564085837192264edcf9953 | 630,264 |
def checkpoints(period, total):
"""
A helpful function for individual train method.
to generate checkpoint list with integers
for every PERIOD time steps and TOTAL time steps in total.
"""
ckps = [
period * x for x in range(1, total // period)
]
return ckps | f0bb59f3aa5da73fe6d70ecf7d7788a2b5437551 | 630,267 |
def json_length(msg_body: str) -> str:
""" The robot's JSON API requires the length of the JSON command to be specified before the JSON command. This
function calculates the length of the JSON message body and formats it for the JSON API.
:param msg_body: the JSON message body.
:return: the length of t... | 527b90c42fa055879680b2dbd0511e531a8422fe | 630,268 |
from typing import List
def how_many_namefellows(queue: List[str], person_name: str) -> int:
"""
:param queue: list - names in the queue.
:param person_name: str - name you wish to count or track.
:return: int - the number of times the name appears in the queue.
"""
return queue.count(person... | 8364adb4226d0f09bb5a7a90af0aee518d448a95 | 630,273 |
def extract_capabilities(text):
"""Extract a capabilities list from a string, if present.
Args:
text: String to extract from
Returns: Tuple with text with capabilities removed and list of capabilities
"""
if b"\0" not in text:
return text, []
text, capabilities = text.rstrip().spl... | 6d974b58275d676d712583a83f08d90e3e2186df | 630,275 |
import torch
def extract_ampl_phase(fft_im):
"""
Extracts amplitude and phase from the image
Args:
fft_im (Tensor): size should be bx3xhxwx2
Returns:
tuple: (amplitude, phase)
"""
# fft_im: size should be bx3xhxwx2
fft_amp = fft_im[:, :, :, :, 0]**2 + fft_im[:, :, :, :, 1]*... | 59d14c950530228262a712427496be9d99840a1c | 630,278 |
def __float2str(value: float) -> str:
"""Convert a float into a human readable string representatoin."""
if value == 0.0:
return "0.0"
return "{0:.5f}".format(value) | 87f315f71ef97a6974e5d9b2ece9f911a209a944 | 630,281 |
def set_prior(kind = 'scale',
logbeta_max=-1,
logbeta_min=-6,
M_max=20, r_max=30,
scale_max=25,
mu_ol_max=25,
r_min_min=0.3,
r_max_max=1.5,
delta_r_min=0.2):
"""
Setup prior transforms for models... | d3a5bb7f6a195947cd5df5db345bdeb12a5dc488 | 630,291 |
import typing
def get_word_transform(name: str) -> typing.Callable[[str], str]:
"""Gets a word transformation function by name."""
if name == "upper":
return str.upper
if name == "lower":
return str.lower
return lambda s: s | 1dde1f9aed0b44e47ee429a778afcf111eb01471 | 630,295 |
def make_query(user_id=None, tenant_id=None, resource_id=None,
user_ids=None, tenant_ids=None, resource_ids=None):
"""Returns query built from given parameters.
This query can be then used for querying resources, meters and
statistics.
:Parameters:
- `user_id`: user_id, has a prio... | 6ec0197f1a9071ecd4381542d323997a12bc55ee | 630,296 |
def get_model_pk_column(model_class):
"""
Get the primary key Column object from a Declarative model class
:param Type[DeclarativeMeta] model_class: a Declarative class
:rtype: Column
"""
primary_keys = model_class.__mapper__.primary_key
assert len(primary_keys) == 1, "Nested object must h... | c73cd31beb9a7609e020c278d0f9703f541c7eeb | 630,298 |
def lgfCoord(point, lgfOrigin, trf2lgfMatrix):
"""
Determines the coordinates of a point in a Local Geodetic Frame.
:param point: Coordinates of the point of interest expressed in ECEF
:param lgfOrigin: Coordinates of the LGF origin expressed in ECEF
:param lgf2trfMatrix: Rotation matrix from
:... | 9d0cd25a17aaeca360f25b2e789bb27412bcedf4 | 630,302 |
import math
def poh_from_hydronium(concentration):
"""Returns the pOH from the hydronium ion concentration."""
return 14 + math.log(concentration) | 5772099bfb75b0b1e056f4274c2e09e7c887e193 | 630,303 |
def __ror__(self, x):
"""Allows piping input to :class:`torch.nn.Module`, to match same style as
the module :mod:`k1lib.cli`. Example::
# returns torch.Size([5, 3])
torch.randn(5, 2) | nn.Linear(2, 3) | cli.shape()"""
return self(x) | 2994a3dce0e9d3d8b1de85a3b25166b9514d868f | 630,304 |
def reverse_match(seq: str, recog: list) -> (bool):
"""
Match the sequence with a recognition sequence in reverse.
:param seq: the sequence to search in
:param recogn: a list with bases that should be
matched subsequently
:return: True if the sequence matches the
rec... | 7686d8d727ac360dc655f80605b20f19f6d2e25c | 630,307 |
import base64
def encode_bytes(bytes_):
""" Encodes some given bytes into base64 using utf-8.
:param bytes bytes_: The bytes to encode
:return: The bytes encoded base64 string
:rtype: str
"""
return base64.encodebytes(bytes_).decode("utf-8") | c434c4cec4a235546ba0ff985d82ddac0d2bf05d | 630,310 |
import torch
def max(dat, dim=None):
"""Maximum element (across an axis) for tensors and arrays"""
if torch.is_tensor(dat):
return dat.max() if dim is None else dat.max(dim=dim).values
else:
return dat.max(axis=dim) | 9fc000bd9635129a448fa00926cf21b648048b49 | 630,315 |
def payload_to_str_base(payload):
"""
Converts a given payload to its str_base representation.
A str_base payload is for example: "0xFF 0xFF 0xFF 0xFF".
:param payload: The payload to be converted.
:return: Returns the str_base representation of the payload.
"""
result = ""
for i in ran... | aa414aca57f3743cb270c3affbd7f9a6bbbda1de | 630,325 |
def _next_regular(target):
"""
Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer.
... | 3cfd3975ad71904283054c3b5b1721b8f409cfb3 | 630,329 |
def __decode_lens__(lens_package):
""" decode the lens_package tuple into its constituents
Args:
lens_package: a tuple or a |ParaxialModel|. If it's a tuple:
- the first element is a |ParaxialModel|
- the second element is a tuple with the begining and ending
... | acdd08577362845c6c95b59feb63f90ec9ef65ce | 630,332 |
def euclidean_algorithm(a: int, b: int) -> int:
"""
Finds the greatest common divisor of two natural numbers.
If n or k is less than or equal to 0, it raises ValueError.
>>> euclidean_algorithm(6,9)
3
>>> euclidean_algorithm(8, 20)
4
>>> euclidean_algorithm(19, 17)
1
>>> euclidea... | 20dfb1521cc1703a978aa20ea37d2673f648cc39 | 630,335 |
def setdiff(list1, list2):
"""
returns list1 elements that are not in list2. preserves order of list1
Args:
list1 (list):
list2 (list):
Returns:
list: new_list
Example:
>>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight']... | 19fb7a44b2796432404f80f46b9650996b45248c | 630,336 |
from functools import reduce
def createLookup(B):
"""Process B to create a reverse lookup scheme that is appropriate for
any of the libraries in pyncomb that allow for one or more base sets to
be specified.
Let rev(K) be the reverse lookup dictionary of a list K, i.e. if
K[i] = j, then rev(K)[j] ... | 6bb2f907fa71cbd7fa4a2ab1482b0457acd61b36 | 630,337 |
def __makenumber(value):
"""
Helper function to change the poorly formatted numbers to floats
Examples:
> value is an integer / float data type -> float type returned
> value = '1,000', then the float value is 1000
> value = '1 000 000.00' then the float value is 1000000
... | 6f1b9c718cb0cce1c9a058ff533c603aad2948e0 | 630,339 |
def request_add_host(request, address):
"""
If the request has no headers field, or request['headers'] does not have a Host field, then add address to Host.
:param request: a dict(request key, request name) of http request
:param address: a string represents a domain name
:return: request after add... | 0ae2eb267e5042b3a662fb8f8b6bb4ec03c56b37 | 630,340 |
import re
def replace_template_vars(string, dictionary):
"""Replaces template variables like {{SOME}} in the string
using the dictionary values."""
orig_string = string
for key, value in dictionary.items():
string = string.replace("{{"+key+"}}", value)
if string == orig_string:
rai... | da1f054360ca906d960588d7ca6edb6c4245bf35 | 630,341 |
def classif_accuracy(labels, preds):
"""Gets the percentage of correct classified predictions.
Parameters
----------
labels : torch.tensor
The true labels.
preds : torch.tensor
The prediction.
Returns
-------
float
Percentage of correct classified labels.
"... | 557aac48865b2d7c942be71bd4ec73ba75e380d6 | 630,343 |
def indexing(pair):
"""
The indexing method receives a pair of user X and followed users by X.
for example it receives (X, Fi) as a pair which X follows Fi.
This method returns (Fi, X) and (X, -Fi).
:param pair: (X, Fi) as a pair which X follows Fi.
:return: is a list of pairs [(Fi, X), (X, -Fi)... | bdb96f5f8e23a81dc4f2f90cbe3e0a2dfeb134ad | 630,346 |
def sanitize_single_id(value: str | int) -> str:
"""
Update `value` to a sanitized sql-friendly name.
Force to string and then scrub out: space, slash, dash, comma
e.g. "Food/Drink" -> "fooddrink"
Arguments:
value (str | int): unique ID value for a POI
Returns:
str: POI value ... | e273f2e9c8e9d19990351d1b71be293f41ce7690 | 630,348 |
def is_in(x, l):
"""Transforms into set and checks existence
Given an element `x` and an array-like `l`, this function turns `l` into a
set and checks the existence of `x` in `l`.
Parameters
--------
x : any
l : array-like
Returns
--------
bool
"""
return x in set(l) | 4e99e946177f85493f6404f170fadca4b5c1e8f2 | 630,354 |
import re
def termlist_to_doubleamp_query(termlist_str, field=None):
"""
Take a comma separated term list and change to a
(double ampersand) type query term (e.g., for solr)
>>> a = "tuckett, dav"
>>> termlist_to_doubleamp_query(a)
'tuckett && dav'
>>> termlist_to_doubleamp_query(a, f... | 2d841e0508c4c403f0aae9398fca33e398c6b4e5 | 630,355 |
import re
def tokenize_datetime(text: str) -> str:
"""Tokenizes datetime to make it consistent with the seaweed tokens."""
# 5.10 => 5 . 10
# 4:00 => 4 : 00
# 5/7 => 5 / 7
# 5\7 => 5 \ 7
# 3-9 => 3 - 9
text = re.sub(r"(\d)([.:/\\-])(\d)", r"\1 \2 \3", text)
# 4pm => 4 pm
text = re... | f7a92b501ad44eef318a46c63c05b028a2d5658f | 630,356 |
def ambitus(pitches: list) -> int:
"""The ambitus or range of a melody in semitones
>>> ambitus([60, 62, 64, 65, 60])
5
Parameters
----------
pitches : list
List of MIDI pitches
Returns
-------
int
The ambitus
"""
return max(pitches) - min(pitches) | 6acc0ec73d7c8cb18cc10eaa0ea0d47d6f0f4ad7 | 630,360 |
def Clamp01(num):
"""
Returns ``num`` clamped between 0 and 1.
Parameters
----------
num : float
Input number
"""
if num < 0:
return 0
if num > 1:
return 1
return num | 0c3eda62d9fbf077804329d0fe088d7871f20f2d | 630,361 |
def get_dayseconds(dt):
"""Returns the number of seconds behind the most recent midnight.
For example: ``get_dayseconds(datetime(2016, 9, 12, 1, 2, 3)) => 3723``.
"""
return dt.hour * 3600 + dt.minute * 60 + dt.second | 3d538a9a5396017ae265599fe4de36fe8ec00065 | 630,365 |
def extract_encoding_and_rate_from_wav_header(wav_header):
"""
Attempt to extract encoding, sample rate from possible WAV header.
Args:
wav_header (bytes):
Possible WAV file header.
Returns:
Union[bool, str]:
False or truthy value, which may be the encoding name... | b4fd300e9e3656f1b1d0d866255c749aabd5e7f7 | 630,367 |
def wrap_in(key):
"""Wraps value in dict ``{key: value}``"""
return lambda val: {key: val} | a6024eeb8f5479dc8ab22aa1eee12fd46baaf9a0 | 630,372 |
def tartaglia(n):
""" Funzione per generare un triangolo di tartaglia.
Parametri
---------
n: int
Altezza del triangolo da generare
Output
------
triangolo: list of lists [[],[],[],...]
Lista di liste, corrispondenti alle righe del triangolo di tartaglia.
Esempio
-... | 1dbb18879e565feef3405e533da492936d4a4b20 | 630,373 |
from datetime import datetime
def format_datetime(dt: datetime):
"""Format a datetime for Magento."""
# "2021-07-02 13:19:18.300700" -> "2021-07-02 13:19:18"
return dt.isoformat(sep=" ").split(".", 1)[0] | a155da72139ab17f0e19c93fe0cd68f1e3ff8dbc | 630,378 |
def _normalize_path(path):
"""Internal helper that strips "./" on the left side of the path. """
if path.startswith("./"):
return path[2:]
return path | 3db6add232715b51bfa8965eb4270808fe87df0a | 630,379 |
def add(a, b):
"""
Adds two numbers.
>>> add(3, 2)
5
:param a: first number
:param b: second number
:return: sum
"""
return a + b | d6dba1312b240d6c7e36fe2a6d00a33cb316f611 | 630,383 |
import json
def load_dataset(data_path):
"""Load existing json format dataset
"""
datafile = open(data_path)
return json.load(datafile) | 7d125a6308c89de15cf4fa6a6edb8cd7c656148c | 630,384 |
def get_sorted_node_parents(graph, node_with_parents):
"""
Get the parent nodes of a WIR node sorted by argument index.
"""
node_parents = list(graph.predecessors(node_with_parents))
node_parents_with_arg_index = [(node_parent, graph.get_edge_data(node_parent, node_with_parents))
... | 8bff6064b01f6eff8baf6de545fb925440f43523 | 630,386 |
from datetime import datetime
def dt_obj_to_isodt_str(dt):
"""
Convert datetime object to ISO 8601 string.
:param datetime dt: datetime object in UTC timezone
:returns: ISO 8601 string
"""
assert isinstance(dt, datetime)
# Using naive datetime object without timezone, assumed utc
retu... | a5949c6eca118f8611ed7b3cf61735c376c6a578 | 630,387 |
import json
def is_json_format(str):
"""json値判断
Args:
str (str): json文字列
Returns:
bool: True:json, False:not json
"""
try:
# Exceptionで引っかかるときはすべてJson意外と判断
json.loads(str)
except json.JSONDecodeError:
return False
except ValueError:
return ... | 38dd2df38dd9ec4be900284476a237cd33c946dd | 630,388 |
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
"""
Find control points of the Bezier curve passing through (*c1x*, *c1y*),
(*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
"""
cmx = .5 * (4 * mmx - (c1x + c2x))
cmy = .5 * (4 * mmy - (c1y + c2y))
return [(c1x, c... | 219b053f98a14149305dbeda67acd5ba1163b04c | 630,390 |
def sensitivity_calc(sign_residues_per_iter):
"""
| Inputs the output of ``bootstrapped_residue_analysis`` and calculates the sensitivity of each residue.
| The returned sensitivity of each residue is calculated by calculating ``residue_appearances / iterations``.
| A sensitivity of 1 is ideal meaning t... | f92772ea60d3ca660ee63aefa024047f8e3c5495 | 630,392 |
def numpy_dtype_to_numeric_type(element):
"""Return a valid numeric_type value based on the dtype of numpy array."""
lst = {
"<u1": "uint8",
"<u2": "uint16",
"<u4": "uint32",
"<u8": "uint64",
"<i1": "int8",
"<i2": "int16",
"<i4": "int32",
"<i8": "i... | acf1fb8e7016319bfc97314e751beae34aee8c06 | 630,393 |
def value_check(inval):
"""
Check if a value is equal to None
:param inval: the input value
:param inval: float
:return: 1 if the input value is None, 0 otherwise
:return type: integer
"""
result = 0
if inval is None:
result = 1
return result | fa2cfd39c8ec581eb486553cde82331fe21b50de | 630,395 |
def nvl(value, defval="Unknown"):
"""
Provide a default value for empty/NULL/None.
Parameters
----------
value: obj
The value to verify.
defval: obj
The value to return if the provide value is None or empty.
Returns
-------
defval if value is None or empty, othe... | 2717b259464a75bca2305aa90f34ba8dafb2935b | 630,397 |
def slope_tree_check(lines: list, dx: int, dy: int) -> int:
"""check how many trees would be encountered with a specific slope"""
x_pos = 0
y_pos = 0
trees_encountered = 0
line_length = len(lines[0])
while y_pos < len(lines):
if lines[y_pos][x_pos] == '#':
trees_encountered +... | d4d518a121893df0d21720e2986887c85087f2e6 | 630,400 |
import math
def log10_zero(x):
"""Return the log10 of x, map log10(0) -> 0."""
if x == 0:
return 0
else:
return math.log10(x) | c47498ff88c83785e98420a02cd2d3d6884864e6 | 630,404 |
def get_digit_at_pos(num, base, pos):
"""
Gets the integer at the given position of the number in a specific base
@param num The number we wish to find the converted digit in
@param base The base in which the digit is calculated
@param pos The position of the digit to be found
@re... | 09026aad59d635f45c706d3d1c5bc61a6127c17b | 630,405 |
def bit_last(x):
"""
Get the last digit where 1 stands (0-indexed)
x.bit_length()と同じ。
ref: https://www.slideshare.net/KMC_JP/slide-www
Args:
x (int): bit
Returns:
int: last digit
>>> bit_last(1)
0
>>> bit_last(4)
2
>>> bit_last(6)
1
>>> bit_last... | 0c5d81af03a19ce7ae1b2c06323fa3ddf35c14cf | 630,406 |
import hashlib
def get_file_hash(path, block_size=8192):
"""Calculates the content hash for the file at the given path."""
md5 = hashlib.md5()
with open(path, 'rb') as f:
while True:
block = f.read(block_size)
if not block:
break
md5.update(block... | 429258dc30bb5a6ab10e5c5c5f98000a0c1f324d | 630,409 |
def create_message_subject(info, context):
"""
Create the message subject
"""
base = '%s request completed' % context['display_name']
if info['errors'] > 0:
return '%s with ERRORS!' % base
elif info['warnings'] > 0:
return '%s with WARNINGS!' % base
else:
return base | 3369b7d3637dd6540ff721b33346d428d4bcd1bb | 630,411 |
import string
def is_pangram(s):
"""
Detect whether or not a given string input is a pangram.
:param s: a string value.
:return: true if string is a pangram, otherwise false.
"""
return set(string.ascii_lowercase) <= set(s.lower()) | 89acf3fa64f74091df74f095cf7a806c78457658 | 630,414 |
def format_input(x):
"""Transforms rows of numers written as strings into a list of lists of ints"""
delimiter = '\t' if '\t' in x else ' ' # test_value doesn't use \t but input does
return [[int(s) for s in r.split(delimiter) if s != ''] for r in x.split('\n')] | 991503c0e0fc5fbc3a444a0849d7eb976a91a5fe | 630,416 |
def cond(x, singular=False, order=0):
"""
If It is singular, return 1 if x>0 else 0.
If It is not singular, return x**order if x>0 else 0
"""
if singular:
return 1 if x>0 else 0
return x**order if x>0 else 0 | f49aea4010c44613d8b8c98c25d86d0ed5627d34 | 630,419 |
import json
def read_summary(filename):
"""Reads the summary dict from a JSON file."""
with open(filename) as f:
return json.load(f) | da7d1798181e513dff2e8cae934081759ce5045d | 630,425 |
def rho(parameters, theta_v, pi):
"""
Returns an expression for the dry density rho in kg / m^3
from the (virtual) potential temperature and Exner pressure.
:arg parameters: a CompressibleParameters object.
:arg theta_v: the virtual potential temperature in K.
:arg pi: the Exner pressure.
"... | 8b7a38bdaa48994af7dbb77034b8c795f5f89cb5 | 630,427 |
def check_column(col, sep=":"):
"""Convert input column string to list of columns
:param col: input string
:param sep: default ":"
:return: list of columns
"""
if isinstance(col, str):
col = col.split(sep)
elif not isinstance(col, list):
raise TypeError(f'Columns "{col}" nee... | eb6fb0e645fd7eb59fbf46a13c01efecef4906d8 | 630,428 |
def is_palindrome(value):
"""Check if a string is a palindrome."""
return value == value[::-1] | 524c2c67874f41854034ec319c10a05e7e267727 | 630,429 |
def _mult_diag_matrix(D, mtx, on_right=False):
""" Multiply diagonal matrix D to mtx
Args:
D (N ndarray) - diagonal matrix
mtx (ndarray) - matrix to multiply
on_right (bool) - whether to return D * mtx (False) or mtx * D (True)
"""
if not on_right:
return (D*mtx.T).T
else:
... | f2d30e8cbb2ef7b842d3daa922185bc3758a5094 | 630,430 |
def get_reflectivity_name(radar):
"""
Test for several possible name for the ground radar reflectivity.
Parameters:
===========
radar: object
Py-ART radar structure
Returns:
key: str
Reflectivity field name.
"""
possible_name = ['reflectivity', 'corrected_reflectivi... | 75bdf283334f2eaea853396fe500bc844bbadfb4 | 630,431 |
import random
import string
def generate_id(length: int = 6) -> str:
"""Helper function for generating an id."""
return "".join(random.choices(string.ascii_uppercase, k=length)) | d90f15c0332c5257846f6f719321d182111c6782 | 630,433 |
def combine_expression_columns(df, columns_to_combine, remove_combined=True):
"""
Combine expression columns, calculating the mean for 2 columns
:param df: Pandas dataframe
:param columns_to_combine: A list of tuples containing the column names to combine
:return:
"""
df = df.copy()
... | 8c9e4be3dbfb8660e659ae09d4d01024bf910906 | 630,434 |
import click
def stack_options(func):
"""
stack_options is a decorator which adds the stack and environment arguments
to the click function ``func``.
:param func: The click function to add the arguments to.
:type func: function
:returns: function
"""
func = click.argument("stack")(fun... | 2291bf119703dae45722dd721ccfd42c2d238bf6 | 630,435 |
def format_pdb_code_for_inputs(pdb_code: str, source_type: str):
"""Format given PDB code for prediction inputs."""
return pdb_code[1:3] if source_type.lower() == 'input' else pdb_code.upper() | 430a97ec59e5c32175f40f2595db5dd90650275a | 630,436 |
def is_palindrome(n):
"""Tests if a number is a palindrome
Args:
n (Integer): Integer to test palindromomity
Returns:
Boolean: True if n is a palindrome, false otherwise
"""
# Turn the integer into a list of characters
chars = list(str(n))
length = len(chars)
# ... | 333b76f1b3de1f66489d3295e2d6e459e89b2727 | 630,437 |
from typing import Callable
def create_callable(func: Callable, *args, **kwargs) -> Callable:
"""
Function creates a callable function where the called function gets passed as an argument along with its
args and kwargs.
Args:
func (Callable): Function to be called
*args (any): Args pa... | 247fd8b29f93cbca2109d4c5d527ae44d21f8abc | 630,439 |
def flatten_deps(deps):
"""Converts deps.lock dict into a list of go packages specified there."""
out = []
for p in deps['imports']:
# Each 'p' here have a form similar to:
#
# - name: golang.org/x/net
# version: 31df19d69da8728e9220def59b80ee577c3e48bf
# repo: https://go.googlesource.com/... | 1a1b5206ff0b592b1972f4f081594c7a8c7b867b | 630,440 |
def transpose(a):
"""
transposes a matrix
"""
return list(zip(*a)) | 5d311c90c61977eb59d63e9ebc0c3bc23b73889e | 630,441 |
def reduce_names(l):
"""Reduce the names in the list to acronyms, if possible.
Args:
l (list(str)): list of names to convert.
Returns:
(list(str)): list of converted names.
"""
for i, item in enumerate(l):
if item == 'QuadraticDiscriminantAnalysis':
l[i] = 'QDA'... | 0d9c8a7d226297658054491d10067b6426cb1287 | 630,442 |
def breit_wigner_fano_alt(x, height=1.0, center=0.0, sigma=1.0, q=-3.0):
"""
An alternate Breit-Wigner-Fano lineshape that uses height rather than amplitude.
breit_wigner_fano(x, height, center, sigma, q) =
height * (1 + (x - center) / (q * sigma))**2 / (1 + ((x - center) / sigma)**2)
"""
... | bf52b96b56ed3fc89a8ed694488ac0b9a0e0b2bf | 630,445 |
import json
def load(file: str):
"""
load json file with default options
:param file: file path to load
:return: json data as python object
"""
with open(file, 'r', encoding='utf-8') as jsonfile:
config = json.load(jsonfile, encoding='utf-8')
return config | 4b500378512d9e2373a92454d0a625107de6f17e | 630,446 |
def update_and_return(dictionary: dict, **kwargs) -> dict:
"""
Utilises the standard dictionary update() function but instead of
returning None it will return the updated dictionary.
:param dictionary: The dictionary that should be updated
:param kwargs: Kwargs of the update method
:return: The... | 69652f1a512eecfa323b7df5048f14c6e4900bde | 630,447 |
def mtx_zip_url(expression_accession):
"""Make the url to grab the zipped mtx experssion data from the ebi's accessionI_id"""
url = "https://www.ebi.ac.uk/gxa/sc/experiment/%s/download/zip?fileType=quantification-filtered&accessKey=" \
% expression_accession
return url | d853cb999958a58651a05e6a2c27d9bc528c4396 | 630,451 |
from datetime import datetime
def read_timestamp(time_string):
"""Return a datetime object from the timestamp string"""
return datetime.strptime(time_string, '%Y%m%d%H%M%S') | 6b4e2d2521e738acb7166d4a1a1b716128fc14e8 | 630,452 |
def readSif(fn):
"""reads in the sif file fn and ouptputs a
dictionary and a list:
interDict : has "interaction" as key
and [(node1,node2), (node3,node4)] as values
nodes list : is the list of unique node names
(both on the right or left hand of an interaction)
"""
interDict = {}
... | 6f8070e95de228291480120bbf86fe628e857dfa | 630,460 |
import math
def airmass(Z, units='degrees'):
"""Calculate the airmass for a source according to Airmass=sec(Z) where
Z is the zenith distnce
Z--zenith distance
units--units of Z
"""
if units=='degrees': Z=math.radians(Z)
return 1.0/math.cos(Z) | 4ba98faff36c5615b978f1b58ed6c7e679b2aa80 | 630,464 |
def enum_words(words_iterable):
"""Return string:
() -> ''
('a') -> 'a'
('a', 'b') -> 'a and b'
('a', 'b', 'c') -> 'a, b and c'
"""
ws = words_iterable
if not ws:
return ''
elif len(ws) == 1:
return ws[0]
elif len(ws) == 2:
return f'{ws[0]} and {ws[1]}'
... | 52897d2dc61337acc840adf134317f7cae391b5f | 630,466 |
def shift(txt, indent = ' ', prepend = ''):
"""Return a list corresponding to the lines of text in the `txt` list
indented by `indent`. Prepend instead the string given in `prepend` to the
beginning of the first line. Note that if len(prepend) > len(indent), then
`prepend` will be truncated (doing be... | a8c75a35bcffb07c2a619d1a208a12fb1ba8c0f8 | 630,468 |
def redact_after_symbol(text:str, symbol:str) ->str:
"""Replaces all characters after a certain symbol appears with XXXXX"""
r_start = text.find(symbol)
r_len = len(text) - r_start
to_redact = text[r_start:]
return text.replace(to_redact, "X"*r_len) | a9a46f4222aff97c5aec2a2d843b4e7bffab031b | 630,470 |
def is_aware(dt):
"""Return whether the datetime is aware.
See https://docs.python.org/3/library/datetime.html#determining-if-an-object-is-aware-or-naive
:param dt: The datetime object to check.
:returns: True if ``datetime`` is aware, False otherwise.
"""
return dt.tzinfo is not None and dt.t... | d3c2f44727f5eb1be5011c2eeb07aaa1fe55ab33 | 630,475 |
from pathlib import Path
def load_txt_to_string(file_path):
"""
Loads a txt file and returns a str representation of it.
:param file_path: str or Path object
:return: The file's text as a string
>>> from pathlib import Path
>>> from gender_analysis.testing.common import TEST_DATA_DIR
>>>... | c38518d98fc05cb1bab0cc07888ae94ad937c534 | 630,476 |
def _to_extended_delta_code(seconds):
"""Return the deltaCode encoding for the ExtendedZoneProcessor which is
roughtly: deltaCode = (deltaSeconds + 1h) / 15m. With 4-bits, this will
handle deltaOffsets from -1:00 to +2:45.
"""
return f"({seconds // 900} + 4)" | e24189c73900cceaa125f6f471633362ec82e27c | 630,479 |
def fmtticks(fmt, fmt0, ticks, tickscle, tickscle0):
"""Formats x and y axis tick labels for a seaborn plot
Parameters
----------
fmt : str
The formatting string to use for all tick labels
fmt0 : str
The formatting string to use for only the first tick label
ticks : numpy.ndarra... | 1b5df83ddf94aec1ea7fea4b696250047126ad46 | 630,484 |
import re
def regex_validator(regex):
""" Creates a callable which will validate text input against the
provided regex string.
Parameters
----------
regex : unicode
A regular expression string to use for matching.
Returns
-------
results : callable
A callable which ta... | 656749fea031a4ad67848180b10e1e25408de174 | 630,493 |
def unpack_uncertainty_parameter(u):
"""Unpack uncertainty parameter (integer or single character).
See:
https://www.minorplanetcenter.net/iau/info/MPOrbitFormat.html
Args:
u (str): Packed uncertainty parameter.
Returns:
int: Uncertainty parameter, or -1 if invalid.
s... | 17260dc1ee0b1bddde52431d61cf4b8ea8197816 | 630,495 |
def prefs_line_to_string(line):
""" Converts a prefs line to a string.
Prefs line is in the format tb(..);tc(..);..;..;.
tb(x, y) are "no preference" intervals (i.e., white) that last for
y 15-minute intervals (x has no meaning):
e.g., tb(0, 4) is an hour of white; tb(2, 8) is two hours.
... | 3497018ebf6306fdd23c8a12b9ad67a09811200c | 630,496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.