content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def filter_cpg_dict_by_cov(cpgDict, coverage=1):
"""
Filter cpg with coverage
Args:
cpgDict:
coverage:
Returns:
"""
if coverage <= 1:
return cpgDict
retDict = {}
for key in cpgDict:
if len(cpgDict[key]) >= coverage:
retDict[key] = cpgDict[key... | e5f325d575f76b0d9c30d84a725bf8455948da89 | 647,557 |
import doctest
def test_all():
"""Run all tests."""
return doctest.DocFileSuite('README.rst') | 4f6140f602b17781dd7d788fe2b8b305d203b095 | 647,558 |
import os
import re
def _get_current_version(session):
"""\
Returns the current Segno version.
"""
fn = os.path.abspath(os.path.join(os.path.dirname(__file__), 'qrcode_artistic.py'))
with open(fn, 'r', encoding='utf-8') as f:
content = f.read()
m = re.search(r'^__version__ = ["\']([^"\... | 6219899d028a03c5b6efcb53433f170cf101bd5b | 647,559 |
import hashlib
def _hash_gene(gene, length=6):
"""Get the first letters of the SHA-1 digest of the gene."""
encoded = sum(
v * 4 ** i for i, v in enumerate(gene)
).to_bytes(13, byteorder='big')
digest = hashlib.sha1(encoded).hexdigest()
return digest[0:length] | 981722aeafeef4899a858da9998fe95046207218 | 647,560 |
import os
def get_default_usubs():
""" Return the default user subroutines
:returns: Two lists containing the default (required) subroutines
for the rollover simulation to work.
:rtype: list[ list[ str ] ]
"""
this_dir = os.path.dirname(os.path.abspath(__file__))
u... | 4d3560d8e5d850c084cc80e1594e68df277da1e5 | 647,561 |
def _tags_to_dict(s):
""" "k1=v1,k2=v2" --> { "k1": "v1", "k2": "v2" } """
return dict(map(lambda kv: kv.split('='), s.split(","))) | 62387274b9cf033909e4d37dbd804b714afb8c2e | 647,562 |
import copy
import re
def _certificate_info_matches(cert_info, required_cert_info, check_serial=False):
"""
Return true if the provided certificate information matches the
required certificate information, i.e. it has the required common
name, subject alt name, organization, etc.
cert_info should... | 103b576685c807a57a8788bbc4a603dd56ecf6ef | 647,564 |
def status_transfer(status, running_status_list, failed_status_list):
"""status display for frontend"""
if status in running_status_list:
return "running"
elif status in failed_status_list:
return "failed"
return "success" | dba9bdbb0f7c2b38b1e1f40447b0d78025f444f0 | 647,565 |
def formatStyle(a):
"""Format an inline style attribute from a dictionary"""
return ";".join([att+":"+str(val) for att,val in a.iteritems()]) | e7c615c2c3ed24014b1f2922aac8cf9789826929 | 647,566 |
import re
def _get_log_fname(mtz_fname):
"""
convert an mtz filename to the corresponding main log filename
"""
regex = re.compile(r'(.*)_all.mtz$')
hit = regex.search(mtz_fname)
assert hit is not None
assert len(hit.groups()) == 1
return hit.groups()[0] + '_main.log' | ba70819f29d983535808f23c805814a1a74850df | 647,567 |
def create_connectivity_list(shape, element_offset=0):
"""Use the element indices for each shape to create the connectivity list"""
num_points = len(shape.points)
num_parts = len(shape.parts)
elements = []
for i in range(num_parts):
# parts[] returns the point index at the start of each par... | 7febca3aba0cd6a83ef7ee3370ee57b99e50615c | 647,568 |
def month_difference(from_date, to_date):
"""
gets the number of months between from_date and to_date
could be negative or zero
example usage:
>>> month_difference(datetime(2010,10,1), datetime(2010,11,1))
1
"""
return (to_date.year - from_date.year) * 12 + (to_date.month - from_... | f0dd16b71e97a280e8ec0c0bd557cee45e70b76f | 647,569 |
def index():
"""
Muestra los registros de cuentas por cobrar
"""
return dict() | 85cfc2c062099087b831ac1d4790df20a064ab28 | 647,570 |
def dt_str(dt_object, format_='%Y-%m-%dT%H:%M:%S') -> str:
"""
Converts python datetime object into datetime string
"""
return dt_object.strftime(format_) | 0f4588df718aade8a4850b2f3c04ac161aa44d54 | 647,571 |
def generateFilename(photoInfo, photoNum):
"""Creates a file system file name for a photo.
The file name will be in the format date-taken_title.extension. For
example, 20180521203625_My_Flickr_Picture.jpg. The date taken will be a
numeric string which means the pictures on the file system will sort i... | 0bd1711078dac94fcbf068789b4358a97b05f93f | 647,572 |
def getNestedValue(dictionary, keyString, default=None):
"""
Returns the value from a nested dictionary where '.' is the delimiter
"""
keys = keyString.split('.')
currentValue = dictionary
for key in keys:
if not isinstance(currentValue, dict):
return default
curr... | b5193cf1d29a9877737c4a208f972d566e6214f4 | 647,573 |
def decompressRLElist(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
sublist = []
list_len = len(nums)
if list_len%2==0:
list_len
else:
list_len-=1
for i in range(0, list_len,2):
freq = nums[i]
val = nums[i+1]
for k in range(freq):
... | cdf8a8001d5fb5b012c749d9a5172bd73d175b97 | 647,574 |
def remove_ticks(ax, x=False, y=False):
"""
Remove ticks from axis.
Parameters:
ax: axes to work on
x: if True, remove xticks. Default False.
y: if True, remove yticks. Default False.
Examples:
removeticks(ax, x=True)
removeticks(ax, x=True, y=True)
"""
if x:
ax... | 6f2b9d5b2f76a648ee0f2d4eac45213a83dac7d2 | 647,576 |
import torch
def normalize_tensor_one_minone(
pp: torch.Tensor,
) -> torch.Tensor:
"""
Receives a tensor and retrieves a normalized version of it between [-1, ..., 1].
We achieve this by normalizing within [0, 2] and subtracting 1 from the result.
"""
pp_norm = pp.float()
pp_max = pp_norm.... | 0b013cc324f782c9989848de438abf81339e8077 | 647,577 |
import io
def file_to_corpus(name_file):
"""Transforma as linahs de um arquivo em uma lista. Example: function(my_file.txt) """
rows = []
#with open(name_file, 'r') as read:
#, encoding = "ISO-8859-1" , encoding='utf-8'
with io.open(name_file, newline='\n', errors='ignore') as read: #erro ignore c... | 697b461cc472a49ab30d64864a134b3175a46c61 | 647,578 |
from typing import Optional
def get_description(description: Optional[str]) -> str:
"""Filter. Get the description of a property or an empty string"""
return description or "" | 9d56b2312d8ec45a3321dcfcd7584d5504547839 | 647,579 |
import random
def _select_sample(samples, length, prev_sample):
"""
Selects a sample via a markov chain
Samples should be in the form:
{
'song_name': [ ... samples ... ],
...
}
"""
if prev_sample is not None:
song = prev_sample.song
# Repe... | 9714abd77673ae3e7bf1f116676979c75a9827b3 | 647,580 |
def _tuple():
"""Create registry entry for tuple."""
entry = {
tuple: {
"flatten": lambda tree: (list(tree), None),
"unflatten": lambda aux_data, children: tuple(children), # noqa: U100
"names": lambda tree: [f"{i}" for i in range(len(tree))],
},
}
re... | 81854b4c6ffad335da9552841b02e0710fbc68aa | 647,581 |
import struct
def bytes_to_16s(data, n):
"""大端字节序"""
ret = [0] * n
for i in range(n):
ret[i] = struct.unpack(">h", bytes(data[i * 2: i * 2 + 2]))[0]
return ret | a7472323d1a385276f2ef45c4448bf6ce37fea18 | 647,583 |
import numpy
def calculate_derivatives(histogram):
"""Calculates derivatives of a given histogram
:param histogram: the histogram to calculate derivatives for
:type histogram: numpy.ndarray
:returns: numpy.ndarray -- the derivatives
"""
return numpy.diff(histogram).astype(numpy.float32) | e9ac585ab64cc2061b4be64d1a878df13169a0db | 647,584 |
def Hex2Alpha(ch):
"""Convert a hexadecimal digit from 0-9 / a-f to a-p.
Args:
ch: a character in 0-9 / a-f.
Returns:
A character in a-p.
"""
if ch >= '0' and ch <= '9':
return chr(ord(ch) - ord('0') + ord('a'))
else:
return chr(ord(ch) + 10) | 86917deb9d0f4af8426b880fe8f28ea637747fff | 647,585 |
def _crypt_audio_packet(packet: bytes, key: bytes) -> bytes:
"""Encrypt/decrypt a plaintext/encrypted audios stream payload. Skips encryption/decryption
if packet is less than or equal to 0x140 bytes.
"""
data = bytearray(packet)
if len(data) > 0x140:
for i in range(0x140, len(data)):
... | 1bc1e84e459a9a41d1c8b3b73448579be39c3a34 | 647,586 |
import json
def parse_logfile_evaluation(logFile):
""" takes log file with evaluation settings in JSON format
and parses relevant parts
"""
run_parameters = {}
with open(logFile, "r") as read_file:
json_data = json.load(read_file) # dictionary
for el in json_data['run_paramet... | ce803213fdc34e2aa3883680bf6aef7366c94c99 | 647,587 |
import json
def json_encode(data, *args, **kwargs):
"""Encodes a dictionary into a JSON string
Arguments:
data {dict} -- Dictionary to encoded
Returns:
str -- JSON encoded string
"""
return json.dumps(data, *args, separators=(',', ':'), **kwargs) | 9ba19524250e79ea0830016f04a281ffddbb35bc | 647,588 |
import re
def remove_URL(text: str)-> str:
"""
Removes URL patterns from text.
Args:
`text`: A string, word/sentence
Returns:
Text without url patterns.
"""
url = re.compile('https?://\S+|www\.\S+')
text = url.sub('',text)
return text | 2b992490591030e2c2be29d0df9ab38d1bd66ddb | 647,589 |
import json
def apply_threshold(in_file, threshold):
"""
apply threshold
"""
out_file = in_file[:-5] + '-' + str(threshold) + '.json'
with open(in_file) as data_file:
data = json.load(data_file)
for person_id in range(len(data)):
keypoints = data[person_id]["keypoints"]
... | 020d1b9a8bdb2300a72888961b5f4c59842d9212 | 647,590 |
def split_by_bar(abc_string):
"""
Takes a string of full ABC notation and splits it into lists representing individual bars
"""
result = abc_string.split('|')
return [x for x in result if x != ''] | f6a44d9fce478c491a4072f0c27998a31d169a65 | 647,591 |
def _unstack(obj):
"""
Private function used to reorder to use the work dimension as the first
dimension, stack all the dimensions except the first one
"""
if 'temp_dim' in obj.dims:
obj_unstacked = obj.unstack('temp_dim')
else:
obj_unstacked = obj
return obj_unstacked | 011b60d8d5d242461de482e771506a117c25d741 | 647,593 |
import math
def convert_bytes(size):
"""Make a human readable size."""
label = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
try:
i = int(math.floor(math.log(size, 1024)))
except ValueError:
i = 0
p = math.pow(1024, i)
readable_size = round(size/p, 2)
return '{}{}'.... | b4b070e85d31c0c607422667aa7f79bc0c21bcfc | 647,594 |
def objtag(accessing_obj, accessed_obj, *args, **kwargs):
"""
Usage:
objtag(tagkey)
objtag(tagkey, category)
Only true if accessed_obj has the specified tag and optional
category.
"""
if hasattr(accessed_obj, "obj"):
accessed_obj = accessed_obj.obj
tagkey = args[0] i... | 7c730527b292fdd4dc8f0e26680a2c78fae0f551 | 647,595 |
def rec_replace(l, d):
""" Recursively replace list l with values of dictionary d
ARGUMENTS:
l - list or list of lists
d - dictionary where if an element in l matches d['key'], it is replaced by the value
OUTPUT:
l - list with elements updated
"""
... | 8b4bb40238d8304f5da8c5b5408541a2742b7ea1 | 647,596 |
import time
def rdkit_desc(mols, functions, names, verbose=True):
"""
Calculate RDKit descriptors for a set of molecules.
Returns calculated descriptors in a dict by their name
"""
start = time.time()
descriptors = {}
for function, name in zip(functions, names):
desc = [functi... | 4f57831da3314a3ec557feb93632ee53512aa217 | 647,598 |
from typing import List
def missingNumber2(nums: 'List[int]') -> 'int':
"""
解法3:异或
"""
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing | 09de9cee1719c6c809f242d8ad642501590765c7 | 647,599 |
def wxToGtkLabel(s):
"""
The message catalog for internationalization should only contain
labels with wx style ('&' to tag shortcut character)
"""
return s.replace("&", "_") | a6952cd35093d2b9188285c077c1c6546eec611a | 647,600 |
def _map(args):
"""Mapping helper function for mp_list_map."""
lst, fnc, kwargs = args
return fnc(list(lst), **kwargs) | 18326e23549216bd16f80057d50935bf4b52f914 | 647,601 |
def maior_precisao(lista):
"""
Auxilio para yicks...
Devolve a maior precisao de entre o inicio dos yticks, e o step dos yticks
:type lista: ``numpy arange()``
:param lista: lista de valores (x-axis ou y-axis)
:return: Devolve maior precisao de entre o inicio dos yticks, e o step dos yticks
"""
if len(li... | 1e7f336ae6da6c6b660c27dbf1a494f5893a1276 | 647,602 |
def read_file(name):
"""
Reads the content of a text file specified by the user.
"""
file = open(name, 'r', encoding="UTF-8")
return file.read() | 364ca6419dfd8bb56f35616ce2db0cc3265aafe5 | 647,603 |
import math
def is_prime(n):
"""Return True if n is a prime number, else False."""
return n >= 2 and not any(
n % p == 0 for p in range(2, int(math.sqrt(n)) + 1)) | 9f85a0e67cf3420cbf07c3f915af7eeb9e931f48 | 647,604 |
def setRegisterNumbersForTemporaries(ast, start):
"""Assign register numbers for temporary registers, keeping track of
aliases and handling immediate operands.
"""
seen = 0
signature = ''
aliases = []
for node in ast.postorderWalk():
if node.astType == 'alias':
aliases.ap... | 6d64c17af9667963a2e36edb8a39aad6e1dfd929 | 647,605 |
def _cldf2wld(dataset):
"""Make lingpy-compatible dictinary out of cldf main data."""
header = [h for h in dataset.rows[0].keys() if h != 'ID']
D = {0: ['lid'] + [h.lower() for h in header]}
for idx, row in enumerate(dataset.rows):
D[idx + 1] = [row['ID']] + [row[h] for h in header]
return D | b85f4a0f5e1dea77ef57a7848bd50a35b4c875e1 | 647,606 |
def get_block_id(color, id_tag="00"):
"""Get block identifier based on color
Args:
color (string): string representation of color
id_tag (string, optional): prefix for the object. Defaults to "00".
Returns:
string: block identifier as string
"""
return "%s_block_%s"... | 52ad52a24f5719f51cc976b464c4e74ef51cab33 | 647,607 |
def add_tune_params(parser):
"""
define hyperparam-tuning params
"""
parser.add_argument('--num_samples', type=int, default=15)
parser.add_argument('--gpus_per_trial', type=int, default=1)
parser.add_argument('--cpus_per_trial', type=int, default=7)
parser.add_argument('--grace_period', type... | 9f998cf50a0d1cd49a37d9b77962917bc82ca9d3 | 647,608 |
def findStartOfLine(text,offset,lineLength=None):
"""Searches backwards through the given text from the given offset, until it finds the offset that is the start of the line. With out a set line length, it searches for new line / cariage return characters, with a set line length it simply moves back to sit on a multip... | c1b8b055ef91a53a618b8bddf4915c47e7bef631 | 647,610 |
def dodo_existing(tmpdir):
"""
Set up a project with a DODO file
"""
prjdir = tmpdir.join('projdir')
prjdir.ensure(dir=True)
prjdir.join('.project').ensure()
dofile = prjdir.join('DODO')
dofile.write("\n - this is a task\n")
return (prjdir, dofile) | 66bf3a3162091b957adfcac0d7f6d78690632477 | 647,611 |
def get_video_play_url(video):
""" Find playback_url for video target named 'high', in case there isn't
one, returns the first target on the list. Change this to the specific
target name you wish to play.
"""
if len(video['targets']) > 0:
target = next((target for target in video['ta... | f5e2f8fc0a25a6fa21dabc38248ebaf95c16302c | 647,612 |
import os
def GetCurrentDirectory():
"""
Library function to return current directory
:return: dictionary or string
data: - Dictionary:
Keys: returnCode
:returnType: dictionary / string
"""
currentDir = os.getcwd()
if currentDir is None:
retStruct = dict()
... | 4f2b9b1c160e810160dfd107010184fb5118cb05 | 647,613 |
def get_theta_bounds(priors):
"""
Returns the state vector parameters bounds.
Parameters
----------
priors : list of instantiated Prior objects
:class:`Prior` vector
Returns
-------
bounds : list
List of (min, max) tuples
"""
return [prior.get_bounds() for prior... | 440348e552027ebb51f92962fea5d537c7c4916f | 647,615 |
def title(snake_case: str):
"""Format snake case string as title."""
return snake_case.replace("_", " ").strip().title() | 362161e7cbfc2451bd3cb3bcb60ef4cfa2eaf415 | 647,616 |
def merge_duplicate(merged_streams_in_island_list):
"""
Merge lists that have at least one common element into one list.
:param merged_streams_in_island_list: list of lists to test and merge
:type merged_streams_in_island_list: list of lists
:return: list of merged lists
:rtype: list o... | f461121f3310a007a1058a4ac64a5e71415428b4 | 647,617 |
from pathlib import Path
from datetime import datetime
def most_recent_run(outputs_path, fmts=["%Y-%m-%d", "%H-%M-%S"]):
"""Get the most recent Hydra run folder.
Parameters
----------
outputs_path : pathlib.Path or str
The root Hydra outputs directory
fmts : list
Optional list of ... | 4440f95390550997f2b88b1454d6095d4f2860d0 | 647,618 |
def sortByLabels(arr, labels):
"""
intended use case: sorting by cluster labels for
plotting a heatmap
"""
return [x[1] for x in sorted(enumerate(arr), key=lambda x: labels[x[0]])] | ddebfeb817e85af942fc9b686f000e39d3c9cbf6 | 647,619 |
import numpy
import math
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
>>> q = quaternion_from_matrix(numpy.identity(4), True)
>>> n... | 4759f43814de95f00ebb1c82f9215f4490801d88 | 647,620 |
def _unix_user(username):
"""Converts a username from the jupyterhub login to a proper username
for the docker virtual machine"""
if '@' in username:
return username.split('@')[0]
# The username in the container is not critical, it's mostly a gimmick.
# If it's not an email address (which ... | dcf115ab89264af33b2e973d2fef9a76d7342f41 | 647,621 |
def b_overlap_a(a, b, alab='a', blab='b', verb=False):
"""Check if there is any value in `b` inside the range of the values in `a`.
Only checks if there is overlap, but not how (e.g. do not tell if all values of b inside a, or just from one side).
Examples
--------
a: ' |---| '
b: '|--... | 1fd137cf4ff3bf13440e5543fa574b15472ca091 | 647,622 |
def writeBenchScript(dir, benchmark_name, size, output_path):
"""
This method creates a script in dir which will be eventually
passed to the simulated system (to run a specific benchmark
at bootup).
"""
input_file_name = '{}/run_{}_{}'.format(dir, benchmark_name, size)
with open(input_file_n... | 4d5d48aa57b7568f8596cdde29a5856507028287 | 647,623 |
def Artifact(file_path, view_url=None, fetch_url=None,
content_type='application/octet-stream'):
"""Build an Artifact dict.
Args:
file_path: A string with the absolute path where the artifact is stored.
view_url: An optional string with a URL where the artifact has been
uploaded to as a ... | 605c865b92090906aa91d89d7782d377826ed3cb | 647,624 |
def filter_combinations(combinations, mode):
"""
Filter a list of combinations, extracting only those which satisfy the condition of filter mode.
:param combinations: a list with all the combinations to filter
:param mode: the filter mode
:return: a list of the filtered combinations.
"""
fil... | 92a6cfca2391239fd1210b3126faf01ced9c80a7 | 647,625 |
def careful_update(adict, bdict):
"""
Carefully updates a dictionary with another dictionary, raising a
ValueError if keys are shared.
"""
if not set(adict.keys()).isdisjoint(set(bdict.keys())):
raise ValueError('adict shares keys with bdict')
else:
adict.update(bdict)
... | ed5eca1a867fe3bc0aac60886c457b58f5997e9d | 647,626 |
def test():
"""测试用接口
"""
return "Hello Task Network" | 160875aea6c988851670583326964fce0a8bff68 | 647,627 |
def extend_dataset_features(dfs):
"""
This function will take a dataframe (elements in list dfs) and extend the features accordingly
:param dfs: List with dataframes over which we want to extend the features
:return: Dict of extended dataframes
"""
extended_dfs_dict = []
for df in dfs:
... | 24997349795b2f4083f01d344287829c08d14069 | 647,628 |
def binnify(test, lower, upper, bins):
"""Compute a bin index for the 'sounding' raster display."""
# No, I don't remember why this works. It's not hard to figure out though.
bins -= 1
ul = upper-lower
bs = ul/bins
return max(0, int(round(min(bins, bins*(test-lower)/ul), 0))) | 2661a32ad4b9f39b8b9bf763c860f7e5a80d342e | 647,629 |
def some_other_function():
"""Dummy function"""
return None | 92be4cf0560f454f29248e7a485f65d861631f45 | 647,630 |
def assign_rank_group(atom_num, assign, rank, rank_num):
"""
|
**Description:** Assign rank to each group
**Input:**
- atom_num: Atom respectively which we are producing the rank from
- assign: Group of molecules grouped on clusters dependiong on the ligand connectivity
- rank: list o... | 5409e378eb751f803c34a12db3a44732536cf041 | 647,632 |
import traceback
def _uno_extract_printable_stacktrace(trace):
"""Extracts a printable stacktrace.
Referenced from pyuno shared lib and pythonscript.py.
"""
return ''.join(traceback.format_tb(trace)) | cf23c1ddd8259c8d4bc02e0a0103ad48125dd098 | 647,633 |
def numerical_diff(self, f, x):
"""
(function) numerical_diff
-------------------------
- Calculate numerical difference
------------------------
Parameter
---------
- f : input function
- x : input value(s)
Return
------
- numerical difference value(s)
"""
# Ca... | 10c55b71d13ee04e9be0e239d817cfa2cc93b8d6 | 647,634 |
def update_dict_key(dict_value, key_map):
"""将字典中的key进行修改
Args:
dict_value:原始字典
key_map: key映射dict类型
Returns:
返回修改后的字典
举例:
dict_value = {'a':1,'b':2}
key_map = {'a':'c'}
返回值new_val = {'c':1, 'b':2}
"""
new_val = dict_value.copy()
for k, v in ke... | bf4d78798514144ac5c1396f67558480c3f7affd | 647,635 |
def create_lookup_tables(unique_words):
""" Create lookup tables for word_to_id and id_to_word
Args:
unique_words: dictionary of words in training set
Return:
word_to_id: dict with words as keys and corresponding ids as values
id_to_word: dict with ids as keys and corr... | 44a99e615c5be147039a2c030e8a45a8c01080b2 | 647,636 |
import shutil
import os
def get_terminal_size(fallback=(80, 24)):
"""Look up character width of terminal."""
try:
return shutil.get_terminal_size(fallback)
except Exception: # pragma: no cover
return os.terminal_size(fallback) | e610d2fc1cfc76743681aa16a0d58e24608fa50f | 647,637 |
def data_args(parser):
"""This is a helper function of the function :func:`parse_cmd_arguments` to
add an argument group for options specific to the dataset generation.
Args:
parser: Object of class :class:`argparse.ArgumentParser`.`.
Returns:
The generated argument group.
"""
... | 59c7ee68da0b16a5cfe2f98b89ec559a95057865 | 647,638 |
import urllib3
def read_pdbid(pdbid):
"""
Read a pdb file from the PDB. Need an internet connection.
Parameters
----------
pdbid: Name of the pdb file. (ex: 1dpx or 1dpx.pdb)
Return
------
The content of the pdb file
"""
# URL of the PDB
url = 'http://files.rcsb.org/downl... | b4eb2f0d4b20be877faa0e2f4df0a4a2825841ae | 647,640 |
from typing import Dict
from typing import List
import string
def generate_encoding_indexes(seps) -> Dict[int, List[str]]:
"""Generate encoding indexes for the provided separators."""
return {
n: [j for i, j in enumerate(string.ascii_letters) if (i % 10 == n and j not in seps)]
for n in range(... | 3ae0a7ff09966ea5cce9d3f9890d32ddb7205081 | 647,641 |
import sys
def _fmt():
"""Produce library naming scheme."""
if sys.platform.startswith('darwin'):
return 'lib%s.dylib'
if sys.platform.startswith('win32'):
return '%s.dll'
if sys.platform.startswith('cygwin'):
return 'lib%s.dll'
return 'lib%s.so' | 41b506be2e7c5162f929c983fed323bb9a787d5f | 647,642 |
def single_structure_property_predicted(body):
"""
Method for make message as dict with data which would be send to rabbitmq
ml single structure property predicted queue
:param body: body of message received from RabbitMQ queue
:type body: dict
:return: single structure property predicted messa... | a18eef6efe28a5e7f8f65637ec3d42fd34e88f93 | 647,643 |
def word_splitter(df):
""" This function takes pandas dataframe as input, split the sentence into a list of separate words and returns a modified dataframe
Example
Input:
Tweets Date
@IamGladstone @CityPowerJhb @HermanMashaba The... 2019-11-29 11... | aa11ba70a2c6de89fd048ad100c88b5056876c98 | 647,644 |
from typing import Awaitable
from typing import Dict
from typing import Any
import aiohttp
import json
async def download_data(url) -> Awaitable[Dict[str, Any]]:
"""The download_data method downloads json data from the `url`.
Args:
url (str): the url that the user wants to download
Returns:
... | ee27b08a61dc008fdcfd2d4f80316d259fe0fd5c | 647,645 |
def xeval(sexpr):
"""
>>> xeval('')
0
>>> xeval('1234567')
1234567
>>> xeval('+1234567')
1234567
>>> xeval('-1234567')
-1234567
>>> xeval('2+3')
5
>>> xeval('2-3')
-1
>>> xeval('2-23+4')
-17
>>> xeval('2-01+3-1')
3
>>> xeval('1-2-3-4-5')
-13
... | 9e7f8120b9f546fdc94c08ab0ee9978d528309f2 | 647,646 |
def set_option_parsing_recorder_cpu_specification(p):
"""specify information about a single recorder (RAM, num cores to use, cache size) directly"""
p.add_argument("--recorder_num_cores", type=int, default=0, help="*OPTIONAL* number of CPU cores to use for LuMP recording. If 0 is specified, the software will ... | 731214f39fffb9eb9f71491ee09609dae86bab08 | 647,647 |
def _basename(repository_ctx, path_str):
"""Returns the basename of a path of type string.
This method is different from path.basename in that it also works if
the host platform is different from the execution platform
i.e. linux -> windows.
"""
num_chars = len(path_str)
for i in range(num_... | 01e1b28cf1e2c9bfcdf411cb996a5daeb74dc981 | 647,648 |
from typing import List
import math
def next_timeout(candidates: List[float], percentile: float) -> int:
"""Cacluate timeout for the next round.
:meta private:
"""
candidates.sort()
num_included = math.ceil(len(candidates) * percentile)
timeout_raw = candidates[num_included - 1]
timeout_c... | d96b37d3cb36210fa46d81c99467f7b8e1222aa5 | 647,649 |
from pathlib import Path
from typing import Dict
import re
def parse_debian_control(cwd: Path) -> Dict[str, str]:
"""
Extract fields from debian/control
:param cwd: Path to debian source package
:return: Dict object with fields as keys
"""
field_re = re.compile(r"^([\w-]+)\s*:\s*(.+)")
co... | 4788719a9322703807f0e87ee431e1a160f98fac | 647,650 |
def _get_cover_address(metadata):
"""Returns cover address.
Returns
-------
int
cover address
"""
if 'COVER_1' in metadata.footer:
address = int(metadata.footer['COVER_1'])
else:
address = 0
return address | 20fa5cda7b26034835900d60bafcf1894596cef7 | 647,651 |
def f_check_param_definition(a, b, c, d, e):
"""Function f
Parameters
----------
a: int
Parameter a
b:
Parameter b
c :
Parameter c
d:int
Parameter d
e
No typespec is allowed without colon
"""
return a + b + c + d | 7839e19f0b9025f895409f9fb3837b8ca34f6023 | 647,652 |
import requests
from typing import Optional
def get_base_url(req: requests.Response) -> Optional[str]:
"""
Get base URL from url.
"""
if req and req.url.find('/'):
return req.url.rsplit('/', 1)[0]
return None | fe01d0589bc2bb83ca4aeffa75692569fa433998 | 647,653 |
def end_ea(obj):
"""
Return end ea for supplied object.
:param obj: Object to retrieve end ea.
:return: end ea.
"""
if not obj:
return None
try:
return obj.endEA
except AttributeError:
return obj.end_ea | 8960419bc65833813e131358e3b12b90d036930f | 647,654 |
import uuid
import os
import shutil
def _zip_artifacts(model_artifacts_path: str) -> str:
""" Zip artifacts from mlflow run
:param model_artifacts_path: directory with model artifacts
:return: temporary zip file name
"""
file_name = str(uuid.uuid4())
file_path = os.path.join(model_artifacts_... | c9667f84146a0b5e5fb174b500274912b817841c | 647,655 |
from typing import OrderedDict
def remove_duplicates(block):
"""
>>> remove_duplicates('AAB')
>>> 'AB'
"""
freq = OrderedDict()
for c in block:
freq[c] = freq.get(c, 0) + 1
return ''.join(freq.keys()) | d5f5c23e81c8612e8af51b3ce549e677bdebb74d | 647,656 |
import random
import string
import os
def bad_filename():
"""Generate a bad filename"""
while True:
file = ''.join(
random.choice(string.ascii_lowercase) for i in range(10))
if not os.path.isfile(file):
return file | 1deae67d85da10b43d6ee429e42c9a6bb5f8ce2d | 647,657 |
def get(isdsAppliance, check_mode=False, force=False):
"""
Get host records
"""
return isdsAppliance.invoke_get("Retrieving current host records",
"/host_records") | 4902789cc35bd60093feffcd95daec713f453254 | 647,658 |
import numpy as np
def _ds_drew(s,ah,Rg,G0,Aw):
"""
Returns ds/d(rew)
"""
x = lambda s: np.sqrt((Rg**2-s**2)/(ah**2+s**2))
y = lambda s: np.sqrt((ah**2+s**2))
dsdrew = 1/(2*Aw*G0)/(s*np.arctan(x(s))/y(s)**3 + (1+x(s)**2)*y(s)*s*x(s)/(Rg**2-s**2)/y(Rg)**2)
return dsdrew | daab8a0e372bcd275f1449410fe4d70687ece861 | 647,659 |
def parse_seeds(seeds):
""" parse website seeds.
@params
seeds example:
- url1
- user1:pwd1@url1
- user1:pwd1@url1|url2|user3:pwd3@url3
"""
seeds = seeds.strip().split('|')
website_list = []
for seed in seeds:
if '@' not in seed:
we... | 7a50a028e127862fff5d1b5592e72f1c258061b8 | 647,661 |
def fix_id(fid):
"""As a temporary measure, escapes certain special characters in a name.
Right now, a measure like this is required to make Vega* work properly
with various field names.
See https://github.com/vega/vega-lite/issues/4965.
"""
new_id = ""
for c in fid:
if c == ".":
... | b53b9c7a2cd3bfde36015c635a5e5f1eefca908f | 647,662 |
def chunk(array, num_memory_steps):
"""Chunk an array into size of N steps.
The array of size N x k_1 x ... k_n will be reshaped to be of size
Batch x num_memory_steps x k_1 x ... k_n.
Parameters
----------
array: Array.
Array to reshape.
num_memory_steps: int.
Number of st... | 90ae3e049e95aa38a8eb35f06c80875874160315 | 647,663 |
def compute_CdS_from_drop_test(
terminal_velocity, rocket_mass, air_density=1.225, gravity=9.80665
):
"""Returns the parachute's CdS calculated through its final speed, air
density in the landing point, the rocket's mass and the force of gravity
in the landing point.
Parameters
----------
t... | 17d56bf6fb35f363eeb2ba398cf17a4e3b988435 | 647,664 |
def cvars(occs):
"""
Return a single representative occurrence for each variable.
"""
names = []
canonicals = []
for occ in occs:
if occ.name in names:
continue
canonicals.append(occ)
return canonicals | 939490076d20ba686f6547a36914452500b15af8 | 647,665 |
def convert_to_babylonian_time(seconds):
###############################################################################
"""
Convert time value to seconds to HH:MM:SS
>>> convert_to_babylonian_time(3661)
'01:01:01'
"""
hours = int(seconds / 3600)
seconds %= 3600
minutes = int(seconds / ... | da785fe6f76dc4e22c96a741fd50749b46da125b | 647,666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.