content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import socket
def get_local_usable_addr():
"""Get local usable IP and port
Returns
-------
str
IP address, e.g., '192.168.8.12:50051'
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
sock.connect(('10.255.255.255'... | d7dfb57a755c5f96ae2e1e5864d5e6b66d45e2cd | 66,300 |
def create_example_randomizer_cata() -> DomainRandomizer:
"""
Create the randomizer for the `CatapultSim` used for the 'illustrative example' in F. Muratore et al, 2019, TAMPI.
:return: randomizer based on the nominal domain parameter values
"""
return DomainRandomizer(
BernoulliDomainParam... | 6909e7b28454a3343d92ac5a6ce3af680216a85b | 66,301 |
def boost_with_rotation_to_lab(four_vecs, rot, inv_rot):
"""rotated back, boost the 4 vecs, rotate again
very ugly..
"""
arr = []
for fv, rotation, inv_rotation in zip(four_vecs, rot, inv_rot):
e = fv.item(0)
p = fv[:, [1, 2, 3]]
p = inv_rotation * p.T
fv = np.mat... | 496748f52cc4689020e48d83ce9cde3426aea043 | 66,302 |
import itertools
def powerset(iterable):
"""All *nonempty* subsets of an iterable.
From itertools docs.
powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
"""
s = list(iterable)
return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(1, len(s)+1)) | 875e4cacc9f1abf92604e89c7a6211e571150b69 | 66,303 |
import base64
def __decode(encoded, n):
"""
decode the string
"""
token = encoded.split(":")[0]
for _ in range(0, n):
token = base64.b64decode(token)
return token | 9ac3ba6da27ae255117b25c5f1c61f35d06c2c2e | 66,304 |
def _exact_instance_filter(query, filters, legal_keys):
"""Applies exact match filtering to an Instance query.
Returns the updated query. Modifies filters argument to remove
filters consumed.
:param query: query to apply filters to
:param filters: dictionary of filters; values that are lists,
... | ffa8e827903e3400f1c0aa0273bb0714827891e0 | 66,305 |
import numpy
def smooth_waterfall(arr,fwhm=4.0,unsharp=False):
"""
Smooth a waterfall plot.
If unsharp set, remove the smoothed component
Input array should have dimensions [timelen, nbolos]
"""
timelen,nbolos = arr.shape
kernel = numpy.exp(-numpy.linspace(-timelen/2,timelen/2,timelen)*... | 849b144a63b1209523e588724531e5cd24269e76 | 66,306 |
def load_graph_from_ckpt_file(weights_path):
"""
:param weights_path:
:return:
"""
# construct compute graph
input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 512, 512, 3], name='input_tensor')
net = resnet_fcn.ResNetFCN(phase='test', cfg=CFG)
prediction = net.inference(
... | 91dfc03a5cf62b0624b97660b5daa6532beefeb0 | 66,307 |
from typing import Dict
async def get_backend_auth_headers(session: ClientSession) -> Dict[str, str]:
"""
Authenticates with the OC Backend server
:return: Authorization header containing the returned JWT
"""
async with session.post(
f"{BACKEND_URL}/auth/login/",
json={"email": B... | 72e6d9bb9c8467f7e5cd1379b5ae3ad8b7aab64e | 66,308 |
from typing import Tuple
from typing import List
def _get_package_names_for_distribution(
distribution_path: str,
) -> Tuple[List[str], str]:
"""Get the top-level import names and project name for a given distribution file path
Args:
distribution_path: Path to the .whl, .tar.gz, or .zip file cont... | 866046a8f23d5c80534cbb500fb875efd42c2fa7 | 66,309 |
def find_geom(geom, geoms):
"""
Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of `in` operator.
"""
for i, g in enumerate(geoms):
if g is geom:
return i | 2c2c9c2230ae745b6a781337192c694ba4ba4c59 | 66,310 |
def calculate_saliency_map(model: Model, data: np.ndarray, c: int, dependencies=None, normalise=True) -> np.ndarray:
"""
https://arxiv.org/abs/1312.6034 - saliency maps
https://arxiv.org/abs/1706.03825 - smoothed version
Calculates saliency map / vanilla gradient for feedforward neural network. Calculat... | 0e0f841995236ce0e2adf36960dc4232a0fd0333 | 66,311 |
from typing import List
from typing import Tuple
def cluster_state(m: int, n: int, inputs: List[Tuple[int,int]]=[]) -> BaseGraph:
"""Build a cluster state m qubits tall and n qubits wide. Optionally, give a list of grid positions
which serve as inputs."""
g = Graph()
vs = [[g.add_vertex(VertexType.Z, ... | 09e338650bcc040f02db7b9d7ee6fc171137ed43 | 66,312 |
def add_two_numbers(value1: int, value2: int) -> int:
"""Method to add two add_two_numbers
ARGUMENTS:
Value1: first value
Value2: second value
"""
try:
return value1 + value2
except TypeError as error:
print('Error at add_two_numbers()', error)
exce... | de4c3b1bd5ebd69fd2ff1dbc63a411f875841d8e | 66,313 |
def summary_table(params, proteins):
"""
Returns a string representing a simple summary table of
protein classifcations.
"""
out = ""
counts = {}
for seqid in proteins:
category = proteins[seqid]['category']
if category not in counts:
counts[category] = 1
... | 1fa3f16f799964bf9f1c0f1c593020902ab2219f | 66,314 |
def add_leading_zeroes( number, digits ):
"""
adds leading zeroes to fill up the digits.
"""
number = int( number )
string = str(number)
i = 1
while i < digits:
if number < 10 ** i:
string = '0' + string
i += 1
return string | 4437a3f930f5947ae749f34a07edd1a68fc6e077 | 66,315 |
def instance_has_unpaused(instance, log_files, alarms, event_logs, alarm_history,
start_datetime, end_datetime, action=False,
guest_hb=False):
"""
Returns true if the instance has unpaused
"""
success, reason = instance_is_running(instance)
if not ... | e8afd87130bad0a2a923c6c1555bab82694d85d2 | 66,316 |
def foreign_key(other_table, nullable=False):
"""
Declare a foreign key property, which will also create a foreign key column in the table with
the name of the property. By convention the property name should end in "_fk".
You are required to explicitly create foreign keys in order to allow for one-to-... | ff837bf20ab423772dce93dec88a9b83857cacb5 | 66,317 |
def propertize(fieldKeyName):
"""Transforms a string into an Python parameter name
"""
return stringcase.snakecase(fieldKeyName) | 4b8b463953500ce0a3848e70709bbbda7817f4fd | 66,318 |
from datetime import datetime
def get_default_datetime():
"""
A hook to help with mock data testing - put the default datetime
right in the middle of the "current" term.
"""
if is_using_file_dao():
term = get_current_term()
first_day = term.first_day_quarter
default_date = ... | 7b97bebb400653f91139ace6b5cdda1961a7f38f | 66,319 |
def get_map(nmers, vocabulary, vectors=None, mapping='random'):
"""
Prep and get a map.
"""
N = len(nmers)
W = len(vocabulary)
if W < N:
print 'ERROR: Not enough words.'
return False
if W > N:
print 'There are', W, 'elements in the vocabulary and only', N,
pri... | c6de0401bb1030fc4135c79c24ebbc894b7e1156 | 66,320 |
def diapreresnet110_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-110 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
pretrained : bool, de... | baf61449f48a25c85e98dcdeef6107652d676e7a | 66,321 |
from typing import Sequence
def pad_image_to_shape(img: npt.ArrayLike, new_shape: Sequence, mode: str = "constant"):
"""Pad all image axis up to specified shape."""
for i, dim in enumerate(img.shape):
if dim < new_shape[i]:
pad_size = (new_shape[i] - dim) // 2
img = pad_image(i... | 87652efad525263b428be4347cab18c76cae30e0 | 66,322 |
import six
import os
def DataIterator(data, checklines=10, transform=None,
force_dialect_check=False, from_string=False, **kwargs):
"""
Iterate over features, no matter how they are provided.
Parameters
----------
data : str, iterable of Feature objs, FeatureDB
`data` can... | 06111090f66c97c519608fd61d2c4bc10c514dc3 | 66,323 |
import PIL
def is_corrupt(jpegfile):
"""Returns None if the file is okay, returns an error string if the file is corrupt."""
# http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted/1401565#1401565
try:
im = PIL.Image.open(jpegfile)... | bf0b284e2df49c079f1cc260d492aca963fba6a5 | 66,324 |
from apex import amp
def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[int, float]:
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
def ... | 89e16027e0eeef4d69323354977357b705375137 | 66,325 |
import math
def is_valid_sample_rate(rate):
# type: (Any) -> bool
"""
Checks the given sample rate to make sure it is valid type and value (a
boolean or a number between 0 and 1, inclusive).
"""
# both booleans and NaN are instances of Real, so a) checking for Real
# checks for the possib... | 77542d10f7c379d565dcf3e66bc2cd5e22322d3f | 66,326 |
import random
def random_password():
"""
随机生成一个8位的数字的字符串
:return:
"""
password = ""
for i in range(8):
password += str(random.randint(0, 9))
return password | d7f83d4e01c79166d6b116c40622c82148252c30 | 66,327 |
import functools
import time
def log_service_time(func):
"""Loga o tempo para o serviço da requisição. Nenhuma exceção relacionada
a medição deve causar erro no serviço da requisição.
"""
@functools.wraps(func)
def wrapper(req):
start_time = time.time()
result = func(req)
e... | 588ce561ce7c47eb72fe207f116698b014c4bf0c | 66,328 |
def partition_to_lists(items, predicate=bool):
"""
Partitions an iterable into two different lists - the first does not match the given condition, and the second
does match the given condition.
Args:
items (iterable): An iterable of items to partition
predicate (function): A function th... | 1c2fe99b8ae7972738ca9028b65135bbfd1dab83 | 66,329 |
def on_board(i, j):
"""Return True if the location is on board
>>> on_board(0,0)
True
>>> on_board(-1,17)
False
"""
return 0 <= i < 8 and 0 <= j < 8 | 107f9e614c965b29c0c872738fd4ea5407971a29 | 66,330 |
def multiplicative_inverse(e, phi):
"""
Euclid's extended algorithm for finding the multiplicative inverse of two numbers
"""
d, next_d, temp_phi = 0, 1, phi
while e > 0:
quotient = temp_phi // e
d, next_d = next_d, d - quotient * next_d
temp_phi, e = e, temp_phi - quotient *... | 9934f6e2f86ff0ef4165728d59f11ba0d1cad928 | 66,331 |
def check_contradiction(statement1, statement2):
"""
Check if two statements are contradictory ignoring the time dimension.
:param statement1: the first statement
:param statement2: the second statement
:return:
"""
if not (statement1.arguments[0][0].startswith("e")
and statement... | fa0a485d68ece3a6ead3c41a017b58926273f42d | 66,332 |
def sort_models_by_encoding(models_list: list) -> list:
"""
Sort models by the encoding that will be used
:param models_list: unsorted list of models
:return: list of models sorted by encoding
"""
encodings = [get_mapping_name_to_class()[model_name].standard_encoding for model_name in models_l... | a45fea6ce8aa9f166340a0c1d181a1d06db1a7d9 | 66,333 |
import os
def make_path(relative_path, root=None):
"""
Get a complete path to a downloaded data file.
"""
root = root or DEFAULT_ROOT
return os.path.join(root, relative_path) | 7ddf01f78b2eadb84e7719a02937b6cba74d06c7 | 66,334 |
import time
def runtime():
"""Gibt die Zeit in Seknden zurück, die das
Script bereits läuft."""
return time.time() - START_TIME | db31d5a6efb17c0f07007e9d1aae7d55b95feac1 | 66,335 |
async def set_bot_stats_api(request: Request, bt: BackgroundTasks, bot_id: int, api: BotStats, Authorization: str = Header("INVALID_API_TOKEN")):
"""
This endpoint allows you to set the guild + shard counts for your bot
"""
id = await db.fetchrow("SELECT bot_id, shard_count, shards, user_count FROM bots... | 5bb1287f81a06cfe5a98daf2f8ccae45ac91a388 | 66,336 |
def rate_limit(task_name, rate_limit, destination=None, **kwargs):
"""Set rate limit for task by type.
:param task_name: Type of task to change rate limit for.
:param rate_limit: The rate limit as tasks per second, or a rate limit
string (``"100/m"``, etc. see :attr:`celery.task.base.Task.rate_limit`... | 5a1d1595bc39bcf59ee4c6884ad63980ff21e6dd | 66,337 |
def allsensors():
"""Page for viewing all sensors."""
data = Sensor.query.all()
# data = Sensor.query.filter_by(name='*').all()
script_root()
if data:
return render_template('public/allsensors.html', data=data, request=request)
else:
return render_template('404.html') | e9ef29012fbebf114bc124a1bc8cd5abf33efbef | 66,338 |
def _Py_ISUPPER(ch):
"""
Equivalent to the CPython macro `Py_ISUPPER()`
"""
return _Py_ctype_table[_Py_CHARMASK(ch)] & _PY_CTF.UPPER | 803ffb2d495fa002d2b3a3afbfffa5541709eaaa | 66,339 |
def get_h_inv(z_val, OM=0.27, OL=0.73):
"""Integrand for calculating comoving distance.
Inputs:
z_val -- redshift value integrand is evaluated at.
OM -- matter density parameter. Defaults to 0.27.
OL -- dark energy density parameter. Defaults to 0.73.
"""
OK = 1.0 - OM - OL
H = np.sq... | 550086c79ad295382d614f29d659b028cd50d2a2 | 66,340 |
def AttachProcess(pid, event_id):
"""
Attach the debugger to a running process
@param pid: PID of the process to attach to. If NO_PROCESS, a dialog box
will interactively ask the user for the process to attach to.
@param event_id: reserved, must be -1
@return:
- -2: im... | de6b66ac1b121cba50246cd14d1c8d640402847b | 66,341 |
def get_configured_interfaces(xml_filter):
"""
Main method that retrieves the interfaces from config via NETCONF.
"""
with manager.connect(host=HOST, port=PORT, username=USER,
password=PASS, hostkey_verify=False,
device_params={'name': 'default'},
... | 87d114dabca85c00142bc5eb129157dbf636a326 | 66,342 |
import logging
def getInitLogger(module: str, **kwargs) -> logging.Logger:
"""Configure and initialize logging, then return a Logger for ``module``.
Parameters are passed to `logger_config`.
:param module: Name of module to be logged
"""
pywikibot.bot.init_handlers()
logging.config.dictConfig... | fcacc1c411e84ed91feb641742f160251811e1a9 | 66,343 |
from datetime import datetime
def is_date(value):
"""
Check if `value` is a date object.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a date object.
Example:
>>> import datetime
>>> is_date(datetime.date.today())
True
>>... | 3815928c9d57bb96ab107b5f74892837cea3123e | 66,344 |
import torch
def get_img_array(imgtensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
"""imgtensor: ([C,H,W],device=cuda)"""
denormimg = (
imgtensor.cpu()
.permute(1, 2, 0)
.mul_(torch.tensor(std))
.add_(torch.tensor(mean))
)
imgarray = denormimg.numpy()
... | ddc3e77c19f22bd928bee45c6d6b699d962f2aa8 | 66,345 |
def snake_bottom_middle_short():
"""
|===========|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|···········|
|·····ox····|
|===========|
"""
return Snake.from_dict(
*... | 11a52b88f5e8501c80dc6e416ec3f3d569e993e1 | 66,346 |
def reachable_form(xsys):
"""Convert a system into reachable canonical form
Parameters
----------
xsys : StateSpace object
System to be transformed, with state `x`
Returns
-------
zsys : StateSpace object
System in reachable canonical form, with state `z`
T : (M, M) rea... | 7eaaa82254bcce1703de7567e49b622647e3467b | 66,347 |
import os
def xonshconfig(env):
"""Ensures and returns the $XONSHCONFIG"""
xcd = env.get('XONSH_CONFIG_DIR')
xc = os.path.join(xcd, 'config.json')
return xc | 19ad736e9128f22836151e84b55803e7d8dd940e | 66,348 |
def email_to_tag(text: pd.Series) -> pd.Series:
"""Convert email to <EMAIL> tag.
Parameters
----------
text : pd.Series
Series of text data
Returns
-------
prepro_text : pd.Series
Text with encoded an email adress
"""
prepro_text = text.replace(regex=r'[\w\.-]+@[... | 60002b7b934f98f0f308f2e6f7aebe6f041bbf9e | 66,349 |
def get_source_position(source):
"""Return max x, y value of a SourceCatalog or catalog row"""
if isinstance(source, SourceCatalog):
x, y = source.maxval_xindex, source.maxval_yindex
else:
x, y = source['maxval_xindex'], source['maxval_yindex']
return x, y | 217c0be6bd8934a9a99e3ddb5ec3f5b2168f7b1b | 66,350 |
def raw_func():
"""
foo bar
baz
"""
return 12345 | 471716eed6860b8abd6a0e9129fe20e7eaadbdb4 | 66,351 |
def bilstm_net(data,
seq_len,
label,
dict_dim,
emb_dim=128,
hid_dim=128,
hid_dim2=96,
class_dim=2,
emb_lr=30.0,
is_prediction=False):
"""
Bi-Lstm net
"""
# embedding lay... | d4f7f9be04b762a8514afb18834a1919c45eec88 | 66,352 |
def conv2d(x, weight, bias=None, stride=1, pad=0,
dilation=1, groups=1, padding_mode='zeros'):
"""Convolution 2D."""
# pylint: disable=unused-argument
validator.check_value_type('stride', stride, (int, tuple), None)
if isinstance(stride, int):
stride = (stride, stride)
elif len(st... | e50f21818f3bbb670e46494ad244e12110fea29d | 66,353 |
def green(room, message, *args):
"""Send a green message."""
return _color(room, message % args, 'green') | 8349b67580ed329969cf69ad8aca0f3dce37d93b | 66,354 |
def pca_3d_loadings(pca, xvars, select_components=None, cmap=None,
text_settings=None):
"""Show contributions to three principal components.
Parameters
----------
pca : object like :class:`sklearn.decomposition._pca.PCA`
The results from a PCA analysis.
xvars : list of s... | f4aabd1f0093e3729721fe7465e0a0a61d6efb05 | 66,355 |
import os
def CleanObjectFiles(object_files):
"""Removes unneeded object files due to linker errors, binary size, etc...
Args:
object_files: List of object files that needs cleaning.
"""
blacklist = [
'libavcodec/inverse.o', # Includes libavutil/inverse.c
'libavcodec/file_open.o', # Include... | 315a283cc4697928adb727dcc1e96a845297ce74 | 66,356 |
def is_hex_str(value, chars=40):
# type: (str, int) -> bool
"""Check if a string is a hex-only string of exactly :param:`chars` characters length.
This is useful to verify that a string contains a valid SHA, MD5 or UUID-like value.
>>> is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c... | f9438238b55a8b8bbe4f29f81046eb39c09423c5 | 66,357 |
import random
def generate_token(length=64):
"""Generate a random token.
Args:
length (int): Number of characters in the token.
Returns:
Random character sequence.
"""
_allowed = 'abcdefghijklmnoprstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_$'
token = ''.join(random.System... | b1cc37216ed43e8d1d3c86e9817e87ab9833bfdd | 66,358 |
from scipy.optimize import fsolve
from math import log
from typing import Iterable
def tsat(p, bounds = False):
"""Saturation temperature (deg C) as a function of pressure (Pa).
If bounds is True, return None if the pressure is out of range."""
if bounds:
ok = (sat(0.01) <= p <= Pc1)
else: ok ... | ae6864547263fe05c165295eef9d317acb62ba73 | 66,359 |
from datetime import datetime
def calc_max_uptime(reboots):
"""Parse the passed in reboots output,
extracting the datetimes.
Calculate the highest uptime between reboots =
highest diff between extracted reboot datetimes.
Return a tuple of this max uptime in days (int) and the
... | 6f7d02bc17c16d4185e566646a70abe840934af3 | 66,360 |
def find_notes(search_terms):
"""Returns all notes corresponding to supplied search object"""
logger.debug("Building search request")
request = ashaw_notes.utils.search.get_search_request(search_terms)
logger.debug("Calling find_redis_notes")
return find_redis_notes(request) | a1ca341a394953af36ea93c0d14f3d390fd228b5 | 66,361 |
import string
def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
d = "".join(x for x in str(s) if x in string.digits)
return cast(d) if d else s | f788bfd13cc7234ca5f290ed047ec9b8bf8acc9b | 66,362 |
import hmac
def get_auth_hmac_from_key(auth_key):
""" Default instanciation of HMAC
:param bytes auth_key: secret key for signing data
:rtype: hmac.HMAC
"""
return hmac.HMAC(auth_key, hashes.SHA512(), backend=default_backend()) | c0b1539242d071768dfc897fa13a55ea2d2d7141 | 66,363 |
def maybe_fail_slow(executable, promise, plan, fail_slow=False):
"""Executes executable respecting fail-slow semantics if requested.
:param executable: The callable to execute.
:type executable: A no-argument callable.
:param promise: The promise the executable's product satisfies.
:type promise: :cl... | e593b31023dd4b56759fca2b96f7e54f63ec876d | 66,364 |
def get_errors():
"""
"""
errors_dict = {
'ReadCsvError': _('Inputed csv file not valid.'),
'ReadDatasetFromFileError': _('File not valid'),
'AddInDB': _('Failed to add object in database.'),
'UpdateInDB': _('Failed to Update object in database.'),
'DeleteInDB': _('Fa... | dffa307ecbc37f12c7b718c027c4ca135c22f4bd | 66,365 |
import uuid
def file_generator(size=2048):
""" Create a bogus file and returns it's name.
:param size: size in bytes
:returns: The name of the generated file.
"""
fn = '/tmp/rucio_testfile_' + uuid()
execute('dd if=/dev/urandom of={0} count={1} bs=1'.format(fn, size))
return fn | b64413f5902df6293d0b414e4cbb480a7be9254c | 66,366 |
def clean_up_dl_objects(data):
"""
Because dl objects need to be parsed out of any dict into json format
before they can be rendered in the browser, yet we cannot just do
json dumps because then they'll be strings...but they need
to be objects to be rendered properly.
"""
if isinstance(data,... | 992388559bbb2953d7e6640a61e6f113f3001db1 | 66,367 |
def spatialccd(jdata: list) -> list:
"""
We can't really guarantee what order (pixel wise) the CCD data is in. This aligns it
in a way that makes sense spatially, which is good for output to rasters.
Args:
jdata: initial JSON deserialization of change results for a chip
Returns:
n... | b21603fabed3fd0b1a69cefae0c72ab715d3341e | 66,368 |
def OpenDocumentText():
"""
Creates a text document
@return an OpenDocument instance with text mimetype
"""
doc = OpenDocument(u'application/vnd.oasis.opendocument.text')
doc.text = Text()
doc.body.addElement(doc.text)
return doc | 9240a85dd8efe3f1ece8210dd116a8be4485ca41 | 66,369 |
import argparse
import logging
def parse_args() -> tuple[int, str]:
"""
Parses command line arguments
:return: Tuple of number for log level and mode selected
"""
parse = argparse.ArgumentParser()
parse.add_argument(
"-log",
"--log",
default="warning",
help=(
... | 5432aa3bb72a097f50d79ee49bb6d4ea5cc4f4c9 | 66,370 |
import numpy
def get_spherical_coordinates(xyz):
"""Compute spherical coordinates (r, theta, phi) for X,Y,Z point.
:param array xyz: column vector (3 row x 1 column numpy array)
:return: tuple of r, theta, phi for input coordinate
"""
r = numpy.linalg.norm(xyz)
if 0 == r:
return numpy... | 894fe52e46b55b37e9db6b447d6061bc1167518c | 66,371 |
def csr_scale_columns(*args):
"""
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, signed char Ax,
signed char Xx)
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, unsigned char Ax,
unsigned char Xx)
csr_scale_columns(int n_row, int n_col, int Ap, int Aj, short Ax, short Xx... | b9221dc01a99466deae29cbd5d3144c2f2d2402f | 66,372 |
import torch
def norm_spherical(cartesian):
"""
@params cartesian coordinate
@return normalize spherical coordinate in [-1,1]
"""
cartesian_len = torch.norm(cartesian, dim=-1)[...,None]
if len(cartesian.shape) == 2:
cartesian_len = cartesian_len.expand(-1, 3)
elif len(cartesian.sh... | bdc95e66b035229cd6d1e07627545545170f92e2 | 66,373 |
def _sp_print_stderr(m: str) -> str:
"""Return the subprocess cmd to print `m` to stderr."""
return 'python -c "import sys; print(\'{}\', file=sys.stderr)"'.format(m) | 7a99aa77e3f54ede37a71df6a1432c82c79352aa | 66,374 |
def figure(*args, **kwargs):
"""does some nice pqol things then returns plt.figure(*args, **kwargs).
Note to user (based on current implementation):
Currently, this function just sets new default font sizes, and returns figure object.
For best use, either generate all your figures with pqol... | 8a0ead87cfccfb42626604d7826827d93aba5347 | 66,375 |
import http
from typing import Optional
def index(
request: http.HttpRequest,
workflow: Optional[models.Workflow],
) -> http.HttpResponse:
"""Http request to serve the details page for the workflow.
:param request: HTTP Request
:param workflow: Workflow being manipulated
:return: Http respons... | d70b81bc4888241c1278112a969b344621a62021 | 66,376 |
import sympy as sp
def MaxCut(nqubits, dense=True):
"""Max Cut Hamiltonian.
.. math::
H = - \\sum _{i,j=0}^N \\frac{1 - Z_i Z_j}{2}.
Args:
nqubits (int): number of quantum bits.
dense (bool): If ``True`` it creates the Hamiltonian as a
:class:`qibo.core.hamiltonians.... | a8c641e3d30e172dc7628ac7ef68c6fc61e7e4f3 | 66,377 |
def fetch_property(object_type, props, name, to_repr):
"""
Get a representation of a property fetched through FetchProperties interface
:param object_type: string representation of object type implementing FetchProperties
:type object_type: str
:param props: dictionary of property names mapped to v... | 6f4bb01fbc8165047511eb44c40f1fc79eb24db8 | 66,378 |
import socket
def reverseNameFromIPv6Address(address):
"""
Return a reverse domain name for the given IPv6 address.
"""
# Expand addresses that are in compressed format eg ::1
fullHex = "".join(
"%02x" % (ord(c),) for c in socket.inet_pton(socket.AF_INET6, address)
)
tokens = list(... | 86991385c0585d6978e8f65de2c6b3b7209ab1f0 | 66,379 |
import re
def validate_duration(duration: str) -> str:
"""Validates time input for job duration."""
pat = re.compile(r"^([0-9]+([dDhHmMsS]?))?$")
if not pat.match(duration):
logger.error(f'Invalid time value given: {duration}')
raise ArgumentTypeError(f'Invalid time value given: {duration... | 804adbf0f2ba9186e5f2d27a0b821bf210a2a593 | 66,380 |
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided... | b70a20afe440638472bc946242f7bc2c094a0526 | 66,381 |
import json
import re
def sd_datatype_mapping(XNAT, project):
"""
Method to get the Datatype mapping from Project level
:param XNAT: XNAT interface
:param project: XNAT Project ID
:return: Dictonary with scan_type/series_description and datatype mapping
"""
sd_dict = {}
if XNAT.select... | b8a4c4e15408b2d6c83a467dac1d7dfc21f9059f | 66,382 |
def power(lhs, rhs):
"""Power with auto-broadcasting
Parameters
----------
lhs : tvm.Tensor or Expr
The left operand
rhs : tvm.Tensor or Expr
The right operand
Returns
-------
ret : tvm.Tensor or Expr
Returns Expr if both operands are Expr.
Otherwise ret... | e6b3c465f3906eeb931f6d28d83ea7e146178507 | 66,383 |
def export_all_games_pgn(database, filename):
"""Export all database games in PGN export format."""
if filename is None:
return True
rr = chessrecord.ChessDBrecordGame()
rr.set_database(database)
all_games_output = None
no_games_output = True
games_for_date = []
prev_date = None
... | 30838512e22dd66747ad5ff46c9b4845ca31a776 | 66,384 |
def get_provider():
"""
Returns the singleton AuthorizationFilter instance
:rtype:
:class:`vmware.vapi.security.authorization_filter.AuthorizationFilter`
:return: AuthorizationFilter instance
"""
return _authz_filter | 4ea67bdc73cfab28f9aee9c0dfdc84de5b33753c | 66,385 |
def get_list_parsers_url(args):
"""Returns list parsers endpoint URL for corresponding region and env."""
url = f'{get_connecting_url(args)}/tools/cbnParsers'
print(f'Connecting to: {url}')
return url | 976da93d007d482d573a8204fbac9b0c71b596e5 | 66,386 |
def remove_whitespace(tokens):
"""Remove any top-level whitespace in a token list.
Whitespace tokens inside recursive :class:`~.token_data.ContainerToken`
are preserved.
:param tokens:
A list of :class:`~.token_data.Token` or
:class:`~.token_data.ContainerToken`.
:return:
A... | 05a0c2d745544e1e60e86539f38e84e8c03d7c0c | 66,387 |
def create_avg_stoplines_df(stoplines_df_name):
"""Create an aggregated stoplines_avg_df with the average stopline X, Y for each link and number of lanes"""
stopline_avg_df = stoplines_df_name.groupby('Link_ID')['stopline_X'].mean().reset_index(name='mean_X')
stopline_avg_df['mean_Y'] = stoplines_df_name.gr... | 284d22d121cb495b95e61da4c45c107b9cfd7a24 | 66,388 |
def wsl_host_docker_path(path):
"""
Returns the windows path with forward slashes. This is the format docker
wants in the -v switch.
"""
winpath = windows_drive_path(path)
return f"/{winpath[0].lower()}{winpath[2:]}" | 9a08c68709ae0b778ef248bdfb8b6c79fe66c330 | 66,389 |
def wrap(value):
"""
Wraps the given value in a Document or DocumentList as applicable.
"""
if isinstance(value, Document) or isinstance(value, DocumentList):
return value
elif isinstance(value, dict):
return Document(value)
elif isinstance(value, list):
return DocumentLi... | 839e29802413061d4b2e48d771346ad98e6e7495 | 66,390 |
def validate_gt(value_name, value, low_lim):
"""Raise error if value not greater than lower limit or wrong type.
Parameters
---------
value_name : str
Name of value being tested
value : int, float, numpy.ndarray, pint.Quantity
Value to be tested
low_lim : type(value)
``v... | 11e3f215daf77cf86842dc5a7d86ef9550dc709e | 66,391 |
def create_grid(dataset: list) -> str:
"""
Create a table grid of the github users
Args:
dataset (list): The dataset to create the table from, in this case, the list of github users.
Returns (str): table grid of github users
"""
row_length = 7
html_card = ''
for i in range(0, l... | 8cd9efaa01ece44ae06400e1e14456f80b2137fa | 66,392 |
import subprocess
def get_gpu_free_mem():
"""return a list of free GPU memory"""
sp = subprocess.Popen(['nvidia-smi', '-q'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_str = sp.communicate()
out_list = out_str[0].split('\n')
out = []
for i in range(len(out_list)):
item = out_... | 7db14ce67945e718d6ab65abc5ce331bfdb09a00 | 66,393 |
import tqdm
import itertools
def get_annotated_phase_df(conflict_score_cost=0.1, unknown_score_cost=0.2):
"""
:return: Pandas DataFrame with the following columns:
site_id, journal_oid, journal_index, is_annotated, conflict_status, phases, {phase_name}_score, journal_text
"""
phase_annotatio... | aca08472e6e0167ba4d6d2d3e125fd452d4a2fbf | 66,394 |
import json
def update_resource(request):
""" View used to update a resource (file). """
post = json.loads(request.body.decode())
path = post.get("path")
if path is None:
return HttpResponseBadRequest(missing_parameter('path'))
try:
with open(join_fb_root(path), 'w') as f... | 4b9feae432b43f957f32185c9e0eb58b815ff60c | 66,395 |
import os
def batch_select(file_in, file_out, types="right"):
"""
@topic: Select and crop the iamges in batch
@input: file_in/file_out: the file name of input&output file; types: left/right (str)
"""
path_total = os.getcwd() # Get current pwd
path_split = path_total+"/{0}".format(file_in)
... | 88da9310e8e517f3b5c870591edd6f9eb2c28721 | 66,396 |
def get_rs(key, ps, hps, imax):
"""
查 P + Pa~R 关系曲线,获取径流深 R
:param key: int 曲线代码
:param ps: list 各设计频率
:param hps: list 各设计频率下的24小时历时设计雨量
:param imax: float 最大初损值
:return: len(hps)D vector
"""
hps = np.array(hps)
pas = get_pas(ps, imax)
return np.array([get_relationship_val... | b0e6d5eb965540ab6f1db2d5a2fc16c28545e3b4 | 66,397 |
def caesar_1(char_in: str) -> str:
"""Character offset by 1 position.
Parameters:
char_in : function
Character of the source text.
Returns:
char_out : str
Character of the encrypted text.
"""
num = ord(char_in[0])
if (97 <= num <= 121) or (65 <= num <=... | 0a77b94ea2f2b1bf75334d633da0a8299f8c7960 | 66,398 |
import re
def _GetPlatformSpecificChromeDriverCompatibleVersionUrl(
google_chrome_version: str) -> str:
"""Returns the platform specific `chromedriver` version URL that is
compatible with the `Google Chrome` version given as `google_chrome_version`.
This function takes out the `major` version from the `goo... | 5757c6f233ed95f3f4a919791a49ab7bef261ee0 | 66,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.