content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Any
def login_access_token(
response: Response,
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(
... | 86976ee36574a6906c7f430fe57e67144bfea8d9 | 44,800 |
def parse_method(name):
"""Parse hyperparameters from string name to make legend label.
Parameters
----------
name : str
Name of method
Returns
-------
string : str
Formatted string
"""
string = r""
if name.split('es_')[1][0] == '1':
string += r'ES'
... | eb6824a6ab7ca126c924fa7acca2725f8b06379e | 44,801 |
import pathlib
def update_game_index(path: pathlib.Path,
source: str, league: str,
df: pd.DataFrame) -> pd.DataFrame:
"""Update the game index for league with data from source."""
league = league.replace(" ", "").replace("-", "")
(path/league).mkdir(exist_ok=Tru... | f731d8c61d35ef28d8430f54427f2de954540993 | 44,802 |
import itertools
def find_td_chordal(graph, order):
"""Finding a tree decomposition for chordal graphs."""
cliques = find_all_maximal_cliques(graph, order)
H = Graph() # graf przeciec klik maksymalnych
bag_dict = dict()
# Budowanie workow.
for c in cliques:
bag = tuple(sorted(c))
... | 9a300e52adf5070f800f575cfc1e76ad0eac072b | 44,803 |
def get_categories() -> pd.DataFrame:
"""Returns dataframe of tesco food categories"""
return pd.read_csv(TESCO_DIR / "food_categories.csv") | 8de1ccd77adb59ed309ecbdb2be456485222e5ab | 44,804 |
def Transformer(input_vocab_size,
output_vocab_size=None,
d_model=512,
d_ff=2048,
n_encoder_layers=6,
n_decoder_layers=6,
n_heads=8,
dropout=0.1,
dropout_shared_axes=None,
max_... | ffb34a8838a12803a26c9969a28f2ff7948e3d50 | 44,805 |
def schedule_conv2d_NHWC_quantized_native_without_transform(cfg, outs):
"""Interface for native schedule_conv2d_NHWC_quantized"""
return _schedule_conv2d_NHWC_quantized(cfg, outs, False) | 7794a68c48228facd6b2f2ea9b1b450ab95defeb | 44,806 |
def mentions(date, aliases):
"""Pull dark web mentions data for an organization."""
# aliases = aliases.replace("'", '"')
# aliases = str(aliases)[1:-1]
mentions = ""
for mention in aliases:
mentions += '"' + mention + '"' + ","
mentions = mentions[:-1]
print(mentions)
query = "s... | 865e9b5053c16c61e4d3dfb2f1ca5f6c6b30a9bc | 44,807 |
import queue
def queue_with(items):
"""Return a thread-safe iterator that yields the given items.
+items+ can be given as an array or an iterator. If an iterator is
given, it will be consumed to fill the queue before queue_with()
returns.
"""
q = queue.Queue()
for val in items:
q.... | a7dae1a57ee09686ae432993678a96638810154a | 44,808 |
import math
def resample_by(image_array, compression_factor_list, is_seg=False):
"""
Resamples `image` to new resolution according to a compression factor using scipy's `ndimage`
Attributes:
image_array (float, np.array) : Array of voxel values for image
compression_factor_list (list) : ... | 1bad1803b5539ff8ab6f9077e791d318e462af01 | 44,809 |
def get_highlight(request):
"""
Get Originals objects with highlight status and
render them.
"""
highlight = Original.objects.filter(status='h')
context = {
'highlight': highlight,
'highlight_page': 'active',
'title': 'Highlights'
}
return render(request, "highli... | 5206e8650080e1f994d8b0bb9f3458b7252d645d | 44,810 |
from typing import Tuple
from typing import Optional
def create_or_update_out_of_the_bbox(
move_data: DataFrame,
bbox: Tuple[int, int, int, int],
new_label: Optional[Text] = OUT_BBOX,
inplace: Optional[bool] = True
) -> Optional[DataFrame]:
"""
Create or update a boolean feature to detect poin... | 03fe49fca38c8b225dc236a5702a90bd9f8f568c | 44,811 |
def pin_compatible(m, package_name, lower_bound=None, upper_bound=None, min_pin='x.x.x.x.x.x',
max_pin='x', permit_undefined_jinja=True):
"""dynamically pin based on currently installed version.
only mandatory input is package_name.
upper_bound is the authoritative upper bound, if provid... | 44044cc44ba70882265a56d098f2239941d99609 | 44,812 |
def _get_etc_dir():
"""The root directory of xedge, such as `/home/gamecenter/etc`"""
return os_path.join(os_path.dirname(os_path.abspath(__file__)),
os_path.pardir, 'etc') | a1b2fc7ca4fe33f8b52d57e3ca8d244b57814432 | 44,813 |
from pathlib import Path
def _sandbox_executable() -> Path:
"""Return full path to Algorand's sandbox executable."""
return ConfigParams.sandbox_dir / "sandbox" | e3b533ecdd9a606a6deb2c7433c7c8b74a30c7f5 | 44,814 |
def _get_file_contents(path):
"""
Gets the contents of a specified file, ensuring that the file is properly
closed when the function exits
"""
with open(path, "r") as f:
return f.read() | cfe84e52e2ac48d3f7d9d20fd1c85c71a222ef95 | 44,815 |
from firebase_admin import auth
from Pages.UserAuthentication.Exceptions import User_not_Found
import traceback
def get_user_by_phone_number(phone):
"""
Returns a user object that is dictionary
of the user with attributes:
display_name , email , password, phone_number
"""
try:
user = auth.get_user_by_phone_n... | 1892c92d6b25c8fdbbd7bfc61b25927bf12972ab | 44,816 |
import re
def get_root_server(domain):
"""
Find the WHOIS server for a given domain
:param domain: The domain to find a WHOIS server for
:return: The WHOIS server, or an empty string if no server is found
"""
data = whois_request(domain, "whois.iana.org").response or ""
for line in [x.stri... | 00ca409f24f48844a1004351b849fca780991732 | 44,817 |
def sample_user(email='test@test.com',password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email,password) | d7aa9cb839a7a767cd83a9448643cf9a2945c76d | 44,818 |
def getsubheader(runid,snapnum,datadir=None,datascope=False,getfof=False,verbose=False):
"""Reads the SUBFIND header (total number of subhalos) of an Indra snapshot.
Parameters
----------
runid : int or tuple
Specifies the Indra run either as an integer from 0 to 511
or as a length ... | e950c9d1c40813408eaa87ce2f0ab2ce0f3b773a | 44,819 |
def from_config(config, token_store: tokens.TokenStore):
""" Generate a Fediverse handler from the given config dictionary.
:param dict config: Configuration values; relevant keys:
* ``FEDIVERSE_NAME``: the name of your website (required)
* ``FEDIVERSE_HOMEPAGE``: your website's homepage (rec... | 29c2dca8268a8ca21a65a26e103276033b9bfcec | 44,820 |
import json
def clickwrap_responses():
"""
1. Get required arguments
2. Call the worker method
3. Render the response
"""
# 1. Get required arguments
args = Eg005Controller.get_args()
try:
# 2. Call the worker method to get clickwrap responses
results = Eg005Controller... | e57c0c30e49fea8461f6d9971a43651a36de54ce | 44,821 |
def get_confirm_token(response):
"""
Filters response for confirm token.
:param Response response: Response object to filter through.
:returns: token or None
"""
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None | ea4a3e28136c77e69af0255027568c216e92ffed | 44,822 |
import math
def wilcoxont(x, y):
"""
Calculates the Wilcoxon T-test for related samples and returns the
result. A non-parametric T-test.
Usage: lwilcoxont(x,y)
Returns: a t-statistic, two-tail probability estimate
"""
if len(x) != len(y):
raise ValueError('Unequal N in wilcoxont. Aborting.')
... | f24df26f434f25062f3f3e43dcbf7a5c301c9579 | 44,823 |
import textwrap
def msgfmt(msg, prefix=''):
"""Format a message"""
lines = []
for line in msg.splitlines():
lines += textwrap.wrap(line, 80 - len(prefix))
return '\n'.join([prefix + line for line in lines]) | 66bd8ecb9aa50ade1d8c588deaf70b3ff7d4f0d7 | 44,824 |
def _parse_text(raw_object: RawObject) -> Text:
"""Parse the raw object into Text.
Args:
raw_object: Raw object to be parsed to a Text
Returns:
Text: The Text object created from the raw object
"""
# required attributes
raw_text: RawText = raw_object["text"]
text = raw_text... | 28ac3f1578fda10ad55b1a9fe5dd1c65177724fd | 44,825 |
def _is_onetime_boot(task):
"""Check onetime boot from server hardware.
Check if the onetime boot option of an OneView server hardware
is set to 'Once' in iLO.
:param task: a task from TaskManager.
:returns: Boolean value. True if onetime boot is 'Once'
False otherwise.
"""
s... | a041323c37b386f3b467b78a6185d97465b134bf | 44,826 |
def get_setting(name: str) -> Setting:
"""Return appropriate setting."""
if name not in SETTINGS:
raise Exception(
"Setting does not exist. Valid settings are: %s" % list(SETTINGS.keys())
)
return SETTINGS[name] | 49ee9171425c63679e546b30d13e25308adb2885 | 44,827 |
def convertKeyValueToString(dict,key) -> str:
""" converts a single key value pair into a concatenated string"""
if dict and key:
# force cast key to string
val = dict[key]
valStr = str(val)
keyStr = str(key)
concantStr = keyStr + valStr
else:
concantStr = ""... | a5c0c4f0c5e2d1b072873ed4c491583ef9784e27 | 44,828 |
def _flatten(seq):
"""Internal function."""
res = ()
for item in seq:
if isinstance(item, (tuple, list)):
res = res + _flatten(item)
elif item is not None:
res = res + (item,)
return res | eeb6c3df5dc4ca5e8a57e2e32f7333bafb107328 | 44,829 |
import uuid
def get_uuid(value):
"""
gets the uuid object of given value.
it raises an error if value is not a valid uuid string.
:param str value: value to get uuid instance from it.
:raises ValueError: value error.
:rtype: uuid.UUID
"""
return uuid.UUID(value) | 8b22f34b9d44366c3903ab1e59d57a3fa1f6b37a | 44,830 |
from .plugin import create_vocabulary
def tag_autocomplete():
""" CKAN autocomplete discards vocabulary_id from request.
This is modification from tag_autocomplete function from CKAN.
Takes vocabulary_id as parameter.
"""
q = request.args.get('incomplete', '')
limit = request.args.get(... | c3d3f58979cad99f9866857bbafdc17e4d9f30bc | 44,831 |
from opf_python.universal import get_HNF_diagonals
def hex_22(n):
"""Finds the symmetry preserving HNFs for the hexagonal lattices
with a determinant of n. Assuming A = [[0,0,-0.5],[1,0,0],[-0.5,0.8660254037844386,0]].
Args:
n (int): The determinant of the HNFs.
Returns:
spHNFs (list... | 4579d451627ab157d45cc54e5d509792577aafec | 44,832 |
def preprocess_int(i, **options):
"""Convert a string to an integer."""
return str(i) | 7d40ef9e0547aaeb635068c11d91e84531e0ae4a | 44,833 |
def es_cadena_valida(adn):
"""
Ingresa una cadena y determina si es valida o no
:param adn: Ingresa unos caracteres en mayuscula para validar si estan o no en el rango
:return: True o False si es o no cadena respectivamente
>>> es_cadena_valida('AGATA')
True
>>> es_cadena_valida('GATA')
... | cc5c6517759d7373b40bc599c234274f1e49d48e | 44,834 |
def legendre_basis(x_data, n_state=2, domain=(0, 1), chunks=(1,)):
"""
legendre discretization of a microstructure.
Args:
x_data (ND array) : The microstructure as an `(n_samples, n_x, ...)`
shaped array where `n_samples` is the number of samples and
`n_x` is the spatial dis... | 59cbc4e2edad27482e09fd2083c4928a0c8dd599 | 44,835 |
def redemption_group_counts():
"""
Build integers which can represent the number of groups in the redemption
process.
"""
return integers(
min_value=1,
# Make this similar to the max_value of voucher_counters since those
# counters count through the groups.
max_value=... | 0c7e40d997761530c2bf79517110666c38b8bddd | 44,836 |
import tempfile
import subprocess
import logging
def netchop_predict(sequences):
"""
Return netChop predictions for each position in each sequence.
Parameters
-----------
sequences : list of string
Amino acid sequences to predict cleavage for
Returns
-----------
list of list of... | c97855c2c23732714471fc6e4e576cd77137c7e8 | 44,837 |
def ThetaV(pressures, temps_cent, dewp_temps_cent):
"""Virtual Potential Temperature
INPUTS
temp_k (K)
pres (Pa)
e: Water vapour pressure (Pa) (Optional)
"""
mixr = WaterVapourMixingRatio(pressures, dewp_temps_cent)
theta = Theta(pressures, temps_cent, dewp_temps_cent)
return... | 6011a3d4042783b3eae2cca3938639c734da221b | 44,838 |
from typing import Dict
from typing import List
import os
def build_fluxfile(spec1d_to_sensfunc: Dict[str,str], output_path: str,
spectrograph: str, user_config_lines: List[str]) -> str:
"""
Writes the fluxfile for fluxing.
Uses archived sensitivity function if no standard was reduced.
Args:... | 12b5984e54e552c0c261651debb3aa9e5afa7e2b | 44,839 |
import six
def check_image_hdu(data, ext=0, logger=logger):
"""Check if a data is a valid ImageHDU type or convert it."""
if not isinstance(data, imhdus):
if isinstance(data, fits.HDUList):
logger.debug(f"Extracting HDU from ext {ext} of HDUList")
data = data[ext]
elif ... | 28968b1bd178a7a55228e4bf72373991adc88ce0 | 44,840 |
def cluster_smiles(smiles: list, clustering_cutoff: float = 0.4):
""" Cluster smiles based on their Murcko scaffold using the Butina algorithm:
D Butina 'Unsupervised Database Clustering Based on Daylight's Fingerprint and Tanimoto Similarity:
A Fast and Automated Way to Cluster Small and Large Data Sets',... | a474678ebea60cfb57b64476fe5ae45cfe3d5c05 | 44,841 |
def is_uri(name):
"""Checks whether the name is a URI or not.
:param name: Name of the resource
:returns: True if name is URI, False otherwise
"""
try:
(urn, prod, trailer) = name.split(':', 2)
return (urn == 'urn' and prod == PROD_NAME)
except Exception:
return False | 8d7e8df1278821c5f6d5a6abf21a61df9f3f5abd | 44,842 |
def query_flask_state():
"""
Query the local state and redis status
:return: flask response
"""
try:
b2d = request.json
if not isinstance(b2d, dict):
logger.warning(ErrorMsg.DATA_TYPE_ERROR).get_msg(
'.The target type is {}, not {}'.format(dict.__name__, t... | 3883b64257bf79454049188a891962c21a0c7f81 | 44,843 |
def calc_delta_L_dash_CS_R_d_t_i(i, region, Q, r_A_ufvnt, underfloor_insulation, A_A, A_MR, A_OR, A_HCZ_i, Theta_ex_d_t,
L_dash_H_R_d_t_i, L_dash_CS_R_d_t_i):
"""当該住戸の暖冷房区画iの床下空間を経由して外気を導入する換気方式による冷房顕熱負荷削減量 (MJ/h) (2)
Args:
i(int): 暖冷房区画の番号
region(int): 省エネルギー地域区分
... | cacf42940597b1efdb07f48e7325def2c27a1680 | 44,844 |
import torch
import random
import math
def select_action(state, valueNetwork, episodeNumber, numTakenActions, args):
""" Take action a with ε-greedy policy based on Q(s, a; θ)
return: int
"""
assert isinstance(state, torch.Tensor)
sample = random.random()
if args.mode == 'train':
eps_... | f7c024ad50360725fcaeda1584bc34e1fe569fbe | 44,845 |
def playpos(context, songpos):
"""
*musicpd.org, playback section:*
``play [SONGPOS]``
Begins playing the playlist at song number ``SONGPOS``.
*Clarifications:*
- ``playid "-1"`` when playing is ignored.
- ``playid "-1"`` when paused resumes playback.
- ``playid "-1"`` when s... | c5826aac6eafb5019df05c0144a62fc3bad4618c | 44,846 |
def get_text(original, lang="en"):
""" Return a translation of text in the user's language.
@type original: unicode
"""
if original == u"":
return u""
global TRANSLATIONS
if not TRANSLATIONS:
init_i18n(BotConfig)
try:
return TRANSLATIONS[lang][original]
exc... | 39bc5c4b65be7f15a58fd077fce73e088c6abc34 | 44,847 |
def is_rectangle(coords):
"""
(tuple(tuple(float or int, float or int))) -> Boolean
Takes a tuple of (x, y) coordinate tuples. Returns True if the
coordinates represent a rectangle. Otherwise returns False.
"""
# look for four segments defined by five points
has_four_segments = (len(coords)... | 223f0edeb89d1c46f69e8404e29dcf1fc4effa23 | 44,848 |
def load_package_file(name: str) -> dict:
"""Load a yaml package file returning the represented dict.
Args:
name: base name of the package file
Returns:
A dict based on specified yaml packaged file
"""
return load_file(package_filename(name)) | 59fd28b257964fbf4f2718a08b79763e7fd5caf7 | 44,849 |
def convert_string_to_list(df, col, new_col):
"""Convert column from string to list format."""
fxn = lambda arr_string: [int(item) for item in str(arr_string).split(" ")]
mask = ~(df[col].isnull())
df[new_col] = df[col]
df.loc[mask, new_col] = df[mask][col].map(fxn)
return df | cc0e04fbe6b5523647ceb954fc4c17e78f2a8554 | 44,850 |
def set_circuit_ic_mrucc(n_qubit_system, nv, na, nc, DS, theta_list, ndim1):
""" Function
Author(s): Yuto Mori
"""
circuit = QuantumCircuit(n_qubit_system)
if DS:
icmr_ucc_singles(circuit, n_qubit_system, nv, na, nc, theta_list, 0)
icmr_ucc_doubles(circuit, n_qubit_system, nv, na, n... | fc5dec99696926412c14eeeb271fce5204c57cc5 | 44,851 |
from typing import Dict
from typing import List
def _parse_or_search(hint: Dict[str, str], attr_query: Dict[str, str]) -> Dict[str, str]:
"""Performs keyword analysis processing.
The search keyword is separated by OR and passed to the next process.
Args:
hint (dict[str, str]): Dictionary of attr... | fabea034450cb1b0af75ae2e6d84915792567b61 | 44,852 |
def tei_place_name(elem_text, attrib_ref="",
attrib_evidence=None, attrib_cert=None):
"""
| create TEI element <placeName> with given element text, @ref
| and (optional) @evidence and @cert
"""
place_name = etree.Element("placeName")
place_name.text = elem_text
add_attrib(... | c960f2f4ddaa2946dbc22a0fb3012938efadb1d7 | 44,853 |
def r_unit(p1, p2):
"""
r_unit(x, y) : Function computes the unit vector
between two points with coordinates p1(x1, y1) and p2(x2, y2)
"""
assert len(p1) == len(p2), 'locs must be the same shape.'
dx = []
for ii in range(len(p1)):
dx.append((p2[ii] - p1[ii]))
# Compute length... | 65293c0450c03aa3cb7cb1a350c989a185583bcc | 44,854 |
from pathlib import Path
def raw_directory(request):
"""Gets 'raw' directory with test datafiles"""
return Path(request.config.rootdir) / "tests/testdata/2020/6/raw" | efbdf7c5966578e2180ea4f9db0580420706ec23 | 44,855 |
def _update_cycle(self, cycle, scatter=False, **kwargs):
"""
Try to update the `~cycler.Cycler` without resetting it if it has not changed.
Also return keys that should be explicitly iterated over for commands that
otherwise don't use the property cycler (currently just scatter).
"""
# Get the o... | 992be19c591abcdd5eacca28a12d7d66c0d74bb8 | 44,856 |
def solution(dataset: list) -> int:
""" "there is a '\n' on the end of the first line but zip() will only go to the sortest length.
If both lines have '\n's then they will be equivalent and won't be counted"""
return sum(i != j for i, j in zip(*dataset)) | f17ef66d94af49a3eafdb20e9fa3aa2e251089e6 | 44,857 |
import os
def load_image(path_image, force_rgb=True):
""" load the image in value range (0, 1)
:param str path_image: path to the image
:param bool force_rgb: convert RGB image
:return ndarray: np.array<height, width, ch>
>>> img = np.random.random((50, 50))
>>> save_image('./test_image.jpg'... | d0315520456930761782661813b9694d44d9b5c1 | 44,858 |
def _GetFeatureCenters(num_groups, center_var, feature_dim):
"""Helper function to generate multivariate Normal feature centers.
Args:
num_groups: number of centers to generate.
center_var: diagonal element of the covariance matrix (off-diagonals = 0).
feature_dim: the dimension of each center.
Retur... | 15fb1fb359187413db8d74b2b3e4693b2f7e6e05 | 44,859 |
def async_pipe(*args, **kwargs):
"""A processor that asynchronously retrieves the current exchange rate
for a given currency pair.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. May... | 304498e836a0f0ff320cadd23a5b1a9094d484f9 | 44,860 |
def get_new_ticket():
"""Request a new upload ticket from Vimeo."""
response = _vimeo_request('vimeo.videos.upload.getTicket', 'POST',
upload_method='post')
if response['stat'] == 'fail':
err = response['err']
logger.error(u'Error retrieving upload ticket: <{cod... | d4dfa416b76b4089cbcd1f8c8cec8ea2fee010a9 | 44,861 |
def _tau(x, y):
"""Helper function for faster computation"""
n = len(x)
numerator = 0
for i in range(n-1):
for j in range(i+1, n):
sx = np.sign(x[i] - x[j])
sy = np.sign(y[i] - y[j])
numerator += sx * sy
nn = n * (n-1) / 2
return numerator / nn | a22370af1655a93c382db8219df302ba006ebe34 | 44,862 |
import functools
def get_session():
"""Make a cached session."""
settings.CACHE_PATH.mkdir(exist_ok=True, parents=True)
path = settings.CACHE_PATH.joinpath("http").as_posix()
session = CachedSession(cache_name=path, expire_after=settings.CACHE_EXPIRE)
session.headers.update(HEADERS)
# weird mo... | cdfc97575ff4a1a8980f471b067af2dc9de32d18 | 44,863 |
from re import M
def createSource(uid, payload):
"""
if id_source in payload, use that id, provided no record already exists, if not use new id
returns the id
"""
source = None
url = payload["url"]
page = parsePage(url)
if "id_source" in payload:
id = payload["id_source"]
... | 7c7cde562a9efb53083fdd361b7cb70e1f97d961 | 44,864 |
def add_atom_counts(df, struct_df):
"""Add atom counts (total and per type) to 'df'."""
pd.options.mode.chained_assignment = None
atoms_per_mol_df = struct_df.groupby(['molecule_name', 'atom']).count()
atoms_per_mol_map = atoms_per_mol_df['atom_index'].unstack().fillna(0)
atoms_per_mol_map = atoms_p... | 3531bf1bc16c30d8059d8f87e39a99b4a36dffc4 | 44,865 |
def nround(number: float, decimals=1):
"""Normalized round. nround(0.5) = 1 (unlike round())"""
number = str(number)
# if decimal places <= decimals
if len(number[number.index('.')::]) <= decimals + 1:
return float(number)
if number[-1] == '5':
number = number[:-1:] + '6'
return ... | de32f7f67dc966f21c657fa4287f1801d1723c21 | 44,866 |
def uniform_vector(shape, min_value=0, max_value=1, return_symbol=False):
"""
Generates a uniformly random tensor
:param shape: shape of the tensor
:param min_value: minimum possible value
:param max_value: maximum possible value (exclusive)
:param return_symbol: True if the result should be a ... | f19591aedbcb39021f8825df7d9eca93e89091e5 | 44,867 |
import collections
def format_seconds(seconds: float) -> str:
"""
Runtimes can be really long, due to exponentially growing configurational space, therefore those h
"""
minute = 60
hour = 60*minute
day = 24*hour
year = 365 * day
units = collections.OrderedDict([
(230000000*year... | 7b2bc9530fa0a14e105aad6d9076b0d2459ee364 | 44,868 |
import collections
def _get_tables_and_columns_in_schema(db, schema):
"""Returns a dict describing all tables and columns in `schema`."""
# Obtain names of tables in `schema`:
q = """
SELECT table_name FROM information_schema.tables
WHERE table_schema = '""" + schema + """'
ORDER BY tab... | 31b7c96e649e97819e92adffa1a05710a802ef37 | 44,869 |
def setup(obs_bp_path, binmixmat_path, mix_lmin, cov_path, pos_nl_path, she_nl_path, noise_lmin, input_lmax,
n_zbin):
"""
Load and precompute everything that is fixed throughout parameter space. This should be called once per analysis,
prior to any calls to execute.
Args:
obs_bp_path ... | c36c47adb0be29e72e7c10a3c6cdb0cc408af7f9 | 44,870 |
def mk_comorbidity(data_id, data): # measurement group 26
"""
transforms a c-comorbidity.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json form
:return: T... | 28214c2d492a9a9b8db06fc80073be741f042221 | 44,871 |
def raw_formatter(subtitles):
"""
Serialize a list of subtitles as a newline-delimited string.
"""
return ' '.join(text for (_rng, text) in subtitles) | 51109a9b29c30257e9e8fa50abf1e718374a521f | 44,872 |
def get_gids(features: dict, data_pd: pd.DataFrame):
"""
Parameters
----------
features : dict
Mapping genome -> feature
data_pd : pd.DataFrame
Feature table
Returns
-------
gid_features : dict
Mapping genome -> feature
"""
data_feats = set(data_pd.index... | cfc7137ea0d7ebbaa6494ea59010780001771bf0 | 44,873 |
def send_message(queue, message_body, message_attributes=None):
"""
Send a message to an SQS queue.
:param queue: The queue that receives the message.
:param message_body: The body text of the message.
:param message_attributes: Custom attributes of the message. These are key-value
... | 8619716dddfe015a1b1d0255092941c9b8e5bb2d | 44,874 |
def dict_diff(first, second):
"""
>>> dict_diff({'a':'b', 'c':1}, {'a':'c', 'c':1})
{'a': {'original':'b', 'changed': 'c'}
:type first: dict
:type second: dict
:rtype dict
"""
diff = {}
keys = set(first) | set(second)
for key in keys:
first_value = first.get(key)
... | 721556706b25888693dfb63c852fca14951890ea | 44,875 |
def struct_union_class_factory (class_name, class_dict):
"""Create a class type with name class_name, descended from
struct_or_union_base and object, to be a factory for instantiating
struct/union values."""
return new.classobj (class_name, (struct_or_union_base,),
class_dict) | 960941971d7bd87ceee0ce9bb3019b8557cc39f4 | 44,876 |
def normalize_images(mode="tr"):
"""
Normalizes all data related to either training or testing, this includes depth, B&W and raw matrixes.
The result is a 100x100 image of the face.
"""
#RGB images for light estimation
rgb_imgs, rgb_labels, rgb_names = manager.get_samples(mode,"rgb")
... | d0ca1de5875f0d0ecf37b2bb4441a130eeb257a8 | 44,877 |
def getNGramCounts(data, N):
"""Count the occurences of all N+1 grams in the
data. Outputs a dictionary mapping histories of length N
to a histogram dictionary."""
counts = defaultdict(dict)
for i in xrange(N,len(data)):
history = tuple(data[i-N:i])
obs = data[i]
if obs in counts[history]:
... | 8c50f36f60f5b46611ba5d094a1e9567fa5af3bd | 44,878 |
def csv_to_grid_02():
"""
:return: 20200201_20200215 csv to grid
"""
df = pd.read_csv('./csv_data/shortstay_20200201_20200215.csv', sep='\t')
df.columns = ['date', 'hour', 'grid_x', 'grid_y', 'index']
grid_h = []
date_h = []
for d in range(20200201, 20200216):
df_y = df[df.iloc[... | aa89b199b861c19ab35f348d7f71a350d7f2b50d | 44,879 |
def network_association_find_distinct_networks(context,
host_name,
session):
"""
returns unique networks from all network associations for given host
:param context: The context for building the data
:param hos... | d9eacce89b7a8da25d8af1fd66787251b3ffd2e2 | 44,880 |
import re
def add_space_after_commas(origString):
"""
Directives with arguements need spaces insert after commas.
"""
# space after a comma
newString = re.sub(',', ', ', origString)
return newString | 4ea62d9c792c9fd2f69d784e7f0c4bb972cd0a7c | 44,881 |
import requests
import json
def get_jwt_key(kid):
"""Get the public key via http."""
# from https://github.com/auth0-samples/auth0-python-api-samples/blob/master/00-Starter-Seed/server.py
# This is only as secure as our HTTP connection is secure ...
url = 'https://{}/.well-known/jwks.json'.format(gaet... | 19e16538b531a95420b6d3ec0e14b761e17d2588 | 44,882 |
def preprocess_tds(df):
"""
Parameters
----------
df : JSON to CSV converted time domain settings data.
Returns
-------
df_expanded : Restructured and reformatted tds data.
"""
#NEED DECIDE WHICH TIMESTAMP TO KEEP, TIMESTOP, OR TIMESTART
df = df.rename(columns={"timeStart": "tim... | 99023550fdf589ae28ca4d936611f786c08a4963 | 44,883 |
import os
from datetime import datetime
import sqlite3
import glob
def make_photometry_indexdb(framedir,
outfile,
frameglob='*_5.fits', # avoid ISM FITS products
photdir=None,
photext='text-fiphot',
... | 1f7c7f0c286e89a1700ca46eeb3dd36e19696384 | 44,884 |
from typing import List
def rr_interval_update(rpeak_temp1: List[DataPoint],
rr_ave: float,
min_size: int = 8) -> float:
"""
:param min_size: 8 last R-peaks are checked to compute the running rr interval average
:param rpeak_temp1: R peak locations
:param rr_... | f9f1b7d0d3bafcda71b209a50d3634a3329e7e7c | 44,885 |
def get_all_matching(cls, column_name, values):
"""Get all the instances of ``cls`` where the column called ``column_name``
matches one of the ``values`` provided.
Setup::
>>> from mock import Mock
>>> mock_cls = Mock()
>>> mock_cls.query.filter.return_value.a... | d74ddf983e33f63dfcaf1f335c91b35faa00a651 | 44,886 |
def assign_country_code(indices, cosmo_grid, projections, countries):
"""Assign the country codes on the gridcells indicated by indices.
Each gridcell gets assigned to code of the country with the most
area in the cell.
If for a given grid cell, no country is found (Ocean for example),
the country... | 43f84994df207d91294d8fb88b5e48555d13fb8e | 44,887 |
def new_figure_manager(num, *args, FigureClass=FigureSurface, **kwargs):
"""Create a new figure manager instance."""
# If a main-level app must be created, this (and
# new_figure_manager_given_figure) is the usual place to do it -- see
# backend_wx, backend_wxagg and backend_tkagg for examples. Not all... | c1a240e5bc1ea99cac913bf7c8072e6be3420067 | 44,888 |
def get_observation_photo_metadata(observation_id, access_token):
"""Attempt to scrape metadata from a photo info pages associated with an observation
(first photo only)
"""
print(f'Fetching observation {observation_id}')
obs = get_observation(observation_id)
photo_ids = [photo['id'] for photo i... | aa168922b154014f9974cb20d3629ffffe3eedd5 | 44,889 |
from typing import Union
from typing import Tuple
import os
def get_median_pulse_height(data_dir: str, fov: str, channel: str,
panel: Union[Tuple[float, float], pd.DataFrame] = (-0.3, 0.0),
time_res: float = 500e-6):
"""Retrieves median pulse intensity and m... | 0716f9366d58c97b06eafead232d40a938360ee4 | 44,890 |
import numpy
def _prepare_hdf5_write_value(array_like):
"""Cast a python object into a numpy array in a HDF5 friendly format.
:param array_like: Input dataset in a type that can be digested by
``numpy.array()`` (`str`, `list`, `numpy.ndarray`…)
:return: ``numpy.ndarray`` ready to be written as an... | 22764d763659c55bdc3e8d2c5e8b47697f595d47 | 44,891 |
def resize(img, rate, flg=cv2.INTER_NEAREST):
"""
画像サイズを変更する
[in] img: N倍にする画像
[in] rate: 倍率
[in] flg: N倍にする時のフラグ
[out] N倍にされた画像リスト
"""
if rate < 0:
logger.debug('resize({},{},{})'.format(
img.shape, rate, flg
))
return img
size = (int(img.shap... | aa5c060fff8fba52ab6e1de4094e17a2ee01c8f8 | 44,892 |
import six
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
... | 1aa2e2ed53a3b691e4b04a80257bfeb274f17d39 | 44,893 |
def get_day_of_week(year: int, month: int, day: int) -> int:
"""
0表示星期日,1-6表示星期一到星期六
"""
if month in (1, 2):
year -= 1
month += 12
return (
day
+ 2 * month
+ 3 * (month + 1) // 5
+ year
+ year // 4
- year // 100
+ year // 400
... | 77d0d74aeadf3e5148573673ffa29ca2abf99467 | 44,894 |
def AddDefaultLocationToListRequest(ref, args, req):
"""Python hook for yaml commands to wildcard the region in list requests."""
del ref
project = properties.VALUES.core.project.Get(required=True)
if hasattr(args, 'zone'):
location = args.region or args.zone or LOCATION_WILDCARD
else:
location = args... | fe8a4090b7579984cd8f8e5beaa58c2331ea9447 | 44,895 |
def normalize_model_parameter(model_parameter):
"""
Args:
model_parameter (str / dict): The parameter to convert.
Returns:
dict: If `model_parameter` is an ID (a string), it turns it into a model
dict. If it's already a dict, the `model_parameter` is returned as it
is. It re... | 70fe08167d5021dc1eaedf1dd07838b1e74452bf | 44,896 |
def _make_json_error(ex):
"""Return JSON error pages, not HTML!
Using a method suggested in http://flask.pocoo.org/snippets/83/, convert
all outgoing errors into JSON format.
"""
status_code = ex.code if isinstance(ex, HTTPException) else 500
response = jsonify(message=str(ex), code=statu... | a393510d0bafe7a9cd6c31234ea03866ceccce40 | 44,897 |
import os
def check_refcard(reffield):
"""
Checks wether the reference card was detected properly by comparing with the original reference
Input:
reffield: list of separated reference field of the detected reference card
Output:
ref_detected: Boolean, indicating, wether the card was ... | af7634b265c8c084625ff598d38757b1ee69b344 | 44,898 |
def householder_qr(A):
"""Computes the QR = A factorization of A using Householder reflections
Algorithm 5.2.1
"""
m, n = A.shape
A = householder_qr_packed(A)
QF , R = householder_split_qf_r(A)
Q = householder_ffm_backward_accum(QF, n)
return Q, R | de2c93080954d39119b2dd3adda78f28e3ddaf2c | 44,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.