content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def errorString(node, error):
"""
Format error messages for node errors returned by checkLinkoStructure.
inputs:
node - the node for the error.
error - a (backset, foreset) tuple, where backset is the set of
missing backlinks and foreset is the set of missing forelinks.
returns: string
... | df87b7838ed84fe4e6b95002357f616c96d04ad0 | 14,182 |
def deep_update(target, source):
"""
Deep merge two dicts
"""
if isinstance(source, dict):
for key, item in source.items():
if key in target:
target[key] = deep_update(target[key], item)
else:
target[key] = source[key]
return target | 5db0c6fa31f3d4408a359d90dbf6e50dfdc12cdc | 14,183 |
import hashlib
def md5_hash_file(path):
"""
Return a md5 hashdigest for a file or None if path could not be read.
"""
hasher = hashlib.md5()
try:
with open(path, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
return hasher.hexdigest()
except I... | 514cafcffa0ae56d54f43508ece642d25b4be442 | 14,184 |
def Constant(value):
"""
Produce an object suitable for use as a source in the 'connect' function that
evaluates to the given 'value'
:param value: Constant value to provide to a connected target
:return: Output instance port of an instance of a Block that produces the given constant when evaluated... | 1763d657e3396286516e6669e57b7ee297463b14 | 14,185 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary ... | cb0b9b55106cf771e95505c00043e5772faaef40 | 14,186 |
import re
def expandvars(s):
"""Expand environment variables of form %var%.
Unknown variables are left unchanged.
"""
global _env_rx
if '%' not in s:
return s
if _env_rx is None:
_env_rx = re.compile(r'%([^|<>=^%]+)%')
return _env_rx.sub(_substenv, s) | ede7861831ea9d9e74422eb3a92a13ba4d1937f2 | 14,187 |
def make_map_counts(events, ref_geom, pointing, offset_max):
"""Build a WcsNDMap (space - energy) with events from an EventList.
The energy of the events is used for the non-spatial axis.
Parameters
----------
events : `~gammapy.data.EventList`
Event list
ref_geom : `~gammapy.maps.WcsG... | 7a22340c8f3909d6ca559361290a4608a0321de1 | 14,188 |
def stats_aggregate():
""" RESTful CRUD Controller """
return crud_controller() | 4a8439139257f39e0d2a34b576e9a9bd98cded5c | 14,189 |
def format_dB(num):
"""
Returns a human readable string of dB. The value is divided
by 10 to get first decimal digit
"""
num /= 10
return f'{num:3.1f} {"dB"}' | 13d6313834333ee2ea432cf08470b6ce1efe1ad6 | 14,190 |
def _check_index_dtype(k):
"""
Check the dtype of the index.
Parameters
----------
k: slice or array_like
Index into an array
Examples
--------
>>> _check_index_dtype(0)
dtype('int64')
>>> _check_index_dtype(np.datetime64(0, 'ms'))
dtype('<M8[ms]')
>>> _check_in... | f9f7bac24f7ceba57978d7e1aed7c4e052c79f35 | 14,191 |
def _wrapper_for_precessing_snr(args):
"""Wrapper function for _precessing_snr for a pool of workers
Parameters
----------
args: tuple
All args passed to _precessing_snr
"""
return _precessing_snr(*args) | 4d64d7e658ecfeed6206abd0827f37805c3ecd0c | 14,192 |
import logging
def put_file_store(store_name, store, block_on_existing=None, user=None): # noqa: E501
"""Create/update store
# noqa: E501
:param store_name: Name of the store
:type store_name: str
:param store: Store information
:type store: dict | bytes
:rtype: FileStore
"""
... | 2e799c7fc2f394c925562c8600b83a1149586ad2 | 14,194 |
from typing import Dict
from typing import Set
from typing import Tuple
def assign_sections(region_table: RegionTable, sections: Dict[str, int]):
"""Assign memory sections.
This is a packing problem and therefore reasonably complex.
A simplistic algorithm is used here which may not always be optimal if u... | 6ad4af4c67be9e9d07a4464bfc1d3c529a5afd4b | 14,195 |
def humanize_arrow_date( date ):
"""
Date is internal UTC ISO format string.
Output should be "today", "yesterday", "in 5 days", etc.
Arrow will try to humanize down to the minute, so we
need to catch 'today' as a special case.
"""
try:
then = arrow.get(date).to('local')
now... | 511e5f7a85a5906d78ed9b252076b1f0e8ea02d9 | 14,196 |
def getCourseTeeHoles(request, courseId, courseTeeId):
"""
Getter function for list of courses and tees
"""
resultList = list(Tee.objects.filter(course_tee_id=courseTeeId).values('id', 'yardage', 'par', 'handicap', 'hole__id', 'hole__name', 'hole__number'))
return JsonResponse({'data' : resultList}) | 7abac65449503d2309cf8cae49b7e555488333f9 | 14,197 |
def create_zone_ajax(request):
"""
This view tries to create a new zone and returns an JSON with either
'success' = True or 'success' = False and some errors.
"""
qd = request.POST.copy()
# See if the domain exists.
# Fail if it already exists or if it's under a delegated domain.
root_d... | 05a0e8a3edc38bd2821057c131760b2c06fc452c | 14,200 |
def main_plot():
"""The view for rendering the scatter chart"""
img = get_main_image()
return send_file(img, mimetype='image/png', cache_timeout=0) | a285cd3bc9a54b96d4fa52d9cc8b13c1bd070cd2 | 14,201 |
def Ising2dT(beta = 0.4, h = 0, isSym = False):
"""
T = Ising2dT(J,h).
-------------------------
Set up the initial tensor for 2d classical Ising model on a square lattice.
Argument: J is defined to be beta * J = J / kT, and h is
defined to be beta*h = h / kT, where J and h are conventional coup... | 416fabb06a1e8aa0f57456d22c2a89fc4da869c6 | 14,202 |
def __grid_count(self):
"""Get number of grids in the case"""
try:
return self.__case_stub.GetGridCount(self.__request()).count
except grpc.RpcError as exception:
if exception.code() == grpc.StatusCode.NOT_FOUND:
return 0
return 0 | e6237a092b4714d787eb9d145f4e972deeaafb69 | 14,203 |
import math
def timer(method):
"""
Decorator to time a function.
:param method: Method to time.
:type method: function
"""
def wrapper(*args, **kwargs):
"""
Start clock, do function with args, print rounded elapsed time.
"""
starttime = compat.perf_clock()
... | 10105d77a32ce62500bdb86c7fbb772f03b4eff9 | 14,205 |
def plot_map_from_nc(path_nc, out_path, var_name, xaxis_min=0.0, xaxis_max=1.1, xaxis_step=0.1,
annotate_date=False, yr=0, date=-1, xlabel='', title='', tme_name='time', show_plot=False,
any_time_data=True, format='%.2f', land_bg=True, cmap=plt.cm.RdBu, grid=False, fill_mask=Fa... | 7e688fd8e5baae173afc711f47633b3037b03e7d | 14,206 |
def f5_add_policy_method_command(client: Client, policy_md5: str, new_method_name: str,
act_as_method: str) -> CommandResults:
"""
Add allowed method to a certain policy.
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of the policy.
new... | 0b7297de004913eeeb5dd962a6cd62fee6f3458a | 14,207 |
def test_set(sc,
idfModel,
numFeatures,
test_file = "data/test_clean.csv"
):
"""
Input :
IDF model obtained in the training phase
number of retained features in the tweet-term structure
Output :
normalized twee... | 7e68e536f3f40761e7885d784c392b2e9a6ca428 | 14,209 |
def is_object_based_ckpt(ckpt_path: str) -> bool:
"""Returns true if `ckpt_path` points to an object-based checkpoint."""
var_names = [var[0] for var in tf.train.list_variables(ckpt_path)]
return '_CHECKPOINTABLE_OBJECT_GRAPH' in var_names | 043069aae83845be44a3248ce0b95096e86d4b8f | 14,210 |
from typing import Any
def gather(first_step: str = PATH, *, filename: str = FILE, stamp: bool = True) -> dict[str, dict[str, Any]]:
"""Walk the steps on the path to read the trees of configuration."""
user = USER if filename == FILE else filename.split('.')[0]
trees = [(where, tree) for where, tree in w... | c290b7bffcf3cb2b022ab1e4bbef68e6ebf4da3c | 14,213 |
def _extractKernelVersion(kernel):
"""
Extract version string from raw kernel binary.
@param bytes kernel Raw kernel binary.
@return string Version string if found.
"""
try:
versionOffset = kernel.index(b'Linux version')
for i in range(versionOffset, versionOffset+1024):
... | f32e995a4a16376b26b0e1d5af826f2f0e71df87 | 14,214 |
def get_vdw_rad(atomic_num):
"""Function to get the user defined atomic radius"""
atomic_rad_dict = {6: 1.7, 7: 1.55, 8: 1.52, 9: 1.47}
if atomic_num in atomic_rad_dict:
return atomic_rad_dict[atomic_num]
else:
return float(Chem.GetPeriodicTable().GetRvdw(atomic_num)) | 98bd3e346afce37458c4ab1ea298e50af1121c21 | 14,215 |
def input_literal(term, prompt):
"""Get console input of literal values and structures."""
while True:
input_string = read_line(term, prompt)
if input_string:
break
return eval_literal(input_string) | 93611e823a59bc61002cc80b481525ac5c91354e | 14,216 |
from typing import List
from typing import Union
from typing import Mapping
from typing import Pattern
def _parse_string(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: Union[mapry.String, mapry.Path],
pattern_uids: Mapping[Pattern[str], int],
auto_id: mapry.go.genera... | bcb653ea8d02ea88569d67fedd5d1e83893a1519 | 14,217 |
from datetime import datetime
def get_dots_case_json(casedoc, anchor_date=None):
"""
Return JSON-ready array of the DOTS block for given patient.
Pulling properties from PATIENT document.
Patient document trumps casedoc in this use case.
"""
if anchor_date is None:
anchor_date = datet... | 4f9e6febcdc7e66f855411d601b69b4aad6955f3 | 14,218 |
import time
def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg | c15dfac46f9b47fcc82ff539116ecc683a593b9c | 14,220 |
def make_coll(db_auth, db_user, db_pass, mongo_server_ip='127.0.0.1'):
"""
Function to establish a connection to a local MonoDB instance.
Parameters
----------
coll_name: String.
Name of MongoDB collection to retrieve.
db_auth: String.
MongoDB database that sh... | eb4297e76c5c0a4bf344430eba26d4ed6e68128c | 14,222 |
def sms_send(recipient):
"""
Attempt to send SMS message using Twilio's API.
If this fails, use the Summit API to send the SMS message.
"""
body = request.get_data()
try:
message = send_sms_through_provider('Twilio', recipient, body)
except TwilioRestException:
message = send... | 15f6049af35970ccbefc3e75ba726281ed2d3329 | 14,223 |
from typing import Dict
from typing import Optional
def cat_to_sub_cat(
dp: Image, categories_dict_names_as_key: Dict[str, str], cat_to_sub_cat_dict: Optional[Dict[str, str]] = None
) -> Image:
"""
Replace some category with its affiliated sub category of CategoryAnnotations. Suppose your category name is... | f2c7dbb95e1a47e4a6775db3857a5f37c9c6b5a8 | 14,224 |
def index_to_str(idx):
"""
Generates a string representation from an index array.
:param idx: The NumPy boolean index array.
:return: The string representation of the array.
"""
num_chars = int(idx.shape[0] / 6 + 0.5)
s = ""
for i in range(num_chars):
b = i * 6
six = idx... | 7f7d49ca31bd70e5f19addaa4913a2cf14382e2d | 14,225 |
def ArclinkStatusLine_ClassName():
"""ArclinkStatusLine_ClassName() -> char const *"""
return _DataModel.ArclinkStatusLine_ClassName() | 4589b3c8bae93b28f5c17b8d432813ac504e58e6 | 14,226 |
import re
def build_sfdisk_partition_line(table_type, dev_path, size, details):
"""Build sfdisk partition line using passed details, returns str."""
line = f'{dev_path} : size={size}'
dest_type = ''
source_filesystem = str(details.get('fstype', '')).upper()
source_table_type = ''
source_type = details.get... | 8ef87f9c4db06382d5788ab846ae5b8cf1c7d2f4 | 14,227 |
def get_allocation_window(allocation,
default_start_date=_get_zero_date_utc(),
default_end_date=_get_current_date_utc()):
"""
Returns a tuple containing the allocation windows start and end date
"""
if not allocation.start_date:
window_start_da... | 7367eb11eac50829de27315155b934297f6bc684 | 14,229 |
def IDFromUID(s,code=''):
""" Create an ID object from the given string UID.
This can raise an Error in case the string does not map to a
valid UID. code is used in the verification process if given.
"""
id = _EmptyClass()
id.__class__ = ID
id.set_uid(s,code)
return id | 5e37d90313517e11bc914fb57320406653da3e3a | 14,231 |
def ordered_pair_accuracy(labels, predictions, weights=None, name=None):
"""Computes the percentage of correctedly ordered pair.
For any pair of examples, we compare their orders determined by `labels` and
`predictions`. They are correctly ordered if the two orders are compatible.
That is, labels l_i >... | 5e6c5e0bc480822149a04b5efaffe2474d1a8394 | 14,232 |
def samp(*args, **kwargs):
"""
The HTML <samp> element is an element intended to identify sample
output from a computer program. It is usually displayed in the
browser's default monotype font (such as Lucida Console).
"""
return el('samp', *args, **kwargs) | eaf9e69413b3ccafc1f0fed9549efb89b7fb5715 | 14,233 |
def knownTypes():
"""Returns all known resource types"""
return loader.typeToExtension.keys()+['WorldModel','MultiPath','Point','Rotation','Matrix3','ContactPoint'] | d332a3344e43bc8f2026eed6feff137fdb2b9b2e | 14,237 |
def args_for_blocking_web_whatsapp_com_http():
""" Returns arguments for blocking web.whatsapp.com over http """
return ["-iptables-reset-keyword", "Host: web.whatsapp.com"] | a15a8ebc087467ec1a8e6817366f93df7b0a181b | 14,238 |
def zeta_vector():
"""The :func:`zeta` vector.
:func:`zeta_vector` returns :math:`\zeta` parameters calculated
by formula (5) on page 17 in `the technical paper`_, which is
.. math::
\\bf \zeta= W^{-1}(p-\mu)
"""
return np.linalg.inv(W_matrix()) @ (m_vector() - mu_vector()) | 7650ad5fb443344e82f6e4bd9fd2cba697e7f768 | 14,239 |
def get_fourier_col_name(k, col_name, function_name="sin", seas_name=None):
"""Returns column name corresponding to a particular fourier term, as returned by fourier_series_fcn
:param k: int
fourier term
:param col_name: str
column in the dataframe used to generate fourier series
:param... | 5c15b52728d0333c9c7df59030d6ead66473c823 | 14,240 |
import uuid
def unique_filename():
"""Creates a UUID-based unique filename"""
return str(uuid.uuid1()) | ee0d9090a4c5f8a6f0ddef2d670f7beb845a4114 | 14,241 |
import mdtraj
import tempfile
def _create_trajectory(molecule):
"""Create an `mdtraj` topology from a molecule object.
Parameters
----------
molecule: openff.toolkit.topology.Molecule
The SMILES pattern.
Returns
-------
mdtraj.Trajectory
The created trajectory.
"""
... | de9e2a94d266dbdc3201ff74cb2bd27e939850d1 | 14,242 |
def preprocess(image):
"""Load and preprocess image."""
# Create the array of the right shape to feed into the keras model
data = []
size = (96, 96)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
image = np.asarray(image)
x = preprocess_input(image)
data.append(x)
data = np.array... | d59eb9e10f6d69e6a1cdcc0d25230f6bd35947d1 | 14,243 |
import torch
def move_to(obj, device):
"""Credit: https://discuss.pytorch.org/t/pytorch-tensor-to-device-for-a-list-of-dict/66283
Arguments:
obj {dict, list} -- Object to be moved to device
device {torch.device} -- Device that object will be moved to
Raises:
TypeError: object is ... | 97abd322f292fe605a06e8235ecb353ed9a01bf8 | 14,244 |
def split(C, dims, axis=1):
"""
Splits the columns or rows of C.
Suppse C = [X_1, X_2, ..., X_B] is an (n x sum_b d_b) matrix.
Returns a list of the constituent matrices as a list.
Parameters
----------
C: array-like, shape (n, sum_b d_b)
The concatonated block matrix.
dims: li... | 2fd55cdde7bc5315f2a78236775c1f36aa8714fd | 14,245 |
def build_binary_value(char_str, bits, alphabet) -> str:
"""
This method converts a string char_str into binary, using n bits per
character and decoding from the supplied alphabet or from ASCII when bits=7
This is almost the inverse method to build_string in the decompress module.
:param char_str:... | 50830dd5cfa3f5428b0946e7382220f9b5ff1915 | 14,246 |
def computeAnswer(inputData):
"""Compute the answer to the task, from the input data."""
# Do some calculations on the inputData
answer = str(int(inputData) * 2)
# EDIT ME (remove this line once done)
return answer | 3bf90dc1c05ca422ffda70d8a053eb76f6dcc66b | 14,247 |
import re
import itertools
import collections
def label_schema_matching(
df, endpoint=DBpedia, uri_data_model=False, to_lowercase=True, remove_prefixes=True,
remove_punctuation=True, prefix_threshold=1, progress=True, caching=True):
"""A schema matching method by checking for attribute -- rdfs:label betw... | 0577c29206da3c6528b85a4868a6f4db12450122 | 14,248 |
from datetime import datetime
def get_last_month_date_dmy() -> str:
"""Returns last month date (dd/mm/yyyy for calls report)."""
return (datetime.now() - timedelta(30)).date().strftime("%d/%m/%Y") | b1dc2066c30797195a8e5e03b994d0374c0b5a2f | 14,250 |
def irange(start, end):
"""Inclusive range from start to end (vs. Python insanity.)
irange(1,5) -> 1, 2, 3, 4, 5"""
return range( start, end + 1 ) | 91d4c270b1d9304b4ee82c0cb16aee5d518db3d5 | 14,251 |
def get_required_params(request, expected_params: list, type: str = 'POST') -> dict:
"""Gets the list of params from request, or returns None if ANY is missing.
:param request: The Request
:type request: flask.Request
:param expected_params: The list of expected parameters
:type expected_params: li... | 2d0b2970464877ed74ecf3bfe0d45325ce3fafe4 | 14,253 |
def bot_send(msg, bot_id, broadcast):
"""
Send a message to a telegram user or group specified on chat_id
chat_id must be a number!
bot_id == bot_username
"""
if broadcast == True:
bot = telegram.Bot(token=config[bot_id]["bot_api_token"])
bot.sendMessage(chat_id=config[bot_id]... | f5647d489c6c4873a031a7a11f9112164881c2e7 | 14,255 |
import random
def split_dataset(dataset, num_train=1200):
"""
Split the dataset into a training and test set.
Args:
dataset: an iterable of Characters.
Returns:
A tuple (train, test) of Character sequences.
"""
all_data = list(dataset)
random.shuffle(all_data)
return all_da... | 140a9926ff5dc70e1a2b3ec9887111595c030355 | 14,257 |
def get_constant():
"""
Keep learning rate constant
"""
def update(lr, epoch):
return lr
return update | 1b68c67202c1c22c1aa6a6d532796e2bba0b42ee | 14,258 |
def spatial_pack_nhwc(data, kernel, stride, padding, in_bits, weight_bits,
pack_dtype, out_dtype, dorefa=False):
""" Compute convolution with pack on spatial axes. """
assert data.shape[0].value == 1, "spatial pack convolution only support batch size=1"
data_q = bitpack(data, in_bits, ... | 9d2527fb9878cc759e5cad0d1df4057cd852bc9f | 14,259 |
import pickle
def load_random_tt_distribution(numAgents, r, pu, samples):
"""
Load a file with a population of random turn-taking values, assuming that it exists
Parameters:
* numAgents -- the desired number of probabilistic agents to include
* r -- the turn-taking resolution
* pu -- the probability that a ... | 948dfa02ff387fbb69902bf35b5cc428f054a6e7 | 14,260 |
from typing import ContextManager
def fail_after(seconds: float) -> ContextManager[CancelScope]:
"""
Create a cancel scope with the given timeout, and raises an error if it is actually
cancelled.
This function and move_on_after() are similar in that both create a cancel scope
with a given timeout... | 917fe4d7d0a599caa855210bd86bb0b57263e71c | 14,261 |
from typing import Union
from typing import Set
from typing import Dict
import copy
def _get_dataset_names_mapping(
names: Union[str, Set[str], Dict[str, str]] = None
) -> Dict[str, str]:
"""Take a name or a collection of dataset names
and turn it into a mapping from the old dataset names to the provided ... | df271cb4cd102eb3731e12b8d92fd4cca8ef8145 | 14,262 |
import json
def _json_keyify(args):
""" converts arguments into a deterministic key used for memoizing """
args = tuple(sorted(args.items(), key=lambda e: e[0]))
return json.dumps(args) | 2800a9a0db0cf8d51efbcbeda2c023172f6662f5 | 14,263 |
def tgsegsm_vect(time_in, data_in):
"""
Transform data from GSE to GSM.
Parameters
----------
time_in: list of float
Time array.
data_in: list of float
xgse, ygse, zgse cartesian GSE coordinates.
Returns
-------
xgsm: list of float
Cartesian GSM coordinates... | 1c1809c722ae84e2d7bd467f78e9cefddb7cf884 | 14,264 |
def choose_a_pick_naive(numbers_left):
"""
Choose any larger number
:param numbers_left:
:return:
"""
if numbers_left[0] > numbers_left[-1]:
return 0, numbers_left[0]
elif numbers_left[-1] > numbers_left[0]:
return -1, numbers_left[-1]
else:
return 0, numbers_left... | 70405a4ad9d1ee1afbec93bea13d7eab3068b42e | 14,265 |
def _Run(args, holder, target_https_proxy_arg, release_track):
"""Issues requests necessary to import target HTTPS proxies."""
client = holder.client
resources = holder.resources
target_https_proxy_ref = target_https_proxy_arg.ResolveAsResource(
args,
holder.resources,
default_scope=compute_s... | 26163d575701045e126ec52ae9adbb24fb98a54a | 14,268 |
def get_mono_cell(locus_file, TotalSNPs, TotalBi_SNPs_used):
"""Determine value to add to [0,0] cell"""
TotalBP, Loci_count = totalbp(locus_file)
return int((TotalBi_SNPs_used * TotalBP) / TotalSNPs) - TotalBi_SNPs_used, \
TotalBP, Loci_count | b6890f4a5129eb0892c6af9f5385dba98612776f | 14,269 |
def remove_bad_particles(st, min_rad='calc', max_rad='calc', min_edge_dist=2.0,
check_rad_cutoff=[3.5, 15], check_outside_im=True,
tries=50, im_change_frac=0.2, **kwargs):
"""
Removes improperly-featured particles from the state, based on a
combination of pa... | 09d767cc2513b542a99f8a846c866a1a8902ebf5 | 14,270 |
def _pyside_import_module(moduleName):
""" The import for PySide
"""
pyside = __import__('PySide', globals(), locals(), [moduleName], -1)
return getattr(pyside, moduleName) | 7b3b18214d12322e230c78678f3ef4fdc1717f10 | 14,271 |
import unicodedata
def sanitize_str(value: str) -> str:
"""Removes Unicode control (Cc) characters EXCEPT for tabs (\t), newlines (\n only), line separators (U+2028) and paragraph separators (U+2029)."""
return "".join(ch for ch in value if unicodedata.category(ch) != 'Cc' and ch not in {'\t', '\n', '\u2028', '\u20... | 5b5eae2b377a834e377a8bf7bcd7cefc2278c2f7 | 14,273 |
def get_tariff_estimated(reporter,
partner='000',
product='all',
year=world_trade_data.defaults.DEFAULT_YEAR,
name_or_id='name'):
"""Tariffs (estimated)"""
return _get_data(reporter, partner, product, year,
... | d4fd81e640d014bf52725a1274d0f3a2c0eebeba | 14,274 |
def task_result_api_view(request, taskid):
"""
Get task `state` and `result` from API endpoint.
Use case: you want to provide to some user with async feedback about
about status of some task.
Example:
# urls.py
urlpatterns = [
url(r'^api/task/result/(.+)/', task_result... | 94e46b3282a1f69e16a8979906b118d8684e1799 | 14,275 |
def get_horizon_coordinates(fp_pointings_spherical):
"""
It converts from spherical to Horizon coordinates, with the conventions:
Altitute = np.pi / 2 - zenith angle (theta)
Azimuth = 2 * np.pi - phi
Parameters
----------
fp_pointings_spherical : numpy array of shape (..., 2), radians... | 7fbc11fe6195129d9c18c0161fe59fab6e31a29c | 14,276 |
from typing import Any
def patch_object_type() -> None:
"""
Patches `graphene.ObjectType` to make it indexable at runttime. This is necessary for it be
generic at typechecking time.
"""
# Lazily import graphene as it is actually an expensive thing to do and we don't want to slow down things at
... | 4ed77870c9df03d072b55bc3a919c59d3e761f38 | 14,278 |
import time
def date_format(time_obj=time, fmt='%Y-%m-%d %H:%M:%S') -> str:
"""
时间转字符串
:param time_obj:
:param fmt:
:return:
"""
_tm = time_obj.time()
_t = time.localtime(_tm)
return time.strftime(fmt, _t) | 0a614763b040587b80743ffacfff6bbb0a6c7365 | 14,280 |
from typing import Optional
def clean_pin_cite(pin_cite: Optional[str]) -> Optional[str]:
"""Strip spaces and commas from pin_cite, if it is not None."""
if pin_cite is None:
return pin_cite
return pin_cite.strip(", ") | 9c495fcc4f1cf192c1358f50fef569c4d6b36290 | 14,281 |
def instrument_code_to_name(rwc_instrument_code):
"""Use the rwc_instrument_map.json to convert an rwc_instrument_code
to its instrument name.
Parameters
----------
rwc_instrument_code : str
Two character instrument code
Returns
-------
instrument_name : str
Full instru... | 9059bb69b86e5c8e326b5c51a745e61c15c41389 | 14,282 |
def record_time(ad, fallback_to_launch=True):
"""
RecordTime falls back to launch time as last-resort and for jobs in the queue
For Completed/Removed/Error jobs, try to update it:
- to CompletionDate if present
- else to EnteredCurrentStatus if present
- else fall back to launch tim... | 517eb369f9d04048bce87b4301761f2b3b629303 | 14,283 |
def getTeamCompatibility(mentor, team):
"""
Gets a "compatibility score" between a mentor and a team (used as the weight in the later optimization problem)
Uses the functions defined above to compute different aspects of the score
"""
score = 0
# find value from overlapping availabilities
# value may differ dep... | a9cd0c65b4419051045706852c3d64baff787e4f | 14,284 |
def mean_edges(graph, feat, weight=None):
"""Averages all the values of edge field :attr:`feat` in :attr:`graph`,
optionally multiplies the field by a scalar edge field :attr:`weight`.
Parameters
----------
graph : DGLGraph
The graph.
feat : str
The feature field.
weight : o... | 8219a4f543fe0903e3a9b313fd3cc142435da788 | 14,285 |
from typing import Optional
async def update_config_file(config: ConfigDTO, reboot_processor: Optional[bool] = True):
"""
Overwrites the configuration used by the processor.
"""
config_dict = map_to_file_format(config)
success = update_config(config_dict, reboot_processor)
if not success:
... | 165c2f59056ce0d71b237897e7379f517b158dc5 | 14,286 |
import requests
def integration_session(scope="session"):
"""
creates a Session object which will persist over the entire test run ("session").
http connections will be reused (higher performance, less resource usage)
Returns a Session object
"""
s = requests.sessions.Session()
s.headers.u... | c002b6d7875be41355990efe0bb10712661f50fe | 14,287 |
import json
def get_json_dump(json_object, indent=4, sort_keys=False):
""" Short handle to get a pretty printed str from a JSON object. """
return json.dumps(json_object, indent=indent, sort_keys=sort_keys) | 505548cdf972ef891b7bcc3bcd7be3347769faec | 14,288 |
from re import S
def number_of_real_roots(f, *gens, **args):
"""Returns the number of distinct real roots of `f` in `(inf, sup]`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> from sympy.polys.polyroots import number_of_real_roots... | d0ed0923aba4e5749a5b5baf267914ea29800c6f | 14,289 |
def heap_sort(arr: list):
"""
Heap sorting a list. Big-O: O(n log n).
@see https://www.geeksforgeeks.org/heap-sort/
"""
def heapify(sub: list, rdx: int, siz: int):
"""
Heapifying range between rdx and size ([rdx:siz]).
@param sub: a slice of list.
@param rdx: root/p... | 9b53f3027804cab16c9850d4858377f49afe7bbf | 14,290 |
def find_max_path(triangle):
"""
Find maximum-sum path from top of triangle to bottom
"""
# Start by copying the values
sums = [[x for x in row] for row in triangle]
# Efficient algorithm: start at the bottom and work our way up, computing max sums
for reverse_index, row in enumerate(reverse... | 1eb0afd076c455e67eacc867d04020ae82c68936 | 14,291 |
def plot_partregress(results, exog_idx=None, xnames=None, grid=None, fig=None):
"""Plot partial regression for a set of regressors.
Parameters
----------
results : results instance
A regression model results instance
exog_idx : None or list of int
(column) indices of the exog used i... | c858b08b732bcd4b325c548ba59bed76316b5551 | 14,292 |
def ufloats_overlap_range(ufloats, vmin, vmax):
"""Return whether the +/- 1 sigma range overlaps the value range."""
vals = []
sigmas = []
for val in ufloats:
if isinstance(val, float):
vals.append(val)
sigmas.append(0)
else:
vals.append(val.nominal_va... | 1dee17437e1ba8904450895a748c9871a9964909 | 14,293 |
from typing import Tuple
import multiprocessing
import itertools
def exact_qaoa_values_on_grid(
graph: nx.Graph,
xlim: Tuple[float, float] = (0, np.pi / 2),
ylim: Tuple[float, float] = (-np.pi / 4, np.pi / 4),
x_grid_num: int = 20,
y_grid_num: int = 20,
num_processors: ... | 1ac1f93a9716e687983c3c557f5ee19cea8afb2d | 14,294 |
def typecheck_eq(expr, ctxt=[]):
"""(par (A) (= A A Bool :chainable))
(par (A) (distinct A A Bool :pairwise))
"""
typ = typecheck_expr(expr.subterms[0], ctxt)
for term in expr.subterms[1:]:
t = typecheck_expr(term, ctxt)
if t != typ:
if not (is_subtype(t, typ) or is_subty... | 78cbf7b3510b30adde74d03a9f0168fdbfbc6bab | 14,295 |
def precision(x, for_sum=False):
"""
This function returns the precision of a given datatype using a comporable numpy array
"""
if not for_sum:
return np.finfo(x.dtype).eps
else:
return np.finfo(x.dtype).eps * x.size | c8d634638c0c8ce43c024d9c342e71adae6534bc | 14,296 |
def parse_line(line, line_count, retries):
"""Coordinate retrieval of scientific name or taxonomy ID.
Read line from input file, calling functions as appropriate to retrieve
scientific name or taxonomy ID.
:param line: str, line from input file
:line_count: number of line in input file - enable tr... | 895ae24672221fe78654f4c2796a419640c19d42 | 14,297 |
def prop_rotate(old_image, theta, **kwargs):
"""Rotate and shift an image via interpolation (bilinear by default)
Parameters
----------
old_image : numpy ndarray
Image to be rotated
theta : float
Angle to rotate image in degrees counter-clockwise
Retur... | b7c94899aba6dc5507bba1f1231954740dfbae1e | 14,298 |
from typing import Dict
from typing import Any
def append_tf_example(data: Dict[Text, Any],
schema: Dict[Text, Any]) -> tf.train.Example:
"""Add tf example to row"""
feature = {}
for key, value in data.items():
data_type = schema[key]
value = CONVERTER_MAPPING[data_ty... | 15fb71794c4e87923197927d80597a8f0e960690 | 14,299 |
def can_login(email, password):
"""Validation login parameter(email, password) with rules.
return validation result True/False.
"""
login_user = User.find_by_email(email)
return login_user is not None and argon2.verify(password, login_user.password_hash) | 41908f753efa1075d6583ee8a6159011bd8af661 | 14,300 |
def toPlanar(arr: np.ndarray, shape: tuple = None) -> np.ndarray:
"""
Converts interleaved frame into planar
Args:
arr (numpy.ndarray): Interleaved frame
shape (tuple, optional): If provided, the interleaved frame will be scaled to specified shape before converting into planar
Returns:... | 0f54b14b72a05fe0b20bdfd14c31084aa9c917ca | 14,301 |
def downsample_grid(
xg: np.ndarray, yg: np.ndarray, distance: float, mask: np.ndarray = None
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Downsample grid locations to approximate spacing provided by 'distance'.
Notes
-----
This implementation is more efficient than the 'downsample_xy' f... | 6ba36486bc081b85670918c63b8c1f183c284503 | 14,303 |
def convert_12bit_to_type(image, desired_type=np.uint8):
"""
Converts the 12-bit tiff from a 6X sensor to a numpy compatible form
:param desired_type: The desired type
:return: The converted image in numpy.array format
"""
image = image / MAX_VAL_12BIT # Scale to 0-1
image = np.iinfo(desire... | 6a3287946d1f56f57c6a44fc3f797753ebcd251a | 14,304 |
def dm_hdu(hdu):
""" Compute DM HDU from the actual FITS file HDU."""
if lsst.afw.__version__.startswith('12.0'):
return hdu + 1
return hdu | 87d93549f3d45ae060ced0f103065b6221e343db | 14,305 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.