content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def seepage_from_unitary(U): """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 """ sump = 0 for i in range(2): for j in range(2): bra_i = qtp.tensor(qtp.ket([i], dim=[2]), ...
8bd4185a69d7280868871dc3c62bb10abac1579c
5,300
def auto_get(*args): """ auto_get(type, lowEA, highEA) -> ea_t Retrieve an address from queues regarding their priority. Returns 'BADADDR' if no addresses not lower than 'lowEA' and less than 'highEA' are found in the queues. Otherwise *type will have queue type. @param type (C++: atype_t *) @para...
810ea49a414e3a044bc94cac4d780c7b624433a2
5,301
def isLineForUser(someLine=None, username=None): """determins if a raw output line is for a user""" doesMatch = False try: doesMatch = utils.isLineForMatch(someLine, username) except Exception as matchErr: logs.log(str(type(matchErr)), "Error") logs.log(str(matchErr), "Error") logs.log(str((matchErr.args)),...
dbf6b92976c8419fc3b9271eb87871c8c7cf6a1b
5,302
import importlib def get_view_class(callback): """ Try to get the class from given callback """ if hasattr(callback, 'view_class'): return callback.view_class if hasattr(callback, 'cls'): return callback.cls # TODO: Below code seems to not do anything.. mod = importlib.impo...
a705917f680bd35643f57377d430cdaef02228a9
5,303
def create_multipart_upload(s3_obj, bucketname, object_key): """ Initiates Multipart Upload Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket on which multipart upload to be initiated on object_key (str): Unique object Identifier Returns: str : M...
375d7d04aefa0ef4f91a42e2478ae624057e1bee
5,304
import sqlite3 def cn(DB): """Return the cursor and connection object.""" conn = sqlite3.connect(DB) c = conn.cursor() return (c,conn)
76abbec283d45732213f8b94031242146cdb4ee0
5,305
def _build_category_tree(slug, reference=None, items=None): """ Builds a recursive tree with category relations as children. """ if items is None: items = [] for key in reference: category = reference[key] if category["parent"] == slug: children = _build_catego...
d06cb736b12025b862363a724b2497a71a8a8a30
5,306
import copy def partially_matched_crossover(random, mom, dad, args): """Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations...
b0d5132cf4ca14095f3d7c637cb50db3fe37d244
5,307
import re def regex_trim(input, regex, replace=''): """ Trims or replaces the regex match in an input string. input (string): the input string to search for matches regex (string): regex to match replace (string - optional): a string to replace any matches with. Defaults to trimming the match. """ return re.s...
169bfaa0d2bfd7a1f32c1e05a63b41993f82bf4b
5,308
import os import glob def getENVIframeDir(strPathScene, sSubDir=None): """ Return directory containing envi frames frame bsqs in this dir are named FR_yyyy.mm.dd_X.bsq Optional subdirectory name sSubDir. workaround for non standard directory organization. """ strWild = strPathScene + r'SEQ...
4dacf64418f97d734f87ecfa5cd7632b7707b5e3
5,309
def LoadAllSuitesOfProject(project_name): """Loads all of the suites of a project.""" project_key = db.Key.from_path(bite_project.BiteProject.kind(), project_name) return BiteSuite.all().ancestor(project_key)
7a1a27229542ed364dddd2cc9a9cd3343c1d934d
5,310
def calc_temps(start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date string in the format %Y-%m-%d end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVG, and TMAX """ return session.query...
567bc943ecfe34c0604427e0fa8cea11f10c7205
5,311
import logging from typing import Callable from typing import Any from typing import Tuple def __check_rse_usage(rse: RseData, greedy: bool = False, logger: "Callable[..., Any]" = logging.log) -> 'Tuple[int, bool]': """ Internal method to check RSE usage and limits. :param rse_name: The RSE name. ...
a097443530ef5fa7c122426ef180a697cf89b5a7
5,312
def train_model(ad, rsrc_loc, algo='IR', log_dir=None): """ Train a CellO model based on the genes of an input dataset. Parameters ---------- ad : AnnData object Expression matrix of n cells by m genes algo : String The name of the algorithm used to train the model. 'IR' ...
46c7736a4f0127ec882d54075564fd447336a332
5,313
def ps_roi_max_align_2d( x, rois, roi_indices, outsize, spatial_scale, group_size, sampling_ratio=None ): """Position Sensitive Region of Interest (ROI) Max align function. This function computes position sensitive max value of input spatial patch with the given region of interests. Each RO...
394879a014d855dd71786cb0941a3aefd30b70b8
5,314
def received_date_date(soup): """ Find the received date in human readable form """ return utils.date_text(history_date(soup, date_type="received"))
5fbba6129da8d6facc66f9ec21e9b6f45fcb399a
5,315
from datetime import datetime def create_observation_from_inat_data(inaturalist_data): """Creates an observation in our local database according to the data from iNaturalist API. :returns: the observation (instance of Nest or Individual) created. Raises: TaxonMatchError """ observation_t...
7f122a37b37c9bdc045e5e93da16f9fcfa6bc132
5,316
import uuid def get_cert_sha256_by_openssl(certraw: str) -> str: """calc the sha1 of a certificate, return openssl result str""" res: str = None tmpname = None try: tmpname = tmppath / f"{uuid.uuid1()}.crt" while tmpname.exists(): tmpname = tmppath / f"{uuid.uuid1()}.crt" ...
9cd095bd8d2d710b1cf7e4a3155a0b4fc08587f5
5,317
def analytic_pi(x, c, w, h): """Analytic response function for an even pair of Lorentz distributions. Correspond to .. math:: \\Pi(x) = \\int_{-\infty}^{\\infty} \\frac{\\omega^2}{\\omega^2+x^2}\sigma()_{i} where :math:`\\sigma(\\omega)` is :func:`~even_lorentzian`. Args: x...
fc622e79a6692105c15e05ea353ba925b8378831
5,318
def run(canvas): """ This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ canvas = np.array(canvas) next_gen_canvas = np.array(create...
4a7ae84cf245755f51c3c7a5c22e646e452e6d7a
5,319
def initialize_vocabulary(vocabulary_path): """Initialize vocabulary from file. We assume the vocabulary is stored one-item-per-line, so a file: dog cat will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"]. Args: vocabulary_p...
bf56054aab47ac959fc38929445fc15a1d59b8a9
5,320
def ravel_space(space): """ Convert the space into a Discrete space. """ dims = _nested_dim_helper(space) return Discrete(dims[0])
baa04d3dd16e1c797bbdb83ff5f42474e77c57b4
5,321
def _add_col(dataframe, metadata, col_limits, families, weights, random_state): """Add a new column to the end of the dataframe by sampling a distribution from ``families`` according to the column limits and distribution weights and sampling the required number of values from that distribution.""" nrow...
b0a711a132f78188cc8b40fe3fb907d022aaa37a
5,322
import struct def read_and_decrypt_mylogin_cnf(f): """Read and decrypt the contents of .mylogin.cnf. This decryption algorithm mimics the code in MySQL's mysql_config_editor.cc. The login key is 20-bytes of random non-printable ASCII. It is written to the actual login path file. It is used t...
84b0831a139db80e0a8d48c7fbaacaef377c93e9
5,323
def list_files(tag=None, inst_id=None, data_path=None, format_str=None, supported_tags=None, file_cadence=dt.timedelta(days=1), two_digit_year_break=None, delimiter=None, file_type=None): """Return a Pandas Series of every file for chosen Instrument data. Parameters ----------...
e8dd3c25c953fb6d8ccef6cbef4fd31c579826fd
5,324
def is_on_top(bb1, bb2): """ For obj 1 to be on top of obj 2: - obj1 must be above obj 2 - the bottom of obj 1 must be close to the top of obj 2 """ bb1_min, _ = bb1 _, bb2_max = bb2 x1,y1,z1 = bb1_min x2,y2,z2 = bb2_max return z1 < z2 + ONTOP_EPSILON and is_above(bb1, ...
666b7a424fc1b8769cc436c07981ae134e6241a9
5,325
def prepare_definitions(defs, prefix=None): """ prepares definitions from a dictionary With a provided dictionary of definitions in key-value pairs and builds them into an definition list. For example, if a dictionary contains a key ``foo`` with a value ``bar``, the returns definitions will be a li...
ddc6d14cc18f8afba766efee65ab365df1d226c2
5,326
def load_training_data(mapsize=512, grfized=False, exclude_fid=False, dense_grid=False, random_split=False, from_files=False): """Load data for different training scenarios.""" if not grfized and (not dense_grid) and (not random_split): # the default data ...
2e2ddf93311c315f070c91af8bcc1a0df5e94343
5,327
def concat_features(args, feature_dim_name='feature'): """Concatenate Xs along a set of feature dimensions Parameters ---------- args : iterable list of tuples of the form (dims, DataArray) where dims is a tuple of dimensions that will be considered feature dimensions Returns ------- ...
d7b44931a5b8a626ca81e5260566c60379d64fc2
5,328
def _inspect_mixin( self, geoctx=None, format="pyarrow", file=None, timeout=30, client=None, **params ): """ Quickly compute this proxy object using a low-latency, lower-reliability backend. Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It's quick...
fd66a1728ca99806dc2c5056cf4a612ca7cac79b
5,329
def list_dvs(service_instance): """ Returns a list of distributed virtual switches associated with a given service instance. service_instance The Service Instance Object from which to obtain distributed virtual switches. """ return utils_common.list_objects(service_instance, vim.Distributed...
2223fe68c13868bea2884b292318e21cb1c2b99c
5,330
from typing import Optional def gdb_cli_args(request: FixtureRequest) -> Optional[str]: """ Enable parametrization for the same cli option """ return getattr(request, 'param', None) or request.config.getoption('gdb_cli_args', None)
635c5cfd397fe286003add99e094778f835a88d9
5,331
from datetime import datetime def coerce_rfc_3339_date(input_date): """This function returns true if its argument is a valid RFC 3339 date.""" if input_date: return datetime.datetime.strptime(input_date, "%Y-%m-%dT%H:%M:%SZ") return False
83cc2c32b74ad896d79db1a91f4a0fd88b26731e
5,332
def extract_job_url(job): """ parse the job data and extract the str for the URL of the job posted params: job str: html str representation from bs4 returns: url str: relative URL path of the job ad """ return job.a["href"]
7517badcc2814e641c04a8f880353d897d434b7f
5,333
import sh def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time), allow_...
a5a75cad77d605ef60905e8b36c6df9913b7bd3c
5,334
def weighted_loss(class_weights): """ Create a weighted loss function. Penalise the misclassification of classes more with the higher usage """ weight_values = list(class_weights.values()) def weighted_binary_crossentropy(y_true, y_pred): # add another dimension to compute dot product ...
804a643dff3916f376545a9f481edc418ebf5d8e
5,335
def delete_cluster(resource_root, name): """ Delete a cluster by name @param resource_root: The root Resource object. @param name: Cluster name @return: The deleted ApiCluster object """ resp = resource_root.delete("%s/%s" % (CLUSTERS_PATH, name)) return ApiCluster.from_json_dict(resp, resource_root)
2ed12d7f927d6579cbea81765b353f0eecae8f4a
5,336
def mk_test(x, alpha = 0.05): """This perform the MK (Mann-Kendall) test to check if there is any trend present in data or not Args: x: a vector of data alpha: significance level Returns: trend: tells the trend (increasing, decreasing or no trend) h: True (if...
8586c7ee5cf71ea79db9f57ebc6cc77d942962f7
5,337
from typing import List def convert_event_to_boxes(event: Event) -> List[EventBox]: """Takes in an event and converts this into a list of boxes that when combined completely cover the time allocated to this event. Usually, this list will contain a single EventBox as many events start and end on the same day, ...
c8f93fb2480792540e9052dd79c654e835021030
5,338
import copy def _reduce_consecutive_layers(conv_defs, start_id, end_id, multiplier=0.5): """Reduce the outputs of consecutive layers with multiplier. Args: conv_defs: Mobilenet conv_defs. start_id: 0-based index of the starting conv_def to be reduced. end_id: 0-based index of the last conv_def to be ...
ffcfad4956f72cf91aeaa5e795e9568d0808417f
5,339
def ajax_save_content(request): """ Save front end edited content """ site = get_current_site(request) content_name = request.POST['content_name'] cms_content = CmsContent.objects.get(site=site, name=content_name) cms_content.content = request.POST['content'] cms_content.save() return HttpRe...
f99bcfaa7ff5773870ed6ba76bfb0cc97fab248b
5,340
def add_regional_group_costs(ws, data_sheet): """ """ ws.sheet_properties.tabColor = "92D050" ##Color white ws.sheet_view.showGridLines = False #Set blue and red border strips set_cell_color(ws, 'A1:AZ1', "004C97") set_cell_color(ws, 'A2:AZ2', "C00000") ws = bar_chart(ws, "Estima...
a325b33b705819be81725e6fb6c4f277c6add097
5,341
def normal(loc=0.0, scale=1.0, size=(1,1), sparsity=1.0): """ Draw random samples from a normal (Gaussian) distribution. Parameters ---------- loc: Mean ("centre") of the distribution. scale: Standard deviation (spread or "width") of the distribution. size: Output shape (only tuple ...
cda973e6fa0ed2dcb0046cb1d5ef99dd5efbaf3c
5,342
def random_data(num): """ will return json random float, hex, int and a random password {0: { 'float': 186.66541583209647, 'hex': '43435c553c722359e386804f6b28d2c2ee3754456c38f5e7e68f', 'int': 851482763158959204, 'password': '5AJ]-02X0J' ...
108ebabe8b156218a452cbade729dc09356d2d0b
5,343
def denied(request): """Authentication failed and user was denied.""" return render(request, 'djangosaml2/denied.html')
9341e694163de3d8cd63d448ac39294003046dac
5,344
import os import traceback import sys def getFontCoverage(f, glyphCache=None): """ Calculate a weighted average of all glyph coverages. Use frequencies of multiple languages to average out language specific bias. So it does not use all the glyphs, just the A-Z, a-z for the languages we hav...
76b5fa4a3eea809e4c68ea72187ef4168a092219
5,345
import time def monday_of_week(year, week): """ Returns a datetime for the monday of the given week of the given year. """ str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w') date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon, day=s...
886c16df011f86eaa95254e360062d5530e05512
5,346
from typing import Mapping from typing import Any from typing import Dict def object_meta(metadata: Metadata) -> Mapping[str, Any]: """ Return a minimal representation of an ObjectMeta with the supplied information. Spec: https://github.com/argoproj/argo-workflows/blob/v3.0.4/docs/fields.md#objectmeta ...
fc4d30954f9c61c90511fbfc00b403017f41f6c9
5,347
from time import time def vectorize_timing(n_targets): """ Calculate the rise time of ``n_targets`` targets, return the run time in seconds. """ vega_coord = SkyCoord(279.23473479*u.degree, 38.78368896*u.degree) vega = FixedTarget(name="Vega", coord=vega_coord) target_list = n_targets*[veg...
287f723d66efedc9eaa874e3b1db9d6724598c10
5,348
import json def get_game(name, all=False): """ Get the game information for a particular game. For response object structure, see: https://dev.twitch.tv/docs/v5/reference/search/#search-games May throw exceptions on network/Twitch error. """ search_opts = { 'query': name, 'type': 'suggest', 'live': 'fa...
0946516ca7062087d0dc01daa89b328a26367145
5,349
def compute_correlation_prob_class_target(candidates_per_query_target): """This function computes the overall correlation between the probability of being in the positive class and the value of the target column """ probs_per_query_target = [] gains_per_query_target = [] for key in candidates_per_query_tar...
e0412cfa3940149d88c75f680aab55dece9b36a2
5,350
def get(sql: str): """ execute select SQL and return unique result. select count(1) form meters or select lass(ts) from meters where tag = 'xxx' :return: only value """ result = _query(sql) try: value = result.next() except StopIteration: return None ...
10b03b64c0a18b4cd5a3c83e6d101d05566b251c
5,351
def _get_parse_pauli_sums(): """Helper function to obtain the generator of the sampled list of the pauli sum coefficients after parsing pauli sums.""" # TODO(jaeyoo) : this will be c++ op def _parse_pauli_sums(pauli_sums, n_programs, n_ops): """Helper function to parse given pauli sums to colle...
4914cb42b8286455ffe0306ec8256e63925111ba
5,352
def is_fully_defined(x): """Returns True iff `x` is fully defined in every dimension. For more details, see `help(tf.TensorShape.is_fully_defined)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: is_fully_defined: `bool` indicating that the shape is fully known. """...
d3d419864fb9d6168adce54afae84f089c9a680c
5,353
def make_shell_context(): """ Creates a python REPL with several default imports in the context of the current_app :return: """ return dict(current_app=current_app)
8db290ccfa51681ac63e8e5d88b29c4e82176f36
5,354
def recommend_hybrid_user( df, model, interactions, user_id, user_dict, item_dict, topn, new_only=True, threshold=3, show=True): """Function to produce user recommendations. Hybrid version of recommend_known_user Args: mo...
f6f1bb5486dcd3a7848ca006998587a8efce4939
5,355
def i(mu_i, mu_ij, N) : """Calcule le tableau I[i, j]""" return [[I_ij(i, j, mu_i, mu_ij, N) for j in range(0, N)] for i in range(0, N)]
518609bbe91088d94267515ccd07b3fa16525d4f
5,356
import dateutil def format_datetime(this, date, date_format=None): """Convert datetime to a required format.""" date = dateutil.parser.isoparse(date) if date_format is None: date_format = "%d-%m-%Y" return date.strftime(date_format)
0311eb918540dbb0c5751244b89de220073b9dcd
5,357
import numpy def _estimate_melting_levels(latitudes_deg, valid_time_unix_sec): """Estimates melting level at each point. This estimate is based on linear regression with respect to latitude. There is one set of regression coefficients for each month. :param latitudes_deg: numpy array of latitudes (...
d72ac1cf0c23eadb49fc15e55c2a71e273120500
5,358
def edit_municipality(self, request, form): """ Edit a municipality. """ layout = EditMunicipalityLayout(self, request) if form.submitted(request): form.update_model(self) request.message(_("Municipality modified."), 'success') return redirect(layout.success_url) if not form.e...
4d233f97cbc7672b38348eb982cecc68f88ade17
5,359
from matplotlib import pyplot as plt def plot_period_transactions( model, max_frequency=7, title="Frequency of Repeat Transactions", xlabel="Number of Calibration Period Transactions", ylabel="Customers", **kwargs ): """ Plot a figure with period actual and predicted transactions. ...
2428c585dcd117302382b3788be9d763f23c1b3a
5,360
import copy def operate_monitor(params): """ different apps has different required params""" ret_obj = copy.deepcopy(RET_OBJ) group_id = params.get("group_id", type=int, default=None) app_name = params.get("app_name") operate = "update" if key_exist(group_id, app_name) else "insert" valid_ke...
8d78d61dc44acf2fdcc85a8e3cd4d6fd68c47bf6
5,361
def construct_rgba_vector(img, n_alpha=0): """ Construct RGBA vector to be used to color faces of pcolormesh This funciton was taken from Flamingo. ---------- Args: img [Mandatory (np.ndarray)]: NxMx3 RGB image matrix n_alpha [Mandatory (float)]: Number of border pixels ...
028275930ad4d2a3b98ce32e48021da8ff1e6c43
5,362
def nice(val): """Make sure this value is nice""" if pd.isna(val): return None return val
a2d0c3c64c7c2e01d66d171902e85a3d0056cc73
5,363
import logging import requests import json def retrieve_tree(issue_id): """Retrieve a tree of issues from Redmine, starting at `issue_id`.""" logging.info(f" Retrieving issue #{issue_id} ...") params = { 'issue_id': issue_id } response = requests.get(ISSUES_ENDPOINT, params=params, header...
928d2f3d68e5b9033a062d5e24d3f34f74781357
5,364
from typing import Sequence from typing import Dict def cmdline_args(argv: Sequence[str], options: Sequence[Option], *, process: callable = None, error: callable = None, results: dict = None) -> (Dict, Sequence[str]): """ Take an array of command line args, process them :param argv: argum...
c9c78d5a6b5fb6147a8b392647ec9a7e4abc2800
5,365
def trailing_zeroes(value): # type: (int) -> int """Count the number of trailing zeros in a given 8-bit integer""" return CTZ_TABLE[value]
a98968aa38c886de9aa38bae71e52d0e012c432c
5,366
def _calc_WaterCirculation(heat_load, CT_design, WBT, DBT, fixedCWT_ctrl, pump_ctrl, ignore_CT_eff, max_CT_eff=0.85): """Calculates the water circulation loop. Used by simulate_CT(). Parameters: Returns: All (time x CT) arrays as HWT Hot water temp [pint, C] CWT ...
46d4d7e8fb1c718821b9f64fe86fa268e05c459a
5,367
import zipfile import os import sys def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None, mode='w' ): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the...
97a24dfac85af54918ecda934ef854e4606ada0b
5,368
def read_dataset_from_csv(data_type, path): """Read dataset from csv Args: data_type (str): train/valid/test Returns: pd: data """ data = pd.read_csv(tf.io.gfile.glob(path + data_type + "*")[0]) return data
3b5fb8318d6b7297166b381d199fe206f4240d84
5,369
def search_ignore_case(s, *keywords): """Convenience function to search a string for keywords. Case insensitive version. """ acora = AcoraBuilder(keywords, ignore_case=True).build() return acora.findall(s)
bf093c3864353278a9ff91267b0806bc1e2362a3
5,370
import logging from typing import Union from typing import Iterable def _logger_setup(logger: logging.Logger, header_label: str, formatter: Formatter = None, level: int = logging.INFO, level_normalized: int = logging.INFO, handl...
20c5147d28e9afd7f6f4c9600f9d43ec68aeacb0
5,371
from typing import Union from typing import List import pathlib def _prepare_directory(data_dir: Union[str, PathLike], ignore_bad: bool = True, confirm_uids: bool = True) -> List[str]: """ Reorganizes PPMI `data_dir` to a structure compatible with ``heudiconv`` ...
2220dec499f875501ab7fd80e4bdcf25c61c641d
5,372
import re def find_log_for(tool_code, form_id, log_f): """Returns an array of lines from log for given tool code (P1,N3,...) and form_id. The form_id is taken from runner - thus we search for formula number ``form_id+1`` """ log = open(log_f,'r') current_f = -1 formula = re.compile('.*...
c28659ce832dcc8ad372188a556699f20c9116db
5,373
import json import subprocess def get_images(repository_name): """Call ecr to get available images""" eprint("obtaining available images") try: out = json.loads( run_command([ "aws", "ecr", "describe-images", "--repository-name", repository_name, "--no-paginate"...
6c523e071b81e24871cb9908677ed69299d22360
5,374
import shlex import inspect import subprocess def exe_cmd_and_poll_output(cmd, encoding='UTF-8', is_capture_output=False): """ 将命令输出实时打印到标准输出 :param is_capture_output: :param cmd: 命令行 :param encoding: 字符编码 :return: 标准输出字符串列表 """ func_name = inspect.stack()[0][3] hlog.enter_func(fu...
cdc7fe1d6412d722a70e14f1fb1576fbfd16ff4b
5,375
def create_patric_boolean_dict(genome_dict,all_ECs): """ Create new dict of dicts to store genome names :param genome_dict: dict of key=genome_id, value=dict of genome's name, id, ec_numbers :param all_ECs: set of all ECs found across all genomes """ ## new format: key=genome, value={EC:0 or 1}...
7ab3554bbf705ee8ce99d1d99ff453b06e3d2b53
5,376
def append_ast_if_req(field): """ Adds a new filter to template tags that for use in templates. Used by writing {{ field | append_ast_if_req }} @register registers the filter into the django template library so it can be used in template. :param Form.field field: a field of a form that you woul...
76e36ead3387729b0536bf84f288c400f376a041
5,377
def getPileupMixingModules(process): """ Method returns two lists: 1) list of mixing modules ("MixingModule") 2) list of data mixing modules ("DataMixingModules") The first gets added only pileup files of type "mc", the second pileup files of type "data". """ mixModules, dataMixModules = [], [] ...
4ee3cc5f7b11e4ad6a846f14dc99e4f82bd04905
5,378
from typing import Hashable from typing import Type from typing import Any from typing import ForwardRef import typing def GetFirstTypeArgImpl_(type_: Hashable, parentClass: Type[Any]) -> Type[Any]: """ Returns the actual type, even if type_ is a string. """ if isinstance(type_, type): return type_ ...
f6fd63c4080af886de24465d866f87e716b49992
5,379
from typing import Callable from typing import Any from typing import Sequence def tree_map_zipped(fn: Callable[..., Any], nests: Sequence[Any]): """Map a function over a list of identical nested structures. Args: fn: the function to map; must have arity equal to `len(list_of_nests)`. nests: a list of id...
8117efd93402fb7ab5e34b4015950c77a24dc038
5,380
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! return pow(side,2)
e3cc1a0d404c62a9b1d50de63ea924087c77066a
5,381
def match_collision_name_to_mesh_name(properties): """ This function matches the selected collison to the selected mesh. :param object properties: The property group that contains variables that maintain the addon's correct state. :return str: The changed collision name. """ collisions = get_fr...
3658435cdaa21408664a511e3555f3976c1b3614
5,382
def _handle_event_colors(color_dict, unique_events, event_id): """Create event-integer-to-color mapping, assigning defaults as needed.""" default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list()))) # warn if not enough colors if color_dict is None: if len(unique_events) > len(_ge...
31ae730af0a184b5de469687b74334960c2939ef
5,383
import logging import warnings def redirect_logs_and_warnings_to_lists( used_logs: list[logging.LogRecord], used_warnings: list ) -> RedirectedLogsAndWarnings: """For example if using many processes with multiprocessing, it may be beneficial to log from one place. It's possible to log to variables (logs a...
31cda3f036c8438371811b6421a8af2b0f6ac215
5,384
def get_file_picker_settings(): """Return all the data FileUploader needs to start the Google Drive Picker.""" google_settings = frappe.get_single("Google Settings") if not (google_settings.enable and google_settings.google_drive_picker_enabled): return {} return { "enabled": True, "appId": google_settings.a...
3b1840e22512e1f9112f9fa4dfb6697299aa248a
5,385
import os import codecs import re def find_version(*file_paths): """ Args: *file_paths: Returns: """ here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Args: *parts: Returns: """ with codecs.open(os.path.join(her...
e4723ef772f210ea0ac9e8c318ddc597b25a8440
5,386
def match_subset(pattern: oechem.OEMol, target:oechem.OEMol): """Check if target is a subset of pattern.""" # Atoms are equal if they have same atomic number (so explicit Hydrogens are needed as well for a match) atomexpr = oechem.OEExprOpts_AtomicNumber # single or double bonds are considered identica...
99d8d5d73f465f929b6710ec53b5e01f92c1e229
5,387
def get_quad_strike_vector(q): """ Compute the unit vector pointing in the direction of strike for a quadrilateral in ECEF coordinates. Top edge assumed to be horizontal. Args: q (list): A quadrilateral; list of four points. Returns: Vector: The unit vector pointing in strike direc...
169b8043a5a385843b92225cba8677ef39bb43a5
5,388
def CP_to_TT( cp_cores, max_rank, eps=1e-8, final_round=None, rsvd_kwargs=None, verbose=False, ): """ Approximate a CP tensor by a TT tensor. All cores of the TT are rounded to have a TT-rank of most `max_rank`, and singular values of at most `eps` times the largest singular val...
54c30dec3f18271050150dfcc443fcbfe74c4df5
5,389
def _create_key_list(entries): """ Checks if entries are from FieldInfo objects and extracts keys :param entries: to create key list from :return: the list of keys """ if len(entries) == 0: return [] if all(isinstance(entry, FieldInfo) for entry in entries): return [entry.ke...
bb87bbfbfc1856d4041c12d8babaaa8d8ce42249
5,390
def compose_rule_hierarchies(rule_hierarchy1, lhs_instances1, rhs_instances1, rule_hierarchy2, lhs_instances2, rhs_instances2): """Compose two rule hierarchies.""" if len(rule_hierarchy1["rules"]) == 0: return rule_hierarchy2, lhs_instances2, rhs_instances2 if len(rule_h...
0cfab451af31bfc7b41d610381efb47e8c5c0fb5
5,391
def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
50adf652fff47418d1f8f1250a2a6d01f712da76
5,392
import logging import requests import time import json import pytz def fetch_exchange(zone_key1='DK-DK1', zone_key2='DK-DK2', session=None, target_datetime=None, logger=logging.getLogger(__name__)): """ Fetches 5-minute frequency exchange data for Danish bidding zones from api.energidat...
93488b4bc24a6a899232a5a1fd0e694d0747ad12
5,393
def snitch(func): """ This method is used to add test function to TestCase classes. snitch method gets test function and returns a copy of this function with 'test_' prefix at the beginning (to identify this function as an executable test). It provides a way to implement a st...
b8b54d55269951cb3db4c1f45c375ac36cbd3bdf
5,394
def average_h5(path, path_dc): """Return averaged data from HDF5 DC measurements. Subtracts dark current from the signal measurements. Args: - path, path_dc: paths to signal and dark measurement files. Returns: - 2D array containing averaged and DC-subtracted measurement. """ with h5....
8daaa7efcdbaf7137d320407b64a96b73f847289
5,395
def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"): """Computes the Levenshtein distance between sequences. This operation takes variable-length sequences (`hypothesis` and `truth`), each provided as a `SparseTensor`, and computes the Levenshtein distance. You can normalize the edit dis...
9dfcebb6f49de41c5d5d6bfcc849873f14e2b3f9
5,396
import os from datetime import datetime def file_timestamp(path): """ Returns a datetime.datetime() object representing the given path's "latest" timestamp, which is calculated via the maximum (newest/youngest) value between ctime and mtime. This accounts for platform variations in said values. ...
f75d381d10072f2ada8c62f333d32f4fc8d6ccf3
5,397
def kl_bernoulli(p: np.ndarray, q: np.ndarray) -> np.ndarray: """ Compute KL-divergence between 2 probabilities `p` and `q`. `len(p)` divergences are calculated simultaneously. Parameters ---------- p Probability. q Probability. Returns ------- Array with the KL...
91567169da22ae42bd90c15292f1699f53a184ab
5,398
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): """Calculate mean update and a Youngs and Cramer variance update. last_mean and last_variance are statistics computed at the last step by the function. Both must be initialized to 0.0. In case no scaling is required last_var...
8fac3715bed8431f0910bbf7a37d3924afece9c0
5,399