content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pivotpoint(arr, first, last):
""" pivot point strategy
using median of first, mid and last elements
to prevent worst case scenario and
overcome recursion max depth """
mid = first + (last - first) >> 1
if (arr[first] - arr[mid]) * (arr[last] - arr[first]) >= 0:
return f... | 6e02516d5114c320cfb87dad3300edba83528884 | 687,865 |
def create_obj(d):
"""Create an object from a dict"""
return type('D', (object,), d)() | 5a95b32ed5f7e7b47919da3da590d13c80901d91 | 687,866 |
def get_option(name,project,default=None):
"""
Get an option flag from the project structure, returning None if
the flag is not defined.
"""
if 'options' not in project:
return default
if name not in project['options']:
return default
return project['options'][name] | 6e59ca528c5cdfaf0a1fb126d91df663686c8a06 | 687,867 |
import re
def read_segmentation(word_boundary_path):
"""
Args:
word_boundary_paths (list): list of paths to word boundary files
Returns:
segmentation_dict (dict):
key (string): utt_index
value (list): list of [start_frame, end_frame, word]
"""
segmentation_d... | 3f13c702e457bacc6d470d0529269339a0247f8d | 687,868 |
def zero_pad(num, digits):
""" for 34, 4 --> '0034' """
str_num = str(num)
while (len(str_num) < digits):
str_num = '0' + str_num
return str_num | 323a938a254fc5eb733e41e55db879daed9df1e2 | 687,869 |
import os
def get_interfaces():
"""
:return:
a python list of network interfaces/adapters
"""
eths = []
srcpath = '/sys/class/net/'
if os.path.exists(srcpath):
interfaces = os.listdir(srcpath)
for inter in interfaces:
if inter == 'lo':
contin... | 4736b631bab4c9a58c7999397bfd47fac3c65f9a | 687,870 |
import re
def fixSlashes(url):
"""
Removes double slashes in URLs, and ensures the protocol is doubleslahed
"""
# insert missing protocol slashes
p = re.compile( '(:/)([^/])' )
url = p.subn( r'\1/\2', url)[0]
# strip any double slashes excluding ://
p = re.compile( '([^:])//' )
... | 8213ff86e85d49a829f4eff8627a97c33e984a9e | 687,871 |
def check_quota(cm_response, **data):
"""
Method returns state of user's quota.
@clmview_admin_cm
@cm_request_transparent{user.get_quota()}
"""
return cm_response | ac1169408a7db09c734d0c331dcab96f1fd75df8 | 687,872 |
import secrets
import binascii
def generate_consul_key(unique=False):
"""
Generate a consul key.
https://www.consul.io/docs/security/encryption
Key generated per the following description:
https://github.com/hashicorp/consul/blob/b3292d13fb8bbc8b14b2a1e2bbae29c6e105b8f4/command/keygen/keygen.go
... | 645a5a37fe7a9ceb46b60fd209ded7f0a9c8222a | 687,873 |
import time
def get_ymd():
"""
:return: 获取年月日
"""
y = time.strftime('%Y')
m = time.strftime('%m')
d = time.strftime('%d')
return y, m, d | cdb97053e71ac83e0ae5693f2cf071315b0dec78 | 687,874 |
def find_index(token, low, high, features): # binary search to find element index in list
"""
# Binary search helper method
# helps finding token index
# with O(log n) time whereas
# np.where() will need O(n)
"""
if high >= low:
mid = int((high + low) / 2)
if features[mid] ... | 181443fa1a95419c28e357b646ecf98e00cdeeaf | 687,875 |
def _calc_target_shape(target_range):
"""Returns the shape of the target image."""
return tuple((target_range[:, 1] - target_range[:, 0]).astype(int)) | b62c079653cd3ed4fd16eee09179b72d2ce6e2a8 | 687,876 |
from typing import Union
from typing import Dict
from typing import Any
from typing import List
def merge_dicts(
dict1: Union[Dict[Any, Any], List[Any]],
dict2: Union[Dict[Any, Any], List[Any]],
deep_merge: bool = True,
) -> Union[Dict[Any, Any], List[Any]]:
"""Merge dict2 into dict1."""
if deep_m... | 3b0307e03e9d27cd75463fede6bb3226adaa43af | 687,877 |
def _convert(x):
"""Generically convert strings to numbers.
:param x: string that maybe represents a number
:returns: value
:rtype: string, float, or int
"""
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return... | 14ac5fdee202adabc8aac927bac9a36ca0b3d806 | 687,878 |
def fast_continuum_subtract(y_data_cut, fast_continuum_cut, hb_half_idx, ha_half_idx):
"""Uses the FAST continuum as the basis for subtraction, then returns the continuum subtacted data in just the ha and hb regions
Parameters:
y_data (array): flux/spectrum data, cut to only the h_alpha and h_beta regions
... | b618e0b33647c848cc51737845c001643f25fd5b | 687,879 |
def is_imported_from_same_module(the_class: str, imported_name: str) -> bool:
"""
Is the class imported from another module?
:param the_class: the class object itself
:param imported_name: name of the imported class
:return: true if the class was imported from another module
"""
return ".".... | 713ddc8b012c70c6261c91f5224b83788c951455 | 687,880 |
def checkPrefix(s, prefix):
"""
Return a pair (hasPrefix, rest).
If prefix is a prefix of s:
hasPrefix is True
rest is everything after the prefix
Else:
hasPrefix is False
rest is s
"""
if s.startswith(prefix):
return (True, s[len(prefix):])
else:
... | f3f552ae3f4b0c5b8cc6a58259fd61a8b8147092 | 687,882 |
import io
import wave
def buffer_to_wav(buffer: bytes) -> bytes:
"""Wraps a buffer of raw audio data (16-bit, 16Khz mono) in a WAV"""
with io.BytesIO() as wav_buffer:
wav_file: wave.Wave_write = wave.open(wav_buffer, mode="wb")
with wav_file:
wav_file.setframerate(16000)
... | 1112c080c11696cbb5f54b9fe49fcf7b8c45e966 | 687,883 |
import torch
def discriminator_loss(logits_r,logits_m,logits_f,logits_f_prime):
"""
Computes the discriminator loss described in the homework pdf
using the bce_loss function.
Inputs:
- logits_r: PyTorch Variable of shape (N,) giving scores for the real data.
- logits_f: PyTorch Variable o... | 5d2a5ea19d1818f2043310fa20be9efdc27e98fe | 687,884 |
import toml
def parse_toml_file(file_object):
"""Parses toml data using a file-like object to a dictionary.
Args:
file_object: (file-like object) file like object instantiated from a toml formatted file
Returns:
A dictionary with parsed toml data fields.
"""
return toml.load(file... | 5fe70fec0d35ef5cfc124c0d8ea3c185b84a8e54 | 687,887 |
import os
def Which(binary, path=None, mode=os.X_OK):
"""Return the absolute path to the specified binary.
Args:
binary: The binary to look for.
path: Search path. Defaults to os.environ['PATH'].
mode: File mode to check on the binary.
Returns:
The full path to |binary| if found (with the righ... | 6880a08e33c1239e30cb9e8cdc6b6dfa17f3876b | 687,888 |
import time
def get_unixtime():
"""Get current unixtime."""
return (int)(time.time()) | 2efc98c0935385761eb348cfe144134b6df34942 | 687,889 |
def escape_delimit(s):
"""
escapes bytes 0x7e, 0x7d, 0x11 (XON), 0x13 (XOFF)
0x7e and 0x7d will be escaped to 0x7d 0x5e and 0x7d 0x5d
0x11 and 0x13 will be escaped to 0x7d 0x31 and 0x7d 0x33
0x7e - packet start/end
0x7d - escape character. escapes the following byte by inverting bit 5.
exa... | 4828e77a2dc14f32d3a2865fb37564a1b7147132 | 687,890 |
def csv_file(tmp_path):
"""Generate a csv file for test purposes
Args:
tmp_path: temporary area to use to write files
Returns:
path to the csv file
"""
tmp_path.mkdir(exist_ok=True)
csv_file_path = tmp_path / "file.csv"
csv_file_path.write_text("x,y\n0,0\n1,1\n")
return csv... | 2b2df6bb396d7bf0e18d9d427f0c81ed30a050e8 | 687,891 |
from typing import Tuple
def calculate_center_coords(
cell_index: Tuple[int, int], cell_size: Tuple[int, int]
) -> Tuple[int, int]:
"""Calculate cell center coordinates.
:param cell_index: selected cell index
:param cell_size: given cell size (height, width)
:return: given cell center coordinates... | c510f55695770a7e3effcb82dd2e59c9a1cd36bc | 687,892 |
from typing import Any
def drop_privates(item: list[Any]) -> list[Any]:
"""Drops items in 'item' with names beginning with an underscore.
Args:
item (list[Any]): attributes, methods, and properties of a class.
Returns:
list[Any]: attributes, methods, and properties that do not start with... | 52c40843c3bf81651f04d8ad9baf5d813287533a | 687,893 |
def select_elite(user_prod_graph, threshold=10):
"""
Select a fixed set of elite accounts
"""
elite_accounts = []
for user in user_prod_graph.keys():
if len(user_prod_graph[user]) >= threshold:
elite_accounts.append(user)
return elite_accounts | f8d9fdc758c23dbde208bd65d89f636f5553e87f | 687,894 |
def grid(numel):
"""Helper function to compute triton grids for pointwise ops"""
def grid_fn(meta):
bs = meta["BLOCK_SIZE"]
# inlined triton.cdiv
return ((numel + bs - 1) // bs,)
return grid_fn | 9e768566c052438ece4bd98e3b9e2fb3958a9f35 | 687,895 |
def cleanup_comment(comment):
"""Given a dictionary of a comment record, return a new dictionary for
output as JSON."""
comm_data = comment
comm_data["id"] = str(comm_data["_id"])
comm_data["user"] = str(comm_data["user"])
comm_data["post"] = str(comm_data["post"])
comm_data["created"] = s... | 54354dfe276911e00b84518310f188378708caab | 687,897 |
import argparse
def get_argument():
"""Parse argument"""
parser = argparse.ArgumentParser(
description='Extract graph structure from multiple alignment result\
and output as GFA/JSON')
parser.add_argument('-f', '--fasta',
help='An input fasta file')
... | 955d67c72e8130a8bd7a2aaecdea4f9f4ed2b5f0 | 687,898 |
import numpy
def sliding_window(data, size, stepsize=1, padded=False, axis=-1, copy=True):
"""
Calculate a sliding window over a signal
Parameters
----------
data : numpy array
The array to be slided over.
size : int
The sliding window size
stepsize : int
The slidi... | 24f2988df7104ea0fbdf25e9469cb96e174ce815 | 687,899 |
def tag2String(tag):
"""Takes a tag placement, and turns it into a verbose string"""
return ("Tag with ID #%d, was placed @ (%f,%f), facing %f deg" %
(tag['id'], tag['x'], tag['y'], tag['th_deg'])) | 5eac5e77228e81efe9968475c85b9d79ab5a2960 | 687,900 |
import xxhash
def get_volname_hash(volname):
"""XXHash based on Volume name"""
return xxhash.xxh64_hexdigest(volname) | cb76279fd84cb26c0e38403472aa99532a26d7ab | 687,901 |
import ast
import collections
def get_simple_vars_from_src(src):
"""Get simple (string/number/boolean and None) assigned values from source.
:param src: Source code
:type src: str
:returns: OrderedDict with keys, values = variable names, values
:rtype: typing.Dict[
str,
... | a2fd5d3aa5ded9592d909cb8015787172069e14c | 687,902 |
def get_level_size(slide, level):
"""Returns the dimensions of a level
"""
return slide.level_dimensions[level] | cb3279b82331152edc8d477ca842f035881621fe | 687,903 |
def mean(x):
"""mean"""
return sum(x) / len(x) | b62187bb8c5a25943d8b94840cae4dbb54bbc6bc | 687,904 |
import torch
def regularization_loss(params, weight):
"""Compute regularization loss.
Args:
params: iterable of all parameters
weight: weight for the regularization term
Returns:
the regularization loss
"""
l2_reg = 0
for param in params:
l2_reg += torch.norm(param)
return weight * l2_... | bee4f75d3782e9c3ba059d0de0cfb6819abd493d | 687,906 |
def comp_binary_same(term, number):
"""
:param term:
:param number:
:return:
"""
for i in range(len(term)):
if term[i] != '-':
if term[i] != number[i]:
return False
return True | 597250abba9bcc302cee5faaaf118645137036ab | 687,907 |
def get_file_dep_dict(mod_dep_dict, mod_path_dict):
"""Transform ModuleName in 'mod_dep_dict' with ModuleFileName
with given given 'mod_path_dict'.
Args:
mod_dep_dict (dictionary): output of 'get_moddep_dict' function
mod_path_dict (dictionary): output of 'get_modpath_dict' function
... | 3072b7050df04022365f60a82f899689dc1c693f | 687,908 |
def format_network_speed(raw_bps=0):
""" Formats a network speed test to human readable format """
fmt = ['b/s', 'Kb/s', 'Mb/s', 'Gb/s']
index = 0
speed = raw_bps
while speed > 1024:
index += 1
speed /= 1024
return "%0.2f %s" % (speed, fmt[index]) | 9d716c135feb862ac1be6d522987302716fec9b1 | 687,909 |
from typing import List
import os
from pathlib import Path
from typing import Counter
def get_files_with_most_frequent_extension(path) -> List[str]:
"""Method that looks into the given path and return the list of files with
the most frequent file extension.
Parameters
----------
path : str
R... | acca420c5980b762b4254ea64830a767872be0a1 | 687,910 |
from typing import Union
from pathlib import Path
def make_path_relative(path_str: Union[str, Path], root: Path) -> Path:
"""
Try to make the given path relative, given the default root.
"""
path = Path(path_str)
try:
path = path.relative_to(root)
except ValueError:
pass
re... | 6c1f048d23999640f2b499f5c778b2dc061c532d | 687,911 |
def derivative_from_polycoefficients(coeff, loc):
"""
Return derivative of a polynomial of the form
f(x) = coeff[0] + coeff[1]*x + coeff[2]*x**2 + ...
at x = loc
"""
derivative = 0.
for n, c in enumerate(coeff):
if n == 0:
continue
derivative += n*c*loc**(n-... | 29991fa0bccb29af85376759ce8c212606c027b2 | 687,912 |
def classify(inputTree, featLabels, testVec):
"""
输入:决策树,分类标签,测试数据
输出:决策结果
描述:跑决策树
"""
firstStr = list(inputTree.keys())[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)
classLabel = '0'
for key in secondDict.keys():
if testVec[featIndex] == key:... | f5e1fef06ebd02ed0582576d2b797b19ef4e080b | 687,913 |
def run(result):
"""Function to test True return"""
return True | ac4499ed80ddc285df83b98bb59933c6412eef4d | 687,916 |
def lookup(obj):
"""returns list object"""
return dir(obj) | 3c48385de3c4276f99c0830634d428f823a3faa5 | 687,917 |
def get_deutsch(trial_text):
"""
"""
if trial_text == None:
return None
if ('ü' in trial_text) | \
('Ü' in trial_text) | \
('ö' in trial_text) | \
('Ö' in trial_text) | \
('ä' in trial_text) | \
('Ä' in trial_text):
return True
elif (' der ' in trial_text) | \
(' ... | bb46252e593657158b249ab7abe8d95d52439fc7 | 687,918 |
from typing import Dict
import json
def _tgToJson(tgAsDict: Dict) -> str:
"""Returns a json representation of a textgrid"""
return json.dumps(tgAsDict, ensure_ascii=False) | d5cb083c5eab6bad7d264ad76e9c39acab2072ea | 687,919 |
def get_safe_name(progname, max_chars = 7):
"""Get a safe program name"""
# Remove special characters
for c in r'-[]/\;,><&*:%=+@!#^()|?^':
progname = progname.replace(c,'')
# Set a program name by default:
if len(progname) <= 0:
progname = 'Program'
# Force the program to start ... | 264c19964fee2d2840e1263e36d186f15453efa3 | 687,920 |
def get_filesystem(module, system):
"""Return Filesystem or None"""
try:
return system.filesystems.get(name=module.params['filesystem'])
except:
return None | 5b17722958010c9a9adfc630f5ecb43a25034ae6 | 687,921 |
def get_probe_hit(tree, gene_info, r, is_gtf=False):
"""
Given a dict tree (from read_probe_bed) and a GMAP SAM record
Go through each exon and find probes that hit it
Return: (number of probes hit), (total number of bases overlapping with probes), (genes seen)
"""
probes_seen = set()
genes... | ea01fdc835851f3960848d5aa2071c1f57c5e970 | 687,922 |
def firstof(*args, default=None):
"""
Returns the first value which is neither empty nor None.
"""
if len(args) == 1:
iterable = args[0]
else:
iterable = args
for value in iterable:
if value:
return value
return default | a3ff74bff3a445b6d8a83320c87ce5cd0681f87f | 687,923 |
import functools
def _validate_satellite(func):
"""A decorator that checks to see if the satellite is in the dataset."""
@functools.wraps(func)
def wrapper(self, satellite, *args, **kwargs):
# First argument has to be satellite
if satellite not in self.ds['satellite']:
raise In... | 747b81a917489a33a3b4e0f6709853618133cfb0 | 687,924 |
def count_lines(filename):
"""Count the number of lines in a source file
Return a pair (n0, n1), where n0 is the total
number of lines, while n1 is the number of non-empty
lines
"""
with open(filename) as f:
lines = f.readlines()
n0 = len(lines)
n1 = 0
for line... | e88e712755006f57f2850886cbc3c1c7ee4407ec | 687,925 |
def __write_rnx3_header_rectype__(rec="unknown", typ="unknown", version="unkown"):
"""
"""
TAIL = "REC # / TYPE / VERS"
res = "{0:20s}{1:20s}{2:20s}{3}\n".format(rec, typ, version, TAIL)
return res | 29c850b35c4734be9cdff0fe0a8b869c7a2afb23 | 687,926 |
import sys
def detokenize_none(caption):
"""
Dummy function: Keeps the caption as it is.
:param caption: String to de-tokenize.
:return: Same caption.
"""
if isinstance(caption, str) and sys.version_info < (3, 0):
caption = caption.decode('utf-8')
return caption | 20056be981fe56846cd1bb50412ad9fb4172bf64 | 687,927 |
def openvpn(args):
"""Manage OpenVPN.
We assume that you are using easy-rsa because that seems to be
what OpenVPN recommends.
"""
return args.operation(args) | b27ff716cf485efc97ce41cf55ddb82d4b30a7c7 | 687,928 |
def make_perm64_table():
"""Make table for conversion from bit vector to suboctad
Let o be an octad. Let {{i},{j}}, 0 <= i, j < 8, i != j be the
even cocode word which is a subset of octad o, such that
precisely the i-th and the j-th bit of octad o is set, as
in module mm_aux.c. Then entr... | 2692a766e7f29166a7353ffb9dc35d55f21128f6 | 687,929 |
def et():
"""Observation ephemeris time."""
return 277399264.66979694 | 3ab9060c6d748e11ec253c594c5f46a2c7922400 | 687,930 |
def dfs_iterative(graph, root):
"""
Iterative version of the DFS algorithm
Args:
graph: dict representation of the graph
root: start point
Returns:
list: in order of visiting vertices
Examples:
"""
node_queue = []
visited = set()
visiting_sequence = []
... | 6290871d1fa4b65e67d484bd7d0bcd86bf9e7a0c | 687,931 |
def make_quick_reply(replay_items):
"""
Create quick reply message.
reference
- `Common Message Property <https://developers.worksmobile.com/jp/document/100500807?lang=en>`_
:param replay_items: Array of return object of make_quick_reply_item function.
:return: quick reply content.
... | ef0c37bf6541e6e64468108717b506b71410c867 | 687,933 |
def concat(str_1: str, str_2: str) -> str:
"""將兩個字串串接在一起
Args:
str_1 (str): 字串 1
str_2 (str): 字串 2
Raises:
TypeError: 當任一參數不為 str 時,拋出 TypeError
Returns:
str: str_1+str_2
"""
if not (isinstance(str_1, str) and isinstance(str_2, str)):
raise TypeError("錯... | 619422096196279145df02def20a1a93fc24791f | 687,934 |
def right_rotate(n: int, b: int) -> int:
"""
Right rotate the input by b.
:param n: The input.
:param b: The rotation factor.
:return: The input after applying rotation.
"""
return ((n >> b) | ((n & 0xffffffff) << (32 - b))) & 0xffffffff | ce12e3af449390f7fbc2a3755264512d416750c9 | 687,935 |
def unstack_batch(tensor, B):
"""Reverses stack_batch."""
N = tensor.shape[0] // B
return tensor.reshape(B, N, *tensor.shape[1:]) | 5e99ad03a85a54fc4b925efacc1e6cfa9d50920e | 687,936 |
def extrapolate_lines(lines, bottom_frame, center_frame):
"""
'lines' is a vector of the form: [x1,y1,x2,y2] which contains
the two points to create a line. Shape of the vector = [:,0,4]
'bottom frame' is the location of the bottom of the image
'center_frame' is th... | e3c16ac499cccaddaefeb2d82211cc3ebd69c5ce | 687,937 |
import datetime as dt
def check_date(indate):
"""Check representations of date and try to force into a datetime.date
The following formats are supported:
1. a date object
2. a datetime object
3. a string of the format YYYYMMDD
4. a string of the format YYYYDDD
... | e17c6637638cf626385ec6c3ddb359f4c22dbf95 | 687,939 |
def path_assemble_hier(path, sep="/", reverse=False, start_index=0):
"""Append the previous"""
if isinstance(path, str):
list_data = path.split(sep)
elif isinstance(path, list):
list_data = []
else:
raise Exception(f"This function only accepts string or lists, got: {path}")
... | 10300e643034a180d74eb42cf59332e7f0c5a099 | 687,940 |
def truncate(data, step):
"""Truncate the data ``data`` as if it had been applied a moving average
with the step ``step``.
:param data: The data to truncate.
:param step: The step of the virtual moving average.
:type data: list
:type step: int
"""
return data[step:-step] | fdfcbc15333576131687e9efdc6992dd11832f27 | 687,941 |
def tokenize_char(sent):
"""
Return the character tokens of a sentence including punctuation.
"""
return list(sent.lower()) | f8dc50f92239bab90633cd4643f5b73c707c1519 | 687,942 |
import getpass
def get_user_name() -> str:
""" Gets the username of the device
Returns
-------
username : str
Username of the device
"""
return getpass.getuser() | ea8388520078afa90b89e10501f9a49fc29852a8 | 687,943 |
from typing import Type
import logging
def asserttype(inputtype: Type, targettype: Type | None, loc: str | None, errormessage: str | None = None) -> Type:
"""
Ensure inputtype == targettype, or when targettype == None, infer the type from inputtype
"""
if targettype == None:
return inputtype
... | 564b9ab4d01f71abc50fe5c4115d7b4ec22ae0c1 | 687,944 |
def quantile(values, p):
"""
Returns the pth-percentile value
>>> quantile([2, 4, 6, 8], 0.25)
4
>>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.5)
6
>>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.55)
7
>>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.75)
9
"""
... | 7b19b24aa668fbcfc2743ca17def719ffea1751a | 687,945 |
def trim_columns(data_frame):
"""
:param data_frame:
:return: trimmed data frame
"""
trim = lambda x: x.strip() if type(x) is str else x
return data_frame.applymap(trim) | da1aabe08716866562d419e9ab55ed46934ebe1c | 687,946 |
import torch
def segmentation_to_binary_mask(segmentation):
"""
replicates boundaries to frame-wise labels
example:
segmentation - [0, 3, 5]
returns - [1, 0, 0, 1, 0, 1]
:param segmentation:
:param phonemes:
"""
mask = torch.zeros(segmentation[-1] + 1).long()
for bound... | 7dc0f7192ca08796d1408df167f11c6b329e135a | 687,947 |
def InStr(*args):
"""Return the location of one string in another"""
if len(args) == 2:
text, subtext = args
return text.find(subtext)+1
else:
start, text, subtext = args
pos = text[start-1:].find(subtext)
if pos == -1:
return 0
else:
r... | d27efe4d0741f754e093d7621ceba172929edc98 | 687,949 |
def create_url(controller_ip, endpoint):
"""Create endpoint url to POST/PUT/GET/DELTE against."""
return 'https://%s:1080/%s' % (controller_ip, endpoint) | 8cb5be8fb102dd2160a58fe7e3f192387374371e | 687,950 |
def parse_psipred_file(psipred_output):
"""
This function parses the psipred output file and returns the
secondary structure predicted.
"""
opened_file = open(psipred_output).readlines()
seq = ""
for line in opened_file:
line = line.strip().split(" ")
seq += line[2]
... | ceef189d62c73f82bb8cb1e589cf217234050d53 | 687,951 |
import argparse
def parse_args():
"""Parse command line arguments.
Return:
args : parsed argument object.
"""
parser = argparse.ArgumentParser(
description='Binding site prediction and enrichment.')
parser.add_argument('--utr_file', type=str, help='Path to tab-separated file with U... | 28faeaa7371f1f5fccec9988ab2587140040ac70 | 687,952 |
def custom(x,w,lambdafunc=None):
"""Custom model (for example, for real data fitting).
Parameters
----------
x : numpy array (N,), dtype=float
Grid points in which the model will be evaluated. N is the number of grid points.
w : numpy array (N,), dtype=float
Weights used to eval... | b0e6dd6ea0d705b92e7b85bf7558aac18c751024 | 687,954 |
def pep8_filter(line):
"""
Standard filter for pep8.
"""
if 'argweaver/bottle.py' in line:
return False
return True | 46368c7ad7385e6eb04c5fc6b40094b2fb0d64e6 | 687,955 |
def command_theme(self, args=None):
"""/theme <theme name>"""
if args is None:
return self.command_help('theme')
self.command_set('theme %s' % (args[0],)) | 16dd9b4826fb6e493a261dbb316c34b7319b0863 | 687,956 |
import base64
import os
def img_to_base64(image_bytes):
"""
:param image_bytes: 文件路径
:return: base64字符串
"""
with open(image_bytes, "rb") as fb:
img = fb.read()
base64_bytes = base64.b64encode(img)
img_suffix = os.path.splitext(image_bytes)[1].replace('.', '')
if im... | 03a92a2757686485fd72e5c866ca1ef313b22119 | 687,957 |
import re
def sanitize(s):
"""
Removes characters that are not allowed in macro names. Anything
that's not alphanumeric is replaced with underscore.
"""
return re.sub(r"\W", '_', s) | 64cdc59d00c7e63b046b68e0944ddb2c7f442d7a | 687,958 |
def crop_to(image_to_crop, reference_image):
"""
Crops image to the size of a reference image. This function assumes that the relevant image is located in the center
and you want to crop away equal sizes on both the left and right as well on both the top and bottom.
:param image_to_crop
:param refer... | 1c12242e1c4fcf9043b75162efdc09aa0fbb75c1 | 687,959 |
def _isbn_has_valid_checksum(identifier):
"""Determine whether the given ISBN has a valid checksum."""
if len(identifier) == 10:
identifier = '978' + identifier
numerals = [int(char) for char in identifier]
checksum = 0
for i, numeral in enumerate(numerals):
weight = 1 if i % 2 == 0... | 9c92104d192ed86a2a139d0cf25cbb5263f64bae | 687,960 |
def _find_physio(subject, session, bids_path):
"""Get physilogy data from BIDS dataset."""
physio_path = list(
bids_path.glob(f"**/sub-{subject}_ses-{session}*_physio.tsv.gz")
)
if physio_path and len(physio_path) == 1:
return physio_path[0]
else:
raise ValueError("No associa... | a5938d6994f8898bdd204ac974f7e7d3374e3ebe | 687,961 |
import hashlib
def md5_encrypt(origin_str):
"""
md5加密
:param origin_str:
:return:
"""
_m1 = hashlib.md5()
# 此处必须声明encode,若写法为hl.update(str) 报错为: Unicode-objects must be encoded before hashing
_m1.update(origin_str.encode(encoding='utf-8'))
_rtn = _m1.hexdigest()
return _rtn | ca386fe86d7de1f84359a4a6750d469906d4693e | 687,962 |
def _is_linux_os(rctx):
"""Returns true if the host operating system is Linux"""
return rctx.os.name.lower().startswith("linux") | b7de6b4cc1e133b9a65cd43441b1571497c9d548 | 687,963 |
def decode_ascii(bytes_obj: bytes) -> str:
"""
>>> decode_ascii(b'hello!')
'hello!'
"""
return bytes_obj.decode("ascii", "ignore") | cc744eab854d447e2204d4ef08b3987b5985665a | 687,964 |
import os
def isDroppableMimeType(mime_data):
"""
Returns True if the given mime_data belongs to a file which can
be dropped onto the ImageViewer/Canvas, i.e. it must be either a file
or a URI of a local file (as we won't support downloading files for now).
"""
if mime_data.hasUrls():
... | a218b0ce48eb0112839e61d0fe50e9d0fb89aa10 | 687,965 |
import collections
def parse_file(path):
"""
Parse a spikes file: fail hard! If parsing does not work,
print offending line and exit(1)
returns dict keyed on gid.
each value is a list of (spiketimes, the line number, line )
"""
fp = open(path, "r")
parsed_data = collections.defau... | 0c9197a3c520be21721b8aa251ea61457bd2f9fc | 687,966 |
def _get_full_customization_args(customization_args, ca_specs):
"""Populates the given customization_args dict with default values
if any of the expected customization_args are missing.
"""
for ca_spec in ca_specs:
if ca_spec.name not in customization_args:
customization_args[ca_spec... | 48c37f7ab3a48970cb9ed65c279c2e00c5245e58 | 687,968 |
def min_prob(x, y):
""" the minimum probability of those fields, that should have
been > .5 """
return min(x[y > 0]) | 4c1076fcde80bc2d5055bfadd13b867ae7622cb4 | 687,970 |
def can_stop_recursive_cache(runway, speed, pos=0):
"""
Solution: xxx
Complexity:
Time: O(?)
Space: O(?)
"""
# If I'm on the runway, and I'm not on a spike, and (my speed is zero or I can can stop on a subsequent move)
return 0 <= pos < len(runway) and runway[pos] and (
speed == 0 or any(can_stop_recursive... | c5cce76bd5b1c7f6d835e8bed567b0312bdded6a | 687,971 |
import math
def eq141d10(l, sx, a, sum_st, iy, fy, e):
"""Compression in extreme fibers of box type flexural members
AREMA 2018 Section 1.4.1 Table 15-1-11 Row 10
Compression in the extreme fibers of box type welded or bolted flexural
members symmetrical about the principal axis midway betwe... | c112d32aa31b43b5342122d705cbff26999e841a | 687,972 |
def alphanumeric(password: str) -> bool:
"""
The string has the following conditions to be alphanumeric:
1. At least one character ("" is not valid)
2. Allowed characters are uppercase /
lowercase latin letters and digits from 0 to 9
3. No whitespaces / underscore
:param password:
:re... | ab07e6d65359e439d84b322ea055764077d2c3b3 | 687,973 |
def validate_user_input_to_int(user_input):
"""
validates user input against type integer & automatically converts and returns the value
: user_input --> value entered by user
"""
try:
return int(user_input)
except Exception:
return "error" | 37c513fc4f7068012d5fad08574e027500a68e2f | 687,974 |
def nested_get(dct, keys):
""" Gets keys recursively from dict, e.g. nested_get({test: inner: 42}, ["test", "inner"])
would return the nested `42`. """
for key in keys:
if isinstance(dct, list):
dct = dct[int(key)]
else:
dct = dct[key]
return dct | a8054e5080691a9d0d8ac3f71582b71ea82c29d9 | 687,975 |
def retinotopy_analysis():
"""Return a command for retinotopy analysis."""
return "from topo.command.pylabplot import measure_position_pref,measure_cog ;\
measure_position_pref(); \
measure_cog()" | c6d6ecd0e627effa5883331beb5f809c8b2f6a5a | 687,977 |
def merge_list(list_d, param=5):
"""
merge similar x in an array
"""
new_list = []
compare_list = []
tag = []
prev = -100
begin = True
if list_d == []:
return []
elif len(list_d) == 1:
return list_d
else:
pass
for i in list_d:
... | 467a898aeba285c1c42140667b31c2295ada60dd | 687,979 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.