content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence from typing import List def transposition_order_rep( ttset: Sequence, n: int ) -> List: """ Applies the transposition operation on a tone row with its order numbers """ result = [0] * len(ttset) for i, pair in enumerate(ttset): new_pc = (pair[1] + n) % 12 ...
1d9bf53166d3119b465c9dab4c7558892f720b79
67,478
def parse_lines(lines: str): """ Parse multiple Write objects separeted by new-line character. """ writes = map(LineParser.parse, lines.split("\n")) return list(writes)
a6533fb6972f66692e730d10d2253b59cad77d8a
67,480
def get_factory_log_recipients(entry): """Read the log recipients specified by the Factory in its configuration Args: entry: dict-like object representing the entry configuration Returns: list: list contaning the URLs of the log servers, empty if none present """ entr_attrs = entry...
f3e776ea9b8102247b5c7e817762523467d9f953
67,481
def translate_name(name: str) -> str: """Not complete func""" return name.replace(' ', '+').replace(',', '%2C').replace('’', "'")
4faf41ffbd2231b35bc235c1c76ea9403b7cd78c
67,482
import csv def get_conditions_bids(infile): """ read onsets, duration and amplitude from 3 column format file. (e.g. events.tsv in BIDS format) """ spec = [] if infile.endswith('.tsv'): # read tsv file with open(infile) as f: reader = csv.reader(f, delimiter='\t'...
3bd0546115fa635abbcc7829911fdb476ad1c33e
67,483
import torch def compute_colors_for_labels(labels, palette=None): """ Simple function that adds fixed colors depending on the class """ if palette is None: palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1]) colors = labels[:, None] * palette colors = (color...
aaab8121146d43c44db7a2450c384213b1b92b7f
67,484
from datetime import datetime def get_query_params(node='SLAP_PGEB-APND', market='RT5', startdate=datetime(2019, 1, 1), enddate=datetime(2019, 1, 15), tz_in='US/Pacific', tz_out='US/Pacific'): """Create a dict...
13169e3956fd30e08bc064228a8bfdbf9db36bda
67,486
def preprocess(raw): """ Basic text formatting e.g. BOM at start of file """ ## 1. Remove byte order marks if necessary if raw[0]=='\ufeff': raw = raw[1:] # if raw[0] == '\xef': # raw = raw[1:] # if raw[0] == '\xbb': # raw = raw[1:] # if ...
dfeb75152196ff2ab751ee206aab03eed1f28502
67,487
def get_assignment_student_grades(course_id, student_id): """ return a list of a student's assignments with grades https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.student_in_course_assignments """ return api.get_list('courses/{}/analytics/users/{}/assignments'.format(course_id...
488fda23b4978ee820ab60638a6df6fe3fc86f65
67,488
from typing import Optional from typing import Dict def get_strain_strat(voc_params: Optional[Dict[str, VocComponent]]): """ Stratify the model by strain, with two strata, being wild or "ancestral" virus type and the single variant of concern ("VoC"). Args: voc_params: All the VoC parameters ...
eb9f2c21c506eebccc9b74d59ac3391e8427ef68
67,489
import tarfile import json from datetime import datetime import re import uuid def oc_parser(instance, parameters, context, feedback, inputs): """ Dieses Python-Script liest aus Daten einem tar-komprimierten Abbild OpenCaching Datenbank Standorte und Attribute von Geocaches sowie Schutzgebieten ein und schrei...
6309b16fc9f8043dcfd20bcadbaab84a36e24599
67,490
def business(category): """ view root page function that returns the categories page and its data """ news_categories_articles = get_category(category) return render_template('business.html', business = news_categories_articles)
0a9ee4416545bc95dc4a568d469543ebee15c9a1
67,491
import time import zlib def query_cash_flow_data(code, year=None, quarter=None): """季频现金流量 @param code: 证券代码,不可为空 @param year: 统计年份,为空时默认当前年 @param quarter: 统计季度,为空时默认当前季度 """ data = rs.ResultData() if code is None or code == "": print("股票代码不能为空,请检查。") data.error_msg = "股票代...
a5dfe8f78abef656562c8eb5824d31fde62a38e5
67,492
def calc_num_pixels(num_pixels, stride): """ Converts the current number of pixels to the number there will be given a specific stride. """ return 1 + (num_pixels - 1) // stride
b6ae056339913c496017251709381c19f551a074
67,493
import re def wrap_onspace_strict(text, width): """Similar to wrap_onspace, but enforces the width constraint: words longer than width are split.""" wordRegex = re.compile(r'\S{'+str(width)+r',}') return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
0a52193b5dc2b827a875641b5cb233b330ef9bfe
67,494
def _eigen_projection(x, b): """ Project the vector `x` onto the eigenvector `b`. Here `b` is a column of the matrix B which is an orthonormal basis from the eigendecomposition:: BDB = C Parameters ---------- x : array_like, shape (n,) Vector. b : array_like, shape (n,) ...
d6ce8183bfa25d474c868786959ed663cd83fbd2
67,495
def disk_simple(radius, precision=0.0001): """ A centered disk of specified radius. Parameters ---------- radius : float Radius of desired disk, presumed to be in coordinate units. precision : float, must be << 1 Desired upper bound for error in fractional partial volumes. ...
183e4884c5781d5ba32332f6f740592e9b9e8b86
67,496
def tokenize(language): """Function to tokenize language by mapping words to integer indices""" # Perform tokenization language_tokenizer = Tokenizer(filters='') language_tokenizer.fit_on_texts(language) tensor = language_tokenizer.texts_to_sequences(language) # Pad sequences to maximum found se...
88466883179065a77f1355a5c7d13989f8fd2e57
67,498
import re def _fix_broken_markup(html): """Replaces invalid comment tags""" if html.startswith("<CENTER>"): logger.error("TolkienFanFiction.com couldn't handle this request: '%s'" % html) html = re.sub("<!-.+?->", "", html) return html
4a4b5749ea7737965fd135e0b190cdb8e1ee3d37
67,499
from typing import Tuple from typing import Optional def _make_generic_sql_bound( bound: str, column_names: Tuple[str, str], values: Tuple[Optional[int], int], engine: BaseDatabaseEngine, ) -> str: """Create an SQL expression that bounds the given column names by the values, e.g. create the eq...
5575c25b78d4176f9be14b4410eee29ccb29347f
67,500
import bisect def add_domain_parallel(updated_mask, lb, ub, lb_all, up_all, domains, selected_domains, slope, growth_rate=0, branching_decision=None, save_tree=False, decision_thresh=0): """ Use binary search to add the new domain `candidate` to the candidate list `domains` so that...
80b1a2a53694fff56584854e28ad0db82fadbc91
67,501
import xloil_core def get_event_loop(): """ Returns the background asyncio event loop used to load the current add-in. Unless specified in the settings, all add-ins are loaded in the same thread and event loop. """ addin = source_addin() return xloil_core.get_event_loop(addi...
4ee0c6c5b495dcb0d0c8fbca43cb28a747a1056d
67,502
import socket import re def write_handler(host, port, element, handler, value): """Write to a click handler.""" sock = socket.socket() sock.connect((host, port)) f_hand = sock.makefile() line = f_hand.readline() if line != "Click::ControlSocket/1.3\n": raise ValueError("Unexpected r...
ace3954a1893b6f3637332ad799be00c5d36e3c5
67,503
def register(request): """Faz o cadastro de um novo usuário""" if request.method != 'POST': # Exibe o formulário de cadastro em branco form = UserCreationForm() else: # Processa o formulário preenchido form = UserCreationForm(data=request.POST) if form.is_val...
136f3b2413745b5d1be3d333e538c82cc7a09e9e
67,504
import copy def set_quantization_configuration_to_graph(graph: Graph, quant_config: QuantizationConfig, fw_info: FrameworkInfo) -> Graph: """ Add quantization configuration for each graph node. Args: graph: Gr...
fbcdbf47cdd119a26a0a04b1b4032f8fec7eb961
67,505
def snowballstem(context_word_list): """Use nltk and Snowball stemmer to stem.""" #print("Stemming using Snowball Stemmer") #texts_gen = back_to_string(texts) # KEEP ONLY NOUNS, ADJ, VERB, ADV return [snowball.stem(word) for word in context_word_list]
6745704fb7412009b519bebdc30fa3da40a8c325
67,507
from typing import Union from typing import Tuple def _make_version(version: Union[str,int,Tuple[int]]) -> Tuple[int]: """Build a tuple-of-integer version from a string or a unique integer. :param version: the version to convert, if needed :return: the tuple-based version """ try: i...
2c8b05f9ae77657aae84f400c927fb8b2924c78c
67,509
import logging def file_getchild( gateway, volume, parent_id, name ): """ Get all metadata for a file, given the its parent ID and name. """ logging.info("getchild /%s/%s/%s" % (volume.volume_id, parent_id, name) ) owner_id = msconfig.GATEWAY_ID_ANON if gateway != None: owner_id = gate...
a906aad0bc9db097b5fc6e5e19e9c166b621b87d
67,510
def __convert_timecode(timecode): """ Takes a timecode value that's either a string or a number and returns it back in a number format. """ if isinstance(timecode, str): try: t = timecode.split(":") if len(t) == 2: t.insert(0, "0") return (int(t[0]) * 60 ...
500e137836db417ff6512c5ff7076abf89b01a28
67,511
def rig_reg_drift(dset, rel_drift): """ Shifting images on top of each other Uses relative drift to shift images on top of each other, with center image as reference. Shifting is done with shift routine of ndimage from scipy. This function is used by rigid_registration routine Parameters -...
29601ef4facf9068d47de29eeb431c965677d404
67,512
def readme(): """Returns the contents of the README without the header image.""" header = '======\nGimbal\n======\n' with open('README.rst', 'r') as f: f.readline() return header + f.read()
892100a63287917a35850258c677ee53ee2883a0
67,513
def init_lstm(params, prefix='lstm', nin=None, dim=None, init='glorot', learn_init=True): """ Initialize the LSTM parameters. """ assert nin > 0, 'nin should be provided' assert dim > 0, 'dim should be provided' logger.info('nin: {} dim: {}'.format(nin, dim)) initializer = u...
9de497d936c8e01da2890743dbf07895ce792875
67,514
def ApplicationError(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 499
96d877b89948a58997a11f5f77b4247fe3c6eeac
67,515
def make_sm_update_status_job( b: Batch, analysis_type: str, status: str, sm_db_name: str, analysis_id: str ) -> Job: """ Creates a job that updates the sample metadata server entry analysis status. """ assert status in ['in-progress', 'failed', 'completed', 'queued'] j = b.new_job(f'SM: update ...
59df34ee6db8d91c81318924819cda405bd20303
67,516
from typing import Callable from typing import Mapping def assembly_sub_strategy_factory_for_book_then_lang( usfm_resources: list[USFMResource], tn_resources: list[TNResource], tq_resources: list[TQResource], tw_resources: list[TWResource], ta_resources: list[TAResource], assembly_substrategy_...
6e74db1ece469523f4a86b5b8e0f501003bc23ad
67,517
from typing import Counter import random def stratified_group_k_fold(X, y, groups, k, seed=None) -> (list, list): """StratifiedKFoldで分割する関数 Args: X (pd.DataFrame): trainデータ y (pd.DataFrame): 目的変数のDF groups (pd.DataFrame): groupに指定するカラムのDF k (int): k数 seed (int): seet. ...
cfa4766d047eec36e835ac83b0bb764f7af9a2eb
67,518
def load_images(image_files: list, input_width: int, input_height: int, data_type=np.uint8, scale: float = 1., mean: list = [0., 0., 0.], stddev: list = [1., 1., 1.], preprocess_fn=preprocess_default): """Loads images, resizes and performs any additional preprocessing to run inferenc...
b4ab3d4dd059f34d5177df6f1743dcc3f6c6ac9e
67,519
def browser(wsgi_app, verwalter): """Get a zope.testbrowser for the WSGI-APP.""" return sw.allotmentclub.browser.testing.Browser(wsgi_app=wsgi_app)
5247993c5587fa4acf7cc6c8c752c4e8eee22bc1
67,520
def get_one_csv(df): """Prepare DataFrame. __Attributes__ df: DataFrame with parsed data. __Returns__ df: DataFrame sorted by date abd without duplicates. """ # 3:19 PM 13/12/2018 # Change datetime format to what we want (example above) df['date'] = df['date'].str.strip()....
0c6ba26f017b47589cf85164bda70ff17dce5ae9
67,521
def get(expr, key, default=None): """ Return the mapped value for this key, or the default if the key does not exist Parameters ---------- key : any default : any """ return ops.MapValueOrDefaultForKey(expr, key, default).to_expr()
1b2e3a8e0d47e5d9512651b840e06c1baba0028c
67,522
from typing import List import re def articles_from_file(file_path: str) -> List[WikitextArticle]: """Read wikitext articles from file. Args: file_path: path to the input `.tokens` file. Returns: A list of `WikitextArticle` tuples. """ with open(file_path, mode='rb') as f: content = f.read() ...
1c8c93e4f781ceeaf27f3fb9362b37ca1f2b1168
67,523
def get_mt( mt_path: str, split: bool = False, hard_filtered_samples_to_remove_ht: hl.Table = None, meta_ht: hl.Table = None, add_meta: bool = False, release_only: bool = False, passing_sites_only: bool = False, unrelated_only: bool = False, ) -> hl.MatrixTable: """ Wrapper funct...
ca34e4c1e0a5a5b19270f8015ae1a07b138ab205
67,524
import itertools def gen_graphs(n_graphs, n_nodes, p_intra=0.7, p_inter=0.01): """ Generate community graphs. """ A = np.zeros((n_graphs, n_nodes, n_nodes)) for idx in range(n_graphs): comms = [nx.gnp_random_graph(n_nodes // 2, p_intra), nx.gnp_random_graph((n_nodes + 1) /...
218793c6a29b675807b7180e6507d40fce5fe6de
67,525
def wallis_product(n_terms): """Implement the Wallis product to compute an approximation of pi. See: https://en.wikipedia.org/wiki/Wallis_product XXX : write Parameters and Returns sections as above. """ # XXX : The n_terms is an int that corresponds to the number of # terms in the produc...
1e0ba6bbb9ec5fd9de1d4ee84448402801fdb514
67,526
def num_executors(sc): """ Get the number of executors configured for Jupyter :param sc: The SparkContext to take the executors from. :type sc: [SparkContext :return: Number of configured executors for Jupyter :rtype: int """ return EnvSing.get_instance().get_executors(sc)
2a18204f17f31fb8ed07d1cacf3ef30d6930b890
67,527
import struct def read_zygo_metadata(file_contents): """Parse metadata from the contents of a binary Zygo file. Parameters ---------- file_contents : `bytes` binary file contents Returns ------- `dict` dictionary with a shitload of keys for all of Zygo's metadata. ""...
23f20e8ffa3c248cde535b2b2fc2d5a4a2fd2884
67,528
def bbox_iou2(box1, box2): """ Returns the IoU of two bounding boxes """ b1_x1, b1_x2 = box1[0], box1[2] b1_y1, b1_y2 = box1[1], box1[3] b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 # get the corrdinates of the i...
e466a3277c0f0ddd55651c4352d026bb106367fc
67,529
def parse_validator(validator): """ parse validator Args: validator (dict): validator maybe in two formats: format1: this is kept for compatiblity with the previous versions. {"check": "status_code", "comparator": "eq", "expect": 201} {"check": "$resp_body_s...
f97cb8e0d538f6d0a9308541b42d2334733bf6b2
67,531
import uuid def AjaxSubForm(form_cls, slug, **kwargs): """ Helper method for modifying one form to act as a sub-form to a parent-form. """ _id = str(uuid.uuid4()).replace('-', '') new_cls = type(str('_%s_%s' % (form_cls.__name__, _id)), ( form_cls,), {'extra': kwargs.get('extra', 0)}) ...
095ba1886958c3a13ff35eed7cf39b23f157f0ec
67,532
def BTAZI2BQBU(Bt,azi): """Transformation from transverse field and azimuth to BQ and BU according to https://arxiv.org/abs/1904.03714 Parameters ---------- Bt, azi : float Values to be transformed """ By = Bt*np.sin(azi) Bx = Bt*np.cos(azi) BQ = np.sign(Bx**2.-By**2.)*np.sq...
eb29d33a55170950bfc6618a55ef38e2cf7e07e6
67,533
def random_phase_vector(s, n, rand_state=None): """ Generates a uniformly random phase vector for a n-qubit Clifford. (This vector, together with the provided symplectic matrix, define a valid Clifford operation.) In combination with a uniformly random `s` the returned `p` defines a uniformly rand...
2565696b4ec5b7a07030fee17eaaa194938bb1ed
67,534
def rewrite_arcs (label_map, nfa): """Rewrite the label arcs in a NFA according to the input remapping.""" states = [[(label_map[label], tostate) for (label, tostate) in arcs] for arcs in nfa[2]] return (nfa[0], nfa[1], states, nfa[3], nfa[4])
2bd9911a5c65ce7711848746614a3a6ceb37f8d2
67,535
def create_fig(image, canvas_list, obj_enc_list, obj_dec_list, z_pres_list, z_prob_list, z_where_list): """ All types should be numpy or python numbers. """ fig = plt.figure() for i in range(3): ax = fig.add_subplot(4, 3, i + 1) ax.set_title('pres: {:.0f}, p: {:.2f}'.format(z_pres_li...
eb7c805d302e9ee90766e2f2fe59356cb8f16c7e
67,536
from typing import List from typing import Tuple def _details_family_code() -> List[Tuple]: """Details for logging FamilyCode.""" return [ ("AccountID", dht.string, lambda fc: fc.accountID), ("FamilyCode", dht.string, lambda fc: fc.familyCodeStr), ]
bcae9a044bb44b1390ee066225d04db2882d4537
67,537
import copy def merge_params(base_params, partial_params=None): """Merge a partial change to the base configuration. Parameters ---------- base_params The base parameters partial_params The partial parameters Returns ------- final_params The final parameters ...
4c52d492358106b7c5e6df0c1e099d45043a7935
67,538
def date_message(date_str: str) -> str: """Return a message about the date.""" # Get location location = get_location(date_str) # Get the current date date = get_time_by_lat_long(location) return f"The date in {location} is {date.strftime('%a %d %b')}."
b9f71253fddad95a2ce877358d7f7ec4e0ff7585
67,539
def modified_cartesian(*args, **kwargs): """Modified Cartesian product. This takes two (or more) lists and returns their Cartesian product. If one of two list is empty this function returns the non-empty one. Parameters ----------- *args : lists, length : two or more The group of input...
fa0f6830dcffb79c6e2a895458495458b6d62e07
67,540
def get_person(person_id): """Get information about a person.""" try: with Session(DB.engine) as session: person = session.query(Person).where(Person.id == person_id).one() return {"person_id": person.id, "name": person.name, "email": person.email} except NoResultFound: ...
e667f8b54d608847e7cbee553b1e5bc3e4dcda4c
67,541
def execute_query(query, db): """ Executes a query Arguments: query - the query to execute db - the database to execute the query on ("users" or "products") """ # Create tables if they don't exist create_products_table() create_user_table() # Connect to tables users_d...
b0a944e9030177132598785e810af121c8bbbb25
67,542
def parse_variant( store, institute_obj, case_obj, variant_obj, update=False, genome_build="37", get_compounds=True, case_dismissed_vars=[], ): """Parse information about variants. - Adds information about compounds - Updates the information about compounds if necessary and '...
5af1283ba64ddd6325e15a18d74de777b4669400
67,543
def create_dicts_same_nodes(my_set, neighbors_dict, node, dict_out, dict_in): """ A function to create useful dictionaries to represent connections between nodes that have the same type, i.e between nodes that are in the embedding and between nodes that aren't in the embedding. It depends on the input. ...
c4ef94964f2944dcbddd79f76182a4bcc64633e7
67,544
import json def get_china_province(ChinaTotal, ChinaProvince): """ 获取最新国内各省数据 :return: """ return json.dumps(inner_get_china_province(ChinaTotal, ChinaProvince), ensure_ascii=False)
a13c22808bedcccbf4d8faba7229fb7b303bd878
67,545
import torch import logging import pickle def evaluate(model, loss_fn, data_iterator, metrics, params, num_steps, sample_weights=None): """Evaluate the model on `num_steps` batches. Args: model: (torch.nn.Module) the neural network superclass loss_fn: a function that takes batch_output and bat...
3e3cf80f1b26c42da5cbfc802c54d9587dfacc7d
67,546
def plaquette_spanning_tree(lattice: Lattice, shortest_edges_only = True): """Given a lattice this returns a list of edges that form a spanning tree over all the plaquettes (aka a spanning tree of the dual lattice!) The optional argument shortest_edge_only automatically sorts the edges to ensure that only the s...
9a83a8743244331e62a3447a3b370a70b8decc14
67,547
def check_params(): """ Check all the CLI inputs. Must give INSTALLER_TYPE, INSTALLER_IP, user and filepath of the output file. Need to give key or password. """ if not args.INSTALLER_TYPE or not args.INSTALLER_IP or not args.user: print("INSTALLER_TYPE, INSTALLER_IP and user are all nee...
abced80ef2cc12b0615bd612051a2c728014cab9
67,548
def flatten(list_of_lists): """Single level flattening of a list.""" return sum((list(sublist) for sublist in list_of_lists), [])
d7a2b9b75a1bd920f50d78cc725f8e551d6bb2f5
67,549
def get_num_channels(x): """ :param x: an input tensor with shape [batch_size, ..., num_channels] :return: the number of channels of x """ return int(x.get_shape()[-1])
6016098ae8cea31ddf902f6c6e8c4b45d2d114ae
67,550
def get_movements( key: dict, tracking: pd.DataFrame, moving_threshold: float, turning_threshold: float, paw_speed_th=10, ) -> dict: """ Creates array indicating when the mouse is doing different kinds of movements """ paws = tracking.loc[ tracking.bpname.isin(["left_fl"...
c8c65c46fecdce61341b701d12e52dce24fe1b6a
67,551
from typing import Type from typing import Optional def _get_inner_meta_class(struct_class: Type[Struct]) -> Optional[Type]: """Retrieve the `Meta` inner class of a Struct class, or None if none is provided.""" if not hasattr(struct_class, _META_INNER_CLASS_NAME): # pytype: disable=wrong-arg-types re...
f3933fca07fb1dbb82546539892160392e672045
67,552
def maximum() -> int: """Returns 9.""" return 9
dfd9a240bdaf985f89ca1b90c2b6e01f5426b2b0
67,554
def input4FwdBkw(states: tuple, observation_labels: np.array, ts_array: np.array, pai: np.array, transDist: np.array, emisDist: np.array, f: object) -> (dict, dict, dict): """ :param states: :param observation_labels: :param ts_array: :param pai: :param transDist: :param em...
39274416fdd84b1e43a9489c7a1d56b9190dc084
67,555
import types def on(signals, callback=None, max_calls=None): """ Registers a single callback for receiving an event (or event list). Optionally, can specify a maximum number of times the callback should receive a signal. This method works as both a function and a decorator:: smokesignal.on('f...
759ab43bed7bd865dc3cfe439575b03894aac30d
67,556
def _only_target_vars(ds: xr.Dataset, data_vars: t.Optional[t.List[str]] = None) -> xr.Dataset: """If the user specifies target fields in the dataset, create a schema only from those fields.""" # If there are no restrictions on data vars, include the whole dataset. if not data_vars: logger.info(f't...
a4602be2d8957e2f1b1b94aac0ce3da0aa9eb6e0
67,557
def load_model_from_path(model_type, path): """ Loads a spark ml model from a path :param str | AlgorithmEnum | ScalerEnum model_type: the string representation of the model import, e.g. `pyspark.ml.feature.StandardScaler` :param str path: :return: """ return class_from_str(model_typ...
b711751d332591b46b8f82fc24768c1a236f278e
67,558
import tqdm import itertools def estimate_parameters(x,processes,total_reads,max_chunk_size): """Estimate parameters? This copied over from the old old old PyFitSeq - dunno if still relevant but it's missing in this version !!! A SUB-FUNCTION CALLED BY MAIN FUNCTION main() TO CALCULATE THE LOG ...
731fd8496f1993635f7c4b6399b861706651dfe6
67,559
def MagScatFac(El, SQ): """compute value of form factor :param El: element dictionary defined in GetFormFactorCoeff :param SQ: (sin-theta/lambda)**2 :param gfac: Lande g factor (normally = 2.0) :return: real part of form factor """ mfa = np.array(El['mfa']) mfb = np.array(El['mfb']) ...
5469cd78b479d4b4be1225c5303231a069c8d980
67,560
def reduce(data, filename): """ Reduce the data given by the data string and the filename. """ #first decide what file type this is. ext = filename.split(".")[1] if ext == 'hfbs': ret = hfbs_reduce(data,filename) elif ext =='hscn': ret = hscn_reduce(data,filename) else: ...
5a3a5b429c0d0cae094951cbe3c1c453e0e01454
67,561
def config(): """ Configuration file for edith usage """ config = { "edith": { # don't change "version": 1.0 # don't change }, "config": { # change this "host": "Raspberry Pi Zero WH", # change host to machine running program "online serv...
3c4adf4407311428be2c97fdc61dd636de63d760
67,563
def vectorize(hash_function, feature_dict=None, size=1024): """Helper function to vectorize a spatial description from a hash. Hash functions are used to perform spatial featurizations in DeepChem. However, it's necessary to convert backwards from the hash function to feature vectors. This function aids in t...
3ecbb776ceb162841c83de3d96288fce6c9f551a
67,564
def get_uniform_random_number(low, high): """ :param low: 均匀分布的下界 :param high: 均匀分布的上界 :return: 从均匀分布中产生的随机数 """ # 均匀分布的随机数生成 number = np.random.uniform(low, high) # 返回值 return number
206704a81a35d71ecadc9a1e7db1ddcc38c8c981
67,565
def bootstrapOneSampTest(data,nv=0,nullTranslation=None,statFunc=None,nPerms=10000): """Uses a bootstrap to calculate a p-value for a one sample test of H0: mean(data) != nv Uses a t-statistic as is used in Efron and Tibshirani""" L=len(data) if statFunc is None: statFunc = lambda data: (np...
caff773b1fbb7f98d21e78da98f9436a40a45312
67,567
def center_time(ds): """make time the center of the time bounds""" ds = ds.copy() attrs = ds.time.attrs encoding = ds.time.encoding tb_name, tb_dim = _get_tb_name_and_tb_dim(ds) ds["time"] = ds[tb_name].compute().mean(tb_dim).squeeze() attrs["note"] = f"time recomputed as {tb_name}.mean({tb...
f0b5d72c59757954495a93c74c392d20bfa5e17b
67,568
from typing import List import logging def download_conversations_history( client, channel: str, page_limit: int, latest_unix_time: float, oldest_unix_time: float) -> List[dict]: """download Slack Web API conversations.list response. Returns: List of dict{"channel":ccc, "message":{ ......
1778400a61c4de1492fd77e891a28cea1778b72f
67,569
def cos_between_vects_batch(v1, v2): """ Returns the cosine angle between vectors 'v1' and 'v2' :param v1: N,C :param v2: N,C :return N, """ v1_u = v1 / np.linalg.norm(v1, axis=1).reshape(-1, 1) # N,C v2_u = v2 / np.linalg.norm(v2, axis=1).reshape(-1, 1) dots = np.sum(v1_u * v2_u, ...
55e5efc445c27316851a8df701d7d4eba406c31d
67,571
def get_exchange_rate_key(item: ExchangeItem) -> str: """ Generate a caching key for exchanging currency from one to another for today """ key = f"{item.currency_from}_{item.currency_to}_{item.historic_date}" return key
d09dafa1baebd9c231ef9e26fb85339b4c89f97a
67,572
import fnmatch def iterator(network_filter="*", clear_sessions=False): """ Iterator over various networks. """ def fetch_networks(module_name, module): ret = [ ("%s.%s" % (module_name, name), (module, name)) for name in module.__all__ if any( ...
3de5c0eb4067b65099f5f1cd51f944b4ef6c8131
67,573
def get_sales_order_items_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(SalesOrderItems, *args, **kwargs)
9504fd6cd84081cc01d3d54efa24895f98f27dc4
67,574
def handle_quit(all_events): """If pygame quiting, terminate self. Returns true if quit""" for event in all_events: if event.type == pygame.QUIT: return True return False
ec2587fcc95b4d6804d6527436c3b5a6155e271c
67,575
def wrap_dqn_bnn(env, noop_max=1): """Apply a common set of wrappers for Atari games.""" assert 'NoFrameskip' in env.spec.id env = EpisodicLifeEnv(env) env = NoopResetEnv(env, noop_max=noop_max) env = MaxAndSkipEnv(env, skip=4) if 'FIRE' in env.unwrapped.get_action_meanings(): env = Fire...
9ca7ba1adb3dd72fdd04f552ee6260ff6b934a6a
67,576
def list_variables(checkpoint_dir): """Returns list of all variables in the latest checkpoint. Args: checkpoint_dir: Directory with checkpoints file or path to checkpoint. Returns: List of tuples `(name, shape)`. """ reader = _load_checkpoint(checkpoint_dir) variable_map = reader.get_variable_to_s...
8b8e75e535073aac66eda14705a770d927edb652
67,577
def _is_schar(self): """Test auf Schar""" return len(self.sch_par) == 1
8d1229a45fab73a9d7f1560806c6e3497bbb1bcf
67,579
def seqid_to_ahref(text): """ Return a new string where each occurrence of a sequence ref `Axxxxxx` replaced as `<a href=...>` html tag. """ return Axxxxxx_regex.sub(r'<a href="http://oeis.org/\g<id>">\g<id></a>', text)
8addba28dda8c05034850bb8c079807af7202b20
67,580
def getTracks(): """ Return a list of Track objects. Result example : [Track1, Track2, ...] """ return loadView('tracks')
c39c2ab7662cf6d641d01c08c05f7d4ea74bbe0c
67,581
def call_interp1d(track, inds, nticks, mess=None, linear=False): """ Call interp1d for each dimension individually. If LOG_L or LOG_TE doesn't change, will return a constant array. Probably could/should go in ._interpolate Parameters ---------- track: padova_tracks.Track object inds: ...
e9521d7a3e8646c5edcf64c09afe1e097a7a3473
67,582
import re def _match(qs, ks): """Return True if regexes in qs match any window of strings in tuple ks.""" # compile regexes and force complete match qts = tuple(map(lambda x: re.compile(x + '$'), qs)) for i in range(len(ks) - len(qs) + 1): matches = [x.match(y) for x, y in zip(qts, ks[i:])] if matches...
b5abe402f8ed0f78b9fef9ff3b274925ce58dbcd
67,583
def getPartCharFunc2Org(partDHisto, key, paramProd, rArray, drPrime, delta): """ Calculates inter-atom contributions to the EPDDF for a partial distance histogram. @param partDHisto Partial distance histogram. @param key string Representing pair of particle species. @param paramProd Parameter dicti...
94dc2ce96600fb999adce3b871074f7a9266bed5
67,584
def GetBuiltinsPyTD(): # Deprecated. Use Loader.concat_all. """Get the "default" AST used to lookup built in types. Get an AST for all Python builtins as well as the most commonly used standard libraries. Returns: A pytd.TypeDeclUnit instance. It'll directly contain the builtin classes and functions,...
552198939d103a04b5c8266aec76b9a8ac16e06b
67,586
def lambda_handler(event, context): """ Root website view. I.e. '/' and client-side routes. """ return { 'statusCode': 200, 'body': load_html_template(event), 'headers': {'Content-Type': 'text/html'} }
b64dd6792bed48d0fd5f3df5839cef0b63b1df7f
67,587
def _fit_ovo_binary(estimator, X, y, i, j, sampling=None): """Fit a single binary estimator (one-vs-one). It is possible to apply a sampling method. """ cond = np.logical_or(y == i, y == j) y = y[cond] y_binary = np.empty(y.shape, np.int) y_binary[y == i] = 0 y_binary[y == j] = 1 in...
f2188696eb25df98a13be40dcbe114cf2191fcf1
67,588
def get_formated_ipaddr(input_ip): """ Format given ip address string to fortigate format (ip netmask) Args: * **ip_str** (string) : string representing ip address accepted format: - ip netmask (ex: 192.168.0.10 255.255.255.0) - ip (ex: 192.168.0.10) - CIDR (ex...
06a6c14041de6603f37329a9e9ecd1f75e9a782c
67,589