content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def unicode_parm(cap, *parms):
"""Return the result of ``tparm(tigetstr())`` except as Unicode."""
return tparm(tigetstr(cap), *parms).decode('utf-8') | cdab15341bf9e7597728bc9552f998118e9a4751 | 52,065 |
def lmtd(tci, tco, thi, tho, counterflow=True):
"""log mean temperature difference
tci = cold inlet
tco = cold outlet
thi = hot inlet
tho = hot outlet
"""
if counterflow:
itd = thi - tco
otd = tho - tci
else:
itd = thi - tci
otd = tho - tco
return lmd(itd, otd) | fef77a7d31ecb7cf00f689d315398643c6df5c5c | 52,066 |
def haversine_distances(X, Y=None):
"""Compute the Haversine distance between samples in X and Y
The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first distance of each point is
assumed to be the latitude, the second is the longitude, g... | fa62a8b6f39625aef2a7223c3c23ec7c6705054c | 52,067 |
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""
72ms 36.76%
13MB 95.80%
:param self:
:param head:
:param k:
:return:
"""
if not head or not head.next:
return head
old_tail = head
length = 1
while old_tail.next:
old_tail = old_tail.next
... | b77ceb294655bf88c41b99366ea6054c6ee29f3a | 52,068 |
def calculate(frame,shares_outstanding):
"""
calculate daily RV/BV/Diff price/volume values from minute price data frame
:param frame: pandas dataframe object from minute price data
:param shares_outstanding: company shares outstanding for volume normalization
:return: the new frame constructed fro... | 75726d2e2fed89bd0c1dfb9a5cb7ac9e17a175b7 | 52,069 |
import numpy
def mgc(piece_u, piece_v, relation):
"""
Computes the final mahalanobis gradient compatibility
:param piece_u: One of the puzzle pieces
:type piece_u: numpy.ndarray
:param piece_v: The other one of the puzzle pieces
:type piece_v: numpy.ndarray
:param relation: The connect... | 3da85a5937715310a524b0f0e5d443b8458dcc3c | 52,070 |
def mock_query_object(LCClient):
"""
Creating a Query Response object and prefilling it with some information
"""
# Creating a Query Response Object
start = '2016/1/1'
end = '2016/1/2'
obj = {
'TimeRange': TimeRange(parse_time(start), parse_time(end)),
'Time_start': parse_tim... | 4ef04e98eb4623763a6ac9cf52d6a5f0489c094f | 52,071 |
def determine_edge_sigmoid_params(laplacian_image: itk.Image) \
-> tuple[float, float]:
"""
This function determines the appropriate alpha and beta
for a sigmoid function. This sigmoid function should map
regions of constant intensity to 1.0, while mapping regions
with high intensity gradien... | 80fc6067fead5a4023abc59535c8d5f8bea58c8c | 52,072 |
def getRandomPopulation(popSize, numItems):
"""
Creates a population of random chromosomes
:param popSize: Population size
:param numItems: Chromosome size
:return: list
"""
return [getRandomChromosome(numItems)
for x in range(popSize)] | 097ef584d48ef2a65e8b47d68f351c9563492387 | 52,073 |
def multi_synonym(w2v_model, multi_syns, n, pooling):
"""Given list of synonyms that represents crossword clue, return aggregate ranking
Args:
w2v_model : standard Word2Vec 'KeyedVectors' data structure
multi_syns : nested list containing lists of each synonym present in a clue
n : ... | bc08827397011f576648ae6a4469d067c890eab5 | 52,074 |
def handleCookbookError(r):
"""Deals with errors when updating cookbook"""
if(r.status_code == 404):
print ""
print "Error Notifying Cookbook of new Gist. Is this URL correct?"
print cookbookURL
print ""
print "If not, update cookbookURL in uploadGists.py in devtools to c... | e17cdb4cbe7e6144365369a27b74a4b50f05d7ae | 52,075 |
import json
def check_cross_account(policy_text, allowed_accounts):
"""Find cross account access policy grant not explicitly allowed
"""
if isinstance(policy_text, basestring):
policy = json.loads(policy_text)
else:
policy = policy_text
violations = []
for s in policy['Stateme... | fadc76cbd37b4d821d9143a7a4804e4725e807ca | 52,076 |
def stokes_ellipsometry(tanpsi, Delta):
"""
Stokes vector using ellipsometer parameters.
This creates a Stokes vector for the specific set of ellipsometry
parameters tanpsi and Delta. See Fujiwara table 3.1 for example.
Args:
tanpsi: abs(E_x/E_y) [-]
Delta: angle(E_x) ... | 12f06c0416d05e001b5805465c43653c59c01c43 | 52,077 |
def gen_psd(q):
"""
Random PSD matrix of size (q,q)
from Wishart distribution
"""
G = np.random.randn(q,q)
G = G @ G.T * (1/q)
return G | 73b3d0bab80a8a266fd58d80c7fced2c4aacd648 | 52,078 |
def strictwwid(wwid):
"""Validity checks WWID for invalid format using strict rules - must be Brocade format"""
if len(wwid) != 23: # WWPN must be 23 characters long
print("WWID has invalid length " + wwid)
return None
# Colon separators must be in the correct place
if wwid[2:3] != ":" ... | 539d9e0ef9f1f9f6d24dbc4a1a514d9a07229388 | 52,079 |
from datetime import datetime
import logging
def GetPlistDateValue(key, secure=False, plist=None, str_format=None):
"""Returns the UTC datetime of a given plist date key, or None if not found.
Args:
key: string key to get from the plist.
secure: boolean; True = munki secure plist, False = munki regular p... | 5cab183096909175ef17857a8b21fcb38edf13e6 | 52,080 |
def get_research_data_by_dev(sn):
"""Return the research data by device
"""
dev = Instrument.query.filter_by(sn=sn).first_or_404()
# Choose model
model = dev._get_data_model()
data = _collection(model, model.query.filter_by(instr_sn=dev.sn),
name='data', sn=dev.sn, researche... | 54c3e00770951ed9d2921264c9da1f6e0a6968ec | 52,081 |
def gethub():
"""
:return: an initialized instance of the github utility.
"""
# Thanks, I'll be here all week.
return Github(base_url=GITHUB_API_URL, login_or_token=GITHUB_ACCESS_TOKEN) | e031cb97abf2316116b1ef1dd17313846ab8ef21 | 52,082 |
def get_verification_link(request):
"""
Computes the verification link
"""
verification = create_verification(request)
if type(verification) is not models.VerificationModel:
return None
else:
return "%s/%s/verify-link/?u=%s&c=%s" %(request.META["HTTP_HOST"], settings.AC... | 6d75c0025c0079aa46d66d3ed117739c4149c559 | 52,083 |
def mrp_shadow(mrpset):
"""return the shadow set of a given modified rodrigues parameter
set
:param mrpset: modified rodrigues parameter set
:return: shadow set of the given MRP set
"""
return np.array([-s/(np.linalg.norm(mrpset)**2) for s in mrpset]) | a7cee1e83c75e252e7cbf955859050dd8c658eae | 52,084 |
def upper_char(c):
"""Return the uppercase version of the character in the current locale."""
return chr(_toupper(ord(c))) | 6e800b61bf19d6cf7987c9f75166e1435c6bdced | 52,085 |
def _create_fig(n_cols, n_rows, figname, wrap_col=5, w_plot=5, h_plot=3):
"""Create a figure with subplots
Parameters
----------
n_cols, n_rows: int, number of rows and column in the plot
figname: str, name of the figure window
wrap_col: int, if only 1 row is present, wrap the columns
w_plo... | 88dad78018869bee4f275f30d481b49ad5f361a6 | 52,086 |
def incomplete_mat_mult_bsr(*args):
"""
incomplete_mat_mult_bsr(int Ap, int Aj, float Ax, int Bp, int Bj, float Bx,
int Sp, int Sj, float Sx, int n_brow, int n_bcol,
int brow_A, int bcol_A, int bcol_B)
incomplete_mat_mult_bsr(int Ap, int Aj, double Ax, int Bp, int Bj, double Bx,
int... | 3bc561d7dfc9be68ad9610ea8daf0ab944bef6b8 | 52,088 |
def write_sorted_dca_scores(file_name, sorted_DI, metadata=None, score_type = None):
"""Writes sorted direct information to file.
Parameters
----------
file_name : str
Path to file where DCA data is going to be saved.
sorted_DI : list
A list containing site pair
... | ce9c368c63a96f7b3f36d34f27db9937aa7b7a3d | 52,089 |
def GetMonthList():
"""
Get a list of the defined month names.
rtype: `list`
"""
monthlist = []
for i in range(13):
name = Month[i]
if name is not None:
monthlist.append(name)
return monthlist | bba7530335d4e4f4a5e7c5029ff7ebac6d07326f | 52,092 |
def get_absolute_url(url, endpoint=None):
"""
Returns the absolute url based on the url and endpoint
Args:
url (str): base url with domain (e.g. https://domain.com)
endpoint (str): link to convert to an absolute url (e.g. /image.png)
"""
endpoint = endpoint.replace('%... | d6b1334dd24d66a1168427a3cfefc35cfe375594 | 52,093 |
import time
async def do_task() -> Response:
"""Run a task with celery workers
Returns:
A response with the results in the payload
"""
s = time()
job = group(tasks.send_task('add.two',args=[i,i]) for i in range(100))
result = job.apply_async()
# result.ready()
res = resu... | cd7bb1fc9244b7f915a08a29d72f1f4a98af6ba2 | 52,094 |
from re import A
def get_validation_augmentation():
"""Add paddings to make image shape divisible by 32"""
test_transform = [
A.PadIfNeeded(384, 160)
]
return A.Compose(test_transform) | 87f3a284ba2ccafc4e8d112fafad94cc0de092a7 | 52,095 |
def lnlike_0(ts, ys, yivars, deltanu, nupeak, K, numax, Lambda0, H, Gamma):
"""Log Likelihood for a comb of K frequencies centered on nupeak and separated by deltanu (solves for the amplitudes)"""
assert len(ts) == len(ys)
halfK = (K - 1) // 2
thisK = 2 * halfK + 1
M = np.zeros((len(t... | 611d473d7d80c5a463c9f0dd0cb386a8b3147709 | 52,096 |
def find_dpid_port_by_ip(ip):
"""
finds dpid and port in which IP is located
"""
p = [(x['dpid'],x['port']) for x in core.discovery.gmat if x['ip'] == ip]
if not p:
return (None, None)
else:
return p.pop() | 6454b725a386412334a73a2c9facfc28ed5c3395 | 52,097 |
import torch
def model_summarize(model, show_weights=True, show_parameters=True):
"""Summarizes torch model by showing trainable parameters and weights."""
tmpstr = model.__class__.__name__ + ' (\n'
params_num = 0
for key, module in model._modules.items():
# if it contains layers let call it r... | 080b9ece46d0769c62b236ae7c1863a42a0aeabb | 52,098 |
def gamedvr_record(console):
"""
Default to record last 60 seconds
Adjust with start/end query parameter
(delta time in seconds)
"""
try:
start_delta = request.args.get('start', -60)
end_delta = request.args.get('end', 0)
console.dvr_record(int(start_delta), int(end_delta... | 58114dd64aae01b30bcaee6cf3298283a3777ebf | 52,099 |
def my_kernel_exp(dis, gamma=.1):
"""gamma is auto tuned. The argument gamma means shrink_ratio.
"""
# if full_output:
# print 'gamma = {0:.4f} dim = {1:.4f} squared = {2}'.format(gamma, dim, squared)
dis *= -gamma
np.exp(dis, dis)
return dis | e1f2eb165e6e05528bb5ad9e409f5ed76a1054ef | 52,101 |
def pipeline_run_add_tag(run_id, tags, organization=None, project=None, detect=None):
""" Add tag(s) for a pipeline run.
:param run_id: ID of the pipeline run.
:type run_id: int
:param tags: Tag(s) to be added to the pipeline run. [Comma seperated values]
:type tags: str
:rtype: list of str
... | f5f8dd7f2a40880a3bd4f271d64f3c0d25d87c4f | 52,104 |
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.),
option=1):
"""
Anisotropic diffusion on single channel image
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter - number of iterations
ka... | cb2a972d48c160e0cf1dbecc3b03ce83137e95c0 | 52,105 |
def add_keys2(a, b, B):
"""
aG + bB, G is basepoint
:param a:
:param b:
:param B:
:return:
"""
return tcry.xmr_add_keys2_vartime_r(a, b, B) | 49586fa9e6917c66ccf65f3ac10f404681e36dab | 52,106 |
from typing import List
from re import T
from typing import Optional
from typing import Callable
from typing import Set
def uniquify(lst: List[T], key: Optional[Callable[[T], K]] = None) -> List[T]:
"""Remove duplicates in lst but preserve the order
Args:
lst: a sequence with possible duplicates
... | 402f664b3222acd46365a3a9dbd27e2dea6d79a7 | 52,107 |
def make_point_plot(x,y):
"""It plots the point chart of the data"""
data_points = pd.DataFrame({'x': x.flatten(), 'y': y.flatten()})
chart = alt.Chart(data_points).mark_point(size=50, color='red',filled=True).encode(
x="x",
y="y"
)
return chart | 5ee0198975ac7db16023b159d7533d59c313cc96 | 52,108 |
from algs20_graph.single_source_sp import dijkstra_sp
def single_source_shortest_path(graph, src):
"""
Act on Single Source Shortest Path and return path as dictionary, where
each node is expanded to have its
"""
(_, edge_to) = dijkstra_sp(graph, src)
expanded = {}
for n in graph.nodes():... | 0d7077933fe23f811fff3a2c06a8f3fc8c2d2971 | 52,109 |
def busco_datasets():
"""BUSCO dataset information
:return: List containing information for each dataset available in file BUSCO_dataset.csv under data directory.
.. seealso:: Additional information on BUSCO datasets available.
- :doc:`BUSCO datasets <../../../data/BUSCO_datasets>`
.. seealso:: This func... | 16c581e55967f273321f4b4f68a74f9868d7a319 | 52,110 |
def aveThick(sit):
"""
Only calculates ave thickness for min and max time... no area weighting
"""
minSep = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,9,:,:],(1,2)))
minMar = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,3,:,:],(1,2)))
print '\nCompleted: Calculated average for Sept/Ma... | 377eab13adbd3f25041337cb7fe784a78b44a74b | 52,111 |
from typing import Dict
from typing import Mapping
import inspect
from typing import Optional
from typing import Any
from typing import Tuple
import functools
def BP(bp_state: BPState, temperature: float = 0.0) -> BeliefPropagation:
"""Function for generating belief propagation functions.
Args:
bp_st... | e96bf22c2e07ec59b1e0c7d653f8956a82b5c3a5 | 52,113 |
def whois_reg_date(whois):
""" Fecha en la que fue registrado el sitio"""
reg_date = []
try:
reg_date = whois.creation_date
if reg_date != None:
if isinstance(reg_date, datetime.date):
reg_date = reg_date
elif len(reg_date) > 1:
reg_dat... | 4c31088349bc45580dc758879ca1dfedef4d8c4a | 52,114 |
def nnlsfit(data, bvals, region=None):
""" Implement Non Negative Fitting for IVIM
Parameters
----------
data: array-like, 4D Matrix
bvals: array-like
region: array-like, [(x1,x2),(y1,y2),(z1,z2)]
optional (default= None)
Returns
-------
d_star: 3D Matrix
Th... | 8efe51013c0b58e35675c854a23816cb73ca5c02 | 52,117 |
def check_if_scheduled_run(time_run: str = None, time_schedule: str = None) -> bool:
"""
Check if run was scheduled or started by user.
Args:
time_run (str, optional): The time the Flow was started. Defaults to None.
time_schedule (str, optional): Scheduled time of Flow. Defaults to None.
... | 8e9d6db6fe66da9314515a024919e9360b856762 | 52,118 |
def controlled(gate):
"""Return a controlled quantum gate, given a quantum gate.
If 'gate' operates on :math:`n` qubits, then the controlled gate operates
on :math:`n+1` qubits, where the most-significant qubit is the control.
Parameters
----------
gate : np.ndarray[complex]
A quantum ... | 653b92af9d83c0ab30b8ebebe532bc7061f0cfbf | 52,119 |
def get_links(anumberscode):
"""
Finds CloudStor links for selected anumbers
Args:
`anumberscode`=list of anumbers
Returns:
`FilteredList`= list of corresponding links
"""
try:
FileDirectory=pd.read_csv('https://geo.loop-gis.org/files/FileDirectory.csv',encoding = "ISO-88... | eebc6d5d2df162bd43135c1647dce8c03f577e04 | 52,120 |
import copy
def passed_test(dtype, as_matrix, provide_C, trans_a, trans_b):
"""
Run one general matrix-matrix multiplication test.
Arguments:
dtype: either 'float64' or 'float32', the NumPy dtype to test
as_matrix: True to test a NumPy matrix, False to test a NumPy ndarray
... | f595706e6b83c3b8d03481a4a9849d12c9846c6d | 52,121 |
import re
def re_repl_escape(s):
"""
Escape backreferences in a string, for the second arg of re.sub().
Parameters:
s: the string to escape
Dependencies:
modules: re
"""
return re.sub(r'\\([1-9][0-9]?)', r'\\\\\1', s) | 4ae7e4198dd65eb46d8dbbf71cf8f28230eb2c76 | 52,123 |
def get_x_vals(stats: dict, x_type: str, date_range: list[tuple]) -> list:
"""Gets the specified x value within a given date range."""
if x_type in X_OPTIONS.values() and x_type != X_OPTIONS[1]:
return [round(stats[date][x_type]) for date in date_range]
else: # Date
return date_range | 4e4f152dd33dca19704bf426390ced02fb9acb43 | 52,124 |
def allowed_file(filename):
"""判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中"""
return '.' in filename and filename.rsplit(
'.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] | 6b4426e8f35b5e89ca8f28a8c55a4f6cd422b3e6 | 52,125 |
def split_data(data, ratio, shuffle=1):
"""Split dataset according to ratio, larger split is first return"""
n_exs = len(data[0])
split_pt = int(n_exs * ratio)
splits = [[], []]
for col in data:
splits[0].append(col[:split_pt])
splits[1].append(col[split_pt:])
return tuple(splits... | fc837dd9f721950dde18cee9ec33eab5e3e96f77 | 52,127 |
def get_user_session_data(parent_folder, user_id, user_session_id):
"""
Combine accelerometer, gyroscope, and activity labels for a specific session of a user
Note: Timestamps are ignored when joining accelerometer and gyroscope data.
:param user_id: user id
:param user_session_id: user session id
... | 1067c791085230a910c8682a293d600888dc2223 | 52,128 |
def jtag(tag):
""" Helper to translate tag to serializable format"""
return (tag[0].devanagari(strict_io=False), [t.devanagari(strict_io=False) for t in list(tag[1])]) | cb8245a435d67d9678e71d449ae9401b9562cb4c | 52,129 |
import math
def _nongeo_latlng2xy(lat_deg, lng_deg):
"""
"""
lat = _DEG_TO_RAD * lat_deg
lng = _DEG_TO_RAD * lng_deg
# First, project to pseudo-mercator
# https://en.wikipedia.org/wiki/Web_Mercator_projection#Formulas
x_proj = _EPSG_3857_X_EXTENT / (2.0 * math.pi) * lng
y_proj = _EPSG... | b062d453339924e4d15a57830e41978488b98044 | 52,130 |
def read_file(file_path):
"""Reads a file contents given a file path"""
file_contents = None
with open(file_path) as f_desc:
file_contents = f_desc.read()
if not file_contents:
raise CLIError('Could not read {}'.format(file_path))
return file_contents | 4688e7c58abc5b6c384e85dbb98f35127085c7f2 | 52,131 |
def part_2a_namd_equilb_NPT_control_file_written(job):
"""General check that the namd_equilb_NPT_control_file
(high temperature to set temp NAMD control file) is written."""
return namd_control_file_written(job, namd_equilb_NPT_control_file_name_str) | 7f77e47be8d2b88bec843de02b7447b0360a2870 | 52,132 |
from typing import Optional
from typing import Dict
from typing import Union
from typing import List
def AutoLayoutModel(
config_path: str,
model_path: Optional[str] = None,
label_map: Optional[Dict]=None,
device: Optional[str]=None,
extra_config: Optional[Union[Dict, List]]=None,
) -> "BaseLayout... | 6d1d4d7f637491bcdbb10b9b93575a53733627eb | 52,133 |
def assert_positive_negative_temporal_consistency(y, t, month_variance=1):
"""Helper function to assert malware-goodware temporal constraint (C2).
In any given testing period, all testing objects must be from the time
window under test. In the malware domain this constraint has often been
violated so t... | ae8c05dd92d990f7fe5260723033c59c051fd710 | 52,134 |
def shape_small_first(shape):
"""sort a tuple so that the smallest entry is swapped to the beginning
"""
if len(shape) <= 2: # no changing dimensions if channel-dim is missing
return shape
smallest_dim = np.argmin(shape)
if smallest_dim != 0: # assume that smallest dim is color channel
... | 0caf5a69d2c12dff31deb002891df71886ce19b7 | 52,135 |
import io
def reformat_cmplx_hoh(cmplx):
"""
get a complex has HoH and split it
"""
stoi = []
for cond in cmplx:
tmp_stoi = io.makehashlist()
tmp_prot_nr = []
for repl in cmplx[cond]:
pks = {k: cmplx[cond][repl][k]["I"] for k in cmplx[cond][repl]}
pk... | e8b6361e7637bc7bc446cd795935cfb3899fc731 | 52,136 |
def filter_builtin():
"""filter: Filter items using a function. Prefer list comprehension."""
return "{}ged top secret".format(
''.join(filter(lambda info: info not in 'open', "pentagone"))) | ae1d96fb5bfa4a675538bf33a5adcd2d2f64c6e5 | 52,137 |
def calculate_gold(*items):
"""Calculate gold for buying given items"""
# access cost in the item dictionary
get_cost = lambda x: x[0][x[1]]['cost']
# return sum of costs of all items
return sum(
# get cost of each item
map(get_cost,
# map items onto their categories
... | 08b1ccd6599d111119c8b2fcbf3a02e0d16d6978 | 52,138 |
from typing import Optional
from datetime import datetime
def skip_reload(cache_load_time: Optional[datetime.datetime], refresh_cache: bool) -> bool:
"""Skip reloading the cache?"""
return abc_depoyment_map.skip_reload(cache_load_time, refresh_cache, REQUIRE_REFRESH_LIMIT) | 81e482b0e43f7f240cbe70733d340fd7f84d6a53 | 52,139 |
def combined_bbox(layers):
"""
Returns a bounding box for ``layers`` or None if this is not possible.
"""
bboxes = [layer.bbox for layer in layers
if layer.bbox is not None and layer.bbox.width > 0 and layer.bbox.height > 0]
if not bboxes:
return None
lefts, tops, rights, ... | c2843bf23393c8d3e75a3fe862e488101dcfbdd0 | 52,140 |
import delphin.codecs
import importlib
def import_codec(name: str):
"""
Import codec *name* and return the module.
"""
codecs = namespace_modules(delphin.codecs)
fullname = codecs[name]
return importlib.import_module(fullname) | cba864133e3cce3e44e06eac23224f6e60b025fe | 52,141 |
def is_named(name):
"""
:samp:`Predicate for loose class-name detection.`
::
f(cls) = cls.name == name or cls.qualified_name == name
:param name: the class-name or qualified class-name in the detection
:return: lambda for loose class-name detection
"""
return lambda cls: name == c... | d26fbb6d853f195cfcc70a6f1791cbacfc7aebd7 | 52,142 |
def get_and_colleagues(ref_string):
"""
:param ref_string:
:return:
"""
match = COLLEAGUES_PAT.search(ref_string)
if match:
andcolleagues = match.group('andcolleagues')
return ref_string.find(andcolleagues), len(andcolleagues)
return 0, 0 | 1a9c2c5f46f7bee9eecbd960c8a2b5e591e80790 | 52,143 |
from django.utils.module_loading import import_string
def app_factory(global_config, django_wsgi_application):
"""
Paste app factory that imports and returns the given WSGI applicaton.
Args:
global_config: The global paste configuration
django_wsgi_application: The wsgi application to dep... | 829d33e21594da6066cc1116985b3292e75186ca | 52,144 |
def fix_arn(arn):
"""Function that attempts to "canonicalize" the given ARN. This includes converting
resource names to ARNs, replacing incorrect regions, account IDs, etc."""
if arn.startswith("arn:aws:lambda"):
parts = arn.split(":")
region = parts[3] if parts[3] in config.VALID_REGIONS el... | 109b0450b9ebd01d6aeba17fc28ef069d1c4544c | 52,145 |
from typing import Any
from typing import Iterator
def ocr_extract(image_data: bytes, link: str, tld: str) -> list[str]:
"""Scan for all valid URLs from a given `image_data` bytes string
Args:
image_data (bytes): Bytes string of image to be scanned
link (str): URL source of image to be scanne... | 4c3507ef1488abdaf2c39eba5ab95c6b782ee785 | 52,146 |
def route(route : dict[str : FunctionType], filter : FunctionType = lambda x : x):
"""Routes links in clisd.py"""
last_link = None
def route_link(e=None, page : str = None, _route : dict[str : FunctionType] = route):
route = _route
# Finds page to route in url
if page:
... | 2563d1600cf2f6129a7f2370445d76f66df136f3 | 52,147 |
import imghdr
def make_answer():
"""Create the message to send"""
# Create the message and set a subject
msg = EmailMessage()
msg["Subject"] = "A random image."
try:
# Choose an image
attachement = IMG_FOLDER + "/" + rdm(IMG_FOLDER)
# Attach the image to the email
... | 9fba96f904de770772580f275229e7540d1db86c | 52,148 |
from typing import List
def download_assets(stac_item: StacItem,
save_directory: str,
from_bucket: bool = False,
nsl_id: str = None) -> List[str]:
"""
Download all the assets for a StacItem into a directory
:param nsl_id: ADVANCED ONLY. Only nece... | eda98decae5709dfe66d13a9dfd2a19b7a29483f | 52,149 |
def shake_128() -> HashAlgorithm:
"""
Convenience function to create hash algorithm object.
"""
return HashAlgorithm(HashAlgorithmId.SHAKE_128) | cced46c8650e24a33772f6b656e5c5c785315318 | 52,150 |
def update_action_effects_with_negated_counterparts(action: Action, negpreds):
""" """
neweffects = []
for eff in action.effects:
if not is_propositional_effect(eff):
raise RepresentationError(f"Don't know how to update negated counterpart atoms for effect {eff}")
atom = eff.ato... | 610253ed171d72941374826b0fa629b1cc6a5f0b | 52,151 |
from typing import Any
def is_listlike(x: Any) -> bool:
"""Check whether `x` is list like, e.g., Tuple, List, or Numpy object.
Parameters:
----------
x: A python object to check.
Returns:
----------
`True` iff `x` is a list like sequence.
"""
return (isinstance(x, (list, tuple))) | 5820a62e0fcb8fead77485c896b3aa864ef555f0 | 52,152 |
def datasetDataText(request, dataset_name):
""" Returns data in text format for a specific dataset. """
#
header_language = request.GET.get('header_language', None)
#
dataset = models.Datasets.objects.get(dataset_name = dataset_name)
dataset_file_name = dataset.dataset_file_name
#
data_a... | c3ccc9430574160f0839ca12bd063010ea8036d4 | 52,154 |
def order_detail(user_key, category_key, order_key):
"""
The page showing the details of a single order -Fetch a specific order
including all steps (GET)
It also handles PUT and DELETE of the order
It also handles updates an existing order
"""
error = None
editable = False
order_deta... | 4b181867c07f8ef293357fa4da16014330957871 | 52,155 |
def distance_corr(X, Y):
"""
Computes the distance correlation between X and Y.
Taken from pypi package dcor based on the paper:
*Measuring and testing dependence by correlation of distances*
by Gábor et Al (2007)
Parameters
----------
X : numpy array like object where the rows correspon... | b4b85c58041760d96e852ad032fd6227f15dc8e1 | 52,156 |
import json
def pinyin_dict_affiche(request):
"""recevoir les valeurs des formulaires front-end via POST
et transmission des informations pinyin analysées au front-end
Args:
request (QueryDict):
les valeurs des formulaires front-end
Returns:
data_pinyin (JSON):
... | a2e167250cf6df2b78f33dfb18a47825d3eed928 | 52,157 |
def diff_sort(matrices, x, softmax=softmax):
"""
Approximate differentiable sort. Takes a set of bitonic sort matrices generated by bitonic_matrices(n), sort
a sequence x of length n. Values may be distorted slightly but will be ordered.
"""
for l, r, map_l, map_r in matrices:
a, b = l @ x,... | 25152f16b9c0ec4ca81ea0e44d4642bf5a7d257f | 52,158 |
def searchwiki(txt, lang='en'):
""" parse wiki data. """
input = []
for i in txt.split():
if i.startswith('-'):
if len(i) != 3: continue
else: lang = i[1:]
continue
input.append(i.strip().capitalize())
what = "_".join(input)
url = u'http://%s.... | e6be584fee726e9781e39078a9ab7588e130b8ef | 52,159 |
import torch
def test():
"""Runs the model on the test data."""
modelA.eval()
modelB.eval()
test_loss = []
errors = []
with torch.no_grad():
for batch_idx, data in enumerate(test_loader):
data = data.permute(0, 3, 1, 2)
dataA = data[:, modA].float().to(device1)
... | ef73bef6f5722cca7b42336f7a6e43bc67673eb9 | 52,160 |
def ifgcfg_exists(ifgcfg_id, version):
"""Return True if ifg-cfg exists."""
query = {
"query": {
"ids": {
"values": [ifgcfg_id],
}
},
"fields": []
}
index = "grq_{}_s1-gunw-ifg-cfg".format(version)
result = query_es(query, index)
r... | 7d40dc1b45ae5ad2573baffc5dcbd148677a7757 | 52,161 |
def calibration_image(file_name, coordinates):
"""calibrate a source image
Arguments:
file_name {int} -- image index
coordiantes {list} -- list of coordinates for homography to plot
"""
prefix_length = 6 - len(str(file_name))
source = path_to_image + str(0)*prefix_length + str(file_... | 6b37d387418c8c1328d450220b204ed6d182ae1d | 52,163 |
import codecs
import logging
def decompress(structure: Value):
"""
Performs decompression on the input value if the codec field has been set and is valid. If the data is being sent
uncompressed already, will just reshape the data using the sizes specified in the dimension field.
Parameters
------... | a3b07a4bcb5dc91344ea339033f1adf27c3e01e6 | 52,164 |
import scipy
def incubation_dist(t: np.ndarray) -> np.ndarray:
"""Incubation period as a log-normal PDF (Lauer et al., 2020).
Args:
t: np.array of days of incubation (i.e. days from infection to symptoms).
Returns:
Relative probability of the specified incubation time.
"""
mu = 1.621
sig = 0.418... | 39f6c570440afe3afb77d65563871079d2cb34bf | 52,165 |
def pid_from_context_or_data(value, context, **kwargs):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
if pid is None:
return value
else:
return pid.pid_value | dff32845ea0d2541503802bdd85ccb299091325b | 52,166 |
import re
def clean_phoenix_2014_trans(prediction):
"""
Yutong
I think the format of ground truth annotation is already well processed.
Some parts of predicted gloss sequence might be processed using this func. e.g. combine single char with +
"""
prediction = prediction.strip()
prediction ... | eceb6f43cc51f66d88045d5eecea7144cf3eaaaf | 52,168 |
import six
def ManagerFactory(name, superclass, qs=QuerySet):
"""Create a manager class, using the given superclass, and adding
django_pg's specific behavior.
"""
# It's completely fine to use our custom manager for related fields,
# and it's necessary, since we need to ensure that our custom quer... | c950898a4ce8fe886f740e2799163a002fd65f79 | 52,169 |
import math
def gfit1(xi,yi,m=5):
"""
moments around a peak
(also) rely on number of pixels left and right of the peak. Masking optional
"""
print("GFIT1")
ipeak = yi.argmax()
xpeak = xi[ipeak]
ypeak = yi[ipeak]
print(ipeak,xpeak,ypeak)
print(xi[ipeak-m:ipeak+m])
print(yi[i... | 3d7f5ccdece2a7fb4f0988a169b35e2f3671f4a3 | 52,170 |
def characteristic_matrix_p(lambda_, d, n, theta):
"""Compute the characteristic matrix M_j^p for a layer of a material stack and p-polarized light.
Uses (4.49) to compute (4.55) from BYU optics book, edition 2015
Parameters
----------
lambda_ : `float`
wavelength of light, microns
d :... | cc67de317b94be42d9f1478b3ae2063d60b9bfaf | 52,171 |
def nets_ib_by_bus_zone_with_boundary_branches(
net, eq_type=None, separate_eqs=True, duplicated_boundary_bus_elements=True, **kwargs):
"""
INPUT:
**net** - pandapower net - In net.bus.zone different zones must be given.
OPTIONAL:
**eq_type** (str, None) - If given, equivalent eleme... | b4de2d1e4be3e2003fd43ffee00f9bed51f6cfb4 | 52,172 |
import random
def get_label_colours(num_class):
"""
return color code for visualizing affordance/object map
"""
all_label_colors = []
random.seed(255)
for i in range(num_class):
curr_color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
all_label_colo... | aaa99885779cc51d2812c3df9e3814afaa495604 | 52,173 |
import time
def timed(fn):
"""Simple timing decorator that stores the elapsed time
as a string property called 'timed' to the fn.
"""
@wraps(fn)
def _timer(*args, **kwargs):
start = time.time()
fn(*args, **kwargs)
end = time.time()
diff = end - start
elapse... | 0c63c21cc1eaf2930ae58ff46a07818503aeac47 | 52,174 |
def get_column_letter(col_idx):
"""Convert a column number into a column letter (3 -> 'C')
Right shift the column col_idx by 26 to find column letters in reverse
order. These numbers are 1-based, and can be converted to ASCII
ordinals by adding 64.
"""
# these indicies corrospond to A -> ZZZ ... | 6f65209d6fc38f3d858d36b4c21908cafea2a494 | 52,175 |
def get_default_cacheinfo():
"""
Return default CacheInfo
"""
return __cacheinfos[__SECTION_CACHE_DEFAULT] | 84aee842b1e0614dd4403644c7c095baa5d2fc23 | 52,176 |
def get_packets_for_flows(sub, flows):
"""
Get packets sent from a subscriber to match a set of flows
Args:
sub (SubscriberContext): subscriber to send packets towards
flows ([FlowDescription]): list of flows to send matching packets to
Returns:
list of scapy packets to send
... | 9b0b210c4e7ff3a8e8f2367d6208350340a14b32 | 52,177 |
def lower_array(x1_arr, y1_arr, x2_arr, y2_arr):
"""function to find the lower bound of two curves(x1, y1), and (x2, y2) represented by two arrays.
"""
# special use: for the first comparison, if y1_arr is [], then y2_arr is passed to it
x1_arr = np.asarray(x1_arr)
x2_arr = np.asarray(x2_arr)
y... | ff985873295697554cb1c1d7e79b327dec2d7e92 | 52,178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.