content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_selector(info, mode="advanced"):
"""
The selector that decides the scope of the dashboard. It MUST have the keywords
?work and ?author.
You can override everything here by adapting the query on WDQS:
https://w.wiki/3Cmd
Args:
info: either a dict containing complex information f... | c499a2b4e29a1afc91e6d40563a71ad5e71b7724 | 3,645,200 |
def get_table_names(self, connection, schema=None, **kw):
"""
Get table names
Args:
connection ():
schema ():
**kw:
Returns:
"""
return self._get_table_or_view_names(
["r", "e"], connection, schema, **kw
) | e66ae9eb284e10785c7172ab36c79b25a48dce47 | 3,645,201 |
def get_general(prefix, generator, pars, **kwargs):
""" A general getter function that either gets the asked-for data
from a file or generates it with the given generator function. """
pars = get_pars(pars, **kwargs)
id_pars, pars = get_id_pars_and_set_default_pars(pars)
try:
result = read_... | a27e25e0ec992f8faa13b167dafd38edd6eb6a1d | 3,645,202 |
def gen_case(test):
"""Generates an OK test case for a test
Args:
test (``Test``): OK test for this test case
Returns:
``dict``: the OK test case
"""
code_lines = str_to_doctest(test.input.split('\n'), [])
for i in range(len(code_lines) - 1):
if code_lines[i+1].sta... | 586a5436442172d43a022e33185bd84c302fdb9c | 3,645,203 |
def get_user_list_view(request):
"""
render user admin view
Arguments:
request {object} -- wsgi http request object
Returns:
html -- render html template
"""
if request.user.has_perm('auth.view_user'):
user_list = User.objects.all()
temp_name = 'admin/li... | f0ee280ac60a48f61f5da0d7d63b050e16ea6696 | 3,645,204 |
def to_odds(p):
"""
Converts a probability to odds
"""
with np.errstate(divide='ignore'):
return p / (1 - p) | b468b75ad736ca67e1fb39fd231bc185d851fbdf | 3,645,205 |
def step_euler(last, dt, drift, volatility, noise):
"""Approximate SDE in one time step with Euler scheme"""
return last + drift * dt + np.dot(volatility, noise) | e9f58425f696316679730397168c7965b3faadd5 | 3,645,206 |
def KK_RC66_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen ([email protected] / [email protected])
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | eb64f86bc0a8a7ff0d88a1246a754563a955c61f | 3,645,207 |
from typing import List
def similar_in_manner(manner_1: UnmarkableManner) -> List[Manner]:
"""
If the value is a wildcard value, return
all possible manner of articualtion values, otherwise
return the single corresponding manner of articulation value.
"""
if isinstance(manner_1, MarkedManner):
return manner_1... | fea0c78c93a5f80e4f2bba6eac7f628106fba796 | 3,645,208 |
import re
def wikify(value):
"""Converts value to wikipedia "style" of URLS, removes non-word characters
and converts spaces to hyphens and leaves case of value.
"""
value = re.sub(r'[^\w\s-]', '', value).strip()
return re.sub(r'[-\s]+', '_', value) | dc4504ea6eb7905b5e18a1d1f473a4f337697b26 | 3,645,209 |
def build_model(name, num_classes, loss='softmax', pretrained=True,
use_gpu=True, dropout_prob=0.0, feature_dim=512, fpn=True, fpn_dim=256,
gap_as_conv=False, input_size=(256, 128), IN_first=False):
"""A function wrapper for building a model.
"""
avai_models = list(__model_fa... | 1278e5c30ebdb73e011b0630de3738936e87dc93 | 3,645,210 |
def policy_absent(name):
"""
Ensure that the named policy is not present
:param name: The name of the policy to be deleted
:returns: The result of the state execution
:rtype: dict
"""
current_policy = __salt__['mdl_vault.get_policy'](name)
ret = {'name': name,
'comment': '',
... | 6f1498f07a8e14f2e7668d7d5cc8d68128cb6004 | 3,645,211 |
def _tolist(arg):
"""
Assure that *arg* is a list, e.g. if string or None are given.
Parameters
----------
arg :
Argument to make list
Returns
-------
list
list(arg)
Examples
--------
>>> _tolist('string')
['string']
>>> _tolist([1,2,3])
[1, 2, ... | e4293991eeb6d15470511281680af44353232c37 | 3,645,212 |
def calc_Qhs_sys(bpr, tsd):
"""
it calculates final loads
"""
# GET SYSTEMS EFFICIENCIES
# GET SYSTEMS EFFICIENCIES
energy_source = bpr.supply['source_hs']
scale_technology = bpr.supply['scale_hs']
efficiency_average_year = bpr.supply['eff_hs']
if scale_technology == "BUILDING":
... | 6016e2061b441248606b5a3ea95930d38b678525 | 3,645,213 |
import socket
from time import time as now
def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exce... | f8089ed335c783140ab4b334c44c534ee5c48121 | 3,645,214 |
import re
def latex_nucleus(nucleus):
"""Creates a isotope symbol string for processing by LaTeX.
Parameters
----------
nucleus : str
Of the form `'<mass><sym>'`, where `'<mass>'` is the nuceleus'
mass number and `'<sym>'` is its chemical symbol. I.e. for
lead-207, `nucleus` w... | e2a2c04a63284cdd8f06fdd556306149e7092703 | 3,645,215 |
def ConvertToFloat(line, colnam_list):
"""
Convert some columns (in colnam_list) to float, and round by 3 decimal.
:param line: a dictionary from DictReader.
:param colnam_list: float columns
:return: a new dictionary
"""
for name in colnam_list:
line[name] = round(float(line[name])... | e95fd6cfa9bb57060fdd835eea139fd9c67bc211 | 3,645,216 |
def rnn_step(x, prev_h, Wx, Wh, b):
"""
Run the forward pass for a single timestep of a vanilla RNN that uses a tanh
activation function.
The input data has dimension D, the hidden state has dimension H, and we use
a minibatch size of N.
Inputs:
- x: Input data for this timestep, of shape ... | 78fef10a4c23b7a33a60829e1ad02a2e0381b834 | 3,645,217 |
from typing import List
import json
def transform_application_assigned_users(json_app_data: str) -> List[str]:
"""
Transform application users data for graph consumption
:param json_app_data: raw json application data
:return: individual user id
"""
users: List[str] = []
app_data = json.l... | 625c8f662b364bb3fe63bb26b06eaca57ae8be79 | 3,645,218 |
def testapp(app):
"""Create Webtest app."""
return TestApp(app) | 68a46e993d75fc44de5a9063b409e89647a2738b | 3,645,219 |
def to_y_channel(img):
"""Change to Y channel of YCbCr.
Args:
img (ndarray): Images with range [0, 255].
Returns:
(ndarray): Images with range [0, 255] (float type) without round.
"""
img = img.astype(np.float32) / 255.
if img.ndim == 3 and img.shape[2] == 3:
img = bgr2... | 64873fabbe6cd12db8c9bc96e4e93f7181c7742d | 3,645,220 |
def get_user_signatures(user_id):
"""
Given a user ID, returns the user's signatures.
:param user_id: The user's ID.
:type user_id: string
:return: list of signature data for this user.
:rtype: [dict]
"""
user = get_user_instance()
try:
user.load(user_id)
except DoesNotE... | 8c099f84c9a9f383b56019f985f1be63e315503a | 3,645,221 |
import json
def post_vehicle_action():
""" Add vehicle
:return:
"""
output = JsonOutput()
try:
if not request.is_json:
raise TypeError('Payload is not json')
payload = request.json
usecases.SetVehicleUsecase(db=db, vehicle=payload).execute()
output.add(s... | a24b4e326fe12c7d2a7054ca4b89245924a96d60 | 3,645,222 |
def get_day_suffix(day):
"""
Returns the suffix of the day, such as in 1st, 2nd, ...
"""
if day in (1, 21, 31):
return 'st'
elif day in (2, 12, 22):
return 'nd'
elif day in (3, 23):
return 'rd'
else:
return 'th' | 7d9277303357de5405b3f6894cda24726d60ad47 | 3,645,223 |
def retain_images(image_dir,xml_file, annotation=''):
"""Deprecated"""
image_in_boxes_dict=return_image_in_boxes_dict(image_dir,xml_file, annotation)
return [img for img in image_in_boxes_dict if image_in_boxes_dict[img]] | 54efc8c8b3c31f8466a0044c2e679cbf5a5545ff | 3,645,224 |
from typing import List
from typing import Tuple
from typing import Dict
from pathlib import Path
from typing import cast
def compute_owa(
metrics: List[Tuple[float, float]],
datasets: Dict[K, DatasetSplit],
metadata: List[MetaData],
) -> float:
"""
Computes the OWA metric from the M4 competition,... | 2f4d19eecf85a9be720fb705eafe83c2ac1bced1 | 3,645,225 |
def parse(cell, config):
"""Extract connection info and result variable from SQL
Please don't add any more syntax requiring
special parsing.
Instead, add @arguments to SqlMagic.execute.
We're grandfathering the
connection string and `<<` operator in.
"""
result = {"connect... | 4711b5f873281db520ff4d91646412ca08f7cbb7 | 3,645,226 |
import requests
import json
def createResource(url, user, pWd, resourceName, resourceJson):
"""
create a new resource based on the provided JSON
returns rc=200 (valid) & other rc's from the put
resourceDef (json)
"""
# create a new resource
apiURL = url + "/access/1/catalog/resou... | 71257041a7bf098edd0668de6026539e554baff4 | 3,645,227 |
import string
def generate_invalid_sequence():
"""Generates an invalid sequence of length 10"""
return ''.join(np.random.choice(list(string.ascii_uppercase + string.digits), size=10)) | 33639bc0c97710c411b2bfd0033ed15200c8edff | 3,645,228 |
from input_surface import circle
def transform_bcs_profile(T, axis, Nc):
""" Translates the profile to body cs and then transforms it for rotation.
"""
profile = circle(Nc, radius = 1, flag = 0)
Pb_new = np.zeros((Nc, 3), dtype = float)
ind_p = np.arange(0, 3*Nc, step = 3, dtype = int)
p... | c3cacd480cba73c7a3ce1b6f5e90582fc93e2a4b | 3,645,229 |
def count_configuration(config, root=True, num_samples_per_dist=1):
"""Recursively count configuration."""
count = 1
if isinstance(config, dict):
for _, v in sorted(config.items()):
count *= count_configuration(
v, root=False, num_samples_per_dist=num_samples_per_dist)
elif callable(config):... | f7709bfd18744355f5739c4d0e4b52b952f6c8c7 | 3,645,230 |
def transition(state_table):
"""Decorator used to set up methods which cause transitions between states.
The decorator is applied to methods of the context (state machine) class.
Invoking the method may cause a transition to another state. To define
what the transitions are, the nextStates method of t... | 675a6afe6abd068027892be561c2d032d13be52a | 3,645,231 |
from typing import Union
def isfinite(x: Union[ivy.Array, ivy.NativeArray], f: ivy.Framework = None)\
-> Union[ivy.Array, ivy.NativeArray]:
"""
Tests each element x_i of the input array x to determine if finite (i.e., not NaN and not equal to positive
or negative infinity).
:param x: Input ar... | 7326343319dae8bb8681a9612caaaddfc947f8c1 | 3,645,232 |
from pathlib import Path
from typing import Optional
def form_overwrite_file(
PATH: Path, QUESTION: Optional[str] = None, DEFAULT_NO: bool = True
) -> bool:
"""Yes/no form to ask whether file should be overwritten if already existing."""
if QUESTION is None:
QUESTION = "Overwrite {PATH}?"
sav... | 51de7eb948af9e0b6cd354e8e72815e16955200c | 3,645,233 |
def dist(integer):
"""
Return the distance from center.
"""
if integer == 1:
return 0
c = which_layer(integer)
rows = layer_rows(c)
l = len(rows[0])
mid = (l / 2) - 1
for r in rows:
if integer in r:
list_pos = r.index(integer)
return c + abs(mid - list_pos) - 1 | 8fd27978058ac0d038836bd88dc2c7c590fec6b7 | 3,645,234 |
from datetime import datetime
def get_market_fundamental_by_ticker(date: str, market: str="KOSPI", prev=False) -> DataFrame:
"""특정 일자의 전종목 PER/PBR/배당수익률 조회
Args:
date (str ): 조회 일자 (YYMMDD)
market (str, optional): 조회 시장 (KOSPI/KOSDAQ/KONEX/ALL)
prev (bool, optional): 조회 일... | ac13ef09867b69f354b75f1e1bd98f46baf995fc | 3,645,235 |
def get_all(request):
""" Gets all tags in the db with counts of use """
tags = []
for tag in Tag.objects.all():
tag_data = {
'name': tag.name,
'count': tag.facebookimage_set.distinct().count()
}
if tag_data['count'] > 0:
tags.append(tag_... | bee0d6afd4ea8afeda0001d090cf0d9156249cce | 3,645,236 |
def quadratic_crop(x, bbox, alpha=1.0):
"""bbox is xmin, ymin, xmax, ymax"""
im_h, im_w = x.shape[:2]
bbox = np.array(bbox, dtype=np.float32)
bbox = np.clip(bbox, 0, max(im_h, im_w))
center = 0.5 * (bbox[0] + bbox[2]), 0.5 * (bbox[1] + bbox[3])
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
... | 53e9acf58cf743a89a4bfaafb9211abbbb9d57ec | 3,645,237 |
def cdlbreakaway(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of breakaway for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): T... | c8bbc5adbbf742daabe39feaaa2dec01790297fe | 3,645,238 |
def depends_on(*args):
"""Caches a `Model` parameter based on its dependencies.
Example
-------
>>> @property
>>> @depends_on('x', 'y')
>>> def param(self):
>>> return self.x * self.y
Parameters
----------
args : list of str
List of parameters this parameter... | 09cdb0ad7601a953eafd01e3e19c0bdfb10dccb2 | 3,645,239 |
def l96(x, t, f):
""""This describes the derivative for the non-linear Lorenz 96 Model of arbitrary dimension n.
This will take the state vector x and return the equation for dxdt"""
# shift minus and plus indices
x_m_2 = np.concatenate([x[-2:], x[:-2]])
x_m_1 = np.concatenate([x[-1:], x[:-1]])
... | 0db03ed3a8923d18b50095852d17f9213e9f1f0f | 3,645,240 |
def translation(im0, im1, filter_pcorr=0, odds=1, constraints=None,
reports=None):
"""
Return translation vector to register images.
It tells how to translate the im1 to get im0.
Args:
im0 (2D numpy array): The first (template) image
im1 (2D numpy array): The second (sub... | 40e15b6154569d6bb13c7a38d595b603e9421d04 | 3,645,241 |
def CalculateConjointTriad(proteinsequence):
"""
Calculate the conjoint triad features from protein sequence.
Useage:
res = CalculateConjointTriad(protein)
Input: protein is a pure protein sequence.
Output is a dict form containing all 343 conjoint triad features.
"""
res = {}
pr... | 1ed73c1aa78c5360715eb71c9d56594d028cf6d3 | 3,645,242 |
from typing import Type
from typing import Dict
from typing import Optional
from typing import List
import argparse
from typing import Union
from typing import get_type_hints
import os
def _create(
*,
cls: Type[THparams],
data: Dict[str, JSON],
parsed_args: Dict[str, str],
cli_args: Optional[List[... | db6a407a1e9b0fdc943bf7851b00f28fcd7aed47 | 3,645,243 |
def extract_url(url):
"""Creates a short version of the URL to work with. Also returns None if its not a valid adress.
Args:
url (str): The long version of the URL to shorten
Returns:
str: The short version of the URL
"""
if url.find("www.amazon.de") != -1:
index = ... | 85421799b601c89aa54fdce6e98c003ea80111eb | 3,645,244 |
import unicodedata
from typing import List
def match_name(own: str, other: str) -> bool:
"""
compares 2 medic names (respects missing middle names, or abbrev. name parts)
Args:
own: the first name
other: the last name
Returns: True if both names match
"""
# the simplest case,... | 6987deb8695f823cd5e1e0948bd2a21dc33759bd | 3,645,245 |
def price_setting():
""" Sets prices """
purchasing_price = float(input("enter purchasing price: "))
new_supplier = str(input("First time user(Y/N)?: ")).lower()
if new_supplier not in ['n', 'y']:
return True, {"errorMsg": f"{new_supplier} not a valid response"}, None
if new_supplier == 'y':... | 5d6b98b62ff7b6c8c3cc4278c3a4f2eb7c5f0f27 | 3,645,246 |
def d4_grid():
"""Test functionality of routing when D4 is specified.
The elevation field in this test looks like::
1 2 3 4 5 6 7
1 2 3 0 5 0 7
1 2 3 4 0 0 7
1 2 3 0 5 6 7
1 2 0 0 0 6 7
1 2 3 0 5 6 7
1 ... | ed285c91cc4cda270a469a0271d1b935f1043d32 | 3,645,247 |
import inspect
def pass_complex_ins(mqc):
"""
The number of PASS complex insertions.
Source: count_variants.py (bcftools view)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_npm_count_variants"].values()))
v = d["pass_complex_ins"]
v = i... | df7177b126829dca4a71252e797a2cb7d7d24ee3 | 3,645,248 |
def get_jwt():
"""
Get authorization token and validate its signature against the public key
from /.well-known/jwks endpoint
"""
expected_errors = {
KeyError: WRONG_PAYLOAD_STRUCTURE,
AssertionError: JWK_HOST_MISSING,
InvalidSignatureError: WRONG_KEY,
DecodeError: WR... | 92b757e3fa9774ac7e93fc0f89c446efefc47b33 | 3,645,249 |
import os
def devlocation()->str:
"""
:return: 'local' or 'github
"""
return os.getenv('DEVLOCATION') or 'local' | f4ab9af75258f6c72786a4cfbbe2d7a7661873c0 | 3,645,250 |
def convert_categorical(df, col_old, conversion, col_new=None):
"""Convet categories"""
if col_new is None:
col_new = col_old
orig_values = df[col_old].values
good_rows = np.isin(orig_values, list(conversion))
df = df.iloc[good_rows]
orig_values = df[col_old].values
cat_values = np.z... | db07bb08f302edf615cab96b04b263f66fa9b8b1 | 3,645,251 |
def _get_pipeline_configs(force=False):
"""
Connects to Shotgun and retrieves information about all projects
and all pipeline configurations in Shotgun. Adds this to the disk cache.
If a cache already exists, this is used instead of talking to Shotgun.
To force a re-cache, set the force flag to Tru... | 3c504606e5a751e0015abbdcf74a3e2513d4d280 | 3,645,252 |
import sys
import argparse
def parse_cmdline(argv):
"""
Returns the parsed argument list and return code.
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = argparse.ArgumentParser(descri... | 64586f30b70ca8af9c107556ffb69bcf1ffa8696 | 3,645,253 |
def info(parentwindow, message, buttons, *,
title=None, defaultbutton=None):
"""Display an information message."""
return _message('info', parentwindow, message, title, buttons,
defaultbutton) | 060e41cde2e83bdeab3fa3147caebabb3292923a | 3,645,254 |
import hashlib
import time
import sys
def add_user(args):
"""
Process arguments and ask user for other needed parameters in order
to add info to DB
:param args: returned object from argparse.parse_args
:return: exit code (0 on success, 1 on failure)
"""
logger = fsurfer.log.get_logger()
... | eac6dc03bb65ce5243f0c3117e65ff969efe4020 | 3,645,255 |
def gru(xs, lengths, init_hidden, params):
"""RNN with GRU. Based on https://github.com/google/jax/pull/2298"""
def apply_fun_single(state, inputs):
i, x = inputs
inp_update = jnp.matmul(x, params["update_in"])
hidden_update = jnp.dot(state, params["update_weight"])
update_gate ... | 76c4ca1f90ba5cefc4227197d70c93c358d5f1d1 | 3,645,256 |
def get_strings_in_flattened_sequence(p):
"""
Traverses nested sequence and for each element, returns first string encountered
"""
if p is None:
return []
#
# string is returned as list of single string
#
if isinstance(p, path_str_type):
return [p]
#
# Get all... | 3de6829386d7877b745277cae88e3b3e6ac889a3 | 3,645,257 |
def kansuji2arabic(string, sep=False):
"""漢数字をアラビア数字に変換"""
def _transvalue(sj, re_obj=re_kunit, transdic=TRANSUNIT):
unit = 1
result = 0
for piece in reversed(re_obj.findall(sj)):
if piece in transdic:
if unit > 1:
result += unit
... | 4787618585baf660164d1c676ac7cae2750fe239 | 3,645,258 |
def get_image(member_status=None, most_recent=None, name=None, owner=None, properties=None, region=None, size_max=None, size_min=None, sort_direction=None, sort_key=None, tag=None, visibility=None):
"""
Use this data source to get the ID of an available OpenStack image.
"""
__args__ = dict()
__args... | 60fc60c558ac3c2e60fcdb73bf72a9d2bbc20855 | 3,645,259 |
def sort_course_dicts(courses):
""" Sorts course dictionaries
@courses: iterable object containing dictionaries representing courses.
Each course must have a course_number and abbreviation key
@return: returns a new list containing the given courses, in naturally sorted order.
"""
det... | f715cf1db4c77bd3412290bc870731e0d923871b | 3,645,260 |
import glob
import re
import numpy
def read_folder(filepath):
"""
Reads multiple image files from a folder and returns the resulting stack.
To find the images in the right order, a regex is used which will search
for files with the following pattern:
[prefix]_p[Nr][suffix]. The start number doesn'... | d50dc5ef09931b7950c91b5ea2f07eaa0d90cba1 | 3,645,261 |
from presqt.targets.zenodo.utilities.helpers.get_zenodo_children import zenodo_get_children
def zenodo_fetch_resource_helper(zenodo_project, resource_id, is_record=False, is_file=False):
"""
Takes a Zenodo deposition/record and builds a Zenodo PresQT resource.
Parameters
----------
zenodo_project... | 8427456ea648d1a5f4b5a0ee3baffc28649184aa | 3,645,262 |
import json
def add_role_menu(request):
"""菜单授权"""
menu_nums = request.POST.get("node_id_json")
role_id = request.POST.get("role_id")
role_obj = auth_db.Role.objects.get(id=role_id)
menu_nums = json.loads(menu_nums)
role_obj.menu.clear()
for i in menu_nums:
menu_obj = auth_db.M... | 31b8d2eb62ad105c4e44f6af7fa75cde2746d2f0 | 3,645,263 |
import os
def repo_path():
"""
little function to help resolve location of doctest_files back in repository
:return: the absolute path to the root of the repository.
"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 2fc1263d0c6c68e6f2e11c97d55fe9f539fb1b70 | 3,645,264 |
def oauth_url(auth_base, country, language):
"""Construct the URL for users to log in (in a browser) to start an
authenticated session.
"""
url = urljoin(auth_base, 'login/sign_in')
query = urlencode({
'country': country,
'language': language,
'svcCode': SVC_CODE,
'a... | d932d161ead93510e2a4b05c20f87982c726e158 | 3,645,265 |
def teammsg(self: Client, message: str) -> str:
"""Sends a team message."""
return self.run('teammsg', message) | 97a3a9c99af17fcf183d72158ec5dc9b5ad3689d | 3,645,266 |
def config_section(section):
"""
This configures a specific section of the configuration file
"""
# get a handle on the configuration reader
config_reader = get_config_reader()
# Find the group that this section belongs to.
# When we're in a namespaced section, we'll be in the group that th... | 93bc61bfc400c8da4e8d677954c6fdb18ae0d959 | 3,645,267 |
def h_html_footnote(e, doc):
"""Handle footnotes with bigfoot"""
if not isinstance(e, pf.Note) or doc.format != "html":
return None
htmlref = rf'<sup id="fnref:{doc.footnotecounter}"><a href="#fn:{doc.footnotecounter}" rel="footnote">{doc.footnotecounter}</a></sup>'
htmlcontent_before = rf'<li c... | 462f4886cc7b4be46b3904abc3396096f36d7938 | 3,645,268 |
def segment(x,u1,u2):
""" given a figure x, create a new figure spanning the specified interval in the original figure
"""
if not (isgoodnum(u1) and isgoodnum(u2)) or close(u1,u2) or u1<0 or u2 < 0 or u1 > 1 or u2 > 1:
raise ValueError('bad parameter arguments passed to segment: '+str(u1)+', '+str(u... | 291ddfb011ece20840a4a56fdc7bc87f2187625f | 3,645,269 |
import os
def compress_files(file_names):
"""
Given a list of files, compress all of them into a single file.
Keeps the existing directory structure in tact.
"""
archive_file_name = 'archive.zip'
print(f'{len(file_names)} files found. Compressing the files...')
cwd = os.getcwd()
with Z... | e7b29373f099d73cc207cc78162742721dc96246 | 3,645,270 |
def box_from_anchor_and_target(anchors, regressed_targets):
"""
Get bounding box from anchor and target through transformation provided in the paper.
:param anchors: Nx4 anchor boxes
:param regressed_targets: Nx4 regression targets
:return:
"""
boxes_v = anchors[:, 2] * regressed_targets[:,... | c55a54535fbfa67502c1b65ec71c23d772dedd7e | 3,645,271 |
def block_device_mapping_update(context, bdm_id, values, legacy=True):
"""Update an entry of block device mapping."""
return IMPL.block_device_mapping_update(context, bdm_id, values, legacy) | 7959cc6c849cb599c719e21f8c8315a7bc7ddd09 | 3,645,272 |
def consumer(address,callback,message_type):
"""
Creates a consumer binding to the given address pull messages.
The callback is invoked for every reply received.
Args:
- address: the address to bind the PULL socket to.
- callback: the callback to invoke for every message. Mu... | a1c01bafa4f65ba0a0a212916556c36315fe2c88 | 3,645,273 |
def _parse_continuous_records(prepared_page, section_dict):
"""Handle parsing a continuous list of records."""
# import pdb; pdb.set_trace()
columns = 6
start = prepared_page.index('Date and time')
for i, column in enumerate(prepared_page[start:start + columns]):
column_index = start + i
... | 7ddcb52433828d37ce6e0cac5d51d8fcfb249296 | 3,645,274 |
def power_law_at_2500(x, amp, slope, z):
""" Power law model anchored at 2500 AA
This model is defined for a spectral dispersion axis in Angstroem.
:param x: Dispersion of the power law
:type x: np.ndarray
:param amp: Amplitude of the power law (at 2500 A)
:type amp: float
:param slope: Sl... | 508227f332f652d00c785074c20f9acefbce9258 | 3,645,275 |
def map2alm(
maps,
lmax=None,
mmax=None,
iter=3,
pol=True,
use_weights=False,
datapath=None,
gal_cut=0,
use_pixel_weights=False,
):
"""Computes the alm of a Healpix map. The input maps must all be
in ring ordering.
Parameters
----------
maps : array-like, shape (... | 9312a6c5ee40fe9a3ef3f6057ee5964d200f9732 | 3,645,276 |
def credits():
"""
Credits Page
"""
return render_template("credits.html") | 00fdc0be4c3abd3df21993b271977208252123df | 3,645,277 |
def register_view(request):
"""Register a new user."""
if request.method == "POST":
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new User object but don't save it yet.
new_user = user_form.save(commit=False)
# Set the chos... | 19fa639603c7ea67a76696e4b88aae376461988c | 3,645,278 |
from typing import Dict
from typing import Any
from typing import Optional
import requests
import json
def handle_pdf_build(pdf_job_dict: Dict[str, Any], tx_payload, redis_connection) -> str:
"""
A job dict is now setup and remembered in REDIS
so that we can match it when we get a future callback.
... | 2d1258ad32fe13782264332c914793c82777e995 | 3,645,279 |
def menu(request):
"""
A View to return the menu.html
where all menu images are returned
in a carousel.
"""
menus = MenuImages.objects.all()
context = {
'menus': menus
}
return render(request, 'menu/menu.html', context) | 9491d9e1d4084ed78d4aadfd867910e2d0511704 | 3,645,280 |
def wav_process(PATH, i):
"""
音频处理,在路径下读取指定序号的文件进行处理
Args:
PATH (str): 音频文件路径
i (int): 指定序号
Returns:
float: 计算得到的音源角度(单位:°)
"""
# 读取数据
wav, sr = read_wav(PATH, i + 1)
# 进行降噪
wav_rn = reduce_noise(wav)
# 计算角度
angle_list = estimate_angle(wav_rn, sr)
... | ee336928b4b5e221a72ba8b6509555666ff3b763 | 3,645,281 |
def extract_vuln_id(input_string):
"""
Function to extract a vulnerability ID from a message
"""
if 'fp' in input_string.lower():
wordlist = input_string.split()
vuln_id = wordlist[-1]
return vuln_id
else:
return None | 06673f2b401472185c8a3e6fc373d39c171791db | 3,645,282 |
import os
def ensure_paths_for_args(args):
"""
Ensure all arguments with paths are absolute & have simplification removed
Just apply os.path.abspath & os.path.expanduser
:param args: the arguments given from argparse
:returns: an updated args
"""
args.seqs_of_interest = os.path.abspath(... | e15b64f2856954bbb7f61d44084d01bb8cdc53ba | 3,645,283 |
def compare_images(img1, img2):
"""Expects strings of the locations of two images. Will return an integer representing their difference"""
with Image.open(img1) as img1, Image.open(img2) as img2:
# Calculate a difference image that is the difference between the two images.
diff = ImageChops.diff... | bc94987785a5731e71a1e25daae51179c415eda6 | 3,645,284 |
def bytes_to_nodes(buf):
""" Return a list of ReadNodes corresponding to the bytes in buf.
@param bytes buf: a bytes object
@rtype: list[ReadNode]
>>> bytes_to_nodes(bytes([0, 1, 0, 2]))
[ReadNode(0, 1, 0, 2)]
"""
lst = []
for i in range(0, len(buf), 4):
l_type = buf[i]
... | 1296b49f5d76605d4408eddf21b76f286dfc5f5b | 3,645,285 |
import sys
def require_captcha(function, *args, **kwargs):
"""Return a decorator for methods that require captchas."""
raise_captcha_exception = kwargs.pop('raise_captcha_exception', False)
captcha_id = None
# Get a handle to the reddit session
if hasattr(args[0], 'reddit_session'):
reddi... | e6f427317fd64a156db331d0d85220e09872b5af | 3,645,286 |
def list_unnecessary_loads(app_label=None):
"""
Scan the project directory tree for template files and process each and
every one of them.
:app_label: String; app label supplied by the user
:returns: None (outputs to the console)
"""
if app_label:
app = get_app(app_label)
else:... | d78aeb6132e4f79f4458454f6107f9003db37999 | 3,645,287 |
from typing import Any
def _element(
html_element: str,
html_class: str,
value: Any,
is_visible: bool,
**kwargs,
) -> dict:
"""
Template to return container with information for a <td></td> or <th></th> element.
"""
if "display_value" not in kwargs:
kwargs["display_value"] ... | 4ce4d2ff9f547470d4a875508c40d3ae2a927ba0 | 3,645,288 |
import os
def create_app(test_config=None):
"""
This method creates a flask app object with a
given configuration.
Args:
test_config (dict): Defaults to None.
Returns:
app (Flask): Flask app object.
"""
app = Flask(__name__)
Bootstrap(app)
# check environment vari... | a901f37ee573b159a25a8c9c715205cf0b2cd496 | 3,645,289 |
import torch
def lovasz_hinge_loss(pred, target, crop_masks, activation='relu', map2inf=False):
"""
Binary Lovasz hinge loss
pred: [P] Variable, logits at each prediction (between -\infty and +\infty)
target: [P] Tensor, binary ground truth labels (0 or 1)
"""
losses = []
for m, p, t i... | c1d7ce49feda1a2ba1116d03de3ba8a5b9ad65a9 | 3,645,290 |
def get_gene_summary(gene):
"""Gets gene summary from a model's gene."""
return {
gene.id: {
"name": gene.name,
"is_functional": gene.functional,
"reactions": [{rxn.id: rxn.name} for rxn in gene.reactions],
"annotation": gene.annotation,
"notes... | dd9cb3f8e9841a558898c67a16a02da1b39479d2 | 3,645,291 |
def prompt_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"typ... | dc5f077d3710420b9d9b26032ee340c0671d009d | 3,645,292 |
def random_permutation_matrix(size):
"""Random permutation matrix.
Parameters
----------
size : int
The dimension of the random permutation matrix.
Returns
-------
random_permutation : array, shape (size, size)
An identity matrix with its rows random shuffled.
"""
... | 0ca4e93218fd647188ac09c4d71a3df1cff3acf7 | 3,645,293 |
from typing import Optional
import collections
def matched(captured: Optional[Capture], groups_count: int) -> MatchedType:
"""
Construct the matched strings transversing\
given a captured structure
The passed Capture has the last captured char\
and so the sequence is transversed in reverse
S... | 0bb7544f9d5ac339e0aed717bc5779deba781dc8 | 3,645,294 |
def tle_fmt_float(num,width=10):
""" Return a left-aligned signed float string, with no leading zero left of the decimal """
digits = (width-2)
ret = "{:<.{DIGITS}f}".format(num,DIGITS=digits)
if ret.startswith("0."):
return " " + ret[1:]
if ret.startswith("-0."):
return "-" + ret[2:... | 686cb4061e5cf2ad620b85b0e66b96a8cd1c3abf | 3,645,295 |
def pack(name=None, prefix=None, output=None, format='infer',
arcroot='', dest_prefix=None, verbose=False, force=False,
compress_level=4, n_threads=1, zip_symlinks=False, zip_64=True,
filters=None, ignore_editable_packages=False):
"""Package an existing conda environment into an archive f... | 500841ec51c58ec0ff99c4b286c8a235ab887d7b | 3,645,296 |
def rasterize(points):
""" Return (array, no_data_value) tuple.
Rasterize the indices of the points in an array at the highest quadtree
resolution. Note that points of larger squares in the quadtree also just
occupy one cell in the resulting array, the rest of the cells get the
no_data_value.
"... | 41db3b63a5956aff192585c7c5ce5b6c83f0d6cd | 3,645,297 |
def parse_aedge_layout_attrs(aedge, translation=None):
"""
parse grpahviz splineType
"""
if translation is None:
translation = np.array([0, 0])
edge_attrs = {}
apos = aedge.attr['pos']
# logger.info('apos = %r' % (apos,))
end_pt = None
start_pt = None
# if '-' in apos:
... | f086e2267d19710685e3515aeee352066bd983b2 | 3,645,298 |
import importlib
import re
def load_class_by_path(taskpath):
""" Given a taskpath, returns the main task class. """
return getattr(importlib.import_module(re.sub(r"\.[^.]+$", "", taskpath)), re.sub(r"^.*\.", "", taskpath)) | a9601dafbc73635d81732a0f3747fd450e393d76 | 3,645,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.