content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_block(f, offset, length, delimiter=None):
""" Read a block of bytes from a file
Parameters
----------
fn: string
Path to filename on HDFS
offset: int
Byte offset to start read
length: int
Number of bytes to read
delimiter: bytes (optional)
Ensure rea... | 739197fc090a05c7bfcdccd5e71bf3bc2dcc0814 | 58,944 |
def iou_from_mask(pred, gt):
"""
Compute intersection over the union.
Args:
pred: Predicted mask
gt: Ground truth mask
"""
pred = pred.astype(np.bool)
gt = gt.astype(np.bool)
true_negatives = np.count_nonzero(np.logical_and(np.logical_not(gt), np.logical_not(pred)))
fals... | ca8ba563a26fb150d9d12035c8ac0689b5035739 | 58,947 |
def md5file(filename):
"""
Re-implementation of md5sum in python. Return the hex digest of a file
without loading it all into memory.
By Nick Craig-Wood <nick@craig-wood.com>
"""
fh = open(filename)
digest = md5.new()
while 1:
buf = fh.read(4096)
if buf == "":
... | 8fd464a1d6bb3625764a06eb23a66d5223f63e58 | 58,948 |
def contains_all_required_firewalls(firewall, topology):
"""
Check that the list of firewall settings contains all necessary firewall settings
"""
for src, row in enumerate(topology):
for dest, col in enumerate(row):
if src == dest:
continue
if col == 1 an... | a4dbbb5833909e816c5b7568cf75da68c06d9e4c | 58,949 |
def truncation(parent_population, child_population, parents_scores,
children_scores, elitism_rate):
"""Selects next generation using elitism truncation selection for
single objective.
This function implements truncation selection while ensuring elitism
to select a specific number of memb... | 373ca6ad168a606995cf3c78cd8732c37642abfd | 58,950 |
def locations__search(request):
"""
Renders the locations page, after a search has been made.
Behaviour will vary, depending on the number of results, if there are errors...
"""
context = {'from_search': True, 'geolocation': request.session.get('geolocation'),
'location_error'... | 2a096dbc2da2d6756182b0df90e1dc4f852c7537 | 58,951 |
def latest_object_or_none(model_class, field_name=None):
"""Identical to Model.latest, except instead of throwing exceptions,
this returns None.
"""
try:
return model_class.objects.latest(field_name)
except (model_class.DoesNotExist, model_class.MultipleObjectsReturned):
return None | d71d6c6a58b7ba4d5a5ffe262353c56752bd486c | 58,952 |
def _get_upload_headers(first_byte, file_size, chunk_size):
"""Prepare the string for the POST request's headers."""
content_range = 'bytes ' + \
str(first_byte) + \
'-' + \
str(first_byte + chunk_size - 1) + \
'/' + \
str(file_size)
return {'Content-Range': content... | 3ccfec747ce8f8f31b97489005b1ac421f7c9024 | 58,953 |
from typing import List
def get_timers_matching_utterance(
utterance: str, timers: List[CountdownTimer], regex_path: str
) -> List[CountdownTimer]:
"""Match timers to an utterance that matched a timer intent."""
matcher = TimerMatcher(utterance, timers, regex_path)
matcher.match()
return matcher.... | cded1b8d7b41373cc03cc110902f7a8a09c89488 | 58,954 |
import logging
import uuid
def load_data():
"""
read mnist data from file
x (60000, 28, 28)
y (60000,)
split each record into leader_part and follower_part
and allocate example_id for each record
"""
logging.info("Load mnist_x.npy and mnist_y.npy")
x = np.load('mnist_x.npy')
y... | 9a3d46d276a883eb3270cc1a97caa250fcb77053 | 58,955 |
def dict_equal(dictionary, other_dictionary):
"""Compare two dict with :class:`numpy.ndarray` value handling.
Comparison is made in two parts:
* We first check that both dict have the same keys.
* If they do we then compare each value pair and lazily return ``False`` if any comparison fails.
Note:... | 043892e324d2a4e9893db79af97765c3f9f2e19f | 58,956 |
def get_Wiener(ase_obj):
"""
Example crystal structure descriptor:
https://en.wikipedia.org/wiki/Wiener_index
defined per a unit cell
"""
return np.sum(ase_obj.get_all_distances()) * 0.5 | 5a6d20990f84d0c907417f583a317e4d34f9cee4 | 58,957 |
import copy
def init_param_cont(args):
"""
init_param_cont(args)
Initializes parameter containers.
Returns args:
- in the following nametuples: analyspar, sesspar, stimpar, autocorr,
permpar, quantpar, roigrppar, tcurvpar
- in the following dic... | fa4f38d0a1da7f1ca51e4e1358ca12a05374f1f6 | 58,958 |
from typing import Optional
def _box_as_indexlike(
dt_array: ArrayLike, utc: Optional[bool] = None, name: Label = None
) -> Index:
"""
Properly boxes the ndarray of datetimes to DatetimeIndex
if it is possible or to generic Index instead
Parameters
----------
dt_array: 1-d array
A... | c7c84833b4135bb5f26d13954509b0c0f412e27f | 58,959 |
from typing import Iterable
import pandas
import numpy
def categorical_encode_series_to_sparse_csc_matrix(
series: Iterable, reduced_rank: bool = False
) -> spsparse.csc_matrix:
"""
Categorically encode (via dummy encoding) a `series` as a sparse matrix.
Args:
series: The iterable which shoul... | 75ccc95055ac091581c8b05f4cc5c92c27deef14 | 58,960 |
def setup_arg_parser():
"""
Sets up argument parser for python scripts.
Returns:
arg_parser (ArgumentParser): Argument parser updated with probabilistic detectron args.
"""
arg_parser = default_argument_parser()
arg_parser.add_argument(
"--dataset-dir",
type=str,
... | 52d3384b6cb853f841cfad7cf0c2755933488dae | 58,961 |
def SegmentConst_get_decorator_type_name():
"""SegmentConst_get_decorator_type_name() -> std::string"""
return _RMF.SegmentConst_get_decorator_type_name() | 1c357834fd4f0406616b8e46cb98c1f0957f5549 | 58,962 |
def write(sec):
"""Write MT section for MF5
Parameters
----------
sec : `sandy.utils.Section`
dictionary with MT section for MF5
Returns
-------
`str`
section content in a single string
"""
text = write_cont(sec["ZA"], sec["AWR"], 0, 0, len(sec["PDISTR"]), 0... | cb03c9dc5672d69f94921f58991c1f6259705a2b | 58,963 |
def emissions(run_start_year, run_end_year, dt, rcp, add_start = 0,
add_end = 0, c_add = 0, ch4_add = 0, n2o_add = 0):
"""
Take annual emissions from a RCP scenario and return
emissions by specified start date, end date, and time step
"""
run_years = run_end_year - run_start_year + 1 ... | 046ea1c9e154920b30b8436deb648d6ee66b626b | 58,964 |
def cv2_fn_wrapper(cv2_fn, mat, *args, **kwargs):
"""" A wrapper for cv2 functions
Data in channel first format are adjusted to channel last format for
cv2 functions
"""
mat_shape = mat.shape
x_size = mat_shape[-2]
y_size = mat_shape[-1]
_mat = mat.reshape((-1, x_size, y_size)... | 5ed5f1c40383d0fe0c0a6f6fd39f0d22616a8307 | 58,965 |
def initial_time():
"""
Real Name: INITIAL TIME
Original Eqn: 0
Units: Day
Limits: (None, None)
Type: constant
Subs: None
The initial time for the simulation.
"""
return 0 | 322f4472123f27400d507f8b4e7dc2262bd1c348 | 58,967 |
def render_template(filename, **context):
""" Render mail template. Returns rendered text """
return jinja_env.get_template(filename).render(**context) | 8ab1e06b7626d5de06a6f814a40cc394cffe1469 | 58,969 |
from typing import Union
from operator import is_
def has_text(expected: Union[Matcher, str]):
"""
Test if ``WebElement`` instance has text.
:param expected: expected text
:return: ``Matcher`` instance
"""
return HasText(is_(expected)) | dfd9968f5ee16d80c6bf701922cc362960ad1208 | 58,970 |
def plot_hate_speech(
df: pd.DataFrame, title: str = None, height: int = 300, label_col: str = "label"
) -> Figure:
"""
Show the percentage of estimated hate speech sentences.
Args:
df (pd.DataFrame):
Dataframe with the outputs of a hate speech model.
title (str):
... | c6c3098a7b30e58722820a1eefbdfbec5ce46328 | 58,971 |
from typing import OrderedDict
def clean_weights(weights: OrderedDict, portfolio, first_prices, latest_prices):
"""Remove low weights as not significant contributors to portfolio performance"""
sum_of_weights = sum(map(lambda t: t[1], weights.items()))
assert sum_of_weights - 1.0 < 1e-6
cw = OrderedDi... | eb7cb0861852cb57e986e0bb8647026bd445287c | 58,972 |
def helper_find_anagrams(s, n, anagrams_list):
"""
:param s: stands for the input word
:param n: n is a counter for the number of anagrams
:param anagrams_list: to collect all anagrams we want
:return: n, anagrams_list
"""
# first to get the list of each characters of the input word 's'
... | f379f8323c974f63096b25a21c181bf5aa5fb9c4 | 58,975 |
def get_metadata_values( file, metadata ):
"""
Gets metadata values from a file path.
:param file: The file path to search.
:param metadata: Metadata from the file name is turned into MultiIndex columns.
+ If list, use standard keywords to include in index [ 'sample' ]
+ If Dictionary, ... | b3d10ccc802ca453f63d6a5728341f42174f985d | 58,976 |
def posECIfromECEF(posECEF_, second):
"""
Args:
posECEF_ (np.array 3x1) : position in ECEF coordinate [m, m, m]
second (double) : time from reference time [s]
Return:
(np.array 3x1) : position in ECI coordinate [m, m, m]
"""
return np.matmul(dcmECEF2ECI(second), posECEF_) | a14717ed6a431cd0ba84781c6141070509f05cd5 | 58,977 |
def get_prediction(url,topics_count=10):
""" Send an url to xplr and gets the result of the prediction
as labelled topics, extracted content and words)
:param url: the url to be predicted
:param topics_count: number of topics expected
:returns: a tuple (title, topics) where title is extracted
b... | 81d2ca151c77c526ce3a9cdcc8ba1b3aaf67df02 | 58,978 |
def startup(name):
"""
Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup
"""
ret = {"name": name, "changes": {}, "result": None, "comment": ""}
if __opts__["test"]:
ret["comment"] = "Starting up local node"
return... | 19d6c1ce478b94d926bbb2c789083f7840e086f8 | 58,979 |
def calc_ma(datas, ma_list):
"""
根据 ma_list 计算 ma 数值
calc
:param datas: dataframe
:param ma_list: string list
:return:
"""
try:
for ma in ma_list:
datas['ma%d' % ma] = ta.SMA(datas['close'].values, ma)
except Exception as e:
print(e)
return datas | ff469f73adfbf014b844f01ed504f31d138e9c78 | 58,980 |
def split_args(arguments):
"""
","구분자로 split
리턴: list
"""
try:
return arguments.split(",")
except UserDefinedException as e:
raise UserDefinedException(f"[-] split_args Error split: {e}") | 7d451cc2078d7fecce9a3cf27fb0fa3d55271a2b | 58,981 |
def Data(Objectid):
"""
Parameters
----------
Objectid : String, ZTF ID
Takes in ZTF object id and makes a dataframe of it's lightcurve data
Returns
-------
DataFrame with lightcurve data
"""
Supernovadf = pd.DataFrame(columns = ["mjd", "band", "magnitude", "error", ... | 6733c624f35fde4e65dc9dd4da445209442d627a | 58,982 |
def init_line_complex(p):
"""
initialize 1D complex on the line
Input:
p - number of 0-simplices
Will add (p-1) 1-simplices
"""
f = d.Filtration()
for i in range(p-1):
c = d.closure([d.Simplex([i, i+1])], 1)
for j in c:
f.append(j)
return f | 2f53a2f2bc1156adea0f22b6a6d999d90c65d0fc | 58,983 |
from datetime import datetime
def prettify_time(time_string: str) -> str:
"""Fix timestamps to a better format."""
if time_string:
parsed = datetime.strptime(time_string, "%Y-%m-%dT%H:%M:%S.%fZ")
return datetime.strftime(parsed, "%Y-%m-%d %H:%M:%S")
else:
return 'N/A' | f40a0dc1f26bea8001d823ab38a3f1cd0000050a | 58,984 |
def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | a6a4544b6754113d0c5ed13a18838770448be6a8 | 58,985 |
def load_lines(file_name,
fields=["lineID", "characterID", "movieID", "character", "text"],
delimiter=" +++$+++ "):
"""
Args:
file_name (str): file to load
fields (set<str>): fields to extract
delimiter (str): delimiter string
Return:
dict<dict<s... | b18d8a84c143cd5a53516b7dc465ba1ef7d72e26 | 58,986 |
def string_camelcase(string):
""" Convert a word to its CamelCase version and remove invalid chars
>>> string_camelcase('lost-pound')
'LostPound'
>>> string_camelcase('missing_images')
'MissingImages'
"""
return CAMELCASE_INVALID_CHARS.sub('', string.title()) | c41b07d5285e9cdf78be107f2b2407f9ba6c266d | 58,987 |
from nltk.tokenize import word_tokenize
from typing import DefaultDict
import torch
from typing import Optional
from typing import Tuple
from typing import List
def prepare_untagged_data(
data_path: str,
word_to_ix: DefaultDict[str, int],
device: torch.device,
tokenizer: Optional[BertT... | 7baecfc656d0ed21e5d94a5b309e39d40f76e587 | 58,988 |
def chunker(arrays, chunk_size):
"""Split the arrays into equally sized chunks
:param arrays: (N * L np.array) arrays of sentences
:param chunk_size: (int) size of the chunks
:return chunks: (list) list of the chunks, numpy arrays"""
chunks = []
# sentence length
sent_len = len(arrays[0])... | 42a6867464e32d59a50927e8e88d067fc86f4fa1 | 58,989 |
from typing import Optional
def standardization(data: Optional[list or np.array], decimals: None or int = None):
"""
对一系列数据进行标准化处理,常用的方法是z-score标准化,处理后数据均值为0,标准差为1。
Args:
data (list or np.array): 需要被标准化的数据。
decimals (None or int): 归一化后,数值保留的精度(小数位数),默认为None,不开启
Returns:
np.ar... | c2009603ff120640c704a7fd26a24acfbd86ef64 | 58,990 |
def scale(img):
"""
scaling
"""
img = (img - np.array([123.68, 116.779, 103.939])) / np.array([58.393, 57.12, 57.375]) # img = (img - tf.constant([123.68, 116.779, 103.939])) / tf.constant([58.393, 57.12, 57.375])
return img | 8240ae4ae9653cf75d91256f8281dfcc84cee88b | 58,991 |
def set_pos(g, gtype='bipartite', **kwargs):
"""
Sets the position of nodes for plots in resultdisp.graph using a graphical tool.
Note: make sure matplotlib is set to plot in an external window (e.g using '%matplotlib qt)
Parameters
----------
g : networkx graph or model or function
nor... | 051ba95e05c22f9c2a687a6ae8bfadb3369378fe | 58,992 |
def fuzzy_replace(
words_list,
query_list,
threshold=81,
return_string=True,
scorer=fuzz.QRatio,
whitelist=False):
"""
Function to perform fuzzy replacing based on `words_list` (vocabulary)
and similarity `threshold`.
Args:
words_list (list):
... | bb6eee92adff1bb28451dec5a9b1de895f9d842a | 58,993 |
def get_type_lists(frame, rejects=['Id', 'ID','id'],frame_type='h2o'):
"""Creates lists of numeric and categorical variables.
:param frame: The frame from which to determine types.
:param rejects: Variable names not to be included in returned lists.
:param frame_type: The type of frame being used. Acc... | 24af8163bd729306f633ffaebd01fa9bfb28ae2e | 58,994 |
def calc_CTheatload(BldgDemand, BldgToCTs, CT_catalog, t_from=None, t_to=None):
"""Calculates the CT heat load to be passed to simulate_CT() by allocating the total heat load to all the CTs by
their capacity (i.e. no smart scheduling of CTs accdg. to load).
PARAMETERS:
BldgDemand DataFrame... | d6de442fc7037717a4a8ba783e4fa049d8915bc3 | 58,995 |
def dmi(sst, frequency='monthly', apply_filter=False, base_period=None,
area_weight=False, lat_name=None, lon_name=None, time_name=None):
"""Calculate dipole mode index.
The DMI introduced by Saji et al is defined as the
difference in SST anomalies between the western and
south-eastern tropical... | a8622fef9d61aa8a52030ec82c4ac3acc5fa9589 | 58,996 |
from typing import Optional
from typing import Tuple
def ptr_to_fresh(c : Contract, ty : LLVMType, name : Optional[str] = None) -> Tuple[FreshVar, SetupVal]:
"""Add to``Contract`` ``c`` an allocation of a pointer of type ``ty`` initialized to an unknown fresh value.
:returns A fresh variable bound to the... | bdc38bfb75ee2b30d88df65e9961f06444f5398a | 58,997 |
import signal
def fit_continuum(wav, spec, func='polynomial', order=3, nit=5,
rej_low=2.0, rej_high=2.5, grow=1, med_filt=0,
percentile_low=0.0, percentile_high=100.0,
min_points=10, verbose=False):
"""
Continuum fitting re-implemented from IRAF's 'continu... | be3c55ef3b763a81511bf04b32b36262ca8ee716 | 58,998 |
def create_rule_name(name, rule):
"""
Produce a gcp compatible rule name
"""
rule_name = '{name}-from-{rule[sources]}-to-{rule[allowed]}'.format(
name=name,
rule=rule)
return utils.get_gcp_resource_name(rule_name) | 417b277888e5c7b231d979d505bfbe4b1cf921d5 | 59,000 |
def get_Flesch_Kincaid(spacy_papers):
"""
gets Flesch-Kincaid readability score for dictionary of spacy papers
FKRA = (0.39 x ASL) + (11.8 x ASW) - 15.59
"""
sent_lengths = {}
syllables = {}
readability = {}
asl = {}
asw = {}
readability = {}
for k in spacy_papers.keys():
... | 19c68520c19a032a7810ec907fcb2fd2cac3677d | 59,001 |
def get_stock_min_data(code=None, date=None, ktype=1, retry_count=100000, pause=0.1):
"""
获取分钟数据
Parameters
------
code:string
股票代码 e.g. 600048
date:string
日期 format:YYYY-MM-DD
retry_count : int, 默认 10000
如遇网络等问题重复执行的次数
... | b00c259a8f78485fea8cb6b7ac7c51f5317413ba | 59,002 |
def type_from_name(name):
"""Return the GType for a name."""
return gobject_lib.g_type_from_name(_to_bytes(name)) | 8d1f46fb2032cb56087cce3920277cda0f29b134 | 59,003 |
import logging
def las_to_height(in_file: str, out_histogram_file: str = None) -> tuple:
"""Return a tuple of (height histogram, max height) from an LAS file.
Arguments:
in_file: the source LAS file
out_histogram_file: optional output file for the histogram data
Return:
A tuple of ... | 5f7cf322a2ba433098abd2c89e79c75254c86a12 | 59,004 |
def is_causal_sink(graph: BELGraph, node: BaseEntity) -> bool:
"""Check if the node has causal in-edges but no causal out-edges.
:param graph: A BEL graph
:param node: A BEL term
"""
return has_causal_in_edges(graph, node) and no_causal_out_edges(graph, node) | 2369f2e7b9e48422975fe50c313fb3f19c8332df | 59,005 |
import torch
def get_dataset_loader(
data,
word_dict,
classes,
device,
max_seq_length=500,
batch_size=1,
shuffle=False,
data_workers=4
):
"""Create a pytorch DataLoader.
Args:
data (list): List of training instances with index, label, and tokenized text.
word_d... | 90a8e5d44a710ef6dbbf23bcb619c3dbb6154175 | 59,006 |
def page():
""" Return HTML page
- return: HTML
- rtype: String
"""
return '<html><body><img src="stream.mjpg" width=' \
+ WIDTH + ' height=' + HEIGHT + '></body></html>' | c067666a7340cde2816038d48e52086d57c39e2c | 59,007 |
def _deriv_arctanh(x):
"""The derivative of arctanh(x)"""
return 1.0 / (1.0 - x*x) | 6c19a1b2a7d1d432a77806552adc0e26c54360ed | 59,008 |
def _save_sprite(data, output_sprite, vmax, vmin, mask=None, cmap='Greys',
format='png'):
""" Generate a sprite from a 3D Niimg-like object.
Returns: sprite
"""
# Create sprite
sprite = _data_to_sprite(data)
# Mask the sprite
if mask is not None:
mask = _data_t... | bf153a8bcd265d7c9c8c7bb3e422a259a527ecf3 | 59,009 |
def valid_geography(dataframe):
"""This checks validity of geography columns, this works
only for datasets in which there is no other repeating entity.
so this will work only for for data like GDP and DemoGraphics
"""
geocols = get_geographic_columns_from_dataframe(dataframe)
timecols = get_time... | a228613e590dbd787cfc3b1115f171bcd3a618a6 | 59,010 |
def get_config(
variant,
expl_env,
eval_env,
obs_dim,
action_dim,
replay_buffer,
):
"""
Setup of soft actor critic (SAC), used as the policy optimization procedure of MBPO
"""
M = variant['policy_kwargs']['layer_size']
qf1, qf2, target_qf1, target_q... | aabe0d8460be52a7848f78dd71efa51b009bbd81 | 59,011 |
def random_data(npoints, dtype):
"""
Generate `npoint` random points with coordinate values in the range [0, 1).
Points are both targets and sources.
Parameters:
-----------
npoints : int
Returns :
tuple(
np.array(shape=(npoints, 3), dtype=float),
np.array... | 0336e1ad9567312d3fbea0a55da8efd7c6493981 | 59,013 |
import torch
def gen_gaussian_target(heatmap, center, radius, k=1):
"""Generate 2D gaussian heatmap.
Args:
heatmap (Tensor): Input heatmap, the gaussian kernel will cover on
it and maintain the max value.
center (list[int]): Coord of gaussian kernel's center.
radius (int):... | 62441a3029f5d96f6a91f70f10f0cbd785f42976 | 59,014 |
def information_file_path(prefix, bath, pot):
""" gradient information file path
"""
return INFORMATION_FILE.path([prefix, bath, pot]) | 307bcfa4d35ffa5184b11d4caab0a8119f82c169 | 59,015 |
import requests
import json
def get_device_response(ctx):
"""Return the deserialized JSON response for /stat/device (devices)"""
r = requests.get(
ctx.obj["URL"] + "stat/device",
verify=ctx.obj["VERIFY"],
cookies=ctx.obj["COOKIES"],
)
return json.loads(r.text) | a763e3a5aedb0b2124244424f44fe7aa56bb8963 | 59,016 |
def build_ictv(cp, instruction):
"""
Build the integer representation of the input channel tag values.
:param cp: CoreParameters instance for the target architecture
:param instruction: Instruction instance
:return: integer representation of the ictv
"""
# Check sizing.
if len(instruct... | 767fa3393e567042ae13b1a613ad7dbcfd27667b | 59,017 |
def get_paths():
"""
Show the path selection window and store the selected paths in variables
:return: a tuple containing strings of data file location and target folder location
"""
root = Tk()
tk_file_loc = StringVar()
tk_target_dir = StringVar()
screen_width = root.winfo_screenwidth... | 8204d52c06d83cc58899a16424186963a240b7e2 | 59,018 |
def parse_userlogin(user, privilege):
"""Parses XCCDF logged in user and elevation"""
return {'user': user, 'privileged': parse_boolean(privilege)} | 8a7b1e6628d5401552cc43c54d7d3127db8ff84a | 59,019 |
def get_file_handlers(input_file):
""" based on extension return tools for looping over annots """
# set up parsing by file type
file_type = input_file[-3:]
if file_type.startswith("f"):
iterator = fna_hit_iterator
record_parser = fna_rec_parser
formatter = lambda g: g.format("fa... | 4634d47f0543207452653720cb9036eb79d7f768 | 59,020 |
def unique_mers(sequencelist, sizeofmer):
""" WEV
This will create a list of all of the unique Nmers of the object
The goal is to have this be flexible enough to take a list or string
"""
output = []
if isinstance(sequencelist, list) or isinstance(sequencelist, set):
for sequence in sequ... | e5e24a968dfe65480bebc2ebeaef39a3510fc4bb | 59,021 |
def calculate_rna_fourier_coefficients(save=False):
"""
Calculates Fourier coefficients of the RNA fitness function. This will try to load them
from the results folder, but will otherwise calculate from scratch. If save=True,
then coefficients will be saved to the results folder.
"""
try:
... | 6f74afec60d3a029ea3745c5ab49c79486e23e8a | 59,022 |
def test_notch(weights,width=0.05):
""" Test for a dropout of gamma-ray emission with a notch shape."""
p0 = lcprimitives.LCTopHat(p=[1-width,0])
lct = lctemplate.LCTemplate([p0],[1])
grid,vals = fill_grid(lct,weights)
return grid,vals | 3df7d28a291e25c0262e115d84e99a9bb3d256b6 | 59,023 |
def api_generate_next_task():
""" Generate next task to label
"""
# try to find task is not presented in completions
project = project_get_or_create()
completions = project.get_completions_ids()
for task_id, task in project.iter_tasks():
if task_id not in completions:
log.inf... | a4244351a46b481965e83ea82d60e96942cc3570 | 59,024 |
def parse_context_var(context, variable_name):
"""解析上下文中的变量
如果以'$'字符开头,那么返回上下文中的对应变量
其它的情况会直接返回字符串
开头两个$$连续为转义,比如'$$aa$$a'为'$aa$$a'
:param context 上下文
:param variable_name
"""
if not isinstance(variable_name, str):
return variable_name
elif variable_name.starts... | d9dbe2a8341179cc5157396a74125b488c0ff053 | 59,025 |
def locate(path, forceload=False):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in path.split('.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport('.'.join(parts[:n + 1]), forceload)
if nextmodule:
mo... | c32bd5061330710fb32244d7349d9fe46153d9bf | 59,026 |
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs):
"""
Format csv rows parsed to Dict or Array
"""
result = None
c_headers = [] if c_headers is None else c_headers
r_headers = [] if r_headers is None else r_headers
rows = [] if rows is None else rows
result_f... | 4b519f6224053aa69ad2033942b9a7357e521a83 | 59,028 |
import ipaddress
def _ipversion(_network):
"""
Return the address version
"""
try:
network = ipaddress.ip_network(u'{}'.format(_network))
except ValueError as err:
log.error("Invalid network {}".format(err))
return 'ipv4'
if network.version == 6:
return 'ipv6'
... | 9066696d451fbde7f2febb0e0990525befc74f75 | 59,030 |
import datasets
def load_data():
"""
读取scikit-learn自带数据:手写数字
"""
digits = datasets.load_digits()
X = digits.data
y = digits.target
return X, y | 61fdcd54c3d61a4316e80709611dd0ed0f1fb9f8 | 59,032 |
def computespectrum_pvtch(uvw,
p,
xy,
xy_sf,
shkl,
eta_mixing,
tth,
dsp,
hkl,
strain_direction_dot_product,
is_in_sublattice,
tth_lis... | 6b0e7db903b0f98733cd80f686ff56f9521861bb | 59,033 |
import functools
def measure_time_cm(logger=None, disabled=False):
"""
Get a context manager for measuring execution time of code blocks and logging the result.
Measure duration and log output:::
measure_time = measure_time_cm()
with measure_time("heavy computation"):
do_heav... | 80b4606fe4c913d9f3b5b666a0455fec03a90860 | 59,034 |
def change_seating(old_map, tolerance):
""" Seat people based on given rule """
new_map = list()
for row, _ in enumerate(old_map):
line = list()
for col, _ in enumerate(old_map[0]):
adjacents = (
check_adjacents(row, col, old_map)
if tolerance == ... | 8dd203653b35899368700e5f87e2c6a535d1126a | 59,035 |
def stresses_for_word(find):
"""Get a list of possible stress patterns for a given word.
.. doctest::
>>> import pronouncing
>>> pronouncing.stresses_for_word('permit')
['01', '12']
:param find: a word to find
:returns: a list of possible stress patterns for the given word.
... | 62c8fd54d7883fd53bfcb056c83df1adb3e2f7fa | 59,036 |
def logo_round(v, *args):
"""
ROUND num
outputs the nearest integer to the input.
"""
return round(v, *args) | fcbf49a40ee95fcbf4c9af62f6b52aed5bfac0a6 | 59,037 |
from typing import List
def get_axis_types(rai: "RandomAccessibleInterval") -> List["AxisType"]:
"""
imagej.dims.get_axis_types(image) is deprecated. Use this code instead:
axis_types = [axis.type() for axis in image.dim_axes]
"""
_logger.warning(
"imagej.dims.get_axis_types(image) is... | 65f114726f0ee364e9feebfb7c94cdaee18f7617 | 59,038 |
import pickle
def get_palette(palette_file):
"""
load color palette
:param palette_file:
:return:
"""
with open(palette_file, 'rb') as fr:
color_palette = pickle.load(fr)
return color_palette | 29d8a661eed7f50d67e108a07017fc93019bfa3c | 59,039 |
def grr_stat_impl(path: Text, path_type: Text = OS) -> pd.DataFrame:
"""Stats the file specified.
Accepts glob expressions as a file path.
Args:
path: File path to stat.
path_type: Path type to use (one of os, tsk, ntfs, registry).
Returns:
A sequence of stat entries.
Raises:
NoClientSelec... | 5027b042508e7c9d4d06762adce8d4a04c57ef8c | 59,040 |
def get_primes_below(n):
""" Returns a list of primes < n """
sieve = [True] * n
q = int(n**0.5)+1
for i in xrange(3, q, 2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
result = [2] + [i for i in xrange(3,n,2) if sieve[i]]
return result | aabd4db41833daa989a2526bc3d9b6622edfc193 | 59,041 |
import html
def scrape_page(url):
"""
Scrapes a web page given a url and returns an HTML tree representation.
This will check for a cachced version of the page before scraping and will attempt to cache
after scraping
:param url: A string of the url of the requested web page
:return: html tree ... | 01946ccfd56219029bd3bd58ebbffdabca2ee7fd | 59,042 |
def actvn(x):
"""
utility helper for leaky Relu activation
:param x: input tensor
:return: activation applied tensor
"""
out = F.leaky_relu(x, 2e-1)
return out | 950e37c58a3220d5023b241457eec23f1f805061 | 59,043 |
def is_name_dict_tuple(transform):
"""Check the transform is somehow like
('normalize_adj', dict(rate=1.0))
"""
return len(transform) == 2 and isinstance(transform[0], str) and isinstance(transform[1], dict) | 4b4803b8263e65d1461a4b4870b12fdcc9e0ee55 | 59,045 |
def get_lookup_dict():
""" Create a dictionary for records already indexed. This is used during
crawling to see if a record for a given identifier (e.g. the label +
value for a metadata entry) already exists, and if so, provide the DB
ID it was given to create new associations (e.g. with Can... | 651c288569d0816219a1db627f80f6a6f7916397 | 59,046 |
import logging
import json
def authenticate(msg, extra_info):
"""Sends a 401 response that enables basic auth"""
logging.info('User parameters: %s', json.dumps(extra_info))
return Response(json.dumps({'status': 'ERROR', 'message': msg}), 401,
mimetype="application/json") | 4386258fcc379fadff86ce4253652a8f00d8c191 | 59,047 |
def float_to_string(value):
"""
"""
if value < 1:
if (value - int(value)) < 0.001:
return str(0)
return decimal_to_string(value)
if value == 1:
return str(1)
else:
if (value - int(value)) < 0.001:
return str(int(value))
return "{} {... | d63f8451ef73bd579774f80d4eca157d85067ff9 | 59,049 |
def get_cross_covariance(maml, x_spt, x_qry, y_spt, y_qry):
"""
The feature (\phi(s) or \phi(q)) of data is obtained
through maml.net.forward_nolinear which returns
the embedded data (i.e., the data before the linear layer).
"""
# Obtain the features
for i_batch in range(1):
... | 736b9aca2ee5da998f323c1e5d891b4ebad8cc72 | 59,050 |
def _get_ratelimit_sleep():
"""
Return the configured time to wait before retrying after a ratelimit has been enforced.
"""
return config.get_cloud_config_value(
"ratelimit_sleep",
get_configured_provider(),
__opts__,
search_global=False,
default=0,
) | 1701372a8d925e84034c2814d7e29084a1495b60 | 59,051 |
import math
def calculate_ransac_iterations(min_points_per_sample, outlier_rate, desired_success_probability):
"""Estimates how many RANSAC iterations you should run.
Args:
min_points_per_sample: Minimum number of points to build a model hypothesis.
outlier_rate: Float, 0-1, how often outlier... | cafca93f052770f695f90d5f37e088e880fd0c45 | 59,052 |
import pymbar
import io
import torch
def _bennett_acceptance_ratio_pymbar(forward_work, reverse_work, compute_uncertainty=True, maximum_iterations=500, relative_tolerance=1e-12):
"""pymbar reference implementation"""
ctx = {"device": forward_work.device, "dtype": forward_work.dtype}
f = io.StringIO()
... | 2d6d8d8206e4fad629c15ef9d5eb6e2861303f86 | 59,053 |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Set
def collectScratchSlots(
subroutineBlocks: Dict[Optional[SubroutineDefinition], TealBlock]
) -> Tuple[Set[ScratchSlot], Dict[Optional[SubroutineDefinition], Set[ScratchSlot]]]:
"""Find and return all referenced... | 46b1a94765dbbcc1bd3da2a9ae4f7f2fd210755d | 59,054 |
def binning_gradient(binning, amp, phsp, m_phsp, var):
"""
calculate bin error for fit
including error propagation (gradients) and weights
"""
nfit = []
for i in range(binning.shape[0] - 1):
m_min = binning[i]
m_max = binning[i + 1]
phsp_i = data_mask(phsp, (m_phsp > m_mi... | 6864c475c3fbd4fedd89cf2c6b5d08f3f712ab22 | 59,056 |
def hi():
"""Tests for connection, says hi."""
return send_this('hi') | ab222b7fc72c0a088147d3543772748768652d69 | 59,057 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.