content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def skip(line):
"""Returns true if line is all whitespace or shebang."""
stripped = line.lstrip()
return stripped == '' or stripped.startswith('#!') | 5,329,300 |
def get_dss_client(deployment_stage: str):
"""
Returns appropriate DSSClient for deployment_stage.
"""
dss_env = MATRIX_ENV_TO_DSS_ENV[deployment_stage]
if dss_env == "prod":
swagger_url = "https://dss.data.humancellatlas.org/v1/swagger.json"
else:
swagger_url = f"https://dss.{ds... | 5,329,301 |
def bounce_off(bounce_obj_rect: Rect, bounce_obj_speed,
hit_obj_rect: Rect, hit_obj_speed):
"""
The alternative version of `bounce_off_ip`. The function returns the result
instead of updating the value of `bounce_obj_rect` and `bounce_obj_speed`.
@return A tuple (`new_bounce_obj_rect`, `new_bounce_... | 5,329,302 |
async def test_storage_is_removed_idempotent(hass):
"""Test entity map storage removal is idempotent."""
await setup_platform(hass)
entity_map = hass.data[ENTITY_MAP]
hkid = '00:00:00:00:00:01'
assert hkid not in entity_map.storage_data
entity_map.async_delete_map(hkid)
assert hkid not i... | 5,329,303 |
def Landsat_Reflect(Bands,input_folder,Name_Landsat_Image,output_folder,shape_lsc,ClipLandsat,Lmax,Lmin,ESUN_L5,ESUN_L7,ESUN_L8,cos_zn,dr,Landsat_nr, proyDEM_fileName):
"""
This function calculates and returns the reflectance and spectral radiation from the landsat image.
"""
Spec_Rad = np.zeros((... | 5,329,304 |
def plot_footprint(img_file_name, camera_file,
reference_dem, output_directory=None,
basemap='ctx', cam_on=True,
verbose=False):
# TODO
# - Add tsai camera plotting.
"""
Function to plot camera footprints.
"""
... | 5,329,305 |
def second(lst):
"""Same as first(nxt(lst)).
"""
return first(nxt(lst)) | 5,329,306 |
def gaussian_noise(height, width):
"""
Create a background with Gaussian noise (to mimic paper)
"""
# We create an all white image
image = np.ones((height, width)) * 255
# We add gaussian noise
cv2.randn(image, 235, 10)
return Image.fromarray(image).convert("RGBA") | 5,329,307 |
def draw_box(image, box, color):
"""Draw 3-pixel width bounding boxes on the given image array.
color: list of 3 int values for RGB.
"""
y1, x1, y2, x2 = box
image[y1:y1 + 1, x1:x2] = color
image[y2:y2 + 1, x1:(x2+1)] = color
image[y1:y2, x1:x1 + 1] = color
image[y1:y2, x2:x2 + 1] = colo... | 5,329,308 |
def get_statuses_one_page(weibo_client, max_id=None):
"""获取一页发布的微博
"""
if max_id:
statuses = weibo_client.statuses.user_timeline.get(max_id=max_id)
else:
statuses = weibo_client.statuses.user_timeline.get()
return statuses | 5,329,309 |
def do_nothing(ax):
"""Do not add any watermark."""
return ax | 5,329,310 |
def exec_lm_pipe(taskstr):
"""
Input: taskstr contains LM calls separated by ;
Used for execute config callback parameters (IRQs and BootHook)
"""
try:
# Handle config default empty value (do nothing)
if taskstr.startswith('n/a'):
return True
# Execute individual ... | 5,329,311 |
def term_size():
"""Print out a sequence of ANSI escape code which will report back the
size of the window.
"""
# ESC 7 - Save cursor position
# ESC 8 - Restore cursor position
# ESC [r - Enable scrolling for entire display
# ESC [row;colH - Move to cursor position
... | 5,329,312 |
def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lin... | 5,329,313 |
def group_sharing(msg):
"""
处理群分享
:param msg:
:return:
"""
if not (config.IS_LISTEN_GROUP and config.IS_LISTEN_SHARING):
return
group = msg.chat.name
if group not in DataBase.all_listen_group():
return
sender = msg.member.name
msg.forward(bot.file_helper, prefix... | 5,329,314 |
def get_dashboard(request, project_id):
"""
Load Project Dashboard to display Latest Cost Estimate and List of Changes
"""
project = get_object_or_404(Project, id=project_id)
# required to determine permission of user,
# if not a project user then project owner
try:
project_user = P... | 5,329,315 |
def _scan_real_end_loop(bytecode, setuploop_inst):
"""Find the end of loop.
Return the instruction offset.
"""
start = setuploop_inst.next
end = start + setuploop_inst.arg
offset = start
depth = 0
while offset < end:
inst = bytecode[offset]
depth += inst.block_effect
... | 5,329,316 |
def six_node_range_5_to_0_bst():
"""Six nodes covering range five to zero."""
b = BST([5, 4, 3, 2, 1, 0])
return b | 5,329,317 |
def hello_datamine(name: str = 'student') -> None:
"""Prints a hello message to a Data Mine student.
Args:
str (name, optional): The name of a student. Defaults to 'student'.
"""
msg = f'Hello {name}! Welcome to The Data Mine!'
print(msg) | 5,329,318 |
def IndividualsInAlphabeticOrder(filename):
"""Checks if the names are in alphabetic order"""
with open(filename, 'r') as f:
lines = f.readlines()
individual_header = '# Individuals:\n'
if individual_header in lines:
individual_authors = lines[lines.index(individual_header) + 1:]
sorted_auth... | 5,329,319 |
def preprocess_img_imagenet(img_path):
"""Preprocessing required for ImageNet classification.
Reference:
https://github.com/onnx/models/tree/master/vision/classification/vgg
"""
import mxnet
from mxnet.gluon.data.vision import transforms
from PIL import Image
img = Image.open(img_path... | 5,329,320 |
def create_lambertian(color):
"""
create a lambertion material
"""
material = bpy.data.materials.new(name="Lambertian")
material.use_nodes = True
nodes = material.node_tree.nodes
# remove principled
material.node_tree.nodes.remove(
material.node_tree.nodes.get('Principled BSDF')... | 5,329,321 |
def submission_view(request, locker_id, submission_id):
"""Displays an individual submission"""
submission = get_object_or_404(Submission, pk=submission_id)
newer = submission.newer()
newest = Submission.objects.newest(submission.locker)
if not newest:
newest = submission
oldest = Submis... | 5,329,322 |
def add_filename_suffix(file_path: str, suffix: str) -> str:
"""
Append a suffix at the filename (before the extension).
Args:
path: pathlib.Path The actual path object we would like to add a suffix
suffix: The suffix to add
Returns: path with suffix appended at the end of the filename a... | 5,329,323 |
def list_dropdownTS(dic_df):
"""
input a dictionary containing what variables to use, and how to clean
the variables
It outputs a list with the possible pair solutions.
This function will populate a dropdown menu in the eventHandler function
"""
l_choice = []
for key_cat, value_cat in d... | 5,329,324 |
def _check_declared_tests_exist(config, tests_root_dir):
"""Check that all the tests declared in the config file correspond to actual valid test functions"""
logging.info("Checking that configured tests exist")
test_functions = discover_all_test_functions(tests_root_dir)
unused_test_functions = deepcopy... | 5,329,325 |
def get_voice_combinations(**kwargs):
"""
Gets k possible combinations of voices from a list of voice indexes. If k is None, it will return all possible
combinations. The combinations are of a minimum size min_n_voices_to_remove and a max size
max_n_voices_to_remove. When choosing a k number a combinati... | 5,329,326 |
def del_contact(credential):
"""This class gives the application the ability to delete different user inputs or details"""
credential.delete_credential() | 5,329,327 |
def data(request):
"""This is a the main entry point to the Data tab."""
context = cache.get("data_tab_context")
if context is None:
context = data_context(request)
cache.set("data_tab_context", context, 29)
return render(request, "rundb/data/data.html", context) | 5,329,328 |
def setup_root(name: str) -> DLogger:
"""Create the root logger."""
logger = get_logger(name)
msg_format = "%(message)s"
level_style = {
"critical": {"color": "magenta", "bright": True, "bold": True},
"debug": {"color": "green", "bright": True, "bold": True},
"error": {"color":... | 5,329,329 |
def from_pickle(
filepath: typing.Union[str, pathlib.Path, typing.IO[bytes]]
) -> typing.Union[Categorization, HierarchicalCategorization]:
"""De-serialize Categorization or HierarchicalCategorization from a file written by
to_pickle.
Note that this uses the pickle module, which executes arbitrary code... | 5,329,330 |
def recostruct(encoded, weights, bias):
"""
Reconstructor : Encoded -> Original
Not Functional
"""
weights.reverse()
for i,item in enumerate(weights):
encoded = encoded @ item.eval() + bias[i].eval()
return encoded | 5,329,331 |
def add_parser_arguments(parser):
""" Add the arguments required by all types of criterion here.
Please add task-specific criterion arguments into the function
of the same name in 'task/xxx/criterion.py'
"""
pass | 5,329,332 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR multiplied by factor 0.1 for every 10 epochs"""
if not ((epoch + 1) % 10):
factor = 0.1
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * factor | 5,329,333 |
def get_file_dataset_from_trixel_id(CatName,index,NfilesinHDF,Verbose=True):#get_file_var_from_htmid in Eran's library
"""Description: given a catalog basename and the index of a trixel and the number of trixels in an HDF5 file,
create the trixel dataset name
Input :- CatName
... | 5,329,334 |
def calc_element_column(NH, fmineral, atom, mineral, d2g=0.009):
"""
Calculate the column density of an element for a particular NH value,
assuming a dust-to-gas ratio (d2g) and the fraction of dust in that
particular mineral species (fmineral)
"""
dust_mass = NH * mp * d2g * fmineral # g cm^{-... | 5,329,335 |
def test_retrieve_notification_as_owner(notification):
"""Tests if a logged in user can retrieve it's own notification"""
client = get_api_client(user=notification.user)
url = _get_notification_url(notification)
response = client.get(url)
assert response.status_code == status.HTTP_200_OK | 5,329,336 |
def output_dot(sieve, column_labels=None, max_edges=None, filename='structure.dot'):
""" A network representation of the structure in Graphviz format. Units in the produced file
are in bits. Weight is the mutual information and tc is the total correlation.
"""
print """Compile by installing graphviz... | 5,329,337 |
def projectSimplex_vec(v):
""" project vector v onto the probability simplex
Parameter
---------
v: shape(nVars,)
input vector
Returns
-------
w: shape(nVars,)
projection of v onto the probability simplex
"""
nVars = v.shape[0]
mu = np.sort(v,kind='quicksort')[:... | 5,329,338 |
def display_c(c, font, screen, lcd, size=5, x=0, y=0):
"""
Displays a character in the given `font` with top-left corner at the specified `x` and `y` coordinates
`c`: A character
`font`: A font dictionary
`size`: An integer from 1-10, 10 being max size that can fit the display
"""
char ... | 5,329,339 |
def render_list(something: Collection, threshold: int, tab: str) -> List[str]:
"""
Разложить список или что то подобное
"""
i = 1
sub_storage = []
order = '{:0' + str(len(str(len(something)))) + 'd}'
for element in something:
if isinstance(element, Sized) and len(element) > thresho... | 5,329,340 |
def combine_result(
intent_metrics: IntentMetrics,
entity_metrics: EntityMetrics,
response_selection_metrics: ResponseSelectionMetrics,
interpreter: Interpreter,
data: TrainingData,
intent_results: Optional[List[IntentEvaluationResult]] = None,
entity_results: Optional[List[EntityEvaluationR... | 5,329,341 |
def get_fns_for_jobid(jobid):
"""Given a job ID number, return a list of that job's data files.
Input:
jobid: The ID number from the job-tracker DB to get files for.
Output:
fns: A list of data files associated with the job ID.
"""
import jobtracker
que... | 5,329,342 |
def linear_schedule(initial_value: float):
"""
Linear learning rate schedule.
:param initial_value: Initial learning rate.
:return: schedule that computes
current learning rate depending on remaining progress
"""
def func(progress_remaining: float) -> float:
"""
... | 5,329,343 |
def download(os_list, software_list, dst):
"""
按软件列表下载其他部分
"""
if os_list is None:
os_list = []
arch = get_arch(os_list)
LOG.info('software arch is {0}'.format(arch))
results = {'ok': [], 'failed': []}
no_mindspore_list = [software for software in software_list if "MindSpore" no... | 5,329,344 |
def get_hash_bin(shard, salt=b"", size=0, offset=0):
"""Get the hash of the shard.
Args:
shard: A file like object representing the shard.
salt: Optional salt to add as a prefix before hashing.
Returns: Hex digetst of ripemd160(sha256(salt + shard)).
"""
shard.seek(0)
digest =... | 5,329,345 |
def upgrade() -> None:
"""Upgrade."""
staticschema = config["schema_static"]
# Instructions
op.create_table(
"oauth2_client",
Column("id", Integer, primary_key=True),
Column("client_id", Unicode, unique=True),
Column("secret", Unicode),
Column("redirect_uri", Uni... | 5,329,346 |
def boltzmann_statistic(
properties: ArrayLike1D,
energies: ArrayLike1D,
temperature: float = 298.15,
statistic: str = "avg",
) -> float:
"""Compute Boltzmann statistic.
Args:
properties: Conformer properties
energies: Conformer energies (a.u.)
temperature: Temperature (... | 5,329,347 |
def test_mypy_unmatched_stdout(testdir):
"""Verify that unexpected output on stdout from mypy is printed."""
stdout = 'This is unexpected output on stdout from mypy.'
testdir.makepyfile(conftest='''
import mypy.api
def _patched_run(*args, **kwargs):
return '{stdout}', '', 1
... | 5,329,348 |
def _check_n_pca_components(ica, _n_pca_comp, verbose=None):
"""Aux function"""
if isinstance(_n_pca_comp, float):
_n_pca_comp = ((ica.pca_explained_variance_ /
ica.pca_explained_variance_.sum()).cumsum()
<= _n_pca_comp).sum()
logger.info('Selected %... | 5,329,349 |
def main():
""" Calls the other functions to test them. """
print()
print("Un-comment and re-comment calls in MAIN one by one as you work.")
# run_test_multiply_numbers()
# run_test_print_characters()
# run_test_print_characters_slanted() | 5,329,350 |
def parse(text):
"""
This is what amounts to a simple lisp parser for turning the server's
returned messages into an intermediate format that's easier to deal
with than the raw (often poorly formatted) text.
This parses generally, taking any lisp-like string and turning it into a
list of nested... | 5,329,351 |
def plot_all(graph, plot_id=''):
"""plot topology graph"""
plt.close()
fig = plt.figure()
fig.canvas.mpl_connect('button_press_event', util.onclick)
lane_middle_point_map = {}
for i, (nd, color) in enumerate(zip(graph.node, color_iter)):
nd_mid_pt = plot_node(nd, plot_id, color)
... | 5,329,352 |
def model_fn():
"""
Renvoie un modèle Inception3 avec la couche supérieure supprimée et les poids pré-entraînés sur imagenet diffusés.
"""
model = InceptionV3(
include_top=False, # Couche softmax de classification supprimée
weights='imagenet', # Poids pré-entraînés sur Imagenet
# input... | 5,329,353 |
def err(msg):
"""Yeah, this is an obnoxious error message, but the user will have to
pick it out of a long scroll of LaTeX and make output.
"""
sys.stderr.write("BEGIN PIPELINE ERROR MSG\n")
sys.stderr.write(msg)
sys.stderr.write("\n")
sys.stderr.write("END PIPELINE ERROR MSG\n")
sys.ex... | 5,329,354 |
def find_correspondance_date(index, csv_file):
"""
The method returns the dates reported in the csv_file for the i-subject
:param index: index corresponding to the subject analysed
:param csv_file: csv file where all the information are listed
:return date
"""
return csv_f... | 5,329,355 |
def get_config(object_config_id):
"""
Returns current and previous config
:param object_config_id:
:type object_config_id: int
:return: Current and previous config in dictionary format
:rtype: dict
"""
fields = ('config', 'attr', 'date', 'description')
try:
object_config = O... | 5,329,356 |
def find_similarity(long_sequence, short_sequence, match, maximum, homology):
"""
This function can find which part of the long DNA sequence best matches the short DNA sequence and it finally shows
the similarity and the best-matching strand.
"""
for i in range(len(long_sequence)-len(short_sequence)... | 5,329,357 |
def normalize_to_ascii(char):
"""Strip a character from its accent and encode it to ASCII"""
return unicodedata.normalize("NFKD", char).encode("ascii", "ignore").lower() | 5,329,358 |
def verify_certificate_chain(certificate, intermediates, trusted_certs, logger):
"""
:param certificate: cryptography.x509.Certificate
:param intermediates: list of cryptography.x509.Certificate
:param trusted_certs: list of cryptography.x509.Certificate
Verify that the certificate is valid, accord... | 5,329,359 |
def create_forcingfile(meteo_fp, output_file, dir_save, lat, lon, P_unit, timezone=+2.0, fpar=0.45, CO2_constant=False):
"""
Create forcing file from meteo.
Args:
meteo_fp (str): file path to meteofile
output_file (str): name of output file (.csv not included)
dir_save (str): output ... | 5,329,360 |
def distribute_py_test(
name,
srcs = [],
deps = [],
tags = [],
data = [],
main = None,
args = [],
shard_count = 1,
**kwargs):
"""Generates py_test targets for CPU and GPU.
Args:
name: test target name to generate suffixed with `tes... | 5,329,361 |
def test_csv_file_validation(test_import_dir):
"""Create and populate a *.csv file for testing Validation import mapping."""
_test_file = TMP_DIR + "/test_inputs_validation.csv"
with open(_test_file, "w") as _csv_file:
filewriter = csv.writer(
_csv_file, delimiter=";", quotechar="|", qu... | 5,329,362 |
def update_strip_chart_data(_n_intervals, acq_state, chart_data_json_str,
samples_to_display_val, active_channels):
"""
A callback function to update the chart data stored in the chartData HTML
div element. The chartData element is used to store the existing data
values, whi... | 5,329,363 |
def etl(fp_source, fp_export, split=None, suffix=None):
"""Read, transform and save datasets.
"""
# get the dataset name
dataset_name = Path(args.s).stem
# read file
df = pd.read_csv(fp_source, sep=None, engine="python")
# # remove records with missing abstracts
# df = df.d... | 5,329,364 |
def genuuid():
"""Generate a random UUID4 string."""
return str(uuid.uuid4()) | 5,329,365 |
def watsons_f(DI1, DI2):
"""
calculates Watson's F statistic (equation 11.16 in Essentials text book).
Parameters
_________
DI1 : nested array of [Dec,Inc] pairs
DI2 : nested array of [Dec,Inc] pairs
Returns
_______
F : Watson's F
Fcrit : critical value from F table
"""
... | 5,329,366 |
def encode(integer_symbol, bit_count):
""" Returns an updated version of the given symbol list with the given symbol encoded into binary.
- `symbol_list` - the list onto which to encode the value.
- `integer_symbol` - the integer value to be encoded.
- `bit_count` - the number of bits from ... | 5,329,367 |
def superkick(update, context):
"""Superkick a member from all rooms by replying to one of their messages with the /superkick command."""
bot = context.bot
user_id = update.message.from_user.id
boot_id = update.message.reply_to_message.from_user.id
username = update.message.reply_to_message.from_use... | 5,329,368 |
def encrypt_session(
signer: typing.Type[Fernet],
session_id: str,
current_time: typing.Optional[typing.Union[int, datetime]] = None,
) -> str:
"""An utility for generating a token from the passed session id.
:param signer: an instance of a fernet object
:param session_id: a user session id
... | 5,329,369 |
def log_params_to_mlflow(
config: Dict[str, Any],
prefix: Optional[str] = None,
) -> None:
"""Log parameters to MLFlow. Allows nested dictionaries."""
nice_config = to_dot(config, prefix=prefix)
# mlflow can only process 100 parameters at once
keys = sorted(nice_config.keys())
batch_size = 1... | 5,329,370 |
def delete_variants_task(req):
"""Perform the actual task of removing variants from the database after receiving an delete request
Accepts:
req(flask.request): POST request received by server
"""
db = current_app.db
req_data = req.json
dataset_id = req_data.get("dataset_id")
samples... | 5,329,371 |
def construct_chargelst(nsingle):
"""
Makes list of lists containing Lin indices of the states for given charge.
Parameters
----------
nsingle : int
Number of single particle states.
Returns
-------
chargelst : list of lists
chargelst[charge] gives a list of state indic... | 5,329,372 |
def parse(json_string):
"""Constructs the Protocol from the JSON text."""
try:
json_data = json.loads(json_string)
except:
raise ProtocolParseException('Error parsing JSON: %s' % json_string)
# construct the Avro Protocol object
return make_avpr_object(json_data) | 5,329,373 |
def create_script_dict(allpacks, path, file, skip_lines):
"""Create script dict or skips file if resources cannot be made"""
allpacks["name"] = "FILL"
allpacks["title"] = "FILL"
allpacks["description"] = "FILL"
allpacks["citation"] = "FILL"
allpacks["licenses"] = [{"name": "FILL"}]
allpacks[... | 5,329,374 |
def get_architecture(model_config: dict, feature_config: FeatureConfig, file_io):
"""
Return the architecture operation based on the model_config YAML specified
"""
architecture_key = model_config.get("architecture_key")
if architecture_key == ArchitectureKey.DNN:
return DNN(model_config, fe... | 5,329,375 |
def get_properties_dict(serialized_file: str, sparql_file: str, repository: str, endpoint: str, endpoint_type: str,
limit: int = 1000) -> ResourceDictionary:
"""
Return a ResourceDictionary with the list of properties in the ontology
:param serialized_file: The file where the propert... | 5,329,376 |
def get_duplicate_sample_ids(taxonomy_ids):
"""Get duplicate sample IDs from the taxonomy table.
It happens that some sample IDs are associated with more than taxon. Which
means that the same sample is two different species. This is a data entry
error and should be removed. Conversely, having more than... | 5,329,377 |
def get_settings_text(poll):
"""Compile the options text for this poll."""
text = []
locale = poll.user.locale
text.append(i18n.t('settings.poll_type',
locale=locale,
poll_type=translate_poll_type(poll.poll_type, locale)))
text.append(i18n.t('settings.l... | 5,329,378 |
def resize_pic(pic_path, new_width, new_height):
"""缩放图像并保存副本
"""
# 图像缩放
img = Image.open(pic_path)
img = img.resize((new_width, new_height), Image.ANTIALIAS)
# 副本路径定义(去掉原有扩展名, 加上_resize.png后缀)
new_pic_path = os.path.splitext(pic_path)[0] + '_resize.png'
# 保存副本
img.save(new_pic_path) | 5,329,379 |
def download_model(model_path, region):
"""
Downloads a model to a local file.
MODEL_PATH The path to download the model to, ending with the name of the model.
"""
impl_download_model(model_path, ensure_s3_bucket(region), region) | 5,329,380 |
def acd(strymobj= None, window_size=30, plot_iteration = False, every_iteration = 200, plot_timespace = True, save_timespace = False, wave_threshold = 50.0, animation = False, title = 'Average Centroid Distance', **kwargs):
"""
Average Centroid Distance Algorithm for calculating stop-and-go wavestrength from
... | 5,329,381 |
def pass_none(func):
"""
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
"""
@functools.wraps(func)
def wrapper(param, *args, **kwargs):
if param is not None:
return func(param, *args, **kwargs)
return wrapper | 5,329,382 |
def _clean_dataframe(dataframe, required_columns=None, lower_case_col_names=True):
"""
inputs:
dataframe: pandas dataframe
required_columns: list of column names that must have a non-NA values
lower_case_col_names: should column names be modified to lower case
Modifies dataframe in p... | 5,329,383 |
def test_no_update_available_with_no_update_string_and_color_no_updates(
fake_qtile, fake_window
):
""" test output with no update (with dedicated string and color) """
cu4 = CheckUpdates(distro=good_distro,
custom_command=cmd_0_line,
no_update_string=nus,
... | 5,329,384 |
def _p_qrs_tconst(pattern, pwave):
"""
Temporal constraints of the P Wave wrt the corresponding QRS complex
"""
BASIC_TCONST(pattern, pwave)
obseq = pattern.obs_seq
idx = pattern.get_step(pwave)
if idx == 0 or not isinstance(obseq[idx - 1], o.QRS):
return
qrs = obseq[idx - 1]
... | 5,329,385 |
def test_trunc():
""" Test trunc """
assert trunc('', 3) == ''
assert trunc('foo', 3) == 'foo'
assert trunc('foobar', 6) == 'foobar'
assert trunc('foobar', 5) == 'fo...' | 5,329,386 |
def create_values_key(key):
"""Creates secondary key representing sparse values associated with key."""
return '_'.join([key, VALUES_SUFFIX]) | 5,329,387 |
def make_mask(variable, **flags):
"""
Return a mask array, based on provided flags
For example:
make_mask(pqa, cloud_acca=False, cloud_fmask=False, land_obs=True)
OR
make_mask(pqa, **GOOD_PIXEL_FLAGS)
where GOOD_PIXEL_FLAGS is a dict of flag_name to True/False
:param variable:
... | 5,329,388 |
def _normalize_block_comments(content: str) -> str:
"""Add // to the beginning of all lines inside a /* */ block"""
comment_partitions = _partition_block_comments(content)
normalized_partitions = []
for partition in comment_partitions:
if isinstance(partition, Comment):
comment = pa... | 5,329,389 |
def check_holidays(date_start, modified_end_date, holidays):
"""
Here app check if holidays in dates of vacation or not.
If Yes - add days to vacation, if Not - end date unchangeable
"""
# first end date for check loop because end date move +1 for every weekend
date_1 = datetime.strptime(d... | 5,329,390 |
def getHouseholdProfiles(
n_persons,
weather_data,
weatherID,
seeds=[0],
ignore_weather=True,
mean_load=True,
cores=mp.cpu_count() - 1,
):
"""
Gets or creates the relevant occupancy profiles for a building
simulation or optimization.
Parameters
----------
n_... | 5,329,391 |
def find_centroid(restaurants):
"""Return the centroid of the locations of RESTAURANTS."""
"*** YOUR CODE HERE ***" | 5,329,392 |
def get_local_ffmpeg() -> Optional[Path]:
"""
Get local ffmpeg binary path.
### Returns
- Path to ffmpeg binary or None if not found.
"""
ffmpeg_path = Path(
get_spotdl_path(), "ffmpeg" + ".exe" if platform.system() == "Windows" else ""
)
if ffmpeg_path.is_file():
retu... | 5,329,393 |
def remaining_time(trace, event):
"""Calculate remaining time by event in trace
:param trace:
:param event:
:return:
"""
# FIXME using no timezone info for calculation
event_time = event['time:timestamp'].strftime("%Y-%m-%dT%H:%M:%S")
last_time = trace[-1]['time:timestamp'].strftime("%Y... | 5,329,394 |
def _water_vapor_pressure_difference(temp, wet_bulb_temp, vap_press, psych_const):
"""
Evaluate the psychrometric formula
e_l - (e_w - gamma * (T_a - T_w)).
Parameters
----------
temp : numeric
Air temperature (K).
wet_bulb_temp : numeric
Wet-bulb temperature (K).
... | 5,329,395 |
def bank_left(midiout):
"""
Will send the note 46, that shifts the bank left
"""
# Send the message
message = mido.Message('note_on', note=46, velocity = 127)
midiout.send(message) | 5,329,396 |
def _service_description_required(func):
"""
Decorator for checking whether the service description is available on a device's service.
"""
@wraps(func)
def wrapper(service, *args, **kwargs):
if service.description is None:
raise exceptions.NotRetrievedError('No service descrip... | 5,329,397 |
def _copy_cudd_license(args):
"""Include CUDD's license in wheels."""
path = args.cudd if args.cudd else CUDD_PATH
license = os.path.join(path, 'LICENSE')
included = os.path.join('dd', 'CUDD_LICENSE')
yes = (
args.bdist_wheel and
getattr(args, 'cudd') is not None)
if yes:
... | 5,329,398 |
def put_all_macros(config, data):
"""
Update macros in Zendesk.
:param config: context config
:param data: the macro data to PUT
"""
entries = (
'title', 'active', 'actions', 'restriction',
'description', 'attachments'
)
succeeded = []
failed = []
with click.pro... | 5,329,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.