content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def replace_values(dataset, oldvalue, newvalue):
"""
Replace all instances of a value.
"""
for row in dataset:
yield {
field: (newvalue if value is oldvalue else value)
for field, value in row.items()
} | 61,200 |
def raster_to_xarray(fpath, chunk_scale=2):
"""Read raster image into an xarray.DataArray.
Using the `chunks` keyword in the open_rasterio method
activates the return of an out-of-memory virtual array instead
of the in-memory xarray.DataArray
fpath: pathlib.Path, str
chunk_scale: int
M... | 61,201 |
def main():
"""Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', ... | 61,202 |
def count_lines(file):
"""Given a file, returns the number of lines it contains.
The current file position should be preserved as long as the file
supports tell() and seek()."""
old_position = file.tell()
file.seek(0)
count = 0
while file.readline() != '':
count += 1
fil... | 61,203 |
def svs_small():
"""download the smallest aperio test image svs"""
small_image = "CMU-1-Small-Region.svs"
small_image_md5 = "1ad6e35c9d17e4d85fb7e3143b328efe"
data_dir = pathlib.Path(__file__).parent / "data"
data_dir.mkdir(parents=True, exist_ok=True)
img_fn = data_dir / small_image
if no... | 61,204 |
def selection_sort(data):
"""Insetion sort: O(n^2)"""
if len(data) == 1:
return
for i in range(len(data)):
# Find minimum unsorted value.
min_val = data[i]
min_idx = i
for j in range(i, len(data)):
if data[j] < min_val:
min_val = data[j]
... | 61,205 |
def loads(data):
"""Loads the json data"""
try:
data = loader(data)
except Exception:
data = loader(data.decode('utf-8'))
return data | 61,206 |
def getImageExplanation(response):
"""gets photo explanation
Args:
response (Dict): Custom response from NASA APOD API
Returns:
String: image explanation
"""
explanation = response['response_data_raw'][EXPLANATION_PARAMETER]
return explanation | 61,207 |
def latency(session, policy_name, policy_display_name, interval, service, return_type=None, **kwargs):
"""
Retrieves details of storage policy latency over time
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type policy_name: str
:p... | 61,208 |
def np_soften_probabilities(probs, epsilon=1e-8):
"""Returns heavily weighted average of categorical distribution and uniform.
Args:
probs: Categorical probabilities of shape [num_samples, num_classes].
epsilon: Small positive value for weighted average.
Returns:
epsilon * uniform + (1-epsilon) * pro... | 61,209 |
def set_retriever_res(resource_up=True):
"""Create or tear down retriever data and scripts
If resource_up, set up retriever else tear down.
Data directory names use "-",
Data file names use "_"
Script file names use "_"
"""
if not os.path.exists(RETRIEVER_SCRIPT_DIR):
os.makedirs(RE... | 61,210 |
def __get_commit():
"""
:return: git commit ID, with trailing '*' if modified
"""
p = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=__sct_dir__)
output, _ = p.communicate()
status = p.returncode
if status == 0:
... | 61,211 |
def cite():
"""Returns BibTeX citation for the dataset."""
return """@misc{stackoverflow2019,
title={TensorFlow Federated Stack Overflow dataset},
author={The TensorFlow Federated Authors.},
year={2019},
}""" | 61,212 |
def calc_aqi(value, index):
"""
Calculates the corresponding air quality index based off the available conversion data using
the sensors current Particulate Matter 2.5 value.
Returns an AQI between 0 and 999 or None if the sensor reading is invalid.
See AQI_BREAKPOINTS in const.py.
"""
if... | 61,213 |
def update_block_relation(relation_df, parent_folder, block, new_folder, sep="/"):
"""Replace the old folder names by the new folder only to the paths where the block appears"""
relation_df.loc[relation_df["Path"].str.endswith(block), "Path"] = relation_df.loc[
relation_df["Path"].str.endswith(block), ... | 61,214 |
def bgd_sky_rate(**kwargs):
"""
Loads the zodiacal background and normalizes it at 500 nm to a particular
flux level (low_zodi = 77, med_zodi = 300, high_zodi = 6000), which are taken from
a paper (to be dropped here later).
Optional Inputs (defaults):
band = Bandpass (180-220)*ur.nm
diame... | 61,215 |
def se3_to_transform(transform_nparray):
""" convert 4x4 SE(3) to geometry_msgs/Transform
Args:
transform_nparray (np.array): 4x4 SE(3)
Returns:
transform (geometry_msgs/Transform): ROS transform of given SE(3)
"""
pos = transform_nparray[:3, 3]
quat = t.quaternion_from_matrix(... | 61,216 |
def trainer(
model, criterion, optimizer, trainloader, validloader, epochs=5, verbose=True
):
"""Simple training wrapper for PyTorch network."""
train_loss, valid_loss, valid_accuracy, train_accuracy = [], [], [], []
for epoch in range(epochs):
train_batch_loss = 0
train_batch_acc = 0
... | 61,217 |
def AddSecurityProfileForCreateFlags(parser, hidden=False):
"""Adds flags related to Security Profile to the parser for cluster creation.
Args:
parser: A given parser.
hidden: Whether or not to hide the help text.
"""
group = parser.add_group(help='Flags for Security Profile:')
group.add_argument(
... | 61,218 |
def create_random_code(chars=AVAIABLE_CHARS):
"""
Creates a random string with the predetermined size
"""
return "".join(
[choice(chars) for _ in range(SIZE)]
) | 61,219 |
def __improve_cluster_tasks_info(cluster_name):
"""Get more infomation for a list of tasks of a cluster."""
tasks = ecs_facade.get_all_tasks_cluster(cluster_name)
return __improve_tasks_info(cluster_name, tasks) | 61,220 |
def rm_outlier():
"""a function to remove outliers using 1.5*interquartile range"""
dataframe = str(input("Dateframe name:"))
Q1 = dataframe.quantile(q=.25)
Q3 = dataframe.quantile(q=.75)
IQR = dataframe.apply(stats.iqr)
outlier_remover = data[~((data < (Q1-1.5*IQR)) | (data > (Q3+... | 61,221 |
def multi_fit_coef(t_, h_, bs_, lew_, tes_):
"""
Calculate scattering correction for height time series.
The correction is given as a linear combination (multivariate fit) of
waveform parameters. The correction time series is obtain in two steps:
1) Fit the coefficients to the differenced/detr... | 61,222 |
def locate(E,K,L1,L2,MM,OMEGA,model):
"""
Args:
E: input orbit energy
K: input orbit kappa (normalized angular momentum)
L1: radial frequency integer
L2: azimuthal frequency integer
MM: pattern frequency integer
OMEGA: pattern frequency
model: input spherical model, see cl... | 61,223 |
def instantiate_feature(feature_name: str):
"""
@param feature_name: The feature to instantiate
"""
log.info('Loading feature {} ...'.format(feature_name))
if feature_name == 'lm':
feature = LanguageModel()
elif feature_name == 'deep':
feature = DeepExtractor()
elif feature... | 61,224 |
def load(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/load.html',
context_instance = RequestContext(request,
{
'title':'System LA (Average Load)',
'message':'On this page you can see the a... | 61,225 |
def look_at(eye, center, world_up):
"""Computes camera viewing matrices.
Functionality mimes gluLookAt (third_party/GL/glu/include/GLU/glu.h).
Args:
eye: 2-D float32 Tensor (or convertible value) with shape [batch_size, 3]
containing the XYZ world space position of the camera.
center: 2-D ... | 61,226 |
def create_file(n,m,filename='DataBlock'):
"""Create a scratch file of a given size.
:param n: size of block
:param m: number of blocks
:param filename: desired filename
:returns: time to allocate block of size n, time to write a file of size m*n
:rtype: tuple
"""
t1=time()
A=np.on... | 61,227 |
def join_apply(df, func, new_column_name):
"""
Join the result of applying a function across dataframe rows.
This method does not mutate the original DataFrame.
This is a convenience function that allows us to apply arbitrary functions
that take any combination of information from any of the colum... | 61,228 |
def solve(task: str) -> int:
"""Find the biggest connected component in graph."""
connections = process_data(task)
nodes = process_nodes(connections)
return len(nodes["0"]) | 61,229 |
def is_main_thread() -> bool:
"""
Check if we are in the main thread.
"""
return threading.main_thread() == threading.current_thread() | 61,230 |
def get_z_icp(x_prev, transf):
"""
Apply transformation matrix from icp to previous pose to get measurement
"""
pose_new = x_prev[0:3] + transf[0:3, 3]
pose_head = np.array([np.cos(x_prev[3]), np.sin(x_prev[3]), 0])[np.newaxis, :]
transf_se3 = SE3(rotation=transf[0:3, 0:3], translation=np.zeros... | 61,231 |
def _validate_target_url(url):
"""Only accept URLs that are basic. No query, fragment or embedded auth allowed"""
if not isinstance(url, str) and not isinstance(url, unicode):
return False
p = urlparse.urlparse(url)
if p.scheme not in ('http', 'https'):
return False
if p.query or p.f... | 61,232 |
def open(name=None, mode='rb', fileobj=None):
"""
Open an RPM archive for reading. Return
an appropriate RPMFile class.
"""
return RPMFile(name, mode, fileobj) | 61,233 |
def MoveInDirection(square, direction):
""" Returns the given square moved in the given direction. """
(x, y) = square
if direction == UP:
return (x, y-1)
elif direction == DOWN:
return (x, y+1)
elif direction == LEFT:
return (x-1, y)
elif direction == RIGHT:
return (x+1, y) | 61,234 |
def test_plot_over_line():
"""this requires matplotlib"""
pytest.importorskip('matplotlib')
mesh = examples.load_uniform()
# Make two points to construct the line between
a = [mesh.bounds[0], mesh.bounds[2], mesh.bounds[4]]
b = [mesh.bounds[1], mesh.bounds[3], mesh.bounds[5]]
mesh.plot_over_... | 61,235 |
def create_govlytics_dirs():
"""Checks if the base govlytics directories exist and creates them
if they dont."""
if not os.path.isdir(GOVLYTICS_CONF_DIR):
logging.info(
'govlytics conf directory {} doesnt exist, creating ... '.
format(GOVLYTICS_CONF_DIR))
subprocess.c... | 61,236 |
def remove_small_blobs(img, threshold=1, debug=True):
"""
Find blobs/clusters of same label. Only keep blobs with more than threshold elements.
This can be used for postprocessing.
"""
# Also considers diagonal elements for determining if a element belongs to a blob
# mask, number_of_blobs = ndi... | 61,237 |
def fast_text_prediction_to_language_code(res: List[Tuple[str, str]]) -> List[str]:
"""Convert fastText language predictions to language codes"""
labels, _ = res
return [tmp[tmp.rfind("_") + 1 :] for tmp in labels] | 61,238 |
def _format(src, language, class_name, md):
"""Inline math formatter."""
return '<span class="lang-%s %s">%s</span>' % (language, class_name, src) | 61,239 |
def check_foreign_key_required(
*,
fk_spec: types.Schema,
fk_logical_name: str,
model_schema: types.Schema,
schemas: types.Schemas,
) -> bool:
"""
Check whether a foreign key has already been defined.
Assume model_schema has already resolved any $ref and allOf at the object level.
T... | 61,240 |
def load_config(config_file, schema, postprocessing=None, retain=None, drop=None):
"""
Loads a configobj-type configuration file. It is also
possible to specify an application-specific postprocessing function which
has three arguments: the configuration object and the warnings and errors
lists. Thes... | 61,241 |
def hideSiblings(self):
"""Hide all the siblings of a node path"""
for sib in self.getParent().getChildren():
if sib.node() != self.node():
sib.hide() | 61,242 |
def licence():
"""Licence details.
"""
box=tk.Tk()
m = tk.Message(box, text="To legally prevent adjustment of the binary in this software, it is licenced under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) licence.\n\nA summary can be found at:\nhttps:/... | 61,243 |
def fizz_buzz(n):
"""Returns fizz when divisible by 3
Returns buzz when divisible by 5
and fizzbuzz if divisible by both 3 and 5"""
if n % 3 == 0 and n % 5 == 0:
return 'fizzbuzz'
elif n % 3 == 0:
return 'fizz'
elif n % 5 == 0:
return 'buzz' | 61,244 |
def partition_spline_curve(alpha):
"""Applies a curve to alpha >= 0 to compress its range before interpolation.
This is a weird hand-crafted function designed to take in alpha values and
curve them to occupy a short finite range that works well when using spline
interpolation to model the partition function Z(... | 61,245 |
def get_sector(fn):
"""Figure out the label to associate with this file, sigh."""
# NB nc.source_scene is not the region of view
tokens = fn.split("-")
s = tokens[2].replace("CMIP", "")
return SECTORS.get(s, s) | 61,246 |
def redirect_with_error(msg: str, url: str = '/') -> Response:
""""Redirect to specific URL, flashing an error message."""
log_web_event('Error redirect to %s with flash message: %s', url, msg)
flash(msg)
return redirect(url) | 61,247 |
def get_engine_conf_file(sensor):
""" return the corresponding configuration file for passed in sensor (engine and version)
also returns the variables (stripped out from config)
"""
# user's browser should be making request to dynamically update 'coverage' submission page
try:
conf_file... | 61,248 |
def setup(bot):
"""
DecoraterBot's various commands Plugin.
"""
new_cog = Commands(bot)
bot.add_cog(new_cog) | 61,249 |
def test_monitor_skip_module(testdir):
"""Make sure that pytest-monitor correctly understand the monitor_skip_test marker."""
# create a temporary pytest test module
testdir.makepyfile("""
import pytest
import time
pytestmark = pytest.mark.monitor_skip_test
def test_ok_not_monitored():
time.sleep(0.1)... | 61,250 |
def _fetch_surf_fsaverage5_sphere(data_dir=None):
"""Helper function to ship fsaverage5 spherical meshes.
These meshes can be used for visualization purposes, but also to run
cortical surface-based searchlight decoding.
The source of the data is downloaded from OSF.
"""
fsaverage_dir = _get_d... | 61,251 |
def test_lon_degree():
"""
<wpt lon="-76.66669595" lat="24.36669586" >
{'uuid': UUID('89f2be82-8907-4a34-afe8-5155e8e61920'), 'UID_unit_number': 12988, 'UID_sequence_number': 206, 'waypt_stream_version': 2, 'waypt_name_length': 20, 'waypt_name': 'WARDRCK BR', 'UID_unit_number_2': 12988, 'longitude': -76.66... | 61,252 |
def get_candidates(simi):
"""
Get best translation pairs candidates.
"""
knn = '10'
assert knn.isdigit()
knn = int(knn)
average_dist1 = get_nn_avg_dist(simi, knn)
average_dist2 = get_nn_avg_dist(simi.T, knn)
score = 2 * simi
score = score - average_dist1 - average_dist2
retur... | 61,253 |
def memoize(func):
"""Memoize given function."""
cache = {}
def _wrapper(*args, **kwargs):
# serialize argument list to a string key
key = repr(args + KWARG_MARK + tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache... | 61,254 |
def validation(plags, psr, src_offsets, susp_offsets, src_bow, susp_bow, src_gap, src_gap_least, susp_gap, susp_gap_least, src_size, susp_size, th3):
"""
DESCRIPTION: Compute the similarity of the resulting plagiarism cases from extension. In case of being below certain threshold extension is applied again with... | 61,255 |
def default_create_container_arguments(local=True):
"""Get set of arguments which would create first known distribution."""
distro_config = list(available_distributions())[0]
arguments = ("distro", "release")
config = {k: v for k, v in distro_config.items() if k in arguments}
# We must force local ... | 61,256 |
def accumulateMethods(obj, dict, prefix='', curClass=None):
"""
accumulateMethods(instance, dict, prefix)
I recurse through the bases of instance.__class__, and add methods
beginning with 'prefix' to 'dict', in the form of
{'methodname':*instance*method_object}.
"""
if not curClass:
... | 61,257 |
def logout():
"""
Logs a user out of their profile.
Clears the user id from the current session and redirects to the home page.
Returns
Login Page: Redirects to login page.
"""
session.clear()
flash('See you again soon!')
return redirect(url_for('.login')) | 61,258 |
def routine_txt(id_to_send,msg_to_send,Gr):
"""does all the routine job with txt file"""
filee=days_file = open('examp.txt','r')
lines=filee.readlines()
i=1 # начинаем с 1, так как на 0 строке ссылка на группу
prom=lines[0]
Gr.append(prom[13:-1]) # имя группы, взятое из ссылки
while i<len(lines):
i... | 61,259 |
def _fill_sizePerCharacterEncodings_popup(driver, ss_path, parent_id):
"""
fills the size per character encodings popup with all required, recommended and optional
information and returns to the parent window
"""
driver.switch_to.window("id_characterencodinginfotype_model_set__dash__0__dash__sizePer... | 61,260 |
def remove_activityintermediator(db):
"""
This removes the old specific ActivityIntermediator model which has been
superseeded by the GenericForeignKey field.
"""
metadata = MetaData(bind=db.bind)
# Remove the columns which reference the AI
collection_table = inspect_table(metadata, "core__... | 61,261 |
def _parse_formatted_date_range(date_range_str):
"""
Parses a string representing a date range (e.g.: "May 1, 2020 - Jan 30, 2021")
Args:
date_range_str (str): A string representing a date range
Returns:
Tuple[datetime.datetime, Optional[datetime.datetime]]: A tuple containing the two ... | 61,262 |
def _gevent_blocking_call(gce_service, project_id, response,
polling_interval: int = DEFAULT_SLEEP_TIME):
"""
polling_interval is seconds
"""
status = response['status']
attempt = 0
max_sleep_time = 5000
while status != 'DONE' and response:
operation_id ... | 61,263 |
def get_document_segmentation_details_url(
document_id: int, project_id: int = KONFUZIO_PROJECT_ID, host: str = KONFUZIO_HOST, action='segmentation'
) -> str:
"""
Generate URL to get the segmentation results of a document.
:param document_id: ID of the document as integer
:param project_id: ID of t... | 61,264 |
def get_file_size(file_path, h=True):
"""获取文件的大小
:param file_path: 文件路径
:param h: 是否human可读
:return: {'value': 数值,'measure': 单位,'str': 字串}
"""
# file_path = unicode(file_path, 'utf8')
org_fsize = os.path.getsize(file_path)
res_info = file_num2size(org_fsize, h=h)
return res_info | 61,265 |
def checkout_shipping_price(
checkout: "Checkout", discounts: "DiscountsListType" = None
) -> "TaxedMoney":
"""Return checkout shipping price.
It takes in account all extensions.
"""
return get_extensions_manager().calculate_checkout_shipping(checkout, discounts) | 61,266 |
def get_metrics(event):
"""Returns all OPRs, DPRs, and CCWM's from event in a dictionary
event: event key (e.g. 2020mdbet)"""
return tba_session.get(BASE_URL + '/event/%s/oprs' %event).json() | 61,267 |
def document_process_change_status(request, document_request_id):
"""Change document status from process to get.
Args:
request: URL request
document_request_id: Document ID
Returns:
Update document status in firebase from process to get.
"""
document_ref = db.collection("docume... | 61,268 |
def main():
"""
General 'try, catch' as handler
"""
try:
entry_point()
except KeyboardInterrupt:
error_no_traceback("\nProcess killed by the user!")
except BaseException as e:
error_no_traceback(str(e)) | 61,269 |
def nll_loss(
input,
target,
weight=None,
size_average=None,
ignore_index=None,
reduce=None,
reduction='mean',
):
"""Compute the negative likelihood loss.
Parameters
----------
input : dragon.vm.torch.Tensor
The input tensor.
target : dragon.vm.torch.Tensor
... | 61,270 |
def add_newline_to_end_of_each_sentence(x: str) -> str:
"""This was added to get rougeLsum scores matching published rougeL scores for BART and PEGASUS."""
if "<n>" in x:
return x.replace("<n>", "\n") # remove pegasus newline char
else:
return x | 61,271 |
def ransac_spline(x_data, y_data, n_order=3, n_knots=10, thres=0.2, b_periodic=False, b_graph=True, random_seed=None, title='ransac'):
"""
Robust B-Spline regression with scikit-learn
https://gist.github.com/MMesch/35d7833a3daa4a9e8ca9c6953cbe21d4
input :
x_data
y_data : numpy array
... | 61,272 |
def generate_samples_frame(cfg, dataset, params, output_file):
""" Generates a moment image for a single frame. """
log_params(cfg, '--generate-samples', output_file, dataset, params)
subprocess.run([mray_bin(cfg), '--generate-samples', output_file, dataset, params], check=True,
stdout=su... | 61,273 |
def _open_sam(fn, fmt):
"""Open SAM | BAM file as AlignmentFile"""
assert fmt == 'sam' or fmt == 'bam'
mode = read_mode_of_file(fn)
return AlignmentFile(fn, mode, check_sq=False) | 61,274 |
def _excluded_scenario(test_name, scenario):
"""Skip list generator for scenarios to skip in test_name.
Arguments
---------
test_name : str, name of test
scenario : instance of TestScenario, to be used in test
Returns
-------
bool, whether scenario should be skipped in test_name
""... | 61,275 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Visualization crop results')
parser.add_argument('--annotation', dest='annotation',
help='annotation file path',
default='',
type=str)... | 61,276 |
def test_Functor_subtype_register():
"""Test registering a Functor subtype for value wrapping."""
test_value = object()
with pytest.raises(ValueError):
Functor.try_wrap(test_value)
class TestFunctor(Functor):
@classmethod
def wrap(cls, value):
if value is test_valu... | 61,277 |
def import_results():
"""
"""
msoa_data = []
with open(os.path.join(INPUT_FILES, 'nga_availability.csv'), 'r', encoding='utf8', errors='replace') as system_file:
reader = csv.reader(system_file)
next(reader)
#reader = [next(reader) for x in range(N)]
for line in reader:
... | 61,278 |
def main_function(
mymodel: str,
myinput: str,
mypattern: str,
mystate: str,
myx_voxel_size: float,
myy_voxel_size: float,
myz_voxel_size: float,
mywavelength: float,
myscalar: float = 1.,
mythreshold: float = 0.,
verbose: bool = True,
plot: bool = True
):
""" Replica... | 61,279 |
def test_d3_4_28v10_d3_4_28v10i(mode, save_output, output_format):
"""
Additional dateTimeStamp tests, for attributes
"""
assert_bindings(
schema="ibmData/valid/D3_4_28/d3_4_28v10.xsd",
instance="ibmData/valid/D3_4_28/d3_4_28v10.xml",
class_name="Root",
version="1.1",
... | 61,280 |
def play_sequence(sequence,
synth=midi_synth.synthesize,
sample_rate=_DEFAULT_SAMPLE_RATE,
colab_ephemeral=True,
**synth_args):
"""Creates an interactive player for a synthesized note sequence.
This function should only be called from a Jupyte... | 61,281 |
def _filter_class_and_zero_scores(
scores: np.array,
classes: np.array,
filter_class: Union[int, None],
confidence: float = 0.001,
) -> list:
"""Create a list of indices representing the filtered elements.
:param scores: Numpy array containing scores of all detections.
:param classes: Numpy ... | 61,282 |
def get_markets_region_id_history(*, region_id, type_id, if_none_match=None):
"""
:param if_none_match: ETag from a previous request. A 304 will be returned if this matches the current ETag
:param region_id: Return statistics in this region
:param type_id: Return statistics for this type
Return a li... | 61,283 |
def test_get_blocked_scenario2(flask_app):
"""Test update case JSON response"""
creation_data['device_details']['imeis'] = ["37002334561234", "37052332331234"]
creation_data['case_details']['get_blocked'] = False
# insert new case
response = flask_app.post(case_api_url, data=json.dumps(creation_dat... | 61,284 |
def smart_resize(x, size, interpolation='bilinear'):
"""Resize images to a target size without aspect ratio distortion.
Warning: `tf.keras.preprocessing.image.smart_resize` is not recommended for
new code. Prefer `tf.keras.layers.Resizing`, which provides the same
functionality as a preprocessing layer and add... | 61,285 |
def almosteq(a, b, tol=1e-8):
"""Almost-equality that supports several formats.
The tolerance ``tol`` is used for the builtin ``float`` and ``mpmath.mpf``.
For ``mpmath.mpf``, we just delegate to ``mpmath.almosteq``, with the given
``tol``. For ``float``, we use the strategy suggested in:
htt... | 61,286 |
def layer_integrate(upper_contour, lower_contour, grid_obect, integrand = 'none', interp_method='none'):
"""!Integrate between two non-trivial surfaces, 'upper_contour' and 'lower_contour'.
At the moment this only works if all the inputs are defined at the same grid location.
The input array 'integra... | 61,287 |
def login(request, id=None, username=None, password=None, skip_authentication=False):
"""
Helper function to login a specific user, optionally
skipping the authentication.
:param HttpRequest request: The request object.
:param int id: *Optional*. The user_id to log in.
:param str username: *Opt... | 61,288 |
def select(element, selector):
"""Syntactic sugar for element#cssselect that grabs the first match."""
matches = element.cssselect(selector)
return matches[0] | 61,289 |
def main(uargs):
"""Main function for making OTU table.
Parameters
----------
uargs : dict
See ``OTU_table`` subcommand.
"""
# args formatting
try:
uargs['--abs'] = int(float(uargs['--abs']))
except TypeError:
msg = '"{}" must be float-like'
raise Ty... | 61,290 |
def type(session: Session) -> None:
"""Type check files with mypy."""
args = session.posargs or LOCATIONS
session.install(*PIP_PARAMS, "workflow/envs/type.txt")
session.run(
"mypy",
"--ignore-missing-imports",
"--disable-error-code",
"name-defined",
*args
) | 61,291 |
def makeCamera(name, scene):
"""
Retruns a new camera, appropriate for rendering a cube face, linked into
`scene`.
"""
cameraData = bpy.data.cameras.new(name)
cameraData.lens_unit = "FOV"
cameraData.angle = PI_OVER_2
camera = bpy.data.objects.new(name, cameraData)
if BLENDER_LEGACY_V... | 61,292 |
def {{cookiecutter.project_slug}}(ctx):
"""CLI for {{cookiecutter.project_slug}}"""
click.echo("{{cookiecutter.project_slug}}") | 61,293 |
def path_and_line(req):
"""Return the path and line number of the file from which an
InstallRequirement came.
"""
path, line = (re.match(r'-r (.*) \(line (\d+)\)$',
req.comes_from).groups())
return path, int(line) | 61,294 |
def write_chords(source='power', write=False):
"""
setting data augmentation
notes -> chords
"""
# indexed_strategies = list(enumerate(list(strategies.keys())))
assert source in strategies, '{} is not a valid source'.format(source)
bp = os.path.abspath(os.path.join(ROOT_DIR,'data/interi... | 61,295 |
def user_group_command(_):
"""Group command: dds user. Manage user accounts, including your own.""" | 61,296 |
def exception(message=None, module=None, exc_info=None):
"""Logs an error plus the current or given exc info."""
if exc_info is None:
exc_info = sys.exc_info()
try:
logger = get_application().log
except AttributeError:
# no application, write the exception to stderr
retur... | 61,297 |
def taupericenter(t, e, f, n):
"""Compute the time of pericenter passage.
Args:
t (float): current time
e (float): eccentricity
f (float): true anomaly
n (float): Keplerian mean motion
Returns:
float: time of pericenter passage
"""
E0 = ... | 61,298 |
def get_voronoi_neighbors(atoms, cutoff):
"""
atoms: ase.Atoms object
cutoff: limits the neighbor search to |rj-ri| < cutoff,
used only for faster search, it should be large
enough so that the output doesn't depend on cutoff.
returns: a list of VorNei objects
* notes:
... | 61,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.