content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def traj_loader(parm, crd, step=1000):
"""
Load and return a trajectory from mda universe.
Input parmater file, coordinate file, and loading step interval (default=1000).
"""
traj = mda.Universe(parm, crd, in_memory=True, in_memory_step=step, verbose=True)
return traj | e5347664507ceb4eb83fa80bd5b7f5f3232ae90d | 49,134 |
def index(request: HttpRequest) -> HttpResponse:
"""Render the index page."""
# Build a list of race options (year/type/state/district/csv)
null = None
options = [['2004', 'pres', 'National', 'atlarge', '2004_pres_us.csv'],\
['2006', 'senate', 'Virginia', 'atlarge', '2006_senate_va.csv']... | e4ef4e976a5e68b116245ed9c26b5ef9fe948ea8 | 49,135 |
from functools import reduce
import operator
def mapping_dicts(lucid_tokens_df, corpus_df, lucid2pascal):
"""return id2word, mapping LUCID id's to words, and id2pic, mapping LUCID id's to
sets of picture names and pic2id, mapping picture names to tokens"""
id2word = dict(zip(lucid_tokens_df['id'], lucid_t... | 9e9ba806eb0a99610aac33c246a76b4394388dfd | 49,138 |
def test_log_append_true(tmp_path, container_runtime_or_fail):
"""run 5 times, append to log each time"""
def side_effect(*_args, **_kwargs):
return None
repeat = 5
new_session_msg = "New ansible-navigator instance"
log_file = tmp_path / "ansible-navigator.log"
cli_args = [
"an... | d3380aeb7bfadbc68ee12000328ac317386cfd28 | 49,139 |
def load_config(path):
"""
"""
def scan(l):
if l == "":
return (NL, l)
elif l[0] == '#':
return (COMM, l)
b = l.find('=')
if b < 0:
return (COMM, l)
key = l[:b].strip()
if key == "":
return (COMM, l)
ret... | 9f53fea839bb8425102d11f15eec76fb3ec56f1a | 49,140 |
def dataset(client):
"""Create a dataset."""
with client.with_dataset(name='dataset') as dataset:
dataset.authors = {
'name': 'me',
'email': 'me@example.com',
}
return dataset | 4f77cd30c58ad74e48280be193f4dd30b0fb5584 | 49,141 |
from .detection import default_conv, default_nnw
def update_SE_kwargs(kwargs={},
kwargs_update={'DETECT_THRESH':3,
'ANALYSIS_THRESH':3}):
""" Update SExtractor keywords in kwargs """
SE_key = kwargs.keys()
for key in kwargs_update.keys():
... | 97742337731568ec2114a2008e2b2fb5a24dd6ae | 49,142 |
from datetime import datetime
def actual_time(ts) -> str:
""" Takes in a UNIX timestamp and spits out actual time as a string without microseconds. """
dt = datetime.datetime.fromtimestamp(float(ts)/1000.0)
dt = dt.replace(microsecond=0)
return str(dt) | c554df608f7933ec08aaee9589582015d0f4612d | 49,143 |
def classify_vector(in_x, weights):
"""
最终的分类函数,根据回归系数和特征向量来计算 Sigmoid 的值,大于0.5函数返回1,否则返回0
:param in_x: 特征向量,features
:param weights: 根据梯度下降/随机梯度下降 计算得到的回归系数
:return:
"""
# print(np.sum(in_x * weights))
prob = sigmoid(np.sum(in_x * weights))
if prob > 0.5:
return 1.0
ret... | 30834f3730116666780753da9aeda25092139954 | 49,144 |
def pd_resample(pd_object, rule, *args, **kwargs):
"""
对pandas中的resample操作,根据pandas version版本自动选择调用方式
:param pd_object: 可迭代的序列,pd.Series, pd.DataFrame或者只是Iterable
:param rule: 具体的resample函数中需要的参数 eg. 21D, 即重采样周期值
:return:
"""
if g_pandas_has_resampler:
"""pandas版本高,使用如pd_object.resam... | df9fe26589144d4aeb92d34b8b45cc54262305c9 | 49,145 |
def clone(pc):
"""
Return a copy of a pointcloud, including registration metadata
Arguments:
pc: pcl.PointCloud()
Returns:
cp: pcl.PointCloud()
"""
cp = pcl.PointCloud(np.asarray(pc))
if is_registered(pc):
force_srs(cp, same_as=pc)
return cp | ecb0c3fb99942c406df06963b4638d407191af08 | 49,146 |
def strategy_best(cookies, cps, history, time_left, build_info):
"""
The best strategy that you are able to implement.
"""
build_items_list = build_info.build_items()
max_cps_div_cost_item = None
for idx in range(len(build_items_list)):
if build_info.get_cost(build_items_list[idx]) <= co... | 77999615f6cde7b7c18c2234e62553db759633be | 49,147 |
import re
def autofocus_field(field, *args, **kwargs):
"""
Add the 'autofocus' attribute to an input tag.
Usage::
{% autofocus_field field field_class='col-md-12' %}
Extra args and kwargs are passed to ``bootstrap_field``.
"""
return mark_safe(re.sub(
'<input', '<input autof... | 03da61b7f1409d9b19d4512c50e245195efb31c1 | 49,149 |
def get_buildrequire_pkgs_from_build(build, session, config):
"""
Function which queries koji for pkgs whom belong to a given build tag
of a koji build and paires rpms with their respective package.
:param dict build: build information returned by koji.
:param koji.ClientSession session: koji conne... | c580ca1c2144b8d04dde5e9d3938bfd5e66c6e72 | 49,150 |
def SceneShadowManagerPrepareAddShadowManager(builder, shadowManager):
"""This method is deprecated. Please switch to AddShadowManager."""
return AddShadowManager(builder, shadowManager) | 368c5f7381e7b0cab5cf7339db057ae512959731 | 49,151 |
import joblib
def load_scaler(scaler_filepath):
"""Load MinMaxScaler save object.
Parameters
----------
scaler_filepath : pathlib.PosixPath
Path to MinMaxScaler save object
Returns
-------
sklearn.preprocessing._data.MinMaxScaler
"""
return joblib.load(scaler_filepath) | cf65787614f2bcfce6df3f32da81e551e8376805 | 49,152 |
import scipy
def get_sender_sparse_date_info(email_ids_per_sender,
senders_idx_to_mid_dic,
df_info):
"""
gets time info as one-hot encoding in sparse matrix
idx matching mids as in idx_to_mids in rows and days in columns
idx_to_mids for e... | 1f6a648d09bd8963195fb861ff71aaa7c01adaf9 | 49,153 |
import grp
def is_existing_group(group_name):
"""Asserts the group exists on the host.
Returns:
bool, True if group exists on the box, False otherwise
"""
try:
grp.getgrnam(group_name)
return True
except KeyError:
return False | 8831281684107d9f4c4511cb4cf3493494269650 | 49,154 |
from typing import Dict
from typing import Any
def unpack_struct(struct: Tag, keydict: Dict[str, Any]) -> Dict[str, Any]:
"""Parse a tag with children, if tag is not arrayof....
Parameters
----------
struct: bs4.Tag
Section of returned tree to be parsed as a complex type
Returns
----... | 246a4057f3a46df7cbab321c2a2e75d0f7721a0c | 49,155 |
def server_error_error():
"""
500错误处理
"""
return server_error('Server error') | d61b9f7fee80a0efa7636eb6c83bb94642a7973f | 49,156 |
def get_c2d_topic_for_subscribe(device_id):
"""
:return: The topic for cloud to device messages.It is of the format
"devices/<deviceid>/messages/devicebound/#"
"""
return _get_topic_base(device_id) + "/messages/devicebound/#" | cd62f848d09df4026bce8a716c9dda486c1cb403 | 49,157 |
import re
def re_search(text: str, expression: str) -> bool:
"""
Test regex match. This method is comparatively
very slow and should be avoided where possible.
"""
return re.search(expression, text) is not None | e86daa552a3f769f46bca794b9d2a4587cbed11c | 49,160 |
def GenerateStochasticBlockModelWithFeatures(
num_vertices,
num_edges,
pi,
prop_mat = None,
out_degs = None,
feature_center_distance = 0.0,
feature_dim = 0,
num_feature_groups = None,
feature_group_match_type = MatchType.RANDOM,
feature_cluster_variance = 1.0,
edge_feature_di... | 6f8ce55f920d1f46a77b895b5d580fb0ef5dd5c8 | 49,162 |
def median(lst):
"""
Get the median value of a list
Arguments:
lst (list) -- list of ints or floats
Returns:
(int or float) -- median value in the list
"""
n = len(lst)
if n < 1:
return None
if n % 2 == 1:
return sorted(lst)[n//2]
else:
... | b6b7eefdf63490e35e74063995cabd38f4c12089 | 49,164 |
def fit_taus(zi, Kti, iter_max=42, eps_max=1e-6, plot=False, quiet=False):
"""
Fit the ASHRAE pseudo-spectral coefficients tau_b & tau_d given a
set of elevation z and clear sky index Kt values.
"""
# Need at least two points
if len(Kti) < 2:
if not quiet:
print("Warning: In... | 855947ba033e4656c74603f59cdf54cab423bf27 | 49,165 |
def e_log() -> str:
"""Check next update content."""
with open(file=TMERGE_LOGFILE, encoding='utf-8') as log_file:
content = log_file.read()
return content | a3b2338c8b1cc12d9d35d42aea02d1188944910b | 49,167 |
def read_ferre_headers(path):
"""
Read a full FERRE library header with multi-extensions.
:param path:
The path of a FERRE header file.
Returns:
libstr0, libstr : first header, then list of extension headers; headers returned as dictionaries
"""
try:
with open(path, "r")... | 454881c30cf372039d539b511bd2df51acd79cef | 49,168 |
import glob
def load_images(folder_path, img_size=32, num_channels=3, dtype=np.float32, normalize=True):
"""Loads images from a folder.
Args:
folder_path: Path to a folder with png images.
img_size: Size of the image.
num_channels: Number of channels in the output image.
dtype... | 1b0c624230e93d7b995cc7876237ff7801e68ca3 | 49,169 |
def orop(funeval, *aa):
""" Lazy version of `or' """
for a in aa:
if funeval(a): return True
return False | f8ed7f88bbbd894cddf5d56a015ba7fe554342e4 | 49,170 |
def get_value(kind, index):
""" Retrieve a previously stored value """
data = retrieve(kind, index)
if data is not None:
data = data["value"]
return data | 6378ad989cd7751b8579f0aec19aac0d689fe424 | 49,171 |
def load_labels():
"""Load the image label file and transform it to the desired format"""
y_labels = pd.read_csv("../data/y_labels/train_v2.csv")
y_labels["tags"] = y_labels["tags"].apply(lambda x:x.split(" "))
y_labels["image_name"] = y_labels["image_name"].apply(lambda x: x + ".jpg")
UNIQUE_LABELS... | 346ee8a1625d7f5d766b3850850403b6a9aebd4e | 49,172 |
import tqdm
def get_QBias(mobile, bc, sss=[None, None, None], d_cutoff=8.0,
prec=3, norm=True, plot=True, warn=True, verbose=True, **kwargs):
"""
Get QValue for formed bias contacts.
.. Note :: selection of get_QBias() is hardcoded to sel='protein and name CA'.
Reason: bias contacts ... | 1242a9a13cc8be663f61bc089d8bc85cba51e4e8 | 49,173 |
import weakref
def weakref_props(*properties):
"""A class decorator to assign properties that hold weakrefs to objects.
This decorator will not overwrite existing attributes and methods.
Parameters
----------
properties : list of str
A list of property attributes to assign to weakrefs.
... | 4ae42fc4e2dccbb7193a377e122f96c4f7d5112d | 49,174 |
def edge_total_communicability(G, u, v, t=1, tol=1e-7, maxit=50):
"""
Computes the edge total communicabilities of edge :math:`(u, v)`.
If nodes :math:`u` and :math:`v` are the :math:`i^{th}` and :math:`j^{th}` nodes of the graph, the edge total communicability of :math:`(u, v)` is given by the product of ... | 97d36e5110040407b318d0e1b5446a546e1ecbc2 | 49,175 |
def kernel_eligible_pair(X, Y):
"""
Validate X and Y if those are eligible to compute karnel
Parameters
----------
X: np.ndarray (n, d) of real (-inf, inf)
n: number of samples in X
d: number of features
if a 1d array (d,) is given, it's automatically
converted ... | 81fb5dd493231c35ae0b99366ee5ee3aa7a60352 | 49,176 |
import requests
def getBadges( steamId ):
"""
:param steamId: int
:return:
{
"player_xp": int,
"player_level": 13,
"player_xp_needed_to_level_up": int,
"player_xp_needed_current_level": int,
"badges":
[
... | 6bc8d0df5d27e4c53aa4235ddc25d4a99fe5f0c3 | 49,177 |
def detect_objects(interpreter, image, threshold):
"""Returns a list of detection results, each a dictionary of object info."""
set_input_tensor(interpreter, image)
interpreter.invoke()
# Get all output details
boxes = get_output_tensor(interpreter, 0)
classes = get_output_tensor(interpreter, 1... | 04f216efaf1b60c27aaae824bf1d6c18e9f309c9 | 49,178 |
def convert_dict_float_to_dec(dict):
"""
Given a dict, take any values that is a float number and convert it to decimal so it can be written to DDB.
:param dict:
:return: a new dict object with all floating number values replaced with Decimal representation.
"""
new_dict = {}
for key in dict... | 504d03a0bbbf873e7b7122788ab933e1f8fab00e | 49,179 |
from pathlib import Path
def lglob(self: Path, pattern="*"):
"""Like Path.glob, but returns a list rather than a generator"""
return list(self.glob(pattern)) | eba1b9d6300a1e1aca5c47bedd6ac456430e4d89 | 49,180 |
def simulationStep(step=0):
"""
Make a simulation step and simulate up to the given second in sim time.
If the given value is 0 or absent, exactly one step is performed.
Values smaller than or equal to the current sim time result in no action.
"""
if "" not in _connections:
raise FatalTr... | 8ab8cb739d4cc7901525c9230211ee98c56d0cb2 | 49,181 |
def transformer_low_resource(configs):
""" Configuration for training transformer on low-resource datasets.
This is equivalent to configuration of IWSLT'14 De2en in fairseq.
"""
configs = transformer_base_v2(configs)
# model configurations
model_configs = configs['model_configs']
model_co... | d8d840dad1b1153dc617ce99e51d8900cc0a0fd8 | 49,182 |
import platform
def handle_credential_command(command, credentials, target_location='.'):
"""Function that executes a git command that requires credentials.
Parameters
----------
command : str
String command to run
credentials : list of str
The user's entered git remote credential... | 0a70507ce9d465452dde862a205a75d044af9a9c | 49,183 |
def _get_setting(name, default=None):
"""Get the Sublime setting."""
return sublime.load_settings('Preferences.sublime-settings').get(name, default) | 72b6e8d4cc878f056d4e9910a9e40a82bc1354ed | 49,184 |
def vuln_delete_multiid_route():
"""delete multiple vulns route"""
form = MultiidForm()
if form.validate_on_submit():
Vuln.query.filter(Vuln.id.in_([tmp.data for tmp in form.ids.entries])).delete(synchronize_session=False)
db.session.commit()
db.session.expire_all()
return '... | 102e73625bcbf281766a54f2385c189d85128267 | 49,186 |
def operator_enum_converter(operator: OperatorEnum):
"""
Function for internal use. Used to translate an OperatorEnum into a string representation of that operator
"""
if operator == OperatorEnum.Equals:
return "=="
elif operator == OperatorEnum.GreaterThan:
return ">"
elif operator == OperatorEnum.GreaterTh... | 8e8a6e23b32784d69d772bd28aa2d2a9f08317ff | 49,187 |
def put_using_index_tuple(a, index_tuple, v):
"""Replaces specified elements of an array with given values.
This function is very similar to put(), but takes a tuple of index arrays rather than a single index array.
The indexing works like fancy indexing:
a[index_tuple] = v
Parameters
----... | 14386dcf7238df544b78d3b5a8bcb960fd852d71 | 49,188 |
def ins_to_dict(ins, option=None):
"""
Convert instance object to dictionary
ex)
ins_to_dict(A, {
'cascade': 3, # 如果子项没有cascade,则使用父项-1,如果cascade不大于0,则不对象属性
'recursion_value': '{...}'
# 'include': ['a1'], # 只有include中的字段才会返回,不区分值是否是对象,include的优先级>exclude
# 'exclude': ['... | f4454e182410cd599b51072b252a8cb58a283508 | 49,189 |
def expandFile(filename, no_stdin_warning=False, **kwargs):
"""Get a filename, expand the text in it and print it.
args: (see `processToList`)
no_stdin_warning (bool) : If True, print short message on stderr
when the program is waiting on input from
... | cfc2cc4b1acfbc7e76dd26b044c0104e9ad8fb3c | 49,190 |
def unflatten(flattened: dict) -> dict:
"""
Unflattens a dictionary
:param flattened: Flattened dictionary
:return: Unflattened dictionary
"""
unflattened = {}
for key, value in flattened.items():
parts = key.split(".")
d = unflattened
for part in parts[:-1]:
... | 1a54f4289cb77e5d6355f91e6a26477bce420c6c | 49,191 |
def col2asset(col, assetPath, scale=30, region=None, create=True, **kwargs):
""" Upload all images from one collection to a Earth Engine Asset. You can
use the same arguments as the original function ee.batch.export.image.toDrive
:param col: Collection to upload
:type col: ee.ImageCollection
:param... | 6e2586232d5811ef0babd655e5b9bb022eea69c0 | 49,192 |
from pathlib import Path
import requests
def upload_notebook(notebook: Path, enable_annotations: bool, enable_discovery: bool, nbss_url: str):
"""
Upload a notebook file to an nbss instance with
"""
upload_url = f"{nbss_url.rstrip('/')}/api/v1/notebook"
with open(notebook, 'rb') as f:
retu... | 5247fe18a1a95076e7c6e35879fa438486a1ce65 | 49,195 |
def compat_assert_outcomes():
"""
Use RunResult.assert_outcomes() in a way that's consistent across pytest
versions.
For more info, on how/why this is inconsistent between pytest versions:
https://github.com/pytest-dev/pytest/issues/6505
"""
def _compat_assert_outcomes(run_result, **kwargs... | 63fe48f7fc3c8b56f296df19ce9c297169e4163a | 49,196 |
from typing import Sequence
def parse_attrs(attrs):
"""Parse an attrs sequence/dict to have tuples as keys/items."""
if isinstance(attrs, Sequence):
ret = [item.split(".") for item in attrs]
else:
ret = dict()
for key, value in attrs.items():
ret[tuple(key.split("."))] = value
return ret | 15779e14fbdb9783d91732aa3420ccb18ee6c620 | 49,197 |
from typing import List
import random
def continuous_setting(agents: List[Agent]) -> Allocation:
"""
Algorithm 3.
Approximation algorithm of the optimal auction for a continuous cake.
Complexity and approximation:
- Requires at most 2n2 values from each agent.
- Runs in time polynomial in n.
... | 0e6cc75e82557f39c5ad5d5e2fd225c0329cdf33 | 49,198 |
def plot_on_sphere(xyz_data, normalize=False):
"""
plots each row of an nx3 numpy array on the surface of a sphere
to do this we first normalize each row
"""
#make 3d figure
fig = plt.figure()
ax = plt.axes(projection='3d')
#build up a sphere
u, v = np.mgrid[0:2*np.pi:200j, 0:np... | 0b803cecb3a625a2746c4db08de8141dcf51f32b | 49,199 |
from .record import decode
def get_flatten_name(fea):
""" Get names of feature after flatten.
Parameters
----------
fea: list or str
return value of get_itervar_feature or a line of logfile
Returns
-------
feature_names: Array of str
"""
feature_name = {
"_attr_"... | 102bc6e780f0312f22e812b47ed4c76c6d940140 | 49,200 |
def change_style(style, representer):
"""
Change the style of a particular YAML representer.
"""
def new_representer(dumper, data):
scalar = representer(dumper, data)
scalar.style = style
return scalar
return new_representer | 1365e8ed6ad8a237404aa3bc2274ab7e8137e50b | 49,201 |
import copy
def move_piece(board, player, piece, initial, final, jumpFlag=False, jumpPosition = None):
"""
Moves a piece on the board and modifies the cell values as required.
"""
assert ((jumpFlag) and (jumpPosition != None)) or ((not jumpFlag) and (jumpPosition == None)), "Jump position not passed b... | 9f1e546e4b27034a4c26e6456be8ba69685532e2 | 49,202 |
def sponge(N:bytearray, d:int):
"""
Sponge construction for hash functions.
N: Thing to hash \n
d: size of hash wanted \n
return bytearray
"""
def pad(N, r):
iN = bm.bytes_to_int(N)
lN = int.bit_length(iN)
# Number of 0 to add
b = (r - ((lN + 3) % r)) % r
... | 0e9a9e03b52fcc2838cdc638948722a82213c08a | 49,203 |
import threading
def track_event(tracking_id, category, action, uid=None, label=None, value=0,
software_version=None, timeout=2, thread=True):
"""
Record an event with Google Analytics
Parameters
----------
tracking_id : str
Google Analytics tracking ID.
category : str... | 8fb4df7da593abe296c0b524b1ab18c3df460b46 | 49,204 |
from typing import List
def get_expected_calls(mocker: MockerFixture, file_name: str) -> List:
"""List of the first 20 expected open calls for the write_nexus_corp method with default args."""
expected_calls = [
mocker.call(file_name, 'w'),
mocker.call().__enter__(),
mocker.call().writ... | f8c15b409ae91819224d333d358888e71bb36461 | 49,205 |
def scanD(d, ck, minSupport):
"""
计算候选数据集CK在数据集D中的支持度,
并返回支持度大于最小支持度 minSupport 的数据
Args:
D 数据集
Ck 候选项集列表
minSupport 最小支持度
Returns:
retList 支持度大于 minSupport 的集合
supportData 候选项集支持度数据
"""
# ssCnt 临时存放选数据集 Ck 的频率. 例如: a->10, b->5, c->8
ssCnt = {... | a37fccca461774777bf082ca1b1e2bf3528cc220 | 49,206 |
import itertools
def accountNames():
""" invert the accountfields list so we can use it to look up user input. """
return dict(
itertools.chain.from_iterable(
((alias.lower(), k.lower()) for alias in aliases)
for k, aliases in accountFields.items()
)
) | 357916b52c6156ae8acfc6ea45e5ce9bb604929a | 49,207 |
import codecs
def _readfile(fname, strip="\n"):
"""Shortcut for reading a text file."""
with codecs.open(fname, 'r', 'UTF8') as fp:
content = fp.read()
return content.strip(strip) if strip else content | 5708a91ed7ceb8743bf0e6a40962c80e74996368 | 49,208 |
def part1and2(data):
"""
>>> part1and2(read_input())
(266, 19242)
"""
grid = defaultdict(int)
length = defaultdict(int)
for wire in data:
wire_grid = process_instructions(wire)
for location in wire_grid:
grid[location] += 1
length[location] += wire_... | 5bf4a67a18472ad0e3d736998d6d363f92a2ba78 | 49,209 |
def functions_str(graph, examples: bool = True, add_count: bool = True, **kwargs) -> str:
"""Make a summary string of the functions in the graph."""
df = function_table_df(graph, examples=examples)
headers = list(df.columns)
if add_count:
headers[0] += ' ({})'.format(len(df.index))
return ta... | 34dc7e2d91dce30eda60cb013d26919907f86f73 | 49,211 |
import numba
def duffing(n_points: int = 10**6, x_0: float = 0.1, y_0: float = 0.1, a: float = 2.75, b: float = 0.15) -> PlotData:
"""
Calculates a list of (x, y) points according to the Duffing Map
https://en.wikipedia.org/wiki/Duffing_map
:param n_points: The number of (x, y) plot points to calculat... | 971208bf9dbb44fd02fdab474397069129604986 | 49,212 |
def _sliding_attacks(square, occupied, deltas, limit=_default_limit):
"""
计算棋子的攻击范围
:param square:
:param occupied:
:param deltas:
:param limit:
:return:
"""
attacks = 0
for delta in deltas:
sq = square
while True:
sq += delta
if not limit(... | d0d6841a77d3dcd48d60fbf6a8c8969705688e7b | 49,213 |
def get_github_repo_url():
"""
Build URL to github repo
"""
return 'git://github.com/%s/%s.git' % (MOZILLA_GITHUB_ACCOUNT, DEEPSPEECH_GITHUB_PROJ) | bf8cf954bade35d6ade834d45cfc48a8c71bcfcf | 49,214 |
import re
def vnpy_opt_DAY_IN_2(opt):
"""
vnpy 优化结果清洗, 针对 DAY_IN_2
:param opt:
:return:
"""
data = re.compile(r'DAY_IN_2\':\s(\d+)\}"\]:\s([\d\.]+)').findall(opt)
data = np.array(data).T
dic = {
"DAY_IN_2": pd.Series(data[0], dtype=np.int),
"capital": pd.Series(data[1],... | 0e428a91f4198fb81041710ec7a49259efdf32c8 | 49,215 |
def get_request(url: str) -> HTMLResponse:
"""Makes a http requests to the server.
:param url: The url to send the get requests.
returns: The html response from the server.
"""
session = HTMLSession()
return session.get(url) | 8c8d0d958c96fd96605444c7bce358d5afc96e76 | 49,217 |
from typing import Union
import httpx
def sync_detailed(
*,
client: AuthenticatedClient,
json_body: SearchEventIn,
) -> Response[Union[ErrorResponse, SearchEventOut]]:
"""Search Event
Dado um Trecho, uma lista de Grupos que resultam da pesquisa
por esse Trecho e um price token, atualiza os p... | 9a076d45545912da5d854b9cd6056151a6aa183d | 49,218 |
def add(lhs, rhs):
"""Elementwise addition.
Parameters
----------
lhs : relay.Expr
The left hand side input data
rhs : relay.Expr
The right hand side input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.add(lhs, rhs) | 21a0599e8746c88c53b63218aa32e904599ee095 | 49,219 |
def view_url(context):
"""Last part of the url for viewing this context.
By default: for Images and Files, redirect to .../view
Code taken from CMFPlone/skins/plone_scripts/livesearch_reply.py
"""
portalProperties = getToolByName(context, 'portal_properties')
siteProperties = getattr(portalPro... | 42c8430e99fb0638fe4664d357e74502e0564fd3 | 49,220 |
from typing import Set
from typing import List
def track_state_update(
self,
update_task: DatabaseTask,
session,
track_factory_txs,
block_number,
block_timestamp,
block_hash,
):
"""Return int representing number of Track model state changes found in transaction."""
num_total_change... | 2195003e463604f8d3473bb67d1b9b26908702bd | 49,221 |
def ignore(x):
"""Method to indicate bypassing property validation"""
return x | cc9ae3c1e15fab3e7f55190278356c11d87d9744 | 49,222 |
def _time_bb_splits(games):
"""
This function plots the time it takes for the spy to leave the CC after the most recent BB.
If the spy fails to leave after the BB (shot, timeout, etc.), then it is the time from BB to
game end.
If the spy BBs multiple times in the same convo without leaving, it wil... | 5cbf507d4b1f84055c8444a6106a24a34076ba21 | 49,224 |
import numpy
def alpha(freqs, cfc_mat, qfc_mat=None):
""" calculate alpha from expansion
"""
# Obtain the imaginary frequency and sort other freqs
ridxs = tuple(idx for idx, freq in enumerate(freqs) if freq < 0.0)
assert len(ridxs) == 1, ('Freqs should only have one imag')
ridx = ridxs[0]
... | 30fd3aa3bbf8e1ec5464233813d0b4c41ad6c9b4 | 49,225 |
def capture_with_stderr(command, cwd=None, env=None, timeout=0, pgrp=0):
"""Run a program in the background and capture its output.
stdout and stderr are captured independently.
:Parameters:
- `command`: The command to execute. If it is a string, it will be
parsed for command-line argum... | 2cd8b6d8c3106d110f23b8a38305a86dd83a67c6 | 49,226 |
def to_rad(pseudo_dms):
""" convert pseudo DMS string (DDD.MMSS) to radians """
w = pseudo_dms.split('.') # separate degree and MMSS
degree = int(w[0])
minute = int(w[1][:2])
second = int(w[1][2:])
return (degree + minute / 60 + second / 3600) / 180 * pi | 96704b6201e7f5129ea162eee8a67bf8a9e91336 | 49,227 |
def default_for_key(key, *args, **kwargs):
"""The :func:`default_for_key` decorator will register the given metric in the global metric dict
(`metrics.DEFAULT_METRICS`) so that it can be referenced by name in instances of :class:`.MetricList` such as in the
list given to the :class:`.torchbearer.Model`.
... | f8c790341135f6124304c75ab74e4d6d53ceea5b | 49,228 |
def website_create(request):
"""
хендлер для запроса, создать сайт
создает и возвращает сайт, или ошибка
:param request:
:return:
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
req = json_request(request)
name = req['name']
ip_address = req['ip... | 65d5c1b164da4d4e74051df4118be9f1f837bbba | 49,229 |
from pytest_localserver import http
def httpserver(request):
"""The returned ``httpserver`` provides a threaded HTTP server instance
running on a randomly assigned port on localhost. It can be taught which
content (i.e. string) to serve with which response code and comes with
following attributes:
... | fce6aef741c936b5d826857d9feb9d56402a66b4 | 49,230 |
def eval_request_bool(val, default=False):
"""
Evaluates the boolean value of a request parameter.
:param val: the value to check
:param default: bool to return by default
:return: Boolean
"""
assert isinstance(default, bool)
if val is not None:
val = val.lower()
if val... | 99909909846f3194abc8c83ad84411c3ccd1245c | 49,231 |
def _drop_constant_dims(ys):
"""Returns a view of the matrix `ys` with dropped constant rows."""
ys = np.asarray(ys)
if ys.ndim != 2:
raise ValueError("Expecting a matrix.")
variances = ys.var(axis=1)
active_mask = variances > 0.
return ys[active_mask, :] | dd57aecc89d13bf19353a7e7488c8bcfb15044cc | 49,232 |
def correlateToOBTmissionEpoch(pyUTCtime):
"""correlate the local time to OBT mission epoch time"""
return pyUTCtime - s_obtMissionEpochWithLeapSeconds | 8a02e3dd31c76298bd1c0c3eac383dc27ded5d56 | 49,233 |
def applicationNavigation(ctx, translator, navigation):
"""
Horizontal, primary-only navigation view.
For the navigation element currently being viewed, copies of the
I{selected-app-tab} and I{selected-tab-contents} patterns will be
loaded from the tag. For all other navigation elements, copies of... | 5158b37c4644ba1e8fabbf186786d3fef8215af9 | 49,234 |
from datetime import datetime
def update_notice():
"""
Update a row in notice table.
:return:
"""
error = None
# Initialize form
doc_change_notice_form = DocChangeNoticeForm(request.form, csrf_enabled=False)
doc_change_id = doc_change_notice_form.doc_change_id.data
# Get Users f... | 8153b26695aec9c3d2b22e17254d444e77bbf1a9 | 49,235 |
def by_priority(feedback):
"""
Converts a feedback into a numeric representation for sorting.
Args:
feedback (Feedback): The feedback object to convert
Returns:
float: A decimal number representing the feedback's relative priority.
"""
category = Feedback.CATEGORIES.UNKNOWN
... | 264493ca79a2d260df1f16c5aa0a7ed35b14fa62 | 49,236 |
def get_feature_2(sentence: str, index: int) -> str:
"""Token to the right."""
tokens = tok(sentence)
return tokens[index + 1].lower() if index < len(tokens) - 1 else "" | 3361cf0c21bd468eac6469a3c3f65ab4c0b8d503 | 49,237 |
def split_by_gaps(vec,num_gaps = 1,index = None):
"""
Aggregates the indices of a vector based on gaps between index values.
The number of gaps is specified by num_gaps,
and the largest num_gaps gaps in the sorted array
are used to cluster values.
Arguments
---------
vec : A one-d... | f5250f11dfefb06bdfc70f97175576c8a4b2ebaa | 49,238 |
def is_hashable(obj):
"""Returns true if *obj* can be hashed"""
try:
hash(obj)
except TypeError:
return False
return True | 01be0946922e6e5cfaf21b32642f367f3690e91d | 49,239 |
def checkout_confirm(request):
"""View for confirming the users order, if he confirms it saves
the order to the database and does all appropriate actions as well."""
order = get_order(request)
cart = request.session.get("cart")
# If the user has no order, no cart or has not chosen an
# address... | a45d3ecb0f2a8d31a46f5364b011fe34b2e5547b | 49,240 |
import torch
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of ... | 14560aee2b168d1c0b1020867158a2e99be1f9b8 | 49,241 |
def is_valid(number, table=None):
"""Checks to see if the number provided passes the Damm algorithm."""
try:
return bool(validate(number), table=table)
except ValidationError:
return False | 8fc0386c2d7aff6293cca3e0ba4702bce048be81 | 49,243 |
def dbscan(points, eps, minpts):
"""
Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M... | d77106fc2cddb2447440014172fee127462eb9c3 | 49,244 |
def line_search(f, x_k, g_k, p_k, ls_method='back_tracking', ls_params={'alf': 1, 'rho': 0.3, 'mu': 1e-4, 'iter_lim': 1000}):
"""
This function performs line search for an objective function "f" using pytorch
ie. at x_k, find an alf for which x_k + alf*p_k decreases the objective function
INPUTS:
... | 70fff57b4813c2778d5dd92b44f89764382dec8a | 49,245 |
def analytical_leg_jacobian(leg_angles, sign):
"""
Computes the analytical Jacobian.
Args:
` leg_angles: a list of 3 numbers for current abduction, hip and knee angle.
sign: whether it's a left (1) or right(-1) leg.
"""
l_up = 0.2
l_low = 0.2
l_hip = HIP_COEFFICIENT* (-1)**(sign + 1)... | 090736207207a96d484bd8d028b89418936d73a1 | 49,246 |
def create_widget(rig, bone_name, bone_transform_name=None):
""" Creates an empty widget object for a bone, and returns the object.
"""
obj_name = WGT_PREFIX + rig.name + '_' + bone_name
scene = bpy.context.scene
collection = ensure_widget_collection(bpy.context)
# Check if it already exists in... | e97514310f0f73e5bcc19595b7a12b4b74d162b3 | 49,247 |
from datetime import datetime
def make_context(asset_depth=0):
"""
Create a base-context for rendering views.
Includes app_config and JS/CSS includers.
`asset_depth` indicates how far into the url hierarchy
the assets are hosted. If 0, then they are at the root.
If 1 then at /foo/, etc.
"""
context = flatten_... | 7d94f4d66143220eea6d276efaa1126aa37a1fc4 | 49,248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.