content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def connect_with_interior_or_edge_bulk(
polygon: Polygon, polygon_array: GeometryArray
) -> List[bool]:
"""
Return boolean array with True iff polys overlap in interior/edge, but not corner.
Args:
polygon (Polygon): A shapely Polygon
polygon_array (GeometryArra... | 852a43d1782ae85dbb2d2adb70feb59ace7a6a44 | 3,643,445 |
import pickle
def get_history(kmodel=None):
"""
returns a python dict with key = metric_id val = [metric each epoch ]
"""
# get kmodel object from input str if the input is a string
if isinstance(kmodel,str):
try:
kmodel = KModel.objects.get(id=kmodel)
except ObjectDoes... | da2886f565ca2f96e49a38b458368de2e4216c01 | 3,643,446 |
def get_neighbor_v4_by_search(search=None):
"""Return a list of NeighborV4's by dict."""
try:
objects = NeighborV4.objects.filter()
search_dict = search if search else dict()
object_map = build_query_to_datatable_v3(objects, search_dict)
except FieldError as e:
raise api_res... | 6893c32014d6b2a8871825744a1953024fe3a289 | 3,643,447 |
def load_clean_data():
"""funcion that loads tuberculosis file and preprocesses/cleans the dataframe"""
df = pd.read_csv('tb.csv')
# drop columns 'fu' and 'mu' since they only contain missing values and would mess up the following processing steps
df = df.drop(columns = ['fu', 'mu'])
# define row an... | 2430bb61705f95c77f68eabbcda535e7d0f443ea | 3,643,448 |
def is_anagram_passphrase(phrase):
"""
Checks whether a phrase contains no words that are anagrams of other words.
>>> is_anagram_passphrase(["abcde", "fghij"])
True
>>> is_anagram_passphrase(["abcde", "xyz", "ecdab"])
False
>>> is_anagram_passphrase(["a", "ab", "abc", "abd", "abf", "abj"])
... | aa7a95cda82317a41d8c4f2765a4706896135f45 | 3,643,449 |
def _client_ip(client):
"""Compatibility layer for Flask<0.12."""
return getattr(client, 'environ_base', {}).get('REMOTE_ADDR') | 1bd110563c5e7165ec795d16e0f0d7be6d053db1 | 3,643,450 |
def extractRecords(getRecordsResponse):
"""Returns a list of etrees of the individual
records of a getRecords response"""
recs = getRecordsResponse.xpath(
'/csw:GetRecordsResponse/csw:SearchResults//csw:Record',
namespaces={'csw': ns_csw})
return recs | 3de69fc99f77c4d06346aa82121cc936e16a06b4 | 3,643,452 |
from typing import Set
def tagify(tail=u'', head=u'', sep=u'.'):
"""
Returns namespaced event tag string.
Tag generated by joining with sep the head and tail in that order
head and tail may be a string or a list, tuple, or Set of strings
If head is a list, tuple or Set Then
join with sep ... | ddebdc0c4224db428a4338fd1e4c61137ac2d5c5 | 3,643,453 |
def get_fn_data(src_db, fn_table, year=None):
"""Get the data and fields from the query in the src database for the
fish net table specified by fn_table. Returns list of
dictionaries - each element represents a single row returned by the query.
Arguments:
- `src_db`: full path the source database.... | 60d48e0b7727ccd25e4b91bf59f1f505ddbc3127 | 3,643,454 |
import collections
def convert_example_to_feature(example, tokenizer, max_seq_length=512,
doc_stride=384, max_query_length=125, is_training=True,
cls_token_at_end=False,
cls_token='[CLS]', sep_token='[SEP]', pad_token=0... | 1db90a014da443e143411276cbbf0e29a9872b7f | 3,643,455 |
def make_pickle(golfed=False):
"""Returns the pickle-quine.
If "golfed" is true, we return the minimized version; if false we return
the one that's easier to understand.
"""
part_1 = b''.join(PART_1)
part_2 = b''.join(GOLFED_PART_2 if golfed else PART_2)
# We tack the length onto part 1:
... | 79fdc182ef3487090a8acd61c44b46d4b7cc5493 | 3,643,456 |
def classify_design_space(action: str) -> int:
"""
The returning index corresponds to the list stored in "count":
[sketching, 3D features, mating, visualizing, browsing, other organizing]
Formulas for each design space action:
sketching = "Add or modify a sketch" + "Copy paste sketch"
3... | 22dc68aa23258691b0d4b9f1b27a9e8451b275d9 | 3,643,457 |
import hashlib
def get_sha256_hash(plaintext):
"""
Hashes an object using SHA256. Usually used to generate hash of chat ID for lookup
Parameters
----------
plaintext: int or str
Item to hash
Returns
-------
str
Hash of the item
"""
hasher = hashlib.sha256(... | 79735973b8ad73823662cc428513ef393952b681 | 3,643,458 |
def get_bit_coords(dtype_size):
"""Get coordinates for bits assuming float dtypes."""
if dtype_size == 16:
coords = (
["±"]
+ [f"e{int(i)}" for i in range(1, 6)]
+ [f"m{int(i-5)}" for i in range(6, 16)]
)
elif dtype_size == 32:
coords = (
... | 6400017e47506613cf15162425843ce2b19eed3e | 3,643,459 |
from klpyastro.utils import obstable
def create_record(user_inputs):
"""
Create a ObsRecord from the informations gathered from the users.
:param user_inputs: Dictionary with all the values (as strings) required
to fully populate a ObsRecord object.
:type user_inputs: dict
:rtype: ObsReco... | 8fc1a31a24ac7663b405074410d1c025fbcd7d62 | 3,643,460 |
import itertools
def best_wild_hand(hand):
"""best_hand но с джокерами"""
non_jokers = list(filter(lambda x: x[0] != '?', hand))
jokers = filter(lambda x: x[0] == '?', hand)
jokers_variations = itertools.product(
*[joker_variations(joker) for joker in jokers]
)
best_hands = []
fo... | 86cb58dba0338c481ce516657118cdc20260ebf3 | 3,643,461 |
def GetTestMetadata(test_metadata_file=FAAS_ROOT+"/synthetic_workload_invoker/test_metadata.out"):
"""
Returns the test start time from the output log of SWI.
"""
test_start_time = None
with open(test_metadata_file) as f:
lines = f.readlines()
test_start_time = lines[0]
confi... | 668e214452bb100885a8631b5d900eb7ca90e43b | 3,643,462 |
import torch
def gen_geo(num_nodes, theta, lambd, source, target, cutoff, seed=None):
"""Generates a random graph with threshold theta consisting of 'num_nodes'
and paths with maximum length 'cutoff' between 'source' adn target.
Parameters
----------
num_nodes : int
Number of nodes.
... | 5d3363aab4e13dd8690277453f603fe707c00d41 | 3,643,463 |
import re
def FilterExceptions(image_name, errors):
"""Filter out the Application Verifier errors that have exceptions."""
exceptions = _EXCEPTIONS.get(image_name, [])
def _HasNoException(error):
# Iterate over all the exceptions.
for (severity, layer, stopcode, regexp) in exceptions:
# And see i... | 37b5febe4da731a426c2cd3ef9d6aeb1f28a802c | 3,643,464 |
from typing import Optional
def dim(text: str, reset_style: Optional[bool] = True) -> str:
"""Return text in dim"""
return set_mode("dim", False) + text + (reset() if reset_style else "") | cb180649913760b71b2857b61e264b6a17207433 | 3,643,465 |
def jaccard(list1, list2):
"""calculates Jaccard distance from two networks\n
| Arguments:
| :-
| list1 (list or networkx graph): list containing objects to compare
| list2 (list or networkx graph): list containing objects to compare\n
| Returns:
| :-
| Returns Jaccard distance between list1 and list2
... | 1056c3d5a592bea9a575c24e947a91968b931000 | 3,643,467 |
def default_argument_preprocessor(args):
"""Return unmodified args and an empty dict for extras"""
extras = {}
return args, extras | 2031dde70dbe54beb933e744e711a0bf8ecaed99 | 3,643,468 |
import random
def early_anomaly(case: pd.DataFrame) -> pd.DataFrame:
"""
A sequence of 2 or fewer events executed too early, which is then skipped later in the case
Parameters
-----------------------
case: pd.DataFrame,
Case to apply anomaly
Returns
-----------------------
Cas... | 0c5f0b0fb3336331737bd9f80712176476110ac9 | 3,643,470 |
def parse_cmd(script, *args):
"""Returns a one line version of a bat script
"""
if args:
raise Exception('Args for cmd not implemented')
# http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
oneline_cmd = '&&'.join(script.split('\n'))
oneline_... | b3355b20af2ca1ab2e996643ae0918a2d387760f | 3,643,472 |
def expected_inheritance(variant_obj):
"""Gather information from common gene information."""
manual_models = set()
for gene in variant_obj.get('genes', []):
manual_models.update(gene.get('manual_inheritance', []))
return list(manual_models) | 29bf223249e29942803cef8468dbd8bd04979e81 | 3,643,473 |
def player_stats_game(data) -> defaultdict:
"""Individual Game stat parser. Directs parsing to the proper
player parser (goalie or skater).
Receives the player_id branch.
Url.GAME
Args:
data (dict): dict representing JSON object.
Returns:
defaultdict: Parsed Data.
"""
... | e39e4e9fb4a3d06421639e9466d29724318484ef | 3,643,474 |
def about(request):
"""
View function for about page
"""
return render(
request,
'about.html',
) | 5bf7a52de1218718041ec7a05a749c623e19074e | 3,643,475 |
def getTimeDeltaFromDbStr(timeStr: str) -> dt.timedelta:
"""Convert db time string in reporting software to time delta object
Args:
timeStr (str): The string that represents time, like 14:25 or 15:23:45
Returns:
dt.timedelta: time delta that has hours and minutes components
"""
if pd... | 66a78192e6cbe5240a9131c2b18e4a42187a6024 | 3,643,476 |
def colorBool(v) -> str:
"""Convert True to 'True' in green and False to 'False' in red
"""
if v:
return colored(str(v),"green")
else:
return colored(str(v),"red") | 8c196bccc5bb1970cc752a495117bcc74ed4f8f6 | 3,643,477 |
from typing import List
def bootstrap(
tokens: List[str],
measure: str = "type_token_ratio",
window_size: int = 3,
ci: bool = False,
raw=False,
):
"""calculate bootstrap for lex diversity measures
as explained in Evert et al. 2017. if measure='type_token_ratio'
it calculates standardiz... | d86cff5edd61698b1adee14a5c2fb800b4b76608 | 3,643,478 |
def by_label(move_data, value, label_name, filter_out=False, inplace=False):
"""
Filters trajectories points according to specified value and collum label.
Parameters
----------
move_data : dataframe
The input trajectory data
value : The type_ of the feature values to be use to filter t... | 3d772f741539009b756744539f4a524e6ad402ea | 3,643,479 |
import numpy
def make_pyrimidine(residue, height = 0.4, scale = 1.2):
"""Creates vertices and normals for pyrimidines:Thymine Uracil Cytosine"""
atoms = residue.atoms
names = [name.split("@")[0] for name in atoms.name]
idx=names.index('N1'); N1 = numpy.array(atoms[idx].coords)
idx=names.ind... | eac8e9bd0cc6abeefa5b8a6bad299ff6a0c6b9d8 | 3,643,480 |
def get_props(filepath, m_co2=22, m_poly=2700/123, N_A=6.022E23,
sigma_co2=2.79E-8, sort=False):
"""
Computes important physical properties from the dft.input file, such as
density of CO2 in the CO2-rich phase, solubility of CO2 in the polyol-rich
phase, and specific volume of the polyol-... | 2aec573795a40c6c95e19ea9ae531abca47128e8 | 3,643,481 |
def get_genotype(chrom, rsid):
"""
"""
geno_path = ('/home/hsuj/lustre/geno/'
'CCF_1000G_Aug2013_Chr{0}.dose.double.ATB.RNASeq_MEQTL.txt')
geno_gen = pd.read_csv(geno_path.format(str(chrom)),
sep=" ", chunksize = 10000)
for i in geno_gen:
if rsid in i.index:
... | 6269aace777e5870e827152158ab70b73a44f401 | 3,643,482 |
import time
def task_dosomething(storage):
"""
Task that gets launched to handle something in the background until it is completed and then terminates. Note that
this task doesn't return until it is finished, so it won't be listening for Threadify pause or kill requests.
"""
# An important task th... | 9eabf3977c53932de8d775c21e4a1209003e0892 | 3,643,483 |
def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
"""Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
"""
with tf.variable_scope(s... | dd90cd6107d5d69596c18d46bbef990cec8b1112 | 3,643,484 |
import functools
def convert_to_entry(func):
"""Wrapper function for converting dicts of entries to HarEnrty Objects"""
@functools.wraps(func)
def inner(*args, **kwargs):
# Changed to list because tuple does not support item assignment
changed_args = list(args)
# Convert the dict ... | a5be9b430a47cb9c0c448e8ba963538fd6a435dc | 3,643,485 |
def transform(record: dict, key_ref: dict, country_ref: pd.DataFrame, who_coding: pd.DataFrame, no_update_phrase: pd.DataFrame):
"""
Apply transformations to OXCGRT records.
Parameters
----------
record : dict
Input record.
key_ref : dict
Reference for key mapping.
country_r... | 2d115f8d64731c5ca88807845d09085b4f07acfd | 3,643,486 |
from google.cloud import vision
import io
def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=image)... | 6dea35d84f538322eed74c9c7c1f9d7a4882dd33 | 3,643,488 |
def file_util_is_ext(path, ext):
"""判断是否指定后缀文件,ext不包含点"""
if file_util_get_ext(path) == ext:
return True
else:
return False | 27389af32333036b998a421ed35952705092ade6 | 3,643,489 |
def load_tract(repo, tract, patches=None, **kwargs):
"""Merge catalogs from forced-photometry coadds across available filters.
Parameters
--
tract: int
Tract of sky region to load
repo: str
File location of Butler repository+rerun to load.
patches: list of str
List of pa... | f989c947dec96426b15219ab224364c96f65d1fb | 3,643,490 |
from datetime import datetime
def calculate_delta(arg1, arg2):
"""
Calculates and returns a `datetime.timedelta` object representing
the difference between arg1 and arg2. Arguments must be either both
`datetime.date`, both `datetime.time`, or both `datetime.datetime`.
The difference is absolute, so the order of ... | f6b3f0b86bd73be7d1702ba8893cd70d99b0b321 | 3,643,491 |
import yaml
def create_model_config(model_dir: str, config_path: str = None):
"""Creates a new configuration file in the model directory and returns the config."""
# read the config file
config_content = file_io.read_file_to_string(root_dir(config_path))
# save the config file to the model directory... | c695ee36b6dec24ef17179adbf40e81aff708082 | 3,643,492 |
def get_deployment_physnet_mtu():
"""Retrieves global physical network MTU setting.
Plugins should use this function to retrieve the MTU set by the operator
that is equal to or less than the MTU of their nodes' physical interfaces.
Note that it is the responsibility of the plugin to deduct the value of... | 161e7f87e2a68643f81e2b62061d65251a1249de | 3,643,493 |
def _path(path):
"""Helper to build an OWFS path from a list"""
path = "/" + "/".join(str(x) for x in path)
return path.encode("utf-8") + b"\0" | d38937deb459bb9bf393402efc31a90a285d4a6d | 3,643,494 |
import time
def current_milli_time():
"""Return the current time in milliseconds"""
return int(time.time() * 1000) | 66605d2e23df2c428c70af75247e2b22a2795363 | 3,643,495 |
from typing import Callable
from typing import Sequence
from typing import Dict
from typing import Optional
def _loo_jackknife(
func: Callable[..., NDArray],
nobs: int,
args: Sequence[ArrayLike],
kwargs: Dict[str, ArrayLike],
extra_kwargs: Optional[Dict[str, ArrayLike]] = None,
) -> NDArray:
"... | 83e39e97e08ef4d16f2c48a084c5ed40d0fbc0ad | 3,643,497 |
from Bio.SeqIO.QualityIO import solexa_quality_from_phred
def _fastq_illumina_convert_fastq_solexa(in_handle, out_handle, alphabet=None):
"""Fast Illumina 1.3+ FASTQ to Solexa FASTQ conversion (PRIVATE).
Avoids creating SeqRecord and Seq objects in order to speed up this
conversion.
"""
# Map une... | 06422e23bb005756742207e63ec1d8dc603ba5b2 | 3,643,498 |
def pull_branch(c: InvokeContext, repo: Repo, directory: str, branch_name: str) -> CommandResult:
"""
Change to the repo directory and pull master.
:argument c: InvokeContext
:argument repo: Repo the repo to pull
:argument directory: str the directory to change to
:argument branch_name: ... | 5c21bdbbe91f5f82b40645a3449d373f6c464717 | 3,643,499 |
def sizeof_fmt(num, suffix='B'):
"""Return human readable version of in-memory size.
Code from Fred Cirera from Stack Overflow:
https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
... | 1aeace0d5ad8ca712704a8ee58e1e206e5e61b56 | 3,643,500 |
def readFPs(filepath):
"""Reads a list of fingerprints from a file"""
try:
myfile = open(filepath, "r")
except:
raise IOError("file does not exist:", filepath)
else:
fps = []
for line in myfile:
if line[0] != "#": # ignore comments
line = line... | 96d483360c411a27a3b570875f61344ef4dae573 | 3,643,501 |
def validate_take_with_convert(convert, args, kwargs):
"""
If this function is called via the 'numpy' library, the third parameter in
its signature is 'axis', which takes either an ndarray or 'None', so check
if the 'convert' parameter is either an instance of ndarray or is None
"""
if isinstanc... | dacaf4aa6fd5ff9fa577a217c0209d75785abbaf | 3,643,502 |
from typing import List
def load_operators_expr() -> List[str]:
"""Returns clip loads operators for std.Expr as a list of string."""
abcd = list(ascii_lowercase)
return abcd[-3:] + abcd[:-3] | 49ba476bebbb6b202b7021458e70e6b1fb927810 | 3,643,503 |
def findScanNumberString(s):
"""If s contains 'NNNN', where N stands for any digit, return the string
beginning with 'NNNN' and extending to the end of s. If 'NNNN' is not
found, return ''."""
n = 0
for i in range(len(s)):
if s[i].isdigit():
n += 1
else:
n = 0
if n == 4:
return s[i-3:]
return '' | fd5973383bcf8b74573408d95d4f0065dfbda32f | 3,643,504 |
import urllib
def parseWsUrl(url):
"""
Parses as WebSocket URL into it's components and returns a tuple (isSecure, host, port, resource, path, params).
isSecure is a flag which is True for wss URLs.
host is the hostname or IP from the URL.
port is the port from the URL or standard port derived from sc... | 149db7e862f832baf7591fb173cd53d5259cfbba | 3,643,505 |
def load_image(filename):
"""Loads an image, reads it and returns image size,
dimension and a numpy array of this image.
filename: the name of the image
"""
try:
img = cv2.imread(filename)
print("(H, W, D) = (height, width, depth)")
print("shape: ",img.shape)
h, w... | 2f27d15cd12fcdf4656291a7349883e8d63ff7cf | 3,643,506 |
def add_manipulable(key, manipulable):
"""
add a ArchipackActiveManip into the stack
if not already present
setup reference to manipulable
return manipulators stack
"""
global manips
if key not in manips.keys():
# print("add_manipulable() key:%s not found create n... | 3d3709758a96edec261141291950d28d2079ae19 | 3,643,507 |
def get_wave_data_type(sample_type_id):
"""Creates an SDS type definition for WaveData"""
if sample_type_id is None or not isinstance(sample_type_id, str):
raise TypeError('sample_type_id is not an instantiated string')
int_type = SdsType('intType', SdsTypeCode.Int32)
double_type = SdsType('do... | e86d693ac1405b7f440065cbc5eced33adcc666f | 3,643,508 |
import random
def _spec_augmentation(x,
warp_for_time=False,
num_t_mask=2,
num_f_mask=2,
max_t=50,
max_f=10,
max_w=80):
""" Deep copy x and do spec augmentation then return it
... | caa4a9010254e13be36e2359d7437cd9f2ced084 | 3,643,509 |
def deg2rad(x, dtype=None):
"""
Converts angles from degrees to radians.
Args:
x (Tensor): Angles in degrees.
dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Tensor, the corresponding angle in radians.... | 9e7ff9f5242e5b2eede27b06eb7eb64ba84bbc69 | 3,643,510 |
import math
def point_in_ellipse(origin, point, a, b, pa_rad, verbose=False):
"""
Identify if the point is inside the ellipse.
:param origin A SkyCoord defining the centre of the ellipse.
:param point A SkyCoord defining the point to be checked.
:param a The semi-major axis in arcsec of the ellip... | 9c4b056c205b8d25e80211adb0eeb1cdfaf4c11c | 3,643,511 |
def isNumberString(value):
"""
Checks if value is a string that has only digits - possibly with leading '+' or '-'
"""
if not value:
return False
sign = value[0]
if (sign == '+') or (sign == '-'):
if len(value) <= 1:
return False
absValue = value[1:]
... | 06feaab112e184e6a01c2b300d0e4f1a88f2250e | 3,643,512 |
def vaseline(tensor, shape, alpha=1.0, time=0.0, speed=1.0):
"""
"""
return value.blend(tensor, center_mask(tensor, bloom(tensor, shape, 1.0), shape), alpha) | 75e61b21e9ffc1f13a8958ee92d0940596ae116b | 3,643,513 |
from typing import Union
from typing import Dict
from typing import Any
from typing import List
def _func_length(target_attr: Union[Dict[str, Any], List[Any]], *_: Any) -> int:
"""Function for returning the length of a dictionary or list."""
return len(target_attr) | b66a883c763c93d9a62a7c09324ab8671d325d05 | 3,643,514 |
from typing import Optional
def import_places_from_swissnames3d(
projection: str = "LV95", file: Optional[TextIOWrapper] = None
) -> str:
"""
import places from SwissNAMES3D
:param projection: "LV03" or "LV95"
see http://mapref.org/CoordinateReferenceFrameChangeLV03.LV95.html#Zweig1098
:param... | cc90f3da95bf84ff3dd854de310a6690a28fd750 | 3,643,515 |
def _generate_data(size):
""" For testing reasons only """
# return FeatureSpec('dummy', name=None, data='x' * size)
return PlotSpec(data='x' * size, mapping=None, scales=[], layers=[]) | 62cbbe947b4d20726f24503c38b9ba2c5d8bdc82 | 3,643,517 |
def configuration_filename(feature_dir, proposed_splits, split, generalized):
"""Calculates configuration specific filenames.
Args:
feature_dir (`str`): directory of features wrt
to dataset directory.
proposed_splits (`bool`): whether using proposed splits.
split (`str`): tr... | a3fc2c23746be7ed17f91820dd30a8156f91940c | 3,643,518 |
import array
def gammaBGRbuf(
buf: array,
gamma: float) -> array:
"""Apply a gamma adjustment to a
BGR buffer
Args:
buf: unsigned byte array
holding BGR data
gamma: float gamma adjust
Returns:
unsigned byte array
holding gamma adjuste... | 2d32f2ae0f1aae12f2ed8597f99b5cd5547ea108 | 3,643,519 |
def sentence_avg_word_length(df, new_col_name, col_with_lyrics):
"""
Count the average word length in a dataframe lyrics column, given a column name, process it, and save as new_col_name
Parameters
----------
df : dataframe
new_col_name : name of new column
col_with_lyric: co... | 50dd7cb7145f5c6b39d3e8199f294b788ca361c0 | 3,643,520 |
def to_sigmas(t,p,w_1,w_2,w_3):
"""Given t = sin(theta), p = sin(phi), and the stds this computes the covariance matrix and its inverse"""
p2 = p*p
t2 = t*t
tc2 = 1-t2
pc2 = 1-p2
tc= np.sqrt(tc2)
pc= np.sqrt(pc2)
s1,s2,s3 = 1./(w_1*w_1),1./(w_2*w_2),1./(w_3*w_3)
a = pc2*tc2*s1 + t2*s... | e6144c8d3313e25cd701f703703309820c60032e | 3,643,521 |
def fetch_atlas_pauli_2017(version='prob', data_dir=None, verbose=1):
"""Download the Pauli et al. (2017) atlas with in total
12 subcortical nodes.
Parameters
----------
version: str, optional (default='prob')
Which version of the atlas should be download. This can be 'prob'
for th... | c7dbf85de92c143a221d91c3dd6f452a4d79ee2f | 3,643,522 |
import traceback
def GeometricError(ref_point_1, ref_point_2):
"""Deprecation notice function. Please use indicated correct function"""
print(GeometricError.__name__ + ' is deprecated, use ' + geometricError.__name__ + ' instead')
traceback.print_stack(limit=2)
return geometricError(ref_point_1, ref_p... | aefd3a21ffa7123401af7ac2b106bc4efde624b5 | 3,643,523 |
def svn_fs_open2(*args):
"""svn_fs_open2(char const * path, apr_hash_t fs_config, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _fs.svn_fs_open2(*args) | 433e8fe01d5b6c3c7b66f8caa3c50e8386e99e92 | 3,643,524 |
def config(workspace):
"""Return a config object."""
return Config(workspace.root_uri, {}) | 6d02a61f4653742b90838a773458944a581f8ed4 | 3,643,525 |
from typing import List
from typing import Optional
def longest_sequence_index(sequences: List[List[XmonQubit]]) -> Optional[int]:
"""Gives the position of a longest sequence.
Args:
sequences: List of node sequences.
Returns:
Index of the longest sequence from the sequences list. If more... | 32aafa324daea819e48bc14516a8532c110c0362 | 3,643,526 |
def subset_raster(rast, band=1, bbox=None, logger=None):
"""
:param rast: The rasterio raster object
:param band: The band number you want to contour. Default: 1
:param bbox: The bounding box in which to generate contours.
:param logger: The logger object to use for this tool
:return: A dict wit... | 62bb0bc292fa2a9d09dc746ce329394cf9dd2fcb | 3,643,527 |
def extract_date_features(df):
"""Expand datetime values into individual features."""
for col in df.select_dtypes(include=['datetime64[ns]']):
print(f"Now extracting features from column: '{col}'.")
df[col + '_month'] = pd.DatetimeIndex(df[col]).month
df[col + '_day'] = pd.DatetimeIndex(... | 8726cf0d160de11dfbad701d6a0c7fb3113691f6 | 3,643,528 |
import copy
def record_setitem(data, attr, value):
"""Implement `record_setitem`."""
data2 = copy(data)
py_setattr(data2, attr, value)
return data2 | 52af700d8d282a411e37de83a7ddfab7f3b9de82 | 3,643,529 |
from typing import Optional
def get_git_branch() -> Optional[str]:
"""Get the git branch."""
return _run("git", "branch", "--show-current") | dee21ab7e6d9800160e161ae32fad3f9c6c6a8fb | 3,643,530 |
def open_image(path, verbose=True, squeeze=False):
"""
Open a NIfTI-1 image at the given path. The image might have an arbitrary number of dimensions; however, its first
three axes are assumed to hold its spatial dimensions.
Parameters
----------
path : str
The path of the file to be lo... | 217522c5ea45b9c1cbff8053dc9668cf5473c709 | 3,643,531 |
def add_one_for_ordered_traversal(graph,
node_idx,
current_path=None):
"""
This recursive function returns an ordered traversal of a molecular graph.
This traversal obeys the following rules:
1. Locations may... | 1c923d07c6ca57d47c900fd2cc05470c4a0eef86 | 3,643,532 |
import json
def get_subject_guide_for_section_params(
year, quarter, curriculum_abbr, course_number, section_id=None):
"""
Returns a SubjectGuide model for the passed section params:
year: year for the section term (4-digits)
quarter: quarter (AUT, WIN, SPR, or SUM)
curriculum_abbr: curri... | fe22c43685eb36e3a0849c198e6e5621e763b7a3 | 3,643,534 |
def dense_reach_bonus(task_rew, b_pos, arm_pos, max_reach_bonus=1.5, reach_thresh=.02,
reach_multiplier=all_rew_reach_multiplier):
""" Convenience function for adding a conditional dense reach bonus to an aux task.
If the task_rew is > 1, this indicates that the actual task is complete, a... | ac1b53836a2a1fd9a4cf7c725222f0e053d65ddb | 3,643,535 |
import re
def getAllNumbers(text):
"""
This function is a copy of systemtools.basics.getAllNumbers
"""
if text is None:
return None
allNumbers = []
if len(text) > 0:
# Remove space between digits :
spaceNumberExists = True
while spaceNumberExists:
... | 42d45d6bb7a5ae1b25d2da6eadb318c3388923d6 | 3,643,536 |
def optimal_string_alignment_distance(s1, s2):
"""
This is a variation of the Damerau-Levenshtein distance that returns the strings' edit distance
taking into account deletion, insertion, substitution, and transposition, under the condition
that no substring is edited more than once.
... | 9c05cfd3217619e76dd1e6063aa1aa689dc1a0ef | 3,643,537 |
def test_sanitize_callable_params():
"""Callback function are not serializiable.
Therefore, we get them a chance to return something and if the returned type is not accepted, return None.
"""
opt = "--max_epochs 1".split(" ")
parser = ArgumentParser()
parser = Trainer.add_argparse_args(parent_p... | d2a553a3c347d5ef0a2be10b21af6920a50697fb | 3,643,538 |
import six
def get_url(bucket_name, filename):
"""
Gets the uri to the object.
"""
client = storage.Client()
bucket = client.bucket(bucket_name)
blob = bucket.blob(filename)
url = blob.public_url
if isinstance(url, six.binary_type):
url = url.decode('utf-8')
return url | 15e2d5ae5cfdfeb9794c9cfef1feecbc0f1e4183 | 3,643,539 |
def distance():
"""
Return a random value of FRB distance,
choosen from a range of observed FRB distances.
- Args: None.
- Returns: FRB distance in meters
"""
dist_m = np.random.uniform(6.4332967e24,1.6849561e26)
return dist_m | c38cfa7878020bafd9fa1cafef962ed2b91bc804 | 3,643,540 |
def p10k(n, empty="-"):
"""
Write number as parts per ten thousand.
"""
if n is None or np.isnan(n):
return empty
elif n == 0:
return "0.0‱"
elif np.isinf(n):
return _("inf") if n > 0 else _("-inf")
return format_number(10000 * n) + "‱" | 6d0ff6e5b48c62ad10207c0f8a72595201042ef4 | 3,643,541 |
from typing import Any
def output_file(filename: str, *codecs: Codec, **kwargs: Any) -> Output:
"""
A shortcut to create proper output file.
:param filename: output file name.
:param codecs: codec list for this output.
:param kwargs: output parameters.
:return: configured ffmpeg output.
""... | c467331d5a2773a014f52326872b7999bf17547c | 3,643,542 |
import warnings
def convert_topology(topology, model_name, doc_string, target_opset,
channel_first_inputs=None,
options=None, remove_identity=True,
verbose=0):
"""
This function is used to convert our Topology object defined in
_parser.py into... | 139efc34473518b0403cd0bdbfc85b0b2715d576 | 3,643,544 |
def multivariate_logrank_test(event_durations, groups, event_observed=None,
alpha=0.95, t_0=-1, suppress_print=False, **kwargs):
"""
This test is a generalization of the logrank_test: it can deal with n>2 populations (and should
be equal when n=2):
H_0: all event series ... | 2d433c4651828cc962a94802eae72e0ab68e7f0b | 3,643,546 |
def ae(y, p):
"""Absolute error.
Absolute error can be defined as follows:
.. math::
\sum_i^n abs(y_i - p_i)
where :math:`n` is the number of provided records.
Parameters
----------
y : :class:`ndarray`
One dimensional array with ground truth values.
p : :c... | 6f08799429c561af37a941e0678ba0c147ba3a9c | 3,643,547 |
def create_masks_from_plane(normal, dist, shape):
"""
Create a binary mask of given size based on a plane defined by its
normal and a point on the plane (in voxel coordinates).
Parameters
----------
dist: Distance of the plane to the origin (in voxel coordinates).
normal: Normal of the plan... | c6f3995a12aa98f960364332195ac5caeb1d6fe4 | 3,643,548 |
from typing import List
def untokenize(tokens: List[str], lang: str = "fr") -> str:
"""
Inputs a list of tokens output string.
["J'", 'ai'] >>> "J' ai"
Parameters
----------
lang : string
language code
Returns
-------
string
text
"""
d = MosesDetokenizer(l... | 551ecf233b0869c4912b47ff1dee765647b07acc | 3,643,549 |
def unwrap_cachable(func):
"""
Converts any HashableNodes in the argument list of a function into their standard node
counterparts.
"""
def inner(*args, **kwargs):
args, kwargs = _transform_by_type(lambda hashable: hashable.node, HashableNode,
*args,... | 40b8f4b62045808815c67f0a22b4d8b97c9fbb1e | 3,643,551 |
def tuples_to_full_paths(tuples):
"""
For a set of tuples of possible end-to-end path [format is:
(up_seg, core_seg, down_seg)], return a list of fullpaths.
"""
res = []
for up_segment, core_segment, down_segment in tuples:
if not up_segment and not core_segment and not down_segment:
... | f5b15e0e2483d194f6cf6c3eb8ec318aadd7b960 | 3,643,552 |
def _fileobj_to_fd(fileobj):
"""Return a file descriptor from a file object.
Parameters:
fileobj -- file object or file descriptor
Returns:
corresponding file descriptor
Raises:
ValueError if the object is invalid
"""
if isinstance(fileobj, int):
fd = fileobj
else:
... | 8b1bea4083c0ecf481c712c8b06c76257cea43db | 3,643,553 |
def request_changes_pull_request(pull_request=None, body_or_reason=None):
"""
:param pull_request:
:param body_or_reason:
:return:
"""
if not pull_request:
raise ValueError("you must provide pull request")
if not body_or_reason:
raise ValueError("you must provide request ch... | 6487b8b47a8a33882010083e97ebbd57b464311b | 3,643,554 |
from typing import Callable
from typing import Union
from typing import Type
from typing import Tuple
def handle(
func: Callable,
exception_type: Union[Type[Exception], Tuple[Type[Exception]]],
*args,
**kwargs
):
"""
Call function with errors handled in cfpm's way.
Before using this funct... | d290fa4353a6e608b21464c33adc6f72675d9e6c | 3,643,555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.