content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import networkx
def graph_from_dict(d):
""" Creates a NetworkX Graph from a dictionary
Parameters
----------
d : dict
Returns
-------
Graph: NetworkX Graph
Examples
--------
>>> g = graph_from_dict({'a':['b'], 'b':['c', 'd'], 'c':[], 'd':[], 'e':['d']})
"""
g = netw... | e0029b6018ff840bd2f314038c25f41e025600a7 | 77,844 |
def calculate_avail_vmem(mems):
"""Fallback for kernels < 3.14 where /proc/meminfo does not provide
"MemAvailable:" column (see: https://blog.famzah.net/2014/09/24/).
This code reimplements the algorithm outlined here:
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
commit/?id=3... | bc53fa2b4e8ebdeb3fb9b4fffbeb01251fcb52c5 | 77,845 |
import sympy
def symbolic_pauli_product(*args, as_tensor_product=False):
"""
Return symbolic sympy object represing product of Pauli matrices.
"""
if as_tensor_product:
tensor_product_elems = []
for arg in args:
if arg == 0:
tensor_product_elems.append(1)
... | 682594aa34d10b53ea14e5faefc99cd3880b9cb5 | 77,846 |
def parse_request_export_options(params): # pylint: disable=too-many-branches
"""
Parse export options in the request object into values returned in a
list. The list represents a boolean for whether the group name should be
removed, the group delimiter, and a boolean for whether select multiples
sh... | 5ac23815f1156e3f039ed124d361febd47de3cd7 | 77,847 |
def dectobin(dec_string):
"""Convert a decimal string to binary string"""
bin_string = bin(int(dec_string))
return bin_string[2:] | 5f02507ae5e7ab855eceb7a5908347060b46a400 | 77,848 |
def confirm_required(template_name, context_creator, key='__confirm__'):
"""
Decorator for views that need confirmation page. For example, delete
object view. Decorated view renders confirmation page defined by template
'template_name'. If request.POST contains confirmation key, defined
by 'key' par... | ef2855de996ddbe0efd9d1bb0c498ed9d772678f | 77,849 |
from typing import Any
from typing import Dict
def dict_or_raise(value: Any) -> Dict[Any, Any]:
"""Return dict or raise exception."""
return enforce_type(value, dict) | f8a481a0da3cfc57f5ce8ac43f165e343ed2469b | 77,850 |
def isValidKey(key):
"""Returns a Boolean value if the given key is a valid value to pass to
PyAutoGUI's keyboard-related functions for the current platform.
This function is here because passing an invalid value to the PyAutoGUI
keyboard functions currently is a no-op that does not raise an exception.... | efcc9475c9f79b31f65538465690706ffdba6adc | 77,851 |
def underscorize(camelcased):
"""
Takes a CamelCase string and returns a separated_with_underscores
version of that name in all lower case. If the name is already all in
lower case and/or separated with underscores, then the returned string
is identical to the original. This function is used to ta... | b0f2622c105c09502aa984e15cf1b61ac12a608b | 77,852 |
def run_query(con, sql, *args, **kwargs):
"""Runs a SQL query on the db.
Parameters
----------
con : :[obj]:`Connection`
A valid cx_Oracle Connection object.
sql : str
SQL query to run.
*args
Variable length argument list.
**kwargs
Arbitrary keyword arguments... | 24d47d61fc6970c7ea61e8cb472441be5d678645 | 77,854 |
def read_growth_highz_benchmark_file():
"""
Read the file containing growth factor benchmarks for the high redshifts.
"""
# Load data from file
dat = np.genfromtxt("benchmarks/data/growth_hiz_model1-3.txt").T
assert(dat.shape == (4, 7))
# Split into redshift column and growth(z) columns
... | 04c13b78c103f6747844f330a7176ff2eb1bf394 | 77,855 |
def cdf(value, loc, scale, skewness):
"""Compute cumulative distribution function of Two-Piece Normal distribution.
Note that scale and skewness can be negative.
Args:
value: Floating-point tensor; where to compute the cdf.
loc: Floating-point tensor; the location(s) of the distribution(s).
scale: F... | 86dc0b0604698ebfb795e48af46ef17f569c60b7 | 77,856 |
def _try_pack(size, rects, result):
"""Try to pack rectangles in the given bounds.
size: (width, height)
rects: array of (width, height, index)
result: array to store result
The (x, y) for each rect is stored in the rect's index in the
result array. Returns True if successful, False otherwise... | 6230a69af9f661de0665620aeae119efdd519808 | 77,857 |
def dictfetchall(cursor):
"""
Return all rows from a cursor as a dict.
See: https://docs.djangoproject.com/en/2.0/topics/db/sql/#executing-custom-sql-directly
"""
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
] | 21daf878a16b5ca2af3b7a5a1d0f46f8f4f41730 | 77,858 |
import itertools
def best_wild_hand_peter(hand):
"""Try all values for jokers in all 5-card """
hands = set(best_hand(h) for h in itertools.product(*map(replacements, hand)))
return max(hands, key=hand_rank) | 1b15dfb076f2f5cab08a76d7f60aaad5b8742d08 | 77,860 |
from functools import reduce
import operator
def valid_pcd(pcd, client_date):
"""Determine if the profile creation date column is valid given the date
reported by the client."""
pcd_format = F.date_format(pcd, 'yyyy-MM-dd')
is_valid_pcd = [
pcd_format.isNotNull(),
(pcd_format > DEFAULT... | 557913387b71c9695b6f51331fd208368a6d0b6f | 77,861 |
def find_minimum_skew(dna, save_skew=False, file_name=None):
"""
Generates a list of indexes with the minimum G - C skew.
:param dna: a string of DNA
:param save_skew: whether to save the skew list to a file
:param file_name: the file to save the skew to
:return: a list of DNA indexes ... | 733a96c14ef4c627bdeaa9a0f9cdbb39bd070b8a | 77,862 |
def best_validation_rows(log_df, valid_col='valid_accuracy', second_criterion='iterations_done'):
"""
Takes a dataframe created by scripts/logs_to_dataframe.py and returns
a dataframe containing the best-validation row for each log.
"""
return log_df.sort_values([valid_col,second_criterion],ascendin... | 9541adb6653a93bfe0385bd24beedf80b065dde7 | 77,863 |
def lint_commit_author(commit):
"""
Checks that the author is properly set.
"""
success = True
if commit.author.email.endswith('users.noreply.github.com'):
error(
'Commit author has no valid email address set: %s. '
'Use "git config user.email user@example.com" to '
... | 2a1a92a89e664babf91812c11dd7b1868794fd4a | 77,864 |
def get_kwargs(names, defaults, kwargs):
"""Return wanted parameters, check remaining.
1. Extracts parameters `names` from `kwargs`, filling them with the
`defaults`-value if it is not in `kwargs`.
2. Check remaining kwargs;
- Raise an error if it is an unknown keyword;
- Print warnin... | 20720215c9d1e2849b519c9f6ce2d8eb074752c3 | 77,865 |
def reset_password():
""" Reset Password Page """
if session.get('email') and session.get('fiscally_data'):
form = ResetPasswordForm()
if form.validate_on_submit():
user = User.query.filter_by(email=session.get('email')).first()
if form.new_password.data == form.verify... | 55c80bdf5e5b2775062b12285687e02cefa97416 | 77,866 |
def create_integration_role(session, role_policy, nr_account_id):
"""
Creates a AWS CloudFormation stack that adds the New Relic AWSLambda Integration
IAM role.
"""
role_name = "NewRelicLambdaIntegrationRole_%s" % nr_account_id
stack_name = "NewRelicLambdaIntegrationRole-%s" % nr_account_id
r... | 3a93825ce42eb80a3e2c829e72cb41b912b17464 | 77,868 |
def insertionsort(a):
""" insertion sort implementation
>>> insertionsort([6, 4, 8, 2, 1, 9, 10])
[1, 2, 4, 6, 8, 9, 10]
"""
for i in range(len(a)):
item = a[i]
j = i
while j > 0 and a[j-1] > item:
a[j] = a[j-1]
j -= 1
a[j] = item
return a | ffaf0c5f81df5086857b2e667e3f5a57d151e8f6 | 77,869 |
from pathlib import Path
def get_organ_volume_data(root_dir: Path) -> pd.DataFrame:
"""
Given a root registration directory, collate all the organ volume CSVs into one file.
Write out the combined organ volume CSV into the root registration directory.
Parameters
----------
root_dir
Th... | 7ea90e1c744542637336e1ada8ea1329a3b08a2c | 77,870 |
from MoinMoin.search.Xapian.search import XapianSearch, IndexDoesNotExistError
def _get_searcher(request, query, sort='weight', mtime=None, historysearch=None, **kw):
"""
Return a searcher object according to the configuration.
"""
query = _parse_query(query, **kw)
searcher = None
if request.... | 88b4e3e6fa9dc3669ae5229be18594dc47f52b5f | 77,871 |
import json
def format_result(result, distance, units, output):
"""Formats nearest store and corresponding distance into specified output.
Args:
result (dict or None): Result of nearest store.
distance (float or None): Distance to nearest store.
units (str): Distance metric (mi or km)... | 0cf9148532131afcbc7dbf71ee36d4d8416ad5da | 77,872 |
import torch
def extract_transformation_matrices(T0, indices):
"""
Compute the relative transformation matrices for the overlaping pairs from their global transformation matrices
Args:
T0 (torch tensor): global transformation matrices [4*b,4]
indices (torch tensor): indices of the overlaping ... | fcae95aa676419b7a2dc919db53080b18165bfb8 | 77,873 |
def display_cookie_consent(request):
"""Add cookie consent state to context"""
accepted_cookie_groups = {}
show_cookie_consent = bool(get_not_accepted_or_declined_cookie_groups(request))
if show_cookie_consent:
user = request.user
if user.is_authenticated:
user_cookie_conse... | a5751f6d56530f5e18dbafcd4049612e7d7a9a0c | 77,874 |
def min(sequence):
"""
Returns the minimum value in sequence, which must be non-empty.
>>> min([3, 1, 4, 1, 5, 9])
1
>>> min([])
Traceback (most recent call last):
...
ValueError: min() arg is an empty sequence
"""
return __builtin__.min(sequence) | 74f6b479e43e265ca435a0e2788d03f92abe1778 | 77,875 |
def SoftsandModel(Phi, Rho, Kmat, Gmat, Kfl, critporo, coordnum, press):
"""
SOFT SAND MODEL
Dvorkin's soft sand model.
Written by Dario Grana (August 2020)
Parameters
----------
Phi : float or array_like
Porosity (unitless).
Rho : float
Density of the saturated rock (g/... | 7742d9019d091ec6e01f457a9c224a61c32d5786 | 77,876 |
import torch
def evaluate(val_ld, selector, predictor, device, k, return_avg=False, numpy_sample=False):
"""Function to evaluate current model weights.
Args:
val_ld (DataLoader): dataloader for the meta-val set
selector (nn.Module): the selector module
predictor (nn.Module): the predictor module
... | 3e4643a408ea05f6eb5b047c3a4001612a495bac | 77,877 |
def filter_labels(atlas_vol, labels):
"""
Filters given volumes to only include given labels, all other voxels are set to 0.
"""
mask = np.zeros(atlas_vol.shape, 'bool')
for label in labels:
mask = np.logical_or(mask, atlas_vol == label)
return atlas_vol * mask | f7242cf9cbf72ae0aeb62f13bacb3b8e77b8a375 | 77,878 |
def n_mask_items(request):
"""Percentage of items to mask on init"""
return request.param | 10c1214b8dca81fde59428835302abe35fc72d23 | 77,879 |
def align(source):
"""Return a string containing the same program but aligned
to the start of a transaction or command (in that order).
This function does not run a complete syntax check, but raises
an ValueError, if the source is commented incorrectly.
Examples:
>>> align("+67; O=0, O+66;... | 228a1fe4bbc94e20b08828fb03e9714ca8acd6f9 | 77,880 |
def getMsgTime(line):
"""Parse the timestamp off the 978 message and return as a float.
Args:
line (str): Line containing a 978 message with a timestamp at the end.
Returns:
float: Timestamp of the message.
Raises:
Exception: If the timestamp can't be f... | 860a02a28d154357d6fcc61de182fee1f4875aaa | 77,882 |
from bs4 import BeautifulSoup
def extract_timeline(html: str) -> list:
"""
Extract tweets from timeline data
:param html:
:return:
"""
result: list = []
soup = BeautifulSoup(html, 'html.parser')
for li in soup.find_all('li', attrs={'class': 'js-stream-item stream-item stream-item'}):
# find first div
fir... | 8ec4803f6fb59bcb5b08e9b150bbd7bfda06d946 | 77,883 |
import scipy
def pulse_from_spectrum(wavelength, spectrum, pulse=None):
""" Generates a pulse instance from a measured spectrum.
"""
# scale to intensity over frequency, convert to amplitude and normalize
spectrum = spectrum * wavelength * wavelength
spectrum[spectrum < 0.0] = 0.0
spectrum = n... | 2e0c123a133f58698968586804169ea7092db2c4 | 77,884 |
import itertools
def expand_jobs(**kwargs):
"""find all possible combinations of options in test arrays"""
options = []
for k, values in kwargs.iteritems():
name_values = []
for v in values:
name_values.append("--%s=%s" % (k, v))
options.append(name_values)
return list(... | 7984efd9ba31e3c87ab0a81af2cc951f07b2f1bf | 77,885 |
def get_fibre_stats(h5path_in, stats=[]):
"""Calculate statistics."""
ds_in = utils.h5_load(h5path_in, load_data=True)[0]
ulabels = np.unique(ds_in)
Nlabels = len(ulabels) - 1
# print("number of %s labels: %d" % (name, Nlabels))
props = {}
props['area'] = np.empty([ds_in.shape[0], Nlabels... | 00ac0e9a070f919da83945f52dad423e84a52958 | 77,889 |
from datetime import datetime
def log_time_converter(value):
"""
Converts the given value to it's snowflake representation.
Parameters
----------
value : `int`, ``DiscordEntity`` instance or `datetime`
If the value is given as `int`, returns it. If given as a ``DiscordEntity``, then retur... | 0af89eb5662b30d36a050f03eedaeeb08ce1cb7f | 77,890 |
import ipaddress
def address_is_a(addresses, node_types):
"""
:param addresses: List of IP addresses
:param node_types: List of acceptable node types
:return: True if the addresses belongs to a host or does not belong to anything
"""
ip_addresses = [ipaddress.ip_address(item) for item in addre... | ae202b221aa1fdcc6c254422629e1d3d20ac23e9 | 77,892 |
import html
def index():
"""
The index route of the application.
Serves the home page with the documentation articles that are fetched from the database.
Errors and metrics are tracked using application insights.
"""
if not session.get('access_token'):
resp = Response(statu... | 27094dc575d548dfac6c664e9d5083982766f7d4 | 77,893 |
def g2n(gtsam_obj:gtsam) -> np.array:
"""converts a gtsam object to a numpy array
Args:
gtsam_obj (gtsam): the input gtsam object, we can accept several types
Raises:
NotImplementedError: if we don't have a conversion for that object raise an exception
Returns:
np.array: the i... | ef17953f09754b904d03436b233fc5af1b031e55 | 77,894 |
def memo_list(request):
"""
List all code memos, or create a new memo.
"""
if request.method == 'GET':
memos = Memo.objects.all()
serializer = MemoSerializer(memos, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSON... | 17308e2f043d899756fd71c03c6554aeb37a2f00 | 77,895 |
def _counting_sort(a, max_value):
"""
sorting positive integers less than or equal to max_value
"""
result = []
counter = [0] * (max_value + 1)
for i in a:
counter[i] += 1
for i, count in enumerate(counter):
result.extend([i]* count)
return result | 8d81ec58e851eab73011ee180c1fe60c36b46675 | 77,896 |
def get_all_vs():
"""Creates a list of all the compatible versions of Visual Studio."""
all_vs = []
for vs_type in VS_COMPATIBLE_TYPES:
for year_num in VS_COMPATIBLE_VERSIONS.iterkeys():
all_vs.append(VS_NAME_PREFIX + vs_type + " " + year_num)
return all_vs | 9209b367f3d32c43ae9e16354cf57c00a169e2c3 | 77,898 |
def GetAllFields(fielddefs):
"""Extract L{objects.QueryFieldDefinition} from field definitions.
@rtype: list of L{objects.QueryFieldDefinition}
"""
return [fdef for (fdef, _, _, _) in fielddefs] | 0a831dc1eadad01a91bfb131feae4ecc0e5cb1f2 | 77,899 |
def create_embedding_matrix(word_index, embedding_dim, w2v_path):
"""
Create the initial embedding matrix for TF Graph.
Args:
word_index: dictionary storing the word-to-index correspondence
embedding_dim: word2vec dimension
w2v_path: file path to the w2v pickle file
Returns:
... | a1ee0024756d77dd5ce4152532f16b278499d7d1 | 77,900 |
def ordinalize(given_number: int) -> str:
"""Ordinalize the number from the given number
Args:
given_number (int): integer number
Example:
>>> ordinalize(34)
'34th'
Returns:
str: string in ordinal form
"""
suffix = ["th", "st", "nd", "rd"]
thenum = int(given_number... | e0b43b3b8353e9e79d2f13a36198782a2a5dcd73 | 77,901 |
import keyword
import builtins
def get_invalid_tokens():
"""
Get a list of invalid tokens that can be used inside sfc_model equations.
:return: list
"""
internal = ['self', 'None']
kw = keyword.kwlist
if is_python_3:
built = dir(builtins)
else: # pragma: no cover
buil... | 41f0f272a6af95c6f428d60f312d20108308d3e4 | 77,902 |
def row_count(in_csv):
"""Utility function for counting rows in a CSV file."""
with open(in_csv) as f:
# Increment idx for each line
for idx, l in enumerate(f):
pass
# idx is equal to # of lines - 1 due to 0 indexing.
# This is the count we want, as the header line should be... | 7e9c72926b6040efe3b5192ab3bba52096a6584c | 77,903 |
def get_filenames(hda_dict):
"""
Generates a list of filenames taken from the results dictionary,
retrieved with the function request_results_list.
Parameters:
hda_dict: dictionary initied with the function init, that
stores all required information to be able to
... | c14911b14fa2b31f061b4420875c603d8acce5c1 | 77,904 |
def get_leap_recommended_pbradii(implicit_solvent):
"""Return the recommended PBradii setting for LeAP.
Parameters
----------
implicit_solvent : str
The implicit solvent model.
Returns
-------
pbradii : str or object
The LeAP recommended PBradii for the model.
Raises
... | 7b302bd7493d38987971238f62cbfaed1461e87c | 77,905 |
def robust_unwrap(signal, discont=3.141592653589793):
"""
Robustly unwrap a phase signal.
Sometimes, due to numerical discreteness, the "jump" in the signal does not
happen immediately between two adjacent signal points, but rather over
several points. For example::
[-2.98, -3.01, -3.03, -3.... | a7f423110fa09f0da1edf90aac0f263462ae0cbe | 77,906 |
def promise_required(fn):
"""
通过 用户 角色 路由 来控制权限
用户包含多种角色
角色又包含多种 路由权限
"""
@wraps(fn)
def promise_check(*args, **kwargs):
promise_list = current_identity.promise_list
has_promise = False
for promise in promise_list:
if (request.path == promise... | 94ead263ffa6b12fcc86dc371b04b132b7285c1d | 77,908 |
def initialize():
"""
This methods initialises the main components.
It returns the postgreSQL object, as well as the Facebook scraper and the REST middleware:
(pg, fb, app)
"""
# Arguments
parser = ArgumentParser(description=info())
parser.add_argument('-i', '--ip', help="Listen address... | cf9bf596526df647decaaf8fa368576e8875d64d | 77,909 |
def compute_overlaps(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: a np array of boxes
For better performance, pass the largest set first and the smaller second.
:return: a matrix of overlaps [boxes1 count, boxes2 count]
"""
# Compute overlaps to generate m... | d5a29d1ae6d2a24115aea94e074339a0a15aceb9 | 77,910 |
def spectrogram(cnt):
"""Calculate the spectrogram of a continuous data object.
See Also
--------
spectrum, stft
"""
framesize = 1000 #ms
width = int(cnt.fs * (framesize / 1000))
specgram = np.array([stft(cnt.data[:,i], width) for i in range(cnt.data.shape[-1])])
freqs = sp.fftpack... | 1c8830fc6fb133c987084b1aa9a048a5b7ac4f36 | 77,911 |
import re
def parse_args(arg_list):
"""
I put command line args and their proper values together in a
dictionaryionary and check, if the value is valid.
"""
dictionary = {}
for item in arg_list:
common_pattern = re.compile(r'^(-pn|-s|-po|-pw|-n|-npw|-ho)$')
common_pattern = co... | 2f221e3ca0adc112869aef4cda217b3352e37db8 | 77,912 |
def create_child(state: Node, move: int) -> Node:
"""Returns a new node for the given move at the given state"""
if not can_make_move(state.empty_tile_index, move):
return None
# print("create child for move:", MOVES_STRING_REPRESENTATION_MAP[move])
next_index = state.empty_tile_index + move
... | d9383b7e5a7737be73fa81fcea2f78ab27b29485 | 77,913 |
def LocalAggregation(config,
query_points,
support_points,
neighbors_indices,
features,
scope,
radius,
out_fdim,
is_training,
init=... | 1173fafebab62fe4c7af641a9d07b01e99e22ecc | 77,914 |
import unittest
def test_suite():
"""Test suite including all test suites"""
testSuite = unittest.TestSuite()
testSuite.addTest(test_base("test_serialize"))
return testSuite | cbcb111c21000330b68cc8be44e644eb4585352d | 77,916 |
def _partition_fn(example,
partition_count, num_splits):
"""Partitions example into train/test based on hash of table id."""
assert partition_count == 2
if isinstance(example, interaction_pb2.Interaction):
example_id = example.table.table_id
elif isinstance(example, tf.train.Example):
... | 81fb5b366da743e6f61efe43e8156d14b15ae555 | 77,917 |
def unscattered_rt(s):
"""
Unscattered reflection and transmission for a slide-slab-slide sandwich.
The sample is characterized by the record 'slab'. The total unscattered_layer
reflection and transmission for oblique irradiance ('urx' and 'utx')
together with their companions 'uru' and 'utu' for ... | 55632edbd3ac20f50e012ab46cfd3fd86f2ccd45 | 77,918 |
def get_predictions(logits: jnp.ndarray) -> jnp.ndarray:
"""Returns predictions given a batch of logits."""
outputs = jax.nn.sigmoid(logits)
return (outputs > 0.5).astype(jnp.int32) | 1c2bb261c58053740851d3054bc3fe5a8ff0ee4a | 77,920 |
from datetime import datetime
def _dump_date(d, delim):
"""Used for `http_date` and `cookie_date`."""
if d is None:
d = gmtime()
elif isinstance(d, datetime):
d = d.utctimetuple()
elif isinstance(d, (integer_types, float)):
d = gmtime(d)
return "%s, %02d%s%s%s%s %02d:%02d:%... | a54fabb6d9cd22878255bee5d2ecc0b512687385 | 77,921 |
from datetime import date
def voto(ano):
"""
-> Verifica a obrigatoriedade de voto de uma pessoa
:param ano: Ano de nascimento de uma pessoa
:return: retonar se uma pessoa tem o voto NEGADO, OPCIONAL OU OBRIGATORIO
Função desenvolvida por Danilo
"""
idade = date.today().year - ano
prin... | 703b86a4c01fef7cd89c961bda8dbd644fb26faf | 77,923 |
def map_recursive(function, iterable):
"""
Apply function recursively to every item or value of iterable and returns a
new iterable object with the results.
"""
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
... | 9e8c089ead09b6da89ab4b349b4ce7d9aa038b31 | 77,924 |
def isRig(node):
"""
Return whether a node represents a pulse rig
Args:
node: A PyNode or string node name
"""
return meta.hasMetaClass(node, RIG_METACLASS) | 238d49f12c9940f9c3dcb7d6d91370ca6b26e9de | 77,925 |
def get_fibonacci_ints(ints, length):
"""f(n) = f(n-1) + f(n-2)"""
first = ints[0]
second = ints[1]
if length == 1:
return [first]
if length == 2:
return [first, second]
ints = get_fibonacci_ints(ints, length=length - 1)
ints.append(ints[-1] + ints[-2])
return ints | ff9e1691183560f12cb844af0e0a9b9f9579efd6 | 77,926 |
from typing import Optional
import logging
def get_sequence(
identifier: str, start: Optional[int] = None, end: Optional[int] = None
) -> str:
"""
Return the sequence for the protein given identifier
If the identifier is null
>>> get_sequence("AFR46509", 10, 23)
'CASSLGTTNTEVFF'
"""
re... | 065faec22e278c996c9f63fc720ea058714cc968 | 77,927 |
def distance_two_rooms(graph_name, room_name0, room_name1):
"""
find the distance between 2 specific rooms on a floor
graph_name: name of the graph to examine
room_name0: name of the starting room
room_name1: name of destination room
"""
data, print_data = dao.get_latest(graph_name)
if d... | 83d2fe2949f850ca42532bef04c6e2ee40f1664e | 77,929 |
from random import shuffle
def random_trial_k_smallest(n, k):
"""Conduct a random k_smallest trial."""
vals = list(range(n))
shuffle(vals)
return k_smallest(vals, k) | 5d3039b0847a0517e0af634d64f9ce4c6a7c31d9 | 77,930 |
def core_profiles_consistent(ods, update=True, use_electrons_density=False):
"""
Calls all core_profiles consistency functions including
- core_profiles_densities
- core_profiles_pressures
- core_profiles_zeff
:param ods: input ods
:param update: operate in place
:param use_elec... | f09227bdec607727dcc7a7ad0c327e52befef7eb | 77,931 |
def _adjust(hsl, attribute, percent):
"""Internal adjust function"""
hsl = list(hsl)
if attribute > 0:
hsl[attribute] = _clamp(hsl[attribute] + percent)
else:
hsl[attribute] += percent
return hsl | a1f6fbed191610c138b3c27348316388090fa5e6 | 77,933 |
def transformation_features(df, age_extra: bool = False, fare_extra: bool = False):
"""get new or modified features based on EDA
Parameters
----------
df : panda dataframe
Returns
-------
Dataframe with all studied modifications
"""
df = utils_hulle.get_size_family(df, mod = Tr... | d18843777326c848c8559db369a815ea32afbb02 | 77,934 |
import re
def split_into_sentences(text):
""" customized sentence splitter for testing (not used now) """
text = " " + text + " "
text = text.replace("\n\n", " . ") # ignore paragraph here
text = text.replace("\n"," . ")
text = re.sub(prefixes,"\\1<prd>",text)
text = re.sub(websites,"<prd>\... | cc04e4c14fb4f25b669c181417956832fcec0b30 | 77,935 |
def evaluate_all(article_title, article_text, base_path='', web=False):
"""
Load all 4 models
Run predictions on all 4 models
Return a dictonary
{ "emotion": pred_emotion, "category": pred_category, "fake": pred_fake, "sentiment": pred_sentiment }
All pred_ are text strings except sentiment (a s... | 6107ef7f148ac17065d2036fe76c527f72edb4ca | 77,936 |
def straified_train_test_split(*arrays, **kwargs):
"""Like train_test_split but stratified
Note that y is a required keyword argument
"""
y = kwargs['y']
test_size = kwargs.pop('test_size', 0.25)
random_state = kwargs.pop('random_state', None)
sss = StratifiedShuffleSplit(y, test_size=test_... | 7b54c5bc31c98481bc4049c00bc636a458fabc6d | 77,937 |
def resnet50(pretrained=True, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), ... | fc034c163f93fef0825ce970ffc6840d47b41b8c | 77,938 |
def top_k_mean(data: list, top_k: int):
"""
This function calculates the arithmetic mean of the first K terms in descending order.
If K is greater than the N number of terms, the remaining terms will be filled in with zero.
:param data: a list of numerical terms
:param top_k: the number of t... | 0c32f7e4d2a5f44b4d0860507c9c5c669f4465bd | 77,939 |
def blend(image1, image2, lam=0.5):
"""Blend image1 and image2 by linearly interpolating by a factor lambda.
"""
ones = [1] * (image1.dim() - 1)
lam = to_tensor(lam)
lam = lam.view(-1, *ones)
lam = lam.to(image1.dtype)
lam = lam.to(image1.device)
return image1 + lam * (image2 - image1) | 83ff715d1a71312e842e74bb9a628e27c43bb0d7 | 77,940 |
def generate_grpc_request():
"""Generate gRPC inference request with payload."""
request = predict_pb2.PredictRequest()
request.model_spec.name = FLAGS.model_name
request.model_spec.signature_name = 'serving_default'
image = get_image_payload()
request.inputs[FLAGS.input_name].CopyFrom(
contrib_util... | 5f9547cf8bcf4236c8c1ea9dfbf2fd90900c5087 | 77,941 |
import numpy
import pandas
def metrics_to_pandas(metrics):
"""
Place holder for an attempt to make a generic Pandas object for the metrics
service. However, for this to work well, you need to know all the possible
year keys, and so currently as it is written it won't result in necessarily
all the ... | af1ae73f2b94680adb838682d97ac926a34ec36e | 77,942 |
def extracted():
"""
return the (set of canonical names) of all extracted packages
"""
return set(dist for dist, rec in package_cache().items() if rec['dirs']) | 0f4de8107ac15dcb8e89b68dfb831d18df55522c | 77,943 |
def times(count: int) -> _Timing:
"""
How many times to expect the request
:param count: count
:return: Timing object
"""
return _Timing(count) | 78a9305ac84d84886a618dd1b9366dc2fb283783 | 77,944 |
def _euclidean_quadrature(interval):
"""Uniform euclidean quadrature.
This quadrature provides discrete inner products for intrinsically discrete
data.
Parameters
----------
interval: numpy.ndarray
The set of points on which define the quadrature.
Returns
-------
nodes: nu... | cf4d78a397a14ee3b9d402253fd0461b64ba1e47 | 77,945 |
from shapely.geometry import LineString
def trip_bbox(trip):
"""
get the bounding box of the given trip
input: trip: a trajectory
output: (minx, miny, maxx, maxy)
"""
line = LineString(list(trip['geometry']))
return line.bounds | 10b1af4961d1c0d479aec9b29acc6b5cb80d5237 | 77,946 |
def segment_chars(plate_img, fixed_width):
"""
extract Value channel from the HSV format of image and apply adaptive thresholding
to reveal the characters on the license plate
"""
V = cv2.split(cv2.cvtColor(plate_img, cv2.COLOR_BGR2HSV))[2]
T = threshold_local(V, 29, offset=15, method='gaussian... | a477c86b94b1fe4986e073c76bcc7bcdefb43afc | 77,947 |
import math
def cfg_callback(config, level):
"""
Get params from dynamic reconfigure
:param config:
:param level:
:return:
"""
global max_vel, min_vel, max_angle, kP, kI, kD, offset, use_odometry_vel, motor_run
print("config")
max_vel = float(config["max_vel"])
min_vel = floa... | 290782cd65be50171990398a75ca434f5a333104 | 77,948 |
def get_centremass(elem, xyz):
"""Returns centre of mass of a set of atoms.
Parameters
----------
elem : (N,) array_like
The atomic symbols.
xyz : (N, 3) array_like
The atomic cartesian coordinates.
Returns
-------
(3,) ndarray
The position of the centre of mass... | 017bf5321c544af2669b3fbbeb4800872ad45938 | 77,951 |
def solve_room(room, objective):
"""Find a sequence of actions to solve a room.
Parameters
----------
room
The room to solve
objective
The objective to reach.
"""
objective_reacher = ObjectiveReacher(room)
problem = PlanningProblem(objective, objective_reacher)
searc... | a3cc544bd91f4db6c8997ba3c06d3bb6a5880061 | 77,952 |
def user_info():
"""展示用户个人中心页面"""
#1.获取用户对象
user = g.user
#2.组织数据
data = {
"user_info": user.to_dict() if user else None
}
return render_template("profile/user.html", data=data) | df09fb07a7f8b10d71217ff06a6c19a179edeee1 | 77,953 |
def is_copula_relation(token1, token2):
"""Return True if `token1` is a copula dependent of `token2`.
We don't want to capture cases where `token2` is an adjective, because
we capture those in `is_predicated_adjective_relation()`.
"""
return (
(token1.deprel == "cop")
and (token2.u... | 35e7b19c3cf1662c09a8fd80c8099073de11bc51 | 77,954 |
def delete_customer(customer_id):
"""Delete customer from Stripe, cancelling subscriptions."""
try:
customer = stripe.Customer.retrieve(customer_id)
return customer.delete()
except stripe.error.InvalidRequestError:
log.exception(
'Customer not deleted. Customer not found ... | ebb9568cd192ac1205dda9a520f1ce28543c0ec0 | 77,955 |
def get_glass_spec_category(glass_spec_name):
"""ガラスの仕様の区分はガラスの仕様に応じて返す
Args:
glass_spec_name(str): ガラスの仕様
Returns:
int: ガラスの仕様の区分はガラスの仕様に応じて返す
"""
# 表3 ガラスの仕様の区分
table_3 = {
'2枚以上のガラス表面にLow-E膜を使用したLow-E三層複層ガラス(日射取得型)': 6,
'2枚以上のガラス表面にLow-E膜を使用したLow-E三層複層ガラス(日射遮蔽型)... | e5fbd29c438384931102744a97e7cd94c96a8478 | 77,956 |
import math
def calculate_coordinates(valid_dict: list) -> list:
""" Calculate the coordinates using trigonometry
This takes a list of dictionaries of the format
`[{'testuser':[6, 4, 3, 10, 5]}, {'testuser2':[1, 5, 17, 20, 6]}]` and
then returns a list of coordinates. These coordinates can be used to... | b648a965c83df841778fe4030e2b9729cbac2c59 | 77,957 |
def _safe_decr(line_num):
"""
Return @line_num decremented by 1, if @line_num is non None, else
None.
"""
if line_num is not None:
return line_num - 1 | ad6092b68240f39ccba13fda44bbf8af22d126f4 | 77,959 |
def CentralDiff(fx, x, h=0.001):
"""
CentralDiff(@fx, x, h);
Use Central difference to approximatee the derivative of function fx
in points x, and with step length h
The function fx must be defined as a function handle with input
parameter x and the derivative as output parameter
Parameters... | 4233926d076f31218c2ae517086c8d9835822073 | 77,960 |
def zfun(p,B,pv0,f):
"""
Steady state solution for z without CRISPR
"""
return p*(B-1/pv0)/(1+p*(B-1/pv0)) | aaddce7a41e0ad9e909e6f5f2bf86354f66c5be8 | 77,961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.