content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import subprocess
import os
import sys
def execute(command, env=None, split_lines=False, ignore_errors=False,
extra_ignore_errors=(), translate_newlines=True, with_errors=True):
"""
Utility function to execute a command and return the output.
"""
if isinstance(command, list):
debug... | 68f1ce92aab50c34b5222b0940c0ad46aa850ed7 | 52,100 |
def my_kernel_exp(dis, gamma=.1):
"""gamma is auto tuned. The argument gamma means shrink_ratio.
"""
# if full_output:
# print 'gamma = {0:.4f} dim = {1:.4f} squared = {2}'.format(gamma, dim, squared)
dis *= -gamma
np.exp(dis, dis)
return dis | e1f2eb165e6e05528bb5ad9e409f5ed76a1054ef | 52,101 |
import logging
import os
import gzip
def __get_mir_precursor_to_mature_mapper__():
"""
:return: a dictionary mapping taxonomy ID and miRBase precursor ID to a list containing the IDs of mature miRNAs
made from this precursor, e.g. the tuple ('9606', 'hsa-mir-155') might be mapped to ['hsa-miR-155... | 540b5a4ac501153ff2b4704b67ae3ece5616b63a | 52,102 |
import argparse
def parse_args():
""" PARAMETERS"""
parser = argparse.ArgumentParser("train")
parser.add_argument("--use_cpu", action="store_true", default=False, help = "use cpu mode?")
parser.add_argument("--gpu", type = str, default="0", help = "specify the gpu device")
parser.add_argument("--b... | fb30f8c2f44e6b7f46622a4476ac47d75008aecb | 52,103 |
def pipeline_run_add_tag(run_id, tags, organization=None, project=None, detect=None):
""" Add tag(s) for a pipeline run.
:param run_id: ID of the pipeline run.
:type run_id: int
:param tags: Tag(s) to be added to the pipeline run. [Comma seperated values]
:type tags: str
:rtype: list of str
... | f5f8dd7f2a40880a3bd4f271d64f3c0d25d87c4f | 52,104 |
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.),
option=1):
"""
Anisotropic diffusion on single channel image
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter - number of iterations
ka... | cb2a972d48c160e0cf1dbecc3b03ce83137e95c0 | 52,105 |
def add_keys2(a, b, B):
"""
aG + bB, G is basepoint
:param a:
:param b:
:param B:
:return:
"""
return tcry.xmr_add_keys2_vartime_r(a, b, B) | 49586fa9e6917c66ccf65f3ac10f404681e36dab | 52,106 |
from typing import List
from re import T
from typing import Optional
from typing import Callable
from typing import Set
def uniquify(lst: List[T], key: Optional[Callable[[T], K]] = None) -> List[T]:
"""Remove duplicates in lst but preserve the order
Args:
lst: a sequence with possible duplicates
... | 402f664b3222acd46365a3a9dbd27e2dea6d79a7 | 52,107 |
def make_point_plot(x,y):
"""It plots the point chart of the data"""
data_points = pd.DataFrame({'x': x.flatten(), 'y': y.flatten()})
chart = alt.Chart(data_points).mark_point(size=50, color='red',filled=True).encode(
x="x",
y="y"
)
return chart | 5ee0198975ac7db16023b159d7533d59c313cc96 | 52,108 |
from algs20_graph.single_source_sp import dijkstra_sp
def single_source_shortest_path(graph, src):
"""
Act on Single Source Shortest Path and return path as dictionary, where
each node is expanded to have its
"""
(_, edge_to) = dijkstra_sp(graph, src)
expanded = {}
for n in graph.nodes():... | 0d7077933fe23f811fff3a2c06a8f3fc8c2d2971 | 52,109 |
def busco_datasets():
"""BUSCO dataset information
:return: List containing information for each dataset available in file BUSCO_dataset.csv under data directory.
.. seealso:: Additional information on BUSCO datasets available.
- :doc:`BUSCO datasets <../../../data/BUSCO_datasets>`
.. seealso:: This func... | 16c581e55967f273321f4b4f68a74f9868d7a319 | 52,110 |
def aveThick(sit):
"""
Only calculates ave thickness for min and max time... no area weighting
"""
minSep = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,9,:,:],(1,2)))
minMar = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,3,:,:],(1,2)))
print '\nCompleted: Calculated average for Sept/Ma... | 377eab13adbd3f25041337cb7fe784a78b44a74b | 52,111 |
import os
def get_module_version():
"""This function gets the version number of the scripts and returns them in array form."""
modules = MODULE_LIST()
scripts = []
for module in modules:
if module.SCRIPT.public:
if os.path.isfile('.'.join(module.__file__.split('.')[:-1]) + '.json')... | cee366f1aaa22bb3c1338e47636e53829449b00c | 52,112 |
from typing import Dict
from typing import Mapping
import inspect
from typing import Optional
from typing import Any
from typing import Tuple
import functools
def BP(bp_state: BPState, temperature: float = 0.0) -> BeliefPropagation:
"""Function for generating belief propagation functions.
Args:
bp_st... | e96bf22c2e07ec59b1e0c7d653f8956a82b5c3a5 | 52,113 |
def whois_reg_date(whois):
""" Fecha en la que fue registrado el sitio"""
reg_date = []
try:
reg_date = whois.creation_date
if reg_date != None:
if isinstance(reg_date, datetime.date):
reg_date = reg_date
elif len(reg_date) > 1:
reg_dat... | 4c31088349bc45580dc758879ca1dfedef4d8c4a | 52,114 |
import re
def get_answer_indices_from_sentence(answer_text: str, sentence: str, loose_match: bool = False):
"""
first match is returned in match case
Args:
answer_text (str)
sentence (str)
loose_match (bool) : if True, regex also matches substrings
Returns:
None, if n... | 12b8094de7730134cfc7264e9c1248b00ff53a68 | 52,115 |
import urllib
import logging
import click
import json
import re
def imdb_get_data(title, mtype, api_keys=[]):
"""This function fetches the poster url and other data related
to Imdb movies from Google Custom Search JSON API."""
movie_title = title
media_type = mtype
gcsearch_api_key = api_keys[0]
... | 0e174379de1b408411961e7708edee002a88e1a3 | 52,116 |
def nnlsfit(data, bvals, region=None):
""" Implement Non Negative Fitting for IVIM
Parameters
----------
data: array-like, 4D Matrix
bvals: array-like
region: array-like, [(x1,x2),(y1,y2),(z1,z2)]
optional (default= None)
Returns
-------
d_star: 3D Matrix
Th... | 8efe51013c0b58e35675c854a23816cb73ca5c02 | 52,117 |
def check_if_scheduled_run(time_run: str = None, time_schedule: str = None) -> bool:
"""
Check if run was scheduled or started by user.
Args:
time_run (str, optional): The time the Flow was started. Defaults to None.
time_schedule (str, optional): Scheduled time of Flow. Defaults to None.
... | 8e9d6db6fe66da9314515a024919e9360b856762 | 52,118 |
def controlled(gate):
"""Return a controlled quantum gate, given a quantum gate.
If 'gate' operates on :math:`n` qubits, then the controlled gate operates
on :math:`n+1` qubits, where the most-significant qubit is the control.
Parameters
----------
gate : np.ndarray[complex]
A quantum ... | 653b92af9d83c0ab30b8ebebe532bc7061f0cfbf | 52,119 |
def get_links(anumberscode):
"""
Finds CloudStor links for selected anumbers
Args:
`anumberscode`=list of anumbers
Returns:
`FilteredList`= list of corresponding links
"""
try:
FileDirectory=pd.read_csv('https://geo.loop-gis.org/files/FileDirectory.csv',encoding = "ISO-88... | eebc6d5d2df162bd43135c1647dce8c03f577e04 | 52,120 |
import copy
def passed_test(dtype, as_matrix, provide_C, trans_a, trans_b):
"""
Run one general matrix-matrix multiplication test.
Arguments:
dtype: either 'float64' or 'float32', the NumPy dtype to test
as_matrix: True to test a NumPy matrix, False to test a NumPy ndarray
... | f595706e6b83c3b8d03481a4a9849d12c9846c6d | 52,121 |
def handler_500(request, exception=500, template_name='handler_500.html'):
"""
handler_500 自定义500错误
只有在Debug == False的时候生效
"""
return render(request, template_name) | 8032395a3072cefc98f91817039294f01e8073fd | 52,122 |
import re
def re_repl_escape(s):
"""
Escape backreferences in a string, for the second arg of re.sub().
Parameters:
s: the string to escape
Dependencies:
modules: re
"""
return re.sub(r'\\([1-9][0-9]?)', r'\\\\\1', s) | 4ae7e4198dd65eb46d8dbbf71cf8f28230eb2c76 | 52,123 |
def get_x_vals(stats: dict, x_type: str, date_range: list[tuple]) -> list:
"""Gets the specified x value within a given date range."""
if x_type in X_OPTIONS.values() and x_type != X_OPTIONS[1]:
return [round(stats[date][x_type]) for date in date_range]
else: # Date
return date_range | 4e4f152dd33dca19704bf426390ced02fb9acb43 | 52,124 |
def allowed_file(filename):
"""判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中"""
return '.' in filename and filename.rsplit(
'.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] | 6b4426e8f35b5e89ca8f28a8c55a4f6cd422b3e6 | 52,125 |
import logging
def create_resource_group(
profile_credentials, subscription_id: str, location: str, resource_group_name: str
) -> ResourceGroup:
"""Creates resource group if it doesn't exist
Args:
profile_credentials : credentials from Azure login
subscription_id (str): subscription you w... | 479608ffe397fd0eb41d857d91771cb4358c1c4f | 52,126 |
def split_data(data, ratio, shuffle=1):
"""Split dataset according to ratio, larger split is first return"""
n_exs = len(data[0])
split_pt = int(n_exs * ratio)
splits = [[], []]
for col in data:
splits[0].append(col[:split_pt])
splits[1].append(col[split_pt:])
return tuple(splits... | fc837dd9f721950dde18cee9ec33eab5e3e96f77 | 52,127 |
def get_user_session_data(parent_folder, user_id, user_session_id):
"""
Combine accelerometer, gyroscope, and activity labels for a specific session of a user
Note: Timestamps are ignored when joining accelerometer and gyroscope data.
:param user_id: user id
:param user_session_id: user session id
... | 1067c791085230a910c8682a293d600888dc2223 | 52,128 |
def jtag(tag):
""" Helper to translate tag to serializable format"""
return (tag[0].devanagari(strict_io=False), [t.devanagari(strict_io=False) for t in list(tag[1])]) | cb8245a435d67d9678e71d449ae9401b9562cb4c | 52,129 |
import math
def _nongeo_latlng2xy(lat_deg, lng_deg):
"""
"""
lat = _DEG_TO_RAD * lat_deg
lng = _DEG_TO_RAD * lng_deg
# First, project to pseudo-mercator
# https://en.wikipedia.org/wiki/Web_Mercator_projection#Formulas
x_proj = _EPSG_3857_X_EXTENT / (2.0 * math.pi) * lng
y_proj = _EPSG... | b062d453339924e4d15a57830e41978488b98044 | 52,130 |
def read_file(file_path):
"""Reads a file contents given a file path"""
file_contents = None
with open(file_path) as f_desc:
file_contents = f_desc.read()
if not file_contents:
raise CLIError('Could not read {}'.format(file_path))
return file_contents | 4688e7c58abc5b6c384e85dbb98f35127085c7f2 | 52,131 |
def part_2a_namd_equilb_NPT_control_file_written(job):
"""General check that the namd_equilb_NPT_control_file
(high temperature to set temp NAMD control file) is written."""
return namd_control_file_written(job, namd_equilb_NPT_control_file_name_str) | 7f77e47be8d2b88bec843de02b7447b0360a2870 | 52,132 |
from typing import Optional
from typing import Dict
from typing import Union
from typing import List
def AutoLayoutModel(
config_path: str,
model_path: Optional[str] = None,
label_map: Optional[Dict]=None,
device: Optional[str]=None,
extra_config: Optional[Union[Dict, List]]=None,
) -> "BaseLayout... | 6d1d4d7f637491bcdbb10b9b93575a53733627eb | 52,133 |
def assert_positive_negative_temporal_consistency(y, t, month_variance=1):
"""Helper function to assert malware-goodware temporal constraint (C2).
In any given testing period, all testing objects must be from the time
window under test. In the malware domain this constraint has often been
violated so t... | ae8c05dd92d990f7fe5260723033c59c051fd710 | 52,134 |
def shape_small_first(shape):
"""sort a tuple so that the smallest entry is swapped to the beginning
"""
if len(shape) <= 2: # no changing dimensions if channel-dim is missing
return shape
smallest_dim = np.argmin(shape)
if smallest_dim != 0: # assume that smallest dim is color channel
... | 0caf5a69d2c12dff31deb002891df71886ce19b7 | 52,135 |
import io
def reformat_cmplx_hoh(cmplx):
"""
get a complex has HoH and split it
"""
stoi = []
for cond in cmplx:
tmp_stoi = io.makehashlist()
tmp_prot_nr = []
for repl in cmplx[cond]:
pks = {k: cmplx[cond][repl][k]["I"] for k in cmplx[cond][repl]}
pk... | e8b6361e7637bc7bc446cd795935cfb3899fc731 | 52,136 |
def filter_builtin():
"""filter: Filter items using a function. Prefer list comprehension."""
return "{}ged top secret".format(
''.join(filter(lambda info: info not in 'open', "pentagone"))) | ae1d96fb5bfa4a675538bf33a5adcd2d2f64c6e5 | 52,137 |
def calculate_gold(*items):
"""Calculate gold for buying given items"""
# access cost in the item dictionary
get_cost = lambda x: x[0][x[1]]['cost']
# return sum of costs of all items
return sum(
# get cost of each item
map(get_cost,
# map items onto their categories
... | 08b1ccd6599d111119c8b2fcbf3a02e0d16d6978 | 52,138 |
from typing import Optional
from datetime import datetime
def skip_reload(cache_load_time: Optional[datetime.datetime], refresh_cache: bool) -> bool:
"""Skip reloading the cache?"""
return abc_depoyment_map.skip_reload(cache_load_time, refresh_cache, REQUIRE_REFRESH_LIMIT) | 81e482b0e43f7f240cbe70733d340fd7f84d6a53 | 52,139 |
def combined_bbox(layers):
"""
Returns a bounding box for ``layers`` or None if this is not possible.
"""
bboxes = [layer.bbox for layer in layers
if layer.bbox is not None and layer.bbox.width > 0 and layer.bbox.height > 0]
if not bboxes:
return None
lefts, tops, rights, ... | c2843bf23393c8d3e75a3fe862e488101dcfbdd0 | 52,140 |
import delphin.codecs
import importlib
def import_codec(name: str):
"""
Import codec *name* and return the module.
"""
codecs = namespace_modules(delphin.codecs)
fullname = codecs[name]
return importlib.import_module(fullname) | cba864133e3cce3e44e06eac23224f6e60b025fe | 52,141 |
def is_named(name):
"""
:samp:`Predicate for loose class-name detection.`
::
f(cls) = cls.name == name or cls.qualified_name == name
:param name: the class-name or qualified class-name in the detection
:return: lambda for loose class-name detection
"""
return lambda cls: name == c... | d26fbb6d853f195cfcc70a6f1791cbacfc7aebd7 | 52,142 |
def get_and_colleagues(ref_string):
"""
:param ref_string:
:return:
"""
match = COLLEAGUES_PAT.search(ref_string)
if match:
andcolleagues = match.group('andcolleagues')
return ref_string.find(andcolleagues), len(andcolleagues)
return 0, 0 | 1a9c2c5f46f7bee9eecbd960c8a2b5e591e80790 | 52,143 |
from django.utils.module_loading import import_string
def app_factory(global_config, django_wsgi_application):
"""
Paste app factory that imports and returns the given WSGI applicaton.
Args:
global_config: The global paste configuration
django_wsgi_application: The wsgi application to dep... | 829d33e21594da6066cc1116985b3292e75186ca | 52,144 |
def fix_arn(arn):
"""Function that attempts to "canonicalize" the given ARN. This includes converting
resource names to ARNs, replacing incorrect regions, account IDs, etc."""
if arn.startswith("arn:aws:lambda"):
parts = arn.split(":")
region = parts[3] if parts[3] in config.VALID_REGIONS el... | 109b0450b9ebd01d6aeba17fc28ef069d1c4544c | 52,145 |
from typing import Any
from typing import Iterator
def ocr_extract(image_data: bytes, link: str, tld: str) -> list[str]:
"""Scan for all valid URLs from a given `image_data` bytes string
Args:
image_data (bytes): Bytes string of image to be scanned
link (str): URL source of image to be scanne... | 4c3507ef1488abdaf2c39eba5ab95c6b782ee785 | 52,146 |
def route(route : dict[str : FunctionType], filter : FunctionType = lambda x : x):
"""Routes links in clisd.py"""
last_link = None
def route_link(e=None, page : str = None, _route : dict[str : FunctionType] = route):
route = _route
# Finds page to route in url
if page:
... | 2563d1600cf2f6129a7f2370445d76f66df136f3 | 52,147 |
import imghdr
def make_answer():
"""Create the message to send"""
# Create the message and set a subject
msg = EmailMessage()
msg["Subject"] = "A random image."
try:
# Choose an image
attachement = IMG_FOLDER + "/" + rdm(IMG_FOLDER)
# Attach the image to the email
... | 9fba96f904de770772580f275229e7540d1db86c | 52,148 |
from typing import List
def download_assets(stac_item: StacItem,
save_directory: str,
from_bucket: bool = False,
nsl_id: str = None) -> List[str]:
"""
Download all the assets for a StacItem into a directory
:param nsl_id: ADVANCED ONLY. Only nece... | eda98decae5709dfe66d13a9dfd2a19b7a29483f | 52,149 |
def shake_128() -> HashAlgorithm:
"""
Convenience function to create hash algorithm object.
"""
return HashAlgorithm(HashAlgorithmId.SHAKE_128) | cced46c8650e24a33772f6b656e5c5c785315318 | 52,150 |
def update_action_effects_with_negated_counterparts(action: Action, negpreds):
""" """
neweffects = []
for eff in action.effects:
if not is_propositional_effect(eff):
raise RepresentationError(f"Don't know how to update negated counterpart atoms for effect {eff}")
atom = eff.ato... | 610253ed171d72941374826b0fa629b1cc6a5f0b | 52,151 |
from typing import Any
def is_listlike(x: Any) -> bool:
"""Check whether `x` is list like, e.g., Tuple, List, or Numpy object.
Parameters:
----------
x: A python object to check.
Returns:
----------
`True` iff `x` is a list like sequence.
"""
return (isinstance(x, (list, tuple))) | 5820a62e0fcb8fead77485c896b3aa864ef555f0 | 52,152 |
import glob
import os
import csv
def read_csv_results(conf):
"""
After all experiments have run, read in Rsquared and RMSE values for all jobs into dictionaries
Args:
conf: Settings object, containing fields where to find saved results, which are stored as CSVs
Returns:
Two dictionari... | c0bda07099f29e1af27a6aa93c85c3beff754f54 | 52,153 |
def datasetDataText(request, dataset_name):
""" Returns data in text format for a specific dataset. """
#
header_language = request.GET.get('header_language', None)
#
dataset = models.Datasets.objects.get(dataset_name = dataset_name)
dataset_file_name = dataset.dataset_file_name
#
data_a... | c3ccc9430574160f0839ca12bd063010ea8036d4 | 52,154 |
def order_detail(user_key, category_key, order_key):
"""
The page showing the details of a single order -Fetch a specific order
including all steps (GET)
It also handles PUT and DELETE of the order
It also handles updates an existing order
"""
error = None
editable = False
order_deta... | 4b181867c07f8ef293357fa4da16014330957871 | 52,155 |
def distance_corr(X, Y):
"""
Computes the distance correlation between X and Y.
Taken from pypi package dcor based on the paper:
*Measuring and testing dependence by correlation of distances*
by Gábor et Al (2007)
Parameters
----------
X : numpy array like object where the rows correspon... | b4b85c58041760d96e852ad032fd6227f15dc8e1 | 52,156 |
import json
def pinyin_dict_affiche(request):
"""recevoir les valeurs des formulaires front-end via POST
et transmission des informations pinyin analysées au front-end
Args:
request (QueryDict):
les valeurs des formulaires front-end
Returns:
data_pinyin (JSON):
... | a2e167250cf6df2b78f33dfb18a47825d3eed928 | 52,157 |
def diff_sort(matrices, x, softmax=softmax):
"""
Approximate differentiable sort. Takes a set of bitonic sort matrices generated by bitonic_matrices(n), sort
a sequence x of length n. Values may be distorted slightly but will be ordered.
"""
for l, r, map_l, map_r in matrices:
a, b = l @ x,... | 25152f16b9c0ec4ca81ea0e44d4642bf5a7d257f | 52,158 |
def searchwiki(txt, lang='en'):
""" parse wiki data. """
input = []
for i in txt.split():
if i.startswith('-'):
if len(i) != 3: continue
else: lang = i[1:]
continue
input.append(i.strip().capitalize())
what = "_".join(input)
url = u'http://%s.... | e6be584fee726e9781e39078a9ab7588e130b8ef | 52,159 |
import torch
def test():
"""Runs the model on the test data."""
modelA.eval()
modelB.eval()
test_loss = []
errors = []
with torch.no_grad():
for batch_idx, data in enumerate(test_loader):
data = data.permute(0, 3, 1, 2)
dataA = data[:, modA].float().to(device1)
... | ef73bef6f5722cca7b42336f7a6e43bc67673eb9 | 52,160 |
def ifgcfg_exists(ifgcfg_id, version):
"""Return True if ifg-cfg exists."""
query = {
"query": {
"ids": {
"values": [ifgcfg_id],
}
},
"fields": []
}
index = "grq_{}_s1-gunw-ifg-cfg".format(version)
result = query_es(query, index)
r... | 7d40dc1b45ae5ad2573baffc5dcbd148677a7757 | 52,161 |
import sys
import platform
import os
def find_built_exe( source, name ):
"""
Find an executable that was built in the repo
:param source: The location of the exe's project, e.g. tools/convert
:param name: The name of the exe, without any platform-specific extensions like .exe
:return: The full pa... | 07e1feecd2300ae92fe8f3dd804c56ab3f36eddf | 52,162 |
def calibration_image(file_name, coordinates):
"""calibrate a source image
Arguments:
file_name {int} -- image index
coordiantes {list} -- list of coordinates for homography to plot
"""
prefix_length = 6 - len(str(file_name))
source = path_to_image + str(0)*prefix_length + str(file_... | 6b37d387418c8c1328d450220b204ed6d182ae1d | 52,163 |
import codecs
import logging
def decompress(structure: Value):
"""
Performs decompression on the input value if the codec field has been set and is valid. If the data is being sent
uncompressed already, will just reshape the data using the sizes specified in the dimension field.
Parameters
------... | a3b07a4bcb5dc91344ea339033f1adf27c3e01e6 | 52,164 |
import scipy
def incubation_dist(t: np.ndarray) -> np.ndarray:
"""Incubation period as a log-normal PDF (Lauer et al., 2020).
Args:
t: np.array of days of incubation (i.e. days from infection to symptoms).
Returns:
Relative probability of the specified incubation time.
"""
mu = 1.621
sig = 0.418... | 39f6c570440afe3afb77d65563871079d2cb34bf | 52,165 |
def pid_from_context_or_data(value, context, **kwargs):
"""Get PID from marshmallow context."""
pid = (context or {}).get('pid')
if pid is None:
return value
else:
return pid.pid_value | dff32845ea0d2541503802bdd85ccb299091325b | 52,166 |
import io
def partial_build(src, lang, bsp_c3, opt_level, march, reporter):
""" Compile source and return an object """
if lang == 'c3':
srcs = [
relpath('..', 'librt', 'io.c3'),
bsp_c3,
io.StringIO(src)]
o2 = c3c(
srcs, [], march, opt_level=opt_... | 61ae71a2ecfbff3b41b0ae6afb4eb86b0e81bcdb | 52,167 |
import re
def clean_phoenix_2014_trans(prediction):
"""
Yutong
I think the format of ground truth annotation is already well processed.
Some parts of predicted gloss sequence might be processed using this func. e.g. combine single char with +
"""
prediction = prediction.strip()
prediction ... | eceb6f43cc51f66d88045d5eecea7144cf3eaaaf | 52,168 |
import six
def ManagerFactory(name, superclass, qs=QuerySet):
"""Create a manager class, using the given superclass, and adding
django_pg's specific behavior.
"""
# It's completely fine to use our custom manager for related fields,
# and it's necessary, since we need to ensure that our custom quer... | c950898a4ce8fe886f740e2799163a002fd65f79 | 52,169 |
import math
def gfit1(xi,yi,m=5):
"""
moments around a peak
(also) rely on number of pixels left and right of the peak. Masking optional
"""
print("GFIT1")
ipeak = yi.argmax()
xpeak = xi[ipeak]
ypeak = yi[ipeak]
print(ipeak,xpeak,ypeak)
print(xi[ipeak-m:ipeak+m])
print(yi[i... | 3d7f5ccdece2a7fb4f0988a169b35e2f3671f4a3 | 52,170 |
def characteristic_matrix_p(lambda_, d, n, theta):
"""Compute the characteristic matrix M_j^p for a layer of a material stack and p-polarized light.
Uses (4.49) to compute (4.55) from BYU optics book, edition 2015
Parameters
----------
lambda_ : `float`
wavelength of light, microns
d :... | cc67de317b94be42d9f1478b3ae2063d60b9bfaf | 52,171 |
def nets_ib_by_bus_zone_with_boundary_branches(
net, eq_type=None, separate_eqs=True, duplicated_boundary_bus_elements=True, **kwargs):
"""
INPUT:
**net** - pandapower net - In net.bus.zone different zones must be given.
OPTIONAL:
**eq_type** (str, None) - If given, equivalent eleme... | b4de2d1e4be3e2003fd43ffee00f9bed51f6cfb4 | 52,172 |
import random
def get_label_colours(num_class):
"""
return color code for visualizing affordance/object map
"""
all_label_colors = []
random.seed(255)
for i in range(num_class):
curr_color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
all_label_colo... | aaa99885779cc51d2812c3df9e3814afaa495604 | 52,173 |
import time
def timed(fn):
"""Simple timing decorator that stores the elapsed time
as a string property called 'timed' to the fn.
"""
@wraps(fn)
def _timer(*args, **kwargs):
start = time.time()
fn(*args, **kwargs)
end = time.time()
diff = end - start
elapse... | 0c63c21cc1eaf2930ae58ff46a07818503aeac47 | 52,174 |
def get_column_letter(col_idx):
"""Convert a column number into a column letter (3 -> 'C')
Right shift the column col_idx by 26 to find column letters in reverse
order. These numbers are 1-based, and can be converted to ASCII
ordinals by adding 64.
"""
# these indicies corrospond to A -> ZZZ ... | 6f65209d6fc38f3d858d36b4c21908cafea2a494 | 52,175 |
def get_default_cacheinfo():
"""
Return default CacheInfo
"""
return __cacheinfos[__SECTION_CACHE_DEFAULT] | 84aee842b1e0614dd4403644c7c095baa5d2fc23 | 52,176 |
def get_packets_for_flows(sub, flows):
"""
Get packets sent from a subscriber to match a set of flows
Args:
sub (SubscriberContext): subscriber to send packets towards
flows ([FlowDescription]): list of flows to send matching packets to
Returns:
list of scapy packets to send
... | 9b0b210c4e7ff3a8e8f2367d6208350340a14b32 | 52,177 |
def lower_array(x1_arr, y1_arr, x2_arr, y2_arr):
"""function to find the lower bound of two curves(x1, y1), and (x2, y2) represented by two arrays.
"""
# special use: for the first comparison, if y1_arr is [], then y2_arr is passed to it
x1_arr = np.asarray(x1_arr)
x2_arr = np.asarray(x2_arr)
y... | ff985873295697554cb1c1d7e79b327dec2d7e92 | 52,178 |
import re
def is_valid_hostname(hostname):
"""Convert domain label into IDN ACE form (handles internationalized
domains and regular (ascii) domains"""
hostname = from_unicode(hostname).to_text()
# stackoverflow.com/a/2532344/1707152
if len(hostname) > 255:
return False
if hostname[-1]... | 1232173f1c2a2fde4cf2dda5fe1741656c5aca71 | 52,179 |
def delBlank(strs):
"""
Delete all blanks in the str.
"""
ans = ""
for e in strs:
if e != " ":
ans += e
return ans | a6155af200918819055533057f63b4b44c8dd508 | 52,180 |
def jdcnv(year, month, day, hour):
"""Convert Gregorian time (UTC) to Julian Date
Input:
year = year (scalar int)
month = month 1-12 (scalar int)
day = day 1-31 (scalar int)
hour = fractional hour (scalar double)
Output:
julian = Julian Date (scalar double)
Origina... | 33f577c95a3e44f7f9ad3002ca170fa0b55ac147 | 52,181 |
def get_all_people():
"""
You can hit the resource name without an ID to get a listing of all of that resource
"""
resp = session.get(GHIBLI_URL + "people")
people = [Person(**json_person)
for json_person in resp.json()]
return people | 80dd9c5bd3103f7a09a8e5a5a55a26572865f996 | 52,182 |
import itertools
def generate_preset_test_translations(dimensions=3):
"""Generates a set of translations."""
permutations = itertools.product([0.1, -0.2, 0.5, 0.7, 0.4, -0.1],
repeat=dimensions)
return np.array(list(permutations)) | 3aee3411cf0493f7a103c2366c7e55cd46012b6b | 52,183 |
def closest_precise_locator_for(element: WebElement, root: WebElement = None):
"""Builds the most precise locator which matches `element`.
If `element` does not have a role, return a semantic locator which matches the
closest ancestor with a role. "Precise" means that it matches the fewest other
elements, whil... | 1177ce673212e33cdc6400f9d01470e8e60e97ad | 52,184 |
import re
def splitn(s, n):
"""split string s into chunks no more than n characters long"""
parts = re.split("(.{%d,%d})" % (n, n), s)
map(parts.remove, [""] * parts.count(""))
return parts | 3f0f697f54515e26f98bc08b53cb4d39952ed128 | 52,185 |
import os
def load_output(data_path, provinces, notrade=True):
"""Read output from disaggregation process and translate to usable pandas DataFrame
Parameters
- data_path - String name of data path
- provinces - pandas DataFrame with provincial/regional data
- notrade - Boolean to spec... | b3947dce81cdd00590d807c94d31d6ff0b7788ed | 52,186 |
def skinHasImage(image):
"""
Returns ``True`` if the image file exists in the skin.
:param image: string - image filename
.. note:: If the media resides in a subfolder include it.
(eg. home-myfiles\home-myfiles2.png). You can use the above as keywords for arguments.
example::
exi... | f64af64c4d18298fe56ebff8388d6fc3020ff5e1 | 52,187 |
def is_date(string, fuzzy=False):
""" return whether the string can be interpreted as a date """
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False | 4330c82967845abb3390005c6a47dbe069f9a2ca | 52,188 |
from pathlib import Path
import copy
def known_good_image_archive(request, tmp_path: Path) -> TypingKnownGoodImageArchive:
"""Provides 'known good' metadata for a local image that can be modified."""
path_destination = tmp_path.joinpath(request.param["resource"])
path_source = get_test_data_path(request, ... | 86ed5e4afb1f4cc500adffc06b9c2dd8a5827787 | 52,189 |
import csv
def LoadMOS(mos_csv):
"""Load a csv file withMOS scores.
Args:
mos_csv: Path to a csv file that has degraded and MOS.
Returns:
Dictionary with filename keys and MOS values
"""
mos_dict = {}
with open(mos_csv, 'r') as csvfile:
mos_reader = csv.reader(csvfile)
for row in mos_rea... | e98cbf93e3bc889a31a98ff32a9f9189a850a55f | 52,190 |
from edge.models import Genome
def import_gff(name, fn):
"""
Creates a new genome using the specified GFF file.
name: Name of genome
fn: path to GFF file
"""
if Genome.objects.filter(name=name).count() > 0:
raise Exception('There is already a genome named "%s"' % (name,))
g = Ge... | 5bc16276278bc4f1559e48d4450a24cccf114024 | 52,191 |
import optparse
import logging
import os
import sys
def main(config_path=None):
""" The main entry point for the unix version of dogstatsd. """
COMMANDS_START_DOGSTATSD = [
'start',
]
parser = optparse.OptionParser("%prog [{commands}]".format(commands='|'.join(Dogstatsd.COMMANDS)))
parser... | d6ccf3c12ba7de4f32861fd17275e78e54648ef4 | 52,192 |
import unicodedata
def url_is_invalid_unicode(url_string):
""" Check for unicode control characters in URL """
for x in str(url_string):
if unicodedata.category(x)[0] == "C":
return True
return False | d1a3974b24023c46a337c7e17718e00aa5916c7d | 52,193 |
import functools
def fn_with_custom_grad(grad_fn, use_global_vars=False, use_entire_scope=False):
"""Decorator to create a subgraph with a custom gradient function.
The subgraph created by the decorated function is NOT put in a Defun and so
does not suffer from the limitations of the Defun (all subgraph o... | 48563bc9cb940853378f3b24193fd67a3daa903f | 52,194 |
import logging
def _monkey_patch_dataset_method(strategy):
"""Monkey-patch `strategy`'s `make_dataset_iterator` method."""
def make_dataset(self, dataset):
logging.info('Using pure synthetic data.')
with self.scope():
if self.extended._global_batch_size: # pylint: disable=protected-access
r... | 7f60d5a941aa300d65c777844e208800b9760b08 | 52,195 |
def _xvert(cls, result_item, generate_links=True):
"""
converts the response object into Json
:param generate_links: if True, it will add the HATEOAS links to the response
:param result_item: the actual item which will get converted
:return:
"""
if isinstance(result_item, Model):
mo... | 97bdc45550393f096f3187edb1d90e111b423901 | 52,196 |
def Gamma_correction(low_frequency, alpha=0.5):
"""
Adjust the coefficient of low frequency component using Gamma correction.
:param low_frequency: the low frequency component of the image calculated with Shearlet transformation.
:param alpha: adjustment factor with a range from 0 to 1, in addition, it ... | 5d750ab117dc6dc0f2f1906e84c793fa98aa12b4 | 52,197 |
def assign_first_visit(df: DataFrame, column_name_to_assign: str, id_column: str, visit_date_column: str) -> DataFrame:
"""
Assign column to represent number of participants in household
Parameters
----------
df
column_name_to_assign
id_column
visit_date_column
"""
window = Windo... | 254a8d50bc844fc83bd02552d0224d6fbfc6ecec | 52,198 |
import msgpack
def _msgpack_ext_pack(x):
"""Msgpack encoders for custom types."""
if isinstance(x, complex):
return msgpack.ExtType(_MsgpackExtType.native_complex,
msgpack.packb((x.real, x.imag)))
if isinstance(x, jax.ShapedArray):
return msgpack.ExtType(_MsgpackExtType.shaped... | 514447f98ca4855b14a70e962fa01033d39b3842 | 52,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.