content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
|---|---|---|
import random
import string
def gen_random_string(str_len):
""" generate random string with specified length
"""
return ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(str_len))
|
f1e7256aace39e8fefdaaec12f1c0dd74d772e4d
| 486,043
|
def string_to_list(t_str, t_char=" "):
"""
Returns a list of elements that are contains inside the string param.
:param str t_str: string with elements and delimiters
:param str t_char: delimiter of the elements
:return list t_list: list of elements that were inside t_str
"""
t_list = t_str.strip(t_char).split(t_char)
return t_list
|
909d3a45bdac900812d9024b46d334b6c6d5c08c
| 506,473
|
def locate_dominating_file(io, filename, directory=None):
"""
Find a file or directory with the given name, either in the given
(defaults to current) directory or a parent. Return the full path,
or None if the root of the filesystem is reached before finding a
matching file.
"""
if directory is None:
directory = io.getcwd()
last, directory = None, io.realpath(directory)
while directory != last:
path = io.join(directory, filename)
if io.exists(path) or io.islink(path):
return path
last, directory = directory, io.dirname(directory)
return None
|
37940616448be54df497ad528cbea20f52a953b7
| 196,634
|
import math
def _calc_KTB_rate(starting_rate, duration, roeotroe, rng):
"""
Returns a simulated rate for the head node of a tree when:
* the tail node has rate ``starting_rate``
* the time duration of the edge is ``duration``
* the rate of evolution of the rate of evolution is ``roeotroe`` (this is
the parameter nu in Kishino, Thorne, and Bruno 2001)
``rng`` is a random number generator.
The model used to generate the rate is the one described by Kishino, Thorne,
and Bruno 2001. The descendant rates or lognormally distributed.
The mean rate returned will have an expectation of ``starting_rate``
The variance of the normal distribution for the logarithm of the ending rate
is the product of ``duration`` and ``roeotroe``
"""
if starting_rate <= 0.0:
raise ValueError("starting_rate must be positive in the KTB model")
rate_var = duration*roeotroe
if rate_var > 0.0:
# Kishino, Thorne and Bruno corrected the tendency for the rate to
# increase seen in teh TKP, 1998 model
mu = math.log(starting_rate) - (rate_var/2.0)
return rng.lognormvariate(mu, math.sqrt(rate_var))
return starting_rate
|
fa31faf91f0e26795ad136b327c116f3192e9913
| 281,524
|
def msg_color(msg_type):
"""Get the color to use for the msg type."""
return {
"sent": 0x4caf50,
"edited": 0xffc107,
"deleted": 0xff5252,
}.get(msg_type, 0x000000)
|
5c1b6615531e9fe018a86d28a5a34122dbcd62e5
| 493,274
|
def _filename_dataset(dataset, market=None, variant=None, extension=None):
"""
Compose the filename for a dataset given its name, variant, market,
and filename extension.
:param dataset: String with dataset name e.g. 'income'.
:param market: Optional string with dataset market e.g. 'usa'.
:param variant: Optional string with dataset variant e.g. 'ttm'.
:param extension: Optional string with filename extension e.g. 'zip' or 'csv'.
:return: String with filename for the dataset-file.
"""
assert dataset is not None
# Compose filename from market and dataset.
if market is None:
filename = dataset
else:
filename = '{}-{}'.format(market, dataset)
# Add variant to filename.
if variant is not None:
filename = '{}-{}'.format(filename, variant)
# Add extension to filename.
if extension is not None:
filename = '{}.{}'.format(filename, extension)
return filename
|
6b4cc7c1fed80088d391b481acc4c7c3fa0e6d85
| 218,265
|
def find_bad_building1099(X, y):
"""Returns indices of bad rows (with absurdly high readings) from building 1099."""
return X[(X.building_id == 1099) & (X.meter == 2) & (y > 3e4)].index
|
96010fcd5d43fd231bdc688b482580ca4f56aba7
| 264,602
|
from typing import Tuple
def get_mode(mode: str, line: str) -> Tuple[str, bool]:
"""Get the mode of the map.
Args:
mode (str): the current mode
line (str): the line to check
Returns:
str, bool: the new mode, if the mode has changed
"""
if line == "" or line[0] == "#":
return mode, True
elif line.startswith("terrain"):
return "terrain", False
elif line.startswith("bounds"):
return "bounds", False
elif line.startswith("players"):
return "players", False
else:
return mode, False
|
721d335ea1eaefbfc3f8a3ab60fb351d1b940674
| 670,820
|
def star_formation_rate(z, z_inhom=0.):
"""Returns the star formation rate, per comoving volume, evaluated at the specified redshift.
Ref:
A.M. Hopkins and J.F. Beacom, Astrophys. J. 651, 142 (2006) [astro-ph/060146]
P. Baerwald, S. Huemmer, and W. Winter, Astropart. Phys. 35, 508 (2012) [1107.5583]
Args:
z (float): redshift
z_inhom (float): redshift where the universe becomes inhomogenous, return 0. below this values
Returns:
float: star formation rate normalized to 1. at y = 0.
"""
if z < z_inhom:
return 0.
elif z <= 0.97:
return (1. + z)**3.44
elif 0.97 < z <= 4.48:
return 10.**1.09 * (1. + z)**-0.26
else:
return 10.**6.66 * (1. + z)**-7.8
|
83da0e6b776bfc35dac1c8e5e0df42c493da9d6b
| 275,291
|
def get_taskResult(plRunitem, taskname, resultName):
"""タスク名、Result項目名を指定しタスクResult値を取得する
Args:
plRunitem (dict): TEKTON CLI pipelinerun listの結果明細(1 pipelinerun)
taskname (str): タスク名
resultName (str): Result項目名
Returns:
(str): タスクResult値
"""
# status.taskRuns[*]にtask毎、Result項目毎で格納されているので、タスク名、Result項目名が合致するものを探して値を返します
for taskRun in plRunitem['status']['taskRuns'].values():
if taskRun['pipelineTaskName'] == taskname:
# キー値が存在する場合のみ処理する
if 'taskResults' in taskRun['status']:
for taskResult in taskRun['status']['taskResults']:
if taskResult['name'] == resultName:
return taskResult['value']
return None
|
5f2b6d930f9b9497ecc1b6a1e6e8d6892ad7781e
| 407,083
|
def bool2yn(b):
"""Converts a boolean to yes or no with the mapping: y = True, n = False."""
return 'y' if b else 'n'
|
d64c34fb720d547e6c9b557fa67fdca2fe3b1860
| 139,111
|
def get_numeric_name(name):
"""
Strips non-numeric characters from a string and returns a string with only numeric values in it.
:param name:
Name of a room
:type name:
`str`
:rtype:
`str`
"""
return ''.join([x for x in name if x.isnumeric()])
|
3bfcc63c92d5bac750420f9ec3c715326b57d8b6
| 336,576
|
def is_installed(settings):
"""
Check Django settings and verify that tinymce application is included
in INSTALLED_APPS to be sure that staticfiles will work properly and
serve required files.
"""
if not hasattr(settings, 'INSTALLED_APPS'):
raise RuntimeError('Django settings should contain INSTALLED_APPS.')
if 'tinymce' not in settings.INSTALLED_APPS:
raise RuntimeError('Add tinymce to INSTALLED_APPS in settings.')
return True
|
ababfb859f3b16921dadeaea7b7d4ffbabc751da
| 172,935
|
def bilinear_interpolation(n1, n2, n3, n4, x, y):
"""
Bilinear interpolation of value for point of interest (P).
:param n1: value at node 1
:param n2: value at node 2
:param n3: value at node 3
:param n4: value at node 4
:param x: interpolation scale factor for x axis
:param y: interpolation scale factor for y axis
:return: value at node P
"""
a0 = n1
a1 = n2 - n1
a2 = n3 - n1
a3 = n1 + n4 - n2 - n3
p = a0 + (a1 * x) + (a2 * y) + (a3 * x * y)
return p
|
dda4474bbd7bbf744a265be7be79fff5f70ee7b8
| 579,780
|
import requests
def get_pypi_package_releases(package_name):
"""
calls PYPI json api as described here
https://wiki.python.org/moin/PyPIJSON
https://warehouse.readthedocs.io/api-reference/json.html
:param package_name: string, pypi project name
:return: json with pypi project response
"""
result = requests.get('https://pypi.org/pypi/{}/json'.format(package_name))
if result.status_code != 200:
print('error occurred fetching package {} from PYPI.\n'
'response is: {}'.format(package_name, result.reason))
raise requests.exceptions.RequestException
return result.json()
|
14b8522e4c6c8087c72268abd9e627dbeff44eba
| 170,271
|
def reject_hit(client, assignment_id, feedback):
"""Rejects a HIT assignment on MTurk
Parameters
----------
client : MTurk.Client
A boto3 client for MTurk
assignment_id : string
The ID of the assignment. The assignment must correspond to a HIT created by the Requester.
feedback: string
A message for the Worker, which the Worker can see in the Status section of the web site.
Returns
-------
bool
returns whether the operation was successful
"""
response = client.reject_assignment(
AssignmentId=assignment_id,
RequesterFeedback=feedback)
return response=={}
|
bc1f742e47baee29cfdf556aed31b32dd43b7da2
| 568,701
|
def virial_mass(FWHM, vel_disp):
"""
Calculates the Vyrial Theorem based Dynamical mass
FWHM is the deconvolved size of the source in pc
vel_disp is the velocity dispersion in km/s
http://adsabs.harvard.edu/abs/2018arXiv180402083L
Leroy et al 2018
"""
M = 892. * FWHM * (vel_disp**2.)
return M
|
0a2529b453edb4c0bc2cbd19d56ccf27fbf77005
| 249,424
|
def module_equals(model1, model2):
"""Check if 2 pytorch modules have the same weights
"""
for p1, p2 in zip(model1.parameters(), model2.parameters()):
if p1.data.ne(p2.data).sum() > 0:
return False
return True
|
cf23a7da62d95b80f6f878dc77f65e14db74dba6
| 659,918
|
def resolve(obj, attrspec):
"""
Resolve elements from an object.
Works with objects and dicts.
From: http://stackoverflow.com/a/9101577/1309774
"""
for attr in attrspec.split("."):
try:
obj = obj[attr]
except (TypeError, KeyError):
obj = getattr(obj, attr)
return obj
|
59280637c1cbc9ec8d402d6dbee020568c35a854
| 466,723
|
def listSnapshots(snapshots, tree=False):
"""Get VM snapshot information.
tree=True will return snapshot tree details required for snapshot removal
"""
snapshot_data = []
for snapshot in snapshots:
if tree is True:
snapshot_data.append(snapshot)
else:
snapshot_data.append(snapshot.id)
snapshot_data = snapshot_data + listSnapshots(snapshot.childSnapshotList, tree)
return snapshot_data
|
bb375fc2eecbb6c395f5a89ba290b7b1d95eb7ee
| 604,815
|
import itertools
def test_combination_combinator(container, pairs_):
"""
r-length tuples, in sorted order, no repeated elements
combinations('ABCD', 2)
AB AC AD BC BD CD
"""
return list(
itertools.combinations(container, pairs_)
)
|
5bd1b6f2e2e6360c1db8b663445085d8b2ae3e99
| 588,490
|
def rotate(image):
"""Rotate the image based on it's exif tag.
If the exif tag is missing or the value
unknown the image is returned unchanged.
"""
try:
# Exif tag for orientation
orientation = image.getexif()[274]
if orientation == 3:
return image.rotate(180, expand=True)
elif orientation == 6:
return image.rotate(270, expand=True)
elif orientation == 8:
return image.rotate(90, expand=True)
except KeyError:
pass
return image
|
51f6fc669263fbe715725de927fc220cf056b784
| 423,852
|
def get_requirements_from_file(requirements_file):
"""
Get requirements from file.
:param str req_file: Name of file to parse for requirements.
:return: List of requirements
:rtype: list(str)
"""
requirements = []
with open(requirements_file) as f:
for line in f:
line = line.strip()
if line and not line.startswith(("#", "-e")):
requirements.append(line)
return requirements
|
5ec6ad1f4c2b22aae1cfa7eb3888b3279ffeca31
| 8,846
|
def _has_numbers(text):
""" Checks if any characters in the input text contain numbers """
return any(char.isdigit() for char in text)
|
c8992cfe40c310f07d292aa376aad8d766a5242b
| 657,440
|
def _get_last_page_offset(url_html):
"""Obtain last page offset.
Required to stop iterating over pages.
Parameters
----------
url_html : BeautifulSoup object
Returns
-------
int
"""
page_numbers = url_html.findAll("div", attrs={"class": "pageNumbers"})[0]
last_page_offset = page_numbers.findAll("a")[-1].get("data-offset")
return int(last_page_offset)
|
3f3d01a095addb2c8ac577e33cc28129047df227
| 568,019
|
def build_form(Form, _request, *args, **kwargs):
"""
Build the ``Form`` instance.
If ``request.method`` is ``POST`` then build bound form else build unbound.
Usage example::
@login_required
@render_to('blog/post_create.html')
def post_create(request):
post = Post(instance=request.user)
form = build_form(PostForm, request, instance=post)
if form.is_valid():
obj = form.save()
return redirect(obj)
return {'form': form,
}
"""
if 'POST' == _request.method:
form = Form(_request.POST, _request.FILES, *args, **kwargs)
else:
form = Form(*args, **kwargs)
return form
|
7365ac3edd578503d25adda8f7f057a44637c123
| 250,765
|
import logging
def column_exists(df, column, log=True, stdout=True, log_msg=None):
"""Check whether a column exists in a given pandas DataFrame."""
if column in df.columns:
return True
if log:
if log_msg:
log_msg = str(log_msg)
else:
log_msg = (f'WARNING: `{column}` column is not used in this DataFrame. '
'Processing for this column was skipped.')
logging.warning(log_msg)
if stdout:
print(log_msg)
return False
|
5e03223b6623f02bfec4a34494913d095f5d8f8b
| 358,446
|
import json
def __force_mutable(plaintext):
"""Dumps mutable objects to string to make them hashable"""
if not isinstance(plaintext, str):
return json.dumps(plaintext)
return plaintext
|
16d1afea71bc23c5f5319197789fec25cd38b916
| 345,316
|
def single(sequence, condition=None):
"""
Returns the single item in a sequence that satisfies specified condition or
raises error if none or more items found.
Args:
sequence: iterable
Sequence of items to go through.
condition: callable
Condition to test.
Returns:
any
Single valid item.
"""
items = list(sequence) if condition is None else [d for d in sequence if condition(d)]
if len(items) == 1:
return items[0]
raise ValueError
|
6849a5ea218f45b2ef163f3ca98b15311b779515
| 398,219
|
def try_int(string):
"""
Return an integer if possible, else string
"""
# Ignore octal & hexadecimal
if len(string) > 1 and string[0] == '0' and string.isdigit():
return string
try:
return int(string)
except ValueError:
return string
|
26beb7162348dc2a3205d223578a52ef5d1abd23
| 412,340
|
import torch
def collate_samples(batch):
"""
Used by DatasetLoader to merge together multiple samples into one mini-batch.
"""
images = [d['image'] for d in batch]
targets = [d['target'] for d in batch]
collated_batch = dict(
image=torch.stack(images),
target=torch.stack(targets)
)
return collated_batch
|
ae4cf311f75909bf57f5132e42806903df4c531a
| 565,496
|
def qualitative_dates(df,
iterator_column='Animal_id',
date_column='relative_date',
label='qualitative_date',
fuzzy_matching={},
):
"""
Assign qualitative date labels.
Parameters
----------
df : pandas.DataFrame
A `pandas.DataFrame` object containing a date column.
iteraor_column : string, optional
The label of the column which identifies the base entities of which each should be assigned a set of qualitatie dates (most commonly this is `Animal_id`, or `Cage_id`).
date_column : string, optional
The label of the column which serves as the quantitative record which is to be discretized into qualitative dates.
label : string, optional
The label to assign to the new qualitative date column.
fuzzy_assignment : dict, optional
A dictionary the keys of which are qualitative date labels to be assigned, and the values of which are lists giving the quantitative date labels in the order of preference based on which to assign the labels.
"""
df[label]=''
for i in df[iterator_column]:
try:
for label, dates in fuzzy_matching.iteritems():
for date in dates:
if date in df[df[iterator_column]==i][date_column].values:
df.loc[(df[iterator_column]==i)&(df[date_column]==date),'qualitative_date']=label
break
except AttributeError:
for label, dates in fuzzy_matching.items():
for date in dates:
if date in df[df[iterator_column]==i][date_column].values:
df.loc[(df[iterator_column]==i)&(df[date_column]==date),'qualitative_date']=label
break
return df
|
370fa4b9e0ce81329094514882cd3686b7989ebb
| 338,894
|
import re
def get_member(path):
"""Retrieve member_id from path ifpotentially wrong in database
Args:
path (str): data directory path
Returns:
string of member_id extracted from path
"""
mo = re.search(r'r\d*i\d*p\d*f\d*', path)
if mo:
return mo.group()
else:
return None
|
caa171d3830763c5b73db3cd557a668c0067c58e
| 463,476
|
def get_upstream_basin(catchment, totalBasinGeom):
"""Get upstream basin geometry by subtracting the local catchment from the totalBasinGeom"""
d = 0.00045
cf = 1.3 # cofactor
upstreamBasinGeom = totalBasinGeom.symmetric_difference(catchment).buffer(-d).buffer(d*cf).simplify(d)
return upstreamBasinGeom
|
53e665f9e3a4203b7374934f9ae6c1d38605aaeb
| 160,522
|
def _strToBoundNumeral(v, interval, conversion):
"""Test (and convert) a generic numerical type, with a check against a lower and upper limit.
@param v: the literal string to be converted
@param interval: lower and upper bounds (non inclusive). If the value is None, no comparison should be done
@param conversion: conversion function, ie, int, long, etc
@raise ValueError: invalid value
"""
try:
i = conversion(v)
if (interval[0] is None or interval[0] < i) and (interval[1] is None or i < interval[1]):
return i
except:
pass
raise ValueError("Invalid numerical value %s" % v)
|
e1a473ba009462316e21b94613f3a8803c0954cd
| 247,380
|
def lookup_in_namespace(name,namespace):
"""Resolve a dotted name into an object, using given namespace."""
bits = name.split(".")
obj = namespace[bits[0]]
for attr in bits[1:]:
obj = getattr(obj,attr)
return obj
|
ccb79410e6357fd3681da2d4afe3f25217e82720
| 588,067
|
def get_symlink_output(pull_number, job_name, build_number):
"""Return the location where the symlink should be created."""
# GCS layout is defined here:
# https://github.com/kubernetes/test-infra/tree/master/gubernator#job-artifact-gcs-layout
if not pull_number:
# Symlinks are only created for pull requests.
return ""
output = ("gs://kubernetes-jenkins/pr-logs/directory/"
"{job}/{build}.txt").format(
job=job_name,
build=build_number)
return output
|
4320d124b12b3c4e0d88e85b27314e1c1c01db7c
| 180,892
|
def assert_time_of_flight_is_positive(tof):
"""
Checks if time of flight is positive.
Parameters
----------
tof: float
Time of flight.
"""
if tof <= 0:
raise ValueError("Time of flight must be positive!")
else:
return True
|
54f85189ca8b25f0447ccbca60179a2eff41b018
| 655,223
|
def a_send_line(text, ctx):
"""Send text line to the controller followed by `os.linesep`."""
ctx.ctrl.sendline(text)
return True
|
79f40657fe2b346c695d808bb3cdc7650077b76e
| 23,966
|
def get_full_name(given_name, family_name, config):
"""Return full name string obtained by concatenating given_name and
family_name in the order specified by config.family_name_first, or just
given_name if config.use_family_name is False."""
if config.use_family_name:
separator = (given_name and family_name) and u' ' or u''
if config.family_name_first:
return separator.join([family_name, given_name])
else:
return separator.join([given_name, family_name])
else:
return given_name
|
51489dda714e678bbec36e6397c07bc228de060d
| 143,577
|
def calculate_boundbox(list_coordinates):
"""
coordinates are inverted x: colums y :rows
list_coordinates: list of the form [ [x2,y1], [x2,y2], . . . ]
returns top left point (x,y) and width (w) and heigth (h) of rectangle
"""
x = int(min(list_coordinates[:,0]))
y = int(min(list_coordinates[:,1]))
w =int(max(list_coordinates[:,0]) - x)
h = int(max(list_coordinates[:,1]) - y)
return x,y,w,h
|
bbabdd81e88dd4304293712aff389bfd568f4772
| 43,538
|
def split_sentences(inp_text, nlp_model):
"""
Splits an input string into sentence determined by spacy model
:param inp_text: string with input text
:param nlp_model: sciSpacy model
:return: list of sentences in string format
"""
doc = nlp_model(inp_text)
sentences_list = [sentence.text for sentence in doc.sents]
return sentences_list
|
b5617d9334509edf09bf4a0360d3030e67ddf800
| 700,537
|
import pathlib
import click
def validate_keep_media_path(ctx, param, value):
"""
Validate the path used to set the 'keep_media' option
"""
if value is None or pathlib.Path(value).exists():
return value
else:
path = pathlib.Path(value)
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
if path.exists():
return path
else:
raise click.BadParameter("provide a valid path for media")
|
75c589e5fbc4c5cd26cac2c6f115de4f91c870b5
| 220,864
|
from typing import List
def is_empty(stack: List[str]) -> bool:
"""
Check if a stack is empty.
We add this custom method, as Python does not have a built-in is_empty() method.
:param stack: is the stack to inspect.
:return: a boolean value determining whether the stack is empty or not.
"""
return len(stack) == 0
|
5a2ca546c08c5c417526869d272ae353469fc30f
| 585,816
|
def evaluate_single_episode(environment, agent, render=False, epsilon=None):
"""
Evaluate a single episode of agent operating inside of an environment.
This method should be applicable to all reinforcement learning algorithms
so long as they implement the Agent interface.
"""
state = environment.reset()
done = False
step = 0
total_reward = 0
while not done:
if render:
environment.render()
action = agent.act(state, training=False, epsilon=epsilon)
next_state, reward, done, _ = environment.step(action)
state = next_state
step += 1
total_reward += reward
agent.end_of_episode()
return total_reward
|
38473730d5c0a600408de8cacb3ec7b43168c7e8
| 144,678
|
import re
def parse_k(msg):
"""Parse create keypoint message and return keypoint number"""
if not re.search(r"KEYPOINT NUMBER", msg):
res = re.search(r"(KEYPOINT\s*)([0-9]+)", msg)
else:
res = re.search(r"(KEYPOINT NUMBER =\s*)([0-9]+)", msg)
if res:
result = int(res.group(2))
else:
result = None
return result
|
92f45ea09a7c9e1eecf48664c49218657687a217
| 35,729
|
def _get_feature_names_from_str_or_col_index(X, names_or_col_indices):
"""Helper function to map the user-input features param to column names."""
feature_list = []
for name_or_index in names_or_col_indices:
if isinstance(name_or_index, int):
feature_list.append(X.columns[name_or_index])
else:
feature_list.append(name_or_index)
return feature_list
|
e5d71f16b5a331425ff579e74df86cc78d60bb09
| 265,617
|
from collections import defaultdict
def problem_1_3(left: str, right: str) -> bool:
"""
Given two strings, write a method to decide if one is a permutation of the other.
So, I could iterate through a range of indicies and construct a single hashmap to store the counts of a character.
We can add from one str and remove from the other. This would result in all values should equal = 0
>>> problem_1_3("abc", "cba")
True
>>> problem_1_3("a", "b")
False
>>> problem_1_3("aabbcc", "ccbbaa")
True
The below solution using a defaultdict should return with speed of O(n)
"""
if len(left) != len(right):
return False
_d = defaultdict(int)
for i in range(len(left)):
_d[left[i]] += 1
_d[right[i]] -= 1
for v in _d.values():
if v != 0:
return False
return True
|
0f350bd19f0720fc41a30fa15930cf6d6f9c08d5
| 325,953
|
from pathlib import Path
def load_from_config(path: str, pattern: str) -> list:
"""
Loads all mris from a given path with a given pattern.
Args:
path (str): Path to the mris.
pattern (str): Pattern to search for.
Returns:
list: List of mris.
"""
p = Path(path).expanduser()
return list(p.glob(pattern))
|
be0a57fa3c1ae2793ea9bee02465f9fb4034cef7
| 529,781
|
def persistence_model(latest_ghi):
"""
Creates a persistence forecast when the software fails to receive a valid
GHI observation. Can also be used if one simply desires a persistence
forecast.
Parameters
----------
latest_ghi: 'Pandas Series object'
Current time. Usually contains a year, month, day, hour, and minute.
Returns
-------
persist_ghi: 'Pandas Series object'
Persistence forecast for inputed date time.
"""
persist_ghi = latest_ghi.copy()
return persist_ghi
|
4a79dfe09d12b8b98cac9e542f20be48b5af1433
| 496,133
|
def get_history_slice(
frame_index: int, history_num_states: int, history_step_size: int, include_current_state: bool = False
) -> slice:
"""Given a frame index and history settings returns a slice that returns the given data in the right order.
Note that this history returned starts with the most "recent" frame first (i.e. reverse in time as it's history).
Example:
``frame_index=20``, ``history_num_frames=2``, ``history_step_size=2``, ``include_current_state=True``
would return a slice for frame index 20, 18, 16.
Arguments:
state_index (int): The "anchor" frame index you want to sample from
history_num_states (int): Number of history frames (not including the current frame).
history_step_size (int): How many frames to step for each history step.
Keyword Arguments:
include_current_state (bool): Whether the slice should include ``frame_index`` (default: {False})
Raises:
IndexError: Returned when ``history_step_size`` is an invalid value (e.g. 0).
Returns:
slice -- Slice that when applied to an array returns the history frames in the right order.
"""
if history_step_size <= 0:
raise IndexError("History step size can not be 0 or negative")
history_earliest_index = frame_index - (history_num_states) * history_step_size - 1
history_latest_index = frame_index - (0 if include_current_state else history_step_size)
if history_latest_index < 0:
return slice(0, 0, -history_step_size)
# Necessary for including the first element with negative step size (step size has to be negated as it's history)
# Example: start index = 2, step size = 2, element 0 should be included.
# +1 is required because it is non-inclusive (-1 is performed above).
if history_earliest_index < 0 and (history_earliest_index + 1) % history_step_size == 0:
history_earliest_index = None # type: ignore
else:
history_earliest_index = max(0, history_earliest_index)
return slice(history_latest_index, history_earliest_index, -history_step_size)
|
185d472bd2b92e77a016473fb1afdc99c4534955
| 622,952
|
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace()
|
2353eebce8f33890d7e2a62a3d627365ac1cbea6
| 512,990
|
def flatten_get_parameters(request):
"""Return a dict with flattened GET parameters.
Otherwise a dict(ImmutableMultiDict) returns a list for each
parameter value and that is not what we want in most of the cases.
"""
if not hasattr(request, 'args'):
return {}
return {k: len(v) == 1 and v[0] or v
for k, v in dict(request.args).items()}
|
7a29d7c7733db5a28b97e472431bbc36e3753e90
| 148,121
|
def fmt_d(num):
"""Decimal formatter"""
return f'${num:,.0f}'
|
4d8e6b6c31de3150ed9530f9204e3d9d491acad6
| 400,157
|
def package_collection(distinct: bool):
"""Return the package collection, set or list."""
if distinct:
package = set()
else:
package = []
return package
|
7dc1090fb526d2bf5c71037f3856f791bd0b8860
| 145,172
|
def renormalize_sv(elements):
"""
Accepts a vector or array and removes the integer part of all elements, reducing them floats in the interval (0,1).
Example:
x = [1.2, 4.5, 5, 3.1]
renormalize(x)
print(x)
[0.2, 0.5, 0, 0.1]
"""
D = len(elements)
elements_new = [elements[i] % 1 for i in range(D)]
return elements_new
|
619d77a20511ccae60304e529519b268fd3c37ce
| 303,813
|
import math
def cphase(c):
"""cphase(c): returns complex phase: (-pi, +pi]."""
return math.atan2(c.imag, c.real)
|
6ff8207819d377bc8279d9f5efbf2123999650e3
| 123,592
|
def _package_root(name):
"""Convert treadmill.logging.xxx => treadmill
"""
return name.split('.', 1)[0]
|
6ad3e2f89f8ce2fa708757ce772e020c1c216f6e
| 243,007
|
def get_item(dictionary, key):
"""
Return a key value from a dictionary object.
**Parameters**
``dictonary``
Python dictionary object to parse
``key``
Key name tor etrieve from the dictionary
"""
# Use `get` to return `None` if not found
return dictionary.get(key)
|
6a0a9bd78c8e7f68a329c39a3cf1b125b529bcd3
| 488,134
|
from typing import List
def load_list(filename: str) -> List[str]:
"""
Load list of strings from files.
Arguments:
filename - filename to be loaded
Returns:
List of lines
Raises:
PermissionError, FileNotFoundError
"""
with open(filename, encoding="UTF-8") as f: # pylint: disable=C0103
return list(f.readlines())
|
9c7b3f962f7167d04ecbcf3e4cc4e9b1a1ad2a04
| 158,320
|
def clamp(x, lo, up):
"""
clamp x to be lo <= x <= up
"""
assert lo <= up
return lo if x < lo else up if x > up else x
|
1778a202559c7773cc3f0724d05235399ba96312
| 572,837
|
def load_phrase_dictionary(file, mode):
"""
Loads a phrase dictionary
:param file: The phrase dictionary to open
:param mode: Mode w, a, r - write, append, read
:return: The loaded phrase dictionary
"""
phrase_dict = open(file, mode)
return phrase_dict
|
b2403ef76880d9f67aa8464c2c41924ec8016227
| 219,573
|
def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True
|
b83d8fadf779fbd46835f5350b2329601a6fd46d
| 130,844
|
def element(point, p, q, n):
"""Test, whether the given point is on the curve (p, q, n)"""
if point:
x, y = point
return (x * x * x - p * x - q) % n == (y * y) % n
else:
return True
|
0433af33e5567597592d2b7fe07420317851b506
| 618,605
|
def get_tier_level(files: str) -> str:
"""
Retrieves the RHCS QE tier level based on the suite path or filename.
The argument contains "::" as a separate for multiple test suite execution. The
understanding in both the cases is that, the qe stage is provided at the starting
of the filename or directory.
Supported formats are
tier_0/
tier-1/
tier_0_rgw.yhaml
tier-1_cephadm.yaml
Args:
files (str): The suite files passed for execution.
Returns:
(str) Tier level
"""
file = files.split("::")[0]
file_name = file.split("/")[-1]
if file_name.startswith("tier_"):
return "-".join(file_name.split("_")[0:2])
if file_name.startswith("tier-"):
return file_name.split("_")[0]
return "Unknown"
|
b7030b110b99d93ee6eef79e69d0db7242060240
| 595,240
|
def get_figsize(df, x, hue):
"""Attempt to get a reasonable figure size."""
num_x = len(df[x].unique())
num_hue = len(df[hue].unique())
width_per_vplot = 0.3
width_per_tick = width_per_vplot * num_hue
width = num_x*width_per_tick + 2 # Extra space for axes/etc.
# Just using default value for y for now.
return width, 4.8
|
3c4ac1d7b1d95de51d4765876216ed31bf2b6151
| 369,929
|
def datetime2DateOrNone(value):
"""
Function for converting datetime to date or None
"""
if value is None:
return None
else:
return value.date()
|
b548896d5b004258a482996a5b98adc965540d97
| 215,000
|
def reshape_to_images(x, im_h=None):
"""Reshape set of vectors to images, assuming square or given height."""
if im_h is None:
im_h = int(x.shape[1]**0.5)
im_w = x.shape[1] // im_h
return x.reshape(x.shape[0], im_h, im_w)
|
cf8fb93c32498622678329d2682783b33c4f7c18
| 316,677
|
def has_workflow_stage(artifact, workflow_step_name):
"""
Checks that the artifact's sample's root artifact has been through the given workflow.
:return True if it has False otherwise
"""
for w, status, name in artifact.samples[0].artifact.workflow_stages_and_statuses:
if name == workflow_step_name and status == 'COMPLETE':
return True
return False
|
13d9d4c2e79331bc5f8bec8ebadfca705439442e
| 649,975
|
import torch
def rot_matrix_from_quaternion(q):
"""
Construct rotation matrix from quaternion
"""
# Shortcuts for individual elements (using wikipedia's convention)
qi, qj, qk, qr = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
# Set individual elements
R00 = 1.0 - 2.0 * (qj ** 2 + qk ** 2)
R01 = 2 * (qi * qj - qk * qr)
R02 = 2 * (qi * qk + qj * qr)
R10 = 2 * (qi * qj + qk * qr)
R11 = 1.0 - 2.0 * (qi ** 2 + qk ** 2)
R12 = 2 * (qj * qk - qi * qr)
R20 = 2 * (qi * qk - qj * qr)
R21 = 2 * (qj * qk + qi * qr)
R22 = 1.0 - 2.0 * (qi ** 2 + qj ** 2)
R0 = torch.stack([R00, R01, R02], dim=-1)
R1 = torch.stack([R10, R11, R12], dim=-1)
R2 = torch.stack([R10, R21, R22], dim=-1)
R = torch.stack([R0, R1, R2], dim=-2)
return R
|
80a7a7110bde1377b7a1ed4c77ad67d5fbf6d688
| 121,714
|
def get_stack_id(x, y):
"""Get stack id.
Get the portainer stack id for a given
stack name.
Args:
x: Portainer stack name
y: Deployed portainer stacks
Return:
String portainer stack id
"""
return str(list(filter(lambda z: z['Name'] == x, y))[0]['Id'])
|
71fe86e81683c749ea2fb7cecb73a022a0ae6df2
| 418,064
|
def use(*authenticator_classes):
""" A decorator to attach one or more :class:`Authenticator`'s to the decorated class.
Usage:
from thorium import auth
@auth.use(BasicAuth, CustomAuth)
class MyEngine(Endpoint):
...
OR
@auth.use(BasicAuth)
@auth.use(CustomAuth)
class MyEngine(Endpoint):
...
:param authenticator_classes: One or more :class:`Authenticator` class definitions.
"""
def wrapped(cls):
if not cls._authenticator_classes:
cls._authenticator_classes = []
cls._authenticator_classes.extend(authenticator_classes)
return cls
return wrapped
|
27aeb7711c842540a1ed77a76cebeb61e0342f1e
| 2,905
|
import random
def generate_int_list(list=[], length=10, min_value=0, max_value=10):
"""Generate and return a list of random integers.
The random values will be between min_value and
max_value - 1. If list's length were less than length,
it'll be completed with random values until list's
length were equal to length.
"""
# Using a variable to check list length, avoid calling
# +the same function (len()) more than once.
length_list = len(list)
while length_list < length:
list.append(random.randrange(min_value, max_value))
length_list += 1
return list
|
f80ce3edd5cd1ca4189d1cda9c3d151ff4943d50
| 19,803
|
def tostr(s):
"""Stringify sequence s."""
return ''.join(s)
|
8d27f8b331083c5b8ed9ae28a3fa22904ba55871
| 163,239
|
def to_netstring(buff):
"""
Converts a buffer into a netstring.
>>> to_netstring(b'hello')
b'5:hello,'
>>> to_netstring(b'with a nul\\x00')
b'11:with a nul\\x00,'
"""
bytes_length = str(len(buff)).encode('ascii')
return bytes_length + b':' + buff + b','
|
eae0f8f3c06f14d9e8d281287386c31d1b5df33f
| 553,570
|
def is_app_code(code: int) -> bool:
"""
Checks whether a code is part of the app range.
:param code: Code to check.
:return: Boolean indicating whether `code` is within the app range.
"""
return 0 < code < 0x10
|
d0bd6485875500418b5ddd60ae5fb3c9b965b71f
| 48,154
|
def gen_reg (class_names):
""" Generates registration calls for funtions with the given class names.
Args:
class_names (list of str): The class names.
Returns:
str: The registration calls.
"""
out = ""
for class_name in class_names:
if len(out) > 0:
out += '\n '
#out += f'evaluator.addFunction(new {class_name}());'
out += f'new {class_name}(),'
out = out.rstrip(',')
return out
|
8ae9adc319dd4a2923ab9cb3fd8cec2a2ae9301b
| 115,545
|
def get_attribute_name(node_and_attribute):
"""
For a string node.attribute, return the attribute portion
"""
split = node_and_attribute.split('.')
attribute = ''
if split and len(split) > 1:
attribute = '.'.join(split[1:])
return attribute
|
a23e515c63e1c3e2d6843b8efe8088092bd783d0
| 587,877
|
from typing import Tuple
def get_current_coins(acc_details:dict) -> Tuple[list,list]:
"""
From account details get the non zero valued coins
Arguments:
acc_details - account details from Spot().account()
Returns:
list -> Non-zero free coins
list -> Non-zero locked coins
"""
balances = acc_details["balances"]
free_balances = []
locked_balances = []
for balance in balances:
asset, free, locked = balance.values()
if float(locked) != 0.0:
locked_balances.append(balance)
if float(free) != 0.0:
free_balances.append(balance)
return free_balances,locked_balances
|
c420cb1bb9751b348305c888ff1c6449397134c0
| 323,552
|
def is_symspec(symspec):
"""
returns True if `symspec` can be used as a symbol specification.
"""
if not hasattr(symspec, 'name'):
return False
if not hasattr(symspec, 'prec'):
return False
return True
|
5bee27e24f68009727ab5320bd577d73be4eb62c
| 367,098
|
def prompt_chars(prompt: str, chars: str) -> str:
"""Prompt the user with a multiple-choice question."""
said = ""
while said not in list(chars):
said = input(f"{prompt} [{chars}]> ").lower()
return said
|
f01719f216b4dee16cedd00722731374aa65291c
| 121,055
|
def extend(*dicts):
"""Create a new dictionary from multiple existing dictionaries
without overwriting."""
new_dict = {}
for each in dicts:
new_dict.update(each)
return new_dict
|
e5f6e4797eab6cc6c6b2c23f0766b6ff23f5f8e1
| 682,630
|
def get_bcg_coverage(database, country_iso_code):
"""
extract bcg coverage from inputs database
:param database: sql database
database containing the bcg data
:param country_iso_code: string
three letter ISO3 code for the country of interest
:return: dict
pandas data frame with columns years and one row containing the values of BCG coverage in that year
"""
_bcg_coverage = database.db_query("BCG", conditions=["ISO_code='" + country_iso_code + "'"])
_bcg_coverage = _bcg_coverage.filter(
items=[column for column in _bcg_coverage.columns if column.isdigit()]
)
return {
int(key): value / 1e2
for key, value in zip(list(_bcg_coverage.columns), _bcg_coverage.loc[0, :])
if value is not None
}
|
47c7c252af9e20dcbf96ef483fdff79b93bfea07
| 491,419
|
def convert_sorting(sortings):
"""Convert a V3 sort parameter into the V4 orderBys field.
Args:
sortings: A string representing the V3 sort parameter.
Returns:
A list of V4 orderBy objects.
"""
order_bys = []
for sorting in sortings.split(','):
order_by = {}
order_by['orderType'] = 'VALUE'
if sorting.startswith('-'):
order_by['fieldName'] = sorting[1:]
order_by['sortOrder'] = 'DESCENDING'
else:
order_by['fieldName'] = sorting
order_bys.append(order_by)
return order_bys
|
3ad2bae0b7aa3d865fbd05d90f5f95169e4345e2
| 297,255
|
def filter_by_extension(ext):
"""
A higher-order function that returns a function
that given a filename filters by the extension
argument.
:param ext: the return function will return true if a filename ends with ext
:return: a one-arg function that takes a filename and returns true if filename ends with ext
"""
def filt(filename):
return filename.endswith(ext)
return filt
|
f4ec9e30bf867af29101226c23335c6328e6d032
| 107,071
|
def user(mocker):
"""Fake User instance."""
user = mocker.Mock()
user.id = "001"
user.email = "foo@bar.com" # /PS-IGNORE
return user
|
21ff2c3c12f450a4e202a1ff75c427118fc56cd2
| 170,846
|
def chunk(mylist, chunksize):
"""
Args:
mylist: array
chunksize: int
Returns:
list of chunks of an array len chunksize (last chunk is less)
"""
N = len(mylist)
chunks = list(range(0, N, chunksize)) + [N]
return [mylist[i:j] for i, j in zip(chunks[:-1], chunks[1:])]
|
69cc8aa812c989c63dae4c444ee132c54a861fa4
| 17,986
|
import _ast
def BinOpMap(operator):
"""Maps operator strings for binary operations to their _ast node."""
op_dict = {
'+': _ast.Add,
'-': _ast.Sub,
'*': _ast.Mult,
'**': _ast.Pow,
'/': _ast.Div,
'//': _ast.FloorDiv,
'%': _ast.Mod,
'<<': _ast.LShift,
'>>': _ast.RShift,
'|': _ast.BitOr,
'&': _ast.BitAnd,
'^': _ast.BitXor,
}
return op_dict[operator]()
|
0b332b1043b31b123daf8812e6f2ecb4e3974f19
| 9,128
|
def _basis_bitstring(i, num_qubits):
"""Create vector corresponding to i-th basis vector of num_qubits system."""
return [int(char) for char in bin(i)[2:].zfill(num_qubits)]
|
bbecb12400e1867274b3465cc37590ad37908c28
| 379,032
|
def _get_realm(response):
"""Return authentication realm requested by server for 'Basic' type or None
:param response: requests.response
:type response: requests.Response
:returns: realm
:rtype: str | None
"""
if 'www-authenticate' in response.headers:
auths = response.headers['www-authenticate'].split(',')
basic_realm = next((auth_type for auth_type in auths
if auth_type.rstrip().lower().startswith("basic")),
None)
if basic_realm:
realm = basic_realm.split('=')[-1].strip(' \'\"').lower()
return realm
else:
return None
else:
return None
|
346b3278eb52b565f747c952493c15820eece729
| 708,344
|
def TourType_idx_rule(M):
"""
Index is (start window, tour type)
:param M: Model
:return: Variable index (list of tuples)
"""
return [(i, t) for i in M.WINDOWS
for t in M.activeTT
if (i, t) in M.okTourType]
|
b017f2d1156b38133da43c5922293aa58d5a3de0
| 291,660
|
def no_none_get(dictionary, key, alternative):
"""Gets the value for a key in a dictionary if it exists and is not None.
dictionary is where the value is taken from.
key is the key that is attempted to be retrieved from the dictionary.
alternative is what returns if the key doesn't exist."""
if key in list(dictionary.keys()):
if dictionary[key] is not None:
return dictionary[key]
else:
return alternative
else:
return alternative
|
68b6f1d3cdd736f5f373093058e630db039be781
| 24,413
|
def transform_schema(actions, schema):
"""Transform schema according to actions.
Args:
actions (list): actions to run
schema (pyarrow.Schema): original schema
Returns:
pyarrow.Schema: Transformed schema
"""
for action in actions:
schema = action.schema(schema)
return schema
|
c37f9cf5c24ab49a1a10caed386c016bf123bc24
| 521,363
|
def bucket_by_length(words):
"""Bucket a list of words based on their lengths"""
num_buckets = list(set([len(x) for x in words]))
buckets = dict()
for x in num_buckets:
buckets[x] = list()
for word in words:
buckets[len(word)].append(word)
return buckets
|
d3a3fd6ff2cd580712fd5933e11918d5e3b2dd5f
| 485,371
|
def task_config_to_dict(task_config):
""" Convert a task config to a dict and remove all empty keys """
dconf = dict(task_config)
for k in list(dconf.keys()):
if not dconf[k]:
del dconf[k]
return dconf
|
acc23d4881a0eb2ae9ea67733efae4127c077192
| 145,727
|
def first_non_empty(data_or_instance, field_or_fields, default=None):
"""
Return the first non-empty attribute of `instance` or `default`
:type data_or_instance: object or dict
:param data_or_instance: the instance or the resource
:type field_or_fields: str or tuple or list
:param field_or_fields: the field or fields to look for on the resource
:type default: anything
:param default: the default value to return if no non-empty field was found, default to None
:return: the first non-empty field of `instance` or `default`
"""
# Convert `data_or_instance` to an object-like structure
# so attributes can be fetched with `getattr` regardless of the initial type.
if isinstance(data_or_instance, dict):
class ObjectView(object):
def __init__(self, d):
self.__dict__ = d
obj = ObjectView(data_or_instance)
else:
obj = data_or_instance
# Find the first non-empty.
if isinstance(field_or_fields, str):
return getattr(obj, field_or_fields, default)
elif isinstance(field_or_fields, (tuple, list)):
for field in field_or_fields:
val = getattr(obj, field, None)
if val:
return val
return default
|
9be9d7fddcfc3b71b92ca12fb8949d85ad4cb342
| 672,593
|
def _get_fields(events):
"""
Returns a list of all fields in the given event set.
@param events: The events as a list of dictionaries.
@type events: list(dict(str: str))
@return: All the fields.
@rtype: set(str)
"""
fields = set()
for event in events:
fields.update(list(event.keys()))
return fields
|
1028e30ea761f4d8397a042863a243e71172539c
| 62,279
|
def rightpad(x, c, w):
"""Rightpad string `x` with `c` using width `w`.
"""
return x + c * (w - len(x))
|
cefcf48f3f60ad62b9d1b745bed8a1fe4086eca6
| 370,968
|
import logging
def logger(request):
"""Sets up a logger at loglevel 1 and attaches a LogHandler."""
logger_ = logging.getLogger(request.function.__name__)
logger_.setLevel(1)
return logger_
|
25e12b5222c17ff9bc2c421099c4042bc5465b6b
| 325,018
|
def split_config_args(args):
"""Split -[-]name=value configuration command-line arguments."""
res = []
for arg in args:
if arg.startswith('-'):
for part in arg.split('=', 1):
res.append(part)
else:
res.append(arg)
return res
|
b08e16ac24edd694b793d1b2ea9c6db88b939083
| 90,078
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.