content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_host(environ, trusted_hosts=None):
"""Return the host for the given WSGI environment. This first checks
the ``Host`` header. If it's not present, then ``SERVER_NAME`` and
``SERVER_PORT`` are used. The host will only contain the port if it
is different than the standard port for the protocol.
... | 5,292,700 |
def feature_engineering(df, ft_requests, idcol):
"""
The Feature Engineering module needs FeatureTools installed to work.
So please do "pip install featuretools" before trying out this module.
It takes a given data set, df and adds features based on the requet types in
ft_requests which can be 'add'... | 5,292,701 |
def test_path_old_new_move():
"""test path move and compare to old style computation"""
n = 100
s_pos = (0, 0, 0)
# path style code translation
pm1 = Cylinder((0, 0, 1000), (3, 3), position=(-5, 0, 3))
pm1.move([(x, 0, 0) for x in np.linspace(0, 10, 100)], start=-1)
B1 = pm1.getB(s_pos)
... | 5,292,702 |
def rss(type: RSSType):
"""Get the RSS feed url for the entire site depending on which feed type you want
Parameters
-----------
type : RSSType
The type of feed you desire to get
Returns
--------
str
URL for the feed type
"""
return f"https://rss.moddb.com/{type.nam... | 5,292,703 |
def assert_allclose(actual: numpy.ndarray, desired: Tuple[int, numpy.float64]):
"""
usage.scipy: 1
"""
... | 5,292,704 |
def test_get_access_token_error():
"""
Error code should be returned when getting an access token fails.
"""
# Arrange
httpretty.register_uri(
httpretty.POST,
settings.TOKEN_PROVIDER_ENDPOINT,
body='{"error_description": "We\'re boned."}',
context_type="application... | 5,292,705 |
def explode_df(df, schema):
"""
Transform ouroborous DR1/DR2 extracts into unified vote table
Designed for Ouroborous raw data extract, after removing rare answers.
Args:
df (pd.DataFrame): rows by classification, columns by question (e.g. 'decals-0'), values by answer (e.g. 'a-0')
schem... | 5,292,706 |
def fold(ts, period, bins, subints=None):
"""
Fold TimeSeries at given period
Parameters
----------
ts : TimeSeries
Input time series to fold
period : float
Period in seconds
bins : int
Number of phase bins
subints : int or None, optional
Number of desire... | 5,292,707 |
def is_image(im, cv2_ok=True, pil_ok=True):
""" Check if the input is a valid image or not
Args:
im: image
cv2_ok (bool, optional): check cv2. Defaults to True.
pil_ok (bool, optional): check pil. Defaults to True.
"""
assert cv2_ok or pil_ok
if cv2_ok:
flag_cv2 = is... | 5,292,708 |
def get_ois_using_template(template,
type_ois: TypeOis, rp: Qcf.RecPay, notional: float, start_date: Qcf.QCDate,
tenor: Qcf.Tenor, fixed_rate_value: float, spread: float, gearing: float):
"""
"""
template_dict = template[type_ois]
meses = tenor.get_y... | 5,292,709 |
def get_versions(
dependency: str,
granularity: str = "minor",
# ascending: bool = False, limit: Optional[int] = None,
# allow_prerelease: bool = False,
) -> Iterable[str]:
"""Yield all versions of `dependency` considering version constraints
Args:
dependency: the name of the dependency
... | 5,292,710 |
def insert_dummy_atom(zma, x_key, x_key_mat, x_name_mat, x_val_dct):
""" insert a dummy atom at a given position in the z-matrix
"""
syms = symbols(zma)
key_mat = numpy.array(key_matrix(zma))
name_mat = numpy.array(name_matrix(zma))
# check whether x_name_mat overlaps with name_mat
natms =... | 5,292,711 |
def prepare_plane_to_curved_flat_arbitrary(k, rs_support, num_pointss, z, xo, yo, qs_center=(0, 0), kz_mode='local_xy'):
"""Prepare propagator from uniformly sampled plane to arbitrarily sampled curved surface.
The zero-th order component (k_z) is included (arbitrarily) in Px.
Args:
k (scalar): Wav... | 5,292,712 |
def deprecated_alias(**aliases):
"""
A deprecation decorator constructor.
Parameters
----------
aliases: str
The key-value pairs of mapping old --> new argument names of a
function.
Returns
-------
callable
A decorator for the specific mapping of deprecated argu... | 5,292,713 |
def get_asset_encryption_key(account_name: Optional[str] = None,
asset_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAssetEncryptionKeyResult:
"... | 5,292,714 |
def _escapeWildCard(klassContent):
"""
>>> _escapeWildCard('')
''
>>> _escapeWildCard(':*')
''
>>> _escapeWildCard(':Object')
':Object'
"""
return klassContent.replace(':*', '') | 5,292,715 |
def convert_xyz_to_rgb(x, y, z, *, space, reference, clip=True):
"""
Converts give XYZ values to RGB (0-1).
Note: For general purpose use, directly use conversion functions like
`xyz_to_srgb`, `xyz_to_adobe_rgb` etc. instead using this function.
:param x: X
:param y: Y
:param z: Z
:par... | 5,292,716 |
def _show_graph() -> None:
"""Function that sets the plt configuration then calls matplotlib.show().
plt configuration is set from _GLOBAL_GRAPH_CONFIGS
"""
_configure_plot(_GLOBAL_GRAPH_CONFIGS)
plt.show()
return None | 5,292,717 |
def pr3_search(bursts, obs_mjds, obs_durations, pmin=1.57, pmax=62.8, nbins=8, pres = None, nopbar=False):
"""
Periodicity search using Pearson chi square method used in The CHIME/FRB Collaboration et al 2020
:param bursts: List or array of burst MJDs
:param obs_mjds: Start MJDs of observations
:pa... | 5,292,718 |
def get_df(path):
""" Apply raw data to pandas DataFrame. """
idx = 0
df = {}
length = len(gzip.open(path, 'rb').readlines())
g = gzip.open(path, 'rb')
# progress = g
progress = tqdm(g, desc='transforming', total=length, leave=False, unit_scale=True)
for line in progress:
# if i... | 5,292,719 |
def width_required_for_column(header, values):
"""
Spaced needed to display column in a single line, accounts for the two
extra characters that the tabulate package adds to the header when the
content is too short
"""
values_max = -1 if not values else max(len(str(v)) for v in values)
return... | 5,292,720 |
def test_get_balances(
rotkehlchen_api_server,
ethereum_accounts, # pylint: disable=unused-argument
start_with_valid_premium,
):
"""Check querying the uniswap balances endpoint works. Uses real data
Checks the functionality both for the graph queries (when premium) and simple
oncha... | 5,292,721 |
def get_coinbase_stats(access_token, currency, period):
"""
Get historical investment data across all accounts.
"""
client = OAuthClient(access_token, access_token)
cache_date = datetime.datetime.date(datetime.datetime.now())
user, accounts = _get_user_and_accounts(access_token, cache_date)
... | 5,292,722 |
def setXformManip(*args, **kwargs):
"""
This command changes some of the settings of the xform manip, to control its appearance. In query mode, return type is
based on queried flag.
Flags:
- showUnits : su (bool) [query]
If set to true, the xform manip displ... | 5,292,723 |
def build(context, nocache=False, forcerm=False, hide=False): # pylint: disable=too-many-arguments
"""Build a Docker image.
Args:
context (obj): Used to run specific commands
nocache (bool): Do not use cache when building the image
forcerm (bool): Always remove intermediate containers
... | 5,292,724 |
def token_to_tuple(token: Token) -> tuple:
"""Convert token to tuple."""
return (token['txn_hash'],
token['owner'],
token['value'],
token['signature']) | 5,292,725 |
def evaluate(args, accelerator, dataloader, eval_set, model, checkpoint, has_labels=True, write_to_file=True):
"""Evaluate a model checkpoint on the given evaluation data."""
num_examples = args.num_examples[eval_set]
eval_metric = None
completed_steps = 0
eval_loss = 0.0
all_predictions = None... | 5,292,726 |
def _setup_entities(hass, dev_ids, platform):
"""Set up Tuya Climate device."""
tuya = hass.data[DOMAIN][TUYA_DATA]
entities = []
for dev_id in dev_ids:
device = tuya.get_device_by_id(dev_id)
if device is None:
continue
entities.append(TuyaClimateEntity(device, platfo... | 5,292,727 |
def imed_collate(batch):
"""Collates data to create batches
Args:
batch (dict): Contains input and gt data with their corresponding metadata.
Returns:
list or dict or str or tensor: Collated data.
"""
error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
e... | 5,292,728 |
def throttle(s):
"""Decorator ensures function that can only be called once every `s` seconds.
"""
def decorate(f):
t = None
def wrapped(*args, **kwargs):
nonlocal t
t_ = time()
if t is None or t_ - t >= s:
result = f(*args, **kwargs)
... | 5,292,729 |
def preprocess(path):
"""
Opens a file, reads the contents - then performs the following tasks:
1. Summarize the text with readability
1. Gets all the target tags in the text
2. Segments the paragraphs with the sent_tokenizer
3. Tokenizes the sentences with the word_tokenizer
4. Tags the se... | 5,292,730 |
def _tot_recovery_op(habitat_arr, num_arr, denom, max_rating):
"""Calculate and reclassify habitat recovery scores to 1 to 3.
The equation for calculating reclassified recovery score is:
score = 3 * (1 - num/denom/max_rating)
If 0 < score <= 1, reclassify it to 1.
If 1 < score <= 2, recla... | 5,292,731 |
def rdsamp(record_name, sampfrom=0, sampto=None, channels=None, pn_dir=None,
channel_names=None, warn_empty=False, return_res=64):
"""
Read a WFDB record, and return the physical signals and a few important
descriptor fields.
Parameters
----------
record_name : str
The name o... | 5,292,732 |
def create_puzzle_frame(parent_frame, n, current_puzzle_frame=None, read_only=False):
"""
Creates a new puzzle frame inside a parent frame and if the puzzle frame already exists, first destroys it.
This is done because when the n changes we have to change the puzzle frame's grid row and column configuration... | 5,292,733 |
def test_main_with_errors(
runner: click.testing.CliRunner,
mock_use_case_toml_validate_extension: Mock,
mock_use_case_toml_with_error: Mock,
) -> None:
"""It outputs error."""
with runner.isolated_filesystem():
with open("file.toml", "w") as f:
f.write("content doesnt matter")
... | 5,292,734 |
def main(imput_file, results_file, ampl_file):
"""Main solution routine. Finds all facets for inpu constraint."""
t_ = time.clock()
A, b, c = ReadInputFile(input_file)
N, A, sort_map = ConstructOrderedSet(A)
constraints = []
used_sets = set()
# Loop through all possible complementing set... | 5,292,735 |
async def tag_info_command(ctx: utils.PrefixContext) -> None:
"""Get info about a tag
Args:
<name|alias>: The tag name or alias to get info about.
"""
name = ctx.options.name.lower()
query = (
"SELECT t.tagname, t.tagowner, t.uses "
"FROM tags t FULL OUTER JOIN tag_aliases a... | 5,292,736 |
def fric_pipe(FlowRate, Diam, Nu, Roughness):
"""Return the friction factor for pipe flow.
For laminar flow, the friction factor is 64 is divided the Reynolds number.
For turbulent flows, friction factor is calculated using the Swamee-Jain
equation, which works best for Re > 3000 and ε/Diam < 0.02.
... | 5,292,737 |
def test_outxml_minimal_mode(data_regression):
"""
Test the minimal mode of the outxml_parser
"""
OUTXML_FILEPATH = os.path.join(outxmlfilefolder_valid[0], 'SiLOXML/files/out.xml')
out_dict = outxml_parser(OUTXML_FILEPATH, iteration_to_parse='all', minimal_mode=True)
data_regression.check({
... | 5,292,738 |
def test_block_size_exception():
"""A JPEG has no TIFF metadata and no API for block size"""
with pytest.raises(RasterBlockError):
with rasterio.open('tests/data/389225main_sw_1965_1024.jpg') as src:
src.block_size(1, 0, 0) | 5,292,739 |
def cli():
"""
This command-line interface allows you to access major parts of the VNEP-Approx framework
developed by Matthias Rost, Elias Döhne, Alexander Elvers, and Tom Koch.
In particular, it allows to reproduce the results presented in the paper:
"Parametrized Complexity of Virtual Network Emb... | 5,292,740 |
def compare_tag_value(tag_value1: TagValue,
tag_value2: TagValue
) -> None:
"""Compare two tag_value objects for equality.
Args:
tag_value1: tag_value 1
tag_value2: tag_value 2
"""
assert tag_value1.tag == tag_value2.tag
assert isinstanc... | 5,292,741 |
def load_model(model_uri, local_destination_path=None):
"""
Load an ONNX model from a local file or a run.
:param local_destination_path: The local path for downloading the model artifacts from the artifact store.
:param model_uri: The location, in URI format, of the MLflow model, for example:
... | 5,292,742 |
def geocode_address(input_address):
"""
Geocode an address to (lat, lon)
"""
try:
latlng = geocoder.arcgis(input_address).latlng
return latlng
except:
pass
try:
latlng = geocoder.osm(input_address).latlng
return latlng
except:
pass
try:
... | 5,292,743 |
def R1(w):
""" R1 is the region after the first non-vowel following a vowel,
or the end of the word if there is no such non-vowel.
"""
m = RE_R1.search(w)
if m:
return w[m.end():]
return "" | 5,292,744 |
def md_from_fast5_file(f5_file):
"""Read from a specified fast5 file and return a dict of metadata
"""
if f5_file.endswith('.gz'):
# Unpack the entire file in memory - much faster than a direct read from gzip handle
with BytesIO() as bfh:
with gzip.open(f5_file, 'rb') as zfh:
... | 5,292,745 |
def db():
"""Recover the current configured DB instance.
If no default instance is configured then ValueError will be raised.
:returns: The DB instance configured through init().
"""
if not __db:
raise ValueError("No DB instance configured! Call init() first.")
return __db | 5,292,746 |
def check_fields(default_dict, new_dict):
"""
Return the dictionary with default keys and values updated by using the information of ``new_dict``
:param dict default_dict:
Dictionary with default values.
:param dict new_dict:
Dictionary with new values.
:return: dict.
"""
# ... | 5,292,747 |
def plot_iv(*args, **kwargs):
"""Alias for uspy.leem.plotting.plot_intensity() with xaxis set
to "energy"."""
return plot_intensity(*args, xaxis="energy", **kwargs) | 5,292,748 |
def snapgene_file_to_gbk(read_file_object, write_file_object):
"""Convert a file object."""
def analyse_gs(dic, *args, **kwargs):
"""Extract gs block in the document."""
if "default" not in kwargs:
kwargs["default"] = None
for arg in args:
if arg in dic:
... | 5,292,749 |
def _iter_problematic_edges(edges):
""" generator that goes through a list of edges and returns intervals that
are problematic, i.e., where the edge would cross a previous edge. Yields
pairs of indices that denote the indices of the edges that surround a
problem region. """
i = 1
while i < len(... | 5,292,750 |
def get_total_click(link):
"""
Requests the total number of clicks at the moment
: param link: Byt.ly link for verification
: return: number of clicks
"""
params = {
'unit': 'day',
'units': '-1'
}
url = f'https://api-ssl.bitly.com/v4/bitlinks/{link}/clicks/summary'
... | 5,292,751 |
def get_default_retries() -> Dict[Retry, RetryConfig]:
"""Returns all default retry values."""
return {
Retry.PORT_INFO: set_retry(count=25, seconds_between=1),
Retry.JUPYTER_JSON: set_retry(count=15, seconds_between=1),
Retry.SCHEDULER_CONNECT: set_retry(count=5, seconds_between=2),
... | 5,292,752 |
def test_J1939Message_size():
"""Tests J1939Message's size parameter."""
msg = J1939.J1939Message()
assert not msg
assert msg.size == 0
assert len(msg) == 6
for x in range(1, 16):
msg.size = x
assert msg
assert msg.size == x
assert len(msg) == 6 + x
for x in r... | 5,292,753 |
def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return ""
x = str(x)
return x.replace("\t", "\\t").replace("\n", "\\n") | 5,292,754 |
def blit_pipes(screen, settings, bird, pipes):
"""
Draw pipes.
"""
for pipe_pair in pipes:
screen.blit(pipe_pair.image_top, (pipe_pair.top_pipe['x'], pipe_pair.top_pipe['y']))
screen.blit(pipe_pair.image_bot, (pipe_pair.bot_pipe['x'], pipe_pair.bot_pipe['y'])) | 5,292,755 |
def ble_connection_reliability_test():
"""
:return:
"""
capture_time = 10
repeat_count = 10
#TODO: Figuring out a way to disconnect the watch port programmatically | 5,292,756 |
def test_D1_fnorm():
""" Testing D'_1(a)
"""
M_d = MatterDominated(Omega0_m=0.3075)
cosmo = flowpm.cosmology.Planck15()
a = np.logspace(-2, 0.0, 128)
gback = M_d.gp(a)
gtfback = D1f(cosmo, a)
assert_allclose(gback, gtfback, rtol=1e-2) | 5,292,757 |
def create_dataset(connection_key: str, yaml_path: str):
"""
Create a dataset in fidesops given a YAML manifest file.
Requires the `connection_key` for the PostgreSQL connection, and `yaml_path`
that is a local filepath to a .yml dataset Fides manifest file.
Returns the response JSON if successful, ... | 5,292,758 |
def _health_info(q_len=None):
"""
compute daemon health info
based only on the visible state of the frontend queue
the queue length can be passed by the caller (for visibility during flush)
or it will be taken from len(_g_queue)
"""
if q_len is None:
q_len = len(_g_queue) # no lock... | 5,292,759 |
def is_to(func):
"""Decorator that ensures caller is owner, TO, or admin."""
@functools.wraps(func)
async def wrapper(self, *args, **kwargs):
ctx = args[0]
user = ctx.author
tourney = kwargs['tourney']
if not (user == tourney.owner or
tourney.channel.permissio... | 5,292,760 |
def _check_decorator_declaration(to_check:dict, name:str) -> dict:
"""Checks the declared decorator for correctness
params:
-------
to_check : dict
The dict containing the different
parameter definitions for the decorated
function.
name : str
The name of the dec... | 5,292,761 |
def tokenise(text_list):
"""
Remove symbols and tokenise strings
Parameters
----------
text_list: list
a list of strings, e.g. review comments
Returns
-------
tokenised_comments: a list of spacy docs
"""
# Remove symbols
text_list = [comment.replace("’", "'") for co... | 5,292,762 |
def sample_most_likely(state_vector):
"""Compute the most likely binary string from state vector.
Args:
state_vector (numpy.ndarray or dict): state vector or counts.
Returns:
numpy.ndarray: binary string as numpy.ndarray of ints.
"""
if isinstance(state_vector, dict) or isinstance(... | 5,292,763 |
def _get_monomial_basis(x):
"""Get the monomial basis (basis for quadratic functions) of x.
Monomial basis = .5*[x(1)^2 sqrt(2)*x(1)*x(2) ... sqrt(2)*x(1)*x(n) ...
... x(2)^2 sqrt(2)*x(2)*x(3) .. x(n)^2]
Args:
x (np.ndarray): Parameter vector of shape (n,).
Returns:
(np.ndarr... | 5,292,764 |
def cardinal(converted_data, path):
"""
Translates first move on path to cardinal direction.
Args:
converted_data (dict): python readable json
path (list): path from a*
Return:
direction (str): cardinal direction as string
"""
# if x values are same check y values for di... | 5,292,765 |
def sum_to_n(n: int) -> int:
"""
>>> sum_to_n(100)
5050
>>> sum_to_n(10)
55
"""
return sum(i for i in range(1, n + 1)) | 5,292,766 |
def catch_error(func):
"""A decorator to read error messages after calling ESP functions."""
def inner(*args, **kwargs):
self = args[0]
func(*args, **kwargs)
self.write('TB?', axis="")
error_string = self.read_error()
if error_string[0] is not '0':
self.abort()
raise NewportError(err... | 5,292,767 |
def normalize_features(x):
""" x - MEAN(x) / STD(x) """
mean = np.mean(x, axis=0)
std = np.std(x, axis = 0)
std[ np.where(std == 0) ] = 1
x = (x - mean)/std
return x | 5,292,768 |
def mostrarPantallaIntro(supPant, j1nombre, j2nombre):
"""Esta es la pantalla que se reproduce si el jugador ha elegido "ver introducción" de la pantalla de inicio."""
supPant.fill(COLOR_CIELO)
dibujarTexto('P y t h o n G O R I L A S', supPant, ANCHO_PNT / 2, 15, COLOR_BLANCO, COLOR_CIELO,... | 5,292,769 |
def set_remove():
"""
>>> sorted(set_remove())
[1, 2]
"""
s = set([1,2,3])
s.remove(3)
return s | 5,292,770 |
def from_yyyymmdd(date_str: str) -> typing.Union[date, str, None]:
"""
:param date_str: YYYY-MM-DD # 2020-07-16
:return: str -> date
"""
try:
return datetime.strptime(date_str, "%Y-%m-%d").date() # 2020-07-16
except (ValueError, TypeError):
return date_str | 5,292,771 |
def _cleanup_args_gen(*args):
"""
A generator, checking passed arguments and turning them to
a list of files to process.
Each argument should be either a file of dir path:
* passed files are checked to exist and have the right extension.
*
passed dirs are supposed to be a root folder for Unity's built-in
... | 5,292,772 |
def skip_if_root(func=None):
"""Skip test if uid == 0.
Note that on Windows (or anywhere else `os.geteuid` is not available) the
test is _not_ skipped.
"""
check_not_generatorfunction(func)
def check_and_raise():
if hasattr(os, "geteuid") and os.geteuid() == 0:
raise SkipTe... | 5,292,773 |
def test_index_with_ipynb(ipynbbuilddir):
"""
Test that index works with a build
"""
runner = CliRunner()
result = runner.invoke(main.cli, ["--path", ipynbbuilddir, "index"])
assert result.stdout.count("An author") >= 3
assert result.exit_code == 0, result.stdout | 5,292,774 |
def delete_carousel_files(sender, instance, **kwargs):
"""
同步删除轮播图文件
"""
instance.carousel.delete(False) | 5,292,775 |
def score_letters(genome, setup_data=None):
"""
We want to form the concept of a letter that is noise tolerant, so we show the
network lots of A's, B's, C's and D's and then ask it to cluster noisy
variants. A basic purity metric is used as the scoring function
"""
try:
data = setup_dat... | 5,292,776 |
def openDatabaseConnection(hostname, username, dbpass):
"""
Opens a database connection the MySQL server specified using the credentials
specified.
Returns a connection to the database in a cursor object
"""
connection = MySQLdb.connect(host=hostname, user=username, passwd=dbpass)
return co... | 5,292,777 |
def timestamp_after_timestamp(timestamp=None, seconds=0, minutes=0, hours=0, days=0):
""" 给定时间戳(10位),计算该时间戳之后多少秒、分钟、小时、天的时间戳(本地时间) """
# 1. 默认时间戳为当前时间
timestamp = get_current_timestamp() if timestamp is None else timestamp
# 2. 先转换为datetime
d1 = datetime.datetime.fromtimestamp(timestamp)
# 3. 根据... | 5,292,778 |
def clr(*colored_text: str, sep: str = "") -> str:
"""Add the color reset code after each colored_text."""
return (sep + colorama.Style.RESET_ALL).join(
colored_text
) + colorama.Style.RESET_ALL | 5,292,779 |
def unvec(vectorized):
"""A function that vectorizes a process in the basis of matrix units, sorted first
by column, then row.
Args:
vectorized (list,numpy.ndarray): Nx1 matrix or N-dimensional vector
Returns:
numpy.ndarray: NxN dimensional column vector
Raises:
ValueError... | 5,292,780 |
def test_copy_files_dirs():
"""
This function tests the copy_files function to ensure that it
correctly copies all directories of a directory to a new directory
"""
if plat in lin_plat:
source = '../data/test/move_directory3'
destination = '../data/test/move_directory2'
dire... | 5,292,781 |
def load_user_defined_function(function_name: str, module_file: str):
"""Function to load arbitrary functions
Args:
function_name (str): name of function to load from function_file
module_file (str): file module where function is defined
Returns:
function loaded from file
"""
... | 5,292,782 |
def create_model_dictionary(library_name, group_keys, db_conn):
"""
Creates a model dictionary based on the group keys
:param library_name
:param group_keys:
:param db_conn
:return:
"""
model = {}
records = db_conn.execute("SELECT * FROM main.audio where library = ?", (library_name,)... | 5,292,783 |
def init_manager(basedir, dbconnect):
"""Initialize the archive manager directory."""
# Test if the base directory exists and is empty.
basedir = basedir if basedir is not None else config.BASEDIR()
if os.path.isdir(basedir):
if os.listdir(basedir):
click.echo('Not an empty directory... | 5,292,784 |
def insert_edge_list():
"""Solution to exercise R-14.8.
Repeat Exercise R-14.7 for the adjacency list representation, as described
in the chapter.
---------------------------------------------------------------------------
Solution:
-------------------------------------------------------------... | 5,292,785 |
def test_constant_cases_high_count(tmp_path):
"""Track constant cases (R=1) at low count"""
data_spec = load_data.DataSpec(
generator_type=load_data.DataGeneratorType.EXP,
disable_deaths=True,
scale=1000.0,
ratechange1=RateChange(0, 1.0),
ratechange2=RateChange(80, 1.5), ... | 5,292,786 |
def lastnb(string: str) -> int:
"""
Return the zero based index of the last non-blank character in
a character string.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lastnb_c.html
:param string: Input character string.
:return: """
string = stypes.string_to_char_p(string)
ret... | 5,292,787 |
def multiple_train_test_data(dataset_cls, n=1000):
"""Example of multiple train and evaluation datasets.
Second one has a special evaluation metric
"""
from gin_train.metrics import MetricsDict, accuracy
return dataset_cls(), [("valid1", RandomDataset(int(n * 0.1))),
("va... | 5,292,788 |
def showParents(person):
"""
A function that prints a person's parents.
"""
if person.parent1 and person.parent2:
print("Parents: {} {} and {} {}".format(person.parent1.firstName, person.parent1.lastName,
person.parent2.firstName, person.parent2.lastName))
else:
if person.par... | 5,292,789 |
def test_write_read(tmpdir):
""" Check that serialization to disk doesn't lose info """
filename = str(tmpdir.join("testcamera.fits.gz"))
geom = CameraGeometry.from_name("LSTCam")
geom.to_table().write(filename, overwrite=True)
geom2 = geom.from_table(filename)
assert geom.camera_name == geom... | 5,292,790 |
def _get_lines(update_data = False):
"""
Get data frame of lines with count of jams per line and split number
"""
logger.info('Lines')
if update_data:
# Download data from Athena
logger.debug("Downloading lines")
conn = utils.connect_athena(path='configs/athena... | 5,292,791 |
def get_s3direct_destinations():
"""Returns s3direct destinations.
NOTE: Don't use constant as it will break ability to change at runtime.
"""
return getattr(settings, 'S3DIRECT_DESTINATIONS', None) | 5,292,792 |
def info(msg, *args):
"""Show information [I] message."""
if MIN_LEVEL <= INFO:
print(f'{get_now()} [I] {msg % args}') | 5,292,793 |
def test_success(database):
""" FederalActionObligation is required for non-loans (i.e., when AssistanceType is not 07 or 08). """
det_award = DetachedAwardFinancialAssistanceFactory(assistance_type='02', federal_action_obligation=0,
correction_delete_ind... | 5,292,794 |
def delete_whole_table(conn: connection, table: LoadableRelation, dry_run=False) -> None:
"""Delete all rows from this table."""
stmt = """DELETE FROM {}""".format(table)
etl.db.run(conn, "Deleting all rows in table {:x}".format(table), stmt, dry_run=dry_run) | 5,292,795 |
def train_multistep_objective(train_data, test_data, output_dir,
num_epochs=5,
num_test_examples=10000,
window_size={0: 2, 1: 10, 2: 20},
test_window_size=64,
num_samples... | 5,292,796 |
def heuristic_iteration(gloss_tokens, trans_tokens, aln, comparison_function, multiple_matches = True, iteration=1, report=False):
"""
:param gloss_tokens:
:type gloss_tokens: list[str]
:param trans_tokens:
:type trans_tokens: list[str]
:param aln:
:type aln: Alignment
:param comparison... | 5,292,797 |
def makeIntervalIndex(k=10, name=None, **kwargs):
"""make a length k IntervalIndex"""
x = np.linspace(0, 100, num=(k + 1))
return IntervalIndex.from_breaks(x, name=name, **kwargs) | 5,292,798 |
def broadcast(sock, message):
"""This function broadcats data to all users
:param sock: socket object
:param message: message to send
"""
#Non Empty sockets
valid_users = []
# Iterate connection list
for s in CONNECTIONS:
if s != server_socket and s != sock:
# find s... | 5,292,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.