content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def ass_vali(text):
"""
验证是否为合法ASS字幕内容
:param text: 文本内容
:return: True|False
"""
if "V4+ Styles" in text:
return True
else:
return False | 925744ed632e3ae1fa35f475682e2d34266ad544 | 696,356 |
def solution(socks):
"""Return an integer representing the number of pairs of matching socks."""
# build a histogram of the socks
sock_colors = {}
for sock in socks:
if sock not in sock_colors.keys():
sock_colors[sock] = 1
else:
sock_colors[sock] += 1
# count ... | 1e64be91018ee633f2637ff768346f9bc6f39603 | 696,358 |
def multi_valued(annotations):
"""Return set of multi-valued fields."""
return {name for name, tp in annotations.items() if getattr(tp, '__origin__', tp) is list} | 09d2b61b96e3bc56758a27375c1e0616995d8554 | 696,360 |
import re
def get_cxx_close_block_regex(semicolon=False, comment=None, at_line_start=False):
###############################################################################
"""
>>> bool(get_cxx_close_block_regex().match("}"))
True
>>> bool(get_cxx_close_block_regex(at_line_start=True).match("}"))
... | c62cd254aaa329358a33ba96fc8d23004c950d85 | 696,361 |
def encode_truncate(text, limit, encoding='utf8', return_encoded=True):
"""
Given a string, return a truncated version of the string such that
the UTF8 encoding of the string is smaller than the given limit.
This function correctly truncates even in the presence of Unicode code
points that encode t... | e73bc332e16f932e609ff40299366e146947c430 | 696,366 |
def default_metric_cmp_fn(current_metric: float, prev_best: float) -> bool:
"""
The default function to compare metric values between current metric and previous best metric.
Args:
current_metric: metric value of current round computation.
prev_best: the best metric value of previous rounds... | e99b346e3196ba9987b490c220ef43817ab0ce1f | 696,372 |
def find_idx_scalar(scalar, value):
"""
Retrieve indexes of the value in the nested list scalar.
The index of the sublist corresponds to a K value.
The index of the element corresponds to a kappa value.
Parameters:
scalar -- list, size 2^n x 2^n
value -- float
Return
indexes -- list of integer
"""
# Give ... | 90032e41eb84084bf9f4b7e02c38ac950ade3f33 | 696,373 |
import struct
import socket
def int2ip(n):
"""Convert an long to IP string."""
packet_ip = struct.pack("!I", n)
return socket.inet_ntoa(packet_ip) | c35cc6a64b57f4879f9580c77abbb05686276824 | 696,374 |
from decimal import Decimal
from math import floor
def get_pow1000(num):
"""Determine exponent for which significand of a number is within the
range [1, 1000).
"""
# Based on algorithm from http://www.mail-archive.com/
# matplotlib-users@lists.sourceforge.net/msg14433.html, accessed 2010/11/7
... | f809994c5023196f7124a3f46bc494c4ba0f654a | 696,376 |
def remove_spades(hand):
"""Returns a hand with the Spades removed."""
spadeless_hand = hand [:]
for card in hand:
if "Spades" in card:
spadeless_hand.remove(card)
return spadeless_hand | 3b273ddd6c5011c6bb4a5a40ff0d2fc426b40dc5 | 696,378 |
def _quadratic_bezier(y_points, t):
"""
Makes a single quadratic Bezier curve weighted by y-values.
Parameters
----------
y_points : Container
A container of the three y-values that define the y-values of the
Bezier curve.
t : numpy.ndarray, shape (N,)
The array of value... | 7c5cf27ce2fadb0843039729dc0f01473dfa946c | 696,382 |
import struct
def bytes_to_long(byte_stream):
"""Convert bytes to long"""
return struct.unpack(">Q", byte_stream)[0] | f5b7ec07b44b4c218a02c9cb9367e38fef311d30 | 696,383 |
def cast_tensor_type(tens, dtype):
"""
tens: pytorch tens
dtype: string, eg 'float', 'int', 'byte'
"""
if dtype is not None:
assert hasattr(tens, dtype)
return getattr(tens, dtype)()
else:
return tens | 378154acebad9ff080090b6dfad803c03c9ea11b | 696,384 |
def topo_param_string(p, exclude=['print_level', 'name'], sep=", "):
"""
Formats global parameters nicely for use in version control (for example).
"""
strings = ['%s=%s' % (name,val) for (name,val) in p.get_param_values()
if name not in exclude]
return sep.join(strings) | d05220ce36d8ba7a22d94a0daef164d74b4d4a87 | 696,385 |
def change_name_of_compressed_op(x: str):
"""
Splits op name and adds kernel:0 to it
:param x: Name of op
:return:
"""
return x.split('/')[0]+'/kernel'+':0' | 6829a49458b6308e06f67021f561295f2b05bad2 | 696,386 |
def uprint(str):
"""Underlined <str> """
return "\033[4m{0}\033[0m".format(str) | 80793e26ac44c4ae3b5724685a22aa4c0a79a89b | 696,388 |
from typing import Dict
def merge_two_dicts(x: Dict, y: Dict) -> Dict:
"""
Given two dicts, merge them into a new dict as a shallow copy, e.g.
.. code-block:: python
z = merge_two_dicts(x, y)
If you can guarantee Python 3.5, then a simpler syntax is:
.. code-block:: python
z =... | 6e4f45ffdb7e231f59b2fda1a3d0931cd1cc1a85 | 696,391 |
def wrap_code_block(message):
"""
Wrap a message in a discord code block
:param message: The message to wrap
:return: A message wrapped in a code block
"""
return "```\r\n{0}\r\n```".format(message) | 48cf6f8c58a6260dbd68750c12339aa578302e4d | 696,392 |
def isOverlap1D(box1, box2):
"""Check if two 1D boxes overlap.
Reference: https://stackoverflow.com/a/20925869/12646778
Arguments:
box1, box2: format: (xmin, xmax)
Returns:
res: bool, True for overlapping, False for not
"""
xmin1, xmax1 = box1
xmin2, xmax2 = box2
return x... | 898331f7f0aced6a86b244e22ebb069423fee719 | 696,396 |
import unicodedata
def unc_to_url(unc: str, as_file: bool = False):
"""Convert UNC to file or smb URL."""
# normalize for the Alfred Workflow
unc = unicodedata.normalize("NFC", unc).strip() # pylint: disable=I1101
url = unc.replace("\\\\", "smb://").replace("\\", "/")
if as_file: # for Windows 1... | ba8828707d2c0ff940ebaa17d95c1b73d1b43c6f | 696,399 |
def determine_pos_neu_neg(compound):
"""
Based on the compound score, classify a sentiment into positive, negative, or neutral.
Arg:
compound: A numerical compound score.
Return:
A label in "positive", "negative", or "neutral".
"""
if compound >= 0.05:
return 'positive'
... | 6c36913ed4399a8bede622a18c06b46a1fb94c0b | 696,402 |
def starts(epsilon=0):
"""Returns a function that computes whether a temporal interval has the
same start time as another interval (+/- epsilon), and ends before it.
The output function expects two temporal intervals (dicts with keys 't1'
and 't2' for the start and end times, respectively). It returns ... | c26d9d05dac253d010d4d689c80552eb81714929 | 696,404 |
def get_lon_lat_dims(dataarray):
"""
Get the name of lon and lat corresponding to an dataarray (based on the dimensions of the dataarray).
"""
# get correct grid
dims = dataarray.dims
lon_name = 'lon_rho'
lat_name = 'lat_rho'
for dim in dims:
if dim.startswith('eta') or dim.startswith('lon'):
lon_name = di... | 1716feffea50a1963de1425e537ab7f39e0da0a8 | 696,415 |
def rs_is_puiseux(p, x):
"""
Test if ``p`` is Puiseux series in ``x``.
Raise an exception if it has a negative power in ``x``.
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_is_puiseux
>>> ... | a93ff5797d8e3b845099f9c8da2a5fd88c288ff6 | 696,417 |
def resultToString(result, white):
"""
The function returns if the game was won based on result and color of figures
Input:
result(str): result in format '1-0','1/2-1/2', '0-1'
white(bool): True if white, False if black
Output:
str: result of a game: 'won', 'lost', 'tie' or 'unknown'
""... | 9294ca5fc67c9f33d263b977bd35847cef2f56cc | 696,418 |
def check_uniprot(alias):
"""
Return True if the protein has UniProt identifier
"""
return len(alias) == 1 or alias.split(':')[0] == 'uniprotkb' | 90fab83a02595ea5808ae8b9dcbec1993eb81404 | 696,422 |
def date_str(year, month, day, hour=0, minute=0, second=0., microsecond=None):
"""
Creates an ISO 8601 string.
"""
# Get microsecond if not provided
if microsecond is None:
if type(second) is float:
microsecond = int((second - int(second)) * 1000000)
else:
mic... | a08bc5aee24f500ff3b4f18ba3bee6d808374136 | 696,429 |
def confirm_action(desc='Really execute?') -> bool:
"""
Return True if user confirms with 'Y' input
"""
inp = ''
while inp.lower() not in ['y', 'n']:
inp = input(desc + ' Y/N: ')
return inp == 'y' | 4dd485e76e36c579b16c91d57edbde18ba52d3db | 696,431 |
def remove(text, removeValue):
"""
Return a string where all remove value are removed from the text.
"""
return text.replace(removeValue, '') | cfc7f5f5ab212bea6e02423fd0fb1fc2947be7a2 | 696,434 |
def _tuple_replace(s, Lindices, Lreplace):
"""
Replace slices of a string with new substrings.
Given a list of slice tuples in C{Lindices}, replace each slice
in C{s} with the corresponding replacement substring from
C{Lreplace}.
Example:
>>> _tuple_replace('0123456789',[(4,5),(6,9)],['a... | 2942023bac0ac81031f9c17ac421d13b872466d4 | 696,436 |
from datetime import datetime
def timestamp_seconds() -> str:
"""
Return a timestamp in 15-char string format: {YYYYMMDD}'T'{HHMMSS}
"""
now = str(datetime.now().isoformat(sep="T", timespec="seconds"))
ts: str = ""
for i in now:
if i not in (" ", "-", ":"):
ts += i
retu... | d4c03925949795e6f9993cc4a79cb088619e0527 | 696,439 |
def get_files_priorities(torrent_data):
"""Returns a dictionary with files priorities, where
filepaths are keys, and priority identifiers are values."""
files = {}
walk_counter = 0
for a_file in torrent_data['files']:
files[a_file['path']] = torrent_data['file_priorities'][walk_counter]
... | c142f73ef1087cee72bbca317e3ea07ebcc5bf8c | 696,443 |
def _make_update_dict(update):
"""
Return course update item as a dictionary with required keys ('id', "date" and "content").
"""
return {
"id": update["id"],
"date": update["date"],
"content": update["content"],
} | f20efac269ad67b9f46f4994bf61e2397fb91d98 | 696,444 |
def is_resource(url):
"""
:param url: url to check;
:return: return boolean;
This function checks if a url is a downloadable resource. This is defined by the list of resources;
"""
if url:
resources = ['mod/resource', 'mod/assign', 'pluginfile']
for resource in resource... | 39496ff5bb170746645d40d954a96c76b4c36a87 | 696,446 |
import re
def group_lines(lines, delimiter):
"""
Group a list of lines into sub-lists. The list is split at line matching the
`delimiter` pattern.
:param lines: Lines of string.
:parma delimiter: Regex matching the delimiting line pattern.
:returns: A list of lists.
"""
if not lines:... | f77e643aa711b160dda97acf35c8be1cec7d703a | 696,447 |
def _build_params(dt):
"""Takes a date and builds the parameters needed to scrape the dgm website.
:param dt: the `datetime` object
:returns: the `params` that contain the needed api information
"""
params = (('yr', dt.year),
('month', dt.month),
('dy', dt.day),
... | 477f763d81407f047ada9d4d16c0207ed0b5ad67 | 696,450 |
def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int:
""" Asymmetric rounding to make `val` divisible by `divisor`. With default
bias, will round up, unless the number is no more than 10% greater than the
smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """
... | fdc644b8d4bd5d3fdf49c5d9892eaf67640fb61b | 696,452 |
import random
def random_choice(array, probs=None):
"""
This function takes in an array of values to make a choice from,
and an pdf corresponding to those values. It returns a random choice
from that array, using the probs as weights.
"""
# If no pdf provided, assume uniform dist:
if probs == None:
index = i... | 2fc692773b50d7b940f72bf4deebede6ffd063f0 | 696,454 |
def parse_requirements(r):
"""Determine which characters are required and the number of them that
are required."""
req = {'d': 0, 'l': 0, 'u': 0, 's': 0}
for c in r:
if c == 'd':
req['d'] += 1
elif c == 'l':
req['l'] += 1
elif c == 'u':
re... | 8c1f82a7136aec08471e672e4b676d725854f2d6 | 696,455 |
def peek(file, length=1):
"""Helper function for reading *length* bytes from *file* without advancing
the current position."""
pos = file.tell()
data = file.read(length)
file.seek(pos)
return data | fe901c4001320c9498b09a1d7caa6b4598a0386a | 696,456 |
def sub_account_universal_transfer_history(self, **kwargs):
"""Query Universal Transfer History (For Master Account)
GET /sapi/v1/sub-account/universalTransfer
https://binance-docs.github.io/apidocs/spot/en/#query-universal-transfer-history-for-master-account
fromEmail and toEmail cannot be sent at t... | c552c4eeea8be9eeb0a662cbaa546085d7c5999a | 696,457 |
def replace_del_alt(var):
"""
Issues occur with deletions hear the ends of the genome.
Currently - is used to represent an entire string of bases
being deleted. Here we replace the ALT with "N" the length
of REF.
"""
ref_length = len(var.REF)
if var.ALT[0] == '-':
fixed_alt ... | f3d081a8dd12b8ca81bd8d5a8aca6bf6dbccc839 | 696,459 |
def pad(value: int, length: int = 2) -> str:
"""
Adds leading and trailing zeros to value ("pads" the value).
>>> pad(5)
05
>>> pad(9, 3)
009
:param value: integer value to pad
:param length: Length to pad to
:return: string of padded value"""
return "{0:0>{width}}".format(valu... | 0ac5c5cebf3cc97f25d0e21fdef9c45f06ce635d | 696,463 |
from typing import List
import csv
def create_list_of_selected_jc() -> List:
"""
Return the "SelectedJournalsAndConferences.csv" as a list
"""
selected_jc = []
with open("SelectedJournalsAndConferences.csv", mode="r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in cs... | abe0f023ba77a4c8d22d6132ee029b104ceb8466 | 696,467 |
def lower_first_letter(sentence):
"""Lowercase the first letter of a sentence."""
return sentence[:1].lower() + sentence[1:] if sentence else "" | de0f79548d42983093f65970464ca84eed032300 | 696,468 |
def prefix_hash(s, p, P=53):
"""
Compute hashes for every prefix. Only [a-zA-Z] symbols are supported
Parameters
-------------
s : str
input string
p : List[int]
all powers of P. p[i] = P ** i
Returns
----------
h : List[int]
h[i] = hash(s[:i + 1])
"""
... | c9d7d4054c580257fab9336fa7881af3c9c074f4 | 696,469 |
def _IsPositional(arg):
"""Returns True if arg is a positional or group that contains a positional."""
if arg.is_hidden:
return False
if arg.is_positional:
return True
if arg.is_group:
for a in arg.arguments:
if _IsPositional(a):
return True
return False | 34147b29533ba9a535ba363c264625222763fb72 | 696,471 |
def is_potential(obj):
"""Identifies if an object is a potential-form or potential-function"""
return hasattr(obj, "is_potential") and obj.is_potential | e84ad5fb59b8a6575eab6821e1b4bcedc1ddb0ab | 696,474 |
def get_default_value(key):
""" Gives default values according to the given key """
default_values = {
"coordinates": 2,
"obabel_path": "obabel",
"obminimize_path": "obminimize",
"criteria": 1e-6,
"method": "cg",
"hydrogens": False,
"steps": 2500,
"cutoff": False,
"rvdw": 6.0,
"rele": ... | 89a12cbb20499a85fc7c6c092fc2ee90aff31ae3 | 696,475 |
def find_longest_common_substring(x: str, y: str) -> str:
"""
Finds the longest common substring between the given two strings in a
bottom-up way.
:param x: str
:param y: str
:return: str
"""
# Check whether the input strings are None or empty
if not x or not y:
return ''
... | 878f41ead963a8171ec7d07509a8dae5aef7fb4b | 696,476 |
def model_includes_pretrained(model):
"""
Checks if a model-class includes the methods to load pretrained models.
Arguments:
model Model-class to check.
Returns:
True if it includes the functionality.
"""
return hasattr(model, "has_pretrained_state_dict") and hasattr(
m... | f19460c4a0ce731d4642ad7092f80910605278a8 | 696,478 |
def _get_other_dims(ds, dim):
"""Return all dimensions other than the given dimension."""
all_dims = list(ds.dims)
return [d for d in all_dims if d != dim] | 4c8fc614442cbf4ee1a22aa8113532dcd2905e3c | 696,479 |
def stag_pressure_ratio(M, gamma):
"""Stagnation pressure / static pressure ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation pressure ratio :math:`p_0 / p` [units: dimension... | 351b14716077386eadea04a4717ea9afec8fdcaf | 696,481 |
import torch
def shift_v(im, shift_amount):
"""Shift the image vertically by shift_amount pixels,
use positive number to shift the image down,
use negative numbers to shift the image up"""
im = torch.tensor(im)
if shift_amount == 0:
return im
else:
if len(im.shape) == 3: # fo... | cbd0eab7b3a0a64e7402e5eb14d0464ab7ba9ac5 | 696,484 |
def getPath(parent_map, start, goal):
"""
Definition
---
Method to generate path using backtracking
Parameters
---
parent_map : dict of nodes mapped to parent node_cost
start : starting node
goal : goal node
Returns
---
path: list of all the points from starting to goal... | 8a23ab5462b064744973f75c294e0814099961c7 | 696,489 |
from typing import List
def input_assert(message: str, choices: List[str]) -> str:
"""
Adds functionality to the python function `input` to limit the choices that can be returned
Args:
message: message to user
choices: list containing possible choices that can be returned
Returns:
... | 062b88356a977cdd119f7ee0c54b7e6a611f76f2 | 696,491 |
def rate(hit, num):
"""Return the fraction of `hit`/`num`."""
return hit / (num or 1.0) | b055fa6995f85ab223747dd369a464644046f7d7 | 696,493 |
def get_function_handle(method, var):
"""
Return a function handle to a given calculation method.
Parameters
----------
method : str
Identifier of the calculation method to return a handle to.
var : dict
Local variables needed in the threshold method.
Returns
-------
... | 1e8dacfeaaa32a93fbfaad8507c976c4f2e126fb | 696,496 |
def is_iterable(var):
""" Return True if the given is list or tuple.
"""
return (isinstance(var, (list, tuple)) or
issubclass(var.__class__, (list, tuple))) | f4c1d60d2e62688aedb776fb90d90049d93ad5e2 | 696,498 |
def relperm_parts_in_model(model,
phase_combo = None,
low_sal = None,
table_index = None,
title = None,
related_uuid = None):
"""Returns list of part names within model that are rep... | 7d4d5d8ac7a2c763f3a0fe2589d6ff0713d0125b | 696,503 |
def tagged_members(obj, meta=None, meta_value=None):
""" Utility function to retrieve tagged members from an object
Parameters
----------
obj : Atom
Object from which the tagged members should be retrieved.
meta : str, optional
The tag to look for, only member which has this tag wi... | 7b1077e774a98bd59b6cb9a59c9745fbfa0b4168 | 696,506 |
def remove_irrelevant_labels(labels):
"""
Filters an array of labels, removing non "CAT" labels
:param labels: array of labels
:return: an array of labels containing only the top-level "CAT" labels
"""
filtered = filter(lambda x: "CAT" in x.upper(), labels)
return list(filtered) | bedeaa6b2dd1adfcef2eb7f1d4c7b34d9e7254f8 | 696,515 |
def lookup_ec2_to_cluster(session):
"""
Takes a session argument and will return a map of instanceid to clusterarn
:param session: boto 3 session for the account to query
:return: map of ec2 instance id to cluster arn
"""
ecs = session.client('ecs')
result = dict()
for cluster in ecs.lis... | 0b148264397e5e598675dfdcd6ac4528888ce107 | 696,517 |
def padded_hex(num, n=2):
"""
Convert a number to a #xx hex string (zero padded to n digits)
"""
return ("%x" % num).zfill(n) | 2a9e401a824cdb856d29591ae282bdbbc64b79e5 | 696,522 |
import tkinter
def gui_input(prompt1, prompt2):
"""
Creates a window to collect Risk and Budget info from user
Parameters
----------
prompt1 : String
First question in input prompt
prompt2 : String
Second question in input prompt
Returns
-------
value1 : String
... | 1c770c56aba7ca7a793561ac2063aa7dae41b15e | 696,527 |
def _remove_doc_types(dict_):
"""
Removes "doc_type" keys from values in `dict_`
"""
result = {}
for key, value in dict_.items():
value = value.copy()
value.pop('doc_type', None)
result[key] = value
return result | e5badc0a73edba3233816d4c99fa7f26845c77f5 | 696,528 |
def create_slices(start, stop, step=None, length=1):
""" Generate slices of time indexes
Parameters
----------
start : int
Index where first slice should start.
stop : int
Index where last slice should maximally end.
length : int
Number of time sample included in a given... | c45979e18db9d3f554ae7d194ca001bc3976fa83 | 696,532 |
def wootric_url(route):
"""helper to build a full wootric API route, handling leading '/'
>>> wootric_url('v1/responses')
''https://api.wootric.com/v1/responses'
>>> wootric_url('/v1/responses')
''https://api.wootric.com/v1/responses'
"""
route = route.lstrip('/')
return f'https://api.w... | f48ebe6ac7fe05798230c5bc27681adcb03804ef | 696,534 |
def check_xml(root):
"""Check xml file root, since jarvis4se version 1.3 it's <systemAnalysis>"""
if root.tag == "systemAnalysis":
return True
else:
return False | d2921e2b5784a26a7636b65f6d3fbcf1425f8448 | 696,542 |
def get_rotation(transform):
"""Gets rotation part of transform
:param transform: A minimum 3x3 matrix
"""
assert transform.shape[0] >= 3 \
and transform.shape[1] >= 3, \
"Not a transform? Shape: %s" % \
transform.shape.__repr__()
assert len(transform.shape) == 2, \
... | c8fa40d883c3b8cbc7fe24ee38fe35cb6813f491 | 696,543 |
def check(s, ans):
"""
This is a predicate function to check whether a string is in a given answer.
:param s: str, the one need to be checked.
:param ans: str, the given answer.
:return: bool,
"""
if s in ans:
return True
return False | 86af3d89634858f4839fc486580e95f1ba04b6a3 | 696,544 |
import struct
def _as_float(value):
"""
Truncate to single-precision float.
"""
return struct.unpack('f', struct.pack('f', value))[0] | 7bf9b2e4d61b7a91f6c8334f0e7f093d55c6d614 | 696,545 |
from pathlib import Path
def ExistFile(path):
"""Check whether a file exists.
Args:
path: The path.
Returns:
bool: True if the file exists otherwise False.
"""
return Path(path).is_file() | b71856d8b8ffde2c768a4a4e16bc9303d9a92251 | 696,547 |
def generate_traits_list(traits: dict) -> list:
"""Returns a list of trait values
Arguments:
traits: a dict containing the current trait data
Return:
A list of trait data
"""
# compose the summary traits
trait_list = [traits['local_datetime'],
traits['canopy_hei... | 995c66208d3306958811420ba8ebb1bcd7a11ccf | 696,548 |
from typing import List
def create_fhir_bundle(
resources: List[dict], bundle_type: str = "transaction"
) -> dict:
"""Creates a FHIR bundle from a list of FHIR resources
Parameters
----------
resources : List[dict]
List of FHIR resources
bundle_type : str, optional
FHIR Bundle... | 70f94829b2e366eea97fd31245eb77e69aaaf066 | 696,549 |
def patch_cmass_output(lst, index=0):
"""
Parameters
----------
lst : list of tuples
output of afni.CenterMass()
index : int
index in the list of tuples
Returns
-------
tuple
one set of center of mass coordinates
"""
if len(lst) <= index:
... | 98b637a6a922bdbbb84b99f78a47de1519443192 | 696,550 |
def replace_version(content, from_version, to_version):
"""
Replaces the value of the version specification value in the contents of
``contents`` from ``from_version`` to ``to_version``.
:param content: The string containing version specification
:param to_version: The new version to be set
:re... | dd792b6674c21dc6e11ef8013d88b9c210f9604f | 696,553 |
def generate_train_config(model_spec, train_batch_spec, val_batch_spec, epoch_size,
n_epochs=100, lr=0.001):
""" Generates a spec fully specifying a run of the experiment
Args:
model_spec: a model spec
train_batch_spec: a batch spec for train
val_batch_spec: batch spe... | 0e19dab0263eda8505ddb830fd255b2a760d822c | 696,554 |
def strip_path_prefix(ipath, prefix):
"""
Strip prefix from path.
Args:
ipath: input path
prefix: the prefix to remove, if it is found in :ipath:
Examples:
>>> strip_path_prefix("/foo/bar", "/bar")
'/foo/bar'
>>> strip_path_prefix("/foo/bar", "/")
'foo/b... | c9634c9b06466c7af07a39c97645f0c601fe3ce2 | 696,560 |
def link_header( header, link_delimiter=',', param_delimiter=';' ):
"""
Parsea en dicionario la respusta de las cabezera ``link``
Parameters
----------
header: string
contenido de la cabezera ``link``
link_delimiter: Optional[str]
caracter que separa los enlaces
param_delimi... | eceab56c0c00fccb9860e85d1e4aa383fcdc5d30 | 696,561 |
import typing
import asyncio
async def process_concurrent(objs: typing.List[typing.Any], process: typing.Callable[[typing.Any], typing.Awaitable], workers: int = 5):
"""
Run a processing coroutine on a list of objects with multiple concurrent workers.
"""
# Divide and round up
step = (len(objs) - ... | 74e983b7cf7480d14c51304b7cc6daaac75ea837 | 696,563 |
def prop_all(printer, ast):
"""Prints an all property "A ..."."""
prop_str = printer.ast_to_string(ast["prop"])
return f'A{prop_str}' | 0a03f04d955251918a1ea7dcf3576f30cb790656 | 696,568 |
def yesno(val, yes='yes', no='no'):
"""
Return ``yes`` or ``no`` depending on value. This function takes the value
and returns either yes or no depending on whether the value evaluates to
``True``.
Examples::
>>> yesno(True)
'yes'
>>> yesno(False)
'no'
>>> y... | cfdbe3ffb53ed0239e39392873ab128506379107 | 696,571 |
from typing import Sequence
from typing import List
def list_insert_list(l:Sequence, to_insert:Sequence, index:int) -> List:
""" Insert `to_insert` into a shallow copy of `l` at position `index`.
This function is adapted from: http://stackoverflow.com/questions/7376019/
Parameters
----------... | 2f332cc70f64a740c7dd26867978121f4b68acb7 | 696,573 |
def ordered_sample(population, sample_size):
"""
Samples the population, taking the first `n` items (a.k.a `sample_size') encountered. If more samples are
requested than are available then only yield the first `sample_size` items
:param population: An iterator of items to sample
:param sample_size: ... | 0aba56350b6acf44098ea247abb979c35df947e8 | 696,575 |
from pathlib import Path
def basename(var, orig = False):
"""Get the basename of a path"""
bname = Path(var).name
if orig or not bname.startswith('['):
return bname
return bname[bname.find(']')+1:] | 16d8365d5be084eaa45921fc633e552e3224847b | 696,576 |
def sort_table(i):
"""
Input: {
table - experiment table
sort_index - if !='', sort by this number within vector (i.e. 0 - X, 1 - Y, etc)
}
Output: {
return - return code = 0, if successful
> 0,... | 5f33731cf8bcc6ea34d2c62cdf0ba20dd97b9aa6 | 696,581 |
def len_(string):
""":yaql:len
Returns size of the string.
:signature: string.len()
:receiverArg string: input string
:argType string: string
:returnType: integer
.. code::
yaql> "abc".len()
3
"""
return len(string) | a73a32c80c1016e3ca2735d56aeec1f98aa83767 | 696,583 |
def _is_clustal_seq_line(line):
"""Returns True if line starts with a non-blank character but not 'CLUSTAL'
Useful for filtering other lines out of the file.
"""
return line and (not line[0].isspace()) and\
(not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE')) | 78c9067fa02254409d33fdb9f243c74d549138ce | 696,588 |
import random
import colorsys
def lincolor(num_colors, saturation=1, value=1, normalized=False):
"""Creates a list of RGB colors linearly sampled from HSV space with
randomised Saturation and Value
# Arguments
num_colors: Integer.
saturation: Float or `None`. If float indicates saturation... | 6540aba364ae13d9cf1d51169674b119f0d3ff82 | 696,589 |
def get_surrounding(field, row, col, value):
"""Finds how many mines are in surrounding squares of a certain coordinate"""
count = 0
# checks surrounding squares
for i in range(row - 1, row + 2):
for k in range(col - 1, col + 2):
# checks if the current coordinate is on the field and... | 5ad8e11e7062ee7d44975b119b69f28937e4083a | 696,590 |
import math
def water_saturation_vapour_pressure_iapws(t):
"""Returns the water vapour pressure according to W. Wagner and A. Pruss (1992) J. Phys. Chem. Reference Data, 22,
783–787.
See http://www.kayelaby.npl.co.uk/chemistry/3_4/3_4_2.html
Valid only above the triple point. The IAWPS formulation 199... | aa424bc63b3165bc439dacbf8748f478654a15b2 | 696,592 |
def cleanPath(path):
"""
Cleans up raw path of pdf to just the name of the PDF (no extension or directories)
:path: path to pdf
:returns: The PDF name with all directory/extensions stripped
"""
filename = path.split("/")[-1]
filename = filename.split(".")[0]
return filename | 0cafdf13cbdc784abaedb49b9b757054c3ff25f6 | 696,595 |
from typing import Union
def get_first_line(o, default_val: str) -> Union[str, None]:
"""
Get first line for a pydoc string
:param o: object which is documented (class or function)
:param default_val: value to return if there is no documentation
:return: the first line which is not whitespace
... | c7003dc1cc5e22ea08c35485e593fd539597637d | 696,598 |
def capStrLen(string, length):
"""
Truncates a string to a certain length.
Adds '...' if it's too long.
Parameters
----------
string : str
The string to cap at length l.
length : int
The maximum length of the string s.
"""
if length <= 2:
raise Exception("l ... | a7b2e264d867d3f5263d7037fb91220128437021 | 696,599 |
def get_line_indentation_spacecount(line: str) -> int:
""" How many spaces is the provided line indented? """
spaces: int = 0
if (len(line) > 0):
if (line[0] == ' '):
for letter_idx in range(len(line)):
if (line[letter_idx + 1] != ' '):
spaces = letter... | b70c65431fada6367a12c1d38f0420bcd66f1d8a | 696,605 |
def _is_possible_expansion(acro: str, full: str) -> bool:
"""
Check whether all acronym characters are present in the full form.
:param acro:
:param full:
:return:
"""
# Empty acronym is presented everywhere
if not acro:
return True
# Non-empty acronym is not presented in e... | e76cace8592c99d4e5e965bcbf8cba17c7114ee1 | 696,609 |
def from_context(cm):
"""Extract the value produced by a context manager"""
with cm as x:
return x | 2d0be1d9d8c66487898e7f2d0f6649b952289468 | 696,614 |
def flatten(arr):
"""Flatten array."""
return [item for sublist in arr for item in sublist] | 16555e7d4c04a0c6ffec03fb4005ddf534a474df | 696,617 |
def get_prefix_from_proxy_group(proxy_group):
"""
Return prefix by analyzing proxy_group name
Args:
proxy_group (str): proxy group name
Returns:
str: prefix if exists, empty string if not
"""
split_name = proxy_group.split("@")[0].split("-")
# if there's only two sections,... | 04433d97dcecc4edd7288e1373d4d6bce5e07ee4 | 696,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.