content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import functools
def _has_arg(fn, arg_name):
"""Returns True if `arg_name` might be a valid parameter for `fn`.
Specifically, this means that `fn` either has a parameter named
`arg_name`, or has a `**kwargs` parameter.
Args:
fn: The function to check.
arg_name: The name fo the parameter.
Returns:... | 6a26cd24818f753642e53d641a93dfe816f4022a | 3,621,964 |
def logout(request):
"""
Allows a non-SAML 2.0 URL to log out the user and
returns a standard logged-out page. (SalesForce and others use this method,
though it's technically not SAML 2.0).
"""
auth.logout(request)
tv = {}
return render('saml2idp/logged_out.html', tv) | ae27ed4caaeacb31bb003b683a485eff8963b7dd | 3,621,965 |
def auto_norm(data_set):
"""
Get the minimum values of each column
and place in min_vals. max_vals, too.
data_set.min(0) allows you to take the minimums
from the columns, not the rows.
Then calculate the range of possible
values seen in our data.
To get the normalized values,
you sub... | 7d3018f8053ebddb19d85ea1712bcec168fa1853 | 3,621,966 |
from typing import Callable
from typing import Any
def middleware(type: MiddlewareType) -> Callable[[CoroFunc[Any]], Middleware]:
"""
A decorator that returns a :class:`~subway.objects.Middleware` object.
Parameters
----------
type: :class:`~subway.objects.MiddlewareType`
The type of midd... | d004a1260c6ffeb1861e6b43b38ea08eb199cd3a | 3,621,967 |
import copy
def add_sorting_info_to_spike_info(original_spike_info, sorted_spike_info, tsne_filename=None, save_to_file=None):
"""
Adds the information in a spike_info dataframe that results after manual sorting (through a t-sne for example)
into the main spike_info. The original_spike_info is the large s... | 995bf4a4c1595c2b0b3b1c9ee2d882f0f872775f | 3,621,968 |
def XXX(self, s):
"""
:type s: str
:rtype: int
"""
left, right = 0, 0
while right < len(s):
right += 1
if len(set(s[left:right])) != right-left:
left += 1
return right-left | 26e08dc0b82985fef73b0b13669c74f3d9f9acef | 3,621,969 |
def people():
"""
View root page function that returns the index page and its data
"""
posts = Post.query.filter_by(category="People").all()
form = SubscriberForm()
if form.validate_on_submit():
email = form.email.data
new_subscriber=Subscriber(email=email)
new_subscribe... | 5891270d777f9a7e26f75535fd3fa59ae0884b53 | 3,621,970 |
def networkDrawSVG(request, networkKey):
"""
A view called when a user wants to draw the potential energy surface for
a given Network in SVG format.
"""
networkModel = get_object_or_404(Network, pk=networkKey)
networkModel.load()
# Run CanTherm! This may take some time...
networ... | 71976acd92f982fb01df4604d9ac812843832357 | 3,621,971 |
def transform_dict_to_count_df(item_dict):
"""Given a dictionary, where each element of the dictionary is a list,
return the data frame with columns all the elements that occur in any of
the lists (union of the lists) and rows the keys of the dictionary. Each
entry is the number of times that the item o... | 90a98d067d131e34239d147edd7dc57667bae030 | 3,621,972 |
import re
def parse_cmscan_tblout(filename):
"""
SNORA74 RF00090 URS00007E391B_9796 - cm 103 201 1 99 + 5' 2 0.49 0.0 97.9 3.2e-26 ! Small nucleolar RNA SNORA74
"""
data = defaultdict(list)
with open(filename, 'r') as f:
for line in ... | 11a07252136604dad87b52cd38981484032572ca | 3,621,973 |
def himmelblauConstraintOne(solution):
"""First restriction
Args:
solution (Solution): Candidate solution
Returns:
bool: True if it meets the constraint, False otherwise
"""
return (26 - (solution[0] - 5) ** 2 - solution[1] ** 2) >= 0 | f5878d2573559b78fee3b434d537a380abb5e2c8 | 3,621,974 |
from unittest.mock import patch
def patch_try_disk(return_value):
"""
Mocks the InsightsUploadConf.try_disk method so it returns the given parsed file contents.
"""
def decorator(old_function):
patcher = patch("insights.client.collection_rules.InsightsUploadConf.try_disk", return_value=return_... | 95ed09006e0a17bc58e5f320f1ae5dfb203300dd | 3,621,975 |
import re
def lyric_wikia_capitalize(string, noupper = True):
"""
lyrics.wikia.com page name rules:
- Uppercase All Words
- No all-uppercase WORDS allowed in song titles (but in artist names)
- Keep StrANgeLy cased words
See http://lyrics.wikia.com/wiki/LyricWiki:Page_... | b3d5aefff0715a7ff1e7298b9bdb492bd461c217 | 3,621,976 |
def create_ip_list(addr0, n_addrs):
"""Creates list of IP multicast subscription addresses.
Args:
addr0 (str): first IP address in the list.
n_addrs (int): number of consecutive IP addresses for subscription.
Returns:
addr_list (list): list of IP addresses for subscription.
"""... | e29b5c4b9f9ec0dc46916977e4a54bb77a9e74a6 | 3,621,977 |
def _classify_samples(indexfile, ssparser):
"""Given an ssparser object, go through all samples and decide sample types."""
sample_table = dict()
index_dict_tenX = parse_10X_indexes(indexfile['tenX'])
index_dict_smartseq = parse_smartseq_indexes(indexfile['smartseq'])
for sample in ssparser.data:
... | 954c3f5ceff6da6eddaa603ae310b83f849e3191 | 3,621,978 |
def get_common_incident_details(static_attributes: dict, editable_attributes: dict, args) -> dict:
"""
Parses the needed incident details into context paths
:param static_attributes: The static attributes of the incident
:param editable_attributes: The editable attributes of the incident
:param args... | 6d88792e2139cd3c57a50d3d148fa01cad44c152 | 3,621,980 |
def win_prob_to_odds(prob, odds_style="a"):
"""
:param prob: Float. Implied winning % of a given wager
:param odds_style: Integer (American), Float(Decimal), String or Fraction Class (Fractional)
:return: The stated odds of a bet in a given style
"""
try:
if odds_style.lower() == "americ... | 49b13a28526c2d18df0d022d0ee51a71ab4b3447 | 3,621,981 |
import random
def cxBlend(var1, var2, alpha=0.5):
"""Executes a blend crossover that modify in-place the input individuals.
The blend crossover expects :term:`sequence` individuals of floating point
numbers.
:param var1: The first variable participating in the crossover.
:param var2: The second v... | 11b7339f388ec228f855d1af87d86034cab7166a | 3,621,983 |
import decimal
def decimal_to_num(obj):
"""
Helper function to convert all decimal valued inputs to the real representation of the value (int or float.)
This function is recursive.
Parameters:
obj (obj): An object to parse for decimals.
Returns:
obj: The passed in object with any transfo... | 395bb2c1c03d2c41e552b405df4bceb4172fe7aa | 3,621,985 |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | d6d16583bdf72b2e26e18b427857aacce88db363 | 3,621,987 |
def check_if_sums_are_close(uvd1, uvd2, redgrps, array='data'):
"""
Check whether the sum of the data, flags, or nsamples in two UVData objects
is the same within each redgrp.
"""
close = []
for i, grp in enumerate(redgrps):
sum_uvd1 = np.sum(get_data_redgrp(uvd1, grp, array... | ae674bf28fb50d5d2c2b5ba16f0d7516ddd56c20 | 3,621,988 |
from datetime import datetime
def stats(update, context):
""" Show help info about all secret admins commands """
user = User.get_user(update, context)
if not user.is_admin:
return
text = f"""
*Users*: {User.objects.count()}
*24h active*: {User.objects.filter(modified__gte=now() - datetime.ti... | 18ca3b406d8750ab7e15894407b601118cacefdc | 3,621,989 |
def load_blacklist():
"""Return blacklist to be used."""
if blacklistfile:
return get_filebased_blacklist()
return get_threecommas_blacklist() | 19b2ef2d710c7065822f396c2ad93698b4bc0d74 | 3,621,990 |
def is_valid_mx(value: str):
"""Check if mx record is valid."""
for line in value.splitlines():
try:
priority, hostname = line.split(" ")
except ValueError:
raise ValidationError(
"Each line must be in the following format: [priority] [hostname]"
... | 5db5a24e6a4b4d6140d9953f059a83f6bae4baf0 | 3,621,991 |
def count_accuracy_raw(pred_corpus, target_corpus):
"""
Test accuracy, Raw accuracy
"""
count_accu = 0
total = 0
pred_sents = pred_corpus.split('.')
target_sents = target_corpus.split('.')
for pred_sent, target_sent in zip(pred_sents, target_sents):
pred_list = pred_sent.split(' ... | 6935fd0bba49d0529be382c3c78f937618f28647 | 3,621,993 |
def f(random_state, dfnum, dfden, size=None, chunk_size=None, gpu=None, dtype=None):
"""
Draw samples from an F distribution.
Samples are drawn from an F distribution with specified parameters,
`dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
freedom in denominator), where both par... | d2d4a9113a7b26c1fb79b0a54fea8a4515350c44 | 3,621,995 |
def get_callers_info(callers_file, callers_package, callers, res_dir):
"""
Tries to create a map between the top callers and its associated file, using a best effort approach, by parsing the
package declaration, in case this is need. If a file matches to a caller in the dataset, it retrieves any required
... | 37fa8fcc47ba455e6bc47243f8334f2ab26e3962 | 3,621,996 |
from typing import Union
from typing import Dict
from typing import Any
import json
def _get_connection_options(data: Union[str, Dict[str, Any]]) -> Dict[str, ConnectionOptions]:
"""Create per-platform ConnectionOptions objects from configuration dict
Args:
data (str|dict): Connection options in dict... | 08420d1785a596d8f4d7cf512e54203009901a55 | 3,621,997 |
def plyify(r, t, ply_thickness, reverse=False):
"""Fill thickness distribution using plies."""
active = []
done = []
np = len(r)
for i in range(np):
while t[i] > len(active) * ply_thickness:
active.append([r[i], -1])
while t[i] <= (len(active) - 1) * ply_thickness:
... | f8fbfa256fd1cc7b83007a631f244162d8534b4e | 3,621,998 |
import skimage.transform
def subdivide_array(shape: tuple[int, ...], count: int) -> np.ndarray:
"""
Create indices for subdivison of an array in a number of blocks.
If 'count' is divisible by the product of 'shape', the amount of cells in each block will be equal.
If 'count' is not divisible, the amo... | 9eb314837f06d67f805894188a96ffb630aad3db | 3,622,000 |
def __hidden(element: Element) -> bool:
"""Element is hidden"""
return element.hidden | ebc9ff1c3e08a84eab9deb8bcad76303b76f7db1 | 3,622,001 |
from typing import List
def average(runs: List[TrecRun], depth: int = None, k: int = None):
"""Perform fusion by averaging on a list of ``TrecRun`` objects.
Parameters
----------
runs : List[TrecRun]
List of ``TrecRun`` objects.
depth : int
Maximum number of results from each inpu... | 69b3f7d9fe092b0ec50d2a840a889f040fb4a9a1 | 3,622,002 |
def rpca(table: biom.Table,
rank: int=3,
min_sample_count: int=500,
min_feature_count: int=10,
iterations: int=5) -> (
skbio.OrdinationResults,
skbio.DistanceMatrix):
""" Runs RPCA with an rclr preprocessing step"""
# filter sample to min depth
def samp... | 91a4d4c1f7a023bf4238c84040d10fbdc3bf1dd5 | 3,622,003 |
def create_latency_update_runner(
*,
start_after: float = 10,
interval: float = 60 * 5,
target: str = f"http://127.0.0.1:{Config['port']}",
method: str = "GET",
header: dict[str, str] = None,
) -> Thread:
"""
Creates a thread which automatically updates the latency displayed on statuspag... | 1a88ee8470ecaa8e8094b7201c6858bb552aa520 | 3,622,005 |
def comp_periodicity(self):
"""Compute the periodicity factor of the lamination
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
per_a : int
Number of spatial periodicities of the lamination
is_antiper_a : bool
True if an spatial ant... | 4bc2111ad3f97631bbb12c7c28bfdcf53fba57ac | 3,622,007 |
def _attack(params):
"""
Test the target URL with requests.
Intended for use with multiprocessing.
"""
print 'Bee %i is joining the swarm.' % params['i']
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if params['gnuplot_... | 20464af4036ad13d0f56e0276533bd1c79b99132 | 3,622,008 |
def extract_entity_ids(hass, service):
"""
Helper method to extract a list of entity ids from a service call.
Will convert group entity ids to the entity ids it represents.
"""
entity_ids = []
if service.data and ATTR_ENTITY_ID in service.data:
group = get_component('group')
# ... | f259a29c2c5d4fd88101c3dd66ca97e9d0115bb3 | 3,622,009 |
def submit_batch(batches):
"""Submit transaction batches using default client URL"""
batch_list = create_batch_list(batches)
client = RestClient(sawtooth_rest_host())
return client.send_batches(batch_list) | 77bb9708ee7e5cb50a1206a9cc13d3cd81fddb1d | 3,622,010 |
def tp53():
"""Create a TP53 fixture."""
params = {
'concept_id': 'ensembl:ENSG00000141510',
'symbol': 'TP53',
'label': 'tumor protein p53',
'previous_symbols': [],
'aliases': [],
'xrefs': ['hgnc:11998'],
'symbol_status': None,
'location_annotation... | 94966b192984052f6c446428b60492530528cc21 | 3,622,011 |
from sopel.tests import pytest_plugin
def get_example_test(*args, **kwargs):
"""Get a function that calls ``tested_func`` with fake wrapper and trigger.
.. deprecated:: 7.1
This is now part of the Sopel pytest plugin at
:mod:`sopel.tests.pytest_plugin`.
"""
return pytest_plugin.get_... | d07d5a6ebbeba45a56f41f0b35cc46b35fdb5987 | 3,622,012 |
def _epoch_ctrl(eva=None, stage="game"):
"""
:param eva:
:param stage: must be one of "game", "confirm", "retrain"
:return:
"""
if stage == "game":
cur_epoch = NAS_CONFIG['eva']['search_epoch']
elif stage == "confirm":
cur_epoch = NAS_CONFIG['eva']['confirm_epoch']
elif ... | 67dbde8ada80b20daad66b008faa860d7a58b929 | 3,622,013 |
from typing import Sequence
from typing import Any
def list_namespaced_applications(
kube_client: KubeClient, namespace: str, application_types: Sequence[Any]
) -> Sequence[Application]:
"""
List all applications in the namespace of the types from application_types.
Only applications with complete set... | a6ea1096bf5860b076d6bd0c5bbd49e473addbc9 | 3,622,015 |
def _train_step(model: _FlaxPenguinModel, optimizer: flax.optim.OptimizerDef,
inputs: _InputBatch, labels: _LabelBatch):
"""Train for a single step, given a batch of inputs and labels."""
def loss_fn(params):
logits = model.apply({'params': params}, inputs)
loss = _categorical_cross_entropy... | 10644ee8f4635e26ec060e6a082d1be58c6e0070 | 3,622,016 |
from distributed import Executor
def dsubmit(*a, args=(), kwargs=None, rtn="", **kw):
"""Returns a distributed submission context manager, DSubmitter(),
with a new executor instance.
Parameters
----------
args : Sequence of str, optional
A tuple of argument names for DSubmitter.
kwarg... | 1a767558ef71e8a8ba9406d5b04142b4c7932c97 | 3,622,017 |
def isNumber(n):
"""retorna true si 'n' es un numero"""
return all(n[i] in "0123456789" for i in range(len(n))) | 40541c759357fe2706fb453947e55dabab513040 | 3,622,019 |
def import_data():
"""Import data
Parameters
----------
none
Returns
-------
df_listings: DataFrame
df_prices: DataFrame
df: DataFrame
"""
# Import listings data
url_listings = "http://data.insideairbnb.com/italy/emilia-romagna/bologna/2021-12-17/data/listings.... | 3572d6ff5773f4ef14b7af7ee05f5e4c712789d3 | 3,622,020 |
def cmap_to_mayavi(colormap: Colormap) -> np.ndarray:
"""
Convert a matplotlib colormap to mayavi format.
Args:
colormap: A matplotlib colormap object.
Returns:
The equivalent mayavi colormap, as a (255, 4) numpy array.
"""
return (colormap(np.linspace(0, 1, 255)) * 255).astype... | 4e75738d8e5c0d1f8f4c3e36ff5ec93218774c97 | 3,622,021 |
def show_task(project_id):
"""shows the tasks of a project that are stored in the database, given the project_id"""
return render_template("project_tasks.html", project=Project.query.filter_by(project_id=project_id).first(),
tasks=Task.query.filter_by(project_id=project_id).all()) | 41eee9ca596b0a69b3bacf1eaace315cd6a9498c | 3,622,022 |
def get_fig_pv_combined(pv: PV, example_index: int):
"""
Create a combined plot
1. Plot the pv intensity in time
2. Plot the pv intensity with coords and animate in time
"""
traces_pv_intensity_in_time = get_trace_all_pv_systems(
pv=pv, example_index=example_index, center_system=False
... | 96ddbdef52ac5f31b45fde3b7a4eb1f57770dfec | 3,622,023 |
def data_frame_empty_typed(column_types: dict):
"""Creates and empty DataFrame with dtypes for each column given
by the dictionary.
Arguments:
column_types (dict): A key, dtype pairs
Returns:
DataFrame: An empty dataframe with the typed columns
"""
df = pd.DataFrame()
for n... | 879aa4d87719efe59234d7f93651bf717d1ef43d | 3,622,024 |
def are_periodic_neighbors(world_size, a, b):
"""
Given the world size and two ranks, return wether two ranks are periodic
neighbours (i.e. they are in opposite borders of the grid).
"""
nrows, ncols = get_grid_size(world_size)
pos = get_node_pos(world_size, False)
if (ncols > 2) and (pos[a... | 65065bb7edbaad78266ff94efdd638dcf65e297d | 3,622,025 |
def file_content_to_list(file):
"""
Append each line of the file to a theèlist
:param file: The file to transform into a theèlist
:return: The the list
"""
lst = []
with open(file) as file_alias:
for line in file_alias:
lst.append(line)
return lst | cee015f6e7121fc513c8944c61cfd225ee0dcf12 | 3,622,026 |
def ceph_health_check_base(namespace=None):
"""
Exec `ceph health` cmd on tools pod to determine health of cluster.
Args:
namespace (str): Namespace of OCS
(default: config.ENV_DATA['cluster_namespace'])
Raises:
CephHealthException: If the ceph health returned is not HEALTH... | 72ace3629d2eff03c91b030dd4f0ebcb86369f24 | 3,622,027 |
from typing import Sequence
def _hash_layer(layer: Sequence[Hash32]) -> Sequence[Hash32]:
"""Calculate the layer on top of another one."""
return tuple(_calc_parent_hash(left, right) for left, right in partition(2, layer)) | a417addc58a0585c1c5e5757d21983540d4acd10 | 3,622,028 |
def get_sample_names(exprs_fname, start, end):
"""Loads PANDA input expression matrix to extract sample names from TSV.
Args:
exprs_fname (str): PANDA input expression matrix TSV
start (int): start index (1-based inclusive)
end (end): end index (1-based inclusive)
Returns:
... | 3fe86bbdc928be8f490c070c7a28186f2fcf0b13 | 3,622,030 |
def get_users(uid=1, dl=0):
"""Method to get county coordinators emails."""
try:
emails = []
sql = QUERY[uid]
df = run_query(sql)
data = df.values.tolist()
for dt in data:
val = dt[0]
if dl > 0:
val = {dt[0]: dt[1]}
emai... | 1c3440b7f8d45ef0584b5db6d422878fe5fd8bad | 3,622,031 |
def make_function(match):
"""Returns a Function JSON Object"""
return {
'type': 'f', #f for function
'name': match.group('name'),
'return_type': match.group('return_type'),
'parameters': get_parameters(match.group('parameters'))
} | a0fd0d3aaca707852cfc08cdb663317ae2e7b659 | 3,622,032 |
import random
def Decimal_to_Binary(x : str) -> str:
"""
It Converts the Given Decimal Number into Binary Number System of Base `2` and takes input in `str` form
Args:
x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User.
Returns (str): The ... | 8555e0bb983ab30dbfd737f9babfaa67193db620 | 3,622,033 |
import torch
def sample_tv_signal(
n,
j_min=10,
j_max=20,
min_dist=5,
bound=5,
min_height=0.2,
n_seed=None,
t_seed=None,
):
""" Creates a random piecewise constant signal.
Creates a piecewise constant signal of shape (n,) with a random number of
"jumps" (discontinuities).
... | 7a080ba600c3cb706d66f9567cd633c4ee3de77e | 3,622,036 |
def float32_variable_storage_getter(getter, name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True, *args, **kwargs):
"""Custom variable getter that forces trainable variables to be stored in
float32 precision a... | db004fa14d6e7f7b898c2ca29f62138c59976dd2 | 3,622,037 |
def _squad_em(pred_data, ref_data):
"""EM score for reading comprehension task"""
em_score = eval_exact_match_score(pred_data, ref_data)
return em_score | ce5b77bf88692a2e3aebd01c6e35e4924f372a6e | 3,622,038 |
def add_slash(text: str):
"""returns the same text with slash at the end"""
return text + '/' | a87c204dfc163f5ee814fbda92ad7a8368346893 | 3,622,039 |
from typing import Tuple
def parse_response(text: str) -> Tuple[bool, str]:
"""
Parses a CommCare HQ Submission API response.
Returns (True, success_message) on success, or (False,
failure_message) on failure.
>>> text = '''
... <OpenRosaResponse xmlns="http://openrosa.org/http/response">
... | afdfc6479323d38c13f45a25b40246ea286633d0 | 3,622,040 |
def launch(context, service_id, subscription, every=EVERY):
""" Initialize the module. """
return MeasRepUe(context=context, service_id=service_id, every=every,
subscription=subscription) | f5954d6fa62d640898ca95ad7df3e85b41a2bb8d | 3,622,041 |
import re
def __detect_str_type(data) -> str:
"""
:column_type str
:rtype str
"""
r = re.search("[^=]+=[^&]*&*", data) # application/x-www-form-urlencoded pattern
if r:
return "application/x-www-form-urlencoded"
else:
return "plain/text" | 6dda59aa570070538b54738b83fc69ba129637f0 | 3,622,042 |
def iterable(x):
"""Check if the input is iterable, stolen from numpy.iterable()"""
try:
iter(x)
return True
except:
return False | edd9f4cc369c0f53470d7323aacfccbd32b0e4d7 | 3,622,043 |
def conv2d_input_grad_wrap(input_size, weight, grad_output, stride, padding,
dilation, groups):
"""Wrap of conv2d_input_grad for pytorch."""
input_size = tuple(i.item() for i in input_size)
stride = tuple(_x.item() for _x in stride)
padding = tuple(_x.item() for _x in padding)... | 5ce20be791e6a7be52be377a85636c087013b05e | 3,622,044 |
def sort_key(entry):
"""Get the value for a key"""
return entry[ds] | 932003d76e959adba187df7f7c6b7f0517d3e779 | 3,622,045 |
def estimation_error_rate(y_true, y_pred):
"""
Compute estimation error rate score
Estimation error rate represents the mean absolute error computed between true
and predicted labels, expressed as a percentage, i.e. mae / range(y_true). It
is defined as follows:
eer = mae / range(y_true)
m... | d5a2927f785b8a90e1d91daab6a540d622a7e3a3 | 3,622,046 |
def ldns_resolver_new_frm_fp(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_new_frm_fp(*args) | 03e47cb19506e9ec6a0121db2c737ba7c6a66204 | 3,622,047 |
from typing import Tuple
from typing import List
import asyncio
from pathlib import Path
async def _populate_downloads(executor, dataset: Dataset,
destination: str, prefix: str, recursive: bool) -> Tuple[List[ObjectState], int]:
"""function to concurrently check if the list of files ... | 68189ba19b051316c7bcb50c8b669f3573a1f073 | 3,622,048 |
def requires_roles(roles):
"""
Assert the user has one of the required roles.
:param list roles: the list of role names to verify
:raises freshmaker.errors.Forbidden: if the user is not in the role
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
if any(us... | a7a5471bfc038b79d9930ac6c1f07f3d318ac59a | 3,622,049 |
import random
def cull_gammas(x, y, mRNA_to_miRNA: np.ndarray) -> np.ndarray:
"""
Removes gammas (sets them to 0) in such a way that the network remains connected. Currently very hacky: uses
DFS to ensure connectivity. Would work better using a min-cut algorithm.
"""
legal = False
while not le... | 69de118949537dc15f490fdd4174b283628ff3a5 | 3,622,050 |
def primality_test(n: PositiveInt) -> bool:
"""Determine whether a number is a prime."""
# Optimization 1: Test from 2 to sqrt(n) only, since a factor will appear twice when we test from 2 to n.
# Optimization 2: Do not test even numbers except 2, since all even numbers is divisible by 2.
# Optimizati... | f49b8caffc7d462111337a7c1251c965467e192e | 3,622,051 |
def diffusion_coeff(t, sigma):
"""Compute the diffusion coefficient of our SDE.
Args:
t: A vector of time steps.
sigma: The $\sigma$ in our SDE.
Returns:
The vector of diffusion coefficients.
"""
return sigma**t | e0b1e1c76f7773a85562adb327c18863c715917a | 3,622,053 |
def get_step_chart(simulation_objects):
"""Get the step chart of the container levels."""
fig = plt.figure(figsize=(14, 7))
for obj in simulation_objects:
df = get_log_dataframe(obj)
container_list = obj.container.container_list
for container in container_list:
if hasatt... | 5acbf66c67214a97b4c40bcb9ebe692df86afd40 | 3,622,054 |
def byte_xor(b: bytes, i: int) -> bytes:
"""
Calculate 'b XOR i'
"""
return int(bytes_to_int(b) ^ i).to_bytes(len(b), 'big') | 3341137ca93bb2c3262579a446a3874cc04c87cc | 3,622,055 |
def get_file_name(f_size):
"""
Returns file name whose filesize correstponds with the files size passed in as parameter.
"""
for x,(z,y) in movie_dict.items():
if z == f_size :
return x | 589255cb011113eebf52312e9c2bb1d4d3baf9a2 | 3,622,056 |
from typing import OrderedDict
def get_form_errors(form):
"""
Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance
"""
return {
'non_field': form.non_field_errors(),
'field_specific': Or... | 056597492d24dc406c9d952f5cb56c14d0a75fff | 3,622,057 |
def is_valid_url(url: str) -> bool:
"""Evaluate whether or not a URL is acceptible for retrieval."""
return current_session().is_valid_url(url) | bcb8517ce5ed613bebef5753e3dad13fcf2f7447 | 3,622,059 |
def plot_poly(x,y,degree, *args):
""" Plot the data with given degree of polynomial.
Example:
plot_poly(x,y,3)
plot_poly(x,y,3,'x','y','title')
Returns: p
Usage:
x_value = 100
p(x_value) gives the polynomial fit of x_value
"""
plt.figure(figsize=(12,8))
pl... | ba39412dd401e7321adceca665baf8f23a2833ed | 3,622,060 |
def comment_exists_in_blogpost(func):
"""Checks to make sure the comment exists or renders a 404"""
def wrapper(self, blog_id, comment_id, *args, **kwargs):
blog_post = BlogPost.get_by_id(int(blog_id), parent=BLOG_KEY)
int_comment_id = int(comment_id)
comment = Comment.get_by_id(int_comm... | 5c5c9e3c003d0ed12c11b4b65ef0fdd1fcba468a | 3,622,063 |
import torch
def log_sum_exp(tensor, dim=-1):
""" Safe log-sum-exp operation """
return torch.logsumexp(tensor, dim) | 5b6154be4c12576941f7e8d97a26296149982e1b | 3,622,064 |
from typing import List
from typing import Dict
def get_vrf_group(files_list: List[str]) -> Dict[str, List[str]]:
"""
Group files by VRF name.
"""
groups = {}
for filename_path in files_list:
filename_path = filename_path.replace("\\", "/")
# print(filename_path)
if "show" i... | 348f1c10f4bd054ca2f45f36b5420a971b52e4cf | 3,622,065 |
def get_legislator_political_positions_by_slug(slug):
"""
Get just this legislator's political positions
https://github.com/INN/maine-legislature/issues/82
"""
copy = get_copy()
political_positions = {}
leg_id = get_legislator_id_by_slug(slug)
for row in copy['position_political']:
... | e6ea3e7efa63bf5424f0eb4ec293f10fb7a96b4d | 3,622,066 |
def config_bgp_neighbor_properties(dut, local_asn, neighbor_ip, family=None, mode=None, **kwargs):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param family:
:param mode:
:param kwargs:
:return:
"""
st.log("Configuring the BGP neighbor properties ..")
properties = ... | 8d36549020ec14533bb28424076c00b7859e5795 | 3,622,067 |
def scr_total(
bscr,
scr_op
):
""" This function simply adds the SCR_Op to the BSCR """
return bscr + scr_op | 7d1711f75abae59b79cf62f6e64daeb7e4c556eb | 3,622,068 |
def _eval_bernstein_dd(x, fvals):
"""Evaluate d-dimensional bernstein polynomial given grid of valuesv
experimental
Parameters
----------
x : array_like
Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
Grid values of coefficients for Bernstein polynomial ba... | c28efdbe8772f6acad83f45de7d33447d7437cee | 3,622,069 |
import re
import six
def load_tff_dat(fname, processor=None):
"""Read a tff.dat or dff.dat files generated by tff command
Parameters
----------
fname : file or str
File, or filename
processor: callable or None
A final output processor, by default a tuple of tuples is returned
... | 55f9ba3915c2d31cb83b8ea26de996f8f29e5e43 | 3,622,070 |
from typing import List
def is_luhn(string: str) -> bool:
"""
Perform Luhn validation on input string
Algorithm:
* Double every other digit starting from 2nd last digit.
* Subtract 9 if number is greater than 9.
* Sum the numbers
*
>>> test_cases = [79927398710, 79927398711, 7992739871... | 92253489a18efc902198d5eb3fb93a06a74a3246 | 3,622,071 |
from typing import Optional
def latest_date_for_day(
start_date: datetime_.date, end_date: datetime_.date, day_of_month: int
) -> Optional[datetime_.date]:
"""
Given an integer day of a month, return the latest date with that day of the month,
bounded by the supplied start_date and end_date. If no suc... | 38a6dee698fd41083acadec6ac7cefc1a8217368 | 3,622,073 |
import sqlite3
def handle_artist(command):
"""
Process the artist command
"""
conn = sqlite3.connect('myjazzalbums.sqlite')
cur = conn.cursor()
if command [-1] == "?":
artist_name = command[6:-1].strip().title()
else:
artist_name = command[6:].strip().title()
if ar... | 4395b4d3a25f3ea5e10accd938a51df342913e17 | 3,622,074 |
def generate_lda_distance(df, model, dictionary):
"""
计算 LDA 主题模型距离
"""
def compute_topic_distances(row):
q1_bow = dictionary.doc2bow(row['cleaned_question1'].split())
q2_bow = dictionary.doc2bow(row['cleaned_question2'].split())
q1_topic_vec = np.array(model.get_document_topics... | f653b557d846bad1c36b0ac85926cb05050d4793 | 3,622,075 |
def build_get_request(base, service_name, operation_name=None, params=None):
"""
Builds a get request out of a service/operation and optional params.
operation_name may be left blank if going to a custom url.
"""
urlarr = [base, service_name]
if operation_name is not None:
urlarr.append(... | e2afb6c40f08fca3a38b54ab36b996533e7f2c8e | 3,622,076 |
def dense(n_prev, n, *, activation="relu"):
"""Creates a dense, fully-connected layer.
Args:
n_prev: number of inputs from the previous layer
n: number of nodes for this layer
activation: activation function for this layer,
one of {sigmoid, tanh, relu}
"""
unit = _nn... | c29365310b2df9913d61702d515a3aa7189b1456 | 3,622,079 |
from typing import Tuple
import json
def load_poses(pose_path: str, skip_params: bool) -> Tuple[tf.Tensor, tf.Tensor, float]:
"""Loads poses from file."""
with open(pose_path) as pose_file:
pose_dict = json.load(pose_file)
poses = []
parameters = []
for pose in pose_dict['frames']:
... | 8529e181cec4cc04f6b6d4fe3517ad0ba01e1b4c | 3,622,080 |
import glob
def patternMatch(pattern, dir='./'):
"""
:pattern: A file pattern to match the desired output. Input to a glob, so use traditional unix wildcarding.
:dir: The directory to search.
:returns: list of matching files in the target directory
"""
files = []
files = glob.glob(dir+pa... | d5e9b1d531cdfa3ebca3baea2b8e273621df3357 | 3,622,081 |
def add_histogram_summary(tensor, name=None, prefix=None):
"""Adds a histogram summary for the given tensor.
Args:
tensor: A variable or op tensor.
name: The optional name for the summary.
prefix: An optional prefix for the summary names.
Returns:
A scalar `Tensor` of type `string` whose content... | 6ca0ee04fa1e35d030f38a4d969d2b992341674f | 3,622,082 |
def tasks_page():
""" Tasks and completions page: tasks.html
"""
project = project_get_or_create()
label_config = open(project.config['label_config']).read() # load editor config from XML
task_ids = project.get_tasks().keys()
completed_at = project.get_completed_at(task_ids)
num_workers= ... | 7a857c0eea1f7b5e5b931761251ff64a098d8a1e | 3,622,083 |
def trim_matrix(mat, i):
"""
Trims a matrix by deleting both a row and a column in a matrix (warning: inefficient)
:param mat: matrix
:param i: row index
:return:
"""
mat = mat.copy()
mat = mat.tocsr()
delete_row_csr(mat, i)
mat = mat.transpose()
mat = mat.tocsr()
delete... | 16806bbde767f709786a15dc06d0f84de2191d27 | 3,622,085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.