content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from sys import version
def english_to_norvegian(english_text):
""" traduit anglais en norvegien"""
if english_text is None:
norvegien_text=None
else:
l_t = get_language_translator(apikey, version, url)
translation = l_t.translate(
text=english_text,
model_i... | 87b3d2d0889ab7e89d82cf33638e0a20f0bc4d1a | 57,600 |
def gen_verification_token(user):
"""Create JWT token that the user can use to verify its account."""
expiration_date = timezone.now() + timedelta(days=3)
payload = {
'user': user.username,
# UTC format
'exp': int(expiration_date.timestamp()),
'typ... | 2d2c286b66b7ee1ad8a579c4c21c030501afbe1c | 57,601 |
def FontMapper_GetSupportedEncodingsCount(*args):
"""FontMapper_GetSupportedEncodingsCount() -> size_t"""
return _gdi_.FontMapper_GetSupportedEncodingsCount(*args) | 68d3111e5d2787393720719ee70c3587d43f874b | 57,602 |
def get_ramp_multiplier(ramp_option, T, wp_final_multiplier=1.0):
"""
Return a time-varying multiplier.
Returns:
A (T,) float vector containing weights for each time step.
"""
if ramp_option == RAMP_CONSTANT:
wpm = np.ones(T)
elif ramp_option == RAMP_LINEAR:
wpm = (np.ara... | e200ed6a31c0758195b89c729fccb0cb0871ff56 | 57,603 |
from typing import Dict
def true_best_objective(
optimization_config: OptimizationConfig, true_values: Dict[str, np.ndarray]
) -> np.ndarray:
"""Compute the true best objective value found by each iteration.
Args:
optimization_config: Optimization config
true_values: Dictionary from metri... | ba4f92c5acc02fc8530f84a097244aaae2faf5eb | 57,604 |
def max_liquid_water_content(model):
"""
Calculate the maximum liquid water content of snow.
The following options for calculating the maximum liquid water content are
supported:
- 'pore_volume_fraction': maximum LWC is set to a fraction of the snow
pore volume following [1].
... | 14441e0fb6476f91160cf413510af925f28f3180 | 57,605 |
import tempfile
import os
import yaml
def save(config):
"""Save a clang config to a new file and returns the name of the file."""
(fd, name) = tempfile.mkstemp()
f = os.fdopen(fd, "a")
f.write(yaml.dump(config))
f.close()
return name | 39651cfc9e60547469fddebf7424e3ee9aa4e84b | 57,606 |
import os
def parse_function(function, default_type='lambda'):
"""
Parse function expression which start from function type (e.g. 'lambda:')
The function expression has to be start from 'lambda:', 'file:', 'regex:',
or 'builtin:' (shortcut alias of 'file:' type for builtin functions).
If no funct... | c9a5366ae6d18c2558d36f940411c8c8fe5c6197 | 57,607 |
def get_equipment_config(oc_user,params):
"""获得装备配置
"""
return 0, {'equipment_config':game_config.equipment_config} | 79a37f365dd4c5bc7bd2c97424e79b4a628d33b9 | 57,608 |
def correct_extrinsic(sample,x0):
"""correct extrinsic parameters for phases and cosines"""
#TODO check these are the right parameters to be shifting
sample[x0.idx_cos_inc],sample[x0.idx_psi] = reflect_cosines(sample[x0.idx_cos_inc],sample[x0.idx_psi],np.pi/2,np.pi)
sample[x0.idx_phase0] = sample[x0.idx... | c5805cc1ca0c1908b17cab90b737d6d124d30ed8 | 57,609 |
import signal
def butter_bandpass_filter(h, lowcut, highcut, fs, order):
"""
-> Esta função aplica um filtro digital linear duas vezes, uma para frente e
outra para trás. O filtro combinado tem fase zero e um filtro solicita o dobro
do original. A função fornece opções para lidar com as bordas do sin... | 2a0b08a4f889f9576302dfc1afd9a46a6a4c251c | 57,610 |
def deleteWatch():
"""
Delete a movie to from watchlist
"""
filmId = request.form["delete"]
record = Watchlist.query.filter_by(id=1)
print(record.film_id)
print(record.user_id)
db.session.delete(record)
db.session.commit()
return redirect(url_for('home.watchlist')) | 16f51ce2dd1652bd15f6c41b8adb2406e279f730 | 57,611 |
import random
def ramb18(tile_name, luts, lines, sites):
""" RAMB18E1 in either top or bottom site. """
params = {}
params['tile'] = tile_name
params['Y0_IN_USE'] = random.randint(0, 1) == 1
params['Y1_IN_USE'] = not params['Y0_IN_USE']
params['FIFO_Y0_IN_USE'] = False
params['FIFO_Y1_IN_... | bddb777fe93fb27fd13fd781db38a8b007fc7528 | 57,612 |
from typing import Sequence
from typing import Tuple
def get_attestation_component_deltas(state: BeaconState,
attestations: Sequence[PendingAttestation]
) -> Tuple[Sequence[Gwei], Sequence[Gwei]]:
"""
Helper with shared logic for use by... | 0236e72808422c1de5df3a83c0a3ca7d064043f3 | 57,613 |
from functools import wraps
import traceback
def throws_synthesis_exception(fn):
"""
A decorator to automatically catch and format synthesis exceptions raised
by synthesis functions. The decorator will call the given function and log
simulator specific exceptions before throwing them to the caller.
... | b6be65d2369e37ddd06c0b63f77cd948bea17f57 | 57,614 |
def pass_messages_down(prob, intermed, C):
"""
Calculate marginal probabilities, using the cardinality probabilities
:param prob: non-sparse probabilities of each component
:param intermed: cardinality probabilities for successive subsets of components
:param C: total cardinality
:return: margin... | 8b2be045f7e9d9e153a72eedf344c3b6eff7c53b | 57,615 |
def _put_key(pubkeyb64, eph_secret, file_key):
"""This method encrypts file key using X25519 and returns X25519 line
argument list.
Args:
pubkeyb64: target base64url-encode X25519 public key.
eph_secret: 32-bytes ephemeral secret.
file_key: file key to encrypt using X25519.
R... | 4e3dbbd37f9d6f7de0a71301d400641603892386 | 57,616 |
def gen_fit_pars(**kwargs):
"""
Generate fit parameters.
Every keyword will create a parameter, keywords ending with '_min' or
'_max' will define the upper and lower bound for the parameter.
Example
-------
gen_fit_pars(D=1e-6, D_min=0, f_c=1000, f_c_max=1e6) will create
OrderedDict([(... | 0ad2c7ad8fa838f2a3164c47630524def52626c1 | 57,617 |
def get_unique_fields(fld_lists):
"""Get unique namedtuple fields, despite potential duplicates in lists of fields."""
flds = []
fld_set = set([f for flst in fld_lists for f in flst])
fld_seen = set()
# Add unique fields to list of fields in order that they appear
for fld_list in fld_lists:
... | 0e131c5b3fe695670fafb51810c674e859c29b63 | 57,618 |
def tag_vm_to_resource_id(tag_id, vm_id):
"""Generate resource_id from tag_id/vm_id"""
if not vm_id or not tag_id:
raise cfy_exc.NonRecoverableError(
"Please recheck tag_id/vm_id"
)
return "%s|%s" % (tag_id, vm_id) | 8bc1a638f423930a38baa0cccb1999557ba70e6c | 57,619 |
def derive_url_dicts(url_obj_list):
"""Derive a list of url dicts from the obj list
:param url_obj_list: List of URL objects
:type url_obj_list: `list`
:return: List of URL dicts
:rtype: `list`
"""
dict_list = []
for url_obj in url_obj_list:
dict_list.append(derive_url_dict(url_... | 176c98559da69fd7465e687819346992ea93eaf7 | 57,620 |
def get_homology_mapping(homologene_file, tax_id="10090", from_tax_id="9606", symbol_type="geneid"):
"""
symbol_type: geneid | symbol
"""
geneid_to_geneid, group_to_taxid_to_geneid = parse_ncbi.get_homology_mapping(homologene_file, tax_id, from_tax_id=from_tax_id, symbol_type=symbol_type)
return gen... | c1cd7a79656230b6da42a324fd81171c3aca6427 | 57,621 |
def cmp_func_different_hash(request):
"""Return a comparison function that checks whether two hashes are different."""
return request.param | 5e917de2db60c03d17fc5536e5af48e0328423fc | 57,622 |
import sys
def get_current_os():
"""The function to determine the OS in which the program operates.
Used in CLI and tests.
:return: an instance of the appropriate class to work with the current OS
"""
if sys.platform.startswith('win'):
current_os = WinOS()
elif sys.platform.startswith... | d4331aad52fa793ef81f142272f6bce8dfa845ae | 57,623 |
def get_root_to_frame_info(frame_to_root_info, verbose):
"""returns a dictionary with per root the frame, path to root and length of the path"""
root_to_frame_dict = defaultdict(list)
for frame, info_list in frame_to_root_info.items():
for info_dict in info_list:
root = info_dict['root'... | 89c4459c269b3915a73182c00afe83ba1f03bfc3 | 57,624 |
import itertools
def partition_probability(partition, A, beta=.1):
"""Gives partitions probabilities as exp(-beta*Ei)
where Ei is the sum of binding energies of the components of the partition.
Given a partition (list of mass fragments {A_j}), the sets of all possible
species per mass {S^A_k} are... | df5c903d692b4241d6bde68df6a61b85d2433054 | 57,625 |
import logging
def setup_console_logger(name, level=logging.INFO):
"""Setup a project wide logger singleton"""
formatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = ColorizingStreamHandler()
handler.setFormatter(formatter)
handler.setLevel(level)
... | cbe0f16997f194fb02469028c4b194869ad07266 | 57,626 |
def rolling_std_nb(a: tp.Array2d, window: int, minp: tp.Optional[int] = None, ddof: int = 0) -> tp.Array2d:
"""2-dim version of `rolling_std_1d_nb`."""
out = np.empty_like(a, dtype=np.float_)
for col in range(a.shape[1]):
out[:, col] = rolling_std_1d_nb(a[:, col], window, minp=minp, ddof=ddof)
r... | 8525beb15647a85fe505e28efe61a05c226ad0d4 | 57,627 |
def winner(board):
"""This function accepts the Connect Four board as a parameter.
If there is no winner, the function will return the empty string "".
If the user has won, it will return 'X', and if the computer has
won it will return 'O'."""
for row in range(7):
count = 0
last = ''... | 7c7983ec33cf6aca89283a2c09b9fabf2045f1b9 | 57,628 |
def main(input_dir, output_dir):
""" Make interim PDB structures (from pdb/raw/)
for final processing (saved in pdb/processed/).
"""
config = utils.read_config()
pdb_code = config['pdb']['id']
# Data import
pdb_struct = load_structure(pdb_code, input_dir, file_extension="pdb1") ... | 61be0b1d9d143296ae9e4b752bf0866b82398e39 | 57,629 |
import torch
def picp(target, predictions:list, total = True):
"""
Calculate PICP (prediction interval coverage probability) or simply the % of true
values in the predicted intervals
Parameters
----------
target : torch.Tensor
true values of the target variable
predictions : list
... | ef075b4cf3904a5f854ab4db3ecfbc6ba66ad674 | 57,630 |
import math
def diameter(freq):
"""Calculates a node diameter based on the frequency of its word."""
return STYLES['node']['diameter'] * math.sqrt(freq) | 9fc992ef3718fa9c741a2346b13f32ca7e083971 | 57,631 |
def get_next_click_pos():
"""
Gets the x, y coordinates of the next left-click.
Returns:
(int, int) - the x and y coordinates.
"""
while win32api.GetKeyState(0x01) > -127:
sleep(0.001)
print("GOT")
pos = win32api.GetCursorPos()
while win32api.GetKeyState(0x01) <= -127:
... | 82975a1e696f944cf02a3f87c4b0bee903400935 | 57,632 |
def licence(request):
"""
授权信息
:param request:
:return:
"""
licence_file = '/usr/local/u-mail/data/www/webmail/licence.dat'
if request.method == "POST":
f = request.FILES.get('licence_file', '')
if not f:
messages.add_message(request, messages.ERROR, u'请选择授权文件导入'... | 039ba06be30e5e76d2ecfc51a9d34fd6cf603676 | 57,633 |
import random
import hashlib
def generate_token():
"""Generates a token with randomly salted SHA1. Returns a string.
"""
_MAX_CSRF_KEY = long(2 << 63)
salt = str(random.randrange(0, _MAX_CSRF_KEY)).encode('utf-8')
return hashlib.sha1(salt).hexdigest() | 6424bd6f8b2f7d8f7233cb878d01f6e96ac98c9c | 57,634 |
def get_solver(solver='default', loss='lin_reg',
penalty=None, constraint=None, lla=False):
"""
Returns a GlmSolver object.
Parameters
----------
solver: str, GlmSolver
The solver we want. If 'default', we will try to guess the best solver to use.
loss: LossConfig
... | 90f59aa1808155ba2e328d9bd0e1456c5db313d9 | 57,635 |
def entropy(y_true, y_pred):
"""SOM class distribution entropy measure.
Parameters
----------
y_true : array, shape = [n]
true labels.
y_pred : array, shape = [n]
predicted cluster ids.
Returns
-------
entropy : float (lower is better)
References
----------
... | 988181d6e875c7139491377ab174f29f385c9be2 | 57,636 |
def _smooth_image_pair(con_img, vcon_img, sigma, method='default'):
"""
Smooth an input image and associated variance image using either
the spatial uncertainty accounting method consistent with Keller
et al's model, or the SPM approach.
"""
if method == 'default':
smooth_fn = _smooth
... | f6c106db4ae6a2416c9e3d862d01c2e69b2a008a | 57,637 |
def section():
"""
RESTful CRUD controller
- unused
"""
# Load Model
#table = s3db.survey_section
def prep(r):
s3db.configure(r.tablename,
deletable = False,
orderby = "%s.posn" % r.tablename,
)
re... | ce2313af3934c95942146fc3eceb0f6d0de24617 | 57,638 |
def getval(filename, key, *ext, **extkeys):
"""Get a keyword's value from a header in a FITS file.
@type filename: string, file object, or file like object
@param filename: name of the FITS file, or file object
(if opened, mode must be one of the following rb,
rb+,... | a112d24795aba4dbf2fbbbb1b672badfdd97751e | 57,639 |
import io
import yaml
import hashlib
def compute_parse_tree_hash(tree):
"""Given a parse tree, compute a consistent hash value for it."""
if tree:
r = tree.as_record(code_only=True, show_raw=True)
if r:
r_io = io.StringIO()
yaml.dump(r, r_io, sort_keys=False)
... | 38f5af485d6f008d46b8b4165096f30e5b004d0b | 57,640 |
def read_sql_table_from_connection(query, connection, selected_columns=None):
"""This function executes a SQL query in the given connection. Although you
can specify the columns selected in the query, you can specify the columns
needed in selected_columns. This will help to deal with different versions
... | 290dd3c7a5a7d64704c908a11d0ffec7fb1c7e3b | 57,641 |
import re
def filterSetupJson(fd):
"""Filters out possible comments in setup JSON file"""
return ''.join(list(filter(lambda line: re.search('^[ \t]*#',line) == None,fd.readlines()))) | b05c0cb2e88c1192ed6dae19d47c112df91441d4 | 57,642 |
from typing import Tuple
import datasets
def load_regression_dataset(
dataset_name: str) -> Tuple[testbed_base.Data, testbed_base.Data]:
"""Returns dataset data from dataset_name."""
if dataset_name not in datasets.REGRESSION_DATASETS:
raise ValueError(f'dataset {dataset_name} is not supported yet.')
x,... | c8b343f05f5b85e17165293a995875a5d2a83825 | 57,643 |
def calc_cost(y, x, theta_1, theta_0):
"""
y = theta_0 + theta_1 * x
"""
h = theta_1 * x + theta_0
d = h - y
cost = np.dot(d.T, d) / (2*x.shape[0])
return cost.flat[0] | f0fe7472044fc1dd711e3e43e2d8d1755919f5bb | 57,644 |
import os
def docker_client(version=None):
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
if 'DOCKER_CLIENT_TIMEOUT' in os.environ:
log.warn('The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. ... | 52c22b9a09da4761207e8e7cf276f0988065e5b2 | 57,645 |
def split_matrix_1(input1):
"""
Split matrix.
Args:
inputs:tvm.Tensor of type float32 with shape [4608,4608].
Returns:
result_2:tvm.Tensor of type float32 with shape [4,128,128].
"""
result_2 = allocate((4, split_dim, split_dim), input1.dtype, 'local')
for i in range(4):
... | 39134ecf4cc12242a4ef868d8ce1b4b6896d92d9 | 57,646 |
from typing import Sequence
def int_seq_to_layertypes(int_seq: Sequence[int]) -> Sequence[LayerTypes]:
"""
Convert an integer sequence to a sequence of layer types.
Parameters
----------
int_seq
An iterable of integers in the range [1, 4)
Returns
-------
type_seq
A... | 6ba257ee8f77cbc0581c401e1312eccad09e215b | 57,647 |
def knot_vector_from_params(degree, params, periodic=False):
"""Computes a knot vector from parameters using the averaging method.
Please refer to the Equation 9.8 on The NURBS Book (2nd Edition), pp.365 for
details.
Parameters
----------
degree : int
The degree of the curve
params... | 059463258011eaa4f76dfd8c640b62aa663d8226 | 57,648 |
import os
import zipfile
def fetch_smsspam(data_home=DATA_HOME):
"""Load the Spambase dataset from the UCI ML repository.
Parameters
----------
data_home: Path to download the files.
Returns
-------
df : DataFrame with the attributes as described in the dataset docs.
"""
if... | f6b744fa3758da4c9d96d15ea1187bf17407fd58 | 57,649 |
from typing import OrderedDict
import json
def _parse_register_dump(version: int, data: memoryview) -> str:
"""
Parser for the register dump.
"""
stream = DataStream(data, byte_order='big', is_signed=False)
parser = ParserData()
out = OrderedDict()
# The register dump will just be a l... | 74f60f9a65631a49f7823ca6c3a53d8336b103cf | 57,650 |
from typing import List
from typing import Callable
def multiple_selection_with_duplicates(population: List[Individual],
selection_size: int,
selection_function: Callable[[List[Individual]], Individual]
... | 6b66f106699e6c00aa08519d9ffc3b5a805dc35d | 57,651 |
import re
def time_to_frame(line: str, fps=24000 / 1001) -> int:
"""
Converts a timestamp in the format <hours>:<minutes>:<seconds>.<milliseconds> into the corresponding frame number.
<hours> and <milliseconds> are optional,
and milliseconds can have arbitrary precision (which means they are no longer... | 0942ce5526592eeb8c6a858631382530ad2dccbd | 57,652 |
import torch
def get_test_dict(idx):
"""
Get FRCNN style dict
"""
num_objs = 0
boxes = torch.zeros((num_objs, 4), dtype=torch.float32)
return {'boxes': boxes,
'labels': torch.ones((num_objs,), dtype=torch.int64),
'image_id': torch.tensor([idx]),
'area': (b... | bd7e37499c30b9bd23d9b99ed187795fb9e5e6e1 | 57,653 |
def effective_robustness_helper(robustness_result, task):
"""
Helper function that computes the effective robustness metric as the performance difference compared to late fusion method.
:param robustness_result: Performance of the method on datasets applied with different level of noises.
:param task: ... | d8ee94f6039b3f674048bcaaf7191ef5794e6252 | 57,654 |
def scan_vul_details(request):
"""
Get the Network scan vulnerability details.
:param request:
:return:
"""
if request.method == 'GET':
scan_id = request.GET['scan_id']
if request.method == 'POST':
vuln_id = request.POST.get('vuln_id')
scan_id = request.POST.get('sca... | 7ffb692798225a4a323d6f0697ed30c4ad569447 | 57,655 |
import numpy
def mp3_singles2N(no, f, eri, D11, D12, D21, D22):
"""Return the doubly anomalous singles piece of the 3rd order
correction to the free energy.
"""
nv = (1.0 - no)
dA = (-1.0)*numpy.einsum(
'i,j,a,ai,ij,ja,ij,ja->',
no, no, nv, f, f, f, D11, D12)
dB = numpy.einsum(... | 3333115b4dfc7d11e11ad50e05f106bde327484c | 57,656 |
import os
def here(file_name):
"""
Get the given file name relative to the working directory
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), file_name)) | 51015b8e6f7443c3980a23b7ce0a27d9b5916748 | 57,657 |
import logging
import collections
import operator
def export_gmf(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
sitecol = dstore['sitecol']
oq = dstore['oqparam']
investigation_time = (None if oq.calculation_mode == 'scenari... | 77db2bcc7f1b33612971d87b24353176caa3b9d5 | 57,658 |
import functools
import inspect
import copy
import traceback
from datetime import datetime
def revert_to_error_rollback(function):
"""Decorator to revert task_state to error on failure."""
@functools.wraps(function)
def decorated_function(self, context, *args, **kwargs):
try:
return ... | 059ba9c19dbd05d3898d51638319861bedb0bfad | 57,659 |
def remove_none_vals(dt):
"""remove None values in a dictionary"""
return {k: v for k, v in dt.items() if not pd.isnull(v)} | 3e6c9762ebdcf44f5cc468f440f571c427e63f25 | 57,660 |
from typing import List
def checksum(rows: List[List[int]]) -> int:
"""
Solves the AOC second puzzle.
"""
check = 0
for row in rows:
minimum = min(row)
maximum = max(row)
check += maximum - minimum
return check | e95ff4418899d1f09671aac83feb4f5d35072808 | 57,661 |
import logging
def novice_move(board):
"""Novice AI - lightly weighted towards a low scoring move.
Args:
board: (Board) The game board.
Returns:
Array: Our chosen move.
"""
valid_moves = _get_moves(board, Square.black)
# Adjust Scores to prefer low point moves
large = valid_moves[0][2]
for ... | 488954650485f8f76a389ec4cdc964c0b6854320 | 57,662 |
def avg_steps_by_zero_eaters(model):
"""Returns average number of steps of zero eaters."""
steps = [
a.done_steps for a in model.schedule.agents
if isinstance(a, Creature) and a.eaten_candies == 0
]
if steps:
return np.average(steps)
else:
return np.NaN | fe628177277a486f15d02bfd5c770c0f5fff819a | 57,663 |
def ham_1d_bilinear_biquadratic(L=None, theta=0, *, S=1 / 2,
cyclic=False, **local_ham_1d_opts):
""" Hamiltonian of one-dimensional bilinear biquadratic chain in LocalHam1D
form, see PhysRevB.93.184428.
Parameters
----------
L : int
The number of sites.
t... | aa7f88fb05fa2188fc8c1597f7f19637d1175d13 | 57,664 |
def source_action(model_artifact_location, assets_bucket):
"""
source_action configures a codepipeline action with S3 as source
:model_artifact_location: path to the model artifact in the S3 bucket: assets_bucket
:assets_bucket: the bucket cdk object where pipeline assets are stored
:return: codepi... | ca3dc8a88ee97784d0d118b3f5f0b18e9b6f254d | 57,665 |
def file_order(entry):
"""
For a PlaylistEntry, return its original order in the Playlist.
"""
return entry['lineno'] | 8bbd6546e120cec018c0f7628fd1473ae5926dad | 57,666 |
import json
def create_diff_json(image_diff, file_output_name):
"""diff image file and save as file
args:
image_diff (object)
file_output_name (str)
returns:
saved_file (str)
"""
diff_content = {}
for attr in image_diff.attributes:
diff_content[attr] = {}
... | 0e5b506b7acbc15ca26f21640ee2748598858008 | 57,667 |
def build_hw_space(generator, constraints, method):
""" Create hardware parameter search space.
Parameters
----------
generator : generator
Generator info.
constraints : dict
constraint dictionary.
method : str
Measure method.
Ret... | 6079229a06ecfc725bcc758005c4d8e8a7d8aa3c | 57,668 |
import textwrap
import asyncio
async def drawtext(message):
"""
Generates an image with given text.
Example::
/drawtext Hello there!
"""
def execute():
im = Image.new('RGB', (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
lines = textwrap.wrap(message.content, w... | 4d83d4f2833e2d26389e5cc57cadca1a2b13ab7a | 57,669 |
def kinetic(ax,ay,az,bx,by,bz,aa,bb,Ra,Rb):
"""
Compute kinetic integral between two Cartesian gaussian functions.
INPUT:
AX: Angular momentum lx for Gaussian 1
AY: Angular momentum ly for Gaussian 1
AZ: Angular momentum lz for Gaussian 1
AA: Exponential coefficient for Gaus... | 54a0d4a923dab421c0c538ba1fed174e0d65d1a6 | 57,670 |
import requests
import json
def get_weather(coord_dict, token=None, test=True):
"""
Getting weather from Open Weather Map by coordinates (needs token).
:param dict coord_dict: latitude & logitude.
:param str token: token to Open Weather Map API.
:param bool test: if test=True, returns sample weat... | 2c6d51992dfea63d198575ef690324e1497e4eb8 | 57,671 |
def format_class_name(spider_name):
"""Format the spider name to A class name."""
return spider_name.capitalize() + 'Spider' | a477c02873347e8df975dade64b8c316ab8dfe67 | 57,672 |
import subprocess
def get_common_commit() -> str:
"""
Return the hash of the common commit of the local and upstream branches.
"""
result = subprocess.run(
'git merge-base @{0} @{u}'.split(),
stdout=subprocess.PIPE,
universal_newlines=True)
return result.stdout.strip() | 5264b2b59d6b3302a734da37be4686cec09d11ca | 57,673 |
def model_histories(request, *args, **kwargs):
"""
Looks at all the audit model histories and shows for a given model
"""
db = AccessAudit.get_db()
vals = db.view('auditcare/model_actions_by_id', group=True, group_level=1).all()
# do a dict comprehension here because we know all the keys in this... | 5dab0e9e2e92dfca1a5c00d14e637bdb0775e526 | 57,674 |
def ordinal(value):
""" Cardinal to ordinal conversion for the edition field """
try:
digit = int(value)
except:
return value.split(' ')[0]
if digit < 1:
return digit
if digit % 100 == 11 or digit % 100 == 12 or digit % 100 == 13:
return value + 'th'
elif digit ... | b97accfe96f214ffe9878c24bd78ab63083c9329 | 57,675 |
def mono_fp(unit_comb):
"""create bit mask image from
wall/entrance/LDK/bedroom/balcony/bathroom stacked array"""
# AREA_WALL = 64
# AREA_ENTRANCE = 32
# AREA_LDK = 16
# AREA_BEDROOM = 8
# AREA_BALCONY = 4
# AREA_BATHROOM = 2
mask_bits = np.array([64, 32, 16, 8, 4, 2], dtype=np.ui... | 79c27a7b8f020e9ec21cae575b8edf7b158c6358 | 57,676 |
import torch
def complex_abs(tensor):
"""Compute absolute value of complex image tensor
Parameters
----------
tensor : torch.Tensor
Tensor of shape (batch, 2, height, width)
Returns
-------
Tensor with magnitude image of shape (batch, 1, height, width)
"""
tensor = (tensor[:, 0] ** 2 + tensor[... | dd206d9fb58b819d5ed1c58af8e9fc559430ac3a | 57,677 |
from typing import OrderedDict
def create_column_index(annotations):
"""
Create a pd.MultiIndex using the column names and any categorical rows.
Note that also non-main columns will be assigned a default category ''.
"""
_column_index = OrderedDict({'Column Name' : annotations['Column Name']})
... | 0174be1f2c747f362c6149d429683f9df2a390d1 | 57,678 |
def base_x(alphabet_id: int) -> BaseX:
"""
lazy initialization for BaseX instance
>>> base_x(58).encode(b'the quick brown fox jumps over the lazy dog')
'9aMVMYHHtr2a2wF61xEqKskeCwxniaf4m7FeCivEGBzLhSEwB6NEdfeySxW'
>>> base_x(58).decode('9aMVMYHHtr2a2wF61xEqKskeCwxniaf4m7FeCivEGBzLhSEwB6NEdfeySxW')
... | d9a2a070c09964182312d7139b6368a7db8506b6 | 57,679 |
from typing import Optional
def get_uuid_for_error(**kwargs) -> Optional[str]:
"""
Return the uuid for the derived dataset if it exists, and of the parent dataset otherwise.
"""
rslt = get_dataset_uuid(**kwargs)
if rslt is None:
rslt = get_parent_dataset_uuid(**kwargs)
return rslt | f3c6e4ec5f3189ef01fe9a8f9b5eac87b2e181b9 | 57,680 |
def mention_list_by_sentence_with_anaphora(a_obj, prev_obj, server):
"""
returns a list of lists of mentions, where the nth index of the list
corresponds to the nth sentence in obj:
[['Andrea', 'Dan'], ['Shane'], []]
this includes mentions via anaphora.
a_obj is the speechact to retrieve menti... | 3f7090bc0769b9bc2c1c8bfe2c7e08c88077fca7 | 57,681 |
import win32security
import os
def isUserAdmin():
"""Check if the current OS user is an Administrator or root.
:return: True if the current user is an 'Administrator', otherwise False.
"""
if os.name == 'nt':
try:
adminSid = win32security.CreateWellKnownSid(
win32... | 9214ef749c6cfeeee0305f2e1d0bfdbf2b5cedcc | 57,682 |
def collect_table_keys(data, exclude):
"""
Resolve used fields per table
"""
table_keys = {}
for rule in data:
t = rule[OF_RECORD_ITEM.table]
for k in rule.keys():
if k not in exclude:
keys = table_keys.setdefault(t, set())
keys.add(k)
... | acb6b9548734c15ead2e9f08e430da68cd0577d5 | 57,683 |
def cross_product_matrices(vectors):
"""Return corresponding cross product matrices for an array of vectors
"""
length = vectors.shape[0]
result = np.tensordot(np.cross(vectors, unit_vectors(length, 3, 0)), np.array([1., 0., 0.]), axes=0) \
+ np.tensordot(np.cross(vectors, unit_vectors(len... | d12b5dca424bc56809c0e85adf20c71e453be4fc | 57,684 |
def format_docstring(usage: str, arg_list, kwarg_dict):
"""
Use argument lists to create Python docstring
"""
usage = usage.strip().strip("\"")
docstring = f'{usage}\n\n'
for arg in arg_list:
if not arg['input']:
continue
docstring += f"\t:param {arg['name']} {arg['t... | a68c0d03aaf851ffb039b722affbdc60f7d05c1c | 57,685 |
from pathlib import Path
import shutil
def temp_article_dir(temp_cwd: Path) -> Path:
"""Run the test from a temporary directory containing the
"tests/data/article" dataset.
"""
article_source_dir = Path(__file__).parent / "data" / "article"
for source_path in article_source_dir.iterdir():
... | 643b2c7f1183f19f263eaba0f3e930ac18fa6988 | 57,686 |
def load_states():
"""Loads the shapefile for states in the United States.
Returns
--------
data : DataFrame
DataFrame containing the shapefile for the United States.
"""
module_path = dirname(__file__)
df = gpd.read_file(join(module_path, 'cb_2018_us_state_500k/cb_2018_us_state_500... | 9f9fadb50781cfa3f783c07a3d9ea16bb3227203 | 57,687 |
def clamp_and_scale(img, bands, p, AOI):
"""
clip the upper range of an image based on percentile
This function is similar to ee.Image().clip() and ee.Image().unitScale(),
but operates on multiple bands with potentially different upper limits.
Parameters:
img (ee.Image): the image to modify
bands (... | 76081111644d4baa3ada4c93037d90ec21af1889 | 57,688 |
from typing import Union
from typing import List
import select
from operator import and_
def get_resources_for(guild_id: int, resource_type="role", session=db.open_session()) -> Union[List[db.Settings], None]:
"""
Searches db for resource in a guild that matches the setting name
:param guild_id: id of th... | af146ec17f71cd1c2cdefbb3beaad196ace80512 | 57,689 |
def rayleigh_k(x,k):
"""Rayleigh distribution parameterized by Fisher k parameter.
"""
return k*x * np.exp(-k*x**2/(2)) | 2dc84228eadb3dc1dc7d946335f02b4254530eda | 57,690 |
def _packaging_type(f):
"""Returns the packaging type used by the file f."""
if f.basename.endswith(".aar"):
return "aar"
elif f.basename.endswith(".apk"):
return "apk"
elif f.basename.endswith(".jar"):
return "jar"
fail("Artifact has unknown packaging type: %s" % f.short_pat... | 2b8cee53091672bb317ecdf29b869b8b8eb73f3f | 57,691 |
def get_validator_keys(epoch, endpoint=_default_endpoint, timeout=_default_timeout) -> list:
"""
Get validator BLS keys in the committee for a particular epoch
Parameters
----------
epoch: :obj:`int`
epoch number
endpoint: :obj:`str`, optional
Endpoint to send request to
tim... | d3f579c75f5cc394c106eefc876dc78074ba798f | 57,692 |
from typing import Any
import time
import json
def read_json_with_timeout(path: str) -> Any:
"""Repeatedly tries to read a json object from the given path, waiting
until there is a trailing new line indicating that the write is complete
Args:
path (str): The path to read from
Raises:
... | 60f61da6e54fdba72f3a5f7300bcd6afd899b866 | 57,693 |
def create_model(model_name, pretrained=False, checkpoint_path=None, **kwargs):
"""Create a model
Almost entirely taken from timm https://github.com/rwightman/pytorch-image-models
Args:
model_name (str): name of model to instantiate
pretrained (bool): load pretrained ImageNet-1k weights if... | 4f3fc75346ad3657891f1460e88bcc45d575ba01 | 57,694 |
from datetime import datetime
def next_weekday(d, weekday):
"""
(datetime, string) -> datetime
returns the first ocurrence of the given weekday after the initial datetime d
"""
days_ahead = weekday - d.weekday()
if days_ahead <= 0:
days_ahead += 7
return d + datetime.timedelta(days... | 456e93f9332bc208e35080c05fcce8c31c329dd1 | 57,695 |
def get_compatibility_matrix(g: nx.Graph, attr_name: str):
"""
From Danai's heterophily paper
:param g:
:param attr_name:
:return:
"""
values = set(nx.get_node_attributes(g, attr_name).values())
mapping = {val: i for i, val in enumerate(values)}
print(mapping)
C = nx.attribute_mi... | 3f8a144278495191ffc861f1c431545255edc93f | 57,696 |
def async_api():
"""
获取异步任务列表
get req:
pass
"""
# q = {filters:[{}], order_by, single, limit, offset, group_by}
query = Async.query.t_query
pagin = gen_query(request.args.get('q', None), query, Async, db=db, per_page=settings.PER_PAGE, get_objects=True)
objects = []
for o in... | 1955bc0c3d27839a4d575779cede5807be110536 | 57,697 |
import os
import concurrent
import tqdm
def get_dataset_metadata(dataset_root, input_w, input_h, max_jobs):
"""
Load all dataset metadata into memory. You might need to adapt this if your dataset is really huge.
"""
nonlocals = { # Python 2 doesn't support nonlocal, using a mutable dict() instead
... | 8ee845083ab3716caa9c58a6227566652fb2f0ac | 57,698 |
from operator import ne
def project(fld_a, fld_b):
""" project a along b (a dot b / magnitude(b)) """
# ax, ay, az = fld_a.component_views() # pylint: disable=W0612
# bx, by, bz = fld_b.component_views() # pylint: disable=W0612
# prod = ne.evaluate("(ax * bx) + (ay * by) + (az * bz)")
# mag = ne... | 5e6f0841896365ef41c180ec0239194e5bf4d632 | 57,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.