content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def parse_ndx(lines):
""" Parses a GROMACS ndx file.
:param lines: Iterable of strings.
:return: Dictionary with group names as key, list of 0-based atom indices as value.
"""
groups = dict()
lastgroup = None
thisvalues = []
for line in lines:
line = line.strip()
# skip comments and empty line... | aeca75ff4ec626e814336b327b11f942a46815b7 | 3,605,940 |
def duration_format(delta: float):
"""
Duration format
:param delta: seconds
:return: string representation: 1 days 1 hour 1 min
"""
if delta < 0:
delta = f'{int(delta * 1000)} ms'
elif delta < 60:
delta = f'{int(delta)} sec'
elif delta < 3600:
delta = f'{int(delt... | 4ea92191076281d2108066a85b2c8662024bdaaf | 3,605,941 |
from datetime import datetime
def isoformat(dt: datetime) -> str:
"""ISO format datetime object with max precision limited to seconds.
Args:
dt: datatime object to be formatted
Returns:
ISO 8601 formatted string
"""
# IMPORTANT should the format be ever changed, be sure to updat... | 679ce7aa71ab30e4c78a0953272c17f487714177 | 3,605,942 |
def ndcg_at_k(
rating_true,
rating_pred,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_prediction=DEFAULT_PREDICTION_COL,
relevancy_method="top_k",
k=DEFAULT_K,
threshold=DEFAULT_THRESHOLD,
):
"""Normalized Discounted Cumulative Gain (nD... | edcb1da897b218c720c868f597463569d6e06952 | 3,605,945 |
def _opt_to_mymessage(msg):
"""Transforms dictionary representation of the VkOpt message to the MeMessage obj.
Notes:
Document id of a VkOpt message isn't parsed and may only be -1.
Photos aren't documents (for some reason).
Message is forwarded if only it has attached forwarded message... | e0cd6ce735b175e08375d940820e862aa075ab62 | 3,605,947 |
def _xls_dslx_verilog_impl(ctx):
"""The implementation of the 'xls_dslx_verilog' rule.
Converts a DSLX file to an IR, optimizes the IR, and generates a verilog
file from the optimized IR.
Args:
ctx: The current rule's context object.
Returns:
DslxInfo provider.
ConvIRInfo provide... | 4a45b1392e8755218efc593cf3aa3bd9a10c52c9 | 3,605,948 |
def generate_X_df_from_descriptor_list(descriptor_list,
default_csv_paths,
col2remove = DEFAULT_INDEX_COLS,
**args,
):
"""
This function generates the combi... | 5c73bbb8d8a3c9621554cbf1efc6dd3746e0b540 | 3,605,950 |
def compile_template(line):
"""
Compile a template expression into a python function (like jsps, but way shorter)
"""
extr = []
def repl(match):
g = match.group
if g('dollar'): return "$"
elif g('backslash'):
return "\\"
elif g('subst'):
extr.a... | 68a275902d20f50c00597194c970237f6c86ae2e | 3,605,951 |
from typing import Optional
def _residual_star(
regular_expression: RegularExpression,
letter: Letter) -> Optional[RegularExpression]:
"""Residual computation, ``STAR`` case
"""
residual_inner = residual(regular_expression.inner, letter)
if residual_inner is not None:
return Re... | aa67c212f2ff063552ef1fd0f1629cf4ee2725b9 | 3,605,952 |
def evaluate_policy(env, policy, args, eval_episodes=1):
""" Runs policy for X episodes and returns average reward """
avg_reward = 0.
avg_episode_steps = 0
save_state = True
if save_state == True:
evaluate_episode_states = []
for _ in range(eval_episodes):
print('eval_episodes', eval_episodes)
obs = env.re... | 47ff74bf41949c78b5e141a34c617909c4347279 | 3,605,954 |
def get_dict(file_name):
"""
This function returns the english to french dictionary given a file where the each column corresponds to a word.
Check out the files this function takes in your workspace.
"""
my_file = pd.read_csv(file_name, delimiter=' ')
etof = {} # the english to french dictiona... | b86d21914c2b978909e7d88b0ca5e9d770a1dd05 | 3,605,955 |
from sklearn.utils import resample
def calc_bootstrap(fcs, obs, func, L, B=1000, bootstrap_range=[2.5, 97.5]):
"""
Calculates moving block bootstrap estimates for an
evaluation metric defined and calculated inside 'func' argument.
INPUT
fcs: forecasted time series
obs: ... | 90b4bcc57e6c337b5638008334e299bdfc70f13d | 3,605,956 |
def histeq(im,nbr_bins = 256):
"""对一幅灰度图像进行直方图均衡化"""
#计算图像的直方图
#在numpy中,也提供了一个计算直方图的函数histogram(),第一个返回的是直方图的统计量,第二个为每个bins的中间值
imhist,bins = histogram(im.flatten(),nbr_bins,normed= True)
cdf = imhist.cumsum() #
cdf = 255.0 * cdf / cdf[-1]
#使用累积分布函数的线性插值,计算新的像素值
im2 = interp(im.flatten... | 11f54f5440eadefa5bd03912d2e5f786eb2a7f29 | 3,605,957 |
def validate(obj, validator, name="object"):
"""Generic function"""
if not isinstance(validator, Validator):
raise TypeError("Not a validator.")
if hasattr(validator, 'validate'):
# Check to ensure that this hasn't looped back to this already
return validator.validate(obj, n... | 527f28f91694593571485ac1d8a828ac7d425906 | 3,605,958 |
def _recursive_namedtuple_convert(data):
"""
Recursively converts the named tuples in the given object to dictionaries
:param data: An object in a named tuple or its children
:return: The converted object
"""
if isinstance(data, list):
# List
return [_recursive_namedtuple_conver... | 292bc249b056c14eb1c700561d366ff4e6e64a10 | 3,605,959 |
def compute_crowd_performance(df_crowd_results, crowd_score_column, experts_score_column):
""" Function to evaluate the answers of the crowd at each posible crowd score threshold"""
rows = []
rows.append(["Thresh", "TP", "TN", "FP", "FN", "Precision", "Recall", "Accuracy", "F1-score"])
precision = 0.0
... | 8316f8af86f9cad7eccf3f2175d0c14e2fbb8e84 | 3,605,960 |
def series_key_from_name(name):
"""Get an ESeries from its name.
Args:
name: The series name as a string, for example 'E24'
Returns:
An ESeries object which can be uses as a series_key.
Raises:
ValueError: If not such series exists.
"""
try:
return ESeries[name... | c571a8975fadf4de14471a0b83157a06d2999080 | 3,605,961 |
def make_transform_sql2(sqlname, typefun, pyfun=None):
""" Makes a sql transformer that accepts two arguments.
sqlname: the name of the sql function.
typefun: a function that accepts a list of datatypes and returns a datatype.
numargs: the number of arguments accepted by this transformer.
pyfun: a python fun... | d2a2b02253670ea4cc7ea6d4ab67ea992c5869cd | 3,605,963 |
def _find_start(score_matrix, align_globally):
"""Return a list of starting points (score, (row, col)).
Indicating every possible place to start the tracebacks.
"""
nrows, ncols = len(score_matrix), len(score_matrix[0])
# In this implementation of the global algorithm, the start will always be
... | 361a1ea87ecf9bbef0950521ed0fdcfd70b7b608 | 3,605,964 |
def get_arguments_by_statement(statement: Statement, issue: Issue) -> dict:
"""
Collects every argument which uses the given statement.
:param statement: Statement which is used for query
:param issue: Extract information for url manager from issue
:rtype: dict
:return: prepared collection with... | faa7d60fa3d4ac073b6ff1cf9104d0f3ccd92299 | 3,605,965 |
def plot_fig(model_name, crypto_list: list, epoch: int, loss: list, acc: list):
"""
draw a figure for loss and acc
"""
cl = concat2str(crypto_list)
pic_name = model_name + '_' + cl
x = np.linspace(1, epoch, epoch)
plt.figure(figsize=(4.5, 5))
plt.subplot(211)
plt.plot(x, loss)
... | 3ebdf445862955c6a1f4f5ac7b3e710578e486bc | 3,605,966 |
def KLT(a):
"""
Returns Karhunen Loeve Transform of the input and the transformation matrix
and eigenvalues.
*** IN DEVELOPMENT ***
Ex:
import numpy as np
a = np.array([[1,2,4],[2,3,10]])
kk,m = KLT(a)
print(kk)
print(m)
# to check, the following should return... | 29ad1baebdb34f474a6a8fdfa89f188b7cc02edc | 3,605,967 |
def get_f1_score(precision, recall):
"""
Calculate and return F1 score
:param precision: precision score
:param recall: recall score
:return: F1 score
"""
return (2 * (precision * recall)) / (precision + recall) | e94dd20acac443be9856b9dbb43adf2ead2e0ba5 | 3,605,968 |
def bh2u(x: bytes) -> str:
"""
str with hex representation of a bytes-like object
>>> x = bytes((1, 2, 10))
>>> bh2u(x)
'01020A'
"""
return x.hex() | 8ab7bf9b536d13a1944e014ea83a4302917c2306 | 3,605,969 |
def chromAndPosSort(x, y):
"""
Comparison function for use in sort routines. Compares strings of the form
chr10:0-100. Sorting is done first by chromosome, in alphabetical order, and then
by start position in numerical order.
"""
xChrom = x.split("_")[-1].split(":")[0]
yChrom = y.split("_")[... | 27db2d05e918f1652ebf154c1004cfad112b5891 | 3,605,970 |
def vis_FasterRCNN_loss(self, scale_weight):
"""
Calculate the roi losses for faster rcnn.
Args:
-- self: FastRCNNOutputs.
-- scale_weight: the weight for loss from different scale.
Returns:
-- losses.
"""
return{
"loss_cls": self.vis_softmax_cross_entropy_loss_(scale_weigh... | 5832d7f28179085db939a7bd624e9ffb08461fe4 | 3,605,971 |
def simple_mask(model, init_fn,
masked_param):
"""Creates a mask given a model and numpy initialization function.
Args:
model: The model to create a mask for.
init_fn: The numpy initialization function, e.g. numpy.ones.
masked_param: The list of parameters to mask.
Returns:
A mas... | 053ed147fe780296de133e9d438127569609d3ed | 3,605,972 |
def word_dropout(tokens, dropout):
""" Randomly dropout tokens (IDs) and replace them with <UNK> tokens. """
return [constant.UNK_ID if x != constant.UNK_ID and np.random.random() < dropout \
else x for x in tokens] | d4a50bccef6e562bd4edb0320c6c5ecdb83fb4bc | 3,605,973 |
def createSimpleResourceMap(ore_pid, sci_meta_pid, data_pids):
"""Create a simple resource map with one metadata document and n data objects."""
ore = d1_common.resource_map.ResourceMap()
ore.initialize(ore_pid)
ore.addMetadataDocument(sci_meta_pid)
ore.addDataDocuments(data_pids, sci_meta_pid)
... | 8837d120804dc75330f8d50a1086a83dabd25059 | 3,605,974 |
import binascii
def crc32(data):
"""计算输入流的crc32检验码:
Args:
data: 待计算校验码的字符流
Returns:
输入流的crc32校验码。
"""
return binascii.crc32(b(data)) & 0xffffffff | ed8966e87070e4fb26e9468fb5ec1bc7b30ebcd1 | 3,605,975 |
def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
"""
Scale operator.
Putting scale and bias to the input Tensor as following:
``bias_after_scale`` is True:
.. math::
Out=scale*X+bias
``bias_after_scale`` is False:
.. math::
... | b68c737ebc0fb10dc43dc9d15b919705d2171555 | 3,605,976 |
def get_version_data(session, url, authenticated=None):
"""Retrieve raw version data from a url."""
headers = {'Accept': 'application/json'}
resp = session.get(url, headers=headers, authenticated=authenticated)
try:
body_resp = resp.json()
except ValueError:
pass
else:
... | b48550583286a7f3941a1ffd71c8129803ec077e | 3,605,977 |
def _select_relevant_files(api_type):
""" Select the folder related to the api_type
Exclude certain files and directories based on api_type
:param api_type: framework or plugin api
:return: The base file path for the api files to document
The list of files to exclude from api
"""
if api_... | fedd27d728aa7e164e709ca0cf5daa473de58927 | 3,605,978 |
from typing import Union
def datetime_to_string(
date: dt.datetime, date_format: str = "%Y-%m-%d %H:%M:%S"
) -> Union[float, str]:
"""Returns a string representation of a datetime object
Args:
date: dt.datetime the date
date_format: what is the format of the date? see datetime documentati... | 9dd7f8f6f53662cdaf6158b100658465893d286b | 3,605,979 |
import json
def request_game(
request: game_server_pb2.GameRequest
) -> game_structs_pb2.GameRequestResponse:
"""Request a game."""
handler = get_default_tictactoe_cache_handler()
# Set a random number seed based on the fractional second part
# of the timestamp. This makes it more reliable on hig... | 3263b33c557ccaf9448f63e4dc22bddbc878e41f | 3,605,980 |
from typing import List
from functools import reduce
def decode(obs: int, spaces: List[int]) -> List[int]:
"""
Decode an observation from a list of gym.Discrete spaces in a list of integers.
It assumes that obs has been encoded by using the 'utils.encode' function.
:param obs: the encoded observation
... | 6c3c1348776b7b164cf70a5bfa9da3e8b53a280f | 3,605,981 |
def anagram_solution_1(words):
""" Complexity O(n2)
If it is possible to “checkoff” each character, then the two strings must be anagrams
:param words: Tuple
:return: bool
"""
s1, s2 = words
still_ok = True
if len(s1) != len(s2):
still_ok = False
a_list = list(s2)
po... | 942ef7bb631bd803d89e71643e994505cb9b827a | 3,605,982 |
def allocation_shimen_wpp():
"""
Real Name: Allocation ShiMen WPP
Original Eqn: IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule Lower Limit , Water Right ShiMenLongTan WPP\ *0.387, IF THEN ELSE( ShiMen Reservoir Depth >=ShiMenReservoir Operation Rule Lower Severe Limit , Water Right Shi... | 3f489eec46527d59b305bcaced216c83e90ef6bc | 3,605,983 |
def bleached(source):
"""Render a string through the bleach library, caching the result."""
render_function = partial(bleach.clean,
tags=settings.BLEACH.allowed_tags,
attributes=settings.BLEACH.allowed_attrs)
return cached_render(render_function, s... | d734ae5d7997be878bf002c0e1fcba7516b9591b | 3,605,984 |
def cna(mac):
"""Builds a mock Client Network Adapter for unit tests."""
return mock.Mock(spec=pvm_net.CNA, mac=mac, vswitch_uri='fake_href') | 28ae759612d9b608b8288f627ac5d013914bbbd4 | 3,605,986 |
def product_from_hand(cards):
"""
Expects a list of cards in integer form.
"""
product = 1
card_symbols = []
i = 0
for n in cards:
product *= (n & 0xFF)
card_symbols.append(RANKS[i])
i += 1
return card_symbols, product | 74eb8df29ed20c886745619d712595c975132f2e | 3,605,987 |
def most_popular(request, username=None, search_key=None):
"""
Shows the most popular search results.
The ``username`` kwarg should be the ``username`` field of
``django.contrib.auth.models.User``. The ``search_key`` can be any string.
Template::
``saved_searches/most_popular.html``
Co... | 79e505270a783e188a913113f67bcecc5ae5814f | 3,605,988 |
from typing import List
from typing import Dict
from typing import Any
def replace_foreign_columns_with_local_columns(foreign_columns: List[ForeignColumnPath],
fks_by_name: Dict[str, Any], src_table: str
) -> List[ForeignCol... | 58346be57c746f1db136c50f786a4c2d4e95667d | 3,605,989 |
from typing import Dict
from typing import List
def split_data(data: pd.DataFrame, parameters: Dict) -> List:
"""Splits data into training and test sets.
Args:
data: Source data.
parameters: Parameters defined in parameters.yml.
Returns:
A list containing split... | a91b8bde176280635f4474e9965a54d6b7fb8cd0 | 3,605,990 |
def enum_pair():
"""
枚举所有的对子
"""
return [(cards2str(pair), w) for w, pair in enumerate(CARD_PAIR)] | 1f993b9014250d71185da3d34d89394b398e75ab | 3,605,991 |
def _normalize_type(i_type: str) -> str:
"""Normalize AXI4-Stream names"""
if i_type in _m_type:
i_type = 'INITIATOR'
elif i_type in _s_type:
i_type = 'TARGET'
else:
raise ValueError("Unknown BUSINTERFACE type {}".format(i_type))
return i_type | 35e9ecc7d3f8bab6d0d996e8ec47382dc7113999 | 3,605,992 |
def gt(input, other, out=None):
"""Compute *input* > *other* element-wise.
Parameters
----------
input : dragon.vm.torch.Tensor
The input tensor.
other : dragon.vm.torch.Tensor, number
The other tensor.
out : dragon.vm.torch.Tensor, optional
The optional output tensor.
... | 978937f5917a9a7917f5d033815d6f17476dea43 | 3,605,993 |
def do_train(config, plugin_factory=None):
# type: (MyNLUConfig, Optional[PluginFactory]) -> Tuple[Trainer, Interpreter, Text]
"""Loads the trainer and the data and runs the training of the specified model."""
# Ensure we are training a model that we can save in the end
# WARN: there is still a race co... | 053262e4678fd40f1adfc84682911cf073fc521e | 3,605,994 |
def remove_invalid_rows(data):
"""
Removes invalid rows from data.
A row is invalid if
* the text is NaN
* session_id is 0
"""
progress = progressbar.ProgressBar(max_value=data.shape[0]).start()
invalid_utterances = []
for i, row in data.iterrows():
if type(r... | 7b409669261289784d0df49702d653318cea4a17 | 3,605,995 |
def load_feature_extractors(rt=None, wp=None, ap=None, slm=None, lm=None) -> 'tuple':
"""
Load feature extractors depending on command line options.
For now we have the following extractors:
* RuleTable
* WordPenalty
* ArityPenalty
* StatelessLM
* KenLM
:return... | 675728cddce5687df44db7d022594dc27aad3675 | 3,605,996 |
def oneYear(token="", version="stable", filter="", format="json", **timeseries_kwargs):
"""Rates data
https://iexcloud.io/docs/api/#treasuries
Args:
token (str): Access token
version (str): API version
filter (str): filters: https://iexcloud.io/docs/api/#filter-results
form... | a11973e8af3b02f5c89bd9a8c527a990f61d7d7d | 3,605,997 |
from typing import Union
from typing import Optional
from typing import List
from typing import Dict
from typing import Any
from typing import Tuple
def sharpen(
image: Union[str, Image.Image],
output_path: Optional[str] = None,
factor: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
... | 9c9c59638c23761ac3ff9612cb9c256cbde8b24a | 3,605,998 |
def get_unlisted_addons():
"""Load the unlisted addons file as a set."""
return set_from_file('validations/unlisted-addons.txt') | 1519dddfb84ee6f3e600fe044b4431e524fd1c38 | 3,605,999 |
def get_worksheet_data_block(sheet, coords, expand=None):
"""Get a data block.
Args:
sheet (Sheet): The worksheet containing the data block.
coords (str): The inclusive coordinates of the data block.
expand (str): Optionally expand the range of values.
Returns
(dict): A dicti... | bc6aed4c9bc300b4120cad3b9e47ac892d996579 | 3,606,000 |
def find_footer(messages, number=1):
"""
Returns the footer of a DataFrame of emails.
A footer is a string occurring at the tail of most messages.
Messages can be a DataFrame or a Series
"""
if isinstance(messages, pd.DataFrame):
messages = messages["Body"]
# sort in lexical order ... | c885f871c04a308bf0be0a549ddbe510055e57b0 | 3,606,002 |
def complexity_tolerance(
signal, method="maxApEn", r_range=None, delay=None, dimension=None, show=False
):
"""**Automated selection of tolerance (r)**
Estimate and select the optimal tolerance (*r*) parameter used by other entropy and other
complexity algorithms.
Many complexity algorithms are bu... | cfba5d97ab4eb91883a4cb4d4d57b7d480f5e99a | 3,606,003 |
def min(X, s):
"""
Compute element-wise min(x,s) assignment for sparse or dense matrix.
:param X: The input matrix.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil, dia
or :class:`numpy.matrix`
:param s: the input scalar.
:type s: `float`
"""
if sp.isspmatrix(X... | 3f7a7a71435bacb18b70fd4aaaa64eb231b81fd3 | 3,606,004 |
import re
def empty_template(pattern, template):
"""F() to extract all {words} from the template using pattern"""
template = re.sub(pattern, "{}", template)
return template | b62592a449ce38971cc81083928cfd034be1984b | 3,606,005 |
def generate_public_authfile(vo_data, legacy=True):
"""
Generate the Xrootd authfile needed for public caches
"""
if legacy:
authfile = "u * /user/ligo -rl \\\n"
else:
authfile = "u * \\\n"
id_to_dir = defaultdict(list)
public_dirs = []
for vo_name, vo_data in vo_data.v... | 3e9900c6fdcb4a5781019839ceb51b8041ec2b8c | 3,606,007 |
def unpack_params(handler):
"""Unpacks the queries from the body of the header
Parameters
----------
handler: tornado.web.RequestHandler
Handler for incoming request to collection
Returns dict
-------
Unpacked query in dict format.
"""
if isinstance(handler, tornado.web.... | 965a7b6568e30e9ab7b1dc4adb4d2c253910a917 | 3,606,008 |
import torch
def aug(image, preprocess):
"""Perform AugMix augmentations and compute mixture.
Args:
image: PIL.Image input image
preprocess: Preprocessing function which should return a torch tensor.
Returns:
mixed: Augmented and mixed image.
"""
ws = np.float32(
np.random.dirichlet([arg... | 988a3aa08df883f32ed9227be8bc430f61dc71e6 | 3,606,009 |
import shlex
def _cropped_pdf_page(pdf_path, page):
"""Extract a page of the specified PDF as an _SVG."""
lines = _run_command(
[
"inkscape",
"--pdf-poppler",
f"--pdf-page={page}",
"--query-width",
"--query-height",
"--export-pla... | 18bd92a24abfd95c840d720ddd2356ba997dcec1 | 3,606,010 |
def _get_auth_token(request: Request, auth_type):
"""Extract the Bearer token from the 'Authentication' header"""
header = get_authorization_header(request)
split = header.split()
if len(split) == 0:
return None
elif len(split) != 2 or split[0].lower() != auth_type:
raise exceptions.... | 0f239cd4f19dfb8e88d4108f2434ab10257e571d | 3,606,011 |
import pickle
def read_pickle(file_name):
"""Reload the dataset"""
with open (file_name,'rb') as file:
return pickle.load(file) | 404d578de68db726e14f6214aed3e512a9abf947 | 3,606,012 |
import re
def duration_to_seconds(duration):
"""
Convert duration string to seconds
:param duration: as string (either 00:00 or 00:00:00)
:return: duration in seconds :class:`int` or None if it's in the wrong format
"""
if not re.match("^\\d\\d:\\d\\d(:\\d\\d)?$", duration):
return Non... | 25340e85fdc2db03eaa65aba60a158f951da389a | 3,606,013 |
def returnTF():
"""Load the image transformer."""
tf = trn.Compose(
[
trn.Resize((224, 224)),
trn.ToTensor(),
trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
return tf | a4f4bcda309d5b65bc622ef87ee10cf1292187de | 3,606,014 |
def get_list_items(name, index, index_end='', to_num=False, to_str=False):
""" Get one or any of list items
Args:
name (`list`): list data
index (`int`): number of index for list to get
index_end (`int`): end number of index for list to get
to_num (`bool`): fl... | f96acb0f1cc661fb66774eaeeb4842cb96ff77c2 | 3,606,015 |
import torch
def h_normal_gpytorch(s):
""" Entropy of a normal distribution """
return torch.log(s * (2 * np.e * np.pi) ** 0.5) | bd43d55cfeb92d1e908f9c23fcc6bc2bf29ed7e0 | 3,606,016 |
def get_task(task_id):
""" Get one task
:param task_id:
:return: task
"""
global tasks
try:
task_id = int(task_id)
except ValueError:
return None
return tasks[task_id] if task_id in tasks else None | e011db4998083f148ab2aaa4ca10ebc7dd3b0298 | 3,606,017 |
def zscore(col: Series) -> Series:
"""Calculates zscore for column"""
zscore_col = (col - col.mean()) / (col.std(ddof=0))
return np.trunc(zscore_col * 100) / 100 | cd98e76c6012bac45ed65e45c4f37df7ef946c5a | 3,606,018 |
from typing import Set
from typing import Tuple
import socket
import time
def ping(addresses: Set[str]) -> Set[Tuple[str, float, headers.ip]]:
"""
Send an ICMP ECHO REQUEST to each address
in the set addresses. Then return a set which
contains all the addresses which replied and
which have the cor... | 721b7c79a22d101d2bed19b2f559b3b4a19e443e | 3,606,020 |
def flatten_tests(test_classes):
"""
>>> test_classes = {x: [x] for x in range(5)}
>>> flatten_tests(test_classes)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> test_classes = {x: [x + 1, x + 2] for x in range(2)}
>>> flatten_tests(test_classes)
[(0, 1), (0, 2), (1, 2), (1, 3)]
"""
te... | 332b98ab499ff53ba974d51ac862e7015f616e64 | 3,606,021 |
def count_wallpapers(arg):
"""
Counts all the wallpaper associated with given category
creates list of all the links in the pagination of given wallpaper category
:param arg: search query from user
:return: wallpaper count and list of links
"""
try:
main_html = send_request(arg)
... | cc78ebe2060f59c68994fb709ade6104954e0d43 | 3,606,022 |
def clues_too_many(text: str) -> bool:
""" Check for any "too many connections" clues in the response code """
text = text.lower()
for clue in ("exceed", "connections", "too many", "threads", "limit"):
# Not 'download limit exceeded' error
if (clue in text) and ("download" not in text) and (... | 0d105985d7eb032668ad8b08704658846da725b7 | 3,606,023 |
def get_maestral_pid(config_name: str) -> int | None:
"""
Returns the PID of the daemon if it is running, ``None`` otherwise.
:param config_name: The name of the Maestral configuration.
:returns: The daemon's PID.
"""
return maestral_lock(config_name).locking_pid() | 0ab25f7a6f99bbd037eacfcb91c4f944208ab55a | 3,606,024 |
def FZStaeckel(u,v,pot,delta): #pragma: no cover because unused
"""
NAME:
FZStaeckel
PURPOSE:
return the vertical force
INPUT:
u - confocal u
v - confocal v
pot - potential
delta - focus
OUTPUT:
FZ(u,v)
HISTORY:
2012-11-30 - Written - Bovy ... | 898214f2255ae94ae3f0691b8d85984ff9993dfb | 3,606,025 |
import re
def sent_from_wordlist(elements):
""" Convert a list of word_texts to a spacy sentence """
text = " ".join(elements)
text = re.sub(r"[\n\s]+", " ", text)
text = re.sub(r"\s+([,\.\!\?])", r"\1", text)
sent = next(islice(nlp(text).sents, 0, None))
return (None, None, sent.root.lemma... | 0633cf9462744af612873f719a4a80a337f99d2d | 3,606,026 |
import pathlib
def create_feed_data(directory, height, width):
"""
Create batchs of feeding data by going directly
to the images. Labels are generated by the file
structure.
INPUT: Directory of images. The directory should
be structured as below:
Parent
|- Training
| |- Label
... | d0620a3a1947460df27df9744494d080977d0dfa | 3,606,027 |
def pyUtils():
"""
Exposing Spark PythonUtils
spark/core/src/main/scala/org/apache/spark/api/python/PythonUtils.scala
"""
return _curr_jvm().PythonUtils | 2456401a9a4c25670e74e1df72c346ccdccb6be7 | 3,606,028 |
import warnings
def flops(show=True):
"""
Decorator function which measures the FLOPs used by the decorated function and prints it to
stdout. The function relies on the availability of the PAPI_DP_OPS event. If the kernel does
not support this event, a warning is printed and the function is simply exe... | 22fd158e163232851eadbbce03a3a486c359c260 | 3,606,029 |
def lime_predictor(explainer, dict_mapping, feature_names, data_point, predictor):
"""
Creates an Explanation on given datapoint
Arguments:
explainer: lime object, A Lime explainer created while training
dict_mapping: dict, mapping dictionary of categorical columns
feature_names: lis... | 7ffcc38dd40c769d1e232ccdc888029683e02943 | 3,606,030 |
def _Candlestick(kwargs):
"""股价蜡烛图"""
df = kwargs.get('df')
limit_start = kwargs.get('limit_start')
limit_end = kwargs.get('limit_end')
data = df.loc[limit_start:limit_end, :]
hovertext = _get_date_hovertext(data)
trace = go.Candlestick(
x=np.arange(data.shape[0]),
open=data.... | 1116616a8332e4d28a4c6ecb7931451fbda7f805 | 3,606,031 |
def k_boltzmann(dlstr):
"""Return value of Boltzmann constant in current DL units
Args:
dlstr (string): "ev" | 'kJ" | "kcal" | "k" | "internal"
Returns:
Boltzmann constant in the relevant units
"""
key = dlstr.lower()
label = Label("k_b", "Boltzmann Constant", None)
if key == "... | 85dfbdc12d6b2d5d6e5dfd8e7efb871736f13a6e | 3,606,032 |
def get_srr(text, all=False, sep=None):
"""
Returns a list of SRR data.
"""
logger.info(f"searching ENA for {text}")
url = ENA_REPORT
if all:
fields = get_ena_fields()
else:
fields = [
'run_accession',
"sample_accession",
'first_public',
... | 0f8c5e54aee5e2f1cea2bbfeff61a94f36fbfdc5 | 3,606,033 |
import functools
def rgetattr(obj, attr, *args):
"""Get attribute recursively.
Nested attribute is specified as `a.b`.
"""
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.')) | 6e69a6730f6f3a5e305d90c77a7895379244d43c | 3,606,034 |
def prepare_job_links(soup):
"""Prepare list of job links from header titles"""
job_links = []
results = soup.select('div[class*="jobsearch-SerpJobCard unifiedRow"]')
for i in range(len(results)):
job_link = f"{URL_PREFIX}{results[i].h2.a['href']}"
job_links.append(job_link)
return j... | a0da2618ba91734855268bab8ff435f384613ed7 | 3,606,035 |
def load_vocab(filename: str):
"""
load vocabulary from given dataset file
"""
with open(filename, 'r', encoding='utf-8') as f:
text = f.read().strip().split('\n')
text = [word.split(' ') for word in text]
vocab_dict = {word[0]: word[1:] for word in text}
vocab_dict = {k: [float(d) f... | fe11e129439173ba13ca276c788c0f27053f5e6a | 3,606,036 |
def HomeHandler():
"""
"""
return render_template('index.html') | 2b77c1ab00c67792512789db3f55788a0589d31d | 3,606,038 |
def BinomialBinArray(pvalues, x_ar, bin_num, use_zeros = True):
"""
Inputs:
Outputs:
"""
pmax = np.amax(pvalues)
pmin = np.amin(pvalues)
bin_width = (pmax-pmin)/float(bin_num)
bin_n = np.zeros(bin_num, dtype=float)
bin_mean = np.zeros(bin_num)
bin_error = np.zeros(bin_... | eba52ed5922f801da1a3e2567ad7741a9ed7fe2b | 3,606,039 |
import re
def normalize_whitespace(s: str) -> str:
"""Convert all whitespace (tabs, newlines, etc) into spaces."""
return re.sub(r"\s+", " ", s, flags=re.MULTILINE) | 6d8b65bcdca9838aa0f4d16d158db5d2218cbf24 | 3,606,041 |
from typing import Counter
def joint_refine_all(hpo_data, final_loci, cs_val=0.95, cnv_cov=None,
jac_cutoff=0.8, ncase_dict={}, cs_merge_buffer=200000):
"""
Wrapper to call joint_refinement() on all multi-HPO clusters
"""
for members in final_loci.values():
n_members = l... | ea88c99bae1e169fd5bfe4983f6b64be8f4cfe95 | 3,606,042 |
import errno
def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
names = net_io_counters().keys()
ret = {}
for name in names:
try:
mtu = cext_posix.net_if_mtu(name)
isup = cext_posix.net_if_flags(name)
duplex, speed = cext_posix.net_if_duplex... | a8f599d75aff1baca753e11498a48bd6f5bcc50a | 3,606,044 |
def ode(Y,T,K):
"""
Ordinary differential equation system for a pendulum.
"""
th, om = Y
DYDT = [om, -g/l*np.sin(th)-K*(om)]
return DYDT | b80d60892f486778c341628dd8060ecfac351392 | 3,606,045 |
def tmp_notebook(tmp_path):
""" make an empty python notebook on disk
"""
notebook = nbformat.v4.new_notebook()
notebook.metadata["kernelspec"] = {"name": "python3"}
nb_path = tmp_path / "Untitled.ipynb"
nb_path.write_text(nbformat.writes(notebook))
return nb_path | 4837235eb77b7fe6a5bd00301994f28a06b88da8 | 3,606,046 |
def CTW_cc_nubar():
"""Fixture for forming a neutrino with charged-current CTWInteraction"""
return Particle(particle_id=Particle.Type.antielectron_neutrino,
vertex=[100, 200, -500], direction=[0, 0, 1], energy=1e9,
interaction_model=CTWInteraction,
in... | 140fd50cbe83d3999741992eb437d9d0ceeb52e7 | 3,606,047 |
def job_delete(jobId):
"""
Delete a saved job
RouteParams:
jobId: the id of a job
GetParams:
account: an account
user: a user
code: the new code for the job
Returns:
a json representation of a job
"""
account = request.form['account']
user = requ... | 682911a05622b0d7b2e8d4cd810ed5854dc8512b | 3,606,048 |
def set_dist_names(spc_dct_i, saddle):
""" Set various things needed for TSs
"""
dist_names = []
if saddle:
dist_names = []
mig = 'migration' in spc_dct_i['class']
elm = 'elimination' in spc_dct_i['class']
if mig or elm:
dist_names.append(spc_dct_i['dist_info... | cb5f72b3d00efb8272f7b5012f776bbd63e38634 | 3,606,049 |
def sort_and_save(summary_dfs):
"""
Takes the summary dfs that merely need sorted. Uses info from the sort_no_further_analysis var to know which dfs to
process
:param summary_dfs: dict of dfs holding summaries on the answers to each question
:return: a better ordered dict of dfs holding summaries on... | bfaec2f793e86904c0cf85cb60cbc07a7eff0416 | 3,606,050 |
import scipy
def applyMedianFilter(obj):
"""Performs a median filter on the array with the specified diameter"""
diameter, array = obj
return scipy.signal.medfilt2d(array, diameter) | 9e3b4c1c4750e3f054e512f2fe93580280614abd | 3,606,051 |
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection,
pool_recycle=FLAGS.sql_idle_timeout,
... | 4e621924d1325e2c152bec158cc3caa92c8e5c9e | 3,606,052 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.