content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def formatField (Field, x, xerr):
"""
Parameters
----------
Field : The name of the field
x : Value of the field
xerr : Error in the field
Returns
-------
Str
Field: x +/- xerr
"""
return str(Field) + " " + str(x) + " +/- " + str(xerr) + "\n" | fb0c4dae3349b6fc88bb23c46bf7112546f854fe | 630,769 |
def getAttr(argAttrName, argAttrs):
"""Extract and return the value of a particular attribute from a list
of (attributeName, attributeValue) pairs. If the attribute does
not exist in the list, return None.
"""
for attr in argAttrs:
if attr[0] == argAttrName: return attr[1]
return None | 34b24e04a186e250bca5a0c13a68e41872271300 | 630,771 |
def get_search_term(request):
"""Get search term from request.
Args:
request: Django request object
Returns:
searchterm: string, search term
"""
# Get search term
searchterm = request.POST.get('search', '')
# If no POST data, try GET
if not searchterm and request.GET.get('search', ''):
s... | 98019759b3fcac959be2766751ea31c1d8d0983b | 630,773 |
def all_leaf_positions(parented_tree):
"""Return tree positions of all leaves of a ParentedTree,
even if the input is only a subtree of that ParentedTree.
"""
return parented_tree.root().treepositions('leaves') | 94d319d7d9f6d7b394f3e0d5448898a5effbe508 | 630,774 |
def extract_package(signature):
"""Extracts the package from a signature.
Args:
signature (string): JNI signature of a method or field.
Returns:
The package name of the class containing the field/method.
"""
full_class_name = signature.split(";->")[0]
package_name = full_class_... | d0274c51337c724d1f26288c8de81426be3c3815 | 630,779 |
def get_line(s):
"""get a gui line with given char"""
return str(s)*72 | 8516e8b170679ce7b779a50323dd5684dab27e36 | 630,780 |
def get_exception_info(exception: BaseException) -> dict:
"""
Given an Exception object, retrieves some information about it: class and message.
:param exception: An exception which inherits from the BaseException class.
:return: A dict, containing two values:
- class: Th... | 5bd8c09478e2b64ad58c857f39946bfcbfd79caa | 630,784 |
def get_count_proteins(filename):
"""
Get the number of unique proteins from unique_proteins output.
"""
with open(filename) as f:
line = f.readline()
if line.startswith("Found"):
count = int(line.split()[1])
else:
count = -1
return count | f91256571683a59138cb54e63e9ae33a159b8c3c | 630,785 |
def fits_header_value(hdu, key):
""" Take FITS hdu and a key, return value associated with key (or None if key absent).
Adapted from package photrix, class FITS.header_value.
:param hdu: astropy fits header+data unit object.
:param key: FITS header key [string] or list of keys to try [list of string... | a452a37b919a69db4faaec53925dd59670dcaa89 | 630,787 |
def camelize(val):
"""Return the camel case version of a :attr:`str`
>>> camelize('this_is_a_thing')
'thisIsAThing'
"""
s = ''.join([t.title() for t in val.split('_')])
return s[0].lower()+s[1:] | a8fd3c1f273759db454589d6a8ef6ebe3e16b760 | 630,789 |
def format_menu(menu):
"""
Textually format a menu.
Args:
menu: A dictionary with as key the type of menu item and as values the menu content and the prices for students
and staff.
Returns:
The nicely format menu including emojis to indicate the menu types.
"""
me... | d8c04ee7f3b47ed604f4fa58ba8a39b60e1c5a67 | 630,790 |
def distance_between(agents_row_a, agents_row_b):
"""
calculate distance between 2 agents
"""
length = (((agents_row_a[0] - agents_row_b[0])**2) +
((agents_row_a[1] - agents_row_b[1])**2))**0.5
return(length) | a214857b0e465da43d5f4aedc703916c4a1885ab | 630,791 |
def crop_border(imgs, crop_border):
"""Crop borders of images.
Args:
imgs (list[ndarray] | ndarray): Images with shape (h, w, c).
crop_border (int): Crop border for each end of height and weight.
Returns:
list[ndarray]: Cropped images.
"""
if crop_border == 0:
retur... | 720812efc06e1a0eec0abc2dbc18554e92aa6d01 | 630,792 |
def convert_to_strings(entities):
"""
Given a tuple of entities, return a list of strings
"""
return [e.text for e in entities] | bbf3c1edcb7e09c5a7c311eb7bc93d1a1453ef2f | 630,796 |
def populate_countries_dict(file_path):
"""
Function to populate dictionary of countries and url numbers.
"""
countries_dict = {}
with open(file_path, 'r') as f:
for line in f.readlines():
key_value = line[:-1].split(':')
countries_dict[key_value[0]] = int(k... | 49f8a00573bc3900a7c0ec9be5bf653c8115c711 | 630,798 |
import re
def remove_extra_description_terms(description):
"""
Sometimes the description contains some things we don't want to include
like trailing '.', extra spaces, the string (non-protein coding) and a typo
in the name of tmRNA's. This corrects those issues.
"""
description = re.sub(
... | 73e4ae305fc728a1ce815f040d2f4aa403df30f6 | 630,801 |
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: ... | 163e2c7de61ad6758bcb6307c427441624c28266 | 630,802 |
def response_verify(resp):
"""
Verify if the response's status code is 200 or not.
:return: True if response code is 200
:rtype: bool
"""
if resp.status_code != 200 or resp.text == "":
return False
else:
return True | 77e01bca93b5be718a54b81f28345bf8ebc9c25e | 630,804 |
def get_transaction_data(consumer_id, transactions):
"""
For all transactions related to a consumer, return
a dictionary with the keys being the offer IDs or the
value 'transaction' for non-offer related events.
"""
txn_dict = {}
txn = transactions[transactions["person"] == co... | ca0866968654f0b267d73a17ba972274456aeced | 630,805 |
import requests
def download(url):
"""
:param url: str
Url to get
:return: response
Response of request
"""
return requests.get(url) | f785920d00d2a9c322dfda074362f78fd5923d52 | 630,806 |
def cost(z):
""" Cost function. """
return 0.1 + 0.4 * (4 * z[0])**2 + 0.5 * z[1] | e6fb9a09edd5a330d10cb04e3a6fac8b8c761558 | 630,807 |
import hashlib
def md5_hex(data):
"""
shortcut of hashlib.md5('xxx').hexdigest()
>>> md5_hex('123')
'202cb962ac59075b964b07152d234b70'
"""
return hashlib.md5(data).hexdigest() | b9471304effed6757b2505c7859adb7a342194c2 | 630,808 |
def get_output_jar_paths(version):
"""
Gets the list of output jars, which includes the primary
jep-${version}.jar, the test jar, and the src jars.
"""
return [
'build/java/jep-{0}-sources.jar'.format(version),
'build/java/jep-{0}.jar'.format(version),
'build/java/jep-{0}-tes... | 5ce415a88d544a1ec4c3096130951706e2a34e69 | 630,809 |
def add_files_to_zip(zip_file, base_dir, file_list):
"""Pack a list of files into a zip archive, that is already opened for
writing.
Args:
zip_file: An object representing the zip archive.
base_dir: Base path of all the files in the real file system.
file_list: List of absolute file paths to add. Mus... | 23ef0aa7767bb97d3bef78b0ab87f9d4877cfbd5 | 630,810 |
def prior_probability_of_category_k(k, c, nk):
"""
Function that calculates the prior probability of category k. This is equation 3-4 in [Ande90]_
Parameters
----------
k : int
Category index. For example, k can be 0 or 1 or 2 etc
c : float
Coupling probability. This is the prob... | c60a71bdc1e4a8d87ae82e156c812287f01a79c8 | 630,811 |
import click
def format(text):
"""Format all OK,FAIL,PR,REPO words
:param text: word
:type text: string
:raises Exception: Unknown text
:return: formated click style text
:rtype: string
"""
text = text.lower()
if text == "ok":
return click.style('OK', fg='green', bold... | 2ac991685f3b70615ba9ef253724f200f4c8e79e | 630,813 |
import hashlib
def HashedKey(*args, version=None):
""" BOSS Key creation function
Takes a list of different key string elements, joins them with the '&' char,
and prepends the MD5 hash of the key to the key.
Args (Common usage):
parent_iso (None or 'ISO')
collection_id
experi... | 050fb353beb8779aaf47a86eca2138a1791c9fed | 630,814 |
from datetime import datetime
def parse_date(date_text: str):
"""
Convert a date string into a datetime instance that can be saved as an
SQL DATE.
:param date_text: A timestamp string in "YYYY-MM-DD" format
:return: A datetime object
"""
return datetime.strptime(date_text, '%Y-%m-%d') | 711f216985761cd91c5314d1aaa5a2e3049ac9fe | 630,815 |
def filter_images(data, split_data):
""" Keep only images that are in some split and have some captions """
all_split_ids = set()
for split_name, ids in split_data.iteritems():
all_split_ids.update(ids)
new_data = []
for img in data:
keep = img['id'] in all_split_ids and len(img['regions']) > 0
if... | 65c7b1765371e6e3875766394de09203e7485837 | 630,819 |
import torch
def adjacency_matrix_to_tensor_representation(W):
""" Create a tensor B[:,:,1] = W and B[i,i,0] = deg(i)"""
degrees = W.sum(1)
B = torch.zeros((len(W), len(W), 2))
B[:, :, 1] = W
indices = torch.arange(len(W))
B[indices, indices, 0] = degrees
return B | 7660f7f442c441df0cd75ec2a04a780a2f5560d8 | 630,823 |
def inverse_weight(distance, num=1.0, const=0.1):
"""
权重函数: 距离的逆.
:param distance: 距离
:type distance: float
:param num: 分子
:type num: float
:param const: 常量
:type const: float
:return: 权重值
"""
return num / (distance + const) | 0b7b48245f7b3932233d236219bfebda168cb4a6 | 630,827 |
import random
import math
def normal_random(mean = 0.0, variance = 1.0):
"""
Samples from a normal distribution.
:param mean
The mean. Default is 0.0.
:param variance
The variance. Default is 1.0.
"""
while True:
v1 = 2.0 * random.random() - 1.0
... | 32ca649ade857a7d6c941de0c46031097ae85092 | 630,832 |
def increment(number):
"""Increases a given number by 1."""
return number + 1 | 945893837ce097eabe8791b1d15b5d85b21fda04 | 630,833 |
import logging
def get_logger(logger_name, logger_level, stream=None):
"""Get a logger for the script.
Using stream handler.
# Arguments
logger_name: `str`<br/>
the name of the logger
logger_level: `int`<br/>
the minimial level that trigger the logger.
str... | 153d0c1fe187f796ebfb5da29bd12fd3451cc44d | 630,837 |
def hamming_weight(n):
"""
Calculates the Hamming weight of a positive integer.
The Hamming weight of an integer is defined as the number of
1s in its binary representation.
"""
c = 0
while n:
c += 1
n &= n - 1
return c | 5dcf4a1fafd5bb98b91566abfb615c4412e0e050 | 630,838 |
def split_plus(line):
"""
Split a line according to the + (plus) sign.
:param line:
:return:
"""
new_line = line.split("+")
return new_line | 4f5cd478cd54124486a77a16dde9f979ec5bc9a9 | 630,840 |
from typing import Union
from typing import Any
def get_keys_containing(obj: Union[dict, Any], key) -> set:
"""
Returns a set with the keys that contain `key`
Example:
.. code-block:: python
from quantify_core.utilities.general import get_keys_containing
dict_obj = {"x0": [1, 2, 3],... | bd608eb3457f49a15ca2a9f73b6b5ffd9fb27491 | 630,844 |
def commonLeader(data, i, j):
"""Get the number of common leading elements beginning at data[i] and data[j]."""
l = 0
try:
while l < 255+9 and data[i+l] == data[j+l]:
l += 1
except IndexError:
pass # terminates
return l | 7b724aaff3c62be2fdd37e42677ef51a20c21f5d | 630,846 |
import re
def _validcas(cas):
"""
Validate a CAS Registry Number
See: https://en.wikipedia.org/wiki/CAS_Registry_Number#Format
:param cas: a string to be validated as a CAS Registry Number
:return: bool
"""
test = re.search(r'^\d{2,8}-\d{2}-\d$', cas)
# if format of string does not mat... | 43c7c7edb1ed640475e84f524f4697ed4ba7caab | 630,848 |
def get_plugin_name(plugin):
"""
Return the PyPI name of the given plugin.
"""
return 'taxi-' + plugin | 9002607babc935afe2096d667ed567c3b10e80f3 | 630,849 |
def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols | 1f674411a06ce7365867d147ca4d96e10957ffd5 | 630,857 |
def _getParameterRange(key):
"""
Returns fur's default parameter range as 2-tuple (min, max).
key: fur attribute (string)
"""
if "Density" ==key: return (10000.0, 30000.0)
## geometry attributes (1) for single strand
if "Length" ==key: return (1.00, 5.00)
if "BaseWidth"==key: return ... | c1ae671671c4bf79abe7675b5e6755730f886823 | 630,860 |
def _read_binary_data(fp, size, name, clip=False):
"""Read zero-padded binary data from a file.
Attempts to read `size+1` bytes from filehandle `fp`. If 0 or more than `size`
bytes are read, raises an IOError. Data of any other size is returned to the
caller, followed by enough zero padding to yield `size` byt... | 9c21d1f5e74abd239bd1c6cd1547d31ac2cfdb77 | 630,861 |
from typing import Counter
def create_vocabulary(text, max_vocab_size = 2000):
""" Create Vocabulary dictionary
Args:
text(str): inout text
max_vocab_size: maximum number of words in the vocabulary
Returns:
word2id(dict): word to id mapping
id2word(dict): id to word mapping... | cded9fd750fd2b778e45ff4565f609f99871187f | 630,864 |
def get_user_version(conn):
"""Return user_version value."""
result = conn.execute('PRAGMA user_version')
return result.fetchone()[0] | 46c1f4d7f25d3af84014f03491e194ad19cd410d | 630,867 |
def object_from_args(args):
"""
Turns argparser's namespace into something manageable by an external library.
Args:
args: The result from parse.parse_args
Returns:
A tuple of a dict representing the kwargs and a list of the positional arguments.
"""
return dict(args._get_kwargs... | e48c0a8a49e4fe106d30d37f03c11a07e479cfc3 | 630,876 |
def get_storage_blob(bucket, source_folder_name, source_file_name):
"""
Fetches and returns the single source file blob from the buck on
Google Cloud Storage
"""
source_path = source_file_name
if source_folder_name != '':
source_path = f'{source_folder_name}/{source_file_name}'
blob ... | aa84facc8752a591b4f25e3832cb8cff64c498ba | 630,880 |
def _to_camel_case(text: str) -> str:
"""
Convert a text in snake_case format into the CamelCase format
:param text: the text to be converted.
:return: The text in CamelCase format.
"""
return "".join(word.title() for word in text.split("_")) | 9cc3edb514a0351cd4de752132627bf32f5f5ee9 | 630,883 |
def largest_prime_factor(number):
"""
Calculate the largest prime factor of a number
:param number: Number of which largest prime should be found
:return: Integer: largest prime factor
"""
count = 2
while count * count <= number:
if number % count:
count += 1
else... | c6dce3a9ac9497ae4a5a6358111031fd82e58b33 | 630,884 |
import hashlib
import json
def get_cache_key(args, kwargs):
"""
Returns a cache key from the given kwargs
This is simply a sha256 hexdigest of the keyword arguments
Args:
kwargs (dict): the arguments to build a cache key from
Returns:
str: the cache key
"""
sha = hashlib... | 44bea88164addbeb830d14cdf640e5e31a114d90 | 630,886 |
def text(node):
"""Extract text from an XML node."""
if node is None: return ''
s = ''.join(node.itertext())
return ' '.join(s.split()) | 30dc94cb3785b6553149911dc7696f10c0969dcb | 630,887 |
from typing import AnyStr
def ensure_bytes(value: AnyStr) -> bytes:
"""Convert text into bytes, and leaves bytes as-is."""
if isinstance(value, bytes):
return value
if isinstance(value, str):
return value.encode('utf-8')
raise TypeError(f"input must be str or bytes, got {type(value).__... | 74c0662b4988e34069b6065bb26f0f9d43af7cc0 | 630,891 |
def add_suffix(suffix, name):
"""Adds subfix to name."""
return "/".join((name, suffix)) | fd4eb00c0468f39f59bbbce677e56e10c186aea5 | 630,897 |
from typing import Union
from typing import List
from typing import Tuple
from typing import Iterable
def flatten(lst: Union[List, Tuple]) -> List:
"""Recursive function that flatten a list (of potential `Iterable` objects)."""
if isinstance(lst, Iterable) and not isinstance(lst, (str, bytes)):
return... | f007f78f8b8b1e3bef9ce70550efdbfb8362539c | 630,901 |
import re
def strip_ws(string: str):
"""
Strip whitespace off a string and replace all instances of >1 space with a single space.
"""
return re.sub(r'\s+', ' ', string.strip()) | 1410dfbd1a9a30a4351d3fc01962f208401f928e | 630,903 |
def try_lower(string):
# Ask for, forgiveness seems faster, perhaps better :-)
"""Converts string to lower case
Args:
string(str): ascii string
Returns:
converted string
"""
try:
return string.lower()
except Exception:
return string | 7b48401d4aaf4ae5a99b3a2d9ee5869c07726156 | 630,906 |
def concatenate_rounds(rounds1, rounds2):
"""Return a list of rounds that combines `rounds1` and `rounds2`."""
return rounds1 + rounds2 | 5c437693cd6c2b742edf56ed081cc0c3f9dae693 | 630,911 |
import torch
def coco_category_to_topology(coco_category):
"""Gets topology tensor from a COCO category
"""
skeleton = coco_category['skeleton']
K = len(skeleton)
topology = torch.zeros((K, 4)).int()
for k in range(K):
topology[k][0] = 2 * k
topology[k][1] = 2 * k + 1
t... | 719fa758c2e4361e9a5d4c0509fe073f42df8630 | 630,912 |
import collections
def tail(n, seq):
""" The last n elements of a sequence
>>> tail(2, [10, 20, 30, 40, 50])
[40, 50]
See Also:
drop
take
"""
try:
return seq[-n:]
except (TypeError, KeyError):
return tuple(collections.deque(seq, n)) | 4cf7fa4301f1989ea16a9d653d083fd4edb6bc76 | 630,917 |
import re
def delete_whitespace(text: str) -> str:
"""
Removes whitespaces from text.
"""
return re.sub(r'\s+', '', text).strip() | a4aacdc74ba16fb5072c6fa1a4e2a924fedcdd1b | 630,925 |
def score_to_quality(qval, offset: int=32, maxval: int=126):
"""Convert a score to quality value."""
cval = int(qval) + offset
if cval > maxval:
cval = maxval
return chr(cval) | c4684d15d5cea820cccc91e26b814647896279fb | 630,928 |
def record_variant_id(record):
"""Get variant ID from pyvcf.model._Record"""
if record.ID:
return record.ID
else:
return record.CHROM + ':' + str(record.POS) | 105b5f27095d0cad5e89e54788ab48bb296690f8 | 630,933 |
from typing import List
def chargement_fichier(nom_fichier : str) -> List[str]:
"""Précondition : nom_fichier est le nom d'un fichier texte existant
Retourne le contenu du fichier texte identifié par nom_fichier
sous la forme d'une liste de lignes de texte.
"""
# Lignes contenues dans le fichier
... | ba9589d66801482083433b5403b72d9f13d91400 | 630,934 |
def parse(resp):
"""
Parse response into status line, headers and body.
"""
pos = resp.find(b'\r\n\r\n')
assert pos != -1, 'response is %s' % repr(resp)
head = resp[:pos]
body = resp[pos+4:]
status,head = head.split(b'\r\n', 1)
hdrs = {}
for line in head.split(b'\r\n'):
k... | 483da7c03b3ceb2dcb45f6beb68040e61247794b | 630,935 |
def flatten_board(board):
""" Turns the 3x3 board into a 1x9 board """
return [cell for row in board for cell in row] | 3729070643f0f5409f977181d2d38dfb358c7a15 | 630,936 |
import typing
def get_path_from_list(to_parse: typing.List[str], path_prefix: str) -> str:
"""Parse a path from a list of path parts."""
ret = path_prefix
for i in to_parse:
ret += f"/{i}"
return ret.lstrip("/").rstrip("/") | 90ccb309751d3bff6d816422b50e23bcf799927b | 630,938 |
def _filter_labels(labels, start_datetime, end_datetime, verbose=True):
""" Select the labels whose date in the provided datetime range """
mask = (labels.Date >= start_datetime) & (labels.Date <= end_datetime)
if verbose:
print("Selecting {} out of {} labels".format(mask.sum(), len(labels)))
re... | f794855b779375361ab423bb57ff41ecd0074360 | 630,940 |
import random
def random_float(min=1.0, max=100.0, decimals=None):
"""Generate a random float between min and max.
`decimals` is the maximum amount of decimal places
the generated float should have.
"""
randomfloat = random.uniform(min, max)
if decimals is not None:
randomfloat = roun... | 38a6f76a223d3dec821dd1db9258eedcc7e4984a | 630,941 |
def ip_to_int(ip):
"""
>>> ip_to_int(None)
0
>>> ip_to_int('0.0.0.0')
0
>>> ip_to_int('1.2.3.4')
16909060
"""
if ip is None:
return 0
result = 0
for part in ip.split('.'):
result = (result << 8) + int(part)
return result | 030fad68684cde8a132df6f5e5891f11a6bf6eb5 | 630,942 |
def is_valid(value, mode):
"""Return True if value is in range of map size.
Mode: WIDTH or HEIGHT, depending what value is checked."""
return False if value < 0 or value > mode-1 else True | 28a027bc96c4ead1b79dec1a895c04a902f31869 | 630,947 |
def get_docs_changed(diffs: str) -> int:
"""Processes diffs from a Pull Request to extract number of doc-type files changed in the PR
Parameters
----------
diffs : str
A string denoting the diffs in the PR
Returns
-------
int
number of files of documentation type that have ... | 8b69cefa16ad216fbf674c9ec7a59b217d109757 | 630,948 |
def check_fit(plaintext: list, ciphertext: list) -> int:
"""Check if ciphertext can fit in plaintext's whitespace.
Sum number of blanks in **plaintext** and compare to number of characters
in **ciphertext** to see if it can fit.
Args:
plaintext (list): Paragraphs of a fake message in a list of... | 5910f4c35e4fb270481a0d94914c5f6faac1732b | 630,951 |
import re
def to_lowercase_alphanum(text):
"""Remove non-alphanumeric characters and convert text to lowercase.
"""
return re.sub(r'[^a-z0-9]', '', text.lower()) | e508e708b964775660a9d188f2ff91e02ea42eaa | 630,952 |
import math
def obliquity_of_ecliptic(t: float) -> float:
"""
Calculate the obliquity of earth's ecliptic around the sun in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The obliquity of earth's ecliptic at the given t... | 9ef9cbc9289ceaa19c113c9e98a771ae8f58b1ff | 630,955 |
def fractional_tune(tune):
""" Returns the fractional tune."""
return tune - int(tune) | 4c7b5e5539cd9f1ab8afa62cc20afec182f375b4 | 630,958 |
def euclid(a, b):
"""
Extended Euclidean Algorithm; finds (x,y,z) such that ax + by = gcd(a,b) = z
Written with help from
http://en.literateprograms.org/Extended_Euclidean_algorithm_%28Python%29
Input:
(a,b) two integers
Output:
(x, y, z) integers such that ax + by = gcd(a,b) ... | fea2d6c15d3cd170d1db63675cd4b2e01d68a1c7 | 630,961 |
from typing import Iterator
from typing import Dict
from typing import Tuple
from typing import Optional
import logging
def _parse_as_to_org_map_remainder(
f: Iterator[str], org_id_to_country_map: Dict[str, Tuple[str, str]]
) -> Dict[int, Tuple[str, Optional[str], Optional[str]]]:
# pyformat: disable
"""Retur... | 5f3028b97ff97316a5359203890387d6a4edaf34 | 630,962 |
def is_special(pat):
"""Whether the given pattern string contains match constructs."""
return "*" in pat or "?" in pat or "[" in pat | 1d8b82c925dfbae343382afd91664133120087f8 | 630,964 |
def ReadIDList(infile, delim=None):#{{{
"""
Read a file containing a list of sequence IDs.
"""
try:
fpin = open(infile,"r")
li = fpin.read().split(delim)
fpin.close()
if delim != None:
li = [x.strip() for x in li]
return li
except IOError:
... | 99cf4d55383d07faa08e72fbaa8b0eeca5b49f10 | 630,965 |
import re
def find_ipv4_with_subnet(string):
"""
Find and return IPv4 address with subnet inside a string.
This function will only return an ipv4 address with a subnet
:param string: (str) The string to search for ipv6 with subnet(i.e. "Successfully added Subnet 10.34.33.20/30")
:return: (str) ... | adc6c73258b7ddb365151f9b729441be8d82a680 | 630,966 |
from typing import List
def create_table_dropdown(order_list: List[dict], order_name: str) -> dict:
""" Create the dropdown-options in the context of assembling orders.
Syntax of the returned dictionary is based on dash.
"""
dropdown_options = {
'component': {
'options': []
... | c7885fc28964df79289dacbe96592d2bb9f1bbc1 | 630,971 |
def get_values_lengthes(dictionary):
"""returns the sum of the lengthes of values of a dictionary"""
return sum(map(lambda value: len(value), dictionary.values())) | 63718868ad50dfe38639b1bb21cec93d7d220c40 | 630,972 |
import torch
def _interp_array(start: torch.Tensor, end: torch.Tensor,
num_steps: int) -> torch.Tensor:
"""Linearly interpolate 2D tensors, returns 3D tensors.
Args:
start: 2D tensor for start point of interpolation of shape [x,y].
end: 2D tensor as end point of interpolation of ... | 232ca65e13d4896c7c0e580bd48f8629b4622573 | 630,975 |
def node_is_shortcuttable(node_i, path, netgraph, rev_netgraph):
"""
Given a index node_i in path and path (list of node numbers) containing node
and the two graph (dict of dicts) structures
where rev_netgraph is just graph with all links reversed, return
True if the node has links only to and from ... | eaabee5cadf80accca728dd00916eacad28b4b44 | 630,986 |
def GetRegionFromZone(gce_zone):
"""Parses and returns the region string from the gce_zone string."""
zone_components = gce_zone.split('-')
# The region is the first two components of the zone.
return '-'.join(zone_components[:2]) | f877337e010af381ad921eb258b0098ab2941988 | 630,989 |
def key(resource):
"""
Returns key name based on resource
"""
return {
'token': 'address',
'pool': 'address',
'address': 'address',
'allowance': 'hash',
'balance': 'hash',
'claim': 'hash',
'wallet': 'hash',
'transaction': 'hash',
't... | 8cd60e306d74ad6f12eaba07478a4bed86f1bc94 | 630,990 |
def is_first_read(flag):
"""
Interpret bitwise flag from SAM field.
Returns True or False indicating whether the read is the first read in a pair.
"""
IS_FIRST_SEGMENT = 0x40
return (int(flag) & IS_FIRST_SEGMENT) != 0 | 4620951597ef2dc481638ecb86b3500ff6475126 | 630,992 |
def comment_code(code_str, line_comment=None, block_comment=None):
"""Adds comments to a snippet of code.
If line_comment is a given string then each line is prepended with the
line_comment string.
If block_comment is a tuple of two strings (begin, end) the code str is
surrounded by the strings.
... | 3868a3d2114b9d9f0e30e8dac6120f597b8b2676 | 630,993 |
def from_image_url(url: str, width: int, height: int) -> str:
"""
Generates GIFT text for a URL.
Parameters
----------
url : str
Input URL.
width : int
Desired width of the image.
height : int
Desired height of the image.
Returns
-------
out: str
GIFT-ready text.
"""
# either both are set or non... | 5b3426b54161d98d98a25e04c6a46d8327691e77 | 630,995 |
import torch
from typing import Optional
def create_src_lengths_mask(batch_size: int, src_lengths: torch.Tensor, max_src_len: Optional[int] = None):
"""
Generate boolean mask to prevent attention beyond the end of source
Inputs:
batch_size : int
src_lengths : [batch_size] of sentence lengths
... | b26c42a5fdc0ec25c1320d4db668e457ada30af2 | 630,996 |
import functools
import random
import time
def rare_delay(delay: float, probability: float):
"""
Decorator to add a fixed random delay before executing the function
with a given probability.
:param delay: Delay in seconds.
:param probability: Probability of delaying the function execution.
:re... | cba0e1d43137bb06173d6a34d2e6c16851047141 | 630,997 |
import random
def rand_index(word):
"""
Returns a random index in a given text.
"""
return random.randint(0, len(word)-1) | 1c33c88742a9ffb06b3515fb7950c96fc951cf65 | 631,000 |
def get_previous_timestep(timesteps, timestep):
"""Get the timestamp for the timestep previous to the input timestep"""
return timesteps[timesteps.ord(timestep) - 1] | 8e41bccf87ae0b6b68c70cfdc522aca3f61565bd | 631,002 |
import math
def latlon2tms(lat,lon,zoom):
"""
Converts lat/lon (in degrees) to tile x/y coordinates in the given zoomlevel.
Note that it doesn't give integers! If you need integers, truncate
the result yourself.
"""
n = 2**zoom
lat_rad = math.radians(lat)
xtile = (lon+ 180.0) / 360.0 *... | f4c238ad3af7635f6a812021cc38744a73a0a437 | 631,003 |
def map_values(function, dictionary):
"""Map ``function`` across the values of ``dictionary``.
:return: A dict with the same keys as ``dictionary``, where the value
of each key ``k`` is ``function(dictionary[k])``.
"""
return {k: function(dictionary[k]) for k in dictionary} | 569225e40969bb5962779344b68ea8963af8f576 | 631,006 |
import inspect
def get_func_args(func, args, kwargs):
""" 获得函数的所有参数信息,保存在 func_args 中
输入:
func: 函数体
args: 传入的位置参数列表
kwargs: 传入的命名参数列表
"""
# 获得当前函数的所有参数信息
full = inspect.getfullargspec(func) # 含缺省值定义
# FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=... | 7b3c6908897d21e3ae4d7bbcd9fd7f45cd671f5b | 631,007 |
def clean_cos(value):
"""
Limits the a value between the range C{[-1, 1]}
@type value: float
@param value: The input value
@rtype: float
@return: The limited value in the range C{[-1, 1]}
"""
return min(1, max(value, -1)) | a3328c90852e4ed788e6e60e7947b10215734240 | 631,011 |
def sliding_window(l, n):
"""
Creates a sliding window of given length over a list.
Examples
--------
>>> l = range(5)
>>> sliding_window(l, 2)
[[0, 1], [1, 2], [2, 3], [3, 4]]
"""
rngs = range(0, len(l) - n + 1)
return map(lambda rng: l[rng:rng + n], rngs) | 57f677ad14cad4660a03ad0f6b43d8f2b596ae05 | 631,012 |
import tqdm
def apply_groups(groups, client, func, *args, return_futures=False,
progress_bar=True, **kwargs):
""" Call `func` on each group in `groups`.
Additionally, `args` and `kwargs` are passed to the function call.
Parameters
----------
groups: pandas.DataFrameGroupBy
The re... | 5bca1f2eb0945fa72c517134b0ea4deaf61ecd23 | 631,014 |
def refine_digits_set(digits):
"""美化连续数字的输出效果
>>> refine_digits_set([210, 207, 207, 208, 211, 212])
'207,208,210-212'
"""
arr = sorted(list(set(digits))) # 去重
n = len(arr)
res = ''
i = 0
while i < n:
j = i + 2
if j < n and arr[i] + 2 == arr[j]:
while j <... | 6775501305ec81821aea99afd32f99bf332f6e67 | 631,016 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.