content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from scipy.spatial.distance import pdist, squareform
import warnings
def make_anisotropic_grf_psf_params(ntrain, nvalidate, nvisualize):
""" Make training/testing data for PSF with params drawn from anisotropic Gaussian random field.
"""
bd = galsim.BaseDeviate(314159+2718281828)
ud = galsim.UniformDe... | 073a2fab6238025b833aafb0a1cf8188f8f93f99 | 71,100 |
async def list_(hub, ctx, resource_group=None, **kwargs):
"""
.. versionadded:: 4.0.0
Lists all of the SSH public keys in the subscription.
:param resource_group: The name of the resource group to limit the results.
CLI Example:
.. code-block:: bash
azurerm.compute.ssh_public_key.li... | e94096f4bec362e35ae162e6b617c2a447354e60 | 71,101 |
import itertools
def load_simulation_params():
"""
Loads Utilities/SimulationParams
get all params from simulation params file.
and create dataframe with all the combinations that can be.
:return:
"""
temp_obj = SimulationParamsOptions()
list_of_params = []
simulations_params_name... | 2f5e82a406c063cc8a5cc3a55663b5d4d22f4407 | 71,102 |
def Specgram(X, W, H):
"""A function to compute the spectrogram of a signal
:parm X: N x 1 Audio Signal
:param W: Window Size
:param H HopSize
:returns: S, an N x NBins spectrogram array
"""
Q = W/H
if Q - np.floor(Q) > 0:
print('Warning: Window size is not integer multiple of ho... | 4a6144f386f9e82fa167d0a6ce4c3e8ee3cfd31e | 71,103 |
def to_3d(pos):
"""Convert 2d coords to 3d numpy arrays by adding a 0 in the z coordinate.
Converts already 3d coords to numpy arrays.
Parameters
----------
pos : tuple, list, ndarray
The coords to be converted to 3d.
Returns
-------
numpy array
3d coords.
"""
... | 38529e389f9a104beb38fe51fce1393e7bac2f67 | 71,104 |
def new_subpart_added(amendment):
""" Return True if label indicates that a new subpart was added """
new_subpart = amendment.action == 'POST'
label = amendment.original_label
m = [t for t, _, _ in amdpar.subpart_label.scanString(label)]
return (len(m) > 0 and new_subpart) | 4cb16044fbc1a8d6d0f8e05ba9185f5e04a08037 | 71,105 |
from typing import Union
from typing import List
from typing import Dict
def parameterised_pose_from_pdbblock(pdbblock: str,
wanted_ligands: Union[List[str], Dict[str, Union[str, None]]] = (),
force_parameterisation: bool = False,
... | 9621fd75b58c56d5fec6a53d4a32c5fd803c0d9a | 71,106 |
def get_peer_owned_files(conn: database.sqlite3.Connection, session_id: str) -> list:
""" Get all the files owned by the given peer
:param conn - the db connection
:param session_id - the session_id of the peer
:param source - 1 if we are interest only to files added originally by the peer, 0 if we are interest onl... | 24d7dbec32754f7250e6c1fd15e771b61bc5496b | 71,107 |
def make_objective(model_path,
param_names,
param_types,
job_path,
prop_name,
metric,
dic_path):
"""
Make objective function that gets called by `hyperopt`.
Args:
model_path (str): directo... | 524acf7fedafda7b5232525aaac5d338b6742a62 | 71,108 |
def build_qat_retinanet(
model: tf.keras.Model, quantization: common.Quantization,
model_config: configs.retinanet.RetinaNet) -> tf.keras.Model:
"""Applies quantization aware training for RetinaNet model.
Args:
model: The model applying quantization aware training.
quantization: The Quantization co... | e867c19e1ae87d1cfe0e8bbcb7704ee9b0d2b329 | 71,109 |
def update_graph_b(start_date, end_date, relayoutData, option_slctd) -> pd.DataFrame:
"""Depending on date picker, subplot figure and dropdown components inputs, update pie figure graph."""
if option_slctd == "AAPL":
df_sentiments_sum = datafetch.df_tweets_aapl_sentiments_minute
if option_slctd == ... | 73eb92d8491c63bf095914e39a96f56eb38b3548 | 71,110 |
def get_embedding(cnn, A, X, PS_params):
"""
Gets the embedding of the graph described by A and X using
Patchy-San and network cnn
Parameters :
cnn : Convolutional neural network giving the embeddings
A : Graph adjacency matrix
Xs: Graph features matrix
PS_params : Patch... | 5a52b0f680b32105616c427dfccb2dc2393fb1c9 | 71,111 |
def allnotq(X):
"""
Helper function used in manual_feature_extraction
Parameters
----------
X
dataframe to subset
Outputs
-------
Subsetted dataframe with no proteins quantified
"""
applied = X.apply(lambda x: np.sum(x),axis=1)
bools = np.where(applied == 0)
return X.iloc[bools].index.tolist() | afca863cdd36396cceb95a3fd48e6433eccf30ae | 71,112 |
def func_1(x: float, a: float, b: float) -> float:
""" Test function. """
return x + a + b | 776ad7473aa52b16fcd759e376f5f47a51c73013 | 71,113 |
import async_timeout
import aiohttp
import asyncio
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Sensibo from a config entry."""
client = pysensibo.SensiboClient(
entry.data[CONF_API_KEY], session=async_get_clientsession(hass), timeout=TIMEOUT
)
device... | 3f1e1a4348f57579b39b62b26d3e169a761fb0a9 | 71,114 |
import os
def get_failed_pending_exp(cfg, experiments):
"""Get the list of expfolders that failed or are pending"""
failed = []
pending = []
for exp in experiments:
outputFolder = get_folder(cfg, exp)
oFile = os.path.join(outputFolder, outputFile)
sFile = os.path.join(outpu... | d1d2151368e47c716e40d0b0b40dc2db20b03615 | 71,115 |
def restart_hostagent(mac, **_):
"""
Ask a node to restart it's hostagent
Variables:
mac => mac address of the node
Arguments:
None
Data Block:
None
Result example:
{ "message_id": UUID } # UUID to look for in the
# control channel to get th... | b680ff1e9139fe12c3152fbbee15e8a101887e00 | 71,116 |
import socket
def get6addr(name):
"""Get IPv6 address for name. If necessary, an IPv4 over IPv6 address."""
try:
addr = socket.getaddrinfo(name, 'domain', family=socket.AF_INET6)
except socket.gaierror:
addr = socket.getaddrinfo(name, 'domain')
addr6 = '::ffff:' + addr[0][4][0]
... | 4ed93d37bf891b80a8a3ad0ff4eee3c1db643733 | 71,117 |
from typing import Optional
import os
import resource
def table(table_name: Optional[str] = None) -> boto3.dynamodb.table.TableResource:
"""Returns a DynamoDB table object.
The table takes its name from the `table_name` argument, or from the environment variable
"DYNAMODB_TABLE". If both are missing the ... | 2a0a805ecd60395d74ecc804a8df5c79256c3ff4 | 71,118 |
import random
def generate_appskey():
"""Generate a random secret key"""
return "".join("{:02X}".format(x) for x in random.sample(range(255), 16)) | bd80160df997209981214201a3fac779ca4cdd60 | 71,119 |
def get_filters_visualization(psi, J, L, mode ='fourier'):
""" Visualizes the scattering filters input for different modes
parameters:
psi -- dictionnary that contains all the wavelet filters
L -- number of orientation
J -- scattering scale
mode -- mode between fourier... | 35009c4a4a83fa85168b028c2f2add4cc11038ad | 71,120 |
import os
def get_local_magics_dir():
"""
Ensures that there is a ~/.ipython/metakernel/magics directory,
and returns the path to it.
"""
base = get_ipython_dir()
dname = os.path.join(base, 'metakernel', 'magics')
if not os.path.exists(dname):
os.makedirs(dname)
return dname | 6ecf2dddd71076be24d6c8e2b4e3568d056ba023 | 71,121 |
def unitchanger(unit):
"""
If unit is in unitdict, convert
otherwise, return the old unit
"""
if unit is None:
return None
lowerunit = unit.lower()
if lowerunit in unitdict:
return unitdict[lowerunit]
return unit | 6a1a6dcea7945d08a559b73a520c8d186693ac56 | 71,122 |
import os
import json
def load_qa_prod(inroot):
"""Load QA for a given production
Args:
inroot : str
filename without format extension
Returns:
odict : dict
"""
log=get_logger()
infile = inroot+'.json'
log.info("Loading QA prod file: {:s}".format(infile))
# R... | d24e6613e1bb77c91805845c1aa5fdf6427965ec | 71,123 |
from airflow.models import DagRun
def latest_dag_runs():
"""Returns the latest DagRun for each DAG formatted for the UI. """
dagruns = DagRun.get_latest_runs()
payload = []
for dagrun in dagruns:
if dagrun.execution_date:
payload.append(
{
"dag_... | d69704810f26f7ea0dbe96b1339ebf2481578973 | 71,124 |
def detect(
A, threshold, is_excessive, min_group_edge_num=0,
):
"""
CIDRE algorithm
Parameters
-----------
A : scipy sparse matrix
Adjacency matrix
threshold : float
The algorithm seeks the groups of nodes that have a
donor score or a recipient score larger than o... | c8c4dce7a0b4e0f6a5196860f526bb981b98fa58 | 71,125 |
def can_fast_forward(repo, c1, c2):
"""Is it possible to fast-forward from c1 to c2?
Args:
repo: Repository to retrieve objects from
c1: Commit id for first commit
c2: Commit id for second commit
"""
if c1 == c2:
return True
# Algorithm: Find the common ancestor
paren... | d1e7a4925d8ef44de325a2d3fb3d0d7548ecb675 | 71,126 |
import os
def update_fields(base_dict, fields_to_check, print_text, field_required,
check_type):
"""
For a subset of fields in a dictionary, prompts the user to provide updated
values.
Parameters
----------
base_dict : Dictionary
The fiducial dictionary we're updati... | 5a79a3d11e6c100f4ed9e5f983f610486e5a402f | 71,127 |
def get_sys_uptime():
"""
:return: (uptime, idle) in seconds
"""
f = open("/proc/uptime") # %f(uptime) %f(idle) , all in seconds
uptime = f.read()
f.close()
uptime, idle = uptime.split(" ")
return float(uptime), float(idle) | 71406d10728820680046a2137129a7410f16cd78 | 71,128 |
def calculate_image_precision(gts, preds, thresholds = (0.5, ), form = 'coco') -> float:
# https://www.kaggle.com/sadmanaraf/wheat-detection-using-faster-rcnn-train
"""Calculates image precision.
Args:
gts: (List[List[Union[int, float]]]) Coordinates of the available ground-truth boxes
pred... | fb6f232c3b7274b6281b912b48eb548a9b28ed37 | 71,129 |
from typing import List
from typing import Dict
def boolean_eval(exp: List[str], result: bool) -> int:
""" Counts the ways that parenthesis can be
arranged on exp that lead to result """
cache: Dict[str, int] = {}
return eval_amount(exp, result, cache) | e45a290873c6cd2a56073c6523f37fd0b648ba6f | 71,130 |
import json
def parse_fio_output_file(fpath: str) -> dict:
""" Read and parse json from fio json outputs """
lines = []
with open(fpath, 'r') as fiof:
do_append = False
for l in fiof:
if l.startswith('{'):
do_append = True
if do_append:
... | ce4efcd3f0508179971788a2c19a7f278d887a79 | 71,131 |
import platform
def is_win_platform():
"""
Checks if the current platform is Windows.
"""
WIN_PLATFORMS = ["windows", "cygwin", "cygwin_nt-10.0"]
return platform.system().lower() in WIN_PLATFORMS | c1e0eb0f57f69349c70470e6da13e687c1d72126 | 71,132 |
def get_full_name(participant):
"""Returns the full name of a given participant"""
return participant['fields']['First Name'].strip() + \
' ' + participant['fields']['Last Name'].strip() | 4292ea595d13e8093f6d221c40634e8fe74b8e91 | 71,133 |
def validator(req, template_name="buildmanager/validator.html"):
"""Validate an xform"""
def get(req, template_name):
return render_to_response(req, template_name, {})
def post(req, template_name):
xform_body = req.POST["xform"]
hq_validation = True if "hq-validate" in req.... | 19f5adf3d07d150e16bcfa4ccc7bb3c7761b1794 | 71,134 |
def config():
"""Get test config, extend to several scenarios"""
model = PowerLaw(
index=2, amplitude=1e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV
)
pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs")
radius = Angle(0.11, "deg")
on_region = CircleSkyRegion(pos, radius)
f... | 940b1820d336d9f8caec8775a279c824d6ca7bcf | 71,135 |
def create_vpc(client, tag_name, cidr):
"""Method to create vpc based on the cidr and tag with tag_name.
Args:
client (boto client): Region specific boto client
tag_name (str): VPC tag name
cidr (str): CIDR string.
Returns:
VPC(Object): Newly created VPC object.
"""
v... | c572e97e2b28f6694b7d9ebb2921e53bbcdcab04 | 71,136 |
def sendHelp():
"""construct the help message to send to the user"""
message = "**Voilà un petit rappel des commandes que tu peux utiliser avec le PoGoBot en remplacant les valeurs `surlignées` : **\n*Ex: `pokemon` => pichu* \n\n"
for name, command in commandex.items():
message += str("**%s :**\t\... | 5796d23b8fd9e682366c2edbe11b870ebba48870 | 71,137 |
def tf_expm_dynamic(A, acc=1e-5):
"""
Matrix exponential by the series method with specified accuracy.
Parameters
----------
A : tf.tensor
Matrix to be exponentiated.
acc : float
Accuracy. Stop when the maximum matrix entry reaches
Returns
-------
tf.tensor
... | 0427f2366db06ffd9d88ad02350b288fdf31693a | 71,138 |
def minutes(m):
""" Create a time interval representing m minutes"""
return pd.tseries.offsets.Minute(m) | 3eb7200cfe21eae1e19b9619b8b67c0512a1d115 | 71,139 |
import math
def breit_wigner_random(rnd, mean, gamma) :
"""
Random Breit-Wigner distribution with specified mean and width
"""
rval = 2.*rnd - 1
displ = 0.5*gamma*atfi.tan(rval*math.pi/2.)
return mean + displ | 6c2d3a5b0e6201ee6d18bb766bb3f352dbb07460 | 71,140 |
def ftoj(instr):
"""
instr must be unicode
"""
return instr.translate(f2jtable) | 7655d82a4ed27ce5e002e07b5dd1704c646f95b4 | 71,141 |
def read_file(path: str) -> str:
"""Read a file and return its contents."""
try:
with open(path, encoding="ascii") as f:
return f.read()
except FileNotFoundError:
raise HERAError('file "{}" does not exist'.format(path))
except PermissionError:
raise HERAError('permiss... | cd3ea25915c265da487052862020d097fd231bc9 | 71,142 |
def WER(x, y):
"""
x, y : list of words for one sentence
output : wer
"""
d = np.zeros(((len(x) + 1), (len(y) + 1)), dtype='float32')
for i in range(len(x) + 1):
for j in range(len(y) + 1):
if i == 0:
d[0][j] = j
elif j == 0:
d[i]... | d29468d5f0a3e164600918c8c35d685c6f7729aa | 71,143 |
def get_gdrive_refresh_token(email):
""" Get user credentials from database
"""
print "inside get_gdrive_access_token() \nemail = ", email
# Get the refresh token from the DB
refresh_token = get_gdrive_token(email)
# print "refresh_token form db = ", refresh_token
if refresh_token:
return refresh_token
pr... | bcebbe0e05ef54a6ddd685beda63042f3af26a76 | 71,144 |
def generate_private_key(filename):
"""Generate private key.
:param filename: Path to generated private key.
"""
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend(),
)
alg = serialization.NoEncryption()
with open(filename, "wb")... | 8da108b8e84635da54e4382d49759f2bab4a87b0 | 71,145 |
import re
def user_has_harvard_email(failure_url='non-harvard-email'):
"""
Decorator to forward user if they don't have Harvard email. E.g.:
@user_has_harvard_email()
def my_view(request):
"""
return user_passes_test(
test_func=lambda u: bool(re.search(r'[.@]harvard.edu$',... | d26ccfe3e3d926b6a197364cbf047c1d90e7ff79 | 71,146 |
def create(large_person_group_id, name, user_data=None):
"""Create a new person in a specified large person group. A newly created
person have no registered face.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
name: Name of the created per... | ce7a09fb554bedc40f87e26c124f76bcf2c98476 | 71,147 |
import os
def segment(im, model_path, pad=0):
"""
Function which takes a list of network outputs and returns an upsampled classification map suitable for plotting
:return: upsampled classification map
"""
model_xml = model_path
model_bin = os.path.splitext(model_xml)[0] + ".bin"
# Plugin... | 70c161b8fef0e7235a60a12b09f63b7485a559b5 | 71,148 |
import time
def get_today_zero_time(now=time.time()):
"""
:param now: 时间轴
:return: 传入时间轴当天的零点时间轴
"""
midnight = now - (now % 86400) + time.timezone
return long(midnight) | 0f995cdf8f87ae30d2e3ab376868284f34206f98 | 71,149 |
def _get_categories_at_tier(project: Project, *, tier: int) -> set:
"""
Extracts categories at tier from a taxonomy associated with Project
Args:
project: Tamr project object
tier: integer specifying the tier to extract the categories;
-1 will return all leaf categories
R... | fa4e7515db8a9804393209352f6ac9ff7ef6621b | 71,150 |
import torch
def calc_squared_dice_loss(input, target, weight=None, eps=0.001):
"""Calculate the squared dice loss
Args:
input (torch.Tensor): The input tensor
target (torch.Tensor): The target tensor
eps (float): The smoothing term preventing division by 0
Return:
dice (... | dbb565861c90f8d505f227869574e9ba8120b8e9 | 71,151 |
import logging
def get_all_coins(client=None):
"""
Returns a dataframe of all available coins on Binance.US
"""
if client is None:
logging.info("No binance client found, attempting to establish connection.")
client = BinanceClient()
coins = client.get_all_tickers()
coins... | 194c4024f906f39775b1806dfbd7a981394654e8 | 71,152 |
def moveToPoseConstV(current_x, current_y, current_angle, current_V,
desired_x, desired_y, desired_angle,
k_alpha, k_beta, wheelbase):
"""Implements a simple proportional controller for Move to Pose
For stability with Ackermann style steering (bicycle model):
k_... | 9b1641fea54fd8935cc8dbbbe772cd9cf7b56739 | 71,153 |
def ioa(boxlist1, boxlist2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxl... | 4c16cf0ca8cf09a333f8ee520cdd716d609abe55 | 71,154 |
from typing import Iterable
from pathlib import Path
from typing import MutableMapping
from typing import Any
def read_toml_multi(filenames: Iterable[Path]) -> MutableMapping[str, Any]:
"""Read and parse multiple experiment configuration files with 'toml'."""
config: dict[str, Any] = {}
for filename in fi... | 3b7923288f147d124ae2640b06caec84387f4d2d | 71,155 |
import re
def join_list_item_to_content(snts):
"""
Evaluates a list of sentences to determininne if an itemized list is
present and then puts the number and list time into the same element of
the list.
:param snts: list of report sentences.
:return: List of sentences where list item and number... | 4cc33b7e9ab65c18b9dc0d587838bd5d56e9ffb6 | 71,156 |
def find_new_values(data, values, key):
"""Identify any new label/description values which could be added to an item.
@param data: the contents of the painting item
@type data: dict
@param values: the output of either make_labels or make_descriptions
@type values: dict
@param key: the type of v... | db56c07aedb38458be8aa0fc6bc4b5f4b49b4f4d | 71,157 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import os
def _getTableImage(
url, filename="dummy_table", path=".", delay=3, height=420, width=800
):
"""Render HTML file in browser and grab a screenshot."""
options = Options()
options.add_argument("--... | 73a2dde59e9cddc50d471e086d8a366be55d2c9a | 71,158 |
def positional_encoding(pos, model_size):
""" Compute positional encoding for a particular position
Args:
pos: position of a token in the sequence
model_size: depth size of the model
Returns:
The positional encoding for the given token
"""
PE = np.zeros((1, model_size))... | c80d9dfb128d635d078e9f9b4ff38ceb9cbdd2ff | 71,159 |
def get_triples_from_bel_commons(network_id: str) -> np.ndarray:
"""Load a BEL document from BEL Commons by wrapping :func:`pybel.io.tsv.api.get_triples`.
:param network_id: The network identifier for a graph in BEL Commons
:return: A three column array with head, relation, and tail in each row
"""
... | b2d3e3d8dda74ad7886ce71a6bd9ae004f3560b2 | 71,160 |
from typing import Callable
def call_tf_no_ad(tf_fun: Callable, arg, *, result_shape):
"""The simplest implementation of calling to TF, without AD support.
We must use hcb.call because the TF invocation must happen outside the
JAX staged computation."""
def tf_to_numpy(t):
# Turn the Tensor to NumPy arr... | df423106f5e9d81427bd5ae26e388e3da9d83267 | 71,161 |
def evaluate_offsets(edges_list):
"""
Takes edges of rails graph with "Offsets" on Beziers, turns offset points into new
control points, finds new top control point (using curve tangents)
Uses: abstract_geometry.narrow_bezier()
Input: rails graph with "Offsets" (list of pythonic dicts)
Output: ... | d1293b3338602d237a9ca0e6de7e910871f5780d | 71,162 |
def _len_sans_ansi(text):
"""Computes the length of a string that might contain ANSI codes.
"""
return len(ANSI_ESCAPE.sub('', text)) | 3c5bca252c8068e00baaa2571e5a4d3cc8d22c00 | 71,163 |
def sceneViewer():
""" Returns an existing open Scene Viewer pane if there is one. A
Context viewer is also acceptable is no dedicated scene viewer
is found.
"""
return hou.SceneViewer | 3f75c04d35a5c7b9822a31c4e9926993a244320a | 71,164 |
import re
def _remove_handles_from_text(text: str) -> str:
"""
removes userhandles. ex: @JohnDoe
"""
return re.sub(r'(@[\w]*)', '', text) | c8f507d58d32ee3c1f38301255cd68fc2e36c666 | 71,165 |
import time
def inference_simple(cfg, blobs, net, num_test=10, scope=None, test_image=None, **net_args):
"""
Assumes blobs[i] is a list of blobs (crops).
Returns inference[i] = list of results for each crop.
"""
net.init_placeholders(**net_args)
if scope is None:
net.create_architectur... | 59441b00e9d1b1b48b35ebba812e2a4736e84420 | 71,166 |
def load_backends(backends, force_load=False):
"""
Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
be imported and cached on BACKENDSCACHE. The key in that dict will be the
backend name, and the value is the backend class.
Only subclasses of BaseAuth (and sub-classes) ar... | 6e75e433fb3075569e00e6321a6a341d9d4a8ef6 | 71,167 |
from typing import Dict
def hausdorff_surface_distance(y_pred: itkImage, y_ref: itkImage) -> Dict[str, float]:
"""Compute symmetric surface distances between two binary masks
Args:
y_pred (itkImage): predicted segmentation
y_ref (itkImage): reference segmentation
Returns:
Dict[st... | 97c0c6c35e78fc0ee2595068586133d3a6da3049 | 71,168 |
def get_user_by_email(email):
"""Return a user by email."""
return User.query.filter(User.email == email).first() | a880409a65e1d1d3790caacd64089bec5e5f5a00 | 71,169 |
import typing
from typing import OrderedDict
def order_by_dependencies(dependency_mapper: typing.Dict[str, typing.Set[str]]) \
-> typing.Tuple[typing.List[str], typing.List[str]]:
"""
You have to make sure there's no cycle dependency.
"""
ordered_dict = OrderedDict()
for _ in range(1000):
... | 23bc887549a722612180b6720adaf4925e886752 | 71,170 |
def getattritem(o,a):
"""
Get either attribute or item `a` from a given object `o`. Supports multiple evaluations, for example
`getattritem(o,'one.two')` would get `o.one.two`, `o['one']['two']`, etc.
:param o: Object
:param a: Attribute or Item index. Can contain `.`, in which case the final value ... | 7b928b2405691dcb5fac26b7a3d7ebfcfa642f6d | 71,171 |
from xml.dom import minidom
def load_mountpoints(fpath):
"""Load mount points mapping from file
:fpath, file path to load
"""
if not fpath:
return
mount_maps = []
with open(fpath, 'r') as rf:
dom = minidom.parse(rf)
imgroot = dom.documentElement
for part in imgroot.g... | 06b11ddcec1d10addfa4ffa3dcd4c5a3ea4e2a9c | 71,172 |
def mesh2array(x_mesh, y_mesh):
"""Mesh to array converter.
Parameters
----------
x_mesh : array, shape = [n_samples, n_samples]
The x_axis mesh.
y_mesh : array, shape = [n_samples, n_samples]
The y_axis mesh.
Returns
-------
inputs : array, shape = [n_samples, 2]
... | d5905163ae884294c0d0d08e919888b5e44bca2b | 71,173 |
def publish_started(not_published, publishing_ip, manager):
""" Publish started services.
"""
publish_stats = []
for service_name in not_published:
def published_hook(sname):
publish_stats.append((sname, True, ["Published"]))
def already_published_hook(sname):
... | e1ee64e10a312bab8e5552689fce56f608ce7b51 | 71,174 |
def simplex_proj(y):
"""Projection of y onto simplex."""
m = len(y)
bget = False
s = sorted(y, reverse=True)
tmpsum = 0.0
for ii in range(m - 1):
tmpsum = tmpsum + s[ii]
tmax = (tmpsum - 1) / (ii + 1)
if tmax >= s[ii + 1]:
bget = True
break
... | 3c811f9c95629006b3f55db377ba42e84ba0b5a5 | 71,175 |
import logging
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Elgato Key Light from a config entry."""
session = async_get_clientsession(hass)
elgato = Elgato(
entry.data[CONF_HOST],
port=entry.data[CONF_PORT],
session=session,
)
# ... | 4cc7f19b955c4ffcb3773705c623caf5b8139b40 | 71,176 |
import re
def normalize_str(text: str) -> str:
"""Normalize str: Remove accent and white spaces from string and convert it into lower case."""
text = re.sub(r'\s+', '', text)
text = text.lower()
return remove_accent(text) | 8eb63a8f1fb70cbe582b0b94b7420334903d430a | 71,177 |
def filter_by_intersection_percent(df: gpd.GeoDataFrame,
geo: Polygon,
min_percent_overlap,
relative_to='geometry') -> gpd.GeoDataFrame:
"""Intersection area relative to dataframe or geometry"""
df_utm, geo... | f1667a024c058a61605433afabb4f2bd3cf17938 | 71,178 |
def handle_top():
""" app_page.route('/') """
return flask.redirect(flask.url_for("app_bp.handle_astutus")) | ffee1a670e3e70ad6fd4e783384746ea74191094 | 71,179 |
def parse_pdb(pdb_fname, base_fname=None):
"""Returns a graph object with available connectivity information"""
trj = md.load(pdb_fname).center_coordinates()
G = make_bondgraph(trj.top)
connect_dict = get_pdb_connect_dict(pdb_fname)
if len(connect_dict) != trj.top.n_atoms:
raise ValueError(... | 4d407f4c4e93945c92538a82baf2de2fe95e4f92 | 71,180 |
def _find_last_notified(location):
"""Find when an update for location was previously notified.
Returns notification time as datetime object or None if never notified.
"""
doc_ref = get_db().collection("locations").document(location)
doc = doc_ref.get()
if not doc.exists:
return None
... | 51c1f1d9eb19e2009c654c3bd6fecff96de1a50e | 71,181 |
from math import floor
def conv_output_shape(h_w, kernel_size=1, stride=1, padding=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
if type(kernel_size) is not tuple:
kernel_size = (kernel_size, kernel_size)
... | 847899bba14ea18f2f0657c8c0e8b3b9cbf5327d | 71,182 |
def wgan_generator_loss(gen_noise, gen_net, disc_net):
"""
Generator loss for Wasserstein GAN (same for WGAN-GP)
Inputs:
gen_noise (PyTorch Tensor): Noise to feed through generator
gen_net (PyTorch Module): Network to generate images from noise
disc_net (PyTorch Module): Network to ... | 090de59ebc8e009b19e79047f132014f747972e7 | 71,183 |
def similarity(a, b):
"""
Returns the similarity between two strings.
Parameters
----------
a : str
String a
b : str
String b
Returns
-------
float
Similarity score (between 0-1)
"""
return SequenceMatcher(None, a, b).ratio() | 67bfea8333a489d130d2f10beb10ea12edd8f25d | 71,184 |
def add_parameter():
"""Add update user snmp info parameter"""
argget = utils.create_common_parameter_list()
add_helpmessage(argget)
args = argget.parse_args()
parameter_info = utils.parse_parameter(args)
parameter_info["username"] = args.username
parameter_info["authentication_protocol"] = ... | 3d5fd4720869c5a41bc6d6a12f021d776876da67 | 71,185 |
def find_project_root_and_manifest(project_items):
""" Given the contents of an archive, find a valid Pebble project.
:param project_items: A list of BaseProjectItems
:return: A tuple of (path_to_project, manifest BaseProjectItem)
"""
SRC_DIR = 'src/'
invalid_package_path = None
for item in ... | 119130f1e8b1c9d86c7558c313ec302962f85af0 | 71,186 |
import torch
def load_extended_vae(model_path, model_args, device=None, optimizer=None):
"""
Load the checkpoint of the extended model.
Args:
model_path: Path to the .pt checkpoint
model_args: Args to pass to the model class (kwargs are saved in the checkpoint)
device: Device of t... | 626bea17a047894766893e212293bcbdcc6c9158 | 71,187 |
def get_date_object(date = None):
"""takes an optional string date and returns a date object
if no argument a date object is returned with today's date"""
if date is None:
return dt.date.today()
if not isinstance(date, str):
raise TypeError('Input must be string')
date_obj ... | ac1c693fdae5503878d314c43cbc788aa9972826 | 71,188 |
import logging
from datetime import datetime
def update_uptime_status():
"""
Perform Periodic Update to Uptime Status in ES
"""
logger = logging.getLogger("utils.uptime.update")
logger.info("Start uptime check...")
def check_status(doc):
api = API(doc)
api.check_api_status()
... | 1cb447017efc585e7ef61a98b04421c76bbcf775 | 71,189 |
import iso3166 #dbg
def _is_country(code):
"""
"""
if _is_region(code):
return False
if _is_income_level(code):
return False
try:
iso3166.countries.get(code.lower())
except:
if not in 'JG'
print '%s not in iso!?!' % code
return True | 40e70f53a6e1257ec47c4123b19d59360aed2157 | 71,190 |
def init_falff_wf(workdir=None, feature=None, fwhm=None, memcalc=MemoryCalculator()):
"""
Calculate Amplitude of low frequency oscillations(ALFF) and
fractional ALFF maps
Returns
-------
workflow : workflow object
ALFF workflow
Notes
-----
Adapted from
<https://github.c... | ac9429bef0b8d3f67d2acea2d74ac54ef055be81 | 71,191 |
def checkHistColumn(existingColNames):
"""
Check for the Histogram column in the attribute table. Return
its column number, and raise an exception if it is not present
"""
histColNdx = -1
for i in range(len(existingColNames)):
if existingColNames[i] == 'Histogram':
histColNdx... | 345311332f5522341b54670c1d626fd970b58b38 | 71,192 |
def findLocsAtTime(assignments=None, timeSec=0.0):
"""
Finds the estimated location of each unique `objectID` in an input `assignments` dataframe at the given time. The output is a dictionary, where the keys are unique objectIDs. The corresponding value for each `objectID` key will be `None` if the object is not de... | 55eec9647ed154e66fa10f8fdf7880bcb3ae087f | 71,193 |
def esm1_t34_670M_UR50D():
"""34 layer transformer model with 670M params, trained on Uniref50 Dense.
Returns a tuple of (Model, Alphabet).
"""
return load_model_and_alphabet_hub("esm1_t34_670M_UR50D") | 451ad13716c147db3e53cdc74d6400290ff36e58 | 71,194 |
def remove_db_connection(profile_id, connection_id, web_session=None):
"""remove a db_connection by disassociating the connection from a profile
Args:
profile_id (int): The id of the profile
connection_id (int): The connection id to remove
web_session (object): The webserver session obj... | 64e42f5f96faa6b1883d19b0feb009ed89ed2497 | 71,195 |
def generate_model(**kwargs):
"""
Get ResNet3D with GloreUnit neural network.
"""
model = ResNet3D(Bottleneck, [3, 4, 6, 3], [64, 128, 256, 512], **kwargs)
return model | fd21e2346caaf5e82e7ef3d2814b5c8672bcea98 | 71,196 |
def cache_predict(smiles, model):
"""
use cache data for the same smiles
"""
mol = Chem.MolFromSmiles(smiles)
graphs = mol2dgl_single([mol])
test_bg = dgl.batch(graphs)
test_bg.set_e_initializer(dgl.init.zero_initializer)
test_bg.set_n_initializer(dgl.init.zero_initializer)
hidden = ... | 6b00a974b8a5dd8062c256404e1bf4953a98444e | 71,197 |
import os
def create(
context: "definitions.Context",
selection: "definitions.Selection",
reinstall: bool = False,
):
"""
Assemble the contents of the bundle folder for zipping.
This copies the entire contents of the project folder to a temporary location
and then installs and bundles the... | fa1a27c42f24c1f82214febda92589db8438ff9d | 71,198 |
def makeItemList(pymarcResults, lib, lCode):
"""input: pymarc. return: list of config'd marc fields"""
lItem = []
try:#Extract the fields we want from the result set. Some fields we want may be unavailable
for r in pymarcResults:
lItem = []
lItem.append(lib)#the library sym... | a3de6fcc290cf8e60594113c4322f8781e39b218 | 71,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.