content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_http_proxy():
"""
Get http_proxy and https_proxy from environment variables.
Username and password is not supported now.
"""
host = conf.get_httpproxy_host()
port = conf.get_httpproxy_port()
return host, port | f04dc8580d9fdd3d867c5b28fa3694fe82a6739a | 13,035 |
def get_parser_udf(
structural=True, # structural information
blacklist=["style", "script"], # ignore tag types, default: style, script
flatten=["span", "br"], # flatten tag types, default: span, br
language="en",
lingual=True, # lingual information
lingual_parser=None,
strip=True,
r... | cf12b36fe9219aabfd746b2ad1f1f39e62ad7fe9 | 13,036 |
def img_preprocess2(image, target_shape,bboxes=None, correct_box=False):
"""
RGB转换 -> resize(resize不改变原图的高宽比) -> normalize
并可以选择是否校正bbox
:param image_org: 要处理的图像
:param target_shape: 对图像处理后,期望得到的图像shape,存储格式为(h, w)
:return: 处理之后的图像,shape为target_shape
"""
h_target, w_target = target_shap... | e950e0e8cca4f31449feb12203ee9a9ef74baa8c | 13,037 |
def pivot_timeseries(df, var_name, timezone=None):
"""
Pivot timeseries DataFrame and shift UTC by given timezone offset
Parameters
----------
df : pandas.DataFrame
Timeseries DataFrame to be pivoted with year, month, hour columns
var_name : str
Name for new column describing da... | 914ba75929caacd16da5170e98a95f2135a1682f | 13,038 |
def _preprocess_stored_query(query_text, config):
"""Inject some default code into each stored query."""
ws_id_text = " LET ws_ids = @ws_ids " if 'ws_ids' in query_text else ""
return '\n'.join([
config.get('query_prefix', ''),
ws_id_text,
query_text
]) | bc63391724773cd4a60f3dc9686d243d6d733b40 | 13,039 |
def handler_request_exception(response: Response):
"""
Args:
response (Response):
"""
status_code = response.status_code
data = response.json()
if "details" in data and len(data.get("details")) > 0:
data = data.get("details")[0]
kwargs = {
"error_code": data.get("err... | 8847b4a1fd6f90d6e25d0ef8dc33a32e38e81617 | 13,040 |
def mlrPredict(W, data):
"""
mlrObjFunction predicts the label of data given the data and parameter W
of Logistic Regression
Input:
W: the matrix of weight of size (D + 1) x 10. Each column is the weight
vector of a Logistic Regression classifier.
X: the data matrix of size... | 18bf0c86195cf144eb63f5b6c440f92c57d2fe9b | 13,043 |
from .error_pages import add_error_pages
from .global_variables import init_global
from .home import home_page
from .rules import rule_page
from .create_game import create_game_page, root_url_games
from .global_stats import global_stats_page, page_url
from .utils.add_dash_table import add_dash as add_dash_table
from .u... | 665ab7beda7ff79e4b81c22d5f28409a31dc896f | 13,044 |
def process_integration(request, case_id):
"""Method to process case."""
try:
case = OVCBasicCRS.objects.get(case_id=case_id, is_void=False)
county_code = int(case.county)
const_code = int(case.constituency)
county_id, const_id = 0, 0
crs_id = str(case_id).replace('-', ''... | bd383b624a072fec634bc28bbba71c2d635eeac2 | 13,045 |
def get_aabb(pts):
"""axis-aligned minimum bounding box"""
x, y = np.floor(pts.min(axis=0)).astype(int)
w, h = np.ceil(pts.ptp(axis=0)).astype(int)
return x, y, w, h | 68cffaf0b1cacf702a2dd3c6c22af6323d220e93 | 13,046 |
from re import S
def _solve(f, *symbols, **flags):
"""Return a checked solution for f in terms of one or more of the
symbols. A list should be returned except for the case when a linear
undetermined-coefficients equation is encountered (in which case
a dictionary is returned).
If no method is imp... | af2c8de5f2ee7cdfc41856ffe438c2bf0fcaee78 | 13,047 |
import numpy
def get_object_ratio(obj):
"""Calculate the ratio of the object's size in comparison to the whole image
:param obj: the binarized object image
:type obj: numpy.ndarray
:returns: float -- the ratio
"""
return numpy.count_nonzero(obj) / float(obj.size) | fd18e460be32037c73fe75c8fa5eef5ba6c1c217 | 13,048 |
def get_region(ds, region):
""" Return a region from a provided DataArray or Dataset
Parameters
----------
region_mask: xarray DataArray or list
Boolean mask of the region to keep
"""
return ds.where(region, drop=True) | 102b672f8040b722ec346435775cba1056485ae2 | 13,049 |
def read_borehole_file(path, fix_df=True):
"""Returns the df with the depths for each borehole in one single row instead
instead being each chunck a new row"""
df = pd.read_table(path,
skiprows=41,
header=None,
sep='\t',
... | 50c3df5a3d2aae2a0f58b555380efb9fd63a90e1 | 13,050 |
def cpl_parse(path):
""" Parse DCP CPL """
cpl = generic_parse(
path, "CompositionPlaylist",
("Reel", "ExtensionMetadata", "PropertyList"))
if cpl:
cpl_node = cpl['Info']['CompositionPlaylist']
cpl_dcnc_parse(cpl_node)
cpl_reels_parse(cpl_node)
return cpl | a025bf82bdeac13d6c7cfbca95d667f2ae58c8f9 | 13,051 |
def notfound():
"""Serve 404 template."""
return make_response(render_template('404.html'), 404) | d81d794bad67c8128b8f6e55dbc5383bda7a1405 | 13,052 |
from typing import Tuple
from typing import List
def read_network(file: str) -> Tuple[int, int, List[int]]:
"""
Read a Boolean network from a text file:
Line 1: number of state variables
Line 2: number of control inputs
Line 3: transition matrix of the network (linear representation of... | 217bd86f8d00cf27cf80d1a199b76b023a374f10 | 13,053 |
def bundle_products_list(request,id):
"""
This view Renders Bundle Product list Page """
bundle = get_object_or_404(Bundle, bundle_id=id)
bundleProd = BundleProducts.objects.filter(bundle=id)
stocks = Stock.objects.all()
context = {
"title": "Bundle Products List",
"bundle": b... | 3afef4fdd2886300bc2fbda306bc05b499a47d0f | 13,055 |
def rot_x(theta):
"""
Rotation matrix around X axis
:param theta: Rotation angle in radians, right-handed
:return: Rotation matrix in form of (3,3) 2D numpy array
"""
return rot_axis(0,theta) | d4a892ed5ede6ffd2353b0121bec640e81c23ec7 | 13,056 |
def ValidateEntryPointNameOrRaise(entry_point):
"""Checks if a entry point name provided by user is valid.
Args:
entry_point: Entry point name provided by user.
Returns:
Entry point name.
Raises:
ArgumentTypeError: If the entry point name provided by user is not valid.
"""
return _ValidateArgum... | 7175e63562b04aba430044e0898db7368b68fb23 | 13,057 |
def park2_4_z(z, x):
""" Computes the Parkd function. """
y1 = x[0][0]
y2 = x[0][1]
chooser = x[1]
y3 = (x[2] - 103.0) / 91.0
y4 = x[3] + 10.0
x = [y1, y2, y3, y4]
if chooser == 'rabbit':
ret = sub_park_1(x)
elif chooser == 'dog':
ret = sub_park_2(x)
elif chooser == 'gerbil':
ret = sub_p... | 458ba79ada010b3c93419719b68f7a953908b184 | 13,058 |
import re
def get_string_coords(line):
"""return a list of string positions (tuple (start, end)) in the line
"""
result = []
for match in re.finditer(STRING_RGX, line):
result.append( (match.start(), match.end()) )
return result | a8fd7443ce242ce4f84196947fb4d82c2ff0d20e | 13,059 |
def array_from_pixbuf(p):
"""Convert from GdkPixbuf to numpy array"
Args:
p (GdkPixbuf): The GdkPixbuf provided from some window handle
Returns:
ndarray: The numpy array arranged for the pixels in height, width, RGBA order
"""
w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channel... | da2e980d804c283e2993049c63e3dacf67f7f0bd | 13,060 |
def entropy(x,k=3,base=2):
""" The classic K-L k-nearest neighbor continuous entropy estimator
x should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]]
if x is a one-dimensional scalar and we have four samples
"""
assert k <= len(x)-1, "Set k smaller than num. samples - 1"
d = len(x[0])
N... | 41d55d2bef2475ece27a487afb1e54d433bad5f0 | 13,061 |
from typing import Optional
def s3upload_start(
request: HttpRequest,
workflow: Optional[Workflow] = None,
) -> HttpResponse:
"""Upload the S3 data as first step.
The four step process will populate the following dictionary with name
upload_data (divided by steps in which they are set
STEP 1... | b3fc1ac6c3754df836d8c219b0fb416f9d5973ce | 13,063 |
def search_explorations(query, limit, sort=None, cursor=None):
"""Searches through the available explorations.
args:
- query_string: the query string to search for.
- sort: a string indicating how to sort results. This should be a string
of space separated values. Each value should start ... | bead5de6f9803a7715ad497bb1f5c22da1faf296 | 13,064 |
import pkgutil
def find_resourceadapters():
"""
Finds all resource adapter classes.
:return List[ResourceAdapter]: a list of all resource adapter classes
"""
subclasses = []
def look_for_subclass(module_name):
module = __import__(module_name)
d = module.__dict__
for... | 3aab6e6b28fa69cf9e7b1c8bc04589c69e43a3ee | 13,065 |
def print_scale(skill, points):
"""Return TeX lines for a skill scale."""
lines = ['\\cvskill{']
lines[0] += skill
lines[0] += '}{'
lines[0] += str(points)
lines[0] += '}\n'
return lines | c88de0c6db9e7b92dbcee025f42f56817a4aa033 | 13,066 |
def print_(fh, *args):
"""Implementation of perl $fh->print method"""
global OS_ERROR, TRACEBACK, AUTODIE
try:
print(*args, end='', file=fh)
return True
except Exception as _e:
OS_ERROR = str(_e)
if TRACEBACK:
cluck(f"print failed: {OS_ERROR}",skip=2)
... | 8289aba67cb81b710d04da609ea63c65fa986e21 | 13,068 |
def subprocess(mocker):
""" Mock the subprocess and make sure it returns a value """
def with_return_value(value: int = 0, stdout: str = ""):
mock = mocker.patch(
"subprocess.run", return_value=CompletedProcess(None, returncode=0)
)
mock.returncode.return_value = value
... | 4b7140127eeb2d9202ed976518a121fed5fac302 | 13,070 |
def ljust(string, width):
"""
A version of ljust that considers the terminal width (see
get_terminal_width)
"""
width -= get_terminal_width(string)
return string + " " * width | e9c6ab8bbeeb268bc82f479e768be32f74fab488 | 13,071 |
import operator
def device_sort (device_set):
"""Sort a set of devices by self_id. Can't be used with PendingDevices!"""
return sorted(device_set, key = operator.attrgetter ('self_id')) | 92a22a87b5b923771cd86588180a8c6eb15b9fdf | 13,072 |
def _ontology_value(curie):
"""Get the id component of the curie, 0000001 from CL:0000001 for example."""
return curie.split(":")[1] | 7ef1f0874e698c498ccef16294c0469f67cd5233 | 13,073 |
def readpacket( timeout=1000, hexdump=False ):
"""Reads a HP format packet (length, data, checksum) from device.
Handles error recovery and ACKing.
Returns data or prints hexdump if told so.
"""
data = protocol.readpacket()
if hexdump == True:
print hpstr.tohexstr( data )
else:
... | d673e61974058fc73a47bd0e5856563c9f5370bf | 13,075 |
def df_down_next_empty_pos(df, pos):
"""
Given a position `pos` at `(c, r)`, reads down column `c` from row `r` to find the next
empty cell.
Returns the position of that cell if found, or `None` otherwise.
"""
return df_down_next_matching_pos(df, pos, pd.isna) | 79fdba60e6a5846c39fb1141f3d21430230c2a31 | 13,076 |
def optimise_f2_thresholds(y, p, verbose=False, resolution=100):
"""Optimize individual thresholds one by one. Code from anokas.
Inputs
------
y: numpy array, true labels
p: numpy array, predicted labels
"""
n_labels = y.shape[1]
def mf(x):
p2 = np.zeros_like(p)
for i in... | 5f1ad6dda86229cffb7167f5cc3365c601048937 | 13,077 |
def holding_vars():
""" input
This is experimental, used to indicate unbound (free) variables in
a sum or list comprehensive.
This is inspired by Harrison's {a | b | c} set comprehension notation.
>>> pstream(holding_vars(),', holding x,y,z')
Etok(holding_vars,', holding x , y , z')
... | 5566bc97e2fa972b1ccde4d24f30fb06635bdcb7 | 13,078 |
import re
def select_with_several_genes(accessions, name, pattern,
description_items=None,
attribute='gene',
max_items=3):
"""
This will select the best description for databases where more than one
gene (or other at... | 04df56e64259aafd1e0d5b0d68839d8016514cb7 | 13,079 |
def list_messages_matching_query(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query:... | a6ec376d7cfb4a6c724646a0e4d9ac1b86526ae7 | 13,080 |
def write_to_string(input_otio, **profile_data):
"""
:param input_otio: Timeline, Track or Clip
:param profile_data: Properties passed to the profile tag describing
the format, frame rate, colorspace and so on. If a passed Timeline has
`global_start_time` set, the frame rate will be set automatical... | 36a0e7fe741b4c216bd068b8544d68c63176d679 | 13,081 |
import re
def parse_IS(reply: bytes, device: str):
"""Parses the reply to the shutter IS command."""
match = re.search(b"\x00\x07IS=([0-1])([0-1])[0-1]{6}\r$", reply)
if match is None:
return False
if match.groups() == (b"1", b"0"):
if device in ["shutter", "hartmann_right"]:
... | 827b5ebf5c98bcc65b823276d5ab5b8086a2c069 | 13,082 |
def quatXYZWFromRotMat(rot_mat):
"""Convert quaternion from rotation matrix"""
quatWXYZ = quaternions.mat2quat(rot_mat)
quatXYZW = quatToXYZW(quatWXYZ, 'wxyz')
return quatXYZW | 2a0a736c3950dca481c993e9801e14b362f78940 | 13,083 |
import sqlite3
def schema_is_current(db_connection: sqlite3.Connection) -> bool:
"""
Given an existing database, checks to see whether the schema version in the existing
database matches the schema version for this version of Gab Tidy Data.
"""
db = db_connection.cursor()
db.execute(
... | 183502c292f9bb92e18a4ea7767028bea4e746fb | 13,084 |
import xattr
def xattr_writes_supported(path):
"""
Returns True if the we can write a file to the supplied
path and subsequently write a xattr to that file.
"""
try:
except ImportError:
return False
def set_xattr(path, key, value):
xattr.setxattr(path, "user.%s" % key, val... | 4992f2f5808575eac1f816aa09d80ff881286368 | 13,085 |
def _lovasz_softmax(probabilities, targets, classes="present", per_image=False, ignore=None):
"""The multiclass Lovasz-Softmax loss.
Args:
probabilities: [B, C, H, W]
class probabilities at each prediction (between 0 and 1).
Interpreted as binary (sigmoid) output
wit... | c46006c921d1f40b5b86ff861750a9d89ec4bbdc | 13,086 |
def encodeDERTRequest(negoTypes = [], authInfo = None, pubKeyAuth = None):
"""
@summary: create TSRequest from list of Type
@param negoTypes: {list(Type)}
@param authInfo: {str} authentication info TSCredentials encrypted with authentication protocol
@param pubKeyAuth: {str} public key encrypted wit... | bba9ed483eec2ef39927689a8924cbcc15a2093e | 13,087 |
def hierholzer(network: Network, source=0):
""" Hierholzer's algorithm for finding an Euler cycle
Args:
network (Network): network object
source(int): node where starts (and ends) the path
Raises:
NotEulerianNetwork: if exists at least one node with odd degree
NotNetworkNod... | 9a1fb1107e9a2b086d1716cea7708dba9849fb4e | 13,089 |
def fit1d(xdata,zdata,degree=1,reject=0,ydata=None,plot=None,plot2d=False,xr=None,yr=None,zr=None,xt=None,yt=None,zt=None,pfit=None,log=False,colorbar=False,size=5) :
"""
Do a 1D polynomial fit to data set and plot if requested
Args:
xdata : independent variable
zdata : dependent variable to be f... | 0c40a2b1af72c0df8523a92cd5cc80c99f631472 | 13,090 |
import torch
def nucleus_sampling(data, p, replace=0, ascending=False, above=True):
"""
:param tensor data: Input data
:param float p: Probability for filtering (or be replaced)
:param float replace: Default value is 0. If value is provided, input data will be replaced by this value
if data m... | 6332e9f5e04fa2ec0130fa2db7dd5a8aad26caec | 13,091 |
from datetime import datetime
import json
def mark_ready_for_l10n_revision(request, document_slug, revision_id):
"""Mark a revision as ready for l10n."""
revision = get_object_or_404(Revision, pk=revision_id,
document__slug=document_slug)
if not revision.document.allows(r... | 64d7d84ceab204a3d3fea98e9753fde486c4490c | 13,092 |
def is_all_maxed_out(bad_cube_counts, bad_cube_maximums):
"""Determines whether all the cubes of each type are at their maximum
amounts."""
for cube_type in CUBE_TYPES:
if bad_cube_counts[cube_type] < bad_cube_maximums[cube_type]:
return False
return True | 23332712b46d33a1a8e552ecf30389d4b0a10c90 | 13,093 |
def get_local_vars(*args):
"""
get_local_vars(prov, ea, out) -> bool
"""
return _ida_dbg.get_local_vars(*args) | ebed21c8b90c48e76734f07a5e83c11bf5b9dd0c | 13,094 |
def gcc():
"""
getCurrentCurve
Get the last curve that was added to the last plot plot
:return: The last curve
:rtype: pg.PlotDataItem
"""
plotWin = gcf()
try:
return plotWin.plotWidget.plotItem.dataItems[-1]
except IndexError:
return None | 2f9226c51a84d39b43f1d8ef83969b94a2c308cd | 13,095 |
import requests
import json
def searchDevice(search):
"""
Method that searches the ExtraHop system for a device that
matches the specified search criteria
Parameters:
search (dict): The device search criteria
Returns:
dict: The metadata of the device that matches ... | 9b65346054f099e4a2aa78035802b2de799850ac | 13,096 |
def regularmeshH8(nelx, nely, nelz, lx, ly, lz):
""" Creates a regular H8 mesh.
Args:
nelx (:obj:`int`): Number of elements on the X-axis.
nely (:obj:`int`): Number of elements on the Y-axis.
nelz (:obj:`int`): Number of elements on the Z-axis.
lx (:obj:`float`): X-axis length.
... | 1c0050b8c48438f548e67f7776194a067c77ae39 | 13,097 |
def only_t1t2(src, names):
"""
This function...
:param src:
:param names:
:return:
"""
if src.endswith("TissueClassify"):
# print "Keeping T1/T2!"
try:
names.remove("t1_average_BRAINSABC.nii.gz")
except ValueError:
pass
try:
... | 60116fbc602bbe03f7c18776b623ef3680b9dfc1 | 13,098 |
def distanceEucl(a, b):
"""Calcul de la distance euclidienne en dimension quelconque"""
dist = np.linalg.norm(a - b)
return dist | 572d98aecf17cd1f0e34dcad9e07beb3bcf6d06d | 13,099 |
def _search(self, *query):
"""Search for a match between the query terms and a tensor's Id, Tag, or Description.
https://github.com/OpenMined/PySyft/issues/2609
Note that the query is an AND query meaning that every item in the list of strings (query*)
must be found somewhere on the tensor in order for it t... | 8ffd9ae2fc0eb9f5f01c9cd3d27123a316bad655 | 13,100 |
def val2str(val):
"""Writes values to a string.
Args:
val (any): Any object that should be represented by a string.
Returns:
valstr (str): String representation of `val`.
"""
# Return the input if it's a string
if isinstance(val,str ): valstr=val
# Handle types where sp... | c8f26553ceeeef841239c534815f86293f91086a | 13,103 |
def showItems(category_name):
"""Pulls all the Categories, the specific Category selected by the user
from the home page, all the items within that specific Category, and
then counts the number of items. All this information is displayed on the
items.html page.
"""
categories = session.query(Cat... | 0ef0c8dfca16a9f16a9d4a46c3d796e817710165 | 13,104 |
from datetime import datetime
import math
import calendar
def date_ranges():
"""Build date ranges for current day, month, quarter, and year.
"""
today = datetime.date.today()
quarter = math.floor((today.month - 1) / 3)
cycle = current_cycle()
return {
'month': (
today.repla... | 08feb47fe09d5a0d1c9e5e16bdcbd65d3e211e1e | 13,105 |
def FiskJohnsonDiscreteFuncBCKWD(r,F0,T):
"""Compute reverse Fourier-Bessel transformation via Fisk Johnson
procedure.
Compute reverse Fourier-Bessel transform (i.e. 0th order reverse Hankel
transform) using a rapidly convergent summation of a Fourier-Bessel
expansion fol... | f950323bcad980f8b0af94d5848b59cd3522adfc | 13,106 |
def make_waterfall_horizontal(data, layout):
"""Function used to flip the figure from vertical to horizontal.
"""
h_data = list(data)
h_data = []
for i_trace, trace in enumerate(list(data)):
h_data.append(trace)
prov_x = h_data[i_trace]['x']
h_data[i_trace]['x'] = list(h_data... | 0dacdefc4e36d10dea3404e1fc5e92ce6f7326be | 13,107 |
def parse_file(producer):
"""
Given a producer name, return appropriate parse function.
:param producer: NMR machine producer.
:return: lambda function that reads file according to producer.
"""
global path_to_directory
return {
"Agilent": (lambda: ng.agilent.read(dir=path_to_directo... | cdb8e5e6f506b6d393eeefc13e982f246ea527b6 | 13,108 |
from typing import Union
from typing import Optional
def get_lon_dim_name_impl(ds: Union[xr.Dataset, xr.DataArray]) -> Optional[str]:
"""
Get the name of the longitude dimension.
:param ds: An xarray Dataset
:return: the name or None
"""
return _get_dim_name(ds, ['lon', 'longitude', 'long']) | 7f063690d8835b7cdd3298e14a5c35bd32025acc | 13,109 |
def logout():
"""Log out user."""
session.pop('eventbrite_token', None)
return redirect(url_for('index')) | 449690645fc19d72ef85636776f8d853ca65f4f8 | 13,110 |
def search(query="", casesense=False, filterout=[], subscribers=0, nsfwmode=2, doreturn=False, sort=None):
"""
Search for a subreddit by name
*str query = The search query
"query" = results where "query" is in the name
"*query" = results where "query" is at the end of the name
"... | c623ee11d507dbd7de84b109c2aa40866bb06dda | 13,111 |
def is_xh(filename):
"""
Detects if the given file is an XH file.
:param filename: The file to check.
:type filename: str
"""
info = detect_format_version_and_endianness(filename)
if info is False:
return False
return True | f0c33e5eed11522210dbc64a556e77f1c68d63c1 | 13,112 |
from typing import Tuple
from typing import List
from typing import Union
from typing import Callable
from typing import Any
def validate_func_kwargs(
kwargs: dict,
) -> Tuple[List[str], List[Union[str, Callable[..., Any]]]]:
"""
Validates types of user-provided "named aggregation" kwargs.
`TypeError`... | 81475f1467546f31a63a021c05a0c5f1adfd28a8 | 13,114 |
def mni152_to_fslr(img, fslr_density='32k', method='linear'):
"""
Projects `img` in MNI152 space to fsLR surface
Parameters
----------
img : str or os.PathLike or niimg_like
Image in MNI152 space to be projected
fslr_density : {'32k', '164k'}, optional
Desired output density of ... | 07129a79bc51e4655516573f517c4270d89800ed | 13,115 |
def parse_record(raw_record, _mode, dtype):
"""Parse CIFAR-10 image and label from a raw record."""
# Convert bytes to a vector of uint8 that is record_bytes long.
record_vector = tf.io.decode_raw(raw_record, tf.uint8)
# The first byte represents the label, which we convert from uint8 to int32
# an... | 278998f8ee1a126c6c248d8124bba1a4abdf7621 | 13,116 |
def makeSSHTTPClient(paramdict):
"""Creates a SingleShotHTTPClient for the given URL. Needed for Carousel."""
# get the "url" and "postbody" keys from paramdict to use as the arguments of SingleShotHTTPClient
return SingleShotHTTPClient(paramdict.get("url", ""),
paramdict.ge... | e7172d849e9c97baf07b9d97b914bf3e05551026 | 13,117 |
import glob
def getFiles(regex, camera, mjdToIngest = None, mjdthreshold = None, days = None, atlasroot='/atlas/', options = None):
"""getFiles.
Args:
regex:
camera:
mjdToIngest:
mjdthreshold:
days:
atlasroot:
options:
"""
# If mjdToIngest is de... | 8d61d2e1900413d55e2cfc590fb6c969dd31b441 | 13,118 |
from typing import Sequence
from typing import Tuple
def chain(*args: GradientTransformation) -> GradientTransformation:
"""Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the ind... | 089b30a4daec8be0033567da147be6dc4fab9990 | 13,119 |
def fibonacci_mult_tuple(fib0=2, fib1=3, count=10):
"""Returns a tuple with a fibonacci sequence using * instead of +."""
return tuple(fibonacci_mult_list(fib0, fib1, count)) | a43d1bd5bd2490ecbf85b305cc99929ac64a4908 | 13,120 |
import logging
def execute_in_process(f):
"""
Decorator.
Execute the function in thread.
"""
def wrapper(*args, **kwargs):
logging.info("Se ha lanzado un nuevo proceso")
process_f = Process(target=f, args=args, kwargs=kwargs)
process_f.start()
return process_f
... | 2a002ce48e07ec4b31066c1fad51cd271eaa6230 | 13,121 |
import copy
def castep_spectral_dispersion(computer, calc_doc, seed):
""" Runs a dispersion interpolation on top of a completed SCF calculation,
optionally running orbitals2bands and OptaDOS projected dispersion.
Parameters:
computer (:obj:`matador.compute.ComputeTask`): the object that will be c... | 0f84e9b4d7a044fd50512093b51ec20425c98cbd | 13,122 |
def return_limit(x):
"""Returns the standardized values of the series"""
dizionario_limite = {'BENZENE': 5,
'NO2': 200,
'O3': 180,
'PM10': 50,
'PM2.5': 25}
return dizionario_limite[x] | 92d40eaef7b47c3a20b9bcf1f7fd72510a05d9b2 | 13,123 |
def npaths(x, y):
"""
Count paths recursively. Memoizing makes this efficient.
"""
if x>0 and y>0:
return npaths(x-1, y) + npaths(x, y-1)
if x>0:
return npaths(x-1, y)
if y>0:
return npaths(x, y-1)
return 1 | 487a1f35b1bf825ffaf6bbf1ed86eb51f6cf18e9 | 13,124 |
from datetime import datetime
def sqlify(obj):
"""
converts `obj` to its proper SQL version
>>> sqlify(None)
'NULL'
>>> sqlify(True)
"'t'"
>>> sqlify(3)
'3'
"""
# because `1 == True and hash(1) == hash(True)`
# we have to do this the hard way...
... | 6342a4fc1b4450181cee5a6287036b1f4ed38883 | 13,125 |
def create_results_dataframe(
list_results,
settings,
result_classes=None,
abbreviate_name=False,
format_number=False,
):
"""
Returns a :class:`pandas.DataFrame`.
If *result_classes* is a list of :class:`Result`, only the columns from
this result classes will be returned. If ``N... | 638328936ee9207777fab504021efd83379ec93c | 13,126 |
def get_first_model_each_manufacturer(cars=cars):
"""return a list of matching models (original ordering)"""
first = []
for key,item in cars.items():
first.append(item[0])
return(first) | c6ec531ccc7a9bc48b404df34ec9c33066cd8717 | 13,127 |
def white(*N, mean=0, std=1):
""" White noise.
:param N: Amount of samples.
White noise has a constant power density. It's narrowband spectrum is therefore flat.
The power in white noise will increase by a factor of two for each octave band,
and therefore increases with 3 dB per octave.
"""
... | 874dd75b3cd735f6b5642cd5567d7d0218af615b | 13,128 |
import random
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
area = w*h
for _ in range(10):
new_area = random.uniform(min_area, 1.0) * area
new_ratio = random.uniform(*rati... | 76c64b91e03cb5cf65b164c10771bd78d13945ee | 13,129 |
import re
def joinAges(dataDict):
"""Merges columns by county, dropping ages"""
popColumns = list(dataDict.values())[0].columns.tolist()
popColumns = [re.sub("[^0-9]", "", column) for column in popColumns]
dictOut = dict()
for compartmentName, table in dataDict.items():
table.columns = pop... | d83ee4883ba58f7090141c131c4e111a4805f15d | 13,131 |
def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None,
margin=0.02, bgcolor='w', axis_off=True, show=True,
save=False, close=True, file_format='png', filename='temp',
dpi=300, annotate=False, node_color='#999999',
node_... | 19483338300d2f0fe9426942b5e0a196178cc036 | 13,132 |
from typing import Dict
def random_polynomialvector(
secpar: int, lp: LatticeParameters, distribution: str, dist_pars: Dict[str, int], num_coefs: int,
bti: int, btd: int, const_time_flag: bool = True
) -> PolynomialVector:
"""
Generate a random PolynomialVector with bounded Polynomial entries.... | 43d059c69f74f2ba91fec690cc6d9a86ca51cf2a | 13,133 |
def get_glare_value(gray):
"""
:param gray: cv2.imread(image_path) grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
:return: numrical value between 0-256 which tells the glare value
"""
blur = cv2.blur(gray, (3, 3)) # With kernel size depending upon image size
mean_blur = cv2.... | c019d79f47949a061e74129b56bfb3d413d03314 | 13,135 |
def generate_n_clusters(object_generator, n_clusters, n_objects_per_cluster, *, rng=None):
""" Creates n_clusters of random objects """
rng = np.random.default_rng(rng)
object_clusters = []
for i in range(n_clusters):
cluster_objects = generate_random_object_cluster(n_objects_per_cluster, object... | 1de8c3793abaf635e182b6b4640ddd8bd7d1ed28 | 13,137 |
def disp2vel(wrange, velscale):
""" Returns a log-rebinned wavelength dispersion with constant velocity.
This code is an adaptation of pPXF's log_rebin routine, simplified to
deal with the wavelength dispersion only.
Parameters
----------
wrange: list, np.array or astropy.Quantity
Inpu... | c15d5cf8dc3f26969f38e4f678441adeae710e77 | 13,138 |
def relabel(labels):
"""
Remaps integer labels based on who is most frequent
"""
uni_labels, uni_inv, uni_counts = np.unique(
labels, return_inverse=True, return_counts=True
)
sort_inds = np.argsort(uni_counts)[::-1]
new_labels = range(len(uni_labels))
uni_labels_sorted = uni_lab... | bc809781968387ec9de9de05f8d5cd990ede4c62 | 13,139 |
from typing import List
from typing import Tuple
def precision_at_threshold(
weighted_actual_names: List[Tuple[str, float, int]],
candidates: np.ndarray,
threshold: float,
distances: bool = False,
) -> float:
"""
Return the precision at a threshold for the given weighted-actuals and candidates... | 40c99830339418acee59c5364f1a70dc5639a475 | 13,140 |
def alias(*alias):
"""Select a (list of) alias(es)."""
valias = [t for t in alias]
return {"alias": valias} | b2ff51f33b601468b1ba4d371bd5abd6d013a188 | 13,141 |
import pathlib
import traceback
def parse_smyle(file):
"""Parser for CESM2 Seasonal-to-Multiyear Large Ensemble (SMYLE)"""
try:
with xr.open_dataset(file, chunks={}, decode_times=False) as ds:
file = pathlib.Path(file)
parts = file.parts
# Case
case = pa... | 791ecf41e4bc1b44ababbf35a021b4a48b46bc24 | 13,143 |
def get_shape(grid, major_ticks=False):
"""
Infer shape from grid
Parameters
----------
grid : ndarray
Minor grid nodes array
major_ticks : bool, default False
If true, infer shape of majr grid nodes
Returns
-------
shape : tuple
Shape of grid ndarray
... | 57f487260ca19257bd3f9891ce87c52c1eafe3bc | 13,144 |
def lorentz_force_derivative(t, X, qm, Efield, Bfield):
"""
Useful when using generic integration schemes, such
as RK4, which can be compared to Boris-Bunemann
"""
v = X[3:]
E = Efield(X)
B = Bfield(X)
# Newton-Lorentz acceleration
a = qm*E + qm*np.cross(v,B)
ydot = np.concaten... | 7a7aade5ece2363e177002bac0c18c4a0b59174f | 13,145 |
def copy_rate(source, target, tokenize=False):
"""
Compute copy rate
:param source:
:param target:
:return:
"""
if tokenize:
source = toktok(source)
target = toktok(target)
source_set = set(source)
target_set = set(target)
if len(source_set) == 0 or len(target_se... | 80b94e90ab43df2f33869660f4b83f41721826f0 | 13,146 |
import json
def read_json_info(fname):
"""
Parse info from the video information file.
Returns: Dictionary containing information on podcast episode.
"""
with open(fname) as fin:
return json.load(fin) | 1eed945ce2917cbca1fb807a807ab57229622374 | 13,147 |
def check_subman_version(required_version):
"""
Verify that the command 'subscription-manager' isn't too old.
"""
status, _ = check_package_version('subscription-manager', required_version)
return status | 33e14fd5cf68e170f5804ae393cb2a45878d19a6 | 13,148 |
import random
def bigsegment_twocolor(rows, cols, seed=None):
"""
Form a map from intersecting line segments.
"""
if seed is not None:
random.seed(seed)
possible_nhseg = [3,5]
possible_nvseg = [1,3,5]
gap_probability = random.random() * 0.10
maxdim = max(rows, cols)
nhs... | 1df4861434b19d6bdebe926baad57e3a11f6a64b | 13,150 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.