content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def write_results(conn, cursor, mag_dict, position_dict):
"""
Write star truth results to the truth table
Parameters
----------
conn is a sqlite3 connection to the database
cursor is a sqlite3.conneciton.cursor() object
mag_dict is a dict of mags. It is keyed on the pid of the
Proces... | 0b0c9234a32050277a7e70fee3ab7ba1be5931bb | 3,657,912 |
def get_sparameters(sim: td.Simulation) -> np.ndarray:
"""Adapted from tidy3d examples.
Returns full Smatrix for a component
https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction
"""
sim = run_simulation(sim).result()
def get_amplitude(monitor):
... | 6577fac645e195c4e30406c6252c9b55831343a0 | 3,657,913 |
def mapmri_STU_reg_matrices(radial_order):
""" Generates the static portions of the Laplacian regularization matrix
according to [1]_ eq. (11, 12, 13).
Parameters
----------
radial_order : unsigned int,
an even integer that represent the order of the basis
Returns
-------
S, T,... | 40cb1159f04d1291e06146dabd89380936c407a0 | 3,657,914 |
def _checker(word: dict):
"""checks if the 'word' dictionary is fine
:param word: the node in the list of the text
:type word: dict
:return: if "f", "ref" and "sig" in word, returns true, else, returns false
:rtype: bool
"""
if "f" in word and "ref" in word and "sig" in word:
return... | ee6ec5a7ee393ddcbc97b13f6c09cdd9019fb1a6 | 3,657,915 |
def construc_prob(history, window, note_set, model, datafilename):
"""
This function constructs the proabilities of seeing each next note
Inputs:
history, A list of strings, the note history in chronological order
window, and integer how far back we are looking
note_set, the set of n... | 92e75d386c5fce984302ca60f80b2dc1891fc873 | 3,657,916 |
def renderPybullet(envs, config, tensor=True):
"""Provides as much images as envs"""
if type(envs) is list:
obs = [
env_.render(
mode="rgb_array",
image_size=config["image_size"],
color=config["color"],
fpv=config["fpv"],
... | fb04ecda7e0dbfbe7899d4684979828b3fcd83c6 | 3,657,917 |
def wifi(request):
"""Collect status information for wifi and return HTML response."""
context = {
'refresh': 5,
'item': '- Wifi',
'timestamp': timestamp(),
'wifi': sorted(Wifi().aps),
}
return render(request, 'ulm.html', context) | 0a5412c2912eaeae192dd6d5fe85d336dec1b169 | 3,657,918 |
def genModel( nChars, nHidden, numLayers = 1, dropout = 0.5, recurrent_dropout = 0.5 ):
"""Generates the RNN model with nChars characters and numLayers hidden units with
dimension nHidden."""
model = Sequential()
model.add( LSTM( nHidden, input_shape = (None, nChars), return_sequences = True,
... | 4aeef47b8a4948e37eaa2ea07ac22ecee167df51 | 3,657,919 |
def rotate_system(shape_list, angle, center_point = None):
"""Rotates a set of shapes around a given point
If no center point is given, assume the center of mass of the shape
Args:
shape_list (list): A list of list of (x,y) vertices
angle (float): Angle in radians to rotate counterclockwis... | 64c4ff717fd432a187d2616263405ae89a0d89f8 | 3,657,920 |
def _large_compatible_negative(tensor_type):
"""Large negative number as Tensor.
This function is necessary because the standard value for epsilon
in this module (-1e9) cannot be represented using tf.float16
Args:
tensor_type: a dtype to determine the type.
Returns:
a large negative number.
"""
... | c73a9e2de341d771ec07ecf2b2a178911ecc27bd | 3,657,921 |
def classified_unread_counts():
"""
Unread counts return by
helper.classify_unread_counts function.
"""
return {
'all_msg': 12,
'all_pms': 8,
'unread_topics': {
(1000, 'Some general unread topic'): 3,
(99, 'Some private unread topic'): 1
},
... | 4d5e984641de88fd497b6c78891b7e6478bb8385 | 3,657,922 |
def company_key(company_name=DEFAULT_COMPANY_NAME):
"""Constructs a Datastore key for a Company entity with company_name."""
return ndb.Key('Company', company_name) | f9387ef2ee33ea87a4a9fd721f14c35ca60ac482 | 3,657,923 |
def to_n_class(digit_lst, data, labels):
"""to make a subset of MNIST dataset, which has particular digits
Parameters
----------
digit_lst : list
for example, [0,1,2] or [1, 5, 8]
data : numpy.array, shape (n_samples, n_features)
labels : numpy.array or list of str
Returns
------... | 79652687ec0670ec00d67681711903ae01f4cc87 | 3,657,924 |
from re import T
import numpy
from operator import ne
def acosh(x: T.Tensor) -> T.Tensor:
"""
Elementwise inverse hyperbolic cosine of a tensor.
Args:
x (greater than 1): A tensor.
Returns:
tensor: Elementwise inverse hyperbolic cosine.
"""
y = numpy.clip(x,1+T.EPSILON, nump... | c5566c9b67b8be57be47c96762ce7371e1d4d988 | 3,657,925 |
def run_unit_tests():
""" Run unit tests against installed tools rpms """
# At the time of this writing, no unit tests exist.
# A unit tests script will be run so that unit tests can easily be modified
print "Running unit tests..."
success, output = run_cli_cmd(["/bin/sh", UNIT_TEST_SCRIPT], False)
... | fd2241bd471b7de61bac922f3da485cb954fbe06 | 3,657,927 |
def encode_input_descr(prm):
""" Encode process description input."""
elem = NIL("Input", *_encode_param_common(prm))
elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)]
elem.attrib["maxOccurs"] = "1"
if isinstance(prm, LiteralData):
elem.append(_encode_literal(prm, True))
elif ... | 9d5db979f5da325595501a50c2031f56fd438b47 | 3,657,928 |
def poly_quo(f, g, *symbols):
"""Returns polynomial quotient. """
return poly_div(f, g, *symbols)[0] | 2a4b04b053189db9bd5cb946b6399257b49a8afb | 3,657,929 |
import random
from typing import OrderedDict
def preprocess_data(dataset, encoder, config):
"""
Function to perform 4 preprocessing steps:
1. Exclude classes below minimum threshold defined in config.threshold
2. Exclude all classes that are not referenced in encoder.classes
3. Encode ... | ed7f7382c4d1c8bc6ce718605b9d64cc2cb6ff6e | 3,657,930 |
from dronekit.mavlink import MAVConnection
def connect(ip,
_initialize=True,
wait_ready=None,
timeout=30,
still_waiting_callback=default_still_waiting_callback,
still_waiting_interval=1,
status_printer=None,
vehicle_class=None,
... | 3cd30bcc35b308913a5f54f39f2e0fb7a5583032 | 3,657,931 |
import json
from datetime import datetime
async def ready(request):
"""
For Kubernetes readiness probe,
"""
try:
# check redis valid.
if app.redis_pool:
await app.redis_pool.save('health', 'ok', 1)
# check mysql valid.
if app.mysql_pool:
sql = "... | f776787f65609fa341eb360c801cf8ebdc16a2eb | 3,657,933 |
def surface_area(polygon_mesh):
""" Computes the surface area for a polygon mesh.
Parameters
----------
polygon_mesh : ``PolygonMesh`` object
Returns
-------
result : surface area
"""
if isinstance(polygon_mesh, polygonmesh.FaceVertexMesh):
print("A FaceVertex Mesh")
... | 587740d493ef5762c85f75f81d98e141121b5d7d | 3,657,934 |
from scipy.optimize import fsolve # non-linear solver
import numpy as np
def gas_zfactor(T_pr, P_pr):
"""
Calculate Gas Compressibility Factor
For range: 0.2 < P_pr < 30; 1 < T_pr < 3 (error 0.486%)
(Dranchuk and Aboukassem, 1975)
"""
# T_pr : calculated pseudoreduced temperature
# P_pr : calculated pse... | b9b1d770483737da8277a89b3f1100ea0c49c1c0 | 3,657,935 |
def format_value_with_percentage(original_value):
"""
Return a value in percentage format from
an input argument, the original value
"""
percentage_value = "{0:.2%}".format(original_value)
return percentage_value | 78bfb753b974bc7cbe3ac96f58ee49251063d2e7 | 3,657,936 |
import numpy
def get_Z_and_extent(topofile):
"""Get data from an ESRI ASCII file."""
f = open(topofile, "r")
ncols = int(f.readline().split()[1])
nrows = int(f.readline().split()[1])
xllcorner = float(f.readline().split()[1])
yllcorner = float(f.readline().split()[1])
cellsize = float(f.... | e96db5c2ae4a0d6c94654d7ad29598c3231ec186 | 3,657,937 |
from typing import Sequence
from typing import MutableMapping
import copy
def modified_config(
file_config: submanager.models.config.ConfigPaths,
request: pytest.FixtureRequest,
) -> submanager.models.config.ConfigPaths:
"""Modify an existing config file and return the path."""
# Get and check request... | 8a453233b6340b50fdcbc4d3bf7b2f1f1e7e15ce | 3,657,938 |
import torch
def train_discrim(discrim, state_features, actions, optim, demostrations,
settings):
"""demostractions: [state_features|actions]
"""
criterion = torch.nn.BCELoss()
for _ in range(settings.VDB_UPDATE_NUM):
learner = discrim(torch.cat([state_features, actions], di... | 7e6c16fc396b371e92d3a04179eacb9cae63659c | 3,657,939 |
def filter_column(text, column, start=0, sep=None, **kwargs):
""" Filters (like grep) lines of text according to a specified column and operator/value
:param text: a string
:param column: integer >=0
:param sep: optional separator between words (default is arbitrary number of blanks)
:param kwargs:... | f7a788d2d79dba33961213c6bc469d41a0151812 | 3,657,941 |
def max_tb(collection): # pragma: no cover
"""Returns the maximum number of TB recorded in the collection"""
max_TB = 0
for doc in collection.find({}).sort([('total_TB',-1)]).limit(1):
max_TB = doc['total_TB']
return max_TB | bde417de0b38de7a7b5e4e3db8c05e87fa6c55ca | 3,657,942 |
def prep_im_for_blob(im, pixel_means, target_size_1, target_size_2, max_size_1, max_size_2):
"""Mean subtract and scale an image for use in a blob."""
im = im.astype(np.float32, copy=False)
im -= pixel_means
im_shape = im.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_sca... | a1842d918149f5d1ccc52e04cc499005570b72ea | 3,657,943 |
def plotann(annotation, title = None, timeunits = 'samples', returnfig = False):
""" Plot sample locations of an Annotation object.
Usage: plotann(annotation, title = None, timeunits = 'samples', returnfig = False)
Input arguments:
- annotation (required): An Annotation object. The sample att... | 2159c1ffed52ef6524990f861d7e986b7aa00c25 | 3,657,945 |
def match_assignments(nb_assignments, course_id):
"""
Check sqlalchemy table for match with nbgrader assignments from a specified course. Creates a dictionary with nbgrader
assignments as the key
If match is found, query the entry from the table and set as the value.
Else, set the value to None
... | 22158bc0d3655a78b8e5b6cb245b781e187f1481 | 3,657,946 |
def tan(input):
"""Computes tangent of values in ``input``.
:rtype: TensorList of tan(input). If input is an integer, the result will be float,
otherwise the type is preserved.
"""
return _arithm_op("tan", input) | 27e6487591ff4d207baea094293be83ef22a4099 | 3,657,947 |
def recall_from_IoU(IoU, samples=500):
"""
plot recall_vs_IoU_threshold
"""
if not (isinstance(IoU, list) or IoU.ndim == 1):
raise ValueError('IoU needs to be a list or 1-D')
iou = np.float32(IoU)
# Plot intersection over union
IoU_thresholds = np.linspace(0.0, 1.0, samples)
r... | 9c24a4e546a76998339ce85e02fae6fec3adb00d | 3,657,948 |
import math
def _GetImage(options):
"""Returns the ndvi regression image for the given options.
Args:
options: a dict created by _ReadOptions() containing the request options
Returns:
An ee.Image with the coefficients of the regression and a band called "rmse" containing the
Root... | 00b4bd82e772a8afa8c4f92c3dd9afa880af79f2 | 3,657,949 |
def get_registered_plugins(registry, as_instances=False, sort_items=True):
"""Get registered plugins.
Get a list of registered plugins in a form if tuple (plugin name, plugin
description). If not yet auto-discovered, auto-discovers them.
:param registry:
:param bool as_instances:
:param bool s... | 68b695ebe3de95a86d37831fe38ce934bcced16c | 3,657,950 |
import time
def datetime_to_timestamp(d):
"""convert a datetime object to seconds since Epoch.
Args:
d: a naive datetime object in default timezone
Return:
int, timestamp in seconds
"""
return int(time.mktime(d.timetuple())) | 356ac090b0827d49e9929a7ef26041b26c6cc690 | 3,657,951 |
import torch
def gumbel_softmax(logits, temperature):
"""From https://gist.github.com/yzh119/fd2146d2aeb329d067568a493b20172f
logits: a tensor of shape (*, n_class)
returns an one-hot vector of shape (*, n_class)
"""
y = gumbel_softmax_sample(logits, temperature)
shape = y.size()
_, ind = ... | 49a79bf5955cfc01fd27f0a56c23d001e3ef65cc | 3,657,952 |
def in_whitelist(address):
"""
Test if the given email address is contained in the list of allowed addressees.
"""
if WHITELIST is None:
return True
else:
return any(regex.search(address) for regex in WHITELIST) | ed552f16a2cd4b9d5e97033e47d5ec8950841164 | 3,657,953 |
def decomposePath(path):
"""
:example:
>>> decomposePath(None)
>>> decomposePath("")
>>> decomposePath(1)
>>> decomposePath("truc")
('', 'truc', '', 'truc')
>>> decomposePath("truc.txt")
('', 'truc', 'txt', 'truc.txt')
>>> decomposePath("/home/... | 7b45cfe64f631912fc56246f404ddbea51b9f1ec | 3,657,954 |
def BSCLLR(c,p):
"""
c: A list of ones and zeros representing a codeword received over a BSC.
p: Flip probability of the BSC.
Returns log-likelihood ratios for c.
"""
N = len(c)
evidence = [0]*N
for i in range(N):
if (c[i]):
evidence[i] = log(p/(1-p))
else:
... | 2ee6f4a72a8c2aa3257ae00e8374511f74edcbdb | 3,657,955 |
import torch
def _res_dynamics_fwd(
real_input, imag_input,
sin_decay, cos_decay,
real_state, imag_state,
threshold, w_scale, dtype=torch.int32
):
""" """
dtype = torch.int64
device = real_state.device
real_old = (real_state * w_scale).clone().detach().to(dtype).to(device)
imag_ol... | 259b520c9ba4491931726b02ff51bc1c69283cdd | 3,657,956 |
def tokenize_finding(finding):
"""Turn the finding into multiple findings split by whitespace."""
tokenized = set()
tokens = finding.text.split()
cursor = 0
# Note that finding.start and finding.end refer to the location in the overall
# text, but finding.text is just the text for this finding.
for token ... | 28974a87bdb006bbdf37fff68345a9df81ea0962 | 3,657,958 |
import scipy
def gaussian_filter_density(gt):
"""generate ground truth density map
Args:
gt: (height, width), object center is 1.0, otherwise 0.0
Returns:
density map
"""
density = np.zeros(gt.shape, dtype=np.float32)
gt_count = np.count_nonzero(gt)
if gt_count == 0:
... | 9a51de844a08af18e5d1f72d368dbd6b05d24d34 | 3,657,959 |
def RGBfactorstoBaseandRange(
lumrange: list[int, int],
rgbfactors: list[float,
float,
float]):
"""Get base color luminosity and
luminosity range from color
expressed as r, g, b float
values and min and max byte
lumin... | 47fba5a98b324fc27869fee8b03903f844ef2c38 | 3,657,960 |
def mean_by_orbit(inst, data_label):
"""Mean of data_label by orbit over Instrument.bounds
Parameters
----------
data_label : string
string identifying data product to be averaged
Returns
-------
mean : pandas Series
simple mean of data_label indexed by start of each orbit
... | 55e3edac3231d4c42428cd87ee758f1b27d959b9 | 3,657,961 |
from typing import Callable
from typing import Optional
def quantile_constraint(
column: str,
quantile: float,
assertion: Callable[[float], bool],
where: Optional[str] = None,
hint: Optional[str] = None,
) -> Constraint:
"""
Runs quantile analysis on the given column and executes the asser... | b3e3924a830ec7fd47de981e1ae9eb3f1810c2a1 | 3,657,962 |
from typing import Tuple
import torch
def _compute_rank(
kg_embedding_model,
pos_triple,
corrupted_subject_based,
corrupted_object_based,
device,
) -> Tuple[int, int]:
"""
:param kg_embedding_model:
:param pos_triple:
:param corrupted_subject_based:
:param c... | 2b5043dfed43907563c473141257626bb93027b7 | 3,657,963 |
def _get_bool_argument(ctx: ClassDefContext, expr: CallExpr,
name: str, default: bool) -> bool:
"""Return the boolean value for an argument to a call or the
default if it's not found.
"""
attr_value = _get_argument(expr, name)
if attr_value:
ret = ctx.api.parse_bool(at... | 7f903f884edcb4af328207a0b7d2569cefce0a93 | 3,657,964 |
import json
def validate_filter_parameter(string):
""" Extracts a single filter parameter in name[=value] format """
result = ()
if string:
comps = string.split('=', 1)
if comps[0]:
if len(comps) > 1:
# In the portal, if value textbox is blank we store the valu... | 8258cff656889a57aaeb24644ea4efc9a60a6997 | 3,657,965 |
def ones(distribution, dtype=float):
"""Create a LocalArray filled with ones."""
la = LocalArray(distribution=distribution, dtype=dtype)
la.fill(1)
return la | d3caa46b76932a44d441574c78ebbd9c4e8d29f9 | 3,657,966 |
def update_podcast_url(video):
"""Query the DDB table for this video. If found, it means
we have a podcast m4a stored in S3. Otherwise, return no
podcast.
"""
try:
response = PODCAST_TABLE_CLIENT.query(
KeyConditionExpression=Key('session').eq(video.session_id) & Key('year').eq(v... | 50a39aceaba7980dff90043bf444b01607b258ae | 3,657,967 |
def translate(filename):
"""
File editing handler
"""
if request.method == 'POST':
return save_translation(app, request, filename)
else:
return open_editor_form(app, request, filename) | 5f9419db30ebd76e17f9f5c6efd746b3ddc1d8b0 | 3,657,968 |
def read_fileset(fileset):
"""
Extract required data from the sdoss fileset.
"""
feat_data = {
'DATE_OBS': [],
'FEAT_HG_LONG_DEG': [],
'FEAT_HG_LAT_DEG': [],
'FEAT_X_PIX': [],
'FEAT_Y_PIX': [],
'FEAT_AREA_DEG2': [],
'FEAT_FILENAME': []}
for c... | 3c1c9018444af04ca8cc7d95176032ad92c42928 | 3,657,969 |
def get_branch_index(edge_index, edge_degree, branch_cutting_frequency=1000):
"""Finds the branch indexes for each branch in the MST.
Parameters
----------
edge_index : array
The node index of the ends of each edge.
edge_degree : array
The degree for the ends of each edge.
branc... | 3ac24625f9c67cdb60759e840b06b21f260733c9 | 3,657,970 |
def update_coverage(coverage, path, func, line, status):
"""Add to coverage the coverage status of a single line"""
coverage[path] = coverage.get(path, {})
coverage[path][func] = coverage[path].get(func, {})
coverage[path][func][line] = coverage[path][func].get(line, status)
coverage[path][func][li... | 46e5a1e5c4ebba3a9483f90ada96a0f7f94d8c1d | 3,657,971 |
def cross_product(v1, v2):
"""Calculate the cross product of 2 vectors as (x1 * y2 - x2 * y1)."""
return v1.x * v2.y - v2.x * v1.y | 871d803ef687bf80facf036549b4b2062f713994 | 3,657,972 |
def loadData(fname='Unstra.out2.00008.athdf'):
"""load 3d bfield and calc the current density"""
#data=ath.athdf(fname,quantities=['B1','B2','B3'])
time,data=ath.athdf(fname,quantities=['vel1'])
vx = data['vel1']
time,data=ath.athdf(fname,quantities=['vel2'])
vy = data['vel2']
time,data=ath.athdf(fname,qu... | 121768232fe71ce8ce3714aea70b5bf2c7493907 | 3,657,973 |
def text_iou(ground_truth: Text, prediction: Text) -> ScalarMetricValue:
"""
Calculates agreement between ground truth and predicted text
"""
return float(prediction.answer == ground_truth.answer) | 5ea135b30ba93da45fb1ecd624fe7dc556f01cf5 | 3,657,974 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
# Fill in the function and change the return statment.
return 0 | f15169b2672847294a219207f6022ad3e49338d2 | 3,657,975 |
def space_oem(*argv):
"""Handle oem files
Usage:
space-oem get <selector>...
space-oem insert (- | <file>)
space-oem compute (- | <selector>...) [options]
space-oem list <selector>... [options]
space-oem purge <selector>... [--until <until>]
space-oem list-tags <... | 54c479f7008f475f778f491c7b6c5574390fd38c | 3,657,976 |
def compare_distance(tree,target):
"""
Checks tree edit distance. Since every node has a unique position, we know that the node is the
same when the positions are the same. Hence, a simple method of counting the number of edits
one needs to do to create the target tree out of a given tree is equal to the number of... | 96b57e88b8e70dbb43231b56cbe7e9b7ebcfd10f | 3,657,977 |
def header(name='peptide'):
"""
Parameters
----------
name
Returns
-------
"""
with open('{}.pdb'.format(name), 'r') as f:
file = f.read()
model = file.find('\nMODEL')
atom = file.find('\nATOM')
if atom < 0:
raise ValueError('no ATOM entries found in... | 84e75e34771b7c395ee36611c8d055ca1fdf67dc | 3,657,978 |
from datetime import datetime
def isoUTC2datetime(iso):
"""Convert and ISO8601 (UTC only) like string date/time value to a
:obj:`datetime.datetime` object.
:param str iso: ISO8061 string
:rtype: datetime.datetime
"""
formats = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"]
if 'T' in iso:
... | 0dae4fb7828f7319afa7190deca6ae4fda5ffd1d | 3,657,979 |
from typing import Optional
from typing import Dict
from typing import Union
def groupstatus(aid: int, state: int = 0) -> EndpointResult:
"""Retrieve anime release status for different groups.
:param aid: anidb anime id
:type aid: int
:param state: release state. int 1 to 6. Example: zenchi.mappings.... | f81ab06c8d47b9660cac9bde76978a722a13f49f | 3,657,980 |
def get_communities_codes(communities, fields=None, community_field='Community'):
"""From the postal code conversion file, select entries for the `communities`.
This function is similar to get_community_codes, but works if
`communities` and `fields` are strings or lists of strings.
"""
if not ... | 552fef722cd138f1a935755349116c89e0df3e3b | 3,657,981 |
from vba import VBA
from dataFrame import DF
def GLMFit_(file, designMatrix, mask, outputVBA, outputCon,
fit="Kalman_AR1"):
"""
Call the GLM Fit function with apropriate arguments
Parameters
----------
file
designmatrix
mask
outputVBA
outputCon
fit='Kalman_AR1'
... | 25ced91bc6c865faaffab30278d59aad6a475d4f | 3,657,982 |
from typing import Iterable
def get_stoch_rsi(quotes: Iterable[Quote], rsi_periods: int, stoch_periods: int, signal_periods: int, smooth_periods: int = 1):
"""Get Stochastic RSI calculated.
Stochastic RSI is a Stochastic interpretation of the Relative Strength Index.
Parameters:
`quotes` : Itera... | b548a620ef3b3bc4cb37049d1dfb29aac442b394 | 3,657,983 |
def PUtilHann (inUV, outUV, err, scratch=False):
""" Hanning smooth a UV data set
returns smoothed UV data object
inUV = Python UV object to smooth
Any selection editing and calibration applied before average.
outUV = Predefined UV data if scratch is False, ignored if
scrat... | a53f8d442055b2d575b36f49a96b68f6c6eff7ed | 3,657,984 |
def str2bytes(seq):
""" Converts an string to a list of integers """
return map(ord,str(seq)) | 7afe8e40cd4133c59be673b537f2717591b093cf | 3,657,985 |
def __downloadFilings(cik: str) -> list:
"""Function to download the XML text of listings pages for a given CIK
from the EDGAR database.
Arguments:
cik {str} -- Target CIK.
Returns:
list -- List of page XML, comprising full listing metadata for CIK.
"""
idx = 0 # Curr... | c98996d3607076ed0328a5e0621ef015037ddc2e | 3,657,986 |
def KK_RC43_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 9f88b73ac5da422069e67af28c15c2846178169b | 3,657,987 |
from .column import ColumnVirtualConstant
def vconstant(value, length, dtype=None, chunk_size=1024):
"""Creates a virtual column with constant values, which uses 0 memory.
:param value: The value with which to fill the column
:param length: The length of the column, i.e. the number of rows it should cont... | b712ec9f1aea2f65f1f992cd3b23ab671339f97a | 3,657,988 |
def gen_color_palette(n: int):
""" Generates a hex color palette of size n, without repeats
and only light colors (easily visible on dark background).
Adapted from code by 3630 TAs Binit Shah and Jerred Chen
Args:
n (int): number of clouds, each cloud gets a unique color
"""
pal... | 6b1004674d1448cdcca8c3500b149b1602e0045f | 3,657,991 |
def absolute_vorticity(u, v, dx, dy, lats, dim_order='yx'):
"""Calculate the absolute vorticity of the horizontal wind.
Parameters
----------
u : (M, N) ndarray
x component of the wind
v : (M, N) ndarray
y component of the wind
dx : float or ndarray
The grid spacing(s) i... | 9ae200b3a8b8415f67fc640b0702bc5272c77d3a | 3,657,992 |
def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
"""
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
if drop_prob == 0.0 or not training:
return input
keep_prob = 1 - drop_prob
shape = (input.shape[0],) + (1,) * (input.... | 289ae545fa184bb459275685d3a2894e5219db2e | 3,657,993 |
from typing import Dict
from typing import Any
from typing import List
import secrets
def ask_user_config() -> Dict[str, Any]:
"""
Ask user a few questions to build the configuration.
Interactive questions built using https://github.com/tmbo/questionary
:returns: Dict with keys to put into template
... | 7697ba65c7ba7f73b81af3ae3575beb0eb9b30b8 | 3,657,994 |
def generate_menusystem():
""" Generate Top-level Menu Structure (cached for specified timeout) """
return '[%s] Top-level Menu System' % timestamp() | eb3575835889af768887f3071816d0f22f867568 | 3,657,995 |
def gnomonic_proj(lon, lat, lon0=0, lat0=0):
"""
lon, lat : arrays of the same shape; longitude and latitude
of points to be projected
lon0, lat0: floats, longitude and latitude in radians for
the tangency point
---------------------------
Returns the gnomonic project... | 61daaee7bc0ca5dd901582adc03ec6c36ddf2ef2 | 3,657,998 |
def local_pluggables(pluggable_type):
"""
Accesses pluggable names
Args:
pluggable_type (Union(PluggableType,str)): The pluggable type
Returns:
list[str]: pluggable names
Raises:
AquaError: if the type is not registered
"""
_discover_on_demand()
if isinstance(plu... | 8626e931da1fd33d76cef4ed85b6ea1a7d7e907d | 3,657,999 |
def view_folio_contact(request, folio_id=None):
"""
View contact page within folio
"""
folio = get_object_or_404(Folio, pk=folio_id)
if not folio.is_published and folio.author_id != request.user:
return render(
request,
'showcase/folio_is_not_published.html'
... | 0269fea6322486912cdd462961fb847ffd8d038a | 3,658,000 |
def faom03(t):
"""
Wrapper for ERFA function ``eraFaom03``.
Parameters
----------
t : double array
Returns
-------
c_retval : double array
Notes
-----
The ERFA documentation is below.
- - - - - - - - - -
e r a F a o m 0 3
- - - - - - - - - -
Fundamental ... | 3e3d1c7e650d6034ed0793e4f1bc8605e9e82e32 | 3,658,001 |
from datetime import datetime
import calendar
def get_dtindex(interval, begin, end=None):
"""Creates a pandas datetime index for a given interval.
Parameters
----------
interval : str or int
Interval of the datetime index. Integer values will be treated as days.
begin : datetime
D... | 32f0992365b075fb8601276bd3680c7db43a677e | 3,658,002 |
import numpy
def asanyarray(a, dtype=None, order=None):
"""Converts the input to an array, but passes ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This includes scalars,
lists, lists of tuples, tuples, tupl... | c079d114ab224c487a65929b7710450262c66733 | 3,658,003 |
import base64
import struct
from datetime import datetime
def parse_fernet_timestamp(ciphertext):
"""
Returns timestamp embedded in Fernet-encrypted ciphertext, converted to Python datetime object.
Decryption should be attempted before using this function, as that does cryptographically strong tests on t... | 216d314c84679cc5806d6a483f68bff485375b36 | 3,658,005 |
def tagcloud(guids):
"""Get "tag cloud" for the search specified by guids
Same return format as taglist, impl is always False.
"""
guids = set(guids)
range = (0, 19 + len(guids))
tags = request.client.find_tags("EI", "", range=range, guids=guids, order="-post", flags="-datatag")
return [(tagfmt(t.name), t, False... | fb94fab24040b3c38a68a2731d9b1bba0cccd3bc | 3,658,006 |
def _ValidateContent(path, expected_content):
"""Helper to validate the given file's content."""
assert os.path.isfile(path), 'File didn\'t exist: %r' % path
name = os.path.basename(path)
current_content = open(path).read()
if current_content == expected_content:
print '%s is good.' % name
else:
try... | ddf6e3089f66d157f281655357753ff2b746d4a2 | 3,658,007 |
from typing import Optional
from typing import Sequence
def api_ofrecord_image_decoder_random_crop(
input_blob: remote_blob_util.BlobDef,
blob_name: str,
color_space: str = "BGR",
num_attempts: int = 10,
seed: Optional[int] = None,
random_area: Sequence[float] = [0.08, 1.0],
random_aspect_... | bcf8ad7deb97677e52b04e3204281a7ecc89c89c | 3,658,009 |
def student_add_information(adding_student_id, student_information):
"""
用于添加学生的详细信息
:@param adding_student_id: int
:@param student_information: dict or str
:@return : 运行状态(True or False)
"""
if type(student_information) == dict:
adding_information = student_information
elif type... | 8a44177b90c1f3e10077313f6765a4699ded676b | 3,658,010 |
async def get_show_by_month_day(month: conint(ge=1, le=12), day: conint(ge=1, le=31)):
"""Retrieve a Show object, based on month and day, containing: Show
ID, date and basic information."""
try:
show = Show(database_connection=_database_connection)
shows = show.retrieve_by_month_day(month, d... | e774f61254a3d7cdfc9a49ca1a9eea4f65853f55 | 3,658,012 |
import random
def generate_random_tag(length):
"""Generate a random alphanumeric tag of specified length.
Parameters
----------
length : int
The length of the tag, in characters
Returns
-------
str
An alphanumeric tag of specified length.
Notes
-----
The ge... | b62a103663b69f0a27d8ba23134473dc01932409 | 3,658,013 |
import io
def loadmat(filename, check_arrays=False, **kwargs):
"""
Big thanks to mergen on stackexchange for this:
http://stackoverflow.com/a/8832212
This function should be called instead of direct scipy.io.loadmat
as it cures the problem of not properly recovering python dictionaries
fr... | 3b054cbabc03b468ec0c80a4ed544b1c054ef223 | 3,658,014 |
def _export_output_to_tensors(export_output):
"""Get a list of `Tensors` used in `export_output`.
Args:
export_output: an `ExportOutput` object such as `ClassificationOutput`,
`RegressionOutput`, or `PredictOutput`.
Returns:
a list of tensors used in export_output.
Raises:
ValueError: ... | 913c1b232f8ac6e66e9104c055c9d34726db1027 | 3,658,015 |
import logging
def train_city_s1(city:str, pollutant= 'PM2.5', n_jobs=-2, default_meta=False,
search_wind_damp=False, choose_cat_hour=False, choose_cat_month=True,
add_weight=True, instr='MODIS', op_fire_zone=False, op_fire_twice=False, op_lag=True, search_tpot=False,
main_data_folder: str ... | 43cd4ff89068feba1bca3c316e40b19f852c1da2 | 3,658,016 |
def download_raw_pages_content(pages_count):
"""download habr pages by page count"""
return [fetch_raw_content(page) for page in range(1, pages_count + 1)] | 77e369a986ff09887a71d996226d147fef9a36ec | 3,658,018 |
def tseries2bpoframe(s: pd.Series, freq: str = "MS", prefix: str = "") -> pd.DataFrame:
"""
Aggregate timeseries with varying values to a dataframe with base, peak and offpeak
timeseries, grouped by provided time interval.
Parameters
----------
s : Series
Timeseries with hourly or quart... | 6b97bc3b8c925be68ba79e8a9abdc2795500df76 | 3,658,019 |
def calc_buffered_bounds(
format, bounds, meters_per_pixel_dim, layer_name, geometry_type,
buffer_cfg):
"""
Calculate the buffered bounds per format per layer based on config.
"""
if not buffer_cfg:
return bounds
format_buffer_cfg = buffer_cfg.get(format.extension)
if f... | 5bbf9720525126e3dcd000329493c894c8249771 | 3,658,020 |
async def read_users_me(
current_user: models.User = Depends(security.get_current_active_user),
):
"""Get User data"""
return current_user | 4b2e37586a4e13074ec009f4cd7e64e7a357d539 | 3,658,021 |
from typing import Iterable
from typing import Tuple
def compute_qp_objective(
configuration: Configuration, tasks: Iterable[Task], damping: float
) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute the Hessian matrix :math:`H` and linear vector :math:`c` of the
QP objective function:
.. math::
... | 623997bbaf7ce92c39084fa44960593b55a0b3a0 | 3,658,025 |
def _is_existing_account(respondent_email):
"""
Checks if the respondent already exists against the email address provided
:param respondent_email: email of the respondent
:type respondent_email: str
:return: returns true if account already registered
:rtype: bool
"""
respondent = party_... | 4cb0462f748d0b80dbb12f89364d279a3436b632 | 3,658,026 |
import socket
def basic_checks(server,port):
"""Perform basics checks on given host"""
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 2 seconds timeout
sock.settimeout(2)
return sock.connect_ex((server,int(port))) == 0 | 4a31521089feb2c178bb5202fa818804dfe87142 | 3,658,027 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.