content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
from pathlib import Path
def _parse_args() -> argparse.Namespace:
"""Registers the script's arguments on an argument parser."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source-root',
type=Path,
required=T... | cda37a6282b95fca4db51e91bfe98cc44f46fd07 | 4,600 |
def qlist(q):
"""Convenience function that converts asyncio.Queues into lists.
This is inefficient and should not be used in real code.
"""
l = []
# get the messages out
while not q.empty():
l.append(q.get_nowait())
# now put the messages back (since we popped them out)
for i in... | 0ce6fb0d543646fb036c35c800d75bbadf670b0d | 4,601 |
def is_stdin(name):
"""Tell whether or not the given name represents stdin."""
return name in STDINS | 535ce3fee9e4a9a42ef24e4b35f84420a61cc529 | 4,602 |
def filter_marker_y_padding(markers_y_indexes, padding_y_top, padding_y_bottom):
"""
Filter the markers indexes for padding space in the top and bottom of answer sheet
:param markers_y_indexes:
:param padding_y_top:
:param padding_y_bottom:
:return:
"""
return markers_y_indexes[(markers... | b1eed0ac24bd6a6354072427be4375ad188572a5 | 4,603 |
import pandas as pd
import os
def budget_italy(path):
"""Budget Shares for Italian Households
a cross-section from 1973 to 1992
*number of observations* : 1729
*observation* : households
*country* : Italy
A dataframe containing :
wfood
food share
whouse
housing and fuels share
wm... | dac6aa79f04bda47395a927c0aba950bc53ae33f | 4,604 |
def hr_admin(request):
""" Views for HR2 Admin page """
template = 'hr2Module/hradmin.html'
# searched employee
query = request.GET.get('search')
if(request.method == "GET"):
if(query != None):
emp = ExtraInfo.objects.filter(
Q(user__first_name__icontains=query)... | b78f78c57282b60b527bbaa03eab9064d881aea1 | 4,605 |
def create_aws_clients(region='us-east-1'):
"""Creates an S3, IAM, and Redshift client to interact with.
Parameters
----------
region : str
The aws region to create each client (default 'us-east-1').
Returns
-------
ec3
A boto3 ec2 resource.
s3
A boto3 s3 resour... | 3a422ac88791e404d67127bc85bab12b6a8aa4d9 | 4,606 |
def apply_function(f, *args, **kwargs):
""" Apply a function or staticmethod/classmethod to the given arguments.
"""
if callable(f):
return f(*args, **kwargs)
elif len(args) and hasattr(f, '__get__'):
# support staticmethod/classmethod
return f.__get__(None, args[0])(*args, **kwa... | 374be0283a234d4121435dbd3fa873640f2b9ad1 | 4,607 |
def join_data(ycom_county, census, land_area_data):
"""
Getting one dataframe from the three datasets
"""
census['LogPopDensity'] = np.log10(census['TotalPop']/land_area_data['LND110200D'])
data = pd.concat(([ycom_county, census]), axis=1)
return data | 171c08d0c5dac721c3100df9be747c90b299a6c1 | 4,608 |
def _createController(config):
"""
Creates the appropriate (hypervisor) controller based on the
given configuration.
This is the place where to perform particular initialization tasks for
the particular hypervisor controller implementations.
@param config: an instance of L{ConfigParser}
... | eaaa80aed58e72de91e8d93288aec65544b39b45 | 4,609 |
def path_graph():
"""Return a path graph of length three."""
G = nx.path_graph(3, create_using=nx.DiGraph)
G.graph["name"] = "path"
nx.freeze(G)
return G | c5fd4ea322b512bd26755d94581d56ddfb4d52bf | 4,610 |
def dropStudentsWithEvents(df, events,
saveDroppedAs=None,
studentId='BookletNumber',
eventId='Label',
verbose=True):
"""
Drop students with certain events.
It finds students with the events, and use... | 5308ec96c8d5d3c9704f4a42202656bc4126e645 | 4,611 |
import os
def get_html_app_files_dirs(output_file):
"""
Return a tuple of (parent_dir, dir_name) directory named after the
`output_file` file object file_base_name (stripped from extension) and a
`_files` suffix Return empty strings if output is to stdout.
"""
if is_stdout(output_file):
... | 36ac7b6cb1d2071c0728dc34fcdbd6d34da8f708 | 4,612 |
def create_slides(user, node, slideshow_data):
""" Generate SlideshowSlides from data """
""" Returns a collection of SlideshowSlide objects """
slides = []
with transaction.atomic():
for slide in slideshow_data:
slide_obj = SlideshowSlide(
contentnode=node,
... | 6fc31c11f0dc24d17fd82eacd366a0026fb95157 | 4,613 |
def is_valid(sequence):
"""
A string is not valid if the knight moves onto a blank square
and the string cannot contain more than two vowels.
"""
if any(letter == "_" for letter in sequence):
return False
# Check for vowels
# Strings shorter than 3 letters are always ok, as they
... | 0c3a72d05155eaf69ffeb7a734e9ceeabe0c44c2 | 4,614 |
def batch_dl1_to_dl2(
dict_paths,
config_file,
jobid_from_training,
batch_config,
logs,
):
"""
Function to batch the dl1_to_dl2 stage once the lstchain train_pipe batched jobs have finished.
Parameters
----------
dict_paths : dict
Core dictionary with {stage: PATHS} info... | 673a65e2a4fb6e55339117da657734557858cec8 | 4,615 |
import webbrowser
import os
import io
def browse():
"""
A browser for the bibmanager database.
"""
# Content of the text buffer:
bibs = bm.load()
keys = [bib.key for bib in bibs]
compact_text = "\n".join(keys)
expanded_text = "\n\n".join(bib.content for bib in bibs)
# A list object... | 90f233a9f3a2088067c6e23efedf5a12a3db1b79 | 4,616 |
import sys
def read_lines_from_input(file):
"""
Reads the provided file line by line to provide a list representation of the contained names.
:param file: A text file containing one name per line. If it's None, the input is read from the standard input.
:return: A list of the names contained in the pr... | 4a653979ee51afea8e7199772199c1a93dbfecc3 | 4,617 |
import urllib
def is_dataproc_VM():
"""Check if this installation is being executed on a Google Compute Engine dataproc VM"""
try:
dataproc_metadata = urllib.request.urlopen("http://metadata.google.internal/0.1/meta-data/attributes/dataproc-bucket").read()
if dataproc_metadata.decode("UTF-8").... | 21044a482b534ce3625b49080d1c472d587039ad | 4,618 |
def lookup_all(base):
"""Looks up a subclass of a base class from the registry.
Looks up a subclass of a base class with name provided from the
registry. Returns a list of registered subclass if found, None otherwise.
Args:
base: The base class of the subclass to be found.
Returns:
A list of subcla... | de6a8504d0c6cf6f149b597e4d8b41f7b5fc1eff | 4,619 |
def makepyfile(testdir):
"""Fixture for making python files with single function and docstring."""
def make(*args, **kwargs):
func_name = kwargs.pop('func_name', 'f')
# content in args and kwargs is treated as docstring
wrap = partial(_wrap_docstring_in_func, func_name)
args = ma... | 420733f4ee299514dba4172cfcc93b7429c635ca | 4,620 |
from PIL import Image, ImageDraw, ImageFont
def createTextWatermark(msg, size, loc, fontcolor='white', fontpath='arial.ttf', fontsize=18):
"""Creates a watermark image of the given text.
Puts it at the given location in an RGBA image of the given size.
Location should be a 2-tuple denoting the center loca... | 6a1ae202a92b351f7d7301735dc825e826898522 | 4,621 |
def get_server_pull_config(config:dict):
"""
takes a config dictionary and returns the variables related to server deployment (pull from intersections).
If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception
"""
try:
server = config["Data... | 3a5a882bf91cb65462cdbf4fe202bbbc9d52ae2c | 4,622 |
def buff_push(item: BufferItem):
"""
Add BufferItem to the buffer and execute if the buffer is full
"""
q.put(item)
make_dependencies(item)
if q.full():
return buff_empty_partial(q.maxsize - 1)
return None | d45c0f67fa21cade7a0c2462e1cd8167f4939e0b | 4,623 |
import os
def installDirectory():
"""
Return the software installation directory, by looking at location of this
method.
"""
#path = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir))
path = os.path.abspath(os.path.realpath(__file__))
path = os.path.abspath(os.path.join(... | d79d57eea1eb38ec56a864246ac2388d7320a0fa | 4,624 |
from rx.core.operators.take import _take
from typing import Callable
def take(count: int) -> Callable[[Observable], Observable]:
"""Returns a specified number of contiguous elements from the start
of an observable sequence.
.. marble::
:alt: take
-----1--2--3--4----|
[ take(2)... | 636cc982c6c8c9b13a2cecb675bb0ca7aadbcd91 | 4,625 |
from typing import List
from typing import Union
def format_fields_for_join(
fields: List[Union[Field, DrivingKeyField]],
table_1_alias: str,
table_2_alias: str,
) -> List[str]:
"""Get formatted list of field names for SQL JOIN condition.
Args:
fields: Fields to be formatted.
tabl... | 691a154f8b984b11ed177a7948fe74398c693b25 | 4,626 |
def get_payment_balance(currency):
"""
Returns available balance for selected currency
This method requires authorization.
"""
result = get_data("/payment/balances", ("currency", currency))
payment_balance = namedtuple("Payment_balance", get_namedtuple(result[0]))
return [payment_balance(... | 354abbf4e9bc1b22a32e31555106ce68a21e9cd1 | 4,627 |
import torch
def build_scheduler(optimizer, config):
"""
"""
scheduler = None
config = config.__dict__
sch_type = config.pop('type')
if sch_type == 'LambdaLR':
burn_in, steps = config['burn_in'], config['steps']
# Learning rate setup
def burnin_schedule(i):
... | b205b323db322336426f3c13195cb49735d7284d | 4,628 |
def rpca_alm(X, lmbda=None, tol=1e-7, max_iters=1000, verbose=True,
inexact=True):
"""
Augmented Lagrange Multiplier
"""
if lmbda is None:
lmbda = 1.0 / np.sqrt(X.shape[0])
Y = np.sign(X)
norm_two = svd(Y, 1)[1]
norm_inf = np.abs(Y).max() / lmbda
dual_norm = np.max(... | 8c09f8f4b004b9a00655402e5466636aa9fc4390 | 4,629 |
def dwt_embed(wmImage, hostImage, alpha, beta):
"""Embeds a watermark image into a host image, using the First Level
Discrete Wavelet Transform and Alpha Blending.\n
The formula used for the alpha blending is:
resultLL = alpha * hostLL + beta * watermarkLL
Arguments:
wmImage (NumPy arr... | 939e8d14ceb9452dc873f7b2d9472630211c0432 | 4,630 |
def make_file_iterator(filename):
"""Return an iterator over the contents of the given file name."""
# pylint: disable=C0103
with open(filename) as f:
contents = f.read()
return iter(contents.splitlines()) | e7b612465717dafc3155d9df9fd007f7aa9af509 | 4,631 |
def build_summary(resource, children, attribute, summarizer, keep_details=False):
"""
Update the `resource` Resource with a summary of itself and its `children`
Resources and this for the `attribute` key (such as copyrights, etc).
- `attribute` is the name of the attribute ('copyrights', 'holders' etc... | 622a560c257eceae6d82dc93ffc15718fca0152d | 4,632 |
def little_endian_bytes_to_int(little_endian_byte_seq):
"""Converts a pair of bytes into an integer.
The `little_endian_byte_seq` input must be a 2 bytes sequence defined
according to the little-endian notation (i.e. the less significant byte
first).
For instance, if the `little_endian_byte_seq` i... | d8d0c6d4ebb70ea541e479b21deb913053886748 | 4,633 |
def higher_follower_count(A, B):
""" Compares follower count key between two dictionaries"""
if A['follower_count'] >= B['follower_count']: return "A"
return "B" | d4d182ca5a3c5bff2bc7229802603a82d44a4d67 | 4,634 |
def _element_or_none(germanium, selector, point):
"""
Function to check if the given selector is only a regular
element without offset clicking. If that is the case, then we
enable the double hovering in the mouse actions, to solve a
host of issues with hovering and scrolling, such as elements
a... | b3de13ecefc7b8593d4b61e7caf63eee41d1521a | 4,635 |
def ENDLEMuEpP_TransferMatrix( style, tempInfo, crossSection, productFrame, angularData, EMuEpPData, multiplicity, comment = None ) :
"""This is LLNL I = 1, 3 type data."""
logFile = tempInfo['logFile']
workDir = tempInfo['workDir']
s = versionStr + '\n'
s += "Process: 'Double differential EMuEpP... | 224e72f52ad6b143e51a50962d548084a8e7c283 | 4,636 |
def _fit_gaussian(f, grid, image_spot, p0, lower_bound=None, upper_bound=None):
"""Fit a gaussian function to a 3-d or 2-d image.
# TODO add equations and algorithm
Parameters
----------
f : func
A 3-d or 2-d gaussian function with some parameters fixed.
grid : np.ndarray, np.float
... | 6fa75997af8dfee3cf90bdcab7919c6eeea0578e | 4,637 |
def createfourierdesignmatrix_chromatic(toas, freqs, nmodes=30, Tspan=None,
logf=False, fmin=None, fmax=None,
idx=4):
"""
Construct Scattering-variation fourier design matrix.
:param toas: vector of time series in seconds
... | 59420ea9bde77f965f4571bdec5112d026c63478 | 4,638 |
def get_word_data(char_data):
"""
获取分词的结果
:param char_data:
:return:
"""
seq_data = [''.join(l) for l in char_data]
word_data = []
# stop_words = [line.strip() for line in open(stop_word_file, 'r', encoding='utf-8')]
for seq in seq_data:
seq_cut = jieba.cut(seq, cut_all=False... | 8ca306d0f3f4c94f6d67cdc7b865ddef4f639291 | 4,639 |
import os
def make_non_absolute(path):
"""
Make a path non-absolute (so it can be joined to a base directory)
@param path: The file path
"""
drive, path = os.path.splitdrive(path)
index = 0
while os.path.isabs(path[index:]):
index = index + 1
return path[index:] | 51eefa84423077273931a3a4c77b4e53669a6599 | 4,640 |
from typing import List
from typing import Dict
from typing import Any
def get_output_stream(items: List[Dict[str, Any]]) -> List[OutputObject]:
"""Convert a list of items in an output stream into a list of output
objects. The element in list items are expected to be in default
serialization format for ou... | 841bffba3f0e4aeab19ca31b62807a5a30e818f1 | 4,641 |
def lvnf_stats(**kwargs):
"""Create a new module."""
return RUNTIME.components[LVNFStatsWorker.__module__].add_module(**kwargs) | 1bdf94687101b8ab90684b67227acec35205e320 | 4,642 |
import re
def parse_float(string):
"""
Finds the first float in a string without casting it.
:param string:
:return:
"""
matches = re.findall(r'(\d+\.\d+)', string)
if matches:
return matches[0]
else:
return None | 4adea9226d0f67cd4d2dfe6a2b65bfd24f3a7ecb | 4,643 |
def objectproxy_realaddress(obj):
"""
Obtain a real address as an integer from an objectproxy.
"""
voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)
return C.addressof(C.c_char.from_buffer(voidp)) | 6c2f1a2b0893ef2fd90315a2cd3a7c5c5524707f | 4,644 |
def CollateRevisionHistory(builds, repo):
"""Sorts builds and revisions in repository order.
Args:
builds: a dict of the form:
```
builds := {
master: {
builder: [Build, ...],
...,
},
...
}
```
repo (GitWrapper): repository in which the revision occurs.
... | e092d5c77c3767dbcf02ba7e19ba5c923bd9aad7 | 4,645 |
def delta_shear(observed_gal, psf_deconvolve, psf_reconvolve, delta_g1, delta_g2):
"""
Takes in an observed galaxy object, two PSFs for metacal (deconvolving
and re-convolving), and the amount by which to shift g1 and g2, and returns
a tuple of tuples of modified galaxy objects.
((g1plus, g1minus), (g2plus, g2minu... | 13ab29088a1a88305e9f74ab1b43351f2d19b3c6 | 4,646 |
def estimateModifiedPiSquared(n):
"""
Estimates that value of Pi^2 through a formula involving partial sums.
n is the number of terms to be summed; the larger the more accurate the
estimation of Pi^2 tends to be (but not always).
The modification relative to estimatePiSquared() is that the n terms a... | 652376bf0964990905bf25b12ad8ab5156975dea | 4,647 |
def pattern_match(template, image, upsampling=16, metric=cv2.TM_CCOEFF_NORMED, error_check=False):
"""
Call an arbitrary pattern matcher using a subpixel approach where the template and image
are upsampled using a third order polynomial.
Parameters
----------
template : ndarray
T... | adb98b96d9ca778a909868c0c0851bf52b1f0a1b | 4,648 |
def main(argv=[__name__]):
"""Raspi_x10 command line interface.
"""
try:
try:
devices_file, rules_file, special_days_file = argv[1:]
except ValueError:
raise Usage('Wrong number of arguments')
sched = Schedule()
try:
sched.load_conf(devices... | 583df25dc3fb3059d6ed5b87d61a547fc1a11935 | 4,649 |
def HexaMeshIndexCoord2VoxelValue(nodes, elements, dim, elementValues):
"""
Convert hexamesh (bricks) in index coordinates to volume in voxels with value of voxels assigned according to elementValues.
dim: dimension of volume in x, y and z in voxels (tuple)
elementValues: len(elements) == len(eleme... | 8dcab059dd137173e780b7dd9941c80c89d7929c | 4,650 |
def hamiltonian(latt: Lattice, eps: (float, np.ndarray) = 0.,
t: (float, np.ndarray) = 1.0,
dense: bool = True) -> (csr_matrix, np.ndarray):
"""Computes the Hamiltonian-matrix of a tight-binding model.
Parameters
----------
latt : Lattice
The lattice the tight-bi... | 63df0f8557ba13fe3501506974c402faca1811f5 | 4,651 |
def pad_in(string: str, space: int) -> str:
"""
>>> pad_in('abc', 0)
'abc'
>>> pad_in('abc', 2)
' abc'
"""
return "".join([" "] * space) + string | 325c0751da34982e33e8fae580af6f439a2dcac0 | 4,652 |
def get_notifies(request):
"""页面展示全部通知"""
user = request.siteuser
if not user:
return HttpResponseRedirect(reverse('siteuser_login'))
notifies = Notify.objects.filter(user=user).select_related('sender').order_by('-notify_at')
# TODO 分页
ctx = get_notify_context(request)
ctx['notifies... | 8042b42f03a7ce48b7355a7ba51f02937c00d9d0 | 4,653 |
def get_existing_rule(text):
"""
Return the matched rule if the text is an existing rule matched exactly,
False otherwise.
"""
matches = get_license_matches(query_string=text)
if len(matches) == 1:
match = matches[0]
if match.matcher == MATCH_HASH:
return match.rule | 9c41241532977b0a30485c7b7609da3c6e75b59c | 4,654 |
import time
def confirm_channel(bitcoind, n1, n2):
"""
Confirm that a channel is open between two nodes
"""
assert n1.id() in [p.pub_key for p in n2.list_peers()]
assert n2.id() in [p.pub_key for p in n1.list_peers()]
for i in range(10):
time.sleep(0.5)
if n1.check_channel(n2) ... | bcbf895b286b446f7bb0ad2d7890a0fa902cdbd1 | 4,655 |
def has_permissions(**perms):
"""A :func:`check` that is added that checks if the member has any of
the permissions necessary.
The permissions passed in must be exactly like the properties shown under
:class:`discord.Permissions`.
Parameters
------------
perms
An argument list of p... | bf9432f136db8cd2643fe7d64807194c0479d3cd | 4,656 |
def extend_params(params, more_params):
"""Extends dictionary with new values.
Args:
params: A dictionary
more_params: A dictionary
Returns:
A dictionary which combines keys from both dictionaries.
Raises:
ValueError: if dicts have the same key.
"""
for yak in more_params:
if yak in p... | 626db0ae8d8a249b8c0b1721b7a2e0f1d4c084b8 | 4,657 |
import logging
def __compute_libdeps(node):
"""
Computes the direct library dependencies for a given SCons library node.
the attribute that it uses is populated by the Libdeps.py script
"""
if getattr(node.attributes, 'libdeps_exploring', False):
raise DependencyCycleError(node)
env ... | 93e44b55bb187ae6123e22845bd4da69b260b107 | 4,658 |
def _AccumulatorResultToDict(partition, feature, grads, hessians):
"""Converts the inputs to a dictionary since the ordering changes."""
return {(partition[i], feature[i, 0], feature[i, 1]): (grads[i], hessians[i])
for i in range(len(partition))} | 20cc895cf936749a35c42a1158c9ea6645019e7d | 4,659 |
def scale_rotor_pots(rotors, scale_factor=((), None)):
""" scale the pots
"""
# Count numbers
numtors = 0
for rotor in rotors:
numtors += len(rotor)
# Calculate the scaling factors
scale_indcs, factor = scale_factor
nscale = numtors - len(scale_indcs)
if nscale > 0:
... | f89a04a86029debdef79d2d39ad3fb005d9a28a0 | 4,660 |
async def create(payload: ProductIn):
"""Create new product from sent data."""
product_id = await db.add_product(payload)
apm.capture_message(param_message={'message': 'Product with %s id created.', 'params': product_id})
return ProductOut(**payload.dict(), product_id=product_id) | 77f9ef1699cba57aa8e0cfd5a09550f6d03b8f72 | 4,661 |
def get_glove_info(glove_file_name):
"""Return the number of vectors and dimensions in a file in GloVe format."""
with smart_open(glove_file_name) as f:
num_lines = sum(1 for line in f)
with smart_open(glove_file_name) as f:
num_dims = len(f.readline().split()) - 1
return num_lines, num_... | 4fde6a034197e51e3901b22c46d946330e2e213e | 4,662 |
from typing import Dict
from typing import List
def retrieve_database_inputs(db_session: Session) -> (
Dict[str, List[RevenueRate]], Dict[str, MergeAddress], List[Driver]):
"""
Retrieve the static inputs of the model from the database
:param db_session: SQLAlchemy Database connection session
:... | f5242680576d7e07b87fb8fd31e26efc1b0c30f0 | 4,663 |
def _evolve_cx(base_pauli, qctrl, qtrgt):
"""Update P -> CX.P.CX"""
base_pauli._x[:, qtrgt] ^= base_pauli._x[:, qctrl]
base_pauli._z[:, qctrl] ^= base_pauli._z[:, qtrgt]
return base_pauli | 5d0529bc4bfe74a122c24069eccb20fa2b69f153 | 4,664 |
def tp_pixel_num_cal(im, gt):
""" im is the prediction result;
gt is the ground truth labelled by biologists;"""
tp = np.logical_and(im, gt)
tp_pixel_num = tp.sum()
return tp_pixel_num | 197c1f64df3430cfbb6f45413b83360a1b9c44bf | 4,665 |
import time
def xsg_data(year=None, month=None,
retry_count=3, pause=0.001):
"""
获取限售股解禁数据
Parameters
--------
year:年份,默认为当前年
month:解禁月份,默认为当前月
retry_count : int, 默认 3
如遇网络等问题重复执行的次数
pause : int, 默认 0
重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题
... | 0ca7070a63ec9ee58bb590b82d9bcdb8e4801d33 | 4,666 |
def crm_ybquery_v2():
"""
crm根据用户手机号查询subId
:return:
"""
resp = getJsonResponse()
try:
jsonStr = request.data
# 调用业务逻辑
resp = {"message":"","status":200,"timestamp":1534844188679,"body":{"password":"21232f297a57a5a743894a0e4a801fc3","username":"admin"},"result":{"id"... | 02b7ff4e1f44643537b4549376aa637dcdbf5261 | 4,667 |
from typing import Dict
from typing import List
from typing import Union
from pathlib import Path
from typing import Iterable
from typing import Tuple
import tqdm
import logging
def get_split_file_ids_and_pieces(
data_dfs: Dict[str, pd.DataFrame] = None,
xml_and_csv_paths: Dict[str, List[Union[str, Path]]] = ... | d01768fddcef9428e5dd3a22592dca8dd083fc9c | 4,668 |
def calc_full_dist(row, vert, hor, N, site_collection_SM):
"""
Calculates full distance matrix. Called once per row.
INPUTS:
:param vert:
integer, number of included rows
:param hor:
integer, number of columns within radius
:param N:
integer, number of points in row
... | e332b3b51cf4dadb764865f7c75eb361aa0cc100 | 4,669 |
def background_upload_do():
"""Handle the upload of a file."""
form = request.form
# Is the upload using Ajax, or a direct POST by the form?
is_ajax = False
if form.get("__ajax", None) == "true":
is_ajax = True
print form.items()
# Target folder for these uploads.
# target = o... | 267608fa9c93a75ca260eb742fed9023ec350b65 | 4,670 |
def catch_list(in_dict, in_key, default, len_highest=1):
"""Handle list and list of list dictionary entries from parameter input files.
Casts list entries of input as same type as default_val.
Assign default values if user does not provide a given input parameter.
Args:
in_dict: Dictionary in ... | e001d35a12f3826be78903f03b6e6539c8d07192 | 4,671 |
import os
import re
def _load_candidate_scorings (spec, input_dir_candidates, predictor):
"""
Load the msms-based scores for the candidates of the specified msms-spectra.
:param spec: string, identifier of the spectra and candidate list. Currently
we use the inchikey of the structure represented ... | dfbc53dc0651cf427ca8e5050e4523c8779415d1 | 4,672 |
def load_dict_data(selected_entities=None, path_to_data_folder=None):
"""Loads up data from .pickle file for the selected entities.
Based on the selected entities, loads data from storage,
into memory, if respective files exists.
Args:
selected_entities: A list of string entity names to be loa... | 0236d69d6ed6c663c3bba5edabd59ced9755c546 | 4,673 |
def cart_del(request, pk):
""" remove an experiment from the analysis cart and return"""
pk=int(pk) # make integer for lookup within template
analyze_list = request.session.get('analyze_list', [])
if pk in analyze_list:
analyze_list.remove(pk)
request.session['analyze_list'] = analyze_list
... | 210a0fd58d9470aa365906420f3769b57815839a | 4,674 |
def get_block_devices(bdms=None):
"""
@type bdms: list
"""
ret = ""
if bdms:
for bdm in bdms:
ret += "{0}\n".format(bdm.get('DeviceName', '-'))
ebs = bdm.get('Ebs')
if ebs:
ret += " Status: {0}\n".format(ebs.get('Status', '-'))
... | bd375f988b13d8fe5949ebdc994210136acc3405 | 4,675 |
from scipy import stats # lazy import
from pandas import DataFrame
def outlier_test(model_results, method='bonf', alpha=.05, labels=None,
order=False, cutoff=None):
"""
Outlier Tests for RegressionResults instances.
Parameters
----------
model_results : RegressionResults instance... | 39219cf5ad86f91cf6da15ea66dc2d18f0a371af | 4,676 |
def move(request, content_type_id, obj_id, rank):
"""View to be used in the django admin for changing a :class:`RankedModel`
object's rank. See :func:`admin_link_move_up` and
:func:`admin_link_move_down` for helper functions to incoroprate in your
admin models.
Upon completion this view sends the ... | 0a8e73d83d7d7c575a8ed5abe43524b22d701a38 | 4,677 |
def test_second_playback_enforcement(mocker, tmp_path):
"""
Given:
- A mockable test
When:
- The mockable test fails on the second playback
Then:
- Ensure that it exists in the failed_playbooks set
- Ensure that it does not exists in the succeeded_playbooks list
"""
... | 314cbfb4f659b34adfdafb6b1c1153c8560249b0 | 4,678 |
import re
def decode_textfield_ncr(content):
"""
Decodes the contents for CIF textfield from Numeric Character Reference.
:param content: a string with contents
:return: decoded string
"""
def match2str(m):
return chr(int(m.group(1)))
return re.sub('&#(\d+);', match2str, content... | 28bf8017869d1ad47dce4362ec2b57131f587bba | 4,679 |
def reflect_or_create_tables(options):
"""
returns a dict of classes
make 'em if they don't exist
"tables" is {'wfdisc': mapped table class, ...}
"""
tables = {}
# this list should mirror the command line table options
for table in list(mapfns.keys()) + ['lastid']:
# if option... | 8974f6e6299240c69cf9deffdb3efb7ba9dc771f | 4,680 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_grpc_interface]
interface_dir=<<path to the parent directory of your Protocol Buffer (pb2) files>>
#<<package_name>>=<<communication_ty... | cb26012ff6ad1a2dbccbbcc5ef81c7a91def7906 | 4,681 |
import multiprocessing
import os
def get_workers_count_based_on_cpu_count():
"""
Returns the number of workers based available virtual or physical CPUs on this system.
"""
# Python 2.6+
try:
return multiprocessing.cpu_count() * 2 + 1
except (ImportError, NotImplementedError):
... | 0f42840196e596a371a78f16443b4bc22a89c460 | 4,682 |
def color_print(path: str, color = "white", attrs = []) -> None:
"""Prints colorized text on terminal"""
colored_text = colored(
text = read_warfle_text(path),
color = color,
attrs = attrs
)
print(colored_text)
return None | c3f587d929f350c86d166e809c9a63995063cf95 | 4,683 |
def create_cluster_spec(parameters_server: str, workers: str) -> tf.train.ClusterSpec:
"""
Creates a ClusterSpec object representing the cluster.
:param parameters_server: comma-separated list of hostname:port pairs to which the parameter servers are assigned
:param workers: comma-separated list of host... | 2b4555b68821327451c48220e64bc92ecd5f3acc | 4,684 |
def bq_client(context):
"""
Initialize and return BigQueryClient()
"""
return BigQueryClient(
context.resource_config["dataset"],
) | 839a72d82b29e0e57f5973aee418360ef6b3e2fc | 4,685 |
def longascnode(x, y, z, u, v, w):
"""Compute value of longitude of ascending node, computed as
the angle between x-axis and the vector n = (-hy,hx,0), where hx, hy, are
respectively, the x and y components of specific angular momentum vector, h.
Args:
x (float): x-component of position
... | d108847fa6835bc5e3ff70eb9673f6650ddf795a | 4,686 |
def volumetric_roi_info(atlas_spec):
"""Returns a list of unique ROIs, their labels and centroids"""
if is_image(atlas_spec) and is_image_3D(atlas_spec):
if atlas_spec.__class__ in nibabel.all_image_classes:
atlas_labels = atlas_spec.get_fdata()
else:
atlas_labels = np.a... | 427d421e53712ddd34982e32c87d77918ecca716 | 4,687 |
def predictFuture(bo:board, sn:snake, snakes:list, foods:list):
"""
Play forward (futuremoves) turns
Check for enemy moves before calculating route boards
==
bo: boardClass as board
sn: snakeClass as snake
snakes: list[] of snakes
==
return: none
(set board routing... | 78020678691e41f447c25cb2bd807c9db7a04c86 | 4,688 |
def convert_to_distance(primer_df, tm_opt, gc_opt, gc_clamp_opt=2):
"""
Convert tm, gc%, and gc_clamp to an absolute distance
(tm_dist, gc_dist, gc_clamp_dist)
away from optimum range. This makes it so that all features will need
to be minimized.
"""
primer_df['tm_dist'] = get_distance(
... | 4d556fd79c2c21877b3cb59712a923d5645b5eba | 4,689 |
import copy
def _tmap_error_detect(tmap: TensorMap) -> TensorMap:
"""Modifies tm so it returns it's mean unless previous tensor from file fails"""
new_tm = copy.deepcopy(tmap)
new_tm.shape = (1,)
new_tm.interpretation = Interpretation.CONTINUOUS
new_tm.channel_map = None
def tff(_: TensorMap,... | 263a16a5cb92e0a9c3d42357280eeb6d15a59773 | 4,690 |
def generate_dataset(config, ahead=1, data_path=None):
"""
Generates the dataset for training, test and validation
:param ahead: number of steps ahead for prediction
:return:
"""
dataset = config['dataset']
datanames = config['datanames']
datasize = config['datasize']
testsize = co... | 89136efffbbd6e115b1d0b887fe7a3c904405bda | 4,691 |
def search(isamAppliance, name, check_mode=False, force=False):
"""
Search UUID for named Web Service connection
"""
ret_obj = get_all(isamAppliance)
return_obj = isamAppliance.create_return_object()
return_obj["warnings"] = ret_obj["warnings"]
for obj in ret_obj['data']:
if obj['na... | f642e9e62203b490a347c21899d45968f6258eba | 4,692 |
def flask_app(initialize_configuration) -> Flask:
"""
Fixture for making a Flask instance, to be able to access application context manager.
This is not possible with a FlaskClient, and we need the context manager for creating
JWT tokens when is required.
@return: A Flask instance.
"""
fla... | 265c912833025d13d06c2470443e68110ce4f60f | 4,693 |
import requests
def http_request(method, url_suffix, params=None, data=None, headers=HEADERS, safe=False):
"""
A wrapper for requests lib to send our requests and handle requests and responses better.
:type method: ``str``
:param method: HTTP method for the request.
:type url_suf... | 9fbd5123e4f1a39f5fa10fbc6a8f41db7ed1775b | 4,694 |
import time
import torch
import sys
def train(train_loader, model, criterion, average, optimizer, epoch, opt):
"""one epoch training"""
model.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
end = time.time()
for i, (images, labels, _) in enumerate(t... | ad2f4379cf283c1716c9d3befb0ee2f50c28c081 | 4,695 |
def FP(target, prediction):
"""
False positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return ((target == 0).float() * prediction.float().round()).sum() | 9c8b21ecbc4f48b737c92fbaf73ef820fe035218 | 4,696 |
import math
def get_angle(A, B, C):
"""
Return the angle at C (in radians) for the triangle formed by A, B, C
a, b, c are lengths
C
/ \
b / \a
/ \
A-------B
c
"""
(col_A, row_A) = A
(col_B, row_B) = B
(col_C, row_C) = C
a = pixel_distance(C, ... | 30e1681bf2c065c4094b2dd909322158a9968c3c | 4,697 |
def single_labels(interesting_class_id):
"""
:param interesting_class_id: integer in range [0,2] to specify class
:return: number of labels for the "interesting_class"
"""
def s_l(y_true, y_pred):
class_id_true = K.argmax(y_true, axis=-1)
accuracy_mask = K.cast(K.equal(class_id_true,... | d137bbd4bba4bcb19e9bc296e4cecdbd7d8effe6 | 4,698 |
def get_iam_policy(client=None, **kwargs):
"""
service_account='string'
"""
service_account=kwargs.pop('service_account')
resp = client.projects().serviceAccounts().getIamPolicy(
resource=service_account).execute()
# TODO(supertom): err handling, check if 'bindings' is correct
if 'bi... | b777a317e9637a410b78847d05a6725f7600c04f | 4,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.