content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_name_from_choice(value, choice):
"""選択肢から値によって、表示名称を取得する
:param value: 値
:param choice: 選択肢
:return:
"""
for k, v in choice:
if k == value:
return v
return None | 00055bc53aeba244a751f9dffe5c1fa2a7c71383 | 3,603,034 |
def getOperationCallback(c):
"""
Get the operation callback.
Returns
-------
`function`
"""
global OPERATION_CALLBACK
return OPERATION_CALLBACK | c9ec067146a2295a053350425ed50f8ba67d549c | 3,603,035 |
def winding_number(X, Y, Z, contour, x_spacing, y_spacing):
"""
This method computes the contour integreation around a positively oriented
square of corners A, B, C and D.
A (x_1, y_2) +---<---+ D (x_2, y_2)
| |
v ^
| |
... | 709163b58aabea7157b97a696927bffced6e1437 | 3,603,036 |
def view_forks(repo, username=None, namespace=None):
"""Forks"""
return flask.render_template(
"repo_forks.html", select="forks", username=username, repo=flask.g.repo
) | 02d4a8dbf17d888f3672c03b45895b21228bc758 | 3,603,038 |
def reduce_on_network(value, network):
"""
Reduces a list of addresses to only the addresses that match a given network.
:param: value: The list of addresses to filter on.
:param: network: The network to validate against.
:return: The reduced list of addresses.
"""
# normalize network vari... | e42c92d32168c977777de358497846358a5472f4 | 3,603,039 |
def clean_text(text, replace_entities=True):
"""Cleans the text in the same way as in data preprocessing part before training"""
if replace_entities:
spacy_text = nlp(text)
text_ents = [(str(ent), str(ent.label_)) for ent in spacy_text.ents]
text = text.lower()
# Replace entitie... | a5c30510a3349e1a0a93100e385606745e112f17 | 3,603,040 |
def prep_dataset():
"""Fetching the dataset """
def load_triu(S, P, dim):
return [extract_triu(s, dim) for s in S], [extract_triu(p, dim) for p in P]
folder = join("butadien", "data", "400")
dataset, molecules = make_butadien_dataset(
np.load(join(folder, "molecules... | 9ef15a2bdeffa2fefc333919ec8279eee5495688 | 3,603,042 |
def var_series(get_var_series, n) -> list:
"""
:param get_var_series: func return random value
:param n: number of elements
:return: variation series
"""
l = []
for i in range(n):
l.append(get_var_series())
l.sort()
return l | 95400d8f3368d7777ed9bf6d1fb42bc06aa3f17d | 3,603,043 |
import torch
def one_hot_argmax(inputs, temperature, axis=-1):
"""Returns one-hot of argmax with backward pass set to softmax-temperature."""
vocab_size = inputs.shape[-1]
z = one_hot(torch.argmax(inputs, dim=axis), vocab_size)
soft = F.softmax(inputs / temperature, dim=axis)
outputs = soft + (z ... | 74a6289a10e5d0e75ceb0e6de74bd13250150a58 | 3,603,044 |
import requests
import html
def generate_token_holdings(n_clicks, address):
"""
Function takes in n_clicks and Ethereum address and outputs
images of the address's ERC20 token holdings
"""
if n_clicks == 0 or address is None:
raise PreventUpdate
else:
# App section title
... | c2f8f38f7a566291b55796a57dea1897abe82582 | 3,603,045 |
def _build_classification_specification(label, num_classes, collapse):
"""Returns a LinearSpecification for adversarial classification."""
# Pre-construct the specifications of the different classes.
eye = np.eye(num_classes - 1)
specifications = []
for i in range(num_classes):
specifications.append(np.co... | a9657c432792d03679a2ca895aab5fe125d9c0fd | 3,603,046 |
def get_prune_list(database=None):
"""Return triggers that will be pruned upon next full install
Args:
database (str, default=None): Only return results from this
database. Defaults to returning results from all databases
"""
installed = {
(model._meta.db_table, trigger.get_... | 6a0109aab43b0a3569bbc13dd726d61b29cf06a6 | 3,603,047 |
def delete_message(user, message_id, basecamp=0):
"""Return raw response data from deleting a message (ID: message_id)
using user (optionally at basecamp)"""
if basecamp:
location = user.basecamp_location
else:
location = user.location
params = [("accuracy", user.location.accuracy),
... | 0e12c9c5b0b73c940966187639e3dac79cb09499 | 3,603,048 |
from typing import List
def compute_distances(
query_feature: np.array, feature_dict: dict, method: str = "l2"
) -> List:
"""Computes the distance between query_image and all the images present in
feature_dict (query_image included)
Args:
query_feature: Features for the query image
... | c6bcfb6593248b90a499cefcb1a38a77b902a630 | 3,603,050 |
def get_img_channel_num(img, img_channels):
"""获取图像的通道数"""
img_shape = img.shape
if img_shape[-1] not in img_channels:
img_channels.append(img_shape[-1])
return img_channels | 0627cffbb3e80fddccc47a4cc8b697a59cdda077 | 3,603,051 |
def _CheckArguments(cmd, args_def, args):
"""Verifies the arguments using the argument definition.
Algorithm:
1. Abort with error if values specified by user but none expected.
1. For each argument in definition
1. Keep running count of minimum number of values (min_count)
1. Keep running co... | ed9fe8ca57d3eaf9f65b2aa9503beac1841a6b49 | 3,603,052 |
def count_spikes(in_fnames):
"""
count spikes
"""
num_pos = 0
num_neg = 0
nsamp = None
for h5file in in_fnames:
fid = tables.open_file(h5file, 'r')
num_pos += fid.root.pos.times.shape[0]
num_neg += fid.root.neg.times.shape[0]
# might be a problem if no spike... | c3b50b17042340334128f0d04ed46c5dbc2c76dd | 3,603,053 |
import pandas as pd
def keep_common_genes(rna_df, sig_df):
"""
Given two dataframes, eliminate all genes that are not present in both dataframes.
Both dataframes must be indexed with the same gene identifier
Inputs:
- rna_df: pandas df. Rows are genes (indexed by 'Hugo_Symbol') and columns are... | f934a351a8c5d8f158b33bb9233dbd62f9dd4c8a | 3,603,054 |
from typing import Tuple
from typing import Any
def get_record_command(client: Client, args: dict) -> Tuple[str, dict, Any]:
"""
Query attributes and relationship information for a specific record.
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
... | 9371bfa151b2f4254538e75c09bce440a9d9ea6a | 3,603,056 |
def circulate(number, lower, upper):
""" 数を範囲内で循環させる。
Params:
number = 数。
lower = 数の下限。
upper = 数の上限。
Returns: 循環させた数。
"""
if lower <= number <= upper:
return number
elif number < lower:
return circulate(upper + lower + number + 1, lower, upper)
e... | 382b82768cc170b27b810c54d0ce753277d1a6f4 | 3,603,058 |
import json
def connect_to_websocket(ws_endpoint, start_request):
"""
returns a successful websocket connection which we can use to start reading in data
args:
- ws_endpoint: your infura project websocket, will look something like
- start_request: a dict of the first thing to send to the infura we... | 827cb56384cfdc494f8968f08d60247058bb4021 | 3,603,059 |
from typing import Callable
from typing import Union
def vpnn(input_dim: int = None,
n_layers: int = 1,
n_rotations: int = 1,
theta_initializer: str = 'uniform',
t_initializer: str = 'uniform',
bias_initializer: str = 'uniform',
output_dim: int = None,
us... | e0f69e35aa627961e2cb3e21ba46ce7e5aef0017 | 3,603,060 |
import binascii
def to_hexstring(string):
"""
Convert Bytes or ByteArray to hexadecimal string
:param string: Variable to convert to hex string
:type string: bytes, bytearray, str
:return: hexstring
"""
string = normalize_var(string)
if isinstance(string, (str, bytes)):
try:... | aeb7a3abc6f88bbe54900d614f2cbe1bf7f471dc | 3,603,061 |
def get_subs(url: str) -> int:
"""Получает количество подписчиков"""
user_id = calculate_raw_account_id(url)
account_type = calculate_account_type(url)
if account_type == 'Сообщество':
subs = get_group_subs(group_id=user_id)
else:
subs = get_account_subs(user_id)
return subs | f7ace521885af7a35f7d094f53e3e91942bd639b | 3,603,062 |
from unittest.mock import patch
def patch_bond_token(
enabled: bool = True, return_value: dict | None = None, side_effect=None
):
"""Patch Bond API token endpoint."""
if not enabled:
return nullcontext()
if return_value is None:
return_value = {"locked": 1}
return patch(
... | 6ffd6e9168a8a41d760788a688c8f67a2c69377a | 3,603,063 |
def clarifai_analysis(image_url, tag_limit=10):
"""
Given an image url return the tags as predicted by the Clarifai API.
"""
res = clarifai_model.predict_by_url(image_url)
return [e['name'] for e in res['outputs'][0]['data']['concepts']][:tag_limit] | 1c390deb04408c025ac713a08703af813aebe816 | 3,603,064 |
def thread_only():
"""
A decorator that checks if the command
is being ran within a Modmail thread.
"""
async def predicate(ctx):
"""
Parameters
----------
ctx : Context
The current discord.py `Context`.
Returns
-------
Bool
... | adec39350f096926e9ab8c5622aa6e5c9dd79570 | 3,603,065 |
from typing import Union
import types
def wal_magneto_conductance(
fields: Union[float, np.ndarray],
l_phi: float,
traces: np.ndarray,
lengths: np.ndarray,
surfaces: np.ndarray,
cosjs: np.ndarray,
) -> Union[float, np.ndarray]:
"""Compute the magneto conductance using precomputed trajector... | 21debc934619cbe7bc71f3ae10a606081333a282 | 3,603,066 |
def auto_str(cls):
"""Auto generate string representation of the object.
Args:
cls: Class for which to generate the __str__ method.
"""
def __str__(self):
return "%s(%s)" % (
type(self).__name__,
", ".join("%s=%s" % item for item in vars(self).items()),
... | 71a95cfeecb00146898656a0150d97fc346ddad3 | 3,603,067 |
def instantiate(process_id: int, customer_category: str) -> dict:
""" Returns either a or b
:param process_id: specify process
:param customer_category: specify customer category
:return: 'a' or 'b'
"""
instantiation_dict = controller.instantiate(process_id, customer_category)
return instan... | 07308761898efd61ef723b945a73a15ed8c2daf9 | 3,603,069 |
import json
def _jsonToDict(json_file):
"""Reads in a JSON file and converts it into a dictionary.
Args:
json_file (str): path to the input file.
Returns:
(dict) a dictionary containing the data from the input JSON file.
"""
with open(json_file, 'r') as fid:
dout = json.loa... | 6e4b5996d6aaf2982012c6c2f135d7876ee5b3ca | 3,603,070 |
from bigflow import schema_pcollection
def _transform_schema_pcollection(pcollection):
""" 内部函数 """
return schema_pcollection.SchemaPCollection(pcollection) | 2bec989359e42625d76c6b7a5380c3f36095ba60 | 3,603,071 |
from typing import Type
from typing import Callable
def parametrized_test_case(cls: Type[TestCase]) -> Type[TestCase]:
"""Decorator for TestCase to enable use of parametrize decorator on its test methods"""
def test_wrapper(test: Callable, **kwargs):
"""Create test executor"""
def test_executo... | a05e0685e61ef2019ea3a7d6ce9d425f78c2b16f | 3,603,072 |
def get_image_patch(cam, rgb_img, target_category=None, threshold=0.5):
"""
Get the important part of the image
"""
input_tensor = preprocess_image(rgb_img)
# You can also pass aug_smooth=True and eigen_smooth=True, to apply smoothing.
grayscale_cam = cam(input_tensor=input_tensor)
grayscal... | eef7311e4c4e3bb8fd00e329b0c4802dc0dde5a3 | 3,603,073 |
def get_cfg_set(flag_dict, default_dict):
"""Get a yacs CfgNode object with default values for my_project."""
# Return a clone so that the defaults will not be altered
# This is for the "local variable" use pattern
cfg_set = create_cfg_set(flag_dict, default_dict)
return cfg_set | 3e73ecd0cfba25a82eb3f6f04650ae3246f0afb4 | 3,603,074 |
def get_pull_requests_by_label(repo: "Repository", label: str) -> list["PullRequest"]:
"""获取所有带有指定标签的拉取请求"""
pulls = list(repo.get_pulls(state="open"))
return [pull for pull in pulls if label in [label.name for label in pull.labels]] | e93c9bedcc568b97e04166b5db1fe933315fc255 | 3,603,075 |
def check_checksum(tmpfile, version):
"""
Creates a SHA512 checksum for the downloaded update package.
:param tmpfile: dowloadad update package
:param version: version numberof update
:return: the two checksums
"""
# download SHA file:
response2 = myurlopen.open('{}/DSR-{}-sha512.sha'.fo... | 2026a9e083915c3347dd788cded086b351778d78 | 3,603,076 |
import collections
def get_ha_regions(reference = None, max_distance = None):
"""
Get hand-authored sectors, optionally in distance order around a reference point
Args:
reference: Optional, position or System/Sector-like object. If provided, returned sectors will be ordered by distance from this point
... | 36b6954be46414587383823e1cb7a27a85bad985 | 3,603,077 |
def _convert_output_type_range(img, dst_type):
"""Convert the type and range of the image according to dst_type."""
if dst_type not in (np.uint8, np.float32):
print('Error,The dst_type should be np.float32 or np.uint8')
if dst_type == np.uint8:
img = img.round()
else:
img /= 255.... | 535cf7a898bf54b28f96beac97ec30c3c5b233ad | 3,603,078 |
def get_mesh_shape(mesh, shape_index = 0):
"""
Get the first mesh shape, or one based in the index.
Args:
mesh (str): The name of a mesh.
shape_index (int): Usually zero, but can be given 1 or 2, etc up to the number of shapes - 1.
The shape at the index will be returned.
... | 80d4819dd470198dd36dc4ea609a9354a7e0a944 | 3,603,079 |
def _matches_app_id(app_id, pkg_info):
"""
:param app_id: the application id
:type app_id: str
:param pkg_info: the package description
:type pkg_info: dict
:returns: True if the app id is not defined or the package matches that app
id; False otherwise
:rtype: bool
"""
... | 4d6cd0d652a2751b7a378fd17d5ef7403cfdc075 | 3,603,080 |
def db(x, *, power=False):
"""Convert *x* to decibel.
Parameters
----------
x : array_like
Input data. Values of 0 lead to negative infinity.
power : bool, optional
If ``power=False`` (the default), *x* is squared before
conversion.
"""
with np.errstate(divide='ign... | e3de5c46c76738bd197ccd467afa917e0018b622 | 3,603,081 |
from robflask.service import service
def download_file(group_id, file_id):
"""Download a given file that was perviously uploaded for a submission.
NOTE: At this point, the user is not authenticated for file downloads to
allow download in the GUI via browser redirect.
"""
with service() as api:
... | a759c44d6e459c96ee40d72bd0b8c168020e21f4 | 3,603,082 |
def rivers_by_station_number(stations, N):
"""Returns a list of the first N (river name, number of stations) tuples with the greatest number of stations.
Params:
stations - list of stations to be filtered \n
N - number of tuples to show \n
Pulls river name & list of stations by river fr... | 4916dc5f9724cef4502499937892d5b34cb5a36e | 3,603,083 |
def gcd(a, b):
""" Return the greatest common divisor of a and b.
:Input:
* a -- an integer
* b -- an integer
:Output:
* an integer -- the gcd of a and b
Examples:
>>> gcd(97,100)
1
>>> gcd(97 * 10**15, 19**20 * 97**2)
97L
... | 90ee10a78e3902f3e82cc2996b17b347bb792974 | 3,603,084 |
def recv_all_chunks(sock, payloadsize, timeout=None):
"""read a bytearray payload from tcp socket"""
current_timeout = sock.gettimeout()
if current_timeout != timeout:
sock.settimeout(timeout)
recvbuf = bytearray()
mark = 0
while mark < payloadsize:
recv_size = min(CHUNKSIZE, pay... | 57b54515777c36a81f81e0d9ec0257b1f64783c3 | 3,603,085 |
def create_mechs(param_dict):
"""Create mechanisms from parameter dictionary. It should be a dict of
dict like: {name: {'gbar': gbar_quantity}} except for passive conductance
`pas`, which must have {'g': gpas_quantity, 'e': epas_quantity}
Returns: a dict of {name: ephys.Mechanism}
"""
ret = {}
... | 19faf0ea33ed24cc6090c6ebf5ec3854ef307957 | 3,603,086 |
import re
from datetime import datetime
import click
def switch_vendor(
ip,
credentials,
return_error=False,
):
"""Get a switch vendor. First try lookup from cache, then from the switch.
Args:
ip: Switch ip
credentials: Switch credentials
return_error: If True, raises requ... | b42dcbd89356c885819a58ed9dac6ba457117a19 | 3,603,087 |
def quad_pvinfo(tao, ele):
"""
Returns dict of PV information for use in a DataMap
"""
head = tao.ele_head(ele)
attrs = tao.ele_gen_attribs(ele)
device = head['alias']
d = {}
d['bmad_name'] = ele
d['pvname_rbv'] = device+':BACT'
d['pvname'] = device+':BDES'
d['bmad_f... | b35e04d78d419673afbc0711f9d454e01bc1dd5d | 3,603,088 |
import collections
def flatten(d, parent_key='', sep='.'):
"""
based on https://stackoverflow.com/a/6027615/1324730
:param d:
:param parent_key:
:param sep:
:return:
"""
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinsta... | a76717f301d053632e0759b7689829fc786cd598 | 3,603,089 |
def decimate(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#decimate"""
return filter(stream, decimate.__name__, *args, **kwargs) | 5c72e22e3ad9f48f3eebfde53a8601e2e31213d7 | 3,603,090 |
import csv
def parse_sample_template(input_file):
"""
Parse the TSV file and return data objects to run def.
@param input_file:
@return:
"""
line_num = 0
options_dictionary = defaultdict(str)
sample_dictionary = defaultdict(list)
index_file = list(csv.reader(open(input_file), delim... | b662174886c178db7f9e886cf932b1398e9c77d3 | 3,603,091 |
def load_pkl(file_path):
"""
Load pyleecan object from pkl file
Parameters
----------
file_path: str
file path
Returns
-------
obj: Pyleecan object
"""
with open(file_path, "rb") as file_:
# file is a group
obj = load(file_)
return obj | e5ff7de738d369623342b43d4fb35e84e16492f4 | 3,603,092 |
from typing import Callable
from typing import List
def min_weight_simple_path_greedy(
graph: nx.Graph,
n: int,
weight_fun: Callable[[nx.Graph, List], float] = path_weight):
"""A greedy algorithm that tries to find a simple path consisting of n
nodes in the given graph, with minimal to... | 2d0b0d02abdd045932a9dae1f565f1412f18ae6d | 3,603,095 |
from typing import List
from typing import Callable
def check_sso_permissions(permissions: List[str]) -> Callable:
"""Проверяет права на уровне пермишенов юзера."""
def decorator(func: Callable) -> Callable:
@wraps(func)
async def wrapper(request: Request, *args, **kwargs): # noqa: ANN201
... | 8e5cdbfc1014b5ed4ef819ae129b2c460124581b | 3,603,096 |
def makeup(formula, multiplier=1, sum=False, count_zero=False, messages=True):
"""
Python wrapper for the makeup() function in CHNOSZ.
Parse a formula into a dictionary of elements and their counts.
Parameters
----------
formula : str or list of str
Chemical formula or a list o... | 99e0289168a1eb6f9aa329d252f565d9b7a6c5fd | 3,603,097 |
from typing import Optional
from typing import Tuple
from typing import cast
import torch
def rollout_mujoco_env(
env: gym.wrappers.TimeLimit,
initial_obs: np.ndarray,
lookahead: int,
agent: Optional[mbrl.planning.Agent] = None,
plan: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, np.ndarray,... | efdf50263147f85497cb36c7c196e3485d528b53 | 3,603,098 |
def chunkit(it, size):
"""
Chunk an iterator <it> into pieces of <size>.
>>> list(chunker('ABCDEFG', 3))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
"""
iterable = iter(it)
return iter(lambda: list(islice(iterable, size)), []) | 45c7842f1ef1512238f7137cff53df09303b96b6 | 3,603,099 |
from pathlib import Path
def select_file(start_path=config['data_saving']['h5file']['save_path'], save=True, ext=None):
"""Save or open a file with Qt5 file dialog, to be used within an Qt5 loop.
Usage::
from pymodaq.daq_utils.daq_utils import select_file
select_file(start_path="C:\\test.h5"... | 64dfa3bf7dff4caa46725fb2e0d140c84dd4700d | 3,603,100 |
import json
def fix_hardprof_str(hardprof):
"""Fixture for a hard profile string"""
return json.dumps(hardprof) | 7cf08fceb561ebadcb44d6b13bcb7ad52198934d | 3,603,102 |
import logging
def eval_policy(policy, rng, state, model, test_ds, epoch):
"""Eval for a single epoch."""
batch_metrics = []
policy = flax.jax_utils.unreplicate(flax.jax_utils.replicate(policy))
# Function is recompiled for this specific policy.
test_ds = util_fns.get_iterator(test_ds)
for batch in test... | 5dcac82776a6671960d7500621409dcec17edb44 | 3,603,103 |
def Imp(x, y):
"""Return True if X implies Y
Performs a bitwise comparison of identically positioned bits
and sets corresponding bit in the output.
This amounts to the following truth table:
X Y Output
F F T
T F F
F T T
... | 68ac0456879d0aedec58988de2528bd9c6141941 | 3,603,104 |
def learning_edge_subset(g, num_pos, num_neg, remove_positives=False, seed=None):
"""
Returns a tuple of (num_pos positives edges, num_neg negative edges).
Selected edges are of kind g.graph['edge_key'], start at the node kind
specified by g.graph['source_kind'], and end at the node kind specified by
... | 603640e20b73062e3e09c8a59b655fb1b58f989c | 3,603,105 |
from typing import Callable
from typing import Set
from typing import Type
def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set):
"""
Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method).
"""
return all([
is_slice_contained(n... | 4a4af3af8ca5a3f969570ef3537ae75c17a8015c | 3,603,106 |
def code_flag(*args):
"""
code_flag() -> flags_t
'FF_CODE'
"""
return _ida_bytes.code_flag(*args) | 4de69be17407ef52aa1f04b3753ecd8d399133e4 | 3,603,107 |
def makecorr_tid(ptsfs=None,dmsfs=None,**kwargs):
"""Tau ID SF, pT-dependent."""
verb = kwargs.get('verb',0)
tag = kwargs.get('tag',"") # output tag for JSON file
outdir = kwargs.get('outdir',"data/tau") # output directory for JSON file
dms = [0,1,2,10,11]
ptbins = kwargs.get('bins',[20.,25.,30... | d3e56c2e92bbcc12ffec8b452cc4d73a0bae0343 | 3,603,108 |
from typing import Optional
def eval_acq_func(
acq_func: AcquisitionFunction,
X_test: MatrixLike2d,
return_type: Optional[str] = 'tensor'
) -> MatrixLike2d:
"""Evaluate acquisition function at test values
Parameters
----------
acq_func : 'botorch.acquisition.AcquisitionFunction'_
... | f688f2e1e9642ef92a8e108ae558c8732905aea9 | 3,603,109 |
from datetime import datetime
def add_datetime_to_page(pdf_page, font_size=12,
h_offset=1, v_offset=0, header=None,
include_date=False, include_micro=False,
datetime_formatter=None, position="nw",
char_w_factor=0.5, li... | b571511ac4240eaf07460d172d04a05049ba873d | 3,603,110 |
def bat_day(soc, temp, cycles, soc_low, soc_high, rate):
"""Model the degradation from the battery in one day. This was a test
model that isn't used in the finak optimizer
"""
# Maybe add some code to check inputs are OK range, etc.
DegCycle = bat_cycle(400, soc_low, soc_high, rate)**(cycles/400)
... | 6b1b80e60f3aee4a323da8ca2f4fbf71c7e2f7cf | 3,603,113 |
def count_consonant(token):
"""
Count consonants in a given token.
token: string to be counted for consonants
returns INTEGER
"""
count = 0
for tok in token:
if check_consonant(tok):
count+=1
return count | ef99ba94eead9bf0b234ffe05de795fb6a4e645e | 3,603,114 |
def enso_finder(dfoni):
"""From an ONI dataframe, this function returns an array with
1 for El Nino, -1 for La Nina and 0 for neutral years. It has been
established that if ONI persists over 0.5 or below -0.5 for 5
consecutive months it is an El Nino or a La Nina respectively.
Parameters
------... | d0c56bd19867cd83358cd9fde60200cb7abb602c | 3,603,115 |
def jensen_shannon_divergence(m1, m2):
"""
Jensen Shannon Divergence between two probability matrices/vectors
:param m1:
:param m2:
:return:
"""
m = 0.5*(m1+m2)
return (0.5 * kullback_leibler_divergence(m1, m)) + (0.5 * kullback_leibler_divergence(m2, m)) | f3c419705e436fbecdd684e332ae50013471a210 | 3,603,116 |
import copy
def get_aecg_intervals(
anns_df_in_ms: pd.DataFrame,
include_all_found_intervals: bool = False) -> pd.DataFrame:
"""Calculate intervals (e.g., PR, QT, ...) from annotations
All intervals are computed regardless of whether intervals are within or
outside of physiological ranges in ... | 6a3b477277d046309630886a7f9f18b16f1337b4 | 3,603,118 |
from pathlib import Path
import json
def save_local(data, file_path="tmp", file_name="tmp"):
"""Saves data locally."""
if file_path == "tmp":
file_path = "TMP/"
file_path = Path(file_path) / Path(file_name)
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
if isinstance(data, p... | 6d44ab5443b6ad45bbfa52a4360feb96fcad9948 | 3,603,119 |
import copy
def clustal_from_alignment(aln, wrap=None):
"""
Parameters
----------
aln
can be an Alignment object or a dict
wrap
sequence line width. Only available if sequences are
aligned.
Returns
-------
Returns a string in Clustal format
"""
if not ... | 49218ea82e58ead3740feda836b337577c77e7e2 | 3,603,121 |
import contextlib
import wave
def read_wave(path):
"""Reads a .wav file.
Takes the path, and returns (PCM audio data, sample rate).
"""
with contextlib.closing(wave.open(path, 'rb')) as wf:
num_channels = wf.getnchannels()
assert num_channels == 1
sample_width = wf.getsampwidth... | e5537450f91bea491a6aa6f35d98095386d6260c | 3,603,122 |
def smeft_evolve_leadinglog(C_in, scale_in, scale_out, newphys=True):
"""Solve the SMEFT RGEs in the leading log approximation.
Input C_in and output C_out are dictionaries of arrays."""
C_out = deepcopy(C_in)
b = beta.beta(C_out, newphys=newphys)
for k, C in C_out.items():
C_out[k] = C + b... | ea004f9a858b7f15e8aa4f62968390f50b3830e2 | 3,603,123 |
def move_column(df: pd.DataFrame, column: str, index=0) -> pd.DataFrame:
""" Moves the column with the given name to the given index, returns dataframe """
columns = list(df.columns)
if column not in columns:
logger.warning(f"move_column - column {column} is not present in df.columns: {df.columns}")... | c4da45fddf458944ecfa083859b1fff3a054c197 | 3,603,124 |
def getSkinFrictionBetweenPosition(data_outVTK, wall_outVTK, cord_choice, x_p0, x_p1, Npts, Uinf=None, Rhoinf=None):
"""
Compute the boundary layer thickness for *Npts* equally distributed between the 2 position
defined thanks to *x_p0*, *x_p1* and *cord_choice*. See the documentation of the function
g... | 0b97b52766f17edfc20a8272f2ab749167176e67 | 3,603,125 |
def xcor_redshift(spectra, template, sub=False, z1=0, z2=1, zstep=0.001):
"""Meaure the redshift of a spectra by cross correlating it
with a template
returns an array of correlation values
"""
zvalue=np.arange(z1,z2,zstep)
cc_arr=np.zeros(len(zvalue))
sflux=continuum_subtract(spectra... | ec766187f2de01a4f5c3353e196f478a6138f38b | 3,603,128 |
from re import match
def extrakey(key):
"""Return True if key is not a boring standard FITS keyword.
To make the data model more human readable, we don't overwhelm the output
with required keywords which are required by the FITS standard anyway, or
cases where the number of headers might change over ... | d4c36c3a5408d7056e55d5e67ebebe0b960e5b72 | 3,603,129 |
def get_number_rows(ai_settings, ship_height, alien_height):
"""Calculating how much rows of aliens can be fitted in screen"""
available_space_y = (ai_settings.screen_height - (3 * alien_height)
- ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return number_rows | 8ce25635ce0e68d1634d8c301a38090815aece03 | 3,603,130 |
def failed(err = adp_err_failed):
"""
the adp event callback failure result.
"""
return adp_result(err) | 60185225394c6360444e1f430f567d1f48e77164 | 3,603,132 |
def copy_structure(x, y):
"""
copy a new x which has same rotation and center as y
"""
n = min(x.shape[0], y.shape[0])
x1 = x[:n, :]
x2 = y[:n, :]
center1 = x1.mean(axis=0)
center2 = x2.mean(axis=0)
_, _, u = superposition(x2, x1)
xa = x1
# centering x
xb = x1 - np.tile(c... | 7d2bc4ed8c52048e63515c88092ca95e59ce3d68 | 3,603,133 |
def dropStudentsWithMinEvents(df,
saveDroppedAs=None,
studentId='BookletNumber',
blockId="BlockCode",
minEvents=3,
verbose=True):
"""Drop students with fewer than a c... | 8743c8e8f1d6c48b852013c53d9e9cf647a17fab | 3,603,134 |
def P(N_c, N_cb, e_t, t, A, N_bb):
"""
Returns the points :math:`P_1`, :math:`P_2` and :math:`P_3`.
Parameters
----------
N_c : numeric
Surround chromatic induction factor :math:`N_{c}`.
N_cb : numeric
Chromatic induction factor :math:`N_{cb}`.
e_t : numeric
Eccentri... | 82e444ca0e7563f061b69daedd82ff3fc771f190 | 3,603,135 |
def update_env(request):
"""
修改环境信息
处理的异常:
id类型错误
指定ID不存在
参数不合法
完整性约束
:param request: object, http request information
:return: status information
"""
@process_frame(request, 'POST')
@safe_response
def func():
env_id = int(request.POST['id'])
... | d1440faa0d933aec07a4a9b25f23a828f8f544d9 | 3,603,136 |
def create(*args, **kwargs):
"""Returns a NLDataset."""
return NLDataset(*args, **kwargs) | 10e926cf9f834cb03effd8c0cd57143b98a1a9af | 3,603,137 |
from datetime import datetime
def index(request):
"""Index page (with daily game scores).
"""
date = datetime.today().date()
return render_score_page(request, 'main/index.html', date, 'Home') | d21b0f8052935ce752a855bc90f565ed276b0785 | 3,603,138 |
import random
import string
def randomStringGenerator(length=13):
"""create random string ascii values"""
return ''.join(random.choice(string.ascii_letters) for _ in range(length)) | 5f4406f67d953cc1198ae79ae049dbd6e9b678b4 | 3,603,140 |
def resnet50(**kwargs):
"""Constructs a ResNet-50 model.
"""
model = SlowFast(Bottleneck, [3, 4, 6, 3], **kwargs)
return model | 19efaa10875f25ff5b26acb82f73d735c24dfa4f | 3,603,141 |
def schedule_conv1d_ncw(outs):
"""Schedule for conv1d_ncw
Parameters
----------
outs: Array of Tensor
The computation graph description of conv1d_ncw
in the format of an array of tensors.
Returns
-------
sch: Schedule
The computation schedule for the op.
"""... | 4dc517cd91e9bbf6881cc4f93940516731dc0a3b | 3,603,142 |
def crushmap_get_all(context):
"""get all crushmaps"""
return IMPL.crushmap_get_all(context) | 523ca4a90fda81f1aac5d9c3df70cf51f3f1e717 | 3,603,143 |
from typing import Dict
from typing import Any
import json
async def load_results(config: Config, document: Dict[str, Any]) -> dict:
"""
Load the analysis results. Hide the alternative loading from a `results.json` file.
These files are only generated if the analysis data would have exceeded the MongoDB s... | 963ea88c1e70f8a6cce23bc4f864fa285f576114 | 3,603,144 |
from typing import Dict
from typing import Any
def obj_blockwords_to_snake(obj: Dict[str, Any]) -> Dict[str, Any]:
"""Converts block cased keys in a dict like SETTLEMENTDATE into settlement_date"""
return {blockwords_to_snake_case(k): v for k, v in obj.items()} | b92d02a1e081113f00947f4bbdd9107e33ff3862 | 3,603,145 |
from typing import Callable
from typing import Any
def Depends(call: Callable, *, to_async: bool = False) -> Any:
"""
Used to provide extra information about a field.
:param call: callable that will be called when a dependency is needed for this field
:param to_async: whether to convert the callable ... | b689de3f0c8876cc73912a78bbf83630192c755b | 3,603,146 |
import copy
def FE_convert_all_object_columns_to_numeric(train, test=""):
"""
FE stands for Feature Engineering - it means this function performs feature engineering
######################################################################################
This is a utility that converts string columns to... | 67d398073b4ed5aae7db57c87ef72753902c9a77 | 3,603,149 |
def to_networkx(
nodes,
edges,
direction="oneway",
from_id_col="u",
to_id_col="v",
edge_id_col="id",
node_id_col="id",
force_bidirectional=False,
network_type=None,
retain_all=False,
osmnx_compatible=True,
):
"""
Creates a NetworkX.MultiDiGraph from given OSM GeoDataF... | b397fe54449dc49d152f42ef2da79836545bfb7c | 3,603,150 |
def paramvec_to_lmfit(paramvec, max_amp, max_fwhm=None):
"""Transform a Python iterable of parameters into a LMFIT Parameters object."""
ncomps = int(len(paramvec) / 3)
params = Parameters()
for i in range(len(paramvec)):
if 0 <= i < ncomps:
if max_amp is not None:
pa... | 80480a2266dcccae4cdb7532496dc83436833f0e | 3,603,151 |
def CGaussFilter_Image16_sigma2Size(dSigma):
"""CGaussFilter_Image16_sigma2Size(dSigma) -> vpl::tSize"""
return _ImageFilters.CGaussFilter_Image16_sigma2Size(dSigma) | 4150bc88e3a2164a5c9e796552cdaa251cc58f79 | 3,603,152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.