content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reverse_complement(string): """Returns the reverse complement strand for a given DNA sequence""" return(string[::-1].translate(str.maketrans('ATGC','TACG')))
bd033b9be51a92fdf111b6c63ef6441c91b638a3
41,000
def normal2color(normal, mask, dtype=np.uint8): """Conversion from 3D (x, y, z) surface normals to a color image representing surface normals. Args: normal (ndarray): Surface normals. The shape is H x W x 3. mask (ndarray): Mask with shape of H x W. The value must be 0 or 1. dtype (type...
4ffbdd036d26c9f2beca8abe88697c83a82b888f
41,001
def sample( rng: chex.PRNGKey, mean: chex.Array, C: chex.Array, sigma: float, popsize: int, ) -> chex.Array: """Jittable Gaussian Sample Helper.""" S = C + sigma ** 2 * jnp.eye(C.shape[0]) candidates = jax.random.multivariate_normal( rng, mean, S, (popsize,) ) # ~ N(m, S) - ...
fa99e09c357203b94ce5351ccba4fa1201109dfe
41,002
import tokenize def build_model(): """ build a MultiOutputClassifier model using GridSearch Input: None Output: cv_model (GridSearchCV): ML model """ pipeline = Pipeline([ ('features', FeatureUnion([ ('text_pipeline', Pipeline([ ('vect'...
70c596cc9d0ea1cd1048a3ccb6e128979c38bb0d
41,003
import copy def stackImages(_imgList, cols, scale): """ Stack Images together to display in a single window :param _imgList: list of images to stack :param cols: the num of img in a row :param scale: bigger~1+ ans smaller~1- :return: Stacked Image """ imgList = copy.deepcopy(_imgList) ...
5829ff5f43dea414c31a86e6c07a50aaf1b59e26
41,004
def ellipsoid_fit(X): """fits an arbitrary ellipsoid to a set of points """ x = X[:, 0] y = X[:, 1] z = X[:, 2] D = np.array([ x * x + y * y - 2 * z * z, x * x + z * z - 2 * y * y, 2 * x * y, 2 * x * z, 2 * y * z, 2 * x, 2 * y, 2 * z, 1 - 0 * x ]) d2 = np.array(x * x + y ...
bb335ef8cbec0fd8bf98f53ee13cdc8c9ab64157
41,005
def same_genes(dictionary, sample_ids): """ update main AnnData object for list of samples so all contain the same list of genes Parameters ---------- dictionary : dict dictionary containing AnnData objects sample_ids : list list of sample IDs to compare against one ano...
00391be20cdbd58a2d367fc11693949ef450fe22
41,006
from typing import Dict from typing import Any def async_engine_from_config( configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any ) -> AsyncEngine: """Create a new AsyncEngine instance using a configuration dictionary. This function is analogous to the :func:`_sa.engine_from_config` ...
4f2044c9035ea9570d210bea51f8fbac6694690f
41,007
def mity_qual(AO, DP, p=0.002): """ Compute variant quality :param AO: (int) number of alternative reads :param DP: (int) total read depth :param p: (float) noise parameter. default=0.002 :return: (float) phred-scaled quality score >>> [mity_qual(x,10) for x in [1,2,3,4,5,6,7,8,9,10]] '...
a154aa770fb9a876b291129fe817fa1b5867368e
41,008
def get_prompt_from_code(code_str): """Split ``code_str`` to a <prompt, completion> based on indents. Args: code_str (str): code str. Returns: <before, after> """ splits = list( split_before( code_str.splitlines(), lambda x: x and x[0].isspace(), max...
916c081a08a267a9fc6deb60d13374bc9a1bb04d
41,009
def mix_chroma(mixmap,chroma_list,illum_count): """ Mix illuminant chroma according to mixture map coefficient mixmap : (w,h,c) - c is the number of valid illuminant chroma_list : (3 (RGB), 3 (Illum_idx)) contains R,G,B value or 0,0,0 illum_count : contains valid illuminant nu...
245fc1c46dca89e14e27bd9ad6515e4863e9dc4c
41,010
def create_worker_dmatrix(*args, **kwargs): """ Creates a DMatrix object local to a given worker. Simply forwards arguments onto the standard DMatrix constructor, if one of the arguments is a dask dataframe, unpack the data frame to get the local components. All dask dataframe arguments must use th...
096c99a7d3e975a4857abf8b5234280fd871d5e7
41,011
def compute_melspec(y, params): """ Computes a mel-spectrogram and puts it at decibel scale Arguments: y {np array} -- signal params {AudioParams} -- Parameters to use for the spectrogram. Expected to have the attributes sr, n_mels, f_min, f_max Returns: np array -- Mel-spectrogr...
068c5e9ae445010d297a99b2836e13cf7088b609
41,012
def _parse_seq(seq): """Get a primary sequence and its length (without gaps)""" return seq, len(seq.replace('-', ''))
f02c6f316e3bc56d3d77b6ca6363aa1e0a6b4780
41,013
import urllib import json def get_pkg_json(pkg): """ recieve json from pypi.org """ url = url_template.format(pkg_name=pkg) u = urllib.request.urlopen(url) resp = json.loads(u.read().decode('utf-8')) return resp
7093f2476d00a695620869ef05db8ffd233018d1
41,014
from typing import Tuple def train_step(vae_apply, vae_params, opt_state: OptState, opt_update: UpdateFn, batch: Batch, random_key: RandomKey) -> Tuple[Params, OptState, Array]: """A single step of training for the VAE.""" def params_loss(...
73bf3302cbf170a33c584f109ee2a1b262508c4b
41,015
def schedule_conv3d_winograd_weight_transform(attrs, outs, target): """Schedule conv3d_winograd_weight_transform""" with target: return topi.generic.schedule_conv3d_winograd_weight_transform(outs)
77145d10a1e781b12e4bbdb8d6175385df9269c7
41,016
def i_(indxs_old, indxs, k): """ Returns indexes of elements that were not enlarged in new enlarged array. :param indxs_old: Indexes (in original 1D array) of elements that won't be substituted in new enlarged 1D array. :param indxs: Indexes of elements in original 1D array that ...
27af69a35b506cfde1892182a8ff149aa32b896e
41,017
def gsl_coerce_float(*args, **kwargs): """gsl_coerce_float(float x) -> float""" return _gslwrap.gsl_coerce_float(*args, **kwargs)
d67aa847d19bc29931bd6622a6da849ef05336df
41,018
def get_one_user(id): """ USERS GET ONE """ cursor = mysql.connection.cursor() cursor.execute("SELECT * FROM users WHERE id = %s", (id)) data = cursor.fetchall() cursor.close() print(data) data_res = {"id": data[0][0], "name": data[0][1], "teamId": data[0][2]} message = {"mes...
1768d4f4eaca488b9d1ac9e6d0e13ba4b7859beb
41,019
def get_phi(row): """Helper function for rotating data. row: 2D-entry in matrix with shape (?, 2) """ return np.arctan2(row[0], row[1])
89a8ea48eca99083a087d951211f1e8a1e4bcb65
41,020
import os def _get_export_path(path, working_path): """Creates an export path and filename (with extension). Arguments: path (str): The input file path. working_path (str): Working path Returns: (str): Export file path. """ filename, extension = _basename(path) export...
803684985eb8da74f6a3559d92101eacf8d7a33c
41,021
def verifyProxy(ip, type): """ 验证代理的有效性 """ request_header = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36" } url = "http://www.baidu.com" # 填写代理地址 proxy = {type: ip} # 创建proxyHandler proxy_ha...
5462d8cba61ac181c2dcf7ca9ab8c334dbdd0e43
41,022
import os, subprocess as sp from ..output import OrcaOutput from ..xyz import OpanXYZ from ..grad import OrcaEngrad from ..hess import OrcaHess from ..utils import template_subst def execute_orca(inp_tp, work_dir, exec_cmd, subs=None, subs_delims=("<",">"), sim_name="orcarun", inp_ext=_DEF.FIL...
85bce981061d0d84407aa85f3dfb8a064c19b612
41,023
def str_aula(value): # Only one argument. """Converts a string into all lowercase""" if(value == True): return "Sim" else: return "Nao"
f90dc7ab8e76ab254b6306131d2c3921453889e9
41,024
def unions_buffered(contig, buffer, lower_bound='start', upper_bound='stop'): """ Calculate interval unions among loci of a contig and extend them with a non-overlapping buffer. The new cluster intervals will contain only fields of the upper and lower bounds of clusters which may be named with the ...
8319075508147904a5a85c5b96bdd2bea836e469
41,025
def coll_exc_xsec(eng, species=None): """ e-e collisional excitation cross section in cm\ :sup:`2`\ . See 0906.1197. Parameters ---------- eng : float or ndarray Abscissa of *kinetic* energies. species : {'HI', 'HeI', 'HeII'} Species of interest. Returns ------- f...
65c6fb83ccab3c43b64b69a977eff18575f7b54d
41,026
def mirror_tree(root: TreeNode): """ Offer 27 二叉树的镜像 :param root: :return: """ if not root: return [] nodes = [root] while nodes: node = nodes.pop(0) node.left, node.right = node.right, node.left if node.left: nodes.append(node.left) i...
07b1c0d32c212b3d886665847c2b164a2b967501
41,027
def reverse_digit(x): """ Reverses the digits of an integer. Parameters ---------- x : int Digit to be reversed. Returns ------- rev_x : int `x` with it's digits reversed. """ # Initialisations if x < 0: neg = True else: neg ...
d7358f5778897262b8d57c6dd3e2eb4acb05a2d1
41,028
def yyyymmdd(d, separator=''): """ :param d: datetime instance separator: string :return: string: yyyymmdd """ month = d.month if month < 10: month = '0' + str(month) else: month = str(month) day = d.day if day < 10: day = '0' + str(day) else: ...
a5b765ea9b740ac26b03fd16def62c7d84389e8e
41,029
def recurrent_layers( value, layer_sizes, bidirectional=True, dropout=0.0, rnn_type="lstm", return_sequences=False): """ Make one or more RNN layers """ if rnn_type == "lstm": rnn_class = LSTM elif rnn_type == "gru": rnn_class = GRU ...
3eb0adf75e3dd9089c4ba1cb4f3049ce430c0c60
41,030
import os import yaml from typing import Dict def load(environment="common"): """Load configuration parameters for an environment, or the common configuration shared by all environments. """ basedir = os.path.abspath( os.path.dirname(os.path.dirname(os.path.dirname(__file__))) ) settin...
9c0cd832fdb34b6b57950d2c49c70415113f0b45
41,031
def _applicable_weight_based_methods(weight, qs): """Return weight based shipping methods that are applicable for the total weight.""" qs = qs.weight_based() min_weight_matched = Q(minimum_order_weight__lte=weight) | Q( minimum_order_weight__isnull=True ) max_weight_matched = Q(maximum_order...
3fbe44950e6738995f865b3cba97967344219b22
41,032
import json import time def index_phenomenon(es, index_l, type_l, phenomenon = None, threshold=0): """ Indexes a phenomenon of a file. Returns the id that the phenomenon will have in the database. """ if phenomenon is None: return pid = None pid = abs(hash(str(phenomenon))) ph...
321a82c247ecc7c98aab0904b71aebbcdf3471d7
41,033
def _run_hive_query(cursor, query, has_results=False): """ Executes a given hive query on a specified database :param cursor: cursor to run queries on :param query: the specified hive query to run :return: results """ _print_debug('Executing query: {}'.format(query)) cursor.execute(query...
f65bbb52a6d44947a64ae846c2c86279961ab6e0
41,034
def _imwread(imgName): """ Reads a *.imw file. imgName should come with no extension. """ w, h = _readDim(imgName + '.dim') return _readImage(imgName + '.imw', w, h, '>H', 2)
05b5b11e935262f10e8be30d25eb8b6ec7639290
41,035
import requests def train(**kwargs): """ Train network https://docs.deep-hybrid-datacloud.eu/projects/deepaas/en/latest/user/v2-api.html#deepaas.model.v2.base.BaseModel.train :param kwargs: :return: """ message = { "status": "ok", "training": [], } # ...
d01e0b5ee5dc623ae11180ede6bff9dec7c95ef8
41,036
import ray def sync_ensemble(workers: WorkerSet) -> None: """Syncs dynamics ensemble weights from driver (main) to workers. Args: workers (WorkerSet): Set of workers, including driver (main). """ def get_ensemble_weights(worker): policy_map = worker.policy_map policies = poli...
bac6b306ff890f1b002389806a112ad7000cd75f
41,037
def last_days_quotations(request): """Return last days quotations of a currency. Keyword arguments: request -- parameters [ days, currency ] """ args = request.GET days = int(args.get('days', None)) currency = args.get('currency', None) quotations = Quotation() quotations_list = qu...
e57e8e10ec1c70a82b37798e58b53c910fec42b7
41,038
from operator import add def cksum(buf): """Return computed CRC-32c checksum.""" return done(add(0xffffffff, buf))
f3c9d110d6f364e669e5d15c718a3497c470df74
41,039
import torch def yuv420_to_rgb(image_y: Tensor, image_uv: Tensor) -> Tensor: """Convert an YUV420 image to RGB. Image data is assumed to be in the range of [0.0, 1.0] for luma and [-0.5, 0.5] for chroma. Input need to be padded to be evenly divisible by 2 horizontal and vertical. This function assumed...
c3d53d721ae905eac9cdf1021b2096d22dfc19d8
41,040
import csv def read_sensor_types_file(csv_file: str) -> []: """ Read in a csv file :param csv_file: path to file :type: csv_file: str :return: sensor_types :rtype: dict """ sensor_types = {} with open(csv_file, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) ...
8d3897de83de18a5d1188d3564af55747ace1277
41,041
def ping(value=0): """Return given value + 1, must be an integer.""" return {'value': value + 1}
487902e19decd04f2d1b7a75da6a9ca6bb2714d7
41,042
import math import random def Lf(lo, hi): """Log-uniform distributed floatint point number.""" return math.exp(random.uniform(math.log(lo), math.log(hi)))
3eb756c65f20ca60f62ef87187476452f30168c7
41,043
def test_default_args(): """ Verify that default arguments are properly passed to the isolated function call. """ def isolated_function(arg1='default1', arg2='default2', arg3='default3'): return arg1, arg2, arg3 # Sanity check assert isolated_function.__defaults__ == ('default1', 'defau...
208293af69b957ce7cefc9b11e159ccf9dfc520f
41,044
def partition_data(array, partition_size=500, seed=None): """Partition the into multiple groups with given size It will partition the data with same schema if seed is consistent for each partitioning Args: array (array) partition_size(int): size of each partition group, default=500 ...
2b1ee3eb37c6a8d393d4b5b0c99fe144f1075f9d
41,045
def add_character(story, name='"Merquivest Monogarymbalid"', role="stranger"): """ Adds a new character to the story with the given name and role. Returns the id Predicate for the added character. """ character = next_id_prs(story, "chr", 1)[0] story.add(character) story.add( intrinsic_pr(story, character...
d8a3aa13e29e85748df58829a28516fb3fb4ac6d
41,046
def resize_image_and_boxes(image, boxes, new_size): """ Resizes image and boxes. :param image: Image to resize. :param boxes: Boxes to resize. :param new_size: New size of the image. :return: Resized image and boxes. """ resized_image = image.resize(new_size) scale = np.zeros(2) sca...
d1bb68cb60a077f0ae2d9b0963657256e9285158
41,047
def _standard_frame_length(header): """Calculates the length of a standard ciphertext frame, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :rtype: int """ frame_length = 4 # Sequence Number frame_length += h...
2e455e536de649ed3e4c9faa7b31ab3abafe19a1
41,048
def f(x): """ Quadratic function. It's easy to see the minimum value of the function is 5 when is x=0. """ return x**2 + 5
7469225fd7d864c96ca957caa51bec924a81d599
41,049
import numbers def coerce_retention_period(value): """ Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expression that can be evaluated to a number. :returns: A number or the string 'always'. :raises: :exc:`~except...
a7a53f84b037a7d48898573a0268aab1eecb0790
41,050
def daily_log_return(close, fillna=False): """Daily Log Return (DLR) https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe Args: close(pandas.Series): dataset 'Close' column. fillna(bool): if True, fill nan values. Returns: pandas.Series: New fea...
1745ffd47133821ca99beeb907758682cc10ca37
41,051
import logging def find_links_fast(communities_grouped, max_parent_combinations, offsets, min_forward_containment=0, min_backward_containment=0, reverse_mappings=None): """find_links_fast Under development. """ n_largest_combos = 0 edge_list = [] for i, communities in en...
b0cff4f97b2a014fe2c8062e5a1de14e9fe4b1e8
41,052
def read(path): """Return dict-like object of config parameters from file path.""" return ConfigObj(path, unrepr=True)
e85b5d260bb9789acd8c2da118152b5e2bf3775e
41,053
from typing import Dict import ast def builds_file(file: str, do_clean: bool = False) -> Dict[str, PyssectGraph]: """Takes a python file and returns the corresponding PyssectGraph""" with open(file, 'r') as f: return ASTtoCFG().build(ast.parse(f.read()), do_clean)
67c05dd46370e5b73d980e32fec5665c236aca78
41,054
def dropLabels(events, minPct=.05): """ # apply weights, drop labels with insufficient examples """ while True: df0 = events['bin'].value_counts(normalize=True) if df0.min() > minPct or df0.shape[0] < 3: break print('dropped label: ', df0.argmin(), df0.min()) ...
cbfc6de91be685d6e5309a490c455badd7596093
41,055
def get_partitions(raw_data_id): """ 获取rt_id对应的kafka topic的partition数量 @:param rt_id: result_table表的id :return: kafka上rt_id对应的topic的分区数量 """ rawdata = model_manager.get_raw_data_by_id(raw_data_id) if rawdata: kafka_bs = _get_rawdata_kafka_bootstrap_server(rawdata) if kafka_bs...
b8fec4945a973340ef600fb4441623ad7a624894
41,056
def latest(history_secs=600, max_data_points=200): """ Retrieve latest data, with sampling to indicated number of data points NOTE: all speedtests are always returned """ return { 'ip_local': ip.local(), 'speedtest': DATA['speedtest'], ** { k: _sample_buffer(...
32de7247bdefa1b0528437e70f393cc8cdebca45
41,057
from typing import List from typing import Pattern from typing import Tuple import sys import os def expand_modules( files_or_modules: List[str], ignore_list: List[str], ignore_list_re: List[Pattern], ignore_list_paths_re: List[Pattern[str]], ) -> Tuple[List[ModuleDescriptionDict], List[ErrorDescripti...
39b90684dfaede1928230055554f5fc65c47e7f3
41,058
def calc_chi2_stats(df_popl, df_cust, attributes, alpha=0.05, exclude_na=True, use_perc=True): """ Calculates the chi-sq stays for the attribute to compare the similarities between population and customer ref: https://machinelearningmastery.com/chi-squared-test-for-machine-learning/ :params df_popl:...
80a335f1ca45d1529c4b0ebbb2719b8afcca2d07
41,059
def hammingDistance(str1, str2): """ Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`. Args --- `str1 : string` The first string `str2 : string` The second string Returns --- `differences : int` The differences between `str1` and `str2` ...
ad35cc79f89171c75a16a13ec6862a2a4abdbd61
41,060
def prepare_data(df, n_cell_x, n_cell_y): """ Feature engineering and computation of the grid. """ # Creating the grid size_x = 10. / n_cell_x size_y = 10. / n_cell_y eps = 0.00001 xs = np.where(df.x.values < eps, 0, df.x.values - eps) ys = np.where(df.y.values < eps, 0, df.y.values ...
f55fd655920daee8deaa8d85dceb6b8922542478
41,061
def powerstat_ucsc(sg, wanted_servers): """ Get the power status of the UCS Central servers. """ try: handle = UCSCUtil.ucsc_login(sg) except KubamError as e: return jsonify({"error": str(e)}), Const.HTTP_UNAUTHORIZED try: powerstat = UCSCServer.list_servers(handle) ...
4c6f78e2deaa722c0d84e1cc8d9b9178c32ff232
41,062
import logging def _from_pretrained(cls, *args, **kw): """Load a transformers model in TF2, with fallback to PyTorch weights.""" try: return cls.from_pretrained(*args, **kw) except OSError as e: logging.warning("Caught OSError loading model: %s", e) logging.warning( "Re-trying to convert fro...
4459aba28e7e30ca63cb328aba84487af6bbe8a7
41,063
def get_frame_durations(file): """ Return an array of each frame duration in the given file. Durations are in milliseconds. """ pos = file.tell() frame_durations = [] last_frame_timestamp = None def collect_timestamps(frame, timestamp): timestamp = round(timestamp*1000) ...
12f22fc489289e7d601699c0b469c8d79cecc86a
41,064
def pedirOpcion(): """Pide y devuelve un entero en el rango de opciones validas""" correcto = False num = 0 while not correcto: try: num = int(input("Elige una opcion -> ")) if num < 0 or num > 3: raise ValueError correcto = True excep...
a758254110e0d39fc8b1b4cab91b95799311fdcf
41,065
import os def option_comment(path_to_dot_setting, option_name, comment): """Returns 200: Successful, 201: Option name was not found in .setting.xml file, file could be corrupted""" file_r = open(path_to_dot_setting, 'r') file_temp = open(path_to_dot_setting + '.temp', 'w') file_r_contents = fi...
4adb4181bc2c964d439e6ac93ef96a523854c893
41,066
import tqdm import glob import json def extract_preprocessing_json(root: str): """ :param root: :return: """ vols_xymin, vols_ccords = dict(), dict() for path in tqdm(sorted(glob(root))): volume_name = "_".join(path[:-5].split("/")[-2:]) with open(path, 'rb') as file: ...
f5335ffd78ebc8f6f45bfac26cdb2510440ccb5d
41,067
def slugurl(context, slug): """Returns the URL for the page that has the given slug.""" page = Page.objects.filter(slug=slug).first() if page: return pageurl(context, page) else: return None
b0ddf5347e1aa8a5342d4563d431950e87473b57
41,068
from typing import OrderedDict def _order_dict(d): """Convert dict to sorted OrderedDict""" if isinstance(d, dict): d = [(k, v) for k, v in d.items()] d = sorted(d, key=lambda x: x[0]) return OrderedDict(d) elif isinstance(d, OrderedDict): return d else: raise E...
94b3e9e0c5b34e466c913c46683c752ca9560a12
41,069
def _sampling_probabilities(indices): """ Compute marginal sampling probabilities for each training point so that the classes will be balanced. """ N, k = indices.shape probs = np.zeros(N) for i in range(k): not_missing = indices[:,i] != -1 probs[not_missing] += 1./(np.s...
9568c0661443bfb7c3b46478042b9062750fa6f7
41,070
def plot_proj_error(traj_top, traj_left, X, Y, Z, cam_top, cam_left, time, savedir='data_treat/Reproj_error.png', plot=True): """Plot the reprojected trajectory for each camera to check for the trajectory errors :param traj_top,traj_left: screen trajectory for the top and left cameras :param X,Y,Z:...
4ae6e4f2a758878fe58cfbb4009d7610eee0c77a
41,071
def temp_monthly(): """Returns temperature obs from the database""" session = Session(bind=engine) year_ago = dt.date(my_date.year, my_date.month, my_date.day) - dt.timedelta(days=365) # In the function (logic should be the same from the starter_climate_analysis.ipynb notebook): # Calculate the date 1 y...
5b3c18b4ab9913856e4009362e88c4f4ec497936
41,072
def get_comment_app(): """ Get the comment app (i.e. "commentary") as defined in the settings """ # Make sure the app's in INSTALLED_APPS comments_app = _get_setting('APP', DEFAULT_COMMENTS_APP) if not apps.is_installed(comments_app): raise ImproperlyConfigured( 'The COMMENTS...
b023de39ed1eafc3b13f8ed2cca2ba1652776a83
41,073
def get_report_types(): """Get the types of reports that are available :rtype: list """ return [{"type": key, "name": val["name"]} for key, val in REPORTS.items()]
a0857b35bb79ac3cdcb7da1ca7e85fc646c64a06
41,074
def read_fasta(fasta_file): """ read a fasta file and retrieve its sequences """ sequences = AlignIO.read(fasta_file, "fasta") return sequences
605907eba45d32c9b734428e71726e4166bfa72e
41,075
def display_get_rule_name(): """display function to prompt for the name of the rule to add""" return input("Name of the rule to add: ")
e6df6b4df7aecb289d56d65c35de78eb1a8ab591
41,076
def _get_stack_status(stack_name, region): """ Returns the stack status which will be one of: 'CREATE_IN_PROGRESS' 'CREATE_FAILED' 'CREATE_COMPLETE' 'ROLLBACK_IN_PROGRESS' 'ROLLBACK_FAILED' 'ROLLBACK_COMPLETE' 'DELETE_IN_PROGRESS' 'DELETE_FAILED' ...
7256d34570eada00ce4838d84957d6a974aa1b62
41,077
import sys def in_virtualenv() -> bool: """Return True when pype is executed inside a virtual env.""" return ( hasattr(sys, 'real_prefix') or ( hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix ) )
3b7e7b8f21b2a988e0190219c8d26a503929d5af
41,078
def parse_varint(stream): """ Parses SQLite's "varint" (short for variable-length integer) as mentioned here: https://www.sqlite.org/fileformat2.html#varint """ usable_bytes = read_usable_bytes(stream) value = 0 for index, usable_byte in enumerate(usable_bytes): # For all bytes except ...
c2349149fca0d362a3e29beea26a2d34cbfa891b
41,079
from pathlib import Path def _latest_input() -> Path: """Since the exports are complete exports, can just use the most recent export""" return last(sorted(get_files(config.export_path), key=lambda p: p.stat().st_mtime))
1b714d549eec243971d6fb358670b7f9844b13b5
41,080
from typing import Callable def jacobian(func: Callable, delta: float): """Finite differences approximation to the Jacobian.""" def jacfn(z): num_dims = len(z) Jac = np.zeros((num_dims, num_dims)) for j in range(num_dims): pert = np.zeros(num_dims) pert[j] = 0.5...
1b29c5d7845197e577f017f9fb0407b5cae26338
41,081
def get_full_width(text, get_full_width_char, get_full_width_number, get_full_width_symbol): """ Get full width characters. :param text: original text. :param get_full_width_char: set True to get full width English letter. :param get_full_width_number: set True to get full width number. :param ...
9ea6b259d40a7d96dca1043d2009ee5d3fe69728
41,082
def polar_to_cartesian_2d(rho, phi): """Convert polar points to cartesian points. Convert polar coordinate points in 2D to cartesian coordinate points in 2D. This function uses the notation convention of ISO 80000-2:2009 and its related successors. Parameters ---------- rho : array_like ...
d749bc25010e7d426c42a05aa502f1bf92c35f6e
41,083
def ast_rotate_left_while_assoc_prec(ast): """Performs a left rotation of the AST around its root if associativity and precedence are not enforced yet. Args: ast: The AST dict. Returns: The new root of the rotated AST. """ if ("op" in ast) and (ast["op"] in all_op_data): if...
9f206ae1aa07c5fe7be8a7c657863395ef160a87
41,084
def convert_direction_from_string(s: str): """Convert direction (SkyCoord) from string TODO: Make more general! :param s: String :return: """ ra, dec, frame = s.split(',') d = SkyCoord(ra, dec, unit='deg', frame=frame.strip()) return d
f6cf79522351bb085abb818e01b409debc8472a7
41,085
def memoryUsage(data, detail=1): """Got memory usage of dataset Parameters ---------- data: dataFrame """ if detail: display(data.memory_usage()) memory = data.memory_usage().sum() / (1024 * 1024) print("Memory usage : {0:.2f}MB".format(memory)) return memory
3c3ed920dea91c07eaa8d227fb9a7ae96ef03b2c
41,086
def settings_finish(update: Update, context: CallbackContext) -> int: """ Settings finish""" devotional_type = update.message.text chat_id = update.effective_chat.id update.message.reply_text( text=YOUR_CHOICE.replace("$choice", devotional_type), parse_mode=ParseMode.HTML ) if ...
4c6700f8768fc0cd73ad8f4af525ee4698246f61
41,087
def dataframe_to_thrift_struct(df, name, roffset, coffset, rows, cols, format): """ :type df: pandas.core.frame.DataFrame :type name: str :type coffset: int :type roffset: int :type rows: int :type cols: int :type format: str """ dim = len(df.axes) num_rows = df.shape[0] ...
8a2bac4a51637810396a82210c6cef6fff0911ea
41,088
from pathlib import Path import copy def find_medoid(indir, pangenome_list): """ Finds the medoid of the groups of nucleotide sequences Picks a best representative sequence for each species and puts the results into self.cluster """ # If we do need to update this seqs_all = [] # ffn sequence ...
079631a4d4b09d4f61b5ce2e347c47c9db1a0910
41,089
import ast def collect_args(args: ast.arguments): """Collect function arguments.""" all_args = args.args + args.kwonlyargs all_args += [args.vararg, args.kwarg] return [arg for arg in all_args if arg is not None]
b8fdd180259aadd6a8d31a83503cf7da2b2c0bae
41,090
def getalllabels(): """Get a dictionary of label name -> SNES address.""" labeldatas = _getall(_asar.dll.asar_getalllabels) return {x.name.decode(): x.location for x in labeldatas}
ae053bc05be3bc689dffd2f5a636d9facf226bdf
41,091
def jinja2_enviroment(**options): """jinja2环境""" #创建环境 env = Environment(**options) #返回环境对象 env.globals.update({ "static":staticfiles_storage.url, #获取静态文件的前缀 "url":reverse, #反向解析 }) #自定义语法 : static. {{static{'静态文件相对路径') }} #return 对象 return env
5489deb7d7f98fccc7edf056e9f8bae60da49d2e
41,092
def pushmarker(repo, key, old, new): """Push markers over pushkey""" if not key.startswith('dump'): repo.ui.warn(_('unknown key: %r') % key) return 0 if old: repo.ui.warn(_('unexpected old value for %r') % key) return 0 data = base85.b85decode(new) lock = repo.lock() ...
9d43edfa3d98fc908f1e18555e3ae7189c0d6901
41,093
import logging def remove_images(): """Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used""" client = get_docker_client() removed = _remove_dangling_images() dusty_images = get_dusty_images() all_images = client.images(all=True) for image...
fac5fb5819de5bd793fcb1f72c912ffd9647701c
41,094
def get_types_and_functions(root): """Return a list of types and functions from a root element.""" types = root.findall('%stype' % namespace) functions = root.findall('%sfunction' % namespace) logger.debug(types) logger.debug(functions) if len(types) == 0 and len(functions) == 0: logge...
b6691df60145f8e27174f5584979e442b244ce96
41,095
def create_version_localization( version_id: str, locale: str, localization_attributes: VersionLocalizationAttributes, access_token: AccessToken, ): """Creates a new app store version localization.""" return fetch( method=FetchMethod.POST, path=f"/appStoreVersionLocalizations", ...
cbd64a70b15126dfa636d0cbf40d7aed73a5e91f
41,096
import shutil from pathlib import Path def clean_build(): """Remove build directory and recreate empty""" shutil.rmtree("site_build", ignore_errors=True) build_dir = Path("site_build") build_dir.mkdir(exist_ok=True) return build_dir
121e6ba5f06243654a3a38946a332efae43ce6c2
41,097
import click def print_markers(f): """A decorator that prints the invoked command before and after the command. """ @click.pass_context def new_func(ctx, *args, **kwargs): command = ctx.info_name assert command is not None command_name = ctx.command_path click_exten...
bee03bbdcfe7da134c21f9d4e5e9ea16a7b3b019
41,098
def gpsapi(): """(re)Generate and/or present API key.""" form = ApiForm(request.form) hasapi = ApiKey.query.filter_by(user_id=current_user.get_id()).all() # Handle regeneration of API key if request.method == "POST": if form.validate_on_submit(): apikey = strgen.StringGenerator("...
77a54a920f898b926900a519847abb4e70236f9e
41,099