content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_df(dass_words, dfcp_words):
"""
this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context
it returns this dictionary
"""
dass = {}
dfcp = {}
data = [dass, dfcp]
for listed_values in dass_words: # access single lis... | 43e5715808247d726a353e7841a5dbc2aa117740 | 3,617,281 |
import string
def t(message):
"""Replace $country and $language in message with dat from settings"""
tpl = string.Template(message)
return tpl.substitute(country=settings.COUNTRY_NAME, language=settings.LANGUAGE_NAME) | 6e9464ebaa915e15420499768f40199a9abc57c5 | 3,617,282 |
def login_handler(fn):
"""
A decorator to redirect users to AWS Cognito login if they aren't already.
If already logged in user will redirect redirect uri.
Use this decorator on the login endpoint.
This handle will not return to handle the respose rather redirect to
redirect uri.
"""
@wr... | f9a84963b50314f4b37c5fc7bf295cd8074b5a89 | 3,617,283 |
def launch(tenant, addrs=DEFAULT_ADDRESS, period=DEFAULT_PERIOD):
""" Initialize the module. """
return RSSITracker(tenant, addrs=addrs, every=period) | 8784326a2083cc12247183de5f5d1e7327cfc821 | 3,617,284 |
import inspect
def register(cls_obj=None, encode=None, decode=None):
"""Register a serializer class.
By default the serializer will use the class type "__getstate__" and "__setstate__" methods if an encode and decode
method is not given.
Args:
cls_obj (class/type): Class/Type/object to regis... | 273868278a777299c4362c30278669b19ee9b6fd | 3,617,285 |
def random_resize(image, min_image_size, max_image_size, max_out_prob=0.,
resize_method=tf.image.ResizeMethod.BILINEAR):
"""Randomly resize the image while preserving aspect ratio.
Args:
image: 3D image tensor.
min_image_size: minimum size for the longer side of the image.
max_image_s... | 2afcbcff8dcaa2514b8b1fe464ab0182603e51ed | 3,617,286 |
def broyden_class_update(y, s, mat, phi=0.0):
"""
Scale free implementation of the broyden class update scheme.
:param y:
difference in gradient
:param s:
search direction in previous step
:param mat:
current hessian approximation
:param phi:
convex combination p... | e1ee7f0eab5a05e3867f367ff305a743f742377c | 3,617,287 |
def resolve_jobs(job_counts, start, length):
"""
:param job_counts: list of blocks(queue, registry, job_count)
:param start: job start index for datatables
:param length: number of jobs to be returned for datatables
:return: list of jobs of len <= "length"
It may happen during processing some j... | 436314b4370806b7f172e0f02ef28a5af0a72104 | 3,617,288 |
def star(x, y, points=20, outer=100, inner=50, **kwargs):
""" Draws a star with the given points, outer radius and inner radius.
The current stroke, strokewidth and fill color are applied.
This is about 20x slower than fast_star; use it only if you need the path returned.
"""
p = BezierPath(... | 44d361471df0f920978914aba2190cf17155aec9 | 3,617,289 |
def q_in_valid_range(q):
"""
Asserts that q is either 1, 2 or 3.
For other values, the formulas have not been implemented.
"""
assert 1 <= q <= 3, "Please enter q in {1,2,3}"
return True | 6ef79efde7376f0743bc840fe394707a8f9b213f | 3,617,290 |
import hashlib
def sha512_first_half(message: bytes) -> bytes:
"""
Returns the first 32 bytes of SHA-512 hash of message.
Args:
message: Bytes input to hash.
Returns:
The first 32 bytes of SHA-512 hash of message.
"""
return hashlib.sha512(message).digest()[:32] | 591a0096e643af32326ae051f9a993db82a758c5 | 3,617,291 |
def find_svc_icon(id):
"""
Locate the absolute path of an ICON for a AWS service.
:type id: str
:param id: service id, for main service it is ``ec2``, for sub service it is
``ec2-instances``
:rtype: str
"""
if id in svc_icon_mapper:
return Icons.abspath(svc_icon_mapper[id])... | 542ff27cc154d9843b2a1df16d77b18c8a420539 | 3,617,292 |
import re
def order_parquet_files_into_batches(parquet_files):
"""
Order the parquet files by searching for a digit within their name.
Returns the parquet files without their numbering or extension.
Parameters
----------
parquet_files : List
List of parquet files to be ordered.
""... | 0d748c5ae50ef49ba98386ee172db0e850a8b9a8 | 3,617,293 |
def get_xml_temperature (root):
"""
Get the temperature from the unit diagnostics XML.
Parameters:
root -- An XML element to the root of the unit diagnostics.
Return:
The system temperature or -1 if the temperature redaing isn't valid.
"""
if (get_xml_string_va... | d2490b6b5f6df63943c042255b7aa0776baa1a72 | 3,617,294 |
def median(arr: list):
"""
Returns the median and its index in the array.
"""
indices = []
list_size = len(arr)
median = 0
if list_size % 2 == 0:
indices.append(int(list_size / 2) - 1) # -1 because index starts from 0
indices.append(int(list_size / 2))
median = (arr... | 639a6d4efbc91457520ef1411ef7b935fb477b82 | 3,617,295 |
import itertools
def plot_confusion_matrix(cm, classes, title="Матрица ошибок", cmap=plt.cm.winter):
"""
Визуализация матрицы ошибок с помощью Matplotlib
cm - матрица ошибок
cmap - стиль оформления
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title, fontsize=30)
plt... | c0c39d27d05232c10a8b6e8e99036e73285073a0 | 3,617,297 |
from typing import Union
import random
import string
def add_nonce_func(
string_array: Union[str, int, float, np.array]
) -> Union[str, int, float, np.array]:
"""
Add random prefix and suffix to an array of strings ``string_array``
This function takes an array of strings passed as ``string_array`` an... | ba72b29c878681c0b70be549a6f1effa83748cfa | 3,617,298 |
import copy
def rename_block_mesh(block_mesh_template_path, foam_files_templates):
"""rename the template to blockMeshDict, and leave in the templates folder for now.
Args:
block_mesh_template_path (str): full path of edited blockmesh template.
Returns:
blockMeshDict_for_run (str): rename... | 768a9b6bb051771548c7ee4443b3d9491170c1a0 | 3,617,299 |
def kmeanspp(matrix, k, *, msr=2, prior=0., seed=0, ntimes=1, lspp=0, expskips=0, n_local_trials=1, weights=None):
"""
Compute kmeans++ over the input matrix for given parameters.
Inputs:
Input matrix: sp.csr_matrix, minicore.CSparseMatrix, or numpy.ndarray
Second argument (k=) can... | 9728889b7a27412963685253d4c40b98235d3863 | 3,617,300 |
def find_constant_lengths(feature, tol=1e-6):
"""
Find lengths of all constant periods in feature data.
Parameters
----------
feature: Numpy array (shape: N)
Vector with feature data for all time
tol: Float (default=1e-2)
What scale factor is applied to variance to determine va... | deed394a7be9a33a8a1dbeedaeb5a52ee7a17f47 | 3,617,301 |
def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag... | 6b48e9b4307f04a99067397e931ec65f4a73f10b | 3,617,302 |
import signal
def eliminate_stim_artifact(raw, events, event_id, tmin=-0.005,
tmax=0.01, mode='linear'):
"""Eliminates stimulations artifacts from raw data
The raw object will be modified in place (no copy)
Parameters
----------
raw : Raw object
raw data objec... | b10a7f61ce186b4d2bd6100980accd489905be9c | 3,617,303 |
import torch
def fast_nms(multi_bboxes,
multi_scores,
multi_coeffs,
score_thr,
iou_thr,
top_k,
max_num=-1):
"""Fast NMS in `YOLACT <https://arxiv.org/abs/1904.02689>`_.
Fast NMS allows already-removed detections to suppress other d... | f9f027fdb3ff09dc2ffa76689e5ca2107d595eb6 | 3,617,304 |
def is_(a: object, b: object) -> bool:
"""
Return `a is b`, for _a_ and _b_.
Example:
>>> is_(object())(object())
False
Args:
a: left element of is expression
b: right element of is expression
Return:
`True` if `a is b`, `False` otherwise
"""
return... | 6edda9af046f6a45f37578c073ed0e21e3320778 | 3,617,306 |
def recurse_sigfig(per_offset_data, num_digits):
"""
Recurse through a dictionary of offset data. Any impacts to ecosystem
services will be rounded to `num_digits` significant figures.
Parameters:
per_offset_data(dict): A dictionary of values, mapping string parcel
IDs to dictionar... | 765168e2e99d8c7dc5742f7db7ff4548e69c46c7 | 3,617,307 |
def generate_vpt_title(radar, field):
"""
Generate a title for a VPT plot.
Parameters
----------
radar : Radar
Radar structure.
field : str
Field plotted.
Returns
-------
title : str
Plot title.
"""
time_str = generate_radar_time_begin(radar).isofor... | bac41da795a261a17a6a543df3a53897a636722e | 3,617,308 |
from typing import Optional
def get_event_bus_policy(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEventBusPolicyResult:
"""
Resource Type definition for AWS::Events::EventBusPolicy
"""
__args__ = dict()
__args__['id'] = id
if op... | 91e6c4d701a86197fab77bb9143498999ddf84bb | 3,617,309 |
def scan_list(request):
"""
The function listing all ZAP Web scans.
:param request:
:return:
"""
all_scans = zap_scans_db.objects.filter(rescan='No')
rescan_all_scans = zap_scans_db.objects.filter(rescan='Yes')
return render(request,
'scan_list.html',
... | 0fa7745879031e45c8ad02b6e0bc60d36d543847 | 3,617,311 |
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int:
"""Set the default contact rating for mechanical relays.
:param contact_form_id: the current contact rating ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _contact_rating_id
:rtype: int
"... | e39f5f9701d4314cd19109ce08c599b3737cd064 | 3,617,312 |
def get_vector_info(vector_path, layer_id=0):
"""Get information about an GDAL vector.
Args:
vector_path (str): a path to a GDAL vector.
layer_id (str/int): name or index of underlying layer to analyze.
Defaults to 0.
Raises:
ValueError if ``vector_path`` does not exist... | adaf6eac80a6d816ef306d5a546494d2e7462b07 | 3,617,313 |
def create_report(user_options: UserOptions) -> Report:
"""
Analyse whether a Python package follows a set of contracts, returning a report on the results.
Raises:
InvalidUserOptions: if the report could not be run due to invalid user configuration,
such as a module that... | e2d4912100fdbca8e3f6e5b252bf68ca6d6156dd | 3,617,314 |
def calc_rms(data, channel, num_channels, num_samples_per_channel):
""" Calculate RMS value from a block of samples. """
value = 0.0
index = channel
for _i in range(num_samples_per_channel):
value += (data[index] * data[index]) / num_samples_per_channel
index += num_channels
return ... | ee5a8e00aed046dffc552a89253edf9c49f5857c | 3,617,315 |
import json
def _read_color_map(path, object_hook=None):
"""
Read a color map as json.
:param path (str): The path to read the map from.
:param object_hook (func): A Function to manipulate the json.
:return: A dictionary of color map.
"""
with open(path) as f:
return json.load(f, o... | 34c627443cd418d84b19bd54b3e79427d8168b1e | 3,617,316 |
def train_forward_parameters(args, net, predictions, targets, loss_function,
forward_optimizer):
""" Train the forward parameters on the current mini-batch."""
if predictions.requires_grad == False:
# we need the gradient of the loss with respect to the network
# out... | c0376e8ddc059864700ffe68492dc8b6226aac66 | 3,617,317 |
def device_of_devicendarray(devicendarray):
"""
Returns the device that backs memory allocated on the given
deviceNDArray
:param devicendarray: devicendarray array to check
:return: int device id
"""
dev = device_of_gpu_matrix(devicendarray)
return get_visible_devices()[dev] | bf2ba4c54dd0bcd5e51561cfdae35aebf3a6ff33 | 3,617,318 |
def create_warehouse() -> Warehouse:
"""Create a ware house."""
warehouse_yml = create_warehouse_yml()
warehouse = Warehouse(warehouse_yml)
return warehouse | 6bcbca3d4d08bca628525f0bd6f53f26b8932b26 | 3,617,319 |
def transformer(model: str = 'xlnet', **kwargs):
"""
Load Transformer emotion model.
Parameters
----------
model : str, optional (default='bert')
Model architecture supported. Allowed values:
* ``'bert'`` - BERT architecture from google.
* ``'tiny-bert'`` - BERT architectur... | 10b59175bba04dec90aa21554246349d05f50adc | 3,617,320 |
import asyncio
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
await asyncio.gather(
*[
hass.async_add_executor_job(gateway.websocket_disconnect)
... | f6c7ccdace7f2f7d6d53a0aadcc4e591df0ac4c9 | 3,617,321 |
def convertd2b(amount, x_pow, y_pow):
"""Apply the equation to get the result. Decimal to binary."""
res = amount * (10 ** x_pow / 2 ** y_pow)
return res | 8a6c7ca98a351b9a6f6c499954f7d8a533559122 | 3,617,322 |
def revtranslate(aa, dna, check=False):
"""Reverse translates aminoacids (with gaps) into DNA
Must supply original ungapped DNA.
"""
# trim stop codon
#if aa[-1] in "*X" and CODON_TABLE.get(dna[-3:], "") == "*":
# aa = aa[:-3]
# dna = dna[:-3]
a = len(aa.replace("-", "")) * 3... | 6de38c790fde63abaf27dcf632b81ef976ee66a0 | 3,617,323 |
def plot_season_avg(
poll_df,
pollutant,
ax,
plot_error=True,
roll=True,
agg='max',
color='blue',
linestyle='solid',
linewidth=2, label=None, offset=182, draw=True, ci=95):
"""Plot the average by date of year. Good for looking seasonal pattern.... | f00eed1f793d65f8acdaea9c64c8ff3a38596dcb | 3,617,324 |
def task_3_list_customers_in_germany(cur) -> list:
"""
List the customers in Germany
Args:
cur: psycopg cursor
Returns: 11 records
"""
cur.execute("""SELECT * FROM Customers WHERE country='Germany'""")
return cur.fetchall() | bf6465cc590cfe7d45817eff02e0dbaacb02e195 | 3,617,325 |
def split_numpy_array(array, portion=None, size=None, shuffle=True):
"""Split NumPy array into two halves, by portion or by size.
Parameters
----------
array : np.ndarray
A NumPy array to be splitted.
portion : float
Portion of the second half. Ignored if `size` is specified.
... | 3914131e3cfd4afe6292a6f401be0040a6aedb59 | 3,617,326 |
def two_agents_three_actions() -> MACID:
"""This macim is a representation of a
game where two players must decide between
threee different actions simultaneously
- the row player is agent 1 and the
column player is agent 2 - the normal form
representation of the payoffs is as follows:
+... | 04de1be6c09d26afe829c9b34a275fcdc9290cc0 | 3,617,327 |
def volume_unit_to_litres(symbol):
"""Convenience function that returns the factor one must multiply to convert a physical quantity with the specified
unit of volume into litres."""
return volume_units.get_scale_factor(symbol) | fafb42a085392cbf0a073e847718c2f2d5cc3410 | 3,617,328 |
def state_task_result_update(task_result, task_result_reason, task_work_result,
task_work_result_reason):
"""
Update State Task Result given a state task work result
"""
if STATE_TASK_WORK_RESULT.WAIT == task_result:
# Nothing to update
return task_result, ta... | d22424788d0488f7352f63f3e41f41149b8e62a8 | 3,617,329 |
def im_detect(net, im, _t, idx):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
s... | fcca9d2548e1a52f7cf9049913d9beb64ccf9feb | 3,617,330 |
def find_page(pages, limit, value):
"""
Function to calculate and return the current page of a paginated result.
:param pages:
:param limit:
:param value:
:return:
"""
page_range = [limit * page for page in range(1, pages + 1)]
for index, my_range in enumerate(page_range):
if... | d1b97fb0c6c54c85b748922fb6df3d96121ea3c7 | 3,617,331 |
def get_gcloud_config_value(monkeypatch):
"""Returns predictable gcloud config values for testing.
Args:
monkeypatch: Fixture helper.
"""
def get_gcloud_config_value_for_tests(key, default=None):
"""Returns predictable gcloud config values for testing.
Args:
key: Config key to retrieve, e.g.... | 77eb1734a2cf459d7235fecfeefb665b311509dc | 3,617,332 |
def dict_to_str(d):
"""Represent dictionary as string.
Represents a dictionary as a string. This is useful when
a representation for a filename is desired. The function
will unroll all keys and join their parameters with '_',
yielding a single string for the dictionary.
Parameters
--------... | 4279cbc08dde9ef4e513cd562c66f63f09c866fa | 3,617,333 |
def compare(guess, answer):
"""
Compare guess and answer
Arguments:
guess -- a 4-digital number string of the guess.
answer -- a 4-digital number string of right answer.
Returns:
cow -- a number of the user guessed correctly in the correct place.
bull -- a number of the user gu... | f615f4ebd555c0c4119d0fcbf9ae581146fe7816 | 3,617,334 |
def discordance(CRITERIA, ACTIONS, PERFORMANCES, THRESHOLDS, CATEGORIES):
"""
Calculates the discordance matrix for a given reference profile.
:param CRITERIA: List containing the names of the criteria as strings.
:param ACTIONS: List containing the names of the actions as strings.
:param PERFORM... | 301977c3ef0089c55be12e534253fc4ed5a9aabb | 3,617,335 |
def mkid():
"""Generates a uuid4 (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0') using the Python
uuid module
Returns:
string: a unique universal ID of type 4. (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0')
"""
return str(uuid4()) | 8c65dd190f1837b967a2ab4edcfe101749e94668 | 3,617,336 |
def colinterp(a, x):
"""Interpolates colors"""
l = len(a) - 1
i = min(l, max(0, int(x * l)))
(u, v) = a[i:i + 2, :]
return u - (u - v) * ((x * l) % 1.0) | 6e1ad7b020d2aaf58f95129551fd720c20f751ef | 3,617,337 |
def _get_parent_node_by_pred(node, pred, search_current=False):
"""Find the first parent node that satisfies a predicate function."""
if not search_current:
node = node.parent
while node is not None:
if pred(node):
return node
node = node.parent
return None | a69be92c468758ea1faf366c2881588e8f6fd688 | 3,617,339 |
def hdf5_read(f,h,p):
"""Main driver for reading HDF5 files"""
if h.reading == 'metallicity':
arr = hdf5_readmetals(f,h,p)
elif h.reading == 'metalarray':
arr = hdf5_readmetals(f,h,p,single=0)
elif h.reading == 'mass':
arr = hdf5_readmass(f,h,p)
else:
arr = hdf5_gener... | be649e18ce086e4dcf2ca045d601350ce87956d8 | 3,617,340 |
def scale_0to1(image_in,
exclude_outliers_below=False,
exclude_outliers_above=False
, multiply_factor=1.0):
"""Scale the two images to [0, 1] based on min/max."""
# making a copy to ensure no side-effects
out_image = image_in.copy()
min_value = np.percentil... | 0ed0b373eb134e69cb0be4d4f7d631281b5ab141 | 3,617,341 |
def xmlvalue(self, value):
"""Patch for xmlvalue"""
if value.startswith(FILETAG):
return value
return b64encode(value) | 80a270f3045a260a7bc33155d8108974dc81fa01 | 3,617,342 |
def print_device_info(nodemap):
"""
This function prints the device information of the camera from the transport
layer; please see NodeMapInfo example for more in-depth comments on printing
device information from the nodemap.
:param nodemap: Transport layer device nodemap.
:type nodemap: INode... | ad091059edfffa5e8fcd5207e95d0d3752c8ab93 | 3,617,344 |
def compute_roc_from_sparse_glm_smpls(data, x_smpls):
""" Compute the ROC curve given samples from a sparse weighted model
We can estimate p(A_{k,k'} | data) from our samples
"""
# Compute the inferred connectivity matrix
p_A = np.zeros_like(x_smpls[0]['net']['graph']['A'])
for smpl in x_smp... | 1dedd9fc312368d549da7c724c347a9ff1b56ee1 | 3,617,345 |
def column_check(lst):
"""
Function check's whether columns have right numbers, according to the given rows
>>> column_check(['***', ' * 1', '123', '111'])
False
"""
var1 = rebuilding(lst)
var2 = number_row_check(var1)
if var2 is True:
return True
return False | 076481e5d3758f411828af7f44740d6fa37fbf92 | 3,617,346 |
def accuracy(W, x, t):
"""computes the accuracy of the model with the weights W (shape (dim_phi, N_classes))
for a test set x (shape (N_examples, dim_x)) and t (shape (N_examples, K_classes)).
"""
phi = features(x)
y = activity(W, phi)
correct = np.equal(np.argmax(y, axis=1), np.argmax(t, axis=... | 05bab6c93d63c3c199ac4ef74af60232665eb62c | 3,617,347 |
def plot_gottselig(n, datatype='calcs'):
""" plot gottselig normalization for all channels
Parameters
----------
datatype: str (default: 'calcs')
which data to plot [options: 'calcs', 'normed_pwr']
"""
exclude = ['EKG', 'EOG_L', 'EOG_R']
eeg_chans = [x for ... | 867ca393deb4d889290e01eea29d60c90baf263c | 3,617,348 |
def find_val_in_lid_shotlog(shotno):
"""
seigyo.lid_shotlog から対応するショット番号のlidデータを取得する。
LID計算機とのファイル共有の問題が解決されないままとなっているため、現状ではデータを取得できない。
しばらく舟場データを使用する)2013.10.21
Parameters
----------
shotno : int
shot number
Returns
-------
dict
"""
vals = {}
db = get_conn... | 2886f804f89f5808e18afd2439768fed0b381d05 | 3,617,349 |
def SB_oxy_eq(coef,oxyvolts,pressure,temp,dvdt,os,cc=[1.92634e-4,-4.64803e-2]):
"""
Oxygen (ml/l) = Soc * (V + Voffset) * (1.0 + A * T + B * T^2 + C * T^3 ) * OxSol(T,S) * exp(E * P / K)
Original equation from calib sheet dated 2014:
coef[0] = Soc
coef[1] = Voffset
coef[2] = A
coef[3] = B
... | a5db733c9aad88a53c3287c93d9fa66af1c7944e | 3,617,350 |
def make_pipeline_short(pipeline_type):
"""Make a short pipeline."""
pipeline = pipeline_type(
ChunkedStreamLink(),
EventLink(),
)
assert isinstance(pipeline.bottom, ChunkedStreamLink)
assert isinstance(pipeline.top, EventLink)
return pipeline | dbfef9d6fa2bb2f15b2cb48fc4b07d2b9dbfcb49 | 3,617,351 |
def get_task_by_user_id():
"""
{
"page": "Long",
"size": "Long",
"user_id": "Long"
}
"""
domain = request.args.to_dict()
return task_service.get_task_by_user_id(domain) | 7c51402af0b472f4acfb2d56c1e3a9bfcc2054dc | 3,617,353 |
from operator import index
def return_suffix(kind=kind,index=index,dimkeys=dimkeys,copula_string=None,marginal_string = None,marginal_data=None,segment_marginal=None):
"""
:return: a coherent string that permits to give a suffix in the name of our files.
"""
if kind == 'diagonal':
diago = dia... | f429552623e3cb38914eaec7c75c57f5a45b1c2d | 3,617,355 |
def collect_metrics(manager: 'TxMiningManager') -> MetricData:
"""Collect data from TxMiningManager."""
return MetricData(
miners_count=len(manager.miners),
total_hashrate_ghs=manager.get_total_hashrate_ghs(),
txs_solved=manager.txs_solved,
txs_timeout=manager.txs_timeout,
... | dfba9378d03e58e243fb2716f4508b0b36c69216 | 3,617,356 |
def normalize_response(response, request=None):
"""
Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object.
"""
if isinstance(response, Response):
return response
if request is not None and not isinstance(request, Requ... | a92feb1e0fc83b62297567e44c0cbb65ea327ec9 | 3,617,357 |
def _get_user():
"""Get the user object or create it based on the token in the session
If there is no access token abort with 401 message
"""
if 'Access-Token' not in request.headers:
abort(401, message='Access Denied!')
token = request.headers['Access-Token']
user_data = github.get('u... | d08e55e8566de348869a1790067e0a231b49c982 | 3,617,358 |
import typing
def get_notifications_by_type(user_id: int, notification_type: NotificationType, unread_only: bool = False) -> typing.List[Notification]:
"""
Get all (unread) notifications of a given type for a given user.
:param user_id: the ID of an existing user
:param notification_type: the type of... | 1cf14a53a483fe945ae010dea394d0b4185e7f96 | 3,617,359 |
def get_processing_unit_config(unit_config):
"""Returns the :class:`.ProcessingUnitConfig` corresponding to
*unit_config*"""
if isinstance(unit_config, ProcessingUnitConfig):
return unit_config
elif isinstance(unit_config, dict):
unit_name = unit_config["unit_name"]
processin... | c9e73c6f0fd64540c982fdde50e63ed690665655 | 3,617,360 |
from re import S
def partscore_pairs(part,score=S):
"""Scores the partition for student groupings accoring to the provided score class,
by performing the groupscore function for every group in the partition
returns: a number (lower scores mean the partition is more novel)
"""
ss = 0
for group... | e6de1780327f4bf1f3e9ff500a9bb60c9ed364df | 3,617,361 |
import json
import click
def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagi... | 5c84deb086001e0406dc8df9df4510ddc301e0e8 | 3,617,364 |
def float_like(x, /) -> bool:
"""
Tests if an object could be converted to a float.
Args:
x (Any): object to test
Returns:
bool: Whether the object can be converted to a float.
"""
try:
float(x)
return True
except ValueError:
return False | ed34d52e34bc7c09242fde6cd0890381df297325 | 3,617,365 |
def schur_comp(M,idx_set):
"""
computes the schur complement/the pieces of the schur complement for a matrix M
"""
comp_idx = [i for i in range(len(M)) if i not in idx_set]
A = M[np.ix_(idx_set,idx_set)]
B = M[np.ix_(idx_set,comp_idx)]
C = M[np.ix_(comp_idx,idx_set)]
D = M[np.ix_(comp_id... | a651692e410d43711a19ba17496d081c52d235c4 | 3,617,367 |
def noise_db(a, snr):
"""
Takes an array of seismic amplitudes and SNR in dB.
Args:
a (ndarray): seismic amplitude array.
snr (int): signal to noise ratio.
Returns: Noise array, the same shape as the input.
Note: it does *not* return the input array with the noise added.
... | e3f8c7d8623b95226be46bf8b5c32ebc29ac3114 | 3,617,368 |
def get_structure_numbers(structure, momenta_dict):
"""Return the number of the parent and children of a given structure
according to some momenta dictionary.
"""
legs = structure.get_all_legs()
children = frozenset((leg.n for leg in legs))
if structure.name() == "S":
return None, child... | db9548b1e26402bb38e9c33741ca38aa866fd217 | 3,617,369 |
def purchase_number(request):
"""Purchases a new phone number using the Twilio API"""
form = PurchaseNumberForm(request.POST)
if form.is_valid():
# Purchase the phone number
phone_number = form.cleaned_data['phone_number']
twilio_number = purchase_phone_number(phone_number.as_e164)
... | e95455b88119486a6b2de3a128d10960f61eed2c | 3,617,370 |
def oneshot_behavior(behaviour, name=None):
"""
This is taken from py_trees.idiom.oneshot. However, we use a different
clearing policy to work around some issues for setting up StartConditions
of OpenSCENARIO
"""
if not name:
name = behaviour.name
variable_name = get_py_tree_path(beh... | 4840ba86e40c5040f8c31223b2370176819c9a5c | 3,617,371 |
import math
def font_render_multiline(font, text, antialias, color, background=None, justify='left', line_spacing=0):
""" Returns a Surface containing the text in the given font.
The first five parameters are the ones used to render single line text.
justify can be 'left', 'right', or 'center'.
line_... | d18720d585fdd49773335bd2d4218ab974b4826b | 3,617,372 |
def user_conversion():
"""
Best pipeline: GaussianNB(ExtraTreesClassifier(XGBClassifier(input_matrix, learning_rate=0.001, max_depth=10, min_child_weight=10, n_estimators=100, n_jobs=1, subsample=0.7500000000000001, verbosity=0), bootstrap=True, criterion=entropy, max_features=0.55, min_samples_leaf=10, min_sam... | 5a7c2b709976f8e51932737eccbcf82563421c3e | 3,617,373 |
from typing import List
def get_files_names_from_dir(directory: str, ext: str) -> List[str]:
"""Return list of file's names with extension `ext` from `directory`."""
files_names = [
file_name
for file_name in listdir(directory) if file_name.endswith(ext)
]
files_names.sort()
return... | 3bbc66146e67596532593214ed8c12592e1d0101 | 3,617,374 |
def check_bin(number, index):
"""
用于某些二进制标志位的场景
返回一个 int 类型变量的某一二进制位的值,index 从 1 开始,即
>>> check_bin(2, 1)
0
>>> check_bin(2, 2)
1
"""
try:
return int(bin(number)[2:][-index])
except IndexError:
return 0 | d5c54f3121f56c028fb20e6bfcd51395cd58aa05 | 3,617,375 |
def parse_exclusion_file(exclusion_file, exclusion_column):
"""
Reads in the specified column of the specified file into a set.
"""
exclusion_list = set()
with open(exclusion_file) as infile:
for line in infile:
to_exclude = line.split('\t')[exclusion_column]
exclus... | 3ae8430a96ed1883691cd63b86cd26d24c6f7652 | 3,617,377 |
def unstack(*args, **kwargs):
""" See https://www.tensorflow.org/api_docs/python/tf/unstack .
"""
return tensorflow.unstack(*args, **kwargs) | dedb75c147cefb792ea8d3242bb6f45c606952ab | 3,617,378 |
from typing import Callable
from typing import Sequence
from typing import Hashable
def map_operations_and_unroll(
circuit: CIRCUIT_TYPE,
map_func: Callable[[ops.Operation, int], ops.OP_TREE],
*,
deep: bool = False,
raise_if_add_qubits=True,
tags_to_ignore: Sequence[Hashable] = (),
) -> CIRCUI... | b7c6c67e8b74c4e6e1feadb305a7d830018c189f | 3,617,379 |
def min_sum_space_improved(arr):
"""
A method that calculates the minimum difference of the sums of 2 arrays consisting of all the elements from the input array.
Wrong problem description (as it talks about sets): https://practice.geeksforgeeks.org/problems/minimum-sum-partition/0
Correct problem descri... | b8eb4f22e44d2d5104b2f4436908aa85ee07ac2d | 3,617,380 |
def full_extraction(url):
"""
Runs a complete end-to-end extraction using all other functions.
:param url: The url to extract the HTML from
:return: An object that contain the HTML from the article
"""
full_html = get_html(url)
pattern_extraction = pattern_article_extraction(url)
retur... | b2133613e30c1f416adbf9d686fbedca7ad05132 | 3,617,381 |
def auth_enabled(controller):
"""Decorator for if an auth plugin is enabled"""
@wraps(controller)
def wrapper(request, *args, **kwargs):
if not mgg.app.auth:
messages.add_message(
request,
messages.WARNING,
_('Sorry, authentication is disab... | 4e781c509414e67e9571a0860b8f9962488429a5 | 3,617,382 |
from typing import Dict
def encode_token_tx(token_tx: Dict) -> bytes:
"""
Creates bytes representation of token transaction data.
args:
token_tx: Dictionary containing the token transaction data.
returns:
Bytes to be saved as token value in DB.
"""
token_tx_str = ''
token... | 4100d4dacdeea4a588906151a02f9adef874aaec | 3,617,383 |
def from_base32(number):
"""Convert a BASE32 representation of an AIC to a BASE10 one."""
number = compact(number)
if not all(x in _base32_alphabet for x in number):
raise InvalidFormat()
s = sum(_base32_alphabet.index(n) * 32 ** i
for i, n in enumerate(reversed(number)))
return ... | 54a493544214edae5414f49c2e3645cfda287768 | 3,617,384 |
def distance(strand_a, strand_b):
"""
Compare two strings and count the differences.
:param strand_a string - String representing a strand of DNA.
:param strand_b string - String representing a different strand of DNA.
:return int - number of differences between 2 strands.
"""
if len(stran... | 012e0b1640e738b17dc6a4fb4a01c1f53e0e7639 | 3,617,385 |
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):
"""
Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
... | 999bb38d67412abdf84078b8026088f5bebae7a5 | 3,617,387 |
import traceback
def set_artist(track_title, track_genre, track_location, track_artist,language):
"""
Function to set only artist details
Returns boolean True if set else False
gets invoked in the get song function
"""
try:
if(Check_artist(track_artist)):
pass
else:
collection = db.collection(u'artis... | 04d5a3940e1f227b4e700788603aca91417e359b | 3,617,389 |
def get_latest_status_from_database(session: Session) -> Status:
"""Get latest status from database"""
latest_status = get_latest_status(session)
# convert to PyDantic object
latest_status = Status.from_orm(latest_status)
return latest_status | 54c88126c3ebb94a68c95d7b82e55a1137b50e21 | 3,617,390 |
def values_to_rgb(ranges, values):
""" Converts a three dimensional tuple to a RGB map
@param ranges The mininum and maximum of each dimension
@param values The value to transform
"""
r_color = (float(values[0]) - float(ranges[0][0])) / float(ranges[0][1])
g_color = (float(values[1]) - float(ran... | 2dabe98b78e873e1aaff91577461e0991402ec64 | 3,617,391 |
def requires_auth(f):
""" Decoretorn to check user auth """
@wraps(f)
def decorated(*args, **kwargs):
""" Check user auth """
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
raise Unauthorized('Could not verify your access level f... | 49bb9a335d413cd3e476e580e99e517d56a9ce23 | 3,617,392 |
def algorithm_m_clean(n):
"""
Knuth's Algorithm M for permutation generation,
cleaned up to remove duplicate rotations.
This generates the rotations:
constructs a map of each sequence
to its captain.
"""
sequence_to_captain = {}
captains = set()
for perm in algorithm_m(n):
... | b2d6228a5872c0cd15a9d3986c0f507aac982306 | 3,617,393 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.