content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def flattenEmailAddresses(addresses):
"""
Turn a list of email addresses into a comma-delimited string of properly
formatted, non MIME-encoded email addresses, suitable for use as an RFC
822 header
@param addresses: sequence of L{EmailAddress} instances
"""
return ', '.join(addr.pseudoForma... | 91c235451006747e419cfd1e01eb7151eec952ed | 3,601,037 |
def predict():
"""
Prediction endpoint that loads data given the file path
and calls the prediction function in diagnostics.py
Returns:
json: model predictions
"""
filepath = request.get_json()['filepath']
df = pd.read_csv(filepath)
df = df.drop(['corporation', 'exited'], axis=... | 35f7c311ec6ba3427336ab358c9a170bb3803057 | 3,601,038 |
def split(text):
""" sometext|split """
return text.split() | 5067bad72a36827f221bde6fcd86c3c124f0b12b | 3,601,039 |
def compute_lda(corpus, id2word, k=10, alpha='auto'):
"""
Performs the LDA and returns the computer model.
Input: Corpus, dictionary and hyperparameters to optimize
Output: the fitted/computed LDA model
"""
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
... | 67b903ee41bb51fa117a7b70b6fb2270b90b44e9 | 3,601,040 |
def load_image(image):
""" Preprocess an image. """
# if self.bgr:
# temp = image.swapaxes(0, 2)
# temp = temp[::-1]
# image = temp.swapaxes(0, 2)
scale_shape = np.array([224, 224], np.int32)
crop_shape = np.array([224, 224], np.int32)
mean = np.array([104.00698793, 116.66876... | 3f4c36fbd381b8c24bda64218a1eabc3e0ccd194 | 3,601,041 |
def not_found(e):
"""
Controller for not found scenarios [404].
:param e: Exception raised due to the not found error.
:return: JSON response.
"""
log.error(f'Endpoint not found: [{e}]')
return response.make(error=True, message='Not found.', code=404) | 67482d1c278d3f3171f8589b885edc8f03df279a | 3,601,043 |
def structural_parameters(keys, columns):
"""
Gets the structural parameters in a specific order (if catalog is generated by the method in tbridge.binning)
"""
mags = columns[keys.index("MAGS")]
r50s = columns[keys.index("R50S")]
ns = columns[keys.index("NS")]
ellips = columns[keys.index("EL... | 3e6fd7c231f31f4fdcb47cd76359411d194f5539 | 3,601,045 |
def infer_batch(model, batch):
"""recognize text in image provided by file path"""
recognized_lines = [infer_line(model, lst) for lst in batch.imgs]
return recognized_lines | 66b477fc39bc1fe4d59de6c8584a085646ef3d8a | 3,601,046 |
def new_unet(
input_size,
num_channels=1,
num_classes=1,
activation="relu",
use_batch_norm=True,
upsample_mode="deconv", # 'deconv' or 'simple'
dropout=0.3,
dropout_change_per_layer=0.0,
dropout_type="spatial",
use_dropout_on_upsampling=False,
use_attention=False,
filter... | 6a6f483b777abb24c9579bb7c8c9e990475a451e | 3,601,047 |
from typing import Optional
def get_lambda_function_association(function_arn: Optional[str] = None,
instance_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLambdaFunctionAssociationResult:
"""
Provid... | b776af4cf7ad1e2b98d676fa4690fe5aa1fd822a | 3,601,048 |
def poly(a, x, y, order=4):
"""Polynomial evaluation.
pol = a[i,j] * x**(i-j) * y**j summed over i and j, where i runs from 0 to order.
Then for each value of i, j runs from 0 to i.
For many of the polynomial operations the coefficients A[i,j] are contained in an
array of dimension (order+1, order+... | e5575d4df2ae4cc5f7f1eea467d9b04ebbb97942 | 3,601,049 |
def random_in_unit_sphere():
"""
Uniformly sample a point from the sphere surface.
Returns:
coords
"""
p = 2.0 * ti.Vector([ti.random(), ti.random(), ti.random()]) - ti.Vector([1.0, 1.0, 1.0])
while p.norm() > 1.0:
p = 2.0 * ti.Vector([ti.random(), ti.random(), ti.random()]) - ti... | 942c5d16760e5e5c7c0e4ada8d6730e32dd3456b | 3,601,050 |
def sharded_and_sliced_predict(params, predict, X, aggregate=max_votes):
"""Given a sharded and sliced dataset and params, defines the prediction function."""
return aggregate(get_votes(params, predict, X)) | f9fba0e246bfb0d15007b340d6093f36286b3ed1 | 3,601,051 |
def unique_vals_counts(df: DataFrame) -> DataFrame:
"""Count unique values in dataframe.
The count is perfromed on all columns in the dataframe.
Parameters
----------
df : DataFrame
Dataframe to check for unique values per column.
Returns
-------
DataFrame
"""
... | 37de2b2aa08e88449e78cff2e259460e88cfdc6b | 3,601,053 |
def groups2csv(grouplist, filename,
x='energy', y='norm', _larch=None):
"""save data from a list of groups to a CSV file
Arguments
---------
grouplist list of groups to save arrays from
filname name of output file
x name of group member to use for `x`
y ... | 8368b4f3e1651c3b6ab3582614313c949707fb26 | 3,601,054 |
import scipy
def discount(x, gamma):
"""
Compute discounted sum of future values. Returns a list, NOT a scalar!
out[i] = in[i] + gamma * in[i+1] + gamma^2 * in[i+2] + ...
"""
return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1] | d4ab307bb0a82a41ab5754e822ccb7aa0d391e6d | 3,601,055 |
def get_center_category(categories):
"""
利用word2vec计算类别列表的相似度,与列表中其他类别最相似的类别作为中心类别
:param categories: 类别列表
:return: 中心类别,各个类别的权重列表
"""
categoryCout = len(categories)
similarityMatrix = np.zeros((categoryCout, categoryCout))
for i in range(categoryCout):
for j in range(categoryCou... | 4e2ff3f60dfeada0e0a45283039013537e2abfdb | 3,601,056 |
def get_moved_siphon(new_centerlines, centerlines, p1, p2):
"""
Extracts new siphon from new centerline
and clipping point information.
Args:
new_centerlines (vtkPolyData): Centerline data.
centerlines (vtkPolyData): Initial centerlines.
p1 (ndarray): First clipping point.
... | e1410dc54b9bfe47b40eee12cccf8db1f2a66e3d | 3,601,058 |
def load_train():
"""Loads training data."""
with open('mnist_train.npz', 'rb') as f:
train_set = np.load(f)
train_inputs = train_set['train_inputs']
train_targets = train_set['train_targets']
return train_inputs, train_targets | 24a8a48f3b78332bdbad5824bdbf090b3519a2c0 | 3,601,059 |
def softmax(X, theta=1.0, axis=None):
"""
https://nolanbconaway.github.io/blog/2017/softmax-numpy
Compute the softmax of each element along an axis of X.
Parameters
----------
X: ND-Array. Probably should be floats.
theta (optional): float parameter, used as a multiplier
prior to ex... | 6148f0312d9bf03f3d6b1cf0f9a270142d671560 | 3,601,060 |
def transform_angular_velocity(
arr,
into,
outof=None,
what="reference_frame",
dim=None,
axis=None,
timestamps=None,
time_axis=None,
cutoff=None,
return_timestamps=False,
):
""" Transform an array of angular velocities between frames.
The array represents the velocity of... | 91b3234ec50d625c67505604eda77f752cbcb30d | 3,601,061 |
import torch
import random
def prepare_model():
"""Main training program."""
#print('Generate Samples')
# Disable CuDNN.
torch.backends.cudnn.enabled = False
# Timer.
timers = Timers()
# Arguments.
args = set_args()
#print(args)
args.mem_length = args.seq_length + args.mem_... | 7a9d8bb544c8edcee4cdabcdfbd5535455edc2d9 | 3,601,062 |
def _get_autogrid(phase):
"""
Helper function to assist with memory re-allocation during FFT calculation
"""
autocorr_grid = _calc_autoc_grid(phase)
nzc = np.sum(np.sum(phase != 0))
autocorr_grid = fftshift(real(autocorr_grid)) / nzc
return autocorr_grid | 55c36e5d48a5343b5e24564a55cf3a1f8d18cfa3 | 3,601,063 |
def vecs2angles(vectors):
"""
theta = asin(-y) -- pitch
phi = atan2(-x, -z) -- yaw
"""
x, y, z = vectors.T
pitch = np.arcsin(-y)
yaw = np.arctan2(-x, -z)
return np.column_stack((yaw, pitch)) | 6a1efda78716c361419b32d95c5d916e10e272c0 | 3,601,064 |
import requests
import io
def cpi(startdate="1960-01-01", enddate="2021-01-01"):
"""
Full Name: Consumer Price Index: Total All Items for the United States
Description: Percent, Monthly, Quarterly and Annually, Seasonally Adjusted
Return: pd.DataFrame
"""
tmp_url = url["fred_econ"]
ua = Us... | 72e16316154e92776f614982211b9a78bb5bcf43 | 3,601,065 |
import struct
def short_to_bytes(short_data):
"""
For a 16 bit signed short in little endian
:param short_data:
:return: bytes(); len == 2
"""
result = struct.pack('<h', short_data)
return result | 26eeb2de936fa6b434c724ef80c008d93aec0446 | 3,601,066 |
def random_circle_at_origin(*, rng=None):
"""
Creates a random circle at the origin
"""
rng = np.random.default_rng(rng)
mv_a = random_euc_mv(rng=rng)
mv_r = random_euc_mv(rng=rng)
r = generate_rotation_rotor(np.pi/2, mv_a, mv_r)
mv_b = r*mv_a*~r
mv_c = r * mv_b * ~r
pp = (up(mv_... | edafd334d8c4329978dfb398f84306c159b7a9b6 | 3,601,067 |
import numpy
def append_gaintable(gt: GainTable, othergt: GainTable) -> GainTable:
"""Append othergt to gt
:param gt:
:param othergt:
:return: GainTable gt + othergt
"""
assert gt.receptor_frame == othergt.receptor_frame
gt.data = numpy.hstack((gt.data, othergt.data))
return gt | f9fcfa4a5a8d5ef916bd6cad027fad2c9e82f6f7 | 3,601,068 |
def cumprod(pda):
"""
Return the cumulative product over the array.
The product is inclusive, such that the ``i`` th element of the
result is the product of elements up to and including ``i``.
"""
if isinstance(pda, pdarray):
repMsg = generic_msg("efunc {} {}".format("cumprod", pda.na... | fd50fe3af900c999409adf5808a29d6168150ec7 | 3,601,069 |
def approximateAgeCohorts(df,
splits=countyAgeProportions,
mode='by county'):
"""Takes a df of flat cases by county and splits by age proportions"""
dfs = []
if mode == 'by county':
for key in ageProportions.keys():
dfSub = df.copy(deep... | dac2a9f5b13338751550851a04ed808872008e99 | 3,601,072 |
def adjust(new_rows, maxi):
"""
A function to set all with maxi number of columns
for making csv compatible
"""
rows = []
for each_row in new_rows:
if len(each_row) < maxi:
for i in range(maxi - len(each_row)):
each_row.append("-")
rows.append(each_row... | 2151362add7a85c4a236ad9ee936dcc08578534b | 3,601,074 |
import struct
def icmp_construct(seq=1):
"""Returns ICMP packet with all required fields.
However, identifier is not set and timestamp might also be included.
"""
icmp_type = 8 # (1B) Echo ping
icmp_code = 0 # (1B)
icmp_checksum = 0 # (2B)
icmp_id = 0 # (2B)
icmp_seq = seq # (2B)
... | 0676937bc7dc94b6417f1f0cec414ac9301d0d28 | 3,601,076 |
def outer_product(u, v):
"""m_ij = u_i v_j"""
return Matrix(
u.x*v.x, u.x*v.y, u.x*v.z,
u.y*v.x, u.y*v.y, u.y*v.z,
u.z*v.x, u.z*v.y, u.z*v.z
) | ea0fa00b9c437bbcfec6cd51ac0ede77a32ff995 | 3,601,077 |
def DefineFrameNodesAndElementsSteelIShape(n_hor_axis: int, n_vert_axis: int, storey_width, storey_height,
list_col: list, list_beam: list, geo_trans_ID: int, N_G = np.array([]), t_dp = np.array([]), L_b_col = np.array([]), L_b_beam = np.array([]),
fix_support = True, show_plot = True, panel_zone = True):
"... | 824242f3512de462197501472e724c17f150de17 | 3,601,078 |
def from_triples(triples):
"""
Decode triples, as from :func:`to_triples`, into a DMRS object.
"""
top = lnk = surface = identifier = None
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
rel = rel.lstrip(':')
src, tgt = str(src), str(tgt) # in case penman converts ids... | f1cdcf5dc035e5e2584ac95864ed08814e66e921 | 3,601,079 |
from typing import Union
from typing import Optional
def convert_chinese_to_bool(message: Union[Message, str]) -> Optional[bool]:
"""将中文中表示判断的词语转换为布尔值
参数:
message: 消息对象或消息文本
返回:
是表达同意的布尔值, 如果无法确认判断的词语, 则返回 `None`
"""
text = message.extract_plain_text() if isinstance(message, Mess... | f6299b1335e46c3844b70d39640cb9cfe77b984d | 3,601,081 |
def user_authenticated(user):
"""
Checks if a user is authenticated.
:param user: User to check
:return: True, if the useris verified and accepted general terms and conditions as well as the privacy policy;
False otherwise.
"""
if isinstance(user, User):
return \
user.is_... | 6f32b49c2d6b9fe704bbf59f63e4182911bc96e9 | 3,601,082 |
def gen_car1(t,alpha,sig):
""" gen_car1 generates red noise time series with uneven time grid.
Inputs:
- t [1-dim numpy array of floats]: the times of the time series.
- alpha [1-dim numpy array of floats]: values of the coefficient of the AR-1 process, as defined in
'A General Theory on Spectral Analysis f... | a4bdf51548d74d3a42737320204274483a896c9c | 3,601,084 |
def unflatten_B(t):
""" Unflatten [B*3, ...] tensor to [B, 3, ...] tensor
t is flattened tensor from component batch, which is [B, 3, ...] tensor
"""
shape = t.shape
return t.view(shape[0]//3, 3, *shape[1:]) | 77017ca136a942f975dfd498fe3aa8d3d20f67b9 | 3,601,085 |
import csv
from datetime import datetime
def findTimestampsOfScoresOnHasAndLas(dateLookup, hardcodedLookup):
"""
Go through all scores in HAS_Calculations and find the corresponding dates
return a list of score objects for all scores in HAS_Calculations with a date added
Hardcoded Lookup ... | e41ce3905d4ceab9f8afdaac456de6be57372850 | 3,601,086 |
def residuals(x1, x2):
""" Calculates the residuals between two data sets.
Parameters:
x1, x2: array
The arrays containing the data. They must have the same dimensions.
Returns:
An array of the same size of x1 containing the residuals.
Th... | a7523fb7d3ddd726508bcc50cfc4cdac10382d8b | 3,601,087 |
def unflatten_optimizer_step(step):
"""
Wrap an optimizer step function that operates on flat 1D arrays
with a version that handles trees of nested containers,
i.e. (lists/tuples/dicts), with arrays/scalars at the leaves.
"""
@wraps(step)
def _step(value_and_grad, x, itr, state=None, *args,... | 8c9fe53af31c741384039503099bdeb193f5c753 | 3,601,088 |
import torch
def l12_smooth(input_tensor, a=0.05):
"""Smoothed L1/2 norm"""
if type(input_tensor) == list:
return sum([l12_smooth(tensor) for tensor in input_tensor])
smooth_abs = torch.where(torch.abs(input_tensor) < a,
torch.pow(input_tensor, 4) / (-8 * a ** 3) + to... | f6de684a53605aa3f28cf21f46f90dbb5d325616 | 3,601,089 |
import json
def english_to_french(englishtext):
"""
This function translates English text to Frenc text
"""
frenchtext = language_translator.translate(
text=englishtext,
model_id='en-fr').get_result()
print(json.dumps(frenchtext, indent=2, ensure_ascii=False))
return frenchtext.get("tr... | acdddc18c0b105e1935494da245b305a554a8d36 | 3,601,090 |
def docker_image_update(tag):
"""Update (if needed) the docker image.
:param tag: docker tag
:type tag: str
:return: either the image has been updated or not
:rtype: bool
"""
set_prompt_color("Purple")
have_been_updated = True
id_image_base = None
try:
print("Trying to u... | 3c37ac89b5942906ecfd9b51d9dd8bc207cc017f | 3,601,091 |
def _dedupe_entities(alerts, ents) -> list:
"""Deduplicate incident and alert entities."""
alrt_ents = []
for alrt in alerts:
if alrt["Entities"]:
alrt_ents += [ent.__hash__() for ent in alrt["Entities"]]
for ent in ents:
if ent.__hash__() in alrt_ents:
ents.remo... | 9fc56c217d5a6f2ad85c100f3ee5f8a049de0d1c | 3,601,093 |
def find_components(value):
""" Extract the three values which have been combined to
form the given output.
"""
r1 = value >> 20 # 11 most significant bits
r2 = (2**10 - 1) & (value >> 10) # 10 middle bits
r3 = (2**10 - 1) & value # 10 least significant bits
return... | 80a235cafe8ceb37cafb6453f3338e03653bffe1 | 3,601,094 |
def linkage_report(
df, no_entity_id="Unable to connect Responsibility to Entity"
):
"""
Creates primary entity linking report for processed RE documents.
Args:
df: dataframe of post-processed RE docs
no_entity_id: text of non-linked entity option
Returns:
dataframe of
... | f59060fc20d7e5e95ae89797fbb889d51692df0d | 3,601,095 |
def callBranchDepth(jid, motifDict, tomtomDict, depth, fileList):
"""Call the Branch and cut algorithm to select motifs
To run use: ./bc moitfSeqFile
To compile using: g++ branch_cut.cc -lglpk -o bc
Args:
motifDict: dict between motif IDs and seqs it occurs in
tomtomDict: dict between motif Ids and a list of m... | 8c599f162f4b7c7733177227f0754b0436c4be49 | 3,601,096 |
def choose_boundary():
"""
Our embarassingly-simple replacement for mimetools.choose_boundary.
"""
return uuid4().hex | be9c1d7060f8a1d191cf8ac7ec6f370a7e49c86a | 3,601,097 |
def get_tfm_secure_targets():
"""
Creates a list of TF-M secure targets from Mbed OS targets.json.
:return: List of TF-M secure targets.
"""
return [str(t) for t in TARGET_NAMES if Target.get_target(t).is_TFM_target] | 7306aa5c815fa4e261f0ff495dd36d94959a9f7a | 3,601,098 |
def most_energetic(df):
"""Grab most energetic particle from mc_tracks dataframe."""
idx = df.groupby(["event_id"])["energy"].transform(max) == df["energy"]
return df[idx].reindex() | 031e5a92d9e890743323012227ffbd4048d0052a | 3,601,099 |
def rad2deg(value):
"""Convert radians to degrees."""
return value * 180 / pi | 1b38d51ab3fc0a0aa9b0d7363bc8e0b263c19a9b | 3,601,100 |
from bs4 import BeautifulSoup
def get_url_brsrm(isin):
"""
Return Brsrm URL
"""
base_url = common.decode_rot('uggcf://jjj.obhefbenzn.pbz')
search_path = common.decode_rot('/erpurepur/nwnk?dhrel=')
content = cache.get(base_url+search_path+isin)
if not content:
return None
soup =... | f368dbdb4fda575d9dadc54d1491f3aa2407cd69 | 3,601,101 |
def affine_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = layers.relu_backward(dout, relu_cache)
dx, dw, db = layers.affine_backward(da, fc_cache)
# da = relu_backward(dout, relu_cache)
# dx, dw, db = affine_backw... | a7d299f7319309160531fc91de5c3c60db255ab4 | 3,601,102 |
import math
def _brug_profile_geometry(row, direction="RICHTING", lijn_lengte="WS_LENGTEBRUG", rotate_degree=0, default_width=1,
default_dir=0):
"""
Convert bridge point to line
direction in degrees"""
dir = math.radians(row[direction] + rotate_degree) if not pd.isnull(row[d... | 010fa33b91f55db1a55d78d09dcfa09cd8db9d7f | 3,601,103 |
def GetInvalidTypeErrors(type_names, metrics):
"""Check that all of the metrics have valid types.
Args:
type_names: The set of valid type names.
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics with invalid_types.
"""
invalid_types = [m for m in metri... | 27af3804cb4a857d044ad365cdfee090a0d1ab56 | 3,601,104 |
def build_backbone(cfg):
"""
For Generalized_RCNN
"""
assert cfg.MODEL.BACKBONE.CONV_BODY in registry.BACKBONES, \
"cfg.MODEL.BACKBONE.CONV_BODY: {} are not registered in registry".format(
cfg.MODEL.BACKBONE.CONV_BODY
)
return registry.BACKBONES[cfg.MODEL.BACKBONE.CONV_BO... | 7755a43e26e6d5d1e3c1f6fd5ad39f29d9ed66a7 | 3,601,105 |
import textwrap
def _NormalizeDescription(description):
"""Normalizes description text.
Args:
description: str, The text to be normalized.
Returns:
str, The normalized text.
"""
if callable(description):
description = description()
if description:
description = textwrap.dedent(descriptio... | ecadc627c34d5de544a03a45850bb034f0678446 | 3,601,107 |
def login_required(f):
"""Redirect to login page if user not logged in"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('logged_in'):
flash('Login required', 'error')
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)... | 2132d610a8e84d1a3febfcfa7873a66fd11e31ba | 3,601,108 |
def get_hrp_allocation(cov, tickers):
"""Compute top-down HRP weights"""
weights = pd.Series(1, index=tickers)
clusters = [tickers] # initialize one cluster with all assets
while len(clusters) > 0:
# run bisectional search:
clusters = [c[start:stop] for c in clusters
... | f369cccec9791250653d34a6171a48b87874ffb4 | 3,601,109 |
def schedule_menu_help():
"""Меню подсказок"""
kb = InlineKeyboardMarkup()
audience_help = InlBtn(text="🚪", callback_data="audience_help")
teacher_help = InlBtn(text="👴", callback_data="teacher_help")
kb.row(audience_help, teacher_help)
return kb | 857217e0798eb2730b56c1973677844e689f84dc | 3,601,110 |
def patch_extraction(Xb, yb, sizePatches=128, Npatches=1):
"""
3D patch extraction
"""
batch_size, rows, columns, slices, channels = Xb.shape
X_patches = np.empty((batch_size*Npatches, sizePatches, sizePatches, sizePatches, channels))
y_patches = np.empty((batch_size*Npatches, sizePatches, ... | 62c9b95b8258902de2a5334e41b5f0b197100f17 | 3,601,112 |
def get_events(content, vm_name):
"""
Get List of events for VM
:param content:
:param vm_name:
:return: List of events
"""
vm = get_obj(content, [vim.VirtualMachine], vm_name)
event_filter = vim.event.EventFilterSpec()
filter_spec_entity = vim.event.EventFilterSpec.ByEntity()
fi... | 1530cc8f36ec788777918b6607bd75b7906815ec | 3,601,113 |
from typing import Optional
from typing import Union
from typing import List
def mv_col_handling(
data: pd.DataFrame,
target: Optional[Union[str, pd.Series, List]] = None,
mv_threshold: float = 0.1,
corr_thresh_features: float = 0.5,
corr_thresh_target: float = 0.3,
return_details: bool = Fals... | f6ba007f25bb40fedeb4ee5e37c1c3acaf2f2261 | 3,601,114 |
def get_vix():
"""Fetch vix from Interactive Brokers and append to history'''
:return: Dataframe
"""
ibw = IbWrapper()
ib = ibw.ib
vix = Index('VIX')
cds = ib.reqContractDetails(vix)
# contracts = [cd.contract for cd in cds]
bars = ib.reqHistoricalData(cds[0].contract,
... | f88a48d86746d05e440889dc4517fb83966d0121 | 3,601,115 |
import json
from pathlib import Path
def parse_json(filepath=None):
"""Parse the json file.
:param filepath: the path name of the file to parse
:type filepath: str|Path
:return: AppConfig
:raises KeyError: if log section not exists
"""
if filepath is None:
# set default config ... | f69330dd1177c2222186e81f9ad39abe28a16d7a | 3,601,116 |
import heapq
def astar(maze, start, end, allow_diagonal_movement=False):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
"""
start_node = Node(None, start)
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, end)
end_node.g = ... | bc4e9a81f4a02ea3899c59a1be1d67a0281c2d2c | 3,601,117 |
import math
def jd_to_date(jd):
"""
Convert Julian Day to date.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
jd : float
Julian Day
Returns
-------
year : int
Year a... | 1b766ff5fd62f8d74817ee8a6fc056798babaa77 | 3,601,119 |
from pathlib import Path
import json
from typing import OrderedDict
def read_json(file_name: str):
"""
Function that reads a json file
Parameters
----------
file_name: str
The json file path
Returns
-------
OrderedDict
The json file's contents
"""
file_name =... | 2d487309bcc4b14c208c02d48e8f7d5994eea88b | 3,601,120 |
def regular2regular(
data,
ilons,
ilats,
olons,
olats,
distances=None,
inds=None,
how="nn",
k=10,
radius_of_influence=100000,
n_jobs=2,
):
"""
Interpolates from regular to regular grid.
It's a wraper around `fesom2regular` that creates an object that
mimic fes... | d1ce6e4d31b143233bd7fb07cb8ce137d249a579 | 3,601,121 |
def km_centroids(pts, assign, k):
"""Implements the centroid-update step of the k-means algorithm.
Given a set of points, ``pts``, of shape ``(npts, ndim)``, and an
assignment of each point to a region, ``assign``, and the number
of means, ``k``, returns an array of shape ``(k, ndim)`` giving
the ce... | 6606ad267fbaf0fd1b015120f0053828933c755e | 3,601,122 |
def recover_wallet(
word1: str, word2: str,
word3: str, word4: str,
word5: str, word6: str,
word7: str, word8: str,
word9: str, word10: str,
word11: str, word12: str
):
""" Recover Wallet private and publick key from 12 seeds words """
seeds = [
word1, word2, word3, word4,
... | b4a70cccad5de4a5868da10bca1113739180420f | 3,601,123 |
import json
def encrypt(d, master_key):
"""
Encrypt a dictionary with a master key.
Args:
d (dict): the dictionary to encrypt.
master_key (str): the master key.
Returns:
str: the encrypted dictionary as a hex string.
"""
key = generate_key(master_key)
fernet = Fer... | 0096443d4f6280f918af2400fd2713d8cd7037ab | 3,601,124 |
def get_lhd_maximin_points(var_lower, var_upper, integer_vars,
sample_size, num_trials=50):
"""Compute a latin hypercube design with maximin distance.
Compute an array of points in the given box, where n is the
dimension of the space. The selected points are picked according
... | aa766f907acc79e5d718bbb876a353ab449fc2e5 | 3,601,126 |
import textwrap
def indent(multiline_str: str, indented=4):
"""
Converts a multiline string to an indented string
Args:
multiline_str: string to be converted
indented: number of space used for indentation
Returns: Indented string
"""
return textwrap.indent(multiline_str, " " ... | 9fd5f2310ade00071a57731040435428cff88557 | 3,601,127 |
def parse_dhcp_logs(from_date, macaddr):
"""Parse dhcpd logs, extract last ipaddr from DHCPACK if found
"""
macaddr = macaddr.lower()
entries = tsclient.fetch_dhcp_logs(from_date)
return entries.get(macaddr, None) | 0da376edc6c0a205a33b804c24bc80d1f105150e | 3,601,128 |
def _iteration_report_pb_to_subnetwork_reports(iteration_report_pb):
"""Converts IterationReport proto to a `MaterializedReport` list."""
def _proto_map_to_dict(proto, field_name):
"""Converts map field of a proto to a dict.
Args:
proto: the proto to read from.
field_name: name of the map fiel... | 49a5bc3966110318088447832ebe8609cd9ba635 | 3,601,130 |
def eval_root_children(node, evi):
"""
Evaluates the PC rooted at `node` at evidence `evi`.
This function only applies to the root of a PC.
"""
n_threads = nb.config.NUMBA_DEFAULT_NUM_THREADS
sizes = np.full(n_threads, node.nchildren // n_threads, dtype=np.int32)
sizes[:node.nchildre... | 01d5b2043927fc3ee5b640f22244997c545b2ef4 | 3,601,131 |
def validate_name(name, flash_errors=True):
"""Validates a name. Flashes errors if flash_errors is True."""
# Allow letters, spaces, hyphens, and apostrophes.
# First and last characters must be letters.
if not name_regex.match(name):
if flash_errors:
flask.flash("'{0}' is not a vali... | 4456e5d91ae0f148d10cf0a7ddee3e9aa554e581 | 3,601,132 |
def upload_user_pic(pic_name, user_id, type):
"""[summary]
Uploads users picture path to database
Args:
pic_name ([String]): [name of pic]
user_id ([String]): [user id]
type ([String]): [admin or user]
Returns:
[String]: [1 if success, 0 if failed]
"""
try:
... | 2f04038a9b48427bcb14d1e00fdafacf9130fbd6 | 3,601,133 |
def availability_zone_get(context, id_or_name):
"""Get availability zone by name or id."""
return IMPL.availability_zone_get(context, id_or_name) | 009b2b6338f7aae7415ca0171e82bca882255198 | 3,601,134 |
def is_stereo_compatible(tra, sgr1, sgr2):
""" is this transformation compatible with the reactant/product stereo
assignments?
"""
cgr1 = without_stereo_parities(sgr1)
cgr2 = without_stereo_parities(sgr2)
atm_key_dct = full_isomorphism(apply(tra, cgr1), cgr2)
# determine the stereo centers ... | 89c79dca8b87cd0a7f341bd56f4b2b77f956cc4b | 3,601,135 |
def pil_to_numpy(x_pil):
"""
:param x_pil: PIL.Image object
:return: Normalized numpy array of shape (channels, height, width)
"""
# Channels are the third dim of a PIL.Image,
# but we want to be able to index it by channel first,
# so we use np.rollaxis to get an array of shape (3, h, w)
... | be2b0d4dbe8d15c0154bb6d2428e8e66435df1c4 | 3,601,136 |
def upload(path, public, file_type=None): # could also call it import
"""
Upload a file or workflow to Galaxy.
Currently, gxwf attempts to upload any file with a .ga extension as a workflow, and all others as datasets.
"""
return upload_commands.upload(path, public, file_type) | 58a7dc3d02178f5e8830efd8647b00551a3c08ae | 3,601,137 |
import scipy.sparse as sp
from time import time
def fit_scan( scan, # input scan
lmk_3d, # input scan landmarks
model, # model
lmk_face_idx, lmk_b_coords, # landmark embedding
weights, ... | 7cd463260608bfb2b3e65de12743caf8371e6e2e | 3,601,138 |
import html
def add_dash(server):
"""
It creates a Dash app that plots a line chart of life expectancy from gapminder dataset
with 2 widgets : rangeslider for years and dropdown for sub-region filter
:param server: The Flask app object
:return: A Dash server
"""
app = Dash(server=serv... | 8f68b887ee5dceacf2403cb2b1efd7bf5e45eb0d | 3,601,139 |
from typing import Concatenate
def create_model(params: dict):
"""Generates a merged ANN and RNN model for hyperparameter training using Optuna
Args:
params (dict): contains Optuna-defined hyperparameter ranges
Returns:
keras model: a compiled model
"""
ACTIVATION = config["RNN_... | e72e0aa0ff2fc3861ab4871876b287c899be7662 | 3,601,140 |
def get_current_positions():
"""Get current positions returns a dataframe with columns:
Date Purchased,
Purchase Price,
Quantity Held,
Ex-dividend date
Current Price,
Symbol
"""
positions = api.list_positions()
target_columns = ['avg_entry_price', 'current... | 36f4529881bc9f86dc9a335435ec67cb87f5acaf | 3,601,141 |
def parse_arguments():
"""
Parse all command line arguments.
Returns:
segments - full file path to segment file
tumor - full file path to tumor bam
normal - full file path to normal bam
fasta - full file path to correct FASTA file
exons - full file path to bed file of all exons
directory - target direct... | 5cf2e5c94712a92b69a1ff722123fae8dcecbb06 | 3,601,142 |
def trapezoid_smooth(spectrum, width):
"""
Smoothing based on a `astropy.convolution.Trapezoid1DKernel` kernel.
Parameters
----------
spectrum : `~specutils.Spectrum1D`
The `~specutils.Spectrum1D` object to which the smoothing will be
applied.
width : number
The width of... | 2ac6a72e780edc6a1620682e21eea37280b1d636 | 3,601,143 |
def test_module_object_function_override():
"""Test that if a the PythonistaModuleAdapter has an overridden function
that function returns as expected when called."""
def open(self, url):
return url
PythonistaModuleAdapter.open = open
webbrowser = PythonistaModuleAdapter('webbrowser')
... | 26058f9807ecee5d385b08486bcaa8dfe61feba3 | 3,601,144 |
import numpy
def uft_d_active_integrals(sys, ea, eb, foa, fva, fob, fvb,
iocca, ivira, ioccb, ivirb, dveca, dvecb):
"""Return derivatives of unrestricted one and two-electron integrals
with small occupations excluded."""
# get FT Fock matrix
fa, fb = sys.u_fock_tot()
fa... | 98967cdd33cf19eb033d171ed590f771fc3be356 | 3,601,145 |
def list_pattern_features(client, patter_name, type_=None, file_=None):
"""List features in a Creo Pattern.
Args:
client (obj):
creopyson Client.
patter_name (str):
Pattern name.
`type_` (str, optional):
Feature type patter (wildcards allowed: True).
... | d1923ccdb178a211ecd896c325170a5e247557aa | 3,601,146 |
def rate_snippet(request, snippet_id):
"""
Allows a user to rate a Snippet.
Context::
None, returns a redirect back to the Snippet.
Template::
None, returns a redirect back to the Snippet.
"""
snippet = get_object_or_404(Snippet, pk=snippet_id)
if not Rati... | 74bc2044e2881725f954d96ea114aed8c6b17288 | 3,601,148 |
def returnBeta(*args):
"""
Return a beta distributed random variables with given parameters
"""
return [np.random.beta(args[0],args[1],1)] | 986853d4be7c95c6ee5164cd5490c38fd345e297 | 3,601,149 |
def get_binary_mask(x):
"""
Return binary mask from numpy array
:param x: numpy array
:return: binary mask from numpy array
"""
x[x >= 0.5] = 1.
x[x < 0.5] = 0.
return x | d63a2cff4d8398c52ea97fff720d78a8d6df66b5 | 3,601,150 |
def match_polygons(prediction_df, annotation_df):
"""
Match polygons (shapely objects) based on area of overlap
"""
'''
1) Find overlap among polygons efficiently
2) Calulate a cost matrix of overlap, with rows as itcs and columns as predictions
3) Hungarian matching for pairing
4) Cal... | 0e2253525161ac236e5154974d3ba7a82d2090a6 | 3,601,151 |
def append_query_params(original_url, **kwargs):
"""
Add additional query string arguments to the given url.
Example call:
new_url = append_query_params(
original_url, error='this is an error',
another_arg='this is another argument')
"""
scheme, netloc, path, query_s... | 2850549307204bcc48a8e773e2d1eadc5e261c94 | 3,601,152 |
def __createGraphStructure(argument, references, graphs, arguments):
""" Using the 'references' of this 'argument', create a graph-like
structure and make it part of the graphs in 'graphs'. The other
'arguments' from the config-subtree of the "dynamic"-tag are provided
to locate the referenced arguments. """
... | 51951bce08070627a251817a6c7c2c7738c0fc61 | 3,601,153 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.