content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_parameter(name, **kwargs):
"""Create ArcPy parameter object using an attribute mapping.
Note that this doesn't check if the attribute exists in the default
parameter instance. This means that you can attempt to set a new
attribute, but the result will depend on how the class implements setat... | c58ca1a18e502cc47b85490157adf30f2306e3cf | 45,239 |
def title_match_ratio(title1, title2):
"""
Returns a number between 0 and 100, representing the percent
match (Levenshtein Distance) between book title1 and book title2,
after each has been normalized.
"""
title1 = normalize_title_for_matching(title1)
title2 = normalize_title_for_matching(ti... | 5855f0dcf33e3f09a2e2936589c903ae9a7c26de | 45,240 |
def get_theme(txt, min_topic_freq=0.05):
"""return the most likely topic based on text"""
new_doc = get_tokens(txt)
new_doc_bow = dictionary.doc2bow(new_doc)
main_theme = sorted(lda.get_document_topics(new_doc_bow), key=itemgetter(1), reverse=True)[0]
return main_theme | 12157d2a2a3a2524698247e1436d43407dd933f1 | 45,241 |
def merge(lhs: _cpp.Dataset, rhs: _cpp.Dataset) -> _cpp.Dataset:
"""Merge two datasets into one.
:param lhs: First dataset.
:param rhs: Second dataset.
:raises: If there are conflicting items with different content.
:return: A new dataset that contains the union of all data items,
coor... | 3a4836fc2fb2b148f47b501685136e669a08bed3 | 45,242 |
def _extract_asm_mnemonic(asm):
"""
:param asm:
:type asm:
"""
return asm.split()[0].strip().upper() | 058d92ceaa3fc6cae505c795c58a4e3f231bc849 | 45,244 |
def calc_model_age(t2_parent, t1_parent, t2_daughter, t1_daughter,
decay_constant):
"""Calculate the model age of a sample. NOTE: THIS FUNCTION IS UNDER
TESTING AND MAY NOT GIVE THE CORRECT ANSWER!
Parameters
----------
t2_parent : float
The measured parent composition.
... | f8d0e501a3b1b354c5195503b4ed4495106c7923 | 45,245 |
def Tri(a, b, c, tag=None):
"""
A triangular random variate
Parameters
----------
a : scalar
Lower bound of the distribution support (default=0)
b : scalar
Upper bound of the distribution support (default=1)
c : scalar
The location of the triangle's peak (a <= c ... | 2050e2331e6fac0c54a992aeee9d24bd74e994b9 | 45,246 |
def reverse_match(text, dict_word, longest_term):
"""
反向最長匹配
參數 text : 要分詞的文字
參數 dict_word : 繁體中文詞語字典
參數 longest_term : 字典中最長詞語的長度
回傳值 : 一個串列 內部元素為 詞語的(起始索引,結束索引)
"""
result_list = []
stack = [] #因為反向最長匹配是由後往前進行分詞 所以使用堆疊的資料結構
end = len(text) - 1
while end... | 860292300f1842195958d535e3926ca27bd1cece | 45,247 |
def get_mean_ztf_alert_braai(_db, ra, dec):
"""
Cross-match by position and get mean alert braai score
"""
try:
ra_geojson = float(ra)
# geojson-friendly ra:
ra_geojson -= 180.0
dec_geojson = float(dec)
''' catalogs '''
catalog = 'ZTF_alerts'
... | edb0fb4768577464c93739332f39d747be12b138 | 45,250 |
def get_spaces(depth):
"""returns the required number of spaces
for indentation purpose"""
return ' ' * (depth * 4 - 2) | f59faaa963b8f1c16e20925b088eb1b7b8fda953 | 45,251 |
def load_webcat_data(webcat_csv):
""" Create a dictionary that maps from eids to lists with webcat data"""
table = generate_form.csv_to_numpy(webcat_csv, FIRST_ROW)
data = {}
for i in range(table.shape[0]):
eid = table[i, USER].strip().lower()
data[eid] = list(table[i, :])
return da... | 4f4f38b1c6eb0e7466b866b3ff77e4243c3eaaa0 | 45,252 |
import torch
import time
def get_pbo_pe_comparisons(
outcome_X,
train_comps,
problem,
utils,
init_round,
total_training_round,
comp_noise_type,
comp_noise,
pe_strategy,
):
"""
Generate TS-based comparisons on previously observed points
Args:
outcome_X ([type]):... | 0e50cfcbddb8119f2a7369dcf2aaef566ee1f84f | 45,253 |
import asyncio
async def _named_spooled_temporary_file(max_size=0, mode='w+b', buffering=-1,
encoding=None, newline=None,
suffix=None, prefix=None, dir=None,
loop=None, executor=None):
"""Open a... | 5ae67aed895a6583d6ff51b8db16dba2a7c6d548 | 45,254 |
def Covariance4D2Correlation4D(Cov_MPMB):
"""It normalizes each element of the 4-D Multi-Polarimetric Multi-Baseline
with respect to the corresponding diagonal terms.
INPUT
Cov_MPMB: [Nimm*Npol x Nimm*Npol x Nr x Na] Covariance matrices
OUTPUT
Corr_MPMB: [Nimm*Npol x Ni... | 44a24db1839f8fcfca0c368de226b246e4bcdee9 | 45,255 |
from typing import Union
from typing import List
def text_pos(text: Union[StringView, str],
line: int, column: int,
lbreaks: List[int] = []) -> int:
"""
Returns the text-position for a given line and column or -1 if the line
and column exceed the size of the text.
"""
if ... | 35534a25e00bc0086c0cb4bd22391385622de77e | 45,257 |
def formatList(inputList):
"""
Formats a list of items to html unordered list
:param inputList: list of items to be formatted
"""
report = HTML()
htmlList = report.ul
for val in inputList:
val = str(val)
htmlList.li(val)
return report | 1e816e5d1390a72c1a13dff47e0615dc621dc861 | 45,258 |
async def get_images_list(
request: Request,
page: schemas.PageRequest,
):
"""
According to params to get images list
:param request: pony ORM
:param page: page_num page_size To decide how many images return
:return: List[image_url]
"""
with request.pony_session:
imag... | 877337892fc4bcf44cdde9f4147fdab0693bf81d | 45,260 |
from typing import List
def _get_det_bboxes(
pred: List[dict], labels: List[str], im_path: str = None
) -> List[DetectionBbox]:
""" Gets the bounding boxes and labels from the prediction object
Args:
pred: the output of passing in an image to torchvision's FasterRCNN
model
labels:... | c145842b8c4e2172646647ffd701c4c6ef2e2776 | 45,261 |
def contrastive_loss_test(y_true, dist):
"""Test function above using implementation with numpy instead tensors."""
margin = P.margin
return y_true * np.square(dist) + (1 - y_true) * np.square(np.max(margin - dist, 0)) | 90f456178b71fbc030ff769c9d1f438df01d23b6 | 45,264 |
def verify_password_hash(password: str, password_hash: str) -> bool:
"""
Helper function for verifying hashed password against
plain password.
Args
----
password: str
password_hash: str
Returns
-------
bool (Confirming if password is same as ... | 3bec34b48dce60f3b2d836749d76c548239343f2 | 45,265 |
def _get_project_results_for_jobs(jobs):
"""Return projects for jobs."""
projects = {}
for job in sorted(jobs, key=lambda j: j.name):
project_name = job.get_environment().get('PROJECT_NAME', job.name)
if project_name not in projects:
projects[project_name] = {'name': project_name, 'jobs': []}
i... | a4637710daf2f4ed9caf31d49fb5db8ff5660d74 | 45,266 |
import re
def untex(s):
"""Replace tex constructs with unicode"""
s = s.replace('$^{\circ}$', degree)
s = re.sub(emph, '<i>\g<emph_text></i>', s)
s = s.replace('\&', '&')
s = s.replace(r'$\beta$', beta)
s = s.replace(r'{\AE}', 'Æ')
s = s.replace(r'{\O}', 'Ø')
s = s.replace(r'{\AA}', 'Å... | 624de244ed86446f504ae837a5b868f71ef8b81f | 45,267 |
import re
def _clean(arr):
"""Convert ratio values for missing pieces of the tax into "unclassified"
and remove empty entries.
Rules:
- if all the cols are unclassified then remove row.
- if there is no classification for either genus, subfamily or family then remove row.
- collaps... | c898fe0b9ecf6afef47f76a8d4f74947a0df389f | 45,268 |
def to_categorical(batch, num_classes):
"""
Converts a batch of length-padded integer sequences to a one-hot encoded sequence
:param batch:
:param num_classes:
:return:
"""
b, l = batch.shape
out = np.zeros((b, l, num_classes))
for i in range(b):
seq = batch[0, :]
... | aa14fcb88c135c15ed9c8b6d24fa5c72bcbbffa7 | 45,269 |
def format_summary(translation):
""" Transforms the output of the `from_batch` function
into nicely formatted summaries.
"""
raw_summary, _, _ = translation
summary = (
raw_summary.replace("[unused0]", "")
.replace("[unused3]", "")
.replace("[PAD]", "")
.replace("[unu... | a23fd464fdfa1efa5f8652d110bfff12919cf92a | 45,271 |
def splitintopolygons(polygons,d):
"""
Give a 1d array of length (N*(d*(d+1))), consisting of a series of N simplexes. Each simplex
has d+1 locations, each location is d long. For example, for 2d:
[(x1,y1),(x2,y2),(x3,y3)][(x1,y1),(x2,y2),(x3,y3)]...
d = dimensions
... | 2a1afaa2fefd5dfece9b77c56e033e71c00c20df | 45,272 |
def read_image(filename):
"""
Reads a filename of an image as PIL pytorch format image. Returns the image
:param filename: Path to image
:return: PIL Image
"""
return Image.open(filename) | 2dac9364031214a9e1351e878415c512aecd098b | 45,274 |
def normalise(x):
"""
Normalises a given 3D vector.
Parameter:
x - a 3D vector that is an array.
"""
if x is not None and len(x) == 3:
return x/np.sqrt(np.dot(x,x))
else:
raise Exception("Three coordinates are required in the array.")
return None | f65417c142cc564c8670d61d5e186042a3edf968 | 45,275 |
def sequence_id(sqlite_connection):
"""
Функция возвращает список из id всех остановок
"""
try:
cur = sqlite_connection.cursor()
cur.execute("SELECT _id FROM stopsker")
seq = list()
for elem in cur.fetchall():
seq.append(int(elem[0]))
except Exception a... | f73352b977c2c96a378985899f02674ab0c2cb14 | 45,276 |
def asin(x):
"""
Computes inverse sine element-wise.
:param x: y-coordinate on the unit circle.
:type x: array
:return: The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].
"""
return _cur_framework(x).asin(x) | bc7d5f7c8fb7a73c6eb777dcdca9b08d1cba846b | 45,277 |
import socket
from typing import cast
def sockaddr_from_tupe(addr):
"""
Converts a socket address tuple (host, port) to a proper socketaddr_*
C struct.
@param addr:
@return:
"""
if ":" in addr[0]:
family = socket.AF_INET6
if len(addr) == 4:
addr, port, flowinf... | 90b06bf907fafc401524a4d612f9b7dfb3f19295 | 45,278 |
def add_matches(flight_matches, flight_ids):
"""
Add new matches to the flight_ids dict.
Returns the number of newly matched flights.
"""
matches = 0
for i in flight_matches.index:
prev_id = flight_matches.loc[i, 'FLIGHT_ID_x']
next_id = flight_matches.loc[i, 'FLIGHT_ID_y']
... | 93d086cd580ac13622c4acaa359fa2a65b718ff3 | 45,279 |
async def handle_command(
request: Request,
response: Response,
background_tasks: BackgroundTasks,
x_slack_request_timestamp: int = Header(None),
x_slack_signature: str = Header(None),
db_session: Session = Depends(get_db),
):
"""Handle all incomming Slack commands."""
raw_request_body =... | 38eac9e1b54ec35e201a4df99430f84a7560b5c9 | 45,280 |
def parse_registry_url(registry_url):
"""
Given an AWS ECR registry URL, parses out the AWS Account ID and Region
>>> aid, region = parse_registry_url('http://12345.dkr.ecr.us-west-2.amazonaws.com')
('12345', 'us-west-2')
>>> aid, region = parse_registry_url('12345.dkr.ecr.us-west-2.amazonaws.com'... | 9df231b3f067dadc4fd248d9b15b8228cdcb7b00 | 45,282 |
def add_zone_ideal_loads_energy(idf):
"""add fmu output of
- Zone Ideal Loads Zone Total Heating Energy
- Zone Ideal Loads Zone Total Cooling Energy
"""
idf = ensure_contains(
idf,
'EnergyManagementSystem:GlobalVariable',
'gv_the')
idf = ensure_contains(
... | 6cee5da2f7159ffe88d0ee1195a7745e6139b594 | 45,284 |
def _entropy(data, group_pop_var, total_pop_var):
"""Calculate Entropy index.
Parameters
----------
data : pandas.DataFrame or geopandas.GeoDataFrame
Dataframe or geodataframe if spatial index holding data for location of interest
group_pop_var : string
Variable containing the popul... | 3076e43ba227d426e4a4680b31f61d94511c1065 | 45,285 |
import scipy
def Delta_calc(airtemp=scipy.array([])):
"""
Function to calculate the slope of the temperature - vapour pressure curve
(Delta) from air temperature T:
.. math::
\\Delta = 1000 \\cdot \\frac{e_s \\cdot 4098}{(T + 237.3)^2}
where es is the saturated vapour pressure at tempera... | bdae190a64deb5734e21b40898ec8c65cb9da2e0 | 45,286 |
def determineRotation(steroid_orientation,reference_orientation,cutoff=1e-2):
"""
Only does rotation if angle differs significantly from 0 or pi. This
minimizes the number of transformations that are done. At the end, we
then decide the correct way to describe the signs of each flip.
"""
... | 5e22633ee0c90f0fbbab655ce6316fee487c7650 | 45,287 |
def make_survey_and_score(theta,args):
"""
Wrapper for score_survey. Makes a new field_list, then scores the stars in star_list.
Parameter
---------
theta : list
Should be a list of length N_fieldx2, with first N_field entries being RAs, next
N_field entries being Decs.
arg... | e0df37f12881eeaa6b3efe7dfb9a2fd4a10e289b | 45,288 |
def crawler1(request):
"""
Hello world
"""
# 方案一的代码
code_crawler1_1_path = crawler_code_dir / 'crawler1_1.py'
code_crawler1_1 = open(code_crawler1_1_path).read()
# 方案二的代码
code_crawler1_2_path = crawler_code_dir / 'crawler1_2.py'
code_crawler1_2 = open(code_crawler1_2_path).read()
... | cf5785e7f27fb2502e760a2270666898b84b2093 | 45,289 |
import random
from unittest.mock import patch
def test_sample_independent_int_loguniform_distributions() -> None:
"""Test sampling from int distribution returns integer."""
study = optuna.create_study()
def int_value_fn(idx: int) -> float:
random.seed(idx)
return random.randint(0, 100)
... | 55e10a9219c28282eb28062fbfdf8ad3083765fb | 45,290 |
def get_data_source_dropdown_options(dataSource, dataType, language):
"""Creates and returns the dropdown options for each data source.
The dropdown options include the label, the value and the title
for each dropdown item.
Parameters
----------
dataSource : str
The name of the data so... | 1e49eea9a5ee5a265fb06657967cc75271330218 | 45,292 |
def Run(args):
"""Adds a binding to the IAM policy for a Google Cloud Function.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The updated IAM policy.
"""
function_ref = args.CONCEPTS.name.Parse()
return util.AddFunctionIamPolicyB... | 60ddc3d062781d1caab39e2627bcfb1d65f0867b | 45,293 |
def cifar10_resnet23_prediction(image, maps=64,
test=False):
"""
Construct Resnet23 as reference.
"""
# Residual Unit
def res_unit(x, scope_name, dn=False):
C = x.shape[1]
with nn.parameter_scope(scope_name):
# Conv -> BN -> Relu
... | f7c2c013a9c56ef176e3b82a20932d8c5a7c3398 | 45,294 |
import types
def dshape_to_alchemy(dshape, primary_key=frozenset()):
"""
>>> dshape_to_alchemy('int')
<class 'sqlalchemy.sql.sqltypes.Integer'>
>>> dshape_to_alchemy('string')
<class 'sqlalchemy.sql.sqltypes.Text'>
>>> dshape_to_alchemy('{name: string, amount: int}')
[Column('name', Tex... | 7cf93fc59b0091dc0e8836985103093c35e5a06e | 45,295 |
def parse_percentiles(percentiles):
"""Parse lists of percentile values in (0,100) range.
Examples:
.2
10,15,99.9
"""
def parse_percentile(val):
try:
result = float(val)
if result <= 0 or result >= 100:
raise ValueError()
except ValueError:
raise ArgumentTypeEr... | 286c0d7383775d4fd9d1015090fa99e27af94df3 | 45,296 |
def get_requirements_from_file(requirements_file):
"""
Get requirements from file.
:param str req_file: Name of file to parse for requirements.
:return: List of requirements
:rtype: list(str)
"""
requirements = []
with open(requirements_file) as f:
for line in f:
lin... | 5ec6ad1f4c2b22aae1cfa7eb3888b3279ffeca31 | 45,298 |
from typing import Tuple
from typing import List
def extract_encoded_headers(payload: bytes) -> Tuple[str, bytes]:
"""This function's purpose is to extract lines that can be decoded using the UTF-8 decoder.
>>> extract_encoded_headers("Host: developer.mozilla.org\\r\\nX-Hello-World: 死の漢字\\r\\n\\r\\n".encode("... | d1f3a371419b81b0e7ede1a7f90401cf7a89559f | 45,299 |
def formatted_loss_components_string(components: dict) -> str:
"""
Formats the components returned by calc_LV_Lbeta
"""
total_loss = components['L_V']+components['L_beta']
fractions = { k : v/total_loss for k, v in components.items() }
fkey = lambda key: f'{components[key]:+.4f} ({100.*fractions... | 717419a5ddccc0c3b020b6412cd497e5d67c8602 | 45,302 |
from typing import Union
def teardown_cluster(cluster_config: Union[dict, str]) -> None:
"""Destroys all nodes of a Ray cluster described by a config json.
Args:
cluster_config (Union[str, dict]): Either the config dict of the
cluster, or a path pointing to a file containing the config.
... | 8cf2a3ab7f576980a3122b6d62f9c826b90158f1 | 45,303 |
def _get_placeholders():
"""Returns placeholders for the image and segmentation."""
img = tf.placeholder(dtype=tf.float32, shape=_IMAGE_SHAPE)
seg = tf.placeholder(dtype=tf.float32, shape=_SEGMENTATION_SHAPE)
return img, seg | 31652c8aef5d295295b14713485b0d6311973ccc | 45,304 |
def _get_mult_function(mt: sparse.COO):
"""
Get a function similar to `` lambda a, b: np.einsum('i,ijk,k->j', a, mt, b)``
Returns
-------
func : function (array_like (n_dims,), array_like (n_dims,)) -> array_like (n_dims,)
A function that computes the appropriate multiplication
"""
... | 36b5a3bc177b857f443eea45530ae03bfe5f7afa | 45,305 |
from saq.analysis import _JSONEncoder
import json
def submission_target_buffer(self,
description,
analysis_mode,
tool,
tool_instance,
type,
eve... | 662fd20700547673ea9da6d01659e56e0fe26a6d | 45,307 |
def autoreturn(tree, *, syntax, **kw):
"""[syntax, block] Implicit "return" in tail position, like in Lisps.
Each ``def`` function definition lexically within the ``with autoreturn``
block is examined, and if the last item within the body is an expression
``expr``, it is transformed into ``return expr`... | 8bc197d55699c1b948891ef48454e2f3c812405e | 45,308 |
def filter_ignore(annotations, filter_fns):
""" Set the ``ignore`` attribute of the annotations to **True** when they do not pass the provided filter functions.
Args:
annotations (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of annotations
... | f59e6c481eb744245ae9503ae07ed88d1f3f8253 | 45,309 |
def load_image_stack(topdir, filename):
"""
Load ome.tif image stack of either 1,2,3 images
Differenciates layers of images as either "left" or "right" image
Rotates images 90 degrees and stiches left and right side together
Returns the loaded left, right and stiched images.
"""
fulldatap... | d6a56b4b16b9eb8b67707016213b23e6b3af7460 | 45,310 |
def update_dict_params_for_calibration(params):
"""
Update some specific parameters that are stored in a dictionary but are updated during calibration.
For example, we may want to update params['default']['compartment_periods']['incubation'] using the parameter
['default']['compartment_periods_incubatio... | 8aaf9cb030076adfddb7c8d5740a2c8cc5c21c06 | 45,311 |
def mk_lt(ctx, x, y):
"""
mk_lt(Int_ctx ctx, Int_net x, Int_net y) -> Int_net
Parameters
----------
ctx: Int_ctx
x: Int_net
y: Int_net
"""
return _api.mk_lt(ctx, x, y) | 8d3f48a64cc96b7df5943e0fe560f707fbdb8644 | 45,312 |
def webServerDetection():
"""
webServerDetection works like this:
-First, program asks user to give IP addresses of web servers ten times.
-Then,it scans them via nmap.
-It writes details of each web server to a file called web.dat
"""
web = []
try:
# Take 10 input... | 9dde346ab5204ea5110ecc6e87174177ad9a5e6b | 45,313 |
def counting_sort(numbers):
"""Sort given numbers (integers) by counting occurrences of each number,
then looping over counts and copying that many numbers into output list.
Running time: O(n + k) where k is the range of numbers, because if k is really high then affects the run time significantly.
Memo... | 7123a215f685ff251c13cfd5210fe1887fe3795f | 45,314 |
def get_payment_balance() -> float:
""" Payment balance """
output = 0
payment_dicts = get_payments()
for payment_dict in payment_dicts["payments"]:
payment = Payment(payment_dict)
direction = payment.direction
if direction == DIRECTION_TRANSFER:
continue
op... | b1df2943f333937fdb5d9de2fb98fa67f7fe2ebd | 45,315 |
def round_to(value: float, target: float):
"""
Round price to price tick value.
"""
rounded = int(round(value / target)) * target
return rounded | 74a417e951be6921cb9208144834132b09607a15 | 45,316 |
def g_data(rgb_data, dim=ArrayDim.TWO):
"""
功能:获取一个 RGB 图像的 G 分量\n
参数:\n
rgb_data:一个图像的 rgb 数据(3维数组)\n
dim:指明返回值是2维数组还是3维数组\n
返回值:图像的 R 分量数组(是一个2维数组 or 3维数组)\n
"""
return _rgb_component_data(rgb_data, RGBComponent.G, dim) | d594b6121f436dbc395dcc8a44aca8d3f6372128 | 45,317 |
def self_replicator(params,
time,
gamma_max,
nu_max,
omega,
phi_Rb,
phi_Mb,
Kd_cpc=0.025,
Kd_cnt=5E-4,
phi_O = 0,
dil_ap... | 72009fb3a59cce7786f4830c22a00bf4edd6def9 | 45,318 |
def imei_get_subscribers_api(imei, **kwargs):
"""IMEI Subscribers API (version 2.0) GET route."""
return ImeiApi().get_subscribers(imei, **kwargs) | c29c5d4db0368f8de8e3636220ed6d6f3c795b65 | 45,319 |
def AvailableAccounts():
"""Get all accounts that have credentials stored for the CloudSDK.
This function will also ping the GCE metadata server to see if GCE credentials
are available.
Returns:
[str], List of the accounts.
"""
store = c_creds.GetCredentialStore()
accounts = store.GetAccounts() | S... | c2aa8463bb99295518943537abfeb9e53d968cfe | 45,320 |
def open(format, **kwargs):
"""
writer.open('.eps') will create a sl.writer instance
"""
if format not in known_formats:
raise WriterFormatError(format, known_formats)
return known_formats[format].open(kwargs) | 4637c2cbf360e88ad315880bc2cc854e2f3075e8 | 45,321 |
def smart_post_expression():
"""
This is the function to be called as the first argument for the AddKnobChanged callback later on.
Sets its context to nuke.thisNode() and picks up the changing knob by the nuke.thisKnob() command.
@return: None
"""
n = nuke.thisNode()
k = nuke.thisKnob()
... | 88931a0aac2518df45c3224c94c6b2ac454d7b13 | 45,322 |
def bspline_to_bezier(ctrl_points, degree, knot_vector=None):
"""Extraction of the Constituent Bezier Curves using Boehm's Algorithm.
This implementation only works for cubic B-Splines.
Derivation is based on the algorithm described in Sederberg's "Computer Aided
Geometric Design", on "Extracting Bezie... | f421ad287316f79bca7d1ad1bac9834dcf52e97c | 45,323 |
def is_private(prefix, base):
"""prefix, base -> true iff name prefix + "." + base is "private".
Prefix may be an empty string, and base does not contain a period.
Prefix is ignored (although functions you write conforming to this
protocol may make use of it).
Return true iff base begins with an (a... | fc68641c1483132c2b15af57f3cc11c8062df318 | 45,326 |
def probability_move(M, current_vertex):
"""get moving probabilities for current vertex"""
# get current vertex id
v_idx = ext.get_python_idx(current_vertex)
n = len(M[v_idx])
prob_move = []
my_vertices = []
for col in range(0, n):
prob_v = M[v_idx][col]
# if target can move... | d6bb1c9f8289475b86d90ccf502c8579116f38f5 | 45,327 |
def SqrtISwapXEBOptions(*args, **kwargs):
"""Options for calibrating a sqrt(ISWAP) gate using XEB."""
return XEBPhasedFSimCharacterizationOptions(*args, **kwargs).with_defaults_from_gate(SQRT_ISWAP) | 0362c685e5b8a594d36d4b7a30a651d7656b1c87 | 45,328 |
def _set_location(hass, data, location_name):
"""Fire HA event to set location."""
device = _device_name(data)
async_dispatcher_send(
hass, TRACKER_UPDATE, device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), location_name, data)
return web.Response(
text="Setting location for ... | cb415b25aae45aca42ed0aa36f8fbc62ac293c88 | 45,329 |
import scipy
def create_decision_per_leafs(tree):
"""
Create a decision path matrix for leaf nodes - relative to all nodes of
single tree
Argument:
---------
tree : sklearn style tree object (has attribute .tree_)
generated tree to create decision path matricies from
Returns:
... | 9a0d82c85a4827a194a8d6b7fad28a11e055522e | 45,330 |
from typing import TextIO
def load_genre(fhandle: TextIO) -> str:
"""Load genre data from a file
Args:
path (str): path to metadata annotation file
Returns:
str: loaded genre data
"""
annotation = jams.load(fhandle)
return annotation.search(namespace="tag_open")[0]["data"][0]... | 2cf9fe938dca3d5bedf1eb80a7adec3fbe02dac3 | 45,331 |
import collections
def _find_resources(graph, types):
"""Build up cache of type=>[resource=>localname]]"""
resources=collections.defaultdict(dict)
for t in types:
resources[t]={}
for x in graph.subjects(RDF.type, t):
resources[t][x]=_quote(localname(x))
resources[RDFS.C... | 410324b343c5987cb335aa2cd891ed1e08fddd62 | 45,332 |
def vocab_parallel_KLDivLoss(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon=1e-12):
"""Helper function for the cross entropy."""
return _VocabParallelKLDivLoss.apply(vocab_parallel_s_logits, vocab_parallel_t_logits, epsilon) | b52610049f45972a43a9617b4b2908991f53530f | 45,333 |
def get_email_list():
"""
Returns an array of files parsed into an actual array (as opposed to an object)
:return: array of strings
"""
email_file_list = []
pending_email_list = aws_list_files()
for email_file in pending_email_list:
email_file_list.append(email_file)
# Remove th... | 4ce4e77c1217b7b19b7bf0c2a67e6c766932eda8 | 45,334 |
def mu_central(components, observation=None, method='centroid', zeropoint=27.0, pixel_scale=0.168, weight_order=0):
"""
Determine the central surface brightness, by calculating the average of 9 pixels around the centroid
Parameters
----------
components: a list of `scarlet.Component` or `scarlet.Co... | 673d0cb5eaa43c61552def552f5861916fb4d4fa | 45,335 |
def cli(text="", items=None, wraplen=80, header=None, border=None, hchar="/"):
"""
Provide a standardized look to the SeisFlows command line interface messages
The look we are after is something like:
$ seisflows cmd
=======================
HEADER
//////
... | e945af2767e66170560d9b9be32aecf9c0918397 | 45,337 |
def resnext56_8x8d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrai... | e42420ef73495c6966af0b1033daa8be44e74e6f | 45,338 |
def _unit_fun(x):
"""unit function"""
return x | 236dfe5d50b76549e601ef5c65c6a04cf8fcbeb8 | 45,339 |
def get_roi_scores(img, d, params):
"""Return array of all scores for each possible ROI of given dimension."""
shape = [img.shape[i]-d[i]+1 for i in range(3)] + [len(params)]
scores = np.empty(shape, dtype=np.float32)
for z, y, x, i in np.ndindex(scores.shape):
roi = img[z:z+d[0], y:y+d[1], x:x+... | 237a11274d9bf01a5aa08989ff84ca45d720c113 | 45,341 |
import json
def dump_grid(grid: Grid) -> str:
"""
Dump a grid to JSON
Args:
grid: The grid.
Returns:
A json string
"""
return json.dumps(_dump_grid_to_hayson(grid)) | 5b0a5c98ba9f0ffbf0b4ea7156b8837a442a0315 | 45,342 |
def abstract_connected_regions(sample_list, aspect='rim', show=False, batch_size_cpu=32, batch_size_gpu=64, outer=False):
"""
:param sample_list: each sample should be a 2d binary numpy array with one semantic, 0 indicate not this semantic
and 1 means positive. If a sample has many semantics, you should sli... | 774b1d045ccf4f4353c05f1815eb45b4e1f7e405 | 45,343 |
def simple_collectd_alarm_generators(update_vals=None):
"""A function for returning Collectd alarm event generators.
Returns generators for a given number of Collectd alarms.
:param update_vals: preset values for ALL update events
:return: generators for alarms as specified
"""
test_entity_sp... | 09f9a97a49647a7de30abee434a6ee11ba4fa486 | 45,344 |
def sample_distribution(
p: np.ndarray,
random: np.random.RandomState,
) -> int:
"""Samples an integer with probabilities given by p."""
return random.choice(np.arange(len(p)), p=p) | 56cb38fd1c9ff328eeb31e0e692845035a775d42 | 45,345 |
def update_confusion_matrix_training_dash(n_clicks, value, n_intervals):
"""
Function that just calls the update_confusion_matrix_training function. This
function is decorated by the Dash Application decorator. Such an arrangement
is used as unit testing decorated functions is complex.
"""
fi... | e0e742d2676bc838e83ca1767ee9af867c325578 | 45,346 |
import math
import statistics
def _get_average_da(streams_da: dict) -> dict:
"""Calculate average data availability among all data streams"""
total_results = {}
for k, v in streams_da.items():
for i, j in v.items():
if i not in total_results:
total_results[i] = []
... | db2fde9e13b4cbb5ce43d5f3c2d2ff2abd30f487 | 45,347 |
def preview_string(graved):
"""
Creates preview string of the given graved content.
Parameters
----------
graved : `None` or `list` of (`str`, ``Grave``) elements
Returns
------
content : `None` or `str`
"""
if graved is None:
return None
words = []
for element... | 382a9dd339e51d90ba6ba42ee9b45173b5c4c8ec | 45,348 |
import get_text_content_from_text_refs
from indra.literature.adeft_tools import universal_extract_text
from indra.literature import pubmed_client
def _get_text_for_grounding(stmt, agent_text):
"""Get text context for Adeft disambiguation
If the INDRA database is available, attempts to get the fulltext from
... | 56905dfd7e446e9ecc2ea8dd6d601763dbae9a0b | 45,349 |
import re
def get_pycon_speaker_first_names(soup=None):
"""Parse the PYCON_HTML using BeautifulSoup, extracting all
speakers (class "speaker"). Note that some items contain
multiple speakers so you need to extract them.
Return a list of first names
"""
if soup is None:
soup = ... | 3b1545732f36a611d7f9ec5b7db81e994884a03c | 45,350 |
def read_trec_res_file(file_name):
"""
Assuming data is in trec format results file with 6 columns, 'Qid entropy cross_entropy Score
'"""
data_df = pd.read_csv(file_name, delim_whitespace=True, header=None, index_col=0,
names=['qid', 'Q0', 'docNo', 'docRank', 'docScore', 'ind']... | 47feaa2abe11bc7ccf2ea7555482394f2219ed93 | 45,351 |
def bboxes_iou(boxes1, boxes2):
"""
boxes: [xmin, ymin, xmax, ymax, score, class] format coordinates.
"""
boxes1 = np.array(boxes1)
boxes2 = np.array(boxes2)
boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) *... | a5fab20307ea3903328ee468cce8e668d8b03f20 | 45,352 |
import torch
def loss_fn(outputs, labels):
"""
Compute the binary cross entropy loss given outputs and labels.
Args:
outputs: (Tensor) dimension batch_size x 1 - output of the model
labels: (Tensor) dimension batch_size, where each element is a value in [0, 1]
Returns:
loss (... | 4190c20ccee794f68af5697a7556ac616dde9724 | 45,353 |
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found.
o(n) runtime, based off the length of the text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a st... | b13ce4571f562a95625cc223818c3d11f5e5aa3b | 45,354 |
from typing import Dict
def _candidate_to_package_info_artefact(candidate: InstallationCandidate) -> Dict[str, str]:
""" Provide artifact metadata """
loc = candidate.link
artefact = {
'filename': loc.filename,
'hash': '{}:{}'.format(loc.hash_name, loc.hash),
'url': loc.url,
}
... | d6d72a496f7181fa8343dbca0f379f687a86b08d | 45,355 |
import importlib
import pkgutil
def get_namespace_pkg_types(ns_pkg_name, preferred='egg', print_msg=True,
use_env=None):
"""Determine how namespace packages are installed.
Parameters:
ns_pkg_name (string): The name of the namespace package to inspect.
preferred='eg... | f59cad9ea13cb5f3531719f73d38ca9aea69c636 | 45,356 |
def compute_boundary(cpumap, cpulist):
"""
I think the name is misleading...
"""
bound = np.searchsorted(cpumap, cpulist)
return np.concatenate([bound, [cpumap.size]]) | 6ac999f361815161399a95488a59a926e3aa4c8a | 45,357 |
def _compute_element_mse(data_a, data_b):
"""Compute MSE (Mean Squared Error).
:param data_a: Data for element a
:param data_b: Data for element b
:returns: The MSE value
"""
return np.mean(np.square(np.subtract(data_a, data_b, dtype=np.double))) | b3679153681ef1843cdf724601a6f35fc654a277 | 45,359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.