content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def simple_split_with_list(x, y, train_fraction=0.8, seed=None):
"""Splits data stored in a list.
The data x and y are list of arrays with shape [batch, ...].
These are split in two sets randomly using train_fraction over the number of
element of the list. Then these sets are returned with
the arra... | 5,330,000 |
def unix_socket_path(suffix=""):
"""A context manager which returns a non-existent file name
and tries to delete it on exit.
"""
assert psutil.POSIX
path = unique_filename(suffix=suffix)
try:
yield path
finally:
try:
os.unlink(path)
except OSError:
... | 5,330,001 |
def test_list_int_enumeration_3_nistxml_sv_iv_list_int_enumeration_4_3(mode, save_output, output_format):
"""
Type list/int is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/int/Schema+Instance/NISTSchema-SV-IV-list-int-enumeration-4.xsd",
instance="nistData/... | 5,330,002 |
def save_correlation_heatmap_results(
correlations: pd.DataFrame, intensity_label: str = "Intensity", show_suptitle: bool = True,
close_plots: str = "all", exp_has_techrep: bool = False, **kwargs
) -> Tuple[plt.Figure, plt.Axes]:
"""
Saves the plot with prefix: {{name}}
Parameters
-----... | 5,330,003 |
def copy_file_with_stream(input_file_name, output_file_name):
"""Copies a file from the file system into an output file on the file system using streams"""
input_file = open(input_file_name, 'rb')
stream = io.BytesIO()
l = input_file.read(1024)
with open(output_file_name, 'w') as output_file:
... | 5,330,004 |
def get_star(star_path, verbose=False, recreate=False):
"""Return a varconlib.star.Star object based on its name.
Parameters
----------
star_path : str
A string representing the name of the directory where the HDF5 file
containing a `star.Star`'s data can be found.
Optional
---... | 5,330,005 |
def get_terminal_map():
"""Get a map of device-id -> path as a dict.
Used by Process.terminal()
"""
ret = {}
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
for name in ls:
assert name not in ret, name
try:
ret[os.stat(name).st_rdev] = name
except FileNo... | 5,330,006 |
def targets(inventory="/etc/ansible/hosts", **kwargs):
"""
Return the targets from the ansible inventory_file
Default: /etc/salt/roster
"""
if not os.path.isfile(inventory):
raise CommandExecutionError("Inventory file not found: {}".format(inventory))
extra_cmd = []
if "export" in k... | 5,330,007 |
def get_relative_days(days):
"""Calculates a relative date/time in the past without any time offsets.
This is useful when a service wants to have a default value of, for example 7 days back. If an ISO duration format
is used, such as P7D then the current time will be factored in which results in the earlie... | 5,330,008 |
def find_pending_trade(df):
""" Find the trade value according to its sign like negative number means Sell type
or positive number means Buy """
p_df = pd.DataFrame()
p_df['Type'] = df['Buy_Qty'] - df['Sell_Qty']
return p_df['Type'].map(lambda val: trade_type_conversion(val)) | 5,330,009 |
def validate_root_vertex_directives(root_ast):
"""Validate the directives that appear at the root vertex field."""
directives_present_at_root = set()
for directive_obj in root_ast.directives:
directive_name = directive_obj.name.value
if is_filter_with_outer_scope_vertex_field_operator(direc... | 5,330,010 |
def test_chpi_adjust():
"""Test cHPI logging and adjustment."""
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')
with catch_logging() as log:
_get_hpi_initial_fit(raw.info, adjust=True, verbose='debug')
_get_hpi_info(raw.info, verbose='debug')
# Ran MaxFilter (with -list, -v, -m... | 5,330,011 |
def setup_database(conn: sqlite3.Connection) -> None:
"""
Sets up the schema of the Moonstream NFTs dataset in the given SQLite database.
"""
cur = conn.cursor()
cur.execute(CREATE_NFTS_TABLE_QUERY)
cur.execute(create_events_table_query(EventType.TRANSFER))
cur.execute(create_events_table_q... | 5,330,012 |
def rtri(x, a, b):
"""Convolution of rect(ax) with tri(bx)."""
assert a > 0
assert b > 0
return b*(step2(x + 1/(2*a) + 1/b) - 2*step2(x + 1/(2*a)) + step2(x + 1/(2*a) - 1/b) - step2(x - 1/(2*a) + 1/b) + 2*step2(x - 1/(2*a)) - step2(x - 1/(2*a) - 1/b)) | 5,330,013 |
def make_xgboost_predict_extractor(
eval_shared_model: tfma.EvalSharedModel,
eval_config: tfma.EvalConfig,
) -> extractor.Extractor:
"""Creates an extractor for performing predictions using a xgboost model.
The extractor's PTransform loads and runs the serving pickle against
every extract yielding a copy... | 5,330,014 |
def cloth():
"""Runs a simple cloth simulation based on linked springs."""
from .cloth import run
run() | 5,330,015 |
def test_coal_heat_content(pudl_out_orig, live_pudl_db):
"""Check that the distribution of coal heat content per unit is valid."""
if not live_pudl_db:
raise AssertionError("Data validation only works with a live PUDL DB.")
for args in pudl.validate.gf_eia923_coal_heat_content:
pudl.validat... | 5,330,016 |
def zip_score_list(exp_list, savedir_base, out_fname, include_list=None):
"""Compress a list of experiments in zip.
Parameters
----------
exp_list : list
List of experiments to zip
savedir_base : str
Directory where the experiments from the list are saved
out_fname : str
... | 5,330,017 |
def training_dataset() -> Dataset:
"""Creating the dataframe."""
data = {
"record1": [
{"@first_name": "Hans", "@last_name": "Peter"},
{"@first_name": "Heinrich", "@last_name": "Meier"},
{"@first_name": "Hans", "@last_name": "Peter"},
],
"record2": [
... | 5,330,018 |
def getWCSForcamera(cameraname, crpix1, crpix2):
""" Return SIP non-linear coordiante correction object intialized for a camera from a lookup table.
If the camera is not in the lookup table, an identify transformation is returned.
TODO: variable order, so far limit ouselves to second order
TODO: Time... | 5,330,019 |
def split_by_table_id_and_write(
examples,
output_dir,
train_suffix = ".tfrecord",
test_suffix = ".tfrecord",
num_splits = 100,
proto_message=interaction_pb2.Interaction,
):
"""Split interactions into train and test and write them to disc."""
train, test = (
examples
| "Partition... | 5,330,020 |
def get_full_frac_val(r_recalc,fs,diff_frac=0,bypass_correction=0):
"""
Compute total offset in number of samples, and also fractional sample correction.
Parameters
----------
r_recalc : float
delay.
fs : float
sampling frequency.
diff_frac : 0
[unused] 0 b... | 5,330,021 |
def extract_random_tiles(
dataset_dir: str,
processed_path: str,
tile_size: Tuple[int, int],
n_tiles: int,
level: int,
seed: int,
check_tissue: bool,
) -> None:
"""Save random tiles extracted from WSIs in `dataset_dir` into `processed_path`/tiles
Parameters
----------
datase... | 5,330,022 |
def get_code():
"""
returns the code for the min cost path function
"""
return inspect.getsource(calculate_path) | 5,330,023 |
def box_net(images,
level,
num_anchors,
num_filters,
is_training,
act_type,
repeats=4,
separable_conv=True,
survival_prob=None,
strategy=None,
data_format='channels_last'):
"""Box regression network... | 5,330,024 |
def main_plot(experiments, legends=None, smoothing_window=10, resample_ticks=None,
x_key="Episode",
y_key='Accumulated Reward', **kwargs
):
"""
Plot an experiment. To plot invidual lines (i.e. no averaging) use
> units="Unit", estimator=None,
"""
ensure_lis... | 5,330,025 |
def user_similarity_pearson(train, iif=False):
"""
通过皮尔逊相关系数计算u和v的兴趣相似度
:param train: 训练集
:param iif: 是否惩罚热门物品
"""
global _avr
_avr = {}
item_users = {}
for user, items in train.iteritems():
_avr[user] = sum(items.itervalues()) / len(items)
for item, rating in items.i... | 5,330,026 |
def NewSetup(*setupnames):
"""Load the given setups instead of the current one.
Example:
>>> NewSetup('tas', 'psd')
will clear the current setup and load the "tas" and "psd" setups at the
same time.
Without arguments, the current setups are reloaded. Example:
>>> NewSetup()
You ca... | 5,330,027 |
def get_distance_to_center(
element: object, centers: "Set[object]", distance_function: "function"
) -> float:
"""
Returns the distance from the given point to its center
:param element: a point to get the distance for
:param centers: an iteratable of the center points
:param distance_function... | 5,330,028 |
def auto_delete_file_on_change(sender, instance, **kwargs):
"""
Deletes old file from filesystem when corresponding
`Worksheet` object is updated with a new file.
"""
if not instance.pk:
return False
db_obj = Worksheet.objects.get(pk=instance.pk)
exists = True
try:
old_f... | 5,330,029 |
def clean_immigration_data(validPorts: dict, immigration_usa_df: psd.DataFrame, spark: pss.DataFrame) -> psd.DataFrame:
"""[This cleans immigration data in USA. It casts date of immigrant entry, city of destination, and port entry.]
Args:
validPorts (dict): [dictionery that includes valid entry ports i... | 5,330,030 |
def copy_dir(dir_from, dir_to):
""" Copy a complete directory """
print "%s/ -> %s/" % (dir_from, dir_to)
try:
shutil.copytree(dir_from, dir_to)
except Exception, err:
error("can't copy '%s' to '%s' (%s)" % (dir_from, dir_to, str(err))) | 5,330,031 |
def prepare(args: dict, overwriting: bool) -> Path:
"""Load config and key file,create output directories and setup log files.
Args:
args (dict): argparser dictionary
Returns:
Path: output directory path
"""
output_dir = make_dir(args, "results_tmp", "aggregation", overwriting)
... | 5,330,032 |
def dd_wave_function_array(x, u_array, Lx):
"""Returns numpy array of all second derivatives
of waves in Fourier sum"""
coeff = 2 * np.pi / Lx
f_array = wave_function_array(x, u_array, Lx)
return - coeff ** 2 * u_array ** 2 * f_array | 5,330,033 |
def plot_energy_fluxes(solver, fsrs, group_bounds=None, norm=True,
loglog=True, get_figure=False):
"""Plot the scalar flux vs. energy for one or more FSRs.
The Solver must have converged the FSR sources before calling this routine.
The routine will generate a step plot of the flux ac... | 5,330,034 |
def test_atomic_any_uri_min_length_3_nistxml_sv_iv_atomic_any_uri_min_length_4_3(mode, save_output, output_format):
"""
Type atomic/anyURI is restricted by facet minLength with value 50.
"""
assert_bindings(
schema="nistData/atomic/anyURI/Schema+Instance/NISTSchema-SV-IV-atomic-anyURI-minLength-... | 5,330,035 |
def surface_distance_ground_truth_plot(ct: np.ndarray, ground_truth: np.ndarray, sds_full: np.ndarray, subject_id: int,
structure: str, plane: Plane, output_img_dir: Path, dice: float = None,
save_fig: bool = True,
... | 5,330,036 |
def handle_health_check():
"""Return response 200 for successful health check"""
return Response(status=200) | 5,330,037 |
def pow(x, n):
""" pow(x, n)
Power function.
"""
return x**n | 5,330,038 |
def create_graph_from_path(path: Path) -> None:
"""Loads recursively all Kubernetes manifests with a yaml file extension in the given directory and constructs a
Caboto graph data structure."""
for p in path.rglob("*.yaml"):
with open(p.absolute(), "r") as stream:
try:
fil... | 5,330,039 |
def read_fifo():
"""
Read messages from the FIFO.
"""
# init fifo
try:
os.unlink(fifo_file)
except OSError, e:
if e.errno == os.errno.ENOENT:
pass
oldmask = os.umask(0)
os.mkfifo(fifo_file, 0777)
os.umask(oldmask)
while True:
fd = open(fifo_fil... | 5,330,040 |
def download_cad_model():
"""Download cad dataset."""
return _download_and_read('42400-IDGH.stl') | 5,330,041 |
def dot_product(u, v):
"""Computes dot product of two vectors u and v, each represented as a tuple
or list of coordinates. Assume the two vectors are the same length."""
output = 0
for i in range(len(u)):
output += (u[i]*v[i])
return output | 5,330,042 |
def precise_diff(
d1, d2
): # type: (typing.Union[datetime.datetime, datetime.date], typing.Union[datetime.datetime, datetime.date]) -> PreciseDiff
"""
Calculate a precise difference between two datetimes.
:param d1: The first datetime
:type d1: datetime.datetime or datetime.date
:pa... | 5,330,043 |
def get_module_doctest_tup(
testable_list=None,
check_flags=True,
module=None,
allexamples=None,
needs_enable=None,
N=0,
verbose=True,
testslow=False,
):
"""
Parses module for testable doctesttups
enabled_testtup_list (list): a list of testtup
testtup (tuple): (name, nu... | 5,330,044 |
def subset_lists(L, min_size=0, max_size=None):
"""Strategy to generate a subset of a `list`.
This should be built in to hypothesis (see hypothesis issue #1115), but was rejected.
Parameters
----------
L : list
List of elements we want to get a subset of.
min_size : int
Minimum... | 5,330,045 |
async def async_setup_entry(
hass: HomeAssistant,
entry: config_entries.ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Flux lights."""
coordinator: FluxLedUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
device = coordinator.device
entities: list[
... | 5,330,046 |
def DCNPack(x, extra_feat, out_channels, kernel_size=(3, 3), strides=(1, 1), padding='same', dilations=(1, 1),
use_bias=True, num_groups=1, num_deform_groups=1, trainable=True, dcn_version='v2', name='DCN'):
"""Deformable convolution encapsulation that acts as normal convolution layers."""
with tf.v... | 5,330,047 |
def endtiming(fn):
"""
Decorator used to end timing.
Keeps track of the count for the first and second calls.
"""
NITER = 10000
def new(*args, **kw):
ret = fn(*args, **kw)
obj = args[0]
if obj.firststoptime == 0:
obj.firststoptime = time.time()
elif ob... | 5,330,048 |
def web_test_named_executable(testonly = True, **kwargs):
"""Wrapper around web_test_named_executable to correctly set defaults."""
_web_test_named_executable(testonly = testonly, **kwargs) | 5,330,049 |
def CreateRailFrames(thisNurbsCurve, parameters, multiple=False):
"""
Computes relatively parallel rail sweep frames at specified parameters.
Args:
parameters (IEnumerable<double>): A collection of curve parameters.
Returns:
Plane[]: An array of planes if successful, or an empty array ... | 5,330,050 |
def news(stock):
"""analyzes analyst recommendations using keywords and assigns values to them
:param stock: stock that will be analyzed
:return recommendations value"""
stock = yf.Ticker(str(stock))
reco = str(stock.recommendations) # Stands for recomend
reco = reco.split()
reco.revers... | 5,330,051 |
async def test_tilt_via_topic_altered_range(opp, mqtt_mock):
"""Test tilt status via MQTT with altered tilt range."""
assert await async_setup_component(
opp,
cover.DOMAIN,
{
cover.DOMAIN: {
"platform": "mqtt",
"name": "test",
"... | 5,330,052 |
def get_pulse_coefficient(pulse_profile_dictionary, tt):
"""
This function generates an envelope that smoothly goes from 0 to 1, and back down to 0.
It follows the nomenclature introduced to me by working with oscilloscopes.
The pulse profile dictionary will contain a rise time, flat time, and fall tim... | 5,330,053 |
def parse_variable_char(packed):
""" Map a 6-bit packed char to ASCII """
packed_char = packed
if packed_char == 0:
return ""
if 1 <= packed_char <= 10:
return chr(ord('0') - 1 + packed_char)
elif 11 <= packed_char <= 36:
return chr(ord('A') - 11 + packed_char)
elif 37 <=... | 5,330,054 |
def do_emulator_error_plots(
data: PowerSpecs,
means_mf: List[np.ndarray],
means_sf: List[np.ndarray],
pred_exacts_mf: List[np.ndarray],
pred_exacts_sf: List[np.ndarray],
label_mf: str = "NARGP",
label_sf: str = "HF only",
figure_name: str = "",
):
"""
1. predicted / exact power ... | 5,330,055 |
def get_feature_vector(feature_id, cohort_id_array):
"""
Fetches the data from BigQuery tables for a given feature identifier and
one or more stored cohorts. Returns the intersection of the samples defined
by the feature identifier and the stored cohort.
Each returned data point is represented as a... | 5,330,056 |
def batch_get_logs(
jobs: List[AWSBatchJob],
jobs_db: AioAWSBatchDB = None,
aio_batch_config: AWSBatchConfig = None,
):
"""
Get job logs.
:param jobs: any AWSBatchJob
:param jobs_db: an optional jobs-db to persist job data;
this is only applied if an aio_batch_config is not provided... | 5,330,057 |
def transcript_iterator(gff_iterator, strict=True):
"""iterate over the contents of a gtf file.
return a list of entries with the same transcript id.
Any features without a transcript_id will be ignored.
The entries for the same transcript have to be consecutive
in the file. If *strict* is set an... | 5,330,058 |
def analyse(tx):
"""
Analyses a given set of features. Marks the features with zero
variance as the features to be deleted from the data set. Replaces
each instance of a null(-999) valued feature point with the mean
of the non null valued feature points. Also handles the outliers
by clipping th... | 5,330,059 |
def validate_word_syntax(word):
"""
This function is designed to validate that the syntax for
a string variable is acceptable.
A validate format is English words that only contain alpha
characters and hyphens.
:param word: string to validate
:return: boolean true or false
"""
if le... | 5,330,060 |
def select_hierarchy(root=None, add=False):
"""
Selects the hierarchy of the given node
If no object is given current selection will be used
:param root: str
:param add: bool, Whether new selected objects need to be added to current selection or not
"""
raise NotImplementedError() | 5,330,061 |
def next_page(context):
"""
Get the next page for signup or login.
The query string takes priority over the template variable and the default
is an empty string.
"""
if "next" in context.request.GET:
return context.request.GET["next"]
if "next" in context.request.POST:
retu... | 5,330,062 |
def main(eml: str):
"""
Encodes entity names in the EML file to the PASTA equivalent.
\b
EML: EML file
"""
p = Path(eml)
if not p.exists():
msg = f"File '{eml}' not found."
raise FileNotFoundError(msg)
eml_file = p.read_text()
names = list()
xml... | 5,330,063 |
def process_references(ctx: Context):
"""
Processes references in the Markdown text
Args:
ctx: Context
"""
ctx.latex_refs = list()
for abbrev, raw_ref in ctx.settings.references.items():
if abbrev in ctx.markdown_text:
ref = Reference(raw_ref, abbrev)
ctx... | 5,330,064 |
def make_train_test_sets(input_matrix, label_matrix, train_per_class):
"""Return ((training_inputs, training_labels), (testing_inputs, testing_labels)).
Args:
input_matrix: attributes matrix. Each row is sample, each column is attribute.
label_matrix: labels matrix. Each row is sample, each col... | 5,330,065 |
def add_coords_table(document: Document, cif: CifContainer, table_num: int):
"""
Adds the table with the atom coordinates.
:param document: The current word document.
:param cif: the cif object from CifContainer.
:return: None
"""
atoms = list(cif.atoms())
table_num += 1
headline = "... | 5,330,066 |
def bz(xp, yp, zp, spheres):
"""
Calculates the z component of the magnetic induction produced by spheres.
.. note:: Input units are SI. Output is in nT
Parameters:
* xp, yp, zp : arrays
The x, y, and z coordinates where the anomaly will be calculated
* spheres : list of :class:`fatia... | 5,330,067 |
def update_stocks():
"""
method to update the data (used by the spark service)
:return:
"""
global stocks
body = request.get_json(silent=True)
'''
{
"data" : [
{
"symbol" : "string",
"ask_price" : "string",
"last_sale_t... | 5,330,068 |
def chunks_from_iterable(iterable: Iterable[T], size: int) -> Iterable[Sequence[T]]:
"""Generate adjacent chunks of data"""
it = iter(iterable)
return iter(lambda: tuple(itertools.islice(it, size)), ()) | 5,330,069 |
def p_transitions(p):
"""
transition_list : transition
"""
p[0] = [p[1]] | 5,330,070 |
def load_ct_phantom(phantom_dir):
"""
load the CT data from a directory
Parameters
----------
phantom_dir : str
The directory contianing the CT data to load
Returns
-------
ndarray
the CT data array
list
the spacing property for this CT
"""
# dicom ... | 5,330,071 |
def summary_overall(queryset: QuerySet) -> Dict[str, Decimal]:
"""Summarizes how much money was spent"""
amount_sum = sum([value[0] for value in queryset.values_list('amount')])
return {'overall': amount_sum} | 5,330,072 |
def test_min_middleware_with_exclude(monkeypatch, test_case: dict[str, str], settings) -> None:
"""Very simple basic minify test."""
settings.HMIN_EXCLUDE = ["hello/", "unrelated/", "strange/trash/happens/"]
importlib.reload(middleware)
_run_inner_middleware_test(test_case) | 5,330,073 |
def test_calculate_smoothness_cost():
""" The Laplacian of a constant field is zero """
u = 10*np.ones((10, 10, 10))
v = 10*np.ones((10, 10, 10))
w = 0*np.ones((10, 10, 10))
dx = 100.0
dy = 100.0
dz = 100.0
z = np.arange(0, 1000.0, 100)
cost = pydda.cost_functions.calculate_smoothn... | 5,330,074 |
def _get_trained_ann(train_exo: "ndarray", train_meth: "ndarray") -> "QdaisANN2010":
"""Return trained ANN."""
train_data = BiogasData(train_exo, train_meth)
ann = QdaisANN2010(train_data.train_exo.shape[1])
try:
ann.load_state_dict(torch.load("./assets/ann.pt"))
except IOError:
opti... | 5,330,075 |
def pi_float():
"""native float"""
lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s | 5,330,076 |
def test_atoms_material_cell(uo2, water):
""" Test if correct number of atoms is returned.
Also check if Cell.atoms still works after volume/material was changed
"""
c = openmc.Cell(fill=uo2)
c.volume = 2.0
expected_nucs = ['U235', 'O16']
# Precalculate the expected number of atoms
M = ... | 5,330,077 |
def work_permit_notify_grd_supervisor(reminder_indicator): # at 9am checks grd supervisor approval on online application
""" Notify GRD Supervisor to remind accepting WP on ASHAL application """
# Get work permit list
if reminder_indicator == 'yellow':
filters = {'docstatus': 1,
'grd_operat... | 5,330,078 |
def iso3_to_country(iso3):
""" Take user input and convert it to the short version of the country name """
if iso3 == 'Global':
return 'Global'
country = coco.convert(names=iso3, to='name_short')
return country | 5,330,079 |
def test_bivariate(N, n_neighbors, rng, noise):
"""Test with bivariate normal variables"""
mu = np.zeros(2)
cov = np.array([[1., 0.8], [0.8, 1.0]])
xy_gauss = rng.multivariate_normal(mu, cov, size=N)
x, y = xy_gauss[:, 0], xy_gauss[:, 1]
z = rng.normal(size=N)
cmi_analytic = -0.5 * np.log(d... | 5,330,080 |
def osm_tile_number_to_latlon(xtile, ytile, zoom):
""" Returns the latitude and longitude of the north west corner of a tile, based on the tile numbers and the zoom level"""
n = 2.0 ** zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
lat_deg = math.degrees(lat_... | 5,330,081 |
def to_timedelta(arg: numpy.ndarray, unit: Literal["h"]):
"""
usage.xarray: 3
"""
... | 5,330,082 |
def prodtab_111():
"""
produces angular distance from [1,1,1] plane with other planes up to (321) type
"""
listangles_111 = [anglebetween([1, 1, 1], elemref) for elemref in LISTNEIGHBORS_111]
return np.array(listangles_111) | 5,330,083 |
def cuda_cos(a):
""" Trigonometric cosine of GPUArray elements.
Parameters:
a (gpu): GPUArray with elements to be operated on.
Returns:
gpu: cos(GPUArray)
Examples:
>>> a = cuda_cos(cuda_give([0, pi / 4]))
array([ 1., 0.70710678])
>>> type(a)
... | 5,330,084 |
def top_diffs(spect: list, num_acids: int) -> list:
"""Finds at least num_acids top differences in [57, 200]
Accepts ties
:param spect: a cyclic spectrum to find differences in
:type spect: list (of ints)
:type keep: int
:returns: the trimmed leaderboard
:rtype: list (of lists (of... | 5,330,085 |
def form_sized_range(range_: Range, substs) -> typing.Tuple[
SizedRange, typing.Optional[Symbol]
]:
"""Form a sized range from the original raw range.
The when a symbol exists in the ranges, it will be returned as the second
result, or the second result will be none.
"""
if not range_.bounded:... | 5,330,086 |
def create_html_app(): # pragma: no cover
"""Returns WSGI app that serves HTML pages."""
app = webapp2.WSGIApplication(
handlers.get_frontend_routes(), debug=utils.is_local_dev_server())
gae_ts_mon.initialize(app, cron_module='backend')
return app | 5,330,087 |
def line_integrals(vs, uloc, vloc, kind="same"):
"""
calculate line integrals along all islands
Arguments:
kind: "same" calculates only line integral contributions of an island with itself,
while "full" calculates all possible pairings between all islands.
"""
if kind == "sam... | 5,330,088 |
def crop_black_borders(image, threshold=0):
"""Crops any edges below or equal to threshold
Crops blank image to 1x1.
Returns cropped image.
"""
if len(image.shape) == 3:
flatImage = np.max(image, 2)
else:
flatImage = image
assert len(flatImage.shape) == 2
rows = np.wh... | 5,330,089 |
def update():
"""
After start() is run, this function is run every frame until the back button
is pressed
"""
# Follow the wall to the right of the car without hitting anything.
scan = rc.lidar.get_samples()
left_angle, left_dist = rc_utils.get_lidar_closest_point(scan, LEFT_WINDOW)
rig... | 5,330,090 |
def change_password():
"""Allows user to change password"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# If password and confirmation don't match, accuse error
if request.form.get("new_password... | 5,330,091 |
def add_placeholders(components):
"""Add placeholders for missing DATA/INSTANCE components"""
headers = [s[:2] for s in components]
for prefix in ("CD", "CR"):
if prefix not in headers:
components.append(prefix + ("C" * 11))
return components | 5,330,092 |
def clipsToHieroClipItems(clips):
"""
@itemUsage hiero.items.HieroClipItem
"""
from ..items import HieroClipItem
clipItems = []
if clips:
for c in clips:
i = HieroClipItem(c)
clipItems.append(i)
return clipItems | 5,330,093 |
def md5(s, raw_output=False):
"""Calculates the md5 hash of a given string"""
res = hashlib.md5(s.encode())
if raw_output:
return res.digest()
return res.hexdigest() | 5,330,094 |
def _write_file(path, contents, mode='w'):
"""Write the string to the specified path.
Returns nothing if the write fails, instead of raising an IOError.
"""
try:
with open(path, mode) as f:
f.write(contents)
except IOError:
pass | 5,330,095 |
def new_Q(T, ms, Ps, G):
"""TODO DOC STRING"""
print("==> Tuning Q")
SIGMA = np.zeros_like(Ps[0], dtype=np.complex128)
PHI = np.zeros_like(Ps[0], dtype=np.complex128)
C = np.zeros_like(Ps[0], dtype=np.complex128)
shape = (Ps[0].shape[0], 1)
for k in range(1, T + 1):
m1 = gains_... | 5,330,096 |
def _get_pk_message_increase(cache_dict: dict,
project_list: list) -> str:
"""根据项目列表构建增量模式下PK播报的信息.
### Args:
``cache_dict``: 增量计算的基础.\n
``project_list``: PK的项目列表.\n
### Result:
``message``: PK进展的播报信息.\n
"""
amount_dict = _get_pk_amount(project_list)
incr... | 5,330,097 |
def test_update_all_fields(mock_get_company_updates):
"""
Test update_companies_from_dnb_service command with no options calls through to
get_company_updates celery task successfully.
"""
datetime = '2019-01-01T00:00:00'
call_command(
'update_companies_from_dnb_service',
datetime... | 5,330,098 |
def flatten(dic, keep_iter=False, position=None):
"""
Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them.
"""
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
... | 5,330,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.