content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Any
def check_int(data: Any) -> int:
"""Check if data is `int` and return it."""
if not isinstance(data, int):
raise TypeError(data)
return data | 814155f2407cd0e8b580372679f4cecfcc087d9e | 32,100 |
def UpdateStatus(key_name, status):
"""Update the status/state of the specified bug.
Args:
key_name: Key name of the bug to update.
status: A string containing the new status of the bug.
Returns:
Bug object with the updated target_element information.
"""
bug = GetBugByKey(key_name)
bug.status... | 614075959da3603cefd220d45c1e6c5c110bf17d | 32,101 |
def onehot_encoding(categories, max_categories):
"""Given a list of integer categories (out of a set of max_categories)
return one-hot enocded values"""
out_array = np.zeros((len(categories), max_categories))
for key, val in enumerate(categories):
out_array[key, int(val)] = 1.0
return out_... | 89203b285faed64b4519a2ad5234b77b4fa837aa | 32,102 |
def canny(gl_image, low_threshold=50, high_threshold=150):
"""Applies the Canny transform"""
return cv2.Canny(gl_image, low_threshold, high_threshold) | de2d7194e9df6ab4cc7cda25a0b5ccd37f81822b | 32,103 |
def res_stage(block:nn.Module, ic:int, oc:int, num_layers:int, dflag:bool=True,
btype:str='basic', fdown:bool=False):
"""
Arguments
---------
block : nn.Module
the block type to be stacked one upon another
ic : int
# of input channels
oc : int
# of output channels
... | 6cd95ba6d923265093daca2bdf888bde248dfd12 | 32,104 |
def getFirstValid(opts, default):
"""Returns the first valid entry from `opts`, or `default` if none found.
Valid is defined as ``if o`` returns true."""
for o in opts:
if o: return o
return default | 799a6ea4a993f0a112fa38b882566d72a0d223e0 | 32,105 |
from typing import Dict
from typing import Any
import json
def read_json(path: str) -> Dict[Any, Any]:
"""
Read a JSON file.
Args:
- path: The path of the JSON file.
Return:
- The data of the JSON file.
"""
_logger.debug(f"Reading JSON file: {path}")
with open(path, encoding="ut... | 7f0b2f8cf35a6edebf46caeb805efb855fbb3d37 | 32,106 |
import os
def upload_thumb():
""" Used when another app has uploaded the main file to the cloud, and is
sending the thumb for local display.
"""
image = request.files["thumb_file"]
fname = request.form["filename"]
tpath = os.path.join(IMAGE_FOLDER, "thumbs", fname)
image.save(tpath)
re... | 2638b8f6a1bf717120c2c8f16dc8702c0b5d88e9 | 32,107 |
def grid_density_gaussian_filter(data, size, resolution=None, smoothing_window=None):
"""Smoothing grid values with a Gaussian filter.
:param [(float, float, float)] data: list of 3-dimensional grid coordinates
:param int size: grid size
:param int resolution: desired grid resolution
:param int smo... | d4c833aee72d28a760584cbd995595497d740531 | 32,108 |
from typing import List
from typing import Dict
from typing import Set
from typing import Tuple
import logging
def channel_message_to_zerver_message(
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulip... | 3abd517aa2b84aaa3db803777e768324c7dac227 | 32,109 |
def print_train_time(start, end, device=None):
"""Prints difference between start and end time.
Args:
start (float): Start time of computation (preferred in timeit format).
end (float): End time of computation.
device ([type], optional): Device that compute is running on. Defaults to N... | 9935f2c12bac8e8beca38075dd6f80b7211318b7 | 32,110 |
def filter_false_positive_matches(
matches,
trace=TRACE_REFINE or TRACE_FILTER_FALSE_POSITIVE,
reason=DiscardReason.FALSE_POSITIVE,
):
"""
Return a filtered list of kept LicenseMatch matches and a list of
discardable matches given a ``matches`` list of LicenseMatch by removing
matches to fal... | 4bf9ec5c88db99c8989ca740f41b726603b892a5 | 32,111 |
def Moving_Average_ADX(data, period=14, smooth=14, limit=18):
"""
Moving Average ADX
ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend
Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/
... | 63595d9cc53999ae1e4b75c971b4388f092da649 | 32,112 |
def forbid_end(interval, function):
""" Forbids an interval variable to end during specified regions.
In the declaration of an interval variable it is only possible to specify a range of possible end times.
This function allows the user to specify more precisely when the interval variable can end.
In p... | fee64b27578f78632ed84d2575a7b2dfb6de39e2 | 32,113 |
import re
def get_all_anime(total_pages: int) -> list:
"""
Get all the anime listed on all the pages of the website.
:param total_pages: Total number of pages of HorribleSubs.
:return: List containing the names of all the anime.
"""
titles = []
for page in range(1, total_pages + 1):
... | 91160353c7b488f21fbc7ed0a50974193a4b45bf | 32,114 |
def network_generator(
rw: int,
cl: int,
b: float,
xi: float,
P: float,
mu: float,
bipartite: bool,
) -> ArrayLike:
"""
function to generate synthetic networks with nested, modular and in-block nested structures. Generates
networks with a fixed block size and increasing number of... | f9c6d615b117a2aa7ee22b7615ddcdbcaf628a71 | 32,115 |
def convert_rgb_to_hex(rgb: tuple([int, int, int])) -> str:
"""Take an RGB value and convert it to hex code.
Args:
rgb: a color represented as rgb values.
Returns:
Hex code of color or None if the RGB code is invalid.
"""
# Validate user Input is not negative or greater than 255
... | c20c6a96dbe577eff4421df28403a57e1f038e4e | 32,116 |
def localVarName(value, position):
"""A name of a class."""
if not value[0].islower():
return Error('BadLocalVariableName', 'Local variable must start with a lower case letter', position, LINES)
return None | d4f8838497109fcf41e9c904aaddc31edd69eadc | 32,117 |
def nodeAndOutputFromScenegraphLocationString(string, dag):
"""
Returns a tuple containing the node defined in a location string and its
corresponding Output.
"""
try:
outputNodeUUID = uuidFromScenegraphLocationString(string)
outputNode = dag.node(nUUID=outputNodeUUID)
outputNodeOutputName = string.split(":... | d7fa1f03b3121f4dbcc9baac8c94bb5113fbc378 | 32,118 |
def rivers_with_station(stations):
"""Returns the names of rivers on which a station is situated"""
return set(stations_by_river(stations).keys()) | c2e78ff18c3fdc73f04e145beae77d914a0ee287 | 32,119 |
def check_string_is_nonempty(string, string_type='string'):
"""Ensures input is a string of non-zero length"""
if string is None or \
(not isinstance(string, str)) or \
len(string) < 1:
raise ValueError('name of the {} must not be empty!'
''.format(string_type))... | 527e60b35f6a827ee9b1eae3c9a3f7abc596b7ff | 32,120 |
def last_frame_with_txt(vid, txt, duration):
"""Take the last frame from vid, show it for duration with txt overlay."""
frame = list(vid.iter_frames())[-1]
clip = ImageClip(frame, duration=duration)
return CompositeVideoClip([
clip,
TextClip(txt, font=MOVIEPY_FONT, color='black', bg_colo... | e7a62332cb4ae69addc12bc679eb30479432caf2 | 32,121 |
import torch
def load_dataset(dataset_size=100, dataset_start=0, shuffle=True, sentence_level=False, n_authors=15, k=5, features=u""):
"""
Load dataset
:return:
"""
# Load from directory
if sentence_level:
reutersc50_dataset = torchlanguage.datasets.ReutersC50SentenceDataset(
... | 2ace76a461699e9f0bdf7ca838d414a3c618898a | 32,122 |
def df_as_table(dataframe, size='50'):
"""
:param dataframe: pandas dataframe to be displayed as a HTML table
:param size: string to set realtive table size in percent standard 50%
:return: string containing a html table
"""
shape = dataframe.shape
n_cols = shape[1]
n_rows = shape[0]
... | 3634a90b3e3d4ef5c8cc737e19a0540305528959 | 32,123 |
def ecdh(privkey, pubkey):
"""
Given a loaded private key and a loaded public key, perform an ECDH exchange
:param privkey:
:param pubkey:
:return:
"""
return ecdsa.ecdh(privkey, pubkey) | 650607024f3fcd10fd7649897461c69a3d80596b | 32,124 |
import getpass
def update_config_cli():
"""Get config from command line and write to a file"""
cfg = Config()
# FIXME: improve CLI experience
print('Note: Enter blank to keep the current value.')
for key in CFG_KEYS:
# Show (or hide) current value
if key in ENCRYPTED:
... | 981f843f25171cab69554658f9866a3551d13770 | 32,125 |
def portfolio_margin_account(self, **kwargs):
"""Get Portfolio Margin Account Info (USER_DATA)
GET /sapi/v1/portfolio/account
https://binance-docs.github.io/apidocs/spot/en/#get-portfolio-margin-account-info-user_data
Keyword Args:
recvWindow (int, optional): The value cannot be greater than 60... | 88a1087d44187ed130211ab7d42fdcbb54a038f3 | 32,126 |
from typing import Any
from typing import Mapping
def init_hyperparams(*, class_name: str, hyperparams, hyperparams_class) -> Any:
"""
Construct a hyperparams object from either a mapping or another hyperparams object.
"""
if isinstance(hyperparams_class, type) and is_dataclass(hyperparams_class):
... | 2aa4ebc5ec9e6d4502f7873e6517dc5285f8604e | 32,127 |
import sys
def get_theta(k, lamada, sequence, alphabet):
"""Get the theta list which use frequency to replace physicochemical properties(the kernel of ZCPseKNC method."""
theta = []
L = len(sequence)
kmer = make_km_list(k, alphabet)
fre_list = [frequency_p(sequence, str(key))[0] for key in kmer]
... | 48624bb1c51315315874c9f7bff4d69f5dc15285 | 32,128 |
def _is_y(filename):
"""
Checks whether a file is a Nanometrics Y file or not.
:type filename: str
:param filename: Name of the Nanometrics Y file to be checked.
:rtype: bool
:return: ``True`` if a Nanometrics Y file.
.. rubric:: Example
>>> _is_y("/path/to/YAYT_BHZ_20021223.124800") ... | adbb75533934d5050658b8a5078e66438b3381df | 32,129 |
def is_scheduler_filter_enabled(filter_name):
"""Check the list of enabled compute scheduler filters from config. """
filters = CONF.compute_feature_enabled.scheduler_available_filters
if len(filters) == 0:
return False
if 'all' in filters:
return True
if filter_name in filters:
... | f40e99f49a49aa24e66de72bad82b87ccf6ae8a2 | 32,130 |
from m2py.numerical.roots import nraphson
def juros_price(PV, PMT, n, PV0=0):
"""
Calcula taxa de juros de um parcelamento pela table price
Usado comummente em cŕedito concedido ao consumidor
:param PV: Valor a Vista / Valor Presente
:param PV0: Entrada
:param PMT: Valor da Parcela
... | d593f27616c7028b39e80dff47a446a40fe43338 | 32,131 |
import json
import re
def delexicalisation(out_src, out_trg, category, properties_objects):
"""
Perform delexicalisation.
:param out_src: source string
:param out_trg: target string
:param category: DBPedia category
:param properties_objects: dictionary mapping properties to objects
:return: delexicalised stri... | 55108ff40e8739571a99a3481221c82c0fcbf255 | 32,132 |
def create_attention_mask_from_input_mask_v1(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor o... | 0f83dd4a2e5cf904f19f89ce5b42e562c4ba401e | 32,133 |
import hashlib
def md5(filename):
"""Hash function for files to be uploaded to Fl33t"""
md5hash = hashlib.md5()
with open(filename, "rb") as filehandle:
for chunk in iter(lambda: filehandle.read(4096), b""):
md5hash.update(chunk)
return md5hash.hexdigest() | 35068abafee2c5c4b1ac672f603b0e720a8c9a8c | 32,134 |
from typing import Iterable
from typing import Any
from typing import Tuple
def pairwise(iterable: Iterable[Any]) -> Iterable[Tuple[Any, Any]]:
""" Divide the given iter into pairs and return as tuple pairs.
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = tee(iterable)
next(b, None)
return zi... | c9867a51d238ee51a993465b1757b387d0c9be6a | 32,135 |
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) | 441466f163a7b968cf193e503d43a1b014be7c5d | 32,136 |
def rightToPurchase(
symbol="", refid="", token="", version="", filter="", **timeseries_kwargs
):
"""Right to purchase up-to-date and detailed information on all new announcements, as well as 12+ years of historical records.
Updated at 5am, 10am, 8pm UTC daily
https://iexcloud.io/docs/api/#right-to-pu... | 8897902c7b729642cdd5e89658f62b70bccf2133 | 32,137 |
def compute_edits(old, new):
"""Compute the in-place edits needed to convert from old to new
Returns a list ``[(index_1,change_1), (index_2,change_2)...]``
where ``index_i`` is an offset into old, and ``change_1`` is the
new bytes to replace.
For example, calling ``compute_edits("abcdef", "qbcdzw"... | f729addf84207f526e27d67932bb5300ced24b54 | 32,138 |
def gpx_to_lat_lon_list(filename):
"""
Summary: takes a .gpx file and turns the latitude and longitudes into a list of tuples
Returns: list of tuples (latitude, longitude).
"""
gpx_file = open(filename, "r")
gpx = gpxpy.parse(gpx_file)
latlonlist = []
if len(gpx.tracks) > 0:
... | 4d413a5894a30bb176a103b8a3933685490f30fe | 32,139 |
def pre_order(size):
"""List in pre order of integers ranging from 0 to size in a balanced
binary tree.
"""
interval_list = [None] * size
interval_list[0] = (0, size)
tail = 1
for head in range(size):
start, end = interval_list[head]
mid = (start + end) // 2
if mid ... | 45ab688c627c19cd0b9c1200830a91b064d46bda | 32,140 |
def LockPrefix():
"""Returns the lock prefix as an operand set."""
return set([Operands(disasms=('lock',))]) | d4f84027494ad176efcb8c01f14876474aaca57f | 32,141 |
def distance(pt, pts):
"""Distances of one point `pt` to a set of points `pts`.
"""
return np.sqrt((pts[:,0] - pt[0])**2 + (pts[:,1] - pt[1])**2) | 06512472ac6c0e58182ad58190c82fa619d66d40 | 32,142 |
def prepare_rw_output_stream(output):
"""
Prepare an output stream that supports both reading and writing.
Intended to be used for writing & updating signed files:
when producing a signature, we render the PDF to a byte buffer with
placeholder values for the signature data, or straight to the provid... | af1afe87e5de12cad9eb72b93da069327c1fffb5 | 32,143 |
from pathlib import Path
def add_references(md, tmp_dir, args):
"""
Remember that this function is run for main, review, and editor.
"""
citations_to_do = tmp_dir / 'citations.json'
biblio = Path(args.library).with_suffix('.json')
_prepare_node_input(md, citations_to_do)
_check_citation_... | 5c4319720a809c9e6543ef078598b7a3539c3492 | 32,144 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Purpose: Create Workout Of (the) Day (WOD)',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f',
'--file',
... | 2f320b4c4093a263c5eb69f0784344299389465c | 32,145 |
from pandas import Timestamp
def timestamp_now() -> Timestamp:
"""Returns a pandas timezone (UTC) aware Timestamp for the current time.
Returns:
pandas.Timestamp: Timestamp at current time
"""
return timestamp_tzaware(Timestamp.now()) | 545b0cb72691d3db127ccfc847295a4bc4902004 | 32,146 |
def readFlat4D(fn,interp=None):
"""
Load in data from 4D measurement of flat mirror.
Scale to microns, remove misalignments,
strip NaNs.
Distortion is bump positive looking at surface from 4D.
Imshow will present distortion in proper orientation as if
viewing the surface.
"""
#Get xp... | 8443ab4943bb571d1ead1f8f4342efec8e426139 | 32,147 |
def inner_product(D1, D2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for key in D1:
if key in D2:
result += D1[key] * D2[key]
return result | 95efb9f63d6a379e1c5f7c8f6ad4bfd4061e2032 | 32,148 |
def list_launch_daemons():
"""
Return an array of the files that are present in /Library/LaunchDaemons/
and /System/Library/LaunchDaemons/
"""
files = list_files_in_dir("/Library/LaunchDaemons/")
files += list_files_in_dir("/System/Library/LaunchDaemons/")
return files | 8e1f0ab1bb78a9121f5c00f032a5c8dc089f39b0 | 32,149 |
import six
import sys
def decode(input, errors='strict'):
""" convert from wtf-8 encoded bytes to unicode text.
If this is a python narrow build this will actually
produce UTF-16 encoded unicode text (e.g. with surrogates).
"""
buf = []
try:
it = six.iterbytes(input)
c... | ddb96ea0e5a12cd5e5b60f868dcd6522cecce86a | 32,150 |
import struct
def us_varchar_encode(text):
"""
encode with utf-16-le
UShort *Varchar
:param str text:
:return:
"""
if not text:
return '\x00\x00'
length = len(text)
return struct.pack('<H', length) + text.encode('utf-16-le') | 07b232cd83e023d770fc4e7cd63250ad746aae19 | 32,151 |
from typing import List
def graph_to_diagonal_h(n: int, nodes: List[int]) -> np.ndarray:
"""Construct diag(H)."""
h = [0.0] * 2**n
for node in nodes:
diag = tensor_diag(n, node[0], node[1], node[2])
for idx, val in enumerate(diag):
h[idx] += val
return h | 5c73d4b4a98465f3f03d9a423f867479b48da8fe | 32,152 |
def condensational_heating(dQ2):
"""
Args:
dQ2: rate of change in moisture in kg/kg/s, negative corresponds
to condensation
Returns:
heating rate in degK/s
"""
return tf.math.scalar_mul(tf.constant(-LV / CPD, dtype=dQ2.dtype), dQ2) | 55d5ec36bf1f4a217e239e35fb95e14060b07fb8 | 32,153 |
def collect_stats(cube, store, datasets=None):
"""
Collect statistics for given cube.
Parameters
----------
cube: Cube
Cube specification.
store: simplekv.KeyValueStore
KV store that preserves the cube.
datasets: Union[None, Iterable[str], Dict[str, kartothek.core.dataset.Da... | 526405128e95e13fb6f011300ddcda922ebe8582 | 32,154 |
def post_move_subject(subject_uuid: SubjectId, target_report_uuid: ReportId, database: Database):
"""Move the subject to another report."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
source = SubjectData(data_model, reports, subject_uuid)
target = ReportData(data_mode... | 405be11279fe3fa2a65b75ac46518cdaabcb5e90 | 32,155 |
import sympy
def makefunction(exprs, assignto, funcname='func', returncodestr=False, usenumba=True):
"""
Given sympy expressions list `expr` and a list of variable names
`assignto`, it creates a function. It returns a function object if
`returncodestr` = False. Otherwise, it returns a formatted functi... | 1ba503589fe18f6678f1ddc1a535978433837276 | 32,156 |
def open_instrument(instr_type):
"""open_visa_instrument implements the public api for each of the drivers for discovering and opening a connection
:param instr_type:
The abstract base class to implement
A dictionary containing the technical specifications of the required equipment
:return:
A i... | 1741b94a527a0283efee7466ccc15be09abe1622 | 32,157 |
import jinja2
from datetime import datetime
def thisyear():
"""The current year."""
return jinja2.Markup(datetime.date.today().year) | 3de970398e1fb55f98a968c0c83411d18e8cd423 | 32,158 |
from unicodedata import east_asian_width
def display_width(str):
"""Return the required over-/underline length for str."""
try:
# Respect &ambiwidth and &tabstop, but old vim may not support this
return vim.strdisplaywidth(str)
except AttributeError:
# Fallback
result = 0
... | ebeedd159de5c31ea435d44a88fe6fe16ccbcb54 | 32,159 |
def get_short_int(filename, ptr):
"""Jump to position 'ptr' in file and read a 16-bit integer."""
val = get_val(filename, ptr, np.int16)
return int( val ) | 42377a73df1dfbff2593fa43e571e3d269db6449 | 32,160 |
def u32_from_dto(dto: U32DTOType) -> int:
"""Convert DTO to 32-bit int."""
check_overflow(0 <= dto <= U32_MAX)
return dto | 066ab2c2ed70d69ac8e37515ea815e1305574eea | 32,161 |
def diagonal_basis_commutes(pauli_a, pauli_b):
"""
Test if `pauli_a` and `pauli_b` share a diagonal basis
Example:
Check if [A, B] with the constraint that A & B must share a one-qubit
diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this
function would return Tr... | b95ac0cfe22233432df3a0e0f814c4e0e7af6d0f | 32,162 |
def cost_using_SigmoidCrossEntropyWithLogits(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've bee... | 7990ee4cb4b4ebfc7b5f1f580be2315ee6667fa5 | 32,163 |
def clone_to_df(clone):
"""Convert a clone to a pandas.DataFrame."""
number_of_mutations = clone.deltas.shape[0]
clone_stats = pd.DataFrame(
np.stack([clone.frequencies for _ in range(number_of_mutations)]),
columns=clone.frequencies.index,
index=clone.deltas.index
)
clone_st... | e383241b024d5deef7022be3d04b36f4ffcee587 | 32,164 |
import os
def get_points_on_rim(mesh_dir, scale=1.2, obj_name='cup'):
"""This will return me points which lie on the rim of the cup or bowl
"""
assert os.path.exists(mesh_dir)
meshes = [osp.join(mesh_dir, m) for m in os.listdir(mesh_dir) if "visual" not in m]
meshes = [m for m in meshes if "conve... | b654aa85057c61fd20753f0660565e9c35d8670b | 32,165 |
def reorder_kernel_weight(torch_weight):
""" Reorder a torch kernel weight into a tf format """
len_shape = len(torch_weight.shape)
transpose_target = list(range(len_shape))
transpose_target = transpose_target[2:] + transpose_target[:2][::-1]
return torch_weight.transpose(transpose_target) | 2e289d768d31d3ed875fbb3613ec0e3061b65cd9 | 32,166 |
def make_windows(x, window_size, horizon):
"""
Creates a window out of
"""
# Create a window of specific window size
window_step = np.expand_dims(np.arange(window_size+horizon), axis=0)
# Create a 2D array of multiple window steps
window_indices = window_step + np.expand_dims(np.arang... | 4e226e2ee2c3951cd2dfe6cb4a92b9d66e9376bf | 32,167 |
def interpolate(arr_old, arr_new, I_old, J_old):
# deprecated 2013-08-26
"""
input: array, i, j
output: value
(int(x),
int(y)+1)
+ + (int(x)+1, int(y)+1)
(x,y)
+ + (int(x)+1, int(y))
(int(x),
int(y))
be careful - floor(x)=ceil(x)=x for intege... | bcb34c33ca462c43390ff0dd8802d05dc0512dd3 | 32,168 |
from typing import Optional
from typing import Union
import os
def create_tif_file(left: float, bottom: float, right: float, top: float, to_file: Optional[str] = None,
cache_dir: str = CACHE_DIR, nodata: int = 0) -> Union[str, MemoryFile]:
"""Create a TIF file using SRTM data for the box def... | 025eb5c5c70e0c2e9d4583bb291ff6caf25bedc4 | 32,169 |
def point_seg_sep(ar, br1, br2):
"""Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
... | a036f4ea9e9c308002e18e75111aed4408d75cf4 | 32,170 |
def get_creds():
"""
Function which will take no arguments, but look for API credentials which are stored on the internet.
Unfortunately, this is the most recognizable and weakest part of the code, since it fetches the creds
from the same places over and over again.
TODO: Rework this so we're not ha... | 0d7c002aa9b04df1baaa6258d84ca6ca8d3c40da | 32,171 |
from typing import Callable
def shd(node_1: BinaryTreeNode,
node_2: BinaryTreeNode,
hd: Callable[[BinaryTreeNode, BinaryTreeNode], float]) -> float:
"""Structural Hamming distance (SHD)
:param node_1:
:param node_2:
:param hd:
:return:
"""
if node_1 is None or node_2 is No... | c6aef0189d41887fc4e63991d0176a27b0e1dd8a | 32,172 |
import numpy
def movmeanstd(ts, m=0):
"""
Calculate the mean and standard deviation within a moving window passing across a time series.
Parameters
----------
ts: Time series to evaluate.
m: Width of the moving window.
"""
if m <= 1:
raise ValueError("Query length must be long... | 8a9e56db4f26862bff972a3dbfac87f6ea5b8c35 | 32,173 |
def importing_regiondata():
"""
Loads the regiondata
Should convert the year column to proper year
Should immediately create geopandas dataframe
Returns: a dataframe
"""
regiondata = pd.read_stata("data/regiondata.dta")
return regiondata | 132e4076e941f4451b6bb52c5d81c5895dde0154 | 32,174 |
from rdkit import Chem
def load_docked_ligands(
pdbqt_output: str) -> Tuple[List[RDKitMol], List[float]]:
"""This function loads ligands docked by autodock vina.
Autodock vina writes outputs to disk in a PDBQT file format. This
PDBQT file can contain multiple docked "poses". Recall that a pose
is an ener... | bf7f6def099ccd3f3b54e431db6b944f85e49a2e | 32,175 |
def rotationFromQuaternion(*args):
"""rotationFromQuaternion(float pA, float pB, float pC, float pD) -> Rotation"""
return _almath.rotationFromQuaternion(*args) | e418bf864246ef209291d970e9cf33f0edc3fe8f | 32,176 |
import re
def get_username(identifier):
"""Checks if a string is a email adress or not."""
pattern = re.compile('.+@\w+\..+')
if pattern.match(identifier):
try:
user = User.objects.get(email=identifier)
except:
raise Http404
else:
return user.use... | de5eb0db99b9580cd210f733cd2e829c84593573 | 32,177 |
def halo_particles(mock_dm_halo):
"""Spherical mock halo."""
def make(N_part=100, seed=None):
random = np.random.RandomState(seed=seed)
mass_dm, pos_dm = mock_dm_halo(N_part=N_part)
vel_dm = random.random_sample(size=(N_part, 3))
return mass_dm, pos_dm, vel_dm
return make | 36c980c0d81c4a1edf09feec9aafcf1605968bb3 | 32,178 |
from typing import Dict
from typing import Any
import torch
def TensorRTCompileSpec(compile_spec: Dict[str, Any]) -> torch.classes.tensorrt.CompileSpec:
"""
Utility to create a formated spec dictionary for using the PyTorch TensorRT backend
Args:
compile_spec (dict): Compilation settings includin... | 0274d315d97eb3b138b53db73374642207abefc5 | 32,179 |
def get_sec (hdr,key='BIASSEC') :
"""
Returns the numpy range for a FITS section based on a FITS header entry using the standard format
{key} = '[{col1}:{col2},{row1}:row2}]'
where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2.
"""
if key in hdr :
s = hdr.get(key) # WITHOUT CARD COMMENT
ny = hdr['NAXIS2']
sx = ... | 3927e6f5d62818079fa9475976f04dda1824e976 | 32,180 |
import numpy
def _fetch_object_array(cursor, type_tree=None):
"""
_fetch_object_array() fetches arrays with a basetype that is not considered
scalar.
"""
arrayShape = cursor_get_array_dim(cursor)
# handle a rank-0 array by converting it to
# a 1-dimensional array of size 1.
if len(ar... | b4e262ec7fc4dba943ab2f8420add12f59aed4eb | 32,181 |
import pickle
def load_training_batch(batch_id, batch_size):
"""Load the Preprocessed Training data and return them in batches of <batch_size> or less"""
filename = 'data/cifar_pickle/' + 'batch_' + str(batch_id) + '.pkl'
features, labels = pickle.load(open(filename, mode='rb'))
return batch_features_... | 4aa762a80dde638d71076a888613606a1ee11a48 | 32,182 |
import subprocess
def check_gzip(f):
"""Checks if a local gzipped file is ok
Runs gunzip -t on the file using subprocess. Returns True on returncode 0.
"""
status = subprocess.run(["gzip", "-t", f], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if status.returncode == 0:
return True
... | c703e1dc39631c581cf9d6b4658160237b6ca27f | 32,183 |
def reason_key_for_alert(alert):
"""Computes the reason key for an alert.
The reason key for an alert is used to group related alerts together. Alerts
for the same step name and reason are grouped together, and alerts for the
same step name and builder are grouped together.
"""
# FIXME: May need something ... | 199d19360d45a7eeb1cbd09fa320d93c215a4be7 | 32,184 |
import logging
import json
def get_record(params,record_uid):
"""Return the referenced record cache"""
record_uid = record_uid.strip()
if not record_uid:
logging.warning('No record UID provided')
return
if not params.record_cache:
logging.warning('No record cache. Sync down ... | 7fce71c2f90387272a9c9b0a61ad4cccabf830f5 | 32,185 |
def get_probabilities(path, seq_len, model, outfile, mode):
"""
Get network-assigned probabilities
Parameters:
filename (str): Input file to be loaded
seq_len (int): Length of input DNA sequence
Returns:
probas (ndarray): An array of probabilities for the test set
true ... | a75bc11704538d082ecf91a61765f4412ec2c75d | 32,186 |
import aiohttp
import virtualenv_support
import async_timeout
import chardet
import multidict
import yarl
import idna
import pip
import setuptools
import virtualenv
import os
import shutil
def install_dependencies(python) -> str:
"""
Copy aiohttp and virtualenv install locations (and their transitive
depe... | f2378db840c1c59b41adb292cc0640380593003f | 32,187 |
from azure.mgmt.sql import SqlManagementClient
from azure.cli.core.commands.client_factory import get_mgmt_service_client
def get_sql_management_client(_):
"""
Gets the SQL management client
"""
return get_mgmt_service_client(SqlManagementClient) | 6f67408fdecbe9b1a70ffbc34a4871c796e0f9f6 | 32,188 |
def string_to_gast(node):
"""
handles primitive string base case
example: "hello"
exampleIn: Str(s='hello')
exampleOut: {'type': 'str', 'value': 'hello'}
"""
return {"type": "str", "value": node.s} | a3dcd89e893c6edd4a9ba6095cd107bb48cc9782 | 32,189 |
def ed25519_generate_key_pair_from_secret(secret):
"""
Generate a new key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
A tuple of (private_key, public_key) encoded in base58.
"""
# if you want to do this correctly, use a key derivation function... | 25b8c18289c4cf8f09a7ba937fc8f9645406e9f2 | 32,190 |
from typing import List
import math
def align_tiles_naive(request: AlignNaiveRequest,
tiles: List[TileModelDB]) -> List[AlignedTiledModel]:
"""
performs a naive aligning of the tiles simply based on the given rows and method.
does not perform any advanced stitching or pixel c... | b279273d800a6884ad95f43f0a6a6f3be1ac3243 | 32,191 |
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area,
wing_span, TURBOPROP):
""" The function estimates the operating empty mass (OEM)
Source: Raymer, D.P. "Aircraft design: a conceptual approach"
AIAA educational Series, Fourth edition (2006)... | 5b9bed8cef76f3c10fed911087727f0164cffab2 | 32,192 |
def var_gaussian(r, level=5, modified=False):
"""
Returns the Parametric Gaussian VaR of a Series or DataFrame
"""
# compute the Z score assuming it was Gaussian
z = norm.ppf(level/100)
if modified:
# modify the Z score based on observed skewness and kurtosis
s = skewness(r)
... | 18d3b1ee2228fafaaf977b216245c8217e77396b | 32,193 |
def grid_search_serial(data, greens, misfit, grid):
"""
Grid search over moment tensors. For each moment tensor in grid, generates
synthetics and evaluates data misfit
"""
results = np.zeros(grid.size)
count = 0
for mt in grid:
print grid.index
for key in data:
... | fa0a2c19cfbfa685d59f3effea7b3f7478999f88 | 32,194 |
def getSqTransMoment(system):
"""//Input SYSTEM is a string with both the molecular species AND the band "system"
// Electronic transition moment, Re, needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2
// //Allen's Astrophysical quantities, 4.12.2 - 4.13.1
// // ROtational & vibrational constants for... | 19c5311f7d8fde4bb834d809fd2f6ed7dd2c036e | 32,195 |
def volumes(assets,
start,
end,
frequency='daily',
symbol_reference_date=None,
start_offset=0,
use_amount=False):
"""
获取资产期间成交量(或成交额)
Parameters
----------
assets (int/str/Asset or iterable of same)
Identifiers ... | e2e0a7d6bd8b659e070299d00699d8cae6ed3c9f | 32,196 |
from datetime import datetime
import os
import requests
import re
import zlib
def fetch(path, url=None):
"""Fetches a file from either url or accession id in filename,
updates file if local version is older.
Checks a given path for file and downloads if a url is given or
file name is an accession id.... | 57e74f4565906452684526535b8a2cdbeefd9f7d | 32,197 |
def qipy_action(cd_to_tmpdir):
""" QiPy Action """
return QiPyAction() | 7c6d828c4baf29d2f457f02b0b54e6c967d96cb3 | 32,198 |
from twistedcaldav.directory.calendaruserproxy import ProxyDBService
def recordProxyAccessInfo(directory, record):
"""
Group membership info for a record.
"""
# FIXME: This proxy finding logic should be in DirectoryRecord.
def meAndMyGroups(record=record, groups=set((record,))):
for group... | 280e7340aa21ec4fd64a8ea2d892b7f67d9a4da5 | 32,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.