content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def authenticate(user, password):
"""return a user's hash"""
user_pass = User.query.filter_by(user=user).first()
if user_pass is None:
raise UserNotFound(user)
else:
return user_pass.serialize_user()["hash"] | 6c26fe1101d8096a9a6ba0bc345e72880c3facdc | 3,610,100 |
from typing import List
def txt2list(path: str) -> List:
"""
Opens a text file and converts to list by splitting on new lines
"""
with open(path, "r") as f:
txt = f.read()
return list(filter(None, txt.split("\n"))) | 02feac063537e3434e053556f19cf8bf66b5df68 | 3,610,101 |
def get_db():
"""Fetch db session from the context var"""
session = session_context_var.get()
if session is None:
raise Exception("Missing session")
return session | 1fa3e82c0ed5f3fa7f97d226731cad978815b9b0 | 3,610,102 |
import gzip
import traceback
def upload_file(bucket: str, key: str, data: bytes):
"""
Upload file with gzip
"""
try:
bio = BytesIO()
with gzip.GzipFile(fileobj=bio, mode="wb") as gz:
gz.write(data)
bio.seek(0)
s3.upload_fileobj(bio, bucket, key, ExtraArgs={... | b0c7bc4c039ae32ba6a1492c31fe9f1b0961ca62 | 3,610,103 |
def prepCohortOneYear(data_config, sql_template_config, year_index, mode, db_engine, logger):
"""
Prepare the cohort table for training or validation data
:param data_config: data config from yaml
:param sql_template_config: sql template config from yaml
:param year_index: the index of cohort, label... | 441b3eb7764cbd31d3ce6d4f2d9d1bfe236c8d63 | 3,610,104 |
import os
def get_files_for_project(project_name):
"""Get the set of files for a learn project"""
found_files = set()
project_dir = "{}/{}/".format(LEARN_GUIDE_REPO, project_name)
for file in os.listdir(project_dir):
if "." in file:
cur_extension = file.split(".")[-1]
i... | 558ce6332b246c3b20e0d93df13535067445ef44 | 3,610,105 |
def create_rsa_encrypted_pem(private_key, passphrase):
"""
<Purpose>
Return a string in PEM format (TraditionalOpenSSL), where the private part
of the RSA key is encrypted using the best available encryption for a given
key's backend. This is a curated (by cryptography.io) encryption choice and
the ... | 8c5a3205246ca7ba6c84fc04f726bd9c0a082de4 | 3,610,106 |
def convert_code_list_to_hierarchy(cl, as_list=False):
"""
Receives a list of codes. Codes are sorted lexicographically (to include numbers).
Two types of coding schemes are supported by assuming that trailing zeros can be ignored to match parent -> child
relations. The first is uniformly sized codes (... | e6c8bc4dfb04485e6ba19c46bb17de6a9ffa8e97 | 3,610,107 |
def precisionAtK(result, k):
"""
Precision@K:
Set a rank threshold K
Compute % relevant in top K
Ignores documents ranked lower than K
"""
if k<result.shape[1]:
result = result[:, :k]
score = 0.0
for i in range(len(result)):
score += np.sum(result[i,:]) /... | bc86ae7bb6a3336d649be86e4013430df80e2d27 | 3,610,108 |
import os
def load_model(model_dir):
"""
Loads a graph based tf saved model and also the classes for detection.
Accepts:
model_dir => directory in which model's pb or pbtxt file is placed
"""
return tf.saved_model.load(os.path.join(os.getcwd(),model_dir)) | 2262e16dc548115b4cd58eb332ea0a2646ec8de0 | 3,610,109 |
def obtain_value(entry):
"""Extract value from entry.
The entries could be like: '81.6', ': ', '79.9 e', ': e'.
"""
entry = entry.split(' ', maxsplit=-1)[0] # Discard notes.
if not entry or entry == ':':
return None
return float(entry) | cabb8c9314716fe988102a6226734dd7408be736 | 3,610,110 |
def load_schema(path):
"""Load the card schema from disk.
Parameters
----------
path : path_like
location of the schema yaml file
Returns
-------
`dict`
dictionary schema
"""
with open(path, 'r') as fid:
return yamlr.load(fid) | b0a762f6e0f479cb0aba7de807d0faa620edb1fb | 3,610,111 |
def call_solver(p,quiet):
"""
Calls solver.
:param p: Convex cvxpy_program.
Assumed to be expanded.
:param quiet: Boolean.
"""
# Set printing format for cvxopt sparse matrices
opt.spmatrix_str = opt.printing.spmatrix_str_triplet
# Expand objects defined via parti... | 1b718d18631494d7329e2cbe9edae62923cc661c | 3,610,112 |
def TNaming_Naming_Name(*args):
"""
* Creates a Namimg attribute at label <where> to identify the shape <Selection>. Geometry is Standard_True if we are only interested by the underlying geometry (e.g. setting a constraint). <Context> is used to find neighbours of <S> when required by the naming. If KeepOrientat... | e4678f34ffcd05bb4bfea1909c39e2d14afca849 | 3,610,113 |
def build_call_seq_nb(target_shape, group_lens, call_seq_type=CallSeqType.Default):
"""Build a new call sequence array."""
if call_seq_type == CallSeqType.Reversed:
out = np.full(target_shape[1], 1, dtype=np.int_)
out[np.cumsum(group_lens)[1:] - group_lens[1:] - 1] -= group_lens[1:]
out ... | 6588ce4f579711b9a5dd3ff89b30ead9d7c4bcf6 | 3,610,114 |
from datetime import datetime
def convert_amazon_time_to_local(s):
""" parse a date-time string given by Amazon and outputs the string of the local time"""
return datetime.datetime.strftime(datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ"), '%c') | 70a4bcb833a853c11ea6ecfad5abffd41c47f78b | 3,610,115 |
from datetime import datetime
def statistics_customer_data(request):
"""returns totals for statistics as JSON"""
cutoff_date = now() - datetime.timedelta(days=FREIGHT_STATISTICS_MAX_DAYS)
finished_contracts = Q(contracts_issuer__status=Contract.Status.FINISHED) & Q(
contracts_issuer__date_complet... | be688c1ac7bd6a02894050112382e7704988ce84 | 3,610,116 |
def save_all():
"""
:return: bool success
"""
return azlmbr.atomtools.AtomToolsDocumentSystemRequestBus(bus.Broadcast, "SaveAllDocuments") | e03d1d20942ed229a8a09fd5b07820f3214f5296 | 3,610,117 |
def retweet_or_no(link):
"""
Function to decide whether or not to retweet the link represented by
the bioarxiv article
Parameters
----------
link : link to bioarxiv article
Returns
-------
bool : True, if female or ambiguous
False, if male or unknown
"""
... | 3e35ecc7563cb52ee2dcc56a9935d5627d260584 | 3,610,118 |
def add_tenants(key, tenant_names):
"""Add the given tenant_names if they don't already exist"""
for tenant_name in tenant_names:
if not get_tenant(key, tenant_name):
key.tenants.create(tenant_name=tenant_name, enabled=True)
return True | 24f85c862aa0e7b154040accb5b1e81fffa592e8 | 3,610,119 |
def get_tilting_angles(
struct: Structure,
b_cation: str = 'Pb',
x_anion: str = 'I',
distance_between_b_cations: float = 6.6,
distance_between_b_x: float = 3.8,
algorithm: str='neighbors',
verbose: bool = False,
):
"""
Calculates tilting angles (between B-X-B) for a given structure.... | 2cec69a10c110f7b3a1026b74123dbe3faaaf38d | 3,610,120 |
import os
def create_persistence_distance_file(
orig_path: str,
interpol_path: str,
savefile: bool = True,
distance_type: ["wasserstein", "bottleneck"] = "wasserstein",
filtration: ["alpha", "rips", "witness"] = "rips",
amount_of_files: int = 100
) -> np.ndarray:
"""
Creates from two d... | 1c988eeaa095aacd9ec134f40723ce445a09c34b | 3,610,121 |
def time_str_fixer(timestr):
"""
timestr : str
output
rval : str
if year is 2006, hysplit trajectory output writes year as single digit 6.
This must be turned into 06 to be read properly.
"""
if isinstance(timestr, str):
temp = timestr.split()
year = str(int(temp[0])).zf... | 546ede251de8a8e30831851d645cbb0143fc01db | 3,610,122 |
def plot_corr_map(
sourceTable, sourceVar, targetTables, targetVars,
dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2,
temporalTolerance, latTolerance, lonTolerance, depthTolerance,
method='spearman', exportDataFlag=False, show=True
... | 279632a2c27716e1e895bc11e4ba3f0709749997 | 3,610,123 |
def abs(x):
"""Element-wise absolute value.
# Arguments
x: Tensor or variable.
# Returns
A tensor.
"""
return tf.abs(x) | 01d4d3c2b3c27d3d3ea466a4f30aa601f499d06d | 3,610,124 |
import torch
def psnr_compute(img_batch, ref_batch, batched=False, factor=1.0, clip=False):
"""Standard PSNR."""
if clip:
img_batch = torch.clamp(img_batch, 0, 1)
if batched:
mse = ((img_batch.detach() - ref_batch) ** 2).mean()
if mse > 0 and torch.isfinite(mse):
retur... | e507e4ae1aa3034319421d8e8bf156f67646fec2 | 3,610,125 |
def solve(input: list) -> dict:
"""Solve equation with the quadratic formula\n
**Please input a list: [a, b, c] for an equation like ax² + bx + c**
Examples of keys: ["step 1"], ["step 2"], etc.
Final answer: ["final answer"]"""
return steps | 7e6b08da0b39ff0be2098209a66847513d71f8b5 | 3,610,126 |
def extend_dict(d1, d2):
"""Extends d1 with d2, removing duplicates from d1"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
return dict(**{o: d1[o] for o in d1_keys - intersect_keys}, **d2) | fdbcb83e1f14098d51a6ca77d6b0085dd6ad915c | 3,610,127 |
def gdf_bbox(gdf):
"""Make a bounding box around all geometries in a GeoDataFrame.
Parameters
----------
gdf : :class:`geopandas.GeoDataFrame`
GeoDataFrame with geometries around which to define bounding box
Returns
-------
:class:`geopandas.Polygon`
Bounding box
"""
... | 2319398c88bc1059d6a7fd77aaaea68c30c4c7d8 | 3,610,128 |
def lint(proto: Proto) -> int:
"""Run default linter on given proto.
Returns number of warning reported.
"""
return Linter().lint(proto) | ca2a8cb4433d77edb4be442d848dff06eec84943 | 3,610,129 |
def login():
"""Redirects the login to the real blaulichtSMS Dashboard API to get a real session token.
Otherwise, the application would not be able to login to the blaulichtSMS Einsatzmonitor web application.
:return: An blaulichtSMS Dashboard API session element in JSON
"""
login_data = request.... | 5d5e00d6107ae969a2f4b2e39294d5c14d6c8942 | 3,610,130 |
import re
def RemoveTime(output):
"""Removes all time information from a Google Test program's output."""
return re.sub(r'\(\d+ ms', '(? ms', output) | 1269b502fdf7d46165b0c0dca3dab50cd2e36550 | 3,610,131 |
def IsInclude(line):
"""Return True if line is an include of another file."""
return line.startswith("@include ") | 42278a2d0ea3582111a9cbae26860e1f229398b3 | 3,610,132 |
import heapq
def largest_n_element(m_dict, n):
"""Get the largest n words from the dict
Args:
m_dict (dict): the dict with word as key and the count of word as value
n (int): the number of elements we have to return
Returns:
list_: the n largest pairs in the dict order by value
... | 80723dd91aae6ffa837b1c3794a730331798de55 | 3,610,133 |
def f(x, a):
"""Fitting function"""
return a/np.log2(x) | a4ed6d87db1038ab0666a42d88c4cc13c382a8b6 | 3,610,134 |
def err_ratio(predict, dataset, examples=None, verbose=0):
"""Return the proportion of the examples that are NOT correctly predicted.
verbose - 0: No output; 1: Output wrong; 2 (or greater): Output correct"""
examples = examples or dataset.examples
if len(examples) == 0:
return 0.0
right = 0... | 9159fdb65e47a817381fe08dfdee77f967a47ef5 | 3,610,135 |
def filename_set_error_plot() -> str:
"""Returns filename of set error plot. """
filename = f"set_error_plot{C.postfix_plot_image_format}"
return filename | de2fa6b4afde44582ab0c2521442b4d71ac76092 | 3,610,136 |
def _get_label_from_dv(dv, i):
"""Return label along with the unit of the dependent variable
Args:
dv: DependentVariable object.
i: integer counter.
"""
name, unit = dv.name, dv.unit
name = name if name != "" else str(i)
label = f"{name} / ({unit})" if unit != "" else name
r... | fd18e3d4b5f61bec6febc27b1d7d86b378205a0a | 3,610,137 |
def damaged_now(feat):
"""Pobiera z OSM poprzednią wersję obiektu i sprawdza czy uszkodzenie powstało w wyniku tego changesetu"""
if int(feat["version"]) > 1:
obj_now = get_Object(feat, int(feat["version"]))
obj_before = get_Object(feat,int(feat["version"])-1)
return addr_edited(obj_now,... | 8cb8ebebad2e521d275e3cf535e6027a3dde8ec0 | 3,610,138 |
def get_land_only(dtset, tolerance=0.5):
"""
Returns True where land.
:param dtset:
:return:
"""
if 'LANDFRAC' in dtset:
mask = dtset['LANDFRAC']>tolerance
if 'time' in mask.dims:
return mask.isel(time=0).squeeze()
else: return mask
else:
print('LA... | 2d9ae86edbb43f8dcd0402e263b6d732e7e02c03 | 3,610,139 |
def current_tree() -> GameTree:
"""Return the current tree."""
return _current_tree | cb4b4d73037d5cce5449b1f4082f9d217529fa17 | 3,610,140 |
from typing import Optional
def lin_segment_from_gcode(command: GCmd, current_pose: np.ndarray, ds: float, is_absolute: bool, curr_vel: float,
curr_acc: float, orig_offset: Optional[Coordinate] = None) -> LinearSegment:
"""
Generates a linear trajectory segment in task space from a ... | 8ac545826f82d45b8eddd3f70ff9c0e9313f2577 | 3,610,141 |
from typing import Optional
from datetime import datetime
def get_facebook_posts(
profile_id: int,
*,
start_date: Optional[datetime.date] = None,
) -> pd.DataFrame:
"""Read data for posts on Facebook profile via Quintly API.
Args:
profile_id (int): ID of profile to request data for.
... | dff251047665d1fb58265e8d9a6b5ba986b249bb | 3,610,142 |
def get_seconds(value, scale):
"""Convert time scale dict to seconds
Given a dictionary with keys for scale and value, convert
value into seconds based on scale.
"""
scales = {
'seconds': lambda x: x,
'minutes': lambda x: x * 60,
'hours': lambda x: x * 60 * 60,
'days': lambda x: x * 60 * 60 *... | 92245d0568ea44eb5a906021badcb888535dc5a0 | 3,610,143 |
def selectEvents(hazard_db):
"""
Select all events from _tblEvents_.
:param hazard_db: :class:`HazardDatabase` instance.
:returns: :class:`numpy.recarray` containing the full listing of each
event in the table.
"""
query = "SELECT * FROM tblEvents ORDER BY eventMaxWind ASC"
... | d642212b2e332188c91a11666eb2179c41b05915 | 3,610,144 |
def remove_surrogates(s, errors='replace'):
"""Replace surrogates generated by fsdecode with '?'"""
return s.encode('utf-8', errors).decode('utf-8') | fd5798c40fc2ea8fd5737118ae4d75d6bc49a22f | 3,610,145 |
import requests
import urllib
def fetch_html(page_url):
""" Returns the HTML of the page at page_url """
html = ""
try:
# spoof header for sites like Amazon that make it more dfficult to scrape
req = requests.get(page_url)
html = req.text
except urllib.error.URLError as e:
... | 008cf43b3d365ecc5f4a9d6f16a3544698fde534 | 3,610,146 |
def np_mat_to_rot6d(np_mat):
""" Get 6D rotation representation for rotation matrix.
Implementation base on
https://arxiv.org/abs/1812.07035
[Inputs]
flattened rotation matrix (last dimension is 9)
[Returns]
6D rotation representation (last dimension is 6)... | 3265eabe7d644ec405e68b3a3bad31a4ca03a384 | 3,610,147 |
def getHandler(database):
"""
a function instantiating and returning this plugin
"""
return SpamReports(database, 'feedback', public_endpoint_extensions=['insert']) | 76e1c890b4d3900e9d00271b2c76a4664f408913 | 3,610,148 |
def createParameterWidgetRemote(instruments, doexec=True):
""" Create a parameter widget in a remote process.
Note: this can only be used if all the Instruments are remote instruments.
"""
p = mp.Process(target=createParameterWidget, args=(instruments,))
p.start()
return p | 5460ec67fa065c39398f5e5fdcbf8e9e647c9e9d | 3,610,149 |
from typing import Tuple
def generate_query_by_keeping_granularity(
query: SQLQuery,
group_by: list,
current_step_name: str,
query_to_complete: str = "",
aggregated_cols=None,
group_by_except_target_columns=None,
) -> Tuple[SQLQuery, str, list]:
"""
On some steps, when we do the Group ... | 6498e27f5a81a1835461aa811a96e54cfc19a180 | 3,610,150 |
import time
def get_access_token(request):
"""Get the access token, or fetch a new one if it is possible, otherwise return None."""
if not get_setting("STORE_TOKENS", False):
return None
prefix = get_setting("SESSION_KEY_PREFIX", DEFAULT_SESSION_KEY_PREFIX)
access_token = request.session.get(... | 1103935c2d9b5b10d50881def839db5827353cb3 | 3,610,151 |
def is_some_float(arg, allow_none=False):
"""
>>> is_some_float(3)
False
>>> is_some_float(3.5)
True
>>> import numpy as np
>>> is_some_float(np.float64(3.5))
True
>>> is_some_float(np.double(3.5))
True
>>> is_some_float(None)
False
>>> is_some_float(None, allow_none=... | d9f18e66944d09408c0ea503e6106f25b1d6b151 | 3,610,152 |
def deletequiz(quizID):
"""Renders the create quiz page for educators."""
if not current_user.check_educator():
return render_template('errors/error403.html'), 403
quiz = validate_quiz_link(current_user, quizID)
delQuizForm = DeleteForm(prefix='quiz')
delQnForm = DeleteForm(prefix='qn')
... | e4b795a17b070a3fa955d816b68f288edc41b16a | 3,610,153 |
import requests
def get_uframe_calibration_events_by_uid(id, uid):
""" Get list of calibration events from uframe for a specific sensor asset uid.
Function also outfitted for using asset id instead of uid. Both required for error processing at this time.
On status_code(s):
200 Success, return... | 2bd139ed5f39d357da88d5e1a87a2e67a6c9cb45 | 3,610,154 |
import numpy
import types
def freqz(b, a=1, worN=None, whole=0, plot=None):
"""
Compute the frequency response of a digital filter.
Given the numerator ``b`` and denominator ``a`` of a digital filter compute
its frequency response::
jw -jw -jmw
jw B(e... | ec5a1b5235398ea18b3ced83e26bdaa66643bb56 | 3,610,155 |
def split_amp_phase(array):
"""
takes a complex array and returns the amplitude and the phase
"""
amp = np.abs(array)
phase = np.angle(array)
return amp, phase | 4b189fbeb89d3ffa4e541ce287b87188e24c9f23 | 3,610,156 |
import re
def get_project(line):
""" Returns project of reactor line. """
start = re.search(r' ', line).end()
end = re.search(r' ', line[start:]).start() + start
return line[start:end] | 0db541ca1215c11f6c1a4988a0eeec7d75ab7725 | 3,610,157 |
def points_2_inches(points) -> float:
"""
Convert points to inches
"""
return points / 72 | 8744659807046c892f2d1f36c3dc47a44417ca96 | 3,610,158 |
def make_optional_parser(arg: t.Any) -> comb.Parser:
"""Return parser for t.Optional[arg]."""
return comb.Or(infer_parser(arg), infer_parser(type(None))) | cb282365471bb69ae333c11aa322bd1c5928747d | 3,610,159 |
def clientes():
"""
Rota para aba de clientes. Mostra na tela uma representação do csv de clientes
Não é necessário modificar nada nessa função
"""
df = pd.read_csv('data/clientes.csv', dtype=object, sep=';')
df = df.replace(np.nan, '', regex=True)
return render_template('clientes.html', df=... | dbea1a697f97f87448ec542ba6c684b978027a19 | 3,610,160 |
def seq_metrics_path(build: int, data_type: str, data_source: str, version: int) -> str:
"""
Path to metadata file associated with samples in the callset for seqr sample QC.
"""
return f"{sample_qc_folder(build, data_type, data_source, version)}/resources/callset_seq_metrics.txt" | 3186356e5a02c8a50fefecd1bdd7778b7e2da37e | 3,610,161 |
import sqlite3
def from_therion_sql(basename):
"""
Creates the Kgraph from on SQL file exported from a Therion survey file.
Parameters
----------
basename : string
The base name used for the input files.
The input file is named using the following convention:
- basename.... | 91c10b8f9190b9f102e1e50670339436bf02f466 | 3,610,162 |
def view_playlist(request, slug):
"""View a playlist"""
playlist = get_playlist_from_slug(slug)
if not playlist.public and (
not request.user.is_authenticated
or playlist.owner != request.user):
return redirect("notifpy:abstract")
playlist.owned = playlist.owner == reques... | 81f436bd7cd62b446cafab45f813e0d049f1dcdb | 3,610,163 |
def numOfDigits(number, base = 10):
"""
given a list of numbers, return the number of digits that number has
Example:
[567] -> [3]
[5, 77, 435] -> [1, 2, 3]
Parameters:
number: an nDim list of numbers to process
Returns:
an nDim list of values
"""
# natural log (number) / log (base) = l... | d642986d6d91801ea0d2698faa56880e94b085c9 | 3,610,164 |
import _io
def create_validator_delegation_withdrawal(
params: DeployParameters,
amount: int,
public_key_of_delegator: PublicKey,
public_key_of_validator: PublicKey,
path_to_wasm: str
) -> Deploy:
"""Returns a standard withdraw delegation deploy.
:param params: Standard parameters use... | e57742b87c848ee6850e785fe4957009fd9ae9a1 | 3,610,165 |
def is_secretary(user):
"""
Check whether the current user is in the 'Secretary' group.
"""
return Group.objects.get(name=settings.GROUP_SECRETARY) in user.groups.all() | ad738c5bc827cbd6f7714b6280a6be8d79ef886c | 3,610,166 |
def parse_dot_data(dotdata):
"""Wrapper for pydot.graph_from_dot_data
Redirects error messages to the log.
"""
parser = dotparsing.DotDataParser()
try:
graph = parser.parse_dot_data(dotdata)
except dotparsing.ParseException:
raise
finally:
del parser
log.debug('P... | 1e2fcaf6db159e60d29b339afcdc8dcc11dd037f | 3,610,167 |
async def async_setup(hass: HomeAssistant, global_config: dict):
"""Set up the Climate Scheduler component."""
config = global_config.get(DOMAIN)
if config is None:
return
climate_scheduler = ClimateScheduler(hass, config)
hass.data[DATA_CLIMATE_SCHEDULER] = climate_scheduler
return T... | d688cb1c3ba0eee998b66fbb4a7287ec3ec43b73 | 3,610,168 |
def type_to_formatting_tag(type_):
"""Return the HTML tag corresponding to the given formatting type."""
tag = FORMATTING_TYPE_TAG_MAP.get(type_, type_)
return html_safe_string(tag) | 3e61b343bb377333df066328dd10001985cea6ed | 3,610,169 |
import os
import wave
def estimate_recording(path):
"""
Args:
Take the path to the folders
Return:
Number of voice recording and total voice recording made.
"""
waves = []
for path , _ , files in os.walk(path):
for record in files:
if record.endswith... | 398a95a6958cb944dca69987dd1da7b022e5fb26 | 3,610,170 |
def points_against_by_week(position, team):
"""
INPUT: String
RETURN: Series
Finds sum of points for players of a position that
played against a team by week.
"""
# get points against team
df = position_against_team(position, team)
# get total points against per week
... | bbecc1ebd9d1c215136decd37ebee1c8b0891942 | 3,610,171 |
import importlib
def my_import(class_name):
"""Return a python class given a class name.
Usage example::
Report = my_import('myclass.models.Report')
model_instance = Report()
model_instance.name = 'Test'
model_instance.save()
:param str class_name: Class name
:retur... | 214bf9efed78a9e2dcc9897a28f389ef40918063 | 3,610,172 |
def process_regular_filter(_input: str):
""" Run a regular spatial search filter
Args:
_input (str): The input
Returns:
results (dict): Contains 'looking_for' (list) and 'in' (list)
"""
searcher = Searcher()
search_text = _input.split(",")
results = searcher.search_location... | ca6fce8113096c6062fb02857734b2d95fe4c0aa | 3,610,173 |
def locally_subscribes(*args):
"""
The @subscribes decorator registers a function as being one which clients
may subscribe to via websocket. This decorator may be used to register a
function which shall be called locally anytime a notify occurs, e.g.
@locally_subscribes('example.channel')
def ... | 800a0df0ca83db06978f6b2685ac775ab2c0e33d | 3,610,174 |
from typing import Tuple
def _calculate_number_of_temperatures(
pvt_collector: pvt.PVT,
) -> Tuple[int, int, int, int, int, int]:
"""
Calculates, based off the PVT collector, the number of temperatures in each layer.
:param pvt_collector:
The PVT collector being modelled.
:return:
... | fd081138a67321b893b3383494529e877ef29105 | 3,610,175 |
from datetime import datetime
def encode_cf_variable(var):
"""Converts an XArray into an XArray suitable for saving as a netCDF
variable
"""
dimensions = var.dimensions
data = var.values
attributes = var.attrs.copy()
encoding = var.encoding.copy()
if (np.issubdtype(data.dtype, np.date... | e3c03a52a6d73de3ba2ee6f5154b06c7ad263aa4 | 3,610,176 |
def get_path_converter(request, task):
"""returns a partial function that converts the given path to another path
that is visible to other OSes.
"""
user_os = get_user_os(request)
repo = task.project.repository
if user_os == 'windows':
return repo.to_windows_path
elif user_os == 'l... | e159f0d770d661d58939e6c66fc516eeecd8be3c | 3,610,177 |
def layout_split(layout, factor=0.0, align=False):
"""Intermediate method for pre and post blender 2.8 split UI function"""
if not hasattr(bpy.app, "version") or bpy.app.version < (2, 80):
return layout.split(percentage=factor, align=align)
return layout.split(factor=factor, align=align) | ff88197ea1b21f047f97f94bfd04f8a0f35c87a3 | 3,610,178 |
def getSubmechanismRoots(selection_only=False):
"""
Args:
selection_only: (Default value = False)
Returns:
"""
if selection_only:
objs = bpy.context.selected_objects
else:
objs = bpy.context.scene.objects
return [obj for obj in objs if 'submechanism/name' in obj] | ce49fea0180c9d46317c4c7b1081f8b5b6da87bc | 3,610,179 |
def eda_column_subset(df, list_of_columns):
"""
Generates descriptive statistics, pair plot, and correlation matrix for a subset of columns.
Accepts: dataframe, list of columns
Returns: None, generates descriptive stats, pairplot, and correlation heat map
"""
plt.figure(figsize=(40, 40))
... | 6baf12c162c85902e57000c9134e4b56abfa9bfe | 3,610,180 |
def _build_time_predicates(
from_date=None,
to_date=None,
from_included=True,
to_included=False,
):
"""
Build time range predicates for 'where' clause
"""
must = []
if from_date:
must.append("time {} {}".format(
">=" if from_included else ">",
make_t... | 34afc28dc8758cb9ddf315dceec70adb049f616a | 3,610,181 |
def init_bk(P,b,c):
"""
initializes the coefficient of Q(x) after the division of P
Needed in Newton-Raphson method
"""
n = len(P)
i = n-3
solution = np.zeros([1,n])
solution[0,n-1] = P[0]
solution[0,n-2] = P[1] + b * solution[0,n-1]
while i > -1:
solution[0,i] = P[n-i-1]... | 5e1ab5f74009c19e9ba5ae91891c96482dfee5a8 | 3,610,182 |
import sys
import subprocess
import os
def spawn_command(*command):
"""
Run the given command, without waiting for completion. Return the Popen
object (which provides .send_signal, .kill(), .wait(), etc), or None
if the command couldn't be run at all.
The command is created with its own process ... | 6e0757379eee2ccb79a2b104f45c40e6705719f2 | 3,610,183 |
from operator import index
def app(environ, start_response):
"""Application object"""
if(environ.get("REQUEST_METHOD") == "GET"):
if(environ.get("PATH_INFO") == "/"):
status, data, headers = index()
elif(environ.get("PATH_INFO") == "/joke"):
status, data, headers = joke... | a4c8a997ced88477a7b2dc2e87d830bc701cab52 | 3,610,184 |
import statistics
def evaluation_diversity(df_source, df_target, baseline=False, max_k=30):
"""
Source: Mariani, G., Scheidegger, F., Istrate, R., Bekas, C., & Malossi, C. (2018).
BAGAN: Data Augmentation with Balancing GAN, 1–9. Retrieved from http://arxiv.org/abs/1803.09655
For df_source rando... | 7c8d8ca064685b9e6368b89043a7158943607514 | 3,610,185 |
def print_lustre_versions(log, lustre_versions, status=False,
print_table=True, field_string=None):
"""
Print table of BarreleAgent.
"""
# pylint: disable=too-many-branches,too-many-locals,too-many-statements
if not print_table and len(lustre_versions) > 1:
log.cl_e... | 9feac6f948c39e739a58728d6b54ac8219e931b0 | 3,610,186 |
def rename_motifs(motifs, stats=None):
"""Rename motifs to GimmeMotifs_1..GimmeMotifs_N.
If stats object is passed, stats will be copied."""
final_motifs = []
for i, motif in enumerate(motifs):
old = str(motif)
motif.id = "GimmeMotifs_{}".format(i + 1)
final_motifs.append(motif)... | bcc7ea61f7791b3c6f9d5b26cde1f8a7ac79bb9b | 3,610,187 |
def _get_region(zone):
"""
Get region name from zone
:param zone: str, zone
:return:
"""
return zone if 'gov' in zone else zone[:-1] | aa272e6e6e00b444f29ffbe821b2d255196d55f6 | 3,610,188 |
def conv_bright_ha_to_lib(brightness) -> int:
"""Convert HA brightness scale 0-255 to library scale 0-16."""
if brightness == 255: # this will end up as 16 which is max
brightness = 256
return int(brightness / 16) | 45782f53a41605b20230c71c7e2ccf713d10c6dc | 3,610,189 |
def findIntersection3(p1, p2, p3, p4):
"""
p1, p2 on the same line
p3, p4 on the another line
"""
px = ((p1[0]*p2[1] - p1[1]*p2[0]) * (p3[0]-p4[0]) - (p1[0]-p2[0]) * (p3[0]*p4[1] - p3[1]*p4[0])) / ((p1[0]-p2[0]) * (p3[1]-p4[1]) - (p1[1]-p2[1]) * (p3[0]-p4[0]))
py = ((p1[0]*p2[1] - p1[1]*p2[0]) *... | 6605f2756d1812c42b6793468366071f4ed4abb8 | 3,610,190 |
def vit_relpos_small_patch16_rpn_224(pretrained=False, **kwargs):
""" ViT-Base (ViT-B/16) w/ relative log-coord position and residual post-norm, no class token
"""
model_kwargs = dict(
patch_size=16, embed_dim=384, depth=12, num_heads=6, qkv_bias=False, block_fn=ResPostRelPosBlock, **kwargs)
mod... | fedee571e2d21c6e0fc7ada1cf577fe05f20dee4 | 3,610,191 |
def secp256k1_multiply(n):
"""Performs elliptic curve point multiplication to compute n * G.
See here:
http://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication
"""
return n * G | cfebeeed560c9280289012fdbc13325796ab80fd | 3,610,192 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up number entities dynamically through discovery."""
def _constructor(device_state: DeviceState) -> list[Entity]:
return [
PeriodicVentingTime(... | a3027cb74ee7b058bd9324dd41a666a57329bddb | 3,610,193 |
def load_amphur(request):
""" Amphur Dependent/Chained Dropdown List """
province_id = request.GET.get('province')
amphur_list = Amphur.objects.filter(
province_id=province_id).order_by('name')
return render(request, 'app_sme12/form_partial/amphur_dropdown_list_options.html', {'amphur_list': amp... | f46dc6a88f0ca083fc0307859269003145ded31f | 3,610,194 |
def _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer):
"""Clone a functional `Model` instance.
Model cloning is similar to calling a model on new inputs,
except that it creates new layers (and thus new weights) instead
of sharing the weights of the existing layers.
Input layers are a... | e23eb5ee05bfb5850a7ed916287422f02b84a667 | 3,610,195 |
import base64
def connectMSExchange(server):
"""
Creates a connection for the inputted server to a Microsoft Exchange server.
:param server | <smtplib.SMTP>
:usage |>>> import smtplib
|>>> import projex.notify
|>>> smtp = smtplib.SMTP('mail.server.com')
... | 604f025185757ce2ce29d1dddb673ce8f65989de | 3,610,196 |
def cohort_selection(definition, db_client):
""" Select the persons id that fall into the citeria provided
for thr cohort.
"""
sql_condition = []
for component in definition:
value = VALUE in component
if component[TABLE].lower() == OBSERVATION_TABLE:
condition = ""
... | 002c9596dfaeb8cb8eee4394f805d6c54a309ff5 | 3,610,197 |
def test_create_test_incident_command_happy(mocker, incidents, attachment, expected):
"""
Given: a file with list-format of valid incidents with labels
a file with single valid incident without labels
a list of valid incidents with labels with attachment,
an empty file witho... | d531ce72994a19260d57d3c909e091b38974ee16 | 3,610,198 |
def _conv_bn_relu(
filters,
kernel_size,
strides=(1, 1),
padding="same",
kernel_regularizer=kernel_regularizer,
):
"""Helper to build a conv -> BN -> relu block
"""
def f(input):
conv = tf.layers.conv2d(
input,
filters=filters,
kernel_size=kerne... | be6832dafdf99f0c0e5400fe239f27dcb2db44d0 | 3,610,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.