content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Dict
def process_line(line: str, conditional_chain: List[str],
fields: Dict[str, str]):
""" Processes a line in the template, i.e. returns the output html code
after evaluating all if statements and filling the fields. Since we
oftentimes are in ... | d84a679d1dc292f3f9cccaf7b6f6718c1ff7cbfc | 20,400 |
def get_groundstation_code(gsi):
"""
Translate a GSI code into an EODS domain code.
Domain codes are used in dataset_ids.
It will also translate common gsi aliases if needed.
:type gsi: str
:rtype: str
>>> get_groundstation_code('ASA')
'002'
>>> get_groundstation_code('HOA')
... | a9a04935cfceeb4ca4b90f7ba05ff5c7076ff917 | 20,401 |
from typing import Union
import copy
def concatenate(*data_frames: DataFrame,
**data_points_or_frames: Union[DataFrame, DataPoint]) \
-> DataFrame:
"""
Concatenate DataFrame's objects or DataPoint's into one DataFrame.
Example:
if one DataFrame represents as:
df1 -> {... | 7f2fb0731c5f1ee8f743e086b8e5ea667f066982 | 20,402 |
def mixed_social_welfare(game, mix):
"""Returns the social welfare of a mixed strategy profile"""
return game.expected_payoffs(mix).dot(game.num_role_players) | 72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df | 20,403 |
def bdh(
tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs
) -> pd.DataFrame:
"""
Bloomberg historical data
Args:
tickers: ticker(s)
flds: field(s)
start_date: start date
end_date: end date - default today
adjust: `all`, `dvd`, `nor... | 2c57e9e7d8f1f0155dab35b59e3a2c31cf4f7aa1 | 20,404 |
import re
def isValid(text):
"""
"Play Blackjack"
"""
return bool(re.search(r'\bblackjack\b', text, re.IGNORECASE)) | c1960a9683bde9701b4e3900edd41e4d6e5444ac | 20,405 |
def init_app(app):
"""init the flask application
:param app:
:return:
"""
return app | 6e460eb1fdc19553c6c4139e60db06daec507a2d | 20,406 |
def bounds(geometry, **kwargs):
"""Computes the bounds (extent) of a geometry.
For each geometry these 4 numbers are returned: min x, min y, max x, max y.
Parameters
----------
geometry : Geometry or array_like
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc doc... | bdf90b760fc7c62d66596159136961e7840077c4 | 20,407 |
def getRidgeEdge(distComponent, maxCoord, direction):
"""
最大値〜最大値-1の範囲で、指定された方向から見て最も遠い点と近い点を見つける。
緑領域からの距離が最大値近辺で、カメラから見て最も遠い点と近い点を見つけるための関数。
これにより、石の天面の中心と底面の中心を求める
"""
# 最大値
maxValue = distComponent[maxCoord]
# 最大値-1以上の点の座標群
ridge = np.array(np.where(distComponent >= maxValue - 1)... | b22b592ee9467f1205d49e5c83dfe978b5dc2f35 | 20,408 |
def map_vL(X, w):
"""
Maps a random sample drawn from vector Langevin with orientation u = [0,...,0,1] to
a sample that follows vector Langevin with orientation w.
"""
assert w.shape[0] == X.shape[0]
#assert np.linalg.norm(w) == 1.
#print('Orientation vector length : ' + str(np.linalg.norm(w)))
d = w.shape[0]
... | a7d06a295569bb08d800c46c302c5a38ef2c2f52 | 20,409 |
def get_constant_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, last_epoch: int = -1):
"""
Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate
increases linearly between 0 and the initial lr set in the optimizer.
Args:
op... | 825c4e14f91992c39d5be37b814e5c3bd7177c50 | 20,410 |
def slid_window_avg(a, wi):
""" a simple window-averaging function, centerd on the current point """
# TODO: replace with pandas rolling average. - rth
acopy = np.array(a).copy()
a_smoothed = np.zeros(acopy.shape)
wi_half = wi // 2
wi_other_half = wi - wi_half
for i in range(acopy.shape[0]):... | bd29ca53e33b473a49fcf75cf639335fb84708fd | 20,411 |
def find_bigrams(textdict, threshold=0.1):
"""
find bigrams in the texts
Input:
- textdict: a dict with {docid: preprocessed_text}
- threshold: for bigrams scores
Returns:
- bigrams: a list of "word1 word2" bigrams
"""
docids = set(textdict.keys())
# to identify bigra... | 4f3d6e3b4b62e42a98ab8bc3f823853680ca9e6f | 20,412 |
def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_inf... | 496056126bdf390a6213dfad5c40c4a14ec35caa | 20,413 |
def find_files(config, file_to_find, exact_filename=False):
"""finds all the files in config.diag_dir that matches the prefix or will use
the config.files string (split on ,) if present and not use a prefix but a full
file name match.
Example:
files = [my.log], diag_dir = "" => only matches my.l... | 2eea21dcc29a45871629ee081b0fcb422d6163af | 20,414 |
import ast
def ast_node_to_source(ast_node: ast.AST) -> str:
"""
Uses astor package to produce source code from ast
Also handles low-level ast functions, such as wrapping in a module if necessary,
and fixing line numbers for modified/extracted ast
Args:
ast_node:
Returns:
"""
... | bc4bb2a9f09907e2c9ab8a8f1629135695da6aa9 | 20,415 |
import codecs
import os
def read(*parts):
"""
returns contents of file
"""
with codecs.open(os.path.join(PROJECT, *parts), "rb", "utf-8") as file:
return file.read() | 065320d95a93602a55c886d05ca54b8be34610ce | 20,416 |
import typing
def _get_base(*, name: str, schemas: oa_types.Schemas) -> typing.Type:
"""
Retrieve the base class of a schema considering inheritance.
If x-inherits is True, retrieve the parent. If it is a string, verify that the
parent is valid. In either case, the model for that schema is used as th... | 47bcca20c82078cd3bd821a0d10e951b346a1e87 | 20,417 |
def classNumber(A):
""" Returns the number of transition classes in the matrix A """
cos = 0
if type(A[0][0]) == list:
cos = len(A)
else:
cos = 1
return cos | a71bce468f7429746bfe246d94f5dcebb85c41d4 | 20,418 |
def lz4_decompress_c(src, dlen, dst=None):
"""
Decompresses src, a bytearray of compressed data.
The dst argument can be an optional bytearray which will have the output appended.
If it's None, a new bytearray is created.
The output bytearray is returned.
"""
if dst is None:
dst = by... | 5b2b15f323c00a8cedec4b9caee0fea8dda89f76 | 20,419 |
def format_coordinates(obj, no_seconds=True, wgs_link=True):
"""Format WGS84 coordinates as HTML.
.. seealso:: https://en.wikipedia.org/wiki/ISO_6709#Order.2C_sign.2C_and_units
"""
def degminsec(dec, hemispheres):
_dec = abs(dec)
degrees = int(floor(_dec))
_dec = (_dec - int(flo... | 1fc6a151f73e8836ee935db3cf265438e597fec2 | 20,420 |
import os
import distutils
def _defaultGromacsIncludeDir():
"""Find the location where gromacs #include files are referenced from, by
searching for (1) gromacs environment variables, (2) for the gromacs binary
'pdb2gmx' or 'gmx' in the PATH, or (3) just using the default gromacs
install location, /usr... | 126d74d22cf0ee3e37c2e718d9fa3cddb8f7e6d5 | 20,421 |
def delete_keys_on_selected():
"""
deletes set driven keys from selected controllers.
:return: <bool> True for success.
"""
s_ctrls = object_utils.get_selected_node(single=False)
if not s_ctrls:
raise IndexError("[DeleteKeysOnSelectedError] :: No controllers are selected.")
selected_... | 5d1b55bdcefcd8b4997432851e015e2a875eb80a | 20,422 |
def scan_continuation(curr, prompt_tag, look_for=None, escape=False):
"""
Segment a continuation based on a given continuation-prompt-tag.
The head of the continuation, up to and including the desired continuation
prompt is reversed (in place), and the tail is returned un-altered.
The hint value |l... | 1182394c26b6d9e745f469f5006b5269e5854db8 | 20,423 |
import logging
import os
import subprocess
def reloadATSConfigs(conf:Configuration) -> bool:
"""
This function will reload configuration files for the Apache Trafficserver caching HTTP
proxy. It does this by calling ``traffic_ctl config reload`
:param conf: An object representing the configuration of :program:`t... | cbfca3129ea6ef64bc9e30115597ce10b77063e6 | 20,424 |
def solar_wcs_frame_mapping(wcs):
"""
This function registers the coordinates frames to their FITS-WCS coordinate
type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry.
"""
dateobs = wcs.wcs.dateobs if wcs.wcs.dateobs else None
# SunPy Map adds 'heliographic_observer' and 'rsu... | dd6a52e8356a242c5f2dfb4808e0a3d1ed57073f | 20,425 |
def toa_error_peak_detection(snr):
"""
Computes the error in time of arrival estimation for a peak detection
algorithm, based on input SNR.
Ported from MATLAB Code
Nicholas O'Donoughue
11 March 2021
:param snr: Signal-to-Noise Ratio [dB]
:return: expected time of arrival ... | 4ab2f653c81a29484d96aed58cb73ca4327dbde0 | 20,426 |
from typing import Set
from typing import List
import glob
import os
import random
def scrape_random_contracts(data_dir: str, max_contracts=10000,
verbose: bool = True, filtering: bool = True, stop_words: Set[str] = None) -> List[LabeledProvision]:
"""Randomly sample contracts to extra... | a1724f4b88661faaa6ed345b2c48e3e12cabddbc | 20,427 |
def statCellFraction(gridLimit, gridSpace, valueFile):
"""
Calculate the fractional value of each grid cell, based on the
values stored in valueFile.
:param dict gridLimit: Dictionary of bounds of the grid.
:param dict gridSpace: Resolution of the grid to calculate values.
:param str valueFile: ... | e26f011c10d94435b134e9f1b3adb2d1b1cd88ce | 20,428 |
from tcrdist.repertoire import TCRrep
import re
import multiprocessing
import os
def tabulate_metaclonotype(
file,
metaclonotype_source_path,
metaclonotype_file,
source_path,
ncpus =1,
max_radius = 36,
write = False,
project_path = "counts"):
"""
Tabulate a set of meta-clonot... | af04ef49ccfa1ee8d707923a47b6f73c0267b817 | 20,429 |
def relative_url_functions(current_url, course, lesson):
"""Return relative URL generators based on current page.
"""
def lesson_url(lesson, *args, **kwargs):
if not isinstance(lesson, str):
lesson = lesson.slug
if course is not None:
absolute = url_for('course_page'... | b49009cfdb8e9095c9ca17fee39feb8689624bd4 | 20,430 |
def fix_CompanySize(r):
"""
Fix the CompanySize column
"""
if type(r.CompanySize) != str:
if r.Employment == "Independent contractor, freelancer, or self-employed":
r.CompanySize = "0 to 1 Employees"
elif r.Employment in [
"Not employed, but looking for work",
... | bd34bb3e72920fb7ef37279a743198387b1c4717 | 20,431 |
import yaml
from pathlib import Path
def write_thermo_yaml(phases=None, species=None, reactions=None,
lateral_interactions=None, units=None,
filename=None, T=300., P=1., newline='\n',
ads_act_method='get_H_act',
yaml_options={'def... | f8d12226a137d2cf3b9ddecb427dc51257498145 | 20,432 |
import random
def move_weighted(state: State, nnet: NNet) -> tuple:
"""
Returns are random move with weighted probabilities from the neural network.
:param state: State to evaluate
:param nnet: Neural network used for evaluation
:return: Move as ((origin_row, origin_column),(target_row,target_col... | 0d9ad3e6344c3c24e71530bd7bbe6dc5a0b9a254 | 20,433 |
from typing import Any
def build_get301_request(**kwargs: Any) -> HttpRequest:
"""Return 301 status code and redirect to /http/success/200.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.res... | 2ef01a4c126890fd30fd3bc656036b92d2ef0408 | 20,434 |
def error_function_latticeparameters(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
... | e1c3242855354ed82d2dd164a7ae16aa76cd5e22 | 20,435 |
def run_forward_model(z_in):
"""
Run forward model and return approximate measured values
"""
x_dummy[:prm.nn]=z_in
x_dummy[prm.nn:]=prm.compute_velocity(z_in,t0)
x_meas = H_meas.dot(x_dummy)
return x_meas | fd6bfbbacba59e08b2bb8c4588793b969cab4b60 | 20,436 |
def optimize(name: str, circuit: cirq.Circuit) -> cirq.Circuit:
"""Applies sycamore circuit decompositions/optimizations.
Args:
name: the name of the circuit for printing messages
circuit: the circuit to optimize_for_sycamore
"""
print(f'optimizing: {name}', flush=True)
start = time... | 07027dc2ad21e33ca2038cb40c3cbb2b529941e7 | 20,437 |
def download_sbr(destination=None):
"""Download an example of SBR+ Array and return the def path.
Examples files are downloaded to a persistent cache to avoid
re-downloading the same file twice.
Parameters
----------
destination : str, optional
Path where files will be downloaded. Opti... | 0b928977806b546325569dbf71e93e8b760868fa | 20,438 |
from typing import Tuple
from typing import Union
def isvalid_sequence(
level: str, time_series: Tuple[Union[HSScoring, CollegeScoring]]
) -> bool:
"""Checks if entire sequence is valid.
Args:
level: 'high school' or 'college' level for sequence analysis.
time_series: Tuple of sorted ... | 5e32906408540c504347c745113fc303ef0d989b | 20,439 |
def create_backend_app(): # pragma: no cover
"""Returns WSGI app for backend."""
routes = handlers.get_backend_routes() + swarming.get_backend_routes()
app = webapp2.WSGIApplication(routes, debug=utils.is_local_dev_server())
gae_ts_mon.initialize(app, cron_module='backend')
gae_ts_mon.register_global_metrics... | 395b34d8a8752664bc49af6d2c0b37fe76ab6956 | 20,440 |
def non_linear_relationships():
"""Plot logarithmic and exponential data along with correlation coefficients."""
# make subplots
fig, axes = plt.subplots(1, 2, figsize=(12, 3))
# plot logarithmic
log_x = np.linspace(0.01, 10)
log_y = np.log(log_x)
axes[0].scatter(log_x, log_y)
axes[0].s... | 86ce934aebc6b6f8e6b5c1826d9d26c408efc8df | 20,441 |
import io
def label_samples(annotation, atlas, atlas_info=None, tolerance=2):
"""
Matches all microarray samples in `annotation` to parcels in `atlas`
Attempts to place each sample provided in `annotation` into a parcel in
`atlas`, where the latter is a 3D niimg-like object that contains parcels
... | 65a3f83b031871a14b250df48c9edef3cdcce7ac | 20,442 |
def group_by(x, group_by_fields='Event', return_group_indices=False):
"""
Splits x into LIST of arrays, each array with rows that have same
group_by_fields values.
Gotchas:
Assumes x is sorted by group_by_fields (works in either order, reversed
or not)
Does NOT put in empty lists... | 12e8034556ca303a9ebd2ccaab83cbcc131b0bec | 20,443 |
def unlock_file(fd):
"""unlock file. """
try:
fcntl.flock(fd, fcntl.LOCK_UN)
return (True, 0)
except IOError, ex_value:
return (False, ex_value[0]) | 2c6ce071072fa45607ce284b0881af5df44b5e6d | 20,444 |
def DsseTrad(nodes_num, measurements, Gmatrix, Bmatrix, Yabs_matrix, Yphase_matrix):
"""
Traditional state estimator
It performs state estimation using rectangular node voltage state variables
and it is customized to work without PMU measurements
@param nodes_num: number of nodes of the grid
@p... | 9e662255875970fc8df38c29e728637e53a30db5 | 20,445 |
def _get_specs(layout, surfs, array_name, cbar_range, nvals=256):
"""Get array specifications.
Parameters
----------
layout : ndarray, shape = (n_rows, n_cols)
Array of surface keys in `surfs`. Specifies how window is arranged.
surfs : dict[str, BSPolyData]
Dictionary of surfaces.
... | 310208c5bd8db46d37635fa8e2fcd8422a753a1b | 20,446 |
import subprocess
def get_pool_data(index, val, field):
"""
Return val for volume based on index.
Parameters
----------
index: str
base field name.
val: str
base field value.
field: str
requested field value.
Returns
-------
str: the requested valu... | 3f4934acfaae40e64bafc69048671d7f1c1c832f | 20,447 |
def upper_camel_to_lower_camel(upper_camel: str) -> str:
"""convert upper camel case to lower camel case
Example:
CamelCase -> camelCase
:param upper_camel:
:return:
"""
return upper_camel[0].lower() + upper_camel[1:] | e731bbee45f5fc3d8e3e218837ccd36c00eff734 | 20,448 |
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False):
"""
Get details of a certificate database
"""
return isamAppliance.invoke_get("Retrieving all current certificate database names",
"/isam/ssl_certificates/{0}/details".format(cert_dbase_id)) | 34ade7c42fcc1b1409b315f8748105ee99157986 | 20,449 |
def model_check(func):
"""Checks if the model is referenced as a valid model. If the model is
valid, the API will be ready to find the correct endpoint for the given
model.
:param func: The function to decorate
:type func: function
"""
def wrapper(*args, **kwargs):
model = None
... | 809d7659a721ad6dedf4a651dd1fdab1b1dbf51e | 20,450 |
def content_loss_func(sess, model):
"""Content loss function defined in the paper."""
def _content_loss(p, x):
# N is the number of filters at layer 1
N = p.shape[3]
# M is the height * width of the feature map at layer 1
M = p.shape[1] * p.shape[2]
return (1 / (4 * N * ... | 229866eaaf6021e7a078460dc29a6f0bfaa853bd | 20,451 |
import joblib
def Extract_from_DF_kmeans(dfdir,num,mode=True):
"""
PlaneDFを読み込んで、client_IP毎に該当index番号の羅列をそれぞれのtxtに書き出す
modeがFalseのときはシーケンスが既にあっても上書き作成
"""
flag = exists("Database/KMeans/km_full_"+dfdir+"_database_name")#namelistが存在するかどうか
if(flag and mode):return
plane_df =... | cb086c07024716022343c7e8eb5755f2de3695db | 20,452 |
from typing import Optional
def get_workspace(workspace_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetWorkspaceResult:
"""
Resource schema for AWS::IoTTwinMaker::Workspace
:param str workspace_id: The ID of the workspace.
"""
__args__ = d... | 5c0970884be38923ae156511faf619fda725d004 | 20,453 |
import socket
def find_open_port():
"""
Use socket's built in ability to find an open port.
"""
sock = socket.socket()
sock.bind(('', 0))
host, port = sock.getsockname()
return port | 516540fd23259d0fe247e02c4058c5ed7f3ee3a8 | 20,454 |
import itertools
def split_list_round_robin(data: tp.Iterable, chunks_num: int) -> tp.List[list]:
"""Divide iterable into `chunks_num` lists"""
result = [[] for _ in range(chunks_num)]
chunk_indexes = itertools.cycle(i for i in range(chunks_num))
for item in data:
i = next(chunk_indexes)
... | a87322b2c6a3601cda6c949354e55c38e215289a | 20,455 |
def calc_Q_loss_FH_d_t(Q_T_H_FH_d_t, r_up):
"""温水床暖房の放熱損失
Args:
Q_T_H_FH_d_t(ndarray): 温水暖房の処理暖房負荷 [MJ/h]
r_up(ndarray): 当該住戸の温水床暖房の上面放熱率 [-]
Returns:
ndarray: 温水床暖房の放熱損失
"""
return hwfloor.get_Q_loss_rad(Q_T_H_rad=Q_T_H_FH_d_t, r_up=r_up) | 04ad561fa0090de2eb64d5514a28729da92af63c | 20,456 |
import asyncio
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
_LOGGER.debug("__init__ async_unload_entry")
unload_ok = all(
await asyncio.gather(
*(
hass.config_entries.async_forward_entry_unload(entry, compo... | dac09bd63986488e9d6164e775ddfc5a953576da | 20,457 |
import random
def t06_ManyGetPuts(C, pks, crypto, server):
"""Many clients upload many files and their contents are checked."""
clients = [C("c" + str(n)) for n in range(10)]
kvs = [{} for _ in range(10)]
for _ in range(200):
i = random.randint(0, 9)
uuid1 = "%08x" % random.randint(... | 384aa2b03169da613b25d2da60cdd1ec007aeed5 | 20,458 |
def multi_lightness_function_plot(functions=None, **kwargs):
"""
Plots given *Lightness* functions.
Parameters
----------
functions : array_like, optional
*Lightness* functions to plot.
\*\*kwargs : \*\*
Keywords arguments.
Returns
-------
bool
Definition su... | 18a4706d919c5b8822ff76a40dcd657028a6179b | 20,459 |
def delete_notification(request):
"""
Creates a Notification model based on uer input.
"""
print request.POST
# Notification's PK
Notification.objects.get(pk=int(request.POST["pk"])).delete()
return JsonResponse({}) | c4750bfbaa8184e64293517689671dbf717e6cd4 | 20,460 |
from dateutil import tz
def parse_query_value(query_str):
""" Return value for the query string """
try:
query_str = str(query_str).strip('"\' ')
if query_str == 'now':
d = Delorean(timezone=tz)
elif query_str.startswith('y'):
d = Delorean(Delorean(timezone=tz).... | ac9c6845871094d043eee7004214fdcecb20daec | 20,461 |
def build_model():
"""
Build the model
:return: the model
"""
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]),
layers.Dense(64, activation='relu'),
layers.Dense(1)
])
optimizer = tf.keras.optimizers.RMSprop(0.00... | b5e4b0a64e7d39a0c7b72c0380ef98d8eaf9cc01 | 20,462 |
def detect(stream):
"""Returns True if given stream is a readable excel file."""
try:
opendocument.load(BytesIO(stream))
return True
except:
pass | a9ef5361d9f6f5ae40767f40f12b89c3d53177a4 | 20,463 |
def new_default_channel():
"""Create new gRPC channel from settings."""
channel_url = urlparse(format_url(settings.SERVICE_BIND))
return Channel(host=channel_url.hostname, port=channel_url.port) | 4771306570213fa03cc5df08a0e8c9b216ecfd44 | 20,464 |
def iou(bbox1, bbox2):
"""
Calculates the intersection-over-union of two bounding boxes.
Args:
bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
Returns:
int: intersection-over-onion o... | 7609bcc6eb39757240a22c28fc7c15f4024cd789 | 20,465 |
def get_version():
"""
Obtain the version of the ITU-R P.1511 recommendation currently being used.
Returns
-------
version: int
Version currently being used.
"""
return __model.__version__ | 4d36eacabebe74bfb18879ba64f190ceb1bbc22a | 20,466 |
import copy
def sample_filepaths(filepaths_in, filepaths_out, intensity):
"""
`filepaths_in` is a list of filepaths for in-set examples.
`filepaths_out` is a list of lists, where `filepaths_out[i]` is a list of
filepaths corresponding to the ith out-of-set class.
`intensity` is the number of i... | b20c1e1a019eaebc0eb7ea46b33c286b72da7af7 | 20,467 |
def makekey(s):
"""
enerates a bitcoin private key from a secret s
"""
return CBitcoinSecret.from_secret_bytes(sha256(s).digest()) | 51658c6426a78ae2e20752542bc579f5bb7ebc01 | 20,468 |
def shape_broadcast(shape1: tuple, shape2: tuple) -> tuple:
"""
Broadcast two shapes to create a new union shape.
Args:
shape1 (tuple) : first shape
shape2 (tuple) : second shape
Returns:
tuple : broadcasted shape
Raises:
IndexingError : if cannot broadcast
"""... | 4737332b371e0f16df3860d5c53e46718f68f30e | 20,469 |
import xxhash
def hash_array(kmer):
"""Return a hash of a numpy array."""
return xxhash.xxh32_intdigest(kmer.tobytes()) | 9761316333fdd9f28e74c4f1975adfca1909f54a | 20,470 |
def GenerateDiskTemplate(
lu, template_name, instance_uuid, primary_node_uuid, secondary_node_uuids,
disk_info, file_storage_dir, file_driver, base_index,
feedback_fn, full_disk_params):
"""Generate the entire disk layout for a given template type.
"""
vgname = lu.cfg.GetVGName()
disk_count = len(disk_in... | 87995b08d3579fc22a8db7c8408a9c29e47a8271 | 20,471 |
def check_pc_overlap(pc1, pc2, min_point_num):
"""
Check if the bounding boxes of the 2 given point clouds overlap
"""
b1 = get_pc_bbox(pc1)
b2 = get_pc_bbox(pc2)
b1_c = Polygon(b1)
b2_c = Polygon(b2)
inter_area = b1_c.intersection(b2_c).area
union_area = b1_c.area + b2_c.area - int... | 8caa07a42850d9ca2a4d298e9be91a44ac15f6a5 | 20,472 |
def apply_hypercube(cube: DataCube, context: dict) -> DataCube:
"""Reduce the time dimension for each tile and compute min, mean, max and sum for each pixel
over time.
Each raster tile in the udf data object will be reduced by time. Minimum, maximum, mean and sum are
computed for each pixel over time.
... | c2c3b7b90a48a37f5e172111ef13e8529a3a80c5 | 20,473 |
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
if ... | 3ba19b6e57c8e51a86e590561331057a44885d10 | 20,474 |
def all_stat(x, stat_func=np.mean, upper_only=False, stat_offset=3):
"""
Generate a matrix that contains the value returned by stat_func for
all possible sub-windows of x[stat_offset:].
stat_func is any function that takes a sequence and returns a scalar.
if upper_only is False, values are added t... | 16ef240b33a477948ae99862bb21540a230a8a2f | 20,475 |
def PyCallable_Check(space, w_obj):
"""Determine if the object o is callable. Return 1 if the object is callable
and 0 otherwise. This function always succeeds."""
return int(space.is_true(space.callable(w_obj))) | e5b8ee9bbbdb0fe53d6fc7241d19f93f7ee8259a | 20,476 |
from typing import Callable
def _multiclass_metric_evaluator(metric_func: Callable[..., float], n_classes: int, y_test: np.ndarray,
y_pred: np.ndarray, **kwargs) -> float:
"""Calculate the average metric for multiclass classifiers."""
metric = 0
for label in range(n_class... | a8a61c7a2e3629ff69a6a2aefdb4565e903b82de | 20,477 |
import glob
import os
import time
from datetime import datetime
from io import StringIO
def insert_phots_into_database(framedir,
frameglob='rsub-*-xtrns.fits',
photdir=None,
photglob='rsub-*-%s.iphot',
... | 9d80f1016c4ed8c0fa70ed818c7ed44f8c09a920 | 20,478 |
def idxs_of_duplicates(lst):
""" Returns the indices of duplicate values.
"""
idxs_of = dict({})
dup_idxs = []
for idx, value in enumerate(lst):
idxs_of.setdefault(value, []).append(idx)
for idxs in idxs_of.values():
if len(idxs) > 1:
dup_idxs.extend(idxs)
return ... | adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04 | 20,479 |
async def store_rekey(
handle: StoreHandle,
wrap_method: str = None,
pass_key: str = None,
) -> StoreHandle:
"""Replace the wrap key on a Store."""
return await do_call_async(
"askar_store_rekey",
handle,
encode_str(wrap_method and wrap_method.lower()),
encode_str(pas... | e7abb35147bd7b5be5aa37b6583571e5be8f144b | 20,480 |
import requests
def prepare_bitbucket_data(data, profile_data, team_name):
"""
Prepare bitbucket data by extracting information needed
if the data contains next page for this team/organisation continue to fetch the next
page until the last page
"""
next_page = False
link = None
profil... | a2fe54a4fd02e80b4bf4d41ff932e27b555afc5c | 20,481 |
def add(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.add <numpy.add>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in add")
# C... | 7c35ea06f5bff91da283e3521185a6b9f1b55b32 | 20,482 |
def aslist(l):
"""Convenience function to wrap single items and lists, and return lists unchanged."""
if isinstance(l, list):
return l
else:
return [l] | 99ccef940229d806d27cb8e429da9c85c44fed07 | 20,483 |
import sys
import locale
import os
def form_03(request_data):
"""
Статистическая форма 066/у Приложение № 5 к приказу Минздрава России от 30 декабря 2002 г. № 413
"""
num_dir = request_data["dir_pk"]
direction_obj = Napravleniya.objects.get(pk=num_dir)
hosp_nums_obj = hosp_get_hosp_direction(n... | 29d3dba011969ce95ab3fcc99081ac2e1bee07d4 | 20,484 |
def getKeyList(rootFile,pathSplit):
"""
Get the list of keys of the directory (rootFile,pathSplit),
if (rootFile,pathSplit) is not a directory then get the key in a list
"""
if isDirectory(rootFile,pathSplit):
changeDirectory(rootFile,pathSplit)
return ROOT.gDirectory.GetListOfKeys()... | 69d51a496ec77e00753518fee7ae8a0e5b9e7c9a | 20,485 |
import argparse
def get_args():
"""Parse command line arguments and return namespace object"""
parser = argparse.ArgumentParser(description='Transcode some files')
parser.add_argument('-c', action="store", dest="config", required=True)
parser.add_argument('-l', action="store", dest="limit", type=int, ... | 8d811d1ff9437eef6fe5031618f9561248e40940 | 20,486 |
from typing import Any
def query_from_json(query_json: Any,
client: cl.Client = None):
"""
The function converts a dictionary or json string of Query to a Query object.
:param query_json: A dictionary or json string that contains the keys of a Query.
:type query_json:... | 58d1b1f3efedf0b74a0136d1edd1da13bf16bf8c | 20,487 |
import os
def _write(info, directory, format, name_format):
"""
Writes the string info
Args:
directory (str): Path to the directory where to write
format (str): Output format
name_format (str): The file name
"""
#pylint: disable=redefined-builtin
file_name = name_forma... | c8f595769607151aa771b4d8d841b4beee77bc9e | 20,488 |
def fetch_validation_annotations():
""" Returns the validation annotations
Returns:
complete_annotations: array of annotation data - [n_annotations, 4]
row format is [T, X, Y, Z]
"""
ann_gen = _annotation_generator()
data = []
for annotation in ann_gen:
if annotation[0] in... | 1b9a8b86bbc005c79b152e1f59e653b7711e674f | 20,489 |
def enough_data(train_data, test_data, verbose=False):
"""Check if train and test sets have any elements."""
if train_data.empty:
if verbose:
print('Empty training data\n')
return False
if test_data.empty:
if verbose:
print('Empty testing data\n')
retu... | f11014d83379a5df84a67ee3b8f1e85b23c058f7 | 20,490 |
import argparse
import sys
def parse_args(args):
"""
Parse the arguments to this application, then return the constructed namespace argument.
:param args: list of arguments to parse
:return: namespace argument
"""
parser = argparse.ArgumentParser(
description="Connects data from F prim... | 36d450bca31efd8709a6c108fa719d15c1d1e724 | 20,491 |
def calculate_tidal_offset(TIDE, GM, R, refell):
"""
Calculates the spherical harmonic offset for a tide system to change
from a tide free state where there is no permanent direct and
indirect tidal potentials
Arguments
---------
TIDE: output tidal system
R: average radius used ... | 278b27b2a1378cf0ccb44055a37baf9def7d6c6a | 20,492 |
def get_questions(set_id, default_txt=None):
"""Method to get set of questions list."""
try:
cache_key = 'question_list_%s' % (set_id)
cache_list = cache.get(cache_key)
if cache_list:
v_list = cache_list
print('FROM Cache %s' % (cache_key))
else:
... | 0153ab71caa705f7a4f2a07ce5ef210b02618dd4 | 20,493 |
import pathlib
import tempfile
import logging
import glob
import os
def _export_photo_uuid_applescript(
uuid,
dest,
filestem=None,
original=True,
edited=False,
live_photo=False,
timeout=120,
burst=False,
):
""" Export photo to dest path using applescript to control Photos
I... | 1602969314a3530b8a9312a3e009f2f0c21268a9 | 20,494 |
def get_mms_operation(workspace, operation_id):
"""
Retrieve the operation payload from MMS.
:return: The json encoded content of the reponse.
:rtype: dict
"""
response = make_mms_request(workspace, 'GET', '/operations/' + operation_id, None)
return response.json() | c88aca93803ab5075a217a10b7782ae791f168bc | 20,495 |
def _check_data_nan(data):
"""Ensure data compatibility for the series received by the smoother.
(Without checking for inf and nans).
Returns
-------
data : array
Checked input.
"""
data = np.asarray(data)
if np.prod(data.shape) == np.max(data.shape):
data = data.ravel... | 1cde49f2836405deb0c1328d5ce53c69ffbcb721 | 20,496 |
def function(row, args):
"""Execute a named function
function(arg, arg...)
@param row: the HXL data row
@param args: the arguments parsed (the first one is the function name)
@returns: the result of executing the function on the arguments
"""
f = FUNCTIONS.get(args[0])
if f:
retu... | 3b6e2e20c09c6cefebb4998d40376ff1b1aa63f2 | 20,497 |
import os
def currencyrates():
"""
print a sh-friendly set of variables representing todays currency rates for $EXCHANGERATES which is a semicolon-
separated list of currencyexchange names from riksbanken.se using daily avg aggregation
:return: none
"""
#print(ratesgroup())
rates = os.env... | 64cefe54afe6fdb47496923a3bab9bc33b93cd3a | 20,498 |
def extract_rfc2822_addresses(text):
"""Returns a list of valid RFC2822 addresses
that can be found in ``source``, ignoring
malformed ones and non-ASCII ones.
"""
if not text: return []
candidates = address_pattern.findall(tools.ustr(text).encode('utf-8'))
return filter(try_coerce_asc... | b256bd585a30900e09a63f0cc29889044da8e0e0 | 20,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.