content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
def split_chunks_on(str_: str, maxlen: int, split_char='\n') -> List[str]:
"""
Split a long string along `split_char` such that all strings are smaller than but as close as
possible to `maxlen` size.
Lines that exceed `maxlen` size will not be split.
"""
len_split = le... | 72e2702a1771d5bbc145234c736f62aeec42e7b5 | 96,133 |
def subpaths_from_list(page_list):
"""
Build node pairs (edges) from a list of page hits
:param page_list: list of page hits
:return: list of all possible node pairs
"""
return [[page, page_list[i + 1]] for i, page in enumerate(page_list) if i < len(page_list) - 1] | d2ec81527515a4eb8777245d1558b6cb5ef3ab4f | 96,139 |
def extract_glyphs_from_coverage(coverage):
"""Return a list of glyphs from a coverage."""
if isinstance(coverage, str):
return [coverage]
else:
return coverage.glyphs | a5af639d12fc05ad1fcb4a06f6562782b15e02a1 | 96,142 |
def RotCurve(vel, radius, C=0.3, p=1.35):
"""Create an analytic disk galaxy rotation curve.
Arguments:
vel -- The approximate maximum circular velocity.
radius -- The radius (or radii) at which to calculate the
rotation curve.
Keywords:
C -- Controls the r... | fe0910cb13af9206b0e3cb4e3e48c871a54542a5 | 96,160 |
def pixel_shuffle_1d(x, upscale_factor):
"""
Performs a pixel shuffle on the input signal
:param x: The input tensor to be dimension shuffled
:param upscale_factor: The upsample factor
:return: The shuffled tensor
"""
batch_size, channels, steps = x.size()
channels //= upsc... | 866f82de3b9de9c02d666417785a687e9c3401eb | 96,165 |
from typing import Any
def convert_state_to_str(input_state: Any):
"""
Convert a state built from a nested dictionaries, lists and tuples to a string
:param input_state:
:return:
"""
if isinstance(input_state, dict):
return {param_name: convert_state_to_str(input_state[param_name]) for... | 9b88be6637d7fcb1371c57ef46b2cdd793c28311 | 96,173 |
def predict_cluster(x, centroids):
"""
Given a vector of dimension D and a matrix of centroids of dimension VxD,
return the id of the closest cluster
:params np.array x:
the data to assign
:params np.array centroids:
a matrix of cluster centroids
:returns int:
cluster as... | 3cbd582bd3a947e3d0a11ad05db1ca98547372e5 | 96,175 |
import re
def _parse_code_and_reference_from_pluscode(pluscode):
"""Split a short Plus Code into a Plus Code and reference using regex. For example, "QXGV+XH Denver, CO, USA" will
return ("QXGV+XH", "Denver, CO, USA").
Parameters
----------
pluscode : str
A short Plus Code with a queryabl... | c128c2849187dd05ba8771b4066016fe3f2b2a69 | 96,176 |
def sarea(a, b, c):
"""Calculate the signed area of 3 points."""
return 0.5 * ((b[0]-a[0])*(c[1]-a[1]) - (c[0]-a[0])*(b[1]-a[1])) | a13440ede266b83700b91979a5bba2bcd548eb1a | 96,177 |
from typing import Dict
from typing import Any
def _add_schemas(schema_a: Dict[str, Any],
schema_b: Dict[str, Any]) -> Dict[str, Any]:
"""Add two bigquery schemas together."""
full_schema: Dict[str, Any] = {}
full_schema.update(schema_a)
full_schema.update(schema_b)
return full_schema | c8fb8bf7827217841202abdfca276b6529a047c8 | 96,178 |
def has_magnet(self):
"""Return if any of the Holes have magnets
Parameters
----------
self : LamHole
A LamHole object
Returns
-------
has_magnet : bool
True if any of the Holes have magnets
"""
has_mag = [hole.has_magnet() for hole in self.hole]
return any(has... | 16b52b586b4057d33bb5e636fb41f86403d21852 | 96,182 |
def is_leap_year(year):
"""
Checks if a year is a leap year
:param year: Year
:type year int
:return:
:rtype: bool
"""
return True if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else False | 7eb6e51f5a0091d27d5c2a74a78b258a130cb5fb | 96,188 |
def boxSeries(ax,ser):
"""
This function draws a vertical box and whisker plot
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which bar graph will be drawn
:type ser: pandas Series
:param ser: data to be plotted
:Return:
:type ax: Matplotlib Axis
... | f26c14ca48916e3748651ac2bc6017f1a785d246 | 96,194 |
import json
def writesJson(markov):
"""Encode Model markov in JSON format and write to string."""
serial = dict()
serial['absClasses'] = markov.absClasses
serial['cumDist'] = list(markov.cumDist.flatten())
serial['random'] = markov.random.getstate() # can be serialized
serial['state'] = markov... | 78252b4896b9b401b009a8edae13c5594c50291e | 96,195 |
def get_message(count, name, deleted=True):
"""Generates a message on the number of records inserted or deleted
Args:
count (int): The number of records
name (str): The table name
deleted (bool): The exception handler to wrap the function in
(default: True)
Examples:
... | 5f0fdaad023f6a6b0c55b33e3014e854e3aadd84 | 96,196 |
from typing import Optional
from typing import Union
from typing import Any
def ensure_list(arr: Optional[Union[Any, list[Any]]]) -> Optional[list[Any]]:
"""Wraps single value to list or return list as it is."""
if arr is not None and not isinstance(arr, list):
arr = [arr]
return arr | f94f18150649a2142c3ae61f69316bd982ca3c5a | 96,200 |
import math
def cosine_decay(base_lr, max_iteration, cur_step):
"""cosine learning rate decay
cosine learning rate decay with parameters proposed FixMatch
base_lr * cos( (7\pi cur_step) / (16 max_warmup_iter) )
Parameters
-----
base_lr: float
maximum learning rate
max_warmup_... | 1ab9b7bdddcca8d061c3da8d0bcaa7a8bdb75ad1 | 96,211 |
def get_category_name(id_, categories):
"""
Return category name
"""
if id_ is None or id_ == '':
return None
item = categories[int(id_)]
if item['active'] is True:
return item['name']
return None | ea52af6b6f2bd2ba9662f22d85b9434ef3da7fa8 | 96,213 |
def string_none(value):
"""
Convert the string 'none' to None
"""
is_string_none = not value or value.lower() == 'none'
return None if is_string_none else value | 9988a9b7e6b8a30c318a8926863585f3c2f902f9 | 96,217 |
import csv
def read_strong_csv(strong_meta_csv_path):
"""Read strongly labelled ground truth csv file.
Args:
strong_meta_csv_path: str
Returns:
meta_dict: {'a.wav': [{'onset': 3.0, 'offset': 5.0, 'label': 'Bus'},
{'onset': 4.0, 'offset': 7.0, 'label': 'Train... | 1654f2f716cdd57a506727723238b9c51d71d459 | 96,229 |
import re
def to_snake(s):
"""Convert string to snakes case."""
return re.sub(r'(\s|-)+', '_', s).lower() | a83dc5b505abb67d965c7f8c4b03a422718d7060 | 96,234 |
def clean_url(url):
"""Remove extraneous characters from URL.
Params:
- url: (type: string) URL to clean.
Returns:
- url: (type: string) clean URL.
"""
if url is None:
return None
if '??' in url:
url = url.split('??')[0]
if url.endswith('?'):
url = url[:-... | 41a8a6682d6778c757690cb3a8ad917001aa12e3 | 96,235 |
def deduplicate(constraints):
"""
Return a new ``constraints`` list with exact duplicated constraints removed.
"""
seen = set()
unique = []
for c in constraints:
if c not in seen:
unique.append(c)
seen.add(c)
return unique | cdbd51d99280baf61603e78cf9aea66f9bc0f73e | 96,241 |
def find_markers(body, marker):
"""
Find all the markers in body.
Parameters
----------
body : string
Input string to parse.
marker : character
Search parameter
Returns
-------
list
Input position where the marker was found.
"""
return [i for i, ch i... | a965907060cb762605032b8d5f8de0be63cc6344 | 96,242 |
from typing import Counter
def count_repeated(sequence: list, nth_repeated: int) -> str:
"""
>>> sequence = ['Algorithms','Algorithm','Python','Python','The','Python','The']
>>> nth_repeated = 2
>>> print(count_repeated(sequence, nth_repeated))
The
"""
return "" if nth_repeated < 1 else Co... | efbf614677a3d3f71e724a89e64168525035b001 | 96,244 |
def median(seq):
"""Returns the median of *seq* - the numeric value separating the higher half
of a sample from the lower half. If there is an even number of elements in
*seq*, it returns the mean of the two middle values.
"""
sseq = sorted(seq)
length = len(seq)
if length % 2 == 1:
... | 110625e47c6e06fad48ff286dea7600fa3c30e24 | 96,245 |
def clamp_value(value, max_value=1.0, min_value=0.0):
"""Clamp a value between max and min
Args:
value (float): value to clamp
Kwargs:
max (float): max value
min (float): min value
Returns:
.float
"""
return max(min(value, max_value), min_value) | 8dbc949361a0c7aff5501bf2a9e3f3faa1821c98 | 96,246 |
import base64
def get_real_room_id(room_encoded):
"""Get a real room ID from a base64 encoded room ID"""
# I found this from a discussion with cisco
# roomId car be different is you are comming from a different endpoint (US/EU)
# This is maybe because of something hardcoded in hookbuster (cisco was no... | 56cae81a9ca061da706db56c5c97d5f37410ddc0 | 96,248 |
import hashlib
def UUID(self):
"""
Return the cluster UUID
(SHA1 digest of the cluster.ascii_grid representation).
"""
return hashlib.sha1(self.ascii_grid).hexdigest() | 8dc659c1bbfc97332f80bd187b35c133dc12de50 | 96,252 |
def same(*values):
"""
Check if all values in a sequence are equal.
Returns True on empty sequences.
Example
-------
>>> same(1, 1, 1, 1)
True
>>> same(1, 2, 1)
False
>>> same()
True
"""
if not values:
return True
first, rest = values[0], values[1:]
... | 9fb20aa6095094eb9fb5110dd50e138a355f07a5 | 96,254 |
def reset_dupe_index(df, ind_name):
"""
Reset index and rename duplicate index column
Parameters:
df (pandas DataFrame): DataFrame to reset index
ind_name (str): Name of column to reset
Returns:
df (pandas DataFrame): DataFrame with reset duplicate index
"""
df.rename({ind_name: ind_name+'_back'}, inplace... | 213de79ad7108f759d2bcdf1bfb9eb9d8f193c19 | 96,256 |
def set_ignorables(licensish, ignorables, verbose=False):
"""
Update ``licensish`` Rule or License using the mapping of ``ignorables``
attributes.
Display progress messages if ``verbose`` is True.
"""
for key, value in ignorables.items():
if verbose:
existing = getattr(licen... | ab11d7375f2b3a1b5257f25bba9bfbdeb9a06897 | 96,258 |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such
that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
input_list.sort(reverse=True)
x = 0
for i in range(0, len(input_list), ... | 29a7cf3eec77566d23685d894f4e973e77169f87 | 96,262 |
import re
def get_max_age(headers):
"""Parse the 'max-age' directive from the 'CACHE-CONTROL' header.
Arguments:
headers -- dictionary of HTTP headers
Return the parsed value as an integer, or None if the 'max-age' directive
or the 'CACHE-CONTROL' header couldn't be found, or if the header i... | 7b20fff8fa343c28d82df1791b62edb45fcef0dc | 96,264 |
def rot_word(word):
"""Takes a 4-byte word and performs cyclic permutation.
Aka one-byte left circular shift.
[b0, b1, b2, b3] -> [b1, b2, b3, b0]
"""
return word[[1, 2, 3, 0]] | f89b3499009d29c7e3e9745e30f643b941c77f00 | 96,265 |
import torch
def f1_score_binary(y_true, y_pred):
"""
Binary f1. Same results as sklearn f1 binary.
Args:
y_true: [bs*x*y], binary
y_pred: [bs*x*y], binary
Returns:
f1
"""
intersect = torch.sum(y_true * y_pred) # works because all multiplied by 0 gets 0
denominat... | 5856fc12197ba54bafc51d17a3467ad0760dcfb5 | 96,266 |
def get_session(monitored_sess):
""" Get Session object from MonitoredTrainingSession.
"""
session = monitored_sess
while type(session).__name__ != 'Session':
session = session._sess
return session | a377a2aeeed1cc7f625f49693adc6b1b6ee203cf | 96,268 |
from datetime import datetime
def utc_timestamp(hours_since_first_epoch):
"""Construct a timestamp of the format "%Y-%m-%d %H:%M:%S"
for the given epoch.
Arguments:
hours_since_first_epoch (int):
Epoch for reftime
Returns:
ts (str)
Timestamp of the format "%Y-... | e82f7b7ee6f2b0d694cac6e77842e112f25c9f79 | 96,269 |
def get_object_range(page, page_size):
""" Get the range of expected object ids given a page and page size.
This will take into account the max_id of the sample data. Currently 5.
"""
max_id = 5
start = min((page - 1) * page_size, max_id)
end = min(start + page_size, max_id + 1)
return list... | 36d65c05361d6818ffabad9690f1d531f371a0d8 | 96,270 |
def get_content_iter_with_chunk_size(content, chunk_size=1024):
"""
Return iterator for the provided content which will return chunks of the specified size.
For performance reasons, larger chunks should be used with very large content to speed up the
tests (since in some cases each iteration may result... | c1550aef62e58b459feb66bde6c2a506e5de31be | 96,273 |
def _invalid_particle_errmsg(argument, mass_numb=None, Z=None):
"""
Return an appropriate error message for an
`~plasmapy.utils.InvalidParticleError`.
"""
errmsg = f"The argument {repr(argument)} "
if mass_numb is not None or Z is not None:
errmsg += "with "
if mass_numb is not None:... | 28866a72a25c79b966ef787e290ab83571f82ef8 | 96,275 |
def _verify_encodings(encodings):
"""Checks the encoding to ensure proper format"""
if encodings is not None:
if not isinstance(encodings, (list, tuple)):
return encodings,
return tuple(encodings)
return encodings | 26b7c16c850e90b16a7aee528ee35c74cfedd230 | 96,276 |
import hashlib
def digest_check(file_path):
"""
Generate hash digest for a file
:param file_path:
:return:
"""
h = hashlib.blake2b()
with open(file_path, "rb") as fh:
for chunk in iter(lambda: fh.read(4096), b""):
h.update(chunk)
return h.hexdigest() | d965aeccb4578011831ec00ed93193b2f52355a4 | 96,277 |
def convert_config_description_dict(configs, for_docs=False):
"""
Recursively converts a documented list of dictionary configurations into a dictionary with the
default values loaded.
Expects a list of the form:
.. code-block:: python
[
{
"key": "config_name",... | 16ceb60faad3a964d447404acf2eabd24056147b | 96,278 |
import re
def delete_comments(file_content):
"""Removes all comments from the given string.
:param str file_content: file content
:return str: same content without comments
"""
string_temp = re.sub(r'--.*\n', '', file_content) # Removing comments
string_temp = re.sub(r'\n+', ' ', string_temp... | b89cfb4dc884fea93c59c23e2da4f2d8c4b79fe7 | 96,280 |
def get_corr_hex(num):
"""
Gets correspondence between a number
and an hexadecimal string
Parameters
-------------
num
Number
Returns
-------------
hex_string
Hexadecimal string
"""
if num < 10:
return str(int(num))
elif num < 11:
return ... | d7842f54dda04903f09aade6c5adaee4be310bc3 | 96,284 |
def entry_compare(x, y):
"""Comparison function for two StandardEntries.
This function establishes a global order by sorting on the
(timestamp, id) tuple.
"""
assert x and y
if x.timestamp == y.timestamp:
return x.id - y.id
else:
return x.timestamp - y.timestamp | 112c91fca55a822cdffce187e5979a9c3abda8bb | 96,286 |
def can_topic(user):
"""Checks if a user can generate a topic"""
return user.permissions['perm_topic'] | 43070a62e806ea314b0ba938283b8b9fc3a55609 | 96,287 |
def pmt_in_module_id(pmt_index):
"""Returns the pmt number within a
module given the 0-indexed pmt number"""
return pmt_index%19 | 41250ca2eed93a2bc51f4654d324379b22b70ba5 | 96,295 |
def count_frequency(word_list):
"""
Counts frequency of each word and returns
a dictionary which maps the word to their frequency
"""
D = {}
for new_word in word_list:
if new_word in D:
D[new_word] = D[new_word] + 1
else:
D[new_word] = 1
return D | 55f237a2b899f2e2358bec071a10ae3418fd97fc | 96,296 |
def _dj(scalararray):
"""Return the difference scalararray(j+1) - scalararray(j)
A priori, for internal use only.
Parameters
----------
scalararray : xarray.DataArray
xarray that should be differentiated.
Returns
-------
dj : xarray.DataArray
xarray of difference, defin... | 274ca1aad19ea8a918393148d2b660ddb3d2ba59 | 96,299 |
def nop(format_chained=True, chained=None, chained_status=None):
"""
This function just returns the chained value. It is a nop/no operation.
This can be useful if you want to do a pipe_on_true to filter out
False values -- you can pipe_on_true to process.nop, and stick a
returner on the nop operati... | 526816e43d02df8639f824960186ca4d3620b23c | 96,304 |
def square(side):
"""Calculate area of square."""
return side * side | b71cae20b7a140d6a265d0575c715f22ebae6af3 | 96,305 |
def get_scale(f_min, f_max, q_min, q_max):
"""Get quantize scaling factor. """
return (q_max - q_min) / (f_max - f_min) | 0f48cc32c21b2efe9355124e162f2dd2abfa3d58 | 96,312 |
def capitalize(text):
"""
Returns a capitalized string. Note that this differs
from python's str.capitalize()/title() methods for
cases like "fooBarBaz"
"""
if text == '':
return ''
return text[0].upper() + text[1:] | 5bedc2be5fa3aa7659d8bc9521c0082db2cccc43 | 96,317 |
from typing import List
from typing import Union
def get_notes_in_scale(all_notes: List[Union[float, int, str]],
scale: int) -> List[Union[float, int, str]]:
"""Return a list of all notes in scale, where the notes are chosen from a
set of all twelve possible semitones.
Args:
... | b1e8b1ef57eaea003dfb68381061d1bdac8aa537 | 96,319 |
def sub_when_empty(string: str, empty_str: str = "-") -> str:
"""
Just returns a given string if it is not empty. If it is empty though, a default
string is returned instead.
Parameters
----------
string
The string to check if it is empty or not
empty_str
The string to be re... | 7b7309d58214734cea9bc70c76fe54785761ce50 | 96,325 |
import warnings
def to_completions_display_value(x):
"""Convert user input to value of ``$COMPLETIONS_DISPLAY``"""
x = str(x).lower()
if x in {"none", "false"}:
x = "none"
elif x in {"multi", "true"}:
x = "multi"
elif x in {"single", "readline"}:
pass
else:
msg ... | cb075b573aa703b356d6a8cb533748f552dd6412 | 96,327 |
def get_cluster_id_by_name(cluster_list, cluster_name):
"""Helper function to retrieve the ID and output bucket of a cluster by
name."""
cluster = [c for c in cluster_list if c['clusterName'] == cluster_name][0]
return cluster['clusterUuid'], cluster['config']['configBucket'] | b255ea9973557d8152952690aa5342c5532d2a1e | 96,329 |
def is_other_or_unknown(df):
"""Return if vehicle is other/unknown, per NHTSA convention."""
yr = df['YEAR']
body = df['BODY_TYP']
tow_veh = df['TOW_VEH']
return ((yr.between(1975, 1981) & (body.between(35, 42) |
body.isin([44, 45, 99]))) |
(yr.bet... | a14ce7414adf17e46410c0ad4a7681b57f32f7f4 | 96,334 |
def add(x,y):
"""
Returns the sum x+y
This works on any types that support addition (numbers, strings, etc.)
Parameter x: The first value to add
Precondition: x supports addition and x is same type as y
Parameter x: The second value to add
Precondition: x supports addition and... | 8c34207fec2fdc1b042cc5b7999eaef4e5beb1db | 96,336 |
import typing
def is_generic_list(tp):
"""Returns true if `tp` is a parameterized typing.List value."""
return tp not in (list, typing.List) and getattr(tp, "__origin__", None) in (
list,
typing.List,
) | 19ad96a2e2325ffb7179d7e30687694c627029dc | 96,343 |
def ct_satratburden(Inom,VArat=None,ANSIv=None,ALF=20,):
"""
ct_satratburden Function
A function to determine the Saturation at rated burden.
Parameters
----------
Inom: float
Nominal Current
VArat: float, optional, exclusive
The apparent ... | 248cf7473113f342451f60b9d0c5a676ab1bf5bb | 96,344 |
def pack_context_with_message(ctxt, msg):
"""Pack context into msg."""
if isinstance(ctxt, dict):
context_d = ctxt
else:
context_d = ctxt.to_dict()
return {'message': msg, 'context': context_d} | 8968712c9e10aa6b016bd322d505c3cb5be288a2 | 96,346 |
def get_structure_from_gismo_cluster(gismo, cluster, depth=3):
"""
Builds a tree structure from Gismo clusterising method.
Args:
gismo: A `Gismo` object used for the clustering.
cluster: The root Cluster of the tree, returned by `gismo.get_clustered_features`
Returns:
A `dict` re... | e746f59c19f3d0c2b0ef514c737f6096853f516a | 96,348 |
def array_sign(nums: list[int]) -> int:
"""Computes the sign of the product of a given array of numbers
Args:
nums:
Returns:
1 if the product of nums is positive.
-1 if the product of nums is negative.
0 if the product of nums is equal to 0.
Examples:
>>> array... | a65d37b4f0d8977e67ff5b4f906363a5d781cfbb | 96,352 |
import time
def timeStamp_s_convert_time(time_num):
"""
输入秒级时间戳的时间,转出正常格式的时间
如: 1595498910 -> 2020-07-23 18:08:30
param time_num: ms时间戳
return: 正常格式的时间
"""
time_array = time.localtime(int(time_num))
normal_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
# print(normal_time)
... | a9c7fc53607e2eb90a876212a90a9c9663ad070c | 96,354 |
from typing import Optional
import re
def extract_url(text: str) -> Optional[str]:
"""Extracts url from text
Parameters
----------
text : str
String from which url to be extracted.
Returns
-------
Optional[str]
Return url if present in the given string.
"""
regex_... | 43df2bc3b0db5ec91e6e1313978dabe7e00da13f | 96,357 |
import inspect
import re
def getSubjDict(in_content, examPat):
"""
Finds the subjects and subject code from in_content.
Returns a dict with the subject code as key and subject as
value.
"""
err_msg = ("%s expected argument of type 'list','str'; %s,%s given" %
(inspect.stack()[... | b523c496cd7f634b6dc5c2f14439e5c4b1ea2e56 | 96,359 |
def node_def_add_node(sss):
""" add node{} to a string of an op.
Args:
sss: original string of an op.
Returns:
new string with node{} added.
"""
sss = sss.replace('\n', '\n\t')
sss = "node {\n\t" + sss
sss = sss[0:len(sss)-1] + '}\n'
return sss | 656073db73db94f3942b4ac8d25b4f3fbf3e7356 | 96,360 |
def centroid2d(points):
"""
Calculate the centroid of a finite set of 2D points.
:param points: the set of points as an iterable. Each point is assumed to
be a sequence of (at least) two real numbers ``[x, y]``, respectively
the x (first element) and y coordinate (second element).
:retu... | 0c314f6047468241978a6ec3547eb2ceb3837626 | 96,364 |
def to_timestamp(datetime_timestamp):
"""Convert UTC datetime to microsecond timestamp used by Hangouts."""
return int(datetime_timestamp.timestamp() * 1000000) | c69cb6a4147db25861d700c56d9327960353a87a | 96,365 |
def mean(data):
"""Calculates the mean value from |data|."""
return float(sum(data)) / len(data) | c9b208e11abe46fb16900d957bb3c5428a6b9cfd | 96,368 |
def _encode_int(n: int) -> bytes:
"""
Encodes an integer into a bencoded string.
"""
return f"i{n}e".encode("utf-8") | e891cc0fcbf018521d6f4f41fbfcf8930195e8ff | 96,370 |
import pkg_resources
def load_description(package: str, path: str, filename: str):
"""
This function loads a static description file.
Parameters:
package (str): Package name where file is located in
path (str): Path within the package.
filename (str): Name of file to load.
Re... | 1a4afa40366d054f8ebf491c301c5cbc2a3a694a | 96,371 |
import operator
def sort_posts(posts, *keys):
"""Sort posts by a given predicate. Helper function for templates.
If a key starts with '-', it is sorted in descending order.
Usage examples::
sort_posts(timeline, 'title', 'date')
sort_posts(timeline, 'author', '-section_name')
"""
... | 2b2e5447694c88324b780e3ab5aa9f7747147851 | 96,382 |
import json
def read_data_json(file_name: str):
"""Read imported snippet data from json file
Parameters
----------
file_name : str
Name of internal `.json` file with snippet info.
Returns
-------
snippets : List[Snippet]
List of snippet objects: dicts with prefix, body, m... | 494ba50ab67aac120966791797ca9a17842ff1c0 | 96,386 |
def pivotDiagnostic(df, index, columns, values):
"""Attempt to pivot the DataFrame. If there are duplicate
entries in the pivot table then return a df of duplicates
Parameters
----------
df : pd.DataFrame
index : str
columns : str or list
values : str or list
Returns
-------
... | e6c8d4ec5d26b37259df8263da8f056e5e583c93 | 96,389 |
def latest_price(prices):
""" returns the latest (i.e., last) price in a list of prices.
input: prices is a list of 1 or more numbers.
"""
return prices[-1] | a4e75253c8ddef9bb0629360e55b816adbcbd0f5 | 96,392 |
def knowledge_area_abbreviation(ka):
"""
Given an ACM knowledge area, split it up by its Abbreviation (eg. AL)
and its Title (eg. Algorithms and Complexity). This is done by
isolating the location of the abbreviation in the title string (where
the first left paren occurs) and only including the subs... | ebe4204b63fe9568ddc82b0656d425ff7277de67 | 96,393 |
import re
def prep_seq(seq):
"""
Adding spaces between AAs and replace rare AA [UZOB] to X.
ref: https://huggingface.co/Rostlab/prot_bert.
Args
seq: a string of AA sequence.
Returns:
String representing the input sequence where U,Z,O and B has been replaced by X.
"""
seq_... | 8e66177ae399053d312d5b0c3aa6c6bf9ef174a2 | 96,395 |
from datetime import datetime
import pytz
def _format_datetime(utc_float):
"""Method ingests a utc timestamp float and formats it into
a datetime format that is prefered by the DRF framework.
It performs conversions through datetime and pytz.
Args:
utc (float): A unix timestamp.
... | bad92d7a3297224b42bb8afe3898612b84b5aa79 | 96,398 |
def with_suffix(number, base=1000):
"""Convert number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.39M"""
mapping = {base**3: "G", base**2: "M", base: "k"}
for bucket, suffix in mapping.items():
if number > 0.999 * bucket:
return "{:.3g}{}".format(number / bucket, suffix)... | 0a0e346778cd7e6ffa3c6222b351b75ec2ce20a6 | 96,403 |
def disable_option(value):
"""Converts a boolean option to a CMake ON/OFF switch"""
return 'OFF' if value else 'ON' | 177be0fc943351a830edf27c1e12b3430af68239 | 96,404 |
def check_auth(username, password):
""" Check if given username/password are valid """
return username == 'admin' and password == 'test' | d9610eb534843e4129aab7c136437455dc55fd14 | 96,406 |
import attr
def filter_unknown_attributes(cls, package_data):
"""
Given a mapping of package_data, return a new mapping of package_data that
contains only known `cls` attr class attributes.
"""
known_fields = attr.fields_dict(cls)
return {
key: value for key, value in package_data.ite... | 1260d4e60dc4bf27ebbe6eda9197f22cdf67e3d9 | 96,408 |
def frequency_to_band(freq):
"""
band code from frequency in GHz
"""
if freq < 1: return None
elif freq >= 1 and freq < 2: return "L"
elif freq >= 2 and freq < 4: return "S"
elif freq >= 4 and freq < 8: return "C"
elif freq >= 8 and freq < 12: return "X"
elif fr... | ab4e17bae39b4f21dc1d6e4b1007eaf43864501d | 96,409 |
def date_to_cisco_date(date):
"""
This function gets a date and returns it according to the standard of Cisco Email security.
Args:
date: YYYY-MM-DD hh:mm:ss.
Returns:
The date according to the standard of Cisco Email security - YYYY-MM-DDThh:mm:ss.000Z.
"""
return date.replace('... | 3e6a5f38fe1cfaae726213895f2436e4067eb8de | 96,411 |
def open_file_and_get_lines(file):
"""
Returns the file as a list of lines
"""
with open(file, 'r') as f:
try:
lines = f.readlines()
return lines
except UnicodeDecodeError as error:
print("\n\n")
print(error)
print("Weird char in ", file)
print("\n")
return None; | 552e8e6b649759f0128436e23f2831cfb7cd66ba | 96,412 |
def ReadLLVMChecksums(f):
"""Reads checksums from a text file, produced by WriteLLVMChecksums.
Returns:
A dict, mapping from project name to project checksum.
"""
checksums = {}
while True:
line = f.readline()
if line == "":
break
checksum, proj = line.split()
checksums[proj] = chec... | 4f7b9fd1375c25655eb9059fb8607a1f42fd1f48 | 96,416 |
def jaccard_score(y_pred, y_true):
"""Compute Jaccard Score (= Intersection / Union) between a prediction and its ground truth
:param y_pred: prediction
:param y_true: ground truth
:return: Jaccard score value
"""
intersection = (y_pred * y_true).sum()
union = y_pred.sum() + y_true.sum() - i... | 518db134089da2c8e1dd4a2ec0cefa82e5ffd1c1 | 96,420 |
import re
def remove_hyphenation(string):
"""
Removes hyphenation from the input string
"""
#regex = r"(\w+)(- )(\w+)?"
#return re.sub(regex,r"\1\3",string)
try:
regex = r"(\w+)(- )(\w+)?"
return re.sub(regex,r"\1\3",string)
except Exception as e:
return string | ef947bfce9d3f8ce513baacb6846af3541bebe74 | 96,423 |
def nonEmpty(v):
"""
If v is a container (tuple, list or dictionary), return None if it is empty,
otherwise return v itself.
"""
if isinstance(v,(tuple,list,dict)):
if len(v) == 0: return None
return v | bc5d0ec29d8986d1cfb03e663a3024d40637ac3e | 96,424 |
import re
def add_hit_symbols(text, search, symbol='_'):
"""Use re to find matches and insert hit symbols."""
find = f'({search})'
replace = f'{symbol}\g<1>{symbol}'
return re.sub(find, replace, text) | 18058fd3ed89899eae9d32bcbaee0e6ff474094b | 96,432 |
def classPath2modulePath(stringIn):
"""
if it get: specification.ocni.AvailabilityInterval
it will return: specification.ocni
"""
tem = stringIn.split('.')
res = ''
#l'indice pour la boucle while
i = 0
while i < len(tem) - 1:
res += tem[i]
if i < len(tem) - 2:
... | a80795241123d9e4cb059a7052284ea90f614997 | 96,435 |
import threading
def spawn_later(seconds, function, *args, **kwargs):
"""Spawns a daemonized thread after `seconds.`"""
thread = threading.Timer(seconds, function, args, kwargs)
thread.daemon = True
thread.start()
return thread | d49fe46b86151442c72435045b87df9fdb465ad9 | 96,438 |
def add_single_letter_words(words):
"""Add single letter words to the dictionary.
"""
words['']=None
words['i']=None
words['a']=None
return words | 0c2eacaf97dddbe0d8106bf38d6b6a7e86f31fa5 | 96,443 |
def standardise(X, how='range=2', mean=None, std=None, midrange=None,
ptp=None):
"""Standardise.
ftp://ftp.sas.com/pub/neural/FAQ2.html#A_std_in
Parameters
----------
X : matrix
Each sample is in range [0, 1]
how : str, {'range=2', 'std=1'}
'range=2' sets midrang... | b7b8dde69e8203b918f23fd80c5f5fcc3bd55941 | 96,450 |
def _parse_settings_args(args: list):
""" Parse settings command args and get settings option and signal. """
if not args:
return 'common', [] # 'common' is the option, when user does not use any option.
else:
try:
option, signal, *_ = args
except ValueError:
... | 1fdd3e124d7a7b9a456533593b9768814c6553c1 | 96,453 |
def cels_from_fahr(fahr):
"""Convert a temperature in Fahrenheit to
Celsius and return the Celsius temperature.
"""
cels = (fahr - 32) * 5 / 9
return cels | 9ad242078e6092e10a81d78e7de4add3224e4d2f | 96,455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.