content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def manager_from(*mixins, **kwds):
"""
Returns a Manager instance with extra methods, also available and
chainable on generated querysets.
(By George Sakkis, originally posted at
http://djangosnippets.org/snippets/2117/)
:param mixins: Each ``mixin`` can be either a class or ... | baa145170f073b596769e6bc359a319f209b5ef8 | 66,096 |
def create_isolated_mask(pr, gt, label_id, output='fp'):
"""
Create a mask image by extracting only the isoated objects that are not overlaped by one of the masks.
Args:
pr ([type]): predicted mask
gt ([type]): GT mask
output (str, optional): Type of mask to be created. 'fp', 'fn' c... | e015a250f680d5b66e0dd1978b04337f1a0b29a5 | 66,097 |
import requests
def get_bot_message_by_id(message_id, bot_id):
"""
This function will get the message content using the {message_id}
:param message_id: Webex Teams message_id
:param bot_id: the Bot id to validate message
:return: message content
"""
url = WEBEX_TEAMS_URL + '/messages/' + m... | b6ed1e3524983aea43c9b9dac69626f2576a2719 | 66,098 |
def extract_indices(idx_to_check, *args):
"""
Look if a given index j_gt is present in all the other series of indices (_, j)
and return the corresponding one for argument
idx_check --> gt index to check for correspondences in other method
idx_method --> index corresponding to the method
idx_gt... | c2de117417689d30d5b9a72f5bae07f12baf72ed | 66,099 |
from typing import Any
async def processing(
background_tasks: BackgroundTasks
) -> Any:
"""
Run dbt DELTA for all models
"""
taskid = libs.new_taskid()
background_tasks.add_task(dbt_run, taskid=taskid, full=False)
return dict(
taskid=taskid,
msg="Processing job has been se... | 183a9d4294d0d792b4429df573cef5d50314111e | 66,100 |
from mds_plugin import object_store
def create_bucket_import_pars(object_name_prefix, bucket_name, db_system_name,
compartment_id, config):
"""Creates the PARs needed for an import from a bucket
Args:
object_name_prefix (str): The prefix used for the object names
... | 5d376627c89d9af8e2483c610b2b8b7ced3a2878 | 66,101 |
def char_ngrams(s, n=3, token_fn=tokens.on_whitespace):
"""
Character-level n-grams from within the words in a string.
By default, the word boundary is assumed to be whitespace. n-grams are
not taken across word boundaries, only within words.
If a word's length is less than or equ... | dd74bf37434dfffa30583d99216597179615f9c5 | 66,102 |
def get_e_rtd_H_default():
"""定格燃料効率
Args:
Returns:
float: 定格燃料効率
"""
return 0.860 | 55f3aa6f96ba5e549ca77e56d63213b1f8761b56 | 66,103 |
def form_sent(request, slug, template="forms/form_sent.html"):
"""
Show the response message.
"""
published = Form.objects.published(for_user=request.user)
context = {"form": get_object_or_404(published, slug=slug)}
return render_to_response(template, context, RequestContext(request)) | 5682c7551b6ca9050df94246f01c0c7eec9bebf0 | 66,105 |
def parse_absolute_url(url):
"""Parse absolute URL
Returns the same result as werkzeug.urls.url_parse, but works on
absolute HTTP and HTTPS URLs only.
The result port is always an integer.
"""
parsed = url_parse(url)
if not parsed.scheme:
raise RelativeURLError(f"Expected an absolut... | 0dbab77b6957d26bee67b8f9e363c7bd07ed2fff | 66,106 |
from re import M
from typing import List
def TypespecOf(signal):
"""Reproduce a typespec for a given signal."""
if type(signal) is M.BitsSignal:
return Bits(signal.width, signal.signed, TypeMeta(signal.meta.sigdir))
elif type(signal) is M.ListSignal:
return List(
len(signal.f... | ec93e8d9d7e0d8919611ab22bd311fd70597db92 | 66,107 |
def get_camera_vector(f, hsize, vsize, hpixels, vpixels):
"""
Given the focal length of the camera, the physical size of the focal plane,
and the size of the image, obtain a vector of photogrammetric information
for each pixel.
Parameters
-----------
f : float
Focal length of camera... | 99b89e934b2193ceae9f476fc97212d7e0dfb517 | 66,108 |
def L_model_backward(AL: np.ndarray, Y: np.ndarray, caches: list,
AL_prime: np.ndarray = None, Y_prime: np.ndarray = None,
J_caches: list = None,
lambd: float = 0, gamma: float = 0) -> tuple:
"""
Implement backward propagation for the entire neural ... | 671bf0a89c81b55a98aee5d0a72edea80100a8cd | 66,109 |
def get_file_date_part(now, hour) -> str:
""" Construct the part of the filename that contains the model run date
"""
if now.hour < hour:
# if now (e.g. 10h00) is less than model run (e.g. 12), it means we have to look for yesterdays
# model run.
day = now.day - 1
else:
d... | 42c2beddccba755f66061364463f8ad759d3c020 | 66,110 |
def cond(parser: Parser, token: Token):
"""Prints some text conditionally
```html
{% cond {'works': True, 'does not work': 1 == 2} %}
```
Will output 'works'.
"""
dict_expression = token.contents[len('cond ') :]
return CondNode(dict_expression) | b59dc504f67530b7cf4c9c459d8faa52b4a91ec0 | 66,111 |
def PVT(prices):
"""
34. PVT价量趋势指标(Price and Volume Trend, PVT)
说明:价量趋势指标类似于能量潮(OBV),也是随收盘价变化而调整的累积成交量。
然而,OBV是加上当期收盘价高于前期收盘价的交易日的全部成交量和减去当期收盘价低于前期收盘价的交易日的全部成交量,
而PVT仅仅加上或减去日成交量的一部分。
计算方法:
PVT = (CLOSE-CLOSE[1])/CLOSE[1]*VOL+PVT[1]
PVT初始值= (CLOSE-CLOSE[1])/CLOSE[1]*VOL
:param price... | 775d2cc1accf4650da581845b3ef1505e3161f62 | 66,112 |
def _get_ax(line):
""" returns the direction of the line
[param] line: tuple or np.array of length 4, where 0,1 is point 1 and 3,4 is point 2
"""
if np.isclose(line[0],line[2]) and line[1] != line[3]:
return 1
else:
return 0 | e3bcb09506105b7b39b0d3196b1ae62dd92f720b | 66,113 |
import wave
def get_fns_seg_list(fns_list=[],
segment_mode='all',
fs=22050,
duration=1,
hop=None):
"""
return: fns_event_seg_list
[[filename, seg_idx, offset_min, offset_max], [ ... ] , ... [ ... ]]
... | e3aa9e5ec538e2d78bcb32914da2544121f14a82 | 66,114 |
import math
def add_dispatchers(project, dispatchers):
""" Adds Dispatchers to a project.
Side effect: Upon successful addition on the server, the object_id and global_id fields of
each Dispatcher in dispatchers will be updated to the values assigned by the server.
:param project:
... | 2d8153fba6b96f44a58436ca2424da57f3414ca7 | 66,115 |
from pathlib import Path
import tempfile
def get_basetemp() -> Path:
"""Return base temporary directory for tests artifacts."""
tempdir = Path(tempfile.gettempdir()) / "cardano-node-tests"
tempdir.mkdir(mode=0o700, exist_ok=True)
return tempdir | e34ffc5cae1373977f1b46ab4b68106e1bef3313 | 66,117 |
def pixel_zapping(xapt, yapt, allspec, plot=False):
""" Removes bad pixels by comparing each pixel
to its column's median."""
nloop=3
# Pixels expected to be outside sigma factor in image
nextra=5.
np.place(allspec, allspec<0, 0)
print('Negative pixels = ', np.sum(allspec<0))
# Zoom in ... | 89054cf488f3b79c32fe45be8df6d0647a0c1051 | 66,119 |
import torch
def multitask_loss2(batch, doc_mt_scores, sm):
"""
doc_mt_scores - bsz x seqlen x seqlen
N.B. rn this only considers entities that are repeated; should
really have it predict a dummy value for things not repeated
"""
bsz, seqlen, _ = doc_mt_scores.size()
loss = 0
reps = ... | 7a7b53c7b54c214d295a5aff55b40ed2291a69db | 66,120 |
def get_age_label(value):
"""
get the age label for a given age category
Parameters
----------
value: int
corresponds to a particular age range bucket
Returns
-------
"""
if value == 1:
return "0 - 7"
elif value == 2:
return "7 - 14"
elif value == ... | 302b5e0b9b17556226c2bedf9c12d04f76a79656 | 66,121 |
def deprocess_image(x):
"""Same normalization as in:
https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py
"""
# normalize tensor: center on 0., ensure std is 0.25
x = x.copy()
x -= x.mean()
x /= (x.std() + K.epsilon())
x *= 0.25
# clip to [0, 1]
x ... | 9401de1cb58053ebab31849b76983fe45a21e1ad | 66,122 |
def remove_duplicate_rows(df):
"""There appear to be 13 'completely' duplicate rows in the cBioPortal
sample-level clinical data file. Remove these duplicate rows from
the dataframe."""
exclude_indices_keep_false = df.index[df.duplicated(keep=False)]
exclude_indices_keep_first = df.index[df.duplic... | c5a5a0184dd760b4615cff4d2e58325f735bfb92 | 66,123 |
def _rio_uri(band: BandInfo) -> str:
"""
- file uris are converted to file names
- if also netcdf wrap in NETCDF:"${filename}":${layer}
- All other protocols go through unmodified
"""
if band.uri_scheme == 'file':
fname = str(uri_to_local_path(band.uri))
if _is_netcdf(band.fo... | 4c0b85324f878f198e2867d2d421e8cae856dca7 | 66,124 |
from typing import Union
from typing import Optional
def read(
filename: Text,
for_object: Union[Text, object],
as_format: Optional[Text] = None,
*args,
**kwargs,
) -> object:
"""
Reads file using the appropriate file format adaptor.
Args:
filename: Full filename of the file t... | 6467ac735fdfaaaa3f377e269a134801f45141d7 | 66,125 |
def experiment_order_batch_add(request, expt_id):
"""
Ajax add experiment order
"""
batch_order = request.POST.get('batch_order', None)
if batch_order:
try:
result = {
'status': 'success',
'objects': []
}
expt_info = get_... | e04207bab4cb832362e9a567cd231a304d4317b7 | 66,126 |
from pathlib import Path
def _from_polyline(polyline: 'Polyline', **kwargs) -> 'Path':
""" Returns a Path from a 2D/3D Polyline. """
path = Path()
if len(polyline.vertices) == 0 or \
polyline.is_polygon_mesh or \
polyline.is_poly_face_mesh:
return path
if polyline.is_3... | a657936ade2d74a25f490e415f25eca8b1410e1a | 66,127 |
import re
def urls_from_details(details):
"""Return list of URLs to objects from details page source."""
return re.findall(
r'<a href="(http://localhost:\d+/object/[^"]+)"',
details,
) | fc1f621574caac1cf7dc53f4c762bad826eb71e9 | 66,128 |
def validateAuth(conn,User,Auth):#takes parameter as dbCursor for db related process
"""Other parameters are the username and Auth to be validated """
try:
sqlStatement="""SELECT * FROM ijm_clientprograms WHERE IJM_Name='%s' AND IJM_Auth='%s'"""%(User,Auth)#sql statement
fetchData=conn.execute(sqlStatement)... | 129134458363dafde9801acfca834c1cd4cebe37 | 66,130 |
import pathlib
import random
def process_yelp(dataset_name='yelp', metadata=None, num_reviews=None, filename=None, random_seed=None):
"""Convert raw yelp data to a Dataset Options dictionary
Parameters
----------
num_reviews: int or None
if set, randomly sample this many reviews from the ... | 55cbd5fd8d7f2130b956ed90e68d9aa082398ef3 | 66,131 |
def new():
"""Endpoint to create new game id"""
return {'game_id': new_id()}, 200 | 4d37d683ffdd1e6b273ac631dbac72a14c097621 | 66,132 |
def edgemap(raw_data, energy_axis, edge):
"""
Inputs:
raw_data - SI
energy_axis - corresponding energy axis
edge - edge parameters corresponding to desired element defined by KEM convention
Outputs:
dummymap - edgemap
"""
xdim, ydim, zdim = np.shape(raw_data)
dummymap = np.zeros((xdim,ydim))
integration_sta... | b5812698c04dc6c1494d77bef7266656cc167bf1 | 66,133 |
def install_elevated(lfs_dir: str, verbose: bool, jobs: int) -> bool:
"""
Installs software as elevated user
:param lfs_dir: installation directory
:param verbose: if true print build messages
:param jobs: number of build jobs
:return: True if successfully installed False otherwise
"""
... | 47e77216b7d964aea567c2bcad5f78c10cf6e356 | 66,134 |
def _make_wave_command(channel, device_name, wave):
"""Creates a wave command string.
Args:
channel: Channel number
wave: A string or an integer. If a string, then wavedef is used as a
lookup table
Raises:
UnknownWaveformError: If a string is passed for wave and it's not found
in wavede... | ba93ae754582b8c939865b84b6dc3b2687b18109 | 66,135 |
def parse_operand_int6(token):
"""Attempts to parse a token as a 6-bit signed immediate value."""
failure = None
if token.token_type in ['NUMBER', 'HEX']:
operand = Obj()
operand.type = 'OPERAND'
operand.operand_type = 'IMMEDIATE'
if token.value < -32 or token.value > 31:
... | a0512599d2c47f42829f1e05ac98cae1f7a46c1a | 66,137 |
def index(pagenr = 1):
""" Index page. """
def prepare_context(conf):
context = {}
posts_per_page = conf['post_per_page']
posts = sorted(conf['posts'], key=lambda k: k['posted'], reverse=True)[(pagenr-1)*posts_per_page:(posts_per_page*pagenr)]
context['type'] = 'index'
... | 76c66ff982d5efb4b224300c87c5915bae391bdb | 66,139 |
def mutate_string(string, pos, change_to):
"""
Fastest way I've found to mutate a string
@ 736 ns
>>> mutate_string('anthony', 0, 'A')
'Anthony'
:param string:
:param pos:
:param change_to:
:return:
"""
string_array = list(string)
string_array[pos] = change_to
retur... | c6119076411b57f9ded2e899d40b6b82bb5f7836 | 66,140 |
def get_all_child_permissions_for_user():
"""
Get all valid child Permission objects for current user
return: list of Permission objects
"""
ac_manager = current_app.ac_manager
permission_keys = ac_manager.get_user_permissions()
return get_child_permissions(permission_keys) | a137764b00a8a87f05df20c559aeec5f417ada01 | 66,141 |
def count_unique(list_to_count):
"""Counnunmber of entries for each unique value in list
"""
uniques = {}
for element in list_to_count:
if element in uniques:
uniques[element] += 1
else:
uniques[element] = 1
return uniques | 085ecdd0e960ac0de05e60c05e5417ca6dba8aef | 66,142 |
def _get_field_type(column_info):
"""
Get the Django field type from the column's information.
@param IN column_info Xylinq column information object
@return A 2-element tuple: the name of the Django type class, and its attributes as a string
"""
xy_type = column_info.type
xy_type_precision... | 74c61b70e07fcef033895d153f67524909c258e2 | 66,144 |
def micd(x, y, k=3, base=2, warning=True, qin=None,qout=None):
""" If x is continuous and y is discrete, compute mutual information
"""
overallentropy = entropy(x, k, base, qin=qin,qout=qout)
if type(y)==np.ndarray:
y = y.tolist()
n = len(y)
word_dict = dict()
for i in range(len(y))... | 3930523a2c8d17be985269768d4d9b3ee7da8368 | 66,145 |
def with_last_degree(template_layers_config, degree):
"""
Change the degree of the last -- or actually penultimate -- layer in a
layered micro-service application, while keeping the average service time
for a user request constant.
"""
assert len(template_layers_config) >= 2
layers_config = ... | f09bec9e27586349c679a66070bc4bac0dcba5d1 | 66,147 |
def bench(n):
"""Just a benchmarking function for relative expected performance"""
items = [x for x in range(n)]
return sum([x ** 2 for x in items]) | 5d91d787aead273d264d6cbc7e3e1edfd17e342f | 66,148 |
def GetErrorOutput(error, new_error=False):
"""Get a output line for an error in regular format."""
line = ''
if error.token:
line = 'Line %d, ' % error.token.line_number
code = 'E:%04d' % error.code
error_message = error.message
if new_error:
error_message = 'New Error ' + error_message
retur... | 4661c74fcef9f13c0aad3d74e827d9eea20f86ef | 66,149 |
def deunicode(s):
"""Returns a UTF-8 compatible string, ignoring any characters that will not convert."""
if not s:
return s
return str(s.decode('utf-8', 'ignore').encode('utf-8')) | baaf99acec746c266059c07e03a1ee4a7e76f46a | 66,150 |
def binary_search(arr, elem):
"""Return the index of the given element within a sorted array."""
low = 0
high = len(arr) - 1
mid = 0
while low < high:
mid = (high + low) // 2
# Check if elem is present at mid
if arr[mid] < elem:
low = mid + 1
# If elem... | 944da4f1808735d6f8f40e9bcf81e6cc972a852f | 66,151 |
def has_id(user_id) -> TYPE_CHECK_FUNCTION:
"""
Checks if the author has the desired ID.
parameters:
coro: the function to check
"""
async def check(ctx: Context) -> bool:
return ctx.author.id == user_id
return check | 20ef91488d5ed49e764487fb8d238175d071fc62 | 66,152 |
def entropy_and_prob(d2=np.array([]), beta=1.0):
"""
Compute the perplexity and the P-row for a specific value of the
precision of a Gaussian distribution.
"""
# Compute P-row and corresponding perplexity
w = np.exp(-d2.copy() * beta)
sum_w = sum(w)
sum_w = np.maximum(sum_w, MACH... | 35cd9946bb5dd2346f858e52e945e191421c905c | 66,153 |
def constructUniformAllelicDistribution(numalleles):
"""Constructs a uniform distribution of N alleles in the form of a frequency list.
Args:
numalleles (int): Number of alleles present in the initial population.
Returns:
(list): Array of floats, giving the initial freq... | 45e834d2129586cb6ff182e1a8fe6ecb1ae582ae | 66,154 |
def sorted_versions(versions): # type: (t.List[str]) -> t.List[str]
"""Return a sorted copy of the given list of versions."""
return [version_to_str(version) for version in sorted(str_to_version(version) for version in versions)] | afde7e9e117e1c14cb1171a7c6e0fd8993f39266 | 66,155 |
def update_exchange_rates(request):
"""Return updated exchange rates."""
exchange_result = get_daily_currency_rates()
return Response({"updated_exchange_rates": exchange_result}) | db27a0d77af92c4b4175a0a37642c15cbf9cc92a | 66,156 |
import math
def rbo_min(S, T, p, k=None):
"""Minimum value of RBO as defined in equation (11).
"""
if not k:
k = min(len(S), len(T))
xk = overlap(S, T, k)
sum1 = sum((overlap(S, T, d) - xk) * p ** d / d for d in range(1, k + 1))
return (1 - p) / p * (sum1 - xk * math.log(1 - p)) | f7a904d9edeeaad0f225ff33c2a86225c59fa4e6 | 66,157 |
def SockPuppetDistance(signatures, df):
"""Wrapper func for L1 Distance Calculation"""
klds = KLDS(signatures)
cc = cross_categories(df)
return SPD(klds, cc) | 7c8c2a9c77cf939a06db303aadb8f2d4cb55b4fa | 66,158 |
from typing import Tuple
def find_two_entries(data: "np.array") -> Tuple["int", "int"]:
"""Check array for the two entries that sum to 2020."""
for idx, j in enumerate(data[:-1]):
for k in data[idx + 1:]:
if j + k == 2020:
return j, k | 24fe338ef23e39869633e51ed53808a769a76672 | 66,160 |
def get_cpu(board, addr):
""" Retrieve CPU. """
if board == 'd2000_dev':
cpu = 'd2000_x86'
else:
if addr == 'addr_arc':
cpu = 'se_arc'
else:
cpu = 'se_x86'
return cpu | 02dcb057d7c1ed178090c84c2baa8d7ca732b98b | 66,161 |
from datetime import datetime
def desired_dates(today=None, start_date=None): # today is provided as keyword arg for testing
"""
Return a list of contiguous dates from [today-n_days thru to today inclusive] as 'YYYY-mm-dd' strings, Ordered
from start_date thru today inclusive. Start_date may be:
1) a... | a90bc5de946546ec4a37a5acebb5cfd46950dcaf | 66,162 |
def sma(serie, look_back_delay):
"""Simple Moving Average"""
return serie.rolling(
window=int(look_back_delay),
center=False
).mean() | d584577e315827ec97c092feb54fbbda8cc43952 | 66,164 |
def canonicalize_dtype(dtype):
"""Canonicalise a dtype, skip if None."""
if dtype is not None:
return jax.dtypes.canonicalize_dtype(dtype)
return dtype | 53a6f9e9e0fb31a01ee7e767e080f468d268bd3b | 66,168 |
def id_record(rec):
"""Converts a record's id to a blank node id and returns the record."""
rec['id'] = '_:f%s' % rec['id']
return rec | 1ee5a9e9600299b56543c92a77cadb1826bb9bb7 | 66,169 |
from typing import Dict
from pathlib import Path
def _get_neume_dict(font_folder_path: str) -> Dict:
"""Search folder path for font configs, load them, and return in Dict.
:param font_folder_path: Path to font.
"""
font_config_dict = {}
for glyphname_path in Path(font_folder_path).rglob('glyphnam... | 2852ef3cc01af5c81d88ec8aeebaedd83fe28ae1 | 66,170 |
import cv2
from numpy import zeros, cumsum
def get_cum_frames_index_range(filename, start, end):
"""
returns a summed of frames as numpy array. The indecies comply with scimage
Addendum to dimension names and orders in scikit-image
Image type: 2D color video
coordinates: (time, row, col, channel)... | ace9be8151700134162cffe7aec1e15210f36bb9 | 66,171 |
def obj_ext(value):
"""
Returns extention of an object.
e.g.
For an object with name 'somecode.py' it returns 'py'.
"""
return value.split('.')[-1] | 7ef6f1009145a0acc543130c41d2082a14412b6d | 66,172 |
def multiclass_decision_tree_learning(examples: list, attributes: list,
parent_examples: list, classes: list):
"""
Decision tree learning algorithm as given in figure 18.5 in Artificial
Intelligence A Modern Approach.
:param examples: list of dictionaries containin... | 840a49529cbaf3d698b4982071560f6f40f5c4da | 66,173 |
import torch
def binary_hyperplane_margin(X, Y, w, b, weight=1.0):
""" A potential function based on margin separation according to a (given
and fixed) hyperplane:
v(x,y) = max(0, 1 - y(x'w - b) ), so that V(ρ) = ∫ max(0, y(x'w - b) ) dρ(x,y)
Returns 0 if all points are at least 1 away from ... | 0f038dc2ae9def9823b3f440a087ede52dcee717 | 66,174 |
def msrm(dem,
resolution,
feature_min,
feature_max,
scaling_factor,
ve_factor=1,
no_data=None
):
"""
Compute Multi-scale relief model (MSRM).
Parameters
----------
dem : numpy.ndarray
Input digital elevation model as 2D numpy ar... | 8468dbc6a9af9eb5437bd1c0d7f606750a4d6dfc | 66,175 |
def extract_number():
"""
Extract a tempered pseudorandom number based on the index-th value,
calling generate_numbers() every 624 numbers
"""
global index
global MT
if index == 0:
generate_numbers()
y = MT[index]
y ^= y >> 11
y ^= (y << 7) & 2636928640
y ^= (y << 15)... | b43c4dcf6f05110e389ecdd7ae58bc351bd6183c | 66,176 |
import click
def main(data_dir,
output_dir,
a_label,
b_label,
size_input,
bounds_a,
bounds_b,
num_classes,
as_volumes):
"""Console script for med_dataloader."""
click.echo(f"""\rGenerating dataset with following parameters:
data_dir: ... | da7641076e4e448b5fa42d2db6f91e05e90a5800 | 66,177 |
def fhhp_fromFile(data, ignoreBadLine=False, useUpper=False, storeOriginalName=True, flatValueFor=None):
"""
Parser for http headers from file-like object.
"""
# first line must be readed
if flatValueFor is None:
flatValueFor=FLAT_HEADERS
res={}
line=None
while True:
line=data.readli... | 451d4120cb4d0c71e8690704d3f3d29d15ce3486 | 66,178 |
import re
from pathlib import Path
def alt_matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
"""Patched matplotlib scraper which won't close figures.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
... | 6d7f1565c3d828e855312cf4be3413ed3fa7d2dd | 66,179 |
def named_textblock(context, name, position = None):
"""A text block that is not bound to a URL, but a name and position. Position is optional."""
return _get_textblock(context=context, url=name, position=position) | 1e7882924b9c668a22555a8bb25ee509563947d6 | 66,180 |
def get_scale_factor(height,width):
"""
This function returns the appropriate scale factor w.r.t to
a target size. Target size has been fixed to 5 megapixels.
Inputs:
height (int): Image height
width (int): Image width
Outputs:
scale factor
"""
TARGET_SIZE=5... | 238b9b19fa75149080ecb4ebb1f3380499596d9b | 66,181 |
def gen_c1():
""" __ consonants """
c1_ = list()
c1_.extend(stop)
c1_.extend(gen_fric_())
c1_.extend(affricate)
c1_.extend(gen_onset_appr_())
c1_.extend(trill)
c1_.extend(ejective)
return c1_ | a7b43a639786a3d091e6c1f310159a45015c7f70 | 66,182 |
def get_joint_adds(joint, model, parameters):
"""process a single joint"""
jointtype = joint['joint_parameters']['joint_type']
addfunc = {'Box': get_box_joint_adds,
'Tab-and-Slot': get_tabslot_joint_adds,
'Interlocking': get_interlock_joint_adds,
'Bolt': get_bolt... | 59b1b1ca4147d18cf79635d45e2b15b27b86cad9 | 66,183 |
def odd_parity(bits):
"""
Determines if the array has even or odd parity.
Returns True if odd, False if even.
Note: this is an extremely inefficient computation, fix later.
"""
count = sum(1 for x in bits if x==1)
return count % 2 | 5705df9b35761c57fa4160761198e2804fb23159 | 66,184 |
def _ensure_connection(fn):
"""Decorator that wraps MonitorSocket external methods"""
def wrapper(*args, **kwargs):
"""Ensure proper connect/close and exception propagation"""
mon = args[0]
already_connected = mon.is_connected()
mon.connect()
try:
ret = fn(*args, **kwargs)
finally:
... | 802e96a03c07e2629c69cd97680ff5a04517401c | 66,185 |
import random
import string
def generate_random_sample_str():
"""Generate a random sample string. Leading character must be either a letter or number,
the rest must be letter, number, '_' or '-', length = 16 .
"""
leading_letter = rand_alnum_generator()
remaining_letters = ''.join(random.choice(st... | b461c4d4d2d5b2f431655252f10dc5e6f4c2a652 | 66,186 |
import urllib
def parse_config(s3url, complain=True):
"""
parse beam config of beam run.
:param s3url: url to s3 output
:param complain: it will complain if there are many config values found with the same name
:return: dictionary config key -> config value
"""
s3path = get_output_path_f... | c7a6705a7d3a2166e51f5e75814e8571365b3543 | 66,187 |
def get_scan_settings(**kwargs):
"""Returns the scan settings as dictionary
>>> get_scan_settings()
{
'update_model': False,
'scheduled': False,
'subtask': 'Steady-State',
'output_during_subtask': False,
'continue_from_current_state': Fals... | 8a2d6ce21d464a46739c42d3a37e1f0d1756c144 | 66,188 |
import ast
def merge_df(df):
"""Merges columns in a dataframe of LingBuzz papers into one bag_of_words
column. The resulting dataframe is organized into two columns : (Title | bag_of_words).
Parameters
----------
df : dataframe to be merged by column into one bag_of_words column
"""
#prin... | 39ed0effb095435a34713721a9ab8dd024449081 | 66,189 |
from io import StringIO
def parse(text):
""" parse the text representation of an xml node
delegate to read()
Args:
text (str): string representation of an xml node
Return:
lxml.etree._Element: root, parsed xml node
"""
try: # Python2
node = StringIO(text.decode())
except AttributeError: #... | 6060716bb55a94a90002f4d233c480a18190cc43 | 66,190 |
def getMapSpkrs(lstOracleSpkrs, dfSpkrTimes):
"""
This function maps ground truth speakers to diarization system speakers on the assumption that
the maximum time overlaps in dfSpkrTimes reflect the intended mapping.
Inputs:
- lstOracleSpkrs: list of ground truth speakers, form: "['FEE029', 'FEE030'... | 2152ee61f5be4706314762253576aab78953a18c | 66,191 |
def demo_kd_too_large(
n_steps=20000,
kp=.01,
kd=1.,
kp_scan_range = (.001, .1),
kd_scan_range = (.1, 10),
n_k_points = 32,
x_cutoff = 0.01,
w_cutoff = 0.002,
w_fixed = False,
k_spacing = 'log',
seed = 1238
):
"""
We... | affabf185495484892110b7725177498d5311a8d | 66,192 |
def get_size_to_hide(sound_path, num_lsb):
"""
Returns the amount of bytes available for hiding with that amount of LSB
:param sound_path: Path to audio file
:param num_lsb: Number of LSBs to use
:return: Amount of bytes
"""
global n_samples
prepare(sound_path, num_lsb)
max_bytes_to... | 0c29bc777bae113cd596ecf0526ca644e3701082 | 66,194 |
def get_homologs(homologs_fname):
"""Extract the list of homolog structures from a list file
:param homologs_fname: file name with the list of homologs
:type homologs_fname: str
:returns homologs_list containing the pdb codes of the homolog structures in the input file
:rtype tuple
"""
hom... | 1db108f30a3ef274cba918c5e1c056c6797a5bca | 66,195 |
def types(func):
"""Used by bot handlers that respond with text.
ChatAction.Typing is called which makes the bot look like it's typing"""
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
bot.send_chat_action(
chat_id=update.message.chat_id,
action=tg.ChatAction.TYP... | 0ebaca7d577f5731d472114a8613272a3a94a72f | 66,196 |
import re
def verify_syslog_interface_shut(interface, server, output):
""" Verify log for interface shut message
Args:
interface ('str'): Interface to be verified
output ('obj'): Tcpdump output
server ('str'): Syslog server address
Returns:
True
... | 7da9755ed08ea58678cdb7113a140a8ed7e77de9 | 66,197 |
def list_files_folders(request_ctx, id, content_types=None, search_term=None, include=None, sort=None, order=None, per_page=None, **request_kwargs):
"""
Returns the paginated list of files for the folder or course.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext... | 73660fb738c60b633aeda612b992098886d82b39 | 66,198 |
def load_learned_warp_parameters(filepath):
"""Loads the pickle file of alignment parameters at filepath.
Args:
filepath: (str) A filepath to an alignment.npy file.
Returns:
Numpy alignment parameters of shape [S, H, W, 2] for aligning stacks using
libs.image_alignment where S is the number of panor... | 2d58b8568bcb26fdc344b46f3f9b4b919d79b3f2 | 66,201 |
def merge_relu(xgraph, bottom_Xs, X, top_Xs, **kwargs):
# type: (XGraph, List[XLayer], XLayer, List[XLayer]) -> XLayer
"""
Try to merge Relu layer into preceding
Convolution/Eltwise/BatchNorm/Scale layer
"""
changes = False
if 'ReLU' in X.type or 'pReLU' in X.type:
if len(bottom_Xs) ... | 9c174633cf67030b8a0e7e7a67c8a5529ce92a39 | 66,202 |
from typing import List
from typing import Optional
from typing import Dict
import tempfile
import asyncio
import shlex
def launch_cluster(
descs: List[MachineDesc],
nonce: str,
subnet_id: str,
key_name: Optional[str],
security_group_id: str,
instance_profile: Optional[str],
extra_tags: Di... | cf737d89a18c9f5238ef2ac608be2594ab38d0dd | 66,203 |
from typing import Iterator
def summary(x, axis=None, shorten=False, float_precision=2):
""" Return string of statistical summary given series `x`
{#:%s|mi:%s|q1:%s|md:%s|mn:%s|q3:%s|ma:%s|sd:%s}
"""
if isinstance(x, Iterator):
x = list(x)
if isinstance(x, (tuple, list, set)):
x = np.array(x)
me... | 926098bc1fcce47c1ece4c76daa452cc8b15ebf2 | 66,204 |
import requests
def macro_china_bond_public():
"""
中国-债券信息披露-债券发行
http://www.chinamoney.com.cn/chinese/xzjfx/
:return: 债券发行
:rtype: pandas.DataFrame
"""
url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bond-an/bnBondEmit"
payload = {
"enty": "",
"bondType": "",
"... | 9b9860d63cf6b14e4877306cadfb4ecfb514506c | 66,205 |
import json
def evaluate_summaries(summaries):
"""Evaluate a list of workload generator summary files."""
result = {}
t_median = []
t_max = []
t_min = []
t_average = []
t_percentile = []
failure_rates = []
num_machines = 0
for summary in summaries:
try:
wit... | f5cf8df1f78204b8513d80d0af07a6831e7965d6 | 66,206 |
def _gam_param(x, z):
""" Compute the parameters of a gamma density from data weighted points
Parameters
----------
x: array of shape(nbitem) the learning points
z: array of shape(nbitem), their membership within the class
Notes
-----
if no point is positive then the couple (1, 1) is r... | 08b1c10d745b76c30820d439401efdd4e59df207 | 66,208 |
from typing import List
import re
def identify_headers(lines: List[str]) -> List[str]:
"""
Filters a list of lines to the header lines.
Identifies headers of the 'leading-hashtag' type as well as
headers of the 'subsequent-line' type by using regex.
:param lines: List of header and text lines.
... | 46f463d6c4178d5a5bef76ecb02bd68046278633 | 66,209 |
def _generate_summary(sentences, sentenceValue, threshold):
"""get the summary: if value above the threshold
Args:
sentences (list): all sentences
sentenceValue (dict): the dict storing its value
threshold (int): threshold to select sentences
Returns:
(str): summary
"""... | 58f432dcc419288b9977d827abf1684d80e3a404 | 66,210 |
def select_FFNN_features(dataset,
shared_features=True,
shared_feature_list=None,
original_bert=False,
has_2=True,
):
"""Only sentence level features
Input:
dataset: the data in p... | da5ec4d44d296807c3dbabda57bb278e7ea9a56a | 66,211 |
def _GetFields(trace=None):
"""Returns the field names to include in the help text for a component."""
del trace # Unused.
return [
'type_name',
'string_form',
'file',
'line',
'docstring',
'init_docstring',
'class_docstring',
'call_docstring',
'length',
... | acf8a1c62853f7648082689002b3ced2689892fe | 66,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.