content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pairwise_to_multiple(pwise, ref_seq, moltype, info=None):
"""
turns pairwise alignments to a reference into a multiple alignment
Parameters
----------
pwise
Series of pairwise alignments to ref_seq as
[(non-refseq name, aligned pair), ...]
ref_seq
The sequence common... | 36f8d63ba9a53aaa448bcf0c782f748edafc25fa | 24,341 |
def get_dashboard(title: str):
"""Get a dashboard by title"""
dashboards = sdk.search_dashboards(title=title)
if not dashboards:
print(f"dashboard {title} was not found")
return None
return dashboards[0] | 3738557ef1ef2dee35382df7da86cf373908974c | 24,342 |
import torch
def translate_tensor(tensor, input_size=32, nt=2):
"""
Data augmentation function to enforce periodic boundary conditions.
Inputs are arbitrarily translated in each dimension
"""
ndim = len(tensor[0,0, :].shape)
t = input_size//nt
t_vec = np.linspace(0, (nt-1)*t, nt).astype(in... | 12280e33331adb6924b36eebc65c85a10f937d58 | 24,343 |
def _get_job_resources(args):
"""Extract job-global resources requirements from input args.
Args:
args: parsed command-line arguments
Returns:
Resources object containing the requested resources for the job
"""
logging = param_util.build_logging_param(
args.logging) if args.logging else None
... | fbbf596c721369890a14581863d4dce0fb24eb42 | 24,344 |
import torch
def cosine_distance(input1, input2):
"""Computes cosine distance.
Args:
input1 (torch.Tensor): 2-D feature matrix.
input2 (torch.Tensor): 2-D feature matrix.
Returns:
torch.Tensor: distance matrix.
"""
input1_normed = F.normalize(input1, p=2, dim=1)
input... | e4aed2f8f0439797312977d674ccc0351a90402b | 24,347 |
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post',
truncating='post', value=0.):
""" pad_sequences.
Pad each sequence to the same length: the length of the longest sequence.
If maxlen is provided, any sequence longer than maxlen is truncated to
maxlen. Truncation... | f69c199861e17575185d0c40371f85b1fa5f2458 | 24,348 |
def get_regions(service_name, region_cls=None, connection_cls=None):
"""
Given a service name (like ``ec2``), returns a list of ``RegionInfo``
objects for that service.
This leverages the ``endpoints.json`` file (+ optional user overrides) to
configure/construct all the objects.
:param service... | b63982d14c415d082c729595c85fee0833e75d8f | 24,349 |
import math
def sol_dec(day_of_year):
"""
Calculate solar declination from day of the year.
Based on FAO equation 24 in Allen et al (1998).
:param day_of_year: Day of year integer between 1 and 365 or 366).
:return: solar declination [radians]
:rtype: float
"""
_check_doy(day_of_year... | 20c0c491a9ad99a324754c8bc2f6a32e6c6b1f51 | 24,350 |
import unittest
def makeTestSuiteV201111():
"""Set up test suite using v201111.
Returns:
TestSuite test suite using v201111.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(NetworkServiceTestV201111))
return suite | 39a7ecb94bce33e3edbbc52ae584e4fa36c95c42 | 24,351 |
def build_series(df):
"""
Return a series tuple where:
the first element is a list of dates,
the second element is the series of the daily-type variables,
the third element is the series of the current-type variables,
the fourth element is the series of the cum-type variables.
:param df: pd.... | d5ca0f87c46a6061544481ca01a88ad29def4c7e | 24,352 |
def lnZ(df_mcmc):
"""
Compute log Z(1) from PTMCMC traces stored in DataFrame.
Parameters
----------
df_mcmc : pandas DataFrame, as outputted from run_ptmcmc.
DataFrame containing output of a parallel tempering MCMC
run. Only need to contain columns pertinent to computing
ln... | 621d6db5a9126608d61688bd79ae09e03d25d114 | 24,353 |
def p2h(p, T=293., P0=1000., m=28.966, unit_p='mbar'):
""" Returns an elevation from barometric pressure
Parameters
----------
p: {float, array}
barometric pressure in mbar or torr specified with unit_p
T: float, optional
Temperature in K
P0: float, optional
Pressure at ... | 646eac27f7723116e9ea5cd9dcef226cc6c45cc5 | 24,354 |
from typing import Callable
def upon_teardown(f: Callable):
"""
Use this decorator to mark you ploogin function as a handler to call upon teardown.
"""
return PlooginEventHandler(event=PlooginEvents.TEARDOWN, f=f) | 289db179d427c9ebccd1ff408e4606d4f6e97bd5 | 24,355 |
def get_train_test_indices_drone(df, frac, seed=None):
""" Split indices of a DataFrame with binary and balanced labels into balanced subindices
Args:
df (pd.DataFrame): {0,1}-labeled data
frac (float): fraction of indicies in first subset
random_seed (int): random seed used as random st... | f27f893f8cfcc48718d0ca5166e2eafdb57bbad2 | 24,356 |
import requests
from bs4 import BeautifulSoup
import re
def get_subs(choice, chatid, obj):
"""Return subtitle download links."""
url = "https://yts-subs.com" + obj.get_url(chatid, int(choice))
try:
reponse = requests.get(url, headers=headers)
except Exception as e:
print(e)
rai... | 60b19f1004771546cfe530be55fa793d24500df0 | 24,357 |
def get_shape(rhoa_range):
"""
Find anomaly `shape` from apparent resistivity values framed to
the best points.
:param rhoa_range: The apparent resistivity from selected anomaly bounds
:attr:`~core.erp.ERP.anom_boundaries`
:type rhoa_range: array_like or list
... | 7de41fb432c733f434853e74e873ecac1542c877 | 24,358 |
def elslib_D2(*args):
"""
* For elementary surfaces from the gp package (cones, cylinders, spheres and tori), computes: - the point P of parameters (U, V), and - the first derivative vectors Vu and Vv at this point in the u and v parametric directions respectively, and - the second derivative vectors Vuu, Vvv and... | c99d089ba0aa95ed1134be53a491f690feb03edd | 24,359 |
def readiness():
"""Handle GET requests that are sent to /api/v1/readiness REST API endpoint."""
return flask.jsonify({}), 200 | 7c1edf3b965ad1f2b7356d634135a75846886b21 | 24,360 |
def camino_minimo(origen,dest,grafo,aeropuertos_por_ciudad,pesado=True):
"""Obtiene el camino minimo de un vertice a otro del grafo"""
camino=[]
costo=float("inf")
for aeropuerto_i in aeropuertos_por_ciudad[origen]:
for aeropuerto_j in aeropuertos_por_ciudad[dest]:
if pesado:
... | a0ef06265ce754fa1a4289761139e86e241f14fc | 24,361 |
def extract_name_from_uri_or_curie(item, schema=None):
"""Extract name from uri or curie
:arg str item: an URI or curie
:arg dict schema: a JSON-LD representation of schema
"""
# if schema is provided, look into the schema for the label
if schema:
name = [record["rdfs:label"] for record... | 08125457496c9d563f96a4f2a54a560c56c01af8 | 24,362 |
def external_forces(cod_obj):
"""actual cone position"""
x_pos,y_pos,z_pos =cod_obj.pos_list[-1]
"""
Drift vector components
Drift signal//all directions
"""
divx = forcep['divxp']([x_pos,y_pos,z_pos])[0]
divy = forcep['divyp']([x_pos,y_pos,z_pos])[0]
divz = forcep['divzp']([x_pos... | 2dbd13b3e09b0eb7e09b10c0607a9e0e7a87c11a | 24,365 |
def charis_font_spec_css():
"""Font spec for using CharisSIL with Pisa (xhtml2pdf)."""
return """
@font-face {{
font-family: 'charissil';
src: url('{0}/CharisSIL-R.ttf');
}}
@font-face {{
font-family: 'charissil';
font-style: italic;
src: url('{0}/CharisSIL-I.... | a812b65da61d333031dac878ebfdf9e4afe4b448 | 24,366 |
def set_symbols(pcontracts,
dt_start="1980-1-1",
dt_end="2100-1-1",
n=None,
spec_date={}): # 'symbol':[,]
"""
Args:
pcontracts (list): list of pcontracts(string)
dt_start (datetime/str): start time of all pcontracts
dt_end ... | 9450e8355fa88d6794d58de7311992bb4bab357f | 24,367 |
def estimate_vol_gBM(data1, data2, time_incr=0.1):
""" Estimate vol and correlation of two geometric Brownian motion samples with time samples on a grid with mesh size time_incr using estimate_vol_2d_rv_incr, the drift parameter and mean rev paramters are set to 0.
----------
args:
data1 data array... | 4ecc5fb7f97c41db2f9b7347db43bda70d7b6c14 | 24,368 |
import requests
def get_coin_total(credentials_file: str, coin: str) -> float:
"""
Get the current total amount of your coin
Args:
credentials_file: A JSON file containing Coinbase Pro credentials
coin: The coin requested
Returns:
coin_total: The total amount of the coin you ... | cf71d211cf44e0b215af8ce219a12179c005f52a | 24,370 |
from datetime import datetime
def datetime_to_serial(dt):
"""
Converts the given datetime to the Excel serial format
"""
if dt.tzinfo:
raise ValueError("Doesn't support datetimes with timezones")
temp = datetime(1899, 12, 30)
delta = dt - temp
return delta.days + (float(delta.sec... | 3142bfc9d33ddf782c0a6485898e6ed6bcc00418 | 24,371 |
from copy import deepcopy
def compute_transitive_closure(graph):
"""Compute the transitive closure of a directed graph using Warshall's
algorithm.
:arg graph: A :class:`collections.abc.Mapping` representing a directed
graph. The dictionary contains one key representing each node in the
... | 62a7191759614f495f5297379544fa3cdf77fcfa | 24,372 |
def A_intermediate(f1, f2, f3, v1, v2, v3, d1, d3):
"""Solves system of equations for intermediate amplitude matching"""
Mat = np.array(
[
[1.0, f1, f1 ** 2, f1 ** 3, f1 ** 4],
[1.0, f2, f2 ** 2, f2 ** 3, f2 ** 4],
[1.0, f3, f3 ** 2, f3 ** 3, f3 ** 4],
[0.... | 484c17d0a176a1e666f2ebe447d74f3c83845918 | 24,373 |
def _evaluate_criterion(criterion, params, criterion_kwargs):
"""Evaluate the criterion function for the first time.
The comparison_plot_data output is needed to initialize the database.
The criterion value is stored in the general options for the tao pounders algorithm.
Args:
criterion (calla... | bbb0b2cdb4fb4e12d18b6e34c1878a3eaa40059a | 24,374 |
def group_by(collection, callback=None):
"""Creates an object composed of keys generated from the results of running
each element of a `collection` through the callback.
Args:
collection (list|dict): Collection to iterate over.
callback (mixed, optional): Callback applied per iteration.
... | 5ca9e3867a1e340da92c223b8ba60a2bdcf2bc0b | 24,375 |
def lemmatize_verbs(words):
"""lemmatize verbs in tokenized word list"""
lemmatizer = WordNetLemmatizer()
lemmas = []
for word in words:
lemma = lemmatizer.lemmatize(word, pos='v')
lemmas.append(lemma)
return lemmas | 6d37cc6c4f52b062872586f56cb4d459d3fa5cb0 | 24,376 |
def loadfromensembl(homology, kingdom='fungi', sequence='cdna',
additional='type=orthologues', saveonfiles=False, normalized=False,
setnans=False, number=0, by="entropy", using="normal", getCAI=None):
"""
Load from ensembl the datas required in parameters ( look at PyCUB.... | b7c3adee4ba4b61c0828b830b5f53578da75211c | 24,377 |
def dereference(reference_buffer, groups):
"""
find a reference within a group
"""
if len(reference_buffer)>0:
ref_number = int(''.join(reference_buffer))-1
return groups[ref_number % len(groups)] +' '
return '' | c76234051e81a16f44690de46435e9856996d677 | 24,378 |
def get_main_corpora_info():
"""Create dict with the main corpora info saved in CORPORA_SOURCES
:return: Dictionary with the corpora info to be shown
:rtype: dict
"""
table = []
for corpus_info in CORPORA_SOURCES:
corpus_id = CORPORA_SOURCES.index(corpus_info) + 1
props = corpus... | d0a642e98248eabdbaa018991774612f33caca8f | 24,379 |
def start_compare_analysis(api_token, project_id, kind, url, username, password, target_branch, target_revision):
"""
Get the project identifier from the GraphQL API
:param api_token: the access token to the GraphQL API
:param project_id: identifier of the project to use as source
:param kind: kind ... | 10482ed334f5522894b271e9d69803b4c804cb09 | 24,380 |
def get_matrix_in_format(original_matrix, matrix_format):
"""Converts matrix to format
Parameters
----------
original_matrix : np.matrix or scipy matrix or np.array of np. arrays
matrix to convert
matrix_format : string
format
Returns
-------
matrix : scipy matrix
... | 837b47ccb4d0bf608907dd13ed1bedd0cb780058 | 24,381 |
def _convert_name(name, recurse=True, subs=None):
"""
From an absolute path returns the variable name and its owner component in a dict.
Names are also formatted.
Parameters
----------
name : str
Connection absolute path and name
recurse : bool
If False, treat the top level ... | aa331f8616e3996d78a2bd278b10e2e806d56440 | 24,383 |
def _orthogonalize(constraints, X):
"""
Orthogonalize spline terms with respect to non spline terms.
Parameters
----------
constraints: numpy array
constraint matrix, non spline terms
X: numpy array
spline terms
Returns
-------
constrained_X: num... | 01eb69ffa30d48c84c76915e33be39b201fda73e | 24,384 |
def tril(input, diagonal=0, name=None):
"""
This op returns the lower triangular part of a matrix (2-D tensor) or batch
of matrices :attr:`input`, the other elements of the result tensor are set
to 0. The lower triangular part of the matrix is defined as the elements
on and below the diagonal.
... | 62eb0c83cc633db655859160ea5df1fc0158086a | 24,386 |
def rename_and_merge_columns_on_dict(data_encoded, rename_encoded_columns_dict, **kwargs):
"""
Parameters
----------
data_encoded: pandas.DataFrame with numerical columns
rename_encoded_columns_dict: dict of columns to rename in data_encoded
**kwargs
inplace:bool, default=False
decides ... | cb8767a102ad421674381182a2ea65468613abee | 24,388 |
from typing import List
def _get_public_props(obj) -> List[str]:
"""Return the list of public props from an object."""
return [prop for prop in dir(obj) if not prop.startswith('_')] | 7b3be3e186bc009329ed417c6685fb2503a7c993 | 24,389 |
from typing import List
def get_vd_html(
voronoi_diagram: FortunesAlgorithm,
limit_sites: List[SiteToUse],
xlim: Limit,
ylim: Limit,
) -> None:
"""Plot voronoi diagram."""
figure = get_vd_figure(
voronoi_diagram, limit_sites, xlim, ylim, voronoi_diagram.SITE_CLASS
)
html = get_... | 1fbec3a3bf2c23d878e9c4b7d1779fb2526560e0 | 24,390 |
def sample_normal_mean_jeffreys(s1, ndata, prec):
"""Samples the mean of a normal distribution"""
##
return rn.normal(s1 / ndata, 1 / np.sqrt(prec * ndata)) | 391cd72ea307903278e94bbc6b323f0997759f10 | 24,391 |
def pipeline_report_build(submission: Submission, stdout: str, passed: bool, **_):
"""
POSTed json should be of the shape:
{
"stdout": "build logs...",
"passed": True
}
:param submission:
:param stdout:
:param passed:
:return:
"""
if len(stdout) > MYSQL_TEXT_MAX_LE... | cbd07d2642b511f301a7e82581d71de3d04a66c6 | 24,393 |
import random
def flatten(episode, context_length, include_labels=True, delimiter='\n'):
"""
Flatten the data into single example episodes.
This is used to make conditional training easier and for a fair comparison of
methods.
"""
context = deque(maxlen=context_length if context_length > 0 el... | 37c44cb5e442e3d257230f151ce11a0012658ef5 | 24,394 |
def calc_binsize(num_bins, t_start, t_stop):
"""
Calculates the stop point from given parameter.
Calculates the size of bins :attr:`binsize` from the three parameter
:attr:`num_bins`, :attr:`t_start` and :attr`t_stop`.
Parameters
----------
num_bins: int
Number of bins
t_start:... | 0eb42e56aebfd29aa76190b4837171e5cfb94e82 | 24,395 |
def d_within(geom, gdf, distance):
"""Find the subset of a GeoDataFrame within some distance of a shapely geometry"""
return _intersects(geom, gdf, distance) | 463be3ff9c3eb7f002dc652047b96fbc15ba05b4 | 24,396 |
def make_params(args, nmax=None):
"""Format GET parameters for the API endpoint.
In particular, the endpoint requires that parameters be sorted
alphabetically by name, and that filtering is done only on one
parameter when multiple filters are offered.
"""
if nmax and len(args) > nmax:
... | 406d23a5090b901c20a4ac10dc182fbc3051e61e | 24,397 |
def remap(value, oldMin, oldMax, newMin, newMax):
"""
Remaps the value to a new min and max value
Args:
value: value to remap
oldMin: old min of range
oldMax: old max of range
newMin: new min of range
newMax: new max of range
Returns:
The remapped value i... | c0e53ce2b2169b08d271f7077e552762c572cf1f | 24,398 |
async def construct_unit_passport(unit: Unit) -> str:
"""construct own passport, dump it as .yaml file and return a path to it"""
passport = _get_passport_dict(unit)
path = f"unit-passports/unit-passport-{unit.uuid}.yaml"
_save_passport(unit, passport, path)
return path | e4f1e90bbe82b1cb425cf5834fafbd1f36258454 | 24,399 |
import warnings
def certification_to_csv(stats, filepath, product_id):
"""Writes certification outputs to the file specified.
Parameters
----------
stats : list of dict
list of statistical outputs from the function
`thermostat.compute_summary_statistics()`
filepath : str
f... | 23f1a84fa2d9c5ad25eb04d23ea9646cf2849286 | 24,400 |
def get_ipns_link(name: str) -> str:
"""Get the ipns link with the name of it which we remember it by
Args:
name (str): Name we call ipns link
Returns:
str: Returns the IPNS url
Raises:
ValueError: if link not found
>>> import random
>>> key_name = str(random.getrand... | 1c171e0539013aecd3e45a7cf7ca2c2907df3955 | 24,401 |
def joint_sim(num_samp, num_dim, noise=0.5):
"""
Function for generating a joint-normal simulation.
:param num_samp: number of samples for the simulation
:param num_dim: number of dimensions for the simulation
:param noise: noise level of the simulation, defaults to 0.5
:return: the data matri... | 71296c5093aa3113b7df70cb8966ac9ca06ccb31 | 24,402 |
def calculate_seasonal_tilt(axial_tilt, degrees):
"""Find the seasonal tilt offset from axial tilt and orbit (in degrees)
axial_tilt -- The planet's tilt. e.g. Earth's tilt is 23.44 degrees.
degrees -- How far along is the planet in its orbit around its star?
(between 0 and 360. 0/360 and 180 are equino... | a31e072f95d9d856b2c2d7549b7f96a97a4d6b60 | 24,403 |
import logging
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
"""Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
generator of tuples containing the match and its score. I... | 784a619b06fed48a5b7d4c8f4c711da954125c9c | 24,404 |
def mark_dts_nn(marked_dict):
"""Loops through a dictionary representation of the XML-text where determiners have been "focus"-marked.
Finds the "focus"-marked determiners and looks for their nouns from the words after the determiner until the end of the current sentence. The found noun is then marked with "foc... | 2db6e21a3ea1f4249ef13fd7a235839a8a2d1871 | 24,405 |
def reservation_rollback(context, reservations, project_id=None, user_id=None):
"""Roll back quota reservations."""
return IMPL.reservation_rollback(context, reservations,
project_id=project_id,
user_id=user_id) | fcb5a82522320ffe6a6d262eb6571153aaa55b29 | 24,406 |
def encrypt(
security_control: SecurityControlField,
system_title: bytes,
invocation_counter: int,
key: bytes,
plain_text: bytes,
auth_key: bytes,
) -> bytes:
"""
Encrypts bytes according the to security context.
"""
if not security_control.encrypted and not security_control.aut... | f03066da2ab54e784063f01255b9f3f53050a2cf | 24,407 |
def leftmost_turn(((x0, y0), (x1, y1)), (x, y), zs):
"""Find the line segment intersecting at the leftmost angle relative to initial segment.
Arguments:
(x0, y0) – where we started
(x1, x2) – direction travelling in
(x, y) – where intersected one or more alternative line segments
... | bfe1650a92e38612461942ddfcee5faaad96ad5f | 24,408 |
def maya_window():
"""Get Maya MainWindow as Qt.
Returns:
QtWidgets.QWidget: Maya main window as QtObject
"""
return to_qwidget("MayaWindow") | bea4ef97a14bb93a461f0dd54dbb6e9a25a14a63 | 24,409 |
def soap2Dict(soapObj):
"""A recursive version of sudsobject.asdict"""
if isinstance(soapObj, sudsobject.Object):
return {k: soap2Dict(v) for k, v in soapObj}
elif isinstance(soapObj, list):
return [soap2Dict(v) for v in soapObj]
return soapObj | 46d5b767640a1b8c506f85d03580508d9b2278f0 | 24,410 |
def generate_sequential_BAOAB_string(force_group_list, symmetric=True):
"""Generate BAOAB-like schemes that break up the "V R" step
into multiple sequential updates
E.g. force_group_list=(0,1,2), symmetric=True -->
"V0 R V1 R V2 R O R V2 R V1 R V0"
force_group_list=(0,1,2), symmetric=False -->
... | 7710775e365f0caae81a9737feec18c662790bde | 24,411 |
def _get_active_tab(visible_tabs, request_path):
"""
return the tab that claims the longest matching url_prefix
if one tab claims
'/a/{domain}/data/'
and another tab claims
'/a/{domain}/data/edit/case_groups/'
then the second tab wins because it's a longer match.
"""
matching_... | ac9cd34d4b4ee1c1c0356499b389c1f6a7195585 | 24,412 |
import logging
def fit_scale_heights(data, masks, min_lat = None, max_lat = None,
deredden = False, fig_names = None, return_smoothed = False,
smoothed_width = None, xlim = None, ylim = None, robust = True,
n_boot = 10000):
"""
Fits scale height data and returns slopes
Parameters
-----... | fe2cd6d1cc1dfa18b7a78593e326f80ee99222bc | 24,414 |
def get_aircon_mock(said):
"""Get a mock of an air conditioner."""
mock_aircon = mock.Mock(said=said)
mock_aircon.connect = AsyncMock()
mock_aircon.fetch_name = AsyncMock(return_value="TestZone")
mock_aircon.get_online.return_value = True
mock_aircon.get_power_on.return_value = True
mock_air... | 68833445b94b2194f73c9b699d925bb92dca010b | 24,416 |
def mutation(individual):
"""
Shuffle certain parameters of the network to keep evolving it. Concretely:
- thresh, tau_v, tau_t, alpha_v, alpha_t, q
"""
individual[0].update_params()
return individual, | 8ccd373f991cbf2e8161e6bbe32375ca8826e48c | 24,417 |
def truncate_repeated_single_step_traversals_in_sub_queries(
compound_match_query: CompoundMatchQuery,
) -> CompoundMatchQuery:
"""For each sub-query, remove one-step traversals that overlap a previous traversal location."""
lowered_match_queries = []
for match_query in compound_match_query.match_querie... | b5d264640fb65ff7162209a714257b0a65128e89 | 24,418 |
def intersect(list1, list2):
"""
Compute the intersection of two sorted lists.
Returns a new sorted list containing only elements that are in
both list1 and list2.
This function can be iterative.
"""
result_list = []
idx1 = 0
idx2 = 0
while idx1 < len(list1) and idx2 < len(list... | d0f50b466108f685dc74d227554ab057cac018ae | 24,419 |
import typing
def get_parent_project_ids(project_id: int, only_if_child_can_add_users_to_parent: bool = False) -> typing.List[int]:
"""
Return the list of parent project IDs for an existing project.
:param project_id: the ID of an existing project
:param only_if_child_can_add_users_to_parent: whether... | b0c9d2241a0b114b3fcf531592b7f05000596fec | 24,420 |
def integral_length(v):
"""
Compute the integral length of a given rational vector.
INPUT:
- ``v`` - any object which can be converted to a list of rationals
OUTPUT: Rational number ``r`` such that ``v = r u``, where ``u`` is the
primitive integral vector in the direction of ``v``.
EXAM... | 54d2b2726bea848e1a5836425516371fc09f54b3 | 24,422 |
def load_classification_pipeline(
model_dir: str = "wukevin/tcr-bert", multilabel: bool = False, device: int = 0
) -> TextClassificationPipeline:
"""
Load the pipeline object that does classification
"""
try:
tok = ft.get_pretrained_bert_tokenizer(model_dir)
except OSError:
tok =... | 0811cdc4ddaac3992e1cec7f43d88df276356c5c | 24,423 |
def skew_image(img, angle):
"""
Skew image using some math
:param img: PIL image object
:param angle: Angle in radians (function doesn't do well outside the range -1 -> 1, but still works)
:return: PIL image object
"""
width, height = img.size
# Get the width that is to be added to the i... | 5b52a87edc44669e9fad82efd5c594df12edee41 | 24,424 |
import logging
def test_process_bto_order_high_risk(monkeypatch, capsys, caplog):
"""BTO order should be correctly processed with high risk flag set """
caplog.set_level(logging.INFO)
monkeypatch.setitem(USR_SET, "high_risk_ord_value", 1000)
monkeypatch.setitem(USR_SET, "buy_limit_percent", 0.03)
... | 0981a09686670ad8d941a438514832c17b541863 | 24,425 |
import types
import doctest
def _load_tests_from_module(tests, module, globs, setUp=None, tearDown=None):
"""Load tests from module, iterating through submodules.
"""
for attr in (getattr(module, x) for x in dir(module) if not x.startswith("_")):
if isinstance(attr, types.ModuleType):
... | 068eb24fd826192730bfb7dde2c978ef42fb8475 | 24,426 |
def calculate_full_spectrum(xs, cp, ep=None, betas=(0,0), data=None):
"""Direct solution of the k-eigenvalue problem in integral transport
by the collision probability method. Input data are the xs list and
the collision probabilities in cp. Only isotropic scattering is
allowed. A relation of albedo for... | ad145dc3fc5ae57f6512cb01b1119a2fc150b4bd | 24,427 |
def get_connectors_by_type(type : str):
"""
Convenience method for `get_connectors()`.
"""
return get_connectors(type) | 7e41c2a37173a4d72d7d947aa5a166c23f102da0 | 24,428 |
def crawl(alphabet, initial, accepts, follow):
"""
Create a new FSM from the above conditions.
"""
states = [initial]
accepting = set()
transition = dict()
i = 0
while i < len(states):
state = states[i]
if accepts(state):
accepting.add(i)
transitio... | c72b743ed4d06691fea020e2e66236a54d53df5f | 24,429 |
def mpncovresnet101(pretrained=False, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = MPNCOVResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_ur... | bad52e5b47a84faabdb9d82fb50e585ee287b392 | 24,430 |
def cathegory_encoder(data, labelCathegory=labelCathegory):
""" Encode cathegorical labels """
for k in labelCathegory:
encoder = sklearn.preprocessing.LabelEncoder()
encoder.fit(list(data[k].values))
data[k] = encoder.transform(list(data[k].values))
return data | dc4c549e58097d219ade1b7140a9e09356692cd8 | 24,431 |
def split_dataset(args, dataset):
"""Split the dataset
Parameters
----------
args : dict
Settings
dataset
Dataset instance
Returns
-------
train_set
Training subset
val_set
Validation subset
test_set
Test subset
"""
train_ratio, v... | 1fbaac75655694bc1ca3a5e8ed06d31401d3dd9c | 24,433 |
def depthwise_conv2d_nchw(inputs, weight, bias=None, stride=1, padding=0, dilation=1):
"""Depthwise convolution 2d NCHW layout
Args:
-----------------------------
inputs : tvm.te.tensor.Tensor
shape [batch, channel, height, width]
weight : tvm.te.tensor.Tensor
shape [in_channel, f... | bd4f5f0f7dc3a12adefce0e19fa010919e9b9407 | 24,434 |
def xtransformed(geo, transformation):
"""Returns a copy of the transformed Rhino Geometry object.
Args:
geo (:class:`Rhino.Geometry.GeometryBase`): a Rhino Geometry object
transformation (:class:`Transformation`): the transformation.
Returns:
(:class:`Rhino.Geometry.GeometryBase`)... | 9d21ad58358bff07b10e18c7c3593cca68f07541 | 24,435 |
def function_calls(libfuncs):
"""
libfuncs is the list of library functions called in script. Returns ths
list of all library functions required in script
"""
libfuncs2 = set()
while libfuncs:
func = libfuncs.pop()
libfuncs2.add(func)
for func in called_functions(func):
... | 3c6e29930f0a59cc2ad5a3b24ca22c07f3fca28b | 24,436 |
def preprocess_yaml_config(config: SimpleNamespace, prefix_keys=False) -> SimpleNamespace:
"""
Preprocess a simple namespace. Currently,
- prepend the prefix key to all the configuration parameters
- change 'None' strings to None values
:param config: The SimpleNamespace containing the configuration... | 52c4e79334bc95c573b795a6962e83d949cf9639 | 24,437 |
from numpy.core import isinf, errstate
def gisinf(x):
"""
Like isinf, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
`isinf` and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function i... | cc525ffc10e87b44a5cee3e93fc1c4466bc7a171 | 24,438 |
def make_const(g, # type: base_graph.BaseGraph
name, # type: str
value, # type: np.ndarray
uniquify_name=False # type: bool
):
"""
Convenience method to add a `Const` op to a `gde.Graph`.
Args:
g: The graph that the node should be added to
name:... | fd8493c6ea33c2fd4f930f78fd906ddb5fcdf12e | 24,439 |
def find_maxima(x):
"""Halla los índices de los máximos relativos"""
idx = []
N = len(x)
if x[1] < x[0]:
idx.append(0)
for i in range(1, N - 1):
if x[i-1] < x[i] and x[i+1] < x[i]:
idx.append(i)
if x[-2] < x[-1]:
idx.append(N - 1)
return idx | 8be862981e46ac2534a78354adf52993ca78426a | 24,440 |
def _transform_rankings(Y):
"""Transform the rankings to integer."""
Yt = np.zeros(Y.shape, dtype=np.int64)
Yt[np.isfinite(Y)] = Y[np.isfinite(Y)]
Yt[np.isnan(Y)] = RANK_TYPE.RANDOM.value
Yt[np.isinf(Y)] = RANK_TYPE.TOP.value
return Yt | 7a89bc4dd2ff1ad8b00456198f4051ab9030ccbc | 24,441 |
import io
import gzip
def gzip_bytes(bytes_obj):
"""byte: Compress a string as gzip in memory.
"""
if isinstance(bytes_obj, (str,)):
bytes_obj = bytes_obj.encode()
out_ = io.BytesIO()
with gzip.GzipFile(fileobj=out_, mode='w') as fo:
fo.write(bytes_obj)
return out_ | 68d0a6b3c64b8633a3084114f617ccd792a688f9 | 24,447 |
def ones_like(other_ary):
"""
Create a PitchArray with all entry equal 1, whose shape
and dtype is the same as other_ary
"""
result = PitchArray(other_ary.shape, other_ary.dtype)
result.fill(1)
return result | 7bbdbdaa409de3986db66c98eedc3670d2483b2b | 24,448 |
def inference_multiview(views, n_classes, keep_prob):
"""
views: N x V x W x H x C tensor
"""
n_views = views.get_shape().as_list()[1]
# transpose views : (NxVxWxHxC) -> (VxNxWxHxC)
views = tf.transpose(views, perm=[1, 0, 2, 3, 4])
view_pool = []
for i in xrange(n_views):
# set... | b9fd30db4d130aad29333d80a24c9cac6a6ce580 | 24,449 |
def trueReturn(data, msg):
""" 操作成功结果 """
result = {
"status": True,
"data": data,
"msg": msg
}
return JSONResponse(content=result) | 7eabfe62bb0cf11b92d146cae3171fe391c27d5f | 24,450 |
from pathlib import Path
import re
def parse_slurm_times(job_id: str, path: Path = Path.cwd()) -> float:
"""Performs the parsing of the file slurm-{job_id}.out by returning
in milliseconds the time measured by Slurm.
Args:
out_file (str): The job slurm output file path to parse.
path (Pat... | 22cc642aa711ab302772273d3d05f7d5615e21d1 | 24,451 |
import torch
def bprl(positive: torch.Tensor, negative: torch.Tensor) -> torch.Tensor:
"""
Bayesian Personalized Ranking Loss
https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf
"""
dist = positive - negative
return -F.logsigmoid(dist).mean() | 0fb13f41c27880e821548298a369091f0b96c0c1 | 24,452 |
def select2_js_url():
"""
Return the full url to the Select2 JavaScript library
Default: ``None``
# Example
{% select2_js_url %}
"""
return sl2.select2_js_url() | 6866c7ad1a00e8d23c15f94fd9169412213aa4f0 | 24,453 |
def _SharedSuffix(pattern1, pattern2):
"""Returns the shared suffix of two patterns."""
return _SharedPrefix(pattern1[::-1], pattern2[::-1])[::-1] | c48792aaaf3e470571cbf4d16f6af0b00a671c3f | 24,454 |
def vgg16(num_class):
"""VGG 16-layer model (configuration "D") with batch normalization
"""
model = VGG(make_layers(cfg['D'], batch_norm=True), num_classes=num_class)
return model | abdb0a48bd5190cd7c7e50193f3d950af5195770 | 24,457 |
def IFS(*args) -> Function:
"""
Evaluates multiple conditions and returns a value that corresponds to the first
true condition.
Learn more: https//support.google.com/docs/answer/7014145
"""
return Function("IFS", args) | 395c67b524b4cccbeabba73666bc1a8f78668ff2 | 24,458 |
def idwt_joined_(w, rec_lo, rec_hi, mode):
"""Computes single level discrete wavelet reconstruction
"""
n = len(w)
m = n // 2
ca = w[:m]
cd = w[m:]
x = idwt_(ca, cd, rec_lo, rec_hi, mode)
return x | 4b7371a36abc4bd094a3cd86faa1005ff5d6fd69 | 24,459 |
def _get_pattern_nts(rule):
"""
Return a list of NT names present in given rule.
"""
nt_names = []
for bt in rule.ipattern.bits:
if bt.is_nonterminal():
nt_name = bt.nonterminal_name()
nt_names.append(nt_name)
return nt_names | e690e9187aaff0cf3138444db085e15adfda3847 | 24,460 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.