content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_train(filePath):
"""Loads training data."""
with open(filePath, 'rb') as f:
train_set = np.load(f)
train_inputs = train_set['train_inputs']
train_targets = train_set['train_targets']
return train_inputs, train_targets | 146864c0872e8d67cccf6602e14ce5775b6943fe | 3,595,801 |
def is_iterable(obj):
"""is_empty: Check if object is iterable.
:obj:
:returns: Bool
"""
try:
return bool(iter(obj))
except TypeError as e:
return False | 793846dbb1503b477115cbb4debfadd65c72a70c | 3,595,802 |
from .interface_vasp import Poscar
from .util.mathtool import mychop
def ReadPBC2Cart(fn_p1, p0, tol=1e-13):
"""
:param fn_p1: filename of p1
:param p0: ideal coordinates
R: lattice vectors
:return:
"""
str1 = Poscar.from_file(fn_p1).structure
p1 = str1.frac_coords
return mychop(... | efa7f2d153f4bde69c199e522e211800ad0ca05b | 3,595,804 |
import copy
import tqdm
def add_srt(raw_data_dicts, srt_data, eos_token="<eos>"):
""" add entries 'sub_time', 'sub_text' """
data_dicts = copy.deepcopy(raw_data_dicts)
eos_token = " %s " % eos_token # add space around
print("Adding subtitle ...")
for i in tqdm(range(len(data_dicts))):
vid... | 8b7c6776c5df4d2e1e668d3b1f26e42c478737bb | 3,595,805 |
def refactorize(arr, first_na, na_sentinel=-1):
"""
Modify `arr` *inplace* to match pandas' factorization rules.
This detects the code missing values were assigned, sets
those to `na_sentinel`, and shifts codes above that value
down by 1 to fill the hole.
Parameters
----------
arr : nd... | 31d5e07650bb0ec6f93d59d453d8de859ab0c621 | 3,595,807 |
def loadlyrics():
"""
Returns a list of all words in the lyrics.
Depending on the size of the lyics, this function may
take a while to finish.
"""
print("\nLoading lyrics from file ...\n")
# # inFile: file
# inFile = open(LYRICS_FILENAME, 'r')
# # line: string
# line = inFile.re... | c83e5d0f5e985b33aaec0da51604b33e052f8b98 | 3,595,808 |
def timFromPkl(timFiles):
"""Return a dictionary of [time of arrival (in MJD), sigma ToA (in microseconds)]xNumber of Observations from a list of pickle files
"""
timDict={}
for fn in timFiles:
#parse file name
#FORMAT: tim<MODE>_sn<SNR>_dj<DJ>_pp<POLPUR>.<CAL/UNCAL>.pkl
calMode=... | 4ca3872c0ec260768d8e61ce7cff89bb6d1314cf | 3,595,809 |
def plan_flight(p0, v0, psi0, t0, trgt, trgt_cpts, pastCpts, pastTimes, params,
tf=None):
"""
"""
randomizer = 0
while True:
ndim = 2
vf = params.monSpeed
psif = 2*np.pi*np.random.rand()
if tf is None:
tf = t0 + params.tflight
dt = tf -... | 2d0d30da1d376fee06bd8c1b104cf70e7002daf6 | 3,595,810 |
def get_exercise(exercise_name):
"""Return exercise data"""
# get filename for data
filename = request.cookies['fn']
# get exercise data
exercise_data = get_exercise_data(filename, exercise_name)
return jsonify(exercise_data=exercise_data) | e4e2b9fc1360d11e2df999681a2871be8307c27d | 3,595,811 |
def draw_five_stars (animal) :
"""Cette fonction permet de dessiner cinq étoiles grâce à la fonction précédente.
Parameters
----------
animal : turtle
l'objet de type turtle
Returns
-------
som : int
la somme des angles dont la tortue a tourné
.. math:: \sum angle
Examples
--------
>>> dra... | 1cf69b42313265a19eb7bfd4c042c25787fa543c | 3,595,812 |
import time
import hashlib
def generate_file_name(filename):
"""
@brief generate file name
@return new file name
"""
i = filename.rfind('.')
ext = filename[i:]
tmp = filename + str(int(time.time()))
hash_md5 = hashlib.md5(tmp)
return hash_md5.hexdigest() + ext | c4b3aebbaecafd85087769c179e33fdbd77a2b17 | 3,595,814 |
def lev_np(source, target):
"""
Levenshtein distance measured using numpy
from:
https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/
Levenshtein_distance#Python
Used under Creative Commons Attribution-ShareAlike License.
Parameters:
-----------
source : string
target... | f62879123cb0d219f19cef57bd3f80d72f5574a0 | 3,595,815 |
import re
def to_python_propname(word):
"""
Converts any word to lowercase word separated by underscore
"""
return re.sub('_+', '_',
re.sub('^_', '',
re.sub('[/\-: +]', '_',
re.sub('([A-Z]+)([A-Z])([a-z0-9])', '\g<1>_\g<2>\g<3>',
... | 3910cf63d11b64030f45f55c22e9a227e224d3c9 | 3,595,817 |
def get_file_id(service, file_name, mime_type=None, parent_id=None):
"""Return the ID of a Google Drive file
:param service: A Google Drive API service object
:param file_name: A string, the name of the file
:param mime_type: A string, optional MIME type of file to search for
:param parent_id: A st... | e8e371ea740ca4be55b35baa74c28207ca6b7b4d | 3,595,818 |
def get_grb_sense_from_string(sense):
"""
Return the GRB constraint sense object
corresponding to the supplied string.
Convention follows the Gurobi docs:
https://www.gurobi.com/documentation/6.5/refman/sense.html#attr:Sense
"""
if sense == "<":
return gp.GRB.LESS_EQUAL
eli... | 1ade439e2e4c27fd8f0bc43371cd86394c1b8903 | 3,595,819 |
import operator
def fetch():
"""
This function will update from TMD to my database now playing
:return:
"""
sqlstring = """SELECT api_key FROM api WHERE api_type='tmd'"""
cur.execute(sqlstring)
rows = cur.fetchall()
# This api_key will be moved to a database after initial build
api... | dd4332fef42ff1003b645ca9a4816099711c733f | 3,595,820 |
def get_section(f, first_delim, second_delim):
"""
Some open-source indicator downloads contain multiple sections.
This will return the section of the file f that is between the first_delim and second_delim
:param f: The file containing the section to be processed
:type f: file
:param first_delim: A string... | d0d08cf5fc157b7361c4ff5e20fe466de76d93fb | 3,595,821 |
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
"""Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.
For each box in boxlist1, we want its IOA to be more than minoverlap with
at least one of the boxes in boxlist2. If it does not, we remove it.
Args:
boxlist1:... | 57ab5a5d99a04e08299ba06a2d33c1737027e724 | 3,595,822 |
def differentiate_wrt(da, dim, x):
"""
Returns the gradient along dim using x to compute differences. This function is required \
because the current implementation of xr.differentiate (0.10.9) can only differentiate with \
respect to a 1D coordinate. It is common to want to... | c5d5514c375d901a4e6186daafe2957dc3c43dcc | 3,595,823 |
def heapsort(l):
"""
堆排序python实现
"""
n=len(l)-1
for i in range(n//2,0,-1):#i的范围为5,4,3,2,1没有0
fixdown(l,i,len(l))#执行到这里后,最大值77已经最后了
while n>1:
l[1],l[n]=l[n],l[1]#把序列尾部的元素放到堆顶位置,
fixdown(l,1,n)#将序列从新排列成大根堆
n=n-1#不断将堆订元素取出
return l[1:] | 60ab1f82f29bdb1b167ae94b4098247fb42c0138 | 3,595,824 |
def expand_node(n, fsroot, term_test, verbose=False):
"""Recursively find files we know what to do with. Specifically,
we recurse on FILE_COREGENISE files, and return a leaf node for
files for which term_test(file_type) is true."""
seq_no, file_type, file_name = n
if term_test(file_type):
... | ab50be66a1f6af8dd2a87c01aa06fec9832fa2ee | 3,595,825 |
def sort_lowest_neighbors(n, sub):
"""Sort neighbor cells by elevation."""
i, j = sub
if j == n.shape[1] - 1:
di, dj = np.array([0, 1, 1]), np.array([-1, -1, 0])
elif j == 0:
di, dj = np.array([1, 1, 0]), np.array([0, 1, 1])
else:
di, dj = np.array([0, 1, 1, 1, 0]), np.array... | c189a420f4dc5179a29b8249bda5113df2552d68 | 3,595,826 |
def track_add_systems(session, systems, distance):
"""
Add all systems specified to tracking with distance specified.
Returns: List of added system names.
"""
track_systems = track_get_all_systems(session)
track_systems = [x.system for x in track_systems]
to_add = set(systems) - set(track_s... | afa4def58ab599748f931a69001bb740494eede6 | 3,595,827 |
async def get_trades() -> list:
"""Returns a list of trades for the currently selected
account for current day and six previous days.
Returns:
list: A collection of `Trade` resources.
"""
return await async_make_request(method='get', endpoint='/api/iserver/account/trades') | 88f5090d602659bc77a54c6c0cc83f7b6e0e5df3 | 3,595,828 |
def accuracy_metric(actual, predicted):
"""
Calculate accuracy percentage
"""
correct = 0
for i in range(len(actual)):
if actual[i] == predicted[i]:
correct += 1
return correct / float(len(actual)) * 100.0 | db7d83d0d993e6ecdef59049009f842235f02bde | 3,595,829 |
from typing import Dict
def number_topics_and_clusters(model, level: int) -> Dict[str, int]:
"""Get the number of topics and clusters for a level of the model hierarchy."""
model.get_groups(level)
return {
"n_topics": model.groups[level]["Bw"],
"n_clusters": model.groups[level]["Bd"],
... | ff587450e06bb6ce7ce97bd454c310a7b8d9e4b1 | 3,595,830 |
import re
def get_year_from_date_str(date_str):
"""
Retrieve only the year from a text string.
"""
return re.findall(r'\d{4}', date_str) if date_str else None | b2b02e97963d12236f20dad5d6b5337404a0dfc7 | 3,595,831 |
def get_all_admin_users():
"""Gets all admin users of the application"""
email = get_jwt_identity()
user = user_obj.get_user_by_email(email)
role = user["role"]
if role != "admin":
return jsonify({"Message": "Log in as admin to view admin users"}), 401
users = user_obj.get_admin_users()
... | c21c343f6b7f30bb73ad494fabb940fc924d7945 | 3,595,832 |
from typing import Any
from typing import Dict
def split_bool(param: Any) -> Dict[str, Any]:
""" Split query parameter into filter-bool parameters """
if not param:
return {}
if type(param) == bool:
return dict(value=param)
value = param.lower() in ["true", "yes", "on", "1"]
return... | 1323eb2ccb1c54957470e8f51ffe8e594d76cabc | 3,595,833 |
def refine_video_friend_msg(ctx: FriendMsg) -> _VideoFriendMsg:
"""好友视频消息"""
if not isinstance(ctx, FriendMsg):
raise InvalidContextError('Expected `FriendMsg`, but got `%s`' % ctx.__class__)
if ctx.MsgType == MsgTypes.VideoMsg:
return _VideoFriendMsg(ctx)
return None | 06e96e2fdb0fd07a7778b68396054354248efcb6 | 3,595,834 |
import torch
def sdf_to_contact(sdf, dot_normal, method=0):
"""
Transform normalized SDF into some contact value
:param sdf: NORMALIZED SDF, 1 is surface of object
:param method: select method
:return: contact (batch, S, 1)
"""
if method == 0:
c = 1 / (sdf + 0.0001) # Exponential... | 836383225d843598d06b22f6caa1a0e9ac0592a5 | 3,595,835 |
def setup_k8s_api():
"""
Common actions to setup Kubernetes API access to Argo workflows
"""
config.load_incluster_config() # Only works inside of JupyterLab Pod
return client.CustomObjectsApi() | 325b82b0993d3360820d848407a99c849c228548 | 3,595,838 |
import types
def _construct_index(spec: types.Index) -> schema.Index:
"""
Construct composite index.
Args:
spec: The definitions for the composite index.
Returns:
The composite index.
"""
return schema.Index(
spec.get("name"), *spec["expressions"], unique=spec.get("u... | c25b4a75bb53c1023dea1c0a5c34949259aae5f3 | 3,595,840 |
def get_no_concrete_or_m2m(model):
"""获取反向或者对对多字段名称列表"""
return [
item.name
for item in get_all_relation_fields(model)
if not item.concrete or item.many_to_many
] | 54b735253f9f4bbf6527b52905c8240708261385 | 3,595,841 |
def profile_solver(ml, accel=None, **kwargs):
"""Profile a particular multilevel object.
Parameters
----------
ml : multilevel
Fully constructed multilevel object
accel : function pointer
Pointer to a valid Krylov solver (e.g. gmres, cg)
Returns
-------
residuals : arra... | e46ebd29784b67095467d1b74ff798a7d559a1e5 | 3,595,842 |
def limit(value, min_val, max_val):
"""Returns value clipped to the range [min_val, max_val]"""
return max(min_val, min(value, max_val)) | 8005e5cc9b6947e265f93eed1aa19f4e2abcc5ab | 3,595,843 |
def int2tap(x):
"""Convert integer to tap position."""
if x[0] == "-":
res = "pre" + x[1:]
else:
res = "post" + x
return res | 2af5e1b98258dfb921005a454689d862bdf3d9fe | 3,595,844 |
def generate_list(start, stop, step):
"""
>>> generate_list(0, 5, 1)
[0, 1, 2, 3, 4]
>>> generate_list(0, 0, 1)
[]
>>> generate_list(5, 10, 2)
[5, 7, 9]
>>> generate_list(10, 5, -2)
[10, 8, 6]
"""
idx = start
lst = []
if idx < stop:
while idx < stop:
... | 51082bd4acf65abdaacbb98b429d79dcb718d9f7 | 3,595,845 |
from typing import Iterable
from typing import Set
from typing import List
def sort_models_with_heuristic(models: Iterable[HuskyModel], taxons: Set[TaxonSlugExpression]) -> List[HuskyModel]:
"""
Returns the models in which order we should try to search the graph. It skips tag models,
because those cannot ... | c3e783155bbeea0c252193144f9a4ede77636596 | 3,595,846 |
def compile_bc_Livneh2013_locations(maptable):
"""
compile a list of file URLs for bias corrected Livneh et al. 2013 (CIG)
maptable: (dataframe) a dataframe that contains the FID, LAT, LONG_, and ELEV for each interpolated data file
"""
locations=[]
for ind, row in maptable.iterrows():
... | 01d6613d42fa1e12d617380f0fec4a9e60e629c7 | 3,595,847 |
def blocksearch(block, name):
""" Recursive search for name in block (inner blocks)
Args:
name (str): search term
Returns:
Block OR False
"""
if hasattr(block, 'tokens'):
for b in block.tokens[1]:
b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch(
... | da9f762dddabe762dbabd80addebc0a957b04135 | 3,595,848 |
def get_pts(directions):
"""From relative directions (eg. right 8, up 5, left 5, down 3),
creates a list of grid points crossed.
Args:
directions: list of relative directions
Returns:
list of (x, y) coordinate tuples (integer values) on the path.
"""
path = []
loc = (0,... | 974839da5e58d6c866983e5d630dbfa5e1e41c86 | 3,595,849 |
import hashlib
def get_hash_of_file(fname, algo="sha512"):
"""Returns the hexdigest of the SHA512 checksum of the
file found at fname.
"""
block_size = 65536
if algo.lower() == "md5":
_hash = hashlib.md5()
else:
_hash = hashlib.sha512()
with open(fname, "rb") as f:
... | db435d55256c787285948975d9e1ed3807cacef4 | 3,595,850 |
def replaceConstants(item: str) -> str:
"""Replaces all known constants defined in `config_values.py` in the given string.
These are placeholders like `${PROJECT_ROOT}`, `${PROJECT_NAME}`, ...
Args:
item (str): The string to parse for known constants.
Returns:
str: The substitution if... | 13efc0bdc1e8993b913b8a5ff456a2b204f9d295 | 3,595,851 |
def _get_mode_handle(ft_handle: FtHandle) -> Result[Ft4222Handle, FtError]:
"""Resolve and instantiate a correct device configuration class.
Args:
ft_handle: Handle to open FT4222 device stream
Returns:
Result[Ft4222Handle, FtError]:
"""
dev_details = ftd.get_device_info(ft_handle... | 17872a65dbccd98ea96351b5cbece44d81c5e378 | 3,595,852 |
def handle_store_boolean(self, *args, **kwargs):
"""Does the add_argument for action='store_boolean'.
"""
disabled_args = None
disabled_kwargs = kwargs.copy()
disabled_kwargs['action'] = 'store_false'
disabled_kwargs['dest'] = get_argument_name(getattr(self, 'cli', self)._arg_parser, *args, **kw... | b82803632747e0860105bc5fe4cfd8c74bed373c | 3,595,853 |
def addr_convert(addr, prefix, encoding=None, to_encoding=None):
"""
Convert address to another encoding and/or address with another prefix.
>>> addr_convert('1GMDUKLom6bJuY37RuFNc6PHv1rv2Hziuo', prefix='bc', to_encoding='bech32')
'bc1q4pwfmstmw8q80nxtxud2h42lev9xzcjqwqyq7t'
:param addr: Base58 ad... | 331ba9660570fbcc20c132de272b7e62f55045be | 3,595,854 |
def tau(x: np.ndarray):
"""Calculate the tissue specificity measure tau as in:
> Yanai, Itai, Hila Benjamin, Michael Shmoish, Vered Chalifa-Caspi, Maxim
> Shklar, Ron Ophir, Arren Bar-Even, et al. 2005. “Genome-Wide Midrange
> Transcription Profiles Reveal Expression Level Relationships in Human
> ... | 7c1ea4926e5b6ca9371a56b8397a3ac82879a4d2 | 3,595,855 |
def Sch(Lvec, LFparams):
"""
Schechter function
dn/dL = phistar * (L/Lstar)^alpha * exp(-L/Lstar)
Luminosity function parameters:
phistar Overall amplitude in (Mpc/h)^-3 L_sun^-1
Lstar High-luminosity cutoff location in L_sun
alpha Power law slope
Lmin Minimum luminosity ... | f70f647245c4fd627e6f9bed3c26e2c9e9bf5804 | 3,595,856 |
def get_symbol_configs(bar_file_format):
"""
根据文件获取合约的配置
:param bar_file_format:
:return: dict
"""
# 从vnpy.data.stock目录下,获取股票得基本信息缓存
config_dict = get_stock_base()
for vt_symbol, config in config_dict.items():
config.update({
'product': "股票",
'price_tick':... | 7c725bb6f3cf5c0577e12c931c54d4a13a3a5066 | 3,595,857 |
def decode_labels(mask, num_images=1, database='Cityscapes', mode = 'id'):
"""
Decode batch of segmentation masks.
:param mask: result of inference after taking argmax. 3D numpy array
:param num_images: number of images to decode from the batch.
:param num_classes: number of classes to predict (inc... | 4eb1e6ceee14dd648dd75c72d6508665ccc2e27f | 3,595,858 |
def _decl_conv2d(cfg, data, kernel, strides, padding, dilation,
layout, out_layout, out_dtype='float32'):
"""Conv2D operator for Intel Graphics backend.
Parameters
----------
data : tvm.Tensor
4-D with shape [batch, in_channel, in_height, in_width]
kernel : tvm.Tensor
... | 95fe98630fc5cb112530ffa0ddd30c2b4032c4dc | 3,595,859 |
def ndarray_mask_equal(ndarray,axis=0):
"""
Check if the mask along the specified axis for all subarrays are equal.
"""
if not np.ma.isMA(ndarray):
raise ValueError("input array is not mask array")
else:
base_array = ndarray[np_get_index(ndarray.ndim,axis,0)]
for i in range(1... | b8bf8aedb4f87cafc9b322b7b6aaa1ba6e3f7705 | 3,595,860 |
def get_het_graph_for(op: relops.Operator) -> nx.DiGraph:
"""
CPU/GPU schema only
:param op:
:return:
"""
if isinstance(op, relops.RelJoin):
return get_het_graph_for_join(op)
cpu = CPU()
gpu = GPU()
g = nx.DiGraph()
cpu_op = PlanNode(op, cpu)
gpu_op = PlanNode(op, gpu... | 27fd185694eb437ecc79707c16bbd5b79c0565e5 | 3,595,861 |
def create_training_input_fn(features, labels, batch_size, num_epochs=None, shuffle=True):
"""
A custom input_fn for sending qauntum data to the estimator for training.
Parameters:
features: The training features.
labels: The training labels.
batch_size: Batch size to use during training.
num_e... | 6cd9c2eef96c31767f1be92fe94ebd6bcec2008a | 3,595,862 |
def lonlat2bng(df, long='longitude', lat: str = 'latitude') -> pd.DataFrame:
"""covert longlat columns to eastern northern and return them as part of the DataFrame"""
df['eastern'], df['northern'] = convert_bng(df[long].tolist(), df[lat].tolist())
return df | 5dbff8994a8293ac529066732c9d26975fb412f8 | 3,595,864 |
def remove_completer(name: str):
"""removes a completer from xonsh
Parameters
----------
name:
NAME is a unique name of a completer (run "completer list" to see the current
completers in order)
"""
err = None
if name not in XSH.completers:
err = f"The name {name} is ... | 53d594236b7d93519ced8660e14472494674d1d8 | 3,595,865 |
def get_provenance_record(ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption':
('(a) Zonally averaged sea surface temperature (SST) error in CMIP5 '
'models. (b) Equatorial SST error in CMIP5 models. (c) Zonally '
'ave... | d0c68eb45dd0a9cee0746294b4fd3202dc1003de | 3,595,867 |
def incidence_plot(adj, classes, from_class):
"""Plots non-square adjacency, sorts by class label, sums input to columns for
marginal
Parameters
----------
adj : np.array
n x n adjacency matrix
classes : np.ndarray
n-length indicator of class membership for sorting nodes
... | 31bdcca6e7dba320f0025ee883d3add24b78e935 | 3,595,868 |
def IntProperty_DoValidation(*args, **kwargs):
"""
IntProperty_DoValidation(PGProperty property, wxLongLong_t value, PGValidationInfo pValidationInfo,
int mode=PG_PROPERTY_VALIDATION_ERROR_MESSAGE) -> bool
"""
return _propgrid.IntProperty_DoValidation(*args, **kwargs) | 83178f3f75461b953c268b84846067f6c1ab9dad | 3,595,869 |
import logging
def set_log(args, path="../"):
"""Loads and replaces default parameters with experiment
specific parameters
Args:
args (argparse): Python argparse that contains arguments
path (str): Root directory to get Git repository. Default: "."
Examples:
log[args.log_name... | 9d4f1c63fa65f655dd87e89e47d9404eacdb450d | 3,595,871 |
def getAverageCoords ( allAtomsList, atomsIndList ):
"""
Oblicz srednie wspolrzedne x, y, z wybranych atomow
Wejscie:
allAtomsList - lista obiektow Atom (cala czasteczka)
atomsIndList - lista indeksow atomow, ktorych usrednione polozenie
ma byc obliczone
... | 076fb6e06972c1de2d4d461ab888bc57f2e4643e | 3,595,872 |
def merge_shapes(shape1, shape2):
"""
Merge 2 shapes, return merged shape, choose more specific dimension value from either side.
Raise exception for mismatch.
"""
if shape1 is None:
return shape2
if shape2 is None:
return shape1
make_sure(is_list_or_tuple(shape1), "invalid ... | 2b328d53465aeb4384f1696dfecb4389b7012703 | 3,595,873 |
import torch
def st_gumbel_softmax(logits, temperature=1.0, mask=None):
"""
Return the result of Straight-Through Gumbel-Softmax Estimation.
It approximates the discrete sampling via Gumbel-Softmax trick
and applies the biased ST estimator.
In the forward propagation, it emits the discrete one-hot... | 97bed581bf62c9221714cfdba1dc5cf1d9c5dad6 | 3,595,875 |
import torch
def getMultiScaleCosAffinityMatrix(uniq_embs_and_timestamps: dict, device: torch.device = torch.device('cpu')):
"""
Calculate cosine similarity values among speaker embeddings for each scale then
apply multiscale weights to calculate the fused similarity matrix.
Args:
uniq_embs_a... | 3acde12e741d045ceee6f4a29c3537356ed5632c | 3,595,876 |
def state_from_measurements(three_measurements):
"""
Estimates state of robot from the last three measurements
Assumes each movement of robot is a "step" and a "turn"
Three measurements constitute two moves, from which turn angle, heading
and step size can be inferred.
"""
x1, y1 = three_m... | a7c0070715a3bfb5719b5c751494bd2738083a7d | 3,595,877 |
import re
def SeparaClitico(palavra):
"""Separa pronomes em ênclise, restaurando a forma canônica das formas verbais que sofrem alomorfias quando da adjunção de clíticos.
>>> for p in Toqueniza.PALAVRAS_COM_CLITICO:
print Toqueniza.SeparaClitico(p)
quebra-cabeça
esquecemos nos
vimos la
vender lo
partir la
partir... | 8b16e3dc8ec7071877ac67c8ec82ed4cbda8f6b2 | 3,595,878 |
def filter_seq(rec, direction = 5):
""" Applies all desired filters to SeqRecord
All settings from the config file should be applied here!
"""
hasStopCodon = '*' in str(rec.seq.translate())
if hasStopCodon:
global starSeqs
starSeqs += 1
return False
else:
... | a9b45dbfe74f890a6239a5153b44fbbd3f8c865b | 3,595,880 |
def write(file_path, new_contents):
""" Write the contents of a file. """
with open(file_path, "wb") as f:
return f.write(new_contents) | 023d90686d4d7033d9421b58df8f1de2cacd5338 | 3,595,881 |
def compute_statistics(datasetKaggle):
"""
Outputs various statistics of the Kaggle dataset
:param datasetKaggle: the input dataset formatted as a dictionary
:type datasetKaggle: dict
:return: dictionary with the processed information
:rtype: dict
"""
yesNoAnswer = 0
annotationsM... | 5d41592f45daa252d2a55c71193c1f022f4f53a2 | 3,595,882 |
def checkForNewMentees(db, mentorenFromServer, menteesFromServer, userListWP):
"""
prüfe welche Benutzer in die DB neu eingetragen werden müssen
"""
logText = ""
somethingChanged = False
for userWP in userListWP:
menteeNameWP = normalizeWpName(userWP['item'])
for userServ in menteesFromServer: # from our da... | c7832b49e6b2368040ae3fe7c77f5c4e7b0703cb | 3,595,883 |
def second_half():
"""
second half solver:
"""
# Generator A starts with 591 ; generator A uses 16807
# Generator B starts with 393 ; ; generator B uses 48271
# 2147483647
A, B = 591, 393
count = 0
for x in range (5000000):
while A % 4 != 0:
A = (A * 16807) % 2147... | 88f2ce5eb85c3e7d3207d021488eca920e00c29b | 3,595,884 |
import functools
def ks_exceptions(f):
"""Wraps keystoneclient functions and centralizes exception handling."""
@functools.wraps(f)
def wrapper(group, *args, **kwargs):
try:
return f(group, *args, **kwargs)
except ks_exception.EndpointNotFound:
service_type = kwargs... | eff35853192ec97abdea6e741790a29a31ee21a8 | 3,595,886 |
import html
def update_output(content: list[str, str], name: list[str, str], date: list[str, str]) -> html.Div:
"""Dash application callback - when a file is uploaded, then the relevant output is updated accordingly if both of
the uploaded files are of the right format and can be parsed normally.
Args:
... | 043b5e52e3b92afc0a36457d1397c075ec0d9172 | 3,595,887 |
def label(field):
"""Render foundation label."""
return {'field': field} | 8c9f9f8623b3e30a6d43220b7931354de5d42828 | 3,595,888 |
import requests
def admin_mc():
"""Returns a ManagementContext for the default global admin user."""
requests.post(CHNG_PWD_URL, json={
'newPassword': 'admin',
}, verify=False)
r = requests.post(AUTH_URL, json={
'username': 'admin',
'password': 'admin',
'responseType': ... | 8d51824284357d91abd0227a1dc5e9685b76f464 | 3,595,889 |
def filter_ice_border(ice_thick):
"""Sets the ice thickness at the border of the domain to zero."""
ice_thick[0, :] = 0
ice_thick[-1, :] = 0
ice_thick[:, 0] = 0
ice_thick[:, -1] = 0
return ice_thick | cbe448c2659cab832cb499765fb0d4ae8f95d751 | 3,595,890 |
def K_ricker_p(X,Y,sig=.6,Kamp=5):
"""
periodized kernel
"""
tot = 0
for n in range(-3,3+1):
for m in range(-3,3+1):
tot = tot + K_ricker(sqrt( (X+n*2*pi)**2 + (Y+m*2*pi)**2 ),sig)
#tot = tot + K_ricker(sqrt( (X+n*30)^2 + (Y+m*30)^2 ),sig)
return Kamp*tot | b607c3efb66d9fc4260847bba0aac0e239042e6d | 3,595,891 |
def validate(number):
"""Check if the number provided is a valid FIGI."""
number = compact(number)
if not all(x in '0123456789BCDFGHJKLMNPQRSTVWXYZ' for x in number):
raise InvalidFormat()
if len(number) != 12:
raise InvalidLength()
if isdigits(number[0]) or isdigits(number[1]):
... | ad326f9c506c45ad7ba65dd6ab8c904a4ebddcb9 | 3,595,892 |
def prompt_for_device(action_id, help_text, dispatcher, devices=None, offset=0):
"""Prompt the user to select a valid device from a drop-down menu."""
# In the previous implementation, we grouped the devices into subgroups by site.
# Unfortunately, while this is possible in Slack, the Adaptive Cards spec (M... | 530175669f3c7860fd8fba784f76f5b78bfdb956 | 3,595,893 |
import re
def split_with_offset(line, _len=len):
""" split string to tokens with offset """
words = re.split('[ ,.:!"|(){}\t\n]', line)
index = line.index
offsets = []
append = offsets.append
running_offset = 0
for word in words:
word_offset = index(word, running_offset)
word_len = _len(word)
... | 6299b4af840c5a7a2fe67ca00bc113fbdca982ec | 3,595,894 |
import secrets
def generate_random_base_64(length_in_bytes: object = 20) -> str:
"""
Generates a random BASE64 string, based on byutes as requested
:param length_in_bytes: number of bytes to randomly generate and convert to BASE64
:return: a random BASE64 string
"""
return secrets.token_urlsaf... | 5650d66a68f25a5d2f293867286ffc4bed0ae319 | 3,595,895 |
def _translate_to_jaeger(spans: Span):
"""Translate the spans to Jaeger format.
Args:
spans: Tuple of spans to convert
"""
jaeger_spans = []
for span in spans:
ctx = span.get_context()
trace_id = ctx.trace_id
span_id = ctx.span_id
start_time_us = _nsec_to_... | 8d3df21cfbe2206c499fbddf8a3e46aae55a84d0 | 3,595,896 |
def action(description, param, group=None, extract=None):
"""
装饰器函数,注册服务的元数据信息
@description 动作描述
@param 动作参数,形式:
{
"<phone>":{
"tip":"<参数描述>",
"default":"<默认值>"
}
}
@group 服务分组
@extract 结果提取,形式:
{
... | dc27c4c54300d678f7e158e01b967a4310062dd5 | 3,595,897 |
def sigmoid(x, a, b, L, shift):
""" a is the xvalue at the sigmoid midpoint """
y = L / (1 + np.exp(-b*(x-a))) + shift
return y | c9084473c1e52569c05b770eeb3ed7fecf17df71 | 3,595,898 |
def he_uniform(shape, random_state=None):
"""He uniform variance scaling initializer. It draws samples from
a uniform distribution within [-limit, limit] where limit is
sqrt(6 / fan_in) where fan_in is the number of input units in
the weight tensor."""
fan_in, fan_out = shape[0], shape[1]
limit ... | 9f860ae25fc83c9c54cb9583be7b0d305e14f9e8 | 3,595,899 |
def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising',
kpsh=False, valley=False, show=False, ax=None):
"""
Detect peaks in data based on their amplitude and other features.
Parameters
----------
x : 1D array_like
data.
mph : {None, number}, optional (default ... | 316d47d2f56c052539ca846715e6f6b5a8fb9f38 | 3,595,900 |
def create_masks(inp, tar):
"""
Encoder:
- encoder_padding_mask (self attention of EncoderLayer)
Decoder:
- look_ahead_mask (self attention of DecoderLayer)
- encoder_decoder_padding_mask (encoder-decoder attention of DecoderLayer)
- decoder_padding_mask (self attention of DecoderLay... | bfe2b1172452cba21634bb4f2e302d5baf75deb7 | 3,595,901 |
def is_missing(column):
"""
Determines whether the specified column has missing values.
:param column: The column
:type column: { pandas.series | list | tuple }
:return boolean: True | False
Usage:
======
>> is_missing(data['population'])
>> True
"""
... | a4cadb501fc7f66dc8680ba40fe4ee292815f53c | 3,595,902 |
from alibi_detect.cd import RegressorUncertaintyDrift as mc
from alibi_detect.cd import ClassifierUncertaintyDrift as mc
from alibi_detect.cd import KSDrift as mc
from alibi_detect.cd import MMDDrift as mc
from alibi_detect.cd import LearnedKernelDrift
from alibi_detect.utils.tensorflow.kernels import DeepKernel
from a... | 4a4833445bfeba8b05cf3ad667e091ab45dcbe86 | 3,595,904 |
def logout_view(request):
"""
This is used to save data in session after logout
"""
data = {}
PREFIX = "_user:"
for i in request.session.keys():
if PREFIX in i:
data[i] = request.session.get(i)
logout(request)
for i in data:
request.session[i] = data[i]
r... | 8a0d87fc27e363e488fcc8323d9de44e72f10f0e | 3,595,905 |
def _prepare_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
"""
Returns a prepared copy of the circuit for execution on the QCS Backend.
"""
circuit = circuit.copy()
_prepare_readouts(circuit)
return circuit | f982b13b6f825fb3ee8755576404820ada1e4afd | 3,595,906 |
def completeness_per_code(importance_matrix):
"""Compute completeness of each code."""
# importance_matrix is of shape [num_codes, num_factors].
return 1. - sp.stats.entropy(importance_matrix + 1e-11,
base=importance_matrix.shape[1]) | 9516f79e7c574aa9e113871a7c594c312ce30529 | 3,595,907 |
def null(t):
"""
null :: Foldable t => t a -> Bool
Source
Test whether the structure is empty.
"""
return Foldable[t].null(t) | ef3feb31659f348973a436593c3986829d92f6f0 | 3,595,908 |
def getReynolds(u: float, d: float, pbar: float, celsius: float) -> float:
"""
compute Reynolds
u: water velocity
d: hydraulic diameter
"""
Reynolds= getRho(pbar, celsius)*u*d/getMu(pbar, celsius)
return Reynolds | b1be931eea8e92b093fd6dee5f889ded1032f8b3 | 3,595,909 |
def user_counts_in(collection, geometry, skip_users=None):
"""
Returns user tweet counts for all tweets in a geometry.
Parameters
----------
collection : MongoDB collection
The collection of tweets.
geometry : GeoJSON-like geometry or list
The GeoJSON-like object representing th... | db432d1860af63d1bb2d171a0a4b09ffe5a7f6cf | 3,595,910 |
def _get_buffered_bounds(minlon, minlat, maxlon, maxlat, zoom=18, classic=True):
"""
minlon, minlat, maxlon, maxlat @float : Bbox limits;
zoon @integer : Square tile zoom level or hexagonal tile resolution;
classic @boolean : Whether to use classic square tiles or Uber H3 hexagonal ones.
Returns th... | 268671fda00eb389698fcfbfb68338c9805c476c | 3,595,911 |
from datetime import datetime
def extract_menu(menu_json: dict, date: datetime.date) -> str:
"""
Convert a menu dict to a prettified menu string
:param menu_json: A menu dict from the API
:param date: The date corresponding to the menu
"""
inner_menu = menu_json[-1]
acf = inner_menu.get("... | 2f9f6455781153c66345979d025fcd74bf58f6e8 | 3,595,913 |
from typing import List
from typing import Dict
def get_taxon_children(taxon_id: int) -> List[Dict]:
"""Get a taxon's children"""
logger.info(f'API: Fetching children of taxon {taxon_id}')
r = get_taxa(parent_id=taxon_id)
logger.info(f'API: {len(r["results"])} child taxa found')
return r['results'... | 7d0d74cf6ebbe37f5a843f3b7e49192aaf396642 | 3,595,914 |
def get_uniq_chars_list(num: int) -> list:
"""Creates a list of uniq characters"""
if num > 60:
raise Exception("Only up to 60 uniq characters supported, you provided:", str(num))
ret = []
for i in range(65, 65 + num):
ret.append(chr(i))
return ret | 35ed7c6af106c1d2864f188b9e2df5a6dc22d717 | 3,595,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.