content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Class_Property (getter) :
"""Return a descriptor for a property that is accessible via the class
and via the instance.
::
>>> from _TFL._Meta.Property import *
>>> from _TFL._Meta.Once_Property import Once_Property
>>> class Foo (object) :
... @Class_Property
... | 845d62444f41b547b9922d10666f8a911c7e8de3 | 15,476 |
def naive_act_norm_initialize(x, axis):
"""Compute the act_norm initial `scale` and `bias` for `x`."""
x = np.asarray(x)
axis = list(sorted(set([a + len(x.shape) if a < 0 else a for a in axis])))
min_axis = np.min(axis)
reduce_axis = tuple(a for a in range(len(x.shape)) if a not in axis)
var_sha... | 78034c16e38c27b146a8ee1be1be86d9fc4ffe6a | 15,477 |
def cmpTensors(t1, t2, atol=1e-5, rtol=1e-5, useLayout=None):
"""Compare Tensor list data"""
assert (len(t1) == len(t2))
for i in range(len(t2)):
if (useLayout is None):
assert(t1[i].layout == t2[i].layout)
dt1 = t1[i].dataAs(useLayout)
dt2 = t2[i].dataAs(useLayout)
... | ce085c9998fddc86420ea4f5307e83e15d49372a | 15,478 |
def auth(body): # noqa: E501
"""Authenticate endpoint
Return a bearer token to authenticate and authorize subsequent calls for resources # noqa: E501
:param body: Request body to perform authentication
:type body: dict | bytes
:rtype: Auth
"""
db = get_db()
cust = db['Customer'].find... | 2992d119cf7fa3a5d797825c704cd837f647dbd7 | 15,479 |
def make_feature(func, *argfuncs):
"""Return a customized feature function that adapts to different input representations.
Args:
func: feature function (callable)
argfuncs: argument adaptor functions (callable, take `ctx` as input)
"""
assert callable(func)
for argfunc in argfuncs:
... | 26064ee0873d63edc877afdcb03a39e40453a831 | 15,480 |
import ctypes
def from_numpy(np_array: np.ndarray):
"""Convert a numpy array to another type of dlpack compatible array.
Parameters
----------
np_array : np.ndarray
The source numpy array that will be converted.
Returns
-------
pycapsule : PyCapsule
A pycapsule containing... | 2663b831274f1fc1dd2e597212fa475f6d03e578 | 15,481 |
def lmsSubstringsAreEqual(string, typemap, offsetA, offsetB):
"""
Return True if LMS substrings at offsetA and offsetB are equal.
"""
# No other substring is equal to the empty suffix.
if offsetA == len(string) or offsetB == len(string):
return False
i = 0
while True:
aIsLMS... | 5177b8cf5b2b80a519ef0d9fbb5f972c584a6b5b | 15,482 |
from .tools import nantrapz
def synthesize_photometry(lbda, flux, filter_lbda, filter_trans,
normed=True):
""" Get Photometry from the given spectral information through the given filter.
This function converts the flux into photons since the transmission provides the
fraction o... | 6eb8b9806388b9b373e37a2c813e3a4ba9696bc2 | 15,483 |
def get_A_dash_floor_bath(house_insulation_type, floor_bath_insulation):
"""浴室の床の面積 (m2)
Args:
house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸'
floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない'
Returns:
float: 浴室の床の面積 (m2)
"""
return get_table_3(15, house_insula... | fbcd2c6dd6b5e2099351b445bf4b3e71aed4d508 | 15,484 |
def cancel_task_async(hostname, task_id):
"""Cancels a swarming task."""
return _call_api_async(
None, hostname, 'task/%s/cancel' % task_id, method='POST') | fb1b57dac80518e2cf3b375d8ecd393b34855b45 | 15,485 |
def generate_two_files_both_stress_strain():
"""Generates two files that have both stress and strain in each file"""
fname = {'stress': 'resources/double_stress.json',
'strain': 'resources/double_strain.json'}
expected = [ # makes an array of two pif systems
pif.System(
pro... | 6cfe410071085bc975f630e34e43c8b2b626f846 | 15,486 |
def recipe_edit(username, pk):
"""Page showing the possibility to edit the recipe."""
recipe_manager = RecipeManager(api_token=g.user_token)
response = recipe_manager.get_recipe_response(pk)
recipe = response.json()
# shows 404 if there is no recipe, response status code is 404 or user is not the au... | 73735cd5c279c8e62aebdacfb29c5d3d83c856fa | 15,488 |
import re
def load_data_file(filename):
"""loads a single file into a DataFrame"""
regexp = '^.*/results/([^/]+)/([^/]+)/([^/]+).csv$'
optimizer, blackbox, seed = re.match(regexp, filename).groups()
f = ROOT + '/results/{}/{}/{}.csv'.format(optimizer, blackbox, seed)
result = np.genfromtxt(f, deli... | a2c53adfc356809f7ec554d20203a5ad276ebc1e | 15,489 |
def get_hub_manager():
"""Generate Hub plugin structure"""
global _HUB_MANAGER
if not _HUB_MANAGER:
_HUB_MANAGER = _HubManager(_plugins)
return _HUB_MANAGER | 384039f45f59cec3db737536a08719770ecfb3ff | 15,490 |
def extract_stimtype(
data: pd.DataFrame, stimtype: str, columns: list
) -> pd.DataFrame:
"""
Get trials with matching label under stimType
"""
if stimtype not in accept_stimtype:
raise ValueError(f"invalid {stimtype}, only accept {accept_stimtype}")
get = columns.copy()
get += ["par... | 186cc066133d1d8d6c443b17a2d17cc70d366d98 | 15,491 |
def compute_rank_clf_loss(hparams, scores, labels, group_size, weight):
"""
Compute ranking/classification loss
Note that the tfr loss is slightly different than our implementation: the tfr loss is sum over all loss and
devided by number of queries; our implementation is sum over all loss and devided by... | 12b45518d5bd11182dbf220ccfe90da2fe0d6c38 | 15,492 |
import string
def get_org_image_url(url, insert_own_log=False):
""" liefert gegebenenfalls die URL zum Logo der betreffenden Institution """
#n_pos = url[7:].find('/') # [7:] um http:// zu ueberspringen
#org_url = url[:n_pos+7+1] # einschliesslich '/'
item_containers = get_image_items(ELIXIER_LOGOS_PATH)
... | b80d29a3393820e6cfc58e36ae34361d4587bd73 | 15,493 |
import asyncio
import logging
async def download_page(url, file_dir, file_name, is_binary=False):
"""
Fetch URL and save response to file
Args:
url (str): Page URL
file_dir (pathlib.Path): File directory
file_name (str): File name
is_binary (bool): True if should download ... | 452285e7d47d7d7c227e356efc0e7dc1ad2ce7ee | 15,494 |
def normal_coffee():
"""
when the user decides to pick a normal or large cup of coffee
:return: template that explains how to make normal coffee
"""
return statement(render_template('explanation_large_cup', product='kaffee')) | ba9ed37cb85327d6541ad86071f047ce87297c95 | 15,495 |
def _transitive_closure_dense_numpy(A, kind='metric', verbose=False):
"""
Calculates Transitive Closure using numpy dense matrix traversing.
"""
C = A.copy()
n, m = A.shape
# Check if diagonal is all zero
if sum(np.diagonal(A)) > 0:
raise ValueError("Diagonal has to be zero for matr... | cf02a380dbf28a6442cc999b3faea329d5041b17 | 15,496 |
def convert_date(raw_dates: pd.Series) -> pd.Series:
"""Automatically converts series containing raw dates
to specific format.
Parameters
----------
raw_dates:
Series to be converted.
Returns
-------
Optimized pandas series.
"""
raw_dates = pd.to_datetime(raw_dates,... | 23a2310ec8fd30dd2b831805817fb3407c10c104 | 15,497 |
async def get_scorekeeper_by_id(scorekeeper_id: conint(ge=0, lt=2**31)):
"""Retrieve a Scorekeeper object, based on Scorekeeper ID,
containing: Scorekeeper ID, name, slug string, and gender."""
try:
scorekeeper = Scorekeeper(database_connection=_database_connection)
scorekeeper_info = scorek... | 044b3bacfdf47918c2ad15635958d69c17ccf5c8 | 15,498 |
from datetime import datetime
def get_time(sec_scale):
"""time since epoch in milisecond
"""
if sec_scale == 'sec':
scale = 0
elif sec_scale == 'msec':
scale = 3
else:
raise
secs = (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds()
return int(secs *... | c233133d61c6347a27186ef3baf0ae2bc79cf8f2 | 15,500 |
import urllib
import json
def get_json(url):
"""
Function that retrieves a json from a given url.
:return: the json that was received
"""
with urllib.request.urlopen(url) as response:
data = response.readall().decode('utf-8')
data = json.loads(data)
return data | 3164bb7d1adc40e3dcd07e82ec734807f3a17abc | 15,501 |
def _defaultChangeProvider(variables,wf):
""" by default we just forword the message to the change provider """
return variables | 5087dc06e0da1f3270b28e9ab1bd2241ed4b4de4 | 15,502 |
def GPPrediction(y_train, X_train, T_train, eqid_train, sid_train = None, lid_train = None,
X_new = None, T_new = None, eqid_new = None, sid_new = None, lid_new = None,
dc_0 = 0.,
Tid_list = None, Hyp_list = None, phi_0 = None, tau_0 = None,... | 28bdf5575f16d1ee3a719aaadc59eefda642171d | 15,504 |
def zdotu(x, y):
"""
This function computes the complex scalar product \M{x^T y} for the
vectors x and y, returning the result.
"""
return _gslwrap.gsl_blas_zdotu(x, y, 1j) | 135b5196568454dc0c721ab42cdd13d4bed63c5c | 15,505 |
def music21_to_chord_duration(p, key):
"""
Takes in a Music21 score, and outputs three lists
List for chords (by primeFormString string name)
List for chord function (by romanNumeralFromChord .romanNumeral)
List for durations
"""
p_chords = p.chordify()
p_chords_o = p_chords.flat.getElem... | 142a0ef06c5c9542097cc7db0631a1f19e2f8f72 | 15,506 |
def city_country(city, country, population=''):
"""Generate a neatly formatted city/country name."""
full_name = city + ', ' + country
if population:
return full_name.title() + ' - population ' + str(population)
else:
return full_name.title() | 23be8d5b39380fd177240e479cf77ac7eb6c7459 | 15,507 |
def generate_headermap(line,startswith="Chr", sep="\t"):
"""
>>> line = "Chr\\tStart\\tEnd\\tRef\\tAlt\\tFunc.refGene\\tGene.refGene\\tGeneDetail.refGene\\tExonicFunc.refGene\\tAAChange.refGene\\tsnp138\\tsnp138NonFlagged\\tesp6500siv2_ea\\tcosmic70\\tclinvar_20150629\\tOtherinfo"
>>> generate_heade... | 16bbbc07fa13ff9bc8ec7af1aafc4ed65b20ec4c | 15,508 |
def max(q):
"""Return the maximum of an array or maximum along an axis.
Parameters
----------
q : array_like
Input data
Returns
-------
array_like
Maximum of an array or maximum along an axis
"""
if isphysicalquantity(q):
return q.__class__(np.max(q.value), ... | 0a3cfae6fb9d1d26913817fcc11765214baa8dff | 15,509 |
from typing import OrderedDict
def make_failure_log(conclusion_pred, premise_preds, conclusion, premises,
coq_output_lines=None):
"""
Produces a dictionary with the following structure:
{"unproved sub-goal" : "sub-goal_predicate",
"matching premises" : ["premise1", "premise2", ..... | 17f7cb8b6867849e034d72f05e9e48622bd35b7d | 15,510 |
import requests
def request(url=None, json=None, parser=lambda x: x, encoding=None, **kwargs):
"""
:param url:
:param json:
:param parser: None 的时候返回r,否则返回 parser(r.json())
:param kwargs:
:return:
"""
method = 'post' if json is not None else 'get' # 特殊情况除外
logger.info(f"Request M... | c222cc2a5c1e2acb457600d223c9ca6ab588aa5e | 15,511 |
import math
def log_density_igaussian(z, z_var):
"""Calculate log density of zero-mean isotropic gaussian distribution given z and z_var."""
assert z.ndimension() == 2
assert z_var > 0
z_dim = z.size(1)
return -(z_dim/2)*math.log(2*math.pi*z_var) + z.pow(2).sum(1).div(-2*z_var) | a412b9e25aecfc2baed2d783a2d7cd281fadc9fb | 15,512 |
def denom(r,E,J,model):
"""solve the denominator"""
ur = model.potcurve(r)#model.potcurve[ (abs(r-model.rcurve)).argmin()]
return 2.0*(E-ur)*r*r - J*J; | 19dc7c5cd283b66f834ba9a0d84fb396ca2c2c89 | 15,513 |
def approximate_gaussians(confidence_array, mean_array, variance_array):
""" Approximate gaussians with given parameters with one gaussian.
Approximation is performed via minimization of Kullback-Leibler
divergence KL(sum_{j} w_j N_{mu_j, sigma_j} || N_{mu, sigma}).
Parameters
----------
confi... | 7c722f0153e46631b3c4731d8a307e0b219be02b | 15,514 |
from typing import Callable
import types
def return_loss(apply_fn: Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray],
steps: types.Transition):
"""Loss wrapper for ReturnMapper.
Args:
apply_fn: applies a transition model (o_t, a_t) -> (o_t+1, r), expects the
leading axis to index the ba... | 970cb6623436982ef1359b1328edcb828012f1f7 | 15,515 |
def part_two(data):
"""Part two"""
array = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
commands = data.split(',')
for _ in range(1000000000 % 30):
dance(array, commands)
return ''.join(map(str, array)) | 75e847cd5a598aa67ca54133c15a0c2c3fc67433 | 15,516 |
def readCSVPremadeGroups(filename, studentProperties=None):
"""studentProperties is a list of student properties in the order they appear in the CSV.
For example, if a CSV row (each group is a row) is as follows: "Rowan Wilson, [email protected], 1579348, Bob Tilano, [email protected], 57387294"
Then the format is:... | f12de287b4a9f19e2e29302338f7233e34d54f0c | 15,518 |
def random_contrast(video, lower, upper, seed=None):
"""Adjust the contrast of an image or images by a random factor.
Equivalent to `adjust_contrast()` but uses a `contrast_factor` randomly
picked in the interval `[lower, upper)`.
For producing deterministic results given a `seed` value, use
`tf.i... | 6ea6a72100ad468d7692c0bb8c2837cba5eaa3e0 | 15,519 |
from typing import Dict
def load(df: DataFrame, config: Dict, logger) -> bool:
"""Write data in final destination
:param df: DataFrame to save.
:type df: DataFrame
:param config: job configuration
:type config: Dict
:param logger: Py4j Logger
:type logger: Py4j.Logger
:return: True
... | 70f962cc24f23264f23dce458c233466dc06d276 | 15,520 |
def phase_correct_zero(spec, phi):
"""
Correct the phases of a spectrum by phi radians
Parameters
----------
spec : float array of complex dtype
The spectrum to be corrected.
phi : float
Returns
-------
spec : float array
The phase corrected spectrum
... | 1647e8f99e10ba5f715e4c268907cbf995e99335 | 15,521 |
def upsample(s, n, phase=0):
"""Increase sampling rate by integer factor n with included offset phase.
"""
return np.roll(np.kron(s, np.r_[1, np.zeros(n-1)]), phase) | 997f48be57816efb11b77c258e945d3161b748be | 15,522 |
def parse_idx_inp(idx_str):
""" parse idx string
"""
idx_str = idx_str.strip()
if idx_str.isdigit():
idxs = [int(idx_str)]
if '-' in idx_str:
[idx_begin, idx_end] = idx_str.split('-')
idxs = list(range(int(idx_begin), int(idx_end)+1))
return idxs | 2dc1282169f7534455f2a0297af6c3079192cb66 | 15,523 |
import requests
def toggl_request_get(url: str, params: dict = False) -> requests.Response:
"""Send a GET request to specified url using toggl headers and configured auth"""
headers = {"Content-Type": "application/json"}
auth = (CONFIG["toggl"]["api_token"], "api_token")
response = requests.get(url, h... | bd4714bb0d92dcfb1e2ef27bb3fa3c67179b8b40 | 15,524 |
def sample_point_cloud(source, target, sample_indices=[2]):
""" Resamples a source point cloud at the coordinates of a target points
Uses the nearest point in the target point cloud to the source point
Parameters
----------
source: array
Input point cloud
target: array... | b490e598e68ef175a5cf80c052f2f82fc70ac4ba | 15,525 |
def make_satellite_gsp_pv_map(batch: Batch, example_index: int, satellite_channel_index: int):
"""Make a animation of the satellite, gsp and the pv data"""
trace_times = []
times = batch.satellite.time[example_index]
pv = batch.pv
for time in times:
trace_times.append(
make_sate... | fd0e0a7543da212f368849c3686277a7c8c42a95 | 15,526 |
def raw_to_engineering_product(product, idbm):
"""Apply parameter raw to engineering conversion for the entire product.
Parameters
----------
product : `BaseProduct`
The TM product as level 0
Returns
-------
`int`
How many columns where calibrated.
"""
col_n = 0
... | aaf5a92c53bfc41a5230593b96c0de7b8ad1ba4a | 15,527 |
def paginate(objects, page_num, per_page, max_paging_links):
"""
Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``.
"""
paginator = Paginator(objects, per_page)
try:
page_num = int(page_num)
except ... | cd8a7ef046a48c580ad12cfa44f1862312bb1aba | 15,528 |
def _get_crop_frame(image, max_wiggle, tx, ty):
"""
Based on on the max_wiggle, determines a cropping frame.
"""
pic_width, pic_height = image.size
wiggle_room_x = max_wiggle * .5 * pic_width
wiggle_room_y = max_wiggle * .5 * pic_height
cropped_width = pic_width - wiggle_room_x
cropped_h... | 18442a97544d6c4bc4116dc43811c9fcd0d203c6 | 15,529 |
from re import U
def __vigenere(s, key='virink', de=0):
"""维吉利亚密码"""
s = str(s).replace(" ", "").upper()
key = str(key).replace(" ", "").upper()
res = ''
i = 0
while i < len(s):
j = i % len(key)
k = U.index(key[j])
m = U.index(s[i])
if de:
if m < k:
... | 4deadfc9fdd1cb002c2f31a1de7763b0c49dd757 | 15,530 |
def mask_unit_group(unit_group: tf.Tensor, unit_group_length: tf.Tensor, mask_value=0) -> tf.Tensor:
""" Masks unit groups according to their length.
Args:
unit_group: A tensor of rank 3 with a sequence of unit feature vectors.
unit_group_length: The length of the unit group (assumes all unit f... | 758028075f793bad1165d0ca8992c78cb4a1318e | 15,531 |
def fill_session_team(team_id, session_id, dbsession=DBSESSION):
"""
Use the FPL API to get list of players in an FPL squad with id=team_id,
then fill the session team with these players.
"""
# first reset the team
reset_session_team(session_id, dbsession)
# now query the API
players = f... | 28118a527c009d90401b368d628725ee29e838ef | 15,532 |
def create_map(users_info):
"""
This function builds an HTML map with locations of user's friends on
Twitter.
"""
my_map = folium.Map(
location=[49.818396058511645, 24.02258071000576], zoom_start=10)
folium.TileLayer('cartodbdark_matter').add_to(my_map)
folium.TileLayer('stamentoner'... | cfe9649101906aa295ffc9984bbed15a99c7ed46 | 15,533 |
def l2sq(x):
"""Sum the matrix elements squared
"""
return (x**2).sum() | c02ea548128dde02e4c3e70f9280f1ded539cee9 | 15,534 |
def normalize(arr, axis=None):
"""
Normalize a vector between 0 and 1.
Parameters
----------
arr : numpy.ndarray
Input array
axis : integer
Axis along which normalization is computed
Returns
-------
arr : numpy.ndarray
Normalized version of the input array
... | 2c9689ee829e66bfd02db3c1c92c749ca068bd73 | 15,535 |
def successive_substitution(m, T, P, max_iter, M, Pc, Tc, omega, delta, Aij,
Bij, delta_groups, calc_delta, K, steps=0):
"""
Find K-factors by successive substitution
Iterate to find a converged set of K-factors defining the gas/liquid
partitioning of a mixture using su... | 1ad40642f940be0d1e967bf97a62e3b754312ae9 | 15,536 |
import re
def Match(context, pattern, arg=None):
"""Do a regular expression match against the argument"""
if not arg:
arg = context.node
arg = Conversions.StringValue(arg)
bool = re.match(pattern, arg) and boolean.true or boolean.false
return bool | 62007fcd4617b0dfebb1bc8857f89fa2e6075f41 | 15,537 |
def rr_rectangle(rbins, a, b):
""" RR_rect(r; a, b) """
return Frr_rectangle(rbins[1:], a, b) - Frr_rectangle(rbins[:-1], a, b) | 98e30791e114ce3e2f6529db92c0103d1477cd76 | 15,538 |
def update_type(title, title_new=None, description=None, col_titles_new={}):
"""Method creates data type
Args:
title (str): current type title
title_new (str): new type title
description (str): type description
col_titles_new (dict): new column values (key - col id, value - col valu... | 92e663d3bfd798de0367a44c4909a330ac9e4254 | 15,539 |
def api(repos_path):
"""Glottolog instance from shared directory for read-only tests."""
return pyglottolog.Glottolog(str(repos_path)) | a941a907050300bc89f6db8b4bd33cf9725cf832 | 15,540 |
from presqt.targets.osf.utilities.utils.async_functions import run_urls_async
import requests
def get_all_paginated_data(url, token):
"""
Get all data for the requesting user.
Parameters
----------
url : str
URL to the current data to get
token: str
User's OSF token
Retu... | cca997d479c63415b519de9cbd8ac2681abc42ed | 15,541 |
def alaw_decode(x_a, quantization_channels, input_int=True, A=87.6):
"""alaw_decode(x_a, quantization_channels, input_int=True)
input
-----
x_a: np.array, mu-law waveform
quantization_channels: int, Number of channels
input_int: Bool
True: convert x_mu (int) from int to float, bef... | a2e10eb590d5b7731227b96233c6b615c11d4af6 | 15,542 |
import dateutil
def swap_year_for_time(df, inplace):
"""Internal implementation to swap 'year' domain to 'time' (as datetime)"""
if not df.time_col == "year":
raise ValueError("Time domain must be 'year' to use this method")
ret = df.copy() if not inplace else df
index = ret._data.index
... | 790e8d24e6c4d87413dfc5d6205cbb04f7acefd6 | 15,545 |
from typing import Optional
from typing import List
def get_orders(
db: Session,
skip: int = 0,
limit: int = 50,
moderator: str = None,
owner: str = None,
desc: bool = True,
) -> Optional[List[entities.Order]]:
"""
Get the registed orders using filters.
Args:
- db: the dat... | a5c86ccaad8573bc641f531751370c264baa60f8 | 15,546 |
def create_data_loader(img_dir, info_csv_path, batch_size):
"""Returns a data loader for the model."""
img_transform = transforms.Compose([transforms.Resize((120, 120), interpolation=Image.BICUBIC),
transforms.ToTensor()])
img_dataset = FashionDataset(img_dir, img_tra... | 1a7df2b691c66ef5957113d5113353f34bf8c855 | 15,547 |
def comp_number_phase_eq(self):
"""Compute the equivalent number of phase
Parameters
----------
self : LamSquirrelCage
A LamSquirrelCage object
Returns
-------
qb: float
Zs/p
"""
return self.slot.Zs / float(self.winding.p) | f4679cf92dffff138a5a96787244a984a11896f9 | 15,548 |
import sympy
def exprOps(expr):
"""This operation estimation is not handling some simple optimizations that
should be done (i.e. y-x is treated as -1*x+y) and it is overestimating multiplications
in situations such as divisions. This is as a result of the simple method
of implementing this function ... | b6255707ef7475c893d9325358e7666b95c0e7c8 | 15,549 |
def ellipsis_reformat(source: str) -> str:
"""
Move ellipses (``...``) for type stubs onto the end of the stub definition.
Before:
.. code-block:: python
def foo(value: str) -> int:
...
After:
.. code-block:: python
def foo(value: str) -> int: ...
:param source: The source to reformat.
:re... | 162d9d863f7316bee87a04857366a7f78f68d75b | 15,550 |
def build_wtk_filepath(region, year, resolution=None):
"""
A utility for building WIND Toolkit filepaths.
Args:
region (str): region in which the lat/lon point is located (see
`get_regions`)
year (int): year to be accessed (see `get_regions`)
resolution (:obj:`str`, option... | 93da894523a6517faaf4fa4976ba986a3719494c | 15,551 |
import logging
def init_doc(args: dict) -> dict:
""" Initialize documentation variable
:param args: A dictionary containing relevant documentation fields
:return:
"""
doc = {}
try:
doc[ENDPOINT_PORT_KEY] = args[ENDPOINT_PORT_KEY]
except KeyError:
logging.warning("No port fo... | afa20f89595eac45e924ecdb32f9ef169fc72726 | 15,552 |
def decode_entities(string):
""" Decodes HTML entities in the given string ("<" => "<").
"""
# http://snippets.dzone.com/posts/show/4569
def replace_entity(match):
hash, hex, name = match.group(1), match.group(2), match.group(3)
if hash == "#" or name.isdigit():
if hex == ... | 480a7ed8a37b05bc65d10e513e021b00fcb718c4 | 15,553 |
def convert2board(chrom, rows, cols):
"""
Converts the chromosome represented in a list into a 2D numpy array.
:param rows: number of rows associated with the board.
:param cols: number of columns associated with the board.
:param chrom: chromosome to be converted.
:return: 2D numpy array.
"... | 9897965550793f54e55ce2c66c95a7584a987a4e | 15,554 |
def filter_halo_pnum(data, Ncut=1000):
""" Returns indicies of halos with more than Ncut particles"""
npart = np.array(data['np'][0])
ind =np.where(npart > Ncut)[0]
print("# of halos:",len(ind))
return ind | 3c89eb263399ef022c1b5492190aff282e4410e8 | 15,555 |
def _preprocess_sgm(line, is_sgm):
"""Preprocessing to strip tags in SGM files."""
if not is_sgm:
return line
# In SGM files, remove <srcset ...>, <p>, <doc ...> lines.
if line.startswith("<srcset") or line.startswith("</srcset"):
return ""
if line.startswith("<refset") or line.start... | 0a482c5ccf2c001dfd9b52458044a1feaf62e5b9 | 15,556 |
def discover(using, index="*"):
"""
:param using: Elasticsearch client
:param index: Comma-separated list or wildcard expression of index names used to limit the request.
"""
indices = Indices()
for index_name, index_detail in using.indices.get(index=index).items():
indices[index_name] =... | 32a53f15b0db3ba2b2c092e8dbd4ffdf57f133c8 | 15,557 |
from datetime import datetime
def quote_sql_value(cursor: Cursor, value: SQLType) -> str:
"""
Use the SQL `quote()` function to return the quoted version of `value`.
:returns: the quoted value
"""
if isinstance(value, (int, float, datetime)):
return str(value)
if value is None:
... | 17887be2440563a1321708f797310eb8f1731687 | 15,558 |
def create_admin_nova_client(context):
"""
Creates client that uses trove admin credentials
:return: a client for nova for the trove admin
"""
client = create_nova_client(context, password=CONF.nova_proxy_admin_pass)
return client | 3fdd56ae419b5228b209a9e00fb8828c17a0d847 | 15,559 |
def page_cache(timeout=1800):
"""
page cache
param:
timeout:the deadline of cache default is 1800
"""
def _func(func):
def wrap(request, *a, **kw):
key = request.get_full_path()
#pass chinese
try:
key = mkey.encode("utf-8")
except Exception, e:
key = str(key)
data = None
try:
d... | ca5be8d6ad1c1d0e627e2e22dbe44532d20af5cd | 15,560 |
def get_available_games():
"""Get a list of games that are available to join."""
games = Game.objects.filter(started=False) #pylint: disable=no-member
if len(games) == 0:
options = [('', '- None -')]
else:
options = [('', '- Select -')]
for game in games:
options.append((game... | 245d85ce623ffe3ed9eb718aafaf7889c67dada6 | 15,561 |
def process_ps_stdout(stdout):
""" Process the stdout of the ps command """
return [i.split()[0] for i in filter(lambda x: x, stdout.decode("utf-8").split("\n")[1:])] | c086cc88c51484abe4308b3ac450faaba978656e | 15,563 |
import shlex
def chpasswd(path, oldpassword, newpassword):
"""Change password of a private key.
"""
if len(newpassword) != 0 and not len(newpassword) > 4: return False
cmd = shlex.split('ssh-keygen -p')
child = pexpect.spawn(cmd[0], cmd[1:])
i = child.expect(['Enter file in which the key is',... | ee84bdccee24ea591db6d9c82bfce8374d1a420d | 15,564 |
def get_display_limits(VarInst, data=None):
"""Get limits to resize the display of Variables.
Function takes as argument a `VariableInstance` from a `Section` or
`Planform` and an optional :obj:`data` argument, which specifies how to
determine the limits to return.
Parameters
----------
Va... | d4864fccd8c282033d99fdc817e077d3f6d5b434 | 15,565 |
def plot_layer_consistency_example(eigval_col, eigvec_col, layernames, layeridx=[0,1,-1], titstr="GAN", figdir="", savelabel="", use_cuda=False):
"""
Note for scatter plot the aspect ratio is set fixed to one.
:param eigval_col:
:param eigvec_col:
:param nsamp:
:param titstr:
:param figdir:
... | 38191663fcf1c9f05aa39127179a3cbf5f29b219 | 15,566 |
def min_vertex_cover(left_v, right_v):
"""
Use the Hopcroft-Karp algorithm to find a maximum
matching or maximum independent set of a bipartite graph.
Next, find a minimum vertex cover by finding the
complement of a maximum independent set.
The function takes as input two dictionaries, one for t... | a94aaf6dd07b98e7f5a77b01ab6548bc401e8b03 | 15,567 |
def neighbor_dist(x1, y1, x2, y2):
"""Return distance of nearest neighbor to x1, y1 in x2, y2"""
m1, m2, d12 = match_xy(x2, y2, x1, y1, neighbors=1)
return d12 | 91b67e571d2812a9bc2e05b25a74fbca292daec7 | 15,568 |
import requests
def add_artist_subscription(auth, userid, artist_mbid):
"""
Add an artist to the list of subscribed artists.
:param tuple auth: authentication data (username, password)
:param str userid: user ID (must match auth data)
:param str artist_mbid: musicbrainz ID of the artist to add
... | 770be84ec9edb272c8c3d8cb1959f419f8867e1d | 15,569 |
from pathlib import Path
import pickle
def get_built_vocab(dataset: str) -> Vocab:
"""load vocab file for `dataset` to get Vocab based on selected client and data in current directory
Args:
dataset (str): string of dataset name to get vocab
Returns:
if there is no built vocab file for `da... | b03daba815ccddb7ff3aee2e2eac39de22ff6cff | 15,570 |
from typing import Optional
from typing import Iterable
def binidx(num: int, width: Optional[int] = None) -> Iterable[int]:
""" Returns the indices of bits with the value `1`.
Parameters
----------
num : int
The number representing the binary state.
width : int, optional
Minimum n... | 70d1895cf0141950d8e2f5efe6bfbf7bd8dbc30b | 15,571 |
import math
def distance_vinchey(f, a, start, end):
"""
Uses Vincenty formula for distance between two Latitude/Longitude points
(latitude,longitude) tuples, in numeric degrees. f,a are ellipsoidal parameters
Returns the distance (m) between two geographic points on the ellipsoid and... | df5ae92a12af6ab656af65a12145436089202cf2 | 15,573 |
def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
# x1、y1、x2、y2、以及score赋值
dets = np.array(dets)
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
#每一个检测框的面积
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
#按照score置信度降序排序
order = score... | d85822e8076bf1695c6f9e7b7271b21572ebf7d6 | 15,574 |
def _romanize(word: str) -> str:
"""
:param str word: Thai word to be romanized, should have already been tokenized.
:return: Spells out how the Thai word should be pronounced.
"""
if not isinstance(word, str) or not word:
return ""
word = _replace_vowels(_normalize(word))
res = _RE... | 5e464faa1011893eb63f1f9afedd42768a8527c8 | 15,575 |
def lookup_beatmap(beatmaps: list, **lookup):
""" Finds and returns the first beatmap with the lookup specified.
Beatmaps is a list of beatmap dicts and could be used with beatmap_lookup().
Lookup is any key stored in a beatmap from beatmap_lookup().
"""
if not beatmaps:
return None
fo... | fa5f126502b5398934882139f01af8f4f80e1ea5 | 15,576 |
def scott(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Scott similarity
Scott, W. A. (1955).
Reliability of content analysis: The case of nominal scale coding.
Public opinion quarterly, 321-325.
Args:
x (BinaryFeatureVector): binary f... | 6b950cb2b716d2e93638b169682cdd99230cbb89 | 15,577 |
import xmlrunner
def get_test_runner():
"""
Returns a test runner instance for unittest.main. This object captures
the test output and saves it as an xml file.
"""
try:
path = get_test_dir()
runner = xmlrunner.XMLTestRunner(output=path)
return runner
except Exception, ... | 6b2db3207c278a7f07ed6fd7922042beea1bfee7 | 15,578 |
def _construct_capsule(geom, pos, rot):
"""Converts a cylinder geometry to a collider."""
radius = float(geom.get('radius'))
length = float(geom.get('length'))
length = length + 2 * radius
return config_pb2.Collider(
capsule=config_pb2.Collider.Capsule(radius=radius, length=length),
rotation=_vec... | a4bddb7c64468515d3a36ebaac22402eeb4f16b0 | 15,579 |
def file_root_dir(tmpdir_factory):
"""Prepares the testing dirs for file tests"""
root_dir = tmpdir_factory.mktemp('complex_file_dir')
for file_path in ['file1.yml',
'arg/name/file2',
'defaults/arg/name/file.yml',
'defaults/arg/name/file2',
... | 834e0d850e7a7dd59d792e98ed25b909d5a20567 | 15,580 |
from typing import Iterable
def path_nucleotide_length(g: BifrostDiGraph, path: Iterable[Kmer]) -> int:
"""Compute the length of a path in nucleotides."""
if not path:
return 0
node_iter = iter(path)
start = next(node_iter)
k = g.graph['k']
length = g.nodes[start]['length'] + k - 1... | 612cff39bcf859a995d90c22e2dacb54e9c0b4c9 | 15,581 |
def extract_static_links(page_content):
"""Deliver the static asset links from a page source."""
soup = bs(page_content, "html.parser")
static_js = [
link.get("src")
for link in soup.findAll("script")
if link.get("src") and "static" in link.get("src")
]
static_images = [
... | 8ea99171d55db182fe4265042c84deca36176d84 | 15,582 |
def zero_inflated_nb(n, p, phi=0, size=None):
"""Models a zero-inflated negative binomial
Something about hte negative binomail model here...
This basically just wraps the numpy negative binomial generator,
where the probability of a zero is additionally inflated by
some probability, psi...
P... | c20f28b33e070e035979093e6ebb9ed10611c5dd | 15,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.