content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def closeMines(user: User) -> int:
"""
Close all open mining games whose end time is due; return
the number of closed games.
"""
client = makeCrabadaWeb3Client(
upperLimitForBaseFeeInGwei=user.config["closeMineMaxGasInGwei"]
)
openGames = fetchOpenMines(user)
finishedGames = [g f... | e21214dd2580dc3fb8f7b3c34b8b6050ba91e2c0 | 71,702 |
def estimate_meters_to_deg(meters, precision=PRECISION_PERSON):
""" Meters to degrees estimation
See https://en.wikipedia.org/wiki/Decimal_degrees
Args:
meters (float)
precision (float)
Returns:
float: meters in degrees approximation
"""
line = PRECISION_TABLE[precision... | 759572fdfb1ee7c33217cb3a15f2d1df272595f3 | 71,703 |
def convert_resolv_conf(nameservers, searchdomains):
"""Returns a string formatted for resolv.conf."""
result = []
if nameservers:
nslist = "DNS="
for ns in nameservers:
nslist = nslist + '%s ' % ns
nslist = nslist + '\n'
result.append(str(nslist))
if searchdo... | 47175fb2dddac151a94b99b1c51942a3e5ca66a1 | 71,704 |
from pathlib import Path
def resolve_model_name(name):
"""
If spaCy is loaded with 'de', check if symlink already exists. If
not, user may have upgraded from older version and have old models installed.
Check if old model directory exists and if so, return that instead and create
shortcut link. If... | 5d40d464f54874c0fdb19144de818e0999218732 | 71,705 |
def slow(data, fs):
"""
Apply slow (S) time-weighting.
"""
return time_weighted_sound_level(data, fs, 1.0) | 7018daa6fbca57f1f424873656bd8bf9ef48eda5 | 71,706 |
def not_found(error):
"""This shows a better looking 404 page."""
return render_template('404.html'), 404 | e62b3eaf7665c01de252600817a17ee79c9a0a91 | 71,707 |
def finiteDifference2D_baru(v, w, nt, dt, nx, dx, nz, dz, g):
"""
2D finite central difference 2nd order. Based on von Neumann Stability analysis,
alpha = v*dt/dx <= 1/sqrt(2).
Parameter
---------
v = velocity model
w = model represented by wavelet
nt,nx,nz = number of time, x and ... | 6c4579941e619b6e43c35629b29083f1edfdb27d | 71,708 |
def fibonacci(n):
"""
Return the nth fibonacci number, that is n if n < 2,
or fibonacci(n-2) + fibonacci(n-1) otherwise.
@param int n: a non-negative integer
@rtype: int
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(3)
2
"""
if n < 2:
return n
else... | 34e0828848130a16dcd0151165941ed6cdcf714d | 71,709 |
def password_okay_by_char_count(pwd_row):
"""
Process list of rows from a file, where each row contains pwd policy and pwd.
Pwd is only valid if the indicated character is found between x and y times (inclusive) in the pwd.
E.g. 5-7 z: qhcgzzz
This pwd is invalid, since z is only found 3 times, bu... | 4571d1d6e47aef1c31257365cd0db4240db93d6c | 71,710 |
def md2py(md, *args, **kwargs):
"""
Converts markdown file Python object
:param str md: markdown string
:return: object
"""
return TreeOfContents.fromMarkdown(md, *args, **kwargs) | 7106e52f12bbce6df2d5155131c3a5b2758f647d | 71,711 |
def calculate_r2(endogenous, residuals):
"""Calculate r2 value of fit.
:param iterable endogenous: vector of observations of endogenous variable.
:param iterable residuals: vector of residuals between modeled fit and observations.
:return: (*float*) -- r-squared value of fit.
"""
sumres = np.sq... | abc4b5488513f613b02eddff9c2ff6ffe728e430 | 71,712 |
def waiting_ride_order() -> jsonify:
"""
获取待乘车的订单
:return:
"""
try:
return jsonify({'code': '1000', 'message': get_waiting_ride_order(g.user.id)})
except NFUError as err:
return jsonify({'code': err.code, 'message': err.message}) | 1fa1477187f7be321796d473b5d011dd43fb2801 | 71,713 |
import itertools
def tee():
"""Duplicate a sequence by making independent iterators."""
duplicates = itertools.tee('ABC', 2)
duplicates = [''.join(copy) for copy in duplicates]
return duplicates | 33ce3884589c14b789243eb50d74b1f19e942356 | 71,715 |
from typing import Tuple
from typing import List
from typing import Optional
import tokenize
def nlp_preprocess(text: str,
vocab: Vocab,
lowercase: bool = False,
lemmatize: bool = False,
with_lemmas: bool = False,
with_toke... | 7ac3fe883fd07f2328a34bf67ca68a2c4c645d3c | 71,716 |
def pmax(high, low, close, length=None, multiplier=None, offset=None, **kwargs):
"""Indicator: PMAX"""
# Validate Arguments
length = int(length) if length and length > 0 else 7
multiplier = float(multiplier) if multiplier and multiplier > 0 else 3.0
close = verify_series(close, length)
offset = ... | 1629cb472ecc893c8c2592c5911585d686d28ae4 | 71,717 |
import gc
def correlationpass(
fmridata,
fmrifftdata,
referencetc,
fmri_x,
os_fmri_x,
tr,
corrorigin,
lagmininpts,
lagmaxinpts,
corrout,
meanval,
ncprefilter,
optiondict,
rt_floatset=np.float64,
rt_floattype="float64",
):
"""
Parameters
--------... | e3462159906d12dd5cac43884116edabaf37a2a9 | 71,718 |
import re
def check_lookahead(text: str) -> ResultComparison:
""" post: _ """
return compare_results(lambda t: groups(re.match("a(?=b)", t)), text) | a0c069da836fb491e5ef6e27f87a7e3b6f839af3 | 71,719 |
def _getSubjectivityFromScore( polarity_score ):
"""
Accepts the subjectivity score and returns the label
0.00 to 0.10 - Very Objective
0.10 to 0.45 - Objective
0.45 to 0.55 - Neutral
0.55 to 0.90 - Subjective
0.90 to 1.00 - Very Subjective
"""
status = "unknown"
if ( 0... | 16e126032fea92d0eac2d4e6b35c9b6666196ad1 | 71,720 |
def has_date_or_time(conf):
"""Check at least date or time is true."""
if conf[CONF_HAS_DATE] or conf[CONF_HAS_TIME]:
return conf
raise vol.Invalid("Entity needs at least a date or a time") | ca404ba5ceade10e8a5b91300b43ea61e13b3a7b | 71,722 |
def get_trajectory_duration(trajectory):
"""This function returns the duration of a given moveit trajectory.
Parameters
----------
trajectory : :py:obj:`!moveit_msgs.msg.DisplayTrajectory`
The computed display trajectory.
Returns
-------
:py:obj:`float`
Trajectory duration ... | d74b2ca3adcc54d938b9031f974cb3cd7ca16f90 | 71,723 |
def calculate_average_popularity(tweet_set):
"""
Calculates average popularity of week_3.tweet set.
Args:
tweet_set: A set of week_3.tweet objects.
Returns:
A float corresponding to the average popularity.
"""
return mean([tweet.calculate_popularity() for tweet in tweet_set]) | 4d47bda24131372a906ce9e95777bb9d470c13a6 | 71,724 |
def order_from_hits(hit_file, by_order=False):
"""
if by_order is True, then the start/stop positions
are the order, not the basepair positions,
so just use that.
"""
if by_order:
return order_from_ordered(hit_file)
seen = {}
list_order = []
bcmp = cmp # faster lookup.
... | d187f17e0268fb1668bcfb94ebb384485a09dcea | 71,725 |
import base64
def extract_basic_auth(auth_header):
"""
extract username and password from a basic auth header
:param auth_header: content of the Authorization HTTP header
:return: username and password extracted from the header
"""
parts = auth_header.split(" ")
if parts[0] != "Basic" or l... | 8f3830bc78b0e9fb6182f130e38acea4bd189c86 | 71,726 |
def xor(b1, b2):
"""Expects two bytes objects of equal length, returns their XOR"""
assert len(b1) == len(b2)
return bytes([x ^ y for x, y in zip(b1, b2)]) | 3376df85b52cea276417e29ae81c80208dc28b86 | 71,728 |
def setOfWordsToVecTor(vocabularyList, smsWords):
"""
SMS内容匹配预料库,标记预料库的词汇出现的次数
:param vocabularyList:
:param smsWords:
:return:
"""
vocabMarked = [0] * len(vocabularyList)
for smsWord in smsWords:
if smsWord in vocabularyList:
vocabMarked[vocabularyList.index(smsWord)... | f14d8fed8a59deb44fc14161de8ae1eaf3ee8b00 | 71,729 |
from pathlib import Path
import secrets
def load_env():
""" Loads common settings into the env object.
"""
env = {}
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
env['client_id'] = environ[constants.AUTH0_CLIENT_ID]
env['callback_url'] = environ[constants.AUTH0_CALLBACK_... | 6dbf63bcd03488b7058aaa39f087b32097137ef3 | 71,730 |
def non_contradiction_instance_1(person_list,
place_list,
n,
vi_function=vi,
not_vi_function=not_vi):
"""
T = {v(x1,P1), ..., v(xn,Pn)}
new = not v(xi,P*) ----------- 0
P* ... | eea26798c451f8772e62df8e1085594bccdf8fbc | 71,731 |
def delete_exploit():
"""
Changes exploit relevent to 0
"""
if not is_logged():
return render_template('login.html', projects=projects, show_create_project=IS_ENV_SAFE)
exploit_id = request.args.get("id")
db.change_relevent_to_zero(session["db"], "exploits",exploit_id)
retu... | 457ebc8c3d2f2250871080037c416010d4f3d35d | 71,732 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | c33b95db028f462ad5912fcf1ac0e9e9413e7fb7 | 71,733 |
import re
def is_valid_file(filename):
"""
Validates file is of type obj
:param filename: str
"""
return re.match(r'^.+\.?(obj|asm)$', filename) is not None, filename[-3:] | 6f0032693f0097f85ec09e802a2ab870095a232e | 71,734 |
import re
def clean_description(text):
"""The original datasource introduces some common, incorrect encodings.
Fix them here"""
text = text.replace("\u00c2\u00bf", "'")
text = re.sub(r"<\s*br\s*/?>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*br>", "", text, flags=re.IGNORECASE)
ret... | 6778c32058137c7af1d99bf52baaa0889a559e95 | 71,735 |
def LinearTransformation(translation, rotation, x, y):
"""
Apply linear transformations to a set of positions in 2 dimensions.
INPUTS
translation : translation vector
rotation : rotation matrix
x : x-coordinates
y : y-coordinates
OUTPUTS
x : transformed x coo... | e674f215c46ecc6f46da0c1e7074210583f59088 | 71,736 |
def seaborn_cdfplot(data, y, **kwargs):
"""
Wrapper to CDF calculated by hand.
Please see seaborn_FacetGridplot() for parameter list
"""
return seaborn_FacetGridplot(data, y, kind="cdf", **kwargs) | 7f2e1aa22338cd40d3b93b0bfd5e4172cd20d4fc | 71,737 |
def get_safe(dic, *keys):
"""
Safely traverse through dictionary chains
:param dict dic:
:param str keys:
:return:
"""
no_d = dict()
for key in keys:
dic = dic.get(key, no_d)
if dic is no_d:
return None
return dic | 17f810ba995314088f93152179e988df436adb47 | 71,739 |
import torch
def squeeze(input_, axis=None):
"""Wrapper of `torch.squeeze`.
Parameters
----------
input_ : DTensor
Input dense tensor.
axis : None or int or tuple of ints, optional
Axis or axes to operate on, by default None
"""
return torch.squeeze(input_._data, dim=axis) | 57bde66b7fb7f3c91ce8661291bd40d233d98c6f | 71,740 |
import uuid
def check_constraint_naming_convention(constraint, table):
"""
Creates a unique name for an unnamed CheckConstraint.
The generated name is the SQL text of the CheckConstraint with
non-alphanumeric, non-underscore operators converted to text, and all
other non-alphanumeric, non-undersc... | 5f697be2fa59d9913a79f2dcdae22de4d3268b2f | 71,742 |
import random
import string
def random_string(length=1, unicode=False):
"""
Returns random ascii or unicode string.
"""
if unicode:
def random_fun():
return chr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))
else:
def random_fun():
return random.c... | 45760b3e3c42e484d51abf76f9eb2ae0c8132fd1 | 71,744 |
from typing import Union
import numpy
def get_default_image(
shape: ImageShape,
tile_factor: int = 0,
shade: bool = True,
as_image: bool = False,
name: str = "lena",
) -> Union[numpy.ndarray, Image.Image]:
"""
Loads default image from resources and reshape it to size
shape.
:param... | de007c5570854b1eba4bf60709f8dabdf5f0c29a | 71,746 |
def validate_file(file_name, package):
"""Validate a file, return array of errors"""
errors = []
if package is None:
all_allowed = ALL_ALLOWED_ORDER[:]
else:
all_allowed = [EXTERNAL] + \
INTERNAL_ALLOWED_ORDER[INTERNAL_ALLOWED_ORDER.index(package):] + [RELATIVE]
allowed =... | 5ab5629b1233ee75a452fa50f830136308749bb6 | 71,748 |
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
court, registry, number, qualifier = _split(number)
return ' '.join(x for x in [court, registry, number, qualifier] if x) | 8db23f329057b48450509b61f221e2b1ab2888bb | 71,749 |
def dynamicauth_api3(request):
"""
动态二维码验证的第三步,PC 端检查自己是否登录成功
"""
return json_response_zh(get_json_ret(0 if request.user.login_status else 51)) | 0db1369bd84b675f193f7e9af547be77d51cb957 | 71,750 |
def comparePaths(path1,path2,pointsToCheck=3):
"""
open paths before closed paths
outer paths come before inner ones
otherwise, top to bottom bounds, left to right
"""
if closed(path1) and not closed(path2):
return 1
elif closed(path2) and not closed(path1):
return -1
... | fea7cd2566334d3ff1de42241a0109f9d828e05a | 71,754 |
import math
def probability(ec, en, t):
"""
Probability function
:param ec: current energy
:param en: next energy
:param t: temperature ratio
:return: probability value
"""
return math.exp((ec - en) / t) | c055081cd93473ecf4abeab1c8b5cc36fb38f0a4 | 71,755 |
def pad_X(X, maxsize):
"""
Pad Xs out to same length
"""
X_padded = []
X_lengths = []
for x in X:
diff = len(x) - maxsize
X_lengths.append(len(x))
if diff < 0:
X_padded.append(list(x) + ["*"]*np.abs(diff))
elif diff > 0:
X_padded.append(lis... | c08cc410dd864c931aec7beb30838aad38bc9405 | 71,756 |
from typing import Dict
from typing import Any
from typing import Tuple
def tag_batch(
model: EncodersDecoders,
batch: Dict[str, Any],
criterion=None,
optimizer=None,
) -> Tuple[Dict[str, float], Dict[str, Sentences]]:
"""Tag (apply POS) on a given data set."""
preds, losses = run_batch(model,... | 819dcb0f1457ce6e5f28cccba6dda12d79160124 | 71,757 |
def request(coap_url, method=MethodCode.get, payload=None):
""" A wrapper to make a single request.
Example - coap.request('coap://coap.me/hello')
"""
url = urlparse.urlparse(coap_url)
if url.scheme.lower() not in ['coap', '']:
raise Exception('Not a CoAP URI')
coap = Coap(host=url... | dca9008863bc7794c291da7f2e6401c778c3bda2 | 71,758 |
def helicsQueryExecuteComplete(query: 'helics_query') -> "char const *":
"""
complete the return from a query called with /ref helicsExecuteQueryAsync
the function will block until the query completes /ref isQueryComplete can be
called to determine if a query has completed or not
Parameters
... | a87e2712371847916fef79b8dd84ec316bd90937 | 71,759 |
from typing import Union
from typing import Mapping
from typing import Iterable
def hist(data: Union[pd.DataFrame, pd.Series],
column=None, key_column=None,
bins=35, ticks=None, xmin=None, xmax=None, ylog=False,
color=None, cumulative=False, stacked=False,
xlabel=None, ylabel=None,... | a81d1d81c37d7e373b6461c442584cd480c97c03 | 71,760 |
def make_adj_set():
"""Get the set of adjectives that appear in the corpora both as <adj> and
un<adj>.
This avoids picking up adjectives that don't make since with an un or
without an un.
"""
all_adj = make_adj_superset()
un_adj = make_unadj_set()
return set(word for word in all_adj if ... | b4324010d576534a55b246bd70ec5075e3e7a9c6 | 71,761 |
def RL_num_steps():
""" returns integer """
return num_steps | ad27af9ab17022c2c12ec513edca594430eecda9 | 71,762 |
def run_as_thread(func):
"""
Decorator for making a function run as a new thread
:param func: the function to run
:return: the resulting thread object
"""
@wraps(func)
def thread_func(*args, **kwargs):
thread = Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = Tru... | b30fd47b1b7df4063356e41c09506a036de149b5 | 71,763 |
def project_to_output_distributions(
inputs,
output_spec,
project_to_discrete=layers.factored_categorical,
project_to_continuous=layers.normal,
outer_rank=1,):
"""Project a batch of inputs to distribution objects.
Args:
inputs: An input Tensor of shape [batch_size, None].
output_spec: A... | e71afad9d5c3b61eb4c5fa137283595acb43bf58 | 71,764 |
def grid(m, dtype=np.float32):
"""Return the embedding of a grid graph."""
# Adapted from https://github.com/mdeff/cnn_graph/blob/master/lib/graph.py
M = m**2
x = np.linspace(0, 1, m, dtype=dtype)
y = np.linspace(0, 1, m, dtype=dtype)
xx, yy = np.meshgrid(x, y)
z = np.empty((M, 2), dtype)
... | 7dde58309b05050b0b7895fb07fc32176206f546 | 71,765 |
import functools
def getModel(mdlParams, placeholders):
"""Returns a function for a model
Args:
mdlParams: dictionary, contains configuration
is_training: bool, indicates whether training is active
Returns:
model: A function that builds the desired model
Raises:
ValueError: If model name is no... | b08dde9a3e22af8749ec16ae2fd0b697da673f08 | 71,767 |
import re
def get_crumble_and_cookie(symbol):
"""gets auth keys for the url i.e. crumble and coookie"""
link = crumble_link.format(symbol)
response = urllib2.urlopen(link)
match = re.search(cookie_regex, str(response.info()))
cookie_str = match.group(1)
text = response.read()
match = re.se... | e41599de76a30136ce16b28f4dd0844ed7e5584c | 71,768 |
def getGamesListUrl(user_name, page, block_size=100):
"""Returns lichess url for downloading list of games"""
URL_TEMPLATE = "https://en.lichess.org/api/user/{}/games?page={}&nb={}"
return URL_TEMPLATE.format(user_name, page, block_size) | 314bc8771628944dde1e52299697362482afd9b1 | 71,769 |
def set_motor_manual(motor, motor_state):
"""
Turn a motor, defined by <motor>, on or off, according to <motor_state>.
:param motor_state: On (1) or off (0).
:param motor: The string that identifies one of the four motors on the process.
:return: Empty HTTP 200 response
"""
plc.set_motor(mot... | aba9f95e70b833c84c2acbe64a6bcbd3e62c572c | 71,770 |
def _equalize(image, _):
"""Equalizes the image (as defined in PIL).
Args:
image: A tf.uint8 tensor.
Returns:
The equalized image.
"""
return autoaugment_utils.equalize(image) | 74928125cb1dde2b611eaded727291ea70e309b2 | 71,771 |
from typing import List
def get_current_nodes(inventory) -> List[str]:
"""Return the current nodes' names (group 'nodes') from the inventory as a list."""
return get_nodes_for_homek8s_group(inventory, 'nodes') | 3132a2d6142b0328716574f3a0923110ec41f0df | 71,772 |
def msg2question(msg: dns.message.Message) -> str:
""" Helper function to return a string of name class and type
"""
question = "<empty>"
if len(msg.question):
q = msg.question[0]
name = q.name.to_text()
qclass = dns.rdataclass.to_text(q.rdclass)
qtype = dns.rdatatype.to_... | b425ae4878980f77063b01e07af7b9bb5d8999c4 | 71,773 |
def snp_induced_protein_changes(snp_df, genome):
"""Given a df of {chr, pos, ref, alt} SNP information,
this extracts all ensembl transcripts where the snps induce a protein change.
Result is a dictionary: transcript_stable_id -> altered amino acid sequence"""
potentially_affected_transcripts = snp_hit_... | f80ace15c7d0a9538ddbc39fb9d96fc21e663a67 | 71,774 |
def add_ext(name, ext, seq=-1):
"""add_ext constructs file names with a name, sequence number, and
extension.
Args:
name (string) - the filename
ext (string) - the file extension
seq (int) - the number in a sequence with other files
(Default -1) means that it is a standalone
file
"""
#add peri... | 650eee088ae58d182c49f35f37e5b8deac57fa1d | 71,775 |
def mjd_fromheader2(hd):
"""
return modified Julian date from header
"""
secinday = 24*3600.0
date = hd['DATE-OBS']
ut = hd['UTC']
datetu = date.replace('-',':')
mjd0,mjd,i = GLOBALutils.iau_cal2jd(int(datetu[0:4]),int(datetu[5:7]),int(datetu[8:10]))
ut =... | 49cef2c7e29ab4c8d28feda68213367ace9ec2ff | 71,776 |
import unicodedata
def is_chars_diff_by_diacritic(char1, char2):
"""Check whether two characters differ only by diacritic.
"""
if isinstance(char1, str):
char1 = unicode(char1, encoding='utf-8')
if isinstance(char2, str):
char2 = unicode(char2, encoding='utf-8')
char1_d = unicoded... | 88d3d63154a258f73f589d1f561eb215071cde60 | 71,777 |
import tqdm
def fetch_many_docs(iso_ids, nproc=1):
"""
Args:
iso_ids ([int]): list of iso_ids to fetch
nproc (int): number of processes to use, if greater than 1, will use
larger number of processes
Returns:
([dict]) list of fetched documents
"""
if nproc > 1... | 504e5b19c96ee2936361836dd4c917284491004b | 71,778 |
def my_filter(func, k):
"""Функция"""
res = []
for i in k:
if func(i):
res.append(i)
return res | e0c5367c0aa5f2da6bf07fc6b9c8e4b10a88d86b | 71,779 |
def assd(pred, label, voxelspacing=None, connectivity=1):
"""compute the average symmetric surface distance
It's not the mean value of asd1(average surface distance) and asd2,
which is calculated in medpy's assd.
Args:
pred: prediction array
label: label array
... | 157c798a36709dafcf63734d64c628a30be3a751 | 71,780 |
def requires_end(func):
"""
Decorator raises error if there is no end specified for the EventList
"""
@wraps(func)
def _requires_end(self, *args, **kwargs):
if not self.end:
raise ValueError(
f"EventList's {func} method requires the 'end' attribute to be set."
... | c523eb51c19c219b6e7330c79077d49cd4a221c5 | 71,781 |
def is_rgb(image):
"""
Check if given image is in RGB color space.
:param image: checked image
:return: result of the check (boolean value)
"""
RGB_DIMENSION_COUNT = 3
return len(image.shape) == RGB_DIMENSION_COUNT | fc5ef58d96f60c105aa4b526c3d710906ea8c343 | 71,782 |
def life_support_rating(numbers):
"""
Calculates the life support rating of a list of numbers.
"""
return calc_co2_rating(numbers) * calc_oxygen_rating(numbers) | 4fa8d400e9ded1ec9f907520b3eade59db85d63f | 71,783 |
def get_coding_annotation_fasta(seq_record):
"""
When passed a sequence record object returns an array of FASTA strings for each annotation.
:param seq_record: A Biopython sequence record object.
:return: A FASTA file string containing all sequences record object CDS sequence features.
"""
fasta = []
features =... | 4fa24279ebb89ea7c61eeae6614c1fa309ffad87 | 71,784 |
from typing import Union
def bars_to_atmospheres(bar: float, unit: str) -> Union[float, str]:
"""
This function converts bar to atm
Wikipedia reference: https://en.wikipedia.org/wiki/Standard_atmosphere_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
>>> bars_to_atmospheres(3... | d460021395af77acda01296710f145e9b52d8594 | 71,785 |
def get_ast(token):
"""
Recursively unrolls token attributes into dictionaries (token.children
into lists).
Returns:
a dictionary of token's attributes.
"""
node = {}
# Python 3.6 uses [ordered dicts] [1].
# Put in 'type' entry first to make the final tree format somewhat
# ... | 3074b6a64061dd5cfb2209d803ab060203dfec06 | 71,786 |
def find_frequent_itemsets(data_iter, minSupport):
"""
run the apriori algorithm. data_iter is a record iterator
Return both:
- items (tuple, support)
- rules ((pretuple, posttuple), confidence)
"""
# read from csv
itemSet, transactionList = getItemSetTransactionList(data_iter)
fre... | 00d21f251b409d17b4ba51ec7b9f86941060bd6d | 71,787 |
def dropbox_fileupload(dropbox, request):
""" accepts a single file upload and adds it to the dropbox as attachment"""
attachment = request.POST['attachment']
attached = dropbox.add_attachment(attachment)
return dict(
files=[dict(
name=attached,
type=attachment.type,
... | 84a89a8b8a21c3a78105d8ef911ee6aba71206f2 | 71,788 |
def series(expr, x, point=0, n=6, dir="+"):
"""Series expansion of expr around point `x=point`.
See the doctring of Basic.series() for complete details of this wrapper.
"""
return expr.series(x, point, n, dir) | fee3fff7a29136813c7d6bf5d1cf7c576651368d | 71,789 |
from typing import Literal
def context_command(type: Literal["user", 2, "message", 3], name=None, guild_ids=None, default_permission=None, guild_permissions=None):
"""
Decorator for cogs that will register a context command in discord
``Right-click message or user`` -> ``apps`` -> ``commands is di... | 97ed539c903dc2004af5804769fcfafa2b5a17b0 | 71,790 |
import numpy
def hz2mel(hz):
"""Convert frequency to Mel frequency.
Args:
hz: Frequency.
Returns:
Mel frequency.
"""
return 2595*numpy.log10(1+hz/700.0) | 0d0138d038ed402fd158379ab023addda93e7bcb | 71,791 |
def live_color_command_formatter(src):
"""Formatter wrapper."""
try:
console, colors = execute(src.strip())
el = _color_command_console(colors)
if not colors:
el += '<div class="swatch-bar"></div>'
el += colorize(console, 'pycon', **{'python3': True, 'stripnl': Fal... | 7c49a79121468d9600a5910550ae03c8475c535b | 71,792 |
from src.model import CNN3
def load_model():
"""
加载本地模型
:return:
"""
model = CNN3()
model.load_weights('./models/cnn3_best_weights.h5')
return model | 2c164dffc7f45a2e7455349ac583121b187681f5 | 71,793 |
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None):
"""Process input of the apply_transform_funcs function.
:param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple
:param dict func_args: function positional arguments, specified as ... | 2e9fe4bec55f0a13a0644cfe27ba887f00e85c55 | 71,794 |
def _flattensome(state, write, schedule, result):
"""
Take strings from an iterator and pass them to a writer function.
@param state: An iterator of C{str} and L{Deferred}. C{str} instances will
be passed to C{write}. L{Deferred} instances will be waited on before
resuming iteration of C{... | 9780ae0944b428693716ce61c697072410f57990 | 71,795 |
def not_found(environ, start_response):
"""serves 404s."""
start_response('404 NOT FOUND', [('Content-Type', 'text/html')])
return [to_bytes('''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /??????? was not ... | 080c5dfb5c4f301f2c327e9773526b24608683eb | 71,796 |
import math
def _get_fov(pillow_image) -> float:
"""Get the horizontal FOV of an image in radians."""
exif_data = pillow_image.getexif()
# 41989 is for 'FocalLengthIn35mmFilm'.
focal_length = exif_data[41989]
# FOV calculation, note 36 is the horizontal frame size for 35mm
# film.
return ... | 9b8101010a980079d950b6151a3d5280d5eedb73 | 71,797 |
def split_vertex(G, v, splitInstructions):
"""
Splits the vertex v into two new vertices, each with
edges depending on s. Returns True if the split
divided the graph, else False.
"""
new_index = G.vcount()
G.add_vertex()
G.vs[new_index]['CONGA_orig'] = G.vs[v]['CONGA_orig']
# adding... | 9e48ede85275f0bc7649d85f9351837fd7d8dbea | 71,798 |
def effective(file, line, frame):
"""Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary bp.
"""
possibles = Breakpoint.bpli... | e630dd5c64699229839cf0d4cc686d14dab2ea2c | 71,799 |
def is_supported_django_language(language_code):
"""
Return whether a language code is supported.
"""
language_code2 = language_code.split("-")[0] # e.g. if fr-ca is not supported fallback to fr
return language_code in LANGUAGES_DICT or language_code2 in LANGUAGES_DICT | a19a0c7c7198b01c3fca0fe41c4e540db0a02504 | 71,802 |
def share_snapshot_instance_delete(context, snapshot_instance_id):
"""Delete a share snapshot instance."""
return IMPL.share_snapshot_instance_delete(context, snapshot_instance_id) | af3342e9e4fe441413374eddfdf59e16e7b5c785 | 71,803 |
def distance_between_points(start, destination):
"""
This function finds the distance between the two points, start and
destination using Pythagoras' Theorem.
"""
startX = start[0]
startY = start[1]
destinationX = destination[0]
destinationY = destination[1]
diffX = destinationX - st... | 35896eb26395161837d198474971f8776b7b0e48 | 71,804 |
def get_layout_from_cli(
layout: str,
cols: int,
) -> QtWidgets.QLayout:
"""
Return a correct layout object based on user input.
Parameters
----------
layout : str
String representation of the layout.
cols : int
Number of columns to use for the grid layout.
Returns
... | 0296608b42d3166d478ff848a37d95d99b72bb78 | 71,805 |
def multiarray_sort(arr, srt=[0]):
"""
Sort rows of a two-dimensional array for a given
hierarchy of rows.
Parameters
----------
arr : ndarray
A two-dimensional numpy array.
srt : list
List specifying in which order of rows to sort.
Returns
-------
ndarray
... | 1b21206bffe07f836b4ab4d239ea68047f676752 | 71,806 |
import six
def tar(target, sources, compression=None):
"""This adds or creates a tarball with the provided folder.
If the tar exists it will append, otherwise it will create the tar.
The folder specified will be added to the root of the tar.
For example, if fs.tar('tar.tar', '/foo') is called, it
... | c63054211d5dda51f72be04b2ecd0c711460855a | 71,807 |
def count_total_molecules(filename: str) -> int:
"""Counts number of molecules in a file"""
total = 0
ifs = oechem.oemolistream(filename)
mol = oechem.OEMol()
while oechem.OEReadMolecule(ifs, mol):
total += 1
return total | 70fc84e2a1ef55c2f2f3d92b154979cd58a82d4a | 71,808 |
def focal_lossIII(prediction_tensor,
target_tensor,
weights,
gamma=2.,
epsilon=0.00001,
):
"""Compute loss function.
Args:
prediction_tensor: A float tensor of shape [batch_size, num_anchors,
num_classes] rep... | 1f08c50768705530fc9b54f4455f1673c5d96dba | 71,809 |
import scipy
def expected_loss(high_sim, low_sim, negative_sample_rate, push_tail=True):
"""
UMAP's true loss function, numpy implementation
:param high_sim: np.array or scipy.sparse.coo_matrix high-dimensional similarities
:param low_sim: np.array low-dimensional similarities
:param negative_samp... | 1cd14c08996d88ff7350023a52ac93eba2192bf9 | 71,810 |
def train_model() -> StructureModel:
"""
This Bayesian Model structure will be used in all tests, and all fixtures will adhere to this structure.
Cause-only nodes: [d, e]
Effect-only nodes: [a, c]
Cause / Effect nodes: [b]
d
↙ ↓ ↘
a ← b → c
↑ ↗
... | d677b9e9bbf943b148f9cf7643fd56cd998c025d | 71,811 |
def invoice():
"""Create invoice."""
class CompanyInfo(object):
"""
Temporary hardcoded params until flask login is implemented.
Then user info will contain these attributes.
"""
name = ""
logo = url_for('static', filename="images/logo.png")
job = ""
... | dd7ace0de4c4e3504a35cb3f75efb6c480c289fe | 71,812 |
from operator import mul
def persistence(n: int) -> int:
"""
>>> persistence(243)
2
"""
a = list(str(n))
count = 0
while len(a) != 1:
a = list(str(mul(map(int, a))))
count = count + 1
return count | d99efee2f40f10c95baec2c6233523a98a31ff1e | 71,813 |
import re
def validate_str(input,validate):
"""
This function returns true or false if the strings pass regexp
validation.
Validate format:
substrname: "^\w{5,10}$",
Validates that the string matches the regexp.
"""
if not re.match(validate,input) == None:
# If the validation returned something, return... | 400fd1cd7b4fa297f5916e80a39d7ef668deab1c | 71,814 |
def searches(from_, to, hashids=None, device=None, query_name=None,
source=None, total_hits=None, tz=None, format_=None, **opts):
"""
Return number of searches in a period grouped by date.
"""
query_params = parse_query_params({
'from': from_,
'to': to,
'hashid': has... | a3f2d05f32839f8aba3fcfbcbc1c2170ca067c2e | 71,815 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.