content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def update_team_area(path, team, include_sub_areas=None, set_as_default=False,
organization=None, project=None, detect=None):
"""(PREVIEW) Update team area.
:param set_as_default: Set as default team area path. Default: False
:type set_as_default: bool
"""
if include_sub_areas i... | 7cb2572ea2446cdc0b9e2038ab490936a5bd7cdb | 62,255 |
import itertools
def ip_sort(a_str,b_str):
"""Fast IP address sorting function"""
for a,b in itertools.izip(a_str.split('.'), b_str.split('.')):
if a == b:
continue
if len(a) == len(b):
return cmp(a,b)
return cmp(int(a), int(b))
return 0 | 1f26d57973c69244c2a9cf7dddb36bf5fb8af64e | 62,256 |
def gradient(output_str):
""" Reads the molecular gradient (in Cartesian coordinates) from
the output file string. Returns the gradient in atomic units.
:param output_str: string of the program's output file
:type output_str: str
:rtype: tuple(tuple(float))
"""
# Try to rea... | 005e2b39ecffd0878a5da3c91c5f46fb1cacdb0c | 62,257 |
def plot_imbalances(imbalances, logplot=False):
"""
Information Imbalance Plane plot, see [1].
Arguments
---------
imbalances : dict
Dictionary storing the imbalances for each
number of retained features. Structured as:
imbalances --- 0 --- 'A_B... | d197f09f6502842a58e4898e703b4b8424379463 | 62,258 |
import re
def camelcase_to_snakecase(name):
"""
Convert a name in camel case to snake case.
Arguments:
name -- The name to convert.
Returns:
The name in snake case.
"""
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower() | 2143c89b7cd4c836040246ecbaa7fe8474c3ca76 | 62,259 |
def dCitySEIR(vector,t,params):
"""
建立城市之间流动模型的SEIR
:param vector:
:param t: time
:param params:R0,Di,De,Lsi,Lei,Lii,Lri,Lo
:return:dF
"""
S,E,I1,I2,R = vector
R0,Di,De,Da,Lsi,Lei,Li1i,Li2i,Lri,Lo= params
N = S+E+I1+I2+R
I = I1+I2
t = np.ceil(t)
dSdt = -(R0/Di)*S*I/N ... | 023fea7779f3a6526eaf54738e430121728873f9 | 62,260 |
def gethostname(data, *args, **kwargs):
"""Description: Method to find hostname in show
command output, uses symbols '# ', '<', '>' to find hostname
"""
REs = [ # ios-xr prompt re must go before ios privilege prompt re
{'juniper': '\n\S*@(\S+)>.*(?=\n)'}, # e.g. 'some.user@router-fw-host>'... | c476b32dd24f59c661bda02aeef637b3b9295f8f | 62,261 |
def calculateinterval(cdsinterval, txregion):
"""
calculate the interval which were included
:param cdsinterval:
:param txregion:
:return:
"""
assert txregion[0] < txregion[1], "start site not smaller than end site in the given region"
cdsinterval = list(map(list, sorted(cdsinterval, key... | e3eb87fb65dd32db640a3432a2924aa50ee2e72c | 62,262 |
from typing import Optional
def top_k(
input: oneflow_api.BlobDesc,
axis: int = -1,
k: int = 1,
sorted: bool = True,
name: Optional[str] = None,
) -> oneflow_api.BlobDesc:
"""Finds the indices of the k largest entries at specified axis, the difference between other framework is that oneflow on... | 8a6486e4d6327f1f2dad4bbfe153637a63cec5b4 | 62,263 |
from typing import List
from typing import Tuple
from typing import Union
def read_expected_file(path: str) -> List[Tuple[Union[str, float], ...]]:
"""Reads and parses resource file."""
types = str, float
with open(path, "r") as file:
expected_fermionic_op = [tuple(t(e) for t, e in zip(types, line... | 1d5228edffd8fa2486b41187f4a10b24209e52fc | 62,264 |
import six
def plot_fleur_mn(nodelist, save=False):
"""
This methods takes any amount of AiiDA node as a list and starts
the standard visualisation for it, if it finds one.
Some nodes types it tries to display together if it knows how to.
and if they are given as a list.
param: save showed t... | d6447506fada827ae15661a81ad3e000e3363a5c | 62,265 |
import time
def do_price_MC(M_io, Lp, Cu, price_data, Nruns = 10):
"""Performs a Monte Carlo based on price variations.
Input:
M_io The Characteristation multiplier matrix, tehcnically C.dot(S).dot(L_io)
Lp Lenontief inverse of the LCA A-matrix
Cu Unscaled Cut off... | b23b7ff2925cf0a2a597c5b0911926c94147d5b2 | 62,268 |
def G1DListCrossoverUniform(genome, **args):
"""
The G1DList Uniform Crossover
Each gene has a 50% chance of being swapped between mom and dad
"""
sister = None
brother = None
gMom = args["mom"]
gDad = args["dad"]
sister = gMom.clone()
brother = gDad.clone()
sister.resetSt... | 45105ea4fba2ceaf6bc7387297c01e5d972902f7 | 62,269 |
def no_space_conjunction(tag1, tag2):
"""If two tags represent one number and one letter."""
if tag1 == 'L' and tag2 == 'N':
return True
elif tag1 == 'N' and tag2 == 'L':
return True
else:
return False | ec3fa6c2aa0f54cc2cd2f92676d932880d572506 | 62,270 |
import binascii
def ShortName(ShortName):
"""
Get AD for the short name of device.
"""
l = binascii.hexlify((len(ShortName)+1).to_bytes(1, 'little')).decode('utf-8') # converts the length to a hex representation in a byte in String format
pl = ''
for i in to_hex(bytes(ShortName, 'utf-8')).spli... | 974c0b0d3f4cc6b210081c868379fc0e31b51234 | 62,271 |
def get_permission_table_data(instance, request_user, actions=['view', 'change', 'delete', 'share']):
"""Prepare data for a permission table.
Parameters
----------
instance: Model
Model instance for which the permission table should be generated.
request_user: User
User for which th... | 0d570b9129a5343abf1e403e25eacf4893623dc8 | 62,272 |
def _guess_ndvar_data_type(info):
"""Guess which type of data to extract from an mne object.
Checks for the presence of channels in that order: "mag", "eeg", "grad".
If none are found, a ValueError is raised.
Parameters
----------
info : dict
MNE info dictionary.
Returns
-----... | 9f1823d8484f0595644d5ca8e937be4a18b3fedf | 62,273 |
from unittest.mock import patch
def create_aliases_duplicate_patcher(client, guid_mock, signed_url_mock):
"""
Same as valid_upload_file_patcher except /aliases requests are mocked
as returning a 500
"""
patches = []
data_upload_mocked_reponse = {
"guid": guid_mock,
"url": sign... | 92afc0d789df6bb0131dbbaa1ae287c8bb0eef62 | 62,275 |
def new_map_entry(dp_id, dp_port, re_id, name):
"""
returns instance of FIBMap
"""
port = FIBCPort(id=dp_id, port=dp_port)
link = FIBCLink(re_id=re_id, name=name)
return FIBMap(port=port, link=link) | 1da6297f08e8dd8040e153828270edd23dc7d121 | 62,276 |
def exact_match(predictions: np.ndarray, actuals: np.ndarray, question_ids: np.ndarray):
"""Compute the exact match (EM) for a sequence of predictions and actual labels"""
unique_questions = set(question_ids)
q_actuals = list(zip(question_ids, actuals))
q_predictions = list(zip(question_ids, prediction... | 05a4a021496f40052ade640fd82343e828a0f2e3 | 62,277 |
def center_button(label):
"""Quickfix to center buttons, not allowed natively from Streamlit"""
col1, col2, col3, col4, col5 = st.beta_columns((0.3, 0.3, 1, 0.3, 0.3))
with col1:
pass
with col2:
pass
with col4:
pass
with col5:
pass
with col3:
return s... | 05b364dd074230b3473ee23544a1636873249ac0 | 62,278 |
from typing import List
from typing import cast
def description_patch(value: str, timestamp: str,
register: Register) -> List[rsf.Command]:
"""
Composes the pair of RSF commands for a description patch.
"""
key = f"register:{register.uid}"
data = cast(Record, register.metalo... | 568aaae65399e52fdacd3853c7b9f27f539561e3 | 62,279 |
def get_date_range(start_date, end_date):
""" https://stackoverflow.com/a/7274316 """
delta = end_date - start_date
date_range = [(start_date + timedelta(days=i)).strftime('%Y%m%d') for i in range(delta.days + 1)]
return date_range | 7427e65718cb0b806a8171e9e67c5a26876a2edd | 62,280 |
def get_package_requirements(requirement_type: str):
"""
Load in extra_requirements.json from the package
"""
requirements = {
"numpy": ["core"],
"requests": ["core"],
"pytest": ["test"],
"sphinx-rtd-theme>=0.5.0": ["test"],
"imageio": ["encoders-image-tfhub"]... | 4c3607de3accb145eb7855915dedc61bbba41a90 | 62,281 |
def generate_randao_reveal(
privkey: int, slot: Slot, state: BeaconState, config: Eth2Config
) -> BLSSignature:
"""
Return the RANDAO reveal for the validator represented by ``privkey``.
The current implementation requires a validator to provide the BLS signature
over the SSZ-serialized epoch in whi... | 83568f698b30e0b1608dad8a8758934395f6d4f9 | 62,282 |
def isAnyNode(input):
"""
This function check input is a AnyNode object.
:param input: unknown type object
"""
return isinstance(input, AnyNode) | 4897a5d2598a07a9c9595055686b65ae13c6e9b7 | 62,283 |
def speechProc(fName, numFrames, fps, kuro = False, return_extras = False):
"""Inputs an audio file and processes audio feature vectors that coincide in time with the source video frames. The audio feature vectors are based on Mel frequency cepstral coefficients (MFCCs). Because the sampling rate in the audio file ... | ff8eb2d50522f214a5a8e8c5a746e72b32b6b29e | 62,284 |
def pretty_print_options(message):
"""
Some modifications for pretty printing.
Use uppercase for first letter in text and a single dot for the end if there isn't one already.
:param message: String
:return: String
"""
# check for html
if message[0:1] == '<':
pos = message.inde... | 09552f39b4862bff9b35c52ef2f2b21f9fa20161 | 62,285 |
from functools import reduce
def find_common_set_of_column_names(dfs):
"""Returns a sorted list of common columns names."""
cols = [set(df.columns) for df in dfs]
return sorted(list(reduce(set.intersection, map(set, cols)))) | 77cf55ace97fbab3ad2e32c3656f5df883b2db7b | 62,286 |
def make_softmax_tests(options):
"""Make a set of tests to do softmax."""
test_parameters = [{
"dtype": [tf.float32],
"input_shape": [[1, 3, 4, 3], [2, 3]],
"dim": [-1, 0],
}, {
"dtype": [tf.float32],
"input_shape": [[4, 7]],
"dim": [-1, 1],
}]
def build_graph(parameters)... | 79e0b97dc61bc90f1feb12e6b30723cdf1c0c873 | 62,287 |
def monthly_returns(returns, eoy=True, compounded=True, prepare_returns=True):
"""Calculates monthly returns"""
if isinstance(returns, _pd.DataFrame):
warn("Pandas DataFrame was passed (Series expeted). "
"Only first column will be used.")
returns = returns.copy()
returns.co... | ae06d364885492c1638c0d0cdb47a2a3bc3d4ebc | 62,288 |
def disjoint_union(G, H):
""" Return the disjoint union of graphs G and H.
This algorithm forces distinct integer node labels.
Parameters
----------
G,H : graph
A NetworkX graph
Returns
-------
U : A union graph with the same type as G.
Notes
-----
A new graph is c... | 76670731ca6c46df944486bd0e66a9fbae888869 | 62,290 |
import numpy
def voigt(omega, cent, delta, gamma=0.0):
"""Normalized Voigt line shape for absorption
"""
z = (omega - cent + 1j*gamma)*numpy.sqrt(numpy.log(2.0))/delta
return numpy.sqrt(numpy.log(2.0))*\
numpy.real(special.wofz(z)) \
/(numpy.sq... | d69312797ccc4ac0c026e6ae4f0c6139354bc7c6 | 62,291 |
def add_new_handler_object_via_bulk(data, rowData, request, errors,
is_validate_only=False, cache={}, obj=None):
"""
Bulk add wrapper for the add_new_handler_object() function.
"""
(result,
retVal) = add_new_handler_object(data, rowData, request,
... | c09e29312112fd8dcea9cb03596c0bff6da0cb60 | 62,292 |
def get_long_description():
"""
:return: The description for the plugin type.
"""
return """Infrastructure plugins use different techniques to identify the
remote operating system, HTTP daemon, Web Application Firewalls, remote users
and any other information that is related to the target web ap... | cbf895c9312d9336c33f9afffb7d1113e30ea093 | 62,293 |
from typing import List
from typing import Dict
def evaluate_det(
ann_frames: List[Frame],
pred_frames: List[Frame],
config: Config,
) -> Dict[str, float]:
"""Load the ground truth and prediction results.
Args:
ann_frames: the ground truth annotations in Scalabel format
pred_frame... | c28e0cdc58b42b9132a3f1262ca82b40e473c72d | 62,295 |
def batch_norm_mean_only(x,
n_out,
is_training,
reuse=None,
gamma=None,
beta=None,
axes=[0, 1, 2],
scope="bnms",
name="b... | 905bd3f1c59449906dbfcac6f584c6c03e56a369 | 62,296 |
def navigation(request):
"""Fetches data required to render navigation menu.
The main menu contains the list of user categories to choose.
Here is the query to fetch them.
"""
context = {}
if hasattr(request, "user_categories"):
context.update(
{
"user_categ... | 5641d35f47d4ae6c7045db81ceaaebae12b541d9 | 62,298 |
from typing import cast
def makeTusClient() -> Erc20Web3Client:
"""
Return an initialized client to interact with the TUS
token contract
"""
tusContract = cast(Address, "0xf693248F96Fe03422FEa95aC0aFbBBc4a8FdD172")
return makeErc20Client(
"Avalanche",
nodeUri,
tusContra... | 38057a020ad83034ab30ae9217047f735df79d10 | 62,299 |
from bs4 import BeautifulSoup
def read_html(input_str: str) -> BeautifulSoup:
"""Takes str, does cleaning as input and returns BeautifulSoup object"""
f = utils.clean_input(input_str)
soup = BeautifulSoup(f, "lxml")
# removes all anchor elements/links and contents thereof
[a.decompose() for a in s... | f4320cda4b0e88c3a5709cb8646ab08c03d93d97 | 62,300 |
from unittest.mock import patch
async def setup_script(hass, notify_q, now, source):
"""Initialize and load the given pyscript."""
scripts = [
"/some/config/dir/pyscripts/hello.py",
]
with patch("custom_components.pyscript.os.path.isdir", return_value=True), patch(
"custom_components.... | 2c1b612801bda9cee797c63ea644684ab9b77a3a | 62,302 |
def compute_mu_for_co_component(graph, component_index, source_index,
root, vertices_in_component):
"""
Compute the mu value for co-component
INPUT:
- ``graph`` -- Graph whose MD tree needs to be computed
- ``component_index`` -- index of the co-component
- ``... | f8277bf8f37635e9c3696d733df7eba7420ae1e0 | 62,303 |
def append_filename(filename, impute_dates, moving_average):
"""! Creates consistent file names for all output.
"""
if moving_average > 0:
filename = filename + '_ma' + str(moving_average)
elif impute_dates:
filename = filename + '_all_dates'
return filename | 3d4137ac023ed1470e20a78626803b29e9c14a0f | 62,304 |
def _merge_css_list(*args):
"""Transform arguments into a single list of string values."""
css_list = []
for arg in args:
css_list += _merge_css_item(arg)
return css_list | dd0af268386aed7c8dc8245986e6edaf55f0277c | 62,305 |
def step_functions_execution_arn(state_machine_name_template: str, execution_name: str) -> str:
"""
The ARN of a state machine execution, with name derived from `state_machine_name_template`, with string formatting
to replace {stage} with the dss deployment stage.
"""
sfn_name = state_machine_name_... | a40a89c34fefb3f405bb0d86228c26a950454665 | 62,306 |
def crawled_url() -> list:
""" Get crawled url"""
# 0
crawled_url = db.uk_181125.find({}, {'_id':0, 'url':1})
crawled_url = list(map(lambda one_url : one_url['url'], crawled_url))
return crawled_url | e51c59bba080716605e8655e4e508f9fd05a92d3 | 62,307 |
def encode_data(data_structure):
"""
Encode an arbitrary python data structure in a format that is suitable
for encryption (encrypt() expects bytes).
The data structure can only contain basic python types, those supported
by json.dumps (including longs, but no arbitrary objects).
Performs the fo... | 7b3a11d7ee5a4014ccdb5499d0f4d589043b4b3b | 62,308 |
def block_layer(
inputs, filters, block_fn, blocks, strides, is_training, name, data_format
):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_format.
filters: T... | 6a87bf15c74812a55680d1350d1dd8667bce484f | 62,311 |
def set_meta (mimetype) :
""" Factory function for Attribute_Access to set all interesting
meta-data
"""
set_attr = []
for attr in meta_counts :
a = OOo_Tag ('meta', attr, mimetype)
t = OOo_Tag ('meta', 'document-statistic', mimetype)
set_attr.append (Set_Attribute (t, a,... | 6a7ac7ae6a2fcf8bfded921254443ef1db4e7ee7 | 62,312 |
def get_two_gaussians(N=0.5, mu=(1, 3), b=(100, 100), r=(1, 1)):
"""
Returns the two Gaussians spectral density defined in Sec. 4.2 of the thesis
"""
mu1 = mu[0]
mu2 = mu[1]
b1 = b[0]
b2 = b[1]
r1 = r[0]
r2 = r[1]
alpha = N / (r1 * np.sqrt(np.pi / b1) + r2 * np.sqrt(np.pi / b... | ec00839d74dfe3635467ba7b878c854410856b06 | 62,313 |
import html
def render_select_cells(data):
"""Render the collapse for selecting cells for differential expression"""
return html.Div(
[
html.P(),
dbc.Button(
"differential expression",
id="select_cells_button",
className="text-lef... | e1c23c329dae8eb5e8712d860e21d65a39610281 | 62,314 |
import requests
def get_sites():
"""
Get list of sites (using GOCDB instead of site configuration)
:return: list of site IDs
"""
query = {"method": "get_site_list", "certification_status": "Certified"}
url = "?".join([GOCDB_PUBLICURL, parse.urlencode(query)])
request = requests.get(url)
... | 0ef0c1203b5de58df8105e5c82e9d6d6d8f91459 | 62,315 |
def get_secret_envs(config: dict):
"""
>>> get_secret_envs({"environment": {"abc": "aws:kms:kmsencval", "def": "unencval"}})
frozenset({'abc'})
>>> get_secret_envs({"environment": {"abc": False, "def" : "aws:kms:secrev"}})
frozenset({'def'})
>>> get_secret_envs({"environment": None})
froze... | fe18e5b608b589acdb1189778279b818d1bea44b | 62,316 |
def tf_get_model_lmks(tf_model, f, lmk_face_idx, lmk_b_coords):
"""Get a differentiable landmark embedding in the FLAME surface"""
faces = f[lmk_face_idx].astype(np.int32)
return tf.einsum('ijk,ij->ik', tf.gather(tf_model, faces), tf.convert_to_tensor(lmk_b_coords)) | f4c79d4c0bc78135dc42ca250adca665b86837fb | 62,317 |
def is_valid_int_param(param, required=True):
"""Checks if the parameter is a valid integer value.
@param param: Value to be validated.
@return True if the parameter has a valid integer value, or False otherwise.
"""
if param is None and not required:
return True
elif param is None:
... | 928b61deaf2c7167f01ec596bf741c0b8f828dad | 62,319 |
def ta(tex, tbg, tau_):
"""
Eq. (18) Goldsmith et al. (2012)
"""
gbg_ = gbg(tbg)
return tstar*(1./(np.exp(tstar/tex) - 1.) - gbg_)*(1. - np.exp(-tau_)) | f6ea7908353e5fa823bd53694876e426cea277d2 | 62,321 |
def has_key(title, key):
""" Check if route dict has a specific key | str, str --> bool """
route_dict = get_route_dict(title)
return key in route_dict | 90af98f070b1bad2b3185d91a5828de5561c2335 | 62,322 |
from functools import reduce
def lcm(*integer_nums: int) -> int:
"""
Private function for calculating LCM [least common multiple] of N integers
Args:
*integer_nums: integer arguments
Returns:
Least common multiple of N positive integers.
Examples:
>>> lcm(16, 20)
... | d4afb601db6fcd0a8b5797cd1f9dea1a090bf5aa | 62,323 |
def invert_transform(T_in):
"""return inverse transform of T_in, assuming T_in is affine 4x4 transformation"""
T_out = np.eye(4)
C_out_inv = T_in[:3, :3].T # exploiting that C^T = C^-1 for rotations
T_out[:3, :3] = C_out_inv
T_out[:3, 3] = -C_out_inv.dot(T_in[:3, 3])
return T_out | e8a5ec8b4d0e2dc8a2e791d4cd60bf5dcd7aaa35 | 62,324 |
def exercise(xml):
"""Find the target element, add the new item, and return the modified XML
string.
"""
ns = {"t": "http://martin.hoppenheit.info/code/generic-tree-xml",
"e": "http://purl.org/dc/elements/1.1/"}
root = ET.fromstring(xml)
for n in root.iter("{%s}node" % ns["t"]):
... | 18079fd9bbd121f532b0e148249c36144521af90 | 62,325 |
def auth_user(
request: Request,
db: Session = Depends(get_db),
) -> UserBase:
"""
## Dependency
Authenticates a user by verifying their access token
and returns the authenticated user info
Returns
--------
user_id : UUID
email : EmailStr
master_pwd : str
"""... | 3d61b897408a296774d9837a1779a070dd4bef33 | 62,327 |
def print_deps(i):
"""
Input: {
data_uoa - data UOA of the repo
or
repo_deps - dict with dependencies on other shared repos
(out_prefix) - output prefix befor each string
}
Output: {
... | fe72bd971b15f0ff9524d887829b60ea7b82051b | 62,328 |
def _get_mask(id_to_node, node_to_id, num_nodes, masked_nodes, additional_mask_rate):
"""
Returns the train and test mask arrays
:param id_to_node: dictionary mapping node names(id) to dgl node idx
:param node_to_id: dictionary mapping dgl node idx to node names(id)
:param num_nodes: number of user/... | 8280d7f6962ee9e0fbc7fca940c64eb72d58ba4a | 62,329 |
def Delete(taxonomy_id, annotation_id):
"""Makes an API call to delete an annotation.
Args:
taxonomy_id: Id of a taxonomy.
annotation_id: Id of the annotation.
Returns:
An Operation message which can be used to check on the progress of the
project creation.
"""
return _GetService().Delete(
... | ca9aaf23ca4df44b50a5ba7192b23bd3b4a5ab8a | 62,330 |
def unique(id, ids):
""" Ensure id is unique in set of ids. Append '_1', '_2'... if not """
while id in ids or not id:
m = IDCOUNT_RE.match(id)
if m:
id = '%s_%d' % (m.group(1), int(m.group(2))+1)
else:
id = '%s_%d' % (id, 1)
ids.add(id)
return id | 05f633aa3db40324e424fa7f889e6b434c0a0bb9 | 62,331 |
def questions_for_written_answer_answered_in_range(start, end):
"""Returns a list of all Questions for Written Answer, and respective
Answers, answered in date range.
"""
try:
_start = start.isoformat()
except AttributeError:
return []
try:
_end = end.isoformat()
exce... | 7cd5341ed5f1fb54c1c230356994bb9c2650c0e1 | 62,333 |
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
# initial = tf.truncated_normal(shape, stddev=0.1)
initial = tf.constant(0.01, shape=shape)
return tf.Variable(initial) | 49ee5b4b9708c3780f10b7980150a6b5f3a2265f | 62,334 |
def init_proof(prop):
"""Initialize proof for proposition."""
vars = prop.get_vars()
assms, concl = prop.strip_implies()
assms.append(concl.arg if concl.is_not() else Not(concl))
return ProofState(vars, assms) | ab2ad2d4e78f4c013c6d445bde142d16ffc6f952 | 62,335 |
def get_vaccine_admin():
"""Returns DataFrame on COVID-19 vaccine administration in Italy.
Parameters
----------
None
Raises
-------
ItaCovidLibConnectionError
Raised when there are issues with Internet connection.
Returns
-------
pandas.core.frame.DataFram... | 5f2a0236f142fbdfcc9f172cf720026dfd428023 | 62,336 |
def delete_category(request, category_id):
""" Delete a category from the database """
# if not request.user.is_superuser:
# messages.error(request, 'Sorry, only site owners can do that.')
# return redirect(reverse('home'))
try:
category = get_object_or_404(Category, pk=category_id)... | 2a023ff146e1d044f895968f3339ed2057eff37a | 62,337 |
async def set_epoch_and_fallback_properties(config: ComponentConfig, current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Set properties (epoch and fallback) in the bot pipeline and policies configurations
"""
mongo_processor.save_component_properties(config.dict(), current_user.g... | 707294b906253681addb1152171b8fd45ce48371 | 62,338 |
def escape_ipv6(address):
"""Escape an IP address in square brackets if IPv6
:param address: address to optionaly escape
:type address: string
:returns: string
.. versionadded:: 3.29.0
"""
if is_valid_ipv6(address):
return "[%s]" % address
return address | c8a2afe222a9fd29e6add1da39666dbef160bb50 | 62,339 |
def fc(inputs, is_training=True, num_classes=7, hidden_layer_size=[128, 128], dropout_keep_prob=0.8, reuse=None,
scope='FC'):
"""Creates a fully connected neural net.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes.
is_training... | 24b7fba8441cc74b3a342496dffe36131ceb95d7 | 62,340 |
def rad2hz(w0, fs=96000):
"""Calculate a normalised rotational frequency so that w0=2*pi --> f0=fs
w0
f0 = fs * ------
2*pi
"""
return fs*np.array(w0)/(2*np.pi) | e178dd58d01c0ca6ffbcd1f032e8d76d436a8501 | 62,342 |
from unittest.mock import patch
async def test_post_method_result_contains_is_new_setup_as_bool(
setup_course_environ, test_quart_client, jupyterhub_api_environ
):
"""
Does the POST endpoint return a boolean value to indicate if new setup was occured?
"""
async def return_async_value():
r... | 0c466dd6f968b15a5e3f3ead0f5a5ea71f1b5582 | 62,343 |
from typing import Optional
from typing import Union
from typing import Dict
def fix_level_type(
level_type: Optional[Union[str, Dict]],
engine: str = "eccodes",
) -> Optional[Union[str, Dict]]:
"""
Convert level type into dict of GRIB keys.
Notes
-----
``typeOfFirstFixedSurface``... | e9a5a608554fa09d6445b03abc790cb787d06f27 | 62,344 |
import platform, psutil
def index():
"""
example action using the internationalization operator T and flash
rendered by views/default/index.html or views/generic.html
if you need a simple wiki simply replace the two lines below with:
return auth.wiki()
"""
host=dict(machine=platform.machi... | 4584b4687d9dbf8e6a76d3308d618a1e2b9e41d1 | 62,345 |
def cal_hel(logits, gts, eps=1e-6, reduction="mean"):
"""
https://github.com/lartpang/HDFNet/blob/master/loss/HEL.py
::
@inproceedings{HDFNet-ECCV2020,
author = {Youwei Pang and Lihe Zhang and Xiaoqi Zhao and Huchuan Lu},
title = {Hierarchical Dynamic Filtering Network for ... | c67fe4a925b9af41cff6940e6072df467d2f9c83 | 62,346 |
import requests
def _send_photo_bytes(telegram_token, chat_id, bytes_io):
"""Send photo in open() or io.BytesIO form.
"""
url = "https://api.telegram.org/bot{}/sendPhoto".format(telegram_token);
files = {'photo': bytes_io}
data = {'chat_id' : chat_id}
r= requests.post(url, files=files, data=da... | 5b72e0baa552ff03a9838119ac2d4f64ffcfa49b | 62,347 |
import io
def _GenerateMtlsDisallowedServices():
"""Generates a table for services which do NOT support client certificate."""
disallowlist = []
for service, versions in apis_map.MAP.items():
for version, api_def in versions.items():
if not api_def.enable_mtls:
disallowlist.append((service, ve... | 2a13748a6619b54604f223930f71793f9a1ba229 | 62,348 |
def clean_up_whitespace_in_template_output(text):
"""Remove some excess whitespace from using Django templates for YAML."""
ret = []
for line in text.split("\n"):
# Truly empty lines are likely intentional, so keep them
if not line:
ret.append("")
continue
#... | 8428e5575f0a731d79ae796d3f20408e33a344e6 | 62,349 |
def _validate_spotlight_mode(the_sicd):
"""
Validate the spotlight mode situation.
Parameters
----------
the_sicd : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if the_sicd.CollectionInfo is None or the_sicd.CollectionInfo.RadarMode is None \
... | 3b72e99e7f6e1bae17fbdced72cfaf741a4d1974 | 62,350 |
def mixed_radix_to_base_10(x, b):
"""Convert the `mixed radix`_ integer with digits `x` and bases `b` to base 10.
Args:
x (list): a list of digits ordered by increasing place values
b (list): a list of bases corresponding to the digits
Examples:
Generally, the base 10 representatio... | a821ca5ee4a720a9c445c98b2bcd2905bd6d87cb | 62,351 |
def calculate_face_normals(hull, eps=10e-6, normalize=False):
"""Calculate outwards pointing normal for each simplex."""
face_normals = np.zeros((len(hull.simplices), 3))
barycenter = np.mean(hull.points, axis=0)
for face_i, face in enumerate(hull.simplices):
# extract vertices face
v = ... | 91d450e4b11d6f0805655e94649ad4144a29db43 | 62,352 |
def test():
"""
前向和后向传播
"""
x, d = lstm_math.data_set()
l = lstm_math.LstmLayer(3, 2, 1e-3)
l.forward(x[0])
l.forward(x[1])
l.backward(x[1], d, IdentityActivator())
return l | ad0cd138c8242b4fa76d5449bcc67716d8e33336 | 62,353 |
def _pprint_dict(seq, _nest_lvl=0):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u"{%s}"
pairs = []
pfmt = u"%s: %s"
for k, v in seq.items():
pairs.append(pfmt % (repr(k), repr(v)))
return fmt % ", ... | 8d48fde0030785139c29b9739a4e056e2ffd176e | 62,354 |
import warnings
def invert_function_interpolation(
d, initial, f_min, f_max, model_function, derivative_function=None, tol=1e-8, dx=1e-2
):
"""This function inverts a function using interpolation. For models where this is required, this is the most time
consuming step. Specifying a sensible f_max for this... | 02e47926bb3e91a8c9c223c2585f5db471ecdf57 | 62,356 |
import string
def validate_username(username: str) -> bool:
"""
Check if username if valid and return boolean.
Introduces following requirements:
- 4 < username length < 30
- username not empty
- all characters are ASCII or digits
Args:
username (str): username to chec... | d708377680e769944cb3a3a9a187f6eef72649bc | 62,357 |
def asarray(a, dtype=None):
"""
Converts the input to tensor.
This function converts tensors from an array-like object.
Args:
a (Union[int, float, bool, list, tuple, numpy.ndarray]): Input data, in
any form that can be converted to a tensor. This includes lists, lists of
tuples... | 041733fca2744d786ffa65960bf1189d02b646a2 | 62,359 |
def apply_mask_v2(mask: str, address: str) -> str:
"""
DOCTEST
>>> apply_mask_v2(mask='000000000000000000000000000000X1001X', address='000000000000000000000000000000101010')
'000000000000000000000000000000X1101X'
"""
output = "".join([address[i] if mask[i] == "0" else mask[i] for i, _ in enumer... | 1865b59317ed394bea4ea658f1acfd4277521b59 | 62,360 |
def gauss_weight(patch_shape, patch_sigma=3):
"""
Gaussian patch weight
"""
patch_x, patch_y = np.meshgrid( np.arange(-(patch_shape[1]//2),patch_shape[1]//2+1), np.arange(-(patch_shape[0]//2),patch_shape[0]//2+1), sparse=False, indexing='xy')
patch_weight = np.exp(-(patch_x**2+patch_y**2)/(patch_sigma**2),dtype=_d... | ca4a70b10e13b46ff92b6dd4fc0fb84110b13e43 | 62,361 |
def grab(key, dictionary):
"""This is just a wrapper around the find function, getting a single item as opposed to the iterator."""
return [i for i in find(key, dictionary)][0] | 763560908d640fa933e0096144ada0f3772ed9b8 | 62,363 |
def eeg_rereference(eeg, reference="average", robust=False, **kwargs):
"""EEG Rereferencing
This function can be used for arrays as well as MNE objects.
EEG recordings measure differences in electrical potentials between two points, which means the
signal displayed at any channel is in fact the differ... | e0f98644808e9ce50e5b5acda31a2829e96b5544 | 62,364 |
import numpy
def extract_slits(slits, spline_x, im, order=2, padding=0):
"""
this function extracts the individual spectra from the MOS image using the
slit positions determined by get_slits. the slit positions are fitted using
a spline, padded with a zero mask and then extracted.
"""
y_dim, x... | 932ed0a79ada8c66a2500dce1b82ca86581fad3f | 62,365 |
from datetime import datetime
import logging
def jwt_auth(login: str, token: str, conf: dict) -> bool:
"""authenticate login against the given jwt token
The token must be valid.
Auth can be validated against 2 secrets: the current one and the old-one
This enable the possibility to change secrets more... | 3e01036f0df7db611fb4195d8810da19983c1331 | 62,366 |
from cp_banner import Banner
from cp_planoaquisanual import Planoaquisanual
from cp_procedimento import Procedimento
def main():
"""Funçao index"""
print('Init do main_route')
#window_id = str(get_window_id())
print('1')
#set_base_context(window_id)
print('2')
#ctx_dict = get_context(windo... | 850469e976deae46a4509a717640b0c8b469096c | 62,368 |
def _first_true_index(bools):
"""
Given a pandas Series of bools, returns the index of the first occurrence
of `True`. **Index-based, NOT location-based**
I.e., say x = pd.Series({0: False, 2: False, 4: True}), then
_first_true_index(x) will return index 4, not the positional index 2.
If no val... | 4d0cc2d2d3f53f5c73653aeafce7b6128a99d204 | 62,369 |
from datetime import datetime
def valid():
"""Проверить, валиден ли токен"""
json = request.get_json()
if "token" not in json:
return errors.wrong_payload("token")
token = json["token"]
actual_token = Token.get_or_none(
(Token.token == token) & (Token.token_type == "access")
... | 35ff542ebb226224b78d27fbfbd60257ccbc587e | 62,370 |
from typing import OrderedDict
def gather_sim_results(m, scenario, input_params_dict, is_dynamic_rcr=False):
"""
Gather dataframes and dictionaries into master results dictionary.
:param m:
:param scenario:
:param input_params_dict:
:param is_dynamic_rcr:
:return: Dictionary containing d... | 29ed909832d4b70136ad4e50ad51950ecae2b059 | 62,371 |
from networkx.algorithms.components import connected_components
from networkx import connected_component_subgraphs
def connect_components(graph, pos_attr, length_attr=None):
""" connects all components by iteratively inserting edges between
components that have minimal distance.
`graph` is a networkx... | 1f480044f999238af001a815e33b16324deb1d36 | 62,372 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.