content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def remove_whitespace(s): """Remove excess whitespace including newlines from string """ words = s.split() # Split on whitespace return ' '.join(words)
7d9e7b15ba101f00412565b42c260e8bc29ac49a
3,631,700
def get_first_group (match): """ Retrieves the first group from the match object. """ return match.group(1)
d4103989a7fbd55e40600d391b51dfb93053ed8f
3,631,701
from typing import Dict from typing import Tuple from typing import Any def plot_from_region_frames( frames: Dict[str, pd.DataFrame], variable: str, binning: Tuple[int, float, float], region_label: str, logy: bool = False, legend_kw : Dict[str, Any] = None, ) -> Tuple[plt.Figure, plt.Axes, plt...
3a0fe727d7160a0ed203bd0431e8ca8329259f27
3,631,702
from unittest.mock import patch async def init_integration(hass, co2_sensor=True) -> MockConfigEntry: """Set up the Nettigo Air Monitor integration in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, title="10.10.2.3", unique_id="aa:bb:cc:dd:ee:ff", data={"host": "10....
5e56cfd160499cc9c6164f231fe21cdcd2e41596
3,631,703
def decode(ciphered_text: str) -> str: """ Decode Atbash cipher :param ciphered_text: Atbash cipher :return: decoded text """ return ''.join(replace_char(char) for char in ciphered_text if char in LOWERCASE or char in DIGITS)
ff70504009ab45a0de476e7d8fcb139785f3590a
3,631,704
def text(label, default=None): """ @brief prompt and read a single line of input from a user @retval string input from user """ display = label if( default ): display += " (default: " + str(default) + ")" input = raw_input( display + ": " ) if input == '' and default: i...
0676596272a13607beae0b4f4ca289be61601834
3,631,705
def update_reservation(reservation, updatedSpots, comments): """ Update the reservation with the new spots needed """ newSpots = updatedSpots - reservation.seats_needed reservation.seats_needed = updatedSpots reservation.note=comments db.session.commit() flash("Reservation updated.") ...
eea612b228c7d3b66690b735cde76d26df964b3a
3,631,706
def qc_freq(species, geom, natom, atom, mult, charge, index=-1, high_level = 0): """ Creates a frequency input and runs it. index: >=0 for sampling, each job will get numbered with index """ if index == -1: job = str(species.chemid) + '_fr' else: job = str(species.c...
26f9bd91f2c688ab687363011661dd816ac250ff
3,631,707
from datetime import datetime def sample_to_timed_points(model, size): """As :func:`sample` but return in :class:`open_cp.data.TimedPoints`. """ t = [datetime.datetime(2017,1,1)] * size pts = sample(model, size) assert pts.shape == (size, 2) return open_cp.data.TimedPoints.from_coords(t, *pts....
11775060c76efdf6cfe31cd7efe3a09d562c888a
3,631,708
def _per_image_standardization(image): """ :param image: image numpy array :return: """ num_compare = 1 for dim in image.shape: num_compare = np.multiply(num_compare, dim) _standardization = (image - np.mean(image)) / max(np.std(image), 1 / num_compare) return _standardization
18461f97a91c1cad2156606b67c7a5f732587b1f
3,631,709
import torch def unflatten_parameters(params, example, device): """Unflatten parameters. :args params: parameters as a single 1D np array :args example: generator of parameters (as returned by module.parameters()), used to reshape params :args device: where to store unflattened parameters ...
f321c536bcbfada2e2cd254ecffaf5b0b9573472
3,631,710
def pattern_to_regex(pattern): """ Convert the CODEOWNERS path pattern into a regular expression string. """ orig_pattern = pattern # for printing errors later # Replicates the logic from normalize_pattern function in Gitlab ee/lib/gitlab/code_owners/file.rb: if not pattern.startswith('/'): ...
8b82ad2efa9e47028a7419dcef72fb9c6b3741ba
3,631,711
def register_extensions(app): """Register Flask extensions.""" assets.init_app(app) bcrypt.init_app(app) cache.init_app(app) db.init_app(app) login_manager.init_app(app) debug_toolbar.init_app(app) migrate.init_app(app, db) flask_mail.init_app(app) celery.conf.update(app.config) ...
f27986ddbd77814d111321726c4d88f9efacdbf4
3,631,712
def unit2uniform(x, vmin, vmax): """ mapping from uniform distribution on parameter space to uniform distribution on unit hypercube """ return vmin + (vmax - vmin) * x
2765db219dfda5debd5f8957c0ad9c0b44335f89
3,631,713
def adaptive_minmax(data, x_data=None, poly_order=None, method='modpoly', weights=None, constrained_fraction=0.01, constrained_weight=1e5, estimation_poly_order=2, method_kwargs=None, **kwargs): """ Fits polynomials of different orders and uses the maximum values as the b...
b93d2025eee27159c722479283a92b83b116aff6
3,631,714
def extractHachidoriTranslations(item): """ Parser for 'Hachidori Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Charging Magic with a Smile' in item['tags']: return buildReleaseMessageWithT...
f596e40b65fa1c92b74bcf8e83ea4b32ccad5124
3,631,715
import os import tempfile import ctypes def create_build_tools_zip(lib): """ Create the update package file. :param lib: lib object :return: """ opera_script_file_name_dict = OPTIONS_MANAGER.opera_script_file_name_dict tmp_dict = {} for each in SCRIPT_KEY_LIST: tmp_dict[each] =...
4e7438cf7a7be9d46a46a4549343c789ea2fe022
3,631,716
def _tvgp_qvgp_optim_setup(): """Creates a VGP model and a matched tVGP model""" time_points, observations, kernel, noise_variance = _setup() input_data = ( tf.constant(time_points), tf.constant((observations > 0.5).astype(float)), ) likelihood = Bernoulli() tvgp = t_VGP( ...
95578fceaa5206d6318c6045a521681d268a1e7d
3,631,717
def get_average_rate(**options): """ gets average imdb rate of all movies. :rtype: float """ return movies_stat_services.get_average_rate()
c32af301d3e2f789a68e5b179d78324b7205cbaa
3,631,718
def _uint_to_le(val, length): """Returns a byte array that represents an unsigned integer in little-endian format. Args: val: Unsigned integer to convert. length: Number of bytes. Returns: A byte array of ``length`` bytes that represents ``val`` in little-endian format. """ retur...
54e765e7b3772c6e2e6dc4c7e6de48d034b9d4b5
3,631,719
def extract_preposition(arg_number, postags, morph, lemmas, syntax_dep_tree): """ Returns preposition for a word in the sentence """ #TODO: fix duplication #TODO: there was a list of words for complex preposition, as we use the whole preposition as a feature children = get_children(arg_number, syn...
52818f0bec42081f8c2c0e4b0e66ad9e84719a4e
3,631,720
import torch def batch_to_patches(x, patch_size, patches_per_image): """ :param x: torch tensor with images in batch (batsize, numchannels, height, width) :param patch_size: size of patch :param patches_per_image: :return: """ device = x.device assert(x.dim()...
200ea8d893d660e981608ddd1276679b3765ee01
3,631,721
import json def parse_json(json_data, category): """ Parses the <json_data> from intermediate value. Args: json_data (str): A string of data to process in JSON format. category (str): The category ('all' / 'spam' / 'ham') to extract data from. Returns: (status_code, data), wh...
bc56ddf35d3551f43b2bd5644a6337d288d6af52
3,631,722
def get_dset_size(shape_json, typesize): """ Return the size of the dataspace. For any unlimited dimensions, assume a value of 1. (so the return size will be the absolute minimum) """ if shape_json is None or shape_json["class"] == 'H5S_NULL': return None if shape_json["class"] ...
82e0cf9041a81ed6f9d2195502ca7f21f557164d
3,631,723
from typing import List def check_shapes( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.shapes``. """ table = "shapes" problems = [] # Preliminary checks if feed.shapes is None: return problems ...
2c22c674f19f2e711fc337cd9c734e300e94b2ad
3,631,724
def get_help_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "OPM Status Help" speech_output = "To begin, ask o. p. m. status an acceptable question. For example, " \ "Is the gov...
8c1fea3cbb575dee9a80dd8b8e0351b90f837b4c
3,631,725
import random def mm_clustering(sampler, state, float_names, fixed_df, total_df_names, fit_scale, runprops, obsdf,geo_obj_pos, best_llhoods, backend, pool, mm_likelihood, ndim, moveset, const = 50, lag = 10, max_prune_frac = 0.9): """ Determines if walkers in the ensemble are lost and removes them. Replacing them ...
724159d78948b57ca1fbc06974b6728b24144ffe
3,631,726
def off_diagonal_min(A): """Returns the minimum of the off diagonal elements Args: A (jax.numpy.ndarray): A real 2D matrix Returns: (float): The smallest off-diagonal element in A """ off_diagonal_entries = off_diagonal_elements(A) return jnp.min(off_diagonal_entries)
0b05e7d2b091538cd4ca95624faaa347cae5401f
3,631,727
def cli_cosmosdb_sql_stored_procedure_create_update(client, resource_group_name, account_name, database_name, co...
4dbeccf559f32cb10762081706d98602a9f8f646
3,631,728
def create(box=None,n=None,nr=None,nc=None,sr=1,sc=1,cr=None,cc=None,const=None) : """ Creates a new HDU """ if box is not None: nr=box.nrow() nc=box.ncol() sc=box.xmin sr=box.ymin else : if nr is None and nc is None : try : nr=n ...
298802654b7f5a5572f4d59c0c3ab30a2c2af6e7
3,631,729
def gcd(num1, num2): """Return Greatest Common Divisor""" # Euclidean Algorithm for GCD a = max([num1, num2]) b = min([num1, num2]) while b != 0: mod = a % b a = b b = mod return a
36c788d44a4aafaaf000963a7c5e1b80fa6f64f5
3,631,730
from typing import List from typing import Dict from typing import Any def read_params_from_config(config: dict, _root_name: str = "") -> List[NamedPyParam]: """Reads params from the nested python dictionary. Args: config: a python dictionary with params definitions _root_name: used internall...
bfdd3de4977bcd2ad09ec52fbdccdd77ed685d09
3,631,731
def dataParser (path): """ This function parses all files in the directory specified by the path input variable. It is assumed that all said files are valid .wav files. """ waves = [] rates = [] digits = [] speakers = [] files = [f for f in listdir (path) if isfile (join (path, f...
921d7381f3daff233fb5e568b414c97d726b8c5d
3,631,732
def deserialize_function(serial, function_type): """Deserializes the Keras-serialized function. (De)serializing Python functions from/to bytecode is unsafe. Therefore we also use the function's type as an anonymous function ('lambda') or named function in the Python environment ('function'). In the latter case...
eb76660c494bf43497dde32617583c17f6ba8ef3
3,631,733
from src.datasets import VOC2007 from src.datasets import VOC2012 import torch def _dataset( dataset_type: str, train_val_test: str = 'train' ) -> torch.utils.data.Dataset: """ Dataset: voc2007 voc2012 """ if dataset_type == "voc2007": if train_val_test == "val": t...
1c818013d04ec33e10df57b5f40c2c38351fd36b
3,631,734
def disaggregate_forecast(history, aggregated_history, aggregated_forecast, dt_units='D', period_agg=7, period_disagg=1, x_reg=None, x_fut...
e74f42335af23325d08f7ad9aa593b85b6917078
3,631,735
def get_path_cost(latency_dict, path): """ Cost of all links over a path combined :param latency_dict: :param path: :return: """ cost = 0 for i in range(len(path) - 1): cost += get_link_cost(latency_dict, path[i], path[i+1]) return cost
ed7be1c7a1a38fcc5ad0904a7a784e8bcf0f4941
3,631,736
import os import json def main(compilation_db_path, source_files, verbose, formatter, iwyu_args): """ Entry point. """ # Canonicalize compilation database path if os.path.isdir(compilation_db_path): compilation_db_path = os.path.join(compilation_db_path, ...
fc0ebba14bb6aede43c1491804426997c8074fc4
3,631,737
def qderiv(array): # TAKE THE ABSOLUTE DERIVATIVE OF A NUMARRY OBJECT """Take the absolute derivate of an image in memory.""" #Create 2 empty arrays in memory of the same dimensions as 'array' tmpArray = np.zeros(array.shape,dtype=np.float64) outArray = np.zeros(array.shape, dtype=np.float64) # Ge...
ebe0242b829409a9844c1d36ac151cbddcf12391
3,631,738
def byte(number): """Return the given bytes as a human friendly KB, MB, GB, or TB string""" B = float(number) KB = float(1024) # 1024 b, 1 千字节=1024 字节 MB = float(KB ** 2) # 1024 kb, 1 兆字节=1048576 字节 GB = float(KB ** 3) # 1024 mb, 1 千兆字节(GB)=1073741824 字节(B) TB = float(KB ** 4) # 1024 gb ...
88c062d97645741025731e2f2cde2646be2891f9
3,631,739
def compute_optimal_warping_path_subsequence_dtw(D, m=-1): """Given an accumulated cost matrix, compute the warping path for subsequence dynamic time warping with step sizes {(1, 0), (0, 1), (1, 1)} Notebook: C7/C7S2_SubsequenceDTW.ipynb Args: D (np.ndarray): Accumulated cost matrix m ...
ba1b86ef7bfd8c5d322b27d5a9c0f264a97351ef
3,631,740
from typing import Dict from typing import Any from typing import Union def _start_tracker(n_workers: int) -> Dict[str, Any]: """Start Rabit tracker """ env: Dict[str, Union[int, str]] = {'DMLC_NUM_WORKER': n_workers} host = get_host_ip('auto') rabit_context = RabitTracker(hostIP=host, n_workers=n_wor...
a8be8ca89fd6ba9383f9b029ac936579b1f164d5
3,631,741
def get_type_path(type, type_hierarchy): """Gets the type's path in the hierarchy (excluding the root type, like owl:Thing). The path for each type is computed only once then cached in type_hierarchy, to save computation. """ if 'path' not in type_hierarchy[type]: type_path = [] ...
29344b63197f4ea6650d059767100401c693990a
3,631,742
def get_required_webots_version(): """Return the Webots version compatible with this version of the package.""" return 'R2020b revision 1'
89e6e458c2409670d70a833996c76f05e77bd7b1
3,631,743
def ScoreStatistics(scores, percentile): """ Capture statistics related to the gencall score distribution Args: scores (list(float)): A list of gencall scores percentile (int): percentile to calculate gc_10 : 10th percentile of Gencall score distribution gc_50 : 50th...
35c3b98681a53cec82908e5634b1c49439b5b044
3,631,744
def download_drill(load=True): # pragma: no cover """Download scan of a power drill. Originally obtained from Laser Design. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returne...
c40635c718afd404f5df55004a32cb5108d8b370
3,631,745
def schlieren_colormap(color=[0, 0, 0]): """ Creates and returns a colormap suitable for schlieren plots. """ if color == 'k': color = [0, 0, 0] if color == 'r': color = [1, 0, 0] if color == 'b': color = [0, 0, 1] if color == 'g': color = [0, 0.5, 0] if c...
7becf570f5af8368d2f169fe9c222d72d22f04d7
3,631,746
def evaluate_binned_cut(values, bin_values, cut_table, op): """ Evaluate a binned cut as defined in cut_table on given events Parameters ---------- values: ``~numpy.ndarray`` or ``~astropy.units.Quantity`` The values on which the cut should be evaluated bin_values: ``~numpy.ndarray`` or...
541a1bf7196e41d2db2bdf4ab272a9cfa760591b
3,631,747
import tempfile def add_EVM(final_update, wd, consensus_mapped_gff3): """ """ db_evm = gffutils.create_db(final_update, ':memory:', merge_strategy='create_unique', keep_order=True) ids_evm = [gene.attributes["ID"][0] for gene in db_evm.features_of_type("mRNA")] db_gmap = gffutils.create_db(cons...
c36945fe984d82245247271210683d81880a757a
3,631,748
def smartCheck(policy_del, policy_add, list_rules_match_add=None, matched_rules_extended=None, subpolicy=False, print_add_matches=False, print_progress=False, DEBUG=False): """ smartCheck will compare two policies trying t...
9c66196422566af42188ed90156f63190acffeab
3,631,749
import logging def create_volume(cinder, size, name=None, image=None): """Create cinder volume. :param cinder: Authenticated cinderclient :type cinder: cinder.Client :param size: Size of the volume :type size: int :param name: display name for new volume :type name: Option[str, None] ...
a0001c7addc39e57928b5baffc9bc0446e4fca4d
3,631,750
def function_linenumber(function_index=1, function_name=None, width=5): """ :param width: :param function_index: int of how many frames back the program should look (2 will give the parent of the caller) :param function_name: str of what function to look for (should not be used with function_index ...
ba046f1106eacb998a6728a6878bb48822920270
3,631,751
from typing import Tuple def get_event_times( data: np.ndarray, kernel_size: int = 71, skip_first: int = 20 * 60, th: float = 0.1, abs_val: bool = False, shift: int = 0, debug: bool = False, ) -> Tuple[list, list]: """ Given a 1D time serires it gets all the times there's a new...
1c44a940995d23a2561b19463f29d7f9e89c6056
3,631,752
def init_base_item(mocker): """Initialize a dummy BaseItem for testing.""" mocker.patch.multiple( houdini_package_runner.items.base.BaseItem, __abstractmethods__=set(), __init__=lambda x, y: None, ) def _create(): return houdini_package_runner.items.base.BaseItem(None) ...
d7d4c0951e4013583f8ea89574da9735daa9aa21
3,631,753
def create_sftp_client2(host, port, username, password, keyfilepath, keyfiletype): """ create_sftp_client(host, port, username, password, keyfilepath, keyfiletype) -> SFTPClient Creates a SFTP client connected to the supplied host on the supplied port authenticating as the user with supplied username ...
c489850945ffc9387781f23f6d58b3c675de8928
3,631,754
def get_vectorize_layer(max_features=10000, sequence_length=250) \ -> tf.keras.layers.experimental.preprocessing.TextVectorization: """Transforms a batch of strings into either a list of token indices or a dense representation. Parameters ---------- max_features : int The maximum size o...
bfd677757a8347f521c53445a2f4bddd2fd57d06
3,631,755
def test_login_success(self): """ In this case both are false, meaning the if statements doesn't get executed """ return login_user(test_user.email, test_user.password) == test_user
53c1599b9a2c442e0be093e90522d08a905f0503
3,631,756
async def tally(): """ Get the results of all election tallies. Returns: Tally results for each contest in the election """ tally = election.get_election_tally() results = { "contests": [ { "contest": contest, "selections": [ ...
144de5592804fd5e6f950385b2789ba1a7c3e195
3,631,757
def expand_parameters_from_remanence_array(magnet_parameters, params, prefix): """ Return a new parameters dict with the magnet parameters in the form '<prefix>_<magnet>_<segment>', with the values from 'magnet_parameters' and other parameters from 'params'. The length of the array 'magnet_paramete...
e087f5b1e8ea264f074f921a5283d7806178664b
3,631,758
import math def addToOrStartNewRange(oldRange, tissueRangeScores, newPosition, vals, tissues, tissueFhs): """For all the tissues in vals, figure out if we are still in the same exon and adding to the previous range/score combo, or if we are in the same exon but with a different score, or a...
addbe75f611995c05dd6aa1998f0d66b1f038798
3,631,759
def transformNode(doc, newTag, node=None, **attrDict): """Transform a DOM node into new node and copy selected attributes. Creates a new DOM node with tag name 'newTag' for document 'doc' and copies selected attributes from an existing 'node' as provided in 'attrDict'. The source 'node' can be None. At...
2329858a02c643077f67d5c705fb3df72c2a96ee
3,631,760
def jsonify(status=200, indent=2, sort_keys=True, **kwargs): """ Creates a jsonified response. Necessary because the default flask.jsonify doesn't correctly handle sets, dates, or iterators Args: status (int): The status code (default: 200). indent (int): Number of spaces to indent (default...
d32eb4418d49802872bbf96fafa29a4704374b1b
3,631,761
from pathlib import Path from typing import Optional from typing import List import tempfile import os import tarfile import requests from typing import Dict def detect_symbols( sources_dir: Path, host: str = "http://127.0.0.1", port: int = 8001, try_expand_macros: Optional[bool] = None, require_b...
b8d0bd9c97db3a496417e8d1c6f4186a5ed9a2fd
3,631,762
import datasets def browse(dataset_id=None, endpoint_id=None, endpoint_path=None): """ - Get list of files for the selected dataset or endpoint ID/path - Return a list of files to a browse view The target template (browse.jinja2) expects an `endpoint_uri` (if available for the endpoint), `target`...
ca88068558e9e32e52ac032c891f28579a9d03b0
3,631,763
def tag_group(tag_group, tag): """Select a tag group and a tag.""" payload = {"group": tag_group, "tag": tag} return payload
f22ccd817145282729876b0234c8309c24450140
3,631,764
from typing import Iterable def rollup(step: Step, store: TableStore): """Rollup a table to produce an aggregation summary. :param step: Parameters to execute the operation. See :py:class:`~data_wrangling_components.engine.verbs.rollup.RollupArgs`. :type step: Step :param store: ...
ee8302a4605fd5ad850b3c1d466276259a12736e
3,631,765
from optimade.server.config import CONFIG def prefix_provider(string: str) -> str: """Prefix string with `_{provider}_`""" if string in CONFIG.provider_fields.get("structures", []): return f"_{CONFIG.provider.prefix}_{string}" return string
6faa8af6d24e4f5ae17a7997b097545415ce53b8
3,631,766
def combine_sequences(vsequences, jsequences): """ Do a pairwise combination of the v and j sequences to get putative germline sequences for the species. """ combined_sequences = {} for v in vsequences: vspecies, vallele = v for j in jsequences: _, jallele= j ...
dac2aea73bd078bcf96dc8e7b44c5dcdeade2759
3,631,767
def read_seq_file(filename): """Reads data from sequence alignment test file. Args: filename (str): The file containing the edge list. Returns: str: The first sequence of characters. str: The second sequence of characters. int: The cost per gap in a sequence. ...
9160bb0b2643deae669818cea1bc1ebeb51506b8
3,631,768
import scipy import numpy def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1): """ Orthogonal Initialization """ sizeX = int(sizeX) sizeY = int(sizeY) assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY' if sparsity < 0: sparsity = sizeY else: sparsit...
98b53e11d6c3a641d6e8fede0d28651c48aa5407
3,631,769
def build_complement(dna): """ :param dna: str, the DNA strand that user gives(all letters are upper case) :return: str, the complement of dna """ new_dna = '' for base in dna: if base == 'A': new_dna += 'T' elif base == 'T': new_dna += 'A' elif ba...
dffdf6345ec25ea80e89996aef7c85a41f38d6f4
3,631,770
def _seasonal_prediction_with_confidence(arima_res, start, end, exog, alpha, **kwargs): """Compute the prediction for a SARIMAX and get a conf interval Unfortunately, SARIMAX does not really provide a nice way to get the confidence intervals out of the box, so we ha...
9520bf1a60eeb39c25e9a369b0b337905df9afb8
3,631,771
def attack(X_train, y_train, X_test, y_test, unmon_label, args, VERBOSE=1): """ Perform WF training and testing """ classes = len(set(list(y_train))) print(classes) # shuffle and split for val s = np.arange(X_test.shape[0]) np.random.shuffle(s) sp = X_test.shape[0]//2 X_va = X_t...
57c33e5e26f04412650bf65a5032cb81fb7d46bf
3,631,772
from typing import Counter def create_lexicon(pos, neg): """Create Lexicon.""" lexicon = [] for fi in [pos, neg]: with open(fi, 'r') as f: contents = f.readlines() for l in contents[:hm_lines]: all_words = word_tokenize(l.lower()) lexicon += ...
f1f81310d0e12e6aa23589c98e0fcb1eb3283dc1
3,631,773
def trailing_zeros(x): """ Number of trailing zeros in a number.""" if x % 1 != 0 | x == 0: return 0 magn = floor(log10(x)) trailing = 0 for i in range(1, magn + 1): if x % (10 ** i) == 0: trailing = i else: break return trailing
d712afc601866eafc8ea1d6fac8e33c50e053b64
3,631,774
import xml from typing import List from typing import Optional import sys def _check_dependency(dependency: xml.etree.ElementTree.Element, include: List[str], exclude: Optional[List[str]] = None) -> bool: """Check a dependency for a component. Verifies that the giv...
f6cfeda5f6f9ad7fd03695e58f3c27d3f299de4d
3,631,775
def top_height(sz): """Returns the height of the top part of size `sz' AS-Waksman network.""" return sz // 2
1e4a43a8935cc5c3ccf104e93f87919205baf4a4
3,631,776
def insert_sequence_read_set(db: DatabaseSession, sample_id: int, urls: list): """ Insert sequencing read set directly into warehouse.sequence_read_set, with the *sample_id* and *urls*. """ LOG.debug(f"Inserting sequence read set for sample {sample_id}") data = { "sample_id": sample_id,...
71201e49266ea8604b2fd1d09d1e2af271cefb5c
3,631,777
def constructAuxGraph(path): """ This function constructs the auxiliary graph given a python dictionary as argument wich consists of the # of the path as the key of the dictionary and the path (source, intermediate nodes, destination) that a predifined route has to traverse in order to go from the sou...
04441f20a9d55e6dcf88c64f9c54efa320dc8ee1
3,631,778
from typing import Callable import logging import time def eval_time(function: Callable): """decorator to log the duration of the decorated method""" def timed(*args, **kwargs): log = logging.getLogger(__name__) time_start = time.time() result = function(*args, **kwargs) time_...
3f40394c5638bf0fc6371d4247c8980da1f6363f
3,631,779
from typing import Union from typing import Optional from typing import Iterable from typing import Tuple def parse_data( data: Union[AnnData, DataFrame, np.ndarray], gene_names: Optional[Iterable[str]] = None, sample_names: Optional[Iterable[str]] = None ) -> Tuple[np.ndarray, list, list]: """Reduces...
03fdf88e3160d41f976d6ebdb336588958a16a91
3,631,780
def german_actionset_unaligned(german_X): """Generate an actionset for German data.""" # setup actionset action_set = ActionSet(X = german_X) immutable_attributes = ['Age', 'Single', 'JobClassIsSkilled', 'ForeignWorker', 'OwnsHouse', 'RentsHouse'] action_set[immutable_attributes].mutable = False ...
5166d4d07d127cc6fa0166a719edca0c78a34150
3,631,781
def recursively_contains(val1, val2, parent_key=None): """ Returns True if val1 is a subset of val2 both in its items as well as the items's items if it's a list or a dictionary. Returns False if there are items within val1 but not in val2. """ # If not same data type, fail if type(val1) != ...
7003eeb39fa5267a4399c574bac4c157c48b4e62
3,631,782
import email import os import mimetypes def generate_email(sender, recipient, subject, body, attachment_path): """Creates an email with an attachement.""" # Basic Email formatting message = email.message.EmailMessage() message["From"] = sender message["To"] = recipient message["Subject"] = subject message.set_...
fb4c15dad4fe643e8b3748413469d98d593cfa7d
3,631,783
def test_mode(user, godmode=False, questions_list=None, quiz_id=None): """creates a trial question paper for the moderators""" if questions_list is not None: trial_course = Course.objects.create_trial_course(user) trial_quiz = Quiz.objects.create_trial_quiz(trial_course, user) trial_que...
600a4391ffd016387f2210db62a3fe9e452cf55a
3,631,784
from typing import Optional def add_auth_token(auth_token: str, desc: Optional[str], call_count_limit: Optional[int] = None, call_count_limit_relative: bool = False) -> bool: """ Add or update an auth token to the DB. Local cache will be updated during next API request in...
243ea14badc4dd3f54f2f5147c38f81bf64be83f
3,631,785
import re def id_for_new_id_style(old_id, is_metabolite=False): """ Get the new style id""" new_id = old_id def _join_parts(the_id, the_compartment): if the_compartment: the_id = the_id + '_' + the_compartment return the_id def _remove_d_underscore(s): """Removed ...
34c21ddfe20eb3e173c176763f6323d5cd4f3d3b
3,631,786
def analysis_instance_start_success(instance_uuid, instance_name, records, action=False, guest_hb=False): """ Analyze records and determine if instance is started """ always = True possible_records \ = [(action, NFV_VIM.INSTANCE_NFVI_ACTION_START), ...
effb9e52a48067160b6a468af6a35cc4a380070c
3,631,787
import scipy from typing import OrderedDict def evaluate_on_semeval_2012_2(w): """ Simple method to score embedding using SimpleAnalogySolver Parameters ---------- w : Embedding or dict Embedding or dict instance. Returns ------- result: pandas.DataFrame Results with spea...
5b6e6cee3a62af1aa5320ae7a549357194a2a334
3,631,788
from magichome import MagicHomeApi def setup(hass, config): """Set up MagicHome Component.""" magichome = MagicHomeApi() username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] company = config[DOMAIN][CONF_COMPANY] platform = config[DOMAIN][CONF_PLATFORM] hass....
bd2202684f875fa6f2619420de7a4ce95c78c332
3,631,789
def valid_lsi(addr): """Is the string a valid Local Scope Identifier? >>> valid_lsi('1.0.0.1') True >>> valid_lsi('127.0.0.1') False >>> valid_lsi('1.0.1') False >>> valid_lsi('1.0.0.365') False >>> valid_lsi('1.foobar') False """ parts = addr.split('.') if not ...
8a90547f239ea6d2a5aa971115c2015edc42932b
3,631,790
def imshow_coocc(coocc, percent=True, ax=None): """visualize profile class co-occurrence matrix""" ax = ax or plt.gca() size = coocc.shape[0] annot = (coocc*100).round().astype(int).values if percent else coocc.values ax.imshow(coocc.T) for x in range(size): for y in range(size): ...
45f259dd2702714793be2dddccc1fdc8d77de55e
3,631,791
def sub_m(D, C_lasso, C_group, C_ridge, eta=1e0): """Solve the Sub_m subproblem.""" return shrink(D, C_lasso * eta, C_group * eta, C_ridge * eta)
7ed14e2f455e1af3645fdc4557ee5b7b4668a7b0
3,631,792
def grade(morse_code, inputs): """Grades how well the `inputs` represents the expected `morse_code`. Returns a tuple with three elements. The first is a Boolean telling if we consider the input good enough (this is the pass/fail evaluation). The next two elements are strings to be show, respectively, in...
43038fa81ff9a5d39d337b38b5afed1c3ca57e4d
3,631,793
def create_test_endpoint(client, ec2_client, name=None, tags=None): """Create an endpoint that can be used for testing purposes. Can't be used for unit tests that need to know/test the arguments. """ if not tags: tags = [] random_num = get_random_hex(10) subnet_ids = create_subnets(ec2_...
8c266beec2d49d5139e08b42aad0df9a9e8bd400
3,631,794
def plot_clusters(estimator, X, chart=None, fig=None, axes=None, n_rows=None, n_cols=None, sample_labels=None, cluster_colors=None, cluster_labels=None, center_colors=None, center_labels=None, center_width=3, col...
59fa26e28233815335e5377c4523e35c9b21e22e
3,631,795
import requests def head(url): """ Make a HEAD request to the URL. If we do not get a 404 then the URL is valid. If there are any exceptions then return False. """ try: resp = s.head(url, timeout=5, verify=False) except requests.exceptions.RequestException: return False ...
e602cc7ad498cacbe7defc955464b701c316d8db
3,631,796
import pathlib def long_description(): """Reads the README file""" with open(pathlib.Path(WORKING_DIRECTORY, "README.rst")) as stream: return stream.read()
1573b8c5dba81e1f7e345b77a49085d0066c4dca
3,631,797
import csv import io def load_embeddings(embeddings_path, aws=False): """Loads pre-trained word embeddings from tsv file. Args: embeddings_path - path to the embeddings file. Returns: embeddings - dict mapping words to vectors; dim - dimension of the vectors. """ if aws: embeddings = {} ...
c2879b05f9110f64aacbc8253e1d095e05c16ee7
3,631,798
from typing import Dict from typing import Any import json import requests async def create_check_request( installation_url: str, repo_name: str, token: str, check_name: str, head_sha: str ) -> Dict[str, Any]: """ Initiate Check after Pull Request was created. It contains terminal hash from PR, name, ...
5afa8efeb6a438520f75cbb0fa486c34102f94b5
3,631,799