content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import base64
def get_content_b64(filepath):
"""Given a filepath, return the base64 encoded representation of the
file's content.
"""
with open(filepath, 'rb') as f:
content = f.read()
return base64.b64encode(content).decode('utf-8') | b95ad844796425a9b5e112b5d1801dd2c8ee28c3 | 38,066 |
import ast
def isConstant(x):
"""Determine whether the provided AST is a constant"""
return (type(x) in [ast.Num, ast.Str, ast.Bytes, ast.NameConstant]) | 232946a37e8bce7c093d6f8a446e11019cfc798c | 38,069 |
def get_instances_not_in_output(possible_instances, stdout_output):
"""return instances where their id is not in the stdout output"""
return [instance
for instance in possible_instances
if instance['id'] not in stdout_output] | 540663c38511c42f95466da06cb05153ce15a872 | 38,070 |
import re
def is_url(url: str):
"""Uses RegEx to check whether a string is a HTTP(s) link"""
# https://stackoverflow.com/a/17773849/8314159
return re.search(r"(https?://(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]"
r"[a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{... | c58be1bc1775024ef412ff15529de7a780bde5ea | 38,078 |
def _make_dataset(
df, label_column_name, left_value_column_name,
right_value_column_name, standing_out_label_name_list):
"""
Make the required dataset from the data frame.
Parameters
----------
df : pandas.DataFrame
The target data frame.
label_column_name : str
... | 3eb220101354ea919369dfeb1317310f18a4df97 | 38,085 |
from pathlib import Path
import logging
def evaluate_implementation(callback_file: Path, function_name: str) -> bool:
"""Checks whether a function name is found in a source file or not."""
found = False
impl = callback_file.read_text()
if function_name in impl:
logging.info(f"Found '{function_... | 3ad087dc2db09aeb78874c9b934a553f7457e511 | 38,088 |
def _get_user_id(data):
"""
Get user ID which this event is generated by.
Event payload schema highly depends on event type.
:param data: event payload
:type data: dict
:rtype: non empty string or None
"""
for key in ['user', 'user_id']:
user = data.get(key)
if user:
... | 4f4b418da99bdd6ae99e628a30fc0c02c2cfe4ab | 38,089 |
def validate_number(num, low, high):
"""
Takes user input as a string and validates that it is
an integer between low and high
"""
try:
num = int(num)
except ValueError:
return False
if num < low or num > high:
return False
return True | ffe695934b09c8c6e34a3ea1880f473efb3a36c9 | 38,090 |
def has_path(coll, path):
"""Checks if path exists in the given nested collection."""
for p in path:
try:
coll = coll[p]
except (KeyError, IndexError):
return False
return True | 9904656c367c466dc6fcf352a828e7601a5ce6d2 | 38,097 |
def headers(questions):
"""
Generate the headers for the CSV file
- take an array of questions. The order is important
- Each question id is a column header
- Paired with the index+1 of it's position in the array
- Example: 43:SQ3-1d
- SQ3-1d is the old question id
- 43 is it's number on... | 81f7da32157ea4bbc2467ccf112f97c7f68fe688 | 38,100 |
import logging
def scope_logger(cls):
"""
Class decorator for adding a class local logger
Example:
>>> @scope_logger
>>> class Test:
>>> def __init__(self):
>>> self.log.info("class instantiated")
>>> t = Test()
"""
cls.log = logging.getLogger('{0}.{1}'.format... | 84e00f8f668accd362d4fc29016fd2ec95f0bcef | 38,102 |
def cvtInt(intstr):
""" Convert integer string into integer.
Parameters:
intstr - integer string
format: "[0-9]+"
Return Value:
Returns converted integer value on success. None on error.
"""
try:
val = int(intstr)
return val
except (SyntaxError, NameE... | 907a73c358d6de3231caffc610afaf3f032613ab | 38,104 |
def add_variable_to_dataset(dataset, var_name):
"""
Convenience function to add a variable to the dataset
only if the variable doesn't already exist. This function
is case sensitive. "radius" and "Radius" are two different
variable names.
returns the Variable object associated with the variabl... | 109359e3f986ea08c1166fd72a76d878238f6a13 | 38,106 |
import unicodedata
def filter_non_printable(string_to_filter):
"""
Filter string 's' by removing non-printable chars
:param string_to_filter:
:return:
"""
output_string = ''.join(
c for c in string_to_filter
if not unicodedata.category(c) in set('Cf')
)
return output_s... | dc9a3513d29ea8891a952b879b31bcb0752f4bb0 | 38,107 |
def _type_to_template(qname, subject_type, predicate, object_type):
"""
>>> _type_to_template(lambda x: "q:"+x, "subject", "pred", "object")
'rdf/q:subject/q:pred/q:object.html'
>>> _type_to_template(lambda x: "q:"+x, "subject", "pred", None)
'rdf/q:subject/q:pred/rdf:Resource.html'
>>> _type_... | 1d7243071cca7226947bfd763d00b7be50620c15 | 38,108 |
def __normalize_str(name):
"""Removes all non-alphanumeric characters from a string and converts
it to lowercase.
"""
return ''.join(ch for ch in name if ch.isalnum()).lower() | bf174967de9d8aa812fd78ad9a18e6f076bc137f | 38,113 |
def without_ends(string: str) -> str:
"""
>>> without_ends('abc')
'b'
"""
return string[1:-1] | eedc605702d67a22341a10a1df3a719b78b6174d | 38,115 |
async def healthcheck():
"""
Return the API status.
"""
return {"ping": "pong"} | cad4018cda809dcc3713b5a104bc25acf4830936 | 38,117 |
def vbar(vmodel, event_depth, station_elevation):
"""
Calculates the average velocity between source and receiver for a given
velocity model.
Only need the difference in the vertical axis as sines of angles will
cancel.
Parameters
----------
vmodel : pandas DataFrame
Contains t... | ce10c0148d9b292b9a825a49bc983b7c81d975b2 | 38,119 |
def is_weekend(data):
"""
Adds a binary is_weekend column to a pandas DataFrame
Args:
data - a pandas DataFrame containing a 'created_time' column of
datetime objects
Returns:
A DataFrame with an additional 'is_weekend' column
if data['created_time'][i] is Fr... | 1dd00dda7e41031bc7bac462618124ca8fd133bd | 38,122 |
def route(url, endpoint=None, methods=None):
"""
A decorator that apply a route to the view or action.
:param str url: The url rule.
:param str endpoint: The endpoint.
:param list methods: A list of http methods.
:return: A function.
"""
if not url:
raise ValueError('url cannot b... | 18b5c3fb287e8f21e8a8eeeac8643f123df75b7f | 38,123 |
import string
import secrets
def rand_token(length: int = 25,
chars: str = string.ascii_uppercase + string.digits) -> str:
"""
Generate a random token. Does not check for duplicates yet.
A length of 25 should give us 8.082812775E38 keys.
length: - length of token to generate
chars... | 1cecef09eca30dee6bb607d7e5ce359d977e8beb | 38,127 |
def word_overlap(left_words, right_words):
"""Returns the Jaccard similarity between two sets.
Note
----
The topics are considered sets of words, and not distributions.
Parameters
----------
left_words : set
The set of words for first topic
right_words : set
The set of... | 3baa3ec5605bef4658815ac4d546539c480ae4b5 | 38,133 |
def convert_weight(val, old_scale="kg", new_scale="pound"):
"""
Convert from a weight scale to another one among kg, gram, and pound.
Parameters
----------
val: float or int
Value of the weight to be converted expressed in the original scale.
old_scale: str
Original scale from ... | d38fed48ac998b8c21b8dd25fb497479d04e899a | 38,138 |
def is_chinese(target_str):
""" determine whether the word is Chinese
Args:
target_str (str): target string
"""
for ch in target_str:
if '\u4e00' <= ch <= '\u9fff':
return True
return False | ee75d9ea6d6e396964f511c10eaeeaf96a836aaa | 38,141 |
def format_record(record):
"""Format float values to high precision, not in exponential form."""
return [f'{r:.15f}' if isinstance(r, float) else r for r in record] | a4b6b25ac429129d843ef59b25d9ae9fc7531969 | 38,144 |
import math
def inverseJukesCantor(d):
"""Takes a substitution distance and calculates the number of expected changes per site (inverse jukes cantor)
d = -3/4 * log(1 - 4/3 * p)
exp(-4/3 * d) = 1 - 4/3 * p
4/3 * p = 1 - exp(-4/3 * d)
p = 3/4 * (1 - exp(-4/3 * d))
"""
assert d >= 0.0
re... | 648f091d2a8daf0b41cf939c007e50f6c0eef52a | 38,145 |
def cnvtol(self, lab="", value="", toler="", norm="", minref="", **kwargs):
"""Sets convergence values for nonlinear analyses.
APDL Command: CNVTOL
Parameters
----------
lab
Valid convergence labels. If STAT, list the status of the currently
specified criteria.
value
T... | 632a895db755cdf23c88b1df88700cb9c0529f69 | 38,147 |
from typing import Any
def find_key(d: dict, key: str) -> Any:
"""Finds a key nested arbitrarily deeply inside a dictself.
Principally useful since the structure of NRPE relation data is
not completely reliable.
"""
if key in d:
return d[key]
for child in d.values():
if not is... | e6b176450d25ea1e194019c7d4bdb85d500488ae | 38,149 |
def gather_results(detectors):
"""
Execute the d.compute method for each given detector.
After that the result (d.getDetectorOutput()) method is called and added as value
under the key d.getName() to the result which is returned in the end.
:param detectors:
:return:
"""
results = {}
... | 10366cc7880474f54d093c5f4bd8c11b4b454aab | 38,150 |
def _find_label_rows(sheet):
"""Search excel file column A for cells containing 'Label'.
Return a list of zero-indexed rows.
"""
label_rows = []
for i in range(sheet.nrows):
if "Label" in sheet.cell_value(i, 0):
label_rows.append(i)
return label_rows | 5515874500c5ef514df02019e745d609b0474b2f | 38,151 |
import hashlib
def hash_all(strs, digest=None):
"""Returns a hash of the concatenation of all the strings in strs.
If a hashlib message digest is not supplied a new sha1 message digest is used.
"""
digest = digest or hashlib.sha1()
for s in strs:
digest.update(s)
return digest.hexdigest() | 585496aaae534d24cba512482765aeb9250ef6b8 | 38,156 |
import socket
import struct
def parse_ipv6(addr):
"""
Return a numeric representation of the given IPv6 address.
"""
binary_ip = socket.inet_pton(socket.AF_INET6, addr)
high, low = struct.unpack('!QQ', binary_ip)
return high << 64 | low | 6456d02ae7b4b5eadd2666fad7308ef5547b98dc | 38,157 |
def get_protein(chain):
"""
Get protein (residues without hetero-residues).
"""
return [residue for residue in chain.get_residues() if residue.full_id[3][0] == ' '] | f5d20e0a7edf15f3a90a4b2c3f889211cb44d87d | 38,159 |
import zlib
def text_decompress(text) -> str:
"""对文本进行解压
Args:
text (str or bytes): 待解压文本
Returns:
str: 解压后的文本
"""
return zlib.decompress(text).decode() if type(text).__name__ == "bytes" else text | 933d8fe5ac4f615b60831551deee80fc429171ac | 38,160 |
def is_rect_intersection(minlat, maxlat, minlon, maxlon, latitude, longitude):
"""
Checks if there is a radial intersection between a point radius boundary
and a latitude/longitude point.
:param: minlat : the minimum rectangular latitude :type: float
:param: maxlat : the maximum rectangular latitude... | 39f872e74a9cf6d77521a5a5666bf8701662ba0c | 38,161 |
from datetime import datetime
import time
def rddToFileName(prefix, suffix, timestamp):
"""
Return string prefix-time(.suffix)
>>> rddToFileName("spark", None, 12345678910)
'spark-12345678910'
>>> rddToFileName("spark", "tmp", 12345678910)
'spark-12345678910.tmp'
"""
if isinstance(tim... | ecf09d0fc16b23b892635197c87495ad8aa42bdf | 38,163 |
def group_com(mat_A, mat_B):
"""Compute the group commutator A B A^dagger B^dagger for two matrices A, B."""
return mat_A @ mat_B @ mat_A.T.conj() @ mat_B.T.conj() | b84170a21fc85f7a3dc68014483137804661f3c0 | 38,165 |
def compare_dict_keys(dict_a, dict_b, compare_keys):
"""Compare two dictionaries with the specified keys"""
return all(dict_a[k] == dict_b[k] for k in dict_a if k in compare_keys) | 00de8cc97f8b56608575570150a97038ed61b997 | 38,170 |
def get_index(sheet, *names):
"""
Returns the column index for the first matching name, assuming first row is header
Matching is done with leading and trailing whitespace stripped, and case insensitive
"""
header = [(c.value or "").strip().lower() for c in sheet[1]]
for name in names:
na... | 45af5638cc66fb51a4addbf8ecec27ffadd2cf09 | 38,174 |
def _hex_to_triplet(h):
"""Convert an hexadecimal color to a triplet of int8 integers."""
if h.startswith('#'):
h = h[1:]
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) | e84b3de0d94eda11a63390cfd0448708bd69cc66 | 38,180 |
def unique_color_from_identifier(identifier):
"""Return unique color as RGB tuple.
Useful for creating PNG images where each color is used as an identifier.
Raises TypeError if the identifier is not an integer.
Raises ValueError if the identifier is not in the range 0 to 16777215
inclusive.
... | dcf3555c95e6799c1d9042c2342d9181e44d56cd | 38,186 |
def get_recall(rec, tru):
"""Recommendation recall: |{R & P}|/|P| (R - recommended products, P - relevant products)"""
return len(rec & tru)/len(tru) if len(tru) != 0 else 0 | 83ec9f53a43a8d4f0b2d6174457cd8a7937a1bed | 38,189 |
import json
def load_config(config_files):
""" loads json configuration files
the latter configs overwrite the previous configs
"""
config = dict()
for f in config_files:
with open(f, 'rt') as cfg:
config.update(json.load(cfg))
return config | 4a61ca063bf8147a0f2576cddc8bf438b33f8792 | 38,192 |
from typing import Optional
def askyn(question: str, default: Optional[bool] = None) -> bool:
"""
Asks a yes or no question and returns a bool.
REF: https://gist.github.com/garrettdreyfus/8153571
"""
# Modify the question with the default value capitalized
if default is not None:
if de... | f038ffce000e5c39d707dd61d3f1967195df4e6d | 38,195 |
import torch
def box_center_to_corners(b):
"""
Converts a set of oriented bounding boxes from
centered representation (x_c, y_c, w, h, theta) to corner representation (x0, y0, ..., x3, y3).
Arguments:
b (Tensor[N, 6]): boxes to be converted. They are
expected to be in (x_c, y_c, w,... | 0ab937e31fc8c2e67748b5d791a7061fa0fb70fe | 38,196 |
def make_iterator(it):
"""
Create iterator from iterable.
"""
return iter(it) | ec683c4d109fd9afedc57b1a9476080400930122 | 38,199 |
from pathlib import Path
def get_datapath_base(data_type: str, filename: str) -> Path:
"""Return the path to the footprints test data file"""
return Path(__file__).resolve(strict=True).parent.joinpath(f"../data/{data_type}/{filename}") | 9bccb92b1c4a5dbaa625b2fa52b3c77163104c11 | 38,200 |
from typing import Collection
def find_valid_words(dictionary: Collection[str], candidates: Collection[str]) -> Collection[str]:
"""Finds valid words from 'candidates' as found in
the given words list.
dictionary: the list to be used as a dictionary. Only strings in the dictionary are considered valid wor... | 14706ca99787869d0eee1c77a929bc1f34cf2238 | 38,201 |
def matchingTest(vector):
""" input: a list of corr coeff scores from moments
output: match or not
criteria:
all > 0.9 - yes
all > 0.8, all but one > 0.9, four>.99 - yes
else - no
"""
point99 = len([v for v in vector if v>0.99])
point9 = len([v for v in vector if v>0.90])
po... | bfc0bd830948cb0c5f4f6342c699ef280d0c4480 | 38,202 |
def drop_column(df, columns_to_drop):
""" Removes columns from a DataFrame
del df[name]
Args:
df (`pandas.DataFrame`): The dataframe to drop columns on
columns_to_drop (:type:`list` of :type:`str`): A list of the columns
to remove
Returns:
`pandas.DataFrame`: `df` ... | 1eadbf301aff80752c93ca4393910dfa19a76b3a | 38,203 |
def add_commas(num: int) -> str:
"""Adds commas to an integer in the international number format
- 1000 -> 1,000
- 100000 -> 100,000
- 1000000 -> 1,000,000
Args:
num (int): The number
Returns:
str: The number with commas
"""
return "{:,}".format(num) | 9f63a6389df5b46ebbe0dc7489d4967919da18d7 | 38,210 |
from typing import Iterable
from typing import List
import locale
def sorted_locale(iterable: Iterable[str], *, reverse: bool = False) -> List[str]:
"""Sort a list of strings according to locale.
Parameters
----------
iterable : iterable of str
A list of strings.
reverse : bool, default=F... | e5092e7343989757ffe5fad9bfaf26637b6b5834 | 38,212 |
from math import sin, cos, sqrt, atan, radians
def calc_distance(position_start: tuple, position_end: tuple) -> float:
"""Calculates the distance between two positions in format (lat, lon)
"""
f = 1 / 298.257223563
a = 6378173
F = radians((position_start[0] + position_end[0]) / 2.0)
G = radian... | c330e7e0e45f7643c7c14c6b066a854a97bd196a | 38,215 |
def strip_schema_version(json_dict):
"""Returns the given JSON dict after stripping its schema version out
:param json_dict: The JSON dict
:type json_dict: dict
:returns: The JSON dict with its schema version stripped out
:rtype: dict
"""
if 'version' in json_dict:
del json_dict['v... | 2c5e7b5bfb401e1adef5479f0d787c2788d1d735 | 38,220 |
def sum_square_difference(ceiling):
"""Compute the difference between the sum of squares and the square of
the sum of the natural numbers up to and including the provided ceiling.
"""
numbers = range(ceiling + 1)
sum_squares = sum(map(lambda number: number**2, numbers))
square_sum = sum(numbers... | 5898969697c2c8500dda0d0ef9ca5f3e7125ff77 | 38,225 |
import fnmatch
def fnmatch_all(names, patterns):
"""Determine whether all strings in `names` match at least one of
the `patterns`, which should be shell glob expressions.
"""
for name in names:
matches = False
for pattern in patterns:
matches = fnmatch.fnmatch(name, pattern... | 52be9c216d222fed331a836d529bc1399ba8e9b4 | 38,227 |
def read_seq(handle):
"""
Read sequence from plain text file (no format). Used for importing
reference sequence.
:param handle:
:return: str, sequence
"""
seq = ''
for line in handle:
seq += line.strip()
return seq | 063f9e5300093537d81ed6ee8eb96579ae0dfcf5 | 38,230 |
def split(n):
"""
Split string or Array
>>> split("hello")
['he', 'llo']
>>> split([1,2,3,1,2,4])
[[1, 2, 3], [1, 2, 4]]
"""
return [ n[:len(n)//2:], n[len(n)//2::] ] | ab132de4077bbc390a8b4f2f38c5154ecd75d579 | 38,231 |
def parse_tile(tile_string):
"""
>>> parse_tile("esew")
(1, -1)
>>> parse_tile("esewnw")
(0, 0)
>>> parse_tile("nwwswee")
(0, 0)
"""
data = list(tile_string)
cur_pos_ew = 0
cur_pos_ns = 0
while len(data) != 0:
c1 = data.pop(0)
if c1 == 'w':
cur... | 7b6ee9725a65e88f3110c288000fb8d9626826b7 | 38,236 |
def parse_storage_mappings(storage_mappings):
""" Given the 'storage_mappings' API field, returns a tuple with the
'default' option, the 'backend_mappings' and 'disk_mappings'.
"""
# NOTE: the 'storage_mappings' property is Nullable:
if storage_mappings is None:
return None, {}, {}
back... | ea182c91ff5e2fe1e9a7a7066071a618eb039a5f | 38,239 |
def bbox3d2result(bboxes, scores, labels, attrs=None):
"""Convert detection results to a list of numpy arrays.
Args:
bboxes (torch.Tensor): Bounding boxes with shape (N, 5).
labels (torch.Tensor): Labels with shape (N, ).
scores (torch.Tensor): Scores with shape (N, ).
attrs (to... | d31481229e17bc25d4f1d6fe5b9ac757b194357e | 38,242 |
import pathlib
def _load_file_contents(path: pathlib.Path) -> str:
"""Return the contents of a file."""
with path.open("r") as fp:
return fp.read() | ca90bcc6f346e69f10323388b8bc2faf49e2553d | 38,244 |
def recordCounter(x):
""" Simple record sizer that just returns 1 for each record """
return 1 | a9b735c34b7978a866de6ffcf268875940664160 | 38,249 |
import hashlib
def sha256(byte_array) -> bytes:
"""
Perform a SHA256 operation on the input.
:param byte_array: data to hash.
:type byte_array: bytearray or bytes
:return: hashed data
:rtype: bytes
"""
return hashlib.sha256(byte_array).digest() | 9017ccfa9f548502fcebdc61aedec85924907225 | 38,251 |
def get_first_and_last_line(fname):
"""
Get the first and last line of the file.
Since the common_crawl files are alphabetical, we can use this information to determine the alphabetic
range of entries covered by the file. This information will later be used to limit the zone comparison
to only those... | 6c69957698cf9357c0c223ec55ba01ecf1aff6ea | 38,252 |
def obtain_points(func, theta_0, theta_1, min_x, max_x, step=0.1):
"""
Return a tuple of x and the corresponding points for the given x
"""
x_values = []
y_values = []
x = min_x
while x <= max_x:
y_values.append(func(x, theta_0, theta_1))
x_values.append(x)
x += ... | a603660d60a8fdc8c99b5fb05c756afe972dd1ab | 38,256 |
def create_aln_expr(id, start=None, stop=None):
"""
Create an alignment expression, such as ``n2[5:8]`` or ``tw1`` given an id, and start/stop range.
:param id: ID with which to align
:type id: str
:param start: Range at which to start
:type start: int
:param stop: Range at which to stop
... | e06c4e65beffc1ec14bd4b16e34e6f14b22f2576 | 38,257 |
import torch
def ellip_gaussian2D(radius,
sigma_x,
sigma_y,
dtype=torch.float32,
device='cpu'):
"""Generate 2D ellipse gaussian kernel.
Args:
radius (tuple(int)): Ellipse radius (radius_x, radius_y) of gaussian
... | 97caa00f535321b4c7831c251d3f0d6aaf3d2e32 | 38,262 |
import heapq
def _simple_chooser(queue, remaining):
"""Default contraction chooser that simply takes the minimum cost option.
"""
cost, k1, k2, k12 = heapq.heappop(queue)
if k1 not in remaining or k2 not in remaining:
return None # candidate is obsolete
return cost, k1, k2, k12 | 5bb92184767ba68247b124d4a935ea9dab327f96 | 38,263 |
import torch
def btranspose(tensor: torch.Tensor) -> torch.Tensor:
"""Batch-wise transpose. Assumes that tensor has dimension of 3: [batch, features, samples]"""
if tensor.dim() != 3:
raise ValueError("The given shape is not supported.")
return torch.transpose(tensor, 1, 2) | 4b238672a2cfca33abb86116949acd6d392434f0 | 38,266 |
import re
def opensearch_clean(f):
"""
Some opensearch clients send along optional parameters from the opensearch
description when they're not needed. For example:
state={openoni:state?}
These can cause search results not to come back, and even can cause Solr's
query parsing to thro... | 862bf8cbb9a2629949746a92b78b3b23bdfd7c49 | 38,273 |
def key2num(key):
"""
Translates MIDI key to a number.
"""
key2num = {"C": 0, "Db": 1, "D": 2, "Eb": 3, "E": 4, "F": 5, "Gb": 6, "G": 7, "Ab": 8, "A": 9, "Bb": 10, "B": 11,
"Cb": 11, "C#": 1, "D#": 3, "F#": 6, "G#": 8, "A#": 10, "B#": 0,
"Cmin": 20, "Dbmin": 21, "Dmin": 22, "Ebmin": 23, "Emin": 24, "Fmin": ... | a11a22a62c94c84a946df710e39d2d874f3bf343 | 38,274 |
import re
def check_for_function(function: str, data: str) -> bool:
""" Checks for a function in javascript code
function: the name of the function
data: the javascript code
returns: Whether the code contains the function
"""
return bool(re.search(f'[^a-zA-Z]{function}[^a-zA-Z]', data)) | 671b3554a70407d447cac26b27f542812cbba97c | 38,276 |
def user_discrim(user):
"""
Return the user's username and disc
in the format <username>#<discriminator>
"""
return f"{user.name}#{user.discriminator}" | 22866ad0c23a23bfbd7460844a9582916970991c | 38,280 |
import configparser
import json
def write_config_to_file(config_dict, ini_fpath):
""" Writes a configuration to an ini file.
:param config_dict: (Dict) config to write
:param ini_fpath: (str) fpath to ini file
:return: (str) ini_file written to
"""
config = configparser.ConfigParser()
config["DEFAULT"]... | 8b9c9c64e08afe64bc4fc6f9570ea84f53b9f72c | 38,281 |
import json
def model_comment(comment_type, text, other=None):
"""
Print a model comment. This is a base function for some functions implemented below but sometimes it is necessary to
use it directly.
:param comment_type: Comment type string.
:param text: Comment text.
:param other: Additiona... | 23b7278bd9bcf1dbe0b41e908bcd41bd792789f1 | 38,284 |
def fetch(spec, **kwargs):
"""
Fetches a file on the local filesystem into memory.
"""
with open(spec['path'], 'rb') as f:
return f.read() | 84442c8df0efa0fa095b2d8282ea9c0d4cd2995f | 38,286 |
from typing import Union
import torch
def reshape_list(flat_list: list, size: Union[torch.Size, tuple]) -> list:
"""
Reshape a (nested) list to a given shape
Args:
flat_list: (nested) list to reshape
size: shape to reshape to
Returns:
list: reshape list
"""
if len(siz... | c9c9b09bb0d91ed3229f0b5e5b28130ac2d93377 | 38,287 |
def prod(*x):
"""
Returns the product of elements, just like built-in function `sum`.
Example:
----------
>>> prod([5, 2, 1, 4, 2])
80
"""
if len(x) == 1 and isinstance(x[0], list): x = x[0]
p = 1
for i in x:
if hasattr(i, "__mul__"):
p *= i
return p | 94569594eab0c6823733d76d69d59d21a6b4d96b | 38,289 |
def hello(bot, update):
"""
Greet the user with their first name and Telegram ID.
"""
user_firstname = update.message.from_user.first_name
user_id = update.message.from_user.id
return update.message.reply_text(
'Hello {}, your Telegram ID is {}'.format(user_firstname, user_id)
) | e5567d6748f202093bc44c514b38d6d32c162d4b | 38,291 |
def create_price_sqm(data):
"""Create price per square meter feature."""
data['Prezzo_per_m2'] = data['Prezzo'] / data['Superficie']
return data | 6a50084f69f233374ffa4512de2653f37f749467 | 38,293 |
def convert_num(mode, num):
"""Converts a number in any given number scale
Example:
`convert_num("100K", 600000) returns 6`
Args:
- mode: (string) the scale for the conversion ("100K", "M", "10M", "100M", "B")
- num: the number to be converted
Returns:
the converted number
"... | 461d5cf0d35e43509db3cffebf5487ab85470545 | 38,294 |
import re
def stripms(stamp):
"""
Given ISO 8601 datestamp, strip out any milliseconds in representation
using a regular expression safe for either stamps with or stamps
without milliseconds included.
"""
parts = stamp.split('.')
if len(parts) == 1:
return stamp # no millisecond p... | 937136fc563f0b6084521ddd912a21bade2166cf | 38,296 |
def get_parent(vmfs):
""" From a set of VMFs, determines which one has the lowest map version
number, and is therefore the parent.
"""
# This avoids the need to subscript and slice.
vmfs = iter(vmfs)
parent = next(vmfs)
lowestRevision = parent.revision
for vmf in vmf... | bae83d2e02edc835c533873994285870246c7623 | 38,298 |
def format_parameter(*args, **kwargs):
"""Format a parameter string
>>> format_parameter(ex=['example', 'one'])
'"ex=example:one"'
>>> format_parameter('one', 'two', 'three')
'one:two:three'
You can mix the arguments und keyword arguments.
"""
parameter_list = []
for value in args:... | 77c84e3edb22de0a4cec58b9bcbeb1ef67ee2d5e | 38,304 |
import torch
def prep_tensor_for_vis(x):
"""Prepare tensor for visualization
If only has one channel, concatenate to produce 3 channels
Clone, detach and pass to cpu before clamping between 0 and 1
Parameters
----------
x: torch.FloatTensor
Tensor with image (CHW)
Returns
---... | 20426f0c3aef6f467ccc0b7b1bca26b30eb3bba9 | 38,307 |
from datetime import datetime
def is_datetime(string):
"""
Check if a string can be converted to a datetime object.
:param string: the string
:return: True if the string can be converted to a datetime object, False otherwise
"""
try:
datetime.strptime(string, "%Y-%m-%d %H.%M.%S")
... | d1fa368d1b7ac45b85661bd4b72771d088c4ac6f | 38,309 |
def _compare_properties(sub_set: list, set_: list) -> bool:
"""
Check for a subset in a set of properties.
Parameters
----------
sub_set : list
The smaller set that should be contained in the 'set'.
schema : dict
The set for which to check if 'sub_set' is a part of.
Returns... | a13a29b4cb0b1728277c237b40bd4c5567beb001 | 38,310 |
def calculate_accuracy(combined_decisions, Y_test_1):
"""calculates percentage accuracy of a combined decisions array
Args:
combined_decisions: predicted values for combined model
Y_test_1: True values
Returns:
percentage accuracy of predictions
"""
total_decisions = len(comb... | 7494ef3bc017e628f9621f803c27bd2c77ccff2b | 38,312 |
import requests
def load_mta_archived_feed(feed='gtfs', timestamp='2014-09-17-09-31'):
"""
Returns archived GTFS data for a particular time_assigned.
Parameters
----------
feed: {'gtfs', 'gtfs-l', 'gtfs-si'}
Archival data is provided in these three rollups. The first one covers 1-6 and th... | d1d38854dbd35f2c30342b9958d0640541162dd1 | 38,317 |
from typing import Dict
from typing import Any
def _setdefault(dictionary: Dict[str, Any], key: str,
value: Any) -> Dict[str, Any]:
"""Sets the default value of `key` to `value` if necessary.
Args:
dictionary: the dictionary to add a default for.
key: The key to add a default for.
val... | d989b167769aaf6674027b68f5ec0463fea5251d | 38,318 |
def _no_op(*args, **kwargs):
"""No operation."""
return None | fa389f2d8aae0e38dd414b0294a3da948e0c9595 | 38,319 |
def set_size(self, mode):
"""Calculates the number of samples in the dataset partition"""
return len(self.data_index[mode]) | 8337089875f70d0d4db68f1ff67bd29705774747 | 38,321 |
def is_derivatized(monosaccharide):
"""Tests whether any of the substituents attached to `monosaccharide` were
added by derivatization.
Parameters
----------
monosaccharide : Monosaccharide
The object to test
Returns
-------
bool
"""
for pos, sub in monosaccharide.subst... | f77cc01e14939b94652bb9d19f7d0729201f35bb | 38,322 |
def gradient_summand(weights, lp):
"""Calculates the gradient summand for a given weight and `LabeledPoint`.
Note:
`DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably
within this function. For example, they both implement the `dot` method.
Args:
... | b34de095fb762aa933570ae58744772205ded5de | 38,325 |
def schedule(intervals):
"""Schedule the maximum number of compatible intervals.
This uses the greedy interval scheduling algorithm to find (schedule)
the maximum number of compatible (non-overlapping) intervals.
Args:
intervals: list of intervals, each of which is a tuple (x,y)
in... | 19480ff5b24070e53e9243066c3f34f8a91d1e98 | 38,328 |
def parse_hgnc_line(line, header):
"""Parse an hgnc formated line
Args:
line(list): A list with hgnc gene info
header(list): A list with the header info
Returns:
hgnc_info(dict): A dictionary with the relevant info
"""
hgnc_gene = {}
line = line.rstr... | 9b0c373a107782d81b818b258e9c273e89b9ec12 | 38,329 |
def get_integer(message, minimum, maximum):
"""Retrieves an integer value prompted from console,
in such a way that `minimum ≤ value ≤ maximum`
"""
while True:
try:
value = int(input(message))
if not minimum <= value <= maximum:
raise ValueError()
... | b3c0708a17b03c66555dfc41e12b2b33cab0914c | 38,337 |
def get_smallest_entry(visited, distance):
""" Returns the position of the unvisited node with the smallest
distance. Returns None if no options are left. """
smallest = None
smallest_entry = None
for i in range(0, len(visited)):
if not visited[i] and distance[i] is not None:
if... | 5097ab5587c495a7fa8c14f173f1109bea55cb4a | 38,345 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.