content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _iget(key, lookup_dict):
"""
Case-insensitive search for `key` within keys of `lookup_dict`.
"""
for k, v in lookup_dict.items():
if k.lower() == key.lower():
return v
return None | f53e1723a015e5ac0a1244ee0821d56f4a26c5d8 | 576,508 |
def url_replace_pop(request, field, value):
"""Remove a value from the GET dictionary and return it urlencoded."""
dict_ = request.GET.copy()
list_ = dict_.pop(field)
dict_.setlist(field, [v for v in list_ if v != value])
return dict_.urlencode() | 071d71d3808f6dbb8781476accd996192a3af148 | 576,513 |
def create_room_pairs(session_capacities):
"""
Creates all size 2 combinations of rooms.
Parameters:
session_capacities: a dictionary mapping each session name to a positive
integer for how many students can fit in that session
Returns a set of room pairings (tuples).
... | 24fb9354b7ba0265a321c58e514da8c7729a91f1 | 576,516 |
def get_commerce_url(root_url: str) -> str:
"""Get the Kamereon base commerce url."""
return f"{root_url}/commerce/v1" | 3e56bfcb13d476a2668d756673bf7c0425404baa | 576,517 |
def __is_member_of(self, group, recursive=False):
"""Check whether this object is a member of the given group"""
return group in self.get_memberOfs(recursive=recursive) | 966a1280166be3ff0064415559398543fad1c66f | 576,518 |
def get_submission_type(submission_type):
"""
A single dispatch to return a Submission Type from either an instance or
the name
"""
return submission_type | 9d1c114e1c80f4cdb44bdfd4cec89346c56063d3 | 576,520 |
def f1_from_confusion(tp , fp , fn , tn):
""" Compute the F1 score from a confusion matrix.
Parameters
----------
tp : int
Number of true positives
fp : int
Number of false positives
fn : int
Number of false negatives
tn : int
Numbe... | c8e0c4e0edd775d10e4f053ccbcbc520d75acc10 | 576,521 |
def _combined_model_name(org, repo=None):
"""Return the name of the combined model for a repo or organization.
If repo is specified looks for a repo specific model. If repo is
none we return an org wide model.
Args:
org: Name of the org.
repo: (Optional) The name of the repo
"""
if repo:
retur... | 64f47c77e41f31695b6fbda47d38cfa0478a3d12 | 576,522 |
def simple_hexdump(bytes_, row_size=16):
"""Convert a bytestring into hex characters.
This is called "simple" because it doesn't print the index in the leftmost
column or the printable characters in the rightmost column (as the CLI
``hexdump -C`` does).
Args:
bytes_ (bytes): The bytestring... | 83ee6bd8b73fe36eeb9c029ea692142b9a896f33 | 576,523 |
def pow_xin(p, i, n):
"""
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import pow_xin
>>> R, x, y = ring('x, y', QQ)
>>> p = x**QQ(2,5) + x + x**QQ(2,3)
>>> index = p.ring.gens.index(x)
>>> pow_xin(p, index, 15)
x**15 ... | 9b50988f13047861eb6eb50ff8b05639f1486671 | 576,525 |
from typing import Callable
from typing import List
from typing import Tuple
from typing import Type
import inspect
def parameters(method: Callable) -> List[Tuple[str, Type]]:
"""
Inspect the desired method extracting a list of parameters needed
to execute it.
Parameters:
method: The type.Cal... | 7cb60dfb1ec9bc0adb4d5753699e9d955d3a9516 | 576,527 |
from typing import Iterable
def is_iterable(x):
"""
Utility function to check if input can be iterated over (that is, if input is a List, np.array, pd.date_range, etc.)
"""
return isinstance(x, Iterable) | 18faf7f952e39e03e4398dd16ff3c5780421e96b | 576,531 |
def get_heads(heads, r, c):
"""
Extracts simulated head values at specified row, column.
Parameters
----------
heads : 2D array OR 3D array
numpy array of shape nlay by n locations (2D) OR complete heads array
of the model for one time (3D)
r : 1D array-like of ints, of length n... | 61d244083c985d581acdb94d092a19b4d82448b5 | 576,533 |
import torch
def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5"""
return torch.tensor([
[-1., 0., 2., 0., -1.],
[-4., 0., 8., 0., -4.],
[-6., 0., 12., 0., -6.],
[-4., 0., 8., 0., -4.],
[-1., 0., 2., 0.... | ff1c81fe0425596b2c3e35c122da6d6c91f00216 | 576,534 |
import ctypes
def generate_hash (element, hash_engine):
"""
Generate hash of a ctypes element
:param element: Element to hash
:param hash_engine: Hashing engine to utilize
:return Buffer with digest
"""
# Copy the element instance to a bytearray. Passing element directly to the hash API... | e51b5041f6c1c8d46335dc2789089e1ca4c9f927 | 576,537 |
def taber(msg, size):
""" Function which tabulates strings.
Example
-------
>>> taber(msg='Example string', size=42)
'Example string '
"""
return str(msg) + (size - len(str(msg)))*' ' | 83b1d6a0c319fee4f1186cb07a665deba1f4778d | 576,541 |
def harass_metric(damage_taken_p1: float, damage_taken_p2: float) -> float:
"""
A metric that looks at damage taken as a fraction of total damage dealt in lane.
Formula: 1 - (damage_taken_p1/(damage_taken_p1 + damage_taken_p2))
:param damage_taken_p1: Damage taken by player one
:param damage_taken... | 8e732b52388d842d397bfa389fb7fb1a9dbd0f38 | 576,543 |
def load_file_into_list(file_path: str) -> list[str]:
"""It reads the URLs of our monitoring targets (Webs to monitor)
from a config file and returns them as a `list` object.
Args:
file_path (str): Full path to config file with the URLs
Returns:
list[str]: URLs loaded from config file
... | 5cb8a1f9466358b58eed398ede29bf29650685f8 | 576,549 |
import torch
def calc_batch_loss_cross_ent_list(model, batch):
"""
List-wise Cross-Entropy loss, described in "Baoxu Shi, Tim Weninger, ProjE: Embedding Projection for KnowledgeGraph Completion, AAAi 2017".
:param model: A PathL model.
:param batch: An iterable with node pairs.
:return: List-wise... | c59e636869541cca172754e2f37e590a1b4e8dc5 | 576,551 |
from typing import Tuple
from typing import List
def count_nb_occurrences(tokens: Tuple[str, ...], all_tokens: List[str]):
"""Count the number of occurences of the sequence of tokens in the
full list all_tokens"""
nb_occurrences = 0
for i in range(len(all_tokens)):
for k in range(len(tokens))... | 316758b850111c6139f2c84febb62112b8a577dc | 576,553 |
import hashlib
def passwordToHash(passwd:str) -> str:
"""
returns any string into a sha256 encoded password hash
"""
passwd = str(passwd)
passwd = hashlib.sha256(passwd.encode("UTF-8")).hexdigest()
return passwd | 40dd97306901f724c169048f1185e88f16dea91a | 576,555 |
def midval(arr):
"""
Calculate the middle value vector.
Args:
arr (np.ndarray): The input N-dim array
Returns:
arr (np.ndarray): The output (N-1)-dim array
Examples:
>>> midval(np.array([0, 1, 2, 3, 4]))
array([0.5, 1.5, 2.5, 3.5])
"""
return (arr[1:] - arr... | 0b0ae5abbc8ee480f195ba19f8168dad6388da94 | 576,558 |
def get_raw_smn1_cn(full_length_cn, smn1_fraction):
"""
Return the raw SMN1 CN by muliplying full-length SMN CN and SMN1 fraction.
"""
lcount = []
for site_fraction in smn1_fraction:
lcount.append(round(full_length_cn * site_fraction, 2))
return lcount | 18e6ce9176f4e0a43f22cba624491c82ee9b3e3f | 576,560 |
from random import randint
def deal_community(deck, cardCount):
"""choose cards randomly from deck"""
deckCopy = deck[:]
dealt = []
for i in range(cardCount):
val = randint(0, len(deckCopy)-1)
dealt.append(deckCopy[val])
del deckCopy[val]
return dealt | 93286355fe3d78fdb1c5eb4ec9f3dd6f4f47ba1f | 576,561 |
def _trim(_vector):
"""Return _vector with all trailing zeros removed."""
if not _vector or len(_vector) == 1:
return _vector
ind = len(_vector)
while _vector[ind - 1] == 0 and ind > 0:
ind -= 1
return _vector[:ind] | 3ecdc9381a1db8b6053afc2adbf4ecdc0a09d8c1 | 576,562 |
def convertToLabelFormat(oldLabels):
""" Convert the label form with sets to label form with lists.
For later functions, the labels are expected to be of the form:
{
'label': [nodeIndex]
}
that is, a dictionary whose keys are the labels and values are the
index number of the nodes that ... | 8eb4e1ca1574233601f0480e19beab42d663a219 | 576,563 |
def lcm(a: int, b: int) -> int:
"""Return a LCM (Lowest Common Multiple) of given two integers
>>> lcm(3, 10)
30
>>> lcm(42, 63)
126
>>> lcm(40, 80)
80
>>> lcm(-20, 30)
60
"""
g = min(abs(a), abs(b))
while g >= 1:
if a % g == 0 and b % g == 0:
break
... | 7039abbcb72edcd01fda66e1d04444821e1a50d6 | 576,564 |
def generic_cmp(x,y):
"""
Compare x and y and return -1, 0, or 1.
This is similar to x.__cmp__(y), but works even in some cases
when a .__cmp__ method isn't defined.
"""
if x<y:
return -1
elif x==y:
return 0
return 1 | 7442a537afb5226dcdf4d1b0939ee352c1801a95 | 576,565 |
def hparams_frame_size(hparams):
"""Find the frame size of the input conditioned on the input type."""
if hparams.spec_type == 'raw':
return hparams.spec_hop_length
return hparams.spec_n_bins | f27cef6e4a6d652704786a43e1d0c2a919f013f9 | 576,567 |
def clamp(value, low, high):
"""Clamp value between low and high (inclusive).
Args:
value (int, float): The value.
low (int, float): Lower bound.
high (int, float): Upper bound.
Returns
int, float: Value such that low <= value <= high.
"""
return max(low, min(value,... | 9a6a3ccd9e1fe2c8f76376ec54eae6f5ba4c1033 | 576,575 |
import importlib
def load_config(config_name):
"""Load config from corresponding configs.<config_name> module."""
return importlib.import_module('configs.%s' % config_name).config | 96707903ee844572d137f3641ff922b647cd2026 | 576,576 |
def is_order_family(listrow):
"""
Check if a CSV row contains only the order and family data
:param listrow: CSV row
:return: True if the row contains only the order and family data
"""
assert type(listrow) is list
return listrow[1] == '' | 6223dd6e6595aaab403c3398aee829ec38e61d16 | 576,577 |
import torch
def get_available_models_names(force_reload=False):
"""Gives list of model names available on torch hub
Return:
models (list[string]): list of pytorch/vision models available
on pytorch hub
"""
return torch.hub.list('pytorch/vision', force_reload=f... | 978cf411ec6f5f88eedf6e42d140f74da67b7fd7 | 576,579 |
import string
def make_name_valid(name):
"""Make a string into a valid Python variable name."""
if not name:
return None
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
name = str().join([c for c in name if c in valid_chars])
if name and not name[0].isalpha():
name = ... | d50343481b34276621e6c5e98075b0a451b1cc3b | 576,580 |
import re
def extract_vars(template):
""" Extract variables from template. Variables are enclosed in
double curly braces.
"""
keys = []
for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template):
keys.append(match.groups()[0])
return keys | e1ca5d6ff440b543664f88fe967e6bdd72879365 | 576,586 |
from typing import Iterable
def ip_groups_to_ranges(ip_range_groups: Iterable):
"""Collapse ip groups to ranges.
Args:
ip_range_groups (Iterable): a list of lists containing connected IPs
Returns:
Set. a set of Ranges.
"""
ip_ranges = set()
for group in ip_range_groups:
... | b326ef7386989742700c35f572ef951961a9ce48 | 576,588 |
import requests
def makeRadioURL(date):
"""Gets the URL for an episode from its date."""
urlbase = "https://media.focusonthefamily.com/fotf/mp3/aio/"
urltip = "aio_{0}.mp3".format(date)
# Sometimes the URLS contain aio and sometimes aiow. I don't see a pattern so I try both.
if requests.get(urlba... | 38747fe0d4c9e47a489c5ccdd1d3889bf3a51cf5 | 576,592 |
def _LDMODULEVERSION(target, source, env, for_signature):
"""
Return "." + version if it's set, otherwise just a blank
"""
value = env.subst('$LDMODULEVERSION', target=target, source=source)
# print("_has_LDMODULEVERSION:%s"%value)
if value:
return "."+value
else:
return "" | 9b3bb78e65014f73be483d67572d5a70a3efef75 | 576,598 |
import torch
def sample_correlated_gaussian(rho=0.5, dim=20, batch_size=128, cubic=None):
"""Generate samples from a correlated Gaussian distribution."""
x, eps = torch.chunk(torch.randn(batch_size, 2 * dim), 2, dim=1)
y = rho * x + torch.sqrt(torch.tensor(1. - rho**2).float()) * eps
if cubic is not ... | d5ee5c4b4ce7c64a875101d5ac5c32008a78cd67 | 576,602 |
def summarize_packet(pkt):
"""
Summarizes a packet into a human-legible string. Five key fields are represented
in the summary - source/destination IP, source/destination MAC address, source/
destination TCP/UDP port, and the transport protocol in use (such as TCP/UDP).
If any of the five key fields... | 7e56e3c36b84ff43c7e00cf6e082e062f29d0d11 | 576,603 |
from typing import List
from typing import Any
def _get_avg(values: List[Any]):
"""Get average value of a list.
Args:
values: A list of values.
Returns:
The average value in the list.
"""
return sum(values) / len(values) | 6f22e60ecf6af15d5e0b885925b913673b33ee1d | 576,606 |
def anal_dboc(data_dict):
""" Returns the DBOC value """
return data_dict["dboc"]["dboc"] | 0907a17c32e53707c2ae5094e642205087826787 | 576,607 |
import socket
def get_celery_shutdown_attachment(**kwargs):
"""Create the slack message attachment for celery shutdown."""
if kwargs["show_celery_hostname"]:
message = "_Celery is shutting down on {}._".format(
socket.gethostname()
)
else:
message = "_Celery is shutting... | e53b93009138c989c75af0231fb5c9511ab4a842 | 576,611 |
from typing import Tuple
def reverse_causal(effective_kernel_size: int) -> Tuple[int, int]:
"""Post-padding such that output has no dependence on the past."""
return (0, effective_kernel_size - 1) | df182b5c710fbb143c83d7c80a718ed9d1db9c9d | 576,612 |
def sanitize_string(string):
"""Sanitizes a string for it to be between U+0000 and U+FFFF"""
if string:
return ''.join(c for c in string if ord(c) <= 0xFFFF).strip() | 4f01448b06180403dedbb787aaa0e072315ebb54 | 576,613 |
import binascii
def b2a_hex(s):
"""Convert binary to hexadecimal"""
# For completeness
return binascii.b2a_hex(s) | 67ea83f8dee243552793eabf72df4d60538df885 | 576,614 |
def split_s3_full_path(s3_path):
"""
Split "s3://foo/bar/baz" into "foo" and "bar/baz"
"""
bucket_name_and_directories = s3_path.split('//')[1]
bucket_name, *directories = bucket_name_and_directories.split('/')
directory_path = '/'.join(directories)
return bucket_name, directory_path | 79fffeab1759a8ca6a69dbd111f9be2977c882cc | 576,622 |
def is_null(content, nulls=None, blanks_as_nulls=False):
"""Determines whether or not content can be converted into a null
Args:
content (scalar): the content to analyze
nulls (Seq[str]): Values to consider null.
blanks_as_nulls (bool): Treat empty strings as null (default: False).
... | 92c21ba790ce407ec318fcd9d4a8b1faf620f024 | 576,623 |
def format_BUILD_MAP_UNPACK_WITH_CALL(oparg):
"""The lowest byte of oparg is the count of mappings, the relative
position of the corresponding callable f is encoded in the second byte
of oparg."""
rel_func_pos, count = divmod(oparg, 256)
return ("%d mappings, function at %d" % (count, count + rel_fu... | b7176dcdd412aa64cf73e055cc9f0f3efce3f6bf | 576,628 |
def extract_data(spark):
"""Load data from Parquet file format.
:param spark: Spark session object.
:return: Spark DataFrame.
"""
df = (
spark
.read
.parquet('tests/test_data/employees'))
return df | 709467817c05eec4ddc6e75f95257d7266c2e5e1 | 576,633 |
def get_version_from_image_tag(image_tag: str) -> str:
"""Returns the image version from an image tag"""
return image_tag.split(":")[1] | 8f36fb398c7e8959a101f8f5e2e545796eaa8cb2 | 576,636 |
import string
def as_variable_name(x):
"""
Convert a string to a legal python variable name
Parameters
----------
x : str
A string to (possibly) rename
Returns
-------
variable_name : str
A legal Python variable name
"""
allowed = string.ascii_letters + string... | 50473c167f3b663365ee0cb6f2cd84a8b375167c | 576,637 |
def str_to_bool(s):
"""
Basic converter for Python boolean values written as a str.
:param s: The value to convert.
:return: The boolean value of the given string.
@raises: ValueError if the string value cannot be converted.
"""
if s == 'True':
return True
elif s == 'False':
... | ce5573e1fe0a0c2135052aa4ce99b5093b97d01d | 576,640 |
def promote_to_double_precision(array):
"""Convert an array to real or complex double precision."""
if array.dtype == "float32":
return array.astype("float64", copy=False)
if array.dtype == "complex64":
return array.astype("complex128", copy=False)
return array | 7ed0352e1ebabaefc33c91a6b80132a4d4042d5a | 576,642 |
from typing import Optional
import re
def to_azure_friendly_string(x: Optional[str]) -> Optional[str]:
"""
Given a string, ensure it can be used in Azure by replacing everything apart from a-z, A-Z, 0-9, or _ with _,
and replace multiple _ with a single _.
:param x: Optional string to be converted.
... | 66089c49c8b8bfb61b0b52a9035da07f431339aa | 576,643 |
def hamming(num):
"""Returns the nth hamming number"""
h = [1] * num
x2, x3, x5 = 2,3,5
i = j = k = 0
for n in range(1, num):
h[n] = min(x2, x3, x5)
if x2 == h[n]:
i += 1
x2 = 2 * h[i]
if x3 == h[n]:
j += 1
x3 = 3 * h[j]
... | dc1d668cf312f758fa484bae3740346947d10b20 | 576,645 |
def fact(n):
""" calculate n! iteratively """
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result | 3ac1ab84016b31261e1cef01b223dc14a2c6265d | 576,647 |
def _get_coefficients(crossection, cn):
"""
Calculates the extinction, scattering or absorbtion coefficient
Parameters
----------
crosssection: float
Units are um^2
cn: float
Particle concentration in cc^-1
Returns
--------
coef... | 6418b0c91f614880a039e9840a8961266056ca50 | 576,649 |
import random
def rand(ctx, plan, candidates):
"""Random choose one"""
return random.choice(candidates) | d5bb5a85da0d3478cda6a63226be9e3a0039f071 | 576,654 |
def readfile(fname):
"""Helper function to read a file (binary).
:param fname: file name to be read
:returns: contents of file
"""
with open(fname, "rb") as stream:
return stream.read() | 7bb9d72f3d761e33d2772bb87376738fea84304f | 576,660 |
def getattr_unwrapped(env, attr):
"""Get attribute attr from env, or one of the nested environments.
Args:
- env(gym.Wrapper or gym.Env): a (possibly wrapped) environment.
- attr: name of the attribute
Returns:
env.attr, if present, otherwise env.unwrapped.attr and so on recursivel... | 87942b5b7b35ed90c6f43ce5c3e22e595ff757ef | 576,661 |
from typing import Pattern
import re
def compile_regex(pattern: str) -> Pattern[str]:
"""Compile a regex."""
return re.compile(pattern) | 1ddb1f2cdc8975e30904b89ab7b1104f854940a7 | 576,662 |
def df_swap_cols(df, columns):
"""Swaps the column by column name or index
columns: Can be a tuple of column indexes or names
ex. (2, -1) or ('a', 'b')
"""
first, second = columns
cols = list(df.columns)
if type(first) is int:
cols[first], cols[second] = cols[second], cols[first]
... | d6f3c9b38f2046e9d9633374e0165a54eb528508 | 576,663 |
def set_timezone_offset(request):
"""Sets the timezone offset."""
request.session['timezone'] = request.form.get('offset', type=int)
return 'OKAY' | a4e24dc255f4658e61a0efb0251646a46e8a2234 | 576,664 |
def dos_integral(E,dos,m=0):
"""
A function to compute the integral of an input phonon DOS (*dos*) with the 3/8 Simpson method.
*m* is the moment of the integral, if :math:`m>0` different moments can be calculated.
For example, with :math:`m=0` (default) it returns the number of modes from the dos,
... | d940e28542e1e13a0deedfd785f7ccd3cf4336c0 | 576,667 |
def fen_expand(fen):
"""Expand fen chessboard to include *every* square.
Use '.' for empty squares
fen="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"
"""
s=""
for c in fen:
if c=="/": continue
if c in "0123456789":
s+="."*int(c)
else:
... | 6fe1e5159d947c40ead27c374c8fe208b73339c9 | 576,668 |
def __check_duplicate_args(lf_graph: dict) -> bool:
""" Check for duplicated predicate arguments in logical form graph.
Parameters:
lf_graph: dict of id (int) and graph (LogicalFormGraph)
Returns:
true if logical form graph has no predicate w/ duplicate arguments
"""
graph = lf_graph['gra... | 1a1c9eb0ecccf092128ec7431285af6faa39904a | 576,670 |
def get_subject_list(manifest_df, subject_list_file):
"""
If a list of subject is provided then use that, else collect all unique
subject ids from the s3 spreadsheet and use that instead
:param manifest_df: pandas dataframe created from the s3 csv
:param subject_list_file: cli path to file containin... | 51c0dcdb2954482ca60f80ce91154eb67c9fe2e7 | 576,671 |
def show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)):
"""Visualize the detection results on the image.
Args:
model (nn.Module): The loaded detector.
img (str or np.ndarray): Image filename or loaded image.
result (tuple[list] or list): The detection result, can be... | 871f6bfaabdc342b8cb120d722176f67fcf98830 | 576,675 |
def generate_block_number(
chapter_number, heading_number, subheading_number, paragraph_number
):
"""
Returns chapter_number.subheading_number.paragraph_number if chapter_number is
available, or heading_number.subheading_number.paragraph_number if not.
Doesn't include any part that isn't available.... | 4d7b2000a37b17710cb8758728b60b9a6bb09797 | 576,676 |
def tidy_to_dict(df, key='name', value='value', keys_exclude=None,
cast_value=float):
"""Convert a tidy DataFrame into a dictionary.
This function converts two columns from an input tidy (or long-form)
DataFrame into a dictionary. A typical use-case is passing
parameters stored in tidy... | 2e51ba04d80ed905012f7d404fb640fcfe6c937a | 576,680 |
import textwrap
def justify(s, max_length, left_pad=0):
"""
Re-wrap the string s so that each line is no more than max_length
characters long, padding all lines but the first on the left with the
string left_pad.
"""
txt = textwrap.wrap(s, width=max_length, subsequent_indent=" " * left_pad)
... | c61f534a7106eb0aa3a67be47dd4cb29749c1342 | 576,682 |
def ns_interp(text, ns=None):
"""
Triple strings (e.g. foo:Bar) have to be expanded because SPARQL queries
can't handle the subject of a triple being
d1resolve:doi:10.6073/AA/knb-lter-pie.77.3
but can handle
<https://cn.dataone.org/cn/v1/resolve/doi:10.6073/AA/knb-lter-pie.77.3>
... | ff39bf68fa077e8fe884e35291b0d0762e0515e7 | 576,686 |
def option(name, short, type, default, descr=''):
"""Declare a new option for the given cli-command.
:param name: option name
:param short: option short name
:param type: option type
:param default: option default value
:param descr: option description
:return: a new decorator that will dec... | cac33f786238fe6d53d0f57230ed98e2ddc811c8 | 576,689 |
def pade(T, n=1):
"""
Create a linear system that approximates a delay.
Return the numerator and denominator coefficients of the Pade approximation.
Parameters
----------
T : number
time delay
n : integer
order of approximation
Returns
------- ... | f0499b675e00c178d7aeaddd66b30f157eda4d2e | 576,692 |
def call(func, *args, **kwargs):
"""
Call `func` with positional arguments `args` and keyword arguments `kwargs`.
Parameters
----------
func : callable
Function to call when the operation is executed.
args : list
Sequence of positional arguments passed to `func`.
kwargs : di... | 783015546bd82b86d600cfdea412a3923c84c0b4 | 576,693 |
def _get_col(column, prefix):
"""
Get the column name after removing the prefix.
"""
# Check if the column is starting with the given prefix
if column.startswith(prefix):
# Return the column name after removing the prefix
return column[len(prefix):]
# Return None, if the column d... | 4d24cfed30a8d7c1bae0cd315501300998215ba3 | 576,694 |
def req_input(prompt, options):
"""
Query for an aswer to prompt message until the user provides a
valid input (i.e., answer is in options).
Parameters
----------
prompt: String
Prompt text for input()'s argument.
options: List
List of options to accept. Elements in list are casted into string... | cdeae8665f8984ed4779f257214ecb7901098d39 | 576,696 |
import math
def pyramid_sizes(init_size, a_output_size, b_output_size):
"""
Determine appropriate resolutions for all levels of an image pyramid.
@param init_size Max width/height of the lowest resolution of the pyramid.
@param a_output_size Size (w,h) of the exemplar image (ai) of the highest
re... | 12de5b7bddf50a056fbcbb78d7aa1334d7033172 | 576,698 |
def ps1_stack_path(proj_cell, sky_cell, band):
"""
construct relative path for a PS1 stack image by projection cell,
sky cell, and band.
"""
proj_cell = str(proj_cell).zfill(4)
sky_cell = str(sky_cell).zfill(3)
return (
f"/rings.v3.skycell/{proj_cell}/{sky_cell}/"
f"rings.v3.... | 0d2d5d348fda6da1775bda48c62e279246283086 | 576,701 |
def sort_array_with_id(arr):
"""
Sort array ascending and keep track of ids.
:param arr: array with values
:return: array with tuples (id, val)
"""
tuple_arr = [(id, arr[id]) for id in range(len(arr))]
return sorted(tuple_arr, key=lambda t: t[1]) | bc89b88a495ba705726954223986d2e7d3a9920e | 576,703 |
def fix_initial_data(initial, initial_data_keymap):
"""
Take a dict like this as `initial`:
{ 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
and a dict like this as `initial_data_keymap`:
{ 'newkey1': ['key1', 'key2'], 'newkey2': ['key3']}
and remap the initial dict to have this form:
{ 'n... | 5f72592e460c058c7a3ffee6f1e2d5957c5fe7b1 | 576,708 |
def binary_search(list, value):
"""This function takes a list as input and a value to find.Then it searches for that value using binary search"""
left, right = 0, len(list)-1
while left <= right:
mid = (left+right)//2
if list[mid] == value:
return mid #Returning the index
... | 7d5365311550a0d480d7c2b88b2c1271a6cd9d81 | 576,712 |
def image_index(pathname):
"""
Helper function for submission. Takes the path to an image, e.g.
"./image_folder/15.jpg", and returns the image name, in this example
"15.jpg".
"""
return pathname[pathname.rfind("/")+1:] | ce2c047ee8367cf6457ca9316eb8487314101c28 | 576,714 |
def change_of_basis(X, W):
"""
Projects data onto new basis W.
Args:
X (numpy array of floats) : Data matrix each column corresponding to a
different random variable
W (numpy array of floats) : new orthonormal basis columns correspond to
bas... | 53378b90d76d2cbca513cab873d829592abda92f | 576,715 |
def task_to_string(df_task, sep=',', sep_points=" "):
"""
Returns a string from a task DataFrame
with sep=',' and sep_points=" "
like:
'5.9840002060,44.0549011230,1500.0 6.0107221603,44.0150871277,1500.0 6.3285999298,44.0536003113,1600.0 6.5361166000,44.2888832092,2700.0 6.3811173439,44.4144477844,2... | 814f979be242ea066a90cc1864da4007966ab934 | 576,716 |
def strxor(x: bytes, y: bytes) -> bytes:
"""XOR two byte strings"""
return bytes([ix ^ iy for ix, iy in zip(x, y)]) | 8f35061f731072950df2d0e24b9d2e56fcd5a192 | 576,717 |
def parse_start_step(stdout_file):
""" Parses the starting_step of the clip from the stdout.txt of the job's run. """
with open(stdout_file, 'r') as f:
for line in f.readlines():
if 'FLAGS.start_step' in line:
return int(line.split()[-1])
# Otherwise return a default star... | 6359aefb8255ad75f10fb432b9f604b67aa75105 | 576,718 |
def find_first_level_groups_span(string, enclosing):
"""Return a list of pairs (start, end) for the groups delimited by the given
enclosing characters.
This does not return nested groups, ie: '(ab(c)(d))' will return a single group
containing the whole string.
>>> find_first_level_groups_span('abcd... | a8df59582821acf6348398d6eaeb8184f30afbaf | 576,720 |
def decode_resouce_type(id: str) -> int:
"""Decode a number between 0 and 0xFFFF from a 4-character hex string"""
return int(id, 16) | 64a1d319a95dd497721635c6cbb4c806ac172245 | 576,722 |
import torch
def draw_r(ps:int, ci: int, N: int, X):
"""
Draws a simple random multi-channel probing matrix.
Arguments:
ps (int): Number of probing vectors.
ci (int): Number of input channels.
N (int): Number of pixels.
X (tensor): Input tensor (untouched, used for device ... | e27c082b4439b0889308c7d0c9f363638ef1c8ba | 576,723 |
from typing import Callable
def get_internal_prop_name(instance: object, func: Callable) -> str:
"""
Build the name to use for storing the value of a property of an object.
The internal property name is based on the function name (i.e. the decorated property name).
If the object has an instance or cl... | df60616dca8e69c8526a2fe1cc84496cc206692e | 576,724 |
def __swap_cols(M, m, n):
"""swap column m and n of matrix M"""
N = M.copy()
N[:, m] = M[:, n]
N[:, n] = M[:, m]
return N | d66f571ab68581977032c0c79368278794a0150a | 576,725 |
def modular_multiply(A, B, C):
"""Finds `(A * B) mod C`
This is equivalent to:
`(A mod C * B mod C) mod C`
https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/modular-multiplication
https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a... | f6694e45d7ed7fd6de417e809dc04abda4308d5b | 576,726 |
def update_chunk_id_maps(chunk_id_maps, cont_id_map):
"""
Creates a new chunkwise id map as if cont_id_map is applied after each
chunk id map
"""
for mapping in chunk_id_maps.flat:
for (k, v) in mapping.items():
mapping[k] = cont_id_map.get(v, v)
return chunk_id_maps | 6a2a5f72fd410c661befd73bf9fbeae79bfcbe78 | 576,727 |
def parse_job_titles(str):
"""Parse job titles from sql into a list."""
str1 = str.replace('{', '').replace('}', '').replace('"', '')
job_list = str1.split(',')
return job_list | 69b849352599c9e92e85a38b0b26183bea346942 | 576,728 |
import torch
def reparameterize(mu, logvar):
"""Sample from N(mu, var)
Parameters
----------
mu : :obj:`torch.Tensor`
vector of mean parameters
logvar : :obj:`torch.Tensor`
vector of log variances; only mean field approximation is currently implemented
Returns
-------
... | 4f3f4e7490b9b9f5b3f90251f52d1c8ebf316a14 | 576,732 |
from typing import Any
def s3_read_text(s3: Any, bucket: str, key: str) -> str:
"""
Reads the contents of a S3 bucket/key.
"""
obj = s3.Object(bucket_name=bucket, key=key)
return obj.get()["Body"].read() | 1dc5598e5e9896c5104fb7e21bc1b71e98e5647b | 576,733 |
import pathlib
def get_files_for_extension(directory: pathlib.Path, extension: str):
"""Cached file list.
Parameters
----------
directory
The directory within which to search
extension
The extension to recursively search for
"""
return [
str(item.relative_to(direc... | b5665cd2ee5c7e4627559b079ad62af0d73dd549 | 576,738 |
def sort_iati_element(element, schema_subdict):
"""
Sort the given elements children according to the order of schema_subdict.
"""
def sort(x):
try:
return list(schema_subdict.keys()).index(x.tag)
except ValueError:
# make sure non schema elements go to the end
... | 8e286f7693a48015ec5066751ea378f46076fbad | 576,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.