content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getTensorRelativError(tA, pA): """Get the relative error between two tensors.""" pA_shape = np.shape(pA) tA_shape = np.shape(tA) assert (pA_shape == tA_shape), "Arrays must be same shape" err = np.max(np.abs(np.array(pA)-np.array(tA))) return err
ea79bcebd5a39c020cdb5b35ee36dfe20b2f9c71
3,643,700
import itertools def eliminations(rct_gras, prd_gras): """ find eliminations consistent with these reactants and products :param rct_gras: reactant graphs (must have non-overlapping keys) :param prd_gras: product graphs (must have non-overlapping keys) Eliminations are identified by forming a bond b...
3acfb77d48223e1e31f7ce9b563bc5d86102b5b2
3,643,701
def sigmoid(*columns): """Fit a Sigmoid through the data of the last scan. The return value is a pair of tuples:: ((a, b, x0, c), (d_a, d_b, d_x0, d_c)) where the elemets of the second tuple the estimated standard errors of the fit parameters. The fit parameters are: * a - amplitude of ...
e9d031d07a8ef00b73634bb44ed6a94a1788f7c9
3,643,702
import traceback from .utils import ( get_conda_package_list, get_required_conda_version, update_installed_pkg_metadata, update_metarecipe_metadata, ) def _install( bz2, recipe_name, debug=False, meta_recipe=False, env_var_dir="", env_var_file="", parent...
57aa3395ca6614c08606899cc900908dfde47c94
3,643,703
import re def MakeSamplesFromOutput(metadata, output): """Create samples containing metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output Example output: perfkitbenchmarker/tests/linux_benchmarks/nccl_benchmark_test.py Returns: Samples containin...
2210caaf37a2fbfe768133e767754fb600435b0b
3,643,704
import tempfile import os def _write_bytes_to_temporary_file(local_path): """if `local_path` is a file-like object, write the contents to an *actual* file and return a pair of new local filename and a function that removes the temporary file when called.""" if hasattr(local_path, "read"): # `local...
96c8796b3b93b84568b7c0467c0e49e91259a6e3
3,643,705
def tree_to_newick_rec(cur_node): """ This recursive function is a helper function to generate the Newick string of a tree. """ items = [] num_children = len(cur_node.descendants) for child_idx in range(num_children): s = '' sub_tree = tree_to_newick_rec(cur_node.descendants[child_idx])...
751d46dbb4e3a5204900601164410b5bf7f0578b
3,643,706
import torch def mdetr_efficientnetB3(pretrained=False, return_postprocessor=False): """ MDETR ENB3 with 6 encoder and 6 decoder layers. Pretrained on our combined aligned dataset of 1.3 million images paired with text. """ model = _make_detr("timm_tf_efficientnet_b3_ns") if pretrained: ...
0e80da12a9fec55ccdbfdb3dcf78806bff2c6f20
3,643,707
import math import itertools def _check_EJR_brute_force(profile, committee): """ Test using brute-force whether a committee satisfies EJR. Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : iterable of int A committee. Returns -------...
f993daf9628ecad18fe25894ccd5fb8882d3e596
3,643,708
def read_stanford_labels(): """Read stanford hardi data and label map""" # First get the hardi data fetch_stanford_hardi() hard_img, gtab = read_stanford_hardi() # Fetch and load files, folder = fetch_stanford_labels() labels_file = pjoin(folder, "aparc-reduced.nii.gz") labels_img = nib...
8c9e5a3586125e7ffe3f9fe36b734ca7c19de53f
3,643,709
import urllib def _WrapRequestForUserAgentAndTracing(http_client, trace_token, trace_email, trace_log, gcloud_ua): """Wrap request with user-agent, and trace reporting. Args: http_client: The ...
d6a2a4c127670aa8409cb39a81833a5a5e3fba90
3,643,710
def indexData_x(x, ukn_words): """ Map each word in the given data to a unique integer. A special index will be kept for "out-of-vocabulary" words. :param x: The data :return: Two dictionaries: one where words are keys and indexes values, another one "reversed" (keys->index, values->words) ...
3f6ffd97d33400c3418b78ad3b383766cc07bee3
3,643,711
def BFS_TreeSearch(problem): """ Tree Search BFS Args->problem: OpenAI Gym environment Returns->(path, time_cost, space_cost): solution as a path and stats. """ node = Node(problem.startstate, None) time_cost = 0 space_cost = 1 if node.state == problem.goalstate: return buil...
b2523dea8b9813e2582a0acef27b0d46bb1a14b9
3,643,712
import os def remove_metaRotation(gA_rot: GeoArray, rspAlg='cubic') -> GeoArray: """Remove any metadata rotation (a rotation that only exists in the map info).""" gA = GeoArray(*warp_ndarray(gA_rot[:], gA_rot.gt, gA_rot.prj, rspAlg=rspAlg, # out_...
354ab23a2514c394c10db3d46ac57ce42660fa15
3,643,713
from typing import Tuple from typing import Optional def _objective_function(extra_features: jnp.ndarray, media_mix_model: lightweight_mmm.LightweightMMM, media_input_shape: Tuple[int, int], media_gap: Optional[int], ...
f8ae8185d84d811dc1d5796aa8374127d2f16ea5
3,643,714
from typing import Union from functools import reduce def decode_block(block: np.ndarray) -> Union[np.ndarray, bool]: """ Decode a data block with hamming parity bits. :param block: The data block to be decoded :return the decoded data bits, False if the block is invalid """ if not block.siz...
c9ed9eb03271e2222aa62260461aaa7ee90eb842
3,643,715
def occupancy(meta, ax=None): """ Show channel occupancy over time. """ if ax is None: f, ax = plt.subplots() f.set_figwidth(14) f.suptitle("Occupancy over time") start_time = meta.read_start_time.min() / 10000 / 60 end_time = meta.read_end_time.max() / 10000 / 60 to...
f6505a5bf7ff417194457ee2e04118edea9e6738
3,643,716
def reg1_r_characteristic(r, s, alpha, beta, c, h): """ evaluate x - ((4/3)r - (2/3)s)t in region 1, equation 19 """ # when s < 0 the expression can be factored and you avoid the # difference of nearly equal numbers and dividing by a small number # equation 74 rr = r/c ss = s/c pol...
9802483289387b7996665fe8f061d4393ff0daaf
3,643,717
from typing import Tuple def olf_gd_offline_in_z(X: np.ndarray, k: int, rtol: float = 1e-6, max_iter: int = 100000, rectY: bool = False, rectZ: bool = False, init: str = 'random', Y0=None, Z0=None, verbose: bool = False, alpha=1, ...
2397b0d24fa8fa9b8ddb9d7dd8553bd076feeb39
3,643,718
from typing import List from typing import Dict from typing import Any import sys def get_features(model_description_features: List[Dict[str, Any]]): """Get features from a list of dictionaries Parameters ---------- model_description_features : List[Dict[str, Any]] Examples -------- >>> ...
77f904fe28ea175a06671dc4533fb0e36ae2d593
3,643,719
def get_cluster_codes(cluster: pd.Categorical) -> pd.Series: """Get the X location for plotting p-value string.""" categories = cluster.cat.categories.rename("cluster") return pd.Series(range(len(categories)), index=categories, name="x")
bb6899e5245c14e47ac855fef95775c282a8ed0f
3,643,720
import math import copy def _expand_configurations_from_chain(chain, *, pragma: str = 'pytmc', allow_no_pragma=False): """ Wrapped by ``expand_configurations_from_chain``, usable for callers that don't want the full product of all configurations. """ def hand...
b1282a9cf65875be3e91c3f0eb09a73f0130ccf9
3,643,721
import base64 def encrypt(data=None, key=None): """ Encrypts data :param data: Data to encrypt :param key: Encryption key (salt) """ k = _get_padded_key(key) e = AES.new(k, AES.MODE_CFB, k[::-1]) enc = e.encrypt(data) return base64.b64encode(enc)
668a5e94ea6d1adddb038f5cab1f0d165bb98bb0
3,643,722
import logging import os from datetime import datetime def get_logger(logdir_path=None): """logging.Logger Args ---- logdir_path: str path of the directory where the log files will be output Returns ------- logger (logging.Logger): instance of logging.Logger """ log_form...
d97b49508490bd82eefa5a929a8b8e680431e766
3,643,723
def box_in_k_largest(boxes, box, k): """Returns True if `box` is one of `k` largest boxes in `boxes`. If there are ties that extend beyond k, they are included.""" if len(boxes) == 0: return False boxes = sorted(boxes, reverse=True, key=box_volume) n = len(boxes) prev = box_volume(boxes[...
e941513e47db5fb09e21b96933c629cf3c39bf49
3,643,724
def diagonal(a, offset=0, axis1=0, axis2=1): """ Returns specified diagonals. If `a` is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to dete...
64ada8a83fd1162e7d84e84007be0263cd71bd0c
3,643,725
def available_number_of_windows_in_array(n_samples_array, n_samples_window, n_advance): """ Parameters ---------- n_samples_array n_samples_window n_advance Returns ------- """ stridable_samples = n_samples_array - n_samples_window if stridable_samples < 0: print("...
cab937efe4408d4707b601d4a0a68782d062ab36
3,643,726
import torch def tensor_to_image(tensor: torch.tensor) -> ndarray: """ Convert a torch tensor to a numpy array :param tensor: torch tensor :return: numpy array """ image = TENSOR_TO_PIL(tensor.cpu().clone().squeeze(0)) return image
fb3f16ec6cee1c50d2b7e6f2e31bd94aa300cdfd
3,643,727
def shimizu_mirioka(XYZ, t, a=0.75, b=0.45): """ The Shinizu-Mirioka Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = y y_dt = (1 - z) * x - a * y z_dt = x**2 - b * z return x_dt, y_dt, z_dt
60e5b52e1755de8bcc966364d828d47b05af3723
3,643,728
def draw_cap_peaks_rh_coord(img_bgr, rafts_loc, rafts_ori, raft_sym, cap_offset, rafts_radii, num_of_rafts): """ draw lines to indicate the capillary peak positions in right-handed coordinate :param numpy array img_bgr: the image in bgr format :param numpy array rafts_loc: the locations of rafts ...
c180a23d7ad6a04d8e56a61a0cb5e058bf1e5d95
3,643,729
import subprocess def invoke(command): """Invoke sub-process.""" try: output = subprocess.check_output(command, stderr=subprocess.STDOUT) status = 0 except subprocess.CalledProcessError as error: # pragma: no cover output = error.output status = error.returncode retur...
fb4023b6118d63a1bbe2551bc007ce2f750751dd
3,643,730
def pack_bidirectional_lstm_state(state, num_layers): """ Pack the hidden state of a BiLSTM s.t. the first dimension equals to the number of layers. """ assert (len(state) == 2 * num_layers) _, batch_size, hidden_dim = state.size() layers = state.view(num_layers, 2, batch_size, hidden_dim).trans...
de102ce55deceb5ca7211def122dc2767c35cdd3
3,643,731
import copy def _create_record_from_template(template, start, end, fasta_reader): """Returns a copy of the template variant with the new start and end. Updates to the start position cause a different reference base to be set. Args: template: third_party.nucleus.protos.Variant. The template variant whose ...
62c9ff204cff3887daad0df4f710cc54f9c8dad9
3,643,732
import xlrd import xlrd.sheet from datetime import datetime import os import copy import hashlib import subprocess import shutil def create_outputfile(prxdoc,inputfiles_element,inputfilehref,nominal_outputfilehref,outputfilehref,outputdict,ignore_locking): """Create the output XML file from the raw input by runni...
7243bf433f1b05631f2ee77911b0b535fa478a26
3,643,733
import os import io import zlib def get_example_data(filepath: str, is_gzip: bool = True, make_bytes: bool = False) -> BytesIO: """ 获取示例数据,下载打开文件,进行解压缩。 :param filepath: 文件路径。 :param is_gzip: 是否压缩的。 :param make_bytes: 字节数据。 :return: """ # 如果本地存在则从本地加载 local_path = os.path.join(EX...
cebcd2773b8958130cbe2d3bc4d8fca3ed926321
3,643,734
import time def convert_time(time_string): """ Input a time in HH:MM:SS form and output a time object representing that """ return time.strptime(time_string, "%H:%M")
f34b46fe8cd242ee12a9768102486cba243d94df
3,643,735
from typing import Union import torch def get_distributed_mean(value: Union[float, torch.Tensor]): """Computes distributed mean among all nodes.""" if check_torch_distributed_initialized(): # Fix for runtime warning: # To copy construct from a tensor, it is recommended to use # sourceT...
9643b522e838a3a0aabcfab7021d4bac7d58e21d
3,643,736
def js_div(A, B): """ Jensen-Shannon divergence between two discrete probability distributions, represented as numpy vectors """ norm_A = A / A.sum() norm_B = B / B.sum() M = (norm_A+norm_B)/2 return 0.5 * (kl_div(norm_A,M)+kl_div(norm_B,M))
1e4ac763d01f3ae3d25907d24229301d464de527
3,643,737
from typing import Dict def _build_request_url( base: str, params_dict: Dict[str, str]) -> str: """Returns an URL combined from base and parameters :param base: base url :type base: str :param params_dict: dictionary of parameter names and values :type params_dict: Dict[str, str]...
30e27cf55692884be408218403c2f94279516ad2
3,643,738
def aesDecrypt(key, data): """AES decryption fucnction Args: key (str): packed 128 bit key data (str): packed encrypted data Returns: Packed decrypted data string """ cipher = python_AES.new(key) return cipher.decrypt(data)
15c70d0699a22bf58ca191ba2fea2d5eb7942b1b
3,643,739
def __format_number_input(number_input, language): """Formats the specified number input. Args: number_input (dict): A number input configuration to format. language (dict): A language configuration used to help format the input configuration. Returns: dict: A formatted number inpu...
0cd76b74396c013d7f76ae5ae11ace56db6552ab
3,643,740
def get_players(picks): """Return the list of players in the team """ players = [] for rd in picks: play = list(rd.keys()) players = players+play players = list(set(players)) return players
79963bc19af662d44d4eaf29a04995ede331706c
3,643,741
def verify_file_details_exists(device, root_path, file, max_time=30, check_interval=10): """ Verify file details exists Args: device ('obj'): Device object roo...
da0e33ca67b9e70dc4b5345ba626a193bcdefdbd
3,643,742
import collections from typing import Literal def generateVoID(g, dataset=None, res=None, distinctForPartitions=True): """ Returns a new graph with a VoID description of the passed dataset For more info on Vocabulary of Interlinked Datasets (VoID), see: http://vocab.deri.ie/void This only makes ...
66f8b5824017fd41995783c75de72451d22ea023
3,643,743
def extract_screen_name_from_twitter_url(url): """ Function returning the screen_name from a given Twitter url. Args: url (str) : Url from which we extract the screen_name if found. Returns: str : screen_name if the url is a valid twitter url, None otherwise. """ parsed_twitt...
3bbc00f2b4fb0aa0b49154d37802a50204f05ccf
3,643,744
def sub_vectors(a, b): """Subtracts two vectors. Args: pos1 (tuple[int]): first position pos1:(tuple[int]): second position Returns: tuple[int]: element wise subtraction Examples: >>> sub_vectors((1,4,6), (1,3,7)) (0, 1, -1) """ return tuple(a[i] - b[i]...
02c35bf46311142a3f3e90cd803d908c6ff63896
3,643,745
def get_prediction_info(predicted_one_hot, predicted_int, y_test, PLOTS_DIR, filename = "test_file"): """ Saves useful information for error analysis in plots directory :param predicted_one_hot: :param predicted_int: :param y_test: :param PLOTS_DIR: :return: """ def get_info_for_labe...
76d95c3793ee29c211d7f32e727e9bf046c075eb
3,643,746
def save_excel_file(): """File save dialog for an excel file. Returns: str: file path """ return pick_excel_file(save=True)
392c014a959a6d61cfa02ca041d0496560df4dec
3,643,747
def load_app_paths(file_path=None, dir_path=None, user_file_path=None, user_dir_path=None, default=None, paths=None, **kwargs): """Parse and merge user and app config files User config will have precedence :param file_path: Path to the base config file :param dir_path: Path to the e...
d5f6fe9b8db396f95656d80fea19dc0f95fba642
3,643,748
def search_playlists(spotify_token, playlist): """ :param spotify_token: :param playlist: :return: """ return _search(spotify_token, query=playlist, type='playlist', limit=9, market='ES', offset=0)
cf2ab61a4f967c8cb570471c3fdea2c772d85e8d
3,643,749
import re def text_pre_process(result): """ 이미지에서 인식된 글자를 정제 합니다. 특수문자 제거, 1-2단어 제거, 줄바꿈 및 공백 제거 :param result: 이미지에서 인식된 글자 :return: 문자를 전처리한 결과 """ copy = str(result) copy2 = copy.replace("\n", "") copy3 = re.sub('[^ㄱ-힗]', '', copy2) # re.sub('[^A-Za-z0-9]', '', copy2) result = re.sub('[-=+,#}/\{:^$.@...
c9a25fb19a723d38eb19a8a086a2134369223ea1
3,643,750
from typing import Tuple import ssl from datetime import datetime def push_thread_callback(app: Flask): """Process outstanding MDM commands by issuing a push to device(s). TODO: A push with no response needs an exponential backoff time. Commands that are ready to send must satisfy these criteria: -...
665b470fa046013e19ca0e58b7b9d58f21f31194
3,643,751
def get_conventional_std_cell(atoms): """Given an ASE atoms object, return the ASE atoms object in the conventional standard cell. It uses symmetries to find the conventional standard cell. In particular, it gives a structure with a conventional cell according to the standard defined in W. Setyawan, an...
78bf131e8f195bd25b424627d6cce2d5295de248
3,643,752
def get_if_rcnn(inputs: Tensor): """ :param inputs: Tensor from Input Layer :return: """ # get back bone outputs if_backbones_out = backbones(inputs) return if_backbones_out
02507f10e4dc791b1f201d2c08d3925f2a2dacb5
3,643,753
import string import secrets def method_3(num_chars: int): """ Pythonicish way of generating random password Args: num_chars (int): Number of Characters the password will be Returns: string: The generated password """ chars = string.ascii_letters + string.digits + string.punc...
03fc383ef8c45f1bc618daf4b70646ea824e31df
3,643,754
def get_animation_for_block( block_start: int, frame_num: int, total_frames: int, duration: int=5, ): """Generate CSS to pop a block from gray to red at the right frame block_start: int frame_num: int total_frames: int duration: int # seconds""" animation_function = gray_...
9ce9a36a5c7ca5161b89a3306c7e38c9c03d2ee0
3,643,755
def find_student_by_username(usuario_id, test=False): """Consulta toda la información de un estudiante según su usuario.""" query = 'SELECT * FROM estudiante WHERE id_usuario = %s' return execute_sql(query, args=[usuario_id], rows=1, test=test)
ecc67992aef2257d35ccc6dfa05c01afc3d40bb3
3,643,756
def reduce_mem_usage(df, use_float16=False): """ Iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024 ** 2 print("Memory usage of dataframe is {:.2f} MB".format(start_mem)) for col in df.columns: ...
842e9c134cd5211fdbe75b0626efa48f68d90c35
3,643,757
import argparse def ParseCommandYAML(): """Function for parsing command line arguments for input to YAML HDIprep""" # if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--im", nargs='*') parser.add_argument("--pars") parser.add_argument("--out_dir") args = ...
3a56d16d960f59f0afd888120c19d12b0b6f25b3
3,643,758
def create_global_step() -> tf.Variable: """Creates a `tf.Variable` suitable for use as a global step counter. Creating and managing a global step variable may be necessary for `AbstractTrainer` subclasses that perform multiple parameter updates per `Controller` "step", or use different optimizers on different...
786ac18f78f092e099844d99b33f5232f53d8a8a
3,643,759
def rl_label_weights(name=None): """Returns the weight for importance.""" with tf.variable_scope(name, 'rl_op_selection'): num_classes = get_src_num_classes() num_choices = FLAGS.num_choices logits = tf.get_variable( name='logits_rl_w', initializer=tf.initializers.zeros(), shape...
b1157c508cb256ab9608ebd78dfbb1ef90cec2b5
3,643,760
from scipy.stats import mannwhitneyu from statsmodels.sandbox.stats.multicomp import multipletests from typing import List import tqdm def run_de_test(dataset1: Dataset, dataset2, test_cells: List[str], control_cells: List[List[str]], test_label: str = None, control_group_labels: list...
422082785845918f7e999125b7e57e6c1fbcb535
3,643,761
def say_hello_twice(subject): """Says hello twice using `say_hello`.""" return say_hello(subject) + " " + say_hello(subject)
66a6fafca01f6ddc6304fef15aea27bb15c23416
3,643,762
def get_zones(ec2): """ Return all available zones in the region """ zones = [] try: aws_zones = ec2.describe_availability_zones()['AvailabilityZones'] except ClientError as e: print(e.response['Error']['Message']) return None for zone in aws_zones: if zone['State'] == 'available': ...
acd023bcf5863aff0cd562f6c097062d9693738d
3,643,763
import torch def x_gate(): """ Pauli x """ return torch.tensor([[0, 1], [1, 0]]) + 0j
736d72d832380ea5a1d6c4a840cb6aa0050638e5
3,643,764
def merge_dictionaries(default_dictionary, user_input_dictionary, path=None): """Merges user_input_dictionary into default dictionary; default values will be overwritten by users input.""" return {**default_dictionary, **user_input_dictionary}
ea600efcd69e920ae536fa2f22a4c883a71d8ad3
3,643,765
def create_frequencyvector(T_end, f_max_requested): """ A function to create the vector of frequencies we need to solve using the reflectivity method, to achieve the desired length of time and highest modelled frequency. NOTE: Because we require the number of frequencies to be odd, the maximum frequency may...
d402840259bdc0049c580e057a6de815dfaa02f1
3,643,766
def get_fiber_protein_intake( nutrients_lower_lists, nutrients_middle_lists,nutrients_upper_lists): """Gets financial class-wise fibee and protein intake data.""" lower_fiber_prot = nutrients_lower_lists.map(lambda x: (x[1], x[3])) middle_fiber_prot = nutrients_middle_lists.map(lambda x: (x[1], x[3...
990293236a10ed18960393b39dbfb46652fca51d
3,643,767
def _add_fvar(font, axes, instances, axis_map): """ Add 'fvar' table to font. axes is a dictionary mapping axis-id to axis (min,default,max) coordinate values. instances is list of dictionary objects with 'location', 'stylename', and possibly 'postscriptfontname' entries. axisMap is dictionary mapping axis-id...
20836c91121603610f5bfb19777e4b6f440f2007
3,643,768
import tqdm def init_nornir(username, password): """INITIALIZES NORNIR SESSIONS""" nr = InitNornir( config_file="network_automation/topology_builder/graphviz/config/config.yml" ) nr.inventory.defaults.username = username nr.inventory.defaults.password = password managed_devs = nr.filt...
edf6a45a2ce9dc7799351892c1b53ab2b949607c
3,643,769
def _format_rest_url(host: str, append: str = "") -> str: """Return URL used for rest commands.""" return f"http://{host}:8001/api/v2/{append}"
1d5ace3919da004e648cb6c7d6d80fe72903c0e1
3,643,770
from typing import Union import torch import os import warnings def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None): """Load a CLIP model Parameters ---------- name : str A...
be42a21f40d97e559e1e1a65b09ca45b57fd88b9
3,643,771
from typing import Optional from typing import Set def get_synonyms(prefix: str) -> Optional[Set[str]]: """Get the synonyms for a given prefix, if available.""" entry = get_resource(prefix) if entry is None: return None return entry.get_synonyms()
44e4fc7259f9536dc192a08566b8db7f9256f916
3,643,772
def results(request): """ Returns the actual body of the search results, for AJAX stuff """ query = request.GET.get("q", "") if len(query) >= 4: ctx = _search_context(query, request.user) return TemplateResponse(request, "search/results.html", ctx) return TemplateResp...
a6282dd489e3406ebc8b2349159b58d4cb0e1fd4
3,643,773
def is_correlated(corr_matrix, feature_pairs, rho_threshold=0.8): """ Returns dict where the key are the feature pairs and the items are booleans of whether the pair is linearly correlated above the given threshold. """ results = {} for pair in feature_pairs: f1, f2 = pair.split("__"...
18afa0cc24f5d9205cde3c8ad23f70d73b5c395b
3,643,774
def find_password(liste, login): """ """ for user in liste: if user[0] == login: return user[1] return None
8f61072a8b1cc34eb27c1665b1cd34aeb6630ce2
3,643,775
def sample_weather_scenario(): """ Generate a weather scenario with known values for the wind condition. """ times = pd.date_range('1/1/2000', periods=72, freq='6H') latitude = np.linspace(0, 10, 11) longitude = np.linspace(0, 10, 11) wsp_vals = np.full((72, 11, 11), 10.0) wdi_vals = np....
124f43b090149bb23e52a88a03c441d1311c5bea
3,643,776
import os def parse_csv_file(csv_filepath, expect_negative_correlation = False, STDev_cutoff = 1.0, headers_start_with = 'ID', comments_start_with = None, separator = ','): """ Analyzes a CSV file. Expects a CSV file with a header line starting with headers_start_with e.g. "ID,experimental value, predicti...
976180982335a69451971b85cd4d411d56da7844
3,643,777
import torch def ToTensor(pic): """Converts a PIL.Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]. """ if isinstance(pic, np.ndarray): img = torch.from_numpy(pic.transpose((2, 0, 1))) return img.float().div(255) if pic.mode ==...
c3ed682c520f17f24169377b2a3016510e9724f9
3,643,778
def part2(data): """ >>> part2([[43, 19], [2, 29, 14]]) 105 >>> part2([[9, 2, 6, 3, 1], [5, 8, 4, 7, 10]]) 291 >>> part2(read_input()) 32528 """ deck_one = tuple(data[0]) deck_two = tuple(data[1]) _, winning_deck = combat(deck_one, deck_two) return score(winning_deck)
226eb835030716cdfa30310e53bc76c5dd3a4e7e
3,643,779
from pathlib import Path def validate_recording( ai_file_path, ephys_ap_data_path, debug=False, sampling_rate=30000 ): """ Checks that an ephys recording and bonsai behavior recording are correctly syncd. To do this: 1. check that number of recording sync signal pulses is the same for ...
269e66a6fc06490c8cbd9f983bc0c57f090c3671
3,643,780
def dehyphenate(string): """Remove hyphenated linebreaks from 'string'.""" return hyphen_newline_re.sub("", string)
6894fd7972c3990fd00e5818e0b30e48e78017e0
3,643,781
def grounder(img, dtype=None): """Tries to remove absolute offset 'img' must be a 3 colors image""" shape = img.shape """ # Mise en forme a = img.reshape((shape[0] * shape[1], 3)) min = np.zeros(a.shape) max = np.zeros(a.shape) # Minimas/maximas min[:,0] = min[:,1] = min[:,2] =...
55a022a26f457cf0ec76d4ed8fa37f470db31e11
3,643,782
def arch_prob(arch, dims, **kwds): """ Returns the combined probability of for arch given values """ values = dict(kwds) dimkeys = list(dims.keys()) assert isinstance(arch, (tuple, list)), "Archictecture must be tuple or list" serial = isinstance(arch, list) probs = [None] * len(arch) for i, subarch in ...
94778c471d4ae3fe534af50543ef9465a6b2e793
3,643,783
def get_bin_values(base_dataset, bin_value): """Gets the values to be used when sorting into bins for the given dataset, from the configured options.""" values = None if bin_value == "results": values = base_dataset.get_output() elif bin_value == "all": # We set all values to 0, assuming...
cf2419066d6e642e65d9a8747081ebfee417ed64
3,643,784
def get_reviews(revision_range): """Returns the list of reviews found in the commits in the revision range. """ log = check_output(['git', '--no-pager', 'log', '--no-color', '--reverse', r...
0ff81eef45fb123e25dc7662f320e49fac7aa378
3,643,785
def create_cert_req(keyType=crypto.TYPE_RSA, bits=1024, messageDigest="md5"): """ Create certificate request. Returns: certificate request PEM text, private key PEM text """ # Create certificate request req = crypto.X509Req() # Generate private key ...
168fd8c7cde30730cdc9e74e5fbf7619783b29c9
3,643,786
def large_xyz_to_lab_star(large_xyz, white=const_d50_large_xyz): """ # 概要 L*a*b* から XYZ値を算出する # 入力データ numpy形式。shape = (N, M, 3) # 参考 https://en.wikipedia.org/wiki/Lab_color_space """ if not common.is_img_shape(large_xyz): raise TypeError('large_xyz shape must be (N, M, 3)') ...
aec3cb423698954aa07a61bf484e1acd8e38d5db
3,643,787
from typing import Any def return_value(value: Any) -> ObservableBase: """Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. There is an alias called 'just'. example res = rx.Observable.return(42) res = rx.Observable.ret...
e14ac3a08a3f127b77f57b7192a8f362ec3485b2
3,643,788
def compare_policies(current_policy, new_policy): """ Compares the existing policy and the updated policy Returns True if there is a difference between policies. """ return set(_hashable_policy(new_policy, [])) != set(_hashable_policy(current_policy, []))
e69ecaa051602e2d9eab0695f62b391a9aca17ad
3,643,789
def meanPSD(d0,win=np.hanning,dx=1.,axis=0,irregular=False,returnInd=False,minpx=10): """Return the 1D PSD averaged over a surface. Axis indicates the axis over which to FFT If irregular is True, each slice will be stripped and then the power spectra interpolated to common frequency grid Presume...
99d6ab3e8ef505f031346db10762a195904b455e
3,643,790
async def get_temperatures(obj): """Get temperatures as read by the thermostat.""" return await obj["madoka"].temperatures.query()
b4643d9c40f6aa8953c598dd572d291948ef34a4
3,643,791
import itertools def get_zero_to_2pi_input(label, required, placeholder=None, initial=None, validators=()): """ Method to get a custom positive float number field :param label: String label of the field :param required: Boolean to define whether the field is required or not :param placeholder: Pla...
d1349088d8b2c29ecc07bdb6900ff335384e3c30
3,643,792
def compile_math(math): """ Compile a mathematical expression Args: math (:obj:`str`): mathematical expression Returns: :obj:`_ast.Expression`: compiled expression """ math_node = evalidate.evalidate(math, addnodes=[ ...
511c281a03591ed5b84e216f3edb1503537cbb86
3,643,793
from typing import Optional from typing import Union from typing import List import click def colfilter( data, skip: Optional[Union[str, List[str]]] = None, only: Optional[Union[str, List[str]]] = None, ): """ Remove some variables (skip) or keep only certain variables (only) Parameters -...
16c901f514afb1990e43c470c7e089eab5b4eb56
3,643,794
import math def acos(x): """ """ return math.acos(x)
0a8ca8f716f0ea54b558ca27021830480dac662d
3,643,795
def get_callable_from_string(f_name): """Takes a string containing a function name (optionally module qualified) and returns a callable object""" try: mod_name, func_name = get_mod_func(f_name) if mod_name == "" and func_name == "": raise AttributeError("%s couldn't be converted to a...
ef1ae8d4c1da06e38a6029e0caa51b4e3fb5b95c
3,643,796
from typing import List import bisect def binary_get_bucket_for_node(buckets: List[KBucket], node: Node) -> KBucket: """Given a list of ordered buckets, returns the bucket for a given node.""" bucket_ends = [bucket.end for bucket in buckets] bucket_position = bisect.bisect_left(bucket_ends, node.id) #...
ff1fc765c56e67af3c33798b403779f7aafb6bb0
3,643,797
def darken(color, factor=0.7): """Return darkened color as a ReportLab RGB color. Take a passed color and returns a Reportlab color that is darker by the factor indicated in the parameter. """ newcol = color_to_reportlab(color) for a in ["red", "green", "blue"]: setattr(newcol, a, facto...
bcb937409a6790c6ac04a1550654e9b4fc398f9f
3,643,798
def fetch_all_tiles(session): """Fetch all tiles.""" return session.query(Tile).all()
15e21dff372859ad07f76d97944b9a002f44a35e
3,643,799