content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def structures_at_boundaries(gdf, datamodel, areas, structures, tolerance, distance):
"""
Check if there are structures near area (typically water-level areas) boundaries.
Parameters
----------
gdf : ExtendedGeoDataframe
ExtendedGeoDataFrame, HyDAMO hydroobject layer
datamodel : HyDAMO
... | 6f1c83f2ac02b6773bf51f64326ed4f6e3c7c354 | 3,654,624 |
from typing import List
from typing import Tuple
from typing import Union
def above_cutoff(gene_freq_tup_list: List[Tuple[Union[str, tuple], Tuple[str, str]]], cutoff: int) -> List[str]:
"""Return the genes/edges that are are in at least the given cutoff's networks
Parameters
----------
gene_freq_tup... | c5679743d0b87fcbf7b6955a755aa8bbb11f5f95 | 3,654,625 |
def normalizeWindows(X):
"""
Do point centering and sphere normalizing to each window
to control for linear drift and global amplitude
Parameters
----------
X: ndarray(N, Win)
An array of N sliding windows
Returns
XRet: ndarray(N, Win)
An array in which the mean of each r... | 013b5829153ee21979bcf9dac8457beb1adbe2a2 | 3,654,626 |
import torch
def cost_matrix_slow(x, y):
"""
Input: x is a Nxd matrix
y is an optional Mxd matirx
Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]
if y is not given then use 'y=x'.
i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2
"""
x_norm =... | c27889346d6fb1a075eabf908f5e56ececb554d0 | 3,654,627 |
def get_dists(ts1_sax, ts2_sax, lookup_table):
"""
Compute distance between each symbol of two words (series) using a lookup table
ts1_sax and ts2_sax are two sax representations (strings) built under the same conditions
"""
# Verify integrity
if ts1_sax.shape[0] != ts2_sax.shape[0]:
ret... | 3da21a1c57952225326c97bb7a58238545131e94 | 3,654,628 |
def get_dom_coords(string, dom):
"""Get Coordinates of a DOM specified by the string and dom number.
Parameters
----------
string : int
String number (between 1 and 86)
dom : int
DOM number (between 1 and 60)
Returns
-------
tuple(float, float, float)
The x, y, ... | 08e0817ab85e71caa38e6c247e1cc488d03ce1c0 | 3,654,629 |
def relevance_ka(x):
"""
based on code from https://www.kaggle.com/aleksandradeis/regression-addressing-extreme-rare-cases
see paper: https://www.researchgate.net/publication/220699419_Utility-Based_Regression
use the sigmoid function to create the relevance function, so that relevance function
has ... | e056c8ae1b1c527dc1a875c201967eacf914d7e0 | 3,654,630 |
from datetime import datetime
def now(mydateformat='%Y%m%dT%H%M%S'):
""" Return current datetime as string.
Just a shorthand to abbreviate the common task to obtain the current
datetime as a string, e.g. for result versioning.
Args:
mydateformat: optional format string (default: '%Y... | f4f98116700888a4be273143d635c62859c96e03 | 3,654,631 |
from datetime import datetime
def cmp_point_identities(a, b):
"""
Given point identities a, b (may be string, number, date, etc),
collation algorithm compares:
(a) strings case-insensitively
(b) dates and datetimes compared by normalizing date->datetime.
(c) all other types use __cmp_... | 475206398fc0c2f301446c5c264bf67d1671a2ad | 3,654,633 |
def shortest_complement(t, m, l):
"""
Given a primitive slope t and the holonomies of the current
meridian and longitude, returns a shortest complementary slope s
so that s.t = +1.
"""
c, d = t # second slope
_, a, b = xgcd(d, c) # first slope
b = -b
assert a*d - b*c == 1
return ... | 4653a7eac7af7ed8a67ce298f1453236cfeabf73 | 3,654,634 |
def run_pii(text, lang):
"""
Runs the given set of regexes on the data "lines" and pulls out the
tagged items.
The lines structure stores the language type(s). This can be used for
language-specific regexes, although we're dropping that for now and using
only "default"/non-language-specific regexes.
"""
... | e9f34686be27773952f64a9231e86c76c0170483 | 3,654,635 |
def get_ref_cat(butler, visit, center_radec, radius=2.1):
"""
Get the reference catalog for the desired visit for the requested
sky location and sky cone radius.
"""
ref_cats = RefCat(butler)
try:
band = list(butler.subset('src', visit=visit))[0].dataId['filter']
except dp.butlerExce... | d2814729aeb775668d6eff6fdc68a0676168b16e | 3,654,636 |
def replace_dict(d, **kwargs):
"""
Replace values by keyword on a dict, returning a new dict.
"""
e = d.copy()
e.update(kwargs)
return e | be1cc21be5320eeea13307dd4ed5025b51339eec | 3,654,637 |
def pageHeader(
headline="",
tagline=""):
"""
*Generate a pageHeader - TBS style*
**Key Arguments:**
- ``headline`` -- the headline text
- ``tagline`` -- the tagline text for below the headline
**Return:**
- ``pageHeader`` -- the pageHeader
"""
pageHeade... | 7d9e91df8af2fff92b0b7096cd1a13198d899e15 | 3,654,638 |
def get_counter_merge_suggestion(merge_suggestion_tokens):
"""Return opposite of merge suggestion
Args:
merge_suggestion_tokens (list): tokens in merge suggestion
Returns:
str: opposite of merge suggestion
"""
counter_merge_suggestion = ' '.join(merge_suggestion_tokens)
if merg... | e32e0f1b64fe77acaa8d88d72dca9304b7427674 | 3,654,639 |
import re
from datetime import datetime
import pytz
def parse_rfc3339_utc_string(rfc3339_utc_string):
"""Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime.
"""
# The timestamp from the Google Operation... | 04653bd5673c5ca7713c9e6014947886781f3f5e | 3,654,640 |
from datetime import datetime
def response(code, body='', etag=None, last_modified=None, expires=None, **kw):
"""Helper to build an HTTP response.
Parameters:
code
: An integer status code.
body
: The response body. See `Response.__init__` for details.
etag
: A value for the ET... | 094e7dc99114d4b742808c0aa123001fb301fb14 | 3,654,641 |
from datetime import datetime
import click
def parse_tweet(raw_tweet, source, now=None):
"""
Parses a single raw tweet line from a twtxt file
and returns a :class:`Tweet` object.
:param str raw_tweet: a single raw tweet line
:param Source source: the source of the given tweet
... | 85f90ce469091cc82dd120e6c100859f8bcc8f2c | 3,654,643 |
import requests
def scopes(request, coalition_id):
"""
Update coalition required scopes with a specific set of scopes
"""
scopes = []
for key in request.POST:
if key in ESI_SCOPES:
scopes.append(key)
url = f"{GLOBAL_URL}/{coalition_id}"
headers = global_headers(reque... | 71d07be26815a8e30ed37074b4452fa7574d07b5 | 3,654,644 |
def recursive_dictionary_cleanup(dictionary):
"""Recursively enrich the dictionary and replace object links with names etc.
These patterns are replaced:
[phobostype, bpyobj] -> {'object': bpyobj, 'name': getObjectName(bpyobj, phobostype)}
Args:
dictionary(dict): dictionary to enrich
... | b49798dd1918401951bae57e544406ee1d14ebd6 | 3,654,645 |
def validate_dtype(dtype_in):
"""
Input is an argument represention one, or more datatypes.
Per column, number of columns have to match number of columns in csv file:
dtype = [pa.int32(), pa.int32(), pa.int32(), pa.int32()]
dtype = {'__columns__': [pa.int32(), pa.int32(), pa.int32(), pa.int32()]}
... | 274df2e010314867f31c14951f1e0b18190218ad | 3,654,646 |
from typing import Callable
from re import T
from typing import List
from typing import Any
from typing import Dict
def cache(
cache_class: Callable[[], base_cache.BaseCache[T]],
serializer: Callable[[], cache_serializer.CacheSerializer],
conditional: Callable[[List[Any], Dict[str, Any]], bool... | c4d5318d471e13f5001eb12b6d3dc4f278478855 | 3,654,648 |
def words2chars(images, labels, gaplines):
""" Transform word images with gaplines into individual chars """
# Total number of chars
length = sum([len(l) for l in labels])
imgs = np.empty(length, dtype=object)
newLabels = []
height = images[0].shape[0]
idx = 0;
for i, gaps... | e04bf5b1e9b47c2f930600433b4214343e067f26 | 3,654,649 |
def create_spark_session(spark_jars: str) -> SparkSession:
"""
Create Spark session
:param spark_jars: Hadoop-AWS JARs
:return: SparkSession
"""
spark = SparkSession \
.builder \
.config("spark.jars.packages", spark_jars) \
.appName("Sparkify ETL") \
.getOrCreate(... | 576072460e465610fff98da377cc20a8472c537f | 3,654,650 |
from datetime import datetime
def make_expired(request, pk):
"""
将号码状态改为过号
"""
try:
reg = Registration.objects.get(pk=pk)
except Registration.DoesNotExist:
return Response('registration not found', status=status.HTTP_404_NOT_FOUND)
data = {
'status': REGISTRATION_STATUS... | 827f45c12bcbb973eb073662d8a14765422fdf51 | 3,654,651 |
def word2vec_similarity(segmented_topics, accumulator, with_std=False, with_support=False):
"""For each topic segmentation, compute average cosine similarity using a
:class:`~gensim.topic_coherence.text_analysis.WordVectorsAccumulator`.
Parameters
----------
segmented_topics : list of lists of (int... | 1a3d439e75c4732138f42ea14e7fd50eb6e7d5cb | 3,654,652 |
def addGroupsToKey(server, activation_key, groups):
"""
Add server groups to a activation key
CLI Example:
.. code-block:: bash
salt-run spacewalk.addGroupsToKey spacewalk01.domain.com 1-my-key '[group1, group2]'
"""
try:
client, key = _get_session(server)
except Exceptio... | 346690a9eac24f62f4410b23f60bb589d174c9ed | 3,654,653 |
def get_user_for_delete():
"""Query for Users table."""
delete_user = Users.query \
.get(DELETE_USER_ID)
return delete_user | 208dbbe47550c6889848b7ff61324acf23a4c495 | 3,654,654 |
from typing import List
from typing import Optional
def station_code_from_duids(duids: List[str]) -> Optional[str]:
"""
Derives a station code from a list of duids
ex.
BARRON1,BARRON2 => BARRON
OSBAG,OSBAG => OSBAG
"""
if type(duids) is not list:
return None
... | 1f976ee0b7a82453673ea07c20070e502df5fcf5 | 3,654,655 |
def erosion(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological erosion of an image.
Morphological erosion sets a pixel at (i,j) to the minimum over all pixels
in the neighborhood centered at (i,j). Erosion shrinks bright regions and
enlarges dark regions.
Para... | 2e7c2547b862add24cc6a4355cf3e0308cb2f342 | 3,654,656 |
def NE(x=None, y=None):
"""
Compares two values and returns:
true when the values are not equivalent.
false when the values are equivalent.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ne/
for more details
:param x: first value or expression
:param y: second... | be721daf480ec0cb465a3c010c4f910a10fbbb1d | 3,654,657 |
def TCPs_from_tc(type_constraint):
"""
Take type_constraint(type_param_str, allowed_type_strs) and return list of TypeConstraintParam
"""
tys = type_constraint.allowed_type_strs # Get all ONNX types
tys = set(
[onnxType_to_Type_with_mangler(ty) for ty in tys]
) # Convert to Knossos and... | 7c2162bb2dde0b00caf289511f20804cadaa17e5 | 3,654,658 |
def _randomde(allgenes,
allfolds,
size):
"""Randomly select genes from the allgenes array and fold changes from the
allfolds array. Size argument indicates how many to draw.
Parameters
----------
allgenes : numpy array
numpy array with all the genes expressed in ... | 1a5f38eab8933b90697f4999cb7571fe602db3f9 | 3,654,659 |
import time
def XCor(spectra, mask_l, mask_h, mask_w, vel, lbary_ltopo, vel_width=30,\
vel_step=0.3, start_order=0, spec_order=9,iv_order=10,sn_order=8,max_vel_rough=300.):
"""
Calculates the cross-correlation function for a Coralie Spectra
"""
# speed of light, km/s
c = 2.99792458E5
# loop over ... | 7007c56e5173999b9d20dfbd8018133a59bb777c | 3,654,660 |
import json
def marks_details(request, pk):
"""
Display details for a given Mark
"""
# Check permission
if not has_access(request):
raise PermissionDenied
# Get context
context = get_base_context(request)
# Get object
mark = get_object_or_404(Mark, pk=pk)
mark.catego... | 1f193c67f1e047ecd6da0e5eec1d29da50f6595e | 3,654,661 |
from bs4 import BeautifulSoup
def clean_text(text):
"""
text: a string
return: modified initial string
"""
text = BeautifulSoup(text, "lxml").text # HTML decoding
text = text.lower() # lowercase text
# replace REPLACE_BY_SPACE_RE symbols by space in text
text = REPLACE_BY_SP... | 6594bd61c2f1ff885948755a0dfc74e7256b9a3e | 3,654,662 |
def _simpsons_interaction(data, groups):
"""
Calculation of Simpson's Interaction index
Parameters
----------
data : a pandas DataFrame
groups : list of strings.
The variables names in data of the groups of interest of the analysis.
Returns
-------
statistic ... | d7c4bc8bfb2d6db17868f0d140c2547e65cfd666 | 3,654,664 |
import json
def run(target='192.168.1.1', ports=[21,22,23,25,80,110,111,135,139,443,445,554,993,995,1433,1434,3306,3389,8000,8008,8080,8888]):
"""
Run a portscan against a target hostname/IP address
`Optional`
:param str target: Valid IPv4 address
:param list ports: Port numbers to scan on target... | 201e4dc1809553eb4fb57848d9e5f8001ccdef23 | 3,654,667 |
import torch
def subsequent_mask(size: int):
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((1, size, s... | f4e40d2e9ac944d3582ed16088e8096f75a5f29e | 3,654,668 |
from typing import Type
def _get_dist_class(
policy: Policy, config: TrainerConfigDict, action_space: gym.spaces.Space
) -> Type[TorchDistributionWrapper]:
"""Helper function to return a dist class based on config and action space.
Args:
policy (Policy): The policy for which to return the action
... | 6511786dff734ddb78ce7c28e19b651c70fe86e2 | 3,654,669 |
def timeexec(fct, number, repeat):
"""
Measures the time for a given expression.
:param fct: function to measure (as a string)
:param number: number of time to run the expression
(and then divide by this number to get an average)
:param repeat: number of times to repeat the computation
... | 01ea6d74bed9d8a7d1b7793d3f8473bc6442f83f | 3,654,670 |
def regexify(w, tags):
"""Convert a single component of a decomposition rule
from Weizenbaum notation to regex.
Parameters
----------
w : str
Component of a decomposition rule.
tags : dict
Tags to consider when converting to regex.
Returns
-------
w : str
Co... | 113a631674c5984d81f830c5e8ca840d95678aa1 | 3,654,672 |
def row_dot_product(a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""
Returns a vectorized dot product between the rows of a and b
:param a: An array of shape (N, M) or (M, )
(or a shape that can be broadcast to (N, M))
:param b: An array of shape (N, M) or (M, )
(or a shape that can be broadcas... | d2544f2957963d343bdeb079418a1a5d96373eb4 | 3,654,673 |
def pmg_pickle_dump(obj, filobj, **kwargs):
"""
Dump an object to a pickle file using PmgPickler.
Args:
obj : Object to dump.
fileobj: File-like object
\\*\\*kwargs: Any of the keyword arguments supported by PmgPickler
"""
return PmgPickler(filobj, **kwargs).dump(obj) | 4ac72623538ce463b1bfc183bcac90919e47c513 | 3,654,674 |
def condition_header(header, needed_keys=None):
"""Return a dictionary of all `needed_keys` from `header` after passing
their values through the CRDS value conditioner.
"""
header = { key.upper():val for (key, val) in header.items() }
if not needed_keys:
needed_keys = header.keys()
else:... | cd8c39e355a05367d479e76bda6f0869c10f8130 | 3,654,675 |
from typing import OrderedDict
def get_generic_path_information(paths, stat_prefix=""):
"""
Get an OrderedDict with a bunch of statistic names and values.
"""
statistics = OrderedDict()
returns = [sum(path["rewards"]) for path in paths]
# rewards = np.vstack([path["rewards"] for path in paths]... | a90995c43d588cee4869bfa8b3f6a1026d265aab | 3,654,676 |
import math
import numpy as np
def pad_images(images, nlayers):
"""
In Unet, every layer the dimension gets divided by 2
in the encoder path. Therefore the image size should be divisible by 2^nlayers.
"""
divisor = 2**nlayers
nlayers, x, y = images.shape # essentially setting nlayers to z dire... | 671fa940d0a0ed87819335b60d12d9e268bf9932 | 3,654,677 |
def remove_measurements(measurements, model_dict, params=None):
"""Remove measurements from a model specification.
If provided, a params DataFrame is also reduced correspondingly.
Args:
measurements (str or list): Name(s) of the measurement(s) to remove.
model_dict (dict): The model specif... | fffddf4368579c999648c29b4746006b38de140c | 3,654,678 |
def good2Go(SC, L, CC, STR):
"""
Check, if all input is correct and runnable
"""
if SC == 1 and L == 1 and CC == 1 and STR == 1:
return True
else:
print(SC, L, CC, STR)
return False | e49229df6b9b187e1840d5bc5c8a1a8e087a5a4e | 3,654,679 |
def __validate_tweet_name(tweet_name: str, error_msg: str) -> str:
"""Validate the tweet's name.
Parameters
----------
tweet_name : str
Tweet's name.
error_msg : str
Error message to display for an invalid name.
Returns
-------
str
Validated tweet name.
Rai... | 7086aeac6ccd0afcad0d13e947f3b454f7333b9f | 3,654,680 |
def convert_event(obj):
"""
:type obj: :class:`sir.schema.modelext.CustomEvent`
"""
event = models.event(id=obj.gid, name=obj.name)
if obj.comment:
event.set_disambiguation(obj.comment)
if obj.type is not None:
event.set_type(obj.type.name)
event.set_type_id(obj.type.gi... | 23a6a31abca03d0c92f6162ce28b8548dc95bdda | 3,654,681 |
from typing import Any
import requests
import json
def get_pr_review_status(pr: PullRequestDetails, per_page: int = 100) -> Any:
"""
References:
https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
"""
url = (f"https://api.github.com/repos/{pr.repo.organization}/{pr.re... | 5ce662ab5d82e374def95e5f3cc4da9f2d4dbf96 | 3,654,682 |
def make_sph_model(filename):
"""reads a spherical model file text file and generates interpolated values
Args:
filename:
Returns:
model:
"""
M = np.loadtxt(filename, dtype={'names': ('rcurve', 'potcurve', 'dpotcurve'),'formats': ('f4', 'f4', 'f4')},skiprows=1)
model = ... | d86a88ffca93ee0618cf5a19aa015077247cffb0 | 3,654,683 |
def minimum(x, y):
"""
Returns the min of x and y (i.e. x < y ? x : y) element-wise.
Parameters
----------
x : tensor.
Must be one of the following types: bfloat16, half, float32, float64, int32, int64.
y : A Tensor.
Must have the same type as x.
name : str
A name fo... | 384e7d15687d03f7b639fc50707712c94029620f | 3,654,685 |
def seconds_to_timestamp(seconds):
"""
Convert from seconds to a timestamp
"""
minutes, seconds = divmod(float(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%06.3f" % (hours, minutes, seconds) | 8b9806f05fe4796baae51001e69455e82fb51eed | 3,654,686 |
def query(querystring: str,
db: tsdb.Database,
**kwargs):
"""
Perform query *querystring* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
querystring (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query... | fa43123b3e0c4706b738104c641836fa08a4fc35 | 3,654,687 |
def TTF_SizeUTF8(font, text, w, h):
"""Calculates the size of a UTF8-encoded string rendered with a given font.
See :func:`TTF_SizeText` for more info.
Args:
font (:obj:`TTF_Font`): The font object to use.
text (bytes): A UTF8-encoded bytestring of text for which the rendered
s... | 3d24382222b1795caa0981c659d00a717c22fc86 | 3,654,688 |
def get_mse(y_true, y_hat):
"""
Return the mean squared error between the ground truth and the prediction
:param y_true: ground truth
:param y_hat: prediction
:return: mean squared error
"""
return np.mean(np.square(y_true - y_hat)) | 3d4c1828abf5bf88607e4ca1a263c483105733aa | 3,654,689 |
def generate_v2_token(username, version, client_ip, issued_at_timestamp, email=''):
"""Creates the JSON Web Token with a new schema
:Returns: String
:param username: The name of person who the token identifies
:type username: String
:param version: The version number for the token
:type versi... | dee10b68fc15ec730a7b8921f95a77804618879c | 3,654,690 |
import math
def choose(n, k):
"""return n choose k
resilient (though not immune) to integer overflow"""
if n == 1:
# optimize by far most-common case
return 1
return fact_div(n, max(k, n - k)) / math.factorial(min(k, n - k)) | fecd411a4148127f998f58d8d27668777bf5efbe | 3,654,691 |
from typing import List
def part_one(puzzle_input: List[str]) -> int:
"""Find the highest seat ID on the plane"""
return max(boarding_pass_to_seat_id(line) for line in puzzle_input) | 1ae95a7784f5348bb435483228630c8795d62d30 | 3,654,692 |
def readbit(val, bitidx):
""" Direct word value """
return int((val & (1<<bitidx))!=0) | 4ca368f89b2496ec46c1641835c1f2a0a1cdd573 | 3,654,693 |
def matrix_bombing_plan(m):
""" This method calculates sum of the matrix by
trying every possible position of the bomb and
returns a dictionary. Dictionary's keys are the
positions of the bomb and values are the sums of
the matrix after the damage """
matrix = deepcopy(m)
rows = len(m)
... | 013d1dc3685013fa6fd5c87cfc2513e07e66e310 | 3,654,694 |
def coord_to_gtp(coord, board_size):
""" From 1d coord (0 for position 0,0 on the board) to A1 """
if coord == board_size ** 2:
return "pass"
return "{}{}".format("ABCDEFGHJKLMNOPQRSTYVWYZ"[int(coord % board_size)],\
int(board_size - coord // board_size)) | a0419e8a7f39cd282585ed1d29d94bbded0e3f1c | 3,654,695 |
def test_alternative_clusting_method(ClusterModel):
"""
Test that users can supply alternative clustering method as dep injection
"""
def clusterer(X: np.ndarray, k: int, another_test_arg):
"""
Function to wrap a sklearn model as a clusterer for OptimalK
First two arguments are ... | 173e376726abe943f15fae44aa746bf9abe7dd53 | 3,654,696 |
def load_dataset(spfile, twfile):
"""Loads dataset given the span file and the tweets file
Arguments:
spfile {string} -- path to span file
twfile {string} -- path to tweets file
Returns:
dict -- dictionary of tweet-id to Tweet object
"""
tw_int_map = {}
# for filen in os.... | e25c382b3fe8c321b70206894e483c3f04ade2ed | 3,654,697 |
from typing import Union
from typing import Tuple
def nameof(var, *more_vars,
# *, keyword only argument, supported with python3.8+
frame: int = 1,
vars_only: bool = True) -> Union[str, Tuple[str]]:
"""Get the names of the variables passed in
Examples:
>>> a = 1
... | 4a7c7d8390dad2597cad65409aaa6cd3f716a8a8 | 3,654,698 |
def scorer(func):
"""This function is a decorator for a scoring function.
This is hack a to get around self being passed as the first argument to the scoring function."""
def wrapped(a, b=None):
if b is not None:
return func(b)
return func(a)
return wrapped | 39ec390982d26d10a6ce827800df654ff6c4ab42 | 3,654,700 |
def print_stats(yards):
"""
This function prints the final stats after a skier has crashed.
"""
print
print "You skied a total of", yards, "yards!"
#print "Want to take another shot?"
print
return 0 | 72b56bf8cfb0691636e41ccfcfe9b3893ab870eb | 3,654,701 |
def _calculate_risk_reduction(module):
"""
Function to calculate the risk reduction due to testing. The algorithms
used are based on the methodology presented in RL-TR-92-52, "SOFTWARE
RELIABILITY, MEASUREMENT, AND TESTING Guidebook for Software
Reliability Measurement and Testing." Rather than at... | c8876bc247243f13572d49c07063a063ba4eb42a | 3,654,702 |
def run_metarl(env, test_env, seed, log_dir):
"""Create metarl model and training."""
deterministic.set_seed(seed)
snapshot_config = SnapshotConfig(snapshot_dir=log_dir,
snapshot_mode='gap',
snapshot_gap=10)
runner = LocalRunner(... | adc4041539d55d9cddba69a44a0d0fcfbbc1c16e | 3,654,703 |
from ..nn.nn_modifiers import get_single_nn_mutation_op
def get_default_mutation_op(dom):
""" Returns the default mutation operator for the domain. """
if dom.get_type() == 'euclidean':
return lambda x: euclidean_gauss_mutation(x, dom.bounds)
elif dom.get_type() == 'integral':
return lambda x: integral_... | 8e9455ca96dac89b11bebcc3e4f779f62111a010 | 3,654,704 |
import itertools
def chunked(src, size, count=None, **kw):
"""Returns a list of *count* chunks, each with *size* elements,
generated from iterable *src*. If *src* is not evenly divisible by
*size*, the final chunk will have fewer than *size* elements.
Provide the *fill* keyword argument to provide a p... | 6f35735d9294f4c245643609641fb86b0f988fb1 | 3,654,705 |
def doc_to_schema_fields(doc, schema_file_name='_schema.yaml'):
"""Parse a doc to retrieve the schema file."""
return doc_to_schema(doc, schema_file_name=schema_file_name)[
'schema_fields'] | b9d88f52ff49e43cae0ad5373a8d841f0236bb50 | 3,654,706 |
from typing import Tuple
from typing import OrderedDict
from typing import Counter
import tqdm
def cluster(df: pd.DataFrame, k: int, knn: int = 10, m: int = 30, alpha: float = 2.0, verbose0: bool = False,
verbose1: bool = False, verbose2: bool = True, plot: bool = True) -> Tuple[pd.DataFrame, OrderedDict]... | 2363df84104da1f182c63faaac21006033e23083 | 3,654,707 |
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
"""
Load the CIFAR-10 dataset from disk and perform preprocessing to prepare
it for the two-layer neural net classifier. These are the same steps as
we used for the SVM, but condensed to a single function.
"""
# Load... | 515777ca498ae9a234a1503660f2cde40f0b0244 | 3,654,708 |
def timeframe_int_to_str(timeframe: int) -> str:
"""
Convert timeframe from integer to string
:param timeframe: minutes per candle (240)
:return: string representation for API (4h)
"""
if timeframe < 60:
return f"{timeframe}m"
elif timeframe < 1440:
return f"{int(timeframe / ... | 75778742dea8204c74a47bfe92c25aef43ebbad8 | 3,654,709 |
def FIT(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d xi^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
y=sum(x**2 for x in individual)
return y | d6aadf620f85bd9cb27cef661e2ec664a4eb43b1 | 3,654,710 |
def update_range(value):
"""
For user selections, return the relevant range
"""
global df
min, max = df.timestamp.iloc[value[0]], df.timestamp.iloc[value[-1]]
return 'timestamp slider: {} | {}'.format(min, max) | c4819b46cdd78be3c86fc503791a7a0ff9cd96b3 | 3,654,711 |
def simplify(tile):
"""
:param tile: 34 tile format
:return: tile: 0-8 presentation
"""
return tile - 9 * (tile // 9) | c8543d73e37d4fa1d665d3d28277ff99095e0635 | 3,654,712 |
def vep(dataset, config, block_size=1000, name='vep', csq=False) -> MatrixTable:
"""Annotate variants with VEP.
.. include:: ../_templates/req_tvariant.rst
:func:`.vep` runs `Variant Effect Predictor
<http://www.ensembl.org/info/docs/tools/vep/index.html>`__ with the `LOFTEE
plugin <https://github... | e9433db17e82d00aba275066026a301a9b97e5e0 | 3,654,713 |
def __get_ll_type__(ll_type):
"""
Given an lltype value, retrieve its definition.
"""
res = [llt for llt in __LL_TYPES__
if llt[1] == ll_type]
assert len(res) < 2, 'Duplicate linklayer types.'
if res:
return res[0]
else:
return None | f2e86ddd027ec26546a4be8ff8060c1cd8c64aca | 3,654,714 |
def slice_node(node, split):
"""Splits a node up into two sides.
For text nodes, this will return two text nodes.
For text elements, this will return two of the source nodes with children
distributed on either side. Children that live on the split will be
split further.
Parameters
-------... | 5958afbb61160f7e00c42e80c4c69aa7f8644925 | 3,654,716 |
def k_radius(x,centroids):
"""
Maximal distance between centroids and corresponding samples in partition
"""
labels = partition_labels(x,centroids)
radii = []
for idx in range(centroids.shape[0]):
mask = labels == idx
radii.append(
np.max(
np.linalg.n... | de010609e726ce250d72d773a9c1ffb772315b0c | 3,654,717 |
def build_feature_df(data, default=True, custom_features={}):
"""
Computes the feature matrix for the dataset of components.
Args:
data (dataset): A mapping of {ic_id: IC}. Compatible with the dataset representaion produced by load_dataset().
default (bool, optional): Determines wether to c... | bbd2543a5043ae11305fe86449778a74f7e7ceb3 | 3,654,718 |
def decode_complex(data, complex_names=(None, None)):
""" Decodes possibly complex data read from an HDF5 file.
Decodes possibly complex datasets read from an HDF5 file. HDF5
doesn't have a native complex type, so they are stored as
H5T_COMPOUND types with fields such as 'r' and 'i' for the real and
... | 4c2fad09751ddfe4c5623d47a187f710ab62532f | 3,654,720 |
def CLYH(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-05-29", **kwargs
) -> Graph:
"""Re... | 6dcddfff1411ea71d1743fabde782066c41ace9f | 3,654,721 |
def lineParPlot(parDict, FigAx=None, **kwargs):
"""
Plot the results of lineParameters().
Parameters
----------
parDict : dict
The relevant parameters:
xPerc : tuple, (xPerc1, xPerc2)
Left and right x-axis values of the line profile at perc% of the peak flux.
Xc ... | 4767446fb983902ea0a3ce631420c61f032970f9 | 3,654,723 |
def prepare_data_arrays(tr_df, te_df, target):
"""
tr_df: train dataset made by "prepare_dataset" function
te_df: test dataset made by "prepare_dataset" function
target: name of target y
return: (numpy array of train dataset),
(numpy array of test dataset: y will be filled with NaN),
... | 097f376263dfeecffaf201f4ea1cd29980d88746 | 3,654,724 |
def plot(model_set, actual_mdot=True, qnuc=0.0, verbose=True, ls='-', offset=True,
bprops=('rate', 'fluence', 'peak'), display=True, grid_version=0):
"""Plot predefined set of mesa model comparisons
model_set : int
ID for set of models (defined below)
"""
mesa_info = get_mesa_set(model... | 2ceec63d162fe07dd4a00a508657095528243421 | 3,654,726 |
def preprocessing_fn(batch):
"""
Standardize, then normalize sound clips
"""
processed_batch = []
for clip in batch:
signal = clip.astype(np.float64)
# Signal normalization
signal = signal / np.max(np.abs(signal))
# get pseudorandom chunk of fixed length (from SincNe... | d277cd95d174e1ec104a8b8a8d72e23e2dd7f991 | 3,654,728 |
def generate_random_bond_list(atom_count, bond_count, seed=0):
"""
Generate a random :class:`BondList`.
"""
np.random.seed(seed)
# Create random bonds between atoms of
# a potential atom array of length ATOM_COUNT
bonds = np.random.randint(atom_count, size=(bond_count, 3))
# Clip bond ty... | cb7784f8561be2ea7c54d5f46c2e6e697164b1b8 | 3,654,729 |
def open_cosmos_files():
"""
This function opens files related to the COSMOS field.
Returns:
A lot of stuff. Check the code to see what it returns
"""
COSMOS_mastertable = pd.read_csv('data/zfire/zfire_cosmos_master_table_dr1.1.csv',index_col='Nameobj')
ZF_cat = ascii.read('d... | 229aa967dce5faaf42b488ebf2768b280ced9359 | 3,654,730 |
import numpy
def convert_image_points_to_points(image_positions, distances):
"""Convert image points to 3d points.
Returns:
positions
"""
hypotenuse_small = numpy.sqrt(
image_positions[:, 0]**2 +
image_positions[:, 1]**2 + 1.0)
ratio = distances / hypotenuse_small
n = ... | 3680a02997cf1109fd08f61c6642b29ea3433f1d | 3,654,731 |
def W(i, j):
"""The Wilson functions.
:func:`W` corresponds to formula (2) on page 16 in `the technical paper`_
defined as:
.. math::
W(t, u_j)= \\
e^{-UFR\cdot (t+u_j)}\cdot \\
\left\{ \\
\\alpha\cdot\min(t, u_j) \\
-0.5\cdot e^{-\\... | 37266db68fb51a87f15290edae06eb6397796b6f | 3,654,732 |
from scipy.interpolate import interp1d
def reddening_fm(wave, ebv=None, a_v=None, r_v=3.1, model='f99'):
"""Determines a Fitzpatrick & Massa reddening curve.
Parameters
----------
wave: ~numpy.ndarray
wavelength in Angstroms
ebv: float
E(B-V) differential extinction; specify eithe... | 1f47b360044613c9bbb18bf3446bcd7e3ad20344 | 3,654,733 |
def list_registered_stateful_ops_without_inputs():
"""Returns set of registered stateful ops that do not expect inputs.
This list is used to identify the ops to be included in the state-graph and
that are subsequently fed into the apply-graphs.
Returns:
A set of strings.
"""
return set([
name
... | aa089bc4157c6a3c36121c6e880ffbd546723f0e | 3,654,734 |
def load_frame_from_video(path: str, frame_index: int) -> np.ndarray:
"""load a full trajectory video file and return a single frame from it"""
vid = load_video(path)
img = vid[frame_index]
return img | 7b8747df38dfcf1f2244166002126d6d25170506 | 3,654,735 |
from typing import Dict
from typing import List
def get_settings_patterns(project_id: int) -> Dict[str, str]:
"""Returning project patterns settings"""
track_patterns: List[Dict[str, str]] = ProjectSettings.objects.get(project_id=project_id).trackPatterns
return {pattern['pattern']: pattern['regex'] for p... | d566ad5ec2fd72e2384fea90aa9cae9d99d9f441 | 3,654,736 |
def video_to_array(filepath):
"""Process the video into an array."""
cap = cv2.VideoCapture(filepath)
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
channel = 3
frame_buffer = np.empty((num_frames, height... | 2034ce56c7ca4fe61d0e0eb443c6fa9910d8a232 | 3,654,737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.