content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def schema_to_entity_names(class_string):
"""
Mapping from classes path to entity names (used by the SQLA import/export)
This could have been written much simpler if it is only for SQLA but there
is an attempt the SQLA import/export code to be used for Django too.
"""
if class_string is None or ... | c7a6aabde74e3639f39b8e56ad5f82c6684dd2ba | 31,900 |
def csm_data(csm):
"""
Return the data field of the sparse variable.
"""
return csm_properties(csm)[0] | c0f6993f9fb005f5659539deb89b459039801ea1 | 31,901 |
def plot_hypnogram(resampled_hypno, cycles=None, label="", fig=None, ax=None):
"""
Plot an aesthetically pleasing hypnogram with optional cycle markers.
Parameters
----------
resampled_hypno : pd.DataFrame
Hypnogram resampled to epoch time units.
cycles : cycles : pd.DataFrame, optional... | 5c9be12d2aa9553d4a0084fd6734e5847eabcb57 | 31,902 |
from typing import Callable
def _scroll_screen(direction: int) -> Callable:
"""
Scroll to the next/prev group of the subset allocated to a specific screen.
This will rotate between e.g. 1->2->3->1 when the first screen is focussed.
"""
def _inner(qtile):
if len(qtile.screens) == 1:
... | e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a | 31,903 |
def _gate_altitude_data_factory(radar):
""" Return a function which returns the gate altitudes. """
def _gate_altitude_data():
""" The function which returns the gate altitudes. """
try:
return radar.altitude['data'] + radar.gate_z['data']
except ValueError:
retur... | 2a13cd44a6c50e6cbe7272e5628926aa4e76c71b | 31,904 |
from typing import Callable
import pathlib
def test_posix_message_queue_ee(
monkeypatch: pytest.MonkeyPatch,
is_dir: bool,
ee_support: bool,
engine: str,
generate_config: Callable,
):
"""Confirm error messages related to missing ``/dev/mqueue/`` and ``podman``.
Test using all possible com... | 7dddd24953261324b982da0ed7adbf632cf47779 | 31,905 |
import random
def RandHexColor(length=6):
"""Generates a random color using hexadecimal digits.
Args:
length: The number of hex digits in the color. Defaults to 6.
"""
result = [random.choice(HEX_DIGITS) for _ in range(length)]
return '#' + ''.join(result) | 7e196fa2b0666dc9aee67bcac83d0186812d9335 | 31,906 |
def _backtest2(prediction, price, acct_num,):
"""
Cal daiy return in % form
:param prediction:
:param price:
:param acct_num:
:return:
"""
# starting net val for trading account
mat = np.ones((acct_num, len(price)))
# liquidate or build position time
_idx = np.arange(len(pric... | 09e230945daf2f745b39523e5fba676e88629e09 | 31,907 |
def check_players(instance):
""" Checks to see if any of the starting players have left.
Args:
instance: The GameInstance model for this operation.
If a player has left the game, they are invited back and
a ValueError is raised.
Raises:
ValueError if a player has left the game.
"""
if len(insta... | d3a31f17cf5d3dee2e3fd075cea2e31d8a806952 | 31,908 |
def list_descendant(input_list):
"""Function that orders a list on descendant order using insertion sort
Args:
input_list ([type]): List with the values that we want to order
Returns:
list: The ordered list
"""
for i in range(1, len(input_list)):
j = i-1
next_elemen... | 8d2c452a513ccf67c4b179bf989fac5cc0108d09 | 31,909 |
from io import StringIO
import csv
async def chargify_invoices_csv(request: Request):
"""
Output Chargify invoices data.
"""
output = StringIO()
writer = csv.writer(output)
if not request.app['chargify_invoices_data']:
raise Exception("data not loaded yet")
writer.writerows(reque... | 5558b1b885f52edccc45a3819cab0353f84578fa | 31,910 |
def generate_base_reference(header,waveform="cosine",period=24,phase=0,width=12):
"""
This will generate a waveform with a given phase and period based on the header,
"""
ZTs = header
tpoints = np.zeros(len(ZTs))
coef = 2.0 * np.pi / float(period)
w = float(width) * coef
for i,ZT in... | b1178e07d9d628654902b6198acac1f791ba2064 | 31,911 |
def from_string(dlstr):
"""Factory method taking the string as appearing in FIELD input"""
input_key = dlstr.split()[0].lower()
for subcls in Interaction.__subclasses__():
if subcls.key == input_key:
return subcls.from_string(dlstr)
raise ValueError("No interaction available for ... | 875eb21e3773f47fdc77d3177a5f5253d0656546 | 31,912 |
def assign_cat(plugin):
"""Assigns `fonts` module keywords to the `Warp` plugin."""
meta = [
[KEYWORD_MATHCAL, "Script (or calligraphy): ๐โฌ๐๐ถ๐ท๐ธ๐๐๐ถ๐ท๐ธ"],
[KEYWORD_MATHBB, "Double-struck: ๐ธ๐นโ๐๐๐๐๐๐๐ธ๐น๐๐๐๐๐๐"],
[KEYWORD_MATHFRAK, "Fraktur: ๐๐
โญ๐๐๐ ๐๐
๐๐๐ "],
... | a1168624fa330ce19a3c8e78346bb7a893bb74e3 | 31,913 |
def config_func(config):
"""Configure the maintenance degrade notifier plugin"""
collectd.debug('%s config function' % PLUGIN)
for node in config.children:
key = node.key.lower()
val = node.values[0]
if key == 'port':
obj.port = int(val)
collectd.info("%s co... | 18d97c46e5a0a72cd4d4c45c2d43c8867f6f6d49 | 31,914 |
def get_holidays(startYear = 2018, endYear = 2025, countryCode = 'ZA'):
"""
Takes in a start and end date, and start and end year.
Produces a dataframe with a daily date and columns:
holiday - 'Y' for holiday
holidayName - name of the holiday if holiday is 'Y'
Returns a dataframe
"... | 6d7d83389bee2a83c6cc2d565f7c04b8d131555a | 31,915 |
import struct
def _testHeadCheckSum(header, tableDirectory):
"""
>>> header = dict(sfntVersion="OTTO")
>>> tableDirectory = [
... dict(tag="head", offset=100, length=100, checkSum=123, data="00000000"+struct.pack(">L", 925903070)),
... dict(tag="aaab", offset=200, length=100, checkSum=456)... | 4391c4d6dd6c3fedf99315a2d6995962251ca10f | 31,916 |
from model import MyLearner
import os
import logging
import time
from sys import path
import scipy
def scoring(argv):
"""
For each task, load and fit the Learner with the support set and evaluate
the submission performance with the query set.
A directory 'scoring_output' is created and contains a tx... | b9baccd716a4e2d01961b3eade801368b1683983 | 31,917 |
def svn_ra_do_status(*args):
"""
svn_ra_do_status(svn_ra_session_t session, svn_ra_reporter2_t reporter,
void report_baton, char status_target, svn_revnum_t revision,
svn_boolean_t recurse, svn_delta_editor_t status_editor,
void status_baton,
apr_pool_t pool) -> svn_error_t
... | 30d2d310bf2e047653c99ba4add68b3e2d07ee00 | 31,918 |
def clear_spaces(comp):
"""
'A + D' -> 'A+D'
"""
r = ''
for c in comp:
if c != ' ':
r += c
return r | cf8f28cf3633eb31d0c934dd9fc3035b3c1539f4 | 31,919 |
def _load_metabolite_linkouts(session, cobra_metabolite, metabolite_database_id):
"""Load new linkouts even ones that are pointing to previously created universal
metabolites.
The only scenario where we don't load a linkout is if the external id and
metabolite is exactly the same as a previous linkout.... | cda0a2fef212b091d39b45d2c8603eedc0f3b99a | 31,920 |
import random
def gen_ascii_captcha(symbols, length=6, max_h=10, noise_level=0, noise_char="."):
"""
Return a string of the specified length made by random symbols.
Print the ascii-art representation of it.
Example:
symbols = gen_ascii_symbols(input_file='ascii_symbols.txt',
... | b6f6f02bbbe3cbdfce007ea13e26836c21e20ef2 | 31,921 |
def get_app_name_cache_file(file_path: str) -> str:
"""Returns path to app name cache file"""
return f'{file_path}.{APP_NAME_FILE_EXTENSION}' | 16bdfe57e28eb5ea97e317fea98285af494ff0a9 | 31,922 |
def make_matrix_A(x_r, simulations, ฮพ, ฮ_t=1, ฮป=1):
"""
Equation (9) from paper
:param x_r: reference output
:param simulations: simulation outputs
:param t_ฮ: the intervals between each observation (series or constant)
:param ฮพ: squash control parameter
:return: the position/trend matr... | f4cb5e4dd5f79385ee4c945b4b7982200f2fa474 | 31,923 |
def generate_markov_content(content):
""" Generate Markov Content
Parameters
----------
content : str
Corpus to generate markov sequences from
"""
# Build the model.
text_model = markovify.Text(content, state_size=3)
# return randomly-generated sentence of no more than 280 chara... | c0503dca553712f8563c53676d3216f8206808ab | 31,924 |
def _quadratic_system_matrix(x):
"""
Create system matrix of a model with linear, quadratic and 1st-order 2-way interaction terms
Parameters
----------
x : array_like, shape (n, m)
Explanatory variable of n data points and m variables
Returns
-------
A : ndarray, shape (n, 1 + ... | 6d958cccaf5127fdc9f3fc6bcc472ceafd2947d6 | 31,925 |
def pytest_pycollect_makeitem(collector, name, obj):
"""A pytest hook to collect curio coroutines."""
if collector.funcnamefilter(name) and curio.meta.iscoroutinefunction(obj):
item = pytest.Function.from_parent(collector, name=name)
if "curio" in item.keywords:
return list(collector... | 95d18bc4575fc31c938dae6d487cf4cd058d89c4 | 31,926 |
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
... | db85099a0a1c19391ed8abc1ea2bcf4b867a93af | 31,927 |
def apply_Hc(C, A_L, A_R, Hlist):
"""
Compute C' via eq 16 of vumps paper (132 of tangent space methods).
"""
H, LH, RH = Hlist
A_Lstar = np.conj(A_L)
A_C = ct.rightmult(A_L, C)
to_contract = [A_C, A_Lstar, A_R, np.conj(A_R), H]
idxs = [(4, 1, 3),
(6, 1, -1),
(5, ... | ae43b1fe1484ee70b2245474f03a3e9676b44929 | 31,928 |
import ipywidgets as ipyw
def make_basic_gui(container):
"""Create a basic GUI layout.
Parameters
----------
container : RenderContainer
Returns
-------
ipywidgets.GridspecLayout
"""
element_controls = [
ipyw.HTML(value="<b>Elements</b>", layout=ipyw.Layout(align_self="... | 5a01c70304910b1b20193c507a348ec90dd6a514 | 31,929 |
import traceback, functools
def multiprocessing_traceback(func):
"""A decorator for formatting exception traceback into a string to aid in
debugging when using the ``multiprocessing`` module."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
... | 078a086574c003f62e332063ef6c3475d9846e20 | 31,930 |
import sysconfig
def shared_libraries_are_available():
"""
check if python was built with --enable-shared or if the system python (with
dynamically linked libs) is in use
default to guessing that the shared libs are not available (be conservative)
"""
# if detection isn't possible because sysc... | 65306cc5bda77f07cc6dc118637d3fec7cae47c0 | 31,931 |
def parse_middleware_mkdir_response(mkdir_resp):
"""
Parse a response from RpcMiddlewareMkdir.
Returns (mtime in nanoseconds, inode number, number of writes)
"""
return (_ctime_or_mtime(mkdir_resp),
mkdir_resp["InodeNumber"],
mkdir_resp["NumWrites"]) | 17336084895bbad579785e7e918674e4367f05c6 | 31,932 |
import torch
def decorate_batch(batch, device='cpu'):
"""Decorate the input batch with a proper device
Parameters
----------
batch : {[torch.Tensor | list | dict]}
The input batch, where the list or dict can contain non-tensor objects
device: str, optional
'cpu' or 'cuda'
... | a0bd4a5dff0b5cf6e304aede678c5d56cb93d1dd | 31,933 |
import yaml
def get_config(filename: str = CONFIG_FILENAME) -> dict:
"""
Get config as a dictionary
Parameters
----------
filename: str
The filename with all the configuration
Returns
-------
dict
A dictionary containing all the entries from the config YAML
"""
... | 79572679204c53f6ecdf91a120bb6a08ced9afd1 | 31,934 |
def partition_trace(vtrace):
"""partition a trace based on its types """
partition = {}
for v in vtrace:
vty = get_vt_type(v)
if vty not in partition:
partition[vty] = []
partition[vty].append(v)
return partition | 6fa30f6180a122cc6cb74bf7dcdfbbfa2b4a8627 | 31,935 |
def test_text_justify_bottom_right_and_top_left(region, projection):
"""
Print text justified at bottom right and top left.
"""
fig = Figure()
fig.text(
region=region,
projection=projection,
x=1.2,
y=0.2,
text="text justified bottom right",
justify="BR... | a8b1735e002f2c310226142bfcbde9bd1fea9f95 | 31,936 |
from pathlib import Path
def get_bench(
lx: tuple[int, int, int], data_dir: Path, tests: list[str], comp_lvls: list[int]
) -> dict[str, pd.DataFrame]:
"""get writing benchmark HDF5 files to pandas dataframe"""
data = {
"write_dr": pd.DataFrame(index=comp_lvls, columns=tests),
"read_dr": p... | d135f58a3793cf161f338118060b16106bd6c96a | 31,937 |
def custom_token(deploy_tester_contract, custom_token_params):
"""Deploy CustomToken contract"""
return deploy_tester_contract(
CONTRACT_CUSTOM_TOKEN,
[],
custom_token_params
) | 175f8b49545e422ae691631b361f7bb62e9f62f5 | 31,938 |
def parse_values(reports, criteria1, criteria2, steps, crit1_name, crit2_name, first=False, cpus=1):
"""
Description: Parse the 'reports' and create a sorted array
of size n_structs following the criteria chosen by the user.
"""
info_reports = [ retrieve_report_data(report) for report i... | 9d22756ecdfe50f7e5563a4fa855ddb5a3a4cd21 | 31,939 |
import io
def read_bytes(n: int, reader: io.IOBase) -> bytes:
"""
Reads the specified number of bytes from the reader. It raises an
`EOFError` if the specified number of bytes is not available.
Parameters:
- `n`: The number of bytes to read;
- `reader`: The reader;
Returns the bytes rea... | bb3d00fc7667839864f4104a94a26e682f058fdc | 31,940 |
import json
def _format_full_payload(_json_field_name, _json_payload, _files_payload):
"""This function formats the full payload for a ``multipart/form-data`` API request including attachments.
.. versionadded:: 2.8.0
:param _json_field_name: The name of the highest-level JSON field used in the JSON pay... | feacd27be3e6fcbd33f77fa755be513a93e3cdeb | 31,941 |
def convert_rows (rows):
"""Read a two-element tuple from a string.
rows should be a string containing two integers separated by a
comma, blank, or colon. The numbers may be enclosed in parentheses
or brackets, but this is not necessary. Note: the row numbers
are one indexed and inclusive, e.g. rows = "480, 544"... | e2d5a8e68459d6cb7a2fa044baa6d25dab46511c | 31,942 |
import numpy
def prepare_data(hsi_img=None, gnd_img=None, window_size=7, n_principle=3,
batch_size=50, merge=False, ratio=[6, 2, 2]):
"""
Process the data from file path to splited train-valid-test sets; Binded in
dataset_spectral and dataset_spatial respectively.
Parameters
... | b54d174cdfc99bc1ba74e7b8cc09661d6bf18f9c | 31,943 |
import os
def make_output_dirs(model_name, dat, let):
"""
Generate output directories of the run corresponding to
- model_name
- dat
- let
0 - output_dir
1 - samples_output_dir
2 - enkf_output_dir
"""
output_dir = (os.environ['HOME'] + "/shematOutputDir/" + model_name +
... | 2804bff3d1da0aae85e133e985bb526859116388 | 31,944 |
def mvresnet152(**kwargs):
"""Constructs a MVResNet-101 model.
"""
model = MVResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
return model | 86b579e5f3a80b87677d0aa0c075d4e3eeb81d46 | 31,945 |
def _wer_compute(errors: Tensor, total: Tensor) -> Tensor:
"""Compute the word error rate.
Args:
errors: Number of edit operations to get from the reference to the prediction, summed over all samples
total: Number of words overall references
Returns:
Word error rate score
"""
... | c7a2ea912e27d1867f771b135cb0c8bd9fd7729e | 31,946 |
def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | 24fa3b52803f1cebae246be8b3988b9568965e6d | 31,947 |
from typing import Any
from typing import Union
import torch
def tocuda(vars: Any) -> Union[str, torch.Tensor]:
"""Convert tensor to tensor on GPU"""
if isinstance(vars, torch.Tensor):
return vars.cuda()
elif isinstance(vars, str):
return vars
else:
raise NotImplementedError("i... | b7be275fe7e909fa54fc62ed9e5fbe61d3ff4863 | 31,948 |
import logging
def get_logger():
"""
Returns:
logging.Logger
"""
logger = logging.getLogger('ds-toolkit')
if not len(logger.handlers):
logger.setLevel(logging.DEBUG)
logger.addHandler(_get_console_handler())
return logger | 68afb0f31c24e72edf7539d51efc0985423115a6 | 31,949 |
from typing import Union
from typing import NewType
from typing import Any
from typing import Tuple
from typing import Optional
def _maybe_node_for_newtype(
typ: Union[NewType, Any],
overrides: OverridesT,
memo: MemoType,
forward_refs: ForwardRefs
) -> Tuple[Optional[schema.nodes.SchemaNode], MemoType... | 5cce0197a44ebc2517c509211746a996d6e0235c | 31,950 |
def read_slug(filename):
"""
Returns the test slug found in specified filename.
"""
with open(filename, "r") as f:
slug = f.read()
return slug | e1882d856e70efa8555dab9e422a1348594ffcaf | 31,951 |
def boolean_value(value):
"""Given a Value, returns whether the object is statically known to be truthy.
Returns None if its truth value cannot be determined.
"""
if isinstance(value, KnownValue):
try:
return bool(value.val)
except Exception:
# Its __bool__ thre... | c4f971b474943f44c2d5b85def14d91901244e72 | 31,952 |
import sys
def _Import(name):
"""Import a module or package if it is not already imported."""
module = sys.modules.get(name, None)
if module is not None:
return module
return import_module(name, None) | 86f65c5e523eb745fe6ffbf122d2e7da34fd223b | 31,953 |
import os
import tqdm
import math
def bin_sparse(X, file, scan_names, bins, max_parent_mass = 850, verbose=False, window_filter=True, filter_window_size=50, filter_window_retain=3):
""" Parses and bins a single MGF file into a matrix that holds the charge intensities of all the spectra
Args:
X: Scipy... | 6fda1ea76fcbdcc032d5a9b6fca05c1a82e0181a | 31,954 |
import os
def ls_img_sequence(path):
"""Listing all available coherent image sequence from path
Arguments:
path (str): A nuke's node object
Returns:
data (dict): with nuke formated path and frameranges
"""
file = os.path.basename(path)
dirpath = os.path.dirname(path)
base... | 5b98496390d94ee96f18769922526d21e136da03 | 31,955 |
def _convert_to_dict(tracked_dict):
"""
Recursively convert a Pony ORM TrackedDict to a normal Python dict
"""
if not isinstance(tracked_dict, orm.ormtypes.TrackedDict):
return tracked_dict
return {k: _convert_to_dict(v) for k, v in tracked_dict.items()} | 40a31ebc96f3010618c3b091e2618d2d6809b82d | 31,956 |
def sky_coords(cluster):
"""Get the sky coordinates of every star in the cluster
Parameters
----------
cluster : class
StarCluster
Returns
-------
ra,dec,d0,pmra,pmdec,vr0 : float
on-sky positions and velocities of cluster stars
History
-------
2018 - Writt... | 26a17879a6c2cc84dbf250d9250014f8554fbb9e | 31,957 |
import time
import requests
import json
def macro_cons_silver_volume():
"""
ๅ
จ็ๆๅคง็ฝ้ถ ETF--iShares Silver Trust ๆไปๆฅๅ, ๆฐๆฎๅบ้ดไป 20060429-่ณไป
:return: pandas.Series
"""
t = time.time()
res = requests.get(
JS_CONS_SLIVER_ETF_URL.format(
str(int(round(t * 1000))), str(int(round(t * 10... | 1a806095e935ea5e6065dec4dc412775ebaa2b22 | 31,958 |
import os
def scan_files(prefix):
""" Gets all words from all files ending in the specified prefix and returns
them as a list.
"""
files = ['/'.join([data.DATA_DIR, f])
for f in os.listdir(data.DATA_DIR) if f.startswith(prefix)]
words = []
for f in files:
with open(f,... | 9861de09940cf437991a66161813f9402b3325c5 | 31,959 |
import numpy as np
from .model_store import get_model_file
import os
def get_jasper(version,
use_dw=False,
use_dr=False,
bn_epsilon=1e-3,
vocabulary=None,
model_name=None,
pretrained=False,
ctx=cpu(),
... | c393894b9c4b0d02289eeeee8f1c027a122ceec3 | 31,960 |
def preprocess_img(img):
"""Preprocessing function for images."""
return img/255 | 11651a809288d5c3aa776b318099b7eb750d28ec | 31,961 |
from typing import OrderedDict
import os
def test_pdbqt():
"""RDKit PDBQT writer and reader"""
mol = next(oddt.toolkit.readfile('sdf', xiap_actives))
mol2 = oddt.toolkit.readstring('pdbqt', mol.write('pdbqt'))
assert mol.title == mol2.title
# test loop breaks in DFS algorithm
mol = oddt.toolk... | 6b01a554b7421b5ac2d7b744eb5371aa5268418b | 31,962 |
def get_apitools_metadata_from_url(cloud_url):
"""Takes storage_url.CloudUrl and returns appropriate Apitools message."""
messages = apis.GetMessagesModule('storage', 'v1')
if cloud_url.is_bucket():
return messages.Bucket(name=cloud_url.bucket_name)
elif cloud_url.is_object():
generation = int(cloud_url... | c8ec4dd6c6019467129c03d367c6dd58963d334f | 31,963 |
def branch(ref=None):
"""Return the name of the current git branch."""
ref = ref or "HEAD"
return local("git symbolic-ref %s 2>/dev/null | awk -F/ {'print $NF'}"
% ref, capture=True) | 8597a9b38f2a6372aa9dba911163bdb44d4db1f2 | 31,964 |
def fit_anis(celldmsx, Ex, ibrav=4, out=False, type="quadratic", ylabel="Etot"):
"""
An auxiliary function for handling fitting in the anisotropic case
"""
if out:
print (type+" fit")
if type=="quadratic":
a, chi = fit_quadratic(celldmsx, Ex, ibrav, out, ylabel)
eli... | 25f88d62876696d1d9e95e1c11c5b687a59cea7b | 31,965 |
def solicitacao_incluir(discente, sugestao_turma):
"""
Inclui uma Solicitaรงรฃo de interesse do Discente na Sugestรฃo de Turma.
:param discente: Um objeto da classe @Discente
:param sugestao_turma: Um objeto da classe @SugestaoTurma
:return: Um objeto da classe @SolicitacaoTurma e um booleano informand... | f346058717a62d6007ea99347043512f4770950d | 31,966 |
def _evolve_trotter_gates(psi,
layers,
step_size,
num_steps,
euclidean=False,
callback=None):
"""Evolve an initial wavefunction psi via gates specified in `layers`.
If the evolution is... | e1319a01434b0de0c4d90db3881a5a1e3b22d491 | 31,967 |
import os
def load_worksheet(
filename,
sheet=None,
worksheet=0,
skip_rows=0,
csv_delimiter=DEFAULT_CSV_DELIMITER,
ext=None,
):
"""
Load a worksheet from a supported file format
:param filename: File to be loaded
:type filename: str
:param sheet: If not None, load the data... | ab2e27729dfdb3ee2b0dfda2c837f4f7a62b9304 | 31,968 |
import os
def _get_next_traj_id(root_data_dir='data'):
""" Resolve what is the next trajectory number """
if not os.path.exists(os.path.join(root_data_dir, 'screens')):
return 0
return 1 + max([
int(x) for x in os.listdir(os.path.join(root_data_dir, 'screens'))
]) | d321af4c90d9de78942e2526c0720b3019fff479 | 31,969 |
def get_user(email):
""" Sometimes user account is setup using @gmail.com domain,
but android phone says @googlemail.com and vice versa
"""
try:
if 'googlemail' in email or 'gmail' in email:
uname = email.partition('@')[0]
users = User.objects.filter(Q(email=uname+'@googl... | 11ce9dddcb2896010cd07c5f95859680e95e7ec4 | 31,970 |
from tvm.tir.analysis import _ffi_api as _analysis_ffi_api
import logging
def test_tuning_gpu_inherits_pass_context(target, dev):
"""Autotvm tuner inherits PassContexts but also adds a gpu verification pass by default.
Test that using PassContext inherits passes properly but also runs gpu verification pass.
... | 8c62f18293b24601a8ee5296f2e4984bed7c20e4 | 31,971 |
def make_scae(config):
"""Builds the SCAE."""
# return: model ๅบ่ฏฅๆฏๆดไธช็่ฆ่ฎญ็ป็modelไบๅง
# ่ฟไธชๅฅฝๅๆฏ่ฆtransform ่ฎญ็ป้
# canvas & template size ้ฝๆไปไน็จๅข ๅจ่ฟ้?
img_size = [config.canvas_size] * 2
template_size = [config.template_size] * 2
# ่ฟไธชๅชๆฏpart encoder็ไธ้จๅ, ็จ็ๆฏๅท็งฏ,็ดๆฅๅฐฑๆฏ4ไธชๅท็งฏๅฑไบ paddingๅฏไปฅ่ชๅจ, snt NB!!
'''
Sequential(
(... | 415ab9d12806f250fa786872b0a3a2d6ecd82f72 | 31,972 |
import requests
def get_materialization_versions(dataset_name, materialization_endpoint=None):
""" Gets materialization versions with timestamps """
if materialization_endpoint is None:
materialization_endpoint = analysisdatalink.materialization_endpoint
url = '{}/api/dataset/{}'.format(mater... | 32d6976e864a9926f6b2e51ec7a65c33e2b86832 | 31,973 |
import scipy
def WilcoxonRankSum(tpms):
"""May be very slow for large datasets."""
wrs = tpms[['SMTSD', 'ENSG']].copy().drop_duplicates().sort_values(by=['SMTSD', 'ENSG'])
wrs.reset_index(drop=True, inplace=True)
wrs['stat'] = pd.Series(dtype=float)
wrs['pval'] = pd.Series(dtype=float)
for smtsd in wrs.SM... | 89733a49bc8e0e0a1d492b21ad6310746e4d23fe | 31,974 |
def filter_image(image, filter_DFT):
"""
Just takes the DFT of a filter and applies the filter to an image
This may optionally pad the image so as to match the number of samples in the
filter DFT. We should make sure this is greater than or equal to the size of
the image.
"""
assert image.dtype == 'float... | 0c6d2e46640fbfd7757231eb398c90fea0ca0a65 | 31,975 |
import traceback
import sys
def create_database(server, db_name, encoding=None):
"""This function used to create database and returns the database id"""
db_id = ''
try:
connection = get_db_connection(
server['db'],
server['username'],
server['db_password'],
... | c4825f4bd0d898cdf4889ab09f14d98b58e909cc | 31,976 |
def _create_diff_matrix(n, order=1):
"""Creates n x n matrix subtracting adjacent vector elements
Example:
>>> print(_create_diff_matrix(4, order=1))
[[ 1 -1 0 0]
[ 0 1 -1 0]
[ 0 0 1 -1]]
>>> print(_create_diff_matrix(4, order=2))
[[ 1 -1 0 0]
... | 0d241d37075e37d342e2601fc307277dd92b180f | 31,977 |
def fourier_frequencies_from_times(times):
"""
Calculates the Fourier frequencies from a set of times. These frequencies are in 1/units, where
`units` is the units of time in `times`. Note that if the times are not exactly equally spaced,
then the Fourier frequencies are ill-defined, and this returns th... | 4976483355af4652eafe28c955b2ca847bc140af | 31,978 |
import copy
def fission(candidate_seed, pop, n, max_seed_area):
"""
In fusion, we use the convention of putting one seed on
the left and the other seed on the right, before we fuse
the two seeds. In fission, we assume that fission will
split the left part from the right part. Find the most
sparse colum... | f056c90f68f91ba1b3f81f76c3599f8f7a3aee51 | 31,979 |
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
param:
box: tuple or array, shifted to the origin (i. e. width and height)
clusters: numpy array of shape (k, 2) where k is the number of clusters
return:
numpy array of shape (... | d181cf7234602f4b3f7d5b6c0a25cd9e15c2b5ed | 31,980 |
def munge_av_status(av_statuses):
"""Truncate and lowercase availability_status"""
return [a[20:].lower() for a in av_statuses] | 52a00fc6733015c3618a2a394371ea9387d92fc0 | 31,981 |
def cdf(vals, reverse=False):
"""Computes the CDF of a list of values"""
vals = sorted(vals, reverse=reverse)
tot = float(len(vals))
x = []
y = []
for i, x2 in enumerate(vals):
x.append(x2)
y.append((i+1) / tot)
return x, y | 3cc64dcb8876f7620f02da873e29569e77477823 | 31,982 |
def user_document_verification(request, document_id):
"""Display user's document information request.
Args:
request: URL request
document_request_id: document ID in firebase
Returns:
Render user document verification view.
"""
# Document Data
document_ref = db.collection("d... | 6610d21e1a0e35aaf3203814c20687a5b48e5d96 | 31,983 |
import os
def get_not_repeated_file_name(path_with_file):
"""
Returns file_name if file_name does not exist. If it exists, it appends an underscore until
this new file name does not exist, returning it. For example if "/home/mine/file.txt" exists,
it will return "/home/mine/_file.txt".
@para... | 7da491a3cd0261d99142905e4e7d2690c3be0d06 | 31,984 |
def attr(name, thing=word, subtype=None):
"""Generate an Attribute with that name, referencing the thing.
Instance variables:
Class Attribute class generated by namedtuple()
"""
# if __debug__:
# if isinstance(thing, (tuple, list)):
# warnings.warn(type(thing).__name__... | 488f1aef2b350ae702652dff9e2c5decc21dd271 | 31,985 |
def bulk_records(
name: str,
bulk: TextClassificationBulkData,
common_params: CommonTaskQueryParams = Depends(),
service: TextClassificationService = Depends(
TextClassificationService.get_instance
),
datasets: DatasetsService = Depends(DatasetsService.get_instance),
current_user: Us... | aa82e779b5bd9286bd1b456f151f3b0679b3582b | 31,986 |
def environment_list(p_engine, p_username, format, envname):
"""
Print list of environments
param1: p_engine: engine name from configuration
param2: format: output format
param3: envname: environemnt name to list, all if None
return 0 if environment found
"""
ret = 0
enginelist = ... | bf1ca059f0fd919445df4ee931450c7a07619707 | 31,987 |
def loss(logits, labels, weight_decay_factor, class_weights = None):
"""
Total loss:
----------
Args:
logits: Tensor, predicted [batch_size * height * width, num_classes]
labels: Tensor, ground truth [batch_size, height, width, 1]
weight_decay_factor: float, factor with which... | 91fae015aeb5bed4c73cf2aa4d6e62a5c1d4580c | 31,988 |
def negative(num):
"""assumes num is a numeric
returns a boolean, True if num is negative, else False"""
return num < 0 | dc8b789b6dbd4d158482de6d4af26f48f9e8cc5b | 31,989 |
def readSudokus(filename):
"""
Returns the n first sudokus of the file with given name
"""
f = open(filename)
res = None
txt = f.readline().strip()
if txt != "":
res = [[int(txt[i + j * 9]) for i in range(9)] for j in range(9)]
f.close()
return np.array(res) | 564da1dd1fc035ec692986eaa8955985acd5b1ce | 31,990 |
from flask.cli import ScriptInfo
def script_info(base_app):
"""Get ScriptInfo object for testing a CLI command.
Scope: module
.. code-block:: python
def test_cmd(script_info):
runner = CliRunner()
result = runner.invoke(mycmd, obj=script_info)
assert result.e... | 5c5298fcd816538e4890a1d46d51aea6d73702e6 | 31,991 |
def measured_points(idf, return_periods, interim_results=None, max_duration=None):
"""
get the calculation results of the rainfall with u and w without the estimation of the formulation
Args:
idf (IntensityDurationFrequencyAnalyse): idf class
return_periods (float | np.array | list | pd.Ser... | ba0e1cbddf6fd7e23abbfba4954683ada69cea2f | 31,992 |
def get_charpixel():
""" Render a single charpixel """
if options.table == 'input':
c = getch()
if c in ['\n','\t']:
print(c)
else:
c = choice( CHARTABLES[ options.table ] )
return c.encode('utf-8') | deb0475dac66c10c1d9edea45cce1cedffbafd1d | 31,993 |
def test_custom_fixer():
""" Test custom ParseFixer
Verify that read_csv uses custom ParseFixer
"""
class fix_pi(ParseFixer):
def __init__(self):
super().__init__()
# augment existing method, simple fix float
def fix_illegal_cell_value(self, vtype, value):
... | c137e190dffef686b04b2f515c6c65ecd2d50879 | 31,994 |
def context_factory(policy, name):
"""Factory function for creating context objects."""
if not isinstance(name, qpol.qpol_context_t):
raise TypeError("Contexts cannot be looked-up.")
return Context(policy, name) | a528978876bdbaa0d2e249f70a056d49fc894349 | 31,995 |
import email
def decode_mail_header(value, default_charset='us-ascii'):
"""Decode a header value into a unicode string."""
try:
headers = decode_header(value)
except email.errors.HeaderParseError:
return value.encode(default_charset, 'replace').decode(default_charset)
else:
for... | 657a45da883bd35d99642af7cfa1ff5ed9200fbe | 31,996 |
def xyz2xyzr(xyz: np.ndarray, *,
axis: int=None,
illuminant: Illuminant=get_default_illuminant(),
observer: Observer=get_default_observer()) -> np.ndarray:
"""
Convert XYZ to normalized XYZ reflectance
:param xyz: the raw xyz values
:param axis: the axis that the X... | 76e0b3c095ac48a44b31349efe259b70a427cfc0 | 31,997 |
import time
def last_updated(a):
"""
Check the time since file was last updated.
"""
return time.time() - op.getmtime(a) | 653eb5b68e00c57165b413d1de1ed0d8afee41f0 | 31,998 |
import functools
def lstm_acd_decomposition(inp, model):
"""
inp: tf.Tensor(dtype=np.int32, shape=(1, -1)) tokenized input
model: tf.keras.Model or equivalent
"""
l = inp.numpy().size
e, k, rk, b, dw, db = model.weights
embed_inp = tf.nn.embedding_lookup(params=e, ids=inp)
return ac... | 51d55fe155290b3ec1bc7f3b67b562e4b6ae4c23 | 31,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.