content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _crosscorr(x, y, **kwargs):
"""
Returns the crosscorrelation sequence between two ndarrays.
This is performed by calling fftconvolve on x, y[::-1]
Parameters
x: ndarray
y: ndarray
axis: time axis
all_lags: {True/False}
whether to return all nonzero lags, or to clip the length ... | 850c1c7ded00968de889589758558397fa06ffc0 | 43,641 |
def get_qword(*args):
"""get_qword(ea_t ea) -> ulonglong"""
return _idaapi.get_qword(*args) | 28659cfc633d6e9170dc0fda2005ed967973108c | 43,642 |
def wine_key(wine_cate=DEFAULT_WINE_CAT):
"""Constructs a Datastore key for a Wine entity."""
return ndb.Key('WineCategory', wine_cate.lower()) | 13d94093f7d160747a7cf222b284295b569be04e | 43,643 |
import torch
from typing import Tuple
def run_knn(
train_features: torch.Tensor,
train_targets: torch.Tensor,
test_features: torch.Tensor,
test_targets: torch.Tensor,
k: int,
T: float,
distance_fx: str,
) -> Tuple[float]:
"""Runs offline knn on a train and a test dataset.
Args:
... | 0157714d48cdf3f3ee797666e367898023fc7e34 | 43,644 |
def create_account(create_account_key):
"""Checks the key. If valid, displays the create account page."""
user_id = auth_utils.check_create_account_key(create_account_key)
if user_id is None:
flask.current_app.logger.warn(
f'Invalid create_account_key: {create_account_key}')
flas... | c921336f59009fb2684f671dc8b409b8ae268e1f | 43,645 |
def determine_inventory_groups(vm_directory):
"""
Determine the Ansible inventory groups that this
VM is a member of.
:param vm_directory: directory to issue `vagrant' commands in
:return: list of Ansible inventory groups
"""
group_config = join(vm_directory, 'groups.yml')
if exists(gro... | c2d36706d7d6860c5c623c81a949926e26b345f2 | 43,646 |
def data_value(value: str) -> float:
"""Convert to a float; some trigger values are strings, rather than
numbers (ex. indicating the letter); convert these to 1.0."""
if value:
try:
return float(value)
except ValueError:
return 1.0
else:
# empty string
... | 5d46ab47c3d8c0ebb9a5f9b06d7bb6b2a47a0939 | 43,647 |
def _monom(n):
"""
monomial in `eta` variables from the number `n` encoding it
"""
v = []
i = 0
while n:
if n % 2:
v.append(i)
n = n >> 1
i += 1
return v | 42621ddbca95b8fc3ca3d7eea51cc1dc97524758 | 43,648 |
def _combin(points,n, max_dist):
"""Summary
Args:
points (lst): sample points
n (integer): number of samples
max_dist (float): maximum permissible distance
Returns:
lst: List of tuples containing the permissible pairs
"""
dist =[]
p = 0
for i in range(0,n):
for j in range((i+1),n):
... | 086a53d697de499489809b6ba1d75651789c5d75 | 43,649 |
import multiprocessing
def concat(rlist, method="gridded", enhance=False, parallel=False):
"""
This function takes a list of Radial objects or radial file paths and
combines them along the time dimension using xarrays built-in concatenation
routines.
Args:
rlist (list):
list o... | c511817e7cb7f215b2dfba284bed4b7db9903781 | 43,651 |
from datetime import datetime
def month_counter(fm, LAST_DAY_OF_TRAIN_PRD=(2015, 10, 31)):
"""Calculate number of months (i.e. month boundaries) between the first
month of train period and the end month of validation period.
Parameters:
-----------
fm : datetime
First day of first month o... | e10e6be0eb8a7762b182d073ca85ed1b97f831d3 | 43,652 |
def warning(message):
"""Log helper function for jinja2 tasks"""
l.warning(message)
return "" | b8f6545518409952446a5be4192727a039e4ab72 | 43,653 |
def demean(X, weights=None, return_mean=False, inplace=False):
"""Remove weighted mean over rows (samples).
Parameters
----------
X : array, shape=(n_samples, n_channels[, n_trials])
Data.
weights : array, shape=(n_samples)
return_mean : bool
If True, also return signal mean (de... | 7fec1b9cafed481219b1deb8848483cd050d4852 | 43,654 |
def tupleize(series_dict, tuple_name="obs"):
"""Creates an observation list of NamedTuples."""
kwarg_dict = {}
keys = [i for i in series_dict.keys()]
for i in range(0, len(keys)):
kwarg_dict[keys[i]] = list(series_dict[keys[i]])
return create_observation_list(tuple_name, **kwarg_dict) | df1fa1e8d52d13a580f1b5db2bac2ab9ea72e2e1 | 43,656 |
def get_background(background_img=BACKGROUND):
"""Start with a background image"""
_img = Image.open(background_img)
# Check the width and height of the image
assert _img.size == (400, 300), "Background must be 400x300"
# Convert the image to use a white / black / red colour palette
# hopefull... | ce4fc6e897cbfd6cb8ad821adb26f53fe4b2b4b6 | 43,658 |
def ZonalComputeUrl(project, zone, collection, name):
"""Generate zone compute URL."""
return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', name]) | d04730be1fa84a2e130ed3613c6389b1605f9376 | 43,659 |
import glob, time, gc
def check_repo(repo_dir = '../../models/all_from_repository',
model_suffix = 'xml',
invalid_if_warnings = False,
compare=True):
"""
Validate every model in the CellML repository, and return a list
of invalid models.
If compare is ... | c47bc626766806d175585e3ee9ebf767da87f0e9 | 43,660 |
def build_get_long_valid_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an ... | bc601a1107941e59285bb32800a08f3a8c4f2152 | 43,661 |
def fromKML(filename=None, data=None, crs=None, encoding=None):
""" Create a list of Features from a KML file. Return a python tuple
with ee.Feature inside. This is due to failing when attempting to create a
FeatureCollection (Broken Pipe ERROR) out of the list. You can try creating
it yourself casting ... | afff38a3dbdf439da32a87fc1f1a9d4d9bd38d5c | 43,662 |
import threading
def run_as_thread(fn):
"""Run function as thread"""
@wraps(fn)
def run(*args, **kwargs):
t = threading.Thread(target=fn, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return t
return run | a388ca61b041e04d5e487654a1a3b738dd3da06b | 43,663 |
def to_unicode(obj):
"""Convert object to unicode"""
if isinstance(obj, bytes):
return obj.decode('utf-8', 'ignore')
return str(obj) | e54c02e04109b8a99a7eb4e357e95ead89166137 | 43,664 |
def positive_definite_matrix(N, M=None):
"""return an array of M positive-definite matrices with shape (N, N)"""
if M is None:
V = np.random.random((N, N))
V = np.dot(V, V.T)
else:
V = np.random.random((M, N, N))
for i in range(M):
V[i] = np.dot(V[i], V[i].T)
... | f458397ee3b993ca6bc05d937512c777b0861051 | 43,665 |
def get_pretrained_model_last_layer_change(model_name, n_classes):
"""
:param model_name: ๋ถ๋ฌ์ฌ pre trained ๋ชจ๋ธ ์ด๋ฆ
:param n_classes: ๋ถ๋ฅํ ํด๋์ค ๊ฐฏ์
:return: ๋ถ๋ฌ์จ ๋ชจ๋ธ์ ๋ถ๋ฅ๊ธฐ ๋ถ๋ถ๋ง ์์ ํ ๊ตฌ์กฐ๋ฅผ ๋ฆฌํดํ๋ค.
"""
if model_name == 'alexnet':
model = models.alexnet(pretrained=True)
# Freeze early layers
... | 31da5843c16a80e5bb9959d10021929d82946bb0 | 43,667 |
from io import StringIO
def download_image(ses, url):
""" dumps image into memory """
dl = ses.get(url, stream=True)
img = StringIO()
img.write(dl.content)
img.seek(0) # rewind to beginning
return img | 7a02dd3161b3e010addd79a33b7b1ae9dbaf91c7 | 43,668 |
import _locale
def get_masteries():
"""
https://developer.riotgames.com/api/methods#!/968/3317
Returns:
MasteryList: all the masteries
"""
request = "{version}/masteries".format(version=cassiopeia.dto.requests.api_versions["staticdata"])
params = {"tags": "all"}
if _locale:
... | 7b55c40c20eaa1a08df65b82f51bbbf3803f8cc7 | 43,669 |
def get_shape(x, unknown_dim_size=1):
"""
Extract shape from onnxruntime input.
Replace unknown dimension by default with 1.
Parameters
----------
x: onnxruntime.capi.onnxruntime_pybind11_state.NodeArg
unknown_dim_size: int
Default: 1
"""
shape = x.shape
# replace unknow... | 1c719191922a46b948fb567273e3a5152769e190 | 43,670 |
import csv
def process_fields(filename, field_occurrences=defaultdict(list)):
"""
Create a dict of fieldnames and the forms that include them.
Args:
filename (str): CSV
field_occurrences (dict): A dictionary of the sort we'll be returning.
Returns:
A dictionary of lists, inde... | 721e5fadfb6f9cc8dbd6f8ec71ebe6b9bbc50c7f | 43,671 |
def _check_typeclass_signature(
typeclass_signature: CallableType,
instance_signature: CallableType,
ctx: MethodContext,
) -> bool:
"""
Checks that instance signature is compatible with.
We use contravariant on arguments and covariant on return type logic here.
What does this mean?
Let... | 577622e18dc3ce110f2ed2a465ac5788cec2d4ab | 43,673 |
def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion."""
q = np.array(quaternion, dtype=np.float64, copy=True)
n = np.dot(q, q)
if n < _EPS:
return np.identity(4)
q *= np.sqrt(2.0 / n)
q = np.outer(q, q)
return np.array([
[1.0-q[2, 2]-q[3, ... | 3ca7b86e6c00530b9b9ad9c640dd97061fd59993 | 43,674 |
def rhex_str(length: int = 4) -> str:
"""Returns a random hex string
:param length: length of random bytes to turn into hex (defaults to 4)
:type length: int
:return: random hexadecimal string
:rtype: str
.. doctest:: python
>>> a = rhex_str()
>>> isinstance(a, str)
Tr... | a6fd1c4ba1fc485b0cdce7607b971ee1ca53e484 | 43,675 |
def word_tally(word_list):
"""
Compiles a dictionary of words. Keys are the word, values are the number of occurrences
of this word in the page.
:param word_list: list
List of words
:return: dictionary
Dict of words: total
"""
word_dict = {}
for word in word_list:
... | 5ab1f7ac4c8a72cd5ceda2a391cef8a62a1ec34f | 43,677 |
from typing import Dict
from typing import Tuple
from typing import Sequence
from typing import Any
def _matches(
spec: jax.core.Jaxpr,
capture_literals: Dict[int, str],
graph: jax.core.Jaxpr,
eqn_idx: int,
) -> Tuple[
bool, int, Sequence[jax.core.Var], Sequence[jax.core.Var], Dict[str, Any]]:
"... | 828851c9426b858d9d99836d9607af23e6ee433b | 43,678 |
def complexity(sequence, N):
"""
Computes the Shannon Entropy of a given sequence of a
biopolymer with `N` possible residues. See (Wooton, 1993)
for more.
:param sequence: the nucleotide or protein sequence whose Shannon Entropy is to calculated.
:param N: the total number of possible residues ... | 38f41c7673010297019cec8616571f6e83aac5a2 | 43,680 |
from typing import Tuple
import copy
import re
def regex_replace_nb(
notebook: NotebookNode, replacements: Tuple[Tuple[str, str, str]]
) -> NotebookNode:
"""Return a new notebook with string regex replacements applied.
:param replacements: list of (path, regex, replacement), path is a string of form
... | ad9f8230aa8ea2bf3c1c6580bf051416fbf790a2 | 43,681 |
import typing
from typing import Any
from typing import Dict
def Axis(
color: str = None,
grid_color: str = None,
grid_lines: str = "solid",
label: str = "",
label_color: str = None,
label_location: str = "middle",
label_offset: str = None,
num_ticks: int = None,
offset: dict = {},... | eb9f5a75cb445a8bd01dcc8c7dce63944b463a07 | 43,682 |
def _kuhn_munkres_algorithm(true_lab, pred_lab):
"""
Private function that implements the Hungarian method. It selects the best label permutation of the
classification output that minimizes the
misclassification error when compared to the clustering labels.
:param true_lab: clustering algorithm lab... | a3abe2c6e47625963e2d243dc58c508b8de10f24 | 43,683 |
import json
async def load_test_system(dir_name, config: dict = None) -> Gateway:
"""Create a system state from a packet log (using an optional configuration)."""
try:
with open(f"{dir_name}/config.json") as f:
kwargs = json.load(f)
except FileNotFoundError:
kwargs = {"config"... | 25d1ff1e1bfefef6bc045eed4c004e65fe90e59a | 43,684 |
def score_segment(previous_segment, current_segment, next_segment):
"""
Computing scores for current segment based on it's surroundings
:param previous_segment: segment tuple for previous segment defined as (start, end, gt_event_index, det_event_index, standard_score) or None
:param current_segment: seg... | aa971050dbba9aa5211611c9356ff1adfb768173 | 43,685 |
def te(s, assignment=None):
"""Convenience wrapper around the meta-language parser."""
return meta.TypedExpr.factory(s, assignment=assignment) | 1f4fdb5b4c05b15f4428012c7b4ffe3b759dca06 | 43,686 |
def edit_party(party_id):
"""Edit a specific party."""
details = request.get_json()
party = PartyModels().update_party(party_id, details)
if party:
n_success = make_response(jsonify({
"status" : 200,
"mg": "party updated successfully",
"data": party
}... | 619c90c5a868a9d54b1f9cd72edb296e27cec0ac | 43,687 |
from typing import Dict
from typing import Tuple
def get_usage_summary(client: AmberApi, site_id: str, start_date: date, end_date: date) -> \
Dict[Tuple[date, str], UsageSummary]:
"""
Uses the given client to query the Amber API for all Usage data for the specified Site between the given dates
(bo... | 0313d4c77c26d9e638123722da80776644c19b62 | 43,688 |
def validate_dataset(data):
"""
Validate user given dataset
"""
if data:
if not isinstance(data, DatasetAutoFolds):
raise ValidationError(
"data",
'Unknown data format. Must be and instance of "DatasetAutoFolds". Got "%s"'
% type(data),... | 58273c47114ff88facf8c27d4f9e7b5ef6a70d44 | 43,690 |
def Linear_Regularized(
name,
alphas=(0.1, 1.0, 10.0),
folds=10,
):
"""
FUNCTION:
Used to create a Linear Machine Learning model with built-in
regularization and cross validation
PARAMS:
name: str
A name/alias given to the model by the user
al... | c6cba028f21516f35f4d3a212f64b053c7ce061a | 43,691 |
import string
import random
def randomString(url, stringLength=30):
"""Generate a random string of fixed length """
Letters = string.ascii_lowercase + string.ascii_uppercase + string.digits
url_split = url.split(".")
format_ = url_split[-1]
s = ''.join(random.choice(Letters) for i in range(string... | bf3787fdb22ba1f06d9f2e5626282125040a81c5 | 43,692 |
def calculateExtents(values):
"""
Calculate the maximum and minimum for each coordinate x, y, and z
Return the max's and min's as:
[x_min, x_max, y_min, y_max, z_min, z_max]
"""
x_min = 0; x_max = 1
y_min = 0; y_max = 1
z_min = 0; z_max = 2
if values:
initial_value = values[... | 47378c219d5d9b49db7196ed999ba906a2add4d7 | 43,693 |
from typing import Counter
def split_data_train_dev_test(df):
"""
Creating sets for model building and testing. Steps:
1. Training set (70%) - for building the model
2. Development set a.k.a. hold-out set (15%) - for optimizing model parameters
3. Test set (15%) - For testing the performance of th... | 384419c869e707b47ed283e86e22bcfa0c39f733 | 43,694 |
def start_simulate(pid):
"""Function for starting Circle-Map simulate"""
print("\nRunning Circle-Map Simulate\n")
sp.call("mkdir temp_files_%s" % pid, shell=True)
return(pid) | 53044da24a8b24915e07bd8e86bfe40c90cc371d | 43,695 |
def _prep_inputs_(X, y, theta, penalty=None, center=None):
"""Internal use function to simplify variable transformations for regression. This function is used on the inputs
to ensure they are the proper shapes
Parameters
----------
X : ndarray
y : ndarray
theta : ndarray
penalty : ndarr... | 4fc747fc97176d612e7f39d28bd60e8fdc6c6579 | 43,696 |
def place_order(order='buy', price=0.0, currency='krw', coin_amount=0.0,
order_type='limit'):
"""Place an order.
:param order: ``buy`` | ``sell``
:param price: Price per BTC
:param currency: KRW by default. I wouldn't assume Korbit supports any other
currency at the... | 3a00844950b302928eaa7963ef236135e3a9256e | 43,697 |
def shuffle_isis(spiketrain, n=1, decimals=None):
"""
Generates surrogates of a neo.SpikeTrain object by inter-spike-interval
(ISI) shuffling.
The surrogates are obtained by randomly sorting the ISIs of the given input
:attr:`spiketrain`. This generates independent `SpikeTrain` object(s) with
s... | 113d4688755cc799fbddc85dc105f287db6df0c9 | 43,698 |
def is_installed(name):
"""
Check if a CRUX package is installed.
"""
with settings(hide("running", "stdout", "stderr", "warnings"), warn_only=True):
res = run("prt-get listinst {}".format(name))
return res.succeeded | 1a0ae488c7efd2536fbf1ebcb768235482bcdf6d | 43,699 |
def parse_conf_node(env: BuildEnvironment, text: str, node: addnodes.desc_signature) -> str:
"""
Parse the content of a :rst:dir:`conf` directive.
:param env: The Sphinx build environment.
:param text: The content of the directive.
:param node: The docutils node class.
"""
args = text.split('^')
name = args[0... | 0653104b79df7d732813c6801e7c81d9aaa21b25 | 43,700 |
def are_postgres_migrations_uptodate() -> bool:
"""
Check that all migrations that the running version of the code knows about
have been applied.
Returns `True` if so, `False` otherwise
"""
try:
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
plan = executor.migratio... | e3f06d27ef3fa63b9ec1ea91f08f98523b896108 | 43,701 |
def step_lr(lr_max, epoch, num_epochs):
"""Step Scheduler"""
ratio = epoch/float(num_epochs)
if ratio < 0.3: return lr_max
elif ratio < 0.6: return lr_max*0.2
elif ratio <0.8: return lr_max*0.2*0.2
else: return lr_max*0.2*0.2*0.2 | 515bb508a207f6aa5175756b49f26d53de9d7f6f | 43,702 |
def insertion_sort_counting(A):
"""
Instrumented Insertion Sort to return #swaps, #compares.
"""
N = len(A)
num_swap = num_compare = 0
for i in range(N):
for j in range(i, 0, -1):
num_compare += 1
if A[j - 1] <= A[j]:
break
num_swap += ... | 260f9a404f80ba93ce12cfcac9aade2135c61097 | 43,703 |
def dir_basename_from_pid(pid,j):
""" Mapping article id from metadata to its location in the arxiv S3 tarbals.
Returns dir/basename without extention and without full qualified path.
It also ignores version because there is no version in the tarbals.
I understand they have the updated version in the tarball... | 38a955b2caecfa65f8aad44c8cf0fbc21d0b3709 | 43,704 |
def heat_capacity(T, E, S):
"""
This function calculates the heat capacity by taking in
the temperature 'T', energy 'E', and entropy 'S' as NumPy
arrays. The number 'Num' is also necessary to complete
the heat capacity calculation.
"""
C = np.zeros_like(T)
for i in range... | 679f4ce34e50684665c0aa0e24fb4721fa81093a | 43,705 |
def retrieve_penalties_from_event_data(period_events):
"""
Retrieves penalty information from game event data.
"""
penalties_dict = dict()
for period in period_events:
events = period_events[period]
for event in events:
if event['type'] != 'penalty':
cont... | 03bdc9a35b82db2e6e0a71529bb39a8425e816a1 | 43,706 |
def create_folder_old(cluster_indices, yhat):
"""
:param cluster_indices: function that returns numpy array of list of indices where the specified label = actual label (yhat)
:param yhat: numpy array of class labels
:return: list of list of indices by label
"""
folders = [cluster_indices(-1, yha... | 1f6d841d3ac77cabc35991ec5df749f1f14c5702 | 43,707 |
def seconds_to_hours(
move_data, label_time=constants.TIME_TO_PREV, new_label=None, inplace=True
):
"""
Convert values, in seconds, in label_distance column to hours.
Parameters
----------
move_data : pymove.core.MoveDataFrameAbstract subclass.
The input trajectory data
label_time ... | f53e4744f81de69142896b9b360b2588fbe2bba3 | 43,708 |
def numba_hist(samples, bins, range):
"""
Wrapper to optimise numpy's histogram function with numba.
"""
return np.histogram(samples, bins, range) | 329c202fd5e4e26d5a561787fce205dc2000ef71 | 43,709 |
def ortools_wrapper_count_solutions(model,var_array):
"""
ortools_wrapper((model,var_array,print_solution=print_solution,num_sols=0)
This is a simple wrapper for just counting the solutions of a model.
Parameters:
- model : the model
- var_array: the array of arrays of the decision vari... | 637ffd69ebe15497b59e01ae6c7f2c59bc5afcae | 43,711 |
def find_manhattan_distance():
"""
ะะฒะธะณะฐะตะผัั ะธะท ัะพัะบะธ (0,0) ะฒ ัะพะพัะฒะตัััะฒะธะต ัะพ ัะฟะธัะบะพะผ ะธะฝััััะบัะธั:
Nx - ะดะฒะธะณะฐัััั ะฝะฐ North ะฝะฐ x ะบะปะตัะพะบ
Sx - ะดะฒะธะณะฐัััั ะฝะฐ South ะฝะฐ x ะบะปะตัะพะบ
Ex - ะดะฒะธะณะฐัััั ะฝะฐ East ะฝะฐ x ะบะปะตัะพะบ
Wx - ะดะฒะธะณะฐัััั ะฝะฐ West ะฝะฐ x ะบะปะตัะพะบ
Lx - ัะผะตะฝะธัั ะฝะฐะฟัะฐะฒะปะตะฝะธะต ะฒะทะณะปัะดะฐ ะฝะฐ x ะณัะฐะดััะพะฒ ะฒะปะตะฒะพ... | d938875ada591b4d6b62f7b601113bf1bd5752d2 | 43,713 |
def padded_chunks(l, n):
"""Yield successive n-sized chunks from l."""
tl = n
out = []
for i in range(0, len(l), n):
if i + n > len(l):
tl = n - (len(l) - i)
out.append(np.pad(np.array(l[i:]), ((0, tl), (0, 0)), 'constant'))
else:
out.append(np.array(l... | 6a566e0e3319fcd6a9e59e4f25384c037c1f5e12 | 43,715 |
import re
def fix_extension(filename_end):
"""Processes ending section of filename to get extension
Args:
filename_end (str): starting section of filename
Returns:
str: file extension
"""
return_value = filename_end
pattern_string = r".*\.(\w{3})$"
pattern = re.compile(
... | 5317c3c52920d669374ac72cc6cccc70a2740174 | 43,717 |
def rhombus_area(diagonal_1, diagonal_2):
"""Returns the area of a rhombus"""
# You have to code here
# REMEMBER: Tests first!!!
return (diagonal_1 * diagonal_2) / 2 | 1b11e0e250d15198b4275c167ce9aa2302292d67 | 43,718 |
def aes_decrypt(ciphertext, password):
"""
This runs a command equivilent to:
echo $ciphertext | openssl enc -aes-256-cbc -a -A -d -k $password
to produce plaintext.
"""
p0 = Popen(["1", ciphertext], shell=False, stdout=PIPE, executable="echo")
p1 = Popen(["1", "enc", "-aes-256-cbc", "... | 506acab25e87f3a0293d27d4a6037c5fefb59b03 | 43,719 |
def unicode_dict(_dict):
"""
Make sure keys and values of dict is unicode.
"""
r = {}
for k, v in iteritems(_dict):
r[unicode_string(k)] = unicode_obj(v)
return r | a9c43839af61c6868b844a6f6a2f817f4d412867 | 43,720 |
def first(column, ignore_nulls=False):
"""
Returns the first value in a group.
The function by default returns the first values it sees. It will return the first non-null
value it sees when ``ignore_nulls`` is set to true. If all values are null, then null is returned.
"""
return _with_expr(exp... | 96ede0db2851a7f127b0d434b37cb9388f31221a | 43,721 |
def group_configurations_detail_handler(request, course_key_string, group_configuration_id, group_id=None):
"""
JSON API endpoint for manipulating a group configuration via its internal ID.
Used by the Backbone application.
POST or PUT
json: update group configuration based on provided informat... | 39d20002df7f4a21fad2b91c192927a75ff10d20 | 43,722 |
def geodetic2geocentric(h, lat, lon, ellipsoid=None, **kwargs):
"""Convert from geodetic to geocentric coordinates.
The geodetic coordinates refer to the reference ellipsoid
specified by input ellipsoid.
See module docstring for a defintion of the geocentric coordinate system.
Parameters:
... | bace36df42bbcfde0bb83bc7caaee73aa0ea9bdc | 43,723 |
def test_conditional_shared_limits():
"""Test that conditional shared limits work."""
app = Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)
@app.route("/limited")
@limiter.shared_limit("1 per day", "test_scope")
def limited_route():
return "passed"
@app.route("/... | 755a98fa963c30e07853f25198643c9fad3c5b88 | 43,724 |
def _profile_is_configured(profile):
""" Check if given profile is already configured.
Args:
profile (str): Profile to check.
Returns:
bool: Whether the profile was already configured or not.
"""
exit_code, _ = awscli(f"configure list --profile {profile}")
return not exit_code | fe238800c13bee45b2da2fb8fa4b95b63009f04a | 43,725 |
def is_equidistant(energy, tol=1e-08):
"""Returns True only when energy is equidistant."""
spacings = np.unique(np.diff(energy))
for spacing in spacings[1:]:
if not np.isclose(spacing, spacings[0], atol=tol):
return False
return True | 045466cc02e4a29724fe9ee6d0010a961eaf58c2 | 43,726 |
import numpy as np
def acf(x,l):
""" Auto correlation function of a given vector x with a maximum lag of length l.
"""
return np.array([1]+[np.corrcoef(x[:-i], x[i:])[0,1] \
for i in range(1, l)]) | f168cf69b7055508a95c22b869b36e5c808f5953 | 43,727 |
def gDawson(n):
"""Return the G-value of a single Dawson game"""
if n == 0:
return 0
if n == 1:
return 1
successors_g = []
for next_state in successors(n):
if len(next_state) == 1:
successors_g.append(gDawson(next_state[0]))
else:
successors_g.... | 9bea61f8593d40d007934d29c6f414fa645c2421 | 43,728 |
from typing import Optional
def preprocess_data(
exec_time_data: pd.DataFrame,
neuro_bins: arrays.IntervalArray | pd.IntervalIndex,
impair_bins: arrays.IntervalArray | pd.IntervalIndex,
duration_bins: arrays.IntervalArray | pd.IntervalIndex,
transition_fade_distance: Optional[int] = None,
) -> pd.... | 92e51430acb2295a135d95433a460b9334260114 | 43,729 |
def op_name(graph, tfobj_or_name):
"""
Get the name of a tf.Operation
:param graph: tf.Graph, a TensorFlow Graph object
:param tfobj_or_name: either a tf.Tensor, tf.Operation or a name to either
"""
graph = validated_graph(graph)
return get_op(graph, tfobj_or_name).name | 100e0c371cae4339c4740e00ad10f5f4b26d54f7 | 43,731 |
def parse_map_align_stdout(stdout):
"""Parse the stdout of map_align and extract the alignment of residues.
Parameters
----------
stdout : str
Standard output created with map_align
Returns
------
dict
A dictionary where aligned residue numbers in map_b are the keys and resi... | 4cb699ffbb817e80402af22b08240323012919f8 | 43,734 |
def diff_dicts(new, origin):
"""Only compare the first layer, return a the dict that represent
add, remove, modify changes from new to origin
NOTE: If one of the two dicts comes from another, eg. from .copy(),
# make sure new and origin are totally different from each other,
that means, the result ... | 45412104ff754096e66f64e0028dd1a9dcc5f715 | 43,735 |
def move_to_answer(request, post, **kwargs):
"""
Move this post to be an answer
"""
parent = post.root
ptype = Post.ANSWER
msg = "dragged post to answer"
return move(request=request,
parent=parent,
source=post,
ptype=ptype,
msg... | ae63e914558b599a0184b52bc2b51d8ec69b1f62 | 43,736 |
import requests
def read_feed(feed_url):
"""
Generates an events list based on a calendar URL
:param feed_url: valid URL for an iCalendar feed
:returns: list of icalendar Events
"""
response = requests.get(feed_url)
cal = Calendar.from_ical(response.content)
return get_events(cal) | 3139c31246f2ac5f310e33b616ea8ba8860213e7 | 43,737 |
def nonmatsubara_exponents(coup_strength, cav_broad, cav_freq, beta):
"""
Get the exponentials for the correlation function for non-matsubara
terms for the underdamped Brownian motion spectral density . (t>=0)
Parameters
----------
coup_strength: float
The coupling strength parameter.
... | 84e441dfd7f8b8bf6e0aaed8b5811eb89acd881a | 43,738 |
def get_branch_index_sub_divide(sub_divisions, edge_index, edge_degree, box_size=None, edge_x=None, edge_y=None,
edge_z=None, phi=None, theta=None, edge_phi=None, edge_theta=None,
branch_cutting_frequency=1000, mode='Euclidean', two_dimension=True):
""... | b20e67d6ed6cad2fa8220cb2390f7de8e90afeb5 | 43,739 |
def get_approved_anime_posts(conn, mal_id) -> dict:
"""
Get reddit posts for some anime, that were manually checked and approved.
"""
with conn:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor:
query = """select mar.post_id, mar.sub_name, mar.source_link, mar.vi... | 4bb3aa0817870a9d549a76e65401faa3e91f3748 | 43,740 |
import re
def get_default_look_in_description(schema_node: SchemaNode) -> str:
"""Filter. Get the default value of a JSON Schema property. If not set, look for it in the description."""
default_value = get_default(schema_node)
if default_value:
return default_value
description = schema_node.k... | 4c4d514de3f58e5d7ebef0f4311715065c272ff6 | 43,741 |
from datetime import datetime
def deserialize_date(data_type, data, model_finder):
"""Deserializes data into a python date
Expected input value in format YYYY-MM-DD as per
https://tools.ietf.org/html/rfc3339#section-5.6 standard
Raise ValueError if the input is well formatted but not a valid... | 1eef3879449dfa5ac237959d79a03864f0e931bf | 43,742 |
def tsunami_forecast_render():
"""
Renders the tsunami forecast index.
"""
return render_template("tsunami_forecast.html") | 2711660aebc4fd7a879bc0b70b669503c50e715a | 43,743 |
import numpy
import torch
def get_tensor_n_elements(tensor):
"""Return the number of elements in a tensor."""
if isinstance(tensor, numpy.ndarray):
return tensor.size
if torch_available():
if isinstance(tensor, torch.Tensor):
return torch.numel(tensor)
raise ValueError("Uns... | efbedb6fc34bbff5e4b9122a439c5419049008ad | 43,744 |
from typing import Callable
from typing import Any
from typing import Union
def task(
fn: Callable = None, **task_init_kwargs: Any
) -> Union[
"prefect.tasks.core.function.FunctionTask",
Callable[[Callable], "prefect.tasks.core.function.FunctionTask"],
]:
"""
A decorator for creating Tasks from fu... | deaf4deae87c43b84a2ee1d24d8b73cebf781971 | 43,745 |
import math
def ads(x, adsParameter):
""" ADS function """
p = adsParameter
exp1 = 1 + math.exp(-1 * (x - p.C + p.D / 2) / p.E)
exp2 = 1 + math.exp(-1 * (x - p.C - p.D / 2) / p.F)
dx = p.A + p.B / exp1 * (1 - 1 / exp2)
return dx / p.DMAX | f09f35aea0bc43c3dcefb922a306c6745e472aaa | 43,746 |
def label_diversity_norm(label):
"""
labelๅทฎๅผๆงๅๅผ
:param label:
:return:
"""
return label_diversity(label) / label_set_num(label) | 5563cf0330af55ea701473ad5c87c1ee21046d35 | 43,747 |
def last_common_ancestor(taxonomies):
"""Compute last common ancestor"""
lca = list()
if len(taxonomies) > 1:
zipped = zip(*taxonomies)
for level in zipped:
if len(set(level)) > 1:
level = "*"
else:
level = level[0]
lca.appe... | 0f49b2faa2e480afd41b93d5442d2ee1b86d5b24 | 43,748 |
from typing import Optional
def get_resource_share(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetResourceShareResult:
"""
Resource Type definition for AWS::RAM::ResourceShare
"""
__args__ = dict()
__args__['id'] = id
if opts is Non... | c72ee6154de617b02ccf8260bd8b7169538c1b28 | 43,749 |
import struct
import socket
def ip_to_ascii(ip_address):
""" Converts the quad IP format to an integer representation. """
return struct.unpack('!L', socket.inet_aton(ip_address))[0] | 2cb3ccbe70eed2dd2e8ac21d10e180805dec95ea | 43,750 |
from functools import reduce
def nck(nval, kval):
"""from https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python"""
# https://en.wikipedia.org/wiki/Binomial_coefficient"""
# Computes the binomial coefficient n choose k"""
kval = min(kval, nval-kval)
numer = reduce(op.mu... | f3628850361a7609c3ba88acd168f646e5839652 | 43,751 |
def accumulate(results, gt, weights = None, exclude_keys = []) :
""" Take results from evaluate_objects and ground truth and compile a simple data structure
containing correct, total and nb_correlations """
# Get default weights
if weights == None :
weights = { a : { o : 1 for o in t.keys()... | 813ac2d8d028a7d9d76e605bfdb143a8349b3c54 | 43,752 |
def label(text='Origin', pos=(0, 0, 0), scale=(0.2, 0.2, 0.2),
color=(1, 1, 1)):
"""Create a label actor.
This actor will always face the camera
Parameters
----------
text : str
Text for the label.
pos : (3,) array_like, optional
Left down position of the label.
s... | 4ddad78c4a84b9668b1468c850ed9f1f241dab05 | 43,754 |
from typing import Any
import jsonschema
def validate_schema(schema_key: str, value: Any, draft_checker=jsonschema.draft7_format_checker) -> Any:
"""Validate a JSONSchema according a json model.
.. versionadded:: 0.6.0
Raises:
jsonschema.ValidationError: When the current value does not match wit... | 361eef4099f5feef470e4f774de6bd3ed6ac5cf5 | 43,755 |
from typing import Any
from typing import Sequence
def complete_ports(_: Any, __: Any, incomplete: str) -> Sequence[str]:
"""Returns common ports for completion."""
return [k for k in ('80', '443', '8080') if k.startswith(incomplete)] | 694306ae57bcfd21d6fa73a595768dde0ffba86a | 43,756 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.