content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def delete_user(username: str):
"""
Parameters
----------
username : str, required
Returns
-------
Response:
{
"deleted": true,
}
Raises
------
HTTPException
"""
response = False
try:
username_constraint(username)
... | 1ad90ce7113b2551e7bc63629061b7c9a45c4943 | 3,611,900 |
def imread(image_name, colorspace="RGB"):
"""
Reads image and returns RGB numpy array
Parameters:
image_name: Image path , str
colorspace: RGB or BGR, str
Returns:
img: numpy array
"""
img = cv2.imread(image_name)
if colorspace == "RGB":
img = cv2.cvtColor(img... | 15129c95eedb86b1bc9be01c87af01a5ab4d86ee | 3,611,901 |
def _extract_time_series(data, time_series_name='values'):
"""
Extract specific time series from provided pandas DataFrame and return as a pandas Series
"""
# If it's already a series, just return it
if isinstance(data, pd.Series):
return data
if time_series_name not in data:
r... | ed10c625d158190707f05da259eb2b204bad2ba2 | 3,611,902 |
def residual_resampling(weights):
"""Residual resampling. The counts in each bin are floor(w*N) + N' where
N' is sampled from a multinomial with the residual weights."""
N = weights.shape[0]
counts = np.floor(weights*N)
R = int(np.sum(counts))
new_weights = (weights*N - counts)/(N-R)
counts ... | f96d8456caf15502c18effb7cb5d1b3cb030a785 | 3,611,903 |
def get_reftypes(exp_type, cal_ver=None, context=None):
"""Based on the exposure type, CAL s/w version, and CRDS context, determine
the list of applicable reference file types.
"""
return [] | ccb08ecd63b85d4602d419fb8fd90e77984c4048 | 3,611,904 |
def mix(n = 1):
"""Accumulate n composite samples from the active generators."""
# Gather samples and count notes.
s = np.zeros(n, dtype=np.float32)
n_notes = 0
for note in set(notemap):
e = note.envelope()
if e == None:
# Release is complete. Get rid of the note.
... | 149059ba5a67997ccd9c0866cb3af18c510aa22c | 3,611,905 |
def train_step(grid, weights, optimizer, mov, fix):
"""
Train step function for backprop using gradient tape
:param grid: reference grid return from layer_util.get_reference_grid
:param weights: trainable affine parameters [1, 4, 3]
:param optimizer: tf.optimizers
:param mov: moving image [1, m... | eb28006c71301ea1a1a7c28fa010e2cf914edf98 | 3,611,906 |
def get_CV_current(CV):
"""
Helper function to compute CV current.
Args:
CV (pd.DataFrame): CV segement of charge
Returns:
(float): current reached at the end of the CV segment
"""
if not CV.empty:
return(CV.current.iat[-1]) | 69e32ecadc57d0855eedfe3404db1e5ec9839862 | 3,611,907 |
def tanh(x):
""" Calculate hyperbolic tangent of the input AD object, integer, or float
INPUTS
=======
x: input value, an AD object, int, or float
RETURNS
========
result: hyperbolic tangent of x
EXAMPLES
=========
>>> x = ad.AD(2.0, [1.0,0.0])
>>> print(tanh(x... | 7fdafe2f8cf7c4330b8008b592ec79c993b172b5 | 3,611,908 |
def init_weights(shape):
""" Weight initialization """
weights = np.asarray(np.random.randn(*shape) * 0.01, dtype=theano.config.floatX)
return theano.shared(weights) | 657ccea8286b9ae84ef28e0285f12f8bc3b8f2e5 | 3,611,909 |
import copy
import os
import yaml
def config(path="config.yml", force_reload=False):
"""
Read the config for this module.
Priority is env, config.yml then defaults.
"""
global CONFIG, DEFAULT_CONFIG
if CONFIG is not None and not force_reload:
return CONFIG
# 1. Defaults. All item... | 8b690576958422aa6b972874f8436875f89c780b | 3,611,910 |
import random
import sys
def generate_sound_file(text_to_read, lang_to_use):
"""
creates a mp3 file with read word
"""
tmp_file_name = '%s/tmp_%s.mp3' % (sound_tmp_dir, str(random.uniform(1, 10e6)).replace('.', ''))
try:
tts = gTTS(text=text_to_read, lang=lang_to_use)
tts.save(tmp... | ec3b0892dca75244a746ead7afe5ce41a2001941 | 3,611,911 |
def get_img_mask_generators(dataset_path,
target_size,
img_path="img",
ann_path="ann",
img_preprocessor=None,
mask_preprocessor=None,
SEED=1,):
"""
... | c0d6a9de27bc8af98c838bea695934129ae8b73e | 3,611,912 |
import sys
from io import StringIO
import traceback
def dump_exception():
"""create execption info for json response."""
info = sys.exc_info()
message = {"name": str(info[0]), "message": str(info[1])}
if __debug__:
buff = StringIO()
traceback.print_exc(file=buff)
message["trace... | f663e3ae3dc07ca489570ba9bbe126df7a2ac3af | 3,611,913 |
def prepare_noise_cov(noise_cov, info, ch_names=None, rank=None,
scalings=None, verbose=None):
"""Prepare noise covariance matrix.
Parameters
----------
noise_cov : instance of Covariance
The noise covariance to process.
info : dict
The measurement info (used t... | eb0111c4f1c4e997bcf71f9f7a3d81ff19e9954f | 3,611,914 |
def gsl_blas_zgemm(*args, **kwargs):
"""
gsl_blas_zgemm(CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB,
gsl_complex alpha, gsl_matrix_complex A, gsl_matrix_complex B,
gsl_complex beta, gsl_matrix_complex C) -> int
"""
return _gslwrap.gsl_blas_zgemm(*args, **kwargs) | 5d273fab2e8b9c0379cd477b1ba51fb5c7e1525c | 3,611,915 |
import requests
from bs4 import BeautifulSoup
def get_login_api(username, password):
"""
登入系统
"""
s = requests.session()
lt = get_ticker(s)
url = 'http://ids.sdufe.edu.cn/authserver/login?service=http%3A%2F%2Flibst.sdufe.edu.cn%2Fcas%2Findex.php%3Fcallback%3Dhttp%3A%2F%2Flibst.sdufe.edu.cn%2Fh... | 7d739178f8316f19e421de9564a2a72a7070d09d | 3,611,916 |
import torch
def sparsify_array(array):
"""Convert a np.array into a torch.sparse.FloatTensor
Args:
array (np.array)
returns:
sparse (torch.sparse.Tensor)
"""
return sparsify_tensor(torch.FloatTensor(array)) | db16c3a369f696694abc050ef0a11264406fff62 | 3,611,917 |
def tracer(pid):
"""tracer(pid) -> int
Arguments:
pid (int): PID of the process.
Returns:
PID of the process tracing `pid`, or None if no `pid` is not being traced.
Example:
>>> tracer(os.getpid()) is None
True
"""
tpid = int(status(pid)['TracerPid'])
retur... | 8042e473f392c255d0e8c75d2e05aa88237361bd | 3,611,918 |
async def staking_config_cms(
project: str,
db=Depends(get_db),
):
"""
Get config
"""
try:
return get_staking_config_by_name(db, project)
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST, content=f"{str(e)}"
) | 5227bf979a7025c5e946cb152e31e7625cb764ec | 3,611,919 |
import shutil
import os
def validate_file(path, validate_yamls, tmpdir=None, lock=None):
"""Validate a file on disk.
Parameters
----------
path : str
The path to the file.
validate_yamls : dict
A dictionary mapping the filename of the validation yaml to its
contents.
t... | 4521ec1b59253837bea03a140c9f965c3dc54bc2 | 3,611,920 |
import bisector
import build_specified_commit
import tempfile
import logging
import traceback
def do_bisect(bisect_type, source_id, project_name, engine, sanitizer,
architecture, fuzz_target, old_commit, new_commit, testcase):
"""Do the actual bisect."""
with tempfile.NamedTemporaryFile() as f:
... | 548c9525199f16778adff12c42ebf4f69a68144f | 3,611,921 |
import torch
def _unstack(array):
"""Similar to `tf.unstack`."""
num_splits = int(array.shape[0])
return [torch.squeeze(x, dim=0) for x in np.split(array, num_splits, axis=0)] | 34df9cd0ea0620f88f47ab6aeeaec80a6d2ba030 | 3,611,922 |
def by_included_absolute_path(path, df_logs_formated):
"""
return subset of conversations that contains specific node
@param path path: array
"""
print("filtering.by_included_absolute_path() is DEPRECATED and will be removed in a future release. ")
# create an empty dataframe with the same colum... | 68baa0b38971a439f9f8287291938c40749bfd54 | 3,611,923 |
def predict(images, model, alpha, rho=0, return_model=False):
"""Apply background subtraction to a batch of images
Args:
images: numpy array with shape [num_ims, height, width, channel]
containing the images to process.
model: tuple (mean, std) obtaining with create_model() function.
... | b06512141faa884cda315d789058a81f95569e2f | 3,611,924 |
def stations_by_river(stations):
"""This function creates a dictionary with river names as a key and a list of all the
station names on the respective river"""
rivers = rivers_with_station(stations)
river_dictionary = {}
for river in rivers:
river_dictionary[river] = [] #Generating Empty Di... | e1ae6797a44a551594dcad1e5b38e171cef7730a | 3,611,925 |
import unicodedata
def filter_nick(name):
"""
filter_nick(name) -> String
Process the name and get rid of all whitespace, invisible characters and
make it all lower case.
This function is intended to mimic euphoria's name pinging system, however
it is slightly less pedantic, allowing for pun... | bba506f4b2e84b4f82df8a4b31feb82203db8356 | 3,611,926 |
from datetime import datetime
from dateutil import tz
def get_mondays():
"""Returns a tuple with start and end Time Stamp Strings from last monday to midnight this monday.
Unless it is a monday. In that case we actually want the previous period."""
today = datetime.now().replace(hour=0, minute=0, second=0... | 1d04182150ae2e4196002b5b18d338e103980d40 | 3,611,927 |
def tfidf_score_str(tokens, texts, tfidf_function_name, number_all_texts_in_db, m=10,*args):
# Same as tfidf_score, only takes tfidf_function name as input instead of function itself.
"""Assigns score to documents based on tfidf_function metric.
Args:
tokens (list): List of tokens (tokenized query).... | bfc91875f28e189b68630115bf7acba1ad05e6e5 | 3,611,928 |
def distort_img(input_img, d_limit=4):
"""
Apply warpPerspective transformation on image, with 4 key points, randomly generated around the corners
with uniform distribution with a range of [-d_limit, d_limit]
:param input_img:
:param d_limit:
:return:
"""
if d_limit == 0:
return ... | c8e214a0a022ade460686b5557b8bc78747a38f1 | 3,611,929 |
def delete_v1_session(session_id): # noqa: E501
"""DELETE /v1/session
Delete the session by session id
"""
with BosEtcdClient() as bec:
key = "{}/{}/".format(BASEKEY, session_id)
resp = bec.delete_prefix(key)
if resp.deleted >= 1:
return '', 204
else:
... | 92e1d3564bf1698cdaeede161370f994dcd7682a | 3,611,930 |
def label_name(event_data):
"""Get the label name from a label-related webhook event."""
return event_data["label"]["name"] | 903173b4fd9ddeb0a74a3e10be94626e0685a037 | 3,611,931 |
import tempfile
import os
import json
def post_file_list():
"""
Upload one or more files and return parsed result back as JSON array
:return:
"""
files = request.files
if not files:
LOGGER.info("No file found in request")
raise BadRequest("No file found in request")
resul... | 80ef736a004dd7a59954ec6ed9db64772bcc129f | 3,611,932 |
from datetime import datetime
def new_event(dtstart=None, dtend=None, summary=None, timezone=None,
_now=datetime.now):
"""create a new event
:param dtstart: starttime of that event
:type dtstart: datetime
:param dtend: end time of that event
:type dtend: datetime
:param summary:... | 9721e2cac6e0fef45e60436e7cf5e5d0d1eb750c | 3,611,933 |
def getCashflowsByUserID(db, userID):
"""
Get cash flows by user's ID
:param db: database object
:param userID: user's ID
:return: Tuple of cash flow
((flowID, userID, amount, message, date), ((flowID, userID, amount, message, date)))
"""
if db is None:
return None
try:
... | b2a1e1d52de74559792feca57f2366d38ced9e46 | 3,611,934 |
def predict_fn(self, x):
"""
Overrides the predict function for models, provided that the predict
function takes in one argument.
"""
predict_array = self.predict(x)
return convert_prediction_to_event(self, predict_array, x) | 0c7d34c121446155f371cb11871714acf78c37d5 | 3,611,935 |
from typing import Dict
from typing import Any
from typing import Type
from typing import Optional
def run(config: Dict[str, Any],
data_class: Type[DataModule],
model_class: Type[Module],
optuna: Optional[Optuna] = None,
runner: Optional[Runner] = None) -> Trainer:
"""Run the pipel... | 8d0890ff3e7a29d770f3365a85324be7edc5ed61 | 3,611,936 |
def concretePolynomialLoad():
"""
pytest fixture that returns a PolynomialLoad object with concrete parameters
:return: PolynomialLoad object initialized with concrete values
"""
addnl_params = dict(p=0.5, q=0.98, r=2678.88)
test_load_params = dict(a=0.01, b=0.05, c=0.1, j_load=0.1, p=0.5, q = ... | 910bc2a38f4b8c321cba4324cfcf99fbc72c9ffe | 3,611,937 |
def decode(data):
"""
Decodes URL safe base64 encoded value
"""
padding = 4 - (len(data) % 4)
data += ('=' * padding)
return urlsafe_b64decode(data).decode() | a39c75e1260a500ec1431c86a9bfa57623599823 | 3,611,938 |
from demisto_sdk.commands.upload.uploader import ConfigFileParser, Uploader
from demisto_sdk.commands.zip_packs.packs_zipper import (EX_FAIL,
PacksZipper)
def upload(**kwargs):
"""Upload integration or pack to Demisto instance.
DEMISTO_BASE_URL environment variable should contain the Demisto server base U... | eba4120bc7701752a1fb9831e4874c20ef29293a | 3,611,939 |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2 ** (int(value) - 1).bit_length() | bb49afee83ac255549ce5b5aaab80bb76ad4e337 | 3,611,940 |
def clip_but_pass_gradient(x, l=-1., h=1.):
"""
Stole this function from SpinningUp
Args:
x: data to be clipped.
l: lower bound
h: upper bound.
Return:
if x < l:
l
elif x > h:
h
else:
x
"""
clip_up = tf.cast(x > ... | a30e034a7b4c98df15c0da766f34c47a1bb39651 | 3,611,941 |
def get_encryption_algs():
"""Return a list of available encryption algorithms"""
return _enc_algs | 54813d7ec3caf8e077ac0d53e69166b861941c4e | 3,611,942 |
def get_statements_by_hash(hash_list, simple_response=False, *args, **kwargs):
"""Get fully formed statements from a list of hashes.
Parameters
----------
hash_list : list[int or str]
A list of statement hashes.
simple_response : bool
If True, a simple list of statements is returned... | 566557527b32348121f0a0f2473a221a1e671e98 | 3,611,943 |
import abc
def _get_prop(props_dict, spec):
"""Gets the given property specification from the dictionary
The specification can be a string or a pair of string and a callable.
:param dict props_dict: The dictionary to retrieve the property.
:param spec: The specification of the property, it can be a ... | 732c65fdfacd44f3b14bdd590990bd35d16c3d22 | 3,611,944 |
from typing import Match
def real_time(
minutes: float = 5,
increment: int = 8,
variant: Variant = Variant.STANDARD,
color: Color = Color.RANDOM,
) -> Match:
"""Start a live match that two players can join
:param minutes: :class:`float`
The number of minutes for the match (excluding i... | 05fcdde0ba90b69763d570749107b656675cb4da | 3,611,945 |
import re
def _RevisionRangeFromSummary(summary):
"""Uses regex to extract revision range from bug a summary string.
Note: Information such as test path and revision range for a bug could
also be gotten by querying the datastore for Anomaly entities for
each bug ID. However, these queries might be relatively... | ddb995993f7c7f145a1c47f278798a64eba32175 | 3,611,946 |
import json
def json_top_atom_count(json_str):
"""Count the number of atoms in a JSON topology used by wepy HDF5."""
top_d = json.loads(json_str)
atom_count = 0
atom_count = 0
for chain in top_d['chains']:
for residue in chain['residues']:
atom_count += len(residue['atoms'])
... | 0e1e23cd4b9e5cedf3e6b5d815ee817798188752 | 3,611,947 |
def length_squared(point):
"""
square of length from origin of a point
Args:
point (QPointF) the point
Returns
square of length
"""
return point.x()*point.x() + point.y()*point.y() | 0289ca736f087dd75f9b9e0f1347fdc223d03f84 | 3,611,948 |
def api_report_conference_role(conference_id, role_id):
"""
Takes a role ID and report data and reports the object with the
provided ID.
"""
return api_report_conference_child(conference_id, request.json, role_id, object_type="role") | 4a1b8ecadfccafdf76e616df851a5ca937e1a432 | 3,611,949 |
from typing import Union
from typing import Sequence
from typing import Callable
from typing import Optional
from typing import Dict
from typing import List
from typing import Any
from typing import Tuple
def plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(
illuminants: Union[str, Sequence[str]],
chro... | efc5dee6f632adccaf9fb413385bc71acda1ef54 | 3,611,950 |
def topSort(G):
"""
使用BFS实现拓扑排序。
每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则放入列队。直到列队为空。
"""
Q = [] # 列队存储每个节点
counter = 0
sort = {}
for i in G:
if i.degree == 0:
Q.append(i)
while len(Q) != 0:
vertex = Q.pop()
sort[vertex] = counter
counter += 1
if vertex.c == None:
continue
for j in... | 3b8662a4adbc32d9a2174b5faf82d0c763d703fe | 3,611,951 |
def _process_hooks(hooks):
"""Prepare hooks data for report."""
hooks_ctx = []
for hook in hooks:
hook_ctx = {"name": hook["config"]["action"][0],
"desc": hook["config"].get("description", ""),
"additive": [], "complete": []}
for res in hook["results"... | f0804e25c095547840f6f7eb5de7a76864b98970 | 3,611,952 |
def find_nearest_index(seq, value):
"""
Return the index of the value in the sequence that is closest to the
given value
"""
return (np.abs(np.array(seq)-value)).argmin() | 199e2ca62a0d820a04964676a28b702993701b36 | 3,611,953 |
import getopt
import sys
def get(params_config, params=None, is_show_help=True):
"""标准化处理参数
根据提供的params_config参数,提供参数params中的字段,返回字典
params_config例:
{
'username':
{'must':False,'data':True,'short':'U','long':'username','default':'root'},
'password':
... | b149a0aeeb246d0b0d5c36c3e9032d0d64563654 | 3,611,954 |
from typing import Union
async def log_request(request: AsyncRequest, session: ClientSession) -> Union[str, None]:
"""
Logging wrapper around AsyncRequest.send method.
"""
log = get_default_logger()
base_url = session._base_url # pylint: disable=protected-access
request_full_url = request.url... | 5efa11e8dc52dac441b3862eef6304eeb5998022 | 3,611,955 |
def get_pv_asp_n(n):
"""Returns ASP PV associated with neg(-) beam species, either -.
Required for Main Buncher.
Arguments:
n(str or int): module or buncher number
"""
return get_pv_asp(n, '+') | e571d8cf062da019a0c52c7b1e383c33bac4afd4 | 3,611,956 |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] | f7841bc5104f96cd66122165a0646b70fc3fd33e | 3,611,957 |
import six
import copy
import os
import shlex
import sys
def wkhtmltopdf(pages, output=None, **kwargs):
"""
Converts html to PDF using http://wkhtmltopdf.org/.
pages: List of file paths or URLs of the html to be converted.
output: Optional output file path. If None, the output is returned.
**kwar... | e719c9ba51678278538f8a42279b823c97729bee | 3,611,958 |
def display_image(obd, mime_type):
"""Display the opaque binary response data with the image using IPython's
display.Image class
:param str obd: The opaque binary data
:param str mime_type: The image mime_type
:rtype: IPython.display.Image
"""
filename = write_temp_file(obd, mime_type)
... | f6530051c6b03d30cbf0952aa4d25412e0ba31b7 | 3,611,959 |
def load_checkpoint_train(cpdir, model, optimizer):
"""Load model and optimizer parameters for training
Note:
This is simply a wrapper to load_checkpoint so that
global_step and epoch are updated correctly.
If cpdir is None, do not load checkpoint and returns
0 for global_step an... | 076d7dc40eb361d523a164a5b1082cd8b1fe4ca9 | 3,611,960 |
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding='valid', data_format=None, dilation_rate=1):
"""1D convolution with separable filters.
# Arguments
x: input tensor
depthwise_kernel: convolution kernel for the depthwise convolution.
poin... | 6ccfa89d31ccb1255552fbb9adef4500846281fa | 3,611,961 |
def has_sub_tasks(task):
"""Returns True if the task has sub tasks"""
if istask(task):
return True
elif isinstance(task, list):
return any(has_sub_tasks(i) for i in task)
else:
return False | fe55cbef39dc9d2a748e8bf9dc283d6146f27c79 | 3,611,962 |
from typing import List
def largest_values_in_row_colums(xs: np.array) -> List[float]:
""" Approximates the largest value in each row/column.
"""
if xs.shape == (0, ):
return [0]
assert len(xs.shape) == 2
# resize matrix to square dimensions if needed
if xs.shape[0] != xs.shape[1]:
... | 5a53345364d24fcf40305b4de5253051572a7de0 | 3,611,963 |
import xmlrpc
def delete_vm(client, session, vm, params):
"""Delete (ie: terminate) a virtual machine."""
if vm['state'] is None:
return {'changed': False}
xmlrpc(client, 'vm.action', session, 'terminate', vm['id'])
return {'changed': True, 'vm_id': -1, 'actions': ['terminated']} | d3f6c4d5fec34569fc9a066b6402f43e7816164e | 3,611,964 |
import os
def file_exists(file):
"""Check if a file exists."""
if not os.path.exists(file):
return False
try:
open(file).close()
except IOError:
return False
return True | 34a3f66e8597cd0cf7b77c9c270407268ac52a70 | 3,611,965 |
def save_polygon_data_format(naptan_polygon,
area_name,
naptan_column):
"""[summary] saves naptan polygon data, into a variety of formats for later
usage by other analytical tools.
Args:
naptan_polygon ([type]): [description]
area_na... | 36e2ec8eab76d9cbef007c51dbcf33f1f7a3ea91 | 3,611,966 |
import collections
def fit_all_random(X_matr, rand_X_matr, Y_matr, rows, lag, fit_method, save_prefix=None, save_XY=True, verbose=False,
has_reps=False, bootstrap=False, seed=None, only_array=False, **kwargs):
"""
X_matr: m x T (x r) of X's
rand_X_matr: m x T ( x r) of X's. Same as X_matr exce... | 4957dae3b60a73e4526a6cee3119a1722d2a1112 | 3,611,967 |
def check_bad_bbox(data, test_op, invalid_bbox_type, expected_error):
"""
:param data: de object detection pipeline
:param test_op: Augmentation Op to test on image
:param invalid_bbox_type: type of bad box
:param expected_error: error expected to get due to bad box
:return: None
"""
de... | fad04a018ef0b7def476f2a5491857e5de40b3d2 | 3,611,968 |
def check_patch_in_bounds(x, y, X_dim, Y_dim):
""" Usage: TrueFalse = check_patch_in_bounds(x, y, X_dim, Y_dim)
determine if the box is within the image
Args:
x: a tuple, list or array (x_start, x_end)
y: a tuple, list or array (y_start, Y_end)
... | 80221a95fda698f31aeed6c91987a5227a21e751 | 3,611,969 |
def _tiger_line_url(geometry, year):
"""
Return URL (or URLs) of zip file(s) containing shape files
for a given census geography
:param geometry: name of census geometry to download
:param year: year of geometry to download
:return: List of URLs
"""
base = "https://www2.census.gov/geo/t... | a6f84c9fd26ec270fd29c37a6181220cde4dabda | 3,611,970 |
def get_coordinate_transformation(source_sr, target_sr):
"""This function takes a source and target spatial reference and creates
a coordinate transformation from source to target, and one from target
to source.
source_sr - A spatial reference
target_sr - A spatial reference
... | 3f47cdd9886f18e4b8357f29a23fee8ac756f250 | 3,611,971 |
def d_customer_orders():
"""
Real Name: b'D Customer Orders'
Original Eqn: b'W Indicated Orders'
Units: b''
Limits: (None, None)
Type: component
b''
"""
return w_indicated_orders() | df26969c14f0d0929b96246926d42b1eab8345f8 | 3,611,972 |
def build_reservations_ical_file(reservations):
"""
Return iCalendar file containing given reservations
"""
cal = Calendar()
cal['X-WR-CALNAME'] = vText('RESPA')
cal['name'] = vText('RESPA')
for reservation in reservations:
event = Event()
event['uid'] = 'respa_reservation_{... | c034502c3854264c3ee1ecea03c87b185519da83 | 3,611,973 |
def domain(request) -> str:
"""Return AWS domain"""
return request.config.getoption("--domain") or "amazonaws.com" | fbf812dd28eb6aa3ff6a647a4cd1d17b739cb320 | 3,611,974 |
def sha2_384(data: bytes) -> hashes.MessageDigest:
"""
Convenience function to hash a message.
"""
return CryptographyHash.hash(hashes.sha2_384(), data) | 6053054b84a37e5d99d2a7bfe4fcf34499945f25 | 3,611,975 |
def build_corpus(group):
"""
Function to apply to a category subset. Returns a list of LabeledSentences to train doc2vec.
"""
return group.apply(lambda row: LabeledSentence(row.clean_comment, [row.sentence_tag]), axis=1).values | 987f7e52553eb09cc30fb3ad2665ee7a8b009c93 | 3,611,976 |
import ast
def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error wil... | 45defbbe9f14a08052fd0c3cb320b8c8735a91cc | 3,611,977 |
import base64
import hashlib
def signature(text):
"""
This helper method normalizes text and takes the SHA1 hash of it,
returning the base64 encoded result. The normalization method includes
the removal of punctuation and white space as well as making the case
completely lowercase. These signature... | 4984094624e172d1e6666746378c7b7dfac256cf | 3,611,978 |
def no_stderr():
"""
There is no standard error
"""
with app.app_context():
return jsonify({'error':'stderr does not exist'}), 400 | 3c42b3557d7fe342cd800a127452c15d5c4ce7ee | 3,611,979 |
import torch
def compute_colors_for_labels(labels):
"""
Simple function that adds fixed colors depending on the class
"""
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = labels[:, None] *palette # self.palette
colors = (colors % 255).numpy().astype("uint8")
... | 59785d9a6f297d022ee13e9a4013cd28e7f62a10 | 3,611,980 |
from api.serializers import InstanceSerializer
def set_instance_from_metadata(esh_driver, core_instance):
"""
NOT BEING USED ANYMORE.. DEPRECATED..
"""
# Fixes Dep. loop - Do not remove
# Breakout for drivers (Eucalyptus) that don't support metadata
if not hasattr(esh_driver._connection, 'ex_g... | 8d4978f72404b25e1aba6ec891c7be4e395a9b88 | 3,611,981 |
def read_table(data, coerce_type, transpose=False):
"""
Reads in data from a simple table and forces it to be a particular type
This is a helper function that allows data to be easily constained in a
simple script
::return: a dictionary of with the keys being a tuple of the strings
in the fi... | 6701736354b30d41b4adf7c6a11406f26c21c71b | 3,611,982 |
def load_def_omni(tint, cfg, data_path):
"""Loads Density Energy Flux spectrum
Parameters
----------
tint : list of str
Time interval
cfg : dict
Hash table from configuration file.
Returns
-------
"""
ic = np.arange(1, 5)
suf = "fpi_{}_{}".format(cfg["data_r... | 868675a6ebaa94719346c97771e5d70547e14cb3 | 3,611,983 |
def test_constant():
""" Test a tesorflow session """
sess = tf.Session()
first = tf.constant(4)
second = tf.constant(5)
return sess.run(first * second) | 2ce039f1c07ac60c751a015c9f56575b7f2d5bb4 | 3,611,984 |
def robots():
"""Robot Crawler txt for search engines."""
if current_app.config['STATIC_ROUTES'].get('robots', None):
response = make_response(
render_template(
template_path(current_app.config['STATIC_ROUTES']['robots'])
)
)
response.headers['Cont... | 2dcb80dd58e86c90cc22b68ad39a09509dd52311 | 3,611,985 |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it trains on the PubMed dataset.
The default hyperparameters give a good quality representation without grid search.
"""
parser = argparse.ArgumentParser(description = "Run .")
parser.add_arg... | 7a4b82373d1d1f7028eb6c228d35d3f35107ce19 | 3,611,986 |
def cat_arg_and_value(arg_name, value):
"""Concatenate a command line argument and its value
This function returns ``arg_name`` and ``value
concatenated in the best possible way for a command
line execution, namely:
- if arg_name starts with `--` (e.g. `--arg`):
`arg_name=value` is returned (... | bcd99ab465707e594646d2152ad7b10b32956f5e | 3,611,987 |
def is_expired_dds_response(response):
"""
Check status_code of the response for the two values denoting expired URLs
:param response: requests.Response
:return: bool: True when the response is expired status
"""
return response.status_code == SWIFT_EXPIRED_STATUS_CODE or response.status_code ==... | 47d774a0fcf22cc11d9f0ed0de0eb77dbc44185e | 3,611,988 |
def write_session(prev_sessions, sessions, start_time, end_time, session_path, logger=structlog.get_logger()):
"""
Rewrite json file with new data
:param prev_sessions: old sessions
:param sessions: new sessions
:param time: timestamp of processed flows
:param session_path: path to json file
... | 306ad7b84acf99bce0a4585bb31b09a297341e6d | 3,611,989 |
def remove_formatting(input: str) -> str:
"""Remove color information from string."""
return input.replace(bcolors.ENDC, "")\
.replace(bcolors.OKGREEN, "")\
.replace(bcolors.OKBLUE, "") | 4e459a38b925bc0fac733c7570407b9c9265ab67 | 3,611,990 |
def update_event(request, event_id):
"""Event update view.
If the request type is POST, update the event and redirect the user to the
events detail page. Otherwise, display the event creation form.
Arguments:
request - Django object containing request information.
event_id (int) - ID of Event ... | fe164f7e17f431559ca3d6ffbdcb78aa49979c77 | 3,611,991 |
def poly_linear_constraints(p, d):
"""
Given p = [p1, ..., pm] in k[t]^m and d in k[t], return
q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such
that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible
by d if and only if (c1, ..., cm) is a solution of Mx = 0, in
which case... | 3fcdcaf312c8a4e95853ff21e9225d81acc9a927 | 3,611,992 |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
step_unit = 1000.0 # 1024?
results=[]
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
results.append("%3.2f %s" % (num, x))
num /= step_unit
return results | 41ec1d6e7a7975d1bddf22a09f840c59e3283b95 | 3,611,993 |
def comment_is_liked(comment_entity, liker):
"""Returns true if a given user (liker) has liked a given comment"""
likes_query = CommentLike.all()
likes_query.filter('liker =', liker)
likes_query.filter('comment =', comment_entity)
return likes_query.count() > 0 | 9cf3e453370a1bec19adbf182f56713b72690a70 | 3,611,994 |
def GetRenderView(connection=None):
"""Return the render view in use. If more than one render view is in
use, return the first one."""
if not connection:
connection = ActiveConnection
render_module = None
for aProxy in ProxyManager().NewConnectionIterator(connection):
if aProxy.IsA... | 4328efd8a96f7185814e4119e98c6f2ec182473c | 3,611,995 |
def get_fuzzer_name(fuzzer_config_filename: str) -> str:
"""Get the fuzzer specified in fuzzer_config_filename"""
fuzzer_config = yaml_utils.read(get_fuzzer_configs_dir() /
fuzzer_config_filename)
# Multiple configurations of the same fuzzer are differentiated by their
... | c7be73a0278262b864d246c45a5193a295af325a | 3,611,996 |
def colorize_mask(mask, color_map=None):
"""
Attaches a color palette to a PIL image. So long as the image is saved as a PNG, it will render visibly using the
provided color map.
:param mask: PIL image whose values are only 0 to 4 inclusive
:param color_map: np.ndarray or list of 3-tuples with 5 row... | 45b6e6fb224711791dab843c42e93c40fbda5a28 | 3,611,997 |
import requests
def langs():
"""
Get list of both src and target languages
"""
html = requests.get(settings.site_url).content
crawl_soup = bs4.BeautifulSoup(html, 'html.parser')
langs = []
lang_id = 0
tags = crawl_soup.find('select').find_all('option')
for tag in tags:
nam... | e8128d0b629e6cb1b810dd9d91b756f6e92e9c37 | 3,611,998 |
def dummy_pipeline_measurements_vaex() -> vaex.dataframe.DataFrame:
"""
A dummy pipeline measurements dataframe, as a vaex dataframe.
Loaded from the test data directory.
Returns:
The dummy pipeline measurements vaex dataframe.
"""
filepath = TEST_DATA_DIR / 'test_measurements_vaex.csv... | 3b89397e18daf20ac2b6c784c8369c796e2012ce | 3,611,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.