content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_last_price_date(con, table, ticker_id):
"""
INPUTS:
con (mysql) - pymysql database connection
table (str) - Database table to query
ticker_id (int) - Ticker id number from symbols table
OUTPUT:
Last price date in ticker's time series. Iso8601 standard format
"""
... | 4b10f2303a329219ffa2cead203c8fc1183685e2 | 587,265 |
import base64
import hashlib
def get_unique_username_from_email(email):
"""
Uniquely generate our 'username' by taking the email and create a hash.
Source: https://github.com/dabapps/django-email-as-username/blob/master/emailusernames/utils.py
"""
email = email.lower() # Emails should be case-ins... | e02b277dff178189f9240e9a97a82ebed10f44b0 | 587,266 |
def maxlen(stringlist):
"""returns the length of the longest string in the string list"""
maxlen = 0
for x in stringlist:
if len(x) > maxlen:
maxlen = len(x)
return maxlen | fc36c99995425a8594f563bd8225017afa407951 | 587,272 |
def _get_encoded_list(items):
"""Return Python list encoded in a string"""
return '[' + ', '.join(['\'%s\'' % (item) for item in items]) + ']' \
if items else '[]' | a6b563be446fe777837837016aa1f0eceb1faa9c | 587,276 |
def split_paragraphs(text, min_length=30):
"""Extract a list of paragraphs from text
Return a list of strings. Paragraphs are separated by double "new-line"
characters.
Any paragraph shorter than min_length is dropped.
Any whitespaces at the beginning or ending of paragraphs are trimmed.
"""
... | 330ccad27a7a4f515ae09501afc08bea5a43eae0 | 587,278 |
def _calc_ts_complexity(tss, pers):
""" Calculates the complexity of a TS schema
Complexity = (Number of Schemas + Number of Permutable Symbols + Lenght of each Permutable Symbol)
"""
return len(tss) + sum([len(per) for ts, per in zip(tss, pers)]) | e6c9b21204b7c779badefb22822959cf8e3d9d6c | 587,281 |
from typing import List
from typing import Tuple
from typing import Set
def get_inf_req(triple_list: List[tuple]) -> Tuple[Set[tuple], Set[tuple]]:
"""Save request type and inform type results respectively according to slot type.
Args:
triple_list: preds or ground truth (domain, slot, value)
Ret... | 0a90bcaa1f7e424e4cffa9e0fd3e44be8d14e19b | 587,284 |
def convert_bits_to_bytes(bit_value):
""" Convert input bits to bytes """
return bit_value / 8 | 6c9662309e0a9599944b115e0044552348e10e25 | 587,286 |
import textwrap
def WrapText(Text, Delimiter, Width):
"""Wrap text using specified delimiter and width.
Arguments:
Text (string): Input text
Delimiter (string): Delimiter for wrapping text
Width (int): Max number of characters before wrapping text
Returns:
str : Wrapp... | fbed62d15c23dc12b58b300bfcd20fbdc12f20f6 | 587,287 |
def check_valid_sequence(sequence: str) -> bool:
"""
Check that the sequence string only contains valid sequence characters
"""
return set(sequence.upper()).issubset(set("WSKMYRVHDBNZNATCGU-")) | 60d5d78d1e94e8dbe3d6976bfc2a139eac739b83 | 587,291 |
def dot2(bits):
"""Compute dot module 2."""
return (bits[0] * bits[2] + bits[1] * bits[3]) % 2 | 3bd6d785db85df25ca4d536bc85a73ac543b146a | 587,292 |
import base64
import json
def decode_base64(data):
"""
decodes from base64.
:param string data:
:return: dict object.
"""
to_bytes = base64.b64decode(data)
return json.loads(to_bytes) | 5b68fecf6cf8675b6a19ba9b3375229029d951f8 | 587,293 |
from typing import Any
def static_vars(obj: Any):
"""
Like :func:`vars`, but bypasses overridden ``__getattribute__`` methods.
:param obj: Any object
:return: The object's ``__dict__``
:raises TypeError: If the object has no ``__dict__``
"""
try:
return object.__getattribute__(obj... | f8e56d59767246f22d3d0b21624387ed12ca355c | 587,300 |
import torch
def _accuracy_within_margin(score_predictions, score_target, margin, device):
""" Returns the percentage of predicted scores that are within the provided margin from the target score. """
return torch.sum(
torch.where(
torch.abs(score_predictions - score_target) <= margin,
... | 05dc890a080b56cf77aa2b01d6eb8b07a1821a05 | 587,302 |
def string_is_true(value):
"""Check to see if a string has a value that should be treated as True."""
return value and value != 'false' and value != 'False' and value != '0' | 43ee1a50f63b10d918a8c37ccff7130a7739ced4 | 587,303 |
def get_cooling_duty(heat_utilities, filter_savings=True):
"""Return the total cooling duty of all heat utilities in GJ/hr."""
return - sum([i.duty for i in heat_utilities if i.flow * i.duty < 0]) / 1e6 | 0ce59baebd02585b612ab72d963756be89c3464d | 587,304 |
def get_pub_type(poa_article):
"""
Given an article object, determine whether the pub_type is for
PoA article or VoR article
"""
pub_type = None
if poa_article.is_poa is True:
# PoA
pub_type = "aheadofprint"
else:
# VoR
pub_type = "epublish"
return pub_typ... | bbbb2394c823dca9085abedac6eaa1f86478b77d | 587,309 |
import torch
def build_align_pharaoh(valid_alignment):
"""Convert valid alignment matrix to i-j (from 0) Pharaoh format pairs,
or empty list if it's None.
"""
align_pairs = []
if isinstance(valid_alignment, torch.Tensor):
tgt_align_src_id = valid_alignment.argmax(dim=-1)
for tgt_i... | 91436674acf033bc39c0404a75e767d90d0d04f6 | 587,314 |
def shuffle_rows(df):
"""
Shuffle the rows of a dataframe
see https://stackoverflow.com/questions/29576430/shuffle-dataframe-rows
"""
return df.sample(frac=1).reset_index(drop=True) | a96021d59dfb72a9cb178caea255ec6bdfc6ac23 | 587,316 |
from typing import Union
def change_message_from_percent(percent_change: Union[str, int, float]) -> str:
"""Creates a change message from given percentage change.
percent_change will be:
- "–" in case the last data point was missing or both the points had values 0
- 0 (int) in case there was ... | b4b9f5144f213bc3cfa5464f2e68d65ea9af3f8b | 587,317 |
def load_smi(smi_file,index=None):
"""
loads list of smiles from a text file. Will return the i-th smiles in file if index is provided, where index
starts at zero.
Parameters
----------
smi_file : str
file name containing strings
index : None or int, default None
index of sm... | 2ef894fb337864630c5ca778111985beac73abee | 587,319 |
import math
def Volume(diameter, factor=4*math.pi/3):
"""Converts a diameter to a volume.
V = 4/3 pi (d/2)^3
"""
return factor * (diameter/2.0)**3 | bb2d0f8f8ed74f629a78a7d31604bfe54a40167f | 587,324 |
import random
def shuffle(data):
"""
Shuffles the Array
"""
random.shuffle(data)
return data | d93854976f5167d8afd5b82e65541f5334fbc666 | 587,325 |
def get_index_of_smallest(lst: list, i: int) -> int:
""" Return the index <i> of the smallest item in lst[i:].
>>> get_index_of_smallest([2, 7, 3, 5], 1)
2
"""
# Index of the smallest item so far
index_of_smallest = i
len_lst = len(lst)
for j in range(i + 1, len_lst):
if lst[j... | 21025f38b84043aef0f691a8ff1593dc007f67fa | 587,327 |
def desc2fn(description: tuple) -> tuple:
"""Extract tuple of field names from psycopg2 cursor.description."""
return tuple(d.name for d in description) | bd178d3941ae5537ad6baca69e4fbe0afe8eafa0 | 587,330 |
from typing import Counter
def is_anagram_counter(s, t):
"""
Determine whether or not teo given strings are anagram by counter
:param s: source string
:type s: str
:param t: target string
:type t: str
:return: whether or not teo given strings are anagram
:rtype: bool
"""
retur... | 5bc70f11d0f39ce45dc31a4f942fb080f43ca474 | 587,334 |
def dates_to_strs(col):
"""
Converts all DataFrame Series of datetime types to strings.
"""
if str(col.dtype).startswith("date"):
return col.astype(str)
return col | fe1fdb2c452c1381fa9091da917eb75aeb8f83da | 587,335 |
def coco_label_reader(FILEPATH):
"""
parse a label map file and return a dictionary
label map has entries like this:
item {
name: ""
id: 0
display_name: ""
}
:param FILEPATH: path to the label map
:return: label dictionary
"""
mapping = {}
with open(FILEPA... | b4c0ea94492e40c4f3d2a9780732bb22c3478eac | 587,337 |
def calc_map_dims(x_size, y_size, mp_size, mp_dpi):
"""
Calculate output map size.
:param x_size: <int or float> Image x dimension
:param y_size: <int or float> Image y dimension
:param mp_size: <int> Percent of image space of which the map will occupy
:param mp_dpi: <int> Map density, as dots ... | 6ba3d1299097b3247c2527a321b1924e58f9ac85 | 587,339 |
import socket
def get_fqdn(ip_address):
"""
Function that transforms a given IP address into the associated FQDN name
for that host.
:param ip_address: IP address of the remote host.
:return: FQDN name for that host.
"""
return socket.gethostbyaddr(ip_address) | ad3c785aa2fc70c960b6e89acb6c9ad8f00f2a07 | 587,341 |
import torch
def classify_action_with_tsn_bni(input, settings, num_crops=None, n_samples=None, average_scores=True):
"""
Test routine for tsn bni, for a single action
:param input: Pytorch variable containing image values
:param settings: dictionary settings
:param num_crops: number of crops (sho... | 61c85ced53357a5e7c02f61ff6e18a173f95012e | 587,342 |
def _reshape_list_to_2d(list_to_reshape, shapes):
"""Reshape list of numpy.ndarray according to list of shapes.
Args:
list_to_reshape (list): List containing numpy.ndarray's.
shapes (list): List of 2-dimensional shape tuples.
Returns:
reshaped (list): List containing the reshaped n... | 8ad3fa8c1df3f2fa43c112ddb31097cdf6659595 | 587,343 |
def strip_query(url):
"""Remove query string from a url"""
return url.split('?', 1)[0] | 34fe61cde242aef09495d4bbc384d68d3961e103 | 587,345 |
def split_line(line, min_line_length=30, max_line_length=100):
"""
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
:param line: The line to split
:param min_line_length: The minimum desired line length
:param max_line_length: The maximum desire... | 09cb5385b2d433579ad825652ccbb27862271cf8 | 587,346 |
def Top1Criterion(x,y, model):
"""Returns True if model prediction is in top1"""
return model(x).topk(1)[1].view(-1)==y | 4c27295d26607f54d052628ee5d5389dba118eeb | 587,348 |
import collections
def get_ngram_counter(ids, n):
"""Get a Counter with the ngrams of the given ID list.
Args:
ids: np.array or a list corresponding to a single sentence
n: n-gram size
Returns:
collections.Counter with ID tuples as keys and 1s as values.
"""
ngram_list = [tuple(ids[i:i + n]) f... | e5c6cae1df58f87391ea135f3b6095ce4cb44a24 | 587,351 |
import random
import math
def define_e(phi_n: int) -> int:
"""Generates a number that is between 1 < e < phi_n and checks if it is coprime with phi_n
Args:
phi_n (int): A value generated using the original prime numbers that is "(p - 1) * (q - 1)"
Returns:
int: A value that satisfies the... | 18f9fcf2c7ed8a2f59d2be34b0449b61d0b639a9 | 587,352 |
def path2ScriptId(path):
"""Answers the scriptId, derived from the __file__ of the main source."""
return path.split('/src/')[-1] | 10ff18ccccd9808efcb18f2c27fb7d7951ca1e28 | 587,353 |
import json
def dejsonize(data):
"""
Returns JSON deserialized data
>>> dejsonize('{\\n "foo": "bar"\\n}')
{u'foo': u'bar'}
"""
return json.loads(data) | dc7bf3e44e936b1222752efed693889268d9d322 | 587,356 |
def have_module(name):
"""
Check whether a Python module named ``name`` can be imported.
This is done by trying to import that module and returning ``True``
if that import succeeded. So, as a side effect, the module is
actually imported if possible.
EXAMPLES::
sage: from sage_setup.ut... | d65d40a22f35e8eca305d0d8fc2004d902cc6662 | 587,358 |
def inside_angle_range(x, start, end, tol=0.0):
"""Assuming end is clockwise from start, is the angle x inside [start,end]
within some tolerance?
Parameters:
x (float): angle to test, in degrees
start (float): start angle of range, in degrees
end (float): end angle of range, in degr... | 9a0a273f55fd0afe6f4a83bf6c091657c766730e | 587,359 |
def _from_serialized_headers(headers):
"""
httpx accepts headers as list of tuples of header key and value.
"""
header_list = []
for key, values in headers.items():
for v in values:
header_list.append((key, v))
return header_list | 4481e0ee8b4f76254f36941ea729f32e8bb257ac | 587,360 |
def mergeDict(source, target):
"""Merges the source dictionary into the target one, keeping
values for duplicate keys from the target dictionary. Keys that
don't exist in 1 or the other are left untouched but are still
copied over to the resulting dictionary.
Args:
source (dict): The initial dictionary
target... | 65feddf6434d59944b5961a4a5f530f243afc8b0 | 587,364 |
import random
def random_walk(G, path_length, alpha=0, rand=random.Random(), start=None):
""" Returns a truncated random walk.
path_length: Length of the random walk.
alpha: probability of restarts.
start: the start node of the random walk.
"""
if start:
path = [start]
else:
path = [rand.choice(list(G.n... | b56e275dcbad67b95960018991175269a64680df | 587,368 |
import re
def json_path_filter(arg):
"""Parse a JSON filter argument."""
key, sep, value = arg.strip().partition('~')
if sep == '~':
return key, re.compile(value)
key, sep, value = arg.strip().rpartition('=')
return key, int(value) | 772fdbd1705d7d12c48cca90c508feb75c12d348 | 587,369 |
def first(iterator, default=None):
"""Return first member of an `iterator`
Example:
>>> def it():
... yield 1
... yield 2
... yield 3
...
>>> first(it())
1
"""
return next(iterator, default) | eda7e734388fbbd1df143c930fd04977389768dd | 587,371 |
import torch
def precision_k(labels, scores, k=5, average=False, largest=False):
"""
Computes the precision@k for the specified values of k
or average precision@k if attribute average is True
:param labels: pytorch.Tensor of shape (n,) containing labels of each value
:param scores: pytorch.Tensor ... | 7be3c0ed62e49d8dd5c1cb0751c99a83eb2f347e | 587,376 |
def convert_to_seconds(val, t):
"""
Convert a given unit of time to seconds
Args:
val (int): Value in number of years/days/minutes
t (str): Specifies the type of value. It can be one of the following
'y': Val denotes years
'd': Val denotes days
... | 4f25c5afb3ea920f02ee91cb24c7e70bfe595268 | 587,381 |
def is_latex_card(card):
"""Should the current card be formatted in latex?"""
return 'latex' in [tag.name for tag in card.tags] | 3d200aab3ea3faebab60ae69414f562c1cf04e8e | 587,382 |
import socket
def is_ip(s):
"""Returns whether or not a given string is an IPV4 address."""
try:
return bool(socket.inet_aton(s))
except socket.error:
return False | aa4d9f29afe68cea1efe3ab3100907e1b45b241d | 587,384 |
def _pretty_class(s):
"""
convert the internal class name representation into what users
expect to see. Currently that just means swapping '/' for '.'
"""
# well that's easy.
return str(s).replace("/", ".") | 4fc3292bce1ce2cf72688c6b580eed174c4ad5c4 | 587,385 |
def __is_reflection_coord(coord):
"""Reflection coordinates have a 2 followed by 0 or more trailing 1s."""
i = len(coord)-1
while coord[i] == 1:
i -= 1
return coord[i] == 2 | f9b26fcf469831b42d95f3979240bdf77e851c40 | 587,394 |
def chrom_sort(in_chroms):
"""
Sort a list of chromosomes in the order 1..22, X, Y, M.
:param list in_chroms: Input chromsomes
:return: Sorted chromosomes
:rtype: list[str]
"""
if not in_chroms:
return in_chroms
chr_prefix = False
if in_chroms[0].startswith('chr'):
i... | ee46b320efeef35b09889f045a6b9ca320428cb3 | 587,395 |
def convert_val_to_time(val):
"""Try to convert value to date & time in ISO-8601 format or None.
Format must include time zone information like '2014-11-06T19:00:02-0500'.
Supported types are:
- NoneType
- str.
"""
if val is None:
return None
elif isinstance(val, str):
... | 05f424a1e95fc2733a28342ecf2ec1f91df25fab | 587,396 |
import math
def textrank_sent_sim(s1, s2):
"""
Arguments
---------
s1, s2 : list of str
Tokenized sentences
Returns
-------
Sentence similarity : float
Non-negative number
"""
n1 = len(s1)
n2 = len(s2)
if (n1 <= 1) or (n2 <= 1):
return 0
common ... | 2fda78adea9faa31e24b3b69593cbe01a0398cc2 | 587,397 |
def drop_table_clause(table_name):
""" Create a drop table if exists clause string for SQL.
Args:
table_name: The table to be dropped.
Returns:
A string with the crafted clause.
"""
return 'DROP TABLE IF EXISTS {}'.format(table_name) | f27e5d6c8af52600af79b883fa057f8625677578 | 587,398 |
def _extract_stack_info(stack):
"""
Given a stack, save the static info for each frame (basically
everything except for the reference to the frame).
"""
stack_info = []
for frame in stack: stack_info.append(frame[1:])
return stack_info | 1219c56f214ef9633504b0eebae4604f4b1f40bc | 587,403 |
def _b_min_ ( bp ) :
"""Get min values for bernstein polynomials
>>> p = ...
>>> mn = p.min()
The value is such that: mn <= p(x) for all x_min<=x<x_max
"""
b = bp.bernstein()
pars = b .pars()
return min ( pars ) | fdcd68ddb557ff3ee30afe392141e3134b6342d0 | 587,408 |
def strict_neg(a):
"""Strict negation
Arguments:
- `a`: a boolean
"""
return not a | 118ad89facb8e19b8fe19885fbe55638d9bd80ea | 587,409 |
def str_to_span(string):
""" Return the equivalent interval time in seconds.
Parameters
----------
string : str
Time periodicity
Returns
-------
span : int
Number of seconds in time interval.
Examples
--------
>>> str_to_span('minutely')
60
"""
if ... | a8de2f1825318356408624339f1b528a6ebf6b4f | 587,415 |
def get_index_of_most_important_sentences(weighted_sums, num_vectors):
""" Finds and returns the index of the two sentences with the highest weighted sum """
largest_sum_index, second_largest_sum_index = 0, 0
largest_sum, second_largest_sum = 0, 0
for i in range(num_vectors):
current_sum = weigh... | f9f6b5583075275c236ff6be104d0e37bf947d78 | 587,416 |
from typing import List
def _bucket(number: float, bucket_boundaries: List[float]) -> int:
"""Returns an int representing a bucket for the number."""
for index, (left, right) in enumerate(zip(bucket_boundaries,
bucket_boundaries[1:])):
if left <= number < right:
... | 2c06752e0cee67b3ab077cd5cbe567d2cff545e0 | 587,418 |
def _getWordCategory(word, words_category_index):
"""
Retrieves the category of a word
:param word:
:param words_category_index:
:return:
"""
if word in words_category_index:
return words_category_index[word]
else:
return None | f9fd5701d4df5582ced02f51773fdcb158521114 | 587,419 |
def transformBelowValue(requestContext, seriesList, valueLimit, newValue):
"""
Takes one metric or a wildcard seriesList.
For every point below (valueLimit), replace it with (newValue). Does nothing
to NULLs
"""
for series in seriesList:
series.tags['transformBelowValue'] = valueLimit
... | 6a540fbb8d1fbf816dfb2613cbf33442d04b1f76 | 587,421 |
def calculate_intersect(a, b, dist):
"""
Calculate the count of destinations from the official and the OSM dataset that intersect with different buffer.
Parameters
----------
a : geopandas.GeoDataFrame
the osm or offical destinations
b : geopandas.GeoDataFrame
the osm or offical... | 65c45a349aebabfe0cd01ad9a367e273a1233cad | 587,422 |
def rank_by_order(df, groupby_columns):
"""Uses 1-based ranking, like `df.groupby(..).rank()`.
"""
return (df
.groupby(groupby_columns).cumcount()
.pipe(lambda x: list(x + 1))
) | 360bb7846febdc9d53857103a1be4683df5d5cb9 | 587,424 |
def _spherical_harmonics_l2(xyz, m):
"""Compute the l=2 Spherical Harmonics
Args:
xyz : array (Nbatch,Nelec,Nrbf,Ndim) x,y,z, of (Point - Center)
m : second quantum number (-2,-1,0,1,2)
Returns
Y2-2 = 1/2\sqrt(15/\pi) xy/r^2
Y2-1 = 1/2\sqrt(15/\pi) yz/r^2
Y20 = 1/4\s... | 2226b5113954cb5bbceb3923d0b9a0e92306a133 | 587,425 |
def sphinpq(phi2, phinot, ql, phinoopt=0.2, fmf0=4.88):
"""Calculate S~PhiNPQ
S~PhiNPQ = 1 - ((phi2 * 1 / (1 + phi2 * (1/phinoopt - 1/phinot) / (ql * fmf0) ))+fmf0)
:param phi2: Phi2
:param phinot: PhiNOt
:param ql: qL
:param phinoopt: Optimum PhiNO (default: 0.2)
:param fmf0: Fv/Fm (defau... | 487440fbf1b34d58bbb15d212db12fdcc5c82700 | 587,426 |
def sort_solution(sol):
"""
Sort a solution to an equation by the variable names.
"""
return tuple(sorted(sol, key=lambda e: str(e.lhs()))) | 28d598b6c6759953dce28ceea9966b20a6c191c8 | 587,432 |
import random
def roulette_wheel_selection(population):
"""
A random number between 0 and the total fitness score of all the genomes in
a population is chosen (a point with a slice of a roulette wheel). The code
iterates through the genomes adding up the fitness scores. When the
subtotal is greate... | 69275109981aa86747cfbddcedb3fb333aa0abcb | 587,433 |
from typing import Iterable
def combine_encoders(name: str,
encoders: Iterable[type]) -> type:
"""Combine several Encoders to a new one.
Use this e.g. as
>>> DataclassAndNumpy = combine_encoders('DataclassAndNumpy',
... (DataclassEncoder, Nump... | ac3681a4f54838439907f2d59d2ca3ab36926829 | 587,434 |
import boto.ec2
def get_instances(stack_name, aws_config):
"""Get the IP addresses of all instances in a CloudFormation stack."""
conn = boto.ec2.connect_to_region(
aws_config['ec2_region'],
aws_access_key_id=aws_config['ec2_access_key'],
aws_secret_access_key=aws_config['ec2_secret_ke... | 0c94ab3a50fdf76d0b8c6837b727bb59b5156376 | 587,435 |
import torch
def create_avg_image_from_mosaic_dataset(mosaic_dataset,labels,foreground_index,dataset_number):
"""
mosaic_dataset : mosaic_dataset contains 9 images 32 x 32 each as 1 data point
labels : mosaic_dataset labels
foreground_index : contains list of indexes where foreground image is present so that ... | adce571866a6515745c9c0a89375aec948402b20 | 587,437 |
def filter_token_counts(counts, min_length=1):
"""
Given a list of (token, count) tuples, create a new list with only
those tuples whose token is >= min_length.
Arguments:
counts (list of (str or unicode, int)): tuples of form (token,
count).
min_length (int): minimum length of ... | 5d118d525b0565a9b5da0ebdb013bc9853aac22e | 587,438 |
import hashlib
import base64
def make_digest(acc):
# acc = "username:password"
"""
It make a digest for string acc
:param acc: The `acc` string is in form:
:return: a digest string.
"""
digest = hashlib.sha1(acc.encode()).digest()
rst = base64.b64encode(digest).strip().decode()
re... | a32203f7c0f9e5de280ea376589995c59779b1ce | 587,442 |
def get_dim_wind(self):
"""Get the two first dimension of the winding matrix
Parameters
----------
self : Winding
A Winding object
Returns
-------
(Nrad, Ntan): tuple
Number of layer in radial and tangential direction
"""
return (1, 1) | 7657697dd8e26d20fd1ce370f7aee7a0eeff6328 | 587,443 |
import jinja2
def create_html_template(template_path: str) -> jinja2.Template:
"""Read in the html template file and create a jinja2 template."""
with open(template_path) as f:
return jinja2.Template(f.read()) | 6318d6eff44e493c6b48da8ba368553830110581 | 587,444 |
def is_fitted(estimator):
"""
Checks if a scikit-learn estimator/transformer has already been fit.
Parameters
----------
estimator: scikit-learn estimator (e.g. RandomForestClassifier)
or transformer (e.g. MinMaxScaler) object
Returns
-------
Boolean that indicates if ``estim... | 951c2e01c214ae98acb4606f2172055f152d3082 | 587,448 |
from pathlib import Path
def read_long_description() -> str:
"""Read from README.md file in root of source directory."""
root = Path(__file__).resolve().parent
readme = root / "README.md"
return readme.read_text(encoding="utf-8") | d578df44b0e4017dc099f8e38d6a30561eb2c31c | 587,450 |
def modifyNote(note, front, back, tag):
"""
Modifies given note with given `front`, `back` and `tag`.
If note with id is not found, do nothing.
"""
note.fields[0] = front
note.fields[1] = back
note.addTag(tag)
note.flush()
return note.id | 35dd533e587563509e925ff6db89f6c309ab7ac0 | 587,456 |
def to_listlist(list_dict):
"""Converts a list-of-dicts to a list-of-lists.
Ex: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] ---> [["a","b"],[1, 2],[3, 4]]
Args:
list_dict (<list<dict>>): A list of dictionaries. Ex: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
Returns:
<list<list>>: list-of-lists. Ex... | 46dcbe676e0864bbd266c4ee9a913353f29a86de | 587,462 |
import functools
def tuplize(generator):
""" Takes a generator and make it a tuple-returning function. As a side
effect, it can also decorate any iterator-returning function to force
return value to be a tuple.
"""
@functools.wraps(generator)
def tuplized(*args, **kwargs):
return tupl... | 11042ea2f69e233842c44c0ebfe37c14f3d78b42 | 587,464 |
def quadratic_fxn_fitness(params):
"""
This function is a wrapper for the environment, which takes a set of params and returns a reward.
It is the function to be maximized, a.k.a. the fitness function or objective function.
:param params: a 1D numpy array of parameters to pass to the environment or fun... | 89e56e4fd7d28a4a8c6c35d577e0fe2bb0dd7000 | 587,472 |
import math
def toRad(degree):
"""convert degrees to radians"""
try:
d = float(degree)
except ValueError:
return None
else:
return d*math.pi/180 | 2b6cbb1c3dff85b26fd8c1e55b2b4cec9faab4ba | 587,473 |
def escape(value, char, escape = "\\"):
"""
Escapes the provided string value according to the requested
target character and escape value. Meaning that all the characters
are going to be replaced by the escape plus character sequence.
:type value: String
:param value: The string that is going ... | eceaa28efb4cccd4980b9065add9d522e304c012 | 587,474 |
def mock_match(A, B):
"""
Checked for params on a mocked function is as expected
It is necesary as sometimes we get a tuple and at the mock data we have
lists.
Examples:
```
>>> mock_match("A", "A")
True
>>> mock_match("A", "B")
False
>>> mock_match(["A", "B", "C"], ["A", "... | 629e30c73aebe2e7c14ce05ee5b496fa217b4e4e | 587,477 |
import io
def read_file(file_path):
"""
Return the content of a file as a string without newlines.
:param file_path: The path to the file
:type file_path: str
:return: File content
:rtype: str
"""
file_string = ''
with io.open(file_path, 'r', newline='', encoding='utf8') as file... | f721d2e37040d35750cf544f82088c372c801acd | 587,478 |
def transpose(m):
"""transpose(m): transposes a 2D matrix, made of tuples or lists of tuples or lists,
keeping their type.
>>> transpose([])
Traceback (most recent call last):
...
IndexError: list index out of range
>>> transpose([[]])
[]
>>> transpose([1,2,3])
Traceback (most... | e6d7b77a2e1fa7e376e4174bf6ea56fabaa3f830 | 587,479 |
def is_punct(char):
"""
Checks if the character is a punctuation
Parameters
--------------
char: str
A single character string to check
"""
if char == "." or char == "," or char == "!" or char == "?" or char == '\\':
return True
else:
return False | 649d649d0e473b64092860b45c1e5457cd61b02b | 587,480 |
import random
def _determine_value(neighbors, values):
"""
Returns the value to set an element to based on its neighbors.
:param neighbors: The neighbors of the element in question.
:param values: The values of the terrain. This is passed in so that
a new dictionary doesn't have to be cre... | 5e8979dd492ef65802fc803956f6d3c5843ac0f1 | 587,484 |
def get_full_querystring(request):
"""
Get the querystring from a request with leading `?` or empty string
Parameters
----------
request : django.http.HttpRequest
Returns
-------
str
Querystring with leading `?` if a querystring could be extracted from
the request. Oth... | 26fb7b01db901544c35d5fe0469db4f19c240ab2 | 587,486 |
def get_by_key_chain(mapping, keys):
"""Get a value from nested mapping by a chain of keys.
:param mapping: the mapping from which the value is extracted.
:param keys: a sequence of keys used to locate the requested value.
:returns: a value resulting from getting a value from the mapping by
the... | ef1067bf03c8e1207039c7f1de7a5c2fd84d46ce | 587,487 |
def merge_zs_lfcs(reference_df, z_scored_residuals, lfc_df):
"""Merge z-score and lfc DataFrames
Parameters
----------
reference_df: DataFrame
Mapping between reference and perturbed conditions
z_scored_residuals: DataFrame
Melted dataframe with residuals for each condition
lfc_... | 6b0389ed093e753b69e9181ff4dc1f72fbdea98f | 587,492 |
def kth_largest_element(nums, left, right, k):
"""
Find kth largest element in given array (like quick sort)
:param nums: given array
:type nums: list[int]
:param left: left position to begin
:type left: int
:param right: right position to end
:type right: int
:param k: kth
:typ... | ecc852faf3fcf70f510baf5a193af2bf6aac8662 | 587,495 |
def _remove_human_readables(token: str) -> str:
"""Remove human readable characters from a string. Example: "$1,000" -> "1000"
:param token:
Token to remove human readable characters
:return:
Token without human readable characters (to cast to numeric type)
"""
# Translate bad chara... | eda562e82381504bcb34a088ca92c12550c927b5 | 587,496 |
def validate_yn(val):
"""
Input validator function for yes/no prompts.
"""
_l = val.lower()
return _l == 'y' or _l == 'n' | 9dbe147c776bad7e6d70719e2510a4266c15bcd9 | 587,498 |
import calendar
def utctotimestamp(dt):
"""Returns a count of the elapsed seconds between the Unix epoch
and the passed-in datetime.datetime object."""
return calendar.timegm(dt.utctimetuple()) | 500a130e160ec38a03dafa4300382e57ae0dca09 | 587,499 |
def get_binding(config_dict):
"""Get the binding for the WeeWX database."""
# Extract our binding from the StdArchive section of the config file. If
# it's missing, return None.
if 'StdArchive' in config_dict:
db_binding_wx = config_dict['StdArchive'].get('data_binding',
... | fa9106e37a0830f0e87b45515d8016406892fc8f | 587,502 |
def get_train_val_split_from_names(src, val_list):
"""
Get indices split for train and validation entity names subset
src -- list of all entities in dataset
val_list -- contains entities that belong to the validation subset
"""
train_idx = []
val_idx = []
len_ = len(val_list)
... | 931c9ed22997bdfdbbaf89454ada2f02439e0208 | 587,503 |
from typing import List
from typing import Union
def perfect_score(student_info: List[List[Union[str, int]]]) -> Union[List[Union[str, int]], str]:
"""
:param student_info: list of [<student name>, <score>] lists
:return: First [<student name>, 100] found OR "No perfect score."
"""
for elem in stu... | 2335d80b0c406778cb58d11d9360f9a25b2693ec | 587,504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.