content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import re
def pgrg_splitter(pgrg_str: str) -> tuple:
"""
Break up a stored page range into its components.
>>> pgrg_splitter("1-5")
('1', '5')
"""
retVal = (None, None)
# pgParts = pgrg_str.split("-")
# pgParts = re.split("[-–—]") # split for dash or ndash
pgParts = [n.st... | ee09b239a3c9d62d8a9d8876ae9220ca781b4464 | 462,453 |
def get_data(input_string):
"""
>>> get_data("hi=mom")
('hi', 'mom')
>>> get_data("hi=mom # with a comment.")
('hi', 'mom')
>>> get_data("# nothing here.")
('', '')
"""
input_string= input_string.strip()
input_string, _, _ = input_string.partition("#")
input_string= input_str... | a6f631a9beda62bac4be513736febdf5a651f9f5 | 465,524 |
def _map_mobility(
dementia: int,
falls: int,
visual_impairment: int,
visual_supervisation: int,
) -> bool:
"""Maps historic patient's mobility status to True or False."""
if dementia + falls + visual_impairment + visual_supervisation > 0:
return True
else:
return False | 11c506e12c6b4c6ffcaf44102c598e29862e59b0 | 220,704 |
def strToBool(val):
"""
Helper function to turn a string representation of "true" into
boolean True.
"""
if isinstance(val, str):
val = val.lower()
return val in ['true', 'on', 'yes', True] | 545754dc7f599bed7a0e75f0d9122bc15b358298 | 501,120 |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Given a url, returns a BeautifulSoup object of that page's html"""
web_page = requests.get(url)
return BeautifulSoup(web_page.text, "html.parser") | eedabb426d409f63f0eaf71105f1f329ad7ee1e5 | 671,956 |
from datetime import datetime
def add_date_to_filename(filename):
"""
Add current date to a filename.
Args:
filename (str)
Returns:
new_filename (str):
filename with added date.
"""
now = datetime.now()
# dd/mm/YY H:M:S
dt_string = now.strftime("%d-%m-%Y_%H... | 230af86ef7d3d5b8d13d42363c7222f7998bed58 | 561,174 |
import torch
def load_model(model, filename, optimizer=None, learning_scheduler=None):
"""
Load the given torch model from the given file. Loads the model by reference, so the passed in model is modified.
An optimizer and learning_scheduler object can also be loaded if they were saved along with the model... | d1fb4c908de2edd4def7a7f207846116b7a98b81 | 549,484 |
def bootstrap_context(value, max_value):
"""
Returns a Bootstrap contextual string based on the closeness to the max_value
Args:
value (int): Current value
max_value (int): The maximum possible, used to determine a percentage
Returns:
(str): One of the following Bootstrap conte... | 451c715143a6321f29e5330b4c4e871a47548813 | 130,809 |
import logging
def get_batch_size(num_replicas, num_samples, steps):
"""Calculate and return batch size for numpy inputs.
Args:
num_replicas: Number of devices over which the model input is distributed.
num_samples: Total number of input samples in the input numpy arrays.
steps: Number of steps that ... | 81d555130feb2fa81eb019a2525dc84d60a905d2 | 261,057 |
def get_number_docs(index_name, es):
""" Return the number of indexed documents in ElasticSearch
:param index_name: ElasticSearch index file
:param es: ElasticSearch object
:return: int
"""
res = es.count(index=index_name)
return res['count'] | 6fb43003d33a1177e1b1ed8da26513db1124a3d3 | 586,668 |
def strip_string(value):
"""Remove all blank spaces from the ends of a given value."""
return value.strip() | 0f66367ffc2c651488875ace33e6a44b453c3262 | 670,700 |
def trap_eq_factory(x_n, dt, f):
"""Factory function to return a function for evaluating the
trapezoidal integration function. This returns a function of
x_(n+1) (x at the next time step) for the given current x (x_n),
time step (dt), and function (f).
:param x_n: one-dimensional numpy array giving... | ea597986cb19252e625cf0aaae5065a6ff3f43d0 | 554,013 |
def jobs_to_delete(expected_jobs, actual_jobs):
"""
Decides on jobs that need to be deleted.
Compares lists of (service, instance) expected jobs to a list of (service, instance, tag) actual jobs
and decides which should be removed. The tag in the actual jobs is ignored, that is to say only the
(serv... | 68c589e019045afe48952ebd23a491ee659f5e7b | 255,562 |
def get_conn_str(db_name):
"""Returns the connection string for the passed in database."""
return f'postgresql://postgres:postgres123@localhost:5432/{db_name}' | 0197fada49a60f22bc716e65692db4c96f91a0af | 636,403 |
import struct
def parse_ipv4(address):
"""
Given a raw IPv4 address (i.e. as an unsigned integer), return it in
dotted quad notation.
"""
raw = struct.pack('I', address)
octets = struct.unpack('BBBB', raw)[::-1]
ipv4 = b'.'.join([('%d' % o).encode('ascii') for o in bytearray(octets)])
... | 80fe6335b91cf4323e01ca18a370e86d65b91f45 | 442,325 |
import json
def pj(jdb):
"""Dumps pretty JSON"""
return json.dumps(jdb,sort_keys=True,indent=4) | 7235ef14a5a55cee58a5cde72bc65b4b56c66755 | 663,958 |
def calcular_iva_propina_total_factura(costo_factura: int) -> str:
""" IVA y propina
Parámetros:
costo_factura (int): Costo de la factura del restaurante, sin impuestos ni propina
Retorno:
str: Cadena con el iva, propina y total de la factura, separados por coma
"""
iva = costo_factura *... | d0946472e5c43551e607a3413fe3cbe5cf888368 | 471,175 |
def _compute_win_probability_from_elo(rating_1, rating_2):
"""Computes the win probability of 1 vs 2 based on the provided Elo ratings.
Args:
rating_1: The Elo rating of player 1.
rating_2: The Elo rating of player 2.
Returns:
The win probability of player 1, when playing against 2.
"""
m = max(... | 150a0593152439e1cb5ed57cd7718c79ffe7cf20 | 570,687 |
def bytes_to_index(lead, tail):
""" Map a pair of ShiftJIS bytes to the WHATWG index.
"""
lead_offset = 0x81 if lead < 0xA0 else 0xC1
tail_offset = 0x40 if tail < 0x7F else 0x41
return (lead - lead_offset) * 188 + tail - tail_offset | edf98e19d9283b2deaf442e29d50469ea6bc0954 | 80,623 |
import re
def redundant(search):
"""returns true if search consists of just an eventtype (e.g. 'eventtype=foo' or 'eventtype="foo bar")"""
return re.match('^eventtype=(?:"[^"]*")|(?:[^"][^ ]*)$', search) != None | ca5762651fd9111304c8ecc8de33fed05b3127ce | 546,341 |
def filter_attached_for_up(items, service_names, attach_dependencies=False,
item_to_service_name=lambda x: x):
"""This function contains the logic of choosing which services to
attach when doing docker-compose up. It may be used both with containers
and services, and any other ent... | d25374831d0455d93e294ee366f98b44b2d89d0d | 330,647 |
def check_for_chr(sam):
""" Check sam file to see if 'chr' needs to be prepended to chromosome """
if 'chr' in sam.references[0]:
return True
return False | 22297aa592faab69d4f7293975738e51fdbacc24 | 599,037 |
def verify_input(user_input, correct_input):
"""Returns True if the user_input is inside correct_input (list) False in other way."""
if user_input in correct_input:
return True
else:
return False | 4a3905dddfdebcc8b8d242c0e9033ce135668cd6 | 340,219 |
def build_slice_path( data_root, data_suffix, experiment_name, variable_name, time_index, xy_slice_index, index_precision=3 ):
"""
Returns the on-disk path to a specific slice. The path generated has the following
form:
<root>/<variable>/<experiment>-<variable>-z=<slice>-Nt=<time><suffix>
<sli... | 68a6f29693f244a6e3ba8a9cd88bd3c14fa75e4d | 219,828 |
def _module_descriptor_file(module_dir):
"""Returns the name of the file containing descriptor for the 'module_dir'."""
return "{}.descriptor.txt".format(module_dir) | aa29da3e708e63376604c71bf40189b2256e46bb | 287,739 |
def beta_pruning_actions(state):
""" Return actions available given a state, we're essentially creating
a binary tree, where each parent has two nodes to choose from
:param state: The current state
:return: The available actions given the current state
"""
match state:
case "a":
... | e9865c0e1ade4d124bb27d491977e570e6df76ed | 59,638 |
import math
def get_utm_zone(x, y):
"""Get EPSG code for utm zone containing x/y lng/lat coordinates."""
utm_code = (math.floor((x + 180)/6) % 60) + 1
lat_code = 6 if y > 0 else 7
epsg_code = int('32%d%02d' % (lat_code, utm_code))
return epsg_code | 7ff1ac5c15376ee2b154be5a2612709c0f802427 | 515,689 |
import unicodedata
def normalize_nfkc(text):
"""Applies NFKC normalization e.g. ™ to TM, ..."""
return unicodedata.normalize("NFKC", text) | 5a717be987aaf01320fde844b8f4091459987f15 | 140,157 |
from pathlib import Path
def _lines_to_set(path):
"""
Converts lines from the file in the specified path to set of strings
which are lines in the file. Returns empty set when file doesn't exist.
"""
out = set()
if Path(path).is_file():
with open(path) as f:
out = set(f.read... | 2f2827bf3ff5c5aff044aacbc5ea1e466403ab94 | 584,100 |
def frontiers_from_bar_to_time(seq, bars):
"""
Converts the frontiers (or a sequence of integers) from bar indexes to absolute times of the bars.
The frontier is considered as the end of the bar.
Parameters
----------
seq : list of integers
The frontiers, in bar indexes.
bars : list... | ea86d14725a6761ba90ba4b62b7f78d687e6a269 | 48,145 |
def pythonize(string):
"""Transforms 'SillyCamelCase' to 'silly_camel_case'"""
normed = string[0].lower()
for char in string[1:]:
if char.isupper():
normed += '_'
normed += char.lower()
return normed | ee9564e71aee8adedf884c0d0f49f388c7c87f18 | 357,518 |
def query(df, query):
"""
Filter a dataset under a condition
---
### Parameters
*mandatory :*
- query (*str*): your query as a string (see [pandas doc](
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html#pandas.DataFrame.query))
---
### Example
... | 7fb2db6f9a8be3993f8a968892260ad0dd725b55 | 523,694 |
from typing import Counter
def most_common_elems(lst):
"""Returns the most common elements from a list.
>>> most_common_elems([2, 2, 1])
[2]
>>> sorted(most_common_elems([2, 1]))
[1, 2]
>>> sorted(most_common_elems([3, 2, 1, 3, 2, 4, 5, 7, 3, 1, 1]))
[1, 3]
"""
c = Counter()
fo... | 9b98a27344626d9db1dc13ca001464c5400c986b | 450,276 |
import re
def strip_quotes(s: str) -> str:
"""Strip a double quote at the beginning and end of the string, if any."""
s = re.sub('^"', '', s)
s = re.sub('"$', '', s)
return s | d8ff112648fd071ad80bd1303ae1c6123b50468b | 187,510 |
def popis_pozici(pozice):
"""Popíše pozici pro lidi
např:
>>> popis_pozici(0, 0)
'a1'
"""
radek, sloupec = pozice
return "abcdefgh"[sloupec] + "12345678"[radek] | efb2df8715b30c04bfdeb82684084f2037ad5e7e | 671,470 |
import random
def split_train_test(all_instances, n=None):
"""
Randomly split `n` instances of the dataset into train and test sets.
:param all_instances: a list of instances (e.g. documents) that will be split.
:param n: the number of instances to consider (in case we want to use only a
subs... | 68d2d94fcc4d5241e053556fcb4c2e50edfd2396 | 137,646 |
def compress(v, slen):
"""
Take as input a list of integers v and a bytelength slen, and
return a bytestring of length slen that encode/compress v.
If this is not possible, return False.
For each coefficient of v:
- the sign is encoded on 1 bit
- the 7 lower bits are encoded naively (binary... | ce45538933efa74e2673d713eae14a9b47e5c020 | 67,274 |
def format_path_data(path_data):
"""
Args:
path_data (list or str): Either a list of paths, or just one path.
Returns:
list: A list of paths
"""
assert isinstance(path_data, str) or isinstance(path_data, list)
if isinstance(path_data, str):
path_data = [path_data]
re... | 5e281848d7424f0957f09eda7b9e75314f4f645c | 249,616 |
def avg_words_per_sent(sent_count, word_count):
"""return the average number of words per sentence"""
result = word_count/sent_count
return result | 04dc6ccf4fde0c61c336f21d166cc370b7c088df | 466,934 |
def get_key_val_of_max_key(dict_obj):
"""Returns the key-value pair with the largest key in the given dict.
Example:
--------
>>> dict_obj = {5: 'g', 3: 'z'}
>>> print(get_key_val_of_max_key(dict_obj))
(5, 'g')
"""
return max(dict_obj.items(), key=lambda item: item[0]) | d8d6a6836f0c8c0e8e914dd4cdd97f9bf703c5e4 | 605,233 |
def _encode_bool(name, value, dummy0, dummy1):
"""Encode a python boolean (True/False)."""
return b"\x08" + name + (value and b"\x01" or b"\x00") | 5c6612ed9919286c0cab29b023b69f7872d40ed8 | 394,762 |
def get_ip_port(socket_str):
"""
Returns ip and port
:param socket_str: ipv4/6:port
:return:
address, port
"""
splitter_index = socket_str.rindex(':')
address = socket_str[0:splitter_index]
port = socket_str[splitter_index + 1:]
return address, port | 5a641bc83f81389d6a7ce30610a62476870d3bea | 417,230 |
import re
def barcode_is_10xgenomics(s):
"""
Check if sample sheet barcode is 10xGenomics sample set ID
10xGenomics sample set IDs of the form e.g. 'SI-P03-C9' or
'SI-GA-B3' are also considered to be valid.
Arguments:
s (str): barcode sequence to validate
Returns:
Boolean: True ... | 4e94ba4606c0a78afda876644d472aecc645aa2e | 166,726 |
def Residuals(xs, ys, inter, slope):
"""Computes residuals for a linear fit with parameters inter and slope.
Args:
xs: independent variable
ys: dependent variable
inter: float intercept
slope: float slope
Returns:
list of residuals
"""
res = [y - inter - slo... | cce5519c6adddf95b29712d51c698aeb1d531fa4 | 200,091 |
def set_compare(a, b):
"""
Compare two iterables a and b. set() is used for comparison, so only
unique elements will be considered.
Parameters
----------
a : iterable
b : iterable
Returns
-------
tuple with 3 elements:
(what is only in a (not in b),
what is onl... | db8e3674198c411355486062cde0258dbaecc5fb | 164,394 |
def outName(finpName):
"""Returns output filename by input filename"""
i = finpName.rfind('.')
if i != -1:
finpName = finpName[0:i]
return finpName + '.hig' | b23092a5356bd6f37ac76bab5af422feb446a3f3 | 654,353 |
def bounds(a):
"""Return a list of slices corresponding to the array bounds."""
return tuple([slice(0,a.shape[i]) for i in range(a.ndim)]) | fa9c7c8ed51d5c10ecd4392a72c6efe379a9407b | 696,738 |
import hashlib
def sha256(code, input):
"""sha256 <string> -- Create a sha256 hash of the input string"""
return code.say(hashlib.sha256(input.group(2)).hexdigest()) | 58935c8513a158725ed8e2f42be4c7fdda16c390 | 124,193 |
def legendre_polynomial(x: float, n: int) -> float:
"""Evaluate n-order Legendre polynomial.
Args:
x: Abscissa to evaluate.
n: Polynomial order.
Returns:
Value of polynomial.
"""
if n == 0:
return 1
elif n == 1:
return x
else:
polynomials = [... | 9c1890f54ae0a91b8d4cd8771f7a944fd3f7e7ab | 638,006 |
def compute_adaptive_order(freq, order_min, order_max):
"""
Computes the superlet order for a given frequency of interest
for the fractional adaptive SLT (FASLT) according to
equation 7 of Moca et al. 2021.
This is a simple linear mapping between the minimal
and maximal order onto the re... | 4ffd3dbff4d62437a479b527a0363afb27c3556b | 364,996 |
def check_param(var, datatype):
"""Checks if a variable is the correct data type.
If it's not correct, return the error message to raise.
Parameters
-----------
var
the variable to check.
datatype
the data type to compare against.
Returns
----------
str
t... | 51c8ed53e516b3f6b53c2f584ca94f82ed2dd60d | 596,530 |
def split_into_characters(s: str) -> list[str]:
"""
>>> split_into_characters("PyCon")
['P', 'y', 'C', 'o', 'n']
"""
return [character for character in s] | db6a8f5235dec5b9995b682c1c03472fac67ac6a | 530,435 |
def pre_post_delete_callback(req, form, storable):
"""
Called before or after an item is deleted.
The return value from a postdelete callback has no effect.
"""
return True | 536fc7adee4aac56c32983b60b283e6340d9bee9 | 444,822 |
def partition(word: str, partitions: int) -> int:
"""
Find a bucket for a given word.
:param word:
:param partitions:
:return:
"""
a = ord('a')
z = ord('z')
value = ord(word[0].lower())
if partitions > 1 and a <= value <= z:
pos = value - a
return int(pos * (part... | ddf981ca7cdd5ad3bd45f524c706c5901bfeb892 | 77,084 |
def getRowUnit(sudoku, i):
"""
Finds a cell's peers in the row that it is in.
Peers are the other numbers in the puzzle.
Input
sudoku : 9x9 numpy array of integers.
i: row index of cell in the puzzle.
Output
temp_row : numpy list of the cell's peers in the specified row.
... | 8b129d54cfea218401a508329278287a537a9436 | 506,110 |
def rosenbrock(x, y):
"""Rosenbrock function, minimum at (1,1) with value of 0"""
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 | dea89459bda6cae4b7b2e44f4cfd6f9d135cb46a | 537,820 |
def get_roi(countours, img_height, img_width):
"""
Computes bounding box which must contain all the passed contours
Arguments:
contours -- numpy array of shape [num_points, 1, 2]
img_height -- int, image height
img_width -- int, image width
Returns:
4 numbers representing x and y ... | a849ee8e21c1b951b112f7f93db4389ce9a1dc45 | 440,209 |
from email.mime.text import MIMEText
import uuid
def new_message(from_email, to_email):
"""Creates an email (headers & body) with a random subject"""
msg = MIMEText('Testing')
msg['Subject'] = uuid.uuid4().hex[:8]
msg['From'] = from_email
msg['To'] = to_email
return msg.as_string(), msg['subje... | 4895121a4193df9c07dfaf4dc4e48c4c8909360d | 251,414 |
import base64
def base64_encode(string):
"""
Encodes data with MIME base64
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
"""
return base64.b64encode(string) | d1632c2952fc470a322926aae6a32a6cbe3cc930 | 613,735 |
def select_columns_by_type(df, dtypes):
"""Return the list of columns which are of object or datetime type
Parameters
----------
df: pandas.DataFrame
Returns
-------
List[str]
"""
return [
column_name
for column_name, column_type in df.dtypes.to_dict().items... | 23ae845c52df0d4ff26b5c691ff8298f6187772e | 490,030 |
import importlib
def is_openeye_installed(oetools=('oechem', 'oequacpac', 'oeiupac', 'oeomega')):
"""
Check if a given OpenEye tool is installed and Licensed.
If the OpenEye toolkit is not installed, returns False.
Parameters
----------
oetools : str or iterable of strings, Optional, Default... | 0e434bef7bf9eaad11bb03993bf46b30875633cf | 419,181 |
def recvall(sock, size: int):
"""Receive data of a specific size from socket.
If 'size' number of bytes are not received, None is returned.
"""
buf = b""
while size:
newbuf = sock.recv(size)
if not newbuf:
return None
buf += newbuf
size -= len(newbuf)
... | 6a0f6814cdaf6847d467f4c5620c3897b1ff2ac8 | 35,183 |
def _check_for_too_many_exclusions(exclude_instances, available_instances,
delta, groups_members):
"""
Check whether the amount of exluded instances will make it possible to
scale down by the given delta.
:param exclude_instances: A list of node instance I... | dca3588e02c8eaf60c6511dfedb3a3b281d64992 | 609,614 |
def is_word(s):
""" String `s` counts as a word if it has at least one letter. """
for c in s:
if c.isalpha(): return True
return False | 524ed5cc506769bd8634a46d346617344485e5f7 | 706,470 |
def unstream(data, version_tag, bits_per_value, int_size):
"""
This function is a pythonic adaptation of Reddit user bxny5's unstream
function for decoding minecraft chunkheightmap data, written in perl.
https://www.reddit.com/r/Minecraft/comments/bxny75/fun_with_chunk_data_heightmap_edition/
""" ... | 59e69159315a7ee0c7384be7f198f6906d1daa8d | 153,502 |
def get_client_region(client):
"""Gets the region from a :class:`boto3.client.Client` object.
Args:
client (:class:`boto3.client.Client`): The client to get the region
from.
Returns:
string: AWS region string.
"""
return client._client_config.region_name | 6727f8e21fee77a2d869c1c4f3aa077a22145f1d | 67,098 |
def all_equal(values: list):
"""Check that all values in given list are equal"""
return all(values[0] == v for v in values) | 8ed08f63959367f3327554adc11b1286291963d8 | 708,786 |
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim):
"""
Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate,
given both the observed interleaved and standard decay parameters.
:param irb_decay: Observed decay parameter in irb experiment with desired gate interle... | 09f5b504ffffb047dc903a19bd51753c46cca7c2 | 675,239 |
def expected_errors(snippets):
"""Get and normalize expected errors from snippet."""
out = snippets.pop(0)
assert out.startswith("[GraphQLError(")
return " ".join(out.split()).replace("( ", "(").replace('" "', "") | 57ff4693779ef221daf400d0b2fef68bfbd4d581 | 635,424 |
def float_to_str(value: float) -> str:
"""Converts double number to string using {.12g} formatter."""
return format(value, ".12g") | 404855c3c17ff19c3ef6275f0d5584b6e8f73350 | 228,721 |
def rotate_patches_90deg(patches):
"""
Rotate patch dictionary as if original image is rotated by 90-degree
CCW.
"""
def rot_pos(i, j):
"""
Board Coordinates:
i
9 ... 1
------ 1 j
| | ...
------ 9
"""
return (10 - ... | f488cb151b869d740c47464816329e730a12f3f0 | 668,965 |
from pathlib import Path
def default_sftp_path(this_path, default_path):
"""
If ``this_path`` exists, return it as a path, else, return
the ``pathlib.Path.name`` of the default path
"""
return Path(this_path) if this_path else Path(Path(default_path).name) | 4b63a77a318593c80f830e810d516ca3aa2fcc75 | 380,687 |
import re
def _is_abbreviation_for(abbreviated, full):
"""
>>> _is_abbreviation_for('yr', 'years')
True
>>> _is_abbreviation_for('years', 'years')
True
>>> _is_abbreviation_for('szco', 'years')
False
Thanks to Michael Brennan
http://stackoverflow.com/questions/7331462/check-if-a-s... | 05e90d501c93e17cd56fa33df73d4b64149da8ec | 199,095 |
def get_strict_smarts_for_atom(atom):
"""
For an RDkit atom object, generate a simple SMARTS pattern.
Parameters
----------
atom: rdkit.Chem.Atom
RDKit atom.
Results
-------
symbol: str
SMARTS symbol of the atom.
"""
symbol = atom.GetSmarts()
if "[" not in ... | 7f6d8f79056f9dd08b99369f02f7d795fbd5866f | 194,376 |
def get_type(transaction):
"""
:return: the type of the transaction
"""
return transaction['type'] | 4f66830f7c1e3bdc5d6b2c4ccc5db493014b9e5f | 697,943 |
def _convert_space_to_shape_index(space):
"""Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing).
Parameters
----------
space : str, values=('feature', 'sample')
Feature or sample space.
Returns
-------
return : int, values=(0, 1)
Index location of th... | 20ec5aad29366929973b2bfa8e503a5bcbbb9a3a | 638,398 |
def compss_wait_on(obj):
"""
Dummy compss_wait_on
:param obj: The object to wait on.
:return: The same object defined as parameter
"""
return obj | cb433878c460a507d98c1c3a8880626f804b201f | 28,565 |
def snake_to_title_case(text):
"""Converts column_title to "Column Title"
"""
return ' '.join(map(lambda x: x.capitalize(), text.split('_'))) | fa9accb2650d0ad20bc235e28db16debd625f565 | 177,646 |
def formatMultiplier(stat : float) -> str:
"""Format a module effect attribute into a string, including a sign symbol and percentage symbol.
:param stat: The statistic to format into a string
:type stat: float
:return: A sign symbol, followed by stat, followed by a percentage sign.
"""
return f... | 5ab9df157d54a5414fc9cba46d0f73512a8a6c4c | 43,002 |
def get_datatype(value):
""" Determine most appropriate SQLite datatype for storing value.
SQLite has only four underlying storage classes: integer, real,
text, and blob.
For compatibility with other flavors of SQL, it's possible to
define columns with more specific datatypes (e.g.... | d70c935e463b6ba9e92422a33e1cfcc9fcf7cb1f | 508,765 |
def __get_topic_info(model, count_vectorizer, n_top_words):
"""
A utility method that generates the detailed topic information
:param model: LDA model trained int topic_modeller method
:param count_vectorizer: vectorizer object to get statistical results
:param n_top_words: num of words for each top... | 024ba487efdca6510074a01bb2154890aaed96f7 | 294,713 |
def convert_field_format(fieldAsArray):
"""
Description:
converts the polygon given as nested arrays
to nested tuples.
Parameters:
fieldAsArray: [ [ [x, y], ... ], ... ]
Return:
( ( (x, y), ... ), ... )
"""
return tuple( tuple( tuple(vertex) for vertex in ring) fo... | 6cc2e47435dcc9581ed60d45f9c5786d0010886c | 484,566 |
def consecutive(span):
"""
Check if a span of indices is consecutive
:param span: the span of indices
:return: whether the span of indices is consecutive
"""
return [i - span[0] for i in span] == range(span[-1] - span[0] + 1) | 6d80f0184e09d9b374ded8707a0198ebd7431599 | 453,762 |
def set_defaults(hotpotato):
"""
Set default values for keys in a dictionary of input parameters.
Parameters
----------
hotpotato : dictionary
Dictionary of input parameters gathered from a configuration script
Returns
-------
hotpotato : dictionary
Input dictionary wi... | 9ce2583b3873b0c9102461eec21dc43682928508 | 458,016 |
def standardize_severity_string(severity):
"""
Returns the severity string in a consistent way.
Parameters
----------
severity : str
The severity string to standardize.
Returns
-------
severity : str
The standardized severity string.
"""
return severity.title() | a52e3f0b299d25d56425f2c5cdd69bb43825e8c3 | 606,176 |
def parent(index: int) -> int:
"""Gets parent's index.
"""
return index // 2 | fd00111ac33ff77f28f30d2f5f0bcf375206f705 | 110,153 |
def split_rows(sentences, column_names):
"""
Creates a list of sentence where each sentence is a list of lines
Each line is a dictionary of columns
:param sentences:
:param column_names:
:return:
"""
new_sentences = []
root_values = ['0', 'ROOT', 'ROOT', 'ROOT', 'ROOT', 'ROOT', '0', ... | 444733a9c169bedae8dc0045cd696cafed7085e2 | 709,383 |
import torch
def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z):
"""
Computes utility values for linear interpolation at points v.
The points are given as normalized offsets in the source interval
(v0_src, v0_src + size_src), more precisely:
v = v0_src + v_... | 7e664fec2d3198c8124131541f2d07658a9f1f83 | 672,935 |
def MakePartition(block_dev, part):
"""Helper function to build Linux device path for storage partition."""
return '%s%s%s' % (block_dev, 'p' if block_dev[-1].isdigit() else '', part) | 3e21c773a69b7c49bb4aad4210b9d168099565ef | 35,041 |
def fixture_sample_id() -> str:
"""Return a sample id"""
return "sample" | 781a9824ad1faffdbda867c2f8df3b335c285fbc | 252,329 |
from typing import Dict
from typing import List
from typing import OrderedDict
def order_dict(value: Dict, ordering: List, ignore_missing=False) -> OrderedDict:
"""
Convert a dict to an OrderedDict with key order provided by ``ordering``.
"""
new_value = OrderedDict()
for elem in ordering:
... | 150fdc9f954cc939966410199a95ecbef22f2a4c | 449,555 |
def acenx(n, asx=25., agx=5.):
"""n-th analyser center (starting from 0!) in x, given its size (asx)
and gap between two (agx) in mm
"""
return (asx + agx) * n | 6cc02676a9f0134fbc9deea93dcfe34b3113f358 | 140,654 |
def search_for_pod_info(details, operator_id):
"""
Get operator pod info, such as: name, status and message error (if failed).
Parameters
----------
details : dict
Workflow manifest from pipeline runtime.
operator_id : str
Returns
-------
dict
Pod informations.
... | 678b6bab7fbcab9223ceaa735f4e8b83d0d3676e | 522,758 |
def CollectSpecies(species_data):
"""
Returns the list of unique species label present in the input list.
this function is mostly used in the last test.py
"""
species_list= []
for item in range(len(species_data)):
species_label= species_data[item][0]
species_list.append(species... | 239cd3f102a9b5070ad4fd42470103e2ba5a5216 | 561,254 |
def _pyval_field_major_to_node_major(keys, values, depth):
"""Regroup each field (k, v) from dict-of-list to list-of-dict.
Given a "field-major" encoding of the StructuredTensor (which maps each key to
a single nested list containing the values for all structs), return a
corresponding "node-major" encoding, co... | b98d867d6b47fdbf494ed81b709a28440b0731c9 | 269,305 |
def solution(A, B): # O(N)
"""
Find common elements in 2 lists.
>>> solution([1, 2, 3, 7, 1, 5], [7, 3, 6])
[7, 3]
>>> solution([2, 4, 5, 10, 1, 2, 4, 4], [10, -1, 3])
[10]
>>> solution([4, 5, 2, 2, 1], [3, 6, -1])
[]
"""
elements ... | 309f83713e4162e8d8c48712c83e32b474279d01 | 541,144 |
import re
def get_perf_event(data, separator=" "):
"""
From data, Read the numbers provided by perf
:param data: The output to process
:param separator: In perf, it is usally number+<separator>+descriptor>
:return: A dict of all the values found by perf
"""
data = str(data)
resul... | a79adfcc8c26512fda30386ddd0f8e9183144a10 | 563,075 |
def create_mosaic_pars(mosaic_wcs):
"""Return dict of values to use with AstroDrizzle to specify output mosaic
Parameters
-----------
mosaic_wcs : object
WCS as generated by make_mosaic_wcs
Returns
--------
mosaic_pars : dict
This dictionary can be used as input to astrodri... | e9a8a499ce3a9196fcaf4f57c4bda4aa25905655 | 668,496 |
from datetime import datetime
def str_to_datetime(dt_str: str) -> datetime:
"""
Converts a datetime in string format to datetime format.
Parameters
----------
dt_str : str
Represents a datetime in string format, "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S"
Returns
-------
datetime
... | 75ab00a545d56abdf475bba0e405972f13c0a30e | 512,883 |
def reformat_large_tick_values(tick_val, pos):
"""
Turns large tick values (in the billions, millions and thousands) such as
4500 into 4.5K and also appropriately turns 4000 into 4K
(no zero after the decimal).
"""
if tick_val >= 1000000000:
val = round(tick_val/1000000000, 1)
ne... | 5d39e9406afc1c33aa364ff3cd353585ec609e61 | 604,223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.