content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def moist_potential_temperature(T, p, m):
"""
Compute Moist Potential Temperature.
Parameters
----------
T: numpy array or xarray DataArray
Temperature (K).
p: numpy array or xarray DataArray
Pressure (Pa).
m: numpy array or xarray DataArray
M... | de1ffa06f0a5d12913f89cff1492bda927d5bea3 | 3,605,800 |
def collect_int_polynomial_coeff(poly):
"""Give an polynomial p, normalize it
return a list of triple: (coeff, var_name, power)
"""
assert poly.get_type() == IntType, "%s should be an integer term" % str(poly)
p = simp_full().get_proof_term(poly).rhs
triple = []
while p.is_plus() or p.is_tim... | caf191014e6a9c68dd231c11a535b6dc5bb6922d | 3,605,801 |
def args_to_dictionary(default_msg:str = "", boolean_options:list=[], arguments:list=SYSTEM_ARGUMENTS) -> dict:
"""
A function that returns a dictionary of the system arguments passed to the program.
-> default_msg: str => A default message to be displayed when the program is called without any arguments.
... | ac910c64df39bcfff0c5fb5c65f3791d5ae26735 | 3,605,802 |
def get_cores(method="", **query):
"""Gets all core parts based on query strings
Gets all core parts based on query strings
from the API
Parameters
----------
method : str (optional)
the method used for the request
query : keyword args
keyword args b... | eaea5a390a5e91867416301eb616c96ab7d15041 | 3,605,803 |
def get_model_field(model, field_label):
"""
Returns model's field.
"""
for field in model._meta.fields:
column_field = field_label
if isinstance(field, models.ForeignKey):
column_field += '_id'
if field.attname == column_field:
return field | 2293d057673fea84b4b339a5eb6529fc198934c7 | 3,605,804 |
def geographical_aligned_velocities(od):
"""
Compute zonal and meridional velocities from U and V on orthogonal curvilinear grid.
.. math::
(u_{zonal}, v_{merid}) = (u\\cos{\\phi} - v\\sin{\\phi}, u\\sin{\\phi} + v\\cos{\\phi})
Parameters
----------
od: OceanDataset
... | 8065432d0ca807283c4a3e1a43b780b41c10819a | 3,605,805 |
def identify_marz(origin, *args, **kwargs):
"""
Identify if the current file is a OzDES file
"""
file_obj = args[0]
if isinstance(file_obj, fits.hdu.hdulist.HDUList):
hdulist = file_obj
else:
hdulist = fits.open(file_obj, **kwargs)
header = hdulist[0].header
if "AAOMEGA... | 0da1cccca5b4a3cd8af2457fb789fdcbc6dd99b5 | 3,605,806 |
import os
def get_db_client():
"""Return an authenticated connection to DocumentDB"""
# Use a global variable so Lambda can reuse the persisted client on future invocations
global db_client
if db_client is None:
logger.debug('Creating new DocumentDB client.')
try:
cluster... | 47971ba83e3aa62c6230cdf162c46d6a1d25a32d | 3,605,807 |
def lock_oj_updating(oj_name):
"""
当OJ更新时锁定OJ,避免重复更新造成冲突。
:param oj_name: OJ的name项
:return: 操作结果
"""
oj = database_get(OJ, name=oj_name)
if oj is None:
return operation_failed(InfoType.NotExists, InfoField.OJ)
oj.updating = True
oj.save()
return operation_succeeded() | 96254a0d2b675efdeec7ad8f1364847da3e44d43 | 3,605,808 |
def check_range(cell_range):
"""Checks if the range is valid."""
# TODO
return True | 0fe88b09e40034c9dbc300ae4af2a15f0d942388 | 3,605,809 |
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):
"""
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
subproblem = 1 if subproblem == "" else subproblem
s... | 03c8f8a189569fee6c37f09dd1b43f1a6b64040a | 3,605,810 |
import os
def get_file_id_to_captions(caption_starts, max_length):
"""Get a map from file_id to a list of captions
Captions are filtered by caption_starts and max_length
Parameters
----------
caption_starts: set
set of strings that a caption must start with
max_length: int
ma... | 97cc4c30ba0f70543b48a63ec949b71e842e3c9e | 3,605,811 |
def spectral_projection(u, eigenpairs):
"""
Returns the coefficients of each eigenvector
in a projection of the vector u onto the normalized
eigenvectors which are contained in eigenpairs.
eigenpairs should be a list of two objects. The
first is a list of eigenvalues and the second a list
... | 2b877e2e9a606c449b38101e1a23504bff999409 | 3,605,812 |
import numpy
def solve_antenna_gains_itsubs_scalar(gain, gwt, x, xwt, niter=30, tol=1e-8, phase_only=True, refant=0,
damping=0.5):
"""Solve for the antenna gains
x(antenna2, antenna1) = gain(antenna1) conj(gain(antenna2))
This uses an iterative substitution algorith... | 1a76a922fb5ba2fe402240048b35482b92a1d135 | 3,605,813 |
def _format_specification(language, specification):
# type: (str, str) -> str
"""
Formats a "language://interface" string
:param language: Specification language
:param specification: Specification name
:return: A formatted string
"""
return "{0}:/{1}".format(language, _escape_specifica... | bceb95255193680b4ad247ee851dbbf6739b41b1 | 3,605,814 |
def fix_cropBox(img, bbox, input_size):
"""Crop bbox from image by Affinetransform.
Parameters
----------
img: torch.Tensor
A tensor with shape: `(3, H, W)`.
bbox: list or tuple
[xmin, ymin, xmax, ymax].
input_size: tuple
Resulting image size, as (height, width).
Re... | 21fcbd29bbffecdf72a43908d0f4e86778c711fd | 3,605,815 |
def get_default_dictionary_path(fuzz_target_path):
"""Return default dictionary path."""
return fuzzer_utils.get_supporting_file(fuzz_target_path,
DICTIONARY_FILE_EXTENSION) | b3269382cf338cde8a0cd4a139eaa2201c98724f | 3,605,816 |
def _get_native_location(name):
# type: (str) -> str
"""
Fetches the location of a native MacOS library.
:param name: The name of the library to be loaded.
:return: The location of the library on a MacOS filesystem.
"""
return '/System/Library/Frameworks/{0}.framework/{0}'.format(name) | 53cb9ac2a771883b791a111e53e23bd77c08f43b | 3,605,817 |
def block_spec_decoder(specs, width_scale, depth_scale):
"""Decodes and returns specs for a block."""
decoded_specs = []
for s in specs:
s = s + (
width_scale,
depth_scale,
)
decoded_specs.append(BlockSpec(*s))
return decoded_specs | 4a34f81275a0a7ed4d7db25fdc1144a41cc7088f | 3,605,818 |
import socket
def PortOpen(port, address=None):
"""
Detect whether the port is open, that is a socket is currently using that port.
Open ports are currently in use by an open socket and are therefore not available
for a server to listen on them.
Returns:
True if there is a connection cur... | 7ef609bc68dba45df3d8773d5d8fb2217b05bf43 | 3,605,819 |
def ra2float(ra):
"""
Convert ra to degress (float).
ra can be given as a time string, HH:MM:SS.SS or as string like '25.6554'
or (trivially) as a float.
An exception is thrown if ra is invalid
360 deg = 24 hrs, 360/24 = 15
"""
if ra is None:
return ra
if type(ra) is float or... | d16e1163f9e821fdff4344eacf7c29b08a8ba266 | 3,605,820 |
def split_unknown_args(argv: list[str]) -> tuple[list[str], list[str]]:
"""Separate known command-line arguments from unknown one.
Unknown arguments are separated from known arguments by
the special **--** argument.
:param argv: command-line arguments
:return: tuple (known_args, unknown_args)
""... | 14e6f202e105cb1001563e9a5a5fc1c5f4bd9fd0 | 3,605,821 |
import os
def get_data_for_regions(data, regions):
"""Return list of DataFrames limited to given regions"""
if len(regions)==1 and os.path.isfile(regions[0]) or os.path.islink(regions[0]):
fn = regions[0]
regions = []
for l in open(fn):
ldata = l[:-1].split("\t")
... | 5bfabd94ecc6648ef7381e31b98109ead884742a | 3,605,822 |
import shlex
import logging
def acquire_commands(command_args):
"""
Given the command_args list passed from the command line, returns a
list of commands to use for job submission. If command_args is None,
the user will be prompted to supply commands from stdin. Otherwise,
the returned commands lis... | 66261cd4adc127d3a12c666261b2df220de7cb39 | 3,605,823 |
def season_validation(season):
""" Decide if the season inputs are valid then return valid inputs.
Parameters:
season(str): A user's inputs to the season factor.
Return:
(str): Valid strings without commas or spaces or characters.
"""
def is_valid_digit(season):
... | 8633c7a1a39103daa212a227317a7d147c3a4bb3 | 3,605,824 |
def byte_to_megabyte(byte):
"""
Convert byte value to megabyte
"""
return byte / (1024.0 ** 2) | 1b410bcec539e3946a7b5751b984758f89a7ed96 | 3,605,825 |
def do_get_power_on_value(i2c_hat):
"""Gets the I2C-HAT digital outputs power on value. The exported robotframework keyword is 'DO Get Power On Value'.
Args:
i2c_hat (I2CHat): board
Returns:
int: The power on value of the digital outputs
"""
return i2c_hat.dq.power_... | 2aa236ba010ad5a73836b8c2b5c218cd59a4ecde | 3,605,826 |
def jump_instruction(args: list, register_copy: dict):
"""
"jnz x y" - Jumps to an instruction y steps away (positive means forward, negative means backward),
but only if x (a constant or a register) is not zero
:param args: Array of arguments passed into this command.
:param register_copy: Dict wit... | 32e855bedc59cd7dbc3bc9de1be6ebfa979abc24 | 3,605,827 |
def pop(the_stack):
""" Returns top of stack if stack not empty. Otherwise, returns None """
if is_empty(the_stack):
return None
else:
item = the_stack[len(the_stack) - 1]
del the_stack[len(the_stack) - 1]
return item | e64b274e7f828e88eb852e96ba8ec29ae8351767 | 3,605,828 |
def build_weighted_graph(G, alpha=0.9, p_null=None):
"""using log-odds ratio probability weighting to model graph edges.
when [p_null] is missing, using a default null model for the weighting:
random degree-preserving rewiring approximation."""
W = G > 0
deg = W.sum(axis=1).reshape((1, -1))
M = ... | b51e5aeb6c8214d609b4ffc119394bb1c763e02d | 3,605,829 |
def get_badge(total, colour=DEFAULT_COLOUR):
"""update total and return shields.io URL
Args:
total:
total coverage (str).
colour:
badge colour (str).
"""
percent = quote("%")
shields_badge = (
f"https://img.shields.io/badge/Coverage-{total}{percent}-{c... | 1f872a12ff3d60847ca9c94248aa8478b12dbefc | 3,605,830 |
import os
def determine_l0_spacing(grid, bpath, index, track):
"""
Determine the separation of l=0 modes in the given track, and only for
the modes that are continuous throughout the track. It currently differs from
the full interpolation scheme, that also accounts for modes appearing and
dissapea... | 61f9486d0bec641de3c766b092b6a8d9fbe47c16 | 3,605,831 |
import torch
def perm(N, seed: int = None):
"""Generate a tensor with the numbers 0 through N-1 ordered randomly."""
gen = torch.Generator()
if seed is not None: gen.manual_seed(seed)
perm = torch.normal(torch.zeros(N), torch.ones(N), generator=gen)
return torch.argsort(perm) | da12d8783e0aec0bea1d3841c30c554dbaaf3a77 | 3,605,832 |
from typing import Union
from typing import Callable
import torch
def pytorch_load(
torch_object: Union[Callable, TORCH_RECOVERABLE],
path: str,
device: torch.device = torch.device("cuda" if torch.cuda.is_available() else "cpu"),
) -> TORCH_RECOVERABLE:
"""Can instantiate or load on an existing instan... | 4e05323192eb15bbf41b8023a986a5ff41814ee0 | 3,605,833 |
def lowercase(df):
"""
lowercase things
"""
return pd.DataFrame({
"sentence": df.sentence.apply(lambda x: " ".join([i.lower() for i in x.split(" ")])),
"label": df.label
}) | 59dfd02de57f57b1272761bd83d5c6971ded0fc9 | 3,605,834 |
def summarise_tenant(instance_states):
""" Summaries usage of Nova tenant """
core_usages = {}
calculator = InstanceScore()
for state in instance_states:
if state["tenant"] not in core_usages:
core_usages[state["tenant"]] = 0
core_usages[state["tenant"]] += calculator.get_sc... | df9a043b5df6cce81eb73d19b42e63e802f4b508 | 3,605,835 |
import string
def decode(digits, base):
"""Decode given digits in given base to number in base 10.
digits: str -- string representation of number (in given base)
base: int -- base of given number
return: int -- integer representation of number (in base 10)"""
# Handle up to base 36 [0-9a-z]
as... | febdf9973a73de5b3686a20b8c2a5738391a815e | 3,605,836 |
import tempfile
import codecs
def check_vocab(vocab_file, special_vocabs, pad_to_eight):
"""Check if vocab_file doesn't exist, create from corpus_file."""
global UNK, SOS, EOS, UNK_ID
if tf.gfile.Exists(vocab_file):
tf.logging.info("# Vocab file %s exists\n" % vocab_file)
vocab = []
vocab_size = 0
... | f2ba4eb1f16097a4e040b9ec232339262895dd66 | 3,605,837 |
import math
import torch
def setup(**config):
"""
Setup and return the datasets, dataloaders, model, and training loop required for training.
:param config: config dictionary
:return: Tuple of dataset collection, dataloader collection, model, and train looper
"""
device = cuda_if_available(us... | 0b193dea5f963c5bc748e7c9c72a89307df8b428 | 3,605,838 |
def sub2ind(subs, shape):
"""Convert sub indices (i, j, k) into linear indices.
Parameters
----------
subs : iterable of array_like
List of sub-indices. Its length is the number of dimension.
Each element should have the same number of elements and shape.
shape : iterable
Si... | 3f729716361c4b44cfde362536320c7e1894ebbc | 3,605,839 |
from typing import Literal
def Tokenize(string, separators):
"""Tokenizes the given string based on a list of separator strings.
This is similar to splitting the string based on separators, except
that this function retains the separators. The separators are
wrapped in Separator objects and everything else i... | f1a2c2a6f7174024350c64da9e493bda2e52ca15 | 3,605,840 |
from apysc._file import module_util
from typing import Callable
from typing import Any
def _get_callable_from_package_path_and_callable_name(
*, module_or_class_package_path: str,
callable_name: str) -> Callable:
"""
Get a callable object from a specified package path and
callable name.
... | 263cc2f677f402889f5878cfdb51100b6f021a10 | 3,605,841 |
def interseccion_todas_capas(c, f, lc, l_index, args):
""" Return true if exist intesection with other layers, false otherwise. """
uri2 = QgsDataSourceUri()
uri2.setConnection(args.server, str(args.port), args.dbname, args.user, args.password)
geom = f.geometry()
bbox_geom = geom.boundingBox()
... | 1f06f60fd33748f254c80e9ce709f0032825f80b | 3,605,842 |
def validinstruction(instruction):
"""
Check whether the given instruction is valid
:param instruction: a cardinal point
:return: If the instruction is a valid input
"""
if instruction in CARDINAL_POINTS:
return True
return False | 4c9668615992a479e6c029fc73360cd4a206d0cd | 3,605,843 |
def read_file(fn, guess_product = True):
"""
Reads a file with the ICARTT format.
https://www-air.larc.nasa.gov/missions/intexna/DataManagement_plan.htm
Parameters
----------
fn : TYPE
DESCRIPTION.
guess_product : TYPE, optional
DESCRIPTION. The default is True.
Returns... | 4fde6bd665093bf4e4f698811fa64018a799fdcc | 3,605,844 |
import argparse
def parseArgs():
"""Parse script parameters and return its values."""
parser = argparse.ArgumentParser(
description="Social Media Profile Cross Reference Tool.")
parser.add_argument("-i",
help="input csv file with emails",
required=Tr... | a3697b1d90f4cd868aac0f085f8a41674b729855 | 3,605,845 |
def generate_phone_numbers():
"""Returns example phone numbers."""
return [PhoneNumber(number="0123456789", location="Mobile"),
PhoneNumber(number="+490", location="Work"),
PhoneNumber(number="", location="")] | 733106d534bed56c456c4cc7853472c4fd13bccc | 3,605,846 |
from numpy import linspace
def gbox_boundary(gbox, pts_per_side=16):
"""Return points in pixel space along the perimeter of a GeoBox, or a 2d array.
"""
H, W = gbox.shape[:2]
xx = linspace(0, W, pts_per_side, dtype='float32')
yy = linspace(0, H, pts_per_side, dtype='float32')
return polygon... | e06176435163694da539cc2f354f64deb8c04734 | 3,605,847 |
def get_model_fields(model):
"""
For a given model, returns all fields with their names
"""
_fields = []
for key, val in dict(model.__dict__).iteritems():
if issubclass(val.__class__, ModelAttribute):
_fields.append((key, val.__class__))
return _fields | e9ce1ab931a5e59624a29f4ef6662c832343a9e5 | 3,605,848 |
def map_pixels_to_ascii_chars(image, range_width=25):
"""Maps each pixel to an ascii char based on the range
in which it lies.
0-255 is divided into 11 ranges of 25 pixels each.
"""
pixels_in_image = list(image.getdata())
pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value... | 31d31ecdda9d1479bbe4c4c9091c4c21e60812ee | 3,605,849 |
import re
def is_good_photo(photo):
"""Return True if photo is usable; False if it is a bad photo."""
return all([re.search(pat, photo['img_src']) is None for pat in BAD_PATS]) | f5163769483ee0e266fedd730fd9c487b92a6315 | 3,605,850 |
def descent_set(t):
"""
Return the descent set of a standard tableau ``t``
(encoded as a sorted list).
The *descent set* of a standard tableau `t` is defined as
the set of all entries `i` of `t` such that the number `i+1`
appears in a row below `i` in `t`.
EXAMPLES::
sage: from sa... | 01d91600ab23646ebb471a1b65c137a6e8287183 | 3,605,851 |
def softmax_with_cross_entropy(preds, target_index):
"""
Computes softmax and cross-entropy loss for model predictions,
including the gradient
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
target_index: np array of int, shape is (1) or ... | 946c2fa76d6bbab53be311b6062b44a1fdef5810 | 3,605,852 |
def evaluate(inputs):
"""
Evaluates a weighted sum function.
$sum = \Sigma_{i=0} (i+1)*x_{i}$
min with replacement = n*(n-1)/2*lb occurs at x_{i} = lb (i.e., lower bound of the discrete variables)
max with replacement = n*(n-1)/2*ub occurs at x_{i} = ub (i.e., upper bound of the discrete variables)
... | c09e4c8973d069e46e981a02d09f8754f893f95d | 3,605,853 |
def _boot_time_amiga() -> "float|None":
"""Returns uptime in seconds or None, on AmigaOS."""
try:
return os.stat("RAM:").st_ctime
except (NameError, OSError):
return None | 45ab403609f18321c039f1e112f433fa6366ba8e | 3,605,854 |
from django.contrib.auth.views import redirect_to_login
import re
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If the page is a draft, only show it to users who are staff.
if f.status == 'd' and not request.user.is_authenticated():
raise Http404
... | 51a10de9c1b4858452921804b4ebe7a5b1277234 | 3,605,855 |
from sklearn.ensemble import IsolationForest
def run_iforest(X):
""" Predict the anomaly score with iForest
"""
clf = IsolationForest()
clf.fit(X)
scores = clf.decision_function(X)
return scores | 56b2ebcd300faca8ef0224f7aacb150e0bf2c133 | 3,605,856 |
def get_A1_hom(s, scalarKP=False):
"""
Builds A1 for the spatial error GM estimation with homoscedasticity as in
Drukker et al. [Drukker2011]_ (p. 9).
.. math::
A_1 = \{1 + [n^{-1} tr(W'W)]^2\}^{-1} \[W'W - n^{-1} tr(W'W) I\]
...
Parameters
----------
s : csr_m... | 7c90fde361ceb2fc7349812b8743264e486c7e01 | 3,605,857 |
import ctypes
def register_node(type_key=None):
"""register node type
Parameters
----------
type_key : str or cls
The type key of the node
"""
node_name = type_key if isinstance(type_key, str) else type_key.__name__
def register(cls):
"""internal register function"""
... | 8105395cc7c19677a04612a3702c6ed1806ca35d | 3,605,858 |
def sort_url_by_query_keys(url):
"""A helper function which sorts the keys of the query string of a url.
For example, an input of '/v2/tasks?sort_key=id&sort_dir=asc&limit=10'
returns '/v2/tasks?limit=10&sort_dir=asc&sort_key=id'. This is to
prevent non-deterministic ordering of the query stri... | 694201c1dc6c5d30df6d589e338e325f538fff47 | 3,605,859 |
import pandas
def add_measured_to_input(time_df, input_df, measured_df):
"""adds info of measurement dataframe to time and layer execution dataframe
Args:
time_df: DataFrame with input layer names as columns, stores runtime
input_df: DataFrame with input layes names as columns, stores executi... | e6871ea8693726ffc33f4e52d0875b6489e672ae | 3,605,860 |
def conditional_lateness_plots(rows=None,
degrees_sep=1,
conds=(0,60,300,600,1200)):
"""
Plots the (weighted) conditional lateness distribution as
F( lateness at stop | lateness at Dth stop previous )
where D = degrees_sep. This is plotted ... | 1c434458cbaf61ff83e2117f17898e63a9401271 | 3,605,861 |
def sample_rois(rois, gt_boxes, num_classes, rois_per_image, fg_rois_per_image, fg_overlap, box_stds, seg, im_info):
"""
generate random sample of ROIs comprising foreground and background examples
:param rois: [n, 5] (batch_index, x1, y1, x2, y2)
:param gt_boxes: [n, 5] (x1, y1, x2, y2, cls)
:param... | 42920de5251879da80346c603a1690f95c2453c8 | 3,605,862 |
import requests
from bs4 import BeautifulSoup
def get_departures(vazi_od, dan_u_nedelji, linija):
"""dan_u_nedelji: R - radni, S - subota, N - nedelja"""
URL = f'http://gspns.co.rs/red-voznje/ispis-polazaka?rv=rvp&vaziod={vazi_od}&dan={dan_u_nedelji}&linija[]={linija}'
r = requests.get(URL)
soup = Bea... | 986d5c175e5d27896cf68c096f2e7201c2dfa778 | 3,605,863 |
def getaccesskeys(show):
"""
This function is used to get the list of all accesskeys
"""
try:
accesskeys=iam.list_access_keys()
except botocore.exceptions.ClientError as e:
coloredtext("There was an error while getting access key data: \n\n\n")
print(... | 52c907385e628638c524ac33f83e38986b081648 | 3,605,864 |
def convert_categorical_column(col : ColumnObject) -> pd.Series:
"""
Convert a categorical column to a Series instance
"""
ordered, is_dict, mapping = col.describe_categorical
if not is_dict:
raise NotImplementedError('Non-dictionary categoricals not supported yet')
# If you want to che... | 30c99adacc32ed8f51b85055494817ae1b58529c | 3,605,865 |
from .RNN.values_arrangement import get_outputs_by_neuron
from typing import Union
from typing import List
def autocorrelation_periodicity(audio_path: Union[str, List[str]], downbeat_model: bool = True) -> float:
"""
Autocorrelation periodicity pulse clarity metric
Args:
audio_path: string or lis... | 80c4d2203d6261599673a4bff0e851225e906e16 | 3,605,866 |
def random_ddm(drift, threshold, ndt, rel_sp=.5, noise_constant=1, dt=0.001, max_rt=10):
"""Simulates behavior (rt and accuracy) according to the diffusion decision model.
In this parametrization, it is assumed that 0 is the lower threshold,
and, when rel_sp=1/2, the diffusion process starts halfway throug... | 8a3df7d78a617d7ed397810b65522eaf0f5a7681 | 3,605,867 |
def flow_camera_motion_loss(gt_masks, camera_motion, depth, flow, camera_intrinsics):
"""Supervise camera_motion with optical flow.
Args:
gt_masks: tensor of shape [batch_size, num_boxes, image_height, image_width]
camera_motion: tensor of shape [batch_size, 7]
depth: tensor of shape [batch_size, image_... | 6a3d2eebd2f96fea2025bd6a02fd4dbe6adcf479 | 3,605,868 |
import time
import subprocess
import json
def pullStatistics(files,chr_list):
"""
Function computes statistics on given file set and chromosome set
Example : pullStatistics(".findFiles() output",['chr1','chr2'])
Returns dataframe of stats per sample
"""
print("Running : Pulling QC statistics")... | bb85df6ba79086ea711f2a3bb00aed29d02780d0 | 3,605,869 |
import random
import string
def user_generate_key(id):
"""Generate new key for user"""
user = User.query.get(id)
key = Key()
key.key = ''.join(random.sample(
string.ascii_letters + string.digits, 32
))
key.user_id = user.id
db.session.add(key)
db.session.commit()
flash('Suc... | d20024c036f678cdafe18d27c2437556fe49c8d3 | 3,605,870 |
def interp2dxy(field3d, xy, meta=True):
"""Return a cross section for a three-dimensional field.
The returned array will hold the vertical cross section data along the
line described by *xy*.
This method differs from :meth:`wrf.vertcross` in that it will return
all vertical levels found ... | 1cda7b44055a61efdcb5a824256e57071d01460a | 3,605,871 |
def calc_prestress(params, calc_eta_func, coords):
"""Calculate the prestress
Calculate -h(eta) * [ C_ijkl(eta) * epsilonT_kl ]
Note that C_1211, C_1222, C_2111 and C_2122 are zero.
Args:
calc_eta_func: function to calculate the phase field
coords: the Sfepy coordinate array
epsilon... | 782ad01fbb1bdba8c399a6543f01481b172516e2 | 3,605,872 |
def pass_args(args):
"""Possible argument to attr_handler()"""
return args | 5681a5f80c1f01bcae099d4baaf7fb07785c5983 | 3,605,873 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Štampar Pelud sensor platform."""
name = config.get(CONF_NAME)
station_id = config.get(CONF_STATION_ID)
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.lon... | e8b432a351f815c0e648a0ce2be736ef6d21564b | 3,605,874 |
def post_detail(request, id):
"""
Create a view that return a single
Post object based on the post ID and
and render it to the 'postdetail.html'
template. Or return a 404 error if the
post is not found
"""
post = get_object_or_404(Post, pk=id)
post.views += 1 # clock up the number o... | ed806e3061a4fbb9ab28068678341d96b4406b4b | 3,605,875 |
def bin_ip_2_ip(bin_ip):
"""
convert a binary string of IP to decimal IP in a numpy array
:param bin_ip: binary string of an IP
:type bin_ip: string
:return: a decimal IP address in numpy array
:rtype: np.array
"""
length = int(len(bin_ip) / 8)
ip = np.zeros(length, dtype=np.uint8)... | cf9e3543335503ec559426f11ddbd8ce52823201 | 3,605,876 |
def gen_rand_params(include=(), cond_dict=None, seed=None):
"""Returns a dict of DDM parameters with random values.
:Optional:
include : tuple
Which optional parameters include. Can be
any combination of:
* 'z' (bias, default=0.5)
... | 0a044a4b79a452e6d6bb54f3a8765f864a3fe217 | 3,605,877 |
def resnet18_ibn_b(**kwargs):
"""
Constructs a ResNet-18-IBN-b model.
"""
model = ResNet_IBN(block=BasicBlock_IBN,
layers=[2, 2, 2, 2],
ibn_cfg=('b', 'b', None, None),
**kwargs)
return model | 3338e7a48fb27e5baca16e750c46f245e062ae4f | 3,605,878 |
def dict_to_tfexample(mol_dict):
"""Convert dictionary of molecular info to tfExample.
Args:
mol_dict : dictionary containing molecule info.
Returns:
example : tf.example containing mol_dict info.
"""
example = tf.train.Example()
feature_map = example.features.feature
feature_map[fmap_constants.... | e3eb8335b4e5ea12b378b978c941fd960ed334c1 | 3,605,879 |
def normalize_pygcn(a):
""" normalize adjacency matrix with normalization-trick. This variant
is proposed in https://github.com/tkipf/pygcn .
Refer https://github.com/tkipf/pygcn/issues/11 for the author's comment.
Arguments:
a (scipy.sparse.coo_matrix): Unnormalied adjacency matrix
Return... | 48ab37ae1b5acb8fce97a61449277966dc3d3545 | 3,605,880 |
def least_significan_bit(n):
"""Least significant bit of a number
num AND -num = LSB
Args:
n ([type]): [description]
Raises:
TypeError: [description]
Returns:
[type]: [description]
"""
if type(n) != int:
raise TypeError("Number must be Integer.")
if... | 5fcde70104f885eeb753697fb74d8ec2e7156eae | 3,605,881 |
def filter_contigs(assembler):
"""Remove junk from the assembled contigs."""
log.info('Saving assembled contigs: iteration {}'.format(
assembler.state['iteration']))
blast_db = blast.temp_db_name(
assembler.iter_dir(), assembler.state['blast_db'])
hits_file = blast.output_file_name(
... | 7c7394a093502d0a62aa8f3a7f5925e0e3c5376e | 3,605,882 |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def moon_agent_filter(app):
return MoonAgentKeystoneMiddleware(app, conf)
return moon_agent_filter | 5abf18ddcb13f54a5872e7596edcf25878670a17 | 3,605,883 |
def add(T, w, i=0):
"""
:param T: trie
:param string w: word to be added to T
:returns: new trie consisting of w added into T
:complexity: O(len(w))
"""
if T is None:
T = TrieNode()
if i == len(w): # 叶子节点
T.isWord = True
else:
T.s[w[i]] = add(T.s[w[i]], w, i... | c8977bd383572b1accb671199589fc519e3805d1 | 3,605,884 |
def make_polar_stereo(attrs_dict, globe):
"""Handle polar stereographic projection."""
attr_mapping = [('central_longitude', 'straight_vertical_longitude_from_pole'),
('true_scale_latitude', 'standard_parallel'),
('scale_factor', 'scale_factor_at_projection_origin')]
... | dcbb25c24c705c7c9503bcb605a2b74f097613a8 | 3,605,885 |
def is_k_anonymous(df,partition,sensitive_column,k =3):
"""
params
df: The dataframe on which to check the partition.
partition: The partition of the dataframe to check.
sensitive_column: The name of the sensitive column
k: The desired k
returns
True if the partition... | e58ae8f65524c8a9f7b404d391c2b1d3d0b188c2 | 3,605,886 |
def normalize_variant(variant: str) -> str:
"""
Normalize variant.
Reformat variant replace colons as separators
to underscore.
chromosome:position:reference:alternative
to
chromosome_position_reference_alternative
:param variant: string representation of variant
:return: reformat... | 2dc97b7f7b09add6a8062db94376c1ab030ff07c | 3,605,887 |
from typing import Union
from typing import Any
from typing import Callable
import warnings
def add_deactivated_after_edit_handler(parent : Union[int, str], *, label: str =None, user_data: Any =None, use_internal_label: bool =True, tag: Union[int, str] =0, callback: Callable =None, show: bool =True) -> Union[int, str... | dfc362c55448f7a21df79ab51d944334a0505931 | 3,605,888 |
from typing import Tuple
def compute_limits(
numdata: int, numblocks: int, blocksize: int, blockn: int
) -> Tuple[int, ...]:
"""Generates the limit of indices corresponding to a specific block. It
takes into account the non-exact divisibility of numdata into numblocks
letting the last block to take th... | 748344d60baa8f2ecd31ce822c0e33aca981bc13 | 3,605,889 |
from astropy.utils.data import download_file
from astropy.utils.data import download_file
def initialise_ephemeris(
ephem="DE405",
units="TCB",
earthfile=None,
sunfile=None,
timefile=None,
ssonly=False,
timeonly=False,
filenames=False,
):
"""
Download/read and return solar syst... | 5161f22ad433b901ca0c35cadc90288e5e30c7b1 | 3,605,890 |
def eval_en_performance(representations: np.array,
):
"""
entropy of probe representations at output layer and at origin.
"""
res = drv.entropy_pmf(representations).mean()
return res | d940d83d8c2eae0115c0f3300ea3582f85b13d59 | 3,605,891 |
def binarized_loss(x, l):
"""Cross-entropy loss
Args:
x: B x 1 x H x W floating point ground truth image, [-1, 1] scale
l: B x 2 x H x W output of neural network
Returns:
loss: 0-dimensional NLL loss tensor
"""
assert l.size(1) == 2
x = _binarized_label(x)
# cross_e... | 599e830165b8bb6b70725e664f5d5d0586a5554e | 3,605,892 |
import json
def getToken(response):
"""
Get the tokenised card reference from the API response
:param response: Response object in JSON
:return: String - token
"""
resp_dict = json.loads(response.text)
try:
token = resp_dict["token"]
except KeyError:
print('Retrieval ... | b849f3b021b995b164b99690a82ecabf881bb18b | 3,605,893 |
def _read_transition_statistics_from_files(model, verbose):
"""Parses the transitions statistics from the simulation output files for later analysis
Parameters
-------
model : obj
object containing all anchor and milestone information
Returns
---------
total_steps : int
total number ... | 1a4f326bd628e6ddd9475c9610b92cb2ba564bba | 3,605,894 |
def _extend_to_nparray(item, n):
"""If item is already list/array return np.array, otherwise extend to length n."""
data = item if isinstance(item, (list, np.ndarray)) else [item for _ in range(n)]
return np.asarray(data) | 69a344c9df8e8b8dd079e7b72c7cf911e5c7ed6a | 3,605,895 |
def maskData(data):
"""
- Occasionally, the simulation may crash due to a Riemann solver failure
- This is typically fixed by a restart from a checkpoint with a lower courant number
- However, the data is still there in the history file
- This function masks out incorrect data, by finding areas where "time tr... | 2321555a87a959fca63c44cc18be1362e1ddb491 | 3,605,896 |
import re
def read_urls(filename):
"""Returns a list of the puzzle urls from the given log file,
extracting the hostname from the filename itself.
Screens out duplicate urls and returns the urls sorted into
increasing order."""
# +++your code here+++
f = open(filename, 'r')
paths = re.findall(r'GET (.*... | ff2b9be867c75fd5b5d4e419a58818a319246d21 | 3,605,897 |
from typing import List
import ipaddress
import json
def k8s_resolve(
runner: Runner, remote_info: RemoteInfo, hosts_or_ips: List[str]
) -> List[str]:
"""
Resolve a list of host and/or ip addresses inside the cluster
using the context, namespace, and remote_info supplied. Note that
if any hostname... | 545412ef7807a57cc46a4a5403681c7047f9c8a1 | 3,605,898 |
def createSubsetGafDict(subset, gafDict):
"""
Generates a dictionary that maps the subset's Uniprot ACs to the GO IDs,
based on the provided gene subset and the gaf dictionary.
Parameters
----------
subset : set of str
A subset of Uniprot ACs of interest.
gafDict : dict of str mappi... | 76e69cd79c984a19254df171403c008405276408 | 3,605,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.