content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def help_package_prompt(help_list, on_select, on_cancel=None):
"""
Given a list of loaded help indexes, prompt the user to select one of the
packages. on_select is invoked with the name of the selected package,
while on_cancel is invoked if the user cancels the selection.
"""
if not help_list:
... | 8f1cb14fb49660634ea5979c7189a7358c950a58 | 3,634,600 |
def exponential_function(X):
"""
Benchmark exponential function f(x) = exp(-3x)
"""
return np.exp(-3 * X) | b600cc45242ffe5634af007eafae43fe01d6098b | 3,634,601 |
import re
import os
def _get_firebase_db_url():
"""Grabs the databaseURL from the Firebase config snippet. Regex looks
scary, but all it is doing is pulling the 'databaseURL' field from the
Firebase javascript snippet"""
regex = re.compile(r'\bdatabaseURL\b.*?["\']([^"\']+)')
cwd = os.path.dirname... | 8b4f65f0a769d7d80a92ee78876f359cc105697a | 3,634,602 |
def get_user_by_name(name):
"""通过 name/oname 获取 user 对象,用于导入评论者
Comment只接受User对象
Args:
name/oname
Returns:
user<object>: 用户对象
user_type: 用户类型
"""
try: return NaturalPerson.objects.get(name=name).person_id, UTYPE_PER
except: pass
try: return Organization.objects.ge... | 4bf5157cc3d4d6e12eb15f2fec36c58fc6e3e173 | 3,634,603 |
import random
def gen_html(length=10, include_tags=True):
"""Return a random string made up of html characters.
:param int length: Length for random data.
:returns: A random string made up of html characters.
:rtype: str
"""
random.seed()
html_tag = random.choice(HTML_TAGS)
if not i... | ad3c76f98591c3f412de0c4eda410e92afc09e55 | 3,634,604 |
from typing import Dict
import itertools
def format_coco(chip_dfs: Dict, patch_size: int, row_name: str):
"""
Format train and test chip geometries to COCO json format.
COCO train and val set have specific ids.
"""
chip_height, chip_width = patch_size, patch_size
cocojson = {
"info": {... | d48c8308a7bc23f737a969c5e4cf55aafb58e74e | 3,634,605 |
def robust_optimize(ydata, fitfunc, arg_dict, maxiter=10, inmask=None, invvar=None,
lower=None, upper=None, maxdev=None, maxrej=None, groupdim=None,
groupsize=None, groupbadpix=False, grow=0, sticky=True, use_mad=False,
verbose=False,
**kwa... | 649f17cb8b104daec735018edef6d6cb5d3dd7fd | 3,634,606 |
def DAGcon(G, N):
"""A method to construct a Directed Acyclic graph
Parameters
----------
G : The subsumption set.
N : The number of nodes.
Returns
-------
Returns the DAG as a list.
"""
l = list()
caches = list()
l_g = sorted(G, key=lambda x: G[x], reverse = True)
... | d2500216d41b34167116046b7a9b0ca5a738f756 | 3,634,607 |
def authenticate_owner_password(password : 'bytes', encryption_dict : 'dict', id_array : 'list'):
"""
Authenticate the owner password.
Parameters
----------
password : bytes
The password to be authenticated as owner password.
encryption_dict : dict
The dictionary containing ... | ffe543bcddc341d6b1744cd4f3dcb60bc3653ce9 | 3,634,608 |
def next_neighbors(p, ps, k):
"""
Function to find the next neighbors for a non-periodic setup
This function gives for a value p the k points next to it which are found in
in the vector ps
Args:
p: the current point
ps (np.ndarray): the grid with the potential neighbors
k (... | 2c0e430434b036a040b3c4cab0e75bc872ab174c | 3,634,609 |
from datetime import datetime
def parse_date(datestring):
"""
Return a datetime for a date string
"""
try:
dt = datetime.strptime(datestring, TIME_FORMAT_FINE)
except ValueError:
dt = datetime.strptime(datestring, TIME_FORMAT_COARSE)
return dt.replace(tzinfo=timezone.utc) | 3a6aeddd0229daa626de377957b8a5597ac2e9e9 | 3,634,610 |
def eigval2(k,aee,aeiaie,aii,see,sei,sii,tau=1,alpha=0):
""" smaller eigenvalue of recurrently connected network of E,I units,
analytically determined
input:
k: spatial frequency
aee: ampltidue E to E connectivity
aeiaie: product of amplitudes of E to I and I to E connectivity
aii: ampltidue I to I connectivity... | 3fd23845d2c4cb1199bc9a782cf28a18b88c4a2d | 3,634,611 |
def randomize_censored_values(x,
lower_bound=None, lower_threshold=None,
upper_bound=None, upper_threshold=None,
inplace=False, inverse=False,
seed=None, lower_power=1., upper_power=1.):
"""
Randomizes values beyond threshold in x or de-randomizes such formerly
randomized val... | 117e523e7be8c1ed51ba1f7b5d7120685a175b49 | 3,634,612 |
def read_fits(filename, params):
"""
read in the polynomial fit fits file (saved from Extract_Orders.py)
and extract using polynomial fits
:param filename: string, location and file name of the file containing the
polynomial fits (params['poly_fits_file'] by default)
:param pa... | 547f02b9d471bc191f9906c9c7cbf0e5b502c97e | 3,634,613 |
def IntCurve_PConicTool_NbSamples(*args):
"""
:param C:
:type C: IntCurve_PConic &
:rtype: int
:param C:
:type C: IntCurve_PConic &
:param U0:
:type U0: float
:param U1:
:type U1: float
:rtype: int
"""
return _IntCurve.IntCurve_PConicTool_NbSamples(*args) | 9b3d78bdc3c19660b0a99d03ce0bd0618f37f4a4 | 3,634,614 |
def nearest_neighbor(graph, restarts=10, weight='weight'):
"""
Recursive Nearest-Neighbor algorithm to solve the traveling salesman problem.
These are the steps of the algorithm for each restart:
#. Start on a random node as current node;
#. Find the shortest edge connecting the current node with an unvisit... | 806617a99bcbfcde6a9366fad1bbfedf3757511d | 3,634,615 |
import time
def update_metrics(metrics, losses, mode, src_seq, tracking_loss=None, batch_level=True):
"""
Records relevant metrics in the metrics data structure while training.
If batch_level is true, this means the loss for the current batch is
recorded in addition to the running epoch loss.
Par... | 5b33722af1ad8ad2d0397d7c4a15e6b253c32333 | 3,634,616 |
def dmet_low_rdm(active_fock, number_active_electrons):
"""Construct the one-particle RDM from low-level calculation.
Args:
active_fock (numpy.array): Fock matrix from low-level calculation (float64).
number_active_electrons (int): Number of electrons in the entire system.
Returns:
... | da8109616337eb2b95f948ed0f0065cad857bed5 | 3,634,617 |
def reversed_complement(string):
"""Find the reverse complement of a DNA string.
Given: A DNA string Pattern.
Return: Pattern, the reverse complement of Pattern."""
complements = {'A': 'T',
'C': 'G',
'G': 'C',
'T': 'A'
}
return "".join([complements[string[i]] for i in... | b4ecaf6d2c58a0c14d87122529e316b43082cf54 | 3,634,618 |
import os
import pickle
def create_service(scopes):
"""
Creates a Gmail service based on the credentials.json found in the current directory.
"""
creds = None
if os.path.exists("modules/token.pickle"):
with open("modules/token.pickle", "rb") as token:
creds = pickle.load(token... | 274430d6ad54de2a84e615b8b16b3f0b321decbf | 3,634,619 |
def package_positions_images(image, position_arr):
"""
获取 背包 位置图片
:param image:
:param position_arr:
:return:
"""
res = []
for position in position_arr:
x1, x2, y1, y2 = position
if image is None:
res.append(image_util.capture((x1, y1, x2, y2)))
else:... | 46e01e09ef5ce948132811095b3edfd95eae4b0e | 3,634,620 |
def save(operator, context, filepath, apply_modifiers, separator,
default_texture_flag, flip_uv, alt_color,
matrix, scale, f15_rot_space, obj=None, **kwargs):
"""
:param bpy.types.Operator operator:
:param context:
:param str filepath:
:param bool apply_modifiers:
:param str s... | cf85302a23cbb051a39403bee1d72faf1f3bbb87 | 3,634,621 |
import os
import sys
def get_checkpoint_path(train_dir, num_iters_ckpt):
""" Finds the checkpoint path that corresponds to the num_iters_ckpt.
Args:
train_dir: string: path to the directory where the checkpoints files are
saved.
num_iters_ckpt: int: number of training iterations performed... | db122c5fac69d1322d5ef69d8ff99be90ecf9eba | 3,634,622 |
def merge_masks(masks):
"""
Merge masks for each organ into one ndimage, overlapped pixels will
be override by the later class value
contours: [num_class, D, H, W]
return: merged contour of shape [D, H, W]
"""
num_class, D, H, W = masks.shape
merged_masks = np.zeros((D, H, W), dtype... | 833a9a462b3ed661e2dd45d178e3e81122bf86f8 | 3,634,623 |
def print_subheader(object_type):
"""
Print out a subheader for a text file.
"""
return """
#################################################################
# {0}
#################################################################
""".format(object_type) | 1ea7185f024ec7dc45a1ccac9f7e2feb6a2a6bf2 | 3,634,624 |
def get_virtualenv_version(args, python): # type: (EnvironmentConfig, str) -> t.Optional[t.Tuple[int, ...]]
"""Get the virtualenv version for the given python intepreter, if available, otherwise return None."""
try:
cache = get_virtualenv_version.cache
except AttributeError:
cache = get_vir... | 4a7d61567224723e46090c79c416134555419f34 | 3,634,625 |
def require_data(PWState, TheAnalyzer):
"""Defines the transition targets for each involved state.
"""
variable_db.require("path_iterator")
def __door_adr_sequences(PWState):
result = ["{\n"]
length = 0
for path_id, door_id_sequence in enumerate(PWState.door_id_sequence_lis... | 34f4af6d229f6e00d73dbcaa55eb9ec88d54a5d8 | 3,634,626 |
def pad_batch_data(insts,
pad_idx=0,
return_pos=False,
return_input_mask=False,
return_max_len=False,
return_num_token=False):
"""
Pad the instances to the max sequence length in batch, and generate the
correspond... | 9cc5f394d5b6fbb4fbdc384e06b70ce83397d0d5 | 3,634,627 |
from typing import Optional
from typing import List
import torch
def push2d(inp, g, shape: Optional[List[int]], bound: List[Bound],
extrapolate: int = 1):
"""
inp: (B, C, iX, iY) tensor
g: (B, iX, iY, 2) tensor
shape: List{2}[int], optional
bound: List{2}[Bound] tensor
extrapolate: ... | f6fda82c2c2c628e51bc19ccf13a64aba6e7b432 | 3,634,628 |
import time
def condor_tables(sqlContext,
hdir='hdfs:///project/monitoring/archive/condor/raw/metric',
date=None, verbose=False):
"""
Parse HTCondor records
Example of HTCondor recornd on HDFS
{"data":{"AccountingGroup":"analysis.wverbeke","Badput":0.0,"CMSGroups":"[\"/cms\"]","CMSPri... | 8742f240f65755431a5b640e9481f657ce3048d5 | 3,634,629 |
from typing import Callable
from typing import List
from typing import Tuple
def _contiguous_groups(
length: int,
comparator: Callable[[int, int], bool]
) -> List[Tuple[int, int]]:
"""Splits range(length) into approximate equivalence classes.
Args:
length: The length of the range to s... | fc25e286a2b6ec9ab7de15146e8b26922ea56e6b | 3,634,630 |
def datatype_derive(times, series):
"""
returns series converted to datatype derive
store only differeces between two subsequent values
parameters:
series <tuple> of <float>
returns:
<tuple> of <float>
"""
new_series = [0.0, ]
for index in range(1, len(series)):
new_ser... | 4a2689030e1911a8b4ee5777157c61c623e94da0 | 3,634,631 |
def ajax_delete_entry(request):
"""Asynchronously deletes an entry
This method is for RUSERs who wish to delete a single entry from
their TrackingEntries. This method is only available via ajax
and obviously requires that users be logged in.
We then create our json_data map to hold our success sta... | 61e8b34ce8b64f451ca4e934313b2d2b0c43f7f1 | 3,634,632 |
def mni152_to_civet(img, civet_density='41k', method='linear'):
"""
Projects `img` in MNI152 space to CIVET surface
Parameters
----------
img : str or os.PathLike or niimg_like
Image in MNI152 space to be projected
civet_density : {'41k'}, optional
Desired output density of CIVE... | 22620ebbe57d8a5090ee450240713e4fd13808b5 | 3,634,633 |
def get_rotational_part(trans):
"""
Get the :math:`d×d` rotational part of a :math:`(d+1)×(d+1)` transformation matrix.
Parameters
----------
trans : array_like
The given transformation matrix.
Returns
-------
numpy.ndarray
The rotational part, with potential scaling re... | 6a0655afe9bca082d4cffcd8d540247be1900213 | 3,634,634 |
def imitation_terminal_condition(env,
dist_fail_threshold=1.0,
rot_fail_threshold=0.5 * np.pi):
"""A terminal condition for motion imitation task.
Args:
env: An instance of MinitaurGymEnv
dist_fail_threshold: Max distance the simulated chara... | 21804759cc45ef54a46236a50f27ded0186de640 | 3,634,635 |
import subprocess
def iproute2_is_vrf_capable():
"""
Checks if the iproute2 version installed on the system is capable of
handling VRFs by interpreting the output of the 'ip' utility found in PATH.
Returns True if capability can be detected, returns False otherwise.
"""
if is_linux():
... | eabb042893167244991450287655fb6cb6d4e8d0 | 3,634,636 |
def cleanRepl(matchobj):
"""
Clean up a directory name so that it can be written to a
matplotlib title without encountering LaTeX escape sequences
Replace backslashes with forward slashes
replace underscores (subscript) with escaped underscores
"""
if matchobj.group(0) == r'\... | ffe9abb42df66780134e058ad24457a75f873055 | 3,634,637 |
def bitcoinAddress2bin(btcAddress):
"""convert a bitcoin address to binary data capable of being put in a CScript"""
# chop the version and checksum out of the bytes of the address
if ":" in btcAddress:
pfx, addr = btcAddress.split(":")
decoded = cashaddrutil.b32decode(addr)
if not c... | 9e0404169dc7c0d4d07c1c8dff5fab2822e6fc1b | 3,634,638 |
def StartITMAgent(TargetServerIP,TargetServerUsername,TargetServerPasswd,StartCommand=r'/itm/bin/itmcmd agent start ux um'):
"""
Start ITM Agent
return:
exitCode:
0: success
1: connection error
2: command error
commandOutput: output
"""
r... | 5c9cea3b55ea749f4584566efc31effe336ce99e | 3,634,639 |
import argparse
def parse_arguments():
"""
Parse command line argument and construct the DNN
:return: a dictionary comprising the command-line arguments
"""
# define the program description
text = 'Coverage Analyzer for DNNs'
# initiate the parser
parser = argparse.ArgumentParser(des... | 0b9bb7437c6719dda7936f3c9cf19e2d7324877f | 3,634,640 |
def cost_matrix(gdf, dist_3d_matrix, line_bc,resolution,Rivers_option):
"""
Creates the cost matrix in €/km by finding the average weight between
two points and then multiplying by the distance and the line base cost.
:param gdf: Geodataframe being analyzed
:param dist_3d_matrix: 3D distance matrix ... | d9e9f316009ce80df88420f38918618762254cd8 | 3,634,641 |
def home():
"""
The home page that asks for user input.
"""
return render_template('index.html') | b8aa9a362929e2c8ba29c7e8c124b59f1fdb7ac6 | 3,634,642 |
def tanh(x):
"""
Computes hyperbolic tangent of x element-wise.
Parameters
----------
x : tensor
Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128.
Returns
-------
A Tensor. Has the same type as x.
"""
_tanh = ms.ops.Tanh()... | 1e87af329177dfd6208a252d717fc400c8c4f0e6 | 3,634,643 |
def all_directions():
"""
:return: Returns all the available directions.
"""
return dt.groups.keys() | 389b2e4a60cf8ee739a4081ab66de51813c3de4e | 3,634,644 |
def determine_result(image, reference, result):
"""
Determine a test result against a reference and thresholds.
Args:
image (TestImage): The image being compressed.
reference (Record): The reference result to compare against.
result (Record): The test result.
Returns:
R... | 92451294e49c212ec54ed6b84705d611ade45bfe | 3,634,645 |
def str2period(x, tostring=False):
"""
Convert string into pandas.Period
ex) 99991231 -> 9999-12-31
"""
if x is not None:
ret = pd.Period(year=x // 10000, month=x // 100 % 100, day=x % 100, freq='D')
else:
ret = None
if tostring and ret is not None:
ret = str(ret)
... | 7a1996240f0386260dc9aa850c63f136ef53c2fb | 3,634,646 |
def webauthn_begin_assertion():
"""
This url is called when the authentication process begins
"""
username = request.form.get("login_username")
if not util.validate_username(username):
return make_response(jsonify({"fail": "Invalid username."}), 401)
credentials = database.get_credentia... | f1e04dd9c4d3633deadb9179fd09b3c4b9f1da85 | 3,634,647 |
from datetime import datetime
def add_new_repository(user, full_name, githubprofile_service, commit_service):
"""
Register a new repository and all your commits from last month
Raises:
github.UnknownObjectException
GitHubProfile.DoesNotExists
RepositoryNotBelongToUserException
... | 2e7a4aabef4debdcda936c04673c709d3e02983c | 3,634,648 |
def case_copy(request):
"""
复制case
:param request:
:return:
"""
user_id = request.session.get('user_id', '')
if not get_user(user_id):
request.session['login_from'] = '/base/case/'
return HttpResponseRedirect('/login/')
else:
if request.method == 'GET':
... | 9c1d5531f0d37b220f42ef2b4c4340a07419ce6c | 3,634,649 |
def get_node_config(node_dir, key):
"""
This function retrieves a setting from the indigo node configuration.
"""
return exec_node_command(node_dir, "config", "get", key) | dde44c551b7d1185752d738c1dee663cda5fe3e1 | 3,634,650 |
def get_argparser():
"""
Returns an argument parser for this script
"""
parser = ArgumentParser(description='Fit a U-Time model defined in'
' a project folder. Invoke '
'"ut init" to start a new project.')
parser.add_arg... | 669427213e3c24ae45f88e143a51d35f38a78c97 | 3,634,651 |
def _deep_different(left, right, entry):
"""
checks that entry is identical between ZipFile instances left and
right
"""
left = chunk_zip_entry(left, entry)
right = chunk_zip_entry(right, entry)
for ldata, rdata in izip_longest(left, right):
if ldata != rdata:
return Tr... | b4e0a47800e1ff2bb74cec9a292e0272edc63520 | 3,634,652 |
def test_xscov_asymmetric(text_cov_lb5_asym):
"""Check that `XsCov` raises error because matrix non symmetric"""
tape = sandy.formats.endf6.Endf6.from_text(text_cov_lb5_asym)
with pytest.raises(Exception):
return sandy.XsCov.from_endf6(tape) | d66bb7baa540468e565edaa77a02db59b9cb3cf9 | 3,634,653 |
def segment(img, img_bg, img0_sigma=5, img0_min_size=300, img0_min_distance=50, img0_thresh_bg=500, img0_min_size_bg=10_000, img0_dilation=5):
"""Standard DAPI / nuclear based cellular segmentation.
Args:
img (np.array): Image array with nuclear labeling.
img_bg (np.array): Image to be used for... | 645398d74c132c837a6715b163c4a310436ba33f | 3,634,654 |
from typing import Optional
from typing import Callable
def get_parsing_function(input_format: Optional[str], filename: str) -> Callable:
"""Return appropriate parser function based on input format of file.
:param input_format: File format
:param filename: Filename
:raises Exception: Unknown file for... | 350126b15b226ba83bade24e924409d10d929f9c | 3,634,655 |
from typing import Iterable
def process_proto_file(proto_file) -> Iterable[OutputFile]:
"""Generates code for a single .proto file."""
_, package_root = build_node_tree(proto_file)
output_filename = _proto_filename_to_generated_header(proto_file.name)
generator = RawCodeGenerator(output_filename)
... | 3041228160c7e6ea17a7d0d41adc624e85377d69 | 3,634,656 |
def custom_resampler(array_like):
"""calculating heat index using monthly values of temperature."""
return np.sum(np.power(np.divide(array_like, 5.0), 1.514)) | 23f9fed7e430c5856ec23e2cdea4e884f9e4bf85 | 3,634,657 |
def make_nhwc(batch, c=3):
"""Makes a NxHxW(x1) tensor NxHxWxC, written in graph mode.
"""
# Assert 3D or 4D
n_dims = tf.rank(batch)
assert_op = tf.debugging.Assert(
tf.logical_or(tf.equal(n_dims, 3),
tf.equal(n_dims, 4)), [n_dims])
# If necessary, 3D to 4D
wit... | 5c2605de058bd3114c247a213f27201e993f8d2a | 3,634,658 |
from typing import Union
from typing import Tuple
from typing import List
def word_window(sequence: str, target: str, size: int) -> Union[Tuple[List[str], List[str]], None]:
"""
Retrieves word windows of 'size' to the left and 'size' to the right.
If size == 0: Take the entire sequence as window
"""
... | bcc19bf4283fc8132a77e723dd24f9ab578bd2f4 | 3,634,659 |
def get_pheonix_restaurants():
"""
Get All Phoenix restaurant.
Returns:
All Phoenix restaurants as a list of restaurant dictionaries objects.
"""
return get_restaurants("Phoenix", PHOENIX_RESTAURANTS_PATH) | 12c38e534680c7bc3da0ae676de4b382724b8ac1 | 3,634,660 |
def get_p_detect_small_jurisdictions(end_date):
"""
Apply a scaling to the daily reported cases by accounting for a ~75% detection probability pre
15/12/2021 and 0.5 following that. To improve the transition, we assume that detection
probability decreases from 0.75 to 0.5 over 7 days beginning 9/12/202... | b6762477197a45e7c45bf5541b7fb60361a94cc5 | 3,634,661 |
def f(x):
"""
Compute function value.
"""
return np.sin(x) | 4716b72bec5cc9c4ced57ac3559719a995703e9c | 3,634,662 |
def _arnoldi_step(j, V_v, H_s, A, A_inv, precision):
""" Performs an iteration of the Arnoldi process:
- A new Krylov vector new_v = (A @ A_inv) @ V_v[:, j] is computed.
- new_v is orthogonalized against the columns of V_v, yielding
the orthogonalized vector orth_v along with new overlaps.
- orth_v ... | 7f992206fb2c88096b8b937a388909bbeb3ecb8e | 3,634,663 |
def get_papers():
"""Get papers discussing COVID-19 treatments
Returns
-------
DataFrame
dataframe of treatment documents
"""
def count_treatments(df):
# TODO: normalize by text length?
return df["text"].str.count(RE_TOPIC)
return filter_docs_by_count(count_treatmen... | bce1106e4bb435a1feb286bf63ea8f9fb46cf152 | 3,634,664 |
def calculate_speed(ds):
"""Calculate speed on the central (T) grid.
First, interpolate U and V to the central grid, then square, add, and take
root.
Parameters
----------
ds : xarray dataset
A grid-aware dataset as produced by `xorca.lib.preprocess_orca`.
Returns
-------
... | 90cbf24068de77f55d21eea4189bbf17a47614bb | 3,634,665 |
def image_preprocessing(image_path, preprocess_input, target_size):
"""
Read and preprocess an image from disk.
Args:
image_path (str): path to the image.
preprocess_input (funciton): a preprocessing function.
target_size (tuple): image target size.
Returns:
np.ndarray:... | 61717a7a6fd3b732cfe4e0f1259111b2713dc854 | 3,634,666 |
def get_ndjson(obj, jobType):
"""
Given an S3 object that points to a JSON file,
read it into memory and return an ndjson string
representation
"""
json_content = json.loads(obj.get()['Body'].read().decode('utf-8'))
output_records =[]
for record in json_content:
output_record = {}
comp... | b87ccfbf088db7ad248a19fc2b2d4f84974e42f9 | 3,634,667 |
import json
import http
def render_to_json(data, is_json=False):
"""Create a JSON response from a data dictionary and return a
Django response object."""
if not is_json:
js = json.dumps(data, cls=DjangoJSONEncoder)
else:
js = data
mime = mimetype = "application/json;charset=utf-8"
... | 9c0792a647a82ca1539c3ea2cabcfb90d29b4042 | 3,634,668 |
def get_ctd_from_txt(fname, summary, source, sea_name, p_lat, p_lon,
p_time, ca=[]):
"""
Create an ambient.Profile object from a text file of ocean property data
Read the CTD and current data in the given filename (fname) and use that
data to create an ambient.Profile object for use in TAMOC. This ... | 77c04bf3ab0ec166e5b8a296e8fd96c061435f16 | 3,634,669 |
import scipy
def get_ndimage_module(*args):
"""
Returns either the scipy.ndimage or cupyx.scipy.ndimage module, cupy module is returned if any
argument is on the GPU.
"""
return cupyx.scipy.ndimage if any(is_on_gpu(arg) for arg in args) else scipy.ndimage | ef763c0bcfd15c07d288ccb65caf8860781bb03e | 3,634,670 |
def sensitivity_plot_comparison(n_bins_energy, energy, sensitivity):
"""
Main sensitivity plot.
We plot the sensitivity achieved, MAGIC sensitivity and Crab SEDs
Parameters
--------
n_bins_energy: `int` number of bins in energy
energy: `numpy.ndarray` sensitivity array
sens: `num... | 43897782fe250fcdd04f6cf64782d42988ef548a | 3,634,671 |
def factor(from_units, to_units, units_class=None):
"""
Return a conversion factor:
>>> value_in_cm = 25
>>> value_in_cm * factor('cm', 'mm')
250
class: If specified, the class of the units must match the class provided.
"""
if (from_units is None or not len(from_units)) a... | d7893b20652ae8cdbefa50d2d8ac75db92ef7db1 | 3,634,672 |
def fibonacci_index(index):
"""
Returns fibonacci sequence with the given index being the last value.
raises a type error if given index is a string, float, zero or negative number.
returns a string for given indexes that are 1 and 2.
"""
try:
if type(index) == str or type(index) == floa... | fe6af59ed30d2559ed3d8822ff3b78d21fee6f65 | 3,634,673 |
from pathlib import Path
def get_history_file_path():
"""Returns path to the training command history file."""
return Path(__file__).parent / 'history' | b55e6ad58f1b841d22cce1fe421f17740abc32a0 | 3,634,674 |
def var_is_protein_effecting(variant_data):
"""Check if variant has a MED or HIGH impact
:param variant_data: A GeminiRow for a single variant.
:type variant_data: GeminiRow.
:returns: bool -- True or False.
"""
if variant_data.INFO.get('impact_severity') != "LOW":
return True
else:... | 7e0915086ada165c0ab814a70907756c976cd361 | 3,634,675 |
def center_embeddings(X, Y):
""" Copied from Alvarez-Melis & Jaakkola (2018) """
X -= X.mean(axis=0)
Y -= Y.mean(axis=0)
return X, Y | a583c400db2e3ddcabc535dc20c8866b432828d6 | 3,634,676 |
def verification_code_form(request):
"""
form to enter the verification code
"""
if request.method == 'POST':
code = request.POST['code']
return _verify_code(request, code)
return {} | bece318d0ea7fd9af4effa595abb79acac8129e2 | 3,634,677 |
import os
def _ProcessGccConfig(target, output_dir):
"""Do what gcc-config would have done"""
binpath = '/bin'
envd = os.path.join(output_dir, 'etc', 'env.d', 'gcc', '*')
srcpath = _EnvdGetVar(envd, 'GCC_PATH')
for prog in os.listdir(output_dir + srcpath):
# Skip binaries already wrapped.
if (not pr... | a3f0b23aebb6b1716783040c1d5a9ff5c88dcafc | 3,634,678 |
from typing import Union
from datetime import datetime
def symbol_directory(date: Union[str, datetime.date, None] = None, filter: str = ''):
"""
Args:This call returns an array of all IEX-listed securities and their corresponding data fields. The IEX-Listed
Symbol Directory Daily List is initially generat... | 86796ab2701a34ab72915b1becafff510ac6cfc0 | 3,634,679 |
import re
def read_requirements(*parts):
"""
Return requirements from parts.
Given a requirements.txt (or similar style file),
returns a list of requirements.
Assumes anything after a single '#' on a line is a comment, and ignores
empty lines.
:param parts: list of filenames which contai... | c281666075e6a6863f5f4e8ca13226f3f20f783c | 3,634,680 |
def build_persistence(config):
"""
Factory method to build a Persistence object from the given config
"""
try:
if config.getboolean("taky", "redis"):
return RedisPersistence(config.get("taky", "hostname"))
return Persistence()
except (AttributeError, ValueError):
... | 786cbfcff5e2c7853bf9661c82a2f763d909dfba | 3,634,681 |
def EulerP_G(e0,e1,e2,e3):
""" Angular velocity matrix such that omega_global = G theta_dot for Euler parameters
G = 2 E
Shabana (2.35, 2.54)
"""
G = 2*np.array([
[-e1 , e0, -e3, e2],
[-e2 , e3, e0, -e1],
[-e3 ,-e2, e1, e0]])
return G | 71c85ba992d67988d52451012b8eb1da1ae426dc | 3,634,682 |
def scale_range(x, x_range, y_range=(0.0, 1.0)):
"""
scale the number x from the range specified by x_range to the range specified by y_range
:param x: the number to scale
:type x: float
:param x_range: the number range that x belongs to
:type x_range: tuple
:param y_range: the number range... | 3e2f5185f1565d70e8d1d699f3b5b1e00d375e21 | 3,634,683 |
import math
def circular_difference(num1, num2):
"""Cicrular Difference on ring: num1 - num2
Arguments:
num1 {Integer}
num2 {Integer}
Returns:
Integer -- Circular Difference
"""
global M
if num1 > num2:
return num1 - num2
else:
return int(m... | dcfd58eab23744c1be4da521df4b85fd3436ee5d | 3,634,684 |
import os
def find_free_port(ports_socket, name):
"""Retrieve a free TCP port from test server."""
request_name = '-'.join((name, str(os.getpid())))
while True:
port = test_server_request(ports_socket, request_name, GETPORT)
if not tcp_listening(port):
return port
error... | b316cba4cb75f80e9022bbecdc886d2cb6449afb | 3,634,685 |
def make_leaderboard() -> dict:
"""
make a leaderboard from the data.
:rtype: dict
:return:
"""
sync_data()
# order function
order = sorted(users.items(), key=lambda val: val[1]['wallet'], reverse=True)
# ranks dict
names = {
'first': {'id': 0, 'name': "None", 'score': 0... | de9665cf8512b1c791c4db387e2f9df286715de8 | 3,634,686 |
from typing import Union
from typing import Optional
import os
def resolve_value_descriptor(value_descriptor: Union[str, dict]) -> Optional:
"""
Resolves the value of a value descriptor, which may be an environment variable
name, or a map with keys `env` (the environment variable name) and `value` (the
... | 1f99a120ea75f48d5093b3fa8253acbb2657947d | 3,634,687 |
def simple_rouse_mid_msd(t, b, N, kbT=1, xi=1, num_modes=1000):
"""
modified from Weber Phys Rev E 2010, Eq. 24.
"""
rouse_corr = 0
for p in range(1, num_modes+1):
k2p = rouse_mode_coef(2*p, b, N, kbT)
rouse_corr += 12*kbT/k2p*(1 - np.exp(-k2p*t/(N*xi)))
return rouse_corr + 6*kbT... | a836a23c6bdd180f9a4df563b1cd283aefe370b5 | 3,634,688 |
def get_output(img):
"""
Input: Image as numpy array.
"""
height, width = img.shape
c = Canvas()
with open("out.txt",'w') as f:
for h in range(height):
for w in range(width):
if img[h,w] == 255:
c.set(w,h)
f.write(c.frame())
... | 1d5d356ae6b9eaaf1c89955d7ac91a42ddc115f8 | 3,634,689 |
def threshold_binarize(x, threshold=0.5):
""" Thresholds tensor, making each element
that is more than 0.5 equal to 1.
"""
ge = tf.greater_equal(x, tf.constant(threshold))
y = tf.where(ge, x=tf.ones_like(x), y=tf.zeros_like(x))
return y | 921db92a7f2af6e5020368589bcc6570aef0fea7 | 3,634,690 |
from scipy.stats import linregress
from scipy.spatial import ConvexHull
from scipy.interpolate import interp1d
def dir_io_surface(links, nodes, dims):
"""
Set directionality by first building a "DEM surface" where inlets are "hills"
and outlets are "depressions," then setting links such that they flow
... | 4f5cc7243332ae75077b2092498ecf80c827e010 | 3,634,691 |
def guardian_join(team):
"""Returns a string of all of the parent guardians on the team joined together"""
guardian_names = []
for player in team['team_players']:
guardian_names.extend(player['guardians'])
guardian_string = ", "
guardian_string = guardian_string.join(guardian_names)
retu... | 5b9c7908598a65bb5e465fae13258de99fbf8597 | 3,634,692 |
def LCF_graph(n,shift_list,repeats,create_using=None):
"""
Return the cubic graph specified in LCF notation.
LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed
notation used in the generation of various cubic Hamiltonian
graphs of high symmetry. See, for example, dodecahedral_graph,
d... | 7d46b4d246ccbd821fbb31659f516fb1e185cea9 | 3,634,693 |
from typing import ByteString
def is_prefix_of(prefix: ByteString, label: ByteString) -> bool:
""" Whether label starts with prefix """
if len(prefix) > len(label):
return False
for (a,b) in zip(prefix, label):
if a != b: return False
return True | 6be10ca432876f7847e2f8513e5205a9ae4d3c16 | 3,634,694 |
from ..architectures import create_unet_model_3d
from ..utilities import get_pretrained_network
from ..utilities import get_antsxnet_data
def lung_extraction(image,
modality="proton",
antsxnet_cache_directory=None,
verbose=None):
"""
Perform proton ... | 4ca10e869413f1739098b46a097b0f07b907734b | 3,634,695 |
def adjective_to_verb(sentence, index):
"""
:param sentence: str that uses the word in sentence
:param index: index of the word to remove and transform
:return: str word that changes the extracted adjective to a verb.
A function takes a `sentence` using the
vocabulary word, and the `index` o... | 3a07f8eaaa8e39e77270b7eda9d2e4bc51bdbaf5 | 3,634,696 |
async def async_setup_entry(hass, config_entry):
"""Load the saved entities."""
_LOGGER.info(
"Version %s is starting, if you have any issues please report" " them here: %s",
VERSION,
ISSUE_URL,
)
config_entry.options = config_entry.data
config_entry.add_update_listener(updat... | 6645db4b75711e3c0c4bd5d635187286e68b1fb4 | 3,634,697 |
import re
def entry(request):
"""微信处理入口
"""
msg_crypt = WXBizMsgCrypt(
Conf.get('WECHAT_TOKEN'),
Conf.get('WECHAT_ENCODING_AES_KEY'),
Conf.get('WECHAT_CORPID'))
msg_signature = request.GET.get('msg_signature')
timestamp = request.GET.get('timestamp')
nonce = request.GET... | 4069690213d923bd3b516f9c83322f3d1107084d | 3,634,698 |
from typing import Union
def unit2internal(src_unit: Union[str, float]):
"""
Convert unit to internal unit system defined above.
Args:
src_unit (str, float): Name of unit
Returns:
float: conversion factor from external to internal unit system.
"""
return _parse_unit(src_unit,... | cd48d4da21d4fd1ac625a8be80ae854db478af3e | 3,634,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.